Skip to main content

tiled/
tileset.rs

1use std::collections::HashMap;
2use std::fmt;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5
6use crate::error::{Error, Result};
7use crate::image::Image;
8use crate::properties::{Properties, parse_properties};
9use crate::tile::TileData;
10use crate::{
11    Gid, InvalidTilesetError, ResourceCache, ResourceReader, Tile, TileId,
12    util::{get_attrs, parse_tag},
13};
14
15mod wangset;
16pub use wangset::*;
17
18/// A collection of tiles for usage in maps and template objects.
19///
20/// Also see the [TMX docs](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tileset).
21#[derive(Debug, PartialEq, Clone)]
22pub struct Tileset {
23    /// The path first used in a [`ResourceReader`] to load this tileset.
24    ///
25    /// For embedded tilesets, this path will be the same as the template or map's source.
26    pub source: PathBuf,
27    /// The name of the tileset, set by the user.
28    pub name: String,
29    /// The (maximum) width in pixels of the tiles in this tileset. Irrelevant for [image collection]
30    /// tilesets.
31    ///
32    /// [image collection]: Self::image
33    pub tile_width: u32,
34    /// The (maximum) height in pixels of the tiles in this tileset. Irrelevant for [image collection]
35    /// tilesets.
36    ///
37    /// [image collection]: Self::image
38    pub tile_height: u32,
39    /// The spacing in pixels between the tiles in this tileset (applies to the tileset image).
40    /// Irrelevant for image collection tilesets.
41    pub spacing: u32,
42    /// The margin around the tiles in this tileset (applies to the tileset image).
43    /// Irrelevant for image collection tilesets.
44    pub margin: u32,
45    /// The number of tiles in this tileset. Note that tile IDs don't always have a connection with
46    /// the tile count, and as such there may be tiles with an ID bigger than the tile count.
47    pub tilecount: u32,
48    /// The number of tile columns in the tileset. Editable for image collection tilesets, otherwise
49    /// calculated using [image](Self::image) width, [tile width](Self::tile_width),
50    /// [spacing](Self::spacing) and [margin](Self::margin).
51    pub columns: u32,
52    /// The x-offset to be used when drawing tiles of this tileset.
53    pub offset_x: i32,
54    /// The y-offset to be used when drawing tiles of this tileset.
55    pub offset_y: i32,
56    /// The size to use when rendering tiles of this tileset on a tile layer.
57    pub tile_render_size: TileRenderSize,
58    /// The fill mode to use when rendering tiles of this tileset, relevant when the tiles are
59    /// not rendered at their native size.
60    pub fill_mode: FillMode,
61    /// The alignment to use for tile objects referring to tiles of this tileset.
62    pub object_alignment: ObjectAlignment,
63    /// The transformations that can be applied to the tiles of this tileset, for example when
64    /// used by Wang sets.
65    pub transformations: Transformations,
66
67    /// A tileset can either:
68    /// * have a single spritesheet `image` in `tileset` ("regular" tileset);
69    /// * have zero images in `tileset` and one `image` per `tile` ("image collection" tileset).
70    ///
71    /// --------
72    /// - Source: [tiled issue #2117](https://github.com/mapeditor/tiled/issues/2117)
73    /// - Source: [`columns` documentation](https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#tileset)
74    pub image: Option<Image>,
75
76    /// All the tiles present in this tileset, indexed by their local IDs.
77    tiles: HashMap<TileId, TileData>,
78
79    /// All the wangsets present in this tileset.
80    pub wang_sets: Vec<WangSet>,
81
82    /// The custom properties of the tileset.
83    pub properties: Properties,
84
85    /// The custom tileset type, arbitrarily set by the user.
86    pub user_type: String,
87}
88
89/// The transformations that can be applied to the tiles of a tileset, for example when used by
90/// Wang sets.
91#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
92pub struct Transformations {
93    /// Whether the tiles in this tileset can be flipped horizontally.
94    pub hflip: bool,
95    /// Whether the tiles in this tileset can be flipped vertically.
96    pub vflip: bool,
97    /// Whether the tiles in this tileset can be rotated in 90-degree increments.
98    pub rotate: bool,
99    /// Whether untransformed tiles remain preferred, otherwise transformed tiles are used to
100    /// produce more variations.
101    pub prefer_untransformed: bool,
102}
103
104/// The size to use when rendering a tileset's tiles on a tile layer.
105#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
106pub enum TileRenderSize {
107    /// The tile is drawn at its own size, positioned so that its bottom left corner aligns with
108    /// the bottom left corner of its grid cell.
109    #[default]
110    Tile,
111    /// The tile is drawn at the size of the map's grid cell.
112    Grid,
113}
114
115#[derive(Debug)]
116/// An error arising from trying to parse a [`TileRenderSize`] that is not valid.
117pub struct TileRenderSizeParseError {
118    /// The invalid string found.
119    pub str_found: String,
120}
121
122impl fmt::Display for TileRenderSizeParseError {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.write_fmt(format_args!(
125            "failed to parse tile render size, valid options are `tile` and `grid` \
126        but got `{}` instead",
127            self.str_found
128        ))
129    }
130}
131
132impl FromStr for TileRenderSize {
133    type Err = TileRenderSizeParseError;
134    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
135        match s {
136            "tile" => Ok(TileRenderSize::Tile),
137            "grid" => Ok(TileRenderSize::Grid),
138            _ => Err(TileRenderSizeParseError {
139                str_found: s.to_owned(),
140            }),
141        }
142    }
143}
144
145impl fmt::Display for TileRenderSize {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            TileRenderSize::Tile => write!(f, "tile"),
149            TileRenderSize::Grid => write!(f, "grid"),
150        }
151    }
152}
153
154/// The fill mode to use when rendering a tileset's tiles at a size differing from their native
155/// size.
156#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
157pub enum FillMode {
158    /// The tile image is stretched to fill the target rectangle.
159    #[default]
160    Stretch,
161    /// The tile image is scaled to fit the target rectangle while preserving its aspect ratio.
162    PreserveAspectFit,
163}
164
165#[derive(Debug)]
166/// An error arising from trying to parse a [`FillMode`] that is not valid.
167pub struct FillModeParseError {
168    /// The invalid string found.
169    pub str_found: String,
170}
171
172impl fmt::Display for FillModeParseError {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.write_fmt(format_args!(
175            "failed to parse fill mode, valid options are `stretch` and `preserve-aspect-fit` \
176        but got `{}` instead",
177            self.str_found
178        ))
179    }
180}
181
182impl FromStr for FillMode {
183    type Err = FillModeParseError;
184    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
185        match s {
186            "stretch" => Ok(FillMode::Stretch),
187            "preserve-aspect-fit" => Ok(FillMode::PreserveAspectFit),
188            _ => Err(FillModeParseError {
189                str_found: s.to_owned(),
190            }),
191        }
192    }
193}
194
195impl fmt::Display for FillMode {
196    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
197        match self {
198            FillMode::Stretch => write!(f, "stretch"),
199            FillMode::PreserveAspectFit => write!(f, "preserve-aspect-fit"),
200        }
201    }
202}
203
204/// The alignment to use for tile objects referring to a tileset's tiles.
205#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
206#[allow(missing_docs)]
207pub enum ObjectAlignment {
208    /// Tile objects use the alignment that older Tiled versions used: [`BottomLeft`] in
209    /// orthogonal maps and [`Bottom`] in isometric maps.
210    ///
211    /// [`BottomLeft`]: ObjectAlignment::BottomLeft
212    /// [`Bottom`]: ObjectAlignment::Bottom
213    #[default]
214    Unspecified,
215    TopLeft,
216    Top,
217    TopRight,
218    Left,
219    Center,
220    Right,
221    BottomLeft,
222    Bottom,
223    BottomRight,
224}
225
226#[derive(Debug)]
227/// An error arising from trying to parse an [`ObjectAlignment`] that is not valid.
228pub struct ObjectAlignmentParseError {
229    /// The invalid string found.
230    pub str_found: String,
231}
232
233impl fmt::Display for ObjectAlignmentParseError {
234    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
235        f.write_fmt(format_args!(
236            "failed to parse object alignment, valid options are `unspecified`, `topleft`, \
237        `top`, `topright`, `left`, `center`, `right`, `bottomleft`, `bottom` and `bottomright` \
238        but got `{}` instead",
239            self.str_found
240        ))
241    }
242}
243
244impl FromStr for ObjectAlignment {
245    type Err = ObjectAlignmentParseError;
246    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
247        match s {
248            "unspecified" => Ok(ObjectAlignment::Unspecified),
249            "topleft" => Ok(ObjectAlignment::TopLeft),
250            "top" => Ok(ObjectAlignment::Top),
251            "topright" => Ok(ObjectAlignment::TopRight),
252            "left" => Ok(ObjectAlignment::Left),
253            "center" => Ok(ObjectAlignment::Center),
254            "right" => Ok(ObjectAlignment::Right),
255            "bottomleft" => Ok(ObjectAlignment::BottomLeft),
256            "bottom" => Ok(ObjectAlignment::Bottom),
257            "bottomright" => Ok(ObjectAlignment::BottomRight),
258            _ => Err(ObjectAlignmentParseError {
259                str_found: s.to_owned(),
260            }),
261        }
262    }
263}
264
265impl fmt::Display for ObjectAlignment {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        match self {
268            ObjectAlignment::Unspecified => write!(f, "unspecified"),
269            ObjectAlignment::TopLeft => write!(f, "topleft"),
270            ObjectAlignment::Top => write!(f, "top"),
271            ObjectAlignment::TopRight => write!(f, "topright"),
272            ObjectAlignment::Left => write!(f, "left"),
273            ObjectAlignment::Center => write!(f, "center"),
274            ObjectAlignment::Right => write!(f, "right"),
275            ObjectAlignment::BottomLeft => write!(f, "bottomleft"),
276            ObjectAlignment::Bottom => write!(f, "bottom"),
277            ObjectAlignment::BottomRight => write!(f, "bottomright"),
278        }
279    }
280}
281
282pub(crate) enum EmbeddedParseResultType {
283    ExternalReference { tileset_path: PathBuf },
284    Embedded { tileset: Box<Tileset> },
285}
286
287pub(crate) struct EmbeddedParseResult {
288    pub first_gid: Gid,
289    pub result_type: EmbeddedParseResultType,
290}
291
292/// Internal structure for holding mid-parse information.
293struct TilesetProperties {
294    spacing: Option<u32>,
295    margin: Option<u32>,
296    tilecount: u32,
297    columns: Option<u32>,
298    name: String,
299    user_type: String,
300    tile_width: u32,
301    tile_height: u32,
302    tile_render_size: Option<TileRenderSize>,
303    fill_mode: Option<FillMode>,
304    object_alignment: Option<ObjectAlignment>,
305    /// The root all non-absolute paths contained within the tileset are relative to.
306    root_path: PathBuf,
307}
308
309impl Tileset {
310    /// Gets the tile with the specified ID from the tileset.
311    #[inline]
312    pub fn get_tile(&self, id: TileId) -> Option<Tile<'_>> {
313        self.tiles.get(&id).map(|data| Tile::new(self, data))
314    }
315
316    /// Iterates through the tiles from this tileset.
317    #[inline]
318    pub fn tiles(&self) -> impl ExactSizeIterator<Item = (TileId, Tile<'_>)> {
319        self.tiles
320            .iter()
321            .map(move |(id, data)| (*id, Tile::new(self, data)))
322    }
323}
324
325impl Tileset {
326    pub(crate) fn parse_xml_in_map<R: std::io::BufRead>(
327        elem: crate::util::XmlElement<'_, R>,
328        path: &Path, // Template or Map file
329        reader: &mut impl ResourceReader,
330        cache: &mut impl ResourceCache,
331    ) -> Result<EmbeddedParseResult> {
332        let attrs = elem.attrs.clone();
333        Tileset::parse_xml_embedded(elem, attrs.clone(), path, reader, cache).or_else(|err| {
334            if matches!(err, Error::MalformedAttributes(_)) {
335                Tileset::parse_xml_reference(attrs, path)
336            } else {
337                Err(err)
338            }
339        })
340    }
341
342    fn parse_xml_embedded<'a, R: std::io::BufRead>(
343        elem: crate::util::XmlElement<'a, R>,
344        attrs: quick_xml::events::BytesStart<'a>,
345        path: &Path, // Template or Map file
346        reader: &mut impl ResourceReader,
347        cache: &mut impl ResourceCache,
348    ) -> Result<EmbeddedParseResult> {
349        let (
350            (spacing, margin, columns, name, user_type, user_class),
351            (tile_render_size, fill_mode, object_alignment),
352            (tilecount, first_gid, tile_width, tile_height),
353        ) = get_attrs!(
354           for v in (attrs) {
355            Some("spacing") => spacing ?= v.parse(),
356            Some("margin") => margin ?= v.parse(),
357            Some("columns") => columns ?= v.parse(),
358            Some("name") => name = v.to_string(),
359            Some("type") => user_type ?= v.parse(),
360            Some("class") => user_class ?= v.parse(),
361            Some("tilerendersize") => tile_render_size ?= v.parse::<TileRenderSize>(),
362            Some("fillmode") => fill_mode ?= v.parse::<FillMode>(),
363            Some("objectalignment") => object_alignment ?= v.parse::<ObjectAlignment>(),
364
365            "tilecount" => tilecount ?= v.parse::<u32>(),
366            "firstgid" => first_gid ?= v.parse::<u32>().map(Gid),
367            "tilewidth" => tile_width ?= v.parse::<u32>(),
368            "tileheight" => tile_height ?= v.parse::<u32>(),
369           }
370           ((spacing, margin, columns, name, user_type, user_class), (tile_render_size, fill_mode, object_alignment), (tilecount, first_gid, tile_width, tile_height))
371        );
372
373        let root_path = path.parent().ok_or(Error::PathIsNotFile)?.to_owned();
374
375        Self::finish_parsing_xml(
376            elem,
377            path.to_owned(),
378            TilesetProperties {
379                spacing,
380                margin,
381                name: name.unwrap_or_default(),
382                user_type: user_type.or(user_class).unwrap_or_default(),
383                root_path,
384                columns,
385                tilecount,
386                tile_height,
387                tile_width,
388                tile_render_size,
389                fill_mode,
390                object_alignment,
391            },
392            reader,
393            cache,
394        )
395        .map(|tileset| EmbeddedParseResult {
396            first_gid,
397            result_type: EmbeddedParseResultType::Embedded {
398                tileset: Box::new(tileset),
399            },
400        })
401    }
402
403    fn parse_xml_reference<'a>(
404        attrs: quick_xml::events::BytesStart<'a>,
405        map_path: &Path,
406    ) -> Result<EmbeddedParseResult> {
407        let (first_gid, source) = get_attrs!(
408            for v in (attrs) {
409                "firstgid" => first_gid ?= v.parse::<u32>().map(Gid),
410                "source" => source = v.to_string(),
411            }
412            (first_gid, source)
413        );
414
415        let tileset_path = map_path.parent().ok_or(Error::PathIsNotFile)?.join(source);
416
417        Ok(EmbeddedParseResult {
418            first_gid,
419            result_type: EmbeddedParseResultType::ExternalReference { tileset_path },
420        })
421    }
422
423    pub(crate) fn parse_external_tileset<R: std::io::BufRead>(
424        elem: crate::util::XmlElement<'_, R>,
425        path: &Path,
426        reader: &mut impl ResourceReader,
427        cache: &mut impl ResourceCache,
428    ) -> Result<Tileset> {
429        let (
430            (spacing, margin, columns, name, user_type, user_class),
431            (tile_render_size, fill_mode, object_alignment),
432            (tilecount, tile_width, tile_height),
433        ) = get_attrs!(
434            for v in (elem.attrs) {
435                Some("spacing") => spacing ?= v.parse(),
436                Some("margin") => margin ?= v.parse(),
437                Some("columns") => columns ?= v.parse(),
438                Some("name") => name = v.to_string(),
439                Some("type") => user_type ?= v.parse(),
440                Some("class") => user_class ?= v.parse(),
441                Some("tilerendersize") => tile_render_size ?= v.parse::<TileRenderSize>(),
442                Some("fillmode") => fill_mode ?= v.parse::<FillMode>(),
443                Some("objectalignment") => object_alignment ?= v.parse::<ObjectAlignment>(),
444
445                "tilecount" => tilecount ?= v.parse::<u32>(),
446                "tilewidth" => tile_width ?= v.parse::<u32>(),
447                "tileheight" => tile_height ?= v.parse::<u32>(),
448            }
449            ((spacing, margin, columns, name, user_type, user_class), (tile_render_size, fill_mode, object_alignment), (tilecount, tile_width, tile_height))
450        );
451
452        let root_path = path.parent().ok_or(Error::PathIsNotFile)?.to_owned();
453
454        Self::finish_parsing_xml(
455            elem,
456            path.to_owned(),
457            TilesetProperties {
458                spacing,
459                margin,
460                name: name.unwrap_or_default(),
461                user_type: user_type.or(user_class).unwrap_or_default(),
462                root_path,
463                columns,
464                tilecount,
465                tile_height,
466                tile_width,
467                tile_render_size,
468                fill_mode,
469                object_alignment,
470            },
471            reader,
472            cache,
473        )
474    }
475
476    fn finish_parsing_xml<R: std::io::BufRead>(
477        elem: crate::util::XmlElement<'_, R>,
478        container_path: PathBuf,
479        prop: TilesetProperties,
480        reader: &mut impl ResourceReader,
481        cache: &mut impl ResourceCache,
482    ) -> Result<Tileset> {
483        let mut image = Option::None;
484        let mut tiles = HashMap::with_capacity(prop.tilecount as usize);
485        let mut properties = HashMap::new();
486        let mut wang_sets = Vec::new();
487        let mut offset = (0i32, 0i32);
488        let mut transformations = Transformations::default();
489
490        parse_tag!(elem, {
491            "image" => |elem| {
492                image = Some(Image::new(elem, &prop.root_path)?);
493                Ok(())
494            },
495            "tileoffset" => |elem| {
496                offset = parse_tileoffset(elem)?;
497                Ok(())
498            },
499            "transformations" => |elem| {
500                transformations = parse_transformations(elem)?;
501                Ok(())
502            },
503            "properties" => |elem| {
504                properties = parse_properties(elem)?;
505                Ok(())
506            },
507            "tile" => |elem| {
508                let (id, tile) = TileData::new(elem, &prop.root_path, reader, cache)?;
509                tiles.insert(id, tile);
510                Ok(())
511            },
512            "wangsets" => |elem: crate::util::XmlElement<'_, R>| {
513                parse_tag!(elem, {
514                    "wangset" => |elem| {
515                        let set = WangSet::new(elem)?;
516                        wang_sets.push(set);
517                        Ok(())
518                    },
519                });
520                Ok(())
521            },
522        });
523
524        // A tileset is considered an image collection tileset if there is no image attribute (because its tiles do).
525        let is_image_collection_tileset = image.is_none();
526
527        if !is_image_collection_tileset {
528            if prop.tile_width == 0 || prop.tile_height == 0 {
529                return Err(Error::InvalidTileset(
530                    InvalidTilesetError::InvalidTileDimensions,
531                ));
532            }
533
534            for tile_id in 0..prop.tilecount {
535                tiles.entry(tile_id).or_default();
536            }
537        }
538
539        let margin = prop.margin.unwrap_or(0);
540        let spacing = prop.spacing.unwrap_or(0);
541        let columns = prop
542            .columns
543            .map(Ok)
544            .unwrap_or_else(|| Self::calculate_columns(&image, prop.tile_width, margin, spacing))?;
545
546        Ok(Tileset {
547            source: container_path,
548            name: prop.name,
549            user_type: prop.user_type,
550            tile_width: prop.tile_width,
551            tile_height: prop.tile_height,
552            spacing,
553            margin,
554            columns,
555            offset_x: offset.0,
556            offset_y: offset.1,
557            tile_render_size: prop.tile_render_size.unwrap_or_default(),
558            fill_mode: prop.fill_mode.unwrap_or_default(),
559            object_alignment: prop.object_alignment.unwrap_or_default(),
560            transformations,
561            tilecount: prop.tilecount,
562            image,
563            tiles,
564            wang_sets,
565            properties,
566        })
567    }
568
569    fn calculate_columns(
570        image: &Option<Image>,
571        tile_width: u32,
572        margin: u32,
573        spacing: u32,
574    ) -> Result<u32> {
575        image
576            .as_ref()
577            .map(|image| (image.width as u32 - margin + spacing) / (tile_width + spacing))
578            .ok_or_else(|| {
579                Error::MalformedAttributes(
580                    "No <image> nor columns attribute in <tileset>".to_string(),
581                )
582            })
583    }
584}
585
586/// Parse the optional <transformations hflip=... vflip=... rotate=... preferuntransformed=.../> tag.
587fn parse_transformations<R: std::io::BufRead>(
588    elem: crate::util::XmlElement<'_, R>,
589) -> Result<Transformations> {
590    let (hflip, vflip, rotate, prefer_untransformed) = get_attrs!(
591        for v in (elem.attrs) {
592            Some("hflip") => hflip = v == "1",
593            Some("vflip") => vflip = v == "1",
594            Some("rotate") => rotate = v == "1",
595            Some("preferuntransformed") => prefer_untransformed = v == "1",
596        }
597        (hflip, vflip, rotate, prefer_untransformed)
598    );
599    parse_tag!(elem, {});
600    Ok(Transformations {
601        hflip: hflip.unwrap_or(false),
602        vflip: vflip.unwrap_or(false),
603        rotate: rotate.unwrap_or(false),
604        prefer_untransformed: prefer_untransformed.unwrap_or(false),
605    })
606}
607
608/// Parse the optional <tileoffset x=... y=.../> tag.
609fn parse_tileoffset<R: std::io::BufRead>(
610    elem: crate::util::XmlElement<'_, R>,
611) -> Result<(i32, i32)> {
612    let offset = get_attrs!(
613        for v in (elem.attrs) {
614            "x" => offset_x ?= v.parse::<i32>(),
615            "y" => offset_y ?= v.parse::<i32>(),
616        }
617        (offset_x, offset_y)
618    );
619    parse_tag!(elem, {});
620    Ok(offset)
621}