Skip to main content

crcbl_render/
instance_pool.rs

1//! The instance array: one storage-buffer element per drawable object, written
2//! by **delta upload** — the changed elements only, coalesced into runs.
3//!
4//! ```text
5//!  set(handle, instance) ──▶ mirror[index] rewritten
6//!                            └─▶ index marked dirty in every frame's range set
7//!
8//!  begin_frame(device) ──▶ rotate to the next frame's buffer
9//!                          └─▶ one write_buffer per dirty run, then clear
10//!                              └─▶ nothing dirty ⇒ nothing written at all
11//! ```
12//!
13//! Topic 03 §3.2: "`GpuInstance` array (SSBO):
14//! transform, mesh id, material id, flags. Written by delta upload each frame
15//! (**changed instances only — dirty ranges, not full re-upload**)." The
16//! emphasis is the whole reason this type exists rather than a `Vec` re-uploaded
17//! every frame, which is what [`crate::sprite_pass`] does and what §3.2 is
18//! written against.
19//!
20//! The record itself — and which of its fields are reserved rather than working
21//! — is [`crcbl_shaders::mesh::GpuInstance`], because the layout is a contract
22//! with `mesh.slang` and belongs in the crate that owns that source.
23//!
24//! # Dirty runs, and the case they exist for
25//!
26//! The pool holds a sorted list of half-open runs that never touch and
27//! never overlap. Marking an index that **abuts** a run extends it; marking one
28//! that closes the gap between two runs merges them; marking one that is already
29//! inside a run does nothing. So writing instances 3, 4 and 5 produces one
30//! upload of three elements and writing 3 and 900 produces two uploads of one —
31//! whatever order the marks arrive in.
32//!
33//! Nothing merges across a gap, however small: two runs one element apart stay
34//! two. A gap-tolerant merge trades bytes for calls, and choosing where that
35//! trade sits needs a real scene to measure — §3.3's, which is also the first
36//! thing that will move more than one instance per frame.
37//!
38//! # A ring, because the previous frame is still reading
39//!
40//! There is one buffer **per frame in flight**, for the reason
41//! [`crate::forward`]'s uniform ring gives: an instance the CPU rewrites while
42//! the GPU is still drawing last frame is a read-after-write hazard across
43//! submissions, which is stage 2's headline risk for
44//! that stage.
45//!
46//! The consequence is that a write is dirty in **every** slot's range set, not
47//! one: each slot is a separate copy of the same logical array and each has to
48//! be caught up before it is drawn from. So one changed instance costs one small
49//! upload per frame for the next `frames_in_flight` frames, and then nothing.
50//! That is still delta upload — the cost is the size of what changed, not the
51//! size of the array — and [`InstancePool::begin_frame`] writes nothing at all
52//! once every slot has caught up.
53//!
54//! # Where each instance was last frame
55//!
56//! [`GpuInstance::previous_transform`] is the pool's field, not the caller's,
57//! the way the liveness bit is. [`InstancePool::set`] fills it from what the
58//! record already holds, [`InstancePool::insert`] fills it from the new
59//! transform — a spawn did not travel from anywhere — and
60//! [`InstancePool::rotate`] puts back at rest whatever moved a frame ago and
61//! has not moved again. [`InstancePool::set_bases`] is the one write that is
62//! **not** a move: it rewrites a record's two base vertices and leaves this
63//! field and the carry-forward enrolment exactly as they stand, because the
64//! per-frame re-point a skinned object goes through is not a caller saying the
65//! object travelled.
66//!
67//! That last step is what makes the field mean *last frame* rather than *the
68//! last time anyone wrote this*. An instance that moves for a while and then
69//! stands still is written on the frames it moves and not after; without the
70//! carry-forward its record would go on naming the transform it left, and every
71//! temporal consumer would go on smearing it along a journey that finished.
72//!
73//! It is the frame *before* the one being assembled that settles, because a
74//! caller writes a frame's instances and then calls
75//! [`InstancePool::begin_frame`] — so the moves of the frame about to be drawn
76//! have already happened by the time the rotate runs, and settling those would
77//! erase each one before it was ever drawn.
78//!
79//! The cost is one comparison per element per frame after the last write to it,
80//! and one extra upload of that element on the first frame it stands still.
81//! Nothing reads the field yet — topic 43 §9 is why
82//! it is here before its readers are.
83//!
84//! # The pool never grows
85//!
86//! Capacity is fixed by [`InstancePoolDesc`] and [`InstancePool::insert`] fails
87//! by name when it runs out. Same reason [`crate::mesh_pool`] gives: growing a
88//! device buffer means allocating a larger one, copying, and re-pointing every
89//! bind group that names the old one, in the middle of a frame.
90//!
91//! Unlike the geometry pools there is no fragmentation to report, because every
92//! instance is the same size: a slot that comes back fits whatever asks for it
93//! next. [`InstancePoolError::PoolFull`] therefore names one number where
94//! [`crate::mesh_pool::MeshPoolError::PoolExhausted`] names three.
95//!
96//! # What a removed instance leaves behind, and the one bit that says so
97//!
98//! [`InstancePool::remove`] frees the slot and retires the handle, and it
99//! rewrites **one field** of the element: it clears
100//! [`GpuInstance::LIVE`] from the record's flags and marks
101//! the slot dirty, so the next [`InstancePool::begin_frame`] carries the
102//! removal to the GPU. Everything else the removed instance held — its
103//! transform, its mesh id — stays exactly as it was.
104//!
105//! That is the whole contract, and it is what §3.3's cull pass needs: the pass
106//! walks the array from element zero, so a freed slot has to be able to say it
107//! is one. `cull.slang` asks the bit before it reads anything else in the
108//! record, and [`crate::cull::visible_instances`] — the CPU oracle — does the
109//! same.
110//!
111//! **The bit is the pool's, not the caller's.** [`InstancePool::insert`] and
112//! [`InstancePool::set`] set it whatever the caller passed, so an instance
113//! cannot arrive dead by omission, and a caller cannot clear it without going
114//! through `remove`. The other bits of the word are the caller's and are left
115//! alone.
116//!
117//! ## Why the record is not zeroed
118//!
119//! [`crate::mesh_pool::MeshPool::free`] clears its table entry to all zeroes,
120//! and the analogous move here would be to zero the whole instance. It is the
121//! wrong one. What the mesh table is doing is *writing the empty value of the
122//! field that answers the question* — `index_count` — and the fields it clears
123//! with it are ones a stale entry would otherwise be misread through; the
124//! parallel here is clearing the liveness bit, which is that same write.
125//!
126//! Zeroing the rest would make it worse rather than tidier. A zeroed transform
127//! is a degenerate box at the origin and a zeroed mesh id names table entry 0,
128//! which is an ordinary resident mesh — so a consumer that skipped the liveness
129//! check would see a removed instance as *visible whenever the origin is*,
130//! where leaving the record alone at least leaves it wherever it was. The
131//! failure a shortcut produces should not be the one that looks plausible.
132
133use core::ops::Range;
134
135use crcbl_core::{Handle, Pool};
136use crcbl_hal::{BufferDesc, BufferHandle, BufferUsage, Device, HalError, MemoryLocation};
137use crcbl_shaders::mesh::{GpuInstance, INSTANCE_STRIDE};
138
139/// Marker type for [`InstanceHandle`]. Uninhabited.
140#[derive(Debug)]
141pub enum Instance {}
142
143/// An instance in an [`InstancePool`]. Generational, so a removed instance's
144/// handle stops resolving rather than naming whatever took its slot.
145pub type InstanceHandle = Handle<Instance>;
146
147/// What an [`InstancePool`] refuses to do.
148#[derive(Debug, thiserror::Error)]
149pub enum InstancePoolError {
150    /// Every slot is in use.
151    ///
152    /// `in_use` is normally the number of live instances. It can exceed that
153    /// only through generation exhaustion — see [`Pool`]'s docs on retired
154    /// slots, which needs about 4.3 billion removals of one slot — and the two
155    /// are reported together so that case is legible rather than baffling.
156    #[error("the instance pool holds {capacity} instances and {in_use} of them are in use")]
157    PoolFull {
158        /// The pool's fixed capacity.
159        capacity: u32,
160        /// Slots that cannot be handed out.
161        in_use: u32,
162    },
163    /// Anything the seam refused.
164    #[error(transparent)]
165    Hal(#[from] HalError),
166}
167
168/// Flattens a pool error into the seam's, for callers whose constructors are
169/// already `Result<_, HalError>`.
170///
171/// Same shape and same reason as [`crate::mesh_pool::MeshPoolError`]'s: the seam
172/// has no vocabulary for "this pool is full", so everything that is not already
173/// a [`HalError`] arrives as [`Backend`](HalError::Backend), which renders
174/// verbatim and keeps the numbers.
175impl From<InstancePoolError> for HalError {
176    fn from(error: InstancePoolError) -> Self {
177        match error {
178            InstancePoolError::Hal(hal) => hal,
179            other => Self::Backend(other.to_string()),
180        }
181    }
182}
183
184/// How large an [`InstancePool`] is, and what to call it.
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub struct InstancePoolDesc<'a> {
187    /// Debug name; each frame's buffer is named after it.
188    pub label: Option<&'a str>,
189    /// Instances the pool can hold. Fixed — see the [module docs](self).
190    pub capacity: u32,
191    /// How many buffers to keep, one per frame in flight. Must be at least one.
192    pub frames_in_flight: usize,
193}
194
195/// One `GpuInstance` array, mirrored on the host and uploaded by delta.
196///
197/// See the [module docs](self) for the coalescing rule, the ring, and what a
198/// removal leaves behind — all three are decisions rather than accidents.
199#[derive(Debug)]
200pub struct InstancePool {
201    /// One per frame in flight; `frame` says which is current.
202    buffers: Vec<BufferHandle>,
203    /// What has changed and not yet reached each buffer. Same length as
204    /// `buffers`, and indexed the same way.
205    dirty: Vec<DirtyRanges>,
206    /// The slot `begin_frame` last rotated to.
207    frame: usize,
208
209    /// The array exactly as a buffer holds it, so a dirty run is one contiguous
210    /// slice and there is no second copy of an instance to drift from this one.
211    mirror: Vec<u8>,
212    /// Generational slot allocation, and nothing else: the values live in
213    /// `mirror`. Reusing the crate's pool rather than writing a second
214    /// allocator that gets the generation-retirement rule subtly different.
215    slots: Pool<()>,
216    /// Elements a caller has written since the last [`InstancePool::rotate`],
217    /// which is what the frame being assembled now moves.
218    written_this_frame: Vec<u32>,
219    /// `written_this_frame` as it stood at the last [`InstancePool::rotate`]:
220    /// what the frame already drawn moved, and so what the next rotate has to
221    /// put back at rest. See the [module docs](self) on the previous transform.
222    written_last_frame: Vec<u32>,
223    /// Whether each element is already in `written_this_frame`, so a caller
224    /// that writes one instance repeatedly in a frame enrols it once. Indexed
225    /// by element, `capacity` long.
226    moved_mark: Vec<bool>,
227    capacity: u32,
228    /// One past the highest element [`InstancePool::insert`] has ever handed
229    /// out — what [`InstancePool::slot_count`] reports.
230    high_water: u32,
231    /// How many times the mirror has been written — [`InstancePool::revision`].
232    revision: u64,
233    /// Elements written since the last [`InstancePool::take_written`], each
234    /// once, in the order they were first written.
235    written_since_taken: Vec<u32>,
236    /// Whether each element is already in `written_since_taken`. Indexed by
237    /// element, `capacity` long.
238    written_since_taken_mark: Vec<bool>,
239}
240
241impl InstancePool {
242    /// Creates the ring, with every buffer **cleared**.
243    ///
244    /// Cleared rather than left as the driver handed it over, and for
245    /// [`crate::mesh_pool::MeshPool`]'s reason rather than for tidiness: a slot
246    /// nothing has written is read by anything that walks the array, and "a
247    /// zeroed element is a dead instance" is only a contract if it holds for
248    /// the slots no one has touched as well as for the ones
249    /// [`InstancePool::remove`] clears. A driver's leftovers are not zeroes,
250    /// and a leftover with [`GpuInstance::LIVE`] set is an instance the cull
251    /// pass keeps, at a transform nobody chose.
252    ///
253    /// This is why it was not always so: until the flags word had a defined
254    /// bit, zeroing bought nothing an element written before it is addressed
255    /// did not already have.
256    ///
257    /// The device buffers are created **before** the host mirror, so a capacity
258    /// no device could hold arrives as a [`HalError`] naming the buffer rather
259    /// than as an aborting host allocation of the same size.
260    ///
261    /// # Errors
262    ///
263    /// [`InstancePoolError::Hal`] from any seam call. A failure part-way through
264    /// releases whatever was already created.
265    ///
266    /// # Panics
267    ///
268    /// If `frames_in_flight` is zero: a ring with no buffers has nothing to
269    /// bind, and every later index into it would be the real failure.
270    pub fn new(
271        device: &dyn Device,
272        desc: &InstancePoolDesc<'_>,
273    ) -> Result<Self, InstancePoolError> {
274        assert!(
275            desc.frames_in_flight > 0,
276            "an instance pool needs at least one buffer to bind"
277        );
278        let stem = desc.label.unwrap_or("instance pool");
279        let size = u64::from(desc.capacity) * INSTANCE_STRIDE as u64;
280        let cleared = vec![0u8; desc.capacity as usize * INSTANCE_STRIDE];
281        let mut buffers = Vec::with_capacity(desc.frames_in_flight);
282        for frame in 0..desc.frames_in_flight {
283            let created = device
284                .create_buffer(&BufferDesc {
285                    label: Some(&format!("{stem} instances {frame}")),
286                    size,
287                    // Host-visible, so a delta is a `write_buffer` rather than a
288                    // staging copy needing a barrier inside a frame.
289                    // `crate::graph` is the only thing allowed to record a
290                    // barrier during a frame, and a per-frame transfer submit is
291                    // what §3.1's start-up upload path deliberately is not.
292                    usage: BufferUsage::STORAGE,
293                    memory: MemoryLocation::HostUpload,
294                })
295                // A buffer created and not cleared is one the failure path below
296                // has to release, so the clear happens here rather than in a
297                // second loop over the finished ring.
298                .and_then(|buffer| match device.write_buffer(buffer, 0, &cleared) {
299                    Ok(()) => Ok(buffer),
300                    Err(error) => {
301                        device.destroy_buffer(buffer);
302                        Err(error)
303                    }
304                });
305            match created {
306                Ok(buffer) => buffers.push(buffer),
307                Err(error) => {
308                    for buffer in buffers {
309                        device.destroy_buffer(buffer);
310                    }
311                    return Err(error.into());
312                }
313            }
314        }
315        Ok(Self {
316            buffers,
317            dirty: vec![DirtyRanges::default(); desc.frames_in_flight],
318            frame: 0,
319            mirror: vec![0; desc.capacity as usize * INSTANCE_STRIDE],
320            slots: Pool::new(),
321            written_this_frame: Vec::new(),
322            written_last_frame: Vec::new(),
323            moved_mark: vec![false; desc.capacity as usize],
324            capacity: desc.capacity,
325            high_water: 0,
326            revision: 0,
327            written_since_taken: Vec::new(),
328            written_since_taken_mark: vec![false; desc.capacity as usize],
329        })
330    }
331
332    /// The buffers, one per frame in flight, in slot order.
333    ///
334    /// A caller builds one bind group per slot naming the buffer at that slot,
335    /// and draws frame `n` with the group whose slot [`InstancePool::begin_frame`]
336    /// returned.
337    #[must_use]
338    pub fn buffers(&self) -> &[BufferHandle] {
339        &self.buffers
340    }
341
342    /// How many instances the pool can hold.
343    #[must_use]
344    pub const fn capacity(&self) -> u32 {
345        self.capacity
346    }
347
348    /// How many instances are live.
349    #[must_use]
350    pub const fn len(&self) -> usize {
351        self.slots.len()
352    }
353
354    /// Whether no instance is live.
355    #[must_use]
356    pub const fn is_empty(&self) -> bool {
357        self.slots.is_empty()
358    }
359
360    /// Array elements anything walking the pool has to cover: one past the
361    /// highest slot ever handed out.
362    ///
363    /// **Not [`InstancePool::len`]**, which counts live instances and so shrinks
364    /// when one is removed while the slots above it stay occupied. A cull
365    /// dispatch sized by `len` would silently stop testing the instances past
366    /// the gap, which reads as "those were culled".
367    ///
368    /// It never shrinks, because a slot handed out once may be handed out again
369    /// and nothing compacts the array. Every element below it is either a live
370    /// instance or a dead record — [`InstancePool::remove`] leaves one, and
371    /// [`InstancePool::new`] clears the buffers so an untouched slot is one too
372    /// — which is what makes walking the whole range safe.
373    /// How many times any element of the array has been written, over the
374    /// pool's whole life.
375    ///
376    /// **A number to compare with an older reading of itself, not to interpret**
377    /// — two readings that differ say the instances a pass draws are not the
378    /// ones it drew last time it looked, and two that agree say they are. What
379    /// wants that is a consumer whose output is a function of the array and can
380    /// be kept instead of recomputed. `ForwardRenderer`'s shadow atlas was the
381    /// one there was, and it now asks [`take_written`](Self::take_written)
382    /// instead, which says which elements moved rather than that one did.
383    ///
384    /// It moves on **every** write, including ones no draw could see: a rewrite
385    /// with identical bytes (which [`set`](Self::set) deliberately does not
386    /// filter), a re-point of a skinned object's bases, and the settling of a
387    /// `previous_transform` the frame after a move stopped. Reading it as "the
388    /// scene changed" is therefore conservative in the safe direction — it says
389    /// *changed* more often than a byte comparison would, and never says
390    /// *unchanged* when a byte moved.
391    ///
392    /// It counts writes rather than hashing the array because the array is the
393    /// pool's own capacity in bytes and this is read once a frame.
394    #[must_use]
395    pub const fn revision(&self) -> u64 {
396        self.revision
397    }
398
399    /// Appends every element written since the last call to `into`, each once
400    /// and in the order it was first written, and forgets them here.
401    ///
402    /// [`revision`](Self::revision) says *that* the array changed; this says
403    /// **which elements** did, on the same terms — every write counts,
404    /// including a rewrite with identical bytes, a re-point of a skinned
405    /// object's bases and the settling of a `previous_transform`, so an element
406    /// is left out only when nothing wrote it. What wants that is a consumer
407    /// that can tell which of its outputs an element could reach:
408    /// `ForwardRenderer`'s shadow atlas tests each written element's bounds,
409    /// before and after, against each shadow group's cull, so one moving
410    /// instance redraws the maps it can be seen in rather than every map.
411    ///
412    /// The log is bounded by [`capacity`](Self::capacity), because an element
413    /// already in it is not added again — a pool nobody drains costs at most
414    /// one entry per element.
415    pub fn take_written(&mut self, into: &mut Vec<u32>) {
416        for index in self.written_since_taken.drain(..) {
417            self.written_since_taken_mark[index as usize] = false;
418            into.push(index);
419        }
420    }
421
422    /// What element `index` holds, live or not, decoded from the host mirror,
423    /// or [`None`] at or past [`slot_count`](Self::slot_count).
424    ///
425    /// By element rather than by handle, for a caller that learned the index
426    /// from [`take_written`](Self::take_written): a removed instance's element
427    /// still holds its last transform and mesh with
428    /// [`GpuInstance::LIVE`] cleared, which is what says it draws nothing now.
429    #[must_use]
430    pub fn record(&self, index: u32) -> Option<GpuInstance> {
431        (index < self.high_water).then(|| self.read(index))
432    }
433
434    #[must_use]
435    pub const fn slot_count(&self) -> u32 {
436        self.high_water
437    }
438
439    /// Takes a slot, writes `instance` into it **live**, and marks it dirty
440    /// everywhere.
441    ///
442    /// [`GpuInstance::LIVE`] is set whatever `instance.flags` carried — see the
443    /// [module docs](self) on why the bit is the pool's rather than the
444    /// caller's.
445    ///
446    /// # Errors
447    ///
448    /// [`InstancePoolError::PoolFull`] when every slot is in use. The pool never
449    /// grows — see the [module docs](self).
450    pub fn insert(&mut self, instance: &GpuInstance) -> Result<InstanceHandle, InstancePoolError> {
451        // `Pool` hands out a fresh index only when it has no vacant slot, so
452        // "live plus permanently retired" is exactly the highest index it could
453        // be about to create. Checking before inserting rather than after keeps
454        // a refused insert from burning a generation.
455        let in_use = self.in_use();
456        if in_use >= self.capacity {
457            return Err(InstancePoolError::PoolFull {
458                capacity: self.capacity,
459                in_use,
460            });
461        }
462        let handle: InstanceHandle = self.slots.insert(()).cast();
463        self.high_water = self.high_water.max(handle.index() + 1);
464        // **A spawn did not travel from anywhere**, so the record is created
465        // already at rest: whatever the slot held before belonged to another
466        // instance, and carrying it forward would give the new one a motion
467        // vector across the gap between them.
468        self.write_live(handle.index(), instance, instance.transform);
469        Ok(handle)
470    }
471
472    /// Rewrites `handle`'s instance and marks it dirty everywhere.
473    ///
474    /// Returns whether the handle named a live instance; a stale one writes
475    /// nothing rather than overwriting whatever took its slot.
476    ///
477    /// [`GpuInstance::LIVE`] is set, exactly as [`InstancePool::insert`] sets
478    /// it: a live instance cannot be made dead by rewriting it, only by
479    /// [`InstancePool::remove`].
480    ///
481    /// A rewrite with the same bytes still marks the slot dirty. Filtering that
482    /// would trade a comparison per write for an upload that mostly does not
483    /// happen, and it would make "what got uploaded" depend on the old value —
484    /// which is exactly the kind of thing a caller cannot reason about. Callers
485    /// that know a value did not change do not call this.
486    pub fn set(&mut self, handle: InstanceHandle, instance: &GpuInstance) -> bool {
487        if !self.slots.contains(handle.cast()) {
488            return false;
489        }
490        // Where it was is what the record already holds, which is why the
491        // caller does not pass it — see [`GpuInstance::previous_transform`].
492        let previous = self.read(handle.index()).transform;
493        self.write_live(handle.index(), instance, previous);
494        true
495    }
496
497    /// Rewrites `handle`'s two base vertices and **nothing else** — the
498    /// previous transform the record already holds included.
499    ///
500    /// Returns whether the handle named a live instance; a stale one writes
501    /// nothing, on [`InstancePool::set`]'s terms. The record keeps
502    /// [`GpuInstance::LIVE`], because every path that puts one in the mirror is
503    /// a path that set the bit.
504    ///
505    /// **It exists because a re-point is not a move.**
506    /// [`ForwardRenderer::point_skinned_instances`](crate::forward::ForwardRenderer)
507    /// rewrites every skinned object's pair of bases once a frame, between the
508    /// [`rotate`](Self::rotate) and the upload, and doing that through
509    /// [`set`](Self::set) made it a *transform* write: `set` takes the previous
510    /// transform from the record it overwrites, and by then that record already
511    /// carries this frame's transform, so `previous_transform` came out equal to
512    /// `transform` for every skinned instance on every frame. A character that
513    /// walked contributed nothing to the motion target from the walk.
514    ///
515    /// It also leaves the element out of the next [`rotate`](Self::rotate)'s
516    /// carry-forward, which is the same reason from the other side: a call that
517    /// runs for every skinned object every frame would keep each of them
518    /// permanently written-this-frame, nothing would ever be put back at rest,
519    /// and one move would be reported for ever. What enrols an element is a
520    /// caller's own write — [`insert`](Self::insert) and [`set`](Self::set).
521    pub fn set_bases(
522        &mut self,
523        handle: InstanceHandle,
524        base_vertex: u32,
525        previous_base_vertex: u32,
526    ) -> bool {
527        if !self.slots.contains(handle.cast()) {
528            return false;
529        }
530        let index = handle.index();
531        let mut record = self.read(index);
532        record.base_vertex = base_vertex;
533        record.previous_base_vertex = previous_base_vertex;
534        self.write(index, &record);
535        true
536    }
537
538    /// Rewrites `handle`'s flags word and **nothing else**, on
539    /// [`set_bases`](Self::set_bases)' terms: a flag is not a move, so the
540    /// transform history is left as it is and the element is not enrolled in the
541    /// next [`rotate`](Self::rotate)'s carry-forward.
542    ///
543    /// [`GpuInstance::LIVE`] is kept set whatever `flags` says, because the pool
544    /// owns that bit. Returns whether the handle named a live instance; a stale
545    /// one writes nothing.
546    pub fn set_flags(&mut self, handle: InstanceHandle, flags: u32) -> bool {
547        if !self.slots.contains(handle.cast()) {
548            return false;
549        }
550        let index = handle.index();
551        let mut record = self.read(index);
552        record.flags = flags | GpuInstance::LIVE;
553        self.write(index, &record);
554        true
555    }
556
557    /// Clears `bits` from the flags of every live instance that carries any of
558    /// them, and writes only those.
559    ///
560    /// A walk over every slot ever handed out, for a change that is rare by
561    /// nature — a view being released, whose bit every record has to stop
562    /// carrying. [`GpuInstance::LIVE`] is never cleared here, whatever `bits`
563    /// holds.
564    pub fn clear_flags(&mut self, bits: u32) {
565        let bits = bits & !GpuInstance::LIVE;
566        for index in 0..self.high_water {
567            let mut record = self.read(index);
568            if record.flags & GpuInstance::LIVE == 0 || record.flags & bits == 0 {
569                continue;
570            }
571            record.flags &= !bits;
572            self.write(index, &record);
573        }
574    }
575
576    /// What `handle`'s slot currently holds, decoded from the host mirror, or
577    /// `None` if the handle is stale.
578    ///
579    /// The record carries [`GpuInstance::LIVE`], because the pool put it there:
580    /// this is what the buffer holds, not what the caller passed.
581    #[must_use]
582    pub fn get(&self, handle: InstanceHandle) -> Option<GpuInstance> {
583        self.slots
584            .contains(handle.cast())
585            .then(|| self.read(handle.index()))
586    }
587
588    /// Every live element of the array, in slot order.
589    ///
590    /// **The records the device would draw**, decoded from the same mirror the
591    /// buffers are filled from — including
592    /// [`GpuInstance::LIVE`](crcbl_shaders::mesh::GpuInstance::LIVE), which the
593    /// pool sets, so a caller filters on the bit rather than on a second list
594    /// it kept. Slots nothing has written are cleared, and a cleared record has
595    /// the bit off.
596    ///
597    /// Added for `crate::probe_visibility`, which needs the scene as it stands
598    /// rather than as it was described: a probe's visibility map is about where
599    /// the walls *are*, and the walls arrive through
600    /// [`InstancePool::insert`] rather than through the description.
601    #[must_use]
602    pub fn live(&self) -> Vec<GpuInstance> {
603        (0..self.high_water)
604            .map(|index| self.read(index))
605            .filter(|record| record.flags & GpuInstance::LIVE != 0)
606            .collect()
607    }
608
609    /// Every element the pool has handed out, in slot order, dead ones included
610    /// — the array [`slot_count`](Self::slot_count) elements long that a cull
611    /// dispatch walks, decoded from the host mirror.
612    ///
613    /// For `crate::cull`'s oracle, which indexes it the way the shader does:
614    /// [`live`](Self::live) drops the dead slots and with them the indices.
615    #[must_use]
616    pub fn records(&self) -> Vec<GpuInstance> {
617        (0..self.high_water).map(|index| self.read(index)).collect()
618    }
619
620    /// Which element of the array `handle` is, or `None` if the handle is stale.
621    ///
622    /// This is the number a shader indexes with, which is why it is public: a
623    /// draw has to be able to say which instance it draws.
624    #[must_use]
625    pub fn index(&self, handle: InstanceHandle) -> Option<u32> {
626        self.slots.contains(handle.cast()).then(|| handle.index())
627    }
628
629    /// Frees `handle`'s slot for reuse, retires the handle, and clears the
630    /// element's [`GpuInstance::LIVE`] bit.
631    ///
632    /// Returns whether the handle named a live instance. The rest of the
633    /// element's bytes are left as they are — see the [module docs](self) on
634    /// why clearing the bit is the whole of what a removal owes the GPU, and why
635    /// zeroing the record would be worse than leaving it.
636    ///
637    /// The clear reaches the device the way every other write does, through
638    /// [`InstancePool::begin_frame`]: the slot is marked dirty in every buffer's
639    /// range set, so a removal costs the same one small upload per frame in
640    /// flight that a rewrite does.
641    pub fn remove(&mut self, handle: InstanceHandle) -> bool {
642        if self.slots.remove(handle.cast()).is_none() {
643            return false;
644        }
645        let index = handle.index();
646        let mut removed = self.read(index);
647        removed.flags &= !GpuInstance::LIVE;
648        self.write(index, &removed);
649        true
650    }
651
652    /// Rotates to the next frame's buffer and writes that buffer's outstanding
653    /// changes into it, returning the slot it rotated to.
654    ///
655    /// **A frame in which nothing was written performs no seam call at all.**
656    /// That is §3.2's claim about this design, and it is the thing to check when
657    /// wondering whether delta upload is really happening.
658    ///
659    /// # Errors
660    ///
661    /// [`HalError`] if a write failed. The runs it had already written stay
662    /// written and the rest stay dirty, so a later frame retries them — a
663    /// half-uploaded array that forgot the rest would be the worse failure.
664    pub fn begin_frame(&mut self, device: &dyn Device) -> Result<usize, HalError> {
665        let slot = self.rotate();
666        self.flush(device)?;
667        Ok(slot)
668    }
669
670    /// Rotates to the next frame's buffer **without uploading anything**, and
671    /// returns the slot it rotated to.
672    ///
673    /// The half of [`begin_frame`](Self::begin_frame) that decides which buffer
674    /// this frame writes, split out for the one caller that has an instance to
675    /// write which *depends* on the slot:
676    /// [`ForwardRenderer::begin_skinned_frame`](crate::forward::ForwardRenderer::begin_skinned_frame)
677    /// points every skinned instance at the half of its region this frame's
678    /// dispatch will fill, and the parity it reads comes from a
679    /// [`Skinning`](crate::skinning::Skinning) that has to be handed this slot
680    /// first. Rotating and uploading in one call would leave that write for the
681    /// *next* frame's upload, which is a character posed one frame late.
682    ///
683    /// [`flush`](Self::flush) must follow it, or this frame draws whatever the
684    /// frame before last left in this buffer.
685    ///
686    /// **This is also the frame boundary the previous transform is measured
687    /// against**: an element the frame before last wrote and this one did not
688    /// is put back at rest here, so an instance that stopped moving stops
689    /// reporting a move. See [`GpuInstance::previous_transform`] and the
690    /// [module docs](self).
691    pub fn rotate(&mut self) -> usize {
692        self.carry_forward();
693        self.frame = (self.frame + 1) % self.buffers.len();
694        self.frame
695    }
696
697    /// Writes the current slot's outstanding changes into its buffer.
698    ///
699    /// The other half of [`begin_frame`](Self::begin_frame). Idempotent: a
700    /// second call with nothing newly written performs no seam call at all.
701    ///
702    /// # Errors
703    ///
704    /// [`HalError`] if a write failed, on [`begin_frame`](Self::begin_frame)'s
705    /// terms — the runs already written stay written and the rest stay dirty.
706    pub fn flush(&mut self, device: &dyn Device) -> Result<(), HalError> {
707        let slot = self.frame;
708        let buffer = self.buffers[slot];
709        // Detached so the mirror can be borrowed while the runs are walked.
710        let mut runs = core::mem::take(&mut self.dirty[slot].runs);
711        for (done, run) in runs.iter().enumerate() {
712            let at = run.start as usize * INSTANCE_STRIDE;
713            let end = run.end as usize * INSTANCE_STRIDE;
714            if let Err(error) = device.write_buffer(buffer, at as u64, &self.mirror[at..end]) {
715                runs.drain(..done);
716                self.dirty[slot].runs = runs;
717                return Err(error);
718            }
719        }
720        runs.clear();
721        self.dirty[slot].runs = runs;
722        Ok(())
723    }
724
725    #[cfg(all(test, not(target_arch = "wasm32")))]
726    pub(super) fn replace_test_buffer(
727        &mut self,
728        slot: usize,
729        replacement: BufferHandle,
730    ) -> BufferHandle {
731        core::mem::replace(&mut self.buffers[slot], replacement)
732    }
733
734    /// Releases every buffer. The device must be idle.
735    pub fn destroy(self, device: &dyn Device) {
736        for buffer in self.buffers {
737            device.destroy_buffer(buffer);
738        }
739    }
740
741    /// Slots that cannot be handed out: live ones, plus any permanently
742    /// withdrawn by generation exhaustion.
743    fn in_use(&self) -> u32 {
744        let used = self.slots.len() + self.slots.retired_slots();
745        u32::try_from(used).unwrap_or(u32::MAX)
746    }
747
748    /// What the mirror holds at `index`, live or not.
749    ///
750    /// Decoded rather than kept beside the bytes, for the reason the mirror is
751    /// bytes at all: a second copy of an instance is a second thing to drift
752    /// from the one the buffer gets.
753    fn read(&self, index: u32) -> GpuInstance {
754        let at = index as usize * INSTANCE_STRIDE;
755        let bytes: &[u8; INSTANCE_STRIDE] = self.mirror[at..at + INSTANCE_STRIDE]
756            .try_into()
757            .unwrap_or_else(|_| unreachable!("the mirror is capacity × INSTANCE_STRIDE"));
758        GpuInstance::from_bytes(bytes)
759    }
760
761    /// [`InstancePool::write`] with [`GpuInstance::LIVE`] forced on and
762    /// `previous_transform` set to `previous`, which is what every
763    /// caller-supplied record goes through.
764    ///
765    /// Both fields are the pool's rather than the caller's, for the same
766    /// reason: the pool is what knows the answer — that the record is live, and
767    /// what it held a moment ago — and a caller asked for either would be
768    /// keeping a second copy of what this one already has.
769    ///
770    /// It also enrols the element in the carry-forward the next
771    /// [`InstancePool::rotate`] performs, which is what stops a moving instance
772    /// that stopped from reporting the move it made forever.
773    fn write_live(&mut self, index: u32, instance: &GpuInstance, previous: [f32; 16]) {
774        self.write(
775            index,
776            &GpuInstance {
777                flags: instance.flags | GpuInstance::LIVE,
778                previous_transform: previous,
779                ..*instance
780            },
781        );
782        if !self.moved_mark[index as usize] {
783            self.moved_mark[index as usize] = true;
784            self.written_this_frame.push(index);
785        }
786    }
787
788    /// Puts every element a caller wrote last frame at rest: its
789    /// `previous_transform` becomes its `transform`, so a frame in which it is
790    /// not written again reports no motion.
791    ///
792    /// **This is the half that makes the field mean "last frame" rather than
793    /// "the last time anyone touched it".** Without it, an instance that moved
794    /// once and then stood still would go on carrying the transform it moved
795    /// from, and every temporal consumer would go on smearing it along a
796    /// journey that finished.
797    ///
798    /// **It carries forward the frame *before* the one being assembled**, and
799    /// that is the whole subtlety. A caller writes the instances for frame `n`
800    /// and *then* calls [`InstancePool::begin_frame`], so by the time this runs
801    /// the moves of frame `n` have already happened and each already carries
802    /// where it came from — putting those at rest would erase the move before
803    /// it was ever drawn. What is left to settle is frame `n - 1`'s writes that
804    /// frame `n` did not repeat, which is exactly "it moved, and then it
805    /// stopped".
806    ///
807    /// A record already at rest is skipped, so the cost of standing still is
808    /// one comparison in the frame after the last move and nothing after that.
809    /// The write goes through [`InstancePool::write`] rather than
810    /// [`InstancePool::write_live`]: it must not enrol the element again, or a
811    /// pool that had ever moved anything would re-examine it every frame
812    /// forever.
813    fn carry_forward(&mut self) {
814        for at in 0..self.written_last_frame.len() {
815            let index = self.written_last_frame[at];
816            if self.moved_mark[index as usize] {
817                // Written again for the frame about to be drawn, so it is
818                // moving rather than stopping and its own write said where
819                // from.
820                continue;
821            }
822            let mut record = self.read(index);
823            if record.previous_transform == record.transform {
824                continue;
825            }
826            record.previous_transform = record.transform;
827            self.write(index, &record);
828        }
829        self.written_last_frame.clear();
830        core::mem::swap(&mut self.written_last_frame, &mut self.written_this_frame);
831        for index in &self.written_last_frame {
832            self.moved_mark[*index as usize] = false;
833        }
834    }
835
836    /// Puts `instance` into the mirror at `index` and marks it dirty in every
837    /// slot's range set.
838    ///
839    /// **The only thing that ever changes the mirror**, which is what makes
840    /// [`revision`](Self::revision) and [`take_written`](Self::take_written)
841    /// total answers rather than counts of the paths somebody remembered to
842    /// instrument.
843    fn write(&mut self, index: u32, instance: &GpuInstance) {
844        let at = index as usize * INSTANCE_STRIDE;
845        self.mirror[at..at + INSTANCE_STRIDE].copy_from_slice(&instance.to_bytes());
846        self.revision = self.revision.wrapping_add(1);
847        if !self.written_since_taken_mark[index as usize] {
848            self.written_since_taken_mark[index as usize] = true;
849            self.written_since_taken.push(index);
850        }
851        for dirty in &mut self.dirty {
852            dirty.mark(index);
853        }
854    }
855}
856
857/// A sorted set of half-open element runs that never overlap and never touch.
858///
859/// "Never touch" is the load-bearing half: it is what makes marking 3, 4 and 5
860/// one run rather than three, and it is maintained by [`DirtyRanges::mark`]
861/// extending and merging rather than appending. A list that only appended would
862/// produce one `write_buffer` per changed element, which is the cost §3.2's
863/// delta upload exists to avoid — it would still be correct, and it would still
864/// pass any test that only checked the bytes.
865#[derive(Clone, Debug, Default, PartialEq, Eq)]
866struct DirtyRanges {
867    runs: Vec<Range<u32>>,
868}
869
870impl DirtyRanges {
871    /// Marks one element dirty, extending or merging the runs around it.
872    ///
873    /// Idempotent: marking an element already inside a run changes nothing, so
874    /// a value written twice between uploads is uploaded once.
875    ///
876    /// `index` must be below `u32::MAX`, which an [`InstancePool`] index is:
877    /// it is below a capacity that is itself a `u32`.
878    fn mark(&mut self, index: u32) {
879        // The first run that could contain or abut `index` from the left.
880        // Everything before it ends strictly below `index`, so nothing there
881        // can touch what this leaves behind.
882        let at = self.runs.partition_point(|run| run.end < index);
883        // Inside the run, or exactly one past its end.
884        if self.runs.get(at).is_some_and(|run| run.start <= index) {
885            if self.runs[at].end == index {
886                self.runs[at].end = index + 1;
887                // Extending may have closed the gap to the next run, which is
888                // the case that turns "3 and 5, then 4" into one run.
889                if self
890                    .runs
891                    .get(at + 1)
892                    .is_some_and(|next| next.start == index + 1)
893                {
894                    let end = self.runs.remove(at + 1).end;
895                    self.runs[at].end = end;
896                }
897            }
898            return;
899        }
900        // Exactly one before the run. It cannot now touch the run before it:
901        // that one ends strictly below `index`.
902        if self.runs.get(at).is_some_and(|run| run.start == index + 1) {
903            self.runs[at].start = index;
904            return;
905        }
906        // A gap on both sides, or past the last run.
907        self.runs.insert(at, index..index + 1);
908    }
909}
910
911// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
912#[cfg(all(test, not(target_arch = "wasm32")))]
913mod tests {
914    use super::*;
915    use crcbl_hal::null::{Event, NullInstance, Recorder};
916    use crcbl_hal::{DeviceDesc, Instance};
917
918    const FRAMES: usize = 2;
919
920    fn open() -> (Recorder, Box<dyn Device>) {
921        let recorder = Recorder::new();
922        let instance = NullInstance::gpu_driven().with_recorder(recorder.clone());
923        let adapter = instance.adapters().remove(0);
924        let device = instance
925            .create_device(&DeviceDesc::for_adapter(adapter.id))
926            .expect("the null backend always opens");
927        (recorder, device)
928    }
929
930    fn pool(device: &dyn Device, capacity: u32) -> InstancePool {
931        InstancePool::new(
932            device,
933            &InstancePoolDesc {
934                label: Some("test"),
935                capacity,
936                frames_in_flight: FRAMES,
937            },
938        )
939        .expect("the null backend accepts every descriptor")
940    }
941
942    /// An instance whose transform is distinguishable from every other `n`, as
943    /// a **caller** hands it over.
944    ///
945    /// Its flags do not carry [`GpuInstance::LIVE`] for the `n` the tests below
946    /// use, which is what makes [`stored`] a different value and the pool's
947    /// forcing of the bit observable.
948    fn instance(n: u32) -> GpuInstance {
949        GpuInstance {
950            transform: [n as f32; 16],
951            // The pool overwrites this, and a value here that the pool would
952            // also have chosen could not tell that apart from it being passed
953            // through. Every `n` the tests use is non-zero, so this is a
954            // transform no caller record carries.
955            previous_transform: [0.0; 16],
956            mesh: n,
957            material: n + 1,
958            sector: n + 2,
959            flags: n + 3,
960            base_vertex: n + 4,
961            previous_base_vertex: n + 5,
962        }
963    }
964
965    /// [`instance`] as the pool stores it when it is **inserted**: the
966    /// caller's record, live, and at rest.
967    ///
968    /// Refuses an `n` whose flags happen to carry the bit already, because a
969    /// comparison against such a record would pass whether or not the pool set
970    /// it — which is the one way an assertion about the bit can be vacuous. The
971    /// same refusal covers the previous transform: `n` is non-zero for every
972    /// caller this module builds, so `instance(n)`'s zeroed one is a value the
973    /// pool has to have replaced.
974    fn stored(n: u32) -> GpuInstance {
975        let caller = instance(n);
976        assert_eq!(
977            caller.flags & GpuInstance::LIVE,
978            0,
979            "instance({n}) already carries the live bit; pick another n"
980        );
981        assert_ne!(
982            n, 0,
983            "instance(0)'s transform is its own zeroed previous one"
984        );
985        GpuInstance {
986            flags: caller.flags | GpuInstance::LIVE,
987            previous_transform: caller.transform,
988            ..caller
989        }
990    }
991
992    /// [`stored`] as the pool holds it after a **rewrite** from `was`: live,
993    /// and carrying where it came from.
994    fn stored_after(n: u32, was: u32) -> GpuInstance {
995        GpuInstance {
996            previous_transform: instance(was).transform,
997            ..stored(n)
998        }
999    }
1000
1001    /// Element `index` of the buffer at `slot`, decoded from the bytes that
1002    /// actually reached the device.
1003    ///
1004    /// Read back rather than taken from the pool's mirror, so an assertion is
1005    /// evidence about what a shader would read and not about the pool's
1006    /// bookkeeping agreeing with itself.
1007    fn on_device(recorder: &Recorder, pool: &InstancePool, slot: usize, index: u32) -> GpuInstance {
1008        let bytes = recorder
1009            .buffer_bytes(pool.buffers()[slot])
1010            .expect("the buffer is live");
1011        let at = index as usize * INSTANCE_STRIDE;
1012        GpuInstance::from_bytes(
1013            bytes[at..at + INSTANCE_STRIDE]
1014                .try_into()
1015                .expect("one element"),
1016        )
1017    }
1018
1019    /// Every `BufferWritten` this recorder saw, as `(offset, len)`.
1020    fn writes(recorder: &Recorder) -> Vec<(u64, usize)> {
1021        recorder
1022            .events()
1023            .into_iter()
1024            .filter_map(|event| match event {
1025                Event::BufferWritten { offset, len, .. } => Some((offset, len)),
1026                _ => None,
1027            })
1028            .collect()
1029    }
1030
1031    /// Drives `frames` uploads, discarding what they wrote — used to reach the
1032    /// steady state where every slot has caught up.
1033    fn settle(pool: &mut InstancePool, device: &dyn Device) {
1034        for _ in 0..FRAMES {
1035            pool.begin_frame(device).expect("the null device writes");
1036        }
1037    }
1038
1039    /// A dirty set's runs as `(start, end)` pairs, which is what the assertions
1040    /// below compare — a bare `Range` literal in an array reads as a range the
1041    /// author meant to iterate, and `clippy` says so.
1042    fn runs(dirty: &DirtyRanges) -> Vec<(u32, u32)> {
1043        dirty.runs.iter().map(|run| (run.start, run.end)).collect()
1044    }
1045
1046    mod scratch;
1047
1048    // --- the coalescing, which is pure logic ---
1049
1050    /// **The headline claim.** Adjacent marks are one run; separated marks are
1051    /// two. A list that appended would report three runs for the first case,
1052    /// which is one `write_buffer` per instance and the whole thing this design
1053    /// exists to avoid.
1054    #[test]
1055    fn adjacent_marks_coalesce_and_separated_ones_do_not() {
1056        let mut dirty = DirtyRanges::default();
1057        for index in [3u32, 4, 5] {
1058            dirty.mark(index);
1059        }
1060        assert_eq!(runs(&dirty), [(3, 6)], "3, 4 and 5 are one run of three");
1061
1062        let mut dirty = DirtyRanges::default();
1063        dirty.mark(3);
1064        dirty.mark(900);
1065        assert_eq!(runs(&dirty), [(3, 4), (900, 901)], "a gap stays a gap");
1066    }
1067
1068    /// The exact boundary, in both directions: two marks that **touch** are one
1069    /// run, two marks one element apart are two. Off by one either way and the
1070    /// first case fragments or the second merges across a gap it must not.
1071    #[test]
1072    fn the_boundary_between_touching_and_separated_is_one_element() {
1073        // `4` touches: 3..4 and 4..5 share an endpoint. `5` leaves one clear
1074        // element between them.
1075        for (second, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
1076            let mut dirty = DirtyRanges::default();
1077            dirty.mark(3);
1078            dirty.mark(second);
1079            assert_eq!(runs(&dirty), expected, "marking 3 then {second}");
1080        }
1081        // And from the other side, because extending a run backwards is a
1082        // different branch of `mark` than extending it forwards.
1083        for (first, expected) in [(4u32, &[(3, 5)][..]), (5, &[(3, 4), (5, 6)][..])] {
1084            let mut dirty = DirtyRanges::default();
1085            dirty.mark(first);
1086            dirty.mark(3);
1087            assert_eq!(runs(&dirty), expected, "marking {first} then 3");
1088        }
1089    }
1090
1091    /// Marking the element between two runs merges all three. Without the merge
1092    /// after an extend, this stays two runs that touch — which breaks the
1093    /// invariant everything else assumes and costs an upload forever after.
1094    #[test]
1095    fn closing_the_gap_between_two_runs_merges_them() {
1096        let mut dirty = DirtyRanges::default();
1097        dirty.mark(3);
1098        dirty.mark(5);
1099        assert_eq!(runs(&dirty), [(3, 4), (5, 6)]);
1100        dirty.mark(4);
1101        assert_eq!(runs(&dirty), [(3, 6)], "one run of three, not two touching");
1102    }
1103
1104    /// Order does not matter: every permutation of the same marks produces the
1105    /// same runs. Coalescing that only worked left-to-right would pass the
1106    /// tests above and fail the moment a caller wrote its instances in any
1107    /// other order.
1108    #[test]
1109    fn coalescing_does_not_depend_on_the_order_marks_arrive_in() {
1110        let marks = [7u32, 3, 5, 4, 900, 6];
1111        let mut permuted = marks;
1112        // Every rotation is enough to move each element through every position.
1113        for shift in 0..marks.len() {
1114            permuted.rotate_left(shift.min(1));
1115            let mut dirty = DirtyRanges::default();
1116            for index in permuted {
1117                dirty.mark(index);
1118            }
1119            assert_eq!(
1120                runs(&dirty),
1121                [(3, 8), (900, 901)],
1122                "the order {permuted:?} produced different runs"
1123            );
1124        }
1125    }
1126
1127    /// Marking the same element twice is one run of one, so a value rewritten
1128    /// between uploads is uploaded once.
1129    #[test]
1130    fn marking_the_same_element_twice_changes_nothing() {
1131        let mut dirty = DirtyRanges::default();
1132        dirty.mark(3);
1133        dirty.mark(3);
1134        assert_eq!(runs(&dirty), [(3, 4)]);
1135        // And re-marking inside an existing run leaves it alone.
1136        dirty.mark(4);
1137        dirty.mark(5);
1138        dirty.mark(4);
1139        assert_eq!(runs(&dirty), [(3, 6)]);
1140    }
1141
1142    // --- the pool ---
1143
1144    /// **The other headline claim: an unchanged frame uploads nothing.**
1145    ///
1146    /// Asserted on the recorded seam calls rather than on a "dirty" flag,
1147    /// because a flag is a claim about the pool's bookkeeping and this is a
1148    /// claim about what reached the device.
1149    #[test]
1150    fn a_frame_with_no_writes_uploads_nothing() {
1151        let (recorder, device) = open();
1152        let mut pool = pool(device.as_ref(), 16);
1153        pool.insert(&instance(1)).expect("room");
1154        settle(&mut pool, device.as_ref());
1155
1156        let before = writes(&recorder).len();
1157        assert!(before > 0, "the insert must have reached the device at all");
1158        for _ in 0..FRAMES * 3 {
1159            pool.begin_frame(device.as_ref()).expect("writes");
1160        }
1161        assert_eq!(
1162            writes(&recorder).len(),
1163            before,
1164            "six frames with nothing written must perform no seam call"
1165        );
1166
1167        pool.destroy(device.as_ref());
1168        recorder.assert_valid();
1169    }
1170
1171    /// **Every path that changes an instance moves the revision, and a frame
1172    /// that changed nothing leaves it alone.**
1173    ///
1174    /// [`InstancePool::revision`]'s whole contract, and the thing a consumer
1175    /// keeping something derived from the array — `ForwardRenderer`'s shadow
1176    /// atlas — bets a frame's correctness on. The list is deliberately every
1177    /// mutator this type has rather than a sample: a path that changed the
1178    /// mirror without moving the number would be a caster that moved under a
1179    /// shadow map nothing redrew.
1180    #[test]
1181    fn every_write_moves_the_revision_and_a_still_frame_does_not() {
1182        let (recorder, device) = open();
1183        let device = device.as_ref();
1184        let mut pool = pool(device, 16);
1185        let start = pool.revision();
1186
1187        let first = pool.insert(&instance(1)).expect("room");
1188        let inserted = pool.revision();
1189        assert!(inserted > start, "an insert did not move the revision");
1190
1191        assert!(pool.set(first, &instance(2)), "the handle is live");
1192        let written = pool.revision();
1193        assert!(written > inserted, "a rewrite did not move the revision");
1194
1195        assert!(
1196            pool.set(first, &instance(2)),
1197            "a rewrite with the same bytes is still a write — see `InstancePool::set`"
1198        );
1199        let repeated = pool.revision();
1200        assert!(
1201            repeated > written,
1202            "a rewrite the pool does not filter must not be filtered here either"
1203        );
1204
1205        assert!(pool.set_bases(first, 4, 8), "the handle is live");
1206        let repointed = pool.revision();
1207        assert!(repointed > repeated, "a re-point did not move the revision");
1208
1209        // A move to somewhere the record was not, so the settle below has a
1210        // `previous_transform` to put back: rewriting an instance with the
1211        // bytes it already holds leaves the two equal, and the carry-forward
1212        // skips a record already at rest.
1213        assert!(pool.set(first, &instance(3)), "the handle is live");
1214        let moved = pool.revision();
1215        assert!(moved > repointed, "a move did not move the revision");
1216
1217        // The frame after a move settles the record's `previous_transform`,
1218        // which is a write and so a change this number reports. Conservative in
1219        // the safe direction, and the reason the doc says so.
1220        settle(&mut pool, device);
1221        let settled = pool.revision();
1222        assert!(
1223            settled > moved,
1224            "the carry-forward wrote the mirror without saying so"
1225        );
1226
1227        // And now the pool is quiet: nothing was written, so nothing moves,
1228        // however many frames go by.
1229        for _ in 0..FRAMES * 3 {
1230            pool.begin_frame(device).expect("the null device writes");
1231        }
1232        assert_eq!(
1233            pool.revision(),
1234            settled,
1235            "a run of frames nobody wrote in moved the revision, so nothing derived from this \
1236             array could ever be kept"
1237        );
1238
1239        assert!(pool.remove(first), "the handle is live");
1240        assert!(
1241            pool.revision() > settled,
1242            "a removal did not move the revision, so an instance that left the scene would go \
1243             on casting a shadow"
1244        );
1245
1246        pool.destroy(device);
1247        recorder.assert_valid();
1248    }
1249
1250    /// **Every path that changes an element puts it in the written log, once,
1251    /// and a still frame puts nothing there.**
1252    ///
1253    /// [`InstancePool::take_written`]'s contract, which `ForwardRenderer`'s
1254    /// shadow atlas now bets a frame's correctness on in place of the revision:
1255    /// an element missing from the log is a caster that moved under a map
1256    /// nothing redrew. Every mutator this type has, as the revision's test
1257    /// above lists them.
1258    #[test]
1259    fn every_write_names_its_element_once_and_a_still_frame_names_none() {
1260        let (recorder, device) = open();
1261        let device = device.as_ref();
1262        let mut pool = pool(device, 16);
1263        let taken = |pool: &mut InstancePool| {
1264            let mut into = Vec::new();
1265            pool.take_written(&mut into);
1266            into
1267        };
1268
1269        let first = pool.insert(&instance(1)).expect("room");
1270        let second = pool.insert(&instance(2)).expect("room");
1271        assert!(pool.set(first, &instance(3)), "the handle is live");
1272        assert_eq!(
1273            taken(&mut pool),
1274            [0, 1],
1275            "two inserts and a rewrite of the first name each element once, first write first"
1276        );
1277        assert!(taken(&mut pool).is_empty(), "a taken log is forgotten");
1278
1279        assert!(pool.set(second, &instance(2)), "the handle is live");
1280        assert_eq!(
1281            taken(&mut pool),
1282            [1],
1283            "a same-bytes rewrite is still a write"
1284        );
1285        assert!(pool.set_bases(first, 4, 8), "the handle is live");
1286        assert_eq!(taken(&mut pool), [0], "a re-point is a write");
1287        assert!(pool.set_flags(second, 1 << 8), "the handle is live");
1288        assert_eq!(taken(&mut pool), [1], "a flag is a write");
1289        pool.clear_flags(1 << 8);
1290        assert_eq!(
1291            taken(&mut pool),
1292            [1],
1293            "clearing a flag writes what carried it"
1294        );
1295
1296        // The first element moved above, so the frame after its move puts its
1297        // `previous_transform` back at rest — a write the log reports.
1298        settle(&mut pool, device);
1299        assert_eq!(
1300            taken(&mut pool),
1301            [0],
1302            "the carry-forward wrote the mirror without naming the element"
1303        );
1304        for _ in 0..FRAMES * 3 {
1305            pool.begin_frame(device).expect("the null device writes");
1306        }
1307        assert!(
1308            taken(&mut pool).is_empty(),
1309            "a run of frames nobody wrote in named an element"
1310        );
1311
1312        assert!(pool.remove(first), "the handle is live");
1313        assert_eq!(taken(&mut pool), [0], "a removal is a write");
1314        let record = pool.record(0).expect("below the high-water mark");
1315        assert_eq!(
1316            record.flags & GpuInstance::LIVE,
1317            0,
1318            "a removed element reads back dead"
1319        );
1320        assert!(pool.record(2).is_none(), "past the high-water mark");
1321
1322        pool.destroy(device);
1323        recorder.assert_valid();
1324    }
1325
1326    /// Three adjacent instances written in one frame reach the device as **one**
1327    /// write of three elements, and two separated ones as two writes of one.
1328    /// This is the coalescing test above, seen from the device's side.
1329    #[test]
1330    fn adjacent_writes_reach_the_device_as_one_call() {
1331        let (recorder, device) = open();
1332        let mut pool = pool(device.as_ref(), 1024);
1333        let handles: Vec<_> = (0..6)
1334            .map(|n| pool.insert(&instance(n)).expect("room"))
1335            .collect();
1336        settle(&mut pool, device.as_ref());
1337
1338        let before = writes(&recorder).len();
1339        for handle in &handles[3..6] {
1340            pool.set(*handle, &instance(99));
1341        }
1342        pool.begin_frame(device.as_ref()).expect("writes");
1343        assert_eq!(
1344            writes(&recorder)[before..],
1345            [(3 * INSTANCE_STRIDE as u64, 3 * INSTANCE_STRIDE)],
1346            "instances 3, 4 and 5 must be one write of three elements"
1347        );
1348
1349        // Drained, so the next measurement is one slot's own runs rather than
1350        // that slot's leftovers from the write above — each slot lags the
1351        // others by a frame, which is the ring doing its job.
1352        settle(&mut pool, device.as_ref());
1353        let before = writes(&recorder).len();
1354        pool.set(handles[0], &instance(98));
1355        pool.set(handles[5], &instance(98));
1356        pool.begin_frame(device.as_ref()).expect("writes");
1357        assert_eq!(
1358            writes(&recorder)[before..],
1359            [
1360                (0, INSTANCE_STRIDE),
1361                (5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)
1362            ],
1363            "instances 0 and 5 are not adjacent and must be two writes"
1364        );
1365
1366        pool.destroy(device.as_ref());
1367        recorder.assert_valid();
1368    }
1369
1370    /// A write reaches **every** buffer in the ring, not just the one that
1371    /// happened to be current: each slot is a separate copy, and a slot that
1372    /// missed an update would draw a stale instance every other frame.
1373    #[test]
1374    fn a_write_reaches_every_buffer_in_the_ring() {
1375        let (recorder, device) = open();
1376        let mut pool = pool(device.as_ref(), 16);
1377        let handle = pool.insert(&instance(1)).expect("room");
1378        settle(&mut pool, device.as_ref());
1379
1380        pool.set(handle, &instance(2));
1381        let mut written_to = Vec::new();
1382        for _ in 0..FRAMES {
1383            let slot = pool.begin_frame(device.as_ref()).expect("writes");
1384            written_to.push(pool.buffers()[slot]);
1385        }
1386        let targets: Vec<BufferHandle> = recorder
1387            .events()
1388            .into_iter()
1389            .filter_map(|event| match event {
1390                Event::BufferWritten { buffer, .. } => Some(buffer),
1391                _ => None,
1392            })
1393            .collect();
1394        for buffer in pool.buffers() {
1395            assert!(
1396                targets.contains(buffer),
1397                "buffer {buffer:?} never received the instance"
1398            );
1399        }
1400        assert_eq!(written_to.len(), FRAMES);
1401
1402        pool.destroy(device.as_ref());
1403        recorder.assert_valid();
1404    }
1405
1406    /// A full pool refuses by name, and takes nothing: the refused insert must
1407    /// not consume a slot, or a caller that retries would lose capacity each
1408    /// time it was told there was none.
1409    #[test]
1410    fn a_full_pool_fails_by_name_and_takes_nothing() {
1411        let (recorder, device) = open();
1412        let mut pool = pool(device.as_ref(), 2);
1413        let first = pool.insert(&instance(0)).expect("room");
1414        pool.insert(&instance(1)).expect("room");
1415
1416        let error = pool
1417            .insert(&instance(2))
1418            .expect_err("two instances fill a pool of two");
1419        assert!(
1420            matches!(
1421                error,
1422                InstancePoolError::PoolFull {
1423                    capacity: 2,
1424                    in_use: 2
1425                }
1426            ),
1427            "got: {error:?}"
1428        );
1429        assert_eq!(pool.len(), 2, "a refused insert must not consume a slot");
1430
1431        // And a freed slot is handed out again, so the refusal above is the
1432        // capacity rather than the pool having given up.
1433        assert!(pool.remove(first));
1434        let reused = pool.insert(&instance(3)).expect("the freed slot");
1435        assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
1436        assert_eq!(pool.index(first), None, "and the old handle is retired");
1437
1438        pool.destroy(device.as_ref());
1439        recorder.assert_valid();
1440    }
1441
1442    /// The number a cull dispatch is sized by covers every occupied slot, and
1443    /// **it does not shrink when one is freed**.
1444    ///
1445    /// That is the whole difference from [`InstancePool::len`]: remove the
1446    /// middle instance of three and `len` says two, while the third is still at
1447    /// element 2 and a walk of `0..2` would never test it. A dispatch sized that
1448    /// way drops an instance from the picture and reports it as culled.
1449    #[test]
1450    fn the_slot_count_covers_every_occupied_element_and_never_shrinks() {
1451        let (recorder, device) = open();
1452        let mut pool = pool(device.as_ref(), 8);
1453        assert_eq!(pool.slot_count(), 0, "an empty pool has nothing to walk");
1454
1455        let handles: Vec<InstanceHandle> = (0..3)
1456            .map(|index| pool.insert(&instance(index)).expect("room"))
1457            .collect();
1458        assert_eq!(pool.slot_count(), 3);
1459
1460        assert!(pool.remove(handles[1]));
1461        assert_eq!(pool.len(), 2, "two are live");
1462        assert_eq!(
1463            pool.slot_count(),
1464            3,
1465            "and the highest is still at element 2, so a walk must still reach it"
1466        );
1467
1468        // A reused slot does not raise it either: the element was already
1469        // covered.
1470        pool.insert(&instance(9)).expect("the freed slot");
1471        assert_eq!(pool.slot_count(), 3);
1472
1473        pool.destroy(device.as_ref());
1474        recorder.assert_valid();
1475    }
1476
1477    /// One buffer per frame in flight, each sized for the whole capacity — the
1478    /// ring is what the module docs claim it is, and a pool that quietly kept
1479    /// one buffer would pass every other test here.
1480    #[test]
1481    fn the_ring_is_one_buffer_per_frame_in_flight() {
1482        let (recorder, device) = open();
1483        let pool = pool(device.as_ref(), 16);
1484        assert_eq!(pool.buffers().len(), FRAMES);
1485        let mut distinct = pool.buffers().to_vec();
1486        distinct.sort_unstable_by_key(|buffer| buffer.to_bits());
1487        distinct.dedup();
1488        assert_eq!(distinct.len(), FRAMES, "the slots must not share a buffer");
1489        assert_eq!(pool.capacity(), 16);
1490        assert!(pool.is_empty());
1491
1492        pool.destroy(device.as_ref());
1493        recorder.assert_valid();
1494    }
1495
1496    /// **Every buffer is cleared when the pool is created**, which is the other
1497    /// half of the removal contract: the cull pass walks from element zero, so
1498    /// the slots above the ones in use have to answer too, and a zeroed element
1499    /// is a dead instance.
1500    ///
1501    /// Asserted on the seam calls rather than on the bytes, and that is the
1502    /// only assertion available here: this recorder zero-fills a mappable
1503    /// buffer at creation, so a byte comparison would pass whether or not the
1504    /// pool ever wrote one. What a real driver leaves in a fresh host-visible
1505    /// allocation is its own business, which is why `crcbl-vk`'s `cull` e2e
1506    /// dispatches over a pool's whole capacity with only three slots inserted.
1507    #[test]
1508    fn every_buffer_is_cleared_when_the_pool_is_created() {
1509        let (recorder, device) = open();
1510        let pool = pool(device.as_ref(), 16);
1511        assert_eq!(
1512            writes(&recorder),
1513            vec![(0, 16 * INSTANCE_STRIDE); FRAMES],
1514            "each buffer in the ring must be cleared, whole, before anything reads it"
1515        );
1516
1517        pool.destroy(device.as_ref());
1518        recorder.assert_valid();
1519    }
1520
1521    /// **Where an instance was last frame, across the three cases that decide
1522    /// it**: a spawn is at rest, a move carries where it moved from, and a
1523    /// frame with no move puts it back at rest.
1524    ///
1525    /// The third is the one the carry-forward exists for and the one a pool
1526    /// without it would fail: `set` alone leaves the record naming the
1527    /// transform it left, so an instance that moved once and then stood still
1528    /// would report that move on every frame afterwards, forever.
1529    ///
1530    /// The order is a frame's real one — write the instances, *then*
1531    /// `begin_frame` — because that is what decides which frame a move belongs
1532    /// to.
1533    ///
1534    /// Read back off the device rather than out of the mirror: this is what a
1535    /// shader would fetch.
1536    #[test]
1537    fn an_instance_carries_where_it_was_last_frame() {
1538        let (recorder, device) = open();
1539        let mut pool = pool(device.as_ref(), 16);
1540        let handle = pool.insert(&instance(7)).expect("room");
1541        settle(&mut pool, device.as_ref());
1542        let index = pool.index(handle).expect("live");
1543        let slot = pool.frame;
1544        assert_eq!(
1545            on_device(&recorder, &pool, slot, index).previous_transform,
1546            instance(7).transform,
1547            "a spawn did not travel from anywhere"
1548        );
1549
1550        // The frame it moves: the record names both ends of the move.
1551        assert!(pool.set(handle, &instance(11)));
1552        let slot = pool
1553            .begin_frame(device.as_ref())
1554            .expect("the null device writes");
1555        let moved = on_device(&recorder, &pool, slot, index);
1556        assert_eq!(moved.transform, instance(11).transform, "it arrived");
1557        assert_eq!(
1558            moved.previous_transform,
1559            instance(7).transform,
1560            "and it says where from"
1561        );
1562
1563        // The next frame, with nothing written: back at rest.
1564        let slot = pool
1565            .begin_frame(device.as_ref())
1566            .expect("the null device writes");
1567        let stopped = on_device(&recorder, &pool, slot, index);
1568        assert_eq!(
1569            stopped.transform,
1570            instance(11).transform,
1571            "it has not moved"
1572        );
1573        assert_eq!(
1574            stopped.previous_transform, stopped.transform,
1575            "so it must report no motion"
1576        );
1577
1578        // And it stays at rest without being written again, in every buffer of
1579        // the ring rather than only the one the last frame rotated to.
1580        settle(&mut pool, device.as_ref());
1581        for slot in 0..FRAMES {
1582            let resting = on_device(&recorder, &pool, slot, index);
1583            assert_eq!(
1584                resting.previous_transform, resting.transform,
1585                "buffer {slot} still has it moving"
1586            );
1587        }
1588
1589        pool.destroy(device.as_ref());
1590        recorder.assert_valid();
1591    }
1592
1593    /// **An instance that keeps moving is never put at rest.** The
1594    /// carry-forward runs a frame behind, so the case it must not touch is the
1595    /// one where the caller wrote the instance again — settling that would
1596    /// erase a move before the frame holding it was ever drawn.
1597    #[test]
1598    fn an_instance_still_moving_is_not_put_at_rest() {
1599        let (recorder, device) = open();
1600        let mut pool = pool(device.as_ref(), 16);
1601        let handle = pool.insert(&instance(1)).expect("room");
1602        settle(&mut pool, device.as_ref());
1603        let index = pool.index(handle).expect("live");
1604
1605        for step in 2..6u32 {
1606            assert!(pool.set(handle, &instance(step)));
1607            let slot = pool
1608                .begin_frame(device.as_ref())
1609                .expect("the null device writes");
1610            let moving = on_device(&recorder, &pool, slot, index);
1611            assert_eq!(
1612                (moving.previous_transform, moving.transform),
1613                (instance(step - 1).transform, instance(step).transform),
1614                "the frame that moved it to {step} lost one end of the move"
1615            );
1616        }
1617
1618        pool.destroy(device.as_ref());
1619        recorder.assert_valid();
1620    }
1621
1622    /// **A re-point rewrites the two bases and leaves the move alone**, which
1623    /// is the whole of why [`InstancePool::set_bases`] exists.
1624    ///
1625    /// The record is moved first, so it is carrying a previous transform that
1626    /// differs from its current one when the bases are rewritten — a call that
1627    /// went through [`InstancePool::set`] would take the previous transform
1628    /// from the record it overwrites, which by then holds the move's *end*, and
1629    /// the move would be gone. That is what
1630    /// [`crate::forward::ForwardRenderer`]'s per-frame re-point did to every
1631    /// skinned instance.
1632    ///
1633    /// The frame checked on the device is the one the move is drawn in. The
1634    /// frame after it puts the record back at rest, which is
1635    /// [`carry_forward`](InstancePool::carry_forward)'s job rather than this
1636    /// call's — [`an_instance_carries_where_it_was_last_frame`] is where that
1637    /// half is asserted, and the renderer-level
1638    /// `a_skinned_instance_that_moves_carries_the_transform_it_moved_from` is
1639    /// where the two meet.
1640    ///
1641    /// The stale half is [`InstancePool::set`]'s contract: `false`, and nothing
1642    /// written — asserted on the bytes that reached the device and on the
1643    /// uploads a later frame performs, because a mirror written without being
1644    /// marked dirty would satisfy only one of the two.
1645    #[test]
1646    fn setting_the_bases_keeps_the_transform_the_record_moved_from() {
1647        let (recorder, device) = open();
1648        let mut pool = pool(device.as_ref(), 16);
1649        let handle = pool.insert(&instance(7)).expect("room");
1650        assert!(pool.set(handle, &instance(11)), "the handle is live");
1651
1652        assert!(pool.set_bases(handle, 40, 41), "the handle is still live");
1653        let repointed = GpuInstance {
1654            base_vertex: 40,
1655            previous_base_vertex: 41,
1656            ..stored_after(11, 7)
1657        };
1658        assert_eq!(
1659            pool.get(handle),
1660            Some(repointed),
1661            "a re-point owes the two bases it was given and every other field the record \
1662             already held — the previous transform above all"
1663        );
1664
1665        let index = pool.index(handle).expect("live");
1666        let slot = pool
1667            .begin_frame(device.as_ref())
1668            .expect("the null device writes");
1669        assert_eq!(
1670            on_device(&recorder, &pool, slot, index),
1671            repointed,
1672            "the buffer this frame draws from did not take the re-point, so a shader reads \
1673             the bases of the frame before"
1674        );
1675
1676        assert!(pool.remove(handle));
1677        for _ in 0..FRAMES * 2 {
1678            pool.begin_frame(device.as_ref())
1679                .expect("the null device writes");
1680        }
1681        recorder.clear();
1682        assert!(
1683            !pool.set_bases(handle, 60, 61),
1684            "a retired handle names no instance"
1685        );
1686        for _ in 0..FRAMES * 2 {
1687            pool.begin_frame(device.as_ref())
1688                .expect("the null device writes");
1689        }
1690        assert_eq!(
1691            writes(&recorder),
1692            [],
1693            "a stale re-point marked a slot dirty, so it wrote into whatever took it"
1694        );
1695        for slot in 0..FRAMES {
1696            let dead = on_device(&recorder, &pool, slot, index);
1697            assert_eq!(
1698                (dead.base_vertex, dead.previous_base_vertex),
1699                (40, 41),
1700                "buffer {slot} took a stale handle's bases"
1701            );
1702        }
1703
1704        pool.destroy(device.as_ref());
1705        recorder.assert_valid();
1706    }
1707
1708    /// **Standing still costs one upload per buffer and then nothing.** That is
1709    /// the claim delta upload is here to make, and an unconditional
1710    /// carry-forward would break it — every instance would be dirty in every
1711    /// frame forever.
1712    ///
1713    /// The first assertion is what keeps the second from being vacuous: a
1714    /// carry-forward that never reached the device would also produce no
1715    /// uploads at rest.
1716    #[test]
1717    fn an_instance_at_rest_is_uploaded_once_and_then_never() {
1718        let (recorder, device) = open();
1719        let mut pool = pool(device.as_ref(), 16);
1720        let handle = pool.insert(&instance(7)).expect("room");
1721        settle(&mut pool, device.as_ref());
1722
1723        assert!(pool.set(handle, &instance(11)));
1724        settle(&mut pool, device.as_ref());
1725
1726        // The move has reached every buffer and the last of those frames
1727        // carried it forward, which marked the element dirty everywhere again.
1728        recorder.clear();
1729        pool.begin_frame(device.as_ref())
1730            .expect("the null device writes");
1731        let carried = writes(&recorder).len();
1732        assert_eq!(
1733            carried, 1,
1734            "the buffer that had not seen the carry-forward yet should have taken it, \
1735             and {carried} write(s) says the carry-forward never reached the device"
1736        );
1737
1738        recorder.clear();
1739        for _ in 0..FRAMES * 2 {
1740            pool.begin_frame(device.as_ref())
1741                .expect("the null device writes");
1742        }
1743        assert_eq!(
1744            writes(&recorder),
1745            [],
1746            "an instance nobody has written costs no upload"
1747        );
1748
1749        pool.destroy(device.as_ref());
1750        recorder.assert_valid();
1751    }
1752
1753    /// What goes in comes out, field for field, and a removed handle stops
1754    /// resolving. The four ids are the same width and would permute silently,
1755    /// so the round trip is checked rather than assumed.
1756    #[test]
1757    fn an_instance_round_trips_through_the_pool() {
1758        let (recorder, device) = open();
1759        let mut pool = pool(device.as_ref(), 16);
1760        let handle = pool.insert(&instance(7)).expect("room");
1761        assert_eq!(pool.get(handle), Some(stored(7)));
1762
1763        assert!(pool.set(handle, &instance(11)));
1764        assert_eq!(
1765            pool.get(handle),
1766            Some(stored_after(11, 7)),
1767            "a rewrite keeps where the instance was"
1768        );
1769
1770        assert!(pool.remove(handle));
1771        assert_eq!(
1772            pool.get(handle),
1773            None,
1774            "a removed handle resolves to nothing"
1775        );
1776        assert!(!pool.set(handle, &instance(12)), "and cannot be written");
1777        assert!(!pool.remove(handle), "and cannot be removed twice");
1778
1779        pool.destroy(device.as_ref());
1780        recorder.assert_valid();
1781    }
1782
1783    /// **Removing an instance clears its live bit on the device, and changes
1784    /// nothing else about the record.**
1785    ///
1786    /// The whole slice: a slot the cull pass walks past has to be able to say
1787    /// it is free, and the bit is the only thing a removal is allowed to
1788    /// rewrite. Asserted on the bytes in the buffer rather than on the mirror,
1789    /// because a removal that never reached a buffer is a removal the GPU does
1790    /// not know about.
1791    #[test]
1792    fn removing_an_instance_clears_its_live_bit_on_the_device() {
1793        let (recorder, device) = open();
1794        let mut pool = pool(device.as_ref(), 16);
1795        let first = pool.insert(&instance(1)).expect("room");
1796        let second = pool.insert(&instance(3)).expect("room");
1797        settle(&mut pool, device.as_ref());
1798        for slot in 0..FRAMES {
1799            assert_eq!(
1800                on_device(&recorder, &pool, slot, 0),
1801                stored(1),
1802                "buffer {slot} did not receive the live instance"
1803            );
1804        }
1805
1806        assert!(pool.remove(first));
1807        settle(&mut pool, device.as_ref());
1808        for slot in 0..FRAMES {
1809            let removed = on_device(&recorder, &pool, slot, 0);
1810            assert_eq!(
1811                removed.flags & GpuInstance::LIVE,
1812                0,
1813                "buffer {slot} still holds a live instance at the removed slot: {removed:?}"
1814            );
1815            // And the rest of the record is exactly what it was. The pool
1816            // deliberately does not zero it — see the module docs — so a test
1817            // that only checked the bit would pass on an implementation that
1818            // wrote a degenerate instance at the origin instead.
1819            assert_eq!(
1820                removed,
1821                GpuInstance {
1822                    flags: stored(1).flags & !GpuInstance::LIVE,
1823                    ..stored(1)
1824                },
1825                "buffer {slot} rewrote more than the flags word"
1826            );
1827            assert_eq!(
1828                on_device(&recorder, &pool, slot, 1),
1829                stored(3),
1830                "buffer {slot} disturbed the instance beside the removed one"
1831            );
1832        }
1833
1834        assert_eq!(
1835            pool.get(second),
1836            Some(stored(3)),
1837            "and the other handle still resolves"
1838        );
1839
1840        // A second removal of the retired handle writes nothing at all, so a
1841        // caller cannot clear the live bit of whatever has since taken the slot.
1842        let before = writes(&recorder).len();
1843        assert!(!pool.remove(first));
1844        settle(&mut pool, device.as_ref());
1845        assert_eq!(
1846            writes(&recorder).len(),
1847            before,
1848            "removing a retired handle must upload nothing"
1849        );
1850
1851        pool.destroy(device.as_ref());
1852        recorder.assert_valid();
1853    }
1854
1855    /// **A slot reused after a removal is live again, holding its new
1856    /// contents.** The other direction of the same defect: a liveness bit that
1857    /// stuck would make the pool leak capacity that looks allocated and draws
1858    /// nothing.
1859    #[test]
1860    fn a_reused_slot_is_live_again_with_its_new_contents() {
1861        let (recorder, device) = open();
1862        let mut pool = pool(device.as_ref(), 16);
1863        let first = pool.insert(&instance(1)).expect("room");
1864        assert!(pool.remove(first));
1865        settle(&mut pool, device.as_ref());
1866
1867        let reused = pool.insert(&instance(5)).expect("the freed slot");
1868        assert_eq!(pool.index(reused), Some(0), "the low slot comes back");
1869        settle(&mut pool, device.as_ref());
1870        for slot in 0..FRAMES {
1871            assert_eq!(
1872                on_device(&recorder, &pool, slot, 0),
1873                stored(5),
1874                "buffer {slot} holds neither the new instance nor the live bit"
1875            );
1876        }
1877        assert_eq!(pool.get(reused), Some(stored(5)));
1878
1879        pool.destroy(device.as_ref());
1880        recorder.assert_valid();
1881    }
1882
1883    /// The bytes that reach the device are the instance's, at the offset its
1884    /// index names — checked by writing a high slot and reading back the offset
1885    /// the seam was given. An off-by-one in the element/byte conversion would
1886    /// put every instance one slot out and still upload the right number of
1887    /// bytes.
1888    #[test]
1889    fn an_instances_offset_is_its_index_times_the_stride() {
1890        let (recorder, device) = open();
1891        let mut pool = pool(device.as_ref(), 16);
1892        for n in 0..5 {
1893            pool.insert(&instance(n)).expect("room");
1894        }
1895        settle(&mut pool, device.as_ref());
1896        let handle = pool.insert(&instance(5)).expect("room");
1897        assert_eq!(pool.index(handle), Some(5));
1898
1899        let before = writes(&recorder).len();
1900        pool.begin_frame(device.as_ref()).expect("writes");
1901        assert_eq!(
1902            writes(&recorder)[before..],
1903            [(5 * INSTANCE_STRIDE as u64, INSTANCE_STRIDE)]
1904        );
1905
1906        pool.destroy(device.as_ref());
1907        recorder.assert_valid();
1908    }
1909
1910    /// Everything created is destroyed.
1911    #[test]
1912    fn a_pool_leaks_nothing() {
1913        let (recorder, device) = open();
1914        let before = recorder.total_live_objects();
1915        let mut pool = pool(device.as_ref(), 16);
1916        pool.insert(&instance(0)).expect("room");
1917        settle(&mut pool, device.as_ref());
1918        assert!(recorder.total_live_objects() > before);
1919
1920        pool.destroy(device.as_ref());
1921        assert_eq!(
1922            recorder.total_live_objects(),
1923            before,
1924            "every buffer created must be destroyed"
1925        );
1926        recorder.assert_valid();
1927    }
1928
1929    /// A pool error that has to travel as a [`HalError`] keeps its message,
1930    /// which is the whole reason the exhaustion error names its numbers.
1931    #[test]
1932    fn a_pool_error_flattens_into_the_seams_without_losing_its_message() {
1933        let full = InstancePoolError::PoolFull {
1934            capacity: 4,
1935            in_use: 4,
1936        };
1937        let message = full.to_string();
1938        assert_eq!(HalError::from(full).to_string(), message);
1939
1940        let hal = InstancePoolError::Hal(HalError::OutOfDeviceMemory);
1941        assert!(
1942            matches!(HalError::from(hal), HalError::OutOfDeviceMemory),
1943            "a HalError must not be stringified on the way through"
1944        );
1945    }
1946}