Skip to main content

euv_core/game/engine3d/jianlai/
impl.rs

1use super::*;
2
3/// Index conversion, label, duration, and classification helpers for `JianlaiAction`.
4impl JianlaiAction {
5    /// Converts a zero-based UI index (`0..5`) into the matching `JianlaiAction`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Action selector index.
10    ///
11    /// # Returns
12    ///
13    /// - `Self` - Resolved Jianlai martial arts or ultimate action.
14    #[must_use]
15    pub const fn from_index(index: usize) -> Self {
16        match index {
17            1 => Self::FlowingSwordDance,
18            2 => Self::MyriadSwordsReturn,
19            3 => Self::SkyCleavingSwordQi,
20            4 => Self::CloudStepGlide,
21            _ => Self::InkStance,
22        }
23    }
24
25    /// Returns the zero-based NLA clip index for this action (`0..5`).
26    ///
27    /// # Returns
28    ///
29    /// - `usize` - Matching NLA clip index.
30    #[must_use]
31    pub const fn as_index(self) -> usize {
32        match self {
33            Self::InkStance => 0,
34            Self::FlowingSwordDance => 1,
35            Self::MyriadSwordsReturn => 2,
36            Self::SkyCleavingSwordQi => 3,
37            Self::CloudStepGlide => 4,
38        }
39    }
40
41    /// Returns the human-readable display label for this action.
42    ///
43    /// # Returns
44    ///
45    /// - `&'static str` - Action label.
46    #[must_use]
47    pub const fn label(self) -> &'static str {
48        JIANLAI_ACTION_LABELS[self.as_index()]
49    }
50
51    /// Returns the loop duration in seconds for this action clip.
52    ///
53    /// # Returns
54    ///
55    /// - `f32` - Clip duration in seconds.
56    #[must_use]
57    pub const fn duration_secs(self) -> f32 {
58        match self {
59            Self::InkStance => 3.2,
60            Self::FlowingSwordDance => 2.8,
61            Self::MyriadSwordsReturn => 4.0,
62            Self::SkyCleavingSwordQi => 3.6,
63            Self::CloudStepGlide => 3.6,
64        }
65    }
66
67    /// Returns `true` when this action is a high-energy ultimate attack (`MyriadSwordsReturn` or `SkyCleavingSwordQi`).
68    ///
69    /// # Returns
70    ///
71    /// - `bool` - Whether this action unleashes ultimate VFX.
72    #[must_use]
73    pub const fn is_ultimate(self) -> bool {
74        matches!(self, Self::MyriadSwordsReturn | Self::SkyCleavingSwordQi)
75    }
76}
77
78/// Index conversion and label helpers for `JianlaiRenderMode`.
79impl JianlaiRenderMode {
80    /// Converts a zero-based UI index (`0..6`) into the matching `JianlaiRenderMode`.
81    ///
82    /// # Arguments
83    ///
84    /// - `usize` - Render mode index.
85    ///
86    /// # Returns
87    ///
88    /// - `Self` - Resolved Blender render mode.
89    #[must_use]
90    pub const fn from_index(index: usize) -> Self {
91        match index {
92            1 => Self::CyclesPbr,
93            2 => Self::EeveeVolumetric,
94            3 => Self::SolidMatcap,
95            4 => Self::WireframeArmature,
96            5 => Self::ShaderDebugPass,
97            _ => Self::InkWashDonghua,
98        }
99    }
100
101    /// Returns the zero-based UI index for this render mode (`0..6`).
102    ///
103    /// # Returns
104    ///
105    /// - `usize` - Render mode index.
106    #[must_use]
107    pub const fn as_index(self) -> usize {
108        match self {
109            Self::InkWashDonghua => 0,
110            Self::CyclesPbr => 1,
111            Self::EeveeVolumetric => 2,
112            Self::SolidMatcap => 3,
113            Self::WireframeArmature => 4,
114            Self::ShaderDebugPass => 5,
115        }
116    }
117
118    /// Returns the display label for this render mode.
119    ///
120    /// # Returns
121    ///
122    /// - `&'static str` - Render mode display name.
123    #[must_use]
124    pub const fn label(self) -> &'static str {
125        JIANLAI_RENDER_MODE_LABELS[self.as_index()]
126    }
127}
128
129/// Index conversion and label helpers for `JianlaiDebugChannel`.
130impl JianlaiDebugChannel {
131    /// Converts a zero-based UI index (`0..4`) into the matching `JianlaiDebugChannel`.
132    ///
133    /// # Arguments
134    ///
135    /// - `usize` - Debug channel index.
136    ///
137    /// # Returns
138    ///
139    /// - `Self` - Resolved shader debug channel.
140    #[must_use]
141    pub const fn from_index(index: usize) -> Self {
142        match index {
143            1 => Self::RoughnessMetallic,
144            2 => Self::Depth,
145            3 => Self::FreestyleInkContour,
146            _ => Self::Normals,
147        }
148    }
149
150    /// Returns the zero-based index for this debug channel (`0..4`).
151    ///
152    /// # Returns
153    ///
154    /// - `usize` - Debug channel index.
155    #[must_use]
156    pub const fn as_index(self) -> usize {
157        match self {
158            Self::Normals => 0,
159            Self::RoughnessMetallic => 1,
160            Self::Depth => 2,
161            Self::FreestyleInkContour => 3,
162        }
163    }
164
165    /// Returns the display label for this debug channel.
166    ///
167    /// # Returns
168    ///
169    /// - `&'static str` - Channel label.
170    #[must_use]
171    pub const fn label(self) -> &'static str {
172        JIANLAI_DEBUG_CHANNEL_LABELS[self.as_index()]
173    }
174}
175
176/// Index conversion helpers for `JianlaiStagePreset`.
177impl JianlaiStagePreset {
178    /// Converts a zero-based preset index (`0..3`) into `JianlaiStagePreset`.
179    ///
180    /// # Arguments
181    ///
182    /// - `usize` - Preset index.
183    ///
184    /// # Returns
185    ///
186    /// - `Self` - Resolved stage preset.
187    #[must_use]
188    pub const fn from_index(index: usize) -> Self {
189        match index {
190            1 => Self::SpiritSwordGallery,
191            2 => Self::ImmortalPavilionMultiCam,
192            _ => Self::HeroInkCliff,
193        }
194    }
195
196    /// Returns the zero-based preset index (`0..3`).
197    ///
198    /// # Returns
199    ///
200    /// - `usize` - Preset index.
201    #[must_use]
202    pub const fn as_index(self) -> usize {
203        match self {
204            Self::HeroInkCliff => 0,
205            Self::SpiritSwordGallery => 1,
206            Self::ImmortalPavilionMultiCam => 2,
207        }
208    }
209}
210
211/// Camera preset lookup helpers for `JianlaiCameraPreset`.
212impl JianlaiCameraPreset {
213    /// Converts a zero-based camera preset index (`0..4`) into `JianlaiCameraPreset`.
214    ///
215    /// # Arguments
216    ///
217    /// - `usize` - Camera preset index.
218    ///
219    /// # Returns
220    ///
221    /// - `Self` - Resolved camera preset.
222    #[must_use]
223    pub const fn from_index(index: usize) -> Self {
224        match index {
225            1 => Self::LowAngleUltimate,
226            2 => Self::CliffPanorama,
227            3 => Self::SwordArrayOverhead,
228            _ => Self::HeroThreeQuarter,
229        }
230    }
231
232    /// Returns `(target, yaw_rad, pitch_rad, distance)` orbit coordinates for this camera preset.
233    ///
234    /// # Returns
235    ///
236    /// - `(Vec3, f32, f32, f32)` - Orbit target, yaw, pitch, and distance in meters.
237    #[must_use]
238    pub fn orbit_tuple(self) -> (Vec3, f32, f32, f32) {
239        match self {
240            Self::HeroThreeQuarter => (Vec3::new(-0.2, 1.32, -0.2), 0.54, -0.22, 6.2),
241            Self::LowAngleUltimate => (Vec3::new(0.0, 1.85, -0.2), 0.44, 0.14, 5.2),
242            Self::CliffPanorama => (Vec3::new(-0.8, 1.65, -2.2), 0.68, -0.28, 14.5),
243            Self::SwordArrayOverhead => (Vec3::new(0.0, 0.9, -0.5), 0.12, -0.98, 10.6),
244        }
245    }
246}
247
248/// Verlet cloth and ribbon solver initialization and simulation stepping for `JianlaiClothSim`.
249impl JianlaiClothSim {
250    /// Creates the pre-configured Verlet cloth grid (robes/hem) and three Verlet rope chains (twin hair ribbons + sword tassel).
251    ///
252    /// # Returns
253    ///
254    /// - `Self` - Ready cloth simulation bundle with body and terrace colliders.
255    #[must_use]
256    pub fn create() -> Self {
257        let mut robe_cloth: VerletClothSolver =
258            VerletClothSolver::new(5, 6, 0.16, Vec3::new(-0.32, 0.98, -0.18));
259        for col in 0..5usize {
260            robe_cloth.pin_particle(col, 0);
261        }
262        robe_cloth.add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 0.62, 0.0), 0.24));
263        robe_cloth.add_plane_collider(VerletPlaneCollider::new(Vec3::new(0.0, 1.0, 0.0), 0.04));
264        let _: &mut VerletClothSolver = robe_cloth
265            .set_gravity(Vec3::new(0.0, -7.8, -0.6))
266            .set_damping(0.96)
267            .set_solver_iterations(5);
268        let mut hair_ribbon_left: VerletRopeSolver = VerletRopeSolver::new(
269            6,
270            0.16,
271            Vec3::new(-0.08, 1.88, -0.10),
272            Vec3::new(-0.22, -0.82, -0.52),
273        );
274        hair_ribbon_left.pin_particle(0);
275        hair_ribbon_left
276            .add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 1.32, 0.0), 0.22));
277        let mut hair_ribbon_right: VerletRopeSolver = VerletRopeSolver::new(
278            6,
279            0.16,
280            Vec3::new(0.08, 1.88, -0.10),
281            Vec3::new(0.22, -0.82, -0.52),
282        );
283        hair_ribbon_right.pin_particle(0);
284        hair_ribbon_right
285            .add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 1.32, 0.0), 0.22));
286        let mut sword_tassel: VerletRopeSolver = VerletRopeSolver::new(
287            5,
288            0.09,
289            Vec3::new(0.70, 0.90, 0.20),
290            Vec3::new(0.0, -1.0, -0.2),
291        );
292        sword_tassel.pin_particle(0);
293        Self {
294            robe_cloth,
295            hair_ribbon_left,
296            hair_ribbon_right,
297            sword_tassel,
298            average_displacement_m: 0.0,
299        }
300    }
301
302    /// Steps all Verlet cloth and ribbon chains using live wind, ultimate qi blasts, and moving head/pelvis anchors.
303    ///
304    /// # Arguments
305    ///
306    /// - `f32` - Timestep in seconds.
307    /// - `Vec3` - Ambient mountain wind + sword-qi blast acceleration vector.
308    /// - `Vec3` - Live world-space pelvis position.
309    /// - `Vec3` - Live world-space head topknot position.
310    ///
311    /// # Returns
312    ///
313    /// - `(f32, f32, f32, f32)` - Derived `(hem_pitch, hem_roll, hair_l_swing, hair_r_swing)` angles in radians.
314    pub fn step_physics(
315        &mut self,
316        dt_secs: f32,
317        wind_accel: Vec3,
318        pelvis_world: Vec3,
319        head_world: Vec3,
320    ) -> (f32, f32, f32, f32) {
321        let dt: f32 = dt_secs.clamp(0.002, 0.033);
322        {
323            let cloth: &mut VerletClothSolver = self.get_mut_robe_cloth();
324            let _: &mut VerletClothSolver = cloth.set_wind(wind_accel);
325            for col in 0..5usize {
326                let offset_x: f32 = ((col as f32) - 2.0) * 0.16;
327                let anchor: Vec3 = pelvis_world.add(Vec3::new(offset_x, 0.0, -0.16));
328                if let Some(part) = cloth.get_mut_particles().get_mut(col) {
329                    let _: &mut VerletParticle3D = part
330                        .set_position(anchor)
331                        .set_prev_position(anchor)
332                        .set_inv_mass(0.0);
333                }
334            }
335            if let Some(sphere) = cloth.get_mut_sphere_colliders().first_mut() {
336                let _: &mut VerletSphereCollider =
337                    sphere.set_center(pelvis_world.add(Vec3::new(0.0, -0.32, 0.0)));
338            }
339            cloth.step(dt);
340        }
341        {
342            let left: &mut VerletRopeSolver = self.get_mut_hair_ribbon_left();
343            let _: &mut VerletRopeSolver = left.set_wind(wind_accel.scale(1.35));
344            let anchor_l: Vec3 = head_world.add(Vec3::new(-0.08, 0.12, -0.10));
345            if let Some(p0) = left.get_mut_particles().first_mut() {
346                let _: &mut VerletParticle3D = p0
347                    .set_position(anchor_l)
348                    .set_prev_position(anchor_l)
349                    .set_inv_mass(0.0);
350            }
351            left.step(dt);
352        }
353        {
354            let right: &mut VerletRopeSolver = self.get_mut_hair_ribbon_right();
355            let _: &mut VerletRopeSolver = right.set_wind(wind_accel.scale(1.25));
356            let anchor_r: Vec3 = head_world.add(Vec3::new(0.08, 0.12, -0.10));
357            if let Some(p0) = right.get_mut_particles().first_mut() {
358                let _: &mut VerletParticle3D = p0
359                    .set_position(anchor_r)
360                    .set_prev_position(anchor_r)
361                    .set_inv_mass(0.0);
362            }
363            right.step(dt);
364        }
365        {
366            let tassel: &mut VerletRopeSolver = self.get_mut_sword_tassel();
367            let _: &mut VerletRopeSolver = tassel.set_wind(wind_accel.scale(1.1));
368            tassel.step(dt);
369        }
370        let cloth_parts: &[VerletParticle3D] = self.get_robe_cloth().get_particles().as_slice();
371        let mut disp_sum: f32 = 0.0;
372        let mut z_sway: f32 = 0.0;
373        let mut x_sway: f32 = 0.0;
374        let mut free_count: f32 = 0.0;
375        for (idx, p) in cloth_parts.iter().enumerate() {
376            if idx < 5 {
377                continue;
378            }
379            let row: usize = idx / 5;
380            let col: usize = idx % 5;
381            let rest_p: Vec3 = pelvis_world.add(Vec3::new(
382                ((col as f32) - 2.0) * 0.16,
383                -(row as f32) * 0.15,
384                -0.16,
385            ));
386            let delta: Vec3 = p.get_position().sub(rest_p);
387            disp_sum += delta.length();
388            x_sway += delta.get_x();
389            z_sway += delta.get_z();
390            free_count += 1.0;
391        }
392        let avg_disp: f32 = if free_count > 0.0 {
393            disp_sum / free_count
394        } else {
395            0.0
396        };
397        let _: &mut Self = self.set_average_displacement_m(avg_disp);
398        let hem_pitch: f32 = ((z_sway / free_count.max(1.0)) * 1.45).clamp(-0.68, 0.68);
399        let hem_roll: f32 = ((x_sway / free_count.max(1.0)) * 1.35).clamp(-0.55, 0.55);
400        let left_tip: Vec3 = self
401            .get_hair_ribbon_left()
402            .get_particles()
403            .last()
404            .map_or(Vec3::zero(), VerletParticle3D::get_position);
405        let right_tip: Vec3 = self
406            .get_hair_ribbon_right()
407            .get_particles()
408            .last()
409            .map_or(Vec3::zero(), VerletParticle3D::get_position);
410        let hair_l_swing: f32 = ((left_tip.get_z() - head_world.get_z()) * 0.85).clamp(-0.75, 0.75);
411        let hair_r_swing: f32 =
412            ((right_tip.get_z() - head_world.get_z()) * 0.85).clamp(-0.75, 0.75);
413        (hem_pitch, hem_roll, hair_l_swing, hair_r_swing)
414    }
415}
416
417/// Complete animation, IK, Verlet cloth, Shape-Key, Ultimate VFX, and Blender render-mode runtime for `JianlaiSceneController`.
418impl JianlaiSceneController {
419    /// Creates a new `JianlaiSceneController` bound to `handles` and `materials` in default Ink-Wash Donghua mode.
420    ///
421    /// # Arguments
422    ///
423    /// - `JianlaiSceneHandles` - Scene object, bone node, skin, and VFX index registry.
424    /// - `JianlaiStyleMaterialIds` - Pre-registered Principled material slot table.
425    ///
426    /// # Returns
427    ///
428    /// - `Self` - Initialized controller ready for per-frame stepping.
429    #[must_use]
430    pub fn new(handles: JianlaiSceneHandles, materials: JianlaiStyleMaterialIds) -> Self {
431        Self {
432            handles,
433            materials,
434            cloth_sim: JianlaiClothSim::create(),
435            active_action: JianlaiAction::InkStance,
436            prev_action: JianlaiAction::InkStance,
437            crossfade_remaining_secs: 0.0,
438            render_mode: JianlaiRenderMode::InkWashDonghua,
439            debug_channel: JianlaiDebugChannel::Normals,
440            skinning_mode: SkinningMode::DualQuaternion,
441            ik_enabled: true,
442            cloth_enabled: true,
443            show_bones: false,
444            freestyle_enabled: true,
445            morph_aura_weight: 0.22,
446            action_time_secs: 0.0,
447            total_time_secs: 0.0,
448            last_ik_error: 0.0,
449            last_ik_iterations: 0,
450            ultimate_charge: 0.0,
451            camera_trauma: 0.0,
452            sky: PhysicalSky3D::new(),
453            volumetric_fog: VolumetricFogVolume3D::default(),
454            postfx_config: PostFxConfig3D::default(),
455        }
456    }
457
458    /// Initiates a smooth NLA crossfade transition onto `action` and resets the action timeline for crisp ultimate playback.
459    ///
460    /// # Arguments
461    ///
462    /// - `&mut World3D` - Mutable world owning `animation_mixer`.
463    /// - `JianlaiAction` - Target martial arts or ultimate action.
464    pub fn select_action(&mut self, world: &mut World3D, action: JianlaiAction) {
465        let prev: JianlaiAction = self.get_active_action();
466        let _: &mut Self = self
467            .set_prev_action(prev)
468            .set_active_action(action)
469            .set_crossfade_remaining_secs(JIANLAI_NLA_CROSSFADE_SECS)
470            .set_action_time_secs(0.0);
471        if action.is_ultimate() {
472            let _: &mut Self = self.set_ultimate_charge(1.0);
473        }
474        let mixer: &mut AnimationMixer3D = world.get_mut_animation_mixer();
475        mixer.clear_layers();
476        if prev != action {
477            let mut fade_out: NlaLayer3D = NlaLayer3D::new(prev.as_index()).with_weight(1.0);
478            fade_out.start_crossfade(0.0, JIANLAI_NLA_CROSSFADE_SECS);
479            let _: usize = mixer.push_layer(fade_out);
480            let mut fade_in: NlaLayer3D = NlaLayer3D::new(action.as_index()).with_weight(0.0);
481            fade_in.start_crossfade(1.0, JIANLAI_NLA_CROSSFADE_SECS);
482            let _: usize = mixer.push_layer(fade_in);
483        } else {
484            let _: usize = mixer.push_layer(NlaLayer3D::new(action.as_index()).with_weight(1.0));
485        }
486        self.step(world, 1.0 / 60.0);
487    }
488
489    /// Scrubs the active NLA timeline forward or backward by `delta_secs` and immediately evaluates deformation and VFX.
490    ///
491    /// # Arguments
492    ///
493    /// - `&mut World3D` - Mutable world.
494    /// - `f32` - Timeline scrub delta in seconds.
495    pub fn scrub_timeline(&mut self, world: &mut World3D, delta_secs: f32) {
496        let dur: f32 = self.get_active_action().duration_secs().max(0.1);
497        let next_t: f32 = (self.get_action_time_secs() + delta_secs).rem_euclid(dur);
498        let _: &mut Self = self.set_action_time_secs(next_t);
499        for layer in world.get_mut_animation_mixer().get_mut_layers().iter_mut() {
500            let _: &mut NlaLayer3D = layer.set_time_secs(next_t);
501        }
502        self.step(world, 0.002);
503    }
504
505    /// Switches the hero armature skinning solver live between `SkinningMode::LinearBlend` (LBS) and `SkinningMode::DualQuaternion` (DQS).
506    ///
507    /// # Arguments
508    ///
509    /// - `&mut World3D` - Mutable world.
510    /// - `SkinningMode` - Target skinning deformation algorithm.
511    pub fn set_skinning(&mut self, world: &mut World3D, mode: SkinningMode) {
512        let _: &mut Self = self.set_skinning_mode(mode);
513        let skin_idx: usize = self.get_handles().get_hero_skin_idx();
514        let _: bool = world.set_skinning_mode(skin_idx, mode);
515        let _: usize = world.update_deformed_meshes();
516        world.bump_world_revision();
517    }
518
519    /// Updates the live Shape Key Battle Aura morph weight (`0.0..=1.0`) on both the hero and Freestyle outline mesh.
520    ///
521    /// # Arguments
522    ///
523    /// - `&mut World3D` - Mutable world.
524    /// - `f32` - Normalized Battle Aura morph weight in `[0.0, 1.0]`.
525    pub fn set_morph_aura(&mut self, world: &mut World3D, weight: f32) {
526        let clamped: f32 = weight.clamp(0.0, 1.0);
527        let _: &mut Self = self.set_morph_aura_weight(clamped);
528        let wind_billow: f32 = (0.18 + clamped * 0.65).clamp(0.0, 1.0);
529        let hero_node: u32 = self.get_handles().get_hero_node_id();
530        world
531            .get_mut_scene_graph()
532            .update_morph_weights(hero_node, &[clamped, wind_billow]);
533        if let Some(out_idx) = self.get_handles().get_hero_outline_obj_idx()
534            && let Some(out_node) = world
535                .get_objects()
536                .get(out_idx)
537                .and_then(SceneObject3D::try_get_node_id)
538        {
539            world
540                .get_mut_scene_graph()
541                .update_morph_weights(out_node, &[clamped, wind_billow]);
542        }
543        let _: usize = world.update_deformed_meshes();
544        world.bump_world_revision();
545    }
546
547    /// Toggles Freestyle inverted-hull calligraphy ink outlines visibility.
548    ///
549    /// # Arguments
550    ///
551    /// - `&mut World3D` - Mutable world.
552    /// - `bool` - Whether Freestyle outlines should be visible.
553    pub fn set_freestyle_outlines(&mut self, world: &mut World3D, enabled: bool) {
554        let _: &mut Self = self.set_freestyle_enabled(enabled);
555        let mode: JianlaiRenderMode = self.get_render_mode();
556        let show_outlines: bool = match mode {
557            JianlaiRenderMode::InkWashDonghua | JianlaiRenderMode::EeveeVolumetric => enabled,
558            JianlaiRenderMode::ShaderDebugPass => {
559                self.get_debug_channel() == JianlaiDebugChannel::FreestyleInkContour
560            }
561            _ => false,
562        };
563        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, show_outlines);
564        world.bump_world_revision();
565    }
566
567    /// Toggles the 3D 27-bone octahedral armature skeleton visualizer overlay.
568    ///
569    /// # Arguments
570    ///
571    /// - `&mut World3D` - Mutable world.
572    /// - `bool` - Whether the bone visualizer overlay is visible.
573    pub fn set_bones_overlay(&mut self, world: &mut World3D, enabled: bool) {
574        let _: &mut Self = self.set_show_bones(enabled);
575        let show_armature: bool =
576            enabled || self.get_render_mode() == JianlaiRenderMode::WireframeArmature;
577        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_ARMATURE, show_armature);
578        let show_wire: bool = self.get_render_mode() == JianlaiRenderMode::WireframeArmature;
579        let wire_indices: Vec<usize> = self.get_handles().get_wireframe_cage_obj_indices().clone();
580        for w_idx in wire_indices {
581            if let Some(nid) = world
582                .get_objects()
583                .get(w_idx)
584                .and_then(SceneObject3D::try_get_node_id)
585                && let Some(node) = world
586                    .get_mut_scene_graph()
587                    .get_mut_nodes()
588                    .get_mut(nid as usize)
589            {
590                let _: &mut SceneNode3D = node.set_visible(show_wire);
591            }
592        }
593        world.bump_world_revision();
594    }
595
596    /// Switches live across all 6 Blender render & inspection modes (`InkWashDonghua`, `CyclesPbr`, `EeveeVolumetric`, `SolidMatcap`, `WireframeArmature`, `ShaderDebugPass`).
597    ///
598    /// # Arguments
599    ///
600    /// - `&mut World3D` - Mutable world whose materials, sky, lighting, and overlays are reconfigured.
601    /// - `JianlaiRenderMode` - Target Blender render mode.
602    pub fn apply_render_mode(&mut self, world: &mut World3D, mode: JianlaiRenderMode) {
603        let _: &mut Self = self.set_render_mode(mode);
604        let mats: JianlaiStyleMaterialIds = self.get_materials();
605        let slots: Vec<(usize, u32)> = self.get_handles().get_scene_material_slots().clone();
606        let assign_slot: fn(&mut World3D, usize, u32) =
607            |w: &mut World3D, obj_idx: usize, mat_id: u32| {
608                let legacy: PbrMaterial = w
609                    .get_principled_materials()
610                    .get(mat_id as usize)
611                    .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
612                if let Some(obj) = w.get_mut_objects().get_mut(obj_idx) {
613                    let _: &mut SceneObject3D = obj
614                        .set_principled_material_id(Some(mat_id))
615                        .set_material(legacy);
616                }
617            };
618        match mode {
619            JianlaiRenderMode::InkWashDonghua => {
620                for (obj_idx, base_mat) in slots {
621                    assign_slot(world, obj_idx, base_mat);
622                }
623                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(10.5);
624                let _: &mut DirectionalLight3D = sun
625                    .set_direction(Vec3::new(0.46, 0.76, 0.45).normalize())
626                    .set_color(Vec3::new(1.12, 1.08, 1.00))
627                    .set_sky_zenith(Vec3::new(0.56, 0.68, 0.72))
628                    .set_sky_horizon(Vec3::new(0.90, 0.92, 0.88));
629                let _: &mut World3D = world.set_sun(sun);
630                world.set_use_agx_tonemap(true);
631                let _: bool = world.set_collection_visible(
632                    JIANLAI_COLLECTION_OUTLINES,
633                    self.get_freestyle_enabled(),
634                );
635                let _: bool = world
636                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
637            }
638            JianlaiRenderMode::CyclesPbr => {
639                for (obj_idx, base_mat) in slots {
640                    assign_slot(world, obj_idx, base_mat);
641                }
642                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(14.0);
643                let _: &mut DirectionalLight3D = sun
644                    .set_direction(Vec3::new(0.62, 0.72, 0.32).normalize())
645                    .set_color(Vec3::new(1.38, 1.32, 1.24))
646                    .set_sky_zenith(Vec3::new(0.18, 0.32, 0.56))
647                    .set_sky_horizon(Vec3::new(0.62, 0.72, 0.84));
648                let _: &mut World3D = world.set_sun(sun);
649                world.set_use_agx_tonemap(true);
650                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
651                let _: bool = world
652                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
653            }
654            JianlaiRenderMode::EeveeVolumetric => {
655                for (obj_idx, base_mat) in slots {
656                    assign_slot(world, obj_idx, base_mat);
657                }
658                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(17.6);
659                let _: &mut DirectionalLight3D = sun
660                    .set_direction(Vec3::new(-0.52, 0.32, -0.78).normalize())
661                    .set_color(Vec3::new(1.55, 0.96, 0.54))
662                    .set_sky_zenith(Vec3::new(0.24, 0.28, 0.44))
663                    .set_sky_horizon(Vec3::new(0.96, 0.68, 0.46));
664                let _: &mut World3D = world.set_sun(sun);
665                world.set_use_agx_tonemap(false);
666                let _: bool = world.set_collection_visible(
667                    JIANLAI_COLLECTION_OUTLINES,
668                    self.get_freestyle_enabled(),
669                );
670                let _: bool = world
671                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
672            }
673            JianlaiRenderMode::SolidMatcap => {
674                for (obj_idx, _) in slots {
675                    assign_slot(world, obj_idx, mats.get_matcap_clay());
676                }
677                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(12.5);
678                let _: &mut DirectionalLight3D = sun
679                    .set_direction(Vec3::new(0.35, 0.82, 0.46).normalize())
680                    .set_color(Vec3::new(1.15, 1.12, 1.08))
681                    .set_sky_zenith(Vec3::new(0.34, 0.36, 0.40))
682                    .set_sky_horizon(Vec3::new(0.52, 0.54, 0.58));
683                let _: &mut World3D = world.set_sun(sun);
684                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
685                let _: bool = world
686                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
687            }
688            JianlaiRenderMode::WireframeArmature => {
689                for (obj_idx, _) in slots {
690                    assign_slot(world, obj_idx, mats.get_ink_trim());
691                }
692                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(13.0);
693                let _: &mut DirectionalLight3D = sun
694                    .set_direction(Vec3::new(0.25, 0.85, 0.45).normalize())
695                    .set_sky_zenith(Vec3::new(0.08, 0.11, 0.15))
696                    .set_sky_horizon(Vec3::new(0.14, 0.18, 0.24));
697                let _: &mut World3D = world.set_sun(sun);
698                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
699                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_ARMATURE, true);
700            }
701            JianlaiRenderMode::ShaderDebugPass => {
702                let channel: JianlaiDebugChannel = self.get_debug_channel();
703                self.apply_debug_channel(world, channel);
704            }
705        }
706        let show_wire: bool = mode == JianlaiRenderMode::WireframeArmature;
707        let wire_indices: Vec<usize> = self.get_handles().get_wireframe_cage_obj_indices().clone();
708        for w_idx in wire_indices {
709            if let Some(nid) = world
710                .get_objects()
711                .get(w_idx)
712                .and_then(SceneObject3D::try_get_node_id)
713                && let Some(node) = world
714                    .get_mut_scene_graph()
715                    .get_mut_nodes()
716                    .get_mut(nid as usize)
717            {
718                let _: &mut SceneNode3D = node.set_visible(show_wire);
719            }
720        }
721        world.bump_world_revision();
722    }
723
724    /// Applies one of the four live shader debug pass channels (`Normals`, `RoughnessMetallic`, `Depth`, `FreestyleInkContour`).
725    ///
726    /// # Arguments
727    ///
728    /// - `&mut World3D` - Mutable world.
729    /// - `JianlaiDebugChannel` - Target shader debug channel.
730    pub fn apply_debug_channel(&mut self, world: &mut World3D, channel: JianlaiDebugChannel) {
731        let _: &mut Self = self.set_debug_channel(channel);
732        if self.get_render_mode() != JianlaiRenderMode::ShaderDebugPass {
733            return;
734        }
735        let mats: JianlaiStyleMaterialIds = self.get_materials();
736        let override_mat: u32 = match channel {
737            JianlaiDebugChannel::Normals => mats.get_debug_normals(),
738            JianlaiDebugChannel::RoughnessMetallic => mats.get_debug_rough_metal(),
739            JianlaiDebugChannel::Depth => mats.get_debug_depth(),
740            JianlaiDebugChannel::FreestyleInkContour => mats.get_debug_freestyle_paper(),
741        };
742        let legacy: PbrMaterial = world
743            .get_principled_materials()
744            .get(override_mat as usize)
745            .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
746        let slots: Vec<(usize, u32)> = self.get_handles().get_scene_material_slots().clone();
747        for (obj_idx, _) in slots {
748            if let Some(obj) = world.get_mut_objects().get_mut(obj_idx) {
749                let _: &mut SceneObject3D = obj
750                    .set_principled_material_id(Some(override_mat))
751                    .set_material(legacy);
752            }
753        }
754        let freestyle_pass: bool = channel == JianlaiDebugChannel::FreestyleInkContour;
755        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, freestyle_pass);
756        if freestyle_pass {
757            let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(12.0);
758            let _: &mut DirectionalLight3D = sun
759                .set_sky_zenith(Vec3::new(0.95, 0.94, 0.90))
760                .set_sky_horizon(Vec3::new(0.97, 0.96, 0.92));
761            let _: &mut World3D = world.set_sun(sun);
762        }
763        world.bump_world_revision();
764    }
765
766    /// Updates a dynamic world object and its linked `SceneNode3D` transform cleanly in O(1).
767    ///
768    /// # Arguments
769    ///
770    /// - `&mut World3D` - Mutable world.
771    /// - `usize` - Object index inside `World3D::objects`.
772    /// - `Transform3D` - New world-space TRS transform.
773    pub(crate) fn update_dynamic_object(world: &mut World3D, obj_idx: usize, tr: Transform3D) {
774        let local_bounds: Option<AxisAlignedBox3D> = world
775            .get_objects()
776            .get(obj_idx)
777            .and_then(|o: &SceneObject3D| world.get_mesh_library().get(o.get_mesh_id()))
778            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
779            .map(Mesh3D::get_bounds);
780        let node_opt: Option<u32> = world
781            .get_objects()
782            .get(obj_idx)
783            .and_then(SceneObject3D::try_get_node_id);
784        if let Some(obj) = world.get_mut_objects().get_mut(obj_idx) {
785            let _: &mut SceneObject3D = obj.set_transform(tr);
786            if let Some(lb) = local_bounds {
787                let _: &mut SceneObject3D = obj.set_world_bounds(tr.transform_bounds(lb));
788            }
789        }
790        if let Some(nid) = node_opt {
791            world.get_mut_scene_graph().set_local_trs(
792                nid,
793                tr.get_position(),
794                tr.get_rotation(),
795                tr.get_scale(),
796            );
797        }
798    }
799
800    /// Advances NLA crossfades, Sword-Tip IK, Verlet cloth physics, LBS/DQS skinning, Shape Keys, Ultimate VFX, 27-bone overlay, and Niagara particles by `dt_secs`.
801    ///
802    /// # Arguments
803    ///
804    /// - `&mut World3D` - Mutable world updated in place with zero steady-state allocations.
805    /// - `f32` - Frame delta time in seconds.
806    pub fn step(&mut self, world: &mut World3D, dt_secs: f32) {
807        let dt: f32 = if dt_secs.is_finite() && dt_secs > 0.0 {
808            dt_secs.clamp(0.001, 0.05)
809        } else {
810            1.0 / 60.0
811        };
812        let action: JianlaiAction = self.get_active_action();
813        let dur: f32 = action.duration_secs().max(0.1);
814        let next_action_t: f32 = (self.get_action_time_secs() + dt).rem_euclid(dur);
815        let next_total_t: f32 = self.get_total_time_secs() + dt;
816        let next_fade: f32 = (self.get_crossfade_remaining_secs() - dt).max(0.0);
817        let next_trauma: f32 = (self.get_camera_trauma() - dt * 1.4).max(0.0);
818        let _: &mut Self = self
819            .set_action_time_secs(next_action_t)
820            .set_total_time_secs(next_total_t)
821            .set_crossfade_remaining_secs(next_fade)
822            .set_camera_trauma(next_trauma);
823        // 1. Advance NLA animation layers onto the 27-bone scene graph.
824        let _: usize = world.tick_animations(dt);
825        let bone_nodes: [u32; JIANLAI_BONE_COUNT] = self.get_handles().get_bone_node_ids();
826        let rest_trans: [Vec3; JIANLAI_BONE_COUNT] =
827            self.get_handles().get_bone_rest_translations();
828        // 2. Live Sword-Tip IK (`IkSolver3D::solve_two_bone` + `IkSolver3D::solve_fabrik`) on right sword arm!
829        let mut ik_err: f32 = 0.0;
830        let mut ik_iters: usize = 0;
831        if self.get_ik_enabled() {
832            let shoulder_pos: Vec3 = world
833                .get_scene_graph()
834                .get_nodes()
835                .get(bone_nodes[BONE_SHOULDER_R] as usize)
836                .map_or(Vec3::new(0.14, 1.48, 0.0), |n: &SceneNode3D| {
837                    n.get_world_matrix().mul_point3(Vec3::zero())
838                });
839            let upper_pos: Vec3 = world
840                .get_scene_graph()
841                .get_nodes()
842                .get(bone_nodes[BONE_UPPER_ARM_R] as usize)
843                .map_or(Vec3::new(0.26, 1.44, 0.0), |n: &SceneNode3D| {
844                    n.get_world_matrix().mul_point3(Vec3::zero())
845                });
846            let phase: f32 = (next_action_t / dur) * TAU;
847            let ik_target: Vec3 = match action {
848                JianlaiAction::InkStance => upper_pos.add(Vec3::new(
849                    0.34 + (phase).cos() * 0.06,
850                    -0.16 + (phase * 2.0).sin() * 0.05,
851                    0.26,
852                )),
853                JianlaiAction::FlowingSwordDance => upper_pos.add(Vec3::new(
854                    0.38 * phase.cos(),
855                    0.18 * (phase * 2.0).sin(),
856                    0.38 * phase.sin().abs() + 0.14,
857                )),
858                JianlaiAction::MyriadSwordsReturn => {
859                    upper_pos.add(Vec3::new(0.22, 0.34 + 0.08 * phase.sin(), 0.24))
860                }
861                JianlaiAction::SkyCleavingSwordQi => {
862                    let norm_t: f32 = next_action_t / dur;
863                    if norm_t < 0.32 {
864                        upper_pos.add(Vec3::new(0.12, 0.44, -0.10))
865                    } else if norm_t < 0.56 {
866                        upper_pos.add(Vec3::new(0.24, -0.18, 0.42))
867                    } else {
868                        upper_pos.add(Vec3::new(0.32, -0.22, 0.30))
869                    }
870                }
871                JianlaiAction::CloudStepGlide => {
872                    upper_pos.add(Vec3::new(0.42, -0.06 + 0.05 * phase.sin(), 0.12))
873                }
874            };
875            let upper_len: f32 = rest_trans[BONE_FOREARM_R].length().max(0.22);
876            let lower_len: f32 = rest_trans[BONE_HAND_R].length().max(0.20);
877            let pole: Vec3 = shoulder_pos.add(Vec3::new(0.35, -0.25, -0.45));
878            let two_bone: IkTwoBoneResult =
879                IkSolver3D::solve_two_bone(upper_pos, upper_len, lower_len, ik_target, pole);
880            let mut chain_pts: [Vec3; 3] =
881                [upper_pos, two_bone.get_joint_mid(), two_bone.get_effector()];
882            let seg_lens: [f32; 2] = [upper_len, lower_len];
883            let fabrik: IkChainResult =
884                IkSolver3D::solve_fabrik(&mut chain_pts, &seg_lens, ik_target, 0.005, 8);
885            ik_err = two_bone.get_error().min(fabrik.get_error());
886            ik_iters = fabrik.get_iterations().max(1);
887            let upper_q: Quat = two_bone.get_upper_rotation();
888            let lower_rel: Quat = upper_q
889                .conjugate()
890                .mul_quat(two_bone.get_lower_rotation())
891                .normalize();
892            let sg: &mut SceneGraph3D = world.get_mut_scene_graph();
893            if let Some(u_node) = sg.get_nodes().get(bone_nodes[BONE_UPPER_ARM_R] as usize) {
894                let blended_u: Quat = u_node.get_local_rotation().slerp(upper_q, 0.32);
895                let cur_t: Vec3 = u_node.get_local_translation();
896                let cur_s: Vec3 = u_node.get_local_scale();
897                sg.set_local_trs(bone_nodes[BONE_UPPER_ARM_R], cur_t, blended_u, cur_s);
898            }
899            if let Some(f_node) = sg.get_nodes().get(bone_nodes[BONE_FOREARM_R] as usize) {
900                let blended_f: Quat = f_node.get_local_rotation().slerp(lower_rel, 0.32);
901                let cur_t: Vec3 = f_node.get_local_translation();
902                let cur_s: Vec3 = f_node.get_local_scale();
903                sg.set_local_trs(bone_nodes[BONE_FOREARM_R], cur_t, blended_f, cur_s);
904            }
905        }
906        let _: &mut Self = self
907            .set_last_ik_error(ik_err)
908            .set_last_ik_iterations(ik_iters);
909        // 3. Step live Verlet cloth & hair ribbon physics and apply dynamic robe/hair bone sway.
910        let pelvis_world: Vec3 = world
911            .get_scene_graph()
912            .get_nodes()
913            .get(bone_nodes[BONE_PELVIS] as usize)
914            .map_or(Vec3::new(0.0, 0.96, 0.0), |n: &SceneNode3D| {
915                n.get_world_matrix().mul_point3(Vec3::zero())
916            });
917        let head_world: Vec3 = world
918            .get_scene_graph()
919            .get_nodes()
920            .get(bone_nodes[BONE_HEAD] as usize)
921            .map_or(Vec3::new(0.0, 1.72, 0.0), |n: &SceneNode3D| {
922                n.get_world_matrix().mul_point3(Vec3::zero())
923            });
924        let qi_wind_boost: f32 = if action.is_ultimate() { 8.5 } else { 2.4 };
925        let wind_vec: Vec3 = Vec3::new(
926            (next_total_t * 1.7).sin() * 2.2,
927            0.8 + (next_total_t * 2.9).cos() * 0.6,
928            -qi_wind_boost - (next_total_t * 2.3).sin().abs() * 2.8,
929        );
930        if self.get_cloth_enabled() {
931            let (hem_p, hem_r, hair_l, hair_r): (f32, f32, f32, f32) = self
932                .get_mut_cloth_sim()
933                .step_physics(dt, wind_vec, pelvis_world, head_world);
934            let sg: &mut SceneGraph3D = world.get_mut_scene_graph();
935            let cloth_bones: [(usize, Quat); 6] = [
936                (
937                    BONE_HEM_FRONT,
938                    Quat::from_euler_yxz(0.0, -hem_p.abs() * 0.45, hem_r),
939                ),
940                (
941                    BONE_HEM_BACK,
942                    Quat::from_euler_yxz(0.0, hem_p.abs() * 0.85, -hem_r),
943                ),
944                (
945                    BONE_HEM_LEFT,
946                    Quat::from_euler_yxz(0.0, hem_p * 0.3, -hem_r.abs() - 0.16),
947                ),
948                (
949                    BONE_HEM_RIGHT,
950                    Quat::from_euler_yxz(0.0, hem_p * 0.3, hem_r.abs() + 0.16),
951                ),
952                (BONE_HAIR_L, Quat::from_euler_yxz(0.12, hair_l, -0.18)),
953                (BONE_HAIR_R, Quat::from_euler_yxz(-0.12, hair_r, 0.18)),
954            ];
955            for (b_idx, b_rot) in cloth_bones {
956                sg.set_local_trs(
957                    bone_nodes[b_idx],
958                    rest_trans[b_idx],
959                    b_rot,
960                    Vec3::splat(1.0),
961                );
962            }
963        }
964        // 4. Modulate live Shape Key battle aura surge during ultimates & propagate deformed meshes.
965        let base_aura: f32 = self.get_morph_aura_weight();
966        let effective_aura: f32 = if action.is_ultimate() {
967            (base_aura + 0.45 * ((next_action_t / dur) * PI).sin()).clamp(0.0, 1.0)
968        } else {
969            base_aura
970        };
971        let wind_morph: f32 =
972            (0.20 + effective_aura * 0.55 + (next_total_t * 2.4).sin().abs() * 0.25)
973                .clamp(0.0, 1.0);
974        let hero_node: u32 = self.get_handles().get_hero_node_id();
975        world
976            .get_mut_scene_graph()
977            .update_morph_weights(hero_node, &[effective_aura, wind_morph]);
978        if let Some(out_idx) = self.get_handles().get_hero_outline_obj_idx()
979            && let Some(out_node) = world
980                .get_objects()
981                .get(out_idx)
982                .and_then(SceneObject3D::try_get_node_id)
983        {
984            world
985                .get_mut_scene_graph()
986                .update_morph_weights(out_node, &[effective_aura, wind_morph]);
987        }
988        let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
989        let _: usize = world.update_deformed_meshes();
990        // 5. Update Primary Spirit Sword & Floating Scabbard from live `SwordSocket` bone world matrix.
991        let socket_world: Mat4 = world
992            .get_scene_graph()
993            .get_nodes()
994            .get(bone_nodes[BONE_SWORD_SOCKET] as usize)
995            .map_or_else(Mat4::identity, SceneNode3D::get_world_matrix);
996        let (sock_pos, sock_rot, _): (Vec3, Quat, Vec3) = socket_world.decompose_trs();
997        let sword_tr: Transform3D = match action {
998            JianlaiAction::CloudStepGlide => Transform3D::from_trs(
999                pelvis_world.add(Vec3::new(0.0, -0.92, 0.12)),
1000                Quat::from_euler_yxz(0.0, FRAC_PI_2, 0.08 * (next_total_t * 2.4).sin()),
1001                Vec3::splat(1.32),
1002            ),
1003            JianlaiAction::MyriadSwordsReturn => Transform3D::from_trs(
1004                pelvis_world.add(Vec3::new(
1005                    0.85,
1006                    0.45 + 0.14 * (next_total_t * 3.0).sin(),
1007                    0.45,
1008                )),
1009                Quat::from_euler_yxz(next_total_t * 0.9, 0.35, -0.18),
1010                Vec3::splat(1.12),
1011            ),
1012            _ => Transform3D::from_trs(
1013                sock_pos,
1014                sock_rot
1015                    .mul_quat(Quat::from_euler_yxz(0.0, 0.72, -0.22))
1016                    .normalize(),
1017                Vec3::splat(1.06),
1018            ),
1019        };
1020        let sword_obj: usize = self.get_handles().get_sword_obj_idx();
1021        Self::update_dynamic_object(world, sword_obj, sword_tr);
1022        if let Some(out_idx) = self.get_handles().get_sword_outline_obj_idx() {
1023            Self::update_dynamic_object(world, out_idx, sword_tr);
1024        }
1025        let scabbard_tr: Transform3D = Transform3D::from_trs(
1026            pelvis_world.add(Vec3::new(
1027                -0.28,
1028                0.42 + (next_total_t * 2.1).sin() * 0.06,
1029                -0.36,
1030            )),
1031            Quat::from_euler_yxz(0.18, 0.06 * (next_total_t * 1.4).cos(), 0.44),
1032            Vec3::splat(1.0),
1033        );
1034        let scabbard_obj: usize = self.get_handles().get_scabbard_obj_idx();
1035        Self::update_dynamic_object(world, scabbard_obj, scabbard_tr);
1036        // 6. Animate Ultimate VFX: 18-Sword Bagua Halo, Sky-Cleaving Crescent Qi Wave, Ink Shockwave Ring, Sword Trail & Niagara Particles!
1037        self.update_ultimate_vfx(world, pelvis_world, sword_tr);
1038        // 7. Update all 26 Octahedral Armature Bone Visualizer prisms from live bone world positions.
1039        let prism_indices: Vec<usize> = self.get_handles().get_bone_prism_obj_indices().clone();
1040        for (slot_idx, prism_obj) in prism_indices.iter().enumerate() {
1041            let child_idx: usize = slot_idx + 1;
1042            let parent_idx: usize = JIANLAI_BONE_PARENTS[child_idx].unwrap_or(0);
1043            let p_pos: Vec3 = world
1044                .get_scene_graph()
1045                .get_nodes()
1046                .get(bone_nodes[parent_idx] as usize)
1047                .map_or(Vec3::zero(), |n: &SceneNode3D| {
1048                    n.get_world_matrix().mul_point3(Vec3::zero())
1049                });
1050            let c_pos: Vec3 = world
1051                .get_scene_graph()
1052                .get_nodes()
1053                .get(bone_nodes[child_idx] as usize)
1054                .map_or(Vec3::zero(), |n: &SceneNode3D| {
1055                    n.get_world_matrix().mul_point3(Vec3::zero())
1056                });
1057            let seg: Vec3 = c_pos.sub(p_pos);
1058            let len: f32 = seg.length().max(0.06);
1059            let dir: Vec3 = seg.scale(1.0 / len);
1060            let up_axis: Vec3 = Vec3::new(0.0, 1.0, 0.0);
1061            let rot: Quat = quat_between_unit_vectors(up_axis, dir);
1062            let bone_tr: Transform3D =
1063                Transform3D::from_trs(p_pos, rot, Vec3::new(len * 0.42, len, len * 0.42));
1064            Self::update_dynamic_object(world, *prism_obj, bone_tr);
1065        }
1066        // 8. Gently drift the 6 Xuan-paper ink-cloud mist ribbons around the cliff abyss.
1067        let cloud_indices: Vec<usize> = self.get_handles().get_cloud_ribbon_obj_indices().clone();
1068        for (idx, c_obj) in cloud_indices.iter().enumerate() {
1069            let base_ang: f32 = ((idx as f32) / 6.0) * TAU + next_total_t * 0.065;
1070            let rad: f32 = 8.4 + (idx as f32) * 1.45;
1071            let y_h: f32 =
1072                -1.55 + ((idx % 3) as f32) * 1.55 + (next_total_t * 0.5 + idx as f32).sin() * 0.22;
1073            let cl_tr: Transform3D = Transform3D::new(
1074                Vec3::new(rad * base_ang.cos(), y_h, rad * base_ang.sin()),
1075                base_ang + FRAC_PI_2,
1076                Vec3::new(1.28, 1.0, 1.28),
1077            );
1078            Self::update_dynamic_object(world, *c_obj, cl_tr);
1079        }
1080        // 9. Advance Niagara 3D ink droplets and golden sword-qi spark particles.
1081        let _: usize = world.get_mut_niagara().update(dt, 0.02);
1082        let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
1083        world.bump_world_revision();
1084    }
1085
1086    /// Drives the 18-sword Bagua halo array, colossal Sky-Cleaving crescent wave, ink-splash shockwave ring, sword-arc trail, and Niagara bursts.
1087    ///
1088    /// # Arguments
1089    ///
1090    /// - `&mut World3D` - Mutable world owning VFX objects and `NiagaraSystem3D`.
1091    /// - `Vec3` - Hero pelvis world position.
1092    /// - `Transform3D` - Live primary spirit sword world transform.
1093    fn update_ultimate_vfx(
1094        &mut self,
1095        world: &mut World3D,
1096        pelvis_world: Vec3,
1097        sword_tr: Transform3D,
1098    ) {
1099        let action: JianlaiAction = self.get_active_action();
1100        let action_t: f32 = self.get_action_time_secs();
1101        let dur: f32 = action.duration_secs().max(0.1);
1102        let total_t: f32 = self.get_total_time_secs();
1103        let norm_t: f32 = (action_t / dur).clamp(0.0, 1.0);
1104        let myriad_indices: Vec<usize> = self.get_handles().get_myriad_sword_obj_indices().clone();
1105        let crescent_obj: usize = self.get_handles().get_crescent_qi_obj_idx();
1106        let shock_obj: usize = self.get_handles().get_shockwave_ring_obj_idx();
1107        let trail_obj: usize = self.get_handles().get_sword_trail_obj_idx();
1108        let parked: Transform3D =
1109            Transform3D::new(Vec3::new(0.0, -4.5, 0.0), 0.0, Vec3::splat(0.001));
1110        match action {
1111            JianlaiAction::MyriadSwordsReturn => {
1112                let deploy: f32 = (norm_t * 3.2).clamp(0.0, 1.0);
1113                let barrage_t: f32 = ((norm_t - 0.52) / 0.42).clamp(0.0, 1.0);
1114                let _: &mut Self = self.set_ultimate_charge((0.55 + 0.45 * deploy).clamp(0.0, 1.0));
1115                for (idx, s_obj) in myriad_indices.iter().enumerate() {
1116                    let is_inner: bool = idx < 6;
1117                    let ring_n: f32 = if is_inner { 6.0 } else { 12.0 };
1118                    let ring_i: f32 = if is_inner {
1119                        idx as f32
1120                    } else {
1121                        (idx - 6) as f32
1122                    };
1123                    let spin_dir: f32 = if is_inner { 1.35 } else { -0.95 };
1124                    let ang: f32 = (ring_i / ring_n) * TAU + total_t * spin_dir;
1125                    let base_rad: f32 = if is_inner { 1.55 } else { 2.55 };
1126                    let rad: f32 = base_rad * (0.35 + 0.65 * deploy);
1127                    let z_launch: f32 = -1.15 + barrage_t * (5.2 + (idx % 4) as f32 * 0.9);
1128                    let pos: Vec3 = Vec3::new(
1129                        pelvis_world.get_x() + rad * ang.cos(),
1130                        pelvis_world.get_y() + 1.15 + rad * ang.sin() * 0.78,
1131                        pelvis_world.get_z() + z_launch,
1132                    );
1133                    let pitch: f32 = if barrage_t > 0.05 { FRAC_PI_2 } else { 0.32 };
1134                    let s_tr: Transform3D = Transform3D::from_trs(
1135                        pos,
1136                        Quat::from_euler_yxz(0.0, pitch, ang - FRAC_PI_2),
1137                        Vec3::splat(0.82 * deploy.max(0.15)),
1138                    );
1139                    Self::update_dynamic_object(world, *s_obj, s_tr);
1140                }
1141                let halo_scale: f32 = 1.2 + deploy * 1.45;
1142                Self::update_dynamic_object(
1143                    world,
1144                    shock_obj,
1145                    Transform3D::from_trs(
1146                        pelvis_world.add(Vec3::new(0.0, 1.15, -1.25)),
1147                        Quat::from_euler_yxz(0.0, FRAC_PI_2, total_t * 1.1),
1148                        Vec3::splat(halo_scale),
1149                    ),
1150                );
1151                Self::update_dynamic_object(world, crescent_obj, parked);
1152                Self::update_dynamic_object(world, trail_obj, parked);
1153                let mut emitter: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
1154                let _: &mut NiagaraEmitterConfig3D = emitter
1155                    .set_origin(pelvis_world.add(Vec3::new(0.0, 1.2, -0.8)))
1156                    .set_base_velocity(Vec3::new(0.0, 0.8, 3.6))
1157                    .set_velocity_spread(2.4)
1158                    .set_start_size_m(0.09)
1159                    .set_end_size_m(0.02)
1160                    .set_start_color(Color::rgba(255, 214, 92, 235))
1161                    .set_end_color(Color::rgba(72, 236, 240, 40))
1162                    .set_emissive_boost(2.2);
1163                world.get_mut_niagara().emit_burst(6, &emitter);
1164            }
1165            JianlaiAction::SkyCleavingSwordQi => {
1166                let charge_phase: bool = norm_t < 0.34;
1167                let cleave_t: f32 = ((norm_t - 0.34) / 0.56).clamp(0.0, 1.0);
1168                let charge_val: f32 = if charge_phase {
1169                    (norm_t / 0.34).clamp(0.0, 1.0)
1170                } else {
1171                    (1.0 - cleave_t * 0.7).clamp(0.0, 1.0)
1172                };
1173                let _: &mut Self = self.set_ultimate_charge(charge_val);
1174                if norm_t > 0.33 && norm_t < 0.42 {
1175                    let _: &mut Self = self.set_camera_trauma(0.95);
1176                }
1177                for (idx, s_obj) in myriad_indices.iter().enumerate() {
1178                    let ang: f32 =
1179                        ((idx as f32) / (JIANLAI_MYRIAD_SWORD_COUNT as f32)) * TAU + total_t * 1.8;
1180                    let r: f32 = 2.8 - charge_val * 0.85;
1181                    let pos: Vec3 =
1182                        Vec3::new(r * ang.cos(), 0.45 + (idx % 3) as f32 * 0.45, r * ang.sin());
1183                    let scale_s: f32 = if idx < 6 { 0.55 } else { 0.001 };
1184                    Self::update_dynamic_object(
1185                        world,
1186                        *s_obj,
1187                        Transform3D::from_trs(
1188                            pos,
1189                            Quat::from_euler_yxz(-ang, 0.25, 0.0),
1190                            Vec3::splat(scale_s),
1191                        ),
1192                    );
1193                }
1194                if !charge_phase && cleave_t < 0.96 {
1195                    let wave_z: f32 = 0.85 + cleave_t * 11.5;
1196                    let wave_s: f32 = 0.65 + (cleave_t * PI).sin() * 1.15;
1197                    Self::update_dynamic_object(
1198                        world,
1199                        crescent_obj,
1200                        Transform3D::from_trs(
1201                            Vec3::new(0.0, 2.25, wave_z),
1202                            Quat::from_euler_yxz(0.0, 0.0, 0.16),
1203                            Vec3::splat(wave_s),
1204                        ),
1205                    );
1206                    let ring_s: f32 = 0.75 + cleave_t * 3.8;
1207                    Self::update_dynamic_object(
1208                        world,
1209                        shock_obj,
1210                        Transform3D::new(
1211                            Vec3::new(0.0, 0.16, 0.0),
1212                            total_t * 2.5,
1213                            Vec3::new(ring_s, 0.8, ring_s),
1214                        ),
1215                    );
1216                } else {
1217                    Self::update_dynamic_object(world, crescent_obj, parked);
1218                    let charge_ring: f32 = 0.55 + charge_val * 0.95;
1219                    Self::update_dynamic_object(
1220                        world,
1221                        shock_obj,
1222                        Transform3D::new(
1223                            Vec3::new(0.0, 0.18, 0.0),
1224                            -total_t * 3.2,
1225                            Vec3::new(charge_ring, 0.6, charge_ring),
1226                        ),
1227                    );
1228                }
1229                Self::update_dynamic_object(world, trail_obj, parked);
1230                let mut ink_emit: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
1231                let _: &mut NiagaraEmitterConfig3D = ink_emit
1232                    .set_origin(Vec3::new(0.0, 1.35, 0.55 + cleave_t * 4.5))
1233                    .set_base_velocity(Vec3::new(0.0, 1.4, 5.2))
1234                    .set_velocity_spread(3.2)
1235                    .set_start_size_m(0.12)
1236                    .set_end_size_m(0.03)
1237                    .set_start_color(Color::rgba(24, 30, 42, 240))
1238                    .set_end_color(Color::rgba(255, 198, 62, 60))
1239                    .set_emissive_boost(2.4);
1240                world.get_mut_niagara().emit_burst(8, &ink_emit);
1241            }
1242            JianlaiAction::FlowingSwordDance => {
1243                let _: &mut Self = self.set_ultimate_charge(0.35);
1244                for s_obj in myriad_indices.iter() {
1245                    Self::update_dynamic_object(world, *s_obj, parked);
1246                }
1247                Self::update_dynamic_object(world, crescent_obj, parked);
1248                Self::update_dynamic_object(world, shock_obj, parked);
1249                Self::update_dynamic_object(
1250                    world,
1251                    trail_obj,
1252                    Transform3D::from_trs(
1253                        pelvis_world.add(Vec3::new(0.0, 0.35, 0.0)),
1254                        Quat::from_euler_yxz(total_t * 4.2, 0.24 * (total_t * 2.0).sin(), 0.28),
1255                        Vec3::splat(1.05),
1256                    ),
1257                );
1258                let mut spark: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
1259                let _: &mut NiagaraEmitterConfig3D = spark
1260                    .set_origin(sword_tr.get_position())
1261                    .set_base_velocity(Vec3::new(0.0, 0.6, 0.4))
1262                    .set_velocity_spread(1.6)
1263                    .set_start_size_m(0.07)
1264                    .set_end_size_m(0.015)
1265                    .set_start_color(Color::rgba(82, 238, 244, 220))
1266                    .set_end_color(Color::rgba(240, 248, 250, 20))
1267                    .set_emissive_boost(1.8);
1268                world.get_mut_niagara().emit_burst(4, &spark);
1269            }
1270            JianlaiAction::InkStance | JianlaiAction::CloudStepGlide => {
1271                let _: &mut Self = self.set_ultimate_charge(0.12);
1272                for (idx, s_obj) in myriad_indices.iter().enumerate() {
1273                    if idx < 4 {
1274                        let ang: f32 = ((idx as f32) / 4.0) * TAU + total_t * 0.65;
1275                        let pos: Vec3 = pelvis_world.add(Vec3::new(
1276                            1.35 * ang.cos(),
1277                            0.65 + (total_t * 1.6 + idx as f32).sin() * 0.14,
1278                            -0.85 + 0.45 * ang.sin(),
1279                        ));
1280                        Self::update_dynamic_object(
1281                            world,
1282                            *s_obj,
1283                            Transform3D::from_trs(
1284                                pos,
1285                                Quat::from_euler_yxz(ang, 0.08, 0.0),
1286                                Vec3::splat(0.52),
1287                            ),
1288                        );
1289                    } else {
1290                        Self::update_dynamic_object(world, *s_obj, parked);
1291                    }
1292                }
1293                Self::update_dynamic_object(world, crescent_obj, parked);
1294                Self::update_dynamic_object(world, shock_obj, parked);
1295                Self::update_dynamic_object(world, trail_obj, parked);
1296                let mut mote: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
1297                let _: &mut NiagaraEmitterConfig3D = mote
1298                    .set_origin(pelvis_world.add(Vec3::new(0.0, 0.2, 0.0)))
1299                    .set_base_velocity(Vec3::new(0.0, 0.55, -0.4))
1300                    .set_velocity_spread(0.85)
1301                    .set_start_size_m(0.06)
1302                    .set_end_size_m(0.015)
1303                    .set_start_color(Color::rgba(148, 234, 226, 180))
1304                    .set_end_color(Color::rgba(242, 246, 244, 10))
1305                    .set_emissive_boost(1.2);
1306                world.get_mut_niagara().emit_burst(2, &mote);
1307            }
1308        }
1309    }
1310
1311    /// Captures a structured `JianlaiRigMetrics` telemetry snapshot from the controller and `world`.
1312    ///
1313    /// # Arguments
1314    ///
1315    /// - `&World3D` - Active world providing live Niagara particle counts.
1316    ///
1317    /// # Returns
1318    ///
1319    /// - `JianlaiRigMetrics` - Complete live rigging, physics, VFX, and geometry metrics.
1320    #[must_use]
1321    pub fn metrics(&self, world: &World3D) -> JianlaiRigMetrics {
1322        let action: JianlaiAction = self.get_active_action();
1323        let active_swords: usize = match action {
1324            JianlaiAction::MyriadSwordsReturn => JIANLAI_MYRIAD_SWORD_COUNT,
1325            JianlaiAction::SkyCleavingSwordQi => 6,
1326            JianlaiAction::InkStance | JianlaiAction::CloudStepGlide => 4,
1327            JianlaiAction::FlowingSwordDance => 1,
1328        };
1329        JianlaiRigMetrics {
1330            bone_count: JIANLAI_BONE_COUNT,
1331            hero_vertices: self.get_handles().get_hero_vertices(),
1332            hero_triangles: self.get_handles().get_hero_triangles(),
1333            stage_triangles: self.get_handles().get_stage_triangles(),
1334            total_triangles: self.get_handles().get_total_triangles(),
1335            active_action: action,
1336            render_mode: self.get_render_mode(),
1337            debug_channel: self.get_debug_channel(),
1338            skinning_mode: self.get_skinning_mode(),
1339            ik_enabled: self.get_ik_enabled(),
1340            ik_error_m: self.get_last_ik_error(),
1341            ik_iterations: self.get_last_ik_iterations(),
1342            cloth_enabled: self.get_cloth_enabled(),
1343            cloth_displacement_m: self.get_cloth_sim().get_average_displacement_m(),
1344            morph_aura_weight: self.get_morph_aura_weight(),
1345            freestyle_enabled: self.get_freestyle_enabled(),
1346            show_bones: self.get_show_bones(),
1347            niagara_particles: world.get_niagara().get_active_count(),
1348            flying_swords_active: active_swords,
1349            ultimate_charge: self.get_ultimate_charge(),
1350            camera_trauma: self.get_camera_trauma(),
1351            timeline_secs: self.get_action_time_secs(),
1352            clip_duration_secs: action.duration_secs(),
1353        }
1354    }
1355}