Skip to main content

crcbl_render/shadow/
cadence.rs

1//! Which of the shadow atlas's maps a frame redraws, out of the ones whose
2//! contents have gone out of date.
3//!
4//! Topic 45's cadence rung. [`super::Selection`] decides which
5//! lights hold tiles and how large each tile is; [`crate::forward`] decides
6//! which of those maps the image no longer holds. What is left is the question
7//! this module answers: **a frame that would have to redraw everything redraws
8//! some of it now and the rest on a later frame**, so a scene where every light
9//! moves at once cannot spike a frame with a whole geometry pass per map.
10//!
11//! # A group, not a tile
12//!
13//! The unit is what the renderer draws together: a cascade, or a light slot's
14//! whole run of tiles. A point light's [`super::POINT_FACES`] faces cull once
15//! against the light's sphere and draw that one visible set through six
16//! matrices, so redrawing three of them and holding three is not a saving —
17//! it is the same cull and the same six visible sets with half the draws. There
18//! are [`GROUPS`] of them, and [`Group::faces`] is what each costs in tiles.
19//!
20//! # Keyed to the frame index, and to nothing else
21//!
22//! [`Cadence::schedule`] is a pure function of the frame index, the groups that
23//! want redrawing and the two limits. No clock, no iteration order and no
24//! address is in it, so a golden blessed at a stated frame is the same golden on
25//! every run, every driver and every backend — which is the property the plan
26//! asks for by name and the one this whole rung would be worthless without.
27//!
28//! # The ladder is the one the tile size already walks
29//!
30//! A group's [`Group::tier`] is the quadtree level `super::tile_level` gave
31//! its light — or, for a cascade, which cascade it is. There is deliberately no
32//! second measure of how much a light matters: `super::coverage` decides the
33//! ranking and the tile size, and the tier is read off the answer it already
34//! gave. A map worth a whole root cell is redrawn every frame, one worth a
35//! quarter of a cell every second frame, and each halving below that doubles the
36//! period again.
37//!
38//! # What it costs, and why it ships off
39//!
40//! A held map is a map drawn for where its light and the camera *were*. The
41//! shadow lags by up to its period, which on a still or slowly-moving light is
42//! invisible and on a fast one is a shadow trailing its caster. That is a
43//! quality decision per tier rather than a fact about the engine, so
44//! [`r_shadow_cadence`] and [`r_shadow_faces`] both default to what ships
45//! today — every map that needs redrawing is redrawn, in the frame it went out
46//! of date — and a frame nobody has touched the console on is the frame every
47//! golden was blessed at.
48
49use super::{CASCADES, LIGHT_SLOTS, TILE_LEVELS, TILES};
50
51/// Groups the shadow atlas is drawn in: one per cascade and one per light slot.
52///
53/// [`super::CASCADES`] then [`super::LIGHT_SLOTS`], which is the order
54/// `crate::forward`'s shadow culls are indexed in — a group *is* a cull, and the
55/// two would have to agree even if this were written twice.
56pub const GROUPS: usize = CASCADES + LIGHT_SLOTS;
57
58/// The coarsest tier any group can be on, which is the ladder's own length.
59///
60/// A light's tier is its quadtree level and a cascade's is its index, so this is
61/// the larger of the two ladders — and `Cadence::period` clamps to it so a
62/// tier arriving from outside cannot shift a period past what a `u32` holds.
63const TIERS: usize = if TILE_LEVELS > CASCADES {
64    TILE_LEVELS
65} else {
66    CASCADES
67};
68
69crcbl_console::convar! {
70    /// Frames a shadow map may be held for before it is redrawn: 1 ships.
71    pub static r_shadow_cadence: i64 in 1 ..= 8 = 1;
72}
73
74crcbl_console::convar! {
75    /// Shadow maps a frame may redraw: the whole atlas ships.
76    pub static r_shadow_faces: i64 in 1 ..= 16 = 16;
77}
78
79const _: () = assert!(
80    TILES == 16,
81    "r_shadow_faces' range is the atlas's tile count spelled out, because a \
82     console variable's bounds are part of its declaration and cannot be an \
83     expression; an atlas of a different size needs that literal moved with it"
84);
85
86/// One group of the atlas that wants redrawing, and what redrawing it costs.
87#[derive(Clone, Copy, Debug, PartialEq, Eq)]
88pub struct Group {
89    /// Tiles the group draws: one for a cascade, and
90    /// [`super::tile_span`] of its light for a light slot.
91    ///
92    /// What [`r_shadow_faces`] is spent in, and the reason the budget is a count
93    /// of *faces* rather than of groups: a point light's cube is
94    /// [`super::POINT_FACES`] whole geometry passes and a spot's cone is one.
95    pub faces: usize,
96    /// Which rung of the ladder this group sits on — 0 is redrawn every frame,
97    /// and each rung below doubles the period.
98    ///
99    /// A light's is the quadtree level [`super::Assignment::level`] holds, so
100    /// `super::coverage` decides it exactly as it decides the tile's size. A
101    /// cascade's is its own index: the near cascade fills most of the screen and
102    /// is fitted to the eye every frame, and the far ones cover ground a texel
103    /// of which is metres across.
104    pub tier: usize,
105    /// Whether the map the image holds for this group describes a region that
106    /// has since moved out from under it, rather than merely being out of date.
107    ///
108    /// **The reset the plan asks for, per group.** A light that jumped further
109    /// than its own radius, or a cascade whose eye moved further than the
110    /// cascade's own sphere reaches, holds texels about somewhere else — which
111    /// is worse than a shadow that lags, and is what makes this bypass the
112    /// period. It does **not** bypass [`Cadence::faces`]: a frame that redrew
113    /// past its budget would have no budget. Forced groups are offered it
114    /// first, and one that still does not fit holds another frame.
115    pub forced: bool,
116}
117
118/// The two limits a frame's redraws are spent under.
119///
120/// Read off the console with [`Cadence::from_console`] once a frame, so the
121/// value cannot move between the decision and the pass that acts on it — which
122/// is the same freeze `crate::forward` gives its render effects and for the same
123/// reason.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub struct Cadence {
126    /// The longest any group may go unredrawn, in frames — [`r_shadow_cadence`].
127    ///
128    /// One is the whole ladder switched off: every period clamps to one, every
129    /// group that wants redrawing is due, and the schedule is what shipped
130    /// before this module existed.
131    pub hold: u32,
132    /// Tiles a frame may redraw — [`r_shadow_faces`].
133    pub faces: usize,
134}
135
136impl Cadence {
137    /// Every group that wants redrawing gets it, this frame.
138    ///
139    /// What the console's defaults resolve to, and what `crate::forward` passes
140    /// on a frame that has reset — see [`Cadence::schedule`]'s note on a map
141    /// whose own region has moved.
142    pub const EVERY_FRAME: Self = Self {
143        hold: 1,
144        faces: TILES,
145    };
146
147    /// The pair as the console holds them.
148    ///
149    /// Clamped through the variables' own ranges rather than trusted, on
150    /// `crate::ssao::slice_count`'s terms: the range is the console's guard and
151    /// this is the one that holds if a range ever moves.
152    #[must_use]
153    pub fn from_console() -> Self {
154        let hold = r_shadow_cadence.get_i64().clamp(1, 8);
155        let faces = r_shadow_faces.get_i64().clamp(1, TILES as i64);
156        Self {
157            hold: u32::try_from(hold).unwrap_or(1),
158            faces: usize::try_from(faces).unwrap_or(TILES),
159        }
160    }
161
162    /// How many frames apart two redraws of a group on `tier` are.
163    ///
164    /// The ladder doubles per rung and [`Cadence::hold`] caps it, so a hold of
165    /// one is every group every frame and a hold of four lets the two coarsest
166    /// rungs share a period.
167    fn period(self, tier: usize) -> u32 {
168        let tier = tier.min(TIERS - 1);
169        let rung = 1u32 << tier;
170        rung.min(self.hold.max(1))
171    }
172
173    /// Which of `wanted`'s groups this frame redraws.
174    ///
175    /// `wanted[group]` is [`Some`] where the image no longer holds what the
176    /// frame would draw into that group, and [`None`] where it does — a free
177    /// slot, a frame with shadows off, or a map whose inputs have not moved
178    /// since it was drawn. So this decides *when* an out-of-date map is
179    /// redrawn and never whether an up-to-date one is.
180    ///
181    /// # Two gates, in this order
182    ///
183    /// * **The cadence.** A group is due on the frames where
184    ///   `(frame + group) % period` is zero. The group index is in the modulus
185    ///   so two groups on one tier fall on different frames rather than
186    ///   arriving together — which is what makes the budget below reachable
187    ///   rather than a cliff every period.
188    /// * **The budget.** The due groups are admitted until [`Cadence::faces`]
189    ///   tiles are spoken for. A group that does not fit is skipped and the walk
190    ///   continues, so a cascade behind a point light's cube is still redrawn —
191    ///   the same rule [`super::Selection::update`] follows when a run of tiles
192    ///   will not fit, and for the same reason. A frame that admitted **nothing**
193    ///   takes the first candidate anyway: a budget smaller than one map is not
194    ///   a budget, it is a map nothing ever draws.
195    ///
196    /// # The tier decides how often a map asks, not who is served
197    ///
198    /// The budget is spent in the group index **rotated by the frame** and in
199    /// nothing else — deliberately not in tier order, which would starve every
200    /// coarse map outright: a tier-0 group is due on every frame, so a budget
201    /// that served tiers in order would be spent before a tier-1 group was ever
202    /// reached, for ever. Rotating instead serves the due groups round-robin,
203    /// and the ladder still comes out of it — a group due twice as often asks
204    /// twice as often and is served twice as often.
205    ///
206    /// # A group that is stale wins nothing over one that is due
207    ///
208    /// Cadence is the outer gate and staleness the inner one: a group whose
209    /// inputs moved but whose turn has not come **holds the texels it has** and
210    /// is redrawn on its turn. The alternative — staleness overriding the
211    /// cadence — is a schedule that binds only while nothing moves, which is
212    /// the case that never needed bounding.
213    ///
214    /// What that leaves is a map drawn for a region that has since moved out
215    /// from under it, which is worse than a lagging shadow — and that is
216    /// [`Group::forced`], which bypasses the period and takes the budget first.
217    /// A frame whose whole atlas was relaid has nothing to hold at all, and
218    /// `crate::forward` passes [`Cadence::EVERY_FRAME`] there rather than
219    /// making it a case here.
220    #[must_use]
221    pub fn schedule(self, frame: u64, wanted: &[Option<Group>; GROUPS]) -> [bool; GROUPS] {
222        // Which groups are due, and in what order they are offered the budget.
223        // An array rather than a `Vec`: the count is bounded by the atlas's own
224        // groups and this runs every frame.
225        let mut due = [(0usize, 0usize, 0usize); GROUPS];
226        let mut count = 0;
227        for (group, want) in wanted.iter().enumerate() {
228            let Some(want) = want else {
229                continue;
230            };
231            let period = u64::from(self.period(want.tier));
232            if !want.forced && !(frame + group as u64).is_multiple_of(period) {
233                continue;
234            }
235            // Forced first, then round-robin — so a map about somewhere else is
236            // redrawn before one that is merely a frame old, and no group holds
237            // a fixed place in the order.
238            let rotated = (group + (frame % GROUPS as u64) as usize) % GROUPS;
239            due[count] = (usize::from(!want.forced), rotated, group);
240            count += 1;
241        }
242        due[..count].sort_unstable();
243
244        let mut redraw = [false; GROUPS];
245        let mut spent = 0;
246        for &(_, _, group) in &due[..count] {
247            let faces = wanted[group].map_or(0, |want| want.faces);
248            if spent + faces > self.faces {
249                continue;
250            }
251            spent += faces;
252            redraw[group] = true;
253        }
254        // A budget smaller than every map that is asking would draw none of
255        // them, on this frame and on every frame after. The first in the order
256        // goes through instead, so a frame always makes progress and the
257        // overshoot is one map.
258        if spent == 0
259            && let Some(&(_, _, group)) = due[..count].first()
260        {
261            redraw[group] = true;
262        }
263        redraw
264    }
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::shadow::POINT_FACES;
271
272    /// `wanted` with every group asking for one tile on `tier`.
273    fn all_on(tier: usize) -> [Option<Group>; GROUPS] {
274        [Some(Group {
275            faces: 1,
276            tier,
277            forced: false,
278        }); GROUPS]
279    }
280
281    /// **The shipped defaults redraw everything that asks**, which is what makes
282    /// every golden in the tree the frame it was blessed from: the cadence is a
283    /// feature a console turns on, not a change to the frame.
284    #[test]
285    fn the_shipped_limits_redraw_every_group_that_wants_it() {
286        // The **declared** defaults rather than the live values: a console
287        // variable is process-global, so a test holding one would otherwise
288        // decide what this one is about.
289        let cadence = Cadence {
290            hold: match r_shadow_cadence.default() {
291                crcbl_console::Value::Int(hold) => u32::try_from(*hold).expect("a small count"),
292                other => panic!("`r_shadow_cadence` is declared as {other:?}"),
293            },
294            faces: match r_shadow_faces.default() {
295                crcbl_console::Value::Int(faces) => usize::try_from(*faces).expect("a small count"),
296                other => panic!("`r_shadow_faces` is declared as {other:?}"),
297            },
298        };
299        assert_eq!(
300            cadence,
301            Cadence::EVERY_FRAME,
302            "the console's defaults are the schedule that shipped"
303        );
304        for frame in 0..8 {
305            for tier in 0..TIERS {
306                assert_eq!(
307                    cadence.schedule(frame, &all_on(tier)),
308                    [true; GROUPS],
309                    "frame {frame}, tier {tier}"
310                );
311            }
312        }
313    }
314
315    /// **The console reaches the schedule**, which is the half
316    /// [`the_shipped_limits_redraw_every_group_that_wants_it`] cannot see:
317    /// reading the declarations proves what shipped and nothing about the
318    /// variables being wired to anything.
319    ///
320    /// [`crate::forward::ForwardRenderer::set_shadow_cadence`] is what every
321    /// test that draws a frame uses instead, and this is why it exists: these
322    /// variables are process-global and the shadow pass is in every frame's
323    /// pass list, so a test that moved them while drawing would change the frame
324    /// every other test in this crate draws. Nothing is drawn here.
325    #[test]
326    fn the_console_moves_both_limits() {
327        let _guard = CONSOLE
328            .lock()
329            .unwrap_or_else(std::sync::PoisonError::into_inner);
330        r_shadow_cadence
331            .set(&crcbl_console::Value::Int(4))
332            .expect("`r_shadow_cadence` is a writable int in range");
333        r_shadow_faces
334            .set(&crcbl_console::Value::Int(3))
335            .expect("`r_shadow_faces` is a writable int in range");
336        let moved = Cadence::from_console();
337        r_shadow_cadence
338            .set(r_shadow_cadence.default())
339            .expect("back to what it was declared holding");
340        r_shadow_faces
341            .set(r_shadow_faces.default())
342            .expect("back to what it was declared holding");
343        assert_eq!(moved, Cadence { hold: 4, faces: 3 });
344        assert_eq!(
345            Cadence::from_console(),
346            Cadence::EVERY_FRAME,
347            "and the restore above put the process back where it found it"
348        );
349    }
350
351    /// [`the_console_moves_both_limits`]' lock, so the cadence's own tests do
352    /// not read a variable another of them is holding.
353    static CONSOLE: std::sync::Mutex<()> = std::sync::Mutex::new(());
354
355    /// A group that wants nothing is never redrawn, whatever the frame — the
356    /// cadence decides *when* an out-of-date map is redrawn and never whether an
357    /// up-to-date one is.
358    #[test]
359    fn a_group_that_wants_nothing_is_never_redrawn() {
360        let cadence = Cadence {
361            hold: 8,
362            faces: TILES,
363        };
364        let mut wanted = all_on(0);
365        wanted[2] = None;
366        for frame in 0..16 {
367            assert!(
368                !cadence.schedule(frame, &wanted)[2],
369                "frame {frame} redrew a group that holds what it should"
370            );
371        }
372    }
373
374    /// **The ladder is a doubling**, and the tier is what walks it: a tier-1
375    /// group is redrawn on half the frames a tier-0 one is, a tier-2 group on a
376    /// quarter of them.
377    #[test]
378    fn each_rung_of_the_ladder_halves_how_often_a_group_is_redrawn() {
379        let cadence = Cadence {
380            hold: 8,
381            faces: TILES,
382        };
383        const FRAMES: u64 = 64;
384        let counts: Vec<usize> = (0..TIERS)
385            .map(|tier| {
386                (0..FRAMES)
387                    .filter(|frame| cadence.schedule(*frame, &all_on(tier))[0])
388                    .count()
389            })
390            .collect();
391        for (tier, drawn) in counts.iter().enumerate() {
392            let expected = FRAMES as usize >> tier;
393            assert_eq!(
394                *drawn, expected,
395                "tier {tier} was redrawn {drawn} times in {FRAMES} frames"
396            );
397        }
398    }
399
400    /// **[`Cadence::hold`] caps the ladder**, so the coarsest tiers share a
401    /// period rather than disappearing for eight frames at a time.
402    #[test]
403    fn the_hold_caps_the_period_the_ladder_asks_for() {
404        let cadence = Cadence {
405            hold: 2,
406            faces: TILES,
407        };
408        for tier in 1..TIERS {
409            assert_eq!(cadence.period(tier), 2, "tier {tier}");
410        }
411        assert_eq!(cadence.period(0), 1, "the top of the ladder is every frame");
412    }
413
414    /// **The budget is spent in tiles**, so a point light's cube costs six of it
415    /// and a cascade one.
416    #[test]
417    fn a_frame_never_redraws_more_tiles_than_the_budget() {
418        let cadence = Cadence { hold: 1, faces: 7 };
419        let mut wanted = [None; GROUPS];
420        wanted[0] = Some(Group {
421            faces: 1,
422            tier: 0,
423            forced: false,
424        });
425        wanted[1] = Some(Group {
426            faces: 1,
427            tier: 0,
428            forced: false,
429        });
430        wanted[2] = Some(Group {
431            faces: 6,
432            tier: 0,
433            forced: false,
434        });
435        wanted[3] = Some(Group {
436            faces: 6,
437            tier: 0,
438            forced: false,
439        });
440        for frame in 0..8 {
441            let redraw = cadence.schedule(frame, &wanted);
442            let spent: usize = redraw
443                .iter()
444                .enumerate()
445                .filter(|(_, drawn)| **drawn)
446                .filter_map(|(group, _)| wanted[group])
447                .map(|want| want.faces)
448                .sum();
449            assert!(spent <= 7, "frame {frame} redrew {spent} tiles");
450        }
451    }
452
453    /// **A group the budget refuses is not the end of the walk**: a cascade
454    /// behind a cube that will not fit is still redrawn, which is
455    /// `super::super::Selection::update`'s rule at this boundary.
456    #[test]
457    fn a_group_the_budget_refuses_does_not_take_the_ones_behind_it_with_it() {
458        let cadence = Cadence { hold: 1, faces: 2 };
459        let mut wanted = [None; GROUPS];
460        wanted[0] = Some(Group {
461            faces: 6,
462            tier: 0,
463            forced: false,
464        });
465        wanted[1] = Some(Group {
466            faces: 1,
467            tier: 0,
468            forced: false,
469        });
470        wanted[2] = Some(Group {
471            faces: 1,
472            tier: 0,
473            forced: false,
474        });
475        let redraw = cadence.schedule(0, &wanted);
476        assert!(!redraw[0], "six tiles do not fit in a budget of two");
477        assert!(
478            redraw[1] && redraw[2],
479            "the two that do fit were refused with it: {redraw:?}"
480        );
481    }
482
483    /// **A budget too small for any map still draws one.** A frame that admitted
484    /// nothing would admit nothing on the next frame too, and the map would be a
485    /// tile the atlas never redraws — which is not a budget, it is a light that
486    /// is silently unshadowed for ever.
487    #[test]
488    fn a_budget_smaller_than_every_map_still_draws_one_of_them() {
489        let cadence = Cadence { hold: 1, faces: 1 };
490        let mut wanted = [None; GROUPS];
491        wanted[0] = Some(Group {
492            faces: POINT_FACES,
493            tier: 0,
494            forced: false,
495        });
496        wanted[3] = Some(Group {
497            faces: POINT_FACES,
498            tier: 0,
499            forced: false,
500        });
501        for frame in 0..8 {
502            let redraw = cadence.schedule(frame, &wanted);
503            assert_eq!(
504                redraw.iter().filter(|drawn| **drawn).count(),
505                1,
506                "frame {frame} drew {redraw:?} against a budget no cube fits in"
507            );
508        }
509    }
510
511    /// **Nothing starves while the budget binds.** Every group that keeps asking
512    /// is redrawn inside a bounded run of frames, which is what the rotation in
513    /// the tie-break buys: without it the same groups would win every frame and
514    /// the rest would never be drawn at all.
515    #[test]
516    fn every_group_that_keeps_asking_is_redrawn_within_a_bounded_run() {
517        let cadence = Cadence { hold: 1, faces: 2 };
518        let wanted = all_on(0);
519        let mut last = [None; GROUPS];
520        for frame in 0..64u64 {
521            for (group, drawn) in cadence.schedule(frame, &wanted).iter().enumerate() {
522                if *drawn {
523                    last[group] = Some(frame);
524                }
525            }
526        }
527        for (group, seen) in last.iter().enumerate() {
528            let seen = seen.unwrap_or_else(|| panic!("group {group} was never redrawn"));
529            assert!(
530                seen + u64::try_from(GROUPS).expect("a handful of groups") >= 63,
531                "group {group} was last redrawn at frame {seen} of 63"
532            );
533        }
534    }
535
536    /// **A forced group bypasses the period**, which is the reset: a map about
537    /// somewhere else is redrawn on the frame that notices rather than on the
538    /// frame its turn comes round.
539    #[test]
540    fn a_forced_group_is_due_on_every_frame_however_coarse_its_tier() {
541        let cadence = Cadence {
542            hold: 8,
543            faces: TILES,
544        };
545        let mut wanted = [None; GROUPS];
546        wanted[0] = Some(Group {
547            faces: 1,
548            tier: TIERS - 1,
549            forced: true,
550        });
551        for frame in 0..16 {
552            assert!(
553                cadence.schedule(frame, &wanted)[0],
554                "frame {frame} held a map that is about somewhere else"
555            );
556        }
557    }
558
559    /// **A forced group is offered the budget first**, so the reset does not
560    /// queue behind a map that is merely a frame out of date.
561    #[test]
562    fn a_forced_group_takes_the_budget_before_one_that_is_only_stale() {
563        let cadence = Cadence { hold: 1, faces: 1 };
564        let mut wanted = [None; GROUPS];
565        wanted[0] = Some(Group {
566            faces: 1,
567            tier: 0,
568            forced: false,
569        });
570        wanted[5] = Some(Group {
571            faces: 1,
572            tier: 0,
573            forced: true,
574        });
575        let redraw = cadence.schedule(0, &wanted);
576        assert!(
577            redraw[5],
578            "the forced group was refused the only tile spare"
579        );
580        assert!(!redraw[0], "the budget of one was spent twice: {redraw:?}");
581    }
582
583    /// **The schedule is a function of the frame index and nothing else**, which
584    /// is what makes a golden at a stated frame the same golden on every run and
585    /// every driver.
586    #[test]
587    fn one_frame_index_gives_one_answer() {
588        let cadence = Cadence { hold: 4, faces: 3 };
589        let wanted = all_on(1);
590        for frame in 0..32 {
591            let first = cadence.schedule(frame, &wanted);
592            for _ in 0..4 {
593                assert_eq!(cadence.schedule(frame, &wanted), first, "frame {frame}");
594            }
595        }
596    }
597}