0 c++ opengl shader glsl glm-math
当运行程序两次时,它在运行时不会显示相同的结果,即使我使用相同的可执行文件.
这里有一点背景:
我用Sierra 10.13在MacAir上编程,我的IDE是Xcode 10.1.
我发现我的问题是由顶点着色器中添加变换矩阵引起的:
// This code is not working
#version 330 core
layout (location = 0) in vec3 position;
layout (location = 1) in vec2 textureCoords;
out vec2 pass_textureCoords;
uniform mat4 transformM;
void main() {
gl_Position = transformM * vec4(position, 1.0);
pass_textureCoords = textureCoords;
}
Run Code Online (Sandbox Code Playgroud)
我以这种方式加载transformM矩阵(我正在使用GLM库进行数学运算):
void LoadMatrix(int location, glm::mat4 matrix) {
glUniformMatrix4fv(location, 1, GL_FALSE, &matrix[0][0]);
}
Run Code Online (Sandbox Code Playgroud)
这里的位置是:
uniformName = "transformM";
location = glGetUniformLocation(_shaderID, uniformName.c_str());
Run Code Online (Sandbox Code Playgroud)
(我保持简单但你可以在这里找到完整的代码:https://github.com/Cuiyere/Ecosystem)
事实上,我希望我的代码能够渲染一个立方体并旋转它,但它并没有显示出50%的时间.
我不明白为什么会出现这个问题.我检查了我的代码一百次,检查了docs.gl网站,将ThinMatrix的代码与我的代码进行了比较(即使用Java编写,整体结构和OpenGL功能仍然完全相同),检查OpenGL论坛,但据我所知看,没有人遇到过这个问题.
我认为这是OpenGL使用顶点着色器的一个问题,但我不能肯定.
默认构造函数glm::mat4不初始化矩阵.之前void Renderer::CreateProjectionMatrix()在构造函数中调用class Render,_projectionMatrix未初始化.
该方法void Renderer::CreateProjectionMatrix()不初始化矩阵的所有字段_projectionMatrix.矩阵中未初始化的字段会导致未定义的行为.
分配单位矩阵,以_projectionMatrix在开始的功能,以确保所有字段都被初始化:
void Renderer::CreateProjectionMatrix() {
_projectionMatrix = glm::mat4(1.0f);
// [...]
}
Run Code Online (Sandbox Code Playgroud)
或者使用构造函数初始化矩阵:
Renderer::Renderer (Shaders::StaticShader shader)
: _projectionMatrix(1.0f)
{
CreateProjectionMatrix();
// [...]
}
Run Code Online (Sandbox Code Playgroud)
但请注意,如果命名了一个方法CreateProjectionMatrix,它应该设置该成员的所有字段_projectionMatrix.
而且你必须初始化成员_position,_pitch,_yaw和_roll的class Camera在构造函数:
Camera()
: _position(0.0f, 0.0f, 0.0f)
, _pitch(0.0f)
, _yaw(0.0f)
, _roll(0.0f)
{};
Run Code Online (Sandbox Code Playgroud)
在该方法中ShaderProgram::CompileShader是另一个问题.返回值的类型ShaderProgram::ReadShader是std::string.因此,ReadShader( shaderPath ).c_str()将返回一个指向临时对象的指针,该指针在赋值语句结束时立即被销毁.该std::string对象被破坏和无处指针指向.
将返回值赋给ShaderProgram::ReadShader局部变量,并在以下范围内使用指向此局部变量内容的指针ShaderProgram::CompileShader:
unsigned int ShaderProgram::CompileShader (unsigned int type, const std::string & shaderPath) {
unsigned int id = glCreateShader(type);
std::string code = ReadShader( shaderPath );
const char* src = code.c_str();
glShaderSource(id, 1, &src, nullptr);
glCompileShader(id);
// [...]
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91 次 |
| 最近记录: |