How to get fragment coordinate in fragment shader in Metal? - ios

This minimal Metal shader pair renders a simple interpolated gradient onto the screen (when provided with a vertex quad/triangle) based on the vertices' color attributes:
#include <metal_stdlib>
using namespace metal;
typedef struct {
float4 position [[position]];
float4 color;
} vertex_t;
vertex vertex_t vertex_function(const device vertex_t *vertices [[buffer(0)]], uint vid [[vertex_id]]) {
return vertices[vid];
}
fragment half4 fragment_function(vertex_t interpolated [[stage_in]]) {
return half4(interpolated.color);
}
…with the following vertices:
{
// x, y, z, w, r, g, b, a
1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, -1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0,
-1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0,
1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0,
1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0,
-1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0
}
So far so good. It renders the well-known gradient triangle/quad.
The one you find in pretty much every single GPU HelloWorld tutorial.
I however need to have a fragment shader that instead of taking the interpolated vertex color computes a color based on the fragments position on screen.
It receives a screen-filling quad of vertices and then uses only the fragment shader to calculate the actual colors.
From my understanding the position of a vertex is a float4 with the first three elements being the 3d vector and the 4th element set to 1.0.
So—I thought—it should be easy to modify the above to have it simply reinterpret the vertex' position as a color in the fragment shader, right?
#include <metal_stdlib>
using namespace metal;
typedef struct {
float4 position [[position]];
} vertex_t;
vertex vertex_t vertex_function(const device vertex_t *vertices [[buffer(0)]], uint vid [[vertex_id]]) {
return vertices[vid];
}
fragment half4 fragment_function(vertex_t interpolated [[stage_in]]) {
float4 color = interpolated.position;
color += 1.0; // move from range -1..1 to 0..2
color *= 0.5; // scale from range 0..2 to 0..1
return half4(color);
}
…with the following vertices:
{
// x, y, z, w,
1.0, -1.0, 0.0, 1.0,
-1.0, -1.0, 0.0, 1.0,
-1.0, 1.0, 0.0, 1.0,
1.0, 1.0, 0.0, 1.0,
1.0, -1.0, 0.0, 1.0,
-1.0, 1.0, 0.0, 1.0,
}
I was quite surprised however to find a uniformly colored (yellow) screen being rendered, instead of a gradient going from red=0.0 to red=1.0 in x-axis and green=0.0 to green=1.0 in x-axis:
(expected render output vs. actual render output)
The interpolated.position appears to be yielding the same value for each fragment.
What am I doing wrong here?
Ps: (While this dummy fragment logic could have easily been accomplished using vertex interpolation, my actual fragment logic cannot.)

The interpolated.position appears to be yielding the same value for
each fragment.
No, the values are just very large. The variable with the [[position]] qualifier, in the fragment shader, is in pixel coordinates. Divide by the render target dimensions, and you'll see what you want, except for having to invert the green value, because Metal's convention is to define the upper-left as the origin for this, not the bottom-left.

Related

Metal Tessellation on subdivided quad

I am totally new to tessellation and relatively new to Metal API, and have been referring to this sample code https://developer.apple.com/library/archive/samplecode/MetalBasicTessellation/Introduction/Intro.html
I realise the max tessellation factor on iOS is 16, which is very low for my use case compared to 64 on OSX.
I suppose i'll need to apply tessellation on a quad that has been sub-divided to 4 by 4 smaller sections to begin with, so that after tessellation it will end up into something like one with a tessellation factor of 64?
So, i've changed the input control points to something like this
static const float controlPointPositionsQuad[] = {
-0.8, 0.8, 0.0, 1.0, // upper-left
0.0, 0.8, 0.0, 1.0, // upper-mid
0.0, 0.0, 0.0, 1.0, // mid-mid
-0.8, 0.0, 0.0, 1.0, // mid-left
-0.8, 0.0, 0.0, 1.0, // mid-left
0.0, 0.0, 0.0, 1.0, // mid-mid
0.0, -0.8, 0.0, 1.0, // lower-mid
-0.8, -0.8, 0.0, 1.0, // lower-left
0.0, 0.8, 0.0, 1.0, // upper-mid
0.8, 0.8, 0.0, 1.0, // upper-right
0.8, 0.0, 0.0, 1.0, // mid-right
0.0, 0.0, 0.0, 1.0, // mid-mid
0.0, 0.0, 0.0, 1.0, // mid-mid
0.8, 0.0, 0.0, 1.0, // mid-right
0.8, -0.8, 0.0, 1.0, // lower-right
0.0, -0.8, 0.0, 1.0, // lower-mid
};
and for the drawPatches i changed it to 16 instead of 4.
But the result is that it is only showing only the first 4 points (top left).
if i change the vertex layout stride to this:
vertexDescriptor.layouts[0].stride = 16*sizeof(float);
it is still showing the same.
I don't really know what i'm doing but what i'm going for is similar to tessellating a 3d mesh, but for my case is just a quad with subdivisions.
I am unable to find any tutorial / code samples that teach about this using Metal API.
Can someone please point me to the right direction? thanks!
Here are a few things to check:
Ensure that your tessellation factor compute kernel is generating inside/edge factors for all patches by dispatching a compute grid of the appropriate size.
When dispatching threadgroups to execute your tessellation factor kernel, use 1D threadgroup counts and sizes (such that the total thread count is the number of patches, and the heights of both sizes passed to the dispatch method are 1).
When drawing patches, the first parameter (numberOfPatchControlPoints) should equal the number of control points in each patch (3 for triangles; 4 for quads), and the third parameter should be the number of patches to draw.

