From 5ee997e3ed53017f093c62ad4b19c47ef49adbff Mon Sep 17 00:00:00 2001 From: clover caruso Date: Tue, 1 Dec 2026 07:54:30 -0800 Subject: [PATCH] scene3d: honor CameraSelector, add Cone/Torus/Ico, UVW texture transforms, ReplaceNormals recompute - Renderer3D picks its camera by CameraSelector (ThursdayMoving Renderer3D2: 18.2% -> 0.8% MAE). - Shape3D Cone, Torus and Icosahedron meshes; cylinder TopCap/BottomCap. - Texture2DOperator UOffset/VOffset/UScale/VScale; TextureTransformOperator full UVW rotation/scale/pivot/InvertTransform through a shared TRS matrix. - ReplaceNormals3D reads Normals.Flip and recomputes normals by smoothing angle. - Visibility.IsUnseenByCameras skips the camera pass, Transform3DOp.InvertTransform inverts nodes. - ReceivesLighting=0 materials add their color once per light; EnablePBRMaterial lights at 1/pi without specular. Assisted-by: claude-sonnet-5.5 --- crates/engine/src/eval/text_3d.rs | 13 +- crates/engine/src/scene3d/collect.rs | 249 +++++++++++++++++++++------ crates/engine/src/scene3d/mesh.rs | 221 +++++++++++++++++++++++- crates/engine/src/scene3d/mod.rs | 18 +- crates/engine/src/scene3d/shader.rs | 11 +- 5 files changed, 441 insertions(+), 71 deletions(-) diff --git a/crates/engine/src/eval/text_3d.rs b/crates/engine/src/eval/text_3d.rs index 646246d568c30f6d3f9747f2d18be58d714a2794..00e809075aec0be345027fd4d15efbbce7726e33 100644 --- a/crates/engine/src/eval/text_3d.rs +++ b/crates/engine/src/eval/text_3d.rs @@ -745,16 +745,12 @@ impl Engine { 0, ); - let is_ortho = visited_nodes - .iter() - .map(|&id| comp.node(id)) - .find(|n| n.kind == "Camera3D") - .and_then(|n| n.static_str("ProjectionType")) - == Some("Orthographic"); + let selector = node.static_str("CameraSelector").unwrap_or_default(); + let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first()); - let (view, proj, cam_pos, cam_far) = if let Some(cam) = cameras.first() { + let (view, proj, cam_pos, cam_far) = if let Some(cam) = selected_camera { let v = crate::scene3d::mat4_inverse(cam.world); - let p = if is_ortho { + let p = if cam.orthographic { let inv_w = 1.0 / aspect.max(1e-4); let inv_dz = 1.0 / (cam.far - cam.near).max(1e-4); [ @@ -781,6 +777,7 @@ impl Engine { hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 }); hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 }); hash_floats.extend_from_slice(&lights.ambient); + hash_floats.push(lights.count as f32); for dl in &lights.dirs { hash_floats.extend_from_slice(&dl.to_light); hash_floats.extend_from_slice(&dl.color); diff --git a/crates/engine/src/scene3d/collect.rs b/crates/engine/src/scene3d/collect.rs index d48c8eaedfe9addc7092cbef4ae3499b7256634c..c56a0fade47279882f7268b6fea583745572b583 100644 --- a/crates/engine/src/scene3d/collect.rs +++ b/crates/engine/src/scene3d/collect.rs @@ -1,12 +1,15 @@ //! 3D scene graph traversal, material resolution, and 3D transform evaluation. +use std::sync::Arc; + use super::fbx::load_mesh_cached; +use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup}; use super::math::{ mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, }; use super::{ CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, - ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES, + ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES, }; use model::{Comp, ExprEngine, Node, NodeId}; @@ -16,6 +19,8 @@ struct SceneOverrides { affected_by_lights: Option, casts_shadow: Option, flip_normals: bool, + /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals. + smooth_normals_deg: Option, displace: Option, cull_back: bool, cull_front: bool, @@ -162,9 +167,12 @@ fn collect_scene_inner( } "ReplaceNormals3D" => { let mut next_ovr = ovr.clone(); - if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 { + if comp.eval_number(node, "Normals.Flip", time, 0.0, expr) > 0.5 { next_ovr.flip_normals = !next_ovr.flip_normals; } + if comp.eval_number(node, "Normals.Recompute", time, 0.0, expr).round() as i32 == 0 { + next_ovr.smooth_normals_deg = Some(comp.eval_number(node, "Normals.SmoothingAngle", time, 45.0, expr) as f32); + } if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); } @@ -257,12 +265,20 @@ fn collect_scene_inner( let vfov_rad = 2.0 * half_v.atan(); let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32; let far = 5000.0_f32; - cameras.push(CameraInstance { world, vfov_rad, near, far }); + cameras.push(CameraInstance { + name: node.name.clone(), + orthographic: node.static_str("ProjectionType") == Some("Orthographic"), + world, + vfov_rad, + near, + far, + }); if let Some(src_id) = node.connected_node("SceneInput").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); } } "LightAmbient" => { + lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; if let Some(color) = light_color(comp, node, time, expr) { for (acc, c) in lights.ambient.iter_mut().zip(color) { *acc += c; @@ -273,6 +289,7 @@ fn collect_scene_inner( } } "LightDirectional" => { + lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; if let Some(color) = light_color(comp, node, time, expr) { // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation! let dx = world[8]; @@ -286,6 +303,7 @@ fn collect_scene_inner( } } "LightPoint" => { + lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; if let Some(color) = light_color(comp, node, time, expr) { let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32; lights.points.push(PointLight { @@ -302,6 +320,7 @@ fn collect_scene_inner( } } "LightSpot" => { + lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; if let Some(color) = light_color(comp, node, time, expr) { let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32; let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32; @@ -359,8 +378,37 @@ fn collect_scene_inner( start_sweep_deg: start_sw, end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, + top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5, + bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5, } } + "SurfaceConeInputs" => { + let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceConeInputs.{k}"), time, d, expr); + let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32]; + custom_shape(build_cone( + f("Radius", 1.0) as f32, + f("Height", 2.0) as f32, + sweep, + f("SubdivisionLevelBase", 20.0).round() as u32, + f("SubdivisionLevelHeight", 1.0).round() as u32, + f("BottomCap", 0.0) > 0.5, + )) + } + "SurfaceTorusInputs" => { + let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceTorusInputs.{k}"), time, d, expr); + let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32]; + custom_shape(build_torus( + f("Radius", 1.0) as f32, + f("Section", 0.5) as f32, + sweep, + f("SubdivisionLevelBase", 20.0).round() as u32, + f("SubdivisionLevelHeight", 20.0).round() as u32, + )) + } + "SurfaceIcoInputs" => { + let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceIcoInputs.{k}"), time, d, expr); + custom_shape(build_icosahedron(f("Size", 1.0) as f32, f("SubdivisionLevel", 0.0).round() as u32)) + } "SurfaceCubeInputs" => ShapeKind::Cube { width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32, sub: cube_subdivisions(comp, node, time, expr), @@ -518,6 +566,10 @@ fn make_mesh_instance( text3d: Option, ovr: &SceneOverrides, ) -> MeshInstance { + let shape = match (ovr.smooth_normals_deg, &shape) { + (Some(deg), s) if !matches!(s, ShapeKind::ImagePlane | ShapeKind::TextPlate { .. }) => ShapeKind::CustomMesh(Arc::new(smooth_normals(build_shape_mesh(s, 1.0), deg))), + _ => shape, + }; MeshInstance { world, shape: ShapeKind::WithMaterialFx { @@ -549,11 +601,13 @@ fn surface_scope( expr: &ExprEngine, ) -> Option { let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5; + let unseen = flag("Visibility.IsUnseenByCameras", 0.0); flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides { affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))), casts_shadow: Some(flag("Lighting.IsShadowCaster", 1.0)), - cull_back: flag("Visibility.CullBackFace", 0.0), - cull_front: flag("Visibility.CullFrontFace", 0.0), + // Unseen-by-cameras surfaces skip the camera pass but still cast shadows. + cull_back: flag("Visibility.CullBackFace", 0.0) || unseen, + cull_front: flag("Visibility.CullFrontFace", 0.0) || unseen, ..ovr.clone() }) } @@ -568,6 +622,10 @@ fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option (color != [0.0; 3]).then_some(color) } +fn custom_shape(mesh: (Vec, Vec)) -> ShapeKind { + ShapeKind::CustomMesh(Arc::new(triangle_soup(mesh))) +} + /// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal. fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 { comp.eval_number(node, "SurfaceCubeInputs.SubdivisionWidth", time, 10.0, expr).round() as u32 @@ -582,6 +640,13 @@ fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: & mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0); mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0); mat.receives_shadows = f("ReceivesShadows", 1.0) > 0.5; + if f("ReceivesLighting", 1.0) < 0.5 { + mat.unlit = true; + mat.fx.per_light_unlit = true; + } + if f("EnablePBRMaterial", 0.0) > 0.5 { + mat.fx.spec_model = SpecModel::Pbr; + } } fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option { @@ -603,15 +668,16 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op None } -/// Mesh-UV -> texture-UV map for a `TextureTransformOperator`. The content is moved by -/// translate * rotate * scale about the pivot in V-up image space, so sampling applies the inverse. -fn texture_transform_uv(translate: [f32; 2], rot_rad: f32, scale: [f32; 2], pivot: [f32; 2]) -> UvAffine { - let inv = |v: f32| 1.0 / if v.abs() < 1e-4 { 1e-4 } else { v }; - let (sn, cs) = rot_rad.sin_cos(); +/// Mesh-UV -> texture-UV map for a UVW content transform `m` (V up, W dropped when sampling). +/// `m` moves the content, so sampling applies its inverse; `invert` swaps the two. +fn texture_transform_uv(m: Mat4, invert: bool) -> UvAffine { + let sampling = if invert { m } else { mat4_inverse(m) }; let sample = |uv: [f32; 2]| { - let q = [uv[0] - translate[0] - pivot[0], (1.0 - uv[1]) - translate[1] - pivot[1]]; - let r = [cs * q[0] + sn * q[1], -sn * q[0] + cs * q[1]]; - [pivot[0] + r[0] * inv(scale[0]), 1.0 - (pivot[1] + r[1] * inv(scale[1]))] + let (x, y) = (uv[0], 1.0 - uv[1]); + [ + sampling[0] * x + sampling[4] * y + sampling[12], + 1.0 - (sampling[1] * x + sampling[5] * y + sampling[13]), + ] }; let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0])); UvAffine { m: [eu[0] - o[0], eu[1] - o[1], ev[0] - o[0], ev[1] - o[1]], t: o } @@ -649,9 +715,14 @@ fn resolve_material_inner( match n.kind.as_str() { "Texture2DOperator" => { let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s)); + let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; ResolvedMaterial { tex_node: tex_src, fx: MaterialFx { + uv: texture_transform_uv( + trs_matrix([f("UOffset", 0.0), f("VOffset", 0.0), 0.0], [0.0; 3], "XYZ", [f("UScale", 1.0), f("VScale", 1.0), 1.0], [0.0; 3]), + false, + ), uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0), ..default_mat.fx }, @@ -663,12 +734,10 @@ fn resolve_material_inner( let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s)); let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1); let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; - let xf = texture_transform_uv( - [f("Translation.U", 0.0), f("Translation.V", 0.0)], - f("Rotation.W", 0.0).to_radians(), - [f("Scale.U", 1.0), f("Scale.V", 1.0)], - [f("Pivot.U", 0.0), f("Pivot.V", 0.0)], - ); + let uvw = |prefix: &str, d: f64| ["U", "V", "W"].map(|a| f(&format!("{prefix}.{a}"), d)); + let order = n.static_str("Rotation.RotOrder").unwrap_or("UVW").replace('U', "X").replace('V', "Y").replace('W', "Z"); + let m = trs_matrix(uvw("Translation", 0.0), uvw("Rotation", 0.0), &order, uvw("Scale", 1.0), uvw("Pivot", 0.0)); + let xf = texture_transform_uv(m, f("InvertTransform", 0.0) > 0.5); mat.fx.uv = xf.then(&mat.fx.uv); if let Some(w) = parse_wrap_mode(comp, n, time, expr) { mat.fx.uv_wrap = w; @@ -728,12 +797,14 @@ fn resolve_material_inner( _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn), }; + let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model }; + let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5; let mut tex_node = diff_mat.tex_node; - let mut fx = MaterialFx { spec_model, ..diff_mat.fx }; + let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx }; if let Some(bm) = bump_mat { if tex_node.is_none() { tex_node = bm.tex_node; - fx = MaterialFx { bump_only: true, spec_model, ..bm.fx }; + fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx }; } fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 }; fx.bump_mode = bm.fx.bump_mode; @@ -746,7 +817,7 @@ fn resolve_material_inner( specular_intensity: spec_int.clamp(0.0, 4.0), specular_exponent: spec_exp, fx, - unlit: false, + unlit: !lit, receives_shadows: comp.eval_number(n, "ReceivesShadows", time, 1.0, expr) > 0.5, has_material_shader: true, } @@ -813,44 +884,36 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32; let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32; - let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians(); - let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians(); - let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians(); + let r = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Rotate.{a}"), time, 0.0, expr) as f32); let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ"); let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5; let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32; - let sy = if scale_lock { - sx + let (sy, sz) = if scale_lock { + (sx, sx) } else { - comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32 - }; - let sz = if scale_lock { - sx - } else { - comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32 + ( + comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32, + comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32, + ) }; - let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32; - let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32; - let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32; - - let mx = mat4_rot_x(rx); - let my = mat4_rot_y(ry); - let mz = mat4_rot_z(rz); - let rot = match rot_order { - "XZY" => mat4_mul(my, mat4_mul(mz, mx)), - "YXZ" => mat4_mul(mz, mat4_mul(mx, my)), - "YZX" => mat4_mul(mx, mat4_mul(mz, my)), - "ZXY" => mat4_mul(my, mat4_mul(mx, mz)), - "ZYX" => mat4_mul(mx, mat4_mul(my, mz)), - _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default - }; + let p = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Pivot.{a}"), time, 0.0, expr) as f32); + let m = trs_matrix([tx, ty, tz], r, rot_order, [sx, sy, sz], p); + if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m } +} - let t = mat4_translate(tx + px, ty + py, tz + pz); - let s = mat4_scale(sx, sy, sz); - let inv_p = mat4_translate(-px, -py, -pz); - mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p))) +/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first). +fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 { + let [rx, ry, rz] = rot_deg.map(f32::to_radians); + let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)]; + let rot = order + .bytes() + .filter_map(|b| "XYZ".find(b as char)) + .fold(mat4_identity(), |acc, a| mat4_mul(axes[a], acc)); + let t = mat4_translate(translate[0] + pivot[0], translate[1] + pivot[1], translate[2] + pivot[2]); + let s = mat4_scale(scale[0], scale[1], scale[2]); + mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2])))) } #[cfg(test)] @@ -904,7 +967,7 @@ mod tests { RepNorm = ReplaceNormals3D { Inputs = { SceneInput = Input { SourceOp = "RepMat", Source = "Output", }, - FlipNormals = Input { Value = 1, }, + ["Normals.Flip"] = Input { Value = 1, }, }, }, Disp1 = Displace3D { @@ -1122,6 +1185,73 @@ mod tests { format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}") } + #[test] + fn cameras_carry_names_for_renderer_selection() { + let src = comp_src( + r#"A = Camera3D { }, B = Camera3D { Inputs = { ProjectionType = Input { Value = FuID { "Orthographic" }, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, }, },"#, + ); + let (cams, ..) = collect(&src, "M"); + let found: Vec<_> = cams.iter().map(|c| (c.name.as_str(), c.orthographic)).collect(); + assert_eq!(found, [("A", false), ("B", true)]); + } + + #[test] + fn texture2d_offset_and_scale_move_content_like_a_texture_transform() { + let src = comp_src( + r#"Bg = Background { }, Tex = Texture2DOperator { Inputs = { UOffset = Input { Value = 0.25, }, UScale = Input { Value = 2, }, Input = Input { SourceOp = "Bg", Source = "Output", }, }, }, + S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },"#, + ); + let (_, meshes, _) = collect(&src, "S"); + let (_, fx) = meshes[0].shape.split_fx(); + // Content scales 2x about the origin then moves right by 0.25: mesh u=0.75 samples texture u=0.25. + assert!((fx.uv.apply([0.75, 0.0])[0] - 0.25).abs() < 1e-5); + } + + #[test] + fn receives_lighting_off_is_unlit_and_lights_are_counted() { + let src = comp_src( + r#"Mtl = MtlBlinn { Inputs = { ReceivesLighting = Input { Value = 0, }, EnablePBRMaterial = Input { Value = 1, }, }, }, + S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, }, }, + A = LightAmbient { }, P = LightPoint { }, Off = LightPoint { Inputs = { Enabled = Input { Value = 0, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, SceneInput2 = Input { SourceOp = "A", Source = "Output", }, SceneInput3 = Input { SourceOp = "P", Source = "Output", }, SceneInput4 = Input { SourceOp = "Off", Source = "Output", }, }, },"#, + ); + let (_, meshes, lights) = collect(&src, "M"); + let (_, fx) = meshes[0].shape.split_fx(); + assert!(fx.per_light_unlit && !meshes[0].affected_by_lights); + assert_eq!(fx.spec_model, SpecModel::Pbr); + assert_eq!(lights.count, 2); + } + + #[test] + fn invert_transform_inverts_the_node_matrix() { + let src = comp_src( + r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 3, }, ["Transform3DOp.InvertTransform"] = Input { Value = 1, }, }, }, + M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#, + ); + let (cams, ..) = collect(&src, "M"); + assert!((cams[0].world[12] + 3.0).abs() < 1e-5); + } + + #[test] + fn replace_normals_recomputes_by_smoothing_angle() { + let tris = |angle: f64| { + let src = comp_src(&format!( + r#"S = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfaceIcoInputs" }}, }}, }}, }}, + N = ReplaceNormals3D {{ Inputs = {{ ["Normals.SmoothingAngle"] = Input {{ Value = {angle}, }}, SceneInput = Input {{ SourceOp = "S", Source = "Output", }}, }}, }},"# + )); + let (_, meshes, _) = collect(&src, "N"); + let (ShapeKind::CustomMesh(v), _) = meshes[0].shape.split_fx() else { panic!("expected a mesh") }; + v.clone() + }; + // Adjacent icosahedron faces differ by ~41.8 degrees: below that every face is flat. + let flat = tris(30.0); + let close = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4); + assert!(flat.chunks_exact(3).all(|t| close(t[0].normal, t[1].normal) && close(t[1].normal, t[2].normal))); + let smooth = tris(90.0); + assert!(smooth.chunks_exact(3).any(|t| !close(t[0].normal, t[1].normal))); + } + #[test] fn camera_vertical_aov_comes_from_default_35mm_focal_length() { // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35). @@ -1174,20 +1304,27 @@ mod tests { #[test] fn texture_transform_moves_content_about_a_bottom_left_pivot() { + let uvw = |t, r, s, invert| texture_transform_uv(trs_matrix(t, r, "XYZ", s, [0.0; 3]), invert); // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up). - let zoom = texture_transform_uv([0.0, 0.0], 0.0, [2.0, 2.0], [0.0, 0.0]); + let zoom = uvw([0.0; 3], [0.0; 3], [2.0, 2.0, 1.0], false); let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0])); assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5); assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5); // Content moved right and up samples from smaller u and larger raw v (V down). - let shift = texture_transform_uv([0.25, 0.1], 0.0, [1.0, 1.0], [0.0, 0.0]).apply([0.5, 0.5]); + let shift = uvw([0.25, 0.1, 0.0], [0.0; 3], [1.0; 3], false).apply([0.5, 0.5]); assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5); // Counter-clockwise content rotation about the pivot. - let quarter = texture_transform_uv([0.0, 0.0], std::f32::consts::FRAC_PI_2, [1.0, 1.0], [0.0, 0.0]); + let quarter = uvw([0.0; 3], [0.0, 0.0, 90.0], [1.0; 3], false); let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}"); + + // Tilting about U drops W, magnifying content in V by 1/cos; InvertTransform undoes a move. + let tilt = uvw([0.0; 3], [60.0, 0.0, 0.0], [1.0; 3], false).apply([0.0, 0.5]); + assert!((tilt[1] - 0.75).abs() < 1e-5, "{tilt:?}"); + let back = uvw([0.2, 0.0, 0.0], [0.0; 3], [1.0; 3], true).apply([0.5, 0.5]); + assert!((back[0] - 0.7).abs() < 1e-5, "{back:?}"); } #[test] diff --git a/crates/engine/src/scene3d/mesh.rs b/crates/engine/src/scene3d/mesh.rs index 2ccc46cd2897cae53c6de0976439e9517e240395..fada7a3e7310beee110b801c359dff7e3cf4485f 100644 --- a/crates/engine/src/scene3d/mesh.rs +++ b/crates/engine/src/scene3d/mesh.rs @@ -19,7 +19,9 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base), + top_cap, + bottom_cap, + } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base, [*top_cap, *bottom_cap]), ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), ShapeKind::CustomMesh(verts) => { let v = verts.as_ref().clone(); @@ -149,6 +151,7 @@ fn build_cylinder( start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, + caps: [bool; 2], ) -> (Vec, Vec) { let seg_u = sub_base.clamp(16, 96); let half_h = height * 0.5; @@ -181,6 +184,20 @@ fn build_cylinder( let d = a + 2; idx.extend_from_slice(&[a, b, d, b, c, d]); } + for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) { + if !cap { + continue; + } + let base = verts.len() as u32; + verts.push(Vertex3D { pos: [0.0, y, 0.0], normal: [0.0, ny, 0.0], uv: [0.5, 0.5] }); + for iu in 0..=seg_u { + let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos(); + verts.push(Vertex3D { pos: [ct * radius, y, st * radius], normal: [0.0, ny, 0.0], uv: [0.5 + 0.5 * ct, 0.5 + 0.5 * st] }); + } + for iu in 0..seg_u { + idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]); + } + } (verts, idx) } @@ -204,6 +221,186 @@ fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec, Vec) (verts, idx) } +/// Expands an indexed mesh to the triangle list `ShapeKind::CustomMesh` carries. +pub(super) fn triangle_soup((verts, idx): (Vec, Vec)) -> Vec { + idx.into_iter().map(|i| verts[i as usize]).collect() +} + +/// Rings run from the apex (`+Y`) down to the base; sweep and angle convention match the cylinder. +pub(super) fn build_cone( + radius: f32, + height: f32, + sweep_deg: [f32; 2], + sub_base: u32, + sub_height: u32, + bottom_cap: bool, +) -> (Vec, Vec) { + let (seg_u, seg_v) = (sub_base.clamp(3, 96), sub_height.clamp(1, 64)); + let [a0, a1] = sweep_deg.map(f32::to_radians); + let slant = (height * height + radius * radius).sqrt().max(1e-6); + let (mut verts, mut idx) = (Vec::new(), Vec::new()); + for iv in 0..=seg_v { + let t = iv as f32 / seg_v as f32; + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + let (st, ct) = (a0 + (a1 - a0) * u).sin_cos(); + verts.push(Vertex3D { + pos: [ct * radius * t, height * (0.5 - t), st * radius * t], + normal: [ct * height / slant, radius / slant, st * height / slant], + uv: [1.0 - u, t], + }); + } + } + grid_indices(&mut idx, 0, seg_u, seg_v); + if bottom_cap { + let base = verts.len() as u32; + let center = Vertex3D { pos: [0.0, -height * 0.5, 0.0], normal: [0.0, -1.0, 0.0], uv: [0.5, 0.5] }; + verts.push(center); + for iu in 0..=seg_u { + let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos(); + verts.push(Vertex3D { pos: [ct * radius, -height * 0.5, st * radius], normal: [0.0, -1.0, 0.0], uv: [0.5 + 0.5 * ct, 0.5 + 0.5 * st] }); + } + for iu in 0..seg_u { + idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]); + } + } + (verts, idx) +} + +/// Tube of radius `section` swept around the `Y` axis at distance `radius`. +pub(super) fn build_torus( + radius: f32, + section: f32, + sweep_deg: [f32; 2], + sub_base: u32, + sub_height: u32, +) -> (Vec, Vec) { + let (seg_u, seg_v) = (sub_base.clamp(3, 128), sub_height.clamp(3, 128)); + let [a0, a1] = sweep_deg.map(f32::to_radians); + let (mut verts, mut idx) = (Vec::new(), Vec::new()); + for iv in 0..=seg_v { + let v = iv as f32 / seg_v as f32; + let (sp, cp) = (v * std::f32::consts::TAU).sin_cos(); + for iu in 0..=seg_u { + let u = iu as f32 / seg_u as f32; + let (st, ct) = (a0 + (a1 - a0) * u).sin_cos(); + verts.push(Vertex3D { + pos: [(radius + section * cp) * ct, section * sp, (radius + section * cp) * st], + normal: [cp * ct, sp, cp * st], + uv: [1.0 - u, v], + }); + } + } + grid_indices(&mut idx, 0, seg_u, seg_v); + (verts, idx) +} + +/// Icosahedron with a vertex on each `Y` pole, each triangle split in four per `level` and +/// projected onto the sphere of circumradius `size`. +pub(super) fn build_icosahedron(size: f32, level: u32) -> (Vec, Vec) { + let ring_y = 1.0 / 5.0_f32.sqrt(); + let ring_r = 2.0 * ring_y; + let ring = |k: u32, y: f32, offset_deg: f32| { + let (s, c) = ((k as f32 * 72.0 + offset_deg).to_radians()).sin_cos(); + [ring_r * c, y, ring_r * s] + }; + let mut pts: Vec<[f32; 3]> = vec![[0.0, 1.0, 0.0], [0.0, -1.0, 0.0]]; + pts.extend((0..5).map(|k| ring(k, ring_y, 54.0))); + pts.extend((0..5).map(|k| ring(k, -ring_y, 54.0 + 36.0))); + let (up, lo) = (|k: u32| 2 + k % 5, |k: u32| 7 + k % 5); + let mut tris: Vec<[[f32; 3]; 3]> = Vec::new(); + for k in 0..5 { + for t in [[0, up(k), up(k + 1)], [up(k), lo(k), up(k + 1)], [lo(k), lo(k + 1), up(k + 1)], [1, lo(k + 1), lo(k)]] { + tris.push(t.map(|i| pts[i as usize])); + } + } + let norm = |p: [f32; 3]| { + let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6); + [p[0] / l, p[1] / l, p[2] / l] + }; + for _ in 0..level.min(4) { + tris = tris + .into_iter() + .flat_map(|[a, b, c]| { + let mid = |p: [f32; 3], q: [f32; 3]| norm([p[0] + q[0], p[1] + q[1], p[2] + q[2]]); + let (ab, bc, ca) = (mid(a, b), mid(b, c), mid(c, a)); + [[a, ab, ca], [ab, b, bc], [ca, bc, c], [ab, bc, ca]] + }) + .collect(); + } + let verts: Vec = tris + .into_iter() + .flatten() + .map(|p| { + let n = norm(p); + Vertex3D { pos: [n[0] * size, n[1] * size, n[2] * size], normal: n, uv: [0.5 + n[2].atan2(n[0]) / std::f32::consts::TAU, 0.5 - n[1].asin() / std::f32::consts::PI] } + }) + .collect(); + let idx = (0..verts.len() as u32).collect(); + (verts, idx) +} + +/// Fusion's `ReplaceNormals3D` recompute: each triangle corner averages (corner-angle weighted) +/// the face normals of every triangle sharing its position within `angle_deg` of its own face. +pub(super) fn smooth_normals((verts, idx): (Vec, Vec), angle_deg: f32) -> Vec { + let sub = |a: [f32; 3], b: [f32; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; + let unit = |a: [f32; 3]| { + let l = dot(a, a).sqrt(); + (l > 1e-12).then(|| [a[0] / l, a[1] / l, a[2] / l]) + }; + let cross = |a: [f32; 3], b: [f32; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); + let tris: Vec<[u32; 3]> = idx.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect(); + let face_n: Vec> = tris + .iter() + .map(|t| { + let p = t.map(|i| verts[i as usize].pos); + // Winding varies per builder; the authored vertex normals say which side is out. + let outward = t.iter().fold(0.0, |a, &i| a + dot(verts[i as usize].normal, cross(sub(p[1], p[0]), sub(p[2], p[0])))); + unit(cross(sub(p[1], p[0]), sub(p[2], p[0]))).map(|n| if outward < 0.0 { n.map(|c| -c) } else { n }) + }) + .collect(); + // Per welded position: (triangle, interior angle at that corner). + let mut at: std::collections::HashMap<[i64; 3], Vec<(usize, f32)>> = std::collections::HashMap::new(); + for (ti, t) in tris.iter().enumerate() { + if face_n[ti].is_none() { + continue; + } + let p = t.map(|i| verts[i as usize].pos); + for c in 0..3 { + let (e0, e1) = (unit(sub(p[(c + 1) % 3], p[c])), unit(sub(p[(c + 2) % 3], p[c]))); + let angle = e0.zip(e1).map_or(0.0, |(a, b)| dot(a, b).clamp(-1.0, 1.0).acos()); + at.entry(key(p[c])).or_default().push((ti, angle)); + } + } + let cos_limit = angle_deg.to_radians().cos() - 1e-4; + let mut out = Vec::with_capacity(tris.len() * 3); + for (ti, t) in tris.iter().enumerate() { + for &i in t { + let mut v = verts[i as usize]; + if let (Some(own), Some(group)) = (face_n[ti], at.get(&key(v.pos))) { + let sum = group.iter().filter_map(|&(fi, w)| face_n[fi].filter(|n| dot(*n, own) >= cos_limit).map(|n| n.map(|c| c * w))).fold([0.0; 3], |a, n| [a[0] + n[0], a[1] + n[1], a[2] + n[2]]); + v.normal = unit(sum).unwrap_or(own); + } + out.push(v); + } + } + out +} + +/// Quad-grid triangulation of `(seg_u + 1) * (seg_v + 1)` vertices starting at `base`. +fn grid_indices(idx: &mut Vec, base: u32, seg_u: u32, seg_v: u32) { + let row = seg_u + 1; + for iv in 0..seg_v { + for iu in 0..seg_u { + let a = base + iv * row + iu; + let (b, c, d) = (a + row, a + row + 1, a + 1); + idx.extend_from_slice(&[a, b, d, b, c, d]); + } + } +} + /// Unique triangle edges as a line-list index buffer. pub(super) fn triangle_edges(indices: &[u32]) -> Vec { let mut seen = std::collections::HashSet::new(); @@ -301,6 +498,28 @@ mod tests { assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0])); } + #[test] + fn icosahedron_has_twenty_faces_on_the_circumsphere() { + let (verts, idx) = build_icosahedron(2.0, 0); + assert_eq!(idx.len(), 20 * 3); + assert!(verts.iter().all(|v| (v.pos.iter().map(|c| c * c).sum::().sqrt() - 2.0).abs() < 1e-4)); + assert_eq!(build_icosahedron(1.0, 1).1.len(), 80 * 3); + } + + #[test] + fn cone_apex_is_up_and_cap_is_optional() { + let (open, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, false); + let (capped, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, true); + assert!(open.iter().take(9).all(|v| v.pos[1] == 1.0 && v.pos[0] == 0.0)); + assert_eq!(capped.len(), open.len() + 1 + 9); + } + + #[test] + fn torus_tube_stays_within_radius_plus_section() { + let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8); + assert!(verts.iter().all(|v| v.pos[1].abs() <= 0.5 + 1e-5 && (v.pos[0].hypot(v.pos[2]) - 1.0).abs() <= 0.5 + 1e-5)); + } + #[test] fn triangle_edges_are_deduplicated() { // Two triangles sharing edge 1-2. diff --git a/crates/engine/src/scene3d/mod.rs b/crates/engine/src/scene3d/mod.rs index c1bc115299c9c9482483c1a2e920f695fe3d1019..0d2ecba1d0f590eb7f2971e316695fbb29b3d31c 100644 --- a/crates/engine/src/scene3d/mod.rs +++ b/crates/engine/src/scene3d/mod.rs @@ -121,6 +121,9 @@ impl Lru { #[derive(Clone)] pub struct CameraInstance { + /// Node name, matched against a renderer's `CameraSelector`. + pub name: String, + pub orthographic: bool, pub world: Mat4, pub vfov_rad: f32, pub near: f32, @@ -131,7 +134,7 @@ pub struct CameraInstance { pub enum ShapeKind { ImagePlane, Sphere { radius: f32, sub_base: u32, sub_height: u32 }, - Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 }, + Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, top_cap: bool, bottom_cap: bool }, Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. Cube { width: f32, sub: u32, faces: u8 }, @@ -194,6 +197,8 @@ pub enum SpecModel { Blinn, Phong, CookTorrance, + /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe. + Pbr, } #[derive(Clone, Copy, Debug, PartialEq)] @@ -211,6 +216,8 @@ pub struct MaterialFx { pub wireframe: bool, pub cull_back: bool, pub cull_front: bool, + /// Unlit surface that Fusion draws once per light, so it brightens with the light count. + pub per_light_unlit: bool, } impl Default for MaterialFx { @@ -225,6 +232,7 @@ impl Default for MaterialFx { wireframe: false, cull_back: false, cull_front: false, + per_light_unlit: false, } } } @@ -241,6 +249,7 @@ impl MaterialFx { self.wireframe.hash(h); self.cull_back.hash(h); self.cull_front.hash(h); + self.per_light_unlit.hash(h); } } @@ -267,8 +276,9 @@ impl ShapeKind { sub_base.hash(h); sub_height.hash(h); } - ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => { + ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, top_cap, bottom_cap } => { 2u8.hash(h); + (*top_cap, *bottom_cap).hash(h); radius.to_bits().hash(h); height.to_bits().hash(h); start_sweep_deg.to_bits().hash(h); @@ -386,6 +396,8 @@ pub struct SceneLights { pub dirs: Vec, pub points: Vec, pub spots: Vec, + /// Enabled light nodes of every kind, including black ones. + pub count: u32, } pub struct DrawMesh { @@ -946,7 +958,7 @@ impl Scene3DRenderer { cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0], light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 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], + uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, if lighting_enabled && fx.per_light_unlit { lights.count.max(1) as f32 } else { 1.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], point_pos, point_col, diff --git a/crates/engine/src/scene3d/shader.rs b/crates/engine/src/scene3d/shader.rs index 3bc729b96655b31e3125db774f4df4d02a5ba55d..bac9cfc23db6f84c2bcb1efecf211f72fc3f29d2 100644 --- a/crates/engine/src/scene3d/shader.rs +++ b/crates/engine/src/scene3d/shader.rs @@ -44,9 +44,9 @@ pub(super) struct MeshUniform { pub(super) light_counts: [f32; 4], /// UV affine matrix, column-major `[m00, m10, m01, m11]` pub(super) uv_xform: [f32; 4], - /// UV translation and wrap mode `[tx, ty, wrap, 0]` + /// UV translation, wrap mode and unlit light-pass count `[tx, ty, wrap, passes]` pub(super) uv_off_wrap: [f32; 4], - /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance]` + /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr]` pub(super) mat_fx: [f32; 4], /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], @@ -256,10 +256,13 @@ fn eval_light_contrib( if (ndotl <= 0.0) { return vec3(0.0); } + let model = i32(u.mat_fx.w + 0.5); + if (model == 3) { + return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265); + } var out = albedo * light_rgb * (ndotl * diffuse_vis); if (spec_int > 1e-4) { let h = normalize(l + v); - let model = i32(u.mat_fx.w + 0.5); var lobe: f32; if (model == 1) { lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); @@ -425,6 +428,8 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4 { } col = vec4(clamp(lit, vec3(0.0), vec3(1.0)) * col.a, col.a); + } else { + col = vec4(min(col.rgb * u.uv_off_wrap.w, vec3(1.0)), col.a); } return col; } -- 2.54.1