Global Texture

So I’ve got a large image of several sprites. Instead of loading that whole texture in every single class that uses a sprite from the image, I’d like to load it once at the beginning of my program, and have it accessible by all classes. How might I go about doing this? (I’m using the slick-util library for textures.)

Here are two common/easy ways. One would be to rely on static getters or singleton instances. You can extend this however you see fit; e.g. storing your textures by a String identifier in a hash map.

MyEntity {
    Texture texture;

    public MyEntity() {
        //gets the already-loaded texture
        this.texture = MyResources.getInstance().getMyTexture();
    }
}

Another common solution is to pass the single texture to the entity when you create it:

MyEntity {
    Texture texture;

    public MyEntity(Texture texture) {
        this.texture = texture;
    }
}

To draw a “sub image” of a texture (i.e. render a particular sprite in a sheet), you need to define your texcoords properly. With slick-util, you might define an Image2D/Sprite class that holds the normalized texture offsets and width/height that will be passed to glTexCoord2f:

	public Image2D(Texture texture) {
		this.texture = texture;
		this.normalizedWidth = texture.getWidth();
		this.normalizedHeight = texture.getHeight();
		this.width = texture.getImageWidth();
		this.height = texture.getImageHeight();
		this.centerX = width / 2f;
		this.centerY = height / 2f;
	}

	public Image2D getSubImage(float x, float y, float width, float height) {
		float tx = ( x / this.width * normalizedWidth ) + textureOffsetX;
		float ty = ( y / this.height * normalizedHeight ) + textureOffsetY;
		float tw = width / this.width * normalizedWidth;
		float th = height / this.height * normalizedHeight;
		
		Image2D img = copy();
		img.textureOffsetX = tx;
		img.textureOffsetY = ty;
		img.width = width;
		img.height = height;
		img.normalizedWidth = tw;
		img.normalizedHeight = th;
		img.centerX = width / 2f;
		img.centerY = height / 2f;
		return img;
	}

I already knew how to divide the texture, I just needed to know how to pass it between classes. Anyways, you answered my question. Much appreciated!

It might heresy for some but just slap those on public static fields on some place.
Work everytime without any effort.

That’s what I tried initially. I can’t remember why it didn’t work, and I’m too tired to try it again (It’s 1:00 am here.) I’ll try it when I wake up, and let you know how it goes. :slight_smile: Thanks!