Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perspecitve divide in vertex shader?

When using a perspective matrix in a vertex shader am I supposed to write code to divide by w or is it done automatically in a later stage?

The reason for my question is that I have seen lots of vertex shaders using:

gl_Position = matrix * pos;

which makes sense if there is a later stage that divides the vector with its w component.

However I never got it to work until I used the following in my vertex shader:

gl_Position = matrix * pos;
gl_Position = gl_Position / gl_Position.w;

Is the second example the correct one or could some other setting be missing?

Put it another way: which of the steps shown in the OpenGL Vertex transformation(first image) do I have to write in the vertex shader?

I know for sure that ModelView and Projection matrix belongs there(or a merge of the two). The viewport transform is not a part of the vertex shader, but what about the divide by w?

My setup is some simple triangles having coordinates within [-1 1] for x/y/z.

The Perspective matrix is supposed to project coordinates from z=-1 to -10 onto z=-1, x=[-1,1], y=[-1,1].

-1.0   0.0   0.0   0.0
 0.0  -1.0   0.0   0.0
 0.0   0.0  -1.2  -2.2
 0.0   0.0   1.0   0.0

It was generated by:

x = 2.0f * zNear / (xMax - xMin);
y = 2.0f * zNear / (yMax - yMin);
a = -(xMax + xMin) / (xMax - xMin);
b = -(yMax + yMin) / (yMax - yMin);
c = (zFar + zNear) / (zNear - zFar);
d = -(2.0f * zFar * zNear) / (zNear - zFar);

To make the matrix P:

x, 0, a, 0
0, y, b, 0
0, 0, c, d
0, 0, 1, 0;

Finally I generate the final matrix by matrix = P * T where T is a translation (0,0,-2)

I have tried to do the math on the CPU and it appears to work generating expected results, however there I also do the divide by w manually.

Update: Solved but need understanding

I negated all components in the matrix (multiply by -1) and now it works. The example above also had an issue with projecting both positive and negative z-coordinates onto the projection plane which also got solved by this change.

Any references or explanation why it got solved by this change is welcome.

like image 361
hultqvist Avatar asked Apr 27 '12 16:04

hultqvist


1 Answers

You should not do the perspective divide yourself in the vertex shader, it will be done automatically later in the pipeline.

If that's not working, can you show some code or describe the problem more? I'm surprised that it's making a difference for you.

like image 104
Tim Avatar answered Oct 11 '22 10:10

Tim