sam*_*sam 1 opengl glfw projection-matrix
我一直在编写一个程序来使用 OpenGL 显示 3D 模型,到目前为止我一直使用正交投影,但我想切换到透视投影,以便当相机朝向模型时,它看起来会变大。我知道我必须将三个矩阵(模型、视图和投影)相乘才能正确应用所有转换。正如您在下面的代码中看到的,我尝试这样做,并且能够正确创建模型和查看矩阵。我知道这些工作正常,因为当我将模型和视图投影相乘时,我可以旋转和平移对象,以及更改相机的位置和角度。我的问题是,当我将该乘积乘以投影矩阵时,我无法再在屏幕上看到该对象。
\n\n这里相机结构的默认值是 {0,0,-.5},但我使用键盘操纵该值来移动相机。
\n\n我正在使用 GLFW+glad,linmath.h用于矩阵数学。
//The model matrix controls where the object is positioned. The\n //identity matrix means no transformations.\n mat4x4_identity(m);\n //Apply model transformations here.\n\n //The view matrix controls camera position and angle.\n vec3 eye={camera.x,camera.y,camera.z};\n vec3 center={camera.x,camera.y,camera.z+1};\n vec3 up={0,1,0};\n mat4x4_look_at(v,eye,center,up);\n\n //The projection matrix flattens the world to 2d to be rendered on a\n //screen.\n mat4x4_perspective(p, 1.57, width/(float)height, 1,10); //FOV of 90\xc2\xb0\n //mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 1.f, -1.f);\n\n //Apply the transformations. mvp=p*v*m.\n mat4x4_mul(mvp, p, v);\n mat4x4_mul(mvp, mvp, m);\nRun Code Online (Sandbox Code Playgroud)\n
当透视投影矩阵设置好后,就设置了到近平面和远平面的距离。在您的情况下,近平面为 1,远平面为 10:
Run Code Online (Sandbox Code Playgroud)mat4x4_perspective(p, 1.57, width/(float)height, 1,10);
模型被近平面剪裁。模型必须位于裁剪空间中。
相机平截头体(截棱锥体)中的眼睛空间坐标被映射到立方体(标准化设备坐标)。所有不在平截头体体积内的几何体都会被剪掉。
这意味着模型到相机的距离必须大于到近平面的距离 (1) 且小于到远平面的距离 (10)。
由于在不使用任何投影矩阵时您可以“看到”模型,因此到模型的实际距离在 [-1, 1] 范围内(标准化设备空间)。请注意,如果不使用投影矩阵,则投影矩阵就是单位矩阵。这类似于正交投影,近平面距离为 -1,远平面距离为 1。
改变相机的位置即可解决问题:
例如
vec3 eye = {camera.x, camera.y, camera.z - 5}; // <--- 5 is in range [1, 10]
vec3 center = {camera.x, camera.y, camera.z};
vec3 up = {0, 1, 0};
mat4x4_look_at(v, eye, center, up);
Run Code Online (Sandbox Code Playgroud)