tiled 0.16.0

A rust crate for loading maps created by the Tiled editor
Documentation
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
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::str::FromStr;

use crate::error::{Error, Result};
use crate::image::Image;
use crate::properties::{Properties, parse_properties};
use crate::tile::TileData;
use crate::{
    Gid, InvalidTilesetError, ResourceCache, ResourceReader, Tile, TileId,
    util::{get_attrs, parse_tag},
};

mod wangset;
pub use wangset::*;

/// A collection of tiles for usage in maps and template objects.
///
/// Also see the [TMX docs](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tileset).
#[derive(Debug, PartialEq, Clone)]
pub struct Tileset {
    /// The path first used in a [`ResourceReader`] to load this tileset.
    ///
    /// For embedded tilesets, this path will be the same as the template or map's source.
    pub source: PathBuf,
    /// The name of the tileset, set by the user.
    pub name: String,
    /// The (maximum) width in pixels of the tiles in this tileset. Irrelevant for [image collection]
    /// tilesets.
    ///
    /// [image collection]: Self::image
    pub tile_width: u32,
    /// The (maximum) height in pixels of the tiles in this tileset. Irrelevant for [image collection]
    /// tilesets.
    ///
    /// [image collection]: Self::image
    pub tile_height: u32,
    /// The spacing in pixels between the tiles in this tileset (applies to the tileset image).
    /// Irrelevant for image collection tilesets.
    pub spacing: u32,
    /// The margin around the tiles in this tileset (applies to the tileset image).
    /// Irrelevant for image collection tilesets.
    pub margin: u32,
    /// The number of tiles in this tileset. Note that tile IDs don't always have a connection with
    /// the tile count, and as such there may be tiles with an ID bigger than the tile count.
    pub tilecount: u32,
    /// The number of tile columns in the tileset. Editable for image collection tilesets, otherwise
    /// calculated using [image](Self::image) width, [tile width](Self::tile_width),
    /// [spacing](Self::spacing) and [margin](Self::margin).
    pub columns: u32,
    /// The x-offset to be used when drawing tiles of this tileset.
    pub offset_x: i32,
    /// The y-offset to be used when drawing tiles of this tileset.
    pub offset_y: i32,
    /// The size to use when rendering tiles of this tileset on a tile layer.
    pub tile_render_size: TileRenderSize,
    /// The fill mode to use when rendering tiles of this tileset, relevant when the tiles are
    /// not rendered at their native size.
    pub fill_mode: FillMode,
    /// The alignment to use for tile objects referring to tiles of this tileset.
    pub object_alignment: ObjectAlignment,
    /// The transformations that can be applied to the tiles of this tileset, for example when
    /// used by Wang sets.
    pub transformations: Transformations,

    /// A tileset can either:
    /// * have a single spritesheet `image` in `tileset` ("regular" tileset);
    /// * have zero images in `tileset` and one `image` per `tile` ("image collection" tileset).
    ///
    /// --------
    /// - Source: [tiled issue #2117](https://github.com/mapeditor/tiled/issues/2117)
    /// - Source: [`columns` documentation](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tileset)
    pub image: Option<Image>,

    /// All the tiles present in this tileset, indexed by their local IDs.
    tiles: HashMap<TileId, TileData>,

    /// All the wangsets present in this tileset.
    pub wang_sets: Vec<WangSet>,

    /// The custom properties of the tileset.
    pub properties: Properties,

    /// The custom tileset type, arbitrarily set by the user.
    pub user_type: String,
}

/// The transformations that can be applied to the tiles of a tileset, for example when used by
/// Wang sets.
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
pub struct Transformations {
    /// Whether the tiles in this tileset can be flipped horizontally.
    pub hflip: bool,
    /// Whether the tiles in this tileset can be flipped vertically.
    pub vflip: bool,
    /// Whether the tiles in this tileset can be rotated in 90-degree increments.
    pub rotate: bool,
    /// Whether untransformed tiles remain preferred, otherwise transformed tiles are used to
    /// produce more variations.
    pub prefer_untransformed: bool,
}

/// The size to use when rendering a tileset's tiles on a tile layer.
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
pub enum TileRenderSize {
    /// The tile is drawn at its own size, positioned so that its bottom left corner aligns with
    /// the bottom left corner of its grid cell.
    #[default]
    Tile,
    /// The tile is drawn at the size of the map's grid cell.
    Grid,
}

#[derive(Debug)]
/// An error arising from trying to parse a [`TileRenderSize`] that is not valid.
pub struct TileRenderSizeParseError {
    /// The invalid string found.
    pub str_found: String,
}

impl fmt::Display for TileRenderSizeParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to parse tile render size, valid options are `tile` and `grid` \
        but got `{}` instead",
            self.str_found
        ))
    }
}

impl FromStr for TileRenderSize {
    type Err = TileRenderSizeParseError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "tile" => Ok(TileRenderSize::Tile),
            "grid" => Ok(TileRenderSize::Grid),
            _ => Err(TileRenderSizeParseError {
                str_found: s.to_owned(),
            }),
        }
    }
}

impl fmt::Display for TileRenderSize {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TileRenderSize::Tile => write!(f, "tile"),
            TileRenderSize::Grid => write!(f, "grid"),
        }
    }
}

/// The fill mode to use when rendering a tileset's tiles at a size differing from their native
/// size.
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
pub enum FillMode {
    /// The tile image is stretched to fill the target rectangle.
    #[default]
    Stretch,
    /// The tile image is scaled to fit the target rectangle while preserving its aspect ratio.
    PreserveAspectFit,
}

#[derive(Debug)]
/// An error arising from trying to parse a [`FillMode`] that is not valid.
pub struct FillModeParseError {
    /// The invalid string found.
    pub str_found: String,
}

impl fmt::Display for FillModeParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to parse fill mode, valid options are `stretch` and `preserve-aspect-fit` \
        but got `{}` instead",
            self.str_found
        ))
    }
}

impl FromStr for FillMode {
    type Err = FillModeParseError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "stretch" => Ok(FillMode::Stretch),
            "preserve-aspect-fit" => Ok(FillMode::PreserveAspectFit),
            _ => Err(FillModeParseError {
                str_found: s.to_owned(),
            }),
        }
    }
}

impl fmt::Display for FillMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FillMode::Stretch => write!(f, "stretch"),
            FillMode::PreserveAspectFit => write!(f, "preserve-aspect-fit"),
        }
    }
}

/// The alignment to use for tile objects referring to a tileset's tiles.
#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
#[allow(missing_docs)]
pub enum ObjectAlignment {
    /// Tile objects use the alignment that older Tiled versions used: [`BottomLeft`] in
    /// orthogonal maps and [`Bottom`] in isometric maps.
    ///
    /// [`BottomLeft`]: ObjectAlignment::BottomLeft
    /// [`Bottom`]: ObjectAlignment::Bottom
    #[default]
    Unspecified,
    TopLeft,
    Top,
    TopRight,
    Left,
    Center,
    Right,
    BottomLeft,
    Bottom,
    BottomRight,
}

#[derive(Debug)]
/// An error arising from trying to parse an [`ObjectAlignment`] that is not valid.
pub struct ObjectAlignmentParseError {
    /// The invalid string found.
    pub str_found: String,
}

impl fmt::Display for ObjectAlignmentParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_fmt(format_args!(
            "failed to parse object alignment, valid options are `unspecified`, `topleft`, \
        `top`, `topright`, `left`, `center`, `right`, `bottomleft`, `bottom` and `bottomright` \
        but got `{}` instead",
            self.str_found
        ))
    }
}

impl FromStr for ObjectAlignment {
    type Err = ObjectAlignmentParseError;
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s {
            "unspecified" => Ok(ObjectAlignment::Unspecified),
            "topleft" => Ok(ObjectAlignment::TopLeft),
            "top" => Ok(ObjectAlignment::Top),
            "topright" => Ok(ObjectAlignment::TopRight),
            "left" => Ok(ObjectAlignment::Left),
            "center" => Ok(ObjectAlignment::Center),
            "right" => Ok(ObjectAlignment::Right),
            "bottomleft" => Ok(ObjectAlignment::BottomLeft),
            "bottom" => Ok(ObjectAlignment::Bottom),
            "bottomright" => Ok(ObjectAlignment::BottomRight),
            _ => Err(ObjectAlignmentParseError {
                str_found: s.to_owned(),
            }),
        }
    }
}

