| author | |
| committer | |
| log | 4b05551050c90049563a0a4869e2ba7ee5a27041 |
| tree | 3b519e301ff4417c7b5cc3c622d6bd51bba13dcb |
| parent | c57c54e1587ab8fe05c4e403154359464909411e |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
Adds LightDome, MtlMerge3D, MtlPBRUber, MtlStereoMix3D, CubeMap, FalloffOperator,
FastNoiseTexture3D, TexCatcher, TexGradient, Fog3D, Locator3D, Ribbon3D,
Triangulate3D, Weld3D and UVMap. Per-mesh surface state moves into a Pod
SurfaceFx block shared with surface_fx.wgsl; the mesh shader moves to mesh.wgsl.
SphereMap drops StartAngle/EndAngle (no effect in Fusion) and fixes its
equirect/angular lookup; MtlReflect and MtlChanBool drop fallback inputs and
treat unwired inputs as Fusion does; Bender3D follows Fusion's axes, extends
rigidly past its range and turns normals with the warp's rotation.
Fuzz: SphereMap 99.955%, MtlChanBool 99.037%, MtlReflect 99.968%, Bender3D 99.838%.
Assisted-by: claude-opus-5.511 files changed, 2075 insertions(+), 1258 deletions(-)
crates/engine/src/scene3d/collect.rs+158-276| ... | @@ -11,6 +11,8 @@ use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, | ... | @@ -11,6 +11,8 @@ use super::mesh::{build_cone, build_icosahedron, build_shape_mesh, build_torus, |
| 11 | use super::math::{ | 11 | use super::math::{ |
| 12 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, | 12 | mat4_identity, mat4_inverse_rigid, mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, |
| 13 | }; | 13 | }; |
| 14 | use super::fx::layer_mode; | ||
| 15 | use super::{materials, scene_ops, textures}; | ||
| 14 | use super::{ | 16 | use super::{ |
| 15 | CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, | 17 | CameraInstance, DirLight, Displace3DSpec, Mat4, MaterialFx, MeshInstance, PointLight, SceneLights, |
| 16 | ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES, | 18 | ShapeKind, SpecModel, SpotLight, Text3DSpec, UvAffine, Vertex3D, CUBE_FACES, |
| ... | @@ -133,7 +135,8 @@ fn collect_scene_inner( | ... | @@ -133,7 +135,8 @@ fn collect_scene_inner( |
| 133 | let world = mat4_mul(parent_xform, local); | 135 | let world = mat4_mul(parent_xform, local); |
| 134 | 136 | ||
| 135 | match node.kind.as_str() { | 137 | match node.kind.as_str() { |
| 136 | "Merge3D" | "Transform3D" => { | 138 | // Triangulate3D only matters to Fusion's own wireframe display; it passes the scene through. |
| 139 | "Merge3D" | "Transform3D" | "Triangulate3D" => { | ||
| 137 | let mut input_names: Vec<&String> = node | 140 | let mut input_names: Vec<&String> = node |
| 138 | .inputs | 141 | .inputs |
| 139 | .keys() | 142 | .keys() |
| ... | @@ -206,6 +209,50 @@ fn collect_scene_inner( | ... | @@ -206,6 +209,50 @@ fn collect_scene_inner( |
| 206 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | 209 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); |
| 207 | } | 210 | } |
| 208 | } | 211 | } |
| 212 | "Weld3D" => { | ||
| 213 | let mut next_ovr = ovr.clone(); | ||
| 214 | if comp.eval_number(node, "WeldNormals", time, 0.0, expr) > 0.5 { | ||
| 215 | next_ovr.smooth_normals_deg = Some(180.0); | ||
| 216 | } | ||
| 217 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 218 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, &next_ovr, cameras, meshes, lights, visited, depth + 1); | ||
| 219 | } | ||
| 220 | } | ||
| 221 | "Fog3D" | "UVMap" => { | ||
| 222 | let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) else { | ||
| 223 | return; | ||
| 224 | }; | ||
| 225 | let mut child_meshes = Vec::new(); | ||
| 226 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, &mut child_meshes, lights, visited, depth + 1); | ||
| 227 | if node.kind == "Fog3D" { | ||
| 228 | scene_ops::fog(comp, node, time, expr, &mut child_meshes); | ||
| 229 | } else if let Some(map) = scene_ops::UvMap::from_node(comp, node, time, expr) { | ||
| 230 | scene_ops::uv_map(&map, &mut child_meshes, |m| infer_image_plane_aspect(comp, m.material_node, time, expr, render_aspect)); | ||
| 231 | } | ||
| 232 | let remaining = MAX_SCENE_MESHES.saturating_sub(meshes.len()); | ||
| 233 | meshes.extend(child_meshes.into_iter().take(remaining)); | ||
| 234 | } | ||
| 235 | "Locator3D" => { | ||
| 236 | if let Some((shape, mat)) = scene_ops::locator(comp, node, time, expr) { | ||
| 237 | meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); | ||
| 238 | } | ||
| 239 | // The locator's own transform does not reach its scene input. | ||
| 240 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 241 | collect_scene_inner(comp, src_id, time, expr, parent_xform, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | ||
| 242 | } | ||
| 243 | } | ||
| 244 | "Ribbon3D" => { | ||
| 245 | let mat_node = ovr.material_override.or_else(|| node.connected_node("MaterialInput").and_then(|s| comp.find_node(s))); | ||
| 246 | let mut mat = resolve_material(comp, mat_node, time, expr, visited); | ||
| 247 | if !mat.has_material_shader { | ||
| 248 | apply_mtl_std(&mut mat, comp, node, "", time, expr); | ||
| 249 | } | ||
| 250 | let (shape, mat) = scene_ops::ribbon(comp, node, time, expr, mat); | ||
| 251 | meshes.push(make_mesh_instance(world, shape, mat, None, ovr)); | ||
| 252 | if let Some(src_id) = node.connected_node("SceneInput").and_then(|s| comp.find_node(s)) { | ||
| 253 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | ||
| 254 | } | ||
| 255 | } | ||
| 209 | "Displace3D" => { | 256 | "Displace3D" => { |
| 210 | let mut next_ovr = ovr.clone(); | 257 | let mut next_ovr = ovr.clone(); |
| 211 | if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { | 258 | if let Some(in_id) = node.connected_node("Input").and_then(|s| comp.find_node(s)) { |
| ... | @@ -520,9 +567,12 @@ fn collect_scene_inner( | ... | @@ -520,9 +567,12 @@ fn collect_scene_inner( |
| 520 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); | 567 | collect_scene_inner(comp, src_id, time, expr, world, render_aspect, ovr, cameras, meshes, lights, visited, depth + 1); |
| 521 | } | 568 | } |
| 522 | } | 569 | } |
| 523 | "LightAmbient" => { | 570 | "LightAmbient" | "LightDome" => { |
| 524 | lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; | 571 | lights.count += (comp.eval_number(node, "Enabled", time, 1.0, expr) > 0.5) as u32; |
| 525 | if let Some(color) = light_color(comp, node, time, expr) { | 572 | // An untextured dome lights nothing; a textured one's irradiance is approximated as a |
| 573 | // uniform ambient, exact for a constant white texture. | ||
| 574 | let lit = node.kind == "LightAmbient" || node.connected_node("DomeTexture").is_some(); | ||
| 575 | if let Some(color) = light_color(comp, node, time, expr).filter(|_| lit) { | ||
| 526 | for (acc, c) in lights.ambient.iter_mut().zip(color) { | 576 | for (acc, c) in lights.ambient.iter_mut().zip(color) { |
| 527 | *acc += c; | 577 | *acc += c; |
| 528 | } | 578 | } |
| ... | @@ -621,6 +671,7 @@ fn collect_scene_inner( | ... | @@ -621,6 +671,7 @@ fn collect_scene_inner( |
| 621 | start_sweep_deg: start_sw, | 671 | start_sweep_deg: start_sw, |
| 622 | end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, | 672 | end_sweep_deg: if (end_sw - start_sw).abs() < 1e-3 { start_sw + 360.0 } else { end_sw }, |
| 623 | sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, | 673 | sub_base: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelBase", time, 20.0, expr).round() as u32, |
| 674 | sub_height: comp.eval_number(node, "SurfaceCylinderInputs.SubdivisionLevelHeight", time, 1.0, expr).round() as u32, | ||
| 624 | top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5, | 675 | top_cap: comp.eval_number(node, "SurfaceCylinderInputs.TopCap", time, 0.0, expr) > 0.5, |
| 625 | bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5, | 676 | bottom_cap: comp.eval_number(node, "SurfaceCylinderInputs.BottomCap", time, 0.0, expr) > 0.5, |
| 626 | } | 677 | } |
| ... | @@ -781,20 +832,20 @@ fn collect_scene_inner( | ... | @@ -781,20 +832,20 @@ fn collect_scene_inner( |
| 781 | } | 832 | } |
| 782 | 833 | ||
| 783 | #[derive(PartialEq)] | 834 | #[derive(PartialEq)] |
| 784 | struct ResolvedMaterial { | 835 | pub(super) struct ResolvedMaterial { |
| 785 | tex_node: Option<NodeId>, | 836 | pub(super) tex_node: Option<NodeId>, |
| 786 | bump_node: Option<NodeId>, | 837 | pub(super) bump_node: Option<NodeId>, |
| 787 | diffuse_col: [f32; 4], | 838 | pub(super) diffuse_col: [f32; 4], |
| 788 | specular_col: [f32; 3], | 839 | pub(super) specular_col: [f32; 3], |
| 789 | specular_intensity: f32, | 840 | pub(super) specular_intensity: f32, |
| 790 | specular_exponent: f32, | 841 | pub(super) specular_exponent: f32, |
| 791 | fx: MaterialFx, | 842 | pub(super) fx: MaterialFx, |
| 792 | /// A bare texture operator used as a surface's material renders flat, ignoring lights. | 843 | /// A bare texture operator used as a surface's material renders flat, ignoring lights. |
| 793 | unlit: bool, | 844 | pub(super) unlit: bool, |
| 794 | receives_shadows: bool, | 845 | pub(super) receives_shadows: bool, |
| 795 | /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`), | 846 | /// True when resolved from a shader material node (`MtlBlinn` / `MtlPhong` / `MtlCookTorrance`), |
| 796 | /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`. | 847 | /// which owns diffuse/specular rather than inheriting the geometry node's `MtlStdInputs`. |
| 797 | has_material_shader: bool, | 848 | pub(super) has_material_shader: bool, |
| 798 | } | 849 | } |
| 799 | 850 | ||
| 800 | impl Default for ResolvedMaterial { | 851 | impl Default for ResolvedMaterial { |
| ... | @@ -858,6 +909,10 @@ fn make_mesh_instance( | ... | @@ -858,6 +909,10 @@ fn make_mesh_instance( |
| 858 | _ => shape, | 909 | _ => shape, |
| 859 | }; | 910 | }; |
| 860 | let unseen = ovr.unseen_by_cameras.unwrap_or(false); | 911 | let unseen = ovr.unseen_by_cameras.unwrap_or(false); |
| 912 | let mut sfx = mat.fx.sfx; | ||
| 913 | if ovr.affected_by_lights == Some(false) { | ||
| 914 | sfx.layer[2] = 0.0; | ||
| 915 | } | ||
| 861 | MeshInstance { | 916 | MeshInstance { |
| 862 | world, | 917 | world, |
| 863 | shape: ShapeKind::WithMaterialFx { | 918 | shape: ShapeKind::WithMaterialFx { |
| ... | @@ -866,6 +921,7 @@ fn make_mesh_instance( | ... | @@ -866,6 +921,7 @@ fn make_mesh_instance( |
| 866 | wireframe: ovr.wireframe.unwrap_or(mat.fx.wireframe), | 921 | wireframe: ovr.wireframe.unwrap_or(mat.fx.wireframe), |
| 867 | cull_back: ovr.cull_back.unwrap_or(false) || unseen, | 922 | cull_back: ovr.cull_back.unwrap_or(false) || unseen, |
| 868 | cull_front: ovr.cull_front.unwrap_or(false) || unseen, | 923 | cull_front: ovr.cull_front.unwrap_or(false) || unseen, |
| 924 | sfx, | ||
| 869 | ..mat.fx | 925 | ..mat.fx |
| 870 | }, | 926 | }, |
| 871 | }, | 927 | }, |
| ... | @@ -1084,59 +1140,16 @@ fn resolve_material_inner( | ... | @@ -1084,59 +1140,16 @@ fn resolve_material_inner( |
| 1084 | ..default_mat | 1140 | ..default_mat |
| 1085 | } | 1141 | } |
| 1086 | } | 1142 | } |
| 1087 | "SphereMap" => { | 1143 | "SphereMap" => textures::sphere_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1088 | let img_in = n | 1144 | "CubeMap" => textures::cube_map(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1089 | .connected_node("Image") | 1145 | "TexGradient" => textures::tex_gradient(comp, n, time, expr), |
| 1090 | .or_else(|| n.connected_node("Input")) | 1146 | "FastNoiseTexture3D" => textures::fast_noise(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1091 | .or_else(|| n.connected_node("MaterialInput")) | 1147 | "MtlMerge3D" => materials::merge3d(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1092 | .and_then(|s| comp.find_node(s)); | 1148 | "MtlStereoMix3D" => materials::stereo_mix(comp, n, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1093 | let img_node = img_in.and_then(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1).tex_node); | 1149 | "MtlPBRUber" => materials::pbr_uber(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1094 | let f = |k: &str, fb: &str, d: f64| { | 1150 | "FalloffOperator" => materials::falloff(comp, n, time, expr, &mut |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)), |
| 1095 | comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32 | 1151 | // Without projectors in the scene there is nothing to catch. |
| 1096 | }; | 1152 | "TexCatcher" => materials::flat([0.0; 4]), |
| 1097 | let rot_deg = [ | ||
| 1098 | f("Rotate.X", "Transform3DOp.Rotate.X", 0.0), | ||
| 1099 | f("Rotate.Y", "Transform3DOp.Rotate.Y", 0.0), | ||
| 1100 | f("Rotate.Z", "Transform3DOp.Rotate.Z", 0.0), | ||
| 1101 | ]; | ||
| 1102 | let rot_order = n | ||
| 1103 | .static_str("Rotate.RotOrder") | ||
| 1104 | .or_else(|| n.static_str("Transform3DOp.Rotate.RotOrder")) | ||
| 1105 | .unwrap_or("XYZ"); | ||
| 1106 | // Rotating the environment sphere by R means sampling world directions via R^T. | ||
| 1107 | let r = euler_matrix(rot_deg, rot_order); | ||
| 1108 | let env_rot = [ | ||
| 1109 | r[0], r[4], r[8], | ||
| 1110 | r[1], r[5], r[9], | ||
| 1111 | r[2], r[6], r[10], | ||
| 1112 | ]; | ||
| 1113 | let start_angle = comp.eval_number(n, "StartAngle", time, 0.0, expr) as f32; | ||
| 1114 | let end_angle = comp.eval_number(n, "EndAngle", time, 360.0, expr) as f32; | ||
| 1115 | let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32; | ||
| 1116 | let tint = [ | ||
| 1117 | comp.eval_number(n, "Color.Red", time, 1.0, expr) as f32, | ||
| 1118 | comp.eval_number(n, "Color.Green", time, 1.0, expr) as f32, | ||
| 1119 | comp.eval_number(n, "Color.Blue", time, 1.0, expr) as f32, | ||
| 1120 | 1.0, | ||
| 1121 | ]; | ||
| 1122 | ResolvedMaterial { | ||
| 1123 | tex_node: img_node, | ||
| 1124 | diffuse_col: tint, | ||
| 1125 | fx: MaterialFx { | ||
| 1126 | env_mode: 1, | ||
| 1127 | env_map_mode: map_mode, | ||
| 1128 | env_tex_slot: if img_node.is_some() { 1 } else { 0 }, | ||
| 1129 | env_rot, | ||
| 1130 | env_start_angle: start_angle, | ||
| 1131 | env_end_angle: end_angle, | ||
| 1132 | refl_tint: [tint[0], tint[1], tint[2]], | ||
| 1133 | ..default_mat.fx | ||
| 1134 | }, | ||
| 1135 | unlit: true, | ||
| 1136 | has_material_shader: true, | ||
| 1137 | ..default_mat | ||
| 1138 | } | ||
| 1139 | } | ||
| 1140 | "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => { | 1153 | "MtlBlinn" | "MtlCookTorrance" | "MtlPhong" | "MtlWard" => { |
| 1141 | let diff_in = n | 1154 | let diff_in = n |
| 1142 | .connected_node("Diffuse.Color.Material") | 1155 | .connected_node("Diffuse.Color.Material") |
| ... | @@ -1230,66 +1243,16 @@ fn resolve_material_inner( | ... | @@ -1230,66 +1243,16 @@ fn resolve_material_inner( |
| 1230 | } | 1243 | } |
| 1231 | } | 1244 | } |
| 1232 | "MtlReflect" => { | 1245 | "MtlReflect" => { |
| 1233 | let bg_in = n.connected_node("BackgroundMaterial").and_then(|s| comp.find_node(s)); | 1246 | let input = |k: &str| n.connected_node(k).and_then(|s| comp.find_node(s)); |
| 1234 | let has_bg = bg_in.is_some(); | 1247 | let has_bg = input("BackgroundMaterial").is_some(); |
| 1235 | let bg_mat = if has_bg { | 1248 | let bg_mat = match input("BackgroundMaterial") { |
| 1236 | resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1) | 1249 | Some(id) => resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1), |
| 1237 | } else { | 1250 | None => ResolvedMaterial { diffuse_col: [0.0; 4], unlit: true, ..default_mat }, |
| 1238 | ResolvedMaterial { | ||
| 1239 | diffuse_col: [0.0, 0.0, 0.0, 0.0], | ||
| 1240 | unlit: true, | ||
| 1241 | ..default_mat | ||
| 1242 | } | ||
| 1243 | }; | ||
| 1244 | let refl_in = n | ||
| 1245 | .connected_node("Reflection.Color.Material") | ||
| 1246 | .or_else(|| n.connected_node("ReflectionMaterial")) | ||
| 1247 | .and_then(|s| comp.find_node(s)); | ||
| 1248 | let refl_mat = refl_in.map(|rid| resolve_material_inner(comp, Some(rid), time, expr, visited, depth + 1)); | ||
| 1249 | let bump_in = n.connected_node("Bumpmap.Material").and_then(|s| comp.find_node(s)); | ||
| 1250 | let bump_mat = bump_in.map(|bid| resolve_material_inner(comp, Some(bid), time, expr, visited, depth + 1)); | ||
| 1251 | |||
| 1252 | let f2 = |k: &str, fb: &str, d: f64| { | ||
| 1253 | comp.eval_number(n, k, time, comp.eval_number(n, fb, time, d, expr), expr) as f32 | ||
| 1254 | }; | ||
| 1255 | let strength_var = comp.eval_number(n, "Reflection.StrengthVariability", time, 1.0, expr).round().clamp(0.0, 1.0) as u32; | ||
| 1256 | let const_str = f2("Reflection.ConstantStrength", "Reflection.ConstantReflection", 1.0); | ||
| 1257 | let glancing = f2("Reflection.GlancingStrength", "GlancingStrength", 0.8); | ||
| 1258 | let face_on = f2("Reflection.FaceOnStrength", "FaceOnStrength", 0.0); | ||
| 1259 | let falloff = f2("Reflection.Falloff", "Falloff", 2.0); | ||
| 1260 | let ior = f2("Refraction.RefractiveIndex.RGB", "RefractionIndex", 1.333).max(0.01); | ||
| 1261 | let refract_tint = [ | ||
| 1262 | comp.eval_number(n, "Refraction.Tint.Red", time, 1.0, expr) as f32, | ||
| 1263 | comp.eval_number(n, "Refraction.Tint.Green", time, 1.0, expr) as f32, | ||
| 1264 | comp.eval_number(n, "Refraction.Tint.Blue", time, 1.0, expr) as f32, | ||
| 1265 | ]; | ||
| 1266 | let base_refl_tint = [ | ||
| 1267 | f2("Reflection.Color.Red", "ReflectionColor.Red", 1.0), | ||
| 1268 | f2("Reflection.Color.Green", "ReflectionColor.Green", 1.0), | ||
| 1269 | f2("Reflection.Color.Blue", "ReflectionColor.Blue", 1.0), | ||
| 1270 | ]; | ||
| 1271 | let (env_node, env_rot, env_map_mode, env_start, env_end, refl_tint) = if let Some(rm) = &refl_mat { | ||
| 1272 | let tint = [ | ||
| 1273 | base_refl_tint[0] * rm.diffuse_col[0], | ||
| 1274 | base_refl_tint[1] * rm.diffuse_col[1], | ||
| 1275 | base_refl_tint[2] * rm.diffuse_col[2], | ||
| 1276 | ]; | ||
| 1277 | if rm.fx.env_mode == 1 { | ||
| 1278 | (rm.tex_node, rm.fx.env_rot, rm.fx.env_map_mode, rm.fx.env_start_angle, rm.fx.env_end_angle, tint) | ||
| 1279 | } else { | ||
| 1280 | (rm.tex_node, MaterialFx::default().env_rot, 0, 0.0, 360.0, tint) | ||
| 1281 | } | ||
| 1282 | } else { | ||
| 1283 | (None, MaterialFx::default().env_rot, 0, 0.0, 360.0, base_refl_tint) | ||
| 1284 | }; | 1251 | }; |
| 1285 | 1252 | let mut tex_node = bg_mat.tex_node.filter(|_| !bg_mat.fx.bump_only); | |
| 1286 | let bg_has_diffuse_tex = bg_mat.tex_node.is_some() && !bg_mat.fx.bump_only; | ||
| 1287 | let mut tex_node = if bg_has_diffuse_tex { bg_mat.tex_node } else { None }; | ||
| 1288 | let mut bump_node = bg_mat.bump_node; | 1253 | let mut bump_node = bg_mat.bump_node; |
| 1289 | let mut fx = bg_mat.fx; | 1254 | let mut fx = MaterialFx { bump_only: false, ..bg_mat.fx }; |
| 1290 | fx.bump_only = false; | 1255 | if let Some(bm) = input("Bumpmap.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) { |
| 1291 | |||
| 1292 | if let Some(bm) = bump_mat { | ||
| 1293 | bump_node = bm.bump_node.or(bm.tex_node); | 1256 | bump_node = bm.bump_node.or(bm.tex_node); |
| 1294 | fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 }; | 1257 | fx.bump_scale = if bm.fx.bump_scale.abs() > 1e-6 { bm.fx.bump_scale } else { 1.0 }; |
| 1295 | fx.bump_mode = bm.fx.bump_mode; | 1258 | fx.bump_mode = bm.fx.bump_mode; |
| ... | @@ -1298,152 +1261,60 @@ fn resolve_material_inner( | ... | @@ -1298,152 +1261,60 @@ fn resolve_material_inner( |
| 1298 | fx.bump_clamp_z = bm.fx.bump_clamp_z; | 1261 | fx.bump_clamp_z = bm.fx.bump_clamp_z; |
| 1299 | fx.bump_channel = bm.fx.bump_channel; | 1262 | fx.bump_channel = bm.fx.bump_channel; |
| 1300 | } | 1263 | } |
| 1301 | 1264 | let mut mat = ResolvedMaterial { tex_node, bump_node, fx, has_material_shader: true, ..bg_mat }; | |
| 1302 | let env_tex_slot = if let Some(en) = env_node { | 1265 | // Without a reflection material Fusion renders the background material alone. |
| 1266 | let Some(rm) = input("Reflection.Color.Material").map(|id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1)) else { | ||
| 1267 | return mat; | ||
| 1268 | }; | ||
| 1269 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 1270 | if let Some(env) = rm.tex_node { | ||
| 1303 | if tex_node.is_none() { | 1271 | if tex_node.is_none() { |
| 1304 | tex_node = Some(en); | 1272 | tex_node = Some(env); |
| 1305 | 1 | 1273 | mat.fx.env_tex_slot = 1; |
| 1306 | } else { | 1274 | } else { |
| 1307 | bump_node = Some(en); | 1275 | bump_node = Some(env); |
| 1308 | 2 | 1276 | mat.fx.env_tex_slot = 2; |
| 1309 | } | 1277 | } |
| 1278 | } | ||
| 1279 | // A SphereMap/CubeMap reflects along directions; a plain image is laid on by mesh UV. | ||
| 1280 | if rm.fx.env_mode == 1 { | ||
| 1281 | mat.fx.env_rot = rm.fx.env_rot; | ||
| 1282 | mat.fx.env_map_mode = rm.fx.env_map_mode; | ||
| 1283 | mat.fx.sfx.env = rm.fx.sfx.env; | ||
| 1310 | } else { | 1284 | } else { |
| 1311 | 0 | 1285 | mat.fx.env_map_mode = 5; |
| 1312 | }; | ||
| 1313 | |||
| 1314 | fx.env_mode = 2; | ||
| 1315 | fx.env_map_mode = env_map_mode; | ||
| 1316 | fx.env_tex_slot = env_tex_slot; | ||
| 1317 | fx.env_rot = env_rot; | ||
| 1318 | fx.env_start_angle = env_start; | ||
| 1319 | fx.env_end_angle = env_end; | ||
| 1320 | fx.refl_strength_var = strength_var; | ||
| 1321 | fx.refl_constant_strength = const_str; | ||
| 1322 | fx.refl_glancing_strength = glancing; | ||
| 1323 | fx.refl_face_on_strength = face_on; | ||
| 1324 | fx.refl_falloff = falloff; | ||
| 1325 | fx.refl_tint = refl_tint; | ||
| 1326 | fx.refl_has_bg = has_bg; | ||
| 1327 | fx.refract_ior = ior; | ||
| 1328 | fx.refract_tint = refract_tint; | ||
| 1329 | |||
| 1330 | ResolvedMaterial { | ||
| 1331 | tex_node, | ||
| 1332 | bump_node, | ||
| 1333 | diffuse_col: bg_mat.diffuse_col, | ||
| 1334 | specular_col: bg_mat.specular_col, | ||
| 1335 | specular_intensity: bg_mat.specular_intensity, | ||
| 1336 | specular_exponent: bg_mat.specular_exponent, | ||
| 1337 | fx, | ||
| 1338 | unlit: if has_bg { bg_mat.unlit } else { true }, | ||
| 1339 | receives_shadows: bg_mat.receives_shadows, | ||
| 1340 | has_material_shader: true, | ||
| 1341 | } | 1286 | } |
| 1287 | mat.fx.env_mode = 2; | ||
| 1288 | mat.fx.refl_strength_var = f("Reflection.StrengthVariability", 1.0).round().clamp(0.0, 1.0) as u32; | ||
| 1289 | mat.fx.refl_constant_strength = f("Reflection.ConstantStrength", 1.0); | ||
| 1290 | mat.fx.refl_glancing_strength = f("Reflection.GlancingStrength", 0.8); | ||
| 1291 | mat.fx.refl_face_on_strength = f("Reflection.FaceOnStrength", 0.0); | ||
| 1292 | mat.fx.refl_falloff = f("Reflection.Falloff", 2.0); | ||
| 1293 | mat.fx.refl_tint = [rm.diffuse_col[0], rm.diffuse_col[1], rm.diffuse_col[2]]; | ||
| 1294 | mat.fx.refl_has_bg = has_bg; | ||
| 1295 | mat.fx.refract_ior = f("Refraction.RefractiveIndex.RGB", 1.333).max(0.01); | ||
| 1296 | mat.fx.refract_tint = ["Red", "Green", "Blue"].map(|c| f(&format!("Refraction.Tint.{c}"), 1.0)); | ||
| 1297 | ResolvedMaterial { tex_node, bump_node, ..mat } | ||
| 1342 | } | 1298 | } |
| 1343 | "MtlChanBool" => { | 1299 | "MtlChanBool" => { |
| 1344 | let bg_in = n | 1300 | let mut resolve = |id| resolve_material_inner(comp, Some(id), time, expr, visited, depth + 1); |
| 1345 | .connected_node("BackgroundMaterial") | 1301 | let black = || materials::flat([0.0, 0.0, 0.0, 1.0]); |
| 1346 | .or_else(|| n.connected_node("Background")) | 1302 | let mut mat = materials::material_input(comp, n, "BackgroundMaterial", &mut resolve).unwrap_or_else(black); |
| 1347 | .and_then(|s| comp.find_node(s)); | 1303 | let fg = materials::material_input(comp, n, "ForegroundMaterial", &mut resolve).unwrap_or_else(black); |
| 1348 | let fg_in = n | 1304 | let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8; |
| 1349 | .connected_node("ForegroundMaterial") | 1305 | let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8; |
| 1350 | .or_else(|| n.connected_node("Foreground")) | 1306 | mat.fx.cb_enabled = true; |
| 1351 | .and_then(|s| comp.find_node(s)); | 1307 | mat.fx.cb_ops_a = [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)]; |
| 1352 | let mut bg_mat = if bg_in.is_some() { | 1308 | mat.fx.cb_ops = [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")]; |
| 1353 | resolve_material_inner(comp, bg_in, time, expr, visited, depth + 1) | 1309 | mat.fx.cb_ops_b = [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)]; |
| 1354 | } else { | 1310 | mat.fx.cb_coord_space = match n.static_str("CoordSpace") { |
| 1355 | ResolvedMaterial { | ||
| 1356 | diffuse_col: [0.0, 0.0, 0.0, 0.0], | ||
| 1357 | unlit: true, | ||
| 1358 | ..default_mat | ||
| 1359 | } | ||
| 1360 | }; | ||
| 1361 | let fg_mat = fg_in.map(|fid| resolve_material_inner(comp, Some(fid), time, expr, visited, depth + 1)); | ||
| 1362 | |||
| 1363 | let has_native_cb = ["OperandAR", "OperandAG", "OperandAB", "OperandAA", "OperationR", "OperationG", "OperationB", "OperationA", "OperandBR", "OperandBG", "OperandBB", "OperandBA"] | ||
| 1364 | .iter() | ||
| 1365 | .any(|k| n.inputs.contains_key(*k)); | ||
| 1366 | let has_legacy_cb = ["Operation", "ToRed", "ToGreen", "ToBlue", "ToAlpha"] | ||
| 1367 | .iter() | ||
| 1368 | .any(|k| n.inputs.contains_key(*k)); | ||
| 1369 | |||
| 1370 | let (cb_ops_a, cb_ops, cb_ops_b) = if has_native_cb || !has_legacy_cb { | ||
| 1371 | let g = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr).round().clamp(0.0, 30.0) as u8; | ||
| 1372 | let op = |k: &str| comp.eval_number(n, k, time, 0.0, expr).round().clamp(0.0, 10.0) as u8; | ||
| 1373 | ( | ||
| 1374 | [g("OperandAR", 4.0), g("OperandAG", 5.0), g("OperandAB", 6.0), g("OperandAA", 7.0)], | ||
| 1375 | [op("OperationR"), op("OperationG"), op("OperationB"), op("OperationA")], | ||
| 1376 | [g("OperandBR", 0.0), g("OperandBG", 1.0), g("OperandBB", 2.0), g("OperandBA", 3.0)], | ||
| 1377 | ) | ||
| 1378 | } else { | ||
| 1379 | // Fallback mapping for 2D ChannelBoolean-style keys (Operation + ToRed/Green/Blue/Alpha). | ||
| 1380 | let leg_op = comp.eval_number(n, "Operation", time, 0.0, expr).round() as i32; | ||
| 1381 | let mapped_op: u8 = match leg_op { | ||
| 1382 | 1 => 4, // Add -> A + B | ||
| 1383 | 2 => 5, // Subtract -> A - B | ||
| 1384 | 6 | 3 => 6, // Multiply / And -> A * B | ||
| 1385 | 7 => 7, // Divide -> A / B | ||
| 1386 | 8 => 9, // Maximum -> max(A, B) | ||
| 1387 | 9 => 8, // Minimum -> min(A, B) | ||
| 1388 | 10 => 3, // Negative -> 1 - B | ||
| 1389 | _ => 1, // Copy -> B | ||
| 1390 | }; | ||
| 1391 | let map_ch = |k: &str, bg_idx: u8, def_ch: f64| -> (u8, u8) { | ||
| 1392 | let v = comp.eval_number(n, k, time, def_ch, expr).round() as i32; | ||
| 1393 | match v { | ||
| 1394 | 0..=3 => (mapped_op, v as u8), | ||
| 1395 | 4 => (0, bg_idx), // Do Nothing -> keep A (BG) | ||
| 1396 | 5..=8 => (mapped_op, (v - 1) as u8), // BG RGBA -> 4..=7 | ||
| 1397 | 15 => (mapped_op, 8), // Black | ||
| 1398 | 16 => (mapped_op, 9), // White | ||
| 1399 | _ => (mapped_op, bg_idx), | ||
| 1400 | } | ||
| 1401 | }; | ||
| 1402 | let (or, br) = map_ch("ToRed", 4, 0.0); | ||
| 1403 | let (og, bg_b) = map_ch("ToGreen", 5, 1.0); | ||
| 1404 | let (ob, bb) = map_ch("ToBlue", 6, 2.0); | ||
| 1405 | let (oa, ba) = map_ch("ToAlpha", 7, 3.0); | ||
| 1406 | ([4, 5, 6, 7], [or, og, ob, oa], [br, bg_b, bb, ba]) | ||
| 1407 | }; | ||
| 1408 | |||
| 1409 | let coord_space = match n.static_str("CoordSpace") { | ||
| 1410 | Some("Model") => 0, | 1311 | Some("Model") => 0, |
| 1411 | Some("World") => 1, | 1312 | Some("World") => 1, |
| 1412 | _ => 2, | 1313 | _ => 2, |
| 1413 | }; | 1314 | }; |
| 1414 | 1315 | materials::set_layer(&mut mat, &fg, layer_mode::CHAN_BOOL, 0.0); | |
| 1415 | let (fg_col, fg_tex_slot) = if let Some(fm) = fg_mat { | 1316 | mat.has_material_shader = true; |
| 1416 | let col = [ | 1317 | mat |
| 1417 | fm.diffuse_col[0], | ||
| 1418 | fm.diffuse_col[1], | ||
| 1419 | fm.diffuse_col[2], | ||
| 1420 | fm.diffuse_col[3] * fm.fx.diffuse_color_alpha, | ||
| 1421 | ]; | ||
| 1422 | let slot = if let Some(ftex) = fm.tex_node.filter(|_| !fm.fx.bump_only) { | ||
| 1423 | if bg_mat.bump_node.is_none() && bg_mat.fx.env_tex_slot != 2 { | ||
| 1424 | bg_mat.bump_node = Some(ftex); | ||
| 1425 | bg_mat.fx.bump_wrap = fm.fx.uv_wrap; | ||
| 1426 | 2 | ||
| 1427 | } else { | ||
| 1428 | 0 | ||
| 1429 | } | ||
| 1430 | } else { | ||
| 1431 | 0 | ||
| 1432 | }; | ||
| 1433 | (col, slot) | ||
| 1434 | } else { | ||
| 1435 | ([0.0, 0.0, 0.0, 0.0], 0) | ||
| 1436 | }; | ||
| 1437 | |||
| 1438 | bg_mat.fx.cb_enabled = true; | ||
| 1439 | bg_mat.fx.cb_ops_a = cb_ops_a; | ||
| 1440 | bg_mat.fx.cb_ops = cb_ops; | ||
| 1441 | bg_mat.fx.cb_ops_b = cb_ops_b; | ||
| 1442 | bg_mat.fx.cb_fg_col = fg_col; | ||
| 1443 | bg_mat.fx.cb_coord_space = coord_space; | ||
| 1444 | bg_mat.fx.cb_fg_tex_slot = fg_tex_slot; | ||
| 1445 | bg_mat.has_material_shader = true; | ||
| 1446 | bg_mat | ||
| 1447 | } | 1318 | } |
| 1448 | _ => ResolvedMaterial { | 1319 | _ => ResolvedMaterial { |
| 1449 | tex_node: Some(mid), | 1320 | tex_node: Some(mid), |
| ... | @@ -1630,7 +1501,7 @@ fn target_aim_matrix(eye: [f32; 3], target: [f32; 3], neg_z_forward: bool) -> Op | ... | @@ -1630,7 +1501,7 @@ fn target_aim_matrix(eye: [f32; 3], target: [f32; 3], neg_z_forward: bool) -> Op |
| 1630 | ]) | 1501 | ]) |
| 1631 | } | 1502 | } |
| 1632 | 1503 | ||
| 1633 | fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 { | 1504 | pub(super) fn euler_matrix(rot_deg: [f32; 3], order: &str) -> Mat4 { |
| 1634 | let [rx, ry, rz] = rot_deg.map(f32::to_radians); | 1505 | let [rx, ry, rz] = rot_deg.map(f32::to_radians); |
| 1635 | let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)]; | 1506 | let axes = [mat4_rot_x(rx), mat4_rot_y(ry), mat4_rot_z(rz)]; |
| 1636 | order | 1507 | order |
| ... | @@ -1647,9 +1518,33 @@ fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; | ... | @@ -1647,9 +1518,33 @@ fn trs_matrix(translate: [f32; 3], rot_deg: [f32; 3], order: &str, scale: [f32; |
| 1647 | mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2])))) | 1518 | mat4_mul(t, mat4_mul(rot, mat4_mul(s, mat4_translate(-pivot[0], -pivot[1], -pivot[2])))) |
| 1648 | } | 1519 | } |
| 1649 | 1520 | ||
| 1521 | #[cfg(test)] | ||
| 1522 | pub(super) fn comp_src(tools: &str) -> String { | ||
| 1523 | format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}") | ||
| 1524 | } | ||
| 1525 | |||
| 1526 | #[cfg(test)] | ||
| 1527 | pub(super) fn collect_test_scene(src: &str, root: &str) -> (Vec<CameraInstance>, Vec<MeshInstance>, SceneLights) { | ||
| 1528 | let comp = Comp::from_fusion_str(src).expect("parse comp"); | ||
| 1529 | let expr = ExprEngine::new(); | ||
| 1530 | let id = comp.find_node(root).expect("root node"); | ||
| 1531 | let (mut cams, mut meshes, mut lights) = (Vec::new(), Vec::new(), SceneLights::default()); | ||
| 1532 | collect_scene(&comp, id, 0.0, &expr, mat4_identity(), 1.0, &mut cams, &mut meshes, &mut lights, 0); | ||
| 1533 | (cams, meshes, lights) | ||
| 1534 | } | ||
| 1535 | |||
| 1536 | /// Resolves node `X` of a comp holding `tools`. | ||
| 1537 | #[cfg(test)] | ||
| 1538 | pub(super) fn resolve_test_material(tools: &str) -> ResolvedMaterial { | ||
| 1539 | let comp = Comp::from_fusion_str(&comp_src(tools)).expect("parse comp"); | ||
| 1540 | let id = comp.find_node("X").expect("node X"); | ||
| 1541 | resolve_material(&comp, Some(id), 0.0, &ExprEngine::new(), &mut Vec::new()) | ||
| 1542 | } | ||
| 1543 | |||
| 1650 | #[cfg(test)] | 1544 | #[cfg(test)] |
| 1651 | mod tests { | 1545 | mod tests { |
| 1652 | use super::*; | 1546 | use super::*; |
| 1547 | use super::collect_test_scene as collect; | ||
| 1653 | 1548 | ||
| 1654 | #[test] | 1549 | #[test] |
| 1655 | fn test_collect_scene_archive_3d_nodes() { | 1550 | fn test_collect_scene_archive_3d_nodes() { |
| ... | @@ -1903,19 +1798,6 @@ mod tests { | ... | @@ -1903,19 +1798,6 @@ mod tests { |
| 1903 | assert!((fbx.shape.split_fx().1.bump_scale - 4.5).abs() < 1e-4); | 1798 | assert!((fbx.shape.split_fx().1.bump_scale - 4.5).abs() < 1e-4); |
| 1904 | } | 1799 | } |
| 1905 | 1800 | ||
| 1906 | fn collect(src: &str, root: &str) -> (Vec<CameraInstance>, Vec<MeshInstance>, SceneLights) { | ||
| 1907 | let comp = Comp::from_fusion_str(src).expect("parse comp"); | ||
| 1908 | let expr = ExprEngine::new(); | ||
| 1909 | let id = comp.find_node(root).expect("root node"); | ||
| 1910 | let (mut cams, mut meshes, mut lights) = (Vec::new(), Vec::new(), SceneLights::default()); | ||
| 1911 | collect_scene(&comp, id, 0.0, &expr, mat4_identity(), 1.0, &mut cams, &mut meshes, &mut lights, 0); | ||
| 1912 | (cams, meshes, lights) | ||
| 1913 | } | ||
| 1914 | |||
| 1915 | fn comp_src(tools: &str) -> String { | ||
| 1916 | format!("Composition {{ CurrentTime = 0, RenderRange = {{ 0, 1 }}, GlobalRange = {{ 0, 1 }}, Tools = ordered() {{ {tools} }}, }}") | ||
| 1917 | } | ||
| 1918 | |||
| 1919 | #[test] | 1801 | #[test] |
| 1920 | fn cameras_carry_names_for_renderer_selection() { | 1802 | fn cameras_carry_names_for_renderer_selection() { |
| 1921 | let src = comp_src( | 1803 | let src = comp_src( |
| ... | @@ -2385,7 +2267,6 @@ mod tests { | ... | @@ -2385,7 +2267,6 @@ mod tests { |
| 2385 | assert_eq!(meshes[0].material_node, Some(env_id)); | 2267 | assert_eq!(meshes[0].material_node, Some(env_id)); |
| 2386 | assert_eq!(fx0.env_mode, 1); | 2268 | assert_eq!(fx0.env_mode, 1); |
| 2387 | assert_eq!(fx0.env_tex_slot, 1); | 2269 | assert_eq!(fx0.env_tex_slot, 1); |
| 2388 | assert!((fx0.env_start_angle - 30.0).abs() < 1e-4 && (fx0.env_end_angle - 330.0).abs() < 1e-4); | ||
| 2389 | 2270 | ||
| 2390 | // MtlWard | 2271 | // MtlWard |
| 2391 | let fx1 = meshes[1].shape.split_fx().1; | 2272 | let fx1 = meshes[1].shape.split_fx().1; |
| ... | @@ -2411,6 +2292,7 @@ mod tests { | ... | @@ -2411,6 +2292,7 @@ mod tests { |
| 2411 | assert_eq!(fx3.cb_ops[0], 4); | 2292 | assert_eq!(fx3.cb_ops[0], 4); |
| 2412 | assert_eq!(fx3.cb_ops_b[0], 0); | 2293 | assert_eq!(fx3.cb_ops_b[0], 0); |
| 2413 | assert_eq!(fx3.cb_coord_space, 1); | 2294 | assert_eq!(fx3.cb_coord_space, 1); |
| 2414 | assert!((fx3.cb_fg_col[0] - 0.2).abs() < 1e-5 && (fx3.cb_fg_col[2] - 0.6).abs() < 1e-5); | 2295 | assert_eq!(fx3.sfx.layer, [layer_mode::CHAN_BOOL, 0.0, 1.0, 0.0], "a wired shader foreground is lit"); |
| 2296 | assert!((fx3.sfx.layer_col[0] - 0.2).abs() < 1e-5 && (fx3.sfx.layer_col[2] - 0.6).abs() < 1e-5); | ||
| 2415 | } | 2297 | } |
| 2416 | } | 2298 | } |
crates/engine/src/scene3d/deform.rs+96-227| ... | @@ -118,24 +118,17 @@ fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] { | ... | @@ -118,24 +118,17 @@ fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] { |
| 118 | vec3_norm(out).unwrap_or([0.0, 0.0, 1.0]) | 118 | vec3_norm(out).unwrap_or([0.0, 0.0, 1.0]) |
| 119 | } | 119 | } |
| 120 | 120 | ||
| 121 | /// Right-handed orthonormal basis `(u, v, w)` where `w` is the bend axis rotated by `angle_deg`. | 121 | /// Right-handed basis `(u, v, w)`: `w` is the bend axis and `u` the direction the ends bend |
| 122 | /// toward (`X -> +Y`, `Y -> +Z`, `Z -> +X`), rotated by `angle_deg` toward `v = w x u`. | ||
| 122 | fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) { | 123 | fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) { |
| 123 | let (u0, v0, w) = match axis { | 124 | let (u0, v0, w) = match axis { |
| 124 | 0 => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]), | 125 | 0 => ([0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]), |
| 125 | 2 => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), | 126 | 2 => ([1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]), |
| 126 | _ => ([1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]), | 127 | _ => ([0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]), |
| 127 | }; | 128 | }; |
| 128 | let (s, c) = angle_deg.to_radians().sin_cos(); | 129 | let (s, c) = angle_deg.to_radians().sin_cos(); |
| 129 | let u = [ | 130 | let u = [0, 1, 2].map(|i| u0[i] * c + v0[i] * s); |
| 130 | u0[0] * c + v0[0] * s, | 131 | let v = [0, 1, 2].map(|i| -u0[i] * s + v0[i] * c); |
| 131 | u0[1] * c + v0[1] * s, | ||
| 132 | u0[2] * c + v0[2] * s, | ||
| 133 | ]; | ||
| 134 | let v = [ | ||
| 135 | -u0[0] * s + v0[0] * c, | ||
| 136 | -u0[1] * s + v0[1] * c, | ||
| 137 | -u0[2] * s + v0[2] * c, | ||
| 138 | ]; | ||
| 139 | (u, v, w) | 132 | (u, v, w) |
| 140 | } | 133 | } |
| 141 | 134 | ||
| ... | @@ -150,10 +143,9 @@ fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { | ... | @@ -150,10 +143,9 @@ fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { |
| 150 | (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) | 143 | (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) |
| 151 | } | 144 | } |
| 152 | 145 | ||
| 153 | /// Applies `Bender3D` deformation to `verts` in-place and recomputes smooth vertex normals. | 146 | /// Applies `Bender3D` deformation to `verts` in-place, turning their normals with it. |
| 154 | pub fn deform_mesh_vertices( | 147 | pub fn deform_mesh_vertices( |
| 155 | verts: &mut [Vertex3D], | 148 | verts: &mut [Vertex3D], |
| 156 | indices: &[u32], | ||
| 157 | params: &Bender3DParams, | 149 | params: &Bender3DParams, |
| 158 | shared_bounds: Option<[f32; 2]>, | 150 | shared_bounds: Option<[f32; 2]>, |
| 159 | ) { | 151 | ) { |
| ... | @@ -185,159 +177,54 @@ pub fn deform_mesh_vertices( | ... | @@ -185,159 +177,54 @@ pub fn deform_mesh_vertices( |
| 185 | let r_min = min_w + r_min_frac * extent; | 177 | let r_min = min_w + r_min_frac * extent; |
| 186 | let r_max = min_w + r_max_frac * extent; | 178 | let r_max = min_w + r_max_frac * extent; |
| 187 | let amount = params.amount; | 179 | let amount = params.amount; |
| 188 | 180 | let k = amount * std::f32::consts::TAU / extent; | |
| 189 | for vert in verts.iter_mut() { | 181 | // Deformation in bender coordinates `(u, v, w)`; outside the range the clamped end's frame |
| 190 | let pu = vec3_dot(vert.pos, u); | 182 | // carries the rest of the mesh rigidly. |
| 191 | let pv = vec3_dot(vert.pos, v); | 183 | let warp = |[pu, pv, pw]: [f32; 3]| -> [f32; 3] { |
| 192 | let pw = vec3_dot(vert.pos, w); | ||
| 193 | let wc = pw.clamp(r_min, r_max); | 184 | let wc = pw.clamp(r_min, r_max); |
| 194 | let w_ext = pw - wc; | 185 | let w_ext = pw - wc; |
| 195 | let t = (wc - w0) / extent; | 186 | let t = (wc - w0) / extent; |
| 196 | 187 | match params.mode { | |
| 197 | let nu_old = vec3_dot(vert.normal, u); | 188 | // Amount = 1.0 bends the full extent into a closed circle. |
| 198 | let nv_old = vec3_dot(vert.normal, v); | 189 | BenderMode::Bend if k.abs() > 1e-6 => { |
| 199 | let nw_old = vec3_dot(vert.normal, w); | 190 | let (st, ct) = (k * (wc - w0)).sin_cos(); |
| 200 | 191 | let r = 1.0 / k; | |
| 201 | let (nu, nv, nw, rnu, rnv, rnw) = match params.mode { | 192 | [r - (r - pu) * ct + w_ext * st, pv, w0 + (r - pu) * st + w_ext * ct] |
| 202 | BenderMode::Bend => { | ||
| 203 | // Amount = 1.0 bends the full extent by PI radians (180 degrees). | ||
| 204 | let k = amount * std::f32::consts::PI / extent; | ||
| 205 | let theta = k * (wc - w0); | ||
| 206 | let (st, ct) = theta.sin_cos(); | ||
| 207 | let (pos_u, pos_w) = if k.abs() > 1e-6 { | ||
| 208 | let r = 1.0 / k; | ||
| 209 | ( | ||
| 210 | r - (r - pu) * ct - w_ext * st, | ||
| 211 | w0 + (r - pu) * st + w_ext * ct, | ||
| 212 | ) | ||
| 213 | } else { | ||
| 214 | (pu, pw) | ||
| 215 | }; | ||
| 216 | // Rotate normal by the local bend angle so face orientation checks stay accurate. | ||
| 217 | let n_u = nu_old * ct - nw_old * st; | ||
| 218 | let n_w = nu_old * st + nw_old * ct; | ||
| 219 | (pos_u, pv, pos_w, n_u, nv_old, n_w) | ||
| 220 | } | 193 | } |
| 194 | BenderMode::Bend => [pu, pv, pw], | ||
| 221 | BenderMode::Taper => { | 195 | BenderMode::Taper => { |
| 222 | let s = (1.0 + amount * 2.0 * t).max(0.0); | 196 | let s = (1.0 + amount * 2.0 * t).max(0.0); |
| 223 | (pu * s, pv * s, pw, nu_old, nv_old, nw_old) | 197 | [pu * s, pv * s, pw] |
| 224 | } | 198 | } |
| 225 | BenderMode::Twist => { | 199 | BenderMode::Twist => { |
| 226 | let theta = amount * std::f32::consts::TAU * t; | 200 | let (st, ct) = (amount * std::f32::consts::TAU * t).sin_cos(); |
| 227 | let (st, ct) = theta.sin_cos(); | 201 | [pu * ct - pv * st, pu * st + pv * ct, pw] |
| 228 | let pos_u = pu * ct - pv * st; | ||
| 229 | let pos_v = pu * st + pv * ct; | ||
| 230 | let n_u = nu_old * ct - nv_old * st; | ||
| 231 | let n_v = nu_old * st + nv_old * ct; | ||
| 232 | (pos_u, pos_v, pw, n_u, n_v, nw_old) | ||
| 233 | } | ||
| 234 | BenderMode::Shear => { | ||
| 235 | let pos_u = pu + amount * (wc - w0); | ||
| 236 | let n_w = nw_old - amount * nu_old; | ||
| 237 | (pos_u, pv, pw, nu_old, nv_old, n_w) | ||
| 238 | } | ||
| 239 | }; | ||
| 240 | |||
| 241 | vert.pos = [ | ||
| 242 | u[0] * nu + v[0] * nv + w[0] * nw, | ||
| 243 | u[1] * nu + v[1] * nv + w[1] * nw, | ||
| 244 | u[2] * nu + v[2] * nv + w[2] * nw, | ||
| 245 | ]; | ||
| 246 | let approx_n = [ | ||
| 247 | u[0] * rnu + v[0] * rnv + w[0] * rnw, | ||
| 248 | u[1] * rnu + v[1] * rnv + w[1] * rnw, | ||
| 249 | u[2] * rnu + v[2] * rnv + w[2] * rnw, | ||
| 250 | ]; | ||
| 251 | vert.normal = vec3_norm(approx_n).unwrap_or(vert.normal); | ||
| 252 | } | ||
| 253 | |||
| 254 | recompute_smooth_normals(verts, indices, 60.0); | ||
| 255 | } | ||
| 256 | |||
| 257 | /// Recomputes smooth vertex normals across welded vertex positions, orienting each triangle | ||
| 258 | /// consistently with the approximate vertex normals and preserving creases sharper than `crease_deg`. | ||
| 259 | pub fn recompute_smooth_normals(verts: &mut [Vertex3D], indices: &[u32], crease_deg: f32) { | ||
| 260 | let tris: Vec<[u32; 3]> = indices | ||
| 261 | .chunks_exact(3) | ||
| 262 | .filter_map(|t| { | ||
| 263 | let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); | ||
| 264 | (a < verts.len() && b < verts.len() && c < verts.len()).then_some([t[0], t[1], t[2]]) | ||
| 265 | }) | ||
| 266 | .collect(); | ||
| 267 | if tris.is_empty() { | ||
| 268 | return; | ||
| 269 | } | ||
| 270 | |||
| 271 | let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); | ||
| 272 | let mut face_normals: Vec<Option<[f32; 3]>> = Vec::with_capacity(tris.len()); | ||
| 273 | let mut face_areas: Vec<f32> = Vec::with_capacity(tris.len()); | ||
| 274 | let mut at_pos: HashMap<[i64; 3], Vec<usize>> = HashMap::new(); | ||
| 275 | |||
| 276 | for (ti, t) in tris.iter().enumerate() { | ||
| 277 | let p = t.map(|i| verts[i as usize].pos); | ||
| 278 | let raw = vec3_cross(vec3_sub(p[1], p[0]), vec3_sub(p[2], p[0])); | ||
| 279 | let area = vec3_dot(raw, raw).sqrt(); | ||
| 280 | if area > 1e-10 { | ||
| 281 | let mut fn_u = [raw[0] / area, raw[1] / area, raw[2] / area]; | ||
| 282 | // Match each builder's outward winding using the Jacobian-transformed vertex normals. | ||
| 283 | let outward = t.iter().fold(0.0_f32, |acc, &i| acc + vec3_dot(verts[i as usize].normal, fn_u)); | ||
| 284 | if outward < 0.0 { | ||
| 285 | fn_u = [-fn_u[0], -fn_u[1], -fn_u[2]]; | ||
| 286 | } | ||
| 287 | face_normals.push(Some(fn_u)); | ||
| 288 | face_areas.push(area); | ||
| 289 | for &i in t { | ||
| 290 | at_pos.entry(key(verts[i as usize].pos)).or_default().push(ti); | ||
| 291 | } | ||
| 292 | } else { | ||
| 293 | face_normals.push(None); | ||
| 294 | face_areas.push(0.0); | ||
| 295 | } | ||
| 296 | } | ||
| 297 | |||
| 298 | let cos_limit = crease_deg.to_radians().cos() - 1e-4; | ||
| 299 | let mut new_normals: Vec<Option<[f32; 3]>> = vec![None; verts.len()]; | ||
| 300 | for (ti, t) in tris.iter().enumerate() { | ||
| 301 | let Some(own_n) = face_normals[ti] else { | ||
| 302 | continue; | ||
| 303 | }; | ||
| 304 | for &vi in t { | ||
| 305 | let v_idx = vi as usize; | ||
| 306 | let k = key(verts[v_idx].pos); | ||
| 307 | let mut sum = [0.0_f32; 3]; | ||
| 308 | if let Some(group) = at_pos.get(&k) { | ||
| 309 | for &fi in group { | ||
| 310 | if let Some(fn_u) = face_normals[fi] { | ||
| 311 | if vec3_dot(fn_u, own_n) >= cos_limit { | ||
| 312 | let w = face_areas[fi]; | ||
| 313 | sum[0] += fn_u[0] * w; | ||
| 314 | sum[1] += fn_u[1] * w; | ||
| 315 | sum[2] += fn_u[2] * w; | ||
| 316 | } | ||
| 317 | } | ||
| 318 | } | ||
| 319 | } | ||
| 320 | let smoothed = vec3_norm(sum).unwrap_or(own_n); | ||
| 321 | if let Some(prev) = new_normals[v_idx] { | ||
| 322 | new_normals[v_idx] = vec3_norm([ | ||
| 323 | prev[0] + smoothed[0], | ||
| 324 | prev[1] + smoothed[1], | ||
| 325 | prev[2] + smoothed[2], | ||
| 326 | ]) | ||
| 327 | .or(Some(smoothed)); | ||
| 328 | } else { | ||
| 329 | new_normals[v_idx] = Some(smoothed); | ||
| 330 | } | 202 | } |
| 203 | BenderMode::Shear => [pu + amount * (wc - w0), pv, pw], | ||
| 331 | } | 204 | } |
| 332 | } | 205 | }; |
| 333 | for (v, n_opt) in verts.iter_mut().zip(new_normals) { | 206 | let to_world = |[a, b, c]: [f32; 3]| [0, 1, 2].map(|i| u[i] * a + v[i] * b + w[i] * c); |
| 334 | if let Some(n) = n_opt { | 207 | let eps = extent * 1e-4; |
| 335 | v.normal = n; | 208 | for vert in verts.iter_mut() { |
| 336 | } | 209 | let p = [vec3_dot(vert.pos, u), vec3_dot(vert.pos, v), vec3_dot(vert.pos, w)]; |
| 210 | let n = [vec3_dot(vert.normal, u), vec3_dot(vert.normal, v), vec3_dot(vert.normal, w)]; | ||
| 211 | // Fusion turns normals with the warp's local rotation and ignores its stretch: the | ||
| 212 | // cofactor of the Jacobian (central differences) with unit columns. | ||
| 213 | let [ja, jb, jc] = [0, 1, 2].map(|axis| { | ||
| 214 | let (mut lo, mut hi) = (p, p); | ||
| 215 | lo[axis] -= eps; | ||
| 216 | hi[axis] += eps; | ||
| 217 | vec3_norm(vec3_sub(warp(hi), warp(lo))).unwrap_or([0.0; 3]) | ||
| 218 | }); | ||
| 219 | let cof = [vec3_cross(jb, jc), vec3_cross(jc, ja), vec3_cross(ja, jb)]; | ||
| 220 | let n_def = [0, 1, 2].map(|i| cof[0][i] * n[0] + cof[1][i] * n[1] + cof[2][i] * n[2]); | ||
| 221 | vert.pos = to_world(warp(p)); | ||
| 222 | vert.normal = vec3_norm(to_world(n_def)).unwrap_or(vert.normal); | ||
| 337 | } | 223 | } |
| 338 | } | 224 | } |
| 339 | 225 | ||
| 340 | /// Applies `Bender3D` to a slice of collected child meshes (either individually or as a group). | 226 | /// Applies `Bender3D` in the bender's own space to collected child meshes, each within its own |
| 227 | /// bounds or, with `group`, within their shared bounds. | ||
| 341 | pub fn apply_bender_to_meshes( | 228 | pub fn apply_bender_to_meshes( |
| 342 | meshes: &mut [MeshInstance], | 229 | meshes: &mut [MeshInstance], |
| 343 | bender_world: Mat4, | 230 | bender_world: Mat4, |
| ... | @@ -347,57 +234,38 @@ pub fn apply_bender_to_meshes( | ... | @@ -347,57 +234,38 @@ pub fn apply_bender_to_meshes( |
| 347 | if meshes.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { | 234 | if meshes.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { |
| 348 | return; | 235 | return; |
| 349 | } | 236 | } |
| 350 | 237 | let inv_bender = mat4_inverse(bender_world); | |
| 351 | if params.group { | 238 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; |
| 352 | let inv_bender = mat4_inverse(bender_world); | 239 | let (_, _, w_axis) = bender_basis(params.axis, angle_deg); |
| 353 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; | 240 | let baked: Vec<(Vec<Vertex3D>, Vec<u32>)> = meshes |
| 354 | let (_, _, w_axis) = bender_basis(params.axis, angle_deg); | 241 | .iter() |
| 355 | let mut baked: Vec<(Vec<Vertex3D>, Vec<u32>)> = Vec::with_capacity(meshes.len()); | 242 | .map(|m| { |
| 356 | let mut g_min = f32::INFINITY; | ||
| 357 | let mut g_max = f32::NEG_INFINITY; | ||
| 358 | |||
| 359 | for m in meshes.iter() { | ||
| 360 | let rel = mat4_mul(inv_bender, m.world); | 243 | let rel = mat4_mul(inv_bender, m.world); |
| 361 | let aspect = image_plane_aspect(m); | 244 | let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), image_plane_aspect(m)); |
| 362 | let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), aspect); | ||
| 363 | for vert in &mut verts { | 245 | for vert in &mut verts { |
| 364 | vert.pos = xform_point(rel, vert.pos); | 246 | vert.pos = xform_point(rel, vert.pos); |
| 365 | vert.normal = xform_normal(rel, vert.normal); | 247 | vert.normal = xform_normal(rel, vert.normal); |
| 366 | let p = vec3_dot(vert.pos, w_axis); | ||
| 367 | g_min = g_min.min(p); | ||
| 368 | g_max = g_max.max(p); | ||
| 369 | } | ||
| 370 | baked.push((verts, idx)); | ||
| 371 | } | ||
| 372 | let shared = (g_min.is_finite() && g_max.is_finite()).then_some([g_min, g_max]); | ||
| 373 | for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) { | ||
| 374 | if idx.is_empty() { | ||
| 375 | continue; | ||
| 376 | } | ||
| 377 | deform_mesh_vertices(&mut verts, &idx, params, shared); | ||
| 378 | let soup = triangle_soup((verts, idx)); | ||
| 379 | let (_, fx) = m.shape.split_fx(); | ||
| 380 | m.shape = ShapeKind::WithMaterialFx { | ||
| 381 | inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), | ||
| 382 | fx, | ||
| 383 | }; | ||
| 384 | m.world = bender_world; | ||
| 385 | } | ||
| 386 | } else { | ||
| 387 | for m in meshes.iter_mut() { | ||
| 388 | let aspect = image_plane_aspect(m); | ||
| 389 | let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), aspect); | ||
| 390 | if idx.is_empty() { | ||
| 391 | continue; | ||
| 392 | } | 248 | } |
| 393 | deform_mesh_vertices(&mut verts, &idx, params, None); | 249 | (verts, idx) |
| 394 | let soup = triangle_soup((verts, idx)); | 250 | }) |
| 395 | let (_, fx) = m.shape.split_fx(); | 251 | .collect(); |
| 396 | m.shape = ShapeKind::WithMaterialFx { | 252 | let shared = params |
| 397 | inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), | 253 | .group |
| 398 | fx, | 254 | .then(|| { |
| 399 | }; | 255 | baked.iter().filter_map(|(v, _)| axis_bounds_of(v, w_axis)).reduce(|a, b| [a[0].min(b[0]), a[1].max(b[1])]) |
| 256 | }) | ||
| 257 | .flatten(); | ||
| 258 | for (m, (mut verts, idx)) in meshes.iter_mut().zip(baked) { | ||
| 259 | if idx.is_empty() { | ||
| 260 | continue; | ||
| 400 | } | 261 | } |
| 262 | deform_mesh_vertices(&mut verts, params, shared); | ||
| 263 | let (_, fx) = m.shape.split_fx(); | ||
| 264 | m.shape = ShapeKind::WithMaterialFx { | ||
| 265 | inner: Box::new(ShapeKind::CustomMesh(Arc::new(triangle_soup((verts, idx))))), | ||
| 266 | fx, | ||
| 267 | }; | ||
| 268 | m.world = bender_world; | ||
| 401 | } | 269 | } |
| 402 | } | 270 | } |
| 403 | 271 | ||
| ... | @@ -673,28 +541,28 @@ mod tests { | ... | @@ -673,28 +541,28 @@ mod tests { |
| 673 | } | 541 | } |
| 674 | 542 | ||
| 675 | #[test] | 543 | #[test] |
| 676 | fn bender_bend_curves_plane_and_updates_normals() { | 544 | fn bender_bend_follows_fusion_axes_and_turns_normals() { |
| 677 | let shape = ShapeKind::Plane { width: 1.0, height: 2.0, sub_w: 4, sub_h: 8 }; | 545 | let shape = ShapeKind::Plane { width: 1.0, height: 2.0, sub_w: 4, sub_h: 8 }; |
| 678 | let (mut verts, idx) = build_shape_mesh(&shape, 1.0); | 546 | let bend = |angle_deg: f32| { |
| 679 | let params = Bender3DParams { | 547 | let (mut verts, _) = build_shape_mesh(&shape, 1.0); |
| 680 | mode: BenderMode::Bend, | 548 | let params = Bender3DParams { mode: BenderMode::Bend, amount: 0.5, axis: 1, angle_deg, center: 0.5, range_min: 0.0, range_max: 1.0, group: false }; |
| 681 | amount: 1.0, | 549 | deform_mesh_vertices(&mut verts, &params, None); |
| 682 | axis: 1, // Y axis | 550 | verts |
| 683 | angle_deg: 0.0, | 551 | }; |
| 684 | center: 0.5, | 552 | let mean = |verts: &[Vertex3D], top: bool, axis: usize| { |
| 685 | range_min: 0.0, | 553 | let edge: Vec<f32> = verts.iter().filter(|v| (v.uv[1] < 0.01) == top && (v.uv[1] > 0.99) != top).map(|v| v.pos[axis]).collect(); |
| 686 | range_max: 1.0, | 554 | edge.iter().sum::<f32>() / edge.len() as f32 |
| 687 | group: false, | ||
| 688 | }; | 555 | }; |
| 689 | deform_mesh_vertices(&mut verts, &idx, &params, None); | 556 | // Amount 0.5 bends the height into a half circle of radius 2 / pi opening toward +Z. |
| 690 | // Plane was originally flat at z=0 with normal +Z; bending around Y along X curls X into a circle | 557 | let verts = bend(0.0); |
| 691 | // and tilts top/bottom vertices in X while keeping finite unit normals. | 558 | let r = 2.0 / std::f32::consts::PI; |
| 692 | let top_x = verts.iter().filter(|v| v.uv[1] < 0.01).map(|v| v.pos[0]).fold(0.0_f32, |a, b| a + b) / 5.0; | 559 | for (top, y) in [(true, r), (false, -r)] { |
| 693 | assert!(top_x > 0.2, "top edge should bend toward +X, got {top_x}"); | 560 | assert!((mean(&verts, top, 2) - r).abs() < 1e-3 && (mean(&verts, top, 1) - y).abs() < 1e-3); |
| 694 | assert!(verts.iter().all(|v| { | 561 | } |
| 695 | let l = vec3_dot(v.normal, v.normal).sqrt(); | 562 | let top_n = verts.iter().find(|v| v.uv[1] < 0.01).unwrap().normal; |
| 696 | l.is_finite() && (l - 1.0).abs() < 1e-3 | 563 | assert!(top_n[1] < -0.99, "the top end's +Z normal turns toward the bend centre: {top_n:?}"); |
| 697 | })); | 564 | // Angle 90 turns the bend toward +X. |
| 565 | assert!(mean(&bend(90.0), true, 0) > 0.6); | ||
| 698 | } | 566 | } |
| 699 | 567 | ||
| 700 | #[test] | 568 | #[test] |
| ... | @@ -702,8 +570,8 @@ mod tests { | ... | @@ -702,8 +570,8 @@ mod tests { |
| 702 | let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 }; | 570 | let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 }; |
| 703 | 571 | ||
| 704 | // Taper: top (+Y) expands, bottom (-Y) shrinks. | 572 | // Taper: top (+Y) expands, bottom (-Y) shrinks. |
| 705 | let (mut v_taper, idx) = build_shape_mesh(&shape, 1.0); | 573 | let (mut v_taper, _) = build_shape_mesh(&shape, 1.0); |
| 706 | deform_mesh_vertices(&mut v_taper, &idx, &Bender3DParams { | 574 | deform_mesh_vertices(&mut v_taper, &Bender3DParams { |
| 707 | mode: BenderMode::Taper, | 575 | mode: BenderMode::Taper, |
| 708 | amount: 0.5, | 576 | amount: 0.5, |
| 709 | axis: 1, | 577 | axis: 1, |
| ... | @@ -715,8 +583,8 @@ mod tests { | ... | @@ -715,8 +583,8 @@ mod tests { |
| 715 | assert!((max_x_top - 1.5).abs() < 1e-4 && (max_x_bot - 0.5).abs() < 1e-4, "top={max_x_top} bot={max_x_bot}"); | 583 | assert!((max_x_top - 1.5).abs() < 1e-4 && (max_x_bot - 0.5).abs() < 1e-4, "top={max_x_top} bot={max_x_bot}"); |
| 716 | 584 | ||
| 717 | // Twist: rotates corners out of z=0 plane. | 585 | // Twist: rotates corners out of z=0 plane. |
| 718 | let (mut v_twist, idx) = build_shape_mesh(&shape, 1.0); | 586 | let (mut v_twist, _) = build_shape_mesh(&shape, 1.0); |
| 719 | deform_mesh_vertices(&mut v_twist, &idx, &Bender3DParams { | 587 | deform_mesh_vertices(&mut v_twist, &Bender3DParams { |
| 720 | mode: BenderMode::Twist, | 588 | mode: BenderMode::Twist, |
| 721 | amount: 0.5, | 589 | amount: 0.5, |
| 722 | axis: 1, | 590 | axis: 1, |
| ... | @@ -727,8 +595,8 @@ mod tests { | ... | @@ -727,8 +595,8 @@ mod tests { |
| 727 | assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}"); | 595 | assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}"); |
| 728 | 596 | ||
| 729 | // Shear with RangeMin=0.5 leaves bottom half unsheared (all at constant offset for wc=0) and shears top half. | 597 | // Shear with RangeMin=0.5 leaves bottom half unsheared (all at constant offset for wc=0) and shears top half. |
| 730 | let (mut v_shear, idx) = build_shape_mesh(&shape, 1.0); | 598 | let (mut v_shear, _) = build_shape_mesh(&shape, 1.0); |
| 731 | deform_mesh_vertices(&mut v_shear, &idx, &Bender3DParams { | 599 | deform_mesh_vertices(&mut v_shear, &Bender3DParams { |
| 732 | mode: BenderMode::Shear, | 600 | mode: BenderMode::Shear, |
| 733 | amount: 1.0, | 601 | amount: 1.0, |
| 734 | axis: 1, | 602 | axis: 1, |
| ... | @@ -737,8 +605,9 @@ mod tests { | ... | @@ -737,8 +605,9 @@ mod tests { |
| 737 | range_max: 1.0, | 605 | range_max: 1.0, |
| 738 | ..Default::default() | 606 | ..Default::default() |
| 739 | }, None); | 607 | }, None); |
| 740 | let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[0]; | 608 | // Bending/shearing along the Y axis moves vertices toward +Z. |
| 741 | let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[0]; | 609 | let top_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] < 0.01).unwrap().pos[2]; |
| 610 | let bot_shift = v_shear.iter().find(|v| (v.uv[0] - 0.5).abs() < 1e-4 && v.uv[1] > 0.99).unwrap().pos[2]; | ||
| 742 | assert!((top_shift - 1.0).abs() < 1e-4, "top center should shear by +1.0, got {top_shift}"); | 611 | assert!((top_shift - 1.0).abs() < 1e-4, "top center should shear by +1.0, got {top_shift}"); |
| 743 | assert!(bot_shift.abs() < 1e-4, "bottom below RangeMin should stay at 0, got {bot_shift}"); | 612 | assert!(bot_shift.abs() < 1e-4, "bottom below RangeMin should stay at 0, got {bot_shift}"); |
| 744 | } | 613 | } |
crates/engine/src/scene3d/fx.rs created+126| ... | @@ -0,0 +1,126 @@ | ||
| 1 | //! Surface shading beyond the classic material: procedural textures, a secondary material layer, | ||
| 2 | //! `MtlPBRUber`, fog and environment coordinate spaces. `SurfaceFx` is copied verbatim into the | ||
| 3 | //! mesh uniform, so its layout mirrors `struct SurfaceFx` in `surface_fx.wgsl`. | ||
| 4 | |||
| 5 | use bytemuck::{Pod, Zeroable}; | ||
| 6 | use model::Gradient; | ||
| 7 | |||
| 8 | /// Entries in the gradient lookup table shared by `TexGradient` and `FalloffOperator`. | ||
| 9 | pub(super) const LUT_SIZE: usize = 16; | ||
| 10 | |||
| 11 | /// Procedural colour source replacing the bound texture (`proc_a.x`). | ||
| 12 | pub(super) mod proc_kind { | ||
| 13 | pub const GRADIENT: f32 = 1.0; | ||
| 14 | pub const NOISE: f32 = 2.0; | ||
| 15 | pub const FALLOFF_GRADIENT: f32 = 3.0; | ||
| 16 | } | ||
| 17 | |||
| 18 | /// How the secondary material in `layer` combines with the base surface (`layer.x`). | ||
| 19 | pub(super) mod layer_mode { | ||
| 20 | /// `MtlChanBool` foreground operands. | ||
| 21 | pub const CHAN_BOOL: f32 = 1.0; | ||
| 22 | /// `MtlMerge3D`: foreground over background scaled by `layer.y` (Blend). | ||
| 23 | pub const MERGE: f32 = 2.0; | ||
| 24 | /// `FalloffOperator`: base is face-on, layer is glancing, mixed by `1 - (N.V)^layer.y`. | ||
| 25 | pub const FALLOFF: f32 = 3.0; | ||
| 26 | } | ||
| 27 | |||
| 28 | #[repr(C)] | ||
| 29 | #[derive(Clone, Copy, Debug, Default, PartialEq, Pod, Zeroable)] | ||
| 30 | pub struct SurfaceFx { | ||
| 31 | /// `[kind, ..]`: gradient `[1, type, scale, offset]`, noise `[2, detail, scale, seethe]`, | ||
| 32 | /// falloff gradient `[3, falloff, 0, 0]`. | ||
| 33 | pub proc_a: [f32; 4], | ||
| 34 | /// Gradient `[repeat, 0, 0, 0]`; noise `[contrast, brightness, inverted, discontinuous]`. | ||
| 35 | pub proc_b: [f32; 4], | ||
| 36 | /// `[mode, amount, lit, tex_slot (2 = bump_tex)]`. | ||
| 37 | pub layer: [f32; 4], | ||
| 38 | /// Layer diffuse colour (straight RGB, alpha). | ||
| 39 | pub layer_col: [f32; 4], | ||
| 40 | /// Layer specular colour and exponent. | ||
| 41 | pub layer_spec: [f32; 4], | ||
| 42 | /// `[specular_intensity, spec_model, 0, 0]`. | ||
| 43 | pub layer_mtl: [f32; 4], | ||
| 44 | /// `MtlPBRUber` `[metalness, roughness, ior, specular]`. | ||
| 45 | pub pbr: [f32; 4], | ||
| 46 | /// `MtlPBRUber` specular colour and `Base.Base` weight. | ||
| 47 | pub pbr_spec: [f32; 4], | ||
| 48 | /// `MtlPBRUber` `[coat, coat_roughness, coat_ior, sheen]`. | ||
| 49 | pub pbr_layers: [f32; 4], | ||
| 50 | /// `MtlPBRUber` sheen colour and roughness. | ||
| 51 | pub sheen: [f32; 4], | ||
| 52 | /// Emitted colour added after lighting. | ||
| 53 | pub emission: [f32; 4], | ||
| 54 | /// `Fog3D` `[type (1 linear, 2 exp, 3 exp2), near, far, density]`. | ||
| 55 | pub fog: [f32; 4], | ||
| 56 | /// Fog colour and `Radial`. | ||
| 57 | pub fog_col: [f32; 4], | ||
| 58 | /// `[coord_space (0 world, 1 model, 2 camera), 0, 0, 0]` for environment lookups. | ||
| 59 | pub env: [f32; 4], | ||
| 60 | /// Premultiplied gradient samples at `i / (LUT_SIZE - 1)`. | ||
| 61 | pub lut: [[f32; 4]; LUT_SIZE], | ||
| 62 | } | ||
| 63 | |||
| 64 | /// Premultiplied lookup table of `gradient`, or of `fallback` stops when the input is absent. | ||
| 65 | pub(super) fn gradient_lut(gradient: Option<Gradient>, fallback: [[f32; 4]; 2]) -> [[f32; 4]; LUT_SIZE] { | ||
| 66 | std::array::from_fn(|i| { | ||
| 67 | let t = i as f64 / (LUT_SIZE - 1) as f64; | ||
| 68 | let c = match &gradient { | ||
| 69 | Some(g) => g.sample(t), | ||
| 70 | None => std::array::from_fn(|k| fallback[0][k] + (fallback[1][k] - fallback[0][k]) * t as f32), | ||
| 71 | }; | ||
| 72 | [c[0] * c[3], c[1] * c[3], c[2] * c[3], c[3]] | ||
| 73 | }) | ||
| 74 | } | ||
| 75 | |||
| 76 | /// Fusion's simplex lattice, shared with the 2D `FastNoise` generator. | ||
| 77 | pub(super) fn simplex_wgsl() -> &'static str { | ||
| 78 | const SRC: &str = include_str!("../shaders/keyers_gen.wgsl"); | ||
| 79 | let start = SRC.find("const PERM: array<u32, 256>").expect("keyers_gen.wgsl defines PERM"); | ||
| 80 | let end = SRC[start..].find("@compute").expect("keyers_gen.wgsl has an entry point after the lattice"); | ||
| 81 | &SRC[start..start + end] | ||
| 82 | } | ||
| 83 | |||
| 84 | pub(super) const SURFACE_FX_WGSL: &str = include_str!("surface_fx.wgsl"); | ||
| 85 | |||
| 86 | #[cfg(test)] | ||
| 87 | mod tests { | ||
| 88 | use super::*; | ||
| 89 | use model::GradientStop; | ||
| 90 | |||
| 91 | #[test] | ||
| 92 | fn surface_fx_matches_wgsl_layout() { | ||
| 93 | let wgsl_vec4s = SURFACE_FX_WGSL | ||
| 94 | .split("struct SurfaceFx {") | ||
| 95 | .nth(1) | ||
| 96 | .and_then(|s| s.split("};").next()) | ||
| 97 | .expect("SurfaceFx struct") | ||
| 98 | .lines() | ||
| 99 | .filter(|l| l.trim_end().ends_with(": vec4<f32>,")) | ||
| 100 | .count(); | ||
| 101 | assert_eq!(wgsl_vec4s, 14, "scalar vec4 fields"); | ||
| 102 | assert_eq!(std::mem::size_of::<SurfaceFx>(), (14 + LUT_SIZE) * 16); | ||
| 103 | assert!(SURFACE_FX_WGSL.contains(&format!("lut: array<vec4<f32>, {LUT_SIZE}>"))); | ||
| 104 | } | ||
| 105 | |||
| 106 | #[test] | ||
| 107 | fn simplex_slice_holds_the_lattice_only() { | ||
| 108 | let s = simplex_wgsl(); | ||
| 109 | assert!(s.contains("fn simplex3d(") && s.contains("const SIMPLEX_GAIN")); | ||
| 110 | assert!(!s.contains("@compute") && !s.contains("var<uniform>")); | ||
| 111 | } | ||
| 112 | |||
| 113 | #[test] | ||
| 114 | fn gradient_lut_premultiplies_and_falls_back() { | ||
| 115 | let lut = gradient_lut(None, [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]); | ||
| 116 | assert_eq!(lut[0], [1.0; 4]); | ||
| 117 | assert_eq!(lut[LUT_SIZE - 1], [0.0, 0.0, 0.0, 1.0]); | ||
| 118 | let g = Gradient { | ||
| 119 | stops: vec![ | ||
| 120 | GradientStop { pos: 0.0, rgba: [1.0, 0.0, 0.0, 0.5] }, | ||
| 121 | GradientStop { pos: 1.0, rgba: [0.0, 1.0, 0.0, 0.5] }, | ||
| 122 | ], | ||
| 123 | }; | ||
| 124 | assert_eq!(gradient_lut(Some(g), [[0.0; 4]; 2])[0], [0.5, 0.0, 0.0, 0.5]); | ||
| 125 | } | ||
| 126 | } | ||
crates/engine/src/scene3d/materials.rs created+225| ... | @@ -0,0 +1,225 @@ | ||
| 1 | //! Material operators layered on `ResolvedMaterial`: `MtlMerge3D`, `MtlPBRUber`, | ||
| 2 | //! `MtlStereoMix3D`, `FalloffOperator`, `TexCatcher`, and the secondary-layer plumbing shared with | ||
| 3 | //! `MtlChanBool`. | ||
| 4 | |||
| 5 | use super::collect::ResolvedMaterial; | ||
| 6 | use super::fx::{gradient_lut, layer_mode, proc_kind, SurfaceFx}; | ||
| 7 | use super::{MaterialFx, SpecModel}; | ||
| 8 | use model::{Comp, ExprEngine, Node, NodeId}; | ||
| 9 | |||
| 10 | pub(super) type Resolve<'a> = dyn FnMut(NodeId) -> ResolvedMaterial + 'a; | ||
| 11 | |||
| 12 | /// A material operator's own input: a bare image there renders flat, as Fusion shows it. | ||
| 13 | pub(super) fn material_input(comp: &Comp, n: &Node, input: &str, resolve: &mut Resolve) -> Option<ResolvedMaterial> { | ||
| 14 | let id = n.connected_node(input).and_then(|s| comp.find_node(s))?; | ||
| 15 | let mut m = resolve(id); | ||
| 16 | m.unlit |= !m.has_material_shader; | ||
| 17 | Some(m) | ||
| 18 | } | ||
| 19 | |||
| 20 | /// Flat colour standing in for an unwired material input. | ||
| 21 | pub(super) fn flat(rgba: [f32; 4]) -> ResolvedMaterial { | ||
| 22 | ResolvedMaterial { diffuse_col: rgba, unlit: true, has_material_shader: true, ..ResolvedMaterial::default() } | ||
| 23 | } | ||
| 24 | |||
| 25 | /// Stores `layer` as the secondary material of `base`; its texture takes the bump slot when free. | ||
| 26 | pub(super) fn set_layer(base: &mut ResolvedMaterial, layer: &ResolvedMaterial, mode: f32, amount: f32) { | ||
| 27 | let tex_slot = match layer.tex_node.filter(|_| !layer.fx.bump_only) { | ||
| 28 | Some(tex) if base.bump_node.is_none() && base.fx.env_tex_slot != 2 => { | ||
| 29 | base.bump_node = Some(tex); | ||
| 30 | base.fx.bump_wrap = layer.fx.uv_wrap; | ||
| 31 | 2.0 | ||
| 32 | } | ||
| 33 | _ => 0.0, | ||
| 34 | }; | ||
| 35 | let [r, g, b, a] = layer.diffuse_col; | ||
| 36 | let [sr, sg, sb] = layer.specular_col; | ||
| 37 | let sfx = &mut base.fx.sfx; | ||
| 38 | sfx.layer = [mode, amount, if layer.unlit { 0.0 } else { 1.0 }, tex_slot]; | ||
| 39 | sfx.layer_col = [r, g, b, a * layer.fx.diffuse_color_alpha]; | ||
| 40 | sfx.layer_spec = [sr, sg, sb, layer.specular_exponent]; | ||
| 41 | sfx.layer_mtl = [layer.specular_intensity, layer.fx.spec_model as u32 as f32, 0.0, 0.0]; | ||
| 42 | } | ||
| 43 | |||
| 44 | /// `MtlMerge3D`: the foreground over the background, scaled by `Blend`. Mono renders ignore | ||
| 45 | /// `MergeType`. | ||
| 46 | pub(super) fn merge3d(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 47 | let mut mat = material_input(comp, n, "BackgroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])); | ||
| 48 | let fg = material_input(comp, n, "ForegroundMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])); | ||
| 49 | set_layer(&mut mat, &fg, layer_mode::MERGE, comp.eval_number(n, "Blend", time, 1.0, expr) as f32); | ||
| 50 | mat.has_material_shader = true; | ||
| 51 | mat | ||
| 52 | } | ||
| 53 | |||
| 54 | /// `MtlStereoMix3D`: mono renders show the left eye whatever `Swap` says. | ||
| 55 | pub(super) fn stereo_mix(comp: &Comp, n: &Node, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 56 | material_input(comp, n, "LeftMaterial", resolve).unwrap_or_else(|| flat([0.0; 4])) | ||
| 57 | } | ||
| 58 | |||
| 59 | pub(super) fn pbr_uber(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 60 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 61 | let rgb = |p: &str, d: f64| ["Red", "Green", "Blue"].map(|c| f(&format!("{p}.{c}"), d)); | ||
| 62 | let base = rgb("Base.Color", 1.0); | ||
| 63 | let opacity = rgb("Opacity.Opacity", 1.0); | ||
| 64 | let spec = rgb("Specular.Color", 1.0); | ||
| 65 | let sheen = rgb("Sheen.Color", 1.0); | ||
| 66 | let emission = rgb("Emission.Color", 1.0).map(|c| c * f("Emission.Emission", 0.0)); | ||
| 67 | let tex = n.connected_node("Base.Color.ColorMtl").and_then(|s| comp.find_node(s)).map(&mut *resolve).unwrap_or_default(); | ||
| 68 | ResolvedMaterial { | ||
| 69 | tex_node: tex.tex_node, | ||
| 70 | diffuse_col: [base[0], base[1], base[2], opacity.iter().sum::<f32>() / 3.0], | ||
| 71 | fx: MaterialFx { | ||
| 72 | spec_model: SpecModel::PbrUber, | ||
| 73 | sfx: SurfaceFx { | ||
| 74 | pbr: [f("Metalness.Metalness", 0.0), f("Specular.Roughness", 0.5), f("Specular.IOR", 1.5), f("Specular.Specular", 1.0)], | ||
| 75 | pbr_spec: [spec[0], spec[1], spec[2], f("Base.Base", 1.0)], | ||
| 76 | pbr_layers: [f("Coat.Coat", 0.0), f("Coat.Roughness", 0.0), f("Coat.IOR", 1.5), f("Sheen.Sheen", 0.0)], | ||
| 77 | sheen: [sheen[0], sheen[1], sheen[2], f("Sheen.Roughness", 0.3)], | ||
| 78 | emission: [emission[0], emission[1], emission[2], 0.0], | ||
| 79 | ..SurfaceFx::default() | ||
| 80 | }, | ||
| 81 | ..tex.fx | ||
| 82 | }, | ||
| 83 | unlit: f("ReceivesLighting", 1.0) < 0.5, | ||
| 84 | receives_shadows: f("ReceivesShadows", 1.0) > 0.5, | ||
| 85 | has_material_shader: true, | ||
| 86 | ..ResolvedMaterial::default() | ||
| 87 | } | ||
| 88 | } | ||
| 89 | |||
| 90 | /// `FalloffOperator`: `t = 1 - (N.V)^Falloff` blends face-on toward glancing, either through the | ||
| 91 | /// gradient or between the two tones (each a colour or a material, scaled by its opacity). | ||
| 92 | pub(super) fn falloff(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 93 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 94 | let power = f("Falloff", 2.0); | ||
| 95 | if n.static_str("ColorVariation") == Some("Gradient") { | ||
| 96 | let mut mat = flat([1.0; 4]); | ||
| 97 | mat.fx.sfx.proc_a = [proc_kind::FALLOFF_GRADIENT, power, 0.0, 0.0]; | ||
| 98 | mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[1.0; 4], [0.0, 0.0, 0.0, 1.0]]); | ||
| 99 | return mat; | ||
| 100 | } | ||
| 101 | let mut tone = |p: &str, opacity: f64| { | ||
| 102 | let mut m = material_input(comp, n, &format!("{p}Material"), resolve) | ||
| 103 | .unwrap_or_else(|| flat(["Red", "Green", "Blue", "Alpha"].map(|c| f(&format!("{p}.{c}"), 1.0)))); | ||
| 104 | m.diffuse_col[3] *= f(&format!("{p}.Opacity"), opacity); | ||
| 105 | m | ||
| 106 | }; | ||
| 107 | let mut mat = tone("FaceOn", 0.2); | ||
| 108 | let glancing = tone("Glancing", 1.0); | ||
| 109 | set_layer(&mut mat, &glancing, layer_mode::FALLOFF, power); | ||
| 110 | mat.has_material_shader = true; | ||
| 111 | mat | ||
| 112 | } | ||
| 113 | |||
| 114 | #[cfg(test)] | ||
| 115 | mod tests { | ||
| 116 | use super::*; | ||
| 117 | use crate::scene3d::collect::resolve_test_material as resolve_in; | ||
| 118 | |||
| 119 | #[test] | ||
| 120 | fn merge3d_layers_foreground_over_background() { | ||
| 121 | let mat = resolve_in( | ||
| 122 | "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.5, }, }, }, | ||
| 123 | FG = MtlPhong { Inputs = { [\"Specular.Exponent\"] = Input { Value = 12, }, }, }, | ||
| 124 | X = MtlMerge3D { Inputs = { Blend = Input { Value = 0.25, }, | ||
| 125 | BackgroundMaterial = Input { SourceOp = \"BG\", Source = \"MaterialOutput\", }, | ||
| 126 | ForegroundMaterial = Input { SourceOp = \"FG\", Source = \"MaterialOutput\", }, }, },", | ||
| 127 | ); | ||
| 128 | assert_eq!(mat.diffuse_col[0], 0.5); | ||
| 129 | assert!(!mat.unlit); | ||
| 130 | let sfx = mat.fx.sfx; | ||
| 131 | assert_eq!(sfx.layer, [layer_mode::MERGE, 0.25, 1.0, 0.0]); | ||
| 132 | assert_eq!(sfx.layer_spec[3], 12.0); | ||
| 133 | assert_eq!(sfx.layer_mtl[1], SpecModel::Phong as u32 as f32); | ||
| 134 | } | ||
| 135 | |||
| 136 | #[test] | ||
| 137 | fn merge3d_unwired_is_transparent_and_bare_images_are_flat() { | ||
| 138 | let empty = resolve_in("X = MtlMerge3D { },"); | ||
| 139 | assert_eq!(empty.diffuse_col, [0.0; 4]); | ||
| 140 | assert_eq!(empty.fx.sfx.layer_col, [0.0; 4]); | ||
| 141 | let img = resolve_in( | ||
| 142 | "Img = Background { }, | ||
| 143 | X = MtlMerge3D { Inputs = { ForegroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", | ||
| 144 | ); | ||
| 145 | assert_eq!(img.bump_node.map(|_| ()), Some(()), "foreground image takes the bump slot"); | ||
| 146 | assert_eq!(img.fx.sfx.layer[2..], [0.0, 2.0]); | ||
| 147 | } | ||
| 148 | |||
| 149 | #[test] | ||
| 150 | fn stereo_mix_always_uses_left() { | ||
| 151 | let mat = resolve_in( | ||
| 152 | "L = MtlBlinn { Inputs = { [\"Diffuse.Color.Green\"] = Input { Value = 0.3, }, }, }, | ||
| 153 | R = MtlBlinn { }, | ||
| 154 | X = MtlStereoMix3D { Inputs = { Swap = Input { Value = 1, }, | ||
| 155 | LeftMaterial = Input { SourceOp = \"L\", Source = \"MaterialOutput\", }, | ||
| 156 | RightMaterial = Input { SourceOp = \"R\", Source = \"MaterialOutput\", }, }, },", | ||
| 157 | ); | ||
| 158 | assert_eq!(mat.diffuse_col[1], 0.3); | ||
| 159 | } | ||
| 160 | |||
| 161 | #[test] | ||
| 162 | fn pbr_uber_reads_metal_roughness_and_emission() { | ||
| 163 | let mat = resolve_in( | ||
| 164 | "X = MtlPBRUber { Inputs = { | ||
| 165 | [\"Metalness.Metalness\"] = Input { Value = 1, }, | ||
| 166 | [\"Specular.Roughness\"] = Input { Value = 0.2, }, | ||
| 167 | [\"Emission.Emission\"] = Input { Value = 0.5, }, | ||
| 168 | [\"Emission.Color.Red\"] = Input { Value = 0, }, | ||
| 169 | [\"Opacity.Opacity.Green\"] = Input { Value = 0.4, }, }, },", | ||
| 170 | ); | ||
| 171 | assert_eq!(mat.fx.spec_model, SpecModel::PbrUber); | ||
| 172 | assert_eq!(mat.fx.sfx.pbr, [1.0, 0.2, 1.5, 1.0]); | ||
| 173 | assert_eq!(mat.fx.sfx.emission, [0.0, 0.5, 0.5, 0.0]); | ||
| 174 | assert!((mat.diffuse_col[3] - 0.8).abs() < 1e-6); | ||
| 175 | } | ||
| 176 | |||
| 177 | #[test] | ||
| 178 | fn falloff_two_tone_and_gradient() { | ||
| 179 | let two = resolve_in("X = FalloffOperator { Inputs = { [\"Glancing.Red\"] = Input { Value = 0, }, Falloff = Input { Value = 3, }, }, },"); | ||
| 180 | assert_eq!(two.diffuse_col, [1.0, 1.0, 1.0, 0.2]); | ||
| 181 | assert!(two.unlit); | ||
| 182 | assert_eq!(two.fx.sfx.layer, [layer_mode::FALLOFF, 3.0, 0.0, 0.0]); | ||
| 183 | assert_eq!(two.fx.sfx.layer_col, [0.0, 1.0, 1.0, 1.0]); | ||
| 184 | let grad = resolve_in("X = FalloffOperator { Inputs = { ColorVariation = Input { Value = FuID { \"Gradient\" }, }, }, },"); | ||
| 185 | assert_eq!(grad.fx.sfx.proc_a, [proc_kind::FALLOFF_GRADIENT, 2.0, 0.0, 0.0]); | ||
| 186 | assert_eq!(grad.fx.sfx.lut[0], [1.0; 4]); | ||
| 187 | assert_eq!(grad.fx.sfx.layer, [0.0; 4]); | ||
| 188 | } | ||
| 189 | |||
| 190 | #[test] | ||
| 191 | fn reflect_without_reflection_is_its_background_and_images_lay_on_by_uv() { | ||
| 192 | let bg = "BG = MtlBlinn { Inputs = { [\"Diffuse.Color.Red\"] = Input { Value = 0.3, }, }, }, Img = Background { },"; | ||
| 193 | let plain = resolve_in(&format!("{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }}, }}, }},")); | ||
| 194 | assert_eq!((plain.fx.env_mode, plain.diffuse_col[0]), (0, 0.3)); | ||
| 195 | let img = resolve_in(&format!( | ||
| 196 | "{bg} X = MtlReflect {{ Inputs = {{ BackgroundMaterial = Input {{ SourceOp = \"BG\", Source = \"MaterialOutput\", }}, | ||
| 197 | [\"Reflection.Color.Material\"] = Input {{ SourceOp = \"Img\", Source = \"Output\", }}, }}, }}," | ||
| 198 | )); | ||
| 199 | assert_eq!((img.fx.env_mode, img.fx.env_map_mode, img.fx.env_tex_slot), (2, 5, 1)); | ||
| 200 | } | ||
| 201 | |||
| 202 | #[test] | ||
| 203 | fn chan_bool_unwired_inputs_are_black_and_bare_images_unlit() { | ||
| 204 | let empty = resolve_in("X = MtlChanBool { },"); | ||
| 205 | assert_eq!(empty.diffuse_col, [0.0, 0.0, 0.0, 1.0]); | ||
| 206 | assert_eq!(empty.fx.sfx.layer_col, [0.0, 0.0, 0.0, 1.0]); | ||
| 207 | assert!(empty.fx.cb_enabled); | ||
| 208 | let img = resolve_in("Img = Background { }, X = MtlChanBool { Inputs = { BackgroundMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },"); | ||
| 209 | assert!(img.unlit && img.tex_node.is_some()); | ||
| 210 | } | ||
| 211 | |||
| 212 | #[test] | ||
| 213 | fn pbr_uber_reads_coat_and_sheen() { | ||
| 214 | let mat = resolve_in("X = MtlPBRUber { Inputs = { [\"Coat.Coat\"] = Input { Value = 1, }, [\"Sheen.Sheen\"] = Input { Value = 0.5, }, [\"Sheen.Color.Blue\"] = Input { Value = 0, }, }, },"); | ||
| 215 | assert_eq!(mat.fx.sfx.pbr_layers, [1.0, 0.0, 1.5, 0.5]); | ||
| 216 | assert_eq!(mat.fx.sfx.sheen, [1.0, 1.0, 0.0, 0.3]); | ||
| 217 | } | ||
| 218 | |||
| 219 | #[test] | ||
| 220 | fn tex_catcher_without_projectors_is_transparent() { | ||
| 221 | let mat = resolve_in("X = TexCatcher { },"); | ||
| 222 | assert_eq!(mat.diffuse_col[3], 0.0); | ||
| 223 | assert!(mat.has_material_shader); | ||
| 224 | } | ||
| 225 | } | ||
crates/engine/src/scene3d/mesh.rs+29-22| ... | @@ -19,9 +19,10 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte | ... | @@ -19,9 +19,10 @@ pub(super) fn build_shape_mesh(shape: &ShapeKind, tex_aspect: f32) -> (Vec<Verte |
| 19 | start_sweep_deg, | 19 | start_sweep_deg, |
| 20 | end_sweep_deg, | 20 | end_sweep_deg, |
| 21 | sub_base, | 21 | sub_base, |
| 22 | sub_height, | ||
| 22 | top_cap, | 23 | top_cap, |
| 23 | bottom_cap, | 24 | bottom_cap, |
| 24 | } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, *sub_base, [*top_cap, *bottom_cap]), | 25 | } => build_cylinder(*radius, *height, *start_sweep_deg, *end_sweep_deg, [*sub_base, *sub_height], [*top_cap, *bottom_cap]), |
| 25 | ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), | 26 | ShapeKind::Cube { width, sub, faces } => build_cube(*width, (*sub).clamp(1, 64), *faces), |
| 26 | ShapeKind::CustomMesh(verts) => { | 27 | ShapeKind::CustomMesh(verts) => { |
| 27 | let v = verts.as_ref().clone(); | 28 | let v = verts.as_ref().clone(); |
| ... | @@ -150,39 +151,33 @@ fn build_cylinder( | ... | @@ -150,39 +151,33 @@ fn build_cylinder( |
| 150 | height: f32, | 151 | height: f32, |
| 151 | start_sweep_deg: f32, | 152 | start_sweep_deg: f32, |
| 152 | end_sweep_deg: f32, | 153 | end_sweep_deg: f32, |
| 153 | sub_base: u32, | 154 | [sub_base, sub_height]: [u32; 2], |
| 154 | caps: [bool; 2], | 155 | caps: [bool; 2], |
| 155 | ) -> (Vec<Vertex3D>, Vec<u32>) { | 156 | ) -> (Vec<Vertex3D>, Vec<u32>) { |
| 156 | let seg_u = sub_base.clamp(16, 96); | 157 | let seg_u = sub_base.clamp(16, 96); |
| 158 | let seg_v = sub_height.clamp(1, 256); | ||
| 157 | let half_h = height * 0.5; | 159 | let half_h = height * 0.5; |
| 158 | let a0 = start_sweep_deg.to_radians(); | 160 | let a0 = start_sweep_deg.to_radians(); |
| 159 | let a1 = end_sweep_deg.to_radians(); | 161 | let a1 = end_sweep_deg.to_radians(); |
| 160 | let mut verts = Vec::with_capacity(((seg_u + 1) * 2) as usize); | 162 | let rows = seg_v + 1; |
| 161 | let mut idx = Vec::with_capacity((seg_u * 6) as usize); | 163 | let mut verts = Vec::with_capacity(((seg_u + 1) * rows) as usize); |
| 164 | let mut idx = Vec::with_capacity((seg_u * seg_v * 6) as usize); | ||
| 162 | for iu in 0..=seg_u { | 165 | for iu in 0..=seg_u { |
| 163 | let u = iu as f32 / seg_u as f32; | 166 | let u = iu as f32 / seg_u as f32; |
| 164 | // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc | 167 | // Fusion Cylinder: theta=270° faces -Z (into camera); u sweeps across the arc |
| 165 | let theta = a0 + (a1 - a0) * u; | 168 | let theta = a0 + (a1 - a0) * u; |
| 166 | let (st, ct) = theta.sin_cos(); | 169 | let (nz, nx) = theta.sin_cos(); |
| 167 | let nx = ct; | 170 | for iv in 0..rows { |
| 168 | let nz = st; | 171 | let v = iv as f32 / seg_v as f32; |
| 169 | verts.push(Vertex3D { | 172 | verts.push(Vertex3D { pos: [nx * radius, half_h - height * v, nz * radius], normal: [nx, 0.0, nz], uv: [1.0 - u, v] }); |
| 170 | pos: [nx * radius, half_h, nz * radius], | 173 | } |
| 171 | normal: [nx, 0.0, nz], | ||
| 172 | uv: [1.0 - u, 0.0], | ||
| 173 | }); | ||
| 174 | verts.push(Vertex3D { | ||
| 175 | pos: [nx * radius, -half_h, nz * radius], | ||
| 176 | normal: [nx, 0.0, nz], | ||
| 177 | uv: [1.0 - u, 1.0], | ||
| 178 | }); | ||
| 179 | } | 174 | } |
| 180 | for iu in 0..seg_u { | 175 | for iu in 0..seg_u { |
| 181 | let a = iu * 2; | 176 | for iv in 0..seg_v { |
| 182 | let b = a + 1; | 177 | let a = iu * rows + iv; |
| 183 | let c = a + 3; | 178 | let (b, d) = (a + 1, a + rows); |
| 184 | let d = a + 2; | 179 | idx.extend_from_slice(&[a, b, d, b, d + 1, d]); |
| 185 | idx.extend_from_slice(&[a, b, d, b, c, d]); | 180 | } |
| 186 | } | 181 | } |
| 187 | for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) { | 182 | for (cap, (y, ny)) in caps.into_iter().zip([(half_h, 1.0), (-half_h, -1.0)]) { |
| 188 | if !cap { | 183 | if !cap { |
| ... | @@ -514,6 +509,18 @@ mod tests { | ... | @@ -514,6 +509,18 @@ mod tests { |
| 514 | assert_eq!(capped.len(), open.len() + 1 + 9); | 509 | assert_eq!(capped.len(), open.len() + 1 + 9); |
| 515 | } | 510 | } |
| 516 | 511 | ||
| 512 | #[test] | ||
| 513 | fn cylinder_height_subdivision_adds_rings() { | ||
| 514 | let rings = |sub_height| { | ||
| 515 | let (v, _) = build_cylinder(1.0, 2.0, 0.0, 360.0, [8, sub_height], [false, false]); | ||
| 516 | let mut ys: Vec<i32> = v.iter().map(|p| (p.pos[1] * 1000.0).round() as i32).collect(); | ||
| 517 | ys.sort_unstable(); | ||
| 518 | ys.dedup(); | ||
| 519 | ys.len() | ||
| 520 | }; | ||
| 521 | assert_eq!((rings(1), rings(4)), (2, 5)); | ||
| 522 | } | ||
| 523 | |||
| 517 | #[test] | 524 | #[test] |
| 518 | fn torus_tube_stays_within_radius_plus_section() { | 525 | fn torus_tube_stays_within_radius_plus_section() { |
| 519 | let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8); | 526 | let (verts, _) = build_torus(1.0, 0.5, [0.0, 360.0], 16, 8); |
crates/engine/src/scene3d/mesh.wgsl created+706| ... | @@ -0,0 +1,706 @@ | ||
| 1 | struct MeshUniform { | ||
| 2 | mvp: mat4x4<f32>, | ||
| 3 | model: mat4x4<f32>, | ||
| 4 | view: mat4x4<f32>, | ||
| 5 | dod: vec4<f32>, | ||
| 6 | flags: vec4<f32>, | ||
| 7 | diffuse_col: vec4<f32>, | ||
| 8 | specular_col: vec4<f32>, | ||
| 9 | ambient: vec4<f32>, | ||
| 10 | dir_to_light: array<vec4<f32>, MAX_DIR_LIGHTS>, | ||
| 11 | dir_color: array<vec4<f32>, MAX_DIR_LIGHTS>, | ||
| 12 | cam_pos: vec4<f32>, | ||
| 13 | light_counts: vec4<f32>, | ||
| 14 | uv_xform: vec4<f32>, | ||
| 15 | uv_off_wrap: vec4<f32>, | ||
| 16 | mat_fx: vec4<f32>, | ||
| 17 | bump_uv_xform: vec4<f32>, | ||
| 18 | bump_off_wrap: vec4<f32>, | ||
| 19 | bump_dod: vec4<f32>, | ||
| 20 | bump_params: vec4<f32>, | ||
| 21 | mtl_params: vec4<f32>, | ||
| 22 | env_rot_0: vec4<f32>, | ||
| 23 | env_rot_1: vec4<f32>, | ||
| 24 | env_rot_2: vec4<f32>, | ||
| 25 | refl_strength: vec4<f32>, | ||
| 26 | refl_params: vec4<f32>, | ||
| 27 | refl_tint: vec4<f32>, | ||
| 28 | refract_tint: vec4<f32>, | ||
| 29 | cb_ops_a: vec4<f32>, | ||
| 30 | cb_ops: vec4<f32>, | ||
| 31 | cb_ops_b: vec4<f32>, | ||
| 32 | cb_flags: vec4<f32>, | ||
| 33 | point_pos: array<vec4<f32>, MAX_LIGHTS>, | ||
| 34 | point_col: array<vec4<f32>, MAX_LIGHTS>, | ||
| 35 | spot_pos: array<vec4<f32>, MAX_LIGHTS>, | ||
| 36 | spot_dir: array<vec4<f32>, MAX_LIGHTS>, | ||
| 37 | spot_col: array<vec4<f32>, MAX_LIGHTS>, | ||
| 38 | sfx: SurfaceFx, | ||
| 39 | }; | ||
| 40 | |||
| 41 | struct ShadowUniform { | ||
| 42 | face_vp: array<mat4x4<f32>, 6 * MAX_SHADOW_LIGHTS>, | ||
| 43 | point: array<vec4<f32>, MAX_LIGHTS>, | ||
| 44 | }; | ||
| 45 | |||
| 46 | override BACK_PASS: bool = false; | ||
| 47 | |||
| 48 | @group(0) @binding(0) var<uniform> u: MeshUniform; | ||
| 49 | @group(0) @binding(1) var mat_tex: texture_2d<f32>; | ||
| 50 | @group(0) @binding(2) var mat_samp: sampler; | ||
| 51 | @group(0) @binding(3) var<uniform> shadow: ShadowUniform; | ||
| 52 | @group(0) @binding(4) var shadow_maps: texture_2d_array<f32>; | ||
| 53 | @group(0) @binding(5) var bump_tex: texture_2d<f32>; | ||
| 54 | |||
| 55 | struct VsIn { | ||
| 56 | @location(0) pos: vec3<f32>, | ||
| 57 | @location(1) normal: vec3<f32>, | ||
| 58 | @location(2) uv: vec2<f32>, | ||
| 59 | }; | ||
| 60 | |||
| 61 | struct VsOut { | ||
| 62 | @builtin(position) clip: vec4<f32>, | ||
| 63 | @location(0) uv: vec2<f32>, | ||
| 64 | @location(1) world_pos: vec3<f32>, | ||
| 65 | @location(2) world_n: vec3<f32>, | ||
| 66 | @location(3) local_pos: vec3<f32>, | ||
| 67 | @location(4) local_n: vec3<f32>, | ||
| 68 | }; | ||
| 69 | |||
| 70 | // Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay | ||
| 71 | // perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored | ||
| 72 | // transforms pointing outward. | ||
| 73 | fn normal_matrix(m: mat4x4<f32>) -> mat3x3<f32> { | ||
| 74 | let c0 = m[0].xyz; | ||
| 75 | let c1 = m[1].xyz; | ||
| 76 | let c2 = m[2].xyz; | ||
| 77 | let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0); | ||
| 78 | return mat3x3<f32>(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign; | ||
| 79 | } | ||
| 80 | |||
| 81 | @vertex | ||
| 82 | fn vs_mesh(v: VsIn) -> VsOut { | ||
| 83 | var out: VsOut; | ||
| 84 | let wp = u.model * vec4<f32>(v.pos, 1.0); | ||
| 85 | out.clip = u.mvp * vec4<f32>(v.pos, 1.0); | ||
| 86 | out.uv = v.uv; | ||
| 87 | out.world_pos = wp.xyz; | ||
| 88 | let wn = normal_matrix(u.model) * v.normal; | ||
| 89 | let nlen = length(wn); | ||
| 90 | var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); | ||
| 91 | var ln = v.normal; | ||
| 92 | if (u.flags.w > 0.5) { | ||
| 93 | n_norm = -n_norm; | ||
| 94 | ln = -ln; | ||
| 95 | } | ||
| 96 | out.world_n = n_norm; | ||
| 97 | out.local_pos = v.pos; | ||
| 98 | out.local_n = ln; | ||
| 99 | return out; | ||
| 100 | } | ||
| 101 | |||
| 102 | fn light_attenuation(dist: f32, decay_type: f32) -> f32 { | ||
| 103 | let dt = i32(decay_type + 0.5); | ||
| 104 | let d = max(dist, 1e-3); | ||
| 105 | if (dt == 1) { | ||
| 106 | return 1.0 / d; | ||
| 107 | } else if (dt == 2) { | ||
| 108 | return 1.0 / (d * d); | ||
| 109 | } | ||
| 110 | return 1.0; | ||
| 111 | } | ||
| 112 | |||
| 113 | /// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. | ||
| 114 | fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos: vec3<f32>) -> f32 { | ||
| 115 | let params = shadow.point[i]; | ||
| 116 | if (params.x < -0.5) { | ||
| 117 | return 0.0; | ||
| 118 | } | ||
| 119 | let slot = i32(params.x + 0.5); | ||
| 120 | let dist = length(world_pos - light_pos); | ||
| 121 | // World size of one texel at this distance for a 90 degree face. | ||
| 122 | let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); | ||
| 123 | // The face is picked from the offset point so the lookup never straddles a cube seam. | ||
| 124 | let biased = world_pos + n * (texel * 1.5); | ||
| 125 | let d = biased - light_pos; | ||
| 126 | let a = abs(d); | ||
| 127 | var face = 4; | ||
| 128 | if (a.x >= a.y && a.x >= a.z) { | ||
| 129 | face = select(1, 0, d.x > 0.0); | ||
| 130 | } else if (a.y >= a.z) { | ||
| 131 | face = select(3, 2, d.y > 0.0); | ||
| 132 | } else { | ||
| 133 | face = select(5, 4, d.z > 0.0); | ||
| 134 | } | ||
| 135 | let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(biased, 1.0); | ||
| 136 | if (clip.w <= 1e-5) { | ||
| 137 | return 0.0; | ||
| 138 | } | ||
| 139 | let ndc = clip.xy / clip.w; | ||
| 140 | let base = vec2<i32>(floor(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE))); | ||
| 141 | let last = SHADOW_MAP_SIZE - 1; | ||
| 142 | var occluded = 0.0; | ||
| 143 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 144 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 145 | let t = clamp(base + vec2<i32>(dx, dy), vec2<i32>(0), vec2<i32>(last)); | ||
| 146 | let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r; | ||
| 147 | occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored); | ||
| 148 | } | ||
| 149 | } | ||
| 150 | return occluded / 9.0; | ||
| 151 | } | ||
| 152 | |||
| 153 | struct TangentFrame { | ||
| 154 | t: vec3<f32>, | ||
| 155 | b: vec3<f32>, | ||
| 156 | }; | ||
| 157 | |||
| 158 | fn compute_tangent_frame( | ||
| 159 | base_n: vec3<f32>, | ||
| 160 | dpdx_w: vec3<f32>, | ||
| 161 | dpdy_w: vec3<f32>, | ||
| 162 | duvdx: vec2<f32>, | ||
| 163 | duvdy: vec2<f32>, | ||
| 164 | ) -> TangentFrame { | ||
| 165 | let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x; | ||
| 166 | var t_vec: vec3<f32>; | ||
| 167 | var b_vec: vec3<f32>; | ||
| 168 | if (abs(det) > 1e-6) { | ||
| 169 | let inv_det = 1.0 / det; | ||
| 170 | t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det; | ||
| 171 | b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det; | ||
| 172 | t_vec = t_vec - base_n * dot(t_vec, base_n); | ||
| 173 | let t_len = length(t_vec); | ||
| 174 | if (t_len > 1e-5) { | ||
| 175 | t_vec = t_vec / t_len; | ||
| 176 | let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0); | ||
| 177 | b_vec = cross(base_n, t_vec) * b_sign; | ||
| 178 | return TangentFrame(t_vec, b_vec); | ||
| 179 | } | ||
| 180 | } | ||
| 181 | let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9); | ||
| 182 | t_vec = normalize(cross(up, base_n)); | ||
| 183 | b_vec = cross(base_n, t_vec); | ||
| 184 | return TangentFrame(t_vec, b_vec); | ||
| 185 | } | ||
| 186 | |||
| 187 | fn eval_light_contrib( | ||
| 188 | n: vec3<f32>, | ||
| 189 | t_vec: vec3<f32>, | ||
| 190 | b_vec: vec3<f32>, | ||
| 191 | v: vec3<f32>, | ||
| 192 | l: vec3<f32>, | ||
| 193 | light_rgb: vec3<f32>, | ||
| 194 | albedo: vec3<f32>, | ||
| 195 | spec_rgb: vec3<f32>, | ||
| 196 | spec_int: f32, | ||
| 197 | shininess: f32, | ||
| 198 | diffuse_vis: f32, | ||
| 199 | spec_vis: f32, | ||
| 200 | model: i32, | ||
| 201 | ) -> vec3<f32> { | ||
| 202 | let ndotl = max(dot(n, l), 0.0); | ||
| 203 | if (ndotl <= 0.0) { | ||
| 204 | return vec3<f32>(0.0); | ||
| 205 | } | ||
| 206 | if (model == 5) { | ||
| 207 | return pbr_uber_light(n, v, l, light_rgb, albedo, diffuse_vis, spec_vis); | ||
| 208 | } | ||
| 209 | if (model == 3) { | ||
| 210 | return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265); | ||
| 211 | } | ||
| 212 | var out = albedo * light_rgb * (ndotl * diffuse_vis); | ||
| 213 | if (spec_int > 1e-4) { | ||
| 214 | let h = normalize(l + v); | ||
| 215 | var lobe: f32; | ||
| 216 | if (model == 1) { | ||
| 217 | lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); | ||
| 218 | } else if (model == 2) { | ||
| 219 | // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F. | ||
| 220 | // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L` | ||
| 221 | // simplifies to `(F*D*G)/(4*N·V)`. | ||
| 222 | let nh = max(dot(n, h), 1e-3); | ||
| 223 | let nv = max(dot(n, v), 1e-3); | ||
| 224 | let vh = max(dot(v, h), 1e-3); | ||
| 225 | let m2 = max(shininess * shininess, 1e-3); | ||
| 226 | let nh2 = nh * nh; | ||
| 227 | let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2); | ||
| 228 | let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh)); | ||
| 229 | var fresnel = 1.0; | ||
| 230 | if (u.mtl_params.z > 0.5) { | ||
| 231 | let eta = max(u.mtl_params.y, 1.0); | ||
| 232 | let c = vh; | ||
| 233 | let g = sqrt(max(eta * eta + c * c - 1.0, 0.0)); | ||
| 234 | let gmc = g - c; | ||
| 235 | let gpc = max(g + c, 1e-5); | ||
| 236 | let r_s = gmc / gpc; | ||
| 237 | let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5); | ||
| 238 | fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p); | ||
| 239 | } | ||
| 240 | lobe = (fresnel * d_term * g_term) / (4.0 * nv); | ||
| 241 | } else if (model == 4) { | ||
| 242 | // Anisotropic Ward (1992) BRDF * (N·L) using tangent frame (T, B) and SpreadU/SpreadV. | ||
| 243 | let nh = max(dot(n, h), 1e-3); | ||
| 244 | let nv = max(dot(n, v), 1e-3); | ||
| 245 | let su = max(shininess, 1e-3); | ||
| 246 | let sv = max(u.mtl_params.w, 1e-3); | ||
| 247 | let ht = dot(h, t_vec) / su; | ||
| 248 | let hb = dot(h, b_vec) / sv; | ||
| 249 | let expo = -(ht * ht + hb * hb) / (nh * nh); | ||
| 250 | let denom = max(4.0 * 3.14159265 * su * sv * sqrt(nv), 1e-4); | ||
| 251 | lobe = (sqrt(ndotl) / denom) * exp(max(expo, -80.0)); | ||
| 252 | } else { | ||
| 253 | lobe = pow(max(dot(n, h), 0.0), shininess); | ||
| 254 | } | ||
| 255 | out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis); | ||
| 256 | } | ||
| 257 | return out; | ||
| 258 | } | ||
| 259 | |||
| 260 | fn sample_bump_height(uv_in: vec2<f32>, wrap_f: f32, ch: i32) -> f32 { | ||
| 261 | let uv = wrap_uv_only(uv_in, wrap_f); | ||
| 262 | let c = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); | ||
| 263 | if (ch == 1) { | ||
| 264 | return (c.r + c.g + c.b) / 3.0; | ||
| 265 | } else if (ch == 2) { | ||
| 266 | return max(c.r, max(c.g, c.b)); | ||
| 267 | } else if (ch == 3) { | ||
| 268 | return min(c.r, min(c.g, c.b)); | ||
| 269 | } else if (ch == 4) { | ||
| 270 | return c.r; | ||
| 271 | } else if (ch == 5) { | ||
| 272 | return c.g; | ||
| 273 | } else if (ch == 6) { | ||
| 274 | return c.b; | ||
| 275 | } else if (ch == 7) { | ||
| 276 | return c.a; | ||
| 277 | } | ||
| 278 | return dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114)); | ||
| 279 | } | ||
| 280 | |||
| 281 | fn perturb_bump_normal( | ||
| 282 | base_n: vec3<f32>, | ||
| 283 | dpdx_w: vec3<f32>, | ||
| 284 | dpdy_w: vec3<f32>, | ||
| 285 | duvdx: vec2<f32>, | ||
| 286 | duvdy: vec2<f32>, | ||
| 287 | uv_in: vec2<f32>, | ||
| 288 | bump_scale: f32, | ||
| 289 | bump_mode: f32, | ||
| 290 | bump_wrap: f32, | ||
| 291 | clamp_z: f32, | ||
| 292 | bump_ch: i32, | ||
| 293 | ) -> vec3<f32> { | ||
| 294 | var uv = uv_in; | ||
| 295 | if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { | ||
| 296 | let bdims = vec2<f32>(textureDimensions(bump_tex)); | ||
| 297 | let canvas_px = vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w); | ||
| 298 | uv = (canvas_px - u.bump_dod.xy) / bdims; | ||
| 299 | } | ||
| 300 | let frame = compute_tangent_frame(base_n, dpdx_w, dpdy_w, duvdx, duvdy); | ||
| 301 | let t_vec = frame.t; | ||
| 302 | let b_vec = frame.b; | ||
| 303 | |||
| 304 | if (bump_mode > 0.5) { | ||
| 305 | let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0); | ||
| 306 | 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); | ||
| 307 | let tn = b_rgb * 2.0 - vec3<f32>(1.0); | ||
| 308 | let perturbed = t_vec * tn.x + b_vec * tn.y + base_n * tn.z; | ||
| 309 | let plen = length(perturbed); | ||
| 310 | return select(base_n, perturbed / plen, plen > 1e-5); | ||
| 311 | } | ||
| 312 | |||
| 313 | let inv_dim = vec2<f32>(1.0) / max(vec2<f32>(textureDimensions(bump_tex)), vec2<f32>(1.0)); | ||
| 314 | let h_l = sample_bump_height(uv - vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch); | ||
| 315 | let h_r = sample_bump_height(uv + vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch); | ||
| 316 | let h_d = sample_bump_height(uv - vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch); | ||
| 317 | let h_u = sample_bump_height(uv + vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch); | ||
| 318 | let dhdu = (h_r - h_l) * 0.5 * bump_scale; | ||
| 319 | let dhdv = (h_u - h_d) * 0.5 * bump_scale; | ||
| 320 | return normalize(base_n - t_vec * dhdu + b_vec * dhdv); | ||
| 321 | } | ||
| 322 | |||
| 323 | fn unpremultiply(c: vec4<f32>) -> vec3<f32> { | ||
| 324 | return select(vec3<f32>(0.0), c.rgb / max(c.a, 1e-5), c.a > 1e-5); | ||
| 325 | } | ||
| 326 | |||
| 327 | // Ambient plus every light's contribution for one material. | ||
| 328 | fn shade( | ||
| 329 | pos: vec3<f32>, | ||
| 330 | n: vec3<f32>, | ||
| 331 | v: vec3<f32>, | ||
| 332 | tf: TangentFrame, | ||
| 333 | albedo: vec3<f32>, | ||
| 334 | spec_rgb: vec3<f32>, | ||
| 335 | spec_int: f32, | ||
| 336 | exponent: f32, | ||
| 337 | model: i32, | ||
| 338 | ) -> vec3<f32> { | ||
| 339 | let shininess = select(max(exponent, 1.0), exponent, model > 1); | ||
| 340 | var lit = albedo * u.ambient.rgb; | ||
| 341 | let n_dir = i32(u.light_counts.z + 0.5); | ||
| 342 | for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { | ||
| 343 | if (i >= n_dir) { break; } | ||
| 344 | let l = normalize(u.dir_to_light[i].xyz); | ||
| 345 | lit = lit + eval_light_contrib(n, tf.t, tf.b, v, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0, model); | ||
| 346 | } | ||
| 347 | |||
| 348 | let n_pt = i32(u.light_counts.x + 0.5); | ||
| 349 | for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { | ||
| 350 | if (i >= n_pt) { break; } | ||
| 351 | let to_l = u.point_pos[i].xyz - pos; | ||
| 352 | let dist = max(length(to_l), 1e-4); | ||
| 353 | let att = light_attenuation(dist, u.point_pos[i].w); | ||
| 354 | var occ = 0.0; | ||
| 355 | if (u.light_counts.w > 0.5) { | ||
| 356 | occ = point_shadow_occlusion(i, pos, n, u.point_pos[i].xyz); | ||
| 357 | } | ||
| 358 | lit = lit + eval_light_contrib( | ||
| 359 | n, tf.t, tf.b, v, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, | ||
| 360 | 1.0 - shadow.point[i].y * occ, 1.0 - occ, model, | ||
| 361 | ); | ||
| 362 | } | ||
| 363 | |||
| 364 | let n_sp = i32(u.light_counts.y + 0.5); | ||
| 365 | for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { | ||
| 366 | if (i >= n_sp) { break; } | ||
| 367 | let to_l = u.spot_pos[i].xyz - pos; | ||
| 368 | let dist = max(length(to_l), 1e-4); | ||
| 369 | let l_dir = to_l / dist; | ||
| 370 | let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); | ||
| 371 | let cos_inner = u.spot_pos[i].w; | ||
| 372 | let cos_outer = u.spot_dir[i].w; | ||
| 373 | let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); | ||
| 374 | if (cone > 0.0) { | ||
| 375 | let att = light_attenuation(dist, u.spot_col[i].w) * cone; | ||
| 376 | lit = lit + eval_light_contrib(n, tf.t, tf.b, v, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0, model); | ||
| 377 | } | ||
| 378 | } | ||
| 379 | return lit; | ||
| 380 | } | ||
| 381 | |||
| 382 | // Secondary material of `MtlChanBool`, `MtlMerge3D` and `FalloffOperator`: straight RGB, alpha. | ||
| 383 | fn layer_color(pos: vec3<f32>, n: vec3<f32>, v: vec3<f32>, tf: TangentFrame, uv: vec2<f32>) -> vec4<f32> { | ||
| 384 | var c = u.sfx.layer_col; | ||
| 385 | if (u.sfx.layer.w > 1.5) { | ||
| 386 | let t = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, u.bump_off_wrap.z), 0.0); | ||
| 387 | c = vec4<f32>(unpremultiply(t) * c.rgb, t.a * c.a); | ||
| 388 | } | ||
| 389 | if (u.sfx.layer.z > 0.5) { | ||
| 390 | let model = i32(u.sfx.layer_mtl.y + 0.5); | ||
| 391 | c = vec4<f32>(shade(pos, n, v, tf, c.rgb, u.sfx.layer_spec.rgb, u.sfx.layer_mtl.x, u.sfx.layer_spec.w, model), c.a); | ||
| 392 | } | ||
| 393 | return c; | ||
| 394 | } | ||
| 395 | |||
| 396 | // Environment colour along `world_dir` (`env_map_mode`: 0 equirect, 1 angular, 2-4 cube map, | ||
| 397 | // 5 the image at `mesh_uv`), tinted, from the texture in `env_tex_slot`. | ||
| 398 | fn sample_sphere_map(world_dir: vec3<f32>, mesh_uv: vec2<f32>) -> vec4<f32> { | ||
| 399 | let slot = i32(u.env_rot_2.w + 0.5); | ||
| 400 | if (slot == 0) { | ||
| 401 | return vec4<f32>(u.refl_tint.rgb, 1.0); | ||
| 402 | } | ||
| 403 | let rot = mat3x3<f32>(u.env_rot_0.xyz, u.env_rot_1.xyz, u.env_rot_2.xyz); | ||
| 404 | let d = normalize(rot * env_space(world_dir)); | ||
| 405 | let map_mode = i32(u.env_rot_1.w + 0.5); | ||
| 406 | let dod = select(u.dod, u.bump_dod, slot == 2); | ||
| 407 | let has_dod = dod.z > 0.5 && dod.w > 0.5; | ||
| 408 | let tex_dims = vec2<f32>(select(textureDimensions(mat_tex), textureDimensions(bump_tex), slot == 2)); | ||
| 409 | var uv: vec2<f32>; | ||
| 410 | if (map_mode == 5) { | ||
| 411 | uv = mesh_uv; | ||
| 412 | } else if (map_mode >= 2) { | ||
| 413 | uv = cube_uv(d, map_mode, select(tex_dims, dod.zw, has_dod)); | ||
| 414 | } else { | ||
| 415 | // Fusion's longitude runs against atan2(x, z); Angular maps V linearly by height. | ||
| 416 | let u_c = 1.0 - fract(atan2(d.x, d.z) / 6.2831853 + 0.75); | ||
| 417 | let v_c = select(acos(clamp(d.y, -1.0, 1.0)) / 3.14159265, 0.5 - 0.5 * d.y, map_mode == 1); | ||
| 418 | uv = vec2<f32>(u_c, v_c); | ||
| 419 | } | ||
| 420 | if (has_dod) { | ||
| 421 | uv = clamp((uv * dod.zw - dod.xy) / tex_dims, vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 422 | } | ||
| 423 | let raw = select(textureSampleLevel(mat_tex, mat_samp, uv, 0.0), textureSampleLevel(bump_tex, mat_samp, uv, 0.0), slot == 2); | ||
| 424 | return vec4<f32>(unpremultiply(raw) * u.refl_tint.rgb, raw.a); | ||
| 425 | } | ||
| 426 | |||
| 427 | // Fusion evaluates the HLS operands (11-16) as 0 and EnvCoords as the eye-space normal's XY. | ||
| 428 | fn cb_operand( | ||
| 429 | idx: i32, | ||
| 430 | bg: vec4<f32>, | ||
| 431 | fg: vec4<f32>, | ||
| 432 | pos: vec3<f32>, | ||
| 433 | uv: vec2<f32>, | ||
| 434 | env_c: vec2<f32>, | ||
| 435 | n: vec3<f32>, | ||
| 436 | ) -> f32 { | ||
| 437 | switch idx { | ||
| 438 | case 0: { return fg.r; } | ||
| 439 | case 1: { return fg.g; } | ||
| 440 | case 2: { return fg.b; } | ||
| 441 | case 3: { return fg.a; } | ||
| 442 | case 4: { return bg.r; } | ||
| 443 | case 5: { return bg.g; } | ||
| 444 | case 6: { return bg.b; } | ||
| 445 | case 7: { return bg.a; } | ||
| 446 | case 9: { return 1.0; } | ||
| 447 | case 10: { return 0.5; } | ||
| 448 | case 17: { return dot(fg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } | ||
| 449 | case 18: { return dot(bg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } | ||
| 450 | case 19: { return pos.x; } | ||
| 451 | case 20: { return pos.y; } | ||
| 452 | case 21: { return pos.z; } | ||
| 453 | case 22: { return uv.x; } | ||
| 454 | case 23: { return 1.0 - uv.y; } | ||
| 455 | case 25: { return env_c.x; } | ||
| 456 | case 26: { return env_c.y; } | ||
| 457 | case 28: { return n.x; } | ||
| 458 | case 29: { return n.y; } | ||
| 459 | case 30: { return n.z; } | ||
| 460 | default: { return 0.0; } | ||
| 461 | } | ||
| 462 | } | ||
| 463 | |||
| 464 | fn cb_combine(op: i32, a: f32, b: f32) -> f32 { | ||
| 465 | switch op { | ||
| 466 | case 0: { return a; } | ||
| 467 | case 1: { return b; } | ||
| 468 | case 2: { return 1.0 - a; } | ||
| 469 | case 3: { return 1.0 - b; } | ||
| 470 | case 4: { return a + b; } | ||
| 471 | case 5: { return a - b; } | ||
| 472 | case 6: { return a * b; } | ||
| 473 | case 7: { return select(a / b, 0.0, abs(b) <= 1e-5); } | ||
| 474 | case 8: { return min(a, b); } | ||
| 475 | case 9: { return max(a, b); } | ||
| 476 | case 10: { return 0.5 * (a + b); } | ||
| 477 | default: { return a; } | ||
| 478 | } | ||
| 479 | } | ||
| 480 | |||
| 481 | @fragment | ||
| 482 | fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { | ||
| 483 | let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); | ||
| 484 | let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); | ||
| 485 | let dpdx_w = dpdx(in.world_pos); | ||
| 486 | let dpdy_w = dpdy(in.world_pos); | ||
| 487 | let duvdx = dpdx(uv_bump_xformed); | ||
| 488 | let duvdy = dpdy(uv_bump_xformed); | ||
| 489 | let duvdx_main = dpdx(uv_xformed); | ||
| 490 | let duvdy_main = dpdy(uv_xformed); | ||
| 491 | let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; | ||
| 492 | if (facing_away != BACK_PASS) { | ||
| 493 | discard; | ||
| 494 | } | ||
| 495 | |||
| 496 | let env_mode = i32(u.env_rot_0.w + 0.5); | ||
| 497 | let cb_on = u.cb_flags.x > 0.5; | ||
| 498 | let layer_mode = i32(u.sfx.layer.x + 0.5); | ||
| 499 | let proc_on = u.sfx.proc_a.x > 0.5; | ||
| 500 | let v_dir = normalize(u.cam_pos.xyz - in.world_pos); | ||
| 501 | var n_surf = normalize(in.world_n); | ||
| 502 | if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { | ||
| 503 | n_surf = perturb_bump_normal( | ||
| 504 | n_surf, | ||
| 505 | dpdx_w, | ||
| 506 | dpdy_w, | ||
| 507 | duvdx, | ||
| 508 | duvdy, | ||
| 509 | uv_bump_xformed, | ||
| 510 | u.mat_fx.x, | ||
| 511 | u.mat_fx.y, | ||
| 512 | u.bump_off_wrap.z, | ||
| 513 | u.bump_params.x, | ||
| 514 | i32(u.bump_params.y + 0.5), | ||
| 515 | ); | ||
| 516 | } | ||
| 517 | let tframe = compute_tangent_frame(n_surf, dpdx_w, dpdy_w, duvdx_main, duvdy_main); | ||
| 518 | |||
| 519 | var base_straight = vec3<f32>(0.0); | ||
| 520 | var rgb_alpha = u.diffuse_col.a; | ||
| 521 | var out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 522 | |||
| 523 | if (env_mode == 1) { | ||
| 524 | // Standalone SphereMap / CubeMap shader: lookup along the view ray. | ||
| 525 | let env_c = sample_sphere_map(-v_dir, in.uv); | ||
| 526 | base_straight = env_c.rgb * u.diffuse_col.rgb; | ||
| 527 | rgb_alpha = env_c.a * u.diffuse_col.a; | ||
| 528 | out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 529 | } else { | ||
| 530 | var col = u.diffuse_col; | ||
| 531 | var tex_col = vec4<f32>(1.0); | ||
| 532 | var tex_straight = vec3<f32>(1.0); | ||
| 533 | if (u.flags.x > 0.5) { | ||
| 534 | var uv_samp = uv_xformed; | ||
| 535 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 536 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 537 | let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); | ||
| 538 | uv_samp = (canvas_px - u.dod.xy) / tdims; | ||
| 539 | if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { | ||
| 540 | discard; | ||
| 541 | } | ||
| 542 | } | ||
| 543 | tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); | ||
| 544 | } | ||
| 545 | if (proc_on) { | ||
| 546 | tex_col = surface_proc(tex_col, vec2<f32>(in.uv.x, 1.0 - in.uv.y), n_surf, v_dir); | ||
| 547 | } | ||
| 548 | if (u.flags.x > 0.5 || proc_on) { | ||
| 549 | if (u.mat_fx.z <= 0.5) { | ||
| 550 | tex_straight = unpremultiply(tex_col); | ||
| 551 | } | ||
| 552 | col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; | ||
| 553 | } | ||
| 554 | // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) | ||
| 555 | // modulates output alpha without attenuating diffuse/specular RGB. | ||
| 556 | rgb_alpha = col.a; | ||
| 557 | out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 558 | if (env_mode == 0 && !cb_on && layer_mode == 0 && out_alpha <= 0.002) { | ||
| 559 | discard; | ||
| 560 | } | ||
| 561 | |||
| 562 | let albedo = tex_straight * u.diffuse_col.rgb; | ||
| 563 | if (env_mode == 2 && u.refl_tint.w < 0.5) { | ||
| 564 | base_straight = vec3<f32>(0.0); | ||
| 565 | rgb_alpha = 0.0; | ||
| 566 | out_alpha = 0.0; | ||
| 567 | } else if (u.flags.y > 0.5) { | ||
| 568 | base_straight = shade(in.world_pos, n_surf, v_dir, tframe, albedo, u.specular_col.rgb, u.flags.z, u.specular_col.w, i32(u.mat_fx.w + 0.5)) | ||
| 569 | + u.sfx.emission.rgb; | ||
| 570 | } else { | ||
| 571 | base_straight = albedo * u.uv_off_wrap.w; | ||
| 572 | } | ||
| 573 | |||
| 574 | if (env_mode == 2) { | ||
| 575 | let r_dir = reflect(-v_dir, n_surf); | ||
| 576 | let refl_c = sample_sphere_map(r_dir, in.uv); | ||
| 577 | var refl_str = clamp(u.refl_strength.y, 0.0, 1.0); | ||
| 578 | if (u.refl_strength.x > 0.5) { | ||
| 579 | let cos_nv = clamp(dot(n_surf, v_dir), 0.0, 1.0); | ||
| 580 | let f_ang = pow(1.0 - cos_nv, max(u.refl_params.z, 1e-4)); | ||
| 581 | refl_str = clamp(mix(u.refl_params.y, u.refl_params.x, f_ang), 0.0, 1.0); | ||
| 582 | } | ||
| 583 | var under_rgb = base_straight; | ||
| 584 | var under_a = rgb_alpha; | ||
| 585 | if (rgb_alpha < 0.999 && u.refl_params.w > 0.01 && u.env_rot_2.w > 0.5 && u.refl_tint.w > 0.5) { | ||
| 586 | let eta = 1.0 / max(u.refl_params.w, 0.01); | ||
| 587 | var refr_dir = refract(-v_dir, n_surf, eta); | ||
| 588 | if (dot(refr_dir, refr_dir) < 1e-5) { | ||
| 589 | refr_dir = r_dir; | ||
| 590 | } | ||
| 591 | let refr_c = sample_sphere_map(refr_dir, in.uv); | ||
| 592 | under_rgb = mix(refr_c.rgb * u.refract_tint.rgb, base_straight, rgb_alpha); | ||
| 593 | under_a = clamp(max(rgb_alpha, refr_c.a * (1.0 - rgb_alpha)), 0.0, 1.0); | ||
| 594 | } | ||
| 595 | let under_premul = under_rgb * under_a; | ||
| 596 | let refl_a = refl_str * refl_c.a; | ||
| 597 | let out_premul = under_premul * (1.0 - refl_str) + refl_c.rgb * refl_a; | ||
| 598 | let final_a = clamp(under_a * (1.0 - refl_str) + refl_a, 0.0, 1.0); | ||
| 599 | base_straight = select(vec3<f32>(0.0), out_premul / max(final_a, 1e-5), final_a > 1e-5); | ||
| 600 | rgb_alpha = final_a; | ||
| 601 | out_alpha = clamp(out_alpha * (1.0 - refl_str) + refl_a, 0.0, 1.0); | ||
| 602 | } | ||
| 603 | } | ||
| 604 | |||
| 605 | if (layer_mode >= 2) { | ||
| 606 | let fg = layer_color(in.world_pos, n_surf, v_dir, tframe, uv_xformed); | ||
| 607 | let bg_p = vec4<f32>(base_straight * rgb_alpha, out_alpha); | ||
| 608 | let fg_p = vec4<f32>(fg.rgb * fg.a, fg.a); | ||
| 609 | var o: vec4<f32>; | ||
| 610 | if (layer_mode == 2) { | ||
| 611 | o = fg_p * u.sfx.layer.y + bg_p * (1.0 - fg.a * u.sfx.layer.y); | ||
| 612 | } else { | ||
| 613 | o = mix(bg_p, fg_p, falloff_t(n_surf, v_dir, u.sfx.layer.y)); | ||
| 614 | } | ||
| 615 | base_straight = unpremultiply(o); | ||
| 616 | rgb_alpha = o.a; | ||
| 617 | out_alpha = o.a; | ||
| 618 | } | ||
| 619 | base_straight = apply_fog(base_straight, in.world_pos); | ||
| 620 | |||
| 621 | if (cb_on) { | ||
| 622 | let bg_c = vec4<f32>(base_straight, out_alpha); | ||
| 623 | let fg_c = layer_color(in.world_pos, n_surf, v_dir, tframe, uv_xformed); | ||
| 624 | let cspace = i32(u.cb_flags.y + 0.5); | ||
| 625 | var c_pos = in.world_pos; | ||
| 626 | var c_n = n_surf; | ||
| 627 | if (cspace == 0) { | ||
| 628 | c_pos = in.local_pos; | ||
| 629 | let ln_len = length(in.local_n); | ||
| 630 | c_n = select(vec3<f32>(0.0, 0.0, 1.0), in.local_n / ln_len, ln_len > 1e-5); | ||
| 631 | } else if (cspace == 2) { | ||
| 632 | c_pos = (u.view * vec4<f32>(in.world_pos, 1.0)).xyz; | ||
| 633 | let en = (u.view * vec4<f32>(n_surf, 0.0)).xyz; | ||
| 634 | let elen = length(en); | ||
| 635 | c_n = select(vec3<f32>(0.0, 0.0, 1.0), en / elen, elen > 1e-5); | ||
| 636 | } | ||
| 637 | let env_c = normalize((u.view * vec4<f32>(n_surf, 0.0)).xyz).xy; | ||
| 638 | let r_out = cb_combine(i32(u.cb_ops.x + 0.5), cb_operand(i32(u.cb_ops_a.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 639 | let g_out = cb_combine(i32(u.cb_ops.y + 0.5), cb_operand(i32(u.cb_ops_a.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 640 | let b_out = cb_combine(i32(u.cb_ops.z + 0.5), cb_operand(i32(u.cb_ops_a.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 641 | let a_out = cb_combine(i32(u.cb_ops.w + 0.5), cb_operand(i32(u.cb_ops_a.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 642 | let clamped_a = clamp(a_out, 0.0, 1.0); | ||
| 643 | if (clamped_a <= 0.002) { | ||
| 644 | discard; | ||
| 645 | } | ||
| 646 | // Fusion does not premultiply the channel results by the computed alpha. | ||
| 647 | return vec4<f32>(clamp(vec3<f32>(r_out, g_out, b_out), vec3<f32>(0.0), vec3<f32>(1.0)), clamped_a); | ||
| 648 | } | ||
| 649 | |||
| 650 | if (out_alpha <= 0.002) { | ||
| 651 | discard; | ||
| 652 | } | ||
| 653 | return vec4<f32>(clamp(base_straight * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha); | ||
| 654 | } | ||
| 655 | |||
| 656 | @fragment | ||
| 657 | fn fs_normal(in: VsOut) -> @location(0) vec4<f32> { | ||
| 658 | let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); | ||
| 659 | let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); | ||
| 660 | let dpdx_w = dpdx(in.world_pos); | ||
| 661 | let dpdy_w = dpdy(in.world_pos); | ||
| 662 | let duvdx = dpdx(uv_bump_xformed); | ||
| 663 | let duvdy = dpdy(uv_bump_xformed); | ||
| 664 | let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; | ||
| 665 | if (facing_away != BACK_PASS) { | ||
| 666 | discard; | ||
| 667 | } | ||
| 668 | |||
| 669 | var col = u.diffuse_col; | ||
| 670 | if (u.flags.x > 0.5) { | ||
| 671 | var uv_samp = uv_xformed; | ||
| 672 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 673 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 674 | let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); | ||
| 675 | uv_samp = (canvas_px - u.dod.xy) / tdims; | ||
| 676 | if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { | ||
| 677 | discard; | ||
| 678 | } | ||
| 679 | } | ||
| 680 | let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); | ||
| 681 | col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; | ||
| 682 | } | ||
| 683 | let out_alpha = col.a * u.mtl_params.x; | ||
| 684 | if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && u.sfx.layer.x < 0.5 && out_alpha <= 0.002) { | ||
| 685 | discard; | ||
| 686 | } | ||
| 687 | |||
| 688 | let nlen = length(in.world_n); | ||
| 689 | var n = select(vec3<f32>(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5); | ||
| 690 | if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { | ||
| 691 | n = perturb_bump_normal( | ||
| 692 | n, | ||
| 693 | dpdx_w, | ||
| 694 | dpdy_w, | ||
| 695 | duvdx, | ||
| 696 | duvdy, | ||
| 697 | uv_bump_xformed, | ||
| 698 | u.mat_fx.x, | ||
| 699 | u.mat_fx.y, | ||
| 700 | u.bump_off_wrap.z, | ||
| 701 | u.bump_params.x, | ||
| 702 | i32(u.bump_params.y + 0.5), | ||
| 703 | ); | ||
| 704 | } | ||
| 705 | return vec4<f32>(n, 0.0); | ||
| 706 | } | ||
crates/engine/src/scene3d/mod.rs+24-36| ... | @@ -9,9 +9,13 @@ | ... | @@ -9,9 +9,13 @@ |
| 9 | mod collect; | 9 | mod collect; |
| 10 | mod deform; | 10 | mod deform; |
| 11 | mod fbx; | 11 | mod fbx; |
| 12 | mod fx; | ||
| 13 | mod materials; | ||
| 12 | mod math; | 14 | mod math; |
| 13 | mod mesh; | 15 | mod mesh; |
| 16 | mod scene_ops; | ||
| 14 | mod shader; | 17 | mod shader; |
| 18 | mod textures; | ||
| 15 | 19 | ||
| 16 | pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; | 20 | pub use collect::{collect_scene, collect_scene_with_nodes, eval_transform3d, mat4_inverse}; |
| 17 | pub use math::{ | 21 | pub use math::{ |
| ... | @@ -28,6 +32,7 @@ fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { | ... | @@ -28,6 +32,7 @@ fn lock_or_recover<T>(m: &Mutex<T>) -> MutexGuard<'_, T> { |
| 28 | } | 32 | } |
| 29 | 33 | ||
| 30 | use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; | 34 | use crate::cache::{AuxChannelTex, AuxChannels, CachedTexture, EMPTY_Z_SENTINEL}; |
| 35 | use fx::{SurfaceFx, SURFACE_FX_WGSL}; | ||
| 31 | use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; | 36 | use mesh::{apply_heightmap_displace, build_shape_mesh, triangle_edges}; |
| 32 | use model::NodeId; | 37 | use model::NodeId; |
| 33 | use shader::{ | 38 | use shader::{ |
| ... | @@ -228,7 +233,7 @@ pub struct CameraInstance { | ... | @@ -228,7 +233,7 @@ pub struct CameraInstance { |
| 228 | pub enum ShapeKind { | 233 | pub enum ShapeKind { |
| 229 | ImagePlane, | 234 | ImagePlane, |
| 230 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, | 235 | Sphere { radius: f32, sub_base: u32, sub_height: u32 }, |
| 231 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, top_cap: bool, bottom_cap: bool }, | 236 | Cylinder { radius: f32, height: f32, start_sweep_deg: f32, end_sweep_deg: f32, sub_base: u32, sub_height: u32, top_cap: bool, bottom_cap: bool }, |
| 232 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, | 237 | Plane { width: f32, height: f32, sub_w: u32, sub_h: u32 }, |
| 233 | /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. | 238 | /// Uniform cube with `sub` cells per edge; `faces` is a bitmask over `CUBE_FACES` order. |
| 234 | Cube { width: f32, sub: u32, faces: u8 }, | 239 | Cube { width: f32, sub: u32, faces: u8 }, |
| ... | @@ -295,6 +300,8 @@ pub enum SpecModel { | ... | @@ -295,6 +300,8 @@ pub enum SpecModel { |
| 295 | Pbr, | 300 | Pbr, |
| 296 | /// Anisotropic Ward BRDF (`MtlWard`). | 301 | /// Anisotropic Ward BRDF (`MtlWard`). |
| 297 | Ward, | 302 | Ward, |
| 303 | /// `MtlPBRUber` metal/roughness BRDF; parameters live in `SurfaceFx::pbr`. | ||
| 304 | PbrUber, | ||
| 298 | } | 305 | } |
| 299 | 306 | ||
| 300 | #[derive(Clone, Copy, Debug, PartialEq)] | 307 | #[derive(Clone, Copy, Debug, PartialEq)] |
| ... | @@ -330,16 +337,13 @@ pub struct MaterialFx { | ... | @@ -330,16 +337,13 @@ pub struct MaterialFx { |
| 330 | pub ward_spread_v: f32, | 337 | pub ward_spread_v: f32, |
| 331 | /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`. | 338 | /// Environment shading mode: `0 = none`, `1 = standalone SphereMap`, `2 = MtlReflect`. |
| 332 | pub env_mode: u32, | 339 | pub env_mode: u32, |
| 333 | /// `SphereMap.MapMode`: `0 = equirectangular`, `1 = angular`. | 340 | /// `0 = equirectangular`, `1 = angular`, `2 = vertical cross`, `3 = horizontal cross`, |
| 341 | /// `4 = single cube face`, `5 = image at the mesh UV`. | ||
| 334 | pub env_map_mode: u32, | 342 | pub env_map_mode: u32, |
| 335 | /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`. | 343 | /// Texture slot carrying the environment image: `0 = solid/none`, `1 = mat_tex`, `2 = bump_tex`. |
| 336 | pub env_tex_slot: u32, | 344 | pub env_tex_slot: u32, |
| 337 | /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup. | 345 | /// Column-major 3x3 inverse rotation matrix for `SphereMap` direction lookup. |
| 338 | pub env_rot: [f32; 9], | 346 | pub env_rot: [f32; 9], |
| 339 | /// `SphereMap.StartAngle` in degrees. | ||
| 340 | pub env_start_angle: f32, | ||
| 341 | /// `SphereMap.EndAngle` in degrees. | ||
| 342 | pub env_end_angle: f32, | ||
| 343 | /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`. | 347 | /// `MtlReflect.Reflection.StrengthVariability`: `0 = Constant`, `1 = By Angle`. |
| 344 | pub refl_strength_var: u32, | 348 | pub refl_strength_var: u32, |
| 345 | pub refl_constant_strength: f32, | 349 | pub refl_constant_strength: f32, |
| ... | @@ -355,11 +359,9 @@ pub struct MaterialFx { | ... | @@ -355,11 +359,9 @@ pub struct MaterialFx { |
| 355 | pub cb_ops_a: [u8; 4], | 359 | pub cb_ops_a: [u8; 4], |
| 356 | pub cb_ops: [u8; 4], | 360 | pub cb_ops: [u8; 4], |
| 357 | pub cb_ops_b: [u8; 4], | 361 | pub cb_ops_b: [u8; 4], |
| 358 | pub cb_fg_col: [f32; 4], | ||
| 359 | /// `0 = Model`, `1 = World`, `2 = Eye`. | 362 | /// `0 = Model`, `1 = World`, `2 = Eye`. |
| 360 | pub cb_coord_space: u8, | 363 | pub cb_coord_space: u8, |
| 361 | /// `0 = constant fg_col`, `2 = sample bump_tex for FG`. | 364 | pub sfx: SurfaceFx, |
| 362 | pub cb_fg_tex_slot: u8, | ||
| 363 | } | 365 | } |
| 364 | 366 | ||
| 365 | impl Default for MaterialFx { | 367 | impl Default for MaterialFx { |
| ... | @@ -387,8 +389,6 @@ impl Default for MaterialFx { | ... | @@ -387,8 +389,6 @@ impl Default for MaterialFx { |
| 387 | env_map_mode: 0, | 389 | env_map_mode: 0, |
| 388 | env_tex_slot: 0, | 390 | env_tex_slot: 0, |
| 389 | env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], | 391 | env_rot: [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0], |
| 390 | env_start_angle: 0.0, | ||
| 391 | env_end_angle: 360.0, | ||
| 392 | refl_strength_var: 1, | 392 | refl_strength_var: 1, |
| 393 | refl_constant_strength: 1.0, | 393 | refl_constant_strength: 1.0, |
| 394 | refl_glancing_strength: 0.8, | 394 | refl_glancing_strength: 0.8, |
| ... | @@ -402,9 +402,8 @@ impl Default for MaterialFx { | ... | @@ -402,9 +402,8 @@ impl Default for MaterialFx { |
| 402 | cb_ops_a: [4, 5, 6, 7], | 402 | cb_ops_a: [4, 5, 6, 7], |
| 403 | cb_ops: [0, 0, 0, 0], | 403 | cb_ops: [0, 0, 0, 0], |
| 404 | cb_ops_b: [0, 1, 2, 3], | 404 | cb_ops_b: [0, 1, 2, 3], |
| 405 | cb_fg_col: [0.0, 0.0, 0.0, 0.0], | ||
| 406 | cb_coord_space: 2, | 405 | cb_coord_space: 2, |
| 407 | cb_fg_tex_slot: 0, | 406 | sfx: SurfaceFx::default(), |
| 408 | } | 407 | } |
| 409 | } | 408 | } |
| 410 | } | 409 | } |
| ... | @@ -436,8 +435,6 @@ impl MaterialFx { | ... | @@ -436,8 +435,6 @@ impl MaterialFx { |
| 436 | for v in self.env_rot { | 435 | for v in self.env_rot { |
| 437 | v.to_bits().hash(h); | 436 | v.to_bits().hash(h); |
| 438 | } | 437 | } |
| 439 | self.env_start_angle.to_bits().hash(h); | ||
| 440 | self.env_end_angle.to_bits().hash(h); | ||
| 441 | self.refl_strength_var.hash(h); | 438 | self.refl_strength_var.hash(h); |
| 442 | self.refl_constant_strength.to_bits().hash(h); | 439 | self.refl_constant_strength.to_bits().hash(h); |
| 443 | self.refl_glancing_strength.to_bits().hash(h); | 440 | self.refl_glancing_strength.to_bits().hash(h); |
| ... | @@ -455,11 +452,8 @@ impl MaterialFx { | ... | @@ -455,11 +452,8 @@ impl MaterialFx { |
| 455 | self.cb_ops_a.hash(h); | 452 | self.cb_ops_a.hash(h); |
| 456 | self.cb_ops.hash(h); | 453 | self.cb_ops.hash(h); |
| 457 | self.cb_ops_b.hash(h); | 454 | self.cb_ops_b.hash(h); |
| 458 | for v in self.cb_fg_col { | ||
| 459 | v.to_bits().hash(h); | ||
| 460 | } | ||
| 461 | self.cb_coord_space.hash(h); | 455 | self.cb_coord_space.hash(h); |
| 462 | self.cb_fg_tex_slot.hash(h); | 456 | bytemuck::bytes_of(&self.sfx).hash(h); |
| 463 | } | 457 | } |
| 464 | } | 458 | } |
| 465 | 459 | ||
| ... | @@ -486,8 +480,9 @@ impl ShapeKind { | ... | @@ -486,8 +480,9 @@ impl ShapeKind { |
| 486 | sub_base.hash(h); | 480 | sub_base.hash(h); |
| 487 | sub_height.hash(h); | 481 | sub_height.hash(h); |
| 488 | } | 482 | } |
| 489 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, top_cap, bottom_cap } => { | 483 | ShapeKind::Cylinder { radius, height, start_sweep_deg, end_sweep_deg, sub_base, sub_height, top_cap, bottom_cap } => { |
| 490 | 2u8.hash(h); | 484 | 2u8.hash(h); |
| 485 | sub_height.hash(h); | ||
| 491 | (*top_cap, *bottom_cap).hash(h); | 486 | (*top_cap, *bottom_cap).hash(h); |
| 492 | radius.to_bits().hash(h); | 487 | radius.to_bits().hash(h); |
| 493 | height.to_bits().hash(h); | 488 | height.to_bits().hash(h); |
| ... | @@ -724,7 +719,7 @@ impl Scene3DRenderer { | ... | @@ -724,7 +719,7 @@ impl Scene3DRenderer { |
| 724 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { | 719 | let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { |
| 725 | label: Some("scene3d-shader"), | 720 | label: Some("scene3d-shader"), |
| 726 | source: wgpu::ShaderSource::Wgsl( | 721 | source: wgpu::ShaderSource::Wgsl( |
| 727 | format!("{UV_XFORM_WGSL}{SHADER_3D}") | 722 | format!("{UV_XFORM_WGSL}{SHADER_3D}{SURFACE_FX_WGSL}{}", fx::simplex_wgsl()) |
| 728 | .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) | 723 | .replace("MAX_SHADOW_LIGHTS", &MAX_SHADOW_LIGHTS.to_string()) |
| 729 | .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) | 724 | .replace("MAX_DIR_LIGHTS", &MAX_DIR_LIGHTS.to_string()) |
| 730 | .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) | 725 | .replace("MAX_LIGHTS", &MAX_LIGHTS.to_string()) |
| ... | @@ -1529,8 +1524,11 @@ impl Scene3DRenderer { | ... | @@ -1529,8 +1524,11 @@ impl Scene3DRenderer { |
| 1529 | dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; | 1524 | dir_color[di] = [dl.color[0], dl.color[1], dl.color[2], 0.0]; |
| 1530 | } | 1525 | } |
| 1531 | let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1; | 1526 | let use_diffuse_tex = m.tex.is_some() && fx.env_tex_slot != 1; |
| 1532 | let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.cb_fg_tex_slot != 2; | 1527 | let has_bump_tex = bump_src.is_some() && fx.env_tex_slot != 2 && fx.sfx.layer[3] != 2.0; |
| 1533 | let env_span = ((fx.env_end_angle - fx.env_start_angle) / 360.0).abs().max(1e-4); | 1528 | let mut sfx = fx.sfx; |
| 1529 | if !lighting_enabled { | ||
| 1530 | sfx.layer[2] = 0.0; | ||
| 1531 | } | ||
| 1534 | let uni = MeshUniform { | 1532 | let uni = MeshUniform { |
| 1535 | mvp, | 1533 | mvp, |
| 1536 | model: m.world, | 1534 | model: m.world, |
| ... | @@ -1570,12 +1568,7 @@ impl Scene3DRenderer { | ... | @@ -1570,12 +1568,7 @@ impl Scene3DRenderer { |
| 1570 | env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32], | 1568 | env_rot_0: [fx.env_rot[0], fx.env_rot[1], fx.env_rot[2], fx.env_mode as f32], |
| 1571 | env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32], | 1569 | env_rot_1: [fx.env_rot[3], fx.env_rot[4], fx.env_rot[5], fx.env_map_mode as f32], |
| 1572 | env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32], | 1570 | env_rot_2: [fx.env_rot[6], fx.env_rot[7], fx.env_rot[8], fx.env_tex_slot as f32], |
| 1573 | env_angles: [ | 1571 | refl_strength: [fx.refl_strength_var as f32, fx.refl_constant_strength, 0.0, 0.0], |
| 1574 | fx.env_start_angle / 360.0, | ||
| 1575 | 1.0 / env_span, | ||
| 1576 | fx.refl_strength_var as f32, | ||
| 1577 | fx.refl_constant_strength, | ||
| 1578 | ], | ||
| 1579 | refl_params: [ | 1572 | refl_params: [ |
| 1580 | fx.refl_glancing_strength, | 1573 | fx.refl_glancing_strength, |
| 1581 | fx.refl_face_on_strength, | 1574 | fx.refl_face_on_strength, |
| ... | @@ -1592,18 +1585,13 @@ impl Scene3DRenderer { | ... | @@ -1592,18 +1585,13 @@ impl Scene3DRenderer { |
| 1592 | cb_ops_a: fx.cb_ops_a.map(f32::from), | 1585 | cb_ops_a: fx.cb_ops_a.map(f32::from), |
| 1593 | cb_ops: fx.cb_ops.map(f32::from), | 1586 | cb_ops: fx.cb_ops.map(f32::from), |
| 1594 | cb_ops_b: fx.cb_ops_b.map(f32::from), | 1587 | cb_ops_b: fx.cb_ops_b.map(f32::from), |
| 1595 | cb_fg_col: fx.cb_fg_col, | 1588 | cb_flags: [if fx.cb_enabled { 1.0 } else { 0.0 }, f32::from(fx.cb_coord_space), 0.0, 0.0], |
| 1596 | cb_flags: [ | ||
| 1597 | if fx.cb_enabled { 1.0 } else { 0.0 }, | ||
| 1598 | f32::from(fx.cb_coord_space), | ||
| 1599 | f32::from(fx.cb_fg_tex_slot), | ||
| 1600 | 0.0, | ||
| 1601 | ], | ||
| 1602 | point_pos, | 1589 | point_pos, |
| 1603 | point_col, | 1590 | point_col, |
| 1604 | spot_pos, | 1591 | spot_pos, |
| 1605 | spot_dir, | 1592 | spot_dir, |
| 1606 | spot_col, | 1593 | spot_col, |
| 1594 | sfx, | ||
| 1607 | }; | 1595 | }; |
| 1608 | let uni_offset = prepared.len() * mesh_uni_stride; | 1596 | let uni_offset = prepared.len() * mesh_uni_stride; |
| 1609 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); | 1597 | mesh_uniform_bytes[uni_offset..uni_offset + mesh_uni_size].copy_from_slice(bytemuck::bytes_of(&uni)); |
crates/engine/src/scene3d/scene_ops.rs created+303| ... | @@ -0,0 +1,303 @@ | ||
| 1 | //! Scene operators that edit or add geometry: `Fog3D`, `Locator3D`, `Ribbon3D` and `UVMap`. | ||
| 2 | |||
| 3 | use std::f32::consts::{PI, TAU}; | ||
| 4 | use std::sync::Arc; | ||
| 5 | |||
| 6 | use super::collect::{euler_matrix, ResolvedMaterial}; | ||
| 7 | use super::materials::flat; | ||
| 8 | use super::mesh::{build_shape_mesh, triangle_soup}; | ||
| 9 | use super::{MeshInstance, ShapeKind, Vertex3D}; | ||
| 10 | use model::{Comp, ExprEngine, Node}; | ||
| 11 | |||
| 12 | pub(super) fn fog(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, meshes: &mut [MeshInstance]) { | ||
| 13 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 14 | if f("Enable", 1.0) < 0.5 { | ||
| 15 | return; | ||
| 16 | } | ||
| 17 | let kind = match n.static_str("FogType") { | ||
| 18 | Some("Exp") => 2.0, | ||
| 19 | Some("Exp2") => 3.0, | ||
| 20 | _ => 1.0, | ||
| 21 | }; | ||
| 22 | let fog = [kind, f("NearFogDist", 1.0), f("FarFogDistance", 100.0), f("FogDensity", 0.05)]; | ||
| 23 | let fog_col = [f("FogRed", 0.7), f("FogGreen", 0.7), f("FogBlue", 0.8), f("Radial", 0.0)]; | ||
| 24 | for m in meshes { | ||
| 25 | if let ShapeKind::WithMaterialFx { fx, .. } = &mut m.shape { | ||
| 26 | fx.sfx.fog = fog; | ||
| 27 | fx.sfx.fog_col = fog_col; | ||
| 28 | } | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | /// Segments as degenerate `(a, b, b)` triangles, which the wireframe pass draws as the line `a-b`. | ||
| 33 | fn lines(segments: impl IntoIterator<Item = [[f32; 3]; 2]>, normal: [f32; 3], mut mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) { | ||
| 34 | let v = |pos| Vertex3D { pos, normal, uv: [0.0; 2] }; | ||
| 35 | mat.fx.wireframe = true; | ||
| 36 | (ShapeKind::CustomMesh(Arc::new(segments.into_iter().flat_map(|[a, b]| [v(a), v(b), v(b)]).collect())), mat) | ||
| 37 | } | ||
| 38 | |||
| 39 | /// `Locator3D` with `MakeRenderable`: an unlit axis cross `Size` across. | ||
| 40 | pub(super) fn locator(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<(ShapeKind, ResolvedMaterial)> { | ||
| 41 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 42 | if f("MakeRenderable", 0.0) < 0.5 || f("UnseenByCamera", 0.0) > 0.5 { | ||
| 43 | return None; | ||
| 44 | } | ||
| 45 | let half = f("Size", 0.25) * 0.5; | ||
| 46 | let axes = [0, 1, 2].map(|a| { | ||
| 47 | let mut p = [0.0; 3]; | ||
| 48 | p[a] = half; | ||
| 49 | [p.map(|c| -c), p] | ||
| 50 | }); | ||
| 51 | Some(lines(axes, [0.0, 0.0, 1.0], flat([f("ColorRed", 1.0), f("ColorGreen", 1.0), f("ColorBlue", 1.0), 1.0]))) | ||
| 52 | } | ||
| 53 | |||
| 54 | /// `Ribbon3D`: `NumberOfLines` parallel lines from `Start` to `End`, spread `RibbonWidth` across | ||
| 55 | /// the axis's up side and turned about it by `RibbonRotation`. | ||
| 56 | pub(super) fn ribbon(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, mat: ResolvedMaterial) -> (ShapeKind, ResolvedMaterial) { | ||
| 57 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 58 | let point = |k: &str, d: [f64; 3]| [0, 1, 2].map(|i| f(&format!("{k}.{}", ["X", "Y", "Z"][i]), d[i])); | ||
| 59 | let (start, end) = (point("Start", [-1.0, 0.0, 0.0]), point("End", [1.0, 0.0, 0.0])); | ||
| 60 | let dot = |a: [f32; 3], b: [f32; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; | ||
| 61 | let unit = |a: [f32; 3]| { | ||
| 62 | let l = dot(a, a).sqrt(); | ||
| 63 | if l > 1e-9 { a.map(|c| c / l) } else { [1.0, 0.0, 0.0] } | ||
| 64 | }; | ||
| 65 | let axis = unit([0, 1, 2].map(|i| end[i] - start[i])); | ||
| 66 | let up = if axis[1].abs() > 0.99 { [0.0, 0.0, 1.0] } else { [0.0, 1.0, 0.0] }; | ||
| 67 | let side0 = unit([0, 1, 2].map(|i| up[i] - axis[i] * dot(up, axis))); | ||
| 68 | let normal0 = [axis[1] * side0[2] - axis[2] * side0[1], axis[2] * side0[0] - axis[0] * side0[2], axis[0] * side0[1] - axis[1] * side0[0]]; | ||
| 69 | let (s, c) = f("RibbonRotation", 0.0).to_radians().sin_cos(); | ||
| 70 | let side = [0, 1, 2].map(|i| side0[i] * c + normal0[i] * s); | ||
| 71 | let normal = [0, 1, 2].map(|i| normal0[i] * c - side0[i] * s); | ||
| 72 | let count = f("NumberOfLines", 10.0).round().max(1.0) as usize; | ||
| 73 | let width = f("RibbonWidth", 0.2); | ||
| 74 | let segments = (0..count).map(|i| { | ||
| 75 | let t = if count == 1 { 0.0 } else { (i as f32 / (count - 1) as f32 - 0.5) * width }; | ||
| 76 | [start, end].map(|p| [0, 1, 2].map(|k| p[k] + side[k] * t)) | ||
| 77 | }); | ||
| 78 | lines(segments, normal, mat) | ||
| 79 | } | ||
| 80 | |||
| 81 | #[derive(Clone, Copy, PartialEq)] | ||
| 82 | enum UvMode { | ||
| 83 | Planar, | ||
| 84 | Cylindrical, | ||
| 85 | Spherical, | ||
| 86 | Cube, | ||
| 87 | Xyz, | ||
| 88 | } | ||
| 89 | |||
| 90 | /// `UVMap` projection: world points enter the map's frame (`R^T (p - Center)`), whose | ||
| 91 | /// `Orientation` axis is "up" and whose other two axes span the image. | ||
| 92 | pub(super) struct UvMap { | ||
| 93 | mode: UvMode, | ||
| 94 | rot: [f32; 16], | ||
| 95 | center: [f32; 3], | ||
| 96 | size: [f32; 3], | ||
| 97 | orientation: usize, | ||
| 98 | tile: [f32; 2], | ||
| 99 | flip: [bool; 2], | ||
| 100 | } | ||
| 101 | |||
| 102 | /// `(s, t, up)` world-axis indices and signs per `Orientation` (`X`, `Y`, `Z`). | ||
| 103 | const FRAMES: [[(usize, f32); 3]; 3] = [[(2, -1.0), (1, 1.0), (0, 1.0)], [(0, 1.0), (2, -1.0), (1, 1.0)], [(0, 1.0), (1, 1.0), (2, 1.0)]]; | ||
| 104 | |||
| 105 | impl UvMap { | ||
| 106 | /// `None` for `Camera` projection, which leaves UVs untouched. | ||
| 107 | pub(super) fn from_node(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> Option<Self> { | ||
| 108 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 109 | let xyz = |k: &str, d: f64| ["X", "Y", "Z"].map(|a| f(&format!("{k}.{a}"), d)); | ||
| 110 | let mode = match n.static_str("MapMode") { | ||
| 111 | Some("Cylindrical") => UvMode::Cylindrical, | ||
| 112 | Some("Spherical") => UvMode::Spherical, | ||
| 113 | Some("CubeMap") => UvMode::Cube, | ||
| 114 | Some("XYZtoUVW") => UvMode::Xyz, | ||
| 115 | Some("Camera") => return None, | ||
| 116 | _ => UvMode::Planar, | ||
| 117 | }; | ||
| 118 | Some(Self { | ||
| 119 | mode, | ||
| 120 | rot: euler_matrix(xyz("Rotate", 0.0), n.static_str("Rotate.RotOrder").unwrap_or("XYZ")), | ||
| 121 | center: xyz("Center", 0.0), | ||
| 122 | size: xyz("Size", 2.0).map(|s| if s.abs() < 1e-6 { 1e-6 } else { s }), | ||
| 123 | orientation: f("Orientation", 1.0).round().clamp(0.0, 2.0) as usize, | ||
| 124 | tile: [f("Tile.U", 1.0), f("Tile.V", 1.0)], | ||
| 125 | flip: [f("Flip.U", 0.0) > 0.5, f("Flip.V", 0.0) > 0.5], | ||
| 126 | }) | ||
| 127 | } | ||
| 128 | |||
| 129 | fn to_local(&self, p: [f32; 3]) -> [f32; 3] { | ||
| 130 | let (r, c) = (&self.rot, self.center); | ||
| 131 | [0, 1, 2].map(|i| r[i * 4] * (p[0] - c[0]) + r[i * 4 + 1] * (p[1] - c[1]) + r[i * 4 + 2] * (p[2] - c[2])) | ||
| 132 | } | ||
| 133 | |||
| 134 | /// Mesh UV (V down) of world point `p`; in cube mode the face is the dominant axis of the | ||
| 135 | /// world point `face_at`. | ||
| 136 | fn uv(&self, p: [f32; 3], face_at: [f32; 3]) -> [f32; 2] { | ||
| 137 | let local = self.to_local(p); | ||
| 138 | let (orientation, face_sign) = if self.mode == UvMode::Cube { | ||
| 139 | let f = self.to_local(face_at); | ||
| 140 | let a = (0..3).max_by(|&a, &b| f[a].abs().total_cmp(&f[b].abs())).unwrap_or(2); | ||
| 141 | (a, if f[a] < 0.0 { -1.0 } else { 1.0 }) | ||
| 142 | } else { | ||
| 143 | (self.orientation, 1.0) | ||
| 144 | }; | ||
| 145 | let [s, t, up] = FRAMES[orientation].map(|(i, sign)| (local[i] * sign, self.size[i])); | ||
| 146 | let (u, v) = match self.mode { | ||
| 147 | UvMode::Xyz => return [s.0, 1.0 - t.0], | ||
| 148 | UvMode::Planar | UvMode::Cube => (face_sign * s.0 / s.1, t.0 / t.1), | ||
| 149 | UvMode::Cylindrical | UvMode::Spherical => { | ||
| 150 | let u = s.0.atan2(-t.0) / TAU; | ||
| 151 | let len = (s.0 * s.0 + t.0 * t.0 + up.0 * up.0).sqrt(); | ||
| 152 | let v = if self.mode == UvMode::Cylindrical { up.0 / up.1 } else { (up.0 / len.max(1e-9)).clamp(-1.0, 1.0).asin() / PI }; | ||
| 153 | (u, v) | ||
| 154 | } | ||
| 155 | }; | ||
| 156 | let [u, v] = [(u, 0), (v, 1)].map(|(c, k)| { | ||
| 157 | let c = c * self.tile[k] + 0.5; | ||
| 158 | if self.flip[k] { 1.0 - c } else { c } | ||
| 159 | }); | ||
| 160 | [u, 1.0 - v] | ||
| 161 | } | ||
| 162 | } | ||
| 163 | |||
| 164 | /// Re-projects UVs; in cube mode each triangle takes the face of its centroid. | ||
| 165 | pub(super) fn uv_map(map: &UvMap, meshes: &mut [MeshInstance], aspect: impl Fn(&MeshInstance) -> f32) { | ||
| 166 | for m in meshes.iter_mut().filter(|m| m.text3d.is_none()) { | ||
| 167 | let mut soup = triangle_soup(build_shape_mesh(m.shape.base_shape(), aspect(m))); | ||
| 168 | let w = m.world; | ||
| 169 | let to_world = |v: [f32; 3]| [0, 1, 2].map(|i| w[i] * v[0] + w[4 + i] * v[1] + w[8 + i] * v[2] + w[12 + i]); | ||
| 170 | for tri in soup.chunks_exact_mut(3) { | ||
| 171 | let p = [0, 1, 2].map(|k| to_world(tri[k].pos)); | ||
| 172 | let centroid = [0, 1, 2].map(|i| (p[0][i] + p[1][i] + p[2][i]) / 3.0); | ||
| 173 | for (v, q) in tri.iter_mut().zip(p) { | ||
| 174 | v.uv = map.uv(q, centroid); | ||
| 175 | } | ||
| 176 | } | ||
| 177 | let (_, fx) = m.shape.split_fx(); | ||
| 178 | m.shape = ShapeKind::WithMaterialFx { inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), fx }; | ||
| 179 | } | ||
| 180 | } | ||
| 181 | |||
| 182 | #[cfg(test)] | ||
| 183 | mod tests { | ||
| 184 | use super::*; | ||
| 185 | use crate::scene3d::collect::{collect_test_scene, comp_src}; | ||
| 186 | |||
| 187 | fn scene(tools: &str) -> (Vec<MeshInstance>, crate::scene3d::SceneLights) { | ||
| 188 | let (_, meshes, lights) = collect_test_scene(&comp_src(tools), "R"); | ||
| 189 | (meshes, lights) | ||
| 190 | } | ||
| 191 | |||
| 192 | #[test] | ||
| 193 | fn fog_tags_every_child_mesh() { | ||
| 194 | let (meshes, _) = scene( | ||
| 195 | "S = Shape3D { }, C = Shape3D { }, | ||
| 196 | M = Merge3D { Inputs = { SceneInput1 = Input { SourceOp = \"S\", Source = \"Output\", }, SceneInput2 = Input { SourceOp = \"C\", Source = \"Output\", }, }, }, | ||
| 197 | R = Fog3D { Inputs = { SceneInput = Input { SourceOp = \"M\", Source = \"Output\", }, FogType = Input { Value = FuID { \"Exp2\" }, }, | ||
| 198 | FogDensity = Input { Value = 0.3, }, Radial = Input { Value = 1, }, }, },", | ||
| 199 | ); | ||
| 200 | assert_eq!(meshes.len(), 2); | ||
| 201 | for m in &meshes { | ||
| 202 | let fx = m.shape.split_fx().1; | ||
| 203 | assert_eq!(fx.sfx.fog, [3.0, 1.0, 100.0, 0.3]); | ||
| 204 | assert_eq!(fx.sfx.fog_col, [0.7, 0.7, 0.8, 1.0]); | ||
| 205 | } | ||
| 206 | } | ||
| 207 | |||
| 208 | #[test] | ||
| 209 | fn locator_draws_a_cross_and_leaves_its_input_untransformed() { | ||
| 210 | let (meshes, _) = scene( | ||
| 211 | "S = Shape3D { }, | ||
| 212 | R = Locator3D { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, MakeRenderable = Input { Value = 1, }, | ||
| 213 | [\"Transform3DOp.Translate.X\"] = Input { Value = 3, }, ColorGreen = Input { Value = 0, }, }, },", | ||
| 214 | ); | ||
| 215 | assert_eq!(meshes.len(), 2); | ||
| 216 | assert_eq!(meshes[0].world[12], 3.0); | ||
| 217 | assert_eq!(meshes[0].diffuse_col, [1.0, 0.0, 1.0, 1.0]); | ||
| 218 | assert!(matches!(meshes[0].shape.base_shape(), ShapeKind::CustomMesh(v) if v.len() == 9)); | ||
| 219 | assert!(meshes[0].shape.split_fx().1.wireframe); | ||
| 220 | assert_eq!(meshes[1].world[12], 0.0); | ||
| 221 | let (hidden, _) = scene("R = Locator3D { },"); | ||
| 222 | assert!(hidden.is_empty()); | ||
| 223 | } | ||
| 224 | |||
| 225 | #[test] | ||
| 226 | fn ribbon_spreads_lines_across_its_width() { | ||
| 227 | let (meshes, _) = scene("R = Ribbon3D { Inputs = { NumberOfLines = Input { Value = 3, }, RibbonWidth = Input { Value = 1, }, }, },"); | ||
| 228 | let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("ribbon mesh") }; | ||
| 229 | let ys: Vec<f32> = v.chunks(3).map(|t| t[0].pos[1]).collect(); | ||
| 230 | assert_eq!(ys, [-0.5, 0.0, 0.5]); | ||
| 231 | assert_eq!((v[0].pos[0], v[1].pos[0]), (-1.0, 1.0)); | ||
| 232 | assert!(meshes[0].shape.split_fx().1.wireframe); | ||
| 233 | } | ||
| 234 | |||
| 235 | #[test] | ||
| 236 | fn triangulate_passes_through_and_weld_smooths_normals() { | ||
| 237 | let cube = "S = Shape3D { Inputs = { Shape = Input { Value = FuID { \"SurfaceCubeInputs\" }, }, }, },"; | ||
| 238 | let (tri, _) = scene(&format!("{cube} R = Triangulate3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, }}, }},")); | ||
| 239 | assert!(matches!(tri[0].shape.base_shape(), ShapeKind::Cube { .. })); | ||
| 240 | let (welded, _) = scene(&format!( | ||
| 241 | "{cube} R = Weld3D {{ Inputs = {{ SceneInput = Input {{ SourceOp = \"S\", Source = \"Output\", }}, WeldNormals = Input {{ Value = 1, }}, }}, }}," | ||
| 242 | )); | ||
| 243 | let ShapeKind::CustomMesh(v) = welded[0].shape.base_shape() else { panic!("welded mesh") }; | ||
| 244 | let corner = v.iter().find(|p| p.pos.iter().all(|c| c.abs() > 0.49)).expect("corner vertex"); | ||
| 245 | assert!(corner.normal.iter().all(|c| c.abs() > 0.5), "corner normals average the three faces: {:?}", corner.normal); | ||
| 246 | } | ||
| 247 | |||
| 248 | #[test] | ||
| 249 | fn light_dome_is_ambient_only_when_textured() { | ||
| 250 | let (_, bare) = scene("R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, }, },"); | ||
| 251 | assert_eq!((bare.count, bare.ambient), (1, [0.0; 3])); | ||
| 252 | let (_, lit) = scene( | ||
| 253 | "Img = Background { }, | ||
| 254 | R = LightDome { Inputs = { Intensity = Input { Value = 0.5, }, DomeTexture = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", | ||
| 255 | ); | ||
| 256 | assert_eq!(lit.ambient, [0.5; 3]); | ||
| 257 | } | ||
| 258 | |||
| 259 | #[test] | ||
| 260 | fn uv_map_rebuilds_child_meshes() { | ||
| 261 | let (meshes, _) = scene( | ||
| 262 | "S = Shape3D { }, | ||
| 263 | R = UVMap { Inputs = { SceneInput = Input { SourceOp = \"S\", Source = \"Output\", }, }, },", | ||
| 264 | ); | ||
| 265 | let ShapeKind::CustomMesh(v) = meshes[0].shape.base_shape() else { panic!("uv mapped mesh") }; | ||
| 266 | assert!(v.iter().all(|p| (0.0..=1.0).contains(&p.uv[0]) && (0.0..=1.0).contains(&p.uv[1]))); | ||
| 267 | } | ||
| 268 | |||
| 269 | fn map(mode: UvMode, orientation: usize) -> UvMap { | ||
| 270 | UvMap { mode, rot: crate::scene3d::mat4_identity(), center: [0.0; 3], size: [2.0; 3], orientation, tile: [1.0; 2], flip: [false; 2] } | ||
| 271 | } | ||
| 272 | |||
| 273 | #[test] | ||
| 274 | fn planar_orientations_follow_fusion_frames() { | ||
| 275 | let p = [0.5, 0.25, -0.5]; | ||
| 276 | assert_eq!(map(UvMode::Planar, 2).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]); | ||
| 277 | assert_eq!(map(UvMode::Planar, 1).uv(p, [0.0; 3]), [0.75, 1.0 - 0.75]); | ||
| 278 | assert_eq!(map(UvMode::Planar, 0).uv(p, [0.0; 3]), [0.75, 1.0 - 0.625]); | ||
| 279 | let mut tiled = map(UvMode::Planar, 2); | ||
| 280 | tiled.tile = [2.0, 1.0]; | ||
| 281 | tiled.flip = [false, true]; | ||
| 282 | assert_eq!(tiled.uv(p, [0.0; 3]), [1.0, 0.625]); | ||
| 283 | } | ||
| 284 | |||
| 285 | #[test] | ||
| 286 | fn cylindrical_spherical_and_xyz() { | ||
| 287 | let front = [0.0, 0.0, 1.0]; | ||
| 288 | let cyl = map(UvMode::Cylindrical, 1).uv(front, front); | ||
| 289 | assert!((cyl[0] - 0.5).abs() < 1e-6 && (cyl[1] - 0.5).abs() < 1e-6, "{cyl:?}"); | ||
| 290 | let top = map(UvMode::Spherical, 1).uv([0.0, 1.0, 0.0], [0.0, 1.0, 0.0]); | ||
| 291 | assert!((top[1] - 0.0).abs() < 1e-6, "pole maps to v = 1 (V down 0): {top:?}"); | ||
| 292 | assert_eq!(map(UvMode::Xyz, 2).uv([0.3, 0.4, 0.5], [0.0; 3]), [0.3, 0.6]); | ||
| 293 | } | ||
| 294 | |||
| 295 | #[test] | ||
| 296 | fn cube_mode_projects_each_face_along_its_dominant_axis() { | ||
| 297 | let m = map(UvMode::Cube, 1); | ||
| 298 | let side = m.uv([1.0, 0.5, 0.0], [1.0, 0.4, 0.0]); | ||
| 299 | let back = m.uv([-1.0, 0.5, 0.0], [-1.0, 0.4, 0.0]); | ||
| 300 | assert_eq!(side[1], back[1]); | ||
| 301 | assert_eq!(side[1], 1.0 - 0.75); | ||
| 302 | } | ||
| 303 | } | ||
crates/engine/src/scene3d/shader.rs+8-697| ... | @@ -2,6 +2,8 @@ | ... | @@ -2,6 +2,8 @@ |
| 2 | 2 | ||
| 3 | use bytemuck::{Pod, Zeroable}; | 3 | use bytemuck::{Pod, Zeroable}; |
| 4 | 4 | ||
| 5 | use super::fx::SurfaceFx; | ||
| 6 | |||
| 5 | /// Point and spot lights each get this many shader slots. | 7 | /// Point and spot lights each get this many shader slots. |
| 6 | pub(super) const MAX_LIGHTS: usize = 8; | 8 | pub(super) const MAX_LIGHTS: usize = 8; |
| 7 | /// Directional lights get this many shader slots. | 9 | /// Directional lights get this many shader slots. |
| ... | @@ -62,12 +64,12 @@ pub(super) struct MeshUniform { | ... | @@ -62,12 +64,12 @@ pub(super) struct MeshUniform { |
| 62 | pub(super) mtl_params: [f32; 4], | 64 | pub(super) mtl_params: [f32; 4], |
| 63 | /// Environment inverse rotation col 0 + `env_mode` (`0=none, 1=SphereMap, 2=MtlReflect`) | 65 | /// Environment inverse rotation col 0 + `env_mode` (`0=none, 1=SphereMap, 2=MtlReflect`) |
| 64 | pub(super) env_rot_0: [f32; 4], | 66 | pub(super) env_rot_0: [f32; 4], |
| 65 | /// Environment inverse rotation col 1 + `env_map_mode` (`0=equirect, 1=angular`) | 67 | /// Environment inverse rotation col 1 + `env_map_mode` (see `sample_sphere_map`) |
| 66 | pub(super) env_rot_1: [f32; 4], | 68 | pub(super) env_rot_1: [f32; 4], |
| 67 | /// Environment inverse rotation col 2 + `env_tex_slot` (`0=solid, 1=mat_tex, 2=bump_tex`) | 69 | /// Environment inverse rotation col 2 + `env_tex_slot` (`0=solid, 1=mat_tex, 2=bump_tex`) |
| 68 | pub(super) env_rot_2: [f32; 4], | 70 | pub(super) env_rot_2: [f32; 4], |
| 69 | /// `[start_angle_norm, inv_angle_span, strength_variability, constant_strength]` | 71 | /// `[strength_variability, constant_strength, 0, 0]` |
| 70 | pub(super) env_angles: [f32; 4], | 72 | pub(super) refl_strength: [f32; 4], |
| 71 | /// `[glancing_strength, face_on_strength, falloff, refract_ior]` | 73 | /// `[glancing_strength, face_on_strength, falloff, refract_ior]` |
| 72 | pub(super) refl_params: [f32; 4], | 74 | pub(super) refl_params: [f32; 4], |
| 73 | /// `[refl_tint_r, refl_tint_g, refl_tint_b, has_bg_material]` | 75 | /// `[refl_tint_r, refl_tint_g, refl_tint_b, has_bg_material]` |
| ... | @@ -80,9 +82,7 @@ pub(super) struct MeshUniform { | ... | @@ -80,9 +82,7 @@ pub(super) struct MeshUniform { |
| 80 | pub(super) cb_ops: [f32; 4], | 82 | pub(super) cb_ops: [f32; 4], |
| 81 | /// `MtlChanBool` operand B indices `[r, g, b, a]` | 83 | /// `MtlChanBool` operand B indices `[r, g, b, a]` |
| 82 | pub(super) cb_ops_b: [f32; 4], | 84 | pub(super) cb_ops_b: [f32; 4], |
| 83 | /// `MtlChanBool` foreground material constant RGBA | 85 | /// `[cb_enabled, cb_coord_space (0=Model,1=World,2=Eye), 0, 0]` |
| 84 | pub(super) cb_fg_col: [f32; 4], | ||
| 85 | /// `[cb_enabled, cb_coord_space (0=Model,1=World,2=Eye), cb_fg_tex_slot (0=none,2=bump_tex), 0]` | ||
| 86 | pub(super) cb_flags: [f32; 4], | 86 | pub(super) cb_flags: [f32; 4], |
| 87 | /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` | 87 | /// Point light positions `(x, y, z, decay_type: 0=none, 1=linear, 2=quad)` |
| 88 | pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], | 88 | pub(super) point_pos: [[f32; 4]; MAX_LIGHTS], |
| ... | @@ -94,6 +94,7 @@ pub(super) struct MeshUniform { | ... | @@ -94,6 +94,7 @@ pub(super) struct MeshUniform { |
| 94 | pub(super) spot_dir: [[f32; 4]; MAX_LIGHTS], | 94 | pub(super) spot_dir: [[f32; 4]; MAX_LIGHTS], |
| 95 | /// Spot light colors * intensity `(r, g, b, decay_type)` | 95 | /// Spot light colors * intensity `(r, g, b, decay_type)` |
| 96 | pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], | 96 | pub(super) spot_col: [[f32; 4]; MAX_LIGHTS], |
| 97 | pub(super) sfx: SurfaceFx, | ||
| 97 | } | 98 | } |
| 98 | 99 | ||
| 99 | #[repr(C)] | 100 | #[repr(C)] |
| ... | @@ -199,694 +200,4 @@ fn fs_shadow(in: VsOut) -> @location(0) f32 { | ... | @@ -199,694 +200,4 @@ fn fs_shadow(in: VsOut) -> @location(0) f32 { |
| 199 | 200 | ||
| 200 | /// WGSL source; `MAX_LIGHTS`, `MAX_DIR_LIGHTS`, `MAX_SHADOW_LIGHTS` and `SHADOW_MAP_SIZE` are | 201 | /// WGSL source; `MAX_LIGHTS`, `MAX_DIR_LIGHTS`, `MAX_SHADOW_LIGHTS` and `SHADOW_MAP_SIZE` are |
| 201 | /// substituted with the Rust constants at pipeline creation. | 202 | /// substituted with the Rust constants at pipeline creation. |
| 202 | pub(super) const SHADER_3D: &str = r#" | 203 | pub(super) const SHADER_3D: &str = include_str!("mesh.wgsl"); |
| 203 | struct MeshUniform { | ||
| 204 | mvp: mat4x4<f32>, | ||
| 205 | model: mat4x4<f32>, | ||
| 206 | view: mat4x4<f32>, | ||
| 207 | dod: vec4<f32>, | ||
| 208 | flags: vec4<f32>, | ||
| 209 | diffuse_col: vec4<f32>, | ||
| 210 | specular_col: vec4<f32>, | ||
| 211 | ambient: vec4<f32>, | ||
| 212 | dir_to_light: array<vec4<f32>, MAX_DIR_LIGHTS>, | ||
| 213 | dir_color: array<vec4<f32>, MAX_DIR_LIGHTS>, | ||
| 214 | cam_pos: vec4<f32>, | ||
| 215 | light_counts: vec4<f32>, | ||
| 216 | uv_xform: vec4<f32>, | ||
| 217 | uv_off_wrap: vec4<f32>, | ||
| 218 | mat_fx: vec4<f32>, | ||
| 219 | bump_uv_xform: vec4<f32>, | ||
| 220 | bump_off_wrap: vec4<f32>, | ||
| 221 | bump_dod: vec4<f32>, | ||
| 222 | bump_params: vec4<f32>, | ||
| 223 | mtl_params: vec4<f32>, | ||
| 224 | env_rot_0: vec4<f32>, | ||
| 225 | env_rot_1: vec4<f32>, | ||
| 226 | env_rot_2: vec4<f32>, | ||
| 227 | env_angles: vec4<f32>, | ||
| 228 | refl_params: vec4<f32>, | ||
| 229 | refl_tint: vec4<f32>, | ||
| 230 | refract_tint: vec4<f32>, | ||
| 231 | cb_ops_a: vec4<f32>, | ||
| 232 | cb_ops: vec4<f32>, | ||
| 233 | cb_ops_b: vec4<f32>, | ||
| 234 | cb_fg_col: vec4<f32>, | ||
| 235 | cb_flags: vec4<f32>, | ||
| 236 | point_pos: array<vec4<f32>, MAX_LIGHTS>, | ||
| 237 | point_col: array<vec4<f32>, MAX_LIGHTS>, | ||
| 238 | spot_pos: array<vec4<f32>, MAX_LIGHTS>, | ||
| 239 | spot_dir: array<vec4<f32>, MAX_LIGHTS>, | ||
| 240 | spot_col: array<vec4<f32>, MAX_LIGHTS>, | ||
| 241 | }; | ||
| 242 | |||
| 243 | struct ShadowUniform { | ||
| 244 | face_vp: array<mat4x4<f32>, 6 * MAX_SHADOW_LIGHTS>, | ||
| 245 | point: array<vec4<f32>, MAX_LIGHTS>, | ||
| 246 | }; | ||
| 247 | |||
| 248 | override BACK_PASS: bool = false; | ||
| 249 | |||
| 250 | @group(0) @binding(0) var<uniform> u: MeshUniform; | ||
| 251 | @group(0) @binding(1) var mat_tex: texture_2d<f32>; | ||
| 252 | @group(0) @binding(2) var mat_samp: sampler; | ||
| 253 | @group(0) @binding(3) var<uniform> shadow: ShadowUniform; | ||
| 254 | @group(0) @binding(4) var shadow_maps: texture_2d_array<f32>; | ||
| 255 | @group(0) @binding(5) var bump_tex: texture_2d<f32>; | ||
| 256 | |||
| 257 | struct VsIn { | ||
| 258 | @location(0) pos: vec3<f32>, | ||
| 259 | @location(1) normal: vec3<f32>, | ||
| 260 | @location(2) uv: vec2<f32>, | ||
| 261 | }; | ||
| 262 | |||
| 263 | struct VsOut { | ||
| 264 | @builtin(position) clip: vec4<f32>, | ||
| 265 | @location(0) uv: vec2<f32>, | ||
| 266 | @location(1) world_pos: vec3<f32>, | ||
| 267 | @location(2) world_n: vec3<f32>, | ||
| 268 | @location(3) local_pos: vec3<f32>, | ||
| 269 | @location(4) local_n: vec3<f32>, | ||
| 270 | }; | ||
| 271 | |||
| 272 | // Cofactor matrix of the upper-left 3x3 of `m` (inverse-transpose up to scale), so normals stay | ||
| 273 | // perpendicular under non-uniform scale. Dividing by |det| instead of det keeps mirrored | ||
| 274 | // transforms pointing outward. | ||
| 275 | fn normal_matrix(m: mat4x4<f32>) -> mat3x3<f32> { | ||
| 276 | let c0 = m[0].xyz; | ||
| 277 | let c1 = m[1].xyz; | ||
| 278 | let c2 = m[2].xyz; | ||
| 279 | let sign = select(-1.0, 1.0, dot(c0, cross(c1, c2)) >= 0.0); | ||
| 280 | return mat3x3<f32>(cross(c1, c2), cross(c2, c0), cross(c0, c1)) * sign; | ||
| 281 | } | ||
| 282 | |||
| 283 | @vertex | ||
| 284 | fn vs_mesh(v: VsIn) -> VsOut { | ||
| 285 | var out: VsOut; | ||
| 286 | let wp = u.model * vec4<f32>(v.pos, 1.0); | ||
| 287 | out.clip = u.mvp * vec4<f32>(v.pos, 1.0); | ||
| 288 | out.uv = v.uv; | ||
| 289 | out.world_pos = wp.xyz; | ||
| 290 | let wn = normal_matrix(u.model) * v.normal; | ||
| 291 | let nlen = length(wn); | ||
| 292 | var n_norm = select(vec3<f32>(0.0, 0.0, 1.0), wn / nlen, nlen > 1e-5); | ||
| 293 | var ln = v.normal; | ||
| 294 | if (u.flags.w > 0.5) { | ||
| 295 | n_norm = -n_norm; | ||
| 296 | ln = -ln; | ||
| 297 | } | ||
| 298 | out.world_n = n_norm; | ||
| 299 | out.local_pos = v.pos; | ||
| 300 | out.local_n = ln; | ||
| 301 | return out; | ||
| 302 | } | ||
| 303 | |||
| 304 | fn light_attenuation(dist: f32, decay_type: f32) -> f32 { | ||
| 305 | let dt = i32(decay_type + 0.5); | ||
| 306 | let d = max(dist, 1e-3); | ||
| 307 | if (dt == 1) { | ||
| 308 | return 1.0 / d; | ||
| 309 | } else if (dt == 2) { | ||
| 310 | return 1.0 / (d * d); | ||
| 311 | } | ||
| 312 | return 1.0; | ||
| 313 | } | ||
| 314 | |||
| 315 | /// Fraction of PCF taps where the cube map of point light `i` records a closer occluder. | ||
| 316 | fn point_shadow_occlusion(i: i32, world_pos: vec3<f32>, n: vec3<f32>, light_pos: vec3<f32>) -> f32 { | ||
| 317 | let params = shadow.point[i]; | ||
| 318 | if (params.x < -0.5) { | ||
| 319 | return 0.0; | ||
| 320 | } | ||
| 321 | let slot = i32(params.x + 0.5); | ||
| 322 | let dist = length(world_pos - light_pos); | ||
| 323 | // World size of one texel at this distance for a 90 degree face. | ||
| 324 | let texel = 2.0 * dist / f32(SHADOW_MAP_SIZE); | ||
| 325 | // The face is picked from the offset point so the lookup never straddles a cube seam. | ||
| 326 | let biased = world_pos + n * (texel * 1.5); | ||
| 327 | let d = biased - light_pos; | ||
| 328 | let a = abs(d); | ||
| 329 | var face = 4; | ||
| 330 | if (a.x >= a.y && a.x >= a.z) { | ||
| 331 | face = select(1, 0, d.x > 0.0); | ||
| 332 | } else if (a.y >= a.z) { | ||
| 333 | face = select(3, 2, d.y > 0.0); | ||
| 334 | } else { | ||
| 335 | face = select(5, 4, d.z > 0.0); | ||
| 336 | } | ||
| 337 | let clip = shadow.face_vp[slot * 6 + face] * vec4<f32>(biased, 1.0); | ||
| 338 | if (clip.w <= 1e-5) { | ||
| 339 | return 0.0; | ||
| 340 | } | ||
| 341 | let ndc = clip.xy / clip.w; | ||
| 342 | let base = vec2<i32>(floor(vec2<f32>(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * f32(SHADOW_MAP_SIZE))); | ||
| 343 | let last = SHADOW_MAP_SIZE - 1; | ||
| 344 | var occluded = 0.0; | ||
| 345 | for (var dy: i32 = -1; dy <= 1; dy = dy + 1) { | ||
| 346 | for (var dx: i32 = -1; dx <= 1; dx = dx + 1) { | ||
| 347 | let t = clamp(base + vec2<i32>(dx, dy), vec2<i32>(0), vec2<i32>(last)); | ||
| 348 | let stored = textureLoad(shadow_maps, t, slot * 6 + face, 0).r; | ||
| 349 | occluded = occluded + select(0.0, 1.0, dist - texel * 3.0 > stored); | ||
| 350 | } | ||
| 351 | } | ||
| 352 | return occluded / 9.0; | ||
| 353 | } | ||
| 354 | |||
| 355 | struct TangentFrame { | ||
| 356 | t: vec3<f32>, | ||
| 357 | b: vec3<f32>, | ||
| 358 | }; | ||
| 359 | |||
| 360 | fn compute_tangent_frame( | ||
| 361 | base_n: vec3<f32>, | ||
| 362 | dpdx_w: vec3<f32>, | ||
| 363 | dpdy_w: vec3<f32>, | ||
| 364 | duvdx: vec2<f32>, | ||
| 365 | duvdy: vec2<f32>, | ||
| 366 | ) -> TangentFrame { | ||
| 367 | let det = duvdx.x * duvdy.y - duvdx.y * duvdy.x; | ||
| 368 | var t_vec: vec3<f32>; | ||
| 369 | var b_vec: vec3<f32>; | ||
| 370 | if (abs(det) > 1e-6) { | ||
| 371 | let inv_det = 1.0 / det; | ||
| 372 | t_vec = (dpdx_w * duvdy.y - dpdy_w * duvdx.y) * inv_det; | ||
| 373 | b_vec = (dpdy_w * duvdx.x - dpdx_w * duvdy.x) * inv_det; | ||
| 374 | t_vec = t_vec - base_n * dot(t_vec, base_n); | ||
| 375 | let t_len = length(t_vec); | ||
| 376 | if (t_len > 1e-5) { | ||
| 377 | t_vec = t_vec / t_len; | ||
| 378 | let b_sign = select(-1.0, 1.0, dot(cross(base_n, t_vec), b_vec) >= 0.0); | ||
| 379 | b_vec = cross(base_n, t_vec) * b_sign; | ||
| 380 | return TangentFrame(t_vec, b_vec); | ||
| 381 | } | ||
| 382 | } | ||
| 383 | let up = select(vec3<f32>(0.0, 1.0, 0.0), vec3<f32>(1.0, 0.0, 0.0), abs(base_n.y) > 0.9); | ||
| 384 | t_vec = normalize(cross(up, base_n)); | ||
| 385 | b_vec = cross(base_n, t_vec); | ||
| 386 | return TangentFrame(t_vec, b_vec); | ||
| 387 | } | ||
| 388 | |||
| 389 | fn eval_light_contrib( | ||
| 390 | n: vec3<f32>, | ||
| 391 | t_vec: vec3<f32>, | ||
| 392 | b_vec: vec3<f32>, | ||
| 393 | v: vec3<f32>, | ||
| 394 | l: vec3<f32>, | ||
| 395 | light_rgb: vec3<f32>, | ||
| 396 | albedo: vec3<f32>, | ||
| 397 | spec_rgb: vec3<f32>, | ||
| 398 | spec_int: f32, | ||
| 399 | shininess: f32, | ||
| 400 | diffuse_vis: f32, | ||
| 401 | spec_vis: f32, | ||
| 402 | ) -> vec3<f32> { | ||
| 403 | let ndotl = max(dot(n, l), 0.0); | ||
| 404 | if (ndotl <= 0.0) { | ||
| 405 | return vec3<f32>(0.0); | ||
| 406 | } | ||
| 407 | let model = i32(u.mat_fx.w + 0.5); | ||
| 408 | if (model == 3) { | ||
| 409 | return albedo * light_rgb * (ndotl * diffuse_vis / 3.14159265); | ||
| 410 | } | ||
| 411 | var out = albedo * light_rgb * (ndotl * diffuse_vis); | ||
| 412 | if (spec_int > 1e-4) { | ||
| 413 | let h = normalize(l + v); | ||
| 414 | var lobe: f32; | ||
| 415 | if (model == 1) { | ||
| 416 | lobe = pow(max(dot(reflect(-l, n), v), 0.0), shininess); | ||
| 417 | } else if (model == 2) { | ||
| 418 | // Cook-Torrance: Beckmann D, Torrance-Sparrow G, exact unpolarized Fresnel F. | ||
| 419 | // `eval_light_contrib` omits the outer N·L factor on `lobe`, so `(F*D*G)/(4*N·L*N·V) * N·L` | ||
| 420 | // simplifies to `(F*D*G)/(4*N·V)`. | ||
| 421 | let nh = max(dot(n, h), 1e-3); | ||
| 422 | let nv = max(dot(n, v), 1e-3); | ||
| 423 | let vh = max(dot(v, h), 1e-3); | ||
| 424 | let m2 = max(shininess * shininess, 1e-3); | ||
| 425 | let nh2 = nh * nh; | ||
| 426 | let d_term = exp(-(1.0 - nh2) / (nh2 * m2)) / (3.14159265 * m2 * nh2 * nh2); | ||
| 427 | let g_term = min(1.0, min(2.0 * nh * nv / vh, 2.0 * nh * ndotl / vh)); | ||
| 428 | var fresnel = 1.0; | ||
| 429 | if (u.mtl_params.z > 0.5) { | ||
| 430 | let eta = max(u.mtl_params.y, 1.0); | ||
| 431 | let c = vh; | ||
| 432 | let g = sqrt(max(eta * eta + c * c - 1.0, 0.0)); | ||
| 433 | let gmc = g - c; | ||
| 434 | let gpc = max(g + c, 1e-5); | ||
| 435 | let r_s = gmc / gpc; | ||
| 436 | let r_p = (c * gpc - 1.0) / max(c * gmc + 1.0, 1e-5); | ||
| 437 | fresnel = 0.5 * r_s * r_s * (1.0 + r_p * r_p); | ||
| 438 | } | ||
| 439 | lobe = (fresnel * d_term * g_term) / (4.0 * nv); | ||
| 440 | } else if (model == 4) { | ||
| 441 | // Anisotropic Ward (1992) BRDF * (N·L) using tangent frame (T, B) and SpreadU/SpreadV. | ||
| 442 | let nh = max(dot(n, h), 1e-3); | ||
| 443 | let nv = max(dot(n, v), 1e-3); | ||
| 444 | let su = max(shininess, 1e-3); | ||
| 445 | let sv = max(u.mtl_params.w, 1e-3); | ||
| 446 | let ht = dot(h, t_vec) / su; | ||
| 447 | let hb = dot(h, b_vec) / sv; | ||
| 448 | let expo = -(ht * ht + hb * hb) / (nh * nh); | ||
| 449 | let denom = max(4.0 * 3.14159265 * su * sv * sqrt(nv), 1e-4); | ||
| 450 | lobe = (sqrt(ndotl) / denom) * exp(max(expo, -80.0)); | ||
| 451 | } else { | ||
| 452 | lobe = pow(max(dot(n, h), 0.0), shininess); | ||
| 453 | } | ||
| 454 | out = out + light_rgb * spec_rgb * (lobe * spec_int * spec_vis); | ||
| 455 | } | ||
| 456 | return out; | ||
| 457 | } | ||
| 458 | |||
| 459 | fn sample_bump_height(uv_in: vec2<f32>, wrap_f: f32, ch: i32) -> f32 { | ||
| 460 | let uv = wrap_uv_only(uv_in, wrap_f); | ||
| 461 | let c = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); | ||
| 462 | if (ch == 1) { | ||
| 463 | return (c.r + c.g + c.b) / 3.0; | ||
| 464 | } else if (ch == 2) { | ||
| 465 | return max(c.r, max(c.g, c.b)); | ||
| 466 | } else if (ch == 3) { | ||
| 467 | return min(c.r, min(c.g, c.b)); | ||
| 468 | } else if (ch == 4) { | ||
| 469 | return c.r; | ||
| 470 | } else if (ch == 5) { | ||
| 471 | return c.g; | ||
| 472 | } else if (ch == 6) { | ||
| 473 | return c.b; | ||
| 474 | } else if (ch == 7) { | ||
| 475 | return c.a; | ||
| 476 | } | ||
| 477 | return dot(c.rgb, vec3<f32>(0.299, 0.587, 0.114)); | ||
| 478 | } | ||
| 479 | |||
| 480 | fn perturb_bump_normal( | ||
| 481 | base_n: vec3<f32>, | ||
| 482 | dpdx_w: vec3<f32>, | ||
| 483 | dpdy_w: vec3<f32>, | ||
| 484 | duvdx: vec2<f32>, | ||
| 485 | duvdy: vec2<f32>, | ||
| 486 | uv_in: vec2<f32>, | ||
| 487 | bump_scale: f32, | ||
| 488 | bump_mode: f32, | ||
| 489 | bump_wrap: f32, | ||
| 490 | clamp_z: f32, | ||
| 491 | bump_ch: i32, | ||
| 492 | ) -> vec3<f32> { | ||
| 493 | var uv = uv_in; | ||
| 494 | if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { | ||
| 495 | let bdims = vec2<f32>(textureDimensions(bump_tex)); | ||
| 496 | let canvas_px = vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w); | ||
| 497 | uv = (canvas_px - u.bump_dod.xy) / bdims; | ||
| 498 | } | ||
| 499 | let frame = compute_tangent_frame(base_n, dpdx_w, dpdy_w, duvdx, duvdy); | ||
| 500 | let t_vec = frame.t; | ||
| 501 | let b_vec = frame.b; | ||
| 502 | |||
| 503 | if (bump_mode > 0.5) { | ||
| 504 | let b_col = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv, bump_wrap), 0.0); | ||
| 505 | 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); | ||
| 506 | let tn = b_rgb * 2.0 - vec3<f32>(1.0); | ||
| 507 | let perturbed = t_vec * tn.x + b_vec * tn.y + base_n * tn.z; | ||
| 508 | let plen = length(perturbed); | ||
| 509 | return select(base_n, perturbed / plen, plen > 1e-5); | ||
| 510 | } | ||
| 511 | |||
| 512 | let inv_dim = vec2<f32>(1.0) / max(vec2<f32>(textureDimensions(bump_tex)), vec2<f32>(1.0)); | ||
| 513 | let h_l = sample_bump_height(uv - vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch); | ||
| 514 | let h_r = sample_bump_height(uv + vec2<f32>(inv_dim.x, 0.0), bump_wrap, bump_ch); | ||
| 515 | let h_d = sample_bump_height(uv - vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch); | ||
| 516 | let h_u = sample_bump_height(uv + vec2<f32>(0.0, inv_dim.y), bump_wrap, bump_ch); | ||
| 517 | let dhdu = (h_r - h_l) * 0.5 * bump_scale; | ||
| 518 | let dhdv = (h_u - h_d) * 0.5 * bump_scale; | ||
| 519 | return normalize(base_n - t_vec * dhdu + b_vec * dhdv); | ||
| 520 | } | ||
| 521 | |||
| 522 | fn sample_sphere_map(world_dir: vec3<f32>) -> vec4<f32> { | ||
| 523 | let slot = i32(u.env_rot_2.w + 0.5); | ||
| 524 | if (slot == 0) { | ||
| 525 | return vec4<f32>(u.refl_tint.rgb, 1.0); | ||
| 526 | } | ||
| 527 | let rot = mat3x3<f32>(u.env_rot_0.xyz, u.env_rot_1.xyz, u.env_rot_2.xyz); | ||
| 528 | let d = normalize(rot * world_dir); | ||
| 529 | let map_mode = i32(u.env_rot_1.w + 0.5); | ||
| 530 | var uv: vec2<f32>; | ||
| 531 | if (map_mode == 1) { | ||
| 532 | let r_xy = length(d.xy); | ||
| 533 | let r = select(0.0, acos(clamp(-d.z, -1.0, 1.0)) / (3.14159265 * r_xy), r_xy > 1e-5); | ||
| 534 | uv = clamp(vec2<f32>(0.5 + d.x * r * 0.5, 0.5 - d.y * r * 0.5), vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 535 | } else { | ||
| 536 | let theta = atan2(d.x, d.z); | ||
| 537 | var u_c = fract(theta / 6.2831853 + 0.75); | ||
| 538 | u_c = fract((u_c - u.env_angles.x) * u.env_angles.y); | ||
| 539 | let v_c = acos(clamp(d.y, -1.0, 1.0)) / 3.14159265; | ||
| 540 | uv = vec2<f32>(u_c, v_c); | ||
| 541 | } | ||
| 542 | var raw: vec4<f32>; | ||
| 543 | if (slot == 2) { | ||
| 544 | if (u.bump_dod.z > 0.5 && u.bump_dod.w > 0.5) { | ||
| 545 | let dims = vec2<f32>(textureDimensions(bump_tex)); | ||
| 546 | uv = clamp((vec2<f32>(uv.x * u.bump_dod.z, uv.y * u.bump_dod.w) - u.bump_dod.xy) / dims, vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 547 | } | ||
| 548 | raw = textureSampleLevel(bump_tex, mat_samp, uv, 0.0); | ||
| 549 | } else { | ||
| 550 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 551 | let dims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 552 | uv = clamp((vec2<f32>(uv.x * u.dod.z, uv.y * u.dod.w) - u.dod.xy) / dims, vec2<f32>(0.0), vec2<f32>(1.0)); | ||
| 553 | } | ||
| 554 | raw = textureSampleLevel(mat_tex, mat_samp, uv, 0.0); | ||
| 555 | } | ||
| 556 | let straight = select(vec3<f32>(0.0), raw.rgb / max(raw.a, 1e-5), raw.a > 1e-5); | ||
| 557 | return vec4<f32>(straight * u.refl_tint.rgb, raw.a); | ||
| 558 | } | ||
| 559 | |||
| 560 | fn cb_hls(c: vec3<f32>) -> vec3<f32> { | ||
| 561 | let mx = max(c.r, max(c.g, c.b)); | ||
| 562 | let mn = min(c.r, min(c.g, c.b)); | ||
| 563 | let l = 0.5 * (mx + mn); | ||
| 564 | let d = mx - mn; | ||
| 565 | if (d <= 1e-6) { | ||
| 566 | return vec3<f32>(0.0, l, 0.0); | ||
| 567 | } | ||
| 568 | let s = d / max(1.0 - abs(2.0 * l - 1.0), 1e-6); | ||
| 569 | var h = 0.0; | ||
| 570 | if (mx == c.r) { | ||
| 571 | h = (c.g - c.b) / d + select(0.0, 6.0, c.g < c.b); | ||
| 572 | } else if (mx == c.g) { | ||
| 573 | h = (c.b - c.r) / d + 2.0; | ||
| 574 | } else { | ||
| 575 | h = (c.r - c.g) / d + 4.0; | ||
| 576 | } | ||
| 577 | return vec3<f32>(h / 6.0, l, clamp(s, 0.0, 1.0)); | ||
| 578 | } | ||
| 579 | |||
| 580 | fn cb_operand( | ||
| 581 | idx: i32, | ||
| 582 | bg: vec4<f32>, | ||
| 583 | fg: vec4<f32>, | ||
| 584 | pos: vec3<f32>, | ||
| 585 | uv: vec2<f32>, | ||
| 586 | env_c: vec3<f32>, | ||
| 587 | n: vec3<f32>, | ||
| 588 | ) -> f32 { | ||
| 589 | switch idx { | ||
| 590 | case 0: { return fg.r; } | ||
| 591 | case 1: { return fg.g; } | ||
| 592 | case 2: { return fg.b; } | ||
| 593 | case 3: { return fg.a; } | ||
| 594 | case 4: { return bg.r; } | ||
| 595 | case 5: { return bg.g; } | ||
| 596 | case 6: { return bg.b; } | ||
| 597 | case 7: { return bg.a; } | ||
| 598 | case 8: { return 0.0; } | ||
| 599 | case 9: { return 1.0; } | ||
| 600 | case 10: { return 0.5; } | ||
| 601 | case 11: { return cb_hls(fg.rgb).x; } | ||
| 602 | case 12: { return cb_hls(fg.rgb).y; } | ||
| 603 | case 13: { return cb_hls(fg.rgb).z; } | ||
| 604 | case 14: { return cb_hls(bg.rgb).x; } | ||
| 605 | case 15: { return cb_hls(bg.rgb).y; } | ||
| 606 | case 16: { return cb_hls(bg.rgb).z; } | ||
| 607 | case 17: { return dot(fg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } | ||
| 608 | case 18: { return dot(bg.rgb, vec3<f32>(0.299, 0.587, 0.114)); } | ||
| 609 | case 19: { return pos.x; } | ||
| 610 | case 20: { return pos.y; } | ||
| 611 | case 21: { return pos.z; } | ||
| 612 | case 22: { return uv.x; } | ||
| 613 | case 23: { return 1.0 - uv.y; } | ||
| 614 | case 24: { return 0.0; } | ||
| 615 | case 25: { return env_c.x; } | ||
| 616 | case 26: { return env_c.y; } | ||
| 617 | case 27: { return env_c.z; } | ||
| 618 | case 28: { return n.x; } | ||
| 619 | case 29: { return n.y; } | ||
| 620 | case 30: { return n.z; } | ||
| 621 | default: { return bg.r; } | ||
| 622 | } | ||
| 623 | } | ||
| 624 | |||
| 625 | fn cb_combine(op: i32, a: f32, b: f32) -> f32 { | ||
| 626 | switch op { | ||
| 627 | case 0: { return a; } | ||
| 628 | case 1: { return b; } | ||
| 629 | case 2: { return 1.0 - a; } | ||
| 630 | case 3: { return 1.0 - b; } | ||
| 631 | case 4: { return a + b; } | ||
| 632 | case 5: { return a - b; } | ||
| 633 | case 6: { return a * b; } | ||
| 634 | case 7: { return select(a / b, 0.0, abs(b) <= 1e-5); } | ||
| 635 | case 8: { return min(a, b); } | ||
| 636 | case 9: { return max(a, b); } | ||
| 637 | case 10: { return 0.5 * (a + b); } | ||
| 638 | default: { return a; } | ||
| 639 | } | ||
| 640 | } | ||
| 641 | |||
| 642 | @fragment | ||
| 643 | fn fs_mesh(in: VsOut) -> @location(0) vec4<f32> { | ||
| 644 | let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); | ||
| 645 | let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); | ||
| 646 | let dpdx_w = dpdx(in.world_pos); | ||
| 647 | let dpdy_w = dpdy(in.world_pos); | ||
| 648 | let duvdx = dpdx(uv_bump_xformed); | ||
| 649 | let duvdy = dpdy(uv_bump_xformed); | ||
| 650 | let duvdx_main = dpdx(uv_xformed); | ||
| 651 | let duvdy_main = dpdy(uv_xformed); | ||
| 652 | let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; | ||
| 653 | if (facing_away != BACK_PASS) { | ||
| 654 | discard; | ||
| 655 | } | ||
| 656 | |||
| 657 | let env_mode = i32(u.env_rot_0.w + 0.5); | ||
| 658 | let cb_on = u.cb_flags.x > 0.5; | ||
| 659 | let v_dir = normalize(u.cam_pos.xyz - in.world_pos); | ||
| 660 | var n_surf = normalize(in.world_n); | ||
| 661 | if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { | ||
| 662 | n_surf = perturb_bump_normal( | ||
| 663 | n_surf, | ||
| 664 | dpdx_w, | ||
| 665 | dpdy_w, | ||
| 666 | duvdx, | ||
| 667 | duvdy, | ||
| 668 | uv_bump_xformed, | ||
| 669 | u.mat_fx.x, | ||
| 670 | u.mat_fx.y, | ||
| 671 | u.bump_off_wrap.z, | ||
| 672 | u.bump_params.x, | ||
| 673 | i32(u.bump_params.y + 0.5), | ||
| 674 | ); | ||
| 675 | } | ||
| 676 | |||
| 677 | var base_straight = vec3<f32>(0.0); | ||
| 678 | var rgb_alpha = u.diffuse_col.a; | ||
| 679 | var out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 680 | |||
| 681 | if (env_mode == 1) { | ||
| 682 | // Standalone SphereMap shader: equirectangular/angular lookup along view ray. | ||
| 683 | let env_c = sample_sphere_map(-v_dir); | ||
| 684 | base_straight = env_c.rgb * u.diffuse_col.rgb; | ||
| 685 | rgb_alpha = env_c.a * u.diffuse_col.a; | ||
| 686 | out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 687 | } else { | ||
| 688 | var col = u.diffuse_col; | ||
| 689 | var tex_col = vec4<f32>(1.0); | ||
| 690 | var uv_samp = uv_xformed; | ||
| 691 | var tex_straight = vec3<f32>(1.0); | ||
| 692 | if (u.flags.x > 0.5) { | ||
| 693 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 694 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 695 | let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); | ||
| 696 | uv_samp = (canvas_px - u.dod.xy) / tdims; | ||
| 697 | if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { | ||
| 698 | discard; | ||
| 699 | } | ||
| 700 | } | ||
| 701 | tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); | ||
| 702 | if (u.mat_fx.z <= 0.5) { | ||
| 703 | tex_straight = select(vec3<f32>(0.0), tex_col.rgb / max(tex_col.a, 1e-5), tex_col.a > 1e-5); | ||
| 704 | } | ||
| 705 | col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; | ||
| 706 | } | ||
| 707 | // `rgb_alpha` is `tex_col.a * Diffuse.Opacity`; `Diffuse.Color.Alpha` (`u.mtl_params.x`) | ||
| 708 | // modulates output alpha without attenuating diffuse/specular RGB. | ||
| 709 | rgb_alpha = col.a; | ||
| 710 | out_alpha = rgb_alpha * u.mtl_params.x; | ||
| 711 | if (env_mode == 0 && !cb_on && out_alpha <= 0.002) { | ||
| 712 | discard; | ||
| 713 | } | ||
| 714 | |||
| 715 | let albedo = tex_straight * u.diffuse_col.rgb; | ||
| 716 | if (env_mode == 2 && u.refl_tint.w < 0.5) { | ||
| 717 | base_straight = vec3<f32>(0.0); | ||
| 718 | rgb_alpha = 0.0; | ||
| 719 | out_alpha = 0.0; | ||
| 720 | } else if (u.flags.y > 0.5) { | ||
| 721 | let tframe = compute_tangent_frame(n_surf, dpdx_w, dpdy_w, duvdx_main, duvdy_main); | ||
| 722 | let spec_rgb = u.specular_col.rgb; | ||
| 723 | let shininess = select(max(u.specular_col.w, 1.0), u.specular_col.w, u.mat_fx.w > 1.5); | ||
| 724 | let spec_int = u.flags.z; | ||
| 725 | |||
| 726 | var lit = albedo * u.ambient.rgb; | ||
| 727 | let n_dir = i32(u.light_counts.z + 0.5); | ||
| 728 | for (var i: i32 = 0; i < MAX_DIR_LIGHTS; i = i + 1) { | ||
| 729 | if (i >= n_dir) { break; } | ||
| 730 | let l = normalize(u.dir_to_light[i].xyz); | ||
| 731 | lit = lit + eval_light_contrib(n_surf, tframe.t, tframe.b, v_dir, l, u.dir_color[i].rgb, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); | ||
| 732 | } | ||
| 733 | |||
| 734 | let n_pt = i32(u.light_counts.x + 0.5); | ||
| 735 | for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { | ||
| 736 | if (i >= n_pt) { break; } | ||
| 737 | let to_l = u.point_pos[i].xyz - in.world_pos; | ||
| 738 | let dist = max(length(to_l), 1e-4); | ||
| 739 | let att = light_attenuation(dist, u.point_pos[i].w); | ||
| 740 | var occ = 0.0; | ||
| 741 | if (u.light_counts.w > 0.5) { | ||
| 742 | occ = point_shadow_occlusion(i, in.world_pos, n_surf, u.point_pos[i].xyz); | ||
| 743 | } | ||
| 744 | lit = lit + eval_light_contrib( | ||
| 745 | n_surf, tframe.t, tframe.b, v_dir, to_l / dist, u.point_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, | ||
| 746 | 1.0 - shadow.point[i].y * occ, 1.0 - occ, | ||
| 747 | ); | ||
| 748 | } | ||
| 749 | |||
| 750 | let n_sp = i32(u.light_counts.y + 0.5); | ||
| 751 | for (var i: i32 = 0; i < MAX_LIGHTS; i = i + 1) { | ||
| 752 | if (i >= n_sp) { break; } | ||
| 753 | let to_l = u.spot_pos[i].xyz - in.world_pos; | ||
| 754 | let dist = max(length(to_l), 1e-4); | ||
| 755 | let l_dir = to_l / dist; | ||
| 756 | let cos_theta = dot(-l_dir, normalize(u.spot_dir[i].xyz)); | ||
| 757 | let cos_inner = u.spot_pos[i].w; | ||
| 758 | let cos_outer = u.spot_dir[i].w; | ||
| 759 | let cone = clamp((cos_theta - cos_outer) / max(cos_inner - cos_outer, 1e-4), 0.0, 1.0); | ||
| 760 | if (cone > 0.0) { | ||
| 761 | let att = light_attenuation(dist, u.spot_col[i].w) * cone; | ||
| 762 | lit = lit + eval_light_contrib(n_surf, tframe.t, tframe.b, v_dir, l_dir, u.spot_col[i].rgb * att, albedo, spec_rgb, spec_int, shininess, 1.0, 1.0); | ||
| 763 | } | ||
| 764 | } | ||
| 765 | base_straight = lit; | ||
| 766 | } else { | ||
| 767 | base_straight = albedo * u.uv_off_wrap.w; | ||
| 768 | } | ||
| 769 | |||
| 770 | if (env_mode == 2) { | ||
| 771 | let r_dir = reflect(-v_dir, n_surf); | ||
| 772 | let refl_c = sample_sphere_map(r_dir); | ||
| 773 | let strength_var = i32(u.env_angles.z + 0.5); | ||
| 774 | var refl_str = clamp(u.env_angles.w, 0.0, 1.0); | ||
| 775 | if (strength_var != 0) { | ||
| 776 | let cos_nv = clamp(dot(n_surf, v_dir), 0.0, 1.0); | ||
| 777 | let f_ang = pow(1.0 - cos_nv, max(u.refl_params.z, 1e-4)); | ||
| 778 | refl_str = clamp(mix(u.refl_params.y, u.refl_params.x, f_ang), 0.0, 1.0); | ||
| 779 | } | ||
| 780 | var under_rgb = base_straight; | ||
| 781 | var under_a = rgb_alpha; | ||
| 782 | if (rgb_alpha < 0.999 && u.refl_params.w > 0.01 && u.env_rot_2.w > 0.5 && u.refl_tint.w > 0.5) { | ||
| 783 | let eta = 1.0 / max(u.refl_params.w, 0.01); | ||
| 784 | var refr_dir = refract(-v_dir, n_surf, eta); | ||
| 785 | if (dot(refr_dir, refr_dir) < 1e-5) { | ||
| 786 | refr_dir = r_dir; | ||
| 787 | } | ||
| 788 | let refr_c = sample_sphere_map(refr_dir); | ||
| 789 | under_rgb = mix(refr_c.rgb * u.refract_tint.rgb, base_straight, rgb_alpha); | ||
| 790 | under_a = clamp(max(rgb_alpha, refr_c.a * (1.0 - rgb_alpha)), 0.0, 1.0); | ||
| 791 | } | ||
| 792 | let under_premul = under_rgb * under_a; | ||
| 793 | let refl_a = refl_str * refl_c.a; | ||
| 794 | let out_premul = under_premul * (1.0 - refl_str) + refl_c.rgb * refl_a; | ||
| 795 | let final_a = clamp(under_a * (1.0 - refl_str) + refl_a, 0.0, 1.0); | ||
| 796 | base_straight = select(vec3<f32>(0.0), out_premul / max(final_a, 1e-5), final_a > 1e-5); | ||
| 797 | rgb_alpha = final_a; | ||
| 798 | out_alpha = clamp(out_alpha * (1.0 - refl_str) + refl_a, 0.0, 1.0); | ||
| 799 | } | ||
| 800 | } | ||
| 801 | |||
| 802 | if (cb_on) { | ||
| 803 | let bg_c = vec4<f32>(base_straight, out_alpha); | ||
| 804 | var fg_c = u.cb_fg_col; | ||
| 805 | if (u.cb_flags.z > 1.5) { | ||
| 806 | let fg_raw = textureSampleLevel(bump_tex, mat_samp, wrap_uv_only(uv_xformed, u.bump_off_wrap.z), 0.0); | ||
| 807 | let fg_s = select(vec3<f32>(0.0), fg_raw.rgb / max(fg_raw.a, 1e-5), fg_raw.a > 1e-5); | ||
| 808 | fg_c = vec4<f32>(fg_s * u.cb_fg_col.rgb, fg_raw.a * u.cb_fg_col.a); | ||
| 809 | } | ||
| 810 | let cspace = i32(u.cb_flags.y + 0.5); | ||
| 811 | var c_pos = in.world_pos; | ||
| 812 | var c_n = n_surf; | ||
| 813 | if (cspace == 0) { | ||
| 814 | c_pos = in.local_pos; | ||
| 815 | let ln_len = length(in.local_n); | ||
| 816 | c_n = select(vec3<f32>(0.0, 0.0, 1.0), in.local_n / ln_len, ln_len > 1e-5); | ||
| 817 | } else if (cspace == 2) { | ||
| 818 | c_pos = (u.view * vec4<f32>(in.world_pos, 1.0)).xyz; | ||
| 819 | let en = (u.view * vec4<f32>(n_surf, 0.0)).xyz; | ||
| 820 | let elen = length(en); | ||
| 821 | c_n = select(vec3<f32>(0.0, 0.0, 1.0), en / elen, elen > 1e-5); | ||
| 822 | } | ||
| 823 | let env_c = reflect(-v_dir, n_surf); | ||
| 824 | let r_out = cb_combine(i32(u.cb_ops.x + 0.5), cb_operand(i32(u.cb_ops_a.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.x + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 825 | let g_out = cb_combine(i32(u.cb_ops.y + 0.5), cb_operand(i32(u.cb_ops_a.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.y + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 826 | let b_out = cb_combine(i32(u.cb_ops.z + 0.5), cb_operand(i32(u.cb_ops_a.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.z + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 827 | let a_out = cb_combine(i32(u.cb_ops.w + 0.5), cb_operand(i32(u.cb_ops_a.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n), cb_operand(i32(u.cb_ops_b.w + 0.5), bg_c, fg_c, c_pos, uv_xformed, env_c, c_n)); | ||
| 828 | let clamped_a = clamp(a_out, 0.0, 1.0); | ||
| 829 | if (clamped_a <= 0.002) { | ||
| 830 | discard; | ||
| 831 | } | ||
| 832 | return vec4<f32>(clamp(vec3<f32>(r_out, g_out, b_out) * clamped_a, vec3<f32>(0.0), vec3<f32>(1.0)), clamped_a); | ||
| 833 | } | ||
| 834 | |||
| 835 | if (out_alpha <= 0.002) { | ||
| 836 | discard; | ||
| 837 | } | ||
| 838 | return vec4<f32>(clamp(base_straight * rgb_alpha, vec3<f32>(0.0), vec3<f32>(1.0)), out_alpha); | ||
| 839 | } | ||
| 840 | |||
| 841 | @fragment | ||
| 842 | fn fs_normal(in: VsOut) -> @location(0) vec4<f32> { | ||
| 843 | let uv_xformed = apply_uv_xform(in.uv, u.uv_xform, u.uv_off_wrap); | ||
| 844 | let uv_bump_xformed = apply_uv_xform(in.uv, u.bump_uv_xform, u.bump_off_wrap); | ||
| 845 | let dpdx_w = dpdx(in.world_pos); | ||
| 846 | let dpdy_w = dpdy(in.world_pos); | ||
| 847 | let duvdx = dpdx(uv_bump_xformed); | ||
| 848 | let duvdy = dpdy(uv_bump_xformed); | ||
| 849 | let facing_away = dot(in.world_n, u.cam_pos.xyz - in.world_pos) < 0.0; | ||
| 850 | if (facing_away != BACK_PASS) { | ||
| 851 | discard; | ||
| 852 | } | ||
| 853 | |||
| 854 | var col = u.diffuse_col; | ||
| 855 | if (u.flags.x > 0.5) { | ||
| 856 | var uv_samp = uv_xformed; | ||
| 857 | if (u.dod.z > 0.5 && u.dod.w > 0.5) { | ||
| 858 | let tdims = vec2<f32>(textureDimensions(mat_tex)); | ||
| 859 | let canvas_px = vec2<f32>(uv_samp.x * u.dod.z, uv_samp.y * u.dod.w); | ||
| 860 | uv_samp = (canvas_px - u.dod.xy) / tdims; | ||
| 861 | if (uv_samp.x < 0.0 || uv_samp.x > 1.0 || uv_samp.y < 0.0 || uv_samp.y > 1.0) { | ||
| 862 | discard; | ||
| 863 | } | ||
| 864 | } | ||
| 865 | let tex_col = textureSampleLevel(mat_tex, mat_samp, uv_samp, 0.0); | ||
| 866 | col = select(tex_col, vec4<f32>(1.0), u.mat_fx.z > 0.5) * u.diffuse_col; | ||
| 867 | } | ||
| 868 | let out_alpha = col.a * u.mtl_params.x; | ||
| 869 | if (i32(u.env_rot_0.w + 0.5) == 0 && u.cb_flags.x < 0.5 && out_alpha <= 0.002) { | ||
| 870 | discard; | ||
| 871 | } | ||
| 872 | |||
| 873 | let nlen = length(in.world_n); | ||
| 874 | var n = select(vec3<f32>(0.0, 0.0, 1.0), in.world_n / nlen, nlen > 1e-5); | ||
| 875 | if (u.bump_off_wrap.w > 0.5 && (u.mat_fx.y > 0.5 || abs(u.mat_fx.x) > 1e-5)) { | ||
| 876 | n = perturb_bump_normal( | ||
| 877 | n, | ||
| 878 | dpdx_w, | ||
| 879 | dpdy_w, | ||
| 880 | duvdx, | ||
| 881 | duvdy, | ||
| 882 | uv_bump_xformed, | ||
| 883 | u.mat_fx.x, | ||
| 884 | u.mat_fx.y, | ||
| 885 | u.bump_off_wrap.z, | ||
| 886 | u.bump_params.x, | ||
| 887 | i32(u.bump_params.y + 0.5), | ||
| 888 | ); | ||
| 889 | } | ||
| 890 | return vec4<f32>(n, 0.0); | ||
| 891 | } | ||
| 892 | "#; |
crates/engine/src/scene3d/surface_fx.wgsl created+232| ... | @@ -0,0 +1,232 @@ | ||
| 1 | struct SurfaceFx { | ||
| 2 | proc_a: vec4<f32>, | ||
| 3 | proc_b: vec4<f32>, | ||
| 4 | layer: vec4<f32>, | ||
| 5 | layer_col: vec4<f32>, | ||
| 6 | layer_spec: vec4<f32>, | ||
| 7 | layer_mtl: vec4<f32>, | ||
| 8 | pbr: vec4<f32>, | ||
| 9 | pbr_spec: vec4<f32>, | ||
| 10 | pbr_layers: vec4<f32>, | ||
| 11 | sheen: vec4<f32>, | ||
| 12 | emission: vec4<f32>, | ||
| 13 | fog: vec4<f32>, | ||
| 14 | fog_col: vec4<f32>, | ||
| 15 | env: vec4<f32>, | ||
| 16 | lut: array<vec4<f32>, 16>, | ||
| 17 | }; | ||
| 18 | |||
| 19 | fn sfx_lut(t: f32) -> vec4<f32> { | ||
| 20 | let x = clamp(t, 0.0, 1.0) * 15.0; | ||
| 21 | let i = min(u32(x), 14u); | ||
| 22 | return mix(u.sfx.lut[i], u.sfx.lut[i + 1u], x - f32(i)); | ||
| 23 | } | ||
| 24 | |||
| 25 | // `TexGradient` position along the gradient. Types measure from the UVW origin; Linear, Reflect | ||
| 26 | // and Cross depend on W alone, which every primitive leaves at 0. | ||
| 27 | fn gradient_t(uv_up: vec2<f32>) -> f32 { | ||
| 28 | let kind = i32(u.sfx.proc_a.y + 0.5); | ||
| 29 | var t = 0.5; | ||
| 30 | if (kind == 1 || kind == 3) { | ||
| 31 | t = 0.0; | ||
| 32 | } else if (kind == 2) { | ||
| 33 | t = max(abs(uv_up.x), abs(uv_up.y)); | ||
| 34 | } else if (kind == 4) { | ||
| 35 | t = length(uv_up); | ||
| 36 | } | ||
| 37 | t = (t - u.sfx.proc_a.w - 0.5) / u.sfx.proc_a.z + 0.5; | ||
| 38 | let repeat = i32(u.sfx.proc_b.x + 0.5); | ||
| 39 | if (repeat == 1) { | ||
| 40 | t = fract(t); | ||
| 41 | } else if (repeat == 2) { | ||
| 42 | t = 1.0 - abs(fract(t * 0.5) * 2.0 - 1.0); | ||
| 43 | } | ||
| 44 | return t; | ||
| 45 | } | ||
| 46 | |||
| 47 | // `FastNoiseTexture3D`: Seethe is the lattice Z for every octave and octave weights 0.5^i are | ||
| 48 | // normalised to sum to 2 (4 for Discontinuous). Contrast scales about 0 after Inverted. | ||
| 49 | fn noise_value(uv_up: vec2<f32>) -> f32 { | ||
| 50 | let detail = clamp(u.sfx.proc_a.y, 0.0, 10.0); | ||
| 51 | let disc = u.sfx.proc_b.w > 0.5; | ||
| 52 | let p = uv_up * (2.0 * u.sfx.proc_a.z); | ||
| 53 | let full = i32(floor(detail)); | ||
| 54 | let frac_w = detail - f32(full); | ||
| 55 | var sum = 0.0; | ||
| 56 | var norm = 0.0; | ||
| 57 | var amp = 1.0; | ||
| 58 | var scale = 1.0; | ||
| 59 | for (var i = 0; i <= full; i = i + 1) { | ||
| 60 | let w = select(amp, amp * frac_w, i == full); | ||
| 61 | if (w > 0.0) { | ||
| 62 | let n = simplex3d(vec3<f32>(p * scale, u.sfx.proc_a.w)); | ||
| 63 | sum = sum + w * select(n, abs(n), disc); | ||
| 64 | norm = norm + w; | ||
| 65 | } | ||
| 66 | amp = amp * 0.5; | ||
| 67 | scale = scale * 2.0; | ||
| 68 | } | ||
| 69 | let avg = select(0.0, sum / norm, norm > 0.0); | ||
| 70 | var val = select(0.5 + 2.0 * avg, 4.0 * avg, disc); | ||
| 71 | if (u.sfx.proc_b.z > 0.5) { | ||
| 72 | val = 1.0 - val; | ||
| 73 | } | ||
| 74 | return clamp(val * u.sfx.proc_b.x + u.sfx.proc_b.y, 0.0, 1.0); | ||
| 75 | } | ||
| 76 | |||
| 77 | // Premultiplied colour of the procedural source `proc_a.x`; `tex` is the bound texture or white. | ||
| 78 | fn surface_proc(tex: vec4<f32>, uv_up: vec2<f32>, n: vec3<f32>, v: vec3<f32>) -> vec4<f32> { | ||
| 79 | let kind = i32(u.sfx.proc_a.x + 0.5); | ||
| 80 | if (kind == 1) { | ||
| 81 | return sfx_lut(gradient_t(uv_up)); | ||
| 82 | } | ||
| 83 | if (kind == 2) { | ||
| 84 | return tex * noise_value(uv_up); | ||
| 85 | } | ||
| 86 | return sfx_lut(falloff_t(n, v, u.sfx.proc_a.y)); | ||
| 87 | } | ||
| 88 | |||
| 89 | fn falloff_t(n: vec3<f32>, v: vec3<f32>, power: f32) -> f32 { | ||
| 90 | // Back faces see their inner side face-on, as Fusion shades them. | ||
| 91 | return 1.0 - pow(min(abs(dot(n, v)), 1.0), power); | ||
| 92 | } | ||
| 93 | |||
| 94 | fn smith_g1(x: f32, a2: f32) -> f32 { | ||
| 95 | return 2.0 * x / max(x + sqrt(a2 + (1.0 - a2) * x * x), 1e-5); | ||
| 96 | } | ||
| 97 | |||
| 98 | // GGX distribution times Smith shadowing over 4 N.V (alpha = roughness^2). | ||
| 99 | fn ggx_spec(nh: f32, nl: f32, nv: f32, rough: f32) -> f32 { | ||
| 100 | let a = max(rough * rough, 1e-3); | ||
| 101 | let a2 = a * a; | ||
| 102 | let dd = nh * nh * (a2 - 1.0) + 1.0; | ||
| 103 | return a2 / (3.14159265 * dd * dd) * smith_g1(nl, a2) * smith_g1(nv, a2) / (4.0 * nv); | ||
| 104 | } | ||
| 105 | |||
| 106 | fn schlick(ior: f32, vh: f32) -> f32 { | ||
| 107 | let r0 = (ior - 1.0) / (ior + 1.0); | ||
| 108 | return r0 * r0 + (1.0 - r0 * r0) * pow(1.0 - vh, 5.0); | ||
| 109 | } | ||
| 110 | |||
| 111 | // GGX/Smith directional albedo E(N.V, roughness): rows are roughness i/7, columns N.V j/7. | ||
| 112 | const GGX_ALBEDO: array<f32, 64> = array<f32, 64>( | ||
| 113 | 0.9990, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, | ||
| 114 | 0.8846, 0.9884, 0.9974, 0.9991, 0.9995, 0.9998, 0.9994, 0.9995, | ||
| 115 | 0.9178, 0.9005, 0.9486, 0.9736, 0.9833, 0.9878, 0.9907, 0.9924, | ||
| 116 | 0.9113, 0.8517, 0.8629, 0.8934, 0.9187, 0.9364, 0.9482, 0.9564, | ||
| 117 | 0.8688, 0.8191, 0.7954, 0.7947, 0.8061, 0.8227, 0.8396, 0.8548, | ||
| 118 | 0.8011, 0.7525, 0.7125, 0.6876, 0.6745, 0.6704, 0.6722, 0.6778, | ||
| 119 | 0.7090, 0.6530, 0.6019, 0.5623, 0.5317, 0.5080, 0.4897, 0.4758, | ||
| 120 | 0.6010, 0.5370, 0.4774, 0.4296, 0.3905, 0.3580, 0.3304, 0.3069, | ||
| 121 | ); | ||
| 122 | |||
| 123 | fn ggx_albedo(nv: f32, rough: f32) -> f32 { | ||
| 124 | let x = clamp(nv, 0.0, 1.0) * 7.0; | ||
| 125 | let y = clamp(rough, 0.0, 1.0) * 7.0; | ||
| 126 | let i = min(u32(x), 6u); | ||
| 127 | let j = min(u32(y), 6u); | ||
| 128 | let row0 = mix(GGX_ALBEDO[j * 8u + i], GGX_ALBEDO[j * 8u + i + 1u], x - f32(i)); | ||
| 129 | let row1 = mix(GGX_ALBEDO[j * 8u + i + 8u], GGX_ALBEDO[j * 8u + i + 9u], x - f32(i)); | ||
| 130 | return mix(row0, row1, y - f32(j)); | ||
| 131 | } | ||
| 132 | |||
| 133 | // `MtlPBRUber`: GGX specular with Schlick Fresnel whose F0 blends from the IOR reflectance toward | ||
| 134 | // the base colour by metalness, scaled by 1 + F0 (1/E - 1) for the energy single scattering | ||
| 135 | // loses; a Charlie sheen lobe; and a GGX coat whose Fresnel dims everything beneath it. | ||
| 136 | fn pbr_uber_light( | ||
| 137 | n: vec3<f32>, | ||
| 138 | v: vec3<f32>, | ||
| 139 | l: vec3<f32>, | ||
| 140 | light_rgb: vec3<f32>, | ||
| 141 | albedo: vec3<f32>, | ||
| 142 | diffuse_vis: f32, | ||
| 143 | spec_vis: f32, | ||
| 144 | ) -> vec3<f32> { | ||
| 145 | let nl = max(dot(n, l), 0.0); | ||
| 146 | let nv = max(dot(n, v), 1e-3); | ||
| 147 | let h = normalize(l + v); | ||
| 148 | let nh = max(dot(n, h), 0.0); | ||
| 149 | let vh = max(dot(v, h), 0.0); | ||
| 150 | let metal = clamp(u.sfx.pbr.x, 0.0, 1.0); | ||
| 151 | let r0 = (u.sfx.pbr.z - 1.0) / (u.sfx.pbr.z + 1.0); | ||
| 152 | let f0 = mix(vec3<f32>(r0 * r0), albedo, metal); | ||
| 153 | let fres = f0 + (vec3<f32>(1.0) - f0) * pow(1.0 - vh, 5.0); | ||
| 154 | let diffuse = (1.0 - metal) * (vec3<f32>(1.0) - u.sfx.pbr.w * fres) * albedo * (u.sfx.pbr_spec.w * nl / 3.14159265); | ||
| 155 | let multi = vec3<f32>(1.0) + f0 * (1.0 / ggx_albedo(nv, u.sfx.pbr.y) - 1.0); | ||
| 156 | var spec = u.sfx.pbr_spec.rgb * fres * multi * (u.sfx.pbr.w * ggx_spec(nh, nl, nv, u.sfx.pbr.y)); | ||
| 157 | let inv_sheen = 1.0 / max(u.sfx.sheen.w * u.sfx.sheen.w, 1e-3); | ||
| 158 | let sin_h = sqrt(max(1.0 - nh * nh, 0.0)); | ||
| 159 | let charlie = (2.0 + inv_sheen) * pow(sin_h, inv_sheen) / 6.2831853; | ||
| 160 | spec = spec + u.sfx.sheen.rgb * (u.sfx.pbr_layers.w * charlie * nl / (4.0 * (nl + nv - nl * nv))); | ||
| 161 | let coat_f = u.sfx.pbr_layers.x * schlick(u.sfx.pbr_layers.z, vh); | ||
| 162 | let coat = coat_f * ggx_spec(nh, nl, nv, u.sfx.pbr_layers.y); | ||
| 163 | return light_rgb * ((diffuse * diffuse_vis + spec * spec_vis) * (1.0 - coat_f) + coat * spec_vis); | ||
| 164 | } | ||
| 165 | |||
| 166 | // `Fog3D` over the lit colour: eye depth, or eye distance when Radial. | ||
| 167 | fn apply_fog(c: vec3<f32>, world_pos: vec3<f32>) -> vec3<f32> { | ||
| 168 | let kind = i32(u.sfx.fog.x + 0.5); | ||
| 169 | if (kind == 0) { | ||
| 170 | return c; | ||
| 171 | } | ||
| 172 | let eye = (u.view * vec4<f32>(world_pos, 1.0)).xyz; | ||
| 173 | let d = select(-eye.z, length(eye), u.sfx.fog_col.w > 0.5); | ||
| 174 | var f = exp(-u.sfx.fog.w * d); | ||
| 175 | if (kind == 1) { | ||
| 176 | f = (u.sfx.fog.z - d) / max(u.sfx.fog.z - u.sfx.fog.y, 1e-5); | ||
| 177 | } else if (kind == 3) { | ||
| 178 | f = exp(-(u.sfx.fog.w * d) * (u.sfx.fog.w * d)); | ||
| 179 | } | ||
| 180 | f = clamp(f, 0.0, 1.0); | ||
| 181 | return c * f + u.sfx.fog_col.rgb * (1.0 - f); | ||
| 182 | } | ||
| 183 | |||
| 184 | // World direction in the environment's coordinate system (`env.x`: 1 model, 2 camera). | ||
| 185 | fn env_space(d: vec3<f32>) -> vec3<f32> { | ||
| 186 | let space = i32(u.sfx.env.x + 0.5); | ||
| 187 | if (space == 1) { | ||
| 188 | // The adjugate is the inverse up to a positive scale, which the caller normalises away. | ||
| 189 | return transpose(normal_matrix(u.model)) * d; | ||
| 190 | } | ||
| 191 | if (space == 2) { | ||
| 192 | return (u.view * vec4<f32>(d, 0.0)).xyz; | ||
| 193 | } | ||
| 194 | return d; | ||
| 195 | } | ||
| 196 | |||
| 197 | // `CubeMap` texture coordinates (V down) of direction `d`: `mode` 2 = vertical cross, 3 = | ||
| 198 | // horizontal cross, 4 = one face image. Crosses sit at the image's bottom-left corner. | ||
| 199 | fn cube_uv(d: vec3<f32>, mode: i32, dims: vec2<f32>) -> vec2<f32> { | ||
| 200 | let a = abs(d); | ||
| 201 | let horizontal = mode == 3; | ||
| 202 | let mid = select(2.0, 1.0, horizontal); | ||
| 203 | var st: vec2<f32>; | ||
| 204 | var tile: vec2<f32>; | ||
| 205 | if (a.x >= a.y && a.x >= a.z) { | ||
| 206 | let s = vec2<f32>(d.z, d.y) / a.x * 0.5 + 0.5; | ||
| 207 | st = select(vec2<f32>(1.0 - s.x, s.y), s, d.x > 0.0); | ||
| 208 | tile = vec2<f32>(select(2.0, 0.0, d.x > 0.0), mid); | ||
| 209 | } else if (a.y >= a.z) { | ||
| 210 | let s = vec2<f32>(d.x, d.z) / a.y * 0.5 + 0.5; | ||
| 211 | st = select(vec2<f32>(1.0 - s.x, s.y), vec2<f32>(1.0) - s, d.y > 0.0); | ||
| 212 | tile = vec2<f32>(1.0, mid + select(-1.0, 1.0, d.y > 0.0)); | ||
| 213 | } else { | ||
| 214 | let s = vec2<f32>(d.x, d.y) / a.z * 0.5 + 0.5; | ||
| 215 | if (d.z > 0.0) { | ||
| 216 | st = vec2<f32>(1.0 - s.x, s.y); | ||
| 217 | tile = vec2<f32>(1.0, mid); | ||
| 218 | } else if (horizontal || mode == 4) { | ||
| 219 | st = s; | ||
| 220 | tile = vec2<f32>(3.0, 1.0); | ||
| 221 | } else { | ||
| 222 | st = vec2<f32>(1.0) - s; | ||
| 223 | tile = vec2<f32>(1.0, 0.0); | ||
| 224 | } | ||
| 225 | } | ||
| 226 | if (mode == 4) { | ||
| 227 | return vec2<f32>(st.x, 1.0 - st.y); | ||
| 228 | } | ||
| 229 | let face = select(min(dims.x / 3.0, dims.y / 4.0), min(dims.x / 4.0, dims.y / 3.0), horizontal); | ||
| 230 | let uv_up = (tile + st) * face / dims; | ||
| 231 | return vec2<f32>(uv_up.x, 1.0 - uv_up.y); | ||
| 232 | } | ||
crates/engine/src/scene3d/textures.rs created+168| ... | @@ -0,0 +1,168 @@ | ||
| 1 | //! Procedural and environment 3D textures: `TexGradient`, `FastNoiseTexture3D`, `SphereMap` and | ||
| 2 | //! `CubeMap`. | ||
| 3 | |||
| 4 | use super::collect::{euler_matrix, ResolvedMaterial}; | ||
| 5 | use super::fx::{gradient_lut, proc_kind, SurfaceFx}; | ||
| 6 | use super::materials::{flat, Resolve}; | ||
| 7 | use super::MaterialFx; | ||
| 8 | use model::{Comp, ExprEngine, Node}; | ||
| 9 | |||
| 10 | pub(super) fn tex_gradient(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> ResolvedMaterial { | ||
| 11 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 12 | let kind = match n.static_str("GradientType") { | ||
| 13 | Some("Reflect") => 1.0, | ||
| 14 | Some("Square") => 2.0, | ||
| 15 | Some("Cross") => 3.0, | ||
| 16 | Some("Radial") => 4.0, | ||
| 17 | _ => 0.0, | ||
| 18 | }; | ||
| 19 | let repeat = match n.static_str("Repeat") { | ||
| 20 | Some("Repeat") => 1.0, | ||
| 21 | Some("Ping-Pong") => 2.0, | ||
| 22 | _ => 0.0, | ||
| 23 | }; | ||
| 24 | let scale = f("Scale", 1.0); | ||
| 25 | let mut mat = flat([1.0; 4]); | ||
| 26 | mat.fx.sfx.proc_a = [proc_kind::GRADIENT, kind, if scale.abs() < 1e-6 { 1e-6 } else { scale }, f("Offset", 0.0)]; | ||
| 27 | mat.fx.sfx.proc_b = [repeat, 0.0, 0.0, 0.0]; | ||
| 28 | mat.fx.sfx.lut = gradient_lut(comp.eval_gradient(n, "Gradient", time), [[0.0, 0.0, 0.0, 1.0], [1.0; 4]]); | ||
| 29 | mat | ||
| 30 | } | ||
| 31 | |||
| 32 | /// `FastNoiseTexture3D` over mesh UVW; `ThreeD` output differs only along W, which primitives | ||
| 33 | /// leave at 0. A `SourceMaterial` texture is scaled by the noise. | ||
| 34 | pub(super) fn fast_noise(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 35 | let f = |k: &str, d: f64| comp.eval_number(n, k, time, d, expr) as f32; | ||
| 36 | let source = n.connected_node("SourceMaterial").and_then(|s| comp.find_node(s)).map(&mut *resolve); | ||
| 37 | let mut mat = flat([1.0; 4]); | ||
| 38 | if let Some(src) = source { | ||
| 39 | mat.tex_node = src.tex_node; | ||
| 40 | mat.fx.uv = src.fx.uv; | ||
| 41 | mat.fx.uv_wrap = src.fx.uv_wrap; | ||
| 42 | } | ||
| 43 | let seethe = f("Seethe", 1.0) + f("SeetheRate", 0.0) * time as f32 * 0.1; | ||
| 44 | mat.fx.sfx.proc_a = [proc_kind::NOISE, f("Detail", 2.0), f("XScale", 1.0), seethe]; | ||
| 45 | mat.fx.sfx.proc_b = [f("Contrast", 1.0), f("Brightness", 0.0), f("Invert", 0.0), f("Discontinuous", 0.0)]; | ||
| 46 | mat | ||
| 47 | } | ||
| 48 | |||
| 49 | /// Column-major `R^T` of the node's `Rotate.*`: rotating the environment by `R` samples world | ||
| 50 | /// directions through its inverse. | ||
| 51 | fn env_rotation(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine) -> [f32; 9] { | ||
| 52 | let rot_deg = ["X", "Y", "Z"].map(|a| comp.eval_number(n, &format!("Rotate.{a}"), time, 0.0, expr) as f32); | ||
| 53 | let r = euler_matrix(rot_deg, n.static_str("Rotate.RotOrder").unwrap_or("XYZ")); | ||
| 54 | [r[0], r[4], r[8], r[1], r[5], r[9], r[2], r[6], r[10]] | ||
| 55 | } | ||
| 56 | |||
| 57 | fn env_material(tex_node: Option<model::NodeId>, env_rot: [f32; 9], env_map_mode: u32, coord_space: f32) -> ResolvedMaterial { | ||
| 58 | ResolvedMaterial { | ||
| 59 | tex_node, | ||
| 60 | fx: MaterialFx { | ||
| 61 | env_mode: 1, | ||
| 62 | env_map_mode, | ||
| 63 | env_tex_slot: u32::from(tex_node.is_some()), | ||
| 64 | env_rot, | ||
| 65 | sfx: SurfaceFx { env: [coord_space, 0.0, 0.0, 0.0], ..SurfaceFx::default() }, | ||
| 66 | ..MaterialFx::default() | ||
| 67 | }, | ||
| 68 | ..flat([1.0; 4]) | ||
| 69 | } | ||
| 70 | } | ||
| 71 | |||
| 72 | /// `SphereMap` along the view ray. `StartAngle`/`EndAngle` have no effect in Fusion's renderer. | ||
| 73 | pub(super) fn sphere_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 74 | let tex = n.connected_node("Image").and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node); | ||
| 75 | let map_mode = comp.eval_number(n, "MapMode", time, 0.0, expr).round().clamp(0.0, 1.0) as u32; | ||
| 76 | env_material(tex, env_rotation(comp, n, time, expr), map_mode, 0.0) | ||
| 77 | } | ||
| 78 | |||
| 79 | /// `CubeMap` from a vertical (`Layout` 1) or horizontal (2) cross, or separate faces (0). | ||
| 80 | /// `Convention` does not change Fusion's render. | ||
| 81 | pub(super) fn cube_map(comp: &Comp, n: &Node, time: f64, expr: &ExprEngine, resolve: &mut Resolve) -> ResolvedMaterial { | ||
| 82 | let env_rot = env_rotation(comp, n, time, expr); | ||
| 83 | let layout = comp.eval_number(n, "Layout", time, 1.0, expr).round() as i32; | ||
| 84 | let (input, mode) = match layout { | ||
| 85 | // Two texture slots cannot hold six faces, so separate images bind the face that the | ||
| 86 | // rotated forward (-Z) view direction sees. | ||
| 87 | 0 => { | ||
| 88 | let fwd = [-env_rot[6], -env_rot[7], -env_rot[8]]; | ||
| 89 | let axis = (0..3).max_by(|&a, &b| fwd[a].abs().total_cmp(&fwd[b].abs())).unwrap_or(2); | ||
| 90 | let sign = if fwd[axis] > 0.0 { "Positive" } else { "Negative" }; | ||
| 91 | (format!("{sign}{}", ["X", "Y", "Z"][axis]), 4) | ||
| 92 | } | ||
| 93 | 2 => ("CrossImage".to_string(), 3), | ||
| 94 | _ => ("CrossImage".to_string(), 2), | ||
| 95 | }; | ||
| 96 | let tex = n.connected_node(&input).and_then(|s| comp.find_node(s)).and_then(|id| resolve(id).tex_node); | ||
| 97 | let coord_space = match n.static_str("CoordSystem") { | ||
| 98 | Some("Model") => 1.0, | ||
| 99 | Some("Camera") => 2.0, | ||
| 100 | _ => 0.0, | ||
| 101 | }; | ||
| 102 | env_material(tex, env_rot, mode, coord_space) | ||
| 103 | } | ||
| 104 | |||
| 105 | #[cfg(test)] | ||
| 106 | mod tests { | ||
| 107 | use super::*; | ||
| 108 | use crate::scene3d::collect::resolve_test_material as resolve_in; | ||
| 109 | |||
| 110 | #[test] | ||
| 111 | fn tex_gradient_maps_type_repeat_and_default_ramp() { | ||
| 112 | let mat = resolve_in( | ||
| 113 | "X = TexGradient { Inputs = { GradientType = Input { Value = FuID { \"Radial\" }, }, | ||
| 114 | Repeat = Input { Value = FuID { \"Ping-Pong\" }, }, Scale = Input { Value = 2, }, Offset = Input { Value = 0.25, }, }, },", | ||
| 115 | ); | ||
| 116 | assert!(mat.unlit); | ||
| 117 | assert_eq!(mat.fx.sfx.proc_a, [proc_kind::GRADIENT, 4.0, 2.0, 0.25]); | ||
| 118 | assert_eq!(mat.fx.sfx.proc_b[0], 2.0); | ||
| 119 | assert_eq!(mat.fx.sfx.lut[0], [0.0, 0.0, 0.0, 1.0]); | ||
| 120 | assert_eq!(mat.fx.sfx.lut[15], [1.0; 4]); | ||
| 121 | } | ||
| 122 | |||
| 123 | #[test] | ||
| 124 | fn fast_noise_reads_fbm_params_and_source() { | ||
| 125 | let mat = resolve_in( | ||
| 126 | "Img = Background { }, | ||
| 127 | X = FastNoiseTexture3D { Inputs = { Detail = Input { Value = 3, }, XScale = Input { Value = 4, }, | ||
| 128 | Contrast = Input { Value = 2, }, Invert = Input { Value = 1, }, Discontinuous = Input { Value = 1, }, | ||
| 129 | SourceMaterial = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", | ||
| 130 | ); | ||
| 131 | assert!(mat.tex_node.is_some()); | ||
| 132 | assert_eq!(mat.fx.sfx.proc_a, [proc_kind::NOISE, 3.0, 4.0, 1.0]); | ||
| 133 | assert_eq!(mat.fx.sfx.proc_b, [2.0, 0.0, 1.0, 1.0]); | ||
| 134 | } | ||
| 135 | |||
| 136 | #[test] | ||
| 137 | fn sphere_map_ignores_start_end_angles_and_transposes_rotation() { | ||
| 138 | let mat = resolve_in( | ||
| 139 | "Img = Background { }, | ||
| 140 | X = SphereMap { Inputs = { [\"Rotate.Y\"] = Input { Value = 90, }, MapMode = Input { Value = 1, }, | ||
| 141 | StartAngle = Input { Value = 30, }, Image = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", | ||
| 142 | ); | ||
| 143 | assert_eq!((mat.fx.env_mode, mat.fx.env_map_mode, mat.fx.env_tex_slot), (1, 1, 1)); | ||
| 144 | // R_y(90) maps +X to -Z, so R^T's first column is (0, 0, 1). | ||
| 145 | let c0 = &mat.fx.env_rot[0..3]; | ||
| 146 | assert!(c0[0].abs() < 1e-6 && (c0[2] - 1.0).abs() < 1e-6, "{c0:?}"); | ||
| 147 | } | ||
| 148 | |||
| 149 | #[test] | ||
| 150 | fn cube_map_layouts_and_separate_face_choice() { | ||
| 151 | let cross = resolve_in( | ||
| 152 | "Img = Background { }, | ||
| 153 | X = CubeMap { Inputs = { Layout = Input { Value = 2, }, CoordSystem = Input { Value = FuID { \"Model\" }, }, | ||
| 154 | CrossImage = Input { SourceOp = \"Img\", Source = \"Output\", }, }, },", | ||
| 155 | ); | ||
| 156 | assert_eq!((cross.fx.env_map_mode, cross.fx.env_tex_slot), (3, 1)); | ||
| 157 | assert_eq!(cross.fx.sfx.env[0], 1.0); | ||
| 158 | let faces = "PX = Background { }, NZ = Background { }, | ||
| 159 | X = CubeMap { Inputs = { Layout = Input { Value = 0, }, [\"Rotate.Y\"] = Input { Value = ROT, }, | ||
| 160 | PositiveX = Input { SourceOp = \"PX\", Source = \"Output\", }, | ||
| 161 | NegativeZ = Input { SourceOp = \"NZ\", Source = \"Output\", }, }, },"; | ||
| 162 | let front = resolve_in(&faces.replace("ROT", "0")); | ||
| 163 | let turned = resolve_in(&faces.replace("ROT", "90")); | ||
| 164 | assert_eq!(front.fx.env_map_mode, 4); | ||
| 165 | assert!(front.tex_node.is_some() && turned.tex_node.is_some()); | ||
| 166 | assert_ne!(front.tex_node, turned.tex_node, "rotating the map brings +X to the front"); | ||
| 167 | } | ||
| 168 | } | ||