APIdia Launch Partner
Top Description Inners Fields Constructors Methods
com.badlogic.gdx.tiledmappacker

public Class TiledMapPacker

extends Object
Class Inheritance
Imports
java.awt.Graphics, java.awt.image.BufferedImage, java.io.File, .FilenameFilter, .IOException, java.util.HashMap, .Iterator, .List, .ArrayList, javax.imageio.ImageIO, javax.xml.parsers.DocumentBuilder, .DocumentBuilderFactory, .ParserConfigurationException, javax.xml.transform.Transformer, .TransformerConfigurationException, .TransformerException, .TransformerFactory, javax.xml.transform.dom.DOMSource, javax.xml.transform.stream.StreamResult, com.badlogic.gdx.assets.loaders.FileHandleResolver, com.badlogic.gdx.graphics.g2d.PixmapPacker, .TextureAtlas, com.badlogic.gdx.maps.ImageResolver, .MapLayer, com.badlogic.gdx.maps.tiled.*, com.badlogic.gdx.utils.*, org.w3c.dom.Attr, .Document, .NamedNodeMap, .Node, .NodeList, org.xml.sax.SAXException, com.badlogic.gdx.ApplicationListener, .Gdx, com.badlogic.gdx.assets.loaders.resolvers.AbsoluteFileHandleResolver, com.badlogic.gdx.backends.lwjgl.LwjglApplication, .LwjglApplicationConfiguration, com.badlogic.gdx.files.FileHandle, com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile, .StaticTiledMapTile, com.badlogic.gdx.math.Vector2, com.badlogic.gdx.tools.texturepacker.TexturePacker, .TexturePacker.Settings

Given one or more TMX or TMJ tilemaps, packs all tileset and imagelayer resources used across the maps, or the resources used per map, into a single, or multiple (one per map), TextureAtlas and produces a new TMX/TMJ file to be loaded with an AtlasTiledMapLoader loader. Optionally, it can keep track of unused tiles and omit them from the generated atlas, reducing the resource size. The original TMX or TMJ map file will be parsed by using the TmxMapLoader or TmjMapLoader loader, thus access to a valid OpenGL context is required, that's why an LwjglApplication is created by this preprocessor. The new TMX/TMJ map file will contain a new property, named "atlas", whose value will enable the AtlasTiledMapLoader to correctly read the associated TextureAtlas representing the tileset. The map file will also overwrite the sources of any imagelayer images to a new unique region name prepending 'atlas_imagelayer_' to a newly generated one which represents it's region in the atlas
Authors
David Fraska and others (initial implementation, tell me who you are!), Manuel Bua

Nested and Inner Type Summary

Modifier and TypeClass and Description
private static class
private static class
private static class
private static class
TiledMapPacker.PackerTmxMapLoader

Below we have 2 custom subclasses of the Map Loaders we use within the TiledMapPacker PackerTmxMapLoader and PackerTmjMapLoader.

public static class

Field Summary

Modifier and TypeField and Description
private static String
private FileHandle
private ObjectMap<String, String>
private ObjectMap<String, Array<String>>
public static File
private TiledMap
private TiledMapPacker.PackerTmxMapLoader
public static File
private TexturePacker
public static String
private TiledMapPacker.TiledMapPackerSettings
private static final String
private ObjectMap<String, TiledMapTileSet>
private HashMap<String, IntArray>
private com.badlogic.gdx.maps.tiled.TmjMapLoader.Parameters
private TiledMapPacker.PackerTmjMapLoader
private com.badlogic.gdx.maps.tiled.TmxMapLoader.Parameters
private static long

Constructor Summary

AccessConstructor and Description
public
TiledMapPacker()

Constructs a new preprocessor by using the default packing settings

public
TiledMapPacker(TiledMapPacker.TiledMapPackerSettings settings)

Constructs a new preprocessor by using the specified packing settings

Method Summary

Modifier and TypeMethod and Description
private void
addTile(TiledMapTile tile, int bucketSize)

private String
private static Node
getFirstChildByNameAttrValue(Node node, String childName, String attr, String value)

If the child node or attribute doesn't exist, it is created.

private static Node
getFirstChildNodeByName(Node parent, String child)

If the child node doesn't exist, it is created.

private IntArray

Returns:

a bucket
getUsedIdsBucket
(String tilesetName, int
The size to use to create a new bucket if it doesn't exist, else specify 0 or lower to return null instead
size
)

Returns the usedIds bucket for the given tileset name.

public static void
main(String[]
args[0]: the input directory containing the tmx/tmj files (and tile sets, and imagelayer imaged relative to the path listed in the tmx file). args[1]: The output directory for the tmx/tmj files, should be empty before running. args[2]: The location of the TiledMap Project File. args[2-5] options
args
)

