From 063aae43771c5f773da736512f1c3724c5782920 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:02:19 -0800 Subject: [PATCH 1/4] craft-raster3d: return camera depth, view-space normal and part ID for each pixel try_render_with_aux, try_render_cpu_with_aux and try_resolve_aux also return, for each pixel, the camera depth, the unit view-space normal and the part ID of the nearest opaque surface, or of a nearer transparent fragment that added color. The fallback pass under discarded opaque pixels records the same outputs for the fragment it draws. Also: a corner on the near plane keeps a depth of 1 when w * (1 / w) rounds below 1, a near-plane crossing in the shadow pass takes its fraction in f64 when the difference overflows f32, and a shadow triangle with an empty texel range returns early. --- crates/raster3d/README.md | 54 +- crates/raster3d/src/lib.rs | 69 ++- crates/raster3d/src/raster.rs | 367 +++++++++++-- crates/raster3d/src/resolve.rs | 101 +++- crates/raster3d/src/scene.rs | 128 +++++ crates/raster3d/src/shade.rs | 39 ++ crates/raster3d/src/shadow.rs | 41 +- crates/raster3d/tests/it/aux_outputs.rs | 506 ++++++++++++++++++ crates/raster3d/tests/it/bounds.rs | 7 +- crates/raster3d/tests/it/differential.rs | 15 +- crates/raster3d/tests/it/main.rs | 1 + .../tests/it/reference/effectcraft/raster.rs | 6 + 12 files changed, 1262 insertions(+), 72 deletions(-) create mode 100644 crates/raster3d/tests/it/aux_outputs.rs diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 4e0e9600ed..98160be6f9 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -57,8 +57,8 @@ Building a scene from an app's document (layers, cameras, models, text) stays in `TexInfo` gives a texture's offset, size and wrap modes (repeat, clamp or mirror). `sample` is a bilinear lookup with texel centers at +0.5. - **Shadow maps.** `try_shadow_maps(&mut scene, draft, &limits)` renders the light-space depth of - every triangle whose material casts shadows into one map per parallel or spot light, six per - point light and one orthographic map for the environment light's dominant direction, for every + every triangle whose material casts shadows into one map per parallel light, one per spot light + (six for a wide spot light, below), six per point light and one orthographic map for the environment light's dominant direction, for every light whose `shadow` is 0 or more. The shader compares each receiver with the nearest depth in the map () over a jittered grid of 5 × 5 to 10 × 10 taps, each a bilinear comparison against the receiver's @@ -86,13 +86,34 @@ Building a scene from an app's document (layers, cameras, models, text) stays in - **Resolve and encoding.** `try_resolve(&target, k)` averages each `k × k` block of premultiplied pixels with equal weights, and takes the mean depth of the block's covered pixels, infinity where none is covered; a pixel whose `f32` sums overflow, and every pixel when a block holds more than - 2^24 subsamples, is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer + 256 subsamples (`k` over 16), is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer function of CSS Color 4 (), a linear segment up to a magnitude of 0.0031308 and a 1/2.4 power above it, with a negative color keeping its sign, multiplies by alpha again and leaves alpha linear. `srgb_to_linear` decodes a negative value the same way. Pixels with alpha of 1e-6 or less are left as they are. `try_render_cpu` renders and resolves by `Scene::ssaa`, and rejects a factor that does not divide the raster size before it renders. +- **Auxiliary outputs.** `try_render_with_aux`, `try_resolve_aux` and `try_render_cpu_with_aux` + return the same color as `try_render`, `try_resolve` and `try_render_cpu`, bit for bit, and + `AuxPlanes`: three planes at the color's size, row-major from the top row, that describe one + surface per pixel. `depth` is the surface's camera depth (`f32`, the units of `Scene::view`), + infinity where empty. `normal` is its unit normal in view space, `[0, 0, 0]` where empty: the + vertex normal interpolated in `f64` (one of length 1e-20 or less is read as `[0, 0, −1]`), + reversed on a back face, turned by the inverse transpose of the upper-left 3 × 3 of `Scene::view` and + normalized, so it stays perpendicular to the surface when the view scales axes unequally or + shears; normal textures are not applied. `part_id` is the `Scene::part_ids` entry of the + surface's triangle (`u32`), or `NO_PART` (`u32::MAX`) where empty; a triangle cut by clipping keeps its ID. Only a fragment that + adds alpha above 0 can be the surface: the nearest opaque surface drawn at the pixel, including + the one found under a discarded fragment, or a nearer transparent fragment; of several such + fragments the nearest is kept. `depth` therefore differs from `Target::depth`, which holds opaque surfaces only. The + resolve copies the depth, normal and part ID of one subsample of each block, the one with the + smallest depth (the first in row-major order on ties), so it does not average depths across + surfaces or mix IDs; a pixel holds one ID, not every surface that covers part of it. + `try_render_with_aux` and `try_render_cpu_with_aux` need one part ID per triangle, none of them + `NO_PART`, and, for a scene with a triangle, a view whose upper-left 3 × 3 is invertible. + `try_resolve_aux` takes no scene: it needs a factor that divides both sides, as `try_resolve` + does, and planes that each hold width × height values. The other functions do not read + `Scene::part_ids` and do not allocate the planes. - **Limits.** `Limits` caps the raster pixels (2^24), the triangles of a scene (2^22), its vertices, used or not (3 × 2^22), the lights (1024) and the coverage tests of the visibility, transparent and fallback passes (2^31). Preparation counts every clipped triangle's bounding-box pixels plus one per triangle; fallback tests count @@ -121,8 +142,14 @@ Building a scene from an app's document (layers, cameras, models, text) stays in pixel that is not finite, an alpha below 0 or above 1 (beyond 1e-4 of rounding), or a color whose division by alpha overflows, and changes no pixel then; the error names the first such pixel. The renderer holds 40 bytes per raster pixel (color, depth and visibility) and up to seven clipped triangles of about 140 bytes per - scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 29 bytes per pixel - (a discard flag and a candidate fragment) while its opaque pixels are shaded. The search for a + scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 45 bytes per pixel + (a discard flag and a candidate fragment with its triangle and weights) while its opaque pixels + are shaded. With auxiliary outputs the renderer holds 20 bytes more per raster pixel, and + `try_render_cpu_with_aux` also 40 bytes per output pixel for the resolve; the sum must fit + `isize::MAX` bytes, or the call returns `TooLarge` before it allocates. `try_render_with_aux` + returns `BadPartIdCount`, `ReservedPartId` or `BadTransform` for the part IDs and view above, and + `BadPixel` when an auxiliary depth overflows `f32`; `try_resolve_aux` returns `BadDataLength` for + a plane of the wrong length. The search for a surviving fragment under discarded opaque pixels visits each opaque triangle's bounding box once more, so it runs no more coverage tests than the visibility pass. Its tests count toward `max_work`, and it can return `TooMuchWork` after the target is allocated. @@ -140,7 +167,7 @@ far plane, where depth-range crossings lie within 1/4096 of an edge from its ins texture coordinates times the texture's width or height reach 2^23 in magnitude, where normals' squared lengths, squared distances from fragments to point and spot lights, or casters' light-space coordinates times a map's focal length overflow `f32`, where shadow-casting spot -lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 2^24 +lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 256 subsamples, where shadows-only materials do not receive shadows, where fragments under discarded opaque pixels leave the depth range, where blended casters have no base texture, where opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of @@ -174,7 +201,8 @@ Changes from those files: same order over their bounding boxes. EffectCraft searched every triangle of the pixel's band of 16 rows for each such pixel, which the work limit could not bound. The search takes only fragments inside the depth range, as the visibility pass does; EffectCraft also took a fragment - whose interpolated depth rounded past 1. + whose interpolated depth rounded past 1. A clipped corner whose clip-space z equals its w is + projected to a depth of exactly 1, also where `w * (1 / w)` rounds below 1. - A shadows-only material that does not receive shadows draws nothing. EffectCraft drew the shadows on it. - A triangle in the opaque range whose material is shadows-only and visible is an error. @@ -191,15 +219,17 @@ Changes from those files: sign kept, as CSS Color 4's conversion code does. EffectCraft put every negative value on the linear segment, so red −0.25 encoded to −3.23 instead of about −0.537. - A normal whose squared length overflows `f32`, and the direction to a point or spot light whose - squared distance overflows `f32`, are normalized in `f64`. EffectCraft divided them by an + coordinate difference or squared distance overflows `f32`, are normalized in `f64`. EffectCraft divided them by an infinite length, so the surface took no direct light. - A caster corner or a receiver whose light-space coordinate times the map's focal length overflows `f32` is projected in `f64`. EffectCraft's map coordinates for it were infinite. - A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps, as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest of the cone were not shadowed. -- A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of - covered subsamples stopped at 2^24, which raised the mean depth. +- A resolve block of more than 256 subsamples is averaged in `f64`. EffectCraft summed every block + in `f32`: its sums dropped the low bits of each subsample as they grew (a 4096 × 4096 block of + 0.75 resolved to about 0.833), and its count of covered subsamples stopped at 2^24, which raised + the mean depth. - A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest values) is projected in `f64` instead of dropping its triangle, and a drawn pixel whose camera depth overflows is an error. @@ -264,6 +294,8 @@ Changes from those files: EffectCraft replaces `adv::raster::render` with `try_render`, `adv::resolve` with `try_resolve`, `adv::encode` with `try_encode`, `adv::render_cpu` with `try_render_cpu`, and `raster::shadow_maps` with `try_shadow_maps`, and maps a `RenderError` to a render failure. Its -scene builder fills `craft_raster3d::Scene`, whose fields are those of its `adv::scene::Scene`. +scene builder fills `craft_raster3d::Scene`, whose fields are those of its `adv::scene::Scene` +plus `part_ids`. A struct literal for the baseline renderers sets `part_ids: Vec::new()`; a caller +of the auxiliary renderers supplies one ID per triangle. The BRDF and the environment BRDF stay as they are here until a separate change moves them to `craft-pbr`, whose results differ (a roughness floor of 0.032 and a clamped environment BRDF). diff --git a/crates/raster3d/src/lib.rs b/crates/raster3d/src/lib.rs index a5d25d295a..3304f6f2df 100644 --- a/crates/raster3d/src/lib.rs +++ b/crates/raster3d/src/lib.rs @@ -23,13 +23,21 @@ //! - **Textures.** [`Scene::texels`] holds linear straight RGBA, row-major from the top row; //! [`TexInfo`] gives each texture's span and wrap modes. //! -//! [`try_render`], [`try_render_cpu`] and [`try_shadow_maps`] check the scene against [`Limits`] and return a -//! [`RenderError`] before they allocate a target: malformed indices, references and spans, -//! values that are not finite, sizes, triangle counts, light counts and the coverage work of -//! setup. A light kind or falloff mode outside 0 to 2 returns [`RenderError::BadLight`]. -//! A pass that runs over `max_work` while rendering also returns -//! [`RenderError::TooMuchWork`]. [`try_resolve`], [`try_encode`] and [`try_env_shadow_map`] check -//! their own inputs and sizes before they allocate. Rows run on several threads with rayon. +//! [`try_render`], [`try_render_with_aux`], [`try_render_cpu`], [`try_render_cpu_with_aux`] and +//! [`try_shadow_maps`] check the scene against [`Limits`] and return a [`RenderError`] before they +//! allocate a target: malformed indices, references and spans, values that are not finite, sizes, +//! triangle counts, light counts and the coverage work of setup. A light kind or falloff mode +//! outside 0 to 2 returns [`RenderError::BadLight`]. A pass that runs over `max_work` while +//! rendering also returns [`RenderError::TooMuchWork`]. [`try_resolve`], [`try_resolve_aux`], +//! [`try_encode`] and [`try_env_shadow_map`] check their own inputs and sizes before they allocate. +//! Rows run on several threads with rayon. +//! +//! **Auxiliary outputs.** [`try_render_with_aux`], [`try_resolve_aux`] and +//! [`try_render_cpu_with_aux`] also return, for each pixel, the camera depth, the unit view-space +//! normal and the part ID ([`Scene::part_ids`]) of one surface: the nearest opaque surface drawn +//! there, or a nearer transparent fragment that added color. Each plane is row-major from the top +//! row at the color's size; an empty pixel holds infinity, `[0, 0, 0]` and [`NO_PART`]. The +//! renderers without them do not allocate these planes. #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -39,9 +47,9 @@ mod scene; mod shade; mod shadow; -pub use raster::{GUARD_BAND, Target, try_render}; -pub use resolve::{Image, try_encode, try_render_cpu, try_resolve}; -pub use scene::{EnvInfo, Light, Material, Scene, ShadowMap, TexInfo, Vertex}; +pub use raster::{AuxPlanes, AuxTarget, GUARD_BAND, Target, try_render, try_render_with_aux}; +pub use resolve::{AuxImage, Image, try_encode, try_render_cpu, try_render_cpu_with_aux, try_resolve, try_resolve_aux}; +pub use scene::{EnvInfo, Light, Material, NO_PART, Scene, ShadowMap, TexInfo, Vertex}; pub use shade::{linear_to_srgb, sample, srgb_to_linear}; pub use shadow::{MAX_SHADOW_TEXELS, shadow_map_size, shadow_point_face_size, shadow_sizes, try_env_shadow_map, try_shadow_maps}; @@ -82,9 +90,17 @@ pub enum RenderError { /// A vertex's clip-space position is not finite. #[error("vertex {0} is outside the range the clip transform can hold")] BadClipPosition(usize), - /// The clip or view transform, the eye or the camera direction is not finite. - #[error("the camera transform is not finite")] + /// The clip or view transform, the eye or the camera direction is not finite, or (for the + /// auxiliary outputs of a scene with a triangle) the upper-left 3 × 3 of the view transform, + /// which turns normals to view space, is singular. + #[error("the camera transform is not finite or cannot turn normals to view space")] BadTransform, + /// [`Scene::part_ids`] does not hold one ID per triangle (auxiliary outputs). + #[error("the scene holds {found} part ids where {expected} triangles need one each")] + BadPartIdCount { expected: usize, found: usize }, + /// The part ID of a triangle (by index) is [`NO_PART`], which marks a pixel with no surface. + #[error("triangle {0} has the part id reserved for an empty pixel")] + ReservedPartId(usize), /// A material value is not finite or out of range (an alpha mode other than 0 to 2, or a /// metallic, roughness or occlusion strength outside 0 to 1, for example), or names a texture /// that does not exist. [`try_render`] also returns it for a visible transparent material @@ -100,7 +116,7 @@ pub enum RenderError { /// A light has a kind or falloff mode other than 0 to 2, a value that is not finite, a cone cosine outside −1 /// to 1, (a spot light) an inner cone cosine below the outer one, a shadow darkness outside 0 /// to 1, or (a parallel or spot light) a direction whose length differs from 1 by more than - /// 0.001. + /// 0.001, or (a point or spot light) an unknown falloff mode. #[error( "light {0} has an unknown kind or falloff mode, a value that is not finite, a cone cosine outside -1 to 1 or out of order, a shadow darkness outside 0 to 1 or a direction that is not unit length" )] @@ -150,7 +166,7 @@ pub enum RenderError { BadDataLength { expected: usize, found: usize }, /// A pixel's color is not finite, or its alpha is negative or over 1. [`try_render`] returns /// it for a rendered pixel whose color or depth overflowed `f32` (finite inputs near the top - /// of its range). + /// of its range), and [`try_render_with_aux`] also for an auxiliary depth or normal that did. #[error("pixel {0} has a color that is not finite or an alpha out of range")] BadPixel(usize), } @@ -205,4 +221,29 @@ impl Limits { } usize::try_from(pixels).map_err(|_| RenderError::TooLarge(w, h)) } + + /// [`Limits::check`] for a render with auxiliary outputs, which also holds + /// [`AUX_BYTES_PER_PIXEL`] more bytes per raster pixel and, when it is resolved by `k` per side + /// (`resolve` is `Some(k)`), [`AUX_BYTES_PER_OUTPUT`] per output pixel: the sum of all of them + /// must fit `isize::MAX`. Nothing is allocated. + pub(crate) fn check_aux(&self, w: u32, h: u32, resolve: Option) -> Result { + let pixels = self.check(w, h)?; + let raster = u64::from(w) * u64::from(h); + let out = resolve.map_or(0, |k| raster / u64::from(k.max(1)).pow(2)); + let bytes = raster + .checked_mul(BYTES_PER_PIXEL + AUX_BYTES_PER_PIXEL) + .and_then(|b| b.checked_add(out.checked_mul(AUX_BYTES_PER_OUTPUT)?)) + .ok_or(RenderError::TooLarge(w, h))?; + if bytes > MAX_ALLOC_BYTES { + return Err(RenderError::TooLarge(w, h)); + } + Ok(pixels) + } } + +/// Bytes the auxiliary outputs add per raster pixel: depth (4), normal (12) and part ID (4). +const AUX_BYTES_PER_PIXEL: u64 = 20; + +/// Bytes a resolve with auxiliary outputs holds per output pixel: color (16), the mean depth that +/// [`try_resolve`] computes (4), depth (4), normal (12) and part ID (4). +const AUX_BYTES_PER_OUTPUT: u64 = 40; diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index b03cbf4987..43409425d8 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -11,7 +11,7 @@ use std::sync::atomic::{AtomicU64, Ordering}; use rayon::prelude::*; -use crate::scene::{Scene, Vertex, validate, validate_passes, validate_shadow_refs}; +use crate::scene::{NO_PART, Scene, Vertex, validate, validate_aux, validate_passes, validate_shadow_refs}; use crate::shade::{Frag, shade}; use crate::{Limits, RenderError}; @@ -32,6 +32,59 @@ pub struct Target { pub depth: Vec, } +/// The auxiliary outputs of one surface per pixel, each row-major from the top row at the size +/// of the color they come with. +/// +/// The surface of a pixel is the nearest opaque surface drawn there (after an alpha test or a +/// single-sided back face hands the pixel to the next surface), or a transparent fragment that +/// adds alpha above 0 and is nearer in camera depth than the surface before it. All three planes +/// name the same surface. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct AuxPlanes { + /// Camera-space depth of the surface (the third row of [`Scene::view`]), ∞ where empty. For + /// a transparent surface this differs from [`Target::depth`], which holds opaque surfaces only. + pub depth: Vec, + /// Unit normal of the surface in view space, `[0, 0, 0]` where empty: the vertex normal + /// interpolated in `f64` (a vector of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face, + /// turned by the inverse transpose of the upper-left 3 × 3 of [`Scene::view`] and normalized, + /// so it stays perpendicular to the surface under a non-uniform scale or a shear. Normal + /// textures are not applied. + pub normal: Vec<[f32; 3]>, + /// [`Scene::part_ids`] of the surface's triangle, [`NO_PART`] where empty. + pub part_id: Vec, +} + +/// A rendered target with its auxiliary outputs at raster size. +#[derive(Clone, Debug, PartialEq)] +pub struct AuxTarget { + pub target: Target, + pub aux: AuxPlanes, +} + +/// One band's rows of the auxiliary planes. +struct AuxRow<'a> { + depth: &'a mut [f32], + normal: &'a mut [[f32; 3]], + part: &'a mut [u32], +} + +impl AuxRow<'_> { + /// Make (camera depth `z`, normal `n` and `part`) the surface of pixel `i`. + fn set(&mut self, i: usize, z: f32, n: [f32; 3], part: u32) { + self.depth[i] = z; + self.normal[i] = n; + self.part[i] = part; + } + + /// Make the surface of pixel `i` the given one when its camera depth `z` is nearer than the + /// pixel's (a NaN depth always replaces it, so the render reports it, and is never replaced). + fn offer(&mut self, i: usize, z: f32, n: impl FnOnce() -> [f32; 3], part: u32) { + if !self.depth[i].is_nan() && (z.is_nan() || z < self.depth[i]) { + self.set(i, z, n(), part); + } + } +} + /// A clipped triangle in screen space; `w` holds, per corner, its weights over the original /// triangle's three vertices. #[derive(Clone, Copy)] @@ -202,7 +255,9 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec, .map(|(c, wt)| { let iw = 1.0 / c[3]; let (nx, ny) = (c[0] * iw, c[1] * iw); - ([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], ndc_z(c[2] * iw), f64::from(iw), *wt) + // A corner on the near plane keeps a depth of 1 even when `w * (1 / w)` rounds below 1. + let z = if c[2] == c[3] { 1.0 } else { ndc_z(c[2] * iw) }; + ([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], z, f64::from(iw), *wt) }) .collect(); let ok = |s: &ScreenCorner| s.0.iter().all(|v| v.is_finite()) && s.1.is_finite() && s.2.is_finite(); @@ -405,6 +460,9 @@ struct Band<'a> { w: usize, spent: &'a AtomicU64, limit: u64, + /// The sign of the determinant of the view's upper-left 3 × 3, which keeps an auxiliary + /// normal on its side. + view_sign: f64, } /// The screen triangles of one pass and the indices of those in the current band. @@ -418,17 +476,25 @@ struct Pass<'a> { /// covers it. type Visibility = Vec<(u32, f32, [f32; 3])>; +/// The surviving opaque fragment that [`Band::fallback`] finds for a discarded pixel. #[derive(Clone, Copy)] struct FallbackFragment { ndc_z: f32, color: [f32; 4], camera_depth: f32, + /// The screen triangle and its weights at the pixel. + tri: u32, + l: [f32; 3], } /// The visibility depth of a pixel with no opaque surface: below the far plane's 0, so a /// fragment on the far plane is drawn. const EMPTY: f32 = -1.0; +/// The rounding error, relative to the largest component, below which an auxiliary normal's +/// component is used without an exact expansion: under half an `f32` step of a unit normal. +const NORMAL_ERROR: f64 = 1.0 / (1u64 << 26) as f64; + /// Whether ndc depth `z` is inside the depth range and nearer than `than`. #[inline] fn nearer(z: f32, than: f32) -> bool { @@ -444,6 +510,69 @@ impl Band<'_> { if z.is_finite() { z } else { f32::NAN } } + /// The unit view-space normal for [`AuxPlanes::normal`] of screen triangle `t` at + /// screen-corner weights `l`. The vertex normals are interpolated, normalized and turned in + /// `f64`, so finite normals near the top of the `f32` range do not overflow. + /// [`crate::scene::validate_aux`] has checked that the view's 3 × 3 is invertible, so the + /// turned vector has a length above 0. + fn view_normal(&self, t: &STri, l: [f32; 3]) -> [f32; 3] { + let unit = |v: [f64; 3], floor: f64| { + let len = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt(); + (len > floor && len.is_finite()).then(|| v.map(|x| x / len)) + }; + let s = self.s; + let base = t.tri as usize * 3; + // The weights over the original vertices, as `frag` computes them. + let mut wv = [0.0f32; 3]; + for c in 0..3 { + for k in 0..3 { + wv[k] += l[c] * t.w[c][k]; + } + } + let mut sum = [0.0f64; 3]; + for (k, &x) in wv.iter().enumerate() { + let vn = s.vertices[s.indices[base + k] as usize].normal; + for i in 0..3 { + sum[i] += f64::from(vn[i]) * f64::from(x); + } + } + // The interpolated normal is turned as it is and normalized after, so its components keep + // their exact ratios through the transform. + let mut n = if unit(sum, 1e-20).is_some() { sum } else { [0.0, 0.0, -1.0] }; + if !t.front { + n = n.map(|x| -x); + } + // Transform the normal by the cofactor matrix and the determinant's sign. + // A row takes an exact expansion when its rounding bound is not negligible next to the + // largest row, which sets the normalized result's scale. + let row = |r: usize| -> [f64; 3] { std::array::from_fn(|c| f64::from(self.s.view[r][c])) }; + let (a, b, c) = (row(0), row(1), row(2)); + let pairs = [(b, c), (c, a), (a, b)]; + let terms: [[(f64, f64); 6]; 3] = std::array::from_fn(|i| { + let (p, q) = pairs[i]; + [(p[1] * q[2], n[0]), (-(p[2] * q[1]), n[0]), (p[2] * q[0], n[1]), (-(p[0] * q[2]), n[1]), (p[0] * q[1], n[2]), (-(p[1] * q[0]), n[2])] + }); + let fast: [(f64, f64); 3] = terms.map(|t| { + let (dot, magnitude) = t.iter().fold((0.0f64, 0.0f64), |(dot, magnitude), &(x, y)| { + let product = x * y; + (dot + product, magnitude + product.abs()) + }); + (dot, magnitude * (8.0 * f64::EPSILON)) + }); + let big = fast.iter().fold(0.0f64, |m, &(dot, _)| m.max(dot.abs())); + let r: [f64; 3] = std::array::from_fn(|i| { + let (dot, bound) = fast[i]; + let dot = if bound <= big * NORMAL_ERROR { dot } else { crate::scene::sum_of_products(terms[i]) }; + self.view_sign * dot + }); + unit(r, 0.0).map_or([f32::NAN; 3], |r| r.map(|x| x as f32)) + } + + /// The part ID of screen triangle `t`. + fn part(&self, t: &STri) -> u32 { + self.s.part_ids.get(t.tri as usize).copied().unwrap_or(NO_PART) + } + /// The nearest opaque triangle covering each pixel of the band. fn visibility(&self, opaque: Pass) -> Visibility { let (w, y0, rows) = (self.w, self.y0, self.rows); @@ -468,7 +597,16 @@ impl Band<'_> { /// Shade each pixel's visible opaque fragment. A discarded fragment (alpha test, back face) /// gives way to the nearest surviving fragment under the pixel, and the pixel's visibility /// depth becomes that fragment's ([`EMPTY`] when none survives). - fn shade_opaque(&self, opaque: Pass, vis: &mut Visibility, crow: &mut [[f32; 4]], drow: &mut [f32]) -> Result<(), RenderError> { + /// When `aux` is given, each shaded pixel's fragment with alpha above 0 becomes its auxiliary + /// surface. + fn shade_opaque( + &self, + opaque: Pass, + vis: &mut Visibility, + crow: &mut [[f32; 4]], + drow: &mut [f32], + aux: &mut Option, + ) -> Result<(), RenderError> { let s = self.s; let mut discarded = vec![false; self.rows * self.w]; for i in 0..self.rows * self.w { @@ -476,11 +614,17 @@ impl Band<'_> { if ti == u32::MAX { continue; } - let f = frag(s, &opaque.tris[ti as usize], l); + let t = &opaque.tris[ti as usize]; + let f = frag(s, t, l); match shade(s, &f) { Some(c) => { crow[i] = c; drow[i] = self.cam_z(f.pos); + if let Some(a) = aux + && c[3] > 0.0 + { + a.set(i, drow[i], self.view_normal(t, l), self.part(t)); + } } None => discarded[i] = true, } @@ -497,6 +641,12 @@ impl Band<'_> { crow[i] = f.color; drow[i] = f.camera_depth; vis[i].1 = f.ndc_z; + if let Some(a) = aux + && f.color[3] > 0.0 + { + let t = &opaque.tris[f.tri as usize]; + a.set(i, f.camera_depth, self.view_normal(t, f.l), self.part(t)); + } } None => vis[i].1 = EMPTY, } @@ -528,7 +678,7 @@ impl Band<'_> { { let f2 = frag(s, t2, l2); if let Some(c) = shade(s, &f2) { - best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos) }); + best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos), tri: tj, l: l2 }); } } } @@ -542,7 +692,9 @@ impl Band<'_> { } /// Transparent fragments in order, blended over the opaque result where they are nearer. - fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]]) { + /// When `aux` is given, a fragment with alpha above 0 is offered as the pixel's auxiliary + /// surface. + fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]], aux: &mut Option) { let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows); for &ti in trans.bins { let t = &trans.tris[ti as usize]; @@ -552,11 +704,17 @@ impl Band<'_> { let i = r + x as usize; if let Some((z, l)) = cover(t, x as f64 + 0.5, y as f64 + 0.5) && nearer(z, vis[i].1) - && let Some(c) = shade(s, &frag(s, t, l)) { + let f = frag(s, t, l); + let Some(c) = shade(s, &f) else { continue }; let d = crow[i]; let k = 1.0 - c[3]; crow[i] = [c[0] + d[0] * k, c[1] + d[1] * k, c[2] + d[2] * k, c[3] + d[3] * k]; + if let Some(a) = aux + && c[3] > 0.0 + { + a.offer(i, self.cam_z(f.pos), || self.view_normal(t, l), self.part(t)); + } } } } @@ -564,8 +722,9 @@ impl Band<'_> { } } -/// Rasterize and shade set-up screen triangles into a target of `pixels` pixels. -fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, work: u64, limit: u64) -> Result { +/// Rasterize and shade set-up screen triangles into a target of `pixels` pixels, with the +/// auxiliary planes when `aux` is true (empty planes otherwise). +fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, aux: bool, work: u64, limit: u64) -> Result<(Target, AuxPlanes), RenderError> { let (w, h) = (s.width as usize, s.height as usize); let bands = (h as i32 + BAND - 1) / BAND; let ob = bin(opaque, bands); @@ -573,15 +732,63 @@ fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, work: u64, let mut color = vec![[0.0f32; 4]; pixels]; let mut depth = vec![f32::INFINITY; pixels]; let spent = AtomicU64::new(work); - color.par_chunks_mut(w * BAND as usize).zip(depth.par_chunks_mut(w * BAND as usize)).enumerate().try_for_each(|(band, (crow, drow))| { - let b = Band { s, y0: band as i32 * BAND, rows: crow.len() / w, w, spent: &spent, limit }; + let band_rows = w * BAND as usize; + let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(1.0); + let render = |band: usize, crow: &mut [[f32; 4]], drow: &mut [f32], mut arow: Option| -> Result<(), RenderError> { + let b = Band { s, y0: band as i32 * BAND, rows: crow.len() / w, w, spent: &spent, limit, view_sign }; let (op, tp) = (Pass { tris: opaque, bins: &ob[band] }, Pass { tris: trans, bins: &tb[band] }); let mut vis = b.visibility(op); - b.shade_opaque(op, &mut vis, crow, drow)?; - b.blend_transparent(tp, &vis, crow); - Ok::<(), RenderError>(()) - })?; - Ok(Target { width: s.width, height: s.height, color, depth }) + b.shade_opaque(op, &mut vis, crow, drow, &mut arow)?; + b.blend_transparent(tp, &vis, crow, &mut arow); + Ok(()) + }; + let mut planes = if aux { + AuxPlanes { depth: vec![f32::INFINITY; pixels], normal: vec![[0.0; 3]; pixels], part_id: vec![NO_PART; pixels] } + } else { + AuxPlanes::default() + }; + if aux { + color + .par_chunks_mut(band_rows) + .zip(depth.par_chunks_mut(band_rows)) + .zip(planes.depth.par_chunks_mut(band_rows)) + .zip(planes.normal.par_chunks_mut(band_rows)) + .zip(planes.part_id.par_chunks_mut(band_rows)) + .enumerate() + .try_for_each(|(band, ((((crow, drow), depth), normal), part))| render(band, crow, drow, Some(AuxRow { depth, normal, part })))?; + } else { + color + .par_chunks_mut(band_rows) + .zip(depth.par_chunks_mut(band_rows)) + .enumerate() + .try_for_each(|(band, (crow, drow))| render(band, crow, drow, None))?; + } + Ok((Target { width: s.width, height: s.height, color, depth }, planes)) +} + +/// Checks the scene (with the checks of the auxiliary outputs when `aux` is true) and sets up +/// its screen triangles: (pixel count, opaque, transparent, preparation work). +fn prepare(s: &Scene, limits: &Limits, aux: bool) -> Result<(usize, Vec, Vec, u64), RenderError> { + if aux { + limits.check_aux(s.width, s.height, None)?; + } + let pixels = validate(s, limits)?; + validate_passes(s)?; + if aux { + validate_aux(s)?; + } + validate_shadow_refs(s)?; + let clip = clip_positions(s)?; + let mut work = 0; + let opaque = setup(s, &clip, 0..s.opaque_count as usize, &mut work, limits.max_work)?; + let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len(), &mut work, limits.max_work)?; + Ok((pixels, opaque, trans, work)) +} + +/// The first pixel whose color is not finite or whose depth is NaN: finite inputs near the top +/// of the `f32` range can still overflow in shading. +fn bad_pixel(t: &Target) -> Option { + t.color.iter().zip(&t.depth).position(|(c, d)| !c.iter().all(|v| v.is_finite()) || d.is_nan()) } /// Rasterize and shade the scene at its raster size. @@ -589,25 +796,69 @@ fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, work: u64, /// The scene is checked first (see [`Limits`]); an empty scene gives a transparent target with /// infinite depth. A triangle whose clipped polygon has zero area draws nothing. pub fn try_render(s: &Scene, limits: &Limits) -> Result { - let pixels = validate(s, limits)?; - validate_passes(s)?; - validate_shadow_refs(s)?; - let clip = clip_positions(s)?; - let mut work = 0; - let opaque = setup(s, &clip, 0..s.opaque_count as usize, &mut work, limits.max_work)?; - let trans = setup(s, &clip, s.opaque_count as usize..s.indices.len(), &mut work, limits.max_work)?; - let t = raster(s, &opaque, &trans, pixels, work, limits.max_work)?; - // Finite inputs near the top of the f32 range can still overflow in shading. - if let Some(i) = t.color.iter().zip(&t.depth).position(|(c, d)| !c.iter().all(|v| v.is_finite()) || d.is_nan()) { - return Err(RenderError::BadPixel(i)); + let (pixels, opaque, trans, work) = prepare(s, limits, false)?; + let (t, _) = raster(s, &opaque, &trans, pixels, false, work, limits.max_work)?; + match bad_pixel(&t) { + Some(i) => Err(RenderError::BadPixel(i)), + None => Ok(t), + } +} + +/// [`try_render`] with the auxiliary outputs ([`AuxPlanes`]): the same target, bit for bit, and +/// the camera depth, view-space normal and part ID of each pixel's surface. +/// +/// Besides the checks of [`try_render`], [`Scene::part_ids`] must hold one ID per triangle and +/// none may be [`NO_PART`], and, when the scene has a triangle, the upper-left 3 × 3 of +/// [`Scene::view`] must be invertible. The +/// render holds 20 more bytes per raster pixel than [`try_render`], and their sum with the +/// target's must fit `isize::MAX` bytes. +pub fn try_render_with_aux(s: &Scene, limits: &Limits) -> Result { + let (pixels, opaque, trans, work) = prepare(s, limits, true)?; + let (target, aux) = raster(s, &opaque, &trans, pixels, true, work, limits.max_work)?; + let bad_aux = || aux.depth.iter().zip(&aux.normal).position(|(d, n)| d.is_nan() || !n.iter().all(|v| v.is_finite())); + match bad_pixel(&target).or_else(bad_aux) { + Some(i) => Err(RenderError::BadPixel(i)), + None => Ok(AuxTarget { target, aux }), } - Ok(t) } #[cfg(test)] mod tests { - use super::{cover, f32_crossing, fan, project}; - use crate::scene::Scene; + use super::{AtomicU64, Band, STri, cover, f32_crossing, fan, project}; + use crate::scene::{Scene, Vertex}; + + #[test] + fn equal_large_clip_depth_and_w_project_to_one() { + let s = Scene { width: 1, height: 1, indices: vec![0, 1, 2], ..Scene::default() }; + let rounded_below_one = (1..=100).map(|w| w as f32).find(|&w| w * (1.0 / w) < 1.0); + assert!(rounded_below_one.is_some()); + for scale in [1.000005e38, rounded_below_one.unwrap_or_default()] { + let clip = [[-0.5 * scale, -0.5 * scale, scale, scale], [0.5 * scale, -0.5 * scale, scale, scale], [0.0, 0.5 * scale, scale, scale]]; + let (scr, _) = project(&s, &clip, 0).unwrap_or_default(); + assert_eq!(scr.len(), 3); + for (_, z, _, _) in scr { + assert_eq!(z.to_bits(), 1.0f32.to_bits()); + } + } + } + + #[test] + fn a_covered_fragment_on_the_near_plane_keeps_a_depth_of_one() { + // The rounded f32 weights here sum to just above 1, which put the depth past the range. + let d = 17.0 * 2f64.powi(-29); + let t = STri { + p: [[0.375, 0.5 - d], [0.875, 0.5 - d], [0.655, 1.0]], + z: [1.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0, 0, 1, 1], + }; + let (z, _) = cover(&t, 0.5, 0.5).unwrap_or((f32::NAN, [0.0; 3])); + assert_eq!(z, 1.0); + } #[test] fn wide_projection_preserves_subnormal_weights_on_an_included_edge() { @@ -633,4 +884,60 @@ mod tests { assert_eq!(f32_crossing(-3e38, 1e38), (false, 0.75)); assert_eq!(f32_crossing(1e38, -3e38), (false, 0.25)); } + + #[test] + fn an_auxiliary_normal_near_the_top_of_f32_is_interpolated_in_f64() { + // Three normals of `[f32::MAX, 0, 0]` at weights whose sum is just above 1: the weighted + // sum overflows `f32` and must still give the normal's direction. + let v = Vertex { normal: [f32::MAX, 0.0, 0.0], ..Vertex::default() }; + let id = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view: id, ..Scene::default() }; + let t = STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0; 4], + }; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let l = [0.5, 0.25, 0.25 + 2f32.powi(-22)]; + assert_eq!(b.view_normal(&t, l), [1.0, 0.0, 0.0]); + let back = STri { front: false, ..t }; + assert_eq!(b.view_normal(&back, l), [-1.0, 0.0, 0.0]); + } + + #[test] + fn a_view_whose_cofactors_nearly_cancel_still_turns_the_normal() { + // The view's determinant is −2^-60, and the rounded cofactors give the normal [1, 1, 0] a + // dot product of 0 with every row; the exact ones turn it to [1, 0, 0]. + let e = 2f32.powi(-30); + let view = [[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let v = Vertex { normal: [1.0, 1.0, 0.0], ..Vertex::default() }; + let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view, ..Scene::default() }; + let t = STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0; 4], + }; + let spent = AtomicU64::new(0); + let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(f64::NAN); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign }; + assert_eq!(b.view_normal(&t, [1.0 / 3.0; 3]), [1.0, 0.0, 0.0]); + // A normal whose normalized components round by different amounts still turns exactly. + let view = [[1.0, 3.0, 0.0, 0.0], [1.0, 3.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let v = Vertex { normal: [1.0, 3.0, 0.0], ..Vertex::default() }; + let s = Scene { vertices: vec![v; 3], indices: vec![0, 1, 2], view, ..Scene::default() }; + let view_sign = crate::scene::det_sign3(&s.view).unwrap_or(f64::NAN); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign }; + assert_eq!(b.view_normal(&t, [1.0 / 3.0; 3]), [1.0, 0.0, 0.0]); + } } diff --git a/crates/raster3d/src/resolve.rs b/crates/raster3d/src/resolve.rs index 1b348dca5f..19726bc0a7 100644 --- a/crates/raster3d/src/resolve.rs +++ b/crates/raster3d/src/resolve.rs @@ -2,8 +2,8 @@ use rayon::prelude::*; -use crate::raster::{Target, try_render}; -use crate::scene::Scene; +use crate::raster::{AuxPlanes, AuxTarget, Target, try_render, try_render_with_aux}; +use crate::scene::{NO_PART, Scene}; use crate::shade::linear_to_srgb; use crate::{Limits, RenderError}; @@ -15,9 +15,19 @@ pub struct Image { pub data: Vec<[f32; 4]>, } +/// A resolved image with its auxiliary outputs at the image's size. +#[derive(Clone, Debug, PartialEq)] +pub struct AuxImage { + pub image: Image, + pub aux: AuxPlanes, +} + /// Alpha above 1 that [`try_encode`] accepts as rounding from blending. const ALPHA_SLACK: f32 = 1e-4; +/// The largest block [`try_resolve`] sums in `f32`. +const F32_SAMPLES: u64 = 256; + /// `w × h` as a length, when it fits `usize`. fn area(w: u32, h: u32) -> Option { usize::try_from(u64::from(w) * u64::from(h)).ok() @@ -26,7 +36,7 @@ fn area(w: u32, h: u32) -> Option { /// Box-filter a supersampled target down by `k` per side: each output pixel is the mean of its /// `k × k` premultiplied colors, and its depth is the mean of the covered subsamples' depths /// (infinity where none is covered). A pixel whose `f32` sums overflow, and every pixel when a -/// block holds more than 2^24 subsamples, is averaged in `f64`. +/// block holds more than 256 subsamples (`k` over 16), is averaged in `f64`. /// /// Returns [`RenderError::BadFactor`] when `k` is zero or does not divide both sides, and /// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height @@ -50,8 +60,9 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> return Ok((img, depth)); } let n = (u64::from(k) * u64::from(k)) as f32; - // An f32 count stops at 2^24, so a larger block is averaged in f64. - let wide = u64::from(k) * u64::from(k) > 1 << 24; + // An f32 sum drops the low bits of each sample as it grows, so a block of more than + // `F32_SAMPLES` subsamples is averaged in f64. + let wide = u64::from(k) * u64::from(k) > F32_SAMPLES; img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { for x in 0..w as usize { if wide { @@ -86,6 +97,54 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> Ok((img, depth)) } +/// Resolve a supersampled target and its auxiliary outputs down by `k` per side. The color is +/// [`try_resolve`]'s, bit for bit. Each output pixel's depth, normal and part ID are copied +/// together from one subsample of its `k × k` block: the one with the smallest finite depth, the +/// first in row-major order on ties. A block with no surface gives ∞, `[0, 0, 0]` and +/// [`NO_PART`]; depths are not averaged and IDs are not mixed. +/// +/// Returns the errors of [`try_resolve`], and [`RenderError::BadDataLength`] when an auxiliary +/// plane does not hold width × height values. +pub fn try_resolve_aux(t: &AuxTarget, k: u32) -> Result { + let tt = &t.target; + if k == 0 || !tt.width.is_multiple_of(k) || !tt.height.is_multiple_of(k) { + return Err(RenderError::BadFactor { k, width: tt.width, height: tt.height }); + } + let expected = area(tt.width, tt.height).ok_or(RenderError::TooLarge(tt.width, tt.height))?; + for found in [tt.color.len(), tt.depth.len(), t.aux.depth.len(), t.aux.normal.len(), t.aux.part_id.len()] { + if found != expected { + return Err(RenderError::BadDataLength { expected, found }); + } + } + let (image, _) = try_resolve(tt, k)?; + let (w, out) = (image.width as usize, image.data.len()); + let mut aux = AuxPlanes { depth: vec![f32::INFINITY; out], normal: vec![[0.0; 3]; out], part_id: vec![NO_PART; out] }; + if out == 0 { + return Ok(AuxImage { image, aux }); + } + let (k, tw) = (k as usize, tt.width as usize); + aux.depth.par_chunks_mut(w).zip(aux.normal.par_chunks_mut(w)).zip(aux.part_id.par_chunks_mut(w)).enumerate().for_each( + |(y, ((drow, nrow), prow))| { + for x in 0..w { + let mut best: Option = None; + for j in 0..k { + for i in 0..k { + let s = (y * k + j) * tw + x * k + i; + let z = t.aux.depth[s]; + if z.is_finite() && best.is_none_or(|b| z < t.aux.depth[b]) { + best = Some(s); + } + } + } + if let Some(s) = best { + (drow[x], nrow[x], prow[x]) = (t.aux.depth[s], t.aux.normal[s], t.aux.part_id[s]); + } + } + }, + ); + Ok(AuxImage { image, aux }) +} + /// Output pixel (`x`, `y`) of a `k`-per-side resolve, summed in `f64`. fn mean_f64(t: &Target, k: usize, x: usize, y: usize) -> ([f32; 4], f32) { let (mut acc, mut dz, mut dn) = ([0.0f64; 4], 0.0f64, 0u64); @@ -158,3 +217,35 @@ pub fn try_render_cpu(s: &Scene, limits: &Limits) -> Result<(Image, Vec), R } try_resolve(&try_render(s, limits)?, k) } + +/// [`try_render_with_aux`] and [`try_resolve_aux`] by the scene's supersampling factor, as +/// [`try_render_cpu`]: the image is [`try_render_cpu`]'s, bit for bit. The resolve's output +/// planes count toward the byte check of [`try_render_with_aux`], which runs before anything is +/// rendered. +pub fn try_render_cpu_with_aux(s: &Scene, limits: &Limits) -> Result { + let k = s.ssaa.max(1); + if !s.width.is_multiple_of(k) || !s.height.is_multiple_of(k) { + return Err(RenderError::BadFactor { k, width: s.width, height: s.height }); + } + limits.check_aux(s.width, s.height, Some(k))?; + try_resolve_aux(&try_render_with_aux(s, limits)?, k) +} + +#[cfg(test)] +mod tests { + use super::{AuxPlanes, AuxTarget, NO_PART, Target, try_resolve, try_resolve_aux}; + + #[test] + fn a_large_block_of_one_color_resolves_to_that_color() { + // An f32 sum of 2^20 samples of 0.7 drifts by whole percent. + let n = 1024u32; + let len = (n * n) as usize; + let t = Target { width: n, height: n, color: vec![[0.7; 4]; len], depth: vec![0.5; len] }; + let (img, depth) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}")); + assert!(img.data[0].iter().all(|&c| (c - 0.7).abs() < 1e-6), "{:?}", img.data[0]); + assert!((depth[0] - 0.5).abs() < 1e-6, "{}", depth[0]); + let aux = AuxPlanes { depth: vec![0.5; len], normal: vec![[0.0, 0.0, -1.0]; len], part_id: vec![NO_PART - 1; len] }; + let a = try_resolve_aux(&AuxTarget { target: t, aux }, n).unwrap_or_else(|e| panic!("{e:?}")); + assert_eq!(a.image, img); + } +} diff --git a/crates/raster3d/src/scene.rs b/crates/raster3d/src/scene.rs index 9667561ac1..ebceeb7005 100644 --- a/crates/raster3d/src/scene.rs +++ b/crates/raster3d/src/scene.rs @@ -207,6 +207,11 @@ pub struct Scene { /// for a shadows-only material. pub indices: Vec, pub opaque_count: u32, + /// The part ID of each triangle, in the order of [`Scene::indices`]: one per three indices. + /// [`crate::try_render_with_aux`] reports it for the surface of each pixel, and a triangle cut + /// by clipping keeps its ID. Any value but [`NO_PART`] is an ID, 0 included. The renderers + /// without auxiliary outputs do not read it, and it may be empty for them. + pub part_ids: Vec, pub materials: Vec, pub textures: Vec, pub texels: Vec<[f32; 4]>, @@ -219,6 +224,71 @@ pub struct Scene { pub linear_io: bool, } +/// The part ID of a pixel with no surface; [`Scene::part_ids`] may not hold it. +pub const NO_PART: u32 = u32::MAX; + +/// Checks what the auxiliary outputs need beyond [`validate`]: one part ID per triangle, none of +/// them [`NO_PART`], and, when the scene has a triangle, a view whose upper-left 3 × 3 (the +/// transform of normals) is invertible. +pub(crate) fn validate_aux(s: &Scene) -> Result<(), RenderError> { + let expected = s.indices.len() / 3; + if s.part_ids.len() != expected { + return Err(RenderError::BadPartIdCount { expected, found: s.part_ids.len() }); + } + if let Some(i) = s.part_ids.iter().position(|&p| p == NO_PART) { + return Err(RenderError::ReservedPartId(i)); + } + if expected == 0 { + return Ok(()); + } + if det_sign3(&s.view).is_none() { + return Err(RenderError::BadTransform); + } + Ok(()) +} + +/// Sums at most six products using an exact expansion, barring overflow and underflow. +pub(crate) fn sum_of_products(terms: [(f64, f64); N]) -> f64 { + const { assert!(N <= 6) }; + let mut storage = [[0.0f64; 2]; N]; + let e = storage.as_flattened_mut(); + let mut len = 0; + for (x, y) in terms { + let hi = x * y; + for part in [hi, x.mul_add(y, -hi)] { + // Grow the expansion by `part` with exact two-sums, keeping every rounding error. + let mut q = part; + for c in &mut e[..len] { + let sum = q + *c; + let bv = sum - q; + let err = (q - (sum - bv)) + (*c - bv); + (*c, q) = (err, sum); + } + e[len] = q; + len += 1; + } + } + // The components do not overlap and grow in magnitude. + e[..len].iter().sum() +} + +/// The sign of the determinant of the upper-left 3 × 3 of `m` (1 or −1), or `None` when the +/// determinant is 0 or an entry is not finite. The sign is exact: each of the six terms of the +/// expansion is an `f32` times an exact `f64` product of two `f32`s, summed with +/// [`sum_of_products`]. Rounded arithmetic can cancel an invertible matrix to 0 or leave a +/// singular one nonzero. +pub(crate) fn det_sign3(m: &[[f32; 4]]) -> Option { + let a = |r: usize, c: usize| m.get(r).map_or(f64::NAN, |row| f64::from(row[c])); + if !(0..3).all(|r| (0..3).all(|c| a(r, c).is_finite())) { + return None; + } + // Exact: two 24-bit significands fit an f64's 53. + let terms = [(0, 1, 2, 1.0), (0, 2, 1, -1.0), (1, 0, 2, -1.0), (1, 2, 0, 1.0), (2, 0, 1, 1.0), (2, 1, 0, -1.0)] + .map(|(i, j, k, s)| (s * a(0, i), a(1, j) * a(2, k))); + let det = sum_of_products(terms); + (det != 0.0 && det.is_finite()).then_some(if det < 0.0 { -1.0 } else { 1.0 }) +} + fn finite(v: &[f32; N]) -> bool { v.iter().all(|x| x.is_finite()) } @@ -405,3 +475,61 @@ fn validate_shadows(s: &Scene) -> Result<(), RenderError> { None => Ok(()), } } + +#[cfg(test)] +mod tests { + use super::{Light, Scene, det_sign3, validate_aux, validate_lights}; + use crate::{Limits, RenderError}; + + #[test] + fn every_light_kind_rejects_unknown_falloff() { + let light = Light { + kind: 0, + pos: [0.0; 3], + dir: [0.0, 0.0, -1.0], + color: [1.0; 3], + cos_inner: 1.0, + cos_outer: 0.0, + falloff: 3, + radius: 0.0, + falloff_distance: 0.0, + shadow: -1, + shadow_darkness: 0.0, + shadow_diffusion: 0.0, + }; + let mut s = Scene { lights: vec![light], ..Scene::default() }; + let limits = Limits::default(); + for kind in [0, 1, 2] { + s.lights[0].kind = kind; + assert!(matches!(validate_lights(&s, &limits), Err(RenderError::BadLight(0)))); + for falloff in 0..=2 { + s.lights[0].falloff = falloff; + assert!(validate_lights(&s, &limits).is_ok()); + } + s.lights[0].falloff = 3; + } + } + + fn with_view(rows: [[f32; 3]; 3]) -> Scene { + let [a, b, c] = rows.map(|r| [r[0], r[1], r[2], 0.0]); + let view = [a, b, c, [0.0, 0.0, 0.0, 1.0]]; + Scene { indices: vec![0, 1, 2], part_ids: vec![0], view, ..Scene::default() } + } + + #[test] + fn a_view_whose_determinant_terms_cancel_is_still_invertible() { + let e = 2f32.powi(-30); + let cancel = with_view([[1.0, 1.0, 0.0], [1.0, 1.0, e], [0.0, e, 1.0]]); + assert!(validate_aux(&cancel).is_ok()); + // The determinant is −2^-60. + assert_eq!(det_sign3(&cancel.view), Some(-1.0)); + assert!(validate_aux(&with_view([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])).is_ok()); + let dup = validate_aux(&with_view([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0], [0.0, 0.0, 1.0]])); + assert!(matches!(dup, Err(RenderError::BadTransform)), "{dup:?}"); + // Rounded elimination leaves a nonzero pivot here: 1/49 × 49 rounds below 1. + let scaled = validate_aux(&with_view([[49.0, 49.0, 0.0], [1.0, 1.0, 0.0], [0.0, 0.0, 1.0]])); + assert!(matches!(scaled, Err(RenderError::BadTransform)), "{scaled:?}"); + assert_eq!(det_sign3(&with_view([[0.0, 1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]).view), Some(-1.0)); + assert_eq!(det_sign3(&with_view([[2.0, 0.0, 0.0], [0.0, 3.0, 0.0], [0.0, 0.0, 0.5]]).view), Some(1.0)); + } +} diff --git a/crates/raster3d/src/shade.rs b/crates/raster3d/src/shade.rs index 1af5b737f8..736babf7a2 100644 --- a/crates/raster3d/src/shade.rs +++ b/crates/raster3d/src/shade.rs @@ -745,6 +745,45 @@ mod tests { } } + fn point_light(pos: [f32; 3], falloff: u32, radius: f32) -> Light { + Light { + kind: 2, + pos, + dir: [0.0, 0.0, 1.0], + color: [1.0; 3], + cos_inner: 1.0, + cos_outer: 1.0, + falloff, + radius, + falloff_distance: 0.0, + shadow: -1, + shadow_darkness: 0.0, + shadow_diffusion: 0.0, + } + } + + #[test] + fn a_light_difference_that_overflows_f32_is_taken_in_f64() { + let l = point_light([2e38, 0.0, 0.0], 0, 0.0); + let (d, len) = to_light(&l, [-2e38, 0.0, 0.0]); + assert_eq!(d, [1.0, 0.0, 0.0]); + assert!(len.is_infinite() || len > 3e38, "{len}"); + } + + #[test] + fn an_overflowing_perspective_denominator_compares_like_a_scaled_down_receiver() { + // Scaling the receiver, its depth and the texels by 2^126 keeps every ratio, but + // focal × z overflows f32 at that scale. + let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + let m = ShadowMap { view, focal: 4.0, ortho: false, size: 16, offset: 0, bias: 0.0, radius: 0.0 }; + let ng = [0.6, 0.0, -0.8]; + let k = f32::from_bits(253 << 23); // 2^126 + let small = shadow_factor(&m, &vec![0.95; 256], [0.0, 0.0, 1.0], ng, 1.0); + let big = shadow_factor(&m, &vec![0.95 * k; 256], [0.0, 0.0, k], ng, 1.0); + assert!(small > 0.0 && small < 1.0, "{small}"); + assert!((big - small).abs() < 1e-6, "{big} vs {small}"); + } + #[test] fn overflowing_footprints_preserve_populated_shadow_comparisons() { let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; diff --git a/crates/raster3d/src/shadow.rs b/crates/raster3d/src/shadow.rs index b18049f663..9ba0aa415e 100644 --- a/crates/raster3d/src/shadow.rs +++ b/crates/raster3d/src/shadow.rs @@ -103,12 +103,16 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec { if (da >= 0.0) != (db >= 0.0) { let (from_b, k) = f32_crossing(da, db); let (p, q) = if from_b { (b, a) } else { (a, b) }; + // `y - x` can overflow f32 between far-apart finite corners; such a lerp is taken in + // f64, with the fraction also taken in f64. + let (dp, dq) = if from_b { (f64::from(db), f64::from(da)) } else { (f64::from(da), f64::from(db)) }; + let k64 = dp / (dp - dq); let lerp = |x: f32, y: f32| { - let d = y - x; - if d.is_finite() || !x.is_finite() || !y.is_finite() { - x + d * k + let fast = x + (y - x) * k; + if fast.is_finite() || !(x.is_finite() && y.is_finite()) { + fast } else { - (f64::from(x) + (f64::from(y) - f64::from(x)) * f64::from(k)) as f32 + (f64::from(x) + (f64::from(y) - f64::from(x)) * k64) as f32 } }; // The crossing lies on the near plane; its depth is set to it, since the lerp of @@ -213,6 +217,9 @@ fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option< let n = m.size as usize; let (a, b, cc) = (tri[0].0, tri[1].0, tri[2].0); let Some((area, [x0, x1, y0, y1])) = texel_bounds(m, &tri) else { return }; + if x0 >= x1 || y0 >= y1 { + return; + } let wide_depth = !m.ortho && tri.iter().any(|c| c.1.is_subnormal()); for y in y0..y1 { for x in x0..x1 { @@ -235,11 +242,11 @@ fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option< if z >= *px { continue; } - let uv = [0, 1].map(|i| caster_uv(&tri, l, z, i, m.ortho)); - if let Some(t) = alpha - && t.discards(sample(t.tex, &s.texels, uv[0], uv[1])[3] * t.factor) - { - continue; + if let Some(t) = alpha { + let uv = [0, 1].map(|i| caster_uv(&tri, l, z, i, m.ortho)); + if t.discards(sample(t.tex, &s.texels, uv[0], uv[1])[3] * t.factor) { + continue; + } } *px = z; } @@ -659,4 +666,20 @@ mod tests { assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0); } } + + #[test] + fn a_near_plane_crossing_whose_difference_overflows_f32_is_interpolated_in_f64() { + // 3e38 − (−3e38) overflows f32; the edge crosses the near plane near x = 0. + let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; + let s = Scene { vertices: vec![v([-3e38, 0.0, -1.0]), v([3e38, 0.0, 1.0]), v([0.0, 0.1, 1.0])], ..Scene::default() }; + let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; + let m = ShadowMap { view, focal: 1.0, ortho: false, size: 8, offset: 0, bias: 0.0, radius: 0.0 }; + let poly = light_poly(&s, &m, [0, 1, 2]); + assert!(!poly.is_empty()); + for (p, uv) in &poly { + assert!(p.iter().chain(uv.iter()).all(|c| c.is_finite()), "{poly:?}"); + } + // The near plane at 0.001 lies 1.001 / 2 of the way along the edge, at x = 3e35. + assert!(poly.iter().any(|(p, _)| (p[0] - 3e35).abs() < 1e31 && p[2] == 0.001), "{poly:?}"); + } } diff --git a/crates/raster3d/tests/it/aux_outputs.rs b/crates/raster3d/tests/it/aux_outputs.rs new file mode 100644 index 0000000000..213f81df6e --- /dev/null +++ b/crates/raster3d/tests/it/aux_outputs.rs @@ -0,0 +1,506 @@ +//! The auxiliary outputs: camera depth, view-space normal and part ID of each pixel's surface. + +use craft_raster3d::{ + AuxImage, AuxPlanes, AuxTarget, Limits, Material, NO_PART, RenderError, Scene, TexInfo, Vertex, try_render, try_render_cpu, + try_render_cpu_with_aux, try_render_with_aux, try_resolve_aux, try_shadow_maps, +}; + +use crate::{bits, bits4, limits, lit_scene, quad_scene}; + +/// `s` with part ID `i` for triangle `i`. +fn with_ids(mut s: Scene) -> Scene { + s.part_ids = (0..s.indices.len() as u32 / 3).collect(); + s +} + +/// The quad scenes of `differential.rs`. +fn quad_scenes() -> Vec<(&'static str, Scene)> { + let red = [1.0, 0.0, 0.0, 1.0]; + let blue = [0.0, 0.0, 1.0, 1.0]; + vec![ + ("overlap", quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)])), + ("half-alpha quad", quad_scene(32, 32, &[([4.0, 4.0, 20.0, 12.0], 10.0, [1.0, 1.0, 1.0, 0.5])])), + ( + "two transparent layers", + quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], 50.0, [0.0, 0.0, 1.0, 0.5])]), + ), + ( + "past the edges", + quad_scene( + 24, + 16, + &[ + ([-30.0, -5.0, 10.0, 40.0], 300.0, red), + ([5.0, 3.0, 90.0, 12.0], 200.0, [0.0, 1.0, 0.0, 0.5]), + ([30.0, 0.0, 40.0, 8.0], 1.0, blue), + ], + ), + ), + ] +} + +/// The lit scenes of `differential.rs`, with their shadow maps. +fn lit_scenes() -> Vec<(&'static str, Scene)> { + let mut out = vec![]; + for (name, out_size, ssaa, ortho, draft) in [ + ("lit perspective", (48, 36), 1, false, false), + ("lit perspective 2x2", (32, 24), 2, false, false), + ("lit orthographic draft", (40, 30), 1, true, true), + ] { + let mut s = lit_scene(out_size, ssaa, ortho); + try_shadow_maps(&mut s, draft, &Limits::default()).unwrap(); + out.push((name, s)); + } + out +} + +/// Every plane marks the same pixels as having a surface, and those are the pixels with alpha +/// above 0 in `color`. +fn assert_same_coverage(name: &str, color: &[[f32; 4]], aux: &AuxPlanes) { + assert_eq!(aux.depth.len(), color.len(), "{name}: depth length"); + assert_eq!(aux.normal.len(), color.len(), "{name}: normal length"); + assert_eq!(aux.part_id.len(), color.len(), "{name}: part length"); + for (i, c) in color.iter().enumerate() { + let covered = c[3] > 0.0; + assert_eq!(aux.depth[i].is_finite(), covered, "{name}: depth at {i}"); + assert_eq!(aux.part_id[i] != NO_PART, covered, "{name}: part at {i}"); + let n = aux.normal[i]; + if covered { + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + assert!((len - 1.0).abs() < 1e-5, "{name}: normal at {i} has length {len}"); + } else { + assert_eq!(n, [0.0; 3], "{name}: normal at {i}"); + } + } +} + +/// With and without auxiliary outputs, the target, the image and its depth are the same bit for +/// bit, and the auxiliary planes cover the pixels the color covers. +fn check_scene(name: &str, s: &Scene) { + let s = with_ids(s.clone()); + let t = try_render(&s, &Limits::default()).unwrap(); + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!(bits4(&a.target.color), bits4(&t.color), "{name}: color"); + assert_eq!(bits(&a.target.depth), bits(&t.depth), "{name}: depth"); + assert!(a.aux.part_id.iter().any(|&p| p != NO_PART), "{name}: nothing drawn"); + assert_same_coverage(name, &a.target.color, &a.aux); + let (img, _) = try_render_cpu(&s, &Limits::default()).unwrap(); + let r = try_render_cpu_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!((r.image.width, r.image.height), (img.width, img.height), "{name}: image size"); + assert_eq!(bits4(&r.image.data), bits4(&img.data), "{name}: resolved color"); + assert_same_coverage(name, &r.image.data, &r.aux); +} + +#[test] +fn every_output_covers_the_pixels_the_color_covers() { + for (name, s) in quad_scenes().into_iter().chain(lit_scenes()) { + check_scene(name, &s); + } +} + +#[test] +fn an_empty_scene_has_no_surface() { + let s = Scene { width: 5, height: 3, ..Scene::default() }; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!(a.target, try_render(&s, &Limits::default()).unwrap()); + assert_eq!(a.aux, AuxPlanes { depth: vec![f32::INFINITY; 15], normal: vec![[0.0; 3]; 15], part_id: vec![NO_PART; 15] }); +} + +/// A perspective camera at (0, 0, −500) looking along +z (+y down), as in `lit_scene`, with one +/// unlit, single-sided material. +fn perspective(w: u32, h: u32) -> Scene { + let base = lit_scene((w, h), 1, false); + let mut s = Scene { + width: w, + height: h, + ssaa: 1, + clip: base.clip, + view: base.view, + eye: base.eye, + cam_fwd: base.cam_fwd, + linear_io: true, + ..Scene::default() + }; + s.materials.push(Material { unlit: true, ..Material::default() }); + s +} + +/// Appends a front-facing quad through `c` (clockwise in world x/y with y down, so +/// counterclockwise on the screen) with `normal` and material `m` as two opaque triangles. +fn push_quad(s: &mut Scene, c: [[f32; 3]; 4], normal: [f32; 3], m: u32) { + let b = s.vertices.len() as u32; + for p in c { + s.vertices.push(Vertex { pos: p, normal, uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m }); + } + s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]); +} + +#[test] +fn depth_rises_along_a_tilted_plane() { + let mut s = perspective(64, 48); + // A plane that recedes from z = 0 on the left to z = 600 on the right. + push_quad(&mut s, [[-300.0, -200.0, 0.0], [300.0, -200.0, 600.0], [300.0, 200.0, 600.0], [-300.0, 200.0, 0.0]], [-0.707, 0.0, -0.707], 0); + s.opaque_count = s.indices.len() as u32; + let a = try_render_with_aux(&with_ids(s), &Limits::default()).unwrap(); + let row: Vec = a.aux.depth[24 * 64..25 * 64].iter().copied().filter(|d| d.is_finite()).collect(); + assert!(row.len() > 40, "{} pixels drawn", row.len()); + assert!(row.windows(2).all(|p| p[1] > p[0]), "{row:?}"); + // Camera depth is the view's z: from 500 (z = 0) toward 1100 (z = 600). + assert!(row[0] >= 500.0 && row[row.len() - 1] <= 1100.0, "{row:?}"); +} + +/// A sphere of radius `r` around `c`, single-sided and wound to face outward, with unit +/// outward vertex normals. +fn push_sphere(s: &mut Scene, c: [f32; 3], r: f32, m: u32) { + let (stacks, slices) = (32u32, 64u32); + let b = s.vertices.len() as u32; + for i in 0..=stacks { + let th = std::f32::consts::PI * i as f32 / stacks as f32; + for j in 0..=slices { + let ph = std::f32::consts::TAU * j as f32 / slices as f32; + let n = [th.sin() * ph.cos(), th.cos(), th.sin() * ph.sin()]; + s.vertices.push(Vertex { + pos: [c[0] + r * n[0], c[1] + r * n[1], c[2] + r * n[2]], + normal: n, + uv: [0.0; 2], + tangent: [1.0, 0.0, 0.0, 1.0], + material: m, + }); + } + } + let at = |i: u32, j: u32| b + i * (slices + 1) + j; + for i in 0..stacks { + for j in 0..slices { + for t in [[at(i, j), at(i + 1, j), at(i + 1, j + 1)], [at(i, j), at(i + 1, j + 1), at(i, j + 1)]] { + let p = t.map(|k| s.vertices[k as usize].pos); + let (u, v) = ([p[1][0] - p[0][0], p[1][1] - p[0][1], p[1][2] - p[0][2]], [p[2][0] - p[0][0], p[2][1] - p[0][1], p[2][2] - p[0][2]]); + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let mid = [0, 1, 2].map(|k| (p[0][k] + p[1][k] + p[2][k]) / 3.0 - c[k]); + if n == [0.0; 3] { + continue; + } + let outward = n[0] * mid[0] + n[1] * mid[1] + n[2] * mid[2] > 0.0; + s.indices.extend(if outward { t } else { [t[0], t[2], t[1]] }); + } + } + } +} + +/// An orthographic 32 × 32 scene (world x/y = pixels, camera depth = z) holding a sphere of +/// radius 12 around (16, 16, 500), and its expected outward unit normal at a pixel center well +/// inside the outline. +fn sphere_scene() -> (Scene, impl Fn(usize, usize) -> Option<[f32; 3]>) { + let mut s = quad_scene(32, 32, &[]); + s.materials.push(Material { unlit: true, ..Material::default() }); + push_sphere(&mut s, [16.0, 16.0, 500.0], 12.0, 0); + s.opaque_count = s.indices.len() as u32; + let expected = |x: usize, y: usize| { + let (dx, dy) = ((x as f32 + 0.5 - 16.0) / 12.0, (y as f32 + 0.5 - 16.0) / 12.0); + let rr = dx * dx + dy * dy; + (rr < 0.8 * 0.8).then(|| [dx, dy, -(1.0 - rr).sqrt()]) + }; + (with_ids(s), expected) +} + +fn dot(a: [f32; 3], b: [f32; 3]) -> f32 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +#[test] +fn sphere_normals_point_outward() { + let (s, expected) = sphere_scene(); + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let mut checked = 0; + for y in 0..32 { + for x in 0..32 { + if let Some(e) = expected(x, y) { + let n = a.aux.normal[y * 32 + x]; + assert!(dot(n, e) > 0.995, "({x}, {y}): {n:?} against {e:?}"); + checked += 1; + } + } + } + assert!(checked > 200, "{checked} pixels checked"); +} + +#[test] +fn normals_are_turned_by_the_view() { + // The view turns a quarter turn about z: x → y, y → −x. Depth (the third row) is unchanged. + let (mut s, expected) = sphere_scene(); + s.view = [[0.0, -1.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let e = expected(22, 16).unwrap(); + let n = a.aux.normal[16 * 32 + 22]; + assert!(dot(n, [-e[1], e[0], e[2]]) > 0.995, "{n:?} against {e:?}"); + // A uniform scale in the view does not change the unit normal. + s.view = [[0.0, -3.0, 0.0, 0.0], [3.0, 0.0, 0.0, 0.0], [0.0, 0.0, 3.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let b = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert!((dot(b.aux.normal[16 * 32 + 22], n) - 1.0).abs() < 1e-6); +} + +#[test] +fn a_view_that_stretches_and_mirrors_keeps_normals_perpendicular_to_the_surface() { + // The view doubles x and mirrors it. A surface's tangents turn by that 3 × 3, so its normal + // turns by the inverse transpose, diag(−1/2, 1, 1), and keeps facing outward. + let (mut s, expected) = sphere_scene(); + s.view = [[-2.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let mut checked = 0; + for y in 0..32 { + for x in 0..32 { + if let Some(e) = expected(x, y) { + let t = [-e[0] / 2.0, e[1], e[2]]; + let len = dot(t, t).sqrt(); + let t = t.map(|v| v / len); + let n = a.aux.normal[y * 32 + x]; + assert!(dot(n, t) > 0.995, "({x}, {y}): {n:?} against {t:?}"); + checked += 1; + } + } + } + assert!(checked > 200, "{checked} pixels checked"); +} + +#[test] +fn a_double_sided_back_face_reports_the_reversed_normal_and_a_zero_normal_reads_as_toward_the_camera() { + let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], 100.0, [1.0; 4])]); + // quad_scene's quads face the camera; reversing the winding shows their back. + for t in s.indices.chunks_mut(3) { + t.swap(1, 2); + } + s.vertices.iter_mut().for_each(|v| v.normal = [0.3, 0.0, -0.4]); + let a = try_render_with_aux(&with_ids(s.clone()), &Limits::default()).unwrap(); + assert!(a.aux.normal.iter().all(|n| dot(*n, [-0.6, 0.0, 0.8]) > 0.99999), "{:?}", a.aux.normal[0]); + s.vertices.iter_mut().for_each(|v| v.normal = [0.0; 3]); + let a = try_render_with_aux(&with_ids(s), &Limits::default()).unwrap(); + assert!(a.aux.normal.iter().all(|n| *n == [0.0, 0.0, 1.0]), "{:?}", a.aux.normal[0]); +} + +#[test] +fn part_ids_separate_two_meshes_whatever_their_order() { + let red = [1.0, 0.0, 0.0, 1.0]; + let blue = [0.0, 0.0, 1.0, 1.0]; + // Blue (far, left) and red (near, right) overlap in x 10 to 30. + let mut s = quad_scene(40, 30, &[([0.0, 0.0, 30.0, 20.0], 500.0, blue), ([10.0, 10.0, 40.0, 30.0], 100.0, red)]); + s.part_ids = vec![7, 7, 0, 0]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let at = |a: &AuxTarget, x: usize, y: usize| (a.aux.part_id[y * 40 + x], a.aux.depth[y * 40 + x]); + assert_eq!(at(&a, 5, 5), (7, 500.0)); + assert_eq!(at(&a, 20, 15), (0, 100.0)); + assert_eq!(at(&a, 35, 25), (0, 100.0)); + assert_eq!(at(&a, 35, 5), (NO_PART, f32::INFINITY)); + // The same quads in the other order. + let mut swapped = s.clone(); + swapped.indices = s.indices[6..].iter().chain(&s.indices[..6]).copied().collect(); + swapped.part_ids = vec![0, 0, 7, 7]; + let b = try_render_with_aux(&swapped, &Limits::default()).unwrap(); + assert_eq!(b.aux.part_id, a.aux.part_id); +} + +#[test] +fn a_clipped_triangle_keeps_its_part_id() { + // The lit scene's floor (triangles 0 and 1) crosses the near plane and reaches past the + // viewport, so it is clipped into several triangles. + let s = with_ids(lit_scene((48, 36), 1, false)); + let a = try_render_with_aux(&Scene { lights: vec![], env: None, ..s }, &Limits::default()).unwrap(); + for x in 0..48 { + assert!(a.aux.part_id[35 * 48 + x] <= 1, "bottom row at {x}: {}", a.aux.part_id[35 * 48 + x]); + } +} + +#[test] +fn a_transparent_fragment_that_adds_alpha_is_the_surface() { + let grey = [0.5, 0.5, 0.5, 1.0]; + let glass = [0.0, 0.0, 1.0, 0.25]; + // Glass in front of an opaque quad on the left half; glass over nothing on the right half. + let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 300.0, grey), ([0.0, 0.0, 8.0, 4.0], 100.0, glass)]); + s.part_ids = vec![3, 3, 9, 9]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!((a.aux.part_id[1], a.aux.depth[1]), (9, 100.0)); + assert_eq!((a.aux.part_id[6], a.aux.depth[6]), (9, 100.0)); + // The opaque depth of the target is unchanged. + assert_eq!((a.target.depth[1], a.target.depth[6]), (300.0, f32::INFINITY)); + // Glass behind the opaque quad is hidden: the opaque quad stays the surface. + let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 100.0, grey), ([0.0, 0.0, 8.0, 4.0], 300.0, glass)]); + s.part_ids = vec![3, 3, 9, 9]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!((a.aux.part_id[1], a.aux.part_id[6]), (3, 9)); +} + +#[test] +fn of_several_transparent_layers_the_nearest_is_the_surface() { + // Drawn back to front, and also in the wrong order: the nearer layer is the surface either way. + for (first, second) in [(100.0, 50.0), (50.0, 100.0)] { + let mut s = quad_scene(8, 8, &[([0.0, 0.0, 8.0, 8.0], first, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 8.0, 8.0], second, [0.0, 0.0, 1.0, 0.5])]); + s.part_ids = vec![1, 1, 2, 2]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let id = if second < first { 2 } else { 1 }; + assert!(a.aux.part_id.iter().all(|&p| p == id), "depths {first} then {second}: {:?}", a.aux.part_id); + assert!(a.aux.depth.iter().all(|&d| d == 50.0)); + } +} + +#[test] +fn a_fragment_that_adds_no_alpha_is_not_the_surface() { + // A shadows-only card with no light draws nothing (alpha 0) over an opaque quad and over + // nothing. + let mut s = quad_scene(8, 4, &[([0.0, 0.0, 4.0, 4.0], 300.0, [0.5, 0.5, 0.5, 1.0])]); + let m = s.materials.len() as u32; + s.materials.push(Material { shadows_only: true, double_sided: true, ..Material::default() }); + s.materials[0].unlit = true; + s.ambient = [0.0; 3]; + let b = s.vertices.len() as u32; + for (x, y) in [(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (0.0, 4.0)] { + s.vertices.push(Vertex { pos: [x, y, 100.0], normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: m }); + } + s.indices.extend([b, b + 2, b + 1, b, b + 3, b + 2]); + s.part_ids = vec![3, 3, 9, 9]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!(bits4(&a.target.color), bits4(&try_render(&s, &Limits::default()).unwrap().color)); + assert_eq!((a.aux.part_id[1], a.aux.depth[1]), (3, 300.0)); + assert_eq!((a.aux.part_id[6], a.aux.depth[6]), (NO_PART, f32::INFINITY)); +} + +#[test] +fn a_masked_out_fragment_hands_the_surface_to_the_one_behind() { + // A near opaque quad whose mask texture is clear on its left half, over a far quad. + let mut s = quad_scene(8, 4, &[([0.0, 0.0, 8.0, 4.0], 100.0, [1.0; 4]), ([0.0, 0.0, 8.0, 4.0], 300.0, [0.5, 0.5, 0.5, 1.0])]); + s.texels = vec![[1.0, 1.0, 1.0, 0.0], [1.0, 1.0, 1.0, 1.0]]; + s.textures = vec![TexInfo { offset: 0, width: 2, height: 1, wrap_u: 1, wrap_v: 1 }]; + s.materials[0].alpha_mode = 1; + s.materials[0].tex_base = 0; + // u runs 0 to 1 across the near quad. + for (k, v) in s.vertices[..4].iter_mut().enumerate() { + v.uv = [if k == 1 || k == 2 { 1.0 } else { 0.0 }, 0.0]; + v.normal = [0.0, 0.6, -0.8]; + } + s.part_ids = vec![5, 5, 6, 6]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert_eq!((a.aux.part_id[0], a.aux.depth[0], a.aux.normal[0]), (6, 300.0, [0.0, 0.0, -1.0])); + assert_eq!((a.aux.part_id[7], a.aux.depth[7]), (5, 100.0)); + assert!(dot(a.aux.normal[7], [0.0, 0.6, -0.8]) > 0.99999); + assert_eq!(a.target.depth[0], 300.0); +} + +#[test] +fn a_zero_area_triangle_has_no_surface() { + let mut s = quad_scene(8, 8, &[]); + s.materials.push(Material { unlit: true, double_sided: true, ..Material::default() }); + for p in [[1.0, 1.0, 10.0], [4.0, 4.0, 10.0], [7.0, 7.0, 10.0]] { + s.vertices.push(Vertex { pos: p, normal: [0.0, 0.0, -1.0], uv: [0.0; 2], tangent: [1.0, 0.0, 0.0, 1.0], material: 0 }); + } + s.indices = vec![0, 1, 2]; + s.opaque_count = 3; + s.part_ids = vec![4]; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + assert!(a.aux.part_id.iter().all(|&p| p == NO_PART)); + assert!(a.target.color.iter().all(|c| c[3] == 0.0)); +} + +#[test] +fn a_resolve_copies_the_nearest_subsample_of_each_block_whole() { + // At 2 × 2, a near quad's edge at x = 5 splits output pixel 2 between it and a far quad. + let mut s = quad_scene(16, 8, &[([0.0, 0.0, 16.0, 8.0], 500.0, [0.0, 0.0, 1.0, 1.0]), ([5.0, 0.0, 16.0, 8.0], 100.0, [1.0, 0.0, 0.0, 1.0])]); + s.ssaa = 2; + s.part_ids = vec![1, 1, 2, 2]; + let t = try_render_with_aux(&s, &Limits::default()).unwrap(); + let r = try_resolve_aux(&t, 2).unwrap(); + assert_eq!(r, try_render_cpu_with_aux(&s, &Limits::default()).unwrap()); + for y in 0..4 { + for x in 0..8 { + let block: Vec = (0..2).flat_map(|j| (0..2).map(move |i| (2 * y + j) * 16 + 2 * x + i)).collect(); + let best = block.iter().copied().min_by(|&a, &b| t.aux.depth[a].total_cmp(&t.aux.depth[b])).unwrap(); + let o = y * 8 + x; + assert_eq!( + (r.aux.depth[o], r.aux.normal[o], r.aux.part_id[o]), + (t.aux.depth[best], t.aux.normal[best], t.aux.part_id[best]), + "({x}, {y})" + ); + } + } + // Pixel 2 mixes both colors but reports one surface, the near quad, with its depth. + assert_eq!((r.aux.part_id[2], r.aux.depth[2]), (2, 100.0)); + assert!(r.image.data[2][0] > 0.0 && r.image.data[2][2] > 0.0); +} + +#[test] +fn a_resolve_breaks_depth_ties_by_the_first_subsample() { + let planes = |ids: [u32; 4]| AuxPlanes { depth: vec![7.0; 4], normal: vec![[0.0, 0.0, -1.0]; 4], part_id: ids.to_vec() }; + let t = AuxTarget { + target: craft_raster3d::Target { width: 2, height: 2, color: vec![[1.0; 4]; 4], depth: vec![7.0; 4] }, + aux: planes([4, 3, 2, 1]), + }; + let AuxImage { aux, .. } = try_resolve_aux(&t, 2).unwrap(); + assert_eq!(aux.part_id, vec![4]); +} + +#[test] +fn a_resolve_rejects_planes_of_the_wrong_length_and_a_bad_factor() { + let s = with_ids(quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])])); + let t = try_render_with_aux(&s, &Limits::default()).unwrap(); + for f in [ + |t: &mut AuxTarget| t.aux.depth.pop().map(drop), + |t: &mut AuxTarget| t.aux.normal.pop().map(drop), + |t: &mut AuxTarget| t.aux.part_id.pop().map(drop), + ] { + let mut bad = t.clone(); + f(&mut bad); + assert_eq!(try_resolve_aux(&bad, 2), Err(RenderError::BadDataLength { expected: 16, found: 15 })); + } + assert_eq!(try_resolve_aux(&t, 3), Err(RenderError::BadFactor { k: 3, width: 4, height: 4 })); + assert_eq!(try_resolve_aux(&t, 0), Err(RenderError::BadFactor { k: 0, width: 4, height: 4 })); +} + +#[test] +fn part_ids_must_name_every_triangle_with_an_unreserved_id() { + let s = quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])]); + assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadPartIdCount { expected: 2, found: 0 })); + let s = Scene { part_ids: vec![1, 2, 3], ..s }; + assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadPartIdCount { expected: 2, found: 3 })); + let s = Scene { part_ids: vec![0, NO_PART], ..s }; + assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::ReservedPartId(1))); + assert_eq!(try_render_cpu_with_aux(&s, &Limits::default()), Err(RenderError::ReservedPartId(1))); + // The renderers without auxiliary outputs do not read them. + assert!(try_render(&s, &Limits::default()).is_ok()); +} + +#[test] +fn a_view_that_cannot_turn_normals_is_rejected() { + let mut s = with_ids(quad_scene(4, 4, &[([0.0, 0.0, 4.0, 4.0], 10.0, [1.0; 4])])); + s.view = [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + assert_eq!(try_render_with_aux(&s, &Limits::default()), Err(RenderError::BadTransform)); + assert!(try_render(&s, &Limits::default()).is_ok()); +} + +#[test] +fn the_byte_check_counts_the_auxiliary_planes() { + // The base target's 40 bytes per pixel fit `isize::MAX`, and 60 do not. + let l = limits(|l| l.max_pixels = u64::MAX); + #[cfg(target_pointer_width = "64")] + let (w, h, resolve_h) = (1 << 30, 150_000_000, 100_000_000); + #[cfg(target_pointer_width = "32")] + let (w, h, resolve_h) = (1 << 20, 40, 24); + assert!(l.check(w, h).is_ok()); + let s = Scene { width: w, height: h, ..Scene::default() }; + assert_eq!(try_render_with_aux(&s, &l), Err(RenderError::TooLarge(w, h))); + assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, h))); + // The smaller raster fits, and its resolve at 1 × 1 adds 40 bytes per pixel more. + let s = Scene { width: w, height: resolve_h, ..Scene::default() }; + assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, resolve_h))); +} + +#[test] +fn the_auxiliary_pass_obeys_the_fallback_work_limit() { + let white = [1.0; 4]; + let mut s = with_ids(quad_scene(4, 32, &[([0.0, 0.0, 4.0, 32.0], 100.0, white), ([0.0, 0.0, 4.0, 32.0], 50.0, white)])); + s.materials[1].alpha_mode = 1; + s.materials[1].base[3] = 0.0; + let setup = 4 * (4 * 32 + 1); + let limited = limits(|l| l.max_work = setup); + assert!(try_render_with_aux(&s, &limits(|l| l.max_work = u64::MAX)).is_ok()); + assert!(matches!(try_render_with_aux(&s, &limited), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup)); + assert!(matches!(try_render_cpu_with_aux(&s, &limited), Err(RenderError::TooMuchWork { limit, needed }) if limit == setup && needed > setup)); + s.materials[1].base[3] = 1.0; + assert!(try_render_with_aux(&s, &limited).is_ok()); + assert!(try_render_cpu_with_aux(&s, &limited).is_ok()); +} diff --git a/crates/raster3d/tests/it/bounds.rs b/crates/raster3d/tests/it/bounds.rs index b73dcc7f35..ee29838eba 100644 --- a/crates/raster3d/tests/it/bounds.rs +++ b/crates/raster3d/tests/it/bounds.rs @@ -1024,7 +1024,12 @@ fn negative_shadow_diffusion_is_rejected() { try_shadow_maps(&mut s, false, &Limits::default()).unwrap(); assert!(try_render(&s, &Limits::default()).is_ok()); let e = EnvInfo { sun: [0.0, -1.0, 0.0], ..s.env.unwrap() }; - assert_eq!(try_env_shadow_map(e, [0.0; 3], 100.0, 512).map(|m| m.radius), Ok(8.0)); + let base = try_env_shadow_map(e, [0.0; 3], 100.0, 512).map(|m| m.radius); + assert_eq!(base, Ok(8.0)); + // A positive diffusion widens the penumbra past that minimum. + let wide = EnvInfo { shadow_diffusion: 4.0, ..e }; + let widened = try_env_shadow_map(wide, [0.0; 3], 100.0, 512).map(|m| m.radius); + assert!(widened.as_ref().is_ok_and(|&r| r > 8.0), "{widened:?}"); } #[test] diff --git a/crates/raster3d/tests/it/differential.rs b/crates/raster3d/tests/it/differential.rs index eb4b755794..3e30a42fa2 100644 --- a/crates/raster3d/tests/it/differential.rs +++ b/crates/raster3d/tests/it/differential.rs @@ -3,11 +3,21 @@ //! pixel matches bit for bit; the README's Origin section lists the scenes that differ. Each test //! prints the 64-bit FNV-1a hash of each output from both sides. -use craft_raster3d::{Limits, Scene, try_encode, try_render, try_render_cpu, try_resolve, try_shadow_maps}; +use craft_raster3d::{Limits, Scene, ShadowMap, try_encode, try_render, try_render_cpu, try_resolve, try_shadow_maps}; use crate::reference::effectcraft as ec; use crate::{bits, bits4, fnv, lit_scene, quad_scene}; +/// A shadow map's fields, with each float as its bits. +type MapBits = ([[u32; 4]; 3], u32, bool, u32, u32, u32, u32); + +/// The fields of each shadow map, with the floats as bits so that 0 and −0 differ. +fn map_bits(maps: &[ShadowMap]) -> Vec { + maps.iter() + .map(|m| (m.view.map(|r| r.map(f32::to_bits)), m.focal.to_bits(), m.ortho, m.size, m.offset, m.bias.to_bits(), m.radius.to_bits())) + .collect() +} + /// Runs both sides on `scene`: shadow maps (when `shadows`), the raster, the resolve and the /// encoding, and asserts that every output matches bit for bit. fn compare(name: &str, scene: &Scene, shadows: Option) { @@ -15,7 +25,7 @@ fn compare(name: &str, scene: &Scene, shadows: Option) { if let Some(draft) = shadows { try_shadow_maps(&mut ours, draft, &Limits::default()).unwrap(); ec::raster::shadow_maps(&mut theirs, draft); - assert_eq!(ours.shadows, theirs.shadows, "{name}: shadow maps"); + assert_eq!(map_bits(&ours.shadows), map_bits(&theirs.shadows), "{name}: shadow maps"); assert_eq!(bits(&ours.shadow_texels), bits(&theirs.shadow_texels), "{name}: shadow texels"); assert_eq!(ours.lights, theirs.lights, "{name}: light marks"); assert_eq!(ours.env, theirs.env, "{name}: environment mark"); @@ -35,6 +45,7 @@ fn compare(name: &str, scene: &Scene, shadows: Option) { assert_eq!(bits(&depth), bits(&rdepth), "{name}: resolved depth"); let (cpu, cpu_depth) = try_render_cpu(&ours, &Limits::default()).unwrap(); let (rcpu, rcpu_depth) = ec::render_cpu(&theirs); + assert_eq!((cpu.width, cpu.height), (rcpu.width, rcpu.height), "{name}: render_cpu size"); assert_eq!(bits4(&cpu.data), bits4(&rcpu.data), "{name}: render_cpu color"); assert_eq!(bits(&cpu_depth), bits(&rcpu_depth), "{name}: render_cpu depth"); println!("{name} resolved: ours {:016x} theirs {:016x}", fnv(&img.data, &depth), fnv(&rimg.data, &rdepth)); diff --git a/crates/raster3d/tests/it/main.rs b/crates/raster3d/tests/it/main.rs index 98f3485e8c..5352e22ae1 100644 --- a/crates/raster3d/tests/it/main.rs +++ b/crates/raster3d/tests/it/main.rs @@ -2,6 +2,7 @@ // Unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod aux_outputs; mod bounds; mod differential; mod moved; diff --git a/crates/raster3d/tests/it/reference/effectcraft/raster.rs b/crates/raster3d/tests/it/reference/effectcraft/raster.rs index 128263c7f3..9e12b837bc 100644 --- a/crates/raster3d/tests/it/reference/effectcraft/raster.rs +++ b/crates/raster3d/tests/it/reference/effectcraft/raster.rs @@ -1,6 +1,12 @@ //! EffectCraft's `crates/render/src/three_d/adv/raster.rs`. Changes: the imports (the scene //! types come from this crate, `basis_view` and `vec3` from `super::geom`), `pub` in place of //! `pub(crate)`, comments removed, and two expressions broken over lines as rustfmt asks. +//! +//! The code keeps EffectCraft's behavior where the crate differs from it, so the differential +//! tests compare against the code EffectCraft runs. Two such points: the visibility pass reads a +//! depth of 0 as an empty pixel, so a fragment on the far plane is drawn only by the fallback under +//! a discarded fragment, and a blended caster without a base texture is drawn whatever its alpha +//! times the opacity. The README's Origin section lists both as changes. use std::cmp::Reverse; use std::collections::BinaryHeap; From d896484bdc121300516ab5bc8f9dcc5cac6dfa96 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:29:13 -0800 Subject: [PATCH 2/4] craft-raster3d: move the 256-subsample resolve cutoff to its own pull request The f64 averaging of resolve blocks over 256 subsamples changes existing try_resolve results, so it moved to #4353. try_resolve keeps the 2^24 cutoff here. --- crates/raster3d/README.md | 10 ++++------ crates/raster3d/src/resolve.rs | 19 ++++++------------- 2 files changed, 10 insertions(+), 19 deletions(-) diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 98160be6f9..2c15709a20 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -86,7 +86,7 @@ Building a scene from an app's document (layers, cameras, models, text) stays in - **Resolve and encoding.** `try_resolve(&target, k)` averages each `k × k` block of premultiplied pixels with equal weights, and takes the mean depth of the block's covered pixels, infinity where none is covered; a pixel whose `f32` sums overflow, and every pixel when a block holds more than - 256 subsamples (`k` over 16), is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer + 2^24 subsamples, is averaged in `f64`. `try_encode(&mut image)` divides each color by alpha, applies the sRGB transfer function of CSS Color 4 (), a linear segment up to a magnitude of 0.0031308 and a 1/2.4 power above it, with a negative color keeping its sign, multiplies by alpha again and leaves alpha linear. `srgb_to_linear` decodes a negative @@ -167,7 +167,7 @@ far plane, where depth-range crossings lie within 1/4096 of an edge from its ins texture coordinates times the texture's width or height reach 2^23 in magnitude, where normals' squared lengths, squared distances from fragments to point and spot lights, or casters' light-space coordinates times a map's focal length overflow `f32`, where shadow-casting spot -lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 256 +lights' outer cones are over 1.40 radians wide, where resolve blocks hold more than 2^24 subsamples, where shadows-only materials do not receive shadows, where fragments under discarded opaque pixels leave the depth range, where blended casters have no base texture, where opaque-mode and masked casters have an opacity below 0.5, where casters reach within 1 unit of @@ -226,10 +226,8 @@ Changes from those files: - A spot light whose outer cone's half angle plus 0.05 radians is over 1.45 radians gets six maps, as a point light does. EffectCraft gave it one map 1.45 radians wide, so receivers in the rest of the cone were not shadowed. -- A resolve block of more than 256 subsamples is averaged in `f64`. EffectCraft summed every block - in `f32`: its sums dropped the low bits of each subsample as they grew (a 4096 × 4096 block of - 0.75 resolved to about 0.833), and its count of covered subsamples stopped at 2^24, which raised - the mean depth. +- A resolve block of more than 2^24 subsamples is averaged in `f64`. EffectCraft's `f32` count of + covered subsamples stopped at 2^24, which raised the mean depth. - A clipped corner whose `1/w` overflows `f32` (a clip transform scaled near `f32`'s smallest values) is projected in `f64` instead of dropping its triangle, and a drawn pixel whose camera depth overflows is an error. diff --git a/crates/raster3d/src/resolve.rs b/crates/raster3d/src/resolve.rs index 19726bc0a7..42a8cd1885 100644 --- a/crates/raster3d/src/resolve.rs +++ b/crates/raster3d/src/resolve.rs @@ -25,9 +25,6 @@ pub struct AuxImage { /// Alpha above 1 that [`try_encode`] accepts as rounding from blending. const ALPHA_SLACK: f32 = 1e-4; -/// The largest block [`try_resolve`] sums in `f32`. -const F32_SAMPLES: u64 = 256; - /// `w × h` as a length, when it fits `usize`. fn area(w: u32, h: u32) -> Option { usize::try_from(u64::from(w) * u64::from(h)).ok() @@ -36,7 +33,7 @@ fn area(w: u32, h: u32) -> Option { /// Box-filter a supersampled target down by `k` per side: each output pixel is the mean of its /// `k × k` premultiplied colors, and its depth is the mean of the covered subsamples' depths /// (infinity where none is covered). A pixel whose `f32` sums overflow, and every pixel when a -/// block holds more than 256 subsamples (`k` over 16), is averaged in `f64`. +/// block holds more than 2^24 subsamples, is averaged in `f64`. /// /// Returns [`RenderError::BadFactor`] when `k` is zero or does not divide both sides, and /// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height @@ -60,9 +57,8 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> return Ok((img, depth)); } let n = (u64::from(k) * u64::from(k)) as f32; - // An f32 sum drops the low bits of each sample as it grows, so a block of more than - // `F32_SAMPLES` subsamples is averaged in f64. - let wide = u64::from(k) * u64::from(k) > F32_SAMPLES; + // An f32 count stops at 2^24, so a larger block is averaged in f64. + let wide = u64::from(k) * u64::from(k) > 1 << 24; img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { for x in 0..w as usize { if wide { @@ -236,14 +232,11 @@ mod tests { use super::{AuxPlanes, AuxTarget, NO_PART, Target, try_resolve, try_resolve_aux}; #[test] - fn a_large_block_of_one_color_resolves_to_that_color() { - // An f32 sum of 2^20 samples of 0.7 drifts by whole percent. - let n = 1024u32; + fn the_auxiliary_resolve_keeps_the_color_resolve() { + let n = 4u32; let len = (n * n) as usize; let t = Target { width: n, height: n, color: vec![[0.7; 4]; len], depth: vec![0.5; len] }; - let (img, depth) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}")); - assert!(img.data[0].iter().all(|&c| (c - 0.7).abs() < 1e-6), "{:?}", img.data[0]); - assert!((depth[0] - 0.5).abs() < 1e-6, "{}", depth[0]); + let (img, _) = try_resolve(&t, n).unwrap_or_else(|e| panic!("{e:?}")); let aux = AuxPlanes { depth: vec![0.5; len], normal: vec![[0.0, 0.0, -1.0]; len], part_id: vec![NO_PART - 1; len] }; let a = try_resolve_aux(&AuxTarget { target: t, aux }, n).unwrap_or_else(|e| panic!("{e:?}")); assert_eq!(a.image, img); From fc716fbbd49e07141cbbb6f11afba4d1db66f1a3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 14:46:57 -0800 Subject: [PATCH 3/4] craft-raster3d: exact normal interpolation, f64 depth ties and aux-only scratch buffers - view_normal sums each interpolated normal component exactly, so a small component that cancels in f64 keeps its direction through the view's inverse transpose. - Transparent auxiliary surfaces whose f32 camera depths are equal are ordered by the untranslated camera depth in f64. - A render without auxiliary outputs no longer holds the fallback triangle indices and weights; the auxiliary byte check counts the band depth and fallback buffers. - try_resolve_aux no longer computes and drops a mean-depth buffer. --- crates/raster3d/README.md | 19 ++- crates/raster3d/src/lib.rs | 37 ++++- crates/raster3d/src/raster.rs | 196 ++++++++++++++++++++---- crates/raster3d/src/resolve.rs | 64 ++++++-- crates/raster3d/tests/it/aux_outputs.rs | 8 +- 5 files changed, 263 insertions(+), 61 deletions(-) diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index 2c15709a20..f6ac2a72fb 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -98,17 +98,19 @@ Building a scene from an app's document (layers, cameras, models, text) stays in `AuxPlanes`: three planes at the color's size, row-major from the top row, that describe one surface per pixel. `depth` is the surface's camera depth (`f32`, the units of `Scene::view`), infinity where empty. `normal` is its unit normal in view space, `[0, 0, 0]` where empty: the - vertex normal interpolated in `f64` (one of length 1e-20 or less is read as `[0, 0, −1]`), + vertex normal interpolated in `f64`, with exact sums for cancellation (one of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face, turned by the inverse transpose of the upper-left 3 × 3 of `Scene::view` and normalized, so it stays perpendicular to the surface when the view scales axes unequally or shears; normal textures are not applied. `part_id` is the `Scene::part_ids` entry of the surface's triangle (`u32`), or `NO_PART` (`u32::MAX`) where empty; a triangle cut by clipping keeps its ID. Only a fragment that adds alpha above 0 can be the surface: the nearest opaque surface drawn at the pixel, including the one found under a discarded fragment, or a nearer transparent fragment; of several such - fragments the nearest is kept. `depth` therefore differs from `Target::depth`, which holds opaque surfaces only. The + fragments the nearest is kept, with equal `f32` camera depths compared in `f64` during rendering. + `depth` therefore differs from `Target::depth`, which holds opaque surfaces only. The resolve copies the depth, normal and part ID of one subsample of each block, the one with the smallest depth (the first in row-major order on ties), so it does not average depths across - surfaces or mix IDs; a pixel holds one ID, not every surface that covers part of it. + surfaces or mix IDs; a pixel holds one ID, not every surface that covers part of it. The auxiliary + resolve does not allocate a mean-depth buffer. `try_render_with_aux` and `try_render_cpu_with_aux` need one part ID per triangle, none of them `NO_PART`, and, for a scene with a triangle, a view whose upper-left 3 × 3 is invertible. `try_resolve_aux` takes no scene: it needs a factor that divides both sides, as `try_resolve` @@ -142,10 +144,13 @@ Building a scene from an app's document (layers, cameras, models, text) stays in pixel that is not finite, an alpha below 0 or above 1 (beyond 1e-4 of rounding), or a color whose division by alpha overflows, and changes no pixel then; the error names the first such pixel. The renderer holds 40 bytes per raster pixel (color, depth and visibility) and up to seven clipped triangles of about 140 bytes per - scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 45 bytes per pixel - (a discard flag and a candidate fragment with its triangle and weights) while its opaque pixels - are shaded. With auxiliary outputs the renderer holds 20 bytes more per raster pixel, and - `try_render_cpu_with_aux` also 40 bytes per output pixel for the resolve; the sum must fit + scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 29 bytes per pixel + (a discard flag and a candidate fragment) while its opaque pixels are shaded. With auxiliary + outputs, each active band holds 8 bytes per pixel for depth comparisons and another 16 bytes + per pixel during fallback shading for triangle indices and weights. The auxiliary planes hold + 20 bytes more per raster pixel, and `try_render_cpu_with_aux` also holds 36 bytes per output pixel + for the resolve. The byte check reserves the 24 band bytes for every raster pixel, for a total + of 84 bytes per raster pixel plus 36 bytes per resolved output pixel. This sum must fit `isize::MAX` bytes, or the call returns `TooLarge` before it allocates. `try_render_with_aux` returns `BadPartIdCount`, `ReservedPartId` or `BadTransform` for the part IDs and view above, and `BadPixel` when an auxiliary depth overflows `f32`; `try_resolve_aux` returns `BadDataLength` for diff --git a/crates/raster3d/src/lib.rs b/crates/raster3d/src/lib.rs index 3304f6f2df..f0f621e3ac 100644 --- a/crates/raster3d/src/lib.rs +++ b/crates/raster3d/src/lib.rs @@ -223,8 +223,9 @@ impl Limits { } /// [`Limits::check`] for a render with auxiliary outputs, which also holds - /// [`AUX_BYTES_PER_PIXEL`] more bytes per raster pixel and, when it is resolved by `k` per side - /// (`resolve` is `Some(k)`), [`AUX_BYTES_PER_OUTPUT`] per output pixel: the sum of all of them + /// [`AUX_BYTES_PER_PIXEL`] more bytes per raster pixel, including concurrent band buffers, + /// and, when it is resolved by `k` per side (`resolve` is `Some(k)`), + /// [`AUX_BYTES_PER_OUTPUT`] per output pixel: the sum of all of them /// must fit `isize::MAX`. Nothing is allocated. pub(crate) fn check_aux(&self, w: u32, h: u32, resolve: Option) -> Result { let pixels = self.check(w, h)?; @@ -241,9 +242,31 @@ impl Limits { } } -/// Bytes the auxiliary outputs add per raster pixel: depth (4), normal (12) and part ID (4). -const AUX_BYTES_PER_PIXEL: u64 = 20; +/// Extra bytes reserved per raster pixel for auxiliary renders: depth (4), normal (12), part ID (4), +/// band depth comparisons (8), and fallback triangle indices and weights (16). +/// The band buffers are bounded by the full raster, including when bands run in parallel. +const AUX_BYTES_PER_PIXEL: u64 = 44; -/// Bytes a resolve with auxiliary outputs holds per output pixel: color (16), the mean depth that -/// [`try_resolve`] computes (4), depth (4), normal (12) and part ID (4). -const AUX_BYTES_PER_OUTPUT: u64 = 40; +/// Bytes a resolve with auxiliary outputs holds per output pixel: color (16), depth (4), +/// normal (12) and part ID (4). +const AUX_BYTES_PER_OUTPUT: u64 = 36; + +#[cfg(test)] +mod tests { + use super::{Limits, MAX_ALLOC_BYTES, RenderError}; + + #[test] + fn auxiliary_byte_check_counts_concurrent_band_buffers() { + let limits = Limits { max_pixels: u64::MAX, ..Limits::default() }; + #[cfg(target_pointer_width = "64")] + let (w, h) = (1 << 30, 120_000_000); + #[cfg(target_pointer_width = "32")] + let (w, h) = (1 << 20, 30); + let pixels = u64::from(w) * u64::from(h); + assert!(limits.check(w, h).is_ok()); + assert!(pixels * (40 + 20) <= MAX_ALLOC_BYTES); + assert!(pixels * (40 + 20 + 8 + 16) > MAX_ALLOC_BYTES); + assert_eq!(limits.check_aux(w, h, None), Err(RenderError::TooLarge(w, h))); + assert_eq!(limits.check_aux(w, h, Some(2)), Err(RenderError::TooLarge(w, h))); + } +} diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index 43409425d8..f951bd2b56 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -37,15 +37,16 @@ pub struct Target { /// /// The surface of a pixel is the nearest opaque surface drawn there (after an alpha test or a /// single-sided back face hands the pixel to the next surface), or a transparent fragment that -/// adds alpha above 0 and is nearer in camera depth than the surface before it. All three planes -/// name the same surface. +/// adds alpha above 0 and is nearer in camera depth than the surface before it. Equal `f32` +/// depths are compared in `f64` without the view translation. All three planes name the same surface. #[derive(Clone, Debug, Default, PartialEq)] pub struct AuxPlanes { /// Camera-space depth of the surface (the third row of [`Scene::view`]), ∞ where empty. For /// a transparent surface this differs from [`Target::depth`], which holds opaque surfaces only. pub depth: Vec, /// Unit normal of the surface in view space, `[0, 0, 0]` where empty: the vertex normal - /// interpolated in `f64` (a vector of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face, + /// interpolated in `f64`, with exact sums for cancellation (a vector of length 1e-20 or less is + /// read as `[0, 0, −1]`), reversed on a back face, /// turned by the inverse transpose of the upper-left 3 × 3 of [`Scene::view`] and normalized, /// so it stays perpendicular to the surface under a non-uniform scale or a shear. Normal /// textures are not applied. @@ -64,23 +65,25 @@ pub struct AuxTarget { /// One band's rows of the auxiliary planes. struct AuxRow<'a> { depth: &'a mut [f32], + precise_depth: Vec, normal: &'a mut [[f32; 3]], part: &'a mut [u32], } impl AuxRow<'_> { /// Make (camera depth `z`, normal `n` and `part`) the surface of pixel `i`. - fn set(&mut self, i: usize, z: f32, n: [f32; 3], part: u32) { + fn set(&mut self, i: usize, z: f32, precise_z: f64, n: [f32; 3], part: u32) { self.depth[i] = z; + self.precise_depth[i] = precise_z; self.normal[i] = n; self.part[i] = part; } /// Make the surface of pixel `i` the given one when its camera depth `z` is nearer than the - /// pixel's (a NaN depth always replaces it, so the render reports it, and is never replaced). - fn offer(&mut self, i: usize, z: f32, n: impl FnOnce() -> [f32; 3], part: u32) { - if !self.depth[i].is_nan() && (z.is_nan() || z < self.depth[i]) { - self.set(i, z, n(), part); + /// pixel's, using `precise_z` to break `f32` ties. A NaN depth always replaces it and is never replaced. + fn offer(&mut self, i: usize, z: f32, precise_z: f64, n: impl FnOnce() -> [f32; 3], part: u32) { + if !self.depth[i].is_nan() && (z.is_nan() || z < self.depth[i] || (z == self.depth[i] && precise_z < self.precise_depth[i])) { + self.set(i, z, precise_z, n(), part); } } } @@ -482,9 +485,12 @@ struct FallbackFragment { ndc_z: f32, color: [f32; 4], camera_depth: f32, - /// The screen triangle and its weights at the pixel. - tri: u32, - l: [f32; 3], +} + +/// The fallback fragments and, for auxiliary renders, their screen triangles and weights. +struct Fallback { + fragments: Vec>, + aux: Option>, } /// The visibility depth of a pixel with no opaque surface: below the far plane's 0, so a @@ -510,6 +516,12 @@ impl Band<'_> { if z.is_finite() { z } else { f32::NAN } } + /// The untranslated camera-depth dot product in `f64` for auxiliary surface comparisons. + fn depth_tie_key(&self, p: [f32; 3]) -> f64 { + let row = self.s.view[2].map(f64::from); + row[0] * f64::from(p[0]) + row[1] * f64::from(p[1]) + row[2] * f64::from(p[2]) + } + /// The unit view-space normal for [`AuxPlanes::normal`] of screen triangle `t` at /// screen-corner weights `l`. The vertex normals are interpolated, normalized and turned in /// `f64`, so finite normals near the top of the `f32` range do not overflow. @@ -529,13 +541,9 @@ impl Band<'_> { wv[k] += l[c] * t.w[c][k]; } } - let mut sum = [0.0f64; 3]; - for (k, &x) in wv.iter().enumerate() { - let vn = s.vertices[s.indices[base + k] as usize].normal; - for i in 0..3 { - sum[i] += f64::from(vn[i]) * f64::from(x); - } - } + let interpolation: [[(f64, f64); 3]; 3] = + std::array::from_fn(|i| std::array::from_fn(|k| (f64::from(s.vertices[s.indices[base + k] as usize].normal[i]), f64::from(wv[k])))); + let sum = interpolation.map(crate::scene::sum_of_products); // The interpolated normal is turned as it is and normalized after, so its components keep // their exact ratios through the transform. let mut n = if unit(sum, 1e-20).is_some() { sum } else { [0.0, 0.0, -1.0] }; @@ -623,7 +631,7 @@ impl Band<'_> { if let Some(a) = aux && c[3] > 0.0 { - a.set(i, drow[i], self.view_normal(t, l), self.part(t)); + a.set(i, drow[i], self.depth_tie_key(f.pos), self.view_normal(t, l), self.part(t)); } } None => discarded[i] = true, @@ -632,7 +640,8 @@ impl Band<'_> { if !discarded.contains(&true) { return Ok(()); } - for (i, best) in self.fallback(opaque, vis, &discarded)?.into_iter().enumerate() { + let fallback = self.fallback(opaque, vis, &discarded, aux.is_some())?; + for (i, best) in fallback.fragments.into_iter().enumerate() { if !discarded[i] { continue; } @@ -643,9 +652,11 @@ impl Band<'_> { vis[i].1 = f.ndc_z; if let Some(a) = aux && f.color[3] > 0.0 + && let Some(surface) = &fallback.aux { - let t = &opaque.tris[f.tri as usize]; - a.set(i, f.camera_depth, self.view_normal(t, f.l), self.part(t)); + let (ti, l) = surface[i]; + let t = &opaque.tris[ti as usize]; + a.set(i, f.camera_depth, self.depth_tie_key(frag(s, t, l).pos), self.view_normal(t, l), self.part(t)); } } None => vis[i].1 = EMPTY, @@ -658,10 +669,12 @@ impl Band<'_> { /// triangle other than the pixel's visible one, inside the depth range as in /// [`Band::visibility`]. Triangles are /// visited in index order over their bounding boxes, and among fragments at equal depth the - /// first triangle's is kept. Coverage tests count toward [`Limits::max_work`]. - fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result>, RenderError> { + /// first triangle's is kept. Triangle indices and weights are stored only when `aux` is true. + /// Coverage tests count toward [`Limits::max_work`]. + fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool], aux: bool) -> Result { let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows); let mut best: Vec> = vec![None; rows * w]; + let mut surface = aux.then(|| vec![(u32::MAX, [0.0; 3]); rows * w]); for &tj in opaque.bins { let t2 = &opaque.tris[tj as usize]; let mut tests = 0u64; @@ -678,7 +691,10 @@ impl Band<'_> { { let f2 = frag(s, t2, l2); if let Some(c) = shade(s, &f2) { - best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos), tri: tj, l: l2 }); + best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos) }); + if let Some(surface) = &mut surface { + surface[i] = (tj, l2); + } } } } @@ -688,7 +704,7 @@ impl Band<'_> { return Err(RenderError::TooMuchWork { needed, limit: self.limit }); } } - Ok(best) + Ok(Fallback { fragments: best, aux: surface }) } /// Transparent fragments in order, blended over the opaque result where they are nearer. @@ -713,7 +729,7 @@ impl Band<'_> { if let Some(a) = aux && c[3] > 0.0 { - a.offer(i, self.cam_z(f.pos), || self.view_normal(t, l), self.part(t)); + a.offer(i, self.cam_z(f.pos), self.depth_tie_key(f.pos), || self.view_normal(t, l), self.part(t)); } } } @@ -755,7 +771,10 @@ fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, aux: bool, .zip(planes.normal.par_chunks_mut(band_rows)) .zip(planes.part_id.par_chunks_mut(band_rows)) .enumerate() - .try_for_each(|(band, ((((crow, drow), depth), normal), part))| render(band, crow, drow, Some(AuxRow { depth, normal, part })))?; + .try_for_each(|(band, ((((crow, drow), depth), normal), part))| { + let precise_depth = vec![f64::INFINITY; depth.len()]; + render(band, crow, drow, Some(AuxRow { depth, precise_depth, normal, part })) + })?; } else { color .par_chunks_mut(band_rows) @@ -810,8 +829,10 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result { /// Besides the checks of [`try_render`], [`Scene::part_ids`] must hold one ID per triangle and /// none may be [`NO_PART`], and, when the scene has a triangle, the upper-left 3 × 3 of /// [`Scene::view`] must be invertible. The -/// render holds 20 more bytes per raster pixel than [`try_render`], and their sum with the -/// target's must fit `isize::MAX` bytes. +/// output holds 20 more bytes per raster pixel than [`try_render`]. Each active band also holds +/// 8 bytes per pixel for depth comparisons and, during fallback shading, 16 bytes per pixel for +/// triangle indices and weights. The byte check reserves all 24 band bytes per raster pixel, +/// for a total of 84 bytes per raster pixel that must fit `isize::MAX` bytes. pub fn try_render_with_aux(s: &Scene, limits: &Limits) -> Result { let (pixels, opaque, trans, work) = prepare(s, limits, true)?; let (target, aux) = raster(s, &opaque, &trans, pixels, true, work, limits.max_work)?; @@ -824,7 +845,7 @@ pub fn try_render_with_aux(s: &Scene, limits: &Limits) -> Result 0.0); + assert_eq!(n[0], n[1]); + assert_eq!(n[2], 0.0); + assert!((n[0] * n[0] + n[1] * n[1] - 1.0).abs() < 1e-6); + } + + #[test] + fn a_non_auxiliary_fallback_keeps_only_the_baseline_fragment_buffer() { + type BaselineFragment = (f32, [f32; 4], f32); + assert_eq!(std::mem::size_of::(), std::mem::size_of::()); + assert_eq!(std::mem::size_of::>(), std::mem::size_of::>()); + let s = Scene::default(); + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 2, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let pass = Pass { tris: &[], bins: &[] }; + let vis = vec![(u32::MAX, super::EMPTY, [0.0; 3]); 2]; + let baseline = b.fallback(pass, &vis, &[true; 2], false).unwrap(); + assert_eq!(baseline.fragments.len(), 2); + assert!(baseline.aux.is_none()); + let auxiliary = b.fallback(pass, &vis, &[true; 2], true).unwrap(); + assert_eq!(auxiliary.aux.unwrap().len(), 2); + } + + #[test] + fn auxiliary_depth_ties_keep_the_nearer_surface_in_f64() { + let mut s = Scene::default(); + s.view[2] = [1.0, 0.0, 1.0, 0.0]; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let (far, near) = ([2f32.powi(-25), 0.0, 1.0], [0.0, 0.0, 1.0]); + assert_eq!(b.cam_z(far), b.cam_z(near)); + assert!(b.depth_tie_key(near) < b.depth_tie_key(far)); + let mut depth = [f32::INFINITY]; + let mut normal = [[0.0; 3]]; + let mut part = [super::NO_PART]; + let mut row = AuxRow { depth: &mut depth, precise_depth: vec![f64::INFINITY], normal: &mut normal, part: &mut part }; + let n = [1.0, 0.0, 0.0]; + row.offer(0, b.cam_z(far), b.depth_tie_key(far), || n, 10); + row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + assert_eq!(row.part[0], 20); + row.offer(0, b.cam_z(far), b.depth_tie_key(far), || panic!("farther surface replaced the nearer one"), 10); + assert_eq!(row.part[0], 20); + row.set(0, b.cam_z(far), b.depth_tie_key(far), n, 30); + row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + assert_eq!(row.part[0], 20); + row.offer(0, f32::NAN, f64::NAN, || n, 40); + row.offer(0, b.cam_z(near), b.depth_tie_key(near), || panic!("NaN surface was replaced"), 20); + assert_eq!(row.part[0], 40); + assert!(row.depth[0].is_nan()); + } + + #[test] + fn auxiliary_depth_ties_ignore_large_camera_translations() { + let mut s = Scene::default(); + s.view[2] = [0.0, 0.0, 1.0, 2f32.powi(60)]; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let (near, far) = ([0.0, 0.0, 0.25], [0.0, 0.0, 0.5]); + assert_eq!(b.cam_z(near), b.cam_z(far)); + let mut depth = [f32::INFINITY]; + let mut normal = [[0.0; 3]]; + let mut part = [super::NO_PART]; + let mut row = AuxRow { depth: &mut depth, precise_depth: vec![f64::INFINITY], normal: &mut normal, part: &mut part }; + let n = [1.0, 0.0, 0.0]; + row.set(0, b.cam_z(far), b.depth_tie_key(far), n, 10); + row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + assert_eq!(row.part[0], 20); + assert_eq!(row.depth[0], b.cam_z(near)); + row.offer(0, b.cam_z(far), b.depth_tie_key(far), || panic!("farther surface replaced the nearer one"), 10); + assert_eq!(row.part[0], 20); + row.offer(0, b.cam_z(near), b.depth_tie_key(near), || panic!("equal depth replaced the surface"), 30); + assert_eq!(row.part[0], 20); + } + #[test] fn a_view_whose_cofactors_nearly_cancel_still_turns_the_normal() { // The view's determinant is −2^-60, and the rounded cofactors give the normal [1, 1, 0] a diff --git a/crates/raster3d/src/resolve.rs b/crates/raster3d/src/resolve.rs index 42a8cd1885..01c74d70c0 100644 --- a/crates/raster3d/src/resolve.rs +++ b/crates/raster3d/src/resolve.rs @@ -39,6 +39,12 @@ fn area(w: u32, h: u32) -> Option { /// [`RenderError::BadDataLength`] when the color or depth buffer does not hold width × height /// values. pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> { + let (image, depth) = resolve(t, k, true)?; + Ok((image, depth.unwrap_or_default())) +} + +/// Box-filter the color and optionally store the mean depth. +fn resolve(t: &Target, k: u32, mean_depth: bool) -> Result<(Image, Option>), RenderError> { if k == 0 || !t.width.is_multiple_of(k) || !t.height.is_multiple_of(k) { return Err(RenderError::BadFactor { k, width: t.width, height: t.height }); } @@ -52,17 +58,21 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> // Fits: at most `expected`. let out = area(w, h).unwrap_or(0); let mut img = Image { width: w, height: h, data: vec![[0.0; 4]; out] }; - let mut depth = vec![f32::INFINITY; out]; + let mut depth = mean_depth.then(|| vec![f32::INFINITY; out]); if out == 0 { return Ok((img, depth)); } let n = (u64::from(k) * u64::from(k)) as f32; // An f32 count stops at 2^24, so a larger block is averaged in f64. let wide = u64::from(k) * u64::from(k) > 1 << 24; - img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { - for x in 0..w as usize { + let resolve_row = |y: usize, row: &mut [[f32; 4]], mut drow: Option<&mut [f32]>| { + for (x, pixel) in row.iter_mut().enumerate() { + let mut d = f32::INFINITY; if wide { - (row[x], drow[x]) = mean_f64(t, k as usize, x, y); + (*pixel, d) = mean_f64(t, k as usize, x, y); + if let Some(drow) = &mut drow { + drow[x] = d; + } continue; } let mut acc = [0.0f32; 4]; @@ -80,16 +90,26 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> } } } - row[x] = acc.map(|v| v / n); + *pixel = acc.map(|v| v / n); if dn > 0.0 { - drow[x] = dz / dn; + d = dz / dn; } // Large finite samples can overflow the f32 sums; such a pixel is averaged in f64. - if !row[x].iter().all(|v| v.is_finite()) || drow[x].is_nan() || (dn > 0.0 && drow[x].is_infinite()) { - (row[x], drow[x]) = mean_f64(t, k as usize, x, y); + if !pixel.iter().all(|v| v.is_finite()) || d.is_nan() || (dn > 0.0 && d.is_infinite()) { + (*pixel, d) = mean_f64(t, k as usize, x, y); + } + if let Some(drow) = &mut drow { + drow[x] = d; } } - }); + }; + if let Some(depth) = &mut depth { + img.data.par_chunks_mut(w as usize).zip(depth.par_chunks_mut(w as usize)).enumerate().for_each(|(y, (row, drow))| { + resolve_row(y, row, Some(drow)); + }); + } else { + img.data.par_chunks_mut(w as usize).enumerate().for_each(|(y, row)| resolve_row(y, row, None)); + } Ok((img, depth)) } @@ -97,7 +117,8 @@ pub fn try_resolve(t: &Target, k: u32) -> Result<(Image, Vec), RenderError> /// [`try_resolve`]'s, bit for bit. Each output pixel's depth, normal and part ID are copied /// together from one subsample of its `k × k` block: the one with the smallest finite depth, the /// first in row-major order on ties. A block with no surface gives ∞, `[0, 0, 0]` and -/// [`NO_PART`]; depths are not averaged and IDs are not mixed. +/// [`NO_PART`]; depths are not averaged and IDs are not mixed. The resolve does not allocate a +/// mean-depth buffer. /// /// Returns the errors of [`try_resolve`], and [`RenderError::BadDataLength`] when an auxiliary /// plane does not hold width × height values. @@ -112,7 +133,7 @@ pub fn try_resolve_aux(t: &AuxTarget, k: u32) -> Result { return Err(RenderError::BadDataLength { expected, found }); } } - let (image, _) = try_resolve(tt, k)?; + let (image, _) = resolve(tt, k, false)?; let (w, out) = (image.width as usize, image.data.len()); let mut aux = AuxPlanes { depth: vec![f32::INFINITY; out], normal: vec![[0.0; 3]; out], part_id: vec![NO_PART; out] }; if out == 0 { @@ -229,7 +250,26 @@ pub fn try_render_cpu_with_aux(s: &Scene, limits: &Limits) -> Result| pixels.into_iter().map(|p| p.map(f32::to_bits)).collect::>(); + assert_eq!(bits(image.data), bits(expected.data)); + } + } + let empty = Target { width: 0, height: 2, color: vec![], depth: vec![] }; + let (image, depth) = resolve(&empty, 2, false).unwrap(); + assert!(image.data.is_empty()); + assert!(depth.is_none()); + } #[test] fn the_auxiliary_resolve_keeps_the_color_resolve() { diff --git a/crates/raster3d/tests/it/aux_outputs.rs b/crates/raster3d/tests/it/aux_outputs.rs index 213f81df6e..e5825f8be6 100644 --- a/crates/raster3d/tests/it/aux_outputs.rs +++ b/crates/raster3d/tests/it/aux_outputs.rs @@ -474,17 +474,17 @@ fn a_view_that_cannot_turn_normals_is_rejected() { #[test] fn the_byte_check_counts_the_auxiliary_planes() { - // The base target's 40 bytes per pixel fit `isize::MAX`, and 60 do not. + // The base target's 40 bytes per pixel fit `isize::MAX`, and the auxiliary render's 84 do not. let l = limits(|l| l.max_pixels = u64::MAX); #[cfg(target_pointer_width = "64")] - let (w, h, resolve_h) = (1 << 30, 150_000_000, 100_000_000); + let (w, h, resolve_h) = (1 << 30, 150_000_000, 80_000_000); #[cfg(target_pointer_width = "32")] - let (w, h, resolve_h) = (1 << 20, 40, 24); + let (w, h, resolve_h) = (1 << 20, 40, 20); assert!(l.check(w, h).is_ok()); let s = Scene { width: w, height: h, ..Scene::default() }; assert_eq!(try_render_with_aux(&s, &l), Err(RenderError::TooLarge(w, h))); assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, h))); - // The smaller raster fits, and its resolve at 1 × 1 adds 40 bytes per pixel more. + // The smaller raster fits, and its resolve at 1 × 1 adds 36 bytes per output pixel. let s = Scene { width: w, height: resolve_h, ..Scene::default() }; assert_eq!(try_render_cpu_with_aux(&s, &l), Err(RenderError::TooLarge(w, resolve_h))); } From 168643233be2c0b10bed7cf8e8c274c09ea54670 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 15:35:52 -0800 Subject: [PATCH 4/4] craft-raster3d: exact aux depth ties from vertex positions, normals transformed before rounding The auxiliary depth tie-breaker now compares depths interpolated from the original vertex positions and weights, normalized by the total weight, with exact expansions. Equal normalized depths stay tied, so the earlier surface keeps the pixel. The exact keys are only computed when two `f32` depths are equal, after a bounded `f64` comparison cannot separate them. The view-space normal keeps the interpolation's exact expansion terms through the inverse-transpose transform instead of rounding them first. The auxiliary byte limit counts the per-pixel tie-breaking scratch at its real size. The near-plane projection change in `project` and the shadow-caster changes in `shadow.rs` are reverted to `main`, with their tests: they change `try_render` without auxiliary outputs and go up in their own pull requests. --- crates/raster3d/README.md | 20 +- crates/raster3d/src/lib.rs | 15 +- crates/raster3d/src/raster.rs | 370 +++++++++++++++++++----- crates/raster3d/src/scene.rs | 92 +++++- crates/raster3d/src/shadow.rs | 41 +-- crates/raster3d/tests/it/aux_outputs.rs | 19 +- 6 files changed, 419 insertions(+), 138 deletions(-) diff --git a/crates/raster3d/README.md b/crates/raster3d/README.md index f6ac2a72fb..4f64bfb481 100644 --- a/crates/raster3d/README.md +++ b/crates/raster3d/README.md @@ -98,14 +98,18 @@ Building a scene from an app's document (layers, cameras, models, text) stays in `AuxPlanes`: three planes at the color's size, row-major from the top row, that describe one surface per pixel. `depth` is the surface's camera depth (`f32`, the units of `Scene::view`), infinity where empty. `normal` is its unit normal in view space, `[0, 0, 0]` where empty: the - vertex normal interpolated in `f64`, with exact sums for cancellation (one of length 1e-20 or less is read as `[0, 0, −1]`), + vertex normal interpolated in `f64`, with exact expansion terms through the transform on cancellation + (one of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face, turned by the inverse transpose of the upper-left 3 × 3 of `Scene::view` and normalized, so it stays perpendicular to the surface when the view scales axes unequally or shears; normal textures are not applied. `part_id` is the `Scene::part_ids` entry of the surface's triangle (`u32`), or `NO_PART` (`u32::MAX`) where empty; a triangle cut by clipping keeps its ID. Only a fragment that adds alpha above 0 can be the surface: the nearest opaque surface drawn at the pixel, including the one found under a discarded fragment, or a nearer transparent fragment; of several such - fragments the nearest is kept, with equal `f32` camera depths compared in `f64` during rendering. + fragments the nearest is kept. Equal `f32` camera depths are compared in `f64` with a rounding + bound and an exact expansion fallback. Normalized depths are compared by cross-multiplying + their total original-vertex weights, without the view translation during rendering. + Equal normalized depths keep the earlier surface. `depth` therefore differs from `Target::depth`, which holds opaque surfaces only. The resolve copies the depth, normal and part ID of one subsample of each block, the one with the smallest depth (the first in row-major order on ties), so it does not average depths across @@ -146,11 +150,12 @@ Building a scene from an app's document (layers, cameras, models, text) stays in pixel (color, depth and visibility) and up to seven clipped triangles of about 140 bytes per scene triangle. A band of 16 rows that has a discarded opaque pixel also holds 29 bytes per pixel (a discard flag and a candidate fragment) while its opaque pixels are shaded. With auxiliary - outputs, each active band holds 8 bytes per pixel for depth comparisons and another 16 bytes - per pixel during fallback shading for triangle indices and weights. The auxiliary planes hold + outputs, each active band holds `size_of::>()` bytes per pixel for depth + comparisons (currently 56) and another 16 bytes per pixel during fallback shading for triangle + indices and weights. The auxiliary planes hold 20 bytes more per raster pixel, and `try_render_cpu_with_aux` also holds 36 bytes per output pixel - for the resolve. The byte check reserves the 24 band bytes for every raster pixel, for a total - of 84 bytes per raster pixel plus 36 bytes per resolved output pixel. This sum must fit + for the resolve. The byte check reserves the 72 band bytes for every raster pixel, for a total + of 136 bytes per raster pixel plus 36 bytes per resolved output pixel. This sum must fit `isize::MAX` bytes, or the call returns `TooLarge` before it allocates. `try_render_with_aux` returns `BadPartIdCount`, `ReservedPartId` or `BadTransform` for the part IDs and view above, and `BadPixel` when an auxiliary depth overflows `f32`; `try_resolve_aux` returns `BadDataLength` for @@ -206,8 +211,7 @@ Changes from those files: same order over their bounding boxes. EffectCraft searched every triangle of the pixel's band of 16 rows for each such pixel, which the work limit could not bound. The search takes only fragments inside the depth range, as the visibility pass does; EffectCraft also took a fragment - whose interpolated depth rounded past 1. A clipped corner whose clip-space z equals its w is - projected to a depth of exactly 1, also where `w * (1 / w)` rounds below 1. + whose interpolated depth rounded past 1. - A shadows-only material that does not receive shadows draws nothing. EffectCraft drew the shadows on it. - A triangle in the opaque range whose material is shadows-only and visible is an error. diff --git a/crates/raster3d/src/lib.rs b/crates/raster3d/src/lib.rs index f0f621e3ac..e68463000a 100644 --- a/crates/raster3d/src/lib.rs +++ b/crates/raster3d/src/lib.rs @@ -243,9 +243,10 @@ impl Limits { } /// Extra bytes reserved per raster pixel for auxiliary renders: depth (4), normal (12), part ID (4), -/// band depth comparisons (8), and fallback triangle indices and weights (16). +/// band depth comparisons (`size_of::>()`, currently 56), and +/// fallback triangle indices and weights (16), currently totaling 96 bytes. /// The band buffers are bounded by the full raster, including when bands run in parallel. -const AUX_BYTES_PER_PIXEL: u64 = 44; +const AUX_BYTES_PER_PIXEL: u64 = 20 + std::mem::size_of::>() as u64 + 16; /// Bytes a resolve with auxiliary outputs holds per output pixel: color (16), depth (4), /// normal (12) and part ID (4). @@ -253,19 +254,19 @@ const AUX_BYTES_PER_OUTPUT: u64 = 36; #[cfg(test)] mod tests { - use super::{Limits, MAX_ALLOC_BYTES, RenderError}; + use super::{AUX_BYTES_PER_PIXEL, BYTES_PER_PIXEL, Limits, MAX_ALLOC_BYTES, RenderError}; #[test] fn auxiliary_byte_check_counts_concurrent_band_buffers() { let limits = Limits { max_pixels: u64::MAX, ..Limits::default() }; #[cfg(target_pointer_width = "64")] - let (w, h) = (1 << 30, 120_000_000); + let (w, h) = (1 << 30, 80_000_000); #[cfg(target_pointer_width = "32")] - let (w, h) = (1 << 20, 30); + let (w, h) = (1 << 20, 20); let pixels = u64::from(w) * u64::from(h); assert!(limits.check(w, h).is_ok()); - assert!(pixels * (40 + 20) <= MAX_ALLOC_BYTES); - assert!(pixels * (40 + 20 + 8 + 16) > MAX_ALLOC_BYTES); + assert!(pixels * (40 + 20 + 8 + 16) <= MAX_ALLOC_BYTES); + assert!(pixels * (BYTES_PER_PIXEL + AUX_BYTES_PER_PIXEL) > MAX_ALLOC_BYTES); assert_eq!(limits.check_aux(w, h, None), Err(RenderError::TooLarge(w, h))); assert_eq!(limits.check_aux(w, h, Some(2)), Err(RenderError::TooLarge(w, h))); } diff --git a/crates/raster3d/src/raster.rs b/crates/raster3d/src/raster.rs index f951bd2b56..a6b15a684b 100644 --- a/crates/raster3d/src/raster.rs +++ b/crates/raster3d/src/raster.rs @@ -15,6 +15,12 @@ use crate::scene::{NO_PART, Scene, Vertex, validate, validate_aux, validate_pass use crate::shade::{Frag, shade}; use crate::{Limits, RenderError}; +#[cfg(test)] +std::thread_local! { + static DEPTH_TIE_KEY_CALLS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static DEPTH_TIE_EXPANSIONS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + /// Half-width of the clip guard band in units of clip w: a triangle reaching past /// `|x| > GUARD_BAND × w` or `|y| > GUARD_BAND × w` is clipped there before the perspective /// divide, so screen coordinates stay within about 512 viewports of the raster. A triangle @@ -38,15 +44,17 @@ pub struct Target { /// The surface of a pixel is the nearest opaque surface drawn there (after an alpha test or a /// single-sided back face hands the pixel to the next surface), or a transparent fragment that /// adds alpha above 0 and is nearer in camera depth than the surface before it. Equal `f32` -/// depths are compared in `f64` without the view translation. All three planes name the same surface. +/// depths are compared in `f64` with a rounding bound and an exact expansion fallback. Normalized +/// depths are compared by cross-multiplying their total original-vertex weights, without the view +/// translation. Equal depths keep the earlier surface. All three planes name the same surface. #[derive(Clone, Debug, Default, PartialEq)] pub struct AuxPlanes { /// Camera-space depth of the surface (the third row of [`Scene::view`]), ∞ where empty. For /// a transparent surface this differs from [`Target::depth`], which holds opaque surfaces only. pub depth: Vec, /// Unit normal of the surface in view space, `[0, 0, 0]` where empty: the vertex normal - /// interpolated in `f64`, with exact sums for cancellation (a vector of length 1e-20 or less is - /// read as `[0, 0, −1]`), reversed on a back face, + /// interpolated in `f64`, with exact expansion terms through the transform on cancellation + /// (a vector of length 1e-20 or less is read as `[0, 0, −1]`), reversed on a back face, /// turned by the inverse transpose of the upper-left 3 × 3 of [`Scene::view`] and normalized, /// so it stays perpendicular to the surface under a non-uniform scale or a shear. Normal /// textures are not applied. @@ -65,25 +73,77 @@ pub struct AuxTarget { /// One band's rows of the auxiliary planes. struct AuxRow<'a> { depth: &'a mut [f32], - precise_depth: Vec, + surface: Vec>, normal: &'a mut [[f32; 3]], part: &'a mut [u32], } +#[derive(Clone, Copy)] +pub(crate) struct AuxSurface { + tri: u32, + w: [[f32; 3]; 3], + l: [f32; 3], +} + +struct DepthTieKey { + terms: [(f64, f64); 27], + weights: [f64; 9], + numerator: f64, + total: f64, + magnitude: f64, + weight_magnitude: f64, +} + +impl DepthTieKey { + fn is_nearer_than(&self, other: &Self) -> bool { + let difference = self.numerator * other.total - other.numerator * self.total; + // Each numerator has 27 rounded products and additions; each total has 9 additions. + // Each cross-product path has at most 38 rounding steps. With u = EPSILON / 2, + // gamma(38) < 20 * EPSILON. The computed absolute sums have at most 38 steps too. + // 128 * EPSILON bounds both paths, the subtraction, and the absolute sums' rounding. + let bound = (self.magnitude * other.weight_magnitude + other.magnitude * self.weight_magnitude) * (128.0 * f64::EPSILON); + let positive_totals = + self.total > self.weight_magnitude * (16.0 * f64::EPSILON) && other.total > other.weight_magnitude * (16.0 * f64::EPSILON); + if positive_totals && difference.abs() > bound { + return difference < 0.0; + } + #[cfg(test)] + DEPTH_TIE_EXPANSIONS.with(|calls| calls.set(calls.get() + 1)); + let numerator = crate::scene::product_expansion(self.terms); + let other_numerator = crate::scene::product_expansion(other.terms); + let total = crate::scene::product_expansion(self.weights.map(|w| (w, 1.0))); + let other_total = crate::scene::product_expansion(other.weights.map(|w| (w, 1.0))); + let left = numerator.terms().iter().flat_map(|&x| other_total.terms().iter().map(move |&y| (x, y))); + let right = other_numerator.terms().iter().flat_map(|&x| total.terms().iter().map(move |&y| (-x, y))); + let sign = crate::scene::product_expansion_sign(left.chain(right)); + let total_sign = total.terms().last().map_or(0.0, |x| x.signum()); + let other_total_sign = other_total.terms().last().map_or(0.0, |x| x.signum()); + sign * total_sign * other_total_sign < 0.0 + } +} + impl AuxRow<'_> { /// Make (camera depth `z`, normal `n` and `part`) the surface of pixel `i`. - fn set(&mut self, i: usize, z: f32, precise_z: f64, n: [f32; 3], part: u32) { + fn set(&mut self, i: usize, z: f32, surface: (&STri, [f32; 3]), n: [f32; 3], part: u32) { self.depth[i] = z; - self.precise_depth[i] = precise_z; + self.surface[i] = Some(AuxSurface { tri: surface.0.tri, w: surface.0.w, l: surface.1 }); self.normal[i] = n; self.part[i] = part; } /// Make the surface of pixel `i` the given one when its camera depth `z` is nearer than the - /// pixel's, using `precise_z` to break `f32` ties. A NaN depth always replaces it and is never replaced. - fn offer(&mut self, i: usize, z: f32, precise_z: f64, n: impl FnOnce() -> [f32; 3], part: u32) { - if !self.depth[i].is_nan() && (z.is_nan() || z < self.depth[i] || (z == self.depth[i] && precise_z < self.precise_depth[i])) { - self.set(i, z, precise_z, n(), part); + /// pixel's. Comparison keys are computed only for `f32` ties. A NaN depth always replaces it and is never replaced. + fn offer(&mut self, i: usize, z: f32, surface: (&STri, [f32; 3]), band: &Band<'_>, n: impl FnOnce() -> [f32; 3], part: u32) { + if !self.depth[i].is_nan() + && (z.is_nan() + || z < self.depth[i] + || (z == self.depth[i] + && self.surface[i].is_some_and(|s| { + band.fragment_depth_tie_key(surface.0.tri, &surface.0.w, surface.1) + .is_nearer_than(&band.fragment_depth_tie_key(s.tri, &s.w, s.l)) + }))) + { + self.set(i, z, surface, n(), part); } } } @@ -258,9 +318,7 @@ fn project(s: &Scene, clip: &[[f32; 4]], t: usize) -> Option<(Vec, .map(|(c, wt)| { let iw = 1.0 / c[3]; let (nx, ny) = (c[0] * iw, c[1] * iw); - // A corner on the near plane keeps a depth of 1 even when `w * (1 / w)` rounds below 1. - let z = if c[2] == c[3] { 1.0 } else { ndc_z(c[2] * iw) }; - ([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], z, f64::from(iw), *wt) + ([(nx as f64 + 1.0) * 0.5 * w, (1.0 - ny as f64) * 0.5 * h], ndc_z(c[2] * iw), f64::from(iw), *wt) }) .collect(); let ok = |s: &ScreenCorner| s.0.iter().all(|v| v.is_finite()) && s.1.is_finite() && s.2.is_finite(); @@ -517,11 +575,33 @@ impl Band<'_> { } /// The untranslated camera-depth dot product in `f64` for auxiliary surface comparisons. + #[cfg(test)] fn depth_tie_key(&self, p: [f32; 3]) -> f64 { let row = self.s.view[2].map(f64::from); row[0] * f64::from(p[0]) + row[1] * f64::from(p[1]) + row[2] * f64::from(p[2]) } + /// The auxiliary comparison numerator and total original-vertex weight, without the view translation. + fn fragment_depth_tie_key(&self, tri: u32, w: &[[f32; 3]; 3], l: [f32; 3]) -> DepthTieKey { + #[cfg(test)] + DEPTH_TIE_KEY_CALLS.with(|calls| calls.set(calls.get() + 1)); + let base = tri as usize * 3; + let positions = [0, 1, 2].map(|k| self.s.vertices[self.s.indices[base + k] as usize].pos); + // Each pair of f32 factors has an exact f64 product. + let weights: [f64; 9] = std::array::from_fn(|i| f64::from(l[i / 3]) * f64::from(w[i / 3][i % 3])); + let terms: [(f64, f64); 27] = std::array::from_fn(|i| { + let axis = i / 9; + (f64::from(self.s.view[2][axis]) * f64::from(positions[i % 3][axis]), weights[i % 9]) + }); + let (numerator, magnitude) = terms.iter().fold((0.0, 0.0), |(sum, magnitude), &(x, y)| { + let product = x * y; + (sum + product, magnitude + product.abs()) + }); + let total = weights.iter().sum(); + let weight_magnitude = weights.iter().map(|w| w.abs()).sum(); + DepthTieKey { terms, weights, numerator, total, magnitude, weight_magnitude } + } + /// The unit view-space normal for [`AuxPlanes::normal`] of screen triangle `t` at /// screen-corner weights `l`. The vertex normals are interpolated, normalized and turned in /// `f64`, so finite normals near the top of the `f32` range do not overflow. @@ -543,13 +623,18 @@ impl Band<'_> { } let interpolation: [[(f64, f64); 3]; 3] = std::array::from_fn(|i| std::array::from_fn(|k| (f64::from(s.vertices[s.indices[base + k] as usize].normal[i]), f64::from(wv[k])))); - let sum = interpolation.map(crate::scene::sum_of_products); - // The interpolated normal is turned as it is and normalized after, so its components keep - // their exact ratios through the transform. - let mut n = if unit(sum, 1e-20).is_some() { sum } else { [0.0, 0.0, -1.0] }; + let expansion = interpolation.map(crate::scene::product_expansion); + let sum = expansion.map(|e| e.sum()); + let mut expansion = if unit(sum, 1e-20).is_some() { + expansion + } else { + [0.0, 0.0, -1.0].map(|x| crate::scene::product_expansion([(x, 1.0), (0.0, 0.0), (0.0, 0.0)])) + }; if !t.front { - n = n.map(|x| -x); + expansion = expansion.map(|e| e.negated()); } + let n = expansion.map(|e| e.sum()); + let magnitude = expansion.map(|e| e.terms().iter().fold(0.0, |sum, x| sum + x.abs())); // Transform the normal by the cofactor matrix and the determinant's sign. // A row takes an exact expansion when its rounding bound is not negligible next to the // largest row, which sets the normalized result's scale. @@ -561,16 +646,22 @@ impl Band<'_> { [(p[1] * q[2], n[0]), (-(p[2] * q[1]), n[0]), (p[2] * q[0], n[1]), (-(p[0] * q[2]), n[1]), (p[0] * q[1], n[2]), (-(p[1] * q[0]), n[2])] }); let fast: [(f64, f64); 3] = terms.map(|t| { - let (dot, magnitude) = t.iter().fold((0.0f64, 0.0f64), |(dot, magnitude), &(x, y)| { + let (dot, magnitude) = t.iter().enumerate().fold((0.0f64, 0.0f64), |(dot, total), (k, &(x, y))| { let product = x * y; - (dot + product, magnitude + product.abs()) + (dot + product, total + x.abs() * magnitude[k / 2]) }); - (dot, magnitude * (8.0 * f64::EPSILON)) + (dot, magnitude * (16.0 * f64::EPSILON)) }); let big = fast.iter().fold(0.0f64, |m, &(dot, _)| m.max(dot.abs())); let r: [f64; 3] = std::array::from_fn(|i| { let (dot, bound) = fast[i]; - let dot = if bound <= big * NORMAL_ERROR { dot } else { crate::scene::sum_of_products(terms[i]) }; + let dot = if bound <= big * NORMAL_ERROR { + dot + } else { + let exact: [(f64, f64); 36] = + std::array::from_fn(|k| (terms[i][k / 6].0, expansion[k / 12].terms().get(k % 6).copied().unwrap_or(0.0))); + crate::scene::sum_of_products(exact) + }; self.view_sign * dot }); unit(r, 0.0).map_or([f32::NAN; 3], |r| r.map(|x| x as f32)) @@ -613,7 +704,7 @@ impl Band<'_> { vis: &mut Visibility, crow: &mut [[f32; 4]], drow: &mut [f32], - aux: &mut Option, + aux: &mut Option>, ) -> Result<(), RenderError> { let s = self.s; let mut discarded = vec![false; self.rows * self.w]; @@ -631,7 +722,7 @@ impl Band<'_> { if let Some(a) = aux && c[3] > 0.0 { - a.set(i, drow[i], self.depth_tie_key(f.pos), self.view_normal(t, l), self.part(t)); + a.set(i, drow[i], (t, l), self.view_normal(t, l), self.part(t)); } } None => discarded[i] = true, @@ -656,7 +747,7 @@ impl Band<'_> { { let (ti, l) = surface[i]; let t = &opaque.tris[ti as usize]; - a.set(i, f.camera_depth, self.depth_tie_key(frag(s, t, l).pos), self.view_normal(t, l), self.part(t)); + a.set(i, f.camera_depth, (t, l), self.view_normal(t, l), self.part(t)); } } None => vis[i].1 = EMPTY, @@ -710,7 +801,7 @@ impl Band<'_> { /// Transparent fragments in order, blended over the opaque result where they are nearer. /// When `aux` is given, a fragment with alpha above 0 is offered as the pixel's auxiliary /// surface. - fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]], aux: &mut Option) { + fn blend_transparent(&self, trans: Pass, vis: &Visibility, crow: &mut [[f32; 4]], aux: &mut Option>) { let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows); for &ti in trans.bins { let t = &trans.tris[ti as usize]; @@ -729,7 +820,7 @@ impl Band<'_> { if let Some(a) = aux && c[3] > 0.0 { - a.offer(i, self.cam_z(f.pos), self.depth_tie_key(f.pos), || self.view_normal(t, l), self.part(t)); + a.offer(i, self.cam_z(f.pos), (t, l), self, || self.view_normal(t, l), self.part(t)); } } } @@ -772,8 +863,8 @@ fn raster(s: &Scene, opaque: &[STri], trans: &[STri], pixels: usize, aux: bool, .zip(planes.part_id.par_chunks_mut(band_rows)) .enumerate() .try_for_each(|(band, ((((crow, drow), depth), normal), part))| { - let precise_depth = vec![f64::INFINITY; depth.len()]; - render(band, crow, drow, Some(AuxRow { depth, precise_depth, normal, part })) + let surface = vec![None; depth.len()]; + render(band, crow, drow, Some(AuxRow { depth, surface, normal, part })) })?; } else { color @@ -830,9 +921,10 @@ pub fn try_render(s: &Scene, limits: &Limits) -> Result { /// none may be [`NO_PART`], and, when the scene has a triangle, the upper-left 3 × 3 of /// [`Scene::view`] must be invertible. The /// output holds 20 more bytes per raster pixel than [`try_render`]. Each active band also holds -/// 8 bytes per pixel for depth comparisons and, during fallback shading, 16 bytes per pixel for -/// triangle indices and weights. The byte check reserves all 24 band bytes per raster pixel, -/// for a total of 84 bytes per raster pixel that must fit `isize::MAX` bytes. +/// `size_of::>()` bytes per pixel for depth comparisons (currently 56) and, +/// during fallback shading, 16 bytes per pixel for triangle indices and weights. The byte check +/// reserves all 72 band bytes per raster pixel, for a total of 136 bytes per raster pixel that +/// must fit `isize::MAX` bytes. pub fn try_render_with_aux(s: &Scene, limits: &Limits) -> Result { let (pixels, opaque, trans, work) = prepare(s, limits, true)?; let (target, aux) = raster(s, &opaque, &trans, pixels, true, work, limits.max_work)?; @@ -848,37 +940,52 @@ mod tests { use super::{AtomicU64, AuxRow, Band, FallbackFragment, Pass, STri, cover, f32_crossing, fan, project}; use crate::scene::{Scene, Vertex}; - #[test] - fn equal_large_clip_depth_and_w_project_to_one() { - let s = Scene { width: 1, height: 1, indices: vec![0, 1, 2], ..Scene::default() }; - let rounded_below_one = (1..=100).map(|w| w as f32).find(|&w| w * (1.0 / w) < 1.0); - assert!(rounded_below_one.is_some()); - for scale in [1.000005e38, rounded_below_one.unwrap_or_default()] { - let clip = [[-0.5 * scale, -0.5 * scale, scale, scale], [0.5 * scale, -0.5 * scale, scale, scale], [0.0, 0.5 * scale, scale, scale]]; - let (scr, _) = project(&s, &clip, 0).unwrap_or_default(); - assert_eq!(scr.len(), 3); - for (_, z, _, _) in scr { - assert_eq!(z.to_bits(), 1.0f32.to_bits()); - } + fn point_triangle(tri: u32) -> STri { + STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri, + front: true, + bbox: [0; 4], } } #[test] - fn a_covered_fragment_on_the_near_plane_keeps_a_depth_of_one() { - // The rounded f32 weights here sum to just above 1, which put the depth past the range. - let d = 17.0 * 2f64.powi(-29); - let t = STri { - p: [[0.375, 0.5 - d], [0.875, 0.5 - d], [0.655, 1.0]], - z: [1.0; 3], - inv_w: [1.0; 3], - wide: false, - w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], - tri: 0, - front: true, - bbox: [0, 0, 1, 1], - }; - let (z, _) = cover(&t, 0.5, 0.5).unwrap_or((f32::NAN, [0.0; 3])); - assert_eq!(z, 1.0); + fn auxiliary_exact_depth_keys_are_computed_only_for_f32_ties() { + let vertices = [3.0, 2.0, 1.0].into_iter().flat_map(|z| [Vertex { pos: [0.0, 0.0, z], ..Vertex::default() }; 3]); + let mut s = Scene { vertices: vertices.collect(), indices: (0..9).collect(), ..Scene::default() }; + s.view[2] = [0.0, 0.0, 1.0, 0.0]; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let triangles = [0, 1, 2].map(point_triangle); + let surface = |i: usize| (&triangles[i], [1.0, 0.0, 0.0]); + let mut depth = [f32::INFINITY]; + let mut normal = [[0.0; 3]]; + let mut part = [super::NO_PART]; + let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part }; + let n = [0.0, 0.0, 1.0]; + super::DEPTH_TIE_KEY_CALLS.with(|calls| calls.set(0)); + super::DEPTH_TIE_EXPANSIONS.with(|calls| calls.set(0)); + row.offer(0, 3.0, surface(0), &b, || n, 10); + row.offer(0, 2.0, surface(1), &b, || n, 20); + row.offer(0, 3.0, surface(0), &b, || panic!("farther surface replaced the nearer one"), 10); + assert_eq!(row.part[0], 20); + row.set(0, 3.0, surface(0), n, 10); + row.offer(0, 2.0, surface(1), &b, || n, 20); + assert_eq!(row.part[0], 20); + super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 0, "unequal depths computed an exact key")); + row.offer(0, 2.0, surface(2), &b, || n, 30); + assert_eq!(row.part[0], 30); + super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 2, "a tie must compare both exact keys")); + row.offer(0, 2.0, surface(1), &b, || panic!("the previous surface was compared after replacement"), 20); + assert_eq!(row.part[0], 30); + super::DEPTH_TIE_KEY_CALLS.with(|calls| assert_eq!(calls.get(), 4)); + super::DEPTH_TIE_EXPANSIONS.with(|calls| assert_eq!(calls.get(), 0, "separated f64 estimates computed exact expansions")); + row.offer(0, 2.0, surface(2), &b, || panic!("equal depth replaced the surface"), 40); + super::DEPTH_TIE_EXPANSIONS.with(|calls| assert_eq!(calls.get(), 1, "equal estimates must use exact expansions")); } #[test] @@ -976,6 +1083,32 @@ mod tests { assert!((n[0] * n[0] + n[1] * n[1] - 1.0).abs() < 1e-6); } + #[test] + fn a_view_transform_preserves_interpolation_residuals_through_cancellation() { + let e = 2f32.powi(-40); + let view = [[1.0, 1.0, 0.0, 0.0], [1.0, 1.0, e, 0.0], [0.0, e, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let vertices = [[1.0, 1.0, 0.0], [0.0, 2f32.powi(-58), 0.0], [0.0; 3]].map(|normal| Vertex { normal, ..Vertex::default() }); + let s = Scene { vertices: vertices.to_vec(), indices: vec![0, 1, 2], view, ..Scene::default() }; + let t = STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0; 4], + }; + let spent = AtomicU64::new(0); + let view_sign = crate::scene::det_sign3(&s.view).unwrap(); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign }; + let n = b.view_normal(&t, [0.5, 0.25, 0.25]); + let expected = [std::f32::consts::FRAC_1_SQRT_2, -std::f32::consts::FRAC_1_SQRT_2, 0.0]; + assert!(n.iter().zip(expected).all(|(x, y)| (x - y).abs() < 1e-5), "{n:?}"); + let back = b.view_normal(&STri { front: false, ..t }, [0.5, 0.25, 0.25]); + assert_eq!(back, n.map(|x| -x)); + } + #[test] fn a_non_auxiliary_fallback_keeps_only_the_baseline_fragment_buffer() { type BaselineFragment = (f32, [f32; 4], f32); @@ -993,54 +1126,139 @@ mod tests { assert_eq!(auxiliary.aux.unwrap().len(), 2); } + #[test] + fn auxiliary_depth_ties_preserve_coordinates_until_after_interpolation() { + let large = 2f32.powi(60); + let vertices = [1.0, 2.0].into_iter().flat_map(|z| [large, -large, 0.0].map(|x| Vertex { pos: [x, 0.0, z], ..Vertex::default() })); + let mut s = Scene { vertices: vertices.collect(), indices: vec![0, 1, 2, 3, 4, 5], ..Scene::default() }; + s.view[2] = [1.0, 0.0, 1.0, 0.0]; + let near = STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0; 4], + }; + let far = STri { tri: 1, ..near }; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let l = [0.5, 0.5, 0.0]; + assert!(b.fragment_depth_tie_key(near.tri, &near.w, l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, l))); + } + + #[test] + fn auxiliary_depth_ties_normalize_original_vertex_weights() { + let near_depth = 5.0f32; + let far_depth = f32::from_bits(near_depth.to_bits() + 1); + let vertices = [near_depth, far_depth].into_iter().flat_map(|z| [Vertex { pos: [0.0, 0.0, z], ..Vertex::default() }; 3]); + let mut s = Scene { vertices: vertices.collect(), indices: vec![0, 1, 2, 3, 4, 5], ..Scene::default() }; + s.view[2] = [0.0, 0.0, 1.0, 0.0]; + let near = STri { + p: [[0.0; 2]; 3], + z: [0.0; 3], + inv_w: [1.0; 3], + wide: false, + w: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], + tri: 0, + front: true, + bbox: [0; 4], + }; + let far = STri { tri: 1, ..near }; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let near_l = [0.5 + 2f32.powi(-24), 0.25 + 2f32.powi(-25), 0.25]; + let far_l = [0.5 - 2f32.powi(-25), 0.25 - 2f32.powi(-26), 0.25]; + let unnormalized = |z, l: [f32; 3]| crate::scene::sum_of_products(l.map(|w| (f64::from(z), f64::from(w)))); + assert!(unnormalized(near_depth, near_l) > unnormalized(far_depth, far_l)); + assert!(b.fragment_depth_tie_key(near.tri, &near.w, near_l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, far_l))); + + let near = STri { w: [near_l; 3], ..near }; + let far = STri { w: [far_l; 3], ..far }; + let l = [0.5, 0.25, 0.25]; + assert!(b.fragment_depth_tie_key(near.tri, &near.w, l).is_nearer_than(&b.fragment_depth_tie_key(far.tri, &far.w, l))); + } + + #[test] + fn equal_normalized_auxiliary_depths_keep_the_earlier_surface() { + let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]; + let s = + Scene { vertices: vec![Vertex { pos: [0.0, 0.0, 0.1], ..Vertex::default() }; 6], indices: (0..6).collect(), view, ..Scene::default() }; + let spent = AtomicU64::new(0); + let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; + let triangles = [0, 1].map(point_triangle); + let weights = [[0.47058824, 0.5, 0.029411765], [0.7352941, 0.25, 0.014705882]]; + let rounded = + |l: [f32; 3]| crate::scene::sum_of_products(l.map(|w| (f64::from(0.1f32), f64::from(w)))) / l.into_iter().map(f64::from).sum::(); + assert_ne!(rounded(weights[0]), rounded(weights[1]), "the fixture must distinguish rounded normalized depths"); + for [first, second] in [weights, [weights[1], weights[0]]] { + let mut depth = [f32::INFINITY]; + let mut normal = [[0.0; 3]]; + let mut part = [super::NO_PART]; + let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part }; + let n = [0.0, 0.0, 1.0]; + row.offer(0, 0.1, (&triangles[0], first), &b, || n, 10); + row.offer(0, 0.1, (&triangles[1], second), &b, || n, 20); + assert_eq!(row.part[0], 10, "equal normalized depths replaced the earlier surface at {first:?}, {second:?}"); + } + } + #[test] fn auxiliary_depth_ties_keep_the_nearer_surface_in_f64() { - let mut s = Scene::default(); + let (far, near) = ([2f32.powi(-25), 0.0, 1.0], [0.0, 0.0, 1.0]); + let vertices = [far, near].into_iter().flat_map(|pos| [Vertex { pos, ..Vertex::default() }; 3]).collect(); + let mut s = Scene { vertices, indices: (0..6).collect(), ..Scene::default() }; s.view[2] = [1.0, 0.0, 1.0, 0.0]; let spent = AtomicU64::new(0); let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; - let (far, near) = ([2f32.powi(-25), 0.0, 1.0], [0.0, 0.0, 1.0]); assert_eq!(b.cam_z(far), b.cam_z(near)); assert!(b.depth_tie_key(near) < b.depth_tie_key(far)); let mut depth = [f32::INFINITY]; let mut normal = [[0.0; 3]]; let mut part = [super::NO_PART]; - let mut row = AuxRow { depth: &mut depth, precise_depth: vec![f64::INFINITY], normal: &mut normal, part: &mut part }; + let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part }; + let (far_triangle, near_triangle) = (point_triangle(0), point_triangle(1)); + let (far_surface, near_surface) = ((&far_triangle, [1.0, 0.0, 0.0]), (&near_triangle, [1.0, 0.0, 0.0])); let n = [1.0, 0.0, 0.0]; - row.offer(0, b.cam_z(far), b.depth_tie_key(far), || n, 10); - row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + row.offer(0, b.cam_z(far), far_surface, &b, || n, 10); + row.offer(0, b.cam_z(near), near_surface, &b, || n, 20); assert_eq!(row.part[0], 20); - row.offer(0, b.cam_z(far), b.depth_tie_key(far), || panic!("farther surface replaced the nearer one"), 10); + row.offer(0, b.cam_z(far), far_surface, &b, || panic!("farther surface replaced the nearer one"), 10); assert_eq!(row.part[0], 20); - row.set(0, b.cam_z(far), b.depth_tie_key(far), n, 30); - row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + row.set(0, b.cam_z(far), far_surface, n, 30); + row.offer(0, b.cam_z(near), near_surface, &b, || n, 20); assert_eq!(row.part[0], 20); - row.offer(0, f32::NAN, f64::NAN, || n, 40); - row.offer(0, b.cam_z(near), b.depth_tie_key(near), || panic!("NaN surface was replaced"), 20); + row.offer(0, f32::NAN, far_surface, &b, || n, 40); + row.offer(0, b.cam_z(near), near_surface, &b, || panic!("NaN surface was replaced"), 20); assert_eq!(row.part[0], 40); assert!(row.depth[0].is_nan()); } #[test] fn auxiliary_depth_ties_ignore_large_camera_translations() { - let mut s = Scene::default(); + let (near, far) = ([0.0, 0.0, 0.25], [0.0, 0.0, 0.5]); + let vertices = [far, near].into_iter().flat_map(|pos| [Vertex { pos, ..Vertex::default() }; 3]).collect(); + let mut s = Scene { vertices, indices: (0..6).collect(), ..Scene::default() }; s.view[2] = [0.0, 0.0, 1.0, 2f32.powi(60)]; let spent = AtomicU64::new(0); let b = Band { s: &s, y0: 0, rows: 1, w: 1, spent: &spent, limit: u64::MAX, view_sign: 1.0 }; - let (near, far) = ([0.0, 0.0, 0.25], [0.0, 0.0, 0.5]); assert_eq!(b.cam_z(near), b.cam_z(far)); let mut depth = [f32::INFINITY]; let mut normal = [[0.0; 3]]; let mut part = [super::NO_PART]; - let mut row = AuxRow { depth: &mut depth, precise_depth: vec![f64::INFINITY], normal: &mut normal, part: &mut part }; + let mut row = AuxRow { depth: &mut depth, surface: vec![None], normal: &mut normal, part: &mut part }; + let (far_triangle, near_triangle) = (point_triangle(0), point_triangle(1)); + let (far_surface, near_surface) = ((&far_triangle, [1.0, 0.0, 0.0]), (&near_triangle, [1.0, 0.0, 0.0])); let n = [1.0, 0.0, 0.0]; - row.set(0, b.cam_z(far), b.depth_tie_key(far), n, 10); - row.offer(0, b.cam_z(near), b.depth_tie_key(near), || n, 20); + row.set(0, b.cam_z(far), far_surface, n, 10); + row.offer(0, b.cam_z(near), near_surface, &b, || n, 20); assert_eq!(row.part[0], 20); assert_eq!(row.depth[0], b.cam_z(near)); - row.offer(0, b.cam_z(far), b.depth_tie_key(far), || panic!("farther surface replaced the nearer one"), 10); + row.offer(0, b.cam_z(far), far_surface, &b, || panic!("farther surface replaced the nearer one"), 10); assert_eq!(row.part[0], 20); - row.offer(0, b.cam_z(near), b.depth_tie_key(near), || panic!("equal depth replaced the surface"), 30); + row.offer(0, b.cam_z(near), near_surface, &b, || panic!("equal depth replaced the surface"), 30); assert_eq!(row.part[0], 20); } diff --git a/crates/raster3d/src/scene.rs b/crates/raster3d/src/scene.rs index ebceeb7005..e91517e959 100644 --- a/crates/raster3d/src/scene.rs +++ b/crates/raster3d/src/scene.rs @@ -247,29 +247,97 @@ pub(crate) fn validate_aux(s: &Scene) -> Result<(), RenderError> { Ok(()) } -/// Sums at most six products using an exact expansion, barring overflow and underflow. +/// Sums products using an exact expansion, barring overflow and underflow. pub(crate) fn sum_of_products(terms: [(f64, f64); N]) -> f64 { - const { assert!(N <= 6) }; + product_expansion(terms).sum() +} + +#[derive(Clone, Copy)] +pub(crate) struct ProductExpansion { + storage: [[f64; 2]; N], + len: usize, +} + +impl ProductExpansion { + pub(crate) fn terms(&self) -> &[f64] { + &self.storage.as_flattened()[..self.len] + } + + pub(crate) fn sum(&self) -> f64 { + self.terms().iter().fold(0.0, |sum, &x| sum + x) + } + + pub(crate) fn negated(mut self) -> Self { + for x in &mut self.storage.as_flattened_mut()[..self.len] { + *x = -*x; + } + self + } +} + +/// The exact expansion terms of a sum of products, barring overflow and underflow. +pub(crate) fn product_expansion(terms: [(f64, f64); N]) -> ProductExpansion { let mut storage = [[0.0f64; 2]; N]; let e = storage.as_flattened_mut(); let mut len = 0; for (x, y) in terms { + if x == 0.0 || y == 0.0 { + continue; + } let hi = x * y; for part in [hi, x.mul_add(y, -hi)] { - // Grow the expansion by `part` with exact two-sums, keeping every rounding error. - let mut q = part; - for c in &mut e[..len] { - let sum = q + *c; - let bv = sum - q; - let err = (q - (sum - bv)) + (*c - bv); - (*c, q) = (err, sum); + if part == 0.0 { + continue; + } + let (used, q) = grow_expansion(&mut e[..len], part); + len = used; + if q != 0.0 { + e[len] = q; + len += 1; } - e[len] = q; - len += 1; } } // The components do not overlap and grow in magnitude. - e[..len].iter().sum() + ProductExpansion { storage, len } +} + +/// Adds a nonzero component with exact two-sums, returning the nonzero prefix and final component. +fn grow_expansion(e: &mut [f64], mut q: f64) -> (usize, f64) { + let mut len = 0; + for i in 0..e.len() { + let c = e[i]; + let sum = q + c; + let bv = sum - q; + let err = (q - (sum - bv)) + (c - bv); + if err != 0.0 { + e[len] = err; + len += 1; + } + q = sum; + } + (len, q) +} + +/// The sign of an exact sum of products, barring overflow and underflow. Zero terms are omitted. +pub(crate) fn product_expansion_sign(terms: impl IntoIterator) -> f64 { + let mut e = Vec::new(); + for (x, y) in terms { + if x == 0.0 || y == 0.0 { + continue; + } + let hi = x * y; + for part in [hi, x.mul_add(y, -hi)] { + if part == 0.0 { + continue; + } + let (len, q) = grow_expansion(&mut e, part); + e.truncate(len); + if q != 0.0 { + e.push(q); + } + } + } + e.last().map_or(0.0, |x| x.signum()) } /// The sign of the determinant of the upper-left 3 × 3 of `m` (1 or −1), or `None` when the diff --git a/crates/raster3d/src/shadow.rs b/crates/raster3d/src/shadow.rs index 9ba0aa415e..b18049f663 100644 --- a/crates/raster3d/src/shadow.rs +++ b/crates/raster3d/src/shadow.rs @@ -103,16 +103,12 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec { if (da >= 0.0) != (db >= 0.0) { let (from_b, k) = f32_crossing(da, db); let (p, q) = if from_b { (b, a) } else { (a, b) }; - // `y - x` can overflow f32 between far-apart finite corners; such a lerp is taken in - // f64, with the fraction also taken in f64. - let (dp, dq) = if from_b { (f64::from(db), f64::from(da)) } else { (f64::from(da), f64::from(db)) }; - let k64 = dp / (dp - dq); let lerp = |x: f32, y: f32| { - let fast = x + (y - x) * k; - if fast.is_finite() || !(x.is_finite() && y.is_finite()) { - fast + let d = y - x; + if d.is_finite() || !x.is_finite() || !y.is_finite() { + x + d * k } else { - (f64::from(x) + (f64::from(y) - f64::from(x)) * k64) as f32 + (f64::from(x) + (f64::from(y) - f64::from(x)) * f64::from(k)) as f32 } }; // The crossing lies on the near plane; its depth is set to it, since the lerp of @@ -217,9 +213,6 @@ fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option< let n = m.size as usize; let (a, b, cc) = (tri[0].0, tri[1].0, tri[2].0); let Some((area, [x0, x1, y0, y1])) = texel_bounds(m, &tri) else { return }; - if x0 >= x1 || y0 >= y1 { - return; - } let wide_depth = !m.ortho && tri.iter().any(|c| c.1.is_subnormal()); for y in y0..y1 { for x in x0..x1 { @@ -242,11 +235,11 @@ fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option< if z >= *px { continue; } - if let Some(t) = alpha { - let uv = [0, 1].map(|i| caster_uv(&tri, l, z, i, m.ortho)); - if t.discards(sample(t.tex, &s.texels, uv[0], uv[1])[3] * t.factor) { - continue; - } + let uv = [0, 1].map(|i| caster_uv(&tri, l, z, i, m.ortho)); + if let Some(t) = alpha + && t.discards(sample(t.tex, &s.texels, uv[0], uv[1])[3] * t.factor) + { + continue; } *px = z; } @@ -666,20 +659,4 @@ mod tests { assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0); } } - - #[test] - fn a_near_plane_crossing_whose_difference_overflows_f32_is_interpolated_in_f64() { - // 3e38 − (−3e38) overflows f32; the edge crosses the near plane near x = 0. - let v = |pos: [f32; 3]| Vertex { pos, ..Vertex::default() }; - let s = Scene { vertices: vec![v([-3e38, 0.0, -1.0]), v([3e38, 0.0, 1.0]), v([0.0, 0.1, 1.0])], ..Scene::default() }; - let view = [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]; - let m = ShadowMap { view, focal: 1.0, ortho: false, size: 8, offset: 0, bias: 0.0, radius: 0.0 }; - let poly = light_poly(&s, &m, [0, 1, 2]); - assert!(!poly.is_empty()); - for (p, uv) in &poly { - assert!(p.iter().chain(uv.iter()).all(|c| c.is_finite()), "{poly:?}"); - } - // The near plane at 0.001 lies 1.001 / 2 of the way along the edge, at x = 3e35. - assert!(poly.iter().any(|(p, _)| (p[0] - 3e35).abs() < 1e31 && p[2] == 0.001), "{poly:?}"); - } } diff --git a/crates/raster3d/tests/it/aux_outputs.rs b/crates/raster3d/tests/it/aux_outputs.rs index e5825f8be6..811cf043fc 100644 --- a/crates/raster3d/tests/it/aux_outputs.rs +++ b/crates/raster3d/tests/it/aux_outputs.rs @@ -327,6 +327,19 @@ fn a_transparent_fragment_that_adds_alpha_is_the_surface() { assert_eq!((a.aux.part_id[1], a.aux.part_id[6]), (3, 9)); } +#[test] +fn transparent_depth_ties_use_original_positions_before_f32_interpolation() { + let (near, far) = (5.0f32, f32::from_bits(5.0f32.to_bits() + 1)); + for (first, second, ids) in [(far, near, vec![10, 10, 20, 20]), (near, far, vec![20, 20, 10, 10])] { + let mut s = quad_scene(3, 3, &[([0.0, 0.0, 3.0, 3.0], first, [1.0, 0.0, 0.0, 0.5]), ([0.0, 0.0, 3.0, 3.0], second, [0.0, 0.0, 1.0, 0.5])]); + s.part_ids = ids; + let a = try_render_with_aux(&s, &Limits::default()).unwrap(); + let pixel = 3; + assert!(a.target.color[pixel][0] > 0.0 && a.target.color[pixel][2] > 0.0); + assert_eq!(a.aux.part_id[pixel], 20); + } +} + #[test] fn of_several_transparent_layers_the_nearest_is_the_surface() { // Drawn back to front, and also in the wrong order: the nearer layer is the surface either way. @@ -474,12 +487,12 @@ fn a_view_that_cannot_turn_normals_is_rejected() { #[test] fn the_byte_check_counts_the_auxiliary_planes() { - // The base target's 40 bytes per pixel fit `isize::MAX`, and the auxiliary render's 84 do not. + // The base target's 40 bytes per pixel fit `isize::MAX`, and the auxiliary render's 136 do not. let l = limits(|l| l.max_pixels = u64::MAX); #[cfg(target_pointer_width = "64")] - let (w, h, resolve_h) = (1 << 30, 150_000_000, 80_000_000); + let (w, h, resolve_h) = (1 << 30, 150_000_000, 60_000_000); #[cfg(target_pointer_width = "32")] - let (w, h, resolve_h) = (1 << 20, 40, 20); + let (w, h, resolve_h) = (1 << 20, 40, 12); assert!(l.check(w, h).is_ok()); let s = Scene { width: w, height: h, ..Scene::default() }; assert_eq!(try_render_with_aux(&s, &l), Err(RenderError::TooLarge(w, h)));