PDA

View Full Version : 3.2 Core, VAO, and glDrawElements not drawing



devonM
11-21-2012, 04:57 PM
Greetings. First time posting here. I'm fairly new with OpenGL and am having a devil of a time trying to get glDrawElements to work. I am using 3.2 Core to attempt to draw a simple multicolored triangle. When I use the glDrawArrays method as specified in the code below the triangle displays. When I comment that out and use the glDrawElements method nothing is displayed. I have to use a vertex array object because I am running this on Mac OS X. I had also checked for glerrors and did not have any. Any help would be greatly appreciated!


GLfloat vertices[] = { -0.3f, 0.5f, -1.0f,
-0.8f, -0.5f, 0.0f,
0.2f, -0.5f, 0.0f };
GLfloat colours[] = { 1.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 1.0f };
GLuint indices[] = {0,1,2};

// two vertex array objects, one for each object drawn
unsigned int vertexArrayObjID;
// three vertex buffer objects in this example
unsigned int vertexBufferObjID[3];

GLuint indexBufferID;

static void initOpenGL()
{
// Allocate Vertex Array Objects
glGenVertexArrays(1, &vertexArrayObjID);
// Setup first Vertex Array Object
glBindVertexArray(vertexArrayObjID);
glGenBuffers(2, vertexBufferObjID);

// VBO for vertex data
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[0]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), vertices, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);

// VBO for colour data
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjID[1]);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), colours, GL_STATIC_DRAW);
glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(1);


glGenBuffers(1, &indexBufferID);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBufferID);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, 9 * sizeof(GLuint), indices, GL_STATIC_DRAW);
}


static void drawAnObject()
{
GLfloat modelView[16];

glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(program);

mtxLoadIdentity(modelView);
glUniformMatrix4fv(modelViewUniformIdx, 1, GL_TRUE, modelView);

glBindVertexArray(vertexArrayObjID); // First VAO
glDrawArrays(GL_TRIANGLES, 0, 3); // draw first object
// glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_SHORT, 0);
glBindVertexArray(0);
}

arekkusu
11-21-2012, 05:39 PM
You've uploaded indices as uints, but are drawing them as ushorts. So this sequence:
0x00000001, 0x00000002, 0x00000003
is interpreted as
0x0000, 0x0001, 0x0000
which is a degenerate triangle, so you see nothing.

You've also uploaded 9 indices when you have only allocated 3, which is a potential crash if your indices happen to be near the end of a malloc page.

devonM
11-21-2012, 05:57 PM
Thank you very much! I can't believe I overlooked that. Changing the indices to GLushort corrected the problem.