Skip to main content

ssruntime/
resource.rs

1//! A parsed `.ssab`: its bytes, each animation's metadata, and the caches built from them on first use.
2
3use alloc::vec::Vec;
4
5use crate::error;
6
7/// A read-only borrow of an external SSAB byte buffer.
8///
9/// The pointer/length pair is never observed publicly; it is only constructed
10/// inside [`SsabData::load_borrow`] (whose `# Safety` clause owns the validity
11/// invariant) and read internally via [`SsabStorage::as_slice`].
12struct BorrowedBuffer {
13    ptr: ::core::ptr::NonNull<u8>,
14    len: usize,
15}
16
17// SAFETY: `BorrowedBuffer` represents a borrow of read-only memory whose
18// validity is upheld by the caller of `SsabData::load_borrow`. Nothing in this
19// crate mutates the pointed-to bytes, so transferring (`Send`) or sharing
20// (`Sync`) the handle does not introduce data races as long as the caller's
21// contract — that the memory remains valid and unmodified for the duration of
22// the borrow, including across threads — is honored.
23unsafe impl Send for BorrowedBuffer {}
24unsafe impl Sync for BorrowedBuffer {}
25
26enum SsabStorage {
27    Owned(Vec<u8>),
28    Borrowed(BorrowedBuffer),
29}
30impl SsabStorage {
31    pub fn as_slice(&self) -> &[u8] {
32        match self {
33            SsabStorage::Owned(vec) => vec.as_slice(),
34            // SAFETY: see the safety contract on `BorrowedBuffer` and
35            // `SsabData::load_borrow`.
36            SsabStorage::Borrowed(b) => unsafe { ::core::slice::from_raw_parts(b.ptr.as_ptr(), b.len) },
37        }
38    }
39}
40
41/// Which of an animation's eight per-coordinate-setup slots a setup uses.
42fn coordinate_slot(coordinate_system: crate::eval::SsCoordinateSystem, origin: crate::eval::SsOrigin, unit: crate::eval::SsUnit) -> usize {
43    usize::from(coordinate_system == crate::eval::SsCoordinateSystem::YDown) | usize::from(origin == crate::eval::SsOrigin::TopLeft) << 1 | usize::from(unit == crate::eval::SsUnit::Normalized) << 2
44}
45
46/// One animation of a pack: its name hash, frame range, rate and canvas, and the
47/// tables playing it reads.
48pub struct AnimationMetadata<'a> {
49    pub name_hash: u32,
50    pub start_frame: i32,
51    pub end_frame: i32,
52    pub fps: i32,
53    pub canvas_width: f32,
54    pub canvas_height: f32,
55    /// The SSAE's setup pose, as stored. It is identical for every animation of
56    /// an AnimationPack — the converter writes the same `isSetup` animation into
57    /// each — and becomes the floor of the track stack once transformed into the
58    /// instance's coordinate space (`AnimationMetadata::setup_pose`).
59    pub initial_attributes: flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ssab::ssab::ss::format::InitialPartAttributes<'a>>>,
60    pub events: Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ssab::ssab::ss::format::EventsPerFrame<'a>>>>,
61    pub initial_events: Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ssab::ssab::ss::format::InitialEvents<'a>>>>,
62    pub labels: Option<flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset<ssab::ssab::ss::format::Label<'a>>>>,
63    animation: ssab::ssab::ss::format::AnimationData<'a>,
64    pub(crate) source: alloc::sync::Arc<PartCacheSource<'a>>,
65    cached_parts: once_cell::race::OnceBox<Vec<crate::eval::framedata::CachedPartData>>,
66    /// Which of the pack's mesh layouts this animation draws with
67    /// (`PartCacheSource::mesh_buffers`).
68    pub(crate) mesh_layout: usize,
69    /// Every part's base (`PartBases::build`), one slot per coordinate setup.
70    part_bases: [once_cell::race::OnceBox<crate::eval::framedata::PartBases>; 8],
71    /// The track stack's floor, one slot per coordinate setup like `part_bases`.
72    setup_pose: [once_cell::race::OnceBox<alloc::vec::Vec<crate::runtime::framedata::ss::runtime::PartState>>; 8],
73}
74
75impl AnimationMetadata<'_> {
76    /// Every part's cache for this animation, built the first time it is asked
77    /// for — in practice by the first `setup_animation` of the animation — so a
78    /// pack pays only for the animations it plays. Two first calls racing on
79    /// different threads may both build it; one result is kept.
80    pub fn cached_parts(&self) -> &[crate::eval::framedata::CachedPartData] {
81        self.cached_parts.get_or_init(|| alloc::boxed::Box::new(self.source.build(self.animation)))
82    }
83
84    /// Every part's base for this animation under one coordinate setup, built
85    /// the first time an instance with that setup plays it and shared by all of
86    /// them. Built only from attributes that never change during the animation.
87    pub(crate) fn part_bases(&self, coordinate_system: crate::eval::SsCoordinateSystem, origin: crate::eval::SsOrigin, unit: crate::eval::SsUnit) -> &crate::eval::framedata::PartBases {
88        let slot = coordinate_slot(coordinate_system, origin, unit);
89        self.part_bases[slot].get_or_init(|| alloc::boxed::Box::new(crate::eval::framedata::PartBases::build(self.cached_parts(), &self.source.keys, self.start_frame as f32, coordinate_system, origin, unit, self.canvas_width, self.canvas_height)))
90    }
91
92    /// The setup pose under one coordinate setup — the floor of the track stack —
93    /// built the first time an instance with that setup mixes tracks and shared
94    /// by all of them. A single track at full alpha never reads it, so an
95    /// animation that is only ever played alone never builds it.
96    pub(crate) fn setup_pose(&self, coordinate_system: crate::eval::SsCoordinateSystem, origin: crate::eval::SsOrigin, unit: crate::eval::SsUnit) -> &[crate::runtime::framedata::ss::runtime::PartState] {
97        self.setup_pose[coordinate_slot(coordinate_system, origin, unit)].get_or_init(|| {
98            let parts = self.cached_parts();
99            alloc::boxed::Box::new(
100                self.initial_attributes.iter().enumerate().map(|(i, a)| crate::eval::framedata::setup_pose_part(&a, parts.get(i).map_or(-1, |p| p.parent_index), coordinate_system, origin, unit, self.canvas_width, self.canvas_height)).collect(),
101            )
102        })
103    }
104
105    /// The static mesh buffers this animation draws with, built the first time
106    /// any animation with the same mesh cells asks for them and shared by all of
107    /// them.
108    pub(crate) fn static_mesh(&self) -> &StaticMeshBuffers {
109        self.source.mesh_buffers[self.mesh_layout].get_or_init(|| alloc::boxed::Box::new(StaticMeshBuffers::build(self.cached_parts())))
110    }
111}
112
113/// What a Player draws a mesh part with besides its per-frame vertices: the
114/// UVs (interleaved `[u, v, ...]`, texture-pixel space) and triangle indices of
115/// each mesh part's cell, concatenated over the parts in CSR form. Fixed by
116/// which cell each mesh part shows (its first key, by the SS mesh spec), so
117/// every animation drawing its meshes with the same cells shares one.
118pub(crate) struct StaticMeshBuffers {
119    /// CSR prefix sum over vertices, length `num_parts + 1`; slices `uvs` (two
120    /// floats a vertex) and the per-instance vertex buffers.
121    pub(crate) vertex_offsets: Vec<u32>,
122    pub(crate) uvs: Vec<f32>,
123    pub(crate) indices: Vec<i32>,
124    /// CSR prefix sum over `indices`, length `num_parts + 1`.
125    pub(crate) index_offsets: Vec<u32>,
126}
127
128impl StaticMeshBuffers {
129    fn build(cached_parts: &[crate::eval::framedata::CachedPartData]) -> Self {
130        let cell = |p: &crate::eval::framedata::CachedPartData| p.mesh_cell.clone();
131        // Non-mesh parts contribute an empty range. The Cell is the authoritative
132        // geometry source for both skeletal and Deform-only meshes; the bind
133        // cache only adds skinning.
134        let mut vertex_offsets = Vec::with_capacity(cached_parts.len() + 1);
135        let mut index_offsets = Vec::with_capacity(cached_parts.len() + 1);
136        let (mut vertices, mut indices) = (0u32, 0u32);
137        vertex_offsets.push(0);
138        index_offsets.push(0);
139        for p in cached_parts {
140            if let Some(m) = cell(p) {
141                vertices += m.num_vertices() as u32;
142                indices += m.indices.len() as u32;
143            }
144            vertex_offsets.push(vertices);
145            index_offsets.push(indices);
146        }
147
148        let mut uvs = alloc::vec![0.0; vertices as usize * 2];
149        let mut all_indices = Vec::with_capacity(indices as usize);
150        for (i, p) in cached_parts.iter().enumerate() {
151            let Some(m) = cell(p) else { continue };
152            all_indices.extend_from_slice(&m.indices);
153            // UVs share the vertex CSR; copy only when the cell vertex count
154            // matches the slot (true for well-formed meshes).
155            let (start, end) = (vertex_offsets[i] as usize, vertex_offsets[i + 1] as usize);
156            if m.uvs.len() == (end - start) * 2 {
157                uvs[start * 2..end * 2].copy_from_slice(&m.uvs);
158            }
159        }
160        Self { vertex_offsets, uvs, indices: all_indices, index_offsets }
161    }
162}
163
164/// What building an animation's part cache needs from its pack, shared by all
165/// of the pack's animations. A part's skin weights and a mesh cell's geometry
166/// are the same whichever animation plays them, so they are decoded once, at
167/// load, and every animation's `CachedPartData` shares them.
168pub(crate) struct PartCacheSource<'a> {
169    ssab: ssab::ssab::ss::format::SsAnimeBinary<'a>,
170    pub(crate) keys: crate::eval::keyframes::KeyColumns<'a>,
171    mesh_bindings: Vec<Option<alloc::sync::Arc<crate::eval::framedata::MeshBindingCache>>>,
172    /// By cell, as an index for `KeyColumns::cell`.
173    mesh_cells: alloc::collections::BTreeMap<u32, Option<alloc::sync::Arc<crate::eval::framedata::MeshCellData>>>,
174    /// One slot per distinct set of cells the pack's animations show on their
175    /// mesh parts, filled the first time an animation using it plays.
176    mesh_buffers: Vec<once_cell::race::OnceBox<StaticMeshBuffers>>,
177    /// Each animation's slot in `mesh_buffers`, by animation index.
178    mesh_layouts: Vec<usize>,
179}
180
181impl<'a> PartCacheSource<'a> {
182    fn new(ssab: ssab::ssab::ss::format::SsAnimeBinary<'a>, keys: crate::eval::keyframes::KeyColumns<'a>) -> Self {
183        let fb_parts = ssab.parts();
184        let mesh_bindings = fb_parts.iter().map(|part| crate::eval::framedata::build_mesh_binding_cache(part.mesh_binding()).map(alloc::sync::Arc::new)).collect();
185        let mut mesh_cells = alloc::collections::BTreeMap::new();
186        // Animations that show the same cell on every mesh part draw with the
187        // same static mesh buffers; number each distinct set as it appears.
188        let mut layout_of = alloc::collections::BTreeMap::<Vec<(usize, u32)>, usize>::new();
189        let mut mesh_layouts = Vec::with_capacity(ssab.animations().len());
190        for anim in ssab.animations() {
191            let mut layout = Vec::new();
192            for (i, p) in anim.parts_animation_data().iter().enumerate() {
193                if fb_parts.get(i).part_type_type() != ssab::ssab::ss::format::PartType::PartTypeMesh {
194                    continue;
195                }
196                if let Some(cell) = crate::eval::framedata::mesh_part_cell(&keys, keys.run(p.cell_keys())) {
197                    layout.push((i, cell));
198                    mesh_cells.entry(cell).or_insert_with(|| crate::eval::framedata::build_mesh_cell_data(&ssab, &keys.cell(cell).cell).map(alloc::sync::Arc::new));
199                }
200            }
201            let next = layout_of.len();
202            mesh_layouts.push(*layout_of.entry(layout).or_insert(next));
203        }
204        let mesh_buffers = (0..layout_of.len()).map(|_| once_cell::race::OnceBox::new()).collect();
205        Self { ssab, keys, mesh_bindings, mesh_cells, mesh_buffers, mesh_layouts }
206    }
207
208    fn build(&self, anim: ssab::ssab::ss::format::AnimationData<'a>) -> Vec<crate::eval::framedata::CachedPartData> {
209        let (ssab, keys) = (&self.ssab, &self.keys);
210        let fb_parts = ssab.parts();
211        let parts = anim.parts_animation_data();
212        let mut cached_parts = Vec::with_capacity(parts.len());
213
214        for (i, p) in parts.iter().enumerate() {
215            let part_meta = fb_parts.get(i);
216            let parent_index = part_meta.parent_index();
217            let blend_type = part_meta.blend_type();
218            let part_type_disc = part_meta.part_type_type();
219            let mask_influence = part_meta.mask_influence();
220            // PartTypeMask is always a pure mask; drawing parts use the unified draw_as_mask flag.
221            let is_mask_contributor = part_type_disc == ssab::ssab::ss::format::PartType::PartTypeMask || part_meta.draw_as_mask();
222            let shape_kind = part_meta.part_type_as_part_type_shape().and_then(|s| match s.shape_type() {
223                ssab::ssab::ss::format::ShapeType::Rectangle => Some(crate::eval::geometry::ShapeType::Rectangle),
224                ssab::ssab::ss::format::ShapeType::Triangle => Some(crate::eval::geometry::ShapeType::Triangle),
225                ssab::ssab::ss::format::ShapeType::Star => Some(crate::eval::geometry::ShapeType::Star),
226                ssab::ssab::ss::format::ShapeType::Arrow => Some(crate::eval::geometry::ShapeType::Arrow),
227                _ => None,
228            });
229            let nines = crate::eval::framedata::build_nines_part_data(&part_meta);
230            let mesh_binding = self.mesh_bindings[i].clone();
231            let mesh_cell = if part_type_disc == ssab::ssab::ss::format::PartType::PartTypeMesh { crate::eval::framedata::mesh_part_cell(keys, keys.run(p.cell_keys())).and_then(|cell| self.mesh_cells.get(&cell).cloned().flatten()) } else { None };
232            let name_hash = fnv1a_hash_str(part_meta.name());
233            let mut part = crate::eval::framedata::CachedPartData::new(p, keys, i as i16, parent_index, name_hash, shape_kind, nines, mesh_binding, mesh_cell, blend_type, part_type_disc, mask_influence, is_mask_contributor, anim.start_frame() as i32);
234            part.cursor_base = crate::eval::framedata::cursor_count(&cached_parts) as u32;
235            cached_parts.push(part);
236        }
237        cached_parts
238    }
239}
240
241/// The bytes of an `.ssab`, owned or borrowed from the caller.
242pub struct SsabData {
243    storage: SsabStorage,
244}
245
246impl SsabData {
247    /// Holds a copy of `ssab_data`.
248    pub fn load_copy(ssab_data: &[u8]) -> Result<Self, error::SSRuntimeError> {
249        let storage = SsabStorage::Owned(ssab_data.to_vec());
250        Ok(Self { storage })
251    }
252
253    /// Refers to the `len` bytes at `ptr` in place, with no copy.
254    ///
255    /// # Safety
256    ///
257    /// The caller must ensure:
258    /// - `ptr` is non-null and points to a valid memory block of at least `len` bytes.
259    /// - The memory remains valid and unmodified for the lifetime of the returned
260    ///   `SsabData` (and any `SsabResource` derived from it).
261    /// - If the resulting `SsabData` is sent to or shared with another thread,
262    ///   no other party may mutate the memory for the duration of the borrow.
263    ///
264    /// Returns `SSRuntimeError::InvalidParameter` if `ptr` is null.
265    pub unsafe fn load_borrow(ptr: *const u8, len: usize) -> Result<Self, error::SSRuntimeError> {
266        let Some(ptr) = ::core::ptr::NonNull::new(ptr as *mut u8) else {
267            return Err(error::SSRuntimeError::InvalidParameter);
268        };
269        Ok(Self { storage: SsabStorage::Borrowed(BorrowedBuffer { ptr, len }) })
270    }
271
272    /// The `.ssab` bytes.
273    pub fn as_slice(&self) -> &[u8] {
274        self.storage.as_slice()
275    }
276}
277
278/// A parsed `.ssab`. It is read-only, and can back any number of
279/// [`Context`](crate::Context)s.
280pub struct AnimationResource<'a> {
281    pub(crate) data: &'a [u8],
282    pub(crate) animations: Vec<AnimationMetadata<'a>>,
283    pub(crate) source: alloc::sync::Arc<PartCacheSource<'a>>,
284}
285
286/// A thread-safe, shared resource containing SSAB data and its parsed metadata.
287///
288/// This is a self-referential structure: `resource` holds borrows into `data`'s
289/// buffer. The `'static` lifetime stored internally is fictitious — the actual
290/// lifetime is bound to `&self`. The `resource()` accessor restores the correct
291/// lifetime, so external code never observes the unsound `'static` form.
292///
293/// Invariants (must hold for soundness):
294/// - Fields are private so `data` cannot be mutated or replaced after construction.
295/// - Field declaration order ensures `resource` is dropped before `data`.
296/// - An owned `SsabData` keeps its `Vec<u8>` buffer at a stable heap address; a
297///   borrowed one requires the caller to keep the memory valid (documented on
298///   `SsabData::load_borrow`).
299pub struct SsabResource {
300    resource: Option<AnimationResource<'static>>,
301    data: SsabData,
302    /// Why `resource` is `None`, kept so the binary faces can say which of the
303    /// several reasons it was. A version mismatch in particular names the two
304    /// versions, and that is the whole of what the user needs to act.
305    parse_error: Option<error::SSRuntimeError>,
306}
307
308impl SsabResource {
309    /// Parses `data` into a shareable resource. On failure the resource holds no
310    /// animation and [`Self::parse_error`] says why.
311    ///
312    /// # Safety
313    ///
314    /// The bytes must be a valid `.ssab`. They are read through FlatBuffers accessors that do not
315    /// bounds-check in release builds, so any other bytes are undefined behaviour (out-of-bounds
316    /// reads). A pack the converter wrote is valid; for any other, run the FlatBuffers verifier
317    /// first (the `ssab` crate's checked `root_as_ss_anime_binary`).
318    pub unsafe fn new(data: SsabData) -> alloc::sync::Arc<Self> {
319        let res = Self { resource: None, data, parse_error: None };
320        let mut arc = alloc::sync::Arc::new(res);
321        if let Some(mut_res) = alloc::sync::Arc::get_mut(&mut arc) {
322            // SAFETY: `mut_res.data` lives as long as `mut_res` (i.e. as long as the
323            // Arc allocation). The `AnimationResource` we build holds borrows into
324            // that buffer, but we store it as `'static` because Rust cannot express
325            // a self-borrow directly. The `resource()` accessor downgrades the lie
326            // back to a self-bound lifetime before exposing it.
327            let data_slice: &'static [u8] = unsafe { &*(mut_res.data.as_slice() as *const [u8]) };
328            // SAFETY: these are `data`'s bytes, which this function's caller guarantees are a
329            // valid `.ssab` (`# Safety`).
330            match unsafe { AnimationResource::new(data_slice) } {
331                Ok(resource) => mut_res.resource = Some(resource),
332                Err(e) => mut_res.parse_error = Some(e),
333            }
334        }
335        arc
336    }
337
338    /// Why [`Self::resource`] is `None`, or `None` when the parse succeeded.
339    #[inline]
340    pub fn parse_error(&self) -> Option<&error::SSRuntimeError> {
341        self.parse_error.as_ref()
342    }
343
344    /// Returns the parsed animation resource, with its lifetime tied to `&self`.
345    #[inline]
346    pub fn resource(&self) -> Option<&AnimationResource<'_>> {
347        self.resource.as_ref()
348    }
349
350    /// Returns the underlying SSAB data.
351    #[inline]
352    pub fn data(&self) -> &SsabData {
353        &self.data
354    }
355
356    /// Returns a raw pointer to the parsed resource (or null if parsing failed),
357    /// detached from `self`'s borrow scope.
358    ///
359    /// This is intended for FFI/WASM bindings that need to extend the resource
360    /// reference into a `'static` context while transferring ownership of the
361    /// surrounding `Arc<SsabResource>` to a long-lived holder. Using a raw
362    /// pointer breaks the borrow chain so the `Arc` can be moved into its
363    /// holder before the pointer is dereferenced.
364    ///
365    /// Obtaining the pointer is safe; dereferencing it is `unsafe` and the
366    /// caller must uphold the obligations below.
367    ///
368    /// # Caller obligations when dereferencing
369    /// - Keep some `Arc<SsabResource>` pointing at this allocation alive for the
370    ///   entire duration the pointer (or any borrow derived from it) is in use.
371    /// - Do not dereference after the last `Arc` referencing this allocation
372    ///   is dropped — doing so is undefined behaviour.
373    #[inline]
374    pub fn resource_static_ptr(&self) -> *const AnimationResource<'static> {
375        match &self.resource {
376            Some(r) => r as *const _,
377            None => ::core::ptr::null(),
378        }
379    }
380}
381
382impl<'a> AnimationResource<'a> {
383    /// Parses the animations' metadata out of `data`. Fails on a schema-version mismatch.
384    ///
385    /// # Safety
386    ///
387    /// The bytes must be a valid `.ssab`. They are read through FlatBuffers accessors that do not
388    /// bounds-check in release builds, so any other bytes are undefined behaviour (out-of-bounds
389    /// reads). A pack the converter wrote is valid; for any other, run the FlatBuffers verifier
390    /// first (the `ssab` crate's checked `root_as_ss_anime_binary`).
391    pub unsafe fn new(data: &'a [u8]) -> Result<Self, error::SSRuntimeError> {
392        // SAFETY: the caller guarantees `data` is a valid `.ssab` (`# Safety`); only the version
393        // is checked here.
394        let ssab = unsafe { ssab::ssab::ss::format::root_as_ss_anime_binary_unchecked(data) };
395        if ssab.version() != ssab::SSAB_SCHEMA_VERSION {
396            return Err(error::SSRuntimeError::InvalidVersion { expected: ssab::SSAB_SCHEMA_VERSION, got: ssab.version() });
397        }
398
399        let keys = crate::eval::keyframes::KeyColumns::new(ssab.keyframes(), ssab.cellmaps());
400        let fb_animations = ssab.animations();
401        let mut animations = Vec::with_capacity(fb_animations.len());
402        let source = alloc::sync::Arc::new(PartCacheSource::new(ssab, keys));
403
404        for (index, anim) in fb_animations.iter().enumerate() {
405            let name_hash = anim.name_hash();
406            let canvas_size = anim.canvas_size();
407            let (canvas_width, canvas_height) = (canvas_size.v1(), canvas_size.v2());
408            animations.push(AnimationMetadata {
409                name_hash,
410                start_frame: anim.start_frame() as i32,
411                end_frame: anim.end_frame() as i32,
412                fps: anim.fps() as i32,
413                canvas_width,
414                canvas_height,
415                initial_attributes: anim.parts_initial_attributes(),
416                events: anim.events(),
417                initial_events: anim.initial_events(),
418                labels: anim.labels(),
419                animation: anim,
420                source: source.clone(),
421                cached_parts: once_cell::race::OnceBox::new(),
422                mesh_layout: source.mesh_layouts[index],
423                part_bases: Default::default(),
424                setup_pose: Default::default(),
425            });
426        }
427
428        Ok(Self { data, animations, source })
429    }
430
431    /// The static mesh buffers of mesh layout `layout`, if an animation using it
432    /// has built them.
433    pub(crate) fn static_mesh(&self, layout: usize) -> Option<&StaticMeshBuffers> {
434        self.source.mesh_buffers.get(layout)?.get()
435    }
436
437    /// The `.ssab` bytes this resource reads.
438    pub fn get_ssab_data(&self) -> &'a [u8] {
439        self.data
440    }
441
442    /// The pack's animations, in the order of the ssab's `animations()`.
443    pub fn animations(&self) -> &[AnimationMetadata<'a>] {
444        &self.animations
445    }
446
447    /// The animations' names, in the same order as [`Self::animations`].
448    pub fn get_animation_names(&self) -> Vec<alloc::string::String> {
449        let ssab = unsafe { ssab::ssab::ss::format::root_as_ss_anime_binary_unchecked(self.data) };
450        let mut names = Vec::new();
451        let animations = ssab.animations();
452
453        for anim in animations {
454            names.push(alloc::string::String::from(anim.name()));
455        }
456
457        names
458    }
459
460    /// The position of the animation `name` in [`Self::animations`].
461    pub fn find_animation_index(&self, name: &str) -> Option<usize> {
462        let hash = fnv1a_hash_str(name);
463        self.find_animation_index_by_hash(hash)
464    }
465
466    /// [`Self::find_animation_index`] by the [`fnv1a_hash_str`] of the name.
467    pub fn find_animation_index_by_hash(&self, hash: u32) -> Option<usize> {
468        self.animations.iter().position(|anim| anim.name_hash == hash)
469    }
470}
471
472/// The FNV-1a hash of `text`, which is what the `.ssab` stores for a name and the
473/// `_by_hash` calls take.
474pub fn fnv1a_hash_str(text: &str) -> u32 {
475    let mut hash: u32 = 2166136261;
476    let prime: u32 = 16777619;
477
478    for b in text.bytes() {
479        hash ^= b as u32;
480        hash = hash.wrapping_mul(prime);
481    }
482    hash
483}