7

I'm familiar with vertex and fragment shaders but still confused about how a fragment shader determines the amount of fragments from the output of vertex shader.

If I have 3 vertices and I draw a triangle primitive in GLSL, then vertex shader will run three times for every vertex and then fragment shader will run many times (depending upon the number of fragments, once for each fragment).

I want to know how fragment shader determines the fragments? Does it use gl_Position? If I don't set gl_Position in my vertex shader does fragment shader still be able to generate fragments or not?

Is gl_Position is compulsory to set every time in vertex shader?

ammar26
  • 1,584
  • 4
  • 21
  • 41

1 Answers1

13

You're talking about the step in rasterization known as scan-conversion. The GPU takes the positions generated by your vertex shader and interpolates their attributes to produce the fragments that are passed to your fragment shader. So yes, it is essential for you to set gl_Position in the vertex shader.

After converting the coordinates of a triangle to window coordinates, scan conversion takes the triangle and breaks it up based on the arrangement of window pixels over the output image that the triangle covers. Source.

scan conversion of a triangle

warrenm
  • 31,094
  • 6
  • 92
  • 116
  • Means every single variable I pass through my vertex shader will be interpolated on the based on gl_Position? For example if I pass Texture Coordinates using out/in keywords from vertex to fragment shader they will also be interpolated for each frament? – ammar26 Nov 21 '14 at 20:46
  • 3
    Yes. Since the default interpolation qualifier is `smooth`, every incoming attribute is interpolated in a perspective-correct manner. – warrenm Nov 21 '14 at 21:00
  • Will it do this for every triangle? If there's a scene that essentially covers the screen 5x over with triangles, is it gonna generate 5x the fragments it needs to? – Java Noob May 01 '21 at 09:30
  • Yes, under some circumstances it will generate overlapping fragments; this is commonly called "overdraw." On mobile GPUs, part of this cost can be avoided by features like early Z-test, but if the primitives are transparent or if the fragment shader alters the depth of the fragments, most such techniques don't apply and work can be wasted. – warrenm May 02 '21 at 21:39