Skip to content
Snippets Groups Projects
loader.rs 1.69 KiB
Newer Older
Louis's avatar
Louis committed
#[cfg(feature = "json_loader")]
mod json {
	use bevy::asset::{AssetLoader, BoxedFuture, Error, LoadContext, LoadedAsset};

	use crate::definitions::AnimationSet;

	pub struct AnimationSetJsonLoader;
	impl AssetLoader for AnimationSetJsonLoader {
		fn load<'a>(
			&'a self,
			bytes: &'a [u8],
			load_context: &'a mut LoadContext,
		) -> BoxedFuture<'a, anyhow::Result<(), Error>> {
			Box::pin(async move {
				let value: AnimationSet = serde_json::from_slice(bytes)?;
				load_context.set_default_asset(LoadedAsset::new(value));
				Ok(())
			})
		}

		fn extensions(&self) -> &[&str] {
			static EXTENSIONS: &[&str] = &["anim.json"];
			EXTENSIONS
		}
	}
}

#[cfg(feature = "toml_loader")]
mod toml {
	use bevy::asset::{AssetLoader, BoxedFuture, Error, LoadContext, LoadedAsset};

	use crate::definitions::AnimationSet;

	pub struct AnimationSetTomlLoader;
	impl AssetLoader for AnimationSetTomlLoader {
		fn load<'a>(
			&'a self,
			bytes: &'a [u8],
			load_context: &'a mut LoadContext,
		) -> BoxedFuture<'a, anyhow::Result<(), Error>> {
			Box::pin(async move {
				let value: AnimationSet = toml::from_slice(bytes)?;
				load_context.set_default_asset(LoadedAsset::new(value));
				Ok(())
			})
		}

		fn extensions(&self) -> &[&str] {
			static EXTENSIONS: &[&str] = &["anim.toml"];
			EXTENSIONS
		}
	}
}

use bevy::app::App;
use bevy::prelude::{AddAsset, Plugin};

pub struct AnimationLoadersPlugin;
impl Plugin for AnimationLoadersPlugin {
	fn build(&self, app: &mut App) {
		app.add_asset::<crate::definitions::AnimationSet>();
		#[cfg(feature = "json_loader")]
		app.add_asset_loader(json::AnimationSetJsonLoader);
		#[cfg(feature = "toml_loader")]
		app.add_asset_loader(self::toml::AnimationSetTomlLoader);
	}
}