-
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathtiled_map.dart
356 lines (323 loc) · 11.7 KB
/
tiled_map.dart
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
part of tiled;
/// Below is Tiled's documentation about how this structure is represented
/// on XML files:
///
/// <map>
///
/// * version: The TMX format version. Was “1.0” so far, and will be incremented
/// to match minor Tiled releases.
/// * tiledversion: The Tiled version used to save the file (since Tiled 1.0.1).
/// May be a date (for snapshot builds). (optional)
/// * orientation: Map orientation. Tiled supports “orthogonal”, “isometric”,
/// “staggered” and “hexagonal” (since 0.11).
/// * renderorder: The order in which tiles on tile layers are rendered.
/// Valid values are right-down (the default), right-up, left-down and
/// left-up. In all cases, the map is drawn row-by-row. (only supported for
/// orthogonal maps at the moment)
/// * compressionlevel: The compression level to use for tile layer data
/// (defaults to -1, which means to use the algorithm default).
/// * width: The map width in tiles.
/// * height: The map height in tiles.
/// * tilewidth: The width of a tile.
/// * tileheight: The height of a tile.
/// * hexsidelength: Only for hexagonal maps. Determines the width or height
/// (depending on the staggered axis) of the tile’s edge, in pixels.
/// * staggeraxis: For staggered and hexagonal maps, determines which axis
/// (“x” or “y”) is staggered. (since 0.11)
/// * staggerindex: For staggered and hexagonal maps, determines whether the
/// “even” or “odd” indexes along the staggered axis are shifted. (since 0.11)
/// * backgroundcolor: The background color of the map. (optional, may include
/// alpha value since 0.15 in the form #AARRGGBB.)
/// Defaults to fully transparent.
/// * nextlayerid: Stores the next available ID for new layers. This number is
/// stored to prevent reuse of the same ID after layers have been removed.
/// (since 1.2) (defaults to the highest layer id in the file + 1)
/// * nextobjectid: Stores the next available ID for new objects. This number is
/// stored to prevent reuse of the same ID after objects have been removed.
/// (since 0.11) (defaults to the highest object id in the file + 1)
/// * infinite: Whether this map is infinite. An infinite map has no fixed size
/// and can grow in all directions. Its layer data is stored in chunks.
/// (0 for false, 1 for true, defaults to 0)
///
/// The tilewidth and tileheight properties determine the general grid size of
/// the map. The individual tiles may have different sizes. Larger tiles will
/// extend at the top and right (anchored to the bottom left).
///
/// A map contains three different kinds of layers. Tile layers were once the
/// only type, and are simply called layer, object layers have the objectgroup
/// tag and image layers use the imagelayer tag. The order in which these layers
/// appear is the order in which the layers are rendered by Tiled.
///
/// The staggered orientation refers to an isometric map using staggered axes.
///
/// Can contain at most one: <properties>
///
/// Can contain any number: <tileset>, <layer>, <objectgroup>, <imagelayer>,
/// <group> (since 1.0), <editorsettings> (since 1.3)
class TiledMap {
TileMapType type;
String version;
String? tiledVersion;
int width;
int height;
bool infinite;
int tileWidth;
int tileHeight;
List<Tileset> tilesets;
List<Layer> layers;
/// Hex-formatted color (#RRGGBB or #AARRGGBB) to be rendered as a solid color
/// behind all other layers (optional).
String? backgroundColorHex;
/// [Color] to be rendered as a solid color behind all other layers
/// (optional).
///
/// Parsed from [backgroundColorHex], will be null if parsing fails for any
/// reason.
Color? backgroundColor;
int compressionLevel;
int? nextLayerId;
int? nextObjectId;
MapOrientation? orientation;
RenderOrder renderOrder;
List<EditorSetting> editorSettings;
CustomProperties properties;
// only for hexagonal maps:
int? hexSideLength;
StaggerAxis? staggerAxis;
StaggerIndex? staggerIndex;
TiledMap({
this.type = TileMapType.map,
this.version = '1.0',
this.tiledVersion,
required this.width,
required this.height,
this.infinite = false,
required this.tileWidth,
required this.tileHeight,
this.tilesets = const [],
this.layers = const [],
this.backgroundColorHex,
this.backgroundColor,
this.compressionLevel = -1,
this.hexSideLength,
this.nextLayerId,
this.nextObjectId,
this.orientation,
this.renderOrder = RenderOrder.rightDown,
this.staggerAxis,
this.staggerIndex,
this.editorSettings = const [],
this.properties = CustomProperties.empty,
});
/// Takes a string [contents] and converts it to a [TiledMap] with the help of
/// the [TsxProvider]s returned from the [tsxProviderFunction].
/// The [tsxProviderFunction] is most commonly your static [TsxProvider.parse]
/// implementation.
static Future<TiledMap> fromString(
String contents,
Future<TsxProvider> Function(String key) tsxProviderFunction,
) async {
final tsxSourcePaths = XmlDocument.parse(contents)
.rootElement
.children
.whereType<XmlElement>()
.where((element) => element.name.local == 'tileset')
.map((e) => e.getAttribute('source'));
final tsxProviders = await Future.wait(
tsxSourcePaths
.where((key) => key != null)
.map((key) async => tsxProviderFunction(key!)),
);
return TileMapParser.parseTmx(
contents,
tsxList: tsxProviders.isEmpty ? null : tsxProviders,
);
}
// Convenience Methods
Tile? tileByGid(int tileGid) {
if (tileGid == 0) {
return Tile(localId: -1);
}
final tileset = tilesetByTileGId(tileGid);
final firstGid = tileset.firstGid ?? 0;
return tileset.tiles.firstWhereOrNull(
(element) => element.localId == (tileGid - firstGid),
);
}
Tile? tileByLocalId(String tileSetName, int localId) {
final tileset = tilesetByName(tileSetName);
return tileset.tiles.firstWhereOrNull(
(element) => element.localId == localId,
);
}
Tile? tileByPhrase(String tilePhrase) {
final split = tilePhrase.split('|');
if (split.length != 2) {
throw ArgumentError(
'$tilePhrase not in the format of "TilesetName|LocalTileID"',
);
}
final tilesetName = split.first;
final tileId = int.tryParse(split.last);
if (tileId == null) {
throw ArgumentError('Local tile ID ${split.last} is not an integer.');
}
return tileByLocalId(tilesetName, tileId);
}
Tileset tilesetByTileGId(int tileGId) {
if (tilesets.length == 1) {
return tilesets.first;
}
for (var i = 0; i < tilesets.length; ++i) {
final tileset = tilesets[i];
final firstGid = tileset.firstGid ?? 0;
if (firstGid > tileGId) {
if (i == 0) {
throw ArgumentError('Tileset not found');
}
return tilesets[i - 1];
}
}
return tilesets.last;
}
List<TiledImage> tiledImages() {
final imageSet = <TiledImage>{};
for (var i = 0; i < tilesets.length; ++i) {
final image = tilesets[i].image;
if (image != null) {
imageSet.add(image);
}
for (var j = 0; j < tilesets[i].tiles.length; ++j) {
final image = tilesets[i].tiles[j].image;
if (image != null) {
imageSet.add(image);
}
}
}
imageSet.addAll(layers.whereType<ImageLayer>().map((e) => e.image));
return imageSet.toList();
}
List<TiledImage> collectImagesInLayer(Layer layer) {
if (layer is ImageLayer) {
return [layer.image];
} else if (layer is Group) {
return layer.layers.expand(collectImagesInLayer).toList();
} else if (layer is TileLayer) {
const emptyTile = 0;
final rows = layer.tileData ?? <List<Gid>>[];
final gids = rows
.expand((row) => row.map((gid) => gid.tile))
.where((gid) => gid != emptyTile)
.toSet();
return gids
.map(tilesetByTileGId)
.toSet() // The different gid can be in the same tileset
.expand(
(tileset) =>
[tileset.image, ...tileset.tiles.map((tile) => tile.image)],
)
.whereNotNull()
.toList();
}
return [];
}
/// Finds the first layer with the matching [name], or throw an
/// [ArgumentError] if one cannot be found.
/// Will search recursively through [Group] children.
Layer layerByName(String name) {
final toSearch = Queue<List<Layer>>();
toSearch.add(layers);
Layer? found;
while (found == null && toSearch.isNotEmpty) {
final currentLayers = toSearch.removeFirst();
currentLayers.forEach((layer) {
if (layer.name == name) {
found = layer;
return;
} else if (layer is Group) {
toSearch.add(layer.layers);
}
});
}
if (found != null) {
return found!;
}
// Couldn't find it in any layer
throw ArgumentError('Layer $name not found');
}
Tileset tilesetByName(String name) {
return tilesets.firstWhere(
(element) => element.name == name,
orElse: () => throw ArgumentError('Tileset $name not found'),
);
}
factory TiledMap.parse(Parser parser, {List<TsxProvider>? tsxList}) {
final backgroundColorHex = parser.getStringOrNull('backgroundcolor');
final backgroundColor = parser.getColorOrNull('backgroundcolor');
final compressionLevel = parser.getInt('compressionlevel', defaults: -1);
final height = parser.getInt('height');
final hexSideLength = parser.getIntOrNull('hexsidelength');
final infinite = parser.getBool('infinite', defaults: false);
final nextLayerId = parser.getIntOrNull('nextlayerid');
final nextObjectId = parser.getIntOrNull('nextobjectid');
final orientation = parser.getMapOrientationOrNull('orientation');
final renderOrder = parser.getRenderOrder(
'renderorder',
defaults: RenderOrder.rightDown,
);
final staggerAxis = parser.getStaggerAxisOrNull('staggeraxis');
final staggerIndex = parser.getStaggerIndexOrNull('staggerindex');
final tiledVersion = parser.getStringOrNull('tiledversion');
final tileHeight = parser.getInt('tileheight');
final tileWidth = parser.getInt('tilewidth');
final type = parser.getTileMapType('type', defaults: TileMapType.map);
final version = parser.getString('version', defaults: '1.0');
final width = parser.getInt('width');
final tilesets = parser.getChildrenAs(
'tileset',
(tilesetData) {
final tilesetSource = tilesetData.getStringOrNull('source');
if (tilesetSource == null || tsxList == null) {
return Tileset.parse(tilesetData);
}
final matchingTsx = tsxList.where(
(tsx) => tsx.filename == tilesetSource,
);
return Tileset.parse(
tilesetData,
tsx: matchingTsx.isNotEmpty ? matchingTsx.first : null,
);
},
);
final layers = Layer.parseLayers(parser);
final properties = parser.getProperties();
final editorSettings = parser.getChildrenAs(
'editorsettings',
EditorSetting.parse,
);
return TiledMap(
type: type,
version: version,
tiledVersion: tiledVersion,
width: width,
height: height,
infinite: infinite,
tileWidth: tileWidth,
tileHeight: tileHeight,
tilesets: tilesets,
layers: layers,
backgroundColorHex: backgroundColorHex,
backgroundColor: backgroundColor,
compressionLevel: compressionLevel,
hexSideLength: hexSideLength,
nextLayerId: nextLayerId,
nextObjectId: nextObjectId,
orientation: orientation,
renderOrder: renderOrder,
staggerAxis: staggerAxis,
staggerIndex: staggerIndex,
editorSettings: editorSettings,
properties: properties,
);
}
}