標籤:最大 def 相對 lun get 啟動 5.0 post pos
#include "stdlib.h" #include <OpenGL/glext.h> #include <GLUT/GLUT.h> #define BUFFER_OFFSET(bytes) ((GLubyte*) NULL + (bytes)) #define VERTICES 0 #define INDICES 1 #define NUM_BUFFERS 6 GLuint buffers[NUM_BUFFERS]; GLfloat vertices[][3] = { {-1.0f,-1.0f,-1.0f}, {1.0f,-1.0f,-1.0f}, {1.0f,1.0f,-1.0f}, {-1.0f,1.0f,-1.0f}, {-1.0f,-1.0f,1.0f}, {1.0f,-1.0f,1.0f}, {1.0f,1.0f,1.0f}, {-1.0f,1.0f,1.0f} }; GLubyte indices[][4] = { {0,1,2,3}, {4,7,6,5}, {0,4,5,1}, {3,2,6,7}, {0,3,7,4}, {1,5,6,2} }; GLfloat* bdata; void changeSize(int w, int h) { glViewport(0,0,(GLsizei)w,(GLsizei)h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0,(double)w/(double)h,0.01,30); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void keyDown(unsigned char key, int x, int y) { switch (key) { case‘b‘: bdata = (GLfloat*)glMapBuffer(GL_ARRAY_BUFFER,GL_READ_WRITE); for (int i =0; i <24; i ++) { *(bdata + i) *=1.1f; } glUnmapBuffer(GL_ARRAY_BUFFER); glutPostRedisplay(); break; } } void mouse(int button, int state, int x, int y) { } void display(void) { glLoadIdentity(); glTranslatef(0.0f,0.0f,-5.0f); glRotatef(30.0f,1.0f,1.0f,0.0f); // 6. 繪製, 這個地方注意的是最後一個參數,這個與普通的非VBO最大的不同就在這裡 glDrawElements(GL_QUADS,24,GL_UNSIGNED_BYTE,BUFFER_OFFSET(0)); //glDrawArrays(GL_TRIANGLE_FAN, 0, 8); glutSwapBuffers(); } void init(void) { glClearColor(0.0f,0.0f,0.0f,0.0f); glShadeModel(GL_FLAT); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //1. 建立緩衝區對象,系統會自動建立緩動區標示符放入到buffers中,可以使用glIsBuffer()函數,判斷一個標示符是否被使用 glGenBuffers(NUM_BUFFERS ,buffers); //2. 啟用緩衝區對象,綁定緩衝區對象表示未來選擇的操作將影響哪個緩衝區。 如果要金融緩衝區對象,可以用0來作為緩衝區對象的標示符, 第一個參數target可以為GL_ARRAY_BUFFER,GL_ELEMENT_ARRAY_FUFFER glBindBuffer(GL_ARRAY_BUFFER,buffers[VERTICES]); //3. 用資料分配和初始化緩衝區對象 glBufferData(GL_ARRAY_BUFFER,sizeof(vertices),vertices,GL_DYNAMIC_DRAW); //4. 指定相對於緩衝區起始位置的位移量 glVertexPointer(3,GL_FLOAT,0,BUFFER_OFFSET(0)); //5.一定不要忘記啟動 glEnableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,buffers[INDICES]); glBufferData(GL_ELEMENT_ARRAY_BUFFER,sizeof(indices),indices,GL_STATIC_DRAW); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GL_DOUBLE | GLUT_RGBA | GLUT_DEPTH); glutInitWindowSize(512, 512); glutCreateWindow("Buffer Demo"); init(); glutReshapeFunc(changeSize); glutMouseFunc(mouse); glutKeyboardFunc(keyDown); glutDisplayFunc(display); glutMainLoop(); return 0; }
原文連結:OpenGL 通過VBO實現頂點數組繪製頂點
[轉]OpenGL 通過VBO實現頂點數組繪製頂點