Reputation: 333
I'm trying to draw a rectangle and apply a texture unto it. The code was copied from a book I'm reading, I just passed to C++(from Java), here it is:
void draw(){
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(2, GL_FLOAT, 4, vertices.data());//vertexSize is 4
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 2, vertices.data() + 2);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, indices.data());
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
the vertices is a std::vector
of size 16
and the following values:
[-0.25,-0.25,0.0,0.25,0.25,-0.25,0.25,0.25,0.25,0.25,0.25,0.0,-0.25,0.25,0.0,0.0]
each 4 floats specifies a vertex coord
and a texture coord
,
and the indices is a std::vector
of size 6
with the following values:
[0,1,2,2,3,0]
which specifies two triangles(with textures) in the vertices array.
This two arrays are always set before calling draw.
The problem is that the rendered object is not right, instead of a rectangle I have a trapezium rotated. The vectors seems correct, as I'm new to OpenGL, I've no idea of what is going wrong in this code.
Thank you for your attention.
---EDITED--- The opengl matrices are set right before enter the application loop:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glClearColor(0.0, 1.0, 0.0, 1.0);
glEnable(GL_TEXTURE_2D);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
/*application loop, no more matrices use*/
Upvotes: 0
Views: 337
Reputation: 474436
glVertexPointer(2, GL_FLOAT, 4, vertices.data());//vertexSize is 4
Yes, there are 4 floats per-vertex. But that's not what the fourth parameter is. It's the number of bytes from one position to the next. That's not 4; it's 4 * sizeof(GLfloat)
.
Also:
glTexCoordPointer(2, GL_FLOAT, 2, vertices.data() + 2);
The second 2 here should also be 4 * sizeof(GLfloat)
. The byte stride for your array is the same for positions and texture coordinates.
Upvotes: 4