summaryrefslogtreecommitdiff
path: root/tools/tmxcopy/map.cpp
blob: 30f16a2d0bad386b031aeca715544a9355c0bcf6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
/*
 *  TMXCopy
 *  Copyright (C) 2007  Philipp Sehmisch
 *  Copyright (C) 2009  Steve Cotton
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <cstring>
#include <iostream>
#include <list>

#include <string.h>
#include <zlib.h>
#include <cassert>
#include <ctime>

#include "xmlutils.h"
#include "zlibutils.h"
#include "base64.h"
#include "tostring.h"

#include "map.hpp"

Map::Map(std::string filename):
    mMaxGid(0)
{
    std::cout<<"Loading map "<<filename<<std::endl;
    //load XML tree
    mXmlDoc = xmlReadFile(filename.c_str(), NULL, 0);

    if (!mXmlDoc)
    {
        std::cerr<<"Could not load "<<filename;
        throw 1;
    }

    xmlNodePtr rootNode = xmlDocGetRootElement(mXmlDoc);

    if (!rootNode || !xmlStrEqual(rootNode->name, BAD_CAST "map")) {
        std::cerr<<filename<<"is not a Tiled map file!";
        throw 1;
    }

    mWidth = XML::getProperty(rootNode, "width", 0);
    mHeight = XML::getProperty(rootNode, "height", 0);
    int layerNum = 0;
    for_each_xml_child_node(node, rootNode)
    {
        if (xmlStrEqual(node->name, BAD_CAST "tileset"))
        {
            //add tilesets to vector of used tilesets
            Tileset* tileset = new Tileset;
            tileset->name = XML::getProperty(node, "name", "Unnamed");
            tileset->tilewidth = XML::getProperty(node, "tilewidth", 0);
            tileset->tileheight = XML::getProperty(node, "tileheight", 0);
            tileset->firstgid = XML::getProperty(node, "firstgid", 0);
            for_each_xml_child_node(imageNode, node)
            {
                if (xmlStrEqual(imageNode->name, BAD_CAST "image"))
                tileset->imagefile = XML::getProperty(imageNode, "source", "");
            }

            //add tileset to tileset list
            Map::mTilesets.push_back(tileset);
        }
    }

    for_each_xml_child_node(node, rootNode)
    {
        if (xmlStrEqual(node->name, BAD_CAST "layer"))
        {
            //build layer information
            std::string name = XML::getProperty(node, "name", "");
            Layer* layer = new Layer(name, mWidth * mHeight);
            if (
                (mWidth  != XML::getProperty(node, "width" , 0)) ||
                (mHeight != XML::getProperty(node, "height", 0)) ||
                (0       != XML::getProperty(node, "x"     , 0)) ||
                (0       != XML::getProperty(node, "y"     , 0)))
            {
                std::cerr<<"Error: layer size does not match map size for layer \""<<name<<"\" in "<<filename<<std::endl;
                throw 1;
            }

            for_each_xml_child_node(dataNode, node)
            {
                if (!xmlStrEqual(dataNode->name, BAD_CAST "data")) continue;

                std::string encoding = XML::getProperty(dataNode, "encoding", "");
                std::string compression = XML::getProperty(dataNode, "compression", "");

                if (encoding != "base64")
                {
                    std::cerr<<"Layers in "<<filename<<" are not base64 encoded!";
                    return;
                }

                // Read base64 encoded map file
                xmlNodePtr dataChild = dataNode->xmlChildrenNode;
                if (!dataChild)
                    continue;

                int len = strlen((const char*)dataChild->content) + 1;
                unsigned char *charData = new unsigned char[len + 1];
                const char *charStart = (const char*)dataChild->content;
                unsigned char *charIndex = charData;

                while (*charStart) {
                    if (*charStart != ' ' && *charStart != '\t' &&
                            *charStart != '\n')
                    {
                        *charIndex = *charStart;
                        charIndex++;
                    }
                    charStart++;
                }
                *charIndex = '\0';

                int binLen;
                unsigned char *binData =
                    php3_base64_decode(charData, strlen((char*)charData), &binLen);

                delete[] charData;

                if (binData) {
                    if (compression == "gzip")
                    {
                        unsigned char *inflated;
                        unsigned int inflatedSize =
                            inflateMemory(binData, binLen, inflated);
                        free(binData);
                        binData = inflated;
                        binLen = inflatedSize;
                        if (inflated == NULL)
                        {
                            std::cerr<<"Error: while decompressing layer "<<layerNum<<" in "<<filename;
                            throw 1;
                        }
                    }

                    int c = 0;
                    for (int i = 0; i < binLen - 3; i += 4) {
                        int gid = binData[i] |
                            binData[i + 1] << 8 |
                            binData[i + 2] << 16 |
                            binData[i + 3] << 24;

                        if (gid == 0)
                        {
                            layer->at(c).tileset = -1;
                            layer->at(c).index = 0;
                        }
                        else
                        {
                            for (int s = mTilesets.size()-1; s >= 0; s--)
                            {
                                if (mTilesets.at(s)->firstgid <= gid)
                                {
                                    layer->at(c).tileset = s;
                                    layer->at(c).index = gid - mTilesets.at(s)->firstgid;
                                    if (mMaxGid < gid) mMaxGid = gid;
                                    break;
                                }
                            }
                        }

                        c++;
                    }
                    free(binData);
                } else {
                    std::cerr<<"error processing layer data in "<<filename<<std::endl;
                }
            }
            mLayers.push_back(layer);
            layerNum++;
        }
    }

    std::cout<<"tilesets: "<<mTilesets.size()<<std::endl;
    std::cout<<"layers:"<<mLayers.size()<<std::endl;
    std::cout<<"largest GID:"<<mMaxGid<<std::endl<<std::endl;
}

/**
 * When copying tiles from another map, add new tilesets to this map, and return the translation table.
 */
