在GLES2中使用VBO和VAO對象,已經簡單vs,ps繪製一個三角形。數組
1. 初始化操做代碼,建立VBO、VAO,編譯和連接shader program。緩存
void DebugApplication::TestCreateVBO() { //頂點shader const GLchar* vertexShaderSrc = "#version 100\n" "attribute vec4 a_position; \n" // 輸入頂點屬性,從外部傳入 "void main()\n" "{\n" "gl_Position = vec4(a_position.x, a_position.y, a_position.z, 1.0);\n" "}\n\0"; //片斷shader const GLchar* fragmentShaderSrc = "#version 100\n" "void main()\n" "{\n" "gl_FragColor = vec4(1.0,0.5,0.5,1.0);\n" //隨意指定一個輸出顏色 "}\n\0"; //建立一個vertex shader GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSrc, NULL); //指定shader代碼 glCompileShader(vertexShader); //編譯shader //檢查是否編譯成功 GLint status; GLchar szInfo[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status); if (status != 1) { GLint realSize; glGetShaderInfoLog(vertexShader, 512, &realSize, szInfo); std::cout << " Vertex Shader Error : " << szInfo << std::endl; glDeleteShader(vertexShader); return; } //建立片斷shader GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragShader, 1, &fragmentShaderSrc, NULL); glCompileShader(fragShader); //檢查是否編譯成功 glGetShaderiv(fragShader, GL_COMPILE_STATUS, &status); if (status != 1) { GLint realSize; glGetShaderInfoLog(fragShader, 512, &realSize, &szInfo[0]); std::cout << " Fragment Shader Error : " << szInfo << std::endl; glDeleteShader(vertexShader); glDeleteShader(fragShader); return; } //連接Shader到Program GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragShader); glLinkProgram(shaderProgram); //檢查是否有連接錯誤 glGetProgramiv(shaderProgram, GL_LINK_STATUS, &status); if (!status) { GLint realSize; glGetShaderInfoLog(shaderProgram, 512, &realSize, &szInfo[0]); std::cout << "Programe Link Error : " << szInfo << std::endl; glDeleteShader(vertexShader); glDeleteShader(fragShader); glDeleteProgram(shaderProgram); return; } m_shader = shaderProgram; //設置頂點緩存 GLfloat vertices[] = { -0.5f,-0.5f, 0.f, 0.5f, -0.5f, 0.f, 0, 0.5f, 0.f }; //建立vbo vao GLuint VBO, VAO; glGenBuffers(1, &VBO); glGenVertexArrays(1, &VAO); //綁定VAO對象 glBindVertexArray(VAO); //複製頂點數組到頂點緩衝區中 glBindBuffer(GL_ARRAY_BUFFER,VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); //獲取vertex attribute "a_position"的入口點 GLuint location = glGetAttribLocation(shaderProgram, "a_position"); glEnableVertexAttribArray(location); //設置頂點屬性指針,傳遞數據vertex shader的位置0, glVertexAttribPointer(location, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 3, (GLvoid*)0); glBindBuffer(GL_ARRAY_BUFFER, 0); //解綁 glBindVertexArray(0); m_vao = VAO; glDeleteShader(vertexShader); glDeleteShader(fragShader); }
2. 使用以前建立好的VAO 和 shader program 在每幀繪製一個帶顏色的三角形。ui
void DebugApplication::TestDrawVBO() { //使用shader 綁定vao對象進行繪製 glUseProgram(m_shader); glBindVertexArray(m_vao); glDrawArrays(GL_TRIANGLES, 0, 3); glBindVertexArray(0); }