在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, , &vertexShaderSrc, NULL); //指定shader代码
glCompileShader(vertexShader); //编译shader //检查是否编译成功
GLint status;
GLchar szInfo[];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &status);
if (status != )
{
GLint realSize;
glGetShaderInfoLog(vertexShader, , &realSize, szInfo);
std::cout << " Vertex Shader Error : " << szInfo << std::endl;
glDeleteShader(vertexShader);
return;
} //创建片段shader
GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragShader, , &fragmentShaderSrc, NULL);
glCompileShader(fragShader); //检查是否编译成功
glGetShaderiv(fragShader, GL_COMPILE_STATUS, &status);
if (status != )
{
GLint realSize;
glGetShaderInfoLog(fragShader, , &realSize, &szInfo[]);
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, , &realSize, &szInfo[]);
std::cout << "Programe Link Error : " << szInfo << std::endl;
glDeleteShader(vertexShader);
glDeleteShader(fragShader);
glDeleteProgram(shaderProgram);
return;
}
m_shader = shaderProgram; //设置顶点缓存
GLfloat vertices[] = {
-0.5f,-0.5f, .f,
0.5f, -0.5f, .f,
, 0.5f, .f
};
//创建vbo vao
GLuint VBO, VAO;
glGenBuffers(, &VBO);
glGenVertexArrays(, &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, , GL_FLOAT, GL_FALSE, sizeof(float) * , (GLvoid*));
glBindBuffer(GL_ARRAY_BUFFER, );
//解绑
glBindVertexArray(); m_vao = VAO; glDeleteShader(vertexShader);
glDeleteShader(fragShader);
}
2. 使用之前创建好的VAO 和 shader program 在每帧绘制一个带颜色的三角形。
void DebugApplication::TestDrawVBO()
{
//使用shader 绑定vao对象进行绘制
glUseProgram(m_shader);
glBindVertexArray(m_vao);
glDrawArrays(GL_TRIANGLES, , );
glBindVertexArray();
}