一、概述
需求:通过两个VAO来管理VBO,从而控制两个三角形
此需求和单独通过VAO绘制一个三角形有较大的不同,此处创建两个VAO,同时需要管理两个VBO。在绘制图形的时候需要分别绑定这两个VAO才能正确的绘制出三角形。
效果:
二、代码示例
1.定义顶点数据(两个三角形的顶点)
float firstTriangle[] = { -0.9f, -0.5f, 0.0f, // left -0.0f, -0.5f, 0.0f, // right -0.45f, 0.5f, 0.0f, // top }; float secondTriangle[] = { 0.0f, -0.5f, 0.0f, // left 0.9f, -0.5f, 0.0f, // right 0.45f, 0.5f, 0.0f // top };
2.定义shader字符串
a.顶点shader字符串
#version 330 core layout (location = 0) in vec3 aPos; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); }
b.片元字符串
#version 330 core out vec4 FragColor; void main(void) { FragColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); }
3.定义两个VAO、和VBO分别进行管理
unsigned int VBOs[2], VAOs[2]; glGenBuffers(2, VBOs); glGenVertexArrays(2, VAOs); // we can also generate multiple VAOs or buffers at the same time // first triangle setup // -------------------- glBindVertexArray(VAOs[0]); glBindBuffer(GL_ARRAY_BUFFER, VBOs[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(firstTriangle), firstTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); // Vertex attributes stay the same glEnableVertexAttribArray(0); glBindVertexArray(VAOs[1]); // note that we bind to a different VAO now glBindBuffer(GL_ARRAY_BUFFER, VBOs[1]); // and a different VBO glBufferData(GL_ARRAY_BUFFER, sizeof(secondTriangle), secondTriangle, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0); // because the vertex data is tightly packed we can also specify 0 as the vertex attribute's stride to let OpenGL figure it out glEnableVertexAttribArray(0);
4.分别绘制出两个三角形
glUseProgram(programId); glBindVertexArray(VAOs[0]); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(VAOs[1]); glDrawArrays(GL_TRIANGLES, 0, 3);
标签:VAOs,OpenGL,0.0,void,0.5,GL,VAO,QT From: https://www.cnblogs.com/tony-yang-flutter/p/18374017