Why passing parameter is OK between Vertex and Fragment shader

288 views Asked by At

A typical shader is like this:

struct vin_vct 
        {
            float4 vertex : POSITION;
            float4 color : COLOR;
            float2 texcoord : TEXCOORD0;
        };

        struct v2f_vct
        {
            float4 vertex : POSITION;
            fixed4 color : COLOR;
            float2 texcoord : TEXCOORD0;
        };

        v2f_vct vert_vct(vin_vct v)
        {
            v2f_vct o;
            o.vertex = mul(UNITY_MATRIX_MVP, v.vertex);
            o.color = v.color;
            o.texcoord = v.texcoord;
            return o;
        }

        fixed4 frag_mult(v2f_vct i) : COLOR
        {
            fixed4 col = tex2D(_MainTex, i.texcoord) * i.color;
            return col;
        }

What I'm confused is: vert_vct is called every vertex; frag_mult is called every fragment (pixel in most cases);

So basically frag_mult will run different times with vert_vct, for example, frag mult runs 10 times, and vert_vct runs 3 times for a triangle. Then every time frag_mult runs it will accept a parameter passed by vert_vct, then how to map between frag and vert if the run times are different, how to decide which vert_vct will pass to specified frag_mult?

1

There are 1 answers

0
bjorke On

The counts for vertex and fragment shader executions are not directly connected.

If you have a triangle, you are correct hat the vertex shader will run three times, once for each vertex. But then its results are interpolated -- that is, rasterized -- onto however many fragments are covered by the final, projected on-screen triangle. It might be every pixel on the screen for a huge triangle, or none for a triangle that's off-screen. If there are any visible pixels, then the fragment shader is run once for each one of those pixels (err, fragments, as the GL nomenclature goes).

Because the values are interpolated between vertices, you may get values on most fragments that are not exactly the values for any single vertex, unless you pass the same value to all three of those vertexes -- for example, if you have all red vertices in your model as v.color then that will pass to o.color and i.color will appear constant everywhere. Even then, the values are still being interpolated, but since they are all the same, the result is effectively constant.

Does that make sense to you?