Processes a directory of Tile Maps, compressing each tile set contained in any map once.

private void
private void
packImageLayerImages(FileHandle inputDirHandle)

Traverse the map of generated image names created from generateImageLayerImageNames() in imagesLayersToPack, get image source path and pass image to the PixmapPacker

private void
packSingleImageTileset(TiledMapTileSet set, FileHandle inputDirHandle)

Handles a tileset that uses one large image for all its tiles.

private void
packTilesets(FileHandle inputDirHandle, TexturePacker.Settings texturePackerSettings)

Traverse the specified tilesets, optionally lookup the used ids and pass every tile image to the TexturePacker, optionally ignoring unused tile ids

private static void
private void
processImageLayerNames(Node imagelayerNode)

Here we Process a single <imagelayer> node.

private void
public void
processInputDir(TexturePacker.Settings texturePackerSettings)

You can either run the TiledMapPacker#main(String[]) method or reference this class in your own project and call this method.

public void
processInputDir(TexturePacker.Settings
the Settings used for packing textures (e.g., padding, filtering, etc.)
texturePackerSettings
,
String
the path to the directory containing map files (.tmx or .tmj); must not be null or empty
inputDirPath
,
String
optional path where processed map files and the atlas will be written; if empty or null, defaults to "../output/" relative to input
outputDirPath
,
String
optional path to a Tiled project file, used when maps require loading a custom tiled project file can be left "" or null
prjtFilePath
)

Processes a directory of Tiled .tmx or .tmj map files, optionally including subdirectories, and outputs updated map files and a texture atlas.

private void
processLayerNode(JsonValue layerNode)

Recursively process a tmj layer node

private void
processSingleMap(File mapFile, FileHandle dirHandle, TexturePacker.Settings texturePackerSettings)

private void
processSubdirectories(FileHandle
The directory to look for maps and other directories
currentDir
,
TexturePacker.Settings texturePackerSettings)

Looks for subdirectories inside parentHandle, processes maps in subdirectory, repeat.

private void
processTmjImageLayersRecursively(JsonValue root)

Start processing at the top of the .tmj's "layers" array.

private void
processTmxImageLayersRecursively(Node parent)

Recursively searches for imagelayer nodes anywhere under the given 'parent'.

private String
removeExtensionIfPresent(String path)

Small helper for removing common image file extensions from the end.

private void
private static void
setProperty(Document doc, Node parent, String name, String value)

private void
setProperty(JsonValue root, String name, String value)

private void
private String
private void
writeUpdatedTMJ(FileHandle tmjFileHandle)

private void
writeUpdatedTMX(FileHandle tmxFileHandle)

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

AtlasOutputNameback to summary
private static String AtlasOutputName
currentDirback to summary
private FileHandle currentDir
imageLayerSourceFilesback to summary
private ObjectMap<String, String> imageLayerSourceFiles
imagesLayersToPackback to summary
private ObjectMap<String, Array<String>> imagesLayersToPack
inputDirback to summary
public static File inputDir
mapback to summary
private TiledMap map
mapLoaderback to summary
private TiledMapPacker.PackerTmxMapLoader mapLoader
outputDirback to summary
public static File outputDir
packerback to summary
private TexturePacker packer
projectFilePathback to summary
public static String projectFilePath
settingsback to summary
private TiledMapPacker.TiledMapPackerSettings settings
TilesetsOutputDirback to summary
private static final String TilesetsOutputDir
tilesetsToPackback to summary
private ObjectMap<String, TiledMapTileSet> tilesetsToPack
tilesetUsedIdsback to summary
private HashMap<String, IntArray> tilesetUsedIds
tmjLoaderParamsback to summary
private com.badlogic.gdx.maps.tiled.TmjMapLoader.Parameters tmjLoaderParams
tmjMapLoaderback to summary
private TiledMapPacker.PackerTmjMapLoader tmjMapLoader
tmxLoaderParamsback to summary
private com.badlogic.gdx.maps.tiled.TmxMapLoader.Parameters tmxLoaderParams
uniqueIdCounterback to summary
private static long uniqueIdCounter

Constructor Detail

TiledMapPackerback to summary
public TiledMapPacker()

Constructs a new preprocessor by using the default packing settings

TiledMapPackerback to summary
public TiledMapPacker(TiledMapPacker.TiledMapPackerSettings settings)

Constructs a new preprocessor by using the specified packing settings

Method Detail

