From 9c00057b07397a81c13f866dbc14fb0ae0d1399a Mon Sep 17 00:00:00 2001 From: clover caruso Date: Mon, 30 Nov 2026 20:44:22 -0800 Subject: [PATCH] Fix 3D normal matrix, scaled cameras, multi-dir lights, GPU mesh/FBX/optflow caching - shader: transform normals by the cofactor of the model 3x3 (non-uniform scale) - collect: general mat4_inverse for camera views, numeric SceneInput order, every LightDirectional collected (4 shader slots) - scene3d: bounded LRU of GPU vertex/index buffers keyed by base shape - fbx: cache keyed by (path, mtime, obj, scale); the missing-file placeholder is never cached - optflow: LRU of 4 half-res flow fields keyed by frame pair so extra alphas only run the warp - eval/text_3d: use mat4_inverse and hash all directional lights Assisted-by: claude-sonnet-5.5 --- crates/engine/src/eval/text_3d.rs | 8 +- crates/engine/src/optflow.rs | 133 ++++++++++--- crates/engine/src/scene3d/collect.rs | 97 +++++++++- crates/engine/src/scene3d/fbx.rs | 57 ++++-- crates/engine/src/scene3d/mod.rs | 276 +++++++++++++++++++++------ crates/engine/src/scene3d/shader.rs | 39 ++-- 6 files changed, 489 insertions(+), 121 deletions(-) diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 9b811a5303f8fc21f98e20dc1448bbba06690d40..a7a040ca8294d64ed6fe25ffd9d4670c6a68c976 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -534,7 +534,7 @@ impl Engine { ); let (view, proj, cam_pos) = if let Some(cam) = cameras.first() { - let v = crate::scene3d::mat4_inverse_rigid(cam.world); + let v = crate::scene3d::mat4_inverse(cam.world); let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far); (v, p, [cam.world[12], cam.world[13], cam.world[14]]) } else { @@ -550,8 +550,10 @@ impl Engine { hash_floats.extend_from_slice(&view_proj); hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 }); hash_floats.extend_from_slice(&lights.ambient); - hash_floats.extend_from_slice(&lights.dir_to_light); - hash_floats.extend_from_slice(&lights.dir_color); + for dl in &lights.dirs { + hash_floats.extend_from_slice(&dl.to_light); + hash_floats.extend_from_slice(&dl.color); + } for pl in &lights.points { hash_floats.extend_from_slice(&pl.pos); hash_floats.extend_from_slice(&pl.color); diff --git a/crates/engine/src/optflow.rs b/crates/engine/src/optflow.rs index a23684daba0ae17b201868b34a20d82e418b9f89..39ddda5b3bda86c5405670f83f98b063f50e348f 100644 --- a/crates/engine/src/optflow.rs +++ b/crates/engine/src/optflow.rs @@ -7,7 +7,7 @@ use model::BitDepth; use std::collections::HashMap; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; -use std::sync::RwLock; +use std::sync::{Mutex, RwLock}; #[repr(C)] #[derive(Clone, Copy, Pod, Zeroable)] @@ -449,6 +449,12 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4 { } "#; +/// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair. +const FLOW_CACHE_CAP: usize = 4; + +/// `(content_hash_a, content_hash_b, full-res size)`. +type FlowKey = (u64, u64, [u32; 2]); + /// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation. pub struct OpticalFlowPipelines { shader: wgpu::ShaderModule, @@ -462,6 +468,8 @@ pub struct OpticalFlowPipelines { flow_smooth: wgpu::RenderPipeline, blend_pipelines: RwLock>, warp_pipelines: RwLock>, + /// Half-resolution flow fields, least recently used first. + flow_cache: Mutex>, } impl OpticalFlowPipelines { @@ -547,6 +555,7 @@ impl OpticalFlowPipelines { flow_smooth, blend_pipelines: RwLock::new(HashMap::new()), warp_pipelines: RwLock::new(HashMap::new()), + flow_cache: Mutex::new(Vec::new()), } } @@ -694,11 +703,58 @@ impl OpticalFlowPipelines { let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format); let dst = alloc_output_texture(device, frame_a, target_format, key); - // Compute 4-level pyramid dimensions: full, 1/2, 1/4, 1/8 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; - let s1 = [s0[0].div_ceil(2).max(1), s0[1].div_ceil(2).max(1)]; - let s2 = [s1[0].div_ceil(2).max(1), s1[1].div_ceil(2).max(1)]; - let s3 = [s2[0].div_ceil(2).max(1), s2[1].div_ceil(2).max(1)]; + let s1 = half_size(s0); + let flow_key = (frame_a.content_hash, frame_b.content_hash, s0); + let cached = { + let mut cache = self.flow_cache.lock().unwrap(); + cache.iter().position(|(k, _)| *k == flow_key).map(|i| { + let entry = cache.remove(i); + let view = entry.1.clone(); + cache.push(entry); + view + }) + }; + let flow1_view = cached.unwrap_or_else(|| { + let view = self.compute_flow_field(device, queue, enc, frame_a, frame_b); + let mut cache = self.flow_cache.lock().unwrap(); + if cache.len() >= FLOW_CACHE_CAP { + cache.remove(0); + } + cache.push((flow_key, view.clone())); + view + }); + + // Full-resolution bidirectional occlusion-aware warp & blend + let scale_1_to_0 = [ + s0[0] as f32 / s1[0] as f32, + s0[1] as f32 / s1[1] as f32, + alpha.clamp(0.0, 1.0), + 0.0, + ]; + let guard = self.warp_pipelines.read().unwrap(); + let pipe = guard.get(&target_format).unwrap(); + self.run_pass( + device, queue, enc, pipe, "optflow-warp", + &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0, + ); + dst + } + + /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the + /// half-resolution flow field. + fn compute_flow_field( + &self, + device: &wgpu::Device, + queue: &wgpu::Queue, + enc: &mut wgpu::CommandEncoder, + frame_a: &CachedTexture, + frame_b: &CachedTexture, + ) -> wgpu::TextureView { + let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)]; + let s1 = half_size(s0); + let s2 = half_size(s1); + let s3 = half_size(s2); // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0"); @@ -784,41 +840,20 @@ impl OpticalFlowPipelines { &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4], ); - // 3. Full-resolution bidirectional occlusion-aware warp & blend - let scale_1_to_0 = [ - s0[0] as f32 / s1[0] as f32, - s0[1] as f32 / s1[1] as f32, - alpha.clamp(0.0, 1.0), - 0.0, - ]; - { - let guard = self.warp_pipelines.read().unwrap(); - let pipe = guard.get(&target_format).unwrap(); - self.run_pass( - device, - queue, - enc, - pipe, - "optflow-warp", - &frame_a.view, - &frame_b.view, - &flow1_view, - &dst.view, - s0, - scale_1_to_0, - ); - } - // Keep temporary textures alive until all passes are encoded into `enc`. drop(( fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex, flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex, )); - dst + flow1_view } } +fn half_size(s: [u32; 2]) -> [u32; 2] { + [s[0].div_ceil(2).max(1), s[1].div_ceil(2).max(1)] +} + fn create_fullscreen_pipeline( device: &wgpu::Device, shader: &wgpu::ShaderModule, @@ -1209,6 +1244,42 @@ mod tests { ); } + #[test] + fn test_flow_field_is_cached_per_frame_pair_and_bounded() { + let (device, queue) = create_headless_device(); + let cached = OpticalFlowPipelines::new(&device); + let fresh = OpticalFlowPipelines::new(&device); + + let (w, h) = (128u32, 72u32); + let frame = |i: i32, hash: u64| { + upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 20 + 8 * i, 20), hash) + }; + let (tex_a, tex_b) = (frame(0, 1), frame(1, 2)); + let fmt = wgpu::TextureFormat::Rgba8Unorm; + let interp = |p: &OpticalFlowPipelines, a: &CachedTexture, b: &CachedTexture, alpha: f32| { + let mut enc = device.create_command_encoder(&Default::default()); + let out = p.interpolate_flow(&device, &queue, &mut enc, a, b, alpha, fmt); + queue.submit(Some(enc.finish())); + readback_bytes(&device, &queue, &out, 4) + }; + + let first = interp(&cached, &tex_a, &tex_b, 0.25); + let field = cached.flow_cache.lock().unwrap()[0].1.clone(); + let second = interp(&cached, &tex_a, &tex_b, 0.75); + { + let cache = cached.flow_cache.lock().unwrap(); + assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field"); + assert!(cache[0].1 == field, "second alpha must hit the cached field texture"); + } + assert_ne!(first, second, "alpha still drives the warp pass"); + assert_eq!(second, interp(&fresh, &tex_a, &tex_b, 0.75), "cached field matches a fresh computation"); + + for i in 2..8 { + interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5); + } + assert_eq!(cached.flow_cache.lock().unwrap().len(), FLOW_CACHE_CAP); + } + #[test] fn test_optflow_mismatched_sizes_and_rgba32float() { let (device, queue) = create_headless_device(); diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index d1a3757963fa4fb10cac7063769d43a970f70be0..5e646de9d4ff0f93aa1c8addce6c6410c645f657 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -2,10 +2,10 @@ use super::fbx::load_mesh_cached; use super::math::{ - mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, + mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, }; use super::{ - CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, + CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES, }; use model::{Comp, ExprEngine, Node, NodeId}; @@ -126,7 +126,8 @@ fn collect_scene_inner( .keys() .filter(|k| k.starts_with("SceneInput")) .collect(); - input_names.sort(); + // `SceneInput2` precedes `SceneInput10`. + input_names.sort_by_cached_key(|k| (k["SceneInput".len()..].parse::().unwrap_or(0), k.to_string())); for in_name in input_names { if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) { collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); @@ -270,9 +271,7 @@ fn collect_scene_inner( let dy = world[9]; let dz = world[10]; let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5); - lights.dir_to_light = [dx / len, dy / len, dz / len]; - lights.dir_color = color; - lights.has_dir = true; + lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color }); } "LightPoint" => { let Some(color) = light_color(comp, node, time, expr) else { return }; @@ -729,6 +728,42 @@ fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz))) } +/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to +/// `mat4_inverse_rigid` so a degenerate camera scale never yields NaNs. +pub fn mat4_inverse(m: Mat4) -> Mat4 { + let mut a = [[0.0_f64; 8]; 4]; + for (r, row) in a.iter_mut().enumerate() { + for c in 0..4 { + row[c] = f64::from(m[c * 4 + r]); + } + row[4 + r] = 1.0; + } + for col in 0..4 { + let pivot = (col..4).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs())).unwrap_or(col); + let invertible = a[pivot][col].abs() > 1e-12; + if !invertible { + return mat4_inverse_rigid(m); + } + a.swap(col, pivot); + let p = a[col][col]; + a[col].iter_mut().for_each(|x| *x /= p); + let pivot_row = a[col]; + for (r, row) in a.iter_mut().enumerate() { + if r != col { + let f = row[col]; + row.iter_mut().zip(pivot_row).for_each(|(x, pv)| *x -= f * pv); + } + } + } + let mut out = [0.0_f32; 16]; + for (r, row) in a.iter().enumerate() { + for c in 0..4 { + out[c * 4 + r] = row[4 + c] as f32; + } + } + out +} + pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 { let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32; let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; @@ -1183,4 +1218,54 @@ mod tests { assert_eq!(meshes.len(), 1); assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. })); } + + #[test] + fn scene_inputs_are_visited_in_numeric_order() { + let plane = |name: &str, x: u32| format!(r#"{name} = Shape3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = {x}, }}, }}, }},"#); + let src = comp_src(&format!( + r#"{} {} {} + M = Merge3D {{ Inputs = {{ SceneInput10 = Input {{ SourceOp = "C", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "B", Source = "Output", }}, SceneInput1 = Input {{ SourceOp = "A", Source = "Output", }}, }}, }},"#, + plane("A", 1), + plane("B", 2), + plane("C", 10), + )); + let (_, meshes, _) = collect(&src, "M"); + let xs: Vec = meshes.iter().map(|m| m.world[12]).collect(); + assert_eq!(xs, [1.0, 2.0, 10.0]); + } + + #[test] + fn every_directional_light_is_collected_with_its_own_direction_and_color() { + let src = comp_src( + r#"Front = LightDirectional { Inputs = { Intensity = Input { Value = 0.5, }, }, }, + Side = LightDirectional { Inputs = { ["Transform3DOp.Rotate.Y"] = Input { Value = 90, }, Red = Input { Value = 0, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Front", Source = "Output", }, SceneInput2 = Input { SourceOp = "Side", Source = "Output", }, }, },"#, + ); + let (_, _, lights) = collect(&src, "M"); + assert_eq!(lights.dirs.len(), 2); + assert_eq!(lights.dirs[0].color, [0.5, 0.5, 0.5]); + assert!((lights.dirs[0].to_light[2] - 1.0).abs() < 1e-5); + assert_eq!(lights.dirs[1].color, [0.0, 1.0, 1.0]); + assert!((lights.dirs[1].to_light[0] - 1.0).abs() < 1e-5, "{:?}", lights.dirs[1].to_light); + } + + #[test] + fn mat4_inverse_handles_scaled_camera_parents() { + let src = comp_src( + r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 30, }, }, }, + Rig = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 2, }, ["Transform3DOp.Scale.Y"] = Input { Value = 0.5, }, ["Transform3DOp.Translate.X"] = Input { Value = 3, }, SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#, + ); + let (cams, ..) = collect(&src, "Rig"); + let world = cams[0].world; + let near_identity = |m: Mat4| m.iter().zip(mat4_identity()).all(|(a, b)| (a - b).abs() < 1e-5); + assert!(near_identity(mat4_mul(mat4_inverse(world), world))); + assert!(!near_identity(mat4_mul(mat4_inverse_rigid(world), world)), "rigid inverse is wrong under scale"); + } + + #[test] + fn mat4_inverse_of_singular_matrix_is_finite() { + let inv = mat4_inverse(mat4_scale(0.0, 1.0, 1.0)); + assert!(inv.iter().all(|v| v.is_finite())); + assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0)); + } } diff --git a/crates/engine/src/scene3d/fbx.rs b/crates/engine/src/scene3d/fbx.rs index 55938d10fef1abf21973fa497cbc392709bc996b..3611f982207e59b8684606d254327129334917af 100644 --- a/crates/engine/src/scene3d/fbx.rs +++ b/crates/engine/src/scene3d/fbx.rs @@ -6,12 +6,13 @@ //! - Binary FBX (`Kaydara FBX Binary \0`, v7100–v7700+, raw & zlib-compressed arrays) //! //! Recomputes smooth vertex normals when absent, applies `ScaleFileUnitsBy`, -//! caches loaded meshes by `(path, obj_name, scale)`, and falls back gracefully -//! to a unit bounding-box placeholder mesh if the file is missing or unreadable. +//! caches loaded meshes by `(path, mtime, obj_name, scale)`, and falls back gracefully +//! to a unit bounding-box placeholder mesh (never cached) if the file is missing or unreadable. use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, OnceLock}; +use std::time::SystemTime; use super::shader::Vertex3D; @@ -21,11 +22,12 @@ const MAX_FBX_DEPTH: usize = 32; const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024; const MAX_TRIANGLES: usize = 500_000; -type MeshCacheKey = (String, String, u32); +type MeshCacheKey = (PathBuf, Option, String, u32); static MESH_CACHE: OnceLock>>>> = OnceLock::new(); /// Loads a `.fbx` or `.obj` mesh (cached), applying `scale_units` (`ScaleFileUnitsBy`). -/// Falls back to a unit bounding-box placeholder mesh if the file is missing or invalid. +/// Editing the file on disk invalidates its entry. A unit bounding-box placeholder is returned, +/// but not cached, if the file is missing or invalid. pub(super) fn load_mesh_cached( raw_path: &str, comp_path: Option<&Path>, @@ -38,12 +40,10 @@ pub(super) fn load_mesh_cached( 1.0 }; let resolved = resolve_import_path(raw_path, comp_path); - let cache_path = resolved - .as_ref() - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_else(|| raw_path.to_string()); + let mtime = resolved.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok()); let key = ( - cache_path, + resolved.clone().unwrap_or_else(|| PathBuf::from(raw_path)), + mtime, obj_name.unwrap_or("").to_string(), scale.to_bits(), ); @@ -61,8 +61,12 @@ pub(super) fn load_mesh_cached( let bytes = std::fs::read(&p).ok()?; parse_mesh_bytes(&bytes, ext.as_deref(), obj_name, scale) }) - .filter(|v| !v.is_empty()) - .unwrap_or_else(unit_box_placeholder); + .filter(|v| !v.is_empty()); + let Some(loaded) = loaded else { + // Shared so a missing file keeps a stable identity for downstream cache keys. + static PLACEHOLDER: OnceLock>> = OnceLock::new(); + return Arc::clone(PLACEHOLDER.get_or_init(|| Arc::new(unit_box_placeholder()))); + }; let arc = Arc::new(loaded); if let Ok(mut guard) = cache.lock() { @@ -1508,8 +1512,35 @@ Objects: { } #[test] - fn test_missing_file_fallback_unit_box() { - let mesh = load_mesh_cached("/nonexistent/path/to/missing_model.fbx", None, None, 1.0); + fn test_missing_file_fallback_unit_box_is_not_cached() { + let path = "/nonexistent/path/to/missing_model.fbx"; + let mesh = load_mesh_cached(path, None, None, 1.0); assert_eq!(mesh.len(), 36, "fallback placeholder should be a 12-triangle unit box"); + let cache = MESH_CACHE.get().unwrap().lock().unwrap(); + assert!(!cache.keys().any(|k| k.0 == Path::new(path))); + } + + #[test] + fn test_editing_file_on_disk_invalidates_cache() { + let dir = std::env::temp_dir().join(format!("fission-fbx-mtime-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("tri.obj"); + let path = file.to_str().unwrap(); + let write = |body: &str, mtime_secs: u64| { + std::fs::write(&file, body).unwrap(); + let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(mtime_secs); + std::fs::File::options().write(true).open(&file).unwrap().set_modified(t).unwrap(); + }; + let tri = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n"; + let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n"; + + write(tri, 1_000_000); + let first = load_mesh_cached(path, None, None, 1.0); + assert_eq!(first.len(), 3); + assert!(Arc::ptr_eq(&first, &load_mesh_cached(path, None, None, 1.0)), "unchanged file hits the cache"); + + write(quad, 2_000_000); + assert_eq!(load_mesh_cached(path, None, None, 1.0).len(), 6, "edited file reloads"); + std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index 0fed81feb15884e4bd4be6404a1b8fed8e549d8b..70ac908ccd588ff1d854515d895f2ceca16af4f9 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -12,19 +12,20 @@ mod math; mod mesh; mod shader; -pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d}; +pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; pub use math::{ mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, }; pub use shader::Vertex3D; -use std::sync::Arc; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; use crate::cache::CachedTexture; use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; use model::NodeId; -use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D}; +use shader::{MeshUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D}; pub type Mat4 = [f32; 16]; // Column-major 4x4 @@ -34,6 +35,52 @@ pub struct Scene3DRenderer { /// faces show the inside of closed meshes. pipelines: [[wgpu::RenderPipeline; 2]; 2], sampler: wgpu::Sampler, + meshes: Mutex>>, +} + +/// Most meshes kept resident on the GPU across frames. +const MESH_CACHE_CAP: usize = 64; + +/// `(base shape hash, image-plane aspect bits, wireframe)`; everything `build_shape_mesh` and the +/// edge conversion read, so animated transforms and materials reuse one upload. +type MeshKey = (u64, u32, bool); + +#[derive(Clone)] +struct GpuMesh { + vbuf: wgpu::Buffer, + ibuf: wgpu::Buffer, + idx_count: u32, + /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address. + _shape: ShapeKind, +} + +/// Bounded map evicting the least recently used entry. +struct Lru { + cap: usize, + tick: u64, + entries: HashMap, +} + +impl Lru { + fn new(cap: usize) -> Self { + Self { cap, tick: 0, entries: HashMap::new() } + } + + fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V { + self.tick += 1; + if let Some((used, v)) = self.entries.get_mut(&key) { + *used = self.tick; + return v.clone(); + } + if self.entries.len() >= self.cap { + if let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) { + self.entries.remove(&oldest); + } + } + let v = make(); + self.entries.insert(key, (self.tick, v.clone())); + v + } } #[derive(Clone)] @@ -287,29 +334,21 @@ pub struct SpotLight { pub decay_type: f32, } -#[derive(Clone, Debug)] +#[derive(Clone, Copy, Debug)] +pub struct DirLight { + pub to_light: [f32; 3], + pub color: [f32; 3], +} + +#[derive(Clone, Debug, Default)] pub struct SceneLights { pub ambient: [f32; 3], - pub dir_to_light: [f32; 3], - pub dir_color: [f32; 3], - pub has_dir: bool, + /// Only the first `MAX_DIR_LIGHTS` reach the shader. + pub dirs: Vec, pub points: Vec, pub spots: Vec, } -impl Default for SceneLights { - fn default() -> Self { - Self { - ambient: [0.0, 0.0, 0.0], - dir_to_light: [0.0, 0.0, 1.0], - dir_color: [0.0, 0.0, 0.0], - has_dir: false, - points: Vec::new(), - spots: Vec::new(), - } - } -} - pub struct DrawMesh { pub world: Mat4, pub shape: ShapeKind, @@ -323,11 +362,24 @@ pub struct DrawMesh { pub displace: Option, } +fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey { + use std::hash::{DefaultHasher, Hasher}; + let mut h = DefaultHasher::new(); + base_shape.hash_into(&mut h); + let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 }; + (h.finish(), aspect_bits, wireframe) +} + impl Scene3DRenderer { pub fn new(device: &wgpu::Device) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("scene3d-shader"), - source: wgpu::ShaderSource::Wgsl(SHADER_3D.replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()).into()), + source: wgpu::ShaderSource::Wgsl( + SHADER_3D + .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) + .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) + .into(), + ), }); let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("scene3d-bgl"), @@ -423,7 +475,7 @@ impl Scene3DRenderer { mipmap_filter: wgpu::MipmapFilterMode::Linear, ..Default::default() }); - Self { bgl, pipelines, sampler } + Self { bgl, pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)) } } #[allow(clippy::too_many_arguments)] @@ -489,32 +541,45 @@ impl Scene3DRenderer { .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4)) .unwrap_or(16.0 / 9.0); let (base_shape, fx) = m.shape.split_fx(); - let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect); - if indices.is_empty() { + let upload = || { + let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect); + if indices.is_empty() { + return None; + } + if let Some(disp) = &m.displace { + apply_heightmap_displace(&mut verts, &indices, disp); + } + if fx.wireframe { + indices = triangle_edges(&indices); + } + let vbytes = bytemuck::cast_slice(&verts); + let ibytes = bytemuck::cast_slice(&indices); + let vbuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-vb"), + size: vbytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&vbuf, 0, vbytes); + let ibuf = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("scene3d-ib"), + size: ibytes.len() as u64, + usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + queue.write_buffer(&ibuf, 0, ibytes); + Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, _shape: base_shape.clone() }) + }; + // Heightmap contents are not part of the key, so displaced meshes are never cached. + let gpu_mesh = if m.displace.is_some() { + upload() + } else { + let key = mesh_key(base_shape, aspect, fx.wireframe); + self.meshes.lock().unwrap().get_or_insert_with(key, upload) + }; + let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else { continue; - } - if let Some(disp) = &m.displace { - apply_heightmap_displace(&mut verts, &indices, disp); - } - if fx.wireframe { - indices = triangle_edges(&indices); - } - let vbytes = bytemuck::cast_slice(&verts); - let ibytes = bytemuck::cast_slice(&indices); - let vbuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("scene3d-vb"), - size: vbytes.len() as u64, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&vbuf, 0, vbytes); - let ibuf = device.create_buffer(&wgpu::BufferDescriptor { - label: Some("scene3d-ib"), - size: ibytes.len() as u64, - usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - queue.write_buffer(&ibuf, 0, ibytes); + }; let mvp = mat4_mul(view_proj, m.world); let dod = if let Some(t) = &m.tex { @@ -542,6 +607,13 @@ impl Scene3DRenderer { spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer]; spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type]; } + let mut dir_to_light = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; + let mut dir_color = [[0.0_f32; 4]; MAX_DIR_LIGHTS]; + let n_dir = lights.dirs.len().min(MAX_DIR_LIGHTS); + for (di, dl) in lights.dirs.iter().take(MAX_DIR_LIGHTS).enumerate() { + dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0]; + dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; + } let uni = MeshUniform { mvp, model: m.world, @@ -560,15 +632,10 @@ impl Scene3DRenderer { m.specular_exponent, ], ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0], - dir_to_light: [ - lights.dir_to_light[0], - lights.dir_to_light[1], - lights.dir_to_light[2], - if lights.has_dir { 1.0 } else { 0.0 }, - ], - dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0], + dir_to_light, + dir_color, cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], - light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0], + light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, 0.0], uv_xform: fx.uv.m, uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0], mat_fx: [fx.bump_scale, fx.bump_mode as f32, if fx.bump_only { 1.0 } else { 0.0 }, fx.spec_model as u32 as f32], @@ -601,7 +668,7 @@ impl Scene3DRenderer { bg, vbuf, ibuf, - idx_count: indices.len() as u32, + idx_count, }); } @@ -726,6 +793,103 @@ mod tests { assert!((alpha - 191).abs() <= 3, "alpha {alpha}"); } + #[test] + fn normals_stay_perpendicular_under_non_uniform_scale() { + // Plane rotated 45 degrees about Y under a [4, 1, 1] scale: the true normal is + // (1/4, 0, 1) normalized, so a +Z light gives cos = 0.970; `model * n` would give 0.243. + let scene = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 45, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, }, + S = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 4, }, SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, }, + L = LightDirectional { }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "L", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#; + let Some(px) = render(true, scene) else { return }; + let expected = 255.0 / (1.0 + 1.0 / 16.0_f32).sqrt(); + let c = center(&px); + assert!((c[0] as f32 - expected).abs() <= 3.0, "{c:?} vs {expected}"); + } + + #[test] + fn up_to_four_directional_lights_accumulate() { + // Five 0.1 lights facing the plane: the first four reach the shader, so 0.4 * 255. + let lights: String = (1..=5) + .map(|i| format!(r#"L{i} = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 0.1, }}, }}, }},"#)) + .collect(); + let ports: String = (1..=5).map(|i| format!(r#"SceneInput{} = Input {{ SourceOp = "L{i}", Source = "Output", }},"#, i + 1)).collect(); + let scene = format!( + r#"{PLANE} {lights} + M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, {ports} SceneInput7 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"# + ); + let Some(px) = render(true, &scene) else { return }; + let c = center(&px); + assert!((c[0] as f32 - 102.0).abs() <= 3.0, "{c:?}"); + } + + #[test] + fn gpu_meshes_are_reused_across_frames_and_split_by_wireframe() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return }; + let renderer = Scene3DRenderer::new(&device); + let target = || { + CachedTexture::from_texture( + device.create_texture(&wgpu::TextureDescriptor { + label: None, + size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT, + view_formats: &[], + }), + [8, 8], + 0, + ) + }; + let (dst, dummy) = (target(), target()); + let sphere = |x: f32, wireframe: bool| DrawMesh { + world: mat4_translate(x, 0.0, 0.0), + shape: ShapeKind::WithMaterialFx { + inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }), + fx: MaterialFx { wireframe, ..Default::default() }, + }, + tex: None, + diffuse_col: [1.0; 4], + specular_col: [1.0; 3], + specular_intensity: 0.0, + specular_exponent: 50.0, + affected_by_lights: false, + flip_normals: false, + displace: None, + }; + let frame = |meshes: &[DrawMesh]| { + let mut enc = device.create_command_encoder(&Default::default()); + let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]); + renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, meshes); + queue.submit(Some(enc.finish())); + renderer.meshes.lock().unwrap().entries.len() + }; + assert_eq!(frame(&[sphere(0.0, false)]), 1); + assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload"); + assert_eq!(frame(&[sphere(0.5, true)]), 2, "wireframe uses edge indices"); + } + + #[test] + fn lru_evicts_the_least_recently_used_entry_and_reuses_hits() { + let mut lru = Lru::new(2); + let builds = std::cell::Cell::new(0); + let get = |lru: &mut Lru, k: u8| lru.get_or_insert_with(k, || { builds.set(builds.get() + 1); k }); + get(&mut lru, 1); + get(&mut lru, 2); + get(&mut lru, 1); + get(&mut lru, 3); + assert_eq!(builds.get(), 3, "second request for key 1 is a hit"); + get(&mut lru, 1); + assert_eq!(builds.get(), 3, "key 1 was refreshed, so key 2 was evicted"); + get(&mut lru, 2); + assert_eq!(builds.get(), 4); + assert_eq!(lru.entries.len(), 2); + } + #[test] fn uv_affine_then_applies_self_first() { let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] }; diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index d71558c468ff74c44b96cff1c68b99821574010c..ffbaa1839514afe4058f44a49fb19e60b51e5146 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -4,6 +4,8 @@ use bytemuck::{Pod, Zeroable}; /// Point and spot lights each get this many shader slots. pub(super) const MAX_LIGHTS: usize = 8; +/// Directional lights get this many shader slots. +pub(super) const MAX_DIR_LIGHTS: usize = 4; #[repr(C)] #[derive(Clone, Copy, Debug, Pod, Zeroable)] @@ -28,13 +30,13 @@ pub(super) struct MeshUniform { pub(super) specular_col: [f32; 4], /// Ambient light `(r, g, b, 0)` pub(super) ambient: [f32; 4], - /// Directional light direction TO light `(dx, dy, dz, has_dir)` - pub(super) dir_to_light: [f32; 4], - /// Directional light color * intensity `(r, g, b, 0)` - pub(super) dir_color: [f32; 4], + /// Directional light directions TO light `(dx, dy, dz, 0)` + pub(super) dir_to_light: [[f32; 4]; MAX_DIR_LIGHTS], + /// Directional light colors * intensity `(r, g, b, 0)` + pub(super) dir_color: [[f32; 4]; MAX_DIR_LIGHTS], /// Camera world position `(cx, cy, cz, 0)` pub(super) cam_pos: [f32; 4], - /// `[num_point_lights, num_spot_lights, 0, 0]` + /// `[num_point_lights, num_spot_lights, num_dir_lights, 0]` pub(super) light_counts: [f32; 4], /// UV affine matrix, column-major `[m00, m10, m01, m11]` pub(super) uv_xform: [f32; 4], @@ -54,7 +56,7 @@ pub(super) struct MeshUniform { pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], } -/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation. +/// WGSL source; `MAX_LIGHTS` and `MAX_DIR_LIGHTS` are substituted with the Rust constants at pipeline creation. pub(super) const SHADER_3D: &str = r#" struct MeshUniform { mvp: mat4x4, @@ -64,8 +66,8 @@ struct MeshUniform { diffuse_col: vec4, specular_col: vec4, ambient: vec4, - dir_to_light: vec4, - dir_color: vec4, + dir_to_light: array, MAX_DIR_LIGHTS>, + dir_color: array, MAX_DIR_LIGHTS>, cam_pos: vec4, light_counts: vec4, uv_xform: vec4, @@ -97,6 +99,17 @@ struct VsOut { @location(2) world_n: vec3, }; +// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay +// perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored +// transforms pointing outward. +fn normal_matrix(m: mat4x4) -> mat3x3 { + let c0 = m[0].xyz; + let c1 = m[1].xyz; + let c2 = m[2].xyz; + let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0); + return mat3x3(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign; +} + @vertex fn vs_mesh(v: VsIn) -> VsOut { var out: VsOut; @@ -104,7 +117,7 @@ fn vs_mesh(v: VsIn) -> VsOut { out.clip = u.mvp * vec4(v.pos, 1.0); out.uv = v.uv; out.world_pos = wp.xyz; - let wn = (u.model * vec4(v.normal, 0.0)).xyz; + let wn = normal_matrix(u.model) * v.normal; let nlen = length(wn); var n_norm = select(vec3(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); if (u.flags.w > 0.5) { @@ -278,9 +291,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { let spec_int = u.flags.z; var lit = albedo * u.ambient.rgb; - if (u.dir_to_light.w > 0.5) { - let l = normalize(u.dir_to_light.xyz); - lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess); + let n_dir = i32(u.light_counts.z + 0.5); + for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { + if (i >= n_dir) { break; } + let l = normalize(u.dir_to_light[i].xyz); + lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess); } let n_pt = i32(u.light_counts.x + 0.5); -- 2.54.1