Trying to flip an OpenGL texture

I'm trying to invert the Y values of a texture on OpenGL ES 2.0, and have had no luck after several days of experimentation. Here's the code in my didRender block (it's a scene kit scene).
let textureCoordinates: [GLfloat] = [
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 1.0]
let flipVertical: [GLfloat] = [
0.0, 1.0,
1.0, 1.0,
0.0, 0.0,
1.0, 0.0]
glEnableVertexAttribArray(0)
glEnableVertexAttribArray(1)
glVertexAttribPointer(0, 2, GLenum(GL_FLOAT), 0, 0, flipVertical)
glVertexAttribPointer(1, 2, GLenum(GL_FLOAT), 0, 0, textureCoordinates)
glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, 4)
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
glFlush()
Is there anything that sticks out to you as wrong? My understanding is that I can flip the texture without having to rewrite to a new texture. Is that true? Thanks!
You don't need a separate vertex attribute to do the flip; just replace the textureCoordinate array with the values from flipVertical (and then delete all of the code related to flipVertical - you don't need it).

WebGl rotation matrix

I have this very simple rotation program in Webgl to get some understanding of rotation matrix.
http://poly.byethost18.com/pyra1.htm
As you can see the object doesn't turn around actually.
The code for the vertex shader is here:
float angle = radians( theta );
float c = cos( angle );
float s = sin( angle );
mat4 ry = mat4( c, 0.0, -s, 0.0,
0.0, 1.0, 0.0, 0.0,
s, 0.0, c, 0.0,
0.0, 0.0, 0.0, 1.0 );
gl_Position = ry * vPosition;
I guess it's a kinda regular beginners stuff but what could be the cause?
Needed to add
gl.enable(gl.DEPTH_TEST);

Querying Current Vertex Attribute State in webGL

For some reasons (emulating VAOs when they are not available), I'd like to get the current state of the bound vertex attribute arrays, and I obtain results that I do not understand concerning
VERTEX_ATTRIB_ARRAY_SIZE and VERTEX_ATTRIB_ARRAY_TYPE.
I tried the following program:
<canvas id='canvas'></canvas>
<script src='/webgl-debug.js'></script>
<script>
var canvas = document.getElementById('canvas');
var gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
gl = WebGLDebugUtils.makeDebugContext(gl); // Remove this in production code
var buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
var data = [
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0
];
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
gl.vertexAttribPointer(0, 1, gl.BYTE, true, 0, 0);
console.log(gl.getVertexAttrib(0,gl.VERTEX_ATTRIB_ARRAY_SIZE));
console.log(gl.getVertexAttrib(0,gl.VERTEX_ATTRIB_ARRAY_TYPE) == gl.FLOAT);
</script>
I expected to get:
1
false
and what I actually get (on Firefox 45.1.1) is:
4
true
(corresponds to the default values, not the the ones I specified in vertexAttribPointer())
Is there something I did wrong in there ?
Update (found a workaround)
I observed that if the corresponding vertex attrib array is enabled, then the queries work as expected:
gl.enableVertexAttribArray(0);
console.log(gl.getVertexAttrib(0,gl.VERTEX_ATTRIB_ARRAY_SIZE));
console.log(gl.getVertexAttrib(0,gl.VERTEX_ATTRIB_ARRAY_TYPE) == gl.BYTE);
then I get:
1
true

WebGL Vertices Order

I am very new to WebGL and I have a question about the order of vertices. When creating a cube, the vertices will look like this:
var vertices = [
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0
];
Can I rearrange the order of these vertices into any order I want, or do they have to be in a certain order?
Order of the vertices depends on the triangle culling paramaters and order in which the triangles are drawn.
Vertices that make up a triangle can be ordered in the right-hand or left-hand manner. Orientation of the triangle than describes the wait the normal of the triangle is pointing at. Read more here.
Depending on the option you select for the gl.cullface( option ), you have different culling of the triangles. So, that affects the vertices order.
Another important aspect to look after is order of the triangles/primitives that are drawn. You may have different requirements in your application, so may need to pre-order triangles that weer to be drawn, so that could also affect the order of the vertices. One such example is drawing transparent primitives. There are many issues with blending transparent primitives so need to take care. For more insightful direct example, read this.
Hope this helps you understand how the order of the vertices may or may not be important.

Resources