Skip to main content

euv_core/game/algorithms/kinematics/
impl.rs

1use super::*;
2
3/// Analytic 2-Bone, FABRIK, and cone-constrained CCD inverse kinematics implementations for `IkSolver3D`.
4impl IkSolver3D {
5    /// Solves exact analytic 2-bone IK with a pole vector controlling the knee/elbow bend plane.
6    ///
7    /// # Arguments
8    ///
9    /// - `Vec3` - Root joint world position (hip or shoulder).
10    /// - `f32` - Upper bone segment length.
11    /// - `f32` - Lower bone segment length.
12    /// - `Vec3` - Desired end-effector target position.
13    /// - `Vec3` - World-space pole vector hint controlling knee/elbow orientation.
14    ///
15    /// # Returns
16    ///
17    /// - `IkTwoBoneResult` - Solved mid-joint, end-effector, bone rotations, and residual error.
18    #[must_use]
19    pub fn solve_two_bone(
20        root: Vec3,
21        upper_len: f32,
22        lower_len: f32,
23        target: Vec3,
24        pole_target: Vec3,
25    ) -> IkTwoBoneResult {
26        let l1: f32 = upper_len.abs().max(1e-4);
27        let l2: f32 = lower_len.abs().max(1e-4);
28        let to_target: Vec3 = target.sub(root);
29        let raw_dist: f32 = to_target.length();
30        let target_dir: Vec3 = if raw_dist > 1e-6 {
31            to_target.scale(1.0 / raw_dist)
32        } else {
33            let pole_hint: Vec3 = pole_target.sub(root);
34            if pole_hint.length_sq() > 1e-10 {
35                pole_hint.normalize()
36            } else {
37                Vec3::new(1.0, 0.0, 0.0)
38            }
39        };
40        let min_reach: f32 = (l1 - l2).abs();
41        let max_reach: f32 = l1 + l2;
42        let clamped_dist: f32 = if max_reach > min_reach + 2e-5 {
43            raw_dist.clamp(min_reach + 1e-5, max_reach - 1e-5)
44        } else {
45            max_reach
46        };
47        let cos_alpha: f32 = ((l1 * l1 + clamped_dist * clamped_dist - l2 * l2)
48            / (2.0 * l1 * clamped_dist))
49            .clamp(-1.0, 1.0);
50        let sin_alpha: f32 = (1.0 - cos_alpha * cos_alpha).max(0.0).sqrt();
51        let to_pole: Vec3 = pole_target.sub(root);
52        let proj_pole: Vec3 = to_pole.sub(target_dir.scale(to_pole.dot(target_dir)));
53        let bend_dir: Vec3 = if proj_pole.length_sq() > 1e-10 {
54            proj_pole.normalize()
55        } else {
56            let fallback: Vec3 = if target_dir.get_y().abs() < 0.9 {
57                Vec3::new(0.0, 1.0, 0.0)
58            } else {
59                Vec3::new(1.0, 0.0, 0.0)
60            };
61            target_dir.cross(fallback).normalize()
62        };
63        let joint_mid: Vec3 = root
64            .add(target_dir.scale(l1 * cos_alpha))
65            .add(bend_dir.scale(l1 * sin_alpha));
66        let lower_vec: Vec3 = target.sub(joint_mid);
67        let lower_dir: Vec3 = if lower_vec.length_sq() > 1e-12 {
68            lower_vec.normalize()
69        } else {
70            target_dir
71        };
72        let effector: Vec3 = joint_mid.add(lower_dir.scale(l2));
73        let up_axis: Vec3 = Vec3::new(0.0, 1.0, 0.0);
74        let upper_rot: Quat = kin_quat_from_to(up_axis, joint_mid.sub(root).normalize());
75        let lower_rot: Quat = kin_quat_from_to(up_axis, lower_dir);
76        let error: f32 = effector.sub(target).length();
77        IkTwoBoneResult::new(
78            joint_mid,
79            effector,
80            upper_rot,
81            lower_rot,
82            error,
83            error <= 1e-3,
84        )
85    }
86
87    /// Solves a multi-bone chain in place using FABRIK (Forward And Backward Reaching IK).
88    ///
89    /// # Arguments
90    ///
91    /// - `&mut [Vec3]` - Mutable world-space joint positions (`len >= 2`; index `0` stays pinned).
92    /// - `&[f32]` - Segment lengths of length `positions.len() - 1`.
93    /// - `Vec3` - Desired end-effector target position.
94    /// - `f32` - Reach convergence tolerance in world units.
95    /// - `usize` - Maximum FABRIK forward-backward iterations.
96    ///
97    /// # Returns
98    ///
99    /// - `IkChainResult` - Executed iteration count, residual error, and reach status.
100    pub fn solve_fabrik(
101        positions: &mut [Vec3],
102        lengths: &[f32],
103        target: Vec3,
104        tolerance: f32,
105        max_iterations: usize,
106    ) -> IkChainResult {
107        let n: usize = positions.len();
108        if n < 2 || lengths.len() + 1 < n {
109            return IkChainResult::new(0, 0.0, false);
110        }
111        let tol: f32 = if tolerance.is_finite() && tolerance > 0.0 {
112            tolerance
113        } else {
114            1e-4
115        };
116        let root: Vec3 = positions[0];
117        let mut total_len: f32 = 0.0;
118        for &len in &lengths[..(n - 1)] {
119            total_len += len.abs();
120        }
121        let root_to_target: Vec3 = target.sub(root);
122        let dist_root_target: f32 = root_to_target.length();
123        if dist_root_target >= total_len {
124            let dir: Vec3 = if dist_root_target > 1e-6 {
125                root_to_target.scale(1.0 / dist_root_target)
126            } else {
127                Vec3::new(1.0, 0.0, 0.0)
128            };
129            for i in 0..(n - 1) {
130                positions[i + 1] = positions[i].add(dir.scale(lengths[i].abs()));
131            }
132            let err: f32 = positions[n - 1].sub(target).length();
133            return IkChainResult::new(1, err, err <= tol);
134        }
135        let mut iterations: usize = 0;
136        let max_iters: usize = max_iterations.max(1);
137        for iter in 0..max_iters {
138            let cur_err: f32 = positions[n - 1].sub(target).length();
139            if cur_err <= tol {
140                return IkChainResult::new(iter, cur_err, true);
141            }
142            iterations = iter + 1;
143            positions[n - 1] = target;
144            for i in (0..(n - 1)).rev() {
145                let seg: Vec3 = positions[i].sub(positions[i + 1]);
146                let dir: Vec3 = if seg.length_sq() > 1e-12 {
147                    seg.normalize()
148                } else {
149                    Vec3::new(0.0, 1.0, 0.0)
150                };
151                positions[i] = positions[i + 1].add(dir.scale(lengths[i].abs()));
152            }
153            positions[0] = root;
154            for i in 0..(n - 1) {
155                let seg: Vec3 = positions[i + 1].sub(positions[i]);
156                let dir: Vec3 = if seg.length_sq() > 1e-12 {
157                    seg.normalize()
158                } else {
159                    Vec3::new(0.0, 1.0, 0.0)
160                };
161                positions[i + 1] = positions[i].add(dir.scale(lengths[i].abs()));
162            }
163        }
164        let final_err: f32 = positions[n - 1].sub(target).length();
165        IkChainResult::new(iterations, final_err, final_err <= tol)
166    }
167
168    /// Solves a multi-bone chain in place using Cyclic Coordinate Descent (CCD) with angular cone limits.
169    ///
170    /// # Arguments
171    ///
172    /// - `&mut [Vec3]` - Mutable world-space joint positions (`len >= 2`; index `0` stays pinned).
173    /// - `&[IkBoneConstraint]` - Optional angular cone constraints per joint (`0..positions.len() - 1`).
174    /// - `Vec3` - Desired end-effector target position.
175    /// - `f32` - Reach convergence tolerance in world units.
176    /// - `usize` - Maximum CCD sweep iterations.
177    ///
178    /// # Returns
179    ///
180    /// - `IkChainResult` - Executed iteration count, residual error, and reach status.
181    pub fn solve_ccd(
182        positions: &mut [Vec3],
183        constraints: &[IkBoneConstraint],
184        target: Vec3,
185        tolerance: f32,
186        max_iterations: usize,
187    ) -> IkChainResult {
188        let n: usize = positions.len();
189        if n < 2 {
190            return IkChainResult::new(0, 0.0, false);
191        }
192        let tol: f32 = if tolerance.is_finite() && tolerance > 0.0 {
193            tolerance
194        } else {
195            1e-4
196        };
197        let max_iters: usize = max_iterations.max(1);
198        let mut iterations: usize = 0;
199        for iter in 0..max_iters {
200            let cur_err: f32 = positions[n - 1].sub(target).length();
201            if cur_err <= tol {
202                return IkChainResult::new(iter, cur_err, true);
203            }
204            iterations = iter + 1;
205            for j in (0..(n - 1)).rev() {
206                let pivot: Vec3 = positions[j];
207                let to_eff: Vec3 = positions[n - 1].sub(pivot);
208                let to_tgt: Vec3 = target.sub(pivot);
209                if to_eff.length_sq() <= 1e-12 || to_tgt.length_sq() <= 1e-12 {
210                    continue;
211                }
212                let step_rot: Quat = kin_quat_from_to(to_eff.normalize(), to_tgt.normalize());
213                for pos in &mut positions[(j + 1)..n] {
214                    let rel: Vec3 = pos.sub(pivot);
215                    *pos = pivot.add(step_rot.rotate_vec3(rel));
216                }
217                if let Some(constraint) = constraints.get(j) {
218                    let max_ang: f32 = constraint.get_max_cone_angle_rad().clamp(0.0, PI);
219                    let ref_axis: Vec3 = if j == 0 {
220                        let axis: Vec3 = constraint.get_reference_axis();
221                        if axis.length_sq() > 1e-10 {
222                            axis.normalize()
223                        } else {
224                            Vec3::new(0.0, 1.0, 0.0)
225                        }
226                    } else {
227                        let parent_seg: Vec3 = pivot.sub(positions[j - 1]);
228                        if parent_seg.length_sq() > 1e-10 {
229                            parent_seg.normalize()
230                        } else {
231                            Vec3::new(0.0, 1.0, 0.0)
232                        }
233                    };
234                    let bone_seg: Vec3 = positions[j + 1].sub(pivot);
235                    if bone_seg.length_sq() > 1e-12 {
236                        let bone_dir: Vec3 = bone_seg.normalize();
237                        let angle: f32 = bone_dir.dot(ref_axis).clamp(-1.0, 1.0).acos();
238                        if angle > max_ang {
239                            let lateral: Vec3 =
240                                bone_dir.sub(ref_axis.scale(bone_dir.dot(ref_axis)));
241                            let lat_dir: Vec3 = if lateral.length_sq() > 1e-10 {
242                                lateral.normalize()
243                            } else {
244                                let fallback: Vec3 = if ref_axis.get_y().abs() < 0.9 {
245                                    Vec3::new(0.0, 1.0, 0.0)
246                                } else {
247                                    Vec3::new(1.0, 0.0, 0.0)
248                                };
249                                ref_axis.cross(fallback).normalize()
250                            };
251                            let clamped_dir: Vec3 = ref_axis
252                                .scale(max_ang.cos())
253                                .add(lat_dir.scale(max_ang.sin()))
254                                .normalize();
255                            let clamp_rot: Quat = kin_quat_from_to(bone_dir, clamped_dir);
256                            for pos in &mut positions[(j + 1)..n] {
257                                let rel: Vec3 = pos.sub(pivot);
258                                *pos = pivot.add(clamp_rot.rotate_vec3(rel));
259                            }
260                        }
261                    }
262                }
263            }
264        }
265        let final_err: f32 = positions[n - 1].sub(target).length();
266        IkChainResult::new(iterations, final_err, final_err <= tol)
267    }
268}
269
270/// Support mapping and translation helpers for `ConvexShape3D`.
271impl ConvexShape3D {
272    /// Returns the approximate geometric center of this convex shape.
273    ///
274    /// # Returns
275    ///
276    /// - `Vec3` - World-space reference center.
277    #[must_use]
278    pub fn center_hint(&self) -> Vec3 {
279        match self {
280            Self::Sphere { center, .. }
281            | Self::Box { center, .. }
282            | Self::Capsule { center, .. }
283            | Self::Cylinder { center, .. } => *center,
284            Self::ConvexHull {
285                vertices,
286                position,
287                rotation,
288            } => {
289                if vertices.is_empty() {
290                    return *position;
291                }
292                let mut sum: Vec3 = Vec3::zero();
293                for &v in vertices {
294                    sum = sum.add(v);
295                }
296                let avg: Vec3 = sum.scale(1.0 / (vertices.len() as f32));
297                position.add(rotation.rotate_vec3(avg))
298            }
299        }
300    }
301
302    /// Returns a copy of this convex shape translated by `delta` in world space.
303    ///
304    /// # Arguments
305    ///
306    /// - `Vec3` - World-space translation offset.
307    ///
308    /// # Returns
309    ///
310    /// - `Self` - Translated convex shape.
311    #[must_use]
312    pub fn translated(&self, delta: Vec3) -> Self {
313        match self {
314            Self::Sphere { center, radius } => Self::Sphere {
315                center: center.add(delta),
316                radius: *radius,
317            },
318            Self::Box {
319                center,
320                half_extents,
321                rotation,
322            } => Self::Box {
323                center: center.add(delta),
324                half_extents: *half_extents,
325                rotation: *rotation,
326            },
327            Self::Capsule {
328                center,
329                half_height,
330                radius,
331                rotation,
332            } => Self::Capsule {
333                center: center.add(delta),
334                half_height: *half_height,
335                radius: *radius,
336                rotation: *rotation,
337            },
338            Self::Cylinder {
339                center,
340                half_height,
341                radius,
342                rotation,
343            } => Self::Cylinder {
344                center: center.add(delta),
345                half_height: *half_height,
346                radius: *radius,
347                rotation: *rotation,
348            },
349            Self::ConvexHull {
350                vertices,
351                position,
352                rotation,
353            } => Self::ConvexHull {
354                vertices: vertices.clone(),
355                position: position.add(delta),
356                rotation: *rotation,
357            },
358        }
359    }
360
361    /// Evaluates the furthest world-space support point of this shape along `direction`.
362    ///
363    /// # Arguments
364    ///
365    /// - `Vec3` - World-space search direction.
366    ///
367    /// # Returns
368    ///
369    /// - `Vec3` - Support point maximizing `point ยท direction`.
370    #[must_use]
371    pub fn support(&self, direction: Vec3) -> Vec3 {
372        let dir: Vec3 = if direction.length_sq() > 1e-12 {
373            direction
374        } else {
375            Vec3::new(1.0, 0.0, 0.0)
376        };
377        match self {
378            Self::Sphere { center, radius } => center.add(dir.normalize().scale(radius.max(0.0))),
379            Self::Box {
380                center,
381                half_extents,
382                rotation,
383            } => {
384                let unit_rot: Quat = rotation.normalize();
385                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
386                let local_pt: Vec3 = Vec3::new(
387                    if local_dir.get_x() >= 0.0 {
388                        half_extents.get_x().abs()
389                    } else {
390                        -half_extents.get_x().abs()
391                    },
392                    if local_dir.get_y() >= 0.0 {
393                        half_extents.get_y().abs()
394                    } else {
395                        -half_extents.get_y().abs()
396                    },
397                    if local_dir.get_z() >= 0.0 {
398                        half_extents.get_z().abs()
399                    } else {
400                        -half_extents.get_z().abs()
401                    },
402                );
403                center.add(unit_rot.rotate_vec3(local_pt))
404            }
405            Self::Capsule {
406                center,
407                half_height,
408                radius,
409                rotation,
410            } => {
411                let unit_rot: Quat = rotation.normalize();
412                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
413                let hh: f32 = half_height.abs();
414                let tip_y: f32 = if local_dir.get_y() >= 0.0 { hh } else { -hh };
415                let spine_pt: Vec3 = center.add(unit_rot.rotate_vec3(Vec3::new(0.0, tip_y, 0.0)));
416                spine_pt.add(dir.normalize().scale(radius.max(0.0)))
417            }
418            Self::Cylinder {
419                center,
420                half_height,
421                radius,
422                rotation,
423            } => {
424                let unit_rot: Quat = rotation.normalize();
425                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
426                let hh: f32 = half_height.abs();
427                let r: f32 = radius.max(0.0);
428                let rad_sq: f32 =
429                    local_dir.get_x() * local_dir.get_x() + local_dir.get_z() * local_dir.get_z();
430                let (rx, rz): (f32, f32) = if rad_sq > 1e-12 {
431                    let inv: f32 = r / rad_sq.sqrt();
432                    (local_dir.get_x() * inv, local_dir.get_z() * inv)
433                } else {
434                    (r, 0.0)
435                };
436                let ry: f32 = if local_dir.get_y() >= 0.0 { hh } else { -hh };
437                center.add(unit_rot.rotate_vec3(Vec3::new(rx, ry, rz)))
438            }
439            Self::ConvexHull {
440                vertices,
441                position,
442                rotation,
443            } => {
444                if vertices.is_empty() {
445                    return *position;
446                }
447                let unit_rot: Quat = rotation.normalize();
448                let local_dir: Vec3 = unit_rot.conjugate().rotate_vec3(dir);
449                let mut best_v: Vec3 = vertices[0];
450                let mut best_dot: f32 = best_v.dot(local_dir);
451                for &v in &vertices[1..] {
452                    let d: f32 = v.dot(local_dir);
453                    if d > best_dot {
454                        best_dot = d;
455                        best_v = v;
456                    }
457                }
458                position.add(unit_rot.rotate_vec3(best_v))
459            }
460        }
461    }
462}
463
464/// 3D GJK intersection test and EPA exact penetration solver for `GjkEpaSolver3D`.
465impl GjkEpaSolver3D {
466    /// Creates a new `GjkEpaSolver3D` with pre-allocated polytope scratch buffers.
467    ///
468    /// # Returns
469    ///
470    /// - `Self` - Ready convex collision solver.
471    #[must_use]
472    pub fn new() -> Self {
473        Self {
474            scratch: GjkEpaScratch {
475                vertices: Vec::with_capacity(64),
476                faces: Vec::with_capacity(128),
477                loose_edges: Vec::with_capacity(64),
478            },
479        }
480    }
481
482    /// Runs GJK to determine intersection and leaves the enclosing simplex inside `simplex`.
483    ///
484    /// # Arguments
485    ///
486    /// - `&ConvexShape3D` - First convex shape A.
487    /// - `&ConvexShape3D` - Second convex shape B.
488    /// - `&mut Vec<Vec3>` - Reusable vertex buffer populated with the terminating simplex.
489    ///
490    /// # Returns
491    ///
492    /// - `bool` - `true` if `shape_a` and `shape_b` intersect.
493    fn run_gjk(shape_a: &ConvexShape3D, shape_b: &ConvexShape3D, simplex: &mut Vec<Vec3>) -> bool {
494        simplex.clear();
495        let initial_diff: Vec3 = shape_a.center_hint().sub(shape_b.center_hint());
496        let mut dir: Vec3 = if initial_diff.length_sq() > 1e-10 {
497            initial_diff
498        } else {
499            Vec3::new(1.0, 0.0, 0.0)
500        };
501        let first: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
502        simplex.push(first);
503        if first.length_sq() <= 1e-12 {
504            return true;
505        }
506        dir = first.scale(-1.0);
507        for _ in 0..GJK_MAX_ITERS {
508            let next_pt: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
509            if next_pt.dot(dir) <= 0.0 {
510                return false;
511            }
512            simplex.insert(0, next_pt);
513            let hit: bool = match simplex.len() {
514                2 => gjk_handle_line(simplex, &mut dir),
515                3 => gjk_handle_triangle(simplex, &mut dir),
516                4 => gjk_handle_tetrahedron(simplex, &mut dir),
517                _ => false,
518            };
519            if hit {
520                return true;
521            }
522        }
523        false
524    }
525
526    /// Expands a degenerate 1-, 2-, or 3-vertex hit simplex into a full non-degenerate tetrahedron for EPA.
527    ///
528    /// # Arguments
529    ///
530    /// - `&ConvexShape3D` - First convex shape A.
531    /// - `&ConvexShape3D` - Second convex shape B.
532    /// - `&mut Vec<Vec3>` - Simplex vertices expanded to length `4` when possible.
533    ///
534    /// # Returns
535    ///
536    /// - `bool` - `true` if a non-degenerate tetrahedron was formed.
537    fn blow_up_simplex(
538        shape_a: &ConvexShape3D,
539        shape_b: &ConvexShape3D,
540        verts: &mut Vec<Vec3>,
541    ) -> bool {
542        let probe_axes: [Vec3; 6] = [
543            Vec3::new(1.0, 0.0, 0.0),
544            Vec3::new(-1.0, 0.0, 0.0),
545            Vec3::new(0.0, 1.0, 0.0),
546            Vec3::new(0.0, -1.0, 0.0),
547            Vec3::new(0.0, 0.0, 1.0),
548            Vec3::new(0.0, 0.0, -1.0),
549        ];
550        if verts.len() == 1 {
551            for &axis in &probe_axes {
552                let p: Vec3 = gjk_support_diff(shape_a, shape_b, axis);
553                if p.sub(verts[0]).length_sq() > 1e-8 {
554                    verts.push(p);
555                    break;
556                }
557            }
558        }
559        if verts.len() == 2 {
560            let line: Vec3 = verts[1].sub(verts[0]);
561            for &axis in &probe_axes {
562                let perp: Vec3 = line.cross(axis);
563                if perp.length_sq() <= 1e-10 {
564                    continue;
565                }
566                let p: Vec3 = gjk_support_diff(shape_a, shape_b, perp);
567                if line.cross(p.sub(verts[0])).length_sq() > 1e-8 {
568                    verts.push(p);
569                    break;
570                }
571            }
572        }
573        if verts.len() == 3 {
574            let normal: Vec3 = verts[1].sub(verts[0]).cross(verts[2].sub(verts[0]));
575            let candidates: [Vec3; 2] = [normal, normal.scale(-1.0)];
576            for &dir in &candidates {
577                if dir.length_sq() <= 1e-12 {
578                    continue;
579                }
580                let p: Vec3 = gjk_support_diff(shape_a, shape_b, dir);
581                if normal.dot(p.sub(verts[0])).abs() > 1e-8 {
582                    verts.push(p);
583                    break;
584                }
585            }
586        }
587        verts.len() == 4
588    }
589
590    /// Tests whether two convex 3D shapes intersect via GJK.
591    ///
592    /// # Arguments
593    ///
594    /// - `&ConvexShape3D` - First convex shape.
595    /// - `&ConvexShape3D` - Second convex shape.
596    ///
597    /// # Returns
598    ///
599    /// - `bool` - `true` when the two shapes overlap.
600    pub fn intersects(&mut self, shape_a: &ConvexShape3D, shape_b: &ConvexShape3D) -> bool {
601        let mut scratch: GjkEpaScratch = take(self.get_mut_scratch());
602        let hit: bool = Self::run_gjk(shape_a, shape_b, &mut scratch.vertices);
603        self.set_scratch(scratch);
604        hit
605    }
606
607    /// Runs GJK + EPA to compute exact minimum-translation penetration normal and depth for overlapping shapes.
608    ///
609    /// # Arguments
610    ///
611    /// - `&ConvexShape3D` - First convex shape A.
612    /// - `&ConvexShape3D` - Second convex shape B.
613    ///
614    /// # Returns
615    ///
616    /// - `Option<GjkEpaContact3D>` - MTV contact separating A from B (`A + normal * depth`), or `None` if separated.
617    pub fn solve_penetration(
618        &mut self,
619        shape_a: &ConvexShape3D,
620        shape_b: &ConvexShape3D,
621    ) -> Option<GjkEpaContact3D> {
622        let mut scratch: GjkEpaScratch = take(self.get_mut_scratch());
623        let hit: bool = Self::run_gjk(shape_a, shape_b, &mut scratch.vertices);
624        if !hit {
625            self.set_scratch(scratch);
626            return None;
627        }
628        if scratch.vertices.len() < 4
629            && !Self::blow_up_simplex(shape_a, shape_b, &mut scratch.vertices)
630        {
631            self.set_scratch(scratch);
632            return None;
633        }
634        let interior: Vec3 = scratch.vertices[0]
635            .add(scratch.vertices[1])
636            .add(scratch.vertices[2])
637            .add(scratch.vertices[3])
638            .scale(0.25);
639        scratch.faces.clear();
640        let init_tris: [(usize, usize, usize); 4] = [(0, 1, 2), (0, 2, 3), (0, 3, 1), (1, 3, 2)];
641        for &(i0, i1, i2) in &init_tris {
642            if let Some(face) = epa_make_face(&scratch.vertices, i0, i1, i2, interior) {
643                scratch.faces.push(face);
644            }
645        }
646        if scratch.faces.is_empty() {
647            self.set_scratch(scratch);
648            return None;
649        }
650        let mut best_normal: Vec3 = scratch.faces[0].normal;
651        let mut best_dist: f32 = scratch.faces[0].distance;
652        for _ in 0..EPA_MAX_ITERS {
653            let mut closest_idx: usize = 0;
654            let mut closest_dist: f32 = f32::INFINITY;
655            for (idx, face) in scratch.faces.iter().enumerate() {
656                if face.distance < closest_dist {
657                    closest_dist = face.distance;
658                    closest_idx = idx;
659                }
660            }
661            let closest: EpaFace3D = scratch.faces[closest_idx];
662            best_normal = closest.normal;
663            best_dist = closest.distance;
664            let support_pt: Vec3 = gjk_support_diff(shape_a, shape_b, closest.normal);
665            let support_dist: f32 = support_pt.dot(closest.normal);
666            if support_dist - closest.distance <= EPA_EPSILON {
667                break;
668            }
669            let mut duplicate: bool = false;
670            for &existing in &scratch.vertices {
671                if existing.sub(support_pt).length_sq() <= 1e-10 {
672                    duplicate = true;
673                    break;
674                }
675            }
676            if duplicate {
677                break;
678            }
679            let new_vert_idx: usize = scratch.vertices.len();
680            scratch.vertices.push(support_pt);
681            scratch.loose_edges.clear();
682            let mut f_idx: usize = 0;
683            while f_idx < scratch.faces.len() {
684                let face: EpaFace3D = scratch.faces[f_idx];
685                let v0: Vec3 = scratch.vertices[face.indices[0]];
686                if face.normal.dot(support_pt.sub(v0)) > 1e-6 {
687                    let edges: [(usize, usize); 3] = [
688                        (face.indices[0], face.indices[1]),
689                        (face.indices[1], face.indices[2]),
690                        (face.indices[2], face.indices[0]),
691                    ];
692                    for &(eu, ev) in &edges {
693                        if let Some(rev_pos) = scratch
694                            .loose_edges
695                            .iter()
696                            .position(|&(lu, lv): &(usize, usize)| lu == ev && lv == eu)
697                        {
698                            let _: (usize, usize) = scratch.loose_edges.swap_remove(rev_pos);
699                        } else {
700                            scratch.loose_edges.push((eu, ev));
701                        }
702                    }
703                    let _: EpaFace3D = scratch.faces.swap_remove(f_idx);
704                } else {
705                    f_idx += 1;
706                }
707            }
708            for &(eu, ev) in &scratch.loose_edges {
709                if let Some(new_face) =
710                    epa_make_face(&scratch.vertices, eu, ev, new_vert_idx, interior)
711                {
712                    scratch.faces.push(new_face);
713                }
714            }
715            if scratch.faces.is_empty() {
716                break;
717            }
718        }
719        self.set_scratch(scratch);
720        let mtv_normal: Vec3 = best_normal.scale(-1.0).normalize();
721        let depth: f32 = best_dist.max(0.0);
722        Some(GjkEpaContact3D::new(mtv_normal, depth))
723    }
724}
725
726/// Verlet / PBD cloth construction, pinning, colliders, and simulation steps for `VerletClothSolver`.
727impl VerletClothSolver {
728    /// Builds a `cols x rows` cloth grid with structural, shear, and 2-hop bend constraints.
729    ///
730    /// # Arguments
731    ///
732    /// - `usize` - Number of vertex columns (`>= 2`).
733    /// - `usize` - Number of vertex rows (`>= 2`).
734    /// - `f32` - Rest spacing between adjacent vertices.
735    /// - `Vec3` - Top-left corner world-space origin `(col = 0, row = 0)`.
736    ///
737    /// # Returns
738    ///
739    /// - `Self` - Initialized cloth solver lying in the horizontal XZ plane.
740    #[must_use]
741    pub fn new(cols: usize, rows: usize, spacing: f32, origin: Vec3) -> Self {
742        let safe_cols: usize = cols.max(2);
743        let safe_rows: usize = rows.max(2);
744        let safe_spacing: f32 = if spacing.is_finite() && spacing > 1e-4 {
745            spacing
746        } else {
747            0.25
748        };
749        let mut particles: Vec<VerletParticle3D> = Vec::with_capacity(safe_cols * safe_rows);
750        for r in 0..safe_rows {
751            for c in 0..safe_cols {
752                let pos: Vec3 = origin.add(Vec3::new(
753                    (c as f32) * safe_spacing,
754                    0.0,
755                    (r as f32) * safe_spacing,
756                ));
757                particles.push(VerletParticle3D::new(pos, pos, 1.0));
758            }
759        }
760        let mut constraints: Vec<VerletDistanceConstraint> =
761            Vec::with_capacity(safe_cols * safe_rows * 6);
762        let diag_len: f32 = safe_spacing * SQRT_2;
763        let bend_len: f32 = safe_spacing * 2.0;
764        for r in 0..safe_rows {
765            for c in 0..safe_cols {
766                let idx: usize = r * safe_cols + c;
767                if c + 1 < safe_cols {
768                    constraints.push(VerletDistanceConstraint::new(
769                        idx,
770                        idx + 1,
771                        safe_spacing,
772                        1.0,
773                    ));
774                }
775                if r + 1 < safe_rows {
776                    constraints.push(VerletDistanceConstraint::new(
777                        idx,
778                        idx + safe_cols,
779                        safe_spacing,
780                        1.0,
781                    ));
782                }
783                if c + 1 < safe_cols && r + 1 < safe_rows {
784                    constraints.push(VerletDistanceConstraint::new(
785                        idx,
786                        idx + safe_cols + 1,
787                        diag_len,
788                        0.85,
789                    ));
790                    constraints.push(VerletDistanceConstraint::new(
791                        idx + 1,
792                        idx + safe_cols,
793                        diag_len,
794                        0.85,
795                    ));
796                }
797                if c + 2 < safe_cols {
798                    constraints.push(VerletDistanceConstraint::new(idx, idx + 2, bend_len, 0.5));
799                }
800                if r + 2 < safe_rows {
801                    constraints.push(VerletDistanceConstraint::new(
802                        idx,
803                        idx + safe_cols * 2,
804                        bend_len,
805                        0.5,
806                    ));
807                }
808            }
809        }
810        Self {
811            cols: safe_cols,
812            rows: safe_rows,
813            gravity: Vec3::new(0.0, -9.81, 0.0),
814            wind: Vec3::zero(),
815            damping: VERLET_DAMPING,
816            solver_iterations: 6,
817            particles,
818            constraints,
819            sphere_colliders: Vec::new(),
820            plane_colliders: Vec::new(),
821        }
822    }
823
824    /// Permanently pins cloth vertex `(col, row)` as an immovable anchor (`inv_mass = 0.0`).
825    ///
826    /// # Arguments
827    ///
828    /// - `usize` - Column index.
829    /// - `usize` - Row index.
830    pub fn pin_particle(&mut self, col: usize, row: usize) {
831        let cols: usize = self.get_cols();
832        let rows: usize = self.get_rows();
833        if col < cols && row < rows {
834            self.get_mut_particles()[row * cols + col].set_inv_mass(0.0);
835        }
836    }
837
838    /// Registers a solid sphere collider interacting with free cloth particles.
839    ///
840    /// # Arguments
841    ///
842    /// - `VerletSphereCollider` - Sphere collider descriptor.
843    pub fn add_sphere_collider(&mut self, collider: VerletSphereCollider) {
844        self.get_mut_sphere_colliders().push(collider);
845    }
846
847    /// Registers a solid infinite plane collider interacting with free cloth particles.
848    ///
849    /// # Arguments
850    ///
851    /// - `VerletPlaneCollider` - Plane collider descriptor.
852    pub fn add_plane_collider(&mut self, collider: VerletPlaneCollider) {
853        self.get_mut_plane_colliders().push(collider);
854    }
855
856    /// Advances the cloth simulation by `dt` with zero steady-state heap allocations.
857    ///
858    /// # Arguments
859    ///
860    /// - `f32` - Simulation time step in seconds.
861    pub fn step(&mut self, dt: f32) {
862        if !dt.is_finite() || dt <= 1e-6 {
863            return;
864        }
865        let accel: Vec3 = self.get_gravity().add(self.get_wind());
866        let accel_dt2: Vec3 = accel.scale(dt * dt);
867        let damping: f32 = self.get_damping().clamp(0.0, 1.0);
868        let iterations: usize = self.get_solver_iterations();
869        let mut particles: Vec<VerletParticle3D> = take(self.get_mut_particles());
870        for particle in &mut particles {
871            if particle.get_inv_mass() <= 0.0 {
872                continue;
873            }
874            let pos: Vec3 = particle.get_position();
875            let vel: Vec3 = pos.sub(particle.get_prev_position()).scale(damping);
876            particle.set_prev_position(pos);
877            particle.set_position(pos.add(vel).add(accel_dt2));
878        }
879        verlet_project_constraints(
880            &mut particles,
881            self.get_constraints(),
882            self.get_sphere_colliders(),
883            self.get_plane_colliders(),
884            iterations,
885        );
886        self.set_particles(particles);
887    }
888}
889
890/// Verlet / PBD rope construction, pinning, colliders, and simulation steps for `VerletRopeSolver`.
891impl VerletRopeSolver {
892    /// Builds a 1D rope chain with structural distance and 2-hop bend stiffness constraints.
893    ///
894    /// # Arguments
895    ///
896    /// - `usize` - Number of particles along the rope (`>= 2`).
897    /// - `f32` - Rest length of each rope segment.
898    /// - `Vec3` - World-space starting anchor position.
899    /// - `Vec3` - Initial extension direction (normalized internally).
900    ///
901    /// # Returns
902    ///
903    /// - `Self` - Initialized rope solver.
904    #[must_use]
905    pub fn new(count: usize, segment_length: f32, start: Vec3, direction: Vec3) -> Self {
906        let safe_count: usize = count.max(2);
907        let safe_len: f32 = if segment_length.is_finite() && segment_length > 1e-4 {
908            segment_length
909        } else {
910            0.25
911        };
912        let unit_dir: Vec3 = if direction.length_sq() > 1e-10 {
913            direction.normalize()
914        } else {
915            Vec3::new(1.0, 0.0, 0.0)
916        };
917        let mut particles: Vec<VerletParticle3D> = Vec::with_capacity(safe_count);
918        for i in 0..safe_count {
919            let pos: Vec3 = start.add(unit_dir.scale((i as f32) * safe_len));
920            particles.push(VerletParticle3D::new(pos, pos, 1.0));
921        }
922        let mut constraints: Vec<VerletDistanceConstraint> = Vec::with_capacity(safe_count * 2);
923        for i in 0..(safe_count - 1) {
924            constraints.push(VerletDistanceConstraint::new(i, i + 1, safe_len, 1.0));
925        }
926        for i in 0..safe_count.saturating_sub(2) {
927            constraints.push(VerletDistanceConstraint::new(
928                i,
929                i + 2,
930                safe_len * 2.0,
931                0.35,
932            ));
933        }
934        Self {
935            gravity: Vec3::new(0.0, -9.81, 0.0),
936            wind: Vec3::zero(),
937            damping: VERLET_DAMPING,
938            solver_iterations: 8,
939            particles,
940            constraints,
941            sphere_colliders: Vec::new(),
942            plane_colliders: Vec::new(),
943        }
944    }
945
946    /// Permanently pins rope particle `index` (`inv_mass = 0.0`).
947    ///
948    /// # Arguments
949    ///
950    /// - `usize` - Particle index to pin.
951    pub fn pin_particle(&mut self, index: usize) {
952        if let Some(particle) = self.get_mut_particles().get_mut(index) {
953            particle.set_inv_mass(0.0);
954        }
955    }
956
957    /// Registers a solid sphere collider interacting with free rope particles.
958    ///
959    /// # Arguments
960    ///
961    /// - `VerletSphereCollider` - Sphere collider descriptor.
962    pub fn add_sphere_collider(&mut self, collider: VerletSphereCollider) {
963        self.get_mut_sphere_colliders().push(collider);
964    }
965
966    /// Registers a solid plane collider interacting with free rope particles.
967    ///
968    /// # Arguments
969    ///
970    /// - `VerletPlaneCollider` - Plane collider descriptor.
971    pub fn add_plane_collider(&mut self, collider: VerletPlaneCollider) {
972        self.get_mut_plane_colliders().push(collider);
973    }
974
975    /// Advances the rope simulation by `dt` with zero steady-state heap allocations.
976    ///
977    /// # Arguments
978    ///
979    /// - `f32` - Simulation time step in seconds.
980    pub fn step(&mut self, dt: f32) {
981        if !dt.is_finite() || dt <= 1e-6 {
982            return;
983        }
984        let accel: Vec3 = self.get_gravity().add(self.get_wind());
985        let accel_dt2: Vec3 = accel.scale(dt * dt);
986        let damping: f32 = self.get_damping().clamp(0.0, 1.0);
987        let iterations: usize = self.get_solver_iterations();
988        let mut particles: Vec<VerletParticle3D> = take(self.get_mut_particles());
989        for particle in &mut particles {
990            if particle.get_inv_mass() <= 0.0 {
991                continue;
992            }
993            let pos: Vec3 = particle.get_position();
994            let vel: Vec3 = pos.sub(particle.get_prev_position()).scale(damping);
995            particle.set_prev_position(pos);
996            particle.set_position(pos.add(vel).add(accel_dt2));
997        }
998        verlet_project_constraints(
999            &mut particles,
1000            self.get_constraints(),
1001            self.get_sphere_colliders(),
1002            self.get_plane_colliders(),
1003            iterations,
1004        );
1005        self.set_particles(particles);
1006    }
1007}
1008
1009/// Default settings for `CameraRigConfig`.
1010impl Default for CameraRigConfig {
1011    /// Returns balanced third-person Spring-Arm camera rig defaults.
1012    ///
1013    /// # Returns
1014    ///
1015    /// - `Self` - Default camera rig configuration.
1016    fn default() -> Self {
1017        Self {
1018            mode: CameraRigMode::SpringArm,
1019            arm_length: 6.0,
1020            arm_min_length: 0.5,
1021            pivot_offset: Vec3::new(0.0, 1.5, 0.0),
1022            position_stiffness: 10.0,
1023            rotation_stiffness: 12.0,
1024            min_pitch: -1.35,
1025            max_pitch: 1.35,
1026            eye_height: 1.7,
1027            fov_deg: 60.0,
1028            near: 0.1,
1029            far: 500.0,
1030            trauma_decay: 1.5,
1031            shake_max_offset: 0.35,
1032            shake_max_angle_rad: 0.08,
1033            shake_frequency: 14.0,
1034            spline_loop: false,
1035        }
1036    }
1037}
1038
1039/// Conversion into `Camera3D` for `CameraRigState`.
1040impl CameraRigState {
1041    /// Converts this rig output pose into a standard `Camera3D` for `euv-core` rendering.
1042    ///
1043    /// # Arguments
1044    ///
1045    /// - `f32` - Near clipping plane distance.
1046    /// - `f32` - Far clipping plane distance.
1047    ///
1048    /// # Returns
1049    ///
1050    /// - `Camera3D` - Ready perspective camera.
1051    #[must_use]
1052    pub fn to_camera3d(&self, near: f32, far: f32) -> Camera3D {
1053        let mut cam: Camera3D = Camera3D::default();
1054        cam.set_position(self.get_position());
1055        cam.set_yaw(self.get_yaw());
1056        cam.set_pitch(self.get_pitch());
1057        cam.set_fov_deg(self.get_fov_deg());
1058        cam.set_near(near);
1059        cam.set_far(far);
1060        cam
1061    }
1062}
1063
1064/// Spring-Arm, Orbit, First-Person, Catmull-Rom Spline Rail, and Perlin Trauma Shake for `CameraRig3D`.
1065impl CameraRig3D {
1066    /// Creates a new `CameraRig3D` from `config` and deterministic Perlin shake `seed`.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `CameraRigConfig` - Camera rig settings.
1071    /// - `u64` - Seed for deterministic Perlin trauma shake.
1072    ///
1073    /// # Returns
1074    ///
1075    /// - `Self` - Initialized camera rig.
1076    #[must_use]
1077    pub fn new(config: CameraRigConfig, seed: u64) -> Self {
1078        let arm_len: f32 = config
1079            .get_arm_length()
1080            .max(config.get_arm_min_length().max(0.1));
1081        let init_pos: Vec3 = Vec3::new(0.0, config.get_pivot_offset().get_y(), arm_len);
1082        let init_target: Vec3 = config.get_pivot_offset();
1083        let state: CameraRigState = CameraRigState::new(
1084            init_pos,
1085            init_target,
1086            Quat::identity(),
1087            0.0,
1088            0.0,
1089            0.0,
1090            config.get_fov_deg(),
1091        );
1092        Self {
1093            config,
1094            desired_yaw: 0.0,
1095            desired_pitch: 0.0,
1096            smooth_position: init_pos,
1097            smooth_target: init_target,
1098            smooth_yaw: 0.0,
1099            smooth_pitch: 0.0,
1100            smooth_fov_deg: config.get_fov_deg(),
1101            current_arm_length: arm_len,
1102            trauma: 0.0,
1103            shake_clock: 0.0,
1104            spline_t: 0.0,
1105            spline_points: Vec::new(),
1106            noise: NoiseField::new(seed),
1107            state,
1108        }
1109    }
1110
1111    /// Applies yaw and pitch input deltas in radians, clamping pitch inside configured limits.
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `f32` - Horizontal yaw delta in radians.
1116    /// - `f32` - Vertical pitch delta in radians.
1117    pub fn apply_look_delta(&mut self, delta_yaw: f32, delta_pitch: f32) {
1118        if delta_yaw.is_finite() {
1119            self.set_desired_yaw(self.get_desired_yaw() + delta_yaw);
1120        }
1121        if delta_pitch.is_finite() {
1122            let cfg: CameraRigConfig = self.get_config();
1123            let clamped: f32 = (self.get_desired_pitch() + delta_pitch)
1124                .clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
1125            self.set_desired_pitch(clamped);
1126        }
1127    }
1128
1129    /// Adds impact trauma clamped into `[0.0, 1.0]` to trigger smooth Perlin camera shake.
1130    ///
1131    /// # Arguments
1132    ///
1133    /// - `f32` - Non-negative trauma impulse.
1134    pub fn add_trauma(&mut self, amount: f32) {
1135        if amount.is_finite() && amount > 0.0 {
1136            self.set_trauma((self.get_trauma() + amount).clamp(0.0, 1.0));
1137        }
1138    }
1139
1140    /// Evaluates the Catmull-Rom cinematic spline rail at normalized parameter `t` in `[0.0, 1.0]`.
1141    ///
1142    /// # Arguments
1143    ///
1144    /// - `f32` - Normalized spline progress in `[0.0, 1.0]`.
1145    ///
1146    /// # Returns
1147    ///
1148    /// - `Option<CameraSplinePoint>` - Interpolated eye position, look target, and FOV.
1149    #[must_use]
1150    pub fn sample_spline(&self, t: f32) -> Option<CameraSplinePoint> {
1151        let pts: &[CameraSplinePoint] = self.get_spline_points();
1152        let n: usize = pts.len();
1153        if n == 0 {
1154            return None;
1155        }
1156        if n == 1 {
1157            return Some(pts[0]);
1158        }
1159        let looping: bool = self.get_config().get_spline_loop();
1160        let clamped_t: f32 = if looping {
1161            t.rem_euclid(1.0)
1162        } else {
1163            t.clamp(0.0, 1.0)
1164        };
1165        let seg_count: usize = if looping { n } else { n - 1 };
1166        let scaled: f32 = clamped_t * (seg_count as f32);
1167        let seg_idx: usize = (scaled.floor() as usize).min(seg_count - 1);
1168        let local_t: f32 = (scaled - (seg_idx as f32)).clamp(0.0, 1.0);
1169        let (i0, i1, i2, i3): (usize, usize, usize, usize) = if looping {
1170            (
1171                (seg_idx + n - 1) % n,
1172                seg_idx % n,
1173                (seg_idx + 1) % n,
1174                (seg_idx + 2) % n,
1175            )
1176        } else {
1177            (
1178                seg_idx.saturating_sub(1),
1179                seg_idx,
1180                (seg_idx + 1).min(n - 1),
1181                (seg_idx + 2).min(n - 1),
1182            )
1183        };
1184        let p0: CameraSplinePoint = pts[i0];
1185        let p1: CameraSplinePoint = pts[i1];
1186        let p2: CameraSplinePoint = pts[i2];
1187        let p3: CameraSplinePoint = pts[i3];
1188        Some(CameraSplinePoint::new(
1189            catmull_rom_vec3(
1190                p0.get_position(),
1191                p1.get_position(),
1192                p2.get_position(),
1193                p3.get_position(),
1194                local_t,
1195            ),
1196            catmull_rom_vec3(
1197                p0.get_look_target(),
1198                p1.get_look_target(),
1199                p2.get_look_target(),
1200                p3.get_look_target(),
1201                local_t,
1202            ),
1203            catmull_rom_f32(
1204                p0.get_fov_deg(),
1205                p1.get_fov_deg(),
1206                p2.get_fov_deg(),
1207                p3.get_fov_deg(),
1208                local_t,
1209            )
1210            .clamp(10.0, 150.0),
1211        ))
1212    }
1213
1214    /// Updates the camera rig for frame step `dt`, resolving spring-arm obstacles and Perlin trauma shake.
1215    ///
1216    /// # Arguments
1217    ///
1218    /// - `f32` - Frame delta time in seconds.
1219    /// - `Vec3` - Followed subject anchor position in world space.
1220    /// - `&[AxisAlignedBox3D]` - World geometry obstacles for spring-arm ray pullback.
1221    ///
1222    /// # Returns
1223    ///
1224    /// - `CameraRigState` - Updated world-space camera pose for this frame.
1225    pub fn update(
1226        &mut self,
1227        dt: f32,
1228        follow_target: Vec3,
1229        obstacles: &[AxisAlignedBox3D],
1230    ) -> CameraRigState {
1231        let safe_dt: f32 = if dt.is_finite() && dt > 0.0 { dt } else { 0.0 };
1232        let cfg: CameraRigConfig = self.get_config();
1233        let pos_alpha: f32 = 1.0 - (-cfg.get_position_stiffness().max(0.1) * safe_dt).exp();
1234        let rot_alpha: f32 = 1.0 - (-cfg.get_rotation_stiffness().max(0.1) * safe_dt).exp();
1235        let next_yaw: f32 =
1236            self.get_smooth_yaw() + (self.get_desired_yaw() - self.get_smooth_yaw()) * rot_alpha;
1237        let clamped_desired_pitch: f32 = self
1238            .get_desired_pitch()
1239            .clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
1240        let next_pitch: f32 =
1241            self.get_smooth_pitch() + (clamped_desired_pitch - self.get_smooth_pitch()) * rot_alpha;
1242        self.set_smooth_yaw(next_yaw);
1243        self.set_smooth_pitch(next_pitch);
1244        let cp: f32 = next_pitch.cos();
1245        let sp: f32 = next_pitch.sin();
1246        let sy: f32 = next_yaw.sin();
1247        let cy: f32 = next_yaw.cos();
1248        let forward: Vec3 = Vec3::new(sy * cp, sp, -cy * cp).normalize();
1249        let (goal_pos, goal_target, goal_fov, base_yaw, base_pitch): (Vec3, Vec3, f32, f32, f32) =
1250            match cfg.get_mode() {
1251                CameraRigMode::SpringArm => {
1252                    let pivot: Vec3 = follow_target.add(cfg.get_pivot_offset());
1253                    let arm_dir: Vec3 = forward.scale(-1.0);
1254                    let max_arm: f32 = cfg.get_arm_length().max(cfg.get_arm_min_length().max(0.1));
1255                    let min_arm: f32 = cfg.get_arm_min_length().clamp(0.05, max_arm);
1256                    let mut target_arm: f32 = max_arm;
1257                    if !obstacles.is_empty() {
1258                        let ray: Ray3D = Ray3D::new(pivot, arm_dir);
1259                        for obs in obstacles {
1260                            let hit_t: f32 = obs.intersect_ray_near(
1261                                ray.get_origin(),
1262                                ray.get_inv_direction(),
1263                                0.0,
1264                                target_arm,
1265                            );
1266                            if hit_t.is_finite() && hit_t < target_arm {
1267                                target_arm = (hit_t - CAMERA_ARM_MARGIN).clamp(min_arm, max_arm);
1268                            }
1269                        }
1270                    }
1271                    let smoothed_arm: f32 = if target_arm < self.get_current_arm_length() {
1272                        target_arm
1273                    } else {
1274                        self.get_current_arm_length()
1275                            + (target_arm - self.get_current_arm_length()) * pos_alpha
1276                    };
1277                    self.set_current_arm_length(smoothed_arm);
1278                    (
1279                        pivot.add(arm_dir.scale(smoothed_arm)),
1280                        pivot,
1281                        cfg.get_fov_deg(),
1282                        next_yaw,
1283                        next_pitch,
1284                    )
1285                }
1286                CameraRigMode::Orbit => {
1287                    let pivot: Vec3 = follow_target.add(cfg.get_pivot_offset());
1288                    let dist: f32 = cfg.get_arm_length().max(0.1);
1289                    let eye: Vec3 = pivot.sub(forward.scale(dist));
1290                    (eye, pivot, cfg.get_fov_deg(), next_yaw, next_pitch)
1291                }
1292                CameraRigMode::FirstPerson => {
1293                    let eye: Vec3 = follow_target.add(Vec3::new(0.0, cfg.get_eye_height(), 0.0));
1294                    let focus: Vec3 = eye.add(forward);
1295                    (eye, focus, cfg.get_fov_deg(), next_yaw, next_pitch)
1296                }
1297                CameraRigMode::SplineRail => {
1298                    if let Some(sample) = self.sample_spline(self.get_spline_t()) {
1299                        let look: Vec3 = sample
1300                            .get_look_target()
1301                            .sub(sample.get_position())
1302                            .normalize();
1303                        let s_yaw: f32 = look.get_x().atan2(-look.get_z());
1304                        let s_pitch: f32 = look.get_y().clamp(-1.0, 1.0).asin();
1305                        (
1306                            sample.get_position(),
1307                            sample.get_look_target(),
1308                            sample.get_fov_deg(),
1309                            s_yaw,
1310                            s_pitch,
1311                        )
1312                    } else {
1313                        (
1314                            self.get_smooth_position(),
1315                            self.get_smooth_target(),
1316                            cfg.get_fov_deg(),
1317                            next_yaw,
1318                            next_pitch,
1319                        )
1320                    }
1321                }
1322            };
1323        let next_pos: Vec3 = self.get_smooth_position().lerp(goal_pos, pos_alpha);
1324        let next_target: Vec3 = self.get_smooth_target().lerp(goal_target, pos_alpha);
1325        let next_fov: f32 =
1326            self.get_smooth_fov_deg() + (goal_fov - self.get_smooth_fov_deg()) * pos_alpha;
1327        self.set_smooth_position(next_pos);
1328        self.set_smooth_target(next_target);
1329        self.set_smooth_fov_deg(next_fov);
1330        let clock: f32 = self.get_shake_clock() + safe_dt * cfg.get_shake_frequency().max(0.1);
1331        self.set_shake_clock(clock);
1332        let cur_trauma: f32 = self.get_trauma();
1333        let shake_amp: f32 = cur_trauma * cur_trauma;
1334        let next_trauma: f32 = (cur_trauma - cfg.get_trauma_decay().max(0.0) * safe_dt).max(0.0);
1335        self.set_trauma(next_trauma);
1336        let (shake_pos, shake_yaw, shake_pitch, shake_roll): (Vec3, f32, f32, f32) =
1337            if shake_amp > 1e-6 {
1338                let max_off: f32 = cfg.get_shake_max_offset() * shake_amp;
1339                let max_ang: f32 = cfg.get_shake_max_angle_rad() * shake_amp;
1340                let noise: &NoiseField = self.get_noise();
1341                (
1342                    Vec3::new(
1343                        noise.perlin_2d(clock, 1.37) * max_off,
1344                        noise.perlin_2d(clock, 5.91) * max_off,
1345                        noise.perlin_2d(clock, 11.43) * max_off,
1346                    ),
1347                    noise.perlin_2d(clock, 17.83) * max_ang,
1348                    noise.perlin_2d(clock, 23.19) * max_ang,
1349                    noise.perlin_2d(clock, 31.67) * max_ang,
1350                )
1351            } else {
1352                (Vec3::zero(), 0.0, 0.0, 0.0)
1353            };
1354        let final_pos: Vec3 = next_pos.add(shake_pos);
1355        let final_yaw: f32 = base_yaw + shake_yaw;
1356        let final_pitch: f32 =
1357            (base_pitch + shake_pitch).clamp(cfg.get_min_pitch(), cfg.get_max_pitch());
1358        let final_rot: Quat = Quat::from_euler_yxz(final_yaw, final_pitch, shake_roll);
1359        let final_state: CameraRigState = CameraRigState::new(
1360            final_pos,
1361            next_target,
1362            final_rot,
1363            final_yaw,
1364            final_pitch,
1365            shake_roll,
1366            next_fov,
1367        );
1368        self.set_state(final_state);
1369        final_state
1370    }
1371}