Skip to main content

crcbl_render/
stack.rs

1//! The camera layer of [`crate::effects`]' four-layer order, as a file.
2//!
3//! [`RenderEffects`] is what a frame draws; [`CameraStack`] is what a **view
4//! asks for**, written down. Topic 48's camera layer (`docs/notes/rendering.md`)
5//! is per view and is a file naming which passes run and with what parameters,
6//! and the toggle layering the same notes record puts that layer at the top
7//! of the resolution order, above the player's `[engine.video]` clamp; this module is
8//! the reader and the writer of that file, and [`CameraStack::compile`] is the
9//! step that turns it into the bits [`EffectRequest::camera`] carries.
10//!
11//! ```
12//! use crcbl_render::stack::CameraStack;
13//! use crcbl_render::RenderEffects;
14//!
15//! let stack = CameraStack::from_ron(
16//!     "(shadows: Some(()), ambient_occlusion: Some(()), bloom: Some(()))",
17//! )?;
18//! assert_eq!(
19//!     stack.compile(),
20//!     RenderEffects::SHADOWS
21//!         .union(RenderEffects::AMBIENT_OCCLUSION)
22//!         .union(RenderEffects::BLOOM),
23//! );
24//! # Ok::<(), crcbl_render::stack::StackError>(())
25//! ```
26//!
27//! # A pass is present or absent, and that is the whole file
28//!
29//! Every field is an [`Option`] of a pass, and [`compile`](CameraStack::compile)
30//! sets that pass's bit exactly where the option is [`Some`] — which is the same
31//! statement `crate::effects` makes about the renderer: an effect that is off is
32//! a frame with fewer passes, never a shader branch. A field a file leaves out
33//! is [`None`], so the shortest legal stack is `()` and draws nothing.
34//!
35//! # The pass types are empty, and each says what it would carry
36//!
37//! Every pass here but [`AntialiasingPass`] is a field-less struct. That is not
38//! a placeholder for parameters this module forgot: the renderer's per-pass
39//! parameters are the setters a caller already has —
40//! [`ForwardRenderer::set_fog`], [`set_exposure`], [`set_exposure_adaptation`],
41//! [`set_tonemap_curve`] — and each of those takes a type that belongs to the
42//! pass rather than to this file. Giving a pass a parameter here means giving
43//! that type a serialized form and one owner, which is a slice of its own;
44//! `docs/backlog.md` lists which passes are waiting for one.
45//!
46//! [`AntialiasingPass`] is the exception because the thing it names is not a
47//! pass but a **slot**. [`Antialiasing`] holds the argument: there is one
48//! resolve, [`RenderEffects::ANTIALIASING`] and [`RenderEffects::CMAA2`] are two
49//! bits of one ladder rung rather than two independent switches, and
50//! `EffectRequest::resolve` clears the whole slot before it fills it. So this
51//! file has **one** antialiasing field naming a tier, and no per-tier field
52//! beside it: two spellings of one rung is exactly what the antialiasing
53//! ladder refused when it collapsed the two bits into one
54//! (`docs/notes/rendering.md`).
55//!
56//! [`EffectRequest::camera`]: crate::EffectRequest::camera
57//! [`ForwardRenderer::set_fog`]: crate::ForwardRenderer::set_fog
58//! [`set_exposure`]: crate::ForwardRenderer::set_exposure
59//! [`set_exposure_adaptation`]: crate::ForwardRenderer::set_exposure_adaptation
60//! [`set_tonemap_curve`]: crate::ForwardRenderer::set_tonemap_curve
61
62use serde::{Deserialize, Serialize};
63
64use crate::effects::{Antialiasing, RenderEffects};
65
66/// The shadow atlas — [`RenderEffects::SHADOWS`].
67///
68/// Field-less, on this module's terms: the atlas budget and
69/// [`ForwardRenderer::set_shadow_cadence`](crate::ForwardRenderer::set_shadow_cadence)'s
70/// cadence are the parameters it would carry, and neither has a serialized form
71/// yet.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
73#[serde(deny_unknown_fields)]
74pub struct ShadowsPass {}
75
76/// Screen-space ambient occlusion — [`RenderEffects::AMBIENT_OCCLUSION`].
77#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
78#[serde(deny_unknown_fields)]
79pub struct AmbientOcclusionPass {}
80
81/// Screen-space reflections — [`RenderEffects::REFLECTIONS`].
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
83#[serde(deny_unknown_fields)]
84pub struct ReflectionsPass {}
85
86/// The bloom chain — [`RenderEffects::BLOOM`].
87///
88/// The chain's length is a function of the target's extent rather than a choice,
89/// which is why the bit is one bit for a variable number of passes; the scalar
90/// the composite adds it back with is the parameter this would carry.
91#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
92#[serde(deny_unknown_fields)]
93pub struct BloomPass {}
94
95/// The frame's one antialiasing resolve, and which tier fills it.
96///
97/// The one pass here with a field, and [`Antialiasing`] is why: the resolve slot
98/// holds one filter, so a view names a rung rather than switching two bits.
99/// [`CameraStack::compile`] puts [`Antialiasing::bits`] in and nothing else, so
100/// a stack can no more ask for both tiers than a settings file can.
101///
102/// [`Antialiasing::None`] is a view asking for **no** resolve, which is not the
103/// same as leaving the field out — both compile to no antialiasing bits today,
104/// and they differ to a reader: one is a view that said so.
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(deny_unknown_fields)]
107pub struct AntialiasingPass {
108    /// Which rung of the antialiasing ladder this view wants.
109    pub tier: Antialiasing,
110}
111
112/// Volumetric fog — [`RenderEffects::VOLUMETRIC_FOG`].
113///
114/// The medium it integrates is the [`Fog`](crate::Fog) a view hands
115/// [`ForwardRenderer::set_fog`](crate::ForwardRenderer::set_fog), which is a
116/// scene property rather than this pass's own: a view with the bit off still
117/// composites that fog analytically. So the parameter this would carry is the
118/// froxel sample count, and there is no setter for one.
119#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(deny_unknown_fields)]
121pub struct VolumetricFogPass {}
122
123/// Auto-exposure — [`RenderEffects::AUTO_EXPOSURE`].
124///
125/// [`ExposureAdaptation`](crate::ExposureAdaptation) is its parameter and it
126/// arrives through
127/// [`ForwardRenderer::set_exposure_adaptation`](crate::ForwardRenderer::set_exposure_adaptation),
128/// because the rates are per-second and there is no clock in this crate to take
129/// a frame delta from.
130#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
131#[serde(deny_unknown_fields)]
132pub struct AutoExposurePass {}
133
134/// Screen-space contact shadows — [`RenderEffects::CONTACT_SHADOWS`].
135#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct ContactShadowsPass {}
138
139/// What one view asks its frame to draw, as a file.
140///
141/// One optional pass per effect [`RenderEffects`] carries, bar the two
142/// antialiasing bits, which are one [`AntialiasingPass`] naming a tier — this
143/// module's header says why. [`compile`](Self::compile) is the whole of the
144/// mapping: a bit per [`Some`].
145///
146/// # Unknown fields are refused
147///
148/// `deny_unknown_fields`, so a stack naming a pass this engine does not have —
149/// a typo, a rung from a later version, a tier's own word written as though it
150/// were a field — fails to parse rather than silently drawing something else.
151/// [`StackError`] names the line, the column and the field.
152///
153/// # Round trip
154///
155/// ```
156/// use crcbl_render::stack::CameraStack;
157///
158/// let stack = CameraStack::default();
159/// assert_eq!(CameraStack::from_ron(&stack.to_ron())?, stack);
160/// # Ok::<(), crcbl_render::stack::StackError>(())
161/// ```
162#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(deny_unknown_fields)]
164pub struct CameraStack {
165    /// The shadow atlas and everything that fills it.
166    #[serde(default)]
167    pub shadows: Option<ShadowsPass>,
168    /// The occlusion pass and its depth-weighted blur.
169    #[serde(default)]
170    pub ambient_occlusion: Option<AmbientOcclusionPass>,
171    /// The reflection march and the blur that composites it.
172    #[serde(default)]
173    pub reflections: Option<ReflectionsPass>,
174    /// The bloom chain.
175    #[serde(default)]
176    pub bloom: Option<BloomPass>,
177    /// The frame's one antialiasing resolve, and which tier fills it.
178    #[serde(default)]
179    pub antialiasing: Option<AntialiasingPass>,
180    /// The froxel scatter, its column scan and the composite over the frame.
181    #[serde(default)]
182    pub volumetric_fog: Option<VolumetricFogPass>,
183    /// The luminance histogram, its reduce, and the tonemap reading the result.
184    #[serde(default)]
185    pub auto_exposure: Option<AutoExposurePass>,
186    /// The short march along the sun's direction through the depth prepass.
187    #[serde(default)]
188    pub contact_shadows: Option<ContactShadowsPass>,
189}
190
191impl Default for CameraStack {
192    /// [`default_stack`](Self::default_stack) — the file form of
193    /// [`RenderEffects::DEFAULT_STACK`].
194    fn default() -> Self {
195        Self::default_stack()
196    }
197}
198
199impl CameraStack {
200    /// A stack that asks for nothing: every field [`None`].
201    ///
202    /// What a file holding `()` parses to, and the base a stack is built up
203    /// from — [`default_stack`](Self::default_stack) is written on it.
204    #[must_use]
205    pub const fn empty() -> Self {
206        Self {
207            shadows: None,
208            ambient_occlusion: None,
209            reflections: None,
210            bloom: None,
211            antialiasing: None,
212            volumetric_fog: None,
213            auto_exposure: None,
214            contact_shadows: None,
215        }
216    }
217
218    /// The file form of [`RenderEffects::DEFAULT_STACK`]: a pass exactly where
219    /// that constant has a bit.
220    ///
221    /// The three light-transport effects and the resolve the default carries —
222    /// a view that has been given no lens. `default_stack().compile() ==
223    /// RenderEffects::DEFAULT_STACK` is asserted, so the two cannot drift: this
224    /// is the same statement written twice, once as bits and once as a file, and
225    /// the file is the one a demo can edit.
226    #[must_use]
227    pub const fn default_stack() -> Self {
228        Self {
229            shadows: Some(ShadowsPass {}),
230            ambient_occlusion: Some(AmbientOcclusionPass {}),
231            reflections: Some(ReflectionsPass {}),
232            antialiasing: Some(AntialiasingPass {
233                tier: Antialiasing::Cmaa2,
234            }),
235            ..Self::empty()
236        }
237    }
238
239    /// The effect set this stack asks for: a bit per [`Some`].
240    ///
241    /// **This is what the camera layer of the resolution order carries.** It is
242    /// a *request*, not what the frame draws — the player's `[engine.video]`
243    /// clamp, the programmatic override and the device all still apply, in that
244    /// order, and `EffectRequest::resolve` is where they do.
245    ///
246    /// The antialiasing field contributes [`Antialiasing::bits`] rather than one
247    /// bit, which is how a stack names the higher tier without a second field.
248    #[must_use]
249    pub const fn compile(&self) -> RenderEffects {
250        let mut effects = RenderEffects::empty();
251        if self.shadows.is_some() {
252            effects = effects.union(RenderEffects::SHADOWS);
253        }
254        if self.ambient_occlusion.is_some() {
255            effects = effects.union(RenderEffects::AMBIENT_OCCLUSION);
256        }
257        if self.reflections.is_some() {
258            effects = effects.union(RenderEffects::REFLECTIONS);
259        }
260        if self.bloom.is_some() {
261            effects = effects.union(RenderEffects::BLOOM);
262        }
263        if let Some(pass) = self.antialiasing {
264            effects = effects.union(pass.tier.bits());
265        }
266        if self.volumetric_fog.is_some() {
267            effects = effects.union(RenderEffects::VOLUMETRIC_FOG);
268        }
269        if self.auto_exposure.is_some() {
270            effects = effects.union(RenderEffects::AUTO_EXPOSURE);
271        }
272        if self.contact_shadows.is_some() {
273            effects = effects.union(RenderEffects::CONTACT_SHADOWS);
274        }
275        effects
276    }
277
278    /// Parses one RON document.
279    ///
280    /// # Errors
281    ///
282    /// [`StackError`] if the text is not RON, or is RON that is not this struct:
283    /// an unknown field, a tier that is not on the ladder, a missing bracket.
284    /// The error names the line, the column and — where ron can say — the field.
285    pub fn from_ron(text: &str) -> Result<Self, StackError> {
286        ron::from_str(text).map_err(StackError::from_spanned)
287    }
288
289    /// Writes this stack back out, deterministically.
290    ///
291    /// **Byte-identical for equal stacks, on every platform.** Fields print in
292    /// struct order because that is the order serde's derive visits them, and
293    /// the newline is pinned to `\n` here rather than left to
294    /// [`ron::ser::PrettyConfig`]'s default, which is `\r\n` on Windows — a
295    /// writer whose output depended on the host is not one a scene format can
296    /// keep in git. No field carries a number today, so what a float would print
297    /// as is ron's answer and not this function's.
298    ///
299    /// # Panics
300    ///
301    /// Never, in practice: this struct is options of field-less structs and one
302    /// C-like enum, and ron's serializer has no failing path over those. The
303    /// `Result` exists for maps with non-string keys and for `Serialize`
304    /// implementations that raise their own errors, and this type has neither.
305    #[must_use]
306    pub fn to_ron(&self) -> String {
307        ron::ser::to_string_pretty(self, Self::pretty())
308            .expect("a CameraStack has no serializer path that can fail")
309    }
310
311    /// The one writer configuration, so [`to_ron`](Self::to_ron) and anything
312    /// that later writes a stack cannot disagree about what a file looks like.
313    fn pretty() -> ron::ser::PrettyConfig {
314        ron::ser::PrettyConfig::new()
315            .new_line("\n")
316            .indentor("    ")
317            .struct_names(true)
318    }
319}
320
321/// Why a string is not a [`CameraStack`].
322///
323/// ron's own [`SpannedError`](ron::error::SpannedError) reduced to the three
324/// things a person fixing the file needs — where, and what — so a caller
325/// reporting it does not have to depend on ron's types. The message is ron's
326/// verbatim, which is what carries the offending field's name.
327#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
328#[error("line {line}, column {column}: {message}")]
329pub struct StackError {
330    line: usize,
331    column: usize,
332    message: String,
333}
334
335impl StackError {
336    /// Where the parser was when it gave up: the **start** of the span, which
337    /// for an unknown field is the field's own name rather than the end of the
338    /// document.
339    #[must_use]
340    pub const fn line(&self) -> usize {
341        self.line
342    }
343
344    /// The column of [`line`](Self::line), 1-based as ron counts it.
345    #[must_use]
346    pub const fn column(&self) -> usize {
347        self.column
348    }
349
350    /// What ron said, without the position it says it at.
351    #[must_use]
352    pub fn message(&self) -> &str {
353        &self.message
354    }
355
356    fn from_spanned(error: ron::error::SpannedError) -> Self {
357        Self {
358            line: error.span.start.line,
359            column: error.span.start.col,
360            message: error.code.to_string(),
361        }
362    }
363}
364
365// `Instance::create_device` is native-only: see the `crcbl_hal::device` module docs.
366#[cfg(all(test, not(target_arch = "wasm32")))]
367mod tests {
368    use super::*;
369
370    /// **Every field survives the round trip, and the writer is deterministic.**
371    ///
372    /// Two claims in one, and the second is the one a scene format stands on: a
373    /// stack written twice has to be the same bytes twice, or a file that
374    /// nothing edited still shows up in a diff. The stack is built with every
375    /// field `Some` rather than from `default_stack`, because a round trip that
376    /// only visits the fields the default fills would pass with a field that
377    /// serializes and cannot be read back.
378    #[test]
379    fn every_field_survives_the_round_trip_and_the_writer_repeats_itself() {
380        let full = CameraStack {
381            shadows: Some(ShadowsPass {}),
382            ambient_occlusion: Some(AmbientOcclusionPass {}),
383            reflections: Some(ReflectionsPass {}),
384            bloom: Some(BloomPass {}),
385            antialiasing: Some(AntialiasingPass {
386                tier: Antialiasing::Cmaa2,
387            }),
388            volumetric_fog: Some(VolumetricFogPass {}),
389            auto_exposure: Some(AutoExposurePass {}),
390            contact_shadows: Some(ContactShadowsPass {}),
391        };
392        let text = full.to_ron();
393        assert_eq!(
394            CameraStack::from_ron(&text).expect("what to_ron wrote has to parse"),
395            full,
396            "{text}"
397        );
398        assert_eq!(text, full.to_ron(), "the writer is not deterministic");
399        assert!(
400            !text.contains('\r'),
401            "the newline is pinned to \\n, so a Windows host writes the same bytes: {text:?}"
402        );
403
404        // And the empty end of the range, which is the file a view that asks for
405        // nothing writes.
406        let empty = CameraStack::empty();
407        assert_eq!(
408            CameraStack::from_ron(&empty.to_ron()).expect("an empty stack parses"),
409            empty
410        );
411        assert_eq!(empty.compile(), RenderEffects::empty());
412    }
413
414    /// **A file that names a field this engine has no pass for is refused, and
415    /// the refusal says where and which.**
416    ///
417    /// `deny_unknown_fields` is what refuses it. Without the attribute serde
418    /// skips the value and parses the rest, so a stack whose `reflectons` was
419    /// misspelled would draw without reflections and report success — which is
420    /// a frame that is wrong and plausible, this crate's whole difficulty.
421    ///
422    /// `smaa` is the unknown field the test uses on purpose: it is the word the
423    /// tier CMAA2 replaced was spelled with, and a file still holding it has to
424    /// be told rather than quietly drawing something else. This file has one
425    /// antialiasing slot instead, and the refusal is where a reader finds that
426    /// out.
427    #[test]
428    fn an_unknown_field_is_refused_by_line_column_and_name() {
429        let error = CameraStack::from_ron("(\n    shadows: Some(()),\n    smaa: Some(()),\n)")
430            .expect_err("`smaa` is not a field of CameraStack");
431        assert_eq!(error.line(), 3, "{error}");
432        assert_eq!(error.column(), 5, "{error}");
433        assert!(
434            error.message().contains("smaa"),
435            "the message has to name the field: {error}"
436        );
437        assert!(
438            error.to_string().contains("line 3, column 5"),
439            "the Display has to carry the position: {error}"
440        );
441
442        // A tier that is not on the ladder, and syntax that is not RON at all:
443        // both come back as this error rather than as a stack.
444        assert!(CameraStack::from_ron("(antialiasing: Some((tier: taa)))").is_err());
445        assert!(CameraStack::from_ron("not ron").is_err());
446    }
447
448    /// **The default stack is `RenderEffects::DEFAULT_STACK`, written as a
449    /// file.**
450    ///
451    /// The one assertion that keeps this module honest about what a view gets
452    /// for saying nothing: `EffectRequest::default().camera` is that constant,
453    /// so a `default_stack` that had drifted from it would hand a demo reading
454    /// its own file a different frame from the demo beside it that reads none.
455    #[test]
456    fn the_default_stack_compiles_to_the_default_stack() {
457        assert_eq!(
458            CameraStack::default_stack().compile(),
459            RenderEffects::DEFAULT_STACK
460        );
461        assert_eq!(CameraStack::default(), CameraStack::default_stack());
462    }
463
464    /// **Each field sets its own bit and no other, and between them they name
465    /// every bit `RenderEffects` has.**
466    ///
467    /// The table is written out rather than looped off `compile`, because a
468    /// table used as its own oracle cannot fail. The second half is the
469    /// tripwire: a tenth effect bit added to `RenderEffects` and given no field
470    /// here fails this, rather than becoming an effect no file can ask for.
471    #[test]
472    fn a_field_sets_its_own_bit_and_the_fields_cover_every_bit() {
473        let one = |stack: CameraStack| stack.compile();
474        for (stack, bit) in [
475            (
476                CameraStack {
477                    shadows: Some(ShadowsPass {}),
478                    ..CameraStack::empty()
479                },
480                RenderEffects::SHADOWS,
481            ),
482            (
483                CameraStack {
484                    ambient_occlusion: Some(AmbientOcclusionPass {}),
485                    ..CameraStack::empty()
486                },
487                RenderEffects::AMBIENT_OCCLUSION,
488            ),
489            (
490                CameraStack {
491                    reflections: Some(ReflectionsPass {}),
492                    ..CameraStack::empty()
493                },
494                RenderEffects::REFLECTIONS,
495            ),
496            (
497                CameraStack {
498                    bloom: Some(BloomPass {}),
499                    ..CameraStack::empty()
500                },
501                RenderEffects::BLOOM,
502            ),
503            (
504                CameraStack {
505                    volumetric_fog: Some(VolumetricFogPass {}),
506                    ..CameraStack::empty()
507                },
508                RenderEffects::VOLUMETRIC_FOG,
509            ),
510            (
511                CameraStack {
512                    auto_exposure: Some(AutoExposurePass {}),
513                    ..CameraStack::empty()
514                },
515                RenderEffects::AUTO_EXPOSURE,
516            ),
517            (
518                CameraStack {
519                    contact_shadows: Some(ContactShadowsPass {}),
520                    ..CameraStack::empty()
521                },
522                RenderEffects::CONTACT_SHADOWS,
523            ),
524        ] {
525            assert_eq!(one(stack), bit, "{stack:?}");
526        }
527
528        // Every bit of the resolve slot, and nothing else in it.
529        let mut covered = RenderEffects::empty();
530        for tier in Antialiasing::ALL {
531            let stack = CameraStack {
532                antialiasing: Some(AntialiasingPass { tier }),
533                ..CameraStack::empty()
534            };
535            assert_eq!(stack.compile(), tier.bits(), "{tier:?}");
536            assert_eq!(
537                Antialiasing::from_effects(stack.compile()),
538                tier,
539                "{tier:?} did not survive its own stack"
540            );
541            covered = covered.union(tier.bits());
542        }
543
544        // …and the fields between them reach every flag the type declares.
545        let mut all = CameraStack {
546            shadows: Some(ShadowsPass {}),
547            ambient_occlusion: Some(AmbientOcclusionPass {}),
548            reflections: Some(ReflectionsPass {}),
549            bloom: Some(BloomPass {}),
550            antialiasing: None,
551            volumetric_fog: Some(VolumetricFogPass {}),
552            auto_exposure: Some(AutoExposurePass {}),
553            contact_shadows: Some(ContactShadowsPass {}),
554        };
555        covered = covered.union(all.compile());
556        all.antialiasing = Some(AntialiasingPass {
557            tier: Antialiasing::Fxaa,
558        });
559        covered = covered.union(all.compile());
560        assert_eq!(
561            covered,
562            RenderEffects::all(),
563            "an effect bit no field of CameraStack names",
564        );
565    }
566
567    /// **A tier is spelled in a file the way `crcbl::settings` spells it in
568    /// one**, and every rung round-trips through RON.
569    ///
570    /// The words are the file-format promise — a stack an author wrote is a
571    /// file that has to go on parsing — and `Antialiasing::name` is where they
572    /// are written down for the settings seam. Two spellings of one rung is the
573    /// failure this asserts against: the serde attribute and that function are
574    /// separate declarations of the same vocabulary.
575    #[test]
576    fn a_tier_is_spelled_the_way_the_settings_seam_spells_it() {
577        for tier in Antialiasing::ALL {
578            let stack = CameraStack {
579                antialiasing: Some(AntialiasingPass { tier }),
580                ..CameraStack::empty()
581            };
582            let text = stack.to_ron();
583            assert!(
584                text.contains(&format!("tier: {}", tier.name())),
585                "{tier:?} is spelled {:?} by the settings seam and {text:?} by this writer",
586                tier.name(),
587            );
588            assert_eq!(
589                CameraStack::from_ron(&text).expect("a tier round-trips"),
590                stack
591            );
592        }
593    }
594
595    /// **`set_camera_stack` moves the camera layer and leaves the other three
596    /// where they were.**
597    ///
598    /// The property that makes the layer worth having: a view reading a file is
599    /// not a view discarding the player's quality clamp, the antialiasing rung
600    /// they picked, or the override game code set a frame ago. Built on the null
601    /// backend, which records the descriptors and draws nothing — the same
602    /// device `graph_compile`'s renderer tests use, and the only one that runs
603    /// with no ICD.
604    #[test]
605    fn setting_a_camera_stack_leaves_the_other_three_layers_alone() {
606        use crcbl_hal::null::NullInstance;
607        use crcbl_hal::{AdapterId, DeviceDesc, Format, Instance, QueueKind};
608
609        use crate::effects::{EffectOverride, EffectRequest};
610
611        let instance = NullInstance::gpu_driven();
612        let device = instance
613            .create_device(&DeviceDesc {
614                label: Some("camera stack"),
615                ..DeviceDesc::for_adapter(AdapterId(0))
616            })
617            .expect("the null backend always opens");
618        let queue = device.queue(QueueKind::Graphics).expect("always present");
619        let mut renderer =
620            crate::ForwardRenderer::new(device.as_ref(), queue, Format::Rgba8UnormSrgb)
621                .expect("the null backend accepts every descriptor");
622
623        // The other three layers, each set to something a default would not
624        // produce, so a `set_camera_stack` that replaced the whole request
625        // fails here rather than passing on a field that happened to match.
626        let elsewhere = EffectRequest {
627            camera: RenderEffects::empty(),
628            video: RenderEffects::all().difference(RenderEffects::BLOOM),
629            antialiasing: Some(Antialiasing::Cmaa2),
630            programmatic: EffectOverride::none().force(RenderEffects::CONTACT_SHADOWS, Some(true)),
631        };
632        renderer.set_effect_request(elsewhere);
633
634        let stack =
635            CameraStack::from_ron("(shadows: Some(()), bloom: Some(()))").expect("that is a stack");
636        renderer.set_camera_stack(&stack);
637
638        let after = renderer.effect_request();
639        assert_eq!(
640            after.camera,
641            RenderEffects::SHADOWS.union(RenderEffects::BLOOM),
642            "the camera layer is the file's",
643        );
644        assert_eq!(after.video, elsewhere.video, "the video clamp moved");
645        assert_eq!(
646            after.antialiasing, elsewhere.antialiasing,
647            "the player's tier moved",
648        );
649        assert_eq!(
650            after.programmatic, elsewhere.programmatic,
651            "the programmatic override moved",
652        );
653
654        renderer.destroy(device.as_ref());
655    }
656}