addTileback to summary
private void addTile(TiledMapTile tile, int bucketSize)
generateUniqueImageNameback to summary
private String generateUniqueImageName(String imageSource)
getFirstChildByNameAttrValueback to summary
private static Node getFirstChildByNameAttrValue(Node node, String childName, String attr, String value)

If the child node or attribute doesn't exist, it is created. Usage example: Node property = getFirstChildByAttrValue(properties, "property", "name");

getFirstChildNodeByNameback to summary
private static Node getFirstChildNodeByName(Node parent, String child)

If the child node doesn't exist, it is created.

getUsedIdsBucketback to summary
private IntArray getUsedIdsBucket(String tilesetName, int size)

Returns the usedIds bucket for the given tileset name. If it doesn't exist one will be created with the specified size if its > 0, else null will be returned.

Parameters
size:int

The size to use to create a new bucket if it doesn't exist, else specify 0 or lower to return null instead

Returns:IntArray

a bucket

mainback to summary
public static void main(String[] args)

Processes a directory of Tile Maps, compressing each tile set contained in any map once.

Parameters
args:String[]

args[0]: the input directory containing the tmx/tmj files (and tile sets, and imagelayer imaged relative to the path listed in the tmx file). args[1]: The output directory for the tmx/tmj files, should be empty before running. args[2]: The location of the TiledMap Project File. args[2-5] options

packCollectionOfImagesTilesetback to summary
private void packCollectionOfImagesTileset(TiledMapTileSet set, FileHandle inputDirHandle) throws IOException
packImageLayerImagesback to summary
private void packImageLayerImages(FileHandle inputDirHandle) throws IOException

Traverse the map of generated image names created from generateImageLayerImageNames() in imagesLayersToPack, get image source path and pass image to the PixmapPacker

packSingleImageTilesetback to summary
private void packSingleImageTileset(TiledMapTileSet set, FileHandle inputDirHandle) throws IOException

Handles a tileset that uses one large image for all its tiles.

packTilesetsback to summary
private void packTilesets(FileHandle inputDirHandle, TexturePacker.Settings texturePackerSettings) throws IOException

Traverse the specified tilesets, optionally lookup the used ids and pass every tile image to the TexturePacker, optionally ignoring unused tile ids

printUsageback to summary
private static void printUsage()
processImageLayerNamesback to summary
private void processImageLayerNames(Node imagelayerNode)

Here we Process a single node. We needed a way to handle images across nested folders as well as matching names relative to the .tmx file. And keeping the changes to the AtlasTmxMapLoader minimal. With that goal in mind we get each image's source attribute, generate a unique name for it, appended that name to this string 'atlas_imagelayer_' and later use it as the atlas id. The AtlasTmxMapLoader's AtlasResolver .getImage() method will check for 'atlas_imagelayer_' to use imagelayer specific logic.

processImageLayerNamesback to summary
private void processImageLayerNames(JsonValue imageLayer)
processInputDirback to summary
public void processInputDir(TexturePacker.Settings texturePackerSettings) throws IOException

You can either run the TiledMapPacker#main(String[]) method or reference this class in your own project and call this method. If working with libGDX sources, you can also run this file to create a run configuration then export it as a Runnable Jar. To run from a nightly build:

Linux / OS X
java -cp gdx.jar:gdx-natives.jar:gdx-backend-lwjgl.jar:gdx-backend-lwjgl-natives.jar:gdx-tiled-preprocessor.jar:extensions/gdx-tools/gdx-tools.jar com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [projectFilePath] [--strip-unused] [--combine-tilesets] [-v]

Windows
java -cp gdx.jar;gdx-natives.jar;gdx-backend-lwjgl.jar;gdx-backend-lwjgl-natives.jar;gdx-tiled-preprocessor.jar;extensions/gdx-tools/gdx-tools.jar com.badlogic.gdx.tiledmappacker.TiledMapPacker inputDir [outputDir] [projectFilePath] [--strip-unused] [--combine-tilesets] [-v]

Keep in mind that this preprocessor will need to load the maps by using the TmxMapLoader or TmjMapLoader loader and this in turn will need a valid OpenGL context to work. Process a directory containing TMX or TMJ map files representing Tiled maps and produce multiple, or a single, TextureAtlas as well as new processed TMX/TMJ map files, correctly referencing the generated TextureAtlas by using the "atlas" custom map property and newly generated image source region names if using imagelayers in your map

processInputDirback to summary
public void processInputDir(TexturePacker.Settings texturePackerSettings, String inputDirPath, String outputDirPath, String prjtFilePath) throws IOException

Processes a directory of Tiled .tmx or .tmj map files, optionally including subdirectories, and outputs updated map files and a texture atlas. This method is intended for usage from external callers such as build scripts or other Java classes. Keep in mind that this preprocessor will need to load the maps by using the TmxMapLoader or TmjMapLoader loader and this in turn will need a valid OpenGL context to work.

Parameters
texturePackerSettings:TexturePacker.Settings

the Settings used for packing textures (e.g., padding, filtering, etc.)

inputDirPath:String

the path to the directory containing map files (.tmx or .tmj); must not be null or empty

outputDirPath:String

optional path where processed map files and the atlas will be written; if empty or null, defaults to "../output/" relative to input

prjtFilePath:String

optional path to a Tiled project file, used when maps require loading a custom tiled project file can be left "" or null

Exceptions
IOException:
if a file cannot be read or written
IllegalArgumentException:
if inputDirPath is null or blank
processLayerNodeback to summary
private void processLayerNode(JsonValue layerNode)

Recursively process a tmj layer node

processSingleMapback to summary
private void processSingleMap(File mapFile, FileHandle dirHandle, TexturePacker.Settings texturePackerSettings) throws IOException
processSubdirectoriesback to summary
private void processSubdirectories(FileHandle currentDir, TexturePacker.Settings texturePackerSettings) throws IOException

Looks for subdirectories inside parentHandle, processes maps in subdirectory, repeat.

Parameters
currentDir:FileHandle

The directory to look for maps and other directories

processTmjImageLayersRecursivelyback to summary
private void processTmjImageLayersRecursively(JsonValue root)

Start processing at the top of the .tmj's "layers" array.

processTmxImageLayersRecursivelyback to summary
private void processTmxImageLayersRecursively(Node parent)

Recursively searches for imagelayer nodes anywhere under the given 'parent'. If it finds any imagelayers, it updates the source attribute to a unique name, and tracks that in imagesLayersToPack/imageLayerSourceFiles.

removeExtensionIfPresentback to summary
private String removeExtensionIfPresent(String path)

Small helper for removing common image file extensions from the end.

savePackerback to summary
private void savePacker() throws IOException
setPropertyback to summary
private static void setProperty(Document doc, Node parent, String name, String value)
setPropertyback to summary
private void setProperty(JsonValue root, String name, String value)
stripUnusedTilesback to summary
private void stripUnusedTiles()
tilesetNameFromTileIdback to summary
private String tilesetNameFromTileId(TiledMap map, int tileid)
writeUpdatedTMJback to summary
private void writeUpdatedTMJ(FileHandle tmjFileHandle) throws IOException
writeUpdatedTMXback to summary
private void writeUpdatedTMX(FileHandle tmxFileHandle) throws IOException
com.badlogic.gdx.tiledmappacker back to summary

private Class TiledMapPacker.DirFilter

extends Object
implements FilenameFilter
Class Inheritance
All Implemented Interfaces
java.io.FilenameFilter

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public boolean
accept(File f, String s)

Implements java.io.FilenameFilter.accept.

Tests if a specified file should be included in a file list.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

DirFilterback to summary
public DirFilter()

Method Detail

acceptback to summary
public boolean accept(File f, String s)

Implements java.io.FilenameFilter.accept.

Doc from java.io.FilenameFilter.accept.

Tests if a specified file should be included in a file list.

Annotations
@Override
com.badlogic.gdx.tiledmappacker back to summary

private Class TiledMapPacker.MapFileFilter

extends Object
implements FilenameFilter
Class Inheritance
All Implemented Interfaces
java.io.FilenameFilter

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
public boolean
accept(File dir, String name)

Implements java.io.FilenameFilter.accept.

Tests if a specified file should be included in a file list.

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Constructor Detail

MapFileFilterback to summary
public MapFileFilter()

Method Detail

acceptback to summary
public boolean accept(File dir, String name)

Implements java.io.FilenameFilter.accept.

Doc from java.io.FilenameFilter.accept.

Tests if a specified file should be included in a file list.

Annotations
@Override
com.badlogic.gdx.tiledmappacker back to summary

private Class TiledMapPacker.PackerTmjMapLoader

extends TmjMapLoader
Class Inheritance

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
addStaticTiles(FileHandle tmjFile, ImageResolver imageResolver, TiledMapTileSet tileSet, JsonValue element, JsonValue tiles, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image)

Overrides com.badlogic.gdx.maps.tiled.TmjMapLoader.addStaticTiles.

protected AnimatedTiledMapTile
Inherited from com.badlogic.gdx.maps.tiled.TmjMapLoader:
getDependencyAssetDescriptorsgetDependencyFileHandlesgetTileSetDependencyFileHandlegetTileSetDependencyFileHandleloadloadloadAsyncloadSyncloadTilesetloadTileset

