Skip to main content

ssplayer_wgpu/
player.rs

1//! [`SSPlayer`] — the primary public API.
2//!
3//! Owns a tree of runtime `Context`s, one per animation instance, and holds no
4//! GPU resource: the host lends `Device` and `Queue` on every `update`.
5//!
6//! Instance parts play a sub-animation from another `.ssab` pack. Each instance
7//! child gets its **own** `Context`, and so its own SoA buffer, which is what
8//! keeps a child's frame from overwriting its parent's. The host registers every
9//! pack via [`SSPlayer::add_ssab`]; external references resolve by pack name.
10
11use crate::events::{SsEvent, decode_events};
12use crate::frame::FrameView;
13use crate::mask::{GeomKind, MaskOp, MaskWriter, PartMaskFlags, ScopedWriter, StencilTest, plan_writers_into};
14use crate::pack::{EmbeddedImage, SSPack, TextureRef};
15use crate::renderer::{CROWD_SHIFT, Retention, SSRenderer};
16use crate::scene::{BatchInfo, FrameChunk, NodeSlot, mat4_mul, pack_tint};
17use ssab::ssab::ss::format::{PartType, root_as_ss_anime_binary_unchecked};
18use ssruntime::error::SSRuntimeError;
19use ssruntime::runtime::framedata::ss::runtime::{DrawBatchKind, root_as_frame_data_unchecked};
20use ssruntime::{Context, EffectSlot, InstanceSlot, TrackBlend, TrackSync};
21use std::collections::{HashMap, HashSet};
22use std::sync::Arc;
23use std::sync::atomic::{AtomicU32, Ordering};
24
25/// The tint that changes nothing — white, in the `0xRRGGBB` order
26/// [`SSPlayer::set_tint`] takes. Deliberately not `pub`: cbindgen sweeps every
27/// module-level `pub const` into the C header.
28pub(crate) const WHITE_TINT: u32 = 0x00FF_FFFF;
29
30/// Column-major 4x4 identity.
31const IDENTITY: [f32; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
32
33/// The three things the loading walk cannot do for itself: reach a file, decode
34/// an image, and know what the renderer already holds.
35///
36/// **This is the whole of the platform-specific part of loading.** Everything
37/// else — reading both texture tables, deduplicating by file, walking instance
38/// references transitively — is the same everywhere and lives in
39/// [`SSPlayer::load_with`], so a face cannot quietly implement half of it.
40///
41/// Two implementations ship: the filesystem behind [`SSPlayer::load`], and the
42/// web face's (`fetch` + `createImageBitmap`, whose pixels reach the GPU without
43/// passing through wasm memory at all). An engine integration writes a
44/// third and gets the walk for free — which it must, because an exported Godot
45/// project keeps its resources in a `.pck` and a Unity one in an APK, where no
46/// `File::open` will reach them.
47///
48/// `async` because a browser leaves no choice; a native implementation simply
49/// does not await anything, and its caller blocks on the future.
50// No `Send` bound: the web implementation holds `Rc`, and nothing here is
51// spawned onto another thread.
52#[allow(async_fn_in_trait)]
53pub trait AssetLoader {
54    /// Go back to the root you were built with, discarding whatever base a
55    /// previous load left behind.
56    ///
57    /// [`SSPlayer::load_with`] calls this first, before it reads anything. It is
58    /// what lets one loader serve more than one load: without it the base set by
59    /// the last load is still in force when the next `src` is read, and a second
60    /// `load_with(loader, "overall/Other.ssab")` looks in `overall/overall`. An
61    /// engine adapter holding a single loader over its
62    /// `AssetServer` / `ResourceLoader` / `.pck` handle is the shape that needs
63    /// this; nothing else about the walk changes.
64    ///
65    /// Keep the root the caller gave you, and restore it here — do not try to undo
66    /// [`AssetLoader::set_base`] by walking back up, which cannot be right for a
67    /// URL and is not always right for a path.
68    fn reset_base(&mut self);
69
70    /// Re-root yourself at the directory `src` turned out to live in: every path
71    /// the walk asks for after this is named relative to **that**.
72    ///
73    /// `src` is the pack's own path — *not* its directory. Resolving it, and
74    /// deciding what "its directory" means, is the whole reason this method
75    /// exists: only the implementation knows whether it is holding a filesystem
76    /// path, a URL, or an archive key, and each of those cuts a directory
77    /// differently. `Path::parent` and a `URL` base already know their own
78    /// vocabulary; the walk, serving all three at once, did not.
79    ///
80    /// Resolve `src` **against the base you were constructed with**, then take its
81    /// directory, so a loader that starts out rooted somewhere (a Godot `res://`
82    /// prefix, an archive subtree) stays inside it.
83    ///
84    /// **Derived from the root you were built with, not folded into the base a
85    /// previous call left behind**, so that this is idempotent and pairs with
86    /// [`AssetLoader::reset_base`]: two loads through one loader land on the same
87    /// base the two would have reached separately.
88    ///
89    /// [`SSPlayer::load_with`] calls this exactly once per load, **after** reading
90    /// the pack and before asking for anything else, so `src` is read while the
91    /// base is still whatever the caller set up and can never be resolved against
92    /// itself. [`SSPlayer::load_assets`] does not call it at all — a caller
93    /// reaching for that one is expected to have rooted the loader itself.
94    fn set_base(&mut self, src: &str);
95
96    /// Read every path — **all of them at once**, so an implementation that can
97    /// overlap the waiting does (the web one issues one `fetch` per path and
98    /// settles them together). Results are positional; `None` is "this one did
99    /// not arrive", which is never fatal to the rest.
100    ///
101    /// Every path is relative to the base — bare, never joined onto anything by
102    /// the caller. The one exception is the first call of a
103    /// [`SSPlayer::load_with`], which is `src` itself, verbatim, before
104    /// [`AssetLoader::set_base`] has been called.
105    async fn read(&mut self, paths: &[String]) -> Vec<Option<Vec<u8>>>;
106
107    /// Bytes for an instance-referenced pack, **by the name it is referenced
108    /// under** rather than by a path.
109    ///
110    /// Tried before `<the .ssab's directory>/<name>.ssab`, and returning `None`
111    /// — the default — falls back to exactly that. Implement it where a pack is
112    /// addressable by name but not by path: an archive keyed by pack name, an
113    /// engine's asset server, bytes a drop handler is already holding.
114    ///
115    /// The alternative is to register the pack with [`SSPlayer::add_ssab`] before
116    /// loading — the walk skips a pack it already has — but that means knowing
117    /// which packs a `.ssab` references before reading it. This is for letting
118    /// the walk ask instead.
119    ///
120    /// Called once per name, not batched: a provider is normally a lookup in
121    /// something already in memory, and the batching exists for the reads that
122    /// actually wait.
123    async fn read_pack(&mut self, _name: &str) -> Option<Vec<u8>> {
124        None
125    }
126
127    /// Which renderer key `path`'s image belongs under.
128    ///
129    /// **A cellmap hash names a slot inside one `.ssab`, not an image.** Some
130    /// tools name the atlas `spritemap1.png` in every project they export, so two packs
131    /// from two projects ask for one hash and mean two different atlases; keyed by
132    /// the hash alone, the second registration is skipped as "already held" and
133    /// that pack silently draws the first one's atlas. Resolving `path` the way
134    /// [`AssetLoader::read`] would and hashing **that** is what tells them apart,
135    /// and it is the implementation that knows how — a path, a URL and an archive
136    /// key each resolve differently, which is the same reason
137    /// [`AssetLoader::set_base`] exists.
138    ///
139    /// Equal keys must mean the same pixels: that is what keeps the sibling packs
140    /// of one project — all naming the one atlas beside them — to a single upload.
141    /// Answering differently for two names of one file costs an upload, which is
142    /// the harmless direction; answering alike for two files draws the wrong
143    /// picture.
144    ///
145    /// The default answers `cellmap_hash`, which is enough for a loader that never
146    /// serves two projects to one renderer.
147    fn texture_key(&self, _path: &str, cellmap_hash: u32) -> u32 {
148        cellmap_hash
149    }
150
151    /// Decode `encoded` (a PNG, as the exporter wrote it) and register it under
152    /// `key` — what [`AssetLoader::texture_key`] answered for it, and what the
153    /// player will translate a draw batch's cellmap hash into.
154    async fn supply_texture(&mut self, key: u32, encoded: &[u8]);
155
156    /// Whether an atlas is already registered for `key` — a hint, used to skip
157    /// reading a file nobody will need. `key` is
158    /// [`AssetLoader::texture_key`]'s answer, not a cellmap hash.
159    ///
160    /// Best effort: a loader that cannot see the renderer answers `false` and
161    /// lets the flush make the real decision. The texture map is device-scoped, so the authoritative check is the one that keeps N players of
162    /// one pack to one decode and one upload between them.
163    fn has_texture(&self, key: u32) -> bool;
164
165    /// Report a file that could not be loaded. One missing atlas or sub-pack
166    /// costs you that one thing, not the character, so this is a diagnostic
167    /// rather than an error.
168    fn warn(&self, message: &str);
169}
170
171/// Point every planned writer's cutout at the renderer key its node's pack
172/// resolved to. A writer's `texture_hash` comes from the batch it belongs to, so
173/// it arrives in cellmap-hash terms like every other one.
174fn retarget(writers: &mut [MaskWriter], keys: &AtlasKeys) {
175    for writer in writers.iter_mut() {
176        writer.texture_hash = keys.resolve(writer.texture_hash);
177    }
178}
179
180/// Re-read every node's table from the player's, for the whole tree.
181///
182/// Recursive because an instance child is a node on its own pack: one `.ssab`
183/// learning where its atlas went says nothing about the sibling packs its
184/// instance parts play from, and those learn theirs on their own pass.
185fn refresh_atlas_keys(node: &mut PlaybackNode, atlas_keys: &HashMap<String, Arc<AtlasKeys>>) {
186    node.atlas_keys = node_atlas_keys(atlas_keys, &node.pack);
187    for child in node.instances.values_mut() {
188        refresh_atlas_keys(&mut child.node, atlas_keys);
189    }
190}
191
192/// The table for one pack, or an empty one when the player has never seen its
193/// atlases — in which case every slot resolves to itself.
194fn node_atlas_keys(atlas_keys: &HashMap<String, Arc<AtlasKeys>>, pack: &str) -> Arc<AtlasKeys> {
195    atlas_keys.get(pack).cloned().unwrap_or_default()
196}
197
198/// fnv1a over bytes — the construction `ssruntime::fnv1a_hash_str` applies to a
199/// `str`, which is the only form the runtime ever needs.
200fn fnv1a_bytes(bytes: &[u8]) -> u32 {
201    let mut hash: u32 = 2166136261;
202    for b in bytes {
203        hash ^= *b as u32;
204        hash = hash.wrapping_mul(16777619);
205    }
206    hash
207}
208
209/// The renderer key for one atlas slot.
210///
211/// **Embedded atlases are keyed by their own bytes.** They have no location to
212/// resolve — they are inside the `.ssab` — and hashing the pixels is what keeps
213/// two players that each read the same embedded pack from the disk to one
214/// upload between them, which keying by pack identity would lose.
215///
216/// A reference-mode atlas is keyed by where it resolves to, which is
217/// [`AssetLoader::texture_key`]'s answer: the bytes are not in hand yet, and the
218/// decision has to be made before [`AssetLoader::has_texture`] is asked.
219fn atlas_key(loader: &impl AssetLoader, texture: &TextureRef, embedded: Option<&[u8]>) -> u32 {
220    match embedded {
221        Some(bytes) => fnv1a_bytes(bytes),
222        None => loader.texture_key(&texture.path, texture.slot),
223    }
224}
225
226/// Which renderer key each of one pack's cellmaps resolves to.
227///
228/// The runtime speaks in cellmap hashes — `DrawBatch.texture_hash`, an effect
229/// command's `cellmap_hash`, a mask writer's cutout — and a cellmap hash is
230/// unique only *inside* its own `.ssab`. [`SSRenderer`]'s texture map is scoped
231/// to the device instead, because that is what lets N players of one pack share
232/// one upload. This is the join between the two: the player assigns a key that
233/// identifies the image (see [`AssetLoader::texture_key`]) and translates every
234/// hash through this table on the way to a draw call.
235///
236/// A slot with no entry resolves to itself: the cellmap hash is the key, for a
237/// pack whose atlases the host registered against [`SSRenderer`] directly.
238///
239/// A `Vec` rather than a map: packs have a handful of cellmaps (usually one), and
240/// this is read once per draw batch.
241#[derive(Clone, Debug, Default)]
242pub struct AtlasKeys(Vec<(u32, u32)>);
243
244impl AtlasKeys {
245    /// The renderer key for `cellmap_hash`, or `cellmap_hash` itself when this
246    /// table says nothing about it.
247    pub fn resolve(&self, cellmap_hash: u32) -> u32 {
248        self.0.iter().find(|(hash, _)| *hash == cellmap_hash).map(|(_, key)| *key).unwrap_or(cellmap_hash)
249    }
250
251    /// Whether this table says anything about `cellmap_hash`.
252    fn has(&self, cellmap_hash: u32) -> bool {
253        self.0.iter().any(|(hash, _)| *hash == cellmap_hash)
254    }
255
256    /// Record — or correct — where `cellmap_hash` points.
257    ///
258    /// Last writer wins, which is the same rule the load walk follows for the
259    /// bytes themselves: a reload that finds a different file behind one name is
260    /// re-registering it, not adding a second.
261    fn set(&mut self, cellmap_hash: u32, key: u32) {
262        match self.0.iter_mut().find(|(hash, _)| *hash == cellmap_hash) {
263            Some(entry) => entry.1 = key,
264            None => self.0.push((cellmap_hash, key)),
265        }
266    }
267
268    fn is_empty(&self) -> bool {
269        self.0.is_empty()
270    }
271}
272
273/// What kind of thing [`SSPlayer::load`] could not get.
274#[derive(Clone, Copy, Debug, PartialEq, Eq)]
275pub enum MissingKind {
276    /// An atlas. The parts that use it draw against the 1x1 white fallback, so
277    /// they appear as silhouettes rather than not at all.
278    Texture,
279    /// An animation pack an instance part plays from. Those parts do not appear.
280    Pack,
281}
282
283/// Something a load needed and did not get.
284///
285/// A missing file is deliberately **not** an error: one unreadable atlas must not
286/// cost you the character, so [`SSPlayer::load`] reports `Err` only when the
287/// `.ssab` itself is unreadable. That leaves the caller unable to tell a complete
288/// load from a partial one, which is what this answers — the human-facing half is
289/// [`AssetLoader::warn`], and this is the half a program can branch on.
290#[derive(Clone, Debug)]
291pub struct MissingAsset {
292    /// Whether a texture or a pack is missing.
293    pub kind: MissingKind,
294    /// What was asked for: for a texture, the path the exporter wrote —
295    /// relative to its pack's directory, which is what the loader resolved it
296    /// against and the only form the walk ever sees. For a pack, its name.
297    pub name: String,
298    /// For a texture, the slot a draw batch will ask for — a cellmap's
299    /// `name_hash`, which [`SSPlayer::texture_key`] turns into the renderer's
300    /// key. Zero for a pack, whose identity is its name.
301    pub slot: u32,
302}
303
304/// Which way the playhead walks the animation.
305///
306/// Deliberately a type of this crate rather than a re-export of the runtime's:
307/// the runtime discriminates `Forward = 1 / Backward = -1` (it multiplies by
308/// them), while every other face of every Player — the C API, the wasm build,
309/// and so the sibling Players — uses `0 / 1`. Re-exporting would leak `-1` into
310/// the `js` and `ffi` faces and silently disagree with all of them, so the wire
311/// value is pinned here and converted at the runtime boundary.
312#[derive(Clone, Copy, Debug, PartialEq, Eq)]
313pub enum PlaybackDirection {
314    Forward,
315    Backward,
316}
317
318impl PlaybackDirection {
319    /// The value crossing the `js` / `ffi` faces: `0` forward, `1` backward.
320    pub fn as_wire(self) -> i32 {
321        match self {
322            Self::Forward => 0,
323            Self::Backward => 1,
324        }
325    }
326
327    /// Anything other than `1` reads as forward, matching the C API's own
328    /// `direction == 0` test rather than rejecting unknown input.
329    pub fn from_wire(value: i32) -> Self {
330        if value == 1 { Self::Backward } else { Self::Forward }
331    }
332}
333
334impl From<PlaybackDirection> for ssruntime::eval::playback_controller::PlaybackDirection {
335    fn from(value: PlaybackDirection) -> Self {
336        match value {
337            PlaybackDirection::Forward => Self::Forward,
338            PlaybackDirection::Backward => Self::Backward,
339        }
340    }
341}
342
343impl From<ssruntime::eval::playback_controller::PlaybackDirection> for PlaybackDirection {
344    fn from(value: ssruntime::eval::playback_controller::PlaybackDirection) -> Self {
345        match value {
346            ssruntime::eval::playback_controller::PlaybackDirection::Forward => Self::Forward,
347            ssruntime::eval::playback_controller::PlaybackDirection::Backward => Self::Backward,
348        }
349    }
350}
351
352/// What happens when the playhead reaches the far end of the range.
353#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum PlaybackStyle {
355    /// Jump back to the start, or stop, according to the loop count.
356    Normal,
357    /// Turn around and walk back, so one loop is a full round trip.
358    PingPong,
359}
360
361impl PlaybackStyle {
362    /// See [`PlaybackDirection::as_wire`].
363    pub fn as_wire(self) -> i32 {
364        match self {
365            Self::Normal => 0,
366            Self::PingPong => 1,
367        }
368    }
369
370    /// See [`PlaybackDirection::from_wire`].
371    pub fn from_wire(value: i32) -> Self {
372        if value == 1 { Self::PingPong } else { Self::Normal }
373    }
374}
375
376impl From<PlaybackStyle> for ssruntime::eval::playback_controller::PlaybackStyle {
377    fn from(value: PlaybackStyle) -> Self {
378        match value {
379            PlaybackStyle::Normal => Self::Normal,
380            PlaybackStyle::PingPong => Self::PingPong,
381        }
382    }
383}
384
385impl From<ssruntime::eval::playback_controller::PlaybackStyle> for PlaybackStyle {
386    fn from(value: ssruntime::eval::playback_controller::PlaybackStyle) -> Self {
387        match value {
388            ssruntime::eval::playback_controller::PlaybackStyle::Normal => Self::Normal,
389            ssruntime::eval::playback_controller::PlaybackStyle::PingPong => Self::PingPong,
390        }
391    }
392}
393
394/// How an override's colour combines with what is underneath — the same four
395/// operations the authored PartColor offers.
396#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
397pub enum BlendOp {
398    #[default]
399    Mix,
400    Mul,
401    Add,
402    Sub,
403}
404
405impl BlendOp {
406    /// The value crossing the `js` / `ffi` faces, and what the runtime takes.
407    pub fn as_wire(self) -> u8 {
408        match self {
409            Self::Mix => 0,
410            Self::Mul => 1,
411            Self::Add => 2,
412            Self::Sub => 3,
413        }
414    }
415
416    /// `None` for anything outside `0..=3`, so a bad value from a C or JS caller
417    /// becomes a rejected call rather than a silently different blend.
418    pub fn from_wire(value: u8) -> Option<Self> {
419        match value {
420            0 => Some(Self::Mix),
421            1 => Some(Self::Mul),
422            2 => Some(Self::Add),
423            3 => Some(Self::Sub),
424            _ => None,
425        }
426    }
427}
428
429/// How long an override outlives the keyframes it beats.
430///
431/// Visibility has no priority: a force-hide always wins, and is always cleared
432/// when a new animation is set up.
433#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
434pub enum OverridePriority {
435    /// Holds until the animation next drives that attribute, so it shows only
436    /// on frames the animation leaves alone.
437    OverwriteOnNextKeyframe,
438    /// Holds for the current animation, and is cleared when another is set up.
439    #[default]
440    HoldUntilNextAnimation,
441    /// Holds for as long as the same pack is playing, surviving animation
442    /// changes.
443    Permanent,
444}
445
446impl OverridePriority {
447    /// See [`BlendOp::as_wire`].
448    pub fn as_wire(self) -> u8 {
449        match self {
450            Self::OverwriteOnNextKeyframe => 0,
451            Self::HoldUntilNextAnimation => 1,
452            Self::Permanent => 2,
453        }
454    }
455
456    /// See [`BlendOp::from_wire`].
457    pub fn from_wire(value: u8) -> Option<Self> {
458        match value {
459            0 => Some(Self::OverwriteOnNextKeyframe),
460            1 => Some(Self::HoldUntilNextAnimation),
461            2 => Some(Self::Permanent),
462            _ => None,
463        }
464    }
465}
466
467/// The most members [`SSPlayer::set_crowd`] draws; those past it are left out.
468pub const MAX_CROWD_MEMBERS: usize = 1 << CROWD_SHIFT;
469
470/// One of the copies [`SSPlayer::set_crowd`] draws: where it stands, and how it
471/// is faded and tinted, each on top of the player's own.
472///
473/// The placement is in [`SSPlayer::set_transform`]'s terms and is composed under
474/// it, so the player's own transform moves the whole crowd. The default stands
475/// where the player does, unfaded and untinted.
476#[derive(Clone, Copy, Debug, PartialEq)]
477pub struct CrowdMember {
478    /// Horizontal position, in the same terms as `set_transform`'s.
479    pub x: f32,
480    /// Measured downward, as `set_transform`'s is.
481    pub y: f32,
482    /// Horizontal scale; negative mirrors.
483    pub scale_x: f32,
484    /// Vertical scale; negative mirrors.
485    pub scale_y: f32,
486    /// Radians.
487    pub rotation: f32,
488    /// Multiplied into the player's alpha, part by part; clamped to 0..=1.
489    pub alpha: f32,
490    /// `0xRRGGBB`, multiplied into the player's tint.
491    pub tint: u32,
492}
493
494impl Default for CrowdMember {
495    fn default() -> Self {
496        Self { x: 0.0, y: 0.0, scale_x: 1.0, scale_y: 1.0, rotation: 0.0, alpha: 1.0, tint: WHITE_TINT }
497    }
498}
499
500impl CrowdMember {
501    /// The member's placement, composed as `set_transform` composes the player's.
502    pub(crate) fn matrix(&self) -> [f32; 16] {
503        placement(self.x, self.y, self.scale_x, self.scale_y, self.rotation)
504    }
505}
506
507/// Translation, scale, then rotation in radians, as a column-major matrix: the
508/// columns are scale*rotation for x and y, then z, then the translation.
509fn placement(x: f32, y: f32, scale_x: f32, scale_y: f32, rotation: f32) -> [f32; 16] {
510    let (sin, cos) = rotation.sin_cos();
511    #[rustfmt::skip]
512    let m = [
513        scale_x * cos, scale_x * sin, 0.0, 0.0,
514        -scale_y * sin, scale_y * cos, 0.0, 0.0,
515        0.0, 0.0, 1.0, 0.0,
516        x, y, 0.0, 1.0,
517    ];
518    m
519}
520
521/// Refill `out` with the timeline events the node's last update crossed.
522///
523/// Cleared first, so it always describes the tick that just ran and never
524/// accumulates. Bails before touching the `.ssab` when the runtime reports
525/// nothing, which is the overwhelmingly common case — a frame with no events
526/// costs one integer read.
527///
528/// Each index addresses the event table of **the animation of the source that
529/// fired it**, so the table is looked up per event: a crossfade on track 0 hands
530/// the track to another animation than the one `set_animation` chose.
531fn collect_events(node: &PlaybackNode, out: &mut Vec<SsEvent>) {
532    out.clear();
533    let indices = node.context.get_passed_event_indices();
534    if indices.is_empty() {
535        return;
536    }
537    let Some(ssab_bytes) = node.context.get_ssab_data() else {
538        return;
539    };
540    // SAFETY: the buffer the node was built from, which the host guaranteed is a valid
541    // `.ssab` (`SSPack::build`).
542    let ab = unsafe { root_as_ss_anime_binary_unchecked(ssab_bytes) };
543    let animations = ab.animations();
544    let sources = node.context.get_passed_event_source_handles();
545    for (&index, &source) in indices.iter().zip(sources) {
546        let Some(anim_index) = node.context.get_source_animation_index(source) else {
547            continue;
548        };
549        if anim_index as usize >= animations.len() {
550            continue;
551        }
552        decode_events(&ab, &animations.get(anim_index as usize), source, &[index], out);
553    }
554}
555
556/// One node in the playback tree: a runtime context plus its instance children
557/// and effect slots.
558struct PlaybackNode {
559    context: Context<'static>,
560    /// The resource this node's context is bound to, for **identity** only.
561    /// `set_animation` compares it with the main pack's current resource to
562    /// decide whether the context can be handed a new clip (the cheap path, and
563    /// the one that keeps the runtime's transport settings) or has to be rebuilt
564    /// against a resource that has since been replaced.
565    ///
566    /// A shared reference rather than the `*const` the pointer comparison wants:
567    /// a raw pointer is neither `Send` nor `Sync`, and storing one here would
568    /// take both off `SSPlayer` — which the Bevy adapter needs to hold it in the
569    /// ECS at all. The context already holds the same reference.
570    res: &'static ssruntime::AnimationResource<'static>,
571    /// Instance children keyed by part index (index into parts/draw_order/SoA).
572    instances: HashMap<usize, InstanceChild>,
573    /// Effect slots keyed by part index. Effects reuse this node's context
574    /// (no separate context, unlike instances).
575    effects: HashMap<usize, EffectPart>,
576    /// The clock [`step_slots`] handed this node's effect slots for the tick,
577    /// held until [`step_effects`] steps them; `None` once it has.
578    effect_clock: Option<EffectClock>,
579    /// Static per-part mask flags, indexed by part index. Read once from ssab
580    /// `PartData` at build time. Empty when the pack has no ssab data.
581    mask_flags: Vec<PartMaskFlags>,
582    /// Which pack this node plays from — the name `atlas_keys` is filed under.
583    /// `res` identifies the same thing but only by pointer, and a refresh needs
584    /// to look the table up by name.
585    pack: String,
586    /// Where this node's pack's cellmap hashes point in the renderer's texture
587    /// map. Read at build time, because the draw walk needs it per batch, and
588    /// re-read by [`refresh_atlas_keys`] when a load moves an atlas.
589    ///
590    /// Per node rather than per player because a node plays from *one* pack
591    /// while the tree spans several — an instance part's sub-animation is a
592    /// child node on its own pack, and that is exactly the case two projects'
593    /// `spritemap1` would be confused across.
594    atlas_keys: Arc<AtlasKeys>,
595}
596
597/// One instance part: its slot, the sub-animation it drives, and what the last
598/// [`step_slots`] left behind for the draw walk to use.
599struct InstanceChild {
600    slot: InstanceSlot,
601    node: Box<PlaybackNode>,
602    /// Frame the slot last left the child on. Read raw — rounding it and writing
603    /// it back would truncate sub-frame progress every tick.
604    frame_no: f32,
605    /// Whether the slot says the child is showing this frame.
606    visible: bool,
607    /// The child's node in this frame's walk, or `None` when the walk did not
608    /// prepare it. Set for every instance part in its node's `draw_order`, which
609    /// are the only ones the draw walk looks up.
610    prep: Option<usize>,
611}
612
613/// One effect part: its slot, and the draw plan the last [`step_effects`] produced.
614struct EffectPart {
615    slot: EffectSlot<'static>,
616    /// This frame's plan, empty when the effect produced nothing or its part is
617    /// not drawn.
618    ///
619    /// Copied rather than borrowed: the buffer behind `step`'s result belongs to
620    /// the slot, and the draw walk that consumes it is a later walk than the one
621    /// that steps. Keeping the raw pointer instead would cost `SSPlayer: Send`,
622    /// which a host that moves players between its own threads needs. The
623    /// allocation is reused frame to frame, so
624    /// the price is one memcpy per effect.
625    plan: Vec<u8>,
626}
627
628/// What an effect slot steps with, as [`step_slots`] read it for the slot's node:
629/// the node's playhead (raw, never floored), the time the tick is worth to it, and
630/// its loop edge.
631#[derive(Clone, Copy)]
632struct EffectClock {
633    frame_no: f32,
634    delta_secs: f32,
635    looped: bool,
636}
637
638/// The SpriteStudio player. One instance owns one animation-instance tree.
639pub struct SSPlayer {
640    /// The playback tree. Declared before `packs` and `retired` because its
641    /// contexts borrow the resources they hold, and fields drop in declaration
642    /// order.
643    root: Option<PlaybackNode>,
644    /// All registered packs, keyed by pack name (matches `ref_anime_pack`).
645    /// Cloning a pack shares its parse and its bytes, so N players of
646    /// one character cost one copy of the `.ssab` between them.
647    packs: HashMap<String, SSPack>,
648    /// Packs that were replaced under a name the live tree may still be playing
649    /// from, kept alive until the tree is rebuilt.
650    ///
651    /// [`build_node`] binds each `Context` to a resource by **raw pointer**, and
652    /// the `Arc` keeping that resource alive lives in `packs` — so re-registering
653    /// a name (`add_pack` / `add_ssab`) would free the very resource the tree is
654    /// still evaluating. Retiring the old pack here is what keeps
655    /// `resource_static_ptr`'s contract ("keep some `Arc` alive for as long as
656    /// the pointer is in use"); the tree goes on playing the data it was built
657    /// from, and [`SSPlayer::set_animation`] — the one call that rebuilds it —
658    /// releases these.
659    retired: Vec<SSPack>,
660    main_pack: Option<String>,
661    current_animation: Option<String>,
662    /// Packs a load registered on its own: the `.ssab` [`SSPlayer::load_with`]
663    /// read, and the sibling packs its walk found. The next [`SSPlayer::set_pack`]
664    /// drops them, so a second load reads its own siblings rather than finding the
665    /// last load's under the same name. Packs the host registered stay.
666    loaded_packs: Vec<String>,
667    /// Names of packs whose embedded atlases have not been offered to
668    /// a renderer yet. The offer happens on the next `update`, which is the
669    /// earliest point the borrow model lends a `Device`/`Queue`; the decode itself
670    /// waits until then too, so a pack whose atlas is already registered is never
671    /// decoded at all.
672    packs_awaiting_textures: Vec<String>,
673    /// Atlases a host-side load read but has not handed to a renderer yet, still
674    /// **encoded**.
675    ///
676    /// The reference-mode twin of `packs_awaiting_textures`, and deliberately the
677    /// same mechanism: [`SSPlayer::load`] borrows no `Device`/`Queue` — the borrow
678    /// model gives it none until `update` — so what it reads waits here for the
679    /// same flush that decodes the embedded ones. Encoded rather than decoded
680    /// because a 2048² atlas is a few hundred KB here against 16 MB of pixels,
681    /// and because it puts both routes on one timeline.
682    pending_images: Vec<(u32, Vec<u8>)>,
683    /// Per pack name, which renderer key each of its cellmaps resolves to.
684    ///
685    /// Filled as the atlases arrive — by the load walk for the ones it read, and
686    /// by the flush for embedded ones — and read by [`build_node`], which hands
687    /// each node the table for the pack it plays from. Per *pack* and not per
688    /// player because one player holds the sibling packs its instance parts
689    /// reference, and a host is free to [`SSPlayer::add_ssab`] packs from two
690    /// projects into one player, which is exactly where two `spritemap1`s meet.
691    ///
692    /// `Arc` because every node clones it, and because replacing a pack must not
693    /// disturb the tree still playing the old one.
694    atlas_keys: HashMap<String, Arc<AtlasKeys>>,
695    /// What the last load could not get. Reset by each [`SSPlayer::load_with`]
696    /// and [`SSPlayer::set_pack`], appended to as the walk gives up on a file.
697    missing: Vec<MissingAsset>,
698    /// Timeline events the last `build_frame` crossed. Cleared and refilled per
699    /// update, and reused rather than reallocated — a frame with no events costs
700    /// nothing beyond the `get_passed_event_indices` read.
701    events: Vec<SsEvent>,
702    /// Whether the last update crossed a loop boundary. A pulse the runtime
703    /// clears on entry to every update, so it is captured there and mirrored
704    /// here for the host to read afterwards.
705    looped: bool,
706    /// Whether the last update ran. A culled tick leaves the runtime's per-track
707    /// pulses where the last tick that ran left them, so the per-track reads
708    /// that pass them on check this first.
709    ran: bool,
710    /// Whether the last update *completed* playback — the rising edge of the
711    /// runtime's sticky `is_finished`, not the flag itself.
712    finished_edge: bool,
713    /// The latch that makes `finished_edge` an edge.
714    ///
715    /// Held explicitly rather than leaning on an earlier `is_playing` guard.
716    /// `play` resets it, or the next completion goes unreported.
717    prev_finished: bool,
718    /// Whether the last update was the first to run after a `play`.
719    started_edge: bool,
720    /// A `play` that no tick has run since. The tick reports it, not the call,
721    /// so a culled player's skipped tick leaves it for the first one that runs.
722    start_pending: bool,
723    /// Where this player sits in the scene — the root transform of its tree,
724    /// composed by [`SSPlayer::set_transform`].
725    transform: [f32; 16],
726    /// Draw order within a scene; lower draws first. Nothing in this file reads
727    /// it — it exists so the host and [`crate::SSScene`] can sort by it.
728    order: i32,
729    /// Draw nothing when false, while the timeline keeps running (see
730    /// [`SSPlayer::set_visible`]).
731    visible: bool,
732    /// Skip this player entirely when true (see [`SSPlayer::set_culled`]).
733    culled: bool,
734    /// Player-level fade folded into every vertex (see [`BatchInfo::alpha`]).
735    alpha: f32,
736    /// The copies [`SSPlayer::set_crowd`] asked for, clamped as they came in.
737    /// Empty draws the player once, at its own placement. Refilled in place, so
738    /// a host that moves its crowd every frame allocates nothing.
739    crowd: Vec<CrowdMember>,
740    /// Player-level tint as the API gives it, `0xRRGGBB` (see
741    /// [`SSPlayer::set_tint`]). Kept in that order rather than the shader's so a
742    /// reader of this field sees what the caller passed; `pack_tint` converts it
743    /// once per frame.
744    tint: u32,
745    /// The loop count the host chose, re-applied whenever track 0's animation
746    /// changes hands: `set_animation`, and a `set_track_animation` or
747    /// `crossfade` on track 0.
748    ///
749    /// Held because the runtime resets the count on every transition,
750    /// deliberately, because a transition is what states it.
751    ///
752    /// `None` until the host sets one, so a count it never chose is never
753    /// written over the animation's own default.
754    loop_count: Option<i32>,
755    /// The rest of the transport the host chose — speed, the frame-rate
756    /// override, frame skip, the direction and style — handed to every root
757    /// context this player builds.
758    ///
759    /// The runtime carries these across a `setup_animation` itself, but they
760    /// live on its context, and this player builds a new one for its first
761    /// animation and whenever the pack behind it changes. Holding them here is
762    /// what makes the settings hold from before the first animation and across a
763    /// pack change. Only the setters below write them, so the
764    /// copy cannot drift from the context it was handed to.
765    transport: HostTransport,
766    /// Whether the *display* frame keeps its fraction (see
767    /// [`SSPlayer::set_sub_frame_enabled`]). The playhead is an `f32` either way.
768    sub_frame: bool,
769    /// This player's identity, drawn once from [`NEXT_PLAYER_ID`]. It exists for
770    /// one reason: a runtime texture override ([`SSPlayer::set_cellmap_texture`])
771    /// registers its replacement in the device-scoped renderer under a *private*
772    /// key, and two players overriding the same cellmap must not collide on it.
773    /// Mixing this id into that key is what keeps the override per player.
774    id: u32,
775    /// Active runtime texture overrides, per pack name. Each entry redirects one
776    /// cellmap's draws to a private renderer key; the map here is the source of
777    /// truth a reload re-applies against (`record_atlas_keys`), so the redirect
778    /// survives the atlas being re-registered under a new base key.
779    overrides: HashMap<String, Vec<CellmapOverride>>,
780    /// Override pixels a `set_cellmap_texture` accepted but has not handed to a
781    /// renderer yet — the same borrow-model deferral as [`pending_images`](Self::pending_images):
782    /// the player is lent no `Device`/`Queue` until `update`, so the upload waits
783    /// for the same flush. `(private key, straight-alpha RGBA8, width, height)`.
784    pending_overrides: Vec<(u32, Vec<u8>, u32, u32)>,
785    /// Private override keys a restore has retired, dropped from the renderer on
786    /// the next flush. Deferred for the same reason as the uploads.
787    pending_forgets: Vec<u32>,
788    /// What one frame's draw walk fills, emptied after it rather than dropped.
789    walk: Walk,
790    /// A call since the last build changed what the tree draws, so the next
791    /// update has to build it even if nothing in it moves (see
792    /// [`SSPlayer::settled`]). Lowered by the build that follows; a scene whose
793    /// players are all settled keeps the frame it built last.
794    rebuild: bool,
795}
796
797/// The transport settings of [`SSPlayer::transport`](SSPlayer), at the
798/// runtime's own defaults until the host changes one.
799#[derive(Clone, Copy, Debug)]
800struct HostTransport {
801    speed_scale: f32,
802    /// The frame-rate override; `0` leaves the authored rate.
803    frame_rate: i32,
804    frame_skip: bool,
805    direction: PlaybackDirection,
806    style: PlaybackStyle,
807}
808
809impl Default for HostTransport {
810    fn default() -> Self {
811        Self { speed_scale: 1.0, frame_rate: 0, frame_skip: true, direction: PlaybackDirection::Forward, style: PlaybackStyle::Normal }
812    }
813}
814
815/// One active runtime texture override: a cellmap redirected to a private
816/// renderer key. The `original` key is what a restore points back at — captured
817/// when the override is first set, and kept current across reloads by
818/// [`SSPlayer::record_atlas_keys`], since the atlas may re-register under a new
819/// base key while the override is live.
820#[derive(Clone, Copy, Debug)]
821struct CellmapOverride {
822    /// The cellmap's `name_hash` — what a draw batch and the runtime speak in.
823    cellmap_hash: u32,
824    /// The private renderer key the override texture is registered under, unique
825    /// to this player and this cellmap.
826    key: u32,
827    /// The base key a restore redirects back to (the shared atlas, untouched).
828    original: u32,
829}
830
831/// Hands each [`SSPlayer`] a distinct [`SSPlayer::id`]. Starts at 1 so 0 stays
832/// free as "no player".
833static NEXT_PLAYER_ID: AtomicU32 = AtomicU32::new(1);
834
835/// The private renderer key a runtime override registers its texture under.
836///
837/// Derived rather than allocated so re-overriding one cellmap reuses the key
838/// (overwriting the texture, not leaking a new entry), and mixed with the
839/// player's id and the pack so two players, or two packs of one player naming a
840/// cellmap alike, stay independent. It is an fnv1a like every other renderer
841/// key, so it shares that keyspace's already-trusted assumption that distinct
842/// inputs do not collide.
843fn override_key(id: u32, pack: &str, cellmap_hash: u32) -> u32 {
844    let mut buf = Vec::with_capacity(pack.len() + 21);
845    buf.extend_from_slice(b"\0ssoverride\0");
846    buf.extend_from_slice(&id.to_le_bytes());
847    buf.extend_from_slice(&cellmap_hash.to_le_bytes());
848    buf.extend_from_slice(pack.as_bytes());
849    fnv1a_bytes(&buf)
850}
851
852/// The renderer key a reference-mode atlas takes before any loader has keyed it.
853fn reference_key(pack: &str, path: &str) -> u32 {
854    let mut buf = Vec::with_capacity(pack.len() + path.len() + 8);
855    buf.extend_from_slice(b"\0ssref\0");
856    buf.extend_from_slice(pack.as_bytes());
857    buf.push(0);
858    buf.extend_from_slice(path.as_bytes());
859    fnv1a_bytes(&buf)
860}
861
862/// A crowd member as it is drawn: alpha clamped, tint masked to `0xRRGGBB`.
863fn clamp_member(member: CrowdMember) -> CrowdMember {
864    CrowdMember { alpha: member.alpha.clamp(0.0, 1.0), tint: member.tint & WHITE_TINT, ..member }
865}
866
867impl Default for SSPlayer {
868    fn default() -> Self {
869        Self::new()
870    }
871}
872
873impl SSPlayer {
874    /// Create a player. Takes nothing: a player holds no GPU resource at all, which is what makes putting a hundred of them in a scene
875    /// cheap. The device-scoped [`SSRenderer`] and the target-scoped
876    /// [`SSScene`](crate::SSScene) are lent to it per frame by
877    /// [`SSScene::update`](crate::SSScene::update).
878    pub fn new() -> Self {
879        Self {
880            packs: HashMap::new(),
881            retired: Vec::new(),
882            main_pack: None,
883            root: None,
884            current_animation: None,
885            packs_awaiting_textures: Vec::new(),
886            pending_images: Vec::new(),
887            atlas_keys: HashMap::new(),
888            missing: Vec::new(),
889            loaded_packs: Vec::new(),
890            events: Vec::new(),
891            looped: false,
892            ran: false,
893            finished_edge: false,
894            prev_finished: false,
895            started_edge: false,
896            start_pending: false,
897            transform: IDENTITY,
898            order: 0,
899            visible: true,
900            culled: false,
901            alpha: 1.0,
902            crowd: Vec::new(),
903            tint: WHITE_TINT,
904            loop_count: None,
905            transport: HostTransport::default(),
906            // On: this player draws for applications and for hosts with a display
907            // refresh to keep up with, where interpolating between authored frames
908            // is the point.
909            sub_frame: true,
910            id: NEXT_PLAYER_ID.fetch_add(1, Ordering::Relaxed),
911            overrides: HashMap::new(),
912            pending_overrides: Vec::new(),
913            pending_forgets: Vec::new(),
914            walk: Walk::default(),
915            rebuild: true,
916        }
917    }
918
919    /// Re-offer this player's embedded atlases after a device loss.
920    ///
921    /// The player itself has nothing to rebuild — it owns no GPU resource. What it
922    /// does own is the `.ssab`, which is the only place a [`Retention::Reproducible`]
923    /// texture can come back from, so the host calls this once per player after
924    /// [`SSRenderer::restore_device`] and
925    /// [`SSScene::restore_device`](crate::SSScene::restore_device).
926    ///
927    /// Playback state (packs, the instance tree, the current frame) is CPU-side and
928    /// was never affected: the animation resumes where it was interrupted.
929    pub fn restore_textures(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue) {
930        self.packs_awaiting_textures = self.packs.values().filter(|p| p.has_embedded_textures()).map(|p| p.name().to_string()).collect();
931        self.flush_textures(renderer, device, queue);
932    }
933
934    /// Load a `.ssab` **and everything it depends on**, then select it.
935    ///
936    /// One call is the whole of loading: the pack, both of its texture tables in
937    /// either export mode, and — transitively — the sibling packs its instance
938    /// parts play from, with their textures. Nothing is left for the caller to
939    /// discover and fetch by hand, which is the point: a host that has to walk
940    /// `textures()` itself will sooner or later miss `external_textures()` and
941    /// ship white silhouettes.
942    ///
943    /// `src` is where the pack is, in whatever terms `loader` understands — a
944    /// path for [`SSPlayer::load`], a URL for the web face. Everything the
945    /// pack names is resolved against its **directory**, because that is what the
946    /// exporter wrote the paths relative to; the walk never joins those paths
947    /// itself, it hands `src` to [`AssetLoader::set_base`] once and asks for bare
948    /// names after that.
949    ///
950    /// A pack keeps the name inside the `.ssab`. That is the name instance
951    /// references are matched against (`ref_anime_pack`), and the same string is
952    /// the sibling file's stem, which is what makes those siblings findable at
953    /// all. Use
954    /// [`SSPlayer::load_ssab`] to name a pack yourself, and expect external
955    /// references to it to stop resolving.
956    ///
957    /// Only the pack itself is worth an error: everything else is reported
958    /// through [`AssetLoader::warn`] and skipped, so one unreadable atlas does
959    /// not cost you the character.
960    ///
961    /// [`SSPlayer::load`] is this call with the filesystem plugged in; reach for
962    /// this one when the bytes live somewhere a `File::open` cannot reach — a
963    /// `.pck`, an APK, an engine's asset server, a URL.
964    ///
965    /// [`SSPlayer::load`]: crate::SSPlayer::load
966    pub async fn load_with(&mut self, loader: &mut impl AssetLoader, src: &str) -> Result<(), SSRuntimeError> {
967        // This load's tally, not the player's history: a caller checks it against
968        // the call it just made.
969        self.missing.clear();
970        // Back to where the caller rooted it, discarding any base a previous load
971        // left behind — that is what makes `src` below mean the same thing on the
972        // second call as on the first.
973        loader.reset_base();
974        let Some(bytes) = loader.read(std::slice::from_ref(&src.to_owned())).await.into_iter().next().flatten() else {
975            loader.warn(&format!("could not read {src}"));
976            return Err(SSRuntimeError::NotLoaded);
977        };
978        let pack = SSPack::load(&bytes)?;
979        let name = pack.name().to_string();
980        self.set_pack(&pack);
981        self.loaded_packs.push(name.clone());
982        // Read first, re-root second. Everything from here is named relative to
983        // wherever `src` turned out to be, and working that out belongs to the
984        // loader — it is the only party that knows which vocabulary it is in.
985        loader.set_base(src);
986        self.load_assets(loader, &name).await;
987        Ok(())
988    }
989
990    /// Load a `.ssab` off the filesystem **and everything it depends on**, then
991    /// select it.
992    ///
993    /// The whole of loading, in one call and with no wgpu state in sight:
994    ///
995    /// ```no_run
996    /// # use ssplayer_wgpu::SSPlayer;
997    /// # fn go() -> Result<(), Box<dyn std::error::Error>> {
998    /// let mut player = SSPlayer::new();
999    /// player.load("assets/overall/Instance.ssab")?;
1000    /// player.set_animation("anime_1")?;
1001    /// player.play();
1002    /// # Ok(()) }
1003    /// ```
1004    ///
1005    /// It borrows no `Device` or `Queue` because the borrow model lends none
1006    /// until the frame starts: what it reads is decoded and uploaded by the first
1007    /// `SSScene::update`, on exactly the timeline an embedded atlas already
1008    /// takes. So nothing is on the GPU when this returns, and nothing needs to be.
1009    ///
1010    /// `path` is resolved by the process's working directory; everything the pack
1011    /// names — its atlases, the sibling packs its instance parts play from — is
1012    /// resolved against **the `.ssab`'s own directory**, because that is what the
1013    /// exporter wrote those paths relative to. That directory is `Path::parent`'s
1014    /// answer, so the platform decides it rather than us.
1015    ///
1016    /// Use [`SSPlayer::load_with`] where a `File::open` cannot reach the bytes: a
1017    /// Godot `.pck`, an APK, an engine's asset server, a browser.
1018    #[cfg(all(feature = "embedded", not(target_arch = "wasm32")))]
1019    pub fn load(&mut self, path: impl AsRef<std::path::Path>) -> Result<(), SSRuntimeError> {
1020        let path = path.as_ref();
1021        // Rooted nowhere: `path` is read as given, and the walk then re-roots the
1022        // loader at its directory through `set_base`.
1023        let mut loader = crate::assets::FsLoader::new();
1024        let out = crate::assets::block_on(self.load_with(&mut loader, &path.to_string_lossy()));
1025        // Queued rather than uploaded: see the note on `pending_images`.
1026        self.pending_images.append(&mut loader.images);
1027        out
1028    }
1029
1030    /// The half of [`SSPlayer::load`] that runs on an **already registered**
1031    /// pack: its atlases, and the packs it plays from, transitively.
1032    ///
1033    /// For a host that got the bytes some other way — a drop, a bundler, an
1034    /// archive — and registered them with [`SSPlayer::load_ssab`].
1035    ///
1036    /// **`loader` must already be rooted where the pack's relative paths resolve**,
1037    /// because this entry point has no `src` to hand [`AssetLoader::set_base`]:
1038    /// the bytes came from somewhere it never saw. Everything asked for here is a
1039    /// bare name — an atlas path as the exporter wrote it, or `<pack>.ssab`.
1040    pub async fn load_assets(&mut self, loader: &mut impl AssetLoader, pack_name: &str) {
1041        let Some(pack) = self.packs.get(pack_name).cloned() else {
1042            loader.warn(&format!("no pack named \"{pack_name}\" is registered"));
1043            return;
1044        };
1045        self.load_textures(loader, &pack).await;
1046
1047        // Breadth first, one round trip per level: `read` takes the whole level
1048        // at once so an implementation that can overlap the waiting does. A pack
1049        // already registered is not fetched again, which is also what stops two
1050        // packs referencing each other from looping.
1051        let mut queue = pack.instance_packs();
1052        while !queue.is_empty() {
1053            let mut wanted: Vec<String> = queue.drain(..).filter(|name| !self.has_pack(name)).collect();
1054            wanted.sort();
1055            wanted.dedup();
1056            if wanted.is_empty() {
1057                break;
1058            }
1059
1060            // The provider first, for packs that have a name but no path
1061            // (`read_pack`); whatever it declines is looked for as a sibling file.
1062            let mut provided: Vec<Option<Vec<u8>>> = Vec::with_capacity(wanted.len());
1063            for name in &wanted {
1064                provided.push(loader.read_pack(name).await);
1065            }
1066            // A bare sibling name: the loader is rooted at the pack's own
1067            // directory, which is what the exporter wrote these relative to.
1068            let paths: Vec<String> = wanted.iter().map(|name| format!("{name}.ssab")).collect();
1069            let unprovided: Vec<String> = paths.iter().zip(&provided).filter(|(_, bytes)| bytes.is_none()).map(|(path, _)| path.clone()).collect();
1070            let mut fetched = loader.read(&unprovided).await.into_iter();
1071            let fetched: Vec<Option<Vec<u8>>> = provided.into_iter().map(|bytes| if bytes.is_some() { bytes } else { fetched.next().flatten() }).collect();
1072
1073            for (name, bytes) in wanted.iter().zip(fetched) {
1074                let Some(bytes) = bytes else {
1075                    loader.warn(&format!("instance pack \"{name}\" did not load; parts that play it will not appear"));
1076                    self.missing.push(MissingAsset { kind: MissingKind::Pack, name: name.clone(), slot: 0 });
1077                    continue;
1078                };
1079                // Never renamed: `ref_anime_pack` is matched against the name the
1080                // exporter wrote, so an override here would be a reference that
1081                // resolves to nothing.
1082                match SSPack::load(&bytes) {
1083                    Ok(sub) => {
1084                        self.add_pack(&sub);
1085                        self.loaded_packs.push(sub.name().to_string());
1086                        self.load_textures(loader, &sub).await;
1087                        queue.extend(sub.instance_packs());
1088                    }
1089                    Err(e) => {
1090                        loader.warn(&format!("instance pack \"{name}\" is not a valid .ssab: {e:?}"));
1091                        self.missing.push(MissingAsset { kind: MissingKind::Pack, name: name.clone(), slot: 0 });
1092                    }
1093                }
1094            }
1095        }
1096    }
1097
1098    /// Supply every atlas `pack` asks for that the renderer does not already
1099    /// hold — both texture tables, either export mode.
1100    ///
1101    /// Embedded images come out of the pack; the rest are read through `loader`,
1102    /// **once per file**: `external_textures()` can name an image a cellmap
1103    /// already named, under a different hash, and that must not become two reads.
1104    ///
1105    /// The paths asked for are `TextureRef::path` exactly as the exporter wrote
1106    /// it, resolved by the loader against its base — so the name that reaches
1107    /// [`SSPlayer::missing_assets`] is that same relative path, and the warning
1108    /// names the pack to say which directory it was relative to.
1109    async fn load_textures(&mut self, loader: &mut impl AssetLoader, pack: &SSPack) {
1110        let refs = pack.textures();
1111        if refs.is_empty() {
1112            return;
1113        }
1114        let carried = pack.embedded_images();
1115        let embedded = |hash: u32| carried.iter().find(|i| i.slot == hash).map(|i| i.bytes);
1116
1117        // Before anything is read, because `has_texture` is asked about the key
1118        // and the table has to describe the atlases already held just as much as
1119        // the ones about to arrive.
1120        let keys: Vec<u32> = refs.iter().map(|t| atlas_key(loader, t, embedded(t.slot))).collect();
1121        self.record_atlas_keys(pack.name(), refs.iter().map(|t| t.slot).zip(keys.iter().copied()));
1122
1123        let wanted: Vec<(&TextureRef, u32)> = refs.iter().zip(keys.iter().copied()).filter(|(_, key)| !loader.has_texture(*key)).collect();
1124        if wanted.is_empty() {
1125            return;
1126        }
1127
1128        let mut paths: Vec<String> = wanted.iter().filter(|(t, _)| embedded(t.slot).is_none()).map(|(t, _)| t.path.clone()).collect();
1129        paths.sort();
1130        paths.dedup();
1131        let fetched: HashMap<&String, Option<Vec<u8>>> = paths.iter().zip(loader.read(&paths).await).collect();
1132
1133        for (texture, key) in &wanted {
1134            let bytes = match embedded(texture.slot) {
1135                Some(bytes) => bytes,
1136                None => match fetched.get(&texture.path).and_then(|b| b.as_deref()) {
1137                    Some(bytes) => bytes,
1138                    None => {
1139                        loader.warn(&format!("atlas {} for pack \"{}\" did not load; parts that use it will draw white", texture.path, pack.name()));
1140                        self.missing.push(MissingAsset { kind: MissingKind::Texture, name: texture.path.clone(), slot: texture.slot });
1141                        continue;
1142                    }
1143                },
1144            };
1145            loader.supply_texture(*key, bytes).await;
1146        }
1147    }
1148
1149    /// Fold what a load or a flush learned into the pack's table, leaving the
1150    /// slots it says nothing about alone.
1151    ///
1152    /// A base key an atlas registers under is also the key a *restore* returns to,
1153    /// so a cellmap that is actively overridden takes the newly-learned key as its
1154    /// new `original` — and the override's redirect is re-applied on top, so a
1155    /// reload never quietly cancels a live override.
1156    fn record_atlas_keys(&mut self, pack: &str, entries: impl Iterator<Item = (u32, u32)>) {
1157        let mut entries: Vec<(u32, u32)> = entries.collect();
1158        if let Some(overrides) = self.overrides.get_mut(pack) {
1159            for over in overrides.iter_mut() {
1160                if let Some((_, key)) = entries.iter().find(|(hash, _)| *hash == over.cellmap_hash) {
1161                    over.original = *key;
1162                }
1163            }
1164            // The overrides win: their redirects go on last.
1165            entries.extend(overrides.iter().map(|over| (over.cellmap_hash, over.key)));
1166        }
1167        self.apply_atlas_entries(pack, entries);
1168    }
1169
1170    /// Set exactly these `cellmap_hash -> renderer key` entries on a pack's table
1171    /// and push the result to the live tree. The mechanical core shared by
1172    /// [`SSPlayer::record_atlas_keys`] and the override redirects, which speak the
1173    /// same table but decide its contents differently.
1174    fn apply_atlas_entries(&mut self, pack: &str, entries: Vec<(u32, u32)>) {
1175        // A redirected cellmap draws from another texture on the next frame.
1176        self.rebuild = true;
1177        let mut table = self.atlas_keys.get(pack).map(|keys| (**keys).clone()).unwrap_or_default();
1178        for (cellmap_hash, key) in entries {
1179            table.set(cellmap_hash, key);
1180        }
1181        if table.is_empty() {
1182            return;
1183        }
1184        self.atlas_keys.insert(pack.to_string(), Arc::new(table));
1185        // The tree may predate this. A host is free to register bytes, select an
1186        // animation, and only then hand the walk a loader (`load_assets`), and
1187        // selecting again cannot repair it — `set_animation` returns early for the
1188        // name already selected. So the keys are pushed to the nodes here, where
1189        // they are learned, rather than waited for at a selection that may never
1190        // come.
1191        if let Some(root) = &mut self.root {
1192            refresh_atlas_keys(root, &self.atlas_keys);
1193        }
1194    }
1195
1196    /// What the last load could not get, in the order it gave up.
1197    /// Empty means everything the packs asked for arrived.
1198    ///
1199    /// A load reports `Err` only when the `.ssab` itself is unreadable, because
1200    /// one missing atlas must not cost you the character. This is how a caller
1201    /// tells "complete" from "played anyway": check it right after `load`, and
1202    /// decide for itself whether a silhouette is worth failing over.
1203    ///
1204    /// ```no_run
1205    /// # use ssplayer_wgpu::SSPlayer;
1206    /// # fn go(player: &mut SSPlayer) -> Result<(), Box<dyn std::error::Error>> {
1207    /// player.load("assets/overall/Instance.ssab")?; // the pack was readable …
1208    /// for missing in player.missing_assets() { // … but maybe not all of it
1209    /// eprintln!("{:?} {} is not there", missing.kind, missing.name);
1210    /// }
1211    /// # Ok(()) }
1212    /// ```
1213    ///
1214    /// Reset by every [`SSPlayer::load_with`] and [`SSPlayer::set_pack`]
1215    /// ([`SSPlayer::load_ssab`] included), so it always describes the most recent
1216    /// load rather than the player's history.
1217    pub fn missing_assets(&self) -> &[MissingAsset] {
1218        &self.missing
1219    }
1220
1221    /// Whether a pack is registered under `name` — what an instance part's
1222    /// `ref_anime_pack` will be looked up by.
1223    ///
1224    /// For a host resolving those references itself: it answers "have I already
1225    /// fetched this one", which is what keeps a cycle of packs referencing each
1226    /// other from being walked forever.
1227    pub fn has_pack(&self, name: &str) -> bool {
1228        self.packs.contains_key(name)
1229    }
1230
1231    /// Register a pack for external instance references without
1232    /// changing what is playing. Registration is by [`SSPack::name`].
1233    ///
1234    /// Sharing one pack between players is the intended shape: the
1235    /// clone is an `Arc` bump, and the atlas reaches the GPU once no matter how
1236    /// many players hold it.
1237    ///
1238    /// Re-registering a name a live animation is playing from does **not** change
1239    /// what is playing: the tree keeps the resource it was built from until the
1240    /// next [`SSPlayer::set_animation`], because its `Context`s point at that
1241    /// resource directly (see `retired`).
1242    pub fn add_pack(&mut self, pack: &SSPack) {
1243        let name = pack.name().to_string();
1244        // Registered by the host now, so the next `set_pack` keeps it; a load
1245        // marks its own packs again after registering them.
1246        self.loaded_packs.retain(|loaded| *loaded != name);
1247        if pack.has_embedded_textures() {
1248            self.packs_awaiting_textures.push(name.clone());
1249        }
1250        // Here rather than at the flush, so [`SSPlayer::texture_key`] can answer
1251        // the moment a pack is registered: a host supplying its own pixels
1252        // (Bevy lending a `GpuImage`'s view) asks between this call and the
1253        // first update, and an answer that arrived later would be an answer it
1254        // had already registered under something else.
1255        // A reference-mode atlas no loader has keyed yet is keyed by the pack and
1256        // the path the exporter wrote: two projects' `spritemap1` stay apart, at
1257        // the cost of one upload per sibling pack naming the same file. A load
1258        // walk replaces these with the loader's own keys, and re-registering the
1259        // same bytes keeps the keys a load already gave the name. Different bytes
1260        // under the name are another pack, whose keys start afresh.
1261        let same = self.packs.get(&name).is_some_and(|held| held.resource().data().as_slice() == pack.resource().data().as_slice());
1262        if !same {
1263            self.atlas_keys.remove(&name);
1264        }
1265        let known = self.atlas_keys.get(&name).cloned().unwrap_or_default();
1266        let mut entries: Vec<(u32, u32)> = pack.embedded_images().iter().map(|image| (image.slot, fnv1a_bytes(image.bytes))).collect();
1267        entries.extend(pack.textures().iter().filter(|texture| !texture.embedded && !known.has(texture.slot)).map(|texture| (texture.slot, reference_key(&name, &texture.path))));
1268        self.record_atlas_keys(&name, entries.into_iter());
1269        // Only while a tree exists is there anything pointing into the pack being
1270        // replaced; without one the old pack is free to go here and now.
1271        if let Some(previous) = self.packs.insert(name, pack.clone())
1272            && self.root.is_some()
1273        {
1274            self.retired.push(previous);
1275            // The live tree was built from the pack just replaced, so it is no
1276            // longer what this name means. Forgetting the selection is what lets
1277            // `set_animation` -- a no-op for the name already set up -- still
1278            // rebuild from the replacement.
1279            self.current_animation = None;
1280        }
1281    }
1282
1283    /// Register `pack` and make it the one [`SSPlayer::set_animation`] selects
1284    /// from. Clears the current animation.
1285    pub fn set_pack(&mut self, pack: &SSPack) {
1286        // Nothing points into a retired pack once the tree is gone, nor into
1287        // the packs the last load found for itself.
1288        self.root = None;
1289        self.retired.clear();
1290        for name in std::mem::take(&mut self.loaded_packs) {
1291            self.packs.remove(&name);
1292            self.atlas_keys.remove(&name);
1293        }
1294        // Read for those packs and not yet uploaded: nothing will draw them.
1295        self.pending_images.clear();
1296        self.add_pack(pack);
1297        self.main_pack = Some(pack.name().to_string());
1298        self.rebuild = true;
1299        self.current_animation = None;
1300        self.missing.clear();
1301    }
1302
1303    /// Parse `data` and register it under `pack_name` — [`SSPack::load_named`] +
1304    /// [`SSPlayer::add_pack`] in one call, for hosts holding bytes rather than
1305    /// packs (the C and js faces, and anything naming packs after files).
1306    pub fn add_ssab(&mut self, pack_name: &str, data: &[u8]) -> Result<(), SSRuntimeError> {
1307        let pack = SSPack::load_named(pack_name, data)?;
1308        self.add_pack(&pack);
1309        Ok(())
1310    }
1311
1312    /// [`SSPlayer::add_ssab`] + [`SSPlayer::set_pack`]: register `pack_name` and
1313    /// make it the main pack to play from.
1314    pub fn load_ssab(&mut self, pack_name: &str, data: &[u8]) -> Result<(), SSRuntimeError> {
1315        let pack = SSPack::load_named(pack_name, data)?;
1316        self.set_pack(&pack);
1317        Ok(())
1318    }
1319
1320    /// Select the animation to play, (re)building the instance tree. The tree is
1321    /// left at its start frame and **not** playing — call [`SSPlayer::play`].
1322    ///
1323    /// This is the allocating half of playback (contexts, slots, mask flags), so
1324    /// the start/stop calls below can stay allocation-free. Mirrors the runtime's
1325    /// own `setup_animation` + `play` split.
1326    pub fn set_animation(&mut self, anim_name: &str) -> Result<(), SSRuntimeError> {
1327        // Already set up: a switch with nothing to switch to, so nothing moves.
1328        // `current_animation` is cleared by `set_pack` and by an `add_pack` that
1329        // replaced a pack, so this can never mistake "the name the *previous*
1330        // pack had selected" for a tree that is still current.
1331        if self.current_animation.as_deref() == Some(anim_name) {
1332            return Ok(());
1333        }
1334        let main_pack = self.main_pack.clone().ok_or(SSRuntimeError::NotLoaded)?;
1335        let res_ptr = self.packs.get(&main_pack).ok_or(SSRuntimeError::NotLoaded)?.resource().resource_static_ptr();
1336        if res_ptr.is_null() {
1337            return Err(SSRuntimeError::NotLoaded);
1338        }
1339        // SAFETY: the resource lives in `packs` for the player's lifetime, and
1340        // the pointer just came from the entry still held there.
1341        let static_res: &'static ssruntime::AnimationResource<'static> = unsafe { &*res_ptr };
1342
1343        // Hand the existing root context the new clip whenever it is still bound
1344        // to the pack we are selecting from: the runtime carries the host's
1345        // transport across a setup on one context. A
1346        // context built new — the first animation, or a replaced pack — is
1347        // handed it from `transport` below instead.
1348        //
1349        // Only the per-animation rig is rebuilt: which instance children are
1350        // mounted and which effect slots exist is the animation's business.
1351        let reused = match &mut self.root {
1352            Some(root) if std::ptr::eq(root.res, static_res) => {
1353                root.context.setup_animation(anim_name)?;
1354                let (instances, effects, mask_flags) = build_rig(&root.context, static_res, &self.packs, &self.atlas_keys);
1355                root.instances = instances;
1356                root.effects = effects;
1357                root.mask_flags = mask_flags;
1358                true
1359            }
1360            _ => false,
1361        };
1362        if !reused {
1363            let mut root = build_node(&self.packs, &self.atlas_keys, &main_pack, anim_name)?;
1364            // A new context starts at the runtime's defaults; the host's settings
1365            // are this player's, not the tree's.
1366            let t = self.transport;
1367            root.context.set_speed_scale(t.speed_scale);
1368            root.context.set_frame_rate(t.frame_rate);
1369            root.context.set_skip_frames(t.frame_skip);
1370            root.context.set_playback_direction(t.direction.into(), t.style.into());
1371            // Assigning drops the previous tree, and with it the last raw pointer
1372            // into any pack a re-registration retired.
1373            self.root = Some(root);
1374        }
1375        // Either way nothing points into a retired pack any more: a rebuilt tree
1376        // replaced every context, and a reused one kept only the root's — which,
1377        // by the check above, is bound to a pack that was never retired. Its rig
1378        // was rebuilt from `packs`, which is where a replacement went.
1379        self.retired.clear();
1380        self.track_zero_switched(anim_name);
1381        // The setup leaves the new animation stopped, so a `play` made before it
1382        // started nothing that a tick could report.
1383        self.started_edge = false;
1384        self.start_pending = false;
1385        self.rebuild = true;
1386        Ok(())
1387    }
1388
1389    /// Record that track 0 now plays `anim_name`, by whichever call handed it
1390    /// over: `set_animation`, or a `set_track_animation` or `crossfade` on
1391    /// track 0, which hands it over from the call on. Recording it there and
1392    /// then is what keeps `set_animation` from mistaking the animation a
1393    /// crossfade left behind for the one still selected.
1394    ///
1395    /// A crossfade keeps playing, so unlike `set_animation` this leaves the
1396    /// start edge alone.
1397    fn track_zero_switched(&mut self, anim_name: &str) {
1398        self.current_animation = Some(anim_name.to_string());
1399        // Nothing that happened under the previous animation describes this one.
1400        self.events.clear();
1401        self.looped = false;
1402        self.finished_edge = false;
1403        self.prev_finished = false;
1404        // The one thing the runtime does NOT carry across a switch, deliberately,
1405        // because the switch is what states it.
1406        self.reapply_loop_count();
1407    }
1408
1409    /// Put the host's loop count back after a switch of track 0's animation
1410    /// dropped it. See [`SSPlayer::loop_count`](struct.SSPlayer.html) — it is
1411    /// the one setting a switch resets.
1412    fn reapply_loop_count(&mut self) {
1413        let Some(count) = self.loop_count else { return };
1414        if let Some(root) = &mut self.root {
1415            root.context.set_loop_count(count);
1416        }
1417    }
1418
1419    /// [`SSPlayer::play`] from `start_frame` rather than from the head of the
1420    /// section. The family spells this `play(startFrame)`; Rust has no
1421    /// overloads, so it is a second name here.
1422    ///
1423    /// Not a resume either — it re-arms the loop count exactly as `play` does,
1424    /// and the frame it starts from becomes the reference the loop counts from.
1425    /// A frame outside the section is brought inside it, as [`SSPlayer::seek`]
1426    /// does; a negative one starts from the head, as `play` does.
1427    pub fn play_from(&mut self, start_frame: f32) {
1428        self.prev_finished = false;
1429        self.rebuild = true;
1430        let (first, last) = (self.start_frame() as f32, self.end_frame() as f32);
1431        if let Some(root) = &mut self.root {
1432            reset_slots(root);
1433            // The runtime takes a non-negative frame as given, and one past the
1434            // section draws nothing at all.
1435            let start_frame = if start_frame < 0.0 || start_frame.is_nan() {
1436                -1.0
1437            } else if start_frame >= last + 1.0 {
1438                last
1439            } else {
1440                start_frame.max(first)
1441            };
1442            root.context.play_with_start_frame(start_frame);
1443            self.start_pending = true;
1444        }
1445    }
1446
1447    /// Start the selected animation from the head of its section, re-arming the
1448    /// loop count. **Not a resume**: it rewinds, so lifting a
1449    /// [`SSPlayer::pause`] is [`SSPlayer::resume`]'s job.
1450    /// No-op until [`SSPlayer::set_animation`] has succeeded.
1451    pub fn play(&mut self) {
1452        // Re-arm the completion latch, or replaying an animation that already
1453        // finished compares against the `true` its last run left and the next
1454        // completion is never reported.
1455        self.prev_finished = false;
1456        self.rebuild = true;
1457        if let Some(root) = &mut self.root {
1458            reset_slots(root);
1459            root.context.play();
1460            self.start_pending = true;
1461        }
1462    }
1463
1464    /// Hold playback on the current frame. Idempotent, and ignored while
1465    /// nothing is playing. [`SSPlayer::is_playing`] stays true — a hold is not
1466    /// a stop.
1467    pub fn pause(&mut self) {
1468        if let Some(root) = &mut self.root {
1469            root.context.pause();
1470        }
1471    }
1472
1473    /// Lift a [`SSPlayer::pause`], carrying on from the same frame. Idempotent,
1474    /// and a no-op on a stopped animation — starting one is [`SSPlayer::play`]'s
1475    /// job, and it rewinds.
1476    pub fn resume(&mut self) {
1477        if let Some(root) = &mut self.root {
1478            root.context.resume();
1479        }
1480    }
1481
1482    /// End playback. The playhead stays where it stands; nothing rewinds, so the
1483    /// host keeps drawing the frame it stopped on.
1484    pub fn stop(&mut self) {
1485        // A `play` stopped before any tick ran never started.
1486        self.start_pending = false;
1487        if let Some(root) = &mut self.root {
1488            root.context.stop();
1489        }
1490    }
1491
1492    /// Scale playback by `speed`, a multiple of the frame rate. `0.0` and
1493    /// negatives are a **stop**, not reverse playback -- that is
1494    /// [`SSPlayer::set_playback_direction`] -- and read back from
1495    /// [`SSPlayer::speed_scale`] as the `0.0` they became.
1496    ///
1497    /// Survives [`SSPlayer::set_animation`] and a pack change, and may be set
1498    /// before the first animation.
1499    pub fn set_speed_scale(&mut self, speed: f32) {
1500        self.transport.speed_scale = speed;
1501        if let Some(root) = &mut self.root {
1502            root.context.set_speed_scale(speed);
1503        }
1504    }
1505
1506    /// The speed in effect, as a multiple of the frame rate. Read from the
1507    /// runtime, so a rate that clamped to a stop reads back as `0.0` rather than
1508    /// as the negative that was asked for.
1509    pub fn speed_scale(&self) -> f32 {
1510        // The runtime stores anything not above zero as the stop it is.
1511        self.root.as_ref().map(|r| r.context.get_speed_scale()).unwrap_or(self.transport.speed_scale.max(0.0))
1512    }
1513
1514    /// Whether an animation has been started and has neither stopped nor
1515    /// finished. A [`SSPlayer::pause`] leaves it true; [`SSPlayer::is_pausing`]
1516    /// says whether it is held.
1517    pub fn is_playing(&self) -> bool {
1518        self.root.as_ref().map(|r| r.context.is_playing()).unwrap_or(false)
1519    }
1520
1521    /// Held in place rather than stopped: [`SSPlayer::is_playing`] stays true.
1522    /// False before the first [`SSPlayer::play`] and after [`SSPlayer::stop`] —
1523    /// the runtime keeps "paused" implying "playing".
1524    pub fn is_pausing(&self) -> bool {
1525        self.root.as_ref().map(|r| r.context.is_pausing()).unwrap_or(false)
1526    }
1527
1528    /// Which way the playhead is actually travelling, which is **not** the
1529    /// heading [`SSPlayer::set_playback_direction`] configured: under ping-pong
1530    /// the return leg runs backward while [`SSPlayer::playback_direction`] still
1531    /// reads forward. A negative speed does not flip it either — that is a stop.
1532    ///
1533    /// This is the gate to put in front of audio. SpriteStudio has no reverse
1534    /// audio, so an [`crate::SsEvent::Audio`] crossed on a backward leg is not
1535    /// meant to sound; the sibling players that own an audio stack apply exactly
1536    /// this test before playing one.
1537    ///
1538    /// True with no animation set up: forward is the resting state, and
1539    /// reporting backward would gate a host's audio off on its first frame.
1540    pub fn is_playing_forward(&self) -> bool {
1541        self.root.as_ref().map(|r| r.context.is_playing_forward()).unwrap_or(true)
1542    }
1543
1544    /// Every configured loop has played. Sticky until the next play or switch
1545    /// of track 0's animation ([`SSPlayer::set_animation`], or a crossfade or
1546    /// track animation on track 0), and never true under an infinite loop.
1547    pub fn is_finished(&self) -> bool {
1548        self.root.as_ref().map(|r| r.context.is_finished()).unwrap_or(false)
1549    }
1550
1551    // --- Playhead ----------------------------------------------------------
1552    //
1553    // Everything below reads or writes the ROOT context only. Instance children
1554    // run their own clocks, driven by their slots from the root's frame, so
1555    // seeking the root carries them with it on the next update.
1556
1557    /// Jump to `frame`. Fractional values are honoured — the tree is evaluated
1558    /// at the sub-frame position on the next update.
1559    pub fn seek(&mut self, frame: f32) {
1560        self.rebuild = true;
1561        if let Some(root) = &mut self.root {
1562            root.context.set_frame_no(frame);
1563        }
1564    }
1565
1566    /// Current playhead position, fractional. Zero before an animation is set.
1567    pub fn frame_no(&self) -> f32 {
1568        self.root.as_ref().map(|r| r.context.get_frame_no()).unwrap_or(0.0)
1569    }
1570
1571    /// First and last frame of the range being played, and its length
1572    /// (`end - start + 1`, both ends inclusive). All zero before an animation is
1573    /// set. These follow [`SSPlayer::set_animation_section`], so they describe
1574    /// what the transport actually walks rather than what the pack contains.
1575    pub fn start_frame(&self) -> i32 {
1576        self.root.as_ref().map(|r| r.context.get_start_frame()).unwrap_or(0)
1577    }
1578
1579    /// See [`SSPlayer::start_frame`].
1580    pub fn end_frame(&self) -> i32 {
1581        self.root.as_ref().map(|r| r.context.get_end_frame()).unwrap_or(0)
1582    }
1583
1584    /// See [`SSPlayer::start_frame`].
1585    pub fn total_frames(&self) -> i32 {
1586        match &self.root {
1587            Some(root) => root.context.get_end_frame() - root.context.get_start_frame() + 1,
1588            None => 0,
1589        }
1590    }
1591
1592    // --- Playback shape ----------------------------------------------------
1593    //
1594    // NOTE: everything here holds across `set_animation` and a pack change, and
1595    // may be set before the first animation, as on every other Player. The
1596    // runtime keeps the speed, the frame skip, the frame-rate override and the
1597    // direction across a setup on one context; this Player also builds a new
1598    // context for its first animation and for a replaced pack, so it holds
1599    // those in `transport` and hands them to each root it builds. A crossfade
1600    // or a track animation on track 0 keeps them as well: the runtime holds
1601    // them on the track, not on the animation. The loop count is the exception
1602    // the runtime makes on purpose — the transition is what states a count —
1603    // so it is held too and put back after every switch of track 0's
1604    // animation, exactly as the others do.
1605    //
1606    // What does NOT survive is the playback SECTION: frame numbers mean nothing
1607    // against a different clip.
1608
1609    /// `count` cycles then stop; `-1` (or `0`) loops forever. Under
1610    /// [`PlaybackStyle::PingPong`] one cycle is a full round trip.
1611    pub fn set_loop_count(&mut self, count: i32) {
1612        self.loop_count = Some(count);
1613        if let Some(root) = &mut self.root {
1614            root.context.set_loop_count(count);
1615        }
1616    }
1617
1618    /// The configured count — before an animation is set up, the one
1619    /// [`SSPlayer::set_loop_count`] is holding for it, or 0 when none was set.
1620    pub fn loop_count(&self) -> i32 {
1621        self.root.as_ref().map(|r| r.context.get_loop_count()).or(self.loop_count).unwrap_or(0)
1622    }
1623
1624    /// How many cycles of [`SSPlayer::loop_count`] are left; 0 with no animation.
1625    pub fn remaining_loops(&self) -> i32 {
1626        self.root.as_ref().map(|r| r.context.get_remaining_loops()).unwrap_or(0)
1627    }
1628
1629    /// Override the advance rate. The pack's authored rate otherwise, and `0`
1630    /// or below goes back to it — prefer [`SSPlayer::set_speed_scale`], which
1631    /// scales playback without replacing it.
1632    ///
1633    /// Survives [`SSPlayer::set_animation`] and a pack change, and may be set
1634    /// before the first animation.
1635    pub fn set_frame_rate(&mut self, fps: i32) {
1636        self.transport.frame_rate = fps;
1637        if let Some(root) = &mut self.root {
1638            root.context.set_frame_rate(fps);
1639        }
1640    }
1641
1642    /// See [`SSPlayer::set_frame_rate`]. Before an animation is set, the
1643    /// override, or zero without one.
1644    pub fn frame_rate(&self) -> i32 {
1645        self.root.as_ref().map(|r| r.context.get_frame_rate()).unwrap_or(self.transport.frame_rate.max(0))
1646    }
1647
1648    /// Restrict playback to `start..=end` of the current animation, so looping
1649    /// and ping-pong turn around inside that range. Reflected by
1650    /// [`SSPlayer::start_frame`] / [`SSPlayer::end_frame`].
1651    ///
1652    /// Both ends are included, so `start == end` holds that one frame. An end
1653    /// outside the animation (`-1`, say) stands for the animation's edge on
1654    /// that side. An end before the start, both inside the animation, is
1655    /// refused with [`SSRuntimeError::InvalidParameter`], and the section and
1656    /// the playhead stay as they were.
1657    ///
1658    /// Call it *after* [`SSPlayer::set_animation`]: frame numbers only mean
1659    /// something inside the animation they were measured in, and setting an
1660    /// animation rebuilds the tree and takes the section with it.
1661    pub fn set_animation_section(&mut self, start: i32, end: i32) -> Result<(), SSRuntimeError> {
1662        let root = self.root.as_mut().ok_or(SSRuntimeError::NotLoaded)?;
1663        root.context.set_animation_section(start, end)?;
1664        // The playhead may be clamped into the new range.
1665        self.rebuild = true;
1666        Ok(())
1667    }
1668
1669    // --- Tracks ------------------------------------------------------------
1670    //
1671    // Pass-throughs to the runtime's track stack, on the ROOT context. Tracks
1672    // fold onto the setup pose in ascending order; track 0 is what
1673    // [`SSPlayer::set_animation`] establishes and carries the structure. A
1674    // track's `alpha` is its strength; a source's `weight` only sets
1675    // proportions among several animations sharing one track.
1676    //
1677    // Instance children are not layered: they run their own contexts, driven by
1678    // their slots from the root's frame.
1679
1680    /// The root, for a track, source or part-override call: whatever it changes
1681    /// shows on the next frame, so it marks one rebuild — a stopped or held
1682    /// player would otherwise go on showing the frame it last built.
1683    fn root_posed(&mut self) -> Result<&mut PlaybackNode, SSRuntimeError> {
1684        self.rebuild = true;
1685        self.root.as_mut().ok_or(SSRuntimeError::NotLoaded)
1686    }
1687
1688    /// Put `anim_name` on `track`, replacing what it was playing. Track 0 is
1689    /// better set with [`SSPlayer::set_animation`], which rebuilds the instance
1690    /// tree; this is for the overlay tracks above it. On track 0 it still makes
1691    /// `anim_name` the [`SSPlayer::current_animation`].
1692    pub fn set_track_animation(&mut self, track: u32, anim_name: &str) -> Result<(), SSRuntimeError> {
1693        let root = self.root_posed()?;
1694        root.context.set_track_animation(track, anim_name)?;
1695        if track == 0 {
1696            self.track_zero_switched(anim_name);
1697        }
1698        Ok(())
1699    }
1700
1701    /// How much of `track` survives onto the pose the tracks below it produced.
1702    pub fn set_track_alpha(&mut self, track: u32, alpha: f32) -> Result<(), SSRuntimeError> {
1703        let root = self.root_posed()?;
1704        root.context.set_track_alpha(track, alpha)
1705    }
1706
1707    /// `track`'s alpha, or `None` when no animation is set up or there is no such track.
1708    pub fn track_alpha(&self, track: u32) -> Option<f32> {
1709        self.root.as_ref()?.context.get_track_alpha(track)
1710    }
1711
1712    /// [`TrackBlend::Mix`] lerps toward the track's pose; [`TrackBlend::Additive`]
1713    /// adds its offset from the setup pose, leaving what is below showing through.
1714    pub fn set_track_blend(&mut self, track: u32, blend: TrackBlend) -> Result<(), SSRuntimeError> {
1715        let root = self.root_posed()?;
1716        root.context.set_track_blend(track, blend)
1717    }
1718
1719    /// How `track` composes onto the tracks below it, or `None` when there is no such track.
1720    pub fn track_blend(&self, track: u32) -> Option<TrackBlend> {
1721        self.root.as_ref()?.context.get_track_blend(track)
1722    }
1723
1724    /// Where the animations laid on `track` start: [`TrackSync::Free`] from the
1725    /// head of their section, [`TrackSync::Start`] at the phase track 0 stands
1726    /// at, so a run laid over a walk keeps its stride. Set it before laying;
1727    /// [`SSPlayer::set_animation`] resets every track to `Free`.
1728    pub fn set_track_sync(&mut self, track: u32, sync: TrackSync) -> Result<(), SSRuntimeError> {
1729        let root = self.root_posed()?;
1730        root.context.set_track_sync(track, sync)
1731    }
1732
1733    /// Where the animations laid on `track` start (see [`SSPlayer::set_track_sync`]),
1734    /// or `None` when there is no such track.
1735    pub fn track_sync(&self, track: u32) -> Option<TrackSync> {
1736        self.root.as_ref()?.context.get_track_sync(track)
1737    }
1738
1739    /// How many tracks are laid, track 0 included. Zero when no animation is set up.
1740    pub fn track_count(&self) -> u32 {
1741        self.root.as_ref().map(|r| r.context.get_track_count()).unwrap_or(0)
1742    }
1743
1744    /// Silence a track. Track 0 is refused — fade it to alpha 0 instead.
1745    pub fn clear_track(&mut self, track: u32) -> Result<(), SSRuntimeError> {
1746        let root = self.root_posed()?;
1747        root.context.clear_track(track)
1748    }
1749
1750    /// Fade `track` to `anim_name` over `duration_ms`, starting from whatever it
1751    /// is playing. Advanced by [`SSScene::update`].
1752    ///
1753    /// On track 0, `anim_name` takes over from the call on, not when the fade
1754    /// completes: it is the [`SSPlayer::current_animation`], its state is what
1755    /// [`SSPlayer::is_finished`] and the frame read-outs report, and it plays
1756    /// with the speed, direction and loop count the host set. The instance
1757    /// tree is not rebuilt the way [`SSPlayer::set_animation`] rebuilds it;
1758    /// the instance and effect parts belong to the pack, so the running
1759    /// children carry on under the new animation's keys.
1760    ///
1761    /// [`SSScene::update`]: crate::SSScene::update
1762    pub fn crossfade(&mut self, track: u32, anim_name: &str, duration_ms: f32) -> Result<(), SSRuntimeError> {
1763        let root = self.root_posed()?;
1764        root.context.crossfade(track, anim_name, duration_ms)?;
1765        if track == 0 {
1766            self.track_zero_switched(anim_name);
1767        }
1768        Ok(())
1769    }
1770
1771    /// Drive `track`'s alpha to `target` over `duration_ms`. Fading track 0 to 0
1772    /// settles the pose onto the setup pose.
1773    pub fn fade_track(&mut self, track: u32, target: f32, duration_ms: f32) -> Result<(), SSRuntimeError> {
1774        let root = self.root_posed()?;
1775        root.context.fade_track(track, target, duration_ms)
1776    }
1777
1778    /// Progress of the fade in flight on `track`, from 0 to 1, or `None` when it is
1779    /// not fading.
1780    pub fn track_fade_progress(&self, track: u32) -> Option<f32> {
1781        self.root.as_ref()?.context.get_track_fade_progress(track)
1782    }
1783
1784    /// Cancel `track`'s fade, leaving its alpha and weights where they stand.
1785    pub fn cancel_track_fade(&mut self, track: u32) -> Result<(), SSRuntimeError> {
1786        let root = self.root_posed()?;
1787        root.context.cancel_track_fade(track)
1788    }
1789
1790    /// Seek a track's animation — how a continuous-control axis is driven:
1791    /// author it as an animation and scrub it with the tracked value.
1792    pub fn set_track_frame(&mut self, track: u32, frame: f32) -> Result<(), SSRuntimeError> {
1793        let root = self.root_posed()?;
1794        root.context.set_track_frame(track, frame)
1795    }
1796
1797    /// `track`'s playhead, or `None` when there is no such track.
1798    pub fn track_frame(&self, track: u32) -> Option<f32> {
1799        self.root.as_ref()?.context.get_track_frame(track)
1800    }
1801
1802    /// Set `track`'s speed, as a multiple of each animation's frame rate. Track
1803    /// 0's is [`SSPlayer::set_speed_scale`].
1804    pub fn set_track_speed(&mut self, track: u32, speed: f32) -> Result<(), SSRuntimeError> {
1805        let root = self.root_posed()?;
1806        root.context.set_track_speed(track, speed)
1807    }
1808
1809    // A track's playback settings are the track's, not its animation's: they
1810    // reach every animation on it now, both sides of a crossfade included, and
1811    // every one laid on it later. Track 0's are the transport above
1812    // ([`SSPlayer::set_speed_scale`] and the rest); these address any track.
1813    // The loop count is the exception, as on track 0: it belongs to the
1814    // animation, and laying another one starts it looping forever again.
1815
1816    /// What [`SSPlayer::set_track_speed`] stored; a negative speed reads back
1817    /// as the `0.0` it became.
1818    pub fn track_speed(&self, track: u32) -> Option<f32> {
1819        self.root.as_ref()?.context.get_track_speed(track)
1820    }
1821
1822    /// [`SSPlayer::set_frame_rate`] for one track.
1823    pub fn set_track_frame_rate(&mut self, track: u32, fps: i32) -> Result<(), SSRuntimeError> {
1824        let root = self.root_posed()?;
1825        root.context.set_track_frame_rate(track, fps)
1826    }
1827
1828    /// The rate the track's animation plays at: the override, or the authored
1829    /// rate. `Some(0)` for a track with neither.
1830    pub fn track_frame_rate(&self, track: u32) -> Option<i32> {
1831        self.root.as_ref()?.context.get_track_frame_rate(track)
1832    }
1833
1834    /// [`SSPlayer::set_frame_skip_enabled`] for one track.
1835    pub fn set_track_frame_skip_enabled(&mut self, track: u32, skip: bool) -> Result<(), SSRuntimeError> {
1836        let root = self.root_posed()?;
1837        root.context.set_track_skip_frames(track, skip)
1838    }
1839
1840    /// Whether `track` skips frames to keep time, or `None` when there is no such track.
1841    pub fn track_frame_skip_enabled(&self, track: u32) -> Option<bool> {
1842        self.root.as_ref()?.context.get_track_skip_frames(track)
1843    }
1844
1845    /// [`SSPlayer::set_playback_direction`] for one track.
1846    pub fn set_track_playback_direction(&mut self, track: u32, direction: PlaybackDirection, style: PlaybackStyle) -> Result<(), SSRuntimeError> {
1847        let root = self.root_posed()?;
1848        root.context.set_track_playback_direction(track, direction.into(), style.into())
1849    }
1850
1851    /// Which way `track`'s playhead walks, or `None` when there is no such track.
1852    pub fn track_playback_direction(&self, track: u32) -> Option<PlaybackDirection> {
1853        self.root.as_ref()?.context.get_track_playback_direction(track).map(Into::into)
1854    }
1855
1856    /// How `track` behaves at the end of its section, or `None` when there is no such track.
1857    pub fn track_playback_style(&self, track: u32) -> Option<PlaybackStyle> {
1858        self.root.as_ref()?.context.get_track_playback_style(track).map(Into::into)
1859    }
1860
1861    /// How many times the track's animation plays before it holds its last
1862    /// frame; `-1` (or `0`) loops forever. Set it after laying the animation:
1863    /// an animation is laid looping forever. On track 0 this is
1864    /// [`SSPlayer::set_loop_count`]: the player keeps the count and puts it
1865    /// back on every animation laid there.
1866    pub fn set_track_loop_count(&mut self, track: u32, count: i32) -> Result<(), SSRuntimeError> {
1867        let root = self.root_posed()?;
1868        root.context.set_track_loop_count(track, count)?;
1869        if track == 0 {
1870            // Written past the kept count, the next switch of track 0 would put
1871            // the old one back.
1872            self.loop_count = Some(count);
1873        }
1874        Ok(())
1875    }
1876
1877    /// `-1` for a track that loops forever; `None` for one with no animation.
1878    pub fn track_loop_count(&self, track: u32) -> Option<i32> {
1879        self.root.as_ref()?.context.get_track_loop_count(track)
1880    }
1881
1882    /// The track's animation has played its loop count out and holds its last
1883    /// frame, still mixed in until the host fades or clears the track. A state,
1884    /// as [`SSPlayer::is_finished`] is for track 0; there is no edge for it.
1885    pub fn is_track_finished(&self, track: u32) -> bool {
1886        self.root.as_ref().is_some_and(|r| r.context.is_track_finished(track))
1887    }
1888
1889    /// The last update wrapped the track's animation back to its start, as
1890    /// [`SSPlayer::just_looped`] is for track 0, and like it `false` after a
1891    /// culled update.
1892    pub fn track_just_looped(&self, track: u32) -> bool {
1893        self.ran && self.root.as_ref().is_some_and(|r| r.context.track_just_looped(track))
1894    }
1895
1896    /// How far into a crossfade on `track` the outgoing animation keeps firing
1897    /// events: while its share of the track, `1 - progress`, is at least
1898    /// `threshold`. The default, `+∞`, silences it from the moment the fade
1899    /// begins, when the incoming one starts firing; `0.5` keeps it firing for
1900    /// the first half. Kept by the track, so it holds for every crossfade on it.
1901    /// The update that completes the fade has already released the outgoing
1902    /// animation, so it fires nothing there, even at `0`.
1903    pub fn set_track_outgoing_event_threshold(&mut self, track: u32, threshold: f32) -> Result<(), SSRuntimeError> {
1904        let root = self.root_posed()?;
1905        root.context.set_track_outgoing_event_threshold(track, threshold)
1906    }
1907
1908    /// The threshold the outgoing side of a crossfade on `track` fires its events
1909    /// at, or `None` when there is no such track.
1910    pub fn track_outgoing_event_threshold(&self, track: u32) -> Option<f32> {
1911        self.root.as_ref()?.context.get_track_outgoing_event_threshold(track)
1912    }
1913
1914    // --- Sources: several animations on one track ------------------------------
1915    //
1916    // A track can carry more than one animation, mixed by `weight` — a walk and a
1917    // run on track 0 blended by the character's speed. Each one is a *source*,
1918    // named by the handle these return; handles stay valid until the source is
1919    // released (a crossfade completing, `clear_track`, `set_track_animation` on
1920    // its track, `set_animation`).
1921
1922    /// The source carrying `track`'s animation — the one `set_track_animation`,
1923    /// `crossfade` or `set_animation` put there.
1924    pub fn track_main_source(&self, track: u32) -> Option<u32> {
1925        self.root.as_ref()?.context.get_track_main_source(track)
1926    }
1927
1928    /// Lay `anim_name` on `track` beside what it already carries, at `weight`,
1929    /// and return its handle. On an empty track it becomes the main source.
1930    /// It starts per the track's [`TrackSync`].
1931    pub fn add_track_source(&mut self, track: u32, anim_name: &str, weight: f32) -> Result<u32, SSRuntimeError> {
1932        let root = self.root_posed()?;
1933        root.context.add_track_source(track, anim_name, weight)
1934    }
1935
1936    /// A source's share **within its track**: weights are ratios, so `(0.7, 0.3)`
1937    /// and `(7, 3)` mix alike. The track's strength is [`SSPlayer::set_track_alpha`].
1938    pub fn set_source_weight(&mut self, source: u32, weight: f32) -> Result<(), SSRuntimeError> {
1939        let root = self.root_posed()?;
1940        root.context.set_source_weight(source, weight)
1941    }
1942
1943    /// `source`'s weight within its track, or `None` when there is no such source.
1944    pub fn source_weight(&self, source: u32) -> Option<f32> {
1945        self.root.as_ref()?.context.get_source_weight(source)
1946    }
1947
1948    /// Seek one source. Sources of different lengths drift apart; this is how a
1949    /// host keeps them in step.
1950    pub fn set_source_frame(&mut self, source: u32, frame: f32) -> Result<(), SSRuntimeError> {
1951        let root = self.root_posed()?;
1952        root.context.set_source_frame(source, frame)
1953    }
1954
1955    /// `source`'s playhead, or `None` when there is no such source.
1956    pub fn source_frame(&self, source: u32) -> Option<f32> {
1957        self.root.as_ref()?.context.get_source_frame(source)
1958    }
1959
1960    /// The weight at or above which `source` fires its events. Only track 0's
1961    /// main source fires by default (the default threshold is `+∞`); lower this
1962    /// to the source's weight or below to have it fire too.
1963    pub fn set_source_event_threshold(&mut self, source: u32, threshold: f32) -> Result<(), SSRuntimeError> {
1964        let root = self.root_posed()?;
1965        root.context.set_source_event_threshold(source, threshold)
1966    }
1967
1968    /// The weight `source` must reach for its events to fire, or `None` when there
1969    /// is no such source.
1970    pub fn source_event_threshold(&self, source: u32) -> Option<f32> {
1971        self.root.as_ref()?.context.get_source_event_threshold(source)
1972    }
1973
1974    /// Which way the playhead walks, and what it does at the far end. Taken
1975    /// together because the runtime sets them as a pair — pass the current value
1976    /// for whichever you are not changing.
1977    ///
1978    /// Survives [`SSPlayer::set_animation`] and a pack change, and may be set
1979    /// before the first animation.
1980    pub fn set_playback_direction(&mut self, direction: PlaybackDirection, style: PlaybackStyle) {
1981        self.transport.direction = direction;
1982        self.transport.style = style;
1983        if let Some(root) = &mut self.root {
1984            root.context.set_playback_direction(direction.into(), style.into());
1985        }
1986    }
1987
1988    /// See [`SSPlayer::set_playback_direction`].
1989    pub fn playback_direction(&self) -> PlaybackDirection {
1990        self.root.as_ref().map(|r| r.context.get_playback_direction().into()).unwrap_or(self.transport.direction)
1991    }
1992
1993    /// See [`SSPlayer::set_playback_direction`].
1994    pub fn playback_style(&self) -> PlaybackStyle {
1995        self.root.as_ref().map(|r| r.context.get_playback_style().into()).unwrap_or(self.transport.style)
1996    }
1997
1998    /// Whether the frame handed to the runtime **for display** keeps its
1999    /// fraction. On by default here.
2000    ///
2001    /// The playhead is an `f32` either way — [`SSPlayer::frame_no`] reports it
2002    /// unrounded, and the instance / effect slots are always stepped from the
2003    /// unrounded value, because truncating there would freeze a child whenever a
2004    /// tick is worth less than a frame. Turning this off only floors what is
2005    /// drawn, which is what pins playback to whole authored frames.
2006    ///
2007    /// Distinct from [`SSPlayer::set_frame_skip_enabled`], which is about *time*: skip
2008    /// frames decides whether a long tick catches up or advances one frame; this
2009    /// decides whether what is drawn may sit between two of them.
2010    pub fn set_sub_frame_enabled(&mut self, enabled: bool) {
2011        self.rebuild |= self.sub_frame != enabled;
2012        self.sub_frame = enabled;
2013    }
2014
2015    /// See [`SSPlayer::set_sub_frame_enabled`].
2016    pub fn sub_frame_enabled(&self) -> bool {
2017        self.sub_frame
2018    }
2019
2020    /// How a long tick is spent. On (the default) advances by the elapsed time
2021    /// and drops the frames in between, keeping playback on the wall clock; off
2022    /// advances exactly one frame per update, so nothing is skipped but a
2023    /// stalled host plays in slow motion.
2024    ///
2025    /// Survives [`SSPlayer::set_animation`] and a pack change, and may be set
2026    /// before the first animation.
2027    pub fn set_frame_skip_enabled(&mut self, skip: bool) {
2028        self.transport.frame_skip = skip;
2029        if let Some(root) = &mut self.root {
2030            root.context.set_skip_frames(skip);
2031        }
2032    }
2033
2034    /// See [`SSPlayer::set_frame_skip_enabled`].
2035    pub fn frame_skip_enabled(&self) -> bool {
2036        self.root.as_ref().map(|r| r.context.get_skip_frames()).unwrap_or(self.transport.frame_skip)
2037    }
2038
2039    // --- Per-part overrides -------------------------------------
2040    //
2041    // Say "make this part this colour / this cell / hidden **now**", beating the
2042    // keyframes underneath. The runtime owns the override table and its whole
2043    // lifecycle, so these are one-shot calls: never drive them from a per-frame
2044    // loop, and expect nothing to be re-applied for you.
2045    //
2046    // Two things to know before reaching for them:
2047    //
2048    // * Part indices address the ROOT animation, and are stable within one pack.
2049    // Resolve a name once with [`SSPlayer::find_part_index`] and keep the
2050    // index if you override often.
2051    // * **Overrides do not reach inside an instance part.** Its child animation
2052    // runs as its own context, so an override on the part that
2053    // *hosts* an instance does not touch what the instance draws.
2054    //
2055    // Every call needs an animation: the runtime sizes its override table in
2056    // `set_animation`, which is also what clears everything but
2057    // [`OverridePriority::Permanent`]. Overriding before selecting an animation
2058    // is therefore both rejected and pointless — override after, never before.
2059
2060    /// Resolve a part name to its index in the current animation, or `None` when
2061    /// the name is unknown or no animation is set up.
2062    ///
2063    /// Only worth calling to cache the index across many frames — every override
2064    /// below takes the name directly and resolves it for you.
2065    pub fn find_part_index(&self, name: &str) -> Option<u32> {
2066        let root = self.root.as_ref()?;
2067        match root.context.find_part_index(name) {
2068            index if index >= 0 => Some(index as u32),
2069            _ => None,
2070        }
2071    }
2072
2073    /// `find_part_index` with the failure turned into the error the override
2074    /// methods return, so each of them stays one line.
2075    fn resolve_part(&self, name: &str) -> Result<u32, SSRuntimeError> {
2076        self.find_part_index(name).ok_or(SSRuntimeError::InvalidParameter)
2077    }
2078
2079    /// Force-hide a part, or revert it to the animation.
2080    ///
2081    /// `cascade` propagates a force-hide to the part's descendants. A keyframe
2082    /// `hide` never cascades, so this is the only way to hide a whole sub-tree.
2083    /// Visibility has no priority mode: it always beats the keyframe, and is
2084    /// always cleared when a new animation is set up.
2085    ///
2086    /// Errors with `InvalidParameter` when the name is not in the current
2087    /// animation. Take [`SSPlayer::set_part_visibility_override_by_index`] when
2088    /// you already hold the index.
2089    pub fn set_part_visibility_override(&mut self, part: &str, hide: bool, cascade: bool) -> Result<(), SSRuntimeError> {
2090        let index = self.resolve_part(part)?;
2091        self.set_part_visibility_override_by_index(index, hide, cascade)
2092    }
2093
2094    /// Index form of [`SSPlayer::set_part_visibility_override`].
2095    pub fn set_part_visibility_override_by_index(&mut self, part: u32, hide: bool, cascade: bool) -> Result<(), SSRuntimeError> {
2096        let root = self.root_posed()?;
2097        root.context.set_part_visibility_override(part, u8::from(hide), cascade)
2098    }
2099
2100    /// Revert a part to the animation's own visibility.
2101    pub fn clear_part_visibility_override(&mut self, part: &str) -> Result<(), SSRuntimeError> {
2102        let index = self.resolve_part(part)?;
2103        self.clear_part_visibility_override_by_index(index)
2104    }
2105
2106    /// Index form of [`SSPlayer::clear_part_visibility_override`].
2107    pub fn clear_part_visibility_override_by_index(&mut self, part: u32) -> Result<(), SSRuntimeError> {
2108        let root = self.root_posed()?;
2109        root.context.clear_part_visibility_override(part)
2110    }
2111
2112    /// Override a part's colour with one value across all four corners.
2113    ///
2114    /// `rgba` is packed `0xRRGGBBAA` in the same 8-bit sRGB space as the
2115    /// authored PartColor: the runtime multiplies its alpha with the part's
2116    /// composed alpha itself, so do not pre-multiply or gamma-convert it here.
2117    /// That alpha is also the strength, which is why `BlendOp::Mix` is the plain
2118    /// case and the value to pass when you have no reason to pass another.
2119    ///
2120    /// Normal parts only. Others ignore it silently — `Ok` means the override
2121    /// was recorded, not that anything looks different.
2122    pub fn set_part_color_override(&mut self, part: &str, rgba: u32, blend_op: BlendOp, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2123        let index = self.resolve_part(part)?;
2124        self.set_part_color_override_by_index(index, rgba, blend_op, priority)
2125    }
2126
2127    /// Index form of [`SSPlayer::set_part_color_override`].
2128    pub fn set_part_color_override_by_index(&mut self, part: u32, rgba: u32, blend_op: BlendOp, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2129        let root = self.root_posed()?;
2130        root.context.set_part_color_override(part, blend_op.as_wire(), rgba, priority.as_wire())
2131    }
2132
2133    /// Override a part's colour with four distinct corners, for a gradient.
2134    ///
2135    /// Same contract as [`SSPlayer::set_part_color_override`]. `corners` is in
2136    /// the runtime's order — **left-top, right-top, left-bottom, right-bottom**,
2137    /// each `[r, g, b, a]` — and getting that order wrong flips the gradient
2138    /// silently rather than failing. One argument rather than four, so the pair
2139    /// of colour methods reads the same.
2140    pub fn set_part_color_override_corners(&mut self, part: &str, corners: [[u8; 4]; 4], blend_op: BlendOp, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2141        let index = self.resolve_part(part)?;
2142        self.set_part_color_override_corners_by_index(index, corners, blend_op, priority)
2143    }
2144
2145    /// Index form of [`SSPlayer::set_part_color_override_corners`].
2146    pub fn set_part_color_override_corners_by_index(&mut self, part: u32, corners: [[u8; 4]; 4], blend_op: BlendOp, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2147        let root = self.root_posed()?;
2148        root.context.set_part_color_override_corners(part, blend_op.as_wire(), corners, priority.as_wire())
2149    }
2150
2151    /// Revert a part to the animation's own colour. Clears either kind of colour
2152    /// override — they share one slot per part.
2153    pub fn clear_part_color_override(&mut self, part: &str) -> Result<(), SSRuntimeError> {
2154        let index = self.resolve_part(part)?;
2155        self.clear_part_color_override_by_index(index)
2156    }
2157
2158    /// Index form of [`SSPlayer::clear_part_color_override`].
2159    pub fn clear_part_color_override_by_index(&mut self, part: u32) -> Result<(), SSRuntimeError> {
2160        let root = self.root_posed()?;
2161        root.context.clear_part_color_override(part)
2162    }
2163
2164    /// Make a part draw a different cell.
2165    ///
2166    /// `cellmap_name` is written without the `.ssce` extension. Both names are
2167    /// hashed here, so pass them exactly as they appear in the pack — see
2168    /// [`SSPlayer::cellmap_names`] and [`SSPlayer::cell_names`] for what is
2169    /// available. Normal and Mask parts only; errors when the cell cannot be
2170    /// resolved against the bound `.ssab`.
2171    pub fn set_part_cell_override(&mut self, part: &str, cellmap_name: &str, cell_name: &str, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2172        let index = self.resolve_part(part)?;
2173        self.set_part_cell_override_by_index(index, cellmap_name, cell_name, priority)
2174    }
2175
2176    /// Index form of [`SSPlayer::set_part_cell_override`].
2177    pub fn set_part_cell_override_by_index(&mut self, part: u32, cellmap_name: &str, cell_name: &str, priority: OverridePriority) -> Result<(), SSRuntimeError> {
2178        let root = self.root_posed()?;
2179        let cellmap_hash = ssruntime::fnv1a_hash_str(cellmap_name);
2180        let cell_hash = ssruntime::fnv1a_hash_str(cell_name);
2181        root.context.set_part_cell_override(part, cellmap_hash, cell_hash, priority.as_wire())
2182    }
2183
2184    /// Revert a part to the animation's own cell.
2185    pub fn clear_part_cell_override(&mut self, part: &str) -> Result<(), SSRuntimeError> {
2186        let index = self.resolve_part(part)?;
2187        self.clear_part_cell_override_by_index(index)
2188    }
2189
2190    /// Index form of [`SSPlayer::clear_part_cell_override`].
2191    pub fn clear_part_cell_override_by_index(&mut self, part: u32) -> Result<(), SSRuntimeError> {
2192        let root = self.root_posed()?;
2193        root.context.clear_part_cell_override(part)
2194    }
2195
2196    /// Drop every override on the root animation at once.
2197    pub fn clear_all_part_overrides(&mut self) {
2198        self.rebuild = true;
2199        if let Some(root) = &mut self.root {
2200            root.context.clear_all_part_overrides();
2201        }
2202    }
2203
2204    // --- Events -------------------------------------------------
2205    //
2206    // Polled, not called back. The borrow model has the host lending the player
2207    // its device per frame and driving the clock, so "read what happened after
2208    // update" is the shape that already fits — and it is the only shape that
2209    // survives being wrapped by both `js` and `ffi` without becoming a different
2210    // API on each.
2211    //
2212    // All four read the tick that `SSScene::update` just ran, and are replaced
2213    // by the next one.
2214
2215    /// Whether the last update was the first to run after a [`SSPlayer::play`]
2216    /// or [`SSPlayer::play_from`] — the start edge, true for exactly one update.
2217    ///
2218    /// **Not raised by [`SSPlayer::resume`]**: lifting a pause carries on, it
2219    /// does not start. The tick reports it rather than the call, so a `play` on
2220    /// a [culled](SSPlayer::set_culled) player is reported by the first tick that
2221    /// runs once it is unculled, and a `play` that [`SSPlayer::stop`] or
2222    /// [`SSPlayer::set_animation`] overtook before any tick ran is not reported.
2223    ///
2224    /// After a `play` of your own the call site already knows. This is for a
2225    /// start something else made — a declarative binding that plays whatever
2226    /// animation it is handed, as the Bevy adapter does.
2227    pub fn just_started(&self) -> bool {
2228        self.started_edge
2229    }
2230
2231    /// Whether the last update crossed a loop boundary.
2232    ///
2233    /// One report per update however many cycles were crossed, since a long tick
2234    /// under frame skipping can complete several. Use it for "the walk cycle came
2235    /// round"; use [`SSPlayer::just_finished`] for "the animation is over".
2236    ///
2237    /// [`SSScene::update`]: crate::SSScene::update
2238    pub fn just_looped(&self) -> bool {
2239        self.looped
2240    }
2241
2242    /// Whether the last update **completed** playback: the rising edge of the
2243    /// runtime's sticky finished state, so it reads true for exactly one update.
2244    ///
2245    /// Never true under an infinite loop, and **not raised by
2246    /// [`SSPlayer::stop`]** — it means "every configured cycle has played", not
2247    /// "playback is no longer running". Counting loops, or calling `stop`
2248    /// yourself, is how you end an infinite one.
2249    ///
2250    /// Do not derive completion from `!is_playing` or from reaching the last
2251    /// frame: `stop` clears the one, and reverse and ping-pong playback pass the
2252    /// other without finishing.
2253    pub fn just_finished(&self) -> bool {
2254        self.finished_edge
2255    }
2256
2257    /// Timeline events the last update crossed, in the order the runtime
2258    /// reported the frames carrying them.
2259    ///
2260    /// **Frames skipped over are still represented.** The runtime records every
2261    /// frame it stepped through, so a footstep on a frame that a slow tick
2262    /// jumped past still appears here — which it would not if the host looked
2263    /// only at the frame that was landed on.
2264    ///
2265    /// Empty on a tick that crossed nothing, and on a
2266    /// [culled](SSPlayer::set_culled) player, which does not advance at all. A
2267    /// player that is merely not [`visible`](SSPlayer::set_visible) still advances,
2268    /// so it reports its events as usual.
2269    pub fn events(&self) -> &[SsEvent] {
2270        &self.events
2271    }
2272
2273    // --- Part read-outs ----------------------------------------
2274
2275    /// How many parts the root animation has. Zero before one is set up.
2276    ///
2277    /// Derived from the world-matrix buffer, which carries one 4x4 per part, so
2278    /// it is exactly the bound [`SSPlayer::part_transform`] checks against.
2279    pub fn part_count(&self) -> usize {
2280        let Some(root) = &self.root else { return 0 };
2281        root.context.get_world_matrices_len() / 16
2282    }
2283
2284    /// The part's transform on the current frame, as the 2D affine
2285    /// `[m00, m01, m10, m11, tx, ty]` — the same six numbers, in the same order,
2286    /// that `ssplayer-webgl`'s `getPartTransform` returns. A point maps as
2287    /// `x' = m00·x + m01·y + tx`, `y' = m10·x + m11·y + ty`.
2288    ///
2289    /// The space is **animation-local and Y-down**: this is the part's pose
2290    /// inside its own animation, with neither [`SSPlayer::set_transform`] nor
2291    /// the scene's projection applied. A host pinning something to a part
2292    /// composes those itself, which is also what lets it pin into whatever
2293    /// coordinate system it actually uses.
2294    ///
2295    /// `None` when no animation is set up or `part` is out of range. Copied out,
2296    /// so unlike a [`FrameView`] it is safe to keep.
2297    ///
2298    /// Read it **after** [`SSScene::update`] — it describes the frame the last
2299    /// update produced. The matrix is computed for every part whether or not it
2300    /// is hidden, so a hidden part still reports where it would have been.
2301    ///
2302    /// [`SSScene::update`]: crate::SSScene::update
2303    pub fn part_transform(&self, part: &str) -> Option<[f32; 6]> {
2304        self.part_transform_by_index(self.find_part_index(part)?)
2305    }
2306
2307    /// Index form of [`SSPlayer::part_transform`], for a caller that already
2308    /// resolved the name and reads the pose every frame.
2309    pub fn part_transform_by_index(&self, part: u32) -> Option<[f32; 6]> {
2310        let root = self.root.as_ref()?;
2311        let matrices = unsafe { slice_f32(root.context.get_world_matrices_ptr(), root.context.get_world_matrices_len()) };
2312        let base = (part as usize).checked_mul(16)?;
2313        // Bounds-checked rather than trusted: these read the runtime's buffer
2314        // directly, so an out-of-range part would read past it instead of
2315        // producing the documented None.
2316        let m = matrices.get(base..base + 16)?;
2317        Some([m[0], m[4], m[1], m[5], m[12], m[13]])
2318    }
2319
2320    /// Whether `part` is hidden on the frame the last [`SSScene::update`] built,
2321    /// or `None` when no animation is set up or it has no such part.
2322    ///
2323    /// The companion to [`SSPlayer::part_transform`], which reports where a part
2324    /// *would* be whether or not it is drawn, on the same frame. A host following
2325    /// a part with its own scene graph needs both: the pose to place its
2326    /// follower, and this to decide whether to show it.
2327    ///
2328    /// It reads that frame and builds none, so a read is a lookup however often
2329    /// it is made, and never changes what the next update builds. An override
2330    /// therefore shows from the next update; a read before then reports the
2331    /// frame before it. A player that is not [`visible`](SSPlayer::set_visible)
2332    /// still builds its frame every update, so this keeps following the
2333    /// animation; a [culled](SSPlayer::set_culled) one, like a tick whose frame
2334    /// could not be built, leaves the last frame in place, as
2335    /// [`SSPlayer::part_transform`] does. `Some(false)` until the first update
2336    /// has built a frame.
2337    ///
2338    /// [`SSScene::update`]: crate::SSScene::update
2339    pub fn is_part_hidden(&self, part: &str) -> Option<bool> {
2340        self.is_part_hidden_by_index(self.find_part_index(part)?)
2341    }
2342
2343    /// Index form of [`SSPlayer::is_part_hidden`], for a caller that already
2344    /// resolved the name.
2345    pub fn is_part_hidden_by_index(&self, part: u32) -> Option<bool> {
2346        if part as usize >= self.part_count() {
2347            return None;
2348        }
2349        let context = &self.root.as_ref()?.context;
2350        let ptr = context.get_frame_data_ptr();
2351        if ptr.is_null() {
2352            return Some(false);
2353        }
2354        // SAFETY: the frame the root context built last. Only the next
2355        // `get_frame_data` replaces it, and that takes the context mutably.
2356        let frame_data = unsafe { root_as_frame_data_unchecked(std::slice::from_raw_parts(ptr, context.get_frame_data_len())) };
2357        let parts = frame_data.parts();
2358        Some((part as usize) < parts.len() && parts.get(part as usize).hide())
2359    }
2360
2361    /// Whether `part` is a **skinned** mesh — a mesh part whose vertices are
2362    /// drawn by bone skinning — or `None` when the pack has no such part.
2363    ///
2364    /// **Why a host wants it.** [`SSPlayer::part_transform`] reports a part's own
2365    /// node transform, which for a skinned mesh stays at its setup position
2366    /// (usually near the character root) while the visible vertices are pulled
2367    /// around by their bones. So pinning a follower to a skinned mesh snaps it to
2368    /// the root rather than onto the art. A host offering a "follow this part"
2369    /// picker can use this to warn, or to steer the choice to a null / bone part,
2370    /// which *does* carry its transform. It does not change what plays — the
2371    /// transform is faithful to the node, this only names when that is not what a
2372    /// follower wants.
2373    ///
2374    /// A **rigid** (deform-only) mesh is not skinned and follows correctly, so it
2375    /// reports `false`, as does every non-mesh part. The test is one bone binding
2376    /// or more, matching the sibling Players' `is_part_skinned_mesh`.
2377    ///
2378    /// Unlike [`SSPlayer::is_part_hidden`], this is a static property of the pack,
2379    /// not a per-frame state, so it reads the `.ssab` directly.
2380    pub fn is_part_skinned_mesh(&self, part: &str) -> Option<bool> {
2381        self.is_part_skinned_mesh_by_index(self.find_part_index(part)?)
2382    }
2383
2384    /// Index form of [`SSPlayer::is_part_skinned_mesh`], for a caller that already
2385    /// resolved the name.
2386    pub fn is_part_skinned_mesh_by_index(&self, part: u32) -> Option<bool> {
2387        let pack = self.packs.get(self.main_pack.as_ref()?)?;
2388        let bytes = pack.resource().data();
2389        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2390        // loaded them (`SSPack::build`).
2391        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2392        let parts = ab.parts();
2393        if part as usize >= parts.len() {
2394            return None;
2395        }
2396        // Skinned == bound to at least one bone. A rigid (deform-only) mesh has a
2397        // binding with no influence bones, and a non-mesh part has none at all;
2398        // both are followable, so both report false.
2399        let skinned = parts.get(part as usize).mesh_binding().and_then(|b| b.influence_bone()).is_some_and(|bones| !bones.is_empty());
2400        Some(skinned)
2401    }
2402
2403    /// Place this player: translation, scale, then rotation in radians, composed
2404    /// into the root transform of its tree.
2405    ///
2406    /// `y` is measured **downward** from the centre, matching the Y-down space
2407    /// the players and their [`SSPlayer::part_transform`] output live in (and
2408    /// ForWeb's `offsetY`).
2409    ///
2410    /// The per-player half of placement: the projection belongs to the render
2411    /// target ([`SSScene::set_viewport`](crate::SSScene::set_viewport)), the
2412    /// placement to the player.
2413    /// It costs nothing extra to draw: the tree walk already composes an
2414    /// arbitrary parent matrix for every instance child, so a non-identity root
2415    /// simply rides along.
2416    pub fn set_transform(&mut self, x: f32, y: f32, scale_x: f32, scale_y: f32, rotation: f32) {
2417        self.place(placement(x, y, scale_x, scale_y, rotation));
2418    }
2419
2420    /// Reset the placement to the identity: centred, unscaled, unrotated.
2421    pub fn reset_transform(&mut self) {
2422        self.place(IDENTITY);
2423    }
2424
2425    /// Take a new root transform. The placement setters compare before they mark
2426    /// a rebuild, because an engine adapter writes them every frame whether they
2427    /// changed or not, and a mark per write would keep the player from settling.
2428    fn place(&mut self, transform: [f32; 16]) {
2429        self.rebuild |= self.transform != transform;
2430        self.transform = transform;
2431    }
2432
2433    /// Draw order within a scene; lower draws first. Ties keep whatever order the
2434    /// host hands the players over in.
2435    pub fn set_order(&mut self, order: i32) {
2436        self.order = order;
2437    }
2438
2439    /// This player's draw order (see [`SSPlayer::set_order`]).
2440    pub fn order(&self) -> i32 {
2441        self.order
2442    }
2443
2444    /// Draw nothing when false, **while the timeline keeps running**: the
2445    /// playhead advances, events, loops and completions are reported, and the
2446    /// part read-outs ([`SSPlayer::part_transform`], [`SSPlayer::is_part_hidden`])
2447    /// follow the animation. Only the geometry is skipped.
2448    ///
2449    /// This is what `visible` means on the other Players, so hiding a character
2450    /// for a moment — a blink, a flicker — does not slow its animation down.
2451    /// To stop paying for a character that cannot be seen at all, use
2452    /// [`SSPlayer::set_culled`] instead.
2453    pub fn set_visible(&mut self, visible: bool) {
2454        self.rebuild |= self.visible != visible;
2455        self.visible = visible;
2456    }
2457
2458    /// Whether this player draws (see [`SSPlayer::set_visible`]).
2459    pub fn is_visible(&self) -> bool {
2460        self.visible
2461    }
2462
2463    /// Skip this player entirely when true: `SSScene::update` advances no
2464    /// timeline and produces no geometry, so `SSScene::draw` records nothing and
2465    /// the player costs nothing. The time spent culled is dropped, not caught up:
2466    /// uncull it and it carries on from where it stopped.
2467    ///
2468    /// For a host that knows the player cannot be seen — outside the viewport, or
2469    /// scrolled away. Because the timeline stops, it is the wrong tool for an
2470    /// effect: a character blinked with it plays in slow motion. Use
2471    /// [`SSPlayer::set_visible`] for that, or [`SSPlayer::set_alpha`] for a fade.
2472    pub fn set_culled(&mut self, culled: bool) {
2473        self.rebuild |= self.culled != culled;
2474        self.culled = culled;
2475    }
2476
2477    /// Whether this player is skipped entirely (see [`SSPlayer::set_culled`]).
2478    pub fn is_culled(&self) -> bool {
2479        self.culled
2480    }
2481
2482    /// Whether `SSScene::update` builds geometry for this player.
2483    pub(crate) fn draws(&self) -> bool {
2484        self.visible && !self.culled
2485    }
2486
2487    /// Player-level fade, clamped to 0..=1 and multiplied into every part's
2488    /// colour alpha. Mask coverage is deliberately unaffected: a faded player
2489    /// clips exactly as it would at full opacity.
2490    ///
2491    /// Part by part, so where two parts overlap the player is more opaque than
2492    /// `alpha`; a scene with [`SSScene::set_group_alpha`](crate::SSScene::set_group_alpha)
2493    /// on fades the player as one layer instead.
2494    pub fn set_alpha(&mut self, alpha: f32) {
2495        let alpha = alpha.clamp(0.0, 1.0);
2496        self.rebuild |= self.alpha != alpha;
2497        self.alpha = alpha;
2498    }
2499
2500    /// The player-level fade, clamped to 0..=1 (see [`SSPlayer::set_alpha`]).
2501    pub fn alpha(&self) -> f32 {
2502        self.alpha
2503    }
2504
2505    /// Player-level tint: `0xRRGGBB`, multiplied into every part the player
2506    /// draws — its instance children included, since the whole tree is one
2507    /// player. White (`0xFFFFFF`, the default) leaves colours untouched.
2508    ///
2509    /// It lands *after* the PartsColor blend, which is what makes it a tint on
2510    /// the finished part rather than another term in that formula. Mask coverage
2511    /// is unaffected, exactly as with [`SSPlayer::set_alpha`]: a tinted player
2512    /// clips the shape it always did.
2513    pub fn set_tint(&mut self, rgb: u32) {
2514        let tint = rgb & 0x00FF_FFFF;
2515        self.rebuild |= self.tint != tint;
2516        self.tint = tint;
2517    }
2518
2519    /// The player-level tint as `0xRRGGBB` (see [`SSPlayer::set_tint`]).
2520    pub fn tint(&self) -> u32 {
2521        self.tint
2522    }
2523
2524    /// Draw this one playhead at every member's placement: a crowd of copies
2525    /// that cost one player's evaluation, one upload of its geometry and one
2526    /// player's draw calls, however many there are. Empty — the default — draws
2527    /// the player once, where [`SSPlayer::set_transform`] put it. Members past
2528    /// [`MAX_CROWD_MEMBERS`] are left out.
2529    ///
2530    /// The members are copied, into a vector this player keeps, so a host that
2531    /// moves its crowd every frame allocates nothing. Everything but placement,
2532    /// alpha and tint is shared: the frame, the animation and its tracks, the
2533    /// overrides, the events (reported once), the masks and the effects —
2534    /// every member's particles are the same ones. `set_order`, `set_visible`,
2535    /// `set_culled` and the player's own alpha and tint apply to the crowd as a
2536    /// whole; to hide one member, leave it out.
2537    ///
2538    /// Each draw is issued once for every member, so members interleave draw by
2539    /// draw: where two overlap, a later part of the first can cover an earlier
2540    /// part of the second. Under [`MaskBackend::Coverage`](crate::MaskBackend::Coverage)
2541    /// each member is clipped by its own mask. Under the stencil backend the
2542    /// members' masks are written together, so they clip correctly only where
2543    /// members do not overlap.
2544    ///
2545    /// [`SSPlayer::part_transform`] stays in the player's space, without the
2546    /// player's placement or any member's: compose a member's onto it to follow
2547    /// that member.
2548    pub fn set_crowd(&mut self, members: &[CrowdMember]) {
2549        // Compared before it is copied, for the reason `place` compares: an
2550        // engine adapter hands over the same crowd every frame.
2551        let kept = &members[..members.len().min(MAX_CROWD_MEMBERS)];
2552        if kept.len() == self.crowd.len() && kept.iter().map(|member| clamp_member(*member)).eq(self.crowd.iter().copied()) {
2553            return;
2554        }
2555        self.set_crowd_from(members.iter().copied());
2556    }
2557
2558    /// [`SSPlayer::set_crowd`] for a face whose members arrive in another form,
2559    /// converted on the way in rather than collected first.
2560    pub(crate) fn set_crowd_from(&mut self, members: impl IntoIterator<Item = CrowdMember>) {
2561        self.rebuild = true;
2562        self.crowd.clear();
2563        self.crowd.extend(members.into_iter().take(MAX_CROWD_MEMBERS).map(clamp_member));
2564    }
2565
2566    /// The crowd [`SSPlayer::set_crowd`] set, as it is drawn: alpha clamped,
2567    /// tint masked to `0xRRGGBB`. Empty when the player draws once.
2568    pub fn crowd(&self) -> &[CrowdMember] {
2569        &self.crowd
2570    }
2571
2572    /// The animation currently set up, or `None` before the first
2573    /// [`SSPlayer::set_animation`] — and again after a pack registration
2574    /// replaced what the tree was built from, which is what makes the next
2575    /// `set_animation` rebuild rather than recognise the name as already set up.
2576    pub fn current_animation(&self) -> Option<&str> {
2577        self.current_animation.as_deref()
2578    }
2579
2580    /// Names of all animations in the main pack, if loaded.
2581    pub fn animation_names(&self) -> Option<Vec<String>> {
2582        let anim_resource = self.packs.get(self.main_pack.as_ref()?)?.resource().resource()?;
2583        Some(anim_resource.get_animation_names())
2584    }
2585
2586    /// Every part name in the main pack, in part-index order.
2587    ///
2588    /// `None` until a pack is bound. This is what turns the `part_index` an
2589    /// [`SsEvent`](crate::SsEvent) carries back into something a human reads, and
2590    /// what fills a part picker; `len()` is the part count.
2591    ///
2592    /// Reads the `.ssab` parts table, which is static for the resource, rather
2593    /// than [`SSPlayer::part_count`] — that one is derived from the world-matrix
2594    /// buffer and is zero until an animation has been set up.
2595    ///
2596    /// A part authored without a name holds its slot as an empty string, so the
2597    /// vector stays index-aligned with `part_index`.
2598    pub fn part_names(&self) -> Option<Vec<String>> {
2599        let pack = self.packs.get(self.main_pack.as_ref()?)?;
2600        let bytes = pack.resource().data();
2601        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2602        // loaded them (`SSPack::build`).
2603        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2604        let parts = ab.parts();
2605        Some((0..parts.len()).map(|i| parts.get(i).name().to_string()).collect())
2606    }
2607
2608    /// Every cellmap name in the main pack, without the `.ssce` extension — the
2609    /// namespace [`SSPlayer::set_part_cell_override`] takes.
2610    ///
2611    /// `None` until a pack is bound. Reads the `.ssab` directly rather than the
2612    /// texture list, because a cellmap whose atlas is embedded still has a name.
2613    pub fn cellmap_names(&self) -> Option<Vec<String>> {
2614        let pack = self.packs.get(self.main_pack.as_ref()?)?;
2615        let bytes = pack.resource().data();
2616        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2617        // loaded them (`SSPack::build`).
2618        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2619        Some(ab.cellmaps()?.iter().map(|c| c.name().to_string()).collect())
2620    }
2621
2622    /// The cell names inside one cellmap, or `None` when no pack is bound or the
2623    /// cellmap is not in it. The other half of what
2624    /// [`SSPlayer::set_part_cell_override`] takes.
2625    pub fn cell_names(&self, cellmap_name: &str) -> Option<Vec<String>> {
2626        let pack = self.packs.get(self.main_pack.as_ref()?)?;
2627        let bytes = pack.resource().data();
2628        // SAFETY: as above.
2629        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2630        let cellmap = ab.cellmaps()?.iter().find(|c| c.name() == cellmap_name)?;
2631        Some(cellmap.cells()?.iter().map(|c| c.name().to_string()).collect())
2632    }
2633
2634    /// Where a pack's cellmap registers in the renderer's texture map.
2635    ///
2636    /// [`TextureRef::slot`] names a *slot inside one `.ssab`*, and two packs from
2637    /// two projects one tool exported can both call theirs `spritemap1`. The renderer's
2638    /// map is device-scoped — that is what keeps N players of one pack to one
2639    /// upload — so the player assigns each atlas a key that identifies the image
2640    /// and translates every draw batch through it. This is that translation, and
2641    /// it is what a host supplying its own pixels has to register under:
2642    ///
2643    /// ```no_run
2644    /// # use ssplayer_wgpu::{Retention, SSPlayer, SSRenderer};
2645    /// # fn go(player: &SSPlayer, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue, rgba: &[u8]) {
2646    /// for texture in player.textures(None).unwrap_or(&[]) {
2647    ///     let key = player.texture_key(None, texture.slot);
2648    ///     renderer.upload_texture(device, queue, key, rgba, (1024, 1024), Retention::Retain);
2649    /// }
2650    /// # }
2651    /// ```
2652    ///
2653    /// A reference-mode atlas of a pack registered without a load
2654    /// ([`SSPlayer::add_ssab`], [`SSPlayer::add_pack`]) is keyed by the pack's name
2655    /// and the path the exporter wrote, so two projects naming their atlas alike
2656    /// never share a key; sibling packs naming one file each upload it. Answers
2657    /// `slot` itself for a pack this player does not hold.
2658    pub fn texture_key(&self, pack_name: Option<&str>, slot: u32) -> u32 {
2659        let Some(name) = pack_name.or(self.main_pack.as_deref()) else { return slot };
2660        self.atlas_keys.get(name).map(|keys| keys.resolve(slot)).unwrap_or(slot)
2661    }
2662
2663    /// The atlases a registered pack asks for, or `None` if
2664    /// `pack_name` names no pack this player holds. `None` selects the main pack.
2665    ///
2666    /// This is the reference-mode half of texture supply, and it exists because
2667    /// only the `.ssab` knows where its atlases were exported to: a host calls it
2668    /// straight after [`SSPlayer::add_ssab`] / [`SSPlayer::load_ssab`], loads
2669    /// every entry that is not [`TextureRef::embedded`] by resolving
2670    /// [`TextureRef::path`] against the directory the `.ssab` came from, and hands
2671    /// the pixels to [`SSRenderer::upload_texture`] **under
2672    /// [`SSPlayer::texture_key`]'s answer for that entry**, not under
2673    /// [`TextureRef::slot`]. The player never opens a file itself — it has no
2674    /// filesystem on the web face, and on any face the host's asset system is the
2675    /// one that should own the bytes.
2676    pub fn textures(&self, pack_name: Option<&str>) -> Option<&[TextureRef]> {
2677        let name = pack_name.or(self.main_pack.as_deref())?;
2678        Some(self.packs.get(name)?.textures())
2679    }
2680
2681    /// The encoded atlases a registered pack carries, or `None` if
2682    /// `pack_name` names no pack this player holds. `None` selects the main pack.
2683    ///
2684    /// The embedded-mode counterpart of [`SSPlayer::textures`]: there is nothing
2685    /// for the host to fetch, but there is something for it to decode. A host
2686    /// with its own decoder walks this and registers the results, rather than
2687    /// leaving it to the decode the next [`SSScene::update`](crate::SSScene::update)
2688    /// runs — which needs the `embedded` feature and only knows how to decode PNG.
2689    pub fn embedded_images(&self, pack_name: Option<&str>) -> Option<Vec<EmbeddedImage<'_>>> {
2690        let name = pack_name.or(self.main_pack.as_deref())?;
2691        Some(self.packs.get(name)?.embedded_images())
2692    }
2693
2694    // --- Runtime texture replacement ---------------------------
2695    //
2696    // Swapping the texture a cellmap binds *from your program* — costume changes,
2697    // dynamic expressions — rather than from the authoring data.
2698    //
2699    // This player's texture map is the device-scoped [`SSRenderer`]'s, shared so N
2700    // players of one character upload it once. So an override here is
2701    // a *redirect*: the replacement is registered under a private key (unique to
2702    // this player and this cellmap), and the player's own atlas-key table — which
2703    // every draw already resolves through — is pointed at it. That keeps the
2704    // override per player without giving `SSPlayer` a wgpu-typed field, and makes
2705    // a restore a redirect back to the shared atlas rather than a reload of it.
2706    //
2707    // An instance child plays from its own pack and so its own table, so a parent
2708    // override does not reach it.
2709
2710    /// Every cellmap name and external-texture name in a pack, the namespace
2711    /// [`SSPlayer::set_cellmap_texture`] takes. `None` selects the main pack;
2712    /// `None` return means no such pack is bound.
2713    ///
2714    /// Both tables, deliberately: a `DrawBatch.texture_hash` is a cellmap's
2715    /// `name_hash` for an ordinary part but a texture *file name*'s hash for one
2716    /// under an authored TextureChange, so the file names a `TCHG` can select
2717    /// (`common.png` and the like, including a cellmap's own image) are listed
2718    /// too — all of them legitimately replaceable.
2719    pub fn replaceable_cellmap_names(&self, pack_name: Option<&str>) -> Option<Vec<String>> {
2720        let name = pack_name.or(self.main_pack.as_deref())?;
2721        let pack = self.packs.get(name)?;
2722        let bytes = pack.resource().data();
2723        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2724        // loaded them (`SSPack::build`).
2725        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2726        let mut names: Vec<String> = Vec::new();
2727        if let Some(cellmaps) = ab.cellmaps() {
2728            names.extend(cellmaps.iter().map(|c| c.name().to_string()));
2729        }
2730        if let Some(externals) = ab.external_textures() {
2731            for et in externals {
2732                if let Some(tex) = et.name()
2733                    && !names.iter().any(|held| held == tex)
2734                {
2735                    names.push(tex.to_string());
2736                }
2737            }
2738        }
2739        Some(names)
2740    }
2741
2742    /// Replace the texture a cellmap binds, from straight-alpha RGBA8 pixels.
2743    ///
2744    /// `name` is a cellmap name (no `.ssce`) or a texture file name — one of the
2745    /// strings [`SSPlayer::replaceable_cellmap_names`] lists; it is hashed here.
2746    /// `None` selects the main pack. `rgba` is `width * height * 4` bytes and is
2747    /// premultiplied on the way to the GPU, exactly like a loaded atlas.
2748    ///
2749    /// The replacement should share the original atlas's size and cell layout: the
2750    /// runtime's UVs stay in the *original* cellmap's pixel space, so a different
2751    /// resolution samples a different region. Pass a part under a TextureChange
2752    /// its authored file name to affect the frames the change is active on — the
2753    /// cellmap name will not, because those frames bind through a different hash.
2754    ///
2755    /// The pixels reach the GPU on the next `update` (the borrow model lends no
2756    /// device before then), so the swap is visible from the following frame.
2757    ///
2758    /// `NotLoaded` with no pack bound; `InvalidParameter` for a pack this player
2759    /// does not hold, a name the pack cannot replace, or pixels that do not fill
2760    /// `width` x `height`.
2761    ///
2762    /// The replacement lives in the device-scoped renderer, which the player does
2763    /// not own: restore it with [`SSPlayer::restore_cellmap_texture`] and let an
2764    /// `update` drop it before dropping the player, or it stays registered.
2765    pub fn set_cellmap_texture(&mut self, pack_name: Option<&str>, name: &str, rgba: &[u8], width: u32, height: u32) -> Result<(), SSRuntimeError> {
2766        if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 {
2767            return Err(SSRuntimeError::InvalidParameter);
2768        }
2769        let Some(key) = self.override_cellmap_texture_key(pack_name, name) else {
2770            return Err(if self.resolve_pack_name(pack_name).is_none() { SSRuntimeError::NotLoaded } else { SSRuntimeError::InvalidParameter });
2771        };
2772        // Last write wins, and never leaves a stale copy queued for one key.
2773        self.pending_overrides.retain(|(queued, ..)| *queued != key);
2774        self.pending_overrides.push((key, rgba.to_vec(), width, height));
2775        Ok(())
2776    }
2777
2778    /// Redirect a cellmap to its private override key and return that key, without
2779    /// supplying any pixels — for a host that owns the GPU texture itself (an
2780    /// engine adapter, or the web face registering an `ImageBitmap`). The caller
2781    /// registers a texture under the returned key against the [`SSRenderer`]; every
2782    /// draw of this player's cellmap then resolves to it.
2783    ///
2784    /// `None` on an unbound player, for a pack this player does not hold, and for
2785    /// a `name` that is not one of [`SSPlayer::replaceable_cellmap_names`]. The
2786    /// lower half of [`SSPlayer::set_cellmap_texture`], and the seam
2787    /// `SSPlayer::restore_cellmap_texture` reverses.
2788    pub fn override_cellmap_texture_key(&mut self, pack_name: Option<&str>, name: &str) -> Option<u32> {
2789        if !self.can_replace(pack_name, name) {
2790            return None;
2791        }
2792        let pack = self.resolve_pack_name(pack_name)?;
2793        let cellmap_hash = ssruntime::fnv1a_hash_str(name);
2794        let key = override_key(self.id, &pack, cellmap_hash);
2795        // The key a restore returns to is whatever the cellmap resolves to *now*,
2796        // before this redirect — captured only when the override is first set, so
2797        // re-overriding does not overwrite it with the override's own key.
2798        let original = self.atlas_keys.get(&pack).map(|keys| keys.resolve(cellmap_hash)).unwrap_or(cellmap_hash);
2799        let entry = self.overrides.entry(pack.clone()).or_default();
2800        if !entry.iter().any(|over| over.cellmap_hash == cellmap_hash) {
2801            entry.push(CellmapOverride { cellmap_hash, key, original });
2802        }
2803        // A pending drop of this key is now stale — the override is live again.
2804        self.pending_forgets.retain(|queued| *queued != key);
2805        self.apply_atlas_entries(&pack, vec![(cellmap_hash, key)]);
2806        Some(key)
2807    }
2808
2809    /// Undo a runtime override: point the cellmap back at the shared atlas and
2810    /// retire the private key. Returns the retired key (so a host that registered
2811    /// its own texture under it can drop that too), or `None` if the cellmap was
2812    /// not overridden. `None` pack selects the main pack.
2813    ///
2814    /// The original atlas was never touched, so there is nothing to reload — the
2815    /// redirect back is the whole of it. The private key's texture is dropped from
2816    /// the renderer on the next `update`.
2817    pub fn restore_cellmap_texture(&mut self, pack_name: Option<&str>, name: &str) -> Option<u32> {
2818        let pack = self.resolve_pack_name(pack_name)?;
2819        let cellmap_hash = ssruntime::fnv1a_hash_str(name);
2820        let (over, now_empty) = {
2821            let overrides = self.overrides.get_mut(&pack)?;
2822            let pos = overrides.iter().position(|over| over.cellmap_hash == cellmap_hash)?;
2823            (overrides.remove(pos), overrides.is_empty())
2824        };
2825        if now_empty {
2826            self.overrides.remove(&pack);
2827        }
2828        // Drop any queued upload for the key; schedule the renderer entry's drop.
2829        self.pending_overrides.retain(|(queued, ..)| *queued != over.key);
2830        self.pending_forgets.push(over.key);
2831        self.apply_atlas_entries(&pack, vec![(cellmap_hash, over.original)]);
2832        Some(over.key)
2833    }
2834
2835    /// The private renderer keys this player's live overrides are registered
2836    /// under, for a face that owns the renderer to drop when it drops the player.
2837    #[cfg(any(feature = "ffi", feature = "web"))]
2838    pub(crate) fn override_keys(&self) -> impl Iterator<Item = u32> + '_ {
2839        self.overrides.values().flatten().map(|over| over.key)
2840    }
2841
2842    /// Whether a cellmap currently carries a runtime override. `None` pack selects
2843    /// the main pack.
2844    pub fn is_cellmap_overridden(&self, pack_name: Option<&str>, name: &str) -> bool {
2845        let Some(pack) = self.resolve_pack_name(pack_name) else { return false };
2846        let cellmap_hash = ssruntime::fnv1a_hash_str(name);
2847        self.overrides.get(&pack).is_some_and(|overrides| overrides.iter().any(|over| over.cellmap_hash == cellmap_hash))
2848    }
2849
2850    /// The pack a texture-override call names, or the main pack for `None`.
2851    fn resolve_pack_name(&self, pack_name: Option<&str>) -> Option<String> {
2852        pack_name.map(str::to_string).or_else(|| self.main_pack.clone())
2853    }
2854
2855    /// Whether the pack (`None` selects the main one) is registered and `name` is
2856    /// one of the names [`SSPlayer::replaceable_cellmap_names`] lists for it.
2857    pub(crate) fn can_replace(&self, pack_name: Option<&str>, name: &str) -> bool {
2858        let Some(pack) = pack_name.or(self.main_pack.as_deref()).and_then(|pack| self.packs.get(pack)) else { return false };
2859        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2860        // loaded them (`SSPack::build`).
2861        let ab = unsafe { root_as_ss_anime_binary_unchecked(pack.resource().data().as_slice()) };
2862        ab.cellmaps().is_some_and(|cellmaps| cellmaps.iter().any(|c| c.name() == name)) || ab.external_textures().is_some_and(|externals| externals.iter().any(|et| et.name() == Some(name)))
2863    }
2864
2865    /// The authored canvas of the currently playing animation, as a box in
2866    /// player-local units — what [`SSPlayer::fit_into`] fits when the caller
2867    /// supplies no frame of its own.
2868    ///
2869    /// This is the frame the artist composed in, not a measured bounding box, and
2870    /// the difference is the point: it costs nothing to read, it holds still while
2871    /// the animation plays, and it is where the author decided the empty space
2872    /// belongs. A tighter box is the host's to supply through
2873    /// [`Placement::frame`](crate::fit::Placement::frame) — measuring one here
2874    /// would mean baking every frame of the animation at load.
2875    ///
2876    /// It is the *current* animation's canvas, and one pack's animations may
2877    /// differ (Ringo's `dead` is 1300 wide, its others 800), so a host that wants
2878    /// one scale across a switch reads this once, after its first
2879    /// [`SSPlayer::set_animation`], and passes it as
2880    /// [`Placement::frame`](crate::fit::Placement::frame) from then on.
2881    ///
2882    /// The canvas is placed against the origin by the animation's **pivot**,
2883    /// which the runtime does not apply (it carries no pivot in its metadata) and
2884    /// which is normalised from the canvas centre: `(0, -0.5)` is the bottom edge,
2885    /// so a character authored standing on the ground reports a box entirely above
2886    /// the origin — negative `y`, because player-local `y` runs downward.
2887    pub fn canvas_rect(&self) -> Option<crate::fit::Rect> {
2888        let name = self.current_animation.as_ref()?;
2889        let pack = self.packs.get(self.main_pack.as_ref()?)?;
2890        let index = pack.resource().resource()?.find_animation_index(name)?;
2891        let bytes = pack.resource().data();
2892        // SAFETY: the pack's bytes, which the host guaranteed are a valid `.ssab` when it
2893        // loaded them (`SSPack::build`).
2894        let ab = unsafe { root_as_ss_anime_binary_unchecked(bytes.as_slice()) };
2895        let animations = ab.animations();
2896        // The runtime built its metadata by walking this same vector in order, so
2897        // the index is in range — checked rather than trusted, as the other reads
2898        // straight out of the buffer are.
2899        if index >= animations.len() {
2900            return None;
2901        }
2902        let animation = animations.get(index);
2903        let (width, height) = (animation.canvas_size().v1(), animation.canvas_size().v2());
2904        let (pivot_x, pivot_y) = (animation.pivot().v1(), animation.pivot().v2());
2905        // The pivot is where the origin sits inside the canvas, in editor space
2906        // (Y-up); the box is reported in player-local space (Y-down), which is
2907        // the one flip in this arithmetic.
2908        Some(crate::fit::Rect { x: -pivot_x * width - width / 2.0, y: pivot_y * height - height / 2.0, width, height })
2909    }
2910
2911    /// Fit the animation into a `width` x `height` box and place it there,
2912    /// writing the result through [`SSPlayer::set_transform`].
2913    ///
2914    /// The box the host lays out is in **pixels of the render target**, so call
2915    /// this again when that box changes — on a resize, and after
2916    /// [`SSPlayer::set_animation`] if the packs differ in canvas. It is pure
2917    /// arithmetic over [`Placement::frame`](crate::fit::Placement::frame) or
2918    /// [`SSPlayer::canvas_rect`]; nothing is measured and no GPU state is touched.
2919    ///
2920    /// The returned [`Placed`](crate::fit::Placed) is what was written, so a host
2921    /// can read back the scale it got rather than recomputing it — and can tell
2922    /// the fit from the no-fit answer, which a collapsed box or an animation that
2923    /// is not set up both produce (see [`solve`](crate::fit::solve)).
2924    pub fn fit_into(&mut self, width: f32, height: f32, placement: &crate::fit::Placement) -> crate::fit::Placed {
2925        let content = placement.frame.or_else(|| self.canvas_rect());
2926        let placed = crate::fit::solve(width, height, content, placement);
2927        self.set_transform(placed.x, placed.y, placed.scale_x, placed.scale_y, placement.rotation);
2928        placed
2929    }
2930
2931    /// Canvas size of the currently playing animation.
2932    pub fn canvas_size(&self) -> Option<(f32, f32)> {
2933        let name = self.current_animation.as_ref()?;
2934        let anim_resource = self.packs.get(self.main_pack.as_ref()?)?.resource().resource()?;
2935        let idx = anim_resource.find_animation_index(name)?;
2936        let anim_meta = &anim_resource.animations()[idx];
2937        Some((anim_meta.canvas_width, anim_meta.canvas_height))
2938    }
2939
2940    /// Hand the renderer any embedded atlas it does not already have.
2941    /// Called at the start of each `update` — the earliest point the borrow model
2942    /// lends a `Device`/`Queue` — and by `restore_textures`, which re-queues every
2943    /// pack against the new device.
2944    ///
2945    /// **Whatever is already registered wins**, and that is what makes the shared
2946    /// texture map pay off: the second player of a pack finds the atlas present,
2947    /// skips the PNG decode as well as the upload, and a host that supplied its own
2948    /// image for a hash keeps it. A host that wants the embedded pixels instead
2949    /// calls [`SSRenderer::forget_texture`] first.
2950    pub(crate) fn flush_textures(&mut self, renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue) {
2951        // Runtime overrides first, and unconditionally: they are host-supplied
2952        // pixels the renderer must retain (nothing can reproduce them after a
2953        // device loss), and a restore's drop rides the same flush. A key is in at
2954        // most one of the two lists — an override clears its pending drop, a
2955        // restore clears its pending upload.
2956        for (key, rgba, width, height) in std::mem::take(&mut self.pending_overrides) {
2957            renderer.upload_texture_owned(device, queue, key, rgba, (width, height), Retention::Retain);
2958        }
2959        for key in std::mem::take(&mut self.pending_forgets) {
2960            renderer.forget_texture(key);
2961        }
2962
2963        let pending = std::mem::take(&mut self.pending_images);
2964        let mut names = std::mem::take(&mut self.packs_awaiting_textures);
2965        if pending.is_empty() && names.is_empty() {
2966            return;
2967        }
2968        // Sorted because packs that disagree about a texture hash resolve by who
2969        // registers first, and that answer must not depend on load order.
2970        names.sort();
2971        names.dedup();
2972
2973        // The batch is assembled before anything is decoded, because the decode
2974        // runs in parallel and "already registered" cannot be re-read between
2975        // images. `claimed` holds the hashes an earlier entry took, so none is
2976        // decoded a second time.
2977        //
2978        // Host-read atlases come first, so a reference-mode image wins over an
2979        // embedded one for the same hash — the order [`SSPlayer::load`] read them
2980        // in. Both routes skip a hash the renderer already holds, which is what
2981        // keeps N players of one pack to one upload between them.
2982        let mut claimed: HashSet<u32> = HashSet::new();
2983        let mut jobs: Vec<(u32, &[u8], Retention)> = Vec::new();
2984        for (key, encoded) in &pending {
2985            if wanted_now(renderer, *key, encoded) && claimed.insert(*key) {
2986                // Retained: the bytes came from outside, so this player has nothing
2987                // it could decode again after a device loss.
2988                jobs.push((*key, encoded, Retention::Retain));
2989            }
2990        }
2991        for name in &names {
2992            let Some(pack) = self.packs.get(name) else { continue };
2993            // Registration decided these (see `add_pack`); reading them back is
2994            // what keeps the tree's lookups and this upload on one key.
2995            let keys = self.atlas_keys.get(name);
2996            for image in pack.embedded_images() {
2997                let key = keys.map(|keys| keys.resolve(image.slot)).unwrap_or(image.slot);
2998                if wanted_now(renderer, key, image.bytes) && claimed.insert(key) {
2999                    // Reproducible: this player still holds the `.ssab` and can
3000                    // decode the atlas again, so the renderer need not retain a
3001                    // second copy.
3002                    jobs.push((key, image.bytes, Retention::Reproducible));
3003                }
3004            }
3005        }
3006        decode_and_register(renderer, device, queue, &jobs);
3007    }
3008
3009    /// Advance this player by `delta_secs` and append its geometry to `scene`.
3010    ///
3011    /// Called by [`SSScene::update`] for each player in draw order — the scene
3012    /// owns the frame boundary (`begin_frame` / `end_frame`), because one frame
3013    /// spans every player sharing the target.
3014    ///
3015    /// `alpha` is the fade to fold into the parts: the player's own, or 1 when
3016    /// the scene fades it as a whole.
3017    pub(crate) fn build_frame(&mut self, scene: &mut FrameChunk, renderer: &SSRenderer, delta_secs: f32, alpha: f32) {
3018        self.rebuild = false;
3019        // `culled` means "this player cannot be seen": no timeline advance and no
3020        // geometry. `SSScene::update_with` has flushed its textures already, so it
3021        // can be unculled without re-loading anything.
3022        if self.culled {
3023            // What the last tick that ran reported is not this tick's news: a host
3024            // that plays a sound per event would replay it every update.
3025            self.report_no_tick();
3026            return;
3027        }
3028
3029        // No tree is a tick that did not run either: before the first
3030        // `set_animation`, and once `set_pack` — which `load` and `load_ssab` go
3031        // through — has dropped the tree that was playing.
3032        let Some(root) = &mut self.root else {
3033            self.report_no_tick();
3034            return;
3035        };
3036        // The runtime works in milliseconds for the primary context.
3037        root.context.update(delta_secs * 1000.0);
3038        self.started_edge = std::mem::take(&mut self.start_pending);
3039        let frame_no = root.context.get_frame_no();
3040        // The loop edge instance/effect slots re-arm their playback keys on. It
3041        // is a pulse the controller clears on entry to every `update`, so it has
3042        // to be read here, right after the one that raised it. Deriving it from
3043        // "the frame went backwards" instead is wrong under reverse and
3044        // ping-pong playback, where the frame goes backwards every tick.
3045        let looped = root.context.just_looped();
3046
3047        // Collect what the host reacts to before anything that could skip work:
3048        // events must fire whenever the runtime reports them, whether or not
3049        // this tick also draws — gating them on the integer draw frame changing
3050        // loses frame 0's events on the first tick after `play()`.
3051        let finished = root.context.is_finished();
3052        collect_events(root, &mut self.events);
3053        self.looped = looped;
3054        self.ran = true;
3055        self.finished_edge = finished && !self.prev_finished;
3056        self.prev_finished = finished;
3057
3058        let root = self.root.as_mut().expect("checked above");
3059
3060        // Advance every slot first, then draw. The two are separate walks for a
3061        // reason — see `step_slots`.
3062        step_slots(root, frame_no, delta_secs, looped);
3063
3064        if !self.visible {
3065            // Hidden, not culled: the clocks move, but nothing is drawn, so no
3066            // effect slot builds a plan.
3067            step_undrawn_effects(root);
3068            // The root's frame is still built, because the part read-outs read what
3069            // it leaves behind — without it a follower pinned to a hidden character
3070            // would freeze where the character was last drawn.
3071            // The display frame, as `prepare_node` asks for it.
3072            let frame_no = if self.sub_frame { frame_no } else { frame_no.floor() };
3073            let _ = root.context.get_frame_data(frame_no);
3074            return;
3075        }
3076
3077        let draw = NodeDraw { alpha, tint: pack_tint(self.tint) };
3078        let mut build = FrameBuild { scene, renderer, sub_frame: self.sub_frame };
3079        render_tree(root, &mut self.walk, &mut build, Place::Top(&self.transform, &self.crowd), frame_no, draw);
3080        // The nodes the walk did not prepare draw nothing, and their effect slots
3081        // still have to keep time: a hidden instance part's sub-animation, a child
3082        // its slot says is not showing.
3083        step_undrawn_effects(root);
3084    }
3085
3086    /// Whether this player's next update would build exactly what its last one
3087    /// did: nothing moves it, and no call has changed what it draws since.
3088    ///
3089    /// Read **before** the update, as the runtime's stack state has to be: the
3090    /// tick a fade ends on still moves the pose, and has to be built.
3091    ///
3092    /// Nothing moves a player whose clock is stopped, or whose track 0 has
3093    /// finished with no fade or other source left playing. A held clock moves
3094    /// only what plays on its own, an independent effect or instance. These are
3095    /// the runtime's reads every time; the player keeps no copy of its tracks,
3096    /// which would go stale the moment the runtime releases a source itself.
3097    pub(crate) fn settled(&self) -> bool {
3098        if self.rebuild {
3099            return false;
3100        }
3101        let Some(root) = self.root.as_ref().filter(|_| !self.culled) else { return true };
3102        let context = &root.context;
3103        if !context.is_playing() && !(context.is_clock_playing() && context.is_stack_in_motion()) {
3104            return true;
3105        }
3106        context.is_clock_pausing() && !plays_on_its_own(root)
3107    }
3108
3109    /// Report an update the scene did not run because every player was settled.
3110    pub(crate) fn skip_tick(&mut self) {
3111        self.report_no_tick();
3112    }
3113
3114    /// This player's identity: what a scene tells it from another by, wherever
3115    /// the host keeps it.
3116    pub(crate) fn id(&self) -> u32 {
3117        self.id
3118    }
3119
3120    /// Empty what a tick reports, for an update that did not run one. The reads
3121    /// between two updates describe the last tick, and there is none to describe.
3122    fn report_no_tick(&mut self) {
3123        self.events.clear();
3124        self.looped = false;
3125        self.ran = false;
3126        self.finished_edge = false;
3127        self.started_edge = false;
3128    }
3129
3130    /// What frame each instance child of the root is on, keyed by part index.
3131    ///
3132    /// A diagnostic, like [`SSPlayer::instance_node_count`] — and the only way to
3133    /// see that a child's clock is running while its part is hidden, since a
3134    /// hidden child draws nothing to look at.
3135    pub fn instance_child_frames(&self) -> Vec<(usize, f32)> {
3136        let Some(root) = &self.root else { return Vec::new() };
3137        let mut out: Vec<(usize, f32)> = root.instances.iter().map(|(&part_idx, child)| (part_idx, child.frame_no)).collect();
3138        out.sort_by_key(|&(part_idx, _)| part_idx);
3139        out
3140    }
3141
3142    /// Total number of instance child nodes in the current tree. A non-zero
3143    /// count confirms external references were resolved and the tree was built.
3144    pub fn instance_node_count(&self) -> usize {
3145        fn count(node: &PlaybackNode) -> usize {
3146            node.instances.values().map(|c| 1 + count(&c.node)).sum()
3147        }
3148        self.root.as_ref().map(count).unwrap_or(0)
3149    }
3150}
3151
3152/// Recursively build a playback node: create a context bound to `pack`'s
3153/// resource, set up `anime`, and build an instance child for every instance
3154/// part found in the pack. Child failures are skipped (not fatal).
3155fn build_node(packs: &HashMap<String, SSPack>, atlas_keys: &HashMap<String, Arc<AtlasKeys>>, pack: &str, anime: &str) -> Result<PlaybackNode, SSRuntimeError> {
3156    let resource = packs.get(pack).ok_or(SSRuntimeError::NotLoaded)?.resource();
3157    let res_ptr = resource.resource_static_ptr();
3158    if res_ptr.is_null() {
3159        return Err(SSRuntimeError::NotLoaded);
3160    }
3161    // SAFETY: the resource lives in `packs` for the player's lifetime.
3162    let static_res = unsafe { &*res_ptr };
3163    let mut context = Context::new();
3164    context.bind_resource(static_res);
3165    // Y-down, matching every sibling Player that draws into a Y-down target.
3166    // The Brain owns the flip and applies it once at the source — it mirrors the
3167    // hierarchy by
3168    // negating `position_y`, `rotation_z` and `pivot_y` — so the baked geometry,
3169    // the world matrices [`SSPlayer::part_transform`] hands out and the effect
3170    // particles all agree about which way is up. The projection undoes it for a
3171    // Y-up target (see `SSScene::set_viewport`), which is the one place the
3172    // target's own sense is known.
3173    context.set_coordinate_system(ssruntime::SsCoordinateSystem::YDown);
3174    context.setup_animation(anime)?;
3175    let (instances, effects, mask_flags) = build_rig(&context, static_res, packs, atlas_keys);
3176    Ok(PlaybackNode { context, instances, effects, effect_clock: None, mask_flags, pack: pack.to_string(), atlas_keys: node_atlas_keys(atlas_keys, pack), res: static_res })
3177}
3178
3179/// The per-animation half of a node: which instance children it mounts, which
3180/// effect slots it owns, and the static mask flags its parts carry.
3181///
3182/// Split out of [`build_node`] because it is the only half a *switch* has to
3183/// redo. The context is the animation-independent half — it belongs to the pack,
3184/// and handing it a new clip through `setup_animation` is what keeps the speed,
3185/// the frame-rate override, the frame skip and the playback direction across the
3186/// switch.
3187fn build_rig(
3188    context: &Context<'static>,
3189    static_res: &'static ssruntime::AnimationResource<'static>,
3190    packs: &HashMap<String, SSPack>,
3191    atlas_keys: &HashMap<String, Arc<AtlasKeys>>,
3192) -> (HashMap<usize, InstanceChild>, HashMap<usize, EffectPart>, Vec<PartMaskFlags>) {
3193    let mut instances = HashMap::new();
3194    let mut effects = HashMap::new();
3195    let mut mask_flags = Vec::new();
3196    if let Some(ssab_bytes) = context.get_ssab_data() {
3197        let ab = unsafe { root_as_ss_anime_binary_unchecked(ssab_bytes) };
3198        // The pack's part list is shared across its animations; part index i
3199        // matches the FrameData part index used by draw_order/SoA.
3200        let parts = ab.parts();
3201        mask_flags = vec![PartMaskFlags::default(); parts.len()];
3202        for (i, part) in parts.iter().enumerate() {
3203            let part_type = part.part_type_type();
3204
3205            // Static mask flags. Geometry kind picks the
3206            // writer builder; Text/Nines can't write coverage yet.
3207            let geom = match part_type {
3208                PartType::PartTypeNormal | PartType::PartTypeMask => GeomKind::Quad,
3209                PartType::PartTypeMesh => GeomKind::Mesh,
3210                PartType::PartTypeShape => GeomKind::Shape,
3211                _ => GeomKind::Unsupported,
3212            };
3213            mask_flags[i] = PartMaskFlags { is_mask_part: part_type == PartType::PartTypeMask, mask_write: part.mask_write(), mask_influence: part.mask_influence(), visible_inside_mask: part.visible_inside_mask(), draw_as_mask: part.draw_as_mask(), geom };
3214
3215            match part_type {
3216                PartType::PartTypeInstance => {
3217                    if let Some(inst) = part.part_type_as_part_type_instance()
3218                        && let Ok(child) = build_node(packs, atlas_keys, inst.ref_anime_pack(), inst.ref_anime_name())
3219                    {
3220                        let frame_no = child.context.get_frame_no();
3221                        instances.insert(i, InstanceChild { slot: InstanceSlot::new(), node: Box::new(child), frame_no, visible: false, prep: None });
3222                    }
3223                }
3224                PartType::PartTypeEffect => {
3225                    if let Some(eff) = part.part_type_as_part_type_effect()
3226                        && let Ok(slot) = EffectSlot::new(static_res, eff.ref_effect_name_hash(), i as u32)
3227                    {
3228                        effects.insert(i, EffectPart { slot, plan: Vec::new() });
3229                    }
3230                }
3231                _ => {}
3232            }
3233        }
3234    }
3235
3236    (instances, effects, mask_flags)
3237}
3238
3239/// Advance every slot this node owns, and recurse through the instance
3240/// children — **over the parts, not over what is drawn**.
3241///
3242/// This is deliberately a separate walk from [`render_node`], because the two
3243/// answer different questions: *whose clock moves* is every slot in the pack,
3244/// while *what is drawn and in what order* is `draw_order`. The runtime drops
3245/// `Hide`-ed parts from `draw_order` / `draw_batches` entirely (`framedata.rs`,
3246/// `drawn_as_self`), so stepping from the draw walk stops a slot the moment its
3247/// part is hidden. For an independently-played effect or instance — one running
3248/// on its own elapsed time rather than the parent's frame — that freezes the
3249/// clock and makes it resume late by exactly the time it spent hidden, which is
3250/// not what SpriteStudio means by independent playback. The slots are built
3251/// from the pack's part list in [`build_node`], so they are all here to walk.
3252///
3253/// What the draw walk needs afterwards is left on each slot: the child's frame
3254/// and visibility. An effect slot is only handed its clock here, and steps in
3255/// [`step_effects`] once its node's frame is fetched: the frame is what says
3256/// whether the effect's part is drawn, and a child's frame is not known until
3257/// its slot has stepped.
3258fn step_slots(node: &mut PlaybackNode, frame_no: f32, delta_secs: f32, node_looped: bool) {
3259    node.effect_clock = Some(EffectClock { frame_no, delta_secs, looped: node_looped });
3260
3261    for (&part_idx, child) in node.instances.iter_mut() {
3262        let ev = node.context.get_active_event_instance(part_idx as u32);
3263        let r = child.slot.step(ev, &mut child.node.context, frame_no, delta_secs, node_looped);
3264        // The child runs at the speed its slot stepped it with, so its own
3265        // sub-tree has to be stepped with the same scaling — the parent's raw
3266        // delta would run the grandchildren at the wrong rate. Read it from the
3267        // slot, not from `ev`: once the parent goes back before an independent
3268        // child's first key, `ev` is the implicit key at speed 1 while the slot
3269        // keeps the child at the last key's speed.
3270        let child_delta = delta_secs * child.slot.get_speed().abs();
3271
3272        // On a transition edge the slot configures the child — section, direction,
3273        // loop count, and the frame it starts on — but does not start it: play()
3274        // does, so independent playback actually advances.
3275        if r.transitioned {
3276            child.node.context.play();
3277            // The child starts over from its section head, so its own slots start
3278            // over too. Left armed, the grandchildren and effects it keyed in its
3279            // last run would read their first key as one they already started and
3280            // carry on from where they were instead of starting with the child.
3281            reset_slots(&mut child.node);
3282        }
3283        // The slot's frame, the transition tick included. Reading the controller
3284        // back after that play() would put a synced child at its section start for
3285        // one tick instead of where the parent has it.
3286        // Raw, never rounded: rounding here would truncate sub-frame progress on
3287        // every tick and freeze the child when a tick is worth less than a frame.
3288        child.frame_no = r.child_frame_no;
3289        child.visible = r.visible;
3290
3291        // Recurse regardless of visibility, and re-arm the grandchildren on the
3292        // *child's* loop rather than the parent animation's: an independent child
3293        // runs on its own clock, so that is the edge they must re-fire on.
3294        step_slots(&mut child.node, child.frame_no, child_delta, r.child_looped);
3295    }
3296}
3297
3298/// Clear every slot's memory of the key it last started, under `node` and in
3299/// its instance children at every depth, so the next step starts each slot on
3300/// its key afresh.
3301///
3302/// For whenever a node's animation heads out again: a [`SSPlayer::play`], or a
3303/// child its slot has just started. Without it, an independent effect or
3304/// instance takes its first key for the one it already started and never
3305/// starts again.
3306fn reset_slots(node: &mut PlaybackNode) {
3307    for effect in node.effects.values_mut() {
3308        effect.slot.reset();
3309    }
3310    for child in node.instances.values_mut() {
3311        child.slot.reset();
3312        reset_slots(&mut child.node);
3313    }
3314}
3315
3316/// Whether anything under `node` plays on its own clock — an effect or an
3317/// instance child its slot runs independently — and so moves while the node's
3318/// own clock is held.
3319fn plays_on_its_own(node: &PlaybackNode) -> bool {
3320    node.effects.values().any(|effect| effect.slot.is_independent()) || node.instances.values().any(|child| child.slot.is_independent() || plays_on_its_own(&child.node))
3321}
3322
3323/// Step every effect slot of `node` on the clock [`step_slots`] left it — once a
3324/// tick, so a node already stepped is left alone.
3325///
3326/// Every slot steps, drawn or not, for the reason [`step_slots`] walks the parts.
3327/// `drawn` says whether a part is in the node's `draw_order` this frame; a slot
3328/// whose part is not keeps time and builds no plan. The step reads only the
3329/// node's playhead and effect keys, which fetching the frame leaves as they are,
3330/// so it steps after the fetch exactly as it would before it.
3331fn step_effects(node: &mut PlaybackNode, drawn: impl Fn(usize) -> bool) {
3332    let Some(EffectClock { frame_no, delta_secs, looped }) = node.effect_clock.take() else { return };
3333    let fps = node.context.get_frame_rate() as f32;
3334    for (&part_idx, effect) in node.effects.iter_mut() {
3335        let ev = node.context.get_active_effect_event(part_idx as u32);
3336        // vert_stride=2 (packed XY), y_flip=true: the context runs Y-down, so the
3337        // particles are mirrored with the parts around them rather than against.
3338        let r = effect.slot.step(ev, frame_no, delta_secs, fps, looped, true, 2, drawn(part_idx));
3339        effect.plan.clear();
3340        if r.visible && !r.draw_plan_buf.is_null() && r.draw_plan_len > 0 {
3341            // SAFETY: the slot just built this buffer and owns it until its next
3342            // step; nothing steps it between here and the copy.
3343            effect.plan.extend_from_slice(unsafe { std::slice::from_raw_parts(r.draw_plan_buf, r.draw_plan_len) });
3344        }
3345    }
3346}
3347
3348/// Step, undrawn, every effect slot under `node` that [`step_effects`] has not
3349/// stepped this tick: the nodes the draw walk did not prepare, or the whole tree
3350/// when nothing is drawn.
3351fn step_undrawn_effects(node: &mut PlaybackNode) {
3352    step_effects(node, |_| false);
3353    for child in node.instances.values_mut() {
3354        step_undrawn_effects(&mut child.node);
3355    }
3356}
3357
3358/// The scene being filled and the device-scoped renderer it reads texture sizes
3359/// from, bundled for the tree walk. Only the scene is mutated — pipelines are compiled later, in
3360/// `end_frame`, which is where the renderer is borrowed mutably.
3361struct FrameBuild<'a> {
3362    scene: &'a mut FrameChunk,
3363    renderer: &'a SSRenderer,
3364    /// The owning player's [`SSPlayer::set_sub_frame_enabled`]. Carried here rather than
3365    /// passed down, so it reaches every node of the tree — an instance child is
3366    /// drawn at its own playhead and has to be floored on the same terms.
3367    sub_frame: bool,
3368}
3369
3370/// Where a node of the tree is placed.
3371#[derive(Clone, Copy)]
3372enum Place<'c> {
3373    /// The top node: at the player's own placement, under each member of its
3374    /// crowd.
3375    Top(&'c [f32; 16], &'c [CrowdMember]),
3376    /// A sub-animation: at its instance part's world matrix, under each of the
3377    /// parent node's placements.
3378    Under(NodeSlot, [f32; 16]),
3379}
3380
3381/// How one node of the tree is drawn: how opaque it is and how it is tinted.
3382///
3383/// `alpha` changes per recursion level (each instance child folds in its
3384/// part's opacity), `tint` is the owning player's and is constant for the whole
3385/// walk. Where a node sits is decided before the walk, in [`prepare_node`].
3386#[derive(Clone, Copy)]
3387struct NodeDraw {
3388    /// Player-level fade; see [`BatchInfo::alpha`]. Never applied to mask
3389    /// coverage — a faded player clips exactly as it would at full opacity.
3390    alpha: f32,
3391    /// Player-level tint, already in the shader's byte order; see
3392    /// [`BatchInfo::tint`]. Constant for the whole walk.
3393    tint: u32,
3394}
3395
3396/// The mask flags an instance part hands the sub-animation it draws.
3397///
3398/// **One level, never a chain**: a sub-animation's parts compose with their own
3399/// instance part's `mask_influence` (AND) and `visible_inside_mask` (OR), and
3400/// with nothing above it — a grandparent instance part that opts out of masking
3401/// does not opt its grandchildren out. And the flags reach the sub-animation
3402/// whether or not anything above masks. SpriteStudio 7.6 draws it this way; the
3403/// data that tells the two apart nests an instance that opts out around one that
3404/// opts in. The identity — a top-level animation called by no instance — is
3405/// [`InheritedMask::ROOT`].
3406#[derive(Clone, Copy)]
3407struct InheritedMask {
3408    influence: bool,
3409    visible_inside: bool,
3410}
3411
3412impl InheritedMask {
3413    /// The identity a top-level animation starts from.
3414    const ROOT: Self = Self { influence: true, visible_inside: false };
3415
3416    /// What `part`, an instance part, hands its sub-animation: its own flags,
3417    /// and none of what its own animation inherited.
3418    fn of_instance(part: &PartMaskFlags) -> Self {
3419        Self { influence: part.mask_influence, visible_inside: part.visible_inside_mask }
3420    }
3421
3422    /// Whether a drawn part is a mask target — its effective `mask_influence`
3423    /// (own AND inherited) is set. `mask_write` does not make it a target; that
3424    /// is the writer's own fact.
3425    fn targets(self, part: &PartMaskFlags) -> bool {
3426        self.influence && part.mask_influence
3427    }
3428
3429    /// Whether a target draws inside the coverage (own OR inherited).
3430    fn inside(self, part: &PartMaskFlags) -> bool {
3431        self.visible_inside || part.visible_inside_mask
3432    }
3433}
3434
3435/// One node of the instance tree, made ready for this frame before anything is
3436/// drawn.
3437///
3438/// The whole tree is prepared first because the mask state is the tree's, not a
3439/// node's: a clipping mask written inside an instance keeps clipping its callers'
3440/// later parts however deep it sits, so every writer and every part's place in
3441/// the drawing order has to be known before the first part draws. Preparing is
3442/// also where each node's frame is fetched, **once** — fetching a frame again
3443/// rebuilds the runtime's buffers under any slice still pointing into them.
3444struct NodePrep<'r> {
3445    frame: FrameView<'r>,
3446    /// Where the node draws, in the arena: the player's placement composed with
3447    /// every instance part above it, once per member of the crowd.
3448    slot: NodeSlot,
3449    /// Node-local to player-local: the chain of instance placements alone. The
3450    /// coverage bitmap is pinned to the player, not to the screen.
3451    to_root: [f32; 16],
3452    ctx: InheritedMask,
3453    /// Where this node's ranks start in [`Walk::seq`].
3454    seq: usize,
3455}
3456
3457/// What one frame's walk over a player's instance tree fills, kept on the player
3458/// so that the walk allocates nothing once the first frames have sized it.
3459struct Walk {
3460    /// Every node prepared this frame, the top one first.
3461    ///
3462    /// `'static` in type only. The views point into the runtime's buffers, which
3463    /// the node's next fetch rebuilds, so the walk empties this before it
3464    /// returns and no view outlives its frame.
3465    preps: Vec<NodePrep<'static>>,
3466    /// Each prepared node's ranks' places on the tree sequence (see
3467    /// [`ScopedWriter`]), at the node's [`NodePrep::seq`].
3468    seq: Vec<i32>,
3469    /// The writers planned for the nodes being prepared: a node's own run at the
3470    /// end while it is, dropped once it is placed.
3471    planned: Vec<MaskWriter>,
3472    mask: TreeMask,
3473}
3474
3475impl Default for Walk {
3476    fn default() -> Self {
3477        Self { preps: Vec::new(), seq: Vec::new(), planned: Vec::new(), mask: TreeMask::new(crate::MaskBackend::None) }
3478    }
3479}
3480
3481/// Where a pure mask of the top animation opens: before the first part.
3482const TREE_START: i32 = -1;
3483/// Where every clipping writer closes: past the last part of the tree.
3484const TREE_END: i32 = i32::MAX;
3485
3486/// How one drawn part meets the mask this frame.
3487#[derive(Clone, Copy, PartialEq, Eq)]
3488enum PartMask {
3489    /// Not tested: no mask reaches it, or it opts out.
3490    Plain,
3491    /// Tested with this polarity.
3492    Tested(StencilTest),
3493    /// Draws only inside a mask and no mask covers it, so it draws nowhere —
3494    /// also in an animation with no mask at all.
3495    Hidden,
3496}
3497
3498/// The player's mask state for one frame: every writer of the instance tree,
3499/// placed on the tree sequence, and — for the stencil — how far the drawing has
3500/// got through adding and removing them.
3501struct TreeMask {
3502    backend: crate::MaskBackend,
3503    /// Capped at [`crate::mask::MAX_MASK_WRITERS`], in drawing order.
3504    writers: Vec<ScopedWriter>,
3505    /// The prep each writer's geometry comes from, parallel to `writers`.
3506    writer_nodes: Vec<usize>,
3507    /// Stencil only: `(seq, writer, add)`, applied once the drawing passes `seq`.
3508    events: Vec<(i32, usize, bool)>,
3509    cursor: usize,
3510    /// Coverage only: the player-local -> coverage-UV affine and the layer the
3511    /// tree baked into, for the effect slots the walk points at them.
3512    coverage: Option<([f32; 6], u32)>,
3513}
3514
3515impl TreeMask {
3516    fn new(backend: crate::MaskBackend) -> Self {
3517        Self { backend, writers: Vec::new(), writer_nodes: Vec::new(), events: Vec::new(), cursor: 0, coverage: None }
3518    }
3519
3520    /// Empty it for a new frame drawn under `backend`, keeping the allocations.
3521    fn reset(&mut self, backend: crate::MaskBackend) {
3522        self.backend = backend;
3523        self.writers.clear();
3524        self.writer_nodes.clear();
3525        self.events.clear();
3526        self.cursor = 0;
3527        self.coverage = None;
3528    }
3529
3530    fn masking(&self) -> bool {
3531        self.backend != crate::MaskBackend::None
3532    }
3533
3534    /// Place one of a node's writers, found at `seq`, on the tree sequence.
3535    /// `open` is where the node's own animation starts.
3536    fn place(&mut self, writer: &MaskWriter, seq: i32, open: i32, node: usize, ctx: InheritedMask) {
3537        if self.writers.len() >= crate::mask::MAX_MASK_WRITERS {
3538            return;
3539        }
3540        // The op follows the effective `mask_influence` — one level, like a
3541        // target's: inside a `mask_influence == 0` instance a writer lands on the
3542        // counter plane and adds to its caller's masks instead of cancelling them.
3543        let writer = MaskWriter { op_invert: writer.op_invert && ctx.influence, ..*writer };
3544        let (open, close) = if writer.is_clipping { (seq, TREE_END) } else { (open, seq) };
3545        self.writers.push(ScopedWriter { writer, open, close });
3546        self.writer_nodes.push(node);
3547    }
3548
3549    /// Whether any writer holds its bit at `seq`.
3550    fn covers(&self, seq: i32) -> bool {
3551        self.writers.iter().any(|w| w.open < seq && seq < w.close)
3552    }
3553
3554    /// How the part at `seq` meets the mask, given its own flags and the ones its
3555    /// instance part handed down.
3556    fn part(&self, flags: &PartMaskFlags, ctx: InheritedMask, seq: i32) -> PartMask {
3557        if !self.masking() || !ctx.targets(flags) {
3558            return PartMask::Plain;
3559        }
3560        let inside = ctx.inside(flags);
3561        if self.covers(seq) {
3562            PartMask::Tested(if inside { StencilTest::Inside } else { StencilTest::Outside })
3563        } else if inside {
3564            PartMask::Hidden
3565        } else {
3566            PartMask::Plain
3567        }
3568    }
3569
3570    /// Stencil only: order every writer's add and removal along the tree.
3571    ///
3572    /// A single hardware stencil holds one state at a time, so each writer is
3573    /// added when the drawing passes its `open` and removed when it passes its
3574    /// `close`: a pure mask is written before its own animation's first part and
3575    /// taken out at itself, a clipping mask put in at itself and left for
3576    /// [`TreeMask::finish`]. Incr/Decr and Invert each stay in their own plane and
3577    /// commute within it, so writers that share a point may go in any order.
3578    fn schedule(&mut self) {
3579        for (i, w) in self.writers.iter().enumerate() {
3580            self.events.push((w.open, i, true));
3581            self.events.push((w.close, i, false));
3582        }
3583        self.events.sort_by_key(|&(seq, _, _)| seq);
3584    }
3585
3586    /// Stencil only: apply every add and removal that falls before `seq`, so the
3587    /// buffer holds exactly the writers in scope for the part drawn there.
3588    fn sync(&mut self, build: &mut FrameBuild<'_>, preps: &[NodePrep<'_>], seq: i32) {
3589        while self.cursor < self.events.len() && self.events[self.cursor].0 < seq {
3590            self.apply_next(build, preps);
3591        }
3592    }
3593
3594    /// Draw the next scheduled add or removal into the stencil.
3595    fn apply_next(&mut self, build: &mut FrameBuild<'_>, preps: &[NodePrep<'_>]) {
3596        let (_, i, add) = self.events[self.cursor];
3597        let w = &self.writers[i].writer;
3598        // Increment pairs with decrement; invert is its own inverse.
3599        let op = match (w.op_invert, add) {
3600            (true, _) => MaskOp::Invert,
3601            (false, true) => MaskOp::Incr,
3602            (false, false) => MaskOp::Decr,
3603        };
3604        let prep = &preps[self.writer_nodes[i]];
3605        build.scene.append_mask_writer(&prep.frame, &prep.slot, w, op);
3606        self.cursor += 1;
3607    }
3608
3609    /// Stencil only: take back everything still applied — the clipping writers,
3610    /// which hold to the end of the tree, and whatever the drawing never reached.
3611    ///
3612    /// Every writer is added once and removed once, so the player leaves the
3613    /// stencil buffer as it found it. Without this the invariant only holds by
3614    /// accident: one player per render pass, with `LoadOp::Clear(0)` wiping the
3615    /// residue between frames. Stack a second player into the same pass and the
3616    /// first one's mask clips it.
3617    fn finish(&mut self, build: &mut FrameBuild<'_>, preps: &[NodePrep<'_>]) {
3618        while self.cursor < self.events.len() {
3619            self.apply_next(build, preps);
3620        }
3621    }
3622}
3623
3624/// Transform a node-local bounding rectangle by `m`, returning the rectangle
3625/// that encloses it. Only the affine 2D part of `m` matters (the runtime's local
3626/// Z is zero).
3627fn transform_bounds(bounds: [f32; 4], m: &[f32; 16]) -> [f32; 4] {
3628    let (m0, m1, m4, m5, m12, m13) = (m[0], m[1], m[4], m[5], m[12], m[13]);
3629    let [min_x, min_y, max_x, max_y] = bounds;
3630    let mut out = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
3631    for (x, y) in [(min_x, min_y), (max_x, min_y), (min_x, max_y), (max_x, max_y)] {
3632        let px = m0 * x + m4 * y + m12;
3633        let py = m1 * x + m5 * y + m13;
3634        out[0] = out[0].min(px);
3635        out[1] = out[1].min(py);
3636        out[2] = out[2].max(px);
3637        out[3] = out[3].max(py);
3638    }
3639    out
3640}
3641
3642/// A player-local -> coverage-UV affine, pulled back through `m` (node-local to
3643/// player-local) so a node's own coordinates land where the writers were baked.
3644/// Only the 2D part matters: coverage is a flat bitmap and the runtime's local Z
3645/// is zero.
3646fn compose_uv(uv: &[f32; 6], m: &[f32; 16]) -> [f32; 6] {
3647    let [a, b, c, d, tx, ty] = *uv;
3648    let (m0, m1, m4, m5, m12, m13) = (m[0], m[1], m[4], m[5], m[12], m[13]);
3649    [a * m0 + c * m1, b * m0 + d * m1, a * m4 + c * m5, b * m4 + d * m5, a * m12 + c * m13 + tx, b * m12 + d * m13 + ty]
3650}
3651
3652/// A column-major 4x4 identity: where the top node sits relative to itself.
3653const IDENTITY_MATRIX: [f32; 16] = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0];
3654
3655/// Draw one player's instance tree: prepare every node, settle the tree's mask,
3656/// then walk it in drawing order.
3657fn render_tree(root: &mut PlaybackNode, walk: &mut Walk, build: &mut FrameBuild<'_>, place: Place<'_>, frame_no: f32, draw: NodeDraw) {
3658    walk.mask.reset(build.scene.mask_backend());
3659    let mut next_seq = 0;
3660    if let Some(top) = prepare_node(root, build, frame_no, place, IDENTITY_MATRIX, InheritedMask::ROOT, TREE_START, &mut next_seq, walk) {
3661        match walk.mask.backend {
3662            crate::MaskBackend::Coverage => bake_coverage(build, &mut walk.preps, &mut walk.mask),
3663            crate::MaskBackend::Stencil => walk.mask.schedule(),
3664            crate::MaskBackend::None => {}
3665        }
3666
3667        render_node(root, top, &walk.preps, &walk.seq, build, draw, &mut walk.mask);
3668
3669        if walk.mask.backend == crate::MaskBackend::Stencil {
3670            walk.mask.finish(build, &walk.preps);
3671        }
3672    }
3673    walk.preps.clear();
3674    walk.seq.clear();
3675}
3676
3677/// Fetch a node's frame, copy it into the arena, step its effect slots, number
3678/// its ranks on the tree sequence and place its writers — then the same for each
3679/// visible instance child, in its instance part's place. Returns the node's
3680/// index in `walk.preps`.
3681///
3682/// `open` is where this node's animation starts on the sequence: the top
3683/// animation's before its first part, a sub-animation's at its instance part.
3684#[allow(clippy::too_many_arguments)]
3685fn prepare_node(node: &mut PlaybackNode, build: &mut FrameBuild<'_>, frame_no: f32, place: Place<'_>, to_root: [f32; 16], ctx: InheritedMask, open: i32, next_seq: &mut i32, walk: &mut Walk) -> Option<usize> {
3686    // The DISPLAY frame. The playhead keeps its fraction whatever this is set to;
3687    // flooring it here is the whole of what turning sub-frame off does.
3688    let frame_no = if build.sub_frame { frame_no } else { frame_no.floor() };
3689    let frame_data: &'static [u8] = match node.context.get_frame_data(frame_no) {
3690        Ok(bytes) => unsafe { std::slice::from_raw_parts(bytes.as_ptr(), bytes.len()) },
3691        Err(_) => return None,
3692    };
3693    let frame = frame_view(&mut node.context, frame_data);
3694    // The node's placement goes into the arena first; each part it draws copies
3695    // its own geometry in after it.
3696    let slot = match place {
3697        Place::Top(transform, crowd) => build.scene.push_root_transform(transform, crowd),
3698        Place::Under(parent, local) => build.scene.push_child_transform(&parent, &local),
3699    };
3700    let index = walk.preps.len();
3701    let fd = unsafe { root_as_frame_data_unchecked(frame.frame_data) };
3702    let draw_order = fd.draw_order();
3703    let seq = walk.seq.len();
3704    walk.seq.resize(seq + draw_order.len(), 0);
3705    walk.preps.push(NodePrep { frame, slot, to_root, ctx, seq });
3706
3707    // `plan_writers_into` appends them in ascending rank.
3708    let planned = walk.planned.len();
3709    if walk.mask.masking() {
3710        plan_writers_into(&frame, &node.mask_flags, &mut walk.planned);
3711    }
3712    retarget(&mut walk.planned[planned..], &node.atlas_keys);
3713    let (mut own, own_end) = (planned, walk.planned.len());
3714
3715    // The runtime leaves a hidden part out of `draw_order`, so its own hide flag
3716    // is whether the effect it plays is drawn.
3717    let parts = fd.parts();
3718    step_effects(node, |part_idx| part_idx < parts.len() && !parts.get(part_idx).hide());
3719
3720    for rank in 0..draw_order.len() {
3721        let here = *next_seq;
3722        *next_seq += 1;
3723        walk.seq[seq + rank] = here;
3724        while own < own_end && walk.planned[own].rank <= rank {
3725            let writer = walk.planned[own];
3726            walk.mask.place(&writer, here, open, index, ctx);
3727            own += 1;
3728        }
3729
3730        // A visible instance's sub-animation is drawn in its instance part's
3731        // place, so it is numbered right there, ahead of the next part.
3732        let part_idx = draw_order.get(rank) as usize;
3733        let Some(child) = node.instances.get_mut(&part_idx) else { continue };
3734        child.prep = None;
3735        if !child.visible || (part_idx + 1) * 16 > frame.world_matrices.len() {
3736            continue;
3737        }
3738        let m: [f32; 16] = frame.world_matrices[part_idx * 16..part_idx * 16 + 16].try_into().unwrap();
3739        let child_ctx = InheritedMask::of_instance(&node.mask_flags.get(part_idx).copied().unwrap_or_default());
3740        let child_frame_no = child.frame_no;
3741        child.prep = prepare_node(&mut child.node, build, child_frame_no, Place::Under(slot, m), mat4_mul(&to_root, &m), child_ctx, here, next_seq, walk);
3742    }
3743    walk.planned.truncate(planned);
3744    Some(index)
3745}
3746
3747/// Rasterise every writer of the tree into one coverage bitmap, owned by the top
3748/// node, and point every other node at it through its own placement.
3749///
3750/// The replay needs no running state: each writer's record carries its scope on
3751/// the tree sequence, and a masked part carries its own place on it.
3752fn bake_coverage(build: &mut FrameBuild<'_>, preps: &mut [NodePrep<'_>], mask: &mut TreeMask) {
3753    // Bounds enclose every writer, each mapped through its node's instance
3754    // placements into the player's local space, so the bitmap covers them all.
3755    let mut bounds: Option<[f32; 4]> = None;
3756    for (w, &n) in mask.writers.iter().zip(&mask.writer_nodes) {
3757        let Some(b) = crate::mask::writer_bounds(&preps[n].frame, std::slice::from_ref(&w.writer)) else { continue };
3758        let b = transform_bounds(b, &preps[n].to_root);
3759        bounds = Some(match bounds {
3760            Some([a, bb, c, d]) => [a.min(b[0]), bb.min(b[1]), c.max(b[2]), d.max(b[3])],
3761            None => b,
3762        });
3763    }
3764    let Some([min_x, min_y, max_x, max_y]) = bounds else {
3765        // Nothing to rasterise, so nothing covers anything: parts drawn only
3766        // inside a mask must draw nowhere rather than untested.
3767        mask.writers.clear();
3768        mask.writer_nodes.clear();
3769        return;
3770    };
3771    let (w, h) = ((max_x - min_x).max(f32::EPSILON), (max_y - min_y).max(f32::EPSILON));
3772    let uv = [1.0 / w, 0.0, 0.0, 1.0 / h, -min_x / w, -min_y / h];
3773
3774    let (top, rest) = preps.split_first_mut().expect("the top node is prepared first");
3775    build.scene.set_node_coverage(&mut top.slot, &uv, (w, h), &mask.writers);
3776    let layer = build.scene.node_coverage_layer(&top.slot);
3777    mask.coverage = Some((uv, layer));
3778    for prep in rest {
3779        build.scene.inherit_node_coverage(&mut prep.slot, &compose_uv(&uv, &prep.to_root), layer, &mask.writers);
3780    }
3781    // Each writer bakes through its own node's block, whose affine lands its
3782    // node-local geometry in the player's bitmap; the bit is its record's index.
3783    for (bit, (w, &n)) in mask.writers.iter().zip(&mask.writer_nodes).enumerate() {
3784        build.scene.append_coverage_writer(&preps[n].frame, &preps[n].slot, &w.writer, bit);
3785    }
3786}
3787
3788/// Append one prepared node's geometry, recursing into its instance children in
3789/// their instance parts' places.
3790///
3791/// Draw only: every instance slot was advanced by [`step_slots`], and every node
3792/// prepared, its effect slots stepped with it, by [`prepare_node`] before this
3793/// walk began, so this reads what they left behind rather than driving it.
3794///
3795/// Masking is decided per part, the same way at every depth: whether it is a
3796/// target and its polarity from its own flags and its instance part's
3797/// ([`InheritedMask`]), and whether any writer of the tree is in scope from its
3798/// place on the tree sequence ([`TreeMask::part`]).
3799fn render_node(node: &mut PlaybackNode, index: usize, preps: &[NodePrep<'_>], seqs: &[i32], build: &mut FrameBuild<'_>, draw: NodeDraw, mask: &mut TreeMask) {
3800    let NodeDraw { alpha, tint } = draw;
3801    let prep = &preps[index];
3802    let (frame, node_slot, ctx) = (&prep.frame, &prep.slot, prep.ctx);
3803    let seq_of = |rank: usize| seqs[prep.seq + rank];
3804
3805    let fd = unsafe { root_as_frame_data_unchecked(frame.frame_data) };
3806    let draw_order = fd.draw_order();
3807    for batch in fd.draw_batches() {
3808        let start_rank = batch.start_rank() as usize;
3809        let count = batch.count() as usize;
3810        let kind = batch.kind();
3811        match kind {
3812            DrawBatchKind::Normal | DrawBatchKind::Mesh | DrawBatchKind::Shape => {
3813                // Pure masks (PartTypeMask / draw_as_mask) contribute coverage but
3814                // never draw their own colour. The runtime still
3815                // emits a content batch for them, so skip it here.
3816                let is_pure = |pi: usize| node.mask_flags.get(pi).map(|f| f.pure_mask()).unwrap_or(false);
3817                let part_mask = |rank: usize, mask: &TreeMask| {
3818                    let f = node.mask_flags.get(draw_order.get(rank) as usize).copied().unwrap_or_default();
3819                    mask.part(&f, ctx, seq_of(rank))
3820                };
3821                let texture_hash = node.atlas_keys.resolve(batch.texture_hash());
3822                let whole = (start_rank..start_rank + count).all(|r| !is_pure(draw_order.get(r) as usize) && part_mask(r, mask) == PartMask::Plain);
3823
3824                if whole {
3825                    let info = BatchInfo { start_rank, count, texture_hash, blend_type: batch.blend_type(), kind, stencil: StencilTest::None, mask_seq: 0, alpha, tint };
3826                    build.scene.append_batch(build.renderer, frame, node_slot, &info);
3827                    continue;
3828                }
3829                // Polarity and the writers in scope vary per part → draw one at a time.
3830                for rank in start_rank..start_rank + count {
3831                    if is_pure(draw_order.get(rank) as usize) {
3832                        continue;
3833                    }
3834                    let seq = seq_of(rank);
3835                    let stencil = match part_mask(rank, mask) {
3836                        PartMask::Hidden => continue,
3837                        PartMask::Plain => StencilTest::None,
3838                        PartMask::Tested(test) => {
3839                            mask.sync(build, preps, seq);
3840                            test
3841                        }
3842                    };
3843                    let info = BatchInfo { start_rank: rank, count: 1, texture_hash, blend_type: batch.blend_type(), kind, stencil, mask_seq: seq.max(0) as u32, alpha, tint };
3844                    build.scene.append_batch(build.renderer, frame, node_slot, &info);
3845                }
3846            }
3847            DrawBatchKind::Instance => {
3848                for rank in start_rank..start_rank + count {
3849                    let part_idx = draw_order.get(rank) as usize;
3850                    let Some(child) = node.instances.get_mut(&part_idx) else { continue };
3851                    // Prepared only when visible; the prep is the draw's go-ahead.
3852                    let Some(child_index) = child.prep else { continue };
3853                    // Fold the instance part's own opacity into the chain the child
3854                    // draws with. SpriteStudio modulates a sub-animation by its
3855                    // instance part's effective alpha (SS6/SpriteStudio 7.6 `RateOpacity`, an
3856                    // unconditional multiply cascade); `part.alpha()` is that
3857                    // hierarchical value. Colour deliberately does not cross the
3858                    // boundary — no player propagates an instance part's tint.
3859                    let child_alpha = alpha * fd.parts().get(part_idx).alpha();
3860                    render_node(&mut child.node, child_index, preps, seqs, build, NodeDraw { alpha: child_alpha, tint }, mask);
3861                }
3862            }
3863            DrawBatchKind::Effect => {
3864                for rank in start_rank..start_rank + count {
3865                    let part_idx = draw_order.get(rank) as usize;
3866                    // Whatever `step_effects` produced for this part when the node
3867                    // was prepared; empty when the effect had nothing to draw.
3868                    let Some(plan) = node.effects.get(&part_idx).map(|e| e.plan.as_slice()).filter(|p| !p.is_empty()) else { continue };
3869                    // Each emitter meets the mask on its own flags and place, like
3870                    // any drawn part — it draws into its own slot anyway.
3871                    let seq = seq_of(rank);
3872                    let f = node.mask_flags.get(part_idx).copied().unwrap_or_default();
3873                    let eff_stencil = match mask.part(&f, ctx, seq) {
3874                        PartMask::Hidden => continue,
3875                        PartMask::Plain => StencilTest::None,
3876                        PartMask::Tested(test) => {
3877                            mask.sync(build, preps, seq);
3878                            test
3879                        }
3880                    };
3881                    let m: [f32; 16] = frame.world_matrices[part_idx * 16..part_idx * 16 + 16].try_into().unwrap();
3882                    // The effect draws from its own plan, so it needs its own
3883                    // arena slot rather than this node's.
3884                    let mut eff_slot = build.scene.push_child_transform(node_slot, &m);
3885                    // Under coverage the slot needs its own view of the bitmap too:
3886                    // the particles are in the effect part's local space, one
3887                    // placement below this node's. Without it the replay has no
3888                    // block to read, and the effect draws unclipped — unlike the
3889                    // stencil, which clips it by pipeline state alone.
3890                    if eff_stencil != StencilTest::None
3891                        && let Some((uv, layer)) = mask.coverage
3892                    {
3893                        build.scene.inherit_node_coverage(&mut eff_slot, &compose_uv(&uv, &mat4_mul(&prep.to_root, &m)), layer, &mask.writers);
3894                    }
3895                    // Same opacity fold as an instance part: the effect emitter's own
3896                    // alpha scales every particle it draws (the particles carry their
3897                    // own per-vertex alpha on top).
3898                    let eff_alpha = alpha * fd.parts().get(part_idx).alpha();
3899                    build.scene.append_effect(plan, &eff_slot, eff_stencil, seq.max(0) as u32, eff_alpha, tint, &node.atlas_keys);
3900                }
3901            }
3902            // Mask batches emit no colour (coverage is handled by the writers
3903            // above). Text / Nines: not yet handled.
3904            _ => {}
3905        }
3906    }
3907}
3908
3909/// Build a [`FrameView`] from the context's current (already-evaluated) SoA.
3910fn frame_view<'a>(ctx: &mut Context<'static>, frame_data: &'a [u8]) -> FrameView<'a> {
3911    FrameView {
3912        frame_data,
3913        world_matrices: unsafe { slice_f32(ctx.get_world_matrices_ptr(), ctx.get_world_matrices_len()) },
3914        local_vertices: unsafe { slice_f32(ctx.get_local_vertices_ptr(), ctx.get_local_vertices_len()) },
3915        local_uvs: unsafe { slice_f32(ctx.get_local_uvs_ptr(), ctx.get_local_uvs_len()) },
3916        mesh_vertices_x: unsafe { slice_f32(ctx.get_mesh_vertices_x_ptr(), ctx.get_mesh_vertices_x_len()) },
3917        mesh_vertices_y: unsafe { slice_f32(ctx.get_mesh_vertices_y_ptr(), ctx.get_mesh_vertices_y_len()) },
3918        mesh_vertex_offsets: unsafe { slice_u32(ctx.get_mesh_vertex_offsets_ptr(), ctx.get_mesh_vertex_offsets_len()) },
3919        mesh_uvs: unsafe { slice_f32(ctx.get_mesh_uvs_ptr(), ctx.get_mesh_uvs_len()) },
3920        mesh_indices: unsafe { slice_i32(ctx.get_mesh_indices_ptr(), ctx.get_mesh_indices_len()) },
3921        mesh_index_offsets: unsafe { slice_u32(ctx.get_mesh_index_offsets_ptr(), ctx.get_mesh_index_offsets_len()) },
3922        shape_vertices: unsafe { slice_f32(ctx.get_shape_vertices_ptr(), ctx.get_shape_vertices_len()) },
3923        shape_vertex_box_coords: unsafe { slice_f32(ctx.get_shape_vertex_box_coords_ptr(), ctx.get_shape_vertex_box_coords_len()) },
3924        shape_vertex_counts: unsafe { slice_i32(ctx.get_shape_vertex_counts_ptr(), ctx.get_shape_vertex_counts_len()) },
3925    }
3926}
3927
3928/// Build a slice from a runtime pointer/length, or empty if null/zero.
3929///
3930/// # Safety
3931/// `ptr` must be valid for `len` `f32`s and stay alive for `'a` (guaranteed
3932/// until the next `get_frame_data` call on the same context).
3933unsafe fn slice_f32<'a>(ptr: *const f32, len: usize) -> &'a [f32] {
3934    if ptr.is_null() || len == 0 { &[] } else { unsafe { std::slice::from_raw_parts(ptr, len) } }
3935}
3936
3937/// See [`slice_f32`]. `ptr` must be valid for `len` `u32`s.
3938unsafe fn slice_u32<'a>(ptr: *const u32, len: usize) -> &'a [u32] {
3939    if ptr.is_null() || len == 0 { &[] } else { unsafe { std::slice::from_raw_parts(ptr, len) } }
3940}
3941
3942/// See [`slice_f32`]. `ptr` must be valid for `len` `i32`s.
3943unsafe fn slice_i32<'a>(ptr: *const i32, len: usize) -> &'a [i32] {
3944    if ptr.is_null() || len == 0 { &[] } else { unsafe { std::slice::from_raw_parts(ptr, len) } }
3945}
3946
3947/// Whether the renderer's entry for `key` still has to be built from `encoded`.
3948///
3949/// Three answers, and the middle one is the whole point:
3950///
3951/// - **Nothing there** — build it.
3952/// - **Something there that a load put there, from different bytes** — build it.
3953///   Same path, same key, re-exported pixels: the viewer's convert / drop / look
3954///   / convert again round, which otherwise keeps showing the old atlas.
3955/// - **Something there from these same bytes, or something a host registered** —
3956///   leave it. The first is what keeps N players of one pack to one upload
3957///   between them; the second is not ours to overwrite.
3958fn wanted_now(renderer: &SSRenderer, key: u32, encoded: &[u8]) -> bool {
3959    if renderer.texture_size(key).is_none() {
3960        return true;
3961    }
3962    renderer.texture_digest(key).is_some_and(|held| held != fnv1a_bytes(encoded))
3963}
3964
3965/// Decode a flush's whole batch of atlases and register them **in `jobs` order**.
3966///
3967/// One call for the batch rather than one per image so the decodes can overlap: a
3968/// character with three 4096² atlases otherwise pays for them end to end on the
3969/// host's thread, which is the load stall this exists to avoid. The registration
3970/// order is still the caller's, not the order the decodes happened to finish in.
3971#[cfg(feature = "embedded")]
3972fn decode_and_register(renderer: &mut SSRenderer, device: &wgpu::Device, queue: &wgpu::Queue, jobs: &[(u32, &[u8], Retention)]) {
3973    let encoded: Vec<&[u8]> = jobs.iter().map(|(_, bytes, _)| *bytes).collect();
3974    // Premultiplied on the worker, so all that is left for this thread
3975    // is creating the texture and writing it.
3976    for (decoded, (hash, bytes, retention)) in crate::decode::decode_all(&encoded, true).into_iter().zip(jobs) {
3977        let Some(decoded) = decoded else {
3978            eprintln!("[ssplayer-wgpu] an image for {hash:#010x} could not be decoded");
3979            continue;
3980        };
3981        renderer.register_premultiplied(device, queue, *hash, decoded.rgba, (decoded.width, decoded.height), crate::renderer::Provenance { retention: *retention, digest: Some(fnv1a_bytes(bytes)) });
3982    }
3983}
3984
3985/// Without a decoder there is nothing to do here: on that build the host supplies
3986/// textures itself (the web face decodes with `createImageBitmap`).
3987#[cfg(not(feature = "embedded"))]
3988fn decode_and_register(_: &mut SSRenderer, _: &wgpu::Device, _: &wgpu::Queue, _: &[(u32, &[u8], Retention)]) {}