3
votes

I'm studying opengl and I'v got i little 3d scene with some objects. In GLSL vertex shader I multiply vertexes on matixes like this:

vertexPos= viewMatrix * worldMatrix * modelMatrix * gl_Vertex;
gl_Position = vertexPos;

vertexPos is a vec4 varying variable and I pass it to fragment shader. Here is how the scene renders normaly: normal render

But then I wana do a debug render. I write in fragment shader:

gl_FragColor = vec4(vertexPos.x, vertexPos.x, vertexPos.x, 1.0); 

vertexPos is multiplied by all matrixes, including perspective matrix, and I assumed that I would get a smooth gradient from the center of the screen to the right edge, because they are mapped in -1 to 1 square. But look like they are in screen space but perspective deformation isn't applied. Here is what I see: (dont look at red line and light source, they are using different shader)

debug render

If I devide it by about 15 it will look like this:

gl_FragColor = vec4(vertexPos.x, vertexPos.x, vertexPos.x, 1.0)/15.0;

devided by 15

Can someone please explain me, why the coordinates aren't homogeneous and the scene still renders correctly with perspective distortion? P.S. if I try to put gl_Position in fragment shader instead of vertexPos, it doesn't work.

1

1 Answers

6
votes

A so-called perspective division is applied to gl_Position after it's computed in a vertex shader:

gl_Position.xyz /= gl_Position.w;

But it doesn't happen to your varyings unless you do it manually. Thus, you need to add

vertexPos.xyz /= vertexPos.w;

at the end of your vertex shader. Make sure to do it after you copy the value to gl_Position, you don't want to do the division twice.