[OpenGL] Drawing cube using glDrawElements and glTexCoordPointer

Started by
2 comments, last by Brother Bob 12 years, 11 months ago
Hi!

I would like to draw simple cube using glDrawElements, glTexCoordPointer .

There is part of my code

glBindTexture(GL_TEXTURE_2D, texture[0]);

glEnableClientState( GL_VERTEX_ARRAY ); // Enable Vertex Arrays
glEnableClientState( GL_TEXTURE_COORD_ARRAY ); // Enable Texture Coord Arrays

float vertices[] = { 1.0f, 0.0f, -1.0f, //0 index
1.0f, 0.0f, 1.0f, //1
-1.0f,0.0f, 1.0f, //2
-1.0f, 0.0f,-1.0f, //3
1.0f, 1.0f, -1.0f, //4
1.0f, 1.0f, 1.0f, //5
-1.0f,1.0f, 1.0f, //6
-1.0f, 1.0f, -1.0f, //7
};
short indices[] = { 0, 1, 2, 0, 2, 3,
0, 4, 5, 0, 5, 1,
};
float texture[] = { 1, 0,
1, 1,
0, 1,
0, 0,
//... I repeat these 4 coordinate 2 times
1, 0,
1, 1,
0, 1,
0, 0,};

glVertexPointer( 3, GL_FLOAT, 0, vertices ); // Set The Vertex Pointer To Our Vertex Data
glTexCoordPointer( 2, GL_FLOAT, 0, texture ); // Set The Vertex Pointer To Our TexCoord Data
glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_SHORT, indices);



The vertices and indices are show below:

[attachment=2315:cube_gamedev.png]

I try render bottom and right face of this cube with texture, but only bottom face is textured, as you can see below

[attachment=2316:cube_textire.png]

Why only bottom face is textured ? I gave texture coordinates for 2 faces. Also if I give more textures coordinates it won't work.
Is there another method to draw textured cube using glDrawElements ?
Advertisement
This is a classical example of when you cannot use shared vertices. As soon as you introduce a vertex attribute other than position, the cube is required to have 24 vertices, not 8. The corners of a cube are not shared vertices, because they don't have the same texture coordinates.

For example, the first two triangles are made up of the indices [0, 1, 2, 0, 2, 3], and if you reference the vertex and texture coordinate arrays, that face is fine. The second two triangles are made up of the indices [0, 4, 5, 0, 5, 1], and while the vertex array is referenced correct to make second face of the cube, the resulting texture coordinates are entirely broken.
so there is no way to use glDrawElements ?

I'd like avoid glVertex3f and glTexCoord2f and VBO to make my code a bit compatible with OpenGL ES, so glDrawArray is the only way ?

A flat vertex array that can be drawn with glDrawArrays can also be drawn with glDrawElements if the index array contains consecutive indices from 0 and up. But that's no point, so just use glDrawArrays.

This topic is closed to new replies.

Advertisement