Skip to main content

ssplayer_bevy/
asset.rs

1//! `.ssab` as a Bevy asset.
2//!
3//! A pack loads through the `AssetServer` like any other asset: on Bevy's IO
4//! pool, from whatever source the app configured (the filesystem, an embedded or
5//! packed source, the web), and again when its file changes if the app enables
6//! hot reloading. What reaches the render world is parsed once per pack, not
7//! once per character, and its atlases are Bevy [`Image`]s — decoded by Bevy,
8//! uploaded once, and lent to the player as texture views.
9//!
10//! The walk that discovers what a pack depends on is the player's own
11//! (`SSPlayer::load_assets`), run over Bevy's reader; nothing here decides which
12//! files a pack needs.
13
14use std::cell::RefCell;
15use std::sync::atomic::{AtomicU64, Ordering};
16
17use bevy::asset::io::Reader;
18use bevy::asset::{Asset, AssetId, AssetLoader, AssetPath, LoadContext};
19use bevy::ecs::system::SystemParamItem;
20use bevy::image::{Image, ImageLoaderSettings};
21use bevy::log::warn;
22use bevy::prelude::Handle;
23use bevy::reflect::TypePath;
24use bevy::render::render_asset::{PrepareAssetError, RenderAsset};
25use ssplayer_wgpu::{SSPack, SSPlayer, SSRuntimeError};
26
27/// A `.ssab`, with every pack its instance parts play from and every atlas it
28/// draws with.
29///
30/// Load it with `asset_server.load("Ringo/Ringo.ssab")` and hand the handle to
31/// [`crate::SsPlayer`]. Characters sharing a handle share one parse of the pack
32/// and one upload of each atlas.
33#[derive(Asset, TypePath, Clone)]
34pub struct SsPack {
35    /// The pack itself first, then the packs its instance parts play from,
36    /// transitively. Cloning one is an `Arc` bump, which is what a character
37    /// takes.
38    pub(crate) packs: Vec<SSPack>,
39    /// Where the pack was loaded from. An atlas is keyed by its path resolved
40    /// against this, in the main world when the pack loads and again in the
41    /// render world when a character is built, so both sides must resolve alike.
42    pub(crate) path: AssetPath<'static>,
43    /// The reference-mode atlases, in the order of `atlas_keys`.
44    #[dependency]
45    pub(crate) atlases: Vec<Handle<Image>>,
46    /// The renderer key each of `atlases` is lent under.
47    pub(crate) atlas_keys: Vec<u32>,
48}
49
50impl SsPack {
51    /// The pack itself: its name and the animations it can play.
52    pub fn pack(&self) -> &SSPack {
53        &self.packs[0]
54    }
55}
56
57/// An [`SsPack`] as the render world holds it: the packs and where each atlas
58/// comes from, with a generation that changes whenever the asset is replaced —
59/// a hot reload rebuilds every character playing it.
60pub(crate) struct RenderSsPack {
61    pub(crate) packs: Vec<SSPack>,
62    pub(crate) path: AssetPath<'static>,
63    pub(crate) atlases: Vec<(u32, AssetId<Image>)>,
64    pub(crate) generation: u64,
65}
66
67impl RenderAsset for RenderSsPack {
68    type SourceAsset = SsPack;
69    type Param = ();
70
71    fn prepare_asset(source: SsPack, _id: AssetId<SsPack>, _param: &mut SystemParamItem<()>, _previous: Option<&Self>) -> Result<Self, PrepareAssetError<SsPack>> {
72        static GENERATION: AtomicU64 = AtomicU64::new(0);
73        let atlases = source.atlas_keys.iter().copied().zip(source.atlases.iter().map(Handle::id)).collect();
74        Ok(Self { packs: source.packs, path: source.path, atlases, generation: GENERATION.fetch_add(1, Ordering::Relaxed) })
75    }
76}
77
78/// Why a `.ssab` did not load.
79#[derive(Debug)]
80pub enum SsPackLoadError {
81    Io(std::io::Error),
82    Parse(SSRuntimeError),
83}
84
85impl std::fmt::Display for SsPackLoadError {
86    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
87        match self {
88            Self::Io(err) => write!(f, "could not read the .ssab: {err}"),
89            Self::Parse(err) => write!(f, "not a valid .ssab: {err}"),
90        }
91    }
92}
93
94impl std::error::Error for SsPackLoadError {}
95
96/// Loads `.ssab` files as [`SsPack`].
97#[derive(Default, TypePath)]
98pub struct SsPackLoader;
99
100impl AssetLoader for SsPackLoader {
101    type Asset = SsPack;
102    type Settings = ();
103    type Error = SsPackLoadError;
104
105    async fn load(&self, reader: &mut dyn Reader, _settings: &(), load_context: &mut LoadContext<'_>) -> Result<SsPack, SsPackLoadError> {
106        let mut bytes = Vec::new();
107        reader.read_to_end(&mut bytes).await.map_err(SsPackLoadError::Io)?;
108        let main = SSPack::load(&bytes).map_err(SsPackLoadError::Parse)?;
109        let path = load_context.path().clone_owned();
110
111        // The player walks the pack; this only answers its reads. The player is
112        // thrown away afterwards — what the asset keeps is the packs and the
113        // atlas handles the walk turned up.
114        let mut walk = Walk { ctx: load_context, base: path.clone(), siblings: Vec::new(), atlases: RefCell::new(Vec::new()) };
115        let mut player = SSPlayer::new();
116        player.add_pack(&main);
117        player.load_assets(&mut walk, main.name()).await;
118
119        let Walk { ctx, siblings, atlases, .. } = walk;
120        let mut atlas_keys = Vec::new();
121        let mut handles = Vec::new();
122        for (key, atlas) in atlases.into_inner() {
123            // Two packs of one project name the same image; one handle serves both.
124            if atlas_keys.contains(&key) {
125                continue;
126            }
127            // Not sRGB: the player takes atlas bytes as they were authored, the
128            // same way it uploads the ones it decodes itself.
129            let handle = ctx.load_builder().with_settings(|settings: &mut ImageLoaderSettings| settings.is_srgb = false).load(atlas);
130            atlas_keys.push(key);
131            handles.push(handle);
132        }
133
134        let mut packs = vec![main];
135        packs.extend(siblings);
136        Ok(SsPack { packs, path, atlases: handles, atlas_keys })
137    }
138
139    fn extensions(&self) -> &[&str] {
140        &["ssab"]
141    }
142}
143
144/// The renderer key an atlas is lent under: its resolved asset path, hashed, so
145/// two packs naming one image share it and two images of one name do not.
146pub(crate) fn atlas_key(path: &AssetPath<'_>) -> u32 {
147    // fnv1a, the family's hash — the value only has to be stable and spread.
148    path.to_string().bytes().fold(2166136261u32, |hash, byte| (hash ^ byte as u32).wrapping_mul(16777619))
149}
150
151/// The player's walk, answered from Bevy's asset reader.
152///
153/// Atlases are never read here: `has_texture` answers yes for every one, so the
154/// walk only keys them, and the keys it asks for are recorded so the loader can
155/// request each image from Bevy. The only reads are the sibling packs, and
156/// reading them through the context is what makes a change to one reload this
157/// pack.
158struct Walk<'a, 'ctx> {
159    ctx: &'a mut LoadContext<'ctx>,
160    base: AssetPath<'static>,
161    /// Sibling packs, parsed as they are read. The walk's player parses its own
162    /// copy and is dropped; this is the one the asset keeps.
163    siblings: Vec<SSPack>,
164    /// Every reference-mode atlas the walk keyed, with where it resolves to. A
165    /// `RefCell` because the walk asks for keys through `&self`.
166    atlases: RefCell<Vec<(u32, AssetPath<'static>)>>,
167}
168
169impl ssplayer_wgpu::AssetLoader for Walk<'_, '_> {
170    // `load_assets` roots nothing; every path resolves against `base`.
171    fn reset_base(&mut self) {}
172
173    fn set_base(&mut self, _src: &str) {}
174
175    async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>> {
176        let mut out = Vec::with_capacity(paths.len());
177        for path in paths {
178            let bytes = match self.base.resolve_embed_str(path) {
179                Ok(resolved) => self.ctx.read_asset_bytes(resolved).await.ok(),
180                Err(_) => None,
181            };
182            if let Some(pack) = bytes.as_deref().and_then(|bytes| SSPack::load(bytes).ok()) {
183                self.siblings.push(pack);
184            }
185            out.push(bytes);
186        }
187        out
188    }
189
190    fn texture_key(&self, path: &str, cellmap_hash: u32) -> u32 {
191        let Ok(resolved) = self.base.resolve_embed_str(path) else { return cellmap_hash };
192        let key = atlas_key(&resolved);
193        self.atlases.borrow_mut().push((key, resolved));
194        key
195    }
196
197    fn has_texture(&self, _key: u32) -> bool {
198        true
199    }
200
201    async fn supply_texture(&mut self, _key: u32, _encoded: &[u8]) {}
202
203    fn warn(&self, message: &str) {
204        warn!("ssplayer-bevy: {} — {message}", self.base);
205    }
206}
207
208/// The same keys, in the render world, for a character being built from an
209/// [`SsPack`] whose packs are already registered: nothing is read, only keyed.
210pub(crate) struct Keys<'a> {
211    pub(crate) base: &'a AssetPath<'static>,
212}
213
214impl ssplayer_wgpu::AssetLoader for Keys<'_> {
215    fn reset_base(&mut self) {}
216
217    fn set_base(&mut self, _src: &str) {}
218
219    async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>> {
220        vec![None; paths.len()]
221    }
222
223    fn texture_key(&self, path: &str, cellmap_hash: u32) -> u32 {
224        self.base.resolve_embed_str(path).map(|resolved| atlas_key(&resolved)).unwrap_or(cellmap_hash)
225    }
226
227    fn has_texture(&self, _key: u32) -> bool {
228        true
229    }
230
231    async fn supply_texture(&mut self, _key: u32, _encoded: &[u8]) {}
232
233    fn warn(&self, message: &str) {
234        warn!("ssplayer-bevy: {} — {message}", self.base);
235    }
236}