Pointer based on size?

Started by
2 comments, last by CirdanValen 13 years, 5 months ago
In my game, I have a Vertex struct:

struct Vertex {	float x, y; // Vert point	float tx, ty; // Texture point};


I create an array of these to represent a quad:

Vertex verts[] = {{0,0,0.5f,0},  {32,0,1,0}, {32,32,1,0.5f},  {0,32,0.5f,0.5f}};


Then to draw the the square using VBOs in openGL they require these two method calls:

	glVertexPointer(2, GL_FLOAT, sizeof(Vertex), 0);	glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (char*)8);


My question is what is (char*)8 doing exactly? I know that in my struct, each float is 4 bytes. So to point the gpu to the location of each texture coordinate I have to tell it to look 8 bytes into the buffer to get the texture coordinates. That is basically what is happening right? Is it creating a pointer to 8 bytes so it knows how far to jump?
Advertisement
When not using VBO's, glVertexPointer and glTexCoordPointer do indeed take a regular void pointer. When using VBO's, this must become an offset. To be able to use the same function, without changing the function signature, it should be cast to a pointer. It doesn't need to be (char *), but can be any pointer type, as the function accepts void pointers.

So, it's not creating a pointer, it is casting an int to a pointer.
Kippesoep
You are correct. Ignoring char* for the moment, the value 8 represents the offset pointer to the first [tx, ty] pair in your vertex array. Basically you will have to skip over the first [x, y] pair, totalling 8 bytes, to specify the starting location of your texture coordinates.

Now the char* bit is just a type cast to a pointer type, because glTexCoordPointer can be used both for VBO rendering (via glDrawElements) and for rendering primitives directly from an external memory location (via glDrawArrays).

If you are using a C compiler, you might want to use this macro to specify offsets:

glVertexPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, x)));glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), (void*)offsetof(Vertex, tx));


Hard coding offsets like you did is not always a good idea. The reason why you want to use the above method, is because there could be a remote possibility that the struct memory alignment will include some padding after the "float x, y;" declaration. Unlikely, but it might.

Another reason, what happens if you shuffle the vertex and texture coords around? Suddenly you have incorrect hard coded offsets everywhere.
Latest project: Sideways Racing on the iPad
Ah, awesome. Thanks for the explanation!

This topic is closed to new replies.

Advertisement