raster3d: validate opaque-range materials and falloff modes, widen shadow-map depths

- try_render returns BadMaterial for a visible transparent material in
  the opaque range (ShadowsOnlyOpaque stays for shadows-only ones), and
  BadLight for a falloff mode outside 0 to 2.
- Perspective shadow maps keep inverse-depth interpolation in f64 for
  subnormal reciprocals, so a caster at extreme depth stays in the map.
- Clipped caster UVs whose endpoint difference overflows are
  interpolated in f64.
- The fallback pass names its fragment type instead of allowing
  clippy::type_complexity.
This commit is contained in:
dotCooCoo committed 2026-11-29 08:18:23 -08:00
1 parent 3db3b68646
commit b37bb4aa6d
6 files changed
+143 -26

No files matched your search

+4 -2
View File
@@ -30,6 +30,8 @@ Building a scene from an app's document (layers, cameras, models, text) stays in
Each is shaded per fragment, depth-tested against the opaque surfaces and blended over them. A
triangle whose material is shadows-only belongs in the transparent range; `try_render` returns an
error for one in the opaque range unless its material's `visible` is false.
Other visible materials for which `Material::transparent()` is true also belong in the
transparent range; `try_render` returns `BadMaterial` for one in the opaque range.
- **Facing.** A triangle whose screen-space winding is negative with y down
(counterclockwise on the screen) faces the camera. A material with `double_sided` false does not
draw back faces; a double-sided material shades a back face with its normal reversed.
@@ -104,10 +106,10 @@ Building a scene from an app's document (layers, cameras, models, text) stays in
strength, a shadow darkness or an environment
light's key outside 0 to 1, a negative shadow diffusion or shadow-map radius, a parallel or spot light direction or an environment light direction
(other than zero) whose length differs from 1 by more than 0.001, a spot light whose inner cone
cosine is below its outer one, a light kind
cosine is below its outer one, a light kind or falloff mode
or alpha mode other than 0 to 2, or a clip-space position past `f32`. `try_render` also returns
`ShadowsOnlyOpaque` for a triangle in the opaque range whose material is shadows-only and
visible, and
visible, `BadMaterial` for any other visible transparent material in the opaque range, and
`BadPixel` when a rendered color or depth overflows `f32` (finite inputs near the top of its
range). `try_shadow_maps` also returns an error when a map's view or a caster's
light-space corners would not fit `f32` (vertices far from the origin).
+8 -5
View File
@@ -16,7 +16,8 @@
//! - **Passes.** The first [`Scene::opaque_count`] indices are opaque triangles: visibility is
//! resolved first and each pixel is shaded once. The rest are transparent triangles, which the
//! caller sorts back to front; they are shaded per fragment, depth-tested against the opaque
//! surfaces and blended over them.
//! surfaces and blended over them. A visible transparent material in the opaque range returns
//! [`RenderError::BadMaterial`], or [`RenderError::ShadowsOnlyOpaque`] for a shadows-only material.
//! - **Facing.** A triangle whose screen-space winding is counterclockwise with y down is front
//! facing. A single-sided material does not draw back faces.
//! - **Textures.** [`Scene::texels`] holds linear straight RGBA, row-major from the top row;
@@ -25,7 +26,8 @@
//! [`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 pass that runs over `max_work` while rendering also returns
//! 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.
#![forbid(unsafe_code)]
@@ -85,7 +87,8 @@ pub enum RenderError {
BadTransform,
/// 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.
/// that does not exist. [`try_render`] also returns it for a visible transparent material
/// in the opaque range, except a shadows-only material returns [`RenderError::ShadowsOnlyOpaque`].
#[error("material {0} has a value that is not finite or out of range, or names a texture that does not exist")]
BadMaterial(usize),
/// A texture has a zero side, or its span runs past [`Scene::texels`].
@@ -94,12 +97,12 @@ pub enum RenderError {
/// A texel is not finite, or its alpha is outside 0 to 1.
#[error("texel {0} is not finite or has an alpha outside 0 to 1")]
BadTexel(usize),
/// A light has a kind other than 0 to 2, a value that is not finite, a cone cosine outside −1
/// 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.
#[error(
"light {0} has an unknown kind, 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"
"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"
)]
BadLight(usize),
/// The light count is over [`Limits::max_lights`].
+16 -10
View File
@@ -418,6 +418,13 @@ struct Pass<'a> {
/// covers it.
type Visibility = Vec<(u32, f32, [f32; 3])>;
#[derive(Clone, Copy)]
struct FallbackFragment {
ndc_z: f32,
color: [f32; 4],
camera_depth: f32,
}
/// 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;
@@ -486,10 +493,10 @@ impl Band<'_> {
continue;
}
match best {
Some((z, c, d)) => {
crow[i] = c;
drow[i] = d;
vis[i].1 = z;
Some(f) => {
crow[i] = f.color;
drow[i] = f.camera_depth;
vis[i].1 = f.ndc_z;
}
None => vis[i].1 = EMPTY,
}
@@ -499,13 +506,12 @@ impl Band<'_> {
/// For each discarded pixel of the band, the nearest surviving opaque fragment of a screen
/// triangle other than the pixel's visible one, inside the depth range as in
/// [`Band::visibility`]: (ndc z, color, camera depth). Triangles are
/// [`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`].
#[allow(clippy::type_complexity)]
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result<Vec<Option<(f32, [f32; 4], f32)>>, RenderError> {
fn fallback(&self, opaque: Pass, vis: &Visibility, discarded: &[bool]) -> Result<Vec<Option<FallbackFragment>>, RenderError> {
let (s, w, y0, rows) = (self.s, self.w, self.y0, self.rows);
let mut best: Vec<Option<(f32, [f32; 4], f32)>> = vec![None; rows * w];
let mut best: Vec<Option<FallbackFragment>> = vec![None; rows * w];
for &tj in opaque.bins {
let t2 = &opaque.tris[tj as usize];
let mut tests = 0u64;
@@ -518,11 +524,11 @@ impl Band<'_> {
}
tests += 1;
if let Some((z, l2)) = cover(t2, x as f64 + 0.5, y as f64 + 0.5)
&& nearer(z, best[i].map_or(EMPTY, |b| b.0))
&& nearer(z, best[i].map_or(EMPTY, |b| b.ndc_z))
{
let f2 = frag(s, t2, l2);
if let Some(c) = shade(s, &f2) {
best[i] = Some((z, c, self.cam_z(f2.pos)));
best[i] = Some(FallbackFragment { ndc_z: z, color: c, camera_depth: self.cam_z(f2.pos) });
}
}
}
+15 -8
View File
@@ -121,7 +121,7 @@ pub struct Light {
pub cos_inner: f32,
/// Cosine of a spot light's cone half angle, −1 to 1.
pub cos_outer: f32,
/// 0 none, 1 smooth, 2 inverse square clamped.
/// 0 none, 1 smooth, 2 inverse square clamped. Other values return [`RenderError::BadLight`].
pub falloff: u32,
pub radius: f32,
pub falloff_distance: f32,
@@ -202,7 +202,9 @@ pub struct Scene {
pub ortho: bool,
pub vertices: Vec<Vertex>,
/// Triangles: the first `opaque_count` indices are opaque, the rest transparent, sorted
/// back to front.
/// back to front. A visible material for which [`Material::transparent`] is true in the
/// opaque range returns [`RenderError::BadMaterial`], or [`RenderError::ShadowsOnlyOpaque`]
/// for a shadows-only material.
pub indices: Vec<u32>,
pub opaque_count: u32,
pub materials: Vec<Material>,
@@ -322,6 +324,7 @@ fn validate_lights(s: &Scene, limits: &Limits) -> Result<(), RenderError> {
}
let ok = |l: &Light| {
l.kind <= 2
&& l.falloff <= 2
&& finite(&l.pos)
&& finite(&l.dir)
&& finite(&l.color)
@@ -356,16 +359,20 @@ fn validate_lights(s: &Scene, limits: &Limits) -> Result<(), RenderError> {
/// Every light and the environment light either has no shadow (a negative mark) or refers to
/// maps in [`Scene::shadows`]: six from its mark for a point light or a spot light whose cone
/// one map does not cover, one otherwise.
/// Checks that no drawn triangle of the opaque range has a shadows-only material (its first
/// Checks that no drawn triangle of the opaque range has a transparent material (its first
/// vertex's material, as the raster reads it; a material with `visible` false is not drawn). Run
/// after [`validate`].
pub(crate) fn validate_passes(s: &Scene) -> Result<(), RenderError> {
let shadows_only =
|t: &[u32]| s.vertices.get(t[0] as usize).and_then(|v| s.materials.get(v.material as usize)).is_some_and(|m| m.shadows_only && m.visible);
match s.indices.get(..s.opaque_count as usize).unwrap_or_default().chunks(3).position(shadows_only) {
Some(t) => Err(RenderError::ShadowsOnlyOpaque(t)),
None => Ok(()),
for (t, ids) in s.indices.get(..s.opaque_count as usize).unwrap_or_default().chunks(3).enumerate() {
if let Some(v) = s.vertices.get(ids[0] as usize)
&& let Some(m) = s.materials.get(v.material as usize)
&& m.visible
&& m.transparent()
{
return Err(if m.shadows_only { RenderError::ShadowsOnlyOpaque(t) } else { RenderError::BadMaterial(v.material as usize) });
}
}
Ok(())
}
pub(crate) fn validate_shadow_refs(s: &Scene) -> Result<(), RenderError> {
+71 -1
View File
@@ -103,7 +103,14 @@ fn light_poly(s: &Scene, m: &ShadowMap, ids: [usize; 3]) -> Vec<LightCorner> {
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) };
let lerp = |x: f32, y: f32| x + (y - x) * k;
let lerp = |x: f32, y: f32| {
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)) * f64::from(k)) as f32
}
};
// The crossing lies on the near plane; its depth is set to it, since the lerp of
// far-apart depths can round to 0 or below.
out.push(([lerp(p.0[0], q.0[0]), lerp(p.0[1], q.0[1]), NEAR], [lerp(p.1[0], q.1[0]), lerp(p.1[1], q.1[1])]));
@@ -206,6 +213,7 @@ 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 };
let wide_depth = !m.ortho && tri.iter().any(|c| c.1.is_subnormal());
for y in y0..y1 {
for x in x0..x1 {
let (px, py) = (x as f64 + 0.5, y as f64 + 0.5);
@@ -218,6 +226,8 @@ fn raster_triangle(s: &Scene, m: &ShadowMap, tri: [MapCorner; 3], alpha: Option<
let l = [e0 as f32, e1 as f32, e2 as f32];
let z = if m.ortho {
l[0] * tri[0].2 + l[1] * tri[1].2 + l[2] * tri[2].2
} else if wide_depth {
(1.0 / (e0 / f64::from(tri[0].2) + e1 / f64::from(tri[1].2) + e2 / f64::from(tri[2].2))) as f32
} else {
1.0 / (l[0] * tri[0].1 + l[1] * tri[1].1 + l[2] * tri[2].1)
};
@@ -590,3 +600,63 @@ fn shadow_maps_checked(s: &mut Scene, draft: bool, limits: &Limits) -> Result<()
s.shadow_texels = all;
Ok(())
}
#[cfg(test)]
mod tests {
use super::{NEAR, light_poly, shadow_raster};
use crate::{Material, Scene, ShadowMap, TexInfo, Vertex};
fn perspective_map() -> ShadowMap {
ShadowMap {
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]],
focal: 4.0,
ortho: false,
size: 8,
offset: 0,
bias: 0.0,
radius: 0.0,
}
}
#[test]
fn perspective_casters_with_subnormal_reciprocals_keep_finite_depth() {
for z in [1e38, f32::MAX] {
let s = Scene {
vertices: [[-0.25 * z, -0.25 * z, z], [0.25 * z, -0.25 * z, z], [0.0, 0.25 * z, z]]
.map(|pos| Vertex { pos, ..Vertex::default() })
.to_vec(),
indices: vec![0, 1, 2],
materials: vec![Material::default()],
..Scene::default()
};
let depths = shadow_raster(&s, &perspective_map(), &[0]);
assert!(depths[3 * 8 + 3].is_finite(), "caster depth {z}");
assert!(depths.iter().filter(|d| d.is_finite()).all(|&d| d == z));
}
}
#[test]
fn clipped_caster_uvs_with_overflowing_differences_keep_the_alpha_test() {
let covered = |u: f32, alphas: [f32; 2], indices: Vec<u32>| {
let s = Scene {
vertices: [([-NEAR, 0.0, 0.0], u), ([NEAR, -NEAR, 2.0 * NEAR], -u), ([NEAR, NEAR, 2.0 * NEAR], -u)]
.map(|(pos, u)| Vertex { pos, uv: [u, 0.5], ..Vertex::default() })
.to_vec(),
indices,
materials: vec![Material { alpha_mode: 1, tex_base: 0, ..Material::default() }],
textures: vec![TexInfo { width: 2, height: 1, wrap_u: 1, wrap_v: 1, ..TexInfo::default() }],
texels: alphas.map(|a| [1.0, 1.0, 1.0, a]).to_vec(),
..Scene::default()
};
let map = perspective_map();
let ids = [s.indices[0] as usize, s.indices[1] as usize, s.indices[2] as usize];
assert!(light_poly(&s, &map, ids).iter().all(|(_, uv)| uv.iter().all(|u| u.is_finite())));
shadow_raster(&s, &map, &[0]).iter().filter(|d| d.is_finite()).count()
};
for indices in [vec![0, 1, 2], vec![0, 2, 1]] {
assert!(covered(f32::MAX, [1.0; 2], indices.clone()) > 0);
assert_eq!(covered(1e20, [0.0, 1.0], indices.clone()), 0);
assert_eq!(covered(f32::MAX, [0.0, 1.0], indices), 0);
}
}
}
+29
View File
@@ -76,6 +76,35 @@ fn a_shadows_only_triangle_in_the_opaque_range_is_rejected() {
assert!(try_render(&s, &Limits::default()).is_ok());
}
#[test]
fn visible_transparent_materials_in_the_opaque_range_are_rejected() {
for material in [Material { alpha_mode: 2, ..Material::default() }, Material { opacity: 0.5, ..Material::default() }] {
let mut s = quad_scene(8, 8, &[([1.0, 1.0, 7.0, 7.0], 100.0, WHITE), ([0.0, 0.0, 8.0, 8.0], 50.0, WHITE)]);
s.materials[1] = material;
assert_eq!(try_render(&s, &Limits::default()), Err(RenderError::BadMaterial(1)));
assert!(matches!(try_render_cpu(&s, &Limits::default()), Err(RenderError::BadMaterial(1))));
s.materials[1].visible = false;
assert!(try_render(&s, &Limits::default()).is_ok());
s.materials[1].visible = true;
s.opaque_count = 6;
assert!(try_render(&s, &Limits::default()).is_ok());
}
}
#[test]
fn unknown_light_falloff_modes_are_rejected() {
for kind in 0..=2 {
for falloff in [3, u32::MAX] {
let mut s = one_quad();
s.lights = vec![Light { falloff, shadow: -1, ..shadow_light(kind) }];
assert_eq!(try_render(&s, &Limits::default()), Err(RenderError::BadLight(0)));
assert_eq!(try_shadow_maps(&mut s, false, &Limits::default()), Err(RenderError::BadLight(0)));
assert!(matches!(try_render_cpu(&s, &Limits::default()), Err(RenderError::BadLight(0))));
assert!(RenderError::BadLight(0).to_string().contains("unknown kind or falloff mode"));
}
}
}
#[test]
fn vertices_naming_missing_materials_are_rejected() {
let mut s = one_quad();