【发布时间】:2024-01-04 12:46:01
【问题描述】:
我已经开始研究定向光的阴影贴图,为此我需要一个 lookAt 矩阵,但是当我尝试从在线教程的示例中构建时,它看起来像这样:
目前看起来像这样: https://media.giphy.com/media/QrMnqBBJZuATu/giphy.gif
我尝试了多种构建它的方法,但没有成功,我检查了规范化、交叉和翻译功能是否不正确,但事实并非如此。我也尝试从列主矩阵更改为行主矩阵,但没有运气。有人能指出我做错了什么吗?
查看矩阵构造:
中心向量 = (0, 0, 0), 上向量 = (0, 1, 0)
Matrix4f Matrix4f::lookAt(const Vector3f& position, const Vector3f& center, const Vector3f& up) {
Matrix4f out(1.0f);
Vector3f z = position.substract(center).normalize();
Vector3f y = up;
Vector3f x = y.cross(z).normalize();
y = z.cross(x);
out.mElements[0 * 4 + 0] = x.x;
out.mElements[0 * 4 + 1] = x.y;
out.mElements[0 * 4 + 2] = x.z;
out.mElements[1 * 4 + 0] = y.x;
out.mElements[1 * 4 + 1] = y.y;
out.mElements[1 * 4 + 2] = y.z;
out.mElements[2 * 4 + 0] = z.x;
out.mElements[2 * 4 + 1] = z.y;
out.mElements[2 * 4 + 2] = z.z;
return (out * Matrix4f::translation(Vector3f(-position.x, -position.y, -position.z)));
}
}
代码致谢:https://*.com/users/5577765/rabbid76
这就是我将矩阵传递给着色器的方式:
void Shader::setMat4(const char* name, const math::Matrix4f& matrix){
glUniformMatrix4fv(getUniformLocation(name), 1, GL_TRUE, matrix.mElements);
}
在我计算出 lookAt 矩阵后,我直接将它传递给顶点着色器到统一:view 并计算一个点,如下所示:
gl_Position = projection * view * model * vec4(vertexPosition, 1.0);
这就是我的矩阵乘法的工作原理:
Matrix4f Matrix4f::multiply(const Matrix4f& other) const {
Matrix4f out;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
fl32 o = 0;
for (int c = 0; c < 4; c++) {
o += this->mElements[c + y * 4] * other.mElements[x + c * 4]; }
out.mElements[x + y * 4] = o;
}
}
return out;
}
编辑:更新图片 编辑:添加了更详细的描述
【问题讨论】:
-
GLSL 不提供
lookAt函数吗?您是否有理由手动执行此操作而不是让着色器处理计算? -
@0x5453 为了让着色器免于计算这么多,并试图弄清楚观察矩阵是如何工作的。
-
@0x5453: "GLSL 不提供查看函数吗?" 不,它没有。
-
@0x5453 glsl 当然没有,但是有一些以 opengl 为中心的库,glm 就是其中之一,因为它在 github 我建议 OP 看看 its implementation
-
如何将 Matrix4f 传递给 OpenGL?矩阵乘法背后的概念是什么?我的意思是,一个点是由
M*p还是p*M转换的?你如何使用lookAt的结果?我的意思是,它是相机的矩阵,还是它的倒数?我们需要知道这些事情才能回答这个问题。