mod asset_server_ext;
mod config;
mod error;
mod manifest;
mod save_queue;
mod systems;
#[cfg(feature = "hot_reload")]
pub mod hot_reload;
pub use asset_server_ext::AssetServerCacheExt;
pub use config::CacheConfig;
pub use error::CacheError;
pub use manifest::{CacheEntry, CacheManifest};
pub use save_queue::CacheQueue;
use bevy::asset::io::{AssetSource, AssetSourceBuilder};
use bevy::prelude::*;
pub mod prelude {
pub use crate::AssetServerCacheExt;
pub use crate::{BevyCachePlugin, CacheError, CacheEntry, CacheConfig, CacheManifest, CacheQueue};
}
#[derive(Default)]
pub struct BevyCachePlugin {
pub config: CacheConfig,
}
impl BevyCachePlugin {
pub fn new(app_name: &str) -> Self {
Self {
config: CacheConfig::new(app_name),
}
}
}
impl Plugin for BevyCachePlugin {
fn build(&self, app: &mut App) {
let cache_dir = self.config.cache_dir.clone();
if let Err(e) = self.config.ensure_cache_dir() {
warn!("bevy_cache: could not create cache directory {:?}: {e}", cache_dir);
}
let s = cache_dir.to_string_lossy().into_owned();
app.register_asset_source(
"cache",
AssetSourceBuilder::new(AssetSource::get_default_reader(s.clone()))
.with_writer(AssetSource::get_default_writer(s.clone()))
.with_watcher(AssetSource::get_default_watcher(
s,
std::time::Duration::from_millis(1000),
))
.with_watch_warning(AssetSource::get_default_watch_warning()),
);
app.insert_resource(self.config.clone())
.init_resource::<save_queue::CacheQueue>()
.add_systems(Startup, systems::load_manifest)
.add_systems(Last, systems::cleanup_on_exit);
#[cfg(not(feature = "hot_reload"))]
app.add_systems(PostUpdate, (
save_queue::process_pending_saves,
systems::save_manifest_on_change,
).chain());
#[cfg(feature = "hot_reload")]
app
.init_resource::<hot_reload::ManifestHotReload>()
.add_systems(
Startup,
hot_reload::startup_watch_manifest.after(systems::load_manifest),
)
.add_systems(PostUpdate, (
save_queue::process_pending_saves,
hot_reload::sync_manifest_from_asset,
hot_reload::save_manifest_skip_reload,
).chain());
}
#[cfg(feature = "hot_reload")]
fn finish(&self, app: &mut App) {
app.init_asset::<hot_reload::CacheManifestAsset>()
.register_asset_loader(hot_reload::CacheManifestLoader::default());
}
}