So, I’m trying to make sense of some code before I copy and paste it into my application. In openGL I’m seeing some variables typed as in and out. I see no such thing in the following code snippet. From what I understand, the vertex shader “magically” gets the input for the “in” typed variables via the program, which incidentally can have a fragment and vertex shader attached to it(the program). Heres the code:
<script id="shader-vs" type="x-shader/x-vertex">
attribute vec2 aVertexPosition;
attribute vec2 aPlotPosition;
varying vec2 vPosition;
void main(void) {
gl_Position = vec4(aVertexPosition, 1.0, 1.0);
vPosition = aPlotPosition;
}
</script>
So, my question is, by attaching an appropriate program here, aVertexPosition and aPlotPosition will both be properly initialized and furthermore, vPosition could be used somewhere else in my app, namely the fragment shader?
Let me try and explain how the GPU pipeline I/O works:
Each Vertex has a set of attributes associated with it. Given your example code:
attribute vec2 aVertexPosition;
attribute vec2 aPlotPosition;
You are saying that each vertex has a 2D vertex position and plot position. If you added:
attribute vec3 vNormal;
Then every vertex would also have a normal. You could think of these as vertex “properties”.
You must tell the GPU where to fetch the values for each of these attributes.
Each vertex attribute is assigned an attribute array index when the shader is compiled. You must enable each attribute array index that your shader requires
Once you’ve enabled it, you want to bind the attribute array to a vertex buffer.
You now describe how to fetch the attribute with this call:
Given your example code:
16 or the stride is the number of bytes between each vertex. Each vertex consists of 4 floats and each float is 4 bytes wide. The offset is where the attribute starts within a vertex. The vertex position is at the 0th byte of the vertex and plot position is at the 8th.
You can think of these as describing how to index into an array. The Nth vertex:
Vertex attributes are fetched automatically for you by the GPU and filled in before your vertex shader function is executed. Yes your vertex shader main is called once for every single vertex you draw.
The output of the vertex shader stage are the ‘varying’ variables. They are ‘varying’ because they are interpolated across the surface of the primitive (triangle) between vertices. You write the values out for each vertex but when the triangle is rasterized into fragments, each fragment gets the interpolated value of each varying variable. The fragment shader gets run for every fragment (pixel) that is “covered” by the draw call. If you draw a small triangle that covers a 4×4 patch of pixels then the fragment shader is executed 16 times.
Concisely: