use std::{ops::Deref, sync::OnceLock};
use assets_manager::{AssetCache, AssetGuard, Compound};
#[derive(Debug)]
pub enum AssetOrPath<T: Compound> {
Path(String),
Owned(T),
}
impl<'a, T: Compound> From<&'a AssetOrPath<T>> for LoadedAsset<'a, T> {
fn from(value: &'a AssetOrPath<T>) -> Self {
match value {
AssetOrPath::Path(path) => LoadedAsset::Guard(crate::asset::<T, _>(path)),
AssetOrPath::Owned(asset) => LoadedAsset::Ref(asset),
}
}
}
impl<T: Compound> From<String> for AssetOrPath<T> {
fn from(val: String) -> Self {
AssetOrPath::Path(val)
}
}
impl<T: Compound> From<&str> for AssetOrPath<T> {
fn from(val: &str) -> Self {
AssetOrPath::Path(val.to_string())
}
}
pub enum LoadedAsset<'a, T: Compound> {
Guard(AssetGuard<'a, T>),
Ref(&'a T),
}
impl<T: Compound> Deref for LoadedAsset<'_, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
match &self {
LoadedAsset::Guard(guard) => guard.deref(),
LoadedAsset::Ref(reference) => reference,
}
}
}
#[cfg(not(any(target_arch = "wasm32", feature = "embedded-assets")))]
type Assets = AssetCache<assets_manager::source::FileSystem>;
#[cfg(any(target_arch = "wasm32", feature = "embedded-assets"))]
type Assets = AssetCache<assets_manager::source::Embedded<'static>>;
static ASSETS: OnceLock<Assets> = OnceLock::new();
pub fn asset<T, S>(path: S) -> AssetGuard<'static, T>
where
T: Compound,
S: AsRef<str>,
{
asset_cache().load_expect(path.as_ref()).read()
}
pub fn asset_owned<T, S>(path: S) -> T
where
T: Compound,
S: AsRef<str>,
{
asset_cache()
.load_owned(path.as_ref())
.expect("Could not load owned asset")
}
fn asset_cache() -> &'static Assets {
let cache = ASSETS.get_or_init(|| {
#[cfg(not(any(target_arch = "wasm32", feature = "embedded-assets")))]
let source = assets_manager::source::FileSystem::new("assets").unwrap();
#[cfg(any(target_arch = "wasm32", feature = "embedded-assets"))]
let source =
assets_manager::source::Embedded::from(assets_manager::source::embed!("assets"));
AssetCache::with_source(source)
});
#[cfg(feature = "hot-reloading-assets")]
cache.enhance_hot_reloading();
cache
}