public TiledMap load(String fileName, AtlasTiledMapLoaderParameters parameter) { try { if (parameter != null) { yUp = parameter.yUp; } else { yUp = true; } FileHandle tmxFile = resolve(fileName); root = xml.parse(tmxFile); ObjectMap<String, TextureAtlas> atlases = new ObjectMap<String, TextureAtlas>(); FileHandle atlasFile = loadAtlas(root, tmxFile); if (atlasFile == null) { throw new GdxRuntimeException("Couldn't load atlas"); } TextureAtlas atlas = new TextureAtlas(atlasFile); atlases.put(atlasFile.path(), atlas); AtlasResolver.DirectAtlasResolver atlasResolver = new AtlasResolver.DirectAtlasResolver(atlases); TiledMap map = loadMap(root, tmxFile, atlasResolver, parameter); map.setOwnedResources(atlases.values().toArray()); setTextureFilters(parameter.textureMinFilter, parameter.textureMagFilter); return map; } catch (IOException e) { throw new GdxRuntimeException("Couldn't load tilemap '" + fileName + "'", e); } }
/** * Load all tiles from the layer * * @param element the layer element * @return an array containing all tile information of this layer * @throws IOException * @throws Exception */ private TileInfo[][] loadTiles(TmxLayer element) throws IOException, Exception { List<Integer> ids = element.getData().getIds(); int id = 0; TileInfo[][] result = new TileInfo[width][height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int tileId = ids.get(id++); if (tileId == 0) { result[x][y] = null; } else { TileSet set = map.findTileSet(tileId); if (set != null) { result[x][y] = new TileInfo( set.getIndex(), tileId - set.getFirstGID(), tileId, set.getTileProperties(tileId)); } else { result[x][y] = new TileInfo(0, 0, tileId, null); } } } } return result; }
/** * Loads the map data, given the XML root element and an {@link ImageResolver} used to return the * tileset Textures * * @param root the XML root element * @param tmxFile the Filehandle of the tmx file * @param imageResolver the {@link ImageResolver} * @return the {@link TiledMap} */ private TiledMap loadMap(Element root, FileHandle tmxFile, ImageResolver imageResolver) { TiledMap map = new TiledMap(); Element properties = root.getChildByName("properties"); if (properties != null) { loadProperties(map.getProperties(), properties); } Element tilesheets = root.getChildByName("TileSheets"); for (Element tilesheet : tilesheets.getChildrenByName("TileSheet")) { loadTileSheet(map, tilesheet, tmxFile, imageResolver); } Element layers = root.getChildByName("Layers"); for (Element layer : layers.getChildrenByName("Layer")) { loadLayer(map, layer); } return map; }
public TiledMap load(String fileName) { try { FileHandle tideFile = resolve(fileName); root = xml.parse(tideFile); ObjectMap<String, Texture> textures = new ObjectMap<String, Texture>(); for (FileHandle textureFile : loadTileSheets(root, tideFile)) { textures.put(textureFile.path(), new Texture(textureFile)); } DirectImageResolver imageResolver = new DirectImageResolver(textures); TiledMap map = loadMap(root, tideFile, imageResolver); map.setOwnedResources(textures.values().toArray()); return map; } catch (IOException e) { throw new GdxRuntimeException("Couldn't load tilemap '" + fileName + "'", e); } }
protected TiledMap loadMap( Element root, FileHandle tmxFile, AtlasResolver resolver, AtlasTiledMapLoaderParameters parameter) { TiledMap map = new TiledMap(); String mapOrientation = root.getAttribute("orientation", null); int mapWidth = root.getIntAttribute("width", 0); int mapHeight = root.getIntAttribute("height", 0); int tileWidth = root.getIntAttribute("tilewidth", 0); int tileHeight = root.getIntAttribute("tileheight", 0); String mapBackgroundColor = root.getAttribute("backgroundcolor", null); MapProperties mapProperties = map.getProperties(); if (mapOrientation != null) { mapProperties.put("orientation", mapOrientation); } mapProperties.put("width", mapWidth); mapProperties.put("height", mapHeight); mapProperties.put("tilewidth", tileWidth); mapProperties.put("tileheight", tileHeight); if (mapBackgroundColor != null) { mapProperties.put("backgroundcolor", mapBackgroundColor); } mapWidthInPixels = mapWidth * tileWidth; mapHeightInPixels = mapHeight * tileHeight; for (int i = 0, j = root.getChildCount(); i < j; i++) { Element element = root.getChild(i); String elementName = element.getName(); if (elementName.equals("properties")) { loadProperties(map.getProperties(), element); } else if (elementName.equals("tileset")) { loadTileset(map, element, tmxFile, resolver, parameter); } else if (elementName.equals("layer")) { loadTileLayer(map, element); } else if (elementName.equals("objectgroup")) { loadObjectGroup(map, element); } } return map; }
@Override public void init(AssetManagerX assetManager) { engine = new Engine(); entityManager = new EntityManager(); physixManager = new PhysixManager(BOX2D_SCALE, 0, GRAVITY); map = loadMap("data/maps/SebFirstPlayable_reworked.tmx"); HashMap<TileSet, Texture> tilesetImages = new HashMap(); for (TileSet tileset : map.getTileSets()) { TmxImage img = tileset.getImage(); String filename = CurrentResourceLocator.combinePaths(tileset.getFilename(), img.getSource()); tilesetImages.put(tileset, new Texture(filename)); } mapRenderer = new TiledMapRendererGdx(map, tilesetImages); // Generate static world int tileWidth = map.getTileWidth(); int tileHeight = map.getTileHeight(); RectangleGenerator generator = new RectangleGenerator(); generator.generate( map, (Layer layer, TileInfo info) -> info.getBooleanProperty("blocked", false), (Rectangle rect) -> addShape(physixManager, rect, tileWidth, tileHeight)); }
protected void loadObjectGroup(TiledMap map, Element element) { if (element.getName().equals("objectgroup")) { String name = element.getAttribute("name", null); MapLayer layer = new MapLayer(); layer.setName(name); Element properties = element.getChildByName("properties"); if (properties != null) { loadProperties(layer.getProperties(), properties); } for (Element objectElement : element.getChildrenByName("object")) { loadObject(layer, objectElement); } map.getLayers().add(layer); } }
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); 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")) { throw new GdxRuntimeException("GZIP compression not supported in GWT backend"); } else if (compression.equals("zlib")) { throw new GdxRuntimeException("ZLIB compression not supported in GWT backend"); } } 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); } }
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; 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); } // get the TextureAtlas for this tileset TextureAtlas atlas = null; String regionsName = ""; if (map.getProperties().containsKey("atlas")) { FileHandle atlasHandle = getRelativeFileHandle(tmxFile, map.getProperties().get("atlas", String.class)); atlasHandle = resolve(atlasHandle.path()); atlas = resolver.getAtlas(atlasHandle.path()); regionsName = atlasHandle.nameWithoutExtension(); 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); 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); } } 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); } map.getTileSets().addTileSet(tileset); } }
@Test public void testRealData() throws Exception { // Define projection for the test case TiledMap map = new TiledMap(492, 690, new LatLng(2.293492496, 30.538372993), 9); // Read data BufferedReader in = new BufferedReader( new InputStreamReader( GraphTest.class.getResourceAsStream("/distribscolaire-points.csv"))); double originalSum = 0; List<PointValue> points = new ArrayList<PointValue>(); while (in.ready()) { String line = in.readLine(); String[] columns = line.split(","); double lat = Double.parseDouble(columns[0]); double lng = Double.parseDouble(columns[1]); PointValue pv = new PointValue(); pv.px = map.fromLatLngToPixel(new LatLng(lat, lng)); pv.value = Double.parseDouble(columns[2]); pv.symbol = new MapSymbol(); originalSum += pv.value; points.add(pv); } // Now build the graph MarkerGraph graph = new MarkerGraph(points, new BubbleLayerGenerator.IntersectionCalculator(15)); // make sure nothing was lost in the merging of coincident points double nodeSum = 0; for (MarkerGraph.Node node : graph.getNodes()) { nodeSum += node.getPointValue().value; } Assert.assertEquals("values after construction of graph", originalSum, nodeSum, 0.001); saveGraphImage("clusterTest2", graph, 15); GeneticSolver solver = new GeneticSolver(); List<Cluster> clusters = solver.solve( graph, new GsLogCalculator(5, 15), new CircleFitnessFunctor(), UpperBoundsCalculator.calculate(graph, new FixedRadiiCalculator(5))); // check to make sure all values were included double sumAfterClustering = 0; for (Cluster cluster : clusters) { sumAfterClustering += cluster.sumValues(); } Assert.assertEquals(originalSum, sumAfterClustering, 0.001); Assert.assertEquals(16, clusters.size()); saveClusters(graph, "clusterTest-solution", clusters); }
/** * Create a new layer object * * @param node The xml node storing the information we need */ LayerObject(TiledMap map, TmxObject node, PolyMode polyMode) { this.node = node; properties = node.getProperties(); if (node.getPolygon() != null) { primitive = Primitive.POLYGON; } else if (node.getPolyline() != null) { primitive = Primitive.POLYLINE; } else if (node.getGid() != null) { primitive = Primitive.TILE; } else if (node.getWidth() == null || node.getHeight() == null) { primitive = Primitive.POINT; } else { primitive = Primitive.RECT; } x = (int) node.getX(); y = (int) node.getY(); width = (node.getWidth() == null) ? 0 : node.getWidth().intValue(); height = (node.getHeight() == null) ? 0 : node.getHeight().intValue(); if (primitive == Primitive.POLYGON || primitive == Primitive.POLYLINE) { TmxPointList pointsNode = node.getPolygon(); if (pointsNode == null) { pointsNode = node.getPolyline(); } String[] numbers = pointsNode.getPoints().split("[\\s,]"); points = new ArrayList(); lowestX = 0; lowestY = 0; for (int i = 0; i < numbers.length; i += 2) { int px = Integer.parseInt(numbers[i]); int py = Integer.parseInt(numbers[i + 1]); points.add(new Point(px, py)); if (px < lowestX) { lowestX = px; } if (py < lowestY) { lowestY = py; } } if (polyMode == PolyMode.RELATIVE_TO_TOPLEFT && (lowestX < 0 || lowestY < 0)) { for (Point p : points) { p.x += -lowestX; p.y += -lowestY; } x -= -lowestX; y -= -lowestY; } else if (polyMode == PolyMode.ABSOLUTE) { int dx = (int) node.getX(); int dy = (int) node.getY(); for (Point p : points) { p.x += dx; p.y += dy; } x = 0; y = 0; } lowestX += node.getX(); lowestY += node.getY(); } else { points = null; lowestX = (int) node.getX(); lowestY = (int) node.getY(); if (primitive == Primitive.TILE) { TileSet set = map.findTileSet(node.getGid()); if (set != null) { width = set.getTileWidth(); height = set.getTileHeight(); if (properties == null) { properties = new SafeProperties(); } properties.setDefaults(set.getTileProperties(node.getGid())); lowestY -= height; } } } }
private void loadLayer(TiledMap map, Element element) { if (element.getName().equals("Layer")) { String id = element.getAttribute("Id"); String visible = element.getAttribute("Visible"); Element dimensions = element.getChildByName("Dimensions"); String layerSize = dimensions.getAttribute("LayerSize"); String tileSize = dimensions.getAttribute("TileSize"); String[] layerSizeParts = layerSize.split(" x "); int layerSizeX = Integer.parseInt(layerSizeParts[0]); int layerSizeY = Integer.parseInt(layerSizeParts[1]); String[] tileSizeParts = tileSize.split(" x "); int tileSizeX = Integer.parseInt(tileSizeParts[0]); int tileSizeY = Integer.parseInt(tileSizeParts[1]); TiledMapTileLayer layer = new TiledMapTileLayer(layerSizeX, layerSizeY, tileSizeX, tileSizeY); Element tileArray = element.getChildByName("TileArray"); Array<Element> rows = tileArray.getChildrenByName("Row"); TiledMapTileSets tilesets = map.getTileSets(); TiledMapTileSet currentTileSet = null; int firstgid = 0; int x, y; for (int row = 0, rowCount = rows.size; row < rowCount; row++) { Element currentRow = rows.get(row); y = rowCount - 1 - row; x = 0; for (int child = 0, childCount = currentRow.getChildCount(); child < childCount; child++) { Element currentChild = currentRow.getChild(child); String name = currentChild.getName(); if (name.equals("TileSheet")) { currentTileSet = tilesets.getTileSet(currentChild.getAttribute("Ref")); firstgid = currentTileSet.getProperties().get("firstgid", Integer.class); } else if (name.equals("Null")) { x += currentChild.getIntAttribute("Count"); } else if (name.equals("Static")) { Cell cell = new Cell(); cell.setTile(currentTileSet.getTile(firstgid + currentChild.getIntAttribute("Index"))); layer.setCell(x++, y, cell); } else if (name.equals("Animated")) { // Create an AnimatedTile int interval = currentChild.getInt("Interval"); Element frames = currentChild.getChildByName("Frames"); Array<StaticTiledMapTile> frameTiles = new Array<StaticTiledMapTile>(); for (int frameChild = 0, frameChildCount = frames.getChildCount(); frameChild < frameChildCount; frameChild++) { Element frame = frames.getChild(frameChild); String frameName = frame.getName(); if (frameName.equals("TileSheet")) { currentTileSet = tilesets.getTileSet(frame.getAttribute("Ref")); firstgid = currentTileSet.getProperties().get("firstgid", Integer.class); } else if (frameName.equals("Static")) { frameTiles.add( (StaticTiledMapTile) currentTileSet.getTile(firstgid + frame.getIntAttribute("Index"))); } } Cell cell = new Cell(); cell.setTile(new AnimatedTiledMapTile(interval / 1000f, frameTiles)); layer.setCell(x++, y, cell); // TODO: Reuse existing animated tiles } } } map.getLayers().add(layer); } }
private void loadTileSheet( TiledMap map, Element element, FileHandle tideFile, ImageResolver imageResolver) { if (element.getName().equals("TileSheet")) { String id = element.getAttribute("Id"); String description = element.getChildByName("Description").getText(); String imageSource = element.getChildByName("ImageSource").getText(); Element alignment = element.getChildByName("Alignment"); String sheetSize = alignment.getAttribute("SheetSize"); String tileSize = alignment.getAttribute("TileSize"); String margin = alignment.getAttribute("Margin"); String spacing = alignment.getAttribute("Spacing"); String[] sheetSizeParts = sheetSize.split(" x "); int sheetSizeX = Integer.parseInt(sheetSizeParts[0]); int sheetSizeY = Integer.parseInt(sheetSizeParts[1]); String[] tileSizeParts = tileSize.split(" x "); int tileSizeX = Integer.parseInt(tileSizeParts[0]); int tileSizeY = Integer.parseInt(tileSizeParts[1]); String[] marginParts = margin.split(" x "); int marginX = Integer.parseInt(marginParts[0]); int marginY = Integer.parseInt(marginParts[1]); String[] spacingParts = margin.split(" x "); int spacingX = Integer.parseInt(spacingParts[0]); int spacingY = Integer.parseInt(spacingParts[1]); FileHandle image = getRelativeFileHandle(tideFile, imageSource); TextureRegion texture = imageResolver.getImage(image.path()); // TODO: Actually load the tilesheet // Need to make global ids as Tide doesn't have global ids. TiledMapTileSets tilesets = map.getTileSets(); int firstgid = 1; for (TiledMapTileSet tileset : tilesets) { firstgid += tileset.size(); } TiledMapTileSet tileset = new TiledMapTileSet(); tileset.setName(id); tileset.getProperties().put("firstgid", firstgid); int gid = firstgid; int stopWidth = texture.getRegionWidth() - tileSizeX; int stopHeight = texture.getRegionHeight() - tileSizeY; for (int y = marginY; y <= stopHeight; y += tileSizeY + spacingY) { for (int x = marginX; x <= stopWidth; x += tileSizeX + spacingX) { TiledMapTile tile = new StaticTiledMapTile(new TextureRegion(texture, x, y, tileSizeX, tileSizeY)); tile.setId(gid); tileset.putTile(gid++, tile); } } Element properties = element.getChildByName("Properties"); if (properties != null) { loadProperties(tileset.getProperties(), properties); } tilesets.addTileSet(tileset); } }