Skip to main content

roxlap_render/
lib.rs

1//! roxlap-render — unified CPU/GPU renderer facade.
2//!
3//! New to roxlap? **[The roxlap book](https://ncrashed.github.io/roxlap/)**
4//! is the guide (quickstart, concepts, rendering, lighting, sprites);
5//! this page is the API reference.
6//!
7//! One [`SceneRenderer`] hides the choice between the CPU opticast
8//! path (`roxlap-core` / `roxlap-scene`, presented via `softbuffer`)
9//! and the GPU compute-shader path (`roxlap-gpu`, presented via its
10//! own wgpu surface). Construction picks the GPU backend when asked
11//! and able, and **falls back to CPU automatically** when WGPU init
12//! fails — so a host never has to branch on GPU availability or carry
13//! the `Scene`→GPU upload/refresh/transform glue itself.
14//!
15//! Hosts stay thin: build a `Scene`, advance it from input, then call
16//! [`SceneRenderer::render`] each frame. The facade owns the window
17//! surface, the framebuffer/z-buffer (CPU) or the resident scene +
18//! dirty-chunk tracking (GPU), and presentation.
19//!
20//! The per-frame flow is `render` → *(optional overlays)* → finish.
21//! Between [`SceneRenderer::render`] and the finishing
22//! [`SceneRenderer::present`] / [`SceneRenderer::paint_egui`] call, a
23//! host may overlay depth-tested world-space lines with
24//! [`SceneRenderer::draw_lines`] (editor gizmos, debug geometry — see
25//! [`Line3`]); they land in the framebuffer, occluded by the rendered
26//! scene, with egui still painting panels on top.
27//!
28//! Beyond the scene render itself, the facade owns sprites (static +
29//! per-instance dynamic), animated voxel clips, billboard sprites +
30//! actors, characters (`.rkc`), materials + transparency, dynamic
31//! lighting ([`FrameParams::lights`]), screen→world picking, overlay
32//! lines / images / egui, and the fixed-resolution post pipeline
33//! ([`SceneRenderer::set_render_resolution`] / `set_ssaa` /
34//! `set_posterize`).
35
36#![forbid(unsafe_code)]
37// Compile the workspace README's Rust snippets as doctests so the
38// "Use it in your game" example can never rot the way the pre-QE.0
39// Multicore snippet did (it kept calling API deleted releases earlier).
40// `cfg(doctest)` keeps the README out of the rendered crate docs.
41#[cfg(doctest)]
42#[doc = include_str!("../../../README.md")]
43struct ReadmeDoctests;
44
45mod cpu;
46/// WebGL2 framebuffer presenter for the CPU backend on wasm (the
47/// browser has no `softbuffer`).
48#[cfg(target_arch = "wasm32")]
49mod cpu_blit;
50#[cfg(feature = "hud")]
51mod cpu_egui;
52/// QE-C6 — the one place `ROXLAP_*` env overrides are read (once, at
53/// construction). The user-facing variable table is on
54/// [`RenderOptions`].
55/// Falling voxel islands over dynamic sprite instances (stage DT) —
56/// see `docs/porting/PORTING-DESTRUCTION.md`.
57mod debris;
58mod env_config;
59mod gpu;
60/// Dynamic lighting types (stages DL + SL) — runtime sun, point and
61/// spot lights, on both backends.
62mod light;
63/// Particle system over dynamic sprite instances (stage PS) — see
64/// `docs/porting/PORTING-PARTICLES.md`.
65mod particles;
66
67#[cfg(not(target_arch = "wasm32"))]
68use std::sync::Arc;
69
70use roxlap_core::kfa_draw::{compose_attachment, solve_kfa_limbs};
71use roxlap_core::opticast::OpticastSettings;
72use roxlap_core::sky::Sky;
73use roxlap_core::Camera;
74use roxlap_formats::material::MaterialTable;
75use roxlap_formats::voxel_clip::{duration_prefix_sums, frame_at_prefix};
76use roxlap_scene::Scene;
77
78pub use debris::{DebrisImpact, DebrisSystem};
79pub use light::{DirectionalLight, LightRig, PointLight, SpotLight};
80pub use particles::{
81    CollisionMode, ConeDef, EmitterId, EmitterShape, Particle, ParticleEmitterDef, ParticleSystem,
82    SpawnMode, VelocityDef, CARVE_DEBRIS_CAP, DEFAULT_MAX_PARTICLES,
83};
84pub use roxlap_formats::character::{Attachment, Character, MeshRef};
85pub use roxlap_formats::color::{OverlayColor, Rgb, VoxColor};
86/// Animated-GIF → [`VoxelClip`] importer for Doom-style billboard sprites
87/// (stage BB). Behind the `gif` feature; see `PORTING-BILLBOARD.md`.
88#[cfg(feature = "gif")]
89pub use roxlap_formats::gif_import;
90pub use roxlap_formats::kfa::KfaSprite;
91pub use roxlap_formats::kv6::Kv6;
92pub use roxlap_formats::material::{BlendMode, Material};
93/// PNG-sequence / APNG → [`VoxelClip`] importer (stage BB). Behind the `png`
94/// feature; see `PORTING-BILLBOARD.md`.
95#[cfg(feature = "png")]
96pub use roxlap_formats::png_import;
97pub use roxlap_formats::sprite::Sprite;
98pub use roxlap_formats::voxel_clip::{
99    DecodeError, DecodedClip, LoopMode, StreamingClip, VoxelClip, VoxelFrame,
100};
101pub use roxlap_gpu::{GpuInitError, GpuRendererSettings, PowerPreference};
102// Re-exported so hosts can name the [`SceneRenderer::new`] bounds
103// without adding a direct `raw-window-handle` dependency of their own.
104pub use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
105// Re-exported so hosts feed [`SceneRenderer::paint_egui`] from the exact
106// egui version the renderer was built against (`hud` feature).
107#[cfg(feature = "hud")]
108pub use egui;
109
110use crate::cpu::CpuBackend;
111use crate::gpu::GpuBackend;
112
113/// Type-erased display handle stored by the CPU backend's softbuffer
114/// surface. `raw-window-handle` implements `HasDisplayHandle` for
115/// `Arc<H>` (`H: ?Sized`), and the bare trait object implements its
116/// own object-safe trait — so `Arc<W>` coerces to `Arc<DynDisplay>`
117/// for any provider `W`.
118#[cfg(not(target_arch = "wasm32"))]
119pub(crate) type DynDisplay = dyn HasDisplayHandle + Send + Sync + 'static;
120/// Type-erased window handle counterpart to [`DynDisplay`].
121#[cfg(not(target_arch = "wasm32"))]
122pub(crate) type DynWindow = dyn HasWindowHandle + Send + Sync + 'static;
123
124/// One placed sprite instance: which [`SpriteSet::models`] entry and
125/// where in the world.
126pub struct SpriteInstanceDesc {
127    /// Positional index into [`SpriteSet::models`].
128    pub model: usize,
129    /// World position of the model's anchor (voxel units).
130    pub pos: [f32; 3],
131}
132
133/// Stable handle to a registered sprite model, returned (one per
134/// [`SpriteSet::models`] entry, in order) by
135/// [`SceneRenderer::set_sprites`]. Pass it to
136/// [`refresh_sprite_model`](SceneRenderer::refresh_sprite_model) to
137/// re-register that model's geometry after a content edit — so callers
138/// never track the positional `usize` index themselves. Opaque on
139/// purpose: there is no arithmetic to do on it.
140///
141/// Also returned by [`SceneRenderer::add_sprite_model`] for an
142/// incrementally registered model, and accepted by
143/// [`remove_sprite_model`](SceneRenderer::remove_sprite_model). A handle
144/// to a removed model is **stale**: it resolves to nothing, so passing
145/// it anywhere is a safe no-op. The `gen` (generation) field guards a
146/// future compacting registry; it stays `0` today because model slots
147/// are tombstoned in place and never reused (GPU chain ids are
148/// append-only).
149#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
150pub struct SpriteModelId {
151    pub(crate) slot: u32,
152    pub(crate) gen: u32,
153}
154
155/// Stable handle to a **dynamically added** sprite instance — the result
156/// of [`SceneRenderer::add_sprite_instance`], passed to
157/// [`remove_sprite_instance`](SceneRenderer::remove_sprite_instance).
158///
159/// Backends remove instances by swap (O(1)), which moves another instance
160/// into the freed slot; this handle survives that because the facade keeps
161/// the id↔slot mapping up to date. The generation guards against a stale
162/// handle aliasing a recycled slot.
163#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
164pub struct SpriteInstanceId {
165    slot: u32,
166    gen: u32,
167}
168
169/// Facade-side slotmap that turns the backends' swap-remove indexing into
170/// stable [`SpriteInstanceId`] handles. Both backends keep their dynamic
171/// instances as a tail sublist indexed `0..n`; `order[dyn_index]` is the
172/// owning slot, and a removal fixes up the one slot whose instance was
173/// swapped into the hole.
174#[derive(Default)]
175struct DynInstanceMap {
176    /// Per slot: `(generation, Some(dyn_index) while live)`.
177    slots: Vec<(u32, Option<u32>)>,
178    /// Per live `dyn_index`: the owning slot. Parallel to the backends'
179    /// dynamic sublist (so `order.len()` == the dynamic instance count).
180    order: Vec<u32>,
181    free: Vec<u32>,
182}
183
184impl DynInstanceMap {
185    /// Register a freshly appended instance (always at `dyn_index ==
186    /// order.len()`); returns its stable handle.
187    fn alloc(&mut self, dyn_index: u32) -> SpriteInstanceId {
188        debug_assert_eq!(self.order.len() as u32, dyn_index);
189        let slot = self.free.pop().unwrap_or_else(|| {
190            self.slots.push((0, None));
191            (self.slots.len() - 1) as u32
192        });
193        let gen = self.slots[slot as usize].0;
194        self.slots[slot as usize].1 = Some(dyn_index);
195        self.order.push(slot);
196        SpriteInstanceId { slot, gen }
197    }
198
199    /// Resolve a handle to its current backend `dyn_index`, or `None` if
200    /// it's stale / already removed.
201    fn dyn_index(&self, id: SpriteInstanceId) -> Option<u32> {
202        let (gen, idx) = *self.slots.get(id.slot as usize)?;
203        (gen == id.gen).then_some(idx).flatten()
204    }
205
206    /// Apply a removal: the backend swap-removed `removed` and reported
207    /// `moved` (the old-last `dyn_index` that slid into `removed`, or
208    /// `None` if `removed` was itself the last).
209    fn remove(&mut self, id: SpriteInstanceId, removed: u32, moved: Option<u32>) {
210        self.slots[id.slot as usize].1 = None;
211        self.slots[id.slot as usize].0 += 1; // bump generation
212        self.free.push(id.slot);
213        if let Some(last) = moved {
214            let moved_slot = self.order[last as usize];
215            self.slots[moved_slot as usize].1 = Some(removed);
216            self.order[removed as usize] = moved_slot;
217        }
218        self.order.pop();
219    }
220}
221
222/// Crate-internal contract of every epoch-slotmap handle type
223/// ([`SpriteModelId`], [`VoxelClipId`], [`CharacterId`],
224/// [`StreamingClipId`], [`BillboardActorId`]): mint from / split into
225/// the `(slot, generation)` pair. Lets one generic [`EpochSlotMap`]
226/// serve all five families while each keeps its own distinct handle
227/// type (so a `CharacterId` can never be passed where a `VoxelClipId`
228/// is expected).
229trait SlotHandle: Copy {
230    fn mint(slot: u32, gen: u32) -> Self;
231    fn parts(self) -> (u32, u32);
232}
233
234macro_rules! impl_slot_handle {
235    ($($t:ty),+ $(,)?) => {$(
236        impl SlotHandle for $t {
237            fn mint(slot: u32, gen: u32) -> Self {
238                Self { slot, gen }
239            }
240            fn parts(self) -> (u32, u32) {
241                (self.slot, self.gen)
242            }
243        }
244    )+};
245}
246
247impl_slot_handle!(
248    SpriteModelId,
249    VoxelClipId,
250    CharacterId,
251    StreamingClipId,
252    BillboardActorId,
253);
254
255/// Facade-side epoch slotmap (QE.1a — one generic replacing five
256/// hand-rolled copies). Unlike [`DynInstanceMap`] there is **no**
257/// swap-remove fixup: a slot maps 1:1 to the backends' positional
258/// index, which is append-only and never reused. A removed entry
259/// tombstones its slot *in place* (the backend frees the data but
260/// keeps the index), so a stale handle resolves to `None` → a safe
261/// no-op rather than aliasing another entry.
262///
263/// [`reset`](Self::reset) clears the slots **and bumps `epoch`**,
264/// which is baked into each minted id's generation. A handle from
265/// before a [`SceneRenderer::set_sprites`] therefore carries the old
266/// epoch and resolves to `None` rather than silently aliasing the
267/// entry that re-took its slot. ([`reset_live`](Self::reset_live) is
268/// the model map's deliberate exception.)
269struct EpochSlotMap<I> {
270    /// Per slot (== backend positional index): `(epoch_at_alloc, live)`.
271    slots: Vec<(u32, bool)>,
272    epoch: u32,
273    _handle: std::marker::PhantomData<I>,
274}
275
276impl<I> Default for EpochSlotMap<I> {
277    fn default() -> Self {
278        Self {
279            slots: Vec::new(),
280            epoch: 0,
281            _handle: std::marker::PhantomData,
282        }
283    }
284}
285
286impl<I: SlotHandle> EpochSlotMap<I> {
287    /// Register a freshly appended entry at positional `index` (always
288    /// the current `slots.len()`); returns its stable handle.
289    fn alloc(&mut self, index: u32) -> I {
290        debug_assert_eq!(self.slots.len() as u32, index);
291        self.slots.push((self.epoch, true));
292        I::mint(index, self.epoch)
293    }
294
295    /// The handle a live slot at `index` resolves from — used by
296    /// [`SceneRenderer::set_sprites`] to hand back ids for the `0..n`
297    /// entries seeded by [`reset_live`](Self::reset_live).
298    fn minted(&self, index: u32) -> I {
299        I::mint(index, self.epoch)
300    }
301
302    /// Resolve a handle to its backend positional index, or `None` if
303    /// it's stale / already removed.
304    fn index(&self, id: I) -> Option<usize> {
305        let (slot, gen) = id.parts();
306        let (epoch, live) = *self.slots.get(slot as usize)?;
307        (epoch == gen && live).then_some(slot as usize)
308    }
309
310    /// Tombstone a slot in place. Returns `false` if the handle is
311    /// stale / already removed.
312    fn remove(&mut self, id: I) -> bool {
313        let (slot, gen) = id.parts();
314        let Some(entry) = self.slots.get_mut(slot as usize) else {
315            return false;
316        };
317        if entry.0 != gen || !entry.1 {
318            return false;
319        }
320        entry.1 = false;
321        true
322    }
323
324    /// Drop every entry and invalidate every outstanding handle (the
325    /// epoch bump).
326    fn reset(&mut self) {
327        self.slots.clear();
328        self.epoch = self.epoch.wrapping_add(1);
329    }
330
331    /// Positional indices of every live entry, ascending — the
332    /// iteration [`SceneRenderer::tick`] drives collection updates
333    /// from.
334    fn live_indices(&self) -> impl Iterator<Item = usize> + '_ {
335        self.slots
336            .iter()
337            .enumerate()
338            .filter_map(|(i, &(_, live))| live.then_some(i))
339    }
340
341    /// Re-seat `n` live entries with positional ids `0..n` **without**
342    /// bumping the epoch — [`SceneRenderer::set_sprites`]' model-map
343    /// semantics, where model index = chain id on both backends and a
344    /// pre-rebuild positional id deliberately keeps meaning "model
345    /// `i` of the current set".
346    fn reset_live(&mut self, n: usize) {
347        self.slots.clear();
348        self.slots.resize(n, (self.epoch, true));
349    }
350}
351
352/// Stable handle to a registered animated voxel clip (VCL.4) — the
353/// result of [`SceneRenderer::add_voxel_clip`], passed to
354/// [`add_clip_instance_posed`](SceneRenderer::add_clip_instance_posed)
355/// and [`remove_voxel_clip`](SceneRenderer::remove_voxel_clip). Like
356/// [`SpriteModelId`], a removed clip's handle is stale → a safe no-op.
357/// Reset by [`set_sprites`](SceneRenderer::set_sprites) (which drops the
358/// dynamic + clip layers).
359#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
360pub struct VoxelClipId {
361    slot: u32,
362    gen: u32,
363}
364
365/// Stable handle to a registered animated character (VCL.6) — the result
366/// of [`SceneRenderer::add_character`], advanced each frame with
367/// [`advance_character`](SceneRenderer::advance_character) and dropped with
368/// [`remove_character`](SceneRenderer::remove_character). Reset by
369/// [`set_sprites`](SceneRenderer::set_sprites).
370#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
371pub struct CharacterId {
372    slot: u32,
373    gen: u32,
374}
375
376/// Stable handle to a registered **streaming** voxel clip (follow-up #3) —
377/// the result of [`SceneRenderer::add_streaming_clip`], advanced with
378/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame) and
379/// dropped with
380/// [`remove_streaming_clip`](SceneRenderer::remove_streaming_clip). Reset by
381/// [`set_sprites`](SceneRenderer::set_sprites).
382#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
383pub struct StreamingClipId {
384    slot: u32,
385    gen: u32,
386}
387
388/// Handle to an instance of a streaming clip
389/// ([`add_streaming_clip_instance`](SceneRenderer::add_streaming_clip_instance)).
390///
391/// Deliberately **distinct** from [`SpriteInstanceId`]: a streaming clip's
392/// frame is per-*clip* (all its instances share one re-uploaded model,
393/// advanced by
394/// [`set_streaming_clip_frame`](SceneRenderer::set_streaming_clip_frame)), so
395/// a streaming instance is *not* accepted by the per-instance
396/// [`set_clip_instance_frame`](SceneRenderer::set_clip_instance_frame) —
397/// trying to scrub two instances of one streaming clip independently is a
398/// compile error, not a silent coupling. (Use a flipbook clip for
399/// per-instance frames.) Move it with
400/// [`set_streaming_instance_transform`](SceneRenderer::set_streaming_instance_transform)
401/// and drop it with
402/// [`remove_streaming_instance`](SceneRenderer::remove_streaming_instance).
403#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
404pub struct StreamingInstanceId(SpriteInstanceId);
405
406/// One registered streaming clip: the seekable cursor + the single sprite
407/// model it re-uploads each frame, plus the dims/pivot used to rebuild it.
408struct StreamingClipState {
409    cursor: StreamingClip,
410    model: SpriteModelId,
411    dims: [u32; 3],
412    pivot: [f32; 3],
413    /// Colour→material map (TV.3), empty for an all-opaque streaming clip.
414    /// Re-applied on every per-frame re-upload so the streamed model keeps
415    /// its per-voxel materials as it advances.
416    material_map: Vec<(Rgb, u8)>,
417    /// PF.5 — the clip frame currently resident on `model`. A player driven
418    /// at render rate re-applies the same clip frame most ticks (10 fps clip
419    /// on a 144 fps render = 14×); when it matches, the dense `to_kv6`
420    /// rebuild + LOD chain + GPU re-upload are skipped entirely.
421    last_applied: Option<usize>,
422}
423
424/// Per-clip-attachment playback clock (VCL.6): the timing it needs to
425/// resolve a frame, plus its own accumulating clock.
426struct ClipClock {
427    /// PF.13 (S4) — inclusive duration prefix sums (ms), built once per
428    /// timeline via [`duration_prefix_sums`] so every tick resolves its
429    /// frame by binary search instead of re-summing the duration list.
430    prefix: Vec<u64>,
431    loop_mode: LoopMode,
432    /// Playback rate, Q8 (256 = 1×).
433    speed_q8: i32,
434    /// Accumulated playback time (ms), seeded from the attachment's
435    /// `start_phase_ms`.
436    clock_ms: f64,
437}
438
439impl ClipClock {
440    /// Build a clock over `durations` starting at `clock_ms`.
441    fn new(durations: &[u32], loop_mode: LoopMode, speed_q8: i32, clock_ms: f64) -> Self {
442        Self {
443            prefix: duration_prefix_sums(durations),
444            loop_mode,
445            speed_q8,
446            clock_ms,
447        }
448    }
449
450    /// Frame shown at `elapsed_ms` on this clock's timeline —
451    /// [`frame_at`](roxlap_formats::voxel_clip::frame_at) over the
452    /// cached prefix sums.
453    fn frame_for(&self, elapsed_ms: u32) -> u32 {
454        frame_at_prefix(&self.prefix, self.loop_mode, elapsed_ms) as u32
455    }
456
457    /// Advance the clock by `dt` seconds at its Q8 `speed` and return the
458    /// frame to show. Shared by character attachments and standalone clip
459    /// players. A negative clock (rewind past 0) reads as frame 0 but is
460    /// kept signed so resuming forward is continuous.
461    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
462    fn tick(&mut self, dt: f64) -> u32 {
463        self.clock_ms += dt * 1000.0 * f64::from(self.speed_q8) / 256.0;
464        self.frame_for(self.clock_ms.max(0.0) as u32)
465    }
466
467    /// Retarget this clock to a different clip's timeline (BB.1): swap the
468    /// per-frame `durations` + `loop_mode` and restart at `0`, **preserving
469    /// the playback rate** (`speed_q8`). Used by
470    /// [`SceneRenderer::set_clip_instance_clip`] so swapping a billboard's
471    /// animation keeps its speed / pause policy.
472    fn retarget(&mut self, durations: &[u32], loop_mode: LoopMode) {
473        self.prefix = duration_prefix_sums(durations);
474        self.loop_mode = loop_mode;
475        self.clock_ms = 0.0;
476    }
477}
478
479/// Facade-side metadata captured for a registered flipbook clip, so editor
480/// queries + the auto-player don't shadow the `DecodedClip`.
481struct ClipMeta {
482    dims: [u32; 3],
483    pivot: [f32; 3],
484    voxel_world_size: f32,
485    durations: Vec<u32>,
486    loop_mode: LoopMode,
487    /// Colour→material map the clip was registered with (TV.3), empty for an
488    /// all-opaque clip. Retained so an in-place
489    /// [`update_clip_frame`](SceneRenderer::update_clip_frame) re-classifies
490    /// the edited frame's voxels instead of dropping its per-voxel materials.
491    material_map: Vec<(Rgb, u8)>,
492}
493
494/// Public metadata for a registered clip — the inspector view returned by
495/// [`SceneRenderer::clip_metadata`].
496#[derive(Clone, Debug, PartialEq)]
497pub struct ClipMetadata {
498    /// Fixed bounding box (voxels).
499    pub dims: [u32; 3],
500    /// Model pivot (the kv6 pivot frames share).
501    pub pivot: [f32; 3],
502    /// Render scale (1 voxel = this many world units).
503    pub voxel_world_size: f32,
504    /// Playback wrap behaviour.
505    pub loop_mode: LoopMode,
506    /// Number of frames.
507    pub frame_count: usize,
508    /// Per-frame durations (ms), one per frame.
509    pub durations: Vec<u32>,
510    /// Total loop length (ms) — sum of `durations`.
511    pub total_ms: u32,
512}
513
514/// What an auto-advancing [`ClipPlayer`] (#6) drives each
515/// [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips). A flipbook
516/// clip's frame is per-instance; a streaming clip's is per-clip (its
517/// instances share one model), so the targets differ.
518#[derive(Clone, Copy)]
519enum PlayerTarget {
520    Flipbook(SpriteInstanceId),
521    Streaming(StreamingClipId),
522}
523
524/// A standalone clip given its own playback clock (#6): the host calls
525/// `advance_voxel_clips(dt)` once instead of hand-driving `frame_at` +
526/// `set_clip_instance_frame`.
527struct ClipPlayer {
528    target: PlayerTarget,
529    clock: ClipClock,
530    /// When `true`, [`advance_voxel_clips`](SceneRenderer::advance_voxel_clips)
531    /// leaves the clock (and frame) untouched — the editor's play/pause.
532    paused: bool,
533}
534
535/// One live bone attachment: which bone drives it, its local offset, the
536/// renderer instance it owns, and (for a clip target) its playback clock.
537struct AttachInst {
538    bone: usize,
539    local_offset: roxlap_formats::xform::BoneXform,
540    inst: SpriteInstanceId,
541    clip: Option<ClipClock>,
542}
543
544/// A live animated character: the hinge skeleton (the bone-transform
545/// solver) + one [`AttachInst`] per bone attachment.
546struct CharInstance {
547    skeleton: KfaSprite,
548    attaches: Vec<AttachInst>,
549    /// Sprite models + voxel clips this character registered, so
550    /// [`remove_character`](SceneRenderer::remove_character) can free them
551    /// (otherwise they leak until the next `set_sprites`).
552    models: Vec<SpriteModelId>,
553    clips: Vec<VoxelClipId>,
554}
555
556/// Orientation + position for a dynamic sprite instance — the per-frame
557/// pose passed to [`SceneRenderer::add_sprite_instance_posed`] and
558/// [`set_sprite_instance_transform`](SceneRenderer::set_sprite_instance_transform).
559///
560/// `right`/`up`/`forward` are the instance's local axes expressed in
561/// world space (the columns of the model→world rotation), mapping
562/// directly onto the underlying [`Sprite`]'s `s`/`h`/`f` (kv6 local
563/// +x/+y/+z). They **must** be non-singular (`det ≠ 0`) but need not be
564/// orthonormal — a uniform/non-uniform scale or shear is fine. A
565/// near-singular basis falls through the renderer's degenerate-basis
566/// guards and the instance silently skips that frame rather than
567/// panicking. [`Default`] is the identity basis (axis-aligned).
568#[derive(Clone, Copy, Debug)]
569pub struct DynSpriteTransform {
570    /// Instance world position (the kv6 pivot maps here).
571    pub pos: [f32; 3],
572    /// Local +x in world space ↦ [`Sprite::s`].
573    pub right: [f32; 3],
574    /// Local +y in world space ↦ [`Sprite::h`].
575    pub up: [f32; 3],
576    /// Local +z in world space ↦ [`Sprite::f`].
577    pub forward: [f32; 3],
578}
579
580impl Default for DynSpriteTransform {
581    fn default() -> Self {
582        Self {
583            pos: [0.0, 0.0, 0.0],
584            right: [1.0, 0.0, 0.0],
585            up: [0.0, 1.0, 0.0],
586            forward: [0.0, 0.0, 1.0],
587        }
588    }
589}
590
591impl DynSpriteTransform {
592    /// Stamp this pose onto a [`Sprite`] in place: `pos → p`,
593    /// `right/up/forward → s/h/f` (a direct copy — the basis is the
594    /// model→world columns). Both backends keep the rest of the template
595    /// (`kv6`, `flags`) and only overwrite the pose.
596    pub(crate) fn apply_to(self, s: &mut Sprite) {
597        s.p = self.pos;
598        s.s = self.right;
599        s.h = self.up;
600        s.f = self.forward;
601    }
602}
603
604/// How a billboard instance turns to face the camera (BB.2). Set per
605/// instance via [`SceneRenderer::add_billboard_instance`] /
606/// [`set_billboard_mode`](SceneRenderer::set_billboard_mode); applied each
607/// [`face_billboards_to`](SceneRenderer::face_billboards_to).
608#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
609pub enum BillboardMode {
610    /// Not auto-oriented — the host drives its transform directly. Default
611    /// (so a billboard record with no mode is inert).
612    #[default]
613    None,
614    /// Yaw-only: the slab stays vertical (image up = world up) and rotates
615    /// about the vertical axis to face the camera. The Doom/Build default —
616    /// its cast shadow stays sane (a vertical card) as the camera orbits.
617    Cylindrical,
618    /// Full face: the slab is always perpendicular to the camera direction
619    /// (pitches with the view). Ideal head-on, but its cast shadow rotates
620    /// as you orbit.
621    Spherical,
622}
623
624/// How a sprite/billboard instance derives its **shading normal** (BB.2b) —
625/// a per-instance choice that rides the sprite `flags`. A camera-facing
626/// billboard's DDA face normal tracks the camera, so its `N·L` would shift as
627/// you orbit; `WorldUp` / `AmbientOnly` tame that. Only affects the dynamic
628/// lighting path (a disabled rig is unaffected). Set via
629/// [`set_sprite_instance_lighting`](SceneRenderer::set_sprite_instance_lighting)
630/// or [`BillboardActorDef::lighting`].
631#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
632pub enum BillboardLighting {
633    /// The DDA hit-face normal — today's DL.7 look (default).
634    #[default]
635    FaceNormal,
636    /// A fixed world-up normal: stable directional shading regardless of the
637    /// camera angle.
638    WorldUp,
639    /// Ambient only — no sun / point-light direct term, the flattest,
640    /// most Doom-faithful cutout look (still scaled by the scene's ambient
641    /// level, so it dims in a dim scene).
642    AmbientOnly,
643    /// Full-bright / **emissive** — the voxel colour at full intensity,
644    /// ignoring all lighting. The right look for glows (fire, spell auras,
645    /// muzzle flashes) and markers that shouldn't darken in shadow.
646    FullBright,
647}
648
649/// One camera-facing billboard instance (BB.2): the clip/sprite instance it
650/// drives, its world position, and how it orients.
651struct BillboardRec {
652    id: SpriteInstanceId,
653    pos: [f32; 3],
654    mode: BillboardMode,
655}
656
657/// roxlap world up — voxlap is z-down, so up is `-z` (matches the
658/// scene-demo camera builder + the lighting bake's z convention). Billboard
659/// orientation assumes this; an app with a different up convention would
660/// need this generalised (not exposed yet — YAGNI).
661const BILLBOARD_UP: [f32; 3] = [0.0, 0.0, -1.0];
662
663fn bb_norm(v: [f32; 3]) -> Option<[f32; 3]> {
664    let m = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
665    (m > 1e-6).then(|| [v[0] / m, v[1] / m, v[2] / m])
666}
667
668fn bb_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
669    [
670        a[1] * b[2] - a[2] * b[1],
671        a[2] * b[0] - a[0] * b[2],
672        a[0] * b[1] - a[1] * b[0],
673    ]
674}
675
676/// The camera-facing basis for a billboard at `pos` (the slab's local axes:
677/// `+x` = image horizontal, `+y` = normal toward the camera, `+z` = image
678/// vertical). Returns `None` for [`BillboardMode::None`] or a degenerate
679/// pose (camera on the sprite's vertical axis for cylindrical; looking
680/// straight along world-up for spherical) — the caller then skips it.
681fn billboard_transform(
682    pos: [f32; 3],
683    cam: [f64; 3],
684    mode: BillboardMode,
685) -> Option<DynSpriteTransform> {
686    #[allow(clippy::cast_possible_truncation)]
687    let to_cam = [
688        cam[0] as f32 - pos[0],
689        cam[1] as f32 - pos[1],
690        cam[2] as f32 - pos[2],
691    ];
692    // `+y` = slab normal toward the camera (horizontal-only for
693    // cylindrical). Degenerate view axes (camera exactly overhead /
694    // exactly at the pos — e.g. a third-person camera the instant
695    // before its boom applies) fall back to a fixed facing instead
696    // of returning None: the card is edge-on/invisible right then
697    // anyway, but the POSITION update must never be dropped, or the
698    // actor freezes at its last pose (the CC.4 third-person bug).
699    const FALLBACK: [f32; 3] = [0.0, 1.0, 0.0];
700    let ny = match mode {
701        BillboardMode::Cylindrical => bb_norm([to_cam[0], to_cam[1], 0.0]).unwrap_or(FALLBACK),
702        BillboardMode::Spherical => bb_norm(to_cam).unwrap_or(FALLBACK),
703        BillboardMode::None => return None,
704    };
705    // `+x` = image horizontal = screen-right (non-mirrored): up × normal.
706    let nx = bb_norm(bb_cross(BILLBOARD_UP, ny)).unwrap_or([1.0, 0.0, 0.0]);
707    // `+z` = image vertical (≈ world up; exactly world up for cylindrical).
708    let nz = bb_cross(ny, nx);
709    Some(DynSpriteTransform {
710        pos,
711        right: nx,
712        up: ny,
713        forward: nz,
714    })
715}
716
717/// Apply shadow cast/receive booleans to a sprite `flags` word in place
718/// (XS.4 bits 4/5), preserving the other bits. Shared by both backends'
719/// per-instance shadow-flag setters (BB.3).
720pub(crate) fn apply_shadow_flags(flags: &mut u32, casts: bool, receives: bool) {
721    use roxlap_formats::sprite::{SPRITE_FLAG_NO_SHADOW_CAST, SPRITE_FLAG_NO_SHADOW_RECEIVE};
722    if casts {
723        *flags &= !SPRITE_FLAG_NO_SHADOW_CAST;
724    } else {
725        *flags |= SPRITE_FLAG_NO_SHADOW_CAST;
726    }
727    if receives {
728        *flags &= !SPRITE_FLAG_NO_SHADOW_RECEIVE;
729    } else {
730        *flags |= SPRITE_FLAG_NO_SHADOW_RECEIVE;
731    }
732}
733
734/// Apply a [`BillboardLighting`] mode to a sprite `flags` word in place
735/// (BB.2b bits 6/7), preserving the other bits. Shared by both backends'
736/// per-instance lighting setters.
737pub(crate) fn apply_lighting_flags(flags: &mut u32, mode: BillboardLighting) {
738    use roxlap_formats::sprite::{SPRITE_FLAG_LIGHT_AMBIENT_ONLY, SPRITE_FLAG_LIGHT_WORLD_UP};
739    *flags &= !(SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY);
740    match mode {
741        BillboardLighting::FaceNormal => {}
742        BillboardLighting::WorldUp => *flags |= SPRITE_FLAG_LIGHT_WORLD_UP,
743        BillboardLighting::AmbientOnly => *flags |= SPRITE_FLAG_LIGHT_AMBIENT_ONLY,
744        // Full-bright is encoded as both bits set (the decoders check it first).
745        BillboardLighting::FullBright => {
746            *flags |= SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY;
747        }
748    }
749}
750
751// ---- billboard actors (BB.4) --------------------------------------------
752
753/// Stable handle to a [`BillboardActor`](SceneRenderer::add_billboard_actor)
754/// — a high-level directional billboard managed by the renderer (it owns one
755/// clip instance, picks the directional clip by view angle, and plays a
756/// named-state animation). Reset by [`set_sprites`](SceneRenderer::set_sprites);
757/// a removed actor's handle is stale → a safe no-op.
758#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
759pub struct BillboardActorId {
760    slot: u32,
761    gen: u32,
762}
763
764/// One animation state of a [`BillboardActorDef`]: its name plus the clips
765/// for each viewing direction. `dirs.len()` may be `1` (non-directional),
766/// `8` (classic Doom rotations), or any `N` (uniform angular bins). Index 0
767/// is the view-from-front (camera in the actor's facing direction),
768/// increasing counter-clockwise.
769pub struct ActorState {
770    /// State name [`SceneRenderer::set_actor_state`] selects by
771    /// (e.g. `"walk"`, `"attack"`). Owned since QE.7b, so actor
772    /// definitions can come from data files (monster definitions
773    /// loaded at runtime) without `Box::leak`.
774    pub name: String,
775    /// One clip per view direction, counter-clockwise from "facing the
776    /// viewer" — 1 (billboard), 4, or 8 entries.
777    pub dirs: Vec<VoxelClipId>,
778}
779
780/// How a sprite instance participates in dynamic-light shadows
781/// (QE.7b — replaces the unreadable
782/// `set_sprite_instance_shadow_flags(id, true, false)` bool pair).
783#[derive(Clone, Copy, PartialEq, Eq, Debug)]
784pub struct ShadowFlags {
785    /// The instance's voxels block dynamic-light shadow rays.
786    pub casts: bool,
787    /// Terrain / other-caster shadows darken the instance's voxels.
788    pub receives: bool,
789}
790
791impl Default for ShadowFlags {
792    /// Both on — the participating default every spawn starts with.
793    fn default() -> Self {
794        Self {
795            casts: true,
796            receives: true,
797        }
798    }
799}
800
801/// Recipe for [`add_billboard_actor`](SceneRenderer::add_billboard_actor).
802pub struct BillboardActorDef {
803    /// Animation states (≥1, each with ≥1 directional clip). The first is
804    /// the initial state.
805    pub states: Vec<ActorState>,
806    /// How the slab turns to face the camera (default [`BillboardMode::Cylindrical`]).
807    pub mode: BillboardMode,
808    /// Shading-normal mode (BB.2b; default [`BillboardLighting::FaceNormal`]).
809    pub lighting: BillboardLighting,
810    /// Playback rate of the state animation (`1.0` = authored speed,
811    /// negative = reverse). QE.7b — was Q8 fixed point (`speed_q8:
812    /// 256`); migrate with `speed = speed_q8 as f32 / 256.0`.
813    pub speed: f32,
814    /// World units per slab voxel (`1.0` = classic 1:1). Applied to
815    /// the instance basis every tick. Composes multiplicatively with
816    /// the clip's own `voxel_world_size` (both backends honour both).
817    pub scale: f32,
818    /// Shadow participation for the actor's voxels.
819    pub shadows: ShadowFlags,
820}
821
822impl Default for BillboardActorDef {
823    fn default() -> Self {
824        Self {
825            states: Vec::new(),
826            mode: BillboardMode::Cylindrical,
827            lighting: BillboardLighting::FaceNormal,
828            speed: 1.0,
829            scale: 1.0,
830            shadows: ShadowFlags::default(),
831        }
832    }
833}
834
835/// QE.7b — the public API speaks `f32` speed (`1.0` = authored rate);
836/// the clip clocks keep their Q8 fixed-point internals.
837#[allow(clippy::cast_possible_truncation)]
838fn speed_to_q8(speed: f32) -> i32 {
839    (speed * 256.0).round() as i32
840}
841
842/// A live directional billboard: one clip instance whose directional clip is
843/// reselected by view angle and whose animation plays a named state.
844struct BillboardActor {
845    /// World units per slab voxel (from the def).
846    scale: f32,
847    inst: SpriteInstanceId,
848    states: Vec<ActorState>,
849    cur_state: usize,
850    pos: [f32; 3],
851    /// World yaw the actor "faces" (radians); the dir picker compares the
852    /// camera's bearing against it.
853    facing_yaw: f64,
854    mode: BillboardMode,
855    clock: ClipClock,
856    /// The directional clip currently shown, to avoid redundant clip swaps.
857    showing: Option<VoxelClipId>,
858    /// The def's playback rate, kept for state-switch clock rebuilds.
859    speed: f32,
860}
861
862impl BillboardActor {
863    /// Pick the directional clip index for a camera at `cam` (world). See
864    /// [`dir_index`].
865    fn pick_dir(&self, cam: [f64; 3]) -> usize {
866        dir_index(
867            self.pos,
868            self.facing_yaw,
869            cam,
870            self.states[self.cur_state].dirs.len(),
871        )
872    }
873}
874
875/// Bin a camera's bearing (relative to an actor at `pos` facing `facing_yaw`)
876/// into one of `n` viewing-direction sectors. Index 0 = viewed-from-front
877/// (camera in the actor's facing direction), increasing counter-clockwise.
878/// `n <= 1` or a camera directly above/below ⇒ 0.
879fn dir_index(pos: [f32; 3], facing_yaw: f64, cam: [f64; 3], n: usize) -> usize {
880    if n <= 1 {
881        return 0;
882    }
883    let dx = cam[0] - f64::from(pos[0]);
884    let dy = cam[1] - f64::from(pos[1]);
885    if dx * dx + dy * dy < 1e-12 {
886        return 0; // camera directly above/below → no horizontal bearing
887    }
888    let rel = (dy.atan2(dx) - facing_yaw).rem_euclid(std::f64::consts::TAU);
889    let sector = std::f64::consts::TAU / n as f64;
890    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
891    let idx = (rel / sector).round() as usize % n;
892    idx
893}
894
895/// Backend-agnostic sprite description. The facade builds the CPU
896/// per-instance draw list and the GPU instanced registry from the
897/// same data, so both backends show identical sprites. The host owns
898/// content (which models, where, recolouring) — building a recoloured
899/// variant is just a second [`Sprite`] model with edited `kv6.voxels`.
900pub struct SpriteSet {
901    /// Distinct voxel models (KV6 + base orientation). Instances index
902    /// into this; their position overrides the model's.
903    pub models: Vec<Sprite>,
904    /// Initial placements — one drawn sprite per entry, each binding a
905    /// [`models`](Self::models) index to a world position.
906    pub instances: Vec<SpriteInstanceDesc>,
907    /// Model the [`SceneRenderer::carve_active_sprite`] hotkey edits
908    /// (GPU only, mirroring the demo's `G`-carve). `None` disables it.
909    pub carve_model: Option<usize>,
910}
911
912/// Per-frame inputs both backends consume. The host builds the
913/// [`OpticastSettings`] (it owns scan distance, projection etc.); the
914/// facade does everything else (pool config, sky fill, render,
915/// present).
916///
917/// **Both backends derive their projection from
918/// [`settings`](Self::settings)** (QE.2a): the vertical field of view
919/// is `2·atan(yres/2 / hz)` and the GPU outer-DDA step budget follows
920/// [`OpticastSettings::max_scan_dist`], so the two backends can no
921/// longer disagree about what they show. Pick an explicit FOV with
922/// [`OpticastSettings::with_fov_y`].
923///
924/// `#[non_exhaustive]`: construct with [`FrameParams::new`] and
925/// override fields — a future field addition is then not a breaking
926/// change (pre-QE.2, every added field broke every host's struct
927/// literal).
928#[non_exhaustive]
929pub struct FrameParams<'a> {
930    /// Render settings both backends share: framebuffer geometry +
931    /// projection (`hx`/`hy`/`hz`), scan distances, and the mip
932    /// ladder. (Named for the CPU renderer it configured first; the
933    /// GPU backend derives its FOV + step budget from it too.)
934    pub settings: &'a OpticastSettings,
935    /// Packed engine sky colour: the CPU sky-miss fill + skycast, and
936    /// the clear colour if no scene renders.
937    pub sky_color: Rgb,
938    /// Optional sky panorama for the CPU rasterizer's sky sampling.
939    pub sky: Option<&'a Sky>,
940    /// CPU fog: the packed colour distant voxels fade toward.
941    pub fog_color: Rgb,
942    /// CPU fog: full-fog distance (voxels). `0` disables CPU fog.
943    pub fog_max_scan_dist: i32,
944    /// CPU: treat z=255 as air (avoids the S1.X bedrock path for
945    /// out-of-bounds cameras).
946    pub treat_z_max_as_air: bool,
947    /// Whether to draw the renderer's sprites this frame. Both backends
948    /// draw KV6 sprites flat-lit (the clean-room DDA sprite raycaster on
949    /// CPU; uploaded model colours on GPU), so no host-supplied lighting
950    /// is needed — this is just the on/off opt-in. `false` skips sprite
951    /// drawing.
952    pub draw_sprites: bool,
953    /// Per-face directional shading for the voxel grids — voxlap's
954    /// `setsideshades(top, bot, left, right, up, down)`, the grid-scan
955    /// analogue of [`draw_sprites`](Self::draw_sprites). Each
956    /// entry darkens the faces pointing that way; the host typically
957    /// passes its engine's `side_shades()`. The default `[0; 6]` keeps
958    /// `sideshademode` off (no per-side shading), so existing hosts and
959    /// the oracle goldens are unaffected. Applied each frame by **both**
960    /// backends: the CPU rasteriser via `gcsub`, and the GPU scene-DDA
961    /// pass by darkening a hit voxel's brightness by the hit face's
962    /// shade (the face taken from the DDA's last-stepped axis).
963    pub side_shades: [i8; 6],
964    /// Dynamic lighting (stages DL + SL) — runtime sun + point + spot
965    /// lights + stylized shadows, applied by **both** backends (GPU
966    /// shaders since DL; the CPU renderer since CPU.1/CPU.2). `None`
967    /// (the default for hosts that don't set it) ⇒ exactly the pre-DL
968    /// render, both backends. The baked brightness byte is
969    /// reinterpreted as the ambient/AO channel; direct light composites
970    /// on top (`albedo*ambient + Σ direct`).
971    pub lights: Option<LightRig<'a>>,
972    /// WT.2 — full-screen colour tint ([`Tint`]), applied by **both**
973    /// backends in the resolve step at the logical resolution: after
974    /// the SSAA downfilter, BEFORE posterize (grade first, quantize
975    /// after — the reduced palette stays palette-shaped under the
976    /// tint). The canonical use is the underwater look — lerp toward
977    /// a deep blue-green while
978    /// [`CharacterBody::eye_in_water`](roxlap_scene::CharacterBody::eye_in_water)
979    /// — but it is a general grade hook (damage flash, night vision).
980    /// `None` (the default) is byte-identical to the pre-WT.2 output.
981    pub tint: Option<Tint>,
982}
983
984/// WT.2 — a full-screen tint: every resolved pixel lerps toward
985/// `color` by `strength`. See [`FrameParams::tint`] for where in the
986/// pipeline it applies.
987///
988/// The blend is **integer**: `strength` quantizes to 8 bits and each
989/// channel computes `(c·(255−s₈) + t·s₈ + 127) / 255` — the identical
990/// arithmetic on both backends, so tinted frames are bit-exact across
991/// CPU and GPU by construction (a float lerp + round pair provably
992/// drifts ±1 from WGSL `mix` + `pack4x8unorm` on ~2.5% of byte
993/// pairs, and driver float contraction is out of our control).
994/// Strengths below `1/510` quantize to 0 = off.
995///
996/// Known seam: overlays ([`SceneRenderer::draw_lines`] /
997/// [`SceneRenderer::draw_images`]) rasterise before the resolve on
998/// the CPU backend (they are graded with the scene) but after it on
999/// the GPU (drawn over the grade at full brightness).
1000#[derive(Debug, Clone, Copy, PartialEq)]
1001pub struct Tint {
1002    /// Target colour, packed `0x00RRGGBB` like every facade colour.
1003    pub color: Rgb,
1004    /// Lerp factor, clamped to `0..=1` at use. `0.0` is an identity
1005    /// (byte-identical to `None`); `1.0` paints the frame flat.
1006    pub strength: f32,
1007}
1008
1009impl Tint {
1010    /// The wire form both backends consume: packed colour + strength
1011    /// quantized to `0..=255`. A strength that quantizes to `0` folds
1012    /// to `None`, so the identity fast paths (skip the whole resolve
1013    /// pass) stay engaged — the ONE place this fold lives; both
1014    /// backend adapters call it.
1015    pub(crate) fn quantized(self) -> Option<(u32, u8)> {
1016        // Byte quantization of the clamped strength; `as u8` after
1017        // round is in range by construction.
1018        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1019        let s8 = (self.strength.clamp(0.0, 1.0) * 255.0).round() as u8;
1020        (s8 > 0).then_some((self.color.0, s8))
1021    }
1022}
1023
1024impl<'a> FrameParams<'a> {
1025    /// Frame params with sensible defaults for everything except
1026    /// [`settings`](Self::settings) (which the host owns): the default
1027    /// sky colour ([`RenderOptions::clear_sky`]'s default), no
1028    /// panorama, CPU fog off, sprites on, no per-side shading, no
1029    /// dynamic lights. Both backends' projection comes from
1030    /// `settings` (see the struct docs).
1031    ///
1032    /// `treat_z_max_as_air` defaults to `true` (what every demo passes;
1033    /// out-of-bounds cameras skip the bedrock path). Hosts that want
1034    /// the pre-QE literal-struct behaviour set it back to `false`.
1035    ///
1036    /// Every field stays public — construct with `new` and override
1037    /// what differs:
1038    ///
1039    /// ```ignore
1040    /// let mut fp = FrameParams::new(&settings);
1041    /// fp.sky = Some(&sky);
1042    /// fp.lights = Some(rig);
1043    /// ```
1044    #[must_use]
1045    pub fn new(settings: &'a OpticastSettings) -> Self {
1046        let default_sky = RenderOptions::default().clear_sky;
1047        Self {
1048            settings,
1049            sky_color: default_sky,
1050            sky: None,
1051            fog_color: default_sky,
1052            fog_max_scan_dist: 0,
1053            treat_z_max_as_air: true,
1054            draw_sprites: true,
1055            side_shades: [0; 6],
1056            lights: None,
1057            tint: None,
1058        }
1059    }
1060
1061    /// The vertical field of view both backends render `settings`
1062    /// with: `2·atan(yres/2 / hz)` — resolution-independent, so it
1063    /// holds at any window / logical size.
1064    // Screen dims cast to f32 are bounded by realistic resolutions.
1065    #[allow(clippy::cast_precision_loss)]
1066    #[must_use]
1067    pub fn fov_y_rad(&self) -> f32 {
1068        2.0 * ((self.settings.yres as f32) * 0.5 / self.settings.hz).atan()
1069    }
1070
1071    /// The GPU outer-DDA step budget (chunks) derived from
1072    /// [`OpticastSettings::max_scan_dist`]: enough chunk steps to cover
1073    /// the scan distance, plus slack for the entry/exit chunks.
1074    #[allow(clippy::cast_sign_loss)]
1075    #[must_use]
1076    pub fn gpu_outer_steps(&self) -> u32 {
1077        (self.settings.max_scan_dist.max(1) as u32) / roxlap_scene::CHUNK_SIZE_XY + 4
1078    }
1079}
1080
1081/// Backend-agnostic scene bookkeeping the facade owns **once** (QE.3a
1082/// — previously each backend kept a duplicate copy, and every new
1083/// feature needed three coordinated edits: facade arm + cpu + gpu,
1084/// with parity drift as the failure mode: the GPU copy had grown
1085/// change-detection the CPU copy lacked).
1086///
1087/// Backends receive `&SceneState` where they need it (the render
1088/// passes); the truly divergent reactions (CPU flipbook draw, GPU
1089/// instance-buffer/model-id writes, device palette mirror) stay in the
1090/// backends behind small `apply_*` hooks.
1091pub(crate) struct SceneState {
1092    /// Global voxel-material palette (TV stage): per-voxel material
1093    /// ids resolve to opacity + blend mode here. The CPU compositor
1094    /// reads it live each frame; the GPU mirrors it to device
1095    /// palettes when [`materials_dirty`](Self::materials_dirty).
1096    pub(crate) materials: MaterialTable,
1097    /// Terrain colour→material map (TV.4) — matching-colour world
1098    /// voxels render with that material (glass walls, water).
1099    pub(crate) terrain_materials: Vec<(Rgb, u8)>,
1100    /// PF.5 — set when `materials` / `terrain_materials` change;
1101    /// cleared after each `render` (the GPU mirrors device palettes
1102    /// only then). Starts `true` so the first GPU frame seeds them.
1103    pub(crate) materials_dirty: bool,
1104    /// Per **dynamic** instance (parallel to the backends' dynamic
1105    /// sublist): `Some((clip_index, current_frame))` for a clip
1106    /// instance, `None` for a plain model instance. The CPU render
1107    /// picks each instance's flipbook frame from this; the GPU keeps
1108    /// its instance buffer in sync via the `apply_clip_*` hooks.
1109    pub(crate) dyn_clip: Vec<Option<(usize, usize)>>,
1110}
1111
1112impl Default for SceneState {
1113    fn default() -> Self {
1114        Self {
1115            materials: MaterialTable::new(),
1116            terrain_materials: Vec::new(),
1117            materials_dirty: true,
1118            dyn_clip: Vec::new(),
1119        }
1120    }
1121}
1122
1123/// Result of [`SceneRenderer::pick`] — a resolved screen→world voxel
1124/// hit. `world` is the surface point (`cam.pos + t · normalize(ray)`);
1125/// `grid` + `voxel` are the owning grid and its **grid-local** voxel
1126/// (transform-correct for rotated / translated grids).
1127#[derive(Clone, Copy, PartialEq, Debug)]
1128pub struct PickHit {
1129    /// World-space surface point of the hit.
1130    pub world: [f32; 3],
1131    /// The grid owning the hit voxel.
1132    pub grid: roxlap_scene::GridId,
1133    /// The hit voxel, in `grid`-local coordinates.
1134    pub voxel: glam::IVec3,
1135}
1136
1137/// A world-space view ray: the canonical unproject output of
1138/// [`SceneRenderer::view_ray`]. `dir` is unit-length. Feed it straight
1139/// to [`roxlap_scene::Scene::raycast`] for depth-free, backend-agnostic
1140/// voxel picking (`scene.raycast(ray.origin, ray.dir, max_dist)`), or
1141/// intersect it with a plane for tile selection.
1142#[derive(Clone, Copy, PartialEq, Debug)]
1143pub struct Ray {
1144    /// World-space ray origin (the camera position for view rays).
1145    pub origin: glam::DVec3,
1146    /// Unit-length world-space ray direction.
1147    pub dir: glam::DVec3,
1148}
1149
1150/// A world-space line segment to draw over a rendered frame via
1151/// [`SceneRenderer::draw_lines`] — editor gizmos (bounding boxes, floor
1152/// grids, axes, hover wireframes), debug paths, etc.
1153#[derive(Clone, Copy, PartialEq, Debug)]
1154pub struct Line3 {
1155    /// World-space endpoints (voxel units), in the same frame the
1156    /// rendered scene + `camera` use.
1157    pub a: [f64; 3],
1158    /// The segment's other endpoint, same space as `a`.
1159    pub b: [f64; 3],
1160    /// `0xAARRGGBB` — the high byte is an alpha blend factor (`0xFF`
1161    /// opaque, `0x00` invisible), the low 24 bits the RGB colour.
1162    pub color: OverlayColor,
1163    /// Screen-space thickness in pixels (`<= 1.0` draws a 1px line).
1164    pub width_px: f32,
1165    /// `true`: the segment is occluded by nearer rendered geometry
1166    /// (depth-tested against the frame's z-buffer). `false`: always on
1167    /// top (e.g. a hover highlight that should show through the model).
1168    pub depth_test: bool,
1169}
1170
1171/// A handle to an uploaded image-sprite texture, returned by
1172/// [`SceneRenderer::upload_image`]. **Generational** (QE-B6): image
1173/// slots are reused after [`drop_image`](SceneRenderer::drop_image),
1174/// so each handle carries the slot's generation — a stale handle
1175/// (kept across a drop) resolves to a safe no-op instead of aliasing
1176/// whatever texture re-took the slot. Pass it in an [`ImageSprite`]
1177/// for [`SceneRenderer::draw_images`]. Opaque on purpose — there's no
1178/// arithmetic to do on it.
1179#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
1180pub struct ImageId {
1181    slot: u32,
1182    gen: u32,
1183}
1184
1185/// QE-B6 — generational guard for image slots. Unlike
1186/// [`EpochSlotMap`] (whose backend indices are append-only), image
1187/// slots ARE reused: `drop_image` frees the texture slot and the next
1188/// upload may take it. Each slot therefore carries its own
1189/// generation; a stale [`ImageId`] resolves to `None`.
1190#[derive(Default)]
1191struct ImageSlotMap {
1192    /// Per backend slot: (current generation, live).
1193    slots: Vec<(u32, bool)>,
1194}
1195
1196impl ImageSlotMap {
1197    /// Register the slot the backend just filled (append or reuse).
1198    fn alloc(&mut self, slot: usize) -> ImageId {
1199        if slot >= self.slots.len() {
1200            self.slots.resize(slot + 1, (0, false));
1201            self.slots[slot] = (0, true);
1202        } else {
1203            let e = &mut self.slots[slot];
1204            e.0 = e.0.wrapping_add(1);
1205            e.1 = true;
1206        }
1207        ImageId {
1208            slot: u32::try_from(slot).expect("image slots fit u32"),
1209            gen: self.slots[slot].0,
1210        }
1211    }
1212
1213    /// Resolve to the backend slot, or `None` when stale / removed.
1214    fn index(&self, id: ImageId) -> Option<usize> {
1215        let e = *self.slots.get(id.slot as usize)?;
1216        (e.0 == id.gen && e.1).then_some(id.slot as usize)
1217    }
1218
1219    /// Tombstone; `false` when the handle was already stale.
1220    fn remove(&mut self, id: ImageId) -> bool {
1221        let Some(e) = self.slots.get_mut(id.slot as usize) else {
1222            return false;
1223        };
1224        if e.0 != id.gen || !e.1 {
1225            return false;
1226        }
1227        e.1 = false;
1228        true
1229    }
1230}
1231
1232/// How an [`ImageSprite`]'s quad is oriented in the world.
1233#[derive(Clone, Copy, PartialEq, Debug)]
1234pub enum ImageFacing {
1235    /// Fixed in world space: the quad lies in the plane spanned by `u`
1236    /// (the image's +column / width direction) and `v` (its +row /
1237    /// height direction). Both are world-space directions; their length
1238    /// is ignored (the quad is sized by [`ImageSprite::size`]), so pass
1239    /// the plane's axes directly. Row 0 of the image is the `origin`
1240    /// edge and rows grow along `v`.
1241    World {
1242        /// World direction of the image's +column (width) axis.
1243        u: [f32; 3],
1244        /// World direction of the image's +row (height) axis.
1245        v: [f32; 3],
1246    },
1247    /// Always faces the camera (billboard); `up` is the world direction
1248    /// the image's top edge points toward (e.g. world `-Z` for the
1249    /// scene-demo's z-down world, or any "up" the host prefers).
1250    Billboard {
1251        /// World direction the image's top edge points toward.
1252        up: [f32; 3],
1253    },
1254}
1255
1256/// One placed 2D image sprite for the current frame: a flat textured
1257/// quad in world space, composited over the rendered scene with the
1258/// frame's depth buffer (so the voxel model can occlude it). Built per
1259/// frame and passed to [`SceneRenderer::draw_images`], mirroring
1260/// [`Line3`] / [`SceneRenderer::draw_lines`]. The texture is uploaded
1261/// once via [`SceneRenderer::upload_image`] and referenced by [`image`].
1262///
1263/// [`image`]: ImageSprite::image
1264#[derive(Clone, Copy, PartialEq, Debug)]
1265pub struct ImageSprite {
1266    /// The uploaded texture to draw (from [`SceneRenderer::upload_image`]).
1267    pub image: ImageId,
1268    /// World position of the quad's **top-left** corner — the image's
1269    /// `(column 0, row 0)` texel. The quad extends `size[0]` along the
1270    /// facing's `u` and `size[1]` along its `v`.
1271    pub origin: [f32; 3],
1272    /// World orientation of the quad — fixed in world or camera-facing.
1273    pub facing: ImageFacing,
1274    /// World size of the quad along `u` and `v`. For pixel-art traced at
1275    /// 1 texel = 1 voxel, pass `[width as f32, height as f32]`.
1276    pub size: [f32; 2],
1277    /// Multiplied into every sampled texel (tint + opacity) — real
1278    /// alpha, so [`OverlayColor`]. `OverlayColor(0xFFFF_FFFF)` draws the
1279    /// texture unchanged; the high byte scales the texel alpha
1280    /// (`OverlayColor(0x80FF_FFFF)` = 50 % opacity).
1281    pub tint: OverlayColor,
1282    /// Alpha cutoff in `0.0..=1.0`. Texels whose **own** alpha is below
1283    /// this are discarded outright (not blended) — crisp pixel-art edges
1284    /// instead of a semi-transparent haze, and the same threshold decides
1285    /// what [`SceneRenderer::pick_image`] treats as solid. `0.0` keeps the
1286    /// plain straight-alpha over-blend (every non-zero texel draws).
1287    pub alpha_cutoff: f32,
1288    /// `true`: occluded by nearer rendered geometry (depth-tested against
1289    /// the frame's depth buffer, with a bias so a quad resting on a
1290    /// coincident voxel face doesn't z-fight). `false`: always on top.
1291    pub depth_test: bool,
1292    /// `true`: draw regardless of which way the quad faces (no backface
1293    /// cull) — what reference images usually want. `false`: cull when the
1294    /// quad faces away from the camera. Ignored for
1295    /// [`ImageFacing::Billboard`] (it always faces the camera).
1296    pub double_sided: bool,
1297}
1298
1299/// Backend-agnostic resolved quad: four world corners (`TL, TR, BL, BR`,
1300/// with UVs `(0,0) (1,0) (0,1) (1,1)`) + the texture to map. The facade
1301/// resolves [`ImageSprite::facing`] into corners and culls back-facing
1302/// quads once, so both backends draw from the same geometry.
1303#[derive(Clone, Copy, Debug)]
1304pub(crate) struct QuadDraw {
1305    pub corners: [[f32; 3]; 4],
1306    /// Backend texture SLOT (facade-resolved; see `draw_images`).
1307    pub image: usize,
1308    pub tint: OverlayColor,
1309    pub depth_test: bool,
1310    pub alpha_cutoff: f32,
1311}
1312
1313/// Result of [`SceneRenderer::pick_image`] — a resolved screen→sprite hit.
1314/// `uv` is the normalised position within the quad (`(0,0)` = top-left
1315/// corner); `texel` is the matching source-image pixel; `world` is the
1316/// hit point; `t` is its euclidean distance from the camera.
1317#[derive(Clone, Copy, PartialEq, Debug)]
1318pub struct ImagePickHit {
1319    /// The hit sprite's texture handle.
1320    pub image: ImageId,
1321    /// Normalised position within the quad (`(0,0)` = top-left).
1322    pub uv: [f32; 2],
1323    /// The matching source-image pixel (column, row).
1324    pub texel: (u32, u32),
1325    /// World-space hit point on the quad.
1326    pub world: [f32; 3],
1327    /// Euclidean distance from the camera to `world`.
1328    pub t: f32,
1329}
1330
1331/// Which renderer a [`SceneRenderer`] resolved to at construction.
1332#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1333pub enum Backend {
1334    /// `roxlap-core` opticast, presented via `softbuffer`.
1335    Cpu,
1336    /// `roxlap-gpu` compute marcher, presented via wgpu.
1337    Gpu,
1338}
1339
1340/// A backend-dependent capability, probed via
1341/// [`SceneRenderer::supports`] (QE.7a). Every method below the parity
1342/// line degrades to a silent no-op on the unsupporting backend; this
1343/// enum turns the tribal knowledge into a queryable answer.
1344///
1345/// | Feature | CPU | GPU |
1346/// |---|---|---|
1347/// | [`Capture`](Self::Capture) | ✅ | ✅ native (❌ wasm — WebGPU can't block) |
1348/// | [`SkyPanorama`](Self::SkyPanorama) | ❌ (use [`FrameParams::sky`]) | ✅ |
1349/// | [`CarveActiveSprite`](Self::CarveActiveSprite) | ❌ | ✅ |
1350/// | [`TranslucentSpriteMaterials`](Self::TranslucentSpriteMaterials) | ✅ | ✅ (TV.3) |
1351/// | [`TranslucentTerrain`](Self::TranslucentTerrain) | ✅ | ✅ (TV.6) |
1352/// | [`FreePickDepth`](Self::FreePickDepth) | ✅ | ❌ (blocking readback) |
1353#[non_exhaustive]
1354#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1355pub enum Feature {
1356    /// [`SceneRenderer::request_capture`] / `take_capture` produce
1357    /// frames.
1358    Capture,
1359    /// [`SceneRenderer::set_sky_panorama`] uploads a sampled sky (the
1360    /// CPU backend samples [`FrameParams::sky`] instead).
1361    SkyPanorama,
1362    /// [`SceneRenderer::carve_active_sprite`] carves.
1363    CarveActiveSprite,
1364    /// Per-voxel / per-instance **sprite** materials composite
1365    /// translucently (an unsupporting backend renders them opaque).
1366    TranslucentSpriteMaterials,
1367    /// [`SceneRenderer::set_terrain_materials`] terrain translucency
1368    /// composites (an unsupporting backend renders terrain opaque).
1369    TranslucentTerrain,
1370    /// [`SceneRenderer::pick_depth`] is cheap enough for per-frame use
1371    /// (an in-memory read). Unsupporting = it works but **blocks** on
1372    /// a device readback — hotkey-grade, not reticle-grade.
1373    FreePickDepth,
1374}
1375
1376/// Which backend [`SceneRenderer::try_new`] should build (QE.7b —
1377/// replaces `RenderOptions.want_gpu: bool`, which couldn't express
1378/// "GPU or fail": headless CI rigs and benchmarks silently fell back
1379/// to a software render and measured the wrong thing).
1380#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
1381pub enum BackendPreference {
1382    /// The CPU renderer, unconditionally (the pre-QE.7 `want_gpu:
1383    /// false`). The default.
1384    #[default]
1385    Cpu,
1386    /// Try the GPU; fall back to CPU with a logged `warn` when WGPU
1387    /// init fails (the pre-QE.7 `want_gpu: true`).
1388    PreferGpu,
1389    /// GPU or [`RenderError::GpuInit`] — no silent software fallback.
1390    /// (The wasm constructor has no `Result` channel and treats this
1391    /// as [`PreferGpu`](Self::PreferGpu).)
1392    RequireGpu,
1393}
1394
1395/// Construction failure from [`SceneRenderer::try_new`] (QE.2b).
1396///
1397/// Under [`BackendPreference::PreferGpu`] a GPU failure is not an
1398/// error (it logs a `warn` and falls back to CPU); `try_new` fails
1399/// when the last-resort CPU surface can't be created, or when
1400/// [`BackendPreference::RequireGpu`] couldn't get its GPU.
1401#[derive(Debug)]
1402pub enum RenderError {
1403    /// The CPU backend couldn't bind its software present surface
1404    /// (softbuffer context/surface creation failed — e.g. a broken or
1405    /// unsupported display connection).
1406    CpuSurface(String),
1407    /// [`BackendPreference::RequireGpu`] and WGPU init failed (QE.7b).
1408    GpuInit(GpuInitError),
1409}
1410
1411impl std::fmt::Display for RenderError {
1412    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1413        match self {
1414            Self::CpuSurface(msg) => write!(f, "CPU present surface init failed: {msg}"),
1415            Self::GpuInit(e) => write!(f, "GPU init failed (RequireGpu, no fallback): {e}"),
1416        }
1417    }
1418}
1419
1420impl std::error::Error for RenderError {
1421    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1422        match self {
1423            Self::GpuInit(e) => Some(e),
1424            Self::CpuSurface(_) => None,
1425        }
1426    }
1427}
1428
1429/// Construction-time options for [`SceneRenderer::new`].
1430///
1431/// # Environment overrides (QE-C6)
1432///
1433/// Each GPU tuning knob below has a `ROXLAP_*` escape hatch, so a
1434/// shipped binary can be re-tuned from the shell. All of them are
1435/// read **once**, at `SceneRenderer` construction (never per frame),
1436/// the env value wins over the programmatic one, and unparseable
1437/// values are dropped with a `log::warn!`. On wasm there is no
1438/// process environment and the field values apply as-is.
1439///
1440/// | variable | overrides | values |
1441/// |---|---|---|
1442/// | `ROXLAP_GPU_POWER` | [`gpu`](Self::gpu)`.power_preference` | `low` / `high` |
1443/// | `ROXLAP_GPU_SPRITE_LOD_PX` | [`gpu_sprite_lod_px`](Self::gpu_sprite_lod_px) | `f32`, screen px |
1444/// | `ROXLAP_GPU_MIP_SCAN_DIST` | [`gpu_mip_scan_dist`](Self::gpu_mip_scan_dist) | `f32`, world units |
1445/// | `ROXLAP_GPU_CHUNK_BUDGET` | [`gpu_chunk_upload_budget`](Self::gpu_chunk_upload_budget) | `u32`, `0` = unbounded |
1446/// | `ROXLAP_GPU_CLIP_BUDGET` | [`gpu_clip_upload_budget`](Self::gpu_clip_upload_budget) | `u32`, `0` = unbounded |
1447///
1448/// Other `ROXLAP_*` variables you may have seen (`ROXLAP_GPU`,
1449/// `ROXLAP_SCENE`, `ROXLAP_CAPTURE`, …) belong to the demo hosts, not
1450/// the library — backend selection is [`backend`](Self::backend),
1451/// decided by *your* code.
1452#[derive(Clone)]
1453pub struct RenderOptions {
1454    /// Which backend to build (QE.7b — replaces `want_gpu: bool`;
1455    /// migrate `want_gpu: true` → [`BackendPreference::PreferGpu`],
1456    /// `false` → [`BackendPreference::Cpu`]).
1457    pub backend: BackendPreference,
1458    /// Settings forwarded to [`roxlap_gpu::GpuRenderer`] when the GPU
1459    /// backend is selected.
1460    pub gpu: GpuRendererSettings,
1461    /// Packed `0x00RRGGBB` (alpha ignored) the empty/clear frame fills
1462    /// with until a scene render lands. Also the CPU sky-miss colour
1463    /// default if a frame supplies none.
1464    pub clear_sky: Rgb,
1465    /// GPU scene-grid LOD scan distance in world units (GPU.11.1):
1466    /// rays farther than this from the camera sample coarser chunk
1467    /// mips. QE.2a — construction-time here (was a per-frame
1468    /// `FrameParams` field); the `ROXLAP_GPU_MIP_SCAN_DIST` env var
1469    /// still overrides it as a user-side escape hatch. Ignored by the
1470    /// CPU backend (its mip ladder comes from
1471    /// [`OpticastSettings::mip_scan_dist`]).
1472    pub gpu_mip_scan_dist: f32,
1473    /// GPU per-frame dirty-chunk install budget (QE.2c — was env-only
1474    /// `ROXLAP_GPU_CHUNK_BUDGET`, which still overrides). Each chunk
1475    /// install issues several `queue.write_buffer` calls; a big batch
1476    /// can exhaust the device staging pool (seen as egui-wgpu panics on
1477    /// Mesa/NVK while flying fast). Small budget = bounded per-frame
1478    /// writes, more terrain pop-in when moving quickly. `0` =
1479    /// unbounded.
1480    pub gpu_chunk_upload_budget: u32,
1481    /// GPU frames-per-staging-flush while registering a flipbook clip
1482    /// (QE.2c — was env-only `ROXLAP_GPU_CLIP_BUDGET`, which still
1483    /// overrides). `0` = unbounded.
1484    pub gpu_clip_upload_budget: u32,
1485    /// GPU sprite mip-LOD threshold (QE.8; `ROXLAP_GPU_SPRITE_LOD_PX`
1486    /// overrides): the pass steps to a coarser sprite mip once a
1487    /// mip-0 voxel would project smaller than this many screen pixels.
1488    /// `1.0` (the default) is the "don't go sub-pixel" threshold and
1489    /// keeps GPU sprites visually identical to the CPU backend (which
1490    /// has no sprite LOD); raise it to trade sprite fidelity for
1491    /// distant-sprite speed (the pre-QE.8 behaviour was `4.0`, which
1492    /// visibly densified thin/hollow translucent models at range).
1493    pub gpu_sprite_lod_px: f32,
1494    /// Unused. Sized the strip-parallel opticast's per-frame scratch
1495    /// pool; the per-pixel DDA renderer that replaced it needs no
1496    /// pre-sizing, so the value is ignored.
1497    #[deprecated(
1498        since = "0.22.0",
1499        note = "ignored — the DDA renderer replaced the strip-parallel \
1500                opticast and needs no scratch-pool pre-sizing"
1501    )]
1502    pub cpu_max_grid_vsid: u32,
1503    /// Unused. Set the strip-parallel opticast's thread count; the DDA
1504    /// renderer parallelises internally over the rayon pool (bound it
1505    /// with `RAYON_NUM_THREADS` if needed), so the value is ignored.
1506    #[deprecated(
1507        since = "0.22.0",
1508        note = "ignored — the DDA renderer parallelises over the rayon \
1509                pool; bound it with RAYON_NUM_THREADS"
1510    )]
1511    pub cpu_render_threads: usize,
1512}
1513
1514// The deprecated fields still have to be constructed until they are
1515// removed for real (QE has a breaking window; see docs/porting/
1516// PORTING-QUALITY.md).
1517#[allow(deprecated)]
1518impl Default for RenderOptions {
1519    fn default() -> Self {
1520        Self {
1521            backend: BackendPreference::Cpu,
1522            gpu: GpuRendererSettings::default(),
1523            clear_sky: Rgb(0x0099_b3d9),
1524            gpu_mip_scan_dist: 64.0,
1525            gpu_chunk_upload_budget: 2,
1526            gpu_clip_upload_budget: 8,
1527            gpu_sprite_lod_px: 1.0,
1528            cpu_max_grid_vsid: 32 * roxlap_scene::CHUNK_SIZE_XY,
1529            cpu_render_threads: 4,
1530        }
1531    }
1532}
1533
1534/// Depth-test slack (same spirit as the backends' `DEPTH_BIAS`) so a
1535/// [`SceneRenderer::pick_image`] hit on a sprite resting on a coincident
1536/// voxel face isn't rejected as "occluded".
1537const PICK_DEPTH_BIAS: f32 = 0.5;
1538
1539// --- image-sprite geometry helpers (shared by both backends) ---
1540
1541fn v_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1542    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
1543}
1544fn v_add(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1545    [a[0] + b[0], a[1] + b[1], a[2] + b[2]]
1546}
1547fn v_scale(a: [f32; 3], s: f32) -> [f32; 3] {
1548    [a[0] * s, a[1] * s, a[2] * s]
1549}
1550fn v_dot(a: [f32; 3], b: [f32; 3]) -> f32 {
1551    a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
1552}
1553fn v_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
1554    [
1555        a[1] * b[2] - a[2] * b[1],
1556        a[2] * b[0] - a[0] * b[2],
1557        a[0] * b[1] - a[1] * b[0],
1558    ]
1559}
1560fn v_norm(a: [f32; 3]) -> [f32; 3] {
1561    let len = v_dot(a, a).sqrt();
1562    if len < 1e-12 {
1563        a
1564    } else {
1565        v_scale(a, 1.0 / len)
1566    }
1567}
1568
1569/// Intersect a ray (`origin` + `dir`, `dir` un-normalised) with a quad
1570/// `[TL, TR, BL, BR]` and return `(uv, t)` for a front/back hit inside
1571/// the quad — `uv` in `0..=1` (`(0,0)` = `TL`), `t` the ray parameter
1572/// (`hit = origin + dir·t`). `None` for a parallel ray, a hit behind the
1573/// origin, a degenerate quad, or a hit outside the `u`/`v` span. Solves
1574/// affine coords exactly for a (possibly skew) parallelogram. Standalone
1575/// so the geometry is unit-testable without a renderer.
1576fn ray_quad_uv(
1577    origin: [f32; 3],
1578    dir: [f32; 3],
1579    corners: &[[f32; 3]; 4],
1580) -> Option<([f32; 2], f32)> {
1581    let [tl, tr, bl, _br] = *corners;
1582    let ue = v_sub(tr, tl); // +u edge (width)
1583    let ve = v_sub(bl, tl); // +v edge (height)
1584    let n = v_cross(ue, ve);
1585    let denom = v_dot(dir, n);
1586    if denom.abs() < 1e-12 {
1587        return None; // ray parallel to the quad's plane
1588    }
1589    let t = v_dot(v_sub(tl, origin), n) / denom;
1590    if t <= 1e-6 {
1591        return None; // behind / at the origin
1592    }
1593    let p = v_add(origin, v_scale(dir, t));
1594    let rel = v_sub(p, tl);
1595    let guu = v_dot(ue, ue);
1596    let guv = v_dot(ue, ve);
1597    let gvv = v_dot(ve, ve);
1598    let det = guu * gvv - guv * guv;
1599    if det.abs() < 1e-12 {
1600        return None; // degenerate quad
1601    }
1602    let wu = v_dot(rel, ue);
1603    let wv = v_dot(rel, ve);
1604    let a = (gvv * wu - guv * wv) / det;
1605    let b = (guu * wv - guv * wu) / det;
1606    if !(0.0..=1.0).contains(&a) || !(0.0..=1.0).contains(&b) {
1607        return None; // outside the quad
1608    }
1609    Some(([a, b], t))
1610}
1611
1612/// Resolve an [`ImageSprite`] into its four world corners (`TL, TR, BL,
1613/// BR`), or `None` when a `double_sided == false` world quad faces away
1614/// from the camera (back-face cull) or its plane is degenerate. The
1615/// camera basis is used only for [`ImageFacing::Billboard`] and the cull
1616/// test.
1617fn resolve_quad(sprite: &ImageSprite, camera: &Camera) -> Option<QuadDraw> {
1618    let cam_pos = [
1619        camera.pos[0] as f32,
1620        camera.pos[1] as f32,
1621        camera.pos[2] as f32,
1622    ];
1623    let cam_fwd = v_norm([
1624        camera.forward[0] as f32,
1625        camera.forward[1] as f32,
1626        camera.forward[2] as f32,
1627    ]);
1628
1629    let (u_hat, v_hat) = match sprite.facing {
1630        ImageFacing::World { u, v } => (v_norm(u), v_norm(v)),
1631        ImageFacing::Billboard { up } => {
1632            // Horizontal axis ⟂ both the view direction and `up`; fall
1633            // back to the camera right when `up` is parallel to the view.
1634            let mut u_hat = v_norm(v_cross(up, cam_fwd));
1635            if v_dot(u_hat, u_hat) < 1e-12 {
1636                u_hat = v_norm([
1637                    camera.right[0] as f32,
1638                    camera.right[1] as f32,
1639                    camera.right[2] as f32,
1640                ]);
1641            }
1642            // Vertical axis ⟂ both, pointing *down* (rows grow downward)
1643            // so the top edge ends up toward `up`.
1644            let mut v_hat = v_norm(v_cross(cam_fwd, u_hat));
1645            if v_dot(v_hat, up) > 0.0 {
1646                v_hat = v_scale(v_hat, -1.0);
1647            }
1648            (u_hat, v_hat)
1649        }
1650    };
1651
1652    let du = v_scale(u_hat, sprite.size[0]);
1653    let dv = v_scale(v_hat, sprite.size[1]);
1654    let tl = sprite.origin;
1655    let tr = v_add(tl, du);
1656    let bl = v_add(tl, dv);
1657    let br = v_add(tr, dv);
1658
1659    // Back-face cull for fixed world quads (billboards always face us).
1660    if !sprite.double_sided {
1661        if let ImageFacing::World { .. } = sprite.facing {
1662            let normal = v_cross(du, dv);
1663            // Front-facing when the quad normal points toward the camera.
1664            if v_dot(normal, v_sub(cam_pos, tl)) <= 0.0 {
1665                return None;
1666            }
1667        }
1668    }
1669
1670    Some(QuadDraw {
1671        corners: [tl, tr, bl, br],
1672        image: 0, // placeholder — draw_images resolves the real slot
1673        tint: sprite.tint,
1674        depth_test: sprite.depth_test,
1675        alpha_cutoff: sprite.alpha_cutoff,
1676    })
1677}
1678
1679/// Where the per-pixel raycaster actually runs, decoupled from the window
1680/// size (RP.0). Both backends are per-pixel marchers, so frame cost scales
1681/// with the pixel count — rendering into a fixed **logical** target and
1682/// nearest-upscaling it to the window makes FPS independent of window size
1683/// and creates the seam for the later posterize / SSAA post (RP.1/RP.2).
1684///
1685/// The default ([`Native`](RenderResolution::Native)) keeps `logical == window`
1686/// and is **byte-identical** to the pre-RP straight blit.
1687#[derive(Clone, Copy, Debug, PartialEq, Default)]
1688pub enum RenderResolution {
1689    /// Logical resolution == window. Default. Identical to pre-RP behaviour.
1690    #[default]
1691    Native,
1692    /// Fixed logical grid, independent of the window (the retro pixel grid).
1693    /// Upscaled to the window with nearest sampling (hard pixels). A logical
1694    /// aspect ratio different from the window's stretches non-uniformly — a
1695    /// deliberate, classic fixed-res look (no letterbox in RP.0).
1696    Fixed {
1697        /// Logical framebuffer width, pixels.
1698        w: u32,
1699        /// Logical framebuffer height, pixels.
1700        h: u32,
1701    },
1702    /// Logical = `round(window * factor)`. `0.5` ⇒ a quarter of the pixels,
1703    /// aspect preserved. Clamped to `>= 1px` per axis.
1704    Scale(f32),
1705}
1706
1707impl RenderResolution {
1708    /// Resolve to a concrete logical pixel size given the current window
1709    /// (native) size. Always `>= 1` per axis.
1710    #[must_use]
1711    pub(crate) fn logical_for(self, native: (u32, u32)) -> (u32, u32) {
1712        let (nw, nh) = (native.0.max(1), native.1.max(1));
1713        match self {
1714            Self::Native => (nw, nh),
1715            Self::Fixed { w, h } => (w.max(1), h.max(1)),
1716            Self::Scale(f) => {
1717                let s = f.max(1e-3);
1718                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1719                let lw = ((nw as f32) * s).round() as u32;
1720                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1721                let lh = ((nh as f32) * s).round() as u32;
1722                (lw.max(1), lh.max(1))
1723            }
1724        }
1725    }
1726}
1727
1728/// Dither applied before the posterize quantization (RP.2), to break up
1729/// banding and turn it into a stable retro pattern instead of crawling edges.
1730/// Indexed by the *logical* pixel, so each hard pixel still resolves to one
1731/// colour.
1732#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
1733pub enum DitherMode {
1734    /// No dither — plain round-to-nearest quantization (hard banding).
1735    #[default]
1736    None,
1737    /// Classic `4×4` ordered (Bayer) dither — the cross-hatch console look.
1738    Bayer4x4,
1739    /// Interleaved-gradient noise — a cheap, texture-free blue-noise-ish
1740    /// stochastic dither (finer than Bayer, no repeating grid).
1741    BlueNoise,
1742}
1743
1744/// Reduced-palette post (RP.2), applied at the logical resolution in the
1745/// resolve step (after the SSAA box-downfilter, before the nearest upscale).
1746/// Each channel is quantized to its own number of levels; `levels <= 1` leaves
1747/// that channel untouched. `None` posterize ⇒ the RP.0/RP.1 paths verbatim.
1748#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1749pub struct PosterizeConfig {
1750    /// Quantisation levels for the red channel (≥ 2).
1751    pub levels_r: u8,
1752    /// Quantisation levels for the green channel (≥ 2).
1753    pub levels_g: u8,
1754    /// Quantisation levels for the blue channel (≥ 2).
1755    pub levels_b: u8,
1756    /// Dither pattern applied before quantisation.
1757    pub dither: DitherMode,
1758}
1759
1760impl PosterizeConfig {
1761    /// Uniform per-channel level count with the given dither.
1762    #[must_use]
1763    pub fn uniform(levels: u8, dither: DitherMode) -> Self {
1764        Self {
1765            levels_r: levels,
1766            levels_g: levels,
1767            levels_b: levels,
1768            dither,
1769        }
1770    }
1771}
1772
1773/// Renderer-internal backend; never exposes wgpu or softbuffer types.
1774/// The GPU variant owns the whole wgpu device/queue/pipelines, so
1775/// it's boxed to keep the enum small.
1776enum BackendImpl {
1777    // Both variants boxed so the enum stays small regardless of which
1778    // backend's state is larger (clippy::large_enum_variant).
1779    Cpu(Box<CpuBackend>),
1780    Gpu(Box<GpuBackend>),
1781}
1782
1783/// Unified renderer over the CPU and GPU paths. See the crate docs.
1784pub struct SceneRenderer {
1785    inner: BackendImpl,
1786    /// Handles for dynamically added sprite instances (see
1787    /// [`Self::add_sprite_instance`]). Reset by [`Self::set_sprites`].
1788    dyn_map: DynInstanceMap,
1789    /// Handles for registered sprite models (see [`Self::add_sprite_model`]
1790    /// and the models returned by [`Self::set_sprites`]). Reset by
1791    /// [`Self::set_sprites`].
1792    model_map: EpochSlotMap<SpriteModelId>,
1793    /// Handles for registered animated voxel clips (see
1794    /// [`Self::add_voxel_clip`]). Reset by [`Self::set_sprites`].
1795    clip_map: EpochSlotMap<VoxelClipId>,
1796    /// Handles for registered animated characters (see
1797    /// [`Self::add_character`]). Reset by [`Self::set_sprites`].
1798    char_map: EpochSlotMap<CharacterId>,
1799    /// Live character runtimes, parallel to `char_map` slots (VCL.6).
1800    char_instances: Vec<CharInstance>,
1801    /// Handles for registered streaming clips (see
1802    /// [`Self::add_streaming_clip`]). Reset by [`Self::set_sprites`].
1803    streaming_map: EpochSlotMap<StreamingClipId>,
1804    /// Streaming-clip runtimes (cursor + one re-uploaded model), parallel
1805    /// to `streaming_map` slots; `None` once removed (#3).
1806    streaming_clips: Vec<Option<StreamingClipState>>,
1807    /// Metadata per registered flipbook clip, indexed by the backend clip
1808    /// index (parallel to `clip_map`). Captured at [`Self::add_voxel_clip`]
1809    /// so the editor queries ([`Self::clip_metadata`]) + the auto-player
1810    /// don't have to re-pass / shadow the `DecodedClip`. Reset by
1811    /// [`Self::set_sprites`].
1812    clip_meta: Vec<ClipMeta>,
1813    /// Auto-advancing clip players (#6); ticked by
1814    /// [`Self::advance_voxel_clips`]. Reset by [`Self::set_sprites`].
1815    clip_players: Vec<ClipPlayer>,
1816    /// Camera-facing billboard instances (BB.2): each carries its world
1817    /// position + mode, re-oriented every [`Self::face_billboards_to`].
1818    /// Reset by [`Self::set_sprites`].
1819    billboards: Vec<BillboardRec>,
1820    /// Handles for high-level directional billboard actors (BB.4). Reset by
1821    /// [`Self::set_sprites`].
1822    actor_map: EpochSlotMap<BillboardActorId>,
1823    /// Live billboard-actor runtimes, parallel to `actor_map` slots; `None`
1824    /// once removed. Driven by [`Self::update_billboard_actors`].
1825    billboard_actors: Vec<Option<BillboardActor>>,
1826    /// QE.3a - the once-per-facade scene bookkeeping both backends
1827    /// read (materials, terrain map, clip-instance frames).
1828    state: SceneState,
1829    /// QE-B6 — generational image-slot guard (see [`ImageSlotMap`]).
1830    image_map: ImageSlotMap,
1831}
1832
1833impl SceneRenderer {
1834    /// Wrap a constructed backend with the facade's (empty) handle
1835    /// registries — the shared tail of every constructor.
1836    fn from_backend(inner: BackendImpl) -> Self {
1837        Self {
1838            inner,
1839            image_map: ImageSlotMap::default(),
1840            dyn_map: DynInstanceMap::default(),
1841            model_map: EpochSlotMap::default(),
1842            clip_map: EpochSlotMap::default(),
1843            char_map: EpochSlotMap::default(),
1844            char_instances: Vec::new(),
1845            streaming_map: EpochSlotMap::default(),
1846            streaming_clips: Vec::new(),
1847            clip_meta: Vec::new(),
1848            clip_players: Vec::new(),
1849            billboards: Vec::new(),
1850            actor_map: EpochSlotMap::default(),
1851            billboard_actors: Vec::new(),
1852            state: SceneState::default(),
1853        }
1854    }
1855
1856    /// Build a renderer for `window` — any [`raw-window-handle`]
1857    /// provider (winit, SDL, GLFW, …) in an `Arc`. `size` is the
1858    /// window's initial physical framebuffer size in pixels; thereafter
1859    /// the host reports changes via [`Self::resize`]. Passing the size
1860    /// explicitly keeps the facade decoupled from any one windowing
1861    /// library's size API.
1862    ///
1863    /// Builds the backend [`opts.backend`](RenderOptions::backend)
1864    /// asks for. Under [`BackendPreference::PreferGpu`] a WGPU-init
1865    /// failure falls back to the CPU backend with a `warn` through
1866    /// the [`log`] facade (install a logger like `env_logger` to see
1867    /// why a machine is software-rendering);
1868    /// [`BackendPreference::RequireGpu`] turns that failure into an
1869    /// error instead (QE.7b — headless CI / benchmark rigs must not
1870    /// silently measure a software render).
1871    ///
1872    /// # Errors
1873    /// [`RenderError::CpuSurface`] — the last-resort softbuffer
1874    /// context/surface couldn't bind to `window`;
1875    /// [`RenderError::GpuInit`] — `RequireGpu` and WGPU init failed.
1876    ///
1877    /// [`raw-window-handle`]: raw_window_handle
1878    #[cfg(not(target_arch = "wasm32"))]
1879    pub fn try_new<W>(
1880        window: Arc<W>,
1881        size: (u32, u32),
1882        opts: &RenderOptions,
1883    ) -> Result<Self, RenderError>
1884    where
1885        W: HasWindowHandle + HasDisplayHandle + Send + Sync + 'static,
1886    {
1887        // QE-C6 — resolve `ROXLAP_*` env overrides once, here, and
1888        // thread plain options into the backends (no env reads below).
1889        let opts = &env_config::EnvOverrides::from_env().applied(opts);
1890        if opts.backend != BackendPreference::Cpu {
1891            match GpuBackend::new(window.clone(), size, opts) {
1892                Ok(g) => return Ok(Self::from_backend(BackendImpl::Gpu(Box::new(g)))),
1893                Err(e) if opts.backend == BackendPreference::RequireGpu => {
1894                    return Err(RenderError::GpuInit(e));
1895                }
1896                Err(e) => {
1897                    log::warn!("GPU init failed ({e}); falling back to the CPU renderer");
1898                }
1899            }
1900        }
1901        let cpu = CpuBackend::try_new(window, size, opts)?;
1902        Ok(Self::from_backend(BackendImpl::Cpu(Box::new(cpu))))
1903    }
1904
1905    /// Infallible [`Self::try_new`]: **panics** if even the CPU
1906    /// software surface can't be created — the convenient default for
1907    /// demos and tools, where "no window surface at all" has no
1908    /// meaningful recovery. Games that want to show their own error UI
1909    /// call [`try_new`](Self::try_new).
1910    ///
1911    /// # Panics
1912    /// When [`Self::try_new`] returns [`RenderError::CpuSurface`].
1913    #[cfg(not(target_arch = "wasm32"))]
1914    #[must_use]
1915    pub fn new<W>(window: Arc<W>, size: (u32, u32), opts: &RenderOptions) -> Self
1916    where
1917        W: HasWindowHandle + HasDisplayHandle + Send + Sync + 'static,
1918    {
1919        match Self::try_new(window, size, opts) {
1920            Ok(r) => r,
1921            Err(e) => panic!("SceneRenderer::new: {e} (use try_new to handle this)"),
1922        }
1923    }
1924
1925    /// wasm/WebGPU build-time entry: build a renderer over an HTML
1926    /// `canvas`. `size` is the canvas's initial framebuffer size in
1927    /// pixels; the host reports later changes via [`Self::resize`].
1928    ///
1929    /// Async because the browser drives wgpu's adapter/device requests
1930    /// through its event loop — `await` it inside a
1931    /// `wasm_bindgen_futures::spawn_local` task. Selects the GPU
1932    /// (WebGPU) backend when `opts.backend` asks for GPU and WebGPU is
1933    /// available (`RequireGpu` degrades to `PreferGpu` here — no
1934    /// `Result` channel in the async wasm constructor);
1935    /// otherwise (no WebGPU, or init failed) it falls back to the CPU
1936    /// opticast path presented through a WebGL2 blit on the same canvas.
1937    /// **Never fails** — the message is logged to the browser console.
1938    #[cfg(target_arch = "wasm32")]
1939    pub async fn new_from_canvas_async(
1940        canvas: web_sys::HtmlCanvasElement,
1941        size: (u32, u32),
1942        opts: &RenderOptions,
1943    ) -> Self {
1944        // QE-C6 mirror of the native path; on wasm every override is
1945        // `None` (no process environment), so this is a plain copy.
1946        let opts = &env_config::EnvOverrides::from_env().applied(opts);
1947        if opts.backend != BackendPreference::Cpu {
1948            // `SurfaceTarget::Canvas` moves the canvas into wgpu, so the
1949            // GPU attempt gets a clone — the CPU fallback keeps the
1950            // original if WebGPU init fails.
1951            match GpuBackend::new_async(canvas.clone(), size, opts).await {
1952                Ok(g) => return Self::from_backend(BackendImpl::Gpu(Box::new(g))),
1953                Err(e) => {
1954                    web_sys::console::warn_1(
1955                        &format!("roxlap-render: WebGPU init failed ({e}); using the CPU renderer")
1956                            .into(),
1957                    );
1958                }
1959            }
1960        }
1961        Self::from_backend(BackendImpl::Cpu(Box::new(CpuBackend::new_from_canvas(
1962            &canvas, size, opts,
1963        ))))
1964    }
1965
1966    /// Which backend was selected.
1967    #[must_use]
1968    pub fn backend(&self) -> Backend {
1969        match self.inner {
1970            BackendImpl::Cpu(_) => Backend::Cpu,
1971            BackendImpl::Gpu(_) => Backend::Gpu,
1972        }
1973    }
1974
1975    /// Whether the active backend supports `feature` (QE.7a) — the
1976    /// queryable form of the parity table on [`Feature`]. Methods on
1977    /// the "❌" side stay callable and degrade to documented no-ops;
1978    /// use this to pick a strategy up front (e.g. photo mode: capture
1979    /// vs "not available on this platform").
1980    #[must_use]
1981    pub fn supports(&self, feature: Feature) -> bool {
1982        let gpu = matches!(self.inner, BackendImpl::Gpu(_));
1983        match feature {
1984            Feature::Capture => {
1985                // GPU capture is a blocking readback — native only.
1986                !gpu || cfg!(not(target_arch = "wasm32"))
1987            }
1988            Feature::SkyPanorama | Feature::CarveActiveSprite => gpu,
1989            // Translucency landed on BOTH backends in the TV stage
1990            // (TV.3 sprites / TV.6 terrain, GPU visually verified);
1991            // QE.7a shipped this table stale — saying `!gpu` — and the
1992            // author re-confirmed the GPU paths before this fix.
1993            Feature::TranslucentSpriteMaterials | Feature::TranslucentTerrain => true,
1994            Feature::FreePickDepth => !gpu,
1995        }
1996    }
1997
1998    /// The GPU adapter description when on the GPU backend, else
1999    /// `None`.
2000    #[must_use]
2001    pub fn adapter_info(&self) -> Option<&str> {
2002        match &self.inner {
2003            BackendImpl::Gpu(g) => Some(g.adapter_info()),
2004            BackendImpl::Cpu(_) => None,
2005        }
2006    }
2007
2008    /// `true` when this renderer runs on modest hardware: the CPU
2009    /// backend, or a GPU adapter that is not a discrete card
2010    /// (integrated / software / virtual). A hint for hosts to pick a
2011    /// lighter default render resolution — never consulted internally.
2012    #[must_use]
2013    pub fn is_low_power(&self) -> bool {
2014        match &self.inner {
2015            BackendImpl::Cpu(_) => true,
2016            BackendImpl::Gpu(g) => g.low_power(),
2017        }
2018    }
2019
2020    /// Upload an equirectangular sky panorama (RGBA8, `w×h`) for the
2021    /// GPU marcher's sky sampling. No-op on the CPU backend, which
2022    /// samples the [`Sky`] passed in each [`FrameParams`] instead.
2023    pub fn set_sky_panorama(&mut self, rgba: &[u8], w: u32, h: u32) {
2024        if let BackendImpl::Gpu(g) = &mut self.inner {
2025            g.set_sky_panorama(rgba, w, h);
2026        }
2027    }
2028
2029    /// Follow a window resize. CPU resizes its framebuffer lazily, so
2030    /// this only matters to the GPU swapchain — but it's safe to call
2031    /// for both.
2032    pub fn resize(&mut self, width: u32, height: u32) {
2033        match &mut self.inner {
2034            BackendImpl::Cpu(c) => c.resize(width, height),
2035            BackendImpl::Gpu(g) => g.resize(width, height),
2036        }
2037    }
2038
2039    /// Set the logical (fixed) render resolution (RP.0). The scene marches at
2040    /// the resolved logical size and is nearest-upscaled to the window, so the
2041    /// raycaster's cost — and thus FPS — stops depending on the window size.
2042    /// [`RenderResolution::Native`] (the default) keeps `logical == window`
2043    /// and is byte-identical to pre-RP rendering. Takes effect from the next
2044    /// [`render`](Self::render).
2045    pub fn set_render_resolution(&mut self, res: RenderResolution) {
2046        match &mut self.inner {
2047            BackendImpl::Cpu(c) => c.set_render_resolution(res),
2048            BackendImpl::Gpu(g) => g.set_render_resolution(res),
2049        }
2050    }
2051
2052    /// Set the supersampling factor (RP.1). `1` = off; `2` marches `2×2`
2053    /// samples per logical pixel and box-downfilters back before the upscale,
2054    /// anti-aliasing the retro grid. Clamped to `1..=4`. The marcher then runs
2055    /// at `logical_dims × factor` — predictable cost, independent of the window
2056    /// size. Takes effect from the next [`render`](Self::render).
2057    pub fn set_ssaa(&mut self, factor: u8) {
2058        match &mut self.inner {
2059            BackendImpl::Cpu(c) => c.set_ssaa(factor),
2060            BackendImpl::Gpu(g) => g.set_ssaa(factor),
2061        }
2062    }
2063
2064    /// The resolution the raycaster actually runs at this frame —
2065    /// `logical_dims × ssaa` (RP.1). Reflects the most recent window size,
2066    /// [`RenderResolution`], and SSAA factor.
2067    #[must_use]
2068    pub fn render_dims(&self) -> (u32, u32) {
2069        match &self.inner {
2070            BackendImpl::Cpu(c) => c.render_dims(),
2071            BackendImpl::Gpu(g) => g.render_dims(),
2072        }
2073    }
2074
2075    /// Set the reduced-palette posterize post (RP.2), or `None` to disable it
2076    /// (the default — RP.0/RP.1 paths verbatim). Quantization runs at the
2077    /// logical resolution in the resolve step, after the SSAA downfilter and
2078    /// before the nearest upscale, with the configured dither. Takes effect
2079    /// from the next [`render`](Self::render).
2080    pub fn set_posterize(&mut self, cfg: Option<PosterizeConfig>) {
2081        match &mut self.inner {
2082            BackendImpl::Cpu(c) => c.set_posterize(cfg),
2083            BackendImpl::Gpu(g) => g.set_posterize(cfg),
2084        }
2085    }
2086
2087    /// The logical (fixed) render-target size resolved against the current
2088    /// window size, per the active [`RenderResolution`].
2089    #[must_use]
2090    pub fn logical_dims(&self) -> (u32, u32) {
2091        match &self.inner {
2092            BackendImpl::Cpu(c) => c.logical_dims(),
2093            BackendImpl::Gpu(g) => g.logical_dims(),
2094        }
2095    }
2096
2097    /// One-call per-frame animation tick (QE.1b): drives **every**
2098    /// facade-owned animated collection, replacing the multi-call
2099    /// protocol hosts previously had to know (and could silently get
2100    /// wrong — a missed call meant frozen clips or unfaced
2101    /// billboards). Call once per frame before [`render`](Self::render):
2102    ///
2103    /// 1. [`advance_voxel_clips`](Self::advance_voxel_clips) —
2104    ///    auto-playing flipbook + streaming clip players;
2105    /// 2. every live character — skeleton + clip attachments (the
2106    ///    all-characters sweep of
2107    ///    [`advance_character`](Self::advance_character));
2108    /// 3. [`update_billboard_actors`](Self::update_billboard_actors) —
2109    ///    actor direction/state clips + camera facing;
2110    /// 4. [`face_billboards_to`](Self::face_billboards_to) — plain
2111    ///    billboard instances.
2112    ///
2113    /// The fine-grained methods stay public for hosts that need a
2114    /// custom per-entity `dt` (slow-motion on one character) or their
2115    /// own ordering — `tick` is the "do the right thing" default and
2116    /// is exactly equivalent to calling them in the order above.
2117    /// KFA sprites driven via
2118    /// [`update_kfa_poses`](Self::update_kfa_poses) remain a separate
2119    /// call (they mutate host-owned skeletons).
2120    pub fn tick(&mut self, camera: &Camera, dt: f64) {
2121        self.advance_voxel_clips(dt);
2122        let live: Vec<usize> = self.char_map.live_indices().collect();
2123        for idx in live {
2124            self.advance_character_at(idx, dt);
2125        }
2126        self.update_billboard_actors(camera, dt);
2127        self.face_billboards_to(camera);
2128    }
2129
2130    /// Composite `scene` from `camera` with `frame` params into the
2131    /// backend's frame buffer — **without presenting**. The CPU backend
2132    /// fills sky + runs the opticast compositor into an owned buffer;
2133    /// the GPU backend uploads/refreshes the scene, runs the compute
2134    /// marcher + sprite pass, and acquires (but does not present) the
2135    /// swapchain frame.
2136    ///
2137    /// Finish the frame with exactly one of [`present`](Self::present)
2138    /// (no overlay) or [`paint_egui`](Self::paint_egui) (UI overlay).
2139    /// Calling `render` again without finishing drops the pending frame.
2140    pub fn render(&mut self, scene: &mut Scene, camera: &Camera, frame: &FrameParams) {
2141        match &mut self.inner {
2142            BackendImpl::Cpu(c) => c.render(scene, camera, frame, &self.state),
2143            BackendImpl::Gpu(g) => g.render(scene, camera, frame, &self.state),
2144        }
2145        // The GPU mirrored its device palettes this frame if it needed
2146        // to; the CPU reads the table live. Either way the change flag
2147        // is consumed.
2148        self.state.materials_dirty = false;
2149    }
2150
2151    /// Draw world-space [`Line3`] segments over the frame
2152    /// [`render`](Self::render) composited, using that frame's camera +
2153    /// projection + depth buffer. Call **after** [`render`](Self::render)
2154    /// and **before** [`present`](Self::present) /
2155    /// [`paint_egui`](Self::paint_egui) — the lines land in the
2156    /// framebuffer, so a subsequent `paint_egui` still draws its panels
2157    /// on top.
2158    ///
2159    /// `camera` must be the one the last frame rendered with (the
2160    /// projection is taken from that frame). Depth-tested segments
2161    /// (`Line3::depth_test`) are occluded by nearer rendered geometry;
2162    /// always-on-top segments ignore depth. See [`Line3`] for colour /
2163    /// width / blend semantics.
2164    pub fn draw_lines(&mut self, camera: &Camera, lines: &[Line3]) {
2165        match &mut self.inner {
2166            BackendImpl::Cpu(c) => c.draw_lines(camera, lines),
2167            BackendImpl::Gpu(g) => g.draw_lines(camera, lines),
2168        }
2169    }
2170
2171    /// Upload (or replace) an RGBA8 image and return a stable [`ImageId`]
2172    /// to reference it in [`draw_images`](Self::draw_images). `rgba` is
2173    /// row-major, `width * height * 4` bytes, **straight** (un-premultiplied)
2174    /// alpha. The texture is retained until [`drop_image`](Self::drop_image),
2175    /// so the per-frame draw call stays cheap. Sampling is
2176    /// nearest-neighbour (pixel-art friendly — no blurring).
2177    ///
2178    /// Returns `None` for malformed input — a wrong byte count
2179    /// (`!= width·height·4`) or a zero dimension — so a bad upload can't be
2180    /// confused with the first valid id (`ImageId(0)`).
2181    pub fn upload_image(&mut self, rgba: &[u8], width: u32, height: u32) -> Option<ImageId> {
2182        if width == 0 || height == 0 || rgba.len() != (width as usize) * (height as usize) * 4 {
2183            return None;
2184        }
2185        let slot = match &mut self.inner {
2186            BackendImpl::Cpu(c) => c.upload_image(rgba, width, height),
2187            BackendImpl::Gpu(g) => g.upload_image(rgba, width, height),
2188        };
2189        Some(self.image_map.alloc(slot))
2190    }
2191
2192    /// Release a texture uploaded with [`upload_image`](Self::upload_image).
2193    /// Stale handles (already dropped, or aliasing a reused slot) are a
2194    /// safe no-op — ids are generational since QE-B6.
2195    pub fn drop_image(&mut self, id: ImageId) {
2196        let Some(slot) = self.image_map.index(id) else {
2197            return;
2198        };
2199        self.image_map.remove(id);
2200        match &mut self.inner {
2201            BackendImpl::Cpu(c) => c.drop_image(slot),
2202            BackendImpl::Gpu(g) => g.drop_image(slot),
2203        }
2204    }
2205
2206    /// Draw 2D [`ImageSprite`]s over the frame [`render`](Self::render)
2207    /// composited — flat textured quads placed in world space, using that
2208    /// frame's camera + projection + depth buffer. Same contract as
2209    /// [`draw_lines`](Self::draw_lines): call **after** [`render`](Self::render)
2210    /// and **before** [`present`](Self::present) / [`paint_egui`](Self::paint_egui).
2211    ///
2212    /// UVs are perspective-correct (no affine warp on an obliquely-viewed
2213    /// quad). Depth-tested sprites are occluded by nearer rendered
2214    /// geometry (with a bias to avoid z-fighting on a coincident face);
2215    /// the texture's straight alpha + the [`ImageSprite::tint`] composite
2216    /// over the scene. `camera` must be the one the last frame rendered.
2217    pub fn draw_images(&mut self, camera: &Camera, images: &[ImageSprite]) {
2218        if images.is_empty() {
2219            return;
2220        }
2221        let quads: Vec<QuadDraw> = images
2222            .iter()
2223            .filter_map(|s| {
2224                // QE-B6 — stale image handles draw nothing (vs aliasing
2225                // whatever texture reused the slot).
2226                let slot = self.image_map.index(s.image)?;
2227                let mut q = resolve_quad(s, camera)?;
2228                q.image = slot;
2229                Some(q)
2230            })
2231            .collect();
2232        if quads.is_empty() {
2233            return;
2234        }
2235        match &mut self.inner {
2236            BackendImpl::Cpu(c) => c.draw_images(camera, &quads),
2237            BackendImpl::Gpu(g) => g.draw_images(camera, &quads),
2238        }
2239    }
2240
2241    /// Project a world point to window pixel coordinates `(x, y)` under
2242    /// the projection the **last frame** rendered with — the backend-correct
2243    /// `world → screen` inverse of [`view_ray`](Self::view_ray). `None`
2244    /// before the first frame or for a point at/behind the camera near
2245    /// plane.
2246    ///
2247    /// Both backends honour their own projection (CPU `setcamera`
2248    /// `hx/hy/hz`, GPU vertical-FOV pinhole), so hosts never reconstruct
2249    /// it themselves. The returned `(x, y)` may fall outside `[0, w) ×
2250    /// [0, h)` for points off-screen but in front of the camera.
2251    #[must_use]
2252    pub fn project_point(&self, camera: &Camera, world: [f32; 3]) -> Option<(f32, f32)> {
2253        match &self.inner {
2254            BackendImpl::Cpu(c) => c.project_point(camera, world),
2255            BackendImpl::Gpu(g) => g.project_point(camera, world),
2256        }
2257    }
2258
2259    /// Screen→sprite pick: the nearest [`ImageSprite`] hit under window
2260    /// pixel `(x, y)`, resolving which texel was clicked. `sprites` is the
2261    /// same list passed to [`draw_images`](Self::draw_images) (image
2262    /// sprites are immediate-mode, so the caller owns the set). `None` for
2263    /// a miss.
2264    ///
2265    /// The ray is intersected with each quad's plane and mapped to its
2266    /// `uv` / source texel. A texel whose alpha is below the sprite's
2267    /// [`ImageSprite::alpha_cutoff`] (and any fully-transparent texel) is
2268    /// **see-through** — the pick passes through it to a sprite behind.
2269    /// For [`depth_test`](ImageSprite::depth_test) sprites the hit is
2270    /// rejected when nearer scene geometry occludes that pixel (shares the
2271    /// depth convention + bias of [`pick`](Self::pick); on the GPU backend
2272    /// the occlusion test costs a click-time depth readback).
2273    #[must_use]
2274    pub fn pick_image(
2275        &self,
2276        camera: &Camera,
2277        x: f64,
2278        y: f64,
2279        sprites: &[ImageSprite],
2280    ) -> Option<ImagePickHit> {
2281        if sprites.is_empty() {
2282            return None;
2283        }
2284        let dir = self.pixel_ray(camera, x, y)?;
2285        let dir = [dir[0] as f32, dir[1] as f32, dir[2] as f32];
2286        let dir_len = v_dot(dir, dir).sqrt();
2287        if dir_len < 1e-9 {
2288            return None;
2289        }
2290        let origin = [
2291            camera.pos[0] as f32,
2292            camera.pos[1] as f32,
2293            camera.pos[2] as f32,
2294        ];
2295        // Scene surface distance under this pixel (sky / no-hit → None);
2296        // used to occlude depth-tested sprites. Same metric as `pick`.
2297        let scene_t = self.pick_depth(x as u32, y as u32);
2298
2299        let mut best: Option<ImagePickHit> = None;
2300        for sprite in sprites {
2301            // Reuse the render-path resolve (back-face cull included), so
2302            // a single-sided quad that isn't drawn also can't be picked.
2303            let Some(q) = resolve_quad(sprite, camera) else {
2304                continue;
2305            };
2306            let Some(([a, b], t)) = ray_quad_uv(origin, dir, &q.corners) else {
2307                continue; // miss / parallel / behind
2308            };
2309            let d_eucl = t * dir_len;
2310            if best.is_some_and(|cur| d_eucl >= cur.t) {
2311                continue; // a nearer sprite already won
2312            }
2313            let p = v_add(origin, v_scale(dir, t));
2314
2315            let Some((iw, ih)) = self.image_dims(sprite.image) else {
2316                continue; // dropped / unknown image
2317            };
2318            let tx = ((a * iw as f32) as i32).clamp(0, iw as i32 - 1) as u32;
2319            let ty = ((b * ih as f32) as i32).clamp(0, ih as i32 - 1) as u32;
2320
2321            // See-through test: a texel is solid when its alpha clears the
2322            // cutoff (and a fully-transparent texel is never solid).
2323            let cutoff_u8 = (sprite.alpha_cutoff.clamp(0.0, 1.0) * 255.0) as u32;
2324            let solid_thresh = cutoff_u8.max(1);
2325            if u32::from(self.image_alpha_at(sprite.image, tx, ty)) < solid_thresh {
2326                continue;
2327            }
2328
2329            // Occlusion: a depth-tested sprite behind nearer geometry loses.
2330            if sprite.depth_test {
2331                if let Some(st) = scene_t {
2332                    if d_eucl > st + PICK_DEPTH_BIAS {
2333                        continue;
2334                    }
2335                }
2336            }
2337
2338            best = Some(ImagePickHit {
2339                image: sprite.image,
2340                uv: [a, b],
2341                texel: (tx, ty),
2342                world: p,
2343                t: d_eucl,
2344            });
2345        }
2346        best
2347    }
2348
2349    /// Source dimensions of an uploaded image, or `None` if the id was
2350    /// dropped / never uploaded. Internal helper for [`Self::pick_image`].
2351    fn image_dims(&self, id: ImageId) -> Option<(u32, u32)> {
2352        let slot = self.image_map.index(id)?;
2353        match &self.inner {
2354            BackendImpl::Cpu(c) => c.image_dims(slot),
2355            BackendImpl::Gpu(g) => g.image_dims(slot),
2356        }
2357    }
2358
2359    /// Alpha byte of texel `(tx, ty)` in an uploaded image (`0` for an
2360    /// unknown id / out-of-range texel). Internal helper for
2361    /// [`Self::pick_image`].
2362    fn image_alpha_at(&self, id: ImageId, tx: u32, ty: u32) -> u8 {
2363        let Some(slot) = self.image_map.index(id) else {
2364            return 0;
2365        };
2366        match &self.inner {
2367            BackendImpl::Cpu(c) => c.image_alpha_at(slot, tx, ty),
2368            BackendImpl::Gpu(g) => g.image_alpha_at(slot, tx, ty),
2369        }
2370    }
2371
2372    /// Mirror the rendered 3D scene horizontally before display. The flip is
2373    /// applied *before* any egui overlay, so the UI stays upright while the
2374    /// viewport un-mirrors — a fix for the engine's left-handed render.
2375    /// Supported on both backends (CPU reverses the framebuffer rows; GPU
2376    /// mirrors the scene blit + line/image overlays). Picking/projection are
2377    /// unchanged, so a host that flips must mirror its cursor X (`width - x`)
2378    /// for ray casts.
2379    pub fn set_flip_x(&mut self, flip: bool) {
2380        match &mut self.inner {
2381            BackendImpl::Cpu(c) => c.set_flip_x(flip),
2382            BackendImpl::Gpu(g) => g.set_flip_x(flip),
2383        }
2384    }
2385
2386    /// Present the frame [`render`](Self::render) composited, with no UI
2387    /// overlay. Pairs with `render`; use [`paint_egui`](Self::paint_egui)
2388    /// instead to overlay an egui UI before presenting.
2389    pub fn present(&mut self) {
2390        match &mut self.inner {
2391            BackendImpl::Cpu(c) => c.present(),
2392            BackendImpl::Gpu(g) => g.present(),
2393        }
2394    }
2395
2396    /// Block until the active backend has finished all in-flight work, ready
2397    /// for a clean teardown. On the GPU backend this drains the device queue
2398    /// and releases any acquired-but-unpresented swapchain frame; on the CPU
2399    /// backend it is a no-op (nothing is in flight).
2400    ///
2401    /// Call this at shutdown **before dropping the renderer and its window**,
2402    /// so the GPU device/surface tear down with no commands queued and no
2403    /// half-presented frame. Skipping it (or dropping the window first) can
2404    /// leave the driver/compositor showing stale buffers after an exit — the
2405    /// "leftover triangles / flicker" symptom of an unclean shutdown.
2406    pub fn wait_idle(&mut self) {
2407        match &mut self.inner {
2408            BackendImpl::Cpu(c) => c.wait_idle(),
2409            BackendImpl::Gpu(g) => g.wait_idle(),
2410        }
2411    }
2412
2413    /// Composite `scene` and return a [`Frame`] guard — the type-state
2414    /// form of the `render → overlays → present`/`paint_egui` protocol
2415    /// (QE-B6), which the split calls enforce by documentation only.
2416    /// With the guard, misuse is unrepresentable: overlays can only be
2417    /// drawn on a live frame (with the camera it was rendered with —
2418    /// the guard holds it), presenting consumes the guard so a double
2419    /// present can't compile, and *dropping* an unfinished frame
2420    /// presents it — a bare `renderer.frame(..);` shows the frame.
2421    ///
2422    /// ```ignore
2423    /// renderer
2424    ///     .frame(&mut scene, &camera, &params)
2425    ///     .draw_lines(&gizmo)
2426    ///     .present(); // or .paint_egui(..); or just drop it
2427    /// ```
2428    ///
2429    /// The split [`render`](Self::render) / [`present`](Self::present)
2430    /// calls remain available for hosts that need custom control flow
2431    /// between the stages.
2432    pub fn frame(&mut self, scene: &mut Scene, camera: &Camera, params: &FrameParams) -> Frame<'_> {
2433        self.render(scene, camera, params);
2434        Frame {
2435            renderer: self,
2436            camera: *camera,
2437            finished: false,
2438        }
2439    }
2440
2441    /// Overlay an egui UI on the frame [`render`](Self::render)
2442    /// composited, then present it (`hud` feature). The host runs egui
2443    /// itself (e.g. `egui` + `egui-winit`) and passes the tessellated
2444    /// `jobs` ([`egui::Context::tessellate`]) and the per-frame
2445    /// `textures` delta from [`egui::FullOutput`]; `pixels_per_point` is
2446    /// the UI scale (`ctx.pixels_per_point()`).
2447    ///
2448    /// The GPU backend paints via `egui-wgpu`; the CPU backend
2449    /// software-rasterises the tessellation into its framebuffer. Use
2450    /// this **instead of** [`present`](Self::present) — both finish the
2451    /// frame.
2452    #[cfg(feature = "hud")]
2453    pub fn paint_egui(
2454        &mut self,
2455        jobs: &[egui::ClippedPrimitive],
2456        textures: &egui::TexturesDelta,
2457        pixels_per_point: f32,
2458    ) {
2459        match &mut self.inner {
2460            BackendImpl::Cpu(c) => c.paint_egui(jobs, textures, pixels_per_point),
2461            BackendImpl::Gpu(g) => g.paint_egui(jobs, textures, pixels_per_point),
2462        }
2463    }
2464
2465    /// Reset the whole sprite world: every model, dynamic instance,
2466    /// voxel clip, streaming clip, character, billboard and actor is
2467    /// dropped, and **every outstanding handle from any of those
2468    /// families goes stale** (resolving to safe no-ops — the maps are
2469    /// generational). The explicit scene-switch verb (QE-B6): what the
2470    /// demo host does between scenes, without the "register an empty
2471    /// set" idiom spelling it.
2472    pub fn clear_sprites(&mut self) {
2473        self.set_sprites(&SpriteSet {
2474            models: Vec::new(),
2475            instances: Vec::new(),
2476            carve_model: None,
2477        });
2478    }
2479
2480    /// Register sprite models + instances — **replacing the whole
2481    /// sprite world**. This is a bulk *set*, not an append: every
2482    /// handle family (models, dynamic instances, clips, streaming
2483    /// clips, characters, billboards, actors) is reset and previously
2484    /// issued handles go stale (safe no-ops). Call once at setup, or
2485    /// again to replace everything; to build up incrementally instead,
2486    /// use [`add_sprite_model`](Self::add_sprite_model) /
2487    /// [`add_sprite_instance`](Self::add_sprite_instance) &c., and to
2488    /// drop everything use [`clear_sprites`](Self::clear_sprites).
2489    pub fn set_sprites(&mut self, set: &SpriteSet) -> Vec<SpriteModelId> {
2490        match &mut self.inner {
2491            BackendImpl::Cpu(c) => c.set_sprites(set),
2492            BackendImpl::Gpu(g) => g.set_sprites(set),
2493        }
2494        // A fresh sprite set replaces the instance world, so any
2495        // previously added dynamic instances + models are gone — drop their
2496        // handles and re-seat the model slotmap with `set.models.len()`
2497        // live ids `0..n` (model index = chain id on both backends).
2498        self.dyn_map = DynInstanceMap::default();
2499        self.model_map.reset_live(set.models.len());
2500        // A full sprite rebuild drops the dynamic + clip layers on both
2501        // backends (the GPU registry is replaced), so reset the clip +
2502        // character maps too.
2503        self.clip_map.reset();
2504        self.char_map.reset();
2505        self.char_instances.clear();
2506        self.streaming_map.reset();
2507        self.streaming_clips.clear();
2508        self.clip_meta.clear();
2509        self.clip_players.clear();
2510        self.billboards.clear();
2511        self.actor_map.reset();
2512        self.billboard_actors.clear();
2513        self.state.dyn_clip.clear();
2514        (0..set.models.len() as u32)
2515            .map(|slot| self.model_map.minted(slot))
2516            .collect()
2517    }
2518
2519    /// Re-register one sprite model's geometry after you've edited its
2520    /// content (a carve or recolour of its `kv6`). `model` is the
2521    /// [`SpriteModelId`] handed back by [`set_sprites`](Self::set_sprites);
2522    /// `kv6` is the model's **new** geometry — the caller owns the source
2523    /// of truth (e.g. a dense carve grid the surface-only `kv6` can't
2524    /// represent) and supplies the refreshed mesh here.
2525    ///
2526    /// This is a **backend-agnostic content refresh**, not a GPU upload:
2527    /// the renderer brings its stored model up to date however its active
2528    /// backend needs to. The instance set is left untouched (an edit never
2529    /// moves or adds an instance), so on the GPU backend only that one
2530    /// model's voxel data is re-uploaded — through a slack-backed
2531    /// suballocator, one model's bytes rather than the whole registry —
2532    /// while the CPU backend swaps the cached `kv6` into each instance of
2533    /// the model. Use [`set_sprites`](Self::set_sprites) to add/remove
2534    /// models or change the instance set.
2535    pub fn refresh_sprite_model(&mut self, model: SpriteModelId, kv6: &Kv6) {
2536        let Some(idx) = self.model_map.index(model) else {
2537            return; // stale / removed handle → no-op
2538        };
2539        match &mut self.inner {
2540            BackendImpl::Cpu(c) => c.update_sprite_model(idx, kv6),
2541            BackendImpl::Gpu(g) => g.update_sprite_model(idx, kv6),
2542        }
2543    }
2544
2545    /// Like [`refresh_sprite_model`](Self::refresh_sprite_model) but also
2546    /// re-classifies the refreshed voxels into per-voxel material ids by
2547    /// colour (TV.3) via `material_map` — used by the material-aware streaming
2548    /// clip path so a re-uploaded frame keeps its per-voxel materials. An
2549    /// empty map matches `refresh_sprite_model`.
2550    pub fn refresh_sprite_model_with_materials(
2551        &mut self,
2552        model: SpriteModelId,
2553        kv6: &Kv6,
2554        material_map: &[(Rgb, u8)],
2555    ) {
2556        let Some(idx) = self.model_map.index(model) else {
2557            return; // stale / removed handle → no-op
2558        };
2559        match &mut self.inner {
2560            BackendImpl::Cpu(c) => {
2561                c.update_sprite_model_with_materials(idx, kv6, Some(material_map));
2562            }
2563            BackendImpl::Gpu(g) => g.update_sprite_model_with_materials(idx, kv6, material_map),
2564        }
2565    }
2566
2567    /// Add one sprite instance of an already-registered `model` at world
2568    /// `pos`, **incrementally** — the cheap streaming-spawn path that both
2569    /// backends now share (GPU: append to the instance buffer, growing by
2570    /// powers of two; CPU: push one pre-posed [`Sprite`]). Returns a
2571    /// stable [`SpriteInstanceId`] for later removal.
2572    ///
2573    /// `model` must be a [`SpriteModelId`] from the current
2574    /// [`set_sprites`](Self::set_sprites) (a model registered there, even
2575    /// with zero initial instances). Dynamic instances live *after* the
2576    /// static set + any KFA limbs, so register those first.
2577    ///
2578    /// Returns `None` — spawning nothing — on a stale/removed `model`
2579    /// handle (QE.1c; previously a silent sentinel id).
2580    pub fn add_sprite_instance(
2581        &mut self,
2582        model: SpriteModelId,
2583        pos: [f32; 3],
2584    ) -> Option<SpriteInstanceId> {
2585        self.add_sprite_instance_posed(
2586            model,
2587            DynSpriteTransform {
2588                pos,
2589                ..DynSpriteTransform::default()
2590            },
2591        )
2592    }
2593
2594    /// Add one sprite instance of an already-registered `model`,
2595    /// pre-posed with the orientation in `xf` — the streaming-spawn path
2596    /// for objects that appear mid-flight already rotated (so there's no
2597    /// one-frame axis-aligned flash before the first
2598    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)).
2599    /// Otherwise identical to
2600    /// [`add_sprite_instance`](Self::add_sprite_instance) (which is just
2601    /// this with the identity basis). Returns a stable
2602    /// [`SpriteInstanceId`].
2603    ///
2604    /// Returns `None` — spawning nothing — on a stale/removed `model`
2605    /// handle (QE.1c; previously a silent sentinel id). `xf`'s basis
2606    /// must be non-singular; a degenerate one makes the instance
2607    /// silently skip drawing (see [`DynSpriteTransform`]).
2608    pub fn add_sprite_instance_posed(
2609        &mut self,
2610        model: SpriteModelId,
2611        xf: DynSpriteTransform,
2612    ) -> Option<SpriteInstanceId> {
2613        let idx = self.model_map.index(model)?;
2614        let dyn_index = match &mut self.inner {
2615            BackendImpl::Cpu(c) => c.add_dyn_instance_posed(idx, xf),
2616            BackendImpl::Gpu(g) => g.add_dyn_instance_posed(idx, xf),
2617        }?;
2618        self.state.dyn_clip.push(None); // a plain model instance
2619        Some(self.dyn_map.alloc(dyn_index as u32))
2620    }
2621
2622    /// Remove a dynamic sprite instance added by
2623    /// [`add_sprite_instance`](Self::add_sprite_instance). O(1) on both
2624    /// backends (swap-remove); other dynamic handles stay valid. Returns
2625    /// `false` if the handle is stale / already removed.
2626    pub fn remove_sprite_instance(&mut self, id: SpriteInstanceId) -> bool {
2627        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2628            return false;
2629        };
2630        let moved = match &mut self.inner {
2631            BackendImpl::Cpu(c) => c.remove_dyn_instance(dyn_index as usize),
2632            BackendImpl::Gpu(g) => g.remove_dyn_instance(dyn_index as usize),
2633        };
2634        // Mirror the backend's swap-remove on the facade's parallel
2635        // clip bookkeeping (QE.3a).
2636        self.state.dyn_clip.swap_remove(dyn_index as usize);
2637        self.dyn_map.remove(id, dyn_index, moved.map(|m| m as u32));
2638        true
2639    }
2640
2641    /// Number of live dynamic sprite instances (those added via
2642    /// [`add_sprite_instance`](Self::add_sprite_instance)).
2643    #[must_use]
2644    pub fn dynamic_sprite_count(&self) -> usize {
2645        self.dyn_map.order.len()
2646    }
2647
2648    /// Define a global voxel **material** (TV stage): the opacity + blend
2649    /// mode that a per-voxel material id resolves to. The renderer owns one
2650    /// 256-entry palette shared by every model and grid.
2651    ///
2652    /// Id `0` is permanently [`Material::OPAQUE`] — the value every voxel
2653    /// without explicit material data resolves to — and **cannot** be
2654    /// redefined; passing `id == 0` is a no-op that returns `false`. Any
2655    /// other id returns `true`.
2656    ///
2657    /// While no translucent material is defined the renderer stays on the
2658    /// fully-opaque fast path, so this is inert until first called. See
2659    /// `PORTING-TRANSPARENCY.md`.
2660    pub fn define_material(&mut self, id: u8, mat: Material) -> bool {
2661        let changed = self.state.materials.set(id, mat);
2662        if changed {
2663            self.state.materials_dirty = true;
2664        }
2665        changed
2666    }
2667
2668    /// The [`Material`] currently at palette `id` ([`Material::OPAQUE`] for
2669    /// any id never passed to [`define_material`](Self::define_material)).
2670    #[must_use]
2671    pub fn material(&self, id: u8) -> Material {
2672        self.state.materials.get(id)
2673    }
2674
2675    /// Set the **terrain** colour→material map (TV.4): pairs of `(rgb,
2676    /// material_id)` that make matching-colour world (grid) voxels translucent
2677    /// — glass walls, water pools. The materials themselves are defined via
2678    /// [`define_material`](Self::define_material). An empty map (the default)
2679    /// keeps all terrain opaque. The CPU backend composites these today; the
2680    /// GPU backend renders them once the TV.6 device path lands.
2681    pub fn set_terrain_materials(&mut self, map: &[(Rgb, u8)]) {
2682        if self.state.terrain_materials != map {
2683            self.state.terrain_materials = map.to_vec();
2684            self.state.materials_dirty = true;
2685        }
2686    }
2687
2688    /// Register one new sprite **model** incrementally from `kv6`,
2689    /// **without** rebuilding the existing model set — the streaming-in
2690    /// counterpart to [`add_sprite_instance`](Self::add_sprite_instance)
2691    /// for unique generated geometry (procedural asteroids, debris).
2692    /// Returns a stable [`SpriteModelId`] usable immediately with
2693    /// [`add_sprite_instance`](Self::add_sprite_instance) /
2694    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed).
2695    ///
2696    /// Works before any [`set_sprites`](Self::set_sprites) (it establishes
2697    /// residency on the GPU backend's first model). The GPU backend
2698    /// appends one LOD chain to the resident registry (amortised O(model
2699    /// voxels)); the CPU backend pushes an axis-aligned template.
2700    pub fn add_sprite_model(&mut self, kv6: &Kv6) -> SpriteModelId {
2701        let model_index = match &mut self.inner {
2702            BackendImpl::Cpu(c) => c.add_model(kv6),
2703            BackendImpl::Gpu(g) => g.add_model(kv6),
2704        };
2705        self.model_map.alloc(model_index as u32)
2706    }
2707
2708    /// Register a **mixed-material** sprite model (TV.3): `material_map` pairs
2709    /// a voxel RGB colour (`0xRRGGBB`) with a material id (defined via
2710    /// [`define_material`](Self::define_material)), so a single model can mix
2711    /// opaque and translucent voxels — an opaque window frame around glass, a
2712    /// bottle around a translucent potion. Voxels whose colour isn't in the
2713    /// map are opaque (material 0). Like [`add_sprite_model`](Self::add_sprite_model)
2714    /// otherwise.
2715    ///
2716    /// The CPU backend composites per-voxel materials today; the GPU backend
2717    /// carries the data and renders per-voxel materials once the TV.3b device
2718    /// path lands (until then it uses the instance's uniform material).
2719    pub fn add_sprite_model_with_materials(
2720        &mut self,
2721        kv6: &Kv6,
2722        material_map: &[(Rgb, u8)],
2723    ) -> SpriteModelId {
2724        let model_index = match &mut self.inner {
2725            BackendImpl::Cpu(c) => c.add_model_with_materials(kv6, material_map),
2726            BackendImpl::Gpu(g) => g.add_model_with_materials(kv6, material_map),
2727        };
2728        self.model_map.alloc(model_index as u32)
2729    }
2730
2731    /// Remove a registered sprite model, freeing its voxel data. Returns
2732    /// `false` if `id` is stale / already removed.
2733    ///
2734    /// The model's slot is tombstoned **in place**: its id is never
2735    /// reused, so every other [`SpriteModelId`] stays valid (no remap).
2736    /// Existing instances of the removed model are **not** dropped here —
2737    /// they linger but draw as nothing on the GPU backend (the CPU
2738    /// backend keeps each instance's own kv6 clone, so they keep drawing
2739    /// until removed via
2740    /// [`remove_sprite_instance`](Self::remove_sprite_instance)); remove
2741    /// them when convenient. Call
2742    /// [`compact_sprite_models`](Self::compact_sprite_models) afterwards
2743    /// to reclaim the GPU buffer holes.
2744    pub fn remove_sprite_model(&mut self, id: SpriteModelId) -> bool {
2745        let Some(idx) = self.model_map.index(id) else {
2746            return false;
2747        };
2748        match &mut self.inner {
2749            BackendImpl::Cpu(c) => c.remove_model(idx),
2750            BackendImpl::Gpu(g) => g.remove_model(idx),
2751        }
2752        self.model_map.remove(id)
2753    }
2754
2755    /// Reclaim the GPU buffer space left by
2756    /// [`remove_sprite_model`](Self::remove_sprite_model) by repacking the
2757    /// resident registry to its live models only. Model ids are preserved
2758    /// (no remap). O(live voxel volume) — call it when many models have
2759    /// been removed, not every frame. No-op on the CPU backend (which
2760    /// keeps cheap empty placeholders) and when nothing was removed.
2761    pub fn compact_sprite_models(&mut self) {
2762        match &mut self.inner {
2763            BackendImpl::Cpu(c) => c.compact_models(),
2764            BackendImpl::Gpu(g) => g.compact_models(),
2765        }
2766    }
2767
2768    /// Update one dynamic instance's full pose (position + orientation)
2769    /// for this frame. `id` is from
2770    /// [`add_sprite_instance`](Self::add_sprite_instance) /
2771    /// [`add_sprite_instance_posed`](Self::add_sprite_instance_posed). A
2772    /// stale / removed handle is a no-op.
2773    ///
2774    /// For many instances per frame prefer
2775    /// [`set_sprite_instance_transforms`](Self::set_sprite_instance_transforms):
2776    /// the GPU backend flushes all pending pose changes to the device
2777    /// once per [`render`](Self::render), so a per-instance call here is
2778    /// still O(1) device work, but the batch variant avoids re-walking
2779    /// the slotmap.
2780    pub fn set_sprite_instance_transform(&mut self, id: SpriteInstanceId, xf: DynSpriteTransform) {
2781        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2782            return;
2783        };
2784        match &mut self.inner {
2785            BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
2786            BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
2787        }
2788    }
2789
2790    /// Batch form of
2791    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
2792    /// — apply many `(instance, pose)` updates in one call. Stale handles
2793    /// in `updates` are skipped. On the GPU backend this marks the
2794    /// instance buffer dirty once and uploads the new poses a single time
2795    /// at the next [`render`](Self::render), so spinning a whole cluster
2796    /// of instances per frame is one device upload, not one per instance.
2797    pub fn set_sprite_instance_transforms(
2798        &mut self,
2799        updates: &[(SpriteInstanceId, DynSpriteTransform)],
2800    ) {
2801        for &(id, xf) in updates {
2802            let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2803                continue;
2804            };
2805            match &mut self.inner {
2806                BackendImpl::Cpu(c) => c.set_dyn_instance_transform(dyn_index as usize, xf),
2807                BackendImpl::Gpu(g) => g.set_dyn_instance_transform(dyn_index as usize, xf),
2808            }
2809        }
2810    }
2811
2812    /// Set sprite instance `id`'s voxel-material id (TV stage) — indexes the
2813    /// global palette defined via [`define_material`](Self::define_material)
2814    /// for this whole instance's opacity + blend mode. `0` (the default) is
2815    /// opaque. Stale handles are ignored.
2816    ///
2817    /// Only the CPU backend composites translucent sprites today; the GPU
2818    /// backend retains the value for the forthcoming device-side path (see
2819    /// `PORTING-TRANSPARENCY.md`).
2820    pub fn set_sprite_instance_material(&mut self, id: SpriteInstanceId, material: u8) {
2821        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2822            return;
2823        };
2824        match &mut self.inner {
2825            BackendImpl::Cpu(c) => c.set_dyn_instance_material(dyn_index as usize, material),
2826            BackendImpl::Gpu(g) => g.set_dyn_instance_material(dyn_index as usize, material),
2827        }
2828    }
2829
2830    /// Set sprite instance `id`'s per-instance alpha multiplier (TV stage),
2831    /// `0..=255` (`255` = unscaled). Scales the material's opacity so an
2832    /// effect can fade out by cheap per-frame updates without re-uploading
2833    /// its volume. Stale handles are ignored.
2834    pub fn set_sprite_instance_alpha(&mut self, id: SpriteInstanceId, alpha_mul: u8) {
2835        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2836            return;
2837        };
2838        match &mut self.inner {
2839            BackendImpl::Cpu(c) => c.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
2840            BackendImpl::Gpu(g) => g.set_dyn_instance_alpha(dyn_index as usize, alpha_mul),
2841        }
2842    }
2843
2844    /// Set sprite instance `id`'s per-instance **RGB tint**, packed
2845    /// `0x00RRGGBB`: every rendered voxel's colour is multiplied by it (per
2846    /// channel), so instances of one model can be recoloured cheaply per frame.
2847    /// `0x00FF_FFFF` (white, the default) is a no-op. Works on both backends;
2848    /// stale handles are ignored. Tint is colour only — for transparency, use a
2849    /// translucent material with
2850    /// [`set_sprite_instance_alpha`](Self::set_sprite_instance_alpha).
2851    pub fn set_sprite_instance_tint(&mut self, id: SpriteInstanceId, tint: Rgb) {
2852        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2853            return;
2854        };
2855        match &mut self.inner {
2856            BackendImpl::Cpu(c) => c.set_dyn_instance_tint(dyn_index as usize, tint.0),
2857            BackendImpl::Gpu(g) => g.set_dyn_instance_tint(dyn_index as usize, tint.0),
2858        }
2859    }
2860
2861    /// Toggle a sprite/clip instance's shadow participation **live**
2862    /// (XS.4 flags, BB.3). [`ShadowFlags::default`] (both on) is what
2863    /// every spawn starts with. The per-instance counterpart to the
2864    /// template-level `Sprite::with_casts_shadow` /
2865    /// `with_receives_shadow` — e.g. a flat additive glow billboard
2866    /// that should not cast, or a UI marker that ignores shadows.
2867    /// Other flag bits are preserved. No-op on a stale id.
2868    ///
2869    /// QE.7b — takes [`ShadowFlags`] instead of the old unreadable
2870    /// `(id, true, false)` bool pair; migrate with
2871    /// `ShadowFlags { casts, receives }`.
2872    pub fn set_sprite_instance_shadow_flags(&mut self, id: SpriteInstanceId, shadows: ShadowFlags) {
2873        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2874            return;
2875        };
2876        match &mut self.inner {
2877            BackendImpl::Cpu(c) => {
2878                c.set_dyn_instance_shadow_flags(
2879                    dyn_index as usize,
2880                    shadows.casts,
2881                    shadows.receives,
2882                );
2883            }
2884            BackendImpl::Gpu(g) => {
2885                g.set_dyn_instance_shadow_flags(
2886                    dyn_index as usize,
2887                    shadows.casts,
2888                    shadows.receives,
2889                );
2890            }
2891        }
2892    }
2893
2894    /// Set a sprite/clip instance's **lighting mode** live (BB.2b): how its
2895    /// shading normal is derived ([`BillboardLighting`]). Useful for
2896    /// camera-facing billboards whose face normal would otherwise track the
2897    /// camera. Other flag bits are preserved; only affects the dynamic
2898    /// lighting path. No-op on a stale id.
2899    pub fn set_sprite_instance_lighting(&mut self, id: SpriteInstanceId, mode: BillboardLighting) {
2900        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
2901            return;
2902        };
2903        match &mut self.inner {
2904            BackendImpl::Cpu(c) => c.set_dyn_instance_lighting(dyn_index as usize, mode),
2905            BackendImpl::Gpu(g) => g.set_dyn_instance_lighting(dyn_index as usize, mode),
2906        }
2907    }
2908
2909    // ---- animated voxel clips (VCL.4) ------------------------------------
2910
2911    /// Register an animated voxel clip ("GIF/MP4 for voxels"): decode all
2912    /// its frames and upload the flipbook to the active backend (GPU: one
2913    /// LOD chain per frame; CPU: a cached dense grid per frame). Returns a
2914    /// [`VoxelClipId`] to spawn instances of it via
2915    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed).
2916    ///
2917    /// Build the [`DecodedClip`] from a `.rvc` via
2918    /// [`VoxelClip::decode`](roxlap_formats::voxel_clip::VoxelClip::decode).
2919    /// Like [`add_sprite_model`](Self::add_sprite_model), this works before
2920    /// any [`set_sprites`](Self::set_sprites); a later `set_sprites`
2921    /// **drops** all registered clips (re-register afterwards).
2922    pub fn add_voxel_clip(&mut self, clip: &DecodedClip) -> VoxelClipId {
2923        self.add_voxel_clip_with_materials(clip, &[])
2924    }
2925
2926    /// Register a **mixed-material** animated voxel clip (TV.3): the clip
2927    /// analogue of
2928    /// [`add_sprite_model_with_materials`](Self::add_sprite_model_with_materials).
2929    /// `material_map` pairs a voxel RGB colour (`0xRRGGBB`) with a material id
2930    /// (defined via [`define_material`](Self::define_material)), classifying
2931    /// every frame's voxels so an animated clip can mix opaque and translucent
2932    /// voxels — an opaque torch handle around an additive flame, a spinning
2933    /// glass orb. Voxels whose colour isn't in the map stay opaque
2934    /// (material 0). Like [`add_voxel_clip`](Self::add_voxel_clip) otherwise.
2935    pub fn add_voxel_clip_with_materials(
2936        &mut self,
2937        clip: &DecodedClip,
2938        material_map: &[(Rgb, u8)],
2939    ) -> VoxelClipId {
2940        let clip_index = match &mut self.inner {
2941            BackendImpl::Cpu(c) => c.add_voxel_clip_with_materials(clip, material_map),
2942            BackendImpl::Gpu(g) => g.add_voxel_clip_with_materials(clip, material_map),
2943        };
2944        // Capture metadata for editor queries + #6 auto-play; clip indices
2945        // are sequential and parallel to `clip_meta`.
2946        debug_assert_eq!(clip_index, self.clip_meta.len());
2947        self.clip_meta.push(ClipMeta {
2948            dims: clip.dims,
2949            pivot: clip.pivot,
2950            voxel_world_size: clip.voxel_world_size,
2951            durations: clip.durations.clone(),
2952            loop_mode: clip.loop_mode,
2953            material_map: material_map.to_vec(),
2954        });
2955        self.clip_map.alloc(clip_index as u32)
2956    }
2957
2958    /// Remove a registered clip, freeing its per-frame volumes. Instances
2959    /// of it linger but draw nothing until removed via
2960    /// [`remove_sprite_instance`](Self::remove_sprite_instance). Returns
2961    /// `false` if `id` is stale / already removed.
2962    pub fn remove_voxel_clip(&mut self, id: VoxelClipId) -> bool {
2963        let Some(clip_index) = self.clip_map.index(id) else {
2964            return false;
2965        };
2966        match &mut self.inner {
2967            BackendImpl::Cpu(c) => c.remove_voxel_clip(clip_index),
2968            BackendImpl::Gpu(g) => g.remove_voxel_clip(clip_index),
2969        }
2970        // Detach instances that were playing this clip so they stop
2971        // being treated as clip instances (QE.3a — facade bookkeeping;
2972        // was duplicated in both backends).
2973        for slot in &mut self.state.dyn_clip {
2974            if matches!(slot, Some((c, _)) if *c == clip_index) {
2975                *slot = None;
2976            }
2977        }
2978        self.clip_map.remove(id)
2979    }
2980
2981    /// Spawn an instance of clip `clip`, posed by `xf`, starting on frame
2982    /// 0. Returns a [`SpriteInstanceId`] — a clip instance is a dynamic
2983    /// sprite instance, so move it with
2984    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform),
2985    /// advance its frame with
2986    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame), and drop
2987    /// it with [`remove_sprite_instance`](Self::remove_sprite_instance).
2988    /// Returns `None` — spawning nothing — on a stale/removed `clip`
2989    /// handle (QE.1c; previously a silent sentinel id).
2990    ///
2991    /// This instance has **no playback clock**: drive its frame yourself via
2992    /// [`set_clip_instance_frame`](Self::set_clip_instance_frame) (frame-based
2993    /// scrubbing). For *clock*-based control — auto-advance, play/pause, or
2994    /// [`set_clip_instance_clock_ms`](Self::set_clip_instance_clock_ms)
2995    /// scrubbing — spawn with
2996    /// [`add_clip_instance_playing`](Self::add_clip_instance_playing) instead
2997    /// (the player-control methods no-op on an instance with no player).
2998    pub fn add_clip_instance_posed(
2999        &mut self,
3000        clip: VoxelClipId,
3001        xf: DynSpriteTransform,
3002    ) -> Option<SpriteInstanceId> {
3003        let clip_index = self.clip_map.index(clip)?;
3004        let dyn_index = match &mut self.inner {
3005            BackendImpl::Cpu(c) => c.add_clip_instance(clip_index, xf),
3006            BackendImpl::Gpu(g) => g.add_clip_instance(clip_index, xf),
3007        }?;
3008        self.state.dyn_clip.push(Some((clip_index, 0)));
3009        Some(self.dyn_map.alloc(dyn_index as u32))
3010    }
3011
3012    /// Select which frame a clip instance shows — the per-frame playback
3013    /// step. Cheap on both backends (GPU: swap the instance's model id;
3014    /// CPU: select the cached frame grid), with no volume re-upload. Drive
3015    /// it from a playback clock via
3016    /// [`DecodedClip::frame_at`](roxlap_formats::voxel_clip::DecodedClip::frame_at).
3017    /// No-op on a stale id or a non-clip instance.
3018    pub fn set_clip_instance_frame(&mut self, id: SpriteInstanceId, frame: u32) {
3019        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
3020            return;
3021        };
3022        let frame = frame as usize;
3023        let Some(Some((clip_index, cur_frame))) = self.state.dyn_clip.get_mut(dyn_index as usize)
3024        else {
3025            return; // not a clip instance
3026        };
3027        // PF.5 — same-frame guard: a player ticking at render rate
3028        // re-applies the same frame most ticks; skip the bookkeeping +
3029        // GPU writes (QE.3a: the guard now covers both backends).
3030        if *cur_frame == frame {
3031            return;
3032        }
3033        let clip_index = *clip_index;
3034        *cur_frame = frame;
3035        // The CPU render reads the frame from `state.dyn_clip`; only
3036        // the GPU keeps device-side state (the instance's model id).
3037        if let BackendImpl::Gpu(g) = &mut self.inner {
3038            g.apply_clip_frame(dyn_index as usize, clip_index, frame);
3039        }
3040    }
3041
3042    /// Retarget a live clip instance onto a **different** registered clip,
3043    /// restarting it at frame 0 while keeping its world transform and any
3044    /// auto-playback clock *policy* (speed / paused). The per-frame primitive
3045    /// for directional ("8-way") billboards and animation-state changes
3046    /// (idle → walk → attack): far cheaper than `remove_sprite_instance` +
3047    /// `add_clip_instance_*`, reusing the instance's existing GPU residency
3048    /// (just a model-id swap, no volume re-upload).
3049    ///
3050    /// If the instance has a playback clock
3051    /// ([`add_clip_instance_playing`](Self::add_clip_instance_playing)), its
3052    /// timeline is retargeted to the new clip (durations + loop mode) and the
3053    /// clock restarts at 0; the speed and paused state carry over.
3054    ///
3055    /// Returns `false` (a safe no-op) on a stale instance id, a stale `clip`,
3056    /// or a non-clip instance.
3057    pub fn set_clip_instance_clip(&mut self, id: SpriteInstanceId, clip: VoxelClipId) -> bool {
3058        let Some(dyn_index) = self.dyn_map.dyn_index(id) else {
3059            return false;
3060        };
3061        let Some(clip_index) = self.clip_map.index(clip) else {
3062            return false;
3063        };
3064        if !matches!(self.state.dyn_clip.get(dyn_index as usize), Some(Some(_))) {
3065            return false; // not a clip instance
3066        }
3067        // Only the GPU has device-side state to retarget (the model
3068        // id); it reports whether the new clip actually has frames.
3069        let ok = match &mut self.inner {
3070            BackendImpl::Cpu(_) => true,
3071            BackendImpl::Gpu(g) => g.apply_clip_retarget(dyn_index as usize, clip_index),
3072        };
3073        if ok {
3074            self.state.dyn_clip[dyn_index as usize] = Some((clip_index, 0));
3075            // Retarget the auto-player's timeline to the new clip (different
3076            // frame count / durations / loop), restart its clock, keep the
3077            // playback policy (speed + paused). Clone metadata first so the
3078            // immutable borrow ends before the mutable player borrow.
3079            let durations = self.clip_meta[clip_index].durations.clone();
3080            let loop_mode = self.clip_meta[clip_index].loop_mode;
3081            if let Some(player) = self.flipbook_player_mut(id) {
3082                player.clock.retarget(&durations, loop_mode);
3083            }
3084        }
3085        ok
3086    }
3087
3088    // ---- billboards (BB.2) -----------------------------------------------
3089
3090    /// Spawn a clip instance that auto-orients toward the camera every
3091    /// [`face_billboards_to`](Self::face_billboards_to) — a Doom/Build-style
3092    /// billboard. `pos` is its world position (the clip pivot maps here);
3093    /// `mode` chooses cylindrical (the Doom default) or spherical facing.
3094    /// Drive its animation through the clip player
3095    /// ([`advance_voxel_clips`](Self::advance_voxel_clips)) and swap
3096    /// animations with [`set_clip_instance_clip`](Self::set_clip_instance_clip).
3097    ///
3098    /// The instance starts axis-aligned until the first `face_billboards_to`,
3099    /// so call that (with the frame's camera) before `render` — like
3100    /// `advance_voxel_clips(dt)`. Returns a stale id on a stale `clip` (no
3101    /// billboard recorded).
3102    pub fn add_billboard_instance(
3103        &mut self,
3104        clip: VoxelClipId,
3105        pos: [f32; 3],
3106        mode: BillboardMode,
3107    ) -> Option<SpriteInstanceId> {
3108        let xf = DynSpriteTransform {
3109            pos,
3110            ..Default::default()
3111        };
3112        let id = self.add_clip_instance_posed(clip, xf)?;
3113        self.billboards.push(BillboardRec { id, pos, mode });
3114        Some(id)
3115    }
3116
3117    /// Change a billboard instance's facing mode. No-op on a non-billboard id.
3118    pub fn set_billboard_mode(&mut self, id: SpriteInstanceId, mode: BillboardMode) {
3119        if let Some(b) = self.billboards.iter_mut().find(|b| b.id == id) {
3120            b.mode = mode;
3121        }
3122    }
3123
3124    /// Move a billboard instance. Its auto-orientation is preserved; the new
3125    /// position takes effect on the next
3126    /// [`face_billboards_to`](Self::face_billboards_to). No-op on a
3127    /// non-billboard id.
3128    pub fn set_billboard_position(&mut self, id: SpriteInstanceId, pos: [f32; 3]) {
3129        if let Some(b) = self.billboards.iter_mut().find(|b| b.id == id) {
3130            b.pos = pos;
3131        }
3132    }
3133
3134    /// Re-orient every billboard instance to face `camera` — one batched
3135    /// transform flush (BB.2). Call once per frame before `render`, after
3136    /// moving billboards / the camera (the billboard analogue of
3137    /// [`advance_voxel_clips`](Self::advance_voxel_clips)). Billboards whose
3138    /// instance was removed are pruned; a degenerate pose (camera on the
3139    /// sprite's vertical axis) is skipped for that frame.
3140    pub fn face_billboards_to(&mut self, camera: &Camera) {
3141        let cam = camera.pos;
3142        let dyn_map = &self.dyn_map;
3143        let mut updates: Vec<(SpriteInstanceId, DynSpriteTransform)> = Vec::new();
3144        self.billboards.retain(|b| {
3145            if dyn_map.dyn_index(b.id).is_none() {
3146                return false; // the instance was removed → drop the record
3147            }
3148            if let Some(xf) = billboard_transform(b.pos, cam, b.mode) {
3149                updates.push((b.id, xf));
3150            }
3151            true
3152        });
3153        self.set_sprite_instance_transforms(&updates);
3154    }
3155
3156    // ---- billboard actors (BB.4) -----------------------------------------
3157
3158    /// Build a [`ClipClock`] seeded from `clip`'s timeline (durations + loop
3159    /// mode), or an empty/looping clock if `clip` is `None`/stale.
3160    fn clock_for_clip(&self, clip: Option<VoxelClipId>, speed: f32) -> ClipClock {
3161        let (durations, loop_mode) = clip.and_then(|c| self.clip_map.index(c)).map_or_else(
3162            || (Vec::new(), LoopMode::Loop),
3163            |ci| {
3164                (
3165                    self.clip_meta[ci].durations.clone(),
3166                    self.clip_meta[ci].loop_mode,
3167                )
3168            },
3169        );
3170        ClipClock::new(&durations, loop_mode, speed_to_q8(speed), 0.0)
3171    }
3172
3173    /// Register a high-level **directional billboard actor** (BB.4): the
3174    /// renderer owns one clip instance and, every
3175    /// [`update_billboard_actors`](Self::update_billboard_actors), picks the
3176    /// directional clip from the view angle, faces it to the camera, and
3177    /// advances its state animation. The convenience layer over
3178    /// [`add_billboard_instance`](Self::add_billboard_instance) +
3179    /// [`set_clip_instance_clip`](Self::set_clip_instance_clip) + the clip
3180    /// clock for Doom-style monsters.
3181    ///
3182    /// `pos` is the actor's world position; `facing_yaw` is the world yaw it
3183    /// faces (radians; the dir picker compares the camera's bearing to it).
3184    /// Returns `None` — spawning nothing — if `def` has no states / a
3185    /// state with no dirs, or the initial clip is stale (QE.1c;
3186    /// previously a silent sentinel id).
3187    pub fn add_billboard_actor(
3188        &mut self,
3189        def: BillboardActorDef,
3190        pos: [f32; 3],
3191        facing_yaw: f64,
3192    ) -> Option<BillboardActorId> {
3193        if def.states.is_empty() || def.states.iter().any(|s| s.dirs.is_empty()) {
3194            return None;
3195        }
3196        let init_clip = def.states[0].dirs[0];
3197        let xf = DynSpriteTransform {
3198            pos,
3199            ..Default::default()
3200        };
3201        let inst = self.add_clip_instance_posed(init_clip, xf)?;
3202        self.set_sprite_instance_shadow_flags(inst, def.shadows);
3203        self.set_sprite_instance_lighting(inst, def.lighting);
3204        let clock = self.clock_for_clip(Some(init_clip), def.speed);
3205        let actor = BillboardActor {
3206            scale: def.scale,
3207            inst,
3208            states: def.states,
3209            cur_state: 0,
3210            pos,
3211            facing_yaw,
3212            mode: def.mode,
3213            clock,
3214            showing: None,
3215            speed: def.speed,
3216        };
3217        let index = self.billboard_actors.len() as u32;
3218        self.billboard_actors.push(Some(actor));
3219        Some(self.actor_map.alloc(index))
3220    }
3221
3222    /// Switch an actor to a named animation state, restarting its clock (the
3223    /// directional clip is reselected on the next
3224    /// [`update_billboard_actors`](Self::update_billboard_actors)). No-op on a
3225    /// stale id or an unknown state name.
3226    pub fn set_actor_state(&mut self, id: BillboardActorId, state: &str) -> bool {
3227        let Some(idx) = self.actor_map.index(id) else {
3228            return false;
3229        };
3230        let Some(a) = self.billboard_actors[idx].as_ref() else {
3231            return false;
3232        };
3233        let Some(state_idx) = a.states.iter().position(|s| s.name == state) else {
3234            return false;
3235        };
3236        let rep = a.states[state_idx].dirs.first().copied();
3237        let speed = a.speed;
3238        let clock = self.clock_for_clip(rep, speed);
3239        let a = self.billboard_actors[idx].as_mut().unwrap();
3240        a.cur_state = state_idx;
3241        a.clock = clock;
3242        a.showing = None; // force a clip reselect next update
3243        true
3244    }
3245
3246    /// Move/turn an actor. Its orientation + directional clip update on the
3247    /// next [`update_billboard_actors`](Self::update_billboard_actors). No-op
3248    /// on a stale id.
3249    pub fn set_actor_transform(&mut self, id: BillboardActorId, pos: [f32; 3], facing_yaw: f64) {
3250        let Some(idx) = self.actor_map.index(id) else {
3251            return;
3252        };
3253        if let Some(a) = self.billboard_actors[idx].as_mut() {
3254            a.pos = pos;
3255            a.facing_yaw = facing_yaw;
3256        }
3257    }
3258
3259    /// Change an actor's lighting mode at runtime (BB.2b) — the per-actor
3260    /// counterpart to [`BillboardActorDef::lighting`], routed to its clip
3261    /// instance via [`set_sprite_instance_lighting`](Self::set_sprite_instance_lighting).
3262    /// Returns `false` on a stale id.
3263    pub fn set_actor_lighting(&mut self, id: BillboardActorId, mode: BillboardLighting) -> bool {
3264        let Some(idx) = self.actor_map.index(id) else {
3265            return false;
3266        };
3267        let Some(inst) = self.billboard_actors[idx].as_ref().map(|a| a.inst) else {
3268            return false;
3269        };
3270        self.set_sprite_instance_lighting(inst, mode);
3271        true
3272    }
3273
3274    /// Tint an actor at runtime — the per-actor counterpart to
3275    /// [`set_sprite_instance_tint`](Self::set_sprite_instance_tint), routed to
3276    /// its clip instance. `tint` is an `0x00RR_GGBB` colour multiply
3277    /// (`0x00FF_FFFF` = white = no-op). Returns `false` on a stale id.
3278    pub fn set_actor_tint(&mut self, id: BillboardActorId, tint: Rgb) -> bool {
3279        let Some(idx) = self.actor_map.index(id) else {
3280            return false;
3281        };
3282        let Some(inst) = self.billboard_actors[idx].as_ref().map(|a| a.inst) else {
3283            return false;
3284        };
3285        self.set_sprite_instance_tint(inst, tint);
3286        true
3287    }
3288
3289    /// Remove an actor and its clip instance. Returns `false` on a stale id.
3290    pub fn remove_billboard_actor(&mut self, id: BillboardActorId) -> bool {
3291        let Some(idx) = self.actor_map.index(id) else {
3292            return false;
3293        };
3294        if let Some(a) = self.billboard_actors[idx].take() {
3295            self.remove_sprite_instance(a.inst);
3296        }
3297        self.actor_map.remove(id)
3298    }
3299
3300    /// Drive every billboard actor by `dt` seconds (BB.4): for each, pick the
3301    /// directional clip from the camera bearing (swapping clips only on
3302    /// change), advance its state-animation clock, and face it to the camera.
3303    /// Call once per frame before `render` (the actor analogue of
3304    /// [`advance_voxel_clips`](Self::advance_voxel_clips) +
3305    /// [`face_billboards_to`](Self::face_billboards_to)). Actors whose
3306    /// instance was removed are pruned.
3307    pub fn update_billboard_actors(&mut self, camera: &Camera, dt: f64) {
3308        struct Action {
3309            inst: SpriteInstanceId,
3310            set_clip: Option<VoxelClipId>,
3311            frame: u32,
3312            xf: Option<DynSpriteTransform>,
3313        }
3314        let cam = camera.pos;
3315        let dyn_map = &self.dyn_map;
3316        let mut actions: Vec<Action> = Vec::new();
3317        for slot in &mut self.billboard_actors {
3318            let Some(a) = slot.as_mut() else {
3319                continue;
3320            };
3321            if dyn_map.dyn_index(a.inst).is_none() {
3322                *slot = None; // instance gone → drop the actor
3323                continue;
3324            }
3325            let dir = a.pick_dir(cam);
3326            let desired = a.states[a.cur_state].dirs[dir];
3327            let set_clip = (a.showing != Some(desired)).then(|| {
3328                a.showing = Some(desired);
3329                desired
3330            });
3331            let frame = a.clock.tick(dt);
3332            let xf = billboard_transform(a.pos, cam, a.mode).map(|mut xf| {
3333                for axis in [&mut xf.right, &mut xf.up, &mut xf.forward] {
3334                    for c in axis.iter_mut() {
3335                        *c *= a.scale;
3336                    }
3337                }
3338                xf
3339            });
3340            actions.push(Action {
3341                inst: a.inst,
3342                set_clip,
3343                frame,
3344                xf,
3345            });
3346        }
3347        // Apply (each call borrows self mutably; disjoint from the loop above).
3348        let mut xforms: Vec<(SpriteInstanceId, DynSpriteTransform)> = Vec::new();
3349        for act in actions {
3350            if let Some(clip) = act.set_clip {
3351                self.set_clip_instance_clip(act.inst, clip);
3352            }
3353            // After a clip swap the backend reset the frame to 0; set the
3354            // clock's frame so the walk cycle stays continuous across turns.
3355            self.set_clip_instance_frame(act.inst, act.frame);
3356            if let Some(xf) = act.xf {
3357                xforms.push((act.inst, xf));
3358            }
3359        }
3360        self.set_sprite_instance_transforms(&xforms);
3361    }
3362
3363    // ---- clip queries (editor inspector) ---------------------------------
3364
3365    /// Frame count of a registered flipbook clip, or `None` if `id` is
3366    /// stale. (Same as `clip_metadata(id)?.frame_count`, without the clone.)
3367    #[must_use]
3368    pub fn clip_frame_count(&self, id: VoxelClipId) -> Option<usize> {
3369        let idx = self.clip_map.index(id)?;
3370        Some(self.clip_meta[idx].durations.len())
3371    }
3372
3373    /// Inspector metadata (dims / pivot / scale / loop mode / per-frame
3374    /// durations) of a registered flipbook clip, or `None` if `id` is stale
3375    /// — so an editor needn't shadow the source [`DecodedClip`].
3376    #[must_use]
3377    pub fn clip_metadata(&self, id: VoxelClipId) -> Option<ClipMetadata> {
3378        let idx = self.clip_map.index(id)?;
3379        let m = &self.clip_meta[idx];
3380        Some(ClipMetadata {
3381            dims: m.dims,
3382            pivot: m.pivot,
3383            voxel_world_size: m.voxel_world_size,
3384            loop_mode: m.loop_mode,
3385            frame_count: m.durations.len(),
3386            durations: m.durations.clone(),
3387            total_ms: m
3388                .durations
3389                .iter()
3390                .fold(0u32, |acc, &d| acc.saturating_add(d)),
3391        })
3392    }
3393
3394    /// Which frame a clip instance is currently showing (the timeline
3395    /// scrubber's read-back), or `None` if `id` isn't a live clip instance.
3396    #[must_use]
3397    pub fn clip_instance_frame(&self, id: SpriteInstanceId) -> Option<u32> {
3398        let dyn_index = self.dyn_map.dyn_index(id)? as usize;
3399        let (_, frame) = (*self.state.dyn_clip.get(dyn_index)?)?;
3400        u32::try_from(frame).ok()
3401    }
3402
3403    /// QE.7b — renamed: this was the only `get_`-prefixed method in
3404    /// the crate. Forwarding shim for one minor release.
3405    #[deprecated(since = "0.22.0", note = "renamed to `clip_instance_frame`")]
3406    #[must_use]
3407    pub fn get_clip_instance_frame(&self, id: SpriteInstanceId) -> Option<u32> {
3408        self.clip_instance_frame(id)
3409    }
3410
3411    /// Re-upload a **single** `frame` of registered clip `id` in place — the
3412    /// editor's one-voxel paint, O(1 frame) instead of `remove_voxel_clip` +
3413    /// `add_voxel_clip` (which rebuilds all N volumes). `vf` must fit the
3414    /// clip's fixed `dims`. Returns `false` on a stale `id`, an out-of-range
3415    /// `frame`, or a frame that fails the clip's layout (so it can't corrupt
3416    /// the flipbook).
3417    pub fn update_clip_frame(&mut self, id: VoxelClipId, frame: u32, vf: &VoxelFrame) -> bool {
3418        let Some(clip_index) = self.clip_map.index(id) else {
3419            return false;
3420        };
3421        let m = &self.clip_meta[clip_index];
3422        let (dims, pivot, vws) = (m.dims, m.pivot, m.voxel_world_size);
3423        if vf.validate(dims).is_err() {
3424            return false;
3425        }
3426        // Re-classify with the clip's registered colour→material map (TV.3) so
3427        // an in-place frame edit keeps the clip's per-voxel materials.
3428        let material_map = m.material_map.clone();
3429        let frame = frame as usize;
3430        match &mut self.inner {
3431            BackendImpl::Cpu(c) => {
3432                c.update_clip_frame(clip_index, frame, vf, dims, pivot, vws, &material_map)
3433            }
3434            BackendImpl::Gpu(g) => {
3435                g.update_clip_frame(clip_index, frame, vf, dims, pivot, vws, &material_map)
3436            }
3437        }
3438    }
3439
3440    // ---- streaming voxel clips (#3) --------------------------------------
3441
3442    /// Register a **streaming** voxel clip — `O(1-frame)` memory (one sprite
3443    /// model + the compact encoded stream) rather than the N-volume flipbook
3444    /// [`add_voxel_clip`](Self::add_voxel_clip) builds, for huge clips where
3445    /// N frames are too costly to hold resident. Builds the model from frame
3446    /// 0; advance it with
3447    /// [`set_streaming_clip_frame`](Self::set_streaming_clip_frame). Spawn
3448    /// instances with
3449    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance) —
3450    /// note that, unlike a flipbook, **all** instances of a streaming clip
3451    /// share its one model and so always show the same (current) frame.
3452    ///
3453    /// Takes the *encoded* [`VoxelClip`] (not a [`DecodedClip`]) — the whole
3454    /// point is to avoid materialising every frame.
3455    ///
3456    /// # Errors
3457    /// [`DecodeError`] if the clip's frame stream is empty or doesn't begin
3458    /// with a keyframe.
3459    pub fn add_streaming_clip(&mut self, clip: &VoxelClip) -> Result<StreamingClipId, DecodeError> {
3460        self.add_streaming_clip_with_materials(clip, &[])
3461    }
3462
3463    /// Register a **mixed-material** streaming voxel clip (TV.3): the streaming
3464    /// analogue of
3465    /// [`add_voxel_clip_with_materials`](Self::add_voxel_clip_with_materials).
3466    /// `material_map` pairs a voxel RGB colour with a material id (defined via
3467    /// [`define_material`](Self::define_material)); it is re-applied on every
3468    /// per-frame re-upload, so the single streamed model keeps its per-voxel
3469    /// materials as the clip advances. An empty map is identical to
3470    /// [`add_streaming_clip`](Self::add_streaming_clip).
3471    ///
3472    /// # Errors
3473    /// As [`add_streaming_clip`](Self::add_streaming_clip).
3474    pub fn add_streaming_clip_with_materials(
3475        &mut self,
3476        clip: &VoxelClip,
3477        material_map: &[(Rgb, u8)],
3478    ) -> Result<StreamingClipId, DecodeError> {
3479        let cursor = StreamingClip::new(clip)?;
3480        let dims = cursor.dims();
3481        let pivot = cursor.pivot();
3482        let kv6 = cursor.current_frame().to_kv6(dims, pivot);
3483        let resident_frame = cursor.current_index();
3484        let model = self.add_sprite_model_with_materials(&kv6, material_map);
3485        let index = self.streaming_clips.len() as u32;
3486        self.streaming_clips.push(Some(StreamingClipState {
3487            cursor,
3488            model,
3489            dims,
3490            pivot,
3491            material_map: material_map.to_vec(),
3492            // The model was just built from the cursor's current frame.
3493            last_applied: Some(resident_frame),
3494        }));
3495        Ok(self.streaming_map.alloc(index))
3496    }
3497
3498    /// Spawn an instance of streaming clip `id`, posed by `xf`. Returns a
3499    /// [`SpriteInstanceId`] — move it with
3500    /// [`set_sprite_instance_transform`](Self::set_sprite_instance_transform)
3501    /// and drop it with
3502    /// [`remove_sprite_instance`](Self::remove_sprite_instance), like any
3503    /// dynamic instance. All instances of one streaming clip share its single
3504    /// model. Returns `None` — spawning nothing — on a stale/removed
3505    /// `id` (QE.1c; previously a silent sentinel handle).
3506    pub fn add_streaming_clip_instance(
3507        &mut self,
3508        id: StreamingClipId,
3509        xf: DynSpriteTransform,
3510    ) -> Option<StreamingInstanceId> {
3511        let model = self
3512            .streaming_map
3513            .index(id)
3514            .and_then(|idx| self.streaming_clips[idx].as_ref())
3515            .map(|s| s.model)?;
3516        let inst = self.add_sprite_instance_posed(model, xf)?;
3517        Some(StreamingInstanceId(inst))
3518    }
3519
3520    /// Re-pose a streaming-clip instance (world transform). No-op on a stale
3521    /// handle.
3522    pub fn set_streaming_instance_transform(
3523        &mut self,
3524        id: StreamingInstanceId,
3525        xf: DynSpriteTransform,
3526    ) {
3527        self.set_sprite_instance_transform(id.0, xf);
3528    }
3529
3530    /// Remove a streaming-clip instance. Returns `false` if `id` is stale.
3531    pub fn remove_streaming_instance(&mut self, id: StreamingInstanceId) -> bool {
3532        self.remove_sprite_instance(id.0)
3533    }
3534
3535    /// Advance a streaming clip to `frame`: seek the cursor and re-upload its
3536    /// single model — the per-frame streaming step (one volume re-upload,
3537    /// vs the flipbook's cheap model-select). Updates **every** instance of
3538    /// the clip at once. Drive it from a clock via
3539    /// [`frame_at`](roxlap_formats::voxel_clip::frame_at). No-op on a stale
3540    /// id; `frame` is clamped to the last.
3541    pub fn set_streaming_clip_frame(&mut self, id: StreamingClipId, frame: u32) {
3542        let Some(idx) = self.streaming_map.index(id) else {
3543            return;
3544        };
3545        let Some((model, kv6, material_map)) = self.streaming_clips[idx].as_mut().and_then(|s| {
3546            s.cursor.seek(frame as usize).ok()?;
3547            // PF.5 — same-frame guard on the RESOLVED (clamped) index: skip
3548            // the dense rebuild + re-upload when this frame is already
3549            // resident on the model.
3550            let resolved = s.cursor.current_index();
3551            if s.last_applied == Some(resolved) {
3552                return None;
3553            }
3554            s.last_applied = Some(resolved);
3555            let vf = s.cursor.current_frame();
3556            Some((s.model, vf.to_kv6(s.dims, s.pivot), s.material_map.clone()))
3557        }) else {
3558            return;
3559        };
3560        self.refresh_sprite_model_with_materials(model, &kv6, &material_map);
3561    }
3562
3563    /// Remove a streaming clip: free its model and drop the cursor (the
3564    /// memory win for huge clips). Instances linger but draw nothing until
3565    /// removed. Returns `false` if `id` is stale / already removed.
3566    pub fn remove_streaming_clip(&mut self, id: StreamingClipId) -> bool {
3567        let Some(idx) = self.streaming_map.index(id) else {
3568            return false;
3569        };
3570        let model = self.streaming_clips[idx].as_ref().map(|s| s.model);
3571        self.streaming_clips[idx] = None;
3572        if let Some(model) = model {
3573            self.remove_sprite_model(model);
3574        }
3575        self.streaming_map.remove(id)
3576    }
3577
3578    // ---- auto-advancing clip players (#6) --------------------------------
3579
3580    /// Spawn a flipbook-clip instance that **plays itself**: like
3581    /// [`add_clip_instance_posed`](Self::add_clip_instance_posed), but the
3582    /// facade tracks a playback clock so a single
3583    /// [`advance_voxel_clips`](Self::advance_voxel_clips) call advances every
3584    /// such instance — no per-frame `frame_at` + `set_clip_instance_frame`
3585    /// bookkeeping in the host. `speed` is the playback rate (`1.0` =
3586    /// authored speed, negative = reverse; QE.7b - was Q8, migrate with
3587    /// `speed_q8 as f32 / 256.0`); `start_phase_ms` offsets the clock
3588    /// (stagger copies of one clip). Returns `None` — spawning nothing,
3589    /// registering no player — on a stale/removed `clip` (QE.1c;
3590    /// previously a silent sentinel id).
3591    pub fn add_clip_instance_playing(
3592        &mut self,
3593        clip: VoxelClipId,
3594        xf: DynSpriteTransform,
3595        speed: f32,
3596        start_phase_ms: u32,
3597    ) -> Option<SpriteInstanceId> {
3598        let clip_index = self.clip_map.index(clip)?;
3599        let meta = &self.clip_meta[clip_index];
3600        let clock = ClipClock::new(
3601            &meta.durations,
3602            meta.loop_mode,
3603            speed_to_q8(speed),
3604            f64::from(start_phase_ms),
3605        );
3606        let inst = self.add_clip_instance_posed(clip, xf)?;
3607        self.clip_players.push(ClipPlayer {
3608            target: PlayerTarget::Flipbook(inst),
3609            clock,
3610            paused: false,
3611        });
3612        Some(inst)
3613    }
3614
3615    /// Give a streaming clip ([`add_streaming_clip`](Self::add_streaming_clip))
3616    /// its own playback clock, advanced by
3617    /// [`advance_voxel_clips`](Self::advance_voxel_clips). A streaming clip's
3618    /// frame is per-clip (all its instances share one model), so this is
3619    /// keyed on the clip, not an instance — register instances separately
3620    /// with
3621    /// [`add_streaming_clip_instance`](Self::add_streaming_clip_instance).
3622    /// No-op on a stale `clip`.
3623    ///
3624    /// Control the player (play/pause/scrub) via
3625    /// [`set_streaming_clip_paused`](Self::set_streaming_clip_paused) /
3626    /// [`set_streaming_clip_speed`](Self::set_streaming_clip_speed) /
3627    /// [`set_streaming_clip_clock_ms`](Self::set_streaming_clip_clock_ms), the
3628    /// per-clip analogues of the flipbook `set_clip_instance_*` methods.
3629    /// `speed` is the playback rate (`1.0` = authored; QE.7b - was Q8).
3630    pub fn play_streaming_clip(&mut self, clip: StreamingClipId, speed: f32, start_phase_ms: u32) {
3631        let Some(idx) = self.streaming_map.index(clip) else {
3632            return;
3633        };
3634        let Some(state) = self.streaming_clips[idx].as_ref() else {
3635            return;
3636        };
3637        let clock = ClipClock::new(
3638            state.cursor.durations(),
3639            state.cursor.loop_mode(),
3640            speed_to_q8(speed),
3641            f64::from(start_phase_ms),
3642        );
3643        self.clip_players.push(ClipPlayer {
3644            target: PlayerTarget::Streaming(clip),
3645            clock,
3646            paused: false,
3647        });
3648    }
3649
3650    /// Advance every auto-playing clip ([`add_clip_instance_playing`] /
3651    /// [`play_streaming_clip`]) by `dt` seconds: tick each clock, resolve its
3652    /// frame via [`frame_at`](roxlap_formats::voxel_clip::frame_at), and
3653    /// apply it. Players whose instance / clip was removed are pruned. Call
3654    /// once per frame.
3655    ///
3656    /// [`add_clip_instance_playing`]: Self::add_clip_instance_playing
3657    /// [`play_streaming_clip`]: Self::play_streaming_clip
3658    pub fn advance_voxel_clips(&mut self, dt: f64) {
3659        // Phase 1: tick clocks → (target, frame), pruning dead players.
3660        // Borrow only the maps (disjoint from `clip_players`).
3661        let dyn_map = &self.dyn_map;
3662        let streaming_map = &self.streaming_map;
3663        let mut updates: Vec<(PlayerTarget, u32)> = Vec::new();
3664        self.clip_players.retain_mut(|p| {
3665            let alive = match p.target {
3666                PlayerTarget::Flipbook(inst) => dyn_map.dyn_index(inst).is_some(),
3667                PlayerTarget::Streaming(clip) => streaming_map.index(clip).is_some(),
3668            };
3669            if !alive {
3670                return false;
3671            }
3672            // A paused player keeps its clock + frame (the editor's pause).
3673            if !p.paused {
3674                updates.push((p.target, p.clock.tick(dt)));
3675            }
3676            true
3677        });
3678        // Phase 2: apply (borrows self mutably, disjoint from the above).
3679        for (target, frame) in updates {
3680            self.apply_player_frame(target, frame);
3681        }
3682    }
3683
3684    /// Apply a resolved frame to a player's target (flipbook instance vs.
3685    /// streaming clip).
3686    fn apply_player_frame(&mut self, target: PlayerTarget, frame: u32) {
3687        match target {
3688            PlayerTarget::Flipbook(inst) => self.set_clip_instance_frame(inst, frame),
3689            PlayerTarget::Streaming(clip) => self.set_streaming_clip_frame(clip, frame),
3690        }
3691    }
3692
3693    /// Find the auto-player driving flipbook instance `inst`, if any.
3694    fn flipbook_player_mut(&mut self, inst: SpriteInstanceId) -> Option<&mut ClipPlayer> {
3695        self.clip_players
3696            .iter_mut()
3697            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == inst))
3698    }
3699
3700    /// Pause / resume the auto-player driving clip instance `id` (the
3701    /// editor's play/pause). No-op if `id` has no player.
3702    pub fn set_clip_instance_paused(&mut self, id: SpriteInstanceId, paused: bool) {
3703        if let Some(p) = self.flipbook_player_mut(id) {
3704            p.paused = paused;
3705        }
3706    }
3707
3708    /// Whether clip instance `id`'s auto-player is paused, or `None` if it
3709    /// has no player.
3710    #[must_use]
3711    pub fn is_clip_instance_paused(&self, id: SpriteInstanceId) -> Option<bool> {
3712        self.clip_players
3713            .iter()
3714            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
3715            .map(|p| p.paused)
3716    }
3717
3718    /// Set the playback speed (`1.0` = authored rate, negative =
3719    /// reverse; QE.7b — was Q8) of clip instance `id`'s auto-player.
3720    /// No-op if `id` has no player.
3721    pub fn set_clip_instance_speed(&mut self, id: SpriteInstanceId, speed: f32) {
3722        if let Some(p) = self.flipbook_player_mut(id) {
3723            p.clock.speed_q8 = speed_to_q8(speed);
3724        }
3725    }
3726
3727    /// **Scrub**: set clip instance `id`'s playback clock to `clock_ms` and
3728    /// immediately show the matching frame (works while paused). No-op if
3729    /// `id` has no player.
3730    pub fn set_clip_instance_clock_ms(&mut self, id: SpriteInstanceId, clock_ms: f64) {
3731        let Some((target, frame)) = self.flipbook_player_mut(id).map(|p| {
3732            p.clock.clock_ms = clock_ms;
3733            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3734            let frame = p.clock.frame_for(clock_ms.max(0.0) as u32);
3735            (p.target, frame)
3736        }) else {
3737            return;
3738        };
3739        self.apply_player_frame(target, frame);
3740    }
3741
3742    /// Clip instance `id`'s current playback-clock position (ms), or `None`
3743    /// if it has no player — the scrubber's read-back.
3744    #[must_use]
3745    pub fn clip_instance_clock_ms(&self, id: SpriteInstanceId) -> Option<f64> {
3746        self.clip_players
3747            .iter()
3748            .find(|p| matches!(p.target, PlayerTarget::Flipbook(i) if i == id))
3749            .map(|p| p.clock.clock_ms)
3750    }
3751
3752    /// Find the auto-player driving streaming clip `clip`, if any (a player
3753    /// registered via [`play_streaming_clip`](Self::play_streaming_clip)).
3754    fn streaming_player_mut(&mut self, clip: StreamingClipId) -> Option<&mut ClipPlayer> {
3755        self.clip_players
3756            .iter_mut()
3757            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3758    }
3759
3760    /// Pause / resume a streaming clip's auto-player
3761    /// ([`play_streaming_clip`](Self::play_streaming_clip)). No-op if `clip`
3762    /// has no player.
3763    pub fn set_streaming_clip_paused(&mut self, clip: StreamingClipId, paused: bool) {
3764        if let Some(p) = self.streaming_player_mut(clip) {
3765            p.paused = paused;
3766        }
3767    }
3768
3769    /// Whether streaming clip `clip`'s auto-player is paused, or `None` if it
3770    /// has no player.
3771    #[must_use]
3772    pub fn is_streaming_clip_paused(&self, clip: StreamingClipId) -> Option<bool> {
3773        self.clip_players
3774            .iter()
3775            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3776            .map(|p| p.paused)
3777    }
3778
3779    /// Set the playback speed (`1.0` = authored rate, negative =
3780    /// reverse; QE.7b — was Q8) of streaming clip `clip`'s
3781    /// auto-player. No-op if `clip` has no player.
3782    pub fn set_streaming_clip_speed(&mut self, clip: StreamingClipId, speed: f32) {
3783        if let Some(p) = self.streaming_player_mut(clip) {
3784            p.clock.speed_q8 = speed_to_q8(speed);
3785        }
3786    }
3787
3788    /// **Scrub** a streaming clip: set its auto-player's clock to `clock_ms`
3789    /// and immediately show the matching frame (works while paused). No-op if
3790    /// `clip` has no player.
3791    pub fn set_streaming_clip_clock_ms(&mut self, clip: StreamingClipId, clock_ms: f64) {
3792        let Some((target, frame)) = self.streaming_player_mut(clip).map(|p| {
3793            p.clock.clock_ms = clock_ms;
3794            #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3795            let frame = p.clock.frame_for(clock_ms.max(0.0) as u32);
3796            (p.target, frame)
3797        }) else {
3798            return;
3799        };
3800        self.apply_player_frame(target, frame);
3801    }
3802
3803    /// Streaming clip `clip`'s current playback-clock position (ms), or
3804    /// `None` if it has no player — the scrubber's read-back.
3805    #[must_use]
3806    pub fn streaming_clip_clock_ms(&self, clip: StreamingClipId) -> Option<f64> {
3807        self.clip_players
3808            .iter()
3809            .find(|p| matches!(p.target, PlayerTarget::Streaming(c) if c == clip))
3810            .map(|p| p.clock.clock_ms)
3811    }
3812
3813    // ---- animated characters (VCL.6) -------------------------------------
3814
3815    /// Register an animated character (RKC v3): upload its meshes as sprite
3816    /// models + its embedded voxel clips as flipbooks, then spawn one
3817    /// renderer instance **per bone attachment** — a static mesh sits at
3818    /// its bone, a clip attachment plays back on its own clock. `clip`
3819    /// selects a skeletal animation clip to drive the bones (`None` =
3820    /// rest pose). Returns a [`CharacterId`]; advance it each frame with
3821    /// [`advance_character`](Self::advance_character).
3822    ///
3823    /// Like clips, this works before any [`set_sprites`](Self::set_sprites);
3824    /// a later `set_sprites` drops all registered characters.
3825    pub fn add_character(&mut self, ch: &Character, clip: Option<usize>) -> CharacterId {
3826        // 1. Meshes → sprite models.
3827        let model_ids: Vec<SpriteModelId> =
3828            ch.meshes.iter().map(|m| self.add_sprite_model(m)).collect();
3829        // 2. Voxel clips → flipbooks; keep each one's timing for the clocks.
3830        let clip_regs: Vec<Option<(VoxelClipId, Vec<u32>, LoopMode)>> = ch
3831            .voxel_clips
3832            .iter()
3833            .map(|vc| {
3834                vc.decode().ok().map(|d| {
3835                    let id = self.add_voxel_clip(&d);
3836                    (id, d.durations, d.loop_mode)
3837                })
3838            })
3839            .collect();
3840        // 3. Build + solve the skeleton (rest pose → bone transforms).
3841        let mut skeleton = ch.to_kfa_sprite(clip);
3842        solve_kfa_limbs(&mut skeleton);
3843        // 4. One instance per attachment, posed by bone × local_offset.
3844        let mut attaches = Vec::new();
3845        for (bi, bone) in ch.bones.iter().enumerate() {
3846            let limb = &skeleton.limbs[bi];
3847            for att in &bone.attachments {
3848                let (s, h, f, p) =
3849                    compose_attachment(limb.s, limb.h, limb.f, limb.p, &att.local_offset);
3850                let xf = DynSpriteTransform {
3851                    pos: p,
3852                    right: s,
3853                    up: h,
3854                    forward: f,
3855                };
3856                match att.target {
3857                    MeshRef::Static(mi) => {
3858                        // The model was registered a few lines up, so the
3859                        // spawn can only fail on an out-of-range mesh index.
3860                        if let Some(inst) = model_ids
3861                            .get(mi)
3862                            .and_then(|&mid| self.add_sprite_instance_posed(mid, xf))
3863                        {
3864                            attaches.push(AttachInst {
3865                                bone: bi,
3866                                local_offset: att.local_offset,
3867                                inst,
3868                                clip: None,
3869                            });
3870                        }
3871                    }
3872                    MeshRef::Clip(ci) => {
3873                        if let Some(Some((cid, durations, loop_mode))) = clip_regs.get(ci) {
3874                            let Some(inst) = self.add_clip_instance_posed(*cid, xf) else {
3875                                continue;
3876                            };
3877                            attaches.push(AttachInst {
3878                                bone: bi,
3879                                local_offset: att.local_offset,
3880                                inst,
3881                                clip: Some(ClipClock::new(
3882                                    durations,
3883                                    *loop_mode,
3884                                    att.playback.speed_q8,
3885                                    f64::from(att.playback.start_phase_ms),
3886                                )),
3887                            });
3888                        }
3889                    }
3890                }
3891            }
3892        }
3893        let clips: Vec<VoxelClipId> = clip_regs
3894            .iter()
3895            .filter_map(|r| r.as_ref().map(|(cid, _, _)| *cid))
3896            .collect();
3897        let idx = self.char_instances.len();
3898        self.char_instances.push(CharInstance {
3899            skeleton,
3900            attaches,
3901            models: model_ids,
3902            clips,
3903        });
3904        self.char_map.alloc(idx as u32)
3905    }
3906
3907    /// Advance a character by `dt` seconds: tick its skeletal animation +
3908    /// each clip attachment's clock, then re-pose every attachment
3909    /// (bone × local_offset) and select each clip's current frame. No-op on
3910    /// a stale id.
3911    pub fn advance_character(&mut self, id: CharacterId, dt: f64) {
3912        let Some(idx) = self.char_map.index(id) else {
3913            return;
3914        };
3915        self.advance_character_at(idx, dt);
3916    }
3917
3918    /// [`advance_character`](Self::advance_character)'s resolved-index
3919    /// core, shared with [`tick`](Self::tick)'s all-characters sweep.
3920    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
3921    fn advance_character_at(&mut self, idx: usize, dt: f64) {
3922        // Phase 1: solve the skeleton + compute each attachment's update,
3923        // borrowing only `char_instances[idx]`.
3924        let updates: Vec<(SpriteInstanceId, DynSpriteTransform, Option<u32>)> = {
3925            let CharInstance {
3926                skeleton, attaches, ..
3927            } = &mut self.char_instances[idx];
3928            skeleton.animsprite((dt * 1000.0) as i32);
3929            solve_kfa_limbs(skeleton);
3930            attaches
3931                .iter_mut()
3932                .map(|a| {
3933                    let limb = &skeleton.limbs[a.bone];
3934                    let (s, h, f, p) =
3935                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
3936                    let xf = DynSpriteTransform {
3937                        pos: p,
3938                        right: s,
3939                        up: h,
3940                        forward: f,
3941                    };
3942                    let frame = a.clip.as_mut().map(|c| c.tick(dt));
3943                    (a.inst, xf, frame)
3944                })
3945                .collect()
3946        };
3947        // Phase 2: apply via the facade primitives (disjoint from
3948        // `char_instances`).
3949        for (inst, xf, frame) in updates {
3950            self.set_sprite_instance_transform(inst, xf);
3951            if let Some(f) = frame {
3952                self.set_clip_instance_frame(inst, f);
3953            }
3954        }
3955    }
3956
3957    /// Move/re-orient a character to a new world transform `xf` (the root
3958    /// limb's world pose) **without** ticking its animation or clip clocks —
3959    /// a teleport that holds the current animation frame (e.g. dragging a
3960    /// paused character in an editor). Re-solves the skeleton from the new
3961    /// root + re-poses every attachment; clip frames are left as-is. No-op on
3962    /// a stale id.
3963    pub fn set_character_world_transform(&mut self, id: CharacterId, xf: DynSpriteTransform) {
3964        let Some(idx) = self.char_map.index(id) else {
3965            return;
3966        };
3967        // Phase 1: set the root pose + re-solve (no animsprite), then compute
3968        // each attachment's new transform — borrowing only `char_instances`.
3969        let updates: Vec<(SpriteInstanceId, DynSpriteTransform)> = {
3970            let CharInstance {
3971                skeleton, attaches, ..
3972            } = &mut self.char_instances[idx];
3973            skeleton.p = xf.pos;
3974            skeleton.s = xf.right;
3975            skeleton.h = xf.up;
3976            skeleton.f = xf.forward;
3977            solve_kfa_limbs(skeleton);
3978            attaches
3979                .iter()
3980                .map(|a| {
3981                    let limb = &skeleton.limbs[a.bone];
3982                    let (s, h, f, p) =
3983                        compose_attachment(limb.s, limb.h, limb.f, limb.p, &a.local_offset);
3984                    (
3985                        a.inst,
3986                        DynSpriteTransform {
3987                            pos: p,
3988                            right: s,
3989                            up: h,
3990                            forward: f,
3991                        },
3992                    )
3993                })
3994                .collect()
3995        };
3996        // Phase 2: apply (clip frames untouched — clocks didn't tick).
3997        for (inst, t) in updates {
3998            self.set_sprite_instance_transform(inst, t);
3999        }
4000    }
4001
4002    /// Remove a character, dropping all its attachment instances **and**
4003    /// freeing the sprite models + voxel clips it registered. Returns
4004    /// `false` if `id` is stale.
4005    pub fn remove_character(&mut self, id: CharacterId) -> bool {
4006        let Some(idx) = self.char_map.index(id) else {
4007            return false;
4008        };
4009        let insts: Vec<SpriteInstanceId> = self.char_instances[idx]
4010            .attaches
4011            .iter()
4012            .map(|a| a.inst)
4013            .collect();
4014        for inst in insts {
4015            self.remove_sprite_instance(inst);
4016        }
4017        self.char_instances[idx].attaches.clear();
4018        // Free the models + clips this character registered (else they leak
4019        // until a `set_sprites` — costly for an editor hot-swapping all
4020        // session). `mem::take` so the per-id frees can borrow `self`.
4021        let models = std::mem::take(&mut self.char_instances[idx].models);
4022        let clips = std::mem::take(&mut self.char_instances[idx].clips);
4023        for model in models {
4024            self.remove_sprite_model(model);
4025        }
4026        for clip in clips {
4027            self.remove_voxel_clip(clip);
4028        }
4029        self.char_map.remove(id)
4030    }
4031
4032    /// Register animated KFA sprites (one or more bone hierarchies).
4033    /// The GPU backend uploads each limb's kv6 as an instanced model
4034    /// **once** (appended to the sprite registry) and seeds the limb
4035    /// instances at their current pose; the CPU backend caches the
4036    /// posed limbs for drawing. Call once at setup, after
4037    /// [`set_sprites`](Self::set_sprites), then drive motion per frame
4038    /// with [`update_kfa_poses`](Self::update_kfa_poses).
4039    ///
4040    /// Limbs are posed from the sprites' current
4041    /// [`kfaval`](roxlap_formats::kfa::KfaSprite::kfaval) (advance
4042    /// [`animsprite`](roxlap_formats::kfa::KfaSprite::animsprite) first
4043    /// if using a baked curve), so `kfas` is taken `&mut`.
4044    pub fn set_kfa_sprites(&mut self, kfas: &mut [KfaSprite]) {
4045        match &mut self.inner {
4046            BackendImpl::Cpu(c) => c.set_kfa_sprites(kfas),
4047            BackendImpl::Gpu(g) => g.set_kfa_sprites(kfas),
4048        }
4049    }
4050
4051    /// Re-pose the registered KFA sprites from their current
4052    /// `kfaval[]`. Call each frame after advancing the animation
4053    /// (`kfa.animsprite(dt_ms)` or poking `kfaval[]`). The GPU backend
4054    /// takes the cheap transform-only update (no model-volume
4055    /// re-upload); the CPU backend re-solves limb transforms for the
4056    /// next [`render`](Self::render). Must follow a
4057    /// [`set_kfa_sprites`](Self::set_kfa_sprites) with the same sprites.
4058    pub fn update_kfa_poses(&mut self, kfas: &mut [KfaSprite]) {
4059        match &mut self.inner {
4060            BackendImpl::Cpu(c) => c.update_kfa_poses(kfas),
4061            BackendImpl::Gpu(g) => g.update_kfa_poses(kfas),
4062        }
4063    }
4064
4065    /// Carve the next z-layer off the [`SpriteSet::carve_model`] and
4066    /// re-upload (the demo's `G` hotkey + GPU.12 copy-on-modify). GPU
4067    /// only; a no-op on the CPU backend. Returns the voxels removed.
4068    pub fn carve_active_sprite(&mut self) -> u32 {
4069        match &mut self.inner {
4070            BackendImpl::Cpu(_) => 0,
4071            BackendImpl::Gpu(g) => g.carve_active_sprite(),
4072        }
4073    }
4074
4075    /// Request that a frame be captured for
4076    /// [`take_capture`](Self::take_capture) — screenshots, photo
4077    /// modes, golden tests. Works on **both** backends since QE.7a
4078    /// (previously a GPU no-op — screenshots were impossible on the
4079    /// backend most games run). CPU: the next
4080    /// [`render`](Self::render) copies its composited framebuffer.
4081    /// GPU: arms [`take_capture`](Self::take_capture) to read back the
4082    /// most recent frame.
4083    pub fn request_capture(&mut self) {
4084        match &mut self.inner {
4085            BackendImpl::Cpu(c) => c.request_capture(),
4086            BackendImpl::Gpu(g) => g.request_capture(),
4087        }
4088    }
4089
4090    /// Take the captured frame as packed `0x00RRGGBB` pixels +
4091    /// dimensions (the **logical** resolution on GPU —
4092    /// post-SSAA/posterize, pre-upscale), or `None` if no capture was
4093    /// requested / nothing rendered yet. The GPU readback blocks like
4094    /// [`pick_depth`](Self::pick_depth) — a hotkey path, not
4095    /// per-frame — and returns `None` on wasm (WebGPU can't block).
4096    pub fn take_capture(&mut self) -> Option<(Vec<u32>, u32, u32)> {
4097        match &mut self.inner {
4098            BackendImpl::Cpu(c) => c.take_capture(),
4099            BackendImpl::Gpu(g) => g.take_capture(),
4100        }
4101    }
4102
4103    /// Screen→world picking input: the world-space hit distance `t` at
4104    /// window pixel `(x, y)` from the **last rendered frame**, or `None`
4105    /// for out-of-bounds pixels and sky / no-hit. The host reconstructs
4106    /// the world hit point as `cam.pos + t * normalize(ray_dir)`, where
4107    /// `ray_dir` is the same per-pixel ray the frame was rendered with
4108    /// (see the backend's projection).
4109    ///
4110    /// `t` is the distance to the nearest **scene-grid** surface
4111    /// (terrain + grids); sprites do not occlude it (the sprite pass
4112    /// reads depth read-only), so a cursor sprite under the pointer is
4113    /// transparent to the pick.
4114    ///
4115    /// Cost: the CPU backend reads its in-memory z-buffer (free); the
4116    /// GPU backend stages the depth buffer and blocks on a device poll
4117    /// (cheap at click time — do not call every frame). The scene pass
4118    /// always writes depth (L3.1), so the pick works with or without
4119    /// sprites in the frame.
4120    ///
4121    /// **wasm GPU path (PW.1): one-frame latency.** WebGPU has no
4122    /// blocking readback, so the call submits the readback for
4123    /// `(x, y)` and returns the latest **completed** pick — usually
4124    /// `None` on the first call and the value on the next; the value
4125    /// may correspond to the previously requested pixel. Poll by
4126    /// calling again next frame. Hosts needing synchronous picks use
4127    /// the CPU backend (which is synchronous everywhere).
4128    #[must_use]
4129    pub fn pick_depth(&self, x: u32, y: u32) -> Option<f32> {
4130        match &self.inner {
4131            BackendImpl::Cpu(c) => c.pick_depth(x, y),
4132            BackendImpl::Gpu(g) => g.pick_depth(x, y),
4133        }
4134    }
4135
4136    /// World-space view-ray direction (un-normalised) for window pixel
4137    /// `(x, y)`, under the projection the **last frame** rendered with.
4138    /// The backends differ (CPU `setcamera` vs GPU vertical-FOV
4139    /// pinhole), so this hides which one is active. `None` before the
4140    /// first frame. Intersect it with a plane for tile picking, or feed
4141    /// it to [`Self::pick`] for a voxel.
4142    #[must_use]
4143    pub fn pixel_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<[f64; 3]> {
4144        match &self.inner {
4145            BackendImpl::Cpu(c) => c.pixel_ray(camera, x, y),
4146            BackendImpl::Gpu(g) => g.pixel_ray(camera, x, y),
4147        }
4148    }
4149
4150    /// Canonical screen→world unproject: the full view [`Ray`]
4151    /// (`camera.pos` origin + unit direction) for window pixel
4152    /// `(x, y)`, under whichever projection the last frame used. The
4153    /// one entry point both backends honour — hosts never reconstruct
4154    /// the projection. `None` before the first frame or for a
4155    /// degenerate ray.
4156    ///
4157    /// Compose with [`roxlap_scene::Scene::raycast`] for depth-free
4158    /// picking that's identical on CPU and GPU:
4159    /// `renderer.view_ray(cam, x, y).and_then(|r| scene.raycast(r.origin, r.dir, max))`.
4160    #[must_use]
4161    pub fn view_ray(&self, camera: &Camera, x: f64, y: f64) -> Option<Ray> {
4162        let d = self.pixel_ray(camera, x, y)?;
4163        let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
4164        if len < 1e-12 {
4165            return None;
4166        }
4167        Some(Ray {
4168            origin: glam::DVec3::from_array([camera.pos[0], camera.pos[1], camera.pos[2]]),
4169            dir: glam::DVec3::new(d[0] / len, d[1] / len, d[2] / len),
4170        })
4171    }
4172
4173    /// One-call screen→world voxel pick: unproject pixel `(x, y)` with
4174    /// the active backend's projection, read the last frame's depth
4175    /// there, reconstruct the world hit, and resolve it to the owning
4176    /// grid + grid-local voxel via [`Scene::resolve_voxel`]. `None` on
4177    /// sky / no-hit, or when no grid claims the surface.
4178    ///
4179    /// `scene` and `camera` must be the ones the last frame rendered;
4180    /// the projection (size + FOV / `hx,hy,hz`) is taken from that
4181    /// frame. Cheap on CPU (in-memory z-buffer); on GPU it stages the
4182    /// depth buffer (a click-time device poll — not per frame). On the
4183    /// **wasm GPU path** the underlying [`Self::pick_depth`] has
4184    /// one-frame latency — expect `None` on the first call after a
4185    /// click and poll again next frame.
4186    #[must_use]
4187    pub fn pick(&self, scene: &Scene, camera: &Camera, x: u32, y: u32) -> Option<PickHit> {
4188        let dir = self.pixel_ray(camera, f64::from(x), f64::from(y))?;
4189        let t = f64::from(self.pick_depth(x, y)?);
4190        let len = (dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]).sqrt();
4191        if len < 1e-9 {
4192            return None;
4193        }
4194        let s = t / len; // world = cam.pos + t · (dir / |dir|)
4195        let world = glam::DVec3::new(
4196            camera.pos[0] + dir[0] * s,
4197            camera.pos[1] + dir[1] * s,
4198            camera.pos[2] + dir[2] * s,
4199        );
4200        let (grid, voxel) = scene.resolve_voxel(world, glam::DVec3::from_array(dir))?;
4201        #[allow(clippy::cast_possible_truncation)]
4202        let world_f32 = [world.x as f32, world.y as f32, world.z as f32];
4203        Some(PickHit {
4204            world: world_f32,
4205            grid,
4206            voxel,
4207        })
4208    }
4209}
4210
4211/// A frame in flight (QE-B6) — returned by [`SceneRenderer::frame`].
4212/// Overlays draw into the composited frame with the camera it was
4213/// rendered with; exactly one present happens, by [`Self::present`] /
4214/// [`Self::paint_egui`] or on drop.
4215pub struct Frame<'r> {
4216    renderer: &'r mut SceneRenderer,
4217    /// The camera the frame composited with — overlays must use it.
4218    camera: Camera,
4219    finished: bool,
4220}
4221
4222impl Frame<'_> {
4223    /// Draw world-space overlay lines (see
4224    /// [`SceneRenderer::draw_lines`]); chainable.
4225    #[must_use = "the frame must still be presented (or dropped)"]
4226    pub fn draw_lines(self, lines: &[Line3]) -> Self {
4227        let cam = self.camera;
4228        self.renderer.draw_lines(&cam, lines);
4229        self
4230    }
4231
4232    /// Draw 2D image-sprite quads (see
4233    /// [`SceneRenderer::draw_images`]); chainable.
4234    #[must_use = "the frame must still be presented (or dropped)"]
4235    pub fn draw_images(self, images: &[ImageSprite]) -> Self {
4236        let cam = self.camera;
4237        self.renderer.draw_images(&cam, images);
4238        self
4239    }
4240
4241    /// Present with no UI overlay. Consuming — a second present
4242    /// cannot compile.
4243    pub fn present(mut self) {
4244        self.finish();
4245    }
4246
4247    /// Overlay a tessellated egui UI, then present (`hud` feature) —
4248    /// see [`SceneRenderer::paint_egui`] for the arguments. Consuming.
4249    #[cfg(feature = "hud")]
4250    pub fn paint_egui(
4251        mut self,
4252        jobs: &[egui::ClippedPrimitive],
4253        textures: &egui::TexturesDelta,
4254        pixels_per_point: f32,
4255    ) {
4256        self.finished = true;
4257        self.renderer.paint_egui(jobs, textures, pixels_per_point);
4258    }
4259
4260    fn finish(&mut self) {
4261        if !self.finished {
4262            self.finished = true;
4263            self.renderer.present();
4264        }
4265    }
4266}
4267
4268impl Drop for Frame<'_> {
4269    /// An unfinished frame presents itself — forgetting to present is
4270    /// not representable.
4271    fn drop(&mut self) {
4272        self.finish();
4273    }
4274}
4275
4276#[cfg(test)]
4277mod tests {
4278    use super::*;
4279
4280    /// RP.0 — `Native` resolves to the window size verbatim (the byte-identical
4281    /// gate), `Fixed` ignores the window, `Scale` scales + clamps, and every
4282    /// result is `>= 1` per axis.
4283    #[test]
4284    fn render_resolution_logical_for() {
4285        let win = (1920, 1080);
4286        assert_eq!(RenderResolution::Native.logical_for(win), win);
4287        assert_eq!(
4288            RenderResolution::Fixed { w: 860, h: 520 }.logical_for(win),
4289            (860, 520)
4290        );
4291        // Fixed is independent of the window.
4292        assert_eq!(
4293            RenderResolution::Fixed { w: 860, h: 520 }.logical_for((640, 480)),
4294            (860, 520)
4295        );
4296        assert_eq!(RenderResolution::Scale(0.5).logical_for(win), (960, 540));
4297        // Scale rounds, not truncates: 801 * 0.5 = 400.5 → 401.
4298        assert_eq!(
4299            RenderResolution::Scale(0.5).logical_for((801, 601)),
4300            (401, 301)
4301        );
4302        // Degenerate inputs never produce a zero axis.
4303        assert_eq!(RenderResolution::Scale(0.001).logical_for((1, 1)), (1, 1));
4304        assert_eq!(
4305            RenderResolution::Fixed { w: 0, h: 0 }.logical_for(win),
4306            (1, 1)
4307        );
4308        assert_eq!(RenderResolution::Native.logical_for((0, 0)), (1, 1));
4309    }
4310
4311    /// The handle map must survive the backends' swap-remove indexing:
4312    /// drive a model `DynInstanceMap` against a `Vec` "backend" that
4313    /// swap-removes, and check every live handle keeps resolving to its
4314    /// own payload through a sequence of adds + removes.
4315    #[test]
4316    fn dyn_instance_map_survives_swap_removes() {
4317        let mut map = DynInstanceMap::default();
4318        // The "backend": payload per dynamic index; swap_remove mirrors
4319        // both backends' remove_dyn_instance.
4320        let mut backend: Vec<u32> = Vec::new();
4321        // Our bookkeeping: handle -> the payload we expect it to address.
4322        let mut expect: Vec<(SpriteInstanceId, u32)> = Vec::new();
4323
4324        let add = |map: &mut DynInstanceMap,
4325                   backend: &mut Vec<u32>,
4326                   expect: &mut Vec<(SpriteInstanceId, u32)>,
4327                   payload: u32| {
4328            let dyn_index = backend.len() as u32;
4329            backend.push(payload);
4330            let id = map.alloc(dyn_index);
4331            expect.push((id, payload));
4332        };
4333
4334        for p in 0..6 {
4335            add(&mut map, &mut backend, &mut expect, p);
4336        }
4337
4338        // Remove a middle handle (payload 2) and a later one (payload 4),
4339        // plus the current last — covering swap and no-swap paths.
4340        for victim_payload in [2u32, 4, 5] {
4341            let pos = expect
4342                .iter()
4343                .position(|&(_, p)| p == victim_payload)
4344                .unwrap();
4345            let (id, _) = expect.remove(pos);
4346            let dyn_index = map.dyn_index(id).expect("live handle resolves");
4347            // Backend swap-remove + report moved index (old last), exactly
4348            // like remove_dyn_instance on both backends.
4349            let last = backend.len() - 1;
4350            backend.swap_remove(dyn_index as usize);
4351            let moved = (dyn_index as usize != last).then_some(last as u32);
4352            map.remove(id, dyn_index, moved);
4353            // The removed handle is now stale.
4354            assert!(map.dyn_index(id).is_none(), "removed handle is stale");
4355        }
4356
4357        // Every surviving handle still resolves to its own payload.
4358        for &(id, payload) in &expect {
4359            let idx = map.dyn_index(id).expect("survivor resolves");
4360            assert_eq!(
4361                backend[idx as usize], payload,
4362                "handle addresses its payload"
4363            );
4364        }
4365        assert_eq!(map.order.len(), backend.len());
4366        assert_eq!(backend.len(), expect.len());
4367    }
4368
4369    /// The model slotmap mints stable ids, resolves only live handles,
4370    /// and never reuses a slot — so a removed model's id stays dead and
4371    /// every other id survives the remove.
4372    #[test]
4373    fn dyn_model_map_lifecycle() {
4374        let mut map = EpochSlotMap::default();
4375        // `set_sprites(3 models)` seeds ids 0..3, all live.
4376        map.reset_live(3);
4377        let ids: Vec<SpriteModelId> = (0..3).map(|s| SpriteModelId { slot: s, gen: 0 }).collect();
4378        for (i, &id) in ids.iter().enumerate() {
4379            assert_eq!(map.index(id), Some(i));
4380        }
4381
4382        // Incrementally add a fourth model.
4383        let extra = map.alloc(3);
4384        assert_eq!(extra, SpriteModelId { slot: 3, gen: 0 });
4385        assert_eq!(map.index(extra), Some(3));
4386
4387        // Remove model 1: its handle goes stale, the rest stay valid.
4388        assert!(map.remove(ids[1]));
4389        assert_eq!(map.index(ids[1]), None);
4390        assert_eq!(map.index(ids[0]), Some(0));
4391        assert_eq!(map.index(ids[2]), Some(2));
4392        assert_eq!(map.index(extra), Some(3));
4393
4394        // Double remove / stale removal is a no-op returning false.
4395        assert!(!map.remove(ids[1]));
4396
4397        // A bogus / out-of-range handle resolves to nothing, no panic.
4398        let bogus = SpriteModelId { slot: 999, gen: 0 };
4399        assert_eq!(map.index(bogus), None);
4400        assert!(!map.remove(bogus));
4401
4402        // A handle with a mismatched generation never resolves (guards a
4403        // future compacting registry).
4404        let wrong_gen = SpriteModelId { slot: 0, gen: 7 };
4405        assert_eq!(map.index(wrong_gen), None);
4406    }
4407
4408    /// The voxel-clip slotmap (VCL.4) mints stable ids, resolves only live
4409    /// handles, tombstones in place, and `reset` clears it — mirroring the
4410    /// model slotmap, since clips register append-only too.
4411    #[test]
4412    fn dyn_clip_map_lifecycle() {
4413        let mut map = EpochSlotMap::default();
4414        // Two clips registered incrementally (indices 0, 1).
4415        let c0 = map.alloc(0);
4416        let c1 = map.alloc(1);
4417        assert_eq!(c0, VoxelClipId { slot: 0, gen: 0 });
4418        assert_eq!(map.index(c0), Some(0));
4419        assert_eq!(map.index(c1), Some(1));
4420
4421        // Remove clip 0: stale handle, clip 1 stays valid; slot not reused.
4422        assert!(map.remove(c0));
4423        assert_eq!(map.index(c0), None);
4424        assert_eq!(map.index(c1), Some(1));
4425        // Double / stale / out-of-range removes are false, no panic.
4426        assert!(!map.remove(c0));
4427        assert!(!map.remove(VoxelClipId { slot: 99, gen: 0 }));
4428        // Mismatched generation never resolves.
4429        assert_eq!(map.index(VoxelClipId { slot: 1, gen: 5 }), None);
4430
4431        // `set_sprites` resets the clip layer → ids restart at slot 0, but
4432        // the epoch bumps so old handles don't alias the new clips.
4433        map.reset();
4434        assert_eq!(map.index(c1), None, "reset invalidates old handles");
4435        let again = map.alloc(0); // re-takes slot 0 under the new epoch
4436        assert_eq!(again, VoxelClipId { slot: 0, gen: 1 });
4437        assert_eq!(map.index(again), Some(0));
4438        // The footgun fix: c0 (slot 0, old epoch) must NOT resolve to the new
4439        // clip now occupying slot 0.
4440        assert_eq!(
4441            map.index(c0),
4442            None,
4443            "a pre-reset handle must not alias a new clip on the same slot"
4444        );
4445    }
4446
4447    /// The character slotmap (VCL.6) mints stable ids, resolves only live
4448    /// handles, tombstones in place, and `reset` clears it.
4449    #[test]
4450    fn char_map_lifecycle() {
4451        let mut map = EpochSlotMap::default();
4452        let a = map.alloc(0);
4453        let b = map.alloc(1);
4454        assert_eq!(a, CharacterId { slot: 0, gen: 0 });
4455        assert_eq!(map.index(a), Some(0));
4456        assert_eq!(map.index(b), Some(1));
4457
4458        assert!(map.remove(a));
4459        assert_eq!(map.index(a), None);
4460        assert_eq!(map.index(b), Some(1));
4461        assert!(!map.remove(a)); // double remove is a no-op
4462        assert!(!map.remove(CharacterId { slot: 9, gen: 0 }));
4463        assert_eq!(map.index(CharacterId { slot: 1, gen: 7 }), None);
4464
4465        map.reset();
4466        assert_eq!(map.index(b), None);
4467        assert_eq!(map.alloc(0), CharacterId { slot: 0, gen: 1 });
4468        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
4469    }
4470
4471    /// The streaming-clip slotmap (#3) mints stable ids, resolves only live
4472    /// handles, tombstones in place, and `reset` clears it.
4473    #[test]
4474    fn streaming_clip_map_lifecycle() {
4475        let mut map = EpochSlotMap::default();
4476        let a = map.alloc(0);
4477        let b = map.alloc(1);
4478        assert_eq!(a, StreamingClipId { slot: 0, gen: 0 });
4479        assert_eq!(map.index(a), Some(0));
4480        assert_eq!(map.index(b), Some(1));
4481
4482        assert!(map.remove(a));
4483        assert_eq!(map.index(a), None);
4484        assert_eq!(map.index(b), Some(1));
4485        assert!(!map.remove(a)); // double remove is a no-op
4486        assert!(!map.remove(StreamingClipId { slot: 9, gen: 0 }));
4487        assert_eq!(map.index(StreamingClipId { slot: 1, gen: 7 }), None);
4488
4489        map.reset();
4490        assert_eq!(map.index(b), None);
4491        assert_eq!(map.alloc(0), StreamingClipId { slot: 0, gen: 1 });
4492        assert_eq!(map.index(a), None, "pre-reset handle must not alias slot 0");
4493    }
4494
4495    /// The shared clip-playback clock (#6 / VCL.6): `tick` accumulates time
4496    /// at its Q8 speed, resolves the frame, honours `start_phase`, and reads
4497    /// a rewound (negative) clock as frame 0.
4498    #[test]
4499    fn clip_clock_tick_advances_and_resolves_frames() {
4500        // 3 frames, 100 ms each → total 300 ms, looping.
4501        let mut c = ClipClock::new(&[100, 100, 100], LoopMode::Loop, 256, 0.0); // 1×
4502        assert_eq!(c.tick(0.0), 0); // t=0 → frame 0
4503        assert_eq!(c.tick(0.10), 1); // t=100 → frame 1 (100 is not < 100)
4504        assert_eq!(c.clock_ms as u32, 100);
4505        assert_eq!(c.tick(0.15), 2); // t=250 → frame 2
4506        assert_eq!(c.tick(0.10), 0); // t=350 → 350%300=50 → frame 0
4507                                     // 0.5× speed advances half as fast.
4508        let mut slow = ClipClock::new(&[100, 100], LoopMode::Once, 128, 0.0); // 0.5×
4509        assert_eq!(slow.tick(0.20), 1); // 200ms wall → 100ms clock → frame 1
4510        assert!((slow.clock_ms - 100.0).abs() < 1e-6);
4511        // start_phase seeds the clock; negative clock reads as frame 0.
4512        // rewind at -1×, clock seeded mid frame 1
4513        let mut phased = ClipClock::new(&[50, 50, 50], LoopMode::Loop, -256, 50.0);
4514        assert_eq!(phased.tick(0.10), 0); // 50 - 100 = -50 → max(0)=0 → frame 0
4515        assert!(phased.clock_ms < 0.0); // kept signed
4516    }
4517
4518    #[test]
4519    fn clip_clock_retarget_swaps_timeline_restarts_keeps_speed() {
4520        // BB.1: swapping a billboard's animation retargets the player's
4521        // timeline (durations + loop) and restarts the clock, but keeps the
4522        // playback rate (the clock policy).
4523        let mut c = ClipClock::new(&[100, 100, 100], LoopMode::Loop, 512, 250.0); // 2×
4524        c.retarget(&[50, 50], LoopMode::Once);
4525        assert_eq!(c.prefix, vec![50, 100]); // new clip's timeline (prefix sums)
4526        assert_eq!(c.loop_mode, LoopMode::Once); // new clip's loop mode
4527        assert!((c.clock_ms - 0.0).abs() < 1e-9); // restarted at frame 0
4528        assert_eq!(c.speed_q8, 512); // playback rate preserved
4529                                     // After retarget, ticking advances on the *new* timeline.
4530        assert_eq!(c.tick(0.0), 0);
4531        assert_eq!(c.tick(0.025), 1); // 25ms wall × 2× = 50ms → frame 1
4532    }
4533
4534    fn dot(a: [f32; 3], b: [f32; 3]) -> f32 {
4535        a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
4536    }
4537    fn unit(v: [f32; 3]) -> bool {
4538        (dot(v, v) - 1.0).abs() < 1e-5
4539    }
4540
4541    #[test]
4542    fn billboard_cylindrical_faces_camera_upright_and_ignores_height() {
4543        // Camera due +x of the sprite. Cylindrical normal (local +y) points
4544        // at the camera horizontally; image vertical (local +z) is world up.
4545        let xf = billboard_transform(
4546            [0.0, 0.0, 0.0],
4547            [10.0, 0.0, 0.0],
4548            BillboardMode::Cylindrical,
4549        )
4550        .expect("non-degenerate");
4551        assert_eq!(xf.up, [1.0, 0.0, 0.0]); // normal → toward camera
4552        assert_eq!(xf.forward, BILLBOARD_UP); // image vertical → world up (-z)
4553        assert_eq!(xf.right, [0.0, -1.0, 0.0]); // image horizontal = screen-right
4554                                                // Cylindrical ignores camera height: a camera at a different z gives
4555                                                // the same (vertical) basis.
4556        let high = billboard_transform(
4557            [0.0, 0.0, 0.0],
4558            [10.0, 0.0, -50.0],
4559            BillboardMode::Cylindrical,
4560        )
4561        .unwrap();
4562        assert_eq!(high.up, xf.up);
4563        assert_eq!(high.forward, xf.forward);
4564        // Orthonormal basis.
4565        for v in [xf.right, xf.up, xf.forward] {
4566            assert!(unit(v));
4567        }
4568        assert!(dot(xf.right, xf.up).abs() < 1e-5);
4569        assert!(dot(xf.up, xf.forward).abs() < 1e-5);
4570        assert!(dot(xf.right, xf.forward).abs() < 1e-5);
4571    }
4572
4573    #[test]
4574    fn billboard_spherical_tilts_with_view_and_normal_points_at_camera() {
4575        // Camera above (-z) and in front (+x): the normal tilts up; the
4576        // image vertical gains an up-tilt too (unlike cylindrical).
4577        let cam = [10.0, 0.0, -10.0];
4578        let xf = billboard_transform([0.0, 0.0, 0.0], cam, BillboardMode::Spherical).unwrap();
4579        // Normal (local +y) = normalized direction to the camera.
4580        let n = bb_norm([cam[0] as f32, cam[1] as f32, cam[2] as f32]).unwrap();
4581        for (u, ni) in xf.up.iter().zip(n.iter()) {
4582            assert!((u - ni).abs() < 1e-5);
4583        }
4584        // Not vertical-locked: image vertical tilts off world up.
4585        assert!(xf.forward != BILLBOARD_UP);
4586        for v in [xf.right, xf.up, xf.forward] {
4587            assert!(unit(v));
4588        }
4589        assert!(dot(xf.right, xf.up).abs() < 1e-5);
4590        assert!(dot(xf.up, xf.forward).abs() < 1e-5);
4591        assert!(dot(xf.right, xf.forward).abs() < 1e-5);
4592    }
4593
4594    #[test]
4595    fn dir_index_bins_view_angle_front_ccw() {
4596        let o = [0.0, 0.0, 0.0];
4597        // N == 1 (non-directional) is always 0, regardless of camera.
4598        assert_eq!(dir_index(o, 0.0, [5.0, 3.0, 0.0], 1), 0);
4599        // 8-way, actor facing +x (yaw 0). Camera in front (+x) = front = 0.
4600        assert_eq!(dir_index(o, 0.0, [10.0, 0.0, 0.0], 8), 0);
4601        // Camera at +y (90° CCW from facing) → sector 2 (90° / 45°).
4602        assert_eq!(dir_index(o, 0.0, [0.0, 10.0, 0.0], 8), 2);
4603        // Camera behind (−x, 180°) → sector 4.
4604        assert_eq!(dir_index(o, 0.0, [-10.0, 0.0, 0.0], 8), 4);
4605        // Camera at −y (270°) → sector 6.
4606        assert_eq!(dir_index(o, 0.0, [0.0, -10.0, 0.0], 8), 6);
4607        // Rotating the actor's facing rotates the picked sector: facing +y
4608        // (yaw 90°), camera at +y is now "front" → 0.
4609        let fy = std::f64::consts::FRAC_PI_2;
4610        assert_eq!(dir_index(o, fy, [0.0, 10.0, 0.0], 8), 0);
4611        // Camera straight overhead (no horizontal bearing) → 0.
4612        assert_eq!(dir_index(o, 0.0, [0.0, 0.0, -10.0], 8), 0);
4613        // 4-way still bins front/left/back/right.
4614        assert_eq!(dir_index(o, 0.0, [10.0, 0.0, 0.0], 4), 0);
4615        assert_eq!(dir_index(o, 0.0, [0.0, 10.0, 0.0], 4), 1);
4616    }
4617
4618    #[test]
4619    fn apply_shadow_flags_toggles_bits_and_preserves_others() {
4620        use roxlap_formats::sprite::{SPRITE_FLAG_NO_SHADOW_CAST, SPRITE_FLAG_NO_SHADOW_RECEIVE};
4621        let other = 1u32 << 2; // an unrelated flag bit must survive every call
4622        let mut f = other;
4623        apply_shadow_flags(&mut f, true, true); // both on ⇒ no NO_* bits
4624        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4625        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4626        apply_shadow_flags(&mut f, false, true); // no cast
4627        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4628        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4629        apply_shadow_flags(&mut f, true, false); // no receive
4630        assert_eq!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4631        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4632        apply_shadow_flags(&mut f, false, false); // neither
4633        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_CAST, 0);
4634        assert_ne!(f & SPRITE_FLAG_NO_SHADOW_RECEIVE, 0);
4635        assert_eq!(f & other, other, "unrelated bit preserved throughout");
4636    }
4637
4638    #[test]
4639    fn apply_lighting_flags_sets_exclusive_mode_and_preserves_others() {
4640        use roxlap_formats::sprite::{
4641            SPRITE_FLAG_LIGHT_AMBIENT_ONLY, SPRITE_FLAG_LIGHT_WORLD_UP, SPRITE_FLAG_NO_SHADOW_CAST,
4642        };
4643        let other = SPRITE_FLAG_NO_SHADOW_CAST; // a shadow bit must survive
4644        let mut f = other;
4645        apply_lighting_flags(&mut f, BillboardLighting::WorldUp);
4646        assert_ne!(f & SPRITE_FLAG_LIGHT_WORLD_UP, 0);
4647        assert_eq!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4648        apply_lighting_flags(&mut f, BillboardLighting::AmbientOnly);
4649        assert_eq!(f & SPRITE_FLAG_LIGHT_WORLD_UP, 0, "modes are exclusive");
4650        assert_ne!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4651        apply_lighting_flags(&mut f, BillboardLighting::FullBright);
4652        assert_ne!(
4653            f & SPRITE_FLAG_LIGHT_WORLD_UP,
4654            0,
4655            "full-bright sets both bits"
4656        );
4657        assert_ne!(f & SPRITE_FLAG_LIGHT_AMBIENT_ONLY, 0);
4658        apply_lighting_flags(&mut f, BillboardLighting::FaceNormal);
4659        assert_eq!(
4660            f & (SPRITE_FLAG_LIGHT_WORLD_UP | SPRITE_FLAG_LIGHT_AMBIENT_ONLY),
4661            0
4662        );
4663        assert_eq!(f & other, other, "unrelated bit preserved throughout");
4664    }
4665
4666    #[test]
4667    fn billboard_degenerate_keeps_position_none_stays_none() {
4668        // Degenerate view axes (camera straight overhead) must still
4669        // yield a transform — a fixed fallback facing — because
4670        // dropping it also drops the POSITION update and the actor
4671        // freezes at its last pose (the CC.4 third-person bug: a
4672        // camera at the actor's own xy column degenerated every
4673        // frame). The card is edge-on right then, so the facing
4674        // itself is cosmetically irrelevant.
4675        let xf = billboard_transform(
4676            [1.0, 2.0, 0.0],
4677            [1.0, 2.0, -10.0],
4678            BillboardMode::Cylindrical,
4679        )
4680        .expect("degenerate cylindrical falls back, not drops");
4681        assert_eq!(xf.pos, [1.0, 2.0, 0.0], "position always lands");
4682        let xf = billboard_transform([1.0, 2.0, 0.0], [1.0, 2.0, -10.0], BillboardMode::Spherical)
4683            .expect("degenerate spherical falls back, not drops");
4684        assert_eq!(xf.pos, [1.0, 2.0, 0.0]);
4685        // None mode is never auto-oriented.
4686        assert!(
4687            billboard_transform([0.0, 0.0, 0.0], [10.0, 0.0, 0.0], BillboardMode::None).is_none()
4688        );
4689    }
4690
4691    #[test]
4692    fn dyn_sprite_transform_default_is_identity_and_applies() {
4693        let xf = DynSpriteTransform::default();
4694        assert_eq!(xf.pos, [0.0, 0.0, 0.0]);
4695        assert_eq!(xf.right, [1.0, 0.0, 0.0]);
4696        assert_eq!(xf.up, [0.0, 1.0, 0.0]);
4697        assert_eq!(xf.forward, [0.0, 0.0, 1.0]);
4698
4699        let mut s = Sprite::axis_aligned(
4700            roxlap_formats::kv6::Kv6::solid_cube(2, roxlap_formats::VoxColor(0x80_FF_FF_FF)),
4701            [9.0, 9.0, 9.0],
4702        );
4703        let posed = DynSpriteTransform {
4704            pos: [1.0, 2.0, 3.0],
4705            right: [0.0, 0.0, 1.0],
4706            up: [0.0, 1.0, 0.0],
4707            forward: [1.0, 0.0, 0.0],
4708        };
4709        posed.apply_to(&mut s);
4710        assert_eq!(s.p, [1.0, 2.0, 3.0]);
4711        assert_eq!(s.s, [0.0, 0.0, 1.0]);
4712        assert_eq!(s.h, [0.0, 1.0, 0.0]);
4713        assert_eq!(s.f, [1.0, 0.0, 0.0]);
4714    }
4715
4716    #[test]
4717    fn options_default_is_cpu_intent() {
4718        let o = RenderOptions::default();
4719        assert_eq!(o.backend, BackendPreference::Cpu);
4720        assert_eq!(o.clear_sky.0 & 0xFF00_0000, 0, "clear_sky is 0x00RRGGBB");
4721    }
4722
4723    /// A camera at the origin looking down +Y (voxlap z-down world): right
4724    /// = +X, down = +Z, forward = +Y. Handedness `right × down == forward`.
4725    fn cam_looking_y() -> Camera {
4726        Camera {
4727            pos: [0.0, 0.0, 0.0],
4728            right: [1.0, 0.0, 0.0],
4729            down: [0.0, 0.0, 1.0],
4730            forward: [0.0, 1.0, 0.0],
4731        }
4732    }
4733
4734    #[test]
4735    fn world_quad_corner_layout() {
4736        // Top-left at (-5, 10, -5); u = +X (width), v = +Z (down). A
4737        // 10×10 quad facing the camera (its +Y normal points back at us).
4738        let sprite = ImageSprite {
4739            image: ImageId { slot: 0, gen: 0 },
4740            origin: [-5.0, 10.0, -5.0],
4741            facing: ImageFacing::World {
4742                u: [1.0, 0.0, 0.0],
4743                v: [0.0, 0.0, 1.0],
4744            },
4745            size: [10.0, 10.0],
4746            tint: OverlayColor(0xFFFF_FFFF),
4747            alpha_cutoff: 0.0,
4748            depth_test: true,
4749            double_sided: true,
4750        };
4751        let q = resolve_quad(&sprite, &cam_looking_y()).expect("front-facing");
4752        assert_eq!(q.corners[0], [-5.0, 10.0, -5.0], "TL = origin");
4753        assert_eq!(q.corners[1], [5.0, 10.0, -5.0], "TR = origin + u·size");
4754        assert_eq!(q.corners[2], [-5.0, 10.0, 5.0], "BL = origin + v·size");
4755        assert_eq!(q.corners[3], [5.0, 10.0, 5.0], "BR = origin + u + v");
4756    }
4757
4758    #[test]
4759    fn world_quad_backface_culls_when_single_sided() {
4760        // Same plane but spanned so its normal (u × v) points *away* from
4761        // the camera: swap u/v so the winding flips.
4762        let sprite = ImageSprite {
4763            image: ImageId { slot: 0, gen: 0 },
4764            origin: [-5.0, 10.0, -5.0],
4765            facing: ImageFacing::World {
4766                u: [0.0, 0.0, 1.0], // v-ish
4767                v: [1.0, 0.0, 0.0], // u-ish → normal flips to -Y... toward camera?
4768            },
4769            size: [10.0, 10.0],
4770            tint: OverlayColor(0xFFFF_FFFF),
4771            alpha_cutoff: 0.0,
4772            depth_test: true,
4773            double_sided: false,
4774        };
4775        // With double_sided=false one of the two windings must cull; the
4776        // opposite winding must draw. Exactly one of the two resolves.
4777        let a = resolve_quad(&sprite, &cam_looking_y()).is_some();
4778        let mut flipped = sprite;
4779        flipped.facing = ImageFacing::World {
4780            u: [1.0, 0.0, 0.0],
4781            v: [0.0, 0.0, 1.0],
4782        };
4783        let b = resolve_quad(&flipped, &cam_looking_y()).is_some();
4784        assert!(a ^ b, "exactly one winding is front-facing");
4785    }
4786
4787    #[test]
4788    fn double_sided_never_culls() {
4789        let mut sprite = ImageSprite {
4790            image: ImageId { slot: 0, gen: 0 },
4791            origin: [-5.0, 10.0, -5.0],
4792            facing: ImageFacing::World {
4793                u: [0.0, 0.0, 1.0],
4794                v: [1.0, 0.0, 0.0],
4795            },
4796            size: [10.0, 10.0],
4797            tint: OverlayColor(0xFFFF_FFFF),
4798            alpha_cutoff: 0.0,
4799            depth_test: true,
4800            double_sided: true,
4801        };
4802        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
4803        sprite.facing = ImageFacing::World {
4804            u: [1.0, 0.0, 0.0],
4805            v: [0.0, 0.0, 1.0],
4806        };
4807        assert!(resolve_quad(&sprite, &cam_looking_y()).is_some());
4808    }
4809
4810    #[test]
4811    fn ray_quad_uv_center_and_corners() {
4812        // 10×10 quad on the y=10 plane: TL(-5,10,-5) u=+X v=+Z. Camera at
4813        // origin looking +Y. A ray straight at the quad centre → uv (.5,.5).
4814        let corners = [
4815            [-5.0, 10.0, -5.0], // TL
4816            [5.0, 10.0, -5.0],  // TR
4817            [-5.0, 10.0, 5.0],  // BL
4818            [5.0, 10.0, 5.0],   // BR
4819        ];
4820        let (uv, t) = ray_quad_uv([0.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).expect("center hit");
4821        assert!(
4822            (uv[0] - 0.5).abs() < 1e-5 && (uv[1] - 0.5).abs() < 1e-5,
4823            "centre → (.5,.5)"
4824        );
4825        assert!((t - 10.0).abs() < 1e-4, "t = plane distance");
4826        // Ray toward the TL corner texel region (−x, +y, −z) → uv near (0,0).
4827        let (uv_tl, _) = ray_quad_uv([0.0, 0.0, 0.0], [-4.0, 10.0, -4.0], &corners).unwrap();
4828        assert!(uv_tl[0] < 0.2 && uv_tl[1] < 0.2, "toward TL → small uv");
4829    }
4830
4831    #[test]
4832    fn ray_quad_uv_misses_outside_and_behind() {
4833        let corners = [
4834            [-5.0, 10.0, -5.0],
4835            [5.0, 10.0, -5.0],
4836            [-5.0, 10.0, 5.0],
4837            [5.0, 10.0, 5.0],
4838        ];
4839        // Ray pointing away (−Y) never reaches the +Y plane in front.
4840        assert!(ray_quad_uv([0.0, 0.0, 0.0], [0.0, -1.0, 0.0], &corners).is_none());
4841        // Ray parallel to the quad plane (in +X) → no intersection.
4842        assert!(ray_quad_uv([0.0, 0.0, 0.0], [1.0, 0.0, 0.0], &corners).is_none());
4843        // Ray hitting the plane far outside the quad → outside uv.
4844        assert!(ray_quad_uv([100.0, 0.0, 0.0], [0.0, 1.0, 0.0], &corners).is_none());
4845    }
4846
4847    #[test]
4848    fn billboard_axes_orthogonal_and_top_toward_up() {
4849        // World up = -Z (z-down world). The billboard's v (top→bottom)
4850        // must point away from `up`, and u/v must be ⟂ the view direction.
4851        let up = [0.0, 0.0, -1.0];
4852        let sprite = ImageSprite {
4853            image: ImageId { slot: 0, gen: 0 },
4854            origin: [0.0, 50.0, 0.0],
4855            facing: ImageFacing::Billboard { up },
4856            size: [4.0, 4.0],
4857            tint: OverlayColor(0xFFFF_FFFF),
4858            alpha_cutoff: 0.0,
4859            depth_test: false,
4860            double_sided: false, // billboards must NEVER cull
4861        };
4862        let q = resolve_quad(&sprite, &cam_looking_y()).expect("billboard always faces camera");
4863        let u = v_sub(q.corners[1], q.corners[0]); // TR - TL = u·size
4864        let v = v_sub(q.corners[2], q.corners[0]); // BL - TL = v·size
4865        let fwd = [0.0, 1.0, 0.0];
4866        assert!(v_dot(u, fwd).abs() < 1e-5, "u ⟂ view");
4867        assert!(v_dot(v, fwd).abs() < 1e-5, "v ⟂ view");
4868        assert!(v_dot(u, v).abs() < 1e-5, "u ⟂ v");
4869        assert!(
4870            v_dot(v, up) < 0.0,
4871            "rows grow away from `up` (top edge toward up)"
4872        );
4873    }
4874}
4875
4876#[cfg(test)]
4877mod image_map_tests {
4878    use super::{ImageId, ImageSlotMap};
4879
4880    /// QE-B6 regression — image slots are reused by the backends, so
4881    /// a stale handle must resolve to nothing rather than alias the
4882    /// texture that re-took its slot (the pre-B6 behaviour).
4883    #[test]
4884    fn image_ids_are_generational() {
4885        let mut m = ImageSlotMap::default();
4886        let a = m.alloc(0);
4887        assert_eq!(m.index(a), Some(0));
4888        assert!(m.remove(a));
4889        assert_eq!(m.index(a), None);
4890
4891        // The backend hands slot 0 out again: a fresh generation.
4892        let b = m.alloc(0);
4893        assert_ne!(a, b, "reused slot must mint a distinct handle");
4894        assert_eq!(m.index(b), Some(0));
4895        assert_eq!(m.index(a), None, "stale handle stays stale");
4896        assert!(!m.remove(a), "stale drop is refused…");
4897        assert_eq!(m.index(b), Some(0), "…and cannot hurt the newcomer");
4898
4899        // Appending past the end still works.
4900        let c = m.alloc(1);
4901        assert_eq!(m.index(c), Some(1));
4902        let _ = ImageId { slot: 9, gen: 9 };
4903        assert_eq!(m.index(ImageId { slot: 9, gen: 9 }), None);
4904    }
4905}