authoravatarclover caruso<git@paperclover.net>2026-11-30 20:44:22-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:54:09-08:00
log9c00057b07397a81c13f866dbc14fb0ae0d1399a
tree960700962a46e3c21a9775b778aa6faad9b5e9c6
parent9f6cd5fe8fd066b899ef73513343ff2e092bd205
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

6 files changed, 489 insertions(+), 121 deletions(-)

crates/engine/src/eval/text_3d.rs+5-3
......@@ -534,7 +534,7 @@ impl Engine {
534534 );
535535
536536 let (view, proj, cam_pos) = if let Some(cam) = cameras.first() {
537 let v = crate::scene3d::mat4_inverse_rigid(cam.world);
537 let v = crate::scene3d::mat4_inverse(cam.world);
538538 let p = crate::scene3d::mat4_perspective_wgpu(cam.vfov_rad, aspect, cam.near, cam.far);
539539 (v, p, [cam.world[12], cam.world[13], cam.world[14]])
540540 } else {
......@@ -550,8 +550,10 @@ impl Engine {
550550 hash_floats.extend_from_slice(&view_proj);
551551 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
552552 hash_floats.extend_from_slice(&lights.ambient);
553 hash_floats.extend_from_slice(&lights.dir_to_light);
554 hash_floats.extend_from_slice(&lights.dir_color);
553 for dl in &lights.dirs {
554 hash_floats.extend_from_slice(&dl.to_light);
555 hash_floats.extend_from_slice(&dl.color);
556 }
555557 for pl in &lights.points {
556558 hash_floats.extend_from_slice(&pl.pos);
557559 hash_floats.extend_from_slice(&pl.color);
crates/engine/src/optflow.rs+102-31
......@@ -7,7 +7,7 @@ use model::BitDepth;
77use std::collections::HashMap;
88use std::collections::hash_map::DefaultHasher;
99use std::hash::{Hash, Hasher};
10use std::sync::RwLock;
10use std::sync::{Mutex, RwLock};
1111
1212#[repr(C)]
1313#[derive(Clone, Copy, Pod, Zeroable)]
......@@ -449,6 +449,12 @@ fn fs_warp_flow(in: VsOut) -> @location(0) vec4<f32> {
449449}
450450"#;
451451
452/// Cached flow fields kept per `OpticalFlowPipelines`; one entry is a single frame pair.
453const FLOW_CACHE_CAP: usize = 4;
454
455/// `(content_hash_a, content_hash_b, full-res size)`.
456type FlowKey = (u64, u64, [u32; 2]);
457
452458/// Self-contained `wgpu` pipelines for GPU optical flow and motion-compensated frame interpolation.
453459pub struct OpticalFlowPipelines {
454460 shader: wgpu::ShaderModule,
......@@ -462,6 +468,8 @@ pub struct OpticalFlowPipelines {
462468 flow_smooth: wgpu::RenderPipeline,
463469 blend_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
464470 warp_pipelines: RwLock<HashMap<wgpu::TextureFormat, wgpu::RenderPipeline>>,
471 /// Half-resolution flow fields, least recently used first.
472 flow_cache: Mutex<Vec<(FlowKey, wgpu::TextureView)>>,
465473}
466474
467475impl OpticalFlowPipelines {
......@@ -547,6 +555,7 @@ impl OpticalFlowPipelines {
547555 flow_smooth,
548556 blend_pipelines: RwLock::new(HashMap::new()),
549557 warp_pipelines: RwLock::new(HashMap::new()),
558 flow_cache: Mutex::new(Vec::new()),
550559 }
551560 }
552561
......@@ -694,11 +703,58 @@ impl OpticalFlowPipelines {
694703 let key = hash_interp(frame_a.content_hash, frame_b.content_hash, alpha, 2, target_format);
695704 let dst = alloc_output_texture(device, frame_a, target_format, key);
696705
697 // Compute 4-level pyramid dimensions: full, 1/2, 1/4, 1/8
698706 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];
699 let s1 = [s0[0].div_ceil(2).max(1), s0[1].div_ceil(2).max(1)];
700 let s2 = [s1[0].div_ceil(2).max(1), s1[1].div_ceil(2).max(1)];
701 let s3 = [s2[0].div_ceil(2).max(1), s2[1].div_ceil(2).max(1)];
707 let s1 = half_size(s0);
708 let flow_key = (frame_a.content_hash, frame_b.content_hash, s0);
709 let cached = {
710 let mut cache = self.flow_cache.lock().unwrap();
711 cache.iter().position(|(k, _)| *k == flow_key).map(|i| {
712 let entry = cache.remove(i);
713 let view = entry.1.clone();
714 cache.push(entry);
715 view
716 })
717 };
718 let flow1_view = cached.unwrap_or_else(|| {
719 let view = self.compute_flow_field(device, queue, enc, frame_a, frame_b);
720 let mut cache = self.flow_cache.lock().unwrap();
721 if cache.len() >= FLOW_CACHE_CAP {
722 cache.remove(0);
723 }
724 cache.push((flow_key, view.clone()));
725 view
726 });
727
728 // Full-resolution bidirectional occlusion-aware warp & blend
729 let scale_1_to_0 = [
730 s0[0] as f32 / s1[0] as f32,
731 s0[1] as f32 / s1[1] as f32,
732 alpha.clamp(0.0, 1.0),
733 0.0,
734 ];
735 let guard = self.warp_pipelines.read().unwrap();
736 let pipe = guard.get(&target_format).unwrap();
737 self.run_pass(
738 device, queue, enc, pipe, "optflow-warp",
739 &frame_a.view, &frame_b.view, &flow1_view, &dst.view, s0, scale_1_to_0,
740 );
741 dst
742 }
743
744 /// Encodes the 4-level (full, 1/2, 1/4, 1/8) coarse-to-fine flow estimate and returns the
745 /// half-resolution flow field.
746 fn compute_flow_field(
747 &self,
748 device: &wgpu::Device,
749 queue: &wgpu::Queue,
750 enc: &mut wgpu::CommandEncoder,
751 frame_a: &CachedTexture,
752 frame_b: &CachedTexture,
753 ) -> wgpu::TextureView {
754 let s0 = [frame_a.size[0].max(1), frame_a.size[1].max(1)];
755 let s1 = half_size(s0);
756 let s2 = half_size(s1);
757 let s3 = half_size(s2);
702758
703759 // 1. Build (luma, R-G, B-Y, alpha) feature pyramids for A and B
704760 let (fa0_tex, fa0_view) = alloc_f16_tex(device, s0, "optflow-fa0");
......@@ -784,41 +840,20 @@ impl OpticalFlowPipelines {
784840 &fa1_view, &fb1_view, &flow1_raw_view, &flow1_view, s1, [0.0; 4],
785841 );
786842
787 // 3. Full-resolution bidirectional occlusion-aware warp & blend
788 let scale_1_to_0 = [
789 s0[0] as f32 / s1[0] as f32,
790 s0[1] as f32 / s1[1] as f32,
791 alpha.clamp(0.0, 1.0),
792 0.0,
793 ];
794 {
795 let guard = self.warp_pipelines.read().unwrap();
796 let pipe = guard.get(&target_format).unwrap();
797 self.run_pass(
798 device,
799 queue,
800 enc,
801 pipe,
802 "optflow-warp",
803 &frame_a.view,
804 &frame_b.view,
805 &flow1_view,
806 &dst.view,
807 s0,
808 scale_1_to_0,
809 );
810 }
811
812843 // Keep temporary textures alive until all passes are encoded into `enc`.
813844 drop((
814845 fa0_tex, fb0_tex, fa1_tex, fb1_tex, fa2_tex, fb2_tex, fa3_tex, fb3_tex,
815846 flow3_raw_tex, flow3_tex, flow2_raw_tex, flow2_tex, flow1_raw_tex, flow1_tex,
816847 ));
817848
818 dst
849 flow1_view
819850 }
820851}
821852
853fn half_size(s: [u32; 2]) -> [u32; 2] {
854 [s[0].div_ceil(2).max(1), s[1].div_ceil(2).max(1)]
855}
856
822857fn create_fullscreen_pipeline(
823858 device: &wgpu::Device,
824859 shader: &wgpu::ShaderModule,
......@@ -1209,6 +1244,42 @@ mod tests {
12091244 );
12101245 }
12111246
1247 #[test]
1248 fn test_flow_field_is_cached_per_frame_pair_and_bounded() {
1249 let (device, queue) = create_headless_device();
1250 let cached = OpticalFlowPipelines::new(&device);
1251 let fresh = OpticalFlowPipelines::new(&device);
1252
1253 let (w, h) = (128u32, 72u32);
1254 let frame = |i: i32, hash: u64| {
1255 upload_rgba8(&device, &queue, w, h, &render_box_scene(w, h, 20 + 8 * i, 20), hash)
1256 };
1257 let (tex_a, tex_b) = (frame(0, 1), frame(1, 2));
1258 let fmt = wgpu::TextureFormat::Rgba8Unorm;
1259 let interp = |p: &OpticalFlowPipelines, a: &CachedTexture, b: &CachedTexture, alpha: f32| {
1260 let mut enc = device.create_command_encoder(&Default::default());
1261 let out = p.interpolate_flow(&device, &queue, &mut enc, a, b, alpha, fmt);
1262 queue.submit(Some(enc.finish()));
1263 readback_bytes(&device, &queue, &out, 4)
1264 };
1265
1266 let first = interp(&cached, &tex_a, &tex_b, 0.25);
1267 let field = cached.flow_cache.lock().unwrap()[0].1.clone();
1268 let second = interp(&cached, &tex_a, &tex_b, 0.75);
1269 {
1270 let cache = cached.flow_cache.lock().unwrap();
1271 assert_eq!(cache.len(), 1, "second alpha reuses the pair's flow field");
1272 assert!(cache[0].1 == field, "second alpha must hit the cached field texture");
1273 }
1274 assert_ne!(first, second, "alpha still drives the warp pass");
1275 assert_eq!(second, interp(&fresh, &tex_a, &tex_b, 0.75), "cached field matches a fresh computation");
1276
1277 for i in 2..8 {
1278 interp(&cached, &frame(i, 10 + i as u64), &frame(i + 1, 20 + i as u64), 0.5);
1279 }
1280 assert_eq!(cached.flow_cache.lock().unwrap().len(), FLOW_CACHE_CAP);
1281 }
1282
12121283 #[test]
12131284 fn test_optflow_mismatched_sizes_and_rgba32float() {
12141285 let (device, queue) = create_headless_device();
crates/engine/src/scene3d/collect.rs+91-6
......@@ -2,10 +2,10 @@
22
33use super::fbx::load_mesh_cached;
44use super::math::{
5 mat4_identity, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
5 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
66};
77use super::{
8 CameraInstance, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
8 CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
99 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,
1010};
1111use model::{Comp, ExprEngine, Node, NodeId};
......@@ -126,7 +126,8 @@ fn collect_scene_inner(
126126 .keys()
127127 .filter(|k| k.starts_with("SceneInput"))
128128 .collect();
129 input_names.sort();
129 // `SceneInput2` precedes `SceneInput10`.
130 input_names.sort_by_cached_key(|k| (k["SceneInput".len()..].parse::<u32>().unwrap_or(0), k.to_string()));
130131 for in_name in input_names {
131132 if let Some(src_id) = node.connected_node(in_name).and_then(|s| comp.find_node(s)) {
132133 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(
270271 let dy = world[9];
271272 let dz = world[10];
272273 let len = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-5);
273 lights.dir_to_light = [dx / len, dy / len, dz / len];
274 lights.dir_color = color;
275 lights.has_dir = true;
274 lights.dirs.push(DirLight { to_light: [dx / len, dy / len, dz / len], color });
276275 }
277276 "LightPoint" => {
278277 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)
729728 mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)))
730729}
731730
731/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to
732/// `mat4_inverse_rigid` so a degenerate camera scale never yields NaNs.
733pub fn mat4_inverse(m: Mat4) -> Mat4 {
734 let mut a = [[0.0_f64; 8]; 4];
735 for (r, row) in a.iter_mut().enumerate() {
736 for c in 0..4 {
737 row[c] = f64::from(m[c * 4 + r]);
738 }
739 row[4 + r] = 1.0;
740 }
741 for col in 0..4 {
742 let pivot = (col..4).max_by(|&i, &j| a[i][col].abs().total_cmp(&a[j][col].abs())).unwrap_or(col);
743 let invertible = a[pivot][col].abs() > 1e-12;
744 if !invertible {
745 return mat4_inverse_rigid(m);
746 }
747 a.swap(col, pivot);
748 let p = a[col][col];
749 a[col].iter_mut().for_each(|x| *x /= p);
750 let pivot_row = a[col];
751 for (r, row) in a.iter_mut().enumerate() {
752 if r != col {
753 let f = row[col];
754 row.iter_mut().zip(pivot_row).for_each(|(x, pv)| *x -= f * pv);
755 }
756 }
757 }
758 let mut out = [0.0_f32; 16];
759 for (r, row) in a.iter().enumerate() {
760 for c in 0..4 {
761 out[c * 4 + r] = row[4 + c] as f32;
762 }
763 }
764 out
765}
766
732767pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {
733768 let tx = comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr) as f32;
734769 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
......@@ -1183,4 +1218,54 @@ mod tests {
11831218 assert_eq!(meshes.len(), 1);
11841219 assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::Plane { .. }));
11851220 }
1221
1222 #[test]
1223 fn scene_inputs_are_visited_in_numeric_order() {
1224 let plane = |name: &str, x: u32| format!(r#"{name} = Shape3D {{ Inputs = {{ ["Transform3DOp.Translate.X"] = Input {{ Value = {x}, }}, }}, }},"#);
1225 let src = comp_src(&format!(
1226 r#"{} {} {}
1227 M = Merge3D {{ Inputs = {{ SceneInput10 = Input {{ SourceOp = "C", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "B", Source = "Output", }}, SceneInput1 = Input {{ SourceOp = "A", Source = "Output", }}, }}, }},"#,
1228 plane("A", 1),
1229 plane("B", 2),
1230 plane("C", 10),
1231 ));
1232 let (_, meshes, _) = collect(&src, "M");
1233 let xs: Vec<f32> = meshes.iter().map(|m| m.world[12]).collect();
1234 assert_eq!(xs, [1.0, 2.0, 10.0]);
1235 }
1236
1237 #[test]
1238 fn every_directional_light_is_collected_with_its_own_direction_and_color() {
1239 let src = comp_src(
1240 r#"Front = LightDirectional { Inputs = { Intensity = Input { Value = 0.5, }, }, },
1241 Side = LightDirectional { Inputs = { ["Transform3DOp.Rotate.Y"] = Input { Value = 90, }, Red = Input { Value = 0, }, }, },
1242 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Front", Source = "Output", }, SceneInput2 = Input { SourceOp = "Side", Source = "Output", }, }, },"#,
1243 );
1244 let (_, _, lights) = collect(&src, "M");
1245 assert_eq!(lights.dirs.len(), 2);
1246 assert_eq!(lights.dirs[0].color, [0.5, 0.5, 0.5]);
1247 assert!((lights.dirs[0].to_light[2] - 1.0).abs() < 1e-5);
1248 assert_eq!(lights.dirs[1].color, [0.0, 1.0, 1.0]);
1249 assert!((lights.dirs[1].to_light[0] - 1.0).abs() < 1e-5, "{:?}", lights.dirs[1].to_light);
1250 }
1251
1252 #[test]
1253 fn mat4_inverse_handles_scaled_camera_parents() {
1254 let src = comp_src(
1255 r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.Z"] = Input { Value = 4, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 30, }, }, },
1256 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", }, }, },"#,
1257 );
1258 let (cams, ..) = collect(&src, "Rig");
1259 let world = cams[0].world;
1260 let near_identity = |m: Mat4| m.iter().zip(mat4_identity()).all(|(a, b)| (a - b).abs() < 1e-5);
1261 assert!(near_identity(mat4_mul(mat4_inverse(world), world)));
1262 assert!(!near_identity(mat4_mul(mat4_inverse_rigid(world), world)), "rigid inverse is wrong under scale");
1263 }
1264
1265 #[test]
1266 fn mat4_inverse_of_singular_matrix_is_finite() {
1267 let inv = mat4_inverse(mat4_scale(0.0, 1.0, 1.0));
1268 assert!(inv.iter().all(|v| v.is_finite()));
1269 assert_eq!(mat4_inverse(mat4_translate(1.0, 2.0, 3.0)), mat4_translate(-1.0, -2.0, -3.0));
1270 }
11861271}
crates/engine/src/scene3d/fbx.rs+44-13
......@@ -6,12 +6,13 @@
66//! - Binary FBX (`Kaydara FBX Binary \0`, v7100–v7700+, raw & zlib-compressed arrays)
77//!
88//! Recomputes smooth vertex normals when absent, applies `ScaleFileUnitsBy`,
9//! caches loaded meshes by `(path, obj_name, scale)`, and falls back gracefully
10//! to a unit bounding-box placeholder mesh if the file is missing or unreadable.
9//! caches loaded meshes by `(path, mtime, obj_name, scale)`, and falls back gracefully
10//! to a unit bounding-box placeholder mesh (never cached) if the file is missing or unreadable.
1111
1212use std::collections::HashMap;
1313use std::path::{Path, PathBuf};
1414use std::sync::{Arc, Mutex, OnceLock};
15use std::time::SystemTime;
1516
1617use super::shader::Vertex3D;
1718
......@@ -21,11 +22,12 @@ const MAX_FBX_DEPTH: usize = 32;
2122const MAX_DECOMPRESS_BYTES: usize = 64 * 1024 * 1024;
2223const MAX_TRIANGLES: usize = 500_000;
2324
24type MeshCacheKey = (String, String, u32);
25type MeshCacheKey = (PathBuf, Option<SystemTime>, String, u32);
2526static MESH_CACHE: OnceLock<Mutex<HashMap<MeshCacheKey, Arc<Vec<Vertex3D>>>>> = OnceLock::new();
2627
2728/// Loads a `.fbx` or `.obj` mesh (cached), applying `scale_units` (`ScaleFileUnitsBy`).
28/// Falls back to a unit bounding-box placeholder mesh if the file is missing or invalid.
29/// Editing the file on disk invalidates its entry. A unit bounding-box placeholder is returned,
30/// but not cached, if the file is missing or invalid.
2931pub(super) fn load_mesh_cached(
3032 raw_path: &str,
3133 comp_path: Option<&Path>,
......@@ -38,12 +40,10 @@ pub(super) fn load_mesh_cached(
3840 1.0
3941 };
4042 let resolved = resolve_import_path(raw_path, comp_path);
41 let cache_path = resolved
42 .as_ref()
43 .map(|p| p.to_string_lossy().into_owned())
44 .unwrap_or_else(|| raw_path.to_string());
43 let mtime = resolved.as_ref().and_then(|p| std::fs::metadata(p).and_then(|m| m.modified()).ok());
4544 let key = (
46 cache_path,
45 resolved.clone().unwrap_or_else(|| PathBuf::from(raw_path)),
46 mtime,
4747 obj_name.unwrap_or("").to_string(),
4848 scale.to_bits(),
4949 );
......@@ -61,8 +61,12 @@ pub(super) fn load_mesh_cached(
6161 let bytes = std::fs::read(&p).ok()?;
6262 parse_mesh_bytes(&bytes, ext.as_deref(), obj_name, scale)
6363 })
64 .filter(|v| !v.is_empty())
65 .unwrap_or_else(unit_box_placeholder);
64 .filter(|v| !v.is_empty());
65 let Some(loaded) = loaded else {
66 // Shared so a missing file keeps a stable identity for downstream cache keys.
67 static PLACEHOLDER: OnceLock<Arc<Vec<Vertex3D>>> = OnceLock::new();
68 return Arc::clone(PLACEHOLDER.get_or_init(|| Arc::new(unit_box_placeholder())));
69 };
6670
6771 let arc = Arc::new(loaded);
6872 if let Ok(mut guard) = cache.lock() {
......@@ -1508,8 +1512,35 @@ Objects: {
15081512 }
15091513
15101514 #[test]
1511 fn test_missing_file_fallback_unit_box() {
1512 let mesh = load_mesh_cached("/nonexistent/path/to/missing_model.fbx", None, None, 1.0);
1515 fn test_missing_file_fallback_unit_box_is_not_cached() {
1516 let path = "/nonexistent/path/to/missing_model.fbx";
1517 let mesh = load_mesh_cached(path, None, None, 1.0);
15131518 assert_eq!(mesh.len(), 36, "fallback placeholder should be a 12-triangle unit box");
1519 let cache = MESH_CACHE.get().unwrap().lock().unwrap();
1520 assert!(!cache.keys().any(|k| k.0 == Path::new(path)));
1521 }
1522
1523 #[test]
1524 fn test_editing_file_on_disk_invalidates_cache() {
1525 let dir = std::env::temp_dir().join(format!("fission-fbx-mtime-{}", std::process::id()));
1526 std::fs::create_dir_all(&dir).unwrap();
1527 let file = dir.join("tri.obj");
1528 let path = file.to_str().unwrap();
1529 let write = |body: &str, mtime_secs: u64| {
1530 std::fs::write(&file, body).unwrap();
1531 let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(mtime_secs);
1532 std::fs::File::options().write(true).open(&file).unwrap().set_modified(t).unwrap();
1533 };
1534 let tri = "v 0 0 0\nv 1 0 0\nv 0 1 0\nf 1 2 3\n";
1535 let quad = "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nf 1 2 3 4\n";
1536
1537 write(tri, 1_000_000);
1538 let first = load_mesh_cached(path, None, None, 1.0);
1539 assert_eq!(first.len(), 3);
1540 assert!(Arc::ptr_eq(&first, &load_mesh_cached(path, None, None, 1.0)), "unchanged file hits the cache");
1541
1542 write(quad, 2_000_000);
1543 assert_eq!(load_mesh_cached(path, None, None, 1.0).len(), 6, "edited file reloads");
1544 std::fs::remove_dir_all(&dir).unwrap();
15141545 }
15151546}
crates/engine/src/scene3d/mod.rs+220-56
......@@ -12,19 +12,20 @@ mod math;
1212mod mesh;
1313mod shader;
1414
15pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d};
15pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse};
1616pub use math::{
1717 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_perspective_wgpu, mat4_rot_x, mat4_rot_y,
1818 mat4_rot_z, mat4_scale, mat4_translate,
1919};
2020pub use shader::Vertex3D;
2121
22use std::sync::Arc;
22use std::collections::HashMap;
23use std::sync::{Arc, Mutex};
2324
2425use crate::cache::CachedTexture;
2526use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges};
2627use model::NodeId;
27use shader::{MeshUniform, MAX_LIGHTS, SHADER_3D};
28use shader::{MeshUniform, MAX_DIR_LIGHTS, MAX_LIGHTS, SHADER_3D};
2829
2930pub type Mat4 = [f32; 16]; // Column-major 4x4
3031
......@@ -34,6 +35,52 @@ pub struct Scene3DRenderer {
3435 /// faces show the inside of closed meshes.
3536 pipelines: [[wgpu::RenderPipeline; 2]; 2],
3637 sampler: wgpu::Sampler,
38 meshes: Mutex<Lru<MeshKey, Option<GpuMesh>>>,
39}
40
41/// Most meshes kept resident on the GPU across frames.
42const MESH_CACHE_CAP: usize = 64;
43
44/// `(base shape hash, image-plane aspect bits, wireframe)`; everything `build_shape_mesh` and the
45/// edge conversion read, so animated transforms and materials reuse one upload.
46type MeshKey = (u64, u32, bool);
47
48#[derive(Clone)]
49struct GpuMesh {
50 vbuf: wgpu::Buffer,
51 ibuf: wgpu::Buffer,
52 idx_count: u32,
53 /// Keeps a `CustomMesh` allocation alive: `ShapeKind::hash_into` hashes its address.
54 _shape: ShapeKind,
55}
56
57/// Bounded map evicting the least recently used entry.
58struct Lru<K, V> {
59 cap: usize,
60 tick: u64,
61 entries: HashMap<K, (u64, V)>,
62}
63
64impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
65 fn new(cap: usize) -> Self {
66 Self { cap, tick: 0, entries: HashMap::new() }
67 }
68
69 fn get_or_insert_with(&mut self, key: K, make: impl FnOnce() -> V) -> V {
70 self.tick += 1;
71 if let Some((used, v)) = self.entries.get_mut(&key) {
72 *used = self.tick;
73 return v.clone();
74 }
75 if self.entries.len() >= self.cap {
76 if let Some(oldest) = self.entries.iter().min_by_key(|(_, (used, _))| *used).map(|(k, _)| *k) {
77 self.entries.remove(&oldest);
78 }
79 }
80 let v = make();
81 self.entries.insert(key, (self.tick, v.clone()));
82 v
83 }
3784}
3885
3986#[derive(Clone)]
......@@ -287,29 +334,21 @@ pub struct SpotLight {
287334 pub decay_type: f32,
288335}
289336
290#[derive(Clone, Debug)]
337#[derive(Clone, Copy, Debug)]
338pub struct DirLight {
339 pub to_light: [f32; 3],
340 pub color: [f32; 3],
341}
342
343#[derive(Clone, Debug, Default)]
291344pub struct SceneLights {
292345 pub ambient: [f32; 3],
293 pub dir_to_light: [f32; 3],
294 pub dir_color: [f32; 3],
295 pub has_dir: bool,
346 /// Only the first `MAX_DIR_LIGHTS` reach the shader.
347 pub dirs: Vec<DirLight>,
296348 pub points: Vec<PointLight>,
297349 pub spots: Vec<SpotLight>,
298350}
299351
300impl Default for SceneLights {
301 fn default() -> Self {
302 Self {
303 ambient: [0.0, 0.0, 0.0],
304 dir_to_light: [0.0, 0.0, 1.0],
305 dir_color: [0.0, 0.0, 0.0],
306 has_dir: false,
307 points: Vec::new(),
308 spots: Vec::new(),
309 }
310 }
311}
312
313352pub struct DrawMesh {
314353 pub world: Mat4,
315354 pub shape: ShapeKind,
......@@ -323,11 +362,24 @@ pub struct DrawMesh {
323362 pub displace: Option<DisplaceHeightmap>,
324363}
325364
365fn mesh_key(base_shape: &ShapeKind, aspect: f32, wireframe: bool) -> MeshKey {
366 use std::hash::{DefaultHasher, Hasher};
367 let mut h = DefaultHasher::new();
368 base_shape.hash_into(&mut h);
369 let aspect_bits = if matches!(base_shape, ShapeKind::ImagePlane) { aspect.to_bits() } else { 0 };
370 (h.finish(), aspect_bits, wireframe)
371}
372
326373impl Scene3DRenderer {
327374 pub fn new(device: &wgpu::Device) -> Self {
328375 let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
329376 label: Some("scene3d-shader"),
330 source: wgpu::ShaderSource::Wgsl(SHADER_3D.replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()).into()),
377 source: wgpu::ShaderSource::Wgsl(
378 SHADER_3D
379 .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string())
380 .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string())
381 .into(),
382 ),
331383 });
332384 let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
333385 label: Some("scene3d-bgl"),
......@@ -423,7 +475,7 @@ impl Scene3DRenderer {
423475 mipmap_filter: wgpu::MipmapFilterMode::Linear,
424476 ..Default::default()
425477 });
426 Self { bgl, pipelines, sampler }
478 Self { bgl, pipelines, sampler, meshes: Mutex::new(Lru::new(MESH_CACHE_CAP)) }
427479 }
428480
429481 #[allow(clippy::too_many_arguments)]
......@@ -489,32 +541,45 @@ impl Scene3DRenderer {
489541 .map(|t| (t.canvas_size[0] as f32 / t.canvas_size[1].max(1) as f32).max(1e-4))
490542 .unwrap_or(16.0 / 9.0);
491543 let (base_shape, fx) = m.shape.split_fx();
492 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);
493 if indices.is_empty() {
544 let upload = || {
545 let (mut verts, mut indices) = build_shape_mesh(base_shape, aspect);
546 if indices.is_empty() {
547 return None;
548 }
549 if let Some(disp) = &m.displace {
550 apply_heightmap_displace(&mut verts, &indices, disp);
551 }
552 if fx.wireframe {
553 indices = triangle_edges(&indices);
554 }
555 let vbytes = bytemuck::cast_slice(&verts);
556 let ibytes = bytemuck::cast_slice(&indices);
557 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
558 label: Some("scene3d-vb"),
559 size: vbytes.len() as u64,
560 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
561 mapped_at_creation: false,
562 });
563 queue.write_buffer(&vbuf, 0, vbytes);
564 let ibuf = device.create_buffer(&wgpu::BufferDescriptor {
565 label: Some("scene3d-ib"),
566 size: ibytes.len() as u64,
567 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
568 mapped_at_creation: false,
569 });
570 queue.write_buffer(&ibuf, 0, ibytes);
571 Some(GpuMesh { vbuf, ibuf, idx_count: indices.len() as u32, _shape: base_shape.clone() })
572 };
573 // Heightmap contents are not part of the key, so displaced meshes are never cached.
574 let gpu_mesh = if m.displace.is_some() {
575 upload()
576 } else {
577 let key = mesh_key(base_shape, aspect, fx.wireframe);
578 self.meshes.lock().unwrap().get_or_insert_with(key, upload)
579 };
580 let Some(GpuMesh { vbuf, ibuf, idx_count, .. }) = gpu_mesh else {
494581 continue;
495 }
496 if let Some(disp) = &m.displace {
497 apply_heightmap_displace(&mut verts, &indices, disp);
498 }
499 if fx.wireframe {
500 indices = triangle_edges(&indices);
501 }
502 let vbytes = bytemuck::cast_slice(&verts);
503 let ibytes = bytemuck::cast_slice(&indices);
504 let vbuf = device.create_buffer(&wgpu::BufferDescriptor {
505 label: Some("scene3d-vb"),
506 size: vbytes.len() as u64,
507 usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
508 mapped_at_creation: false,
509 });
510 queue.write_buffer(&vbuf, 0, vbytes);
511 let ibuf = device.create_buffer(&wgpu::BufferDescriptor {
512 label: Some("scene3d-ib"),
513 size: ibytes.len() as u64,
514 usage: wgpu::BufferUsages::INDEX | wgpu::BufferUsages::COPY_DST,
515 mapped_at_creation: false,
516 });
517 queue.write_buffer(&ibuf, 0, ibytes);
582 };
518583
519584 let mvp = mat4_mul(view_proj, m.world);
520585 let dod = if let Some(t) = &m.tex {
......@@ -542,6 +607,13 @@ impl Scene3DRenderer {
542607 spot_dir[si] = [sl.dir[0], sl.dir[1], sl.dir[2], sl.cos_outer];
543608 spot_col[si] = [sl.color[0], sl.color[1], sl.color[2], sl.decay_type];
544609 }
610 let mut dir_to_light = [[0.0_f32; 4]; MAX_DIR_LIGHTS];
611 let mut dir_color = [[0.0_f32; 4]; MAX_DIR_LIGHTS];
612 let n_dir = lights.dirs.len().min(MAX_DIR_LIGHTS);
613 for (di, dl) in lights.dirs.iter().take(MAX_DIR_LIGHTS).enumerate() {
614 dir_to_light[di] = [dl.to_light[0], dl.to_light[1], dl.to_light[2], 0.0];
615 dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0];
616 }
545617 let uni = MeshUniform {
546618 mvp,
547619 model: m.world,
......@@ -560,15 +632,10 @@ impl Scene3DRenderer {
560632 m.specular_exponent,
561633 ],
562634 ambient: [lights.ambient[0], lights.ambient[1], lights.ambient[2], 0.0],
563 dir_to_light: [
564 lights.dir_to_light[0],
565 lights.dir_to_light[1],
566 lights.dir_to_light[2],
567 if lights.has_dir { 1.0 } else { 0.0 },
568 ],
569 dir_color: [lights.dir_color[0], lights.dir_color[1], lights.dir_color[2], 0.0],
635 dir_to_light,
636 dir_color,
570637 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
571 light_counts: [n_pt as f32, n_sp as f32, 0.0, 0.0],
638 light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, 0.0],
572639 uv_xform: fx.uv.m,
573640 uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0],
574641 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 {
601668 bg,
602669 vbuf,
603670 ibuf,
604 idx_count: indices.len() as u32,
671 idx_count,
605672 });
606673 }
607674
......@@ -726,6 +793,103 @@ mod tests {
726793 assert!((alpha - 191).abs() <= 3, "alpha {alpha}");
727794 }
728795
796 #[test]
797 fn normals_stay_perpendicular_under_non_uniform_scale() {
798 // Plane rotated 45 degrees about Y under a [4, 1, 1] scale: the true normal is
799 // (1/4, 0, 1) normalized, so a +Z light gives cos = 0.970; `model * n` would give 0.243.
800 let scene = r#"P = Shape3D { Inputs = { ["SurfacePlaneInputs.Width"] = Input { Value = 2, }, ["Transform3DOp.Rotate.Y"] = Input { Value = 45, }, MaterialInput = Input { SourceOp = "Flat", Source = "MaterialOutput", }, }, },
801 S = Transform3D { Inputs = { ["Transform3DOp.ScaleLock"] = Input { Value = 0, }, ["Transform3DOp.Scale.X"] = Input { Value = 4, }, SceneInput1 = Input { SourceOp = "P", Source = "Output", }, }, },
802 L = LightDirectional { },
803 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "L", Source = "Output", }, SceneInput3 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#;
804 let Some(px) = render(true, scene) else { return };
805 let expected = 255.0 / (1.0 + 1.0 / 16.0_f32).sqrt();
806 let c = center(&px);
807 assert!((c[0] as f32 - expected).abs() <= 3.0, "{c:?} vs {expected}");
808 }
809
810 #[test]
811 fn up_to_four_directional_lights_accumulate() {
812 // Five 0.1 lights facing the plane: the first four reach the shader, so 0.4 * 255.
813 let lights: String = (1..=5)
814 .map(|i| format!(r#"L{i} = LightDirectional {{ Inputs = {{ Intensity = Input {{ Value = 0.1, }}, }}, }},"#))
815 .collect();
816 let ports: String = (1..=5).map(|i| format!(r#"SceneInput{} = Input {{ SourceOp = "L{i}", Source = "Output", }},"#, i + 1)).collect();
817 let scene = format!(
818 r#"{PLANE} {lights}
819 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "P", Source = "Output", }}, {ports} SceneInput7 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},"#
820 );
821 let Some(px) = render(true, &scene) else { return };
822 let c = center(&px);
823 assert!((c[0] as f32 - 102.0).abs() <= 3.0, "{c:?}");
824 }
825
826 #[test]
827 fn gpu_meshes_are_reused_across_frames_and_split_by_wireframe() {
828 let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
829 let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { return };
830 let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) else { return };
831 let renderer = Scene3DRenderer::new(&device);
832 let target = || {
833 CachedTexture::from_texture(
834 device.create_texture(&wgpu::TextureDescriptor {
835 label: None,
836 size: wgpu::Extent3d { width: 8, height: 8, depth_or_array_layers: 1 },
837 mip_level_count: 1,
838 sample_count: 1,
839 dimension: wgpu::TextureDimension::D2,
840 format: wgpu::TextureFormat::Rgba8Unorm,
841 usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
842 view_formats: &[],
843 }),
844 [8, 8],
845 0,
846 )
847 };
848 let (dst, dummy) = (target(), target());
849 let sphere = |x: f32, wireframe: bool| DrawMesh {
850 world: mat4_translate(x, 0.0, 0.0),
851 shape: ShapeKind::WithMaterialFx {
852 inner: Box::new(ShapeKind::Sphere { radius: 1.0, sub_base: 8, sub_height: 8 }),
853 fx: MaterialFx { wireframe, ..Default::default() },
854 },
855 tex: None,
856 diffuse_col: [1.0; 4],
857 specular_col: [1.0; 3],
858 specular_intensity: 0.0,
859 specular_exponent: 50.0,
860 affected_by_lights: false,
861 flip_normals: false,
862 displace: None,
863 };
864 let frame = |meshes: &[DrawMesh]| {
865 let mut enc = device.create_command_encoder(&Default::default());
866 let (vp, cam) = (mat4_identity(), [0.0, 0.0, 5.0]);
867 renderer.render_meshes(&device, &queue, &mut enc, &dst, &dummy, vp, vp, cam, SceneLights::default(), false, meshes);
868 queue.submit(Some(enc.finish()));
869 renderer.meshes.lock().unwrap().entries.len()
870 };
871 assert_eq!(frame(&[sphere(0.0, false)]), 1);
872 assert_eq!(frame(&[sphere(0.5, false)]), 1, "a moved copy reuses the upload");
873 assert_eq!(frame(&[sphere(0.5, true)]), 2, "wireframe uses edge indices");
874 }
875
876 #[test]
877 fn lru_evicts_the_least_recently_used_entry_and_reuses_hits() {
878 let mut lru = Lru::new(2);
879 let builds = std::cell::Cell::new(0);
880 let get = |lru: &mut Lru<u8, u8>, k: u8| lru.get_or_insert_with(k, || { builds.set(builds.get() + 1); k });
881 get(&mut lru, 1);
882 get(&mut lru, 2);
883 get(&mut lru, 1);
884 get(&mut lru, 3);
885 assert_eq!(builds.get(), 3, "second request for key 1 is a hit");
886 get(&mut lru, 1);
887 assert_eq!(builds.get(), 3, "key 1 was refreshed, so key 2 was evicted");
888 get(&mut lru, 2);
889 assert_eq!(builds.get(), 4);
890 assert_eq!(lru.entries.len(), 2);
891 }
892
729893 #[test]
730894 fn uv_affine_then_applies_self_first() {
731895 let shift = UvAffine { m: [1.0, 0.0, 0.0, 1.0], t: [0.5, 0.0] };
crates/engine/src/scene3d/shader.rs+27-12
......@@ -4,6 +4,8 @@ use bytemuck::{Pod, Zeroable};
44
55/// Point and spot lights each get this many shader slots.
66pub(super) const MAX_LIGHTS: usize = 8;
7/// Directional lights get this many shader slots.
8pub(super) const MAX_DIR_LIGHTS: usize = 4;
79
810#[repr(C)]
911#[derive(Clone, Copy, Debug, Pod, Zeroable)]
......@@ -28,13 +30,13 @@ pub(super) struct MeshUniform {
2830 pub(super) specular_col: [f32; 4],
2931 /// Ambient light `(r, g, b, 0)`
3032 pub(super) ambient: [f32; 4],
31 /// Directional light direction TO light `(dx, dy, dz, has_dir)`
32 pub(super) dir_to_light: [f32; 4],
33 /// Directional light color * intensity `(r, g, b, 0)`
34 pub(super) dir_color: [f32; 4],
33 /// Directional light directions TO light `(dx, dy, dz, 0)`
34 pub(super) dir_to_light: [[f32; 4]; MAX_DIR_LIGHTS],
35 /// Directional light colors * intensity `(r, g, b, 0)`
36 pub(super) dir_color: [[f32; 4]; MAX_DIR_LIGHTS],
3537 /// Camera world position `(cx, cy, cz, 0)`
3638 pub(super) cam_pos: [f32; 4],
37 /// `[num_point_lights, num_spot_lights, 0, 0]`
39 /// `[num_point_lights, num_spot_lights, num_dir_lights, 0]`
3840 pub(super) light_counts: [f32; 4],
3941 /// UV affine matrix, column-major `[m00, m10, m01, m11]`
4042 pub(super) uv_xform: [f32; 4],
......@@ -54,7 +56,7 @@ pub(super) struct MeshUniform {
5456 pub(super) spot_col: [[f32; 4]; MAX_LIGHTS],
5557}
5658
57/// WGSL source; `MAX_LIGHTS` is substituted with the Rust constant at pipeline creation.
59/// WGSL source; `MAX_LIGHTS` and `MAX_DIR_LIGHTS` are substituted with the Rust constants at pipeline creation.
5860pub(super) const SHADER_3D: &str = r#"
5961struct MeshUniform {
6062 mvp: mat4x4<f32>,
......@@ -64,8 +66,8 @@ struct MeshUniform {
6466 diffuse_col: vec4<f32>,
6567 specular_col: vec4<f32>,
6668 ambient: vec4<f32>,
67 dir_to_light: vec4<f32>,
68 dir_color: vec4<f32>,
69 dir_to_light: array<vec4<f32>, MAX_DIR_LIGHTS>,
70 dir_color: array<vec4<f32>, MAX_DIR_LIGHTS>,
6971 cam_pos: vec4<f32>,
7072 light_counts: vec4<f32>,
7173 uv_xform: vec4<f32>,
......@@ -97,6 +99,17 @@ struct VsOut {
9799 @location(2) world_n: vec3<f32>,
98100};
99101
102// Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay
103// perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored
104// transforms pointing outward.
105fn normal_matrix(m: mat4x4<f32>) -> mat3x3<f32> {
106 let c0 = m[0].xyz;
107 let c1 = m[1].xyz;
108 let c2 = m[2].xyz;
109 let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0);
110 return mat3x3<f32>(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign;
111}
112
100113@vertex
101114fn vs_mesh(v: VsIn) -> VsOut {
102115 var out: VsOut;
......@@ -104,7 +117,7 @@ fn vs_mesh(v: VsIn) -> VsOut {
104117 out.clip = u.mvp * vec4<f32>(v.pos, 1.0);
105118 out.uv = v.uv;
106119 out.world_pos = wp.xyz;
107 let wn = (u.model * vec4<f32>(v.normal, 0.0)).xyz;
120 let wn = normal_matrix(u.model) * v.normal;
108121 let nlen = length(wn);
109122 var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5);
110123 if (u.flags.w > 0.5) {
......@@ -278,9 +291,11 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
278291 let spec_int = u.flags.z;
279292
280293 var lit = albedo * u.ambient.rgb;
281 if (u.dir_to_light.w > 0.5) {
282 let l = normalize(u.dir_to_light.xyz);
283 lit = lit + eval_light_contrib(n, v, l, u.dir_color.rgb, albedo, spec_rgb, spec_int, shininess);
294 let n_dir = i32(u.light_counts.z + 0.5);
295 for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) {
296 if (i >= n_dir) { break; }
297 let l = normalize(u.dir_to_light[i].xyz);
298 lit = lit + eval_light_contrib(n, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess);
284299 }
285300
286301 let n_pt = i32(u.light_counts.x + 0.5);