打开GL绘图GL_LINES给出不正确的结果



我正在尝试绘制速度矢量的网格,我希望每个网格点的速度是一条斜率为 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));

这是我得到的图像: 生成的图像

glVertexAttribPointer的第5个参数(stride(是两个顶点坐标之间的偏移量,而不是基元之间的偏移量。由于您的顶点坐标有 3 个类型float的分量,偏移量必须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);

最新更新