c++ - glm 在简单翻译中返回 nan

标签 c++ opengl matrix glm-math coordinate-transformation

我正在使用 glfw、glad 和 glm 修补 OpenGL。在我使用的其中一个教程中,他们演示了 glm 的一些简单用法:

glm::vec4 vec(1.0f, 0.0f, 0.0f, 1.0f);
glm::mat4 trans;
trans = glm::translate(trans, glm::vec3(1.0f, 1.0f, 0.0f));
vec = trans * vec;
std::cout << vec.x << vec.y << vec.z << std::endl;

当我编译并运行这段代码时,我得到了垃圾值(通常是 NAN)。教程特别指出实例化

glm::mat4 trans;

默认情况下会为变量“trans”创建一个单位矩阵。我在想也许这就是问题所在,尽管我已经证实 glm 默认情况下确实这样做。

如果有帮助,您可以找到整个源文件 here在第 308 行。非常感谢您的宝贵时间!

最佳答案

您必须初始化矩阵变量 glm::mat4 trans

glm API documentationThe OpenGL Shading Language specification 4.20 .

5.4.2 Vector and Matrix Constructors

If there is a single scalar parameter to a vector constructor, it is used to initialize all components of the constructed vector to that scalar’s value. If there is a single scalar parameter to a matrix constructor, it is used to initialize all the components on the matrix’s diagonal, with the remaining components initialized to 0.0.

这意味着,单位矩阵可以通过单个参数 1.0 进行初始化:glm::mat4(1.0f)

像这样改变你的代码:

glm::mat4 trans(1.0f);


另见 OpenGL Mathematics (GLM); 2. Vector and Matrix Constructors

关于c++ - glm 在简单翻译中返回 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49058381/

相关文章:

c++ - 为什么模板只能在头文件中实现?

python - 检索矩阵中的上述元素 (Python)

c++ - 如何在QGLWidget中缩放和滚动

c++ - 尝试在 OSX 而不是 Linux 中创建多个帧缓冲区对象时出现问题

c++ - glReadPixels 不起作用

C++ 多维 vector 如何在内部增长?

python - 将 2-d 矩阵的每一列乘以 3-d 矩阵的每个切片的更有效方法

c++ - 在 C++ 中逐像素绘制

c++ - 反复点击QSplashscreen背景变黑

c++ - 在 Visual C 2010 项目中包含一个 Visual 2005 库