Example usage for com.badlogic.gdx.maps.tiled TiledMap getTileSets

List of usage examples for com.badlogic.gdx.maps.tiled TiledMap getTileSets

Introduction

In this page you can find the example usage for com.badlogic.gdx.maps.tiled TiledMap getTileSets.

Prototype

public TiledMapTileSets getTileSets() 

Source Link

Usage

From source file:ca.hiphiparray.amazingmaze.MapFactory.java

License:Open Source License

/**
 * Return a map generated with the {@link MapFactory}'s parameters.
 *
 * @return a tiled map./*from   w  w w.  j av a2  s. c  o  m*/
 */
public TiledMap generateMap() {
    TiledMap map = new TiledMap();
    map.getTileSets().addTileSet(assets.tiles);

    TiledMapTileLayer backgroundLayer = new TiledMapTileLayer(width, height, MazeScreen.TILE_SIZE,
            MazeScreen.TILE_SIZE);
    backgroundLayer.setName(BACKGROUND_LAYER);
    for (int c = 0; c < backgroundLayer.getWidth(); c++) {
        for (int r = 0; r < backgroundLayer.getHeight(); r++) {
            Cell cell = new Cell();
            cell.setTile(assets.tiles.getTile(TileIDs.computeID(TileIDs.BACKGROUND)));
            backgroundLayer.setCell(c, r, cell);
        }
    }
    map.getLayers().add(backgroundLayer);

    final int gateSpace = 2;
    final int extraRoom = 3;
    List<Integer> splits = generateWireLocations();

    TiledMapTileLayer objectLayer = new TiledMapTileLayer(width, height, MazeScreen.TILE_SIZE,
            MazeScreen.TILE_SIZE);
    objectLayer.setName(OBJECT_LAYER);
    TiledMapTileLayer wireLayer = new TiledMapTileLayer(width, height, MazeScreen.TILE_SIZE,
            MazeScreen.TILE_SIZE);
    wireLayer.setName(WIRE_LAYER);
    for (int col : splits) { // Place the middle barriers and the unknown wires.
        boolean upperOutput = random.nextBoolean();
        Circuit upperGate = new Circuit(upperOutput, random);
        Circuit lowerGate = new Circuit(!upperOutput, random);
        Point highLocation = new Point(col, height - gateSpace);
        Point lowLocation = new Point(col, gateSpace - 1);

        if (Circuit.evaluateGate(upperGate.getGate(), upperGate.isInputA(), upperGate.isInputB())) {
            gateOn.add(upperGate);
        } else {
            gateOn.add(lowerGate);
        }

        placeUpperCircuit(objectLayer, upperGate, highLocation);
        placeLowerCircuit(objectLayer, lowerGate, lowLocation);
        int barrierLoc = randomInt(gateSpace + extraRoom, height - (gateSpace + extraRoom));
        Cell cell = new Cell();
        cell.setTile(assets.tiles.getTile(TileIDs.computeID(TileIDs.BARRIER)));
        objectLayer.setCell(col, barrierLoc, cell);
        for (int r = barrierLoc - 1; r >= gateSpace; r--) { // Place the lower wires.
            WireCell wire = new WireCell(!upperOutput);
            wire.setTile(assets.tiles
                    .getTile(TileIDs.computeID(TileIDs.WIRE_RANGE, TileIDs.VERTICAL, TileIDs.UNKNOWN)));
            wireLayer.setCell(col, r, wire);
        }
        for (int r = barrierLoc + 1; r < height - gateSpace; r++) { // Place the upper wires.
            WireCell wire = new WireCell(upperOutput);
            wire.setTile(assets.tiles
                    .getTile(TileIDs.computeID(TileIDs.WIRE_RANGE, TileIDs.VERTICAL, TileIDs.UNKNOWN)));
            wireLayer.setCell(col, r, wire);
        }
    }
    for (int c = 0; c < width; c++) {
        if (!splits.contains(c)) {
            Cell cell = new Cell();
            cell.setTile(assets.tiles.getTile(TileIDs.computeID(TileIDs.BARRIER)));
            objectLayer.setCell(c, gateSpace, cell);
            cell = new Cell();
            cell.setTile(assets.tiles.getTile(TileIDs.computeID(TileIDs.BARRIER)));
            objectLayer.setCell(c, height - gateSpace - 1, cell);
        }
    }

    map.getLayers().add(objectLayer);
    map.getLayers().add(wireLayer);

    TiledMapTileLayer powerUpLayer = new TiledMapTileLayer(width, height, MazeScreen.TILE_SIZE,
            MazeScreen.TILE_SIZE);
    powerUpLayer.setName(ITEM_LAYER);
    for (int c = 1; c < width; c++) {
        if (!splits.contains(c)) {
            if (random.nextDouble() <= 0.25) {
                placeFish(powerUpLayer, c, gateSpace);
                c++;
            } else if (random.nextDouble() <= 0.1) {
                placeCheese(powerUpLayer, c, gateSpace);
                c++;
            }
        }
    }
    map.getLayers().add(powerUpLayer);

    return map;
}

From source file:com.betmansmall.game.gameLogic.mapLoader.MapLoader.java

License:Apache License