Constructor Detail

PackerTmjMapLoaderback to summary
public PackerTmjMapLoader(FileHandleResolver resolver)

Method Detail

addStaticTilesback to summary
protected void addStaticTiles(FileHandle tmjFile, ImageResolver imageResolver, TiledMapTileSet tileSet, JsonValue element, JsonValue tiles, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image)

Overrides com.badlogic.gdx.maps.tiled.TmjMapLoader.addStaticTiles.

Annotations
@Override
createAnimatedTileback to summary
protected AnimatedTiledMapTile createAnimatedTile(TiledMapTileSet tileSet, TiledMapTile originalTile, JsonValue tileDefinition, int firstgid)

Overrides com.badlogic.gdx.maps.tiled.BaseTmjMapLoader.createAnimatedTile.

Annotations
@Override
com.badlogic.gdx.tiledmappacker back to summary

private Class TiledMapPacker.PackerTmxMapLoader

extends TmxMapLoader
Class Inheritance

Below we have 2 custom subclasses of the Map Loaders we use within the TiledMapPacker PackerTmxMapLoader and PackerTmjMapLoader. The only reason these are here is to add support for packing Maps which use a Collection of Images tileset. This was done so we would not be forced to make Core code changes just to appease the TiledMapPacker. We just needed a way to pass along the image source into a tile's property so we could use this to find and load the textures for packing. When loading a Collection of Images that data is not stored anywhere. The basic logic is as follows: Let super.addStaticTiles() run like normal. Within that method addStaticTiledMapTile() is eventually called. This is where the new StaticTiledMapTile's are created and then put into the tileset collection. We can then get a tile from tileSet based on the id and add the property directly to that tile.

Constructor Summary

AccessConstructor and Description
public

Method Summary

Modifier and TypeMethod and Description
protected void
addStaticTiles(FileHandle tmxFile, ImageResolver imageResolver, TiledMapTileSet tileSet, XmlReader.Element element, Array<XmlReader.Element> tileElements, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image)

Overrides com.badlogic.gdx.maps.tiled.TmxMapLoader.addStaticTiles.

protected AnimatedTiledMapTile
Inherited from com.badlogic.gdx.maps.tiled.TmxMapLoader:
getDependencyAssetDescriptorsgetDependencyFileHandlesgetTileSetDependencyFileHandlegetTileSetDependencyFileHandleloadloadloadAsyncloadSyncloadTilesetloadTileset

Constructor Detail

PackerTmxMapLoaderback to summary
public PackerTmxMapLoader(FileHandleResolver resolver)

Method Detail

addStaticTilesback to summary
protected void addStaticTiles(FileHandle tmxFile, ImageResolver imageResolver, TiledMapTileSet tileSet, XmlReader.Element element, Array<XmlReader.Element> tileElements, String name, int firstgid, int tilewidth, int tileheight, int spacing, int margin, int offsetX, int offsetY, String imageSource, int imageWidth, int imageHeight, FileHandle image)

Overrides com.badlogic.gdx.maps.tiled.TmxMapLoader.addStaticTiles.

Annotations
@Override
createAnimatedTileback to summary
protected AnimatedTiledMapTile createAnimatedTile(TiledMapTileSet tileSet, TiledMapTile originalTile, XmlReader.Element tileElement, int firstgid)

Overrides com.badlogic.gdx.maps.tiled.BaseTmxMapLoader.createAnimatedTile.

Annotations
@Override
com.badlogic.gdx.tiledmappacker back to summary

public Class TiledMapPacker.TiledMapPackerSettings

extends Object
Class Inheritance
  • java.lang.Object
  • com.badlogic.gdx.tiledmappacker.TiledMapPacker.TiledMapPackerSettings

Field Summary

Modifier and TypeField and Description
public String
public boolean
public boolean
public boolean
public String
public boolean

Constructor Summary

AccessConstructor and Description
public

Method Summary

Inherited from java.lang.Object:
cloneequalsfinalizegetClasshashCodenotifynotifyAlltoStringwaitwaitwait

Field Detail

atlasOutputNameback to summary
public String atlasOutputName
combineTilesetsback to summary
public boolean combineTilesets
ignoreCollectionOfImagesback to summary
public boolean ignoreCollectionOfImages
stripUnusedTilesback to summary
public boolean stripUnusedTiles
tilesetOutputDirectoryback to summary
public String tilesetOutputDirectory
verboseback to summary
public boolean verbose

Constructor Detail

TiledMapPackerSettingsback to summary
public TiledMapPackerSettings()