I am using LWJGL and Slick-util to make a game. I made a helper class TextureAtlas, which helps me draw parts of image (to avoid unnecessary binding).
I managed to create it the following way:
public class TextureAtlas {
private Texture tex;
public TextureAtlas(String fileName) {
try {
tex = TextureLoader.getTexture("PNG",
ResourceLoader.getResourceAsStream(fileName));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Added texture \"" + fileName + "\" with id: "
+ tex.getTextureID());
}
public void bind() {
tex.bind();
}
public void draw(int x, int y, int width, int height, float xp, float yp,
boolean flipHorz, boolean flipVert) {
float spriteX = (float) x / (float) tex.getTextureWidth();
float spriteY = (float) y / (float) tex.getTextureHeight();
float spriteWidth = (float) width / (float) tex.getTextureWidth();
float spriteHeight = (float) height / (float) tex.getTextureHeight();
float spriteX2 = spriteX + spriteWidth;
float spriteY2 = spriteY + spriteHeight;
if (flipHorz) {
float tmp = spriteX;
spriteX = spriteX2;
spriteX2 = tmp;
}
if (flipVert) {
float tmp = spriteY;
spriteY = spriteY2;
spriteY2 = tmp;
}
glBegin(GL_QUADS);
glTexCoord2f(spriteX, spriteY);
glVertex2f(xp, yp);
glTexCoord2f(spriteX2, spriteY);
glVertex2f(xp + (float) width, yp);
glTexCoord2f(spriteX2, spriteY2);
glVertex2f(xp + (float) width, yp + (float) height);
glTexCoord2f(spriteX, spriteY2);
glVertex2f(xp, yp + (float) height);
glEnd();
}
}
And then when drawing:
TextureAtlas atlas = new TextureAtlas("res/atlas.png");
atlas.bind();
// in game loop:
atlas.draw(0, 0, 16, 16, 0.0f, 0.0f, true, false); // flips horizontal
It works and there are no performance drops, but I still think it's not good. I mean, two if-s and six temporary variables for one sprite! And I plan on having lots of sprites in my game. Is there a better way to do this? By shaders or something?
Thanks
Mateja