Loader

Struct Loader 

Source
pub struct Loader<Cache: ResourceCache = DefaultResourceCache, Reader: ResourceReader = FilesystemResourceReader> { /* private fields */ }
Expand description

A type used for loading Maps and Tilesets.

Internally, it holds a ResourceCache that, as its name implies, caches intermediate loading artifacts, most notably map tilesets.

It also contains a ResourceReader which is the object in charge of providing read handles to files via a ResourcePath.

§Reasoning

This type is used for loading operations because they require a ResourceCache for intermediate artifacts, so using a type for creation can ensure that the cache is reused if loading more than one object is required.

Implementations§

Source§

impl Loader

Source

pub fn new() -> Self

Creates a new loader, creating a default resource cache and reader (DefaultResourceCache & FilesystemResourceReader respectively) in the process.

Source§

impl<Reader: ResourceReader> Loader<DefaultResourceCache, Reader>

Source

pub fn with_reader(reader: Reader) -> Self

Creates a new loader using a specific reader and the default resource cache (DefaultResourceCache). Shorthand for Loader::with_cache_and_reader(DefaultResourceCache::new(), reader).

§Example
use std::{sync::Arc, path::Path};

use tiled::{Loader, ResourceCache};

let mut loader = Loader::with_reader(
    // Specify the reader to use. We can use anything that implements `ResourceReader`, e.g. FilesystemResourceReader.
    // Any function that has the same signature as `ResourceReader::read_from` also implements it.
    // Here we define a reader that embeds the map at "assets/tiled_xml.csv" into the executable, and allow
    // accessing it only through "/my-map.tmx"
    // ALL maps, tilesets and templates will be read through this function, even if you don't explicitly load them
    // (They can be dependencies of one you did want to load in the first place).
    // Doing this embedding is useful for places where the OS filesystem is not available (e.g. WASM applications).
    |path: &std::path::Path| -> std::io::Result<_> {
        if path == std::path::Path::new("/my-map.tmx") {
            Ok(std::io::Cursor::new(include_bytes!("../assets/tiled_csv.tmx")))
        } else {
            Err(std::io::ErrorKind::NotFound.into())
        }
    }
);

let map = loader.load_tmx_map("/my-map.tmx")?;

assert_eq!(
    map.tilesets()[0].image.as_ref().unwrap().source,
    Path::new("/tilesheet.png")
);
Source§

impl<Cache: ResourceCache, Reader: ResourceReader> Loader<Cache, Reader>

Source

pub fn with_cache_and_reader(cache: Cache, reader: Reader) -> Self

Creates a new loader using a specific resource cache and reader. In most cases you won’t need a custom resource cache; If that is the case you can use Loader::with_reader() for a less verbose version of this function.

§Example
use std::{sync::Arc, path::Path};

use tiled::{Loader, ResourceCache};

/// An example resource cache that doesn't actually cache any resources at all.
struct NoopResourceCache;

impl ResourceCache for NoopResourceCache {
    fn get_tileset(
        &self,
        _path: impl AsRef<tiled::ResourcePath>,
    ) -> Option<std::sync::Arc<tiled::Tileset>> {
        None
    }

    fn get_template(
        &self,
        _path: impl AsRef<tiled::ResourcePath>,
    ) -> Option<std::sync::Arc<tiled::Template>> {
        None
    }

    fn insert_tileset(
        &mut self,
        _path: impl AsRef<tiled::ResourcePath>,
        _tileset: Arc<tiled::Tileset>
    ) {}

    fn insert_template(
        &mut self,
        _path: impl AsRef<tiled::ResourcePath>,
        _template: Arc<tiled::Template>
    ) {}
}

let mut loader = Loader::with_cache_and_reader(
    // Specify the resource cache to use. In this case, the one we defined earlier.
    NoopResourceCache,
    // Specify the reader to use. We can use anything that implements `ResourceReader`, e.g. FilesystemResourceReader.
    // Any function that has the same signature as `ResourceReader::read_from` also implements it.
    // Here we define a reader that embeds the map at "assets/tiled_xml.csv" into the executable, and allow
    // accessing it only through "/my-map.tmx"
    // ALL maps, tilesets and templates will be read through this function, even if you don't explicitly load them
    // (They can be dependencies of one you did want to load in the first place).
    // Doing this embedding is useful for places where the OS filesystem is not available (e.g. WASM applications).
    |path: &std::path::Path| -> std::io::Result<_> {
        if path == std::path::Path::new("/my-map.tmx") {
            Ok(std::io::Cursor::new(include_bytes!("../assets/tiled_csv.tmx")))
        } else {
            Err(std::io::ErrorKind::NotFound.into())
        }
    }
);

let map = loader.load_tmx_map("/my-map.tmx")?;

assert_eq!(
    map.tilesets()[0].image.as_ref().unwrap().source,
    Path::new("/tilesheet.png")
);
Source

pub fn load_tmx_map(&mut self, path: impl AsRef<Path>) -> Result<Map>

Parses a file hopefully containing a Tiled map and tries to parse it. All external files will be loaded relative to the path given.

All intermediate objects such as map tilesets will be stored in the internal loader cache.

Source

pub fn load_tsx_tileset(&mut self, path: impl AsRef<Path>) -> Result<Tileset>

Parses a file hopefully containing a Tiled tileset and tries to parse it. All external files will be loaded relative to the path given.

Unless you specifically want to load a tileset, you won’t need to call this function. If you are trying to load a map, simply use Loader::load_tmx_map.

§Note

This function will not cache the tileset inside the internal ResourceCache, since in this context it is not an intermediate object.

Source

pub fn cache(&self) -> &Cache

Returns a reference to the loader’s internal ResourceCache.

Source

pub fn cache_mut(&mut self) -> &mut Cache

Returns a mutable reference to the loader’s internal ResourceCache.

Source

pub fn reader(&self) -> &Reader

Returns a reference to the loader’s internal ResourceReader.

Source

pub fn reader_mut(&mut self) -> &mut Reader

Returns a mutable reference to the loader’s internal ResourceReader.

Source

pub fn into_inner(self) -> (Cache, Reader)

Consumes the loader and returns its internal ResourceCache and ResourceReader.

Trait Implementations§

Source§

impl<Cache: Clone + ResourceCache, Reader: Clone + ResourceReader> Clone for Loader<Cache, Reader>

Source§

fn clone(&self) -> Loader<Cache, Reader>

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<Cache: Debug + ResourceCache, Reader: Debug + ResourceReader> Debug for Loader<Cache, Reader>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<Cache: Default + ResourceCache, Reader: Default + ResourceReader> Default for Loader<Cache, Reader>

Source§

fn default() -> Loader<Cache, Reader>

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<Cache, Reader> Freeze for Loader<Cache, Reader>
where Cache: Freeze, Reader: Freeze,

§

impl<Cache, Reader> RefUnwindSafe for Loader<Cache, Reader>
where Cache: RefUnwindSafe, Reader: RefUnwindSafe,

§

impl<Cache, Reader> Send for Loader<Cache, Reader>
where Cache: Send, Reader: Send,

§

impl<Cache, Reader> Sync for Loader<Cache, Reader>
where Cache: Sync, Reader: Sync,

§

impl<Cache, Reader> Unpin for Loader<Cache, Reader>
where Cache: Unpin, Reader: Unpin,

§

impl<Cache, Reader> UnwindSafe for Loader<Cache, Reader>
where Cache: UnwindSafe, Reader: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.