如何使用glDrawElements在OpenGL中绘制一个立方体?

时间:2015-12-07 00:30:32

标签: c++ opengl

使用glDrawElements绘制多维数据集时遇到问题。这是应该工作的代码,我在一些演示文稿中找到了它,但我没有得到一个立方体,并且图像在调整大小时闪烁。

以下是代码:

float a = 1;

float* vert = new float[24];
float* col = new float[24];
float* ind = new float[24];

vert[0] = -a / 2;   vert[1] = -a / 2;   vert[2] = a / 2;        //vert0
vert[3] = a / 2;    vert[4] = -a / 2;   vert[5] = a / 2;        //vert1
vert[6] = a / 2;    vert[7] = a / 2;    vert[8] = a / 2;        //vert2
vert[9] = -a / 2;   vert[10] = a / 2;   vert[11] = a / 2;       //vert3
vert[12] = -a / 2;  vert[13] = -a / 2;  vert[14] = -a / 2;      //vert4
vert[15] = a / 2;   vert[16] = -a / 2;  vert[17] = -a / 2;      //vert5
vert[18] = a / 2;   vert[19] = a / 2;   vert[20] = -a / 2;      //vert6
vert[21] = -a / 2;  vert[22] = a / 2;   vert[23] = -a / 2;      //vert7

col[0] = 0.0;   col[1] = 0.0;   col[2] = 0.0;                   //col10
col[3] = 1.0;   col[4] = 0.0;   col[5] = 0.0;                   //col11
col[6] = 1.0;   col[7] = 1.0;   col[8] = 0.0;                   //col12
col[9] = 1.0;   col[10] = 1.0;  col[11] = 1.0;                  //col13
col[12] = 0.0;  col[13] = 1.0;  col[14] = 0.0;                  //col14
col[15] = 0.0;  col[16] = 1.0;  col[17] = 1.0;                  //col15
col[18] = 0.0;  col[19] = 0.0;  col[20] = 1.0;                  //col16
col[21] = 0.0;  col[22] = 0.0;  col[23] = 0.0;                  //col17

//indeksi
ind[0] = 0; ind[1] = 1; ind[2] = 2; ind[3] = 3;             //quad0
ind[4] = 1; ind[5] = 5; ind[6] = 6; ind[7] = 2;             //quad1
ind[8] = 7; ind[9] = 6; ind[10] = 5;ind[11] = 4;            //quad2
ind[12] = 0;ind[13] = 3;ind[14] = 7;ind[15] = 4;            //quad3
ind[16] = 7;ind[17] = 3;ind[18] = 2;ind[19] = 6;            //quad4
ind[20] = 0;ind[21] = 4;ind[22] = 5;ind[23] = 1;            //quad5


glVertexPointer(3, GL_FLOAT, 0, vert);
glColorPointer(3, GL_FLOAT, 0, col);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, ind);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);

以下是我调整大小的一些图像(有时我没有得到图像): OpenGl Cube glDrawElements

您有什么建议如何解决这个问题? 提前致谢

1 个答案:

答案 0 :(得分:0)

索引类型与数据不对应。

float* ind = new float[24];
glDrawElements(GL_QUADS, 24, GL_UNSIGNED_BYTE, ind);

您定义了一个float数组,但告诉OpenGL它包含无符号字节。

阵列的正确版本是

GLubyte* ind = new GLubyte[24];