std::map<int, int> Map::addAndTranslateTilesets(const Map* srcMap)
{
    std::map<int, int> translation;
    translation[-1] = -1;
    std::vector<Tileset*>* srcTilesets = const_cast<Map*>(srcMap)->getTilesets();

    for (std::vector<Tileset*>::size_type a = 0; a < srcTilesets->size(); a++)
    {
        std::vector<Tileset*>::size_type b;
        for (b = 0; b < mTilesets.size(); b++)
        {
            if (*srcTilesets->at(a) == *mTilesets.at(b))
            {
                break;
            }
        }
        if (b == mTilesets.size())
        {
            mMaxGid += srcTilesets->at(a)->firstgid;
            Tileset* destTileset = new Tileset(*srcTilesets->at(a));
            destTileset->firstgid = mMaxGid;//it is possible to get some holes in the gid index this way but who cares, we got 32bit.
            mTilesets.push_back(destTileset);
        }
        translation[a] = b;
    }
    return translation;
}

bool Map::overwrite(  Map* srcMap,
                    int srcX, int srcY, int srcWidth, int srcHeight,
                    int destX, int destY,
                    const ConfigurationOptions& config)
{
    //plausibility check of coordinates
    bool checkPassed = true;
    if (srcX + srcWidth > srcMap->getWidth()) {
        std::cerr<<"Error: Area exceeds right map border of source map!"<<std::endl;
        checkPassed = false;
    }
    if (srcY + srcHeight > srcMap->getHeight()) {
        std::cerr<<"Error: Area exceeds lower map border of source map!"<<std::endl;
        checkPassed = false;
    }
    if (destX + srcWidth > mWidth) {
        std::cerr<<"Error: Area exceeds right map border of target map!"<<std::endl;
        checkPassed = false;
    }
    if (destY + srcHeight > mHeight) {
        std::cerr<<"Error: Area exceeds lower map border of target map!"<<std::endl;
        checkPassed = false;
    }
    if (!config.createMissingLayers)
    {
        if (config.copyLayersByOrdinal)
        {
            if (srcMap->getNumberOfLayers() > mLayers.size()) {
                std::cerr<<"Error: Source has more layers than target map"<<std::endl
                         <<"(and the command-line \"create layers\" option was not used)"<<std::endl;
                checkPassed = false;
            }
        }
        else
        {
            for (int i = 0; i < srcMap->getNumberOfLayers(); i++)
            {
                Layer* srcLayer = srcMap->getLayer(i);
                Layer* destLayer = getLayer(srcLayer->getName());
                if (!destLayer)
                {
                    std::cerr<<"Error: target map has no layer named \""<<srcLayer->getName()<<"\""<<std::endl
                         <<"(and the command-line \"create layers\" option was not used)"<<std::endl;
                    checkPassed = false;
                }
            }
        }
    }

    if (!checkPassed) return false;

    std::map<int, int> translation = addAndTranslateTilesets(srcMap);


    //combining layer information
    for (int i = 0; i < srcMap->getNumberOfLayers(); i++)
    {
        Layer* srcLayer = srcMap->getLayer(i);
        Layer* destLayer = NULL;
        if (config.copyLayersByOrdinal)
        {
            if (i < mLayers.size())
            {
                destLayer = mLayers.at(i);
            }
        }
        else
        {
            destLayer = getLayer(srcLayer->getName());
        }

        if (!destLayer)
        {
            assert(config.createMissingLayers); /* Tested earlier, in the checkPassed section */
            /* Generate a name for the new layer, which must be
             * unique in the target map, and should be unique in
             * the source map (to avoid collisions later in the
             * copying process).
             * Start by trying the name of the source layer.
             */
            std::string name = srcLayer->getName();
            if (getLayer(name))
            {
                int k=0;
                do
                {
                    name = "Layer" + toString(k);
                    k++;
                } while (getLayer(name) || srcMap->getLayer(name));
            }

            destLayer = new Layer(name, mWidth * mHeight);
            mLayers.push_back(destLayer);
            std::cout<<"Created new layer "<<name<<std::endl;
        }

        for (int y=0; y<srcHeight; y++)
        {

            for (int x=0; x<srcWidth; x++)
            {
                int srcIndex = srcMap->getWidth() * (y + srcY) + (x + srcX);
                int tgtIndex = mWidth * (y + destY) + (x + destX);
                Tile tmpTile = srcLayer->at(srcIndex);
                tmpTile.tileset = translation[tmpTile.tileset];
                destLayer->at(tgtIndex) = tmpTile;
            }
        }
    }

    std::clog<<"copying successful!"<<std::endl;
    return true;
}