/** Loads the specified tileset data, adding it to the collection of the specified map, given the XML element, the tmxFile and
 * an {@link ImageResolver} used to retrieve the tileset Textures.
 *
 * <p>/*from   w w w.ja  va2s.c  o  m*/
 * Default tileset's property keys that are loaded by default are:
 * </p>
 *
 * <ul>
 * <li><em>firstgid</em>, (int, defaults to 1) the first valid global id used for tile numbering</li>
 * <li><em>imagesource</em>, (String, defaults to empty string) the tileset source image filename</li>
 * <li><em>imagewidth</em>, (int, defaults to 0) the tileset source image width</li>
 * <li><em>imageheight</em>, (int, defaults to 0) the tileset source image height</li>
 * <li><em>tilewidth</em>, (int, defaults to 0) the tile width</li>
 * <li><em>tileheight</em>, (int, defaults to 0) the tile height</li>
 * <li><em>margin</em>, (int, defaults to 0) the tileset margin</li>
 * <li><em>spacing</em>, (int, defaults to 0) the tileset spacing</li>
 * </ul>
 *
 * <p>
 * The values are extracted from the specified Tmx file, if a value can't be found then the default is used.
 * </p>
 * @param map the Map whose tilesets collection will be populated
 * @param element the XML element identifying the tileset to load
 * @param tmxFile the Filehandle of the tmx file
 * @param imageResolver the {@link ImageResolver} */
protected void loadTileSet(TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) {
    if (element.getName().equals("tileset")) {
        String name = element.get("name", null);
        int firstgid = element.getIntAttribute("firstgid", 1);
        int tilewidth = element.getIntAttribute("tilewidth", 0);
        int tileheight = element.getIntAttribute("tileheight", 0);
        int spacing = element.getIntAttribute("spacing", 0);
        int margin = element.getIntAttribute("margin", 0);
        String source = element.getAttribute("source", null);

        int offsetX = 0;
        int offsetY = 0;

        String imageSource = "";
        int imageWidth = 0, imageHeight = 0;

        FileHandle image = null;
        if (source != null) {
            FileHandle tsx = getRelativeFileHandle(tmxFile, source);
            try {
                element = xml.parse(tsx);
                name = element.get("name", null);
                tilewidth = element.getIntAttribute("tilewidth", 0);
                tileheight = element.getIntAttribute("tileheight", 0);
                spacing = element.getIntAttribute("spacing", 0);
                margin = element.getIntAttribute("margin", 0);
                Element offset = element.getChildByName("tileoffset");
                if (offset != null) {
                    offsetX = offset.getIntAttribute("x", 0);
                    offsetY = offset.getIntAttribute("y", 0);
                }
                Element imageElement = element.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandle(tsx, imageSource);
                }
            } catch (IOException e) {
                throw new GdxRuntimeException("Error parsing external tileset.");
            }
        } else {
            Element offset = element.getChildByName("tileoffset");
            if (offset != null) {
                offsetX = offset.getIntAttribute("x", 0);
                offsetY = offset.getIntAttribute("y", 0);
            }
            Element imageElement = element.getChildByName("image");
            if (imageElement != null) {
                imageSource = imageElement.getAttribute("source");
                imageWidth = imageElement.getIntAttribute("width", 0);
                imageHeight = imageElement.getIntAttribute("height", 0);
                image = getRelativeFileHandle(tmxFile, imageSource);
            }
        }

        TiledMapTileSet tileset = new TiledMapTileSet();
        tileset.setName(name);
        tileset.getProperties().put("firstgid", firstgid);
        if (image != null) {
            TextureRegion texture = imageResolver.getImage(image.path());

            MapProperties props = tileset.getProperties();
            props.put("imagesource", imageSource);
            props.put("imagewidth", imageWidth);
            props.put("imageheight", imageHeight);
            props.put("tilewidth", tilewidth);
            props.put("tileheight", tileheight);
            props.put("margin", margin);
            props.put("spacing", spacing);

            int stopWidth = texture.getRegionWidth() - tilewidth;
            int stopHeight = texture.getRegionHeight() - tileheight;

            int id = firstgid;

            for (int y = margin; y <= stopHeight; y += tileheight + spacing) {
                for (int x = margin; x <= stopWidth; x += tilewidth + spacing) {
                    TextureRegion tileRegion = new TextureRegion(texture, x, y, tilewidth, tileheight);
                    TiledMapTile tile = new StaticTiledMapTile(tileRegion);
                    tile.setId(id);
                    tile.setOffsetX(offsetX);
                    tile.setOffsetY(flipY ? -offsetY : offsetY);
                    tileset.putTile(id++, tile);
                }
            }
        } else {
            Array<Element> tileElements = element.getChildrenByName("tile");
            for (Element tileElement : tileElements) {
                Element imageElement = tileElement.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandle(tmxFile, imageSource);
                }
                TextureRegion texture = imageResolver.getImage(image.path());
                TiledMapTile tile = new StaticTiledMapTile(texture);
                tile.setId(firstgid + tileElement.getIntAttribute("id"));
                tile.setOffsetX(offsetX);
                tile.setOffsetY(flipY ? -offsetY : offsetY);
                tileset.putTile(tile.getId(), tile);
            }
        }
        Array<Element> tileElements = element.getChildrenByName("tile");

        Array<AnimatedTiledMapTile> animatedTiles = new Array<AnimatedTiledMapTile>();

        for (Element tileElement : tileElements) {
            int localtid = tileElement.getIntAttribute("id", 0);
            TiledMapTile tile = tileset.getTile(firstgid + localtid);
            if (tile != null) {
                Element animationElement = tileElement.getChildByName("animation");
                if (animationElement != null) {

                    Array<StaticTiledMapTile> staticTiles = new Array<StaticTiledMapTile>();
                    IntArray intervals = new IntArray();
                    for (Element frameElement : animationElement.getChildrenByName("frame")) {
                        staticTiles.add((StaticTiledMapTile) tileset
                                .getTile(firstgid + frameElement.getIntAttribute("tileid")));
                        intervals.add(frameElement.getIntAttribute("duration"));
                    }

                    AnimatedTiledMapTile animatedTile = new AnimatedTiledMapTile(intervals, staticTiles);
                    animatedTile.setId(tile.getId());
                    animatedTiles.add(animatedTile);
                    tile = animatedTile;
                }

                String terrain = tileElement.getAttribute("terrain", null);
                if (terrain != null) {
                    tile.getProperties().put("terrain", terrain);
                }
                String probability = tileElement.getAttribute("probability", null);
                if (probability != null) {
                    tile.getProperties().put("probability", probability);
                }
                Element properties = tileElement.getChildByName("properties");
                if (properties != null) {
                    loadProperties(tile.getProperties(), properties);
                }
            }
        }

        for (AnimatedTiledMapTile tile : animatedTiles) {
            tileset.putTile(tile.getId(), tile);
        }

        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(tileset.getProperties(), properties);
        }
        map.getTileSets().addTileSet(tileset);
    }
}

From source file:com.gdx.game.sprites.Token.java

public Token(World world, TiledMap map, Rectangle bounds, AssetManager assetManager) {
    super(world, map, bounds);
    this.assetManager = assetManager;
    tileSet = map.getTileSets().getTileSet("Tileset");
    fixture.setUserData(this);
    setCategoryFilter(GdxGame.COIN_BIT);
}

From source file:com.skettios.loader.TmxMapLoaderFixed.java

License:Apache License

/**
 * Loads the specified tileset data, adding it to the collection of the specified map, given the XML element, the tmxFile and
 * an {@link ImageResolver} used to retrieve the tileset Textures.
 * <p/>//from  w ww.  j  a  v  a2  s.c o  m
 * <p>
 * Default tileset's property keys that are loaded by default are:
 * </p>
 * <p/>
 * <ul>
 * <li><em>firstgid</em>, (int, defaults to 1) the first valid global id used for tile numbering</li>
 * <li><em>imagesource</em>, (String, defaults to empty string) the tileset source image filename</li>
 * <li><em>imagewidth</em>, (int, defaults to 0) the tileset source image width</li>
 * <li><em>imageheight</em>, (int, defaults to 0) the tileset source image height</li>
 * <li><em>tilewidth</em>, (int, defaults to 0) the tile width</li>
 * <li><em>tileheight</em>, (int, defaults to 0) the tile height</li>
 * <li><em>margin</em>, (int, defaults to 0) the tileset margin</li>
 * <li><em>spacing</em>, (int, defaults to 0) the tileset spacing</li>
 * </ul>
 * <p/>
 * <p>
 * The values are extracted from the specified Tmx file, if a value can't be found then the default is used.
 * </p>
 *
 * @param map           the Map whose tilesets collection will be populated
 * @param element       the XML element identifying the tileset to load
 * @param tmxFile       the Filehandle of the tmx file
 * @param imageResolver the {@link ImageResolver}
 */
protected void loadTileSet(TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) {
    if (element.getName().equals("tileset")) {
        String name = element.get("name", null);
        int firstgid = element.getIntAttribute("firstgid", 1);
        int tilewidth = element.getIntAttribute("tilewidth", 0);
        int tileheight = element.getIntAttribute("tileheight", 0);
        int spacing = element.getIntAttribute("spacing", 0);
        int margin = element.getIntAttribute("margin", 0);
        String source = element.getAttribute("source", null);

        int offsetX = 0;
        int offsetY = 0;

        String imageSource = "";
        int imageWidth = 0, imageHeight = 0;

        FileHandle image = null;
        if (source != null) {
            FileHandle tsx = getRelativeFileHandleFixed(tmxFile, source);
            try {
                element = xml.parse(tsx);
                name = element.get("name", null);
                tilewidth = element.getIntAttribute("tilewidth", 0);
                tileheight = element.getIntAttribute("tileheight", 0);
                spacing = element.getIntAttribute("spacing", 0);
                margin = element.getIntAttribute("margin", 0);
                Element offset = element.getChildByName("tileoffset");
                if (offset != null) {
                    offsetX = offset.getIntAttribute("x", 0);
                    offsetY = offset.getIntAttribute("y", 0);
                }
                Element imageElement = element.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandleFixed(tsx, imageSource);
                }
            } catch (IOException e) {
                throw new GdxRuntimeException("Error parsing external tileset.");
            }
        } else {
            Element offset = element.getChildByName("tileoffset");
            if (offset != null) {
                offsetX = offset.getIntAttribute("x", 0);
                offsetY = offset.getIntAttribute("y", 0);
            }
            Element imageElement = element.getChildByName("image");
            if (imageElement != null) {
                imageSource = imageElement.getAttribute("source");
                imageWidth = imageElement.getIntAttribute("width", 0);
                imageHeight = imageElement.getIntAttribute("height", 0);
                image = getRelativeFileHandleFixed(tmxFile, imageSource);
            }
        }

        TiledMapTileSet tileset = new TiledMapTileSet();
        tileset.setName(name);
        tileset.getProperties().put("firstgid", firstgid);
        if (image != null) {
            TextureRegion texture = imageResolver.getImage(image.path());

            MapProperties props = tileset.getProperties();
            props.put("imagesource", imageSource);
            props.put("imagewidth", imageWidth);
            props.put("imageheight", imageHeight);
            props.put("tilewidth", tilewidth);
            props.put("tileheight", tileheight);
            props.put("margin", margin);
            props.put("spacing", spacing);

            int stopWidth = texture.getRegionWidth() - tilewidth;
            int stopHeight = texture.getRegionHeight() - tileheight;

            int id = firstgid;

            for (int y = margin; y <= stopHeight; y += tileheight + spacing) {
                for (int x = margin; x <= stopWidth; x += tilewidth + spacing) {
                    TextureRegion tileRegion = new TextureRegion(texture, x, y, tilewidth, tileheight);
                    TiledMapTile tile = new StaticTiledMapTile(tileRegion);
                    tile.setId(id);
                    tile.setOffsetX(offsetX);
                    tile.setOffsetY(-offsetY);
                    tileset.putTile(id++, tile);
                }
            }
        } else {
            Array<Element> tileElements = element.getChildrenByName("tile");
            for (Element tileElement : tileElements) {
                Element imageElement = tileElement.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandleFixed(tmxFile, imageSource);
                }
                TextureRegion texture = imageResolver.getImage(image.path());
                TiledMapTile tile = new StaticTiledMapTile(texture);
                tile.setId(firstgid + tileElement.getIntAttribute("id"));
                tile.setOffsetX(offsetX);
                tile.setOffsetY(-offsetY);
                tileset.putTile(tile.getId(), tile);
            }
        }
        Array<Element> tileElements = element.getChildrenByName("tile");

        Array<AnimatedTiledMapTile> animatedTiles = new Array<AnimatedTiledMapTile>();

        for (Element tileElement : tileElements) {
            int localtid = tileElement.getIntAttribute("id", 0);
            TiledMapTile tile = tileset.getTile(firstgid + localtid);
            if (tile != null) {
                Element animationElement = tileElement.getChildByName("animation");
                if (animationElement != null) {

                    Array<StaticTiledMapTile> staticTiles = new Array<StaticTiledMapTile>();
                    IntArray intervals = new IntArray();
                    for (Element frameElement : animationElement.getChildrenByName("frame")) {
                        staticTiles.add((StaticTiledMapTile) tileset
                                .getTile(firstgid + frameElement.getIntAttribute("tileid")));
                        intervals.add(frameElement.getIntAttribute("duration"));
                    }

                    AnimatedTiledMapTile animatedTile = new AnimatedTiledMapTile(intervals, staticTiles);
                    animatedTile.setId(tile.getId());
                    animatedTiles.add(animatedTile);
                    tile = animatedTile;
                }

                String terrain = tileElement.getAttribute("terrain", null);
                if (terrain != null) {
                    tile.getProperties().put("terrain", terrain);
                }
                String probability = tileElement.getAttribute("probability", null);
                if (probability != null) {
                    tile.getProperties().put("probability", probability);
                }
                Element properties = tileElement.getChildByName("properties");
                if (properties != null) {
                    loadProperties(tile.getProperties(), properties);
                }
            }
        }

        for (AnimatedTiledMapTile tile : animatedTiles) {
            tileset.putTile(tile.getId(), tile);
        }

        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(tileset.getProperties(), properties);
        }
        map.getTileSets().addTileSet(tileset);
    }
}

From source file:de.bitowl.advent.game2.MyAtlasTmxMapLoader.java

License:Apache License

protected void loadTileset(TiledMap map, Element element, FileHandle tmxFile, AtlasResolver resolver,
        AtlasTiledMapLoaderParameters parameter) {
    if (element.getName().equals("tileset")) {
        String name = element.get("name", null);
        int firstgid = element.getIntAttribute("firstgid", 1);
        int tilewidth = element.getIntAttribute("tilewidth", 0);
        int tileheight = element.getIntAttribute("tileheight", 0);
        int spacing = element.getIntAttribute("spacing", 0);
        int margin = element.getIntAttribute("margin", 0);
        String source = element.getAttribute("source", null);

        String imageSource = "";
        int imageWidth = 0, imageHeight = 0;

        FileHandle image = null;/*ww  w .j av a  2  s . c  o m*/
        if (source != null) {
            FileHandle tsx = getRelativeFileHandle(tmxFile, source);
            try {
                element = xml.parse(tsx);
                name = element.get("name", null);
                tilewidth = element.getIntAttribute("tilewidth", 0);
                tileheight = element.getIntAttribute("tileheight", 0);
                spacing = element.getIntAttribute("spacing", 0);
                margin = element.getIntAttribute("margin", 0);
                imageSource = element.getChildByName("image").getAttribute("source");
                imageWidth = element.getChildByName("image").getIntAttribute("width", 0);
                imageHeight = element.getChildByName("image").getIntAttribute("height", 0);
            } catch (IOException e) {
                throw new GdxRuntimeException("Error parsing external tileset.");
            }
        } else {
            imageSource = element.getChildByName("image").getAttribute("source");
            imageWidth = element.getChildByName("image").getIntAttribute("width", 0);
            imageHeight = element.getChildByName("image").getIntAttribute("height", 0);
        }

        if (!map.getProperties().containsKey("atlas")) {
            throw new GdxRuntimeException("The map is missing the 'atlas' property");
        }

        // get the TextureAtlas for this tileset
        FileHandle atlasHandle = getRelativeFileHandle(tmxFile, map.getProperties().get("atlas", String.class));
        atlasHandle = resolve(atlasHandle.path());
        TextureAtlas atlas = resolver.getAtlas(atlasHandle.path());
        //String regionsName = atlasHandle.nameWithoutExtension();
        String regionsName = name;

        if (parameter != null && parameter.forceTextureFilters) {
            for (Texture texture : atlas.getTextures()) {
                trackedTextures.add(texture);
            }
        }

        TiledMapTileSet tileset = new TiledMapTileSet();
        MapProperties props = tileset.getProperties();
        tileset.setName(name);
        props.put("firstgid", firstgid);
        props.put("imagesource", imageSource);
        props.put("imagewidth", imageWidth);
        props.put("imageheight", imageHeight);
        props.put("tilewidth", tilewidth);
        props.put("tileheight", tileheight);
        props.put("margin", margin);
        props.put("spacing", spacing);

        Array<AtlasRegion> regions = atlas.findRegions(regionsName);
        System.out.println(regions.size);
        for (AtlasRegion region : regions) {
            // handle unused tile ids
            if (region != null) {
                StaticTiledMapTile tile = new StaticTiledMapTile(region);

                if (!yUp) {
                    region.flip(false, true);
                }

                int tileid = firstgid + region.index;
                tile.setId(tileid);
                tileset.putTile(tileid, tile);
                System.out.println("put tile " + tileid);
            }
        }

        Array<Element> tileElements = element.getChildrenByName("tile");

        for (Element tileElement : tileElements) {
            int localtid = tileElement.getIntAttribute("id", 0);
            TiledMapTile tile = tileset.getTile(firstgid + localtid);
            if (tile != null) {
                String terrain = tileElement.getAttribute("terrain", null);
                if (terrain != null) {
                    tile.getProperties().put("terrain", terrain);
                }
                String probability = tileElement.getAttribute("probability", null);
                if (probability != null) {
                    tile.getProperties().put("probability", probability);
                }
                Element properties = tileElement.getChildByName("properties");
                if (properties != null) {
                    loadProperties(tile.getProperties(), properties);
                }
            }
        }

        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(tileset.getProperties(), properties);
        }
        System.out.println("add tileset to map: " + tileset.getName());
        map.getTileSets().addTileSet(tileset);
    }
}

From source file:de.bitowl.advent.game2.MyAtlasTmxMapLoader.java

License:Apache License

protected void loadTileLayer(TiledMap map, Element element) {
    if (element.getName().equals("layer")) {
        String name = element.getAttribute("name", null);
        int width = element.getIntAttribute("width", 0);
        int height = element.getIntAttribute("height", 0);
        int tileWidth = element.getParent().getIntAttribute("tilewidth", 0);
        int tileHeight = element.getParent().getIntAttribute("tileheight", 0);
        boolean visible = element.getIntAttribute("visible", 1) == 1;
        float opacity = element.getFloatAttribute("opacity", 1.0f);
        TiledMapTileLayer layer = new TiledMapTileLayer(width, height, tileWidth, tileHeight);
        layer.setVisible(visible);//www .  j  a v a2s  .c om
        layer.setOpacity(opacity);
        layer.setName(name);

        TiledMapTileSets tilesets = map.getTileSets();

        Element data = element.getChildByName("data");
        String encoding = data.getAttribute("encoding", null);
        String compression = data.getAttribute("compression", null);
        if (encoding == null) { // no 'encoding' attribute means that the encoding is XML
            throw new GdxRuntimeException("Unsupported encoding (XML) for TMX Layer Data");
        }
        if (encoding.equals("csv")) {
            String[] array = data.getText().split(",");
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    int id = (int) Long.parseLong(array[y * width + x].trim());

                    final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
                    final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
                    final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);

                    id = id & ~MASK_CLEAR;

                    tilesets.getTile(id);

                    TiledMapTile tile = tilesets.getTile(id);
                    if (tile != null) {
                        Cell cell = createTileLayerCell(flipHorizontally, flipVertically, flipDiagonally);
                        cell.setTile(tile);
                        layer.setCell(x, yUp ? height - 1 - y : y, cell);
                    }
                }
            }
        } else {
            if (encoding.equals("base64")) {
                byte[] bytes = Base64Coder.decode(data.getText());
                if (compression == null) {
                    int read = 0;
                    for (int y = 0; y < height; y++) {
                        for (int x = 0; x < width; x++) {

                            int id = unsignedByteToInt(bytes[read++]) | unsignedByteToInt(bytes[read++]) << 8
                                    | unsignedByteToInt(bytes[read++]) << 16
                                    | unsignedByteToInt(bytes[read++]) << 24;

                            final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
                            final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
                            final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);

                            id = id & ~MASK_CLEAR;

                            tilesets.getTile(id);
                            TiledMapTile tile = tilesets.getTile(id);
                            if (tile != null) {
                                Cell cell = createTileLayerCell(flipHorizontally, flipVertically,
                                        flipDiagonally);
                                cell.setTile(tile);
                                layer.setCell(x, yUp ? height - 1 - y : y, cell);
                            }
                        }
                    }
                } else if (compression.equals("gzip")) {
                    GZIPInputStream GZIS = null;
                    try {
                        GZIS = new GZIPInputStream(new ByteArrayInputStream(bytes), bytes.length);
                    } catch (IOException e) {
                        throw new GdxRuntimeException(
                                "Error Reading TMX Layer Data - IOException: " + e.getMessage());
                    }

                    byte[] temp = new byte[4];
                    for (int y = 0; y < height; y++) {
                        for (int x = 0; x < width; x++) {
                            try {
                                GZIS.read(temp, 0, 4);
                                int id = unsignedByteToInt(temp[0]) | unsignedByteToInt(temp[1]) << 8
                                        | unsignedByteToInt(temp[2]) << 16 | unsignedByteToInt(temp[3]) << 24;

                                final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
                                final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
                                final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);

                                id = id & ~MASK_CLEAR;

                                tilesets.getTile(id);
                                TiledMapTile tile = tilesets.getTile(id);
                                if (tile != null) {
                                    Cell cell = createTileLayerCell(flipHorizontally, flipVertically,
                                            flipDiagonally);
                                    cell.setTile(tile);
                                    layer.setCell(x, yUp ? height - 1 - y : y, cell);
                                }
                            } catch (IOException e) {
                                throw new GdxRuntimeException("Error Reading TMX Layer Data.", e);
                            }
                        }
                    }
                } else if (compression.equals("zlib")) {
                    Inflater zlib = new Inflater();

                    byte[] temp = new byte[4];

                    zlib.setInput(bytes, 0, bytes.length);

                    for (int y = 0; y < height; y++) {
                        for (int x = 0; x < width; x++) {
                            try {
                                zlib.inflate(temp, 0, 4);
                                int id = unsignedByteToInt(temp[0]) | unsignedByteToInt(temp[1]) << 8
                                        | unsignedByteToInt(temp[2]) << 16 | unsignedByteToInt(temp[3]) << 24;

                                final boolean flipHorizontally = ((id & FLAG_FLIP_HORIZONTALLY) != 0);
                                final boolean flipVertically = ((id & FLAG_FLIP_VERTICALLY) != 0);
                                final boolean flipDiagonally = ((id & FLAG_FLIP_DIAGONALLY) != 0);

                                id = id & ~MASK_CLEAR;

                                tilesets.getTile(id);
                                if (id != 0) {
                                    String inset = "NONE";
                                    if (tilesets.getTileSet(0).getTile(id) != null) {
                                        inset = tilesets.getTileSet(0).getName();
                                    } else if (tilesets.getTileSet(1).getTile(id) != null) {
                                        inset = tilesets.getTileSet(1).getName();
                                    }
                                    System.out.println("need tile " + id + inset);
                                }

                                TiledMapTile tile = tilesets.getTile(id);
                                if (tile != null) {
                                    Cell cell = createTileLayerCell(flipHorizontally, flipVertically,
                                            flipDiagonally);
                                    cell.setTile(tile);
                                    layer.setCell(x, yUp ? height - 1 - y : y, cell);
                                }

                            } catch (DataFormatException e) {
                                throw new GdxRuntimeException("Error Reading TMX Layer Data.", e);
                            }
                        }
                    }
                }
            } else {
                // any other value of 'encoding' is one we're not aware of, probably a feature of a future version of Tiled
                // or another editor
                throw new GdxRuntimeException("Unrecognised encoding (" + encoding + ") for TMX Layer Data");
            }
        }
        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(layer.getProperties(), properties);
        }
        map.getLayers().add(layer);
    }
}

