authoravatarclover caruso<git@paperclover.net>2026-12-01 07:54:30-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 08:47:42-08:00
log5ee997e3ed53017f093c62ad4b19c47ef49adbff
tree81b85e7f2271cfd45839623b45a359360f904675
parent734dbaf1c2fcf70c87991f52f94ff9092ec9eae5
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

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

5 files changed, 441 insertions(+), 71 deletions(-)

crates/engine/src/eval/text_3d.rs+5-8
...@@ -745,16 +745,12 @@ impl Engine {...@@ -745,16 +745,12 @@ impl Engine {
745 0,745 0,
746 );746 );
747747
748 let is_ortho = visited_nodes748 let selector = node.static_str("CameraSelector").unwrap_or_default();
749 .iter()749 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());
750 .map(|&id| comp.node(id))
751 .find(|n| n.kind == "Camera3D")
752 .and_then(|n| n.static_str("ProjectionType"))
753 == Some("Orthographic");
754750
755 let (view, proj, cam_pos, cam_far) = if let Some(cam) = cameras.first() {751 let (view, proj, cam_pos, cam_far) = if let Some(cam) = selected_camera {
756 let v = crate::scene3d::mat4_inverse(cam.world);752 let v = crate::scene3d::mat4_inverse(cam.world);
757 let p = if is_ortho {753 let p = if cam.orthographic {
758 let inv_w = 1.0 / aspect.max(1e-4);754 let inv_w = 1.0 / aspect.max(1e-4);
759 let inv_dz = 1.0 / (cam.far - cam.near).max(1e-4);755 let inv_dz = 1.0 / (cam.far - cam.near).max(1e-4);
760 [756 [
...@@ -781,6 +777,7 @@ impl Engine {...@@ -781,6 +777,7 @@ impl Engine {
781 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });777 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
782 hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 });778 hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 });
783 hash_floats.extend_from_slice(&lights.ambient);779 hash_floats.extend_from_slice(&lights.ambient);
780 hash_floats.push(lights.count as f32);
784 for dl in &lights.dirs {781 for dl in &lights.dirs {
785 hash_floats.extend_from_slice(&dl.to_light);782 hash_floats.extend_from_slice(&dl.to_light);
786 hash_floats.extend_from_slice(&dl.color);783 hash_floats.extend_from_slice(&dl.color);
crates/engine/src/scene3d/collect.rs+193-56
...@@ -1,12 +1,15 @@...@@ -1,12 +1,15 @@
1//! 3D scene graph traversal, material resolution, and 3D transform evaluation.1//! 3D scene graph traversal, material resolution, and 3D transform evaluation.
22
3use std::sync::Arc;
4
3use super::fbx::load_mesh_cached;5use super::fbx::load_mesh_cached;
6use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup};
4use super::math::{7use super::math::{
5 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,8 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
6};9};
7use super::{10use super::{
8 CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,11 CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights,
9 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, CUBE_FACES,12 ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES,
10};13};
11use model::{Comp, ExprEngine, Node, NodeId};14use model::{Comp, ExprEngine, Node, NodeId};
1215
...@@ -16,6 +19,8 @@ struct SceneOverrides {...@@ -16,6 +19,8 @@ struct SceneOverrides {
16 affected_by_lights: Option<bool>,19 affected_by_lights: Option<bool>,
17 casts_shadow: Option<bool>,20 casts_shadow: Option<bool>,
18 flip_normals: bool,21 flip_normals: bool,
22 /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals.
23 smooth_normals_deg: Option<f32>,
19 displace: Option<Displace3DSpec>,24 displace: Option<Displace3DSpec>,
20 cull_back: bool,25 cull_back: bool,
21 cull_front: bool,26 cull_front: bool,
...@@ -162,9 +167,12 @@ fn collect_scene_inner(...@@ -162,9 +167,12 @@ fn collect_scene_inner(
162 }167 }
163 "ReplaceNormals3D" => {168 "ReplaceNormals3D" => {
164 let mut next_ovr = ovr.clone();169 let mut next_ovr = ovr.clone();
165 if comp.eval_number(node, "FlipNormals", time, 0.0, expr) > 0.5 {170 if comp.eval_number(node, "Normals.Flip", time, 0.0, expr) > 0.5 {
166 next_ovr.flip_normals = !next_ovr.flip_normals;171 next_ovr.flip_normals = !next_ovr.flip_normals;
167 }172 }
173 if comp.eval_number(node, "Normals.Recompute", time, 0.0, expr).round() as i32 == 0 {
174 next_ovr.smooth_normals_deg = Some(comp.eval_number(node, "Normals.SmoothingAngle", time, 45.0, expr) as f32);
175 }
168 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {176 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
169 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);177 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
170 }178 }
...@@ -257,12 +265,20 @@ fn collect_scene_inner(...@@ -257,12 +265,20 @@ fn collect_scene_inner(
257 let vfov_rad = 2.0 * half_v.atan();265 let vfov_rad = 2.0 * half_v.atan();
258 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;266 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;
259 let far = 5000.0_f32;267 let far = 5000.0_f32;
260 cameras.push(CameraInstance { world, vfov_rad, near, far });268 cameras.push(CameraInstance {
269 name: node.name.clone(),
270 orthographic: node.static_str("ProjectionType") == Some("Orthographic"),
271 world,
272 vfov_rad,
273 near,
274 far,
275 });
261 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {276 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
262 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);277 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
263 }278 }
264 }279 }
265 "LightAmbient" => {280 "LightAmbient" => {
281 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
266 if let Some(color) = light_color(comp, node, time, expr) {282 if let Some(color) = light_color(comp, node, time, expr) {
267 for (acc, c) in lights.ambient.iter_mut().zip(color) {283 for (acc, c) in lights.ambient.iter_mut().zip(color) {
268 *acc += c;284 *acc += c;
...@@ -273,6 +289,7 @@ fn collect_scene_inner(...@@ -273,6 +289,7 @@ fn collect_scene_inner(
273 }289 }
274 }290 }
275 "LightDirectional" => {291 "LightDirectional" => {
292 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
276 if let Some(color) = light_color(comp, node, time, expr) {293 if let Some(color) = light_color(comp, node, time, expr) {
277 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!294 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
278 let dx = world[8];295 let dx = world[8];
...@@ -286,6 +303,7 @@ fn collect_scene_inner(...@@ -286,6 +303,7 @@ fn collect_scene_inner(
286 }303 }
287 }304 }
288 "LightPoint" => {305 "LightPoint" => {
306 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
289 if let Some(color) = light_color(comp, node, time, expr) {307 if let Some(color) = light_color(comp, node, time, expr) {
290 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;308 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
291 lights.points.push(PointLight {309 lights.points.push(PointLight {
...@@ -302,6 +320,7 @@ fn collect_scene_inner(...@@ -302,6 +320,7 @@ fn collect_scene_inner(
302 }320 }
303 }321 }
304 "LightSpot" => {322 "LightSpot" => {
323 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
305 if let Some(color) = light_color(comp, node, time, expr) {324 if let Some(color) = light_color(comp, node, time, expr) {
306 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;325 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
307 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;326 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
...@@ -359,8 +378,37 @@ fn collect_scene_inner(...@@ -359,8 +378,37 @@ fn collect_scene_inner(
359 start_sweep_deg: start_sw,378 start_sweep_deg: start_sw,
360 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },379 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
361 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,380 sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32,
381 top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5,
382 bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5,
362 }383 }
363 }384 }
385 "SurfaceConeInputs" => {
386 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceConeInputs.{k}"), time, d, expr);
387 let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32];
388 custom_shape(build_cone(
389 f("Radius", 1.0) as f32,
390 f("Height", 2.0) as f32,
391 sweep,
392 f("SubdivisionLevelBase", 20.0).round() as u32,
393 f("SubdivisionLevelHeight", 1.0).round() as u32,
394 f("BottomCap", 0.0) > 0.5,
395 ))
396 }
397 "SurfaceTorusInputs" => {
398 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceTorusInputs.{k}"), time, d, expr);
399 let sweep = [f("StartSweep", 0.0) as f32, f("EndSweep", 360.0) as f32];
400 custom_shape(build_torus(
401 f("Radius", 1.0) as f32,
402 f("Section", 0.5) as f32,
403 sweep,
404 f("SubdivisionLevelBase", 20.0).round() as u32,
405 f("SubdivisionLevelHeight", 20.0).round() as u32,
406 ))
407 }
408 "SurfaceIcoInputs" => {
409 let f = |k: &str, d: f64| comp.eval_number(node, &format!("SurfaceIcoInputs.{k}"), time, d, expr);
410 custom_shape(build_icosahedron(f("Size", 1.0) as f32, f("SubdivisionLevel", 0.0).round() as u32))
411 }
364 "SurfaceCubeInputs" => ShapeKind::Cube {412 "SurfaceCubeInputs" => ShapeKind::Cube {
365 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,413 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
366 sub: cube_subdivisions(comp, node, time, expr),414 sub: cube_subdivisions(comp, node, time, expr),
...@@ -518,6 +566,10 @@ fn make_mesh_instance(...@@ -518,6 +566,10 @@ fn make_mesh_instance(
518 text3d: Option<Text3DSpec>,566 text3d: Option<Text3DSpec>,
519 ovr: &SceneOverrides,567 ovr: &SceneOverrides,
520) -> MeshInstance {568) -> MeshInstance {
569 let shape = match (ovr.smooth_normals_deg, &shape) {
570 (Some(deg), s) if !matches!(s, ShapeKind::ImagePlane | ShapeKind::TextPlate { .. }) => ShapeKind::CustomMesh(Arc::new(smooth_normals(build_shape_mesh(s, 1.0), deg))),
571 _ => shape,
572 };
521 MeshInstance {573 MeshInstance {
522 world,574 world,
523 shape: ShapeKind::WithMaterialFx {575 shape: ShapeKind::WithMaterialFx {
...@@ -549,11 +601,13 @@ fn surface_scope(...@@ -549,11 +601,13 @@ fn surface_scope(
549 expr: &ExprEngine,601 expr: &ExprEngine,
550) -> Option<SceneOverrides> {602) -> Option<SceneOverrides> {
551 let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5;603 let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5;
604 let unseen = flag("Visibility.IsUnseenByCameras", 0.0);
552 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {605 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {
553 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),606 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),
554 casts_shadow: Some(flag("Lighting.IsShadowCaster", 1.0)),607 casts_shadow: Some(flag("Lighting.IsShadowCaster", 1.0)),
555 cull_back: flag("Visibility.CullBackFace", 0.0),608 // Unseen-by-cameras surfaces skip the camera pass but still cast shadows.
556 cull_front: flag("Visibility.CullFrontFace", 0.0),609 cull_back: flag("Visibility.CullBackFace", 0.0) || unseen,
610 cull_front: flag("Visibility.CullFrontFace", 0.0) || unseen,
557 ..ovr.clone()611 ..ovr.clone()
558 })612 })
559}613}
...@@ -568,6 +622,10 @@ fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option...@@ -568,6 +622,10 @@ fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option
568 (color != [0.0; 3]).then_some(color)622 (color != [0.0; 3]).then_some(color)
569}623}
570624
625fn custom_shape(mesh: (Vec<Vertex3D>, Vec<u32>)) -> ShapeKind {
626 ShapeKind::CustomMesh(Arc::new(triangle_soup(mesh)))
627}
628
571/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal.629/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal.
572fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 {630fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 {
573 comp.eval_number(node, "SurfaceCubeInputs.SubdivisionWidth", time, 10.0, expr).round() as u32631 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: &...@@ -582,6 +640,13 @@ fn apply_mtl_std(mat: &mut ResolvedMaterial, comp: &Comp, node: &Node, prefix: &
582 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);640 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);
583 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);641 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);
584 mat.receives_shadows = f("ReceivesShadows", 1.0) > 0.5;642 mat.receives_shadows = f("ReceivesShadows", 1.0) > 0.5;
643 if f("ReceivesLighting", 1.0) < 0.5 {
644 mat.unlit = true;
645 mat.fx.per_light_unlit = true;
646 }
647 if f("EnablePBRMaterial", 0.0) > 0.5 {
648 mat.fx.spec_model = SpecModel::Pbr;
649 }
585}650}
586651
587fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {652fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option<u32> {
...@@ -603,15 +668,16 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op...@@ -603,15 +668,16 @@ fn parse_wrap_mode(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Op
603 None668 None
604}669}
605670
606/// Mesh-UV -> texture-UV map for a `TextureTransformOperator`. The content is moved by671/// Mesh-UV -> texture-UV map for a UVW content transform `m` (V up, W dropped when sampling).
607/// translate * rotate * scale about the pivot in V-up image space, so sampling applies the inverse.672/// `m` moves the content, so sampling applies its inverse; `invert` swaps the two.
608fn texture_transform_uv(translate: [f32; 2], rot_rad: f32, scale: [f32; 2], pivot: [f32; 2]) -> UvAffine {673fn texture_transform_uv(m: Mat4, invert: bool) -> UvAffine {
609 let inv = |v: f32| 1.0 / if v.abs() < 1e-4 { 1e-4 } else { v };674 let sampling = if invert { m } else { mat4_inverse(m) };
610 let (sn, cs) = rot_rad.sin_cos();
611 let sample = |uv: [f32; 2]| {675 let sample = |uv: [f32; 2]| {
612 let q = [uv[0] - translate[0] - pivot[0], (1.0 - uv[1]) - translate[1] - pivot[1]];676 let (x, y) = (uv[0], 1.0 - uv[1]);
613 let r = [cs * q[0] + sn * q[1], -sn * q[0] + cs * q[1]];677 [
614 [pivot[0] + r[0] * inv(scale[0]), 1.0 - (pivot[1] + r[1] * inv(scale[1]))]678 sampling[0] * x + sampling[4] * y + sampling[12],
679 1.0 - (sampling[1] * x + sampling[5] * y + sampling[13]),
680 ]
615 };681 };
616 let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0]));682 let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0]));
617 UvAffine { m: [eu[0] - o[0], eu[1] - o[1], ev[0] - o[0], ev[1] - o[1]], t: o }683 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(...@@ -649,9 +715,14 @@ fn resolve_material_inner(
649 match n.kind.as_str() {715 match n.kind.as_str() {
650 "Texture2DOperator" => {716 "Texture2DOperator" => {
651 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));717 let tex_src = n.connected_node("Input").and_then(|s| comp.find_node(s));
718 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
652 ResolvedMaterial {719 ResolvedMaterial {
653 tex_node: tex_src,720 tex_node: tex_src,
654 fx: MaterialFx {721 fx: MaterialFx {
722 uv: texture_transform_uv(
723 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]),
724 false,
725 ),
655 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),726 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
656 ..default_mat.fx727 ..default_mat.fx
657 },728 },
...@@ -663,12 +734,10 @@ fn resolve_material_inner(...@@ -663,12 +734,10 @@ fn resolve_material_inner(
663 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));734 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));
664 let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1);735 let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1);
665 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;736 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
666 let xf = texture_transform_uv(737 let uvw = |prefix: &str, d: f64| ["U", "V", "W"].map(|a| f(&format!("{prefix}.{a}"), d));
667 [f("Translation.U", 0.0), f("Translation.V", 0.0)],738 let order = n.static_str("Rotation.RotOrder").unwrap_or("UVW").replace('U', "X").replace('V', "Y").replace('W', "Z");
668 f("Rotation.W", 0.0).to_radians(),739 let m = trs_matrix(uvw("Translation", 0.0), uvw("Rotation", 0.0), &order, uvw("Scale", 1.0), uvw("Pivot", 0.0));
669 [f("Scale.U", 1.0), f("Scale.V", 1.0)],740 let xf = texture_transform_uv(m, f("InvertTransform", 0.0) > 0.5);
670 [f("Pivot.U", 0.0), f("Pivot.V", 0.0)],
671 );
672 mat.fx.uv = xf.then(&mat.fx.uv);741 mat.fx.uv = xf.then(&mat.fx.uv);
673 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {742 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
674 mat.fx.uv_wrap = w;743 mat.fx.uv_wrap = w;
...@@ -728,12 +797,14 @@ fn resolve_material_inner(...@@ -728,12 +797,14 @@ fn resolve_material_inner(
728 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn),797 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn),
729 };798 };
730799
800 let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model };
801 let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5;
731 let mut tex_node = diff_mat.tex_node;802 let mut tex_node = diff_mat.tex_node;
732 let mut fx = MaterialFx { spec_model, ..diff_mat.fx };803 let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx };
733 if let Some(bm) = bump_mat {804 if let Some(bm) = bump_mat {
734 if tex_node.is_none() {805 if tex_node.is_none() {
735 tex_node = bm.tex_node;806 tex_node = bm.tex_node;
736 fx = MaterialFx { bump_only: true, spec_model, ..bm.fx };807 fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx };
737 }808 }
738 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };809 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
739 fx.bump_mode = bm.fx.bump_mode;810 fx.bump_mode = bm.fx.bump_mode;
...@@ -746,7 +817,7 @@ fn resolve_material_inner(...@@ -746,7 +817,7 @@ fn resolve_material_inner(
746 specular_intensity: spec_int.clamp(0.0, 4.0),817 specular_intensity: spec_int.clamp(0.0, 4.0),
747 specular_exponent: spec_exp,818 specular_exponent: spec_exp,
748 fx,819 fx,
749 unlit: false,820 unlit: !lit,
750 receives_shadows: comp.eval_number(n, "ReceivesShadows", time, 1.0, expr) > 0.5,821 receives_shadows: comp.eval_number(n, "ReceivesShadows", time, 1.0, expr) > 0.5,
751 has_material_shader: true,822 has_material_shader: true,
752 }823 }
...@@ -813,44 +884,36 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)...@@ -813,44 +884,36 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)
813 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;884 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
814 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32;885 let tz = comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr) as f32;
815886
816 let rx = (comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr) as f32).to_radians();887 let r = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Rotate.{a}"), time, 0.0, expr) as f32);
817 let ry = (comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr) as f32).to_radians();
818 let rz = (comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr) as f32).to_radians();
819 let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ");888 let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ");
820889
821 let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5;890 let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5;
822 let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32;891 let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32;
823 let sy = if scale_lock {892 let (sy, sz) = if scale_lock {
824 sx893 (sx, sx)
825 } else {
826 comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32
827 };
828 let sz = if scale_lock {
829 sx
830 } else {894 } else {
831 comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32895 (
896 comp.eval_number(node, "Transform3DOp.Scale.Y", time, 1.0, expr) as f32,
897 comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32,
898 )
832 };899 };
833900
834 let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32;901 let p = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Pivot.{a}"), time, 0.0, expr) as f32);
835 let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32;902 let m = trs_matrix([tx, ty, tz], r, rot_order, [sx, sy, sz], p);
836 let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32;903 if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m }
837904}
838 let mx = mat4_rot_x(rx);
839 let my = mat4_rot_y(ry);
840 let mz = mat4_rot_z(rz);
841 let rot = match rot_order {
842 "XZY" => mat4_mul(my, mat4_mul(mz, mx)),
843 "YXZ" => mat4_mul(mz, mat4_mul(mx, my)),
844 "YZX" => mat4_mul(mx, mat4_mul(mz, my)),
845 "ZXY" => mat4_mul(my, mat4_mul(mx, mz)),
846 "ZYX" => mat4_mul(mx, mat4_mul(my, mz)),
847 _ => mat4_mul(mz, mat4_mul(my, mx)), // XYZ default
848 };
849905
850 let t = mat4_translate(tx + px, ty + py, tz + pz);906/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first).
851 let s = mat4_scale(sx, sy, sz);907fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 {
852 let inv_p = mat4_translate(-px, -py, -pz);908 let [rx, ry, rz] = rot_deg.map(f32::to_radians);
853 mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p)))909 let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)];
910 let rot = order
911 .bytes()
912 .filter_map(|b| "XYZ".find(b as char))
913 .fold(mat4_identity(), |acc, a| mat4_mul(axes[a], acc));
914 let t = mat4_translate(translate[0] + pivot[0], translate[1] + pivot[1], translate[2] + pivot[2]);
915 let s = mat4_scale(scale[0], scale[1], scale[2]);
916 mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2]))))
854}917}
855918
856#[cfg(test)]919#[cfg(test)]
...@@ -904,7 +967,7 @@ mod tests {...@@ -904,7 +967,7 @@ mod tests {
904 RepNorm = ReplaceNormals3D {967 RepNorm = ReplaceNormals3D {
905 Inputs = {968 Inputs = {
906 SceneInput = Input { SourceOp = "RepMat", Source = "Output", },969 SceneInput = Input { SourceOp = "RepMat", Source = "Output", },
907 FlipNormals = Input { Value = 1, },970 ["Normals.Flip"] = Input { Value = 1, },
908 },971 },
909 },972 },
910 Disp1 = Displace3D {973 Disp1 = Displace3D {
...@@ -1122,6 +1185,73 @@ mod tests {...@@ -1122,6 +1185,73 @@ mod tests {
1122 format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}")1185 format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}")
1123 }1186 }
11241187
1188 #[test]
1189 fn cameras_carry_names_for_renderer_selection() {
1190 let src = comp_src(
1191 r#"A = Camera3D { }, B = Camera3D { Inputs = { ProjectionType = Input { Value = FuID { "Orthographic" }, }, }, },
1192 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "A", Source = "Output", }, SceneInput2 = Input { SourceOp = "B", Source = "Output", }, }, },"#,
1193 );
1194 let (cams, ..) = collect(&src, "M");
1195 let found: Vec<_> = cams.iter().map(|c| (c.name.as_str(), c.orthographic)).collect();
1196 assert_eq!(found, [("A", false), ("B", true)]);
1197 }
1198
1199 #[test]
1200 fn texture2d_offset_and_scale_move_content_like_a_texture_transform() {
1201 let src = comp_src(
1202 r#"Bg = Background { }, Tex = Texture2DOperator { Inputs = { UOffset = Input { Value = 0.25, }, UScale = Input { Value = 2, }, Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
1203 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Tex", Source = "MaterialOutput", }, }, },"#,
1204 );
1205 let (_, meshes, _) = collect(&src, "S");
1206 let (_, fx) = meshes[0].shape.split_fx();
1207 // Content scales 2x about the origin then moves right by 0.25: mesh u=0.75 samples texture u=0.25.
1208 assert!((fx.uv.apply([0.75, 0.0])[0] - 0.25).abs() < 1e-5);
1209 }
1210
1211 #[test]
1212 fn receives_lighting_off_is_unlit_and_lights_are_counted() {
1213 let src = comp_src(
1214 r#"Mtl = MtlBlinn { Inputs = { ReceivesLighting = Input { Value = 0, }, EnablePBRMaterial = Input { Value = 1, }, }, },
1215 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, }, },
1216 A = LightAmbient { }, P = LightPoint { }, Off = LightPoint { Inputs = { Enabled = Input { Value = 0, }, }, },
1217 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", }, }, },"#,
1218 );
1219 let (_, meshes, lights) = collect(&src, "M");
1220 let (_, fx) = meshes[0].shape.split_fx();
1221 assert!(fx.per_light_unlit && !meshes[0].affected_by_lights);
1222 assert_eq!(fx.spec_model, SpecModel::Pbr);
1223 assert_eq!(lights.count, 2);
1224 }
1225
1226 #[test]
1227 fn invert_transform_inverts_the_node_matrix() {
1228 let src = comp_src(
1229 r#"Cam = Camera3D { Inputs = { ["Transform3DOp.Translate.X"] = Input { Value = 3, }, ["Transform3DOp.InvertTransform"] = Input { Value = 1, }, }, },
1230 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "Cam", Source = "Output", }, }, },"#,
1231 );
1232 let (cams, ..) = collect(&src, "M");
1233 assert!((cams[0].world[12] + 3.0).abs() < 1e-5);
1234 }
1235
1236 #[test]
1237 fn replace_normals_recomputes_by_smoothing_angle() {
1238 let tris = |angle: f64| {
1239 let src = comp_src(&format!(
1240 r#"S = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfaceIcoInputs" }}, }}, }}, }},
1241 N = ReplaceNormals3D {{ Inputs = {{ ["Normals.SmoothingAngle"] = Input {{ Value = {angle}, }}, SceneInput = Input {{ SourceOp = "S", Source = "Output", }}, }}, }},"#
1242 ));
1243 let (_, meshes, _) = collect(&src, "N");
1244 let (ShapeKind::CustomMesh(v), _) = meshes[0].shape.split_fx() else { panic!("expected a mesh") };
1245 v.clone()
1246 };
1247 // Adjacent icosahedron faces differ by ~41.8 degrees: below that every face is flat.
1248 let flat = tris(30.0);
1249 let close = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-4);
1250 assert!(flat.chunks_exact(3).all(|t| close(t[0].normal, t[1].normal) && close(t[1].normal, t[2].normal)));
1251 let smooth = tris(90.0);
1252 assert!(smooth.chunks_exact(3).any(|t| !close(t[0].normal, t[1].normal)));
1253 }
1254
1125 #[test]1255 #[test]
1126 fn camera_vertical_aov_comes_from_default_35mm_focal_length() {1256 fn camera_vertical_aov_comes_from_default_35mm_focal_length() {
1127 // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35).1257 // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35).
...@@ -1174,20 +1304,27 @@ mod tests {...@@ -1174,20 +1304,27 @@ mod tests {
11741304
1175 #[test]1305 #[test]
1176 fn texture_transform_moves_content_about_a_bottom_left_pivot() {1306 fn texture_transform_moves_content_about_a_bottom_left_pivot() {
1307 let uvw = |t, r, s, invert| texture_transform_uv(trs_matrix(t, r, "XYZ", s, [0.0; 3]), invert);
1177 // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up).1308 // Scale 2 about the (0, 0) pivot zooms toward the bottom-left corner (V up).
1178 let zoom = texture_transform_uv([0.0, 0.0], 0.0, [2.0, 2.0], [0.0, 0.0]);1309 let zoom = uvw([0.0; 3], [0.0; 3], [2.0, 2.0, 1.0], false);
1179 let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0]));1310 let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0]));
1180 assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5);1311 assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5);
1181 assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5);1312 assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5);
11821313
1183 // Content moved right and up samples from smaller u and larger raw v (V down).1314 // Content moved right and up samples from smaller u and larger raw v (V down).
1184 let shift = texture_transform_uv([0.25, 0.1], 0.0, [1.0, 1.0], [0.0, 0.0]).apply([0.5, 0.5]);1315 let shift = uvw([0.25, 0.1, 0.0], [0.0; 3], [1.0; 3], false).apply([0.5, 0.5]);
1185 assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5);1316 assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5);
11861317
1187 // Counter-clockwise content rotation about the pivot.1318 // Counter-clockwise content rotation about the pivot.
1188 let quarter = texture_transform_uv([0.0, 0.0], std::f32::consts::FRAC_PI_2, [1.0, 1.0], [0.0, 0.0]);1319 let quarter = uvw([0.0; 3], [0.0, 0.0, 90.0], [1.0; 3], false);
1189 let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right1320 let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right
1190 assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}");1321 assert!((p[0] - 1.0).abs() < 1e-5 && (p[1] - 1.0).abs() < 1e-5, "{p:?}");
1322
1323 // Tilting about U drops W, magnifying content in V by 1/cos; InvertTransform undoes a move.
1324 let tilt = uvw([0.0; 3], [60.0, 0.0, 0.0], [1.0; 3], false).apply([0.0, 0.5]);
1325 assert!((tilt[1] - 0.75).abs() < 1e-5, "{tilt:?}");
1326 let back = uvw([0.2, 0.0, 0.0], [0.0; 3], [1.0; 3], true).apply([0.5, 0.5]);
1327 assert!((back[0] - 0.7).abs() < 1e-5, "{back:?}");
1191 }1328 }
11921329
1193 #[test]1330 #[test]
crates/engine/src/scene3d/mesh.rs+220-1
...@@ -19,7 +19,9 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte...@@ -19,7 +19,9 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte
19 start_sweep_deg,19 start_sweep_deg,
20 end_sweep_deg,20 end_sweep_deg,
21 sub_base,21 sub_base,
22 } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base),22 top_cap,
23 bottom_cap,
24 } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base, [*top_cap, *bottom_cap]),
23 ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces),25 ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces),
24 ShapeKind::CustomMesh(verts) => {26 ShapeKind::CustomMesh(verts) => {
25 let v = verts.as_ref().clone();27 let v = verts.as_ref().clone();
...@@ -149,6 +151,7 @@ fn build_cylinder(...@@ -149,6 +151,7 @@ fn build_cylinder(
149 start_sweep_deg: f32,151 start_sweep_deg: f32,
150 end_sweep_deg: f32,152 end_sweep_deg: f32,
151 sub_base: u32,153 sub_base: u32,
154 caps: [bool; 2],
152) -> (Vec<Vertex3D>, Vec<u32>) {155) -> (Vec<Vertex3D>, Vec<u32>) {
153 let seg_u = sub_base.clamp(16, 96);156 let seg_u = sub_base.clamp(16, 96);
154 let half_h = height * 0.5;157 let half_h = height * 0.5;
...@@ -181,6 +184,20 @@ fn build_cylinder(...@@ -181,6 +184,20 @@ fn build_cylinder(
181 let d = a + 2;184 let d = a + 2;
182 idx.extend_from_slice(&[a, b, d, b, c, d]);185 idx.extend_from_slice(&[a, b, d, b, c, d]);
183 }186 }
187 for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) {
188 if !cap {
189 continue;
190 }
191 let base = verts.len() as u32;
192 verts.push(Vertex3D { pos: [0.0, y, 0.0], normal: [0.0, ny, 0.0], uv: [0.5, 0.5] });
193 for iu in 0..=seg_u {
194 let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos();
195 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] });
196 }
197 for iu in 0..seg_u {
198 idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]);
199 }
200 }
184 (verts, idx)201 (verts, idx)
185}202}
186203
...@@ -204,6 +221,186 @@ fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>)...@@ -204,6 +221,186 @@ fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>)
204 (verts, idx)221 (verts, idx)
205}222}
206223
224/// Expands an indexed mesh to the triangle list `ShapeKind::CustomMesh` carries.
225pub(super) fn triangle_soup((verts, idx): (Vec<Vertex3D>, Vec<u32>)) -> Vec<Vertex3D> {
226 idx.into_iter().map(|i| verts[i as usize]).collect()
227}
228
229/// Rings run from the apex (`+Y`) down to the base; sweep and angle convention match the cylinder.
230pub(super) fn build_cone(
231 radius: f32,
232 height: f32,
233 sweep_deg: [f32; 2],
234 sub_base: u32,
235 sub_height: u32,
236 bottom_cap: bool,
237) -> (Vec<Vertex3D>, Vec<u32>) {
238 let (seg_u, seg_v) = (sub_base.clamp(3, 96), sub_height.clamp(1, 64));
239 let [a0, a1] = sweep_deg.map(f32::to_radians);
240 let slant = (height * height + radius * radius).sqrt().max(1e-6);
241 let (mut verts, mut idx) = (Vec::new(), Vec::new());
242 for iv in 0..=seg_v {
243 let t = iv as f32 / seg_v as f32;
244 for iu in 0..=seg_u {
245 let u = iu as f32 / seg_u as f32;
246 let (st, ct) = (a0 + (a1 - a0) * u).sin_cos();
247 verts.push(Vertex3D {
248 pos: [ct * radius * t, height * (0.5 - t), st * radius * t],
249 normal: [ct * height / slant, radius / slant, st * height / slant],
250 uv: [1.0 - u, t],
251 });
252 }
253 }
254 grid_indices(&mut idx, 0, seg_u, seg_v);
255 if bottom_cap {
256 let base = verts.len() as u32;
257 let center = Vertex3D { pos: [0.0, -height * 0.5, 0.0], normal: [0.0, -1.0, 0.0], uv: [0.5, 0.5] };
258 verts.push(center);
259 for iu in 0..=seg_u {
260 let (st, ct) = (a0 + (a1 - a0) * iu as f32 / seg_u as f32).sin_cos();
261 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] });
262 }
263 for iu in 0..seg_u {
264 idx.extend_from_slice(&[base, base + 1 + iu, base + 2 + iu]);
265 }
266 }
267 (verts, idx)
268}
269
270/// Tube of radius `section` swept around the `Y` axis at distance `radius`.
271pub(super) fn build_torus(
272 radius: f32,
273 section: f32,
274 sweep_deg: [f32; 2],
275 sub_base: u32,
276 sub_height: u32,
277) -> (Vec<Vertex3D>, Vec<u32>) {
278 let (seg_u, seg_v) = (sub_base.clamp(3, 128), sub_height.clamp(3, 128));
279 let [a0, a1] = sweep_deg.map(f32::to_radians);
280 let (mut verts, mut idx) = (Vec::new(), Vec::new());
281 for iv in 0..=seg_v {
282 let v = iv as f32 / seg_v as f32;
283 let (sp, cp) = (v * std::f32::consts::TAU).sin_cos();
284 for iu in 0..=seg_u {
285 let u = iu as f32 / seg_u as f32;
286 let (st, ct) = (a0 + (a1 - a0) * u).sin_cos();
287 verts.push(Vertex3D {
288 pos: [(radius + section * cp) * ct, section * sp, (radius + section * cp) * st],
289 normal: [cp * ct, sp, cp * st],
290 uv: [1.0 - u, v],
291 });
292 }
293 }
294 grid_indices(&mut idx, 0, seg_u, seg_v);
295 (verts, idx)
296}
297
298/// Icosahedron with a vertex on each `Y` pole, each triangle split in four per `level` and
299/// projected onto the sphere of circumradius `size`.
300pub(super) fn build_icosahedron(size: f32, level: u32) -> (Vec<Vertex3D>, Vec<u32>) {
301 let ring_y = 1.0 / 5.0_f32.sqrt();
302 let ring_r = 2.0 * ring_y;
303 let ring = |k: u32, y: f32, offset_deg: f32| {
304 let (s, c) = ((k as f32 * 72.0 + offset_deg).to_radians()).sin_cos();
305 [ring_r * c, y, ring_r * s]
306 };
307 let mut pts: Vec<[f32; 3]> = vec![[0.0, 1.0, 0.0], [0.0, -1.0, 0.0]];
308 pts.extend((0..5).map(|k| ring(k, ring_y, 54.0)));
309 pts.extend((0..5).map(|k| ring(k, -ring_y, 54.0 + 36.0)));
310 let (up, lo) = (|k: u32| 2 + k % 5, |k: u32| 7 + k % 5);
311 let mut tris: Vec<[[f32; 3]; 3]> = Vec::new();
312 for k in 0..5 {
313 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)]] {
314 tris.push(t.map(|i| pts[i as usize]));
315 }
316 }
317 let norm = |p: [f32; 3]| {
318 let l = (p[0] * p[0] + p[1] * p[1] + p[2] * p[2]).sqrt().max(1e-6);
319 [p[0] / l, p[1] / l, p[2] / l]
320 };
321 for _ in 0..level.min(4) {
322 tris = tris
323 .into_iter()
324 .flat_map(|[a, b, c]| {
325 let mid = |p: [f32; 3], q: [f32; 3]| norm([p[0] + q[0], p[1] + q[1], p[2] + q[2]]);
326 let (ab, bc, ca) = (mid(a, b), mid(b, c), mid(c, a));
327 [[a, ab, ca], [ab, b, bc], [ca, bc, c], [ab, bc, ca]]
328 })
329 .collect();
330 }
331 let verts: Vec<Vertex3D> = tris
332 .into_iter()
333 .flatten()
334 .map(|p| {
335 let n = norm(p);
336 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] }
337 })
338 .collect();
339 let idx = (0..verts.len() as u32).collect();
340 (verts, idx)
341}
342
343/// Fusion's `ReplaceNormals3D` recompute: each triangle corner averages (corner-angle weighted)
344/// the face normals of every triangle sharing its position within `angle_deg` of its own face.
345pub(super) fn smooth_normals((verts, idx): (Vec<Vertex3D>, Vec<u32>), angle_deg: f32) -> Vec<Vertex3D> {
346 let sub = |a: [f32; 3], b: [f32; 3]| [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
347 let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
348 let unit = |a: [f32; 3]| {
349 let l = dot(a, a).sqrt();
350 (l > 1e-12).then(|| [a[0] / l, a[1] / l, a[2] / l])
351 };
352 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]];
353 let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64);
354 let tris: Vec<[u32; 3]> = idx.chunks_exact(3).map(|t| [t[0], t[1], t[2]]).collect();
355 let face_n: Vec<Option<[f32; 3]>> = tris
356 .iter()
357 .map(|t| {
358 let p = t.map(|i| verts[i as usize].pos);
359 // Winding varies per builder; the authored vertex normals say which side is out.
360 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]))));
361 unit(cross(sub(p[1], p[0]), sub(p[2], p[0]))).map(|n| if outward < 0.0 { n.map(|c| -c) } else { n })
362 })
363 .collect();
364 // Per welded position: (triangle, interior angle at that corner).
365 let mut at: std::collections::HashMap<[i64; 3], Vec<(usize, f32)>> = std::collections::HashMap::new();
366 for (ti, t) in tris.iter().enumerate() {
367 if face_n[ti].is_none() {
368 continue;
369 }
370 let p = t.map(|i| verts[i as usize].pos);
371 for c in 0..3 {
372 let (e0, e1) = (unit(sub(p[(c + 1) % 3], p[c])), unit(sub(p[(c + 2) % 3], p[c])));
373 let angle = e0.zip(e1).map_or(0.0, |(a, b)| dot(a, b).clamp(-1.0, 1.0).acos());
374 at.entry(key(p[c])).or_default().push((ti, angle));
375 }
376 }
377 let cos_limit = angle_deg.to_radians().cos() - 1e-4;
378 let mut out = Vec::with_capacity(tris.len() * 3);
379 for (ti, t) in tris.iter().enumerate() {
380 for &i in t {
381 let mut v = verts[i as usize];
382 if let (Some(own), Some(group)) = (face_n[ti], at.get(&key(v.pos))) {
383 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]]);
384 v.normal = unit(sum).unwrap_or(own);
385 }
386 out.push(v);
387 }
388 }
389 out
390}
391
392/// Quad-grid triangulation of `(seg_u + 1) * (seg_v + 1)` vertices starting at `base`.
393fn grid_indices(idx: &mut Vec<u32>, base: u32, seg_u: u32, seg_v: u32) {
394 let row = seg_u + 1;
395 for iv in 0..seg_v {
396 for iu in 0..seg_u {
397 let a = base + iv * row + iu;
398 let (b, c, d) = (a + row, a + row + 1, a + 1);
399 idx.extend_from_slice(&[a, b, d, b, c, d]);
400 }
401 }
402}
403
207/// Unique triangle edges as a line-list index buffer.404/// Unique triangle edges as a line-list index buffer.
208pub(super) fn triangle_edges(indices: &[u32]) -> Vec<u32> {405pub(super) fn triangle_edges(indices: &[u32]) -> Vec<u32> {
209 let mut seen = std::collections::HashSet::new();406 let mut seen = std::collections::HashSet::new();
...@@ -301,6 +498,28 @@ mod tests {...@@ -301,6 +498,28 @@ mod tests {
301 assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0]));498 assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0]));
302 }499 }
303500
501 #[test]
502 fn icosahedron_has_twenty_faces_on_the_circumsphere() {
503 let (verts, idx) = build_icosahedron(2.0, 0);
504 assert_eq!(idx.len(), 20 * 3);
505 assert!(verts.iter().all(|v| (v.pos.iter().map(|c| c * c).sum::<f32>().sqrt() - 2.0).abs() < 1e-4));
506 assert_eq!(build_icosahedron(1.0, 1).1.len(), 80 * 3);
507 }
508
509 #[test]
510 fn cone_apex_is_up_and_cap_is_optional() {
511 let (open, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, false);
512 let (capped, _) = build_cone(1.0, 2.0, [0.0, 360.0], 8, 1, true);
513 assert!(open.iter().take(9).all(|v| v.pos[1] == 1.0 && v.pos[0] == 0.0));
514 assert_eq!(capped.len(), open.len() + 1 + 9);
515 }
516
517 #[test]
518 fn torus_tube_stays_within_radius_plus_section() {
519 let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8);
520 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));
521 }
522
304 #[test]523 #[test]
305 fn triangle_edges_are_deduplicated() {524 fn triangle_edges_are_deduplicated() {
306 // Two triangles sharing edge 1-2.525 // Two triangles sharing edge 1-2.
crates/engine/src/scene3d/mod.rs+15-3
...@@ -121,6 +121,9 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {...@@ -121,6 +121,9 @@ impl<K: std::hash::Hash + Eq + Copy, V: Clone> Lru<K, V> {
121121
122#[derive(Clone)]122#[derive(Clone)]
123pub struct CameraInstance {123pub struct CameraInstance {
124 /// Node name, matched against a renderer's `CameraSelector`.
125 pub name: String,
126 pub orthographic: bool,
124 pub world: Mat4,127 pub world: Mat4,
125 pub vfov_rad: f32,128 pub vfov_rad: f32,
126 pub near: f32,129 pub near: f32,
...@@ -131,7 +134,7 @@ pub struct CameraInstance {...@@ -131,7 +134,7 @@ pub struct CameraInstance {
131pub enum ShapeKind {134pub enum ShapeKind {
132 ImagePlane,135 ImagePlane,
133 Sphere { radius: f32, sub_base: u32, sub_height: u32 },136 Sphere { radius: f32, sub_base: u32, sub_height: u32 },
134 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32 },137 Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, top_cap: bool, bottom_cap: bool },
135 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },138 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },
136 /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order.139 /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order.
137 Cube { width: f32, sub: u32, faces: u8 },140 Cube { width: f32, sub: u32, faces: u8 },
...@@ -194,6 +197,8 @@ pub enum SpecModel {...@@ -194,6 +197,8 @@ pub enum SpecModel {
194 Blinn,197 Blinn,
195 Phong,198 Phong,
196 CookTorrance,199 CookTorrance,
200 /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe.
201 Pbr,
197}202}
198203
199#[derive(Clone, Copy, Debug, PartialEq)]204#[derive(Clone, Copy, Debug, PartialEq)]
...@@ -211,6 +216,8 @@ pub struct MaterialFx {...@@ -211,6 +216,8 @@ pub struct MaterialFx {
211 pub wireframe: bool,216 pub wireframe: bool,
212 pub cull_back: bool,217 pub cull_back: bool,
213 pub cull_front: bool,218 pub cull_front: bool,
219 /// Unlit surface that Fusion draws once per light, so it brightens with the light count.
220 pub per_light_unlit: bool,
214}221}
215222
216impl Default for MaterialFx {223impl Default for MaterialFx {
...@@ -225,6 +232,7 @@ impl Default for MaterialFx {...@@ -225,6 +232,7 @@ impl Default for MaterialFx {
225 wireframe: false,232 wireframe: false,
226 cull_back: false,233 cull_back: false,
227 cull_front: false,234 cull_front: false,
235 per_light_unlit: false,
228 }236 }
229 }237 }
230}238}
...@@ -241,6 +249,7 @@ impl MaterialFx {...@@ -241,6 +249,7 @@ impl MaterialFx {
241 self.wireframe.hash(h);249 self.wireframe.hash(h);
242 self.cull_back.hash(h);250 self.cull_back.hash(h);
243 self.cull_front.hash(h);251 self.cull_front.hash(h);
252 self.per_light_unlit.hash(h);
244 }253 }
245}254}
246255
...@@ -267,8 +276,9 @@ impl ShapeKind {...@@ -267,8 +276,9 @@ impl ShapeKind {
267 sub_base.hash(h);276 sub_base.hash(h);
268 sub_height.hash(h);277 sub_height.hash(h);
269 }278 }
270 ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base } => {279 ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, top_cap, bottom_cap } => {
271 2u8.hash(h);280 2u8.hash(h);
281 (*top_cap, *bottom_cap).hash(h);
272 radius.to_bits().hash(h);282 radius.to_bits().hash(h);
273 height.to_bits().hash(h);283 height.to_bits().hash(h);
274 start_sweep_deg.to_bits().hash(h);284 start_sweep_deg.to_bits().hash(h);
...@@ -386,6 +396,8 @@ pub struct SceneLights {...@@ -386,6 +396,8 @@ pub struct SceneLights {
386 pub dirs: Vec<DirLight>,396 pub dirs: Vec<DirLight>,
387 pub points: Vec<PointLight>,397 pub points: Vec<PointLight>,
388 pub spots: Vec<SpotLight>,398 pub spots: Vec<SpotLight>,
399 /// Enabled light nodes of every kind, including black ones.
400 pub count: u32,
389}401}
390402
391pub struct DrawMesh {403pub struct DrawMesh {
...@@ -946,7 +958,7 @@ impl Scene3DRenderer {...@@ -946,7 +958,7 @@ impl Scene3DRenderer {
946 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],958 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
947 light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 0.0 }],959 light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 0.0 }],
948 uv_xform: fx.uv.m,960 uv_xform: fx.uv.m,
949 uv_off_wrap: [fx.uv.t[0], fx.uv.t[1], fx.uv_wrap as f32, 0.0],961 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 }],
950 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],962 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],
951 point_pos,963 point_pos,
952 point_col,964 point_col,
crates/engine/src/scene3d/shader.rs+8-3
...@@ -44,9 +44,9 @@ pub(super) struct MeshUniform {...@@ -44,9 +44,9 @@ pub(super) struct MeshUniform {
44 pub(super) light_counts: [f32; 4],44 pub(super) light_counts: [f32; 4],
45 /// UV affine matrix, column-major `[m00, m10, m01, m11]`45 /// UV affine matrix, column-major `[m00, m10, m01, m11]`
46 pub(super) uv_xform: [f32; 4],46 pub(super) uv_xform: [f32; 4],
47 /// UV translation and wrap mode `[tx, ty, wrap, 0]`47 /// UV translation, wrap mode and unlit light-pass count `[tx, ty, wrap, passes]`
48 pub(super) uv_off_wrap: [f32; 4],48 pub(super) uv_off_wrap: [f32; 4],
49 /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance]`49 /// `[bump_scale, bump_mode, bump_only, spec_model: 0=Blinn 1=Phong 2=CookTorrance 3=Pbr]`
50 pub(super) mat_fx: [f32; 4],50 pub(super) mat_fx: [f32; 4],
51 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`51 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
52 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],52 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
...@@ -256,10 +256,13 @@ fn eval_light_contrib(...@@ -256,10 +256,13 @@ fn eval_light_contrib(
256 if (ndotl <= 0.0) {256 if (ndotl <= 0.0) {
257 return vec3<f32>(0.0);257 return vec3<f32>(0.0);
258 }258 }
259 let model = i32(u.mat_fx.w + 0.5);
260 if (model == 3) {
261 return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265);
262 }
259 var out = albedo * light_rgb * (ndotl * diffuse_vis);263 var out = albedo * light_rgb * (ndotl * diffuse_vis);
260 if (spec_int > 1e-4) {264 if (spec_int > 1e-4) {
261 let h = normalize(l + v);265 let h = normalize(l + v);
262 let model = i32(u.mat_fx.w + 0.5);
263 var lobe: f32;266 var lobe: f32;
264 if (model == 1) {267 if (model == 1) {
265 lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess);268 lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess);
...@@ -425,6 +428,8 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -425,6 +428,8 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
425 }428 }
426429
427 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);430 col = vec4<f32>(clamp(lit, vec3<f32>(0.0), vec3<f32>(1.0)) * col.a, col.a);
431 } else {
432 col = vec4<f32>(min(col.rgb * u.uv_off_wrap.w, vec3<f32>(1.0)), col.a);
428 }433 }
429 return col;434 return col;
430}435}