Skip to main content

crcbl_render/
layers.rs

1//! Parallax layers: which band of the world a sprite is drawn in, and how much
2//! of the camera's motion that band takes.
3//!
4//! ```text
5//!   LayerStack ──push_layer(Parallax)──▶ layer 0 (back) … layer n (front)
6//!        │  push(layer, sprite)              each keeps its own submission order
7//!        │
8//!        └──resolve(camera)──▶ &[Sprite]  back to front, each layer offset by
9//!                                          (1 − factor) × camera
10//!                                              │
11//!                                              ▼
12//!                              SpriteRenderer::begin_frame
13//! ```
14//!
15//! # What a parallax factor means
16//!
17//! **The fraction of the camera's motion the layer takes.** `1.0` is fixed in
18//! the world — it scrolls past at the same rate as everything else in the
19//! simulation. `0.0` is pinned to the camera and never moves on screen, which is
20//! a HUD. `0.5` is a hill that drifts by half as much as the ground in front of
21//! it.
22//!
23//! There is no second matrix and no second pass. A sprite on a layer of factor
24//! `p`, at world position `w`, is submitted at `w + (1 − p) · c` for a camera at
25//! `c`, so the one view-projection the pass already has puts it on screen at
26//! `w − p · c`. At `p = 1` that is `w − c`, the ordinary world position; at
27//! `p = 0` it is `w`, unmoved by the camera. The whole feature is one add per
28//! sprite in [`LayerStack::resolve`], which is why it does not need a
29//! per-layer camera, a second constant buffer, or a pass per layer.
30//!
31//! # This is not Aseprite's `meta.layers`
32//!
33//! `docs/specs/crcbl/pix.md` §9 flags the collision by name and it is worth
34//! repeating where the type lives. Aseprite's `meta.layers` is a **compositing**
35//! layer *inside one sheet* — the art's own stack of paint, which the exporter
36//! has already flattened into the frames by the time anything here sees them. A
37//! [`Layer`] here is a band of the **world**, chosen by the game per drawn
38//! sprite, and two sprites cut from the same sheet routinely belong to different
39//! ones. Nothing reads `meta.layers`; nothing here is derived from it.
40//!
41//! That is also why parallax lives on the *drawn sprite* rather than on
42//! [`Sheet`](crcbl_sprite::Sheet): one pipe sheet serves the foreground pipes
43//! and, at a different factor, the distant ones.
44//!
45//! # Ordering, and slice 3's batching contract
46//!
47//! [`sprite_pass`](crate::sprite_pass) is explicit that **submission order is
48//! the caller's** and that nothing sorts behind their back — `A B A` is three
49//! batches, not two, because grouping the two `A`s would put the second one on
50//! top of `B`. Drawing layers back to front *is* a reordering, so it cannot
51//! happen inside the renderer without breaking that.
52//!
53//! It does not. Two things keep both properties at once:
54//!
55//! * **A layer is a container, not a field on [`Sprite`].** There is nothing to
56//!   sort by, because the sprites of one layer are already contiguous — the
57//!   ordering is structural. Nothing compares two sprites, anywhere.
58//! * **[`LayerStack::resolve`] is the caller's own call**, named, documented as
59//!   the point where the frame's order is decided, and returning the flat slice
60//!   they then hand to [`begin_frame`](crate::SpriteRenderer::begin_frame). A
61//!   caller who wants their own order does not build a `LayerStack` and nothing
62//!   changes for them.
63//!
64//! Within a layer, order is preserved exactly: `resolve` concatenates, it does
65//! not sort. So the batching rule still sees the order it was given, and
66//! `sprite_pass`'s existing order tests are untouched — none of them changed for
67//! this module.
68
69use crate::sprite_pass::Sprite;
70
71/// How much of the camera's motion a layer takes.
72///
73/// `1.0` is fixed in the world, `0.0` is pinned to the camera. Values between
74/// are the usual parallax; values outside are legal and occasionally wanted — a
75/// factor above `1` runs *ahead* of the camera, which is how a foreground
76/// element sweeps past faster than the ground.
77///
78/// ```
79/// use crcbl_render::Parallax;
80/// // A camera 100 units to the right. Each layer keeps the share of that
81/// // movement it did *not* take: the hills drift by half, the HUD by all of it
82/// // (so it does not move on screen), the world by none.
83/// let hills = Parallax::new(0.5).expect("0.5 is finite");
84/// assert_eq!(hills.offset([100.0, 0.0]), [50.0, 0.0]);
85/// assert_eq!(Parallax::CAMERA.offset([100.0, 0.0]), [100.0, 0.0]);
86/// assert_eq!(Parallax::WORLD.offset([100.0, 0.0]), [0.0, 0.0]);
87/// ```
88///
89/// Deliberately **not** `PartialOrd`: a layer's depth is where it sits in its
90/// [`LayerStack`], not how much parallax it takes, and the two disagree the
91/// moment a HUD is added.
92#[derive(Clone, Copy, Debug, PartialEq)]
93pub struct Parallax(f32);
94
95impl Parallax {
96    /// Fixed in the world: the layer the simulation actually happens on.
97    pub const WORLD: Self = Self(1.0);
98
99    /// Pinned to the camera, so it never moves on screen — a HUD.
100    pub const CAMERA: Self = Self(0.0);
101
102    /// A factor of `factor`.
103    ///
104    /// `None` for anything not finite. A `NaN` factor would put every sprite on
105    /// the layer at a `NaN` world position, which draws nothing at all and looks
106    /// exactly like a renderer that stopped working; refusing it here is one
107    /// branch, at the only point where a computed factor enters the system.
108    #[must_use]
109    pub fn new(factor: f32) -> Option<Self> {
110        factor.is_finite().then_some(Self(factor))
111    }
112
113    /// The factor itself.
114    #[must_use]
115    pub const fn factor(self) -> f32 {
116        self.0
117    }
118
119    /// How far this layer's contents shift for a camera at `camera`.
120    ///
121    /// `(1 − factor) × camera`, which is the whole of parallax — see this
122    /// module's docs for why that is the value that makes one view-projection
123    /// enough.
124    #[must_use]
125    pub fn offset(self, camera: [f32; 2]) -> [f32; 2] {
126        let take = 1.0 - self.0;
127        [take * camera[0], take * camera[1]]
128    }
129}
130
131impl Default for Parallax {
132    /// [`Parallax::WORLD`]: a layer nobody said anything about is part of the
133    /// world, which is the answer that makes an unconfigured stack behave like
134    /// no stack at all.
135    fn default() -> Self {
136        Self::WORLD
137    }
138}
139
140/// A layer's place in a [`LayerStack`]: `0` is the **backmost**.
141///
142/// Opaque and per-stack, for [`SheetId`](crate::SheetId)'s reason: an index from
143/// one stack means nothing in another.
144#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
145pub struct Layer(usize);
146
147impl Layer {
148    /// The depth this layer sits at, `0` being the back. For tests and
149    /// diagnostics.
150    #[must_use]
151    pub const fn depth(self) -> usize {
152        self.0
153    }
154}
155
156/// One layer's parallax factor and the sprites pushed onto it, in order.
157#[derive(Clone, Debug, Default)]
158struct Band {
159    parallax: Parallax,
160    sprites: Vec<Sprite>,
161}
162
163/// A frame's sprites, grouped into parallax layers and drawn back to front.
164///
165/// Built once and reused: [`LayerStack::clear`] empties the sprites and keeps
166/// the layers and their `Vec`s, so a steady-state frame allocates nothing — the
167/// same discipline [`SpriteRenderer`](crate::SpriteRenderer)'s instance ring
168/// follows.
169///
170/// ```
171/// use crcbl_hal::null::NullInstance;
172/// use crcbl_hal::{DeviceDesc, Format, Instance, QueueKind};
173/// use crcbl_render::{LayerStack, Parallax, SheetDesc, Sprite, SpriteRenderer};
174///
175/// # let instance = NullInstance::gpu_driven();
176/// # let adapter = instance.adapters().remove(0);
177/// # let device = instance.create_device(&DeviceDesc::for_adapter(adapter.id))?;
178/// # let queue = device.queue(QueueKind::Graphics).expect("always present");
179/// # let mut renderer =
180/// #     SpriteRenderer::new(device.as_ref(), queue, Format::Bgra8UnormSrgb)?;
181/// # let sheet = renderer.register_sheet(device.as_ref(), &SheetDesc {
182/// #     label: "art", width: 1, height: 1,
183/// #     sample: crcbl_render::SampleMode::Pixel, pixels: &[255; 4],
184/// # })?;
185/// # let sprite =
186/// #     |x: f32| Sprite::new(sheet, [x, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0]);
187/// let mut stack = LayerStack::new();
188/// let hills = stack.push_layer(Parallax::new(0.5).expect("finite"));
189/// let ground = stack.push_layer(Parallax::WORLD);
190/// let hud = stack.push_layer(Parallax::CAMERA);
191///
192/// // Submitted in whatever order the game finds them; the layer decides depth.
193/// stack.push(ground, sprite(0.0));
194/// stack.push(hills, sprite(0.0));
195/// stack.push(hud, sprite(0.0));
196///
197/// // The camera has moved 100 units right.
198/// let frame = stack.resolve([100.0, 0.0]);
199/// // Back to front: hills, then ground, then the HUD.
200/// assert_eq!(frame[0].rect[0], 50.0, "the hills took half the camera");
201/// assert_eq!(frame[1].rect[0], 0.0, "the ground is where the world put it");
202/// assert_eq!(frame[2].rect[0], 100.0, "the HUD follows the camera exactly");
203/// # renderer.destroy(device.as_ref());
204/// # Ok::<(), Box<dyn std::error::Error>>(())
205/// ```
206#[derive(Clone, Debug, Default)]
207pub struct LayerStack {
208    bands: Vec<Band>,
209    /// The flattened frame [`LayerStack::resolve`] hands out, kept between
210    /// frames so its capacity is reused.
211    flat: Vec<Sprite>,
212}
213
214impl LayerStack {
215    /// An empty stack with no layers.
216    #[must_use]
217    pub fn new() -> Self {
218        Self::default()
219    }
220
221    /// Adds a layer **in front of** every layer already added, and returns it.
222    ///
223    /// Depth is the order layers are added, not a number the caller invents:
224    /// there is no way to write two layers at the same depth, and no comparison
225    /// anywhere that could tie.
226    pub fn push_layer(&mut self, parallax: Parallax) -> Layer {
227        self.bands.push(Band {
228            parallax,
229            sprites: Vec::new(),
230        });
231        Layer(self.bands.len() - 1)
232    }
233
234    /// How many layers the stack has.
235    #[must_use]
236    pub fn layer_count(&self) -> usize {
237        self.bands.len()
238    }
239
240    /// `layer`'s parallax factor.
241    ///
242    /// # Panics
243    ///
244    /// If `layer` came from a different stack — the same contract as indexing a
245    /// [`Vec`], and for the same reason: a silently ignored push would lose
246    /// sprites rather than report anything.
247    #[must_use]
248    pub fn parallax(&self, layer: Layer) -> Parallax {
249        self.band(layer).parallax
250    }
251
252    /// The sprites pushed onto `layer` so far, in submission order and **before**
253    /// parallax is applied.
254    ///
255    /// # Panics
256    ///
257    /// If `layer` came from a different stack.
258    #[must_use]
259    pub fn sprites(&self, layer: Layer) -> &[Sprite] {
260        &self.band(layer).sprites
261    }
262
263    /// Adds one sprite to the front of `layer`'s own order.
264    ///
265    /// # Panics
266    ///
267    /// If `layer` came from a different stack.
268    pub fn push(&mut self, layer: Layer, sprite: Sprite) {
269        self.band_mut(layer).sprites.push(sprite);
270    }
271
272    /// Adds several, keeping their order — [`NineQuads::sprites`] feeds straight
273    /// into this.
274    ///
275    /// [`NineQuads::sprites`]: crate::nine_slice::NineQuads::sprites
276    ///
277    /// # Panics
278    ///
279    /// If `layer` came from a different stack.
280    pub fn extend(&mut self, layer: Layer, sprites: impl IntoIterator<Item = Sprite>) {
281        self.band_mut(layer).sprites.extend(sprites);
282    }
283
284    /// Empties every layer, keeping the layers themselves and their capacity.
285    ///
286    /// The per-frame call. [`LayerStack::push_layer`] is startup work — a stack
287    /// rebuilt every frame would hand out fresh [`Layer`]s a game then has to
288    /// store somewhere anyway.
289    pub fn clear(&mut self) {
290        for band in &mut self.bands {
291            band.sprites.clear();
292        }
293        self.flat.clear();
294    }
295
296    /// How many sprites are in the stack across all layers.
297    #[must_use]
298    pub fn sprite_count(&self) -> usize {
299        self.bands.iter().map(|band| band.sprites.len()).sum()
300    }
301
302    /// **Flattens the stack into one frame's submission order.** Back layer
303    /// first, each layer's sprites offset by its share of `camera`.
304    ///
305    /// `camera` is the camera's world position on the sprite plane —
306    /// `[camera.eye.x, camera.eye.y]` for the [`Camera`](crate::Camera) the same
307    /// frame's `view_projection` came from. Passing a different one silently
308    /// desynchronises the parallax from the projection; there is no way for this
309    /// to check that, which is why it takes the position rather than pretending
310    /// to derive it.
311    ///
312    /// **This is the reordering, and it is the caller's.**
313    /// [`sprite_pass`](crate::sprite_pass) never sorts; this does, once, where
314    /// the caller can see it. Within a layer nothing moves: the result is the
315    /// layers concatenated in depth order, each in its own push order, so the
316    /// batching rule downstream still sees exactly the order it was handed.
317    pub fn resolve(&mut self, camera: [f32; 2]) -> &[Sprite] {
318        let total = self.sprite_count();
319        self.flat.clear();
320        self.flat.reserve(total);
321        for band in &self.bands {
322            let [dx, dy] = band.parallax.offset(camera);
323            self.flat.extend(band.sprites.iter().map(|sprite| {
324                let mut moved = *sprite;
325                moved.rect[0] += dx;
326                moved.rect[1] += dy;
327                moved
328            }));
329        }
330        &self.flat
331    }
332
333    /// The frame [`LayerStack::resolve`] last produced.
334    #[must_use]
335    pub fn resolved(&self) -> &[Sprite] {
336        &self.flat
337    }
338
339    fn band(&self, layer: Layer) -> &Band {
340        self.bands
341            .get(layer.0)
342            .unwrap_or_else(|| panic!("layer {} is not in this stack", layer.0))
343    }
344
345    fn band_mut(&mut self, layer: Layer) -> &mut Band {
346        let count = self.bands.len();
347        self.bands
348            .get_mut(layer.0)
349            .unwrap_or_else(|| panic!("layer {} is not in a stack of {count}", layer.0))
350    }
351}
352
353#[cfg(test)]
354mod tests {
355    use super::*;
356    use crate::sprite_pass::SheetId;
357
358    fn sprite(sheet: SheetId, position: [f32; 2]) -> Sprite {
359        Sprite::new(
360            sheet,
361            [position[0], position[1], 4.0, 4.0],
362            [0.0, 0.0, 1.0, 1.0],
363        )
364    }
365
366    /// Where a sprite lands **on screen** for a camera at `camera`: the
367    /// submitted world position minus the camera, which is what the
368    /// view-projection does.
369    fn screen(sprite: &Sprite, camera: [f32; 2]) -> [f32; 2] {
370        [sprite.rect[0] - camera[0], sprite.rect[1] - camera[1]]
371    }
372
373    /// **The parallax claim, measured.** For a given camera movement, a layer at
374    /// factor 0.5 moves half as far on screen as the world does, and a layer at
375    /// 0 does not move at all.
376    ///
377    /// Asserted on the *change* between two camera positions rather than on one
378    /// frame's numbers, because that is what parallax is — a frame's absolute
379    /// offset can be right for the wrong reason.
380    #[test]
381    fn a_half_parallax_layer_moves_half_as_far_as_the_world() {
382        let sheet = SheetId(0);
383        let mut stack = LayerStack::new();
384        let far = stack.push_layer(Parallax::new(0.5).expect("finite"));
385        let world = stack.push_layer(Parallax::WORLD);
386        let hud = stack.push_layer(Parallax::CAMERA);
387        // The *same* world position on all three, so any difference is the
388        // factor and nothing else.
389        for layer in [far, world, hud] {
390            stack.push(layer, sprite(sheet, [10.0, 20.0]));
391        }
392
393        let before: Vec<[f32; 2]> = stack
394            .resolve([0.0, 0.0])
395            .iter()
396            .map(|sprite| screen(sprite, [0.0, 0.0]))
397            .collect();
398        let camera = [100.0f32, -40.0];
399        let after: Vec<[f32; 2]> = stack
400            .resolve(camera)
401            .iter()
402            .map(|sprite| screen(sprite, camera))
403            .collect();
404
405        let moved: Vec<[f32; 2]> = before
406            .iter()
407            .zip(&after)
408            .map(|(a, b)| [b[0] - a[0], b[1] - a[1]])
409            .collect();
410        assert_eq!(
411            moved[1],
412            [-100.0, 40.0],
413            "the world layer moves the whole of the camera, the other way"
414        );
415        assert_eq!(
416            moved[0],
417            [-50.0, 20.0],
418            "and a factor of 0.5 moves exactly half as far"
419        );
420        assert_eq!(
421            moved[2],
422            [0.0, 0.0],
423            "a factor of 0 is pinned to the camera: a HUD does not move at all"
424        );
425
426        // Said the other way round, so a sign error that halved both cannot
427        // pass: half of the world layer's movement, not half of something else.
428        assert_eq!(moved[0][0], moved[1][0] / 2.0);
429        assert_eq!(moved[0][1], moved[1][1] / 2.0);
430        // Anti-vacuity: the world layer really did move.
431        assert_ne!(moved[1], [0.0, 0.0]);
432    }
433
434    /// Resolving is back to front, and **within a layer nothing moves**. That
435    /// second half is the batching contract: `sprite_pass` batches consecutive
436    /// sprites and never reorders, so a stack that shuffled inside a layer would
437    /// silently recompose the frame.
438    #[test]
439    fn resolve_concatenates_back_to_front_and_preserves_each_layers_own_order() {
440        let mut stack = LayerStack::new();
441        let back = stack.push_layer(Parallax::WORLD);
442        let front = stack.push_layer(Parallax::WORLD);
443        assert_eq!((back.depth(), front.depth()), (0, 1));
444        assert_eq!(stack.layer_count(), 2);
445
446        // Distinct x per sprite, and interleaved pushes: a stack that appended
447        // to one flat list would come back in push order rather than layer
448        // order, and one that sorted inside a layer would come back ascending.
449        let sheet = SheetId(0);
450        for (layer, x) in [
451            (front, 3.0),
452            (back, 1.0),
453            (front, 0.0),
454            (back, 2.0),
455            (front, 9.0),
456        ] {
457            stack.push(layer, sprite(sheet, [x, 0.0]));
458        }
459        assert_eq!(stack.sprite_count(), 5);
460
461        let order: Vec<f32> = stack
462            .resolve([0.0, 0.0])
463            .iter()
464            .map(|sprite| sprite.rect[0])
465            .collect();
466        assert_eq!(
467            order,
468            [1.0, 2.0, 3.0, 0.0, 9.0],
469            "the back layer's two sprites first, in push order, then the front \
470             layer's three, in push order — not sorted, and not interleaved"
471        );
472        let kept: Vec<f32> = stack.resolved().iter().map(|s| s.rect[0]).collect();
473        assert_eq!(kept, order, "the frame is kept for re-reading");
474
475        // The per-layer subsequences are exactly what was pushed there.
476        let xs = |layer| {
477            stack
478                .sprites(layer)
479                .iter()
480                .map(|s: &Sprite| s.rect[0])
481                .collect::<Vec<_>>()
482        };
483        assert_eq!(xs(back), [1.0, 2.0]);
484        assert_eq!(xs(front), [3.0, 0.0, 9.0]);
485
486        // And a resolve leaves the layers themselves alone, so a second one with
487        // a different camera starts from the same world positions.
488        let again: Vec<f32> = stack
489            .resolve([10.0, 0.0])
490            .iter()
491            .map(|sprite| sprite.rect[0])
492            .collect();
493        assert_eq!(
494            again,
495            [1.0, 2.0, 3.0, 0.0, 9.0],
496            "a WORLD layer takes no offset, and resolve must not accumulate one"
497        );
498    }
499
500    /// A layer that is neither `WORLD` nor `CAMERA` still leaves the layers
501    /// untouched between frames — the bug an in-place offset would have.
502    #[test]
503    fn resolving_twice_does_not_accumulate_the_offset() {
504        let sheet = SheetId(0);
505        let mut stack = LayerStack::new();
506        let drift = stack.push_layer(Parallax::new(0.25).expect("finite"));
507        stack.push(drift, sprite(sheet, [0.0, 0.0]));
508
509        let first = stack.resolve([80.0, 40.0])[0].rect;
510        let second = stack.resolve([80.0, 40.0])[0].rect;
511        assert_eq!(first, second, "the same camera must give the same frame");
512        assert_eq!(
513            [first[0], first[1]],
514            [60.0, 30.0],
515            "0.75 of the camera, because the layer takes only a quarter of it"
516        );
517        assert_eq!(
518            stack.sprites(drift)[0].rect[0],
519            0.0,
520            "the layer is untouched"
521        );
522    }
523
524    /// `clear` is the per-frame call: the layers and their factors survive and
525    /// the sprites do not, so a game's [`Layer`] handles stay valid for the
526    /// lifetime of the stack rather than for one frame.
527    #[test]
528    fn clear_keeps_the_layers_and_their_ids() {
529        let sheet = SheetId(0);
530        let mut stack = LayerStack::new();
531        let sky = stack.push_layer(Parallax::new(0.2).expect("finite"));
532        let ground = stack.push_layer(Parallax::WORLD);
533        stack.extend(sky, (0..4).map(|i| sprite(sheet, [i as f32, 0.0])));
534        stack.push(ground, sprite(sheet, [0.0, 0.0]));
535        assert_eq!(stack.sprite_count(), 5);
536        let count = stack.sprites(sky).len();
537
538        stack.clear();
539        assert_eq!(stack.sprite_count(), 0);
540        assert_eq!(stack.layer_count(), 2, "the layers survive a clear");
541        assert_eq!(stack.parallax(sky).factor(), 0.2);
542        assert_eq!(stack.parallax(ground), Parallax::WORLD);
543        assert!(stack.resolve([0.0, 0.0]).is_empty());
544
545        // And the ids still address the same layers afterwards.
546        stack.extend(sky, (0..count).map(|i| sprite(sheet, [i as f32, 0.0])));
547        assert_eq!(stack.sprites(sky).len(), count);
548    }
549
550    /// A factor has to be a number. A `NaN` one would put every sprite on the
551    /// layer at a `NaN` position, which draws nothing and looks like a broken
552    /// renderer rather than a bad input.
553    #[test]
554    fn a_parallax_factor_must_be_finite() {
555        assert_eq!(Parallax::new(0.5).map(Parallax::factor), Some(0.5));
556        assert_eq!(Parallax::new(f32::NAN), None);
557        assert_eq!(Parallax::new(f32::INFINITY), None);
558        assert_eq!(Parallax::new(f32::NEG_INFINITY), None);
559        assert_eq!(Parallax::WORLD.factor(), 1.0);
560        assert_eq!(Parallax::CAMERA.factor(), 0.0);
561        assert_eq!(Parallax::default(), Parallax::WORLD);
562
563        // A factor above 1 runs ahead of the camera, and is allowed.
564        let ahead = Parallax::new(2.0).expect("finite");
565        assert_eq!(ahead.offset([10.0, 10.0]), [-10.0, -10.0]);
566        assert_eq!(Parallax::WORLD.offset([10.0, 10.0]), [0.0, 0.0]);
567        assert_eq!(Parallax::CAMERA.offset([10.0, 10.0]), [10.0, 10.0]);
568    }
569
570    /// A [`Layer`] from another stack is a programming error, not something to
571    /// swallow: a silently dropped push loses sprites and reports nothing.
572    #[test]
573    #[should_panic(expected = "layer 0 is not in a stack of 0")]
574    fn pushing_onto_a_layer_from_another_stack_panics() {
575        let sheet = SheetId(0);
576        let mut other = LayerStack::new();
577        let stray = other.push_layer(Parallax::WORLD);
578        LayerStack::new().push(stray, sprite(sheet, [0.0, 0.0]));
579    }
580}