glDrawElements
接口定义
void glDrawElements(
GLenum mode, // 绘制的类型,如GL_LINE_STRIP,GL_TRIANGLES等
GLsizei count, // 需要绘制的顶点数
GLenum type, // 绘制元素的类型(取决于顶点数据的类型)
const GLvoid * indices // 数据Buffer的Offset指针
);
简单使用:
//correspond code in shader: layout (location = 2) in vec3 aColor;
GLint vertexColorLocation = 2;
glEnableVertexAttribArray(vertexLocation);
glVertexAttribPointer(vertexColorLocation,
3,
GL_FLOAT,
GL_FALSE,
0,
colour);//colour为每个顶点的颜色数组
// indices 为顶点位置数据,36 为顶点数量
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, indices);
glDisableVertexAttribArray(vertexColorLocation);
glDrawArrays
接口定义
void glDrawArrays(
GLenum mode,
GLint first, // 绑定数组(加载到OpenGL)中的元素开始下标
GLsizei count //读取几个
);
绘制例子
// 顶点数据格式:
// GLfloat[] = {x1,y1,z1,r1,g1,b1,x2,y2,z2,r2,g2,b2....}
// 顶点颜色Buf
GLuint vertBuf;
glGenBuffers(1, &vertBuf);
glBindBuffer(GL_ARRAY_BUFFER, vertBuf);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cubeVerticesWithColor),
cubeVerticesWithColor,
GL_STATIC_DRAW);
// 设置顶点数据属性
GLint vertexLocation = 0;
glVertexAttribPointer(
vertexLocation,
3,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 6,//6:x,y,z,r,g,b
(void *) 0
);
glEnableVertexAttribArray(vertexLocation);
// 设置顶点颜色数据属性
GLint vertexColorLocation = 2;
glVertexAttribPointer(vertexColorLocation,
3,
GL_FLOAT,
GL_FALSE,
sizeof(GLfloat) * 6,
(void *) (sizeof(GLfloat) * 3));
glEnableVertexAttribArray(vertexColorLocation);
// 索引Buf
GLuint vertIndexedBuf;
glGenBuffers(1, &vertIndexedBuf);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertIndexedBuf);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
// 绘制
// glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, indices);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_SHORT, 0);
if (EGL_FALSE == eglSwapBuffers(mEglDisplay, mEglSurface)) {
//error
}
glDisableVertexAttribArray(vertexLocation);
glDisableVertexAttribArray(vertexColorLocation);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glDeleteBuffers(1, &vertBuf);
glDeleteBuffers(1, &vertIndexedBuf);