Skip to content
Snippets Groups Projects
image.rs 1.59 KiB
Newer Older
alexdevteam's avatar
alexdevteam committed
use std::{
    io::Read,
    path::{Path, PathBuf},
};
alexdevteam's avatar
alexdevteam committed

use xml::{attribute::OwnedAttribute, EventReader};

alexdevteam's avatar
alexdevteam committed
use crate::{error::TiledError, properties::Color, util::*};
alexdevteam's avatar
alexdevteam committed

#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Image {
alexdevteam's avatar
alexdevteam committed
    /// The filepath of the image.
    ///
    /// ## Note
    /// The crate does not currently support embedded images (Even though Tiled
    /// does not allow creating maps with embedded image data, the TMX format does; [source])
    ///
    /// [source]: https://doc.mapeditor.org/en/stable/reference/tmx-map-format/#image
    // TODO: Embedded images
    pub source: PathBuf,
alexdevteam's avatar
alexdevteam committed
    pub width: i32,
    pub height: i32,
alexdevteam's avatar
alexdevteam committed
    pub transparent_colour: Option<Color>,
alexdevteam's avatar
alexdevteam committed
}

impl Image {
    pub(crate) fn new<R: Read>(
        parser: &mut EventReader<R>,
        attrs: Vec<OwnedAttribute>,
alexdevteam's avatar
alexdevteam committed
        path_relative_to: impl AsRef<Path>,
alexdevteam's avatar
alexdevteam committed
    ) -> Result<Image, TiledError> {
        let (c, (s, w, h)) = get_attrs!(
            attrs,
            optionals: [
                ("trans", trans, |v:String| v.parse().ok()),
            ],
            required: [
                ("source", source, |v| Some(v)),
                ("width", width, |v:String| v.parse().ok()),
                ("height", height, |v:String| v.parse().ok()),
            ],
alexdevteam's avatar
alexdevteam committed
            TiledError::MalformedAttributes("Image must have a source, width and height with correct types".to_string())
alexdevteam's avatar
alexdevteam committed
        );

        parse_tag!(parser, "image", { "" => |_| Ok(()) });
        Ok(Image {
alexdevteam's avatar
alexdevteam committed
            source: path_relative_to.as_ref().join(s),
alexdevteam's avatar
alexdevteam committed
            width: w,
            height: h,
            transparent_colour: c,
        })
    }
}