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#[derive(Debug, PartialEq, Clone)]
22pub struct Tileset {
23 pub source: PathBuf,
27 pub name: String,
29 pub tile_width: u32,
34 pub tile_height: u32,
39 pub spacing: u32,
42 pub margin: u32,
45 pub tilecount: u32,
48 pub columns: u32,
52 pub offset_x: i32,
54 pub offset_y: i32,
56 pub tile_render_size: TileRenderSize,
58 pub fill_mode: FillMode,
61 pub object_alignment: ObjectAlignment,
63 pub transformations: Transformations,
66
67 pub image: Option<Image>,
75
76 tiles: HashMap<TileId, TileData>,
78
79 pub wang_sets: Vec<WangSet>,
81
82 pub properties: Properties,
84
85 pub user_type: String,
87}
88
89#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
92pub struct Transformations {
93 pub hflip: bool,
95 pub vflip: bool,
97 pub rotate: bool,
99 pub prefer_untransformed: bool,
102}
103
104#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
106pub enum TileRenderSize {
107 #[default]
110 Tile,
111 Grid,
113}
114
115#[derive(Debug)]
116pub struct TileRenderSizeParseError {
118 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#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
157pub enum FillMode {
158 #[default]
160 Stretch,
161 PreserveAspectFit,
163}
164
165#[derive(Debug)]
166pub struct FillModeParseError {
168 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#[derive(Debug, Default, PartialEq, Eq, Copy, Clone)]
206#[allow(missing_docs)]
207pub enum ObjectAlignment {
208 #[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)]
227pub struct ObjectAlignmentParseError {
229 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
292struct 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 root_path: PathBuf,
307}
308
309impl Tileset {
310 #[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 #[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, 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, 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 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
586fn 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
608fn 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}