OpenGL - 在3D场景

时间:2015-09-07 07:44:28

标签: c++ opengl orthographic

我正在尝试在3D模型的顶部绘制一个2D叠加层,它必须出现在屏幕的左上角,但我得到的是我想要绘制的矩形放置在3D的中间模型。您可以在下面看到我输出的屏幕截图。 enter image description here

我对正交矩阵的设置就像这样

2 / (right - left), 0, 0, 0,
0, 2 / (top - bottom), 0, 0,
0, 0, 2 / (far - near), 0,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1

关于如何在3D上绘制2D叠加层的步骤,我按照this回答。此外,根据输出,矩形看起来根本不是叠加层。 希望你能帮助我:)。

编辑:

这是我绘制模型的方式。请注意,此代码块将使用两次来绘制2个模型

GLuint vao;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

GLuint buffer;
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, cc * sizeof(GLfloat), v, GL_STATIC_DRAW);

GLuint tcbuffer;
glGenBuffers(1, &tcbuffer);
glBindBuffer(GL_ARRAY_BUFFER, tcbuffer);
glBufferData(GL_ARRAY_BUFFER, tcc * sizeof(GLfloat), vt, GL_STATIC_DRAW);

GLuint ncbuffer;
glGenBuffers(1, &ncbuffer);
glBindBuffer(GL_ARRAY_BUFFER, ncbuffer);
glBufferData(GL_ARRAY_BUFFER, ncc * sizeof(GLfloat), vn, GL_STATIC_DRAW);

glEnableVertexAttribArray(m_vert);
glBindBuffer(GL_ARRAY_BUFFER, vbufferid);
glVertexAttribPointer(m_vert, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(m_texcoord);
glBindBuffer(GL_ARRAY_BUFFER, tcbufferid);
glVertexAttribPointer(m_texcoord, 2, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(m_color);
glBindBuffer(GL_ARRAY_BUFFER, cbufferid);
glVertexAttribPointer(m_color, 4, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(m_vertexnormal);
glBindBuffer(GL_ARRAY_BUFFER, ncbufferid);
glVertexAttribPointer(m_vertexnormal, 3, GL_FLOAT, GL_FALSE, 0, 0);

glDrawArrays(GL_TRIANGLES, 0, vc);

用于设置投影。

Matrix44 fov_matrix(double fov, double aspect, double near, double far) {
    var yScale = 1.0 / Math.tan(fov / 2);
    var xScale = yScale / aspect;
    return(Matrix44.for_values(
        xScale, 0, 0, 0,
        0, yScale, 0, 0,
        0, 0, (far + near) / (near - far), -1,
        0, 0, 2 * far * near / (near - far), 0
    ));
}

Matrix44 orthographic_matrix(double left, double right, double bottom, double top, double near, double far) {
    return(Matrix44.for_values(
        2 / (right - left), 0, 0, 0,
        0, 2 / (top - bottom), 0, 0,
        0, 0, 2 / (far - near), 0,
        -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1
    ));
}

var projm = fov_matrix(MathConstant.M_PI/4, get_aspect_ratio(), 1.0, 100.0);
var orthoprojm = orthographic_matrix(0.0, 800, 600, 0.0, -100.0, 1.0);

1 个答案:

答案 0 :(得分:2)

你的投影基质对我来说是正确的。看起来用于Spanch Bob绘图的矩阵也用于您的叠加。 检查:

  1. 编译叠加层的两个着色器。 glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
  2. 叠加程序已正确关联。 glGetProgramiv(program, GL_LINK_STATUS, &status);
  3. 检查您使用的是正确的程序。 glGetIntegeriv(GL_CURRENT_PROGRAM, &program)
  4. glGetUniformLocation(program, "yourMVPmatrix")返回正确的ID。
  5. 请注意,如果任何程序未正确链接,OpenGL将在glDraw*的任何一个上赢得竞赛错误。