Skip to main content

crcbl_render/
camera.rs

1//! Cameras, and the reversed-Z projection matrices that are the engine's whole
2//! depth convention.
3//!
4//! ```text
5//! Camera { view, Projection::Perspective { .. } }  ──▶ view_proj  ──▶ FrameUniforms
6//!          ^                Projection::Orthographic { .. }
7//!          └── the only thing milestone 5 changes
8//! ```
9//!
10//! # Reversed-Z is produced *here*, and nowhere else
11//!
12//! Stage 2 locked the convention — "`D32_SFLOAT`,
13//! projection uses an **infinite far plane with reversed depth**, compare op
14//! `GREATER`, clear to 0.0" — and `crcbl-hal` bakes three of those four into its
15//! defaults: [`DepthStencilState::default`](crcbl_hal::DepthStencilState) is
16//! `Greater` on `D32Float`, [`ClearValue::default`](crcbl_hal::ClearValue)
17//! clears to `0.0`, and [`Viewport::default`](crcbl_hal::Viewport) keeps the
18//! depth range `0.0..1.0` *unreversed* because reversing the viewport is the
19//! well-known trap that looks right and throws the precision away.
20//!
21//! The fourth is the projection matrix, and it lives in this module. Everything
22//! else in the engine inherits the convention by using what this produces.
23//!
24//! ## Why it is worth the trouble at all
25//!
26//! Not aesthetics: **precision**. A conventional `0..1` depth buffer spends most
27//! of a float's mantissa near the near plane, where nothing needs it, and runs
28//! out at distance. Stage 2's stated case is "a
29//! sector-tiled world with 300 m+ sightlines z-fights immediately on a
30//! conventional `0..1` buffer".
31//!
32//! That is a *measurable* claim, and this module's
33//! `reversed_z_resolves_a_centimetre_at_300_metres_and_standard_z_does_not`
34//! measures it: two surfaces one centimetre apart at 300 m quantise to the same
35//! `f32` under a standard projection and to different ones under this module's.
36//! The test computes both, so it fails if this module ever stops being
37//! reversed — a comment could not do that.
38
39use core::f32::consts::FRAC_PI_4;
40
41use glam::{Mat4, Vec2, Vec3, Vec4};
42
43/// A second clip-space depth, in front of [`crcbl_hal::depth::NEAR`], that
44/// [`Camera::ray_through`] unprojects to get a ray's direction.
45///
46/// Any depth between the two ends gives the same direction; this one is picked
47/// because it is well away from both under either projection.
48/// [`crcbl_hal::depth::FAR`] would **not** do: under
49/// [`Projection::Perspective`] the far plane is at infinity, so a point there
50/// has `w = 0` and the perspective divide is undefined.
51const RAY_DEPTH: f32 = 0.5;
52
53/// How a camera flattens the world into clip space.
54///
55/// Two variants and one code path: stage 2's milestone
56/// 5 is "orthographic camera mode proving the 2D story (z = z-index) is just a
57/// projection matrix swap", and this enum is that proof's shape. Nothing
58/// downstream of [`Camera::view_projection`] — not the shader, not the pipeline,
59/// not the render graph — can tell which variant produced the matrix it was
60/// handed.
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub enum Projection {
63    /// Infinite-far reversed-Z perspective.
64    ///
65    /// There is no `far` field, and its absence is the design: an infinite far
66    /// plane is free under reversed-Z (it costs one matrix element, not
67    /// precision) and it removes the "what should the far plane be?" question
68    /// from every caller in a world measured in sectors.
69    Perspective {
70        /// Vertical field of view, in radians.
71        fov_y: f32,
72        /// Distance to the near plane. Must be positive; **this is the only
73        /// number that controls depth precision** under reversed-Z, so it is
74        /// worth raising rather than lowering.
75        near: f32,
76    },
77    /// Reversed-Z orthographic.
78    ///
79    /// The 2D mode. `half_height` is half the visible world height; the width
80    /// follows from the aspect ratio, so a resize changes what is visible
81    /// horizontally and never squashes the picture.
82    Orthographic {
83        /// Half the visible height, in world units.
84        half_height: f32,
85        /// Near plane distance along the view direction.
86        near: f32,
87        /// Far plane distance along the view direction. Finite, unlike the
88        /// perspective case: an orthographic projection is linear in depth, so
89        /// an infinite far plane would map every finite z to 1.0.
90        far: f32,
91    },
92}
93
94impl Default for Projection {
95    /// A 45° vertical field of view with a 10 cm near plane.
96    fn default() -> Self {
97        Self::Perspective {
98            fov_y: FRAC_PI_4,
99            near: 0.1,
100        }
101    }
102}
103
104impl Projection {
105    /// The projection matrix for an `aspect` (width ÷ height) viewport.
106    ///
107    /// The result maps to **Y-up NDC with depth in `0..1`**. Y-up rather than
108    /// Vulkan's native Y-down because `crcbl-vk` submits a negative-height
109    /// viewport, so the seam's convention is +Y up and a backend that did not
110    /// flip would be the one out of step. Depth `0..1` because that is what
111    /// every backend this engine targets uses; only the *direction* is unusual.
112    ///
113    /// # Panics
114    ///
115    /// If `aspect` is not finite and positive, or if a distance is not positive
116    /// — all of which are caller bugs that otherwise produce a NaN matrix and a
117    /// blank screen with no error anywhere.
118    #[must_use]
119    pub fn matrix(self, aspect: f32) -> Mat4 {
120        assert!(
121            aspect.is_finite() && aspect > 0.0,
122            "aspect ratio must be finite and positive, got {aspect}"
123        );
124        match self {
125            Self::Perspective { fov_y, near } => {
126                assert!(near > 0.0, "the near plane must be positive, got {near}");
127                assert!(
128                    fov_y > 0.0 && fov_y < core::f32::consts::PI,
129                    "the field of view must be in (0, π), got {fov_y}"
130                );
131                // Maps `near` to depth 1 and infinity to depth 0.
132                glam::camera::rh::proj::directx::perspective_infinite_reverse(fov_y, aspect, near)
133            }
134            Self::Orthographic {
135                half_height,
136                near,
137                far,
138            } => {
139                assert!(
140                    half_height > 0.0,
141                    "the orthographic half-height must be positive, got {half_height}"
142                );
143                assert!(far > near, "far {far} must be beyond near {near}");
144                let half_width = half_height * aspect;
145                // **The `near`/`far` arguments are swapped, and that is the
146                // whole reversal.** `directx::orthographic(l, r, b, t, n, f)`
147                // maps view depth `n` to 0 and `f` to 1; handing it `(f, n)`
148                // maps `f` to 0 and `n` to 1, which is reversed-Z. There is no
149                // other trick — no negated viewport, no flipped compare op at
150                // the call site — because a second mechanism is how a convention
151                // gets applied twice and cancels.
152                glam::camera::rh::proj::directx::orthographic(
153                    -half_width,
154                    half_width,
155                    -half_height,
156                    half_height,
157                    far,
158                    near,
159                )
160            }
161        }
162    }
163
164    /// Whether this is the 2D mode.
165    #[must_use]
166    pub const fn is_orthographic(self) -> bool {
167        matches!(self, Self::Orthographic { .. })
168    }
169
170    /// How many pixels one unit of length subtends one unit from the eye, in a
171    /// viewport `height` pixels tall.
172    ///
173    /// Topic 25's scale factor: the number that carries a frame's
174    /// size and field of view into a screen-space error, so a level's stored
175    /// error in world units becomes the pixels its simplification would cost.
176    /// [`ClusterSelect::is_drawn`] divides it by the distance to the group's
177    /// sphere, which is where the perspective falloff comes from.
178    ///
179    /// **An orthographic projection has no falloff at all**, so for that variant
180    /// this is the whole scale factor and dividing it by a distance is wrong.
181    /// The value returned is still the right one — half the viewport over half
182    /// the visible height — and [`ForwardRenderer`] is what deals with the rest:
183    /// it pairs an orthographic camera with a budget nothing satisfies, so the
184    /// descent expands every group and draws the base level. That is the honest
185    /// answer for a 2D mode rather than a distance term invented for it.
186    ///
187    /// # Panics
188    ///
189    /// On the same arguments [`matrix`](Self::matrix) refuses: a field of view
190    /// outside `(0, π)` or a non-positive half-height. `height` is not checked —
191    /// a zero-height viewport gives zero pixels per unit, which is a budget
192    /// nothing exceeds and a frame with no pixels in it.
193    ///
194    /// [`ClusterSelect::is_drawn`]: crcbl_shaders::cluster_select::ClusterSelect::is_drawn
195    /// [`ForwardRenderer`]: crate::forward::ForwardRenderer
196    #[must_use]
197    pub fn pixels_per_unit(self, height: f32) -> f32 {
198        match self {
199            Self::Perspective { fov_y, .. } => {
200                assert!(
201                    fov_y > 0.0 && fov_y < core::f32::consts::PI,
202                    "the field of view must be in (0, π), got {fov_y}"
203                );
204                0.5 * height / (0.5 * fov_y).tan()
205            }
206            Self::Orthographic { half_height, .. } => {
207                assert!(
208                    half_height > 0.0,
209                    "the orthographic half-height must be positive, got {half_height}"
210                );
211                0.5 * height / half_height
212            }
213        }
214    }
215}
216
217/// A camera: where it is, what it looks at, and how it projects.
218///
219/// Positions are plain [`Vec3`] in **camera-relative render space**, not
220/// [`WorldPos`](crcbl_core::WorldPos). That is deliberate and is
221/// the `WorldPos` rule recorded in `docs/notes/backends.md`: every simulation
222/// position is a `WorldPos`, and plain `Vec3` is only ever camera-relative
223/// render space. Converting one to the other is the renderer's job at P2, when
224/// something other than a hardcoded cube has a position at all.
225#[derive(Clone, Copy, Debug, PartialEq)]
226pub struct Camera {
227    /// Eye position in render space.
228    pub eye: Vec3,
229    /// Point the camera looks at.
230    pub target: Vec3,
231    /// World up. Must not be parallel to `target - eye`.
232    pub up: Vec3,
233    /// How the world flattens into clip space.
234    pub projection: Projection,
235}
236
237impl Default for Camera {
238    /// Two metres back along +Z, looking at the origin, Y up, default
239    /// perspective.
240    fn default() -> Self {
241        Self {
242            eye: Vec3::new(0.0, 0.0, 2.0),
243            target: Vec3::ZERO,
244            up: Vec3::Y,
245            projection: Projection::default(),
246        }
247    }
248}
249
250impl Camera {
251    /// The view matrix: world → right-handed Y-up view space.
252    ///
253    /// # Panics
254    ///
255    /// If the camera is degenerate: `eye` and `target` coincide, `up` is zero,
256    /// or `up` is parallel to the view direction. Each of those makes
257    /// `look_at` divide by a zero-length vector and hand back a matrix of
258    /// `NaN`s — which propagates through the uniform block into the vertex
259    /// shader and shows up as an empty screen with no error anywhere, the same
260    /// failure [`Projection::matrix`] asserts against.
261    #[must_use]
262    pub fn view(&self) -> Mat4 {
263        let direction = self.target - self.eye;
264        assert!(
265            direction.length_squared() > 0.0 && direction.is_finite(),
266            "the camera must look somewhere: eye {:?} and target {:?}",
267            self.eye,
268            self.target
269        );
270        assert!(
271            self.up.length_squared() > 0.0 && self.up.is_finite(),
272            "the camera's up vector must be non-zero and finite, got {:?}",
273            self.up
274        );
275        assert!(
276            direction
277                .normalize()
278                .cross(self.up.normalize())
279                .length_squared()
280                > f32::EPSILON,
281            "the camera's up vector {:?} is parallel to its view direction {direction:?}; there \
282             is no basis to build",
283            self.up
284        );
285        glam::camera::rh::view::look_at_mat4(self.eye, self.target, self.up.normalize())
286    }
287
288    /// The combined world → clip matrix for an `aspect` viewport.
289    ///
290    /// # Panics
291    ///
292    /// As [`Projection::matrix`].
293    #[must_use]
294    pub fn view_projection(&self, aspect: f32) -> Mat4 {
295        self.projection.matrix(aspect) * self.view()
296    }
297
298    /// The same camera with a different projection — **milestone 5, entire**.
299    #[must_use]
300    pub fn with_projection(mut self, projection: Projection) -> Self {
301        self.projection = projection;
302        self
303    }
304
305    /// The depth value a point in render space projects to.
306    ///
307    /// The perspective divide, done on the CPU. Exists because it is what makes
308    /// the depth convention *testable* without a GPU: this is the number that
309    /// ends up in the `D32_SFLOAT` buffer, and reversed-Z is a claim about how
310    /// it is distributed.
311    ///
312    /// Returns `None` for a point on or behind the eye plane, where the divide
313    /// is undefined.
314    ///
315    /// `w > 0`, not `w.abs() > 0`: under a right-handed perspective projection
316    /// `w` is the distance in front of the eye, so a point *behind* it has a
317    /// negative `w` and dividing by it yields a positive-looking depth for
318    /// geometry that is not in the frustum at all. Under
319    /// [`Projection::Orthographic`] `w` is always `1`, so every point has a
320    /// depth and this returns one — which is correct, an orthographic camera
321    /// has no eye plane to be behind.
322    ///
323    /// # Panics
324    ///
325    /// As [`Projection::matrix`] and [`Camera::view`].
326    #[must_use]
327    pub fn depth_of(&self, point: Vec3, aspect: f32) -> Option<f32> {
328        let clip = self.view_projection(aspect) * point.extend(1.0);
329        (clip.w > f32::MIN_POSITIVE).then(|| clip.z / clip.w)
330    }
331
332    /// The world-space ray through the pixel at `at`, in a viewport of
333    /// `extent` pixels.
334    ///
335    /// The inverse of [`depth_of`](Self::depth_of), and the reason it is here
336    /// rather than in the caller: both are the perspective divide done on the
337    /// CPU, and a screen-to-ray written against a matrix somebody else built is
338    /// the classic place a convention gets applied twice or not at all.
339    ///
340    /// **`at` is in the same pixels a [`ShellEvent`] reports**: `(0, 0)` is the
341    /// top-left corner of the window and `y` grows downward, which is
342    /// `crcbl_ui::draw_list`'s convention too. A whole pixel is its top-left
343    /// corner, so a caller that wants the ray through a pixel's **centre** adds
344    /// half a pixel to both — what matters for picking, and what a test
345    /// projecting a point back must account for.
346    ///
347    /// The ray begins on the near plane rather than at
348    /// [`eye`](Self::eye), because that is where the visible world starts and
349    /// because [`Projection::Orthographic`] has no single eye point at all. The
350    /// direction is unit length, so a hit's parametric distance is a distance
351    /// in metres.
352    ///
353    /// ```
354    /// use crcbl_render::{Camera, Projection};
355    /// use glam::Vec2;
356    ///
357    /// let camera = Camera::default();
358    /// let extent = (800, 600);
359    /// // The centre of the viewport looks where the camera looks.
360    /// let ray = camera.ray_through(Vec2::new(400.0, 300.0), extent);
361    /// let forward = (camera.target - camera.eye).normalize();
362    /// assert!((ray.direction - forward).length() < 1e-5);
363    /// ```
364    ///
365    /// # Panics
366    ///
367    /// If `extent` has a zero side — there is no pixel to shoot through — and
368    /// otherwise as [`Projection::matrix`] and [`Camera::view`].
369    ///
370    /// [`ShellEvent`]: https://docs.rs/crcbl-shell
371    #[must_use]
372    pub fn ray_through(&self, at: Vec2, extent: (u32, u32)) -> ViewRay {
373        let (width, height) = extent;
374        assert!(
375            width > 0 && height > 0,
376            "a viewport with a zero side has no pixel to shoot a ray through, got {width}x{height}"
377        );
378        let size = Vec2::new(width as f32, height as f32);
379        // Clip space is +Y up and the window is +Y down, which is the one
380        // conversion in here that is a convention rather than arithmetic.
381        let ndc = Vec2::new(at.x / size.x * 2.0 - 1.0, 1.0 - at.y / size.y * 2.0);
382
383        let inverse = self.view_projection(size.x / size.y).inverse();
384        let unproject = |depth: f32| {
385            let point = inverse * Vec4::new(ndc.x, ndc.y, depth, 1.0);
386            point.truncate() / point.w
387        };
388        let origin = unproject(crcbl_hal::depth::NEAR);
389        ViewRay {
390            origin,
391            direction: (unproject(RAY_DEPTH) - origin).normalize(),
392        }
393    }
394
395    /// The pixel a point in render space lands on, in a viewport of `extent`
396    /// pixels — [`ray_through`](Self::ray_through) run the other way.
397    ///
398    /// In the same pixels `ray_through` takes: `(0, 0)` is the top-left corner
399    /// and `y` grows downward, and the answer is a position rather than a whole
400    /// pixel, so the ray through it passes through `point`. What a marker drawn
401    /// over the scene — a health bar, a label, an editor's handles — is placed
402    /// with.
403    ///
404    /// Not clamped to the viewport: a point off to the side answers with a pixel
405    /// outside it. [`None`] for a point on or behind the eye plane, on
406    /// [`depth_of`](Self::depth_of)'s terms, where it lands on no pixel at all.
407    ///
408    /// ```
409    /// use crcbl_render::Camera;
410    /// use glam::Vec2;
411    ///
412    /// let camera = Camera::default();
413    /// let at = camera.pixel_of(camera.target, (800, 600)).expect("in front");
414    /// assert!((at - Vec2::new(400.0, 300.0)).length() < 1e-3);
415    /// ```
416    ///
417    /// # Panics
418    ///
419    /// As [`ray_through`](Self::ray_through).
420    #[must_use]
421    pub fn pixel_of(&self, point: Vec3, extent: (u32, u32)) -> Option<Vec2> {
422        let (width, height) = extent;
423        assert!(
424            width > 0 && height > 0,
425            "a viewport with a zero side has no pixel to land on, got {width}x{height}"
426        );
427        let size = Vec2::new(width as f32, height as f32);
428        let clip = self.view_projection(size.x / size.y) * point.extend(1.0);
429        if clip.w <= f32::MIN_POSITIVE {
430            return None;
431        }
432        let ndc = Vec2::new(clip.x, clip.y) / clip.w;
433        Some(Vec2::new(
434            (ndc.x + 1.0) * 0.5 * size.x,
435            (1.0 - ndc.y) * 0.5 * size.y,
436        ))
437    }
438}
439
440/// Where a pixel's ray starts and where it goes — what
441/// [`Camera::ray_through`] answers with.
442///
443/// A pair rather than a [`crcbl_phys::Ray`]: this crate does not depend on the
444/// physics crate and must not, so the caller that wants to cast one builds it —
445/// one line, and the widening from render space's `f32` to simulation space's
446/// `f64` is that caller's decision to make rather than this one's to make for
447/// it.
448///
449/// [`crcbl_phys::Ray`]: https://docs.rs/crcbl-phys
450#[derive(Clone, Copy, Debug, PartialEq)]
451pub struct ViewRay {
452    /// Where the ray begins: the point on the near plane the pixel unprojects
453    /// to.
454    pub origin: Vec3,
455    /// Unit direction, away from the viewer.
456    pub direction: Vec3,
457}
458
459/// A directional light: the whole of milestone 4's lighting model.
460///
461/// One light, no shadows, no attenuation. Stage 2's rung
462/// 4 is "single directional light, Lambert+Blinn — enough to see geometry
463/// properly; real material model comes with stage 3/5", and cascaded shadow maps
464/// are explicitly P7 (topic 18). The real material model arrived: `mesh.slang`
465/// shades with a Cook-Torrance GGX lobe against a glTF metallic-roughness row,
466/// and the rung's Blinn wording is what it replaced.
467#[derive(Clone, Copy, Debug, PartialEq)]
468pub struct DirectionalLight {
469    /// Direction **towards** the light, in render space. Normalised on the way
470    /// into the uniform block.
471    ///
472    /// Towards, not "the direction the light travels": that is the vector both
473    /// the Lambert term and the specular lobe's half-vector want, and storing
474    /// the other one means every consumer negates it and one of them eventually
475    /// forgets.
476    pub direction: Vec3,
477    /// Colour premultiplied by intensity. **May exceed 1.0** — the scene target
478    /// is `Rgba16Float` precisely so that it can.
479    pub color: Vec3,
480    /// Flat ambient term. A real irradiance probe is P7's.
481    pub ambient: Vec3,
482}
483
484impl Default for DirectionalLight {
485    /// A warm key light over the viewer's **right** shoulder, with headroom.
486    ///
487    /// Two of the three numbers here are deliberate rather than aesthetic:
488    ///
489    /// * The direction has a **positive** X, so it comes from the same side as
490    ///   the default camera rather than from behind the geometry that camera can
491    ///   see. A light pointing away from every visible face renders a technically
492    ///   correct picture of an unlit cube, which is a confusing first result and
493    ///   was in fact P1.3's first result.
494    /// * The intensity is **above 1.0**, so the brightest lit surface exceeds
495    ///   what the swapchain can hold. That is what makes the `Rgba16Float` scene
496    ///   target carry something an `Rgba8` one could not, and it is what
497    ///   `crcbl-vk`'s e2e suite reads back to prove HDR-from-P1 is a pipeline
498    ///   rather than a format enum. A key light brighter than the display is
499    ///   also simply what daylight is.
500    ///
501    /// The ambient is small but non-zero, so a face turned away from the light
502    /// is dark rather than black.
503    fn default() -> Self {
504        Self {
505            direction: Vec3::new(0.4, 0.8, 0.6).normalize(),
506            color: Vec3::new(1.60, 1.55, 1.45),
507            ambient: Vec3::splat(0.08),
508        }
509    }
510}
511
512/// Exponential height fog: how thick the air is, and what colour it scatters.
513///
514/// Topic 43 §4's cheapest large win. Density falls
515/// off exponentially with height above [`reference_height`](Self::reference_height),
516/// and `mesh.slang`'s fragment stage integrates it along the ray from the eye
517/// to each shaded point — so a distant surface fades towards
518/// [`color`](Self::color) and a valley fills while a hilltop stays clear, from
519/// four numbers and no extra pass.
520///
521/// **[`Fog::NONE`] is the default and is exactly no fog**, not nearly none:
522/// a zero density gives a zero optical depth, whose transmittance is exactly
523/// one, and the shader composites as two multiplies rather than an
524/// interpolation so that one returns the unfogged radiance bit for bit. Every
525/// golden blessed before fog existed still matches.
526///
527/// [`ForwardRenderer::set_fog`] is what a caller hands this to, and
528/// [`crcbl_shaders::fog`] is the arithmetic both sides run.
529///
530/// [`ForwardRenderer::set_fog`]: crate::forward::ForwardRenderer::set_fog
531#[derive(Clone, Copy, Debug, PartialEq)]
532pub struct Fog {
533    /// Optical depth added per world unit travelled at the reference height.
534    ///
535    /// Zero is off. The useful range is small — a density of one puts a surface
536    /// a single unit away behind more than half the fog — so this is tenths and
537    /// hundredths for a scene measured in metres.
538    pub density: f32,
539    /// The height over which the density falls by a factor of `e`.
540    ///
541    /// Larger is a thicker atmosphere reaching further up; zero or less is fog
542    /// that does not thin with height at all, which is the limit this
543    /// approaches rather than a special case in the shader.
544    pub falloff: f32,
545    /// Where the density is [`density`](Self::density), in render-space `y`.
546    ///
547    /// Usually the ground the scene sits on, so the fog is thickest where the
548    /// geometry is and thins above it.
549    pub reference_height: f32,
550    /// The radiance the fog scatters towards the eye.
551    ///
552    /// **May exceed 1.0**, like [`DirectionalLight::color`] and for the same
553    /// reason: the scene target is `Rgba16Float` and this is a radiance rather
554    /// than a display colour, so a bright sky's haze is allowed to bloom.
555    pub color: Vec3,
556    /// What fraction of the sun's radiance the medium scatters towards the eye,
557    /// per unit length.
558    ///
559    /// **Read only by the froxel path** — [`RenderEffects::VOLUMETRIC_FOG`] —
560    /// and zero everywhere else. `mesh.slang`'s closed form integrates
561    /// absorption along the view ray and has no direction in it at all, so
562    /// there is nowhere for a phase function to go; a caller who sets this
563    /// without switching the effect on gets the frame they had.
564    ///
565    /// Zero is exactly off: the scattering source is a sum, so a zero term
566    /// leaves [`color`](Self::color)'s environment term bit for bit.
567    ///
568    /// [`RenderEffects::VOLUMETRIC_FOG`]: crate::RenderEffects::VOLUMETRIC_FOG
569    pub sun_scattering: f32,
570    /// What fraction of a point or spot light's radiance the medium scatters
571    /// towards the eye, per unit length — the glow around every punctual light
572    /// in the scene, and the cone a spot cuts through the air.
573    ///
574    /// One coefficient for every light rather than one per light: the medium
575    /// is what scatters, and it is the same air around all of them. Separate
576    /// from [`sun_scattering`](Self::sun_scattering) because a scene's sun and
577    /// its lamps are authored in different units, and a haze that reads right
578    /// against the sun would swamp the frame around a lamp of the same number.
579    ///
580    /// Read only by the froxel path, on `sun_scattering`'s terms, and zero is
581    /// exactly off for the same reason: the term is added to the scattering
582    /// source and a zero adds nothing. A light's glow is evaluated once per
583    /// froxel, at its slice's midpoint, and occluded by the light's own shadow
584    /// tiles where its row names them. What the midpoint misses — a small light
585    /// in a long far slice — is in `docs/backlog.md` under _The froxel column
586    /// casts its shaft_.
587    pub light_scattering: f32,
588    /// How the medium redistributes what it scatters: positive forward, zero
589    /// evenly, negative back.
590    ///
591    /// The `g` of [`crcbl_shaders::volumetric::phase`], clamped there to
592    /// [`MAX_ANISOTROPY`](crcbl_shaders::volumetric::MAX_ANISOTROPY). Mie
593    /// scattering in fog is around `0.8`, which is what makes looking towards
594    /// the sun through it bright and looking away from it flat; smoke is
595    /// lower. Read only by the froxel path, on
596    /// [`sun_scattering`](Self::sun_scattering)'s terms.
597    pub anisotropy: f32,
598}
599
600impl Fog {
601    /// No fog, which is what a renderer nobody has called
602    /// [`ForwardRenderer::set_fog`] on carries.
603    ///
604    /// The colour is black and unobservable: it is read only through the
605    /// density, which is zero here.
606    ///
607    /// [`ForwardRenderer::set_fog`]: crate::forward::ForwardRenderer::set_fog
608    pub const NONE: Self = Self {
609        density: 0.0,
610        falloff: 0.0,
611        reference_height: 0.0,
612        color: Vec3::ZERO,
613        sun_scattering: 0.0,
614        light_scattering: 0.0,
615        anisotropy: 0.0,
616    };
617}
618
619impl Default for Fog {
620    /// [`Fog::NONE`].
621    fn default() -> Self {
622        Self::NONE
623    }
624}
625
626/// A gradient sky: three radiances, and the environment they light with.
627///
628/// Topic 43 §8. The sky is a smoothstep blend from
629/// [`ground`](Self::ground) through [`horizon`](Self::horizon) to
630/// [`zenith`](Self::zenith) in a direction's `y`, and what reaches the scene is
631/// that field projected onto the L1 spherical-harmonic basis the irradiance
632/// grid already speaks — so a surface facing up is lit by the sky and one
633/// facing down by the ground, from three colours and no extra pass.
634///
635/// **It is added to the flat ambient and to the probe grid, not chosen between
636/// them**, because all three are the same term: what a diffuse surface receives
637/// from an environment it is not looking at directly. An author who wants the
638/// sky to be the whole of the environment sets [`DirectionalLight::ambient`] to
639/// zero.
640///
641/// **[`Sky::NONE`] is the default and is exactly no sky.** A black gradient
642/// projects to coefficients that are all zero, so the three dot products the
643/// fragment stage adds are zero, and every golden blessed before a sky existed
644/// still matches.
645///
646/// Nothing draws the sky yet — this lights with it, and the background is still
647/// the scene target's clear colour. [`ForwardRenderer::set_sky`] is what a
648/// caller hands this to, and [`crcbl_shaders::sky`] is the projection.
649///
650/// [`ForwardRenderer::set_sky`]: crate::forward::ForwardRenderer::set_sky
651#[derive(Clone, Copy, Debug, PartialEq)]
652pub struct Sky {
653    /// Radiance straight up.
654    ///
655    /// **May exceed 1.0**, like [`DirectionalLight::color`] and [`Fog::color`]
656    /// and for their reason: the scene target is `Rgba16Float` and this is a
657    /// radiance rather than a display colour.
658    pub zenith: Vec3,
659    /// Radiance at the horizon, where a direction's `y` is zero.
660    ///
661    /// The band both hemispheres blend away from, so it carries more weight in
662    /// the ambient than either pole does.
663    pub horizon: Vec3,
664    /// Radiance straight down — the ground's bounce, not the ground itself.
665    ///
666    /// This engine traces nothing to find it, so it is an author's estimate of
667    /// what the surface below sends back up.
668    pub ground: Vec3,
669}
670
671impl Sky {
672    /// No sky, which is what a renderer nobody has called
673    /// [`ForwardRenderer::set_sky`] on carries.
674    ///
675    /// Black in every direction, and its projection is every coefficient zero,
676    /// so it adds nothing rather than nearly nothing.
677    ///
678    /// [`ForwardRenderer::set_sky`]: crate::forward::ForwardRenderer::set_sky
679    pub const NONE: Self = Self {
680        zenith: Vec3::ZERO,
681        horizon: Vec3::ZERO,
682        ground: Vec3::ZERO,
683    };
684
685    /// This sky in the form [`crcbl_shaders::sky`] projects.
686    pub(crate) fn gradient(self) -> crcbl_shaders::sky::SkyGradient {
687        crcbl_shaders::sky::SkyGradient {
688            zenith: self.zenith.to_array(),
689            horizon: self.horizon.to_array(),
690            ground: self.ground.to_array(),
691        }
692    }
693}
694
695impl Default for Sky {
696    /// [`Sky::NONE`].
697    fn default() -> Self {
698        Self::NONE
699    }
700}
701
702/// Hillaire's atmosphere: a sun, an exposure and a viewpoint, over the planet
703/// `crcbl_shaders::atmosphere`'s committed tables describe.
704///
705/// Topic 43 §8. Where [`Sky`] is three authored
706/// colours, this is the light a real planet's air scatters — so the sky is blue
707/// overhead because Rayleigh scattering is, and red at a low sun because the
708/// slant path has already taken the blue out, rather than because somebody
709/// picked those colours.
710///
711/// **It replaces the gradient rather than adding to it.** A renderer given an
712/// atmosphere draws it, lights with its L1 projection and reflects with its
713/// three bands; the [`Sky`] it also holds is not read on those frames.
714/// [`ForwardRenderer::set_atmosphere`] is what a caller hands this to, and
715/// `None` is what puts the gradient back.
716///
717/// # What it costs
718///
719/// The sky-view LUT is marched on the **host** — see
720/// [`crcbl_shaders::atmosphere::SkyView::build`] — so the sky's device cost is
721/// four buffer loads and a blend, the same as the gradient's. The air in front
722/// of the scene is one more full-screen pass, `volumetric-composite`, which an
723/// atmosphere frame runs whether or not the fog effect is on: one trilinear
724/// read per covered pixel and no march. What is not free
725/// is changing this value: the first [`ForwardRenderer::begin_frame`] after an
726/// atmosphere is set marches the whole LUT and the aerial-perspective LUT
727/// beside it, which is tens of milliseconds of CPU. Every later move of the sun
728/// — or change of [`Self::km_per_unit`] — is marched
729/// [`crcbl_shaders::atmosphere::SKY_VIEW_BUILD_ROWS`] rows per frame with the
730/// last finished LUT still drawn, so a scene that sweeps the sun pays a stripe
731/// per frame and sees a sky that lags — `ForwardRenderer::refresh_sky_view`
732/// carries that trade.
733///
734/// [`ForwardRenderer::set_atmosphere`]: crate::forward::ForwardRenderer::set_atmosphere
735/// [`ForwardRenderer::begin_frame`]: crate::forward::ForwardRenderer::begin_frame
736#[derive(Clone, Copy, Debug, PartialEq)]
737pub struct Atmosphere {
738    /// The direction **towards** the sun, in world space.
739    ///
740    /// Normalised on the way in, so a caller may hand over the same unnormalised
741    /// vector it built a [`DirectionalLight`] from. A zero vector is taken as
742    /// straight up, which is the one direction that leaves the sky azimuthally
743    /// symmetric and therefore the one a degenerate input cannot make look
744    /// wrong.
745    pub sun_direction: Vec3,
746    /// The sun's illuminance above the atmosphere, in linear RGB.
747    ///
748    /// **May exceed 1.0**, like [`DirectionalLight::color`] and for its reason:
749    /// the scene target is `Rgba16Float` and this is a radiance rather than a
750    /// display colour. The whole sky is linear in it, so it is an exposure knob
751    /// as much as a colour one.
752    pub sun_illuminance: Vec3,
753    /// The viewpoint's height above sea level, in **kilometres**.
754    ///
755    /// Kilometres because that is the unit the planet's coefficients are quoted
756    /// in and the one number in this type that is not in the engine's own
757    /// units. A scene at ground level passes zero; the LUT is built for one
758    /// height per sun, which is Hillaire's own approximation.
759    pub altitude_km: f32,
760    /// How many kilometres one world unit is — the scale the air in front of
761    /// the scene is marched at.
762    ///
763    /// **Aerial perspective**: a frame drawn under an atmosphere puts the air
764    /// between the eye and every surface in front of that surface, out of
765    /// [`crcbl_shaders::atmosphere::AerialView`], and how much air a surface
766    /// fifty units away has in front of it is this times fifty kilometres.
767    /// The engine's unit is the metre, so a scene laid out in metres passes
768    /// [`crcbl_shaders::atmosphere::KM_PER_METRE`] — which is what
769    /// [`Self::NOON`] carries — and its air is as thin as the physics says: a
770    /// plaza's worth of it is an optical depth under a thousandth. A scene
771    /// built at another scale passes its own, and zero is no air at all.
772    pub km_per_unit: f32,
773}
774
775impl Atmosphere {
776    /// A sun overhead at sea level, normalised so its illuminance is one in
777    /// every channel, over a scene laid out in metres.
778    ///
779    /// The fixture the render tests build from, and the value a caller starts
780    /// from before pointing the sun somewhere and scaling it.
781    pub const NOON: Self = Self {
782        sun_direction: Vec3::Y,
783        sun_illuminance: Vec3::ONE,
784        altitude_km: 0.0,
785        km_per_unit: crcbl_shaders::atmosphere::KM_PER_METRE,
786    };
787
788    /// This atmosphere in the form [`crcbl_shaders::atmosphere`] marches.
789    ///
790    /// The normalisation lives here rather than in the shader crate for the
791    /// reason `Sky`'s own conversion does: that crate names no vector type but
792    /// its own arrays, and `glam` is where a normalise belongs.
793    ///
794    /// **Public where that conversion is not**, and for a reason rather than
795    /// an inconsistency: a test that predicts a frame drawn under this
796    /// atmosphere has to march the same sky-view LUT the renderer marched, and
797    /// building one from the caller's own spelling of the sun would put the
798    /// normalisation on only one side of that comparison.
799    /// `crcbl::screenshot::atmosphere_view` is the consumer.
800    #[must_use]
801    pub fn parameters(self) -> crcbl_shaders::atmosphere::Atmosphere {
802        let direction = self.sun_direction.normalize_or(Vec3::Y);
803        crcbl_shaders::atmosphere::Atmosphere {
804            sun_direction: direction.to_array(),
805            sun_illuminance: self.sun_illuminance.to_array(),
806            altitude_km: self.altitude_km,
807            km_per_unit: self.km_per_unit,
808        }
809    }
810}
811
812impl Default for Atmosphere {
813    /// [`Atmosphere::NOON`].
814    fn default() -> Self {
815        Self::NOON
816    }
817}
818
819#[cfg(test)]
820mod tests {
821    use super::*;
822
823    const ASPECT: f32 = 16.0 / 9.0;
824
825    /// A conventional (non-reversed) projection, built only so the tests below
826    /// have something to compare against.
827    ///
828    /// This is what the engine would use if the decision had gone the other way,
829    /// and it is the control in every experiment here.
830    fn standard_z(near: f32, far: f32) -> Mat4 {
831        glam::camera::rh::proj::directx::perspective(FRAC_PI_4, ASPECT, near, far)
832    }
833
834    fn reversed() -> Camera {
835        Camera {
836            eye: Vec3::ZERO,
837            target: -Vec3::Z,
838            up: Vec3::Y,
839            projection: Projection::Perspective {
840                fov_y: FRAC_PI_4,
841                near: 0.1,
842            },
843        }
844    }
845
846    /// The convention itself: the near plane holds 1.0 and infinity holds 0.0.
847    #[test]
848    fn perspective_depth_runs_from_one_at_the_near_plane_to_zero_at_infinity() {
849        let camera = reversed();
850        let near = camera
851            .depth_of(Vec3::new(0.0, 0.0, -0.1), ASPECT)
852            .expect("in front of the eye");
853        assert!(
854            (near - crcbl_hal::depth::NEAR).abs() < 1e-5,
855            "a point on the near plane must have depth {}, got {near}",
856            crcbl_hal::depth::NEAR
857        );
858
859        let far = camera
860            .depth_of(Vec3::new(0.0, 0.0, -1.0e9), ASPECT)
861            .expect("in front of the eye");
862        assert!(
863            far.abs() < 1e-6,
864            "a point at effectively infinity must approach {}, got {far}",
865            crcbl_hal::depth::FAR
866        );
867
868        // And it is monotonic the *reversed* way: nearer is larger.
869        let mut previous = f32::INFINITY;
870        for distance in [0.1f32, 0.5, 1.0, 10.0, 100.0, 1000.0, 100_000.0] {
871            let depth = camera
872                .depth_of(Vec3::new(0.0, 0.0, -distance), ASPECT)
873                .expect("in front of the eye");
874            assert!(
875                depth < previous,
876                "depth must decrease with distance under reversed-Z: {distance} m gave \
877                 {depth}, which is not below {previous}"
878            );
879            assert!((0.0..=1.0).contains(&depth), "{distance} m gave {depth}");
880            previous = depth;
881        }
882    }
883
884    /// **The reason reversed-Z is locked**, measured rather than asserted.
885    ///
886    /// Stage 2's design review: "a sector-tiled world with 300 m+
887    /// sightlines z-fights immediately on a conventional 0..1 buffer". This test
888    /// puts two surfaces one centimetre apart at 300 m and quantises both depths
889    /// to `f32` — which is what a `D32_SFLOAT` attachment stores — under *both*
890    /// projections.
891    ///
892    /// Under the engine's reversed projection they are distinguishable. Under
893    /// the conventional one they are the *same float*, which is z-fighting with
894    /// no dither and no fix. If this module ever stopped being reversed, the
895    /// first assertion would fail, and if the control were wrong the second
896    /// would.
897    #[test]
898    fn reversed_z_resolves_a_centimetre_at_300_metres_and_standard_z_does_not() {
899        let camera = reversed();
900        let near_surface = Vec3::new(0.0, 0.0, -300.0);
901        let far_surface = Vec3::new(0.0, 0.0, -300.01);
902
903        let reversed_near = camera.depth_of(near_surface, ASPECT).expect("in front");
904        let reversed_far = camera.depth_of(far_surface, ASPECT).expect("in front");
905        assert_ne!(
906            reversed_near, reversed_far,
907            "reversed-Z must resolve 1 cm at 300 m; both quantised to {reversed_near}"
908        );
909        assert!(
910            reversed_near > reversed_far,
911            "the nearer surface must hold the larger value under reversed-Z"
912        );
913
914        // The control: the same two points through a conventional projection
915        // with a generous far plane, which is what this engine deliberately does
916        // not use.
917        let conventional = standard_z(0.1, 10_000.0);
918        let depth = |point: Vec3| {
919            let clip = conventional * point.extend(1.0);
920            clip.z / clip.w
921        };
922        let (standard_near, standard_far) = (depth(near_surface), depth(far_surface));
923        assert_eq!(
924            standard_near, standard_far,
925            "the control is only meaningful if conventional depth genuinely \
926             collapses here; it gave {standard_near} and {standard_far}, which \
927             differ — re-derive the distances rather than relaxing the test"
928        );
929    }
930
931    /// The seam's clear value and compare op only make sense against *this*
932    /// matrix, so the agreement is worth pinning in one place.
933    #[test]
934    fn the_projection_agrees_with_the_seams_depth_defaults() {
935        use crcbl_hal::{ClearValue, CompareOp, DepthStencilState, Format};
936
937        let state = DepthStencilState::default();
938        assert_eq!(state.depth_compare, CompareOp::Greater);
939        assert_eq!(state.format, Format::D32Float);
940        assert_eq!(ClearValue::default().depth, crcbl_hal::depth::CLEAR);
941
942        // Geometry anywhere in front of the camera beats the cleared buffer
943        // under `Greater`. Under a conventional projection it would not: a
944        // fragment at depth 0.003 fails `Greater` against a clear of 0.0 only
945        // marginally, and the *far* geometry would win instead — which is the
946        // bug this arrangement exists to make impossible.
947        let camera = reversed();
948        for distance in [0.11f32, 1.0, 50.0, 5_000.0] {
949            let depth = camera
950                .depth_of(Vec3::new(0.0, 0.0, -distance), ASPECT)
951                .expect("in front");
952            assert!(
953                depth > ClearValue::default().depth,
954                "geometry at {distance} m must beat the cleared far plane, got {depth}"
955            );
956        }
957    }
958
959    /// Milestone 5's claim, checked: **nothing but the projection changes**.
960    #[test]
961    fn switching_to_orthographic_changes_only_the_projection() {
962        let perspective = Camera::default();
963        let ortho = perspective.with_projection(Projection::Orthographic {
964            half_height: 1.0,
965            near: 0.1,
966            far: 100.0,
967        });
968
969        assert_eq!(perspective.eye, ortho.eye);
970        assert_eq!(perspective.target, ortho.target);
971        assert_eq!(perspective.up, ortho.up);
972        assert_eq!(
973            perspective.view(),
974            ortho.view(),
975            "the view matrix is a property of where the camera is, not of how it projects"
976        );
977        assert!(!perspective.projection.is_orthographic());
978        assert!(ortho.projection.is_orthographic());
979        assert_ne!(
980            perspective.view_projection(ASPECT),
981            ortho.view_projection(ASPECT)
982        );
983    }
984
985    /// The 2D story: **z is a z-index**, and a larger z draws on top.
986    ///
987    /// With the engine's `Greater` depth test, "on top" means "larger depth
988    /// value", so a sprite at z = 5 must produce a larger depth than one at
989    /// z = 1. Under an unreversed orthographic projection it would produce a
990    /// *smaller* one and the layering would silently invert — which is exactly
991    /// the bug a 2D sample would spend an afternoon on.
992    #[test]
993    fn orthographic_depth_makes_a_larger_z_draw_on_top() {
994        let camera = Camera {
995            eye: Vec3::new(0.0, 0.0, 100.0),
996            target: Vec3::ZERO,
997            up: Vec3::Y,
998            projection: Projection::Orthographic {
999                half_height: 10.0,
1000                near: 0.1,
1001                far: 200.0,
1002            },
1003        };
1004
1005        let mut previous = f32::NEG_INFINITY;
1006        for z_index in [0.0f32, 1.0, 2.0, 5.0, 20.0] {
1007            let depth = camera
1008                .depth_of(Vec3::new(0.0, 0.0, z_index), ASPECT)
1009                .expect("orthographic w is always 1");
1010            assert!(
1011                (0.0..=1.0).contains(&depth),
1012                "z-index {z_index} projected outside the depth range: {depth}"
1013            );
1014            assert!(
1015                depth > previous,
1016                "z-index {z_index} gave depth {depth}, which does not beat {previous}; \
1017                 a larger z must draw on top under the seam's `Greater` test"
1018            );
1019            previous = depth;
1020        }
1021    }
1022
1023    /// Orthographic depth is *linear*, which is what makes a z-index usable as
1024    /// an integer layer number at all.
1025    #[test]
1026    fn orthographic_depth_is_linear_in_z() {
1027        let camera = Camera {
1028            eye: Vec3::new(0.0, 0.0, 100.0),
1029            target: Vec3::ZERO,
1030            up: Vec3::Y,
1031            projection: Projection::Orthographic {
1032                half_height: 10.0,
1033                near: 0.0,
1034                far: 100.0,
1035            },
1036        };
1037        let depth = |z: f32| {
1038            camera
1039                .depth_of(Vec3::new(0.0, 0.0, z), ASPECT)
1040                .expect("orthographic w is always 1")
1041        };
1042        let step = depth(1.0) - depth(0.0);
1043        for z in [1.0f32, 2.0, 10.0, 50.0] {
1044            let measured = depth(z + 1.0) - depth(z);
1045            assert!(
1046                (measured - step).abs() < 1e-6,
1047                "the depth step at z={z} is {measured}, not the constant {step}"
1048            );
1049        }
1050        assert!(step > 0.0, "successive layers must increase in depth");
1051    }
1052
1053    /// The aspect ratio changes what is visible horizontally and never squashes
1054    /// the picture — the property a resize depends on.
1055    #[test]
1056    fn a_wider_viewport_shows_more_world_and_does_not_stretch_it() {
1057        for projection in [
1058            Projection::default(),
1059            Projection::Orthographic {
1060                half_height: 1.0,
1061                near: 0.1,
1062                far: 10.0,
1063            },
1064        ] {
1065            let square = projection.matrix(1.0);
1066            let wide = projection.matrix(2.0);
1067            // The vertical scale is untouched; only the horizontal one changes.
1068            assert!(
1069                (square.y_axis.y - wide.y_axis.y).abs() < 1e-6,
1070                "{projection:?}"
1071            );
1072            assert!(wide.x_axis.x < square.x_axis.x, "{projection:?}");
1073        }
1074    }
1075
1076    /// A camera that cannot see is a caller bug, and a NaN matrix is a blank
1077    /// screen with no error. Both are panics rather than silent output.
1078    #[test]
1079    #[should_panic(expected = "aspect ratio")]
1080    fn a_zero_aspect_ratio_is_refused() {
1081        let _ = Projection::default().matrix(0.0);
1082    }
1083
1084    #[test]
1085    #[should_panic(expected = "near plane")]
1086    fn a_zero_near_plane_is_refused() {
1087        let _ = Projection::Perspective {
1088            fov_y: FRAC_PI_4,
1089            near: 0.0,
1090        }
1091        .matrix(ASPECT);
1092    }
1093
1094    #[test]
1095    #[should_panic(expected = "must be beyond near")]
1096    fn an_inverted_orthographic_range_is_refused() {
1097        let _ = Projection::Orthographic {
1098            half_height: 1.0,
1099            near: 10.0,
1100            far: 1.0,
1101        }
1102        .matrix(ASPECT);
1103    }
1104
1105    /// The default light points *at* something rather than away from it, is
1106    /// unit length so the shader's `dot` is a cosine, and is bright enough that
1107    /// the HDR target has something to carry.
1108    #[test]
1109    fn the_default_light_is_normalised_and_has_headroom() {
1110        let light = DirectionalLight::default();
1111        assert!((light.direction.length() - 1.0).abs() < 1e-6);
1112        assert!(
1113            light.ambient.min_element() > 0.0,
1114            "an unlit face must not be black"
1115        );
1116        assert!(
1117            light.ambient.max_element() < 0.5,
1118            "ambient must not flatten the shading"
1119        );
1120
1121        // **HDR from P1 needs something above 1.0 to carry.** The brightest
1122        // albedo in the engine's demo cube is 0.9, so an intensity below
1123        // `1 / 0.9` could never push any surface past what an `Rgba8` target
1124        // holds, and the e2e suite's HDR assertion would be checking a format
1125        // enum rather than a pipeline.
1126        assert!(
1127            light.color.max_element() > 1.0 / 0.9,
1128            "the key light must have HDR headroom, got {:?}",
1129            light.color
1130        );
1131
1132        // And it comes from the camera's side, so the faces the default camera
1133        // can see are the faces it lights.
1134        let to_camera = Camera::default().eye.normalize();
1135        assert!(
1136            light.direction.dot(to_camera) > 0.0,
1137            "a key light pointing away from every visible face renders an \
1138             unlit cube: light {:?} against camera {to_camera:?}",
1139            light.direction
1140        );
1141    }
1142
1143    /// A point behind the eye is not in front of the camera, and `depth_of`
1144    /// says so. The guard used to be `w.abs()`, which handed back a plausible
1145    /// negative depth for geometry the frustum does not contain — and the doc
1146    /// comment above it said the opposite.
1147    #[test]
1148    fn a_point_behind_the_eye_has_no_depth() {
1149        let camera = reversed();
1150        // The camera sits at the origin looking down -Z, so anything at
1151        // positive Z is behind it and the eye itself is on the eye plane.
1152        assert_eq!(camera.depth_of(Vec3::new(0.0, 0.0, 10.0), ASPECT), None);
1153        assert_eq!(camera.depth_of(camera.eye, ASPECT), None);
1154        assert!(camera.depth_of(Vec3::new(0.0, 0.0, -1.0), ASPECT).is_some());
1155    }
1156
1157    /// An orthographic camera has no eye plane, so every point projects.
1158    #[test]
1159    fn an_orthographic_camera_projects_everything() {
1160        let camera = reversed().with_projection(Projection::Orthographic {
1161            half_height: 2.0,
1162            near: 0.1,
1163            far: 100.0,
1164        });
1165        assert!(
1166            camera.depth_of(Vec3::new(0.0, 0.0, 10.0), ASPECT).is_some(),
1167            "an orthographic camera has no eye plane to be behind"
1168        );
1169    }
1170
1171    /// A degenerate basis makes `look_at` divide by a zero-length vector and
1172    /// return `NaN`s, which reach the shader as a blank screen and no error.
1173    /// Every other degenerate input to this module is asserted; so is this one.
1174    #[test]
1175    #[should_panic(expected = "parallel to its view direction")]
1176    fn an_up_vector_along_the_view_direction_panics() {
1177        let camera = Camera {
1178            eye: Vec3::new(0.0, 0.0, 2.0),
1179            target: Vec3::ZERO,
1180            up: Vec3::Z,
1181            projection: Projection::default(),
1182        };
1183        let _ = camera.view();
1184    }
1185
1186    #[test]
1187    #[should_panic(expected = "up vector must be non-zero")]
1188    fn a_zero_up_vector_panics() {
1189        let camera = Camera {
1190            up: Vec3::ZERO,
1191            ..Camera::default()
1192        };
1193        let _ = camera.view();
1194    }
1195
1196    #[test]
1197    #[should_panic(expected = "must look somewhere")]
1198    fn a_camera_looking_at_its_own_eye_panics() {
1199        let camera = Camera {
1200            target: Vec3::new(0.0, 0.0, 2.0),
1201            ..Camera::default()
1202        };
1203        let _ = camera.view();
1204    }
1205
1206    /// **Every projection this module builds inverts to the sparsity the
1207    /// screen-space shaders read**, and the reduced form they use is the same
1208    /// value rather than a close one.
1209    ///
1210    /// `ssao.slang`'s `unproject` — copied verbatim into `ssao_blur.slang`,
1211    /// `ssr.slang`, `ssr_blur.slang` and `contact_shadows.slang`, and held
1212    /// together by `crcbl_shaders::ssr`'s drift guard — keeps four terms of
1213    /// `mul(inv_proj, float4(ndc, depth, 1.0))` and drops the rest, because
1214    /// those entries are zero for both variants of [`Projection`]. Nothing on
1215    /// the shader side can check that: a projection that broke the pattern
1216    /// would reconstruct positions from the wrong entries and draw a wrong
1217    /// picture on hardware, with no error anywhere. So it is checked here,
1218    /// where the projections are built and where a third variant would be
1219    /// added.
1220    ///
1221    /// The comparison is on **bits** rather than a tolerance, because the claim
1222    /// is that the two forms agree exactly — dropping a term that is exactly
1223    /// zero changes nothing, and a tolerance would also pass on one that had
1224    /// drifted to a denormal, which is the case this exists to catch.
1225    ///
1226    /// What it cannot catch is a reduction reading the *wrong* entry, because
1227    /// several of the ones it reads hold the same value in every matrix
1228    /// reachable from here. That is
1229    /// [`the_screen_space_unprojection_is_the_full_product_for_that_sparsity`],
1230    /// which is where the entries are told apart.
1231    #[test]
1232    fn every_projection_inverts_to_the_sparsity_the_screen_space_shaders_read() {
1233        // The entries `unproject` does not read, as (row, column). Every one of
1234        // them must be exactly zero for the four terms it keeps to be the whole
1235        // product.
1236        const DROPPED: [(usize, usize); 8] = [
1237            (0, 1),
1238            (0, 2),
1239            (1, 0),
1240            (1, 2),
1241            (2, 0),
1242            (2, 1),
1243            (3, 0),
1244            (3, 1),
1245        ];
1246
1247        let projections = [
1248            (Projection::default(), ASPECT),
1249            (
1250                Projection::Perspective {
1251                    fov_y: FRAC_PI_4,
1252                    near: 0.1,
1253                },
1254                1264.0 / 1370.0,
1255            ),
1256            (
1257                Projection::Perspective {
1258                    fov_y: 0.3,
1259                    near: 5.0,
1260                },
1261                0.5,
1262            ),
1263            (
1264                Projection::Perspective {
1265                    fov_y: 2.9,
1266                    near: 0.001,
1267                },
1268                3.7,
1269            ),
1270            (
1271                Projection::Orthographic {
1272                    half_height: 10.0,
1273                    near: 0.1,
1274                    far: 1000.0,
1275                },
1276                ASPECT,
1277            ),
1278            (
1279                Projection::Orthographic {
1280                    half_height: 0.5,
1281                    near: 1.0,
1282                    far: 2.0,
1283                },
1284                0.25,
1285            ),
1286        ];
1287
1288        for (projection, aspect) in projections {
1289            let inverse = projection.matrix(aspect).inverse();
1290            let columns = inverse.to_cols_array();
1291            // `to_cols_array` is column-major; the shader indexes
1292            // `inv_proj[row][column]`, which is the logical element whichever
1293            // way the target packs the block.
1294            let at = |row: usize, column: usize| columns[column * 4 + row];
1295
1296            for (row, column) in DROPPED {
1297                assert_eq!(
1298                    at(row, column),
1299                    0.0,
1300                    "{projection:?} at aspect {aspect} inverts with a non-zero at \
1301                     ({row}, {column}), which `unproject` in the screen-space shaders drops"
1302                );
1303            }
1304
1305            for ndc in [
1306                glam::Vec2::ZERO,
1307                glam::Vec2::new(-1.0, -1.0),
1308                glam::Vec2::new(1.0, 1.0),
1309                glam::Vec2::new(-0.731, 0.269),
1310            ] {
1311                for depth in [0.0, crcbl_hal::depth::NEAR, 0.5, 1.0e-4] {
1312                    let full = inverse * glam::Vec4::new(ndc.x, ndc.y, depth, 1.0);
1313                    let reduced = glam::Vec4::new(
1314                        at(0, 0) * ndc.x + at(0, 3),
1315                        at(1, 1) * ndc.y + at(1, 3),
1316                        at(2, 2) * depth + at(2, 3),
1317                        at(3, 2) * depth + at(3, 3),
1318                    );
1319                    assert_eq!(
1320                        full.to_array().map(f32::to_bits),
1321                        reduced.to_array().map(f32::to_bits),
1322                        "{projection:?} at aspect {aspect}: the shaders' reduced unprojection \
1323                         of {ndc:?} at depth {depth} is not the full product {full:?}"
1324                    );
1325                }
1326            }
1327        }
1328    }
1329
1330    /// **The other half of the claim above**: given that sparsity, the four
1331    /// terms the shaders keep are the whole product — the right entries against
1332    /// the right components.
1333    ///
1334    /// Separate from
1335    /// [`every_projection_inverts_to_the_sparsity_the_screen_space_shaders_read`]
1336    /// because the two guard different things, and because that one **cannot**
1337    /// guard this. Every matrix it can reach has `(0, 3)` and `(1, 3)` at zero
1338    /// — an infinite reversed-Z perspective is centred, and [`Projection`]
1339    /// builds only a symmetric orthographic box — so a copy reading one of
1340    /// those two in place of the other draws exactly the same frame and passes
1341    /// it. Confirmed by mutating the reduction there and watching it stay
1342    /// green, which is why this exists.
1343    ///
1344    /// So the matrix here is **synthetic**, with a different value in each of
1345    /// the eight slots the reduction reads and a zero everywhere else. Nothing
1346    /// builds one like it today; the point is that every kept term is
1347    /// distinguishable, so an index that swapped two of them fails here rather
1348    /// than waiting for the projection that first tells them apart. A jittered
1349    /// projection is that projection — which is why `unproject` keeps the two
1350    /// additions the engine's own matrices would let it drop.
1351    #[test]
1352    fn the_screen_space_unprojection_is_the_full_product_for_that_sparsity() {
1353        // Column-major, as `Mat4::from_cols_array` takes it and
1354        // `to_cols_array` gives it back. Reading down the columns, the
1355        // non-zero entries are (0,0), (1,1), (2,2), (3,2) and the whole last
1356        // column — the eight `unproject` reads.
1357        let sparse = Mat4::from_cols_array(&[
1358            2.5, 0.0, 0.0, 0.0, //
1359            0.0, -3.25, 0.0, 0.0, //
1360            0.0, 0.0, 0.75, -1.5, //
1361            0.125, -0.375, 4.5, 1.25,
1362        ]);
1363        let columns = sparse.to_cols_array();
1364        let at = |row: usize, column: usize| columns[column * 4 + row];
1365
1366        for ndc in [
1367            glam::Vec2::new(-0.731, 0.269),
1368            glam::Vec2::new(0.5, -0.125),
1369            glam::Vec2::new(1.0, -1.0),
1370        ] {
1371            for depth in [crcbl_hal::depth::NEAR, 0.375, 1.0e-4] {
1372                let full = sparse * glam::Vec4::new(ndc.x, ndc.y, depth, 1.0);
1373                let reduced = glam::Vec4::new(
1374                    at(0, 0) * ndc.x + at(0, 3),
1375                    at(1, 1) * ndc.y + at(1, 3),
1376                    at(2, 2) * depth + at(2, 3),
1377                    at(3, 2) * depth + at(3, 3),
1378                );
1379                assert_eq!(
1380                    full.to_array().map(f32::to_bits),
1381                    reduced.to_array().map(f32::to_bits),
1382                    "the shaders' reduced unprojection of {ndc:?} at depth {depth} is not the \
1383                     full product {full:?}"
1384                );
1385            }
1386        }
1387    }
1388
1389    // ── Screen to ray ──────────────────────────────────────────────────────
1390
1391    /// The extent every ray test shoots through: not square, so a transposed
1392    /// aspect or a swapped axis is a different answer rather than the same one.
1393    const VIEWPORT: (u32, u32) = (800, 600);
1394
1395    /// The centre of `VIEWPORT`, as a pixel coordinate.
1396    fn centre() -> Vec2 {
1397        Vec2::new(VIEWPORT.0 as f32, VIEWPORT.1 as f32) * 0.5
1398    }
1399
1400    /// An off-centre camera, so a ray test that quietly ignored the view matrix
1401    /// would answer in the wrong space.
1402    fn perspective() -> Camera {
1403        Camera {
1404            eye: Vec3::new(3.0, 4.0, 5.0),
1405            target: Vec3::new(-1.0, 0.5, 0.0),
1406            up: Vec3::Y,
1407            projection: Projection::Perspective {
1408                fov_y: FRAC_PI_4,
1409                near: 0.25,
1410            },
1411        }
1412    }
1413
1414    /// **The ray through a pixel projects back to that pixel**, through
1415    /// [`Camera::pixel_of`].
1416    ///
1417    /// The round trip against [`Camera::view_projection`], which is the only
1418    /// check here that could catch a sign, an axis or an aspect applied twice —
1419    /// every one of those still yields a plausible-looking unit direction. The
1420    /// Y convention both share is held on its own below.
1421    #[test]
1422    fn a_pixels_ray_projects_back_to_that_pixel() {
1423        for at in [
1424            Vec2::new(0.5, 0.5),
1425            centre(),
1426            Vec2::new(11.5, 523.5),
1427            Vec2::new(799.5, 0.5),
1428            Vec2::new(640.5, 480.5),
1429        ] {
1430            let ray = perspective().ray_through(at, VIEWPORT);
1431            for distance in [0.5_f32, 7.0, 250.0] {
1432                let pixel = perspective()
1433                    .pixel_of(ray.origin + ray.direction * distance, VIEWPORT)
1434                    .expect("a point along the ray is in front of the eye");
1435                assert!(
1436                    (pixel - at).length() < 1e-2,
1437                    "the ray through {at:?} reached {pixel:?} {distance} m along itself",
1438                );
1439            }
1440        }
1441    }
1442
1443    /// **The window's +Y is down and clip space's is up.**
1444    ///
1445    /// The one conversion in [`Camera::ray_through`] that is a convention
1446    /// rather than arithmetic, and the one a reader cannot check by inspection.
1447    /// A camera looking down `-Z` with `+Y` up: the top of the window has to be
1448    /// the `+Y` half of the world and the left of it the `-X` half.
1449    #[test]
1450    fn the_top_left_pixel_is_up_and_to_the_left_in_the_world() {
1451        let camera = Camera {
1452            eye: Vec3::ZERO,
1453            target: -Vec3::Z,
1454            up: Vec3::Y,
1455            projection: Projection::Perspective {
1456                fov_y: FRAC_PI_4,
1457                near: 0.1,
1458            },
1459        };
1460        let top_left = camera.ray_through(Vec2::new(0.5, 0.5), VIEWPORT);
1461        assert!(
1462            top_left.direction.y > 0.0,
1463            "the top of the window must look up, got {:?}",
1464            top_left.direction,
1465        );
1466        assert!(
1467            top_left.direction.x < 0.0,
1468            "the left of the window must look left, got {:?}",
1469            top_left.direction,
1470        );
1471        let bottom_right = camera.ray_through(Vec2::new(799.5, 599.5), VIEWPORT);
1472        assert!(bottom_right.direction.y < 0.0 && bottom_right.direction.x > 0.0);
1473    }
1474
1475    /// A point behind the eye lands on no pixel, rather than on the mirrored
1476    /// one the divide by a negative `w` would give.
1477    #[test]
1478    fn a_point_behind_the_eye_lands_on_no_pixel() {
1479        let camera = perspective();
1480        let behind = camera.eye + (camera.eye - camera.target);
1481        assert_eq!(camera.pixel_of(behind, VIEWPORT), None);
1482        assert!(camera.pixel_of(camera.target, VIEWPORT).is_some());
1483    }
1484
1485    /// **The ray starts on the near plane**, which is what
1486    /// [`Camera::ray_through`] promises rather than "at the eye" — and under
1487    /// [`Projection::Orthographic`] the two are not even the same kind of
1488    /// thing.
1489    #[test]
1490    fn the_ray_begins_at_the_near_plane_depth() {
1491        for camera in [
1492            perspective(),
1493            Camera {
1494                projection: Projection::Orthographic {
1495                    half_height: 3.0,
1496                    near: 0.5,
1497                    far: 40.0,
1498                },
1499                ..perspective()
1500            },
1501        ] {
1502            let ray = camera.ray_through(Vec2::new(210.5, 99.5), VIEWPORT);
1503            let depth = camera
1504                .depth_of(ray.origin, VIEWPORT.0 as f32 / VIEWPORT.1 as f32)
1505                .expect("the near plane is in front of the eye");
1506            assert!(
1507                (depth - crcbl_hal::depth::NEAR).abs() < 1e-4,
1508                "the ray started at depth {depth}, not the near plane",
1509            );
1510        }
1511    }
1512
1513    /// **An orthographic viewport's rays are parallel**, and a perspective
1514    /// one's are not. The projection is the only thing that differs between the
1515    /// two halves, so this is what says the unprojection reads it at all.
1516    #[test]
1517    fn an_orthographic_camera_shoots_parallel_rays_and_a_perspective_one_does_not() {
1518        let orthographic = Camera {
1519            projection: Projection::Orthographic {
1520                half_height: 3.0,
1521                near: 0.5,
1522                far: 40.0,
1523            },
1524            ..perspective()
1525        };
1526        let left = Vec2::new(40.5, 300.5);
1527        let right = Vec2::new(760.5, 300.5);
1528        let spread = |camera: &Camera| {
1529            camera
1530                .ray_through(left, VIEWPORT)
1531                .direction
1532                .dot(camera.ray_through(right, VIEWPORT).direction)
1533        };
1534        assert!(
1535            (spread(&orthographic) - 1.0).abs() < 1e-5,
1536            "orthographic rays must be parallel, got a dot of {}",
1537            spread(&orthographic),
1538        );
1539        assert!(
1540            spread(&perspective()) < 0.95,
1541            "perspective rays must diverge, got a dot of {}",
1542            spread(&perspective()),
1543        );
1544        // Their origins still differ: an orthographic camera moves the ray
1545        // rather than turning it.
1546        assert!(
1547            orthographic
1548                .ray_through(left, VIEWPORT)
1549                .origin
1550                .distance(orthographic.ray_through(right, VIEWPORT).origin)
1551                > 1.0
1552        );
1553    }
1554
1555    /// The direction is unit length, which is what makes a hit's parametric
1556    /// distance a distance in metres.
1557    #[test]
1558    fn the_direction_is_unit_length() {
1559        let ray = perspective().ray_through(Vec2::new(1.5, 599.5), VIEWPORT);
1560        assert!((ray.direction.length() - 1.0).abs() < 1e-6);
1561    }
1562
1563    /// A viewport with no pixels in it has no pixel to shoot through, and says
1564    /// so rather than handing back a `NaN` ray.
1565    #[test]
1566    #[should_panic(expected = "zero side")]
1567    fn a_viewport_with_a_zero_side_is_refused() {
1568        let _ = perspective().ray_through(centre(), (800, 0));
1569    }
1570}