From source file:de.bitowl.advent.game2.MyTiledMapPacker.java

License:Apache License

/** Returns the tileset name associated with the specified tile id
 * @return a tileset name *///from w ww .j a  v  a 2 s  . c o m
private String tilesetNameFromTileId(TiledMap map, int tileid) {
    String name = "";
    if (tileid == 0) {
        return "";
    }

    for (TiledMapTileSet tileset : map.getTileSets()) {
        int firstgid = tileset.getProperties().get("firstgid", -1, Integer.class);
        if (firstgid == -1)
            continue; // skip this tileset
        if (tileid >= firstgid) {
            name = tileset.getName();
        } else {
            return name;
        }
    }

    return name;
}

From source file:me.boxcubed.main.desktop.server.ServerTiledMapLoader.java

License:Apache License

/** Loads the specified tileset data, adding it to the collection of the specified map, given the XML element, the tmxFile and
 * an {@link ImageResolver} used to retrieve the tileset Textures.
 * //www .  ja v  a 2  s .  co m
 * <p>
 * Default tileset's property keys that are loaded by default are:
 * </p>
 * 
 * <ul>
 * <li><em>firstgid</em>, (int, defaults to 1) the first valid global id used for tile numbering</li>
 * <li><em>imagesource</em>, (String, defaults to empty string) the tileset source image filename</li>
 * <li><em>imagewidth</em>, (int, defaults to 0) the tileset source image width</li>
 * <li><em>imageheight</em>, (int, defaults to 0) the tileset source image height</li>
 * <li><em>tilewidth</em>, (int, defaults to 0) the tile width</li>
 * <li><em>tileheight</em>, (int, defaults to 0) the tile height</li>
 * <li><em>margin</em>, (int, defaults to 0) the tileset margin</li>
 * <li><em>spacing</em>, (int, defaults to 0) the tileset spacing</li>
 * </ul>
 * 
 * <p>
 * The values are extracted from the specified Tmx file, if a value can't be found then the default is used.
 * </p>
 * @param map the Map whose tilesets collection will be populated
 * @param element the XML element identifying the tileset to load
 * @param tmxFile the Filehandle of the tmx file
 * @param imageResolver the {@link ImageResolver} */