bool Map::randomFill(Map* templateMap, const std::string& destLayerName,
            int destX, int destY, int destWidth, int destHeight,
            const ConfigurationOptions& config)
{
    //plausibility check of coordinates
    bool checkPassed = true;
    if (destX + destWidth > mWidth)
    {
        std::cerr<<"Error: Area exceeds right map border of target map!"<<std::endl;
        checkPassed = false;
    }
    if (destY + destHeight > mHeight)
    {
        std::cerr<<"Error: Area exceeds lower map border of target map!"<<std::endl;
        checkPassed = false;
    }
    if (destWidth < templateMap->getWidth())
    {
        std::cerr<<"Error: Template is wider than target area"<<std::endl;
        checkPassed = false;
    }
    if (destWidth < templateMap->getHeight())
    {
        std::cerr<<"Error: Template is higher than target area"<<std::endl;
        checkPassed = false;
    }
    if (templateMap->getNumberOfLayers() == 0)
    {
        std::cerr<<"Error: Template has no layers"<<std::endl;
        checkPassed = false;
    }
    if (!config.createMissingLayers && !getLayer(destLayerName))
    {
        std::cerr<<"Error: target map has no layer named \""<<destLayerName<<"\""<<std::endl
             <<"(and the command-line \"create layers\" option was not used)"<<std::endl;
        checkPassed = false;
    }
    if (!checkPassed) return false;

    std::map<int, int> translation = addAndTranslateTilesets(templateMap);


    Layer* destLayer = getLayer(destLayerName);
    if (!destLayer)
    {
        destLayer = new Layer(destLayerName, mWidth * mHeight);
        mLayers.push_back(destLayer);
        std::cout<<"Created new layer "<<destLayerName<<std::endl;
    }

    /* Now generate extra tiles.
     * TODO Need to configure this for desired density.  For 2x1 trees, dW*dH/10 is very sparse, dW*dH/2 is dense */
    srand(time(NULL));
    for (int i = destWidth*destHeight / 10; i > 0; i--)
    {
        /* Pick a random location, with enough tiles left and down from it to
         * fit the template in (the +1 is because it starts on tile (x,y))
         */
        int x = destX + (rand() % (destWidth  - templateMap->getWidth () + 1));
        int y = destY + (rand() % (destHeight - templateMap->getHeight() + 1));

        bool areaIsClear = true;

        for (int loop_y=0; loop_y<templateMap->getHeight(); loop_y++)
        {
            for (int loop_x=0; loop_x<templateMap->getWidth(); loop_x++)
            {
                if (! destLayer->getTile(x+loop_x, y+loop_y, mWidth).empty())
                {
                    areaIsClear = false;
                }
            }
        }

        if (areaIsClear)
        {
            int p = rand() % templateMap->getNumberOfLayers();
            std::cout <<"Copying pattern "<<p<<" to "<<x<<", "<<y<<std::endl;

            Layer* srcLayer = templateMap->getLayer(p);
            for (int loop_y=0; loop_y<templateMap->getHeight(); loop_y++)
            {
                for (int loop_x=0; loop_x<templateMap->getWidth(); loop_x++)
                {
                    Tile& srcTile  = srcLayer->getTile(loop_x, loop_y, templateMap->getWidth());
                    Tile& destTile = destLayer->getTile(x+loop_x, y+loop_y, mWidth);
                    destTile.tileset = translation[srcTile.tileset];
                    destTile.index = srcTile.index;
                }
            }
        }
        else
        {
            std::cout <<"Area occupied "<<x<<", "<<y<<std::endl;
        }
    }

    std::clog<<"copying successful!"<<std::endl;
    return true;
}



