简体   繁体   中英

OpenGL projection matrix for perspective with fovy and aspect

I'm making my custom frustum and perspective implementations, part of the reasons are that I might need to do it myself, without library, in the future, and I want to polish up computer graphics skills before the exam.

I'm following a book and I am converting their examples in C++ to my ones in Java/LWJGL, however one example strikes me, it is the projection of a cube.
My cube is projected much further away (about double?) as theirs, which is odd.

This are my implemenations in column-major order:

public static Matrix4f frustum(final float left, final float right, final float bottom, final float top, final float near, final float far) {
    return new Matrix4f(new float[] {
        2 * near / (right - left),          0.0f,                               0.0f,                           0.0f,   //X column
        0.0f,                               2 * near / (top - bottom),          0.0f,                           0.0f,   //Y column
        (right + left) / (right - left),    (top + bottom) / (top - bottom),    (near + far) / (near - far),    -1.0f,  //Z column
        0.0f,                               0.0f,                               2 * near * far / (near - far),  0.0f    //Z column
    });
}

public static Matrix4f perspective(final float fovy, final float aspect, final float near, final float far) {
    float y2 = near * (float)Math.tan(Math.toRadians(fovy));
    float y1 = -y2;
    float x1 = y1 * aspect;
    float x2 = y2 * aspect;
    return frustum(x1, x2, y1, y2, near, far);
}

I've seen somewhere where they use a similar y2 as I have but divide it by 2, however I do not want to make a dirty fix without exactly understanding why it is going wrong.

Could someone verify whether the perspective matrix I am using, and point me out what the other reasons could be that my object looks to be further away?

I have got my other matrix math right and I am only translating the cube by (0f, 0f, -4f) and verified that that was also correct.

Would a wrongly implemented perspective matrix cause my object to be further away?

Your implementation of frustum seems correct.

In your implementation of perspective, fovy should be fovy / 2 instead.

See this answer: https://stackoverflow.com/a/21064935/3146587

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM