如何正确应用透视投影矩阵

时间:2021-07-01 16:26:11

标签: graphics 3d transformation projection-matrix

过去几天我一直在努力了解计算机图形学的基本原理并学习了一些教程。我选择不使用任何数学或图形库,因为这仅用于教育目的。我按照 opengl 教程来了解渲染 3d 点并对其进行转换的基本概念。 我成功渲染了一个立方体,但没有任何透视或考虑 z 轴。我无法弄清楚如何正确应用投影矩阵。从我读到的,我们变换的顶点必须在 [-1, 1] 中。但是,如果我已经对其进行了缩放和翻译,我该怎么做。在使用投影矩阵之前我需要做一个特定的转换吗?在应用投影矩阵后,我还需要进行转换吗?我在网上尝试了很多资源,但我无法弄清楚。我还没有添加相机,只是假设它在原点。

        Vector4 TemporaryVertex = triangles[i].points[j];
        TemporaryVertex = RotationZ() * RotationX() * scale() * TemporaryVertex; 
        //Scaled by 200 pixels currently, then rotating
        TemporaryVertex.x += position.x + window.getSize().x / 2; //translating
        TemporaryVertex.y += position.y + window.getSize().y / 2;
        TemporaryVertex.z += position.z + 5.f;

        TemporaryVertex = Projected() * temp.points[j]; //projecting

这些是投影矩阵的内容。

    float fNear = 0.1f;
    float fFar = 1000.0f;
    float fFov = 90.0f;
    float fAspectRatio = float(window.getSize().y)/ float(window.getSize().x);
    float fFovRad = 1.0f / tanf(fFov * 0.5f / 180.0f * 3.14159f);

    matProj[0][0] = fAspectRatio * fFovRad;
    matProj[1][1] = fFovRad;
    matProj[2][2] = fFar / (fFar - fNear);
    matProj[3][2] = (-fFar * fNear) / (fFar - fNear);
    matProj[2][3] = 1.0f;

这些都是顶点/三角形。

triangles = {
                Triangle(Vector4(0.0f, 0.0f, 0.0f), Vector4(0.0f, 1.0f, 0.0f), Vector4(1.0f, 1.0f, 0.0f)),
                Triangle(Vector4(0.0f, 0.0f, 0.0f), Vector4(1.0f, 1.0f, 0.0f), Vector4(1.0f, 0.0f, 0.0f)),
                Triangle(Vector4(1.0f, 0.0f, 0.0f), Vector4(1.0f, 1.0f, 0.0f), Vector4(1.0f, 1.0f, 1.0f)),
                Triangle(Vector4(1.0f, 0.0f, 0.0f), Vector4(1.0f, 1.0f, 1.0f), Vector4(1.0f, 0.0f, 1.0f)),
                Triangle(Vector4(1.0f, 0.0f, 1.0f), Vector4(1.0f, 1.0f, 1.0f), Vector4(0.0f, 1.0f, 1.0f)),
                Triangle(Vector4(1.0f, 0.0f, 1.0f), Vector4(0.0f, 1.0f, 1.0f), Vector4(0.0f, 0.0f, 1.0f)),
                Triangle(Vector4(0.0f, 0.0f, 1.0f), Vector4(0.0f, 1.0f, 1.0f), Vector4(0.0f, 1.0f, 0.0f)),
                Triangle(Vector4(0.0f, 0.0f, 1.0f), Vector4(0.0f, 1.0f, 0.0f), Vector4(0.0f, 0.0f, 0.0f)),
                Triangle(Vector4(0.0f, 1.0f, 0.0f), Vector4(0.0f, 1.0f, 1.0f), Vector4(1.0f, 1.0f, 1.0f)),
                Triangle(Vector4(0.0f, 1.0f, 0.0f), Vector4(1.0f, 1.0f, 1.0f), Vector4(1.0f, 1.0f, 0.0f)),
                Triangle(Vector4(1.0f, 0.0f, 1.0f), Vector4(0.0f, 0.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f)),
                Triangle(Vector4(1.0f, 0.0f, 1.0f), Vector4(0.0f, 0.0f, 0.0f), Vector4(1.0f, 0.0f, 0.0f))
    };

0 个答案:

没有答案