LibGdx TextureAtlas (non .pack file)
Okay, I hit a block when I was starting to think about writing a quick networked multiplayer shoot em up game in LibGdx.
LibGdx texture atlas’s are very handy things because you can store a load of smaller images in one image. This also optimises the GPU draw routines because it doesn’t have to keep swapping textures for each sprite drawn.
I found pre-made free to use sprites from Kenney.nl, below is a section of what they look like:
Unfortunately though, LibGdx uses .pack files for it’s texture atlas’s and this one come with one that looks like this:
<TextureAtlas imagePath="sprites.png"> <SubTexture name="spaceAstronauts_001.png" x="998" y="847" width="34" height="44"/> <SubTexture name="spaceAstronauts_002.png" x="919" y="142" width="37" height="44"/> <SubTexture name="spaceAstronauts_003.png" x="824" y="0" width="50" height="44"/> ... </TextureAtlas>
Which is completely different to a .pack file.
So without further ado I decided to test out an xml parser to retrieve all the sub-regions from the xml file.
Test code as follows:
package com.wlgfx.xml.atlas; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class XmlTextureAtlas { private static final String atlas_src_xml = "/home/wlgfx/Pictures/art-assets/kenny-spaceshooter/Spritesheet/spaceShooter2_spritesheet.xml"; public static void main(String[] args) { File xml_file = new File(atlas_src_xml); try { DocumentBuilderFactory db_factory = DocumentBuilderFactory.newInstance(); DocumentBuilder d_builder; d_builder = db_factory.newDocumentBuilder(); Document doc = d_builder.parse(xml_file); doc.getDocumentElement().normalize(); System.out.println("Root element: " + doc.getDocumentElement().getNodeName()); NodeList list = doc.getElementsByTagName("SubTexture"); System.out.println(list.getLength()); for (int c = 0; c < list.getLength(); c++) { Element elem = (Element)list.item(c); String name = elem.getAttribute("name"); String x = elem.getAttribute("x"); String y = elem.getAttribute("y"); String w = elem.getAttribute("width"); String h = elem.getAttribute("height"); System.out.println(name+" ("+x+","+y+")("+w+","+h+")"); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
So, armed with this now, all thanks mainly to working with GWT, I can quickly move on to creating my own class to generate the texture atlas in LibGdx.
Leave a Reply