⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlmaptransformer.java

📁 tiled地图编辑器是2d的,很不错的国外软件,使用起来很方便的
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        } catch (Exception e) {            e.printStackTrace();            return obj;        }        readProperties(t.getChildNodes(), obj.getProperties());        return obj;    }    /**     * Reads properties from amongst the given children. When a "properties"     * element is encountered, it recursively calls itself with the children     * of this node. This function ensures backward compatibility with tmx     * version 0.99a.     *     * @param children the children amongst which to find properties     * @param props    the properties object to set the properties of     */    private static void readProperties(NodeList children, Properties props) {        for (int i = 0; i < children.getLength(); i++) {            Node child = children.item(i);            if ("property".equalsIgnoreCase(child.getNodeName())) {                props.setProperty(                        getAttributeValue(child, "name"),                        getAttributeValue(child, "value"));            }            else if ("properties".equals(child.getNodeName())) {                readProperties(child.getChildNodes(), props);            }        }    }    private Tile unmarshalTile(TileSet set, Node t, String baseDir)        throws Exception    {        Tile tile = null;        NodeList children = t.getChildNodes();        boolean isAnimated = false;        for (int i = 0; i < children.getLength(); i++) {            Node child = children.item(i);            if ("animation".equalsIgnoreCase(child.getNodeName())) {                isAnimated = true;                break;            }        }        try {            if (isAnimated) {                tile = (Tile)unmarshalClass(AnimatedTile.class, t);            } else {                tile = (Tile)unmarshalClass(Tile.class, t);            }        } catch (Exception e) {            logger.error("failed creating tile: "+e.getLocalizedMessage());            //e.printStackTrace();            return tile;        }        tile.setTileSet(set);        readProperties(children, tile.getProperties());        for (int i = 0; i < children.getLength(); i++) {            Node child = children.item(i);            if ("image".equalsIgnoreCase(child.getNodeName())) {                int id = getAttribute(child, "id", -1);                Image img = unmarshalImage(child, baseDir);                if (id < 0) {                    id = set.addImage(img);                }                tile.setImage(id);            } else if ("animation".equalsIgnoreCase(child.getNodeName())) {                // TODO: fill this in once XMLMapWriter is complete            }        }        return tile;    }    private MapLayer unmarshalObjectGroup(Node t) throws Exception {        ObjectGroup og = null;        try {            og = (ObjectGroup)unmarshalClass(ObjectGroup.class, t);        } catch (Exception e) {            e.printStackTrace();            return og;        }        //Read all objects from the group, "...and in the darkness bind them."        NodeList children = t.getChildNodes();        for (int i = 0; i < children.getLength(); i++) {            Node child = children.item(i);            if ("object".equalsIgnoreCase(child.getNodeName())) {                og.bindObject(unmarshalObject(child));            }        }        return og;    }    /**     * Loads a map layer from a layer node.     */    private MapLayer readLayer(Node t) throws Exception {        int layerWidth = getAttribute(t, "width", map.getWidth());        int layerHeight = getAttribute(t, "height", map.getHeight());        TileLayer ml = new TileLayer(layerWidth, layerHeight);        int offsetX = getAttribute(t, "x", 0);        int offsetY = getAttribute(t, "y", 0);        int visible = getAttribute(t, "visible", 1);        String opacity = getAttributeValue(t, "opacity");        ml.setOffset(offsetX, offsetY);        ml.setName(getAttributeValue(t, "name"));        if (opacity != null) {            ml.setOpacity(Float.parseFloat(opacity));        }        readProperties(t.getChildNodes(), ml.getProperties());        for (Node child = t.getFirstChild(); child != null;                child = child.getNextSibling())        {            if ("data".equalsIgnoreCase(child.getNodeName())) {                String encoding = getAttributeValue(child, "encoding");                if (encoding != null && "base64".equalsIgnoreCase(encoding)) {                    Node cdata = child.getFirstChild();                    if (cdata == null) {                    	logger.warn("layer <data> tag enclosed no data. (empty data tag)");                    } else {                        char[] enc = cdata.getNodeValue().trim().toCharArray();                        byte[] dec = Base64.decode(enc);                        ByteArrayInputStream bais = new ByteArrayInputStream(dec);                        InputStream is;                        String comp = getAttributeValue(child, "compression");                        if (comp != null && "gzip".equalsIgnoreCase(comp)) {                            is = new GZIPInputStream(bais);                        } else {                            is = bais;                        }                        for (int y = 0; y < ml.getHeight(); y++) {                            for (int x = 0; x < ml.getWidth(); x++) {                                int tileId = 0;                                tileId |= is.read();                                tileId |= is.read() <<  8;                                tileId |= is.read() << 16;                                tileId |= is.read() << 24;                                TileSet ts = map.findTileSetForTileGID(tileId);                                if (ts != null) {                                    ml.setTileAt(x, y,                                            ts.getTile(tileId - ts.getFirstGid()));                                } else {                                    ml.setTileAt(x, y, null);                                }                            }                        }                    }                } else {                    int x = 0, y = 0;                    for (Node dataChild = child.getFirstChild();                            dataChild != null;                            dataChild = dataChild.getNextSibling())                    {                        if ("tile".equalsIgnoreCase(dataChild.getNodeName())) {                            int tileId = getAttribute(dataChild, "gid", -1);                            TileSet ts = map.findTileSetForTileGID(tileId);                            if (ts != null) {                                ml.setTileAt(x, y,                                        ts.getTile(tileId - ts.getFirstGid()));                            } else {                                ml.setTileAt(x, y, null);                            }                            x++;                            if (x == ml.getWidth()) {                                x = 0; y++;                            }                            if (y == ml.getHeight()) { break; }                        }                    }                }            }        }        // Invisible layers are automatically locked, so it is important to        // set the layer to potentially invisible _after_ the layer data is        // loaded.        // todo: Shouldn't this be just a user interface feature, rather than        // todo: something to keep in mind at this level?        ml.setVisible(visible == 1);        return ml;    }    private void buildMap(Document doc) throws Exception {        Node item, mapNode;        mapNode = doc.getDocumentElement();        if (!"map".equals(mapNode.getNodeName())) {            throw new Exception("Not a valid tmx map file.");        }        // Get the map dimensions and create the map        int mapWidth = getAttribute(mapNode, "width", 0);        int mapHeight = getAttribute(mapNode, "height", 0);        if (mapWidth > 0 && mapHeight > 0) {            map = new Map(mapWidth, mapHeight);        } else {            // Maybe this map is still using the dimensions element            NodeList l = doc.getElementsByTagName("dimensions");            for (int i = 0; (item = l.item(i)) != null; i++) {                if (item.getParentNode() == mapNode) {                    mapWidth = getAttribute(item, "width", 0);                    mapHeight = getAttribute(item, "height", 0);                    if (mapWidth > 0 && mapHeight > 0) {                        map = new Map(mapWidth, mapHeight);                    }                }            }        }        if (map == null) {            throw new Exception("Couldn't locate map dimensions.");        }        // Load other map attributes        String orientation = getAttributeValue(mapNode, "orientation");        int tileWidth = getAttribute(mapNode, "tilewidth", 0);        int tileHeight = getAttribute(mapNode, "tileheight", 0);        if (tileWidth > 0) {            map.setTileWidth(tileWidth);        }        if (tileHeight > 0) {            map.setTileHeight(tileHeight);        }        if (orientation != null) {            setOrientation(orientation);        } else {            setOrientation("orthogonal");        }        readProperties(mapNode.getChildNodes(), map.getProperties());        // Load the tilesets, properties, layers and objectgroups        for (Node sibs = mapNode.getFirstChild(); sibs != null;                sibs = sibs.getNextSibling())        {            if ("tileset".equals(sibs.getNodeName())) {                map.addTileset(unmarshalTileset(sibs));            }            else if ("layer".equals(sibs.getNodeName())) {                MapLayer layer = readLayer(sibs);                if (layer != null) {                    map.addLayer(layer);                }            }            else if ("objectgroup".equals(sibs.getNodeName())) {                MapLayer layer = unmarshalObjectGroup(sibs);                if (layer != null) {                    map.addLayer(layer);                }            }        }    }    private Map unmarshal(InputStream in) throws IOException, Exception {        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();        Document doc;        try {            factory.setIgnoringComments(true);            factory.setIgnoringElementContentWhitespace(true);            factory.setExpandEntityReferences(false);            DocumentBuilder builder = factory.newDocumentBuilder();            doc = builder.parse(in, xmlPath);        } catch (SAXException e) {            e.printStackTrace();            throw new Exception("Error while parsing map file: " +                    e.toString());        }        buildMap(doc);        return map;    }    // MapReader interface    public Map readMap(String filename) throws Exception {        xmlPath = filename.substring(0,                filename.lastIndexOf(File.separatorChar) + 1);        String xmlFile = makeUrl(filename);        //xmlPath = makeUrl(xmlPath);        URL url = new URL(xmlFile);        InputStream is = url.openStream();        // Wrap with GZIP decoder for .tmx.gz files        if (filename.endsWith(".gz")) {            is = new GZIPInputStream(is);        }        Map unmarshalledMap = unmarshal(is);        unmarshalledMap.setFilename(filename);        return unmarshalledMap;    }    public Map readMap(InputStream in) throws Exception {        xmlPath = makeUrl(".");        Map unmarshalledMap = unmarshal(in);        //unmarshalledMap.setFilename(xmlFile)        //        return unmarshalledMap;    }    public TileSet readTileset(String filename) throws Exception {        String xmlFile = filename;        xmlPath = filename.substring(0,                filename.lastIndexOf(File.separatorChar) + 1);        xmlFile = makeUrl(xmlFile);        xmlPath = makeUrl(xmlPath);        URL url = new URL(xmlFile);        return unmarshalTilesetFile(url.openStream(), filename);    }    public TileSet readTileset(InputStream in) throws Exception {        // TODO: The MapReader interface should be changed...        return unmarshalTilesetFile(in, ".");    }    /**     * @see tiled.io.PluggableMapIO#getFilter()     */    public String getFilter() throws Exception {        return "*.tmx,*.tmx.gz,*.tsx";    }    public String getPluginPackage() {        return "Tiled internal TMX reader/writer";    }    /**     * @see tiled.io.PluggableMapIO#getDescription()     */    public String getDescription() {        return "This is the core Tiled TMX format reader\n" +            "\n" +            "Tiled Map Editor, (c) 2004-2006\n" +            "Adam Turk\n" +            "Bjorn Lindeijer";    }    public String getName() {        return "Default Tiled XML (TMX) map reader";    }    public boolean accept(File pathname) {        try {            String path = pathname.getCanonicalPath();            if (path.endsWith(".tmx") || path.endsWith(".tsx") ||                        path.endsWith(".tmx.gz")) {                return true;            }        } catch (IOException e) {}        return false;    }    public void setLogger(PluginLogger logger) {        this.logger = logger;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -