archive: preserve reviewed CPU RGB lighting prerequisite (unrun source)
This commit is contained in:
1 parent
7464a9ba23
commit
fffecd56a9
8 files changed
+1056
-1
No files matched your search
@@ -171,4 +171,8 @@ explicit. Source review and replay are not compilation, full CI or GPU parity.
|
||||
|
||||
## 2026-10-31: original native CPU acceptance cases G01/G02 — not run
|
||||
|
||||
[Mouse/keyboard acceptance procedures](../2026-10-31/native-g01-g02-acceptance/README.md) preserve G01's original 19-body progressive/cancel/export requirement and add the distinct two-box physical-glass G02 case. G02 requires an actual completed IOR1.50 Strict image; a preserved error cannot pass it, and Standard observations remain separate. Actual CAD certification, optical-edit pixel refresh, stale-body recovery and CPU optical persistence are explicit obligations/limitations. Source-derived risks are labelled; all native observations are NOT_RUN. These are editable CAD recipes and procedures, with no bundled models, screenshots, binaries, full sources or runtime results. They do not replace the original 24 cases or constitute an execution grant.
|
||||
[Mouse/keyboard acceptance procedures](../2026-10-31/native-g01-g02-acceptance/README.md) preserve G01's original 19-body progressive/cancel/export requirement and add the distinct two-box physical-glass G02 case. G02 requires an actual completed IOR1.50 Strict image; a preserved error cannot pass it, and Standard observations remain separate. Actual CAD certification, optical-edit pixel refresh, stale-body recovery and CPU optical persistence are explicit obligations/limitations. Source-derived risks are labelled; all native observations are NOT_RUN. These are editable CAD recipes and procedures, with no bundled models, screenshots, binaries, full sources or runtime results. They do not replace the original 24 cases or constitute an execution grant.
|
||||
|
||||
## 2026-10-31: CPU RGB light-transmission shading — source-only prerequisite
|
||||
|
||||
[RGB direct-light shading helper](../2026-10-31/cpu-rgb-lighting/README.md) preserves the existing boolean lighting API and eight original test bodies, adding a separate per-light RGB-transmission method and seven analytic/boundary cases. The complete 15-case source set is unrun. It applies finite admitted channel values once without exposure or tone-map changes; invalid values/errors are refused. There is no ImageTask consumer, mode flag, UI, saved-format or render result, and this helper is outside C21. The owned-cursor and RGB proposals remain separate prerequisites for a later coherently reviewed consumer.
|
||||
@@ -0,0 +1,11 @@
|
||||
# CPU directional lighting: RGB transmission prerequisite
|
||||
|
||||
Source-only two-file proposal. Adds an internal sibling of the existing boolean visibility shading method, accepting completed per-light RGB transmission. Finite channels in[0,1] are required; invalid input and callback errors refuse without clamp/fallback. Light eligibility, index/order, directions, BRDF, intensity/cosine and accumulated-radiance validation are preserved. Original incident contribution is multiplied by RGB transmission exactly once. No exposure or tone mapping is added.
|
||||
|
||||
Before/candidate files and exact delta are bound in bindings.json. The complete previous lighting file is unchanged except for the inserted method; all8 prior tests remain byte-identical as a prefix, plus7 new tests. All15 are UNRUN. Exact source comparison/replay is not compilation, typecheck, lint, numerical execution, runtime or native acceptance. The internal method has no productive caller yet and may cause dead_code warnings; no suppressions added.
|
||||
|
||||
Independent Lambert constants and binary-preservation cases accompany invalid-channel/error/eligibility/index tests. The radiance-bound test intentionally constructs a private hostile light intensity outside public admission; it does not change or claim public acceptance of that intensity.
|
||||
|
||||
No ImageTask, colored-shadow feature flag, layout/resource accounting, command/UI/saved format, dependency or asset is included. This alone does not implement functioning colored shadows and is not a release or launch grant. Re-pin the actual receiver before composing; retain unrelated later changes. OWNER and runtime consumer require separate integration and validation; earlier runtime results do not qualify this source.
|
||||
|
||||
Original contribution under repository MIT OR Apache-2.0 terms. No third-party code or assets added.
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
//! Bounded direct lighting for RT2. World directions point from a hit towards each light.
|
||||
//! Colours are linear sRGB; intensity is relative radiance, not watts or illuminance.
|
||||
//! Visibility is supplied separately for every light by the ray-tracing consumer.
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use crate::surface::{OpaqueSurface, unit_direction};
|
||||
|
||||
use super::{Result, TraceError};
|
||||
|
||||
pub const MAX_LIGHTS: usize = 8;
|
||||
pub const MAX_LIGHT_INTENSITY: f64 = 64.0;
|
||||
/// Refuse unrepresentable or excessive output rather than silently clip the transport.
|
||||
pub const MAX_LINEAR_RADIANCE: f64 = 1.0e12;
|
||||
// With admitted radiance <=1e12, exposure <=2^32 remains below2^73 in f64.
|
||||
// This output-only range does not change the transport or film bounds.
|
||||
pub const MAX_EXPOSURE_EV: f64 = 32.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DirectionalLight {
|
||||
direction: Vec3,
|
||||
color: Vec3,
|
||||
intensity: f64,
|
||||
}
|
||||
|
||||
impl DirectionalLight {
|
||||
pub fn new(direction: Vec3, linear_color: Vec3, intensity: f64) -> Result<Self> {
|
||||
let direction = unit_direction(direction).map_err(|_| TraceError::InvalidInput("finite nonzero light direction required"))?;
|
||||
if !linear_color.is_finite() || !channels(linear_color).into_iter().all(|c| (0.0..=1.0).contains(&c)) {
|
||||
return Err(TraceError::InvalidInput("light colour must be finite linear sRGB in [0, 1]"));
|
||||
}
|
||||
if !intensity.is_finite() || !(0.0..=MAX_LIGHT_INTENSITY).contains(&intensity) {
|
||||
return Err(TraceError::InvalidInput("light intensity must be finite relative radiance in [0, 64]"));
|
||||
}
|
||||
Ok(Self { direction, color: linear_color, intensity })
|
||||
}
|
||||
|
||||
pub fn direction(self) -> Vec3 {
|
||||
self.direction
|
||||
}
|
||||
|
||||
pub fn color(self) -> Vec3 {
|
||||
self.color
|
||||
}
|
||||
|
||||
pub fn intensity(self) -> f64 {
|
||||
self.intensity
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StudioPreset {
|
||||
/// The existing three neutral lights, with unchanged directions and intensities.
|
||||
Neutral,
|
||||
/// Original warm key / cool fill colour composition, without a Kelvin claim.
|
||||
WarmCool,
|
||||
/// Original opposing key / rim composition. These are hard directional lights.
|
||||
KeyRim,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Lighting {
|
||||
lights: Vec<DirectionalLight>,
|
||||
}
|
||||
|
||||
impl Default for Lighting {
|
||||
fn default() -> Self {
|
||||
Self::studio_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Lighting {
|
||||
pub fn new(lights: Vec<DirectionalLight>) -> Result<Self> {
|
||||
if lights.len() > MAX_LIGHTS || lights.capacity() > MAX_LIGHTS {
|
||||
return Err(TraceError::InvalidInput("RT2 admits at most eight directional lights and eight reserved light slots"));
|
||||
}
|
||||
// An empty list deliberately means no direct illumination.
|
||||
Ok(Self { lights })
|
||||
}
|
||||
|
||||
pub fn studio_default() -> Self {
|
||||
Self {
|
||||
lights: crate::studio::LIGHTS
|
||||
.into_iter()
|
||||
.map(|(direction, intensity)| DirectionalLight { direction, color: Vec3::new(1.0, 1.0, 1.0), intensity })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preset(preset: StudioPreset) -> Result<Self> {
|
||||
let preset = match preset {
|
||||
StudioPreset::Neutral => return Ok(Self::studio_default()),
|
||||
StudioPreset::WarmCool => crate::job::LightingPreset::WarmCool,
|
||||
StudioPreset::KeyRim => crate::job::LightingPreset::KeyRim,
|
||||
};
|
||||
let lights = preset
|
||||
.directional_lights()
|
||||
.into_iter()
|
||||
.map(|light| {
|
||||
let [x, y, z] = light.direction;
|
||||
let [r, g, b] = light.color;
|
||||
DirectionalLight::new(Vec3::new(x, y, z), Vec3::new(r, g, b), light.intensity)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Self::new(lights)
|
||||
}
|
||||
|
||||
pub fn lights(&self) -> &[DirectionalLight] {
|
||||
&self.lights
|
||||
}
|
||||
|
||||
/// Sum BRDF * cosine * incident colour/intensity for independently visible lights.
|
||||
/// `visible` returns true for an unobstructed shadow ray; its errors propagate.
|
||||
/// No ambient term, exposure, tone map, display encoding or indirect bounce occurs here.
|
||||
pub fn shade_linear(
|
||||
&self,
|
||||
surface: OpaqueSurface,
|
||||
normal: Vec3,
|
||||
view: Vec3,
|
||||
mut visible: impl FnMut(usize, Vec3) -> Result<bool>,
|
||||
) -> Result<Vec3> {
|
||||
let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?;
|
||||
let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?;
|
||||
let mut sum = Vec3::ZERO;
|
||||
if n.dot(v) <= 0.0 {
|
||||
return Ok(sum);
|
||||
}
|
||||
for (index, light) in self.lights.iter().enumerate() {
|
||||
let cosine = n.dot(light.direction).max(0.0);
|
||||
if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO || !visible(index, light.direction)? {
|
||||
continue;
|
||||
}
|
||||
let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?;
|
||||
let weight = light.intensity * cosine;
|
||||
sum += Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight;
|
||||
validate_radiance(sum)?;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
}
|
||||
|
||||
fn channels(v: Vec3) -> [f64; 3] {
|
||||
[v.x, v.y, v.z]
|
||||
}
|
||||
|
||||
pub(super) fn validate_radiance(radiance: Vec3) -> Result<()> {
|
||||
if !radiance.is_finite() || !channels(radiance).into_iter().all(|c| (0.0..=MAX_LINEAR_RADIANCE).contains(&c)) {
|
||||
return Err(TraceError::InvalidInput("RT2 linear radiance must be finite and in [0, 1e12]"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The output boundary applies exposure once, then Reinhard once. The returned value
|
||||
/// is still linear sRGB: the image consumer must encode sRGB exactly once afterwards.
|
||||
/// Call this once after summing all direct lighting, never once per light.
|
||||
pub fn map_to_display(radiance: Vec3, exposure_ev: f64) -> Result<Vec3> {
|
||||
validate_radiance(radiance)?;
|
||||
if !exposure_ev.is_finite() || !(-MAX_EXPOSURE_EV..=MAX_EXPOSURE_EV).contains(&exposure_ev) {
|
||||
return Err(TraceError::InvalidInput("RT2 exposure must be finite and in [-32, 32] EV"));
|
||||
}
|
||||
crate::studio::tone_map(radiance * exposure_ev.exp2()).map_err(|_| TraceError::InvalidInput("invalid exposed radiance"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lighting_tests.rs"]
|
||||
mod tests;
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
use super::*;
|
||||
use std::f64::consts::PI;
|
||||
|
||||
fn lambert() -> OpaqueSurface {
|
||||
// At normal incidence IOR 1 gives f = base_colour / pi exactly.
|
||||
OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analytic_lambert_separates_linear_colour_intensity_and_cosine() {
|
||||
let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), 2.0).unwrap();
|
||||
let lights = Lighting::new(vec![light]).unwrap();
|
||||
let actual = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
let expected = Vec3::new(0.8, 0.25, 0.0625) * (2.0 / PI);
|
||||
assert!((actual - expected).len() < 1e-14);
|
||||
let twice = Lighting::new(vec![DirectionalLight::new(light.direction(), light.color(), 4.0).unwrap()]).unwrap();
|
||||
assert!((twice.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap() - actual * 2.0).len() < 1e-14);
|
||||
// White, fully rough conductor has f = 1 / (2*pi*(1+cos(theta)))
|
||||
// at a normal view. This independently checks the incident cosine.
|
||||
let conductor = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap();
|
||||
let angled = Lighting::new(vec![DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), light.color(), 2.0).unwrap()]).unwrap();
|
||||
let actual = angled.shade_linear(conductor, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!((actual - light.color() * (0.8 / (1.8 * PI))).len() < 1e-14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_visibility_is_independent_for_each_coloured_light() {
|
||||
let lights = Lighting::new(vec![
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.0, 0.0), 2.0).unwrap(),
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let mut visited = Vec::new();
|
||||
let blue = lights
|
||||
.shade_linear(lambert(), Vec3::Z, Vec3::Z, |i, direction| {
|
||||
visited.push((i, direction));
|
||||
Ok(i == 1)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]);
|
||||
assert!((blue - Vec3::new(0.0, 0.0, 0.75 / PI)).len() < 1e-14);
|
||||
assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(false)).unwrap(), Vec3::ZERO);
|
||||
for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] {
|
||||
assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_default_preserves_existing_studio_linear_response() {
|
||||
let lighting = Lighting::studio_default();
|
||||
assert_eq!(lighting.lights().len(), 3);
|
||||
for (light, (direction, intensity)) in lighting.lights().iter().zip(crate::studio::LIGHTS) {
|
||||
assert_eq!(light.direction(), direction);
|
||||
assert_eq!(light.intensity(), intensity);
|
||||
assert_eq!(light.color(), Vec3::new(1.0, 1.0, 1.0));
|
||||
}
|
||||
for metallic in [0.0, 0.5, 1.0] {
|
||||
let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap();
|
||||
let expected = crate::studio::shade(surface, Vec3::Z, Vec3::Z).unwrap();
|
||||
let actual = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!((expected - actual).len() < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_is_applied_after_the_sum_before_one_tone_map() {
|
||||
let linear = Vec3::new(0.25, 0.5, 1.0);
|
||||
let mapped = map_to_display(linear, 1.0).unwrap();
|
||||
assert!((mapped - Vec3::new(1.0 / 3.0, 0.5, 2.0 / 3.0)).len() < 1e-14);
|
||||
assert_eq!(map_to_display(Vec3::ZERO, -16.0).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(map_to_display(linear, 0.0).unwrap(), crate::studio::tone_map(linear).unwrap());
|
||||
let high = map_to_display(Vec3::new(MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE), 16.0).unwrap();
|
||||
assert!(high.is_finite() && high.x <= 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark_backfacing_and_unlit_surfaces_do_not_trace_shadow_rays() {
|
||||
let muted = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 0.0).unwrap();
|
||||
let behind = DirectionalLight::new(-Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap();
|
||||
let black = DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap();
|
||||
let lighting = Lighting::new(vec![muted, behind, black]).unwrap();
|
||||
assert_eq!(lighting.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no contributing light")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(Lighting::default().shade_linear(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inputs_are_refused_and_extreme_direction_scales_normalize() {
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 64.01] {
|
||||
assert!(DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), bad).is_err());
|
||||
}
|
||||
for bad in [f64::NAN, f64::INFINITY, -0.01, 1.01] {
|
||||
assert!(DirectionalLight::new(Vec3::Z, Vec3::new(bad, 1.0, 1.0), 1.0).is_err());
|
||||
}
|
||||
for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0)] {
|
||||
assert!(DirectionalLight::new(bad, Vec3::ZERO, 1.0).is_err());
|
||||
assert!(Lighting::default().shade_linear(lambert(), bad, Vec3::Z, |_, _| Ok(true)).is_err());
|
||||
assert!(Lighting::default().shade_linear(lambert(), Vec3::Z, bad, |_, _| Ok(true)).is_err());
|
||||
}
|
||||
let white = Vec3::new(1.0, 1.0, 1.0);
|
||||
for magnitude in [1e-300, 1e308] {
|
||||
let direction = DirectionalLight::new(Vec3::new(magnitude, magnitude, magnitude), white, 1.0).unwrap().direction();
|
||||
assert!((direction.len() - 1.0).abs() < 1e-14);
|
||||
}
|
||||
let light = DirectionalLight::new(Vec3::Z, white, MAX_LIGHT_INTENSITY).unwrap();
|
||||
assert!(Lighting::new(vec![light; MAX_LIGHTS]).is_ok());
|
||||
assert!(Lighting::new(vec![light; MAX_LIGHTS + 1]).is_err());
|
||||
let excess_capacity = Vec::<DirectionalLight>::with_capacity(MAX_LIGHTS + 1);
|
||||
assert_eq!(excess_capacity.len(), 0);
|
||||
assert!(Lighting::new(excess_capacity).is_err(), "empty vectors cannot retain an unbounded light allocation");
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -33.0, 33.0, -32.01, 32.01] {
|
||||
assert!(map_to_display(Vec3::ZERO, bad).is_err());
|
||||
}
|
||||
for bad in [f64::NAN, f64::INFINITY, -1.0, MAX_LINEAR_RADIANCE * 2.0] {
|
||||
assert!(map_to_display(Vec3::new(bad, 0.0, 0.0), 0.0).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_presets_have_distinct_bounded_real_direct_responses() {
|
||||
let white = Lighting::preset(StudioPreset::Neutral).unwrap();
|
||||
assert_eq!(white, Lighting::default());
|
||||
let warm = Lighting::preset(StudioPreset::WarmCool).unwrap();
|
||||
let rim = Lighting::preset(StudioPreset::KeyRim).unwrap();
|
||||
for lights in [&white, &warm, &rim] {
|
||||
assert!(lights.lights().len() <= MAX_LIGHTS);
|
||||
let response = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!(response.is_finite() && response.x > 0.0 && response.y > 0.0 && response.z > 0.0);
|
||||
}
|
||||
assert_ne!(
|
||||
white.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(),
|
||||
warm.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_full_saved_range_has_finite_binary_scaled_rational_outputs() {
|
||||
// Independent powers of two make the exposed channels exactly 1, 1/2, 0.
|
||||
// Do not obtain expected values from another renderer or the display mapper.
|
||||
for (ev, unit) in [(17.0, 1.0 / 131_072.0), (32.0, 1.0 / 4_294_967_296.0), (-17.0, 131_072.0), (-32.0, 4_294_967_296.0)] {
|
||||
let actual = map_to_display(Vec3::new(unit, unit * 0.5, 0.0), ev).unwrap();
|
||||
assert!((actual - Vec3::new(0.5, 1.0 / 3.0, 0.0)).len() < 1e-14);
|
||||
}
|
||||
for ev in [-32.0, -17.0, 0.0, 17.0, 32.0] {
|
||||
assert_eq!(map_to_display(Vec3::ZERO, ev).unwrap(), Vec3::ZERO);
|
||||
let high = map_to_display(Vec3::new(MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE), ev).unwrap();
|
||||
assert!(high.is_finite());
|
||||
assert!([high.x, high.y, high.z].into_iter().all(|v| (0.0..=1.0).contains(&v)));
|
||||
}
|
||||
// Expanding exposure never expands the admitted LINEAR transport bound.
|
||||
assert!(map_to_display(Vec3::new(MAX_LINEAR_RADIANCE * 2.0, 0.0, 0.0), -32.0).is_err());
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
{
|
||||
"status": "SOURCE_ONLY_TWO_FILE_PREREQUISITE_UNRUN",
|
||||
"tests": {
|
||||
"preserved": 8,
|
||||
"added": 7,
|
||||
"total": 15,
|
||||
"executed": 0
|
||||
},
|
||||
"members": [
|
||||
{
|
||||
"path": "before/crates/render/src/raytrace/lighting.rs",
|
||||
"bytes": 6620,
|
||||
"sha256": "d4bc7940af35ced7a727106b371f67b53ec68615cbd3013de6ddcf5d42708486"
|
||||
},
|
||||
{
|
||||
"path": "before/crates/render/src/raytrace/lighting_tests.rs",
|
||||
"bytes": 8201,
|
||||
"sha256": "2f7cdf2b371e7303cdbe91a5b064af0139db79acade2cf58581a30f424e0ca09"
|
||||
},
|
||||
{
|
||||
"path": "candidate/crates/render/src/raytrace/lighting.rs",
|
||||
"bytes": 8678,
|
||||
"sha256": "ab270656a20eedaea08e6858bdf0fd349ca64a5e528c0fc9162207adda541764"
|
||||
},
|
||||
{
|
||||
"path": "candidate/crates/render/src/raytrace/lighting_tests.rs",
|
||||
"bytes": 14927,
|
||||
"sha256": "cfd4194e7e5d6c6996700b0367984e2d91069078ee1a3aa3b6aa5453bd2cfc85"
|
||||
},
|
||||
{
|
||||
"path": "delta.patch",
|
||||
"bytes": 9450,
|
||||
"sha256": "0fba0675909e151a73a8848ecced19d16666f59892ad98f19a85060f9ab60038"
|
||||
},
|
||||
{
|
||||
"path": "README.md",
|
||||
"bytes": 1833,
|
||||
"sha256": "d67c774d8a26c2a58fa996f8120972ba21c3f17862b7a97d6924f3d6fee6b8ca"
|
||||
}
|
||||
]
|
||||
}
|
||||
+204
@@ -0,0 +1,204 @@
|
||||
//! Bounded direct lighting for RT2. World directions point from a hit towards each light.
|
||||
//! Colours are linear sRGB; intensity is relative radiance, not watts or illuminance.
|
||||
//! Visibility is supplied separately for every light by the ray-tracing consumer.
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use crate::surface::{OpaqueSurface, unit_direction};
|
||||
|
||||
use super::{Result, TraceError};
|
||||
|
||||
pub const MAX_LIGHTS: usize = 8;
|
||||
pub const MAX_LIGHT_INTENSITY: f64 = 64.0;
|
||||
/// Refuse unrepresentable or excessive output rather than silently clip the transport.
|
||||
pub const MAX_LINEAR_RADIANCE: f64 = 1.0e12;
|
||||
// With admitted radiance <=1e12, exposure <=2^32 remains below2^73 in f64.
|
||||
// This output-only range does not change the transport or film bounds.
|
||||
pub const MAX_EXPOSURE_EV: f64 = 32.0;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct DirectionalLight {
|
||||
direction: Vec3,
|
||||
color: Vec3,
|
||||
intensity: f64,
|
||||
}
|
||||
|
||||
impl DirectionalLight {
|
||||
pub fn new(direction: Vec3, linear_color: Vec3, intensity: f64) -> Result<Self> {
|
||||
let direction = unit_direction(direction).map_err(|_| TraceError::InvalidInput("finite nonzero light direction required"))?;
|
||||
if !linear_color.is_finite() || !channels(linear_color).into_iter().all(|c| (0.0..=1.0).contains(&c)) {
|
||||
return Err(TraceError::InvalidInput("light colour must be finite linear sRGB in [0, 1]"));
|
||||
}
|
||||
if !intensity.is_finite() || !(0.0..=MAX_LIGHT_INTENSITY).contains(&intensity) {
|
||||
return Err(TraceError::InvalidInput("light intensity must be finite relative radiance in [0, 64]"));
|
||||
}
|
||||
Ok(Self { direction, color: linear_color, intensity })
|
||||
}
|
||||
|
||||
pub fn direction(self) -> Vec3 {
|
||||
self.direction
|
||||
}
|
||||
|
||||
pub fn color(self) -> Vec3 {
|
||||
self.color
|
||||
}
|
||||
|
||||
pub fn intensity(self) -> f64 {
|
||||
self.intensity
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum StudioPreset {
|
||||
/// The existing three neutral lights, with unchanged directions and intensities.
|
||||
Neutral,
|
||||
/// Original warm key / cool fill colour composition, without a Kelvin claim.
|
||||
WarmCool,
|
||||
/// Original opposing key / rim composition. These are hard directional lights.
|
||||
KeyRim,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Lighting {
|
||||
lights: Vec<DirectionalLight>,
|
||||
}
|
||||
|
||||
impl Default for Lighting {
|
||||
fn default() -> Self {
|
||||
Self::studio_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl Lighting {
|
||||
pub fn new(lights: Vec<DirectionalLight>) -> Result<Self> {
|
||||
if lights.len() > MAX_LIGHTS || lights.capacity() > MAX_LIGHTS {
|
||||
return Err(TraceError::InvalidInput("RT2 admits at most eight directional lights and eight reserved light slots"));
|
||||
}
|
||||
// An empty list deliberately means no direct illumination.
|
||||
Ok(Self { lights })
|
||||
}
|
||||
|
||||
pub fn studio_default() -> Self {
|
||||
Self {
|
||||
lights: crate::studio::LIGHTS
|
||||
.into_iter()
|
||||
.map(|(direction, intensity)| DirectionalLight { direction, color: Vec3::new(1.0, 1.0, 1.0), intensity })
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn preset(preset: StudioPreset) -> Result<Self> {
|
||||
let preset = match preset {
|
||||
StudioPreset::Neutral => return Ok(Self::studio_default()),
|
||||
StudioPreset::WarmCool => crate::job::LightingPreset::WarmCool,
|
||||
StudioPreset::KeyRim => crate::job::LightingPreset::KeyRim,
|
||||
};
|
||||
let lights = preset
|
||||
.directional_lights()
|
||||
.into_iter()
|
||||
.map(|light| {
|
||||
let [x, y, z] = light.direction;
|
||||
let [r, g, b] = light.color;
|
||||
DirectionalLight::new(Vec3::new(x, y, z), Vec3::new(r, g, b), light.intensity)
|
||||
})
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
Self::new(lights)
|
||||
}
|
||||
|
||||
pub fn lights(&self) -> &[DirectionalLight] {
|
||||
&self.lights
|
||||
}
|
||||
|
||||
/// Sum BRDF * cosine * incident colour/intensity for independently visible lights.
|
||||
/// `visible` returns true for an unobstructed shadow ray; its errors propagate.
|
||||
/// No ambient term, exposure, tone map, display encoding or indirect bounce occurs here.
|
||||
pub fn shade_linear(
|
||||
&self,
|
||||
surface: OpaqueSurface,
|
||||
normal: Vec3,
|
||||
view: Vec3,
|
||||
mut visible: impl FnMut(usize, Vec3) -> Result<bool>,
|
||||
) -> Result<Vec3> {
|
||||
let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?;
|
||||
let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?;
|
||||
let mut sum = Vec3::ZERO;
|
||||
if n.dot(v) <= 0.0 {
|
||||
return Ok(sum);
|
||||
}
|
||||
for (index, light) in self.lights.iter().enumerate() {
|
||||
let cosine = n.dot(light.direction).max(0.0);
|
||||
if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO || !visible(index, light.direction)? {
|
||||
continue;
|
||||
}
|
||||
let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?;
|
||||
let weight = light.intensity * cosine;
|
||||
sum += Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight;
|
||||
validate_radiance(sum)?;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
/// Sum direct lighting with independently completed RGB transmittance.
|
||||
/// Ineligible lights never call `transmittance`. Each returned channel must
|
||||
/// be finite in [0, 1]; errors propagate without clipping or a fallback.
|
||||
/// No exposure, tone mapping, display encoding or indirect transport here.
|
||||
pub(super) fn shade_linear_transmitted(
|
||||
&self,
|
||||
surface: OpaqueSurface,
|
||||
normal: Vec3,
|
||||
view: Vec3,
|
||||
mut transmittance: impl FnMut(usize, Vec3) -> Result<Vec3>,
|
||||
) -> Result<Vec3> {
|
||||
let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?;
|
||||
let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?;
|
||||
let mut sum = Vec3::ZERO;
|
||||
if n.dot(v) <= 0.0 {
|
||||
return Ok(sum);
|
||||
}
|
||||
for (index, light) in self.lights.iter().enumerate() {
|
||||
let cosine = n.dot(light.direction).max(0.0);
|
||||
if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO {
|
||||
continue;
|
||||
}
|
||||
let transmission = transmittance(index, light.direction)?;
|
||||
if !transmission.is_finite() || !channels(transmission).into_iter().all(|c| (0.0..=1.0).contains(&c)) {
|
||||
return Err(TraceError::InvalidInput("direct transmittance must be finite RGB in [0, 1]"));
|
||||
}
|
||||
if transmission == Vec3::ZERO {
|
||||
continue;
|
||||
}
|
||||
let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?;
|
||||
let weight = light.intensity * cosine;
|
||||
let incident = Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight;
|
||||
sum += Vec3::new(incident.x * transmission.x, incident.y * transmission.y, incident.z * transmission.z);
|
||||
validate_radiance(sum)?;
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fn channels(v: Vec3) -> [f64; 3] {
|
||||
[v.x, v.y, v.z]
|
||||
}
|
||||
|
||||
pub(super) fn validate_radiance(radiance: Vec3) -> Result<()> {
|
||||
if !radiance.is_finite() || !channels(radiance).into_iter().all(|c| (0.0..=MAX_LINEAR_RADIANCE).contains(&c)) {
|
||||
return Err(TraceError::InvalidInput("RT2 linear radiance must be finite and in [0, 1e12]"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The output boundary applies exposure once, then Reinhard once. The returned value
|
||||
/// is still linear sRGB: the image consumer must encode sRGB exactly once afterwards.
|
||||
/// Call this once after summing all direct lighting, never once per light.
|
||||
pub fn map_to_display(radiance: Vec3, exposure_ev: f64) -> Result<Vec3> {
|
||||
validate_radiance(radiance)?;
|
||||
if !exposure_ev.is_finite() || !(-MAX_EXPOSURE_EV..=MAX_EXPOSURE_EV).contains(&exposure_ev) {
|
||||
return Err(TraceError::InvalidInput("RT2 exposure must be finite and in [-32, 32] EV"));
|
||||
}
|
||||
crate::studio::tone_map(radiance * exposure_ev.exp2()).map_err(|_| TraceError::InvalidInput("invalid exposed radiance"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "lighting_tests.rs"]
|
||||
mod tests;
|
||||
+288
@@ -0,0 +1,288 @@
|
||||
use super::*;
|
||||
use std::f64::consts::PI;
|
||||
|
||||
fn lambert() -> OpaqueSurface {
|
||||
// At normal incidence IOR 1 gives f = base_colour / pi exactly.
|
||||
OpaqueSurface::new(Vec3::new(0.8, 0.5, 0.25), 0.0, 1.0, 1.0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analytic_lambert_separates_linear_colour_intensity_and_cosine() {
|
||||
let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), 2.0).unwrap();
|
||||
let lights = Lighting::new(vec![light]).unwrap();
|
||||
let actual = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
let expected = Vec3::new(0.8, 0.25, 0.0625) * (2.0 / PI);
|
||||
assert!((actual - expected).len() < 1e-14);
|
||||
let twice = Lighting::new(vec![DirectionalLight::new(light.direction(), light.color(), 4.0).unwrap()]).unwrap();
|
||||
assert!((twice.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap() - actual * 2.0).len() < 1e-14);
|
||||
// White, fully rough conductor has f = 1 / (2*pi*(1+cos(theta)))
|
||||
// at a normal view. This independently checks the incident cosine.
|
||||
let conductor = OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap();
|
||||
let angled = Lighting::new(vec![DirectionalLight::new(Vec3::new(0.6, 0.0, 0.8), light.color(), 2.0).unwrap()]).unwrap();
|
||||
let actual = angled.shade_linear(conductor, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!((actual - light.color() * (0.8 / (1.8 * PI))).len() < 1e-14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadow_visibility_is_independent_for_each_coloured_light() {
|
||||
let lights = Lighting::new(vec![
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.0, 0.0), 2.0).unwrap(),
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(0.0, 0.0, 1.0), 3.0).unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let mut visited = Vec::new();
|
||||
let blue = lights
|
||||
.shade_linear(lambert(), Vec3::Z, Vec3::Z, |i, direction| {
|
||||
visited.push((i, direction));
|
||||
Ok(i == 1)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]);
|
||||
assert!((blue - Vec3::new(0.0, 0.0, 0.75 / PI)).len() < 1e-14);
|
||||
assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(false)).unwrap(), Vec3::ZERO);
|
||||
for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] {
|
||||
assert_eq!(lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neutral_default_preserves_existing_studio_linear_response() {
|
||||
let lighting = Lighting::studio_default();
|
||||
assert_eq!(lighting.lights().len(), 3);
|
||||
for (light, (direction, intensity)) in lighting.lights().iter().zip(crate::studio::LIGHTS) {
|
||||
assert_eq!(light.direction(), direction);
|
||||
assert_eq!(light.intensity(), intensity);
|
||||
assert_eq!(light.color(), Vec3::new(1.0, 1.0, 1.0));
|
||||
}
|
||||
for metallic in [0.0, 0.5, 1.0] {
|
||||
let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap();
|
||||
let expected = crate::studio::shade(surface, Vec3::Z, Vec3::Z).unwrap();
|
||||
let actual = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!((expected - actual).len() < 1e-12);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_is_applied_after_the_sum_before_one_tone_map() {
|
||||
let linear = Vec3::new(0.25, 0.5, 1.0);
|
||||
let mapped = map_to_display(linear, 1.0).unwrap();
|
||||
assert!((mapped - Vec3::new(1.0 / 3.0, 0.5, 2.0 / 3.0)).len() < 1e-14);
|
||||
assert_eq!(map_to_display(Vec3::ZERO, -16.0).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(map_to_display(linear, 0.0).unwrap(), crate::studio::tone_map(linear).unwrap());
|
||||
let high = map_to_display(Vec3::new(MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE), 16.0).unwrap();
|
||||
assert!(high.is_finite() && high.x <= 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dark_backfacing_and_unlit_surfaces_do_not_trace_shadow_rays() {
|
||||
let muted = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 0.0).unwrap();
|
||||
let behind = DirectionalLight::new(-Vec3::Z, Vec3::new(1.0, 1.0, 1.0), 1.0).unwrap();
|
||||
let black = DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap();
|
||||
let lighting = Lighting::new(vec![muted, behind, black]).unwrap();
|
||||
assert_eq!(lighting.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no contributing light")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(Lighting::default().shade_linear(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_inputs_are_refused_and_extreme_direction_scales_normalize() {
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 64.01] {
|
||||
assert!(DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), bad).is_err());
|
||||
}
|
||||
for bad in [f64::NAN, f64::INFINITY, -0.01, 1.01] {
|
||||
assert!(DirectionalLight::new(Vec3::Z, Vec3::new(bad, 1.0, 1.0), 1.0).is_err());
|
||||
}
|
||||
for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0)] {
|
||||
assert!(DirectionalLight::new(bad, Vec3::ZERO, 1.0).is_err());
|
||||
assert!(Lighting::default().shade_linear(lambert(), bad, Vec3::Z, |_, _| Ok(true)).is_err());
|
||||
assert!(Lighting::default().shade_linear(lambert(), Vec3::Z, bad, |_, _| Ok(true)).is_err());
|
||||
}
|
||||
let white = Vec3::new(1.0, 1.0, 1.0);
|
||||
for magnitude in [1e-300, 1e308] {
|
||||
let direction = DirectionalLight::new(Vec3::new(magnitude, magnitude, magnitude), white, 1.0).unwrap().direction();
|
||||
assert!((direction.len() - 1.0).abs() < 1e-14);
|
||||
}
|
||||
let light = DirectionalLight::new(Vec3::Z, white, MAX_LIGHT_INTENSITY).unwrap();
|
||||
assert!(Lighting::new(vec![light; MAX_LIGHTS]).is_ok());
|
||||
assert!(Lighting::new(vec![light; MAX_LIGHTS + 1]).is_err());
|
||||
let excess_capacity = Vec::<DirectionalLight>::with_capacity(MAX_LIGHTS + 1);
|
||||
assert_eq!(excess_capacity.len(), 0);
|
||||
assert!(Lighting::new(excess_capacity).is_err(), "empty vectors cannot retain an unbounded light allocation");
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -33.0, 33.0, -32.01, 32.01] {
|
||||
assert!(map_to_display(Vec3::ZERO, bad).is_err());
|
||||
}
|
||||
for bad in [f64::NAN, f64::INFINITY, -1.0, MAX_LINEAR_RADIANCE * 2.0] {
|
||||
assert!(map_to_display(Vec3::new(bad, 0.0, 0.0), 0.0).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_presets_have_distinct_bounded_real_direct_responses() {
|
||||
let white = Lighting::preset(StudioPreset::Neutral).unwrap();
|
||||
assert_eq!(white, Lighting::default());
|
||||
let warm = Lighting::preset(StudioPreset::WarmCool).unwrap();
|
||||
let rim = Lighting::preset(StudioPreset::KeyRim).unwrap();
|
||||
for lights in [&white, &warm, &rim] {
|
||||
assert!(lights.lights().len() <= MAX_LIGHTS);
|
||||
let response = lights.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap();
|
||||
assert!(response.is_finite() && response.x > 0.0 && response.y > 0.0 && response.z > 0.0);
|
||||
}
|
||||
assert_ne!(
|
||||
white.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap(),
|
||||
warm.shade_linear(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(true)).unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exposure_full_saved_range_has_finite_binary_scaled_rational_outputs() {
|
||||
// Independent powers of two make the exposed channels exactly 1, 1/2, 0.
|
||||
// Do not obtain expected values from another renderer or the display mapper.
|
||||
for (ev, unit) in [(17.0, 1.0 / 131_072.0), (32.0, 1.0 / 4_294_967_296.0), (-17.0, 131_072.0), (-32.0, 4_294_967_296.0)] {
|
||||
let actual = map_to_display(Vec3::new(unit, unit * 0.5, 0.0), ev).unwrap();
|
||||
assert!((actual - Vec3::new(0.5, 1.0 / 3.0, 0.0)).len() < 1e-14);
|
||||
}
|
||||
for ev in [-32.0, -17.0, 0.0, 17.0, 32.0] {
|
||||
assert_eq!(map_to_display(Vec3::ZERO, ev).unwrap(), Vec3::ZERO);
|
||||
let high = map_to_display(Vec3::new(MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE, MAX_LINEAR_RADIANCE), ev).unwrap();
|
||||
assert!(high.is_finite());
|
||||
assert!([high.x, high.y, high.z].into_iter().all(|v| (0.0..=1.0).contains(&v)));
|
||||
}
|
||||
// Expanding exposure never expands the admitted LINEAR transport bound.
|
||||
assert!(map_to_display(Vec3::new(MAX_LINEAR_RADIANCE * 2.0, 0.0, 0.0), -32.0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_lambert_has_independent_analytic_colour_and_channel_weights() {
|
||||
let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), PI).unwrap();
|
||||
let lighting = Lighting::new(vec![light]).unwrap();
|
||||
let actual = lighting
|
||||
.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
assert_eq!((index, direction), (0, Vec3::Z));
|
||||
Ok(Vec3::new(0.5, 0.25, 0.75))
|
||||
})
|
||||
.unwrap();
|
||||
// base(.8,.5,.25) * light(1,.5,.25) * PI/PI * T(.5,.25,.75).
|
||||
assert!((actual - Vec3::new(0.4, 0.0625, 0.046875)).len() < 1e-14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_white_black_and_binary_visibility_preserve_boolean_shading() {
|
||||
let lighting = Lighting::preset(StudioPreset::WarmCool).unwrap();
|
||||
for metallic in [0.0, 0.5, 1.0] {
|
||||
let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap();
|
||||
for selection in 0..3 {
|
||||
let visible = |index: usize| match selection { 0 => false, 1 => true, _ => index % 2 == 0 };
|
||||
let old = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |i, _| Ok(visible(i))).unwrap();
|
||||
let rgb = lighting
|
||||
.shade_linear_transmitted(surface, Vec3::Z, Vec3::Z, |i, _| {
|
||||
Ok(if visible(i) { Vec3::new(1.0, 1.0, 1.0) } else { Vec3::ZERO })
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(rgb, old);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_two_lights_use_independent_indices_and_sum_before_output() {
|
||||
let lighting = Lighting::new(vec![
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.0), PI).unwrap(),
|
||||
DirectionalLight::new(Vec3::Z, Vec3::new(0.5, 0.0, 1.0), 2.0 * PI).unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let mut visited = Vec::new();
|
||||
let actual = lighting
|
||||
.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
visited.push((index, direction));
|
||||
match index {
|
||||
0 => Ok(Vec3::new(0.25, 1.0, 0.5)),
|
||||
1 => Ok(Vec3::new(1.0, 0.5, 0.5)),
|
||||
_ => panic!("unexpected light index"),
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]);
|
||||
// Light0=(.2,.25,0), light1=(.8,0,.25); no tone mapping or exposure.
|
||||
assert!((actual - Vec3::new(1.0, 0.25, 0.25)).len() < 1e-14);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_ineligible_lights_do_not_request_visibility_or_renumber_indices() {
|
||||
let white = Vec3::new(1.0, 1.0, 1.0);
|
||||
let lighting = Lighting::new(vec![
|
||||
DirectionalLight::new(Vec3::Z, white, 0.0).unwrap(),
|
||||
DirectionalLight::new(-Vec3::Z, white, 1.0).unwrap(),
|
||||
DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap(),
|
||||
DirectionalLight::new(Vec3::X, white, 1.0).unwrap(),
|
||||
DirectionalLight::new(Vec3::Z, white, PI).unwrap(),
|
||||
])
|
||||
.unwrap();
|
||||
let mut visited = Vec::new();
|
||||
let actual = lighting
|
||||
.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
assert_eq!((index, direction), (4, Vec3::Z));
|
||||
visited.push(index);
|
||||
Ok(white)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(visited, vec![4]);
|
||||
assert!((actual - Vec3::new(0.8, 0.5, 0.25)).len() < 1e-14);
|
||||
assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::X, |_, _| panic!("tangent view")).unwrap(), Vec3::ZERO);
|
||||
assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_rejects_every_invalid_channel_and_propagates_callback_errors() {
|
||||
let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap();
|
||||
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 1.01] {
|
||||
for channel in 0..3 {
|
||||
let transmittance = match channel {
|
||||
0 => Vec3::new(bad, 0.0, 0.0),
|
||||
1 => Vec3::new(0.0, bad, 0.0),
|
||||
_ => Vec3::new(0.0, 0.0, bad),
|
||||
};
|
||||
assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(transmittance)), Err(TraceError::InvalidInput(_))));
|
||||
}
|
||||
}
|
||||
for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] {
|
||||
assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_keeps_shading_direction_validation_and_scale_normalization() {
|
||||
let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap();
|
||||
for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(0.0, 0.0, f64::INFINITY)] {
|
||||
assert!(lighting.shade_linear_transmitted(lambert(), bad, Vec3::Z, |_, _| panic!("invalid normal")).is_err());
|
||||
assert!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, bad, |_, _| panic!("invalid view")).is_err());
|
||||
}
|
||||
for magnitude in [1e-300, 1e308] {
|
||||
let actual = lighting
|
||||
.shade_linear_transmitted(lambert(), Vec3::new(0.0, 0.0, magnitude), Vec3::new(0.0, 0.0, magnitude), |_, _| Ok(Vec3::new(0.5, 0.25, 1.0)))
|
||||
.unwrap();
|
||||
assert!((actual - Vec3::new(0.4, 0.125, 0.25)).len() < 1e-14);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transmitted_checks_accumulated_radiance_after_transmission_without_clamping() {
|
||||
// Hostile INTERNAL fixture deliberately bypasses DirectionalLight::new's
|
||||
// intensity admission. This isolates the existing accumulated-radiance gate;
|
||||
// these intensities are not asserted to be accepted by the public API.
|
||||
// Each unattenuated term is (.6,.375,.1875)*MAX; two exceed MAX in red.
|
||||
let light = DirectionalLight { direction: Vec3::Z, color: Vec3::new(1.0, 1.0, 1.0), intensity: 0.75 * PI * MAX_LINEAR_RADIANCE };
|
||||
let lighting = Lighting::new(vec![light, light]).unwrap();
|
||||
let mut visits = 0;
|
||||
assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| {
|
||||
visits += 1;
|
||||
Ok(Vec3::new(1.0, 1.0, 1.0))
|
||||
}), Err(TraceError::InvalidInput(_))));
|
||||
assert_eq!(visits, 2);
|
||||
let attenuated = lighting
|
||||
.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::new(0.5, 0.5, 0.5)))
|
||||
.unwrap();
|
||||
let expected = Vec3::new(0.6, 0.375, 0.1875) * MAX_LINEAR_RADIANCE;
|
||||
assert!((attenuated - expected).len() <= MAX_LINEAR_RADIANCE * 1e-14);
|
||||
assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::ZERO)).unwrap(), Vec3::ZERO);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
--- a/crates/render/src/raytrace/lighting.rs
|
||||
+++ b/crates/render/src/raytrace/lighting.rs
|
||||
@@ -137,6 +137,44 @@
|
||||
}
|
||||
Ok(sum)
|
||||
}
|
||||
+ /// Sum direct lighting with independently completed RGB transmittance.
|
||||
+ /// Ineligible lights never call `transmittance`. Each returned channel must
|
||||
+ /// be finite in [0, 1]; errors propagate without clipping or a fallback.
|
||||
+ /// No exposure, tone mapping, display encoding or indirect transport here.
|
||||
+ pub(super) fn shade_linear_transmitted(
|
||||
+ &self,
|
||||
+ surface: OpaqueSurface,
|
||||
+ normal: Vec3,
|
||||
+ view: Vec3,
|
||||
+ mut transmittance: impl FnMut(usize, Vec3) -> Result<Vec3>,
|
||||
+ ) -> Result<Vec3> {
|
||||
+ let n = unit_direction(normal).map_err(|_| TraceError::InvalidInput("finite nonzero shading normal required"))?;
|
||||
+ let v = unit_direction(view).map_err(|_| TraceError::InvalidInput("finite nonzero shading view required"))?;
|
||||
+ let mut sum = Vec3::ZERO;
|
||||
+ if n.dot(v) <= 0.0 {
|
||||
+ return Ok(sum);
|
||||
+ }
|
||||
+ for (index, light) in self.lights.iter().enumerate() {
|
||||
+ let cosine = n.dot(light.direction).max(0.0);
|
||||
+ if cosine == 0.0 || light.intensity == 0.0 || light.color == Vec3::ZERO {
|
||||
+ continue;
|
||||
+ }
|
||||
+ let transmission = transmittance(index, light.direction)?;
|
||||
+ if !transmission.is_finite() || !channels(transmission).into_iter().all(|c| (0.0..=1.0).contains(&c)) {
|
||||
+ return Err(TraceError::InvalidInput("direct transmittance must be finite RGB in [0, 1]"));
|
||||
+ }
|
||||
+ if transmission == Vec3::ZERO {
|
||||
+ continue;
|
||||
+ }
|
||||
+ let brdf = surface.brdf(n, v, light.direction).map_err(|_| TraceError::InvalidInput("invalid opaque surface lighting directions"))?;
|
||||
+ let weight = light.intensity * cosine;
|
||||
+ let incident = Vec3::new(brdf.x * light.color.x, brdf.y * light.color.y, brdf.z * light.color.z) * weight;
|
||||
+ sum += Vec3::new(incident.x * transmission.x, incident.y * transmission.y, incident.z * transmission.z);
|
||||
+ validate_radiance(sum)?;
|
||||
+ }
|
||||
+ Ok(sum)
|
||||
+ }
|
||||
+
|
||||
}
|
||||
|
||||
fn channels(v: Vec3) -> [f64; 3] {
|
||||
--- a/crates/render/src/raytrace/lighting_tests.rs
|
||||
+++ b/crates/render/src/raytrace/lighting_tests.rs
|
||||
@@ -150,3 +150,139 @@
|
||||
// Expanding exposure never expands the admitted LINEAR transport bound.
|
||||
assert!(map_to_display(Vec3::new(MAX_LINEAR_RADIANCE * 2.0, 0.0, 0.0), -32.0).is_err());
|
||||
}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_lambert_has_independent_analytic_colour_and_channel_weights() {
|
||||
+ let light = DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.25), PI).unwrap();
|
||||
+ let lighting = Lighting::new(vec![light]).unwrap();
|
||||
+ let actual = lighting
|
||||
+ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
+ assert_eq!((index, direction), (0, Vec3::Z));
|
||||
+ Ok(Vec3::new(0.5, 0.25, 0.75))
|
||||
+ })
|
||||
+ .unwrap();
|
||||
+ // base(.8,.5,.25) * light(1,.5,.25) * PI/PI * T(.5,.25,.75).
|
||||
+ assert!((actual - Vec3::new(0.4, 0.0625, 0.046875)).len() < 1e-14);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_white_black_and_binary_visibility_preserve_boolean_shading() {
|
||||
+ let lighting = Lighting::preset(StudioPreset::WarmCool).unwrap();
|
||||
+ for metallic in [0.0, 0.5, 1.0] {
|
||||
+ let surface = OpaqueSurface::new(Vec3::new(0.8, 0.3, 0.2), metallic, 0.5, 1.5).unwrap();
|
||||
+ for selection in 0..3 {
|
||||
+ let visible = |index: usize| match selection { 0 => false, 1 => true, _ => index % 2 == 0 };
|
||||
+ let old = lighting.shade_linear(surface, Vec3::Z, Vec3::Z, |i, _| Ok(visible(i))).unwrap();
|
||||
+ let rgb = lighting
|
||||
+ .shade_linear_transmitted(surface, Vec3::Z, Vec3::Z, |i, _| {
|
||||
+ Ok(if visible(i) { Vec3::new(1.0, 1.0, 1.0) } else { Vec3::ZERO })
|
||||
+ })
|
||||
+ .unwrap();
|
||||
+ assert_eq!(rgb, old);
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_two_lights_use_independent_indices_and_sum_before_output() {
|
||||
+ let lighting = Lighting::new(vec![
|
||||
+ DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 0.5, 0.0), PI).unwrap(),
|
||||
+ DirectionalLight::new(Vec3::Z, Vec3::new(0.5, 0.0, 1.0), 2.0 * PI).unwrap(),
|
||||
+ ])
|
||||
+ .unwrap();
|
||||
+ let mut visited = Vec::new();
|
||||
+ let actual = lighting
|
||||
+ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
+ visited.push((index, direction));
|
||||
+ match index {
|
||||
+ 0 => Ok(Vec3::new(0.25, 1.0, 0.5)),
|
||||
+ 1 => Ok(Vec3::new(1.0, 0.5, 0.5)),
|
||||
+ _ => panic!("unexpected light index"),
|
||||
+ }
|
||||
+ })
|
||||
+ .unwrap();
|
||||
+ assert_eq!(visited, vec![(0, Vec3::Z), (1, Vec3::Z)]);
|
||||
+ // Light0=(.2,.25,0), light1=(.8,0,.25); no tone mapping or exposure.
|
||||
+ assert!((actual - Vec3::new(1.0, 0.25, 0.25)).len() < 1e-14);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_ineligible_lights_do_not_request_visibility_or_renumber_indices() {
|
||||
+ let white = Vec3::new(1.0, 1.0, 1.0);
|
||||
+ let lighting = Lighting::new(vec![
|
||||
+ DirectionalLight::new(Vec3::Z, white, 0.0).unwrap(),
|
||||
+ DirectionalLight::new(-Vec3::Z, white, 1.0).unwrap(),
|
||||
+ DirectionalLight::new(Vec3::Z, Vec3::ZERO, 1.0).unwrap(),
|
||||
+ DirectionalLight::new(Vec3::X, white, 1.0).unwrap(),
|
||||
+ DirectionalLight::new(Vec3::Z, white, PI).unwrap(),
|
||||
+ ])
|
||||
+ .unwrap();
|
||||
+ let mut visited = Vec::new();
|
||||
+ let actual = lighting
|
||||
+ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |index, direction| {
|
||||
+ assert_eq!((index, direction), (4, Vec3::Z));
|
||||
+ visited.push(index);
|
||||
+ Ok(white)
|
||||
+ })
|
||||
+ .unwrap();
|
||||
+ assert_eq!(visited, vec![4]);
|
||||
+ assert!((actual - Vec3::new(0.8, 0.5, 0.25)).len() < 1e-14);
|
||||
+ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, -Vec3::Z, |_, _| panic!("backfacing view")).unwrap(), Vec3::ZERO);
|
||||
+ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::X, |_, _| panic!("tangent view")).unwrap(), Vec3::ZERO);
|
||||
+ assert_eq!(Lighting::new(Vec::new()).unwrap().shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| panic!("no lights")).unwrap(), Vec3::ZERO);
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_rejects_every_invalid_channel_and_propagates_callback_errors() {
|
||||
+ let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap();
|
||||
+ for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -0.01, 1.01] {
|
||||
+ for channel in 0..3 {
|
||||
+ let transmittance = match channel {
|
||||
+ 0 => Vec3::new(bad, 0.0, 0.0),
|
||||
+ 1 => Vec3::new(0.0, bad, 0.0),
|
||||
+ _ => Vec3::new(0.0, 0.0, bad),
|
||||
+ };
|
||||
+ assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(transmittance)), Err(TraceError::InvalidInput(_))));
|
||||
+ }
|
||||
+ }
|
||||
+ for error in [TraceError::Cancelled, TraceError::WorkLimit, TraceError::MemoryLimit] {
|
||||
+ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Err(error)), Err(error));
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_keeps_shading_direction_validation_and_scale_normalization() {
|
||||
+ let lighting = Lighting::new(vec![DirectionalLight::new(Vec3::Z, Vec3::new(1.0, 1.0, 1.0), PI).unwrap()]).unwrap();
|
||||
+ for bad in [Vec3::ZERO, Vec3::new(f64::NAN, 0.0, 1.0), Vec3::new(0.0, 0.0, f64::INFINITY)] {
|
||||
+ assert!(lighting.shade_linear_transmitted(lambert(), bad, Vec3::Z, |_, _| panic!("invalid normal")).is_err());
|
||||
+ assert!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, bad, |_, _| panic!("invalid view")).is_err());
|
||||
+ }
|
||||
+ for magnitude in [1e-300, 1e308] {
|
||||
+ let actual = lighting
|
||||
+ .shade_linear_transmitted(lambert(), Vec3::new(0.0, 0.0, magnitude), Vec3::new(0.0, 0.0, magnitude), |_, _| Ok(Vec3::new(0.5, 0.25, 1.0)))
|
||||
+ .unwrap();
|
||||
+ assert!((actual - Vec3::new(0.4, 0.125, 0.25)).len() < 1e-14);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+#[test]
|
||||
+fn transmitted_checks_accumulated_radiance_after_transmission_without_clamping() {
|
||||
+ // Hostile INTERNAL fixture deliberately bypasses DirectionalLight::new's
|
||||
+ // intensity admission. This isolates the existing accumulated-radiance gate;
|
||||
+ // these intensities are not asserted to be accepted by the public API.
|
||||
+ // Each unattenuated term is (.6,.375,.1875)*MAX; two exceed MAX in red.
|
||||
+ let light = DirectionalLight { direction: Vec3::Z, color: Vec3::new(1.0, 1.0, 1.0), intensity: 0.75 * PI * MAX_LINEAR_RADIANCE };
|
||||
+ let lighting = Lighting::new(vec![light, light]).unwrap();
|
||||
+ let mut visits = 0;
|
||||
+ assert!(matches!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| {
|
||||
+ visits += 1;
|
||||
+ Ok(Vec3::new(1.0, 1.0, 1.0))
|
||||
+ }), Err(TraceError::InvalidInput(_))));
|
||||
+ assert_eq!(visits, 2);
|
||||
+ let attenuated = lighting
|
||||
+ .shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::new(0.5, 0.5, 0.5)))
|
||||
+ .unwrap();
|
||||
+ let expected = Vec3::new(0.6, 0.375, 0.1875) * MAX_LINEAR_RADIANCE;
|
||||
+ assert!((attenuated - expected).len() <= MAX_LINEAR_RADIANCE * 1e-14);
|
||||
+ assert_eq!(lighting.shade_linear_transmitted(lambert(), Vec3::Z, Vec3::Z, |_, _| Ok(Vec3::ZERO)).unwrap(), Vec3::ZERO);
|
||||
+}
|
||||
Reference in new issue
Block a user