OpenGL顶点缓冲区例子
顶点缓冲区和顶点数组比较类似,但可以一次性将顶点数组放到缓冲区中,节省资源。
绘制部分代码如下:
1 #define BUFFER_COUNT 2
2 #define FOR_VERTICES 0
3 #define FOR_INDICES 1
4 static GLuint buffers[BUFFER_COUNT];
5
6 static void Draw()
7 {
8 static GLfloat vertices[][3] = {
9 { 0.5f, -sqrt(6.0f)/12, -sqrt(3.0f)/6},
10 {-0.5f, -sqrt(6.0f)/12, -sqrt(3.0f)/6},
11 { 0.0f, -sqrt(6.0f)/12, sqrt(3.0f)/3},
12 { 0.0f, sqrt(6.0f)/4, 0}
13 }; // 顶点数组
14
15 static GLuint vertexIndices[][3] = {
16 {0, 1, 2},
17 {0, 2, 3},
18 {2, 1, 3},
19 {1, 0, 3},
20 }; // 序号数组
21
22 // 一次分配两个缓冲区,并将顶点数据指定到其中
23 glGenBuffers(2, buffers);
24
25 // 绑定和载入顶点数组,告诉它使用顶点数组
26 glBindBuffer(GL_ARRAY_BUFFER, buffers[FOR_VERTICES]);
27 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
28
29 // 绑定和载入顶点索引数组
30 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[FOR_INDICES]);
31 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertexIndices), vertexIndices, GL_STATIC_DRAW);
32
33 // 和单纯使用顶点数组一样,需要声明顶点数组。
34 // 绑定缓冲区对象后,最后一个参数不再是指向数组的指针,而是
35 // 被解释为一个整数,表示相对于缓冲区的偏移。
36 glVertexPointer(3, GL_FLOAT, 0, (void *)0);
37 glEnableClientState(GL_VERTEX_ARRAY);
38 glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void *)0);
39 }
3 #define FOR_INDICES 1
4 static GLuint buffers[BUFFER_COUNT];
5
6 static void Draw()
7 {
8 static GLfloat vertices[][3] = {
9 { 0.5f, -sqrt(6.0f)/12, -sqrt(3.0f)/6},
10 {-0.5f, -sqrt(6.0f)/12, -sqrt(3.0f)/6},
11 { 0.0f, -sqrt(6.0f)/12, sqrt(3.0f)/3},
12 { 0.0f, sqrt(6.0f)/4, 0}
13 }; // 顶点数组
14
15 static GLuint vertexIndices[][3] = {
16 {0, 1, 2},
17 {0, 2, 3},
18 {2, 1, 3},
19 {1, 0, 3},
20 }; // 序号数组
21
22 // 一次分配两个缓冲区,并将顶点数据指定到其中
23 glGenBuffers(2, buffers);
24
25 // 绑定和载入顶点数组,告诉它使用顶点数组
26 glBindBuffer(GL_ARRAY_BUFFER, buffers[FOR_VERTICES]);
27 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
28
29 // 绑定和载入顶点索引数组
30 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffers[FOR_INDICES]);
31 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(vertexIndices), vertexIndices, GL_STATIC_DRAW);
32
33 // 和单纯使用顶点数组一样,需要声明顶点数组。
34 // 绑定缓冲区对象后,最后一个参数不再是指向数组的指针,而是
35 // 被解释为一个整数,表示相对于缓冲区的偏移。
36 glVertexPointer(3, GL_FLOAT, 0, (void *)0);
37 glEnableClientState(GL_VERTEX_ARRAY);
38 glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void *)0);
39 }