3

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.

3dmodels
  • 103
  • 7

1 Answers1

6

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.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
  • Thanks, that worked! And what if I'd like to perform a reverse operation? I multiply the coords by inversed matrix, but what to do with W components? I tryied both multiplying and dividing xyz with w but that gave strange results.. – 3dmodels Jan 07 '18 at 10:12
  • @3dmodels Probably you need to do `pos.xyz *= pos.w;` to cancel out the division first if needed, and then multiply by the inverse matrix. – HolyBlackCat Jan 07 '18 at 11:35