impl fmt::Display for ObjectAlignment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ObjectAlignment::Unspecified => write!(f, "unspecified"),
            ObjectAlignment::TopLeft => write!(f, "topleft"),
            ObjectAlignment::Top => write!(f, "top"),
            ObjectAlignment::TopRight => write!(f, "topright"),
            ObjectAlignment::Left => write!(f, "left"),
            ObjectAlignment::Center => write!(f, "center"),
            ObjectAlignment::Right => write!(f, "right"),
            ObjectAlignment::BottomLeft => write!(f, "bottomleft"),
            ObjectAlignment::Bottom => write!(f, "bottom"),
            ObjectAlignment::BottomRight => write!(f, "bottomright"),
        }
    }
}

pub(crate) enum EmbeddedParseResultType {
    ExternalReference { tileset_path: PathBuf },
    Embedded { tileset: Box<Tileset> },
}

pub(crate) struct EmbeddedParseResult {
    pub first_gid: Gid,
    pub result_type: EmbeddedParseResultType,
}

/// Internal structure for holding mid-parse information.
struct TilesetProperties {
    spacing: Option<u32>,
    margin: Option<u32>,
    tilecount: u32,
    columns: Option<u32>,
    name: String,
    user_type: String,
    tile_width: u32,
    tile_height: u32,
    tile_render_size: Option<TileRenderSize>,
    fill_mode: Option<FillMode>,
    object_alignment: Option<ObjectAlignment>,
    /// The root all non-absolute paths contained within the tileset are relative to.
    root_path: PathBuf,
}

impl Tileset {
    /// Gets the tile with the specified ID from the tileset.
    #[inline]
    pub fn get_tile(&self, id: TileId) -> Option<Tile<'_>> {
        self.tiles.get(&id).map(|data| Tile::new(self, data))
    }

    /// Iterates through the tiles from this tileset.
    #[inline]
    pub fn tiles(&self) -> impl ExactSizeIterator<Item = (TileId, Tile<'_>)> {
        self.tiles
            .iter()
            .map(move |(id, data)| (*id, Tile::new(self, data)))
    }
}

impl Tileset {
    pub(crate) fn parse_xml_in_map<R: std::io::BufRead>(
        elem: crate::util::XmlElement<'_, R>,
        path: &Path, // Template or Map file
        reader: &mut impl ResourceReader,
        cache: &mut impl ResourceCache,
    ) -> Result<EmbeddedParseResult> {
        let attrs = elem.attrs.clone();
        Tileset::parse_xml_embedded(elem, attrs.clone(), path, reader, cache).or_else(|err| {
            if matches!(err, Error::MalformedAttributes(_)) {
                Tileset::parse_xml_reference(attrs, path)
            } else {
                Err(err)
            }
        })
    }

    fn parse_xml_embedded<'a, R: std::io::BufRead>(
        elem: crate::util::XmlElement<'a, R>,
        attrs: quick_xml::events::BytesStart<'a>,
        path: &Path, // Template or Map file
        reader: &mut impl ResourceReader,
        cache: &mut impl ResourceCache,
    ) -> Result<EmbeddedParseResult> {
        let (
            (spacing, margin, columns, name, user_type, user_class),
            (tile_render_size, fill_mode, object_alignment),
            (tilecount, first_gid, tile_width, tile_height),
        ) = get_attrs!(
           for v in (attrs) {
            Some("spacing") => spacing ?= v.parse(),
            Some("margin") => margin ?= v.parse(),
            Some("columns") => columns ?= v.parse(),
            Some("name") => name = v.to_string(),
            Some("type") => user_type ?= v.parse(),
            Some("class") => user_class ?= v.parse(),
            Some("tilerendersize") => tile_render_size ?= v.parse::<TileRenderSize>(),
            Some("fillmode") => fill_mode ?= v.parse::<FillMode>(),
            Some("objectalignment") => object_alignment ?= v.parse::<ObjectAlignment>(),

            "tilecount" => tilecount ?= v.parse::<u32>(),
            "firstgid" => first_gid ?= v.parse::<u32>().map(Gid),
            "tilewidth" => tile_width ?= v.parse::<u32>(),
            "tileheight" => tile_height ?= v.parse::<u32>(),
           }
           ((spacing, margin, columns, name, user_type, user_class), (tile_render_size, fill_mode, object_alignment), (tilecount, first_gid, tile_width, tile_height))
        );

        let root_path = path.parent().ok_or(Error::PathIsNotFile)?.to_owned();

        Self::finish_parsing_xml(
            elem,
            path.to_owned(),
            TilesetProperties {
                spacing,
                margin,
                name: name.unwrap_or_default(),
                user_type: user_type.or(user_class).unwrap_or_default(),
                root_path,
                columns,
                tilecount,
                tile_height,
                tile_width,
                tile_render_size,
                fill_mode,
                object_alignment,
            },
            reader,
            cache,
        )
        .map(|tileset| EmbeddedParseResult {
            first_gid,
            result_type: EmbeddedParseResultType::Embedded {
                tileset: Box::new(tileset),
            },
        })
    }

    fn parse_xml_reference<'a>(
        attrs: quick_xml::events::BytesStart<'a>,
        map_path: &Path,
    ) -> Result<EmbeddedParseResult> {
        let (first_gid, source) = get_attrs!(
            for v in (attrs) {
                "firstgid" => first_gid ?= v.parse::<u32>().map(Gid),
                "source" => source = v.to_string(),
            }
            (first_gid, source)
        );

        let tileset_path = map_path.parent().ok_or(Error::PathIsNotFile)?.join(source);

        Ok(EmbeddedParseResult {
            first_gid,
            result_type: EmbeddedParseResultType::ExternalReference { tileset_path },
        })
    }

    pub(crate) fn parse_external_tileset<R: std::io::BufRead>(
        elem: crate::util::XmlElement<'_, R>,
        path: &Path,
        reader: &mut impl ResourceReader,
        cache: &mut impl ResourceCache,
    ) -> Result<Tileset> {
        let (
            (spacing, margin, columns, name, user_type, user_class),
            (tile_render_size, fill_mode, object_alignment),
            (tilecount, tile_width, tile_height),
        ) = get_attrs!(
            for v in (elem.attrs) {
                Some("spacing") => spacing ?= v.parse(),
                Some("margin") => margin ?= v.parse(),
                Some("columns") => columns ?= v.parse(),
                Some("name") => name = v.to_string(),
                Some("type") => user_type ?= v.parse(),
                Some("class") => user_class ?= v.parse(),
                Some("tilerendersize") => tile_render_size ?= v.parse::<TileRenderSize>(),
                Some("fillmode") => fill_mode ?= v.parse::<FillMode>(),
                Some("objectalignment") => object_alignment ?= v.parse::<ObjectAlignment>(),

                "tilecount" => tilecount ?= v.parse::<u32>(),
                "tilewidth" => tile_width ?= v.parse::<u32>(),
                "tileheight" => tile_height ?= v.parse::<u32>(),
            }
            ((spacing, margin, columns, name, user_type, user_class), (tile_render_size, fill_mode, object_alignment), (tilecount, tile_width, tile_height))
        );

        let root_path = path.parent().ok_or(Error::PathIsNotFile)?.to_owned();

        Self::finish_parsing_xml(
            elem,
            path.to_owned(),
            TilesetProperties {
                spacing,
                margin,
                name: name.unwrap_or_default(),
                user_type: user_type.or(user_class).unwrap_or_default(),
                root_path,
                columns,
                tilecount,
                tile_height,
                tile_width,
                tile_render_size,
                fill_mode,
                object_alignment,
            },
            reader,
            cache,
        )
    }

    fn finish_parsing_xml<R: std::io::BufRead>(
        elem: crate::util::XmlElement<'_, R>,
        container_path: PathBuf,
        prop: TilesetProperties,
        reader: &mut impl ResourceReader,
        cache: &mut impl ResourceCache,
    ) -> Result<Tileset> {
        let mut image = Option::None;
        let mut tiles = HashMap::with_capacity(prop.tilecount as usize);
        let mut properties = HashMap::new();
        let mut wang_sets = Vec::new();
        let mut offset = (0i32, 0i32);
        let mut transformations = Transformations::default();

        parse_tag!(elem, {
            "image" => |elem| {
                image = Some(Image::new(elem, &prop.root_path)?);
                Ok(())
            },
            "tileoffset" => |elem| {
                offset = parse_tileoffset(elem)?;
                Ok(())
            },
            "transformations" => |elem| {
                transformations = parse_transformations(elem)?;
                Ok(())
            },
            "properties" => |elem| {
                properties = parse_properties(elem)?;
                Ok(())
            },
            "tile" => |elem| {
                let (id, tile) = TileData::new(elem, &prop.root_path, reader, cache)?;
                tiles.insert(id, tile);
                Ok(())
            },
            "wangsets" => |elem: crate::util::XmlElement<'_, R>| {
                parse_tag!(elem, {
                    "wangset" => |elem| {
                        let set = WangSet::new(elem)?;
                        wang_sets.push(set);
                        Ok(())
                    },
                });
                Ok(())
            },
        });

        // A tileset is considered an image collection tileset if there is no image attribute (because its tiles do).
        let is_image_collection_tileset = image.is_none();

        if !is_image_collection_tileset {
            if prop.tile_width == 0 || prop.tile_height == 0 {
                return Err(Error::InvalidTileset(
                    InvalidTilesetError::InvalidTileDimensions,
                ));
            }

            for tile_id in 0..prop.tilecount {
                tiles.entry(tile_id).or_default();
            }
        }

        let margin = prop.margin.unwrap_or(0);
        let spacing = prop.spacing.unwrap_or(0);
        let columns = prop
            .columns
            .map(Ok)
            .unwrap_or_else(|| Self::calculate_columns(&image, prop.tile_width, margin, spacing))?;

        Ok(Tileset {
            source: container_path,
            name: prop.name,
            user_type: prop.user_type,
            tile_width: prop.tile_width,
            tile_height: prop.tile_height,
            spacing,
            margin,
            columns,
            offset_x: offset.0,
            offset_y: offset.1,
            tile_render_size: prop.tile_render_size.unwrap_or_default(),
            fill_mode: prop.fill_mode.unwrap_or_default(),
            object_alignment: prop.object_alignment.unwrap_or_default(),
            transformations,
            tilecount: prop.tilecount,
            image,
            tiles,
            wang_sets,
            properties,
        })
    }

    fn calculate_columns(
        image: &Option<Image>,
        tile_width: u32,
        margin: u32,
        spacing: u32,
    ) -> Result<u32> {
        image
            .as_ref()
            .map(|image| (image.width as u32 - margin + spacing) / (tile_width + spacing))
            .ok_or_else(|| {
                Error::MalformedAttributes(
                    "No <image> nor columns attribute in <tileset>".to_string(),
                )
            })
    }
}