@SuppressWarnings("unused")
protected void loadTileSet(TiledMap map, Element element, FileHandle tmxFile, ImageResolver imageResolver) {
    if (element.getName().equals("tileset")) {
        String name = element.get("name", null);
        int firstgid = element.getIntAttribute("firstgid", 1);
        int tilewidth = element.getIntAttribute("tilewidth", 0);
        int tileheight = element.getIntAttribute("tileheight", 0);
        int spacing = element.getIntAttribute("spacing", 0);
        int margin = element.getIntAttribute("margin", 0);
        String source = element.getAttribute("source", null);

        int offsetX = 0;
        int offsetY = 0;

        String imageSource = "";
        int imageWidth = 0, imageHeight = 0;

        FileHandle image = null;
        if (source != null) {
            FileHandle tsx = getRelativeFileHandle(tmxFile, source);
            try {
                element = xml.parse(tsx);
                name = element.get("name", null);
                tilewidth = element.getIntAttribute("tilewidth", 0);
                tileheight = element.getIntAttribute("tileheight", 0);
                spacing = element.getIntAttribute("spacing", 0);
                margin = element.getIntAttribute("margin", 0);
                Element offset = element.getChildByName("tileoffset");
                if (offset != null) {
                    offsetX = offset.getIntAttribute("x", 0);
                    offsetY = offset.getIntAttribute("y", 0);
                }
                Element imageElement = element.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandle(tsx, imageSource);
                }
            } catch (IOException e) {
                throw new GdxRuntimeException("Error parsing external tileset.");
            }
        } else {
            Element offset = element.getChildByName("tileoffset");
            if (offset != null) {
                offsetX = offset.getIntAttribute("x", 0);
                offsetY = offset.getIntAttribute("y", 0);
            }
            Element imageElement = element.getChildByName("image");
            if (imageElement != null) {
                imageSource = imageElement.getAttribute("source");
                imageWidth = imageElement.getIntAttribute("width", 0);
                imageHeight = imageElement.getIntAttribute("height", 0);
                image = getRelativeFileHandle(tmxFile, imageSource);
            }
        }

        TiledMapTileSet tileset = new TiledMapTileSet();
        tileset.setName(name);
        tileset.getProperties().put("firstgid", firstgid);
        if (false) {
        }

        else {
            Array<Element> tileElements = element.getChildrenByName("tile");
            for (Element tileElement : tileElements) {
                Element imageElement = tileElement.getChildByName("image");
                if (imageElement != null) {
                    imageSource = imageElement.getAttribute("source");
                    imageWidth = imageElement.getIntAttribute("width", 0);
                    imageHeight = imageElement.getIntAttribute("height", 0);
                    image = getRelativeFileHandle(tmxFile, imageSource);
                }
                TextureRegion texture = imageResolver.getImage(image.path());
                TiledMapTile tile = new StaticTiledMapTile(texture);
                tile.setId(firstgid + tileElement.getIntAttribute("id"));
                tile.setOffsetX(offsetX);
                tile.setOffsetY(flipY ? -offsetY : offsetY);
                tileset.putTile(tile.getId(), tile);
            }
        }
        Array<Element> tileElements = element.getChildrenByName("tile");

        Array<AnimatedTiledMapTile> animatedTiles = new Array<AnimatedTiledMapTile>();

        for (Element tileElement : tileElements) {
            int localtid = tileElement.getIntAttribute("id", 0);
            TiledMapTile tile = tileset.getTile(firstgid + localtid);
            if (tile != null) {
                Element animationElement = tileElement.getChildByName("animation");
                if (animationElement != null) {

                    Array<StaticTiledMapTile> staticTiles = new Array<StaticTiledMapTile>();
                    IntArray intervals = new IntArray();
                    for (Element frameElement : animationElement.getChildrenByName("frame")) {
                        staticTiles.add((StaticTiledMapTile) tileset
                                .getTile(firstgid + frameElement.getIntAttribute("tileid")));
                        intervals.add(frameElement.getIntAttribute("duration"));
                    }

                    AnimatedTiledMapTile animatedTile = new AnimatedTiledMapTile(intervals, staticTiles);
                    animatedTile.setId(tile.getId());
                    animatedTiles.add(animatedTile);
                    tile = animatedTile;
                }

                String terrain = tileElement.getAttribute("terrain", null);
                if (terrain != null) {
                    tile.getProperties().put("terrain", terrain);
                }
                String probability = tileElement.getAttribute("probability", null);
                if (probability != null) {
                    tile.getProperties().put("probability", probability);
                }
                Element properties = tileElement.getChildByName("properties");
                if (properties != null) {
                    loadProperties(tile.getProperties(), properties);
                }
            }
        }

        for (AnimatedTiledMapTile tile : animatedTiles) {
            tileset.putTile(tile.getId(), tile);
        }

        Element properties = element.getChildByName("properties");
        if (properties != null) {
            loadProperties(tileset.getProperties(), properties);
        }
        map.getTileSets().addTileSet(tileset);
    }
}

From source file:releasethekraken.LevelLoader.java

/**
 * Parses the level file and constructs a game world from it, and returns it.
 * Throws an exception if loading failed.
 * @return The newly loaded GameWorld/*from   w w w .j ava  2 s  . c o m*/
 */
