Skip to main content

crcbl_render/
skinning.rs

1//! The skinning prepass: joint palettes and bind-pose vertices in, skinned
2//! vertices written back into a transient region of the same vertex pool.
3//!
4//! ```text
5//!  MeshPool ──reserve_vertices ×2──▶ SkinnedRegion { prev, current }
6//!
7//!  begin_frame ──▶ palettes[frame]      (one buffer, every range end to end)
8//!              ──▶ bindings[frame]      (one buffer, every range end to end,
9//!                                         rewritten only when they change)
10//!              ──▶ params[frame][slot]  (one uniform block per range)
11//!
12//!  add_pass ──── compute "skinning"  vertex pool ──▶ vertex pool
13//!                                         │ graph barrier
14//!                    the caller's mesh pass ◀┘  ShaderRead
15//! ```
16//!
17//! GPU skinning as the rules in `docs/notes/simulation.md` (_What the deleted
18//! 17-animation plan left behind_) set it out, and the host side of
19//! `crates/crcbl-shaders/shaders/skinning.slang`. The kernel is that file's;
20//! everything here is what it cannot do for itself — allocate the region it
21//! writes into, upload the palette it blends onto, and refuse the inputs it has
22//! no way to reject.
23//!
24//! # What the pass writes is what the vertex stage pulls
25//!
26//! The one sentence the whole design hangs off, and the shader's header carries
27//! it in full: a skinned draw is an ordinary draw whose base vertex names the
28//! region this pass filled. That is why [`SkinnedRegion`] is a range of
29//! [`crate::mesh_pool`]'s pool rather than a buffer of its own.
30//!
31//! Where the base comes from is **one branch, in the raster stages**: an
32//! instance carrying
33//! [`GpuInstance::BASE_VERTEX_OVERRIDE`](crcbl_shaders::mesh::GpuInstance::BASE_VERTEX_OVERRIDE)
34//! takes it from its own record instead of from the mesh entry the draw
35//! resolved. A skinned instance still names its **source** mesh for bucket
36//! scattering and level selection. Cluster culling keeps every selected cluster
37//! of a deforming instance, because the source spheres and normal cones no
38//! longer describe the vertices that the skinning pass writes. Instance culling
39//! keeps the whole instance too, unless its record carries a box of its own —
40//! [`SkinnedInstanceDesc::bounds`](crate::SkinnedInstanceDesc::bounds) — which
41//! the culls then test in place of the source mesh's. The renderer drops this
42//! pass's dispatch for a region whose every object such a box puts out of
43//! everything the frame draws — see
44//! [`ForwardRenderer::set_skinning_culls`](crate::ForwardRenderer::set_skinning_culls).
45//!
46//! # The region is double-buffered, and the motion-vector pass reads the other half
47//!
48//! The animation plan's 2026-07-27 correction: "TAA motion vectors for
49//! skinned meshes need previous-frame skinned **positions**, not just a previous
50//! transform… the skinned-output pool region is double-buffered (prev/current
51//! ping-pong) from day one — a pool-layout decision that is nearly free now and
52//! a skinning-pipeline rewrite later."
53//!
54//! So [`SkinnedRegion`] reserves **two** runs and [`Skinning::begin_frame`]
55//! alternates which one a frame writes. **What reads the other one is the
56//! motion-vector pass**:
57//! [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
58//! writes its base into
59//! [`GpuInstance::previous_base_vertex`](crcbl_shaders::mesh::GpuInstance::previous_base_vertex)
60//! every frame, beside the current half's, and `mesh.slang`'s vertex stage and
61//! `mesh_cluster.slang`'s `emit_cluster` take a fragment's previous clip
62//! position from the vertex there. Subtracting the *current* deformed vertex
63//! instead — which is what a record with no previous base leaves them doing —
64//! gives a swinging limb the motion of the body it hangs off.
65//!
66//! The correction was followed ahead of that reader, and the alternative it
67//! avoided was shipping a pass whose output has one home and then re-pointing
68//! every bind group, every barrier and every draw that names it.
69//!
70//! # One dispatch per range, one bind group per range
71//!
72//! [`crcbl_shaders::skinning::Params`] describes exactly one contiguous run of
73//! vertices, so a frame with three animated characters is three dispatches. Each
74//! needs its own uniform block, so [`Skinning`] holds one params buffer and one
75//! bind group per (frame, range) slot and [`SkinningDesc::ranges`] is how many
76//! of those exist. The palette buffer, the skin-binding buffer and the vertex
77//! pool are shared by all of them, and a range names its own start in each.
78//!
79//! The GPU-driven form — one dispatch over a table of ranges — is what §3.3's
80//! other passes look like and is deliberately not here. It needs a range table
81//! the shader can index, which is a second layout to pin against `slangc`, and
82//! the kernel as committed reads one block.
83//!
84//! # Where a bad joint index is refused
85//!
86//! In [`Skinning::begin_frame`], by name, before anything is uploaded. The
87//! shader clamps every index against the palette length, so a malformed asset
88//! draws wrongly rather than reading past a storage buffer — but a clamp is a
89//! containment, not a diagnosis, and `docs/backlog.md` records that
90//! `crcbl-scene` cannot do better because a glTF primitive does not know its
91//! skin at import time. This call does: it is handed the palette and the
92//! bindings together, and it is the last place either is a Rust value. See
93//! [`SkinningError::JointOutOfRange`].
94//!
95//! Every joint is checked when the bindings change. A frame handing over the
96//! same bindings as the one before tests each range's palette length against
97//! the highest joint that range was found to name, which refuses exactly what
98//! the full scan would — and the scan then runs to name the vertex.
99//!
100//! # The oracle
101//!
102//! [`skin_vertex`] is this module's [`crate::cull::visible_instances`]: ordinary
103//! Rust that computes what `computeMain` computes, so a test that reads the
104//! pool back has something to compare against. Nothing in a frame calls it, and
105//! that is the point of an oracle.
106//!
107//! **Nothing in this workspace executes the kernel yet.** `crcbl-render` depends
108//! on `crcbl-hal` and no backend, so its own tests run against the null backend,
109//! which records a dispatch and never runs one. The readback that proves the
110//! kernel belongs beside the cull one in `crates/crcbl-vk/tests/vk_e2e/`, which
111//! is where `crcbl_render::cull`'s oracle is already used that way.
112
113use crcbl_hal::{
114    BindGroupDesc, BindGroupHandle, BindGroupLayoutDesc, BindGroupLayoutHandle, BufferDesc,
115    BufferHandle, BufferUsage, ComputePipelineHandle, Device, HalError, MemoryLocation,
116    PipelineLayoutDesc, PipelineLayoutHandle, ResourceState, check_portable_storage_buffers,
117};
118use crcbl_shaders::mesh::MeshVertex;
119use crcbl_shaders::skinning::{
120    JOINT_STRIDE, JOINTS_PER_VERTEX, PARAMS_SIZE, Params, SKIN_BINDING_STRIDE, SkinBinding,
121    WORKGROUP_SIZE,
122};
123use crcbl_shaders::vertex::{QTangent, TangentFrame};
124use glam::{Mat3, Mat4, Vec3, Vec4};
125
126use crate::draw_gen::{UINT_STRIDE, bound, compute_pipeline, storage, uniform};
127use crate::graph::{BufferId, ImportedBuffer, RenderGraph};
128use crate::mesh_pool::{MeshHandle, MeshPool, MeshPoolError};
129
130/// A skinned mesh's transient region of the vertex pool: two runs of the same
131/// length, one written per frame and one holding the frame before it.
132///
133/// Reserved with [`SkinnedRegion::reserve`] and given back with
134/// [`SkinnedRegion::release`]. Neither [`Clone`] nor [`Copy`], because a copy
135/// is a second thing that would try to release the same two runs.
136///
137/// See the [module docs](self) for what each of the two runs is for.
138#[derive(Debug)]
139pub struct SkinnedRegion {
140    /// The two runs' first vertices, indexed by a frame's parity.
141    bases: [u32; 2],
142    vertex_count: u32,
143}
144
145impl SkinnedRegion {
146    /// Reserves both halves from `pool`.
147    ///
148    /// Two separate reservations rather than one run of `2 * vertex_count`: a
149    /// fragmented pool can hold two halves where it has no single block for the
150    /// pair, and nothing here needs the two to be adjacent.
151    ///
152    /// # Errors
153    ///
154    /// Whatever [`MeshPool::reserve_vertices`] refuses. A failure on the second
155    /// half gives the first one back before it returns, so a refused
156    /// reservation leaks no pool space.
157    pub fn reserve(pool: &mut MeshPool, vertex_count: u32) -> Result<Self, MeshPoolError> {
158        let first = pool.reserve_vertices(vertex_count)?;
159        let second = match pool.reserve_vertices(vertex_count) {
160            Ok(second) => second,
161            Err(error) => {
162                pool.release_vertices(first, vertex_count);
163                return Err(error);
164            }
165        };
166        Ok(Self {
167            bases: [first, second],
168            vertex_count,
169        })
170    }
171
172    /// Gives both halves back to `pool`.
173    ///
174    /// The device must not be reading either of them: this is pool bookkeeping
175    /// and records no barrier, exactly like [`MeshPool::free`].
176    pub fn release(self, pool: &mut MeshPool) {
177        for base in self.bases {
178            pool.release_vertices(base, self.vertex_count);
179        }
180    }
181
182    /// Vertices in each half, which is also the skinned mesh's vertex count.
183    #[must_use]
184    pub const fn vertex_count(&self) -> u32 {
185        self.vertex_count
186    }
187
188    /// The half a frame of this parity writes — the run a draw of this mesh
189    /// takes its base vertex from.
190    ///
191    /// `parity` is [`Skinning::parity`], the alternating bit of the frame most
192    /// recently begun.
193    #[must_use]
194    pub const fn base(&self, parity: u32) -> u32 {
195        self.bases[(parity & 1) as usize]
196    }
197
198    /// The other half: what the frame before this one skinned.
199    ///
200    /// **The half a motion vector is subtracted against** — see the
201    /// [module docs](self).
202    /// [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
203    /// puts this number in every skinned instance's
204    /// [`GpuInstance::previous_base_vertex`](crcbl_shaders::mesh::GpuInstance::previous_base_vertex),
205    /// off its own copy of the two bases rather than through this call, because
206    /// a placed object keeps the pair and not the region; this is where that
207    /// indexing is defined and what a test compares against.
208    #[must_use]
209    pub const fn previous_base(&self, parity: u32) -> u32 {
210        self.bases[((parity ^ 1) & 1) as usize]
211    }
212
213    /// Both halves' first vertices, in parity order: what tells two live
214    /// regions apart, since the pool hands a run out again only once the
215    /// region holding it has been released.
216    #[must_use]
217    pub(crate) const fn halves(&self) -> [u32; 2] {
218        self.bases
219    }
220}
221
222/// A resident mesh a draw can be pointed at the skinned output of: a
223/// [`SkinnedRegion`], the mesh it was deformed from, and that mesh's own first
224/// vertex.
225///
226/// ```text
227///  source mesh ─┬─ region half 0   drawn on even frames
228///               └─ region half 1   drawn on odd frames
229/// ```
230///
231/// # The parity rides on the instance, not on the mesh table
232///
233/// [`SkinnedRegion::base`] alternates every frame, and an instance drawn out of
234/// a region carries that base itself — see
235/// [`GpuInstance::base_vertex`](crcbl_shaders::mesh::GpuInstance::base_vertex),
236/// which the raster stages read in place of the mesh entry's when
237/// [`GpuInstance::BASE_VERTEX_OVERRIDE`](crcbl_shaders::mesh::GpuInstance::BASE_VERTEX_OVERRIDE)
238/// is set. So a frame's ping-pong is a write to the instance array, which
239/// [`crate::instance_pool`] rings, and **no mesh-table entry is rewritten
240/// between frames** — the property [`crate::mesh_pool`]'s module docs rest that
241/// table's lack of a ring on.
242///
243/// [`mesh_id`](Self::mesh_id) is therefore the **source** mesh's id, one entry
244/// and not two: the bucket `draw_gen.slang` scatters the instance into and the
245/// level tables it indexes still belong to the source mesh. Culling must not
246/// reject the deformed vertices using that mesh's undeformed bounds.
247///
248/// # It does not own the mesh
249///
250/// `source`'s vertices, indices and table entry are still the pool's. Freeing
251/// that mesh while one of these is live leaves an instance naming an entry that
252/// reads as the empty range, which draws nothing.
253#[derive(Debug)]
254pub struct SkinnedMesh {
255    region: SkinnedRegion,
256    /// The source mesh's table id: what
257    /// [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh) holds for
258    /// every instance drawn out of this region, under either parity.
259    mesh: u32,
260    /// The bind pose's first vertex — what [`SkinRange::input_base`] wants, kept
261    /// here so the one call that needs it cannot be handed the skinned base by
262    /// mistake.
263    input_base: u32,
264}
265
266impl SkinnedMesh {
267    /// Reserves a region as long as `source`'s vertex run.
268    ///
269    /// Nothing writes the region: it holds whatever its allocation came with
270    /// until a [`Skinning`] dispatch fills it, exactly as
271    /// [`MeshPool::reserve_vertices`] says. A draw out of it before that has
272    /// happened is a draw of undefined vertices, which is what
273    /// [`crate::forward::ForwardRenderer::add_skinned_passes`] exists to make
274    /// impossible to record.
275    ///
276    /// # Errors
277    ///
278    /// [`MeshPoolError::NotResident`] if `source` is not a resident mesh of this
279    /// pool, and whatever [`SkinnedRegion::reserve`] refuses — a pool with no
280    /// room for both halves. **A failure gives back everything the earlier steps
281    /// took**, so a refused reservation leaks no pool space.
282    pub fn reserve(pool: &mut MeshPool, source: MeshHandle) -> Result<Self, MeshPoolError> {
283        let range = pool
284            .mesh(source)
285            .ok_or(MeshPoolError::NotResident { handle: source })?;
286        let vertex_count = pool
287            .vertex_count(source)
288            .ok_or(MeshPoolError::NotResident { handle: source })?;
289        let region = SkinnedRegion::reserve(pool, vertex_count)?;
290        Ok(Self {
291            region,
292            mesh: source.index(),
293            input_base: range.base_vertex,
294        })
295    }
296
297    /// Gives the region back.
298    ///
299    /// The device must not be reading either half: this records no barrier, on
300    /// [`SkinnedRegion::release`]'s terms. It takes no table entry back, because
301    /// it never took one — the source mesh's entry is the pool's and outlives
302    /// this.
303    pub fn release(self, pool: &mut MeshPool) {
304        self.region.release(pool);
305    }
306
307    /// The region the dispatch writes and the draws read.
308    #[must_use]
309    pub const fn region(&self) -> &SkinnedRegion {
310        &self.region
311    }
312
313    /// Vertices in each half, which is the bind pose's vertex count.
314    #[must_use]
315    pub const fn vertex_count(&self) -> u32 {
316        self.region.vertex_count()
317    }
318
319    /// The bind pose's first vertex: [`SkinRange::input_base`].
320    #[must_use]
321    pub const fn input_base(&self) -> u32 {
322        self.input_base
323    }
324
325    /// The mesh-table id an instance drawn out of this region carries — what
326    /// [`GpuInstance::mesh`](crcbl_shaders::mesh::GpuInstance::mesh) holds.
327    ///
328    /// The **source** mesh's, and the same under either parity: what changes
329    /// per frame is
330    /// [`GpuInstance::base_vertex`](crcbl_shaders::mesh::GpuInstance::base_vertex),
331    /// which [`SkinnedRegion::base`] answers for.
332    #[must_use]
333    pub const fn mesh_id(&self) -> u32 {
334        self.mesh
335    }
336
337    /// This mesh's [`SkinRange`] for one frame, given the palette and the
338    /// bindings.
339    ///
340    /// The only way to build one where `input_base` and `region` can disagree
341    /// about which mesh they belong to, which is the mistake that would skin one
342    /// primitive's vertices into another's region.
343    #[must_use]
344    pub const fn skin_range<'a>(
345        &'a self,
346        palette: &'a [Mat4],
347        bindings: &'a [SkinBinding],
348    ) -> SkinRange<'a> {
349        SkinRange {
350            input_base: self.input_base,
351            region: &self.region,
352            palette,
353            bindings,
354        }
355    }
356}
357
358/// What a [`Skinning`] refuses to do.
359#[derive(Debug, thiserror::Error)]
360pub enum SkinningError {
361    /// A skin binding names a joint the range's palette has not got.
362    ///
363    /// **The check `crcbl-scene` could not make.** A glTF primitive's
364    /// `JOINTS_0` is validated at import against the attribute lengths and
365    /// against nothing else, because a primitive does not know which skin will
366    /// be applied to it; this call is handed the palette and the bindings
367    /// together and can say. The shader clamps such an index rather than
368    /// reading past the palette, so the containment is real either way — but a
369    /// clamped index is a mesh that deforms wrongly with nothing to look at,
370    /// and this names the vertex.
371    #[error(
372        "range {range}'s vertex {vertex} is bound to joint {joint} in slot {slot}, and its \
373         palette holds {palette} — the shader would clamp it and the mesh would deform wrongly"
374    )]
375    JointOutOfRange {
376        /// Which of the frame's ranges, in the order they were handed over.
377        range: usize,
378        /// The vertex within that range.
379        vertex: usize,
380        /// Which of the four joint slots of that vertex.
381        slot: usize,
382        /// The index it named.
383        joint: u32,
384        /// Matrices the range's palette actually holds.
385        palette: usize,
386    },
387    /// A range's palette is empty.
388    ///
389    /// Refused here rather than left to
390    /// [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes), which
391    /// panics: the shader clamps against `joint_count - 1`, so an empty palette
392    /// is every index in the buffer.
393    #[error("range {range} has an empty joint palette, which the shader's index clamp would wrap")]
394    EmptyPalette {
395        /// Which of the frame's ranges.
396        range: usize,
397    },
398    /// A range's skin bindings are not one per vertex of its region.
399    ///
400    /// They are parallel arrays — binding `i` describes bind-pose vertex `i` —
401    /// so a short list would leave the tail of the mesh reading another range's
402    /// bindings, and a long one is a caller that has the wrong region.
403    #[error(
404        "range {range} covers {vertices} vertices and was given {bindings} skin bindings; they \
405         are parallel runs and must be the same length"
406    )]
407    BindingCountMismatch {
408        /// Which of the frame's ranges.
409        range: usize,
410        /// Vertices in the range's region.
411        vertices: u32,
412        /// Bindings offered.
413        bindings: usize,
414    },
415    /// More ranges, palette matrices or skin bindings than this pass was built
416    /// for.
417    ///
418    /// Refused rather than truncated, for [`crate::light_grid`]'s reason: a
419    /// character silently missing from the frame is what the capacity exists to
420    /// prevent, and nothing downstream would report it.
421    #[error(
422        "this skinning pass holds {capacity} {what} and the frame asked for {asked}; raise \
423         the renderer's skinning capacity rather than dropping a character, which no counter \
424         would report"
425    )]
426    OverCapacity {
427        /// `"ranges"`, `"palette matrices"` or `"skin bindings"`.
428        what: &'static str,
429        /// What the pass was built with.
430        capacity: u32,
431        /// What the frame needed.
432        asked: u64,
433    },
434    /// Anything the seam refused.
435    #[error(transparent)]
436    Hal(#[from] HalError),
437}
438
439/// How large a [`Skinning`] is, and what it writes into.
440#[derive(Clone, Copy, Debug, PartialEq, Eq)]
441pub struct SkinningDesc<'a> {
442    /// Debug name; every buffer, group and pipeline is named after it.
443    pub label: Option<&'a str>,
444    /// How many frames in flight, and so how long every ring here is.
445    pub frames: usize,
446    /// Skinned ranges one frame can dispatch — one animated primitive each.
447    ///
448    /// A params buffer and a bind group exist per (frame, range), so this is a
449    /// capacity rather than a hint.
450    pub ranges: u32,
451    /// Palette matrices the joint buffer holds, summed across every range of
452    /// one frame.
453    pub joints: u32,
454    /// Skin bindings the binding buffer holds, likewise — which is the total
455    /// **skinned** vertex count, not the vertex pool's capacity. See
456    /// [`Params::binding_base`](crcbl_shaders::skinning::Params::binding_base).
457    pub bindings: u32,
458    /// The vertex pool this pass reads the bind pose from and writes the
459    /// skinned vertices into: [`MeshPool::vertex_buffer`].
460    ///
461    /// One binding, read at one base and written at another — WebGPU forbids
462    /// the same range appearing as a writable storage buffer and as anything
463    /// else in one usage scope, so the two-view spelling is a
464    /// `createBindGroup` failure in the browser rather than a matter of taste.
465    pub vertices: BufferHandle,
466    /// Where that pool's **attribute** region begins, in words:
467    /// [`MeshPool::attribute_base`].
468    ///
469    /// The dispatch reads and writes both streams, and the boundary is the
470    /// pool's capacity — which is why it arrives here rather than being derived:
471    /// see `crcbl_shaders::skinning::Params::attribute_base`, the block lane it
472    /// ends up in.
473    ///
474    /// [`MeshPool::attribute_base`]: crate::MeshPool::attribute_base
475    pub attribute_base: u32,
476}
477
478/// One range the caller asks to be skinned this frame: one animated
479/// primitive's bind pose, its region, its palette and its per-vertex bindings.
480#[derive(Clone, Copy, Debug)]
481pub struct SkinRange<'a> {
482    /// First vertex of the **bind-pose** run in the pool —
483    /// [`MeshRange::base_vertex`](crate::mesh_pool::MeshRange::base_vertex).
484    pub input_base: u32,
485    /// Where the skinned vertices go. Its
486    /// [`vertex_count`](SkinnedRegion::vertex_count) is the dispatch's extent.
487    pub region: &'a SkinnedRegion,
488    /// This instance's joint palette — what
489    /// [`crcbl_anim::Palette::matrices`] hands out: each joint's global
490    /// transform times its inverse bind matrix, with the skinned node's own
491    /// transform deliberately absent.
492    ///
493    /// [`crcbl_anim::Palette::matrices`]: https://docs.rs/crcbl-anim
494    pub palette: &'a [Mat4],
495    /// One entry per vertex of the bind-pose run, in the same order.
496    pub bindings: &'a [SkinBinding],
497}
498
499/// The palette buffer, the skin-binding buffer, the per-range uniform blocks
500/// and the compute pass over them.
501#[derive(Debug)]
502pub struct Skinning {
503    /// `[frame]` — every range's palette, end to end.
504    palettes: Vec<BufferHandle>,
505    /// `[frame]` — every range's skin bindings, end to end.
506    bindings: Vec<BufferHandle>,
507    /// `[frame][range]` — one uniform block each.
508    params: Vec<Vec<BufferHandle>>,
509    /// `[frame][range]`, in the same order.
510    groups: Vec<Vec<BindGroupHandle>>,
511    /// `[frame]` — each range [`Skinning::begin_frame`] was last handed for
512    /// that slot, in range order: its group count and the region it writes.
513    active: Vec<Vec<Planned>>,
514    layout: BindGroupLayoutHandle,
515    pipeline_layout: PipelineLayoutHandle,
516    pipeline: ComputePipelineHandle,
517    vertices: BufferHandle,
518    /// [`SkinningDesc::attribute_base`], carried into every block this pass
519    /// writes.
520    attribute_base: u32,
521    range_capacity: u32,
522    joint_capacity: u32,
523    binding_capacity: u32,
524    /// Frames [`Skinning::begin_frame`] has accepted. Its low bit is the
525    /// ping-pong.
526    frames_begun: u64,
527    /// The skin bindings most recently passed validation, end to end, and what
528    /// each range of them was checked to name — see [`Bindings`]. Kept even if
529    /// a device write later fails that frame: they were valid, and the slots'
530    /// generations say which of them still need writing.
531    latest: Bindings,
532    /// `[frame]` — the [`Bindings::generation`] that slot's binding buffer
533    /// holds, or [`None`] for one it is not known to hold.
534    uploaded: Vec<Option<u64>>,
535}
536
537/// One range of a slot's plan: what [`Skinning::add_pass`] dispatches for it.
538#[derive(Clone, Copy, Debug)]
539struct Planned {
540    /// Workgroups the dispatch covers.
541    groups: u32,
542    /// The region it writes, as [`SkinnedRegion::halves`] names it.
543    region: [u32; 2],
544}
545
546/// The skin bindings a [`Skinning`] last accepted, kept so a frame handing over
547/// the same ones again is neither re-checked nor re-uploaded.
548///
549/// Bindings are a mesh's own vertex data and do not move from one frame to the
550/// next, where the palette does. Comparing against this copy is one read of
551/// each; what it saves is the joint scan, the serialisation and the write into
552/// host-visible memory, every frame.
553#[derive(Debug, Default)]
554struct Bindings {
555    /// Every range's bindings, end to end, in the order they were handed over.
556    all: Vec<SkinBinding>,
557    /// Per range: how many of `all` it covers, and the highest joint index any
558    /// slot of them names — what [`SkinningError::JointOutOfRange`] tests a
559    /// palette against, so an unchanged range is checked in one comparison.
560    ranges: Vec<(usize, u32)>,
561    /// Bumped whenever `all` changes; a slot whose
562    /// [`Skinning::uploaded`] entry differs is re-uploaded.
563    generation: u64,
564}
565
566impl Bindings {
567    /// Whether `ranges` hand over exactly these bindings, range for range.
568    fn matches(&self, ranges: &[SkinRange<'_>]) -> bool {
569        if self.ranges.len() != ranges.len() {
570            return false;
571        }
572        let mut at = 0;
573        for (range, &(len, _)) in ranges.iter().zip(&self.ranges) {
574            if range.bindings.len() != len || !same_bits(range.bindings, &self.all[at..at + len]) {
575                return false;
576            }
577            at += len;
578        }
579        true
580    }
581}
582
583/// Whether two binding runs are the same **bits**, which is what the buffer
584/// holds — `f32`'s `==` calls `-0.0` and `0.0` equal and a `NaN` unequal to
585/// itself, which would skip an upload that changes the buffer and repeat one
586/// that does not.
587fn same_bits(a: &[SkinBinding], b: &[SkinBinding]) -> bool {
588    a.len() == b.len()
589        && a.iter().zip(b).all(|(a, b)| {
590            a.joints == b.joints && a.weights.map(f32::to_bits) == b.weights.map(f32::to_bits)
591        })
592}
593
594/// The highest joint index any slot of `range`'s bindings names, or the first
595/// one past its palette, refused by name.
596///
597/// **The check the shader cannot make and `crcbl-scene` could not make
598/// either** — see [`SkinningError::JointOutOfRange`]. Every slot of every
599/// vertex, including the ones carrying zero weight: the shader reads all four
600/// matrices before it scales any of them, so a weightless slot naming a joint
601/// past the palette is the same clamped read as a weighted one.
602fn highest_joint(index: usize, range: &SkinRange<'_>) -> Result<u32, SkinningError> {
603    let mut highest = 0;
604    for (vertex, binding) in range.bindings.iter().enumerate() {
605        for (slot, joint) in binding.joints.iter().enumerate() {
606            if *joint as usize >= range.palette.len() {
607                return Err(SkinningError::JointOutOfRange {
608                    range: index,
609                    vertex,
610                    slot,
611                    joint: *joint,
612                    palette: range.palette.len(),
613                });
614            }
615            highest = highest.max(*joint);
616        }
617    }
618    Ok(highest)
619}
620
621impl Skinning {
622    /// Builds every buffer, every bind group and the skinning pipeline.
623    ///
624    /// # Errors
625    ///
626    /// [`SkinningError::Hal`] if a resource could not be created, and
627    /// [`HalError::InvalidDescriptor`] through it for a descriptor asking for
628    /// no frames, no ranges, no joints or no bindings — a buffer of zero bytes
629    /// is not a buffer on any backend the engine targets.
630    pub fn new(device: &dyn Device, desc: &SkinningDesc<'_>) -> Result<Self, SkinningError> {
631        if desc.frames == 0 || desc.ranges == 0 || desc.joints == 0 || desc.bindings == 0 {
632            return Err(HalError::InvalidDescriptor(
633                "a skinning pass needs at least one frame in flight, one range, one palette \
634                 matrix and one skin binding"
635                    .to_string(),
636            )
637            .into());
638        }
639        let label = desc.label.unwrap_or("skinning");
640
641        let mut rollback = Rollback::default();
642        let result = Self::build(device, desc, label, &mut rollback);
643        if result.is_err() {
644            rollback.run(device);
645        }
646        result
647    }
648
649    fn build(
650        device: &dyn Device,
651        desc: &SkinningDesc<'_>,
652        label: &str,
653        rollback: &mut Rollback,
654    ) -> Result<Self, SkinningError> {
655        // `skinning.slang`'s declaration order, which
656        // `crcbl_shaders::skinning`'s bind-group table records and
657        // `crcbl_shaders::declaration_order` holds the shader to. The vertex
658        // pool is the one writable entry.
659        let entries = [
660            uniform(0),
661            storage(1, true, crcbl_shaders::skinning::JOINT_STRIDE as u32),
662            storage(2, true, crcbl_shaders::skinning::SKIN_BINDING_STRIDE as u32),
663            storage(3, false, UINT_STRIDE),
664        ];
665        let layout_desc = BindGroupLayoutDesc {
666            label: Some(label),
667            entries: &entries,
668        };
669        check_portable_storage_buffers(Some(label), &[&layout_desc])?;
670        let layout = device.create_bind_group_layout(&layout_desc)?;
671        rollback.layouts.push(layout);
672        let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDesc {
673            label: Some(label),
674            bind_group_layouts: &[layout],
675            push_constants: None,
676        })?;
677        rollback.pipeline_layouts.push(pipeline_layout);
678        let pipeline = compute_pipeline(
679            device,
680            label,
681            &crcbl_shaders::SKINNING,
682            pipeline_layout,
683            WORKGROUP_SIZE,
684        )?;
685        rollback.pipelines.push(pipeline);
686
687        let mut palettes = Vec::with_capacity(desc.frames);
688        let mut bindings = Vec::with_capacity(desc.frames);
689        let mut params = Vec::with_capacity(desc.frames);
690        let mut groups = Vec::with_capacity(desc.frames);
691        for frame in 0..desc.frames {
692            let mut buffer = |name: &str, size: u64, usage| {
693                let handle = device.create_buffer(&BufferDesc {
694                    label: Some(&format!("{label} {name} {frame}")),
695                    size,
696                    usage,
697                    // Host-uploaded and bound **read-only**, which is what keeps
698                    // them off `crate::draw_gen`'s device-local rule: D3D12
699                    // refuses an unordered-access view of an upload heap, not a
700                    // shader resource view of one. The one buffer a shader
701                    // writes here is the vertex pool, and `crate::mesh_pool`
702                    // already makes that device-local.
703                    memory: MemoryLocation::HostUpload,
704                })?;
705                rollback.buffers.push(handle);
706                Ok::<_, HalError>(handle)
707            };
708            let palette = buffer(
709                "palette",
710                u64::from(desc.joints) * JOINT_STRIDE as u64,
711                BufferUsage::STORAGE,
712            )?;
713            let skin = buffer(
714                "bindings",
715                u64::from(desc.bindings) * SKIN_BINDING_STRIDE as u64,
716                BufferUsage::STORAGE,
717            )?;
718
719            let mut frame_params = Vec::with_capacity(desc.ranges as usize);
720            let mut frame_groups = Vec::with_capacity(desc.ranges as usize);
721            for range in 0..desc.ranges {
722                let block = buffer(
723                    &format!("params {range}"),
724                    PARAMS_SIZE as u64,
725                    BufferUsage::UNIFORM,
726                )?;
727                let group = device.create_bind_group(&BindGroupDesc {
728                    label: Some(&format!("{label} {frame} {range}")),
729                    layout,
730                    entries: &[
731                        bound(0, block),
732                        bound(1, palette),
733                        bound(2, skin),
734                        bound(3, desc.vertices),
735                    ],
736                    // No binding here is an array, so nothing has a runtime
737                    // length to declare.
738                    variable_count: None,
739                })?;
740                rollback.groups.push(group);
741                frame_params.push(block);
742                frame_groups.push(group);
743            }
744
745            palettes.push(palette);
746            bindings.push(skin);
747            params.push(frame_params);
748            groups.push(frame_groups);
749        }
750
751        Ok(Self {
752            palettes,
753            bindings,
754            params,
755            groups,
756            active: vec![Vec::new(); desc.frames],
757            layout,
758            pipeline_layout,
759            pipeline,
760            vertices: desc.vertices,
761            attribute_base: desc.attribute_base,
762            range_capacity: desc.ranges,
763            joint_capacity: desc.joints,
764            binding_capacity: desc.bindings,
765            frames_begun: 0,
766            latest: Bindings::default(),
767            uploaded: vec![None; desc.frames],
768        })
769    }
770
771    /// Ranges one frame can dispatch.
772    #[must_use]
773    pub const fn range_capacity(&self) -> u32 {
774        self.range_capacity
775    }
776
777    /// Palette matrices one frame's joint buffer holds, across every range.
778    #[must_use]
779    pub const fn joint_capacity(&self) -> u32 {
780        self.joint_capacity
781    }
782
783    /// Skin bindings one frame's binding buffer holds, across every range.
784    #[must_use]
785    pub const fn binding_capacity(&self) -> u32 {
786        self.binding_capacity
787    }
788
789    /// Which half of every [`SkinnedRegion`] the frame most recently begun
790    /// writes.
791    ///
792    /// Zero before the first [`begin_frame`](Self::begin_frame), which names a
793    /// half no dispatch has filled — there is nothing to draw yet either way.
794    #[must_use]
795    pub const fn parity(&self) -> u32 {
796        (self.frames_begun % 2) as u32
797    }
798
799    /// Validates `ranges`, alternates the ping-pong, and uploads the palette,
800    /// one uniform block per range, and the skin bindings **if this slot does
801    /// not already hold them**.
802    ///
803    /// Call once per frame, before [`Skinning::add_pass`], against the frame
804    /// slot the instance pool rotated to. A frame with no skinned meshes calls
805    /// it with an empty slice, which clears the slot's plan — otherwise the
806    /// pass would re-dispatch the ranges of whichever frame last used it.
807    ///
808    /// # The bindings are uploaded when they change, into every slot
809    ///
810    /// A mesh's bindings are its own vertex data, so a frame normally hands
811    /// over the very ones the frame before it did. This keeps the last
812    /// accepted set and compares against it: an unchanged set is neither
813    /// re-checked joint by joint nor re-written. A changed one is checked in
814    /// full and given a new generation, and each slot's binding buffer is
815    /// rewritten the next time that slot begins a frame — once per slot, so
816    /// every frame in flight reads the set it was handed, whichever slot it
817    /// landed in.
818    ///
819    /// # Errors
820    ///
821    /// [`SkinningError::JointOutOfRange`], [`SkinningError::EmptyPalette`],
822    /// [`SkinningError::BindingCountMismatch`] and
823    /// [`SkinningError::OverCapacity`] for inputs the dispatch could not be
824    /// built from, all of them checked **before** anything is written, so a
825    /// refused frame leaves the slot's buffers alone; and
826    /// [`SkinningError::Hal`] if a write failed, after which the slot
827    /// dispatches nothing until a later frame succeeds on it.
828    ///
829    /// # Panics
830    ///
831    /// If `frame` is not a slot this was built with.
832    pub fn begin_frame(
833        &mut self,
834        device: &dyn Device,
835        frame: usize,
836        ranges: &[SkinRange<'_>],
837    ) -> Result<(), SkinningError> {
838        if let Some(shapes) = self.check(ranges)? {
839            let latest = &mut self.latest;
840            latest.all.clear();
841            for range in ranges {
842                latest.all.extend_from_slice(range.bindings);
843            }
844            latest.ranges = shapes;
845            latest.generation = latest.generation.wrapping_add(1);
846        }
847
848        // Cleared before anything is written rather than replaced after: a
849        // write that fails part-way would otherwise leave this slot dispatching
850        // the *previous* frame's plan against uniform blocks half of which have
851        // already been overwritten, which is a mesh skinned onto another
852        // instance's palette. Nothing dispatched is the honest outcome.
853        self.active[frame].clear();
854
855        // The ping-pong, and the only place it moves: one step per frame that
856        // was accepted, so `parity` alternates and the half a frame did not
857        // write is the half the frame before it did.
858        self.frames_begun = self.frames_begun.wrapping_add(1);
859        let parity = self.parity();
860
861        let joints: usize = ranges.iter().map(|range| range.palette.len()).sum();
862        let mut palette_bytes = Vec::with_capacity(joints * JOINT_STRIDE);
863        let mut binding_base = 0u32;
864        let mut plan = Vec::with_capacity(ranges.len());
865        for (slot, range) in ranges.iter().enumerate() {
866            let vertex_count = range.region.vertex_count();
867            let block = Params {
868                vertex_count,
869                input_base: range.input_base,
870                output_base: range.region.base(parity),
871                binding_base,
872                joint_base: (palette_bytes.len() / JOINT_STRIDE) as u32,
873                joint_count: range.palette.len() as u32,
874                attribute_base: self.attribute_base,
875            };
876            // `to_bytes` panics on an overlap and on an empty palette. Neither
877            // can happen here: `check` refused the empty palette by name, and
878            // the two runs are separate `MeshPool` allocations, which the free
879            // list never hands out twice. It is the backstop, not the check.
880            device.write_buffer(self.params[frame][slot], 0, &block.to_bytes())?;
881
882            write_palette(&mut palette_bytes, range.palette);
883            // `check` held the total to the binding capacity, which is a `u32`.
884            binding_base += vertex_count;
885            plan.push(Planned {
886                groups: vertex_count.div_ceil(WORKGROUP_SIZE),
887                region: range.region.halves(),
888            });
889        }
890
891        if !palette_bytes.is_empty() {
892            device.write_buffer(self.palettes[frame], 0, &palette_bytes)?;
893        }
894        let generation = self.latest.generation;
895        if self.uploaded[frame] != Some(generation) {
896            // Forgotten first, so a write that fails leaves the slot due for
897            // another rather than claiming bytes it may only half hold.
898            self.uploaded[frame] = None;
899            if !self.latest.all.is_empty() {
900                let bytes: Vec<u8> = self
901                    .latest
902                    .all
903                    .iter()
904                    .flat_map(SkinBinding::to_bytes)
905                    .collect();
906                device.write_buffer(self.bindings[frame], 0, &bytes)?;
907            }
908            self.uploaded[frame] = Some(generation);
909        }
910        self.active[frame] = plan;
911        Ok(())
912    }
913
914    /// Everything [`begin_frame`](Self::begin_frame) refuses, checked before it
915    /// writes anything.
916    ///
917    /// Returns each range's binding count and highest joint when the bindings
918    /// differ from [`Skinning::latest`], and [`None`] when they are the same —
919    /// whose joints were checked when they were accepted, so only the palette
920    /// lengths, which do move, are tested against them again.
921    fn check(&self, ranges: &[SkinRange<'_>]) -> Result<Option<Vec<(usize, u32)>>, SkinningError> {
922        let over = |what, capacity, asked| SkinningError::OverCapacity {
923            what,
924            capacity,
925            asked,
926        };
927        if ranges.len() as u64 > u64::from(self.range_capacity) {
928            return Err(over("ranges", self.range_capacity, ranges.len() as u64));
929        }
930
931        let mut shapes = (!self.latest.matches(ranges)).then(|| Vec::with_capacity(ranges.len()));
932        let mut joints = 0u64;
933        let mut bindings = 0u64;
934        for (index, range) in ranges.iter().enumerate() {
935            if range.palette.is_empty() {
936                return Err(SkinningError::EmptyPalette { range: index });
937            }
938            let vertices = range.region.vertex_count();
939            if range.bindings.len() as u64 != u64::from(vertices) {
940                return Err(SkinningError::BindingCountMismatch {
941                    range: index,
942                    vertices,
943                    bindings: range.bindings.len(),
944                });
945            }
946            match shapes.as_mut() {
947                Some(shapes) => shapes.push((range.bindings.len(), highest_joint(index, range)?)),
948                // The same bindings with a shorter palette still have to be
949                // refused, and by name: the scan that names the vertex runs
950                // only once the one comparison says it will find one.
951                None if self.latest.ranges[index].1 as usize >= range.palette.len() => {
952                    highest_joint(index, range)?;
953                }
954                None => {}
955            }
956            joints += range.palette.len() as u64;
957            bindings += range.bindings.len() as u64;
958        }
959        if joints > u64::from(self.joint_capacity) {
960            return Err(over("palette matrices", self.joint_capacity, joints));
961        }
962        if bindings > u64::from(self.binding_capacity) {
963            return Err(over("skin bindings", self.binding_capacity, bindings));
964        }
965        Ok(shapes)
966    }
967
968    /// How many passes [`add_pass`](Self::add_pass) adds to a frame.
969    ///
970    /// **At most one**, not exactly one: a frame whose
971    /// [`begin_frame`](Self::begin_frame) was handed no ranges adds nothing,
972    /// because a pass with an empty body would still cost the vertex pool two
973    /// barriers it has no use for.
974    pub const MAX_PASSES: u32 = 1;
975
976    /// Adds the skinning pass to `graph` and returns the vertex pool's id, or
977    /// [`None`] when this frame has nothing to skin.
978    ///
979    /// The id is what a caller declaring its own read of the pool must use: the
980    /// graph orders this pass against a mesh pass only when both name the
981    /// **same** buffer node, and importing the pool twice would be two
982    /// resources it cannot order against each other. So a mesh pass drawing
983    /// skinned geometry passes this id to
984    /// [`PassBuilder::read_buffer`](crate::graph::PassBuilder::read_buffer),
985    /// and must be added after this.
986    ///
987    /// # Panics
988    ///
989    /// If `frame` is not a slot this was built with.
990    pub fn add_pass(&self, graph: &mut RenderGraph<'_>, frame: usize) -> Option<BufferId> {
991        self.add_pass_where(graph, frame, |_| true)
992    }
993
994    /// The regions slot `frame`'s plan writes, in range order, each as
995    /// [`SkinnedRegion::halves`] names it.
996    ///
997    /// # Panics
998    ///
999    /// If `frame` is not a slot this was built with.
1000    pub(crate) fn planned_regions(&self, frame: usize) -> impl Iterator<Item = [u32; 2]> + '_ {
1001        self.active[frame].iter().map(|planned| planned.region)
1002    }
1003
1004    /// [`add_pass`](Self::add_pass) dispatching only the ranges whose region
1005    /// `keep` answers `true` for — the renderer's skinning cull, see
1006    /// `ForwardRenderer::cull_skinned_regions`. A plan `keep` empties adds no
1007    /// pass and returns [`None`], on `add_pass`'s terms.
1008    ///
1009    /// **The plan is left as it is**: the palettes and blocks were uploaded by
1010    /// [`begin_frame`](Self::begin_frame), the parity has moved, and a range
1011    /// dropped here leaves both halves of its region holding what they held.
1012    /// What a draw out of such a region then reads is the caller's to make
1013    /// impossible.
1014    ///
1015    /// # Panics
1016    ///
1017    /// If `frame` is not a slot this was built with.
1018    pub(crate) fn add_pass_where(
1019        &self,
1020        graph: &mut RenderGraph<'_>,
1021        frame: usize,
1022        keep: impl Fn([u32; 2]) -> bool,
1023    ) -> Option<BufferId> {
1024        let dispatches: Vec<(BindGroupHandle, u32)> = self.active[frame]
1025            .iter()
1026            .enumerate()
1027            .filter(|(_, planned)| keep(planned.region))
1028            .map(|(slot, planned)| (self.groups[frame][slot], planned.groups))
1029            .collect();
1030        if dispatches.is_empty() {
1031            return None;
1032        }
1033
1034        // The pool arrives in the state `MeshPool::upload` left it in and the
1035        // state every mesh pass reads it in, which are the same one.
1036        let pool = graph.import_buffer(
1037            "vertex-pool",
1038            ImportedBuffer {
1039                buffer: self.vertices,
1040                initial: ResourceState::ShaderRead,
1041                final_state: ResourceState::ShaderRead,
1042            },
1043        );
1044        let pipeline = self.pipeline;
1045        let layout = self.pipeline_layout;
1046        graph
1047            .add_compute_pass("skinning")
1048            // One declaration for one binding: the bind pose is read and the
1049            // skinned run is written through the same descriptor, so there is
1050            // no read-only half to declare separately.
1051            .use_buffer(pool, ResourceState::ShaderReadWrite)
1052            .execute(move |ctx| {
1053                let encoder = ctx.encoder();
1054                encoder.bind_compute_pipeline(pipeline);
1055                for (group, groups) in dispatches {
1056                    encoder.bind_group(0, group, &[], layout);
1057                    encoder.dispatch(groups, 1, 1);
1058                }
1059            });
1060        Some(pool)
1061    }
1062
1063    /// Releases everything, in dependency order. The device must be idle.
1064    ///
1065    /// The vertex pool is **not** released here: it is
1066    /// [`crate::mesh_pool`]'s, and this pass only ever borrowed the handle.
1067    pub fn destroy(self, device: &dyn Device) {
1068        device.destroy_compute_pipeline(self.pipeline);
1069        device.destroy_pipeline_layout(self.pipeline_layout);
1070        for group in self.groups.into_iter().flatten() {
1071            device.destroy_bind_group(group);
1072        }
1073        device.destroy_bind_group_layout(self.layout);
1074        for buffer in self
1075            .palettes
1076            .into_iter()
1077            .chain(self.bindings)
1078            .chain(self.params.into_iter().flatten())
1079        {
1080            device.destroy_buffer(buffer);
1081        }
1082    }
1083}
1084
1085/// What a failed [`Skinning::new`] has to give back, in the order it must.
1086#[derive(Default)]
1087struct Rollback {
1088    pipelines: Vec<ComputePipelineHandle>,
1089    pipeline_layouts: Vec<PipelineLayoutHandle>,
1090    groups: Vec<BindGroupHandle>,
1091    layouts: Vec<BindGroupLayoutHandle>,
1092    buffers: Vec<BufferHandle>,
1093}
1094
1095impl Rollback {
1096    fn run(self, device: &dyn Device) {
1097        for pipeline in self.pipelines {
1098            device.destroy_compute_pipeline(pipeline);
1099        }
1100        for layout in self.pipeline_layouts {
1101            device.destroy_pipeline_layout(layout);
1102        }
1103        for group in self.groups {
1104            device.destroy_bind_group(group);
1105        }
1106        for layout in self.layouts {
1107            device.destroy_bind_group_layout(layout);
1108        }
1109        for buffer in self.buffers {
1110            device.destroy_buffer(buffer);
1111        }
1112    }
1113}
1114
1115// --- the oracle ------------------------------------------------------------
1116
1117/// The matrix `computeMain` blends before it transforms anything: the four
1118/// palette matrices scaled by the four weights and summed.
1119///
1120/// **Blended first, transformed once** — the shader's own order, and for a
1121/// normal it is not the same answer as transforming four times and blending the
1122/// results. The kernel's header carries that argument.
1123///
1124/// `joints` are clamped against `palette.len() - 1` exactly as the shader
1125/// clamps them, so this reproduces what a malformed asset actually draws rather
1126/// than what it meant to.
1127///
1128/// # Panics
1129///
1130/// If `palette` is empty, which is the clamp's `joint_count - 1` wrapping and
1131/// what [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes) refuses
1132/// on the buffer side.
1133#[must_use]
1134pub fn blend(palette: &[Mat4], binding: &SkinBinding) -> Mat4 {
1135    assert!(
1136        !palette.is_empty(),
1137        "a skinned vertex with an empty joint palette has nothing to blend onto, and the \
1138         shader's index clamp would wrap"
1139    );
1140    let last = palette.len() - 1;
1141    let mut blended = Mat4::ZERO;
1142    for slot in 0..JOINTS_PER_VERTEX {
1143        let joint = (binding.joints[slot] as usize).min(last);
1144        blended += palette[joint] * binding.weights[slot];
1145    }
1146    blended
1147}
1148
1149/// The matrix that carries a normal through the linear part `basis` carries a
1150/// tangent through: the **cofactor** matrix, matching `normal_basis` in
1151/// `crates/crcbl-shaders/shaders/skinning.slang` term for term.
1152///
1153/// Row `i` is the cross product of the other two rows in cyclic order, which is
1154/// `det(basis)` times the inverse transpose. A normal is perpendicular to a
1155/// surface and only an angle-preserving transform carries a perpendicular the
1156/// way it carries a tangent, so the bare 3×3 is the wrong matrix the moment a
1157/// joint carries a non-uniform scale.
1158///
1159/// The cross-product form rather than `inverse().transpose() * determinant()`:
1160/// it is what the shader computes, and it is defined for a singular basis —
1161/// where the inverse is not, and where a blend of joints can genuinely land.
1162#[must_use]
1163pub fn normal_basis(basis: Mat3) -> Mat3 {
1164    let (first, second, third) = (basis.row(0), basis.row(1), basis.row(2));
1165    // The three cross products are the cofactor's *rows*, and `from_cols` takes
1166    // columns — so this builds the transpose and puts it back.
1167    Mat3::from_cols(second.cross(third), third.cross(first), first.cross(second)).transpose()
1168}
1169
1170/// One vertex as `computeMain` writes it: the oracle a readback compares
1171/// against.
1172///
1173/// Ordinary Rust, and nothing in a frame calls it — [`crate::cull`]'s
1174/// [`visible_instances`](crate::cull::visible_instances) is the same shape for
1175/// the same reason. A dispatch that runs and writes a buffer nobody reads is
1176/// indistinguishable from one that does nothing.
1177///
1178/// Everything the kernel does, in the order it does it:
1179///
1180/// * the four palette matrices are blended by the four weights, **used exactly
1181///   as stored and never renormalised** — a set summing to 0.9 pulls its vertex
1182///   a tenth of the way to the palette's origin, which is the loudest failure
1183///   available and what the shader deliberately keeps;
1184/// * the position goes through the blended matrix;
1185/// * the normal goes through [`normal_basis`] of its linear part, and is
1186///   normalised **only if it is non-zero** — the shader's guard, whose fallback
1187///   is the bind-pose normal, because a `NaN` written into the pool is read
1188///   again by the shadow passes;
1189/// * the tangent goes through the **bare** linear part, because a tangent lies
1190///   in the surface where a normal is perpendicular to it, and is then
1191///   Gram-Schmidted against the posed normal — a quaternion is three axes at
1192///   right angles, and a shearing blend leaves the pair at some other one;
1193/// * the handedness is the bind pose's, carried rather than re-derived: it is
1194///   a property of the UV parameterisation, which no pose changes;
1195/// * `uv0`, `uv1` and `color` are copied through, because the destination is a
1196///   different range of the pool and a field left alone is a field holding
1197///   whatever the allocator last put there.
1198///
1199/// # Panics
1200///
1201/// If `palette` is empty — see [`blend`].
1202#[must_use]
1203pub fn skin_vertex(palette: &[Mat4], binding: &SkinBinding, vertex: &MeshVertex) -> MeshVertex {
1204    let blended = blend(palette, binding);
1205    let position = blended * Vec4::from((Vec3::from_array(vertex.position), 1.0));
1206    let bind_pose = vertex.qtangent.decode();
1207    let bind_normal = Vec3::from_array(bind_pose.normal);
1208    let bind_tangent = Vec3::from_array(bind_pose.tangent);
1209
1210    let carried = normal_basis(Mat3::from_mat4(blended)) * bind_normal;
1211    let square_length = carried.dot(carried);
1212    let normal = if square_length > 0.0 {
1213        carried / square_length.sqrt()
1214    } else {
1215        bind_normal
1216    };
1217    let projected = {
1218        let moved = Mat3::from_mat4(blended) * bind_tangent;
1219        moved - normal * normal.dot(moved)
1220    };
1221    let square_length = projected.dot(projected);
1222    let tangent = if square_length > 0.0 {
1223        projected / square_length.sqrt()
1224    } else {
1225        bind_tangent
1226    };
1227    let handedness = Vec3::from_array(bind_pose.normal)
1228        .cross(bind_tangent)
1229        .dot(Vec3::from_array(bind_pose.bitangent));
1230    MeshVertex {
1231        position: [position.x, position.y, position.z],
1232        qtangent: QTangent::encode(TangentFrame {
1233            tangent: tangent.to_array(),
1234            bitangent: (normal.cross(tangent) * if handedness < 0.0 { -1.0 } else { 1.0 })
1235                .to_array(),
1236            normal: normal.to_array(),
1237        }),
1238        uv0: vertex.uv0,
1239        uv1: vertex.uv1,
1240        color: vertex.color,
1241    }
1242}
1243
1244/// Appends `palette` to `out` as the shader reads it: each matrix's columns,
1245/// one after another, every `f32` little-endian.
1246///
1247/// A little-endian target's native bytes already are that, so each matrix
1248/// goes in as one slice rather than a float at a time; a big-endian target
1249/// swaps each float explicitly.
1250fn write_palette(out: &mut Vec<u8>, palette: &[Mat4]) {
1251    for matrix in palette {
1252        let columns = matrix.to_cols_array();
1253        #[cfg(target_endian = "little")]
1254        out.extend_from_slice(bytemuck::cast_slice(&columns));
1255        #[cfg(target_endian = "big")]
1256        for value in columns {
1257            out.extend_from_slice(&value.to_le_bytes());
1258        }
1259    }
1260}
1261
1262// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
1263#[cfg(all(test, not(target_arch = "wasm32")))]
1264mod tests {
1265    use crcbl_shaders::vertex::UvRange;
1266
1267    use crcbl_hal::null::{Command, Event, NullInstance, Recorder};
1268    use crcbl_hal::{CommandEncoderDesc, DeviceDesc, Instance, QueueHandle, QueueKind};
1269    use crcbl_shaders::mesh::VERTEX_STRIDE;
1270
1271    use super::*;
1272    use crate::mesh_pool::{MeshPoolDesc, MeshUpload};
1273    use crate::transient::TransientPool;
1274
1275    fn open() -> (Recorder, Box<dyn Device>, QueueHandle) {
1276        let recorder = Recorder::new();
1277        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
1278        let adapter = instance.adapters().remove(0);
1279        let device = instance
1280            .create_device(&DeviceDesc::for_adapter(adapter.id))
1281            .expect("the null backend always opens");
1282        let queue = device.queue(QueueKind::Graphics).expect("always present");
1283        (recorder, device, queue)
1284    }
1285
1286    /// A pool wide enough for every reservation the tests below make, unless
1287    /// one is asking for the exhausted case on purpose.
1288    fn pool(device: &dyn Device, vertices: u32) -> MeshPool {
1289        MeshPool::new(
1290            device,
1291            &MeshPoolDesc {
1292                label: Some("skinning test"),
1293                vertex_capacity: vertices,
1294                index_capacity: 64,
1295                mesh_capacity: 4,
1296            },
1297        )
1298        .expect("the null backend accepts every descriptor")
1299    }
1300
1301    /// A skinning pass over `pool`'s vertex buffer, sized for the frame the
1302    /// caller is about to build.
1303    fn skinning(
1304        device: &dyn Device,
1305        pool: &MeshPool,
1306        ranges: u32,
1307        joints: u32,
1308        bindings: u32,
1309    ) -> Skinning {
1310        Skinning::new(
1311            device,
1312            &SkinningDesc {
1313                label: Some("skinning test"),
1314                frames: 2,
1315                ranges,
1316                joints,
1317                bindings,
1318                vertices: pool.vertex_buffer(),
1319                attribute_base: pool.attribute_base(),
1320            },
1321        )
1322        .expect("the null backend accepts every descriptor")
1323    }
1324
1325    /// `n` skin bindings, every vertex bound wholly to joint 0.
1326    fn rigid(n: usize) -> Vec<SkinBinding> {
1327        vec![
1328            SkinBinding {
1329                joints: [0; JOINTS_PER_VERTEX],
1330                weights: [1.0, 0.0, 0.0, 0.0],
1331            };
1332            n
1333        ]
1334    }
1335
1336    /// Compiles and executes a one-pass graph over `frame`, so the recorder
1337    /// holds the commands the pass body really recorded.
1338    ///
1339    /// The encoder is **finished**, because the null backend buffers a command
1340    /// stream and hands it to the recorder there — a test that skipped it would
1341    /// read an empty command list and pass whatever the body did.
1342    fn run(
1343        recorder: &Recorder,
1344        device: &dyn Device,
1345        queue: QueueHandle,
1346        pass: &Skinning,
1347        frame: usize,
1348    ) {
1349        let mut transients = TransientPool::new();
1350        let mut graph = RenderGraph::new(queue);
1351        pass.add_pass(&mut graph, frame);
1352        let compiled = graph.compile(&transients).expect("a legal frame");
1353        let mut encoder = device.create_command_encoder(&CommandEncoderDesc {
1354            label: Some("skinning"),
1355            queue,
1356        });
1357        compiled
1358            .execute(device, &mut transients, encoder.as_mut(), None)
1359            .expect("the graph executed");
1360        let commands = encoder.finish().expect("a legal command stream");
1361        device.destroy_command_buffer(commands);
1362        // A dispatch outside a compute pass, a group bound to a dead object, a
1363        // binding wider than the device allows: the null backend records each
1364        // of those rather than refusing, so a test that never asked would pass
1365        // over a command stream Vulkan rejects.
1366        recorder.assert_valid();
1367    }
1368
1369    /// Every `dispatch`'s group count, in the order they were recorded.
1370    fn dispatches(recorder: &Recorder) -> Vec<u32> {
1371        recorder
1372            .commands()
1373            .into_iter()
1374            .filter_map(|command| match command {
1375                Command::Dispatch { x, y, z } => {
1376                    assert_eq!((y, z), (1, 1), "the kernel is one-dimensional");
1377                    Some(x)
1378                }
1379                _ => None,
1380            })
1381            .collect()
1382    }
1383
1384    /// The six words of a range's uniform block, read back out of the bytes
1385    /// that actually reached the buffer rather than mirrored from the inputs.
1386    fn params_of(recorder: &Recorder, pass: &Skinning, frame: usize, slot: usize) -> Params {
1387        let bytes = recorder
1388            .buffer_bytes(pass.params[frame][slot])
1389            .expect("the block is live");
1390        assert_eq!(bytes.len(), PARAMS_SIZE);
1391        let word = |at: usize| {
1392            u32::from_le_bytes(bytes[at..at + 4].try_into().expect("four bytes of a word"))
1393        };
1394        Params {
1395            vertex_count: word(0),
1396            input_base: word(4),
1397            output_base: word(8),
1398            binding_base: word(12),
1399            joint_base: word(16),
1400            joint_count: word(20),
1401            attribute_base: word(24),
1402        }
1403    }
1404
1405    // --- the drawable region -------------------------------------------------
1406
1407    /// **Releasing a skinned mesh gives back the region**, and the space is
1408    /// reusable straight away.
1409    ///
1410    /// The second reservation is what says the vertices really came back rather
1411    /// than only that the free counter moved: a pool sized for one region and
1412    /// its source refuses the second reserve outright if the first leaked.
1413    #[test]
1414    fn releasing_a_skinned_mesh_returns_its_region() {
1415        let (recorder, device, queue) = open();
1416        let device = device.as_ref();
1417        let mut pool = pool(device, 64);
1418        const VERTICES: u32 = 8;
1419        let source = pool
1420            .upload(
1421                device,
1422                queue,
1423                &MeshUpload {
1424                    label: "source",
1425                    vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
1426                    indices: &[0, 1, 2],
1427                    uv_range: UvRange::default(),
1428                    flags: 0,
1429                },
1430            )
1431            .expect("the pool has room");
1432        pool.flush(device).expect("the null backend completes it");
1433        let (free_before, _) = pool.vertex_space();
1434
1435        let skinned = SkinnedMesh::reserve(&mut pool, source).expect("room for two halves");
1436        assert_eq!(
1437            skinned.vertex_count(),
1438            VERTICES,
1439            "each half is as long as the bind pose it deforms"
1440        );
1441        assert_eq!(
1442            skinned.input_base(),
1443            pool.mesh(source).expect("resident").base_vertex,
1444            "the range reads the bind pose where the pool put it"
1445        );
1446        assert_eq!(
1447            skinned.mesh_id(),
1448            source.index(),
1449            "a skinned instance names the mesh it was deformed from, so the bucket, the \
1450             level tables and the bounding box all resolve as the source's"
1451        );
1452        assert_eq!(
1453            pool.vertex_space().0,
1454            free_before - 2 * VERTICES,
1455            "two halves are taken, not one"
1456        );
1457
1458        skinned.release(&mut pool);
1459        assert_eq!(
1460            pool.vertex_space().0,
1461            free_before,
1462            "the region goes back whole, and the free list coalesces it"
1463        );
1464
1465        let again = SkinnedMesh::reserve(&mut pool, source).expect("the vertices came back");
1466        again.release(&mut pool);
1467        pool.destroy(device);
1468        recorder.assert_valid();
1469    }
1470
1471    /// **A reservation takes no mesh-table entry**, so a pool whose table has no
1472    /// spare slot at all can still hold a skinned mesh.
1473    ///
1474    /// The table below has exactly one entry and the source mesh occupies it.
1475    /// Before 2026-08 this call took two more and a table of one refused it;
1476    /// what says the mechanism is gone rather than merely unused is that the
1477    /// reservation now succeeds here.
1478    #[test]
1479    fn a_reservation_needs_no_spare_table_entry() {
1480        let (recorder, device, queue) = open();
1481        let device = device.as_ref();
1482        let mut pool = MeshPool::new(
1483            device,
1484            &MeshPoolDesc {
1485                label: Some("no spare entry"),
1486                vertex_capacity: 64,
1487                index_capacity: 64,
1488                mesh_capacity: 1,
1489            },
1490        )
1491        .expect("the null backend accepts every descriptor");
1492        let source = pool
1493            .upload(
1494                device,
1495                queue,
1496                &MeshUpload {
1497                    label: "source",
1498                    vertices: &vec![0u8; 8 * VERTEX_STRIDE],
1499                    indices: &[0, 1, 2],
1500                    uv_range: UvRange::default(),
1501                    flags: 0,
1502                },
1503            )
1504            .expect("the pool has room");
1505        pool.flush(device).expect("the null backend completes it");
1506
1507        let skinned = SkinnedMesh::reserve(&mut pool, source)
1508            .expect("a region is vertices, and the table is untouched");
1509        assert_eq!(
1510            skinned.mesh_id(),
1511            source.index(),
1512            "and the entry it draws through is the one the source already had"
1513        );
1514        skinned.release(&mut pool);
1515
1516        pool.destroy(device);
1517        recorder.assert_valid();
1518    }
1519
1520    /// A reservation the vertex pool has no room for leaks nothing.
1521    ///
1522    /// The half-and-then-refused path in [`SkinnedRegion::reserve`], reached
1523    /// through the call that wraps it: a pool with room for one half and not two
1524    /// must come back with its free list exactly as it was.
1525    #[test]
1526    fn a_refused_region_gives_back_the_half_it_took() {
1527        let (recorder, device, queue) = open();
1528        let device = device.as_ref();
1529        const VERTICES: u32 = 8;
1530        let mut pool = MeshPool::new(
1531            device,
1532            &MeshPoolDesc {
1533                label: Some("room for one half"),
1534                vertex_capacity: 2 * VERTICES + VERTICES / 2,
1535                index_capacity: 64,
1536                mesh_capacity: 4,
1537            },
1538        )
1539        .expect("the null backend accepts every descriptor");
1540        let source = pool
1541            .upload(
1542                device,
1543                queue,
1544                &MeshUpload {
1545                    label: "source",
1546                    vertices: &vec![0u8; VERTICES as usize * VERTEX_STRIDE],
1547                    indices: &[0, 1, 2],
1548                    uv_range: UvRange::default(),
1549                    flags: 0,
1550                },
1551            )
1552            .expect("the pool has room");
1553        pool.flush(device).expect("the null backend completes it");
1554        let space = pool.vertex_space();
1555
1556        let refused = SkinnedMesh::reserve(&mut pool, source);
1557        assert!(
1558            refused.is_err(),
1559            "the pool has room for one half of the region and not for two: {refused:?}"
1560        );
1561        assert_eq!(
1562            pool.vertex_space(),
1563            space,
1564            "a refused reservation leaks no pool space"
1565        );
1566
1567        pool.destroy(device);
1568        recorder.assert_valid();
1569    }
1570
1571    // --- the oracle ---------------------------------------------------------
1572
1573    /// A vertex, distinct in every field so a copy landing in the wrong lane
1574    /// could not compare equal by accident.
1575    fn vertex(position: Vec3, normal: Vec3) -> MeshVertex {
1576        MeshVertex::from_normal(
1577            position.to_array(),
1578            normal.to_array(),
1579            [0.25, 0.5, 0.75, 1.0],
1580            [0.125, 0.375],
1581            &UvRange {
1582                scale: [1.0, 1.0],
1583                offset: [0.0, 0.0],
1584            },
1585        )
1586    }
1587
1588    /// The normal a vertex's frame decodes to — what the tests below compare,
1589    /// since the record carries a quaternion rather than a normal.
1590    fn normal_of(vertex: &MeshVertex) -> Vec3 {
1591        Vec3::from_array(vertex.qtangent.decode().normal)
1592    }
1593
1594    /// **A vertex whose weight is entirely on one joint is transformed
1595    /// exactly** — the kernel's own claim, and the one case where linear blend
1596    /// skinning owes an exact answer rather than an approximation.
1597    ///
1598    /// Exact equality rather than a tolerance, and it is not a lucky one: the
1599    /// blend is `M * 1.0` plus three `M * 0.0`, and adding a zero matrix to a
1600    /// finite one changes no bit.
1601    #[test]
1602    fn a_vertex_bound_wholly_to_one_joint_is_transformed_exactly() {
1603        let joint = Mat4::from_rotation_translation(
1604            glam::Quat::from_rotation_z(core::f32::consts::FRAC_PI_3),
1605            Vec3::new(2.0, -3.0, 0.5),
1606        );
1607        let palette = [Mat4::IDENTITY, joint];
1608        let binding = SkinBinding {
1609            joints: [1, 0, 0, 0],
1610            weights: [1.0, 0.0, 0.0, 0.0],
1611        };
1612        let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);
1613
1614        let skinned = skin_vertex(&palette, &binding, &bind_pose);
1615
1616        let expected = joint * Vec4::new(1.0, 2.0, 3.0, 1.0);
1617        assert_eq!(
1618            skinned.position,
1619            [expected.x, expected.y, expected.z],
1620            "a rigidly bound vertex is the joint's transform of it and nothing else"
1621        );
1622        // A rotation is its own cofactor to within rounding, so the normal is
1623        // the rotated one; the tolerance is the normalise, not the blend.
1624        let want = Mat3::from_mat4(joint) * Vec3::Y;
1625        let got = normal_of(&skinned);
1626        for (got, want) in got.to_array().iter().zip(want.to_array()) {
1627            assert!(
1628                (got - want).abs() <= QTangent::MAX_COMPONENT_ERROR,
1629                "a rigidly bound normal is the joint's rotation of it: {got:?} against {want}"
1630            );
1631        }
1632        assert_eq!(skinned.color, bind_pose.color, "colour is copied through");
1633        assert_eq!(skinned.uv0, bind_pose.uv0, "uv is copied through");
1634        assert_eq!(skinned.uv1, bind_pose.uv1, "and the second set with it");
1635    }
1636
1637    /// A vertex blended across two joints, against the value worked out by
1638    /// hand.
1639    ///
1640    /// Two pure translations and weights of a quarter and three quarters —
1641    /// both exact in binary, and both linear parts identity — so the blended
1642    /// matrix is the identity with `0.25 * t0 + 0.75 * t1` in its translation
1643    /// and the answer has no rounding in it at all.
1644    #[test]
1645    fn a_vertex_blended_across_two_joints_is_the_weighted_sum_of_both() {
1646        let palette = [
1647            Mat4::from_translation(Vec3::new(4.0, 0.0, 0.0)),
1648            Mat4::from_translation(Vec3::new(0.0, 8.0, 0.0)),
1649        ];
1650        let binding = SkinBinding {
1651            joints: [0, 1, 0, 0],
1652            weights: [0.25, 0.75, 0.0, 0.0],
1653        };
1654        let bind_pose = vertex(Vec3::new(1.0, 1.0, 1.0), Vec3::Z);
1655
1656        let skinned = skin_vertex(&palette, &binding, &bind_pose);
1657
1658        assert_eq!(
1659            skinned.position,
1660            [1.0 + 0.25 * 4.0, 1.0 + 0.75 * 8.0, 1.0],
1661            "a quarter of the first joint's translation and three quarters of the second's"
1662        );
1663        assert_eq!(
1664            skinned.qtangent, bind_pose.qtangent,
1665            "a blend of translations has an identity linear part, so the frame is unmoved — \
1666             and lane for lane, because the re-encode is the same arithmetic on the same frame"
1667        );
1668    }
1669
1670    /// **A normal under a joint carrying a non-uniform scale goes through the
1671    /// cofactor matrix, and the bare 3×3 is a different vector.**
1672    ///
1673    /// The case the cofactor exists for: a scale of `(4, 1, 1)` stretches a
1674    /// 45° normal *toward* the stretched axis if it is carried like a tangent,
1675    /// and the surface's perpendicular tilts the other way. Both halves are
1676    /// asserted, because "it used the cofactor" is only evidence if the bare
1677    /// basis would have given something else.
1678    #[test]
1679    fn a_normal_under_a_non_uniform_scale_goes_through_the_cofactor_not_the_basis() {
1680        let scale = Mat4::from_scale(Vec3::new(4.0, 1.0, 1.0));
1681        let palette = [scale];
1682        let binding = SkinBinding {
1683            joints: [0, 0, 0, 0],
1684            weights: [1.0, 0.0, 0.0, 0.0],
1685        };
1686        let diagonal = Vec3::new(1.0, 1.0, 0.0).normalize();
1687        let skinned = skin_vertex(&palette, &binding, &vertex(Vec3::X, diagonal));
1688
1689        // Cofactor of diag(4,1,1) is diag(1, 4, 4), so the normal tilts away
1690        // from x; the bare basis is diag(4,1,1) and tilts toward it.
1691        let through_cofactor = (Vec3::new(1.0, 4.0, 0.0)).normalize();
1692        let through_basis = (Vec3::new(4.0, 1.0, 0.0)).normalize();
1693        let got = normal_of(&skinned);
1694        assert!(
1695            (got - through_cofactor).length() <= QTangent::MAX_COMPONENT_ERROR,
1696            "{got:?} is not the cofactor's answer {through_cofactor:?}"
1697        );
1698        assert!(
1699            (got - through_basis).length() > 0.5,
1700            "the bare basis would have given {through_basis:?}, which is not far from {got:?} — \
1701             this test would pass with the wrong matrix"
1702        );
1703        assert!(
1704            (got.length() - 1.0).abs() <= QTangent::MAX_COMPONENT_ERROR,
1705            "the shader normalises, so the written normal is unit length"
1706        );
1707    }
1708
1709    /// The cross-product form and the textbook one agree wherever the textbook
1710    /// one is defined.
1711    ///
1712    /// The shader is written in cross products because they are defined for a
1713    /// singular basis, where `inverse()` is not — so this is what says the two
1714    /// are the same matrix and not merely two plausible ones.
1715    #[test]
1716    fn the_cofactor_matches_the_inverse_transpose_scaled_by_the_determinant() {
1717        for basis in [
1718            Mat3::from_mat4(Mat4::from_scale(Vec3::new(2.0, 3.0, 0.5))),
1719            Mat3::from_rotation_y(0.7) * Mat3::from_diagonal(Vec3::new(1.0, 4.0, 0.25)),
1720            // A mirrored basis: negative determinant, which is the case
1721            // `graphitemaster/normals_revisited` is about.
1722            Mat3::from_diagonal(Vec3::new(-1.0, 2.0, 3.0)),
1723        ] {
1724            let textbook = basis.inverse().transpose() * basis.determinant();
1725            let cofactor = normal_basis(basis);
1726            for (got, want) in cofactor
1727                .to_cols_array()
1728                .iter()
1729                .zip(textbook.to_cols_array())
1730            {
1731                assert!(
1732                    (got - want).abs() < 1e-4,
1733                    "{cofactor:?} is not {textbook:?} for basis {basis:?}"
1734                );
1735            }
1736        }
1737    }
1738
1739    /// A blend that collapses to nothing keeps the bind-pose normal rather
1740    /// than writing a `NaN` into the pool.
1741    ///
1742    /// The shader's guarded normalise, and it is guarded because the geometry
1743    /// it would poison is read again by the shadow passes: a `NaN` position
1744    /// makes triangles vanish rather than making anything report an error.
1745    #[test]
1746    fn a_blend_that_collapses_to_zero_keeps_the_bind_pose_normal() {
1747        let palette = [Mat4::IDENTITY];
1748        let binding = SkinBinding {
1749            joints: [0; JOINTS_PER_VERTEX],
1750            weights: [0.0; JOINTS_PER_VERTEX],
1751        };
1752        let bind_pose = vertex(Vec3::new(1.0, 2.0, 3.0), Vec3::Y);
1753
1754        let skinned = skin_vertex(&palette, &binding, &bind_pose);
1755
1756        assert_eq!(
1757            skinned.position,
1758            [0.0, 0.0, 0.0],
1759            "no weight at all puts the vertex at the palette's origin"
1760        );
1761        assert_eq!(
1762            skinned.qtangent, bind_pose.qtangent,
1763            "and the frame is the bind pose's, finite and already orthonormal"
1764        );
1765        assert!(
1766            normal_of(&skinned)
1767                .to_array()
1768                .iter()
1769                .all(|value| value.is_finite()),
1770            "nothing written into the vertex pool may be NaN"
1771        );
1772    }
1773
1774    /// Weights that do not sum to one deflate their vertex toward the
1775    /// palette's origin, which is the failure the kernel deliberately keeps.
1776    ///
1777    /// Renormalising here would be this engine overruling
1778    /// `crcbl_scene::GltfPrimitive::weights`, which reports them as the file
1779    /// stored them so that a file whose weights do not sum is one whose author
1780    /// hears about it.
1781    #[test]
1782    fn weights_that_do_not_sum_to_one_deflate_the_vertex_rather_than_being_renormalised() {
1783        let palette = [Mat4::IDENTITY];
1784        let binding = SkinBinding {
1785            joints: [0; JOINTS_PER_VERTEX],
1786            weights: [0.9, 0.0, 0.0, 0.0],
1787        };
1788        let skinned = skin_vertex(
1789            &palette,
1790            &binding,
1791            &vertex(Vec3::new(10.0, 0.0, 0.0), Vec3::Y),
1792        );
1793        assert_eq!(
1794            skinned.position[0], 9.0,
1795            "a tenth of the way toward the origin, not renormalised back out to 10"
1796        );
1797    }
1798
1799    /// A joint index past the palette is clamped the way the shader clamps it
1800    /// — so the oracle predicts what a malformed asset really draws, not what
1801    /// it meant to.
1802    #[test]
1803    fn a_joint_index_past_the_palette_is_clamped_the_way_the_shader_clamps_it() {
1804        let palette = [
1805            Mat4::from_translation(Vec3::X),
1806            Mat4::from_translation(Vec3::Y),
1807        ];
1808        let past = SkinBinding {
1809            joints: [99, 0, 0, 0],
1810            weights: [1.0, 0.0, 0.0, 0.0],
1811        };
1812        let last = SkinBinding {
1813            joints: [1, 0, 0, 0],
1814            weights: [1.0, 0.0, 0.0, 0.0],
1815        };
1816        let bind_pose = vertex(Vec3::ZERO, Vec3::Y);
1817        assert_eq!(
1818            skin_vertex(&palette, &past, &bind_pose).position,
1819            skin_vertex(&palette, &last, &bind_pose).position,
1820            "an out-of-range index resolves to the palette's last matrix"
1821        );
1822    }
1823
1824    // --- the transient region ----------------------------------------------
1825
1826    /// **The two halves alternate with the parity, and the one a frame does
1827    /// not write is the one the frame before it did.**
1828    ///
1829    /// This is the animation plan's 2026-07-27 correction as an
1830    /// assertion. A region that answered the same base for both parities would
1831    /// be a single-buffered one wearing the API of a double-buffered one, and
1832    /// nothing else in the tree would notice until TAA arrived.
1833    #[test]
1834    fn a_regions_two_halves_alternate_with_the_parity() {
1835        let (_recorder, device, _queue) = open();
1836        let mut pool = pool(device.as_ref(), 64);
1837        let region = SkinnedRegion::reserve(&mut pool, 8).expect("room for both halves");
1838
1839        assert_ne!(
1840            region.base(0),
1841            region.base(1),
1842            "the two parities must name different runs, or the previous frame's skinned \
1843             positions are this frame's"
1844        );
1845        assert_eq!(region.base(0), region.previous_base(1));
1846        assert_eq!(region.base(1), region.previous_base(0));
1847        // The parity is a bit, so every even frame index is one half.
1848        assert_eq!(region.base(2), region.base(0));
1849        assert_eq!(region.base(3), region.base(1));
1850        assert_eq!(region.vertex_count(), 8);
1851    }
1852
1853    /// Neither half overlaps the other, and neither overlaps the bind pose —
1854    /// which is the precondition
1855    /// [`Params::to_bytes`](crcbl_shaders::skinning::Params::to_bytes) panics
1856    /// on and which the allocator is what actually makes true.
1857    ///
1858    /// The bind pose here is a **real upload**, not a second reservation, so
1859    /// the claim is about the pool the renderer uses rather than about the free
1860    /// list in isolation.
1861    #[test]
1862    fn a_regions_halves_never_overlap_each_other_or_the_bind_pose() {
1863        let (_recorder, device, queue) = open();
1864        let mut pool = pool(device.as_ref(), 64);
1865        let count = 6u32;
1866        let handle = pool
1867            .upload(
1868                device.as_ref(),
1869                queue,
1870                &MeshUpload {
1871                    label: "bind pose",
1872                    vertices: &vec![0u8; count as usize * VERTEX_STRIDE],
1873                    indices: &[0, 1, 2],
1874                    uv_range: UvRange::default(),
1875                    flags: 0,
1876                },
1877            )
1878            .expect("room in both pools");
1879        pool.flush(device.as_ref()).expect("the null backend lands");
1880        let bind_pose = pool.mesh(handle).expect("resident").base_vertex;
1881
1882        let region = SkinnedRegion::reserve(&mut pool, count).expect("room for both halves");
1883        let runs = [
1884            bind_pose..bind_pose + count,
1885            region.base(0)..region.base(0) + count,
1886            region.base(1)..region.base(1) + count,
1887        ];
1888        for (index, run) in runs.iter().enumerate() {
1889            for other in &runs[index + 1..] {
1890                assert!(
1891                    run.end <= other.start || other.end <= run.start,
1892                    "{run:?} overlaps {other:?}; one invocation would read a vertex another had \
1893                     already overwritten"
1894                );
1895            }
1896        }
1897        // And the block the pass would build from them is one `to_bytes`
1898        // accepts, on either parity.
1899        for parity in [0, 1] {
1900            let _ = Params {
1901                vertex_count: count,
1902                input_base: bind_pose,
1903                output_base: region.base(parity),
1904                binding_base: 0,
1905                joint_base: 0,
1906                joint_count: 1,
1907                attribute_base: 0,
1908            }
1909            .to_bytes();
1910        }
1911    }
1912
1913    /// Releasing gives both halves back, so a pool that held one region can
1914    /// hold the next.
1915    #[test]
1916    fn a_released_region_gives_both_halves_back() {
1917        let (_recorder, device, _queue) = open();
1918        let mut pool = pool(device.as_ref(), 16);
1919        let before = pool.vertex_space();
1920        let region = SkinnedRegion::reserve(&mut pool, 8).expect("exactly fits");
1921        assert_eq!(pool.vertex_space().0, 0, "both halves are taken");
1922        region.release(&mut pool);
1923        assert_eq!(
1924            pool.vertex_space(),
1925            before,
1926            "everything is free again, and in one block"
1927        );
1928        SkinnedRegion::reserve(&mut pool, 8).expect("the space really came back");
1929    }
1930
1931    /// A pool with room for one half and not two gives the first one back
1932    /// rather than leaking it.
1933    ///
1934    /// The half-allocated failure is the one a rollback is written for, and it
1935    /// is invisible without this: the reservation succeeds, the error is
1936    /// returned, and the pool is quietly smaller for the rest of the process.
1937    #[test]
1938    fn a_pool_with_room_for_one_half_gives_it_back_rather_than_leaking_it() {
1939        let (_recorder, device, _queue) = open();
1940        let mut pool = pool(device.as_ref(), 8);
1941        let before = pool.vertex_space();
1942        let error = SkinnedRegion::reserve(&mut pool, 6).expect_err("no room for twelve vertices");
1943        assert!(
1944            matches!(error, MeshPoolError::PoolExhausted { .. }),
1945            "{error} does not name the exhausted pool"
1946        );
1947        assert_eq!(
1948            pool.vertex_space(),
1949            before,
1950            "the first half must have gone back"
1951        );
1952    }
1953
1954    /// A reservation of nothing is refused by its own name.
1955    #[test]
1956    fn a_region_of_no_vertices_is_refused() {
1957        let (_recorder, device, _queue) = open();
1958        let mut pool = pool(device.as_ref(), 8);
1959        let error = SkinnedRegion::reserve(&mut pool, 0).expect_err("no address to hand back");
1960        assert!(
1961            matches!(error, MeshPoolError::EmptyReservation),
1962            "{error} does not name the empty reservation"
1963        );
1964    }
1965
1966    // --- the pass ------------------------------------------------------------
1967
1968    /// **The dispatch covers every vertex and no more.**
1969    ///
1970    /// One invocation is one vertex and the division rounds up, so a count that
1971    /// is not a multiple of the workgroup size still gets a whole last group —
1972    /// whose tail the shader discards itself. A dispatch sized with a truncating
1973    /// divide skins a *prefix* of the mesh, which reads as a rigging mistake
1974    /// rather than as a dispatch that was too short.
1975    #[test]
1976    fn the_dispatch_covers_every_vertex_and_no_more() {
1977        for count in [1u32, 63, 64, 65, 127, 128, 200] {
1978            let (recorder, device, queue) = open();
1979            let mut pool = pool(device.as_ref(), count * 2 + 1);
1980            let region = SkinnedRegion::reserve(&mut pool, count).expect("room");
1981            let mut pass = skinning(device.as_ref(), &pool, 1, 2, count);
1982            let bindings = rigid(count as usize);
1983            pass.begin_frame(
1984                device.as_ref(),
1985                0,
1986                &[SkinRange {
1987                    input_base: 0,
1988                    region: &region,
1989                    palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
1990                    bindings: &bindings,
1991                }],
1992            )
1993            .expect("a legal frame");
1994            run(&recorder, device.as_ref(), queue, &pass, 0);
1995
1996            let groups = dispatches(&recorder);
1997            assert_eq!(groups.len(), 1, "one range is one dispatch");
1998            assert_eq!(
1999                groups[0],
2000                count.div_ceil(WORKGROUP_SIZE),
2001                "{count} vertices at {WORKGROUP_SIZE} per group"
2002            );
2003            assert!(
2004                u64::from(groups[0]) * u64::from(WORKGROUP_SIZE) >= u64::from(count),
2005                "{count} vertices need at least that many invocations, and {} groups give {}",
2006                groups[0],
2007                u64::from(groups[0]) * u64::from(WORKGROUP_SIZE)
2008            );
2009            pass.destroy(device.as_ref());
2010            region.release(&mut pool);
2011            pool.destroy(device.as_ref());
2012        }
2013    }
2014
2015    /// Three ranges are three dispatches, in the order they were handed over,
2016    /// each against its own bind group.
2017    #[test]
2018    fn every_range_gets_its_own_dispatch_and_its_own_bind_group() {
2019        let (recorder, device, queue) = open();
2020        let mut pool = pool(device.as_ref(), 64);
2021        let counts = [1u32, 2, 3];
2022        let regions: Vec<SkinnedRegion> = counts
2023            .iter()
2024            .map(|count| SkinnedRegion::reserve(&mut pool, *count).expect("room"))
2025            .collect();
2026        let mut pass = skinning(device.as_ref(), &pool, 3, 6, 8);
2027        let bindings: Vec<Vec<SkinBinding>> =
2028            counts.iter().map(|count| rigid(*count as usize)).collect();
2029        let ranges: Vec<SkinRange<'_>> = (0..3)
2030            .map(|index| SkinRange {
2031                input_base: 32 + index as u32,
2032                region: &regions[index],
2033                palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
2034                bindings: &bindings[index],
2035            })
2036            .collect();
2037        pass.begin_frame(device.as_ref(), 1, &ranges)
2038            .expect("a legal frame");
2039        run(&recorder, device.as_ref(), queue, &pass, 1);
2040
2041        assert_eq!(dispatches(&recorder), vec![1, 1, 1], "three ranges");
2042        let bound: Vec<_> = recorder
2043            .commands()
2044            .into_iter()
2045            .filter_map(|command| match command {
2046                Command::BindGroup { group, .. } => Some(group),
2047                _ => None,
2048            })
2049            .collect();
2050        assert_eq!(
2051            bound, pass.groups[1],
2052            "each dispatch is preceded by that range's own group, in range order"
2053        );
2054    }
2055
2056    /// **The uniform block names this frame's half**, and the next frame's
2057    /// names the other one.
2058    ///
2059    /// Read back out of the buffer the pass wrote rather than recomputed, so
2060    /// this is evidence about the upload and not about the plan repeating
2061    /// itself.
2062    #[test]
2063    fn the_params_block_names_this_frames_half_and_the_next_frames_names_the_other() {
2064        let (recorder, device, _queue) = open();
2065        let mut pool = pool(device.as_ref(), 64);
2066        let region = SkinnedRegion::reserve(&mut pool, 5).expect("room");
2067        let mut pass = skinning(device.as_ref(), &pool, 1, 3, 5);
2068        let bindings = rigid(5);
2069        let palette = [Mat4::IDENTITY; 3];
2070
2071        let mut seen = Vec::new();
2072        for frame in [0usize, 1] {
2073            pass.begin_frame(
2074                device.as_ref(),
2075                frame,
2076                &[SkinRange {
2077                    input_base: 40,
2078                    region: &region,
2079                    palette: &palette,
2080                    bindings: &bindings,
2081                }],
2082            )
2083            .expect("a legal frame");
2084            let block = params_of(&recorder, &pass, frame, 0);
2085            assert_eq!(
2086                block,
2087                Params {
2088                    vertex_count: 5,
2089                    input_base: 40,
2090                    output_base: region.base(pass.parity()),
2091                    binding_base: 0,
2092                    joint_base: 0,
2093                    joint_count: 3,
2094                    attribute_base: pool.attribute_base(),
2095                }
2096            );
2097            seen.push(block.output_base);
2098        }
2099        assert_ne!(
2100            seen[0], seen[1],
2101            "two consecutive frames must write different halves of the region"
2102        );
2103    }
2104
2105    /// A second range's bases are the first range's lengths, so the two
2106    /// dispatches read disjoint runs of the shared palette and binding buffers.
2107    ///
2108    /// One base serving both would make the second character read the first
2109    /// one's skin.
2110    #[test]
2111    fn each_ranges_palette_and_binding_bases_follow_the_range_before_it() {
2112        let (recorder, device, _queue) = open();
2113        let mut pool = pool(device.as_ref(), 64);
2114        let first = SkinnedRegion::reserve(&mut pool, 3).expect("room");
2115        let second = SkinnedRegion::reserve(&mut pool, 4).expect("room");
2116        let mut pass = skinning(device.as_ref(), &pool, 2, 5, 7);
2117        let (three, four) = (rigid(3), rigid(4));
2118        pass.begin_frame(
2119            device.as_ref(),
2120            0,
2121            &[
2122                SkinRange {
2123                    input_base: 50,
2124                    region: &first,
2125                    palette: &[Mat4::IDENTITY; 2],
2126                    bindings: &three,
2127                },
2128                SkinRange {
2129                    input_base: 54,
2130                    region: &second,
2131                    palette: &[Mat4::IDENTITY; 3],
2132                    bindings: &four,
2133                },
2134            ],
2135        )
2136        .expect("a legal frame");
2137
2138        let first_block = params_of(&recorder, &pass, 0, 0);
2139        let second_block = params_of(&recorder, &pass, 0, 1);
2140        assert_eq!((first_block.joint_base, first_block.binding_base), (0, 0));
2141        assert_eq!(
2142            (second_block.joint_base, second_block.binding_base),
2143            (2, 3),
2144            "the second range starts where the first one's palette and bindings ended"
2145        );
2146        assert_eq!((first_block.joint_count, second_block.joint_count), (2, 3));
2147    }
2148
2149    /// The palette and the skin bindings reach their buffers as the bytes the
2150    /// shader indexes: `to_cols_array` order at
2151    /// [`JOINT_STRIDE`](crcbl_shaders::skinning::JOINT_STRIDE), and
2152    /// [`SkinBinding::to_bytes`] at its own stride.
2153    #[test]
2154    fn the_uploaded_palette_and_bindings_are_the_bytes_the_shader_reads() {
2155        let (recorder, device, _queue) = open();
2156        let mut pool = pool(device.as_ref(), 32);
2157        let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
2158        let mut pass = skinning(device.as_ref(), &pool, 1, 2, 2);
2159        let palette = [
2160            Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0)),
2161            Mat4::from_scale(Vec3::new(2.0, 4.0, 8.0)),
2162        ];
2163        let bindings = [
2164            SkinBinding {
2165                joints: [1, 0, 1, 0],
2166                weights: [0.5, 0.25, 0.125, 0.125],
2167            },
2168            SkinBinding {
2169                joints: [0, 1, 0, 1],
2170                weights: [1.0, 0.0, 0.0, 0.0],
2171            },
2172        ];
2173        pass.begin_frame(
2174            device.as_ref(),
2175            0,
2176            &[SkinRange {
2177                input_base: 8,
2178                region: &region,
2179                palette: &palette,
2180                bindings: &bindings,
2181            }],
2182        )
2183        .expect("a legal frame");
2184
2185        let written = recorder
2186            .buffer_bytes(pass.palettes[0])
2187            .expect("the palette is live");
2188        for (index, matrix) in palette.iter().enumerate() {
2189            let want: Vec<u8> = matrix
2190                .to_cols_array()
2191                .iter()
2192                .flat_map(|value| value.to_le_bytes())
2193                .collect();
2194            assert_eq!(
2195                &written[index * JOINT_STRIDE..(index + 1) * JOINT_STRIDE],
2196                &want[..],
2197                "palette matrix {index} is not the columns the shader reads with no transpose"
2198            );
2199        }
2200        let written = recorder
2201            .buffer_bytes(pass.bindings[0])
2202            .expect("the binding buffer is live");
2203        for (index, binding) in bindings.iter().enumerate() {
2204            assert_eq!(
2205                &written[index * SKIN_BINDING_STRIDE..(index + 1) * SKIN_BINDING_STRIDE],
2206                &binding.to_bytes()[..],
2207                "skin binding {index} is not what the shader crate encodes"
2208            );
2209        }
2210    }
2211
2212    /// How many host writes landed in each slot's binding buffer since the
2213    /// recorder was last cleared, in slot order.
2214    fn binding_writes(recorder: &Recorder, pass: &Skinning) -> Vec<usize> {
2215        let events = recorder.events();
2216        pass.bindings
2217            .iter()
2218            .map(|slot| {
2219                events
2220                    .iter()
2221                    .filter(|event| {
2222                        matches!(event, Event::BufferWritten { buffer, .. } if buffer == slot)
2223                    })
2224                    .count()
2225            })
2226            .collect()
2227    }
2228
2229    /// Whether a slot's binding buffer starts with `bindings`, as the shader
2230    /// reads them.
2231    fn holds(recorder: &Recorder, pass: &Skinning, slot: usize, bindings: &[SkinBinding]) -> bool {
2232        let want: Vec<u8> = bindings.iter().flat_map(SkinBinding::to_bytes).collect();
2233        recorder
2234            .buffer_bytes(pass.bindings[slot])
2235            .is_some_and(|bytes| bytes[..want.len()] == want[..])
2236    }
2237
2238    /// **Unchanged skin bindings are not uploaded again, and a change reaches
2239    /// every frame slot exactly once.**
2240    ///
2241    /// The bindings are a mesh's own vertex data, so re-sending them every
2242    /// frame was most of a skinned frame's host cost. More slots than the
2243    /// renderer's [`crate::forward::FRAMES_IN_FLIGHT`], so "every slot" is not
2244    /// satisfied by "this one and the other": a change written into only the
2245    /// slot that saw it leaves the next frame in flight skinning against the
2246    /// old set, which is a visible flicker every other frame and nothing else
2247    /// reports it.
2248    #[test]
2249    fn unchanged_bindings_are_not_uploaded_again_and_a_change_reaches_every_slot_once() {
2250        const FRAMES: usize = 3;
2251        const { assert!(FRAMES > crate::forward::FRAMES_IN_FLIGHT) };
2252        let (recorder, device, _queue) = open();
2253        let mut pool = pool(device.as_ref(), 32);
2254        let source = pool.reserve_vertices(4).expect("room");
2255        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
2256        let mut pass = Skinning::new(
2257            device.as_ref(),
2258            &SkinningDesc {
2259                label: Some("skinning test"),
2260                frames: FRAMES,
2261                ranges: 1,
2262                joints: 2,
2263                bindings: 4,
2264                vertices: pool.vertex_buffer(),
2265                attribute_base: pool.attribute_base(),
2266            },
2267        )
2268        .expect("the null backend accepts every descriptor");
2269        let palette = [Mat4::IDENTITY; 2];
2270        let before = rigid(4);
2271        let mut after = rigid(4);
2272        after[2] = SkinBinding {
2273            joints: [1, 0, 0, 0],
2274            weights: [0.75, 0.25, 0.0, 0.0],
2275        };
2276        let mut frame = 0;
2277        let mut begin = |pass: &mut Skinning, bindings: &[SkinBinding]| {
2278            let slot = frame % FRAMES;
2279            frame += 1;
2280            pass.begin_frame(
2281                device.as_ref(),
2282                slot,
2283                &[SkinRange {
2284                    input_base: source,
2285                    region: &region,
2286                    palette: &palette,
2287                    bindings,
2288                }],
2289            )
2290            .expect("a legal frame");
2291            slot
2292        };
2293
2294        // The first lap fills every slot, once each.
2295        for _ in 0..FRAMES {
2296            begin(&mut pass, &before);
2297        }
2298        assert_eq!(binding_writes(&recorder, &pass), [1; FRAMES]);
2299
2300        // Steady frames write the palette and nothing of the bindings.
2301        recorder.clear();
2302        for _ in 0..2 * FRAMES {
2303            begin(&mut pass, &before);
2304        }
2305        assert_eq!(
2306            binding_writes(&recorder, &pass),
2307            [0; FRAMES],
2308            "a frame handing over the same bindings re-uploaded them"
2309        );
2310        let palette_writes = recorder
2311            .events()
2312            .iter()
2313            .filter(|event| {
2314                matches!(
2315                    event,
2316                    Event::BufferWritten { buffer, .. } if pass.palettes.contains(buffer)
2317                )
2318            })
2319            .count();
2320        assert_eq!(
2321            palette_writes,
2322            2 * FRAMES,
2323            "the pose still has to go up every frame, and the count above has to be able to \
2324             see a write"
2325        );
2326
2327        // A change goes into each slot as that slot comes round, and only then.
2328        recorder.clear();
2329        for lap in 0..2 * FRAMES {
2330            let slot = begin(&mut pass, &after);
2331            assert_eq!(slot, lap % FRAMES, "the change lands at the start of a lap");
2332            assert!(
2333                holds(&recorder, &pass, slot, &after),
2334                "slot {slot} skinned frame {lap} after the change against the old bindings"
2335            );
2336            for later in lap + 1..FRAMES {
2337                assert!(
2338                    holds(&recorder, &pass, later % FRAMES, &before),
2339                    "slot {later} was written before it began a frame, while the device may still \
2340                     read it"
2341                );
2342            }
2343        }
2344        assert_eq!(
2345            binding_writes(&recorder, &pass),
2346            [1; FRAMES],
2347            "a change is one write into each slot, and then none"
2348        );
2349    }
2350
2351    /// A change is a change of **bits**: a weight going from `0.0` to `-0.0`
2352    /// is a different buffer, which `f32`'s `==` would call the same.
2353    #[test]
2354    fn a_change_to_a_bindings_sign_of_zero_is_still_uploaded() {
2355        let (recorder, device, _queue) = open();
2356        let mut pool = pool(device.as_ref(), 32);
2357        let source = pool.reserve_vertices(1).expect("room");
2358        let region = SkinnedRegion::reserve(&mut pool, 1).expect("room");
2359        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 1);
2360        let positive = rigid(1);
2361        let mut negative = rigid(1);
2362        negative[0].weights[3] = -0.0;
2363        for (frame, bindings) in [&positive, &negative].into_iter().enumerate() {
2364            pass.begin_frame(
2365                device.as_ref(),
2366                frame % 2,
2367                &[SkinRange {
2368                    input_base: source,
2369                    region: &region,
2370                    palette: &[Mat4::IDENTITY],
2371                    bindings,
2372                }],
2373            )
2374            .expect("a legal frame");
2375        }
2376        assert!(holds(&recorder, &pass, 1, &negative));
2377        assert!(holds(&recorder, &pass, 0, &positive));
2378    }
2379
2380    /// **The joint check survives the bindings not changing.** They are
2381    /// checked in full only when they differ from the last set, so the same
2382    /// set handed over with a shorter palette must still be refused, and by
2383    /// the vertex that names the missing joint — and the refusal must not count
2384    /// as having accepted anything.
2385    #[test]
2386    fn unchanged_bindings_are_still_checked_against_a_shorter_palette() {
2387        let (recorder, device, _queue) = open();
2388        let mut pool = pool(device.as_ref(), 32);
2389        let source = pool.reserve_vertices(3).expect("room");
2390        let region = SkinnedRegion::reserve(&mut pool, 3).expect("room");
2391        let mut pass = skinning(device.as_ref(), &pool, 1, 4, 3);
2392        let mut bindings = rigid(3);
2393        bindings[2].joints[1] = 3;
2394        let begin = |pass: &mut Skinning, palette: &[Mat4]| {
2395            pass.begin_frame(
2396                device.as_ref(),
2397                0,
2398                &[SkinRange {
2399                    input_base: source,
2400                    region: &region,
2401                    palette,
2402                    bindings: &bindings,
2403                }],
2404            )
2405        };
2406
2407        begin(&mut pass, &[Mat4::IDENTITY; 4]).expect("joint 3 of a four-joint palette");
2408        match begin(&mut pass, &[Mat4::IDENTITY; 2]) {
2409            Err(SkinningError::JointOutOfRange {
2410                range,
2411                vertex,
2412                slot,
2413                joint,
2414                palette,
2415            }) => assert_eq!((range, vertex, slot, joint, palette), (0, 2, 1, 3, 2)),
2416            other => panic!("{other:?} does not name the joint that is out of range"),
2417        }
2418        recorder.clear();
2419        begin(&mut pass, &[Mat4::IDENTITY; 4]).expect("joint 3 of a four-joint palette again");
2420        assert_eq!(
2421            binding_writes(&recorder, &pass),
2422            [0, 0],
2423            "the refused frame changed what the slot is known to hold"
2424        );
2425    }
2426
2427    /// **A binding naming a joint the palette has not got is refused, loudly
2428    /// and by name.**
2429    ///
2430    /// The gap `docs/backlog.md` records: `crcbl-scene` cannot make this check
2431    /// because a glTF primitive does not know its skin at import, and the
2432    /// shader can only clamp. This call knows both, so it is where the refusal
2433    /// belongs — and the message has to name the vertex, or a rigger is left
2434    /// with "somewhere in this mesh".
2435    #[test]
2436    fn a_binding_naming_a_joint_the_palette_has_not_got_is_refused() {
2437        let (recorder, device, _queue) = open();
2438        let mut pool = pool(device.as_ref(), 32);
2439        let region = SkinnedRegion::reserve(&mut pool, 3).expect("room");
2440        let mut pass = skinning(device.as_ref(), &pool, 1, 2, 3);
2441        let mut bindings = rigid(3);
2442        // The third joint slot of the middle vertex, carrying no weight at all
2443        // — the shader reads all four matrices before it scales any of them, so
2444        // a weightless slot is the same clamped read as a weighted one.
2445        bindings[1].joints[2] = 7;
2446
2447        let error = pass
2448            .begin_frame(
2449                device.as_ref(),
2450                0,
2451                &[SkinRange {
2452                    input_base: 0,
2453                    region: &region,
2454                    palette: &[Mat4::IDENTITY, Mat4::IDENTITY],
2455                    bindings: &bindings,
2456                }],
2457            )
2458            .expect_err("joint 7 of a two-joint palette");
2459
2460        match error {
2461            SkinningError::JointOutOfRange {
2462                range,
2463                vertex,
2464                slot,
2465                joint,
2466                palette,
2467            } => assert_eq!((range, vertex, slot, joint, palette), (0, 1, 2, 7, 2)),
2468            other => panic!("{other} does not name the joint that is out of range"),
2469        }
2470        assert!(
2471            recorder
2472                .buffer_bytes(pass.params[0][0])
2473                .is_some_and(|bytes| bytes.iter().all(|byte| *byte == 0)),
2474            "a refused frame must not have written a uniform block"
2475        );
2476        assert!(
2477            pass.active[0].is_empty(),
2478            "and it must not have left a dispatch plan behind"
2479        );
2480    }
2481
2482    /// The palette length is a range's own, not the buffer's: a joint index
2483    /// legal for a longer palette elsewhere in the frame is still refused here.
2484    #[test]
2485    fn a_joint_index_is_checked_against_its_own_ranges_palette() {
2486        let (_recorder, device, _queue) = open();
2487        let mut pool = pool(device.as_ref(), 32);
2488        let long = SkinnedRegion::reserve(&mut pool, 1).expect("room");
2489        let short = SkinnedRegion::reserve(&mut pool, 1).expect("room");
2490        let mut pass = skinning(device.as_ref(), &pool, 2, 6, 2);
2491        let mut named_three = rigid(1);
2492        named_three[0].joints[0] = 3;
2493
2494        // Legal against a four-joint palette…
2495        pass.begin_frame(
2496            device.as_ref(),
2497            0,
2498            &[SkinRange {
2499                input_base: 0,
2500                region: &long,
2501                palette: &[Mat4::IDENTITY; 4],
2502                bindings: &named_three,
2503            }],
2504        )
2505        .expect("joint 3 of a four-joint palette");
2506
2507        // …and refused against the two-joint one beside it.
2508        let error = pass
2509            .begin_frame(
2510                device.as_ref(),
2511                0,
2512                &[
2513                    SkinRange {
2514                        input_base: 0,
2515                        region: &long,
2516                        palette: &[Mat4::IDENTITY; 4],
2517                        bindings: &rigid(1),
2518                    },
2519                    SkinRange {
2520                        input_base: 1,
2521                        region: &short,
2522                        palette: &[Mat4::IDENTITY; 2],
2523                        bindings: &named_three,
2524                    },
2525                ],
2526            )
2527            .expect_err("joint 3 of a two-joint palette");
2528        assert!(
2529            matches!(error, SkinningError::JointOutOfRange { range: 1, .. }),
2530            "{error} blames the wrong range"
2531        );
2532    }
2533
2534    /// An empty palette is refused here rather than left to the shader crate's
2535    /// panic, which is what would otherwise take the frame down.
2536    #[test]
2537    fn an_empty_palette_is_refused_rather_than_reaching_the_blocks_panic() {
2538        let (_recorder, device, _queue) = open();
2539        let mut pool = pool(device.as_ref(), 32);
2540        let region = SkinnedRegion::reserve(&mut pool, 1).expect("room");
2541        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 1);
2542        let error = pass
2543            .begin_frame(
2544                device.as_ref(),
2545                0,
2546                &[SkinRange {
2547                    input_base: 0,
2548                    region: &region,
2549                    palette: &[],
2550                    bindings: &rigid(1),
2551                }],
2552            )
2553            .expect_err("no joints to blend onto");
2554        assert!(
2555            matches!(error, SkinningError::EmptyPalette { range: 0 }),
2556            "{error}"
2557        );
2558    }
2559
2560    /// The skin bindings are parallel to the bind-pose run, so a list that is
2561    /// not one per vertex is refused rather than silently covering part of the
2562    /// mesh.
2563    #[test]
2564    fn a_binding_run_that_is_not_one_per_vertex_is_refused() {
2565        let (_recorder, device, _queue) = open();
2566        let mut pool = pool(device.as_ref(), 32);
2567        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
2568        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 8);
2569        for offered in [3usize, 5] {
2570            let error = pass
2571                .begin_frame(
2572                    device.as_ref(),
2573                    0,
2574                    &[SkinRange {
2575                        input_base: 0,
2576                        region: &region,
2577                        palette: &[Mat4::IDENTITY],
2578                        bindings: &rigid(offered),
2579                    }],
2580                )
2581                .expect_err("four vertices need four bindings");
2582            assert!(
2583                matches!(
2584                    error,
2585                    SkinningError::BindingCountMismatch {
2586                        vertices: 4,
2587                        bindings,
2588                        ..
2589                    } if bindings == offered
2590                ),
2591                "{error}"
2592            );
2593        }
2594    }
2595
2596    /// Every capacity is refused by name rather than truncated: a character
2597    /// silently missing from the frame is what these bounds exist to prevent.
2598    #[test]
2599    fn a_frame_over_any_capacity_is_refused_and_names_which() {
2600        let (_recorder, device, _queue) = open();
2601        let mut pool = pool(device.as_ref(), 64);
2602        let region = SkinnedRegion::reserve(&mut pool, 2).expect("room");
2603        let two = rigid(2);
2604        let range = |palette: &'static [Mat4]| SkinRange {
2605            input_base: 0,
2606            region: &region,
2607            palette,
2608            bindings: &two,
2609        };
2610        const ONE: &[Mat4] = &[Mat4::IDENTITY];
2611        const THREE: &[Mat4] = &[Mat4::IDENTITY, Mat4::IDENTITY, Mat4::IDENTITY];
2612
2613        let mut pass = skinning(device.as_ref(), &pool, 1, 8, 8);
2614        let error = pass
2615            .begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
2616            .expect_err("two ranges in a pass built for one");
2617        assert!(
2618            matches!(
2619                error,
2620                SkinningError::OverCapacity {
2621                    what: "ranges",
2622                    capacity: 1,
2623                    asked: 2
2624                }
2625            ),
2626            "{error}"
2627        );
2628
2629        let mut pass = skinning(device.as_ref(), &pool, 2, 2, 8);
2630        let error = pass
2631            .begin_frame(device.as_ref(), 0, &[range(THREE)])
2632            .expect_err("three matrices in a buffer of two");
2633        assert!(
2634            matches!(
2635                error,
2636                SkinningError::OverCapacity {
2637                    what: "palette matrices",
2638                    capacity: 2,
2639                    asked: 3
2640                }
2641            ),
2642            "{error}"
2643        );
2644
2645        let mut pass = skinning(device.as_ref(), &pool, 2, 8, 3);
2646        let error = pass
2647            .begin_frame(device.as_ref(), 0, &[range(ONE), range(ONE)])
2648            .expect_err("four bindings in a buffer of three");
2649        assert!(
2650            matches!(
2651                error,
2652                SkinningError::OverCapacity {
2653                    what: "skin bindings",
2654                    capacity: 3,
2655                    asked: 4
2656                }
2657            ),
2658            "{error}"
2659        );
2660    }
2661
2662    /// A frame with nothing to skin adds no pass, so the vertex pool pays no
2663    /// barrier for a dispatch that would not have happened.
2664    ///
2665    /// And a slot whose previous frame *did* have ranges is cleared by the
2666    /// empty call rather than re-dispatching them, which is the failure the
2667    /// plan being per-slot state would otherwise produce.
2668    #[test]
2669    fn a_frame_with_nothing_to_skin_adds_no_pass_and_clears_the_slot() {
2670        let (recorder, device, queue) = open();
2671        let mut pool = pool(device.as_ref(), 32);
2672        let region = SkinnedRegion::reserve(&mut pool, 4).expect("room");
2673        let mut pass = skinning(device.as_ref(), &pool, 1, 1, 4);
2674        pass.begin_frame(
2675            device.as_ref(),
2676            0,
2677            &[SkinRange {
2678                input_base: 0,
2679                region: &region,
2680                palette: &[Mat4::IDENTITY],
2681                bindings: &rigid(4),
2682            }],
2683        )
2684        .expect("a legal frame");
2685
2686        let mut graph = RenderGraph::new(queue);
2687        assert!(
2688            pass.add_pass(&mut graph, 0).is_some(),
2689            "a frame with a range has a pass"
2690        );
2691
2692        pass.begin_frame(device.as_ref(), 0, &[])
2693            .expect("an empty frame is legal");
2694        recorder.clear();
2695        let mut graph = RenderGraph::new(queue);
2696        assert!(
2697            pass.add_pass(&mut graph, 0).is_none(),
2698            "a frame with no ranges adds nothing"
2699        );
2700        let compiled = graph.compile(&TransientPool::new()).expect("a legal frame");
2701        assert!(
2702            compiled.passes().is_empty(),
2703            "and the graph has no skinning pass in it"
2704        );
2705        run(&recorder, device.as_ref(), queue, &pass, 0);
2706        assert!(
2707            dispatches(&recorder).is_empty(),
2708            "nothing is dispatched for a frame with nothing to skin"
2709        );
2710    }
2711
2712    /// The bind-group layout is the order `skinning.slang` declares its
2713    /// resources, and the vertex pool is the one writable entry.
2714    ///
2715    /// `crcbl_shaders::skinning` records the same table and holds the shader to
2716    /// it; this is the other half — a layout built against a different
2717    /// assignment binds the palette where the skin bindings belong, and every
2718    /// backend accepts it happily because both are read-only storage buffers.
2719    #[test]
2720    fn the_bind_group_layout_is_the_order_the_shader_declares() {
2721        let (recorder, device, _queue) = open();
2722        let pool = pool(device.as_ref(), 8);
2723        let pass = skinning(device.as_ref(), &pool, 1, 1, 1);
2724        let (_, entries) = recorder
2725            .bind_group_layouts_created()
2726            .into_iter()
2727            .find(|(label, _)| label.as_deref() == Some("skinning test"))
2728            .expect("the pass created its layout");
2729        assert_eq!(entries.len(), 4);
2730        assert!(matches!(
2731            entries[0].kind,
2732            crcbl_hal::BindingKind::UniformBuffer { .. }
2733        ));
2734        for (binding, read_only) in [(1usize, true), (2, true), (3, false)] {
2735            match entries[binding].kind {
2736                crcbl_hal::BindingKind::StorageBuffer { read_only: got, .. } => assert_eq!(
2737                    got, read_only,
2738                    "binding {binding} is the wrong kind of storage buffer"
2739                ),
2740                other => panic!("binding {binding} is {other:?}, not a storage buffer"),
2741            }
2742        }
2743        pass.destroy(device.as_ref());
2744    }
2745
2746    /// Every object the pass created is released, and the vertex pool it
2747    /// borrowed is not.
2748    #[test]
2749    fn destroy_releases_everything_the_pass_made_and_nothing_it_borrowed() {
2750        let (recorder, device, _queue) = open();
2751        let pool = pool(device.as_ref(), 8);
2752        let borrowed = recorder.total_live_objects();
2753        let pass = skinning(device.as_ref(), &pool, 2, 4, 4);
2754        assert!(recorder.total_live_objects() > borrowed);
2755        pass.destroy(device.as_ref());
2756        assert_eq!(
2757            recorder.total_live_objects(),
2758            borrowed,
2759            "the pass released everything it made, and left the pool's buffers alone"
2760        );
2761        pool.destroy(device.as_ref());
2762        assert_eq!(
2763            recorder.total_live_objects(),
2764            0,
2765            "and the pool's own buffers were still there to release"
2766        );
2767    }
2768
2769    /// A descriptor asking for no frames, ranges, joints or bindings is
2770    /// refused: a buffer of zero bytes is not a buffer on any backend the
2771    /// engine targets.
2772    #[test]
2773    fn a_descriptor_with_a_zero_in_it_is_refused() {
2774        let (_recorder, device, _queue) = open();
2775        let pool = pool(device.as_ref(), 8);
2776        let base = SkinningDesc {
2777            label: Some("zero"),
2778            frames: 1,
2779            ranges: 1,
2780            joints: 1,
2781            bindings: 1,
2782            vertices: pool.vertex_buffer(),
2783            attribute_base: pool.attribute_base(),
2784        };
2785        for desc in [
2786            SkinningDesc { frames: 0, ..base },
2787            SkinningDesc { ranges: 0, ..base },
2788            SkinningDesc { joints: 0, ..base },
2789            SkinningDesc {
2790                bindings: 0,
2791                ..base
2792            },
2793        ] {
2794            let error = Skinning::new(device.as_ref(), &desc).expect_err("a zero is refused");
2795            assert!(matches!(error, SkinningError::Hal(_)), "{error}");
2796        }
2797    }
2798
2799    /// The float-at-a-time serialisation `write_palette` replaced, kept as the
2800    /// reference its bytes must equal.
2801    fn reference_palette(palette: &[Mat4]) -> Vec<u8> {
2802        let mut out = Vec::new();
2803        for matrix in palette {
2804            for value in matrix.to_cols_array() {
2805                out.extend_from_slice(&value.to_le_bytes());
2806            }
2807        }
2808        out
2809    }
2810
2811    #[test]
2812    fn write_palette_matches_the_float_at_a_time_bytes() {
2813        // A fixed xorshift, so the values are arbitrary bit patterns (NaN
2814        // payloads and subnormals included) and the run is repeatable.
2815        let mut state = 0x9e37_79b9_7f4a_7c15u64;
2816        let mut next = || {
2817            state ^= state << 13;
2818            state ^= state >> 7;
2819            state ^= state << 17;
2820            f32::from_bits(state as u32)
2821        };
2822        let edges = [
2823            -0.0,
2824            0.0,
2825            f32::from_bits(0x7fc0_0001),
2826            f32::from_bits(0xffa0_1234),
2827            f32::from_bits(1),
2828            f32::from_bits(0x807f_ffff),
2829            f32::INFINITY,
2830            f32::NEG_INFINITY,
2831            f32::MAX,
2832            f32::MIN_POSITIVE,
2833        ];
2834        let mut palette: Vec<Mat4> = (0..64)
2835            .map(|_| Mat4::from_cols_array(&std::array::from_fn(|_| next())))
2836            .collect();
2837        palette.push(Mat4::from_cols_array(&std::array::from_fn(|index| {
2838            edges[index % edges.len()]
2839        })));
2840        // Not symmetric, so a transpose cannot pass.
2841        palette.push(Mat4::from_cols_array(&std::array::from_fn(|index| {
2842            index as f32
2843        })));
2844
2845        let mut written = vec![0xaa];
2846        write_palette(&mut written, &palette);
2847        assert_eq!(written[0], 0xaa, "write_palette appends, it does not clear");
2848        assert_eq!(written.len() - 1, palette.len() * JOINT_STRIDE);
2849        assert!(
2850            written[1..] == reference_palette(&palette)[..],
2851            "write_palette is not the float-at-a-time bytes"
2852        );
2853    }
2854}