The animation engine for agents: blazingly fast math and 3D videos with Manim's Python API, on a Rust GPU core.
Python
Add scene shadow rendering
Sina Atalayec09c925e74a
diff --git a/rust/engine/src/light.wgsl b/rust/engine/src/light.wgslnew file mode 100644index 00000000..4cb39319--- /dev/null+++ b/rust/engine/src/light.wgsl@@ -0,0 +1,177 @@+// Light on a surface with a material, as Filament shades it (its standard model: GGX distribution, height-correlated+// Smith visibility, Schlick Fresnel, Lambert diffuse), from a view's lights: the radiance the surface sends toward the+// eye, which the view's tone mapping shows (`tone.wgsl`). A light's intensity is what a white matte surface shows: 1+// makes one facing it white (its illuminance is π times the intensity; an ambient light's radiance is the intensity,+// from every direction).++// A light (see `feed.lighting`): where (an ambient light: nowhere; a sun: the unit direction toward it; a point or+// spot: its position; an environment: its picture's +x) and its kind (0 ambient, 1 sun, 2 point, 3 spot, 4+// environment); its color in linear light times its intensity, and how far a point or spot reaches (an environment:+// its cube's roughest level); a spot's axis (where it points; an environment: its picture's up, +z, and the light a 1+// in its cube stands for) and its cone's falloff, scale and offset (Filament's); then its shadow map's layer (-1: none), a texel's world size (a spot's: at+// unit distance along its axis), whether the map is a perspective one (`shadow.rs`), and where the map sees from+// (clip = shadow · world).+struct Light {+ place: vec4<f32>,+ color: vec4<f32>,+ axis: vec4<f32>,+ cone: vec4<f32>,+ shadow: mat4x4<f32>,+};++const LIGHT_PI: f32 = 3.14159265358979;+const MIN_PERCEPTUAL_ROUGHNESS: f32 = 0.045; // below it, highlights alias and f16 overflows (Filament's)++fn d_ggx(roughness: f32, NoH: f32) -> f32 {+ let one_minus = 1.0 - NoH * NoH;+ let a = NoH * roughness;+ let k = min(roughness / (one_minus + a * a), 453.5);+ return k * k * (1.0 / LIGHT_PI);+}++fn v_smith_ggx_correlated(roughness: f32, NoV: f32, NoL: f32) -> f32 {+ let a2 = roughness * roughness;+ let lambda_v = NoL * sqrt((NoV - a2 * NoV) * NoV + a2);+ let lambda_l = NoV * sqrt((NoL - a2 * NoL) * NoL + a2);+ return 0.5 / max(lambda_v + lambda_l, 0.0000077);+}++fn f_schlick(f0: vec3<f32>, LoH: f32) -> vec3<f32> {+ let f90 = clamp(dot(f0, vec3<f32>(50.0 * 0.33)), 0.0, 1.0); // a surface darker than any real one: no glare+ let x = 1.0 - LoH;+ let x2 = x * x;+ return f0 + (f90 - f0) * (x2 * x2 * x);+}++// The radiance a surface at p, facing n (either side: the one toward v), sends toward v (a unit vector toward the+// eye), lit by the view's lights (`light_count`, `light_at`, `shadowed`, `dfg_at`, `environment_at`, `harmonic`: its+// host's): its base color in linear light, how metallic, how rough (perceptual), how much a dielectric reflects head+// on. The specular lobe keeps the light single scattering loses on a rough surface (Filament's energy compensation,+// from the DFG table's albedo of a white conductor, y): a white rough metal under a uniform light shows that light,+// at any roughness. Light from all around (an ambient light, an environment) lights by the split sum, as Filament's+// image-based light does: the specular lobe's albedo, mix(dfg.x, dfg.y, f0), times the light the lobe gathers (an+// environment's cube at the roughness's level, toward the lobe's dominant direction), and the diffuse part the light+// the specular lobe does not reflect (1 - its albedo). Of that light, `ao` reaches p (its view's ambient occlusion; 1:+// all of it): the diffuse part takes it as it is, the specular lobe as much of it as a lobe that narrow sees (Lagarde+// and de Rousiers' approximation), each with the light that bounces between the surfaces that shut it out (`bounced`),+// as Filament's multiple-bounce ambient occlusion has them.+fn reflected(base: vec3<f32>, metallic: f32, perceptual_roughness: f32, reflectance: f32, normal: vec3<f32>, p: vec3<f32>, v: vec3<f32>, ao: f32) -> vec3<f32> {+ let n = select(normal, -normal, dot(normal, v) < 0.0);+ let perceptual = clamp(perceptual_roughness, MIN_PERCEPTUAL_ROUGHNESS, 1.0);+ let roughness = perceptual * perceptual;+ let diffuse = base * (1.0 - metallic);+ let f0 = base * metallic + vec3<f32>(0.16 * reflectance * reflectance * (1.0 - metallic));+ let NoV = max(dot(n, v), 1e-4);+ let dfg = dfg_at(NoV, perceptual);+ let energy = 1.0 + f0 * (1.0 / max(dfg.y, 1e-4) - 1.0);+ let albedo = mix(vec3<f32>(dfg.x), vec3<f32>(dfg.y), f0);+ var diffuse_ao = vec3<f32>(1.0);+ var specular_ao = vec3<f32>(1.0);+ if (ao < 1.0) {+ diffuse_ao = bounced(ao, diffuse);+ specular_ao = bounced(clamp(pow(NoV + ao, exp2(-16.0 * roughness - 1.0)) - 1.0 + ao, 0.0, 1.0), f0);+ }+ var color = vec3<f32>(0.0);+ for (var i = 0u; i < light_count(); i++) {+ let light = light_at(i);+ let kind = u32(light.place.w + 0.5);+ if (kind == 0u) {+ color += (diffuse * (1.0 - albedo) * diffuse_ao + albedo * energy * specular_ao) * light.color.rgb;+ continue;+ }+ if (kind == 4u) {+ // directions in the environment's axes (x, z: the light's place and axis)+ let axes = mat3x3<f32>(light.place.xyz, cross(light.axis.xyz, light.place.xyz), light.axis.xyz);+ let dominant = mix(reflect(-v, n), n, roughness * roughness);+ let level = light.color.w * perceptual * (2.0 - perceptual);+ let specular = environment_at(dominant * axes, level) * (light.axis.w * albedo * energy);+ color += (diffuse * (1.0 - albedo) * irradiance(n * axes) * diffuse_ao + specular * specular_ao) * light.color.rgb;+ continue;+ }+ var l = light.place.xyz;+ var attenuation = 1.0;+ if (kind >= 2u) {+ let to_light = light.place.xyz - p;+ let d2 = dot(to_light, to_light);+ let f = d2 / max(light.color.w * light.color.w, 1e-8);+ let window = clamp(1.0 - f * f, 0.0, 1.0);+ attenuation = window * window / max(d2, 1e-4);+ l = to_light * inverseSqrt(max(d2, 1e-12));+ if (kind == 3u) {+ let t = clamp(dot(-light.axis.xyz, l) * light.axis.w + light.cone.x, 0.0, 1.0);+ attenuation *= t * t;+ }+ }+ let NoL = dot(n, l);+ if (attenuation <= 0.0 || NoL <= 0.0) {+ continue;+ }+ let h = normalize(v + l);+ let NoH = clamp(dot(n, h), 0.0, 1.0);+ let LoH = clamp(dot(l, h), 0.0, 1.0);+ let specular = d_ggx(roughness, NoH) * v_smith_ggx_correlated(roughness, NoV, NoL) * f_schlick(f0, LoH) * energy;+ let seen = shadowed(light, p, n);+ color += (diffuse * (1.0 / LIGHT_PI) + specular) * (NoL * LIGHT_PI * attenuation * seen) * light.color.rgb;+ }+ return color;+}++// A surface's perceptual roughness widened by how far its normal turns across a pixel (`turn`: the normal's change a+// pixel across and a pixel down, each squared, summed): a highlight narrower than the pixel then shows its light+// averaged over the pixel, not its light at the one point shaded, which a glint misses or hits, by orders of magnitude,+// from frame to frame (Filament's normal filtering: Kaplanyan 2016; Tokuyoshi and Kaplanyan 2019; its variance 0.15 and+// threshold 0.2). A flat surface keeps its roughness.+fn over_pixel(perceptual: f32, turn: f32) -> f32 {+ let roughness = perceptual * perceptual;+ let kernel = min(2.0 * 0.15 * turn, 0.2);+ return sqrt(sqrt(clamp(roughness * roughness + kernel, 0.0, 1.0)));+}++// The light from all around that reaches a surface of `albedo` where `visibility` of it is not shut out, with what+// bounces off the surfaces around it (as bright as it: Jimenez et al. 2016's fit), no less than the visibility.+fn bounced(visibility: f32, albedo: vec3<f32>) -> vec3<f32> {+ let a = 2.0404 * albedo - 0.3324;+ let b = -4.7951 * albedo + 0.6417;+ let c = 2.7552 * albedo + 0.6903;+ return max(vec3<f32>(visibility), ((visibility * a + b) * visibility + c) * visibility);+}++// An environment's diffuse light on a surface facing n (in its axes): its nine harmonics' sum (`harmonic`, its host's;+// `environment::harmonics`), no less than none.+fn irradiance(n: vec3<f32>) -> vec3<f32> {+ let first = harmonic(0u) + harmonic(1u) * n.y + harmonic(2u) * n.z + harmonic(3u) * n.x;+ let second = harmonic(4u) * (n.x * n.y) + harmonic(5u) * (n.y * n.z) + harmonic(6u) * (3.0 * n.z * n.z - 1.0) + harmonic(7u) * (n.z * n.x) + harmonic(8u) * (n.x * n.x - n.y * n.y);+ return max(first + second, vec3<f32>(0.0));+}++// How much of a light reaches p, a surface facing n: its shadow map's depth there (its host's `shadow_compare_at`,+// `shadow_texel`) compared with p's, each texel of a 3x3 neighbourhood bilinearly (a soft edge a few texels wide), p+// moved off the surface by a texel and a half along its normal first (no surface shadows itself: acne). Outside the+// map, lit.+fn shadowed(light: Light, p: vec3<f32>, n: vec3<f32>) -> f32 {+ let layer = i32(round(light.cone.y));+ if (layer < 0) {+ return 1.0;+ }+ var texel = light.cone.z;+ if (light.cone.w > 0.5) {+ texel *= max((light.shadow * vec4<f32>(p, 1.0)).w, 0.0);+ }+ let q = light.shadow * vec4<f32>(p + n * (1.5 * texel), 1.0);+ let ndc = q.xyz / q.w;+ let uv = ndc.xy * vec2<f32>(0.5, -0.5) + vec2<f32>(0.5);+ if (q.w <= 0.0 || ndc.z > 1.0 || any(uv < vec2<f32>(0.0)) || any(uv > vec2<f32>(1.0))) {+ return 1.0;+ }+ let step = shadow_texel();+ var seen = 0.0;+ for (var dy = -1; dy <= 1; dy++) {+ for (var dx = -1; dx <= 1; dx++) {+ seen += shadow_compare_at(uv + vec2<f32>(f32(dx), f32(dy)) * step, layer, ndc.z);+ }+ }+ return seen / 9.0;+}++// The most exposed light a view with lit meshes keeps (its raster base's light is half floats: `blend.wgsl`'s `Base`).+const LIGHT_MOST: f32 = 65000.0;diff --git a/rust/engine/src/shadow.rs b/rust/engine/src/shadow.rsnew file mode 100644index 00000000..9b61e8de--- /dev/null+++ b/rust/engine/src/shadow.rs@@ -0,0 +1,170 @@+//! Shadows: each sun and spot of a 3D view that casts them draws what casts them (its meshes' depth, then its paths'+//! nearest: `vector.wgsl`'s `fs_nearest`) from where it shines, into a map of `SIZE`² (a layer of an array), fitted+//! to the sphere around the casters and as deep as what their shadows can fall on; a surface with a material compares+//! its depth with the map (`light.wgsl`'s `shadowed`).++/// A map's side, in texels (Filament's default).+pub(crate) const SIZE: u32 = 2048;+/// The most maps a view draws (its first suns and spots that cast shadows).+pub(crate) const MOST: usize = 4;++/// A light's shadow map: the light (its slot in the view), where the map sees from (clip = matrix · world, its+/// columns), a texel's size in world units (a spot's: at unit distance along its axis), whether it sees in+/// perspective, its texels per world unit at the casters, and the unit vector toward the light (as a camera's+/// toward its viewer: the paths' plan seen from it).+pub(crate) struct Shadow {+ pub(crate) light: usize,+ pub(crate) matrix: [[f32; 4]; 4],+ pub(crate) texel: f32,+ pub(crate) perspective: bool,+ pub(crate) unit: f32,+ pub(crate) toward: [f32; 3],+}++type V = [f32; 3];++fn dot(a: V, b: V) -> f32 {+ a[0] * b[0] + a[1] * b[1] + a[2] * b[2]+}++fn cross(a: V, b: V) -> V {+ [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]+}++fn unit(a: V) -> V {+ let l = dot(a, a).sqrt().max(1e-12);+ a.map(|x| x / l)+}++/// A frame for looking along `f` (a unit vector): right and up.+fn basis(f: V) -> (V, V) {+ let up = if f[2].abs() < 0.9 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] };+ let x = unit(cross(f, up));+ (x, cross(x, f))+}++/// A matrix's columns from its rows.+fn columns(rows: [[f32; 4]; 4]) -> [[f32; 4]; 4] {+ std::array::from_fn(|j| std::array::from_fn(|i| rows[i][j]))+}++/// The maps of a view's `lights` (16 floats each, as `feed.lighting` packs them) that cast shadows, the first+/// `MOST`: each sees the sphere around `casters` (the meshes' box in the world: low, high corners), and as deep as+/// `receivers` (the box of what shadows can fall on: the meshes and the paths with a material) reach behind it.+pub(crate) fn fit(lights: &[f32], count: usize, casters: [V; 2], receivers: [V; 2]) -> Vec<Shadow> {+ let c: V = std::array::from_fn(|k| 0.5 * (casters[0][k] + casters[1][k]));+ let half: V = std::array::from_fn(|k| 0.5 * (casters[1][k] - casters[0][k]));+ let r = dot(half, half).sqrt().max(1e-3) * 1.02;+ // how far the receivers reach along f from a point+ let reach = |f: V, from: V| {+ (0..8).map(|k| dot(f, std::array::from_fn(|i| receivers[k >> i & 1][i] - from[i]))).fold(f32::MIN, f32::max)+ };+ let mut out = Vec::new();+ for light in 0..count.min(lights.len() / 16) {+ let slot = &lights[16 * light..16 * light + 16];+ if slot[13] < 0.5 || out.len() == MOST {+ continue;+ }+ let place: V = [slot[0], slot[1], slot[2]];+ match slot[3].round() as u32 {+ // a sun: an orthographic map along its light, the sphere in its box, from the sphere's near side to+ // its far side or the receivers', whichever is farther. Held still while the casters move (a still+ // shadow keeps its texels: no shimmer): the sphere's radius rounded up to a step of 2^(1/4), its centre+ // moved to a whole texel across the light+ 1 => {+ let f = unit(place.map(|x| -x));+ let (x, y) = basis(f);+ let r = 2f32.powf((r.log2() * 4.0).ceil() / 4.0);+ let texel = 2.0 * r / SIZE as f32;+ let (cx, cy) = (dot(x, c), dot(y, c));+ let (dx, dy) = ((cx / texel).round() * texel - cx, (cy / texel).round() * texel - cy);+ let c: V = std::array::from_fn(|k| c[k] + x[k] * dx + y[k] * dy);+ let deep = r + reach(f, c).max(r);+ let rows = [+ [x[0] / r, x[1] / r, x[2] / r, -dot(x, c) / r],+ [y[0] / r, y[1] / r, y[2] / r, -dot(y, c) / r],+ [f[0] / deep, f[1] / deep, f[2] / deep, (r - dot(f, c)) / deep],+ [0.0, 0.0, 0.0, 1.0],+ ];+ out.push(Shadow { light, matrix: columns(rows), texel: 2.0 * r / SIZE as f32, perspective: false, unit: SIZE as f32 / (2.0 * r), toward: place });+ }+ // a spot: a perspective map from its point along its axis, a little wider than its cone, from the+ // sphere's near side to its far side or the receivers', whichever is farther+ 3 => {+ let f = unit([slot[8], slot[9], slot[10]]);+ let (scale, offset) = (slot[11], slot[12]);+ let outer = (-offset / scale.max(1e-6)).clamp(-1.0, 1.0).acos();+ let t = (outer * 1.15 + 0.02).min(1.4).tan();+ let along = dot(f, std::array::from_fn(|k| c[k] - place[k]));+ let far = (along + r).max(reach(f, place));+ let near = (along - r).max(0.01 * r).max(1e-3);+ if far <= near {+ continue; // nothing in front of it+ }+ let (x, y) = basis(f);+ let (a, b) = (far / (far - near), far * near / (far - near));+ let rows = [+ [x[0] / t, x[1] / t, x[2] / t, -dot(x, place) / t],+ [y[0] / t, y[1] / t, y[2] / t, -dot(y, place) / t],+ [a * f[0], a * f[1], a * f[2], -a * dot(f, place) - b],+ [f[0], f[1], f[2], -dot(f, place)],+ ];+ out.push(Shadow { light, matrix: columns(rows), texel: 2.0 * t / SIZE as f32, perspective: true, unit: SIZE as f32 / (2.0 * t * along.max(near)), toward: f.map(|x| -x) });+ }+ _ => {}+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn apply(m: &[[f32; 4]; 4], p: V) -> [f32; 4] {+ std::array::from_fn(|i| m[0][i] * p[0] + m[1][i] * p[1] + m[2][i] * p[2] + m[3][i])+ }++ fn light(kind: f32, place: V, axis: V, angle: f32) -> [f32; 16] {+ let (outer, inner) = (angle.cos(), (angle * 0.8).cos());+ let scale = 1.0 / (inner - outer);+ [place[0], place[1], place[2], kind, 1.0, 1.0, 1.0, 20.0, axis[0], axis[1], axis[2], scale, -outer * scale, 1.0, 0.0, 0.0]+ }++ /// A sun's map holds every point of the sphere around the box: in the map's square, at a depth in [0, 1], the+ /// nearer the sun the smaller.+ #[test]+ fn a_sun_sees_the_whole_box() {+ let shadows = fit(&light(1.0, [1.0, 2.0, 3.0], [0.0; 3], 0.0), 1, [[-2.0, -1.0, -0.5], [2.0, 1.0, 0.5]], [[-2.0, -1.0, -0.5], [2.0, 1.0, 0.5]]);+ let m = &shadows[0].matrix;+ for corner in 0..8 {+ let p = [if corner & 1 == 0 { -2.0 } else { 2.0 }, if corner & 2 == 0 { -1.0 } else { 1.0 }, if corner & 4 == 0 { -0.5 } else { 0.5 }];+ let q = apply(m, p);+ assert!(q[0].abs() <= 1.0 && q[1].abs() <= 1.0 && (0.0..=1.0).contains(&q[2]), "{q:?}");+ }+ let toward = unit([1.0, 2.0, 3.0]);+ assert!(apply(m, toward)[2] < apply(m, toward.map(|x| -x))[2]);+ }++ /// A spot's map sees along its axis: the point it shines at is at the map's center, at a depth in [0, 1].+ #[test]+ fn a_spot_looks_along_its_axis() {+ let shadows = fit(&light(3.0, [0.0, 0.0, 4.0], [0.0, 0.0, -1.0], 0.5), 1, [[-1.0, -1.0, -0.1], [1.0, 1.0, 0.1]], [[-1.0, -1.0, -0.1], [1.0, 1.0, 0.1]]);+ let q = apply(&shadows[0].matrix, [0.0, 0.0, 0.0]);+ let ndc = [q[0] / q[3], q[1] / q[3], q[2] / q[3]];+ assert!(ndc[0].abs() < 1e-5 && ndc[1].abs() < 1e-5 && (0.0..=1.0).contains(&ndc[2]), "{ndc:?}");+ }++ /// A map reaches as deep as what shadows fall on: a wide floor far under a small caster is within its depth.+ #[test]+ fn a_map_reaches_the_receivers() {+ let floor = [[-6.0, -6.0, -3.0], [6.0, 6.0, -3.0]];+ let caster = [[-0.5, -0.5, -0.5], [0.5, 0.5, 0.5]];+ let sun = fit(&light(1.0, [1.0, 0.0, 1.0], [0.0; 3], 0.0), 1, caster, floor);+ let spot = fit(&light(3.0, [0.0, 0.0, 4.0], [0.0, 0.0, -1.0], 0.5), 1, caster, floor);+ for (s, p) in [(&sun[0], [3.0, 0.0, -3.0]), (&spot[0], [0.0, 0.0, -3.0])] {+ let q = apply(&s.matrix, p);+ assert!((0.0..=1.0).contains(&(q[2] / q[3])), "{q:?}");+ }+ }+}