Click here to Skip to main content
15,867,453 members
Articles / Mobile Apps / Android

Texture Atlas Maker

Rate me:
Please Sign up or sign in to vote.
4.94/5 (16 votes)
1 Apr 2012BSD6 min read 141.5K   7K   55  
A utility to create texture atlases for 2D OpenGL games
import java.util.ArrayList;


public class TweekDimensions
{
	private int bestSavings;
	private int bestWidth;
	private int bestHeight;
	private int origWidth;
	private int origHeight;
	public void run(BinPacker binPacker, 
			ArrayList<AtlasImage> listImage)
	{
		bestSavings = 0;
		binPacker.getTexturePiece().trim();
		origWidth = binPacker.getTexturePiece().getWidth();
		origHeight = binPacker.getTexturePiece().getHeight();
		bestWidth = origWidth;
		bestHeight = origHeight;
		tweekWidthHeight(binPacker, listImage, origWidth, origHeight, true);
		binPacker.getTexturePiece().setSize(origWidth, origHeight);
		tweekWidthHeight(binPacker, listImage, origWidth, origHeight, false);
		binPacker.resize(bestWidth, bestHeight, listImage); 
		// tweek the other dimension
		if (origHeight > bestHeight)
			tweekWidthHeight(binPacker, listImage, bestWidth, bestHeight, true);
		else
			tweekWidthHeight(binPacker, listImage, bestWidth, bestHeight, false);
		
		if (bestWidth != binPacker.getTexturePiece().getWidth() ||
			bestHeight != binPacker.getTexturePiece().getHeight())
		{	
			binPacker.resize(bestWidth, bestHeight, listImage); 
			binPacker.pack(listImage);
		}
		assert(listImage.size() == 0);
	}
	
	private void tweekWidthHeight(BinPacker binPacker, 
			ArrayList<AtlasImage> listImage, int width, int height,   
			boolean doWidth)
	{
		int savings;
		savings = 0;
		int prevWidth, prevHeight;
	    do
	    {
	    	prevWidth = width;
	    	prevHeight = height;
	    	// reduce by two pixes to force minimum re-organise
	    	if (doWidth)
	    	{
		    	width = binPacker.getTexturePiece().getWidth()-1;
	    	}
	    	else
	    	{
	    		height = binPacker.getTexturePiece().getHeight()-1;
	    	}
			binPacker.resize(width, height, listImage); 
			binPacker.pack(listImage);
			if (listImage.size() > 0)
			{
	    		break;
			}
			binPacker.getTexturePiece().trim();
	    } while (true);
		savings = origWidth*origHeight-
			binPacker.getTexturePiece().getPixels();
	    if (bestSavings < savings)
	    {
	    	bestSavings = savings;
	    	bestWidth = prevWidth;
	    	bestHeight = prevHeight;
	    }
	}

}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The BSD License


Written By
Software Developer Astronautz
Spain Spain
After working in the software industry for many years, I've started my own games company that specialises in strategy games for mobile platforms.

Comments and Discussions