authoravatarclover caruso<git@paperclover.net>2026-12-01 10:03:31-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 10:52:45-08:00
log472baaeb7f0c565a1022bd0ff0a68630f7f6c52c
treef2b0696c1d77f9a3241b5dd0190851ed9cf317e9
parent9b88f4b2d51db38bda7ec0c493c056dda5dbd14d
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Wave 20A: fix 3D node parity across Duplicate3D, Displace3D, BumpMap, Camera3D, Override3D, Text3D, ReplaceMaterial3D, Merge3D, and Renderer3D


4 files changed, 652 insertions(+), 93 deletions(-)

crates/engine/src/eval/text_3d.rs+179-3
...@@ -25,6 +25,7 @@ struct ResolvedTextInputs {...@@ -25,6 +25,7 @@ struct ResolvedTextInputs {
25 write_start: f32,25 write_start: f32,
26 write_end: f32,26 write_end: f32,
27 shear_x: f32,27 shear_x: f32,
28 char_size_x: f32,
28 cls_rules: Vec<StyledClsRule>,29 cls_rules: Vec<StyledClsRule>,
29 soft_fill: [f32; 3],30 soft_fill: [f32; 3],
30 soft_outline: [f32; 3],31 soft_outline: [f32; 3],
...@@ -48,7 +49,7 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp...@@ -48,7 +49,7 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
48 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned();49 let font_family = node.static_str("Font").unwrap_or("Helvetica Neue").to_owned();
49 let font_style = node.static_str("Style").unwrap_or("Regular").to_owned();50 let font_style = node.static_str("Style").unwrap_or("Regular").to_owned();
50 let raw_size = comp.eval_number(node, "Size", time, if is_text3d { 1.0 } else { 0.08 }, expr) as f32;51 let raw_size = comp.eval_number(node, "Size", time, if is_text3d { 1.0 } else { 0.08 }, expr) as f32;
51 let size_norm = if is_text3d { raw_size * 0.25 } else { raw_size };52 let size_norm = if is_text3d { raw_size * 0.20 } else { raw_size };
52 let tracking = comp.eval_number(node, "CharacterSpacing", time, 1.0, expr) as f32;53 let tracking = comp.eval_number(node, "CharacterSpacing", time, 1.0, expr) as f32;
53 let line_spacing = comp.eval_number(node, "LineSpacing", time, 1.0, expr) as f32;54 let line_spacing = comp.eval_number(node, "LineSpacing", time, 1.0, expr) as f32;
54 let center = if is_text3d {55 let center = if is_text3d {
...@@ -84,6 +85,11 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp...@@ -84,6 +85,11 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
84 let write_start = comp.eval_number(node, "Start", time, 0.0, expr) as f32;85 let write_start = comp.eval_number(node, "Start", time, 0.0, expr) as f32;
85 let write_end = comp.eval_number(node, "End", time, 1.0, expr) as f32;86 let write_end = comp.eval_number(node, "End", time, 1.0, expr) as f32;
86 let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, expr) as f32;87 let shear_x = comp.eval_number(node, "CharacterShearX", time, 0.0, expr) as f32;
88 let char_size_x = if is_text3d {
89 comp.eval_number(node, "CharacterSizeX", time, 1.0, expr).max(0.0) as f32
90 } else {
91 1.0
92 };
8793
88 let soft1_on = comp.eval_number(node, "Softness1", time, 1.0, expr) > 0.5;94 let soft1_on = comp.eval_number(node, "Softness1", time, 1.0, expr) > 0.5;
89 let soft2_on = comp.eval_number(node, "Softness2", time, 1.0, expr) > 0.5;95 let soft2_on = comp.eval_number(node, "Softness2", time, 1.0, expr) > 0.5;
...@@ -133,6 +139,7 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp...@@ -133,6 +139,7 @@ fn resolve_text_inputs(comp: &Comp, node: &Node, time: f64, is_text3d: bool, exp
133 write_start,139 write_start,
134 write_end,140 write_end,
135 shear_x,141 shear_x,
142 char_size_x,
136 cls_rules,143 cls_rules,
137 soft_fill,144 soft_fill,
138 soft_outline,145 soft_outline,
...@@ -204,6 +211,96 @@ impl ResolvedTextInputs {...@@ -204,6 +211,96 @@ impl ResolvedTextInputs {
204 }211 }
205}212}
206213
214/// Scales individual character spans horizontally about each glyph's center (`Text3D.CharacterSizeX`).
215fn scale_text_chars_x(
216 tex_size: [u32; 2],
217 origin: [i32; 2],
218 canvas: [u32; 2],
219 pixels: Vec<u8>,
220 char_sx: f32,
221) -> ([u32; 2], [i32; 2], Vec<u8>) {
222 let tw = tex_size[0] as usize;
223 let th = tex_size[1] as usize;
224 if tw == 0 || th == 0 || pixels.len() < tw * th * 4 || char_sx <= 1e-4 {
225 return (tex_size, origin, pixels);
226 }
227 let row_has: Vec<bool> = (0..th)
228 .map(|y| (0..tw).any(|x| pixels[(y * tw + x) * 4 + 3] > 0))
229 .collect();
230 let mut spans: Vec<(usize, usize, usize, usize)> = Vec::new();
231 let mut y = 0;
232 while y < th {
233 if !row_has[y] {
234 y += 1;
235 continue;
236 }
237 let y0 = y;
238 while y < th && row_has[y] {
239 y += 1;
240 }
241 let y1 = y - 1;
242 let mut x = 0;
243 while x < tw {
244 let has_col = (y0..=y1).any(|ry| pixels[(ry * tw + x) * 4 + 3] > 0);
245 if !has_col {
246 x += 1;
247 continue;
248 }
249 let x0 = x;
250 while x < tw && (y0..=y1).any(|ry| pixels[(ry * tw + x) * 4 + 3] > 0) {
251 x += 1;
252 }
253 spans.push((x0, x - 1, y0, y1));
254 }
255 }
256 if spans.is_empty() {
257 return (tex_size, origin, pixels);
258 }
259 let cw = canvas[0] as i32;
260 let mut out_x0 = origin[0];
261 let mut out_x1 = origin[0] + tw as i32;
262 for &(x0, x1, _, _) in &spans {
263 let cx = origin[0] as f32 + (x0 + x1 + 1) as f32 * 0.5;
264 let hw = (x1 - x0 + 1) as f32 * 0.5 * char_sx + 1.0;
265 out_x0 = out_x0.min((cx - hw).floor() as i32);
266 out_x1 = out_x1.max((cx + hw).ceil() as i32);
267 }
268 out_x0 = out_x0.clamp(0, cw);
269 out_x1 = out_x1.clamp(out_x0 + 1, cw);
270 let out_w = (out_x1 - out_x0) as usize;
271 let mut out = vec![0u8; out_w * th * 4];
272 for &(x0, x1, y0, y1) in &spans {
273 let span_cx = (x0 + x1 + 1) as f32 * 0.5;
274 let cx_canvas = origin[0] as f32 + span_cx;
275 let hw = (x1 - x0 + 1) as f32 * 0.5 * char_sx + 1.0;
276 let dx0 = ((cx_canvas - hw).floor() as i32 - out_x0).max(0) as usize;
277 let dx1 = ((cx_canvas + hw).ceil() as i32 - out_x0).min(out_w as i32) as usize;
278 for ry in y0..=y1 {
279 for dx in dx0..dx1 {
280 let gx = (out_x0 + dx as i32) as f32 + 0.5;
281 let sx = (gx - cx_canvas) / char_sx + span_cx - 0.5;
282 let i0 = sx.floor() as isize;
283 let f = sx - i0 as f32;
284 let sample = |ix: isize, c: usize| -> f32 {
285 if ix < x0 as isize || ix > x1 as isize {
286 0.0
287 } else {
288 pixels[(ry * tw + ix as usize) * 4 + c] as f32
289 }
290 };
291 let dst_off = (ry * out_w + dx) * 4;
292 for c in 0..4 {
293 let v = (sample(i0, c) * (1.0 - f) + sample(i0 + 1, c) * f).round().clamp(0.0, 255.0) as u8;
294 if v > out[dst_off + c] {
295 out[dst_off + c] = v;
296 }
297 }
298 }
299 }
300 }
301 ([out_w as u32, tex_size[1]], [out_x0, origin[1]], out)
302}
303
207impl Engine {304impl Engine {
208 #[allow(clippy::too_many_arguments)]305 #[allow(clippy::too_many_arguments)]
209 pub(super) fn eval_p_render(306 pub(super) fn eval_p_render(
...@@ -386,6 +483,7 @@ impl Engine {...@@ -386,6 +483,7 @@ impl Engine {
386 ti.outline_rgba[0], ti.outline_rgba[1], ti.outline_rgba[2], ti.outline_rgba[3], ti.elem2_opacity,483 ti.outline_rgba[0], ti.outline_rgba[1], ti.outline_rgba[2], ti.outline_rgba[3], ti.elem2_opacity,
387 ti.outline_thickness, ti.border_ext_h, ti.border_ext_v, ti.border_round,484 ti.outline_thickness, ti.border_ext_h, ti.border_ext_v, ti.border_round,
388 ti.border_offset[0], ti.border_offset[1], ti.write_start, ti.write_end, ti.shear_x,485 ti.border_offset[0], ti.border_offset[1], ti.write_start, ti.write_end, ti.shear_x,
486 ti.char_size_x,
389 ti.soft_fill[0], ti.soft_fill[1], ti.soft_fill[2],487 ti.soft_fill[0], ti.soft_fill[1], ti.soft_fill[2],
390 ti.soft_outline[0], ti.soft_outline[1], ti.soft_outline[2],488 ti.soft_outline[0], ti.soft_outline[1], ti.soft_outline[2],
391 ] {489 ] {
...@@ -411,7 +509,7 @@ impl Engine {...@@ -411,7 +509,7 @@ impl Engine {
411 };509 };
412 let rich = ti.as_rich_params();510 let rich = ti.as_rich_params();
413 let has_soft = ti.soft_fill != [0.0; 3] || ti.soft_outline != [0.0; 3];511 let has_soft = ti.soft_fill != [0.0; 3] || ti.soft_outline != [0.0; 3];
414 let (tex_size, origin, mut pixels) = if !is_text3d && ti.cls_rules.is_empty() && !has_soft {512 let (tex_size, origin, pixels) = if !is_text3d && ti.cls_rules.is_empty() && !has_soft {
415 let is_text_outline = ti.outline_enabled && ti.elem2_shape != 2;513 let is_text_outline = ti.outline_enabled && ti.elem2_shape != 2;
416 let outline_width_px = if is_text_outline && ti.outline_thickness > 1e-4 {514 let outline_width_px = if is_text_outline && ti.outline_thickness > 1e-4 {
417 (ti.outline_thickness * size_px).clamp(2.0, 56.0)515 (ti.outline_thickness * size_px).clamp(2.0, 56.0)
...@@ -443,6 +541,11 @@ impl Engine {...@@ -443,6 +541,11 @@ impl Engine {
443 } else {541 } else {
444 crate::text_engine::rasterize_text_plus_rich(size, &rich, border_pad_px)542 crate::text_engine::rasterize_text_plus_rich(size, &rich, border_pad_px)
445 };543 };
544 let (tex_size, origin, mut pixels) = if is_text3d && (ti.char_size_x - 1.0).abs() > 1e-4 {
545 scale_text_chars_x(tex_size, origin, size, pixels, ti.char_size_x)
546 } else {
547 (tex_size, origin, pixels)
548 };
446 let outline_rgba = rich.outline_rgba;549 let outline_rgba = rich.outline_rgba;
447 let elem2_opacity = ti.elem2_opacity;550 let elem2_opacity = ti.elem2_opacity;
448 let border_level = ti.border_level;551 let border_level = ti.border_level;
...@@ -748,7 +851,12 @@ impl Engine {...@@ -748,7 +851,12 @@ impl Engine {
748 let selector = node.static_str("CameraSelector").unwrap_or_default();851 let selector = node.static_str("CameraSelector").unwrap_or_default();
749 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());852 let selected_camera = cameras.iter().find(|c| c.name == selector).or(cameras.first());
750853
751 let (view, proj, cam_pos, cam_far) = if let Some(cam) = selected_camera {854 let (view, mut proj, cam_pos, cam_far) = if let Some(cam) = selected_camera {
855 if cam.near >= cam.far || (!cam.orthographic && cam.near <= 0.0) {
856 let mut empty = create_texture(&self.device, size, 0);
857 empty.tex_scale = tex_scale;
858 return empty;
859 }
752 let v = crate::scene3d::mat4_inverse(cam.world);860 let v = crate::scene3d::mat4_inverse(cam.world);
753 let p = if cam.orthographic {861 let p = if cam.orthographic {
754 let inv_w = 1.0 / aspect.max(1e-4);862 let inv_w = 1.0 / aspect.max(1e-4);
...@@ -768,6 +876,18 @@ impl Engine {...@@ -768,6 +876,18 @@ impl Engine {
768 let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0);876 let p = crate::scene3d::mat4_perspective_wgpu(45.0_f32.to_radians(), aspect, 0.05, 5000.0);
769 (v, p, [0.0, 0.0, 5.0], 5000.0)877 (v, p, [0.0, 0.0, 5.0], 5000.0)
770 };878 };
879 let lock_os = comp.eval_number(node, "LockOverscanXY", time, 1.0, &self.expr) > 0.5;
880 let os_main = comp.eval_number(node, "Overscan", time, 1.0, &self.expr).max(1e-4) as f32;
881 let (osx, osy) = if lock_os {
882 (os_main, os_main)
883 } else {
884 (
885 comp.eval_number(node, "OverscanX", time, 1.0, &self.expr).max(1e-4) as f32,
886 comp.eval_number(node, "OverscanY", time, 1.0, &self.expr).max(1e-4) as f32,
887 )
888 };
889 proj[0] /= osx;
890 proj[5] /= osy;
771 let view_proj = crate::scene3d::mat4_mul(proj, view);891 let view_proj = crate::scene3d::mat4_mul(proj, view);
772892
773 let mut draw_meshes = Vec::with_capacity(mesh_specs.len());893 let mut draw_meshes = Vec::with_capacity(mesh_specs.len());
...@@ -858,12 +978,18 @@ impl Engine {...@@ -858,12 +978,18 @@ impl Engine {
858 } else {978 } else {
859 ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats))979 ms.material_node.map(|mid| self.eval_node(comp, mid, time, enc, visiting, stats))
860 };980 };
981 let bump_tex = match ms.bump_node {
982 Some(bid) if Some(bid) == ms.material_node => tex.clone(),
983 Some(bid) => Some(self.eval_node(comp, bid, time, enc, visiting, stats)),
984 None => None,
985 };
861 let disp_entry = ms.displace.as_ref().map(|ds| {986 let disp_entry = ms.displace.as_ref().map(|ds| {
862 let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats);987 let dtex = self.eval_node(comp, ds.input_node, time, enc, visiting, stats);
863 (dtex, ds.scale, ds.bias, ds.channel)988 (dtex, ds.scale, ds.bias, ds.channel)
864 });989 });
865 mesh_shape.hash_into(&mut h_scene);990 mesh_shape.hash_into(&mut h_scene);
866 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));991 upstream_hashes.push(tex.as_ref().map_or(0, |t| t.content_hash));
992 upstream_hashes.push(bump_tex.as_ref().map_or(0, |t| t.content_hash));
867 upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash));993 upstream_hashes.push(disp_entry.as_ref().map_or(0, |(t, _, _, _)| t.content_hash));
868 hash_floats.extend_from_slice(&ms.world);994 hash_floats.extend_from_slice(&ms.world);
869 hash_floats.extend_from_slice(&diffuse_col);995 hash_floats.extend_from_slice(&diffuse_col);
...@@ -884,6 +1010,7 @@ impl Engine {...@@ -884,6 +1010,7 @@ impl Engine {
884 shape: mesh_shape,1010 shape: mesh_shape,
885 custom_mesh_key,1011 custom_mesh_key,
886 tex,1012 tex,
1013 bump_tex,
887 diffuse_col,1014 diffuse_col,
888 specular_col: ms.specular_col,1015 specular_col: ms.specular_col,
889 specular_intensity: ms.specular_intensity,1016 specular_intensity: ms.specular_intensity,
...@@ -1225,4 +1352,53 @@ Composition {...@@ -1225,4 +1352,53 @@ Composition {
1225 "BorderFill Opacity2=0.5 should yield ~128 alpha, got {box_alpha}"1352 "BorderFill Opacity2=0.5 should yield ~128 alpha, got {box_alpha}"
1226 );1353 );
1227 }1354 }
1355
1356 #[test]
1357 fn camera_near_ge_far_renders_empty_and_overscan_shrinks_coverage() {
1358 let make_ren = |near: f32, overscan: f32| {
1359 let src = format!(
1360 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
1361 Sph = Shape3D {{ Inputs = {{ Shape = Input {{ Value = FuID {{ "SurfaceSphereInputs" }}, }}, }}, }},
1362 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 3.0, }}, PerspNearClip = Input {{ Value = {near}, }}, PerspFarClip = Input {{ Value = 100.0, }}, }}, }},
1363 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "Sph", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},
1364 R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 64, }}, Height = Input {{ Value = 64, }}, Overscan = Input {{ Value = {overscan}, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }},
1365 }} }}"#
1366 );
1367 let comp = Comp::from_fusion_str(&src).unwrap();
1368 let mut eng = Engine::new_headless().ok()?;
1369 let r = comp.find_node("R").unwrap();
1370 let (tex, _) = eng.evaluate(&comp, r, 0.0);
1371 eng.readback_rgba(&tex).ok()
1372 };
1373 let (Some(empty), Some(normal), Some(wide)) = (make_ren(200.0, 1.0), make_ren(0.1, 1.0), make_ren(0.1, 2.5)) else {
1374 return;
1375 };
1376 let cov = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count();
1377 assert_eq!(cov(&empty), 0, "near >= far must render empty");
1378 assert!(cov(&normal) > cov(&wide), "overscan=2.5 must shrink projected sphere: {} vs {}", cov(&normal), cov(&wide));
1379 }
1380
1381 #[test]
1382 fn text3d_character_size_x_widens_glyphs_without_moving_baseline() {
1383 let render_txt = |csx: f32| {
1384 let src = format!(
1385 r#"Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{
1386 T = Text3D {{ Inputs = {{ StyledText = Input {{ Value = "HI", }}, Size = Input {{ Value = 0.5, }}, CharacterSizeX = Input {{ Value = {csx}, }}, }}, }},
1387 Cam = Camera3D {{ Inputs = {{ ["Transform3DOp.Translate.Z"] = Input {{ Value = 3.0, }}, }}, }},
1388 M = Merge3D {{ Inputs = {{ SceneInput1 = Input {{ SourceOp = "T", Source = "Output", }}, SceneInput2 = Input {{ SourceOp = "Cam", Source = "Output", }}, }}, }},
1389 R = Renderer3D {{ Inputs = {{ Width = Input {{ Value = 128, }}, Height = Input {{ Value = 128, }}, SceneInput = Input {{ SourceOp = "M", Source = "Output", }}, }}, }},
1390 }} }}"#
1391 );
1392 let comp = Comp::from_fusion_str(&src).unwrap();
1393 let mut eng = Engine::new_headless().ok()?;
1394 let r = comp.find_node("R").unwrap();
1395 let (tex, _) = eng.evaluate(&comp, r, 0.0);
1396 eng.readback_rgba(&tex).ok()
1397 };
1398 let (Some(base), Some(wide)) = (render_txt(1.0), render_txt(2.5)) else {
1399 return;
1400 };
1401 let cov = |px: &[u8]| px.chunks_exact(4).filter(|c| c[3] > 0).count();
1402 assert!(cov(&wide) > cov(&base) + 10, "CharacterSizeX=2.5 should increase coverage: {} vs {}", cov(&wide), cov(&base));
1403 }
1228}1404}
crates/engine/src/scene3d/collect.rs+353-56
...@@ -18,12 +18,15 @@ struct SceneOverrides {...@@ -18,12 +18,15 @@ struct SceneOverrides {
18 material_override: Option<NodeId>,18 material_override: Option<NodeId>,
19 affected_by_lights: Option<bool>,19 affected_by_lights: Option<bool>,
20 casts_shadow: Option<bool>,20 casts_shadow: Option<bool>,
21 receives_shadows: Option<bool>,
22 wireframe: Option<bool>,
21 flip_normals: bool,23 flip_normals: bool,
22 /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals.24 /// Smoothing angle of an enclosing `ReplaceNormals3D` that recomputes normals.
23 smooth_normals_deg: Option<f32>,25 smooth_normals_deg: Option<f32>,
24 displace: Option<Displace3DSpec>,26 displace: Option<Displace3DSpec>,
25 cull_back: bool,27 cull_back: Option<bool>,
26 cull_front: bool,28 cull_front: Option<bool>,
29 unseen_by_cameras: Option<bool>,
27}30}
2831
29fn splitmix64(mut x: u64) -> f32 {32fn splitmix64(mut x: u64) -> f32 {
...@@ -142,8 +145,10 @@ fn collect_scene_inner(...@@ -142,8 +145,10 @@ fn collect_scene_inner(
142 }145 }
143 "ReplaceMaterial3D" => {146 "ReplaceMaterial3D" => {
144 let mut next_ovr = ovr.clone();147 let mut next_ovr = ovr.clone();
145 if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) {148 if comp.eval_number(node, "Enable", time, 1.0, expr) > 0.5 {
146 next_ovr.material_override = Some(mid);149 if let Some(mid) = node.connected_node("MaterialInput").and_then(|s| comp.find_node(s)) {
150 next_ovr.material_override = Some(mid);
151 }
147 }152 }
148 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {153 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
149 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);154 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
...@@ -156,10 +161,30 @@ fn collect_scene_inner(...@@ -156,10 +161,30 @@ fn collect_scene_inner(
156 return;161 return;
157 }162 }
158 let mut next_ovr = ovr.clone();163 let mut next_ovr = ovr.clone();
159 let do_lit = comp.eval_number(node, "Lighting.DoAffectedByLights", time, 0.0, expr) > 0.5;164 let flag_ovr = |do_k: &str, val_k: &str, def_val: f64| -> Option<bool> {
160 if do_lit {165 (comp.eval_number(node, do_k, time, 0.0, expr) > 0.5)
161 let is_lit = comp.eval_number(node, "Lighting.IsAffectedByLights", time, 1.0, expr) > 0.5;166 .then(|| comp.eval_number(node, val_k, time, def_val, expr) > 0.5)
162 next_ovr.affected_by_lights = Some(is_lit);167 };
168 if let Some(v) = flag_ovr("Visibility.DoIsUnseenByCameras", "Visibility.IsUnseenByCameras", 0.0) {
169 next_ovr.unseen_by_cameras = Some(v);
170 }
171 if let Some(v) = flag_ovr("Visibility.DoCullFrontFace", "Visibility.CullFrontFace", 0.0) {
172 next_ovr.cull_front = Some(v);
173 }
174 if let Some(v) = flag_ovr("Visibility.DoCullBackFace", "Visibility.CullBackFace", 0.0) {
175 next_ovr.cull_back = Some(v);
176 }
177 if let Some(v) = flag_ovr("Wireframe.DoWireframe", "Wireframe.Wireframe", 0.0) {
178 next_ovr.wireframe = Some(v);
179 }
180 if let Some(v) = flag_ovr("Lighting.DoAffectedByLights", "Lighting.IsAffectedByLights", 1.0) {
181 next_ovr.affected_by_lights = Some(v);
182 }
183 if let Some(v) = flag_ovr("Lighting.DoShadowCaster", "Lighting.IsShadowCaster", 1.0) {
184 next_ovr.casts_shadow = Some(v);
185 }
186 if let Some(v) = flag_ovr("Lighting.DoShadowReceiver", "Lighting.IsShadowReceiver", 1.0) {
187 next_ovr.receives_shadows = Some(v);
163 }188 }
164 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {189 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
165 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);190 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1);
...@@ -180,7 +205,7 @@ fn collect_scene_inner(...@@ -180,7 +205,7 @@ fn collect_scene_inner(
180 "Displace3D" => {205 "Displace3D" => {
181 let mut next_ovr = ovr.clone();206 let mut next_ovr = ovr.clone();
182 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {207 if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) {
183 let scale = comp.eval_number(node, "Scale", time, 1.0, expr) as f32;208 let scale = comp.eval_number(node, "Scale", time, 0.1, expr) as f32;
184 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;209 let bias = comp.eval_number(node, "Bias", time, 0.0, expr) as f32;
185 let channel = comp.eval_number(node, "Channel", time, 0.0, expr).round() as i32;210 let channel = comp.eval_number(node, "Channel", time, 0.0, expr).round() as i32;
186 next_ovr.displace = Some(Displace3DSpec {211 next_ovr.displace = Some(Displace3DSpec {
...@@ -198,40 +223,83 @@ fn collect_scene_inner(...@@ -198,40 +223,83 @@ fn collect_scene_inner(
198 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {223 let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else {
199 return;224 return;
200 };225 };
226 let region_mode = node.static_str("RegionMode").unwrap_or("Ignore");
227 let region = node.static_str("Region").unwrap_or("AllRgn");
228 if region_mode == "NotInside" && region == "AllRgn" {
229 return;
230 }
201 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;231 let first = comp.eval_number(node, "FirstCopy", time, 0.0, expr).round() as i32;
202 let last = comp.eval_number(node, "LastCopy", time, 1.0, expr).round() as i32;232 let last = comp.eval_number(node, "LastCopy", time, 2.0, expr).round() as i32;
203 let count = (last - first + 1).clamp(0, 256);233 let count = (last - first).clamp(0, 256);
204 // Fusion Duplicate3D uses bare `Translate.X/Y/Z`, `Rotate.X/Y/Z`, `Scale.X/Y/Z` (with fallback to `Transform3DOp.*`)234 if count == 0 {
205 let step = eval_duplicate3d_step(comp, node, time, expr);235 return;
206 let seed = comp.eval_number(node, "RandomSeed", time, 26024.0, expr).round() as u64;236 }
237 let dup_params = eval_duplicate3d_params(comp, node, time, expr);
238 let is_linear = node.static_str("TransformMethod") == Some("Linear");
239 let step = dup_params.matrix_for_step(1.0, false);
240
241 let copy_prob = comp.eval_number(node, "CopyProbability", time, 1.0, expr) as f32;
242 let seed = comp.eval_number(node, "RandomSeed", time, 0.0, expr).round() as u64;
207 let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32;243 let jtx = comp.eval_number(node, "JitterTranslate.X", time, 0.0, expr) as f32;
208 let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32;244 let jty = comp.eval_number(node, "JitterTranslate.Y", time, 0.0, expr) as f32;
209 let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32;245 let jtz = comp.eval_number(node, "JitterTranslate.Z", time, 0.0, expr) as f32;
210 let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32;246 let jrx = comp.eval_number(node, "JitterRotate.X", time, 0.0, expr) as f32;
211 let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32;247 let jry = comp.eval_number(node, "JitterRotate.Y", time, 0.0, expr) as f32;
212 let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32;248 let jrz = comp.eval_number(node, "JitterRotate.Z", time, 0.0, expr) as f32;
213 let has_jitter = (jtx.abs() + jty.abs() + jtz.abs() + jrx.abs() + jry.abs() + jrz.abs()) > 1e-5;249 let j_scale_lock = comp.eval_number(node, "JitterScaleLock", time, 1.0, expr) > 0.5;
250 let jsx = comp.eval_number(node, "JitterScale.X", time, 0.0, expr) as f32;
251 let (jsy, jsz) = if j_scale_lock {
252 (jsx, jsx)
253 } else {
254 (
255 comp.eval_number(node, "JitterScale.Y", time, 0.0, expr) as f32,
256 comp.eval_number(node, "JitterScale.Z", time, 0.0, expr) as f32,
257 )
258 };
259 let has_jitter = (jtx.abs() + jty.abs() + jtz.abs()
260 + jrx.abs() + jry.abs() + jrz.abs()
261 + jsx.abs() + jsy.abs() + jsz.abs()) > 1e-5;
214262
215 let mut acc = mat4_identity();263 let mut acc = mat4_identity();
216 for _ in 0..first.max(0) {264 if !is_linear {
217 acc = mat4_mul(acc, step);265 for _ in 0..first.max(0) {
266 acc = mat4_mul(acc, step);
267 }
218 }268 }
219 for i in 0..count {269 for i in 0..count {
220 let copy_idx = (first + i) as u64;270 let copy_idx = (first + i) as u64;
221 let mut m = mat4_mul(parent_xform, acc);271 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));
222 if has_jitter {272 if copy_prob < 0.9999 && (splitmix64(s ^ 13) + 0.5) > copy_prob {
223 let s = seed.wrapping_mul(6364136223846793005).wrapping_add(copy_idx.wrapping_mul(1442695040888963407));273 if !is_linear {
274 acc = mat4_mul(acc, step);
275 }
276 continue;
277 }
278 let base_m = if is_linear {
279 dup_params.matrix_for_step((first + i) as f32, true)
280 } else {
281 acc
282 };
283 let mut m = mat4_mul(parent_xform, base_m);
284 // Fusion Duplicate3D leaves copy 0 unjittered.
285 if has_jitter && copy_idx > 0 {
224 let tx = splitmix64(s ^ 1) * jtx;286 let tx = splitmix64(s ^ 1) * jtx;
225 let ty = splitmix64(s ^ 2) * jty;287 let ty = splitmix64(s ^ 2) * jty;
226 let tz = splitmix64(s ^ 3) * jtz;288 let tz = splitmix64(s ^ 3) * jtz;
227 let rx = (splitmix64(s ^ 4) * jrx).to_radians();289 let rx = (splitmix64(s ^ 4) * jrx).to_radians();
228 let ry = (splitmix64(s ^ 5) * jry).to_radians();290 let ry = (splitmix64(s ^ 5) * jry).to_radians();
229 let rz = (splitmix64(s ^ 6) * jrz).to_radians();291 let rz = (splitmix64(s ^ 6) * jrz).to_radians();
230 let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))));292 let sx = (1.0 + splitmix64(s ^ 7) * jsx).max(1e-4);
293 let sy = (1.0 + splitmix64(s ^ 8) * jsy).max(1e-4);
294 let sz = (1.0 + splitmix64(s ^ 9) * jsz).max(1e-4);
295 let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)));
296 let jm = mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)));
231 m = mat4_mul(m, jm);297 m = mat4_mul(m, jm);
232 }298 }
233 collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);299 collect_scene_inner(comp, src_id, time, expr, m, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
234 acc = mat4_mul(acc, step);300 if !is_linear {
301 acc = mat4_mul(acc, step);
302 }
235 }303 }
236 }304 }
237 "Camera3D" => {305 "Camera3D" => {
...@@ -263,11 +331,21 @@ fn collect_scene_inner(...@@ -263,11 +331,21 @@ fn collect_scene_inner(
263 _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!)331 _ => half_aov * (gate_aspect / render_aspect.max(1e-4)).max(1.0), // Inside (Fusion default!)
264 };332 };
265 let vfov_rad = 2.0 * half_v.atan();333 let vfov_rad = 2.0 * half_v.atan();
266 let near = comp.eval_number(node, "PlaneOfFocus", time, 0.05, expr).min(0.05).max(0.005) as f32;334 let orthographic = node.static_str("ProjectionType") == Some("Orthographic");
267 let far = 5000.0_f32;335 let (near, far) = if orthographic {
336 (
337 comp.eval_number(node, "OrthoNearClip", time, 0.0, expr) as f32,
338 comp.eval_number(node, "OrthoFarClip", time, 1000.0, expr) as f32,
339 )
340 } else {
341 (
342 comp.eval_number(node, "PerspNearClip", time, 0.1, expr).max(1e-4) as f32,
343 comp.eval_number(node, "PerspFarClip", time, 1000.0, expr) as f32,
344 )
345 };
268 cameras.push(CameraInstance {346 cameras.push(CameraInstance {
269 name: node.name.clone(),347 name: node.name.clone(),
270 orthographic: node.static_str("ProjectionType") == Some("Orthographic"),348 orthographic,
271 world,349 world,
272 vfov_rad,350 vfov_rad,
273 near,351 near,
...@@ -506,6 +584,16 @@ fn collect_scene_inner(...@@ -506,6 +584,16 @@ fn collect_scene_inner(
506 if mat_node.is_none() {584 if mat_node.is_none() {
507 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];585 mat.diffuse_col = [1.0, 1.0, 1.0, 1.0];
508 }586 }
587 let line_sx = comp.eval_number(node, "LineSizeX", time, 1.0, expr) as f32;
588 let line_sy = comp.eval_number(node, "LineSizeY", time, 1.0, expr) as f32;
589 let text_world = if (line_sx - 1.0).abs() > 1e-5 || (line_sy - 1.0).abs() > 1e-5 {
590 let lp = comp.eval_point(node, "LinePivot", time, [0.0, 0.0], expr);
591 let (px, py) = (lp[0] as f32, lp[1] as f32);
592 let lxf = mat4_mul(mat4_translate(px, py, 0.0), mat4_mul(mat4_scale(line_sx, line_sy, 1.0), mat4_translate(-px, -py, 0.0)));
593 mat4_mul(world, lxf)
594 } else {
595 world
596 };
509 // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate)597 // Text3D maps 1.0 vertical unit to the text frame height (width = 2.0 * height for 2:1 plate)
510 let shape = ShapeKind::TextPlate {598 let shape = ShapeKind::TextPlate {
511 width: 4.0,599 width: 4.0,
...@@ -513,7 +601,7 @@ fn collect_scene_inner(...@@ -513,7 +601,7 @@ fn collect_scene_inner(
513 depth: ext_depth,601 depth: ext_depth,
514 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },602 slices: if ext_depth.abs() > 1e-4 { 8 } else { 1 },
515 };603 };
516 meshes.push(make_mesh_instance(world, shape, mat, Some(Text3DSpec { node_id }), ovr));604 meshes.push(make_mesh_instance(text_world, shape, mat, Some(Text3DSpec { node_id }), ovr));
517 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {605 if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) {
518 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);606 collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1);
519 }607 }
...@@ -530,6 +618,7 @@ fn collect_scene_inner(...@@ -530,6 +618,7 @@ fn collect_scene_inner(
530#[derive(PartialEq)]618#[derive(PartialEq)]
531struct ResolvedMaterial {619struct ResolvedMaterial {
532 tex_node: Option<NodeId>,620 tex_node: Option<NodeId>,
621 bump_node: Option<NodeId>,
533 diffuse_col: [f32; 4],622 diffuse_col: [f32; 4],
534 specular_col: [f32; 3],623 specular_col: [f32; 3],
535 specular_intensity: f32,624 specular_intensity: f32,
...@@ -547,6 +636,7 @@ impl Default for ResolvedMaterial {...@@ -547,6 +636,7 @@ impl Default for ResolvedMaterial {
547 fn default() -> Self {636 fn default() -> Self {
548 Self {637 Self {
549 tex_node: None,638 tex_node: None,
639 bump_node: None,
550 diffuse_col: [1.0, 1.0, 1.0, 1.0],640 diffuse_col: [1.0, 1.0, 1.0, 1.0],
551 specular_col: [1.0, 1.0, 1.0],641 specular_col: [1.0, 1.0, 1.0],
552 specular_intensity: 1.0,642 specular_intensity: 1.0,
...@@ -570,13 +660,20 @@ fn make_mesh_instance(...@@ -570,13 +660,20 @@ fn make_mesh_instance(
570 (Some(deg), s) if !matches!(s, ShapeKind::ImagePlane | ShapeKind::TextPlate { .. }) => ShapeKind::CustomMesh(Arc::new(smooth_normals(build_shape_mesh(s, 1.0), deg))),660 (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,661 _ => shape,
572 };662 };
663 let unseen = ovr.unseen_by_cameras.unwrap_or(false);
573 MeshInstance {664 MeshInstance {
574 world,665 world,
575 shape: ShapeKind::WithMaterialFx {666 shape: ShapeKind::WithMaterialFx {
576 inner: Box::new(shape),667 inner: Box::new(shape),
577 fx: MaterialFx { cull_back: ovr.cull_back, cull_front: ovr.cull_front, ..mat.fx },668 fx: MaterialFx {
669 wireframe: ovr.wireframe.unwrap_or(mat.fx.wireframe),
670 cull_back: ovr.cull_back.unwrap_or(false) || unseen,
671 cull_front: ovr.cull_front.unwrap_or(false) || unseen,
672 ..mat.fx
673 },
578 },674 },
579 material_node: mat.tex_node,675 material_node: mat.tex_node,
676 bump_node: mat.bump_node,
580 text3d,677 text3d,
581 diffuse_col: mat.diffuse_col,678 diffuse_col: mat.diffuse_col,
582 specular_col: mat.specular_col,679 specular_col: mat.specular_col,
...@@ -584,7 +681,7 @@ fn make_mesh_instance(...@@ -584,7 +681,7 @@ fn make_mesh_instance(
584 specular_exponent: mat.specular_exponent,681 specular_exponent: mat.specular_exponent,
585 affected_by_lights: !mat.unlit && ovr.affected_by_lights.unwrap_or(true),682 affected_by_lights: !mat.unlit && ovr.affected_by_lights.unwrap_or(true),
586 casts_shadow: ovr.casts_shadow.unwrap_or(true),683 casts_shadow: ovr.casts_shadow.unwrap_or(true),
587 receives_shadows: mat.receives_shadows,684 receives_shadows: ovr.receives_shadows.unwrap_or(mat.receives_shadows),
588 flip_normals: ovr.flip_normals,685 flip_normals: ovr.flip_normals,
589 displace: ovr.displace.clone(),686 displace: ovr.displace.clone(),
590 }687 }
...@@ -601,13 +698,15 @@ fn surface_scope(...@@ -601,13 +698,15 @@ fn surface_scope(
601 expr: &ExprEngine,698 expr: &ExprEngine,
602) -> Option<SceneOverrides> {699) -> Option<SceneOverrides> {
603 let flag = |k: &str, d: f64| comp.eval_number(node, &format!("{group}.{k}"), time, d, expr) > 0.5;700 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);701 let unseen = ovr.unseen_by_cameras.unwrap_or_else(|| flag("Visibility.IsUnseenByCameras", 0.0));
605 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {702 flag("Visibility.IsVisible", 1.0).then(|| SceneOverrides {
606 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),703 affected_by_lights: ovr.affected_by_lights.or(Some(flag("Lighting.IsAffectedByLights", 1.0))),
607 casts_shadow: Some(flag("Lighting.IsShadowCaster", 1.0)),704 casts_shadow: ovr.casts_shadow.or(Some(flag("Lighting.IsShadowCaster", 1.0))),
705 receives_shadows: ovr.receives_shadows,
608 // Unseen-by-cameras surfaces skip the camera pass but still cast shadows.706 // Unseen-by-cameras surfaces skip the camera pass but still cast shadows.
609 cull_back: flag("Visibility.CullBackFace", 0.0) || unseen,707 cull_back: Some(ovr.cull_back.unwrap_or_else(|| flag("Visibility.CullBackFace", 0.0)) || unseen),
610 cull_front: flag("Visibility.CullFrontFace", 0.0) || unseen,708 cull_front: Some(ovr.cull_front.unwrap_or_else(|| flag("Visibility.CullFrontFace", 0.0)) || unseen),
709 unseen_by_cameras: Some(unseen),
611 ..ovr.clone()710 ..ovr.clone()
612 })711 })
613}712}
...@@ -739,27 +838,49 @@ fn resolve_material_inner(...@@ -739,27 +838,49 @@ fn resolve_material_inner(
739 let m = trs_matrix(uvw("Translation", 0.0), uvw("Rotation", 0.0), &order, uvw("Scale", 1.0), uvw("Pivot", 0.0));838 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);839 let xf = texture_transform_uv(m, f("InvertTransform", 0.0) > 0.5);
741 mat.fx.uv = xf.then(&mat.fx.uv);840 mat.fx.uv = xf.then(&mat.fx.uv);
841 if mat.bump_node.is_some() {
842 mat.fx.bump_uv = xf.then(&mat.fx.bump_uv);
843 }
742 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {844 if let Some(w) = parse_wrap_mode(comp, n, time, expr) {
743 mat.fx.uv_wrap = w;845 mat.fx.uv_wrap = w;
846 if mat.bump_node.is_some() {
847 mat.fx.bump_wrap = w;
848 }
744 }849 }
745 mat850 mat
746 }851 }
747 "BumpMap" => {852 "BumpMap" => {
748 let src = n.connected_node("Input").and_then(|s| comp.find_node(s));853 let src = n.connected_node("Input").and_then(|s| comp.find_node(s));
749 let height_scale = comp.eval_number(n, "HeightScale", time, 1.0, expr) as f32;854 let height_scale = comp.eval_number(n, "HeightScale", time, 1.0, expr) as f32;
855 let clamp_z = comp.eval_number(n, "ClampNormalZ", time, 0.0, expr).clamp(0.0, 1.0) as f32;
750 let bump_mode = if let Some(s) = n.static_str("SourceImageType") {856 let bump_mode = if let Some(s) = n.static_str("SourceImageType") {
751 if s.eq_ignore_ascii_case("NormalMap") || s == "1" { 1 } else { 0 }857 if s.eq_ignore_ascii_case("NormalMap") || s.eq_ignore_ascii_case("Bumpmap") || s == "1" { 1 } else { 0 }
752 } else {858 } else {
753 comp.eval_number(n, "SourceImageType", time, 0.0, expr)859 comp.eval_number(n, "SourceImageType", time, 0.0, expr)
754 .round()860 .round()
755 .clamp(0.0, 1.0) as u32861 .clamp(0.0, 1.0) as u32
756 };862 };
863 let bump_channel = match n.static_str("SourceChannel").unwrap_or("Luminance") {
864 "Average" => 1,
865 "Max" => 2,
866 "Min" => 3,
867 "Red" => 4,
868 "Green" => 5,
869 "Blue" => 6,
870 "Alpha" => 7,
871 _ => 0,
872 };
873 let wrap = parse_wrap_mode(comp, n, time, expr).unwrap_or(0);
757 ResolvedMaterial {874 ResolvedMaterial {
758 tex_node: src,875 tex_node: src,
876 bump_node: src,
759 fx: MaterialFx {877 fx: MaterialFx {
760 uv_wrap: parse_wrap_mode(comp, n, time, expr).unwrap_or(0),878 uv_wrap: wrap,
761 bump_scale: height_scale,879 bump_scale: height_scale,
762 bump_mode,880 bump_mode,
881 bump_wrap: wrap,
882 bump_clamp_z: clamp_z,
883 bump_channel,
763 ..default_mat.fx884 ..default_mat.fx
764 },885 },
765 ..default_mat886 ..default_mat
...@@ -800,18 +921,25 @@ fn resolve_material_inner(...@@ -800,18 +921,25 @@ fn resolve_material_inner(
800 let spec_model = if comp.eval_number(n, "EnablePBRMaterial", time, 0.0, expr) > 0.5 { SpecModel::Pbr } else { spec_model };921 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;922 let lit = comp.eval_number(n, "ReceivesLighting", time, 1.0, expr) > 0.5;
802 let mut tex_node = diff_mat.tex_node;923 let mut tex_node = diff_mat.tex_node;
924 let mut bump_node = diff_mat.bump_node;
803 let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx };925 let mut fx = MaterialFx { spec_model, per_light_unlit: !lit, ..diff_mat.fx };
804 if let Some(bm) = bump_mat {926 if let Some(bm) = bump_mat {
927 bump_node = bm.bump_node.or(bm.tex_node);
805 if tex_node.is_none() {928 if tex_node.is_none() {
806 tex_node = bm.tex_node;929 tex_node = bump_node;
807 fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx };930 fx = MaterialFx { bump_only: true, spec_model, per_light_unlit: !lit, ..bm.fx };
808 }931 }
809 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };932 fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 };
810 fx.bump_mode = bm.fx.bump_mode;933 fx.bump_mode = bm.fx.bump_mode;
934 fx.bump_uv = bm.fx.uv;
935 fx.bump_wrap = bm.fx.uv_wrap;
936 fx.bump_clamp_z = bm.fx.bump_clamp_z;
937 fx.bump_channel = bm.fx.bump_channel;
811 }938 }
812939
813 ResolvedMaterial {940 ResolvedMaterial {
814 tex_node,941 tex_node,
942 bump_node,
815 diffuse_col: col,943 diffuse_col: col,
816 specular_col: spec_col,944 specular_col: spec_col,
817 specular_intensity: spec_int.clamp(0.0, 4.0),945 specular_intensity: spec_int.clamp(0.0, 4.0),
...@@ -829,18 +957,82 @@ fn resolve_material_inner(...@@ -829,18 +957,82 @@ fn resolve_material_inner(
829 }957 }
830}958}
831959
832fn eval_duplicate3d_step(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine) -> Mat4 {960struct Duplicate3DParams<'a> {
833 let tx = comp.eval_number(node, "Translate.X", time, comp.eval_number(node, "Transform3DOp.Translate.X", time, 0.0, expr), expr) as f32;961 translate: [f32; 3],
834 let ty = comp.eval_number(node, "Translate.Y", time, comp.eval_number(node, "Transform3DOp.Translate.Y", time, 0.0, expr), expr) as f32;962 rot_deg: [f32; 3],
835 let tz = comp.eval_number(node, "Translate.Z", time, comp.eval_number(node, "Transform3DOp.Translate.Z", time, 0.0, expr), expr) as f32;963 scale: [f32; 3],
836 let rx = (comp.eval_number(node, "Rotate.X", time, comp.eval_number(node, "Transform3DOp.Rotate.X", time, 0.0, expr), expr) as f32).to_radians();964 pivot: [f32; 3],
837 let ry = (comp.eval_number(node, "Rotate.Y", time, comp.eval_number(node, "Transform3DOp.Rotate.Y", time, 0.0, expr), expr) as f32).to_radians();965 rot_order: &'a str,
838 let rz = (comp.eval_number(node, "Rotate.Z", time, comp.eval_number(node, "Transform3DOp.Rotate.Z", time, 0.0, expr), expr) as f32).to_radians();966 xform_order: &'a str,
839 let sx = comp.eval_number(node, "Scale.X", time, comp.eval_number(node, "Transform3DOp.Scale.X", time, 1.0, expr), expr) as f32;967}
840 let sy = comp.eval_number(node, "Scale.Y", time, comp.eval_number(node, "Transform3DOp.Scale.Y", time, sx as f64, expr), expr) as f32;968
841 let sz = comp.eval_number(node, "Scale.Z", time, comp.eval_number(node, "Transform3DOp.Scale.Z", time, sx as f64, expr), expr) as f32;969impl Duplicate3DParams<'_> {
842 let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx)));970 fn matrix_for_step(&self, step: f32, linear: bool) -> Mat4 {
843 mat4_mul(mat4_translate(tx, ty, tz), mat4_mul(rot, mat4_scale(sx, sy, sz)))971 let [tx, ty, tz] = self.translate.map(|v| v * step);
972 let rot_deg = self.rot_deg.map(|v| v * step);
973 let [sx, sy, sz] = if linear {
974 self.scale.map(|s| 1.0 + (s - 1.0) * step)
975 } else {
976 self.scale
977 };
978 let rot = euler_matrix(rot_deg, self.rot_order);
979 let t_mat = mat4_translate(tx, ty, tz);
980 let s_mat = mat4_scale(sx, sy, sz);
981 let core = self.xform_order.bytes().fold(mat4_identity(), |acc, op| match op {
982 b'S' => mat4_mul(s_mat, acc),
983 b'R' => mat4_mul(rot, acc),
984 b'T' => mat4_mul(t_mat, acc),
985 _ => acc,
986 });
987 mat4_mul(
988 mat4_translate(self.pivot[0], self.pivot[1], self.pivot[2]),
989 mat4_mul(core, mat4_translate(-self.pivot[0], -self.pivot[1], -self.pivot[2])),
990 )
991 }
992}
993
994fn eval_duplicate3d_params<'a>(comp: &'a Comp, node: &'a Node, time: f64, expr: &ExprEngine) -> Duplicate3DParams<'a> {
995 let f = |k: &str, fb: &str, d: f64| {
996 comp.eval_number(node, k, time, comp.eval_number(node, fb, time, d, expr), expr) as f32
997 };
998 let translate = [
999 f("Translate.X", "Transform3DOp.Translate.X", 0.0),
1000 f("Translate.Y", "Transform3DOp.Translate.Y", 0.0),
1001 f("Translate.Z", "Transform3DOp.Translate.Z", 0.0),
1002 ];
1003 let rot_deg = [
1004 f("Rotate.X", "Transform3DOp.Rotate.X", 0.0),
1005 f("Rotate.Y", "Transform3DOp.Rotate.Y", 0.0),
1006 f("Rotate.Z", "Transform3DOp.Rotate.Z", 0.0),
1007 ];
1008 let scale_lock = comp.eval_number(node, "ScaleLock", time, 1.0, expr) > 0.5;
1009 let sx = f("Scale.X", "Transform3DOp.Scale.X", 1.0);
1010 let (sy, sz) = if scale_lock {
1011 (sx, sx)
1012 } else {
1013 (
1014 f("Scale.Y", "Transform3DOp.Scale.Y", 1.0),
1015 f("Scale.Z", "Transform3DOp.Scale.Z", 1.0),
1016 )
1017 };
1018 let pivot = [
1019 f("Pivot.X", "Transform3DOp.Pivot.X", 0.0),
1020 f("Pivot.Y", "Transform3DOp.Pivot.Y", 0.0),
1021 f("Pivot.Z", "Transform3DOp.Pivot.Z", 0.0),
1022 ];
1023 let rot_order = node
1024 .static_str("RotationOrder")
1025 .or_else(|| node.static_str("Transform3DOp.Rotate.RotOrder"))
1026 .unwrap_or("XYZ");
1027 let xform_order = node.static_str("TransformOrder").unwrap_or("SRT");
1028 Duplicate3DParams {
1029 translate,
1030 rot_deg,
1031 scale: [sx, sy, sz],
1032 pivot,
1033 rot_order,
1034 xform_order,
1035 }
844}1036}
8451037
846/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to1038/// General 4x4 inverse (Gauss-Jordan, partial pivoting); a singular `m` falls back to
...@@ -899,18 +1091,62 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)...@@ -899,18 +1091,62 @@ pub fn eval_transform3d(comp: &Comp, node: &Node, time: f64, expr: &ExprEngine)
899 };1091 };
9001092
901 let p = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Pivot.{a}"), time, 0.0, expr) as f32);1093 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);1094 let mut m = trs_matrix([tx, ty, tz], r, rot_order, [sx, sy, sz], p);
1095 if comp.eval_number(node, "Transform3DOp.UseTarget", time, 0.0, expr) > 0.5 {
1096 let tgt = ["X", "Y", "Z"].map(|a| comp.eval_number(node, &format!("Transform3DOp.Target.{a}"), time, 0.0, expr) as f32);
1097 let neg_z = matches!(node.kind.as_str(), "Camera3D" | "LightDirectional" | "LightSpot" | "LightPoint");
1098 if let Some(aim) = target_aim_matrix([tx, ty, tz], tgt, neg_z) {
1099 let local_r = euler_matrix(r, rot_order);
1100 let local_s = mat4_scale(sx, sy, sz);
1101 let t = mat4_translate(tx + p[0], ty + p[1], tz + p[2]);
1102 m = mat4_mul(t, mat4_mul(aim, mat4_mul(local_r, mat4_mul(local_s, mat4_translate(-p[0], -p[1], -p[2])))));
1103 }
1104 }
903 if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m }1105 if comp.eval_number(node, "Transform3DOp.InvertTransform", time, 0.0, expr) > 0.5 { mat4_inverse(m) } else { m }
904}1106}
9051107
906/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first).1108/// Right-handed aim rotation pointing local `-Z` (cameras/lights) or `+Z` (meshes/merges) from `eye` toward `target`.
907fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 {1109fn target_aim_matrix(eye: [f32; 3], target: [f32; 3], neg_z_forward: bool) -> Option<Mat4> {
1110 let f = [target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]];
1111 let flen = (f[0] * f[0] + f[1] * f[1] + f[2] * f[2]).sqrt();
1112 if flen < 1e-6 {
1113 return None;
1114 }
1115 let dir = [f[0] / flen, f[1] / flen, f[2] / flen];
1116 // Local +Z axis in world space
1117 let z_axis = if neg_z_forward { [-dir[0], -dir[1], -dir[2]] } else { dir };
1118 let up_ref = if z_axis[1].abs() > 0.999 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] };
1119 // right = normalize(cross(up_ref, z_axis))
1120 let rx = up_ref[1] * z_axis[2] - up_ref[2] * z_axis[1];
1121 let ry = up_ref[2] * z_axis[0] - up_ref[0] * z_axis[2];
1122 let rz = up_ref[0] * z_axis[1] - up_ref[1] * z_axis[0];
1123 let rlen = (rx * rx + ry * ry + rz * rz).sqrt().max(1e-6);
1124 let right = [rx / rlen, ry / rlen, rz / rlen];
1125 let up = [
1126 z_axis[1] * right[2] - z_axis[2] * right[1],
1127 z_axis[2] * right[0] - z_axis[0] * right[2],
1128 z_axis[0] * right[1] - z_axis[1] * right[0],
1129 ];
1130 Some([
1131 right[0], right[1], right[2], 0.0,
1132 up[0], up[1], up[2], 0.0,
1133 z_axis[0], z_axis[1], z_axis[2], 0.0,
1134 0.0, 0.0, 0.0, 1.0,
1135 ])
1136}
1137
1138fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 {
908 let [rx, ry, rz] = rot_deg.map(f32::to_radians);1139 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)];1140 let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)];
910 let rot = order1141 order
911 .bytes()1142 .bytes()
912 .filter_map(|b| "XYZ".find(b as char))1143 .filter_map(|b| "XYZ".find(b as char))
913 .fold(mat4_identity(), |acc, a| mat4_mul(axes[a], acc));1144 .fold(mat4_identity(), |acc, a| mat4_mul(axes[a], acc))
1145}
1146
1147/// `T(translate + pivot) * R * S * T(-pivot)`; `rot_deg` is per-axis, composed in `order` (`"XYZ"` applies X first).
1148fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; 3], pivot: [f32; 3]) -> Mat4 {
1149 let rot = euler_matrix(rot_deg, order);
914 let t = mat4_translate(translate[0] + pivot[0], translate[1] + pivot[1], translate[2] + pivot[2]);1150 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]);1151 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]))))1152 mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2]))))
...@@ -1048,13 +1284,13 @@ mod tests {...@@ -1048,13 +1284,13 @@ mod tests {
1048 0,1284 0,
1049 );1285 );
1050 assert_eq!(cams.len(), 1);1286 assert_eq!(cams.len(), 1);
1051 // 3 copies from Duplicate3D (0..=2) + 1 Text3D (OvrHide suppresses its Shape1)1287 // 2 copies from Duplicate3D (0..2, exclusive LastCopy) + 1 Text3D (OvrHide suppresses its Shape1)
1052 assert_eq!(meshes.len(), 4);1288 assert_eq!(meshes.len(), 3);
1053 assert!(meshes[0].flip_normals);1289 assert!(meshes[0].flip_normals);
1054 assert!(meshes[0].displace.is_some());1290 assert!(meshes[0].displace.is_some());
1055 assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1");1291 assert!((meshes[0].diffuse_col[1] - 0.6).abs() < 1e-4, "ReplaceMaterial3D should apply Cook1");
1056 assert!((meshes[2].world[12] - 3.0).abs() < 1e-4, "Duplicate3D copy 2 translated X=3.0");1292 assert!((meshes[1].world[12] - 1.5).abs() < 1e-4, "Duplicate3D copy 1 translated X=1.5");
1057 assert!(meshes[3].text3d.is_some());1293 assert!(meshes[2].text3d.is_some());
1058 assert_eq!(lights.points.len(), 1);1294 assert_eq!(lights.points.len(), 1);
1059 assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4);1295 assert!((lights.points[0].pos[0] - 3.0).abs() < 1e-4);
1060 assert_eq!(lights.spots.len(), 1);1296 assert_eq!(lights.spots.len(), 1);
...@@ -1467,4 +1703,65 @@ mod tests {...@@ -1467,4 +1703,65 @@ mod tests {
1467 let front = meshes.iter().find(|m| matches!(m.shape.base_shape(), ShapeKind::Cube { faces: 1, .. })).unwrap();1703 let front = meshes.iter().find(|m| matches!(m.shape.base_shape(), ShapeKind::Cube { faces: 1, .. })).unwrap();
1468 assert_eq!(front.diffuse_col, [1.0, 0.5, 0.0, 1.0]);1704 assert_eq!(front.diffuse_col, [1.0, 0.5, 0.0, 1.0]);
1469 }1705 }
1706
1707 #[test]
1708 fn duplicate3d_honors_exclusive_last_copy_region_scale_lock_linear_and_copy0_unjittered() {
1709 let src = comp_src(
1710 r#"S = Shape3D { },
1711 Hidden = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, RegionMode = Input { Value = FuID { "NotInside" }, }, }, },
1712 Locked = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, LastCopy = Input { Value = 2, }, ["Scale.Y"] = Input { Value = 3.0, }, ["JitterTranslate.X"] = Input { Value = 2.0, }, }, },
1713 Linear = Duplicate3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, LastCopy = Input { Value = 3, }, TransformMethod = Input { Value = FuID { "Linear" }, }, ["Translate.X"] = Input { Value = 1.0, }, ["Rotate.Z"] = Input { Value = 90.0, }, ["Scale.X"] = Input { Value = 0.5, }, }, },"#,
1714 );
1715 assert_eq!(collect(&src, "Hidden").1.len(), 0, "RegionMode=NotInside with AllRgn emits zero copies");
1716
1717 let (_, locked, _) = collect(&src, "Locked");
1718 assert_eq!(locked.len(), 2, "LastCopy=2 emits copies 0..2");
1719 assert!((locked[0].world[5] - 1.0).abs() < 1e-5, "ScaleLock=1 ignores Scale.Y");
1720 assert!(locked[0].world[12].abs() < 1e-5, "copy 0 is never jittered");
1721 assert!(locked[1].world[12].abs() > 1e-4, "copy 1 receives jitter");
1722
1723 let (_, linear, _) = collect(&src, "Linear");
1724 assert_eq!(linear.len(), 3);
1725 // Linear SRT: copy 2 has T = 2*(1,0,0), S = 1 + 2*(0.5-1) = 0, so copy 2 stays at X=2 without orbiting.
1726 assert!((linear[2].world[12] - 2.0).abs() < 1e-4 && linear[2].world[13].abs() < 1e-4);
1727 }
1728
1729 #[test]
1730 fn replace_material_enable_zero_displace_default_scale_and_override_wireframe() {
1731 let src = comp_src(
1732 r#"Bg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1733 Mtl = MtlBlinn { Inputs = { ["Diffuse.Color.Red"] = Input { Value = 0.2, }, }, },
1734 S = Shape3D { Inputs = { ["MtlStdInputs.Diffuse.Color.Red"] = Input { Value = 0.9, }, }, },
1735 RepOff = ReplaceMaterial3D { Inputs = { SceneInput = Input { SourceOp = "S", Source = "Output", }, MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, Enable = Input { Value = 0, }, }, },
1736 Disp = Displace3D { Inputs = { SceneInput = Input { SourceOp = "RepOff", Source = "Output", }, Input = Input { SourceOp = "Bg", Source = "Output", }, }, },
1737 Ovr = Override3D { Inputs = { SceneInput = Input { SourceOp = "Disp", Source = "Output", }, ["Wireframe.DoWireframe"] = Input { Value = 1, }, ["Wireframe.Wireframe"] = Input { Value = 1, }, ["Lighting.DoShadowCaster"] = Input { Value = 1, }, ["Lighting.IsShadowCaster"] = Input { Value = 0, }, }, },"#,
1738 );
1739 let (_, meshes, _) = collect(&src, "Ovr");
1740 assert_eq!(meshes.len(), 1);
1741 assert!((meshes[0].diffuse_col[0] - 0.9).abs() < 1e-4, "Enable=0 keeps Shape3D material");
1742 assert!((meshes[0].displace.as_ref().unwrap().scale - 0.1).abs() < 1e-5, "Displace3D default Scale=0.1");
1743 let (_, fx) = meshes[0].shape.split_fx();
1744 assert!(fx.wireframe);
1745 assert!(!meshes[0].casts_shadow);
1746 }
1747
1748 #[test]
1749 fn merge3d_use_target_aims_plus_z_and_bumpmap_preserves_diffuse_and_bump_nodes() {
1750 let src = comp_src(
1751 r#"DiffBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1752 BumpBg = Background { Inputs = { Width = Input { Value = 8, }, Height = Input { Value = 8, }, }, },
1753 Bump = BumpMap { Inputs = { Input = Input { SourceOp = "BumpBg", Source = "Output", }, SourceImageType = Input { Value = 1, }, }, },
1754 Mtl = MtlBlinn { Inputs = { ["Diffuse.Color.Material"] = Input { SourceOp = "DiffBg", Source = "Output", }, ["Bumpmap.Material"] = Input { SourceOp = "Bump", Source = "MaterialOutput", }, }, },
1755 S = Shape3D { Inputs = { MaterialInput = Input { SourceOp = "Mtl", Source = "MaterialOutput", }, }, },
1756 M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = "S", Source = "Output", }, ["Transform3DOp.UseTarget"] = Input { Value = 1, }, ["Transform3DOp.Target.Z"] = Input { Value = -3.0, }, }, },"#,
1757 );
1758 let comp = Comp::from_fusion_str(&src).unwrap();
1759 let diff_id = comp.find_node("DiffBg").unwrap();
1760 let bump_id = comp.find_node("BumpBg").unwrap();
1761 let (_, meshes, _) = collect(&src, "M");
1762 assert_eq!(meshes[0].material_node, Some(diff_id));
1763 assert_eq!(meshes[0].bump_node, Some(bump_id));
1764 // Target at -Z rotates Merge3D +Z toward -Z (world[10] == -1).
1765 assert!((meshes[0].world[10] + 1.0).abs() < 1e-4, "world[10]={}", meshes[0].world[10]);
1766 }
1470}1767}
crates/engine/src/scene3d/mod.rs+40-9
...@@ -211,6 +211,12 @@ pub struct MaterialFx {...@@ -211,6 +211,12 @@ pub struct MaterialFx {
211 pub bump_mode: u32,211 pub bump_mode: u32,
212 /// The bound texture only perturbs normals; it does not color the surface.212 /// The bound texture only perturbs normals; it does not color the surface.
213 pub bump_only: bool,213 pub bump_only: bool,
214 pub bump_uv: UvAffine,
215 /// 0 = clamp, 1 = wrap, 2 = mirror
216 pub bump_wrap: u32,
217 pub bump_clamp_z: f32,
218 /// 0=Luminance, 1=Average, 2=Max, 3=Min, 4=Red, 5=Green, 6=Blue, 7=Alpha
219 pub bump_channel: u32,
214 pub spec_model: SpecModel,220 pub spec_model: SpecModel,
215 /// Draw the mesh edges as lines instead of filled triangles.221 /// Draw the mesh edges as lines instead of filled triangles.
216 pub wireframe: bool,222 pub wireframe: bool,
...@@ -228,6 +234,10 @@ impl Default for MaterialFx {...@@ -228,6 +234,10 @@ impl Default for MaterialFx {
228 bump_scale: 0.0,234 bump_scale: 0.0,
229 bump_mode: 0,235 bump_mode: 0,
230 bump_only: false,236 bump_only: false,
237 bump_uv: UvAffine::IDENTITY,
238 bump_wrap: 0,
239 bump_clamp_z: 0.0,
240 bump_channel: 0,
231 spec_model: SpecModel::Blinn,241 spec_model: SpecModel::Blinn,
232 wireframe: false,242 wireframe: false,
233 cull_back: false,243 cull_back: false,
...@@ -245,6 +255,10 @@ impl MaterialFx {...@@ -245,6 +255,10 @@ impl MaterialFx {
245 self.bump_scale.to_bits().hash(h);255 self.bump_scale.to_bits().hash(h);
246 self.bump_mode.hash(h);256 self.bump_mode.hash(h);
247 self.bump_only.hash(h);257 self.bump_only.hash(h);
258 self.bump_uv.hash_into(h);
259 self.bump_wrap.hash(h);
260 self.bump_clamp_z.to_bits().hash(h);
261 self.bump_channel.hash(h);
248 (self.spec_model as u8).hash(h);262 (self.spec_model as u8).hash(h);
249 self.wireframe.hash(h);263 self.wireframe.hash(h);
250 self.cull_back.hash(h);264 self.cull_back.hash(h);
...@@ -349,6 +363,7 @@ pub struct MeshInstance {...@@ -349,6 +363,7 @@ pub struct MeshInstance {
349 pub world: Mat4,363 pub world: Mat4,
350 pub shape: ShapeKind,364 pub shape: ShapeKind,
351 pub material_node: Option<NodeId>,365 pub material_node: Option<NodeId>,
366 pub bump_node: Option<NodeId>,
352 pub text3d: Option<Text3DSpec>,367 pub text3d: Option<Text3DSpec>,
353 pub diffuse_col: [f32; 4],368 pub diffuse_col: [f32; 4],
354 pub specular_col: [f32; 3],369 pub specular_col: [f32; 3],
...@@ -406,6 +421,7 @@ pub struct DrawMesh {...@@ -406,6 +421,7 @@ pub struct DrawMesh {
406 /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing.421 /// Optional deterministic content key for `ShapeKind::CustomMesh` so GPU mesh LRU avoids pointer hashing.
407 pub custom_mesh_key: Option<u64>,422 pub custom_mesh_key: Option<u64>,
408 pub tex: Option<CachedTexture>,423 pub tex: Option<CachedTexture>,
424 pub bump_tex: Option<CachedTexture>,
409 pub diffuse_col: [f32; 4],425 pub diffuse_col: [f32; 4],
410 pub specular_col: [f32; 3],426 pub specular_col: [f32; 3],
411 pub specular_intensity: f32,427 pub specular_intensity: f32,
...@@ -519,6 +535,16 @@ impl Scene3DRenderer {...@@ -519,6 +535,16 @@ impl Scene3DRenderer {
519 },535 },
520 count: None,536 count: None,
521 },537 },
538 wgpu::BindGroupLayoutEntry {
539 binding: 5,
540 visibility: wgpu::ShaderStages::FRAGMENT,
541 ty: wgpu::BindingType::Texture {
542 sample_type: wgpu::TextureSampleType::Float { filterable: true },
543 view_dimension: wgpu::TextureViewDimension::D2,
544 multisampled: false,
545 },
546 count: None,
547 },
522 ],548 ],
523 });549 });
524 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {550 let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
...@@ -565,7 +591,7 @@ impl Scene3DRenderer {...@@ -565,7 +591,7 @@ impl Scene3DRenderer {
565 depth_stencil: Some(wgpu::DepthStencilState {591 depth_stencil: Some(wgpu::DepthStencilState {
566 format: wgpu::TextureFormat::Depth32Float,592 format: wgpu::TextureFormat::Depth32Float,
567 depth_write_enabled: Some(true),593 depth_write_enabled: Some(true),
568 depth_compare: Some(wgpu::CompareFunction::LessEqual),594 depth_compare: Some(wgpu::CompareFunction::Less),
569 stencil: wgpu::StencilState::default(),595 stencil: wgpu::StencilState::default(),
570 bias: wgpu::DepthBiasState::default(),596 bias: wgpu::DepthBiasState::default(),
571 }),597 }),
...@@ -903,15 +929,13 @@ impl Scene3DRenderer {...@@ -903,15 +929,13 @@ impl Scene3DRenderer {
903 };929 };
904930
905 let mvp = mat4_mul(view_proj, m.world);931 let mvp = mat4_mul(view_proj, m.world);
906 let dod = if let Some(t) = &m.tex {932 let tex_dod = |tex: Option<&CachedTexture>| -> [f32; 4] {
907 if t.has_dod() {933 tex.filter(|t| t.has_dod())
908 [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32]934 .map_or([0.0; 4], |t| [t.origin[0] as f32, t.origin[1] as f32, t.canvas_size[0] as f32, t.canvas_size[1] as f32])
909 } else {
910 [0.0; 4]
911 }
912 } else {
913 [0.0; 4]
914 };935 };
936 let dod = tex_dod(m.tex.as_ref());
937 let bump_src = m.bump_tex.as_ref().or_else(|| if fx.bump_only { m.tex.as_ref() } else { None });
938 let bump_dod = tex_dod(bump_src);
915 let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS];939 let mut point_pos = [[0.0_f32; 4]; MAX_LIGHTS];
916 let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS];940 let mut point_col = [[0.0_f32; 4]; MAX_LIGHTS];
917 let n_pt = lights.points.len().min(MAX_LIGHTS);941 let n_pt = lights.points.len().min(MAX_LIGHTS);
...@@ -960,6 +984,10 @@ impl Scene3DRenderer {...@@ -960,6 +984,10 @@ impl Scene3DRenderer {
960 uv_xform: fx.uv.m,984 uv_xform: fx.uv.m,
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 }],985 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 }],
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],986 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],
987 bump_uv_xform: fx.bump_uv.m,
988 bump_off_wrap: [fx.bump_uv.t[0], fx.bump_uv.t[1], fx.bump_wrap as f32, if bump_src.is_some() { 1.0 } else { 0.0 }],
989 bump_dod,
990 bump_params: [fx.bump_clamp_z, fx.bump_channel as f32, 0.0, 0.0],
963 point_pos,991 point_pos,
964 point_col,992 point_col,
965 spot_pos,993 spot_pos,
...@@ -974,6 +1002,7 @@ impl Scene3DRenderer {...@@ -974,6 +1002,7 @@ impl Scene3DRenderer {
974 });1002 });
975 queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni));1003 queue.write_buffer(&ubuf, 0, bytemuck::bytes_of(&uni));
976 let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view);1004 let tex_view = m.tex.as_ref().map_or(&dummy.view, |t| &t.view);
1005 let bump_view = bump_src.map_or(&dummy.view, |t| &t.view);
977 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {1006 let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
978 label: Some("scene3d-bg"),1007 label: Some("scene3d-bg"),
979 layout: &self.bgl,1008 layout: &self.bgl,
...@@ -986,6 +1015,7 @@ impl Scene3DRenderer {...@@ -986,6 +1015,7 @@ impl Scene3DRenderer {
986 binding: 4,1015 binding: 4,
987 resource: wgpu::BindingResource::TextureView(shadow_view.as_ref().unwrap_or(&self.shadow_dummy)),1016 resource: wgpu::BindingResource::TextureView(shadow_view.as_ref().unwrap_or(&self.shadow_dummy)),
988 },1017 },
1018 wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(bump_view) },
989 ],1019 ],
990 });1020 });
991 // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha.1021 // Fusion's RendererOpenGL casts solid geometry shadows regardless of texture/material alpha.
...@@ -1265,6 +1295,7 @@ mod tests {...@@ -1265,6 +1295,7 @@ mod tests {
1265 },1295 },
1266 custom_mesh_key: None,1296 custom_mesh_key: None,
1267 tex: None,1297 tex: None,
1298 bump_tex: None,
1268 diffuse_col: [1.0; 4],1299 diffuse_col: [1.0; 4],
1269 specular_col: [1.0; 3],1300 specular_col: [1.0; 3],
1270 specular_intensity: 0.0,1301 specular_intensity: 0.0,
crates/engine/src/scene3d/shader.rs+80-25
...@@ -48,6 +48,14 @@ pub(super) struct MeshUniform {...@@ -48,6 +48,14 @@ pub(super) struct MeshUniform {
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 3=Pbr]`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 /// Bump UV affine matrix, column-major `[m00, m10, m01, m11]`
52 pub(super) bump_uv_xform: [f32; 4],
53 /// Bump UV translation, wrap mode and presence `[tx, ty, wrap, has_bump_tex]`
54 pub(super) bump_off_wrap: [f32; 4],
55 /// Bump DoD `[origin_x, origin_y, canvas_w, canvas_h]` (zeros if standard texture)
56 pub(super) bump_dod: [f32; 4],
57 /// `[bump_clamp_z, bump_channel, bump_filter_size, 0]`
58 pub(super) bump_params: [f32; 4],
51 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`59 /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)`
52 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],60 pub(super) point_pos: [[f32; 4]; MAX_LIGHTS],
53 /// Point light colors * intensity `(r, g, b, 0)`61 /// Point light colors * intensity `(r, g, b, 0)`
...@@ -71,13 +79,21 @@ pub(super) struct ShadowUniform {...@@ -71,13 +79,21 @@ pub(super) struct ShadowUniform {
7179
72/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines.80/// UV affine plus wrap (`off_wrap.z`: 0 clamp, 1 wrap, 2 mirror), shared by both pipelines.
73pub(super) const UV_XFORM_WGSL: &str = r#"81pub(super) const UV_XFORM_WGSL: &str = r#"
74fn apply_uv_xform(raw_uv: vec2<f32>, m: vec4<f32>, off_wrap: vec4<f32>) -> vec2<f32> {82fn wrap_uv_only(uv_in: vec2<f32>, wrap_f: f32) -> vec2<f32> {
75 var uv = vec2<f32>(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + off_wrap.xy;83 let wrap = i32(wrap_f + 0.5);
76 let wrap = i32(off_wrap.z + 0.5);
77 if (wrap == 1) {84 if (wrap == 1) {
78 uv = fract(uv);85 return fract(uv_in);
79 } else if (wrap == 2) {86 } else if (wrap == 2) {
80 uv = vec2<f32>(1.0) - abs(fract(uv * 0.5) * 2.0 - vec2<f32>(1.0));87 return vec2<f32>(1.0) - abs(fract(uv_in * 0.5) * 2.0 - vec2<f32>(1.0));
88 }
89 return clamp(uv_in, vec2<f32>(0.0), vec2<f32>(1.0));
90}
91
92fn apply_uv_xform(raw_uv: vec2<f32>, m: vec4<f32>, off_wrap: vec4<f32>) -> vec2<f32> {
93 let uv = vec2<f32>(m.x * raw_uv.x + m.z * raw_uv.y, m.y * raw_uv.x + m.w * raw_uv.y) + off_wrap.xy;
94 let wrap = i32(off_wrap.z + 0.5);
95 if (wrap == 1 || wrap == 2) {
96 return wrap_uv_only(uv, off_wrap.z);
81 }97 }
82 return uv;98 return uv;
83}99}
...@@ -128,6 +144,10 @@ struct MeshUniform {...@@ -128,6 +144,10 @@ struct MeshUniform {
128 uv_xform: vec4<f32>,144 uv_xform: vec4<f32>,
129 uv_off_wrap: vec4<f32>,145 uv_off_wrap: vec4<f32>,
130 mat_fx: vec4<f32>,146 mat_fx: vec4<f32>,
147 bump_uv_xform: vec4<f32>,
148 bump_off_wrap: vec4<f32>,
149 bump_dod: vec4<f32>,
150 bump_params: vec4<f32>,
131 point_pos: array<vec4<f32>, MAX_LIGHTS>,151 point_pos: array<vec4<f32>, MAX_LIGHTS>,
132 point_col: array<vec4<f32>, MAX_LIGHTS>,152 point_col: array<vec4<f32>, MAX_LIGHTS>,
133 spot_pos: array<vec4<f32>, MAX_LIGHTS>,153 spot_pos: array<vec4<f32>, MAX_LIGHTS>,
...@@ -147,6 +167,7 @@ override BACK_PASS: bool = false;...@@ -147,6 +167,7 @@ override BACK_PASS: bool = false;
147@group(0) @binding(2) var mat_samp: sampler;167@group(0) @binding(2) var mat_samp: sampler;
148@group(0) @binding(3) var<uniform> shadow: ShadowUniform;168@group(0) @binding(3) var<uniform> shadow: ShadowUniform;
149@group(0) @binding(4) var shadow_maps: texture_2d_array<f32>;169@group(0) @binding(4) var shadow_maps: texture_2d_array<f32>;
170@group(0) @binding(5) var bump_tex: texture_2d<f32>;
150171
151struct VsIn {172struct VsIn {
152 @location(0) pos: vec3<f32>,173 @location(0) pos: vec3<f32>,
...@@ -279,17 +300,46 @@ fn eval_light_contrib(...@@ -279,17 +300,46 @@ fn eval_light_contrib(
279 return out;300 return out;
280}301}
281302
303fn sample_bump_height(uv_in: vec2<f32>, wrap_f: f32, ch: i32) -> f32 {
304 let uv = wrap_uv_only(uv_in, wrap_f);
305 let c = textureSampleLevel(bump_tex, mat_samp, uv, 0.0);
306 if (ch == 1) {
307 return (c.r + c.g + c.b) / 3.0;
308 } else if (ch == 2) {
309 return max(c.r, max(c.g, c.b));
310 } else if (ch == 3) {
311 return min(c.r, min(c.g, c.b));
312 } else if (ch == 4) {
313 return c.r;
314 } else if (ch == 5) {
315 return c.g;
316 } else if (ch == 6) {
317 return c.b;
318 } else if (ch == 7) {
319 return c.a;
320 }
321 return dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114));
322}
323
282fn perturb_bump_normal(324fn perturb_bump_normal(
283 base_n: vec3<f32>,325 base_n: vec3<f32>,
284 dpdx_w: vec3<f32>,326 dpdx_w: vec3<f32>,
285 dpdy_w: vec3<f32>,327 dpdy_w: vec3<f32>,
286 duvdx: vec2<f32>,328 duvdx: vec2<f32>,
287 duvdy: vec2<f32>,329 duvdy: vec2<f32>,
288 uv: vec2<f32>,330 uv_in: vec2<f32>,
289 tex_col: vec4<f32>,
290 bump_scale: f32,331 bump_scale: f32,
291 bump_mode: f32,332 bump_mode: f32,
333 bump_wrap: f32,
334 clamp_z: f32,
335 bump_ch: i32,
292) -> vec3<f32> {336) -> vec3<f32> {
337 var uv = uv_in;
338 if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) {
339 let bdims = vec2<f32>(textureDimensions(bump_tex));
340 let canvas_px = vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w);
341 uv = (canvas_px - u.bump_dod.xy) / bdims;
342 }
293 let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x;343 let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x;
294 var t_vec: vec3<f32>;344 var t_vec: vec3<f32>;
295 var b_vec: vec3<f32>;345 var b_vec: vec3<f32>;
...@@ -316,33 +366,36 @@ fn perturb_bump_normal(...@@ -316,33 +366,36 @@ fn perturb_bump_normal(
316 }366 }
317367
318 if (bump_mode > 0.5) {368 if (bump_mode > 0.5) {
319 let tn_xy = (tex_col.rg * 2.0 - vec2<f32>(1.0)) * bump_scale;369 let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0);
320 let tn_z = max(tex_col.b * 2.0 - 1.0, 0.05);370 let b_rgb = select(vec3<f32>(0.5, 0.5, 1.0), b_col.rgb / max(b_col.a, 1e-5), b_col.a > 1e-5);
321 return normalize(t_vec * tn_xy.x + b_vec * tn_xy.y + base_n * tn_z);371 let tn = b_rgb * 2.0 - vec3<f32>(1.0);
372 let perturbed = t_vec * tn.x + b_vec * tn.y + base_n * tn.z;
373 let plen = length(perturbed);
374 return select(base_n, perturbed / plen, plen > 1e-5);
322 }375 }
323376
324 let inv_dim = vec2<f32>(1.0) / max(vec2<f32>(textureDimensions(mat_tex)), vec2<f32>(1.0));377 let inv_dim = vec2<f32>(1.0) / max(vec2<f32>(textureDimensions(bump_tex)), vec2<f32>(1.0));
325 let luma_w = vec3<f32>(0.299, 0.587, 0.114);378 let h_l = sample_bump_height(uv - vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch);
326 let h_l = dot(textureSampleLevel(mat_tex, mat_samp, uv - vec2<f32>(inv_dim.x, 0.0), 0.0).rgb, luma_w);379 let h_r = sample_bump_height(uv + vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch);
327 let h_r = dot(textureSampleLevel(mat_tex, mat_samp, uv + vec2<f32>(inv_dim.x, 0.0), 0.0).rgb, luma_w);380 let h_d = sample_bump_height(uv - vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch);
328 let h_d = dot(textureSampleLevel(mat_tex, mat_samp, uv - vec2<f32>(0.0, inv_dim.y), 0.0).rgb, luma_w);381 let h_u = sample_bump_height(uv + vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch);
329 let h_u = dot(textureSampleLevel(mat_tex, mat_samp, uv + vec2<f32>(0.0, inv_dim.y), 0.0).rgb, luma_w);
330 let dhdu = (h_r - h_l) * 0.5 * bump_scale;382 let dhdu = (h_r - h_l) * 0.5 * bump_scale;
331 let dhdv = (h_u - h_d) * 0.5 * bump_scale;383 let dhdv = (h_u - h_d) * 0.5 * bump_scale;
332 return normalize(base_n - t_vec * dhdu - b_vec * dhdv);384 return normalize(base_n - t_vec * dhdu + b_vec * dhdv);
333}385}
334386
335@fragment387@fragment
336fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {388fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
389 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap);
390 let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap);
391 let dpdx_w = dpdx(in.world_pos);
392 let dpdy_w = dpdy(in.world_pos);
393 let duvdx = dpdx(uv_bump_xformed);
394 let duvdy = dpdy(uv_bump_xformed);
337 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;395 let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0;
338 if (facing_away != BACK_PASS) {396 if (facing_away != BACK_PASS) {
339 discard;397 discard;
340 }398 }
341 let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap);
342 let dpdx_w = dpdx(in.world_pos);
343 let dpdy_w = dpdy(in.world_pos);
344 let duvdx = dpdx(uv_xformed);
345 let duvdy = dpdy(uv_xformed);
346399
347 var col = u.diffuse_col;400 var col = u.diffuse_col;
348 var tex_col = vec4<f32>(1.0);401 var tex_col = vec4<f32>(1.0);
...@@ -367,17 +420,19 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {...@@ -367,17 +420,19 @@ fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> {
367 // Premultiplied -> unpremultiplied albedo for lighting420 // Premultiplied -> unpremultiplied albedo for lighting
368 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);421 let albedo = select(vec3<f32>(0.0), col.rgb / max(col.a, 1e-5), col.a > 1e-5);
369 var n = normalize(in.world_n);422 var n = normalize(in.world_n);
370 if (u.flags.x > 0.5 && abs(u.mat_fx.x) > 1e-5) {423 if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) {
371 n = perturb_bump_normal(424 n = perturb_bump_normal(
372 n,425 n,
373 dpdx_w,426 dpdx_w,
374 dpdy_w,427 dpdy_w,
375 duvdx,428 duvdx,
376 duvdy,429 duvdy,
377 uv_samp,430 uv_bump_xformed,
378 tex_col,
379 u.mat_fx.x,431 u.mat_fx.x,
380 u.mat_fx.y,432 u.mat_fx.y,
433 u.bump_off_wrap.z,
434 u.bump_params.x,
435 i32(u.bump_params.y + 0.5),
381 );436 );
382 }437 }
383 let v = normalize(u.cam_pos.xyz - in.world_pos);438 let v = normalize(u.cam_pos.xyz - in.world_pos);