顶点着色器中的透视划分?

hul*_*ist 5 opengl opengl-3

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;
Run Code Online (Sandbox Code Playgroud)

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;
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

To make the matrix P:

x, 0, a, 0
0, y, b, 0
0, 0, c, d
0, 0, 1, 0;
Run Code Online (Sandbox Code Playgroud)

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.

Tim*_*Tim 5

你不应该在顶点着色器中自己做透视分割,它会在稍后的管道中自动完成。

如果这不起作用,您能否显示一些代码或更多地描述问题?我很惊讶它对你产生了影响。