public GameWorld loadWorld() {
    Gdx.app.log("LevelLoader", "Loading level \"" + this.levelName + "\"");

    MapBodyManager mapBodyManager;
    GameWorld newWorld = new GameWorld(this.levelName);

    //Make a new TiledMap
    TiledMap map = new TmxMapLoader().load(this.levelName + ".tmx");

    float unitScale = 16.0F; //16 pixels = 1 meter

    mapBodyManager = new MapBodyManager(newWorld.getPhysWorld(), unitScale, null, 2);
    mapBodyManager.createPhysics(map, "physics");

    //Get the map properties
    MapProperties properties = map.getProperties();

    //Load world properties
    newWorld.setName(properties.get("levelname", String.class));
    newWorld.setPointsForKraken(Integer.parseInt(properties.get("krakenpoints", String.class)));
    newWorld.setWidth(properties.get("width", Integer.class) * 2);
    newWorld.setHeight(properties.get("height", Integer.class) * 2);
    newWorld.setTiledMap(map);
    newWorld.setTiledMapUnitScale(unitScale);
    newWorld.spawnWorldBoundaries();

    //Load Entity Tile Data
    Gdx.app.log("LevelLoader", "Parsing entity tile data");

    TiledMapTileSet entityTileSet = map.getTileSets().getTileSet("Entities");
    Iterator<TiledMapTile> entityTileIterator = entityTileSet.iterator();

    while (entityTileIterator.hasNext()) //Iterate through entity tiles
    {
        TiledMapTile tile = entityTileIterator.next();
        String type = tile.getProperties().get("type", String.class);

        if (type == null) //Only check tiles that have a type set
            continue;

        //See if there is an entity class for a given name
        Class<? extends Entity> entityClass = ReleaseTheKraken.getEntityFromName(type);

        //If there is, register the ID
        if (entityClass != null)
            this.entityTileIDs.put(tile.getId(), entityClass);

        Gdx.app.log("LevelLoader", "Tile ID: " + tile.getId() + " type: " + type);
    }

    //If you thought that was complicated, wait until you see what's next: paths!

    //Load world paths
    Gdx.app.log("LevelLoader", "Parsing world paths");
    MapLayer pathLayer = map.getLayers().get("paths");

    //If the layer doesn't exist, throw an exception
    if (pathLayer == null)
        throw new NullPointerException("paths layer is null");

    MapObjects pathObjects = pathLayer.getObjects();
    Iterator<MapObject> pathObjIterator = pathObjects.iterator();

    //Create an IntMap to map integer path IDs to paths
    IntMap<SeaCreaturePath> pathMap = new IntMap<SeaCreaturePath>();
    //Create an IntMap to map integer path IDs to arrays of next path IDs
    IntMap<int[]> nextPathsMap = new IntMap<int[]>();

    while (pathObjIterator.hasNext()) //Iterate over paths on the map
    {
        MapObject pathObject = pathObjIterator.next();

        //Gdx.app.log("LevelLoader", "Parsing map object: " + pathObject);

        if (pathObject instanceof PolylineMapObject) //If the mapObject is of the correct type
        {
            PolylineMapObject polylineMapObject = (PolylineMapObject) pathObject;

            int pathID = polylineMapObject.getProperties().get("id", Integer.class);

            Gdx.app.log("LevelLoader", "Attempting to load path with ID: " + pathID);

            //Get and parse the list of next paths
            String nextPaths = polylineMapObject.getProperties().get("next", String.class);
            String[] nextPathIDs = nextPaths.split(",");

            //Make an array of next path integer IDs
            int[] nextPathIntIDs = new int[nextPathIDs.length];

            //Parse the integer IDs from the string IDs
            for (int i = 0; i < nextPathIDs.length; i++)
                if (!nextPathIDs[i].equals(""))
                    nextPathIntIDs[i] = Integer.parseInt(nextPathIDs[i]);

            //Create a new SeaCreaturePath object
            SeaCreaturePath seaCreaturePath = new SeaCreaturePath(pathID, null, null,
                    polylineMapObject.getPolyline());

            //Add the SeaCreaturePath object and its next paths to the IntMaps
            pathMap.put(pathID, seaCreaturePath); //Add the path to the IntMap so that it can be connected later
            nextPathsMap.put(pathID, nextPathIntIDs); //Add the next paths to the IntMap so that the paths can be connected later
        }
    }

    //Gdx.app.log("LevelLoader", "Done creating paths");
    //Gdx.app.log("LevelLoader", "pathMap: " + pathMap);
    //Gdx.app.log("LevelLoader", "nextPathsMap: " + nextPathsMap);

    //Now that all of the SeaCreaturePaths are created, it's time to connect them

    SeaCreaturePath firstPath = null; //The first path, which will be the one added to the world
    Iterator<IntMap.Entry<SeaCreaturePath>> pathIterator = pathMap.iterator();

    //Iterate over each path, connecting it to the other paths it should be connected to
    while (pathIterator.hasNext()) {
        IntMap.Entry<SeaCreaturePath> currentPathEntry = pathIterator.next();

        int pathID = currentPathEntry.key;
        SeaCreaturePath currentPath = currentPathEntry.value;

        //Create the next paths list
        Array<SeaCreaturePath> nextPaths = new Array<SeaCreaturePath>();

        //Get the array of next path IDs
        int[] nextPathIDs = nextPathsMap.get(pathID);

        //Connect the paths
        for (int i = 0; i < nextPathIDs.length; i++) {
            nextPaths.add(pathMap.get(nextPathIDs[i])); //Add the path to the list of next paths

            if (pathMap.get(nextPathIDs[i]) != null)
                pathMap.get(nextPathIDs[i]).setParent(currentPath); //Tell the next path that this current path is the parent
            //BUG: Each next path overwrites this, only the last "next path" gets to be the parent
        }

        currentPath.setNextPaths(nextPaths); //Set the next paths list for the path

        //Set the first path to the path that has a null parent
        if (currentPath.getParent() == null)
            firstPath = currentPath;
        //BUG: Only the last path that has a null parent becomes the first path.  
        //This might not be a problem, as only one path should ever have a null parent.
    }

    newWorld.setFirstPath(firstPath); //Set the first path in the world
    //Done loading paths

    //Load world entities
    Gdx.app.log("LevelLoader", "Parsing world entities");
    MapLayer entityLayer = map.getLayers().get("entities");

    //If the layer doesn't exist, throw an exception
    if (entityLayer == null)
        throw new NullPointerException("entities layer is null");

    MapObjects entityObjects = entityLayer.getObjects();
    Iterator<MapObject> entityObjIterator = entityObjects.iterator();

    while (entityObjIterator.hasNext()) //Iterate over entities on the map
    {
        MapObject entityObject = entityObjIterator.next();

        //Gdx.app.log("LevelLoader", "Parsing map object: " + entityObject);

        if (entityObject instanceof TextureMapObject) //If the mapObject is of the correct type
        {
            //Get the entity class from the mapObject's tile ID
            int gid = ((TextureMapObject) entityObject).getProperties().get("gid", Integer.class);
            Class<? extends Entity> entityClass = this.entityTileIDs.get(gid);

            if (entityClass != null) {
                Gdx.app.log("LevelLoader", "Attempting to spawn " + entityClass.getSimpleName());

                try {
                    //Construct a new entity by finding the correct constructor from its class, and reflectively instantiating it.  Magic!
                    Constructor<? extends Entity> constructor = entityClass.getConstructor(GameWorld.class,
                            TextureMapObject.class);
                    Entity entity = constructor.newInstance(newWorld, entityObject);
                    //newWorld.addEntity(entity); //Add the entity to the world //With Box2D, the entity should add itself to the world

                    if (entity instanceof EntityPlayer) //Set the player if the entity is the player
                        newWorld.setPlayer((EntityPlayer) entity);
                    else if (entity instanceof EntityPirateBase) //Set the pirate base if the entity is the pirate base
                        newWorld.setPirateBase((EntityPirateBase) entity);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    Gdx.app.log("LevelLoader", "Successfully loaded the world!");
    Gdx.app.log("LevelLoader", newWorld.toString());

    return newWorld;
}

From source file:sink.map.Map.java

License:Apache License

public Map(TiledMap map, int tileSize) {
    setPosition(0, 0);//from   www .j  a v a  2 s  .c  o  m
    setOrigin(0, 0);
    this.tileSize = tileSize;
    mlayers = map.getLayers();
    tileSets = map.getTileSets();
}