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 {
745745 0,
746746 );
747747
748 let is_ortho = visited_nodes
749 .iter()
750 .map(|&id| comp.node(id))
751 .find(|n| n.kind == "Camera3D")
752 .and_then(|n| n.static_str("ProjectionType"))
753 == Some("Orthographic");
748 let selector = node.static_str("CameraSelector").unwrap_or_default();
749 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());
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 {
756752 let v = crate::scene3d::mat4_inverse(cam.world);
757 let p = if is_ortho {
753 let p = if cam.orthographic {
758754 let inv_w = 1.0 / aspect.max(1e-4);
759755 let inv_dz = 1.0 / (cam.far - cam.near).max(1e-4);
760756 [
......@@ -781,6 +777,7 @@ impl Engine {
781777 hash_floats.push(if lighting_enabled { 1.0 } else { 0.0 });
782778 hash_floats.push(if shadows_enabled { 1.0 } else { 0.0 });
783779 hash_floats.extend_from_slice(&lights.ambient);
780 hash_floats.push(lights.count as f32);
784781 for dl in &lights.dirs {
785782 hash_floats.extend_from_slice(&dl.to_light);
786783 hash_floats.extend_from_slice(&dl.color);
crates/engine/src/scene3d/collect.rs+193-56
......@@ -1,12 +1,15 @@
11//! 3D scene graph traversal, material resolution, and 3D transform evaluation.
22
3use std::sync::Arc;
4
35use super::fbx::load_mesh_cached;
6use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, smooth_normals, triangle_soup};
47use super::math::{
58 mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate,
69};
710use super::{
811 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,
1013};
1114use model::{Comp, ExprEngine, Node, NodeId};
1215
......@@ -16,6 +19,8 @@ struct SceneOverrides {
1619 affected_by_lights: Option<bool>,
1720 casts_shadow: Option<bool>,
1821 flip_normals: bool,
22 /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals.
23 smooth_normals_deg: Option<f32>,
1924 displace: Option<Displace3DSpec>,
2025 cull_back: bool,
2126 cull_front: bool,
......@@ -162,9 +167,12 @@ fn collect_scene_inner(
162167 }
163168 "ReplaceNormals3D" => {
164169 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 {
166171 next_ovr.flip_normals = !next_ovr.flip_normals;
167172 }
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 }
168176 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
169177 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
170178 }
......@@ -257,12 +265,20 @@ fn collect_scene_inner(
257265 let vfov_rad = 2.0 * half_v.atan();
258266 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;
259267 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 });
261276 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
262277 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
263278 }
264279 }
265280 "LightAmbient" => {
281 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
266282 if let Some(color) = light_color(comp, node, time, expr) {
267283 for (acc, c) in lights.ambient.iter_mut().zip(color) {
268284 *acc += c;
......@@ -273,6 +289,7 @@ fn collect_scene_inner(
273289 }
274290 }
275291 "LightDirectional" => {
292 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
276293 if let Some(color) = light_color(comp, node, time, expr) {
277294 // Default Fusion LightDirectional shines along -Z => direction TO light is +Z transformed by world rotation!
278295 let dx = world[8];
......@@ -286,6 +303,7 @@ fn collect_scene_inner(
286303 }
287304 }
288305 "LightPoint" => {
306 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
289307 if let Some(color) = light_color(comp, node, time, expr) {
290308 let decay_type = comp.eval_number(node, "DecayType", time, 0.0, expr) as f32;
291309 lights.points.push(PointLight {
......@@ -302,6 +320,7 @@ fn collect_scene_inner(
302320 }
303321 }
304322 "LightSpot" => {
323 lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32;
305324 if let Some(color) = light_color(comp, node, time, expr) {
306325 let cone_deg = comp.eval_number(node, "ConeAngle", time, 40.0, expr) as f32;
307326 let penumbra_deg = comp.eval_number(node, "PenumbraAngle", time, 0.0, expr) as f32;
......@@ -359,8 +378,37 @@ fn collect_scene_inner(
359378 start_sweep_deg: start_sw,
360379 end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw },
361380 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,
362383 }
363384 }
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 }
364412 "SurfaceCubeInputs" => ShapeKind::Cube {
365413 width: comp.eval_number(node, "SurfaceCubeInputs.Width", time, 1.0, expr) as f32,
366414 sub: cube_subdivisions(comp, node, time, expr),
......@@ -518,6 +566,10 @@ fn make_mesh_instance(
518566 text3d: Option<Text3DSpec>,
519567 ovr: &SceneOverrides,
520568) -> 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 };
521573 MeshInstance {
522574 world,
523575 shape: ShapeKind::WithMaterialFx {
......@@ -549,11 +601,13 @@ fn surface_scope(
549601 expr: &ExprEngine,
550602) -> Option<SceneOverrides> {
551603 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);
552605 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {
553606 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),
554607 casts_shadow: Some(flag("Lighting.IsShadowCaster", 1.0)),
555 cull_back: flag("Visibility.CullBackFace", 0.0),
556 cull_front: flag("Visibility.CullFrontFace", 0.0),
608 // Unseen-by-cameras surfaces skip the camera pass but still cast shadows.
609 cull_back: flag("Visibility.CullBackFace", 0.0) || unseen,
610 cull_front: flag("Visibility.CullFrontFace", 0.0) || unseen,
557611 ..ovr.clone()
558612 })
559613}
......@@ -568,6 +622,10 @@ fn light_color(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Option
568622 (color != [0.0; 3]).then_some(color)
569623}
570624
625fn custom_shape(mesh: (Vec<Vertex3D>, Vec<u32>)) -> ShapeKind {
626 ShapeKind::CustomMesh(Arc::new(triangle_soup(mesh)))
627}
628
571629/// Cells per cube edge; Fusion's cube keeps all three subdivision counts equal.
572630fn cube_subdivisions(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> u32 {
573631 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: &
582640 mat.specular_intensity = f("Specular.Intensity", 1.0).clamp(0.0, 4.0);
583641 mat.specular_exponent = f("Specular.Exponent", 50.0).max(1.0);
584642 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 }
585650}
586651
587652fn 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
603668 None
604669}
605670
606/// Mesh-UV -> texture-UV map for a `TextureTransformOperator`. The content is moved by
607/// translate * rotate * scale about the pivot in V-up image space, so sampling applies the inverse.
608fn texture_transform_uv(translate: [f32; 2], rot_rad: f32, scale: [f32; 2], pivot: [f32; 2]) -> UvAffine {
609 let inv = |v: f32| 1.0 / if v.abs() < 1e-4 { 1e-4 } else { v };
610 let (sn, cs) = rot_rad.sin_cos();
671/// Mesh-UV -> texture-UV map for a UVW content transform `m` (V up, W dropped when sampling).
672/// `m` moves the content, so sampling applies its inverse; `invert` swaps the two.
673fn texture_transform_uv(m: Mat4, invert: bool) -> UvAffine {
674 let sampling = if invert { m } else { mat4_inverse(m) };
611675 let sample = |uv: [f32; 2]| {
612 let q = [uv[0] - translate[0] - pivot[0], (1.0 - uv[1]) - translate[1] - pivot[1]];
613 let r = [cs * q[0] + sn * q[1], -sn * q[0] + cs * q[1]];
614 [pivot[0] + r[0] * inv(scale[0]), 1.0 - (pivot[1] + r[1] * inv(scale[1]))]
676 let (x, y) = (uv[0], 1.0 - uv[1]);
677 [
678 sampling[0] * x + sampling[4] * y + sampling[12],
679 1.0 - (sampling[1] * x + sampling[5] * y + sampling[13]),
680 ]
615681 };
616682 let (o, eu, ev) = (sample([0.0, 0.0]), sample([1.0, 0.0]), sample([0.0, 1.0]));
617683 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(
649715 match n.kind.as_str() {
650716 "Texture2DOperator" => {
651717 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;
652719 ResolvedMaterial {
653720 tex_node: tex_src,
654721 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 ),
655726 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),
656727 ..default_mat.fx
657728 },
......@@ -663,12 +734,10 @@ fn resolve_material_inner(
663734 let inner_id = n.connected_node("MaterialInput").and_then(|s| comp.find_node(s));
664735 let mut mat = resolve_material_inner(comp, inner_id, time, expr, visited, depth + 1);
665736 let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32;
666 let xf = texture_transform_uv(
667 [f("Translation.U", 0.0), f("Translation.V", 0.0)],
668 f("Rotation.W", 0.0).to_radians(),
669 [f("Scale.U", 1.0), f("Scale.V", 1.0)],
670 [f("Pivot.U", 0.0), f("Pivot.V", 0.0)],
671 );
737 let uvw = |prefix: &str, d: f64| ["U", "V", "W"].map(|a| f(&format!("{prefix}.{a}"), d));
738 let order = n.static_str("Rotation.RotOrder").unwrap_or("UVW").replace('U', "X").replace('V', "Y").replace('W', "Z");
739 let m = trs_matrix(uvw("Translation", 0.0), uvw("Rotation", 0.0), &order, uvw("Scale", 1.0), uvw("Pivot", 0.0));
740 let xf = texture_transform_uv(m, f("InvertTransform", 0.0) > 0.5);
672741 mat.fx.uv = xf.then(&mat.fx.uv);
673742 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
674743 mat.fx.uv_wrap = w;
......@@ -728,12 +797,14 @@ fn resolve_material_inner(
728797 _ => (comp.eval_number(n, "Specular.Exponent", time, 50.0, expr).max(1.0) as f32, SpecModel::Blinn),
729798 };
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;
731802 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 };
733804 if let Some(bm) = bump_mat {
734805 if tex_node.is_none() {
735806 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 };
737808 }
738809 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
739810 fx.bump_mode = bm.fx.bump_mode;
......@@ -746,7 +817,7 @@ fn resolve_material_inner(
746817 specular_intensity: spec_int.clamp(0.0, 4.0),
747818 specular_exponent: spec_exp,
748819 fx,
749 unlit: false,
820 unlit: !lit,
750821 receives_shadows: comp.eval_number(n, "ReceivesShadows", time, 1.0, expr) > 0.5,
751822 has_material_shader: true,
752823 }
......@@ -813,44 +884,36 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)
813884 let ty = comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr) as f32;
814885 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();
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();
887 let r = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Rotate.{a}"), time, 0.0, expr) as f32);
819888 let rot_order = node.static_str("Transform3DOp.Rotate.RotOrder").unwrap_or("XYZ");
820889
821890 let scale_lock = comp.eval_number(node, "Transform3DOp.ScaleLock", time, 1.0, expr) > 0.5;
822891 let sx = comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr) as f32;
823 let sy = if scale_lock {
824 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
892 let (sy, sz) = if scale_lock {
893 (sx, sx)
830894 } else {
831 comp.eval_number(node, "Transform3DOp.Scale.Z", time, 1.0, expr) as f32
895 (
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 )
832899 };
833900
834 let px = comp.eval_number(node, "Transform3DOp.Pivot.X", time, 0.0, expr) as f32;
835 let py = comp.eval_number(node, "Transform3DOp.Pivot.Y", time, 0.0, expr) as f32;
836 let pz = comp.eval_number(node, "Transform3DOp.Pivot.Z", time, 0.0, expr) as f32;
837
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 };
901 let p = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Pivot.{a}"), time, 0.0, expr) as f32);
902 let m = trs_matrix([tx, ty, tz], r, rot_order, [sx, sy, sz], p);
903 if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m }
904}
849905
850 let t = mat4_translate(tx + px, ty + py, tz + pz);
851 let s = mat4_scale(sx, sy, sz);
852 let inv_p = mat4_translate(-px, -py, -pz);
853 mat4_mul(t, mat4_mul(rot, mat4_mul(s, inv_p)))
906/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first).
907fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 {
908 let [rx, ry, rz] = rot_deg.map(f32::to_radians);
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]))))
854917}
855918
856919#[cfg(test)]
......@@ -904,7 +967,7 @@ mod tests {
904967 RepNorm = ReplaceNormals3D {
905968 Inputs = {
906969 SceneInput = Input { SourceOp = "RepMat", Source = "Output", },
907 FlipNormals = Input { Value = 1, },
970 ["Normals.Flip"] = Input { Value = 1, },
908971 },
909972 },
910973 Disp1 = Displace3D {
......@@ -1122,6 +1185,73 @@ mod tests {
11221185 format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}")
11231186 }
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
11251255 #[test]
11261256 fn camera_vertical_aov_comes_from_default_35mm_focal_length() {
11271257 // Serialized AoV is ignored: 35mm on a 1" gate gives 2*atan(12.7/35).
......@@ -1174,20 +1304,27 @@ mod tests {
11741304
11751305 #[test]
11761306 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);
11771308 // 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);
11791310 let (bl, tr) = (zoom.apply([0.0, 1.0]), zoom.apply([1.0, 0.0]));
11801311 assert!(bl[0].abs() < 1e-5 && (bl[1] - 1.0).abs() < 1e-5);
11811312 assert!((tr[0] - 0.5).abs() < 1e-5 && (tr[1] - 0.5).abs() < 1e-5);
11821313
11831314 // 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]);
11851316 assert!((shift[0] - 0.25).abs() < 1e-5 && (shift[1] - 0.6).abs() < 1e-5);
11861317
11871318 // 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);
11891320 let p = quarter.apply([0.0, 0.0]); // top-left corner samples from the content to its right
11901321 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:?}");
11911328 }
11921329
11931330 #[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
1919 start_sweep_deg,
2020 end_sweep_deg,
2121 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]),
2325 ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces),
2426 ShapeKind::CustomMesh(verts) => {
2527 let v = verts.as_ref().clone();
......@@ -149,6 +151,7 @@ fn build_cylinder(
149151 start_sweep_deg: f32,
150152 end_sweep_deg: f32,
151153 sub_base: u32,
154 caps: [bool; 2],
152155) -> (Vec<Vertex3D>, Vec<u32>) {
153156 let seg_u = sub_base.clamp(16, 96);
154157 let half_h = height * 0.5;
......@@ -181,6 +184,20 @@ fn build_cylinder(
181184 let d = a + 2;
182185 idx.extend_from_slice(&[a, b, d, b, c, d]);
183186 }
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 }
184201 (verts, idx)
185202}
186203
......@@ -204,6 +221,186 @@ fn build_cube(width: f32, sub: u32, faces_mask: u8) -> (Vec<Vertex3D>, Vec<u32>)
204221 (verts, idx)
205222}
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
207404/// Unique triangle edges as a line-list index buffer.
208405pub(super) fn triangle_edges(indices: &[u32]) -> Vec<u32> {
209406 let mut seen = std::collections::HashSet::new();
......@@ -301,6 +498,28 @@ mod tests {
301498 assert!(front.iter().all(|v| v.normal == [0.0, 0.0, 1.0]));
302499 }
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
304523 #[test]
305524 fn triangle_edges_are_deduplicated() {
306525 // 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> {
121121
122122#[derive(Clone)]
123123pub struct CameraInstance {
124 /// Node name, matched against a renderer's `CameraSelector`.
125 pub name: String,
126 pub orthographic: bool,
124127 pub world: Mat4,
125128 pub vfov_rad: f32,
126129 pub near: f32,
......@@ -131,7 +134,7 @@ pub struct CameraInstance {
131134pub enum ShapeKind {
132135 ImagePlane,
133136 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 },
135138 Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 },
136139 /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order.
137140 Cube { width: f32, sub: u32, faces: u8 },
......@@ -194,6 +197,8 @@ pub enum SpecModel {
194197 Blinn,
195198 Phong,
196199 CookTorrance,
200 /// `EnablePBRMaterial`: diffuse-only lights at 1/pi, no specular lobe.
201 Pbr,
197202}
198203
199204#[derive(Clone, Copy, Debug, PartialEq)]
......@@ -211,6 +216,8 @@ pub struct MaterialFx {
211216 pub wireframe: bool,
212217 pub cull_back: bool,
213218 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,
214221}
215222
216223impl Default for MaterialFx {
......@@ -225,6 +232,7 @@ impl Default for MaterialFx {
225232 wireframe: false,
226233 cull_back: false,
227234 cull_front: false,
235 per_light_unlit: false,
228236 }
229237 }
230238}
......@@ -241,6 +249,7 @@ impl MaterialFx {
241249 self.wireframe.hash(h);
242250 self.cull_back.hash(h);
243251 self.cull_front.hash(h);
252 self.per_light_unlit.hash(h);
244253 }
245254}
246255
......@@ -267,8 +276,9 @@ impl ShapeKind {
267276 sub_base.hash(h);
268277 sub_height.hash(h);
269278 }
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 } => {
271280 2u8.hash(h);
281 (*top_cap, *bottom_cap).hash(h);
272282 radius.to_bits().hash(h);
273283 height.to_bits().hash(h);
274284 start_sweep_deg.to_bits().hash(h);
......@@ -386,6 +396,8 @@ pub struct SceneLights {
386396 pub dirs: Vec<DirLight>,
387397 pub points: Vec<PointLight>,
388398 pub spots: Vec<SpotLight>,
399 /// Enabled light nodes of every kind, including black ones.
400 pub count: u32,
389401}
390402
391403pub struct DrawMesh {
......@@ -946,7 +958,7 @@ impl Scene3DRenderer {
946958 cam_pos: [cam_pos[0], cam_pos[1], cam_pos[2], 0.0],
947959 light_counts: [n_pt as f32, n_sp as f32, n_dir as f32, if m.receives_shadows { 1.0 } else { 0.0 }],
948960 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 }],
950962 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],
951963 point_pos,
952964 point_col,
crates/engine/src/scene3d/shader.rs+8-3
......@@ -44,9 +44,9 @@ pub(super) struct MeshUniform {
4444 pub(super) light_counts: [f32; 4],
4545 /// UV affine matrix, column-major `[m00, m10, m01, m11]`
4646 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]`
4848 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]`
5050 pub(super) mat_fx: [f32; 4],
5151 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
5252 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
......@@ -256,10 +256,13 @@ fn eval_light_contrib(
256256 if (ndotl <= 0.0) {
257257 return vec3<f32>(0.0);
258258 }
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 }
259263 var out = albedo * light_rgb * (ndotl * diffuse_vis);
260264 if (spec_int > 1e-4) {
261265 let h = normalize(l + v);
262 let model = i32(u.mat_fx.w + 0.5);
263266 var lobe: f32;
264267 if (model == 1) {
265268 lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess);
......@@ -425,6 +428,8 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
425428 }
426429
427430 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);
428433 }
429434 return col;
430435}