-
Notifications
You must be signed in to change notification settings - Fork 4
/
TMXGenerator.m
887 lines (730 loc) · 31.8 KB
/
TMXGenerator.m
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
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
* TMXGenerator.m
*
* Created by Jeremy Stone on 3/19/11.
* Copyright (c) 2011 Stone Software.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#import "TMXGenerator.h"
#import "LFCGzipUtility.h"
#import "cencode.h"
#define kFlippedHorizontallyFlag 0x80000000
#define kFlippedVerticallyFlag 0x40000000
#define kFlippedAntiDiagonallyFlag 0x20000000
#define kFlippedMask ~(kFlippedHorizontallyFlag|kFlippedVerticallyFlag|kFlippedAntiDiagonallyFlag)
@interface TMXGenerator ()
- (void) addMapAttributesWithPath:(NSString*)inPath width:(int)width height:(int)height tileWidth:(int)widthInPixels tileHeight:(int)heightInPixels orientation:(NSString*)orientation properties:(NSDictionary*)properties;
- (void) addLayerNamed:(NSString*)layerName width:(int)width height:(int)height data:(NSData*)binaryLayerData visible:(BOOL)isVisible;
- (BOOL) addTilesetWithImage:(NSString*)imgName named:(NSString*)name width:(int)width height:(int)height tileSpacing:(int)spacing tileProperties:(NSDictionary*)properties;
- (void) addObjectGroupNamed:(NSString*)name width:(int)width height:(int)height objectList:(NSArray*)objects;
@end
@implementation TMXGenerator
@synthesize delegate = delegate_;
- (id) init
{
self = [super init];
if (self != nil)
{
highestGID = 0;
tileSets = nil;
path = nil;
mapAttributes = nil;
layers = nil;
delegate_ = nil;
}
return self;
}
//- (void) dealloc
//{
// [tileSets release];
// [mapAttributes release];
// [layers release];
// [path release];
// [copiedAtlasNames release];
// [objectGroups release];
//
// [delegate_ release];
//
// [super dealloc];
//}
#pragma mark -
- (void) addMapAttributesWithPath:(NSString*)inPath width:(int)width height:(int)height tileWidth:(int)widthInPixels tileHeight:(int)heightInPixels orientation:(NSString*)orientation properties:(NSDictionary*)properties
{
// if (mapAttributes)
// [mapAttributes release];
mapAttributes = [[NSMutableDictionary alloc] initWithCapacity:5];
[mapAttributes setObject:[NSString stringWithFormat:@"%i", width] forKey:kTMXGeneratorHeaderInfoMapWidth];
[mapAttributes setObject:[NSString stringWithFormat:@"%i", height] forKey:kTMXGeneratorHeaderInfoMapHeight];
[mapAttributes setObject:[NSString stringWithFormat:@"%i", widthInPixels] forKey:kTMXGeneratorHeaderInfoMapTileWidth];
[mapAttributes setObject:[NSString stringWithFormat:@"%i", heightInPixels] forKey:kTMXGeneratorHeaderInfoMapTileHeight];
if (orientation)
[mapAttributes setObject:orientation forKey:kTMXGeneratorHeaderInfoMapOrientation];
if (properties)
[mapAttributes setObject:properties forKey:kTMXGeneratorHeaderInfoMapProperties];
// if (path)
// [path release];
path = [[NSString alloc] initWithString:inPath];
}
/*
binary layer data is filled with GID's (unsigned int each), coords going left top to right
bottom. i.e. (0,0) (1,0) (2,0) (3,0) (0,1) (1,1) (2,1) (3,1) (0,2) (1,2) (2,2) (3,2)...
see this link: http://sourceforge.net/apps/mediawiki/tiled/index.php?title=Examining_the_map_format
*/
- (void) addLayerNamed:(NSString*)layerName width:(int)width height:(int)height data:(NSData*)binaryLayerData visible:(BOOL)isVisible
{
NSDictionary* dict = [TMXGenerator layerNamed:layerName width:width height:height data:binaryLayerData visible:isVisible];
if (!layers)
layers = [[NSMutableArray alloc] initWithCapacity:10];
[layers addObject:dict];
}
/*
add a new tileset to our class.
Properties are individual tile properties and are in standard dictionary key-value format.
They are indexed by tile offset. So the top-left tile in your designated tile atlas would be
tile 0, tile 1 would be the tile just to the right of tile 0 and so forth, wrapping at the
right edge of the tile.
**NOTE: values need to be NSStrings for these properties!
*/
- (BOOL) addTilesetWithDictionary:(NSDictionary*)tileAttributes tileProperties:(NSDictionary*)properties
{
highestGID++;
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithDictionary:tileAttributes];
[dict setObject:[NSString stringWithFormat:@"%i", highestGID] forKey:kTMXGeneratorTilesetGIDStart];
// add properties
if (properties)
{
[dict setObject:properties forKey:kTMXGeneratorTileProperties];
}
// figure out the highest GID possible and set our max GIDs used for the next possible texture map
#ifdef __IPHONE_OS_VERSION_MAX_ALLOWED
UIImage* img = [UIImage imageNamed:[dict objectForKey:kTMXGeneratorTileSetImageAtlasFilename]];
CGSize imgSize = img.size;
#elif defined(__MAC_OS_X_VERSION_MAX_ALLOWED)
NSImage* img = [NSImage imageNamed:[dict objectForKey:kTMXGeneratorTileSetImageAtlasFilename]];
CGSize imgSize = NSSizeToCGSize( img.size );
#endif
if (img)
{
int width = [[dict objectForKey:kTMXGeneratorImageAtlasTileWidth] intValue];
int height = [[dict objectForKey:kTMXGeneratorImageAtlasTileHeight] intValue];
int spacing = [[dict objectForKey:kTMXGeneratorImageAtlasTileSpacing] intValue];
int across = imgSize.width / (width + spacing);
int down = imgSize.height / (height + spacing);
highestGID += across * down;
// add the dictionary to our tileset list.
if (!tileSets)
tileSets = [[NSMutableDictionary alloc] initWithCapacity:20];
NSString* name = [dict objectForKey:kTMXGeneratorTileSetName];
if (name)
[tileSets setObject:dict forKey:name];
else
return NO;
return YES;
}
return NO;
}
// helper function, turns out I would rather pass in a dictionary, but this may prove helpful later...
- (BOOL) addTilesetWithImage:(NSString*)imgName named:(NSString*)name width:(int)width height:(int)height tileSpacing:(int)spacing tileProperties:(NSDictionary*)properties
{
NSDictionary* dict = [TMXGenerator tileSetWithImage:imgName named:name width:width height:height tileSpacing:spacing];
return [self addTilesetWithDictionary:dict tileProperties:properties];
}
/*
the objects variable should have > 0 objects in it. Valid object keys include:
"name", "x", "y", "width", "height", "type", and an array of key/value entries named "properties" (with the keys "name" and "value").
Example:
<objectgroup name="Object Layer 1" width="32" height="32">
... // object here
</objectgroup>
*/
- (void) addObjectGroupNamed:(NSString*)name width:(int)width height:(int)height objectList:(NSArray*)objects
{
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:10];
if (!objectGroups)
objectGroups = [[NSMutableArray alloc] initWithCapacity:10];
[dict setObject:name forKey:kTMXGeneratorObjectGroupName];
[dict setObject:[NSString stringWithFormat:@"%i", width] forKey:kTMXGeneratorObjectGroupWidth];
[dict setObject:[NSString stringWithFormat:@"%i", height] forKey:kTMXGeneratorObjectGroupHeight];
[dict setObject:objects forKey:kTMXGeneratorObjectGroupProperties];
[objectGroups addObject:dict];
}
- (NSString*) tileIDFromTileSet:(NSDictionary*)tileset thatMatchesKey:(NSString*)tileKeyVal property:(NSString*)tilePropertyVal
{
NSDictionary* properties = [tileset objectForKey:kTMXGeneratorTileProperties];
if (properties)
{
for (id propertyKey in [properties allKeys])
{
NSDictionary* dict = [properties objectForKey:propertyKey];
NSString* str = [dict objectForKey:tileKeyVal];
if (str && [tilePropertyVal isEqualToString:str])
return propertyKey;
}
}
return nil;
}
#pragma mark -
+ (NSString*) propertiesToXML:(NSDictionary*)properties
{
NSMutableString* retVal = [NSMutableString string];
if (!properties)
return retVal;
[retVal appendString:@"<properties>\r"];
for (NSString* valueKey in [properties allKeys])
{
[retVal appendFormat:@"<property name=\"%@\" value=\"%@\"/>\r", valueKey, [properties objectForKey:valueKey]];
}
[retVal appendString:@"</properties>\r"];
return retVal;
}
+ (NSString*) objectGroupsToXML:(NSArray*)groups
{
NSMutableString* retVal = [NSMutableString string];
// convert the passed in array to an array of objects XML.
for (NSDictionary* group in groups)
{
[retVal appendFormat:@"<objectgroup name=\"%@\" width=\"%@\" height=\"%@\">\r", [group objectForKey:kTMXGeneratorObjectGroupName], [group objectForKey:kTMXGeneratorObjectGroupWidth], [group objectForKey:kTMXGeneratorObjectGroupHeight]];
NSArray* objects = [group objectForKey:kTMXGeneratorObjectGroupProperties];
for (NSDictionary* dict in objects)
{
[retVal appendFormat:@"<object name=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectName]];
if ([dict objectForKey:kTMXGeneratorGroupObjectType])
[retVal appendFormat:@" type=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectType]];
if ([dict objectForKey:kTMXGeneratorGroupObjectX])
[retVal appendFormat:@" x=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectX]];
if ([dict objectForKey:kTMXGeneratorGroupObjectY])
[retVal appendFormat:@" y=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectY]];
if ([dict objectForKey:kTMXGeneratorGroupObjectWidth])
[retVal appendFormat:@" width=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectWidth]];
if ([dict objectForKey:kTMXGeneratorGroupObjectHeigth])
[retVal appendFormat:@" height=\"%@\"", [dict objectForKey:kTMXGeneratorGroupObjectHeigth]];
[retVal appendString:@">\r"];
if ([dict objectForKey:kTMXGeneratorGroupObjectProperties])
[retVal appendString:[TMXGenerator propertiesToXML:[dict objectForKey:kTMXGeneratorGroupObjectProperties]]];
[retVal appendString:@"</object>"];
}
[retVal appendString:@"</objectgroup>\r"];
}
return retVal;
}
+ (NSString*) layersToXML:(NSArray*)inLayers
{
NSMutableString* retVal = [NSMutableString string];
// convert the passed in array to an array of layer XML.
for (NSDictionary* dict in inLayers)
{
// this will be where we zip and encode layers.
// layers should be dictionaries.
// if ([dict objectForKey:kTMXGeneratorLayerIsVisible]) // making the layer invisible causes the TMX map to not load it! :/
// [retVal appendFormat:@"<layer name=\"%@\" width=\"%@\" height=\"%@\" visible=\"%@\">\r", [dict objectForKey:kTMXGeneratorLayerName], [dict objectForKey:kTMXGeneratorLayerWidth], [dict objectForKey:kTMXGeneratorLayerHeight], [dict objectForKey:kTMXGeneratorLayerIsVisible]];
// else
[retVal appendFormat:@"<layer name=\"%@\" width=\"%@\" height=\"%@\">\r", [dict objectForKey:kTMXGeneratorLayerName], [dict objectForKey:kTMXGeneratorLayerWidth], [dict objectForKey:kTMXGeneratorLayerHeight]];
[retVal appendString:@"<data encoding=\"base64\" compression=\"gzip\">\r"];
NSData *bufferData = [dict objectForKey:kTMXGeneratorLayerData];
if (bufferData)
{
NSData *data = [LFCGzipUtility gzipData:bufferData];
NSUInteger len = [data length];
char* byteData = (char*)malloc(len);
memcpy(byteData, [data bytes], len);
char* encodedStr = base64_encode(byteData, len);
[retVal appendFormat:@"%s\r</data>\r", encodedStr];
// rotation XML. See http://www.cocos2d-iphone.org/forum/topic/16552
bufferData = [dict objectForKey:kTMXGeneratorLayerRotationData];
if (bufferData)
{
[retVal appendString:@"<rotation_data encoding=\"base64\" compression=\"gzip\">\r"];
data = [LFCGzipUtility gzipData:bufferData];
len = [data length];
char* byteData2 = (char*)malloc(len);
memcpy(byteData2, [data bytes], len);
encodedStr = base64_encode(byteData2, len);
[retVal appendFormat:@"%s\r</rotation_data>\r", encodedStr];
free(byteData2);
}
[retVal appendString:@"</layer>\r"];
free(encodedStr);
free(byteData);
}
}
return retVal;
}
/*
Attributes include:
kTMXGeneratorImageAtlasTileWidth (width)
kTMXGeneratorImageAtlasTileHeight (height)
kTMXGeneratorImageAtlasTileSpacing (tiles are spaced apart this amount of pixels in the atlas image)
kTMXGeneratorTilesetGIDStart (first GID used in the tileset)
kTMXGeneratorTilesetName (tileset name)
kTMXGeneratorTileSetImageAtlasFilename (filename of image atlas)
example tileset XML:
<tileset firstgid="1" name="Test Tileset" tilewidth="32" tileheight="32" spacing="2">
<image source="regularTiles_default.png"/>
<tile id="0">
<properties>
<property name="Grass Property" value=""/>
<property name="type" value="1"/>
</properties>
</tile>
<tile id="8">
<properties>
<property name="ocean" value=""/>
<property name="type" value="1"/>
</properties>
</tile>
</tileset>
*/
+ (NSString*) tileSetsToXML:(NSDictionary*)inTileSets
{
NSMutableString* retVal = [NSMutableString string];
// iterate through each key and generate a tileset named the same as the key name of the dictionary for the tilesets.
NSArray* keys = [inTileSets allKeys];
for (id key in keys)
{
NSDictionary* dict = [inTileSets objectForKey:key];
if (dict)
{
[retVal appendFormat:@"<tileset firstgid=\"%i\"", [[dict objectForKey:kTMXGeneratorTilesetGIDStart] intValue]];
[retVal appendFormat:@" name=\"%@\"", [dict objectForKey:kTMXGeneratorTileSetName]];
[retVal appendFormat:@" tilewidth=\"%i\"", [[dict objectForKey:kTMXGeneratorImageAtlasTileWidth] intValue]];
[retVal appendFormat:@" tileheight=\"%i\"", [[dict objectForKey:kTMXGeneratorImageAtlasTileHeight] intValue]];
[retVal appendFormat:@" spacing=\"%i\"", [[dict objectForKey:kTMXGeneratorImageAtlasTileSpacing] intValue]];
[retVal appendString:@">\r"];
[retVal appendFormat:@"<image source=\"%@\"/>\r", [dict objectForKey:kTMXGeneratorTileSetImageAtlasFilename]];
// properties
NSDictionary* properties = [dict objectForKey:kTMXGeneratorTileProperties];
if (properties)
{
for (id propertyKey in [properties allKeys])
{
[retVal appendFormat:@"<tile id=\"%@\">\r", propertyKey];
[retVal appendString:[TMXGenerator propertiesToXML:[properties objectForKey:propertyKey]]];
[retVal appendString:@"</tile>\r"];
}
}
[retVal appendString:@"</tileset>\r"];
}
}
return retVal;
}
+ (NSString*) XMLWithAttributes:(NSDictionary*)mapAttributes tilesets:(NSDictionary*)inTileSets layers:(NSArray*)inLayers objectGroups:(NSArray*)inObjectGroups
{
NSMutableString* outStr = [NSMutableString stringWithString:@"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r<!DOCTYPE map SYSTEM \"http://mapeditor.org/dtd/1.0/map.dtd\">\r"];
// map header details
NSString* orientation = @"orthogonal";
if ([mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapOrientation])
orientation = [mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapOrientation];
[outStr appendFormat:@"<map version=\"1.0\" orientation=\"%@\" ", orientation];
// width and height (for now always square)
int width = [[mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapWidth] intValue];
int height = [[mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapHeight] intValue];
[outStr appendFormat:@"width=\"%i\" height=\"%i\" ", width, height];
// tile width and height for map
int tileWidth = [[mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapTileWidth] intValue];
int tileHeight = [[mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapTileHeight] intValue];
[outStr appendFormat:@"tilewidth=\"%i\" tileheight=\"%i\">\r", tileWidth, tileHeight];
// map properties
NSDictionary* properties = [mapAttributes objectForKey:kTMXGeneratorHeaderInfoMapProperties];
if (properties)
[outStr appendString:[TMXGenerator propertiesToXML:properties]];
// append the tilesets
[outStr appendString:[TMXGenerator tileSetsToXML:inTileSets]];
// append the layers
[outStr appendString:[TMXGenerator layersToXML:inLayers]];
// append the object groups
[outStr appendString:[TMXGenerator objectGroupsToXML:inObjectGroups]];
// close map tag
[outStr appendString:@"\r</map>"];
return [NSString stringWithString:outStr];
}
/*
mapAttributes is a dictionary with the following attributes:
kTMXGeneratorHeaderInfoMapWidth - how many tiles wide
kTMXGeneratorHeaderInfoMapHeight - how many tiles high
kTMXGeneratorHeaderInfoMapTileWidth - tile width in pixels
kTMXGeneratorHeaderInfoMapTileHeight - tile height in pixels
optional:
kTMXGeneratorHeaderInfoMapOrientation - tile orientation, default is @"orthogonal", @"isometric" also supported by cocos2d
tileSets is a dictionary of named tilesets (dictionaries of tileset attributes, including properties)
layers is an NSArray of layer information dictionaries.
*/
+ (void) writeTMXFileWithXML:(NSString*)xml fileName:(NSString*)filePath
{
if (xml)
[xml writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
}
#pragma mark -
#pragma mark helper functions
// create layer information.
// binaryLayerData can be nil
+ (NSDictionary*) layerNamed:(NSString*)layerName width:(int)width height:(int)height data:(NSData*)binaryLayerData visible:(BOOL)isVisible
{
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:4];
[dict setObject:layerName forKey:kTMXGeneratorLayerName];
[dict setObject:[NSString stringWithFormat:@"%i", width] forKey:kTMXGeneratorLayerWidth];
[dict setObject:[NSString stringWithFormat:@"%i", height] forKey:kTMXGeneratorLayerHeight];
if (isVisible == NO)
[dict setObject:@"0" forKey:kTMXGeneratorLayerIsVisible];
if (binaryLayerData)
[dict setObject:binaryLayerData forKey:kTMXGeneratorLayerData];
return dict;
}
+ (NSDictionary*) tileSetWithImage:(NSString*)imgName named:(NSString*)name width:(int)width height:(int)height tileSpacing:(int)spacing
{
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:20];
[dict setObject:imgName forKey:kTMXGeneratorTileSetImageAtlasFilename];
[dict setObject:name forKey:kTMXGeneratorTileSetName];
[dict setObject:[NSString stringWithFormat:@"%i", width] forKey:kTMXGeneratorImageAtlasTileWidth];
[dict setObject:[NSString stringWithFormat:@"%i", height] forKey:kTMXGeneratorImageAtlasTileHeight];
[dict setObject:[NSString stringWithFormat:@"%i", spacing] forKey:kTMXGeneratorImageAtlasTileSpacing];
return dict;
}
/*
Object Groups contain objects (non-tile entities). These can represent things like triggers, spawn points, etc.
Name, x and y value required.
Example:
<object name="asdf" type="whee" x="484" y="283" width="45" height="46">
<properties>
<property name="property1" value="prop"/>
</properties>
</object>
*/
+ (NSDictionary*) makeObjectWithName:(NSString*)name type:(NSString*)type x:(int)x y:(int)y width:(int)width height:(int)height properties:(NSDictionary*)properties
{
NSMutableDictionary* dict = [NSMutableDictionary dictionaryWithCapacity:10];
[dict setObject:name forKey:kTMXGeneratorGroupObjectName];
[dict setObject:[NSString stringWithFormat:@"%i", x] forKey:kTMXGeneratorGroupObjectX];
[dict setObject:[NSString stringWithFormat:@"%i", y] forKey:kTMXGeneratorGroupObjectY];
if (type)
[dict setObject:type forKey:kTMXGeneratorGroupObjectType];
if (width)
[dict setObject:[NSString stringWithFormat:@"%i", width] forKey:kTMXGeneratorGroupObjectWidth];
if (height)
[dict setObject:[NSString stringWithFormat:@"%i", height] forKey:kTMXGeneratorGroupObjectHeigth];
if (properties)
[dict setObject:properties forKey:kTMXGeneratorGroupObjectProperties];
return dict;
}
#pragma mark -
- (NSString*) generateMapXML:(NSError**)error
{
if (!delegate_)
{
if (error)
*error = [NSError errorWithDomain:@"Unable to get delegate when calling generateMapXML:" code:0 userInfo:nil];
return nil;
}
NSDictionary* mapInfo = [delegate_ mapAttributeSetup];
if (!mapInfo)
{
if (error)
*error = [NSError errorWithDomain:@"Unable to get basic map info when calling delegate method mapAttributeSetup" code:0 userInfo:nil];
return nil;
}
int mapWidth = [[mapInfo objectForKey:kTMXGeneratorHeaderInfoMapWidth] intValue];
int mapHeight = [[mapInfo objectForKey:kTMXGeneratorHeaderInfoMapHeight] intValue];
NSArray* tileSetNames = nil;
if ([delegate_ respondsToSelector:@selector(tileSetNames)])
tileSetNames = [delegate_ tileSetNames];
else
tileSetNames = [NSArray arrayWithObject:kTMXGeneratorDefaultTilesetName];
if (!tileSetNames || ![tileSetNames count])
{
if (error)
*error = [NSError errorWithDomain:@"Unable to get any tileset names when calling delegate method tileSetNames" code:0 userInfo:nil];
return nil;
}
// add our tilesets
NSString* key;
for (key in tileSetNames)
{
NSDictionary* dict = [delegate_ tileSetInfoForName:key];
if (!dict)
{
if (error)
*error = [NSError errorWithDomain:[NSString stringWithFormat:@"Unable to get tileset from name %@ when calling delegate method tileSetInfoForName:", key] code:0 userInfo:nil];
return nil;
}
NSDictionary* properties = nil;
if ([delegate_ respondsToSelector:@selector(propertiesForTileSetNamed:)])
properties = [delegate_ propertiesForTileSetNamed:key];
[self addTilesetWithDictionary:dict tileProperties:properties];
}
NSArray* layerNames;
if ([delegate_ respondsToSelector:@selector(layerNames)])
layerNames = [delegate_ layerNames];
else
layerNames = [NSArray arrayWithObject:kTMXGeneratorDefaultLayerName];
if (!layerNames || ![layerNames count])
{
if (error)
*error = [NSError errorWithDomain:@"Unable to get any layer names when calling delegate method layerNames" code:0 userInfo:nil];
return nil;
}
// add our layers
NSString* tilePropertyVal;
NSString* tileKeyVal = nil;
unsigned int mapData[mapHeight][mapWidth];
for (key in layerNames)
{
NSDictionary* dict = [delegate_ layerInfoForName:key];
if (!dict)
{
if (error)
*error = [NSError errorWithDomain:[NSString stringWithFormat:@"Unable to get layer from name %@ when calling delegate method layerInfoForName:", key] code:0 userInfo:nil];
return nil;
}
BOOL hasData = NO;
NSString* tileSetName = kTMXGeneratorDefaultTilesetName;
if ([delegate_ respondsToSelector:@selector(tileSetNameForLayer:)])
tileSetName = [delegate_ tileSetNameForLayer:key];
NSDictionary* tileSetForLayer = [tileSets objectForKey:tileSetName];
int startGid = [[tileSetForLayer objectForKey:kTMXGeneratorTilesetGIDStart] intValue];
// if we are assigning GIDs via the tile properties and have the appropriate delegates then set that key up here.
if ([delegate_ respondsToSelector:@selector(tileIdentificationKeyForLayer:)] &&
[delegate_ respondsToSelector:@selector(tilePropertyForLayer:tileSetName:X:Y:)])
{
tileKeyVal = [delegate_ tileIdentificationKeyForLayer:key];
}
// if we are not using properties then we should be using custom GIDs
BOOL customGIDs = [delegate_ respondsToSelector:@selector(tileGIDForLayer:tileSetName:X:Y:)];
// check for delegate creation setup. Return an error if this is incorrect.
if (!customGIDs && !tileKeyVal)
{
if (error)
*error = [NSError errorWithDomain:@"No way to know how to assign GIDs in generateMapXML! Set up your delegate!" code:0 userInfo:nil];
return nil;
}
for (int y = 0; y < mapHeight; y++)
{
for (int x = 0; x < mapWidth; x++)
{
int GID = startGid; // default to the first atlas tile for each layer
if (customGIDs)
{
int val = [delegate_ tileGIDForLayer:key tileSetName:tileSetName X:x Y:y];
if (val >= 0)
GID += val;
else
GID = 0;
}
else
{
if (tileKeyVal)
{
// get the tileset name and the appropriate property to look for within that tileset.
tilePropertyVal = [delegate_ tilePropertyForLayer:key tileSetName:tileSetName X:x Y:y];
// find the tileset and then look through it to find the property key/value pair we are after.
NSString* tempStr = [self tileIDFromTileSet:tileSetForLayer thatMatchesKey:tileKeyVal property:tilePropertyVal];
if (tempStr)
GID += [tempStr intValue]; // atlas offset + start GID
else
GID = 0; // default to nothing if not found.
}
}
if (GID)
{
bool rotated = false;
if ([delegate_ respondsToSelector:@selector(tileRotationForLayer:X:Y:)])
{
int rotationInDegrees = [delegate_ tileRotationForLayer:key X:x Y:y];
switch (rotationInDegrees)
{
case kRotationOnce: // 90 degrees
GID |= kFlippedHorizontallyFlag | kFlippedAntiDiagonallyFlag;
rotated = true;
break;
case kRotationTwice: // 180 degrees
GID |= kFlippedHorizontallyFlag | kFlippedVerticallyFlag;
rotated = true;
break;
case kRotationThrice: // 270 degrees
GID |= kFlippedAntiDiagonallyFlag | kFlippedVerticallyFlag;
rotated = true;
break;
default: // 0, 360, any other value, do no rotation.
break;
}
}
if (!rotated)
{
if ([delegate_ respondsToSelector:@selector(tileflippedHorizontallyAtPos:layer:)] &&
[delegate_ tileflippedHorizontallyAtPos:CGPointMake(x, y) layer:key])
{
GID |= kFlippedHorizontallyFlag;
}
if ([delegate_ respondsToSelector:@selector(tileflippedVerticallyAtPos:layer:)] &&
[delegate_ tileflippedVerticallyAtPos:CGPointMake(x, y) layer:key])
{
GID |= kFlippedVerticallyFlag;
}
}
hasData = YES;
}
mapData[y][x] = GID; // TMX Maps stored different.
}
}
if (hasData) // skip this if it's a blank layer.
{
NSData* data = [NSData dataWithBytes:mapData length:sizeof(unsigned int) * mapWidth * mapHeight];
NSMutableDictionary* dictToAdd = [NSMutableDictionary dictionaryWithDictionary:dict];
[dictToAdd setObject:data forKey:kTMXGeneratorLayerData];
// old method deprecated in favor of the new flipping method
// // rotation data in addition to map data.
// if ([delegate_ respondsToSelector:@selector(tileRotationForLayer:X:Y:)])
// {
// unsigned int rotationData[mapHeight][mapWidth];
//
// for (int y = 0; y < mapHeight; y++)
// {
// for (int x = 0; x < mapWidth; x++)
// {
// rotationData[y][x] = [delegate_ tileRotationForLayer:key X:x Y:y];
// }
// }
//
// NSData* data = [NSData dataWithBytes:rotationData length:sizeof(unsigned int) * mapWidth * mapHeight];
// [dictToAdd setObject:data forKey:kTMXGeneratorLayerRotationData];
// }
if (!layers)
layers = [[NSMutableArray alloc] initWithCapacity:10];
[layers addObject:dictToAdd];
}
}
NSArray* groups = nil;
if ([delegate_ respondsToSelector:@selector(objectGroupNames)])
groups = [delegate_ objectGroupNames];
if (groups && // object groups are optional, so don't throw an error if there are none, just skip them.
[groups count] &&
[delegate_ respondsToSelector:@selector(objectsGroupInfoForName:)])
{
for (key in groups)
{
NSMutableArray* results = [NSMutableArray arrayWithCapacity:10];
NSArray* objects = [delegate_ objectsGroupInfoForName:key];
for (__strong NSDictionary* dict in objects)
{
if (!dict)
{
if (error)
*error = [NSError errorWithDomain:[NSString stringWithFormat:@"Unable to get object group from name %@ when calling delegate method objectsGroupInfoForName:", key] code:0 userInfo:nil];
return nil;
}
// add the properties if they are defined
NSArray* properties = nil;
if ([delegate_ respondsToSelector:@selector(propertiesForObjectWithName:inGroupWithName:)])
{
properties = [delegate_ propertiesForObjectWithName:[dict objectForKey:kTMXGeneratorGroupObjectName] inGroupWithName: key];
if (properties)
{
NSMutableDictionary* tempDict = [NSMutableDictionary dictionaryWithCapacity:[dict count] + 1];
[tempDict addEntriesFromDictionary:dict];
[tempDict setObject:properties forKey:kTMXGeneratorGroupObjectProperties];
dict = [NSDictionary dictionaryWithDictionary:tempDict];
}
}
if (dict)
[results addObject:dict];
}
[self addObjectGroupNamed:key width:mapWidth height:mapHeight objectList:results];
}
}
// create the TMX file on disk.
NSString* xml = [TMXGenerator XMLWithAttributes:mapInfo
tilesets:tileSets
layers:layers
objectGroups:objectGroups];
return xml;
}
- (BOOL) generateAndSaveTMXMap:(NSError**)error
{
if (!delegate_)
return NO;
NSString* xml = [self generateMapXML:error];
if (!xml)
return NO;
NSString* mapPath = [delegate_ mapFilePath];
[TMXGenerator writeTMXFileWithXML:xml fileName:mapPath];
// copy the image atlas to the written path from the main bundle. We can change this later as needed to copy/move from a different source.
if (!copiedAtlasNames)
copiedAtlasNames = [[NSMutableSet alloc] initWithCapacity:10];
// we can skip this step with the delegate as desired.
NSString* pathForDest = [mapPath stringByDeletingLastPathComponent];
for (NSString* tileKey in tileSets)
{
BOOL copyAtlases = YES;
if ([delegate_ respondsToSelector:@selector(copyAtlasFileForName:)])
copyAtlases = [delegate_ copyAtlasFileForName:tileKey];
if (copyAtlases)
{
NSDictionary* dict = [tileSets objectForKey:tileKey];
NSString* fileName = [dict objectForKey:kTMXGeneratorTileSetImageAtlasFilename];
NSString* destPath = [pathForDest stringByAppendingPathComponent:fileName];
if (![copiedAtlasNames containsObject:fileName])
{
[[NSFileManager defaultManager] removeItemAtPath:destPath error:nil];
if (![[NSFileManager defaultManager] copyItemAtPath:[[NSBundle mainBundle] pathForResource:[fileName stringByDeletingPathExtension] ofType:[fileName pathExtension]] toPath:destPath error:error])
{
if (error)
*error = [NSError errorWithDomain:[NSString stringWithFormat:@"Unable to copy atlas to %@ with name %@ after creating the map", pathForDest, fileName] code:0 userInfo:nil];
return NO;
}
[copiedAtlasNames addObject:fileName];
}
}
}
return YES;
}
// using this class inline. Problem with this is that it isn't terribly flexible, but is a good example if you don't want to use the delegate for some reason.
- (void) saveSampleMapWithPath:(NSString*)inPath
{
int width = 16;
int height = 16;
// add map attributes
[self addMapAttributesWithPath:inPath width:width height:height tileWidth:32 tileHeight:32 orientation:nil properties:nil];
// add a tileset
[self addTilesetWithImage:@"regularTiles_default.png" named:@"Default Tileset" width:32 height:32 tileSpacing:2 tileProperties:nil];
// fill in the GIDs
// should we use a delegate here, make this more generic? Thinking we should...
arc4random_stir();
unsigned int gids[width][height];
for (int x = 0; x < height; x++)
{
for (int y = 0; y < width; y++)
{
gids[x][y] = arc4random() % 3 + 1; // one of 3 different tiles, grass, hills or dirt.
}
}
NSData* data = [NSData dataWithBytes:gids length:sizeof(unsigned int)*width*height];
// add a layer
[self addLayerNamed:@"Background" width:width height:height data:data visible:YES];
// add a spawn point object and an object layer
NSDictionary* dict = [TMXGenerator makeObjectWithName:@"SpawnPoint" type:nil x:50 y:50 width:0 height:0 properties:[NSDictionary dictionaryWithObject:@"This is a property string" forKey:@"somePropertyKey"]];
[self addObjectGroupNamed:@"Object Layer" width:width height:height objectList:[NSArray arrayWithObject:dict]];
// convert to XML
NSString* xml = [TMXGenerator XMLWithAttributes:mapAttributes
tilesets:tileSets
layers:layers
objectGroups:objectGroups];
// save as file
[TMXGenerator writeTMXFileWithXML:xml fileName:path];
}
@end