OpenGL LWJGL Sprite Sheet

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.

I'm currently trying to use a texture sheet for a sprite. I have a graphic file with each texture 16x16 pixels with 256 sprites squared (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 entire sprite sheet, so u and v glTexCoord2f have less than 1.0f.

Now I need a formula that will calculate u and v any sprite id in the texture.

The raster identifiers of the texture are as follows:

 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 would like to have u and v for any of these identifiers. The last bit is not explained very well, so I will explain it better if you want.

Thank you in advance!

+4
source share
2 answers

The location of the sprite texture in the image is in the 16 x 16 array, so the texture location (if you consider the first one to be 0):

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

Coordinates:

 u0 = row / 16; u1 = (row + 1) / 16; v0 = col / 16; v1 = (col + 1) / 16; 

Then replace 1.0f with u1 or v1, if necessary, and 0.0f with u0 or v0 in calls to glTexCoord2Df.

+5
source

The sprite sheet extends from 0..1 in u and v . If it is 16x16, then the upper left corners are at n/16, m/16 , where n, m are from 0..15. If your sheets are only 16x16, you can simplify your life by dividing 1/16 into a texture matrix:

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

This will allow you to access the sprite at 0,0, 1,0, 2,0, etc. with integers due to scaling in the matrix.

An added benefit of using a texture matrix like this is that your texture coordinates become integers, and now you can use the integer type in your vertex array or VBO to represent the texture coordinates.

+1
source

Source: https://habr.com/ru/post/1333500/


All Articles