Question

I am new to OpenGL and am currently trying to render a cube with four faces, each with a different texture.

As you all know, having a separate texture for each face type is very memory intensive and makes the application slow.

At the moment I am trying to use a texture sheet for the sprite. I have the graphic file with each texture 16x16 pixels with 256 sprites arranged in a square (16x16).

I know that

GL11.glTexCoord2f(1.0f, 0.0f);
GL11.glVertex3f(1.0f, 1.0f,  1.0f);
GL11.glTexCoord2f(0.0f, 0.0f);
GL11.glVertex3f(0.0f, 1.0f, 1.0f);
GL11.glTexCoord2f(0.0f, 1.0f);
GL11.glVertex3f(0.0f, 0.0f, 1.0f);
GL11.glTexCoord2f(1.0f, 1.0f);
GL11.glVertex3f(1.0f, 0.0f, 1.0f);

gives me a rectangle with the whole sprite sheet so u and v of glTexCoord2f have to be less than 1.0f.

What I need now is a formula which will calculate the u and v of any sprite id in the texture.

The IDs go as following in the texture bitmap:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
17 18 16 20 21 22 23 24...

and I'd like to have a u and v for any of these IDs. The last bit isn't explained very well, so I'll explain it better if you would like.

Thank you in advance!

Was it helpful?

Solution

The locations of the sprites' texture in the image are in a 16 x 16 array, so the location of a texture (if you count the first one as 0) are:

row = texNo / 16;
col = texNo % 16;

The coordinates are then:

u0 = row / 16;
u1 = (row + 1) / 16;

v0 = col / 16;
v1 = (col + 1) / 16; 

Then replace 1.0f with u1 or v1 as appropriate and 0.0f with u0 or v0 in the glTexCoord2Df calls.

OTHER TIPS

The sprite sheet extends from 0..1 in u and v. If it's 16x16 then the upper left corners are at n/16, m/16 where n, m range from 0..15. If your sheets are all 16x16 you can simplify your life by factoring out the 1/16th into the texture matrix:

        glMatrixMode(GL_TEXTURE)
        glLoadIdentity()
        glScalef(1f/16f, 1f/16f, 1f)

That would let you address a sprite at 0,0, 1,0, 2,0, etc. with integers because of the scaling in the matrix.

A further advantage of using the texture matrix like this is that your texture coordinates become integers and now you can use an integer type in your vertex array or VBO to represent the texture coordinates.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top