| 1 | //! 3D mesh deformers (`Bender3D`) and vertex instancing (`Replicate3D`). |
| 2 | |
| 3 | use std::collections::HashMap; |
| 4 | use std::sync::Arc; |
| 5 | |
| 6 | use super::collect::mat4_inverse; |
| 7 | use super::math::{ |
| 8 | mat4_mul, mat4_rot_x, mat4_rot_y, mat4_rot_z, mat4_scale, mat4_translate, |
| 9 | }; |
| 10 | use super::mesh::{build_shape_mesh, triangle_soup}; |
| 11 | use super::{Mat4, MeshInstance, ShapeKind, Vertex3D}; |
| 12 | |
| 13 | /// Maximum number of meshes allowed in a collected 3D scene (shared with `collect.rs`). |
| 14 | pub(super) const MAX_SCENE_MESHES: usize = 16_384; |
| 15 | |
| 16 | /// Deformation mode of `Bender3D`. |
| 17 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 18 | pub enum BenderMode { |
| 19 | Bend, |
| 20 | Taper, |
| 21 | Twist, |
| 22 | Shear, |
| 23 | } |
| 24 | |
| 25 | /// Evaluated parameters for a `Bender3D` node. |
| 26 | #[derive(Clone, Copy, Debug)] |
| 27 | pub struct Bender3DParams { |
| 28 | pub mode: BenderMode, |
| 29 | pub amount: f32, |
| 30 | /// `0 = X`, `1 = Y`, `2 = Z`. |
| 31 | pub axis: u32, |
| 32 | /// Bend/shear plane angle in degrees around the bend axis. |
| 33 | pub angle_deg: f32, |
| 34 | /// Pivot fraction along the bounding box on the chosen axis (`0..=1`, default `0.5`). |
| 35 | pub center: f32, |
| 36 | /// Lower active range fraction along the chosen axis (`0..=1`, default `0.0`). |
| 37 | pub range_min: f32, |
| 38 | /// Upper active range fraction along the chosen axis (`0..=1`, default `1.0`). |
| 39 | pub range_max: f32, |
| 40 | /// When true, all child meshes are deformed together inside their shared bounding box. |
| 41 | pub group: bool, |
| 42 | } |
| 43 | |
| 44 | impl Default for Bender3DParams { |
| 45 | fn default() -> Self { |
| 46 | Self { |
| 47 | mode: BenderMode::Bend, |
| 48 | amount: 0.0, |
| 49 | axis: 1, |
| 50 | angle_deg: 0.0, |
| 51 | center: 0.5, |
| 52 | range_min: 0.0, |
| 53 | range_max: 1.0, |
| 54 | group: false, |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | #[inline] |
| 60 | fn vec3_dot(a: [f32; 3], b: [f32; 3]) -> f32 { |
| 61 | a[0] * b[0] + a[1] * b[1] + a[2] * b[2] |
| 62 | } |
| 63 | |
| 64 | #[inline] |
| 65 | fn vec3_sub(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { |
| 66 | [a[0] - b[0], a[1] - b[1], a[2] - b[2]] |
| 67 | } |
| 68 | |
| 69 | #[inline] |
| 70 | fn vec3_cross(a: [f32; 3], b: [f32; 3]) -> [f32; 3] { |
| 71 | [ |
| 72 | a[1] * b[2] - a[2] * b[1], |
| 73 | a[2] * b[0] - a[0] * b[2], |
| 74 | a[0] * b[1] - a[1] * b[0], |
| 75 | ] |
| 76 | } |
| 77 | |
| 78 | #[inline] |
| 79 | fn vec3_norm(a: [f32; 3]) -> Option<[f32; 3]> { |
| 80 | let l = vec3_dot(a, a).sqrt(); |
| 81 | (l > 1e-8).then(|| [a[0] / l, a[1] / l, a[2] / l]) |
| 82 | } |
| 83 | |
| 84 | #[inline] |
| 85 | fn xform_point(m: Mat4, p: [f32; 3]) -> [f32; 3] { |
| 86 | [ |
| 87 | m[0] * p[0] + m[4] * p[1] + m[8] * p[2] + m[12], |
| 88 | m[1] * p[0] + m[5] * p[1] + m[9] * p[2] + m[13], |
| 89 | m[2] * p[0] + m[6] * p[1] + m[10] * p[2] + m[14], |
| 90 | ] |
| 91 | } |
| 92 | |
| 93 | #[inline] |
| 94 | fn xform_vector(m: Mat4, v: [f32; 3]) -> [f32; 3] { |
| 95 | [ |
| 96 | m[0] * v[0] + m[4] * v[1] + m[8] * v[2], |
| 97 | m[1] * v[0] + m[5] * v[1] + m[9] * v[2], |
| 98 | m[2] * v[0] + m[6] * v[1] + m[10] * v[2], |
| 99 | ] |
| 100 | } |
| 101 | |
| 102 | /// Transforms a surface normal by the cofactor matrix of `m` (inverse-transpose up to scale), |
| 103 | /// preserving outward orientation under non-uniform scale and mirroring. |
| 104 | #[inline] |
| 105 | fn xform_normal(m: Mat4, n: [f32; 3]) -> [f32; 3] { |
| 106 | let c0 = [m[0], m[1], m[2]]; |
| 107 | let c1 = [m[4], m[5], m[6]]; |
| 108 | let c2 = [m[8], m[9], m[10]]; |
| 109 | let sign = if vec3_dot(c0, vec3_cross(c1, c2)) >= 0.0 { 1.0 } else { -1.0 }; |
| 110 | let r0 = vec3_cross(c1, c2); |
| 111 | let r1 = vec3_cross(c2, c0); |
| 112 | let r2 = vec3_cross(c0, c1); |
| 113 | let out = [ |
| 114 | (r0[0] * n[0] + r1[0] * n[1] + r2[0] * n[2]) * sign, |
| 115 | (r0[1] * n[0] + r1[1] * n[1] + r2[1] * n[2]) * sign, |
| 116 | (r0[2] * n[0] + r1[2] * n[1] + r2[2] * n[2]) * sign, |
| 117 | ]; |
| 118 | vec3_norm(out).unwrap_or([0.0, 0.0, 1.0]) |
| 119 | } |
| 120 | |
| 121 | /// Right-handed orthonormal basis `(u, v, w)` where `w` is the bend axis rotated by `angle_deg`. |
| 122 | fn bender_basis(axis: u32, angle_deg: f32) -> ([f32; 3], [f32; 3], [f32; 3]) { |
| 123 | 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 | 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 | }; |
| 128 | let (s, c) = angle_deg.to_radians().sin_cos(); |
| 129 | let u = [ |
| 130 | u0[0] * c + v0[0] * s, |
| 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) |
| 140 | } |
| 141 | |
| 142 | fn axis_bounds_of(verts: &[Vertex3D], w: [f32; 3]) -> Option<[f32; 2]> { |
| 143 | let mut mn = f32::INFINITY; |
| 144 | let mut mx = f32::NEG_INFINITY; |
| 145 | for v in verts { |
| 146 | let p = vec3_dot(v.pos, w); |
| 147 | mn = mn.min(p); |
| 148 | mx = mx.max(p); |
| 149 | } |
| 150 | (mn.is_finite() && mx.is_finite()).then_some([mn, mx]) |
| 151 | } |
| 152 | |
| 153 | /// Applies `Bender3D` deformation to `verts` in-place and recomputes smooth vertex normals. |
| 154 | pub fn deform_mesh_vertices( |
| 155 | verts: &mut [Vertex3D], |
| 156 | indices: &[u32], |
| 157 | params: &Bender3DParams, |
| 158 | shared_bounds: Option<[f32; 2]>, |
| 159 | ) { |
| 160 | if verts.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { |
| 161 | return; |
| 162 | } |
| 163 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; |
| 164 | let (u, v, w) = bender_basis(params.axis, angle_deg); |
| 165 | let Some([min_w, max_w]) = shared_bounds.or_else(|| axis_bounds_of(verts, w)) else { |
| 166 | return; |
| 167 | }; |
| 168 | let extent = max_w - min_w; |
| 169 | if !extent.is_finite() || extent <= 1e-6 { |
| 170 | return; |
| 171 | } |
| 172 | let raw_r_min = if params.range_min.is_finite() { params.range_min } else { 0.0 }; |
| 173 | let raw_r_max = if params.range_max.is_finite() { params.range_max } else { 1.0 }; |
| 174 | let r_min_frac = raw_r_min.clamp(0.0, 1.0); |
| 175 | let r_max_frac = raw_r_max.clamp(r_min_frac, 1.0); |
| 176 | if (r_max_frac - r_min_frac) <= 1e-6 { |
| 177 | return; |
| 178 | } |
| 179 | let center_frac = if params.center.is_finite() { |
| 180 | params.center.clamp(0.0, 1.0) |
| 181 | } else { |
| 182 | 0.5 |
| 183 | }; |
| 184 | let w0 = min_w + center_frac * extent; |
| 185 | let r_min = min_w + r_min_frac * extent; |
| 186 | let r_max = min_w + r_max_frac * extent; |
| 187 | let amount = params.amount; |
| 188 | |
| 189 | for vert in verts.iter_mut() { |
| 190 | let pu = vec3_dot(vert.pos, u); |
| 191 | let pv = vec3_dot(vert.pos, v); |
| 192 | let pw = vec3_dot(vert.pos, w); |
| 193 | let wc = pw.clamp(r_min, r_max); |
| 194 | let w_ext = pw - wc; |
| 195 | let t = (wc - w0) / extent; |
| 196 | |
| 197 | let nu_old = vec3_dot(vert.normal, u); |
| 198 | let nv_old = vec3_dot(vert.normal, v); |
| 199 | let nw_old = vec3_dot(vert.normal, w); |
| 200 | |
| 201 | let (nu, nv, nw, rnu, rnv, rnw) = match params.mode { |
| 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 | } |
| 221 | BenderMode::Taper => { |
| 222 | let s = (1.0 + amount * 2.0 * t).max(0.0); |
| 223 | (pu * s, pv * s, pw, nu_old, nv_old, nw_old) |
| 224 | } |
| 225 | BenderMode::Twist => { |
| 226 | let theta = amount * std::f32::consts::TAU * t; |
| 227 | let (st, ct) = theta.sin_cos(); |
| 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 | } |
| 331 | } |
| 332 | } |
| 333 | for (v, n_opt) in verts.iter_mut().zip(new_normals) { |
| 334 | if let Some(n) = n_opt { |
| 335 | v.normal = n; |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | /// Applies `Bender3D` to a slice of collected child meshes (either individually or as a group). |
| 341 | pub fn apply_bender_to_meshes( |
| 342 | meshes: &mut [MeshInstance], |
| 343 | bender_world: Mat4, |
| 344 | params: &Bender3DParams, |
| 345 | image_plane_aspect: impl Fn(&MeshInstance) -> f32, |
| 346 | ) { |
| 347 | if meshes.is_empty() || !params.amount.is_finite() || params.amount.abs() < 1e-6 { |
| 348 | return; |
| 349 | } |
| 350 | |
| 351 | if params.group { |
| 352 | let inv_bender = mat4_inverse(bender_world); |
| 353 | let angle_deg = if params.angle_deg.is_finite() { params.angle_deg } else { 0.0 }; |
| 354 | let (_, _, w_axis) = bender_basis(params.axis, angle_deg); |
| 355 | let mut baked: Vec<(Vec<Vertex3D>, Vec<u32>)> = Vec::with_capacity(meshes.len()); |
| 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); |
| 361 | let aspect = image_plane_aspect(m); |
| 362 | let (mut verts, idx) = build_shape_mesh(m.shape.base_shape(), aspect); |
| 363 | for vert in &mut verts { |
| 364 | vert.pos = xform_point(rel, vert.pos); |
| 365 | 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 | } |
| 393 | deform_mesh_vertices(&mut verts, &idx, params, None); |
| 394 | let soup = triangle_soup((verts, idx)); |
| 395 | let (_, fx) = m.shape.split_fx(); |
| 396 | m.shape = ShapeKind::WithMaterialFx { |
| 397 | inner: Box::new(ShapeKind::CustomMesh(Arc::new(soup))), |
| 398 | fx, |
| 399 | }; |
| 400 | } |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | /// World-space destination point + orthonormal TBN frame extracted for `Replicate3D`. |
| 405 | #[derive(Clone, Copy, Debug)] |
| 406 | pub struct ReplicatePoint { |
| 407 | pub pos: [f32; 3], |
| 408 | pub normal: [f32; 3], |
| 409 | pub tangent: [f32; 3], |
| 410 | pub bitangent: [f32; 3], |
| 411 | } |
| 412 | |
| 413 | /// Extracts deduplicated world-space vertex frames from destination meshes for `Replicate3D`. |
| 414 | pub fn extract_replicate_points( |
| 415 | dest_meshes: &[MeshInstance], |
| 416 | step: usize, |
| 417 | max_points: usize, |
| 418 | ) -> Vec<ReplicatePoint> { |
| 419 | if dest_meshes.is_empty() || max_points == 0 { |
| 420 | return Vec::new(); |
| 421 | } |
| 422 | let stride = step.max(1); |
| 423 | let key = |p: [f32; 3]| p.map(|c| (c * 1e4).round() as i64); |
| 424 | |
| 425 | struct Accum { |
| 426 | pos: [f32; 3], |
| 427 | normal: [f32; 3], |
| 428 | tangent: [f32; 3], |
| 429 | } |
| 430 | |
| 431 | let mut order: Vec<[i64; 3]> = Vec::new(); |
| 432 | let mut table: HashMap<[i64; 3], Accum> = HashMap::new(); |
| 433 | |
| 434 | for dm in dest_meshes { |
| 435 | let (verts, indices) = build_shape_mesh(dm.shape.base_shape(), 1.0); |
| 436 | if verts.is_empty() { |
| 437 | continue; |
| 438 | } |
| 439 | // Compute per-vertex tangents from triangles when available. |
| 440 | let mut tangents = vec![[0.0_f32; 3]; verts.len()]; |
| 441 | for tri in indices.chunks_exact(3) { |
| 442 | let (i0, i1, i2) = (tri[0] as usize, tri[1] as usize, tri[2] as usize); |
| 443 | if i0 >= verts.len() || i1 >= verts.len() || i2 >= verts.len() { |
| 444 | continue; |
| 445 | } |
| 446 | let e1 = vec3_sub(verts[i1].pos, verts[i0].pos); |
| 447 | let e2 = vec3_sub(verts[i2].pos, verts[i0].pos); |
| 448 | let du1 = verts[i1].uv[0] - verts[i0].uv[0]; |
| 449 | let dv1 = verts[i1].uv[1] - verts[i0].uv[1]; |
| 450 | let du2 = verts[i2].uv[0] - verts[i0].uv[0]; |
| 451 | let dv2 = verts[i2].uv[1] - verts[i0].uv[1]; |
| 452 | let det = du1 * dv2 - dv1 * du2; |
| 453 | let t_tri = if det.abs() > 1e-6 { |
| 454 | let inv = 1.0 / det; |
| 455 | [ |
| 456 | (e1[0] * dv2 - e2[0] * dv1) * inv, |
| 457 | (e1[1] * dv2 - e2[1] * dv1) * inv, |
| 458 | (e1[2] * dv2 - e2[2] * dv1) * inv, |
| 459 | ] |
| 460 | } else { |
| 461 | e1 |
| 462 | }; |
| 463 | for idx in [i0, i1, i2] { |
| 464 | tangents[idx][0] += t_tri[0]; |
| 465 | tangents[idx][1] += t_tri[1]; |
| 466 | tangents[idx][2] += t_tri[2]; |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | for (vi, v) in verts.iter().enumerate() { |
| 471 | let wp = xform_point(dm.world, v.pos); |
| 472 | let wn = xform_normal(dm.world, v.normal); |
| 473 | let wt = xform_vector(dm.world, tangents[vi]); |
| 474 | let k = key(wp); |
| 475 | if let Some(acc) = table.get_mut(&k) { |
| 476 | acc.normal[0] += wn[0]; |
| 477 | acc.normal[1] += wn[1]; |
| 478 | acc.normal[2] += wn[2]; |
| 479 | acc.tangent[0] += wt[0]; |
| 480 | acc.tangent[1] += wt[1]; |
| 481 | acc.tangent[2] += wt[2]; |
| 482 | } else { |
| 483 | order.push(k); |
| 484 | table.insert(k, Accum { pos: wp, normal: wn, tangent: wt }); |
| 485 | } |
| 486 | } |
| 487 | } |
| 488 | |
| 489 | let mut out = Vec::with_capacity((order.len() / stride + 1).min(max_points)); |
| 490 | for (idx, k) in order.into_iter().enumerate() { |
| 491 | if idx % stride != 0 { |
| 492 | continue; |
| 493 | } |
| 494 | if out.len() >= max_points { |
| 495 | break; |
| 496 | } |
| 497 | let acc = &table[&k]; |
| 498 | let n = vec3_norm(acc.normal).unwrap_or([0.0, 0.0, 1.0]); |
| 499 | // Gram-Schmidt orthogonalize tangent against normal; fallback when degenerate. |
| 500 | let t_proj = [ |
| 501 | acc.tangent[0] - n[0] * vec3_dot(acc.tangent, n), |
| 502 | acc.tangent[1] - n[1] * vec3_dot(acc.tangent, n), |
| 503 | acc.tangent[2] - n[2] * vec3_dot(acc.tangent, n), |
| 504 | ]; |
| 505 | let t = vec3_norm(t_proj).unwrap_or_else(|| { |
| 506 | let up = if n[1].abs() > 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; |
| 507 | vec3_norm(vec3_cross(up, n)).unwrap_or([1.0, 0.0, 0.0]) |
| 508 | }); |
| 509 | let b = vec3_norm(vec3_cross(n, t)).unwrap_or([0.0, 1.0, 0.0]); |
| 510 | out.push(ReplicatePoint { pos: acc.pos, normal: n, tangent: t, bitangent: b }); |
| 511 | } |
| 512 | out |
| 513 | } |
| 514 | |
| 515 | /// Builds the placement matrix for a destination point according to `Replicate3D.Alignment`: |
| 516 | /// - `0`: Not aligned (translation only) |
| 517 | /// - `1`: Aligned (aligns local `+Z` to destination vertex normal) |
| 518 | /// - `2`: TBN Aligned (aligns local X/Y/Z to destination vertex T/B/N frame) |
| 519 | pub fn replicate_alignment_matrix(pt: &ReplicatePoint, alignment: i32) -> Mat4 { |
| 520 | match alignment { |
| 521 | 1 => { |
| 522 | let z = pt.normal; |
| 523 | let up = if z[1].abs() > 0.99 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] }; |
| 524 | let x = vec3_norm(vec3_cross(up, z)).unwrap_or([1.0, 0.0, 0.0]); |
| 525 | let y = vec3_cross(z, x); |
| 526 | [ |
| 527 | x[0], x[1], x[2], 0.0, |
| 528 | y[0], y[1], y[2], 0.0, |
| 529 | z[0], z[1], z[2], 0.0, |
| 530 | pt.pos[0], pt.pos[1], pt.pos[2], 1.0, |
| 531 | ] |
| 532 | } |
| 533 | 2 => { |
| 534 | let x = pt.tangent; |
| 535 | let y = pt.bitangent; |
| 536 | let z = pt.normal; |
| 537 | [ |
| 538 | x[0], x[1], x[2], 0.0, |
| 539 | y[0], y[1], y[2], 0.0, |
| 540 | z[0], z[1], z[2], 0.0, |
| 541 | pt.pos[0], pt.pos[1], pt.pos[2], 1.0, |
| 542 | ] |
| 543 | } |
| 544 | _ => mat4_translate(pt.pos[0], pt.pos[1], pt.pos[2]), |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | /// Evaluated parameters for a `Replicate3D` node. |
| 549 | #[derive(Clone, Debug)] |
| 550 | pub struct Replicate3DParams { |
| 551 | pub random_input: bool, |
| 552 | /// `0 = Not aligned`, `1 = Aligned`, `2 = TBN Aligned`. |
| 553 | pub alignment: i32, |
| 554 | pub base_xform: Mat4, |
| 555 | pub random_seed: u64, |
| 556 | pub jitter_prob: f32, |
| 557 | pub jitter_translate: [f32; 3], |
| 558 | pub jitter_rotate: [f32; 3], |
| 559 | pub jitter_pivot: [f32; 3], |
| 560 | pub jitter_scale: [f32; 3], |
| 561 | } |
| 562 | |
| 563 | fn splitmix64_signed(mut x: u64) -> f32 { |
| 564 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 565 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 566 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 567 | x ^= x >> 31; |
| 568 | ((x >> 40) as f32 / ((1u64 << 24) as f32)) - 0.5 |
| 569 | } |
| 570 | |
| 571 | fn splitmix64_u64(mut x: u64) -> u64 { |
| 572 | x = x.wrapping_add(0x9E37_79B9_7F4A_7C15); |
| 573 | x = (x ^ (x >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9); |
| 574 | x = (x ^ (x >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB); |
| 575 | x ^ (x >> 31) |
| 576 | } |
| 577 | |
| 578 | /// Instantiates `source_templates` (`Input1..InputN`) onto `dest_points` while honoring |
| 579 | /// `MAX_SCENE_MESHES` so large destination meshes never exhaust memory. |
| 580 | pub fn replicate_meshes( |
| 581 | dest_points: &[ReplicatePoint], |
| 582 | source_templates: &[Vec<MeshInstance>], |
| 583 | node_world: Mat4, |
| 584 | params: &Replicate3DParams, |
| 585 | out_meshes: &mut Vec<MeshInstance>, |
| 586 | ) { |
| 587 | if dest_points.is_empty() || source_templates.is_empty() { |
| 588 | return; |
| 589 | } |
| 590 | let has_jitter = params.jitter_translate.iter().any(|v| v.abs() > 1e-5) |
| 591 | || params.jitter_rotate.iter().any(|v| v.abs() > 1e-5) |
| 592 | || params.jitter_pivot.iter().any(|v| v.abs() > 1e-5) |
| 593 | || params.jitter_scale.iter().any(|v| v.abs() > 1e-5); |
| 594 | |
| 595 | for (idx, pt) in dest_points.iter().enumerate() { |
| 596 | if out_meshes.len() >= MAX_SCENE_MESHES { |
| 597 | break; |
| 598 | } |
| 599 | let s = params |
| 600 | .random_seed |
| 601 | .wrapping_mul(6_364_136_223_846_793_005) |
| 602 | .wrapping_add((idx as u64).wrapping_mul(1_442_695_040_888_963_407)); |
| 603 | let tpl_idx = if params.random_input { |
| 604 | (splitmix64_u64(s ^ 17) as usize) % source_templates.len() |
| 605 | } else { |
| 606 | idx % source_templates.len() |
| 607 | }; |
| 608 | let template = &source_templates[tpl_idx]; |
| 609 | if template.is_empty() { |
| 610 | continue; |
| 611 | } |
| 612 | |
| 613 | let place = replicate_alignment_matrix(pt, params.alignment); |
| 614 | let mut inst_m = mat4_mul(node_world, mat4_mul(place, params.base_xform)); |
| 615 | if has_jitter && (params.jitter_prob >= 0.9999 || (splitmix64_signed(s ^ 13) + 0.5) <= params.jitter_prob) { |
| 616 | let tx = splitmix64_signed(s ^ 1) * params.jitter_translate[0]; |
| 617 | let ty = splitmix64_signed(s ^ 2) * params.jitter_translate[1]; |
| 618 | let tz = splitmix64_signed(s ^ 3) * params.jitter_translate[2]; |
| 619 | let rx = (splitmix64_signed(s ^ 4) * params.jitter_rotate[0]).to_radians(); |
| 620 | let ry = (splitmix64_signed(s ^ 5) * params.jitter_rotate[1]).to_radians(); |
| 621 | let rz = (splitmix64_signed(s ^ 6) * params.jitter_rotate[2]).to_radians(); |
| 622 | let sx = (1.0 + splitmix64_signed(s ^ 7) * params.jitter_scale[0]).max(1e-4); |
| 623 | let sy = (1.0 + splitmix64_signed(s ^ 8) * params.jitter_scale[1]).max(1e-4); |
| 624 | let sz = (1.0 + splitmix64_signed(s ^ 9) * params.jitter_scale[2]).max(1e-4); |
| 625 | let px = splitmix64_signed(s ^ 10) * params.jitter_pivot[0]; |
| 626 | let py = splitmix64_signed(s ^ 11) * params.jitter_pivot[1]; |
| 627 | let pz = splitmix64_signed(s ^ 12) * params.jitter_pivot[2]; |
| 628 | let rot = mat4_mul(mat4_rot_z(rz), mat4_mul(mat4_rot_y(ry), mat4_rot_x(rx))); |
| 629 | let jm = mat4_mul( |
| 630 | mat4_translate(tx + px, ty + py, tz + pz), |
| 631 | mat4_mul(rot, mat4_mul(mat4_scale(sx, sy, sz), mat4_translate(-px, -py, -pz))), |
| 632 | ); |
| 633 | inst_m = mat4_mul(inst_m, jm); |
| 634 | } |
| 635 | |
| 636 | for src_m in template { |
| 637 | if out_meshes.len() >= MAX_SCENE_MESHES { |
| 638 | break; |
| 639 | } |
| 640 | let mut cloned = src_m.clone(); |
| 641 | cloned.world = mat4_mul(inst_m, src_m.world); |
| 642 | out_meshes.push(cloned); |
| 643 | } |
| 644 | } |
| 645 | } |
| 646 | |
| 647 | #[cfg(test)] |
| 648 | mod tests { |
| 649 | use super::*; |
| 650 | use crate::scene3d::math::mat4_identity; |
| 651 | use crate::scene3d::MaterialFx; |
| 652 | |
| 653 | fn dummy_mesh(shape: ShapeKind, world: Mat4) -> MeshInstance { |
| 654 | MeshInstance { |
| 655 | world, |
| 656 | shape: ShapeKind::WithMaterialFx { |
| 657 | inner: Box::new(shape), |
| 658 | fx: MaterialFx::default(), |
| 659 | }, |
| 660 | material_node: None, |
| 661 | bump_node: None, |
| 662 | text3d: None, |
| 663 | diffuse_col: [1.0, 1.0, 1.0, 1.0], |
| 664 | specular_col: [1.0, 1.0, 1.0], |
| 665 | specular_intensity: 1.0, |
| 666 | specular_exponent: 50.0, |
| 667 | affected_by_lights: true, |
| 668 | casts_shadow: true, |
| 669 | receives_shadows: true, |
| 670 | flip_normals: false, |
| 671 | displace: None, |
| 672 | } |
| 673 | } |
| 674 | |
| 675 | #[test] |
| 676 | fn bender_bend_curves_plane_and_updates_normals() { |
| 677 | 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); |
| 679 | let params = Bender3DParams { |
| 680 | mode: BenderMode::Bend, |
| 681 | amount: 1.0, |
| 682 | axis: 1, // Y axis |
| 683 | angle_deg: 0.0, |
| 684 | center: 0.5, |
| 685 | range_min: 0.0, |
| 686 | range_max: 1.0, |
| 687 | group: false, |
| 688 | }; |
| 689 | deform_mesh_vertices(&mut verts, &idx, &params, None); |
| 690 | // Plane was originally flat at z=0 with normal +Z; bending around Y along X curls X into a circle |
| 691 | // and tilts top/bottom vertices in X while keeping finite unit normals. |
| 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; |
| 693 | assert!(top_x > 0.2, "top edge should bend toward +X, got {top_x}"); |
| 694 | assert!(verts.iter().all(|v| { |
| 695 | let l = vec3_dot(v.normal, v.normal).sqrt(); |
| 696 | l.is_finite() && (l - 1.0).abs() < 1e-3 |
| 697 | })); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn bender_taper_twist_shear_and_range_clamp() { |
| 702 | let shape = ShapeKind::Plane { width: 2.0, height: 2.0, sub_w: 4, sub_h: 4 }; |
| 703 | |
| 704 | // Taper: top (+Y) expands, bottom (-Y) shrinks. |
| 705 | let (mut v_taper, idx) = build_shape_mesh(&shape, 1.0); |
| 706 | deform_mesh_vertices(&mut v_taper, &idx, &Bender3DParams { |
| 707 | mode: BenderMode::Taper, |
| 708 | amount: 0.5, |
| 709 | axis: 1, |
| 710 | center: 0.5, |
| 711 | ..Default::default() |
| 712 | }, None); |
| 713 | let max_x_top = v_taper.iter().filter(|v| v.pos[1] > 0.9).map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 714 | let max_x_bot = v_taper.iter().filter(|v| v.pos[1] < -0.9).map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 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}"); |
| 716 | |
| 717 | // Twist: rotates corners out of z=0 plane. |
| 718 | let (mut v_twist, idx) = build_shape_mesh(&shape, 1.0); |
| 719 | deform_mesh_vertices(&mut v_twist, &idx, &Bender3DParams { |
| 720 | mode: BenderMode::Twist, |
| 721 | amount: 0.5, |
| 722 | axis: 1, |
| 723 | center: 0.5, |
| 724 | ..Default::default() |
| 725 | }, None); |
| 726 | let max_z = v_twist.iter().map(|v| v.pos[2].abs()).fold(0.0_f32, f32::max); |
| 727 | assert!(max_z > 0.5, "twist should rotate vertices out of XY plane, max_z={max_z}"); |
| 728 | |
| 729 | // 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); |
| 731 | deform_mesh_vertices(&mut v_shear, &idx, &Bender3DParams { |
| 732 | mode: BenderMode::Shear, |
| 733 | amount: 1.0, |
| 734 | axis: 1, |
| 735 | center: 0.5, |
| 736 | range_min: 0.5, |
| 737 | range_max: 1.0, |
| 738 | ..Default::default() |
| 739 | }, 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]; |
| 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]; |
| 742 | 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}"); |
| 744 | } |
| 745 | |
| 746 | #[test] |
| 747 | fn bender_group_mode_deforms_multiple_meshes_in_shared_bounds() { |
| 748 | let mut meshes = vec![ |
| 749 | dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, -1.0, 0.0)), |
| 750 | dummy_mesh(ShapeKind::Cube { width: 1.0, sub: 2, faces: 0b11_1111 }, mat4_translate(0.0, 1.0, 0.0)), |
| 751 | ]; |
| 752 | apply_bender_to_meshes( |
| 753 | &mut meshes, |
| 754 | mat4_identity(), |
| 755 | &Bender3DParams { |
| 756 | mode: BenderMode::Taper, |
| 757 | amount: 0.5, |
| 758 | axis: 1, |
| 759 | center: 0.5, |
| 760 | group: true, |
| 761 | ..Default::default() |
| 762 | }, |
| 763 | |_| 1.0, |
| 764 | ); |
| 765 | let ShapeKind::CustomMesh(v0) = meshes[0].shape.base_shape() else { panic!("expected custom mesh") }; |
| 766 | let ShapeKind::CustomMesh(v1) = meshes[1].shape.base_shape() else { panic!("expected custom mesh") }; |
| 767 | let bot_w = v0.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 768 | let top_w = v1.iter().map(|v| v.pos[0].abs()).fold(0.0_f32, f32::max); |
| 769 | assert!(top_w > bot_w * 1.4, "group taper should widen upper cube relative to lower cube: {top_w} vs {bot_w}"); |
| 770 | } |
| 771 | |
| 772 | #[test] |
| 773 | fn replicate_extracts_unique_vertices_aligns_normals_and_respects_cap() { |
| 774 | // 1x1 subdivided cube has 8 unique corner vertices (36 triangle-soup vertices across 6 faces). |
| 775 | let dest = vec![dummy_mesh(ShapeKind::Cube { width: 2.0, sub: 1, faces: 0b11_1111 }, mat4_identity())]; |
| 776 | let pts = extract_replicate_points(&dest, 1, MAX_SCENE_MESHES); |
| 777 | assert_eq!(pts.len(), 8, "cube with sub=1 should deduplicate to 8 corner points"); |
| 778 | for pt in &pts { |
| 779 | // Corner normal should point radially outward along pos. |
| 780 | assert!(vec3_dot(pt.pos, pt.normal) > 0.5, "corner normal should point outward: {pt:?}"); |
| 781 | } |
| 782 | |
| 783 | let src_tpl = vec![vec![dummy_mesh(ShapeKind::Plane { width: 0.2, height: 0.2, sub_w: 1, sub_h: 1 }, mat4_identity())]]; |
| 784 | let mut out = Vec::new(); |
| 785 | let params = Replicate3DParams { |
| 786 | random_input: false, |
| 787 | alignment: 1, |
| 788 | base_xform: mat4_identity(), |
| 789 | random_seed: 0, |
| 790 | jitter_prob: 1.0, |
| 791 | jitter_translate: [0.0; 3], |
| 792 | jitter_rotate: [0.0; 3], |
| 793 | jitter_pivot: [0.0; 3], |
| 794 | jitter_scale: [0.0; 3], |
| 795 | }; |
| 796 | replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut out); |
| 797 | assert_eq!(out.len(), 8); |
| 798 | // Aligned mode aligns local +Z (column 2 of world) with destination normal. |
| 799 | let z_col = [out[0].world[8], out[0].world[9], out[0].world[10]]; |
| 800 | assert!(vec3_dot(z_col, pts[0].normal) > 0.99, "aligned +Z should match vertex normal"); |
| 801 | |
| 802 | // Cap enforcement: pre-fill close to MAX_SCENE_MESHES and verify we never exceed it. |
| 803 | let mut capped = vec![dummy_mesh(ShapeKind::Plane { width: 0.1, height: 0.1, sub_w: 1, sub_h: 1 }, mat4_identity()); MAX_SCENE_MESHES - 3]; |
| 804 | replicate_meshes(&pts, &src_tpl, mat4_identity(), &params, &mut capped); |
| 805 | assert_eq!(capped.len(), MAX_SCENE_MESHES, "must strictly enforce MAX_SCENE_MESHES cap"); |
| 806 | } |
| 807 | } |