int Map::save(std::string filename)
{
    //remove old tileset and layer information in XML tree
    xmlNodePtr rootNode = xmlDocGetRootElement(mXmlDoc);
    std::list<xmlNodePtr> toRemove;
    for_each_xml_child_node(node, rootNode)
    {
        if (    xmlStrEqual(node->name, BAD_CAST "tileset")
            ||  xmlStrEqual(node->name, BAD_CAST "layer"))
        {
            toRemove.push_back(node);
        }
    }

    while (!toRemove.empty())
    {
        xmlUnlinkNode(toRemove.back());
        xmlFreeNode(toRemove.back());
        toRemove.pop_back();
    }

    //TODO: reorganize GIDs

    //add new tileset information to XML tree
    for (int i = 0; i< mTilesets.size(); i++)
    {
        xmlNodePtr newNode;

        xmlAddChild(rootNode, xmlNewDocText(mXmlDoc, BAD_CAST " "));
        newNode = xmlNewNode(NULL, BAD_CAST "tileset");
        xmlNewProp(newNode, BAD_CAST "name", BAD_CAST mTilesets.at(i)->name.c_str());
        xmlNewProp(newNode, BAD_CAST "firstgid", BAD_CAST toString(mTilesets.at(i)->firstgid).c_str());
        xmlNewProp(newNode, BAD_CAST "tilewidth", BAD_CAST toString(mTilesets.at(i)->tilewidth).c_str());
        xmlNewProp(newNode, BAD_CAST "tileheight", BAD_CAST toString(mTilesets.at(i)->tileheight).c_str());
        xmlAddChild(newNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n  "));
        xmlNodePtr imageNode = xmlNewNode(NULL, BAD_CAST "image");
        xmlNewProp(imageNode, BAD_CAST "source", BAD_CAST mTilesets.at(i)->imagefile.c_str());
        xmlAddChild(newNode, imageNode);
        xmlAddChild(newNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n "));
        xmlAddChild(rootNode, newNode);
        xmlAddChild(rootNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n"));
    }

    //add new layer information to XML tree
    for (int i = 0; i < mLayers.size(); i++)
    {
        //lay out layer information in binary
        unsigned char* binData = (unsigned char*)malloc(mWidth * mHeight * 4);

        for (int a=0; a < mWidth * mHeight; a++)
        {
            Tile tile = mLayers.at(i)->at(a);
            int ldata;
            if (tile.tileset != -1)
            {
                ldata = tile.index + mTilesets.at(tile.tileset)->firstgid;
            } else {
                ldata = 0;
            }

            binData[a * 4 + 0] = (ldata & 0x000000ff);
            binData[a * 4 + 1] = (ldata & 0x0000ff00) >> 8;
            binData[a * 4 + 2] = (ldata & 0x00ff0000) >> 16;
            binData[a * 4 + 3] = (ldata & 0xff000000) >> 24;
        }


        //GZIP layer information
        /*
        unsigned char* gzipData = (unsigned char*)malloc((mWidth * mHeight * 4) + 128);
        unsigned int gzipLen;
        compressMemory (binData, (mWidth * mHeight * 4) + 128, gzipData, gzipLen);
        free (binData);
        std::cout<<"GZIP length: "<<gzipLen<<std::endl;
        */

        //encode layer information in base64
        unsigned char* base64Data;
        int base64len;
        //base64Data = php3_base64_encode(gzipData, gzipLen, &base64len);
        base64Data = php3_base64_encode(binData, (mWidth * mHeight * 4), &base64len);
        //free(gzipData);

        xmlNodePtr newNode;
        xmlAddChild(rootNode, xmlNewDocText(mXmlDoc, BAD_CAST " "));
        newNode = xmlNewNode(NULL, BAD_CAST "layer");
        xmlNewProp(newNode, BAD_CAST "name", BAD_CAST (mLayers.at(i)->getName()).c_str());
        xmlNewProp(newNode, BAD_CAST "width", BAD_CAST toString(mWidth).c_str());
        xmlNewProp(newNode, BAD_CAST "height", BAD_CAST toString(mHeight).c_str());
        xmlAddChild(newNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n  "));
        xmlNodePtr dataNode = xmlNewNode(NULL, BAD_CAST "data");
        xmlNewProp(dataNode, BAD_CAST "encoding", BAD_CAST "base64");
        //xmlNewProp(dataNode, BAD_CAST "compression", BAD_CAST "gzip");
        xmlAddChild(dataNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n   "));
        xmlAddChild(dataNode, xmlNewDocText(mXmlDoc, BAD_CAST base64Data));
        xmlAddChild(dataNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n  "));
        xmlAddChild(newNode, dataNode);
        xmlAddChild(newNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n "));
        xmlAddChild(rootNode, newNode);
        xmlAddChild(rootNode, xmlNewDocText(mXmlDoc, BAD_CAST "\n"));

        free(base64Data);
        free(binData);
    }

    //save XML tree
    int retval = xmlSaveFile(filename.c_str(), mXmlDoc);

    if (retval == -1)
    {
        std::cerr<<"Could not write outfile "<<filename<<std::endl;
        return false;
    }
    else
    {
        std::cout<<"File saved successfully to "<<filename<<std::endl;
        return true;
    }
}

Layer* Map::getLayer(std::string name)
{
    for (std::vector<Layer*>::iterator layer = mLayers.begin();
         layer != mLayers.end();
         layer++)
    {
        if ((*layer)->getName() == name)
            return *layer;
    }
    return NULL;
}

Map::~Map()
{
    for (std::vector<Layer*>::iterator layer = mLayers.begin();
         layer != mLayers.end();
         layer++)
    {
         delete *layer;
    }

    for (std::vector<Tileset*>::iterator tileset = mTilesets.begin();
         tileset != mTilesets.end();
         tileset++)
    {
         delete *tileset;
    }

    xmlFreeDoc(mXmlDoc);
}