openGL绘图GL_LINES给出不正确的结果

时间:2018-10-08 15:06:52

标签: opengl vertex-buffer vertex-array-object openglrenderer

我正在尝试绘制速度矢量网格,我希望每个网格点处的速度都是斜率为1的线。斜线,但是我总是以垂直线结尾。我不确定自己在做什么错。我有什么要忽略的吗?

这是我的顶点缓冲区的外观:

float vel_pos[6*(N+2)*(N+2)];
int index1 = 0;
for (int i=0;i<N+2;i++)
{
    for (int j=0;j<N+2;j++)
    {
        vel_pos[index1] = float(i);
        vel_pos[index1+1] = float(j);
        vel_pos[index1+2] = 0.0f;
        vel_pos[index1+3] = float(i) +0.5f;
        vel_pos[index1+4] = float(j) + 0.5f;
        vel_pos[index1+5] = 0.0f;
        index1 += 6;
    }
}

这是我创建VBO和VAO的方式:

unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);

// Bind vertex array object first and then bind the vertex buffer objects
glBindVertexArray(VAO);

glBindBuffer(GL_ARRAY_BUFFER, VBO);

glBufferData(GL_ARRAY_BUFFER, sizeof(vel_pos), vel_pos, GL_STREAM_DRAW);


GLint velAttrib = glGetAttribLocation(ourShader.ID, "aPos");

// iterpreting data from buffer 
glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);

这是我的顶点着色器:

  out vec4 vertexColor;
  layout (location = 0) in vec3 aPos; 
  layout (location = 1) in float densitySource; /* source of density */
  uniform mat4 transform;
  uniform mat4 projection;

  void main()
  {
  gl_Position = projection*transform * vec4(aPos, 1.0);
  vertexColor = vec4(1, 0.0, 0.0, 1.0);
  }

这是我的绘图代码:

  ourShader.use();

    glm::mat4 trans = glm::mat4(1.0f);
    trans = glm::translate(trans, glm::vec3(-0.5f, -0.5f, 0.0f));
    unsigned int transformMatrixLocation = glGetUniformLocation(ourShader.ID, "transform");
    glUniformMatrix4fv(transformMatrixLocation, 1, GL_FALSE, glm::value_ptr(trans));

    glm::mat4 projection = glm::ortho(-10.0f, 110.0f, -1.0f, 110.0f, -1.0f, 100.0f);

    unsigned int projectionMatrixLocation = glGetUniformLocation(ourShader.ID, "projection");
    glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, glm::value_ptr(projection));

    glBindVertexArray(VAO); 
    glLineWidth(1.0f);
    glDrawArrays(GL_LINES,  0, (N+2)*(N+2));

这是我得到的图像: resulting image

1 个答案:

答案 0 :(得分:1)

glVertexAttribPointer的第五个参数(stride)是两个顶点坐标之间的偏移量,而不是图元之间的偏移量。由于您的顶点坐标具有float类型的3个分量,因此偏移量必须为3 * sizeof(float)

glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  3 * sizeof(float), (void*)0);

由于将偏移量设置为6 * sizeof(float),因此跳过了每2个坐标,并在网格的点之间绘制了线。

但是请注意,如果stride为0,则将通用顶点属性理解为紧密包装在数组中。就是这种情况,因此您可以使用0的偏移量:

glVertexAttribPointer(velAttrib, 3, GL_FLOAT, GL_FALSE,  0, (void*)0);