/// Parse the optional <transformations hflip=... vflip=... rotate=... preferuntransformed=.../> tag.
fn parse_transformations<R: std::io::BufRead>(
    elem: crate::util::XmlElement<'_, R>,
) -> Result<Transformations> {
    let (hflip, vflip, rotate, prefer_untransformed) = get_attrs!(
        for v in (elem.attrs) {
            Some("hflip") => hflip = v == "1",
            Some("vflip") => vflip = v == "1",
            Some("rotate") => rotate = v == "1",
            Some("preferuntransformed") => prefer_untransformed = v == "1",
        }
        (hflip, vflip, rotate, prefer_untransformed)
    );
    parse_tag!(elem, {});
    Ok(Transformations {
        hflip: hflip.unwrap_or(false),
        vflip: vflip.unwrap_or(false),
        rotate: rotate.unwrap_or(false),
        prefer_untransformed: prefer_untransformed.unwrap_or(false),
    })
}

/// Parse the optional <tileoffset x=... y=.../> tag.
fn parse_tileoffset<R: std::io::BufRead>(
    elem: crate::util::XmlElement<'_, R>,
) -> Result<(i32, i32)> {
    let offset = get_attrs!(
        for v in (elem.attrs) {
            "x" => offset_x ?= v.parse::<i32>(),
            "y" => offset_y ?= v.parse::<i32>(),
        }
        (offset_x, offset_y)
    );
    parse_tag!(elem, {});
    Ok(offset)
}