crcbl_render/effects.rs
1//! Which render effects a frame draws, and topic 39's four-layer order that
2//! decides it.
3//!
4//! ```text
5//! camera stack (RON) declares what the view wants
6//! → [engine.video] clamps it downward as a player quality setting
7//! and its `antialiasing` rung replaces the one resolve slot
8//! → programmatic override may set it either way
9//! → device capability clamps it downward, last and absolutely
10//! ```
11//!
12//! [`EffectRequest`] carries the first four — they are what a caller supplies
13//! — and [`EffectRequest::resolve`] applies the whole order in one place, which
14//! is the property topic 39 asks for by name. The renderer holds one request and
15//! one resolved set, and every pass it records reads the resolved set; nothing
16//! else in this crate branches on a layer.
17//!
18//! # The antialiasing rung is a choice, not a clamp
19//!
20//! [`Antialiasing`] is the one thing the `[engine.video]` layer **replaces**
21//! rather than removes, and that type says why: a clamp can only take the
22//! resolve away, and a player choosing CMAA2 where the camera asked for FXAA is
23//! asking for a different filter rather than for less of one. It is still one
24//! layer — [`EffectRequest::resolve`] applies it where the video clamp sits,
25//! before the override and before the device.
26//!
27//! # An effect that is off is a frame with fewer passes, never a shader branch
28//!
29//! Each toggle removes work rather than selecting an alternative:
30//!
31//! * [`RenderEffects::SHADOWS`] off records no cull and no draw into the shadow
32//! atlas, and the atlas keeps the reversed-Z clear the pass writes — which
33//! every comparison against it reads as "fully lit".
34//! * [`RenderEffects::AMBIENT_OCCLUSION`] off records neither occlusion pass and
35//! leaves the renderer's 1×1 white `R8Unorm` bound, which `mesh.slang`
36//! multiplies its ambient term by.
37//! * [`RenderEffects::REFLECTIONS`] off records neither reflection pass and
38//! tonemaps the forward pass's own scene colour, which is bit-identical to the
39//! frame before that pair existed.
40//! * [`RenderEffects::BLOOM`] off records no chain pass and takes no chain image
41//! out of the transient pool, and the tonemap reads whichever image it would
42//! have read before — bit-identical, on the reflection pair's terms exactly.
43//! It is off in [`RenderEffects::DEFAULT_STACK`], so that is the frame every
44//! view in this workspace draws until one asks otherwise.
45//!
46//! Topic 18 specifies the first two mechanisms in writing and refuses the
47//! alternatives; the third is that document's own words about the march.
48//!
49//! # What sets each layer today
50//!
51//! | Layer | Source | Wired |
52//! | --- | --- | --- |
53//! | [`EffectRequest::camera`] | the view's own render stack, as RON | yes — [`CameraStack`](crate::stack::CameraStack) compiles the file and [`ForwardRenderer::set_camera_stack`] writes this field |
54//! | [`EffectRequest::video`] | `[engine.video]` | yes — `crcbl`'s start-up reads it: `GpuContextDesc::settings`, `GpuContext::effect_request` |
55//! | [`EffectRequest::antialiasing`] | `[engine.video] antialiasing` | yes — the same read: `crcbl::settings::antialiasing`, `GpuContext::effect_request` |
56//! | [`EffectRequest::programmatic`] | game code | yes — [`ForwardRenderer::set_effect_request`] |
57//! | the device clamp | nothing yet — no [`crcbl_hal::DeviceCaps`] value reaches it | the clamp runs and its rule set is empty, which is a fact about these effects — see [`ForwardRenderer::device_effects`] |
58//!
59//! The camera row's source is the render-stack RON topic 18 describes, and it is
60//! [`crate::stack`]: a [`CameraStack`](crate::stack::CameraStack) is the file,
61//! [`compile`](crate::stack::CameraStack::compile) is what turns it into this
62//! field, and [`ForwardRenderer::set_camera_stack`] is what writes it without
63//! touching the three layers around it. `apps/lantern/assets/camera.ron` is the
64//! file a demo draws through and `crcbl::screenshot`'s bloom fixture composes
65//! one from a string literal.
66//!
67//! **A renderer per view is still what makes the layer real**, and the file did
68//! not replace it: what the layer means is "two views in one frame resolve to
69//! different effect sets", which is a property of having a request each rather
70//! than of where the request was written. `apps/lantern`'s in-scene monitor is
71//! that consumer — its render-to-texture camera draws the room without
72//! reflections while the frame it hangs in draws them, from one device, in one
73//! graph, through this one function — and its stack is a constant in the
74//! sample's source, because what it says is a fact about a render-to-texture
75//! camera rather than something a run tunes.
76//!
77//! Every row has a source now. The `[engine.video]` one arrives through the
78//! umbrella rather than through this crate, because it has to: the keys are a
79//! settings question and `crcbl-render` has no storage, so `crcbl::settings`
80//! owns the one table mapping a key to a [`RenderEffects`] bit and
81//! `crcbl::engine::GpuContext` does the read while it opens. A context is what
82//! every sample and every `crcbl new` scaffold already opens before it builds a
83//! renderer, which is what makes the layer free rather than opt-in, and the
84//! read is infallible — a player with no settings file, and a platform that
85//! names no settings directory, both mean "the player has not asked for less".
86//!
87//! **What a context reads is the player's answer, not a request.**
88//! `effect_request` returns this struct with
89//! [`video`](EffectRequest::video) and
90//! [`antialiasing`](EffectRequest::antialiasing) filled in and the other two at
91//! their defaults, so a caller with a per-view stack writes
92//! `EffectRequest { camera, ..ctx.effect_request() }` and keeps both.
93//!
94//! [`ForwardRenderer::set_effect_request`]: crate::ForwardRenderer::set_effect_request
95//! [`ForwardRenderer::set_camera_stack`]: crate::ForwardRenderer::set_camera_stack
96//! [`ForwardRenderer::device_effects`]: crate::ForwardRenderer::device_effects
97
98bitflags::bitflags! {
99 /// The render effects, one bit each.
100 ///
101 /// One bit per effect and **not** one per pass: the occlusion pass and its
102 /// blur are one switch because the blur is not optional (`crate::ssao` says
103 /// why), and the reflection march and its blur are one switch because the
104 /// blur is the composite.
105 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106 pub struct RenderEffects: u32 {
107 /// The shadow atlas: the sun's cascades and every shadowed light's
108 /// tiles, their culls, and the depth-only pass that fills them.
109 const SHADOWS = 1 << 0;
110 /// Screen-space ambient occlusion — the occlusion pass and its
111 /// depth-weighted blur, whose result scales the ambient term.
112 const AMBIENT_OCCLUSION = 1 << 1;
113 /// Screen-space reflections — the march and the blur that composites it
114 /// into the scene colour.
115 const REFLECTIONS = 1 << 2;
116 /// The bloom chain — the threshold-free downsample pyramid, the tent
117 /// upsample that walks it back down, and the composite that adds it to
118 /// the scene colour.
119 ///
120 /// One bit for a variable number of passes, because the chain's length
121 /// is a function of the target's extent rather than a choice — see
122 /// `crate::bloom`. It is also the first bit here that is **not** in
123 /// [`RenderEffects::DEFAULT_STACK`]; that constant says why.
124 const BLOOM = 1 << 3;
125 /// FXAA — the fullscreen edge filter that resolves the tonemapped
126 /// frame into the target. [`Antialiasing::Fxaa`] is the rung a settings
127 /// file names it by.
128 ///
129 /// **Not in [`RenderEffects::DEFAULT_STACK`]**, and not on
130 /// [`BLOOM`](Self::BLOOM)'s grounds: this one is not a lens, it is a
131 /// resolve, and what keeps it out is that the slot holds one filter and
132 /// [`CMAA2`](Self::CMAA2) is the tier the default carries —
133 /// [`Antialiasing::from_effects`] of the default stack answers
134 /// [`Antialiasing::Cmaa2`]. So this is the *cheap* tier rather than the
135 /// absent one: a view's own stack, or a player writing
136 /// `antialiasing = "fxaa"`, asks for the one pass instead of the three.
137 /// `docs/notes/rendering.md` is where the ladder's rules are written down.
138 const ANTIALIASING = 1 << 4;
139 /// Volumetric fog — the froxel scatter, the column scan that turns it
140 /// into a prefix, and the fullscreen composite over the frame.
141 ///
142 /// The froxel ladder in `docs/notes/rendering.md`. **The second bit not in
143 /// [`RenderEffects::DEFAULT_STACK`], and for a reason neither of the
144 /// other two has**: this one does not add a term, it *moves* one. The
145 /// medium it integrates is the same exponential height fog `mesh.slang`
146 /// composites analytically, so a frame that ran both would charge the
147 /// air twice — [`ForwardRenderer::add_passes`] zeroes the frame block's
148 /// density when this is on, and the froxel path owns the medium
149 /// instead.
150 ///
151 /// A view with [`Fog::NONE`](crate::Fog::NONE) draws the same frame
152 /// either way, exactly: a zero density gives every froxel a
153 /// transmittance of one and no radiance, and the composite multiplies
154 /// by that one and adds those zeroes.
155 ///
156 /// [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes
157 const VOLUMETRIC_FOG = 1 << 5;
158 /// Auto-exposure — the luminance histogram of the finished frame, the
159 /// reduce that turns it into one number, and the tonemap reading that
160 /// number instead of the one a caller set.
161 ///
162 /// Topic 43 §6's rung, and **the third bit
163 /// not in [`RenderEffects::DEFAULT_STACK`]**. The reason is
164 /// [`VOLUMETRIC_FOG`](Self::VOLUMETRIC_FOG)'s rather than
165 /// [`BLOOM`](Self::BLOOM)'s: it does not add a term to the picture, it
166 /// takes the exposure away from the caller and computes it from the
167 /// frame. A view that set an exposure and then found the engine
168 /// overriding it would have been given a control that does nothing, so
169 /// handing the control over is something a view asks for.
170 ///
171 /// It also has no additive-zero form to land behind — an exposure
172 /// measured from the frame is not the exposure a caller happened to
173 /// set — so switching it on moves every frame it is on for, which is the
174 /// re-bless each tier of the resolve slot has already spent in turn.
175 ///
176 /// A view that hands `ForwardRenderer::set_exposure_adaptation` its
177 /// rates and frame delta gets an exposure that steps toward each
178 /// frame's measurement, so a cut between two differently-lit shots
179 /// rolls over a few tenths of a second; a view that sets none lands on
180 /// the measurement in one frame.
181 const AUTO_EXPOSURE = 1 << 6;
182 /// CMAA2 — the edge detect that writes one edge word per pixel, the
183 /// shape classification with its bounded long-edge search, adding its
184 /// fixed-point shares straight into the accumulation, and the deferred
185 /// colour apply.
186 /// [`Antialiasing::Cmaa2`] is the rung a settings file names it by.
187 ///
188 /// The antialiasing ladder's second rung and
189 /// **the higher of the two antialiasing tiers**. When it is set it takes
190 /// the resolve slot instead of [`ANTIALIASING`](Self::ANTIALIASING):
191 /// three passes where FXAA is one, over-blurring far less of the thin
192 /// geometry and text that is FXAA's known weakness, and costing what a
193 /// frame's *edges* cost rather than what its pixels do.
194 ///
195 /// **The two are never both run**, and that is what "a tier that is off
196 /// is a frame with fewer passes" means here — the FXAA bit may stay set
197 /// beside this one and is simply not recorded, because there is one
198 /// resolve slot and this fills it.
199 /// [`ForwardRenderer::add_passes`] is where the choice is made, once,
200 /// and `crate::cmaa2` is the pass group.
201 ///
202 /// **In [`RenderEffects::DEFAULT_STACK`]**, on
203 /// [`ANTIALIASING`](Self::ANTIALIASING)'s terms and in its place: a
204 /// resolve is not a lens, so the slot belongs in the default, and the
205 /// tier the engine reaches for is the honest thing to put in it.
206 /// Swapping the slot moved every golden the bit is on for at once,
207 /// which is the re-bless the antialiasing ladder priced and which
208 /// was taken as a change of its own.
209 ///
210 /// The bit is numbered after the tiers it postdates rather than beside
211 /// the one it replaces, so no existing flag's value moves. It kept the
212 /// slot the retired SMAA tier had, for the same reason.
213 ///
214 /// [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes
215 const CMAA2 = 1 << 7;
216 /// Screen-space contact shadows — the short march along the sun's
217 /// direction through the depth prepass, whose `R8Unorm` channel scales
218 /// the sun's shadow term.
219 ///
220 /// Topic 45's 2026-08-30 decision, and the rung the
221 /// shadow ladder reached after the rotated disc: the sliver where a foot
222 /// meets the floor or a book meets a shelf is finer than any atlas
223 /// texel, so no bias and no filter can close it — a bias large enough to
224 /// stop acne is large enough to detach the contact. `crate::shadow` is
225 /// what the atlas answers for and `crate::contact_shadows` is the pass.
226 ///
227 /// **A screen-space term, so it leaves no trace on a tile and stacks
228 /// with every rung above it**: it neither reads the atlas nor writes it,
229 /// and a frame that switches it off records one fewer full-screen pass
230 /// and binds the renderer's 1×1 white in its place.
231 ///
232 /// **Not in [`RenderEffects::DEFAULT_STACK`], and parked there rather
233 /// than argued out of it.** The decision puts it *in* the default stack,
234 /// with the low quality preset clearing it; what holds it out today is
235 /// that switching it on moves every golden the workspace has. That flip
236 /// and its re-bless is its own change — see the constant, which lists it
237 /// with the three bits that are out on the merits.
238 ///
239 /// The bit is numbered after the tiers it postdates rather than beside
240 /// the shadow bit it completes, so no existing flag's value moves —
241 /// [`CMAA2`](Self::CMAA2)'s rule.
242 const CONTACT_SHADOWS = 1 << 8;
243 }
244}
245
246impl RenderEffects {
247 /// What a view that has declared no render stack asks for.
248 ///
249 /// The three light-transport effects, and neither of the two post passes.
250 /// The line is not arbitrary: shadows, ambient occlusion and reflections
251 /// each approximate light transport that is **physically present in the
252 /// scene**, so a view that says nothing about them is a view asking for the
253 /// most correct picture the device can draw. Bloom is a property of a
254 /// **lens** — topic 18 files it under the post stack, whose contents that
255 /// document says are "data-driven per camera (RON: which passes,
256 /// parameters)" — and a camera that has been given no stack has been given
257 /// no lens.
258 ///
259 /// [`VOLUMETRIC_FOG`](Self::VOLUMETRIC_FOG) is out for a second reason: it
260 /// does not add a term to the picture, it takes one away from the fragment
261 /// stage and computes it somewhere else, and which of the two a view wants
262 /// is a cost question rather than a correctness one.
263 /// [`AUTO_EXPOSURE`](Self::AUTO_EXPOSURE) is out for a third, written on
264 /// the bit: it takes a control away from the caller, and a view that set an
265 /// exposure has said what it wants done with it.
266 /// [`ANTIALIASING`](Self::ANTIALIASING) is out for a fourth that is not a
267 /// refusal: the resolve slot holds one filter and [`CMAA2`](Self::CMAA2) —
268 /// which *is* in here — fills it, so the cheap tier is what a view or a
269 /// player asks for by name when it wants the one pass instead of the
270 /// three.
271 /// [`CONTACT_SHADOWS`](Self::CONTACT_SHADOWS) is out for a fifth reason
272 /// that is not a reason at all: topic 45 decided it belongs
273 /// *here*, with the low preset clearing it, and it is parked outside only
274 /// until the re-bless its first frame forces is taken on its own. It is the
275 /// one member of this list that is expected to leave it.
276 ///
277 /// So the default is the most correct picture, no lens and the higher
278 /// antialiasing tier, and a view that wants otherwise asks for it: through
279 /// its own stack, or through [`EffectOverride`], which is the layer that may
280 /// move a decision upward.
281 ///
282 /// This is what [`EffectRequest::default`]'s
283 /// [`camera`](EffectRequest::camera) holds, and it is why adding the bloom
284 /// bit — and each antialiasing tier's bit in turn — did not change a single
285 /// frame the engine already drew on the change that added it.
286 pub const DEFAULT_STACK: Self = Self::all().difference(
287 Self::BLOOM
288 .union(Self::VOLUMETRIC_FOG)
289 .union(Self::AUTO_EXPOSURE)
290 .union(Self::ANTIALIASING)
291 // **Parked, not decided.** Topic 45 puts
292 // [`CONTACT_SHADOWS`](Self::CONTACT_SHADOWS) *in* this stack and has
293 // the low preset clear it; it sits in this list because switching it
294 // on moves every golden in the workspace at once, and that re-bless
295 // is a change of its own rather than a rider on the change that
296 // built the pass. The other four are out on the merits — three of
297 // them refused and the fourth displaced from a slot that holds one
298 // filter — and say so above; this one is out on timing and says so
299 // here.
300 .union(Self::CONTACT_SHADOWS),
301 );
302
303 /// Every effect and the one word a report spells it with, in bit order.
304 ///
305 /// **The length is the flag count, not a number written here**, so a fifth
306 /// bit added to [`RenderEffects`] and left out of this table is a `cargo
307 /// build` error rather than a row that silently stops mentioning it. That
308 /// was the failure this table replaced: a hand-written list in
309 /// `apps/lantern` that named every effect but [`BLOOM`](Self::BLOOM), in a
310 /// sample whose summary line claimed to say what its frames drew.
311 ///
312 /// The length cannot see a table that reaches it by naming one bit twice —
313 /// `every_effect_is_named_exactly_once_and_the_row_prints_them` is what
314 /// does.
315 const NAMES: [(Self, &'static str); Self::all().bits().count_ones() as usize] = [
316 (Self::SHADOWS, "shadows"),
317 (Self::AMBIENT_OCCLUSION, "ao"),
318 (Self::REFLECTIONS, "ssr"),
319 (Self::BLOOM, "bloom"),
320 (Self::ANTIALIASING, "aa"),
321 (Self::VOLUMETRIC_FOG, "vfog"),
322 (Self::AUTO_EXPOSURE, "autoexp"),
323 (Self::CMAA2, "cmaa2"),
324 (Self::CONTACT_SHADOWS, "contact"),
325 ];
326
327 /// This set as a debug panel row and a headless summary line spell it:
328 /// `shadows ao ssr`, with a switched-off effect dropped, and `none` where
329 /// they all are.
330 ///
331 /// One spelling for every sample, because every sample reports this and a
332 /// second copy of the table is where one of them comes to disagree about
333 /// what a frame drew.
334 #[must_use]
335 pub fn row(self) -> String {
336 let on: Vec<&str> = Self::NAMES
337 .into_iter()
338 .filter(|(effect, _)| self.contains(*effect))
339 .map(|(_, name)| name)
340 .collect();
341 if on.is_empty() {
342 "none".to_string()
343 } else {
344 on.join(" ")
345 }
346 }
347}
348
349/// Why a ray-traced lighting path never appears in a sample's `paths` section,
350/// in the one line the panel prints.
351///
352/// **Not a device answer.** `crcbl-vk` can report `RAY_QUERY` and
353/// `ACCELERATION_STRUCTURE`, so [`crcbl_hal::DeviceCaps::lighting_path`] would
354/// choose [`LightingPath::RayTraced`](crcbl_hal::LightingPath::RayTraced) — but
355/// nothing in this crate builds an acceleration structure or traces one, so a
356/// run that selected it would draw the rasterised frame and say it had done
357/// something else. The row says so instead of implying a choice was made.
358///
359/// One string for every sample whose milestone this is, because the claim is
360/// about **this crate**: the day a ray-traced path lands here, the row that
361/// still says otherwise must not be four rows in four samples. A sample whose
362/// own charter numbers the rung differently — `apps/shard` — spells its own.
363#[must_use]
364pub const fn ray_tracing_note() -> &'static str {
365 "raster only (P7C)"
366}
367
368/// Which tier fills the frame's one antialiasing slot.
369///
370/// The antialiasing ladder's eighth decision (`docs/notes/rendering.md`), taken 2026-08-30 with
371/// Counter-Strike 2's video panel in front of it: the slot holds **one** filter,
372/// so the settings seam holds one ladder rather than two independent bits a
373/// panel could switch on together. The renderer still reads
374/// [`RenderEffects::ANTIALIASING`] and [`RenderEffects::CMAA2`] —
375/// [`bits`](Self::bits) and [`from_effects`](Self::from_effects) are the join,
376/// and [`ForwardRenderer::add_passes`] is where the bits become passes.
377///
378/// The rungs above this one — MSAA 2×, 4× and 8× — are that decision's next
379/// slice and are deliberately not here (`docs/backlog.md`, _MSAA was reopened
380/// rather than reversed_).
381///
382/// **Serialized in snake_case, which is [`name`](Self::name)'s spelling.** A
383/// camera stack names a rung by that word — see [`crate::stack`] — and
384/// `crcbl::settings` writes the same word into `[engine.video]`, so the two
385/// seams a player's choice can arrive through spell it once.
386/// `a_tier_is_spelled_the_way_the_settings_seam_spells_it` is what holds the
387/// attribute and that function together.
388///
389/// [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes
390#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
391#[serde(rename_all = "snake_case")]
392pub enum Antialiasing {
393 /// Neither tier: the tonemap writes the caller's target and no resolve pass
394 /// is recorded at all.
395 None,
396 /// FXAA 3.11 — [`RenderEffects::ANTIALIASING`], one fullscreen pass.
397 Fxaa,
398 /// CMAA2 — [`RenderEffects::CMAA2`], three passes and the higher tier.
399 Cmaa2,
400}
401
402impl Antialiasing {
403 /// The tiers, in the order a settings ladder climbs them.
404 ///
405 /// Ascending by cost and by what it removes, which is the order
406 /// `apps/options`' `ANTIALIASING` row steps and the order
407 /// [`from_name`](Self::from_name) searches.
408 pub const ALL: [Self; 3] = [Self::None, Self::Fxaa, Self::Cmaa2];
409
410 /// The two bits one resolve slot is made of.
411 ///
412 /// [`EffectRequest::resolve`] clears both before it sets the chosen one, so
413 /// a set that reached it with both on cannot leave with both on.
414 ///
415 /// **Public because a caller that wants *no* resolve has to name the slot
416 /// rather than a tier.** A fixture forcing one bit off leaves the other one
417 /// running — which is what a frame reading a single texel back against the
418 /// tonemap's own arithmetic cannot afford — and a fixture naming the bits by
419 /// hand is one that a third rung on the ladder would silently walk past.
420 pub const SLOT: RenderEffects = RenderEffects::ANTIALIASING.union(RenderEffects::CMAA2);
421
422 /// The bits this tier sets, and no others.
423 #[must_use]
424 pub const fn bits(self) -> RenderEffects {
425 match self {
426 Self::None => RenderEffects::empty(),
427 Self::Fxaa => RenderEffects::ANTIALIASING,
428 Self::Cmaa2 => RenderEffects::CMAA2,
429 }
430 }
431
432 /// The tier `effects` draws.
433 ///
434 /// **[`Cmaa2`](Self::Cmaa2) wins where both bits are set**, because that is
435 /// the choice [`ForwardRenderer::add_passes`] makes when it fills the slot:
436 /// this answers what the frame draws rather than what the set says.
437 ///
438 /// [`ForwardRenderer::add_passes`]: crate::forward::ForwardRenderer::add_passes
439 #[must_use]
440 pub const fn from_effects(effects: RenderEffects) -> Self {
441 if effects.contains(RenderEffects::CMAA2) {
442 Self::Cmaa2
443 } else if effects.contains(RenderEffects::ANTIALIASING) {
444 Self::Fxaa
445 } else {
446 Self::None
447 }
448 }
449
450 /// The snake_case word a settings file spells this tier with.
451 ///
452 /// **The one place a rung's spelling is written**, which is why
453 /// [`from_name`](Self::from_name) searches [`ALL`](Self::ALL) through this
454 /// rather than matching the strings a second time: two spellings of one
455 /// rung is a row a screen saves and a start-up never reads back.
456 #[must_use]
457 pub const fn name(self) -> &'static str {
458 match self {
459 Self::None => "none",
460 Self::Fxaa => "fxaa",
461 Self::Cmaa2 => "cmaa2",
462 }
463 }
464
465 /// The tier `name` spells, or [`None`] for a word no rung
466 /// wears.
467 #[must_use]
468 pub fn from_name(name: &str) -> Option<Self> {
469 Self::ALL.into_iter().find(|tier| tier.name() == name)
470 }
471}
472
473/// A programmatic override: which effects are forced on, and which off.
474///
475/// The third layer, and the only one that may move a decision **either way** —
476/// the two around it clamp downward. A game with its own quality logic drives
477/// this directly, which is the escape hatch topic 39 names
478/// `GpuContext::set_pacing` as the precedent for.
479///
480/// The two sets are kept disjoint by construction: [`force`](Self::force) is the
481/// only way to write either, and it removes the bit from the other set. A
482/// effect in both would make the resolution order depend on which of the two is
483/// applied first, which is a rule nobody should have to know.
484#[derive(Clone, Copy, Debug, PartialEq, Eq)]
485pub struct EffectOverride {
486 on: RenderEffects,
487 off: RenderEffects,
488}
489
490impl Default for EffectOverride {
491 fn default() -> Self {
492 Self::none()
493 }
494}
495
496impl EffectOverride {
497 /// Nothing overridden — the layers around this one decide.
498 #[must_use]
499 pub const fn none() -> Self {
500 Self {
501 on: RenderEffects::empty(),
502 off: RenderEffects::empty(),
503 }
504 }
505
506 /// Forces every effect in `effects` on, off, or back to undecided.
507 ///
508 /// `Some(true)` is on, `Some(false)` is off, and [`None`] releases them —
509 /// which is not the same as forcing them off, and is what a settings screen
510 /// does when a player returns a row to "auto".
511 #[must_use]
512 pub const fn force(mut self, effects: RenderEffects, state: Option<bool>) -> Self {
513 self.on = self.on.difference(effects);
514 self.off = self.off.difference(effects);
515 match state {
516 Some(true) => self.on = self.on.union(effects),
517 Some(false) => self.off = self.off.union(effects),
518 None => {}
519 }
520 self
521 }
522
523 /// What this override says about `effect`, on [`force`](Self::force)'s
524 /// terms.
525 ///
526 /// # Panics
527 ///
528 /// If `effect` is more than one flag: the answer would have to be one
529 /// verdict about several independent switches.
530 #[must_use]
531 pub fn state(&self, effect: RenderEffects) -> Option<bool> {
532 assert!(
533 effect.bits().is_power_of_two(),
534 "{effect:?} is not a single effect, so it has no one state"
535 );
536 if self.on.contains(effect) {
537 Some(true)
538 } else if self.off.contains(effect) {
539 Some(false)
540 } else {
541 None
542 }
543 }
544
545 /// Whether this override decides nothing.
546 #[must_use]
547 pub const fn is_empty(&self) -> bool {
548 self.on.is_empty() && self.off.is_empty()
549 }
550}
551
552/// The layers a caller supplies, in the order they are applied.
553///
554/// A struct rather than positional arguments, for the reason this crate's
555/// `SsrImages` is one: two of these fields are the same type, so positional
556/// arguments could be swapped at a call site and the frame would still compile
557/// and still draw a picture.
558///
559/// [`Default`] is [`RenderEffects::DEFAULT_STACK`] wanted by the view, no
560/// quality clamp, no antialiasing choice and no override — which resolves to
561/// whatever the device permits, and is what every frame the engine drew before
562/// this type existed did.
563#[derive(Clone, Copy, Debug, PartialEq, Eq)]
564pub struct EffectRequest {
565 /// What this **view** needs, from its render stack.
566 ///
567 /// Per camera because it is genuinely per view: topic 18's
568 /// render-to-texture security monitor and its planar reflection do not want
569 /// reflections of their own, and that is a property of the camera rather
570 /// than of the player's hardware.
571 ///
572 /// **A [`crate::stack::CameraStack`] is what a view writes it from**, which
573 /// is the render-stack RON topic 18 describes;
574 /// [`ForwardRenderer::set_camera_stack`](crate::ForwardRenderer::set_camera_stack)
575 /// is the one-layer setter. A renderer
576 /// per view is what makes the layer real either way — see this module's
577 /// table — and `apps/lantern`'s monitor camera is the consumer whose stack
578 /// is still a constant rather than a file.
579 pub camera: RenderEffects,
580 /// What the **player** allows, from `[engine.video]`.
581 ///
582 /// A quality setting, so it only ever clamps downward: a player who turned
583 /// reflections off gets none, and a player who turned them on gets them
584 /// where the view asked for them.
585 ///
586 /// **`crcbl`'s start-up is what sets it**: `crcbl::settings::VIDEO_KEYS` is
587 /// the one place a key is spelled, `crcbl::engine::GpuContext` reads the
588 /// namespace through `crcbl_store::settings::SettingsStack` while it opens,
589 /// and `GpuContext::effect_request` is what a renderer built on that context
590 /// is handed. See this module's table.
591 ///
592 /// [`RenderEffects::all`] is "the player has said nothing", which is what a
593 /// missing key, a missing file and a missing settings directory all produce
594 /// — a clamp that removes nothing rather than a frame with no effects in it.
595 pub video: RenderEffects,
596 /// Which antialiasing tier the **player** picked, from
597 /// `[engine.video] antialiasing`.
598 ///
599 /// [`None`] is "the player has not picked one", and is what a
600 /// missing key, a missing file and a missing settings directory all produce
601 /// — the view's own stack keeps the slot it asked for.
602 ///
603 /// **The one layer that replaces rather than clamps**, and
604 /// [`Antialiasing`]'s docs carry the argument: the slot holds one filter, so
605 /// a player choosing CMAA2 where the camera asked for FXAA is asking for a
606 /// different filter and not for less of one. It is applied after
607 /// [`video`](Self::video) and before [`programmatic`](Self::programmatic),
608 /// so game code still has the last word before the device — see
609 /// [`resolve`](Self::resolve).
610 pub antialiasing: Option<Antialiasing>,
611 /// What this **moment** calls for, from game code.
612 pub programmatic: EffectOverride,
613}
614
615impl Default for EffectRequest {
616 /// [`RenderEffects::DEFAULT_STACK`] for the view, no quality clamp, no
617 /// antialiasing choice and no override.
618 ///
619 /// **The camera field is the default stack rather than
620 /// [`RenderEffects::all`]**, and that constant carries the argument: the
621 /// effects that model the scene's own light transport are what a view asks
622 /// for by saying nothing, and the lens effects are what it has to ask for.
623 fn default() -> Self {
624 Self {
625 camera: RenderEffects::DEFAULT_STACK,
626 video: RenderEffects::all(),
627 antialiasing: None,
628 programmatic: EffectOverride::none(),
629 }
630 }
631}
632
633impl EffectRequest {
634 /// Applies the whole order and returns what the frame draws.
635 ///
636 /// ```text
637 /// camera → clamped by video → the AA slot replaced by the player's tier
638 /// → moved either way by the override
639 /// → clamped by device, last and absolutely
640 /// ```
641 ///
642 /// **The antialiasing tier sits inside the order rather than beside it**,
643 /// and both of its neighbours matter. It is after the video clamp because a
644 /// clamp can only take the resolve away, and the player picking a *different*
645 /// filter is not a smaller ask; it is before the programmatic override
646 /// because game code is the layer that may move a decision either way, and a
647 /// tier applied after it would silently undo an override that had just
648 /// forced a resolve on or off.
649 ///
650 /// `device` is what the hardware can run. **It cannot be overridden
651 /// upward**: asking for an effect a device has no way to draw is what
652 /// [`DeviceDesc::required_features`](crcbl_hal::DeviceDesc::required_features)
653 /// is for, and it is not something a toggle can force.
654 #[must_use]
655 pub fn resolve(&self, device: RenderEffects) -> RenderEffects {
656 let clamped = self.camera.intersection(self.video);
657 let chosen = match self.antialiasing {
658 Some(tier) => clamped.difference(Antialiasing::SLOT).union(tier.bits()),
659 None => clamped,
660 };
661 chosen
662 .union(self.programmatic.on)
663 .difference(self.programmatic.off)
664 .intersection(device)
665 }
666}
667
668#[cfg(test)]
669mod tests {
670 use super::*;
671
672 /// **The four layers apply in the order topic 39 writes them down**, and
673 /// each arm is the one that fails if two are swapped.
674 ///
675 /// Written as a table because the order is the whole point: an override
676 /// applied before `[engine.video]` would be silently clamped away by a
677 /// quality setting it is meant to escape, and a device clamp applied before
678 /// the override would let a toggle force on an effect the hardware cannot
679 /// draw. Both of those compile and both draw a plausible frame.
680 #[test]
681 fn the_layers_resolve_in_the_order_topic_39_specifies() {
682 let all = RenderEffects::all();
683 let shadows = RenderEffects::SHADOWS;
684 let ao = RenderEffects::AMBIENT_OCCLUSION;
685
686 // The default is `DEFAULT_STACK`: every effect that models the scene's
687 // own light transport, which is the frame the engine drew before there
688 // were toggles and before there was a lens effect to leave out of it.
689 assert_eq!(
690 EffectRequest::default().resolve(all),
691 RenderEffects::DEFAULT_STACK
692 );
693
694 // 1. The camera's stack is the top: a view that does not ask for an
695 // effect does not get it, whatever the layers below say.
696 let view = EffectRequest {
697 camera: all.difference(RenderEffects::REFLECTIONS),
698 ..EffectRequest::default()
699 };
700 assert_eq!(
701 view.resolve(all),
702 all.difference(RenderEffects::REFLECTIONS)
703 );
704
705 // 2. `[engine.video]` clamps downward and never upward. A player who
706 // turned an effect *on* that the view never asked for does not get
707 // it — which is the arm that fails if the two are unioned.
708 let quality = EffectRequest {
709 camera: shadows,
710 video: all,
711 ..EffectRequest::default()
712 };
713 assert_eq!(quality.resolve(all), shadows, "video must not add");
714 let clamped = EffectRequest {
715 camera: all,
716 video: shadows,
717 ..EffectRequest::default()
718 };
719 assert_eq!(clamped.resolve(all), shadows, "video must clamp");
720
721 // 3. The override moves it either way, and it is applied *after* the
722 // quality clamp — so it can restore what the clamp took.
723 let forced_on = EffectRequest {
724 camera: all,
725 video: shadows,
726 programmatic: EffectOverride::none().force(ao, Some(true)),
727 ..EffectRequest::default()
728 };
729 assert_eq!(
730 forced_on.resolve(all),
731 shadows.union(ao),
732 "the override must escape the quality clamp, which is what it is for"
733 );
734 let forced_off = EffectRequest {
735 programmatic: EffectOverride::none().force(shadows, Some(false)),
736 ..EffectRequest::default()
737 };
738 assert_eq!(
739 forced_off.resolve(all),
740 RenderEffects::DEFAULT_STACK.difference(shadows)
741 );
742
743 // 4. The device clamps last and absolutely: an override forcing an
744 // effect on cannot conjure one the device has no way to draw.
745 assert_eq!(
746 forced_on.resolve(all.difference(ao)),
747 shadows,
748 "the device clamp must be last, and must not be overridable upward"
749 );
750
751 // 5. The antialiasing tier *replaces* the resolve slot rather than
752 // clamping it, which is the arm that fails if it is intersected with
753 // the camera's set the way `video` is: the camera here asks for
754 // CMAA2 and the player asked for FXAA, and an intersection leaves
755 // neither.
756 let fxaa = RenderEffects::ANTIALIASING;
757 let picked = EffectRequest {
758 camera: RenderEffects::DEFAULT_STACK,
759 antialiasing: Some(Antialiasing::Fxaa),
760 ..EffectRequest::default()
761 };
762 assert_eq!(
763 picked.resolve(all),
764 RenderEffects::DEFAULT_STACK
765 .difference(RenderEffects::CMAA2)
766 .union(fxaa),
767 "the player's tier must take the slot, not intersect with it"
768 );
769 assert_eq!(
770 EffectRequest {
771 antialiasing: Some(Antialiasing::None),
772 ..EffectRequest::default()
773 }
774 .resolve(all),
775 RenderEffects::DEFAULT_STACK.difference(Antialiasing::SLOT),
776 "a player who chose no tier must empty the slot, both bits of it"
777 );
778
779 // 6. And it is applied *before* the override, which is the arm that
780 // fails if the two are swapped: game code forcing the resolve off is
781 // the last word, and a tier applied after it would put FXAA back.
782 let forced_off_after = EffectRequest {
783 antialiasing: Some(Antialiasing::Fxaa),
784 programmatic: EffectOverride::none().force(Antialiasing::SLOT, Some(false)),
785 ..EffectRequest::default()
786 };
787 assert_eq!(
788 forced_off_after.resolve(all),
789 RenderEffects::DEFAULT_STACK.difference(Antialiasing::SLOT),
790 "the override must run after the tier, not before it"
791 );
792 let forced_on_after = EffectRequest {
793 antialiasing: Some(Antialiasing::None),
794 programmatic: EffectOverride::none().force(RenderEffects::CMAA2, Some(true)),
795 ..EffectRequest::default()
796 };
797 assert_eq!(
798 forced_on_after.resolve(all),
799 RenderEffects::DEFAULT_STACK,
800 "the override must be able to restore a slot the player emptied"
801 );
802
803 // 7. The device still clamps the tier, last and absolutely.
804 assert_eq!(
805 picked.resolve(all.difference(fxaa)),
806 RenderEffects::DEFAULT_STACK.difference(RenderEffects::CMAA2),
807 "a device with no FXAA must not draw the tier the player picked"
808 );
809 }
810
811 /// **A tier is one word, one pair of bits, and the same tier back again.**
812 ///
813 /// The spellings are written out rather than looped off
814 /// [`Antialiasing::ALL`], for the reason `crcbl::settings`' key table is:
815 /// a table used as its own oracle cannot fail, and these words are the
816 /// file-format promise — renaming one is a settings file every existing
817 /// player has already written. The match is exhaustive, so a rung added to
818 /// the enum arrives here as a build error rather than as a silent gap.
819 #[test]
820 fn a_tier_spells_one_word_and_sets_one_pair_of_bits() {
821 for tier in Antialiasing::ALL {
822 let (word, bits) = match tier {
823 Antialiasing::None => ("none", RenderEffects::empty()),
824 Antialiasing::Fxaa => ("fxaa", RenderEffects::ANTIALIASING),
825 Antialiasing::Cmaa2 => ("cmaa2", RenderEffects::CMAA2),
826 };
827 assert_eq!(tier.name(), word);
828 assert_eq!(Antialiasing::from_name(word), Some(tier));
829 assert_eq!(tier.bits(), bits);
830 assert!(
831 Antialiasing::SLOT.contains(tier.bits()),
832 "{tier:?} sets a bit outside the resolve slot"
833 );
834 assert_eq!(
835 Antialiasing::from_effects(tier.bits()),
836 tier,
837 "{tier:?} did not survive the trip through its own bits"
838 );
839 }
840
841 assert_eq!(
842 Antialiasing::from_name("FXAA"),
843 None,
844 "the key is snake_case"
845 );
846 assert_eq!(
847 Antialiasing::from_name("smaa"),
848 None,
849 "the retired tier's word, which is now a word no rung wears"
850 );
851 assert_eq!(Antialiasing::from_name(""), None);
852
853 // Every set the two bits can be in names a tier that is on the ladder,
854 // which is what makes `ALL` the whole enum rather than most of it.
855 for extra in [
856 RenderEffects::empty(),
857 RenderEffects::ANTIALIASING,
858 RenderEffects::CMAA2,
859 Antialiasing::SLOT,
860 ] {
861 let tier = Antialiasing::from_effects(extra);
862 assert!(
863 Antialiasing::ALL.contains(&tier),
864 "{extra:?} resolved to {tier:?}, which is not on the ladder"
865 );
866 }
867 assert_eq!(
868 Antialiasing::from_effects(Antialiasing::SLOT),
869 Antialiasing::Cmaa2,
870 "the higher tier fills the slot when both bits are set, as add_passes does",
871 );
872
873 // The rung a view that declared no stack draws, which is what the
874 // `ANTIALIASING` row is born on.
875 assert_eq!(
876 Antialiasing::from_effects(RenderEffects::DEFAULT_STACK),
877 Antialiasing::Cmaa2,
878 );
879 }
880
881 /// **The default stack is every effect but the two a view has to ask for,
882 /// and a view that wants them can still get them.**
883 ///
884 /// Two claims, and the second is what keeps the first from being a way of
885 /// switching bloom off for good. The camera layer is a *request*, not a
886 /// clamp, so a view that declares its own stack — or a caller reaching for
887 /// [`EffectOverride`], the one layer that may move a decision upward — puts
888 /// the chain back in the frame. `crcbl::screenshot`'s bloom fixture is the
889 /// consumer that does exactly that.
890 ///
891 /// What it guards is the claim [`RenderEffects::DEFAULT_STACK`]'s docs make:
892 /// the lens, the froxel volume, auto-exposure, the cheap antialiasing tier
893 /// and — until its re-bless is taken — the contact march are what a view has
894 /// to ask for, and they are the **only** ones. A
895 /// default that quietly included one would have re-blessed every golden
896 /// image in the tree, and each of them would still have been a plausible
897 /// picture — which is the whole difficulty: a wrongly-defaulted post pass
898 /// does not look like a bug.
899 ///
900 /// The resolve slot has been through that twice, once per tier, and each
901 /// time it was a change of its own that re-blessed the suite;
902 /// [`RenderEffects::CMAA2`] is what fills it now, and this asserts that none
903 /// of the other four followed it in.
904 /// [`RenderEffects::CONTACT_SHADOWS`] is the one on that path today, and
905 /// this is what will go red on the change that moves it.
906 #[test]
907 fn the_default_stack_is_the_light_transport_effects_and_a_view_can_still_ask() {
908 assert_eq!(
909 RenderEffects::DEFAULT_STACK,
910 RenderEffects::all().difference(
911 RenderEffects::BLOOM
912 .union(RenderEffects::VOLUMETRIC_FOG)
913 .union(RenderEffects::AUTO_EXPOSURE)
914 .union(RenderEffects::ANTIALIASING)
915 .union(RenderEffects::CONTACT_SHADOWS)
916 ),
917 );
918 let post = RenderEffects::BLOOM
919 .union(RenderEffects::VOLUMETRIC_FOG)
920 .union(RenderEffects::AUTO_EXPOSURE)
921 .union(RenderEffects::CMAA2)
922 .union(RenderEffects::CONTACT_SHADOWS);
923 assert!(!EffectRequest::default().camera.contains(post));
924 assert!(
925 !EffectRequest::default()
926 .resolve(RenderEffects::all())
927 .contains(post),
928 "a view that said nothing must not get a post pass"
929 );
930
931 // The camera's own stack, which is the layer topic 18 puts the post
932 // stack in.
933 let declared = EffectRequest {
934 camera: RenderEffects::all(),
935 ..EffectRequest::default()
936 };
937 assert_eq!(declared.resolve(RenderEffects::all()), RenderEffects::all());
938
939 // And the override, for a caller with no stack of its own.
940 let forced = EffectRequest {
941 programmatic: EffectOverride::none()
942 .force(RenderEffects::BLOOM, Some(true))
943 .force(RenderEffects::ANTIALIASING, Some(true))
944 .force(RenderEffects::VOLUMETRIC_FOG, Some(true))
945 .force(RenderEffects::AUTO_EXPOSURE, Some(true))
946 .force(RenderEffects::CMAA2, Some(true))
947 .force(RenderEffects::CONTACT_SHADOWS, Some(true)),
948 ..EffectRequest::default()
949 };
950 assert_eq!(forced.resolve(RenderEffects::all()), RenderEffects::all());
951 }
952
953 /// **An override's two halves cannot disagree**, because the setter is the
954 /// only way to write either and it clears the other side.
955 ///
956 /// The failure this prevents is an override holding an effect in both sets,
957 /// where the answer depends on whether the union or the difference is
958 /// applied first — a rule that reads as an implementation detail and decides
959 /// what a frame draws.
960 #[test]
961 fn forcing_an_effect_one_way_releases_the_other() {
962 let ssr = RenderEffects::REFLECTIONS;
963 let over = EffectOverride::none().force(ssr, Some(true));
964 assert_eq!(over.state(ssr), Some(true));
965
966 let over = over.force(ssr, Some(false));
967 assert_eq!(over.state(ssr), Some(false));
968 assert_eq!(
969 EffectRequest {
970 programmatic: over,
971 ..EffectRequest::default()
972 }
973 .resolve(RenderEffects::all()),
974 RenderEffects::DEFAULT_STACK.difference(ssr),
975 "the second force must stand alone, not be unioned with the first"
976 );
977
978 let released = over.force(ssr, None);
979 assert_eq!(released.state(ssr), None);
980 assert!(released.is_empty());
981 }
982
983 /// **Every effect bit has a word, and [`RenderEffects::row`] prints every
984 /// one of them.**
985 ///
986 /// The guard for the shape this table replaced. `RenderEffects::NAMES` is
987 /// as long as the type has bits, so a new effect left unnamed does not
988 /// compile — what that length cannot see is a table that reaches it by
989 /// naming one bit twice, which is what the first half here asserts. The
990 /// count is taken from `bitflags`' own declared list rather than from a
991 /// number written down, so it moves when the flags do.
992 ///
993 /// The second half is the part that matters to a reader of a summary line:
994 /// a name in the table that `row` never emits is an effect that is on and
995 /// unmentioned, which reads exactly like an effect that is off.
996 #[test]
997 fn every_effect_is_named_exactly_once_and_the_row_prints_them() {
998 assert_eq!(
999 RenderEffects::NAMES.len(),
1000 RenderEffects::all().iter_names().count(),
1001 "the table has to name every flag `bitflags` declares, once each",
1002 );
1003
1004 let mut named = RenderEffects::empty();
1005 for (effect, word) in RenderEffects::NAMES {
1006 assert!(
1007 effect.bits().is_power_of_two(),
1008 "{word} names {effect:?}, which is not a single effect",
1009 );
1010 assert!(!named.intersects(effect), "{effect:?} is named twice");
1011 named = named.union(effect);
1012 }
1013 assert_eq!(named, RenderEffects::all());
1014
1015 let row = RenderEffects::all().row();
1016 let words: Vec<&str> = row.split(' ').collect();
1017 assert_eq!(words.len(), RenderEffects::NAMES.len(), "{row:?}");
1018 for (effect, word) in RenderEffects::NAMES {
1019 assert!(
1020 words.contains(&word),
1021 "{effect:?} is on and unmentioned in {row:?}"
1022 );
1023 }
1024
1025 // The spelling every sample's summary line and debug panel already
1026 // print, which this must not have moved.
1027 assert_eq!(RenderEffects::DEFAULT_STACK.row(), "shadows ao ssr cmaa2");
1028 assert_eq!(RenderEffects::empty().row(), "none");
1029 assert_eq!(RenderEffects::BLOOM.row(), "bloom");
1030 }
1031}