OpenGL perspective matrix far plane

The near plane clips at exactly the value I set just fine but instead of clipping at 1000 the far plane clips at 1.

Here is the code for the projection matrix:

public static Matrix4f perspective(Matrix4f dest, float fov, float aspectRatio, float near, float far) {
if (dest == null)
dest = new Matrix4f();

float tanHalfFOV = (float) Math.tan(fov / 2);
float range = near - far;

dest.m00 = 1.0f / (tanHalfFOV * aspectRatio);
dest.m10 = 0;
dest.m20 = 0;
dest.m30 = 0;
dest.m01 = 0;
dest.m11 = 1.0f / tanHalfFOV;
dest.m21 = 0;
dest.m31 = 0;
dest.m02 = 0;
dest.m12 = 0;
dest.m22 = (-near - far) / range;
dest.m32 = 2 * far * near / range;
dest.m03 = 0;
dest.m13 = 0;
dest.m23 = 1;
dest.m33 = 0;

return dest;
}


The near plane is 0.1 and the far plane is supposed to be 1000.

Your whole matrix is incorrect. For example, this is one of the ways it should look like:

So, in code:

dest.m00 = 1.0f / (tanHalfFOV * aspectRatio);
dest.m10 = 0;
dest.m20 = 0;
dest.m30 = 0;
dest.m01 = 0;
dest.m11 = 1.0f / tanHalfFOV;
dest.m21 = 0;
dest.m31 = 0;
dest.m02 = 0;
dest.m12 = 0;
dest.m22 = -(far + near) / range;
dest.m32 = -2 * far * near / range;
dest.m03 = 0;
dest.m13 = 0;
dest.m23 = -1;
dest.m33 = 0;


And you calculate range the wrong way, it needs to be far - near, not near - far.

• You were a bit rush when blamed the original matrix 'wrong'. It is correct. You can find it, for example here. – Grief Jun 3 '17 at 22:11

As far as I can tell by comparing to GLM perspective matrix implementation, your range is computed negative and you are missing some negative signs. Below are the corrections.

float range = far - near;
...
dest.m32 = - 2 * far * near / range;
dest.m23 = - 1;


Check it out on their git. I am not sure just which matrix you need, this answer is for the RH one. Check the link for other implementations.

• Wiith this nothing shows up at all. – minecraftwarlock Mar 24 '16 at 3:07
• @minecraftwarlock perhaps a sign is wrong somewhere or the camera is positioned incorrectly – Bikush Mar 24 '16 at 13:52