euv-core 0.57.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
use super::*;

/// Index conversion, label, duration, and classification helpers for `JianlaiAction`.
impl JianlaiAction {
    /// Converts a zero-based UI index (`0..5`) into the matching `JianlaiAction`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Action selector index.
    ///
    /// # Returns
    ///
    /// - `Self` - Resolved Jianlai martial arts or ultimate action.
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        match index {
            1 => Self::FlowingSwordDance,
            2 => Self::MyriadSwordsReturn,
            3 => Self::SkyCleavingSwordQi,
            4 => Self::CloudStepGlide,
            _ => Self::InkStance,
        }
    }

    /// Returns the zero-based NLA clip index for this action (`0..5`).
    ///
    /// # Returns
    ///
    /// - `usize` - Matching NLA clip index.
    #[must_use]
    pub const fn as_index(self) -> usize {
        match self {
            Self::InkStance => 0,
            Self::FlowingSwordDance => 1,
            Self::MyriadSwordsReturn => 2,
            Self::SkyCleavingSwordQi => 3,
            Self::CloudStepGlide => 4,
        }
    }

    /// Returns the human-readable display label for this action.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Action label.
    #[must_use]
    pub const fn label(self) -> &'static str {
        JIANLAI_ACTION_LABELS[self.as_index()]
    }

    /// Returns the loop duration in seconds for this action clip.
    ///
    /// # Returns
    ///
    /// - `f32` - Clip duration in seconds.
    #[must_use]
    pub const fn duration_secs(self) -> f32 {
        match self {
            Self::InkStance => 3.2,
            Self::FlowingSwordDance => 2.8,
            Self::MyriadSwordsReturn => 4.0,
            Self::SkyCleavingSwordQi => 3.6,
            Self::CloudStepGlide => 3.6,
        }
    }

    /// Returns `true` when this action is a high-energy ultimate attack (`MyriadSwordsReturn` or `SkyCleavingSwordQi`).
    ///
    /// # Returns
    ///
    /// - `bool` - Whether this action unleashes ultimate VFX.
    #[must_use]
    pub const fn is_ultimate(self) -> bool {
        matches!(self, Self::MyriadSwordsReturn | Self::SkyCleavingSwordQi)
    }
}

/// Index conversion and label helpers for `JianlaiRenderMode`.
impl JianlaiRenderMode {
    /// Converts a zero-based UI index (`0..6`) into the matching `JianlaiRenderMode`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Render mode index.
    ///
    /// # Returns
    ///
    /// - `Self` - Resolved Blender render mode.
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        match index {
            1 => Self::CyclesPbr,
            2 => Self::EeveeVolumetric,
            3 => Self::SolidMatcap,
            4 => Self::WireframeArmature,
            5 => Self::ShaderDebugPass,
            _ => Self::InkWashDonghua,
        }
    }

    /// Returns the zero-based UI index for this render mode (`0..6`).
    ///
    /// # Returns
    ///
    /// - `usize` - Render mode index.
    #[must_use]
    pub const fn as_index(self) -> usize {
        match self {
            Self::InkWashDonghua => 0,
            Self::CyclesPbr => 1,
            Self::EeveeVolumetric => 2,
            Self::SolidMatcap => 3,
            Self::WireframeArmature => 4,
            Self::ShaderDebugPass => 5,
        }
    }

    /// Returns the display label for this render mode.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Render mode display name.
    #[must_use]
    pub const fn label(self) -> &'static str {
        JIANLAI_RENDER_MODE_LABELS[self.as_index()]
    }
}

/// Index conversion and label helpers for `JianlaiDebugChannel`.
impl JianlaiDebugChannel {
    /// Converts a zero-based UI index (`0..4`) into the matching `JianlaiDebugChannel`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Debug channel index.
    ///
    /// # Returns
    ///
    /// - `Self` - Resolved shader debug channel.
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        match index {
            1 => Self::RoughnessMetallic,
            2 => Self::Depth,
            3 => Self::FreestyleInkContour,
            _ => Self::Normals,
        }
    }

    /// Returns the zero-based index for this debug channel (`0..4`).
    ///
    /// # Returns
    ///
    /// - `usize` - Debug channel index.
    #[must_use]
    pub const fn as_index(self) -> usize {
        match self {
            Self::Normals => 0,
            Self::RoughnessMetallic => 1,
            Self::Depth => 2,
            Self::FreestyleInkContour => 3,
        }
    }

    /// Returns the display label for this debug channel.
    ///
    /// # Returns
    ///
    /// - `&'static str` - Channel label.
    #[must_use]
    pub const fn label(self) -> &'static str {
        JIANLAI_DEBUG_CHANNEL_LABELS[self.as_index()]
    }
}

/// Index conversion helpers for `JianlaiStagePreset`.
impl JianlaiStagePreset {
    /// Converts a zero-based preset index (`0..3`) into `JianlaiStagePreset`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Preset index.
    ///
    /// # Returns
    ///
    /// - `Self` - Resolved stage preset.
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        match index {
            1 => Self::SpiritSwordGallery,
            2 => Self::ImmortalPavilionMultiCam,
            _ => Self::HeroInkCliff,
        }
    }

    /// Returns the zero-based preset index (`0..3`).
    ///
    /// # Returns
    ///
    /// - `usize` - Preset index.
    #[must_use]
    pub const fn as_index(self) -> usize {
        match self {
            Self::HeroInkCliff => 0,
            Self::SpiritSwordGallery => 1,
            Self::ImmortalPavilionMultiCam => 2,
        }
    }
}

/// Camera preset lookup helpers for `JianlaiCameraPreset`.
impl JianlaiCameraPreset {
    /// Converts a zero-based camera preset index (`0..4`) into `JianlaiCameraPreset`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Camera preset index.
    ///
    /// # Returns
    ///
    /// - `Self` - Resolved camera preset.
    #[must_use]
    pub const fn from_index(index: usize) -> Self {
        match index {
            1 => Self::LowAngleUltimate,
            2 => Self::CliffPanorama,
            3 => Self::SwordArrayOverhead,
            _ => Self::HeroThreeQuarter,
        }
    }

    /// Returns `(target, yaw_rad, pitch_rad, distance)` orbit coordinates for this camera preset.
    ///
    /// # Returns
    ///
    /// - `(Vec3, f32, f32, f32)` - Orbit target, yaw, pitch, and distance in meters.
    #[must_use]
    pub fn orbit_tuple(self) -> (Vec3, f32, f32, f32) {
        match self {
            Self::HeroThreeQuarter => (Vec3::new(-0.2, 1.32, -0.2), 0.54, -0.22, 6.2),
            Self::LowAngleUltimate => (Vec3::new(0.0, 1.85, -0.2), 0.44, 0.14, 5.2),
            Self::CliffPanorama => (Vec3::new(-0.8, 1.65, -2.2), 0.68, -0.28, 14.5),
            Self::SwordArrayOverhead => (Vec3::new(0.0, 0.9, -0.5), 0.12, -0.98, 10.6),
        }
    }
}

/// Verlet cloth and ribbon solver initialization and simulation stepping for `JianlaiClothSim`.
impl JianlaiClothSim {
    /// Creates the pre-configured Verlet cloth grid (robes/hem) and three Verlet rope chains (twin hair ribbons + sword tassel).
    ///
    /// # Returns
    ///
    /// - `Self` - Ready cloth simulation bundle with body and terrace colliders.
    #[must_use]
    pub fn create() -> Self {
        let mut robe_cloth: VerletClothSolver =
            VerletClothSolver::new(5, 6, 0.16, Vec3::new(-0.32, 0.98, -0.18));
        for col in 0..5usize {
            robe_cloth.pin_particle(col, 0);
        }
        robe_cloth.add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 0.62, 0.0), 0.24));
        robe_cloth.add_plane_collider(VerletPlaneCollider::new(Vec3::new(0.0, 1.0, 0.0), 0.04));
        let _: &mut VerletClothSolver = robe_cloth
            .set_gravity(Vec3::new(0.0, -7.8, -0.6))
            .set_damping(0.96)
            .set_solver_iterations(5);
        let mut hair_ribbon_left: VerletRopeSolver = VerletRopeSolver::new(
            6,
            0.16,
            Vec3::new(-0.08, 1.88, -0.10),
            Vec3::new(-0.22, -0.82, -0.52),
        );
        hair_ribbon_left.pin_particle(0);
        hair_ribbon_left
            .add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 1.32, 0.0), 0.22));
        let mut hair_ribbon_right: VerletRopeSolver = VerletRopeSolver::new(
            6,
            0.16,
            Vec3::new(0.08, 1.88, -0.10),
            Vec3::new(0.22, -0.82, -0.52),
        );
        hair_ribbon_right.pin_particle(0);
        hair_ribbon_right
            .add_sphere_collider(VerletSphereCollider::new(Vec3::new(0.0, 1.32, 0.0), 0.22));
        let mut sword_tassel: VerletRopeSolver = VerletRopeSolver::new(
            5,
            0.09,
            Vec3::new(0.70, 0.90, 0.20),
            Vec3::new(0.0, -1.0, -0.2),
        );
        sword_tassel.pin_particle(0);
        Self {
            robe_cloth,
            hair_ribbon_left,
            hair_ribbon_right,
            sword_tassel,
            average_displacement_m: 0.0,
        }
    }

    /// Steps all Verlet cloth and ribbon chains using live wind, ultimate qi blasts, and moving head/pelvis anchors.
    ///
    /// # Arguments
    ///
    /// - `f32` - Timestep in seconds.
    /// - `Vec3` - Ambient mountain wind + sword-qi blast acceleration vector.
    /// - `Vec3` - Live world-space pelvis position.
    /// - `Vec3` - Live world-space head topknot position.
    ///
    /// # Returns
    ///
    /// - `(f32, f32, f32, f32)` - Derived `(hem_pitch, hem_roll, hair_l_swing, hair_r_swing)` angles in radians.
    pub fn step_physics(
        &mut self,
        dt_secs: f32,
        wind_accel: Vec3,
        pelvis_world: Vec3,
        head_world: Vec3,
    ) -> (f32, f32, f32, f32) {
        let dt: f32 = dt_secs.clamp(0.002, 0.033);
        {
            let cloth: &mut VerletClothSolver = self.get_mut_robe_cloth();
            let _: &mut VerletClothSolver = cloth.set_wind(wind_accel);
            for col in 0..5usize {
                let offset_x: f32 = ((col as f32) - 2.0) * 0.16;
                let anchor: Vec3 = pelvis_world.add(Vec3::new(offset_x, 0.0, -0.16));
                if let Some(part) = cloth.get_mut_particles().get_mut(col) {
                    let _: &mut VerletParticle3D = part
                        .set_position(anchor)
                        .set_prev_position(anchor)
                        .set_inv_mass(0.0);
                }
            }
            if let Some(sphere) = cloth.get_mut_sphere_colliders().first_mut() {
                let _: &mut VerletSphereCollider =
                    sphere.set_center(pelvis_world.add(Vec3::new(0.0, -0.32, 0.0)));
            }
            cloth.step(dt);
        }
        {
            let left: &mut VerletRopeSolver = self.get_mut_hair_ribbon_left();
            let _: &mut VerletRopeSolver = left.set_wind(wind_accel.scale(1.35));
            let anchor_l: Vec3 = head_world.add(Vec3::new(-0.08, 0.12, -0.10));
            if let Some(p0) = left.get_mut_particles().first_mut() {
                let _: &mut VerletParticle3D = p0
                    .set_position(anchor_l)
                    .set_prev_position(anchor_l)
                    .set_inv_mass(0.0);
            }
            left.step(dt);
        }
        {
            let right: &mut VerletRopeSolver = self.get_mut_hair_ribbon_right();
            let _: &mut VerletRopeSolver = right.set_wind(wind_accel.scale(1.25));
            let anchor_r: Vec3 = head_world.add(Vec3::new(0.08, 0.12, -0.10));
            if let Some(p0) = right.get_mut_particles().first_mut() {
                let _: &mut VerletParticle3D = p0
                    .set_position(anchor_r)
                    .set_prev_position(anchor_r)
                    .set_inv_mass(0.0);
            }
            right.step(dt);
        }
        {
            let tassel: &mut VerletRopeSolver = self.get_mut_sword_tassel();
            let _: &mut VerletRopeSolver = tassel.set_wind(wind_accel.scale(1.1));
            tassel.step(dt);
        }
        let cloth_parts: &[VerletParticle3D] = self.get_robe_cloth().get_particles().as_slice();
        let mut disp_sum: f32 = 0.0;
        let mut z_sway: f32 = 0.0;
        let mut x_sway: f32 = 0.0;
        let mut free_count: f32 = 0.0;
        for (idx, p) in cloth_parts.iter().enumerate() {
            if idx < 5 {
                continue;
            }
            let row: usize = idx / 5;
            let col: usize = idx % 5;
            let rest_p: Vec3 = pelvis_world.add(Vec3::new(
                ((col as f32) - 2.0) * 0.16,
                -(row as f32) * 0.15,
                -0.16,
            ));
            let delta: Vec3 = p.get_position().sub(rest_p);
            disp_sum += delta.length();
            x_sway += delta.get_x();
            z_sway += delta.get_z();
            free_count += 1.0;
        }
        let avg_disp: f32 = if free_count > 0.0 {
            disp_sum / free_count
        } else {
            0.0
        };
        let _: &mut Self = self.set_average_displacement_m(avg_disp);
        let hem_pitch: f32 = ((z_sway / free_count.max(1.0)) * 1.45).clamp(-0.68, 0.68);
        let hem_roll: f32 = ((x_sway / free_count.max(1.0)) * 1.35).clamp(-0.55, 0.55);
        let left_tip: Vec3 = self
            .get_hair_ribbon_left()
            .get_particles()
            .last()
            .map_or(Vec3::zero(), VerletParticle3D::get_position);
        let right_tip: Vec3 = self
            .get_hair_ribbon_right()
            .get_particles()
            .last()
            .map_or(Vec3::zero(), VerletParticle3D::get_position);
        let hair_l_swing: f32 = ((left_tip.get_z() - head_world.get_z()) * 0.85).clamp(-0.75, 0.75);
        let hair_r_swing: f32 =
            ((right_tip.get_z() - head_world.get_z()) * 0.85).clamp(-0.75, 0.75);
        (hem_pitch, hem_roll, hair_l_swing, hair_r_swing)
    }
}

/// Complete animation, IK, Verlet cloth, Shape-Key, Ultimate VFX, and Blender render-mode runtime for `JianlaiSceneController`.
impl JianlaiSceneController {
    /// Creates a new `JianlaiSceneController` bound to `handles` and `materials` in default Ink-Wash Donghua mode.
    ///
    /// # Arguments
    ///
    /// - `JianlaiSceneHandles` - Scene object, bone node, skin, and VFX index registry.
    /// - `JianlaiStyleMaterialIds` - Pre-registered Principled material slot table.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized controller ready for per-frame stepping.
    #[must_use]
    pub fn new(handles: JianlaiSceneHandles, materials: JianlaiStyleMaterialIds) -> Self {
        Self {
            handles,
            materials,
            cloth_sim: JianlaiClothSim::create(),
            active_action: JianlaiAction::InkStance,
            prev_action: JianlaiAction::InkStance,
            crossfade_remaining_secs: 0.0,
            render_mode: JianlaiRenderMode::InkWashDonghua,
            debug_channel: JianlaiDebugChannel::Normals,
            skinning_mode: SkinningMode::DualQuaternion,
            ik_enabled: true,
            cloth_enabled: true,
            show_bones: false,
            freestyle_enabled: true,
            morph_aura_weight: 0.22,
            action_time_secs: 0.0,
            total_time_secs: 0.0,
            last_ik_error: 0.0,
            last_ik_iterations: 0,
            ultimate_charge: 0.0,
            camera_trauma: 0.0,
            sky: PhysicalSky3D::new(),
            volumetric_fog: VolumetricFogVolume3D::default(),
            postfx_config: PostFxConfig3D::default(),
        }
    }

    /// Initiates a smooth NLA crossfade transition onto `action` and resets the action timeline for crisp ultimate playback.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world owning `animation_mixer`.
    /// - `JianlaiAction` - Target martial arts or ultimate action.
    pub fn select_action(&mut self, world: &mut World3D, action: JianlaiAction) {
        let prev: JianlaiAction = self.get_active_action();
        let _: &mut Self = self
            .set_prev_action(prev)
            .set_active_action(action)
            .set_crossfade_remaining_secs(JIANLAI_NLA_CROSSFADE_SECS)
            .set_action_time_secs(0.0);
        if action.is_ultimate() {
            let _: &mut Self = self.set_ultimate_charge(1.0);
        }
        let mixer: &mut AnimationMixer3D = world.get_mut_animation_mixer();
        mixer.clear_layers();
        if prev != action {
            let mut fade_out: NlaLayer3D = NlaLayer3D::new(prev.as_index()).with_weight(1.0);
            fade_out.start_crossfade(0.0, JIANLAI_NLA_CROSSFADE_SECS);
            let _: usize = mixer.push_layer(fade_out);
            let mut fade_in: NlaLayer3D = NlaLayer3D::new(action.as_index()).with_weight(0.0);
            fade_in.start_crossfade(1.0, JIANLAI_NLA_CROSSFADE_SECS);
            let _: usize = mixer.push_layer(fade_in);
        } else {
            let _: usize = mixer.push_layer(NlaLayer3D::new(action.as_index()).with_weight(1.0));
        }
        self.step(world, 1.0 / 60.0);
    }

    /// Scrubs the active NLA timeline forward or backward by `delta_secs` and immediately evaluates deformation and VFX.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `f32` - Timeline scrub delta in seconds.
    pub fn scrub_timeline(&mut self, world: &mut World3D, delta_secs: f32) {
        let dur: f32 = self.get_active_action().duration_secs().max(0.1);
        let next_t: f32 = (self.get_action_time_secs() + delta_secs).rem_euclid(dur);
        let _: &mut Self = self.set_action_time_secs(next_t);
        for layer in world.get_mut_animation_mixer().get_mut_layers().iter_mut() {
            let _: &mut NlaLayer3D = layer.set_time_secs(next_t);
        }
        self.step(world, 0.002);
    }

    /// Switches the hero armature skinning solver live between `SkinningMode::LinearBlend` (LBS) and `SkinningMode::DualQuaternion` (DQS).
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `SkinningMode` - Target skinning deformation algorithm.
    pub fn set_skinning(&mut self, world: &mut World3D, mode: SkinningMode) {
        let _: &mut Self = self.set_skinning_mode(mode);
        let skin_idx: usize = self.get_handles().get_hero_skin_idx();
        let _: bool = world.set_skinning_mode(skin_idx, mode);
        let _: usize = world.update_deformed_meshes();
        world.bump_world_revision();
    }

    /// Updates the live Shape Key Battle Aura morph weight (`0.0..=1.0`) on both the hero and Freestyle outline mesh.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `f32` - Normalized Battle Aura morph weight in `[0.0, 1.0]`.
    pub fn set_morph_aura(&mut self, world: &mut World3D, weight: f32) {
        let clamped: f32 = weight.clamp(0.0, 1.0);
        let _: &mut Self = self.set_morph_aura_weight(clamped);
        let wind_billow: f32 = (0.18 + clamped * 0.65).clamp(0.0, 1.0);
        let hero_node: u32 = self.get_handles().get_hero_node_id();
        world
            .get_mut_scene_graph()
            .update_morph_weights(hero_node, &[clamped, wind_billow]);
        if let Some(out_idx) = self.get_handles().get_hero_outline_obj_idx()
            && let Some(out_node) = world
                .get_objects()
                .get(out_idx)
                .and_then(SceneObject3D::try_get_node_id)
        {
            world
                .get_mut_scene_graph()
                .update_morph_weights(out_node, &[clamped, wind_billow]);
        }
        let _: usize = world.update_deformed_meshes();
        world.bump_world_revision();
    }

    /// Toggles Freestyle inverted-hull calligraphy ink outlines visibility.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `bool` - Whether Freestyle outlines should be visible.
    pub fn set_freestyle_outlines(&mut self, world: &mut World3D, enabled: bool) {
        let _: &mut Self = self.set_freestyle_enabled(enabled);
        let mode: JianlaiRenderMode = self.get_render_mode();
        let show_outlines: bool = match mode {
            JianlaiRenderMode::InkWashDonghua | JianlaiRenderMode::EeveeVolumetric => enabled,
            JianlaiRenderMode::ShaderDebugPass => {
                self.get_debug_channel() == JianlaiDebugChannel::FreestyleInkContour
            }
            _ => false,
        };
        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, show_outlines);
        world.bump_world_revision();
    }

    /// Toggles the 3D 27-bone octahedral armature skeleton visualizer overlay.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `bool` - Whether the bone visualizer overlay is visible.
    pub fn set_bones_overlay(&mut self, world: &mut World3D, enabled: bool) {
        let _: &mut Self = self.set_show_bones(enabled);
        let show_armature: bool =
            enabled || self.get_render_mode() == JianlaiRenderMode::WireframeArmature;
        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_ARMATURE, show_armature);
        let show_wire: bool = self.get_render_mode() == JianlaiRenderMode::WireframeArmature;
        let wire_indices: Vec<usize> = self.get_handles().get_wireframe_cage_obj_indices().clone();
        for w_idx in wire_indices {
            if let Some(nid) = world
                .get_objects()
                .get(w_idx)
                .and_then(SceneObject3D::try_get_node_id)
                && let Some(node) = world
                    .get_mut_scene_graph()
                    .get_mut_nodes()
                    .get_mut(nid as usize)
            {
                let _: &mut SceneNode3D = node.set_visible(show_wire);
            }
        }
        world.bump_world_revision();
    }

    /// Switches live across all 6 Blender render & inspection modes (`InkWashDonghua`, `CyclesPbr`, `EeveeVolumetric`, `SolidMatcap`, `WireframeArmature`, `ShaderDebugPass`).
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world whose materials, sky, lighting, and overlays are reconfigured.
    /// - `JianlaiRenderMode` - Target Blender render mode.
    pub fn apply_render_mode(&mut self, world: &mut World3D, mode: JianlaiRenderMode) {
        let _: &mut Self = self.set_render_mode(mode);
        let mats: JianlaiStyleMaterialIds = self.get_materials();
        let slots: Vec<(usize, u32)> = self.get_handles().get_scene_material_slots().clone();
        let assign_slot: fn(&mut World3D, usize, u32) =
            |w: &mut World3D, obj_idx: usize, mat_id: u32| {
                let legacy: PbrMaterial = w
                    .get_principled_materials()
                    .get(mat_id as usize)
                    .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
                if let Some(obj) = w.get_mut_objects().get_mut(obj_idx) {
                    let _: &mut SceneObject3D = obj
                        .set_principled_material_id(Some(mat_id))
                        .set_material(legacy);
                }
            };
        match mode {
            JianlaiRenderMode::InkWashDonghua => {
                for (obj_idx, base_mat) in slots {
                    assign_slot(world, obj_idx, base_mat);
                }
                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(10.5);
                let _: &mut DirectionalLight3D = sun
                    .set_direction(Vec3::new(0.46, 0.76, 0.45).normalize())
                    .set_color(Vec3::new(1.12, 1.08, 1.00))
                    .set_sky_zenith(Vec3::new(0.56, 0.68, 0.72))
                    .set_sky_horizon(Vec3::new(0.90, 0.92, 0.88));
                let _: &mut World3D = world.set_sun(sun);
                world.set_use_agx_tonemap(true);
                let _: bool = world.set_collection_visible(
                    JIANLAI_COLLECTION_OUTLINES,
                    self.get_freestyle_enabled(),
                );
                let _: bool = world
                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
            }
            JianlaiRenderMode::CyclesPbr => {
                for (obj_idx, base_mat) in slots {
                    assign_slot(world, obj_idx, base_mat);
                }
                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(14.0);
                let _: &mut DirectionalLight3D = sun
                    .set_direction(Vec3::new(0.62, 0.72, 0.32).normalize())
                    .set_color(Vec3::new(1.38, 1.32, 1.24))
                    .set_sky_zenith(Vec3::new(0.18, 0.32, 0.56))
                    .set_sky_horizon(Vec3::new(0.62, 0.72, 0.84));
                let _: &mut World3D = world.set_sun(sun);
                world.set_use_agx_tonemap(true);
                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
                let _: bool = world
                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
            }
            JianlaiRenderMode::EeveeVolumetric => {
                for (obj_idx, base_mat) in slots {
                    assign_slot(world, obj_idx, base_mat);
                }
                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(17.6);
                let _: &mut DirectionalLight3D = sun
                    .set_direction(Vec3::new(-0.52, 0.32, -0.78).normalize())
                    .set_color(Vec3::new(1.55, 0.96, 0.54))
                    .set_sky_zenith(Vec3::new(0.24, 0.28, 0.44))
                    .set_sky_horizon(Vec3::new(0.96, 0.68, 0.46));
                let _: &mut World3D = world.set_sun(sun);
                world.set_use_agx_tonemap(false);
                let _: bool = world.set_collection_visible(
                    JIANLAI_COLLECTION_OUTLINES,
                    self.get_freestyle_enabled(),
                );
                let _: bool = world
                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
            }
            JianlaiRenderMode::SolidMatcap => {
                for (obj_idx, _) in slots {
                    assign_slot(world, obj_idx, mats.get_matcap_clay());
                }
                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(12.5);
                let _: &mut DirectionalLight3D = sun
                    .set_direction(Vec3::new(0.35, 0.82, 0.46).normalize())
                    .set_color(Vec3::new(1.15, 1.12, 1.08))
                    .set_sky_zenith(Vec3::new(0.34, 0.36, 0.40))
                    .set_sky_horizon(Vec3::new(0.52, 0.54, 0.58));
                let _: &mut World3D = world.set_sun(sun);
                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
                let _: bool = world
                    .set_collection_visible(JIANLAI_COLLECTION_ARMATURE, self.get_show_bones());
            }
            JianlaiRenderMode::WireframeArmature => {
                for (obj_idx, _) in slots {
                    assign_slot(world, obj_idx, mats.get_ink_trim());
                }
                let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(13.0);
                let _: &mut DirectionalLight3D = sun
                    .set_direction(Vec3::new(0.25, 0.85, 0.45).normalize())
                    .set_sky_zenith(Vec3::new(0.08, 0.11, 0.15))
                    .set_sky_horizon(Vec3::new(0.14, 0.18, 0.24));
                let _: &mut World3D = world.set_sun(sun);
                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, false);
                let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_ARMATURE, true);
            }
            JianlaiRenderMode::ShaderDebugPass => {
                let channel: JianlaiDebugChannel = self.get_debug_channel();
                self.apply_debug_channel(world, channel);
            }
        }
        let show_wire: bool = mode == JianlaiRenderMode::WireframeArmature;
        let wire_indices: Vec<usize> = self.get_handles().get_wireframe_cage_obj_indices().clone();
        for w_idx in wire_indices {
            if let Some(nid) = world
                .get_objects()
                .get(w_idx)
                .and_then(SceneObject3D::try_get_node_id)
                && let Some(node) = world
                    .get_mut_scene_graph()
                    .get_mut_nodes()
                    .get_mut(nid as usize)
            {
                let _: &mut SceneNode3D = node.set_visible(show_wire);
            }
        }
        world.bump_world_revision();
    }

    /// Applies one of the four live shader debug pass channels (`Normals`, `RoughnessMetallic`, `Depth`, `FreestyleInkContour`).
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `JianlaiDebugChannel` - Target shader debug channel.
    pub fn apply_debug_channel(&mut self, world: &mut World3D, channel: JianlaiDebugChannel) {
        let _: &mut Self = self.set_debug_channel(channel);
        if self.get_render_mode() != JianlaiRenderMode::ShaderDebugPass {
            return;
        }
        let mats: JianlaiStyleMaterialIds = self.get_materials();
        let override_mat: u32 = match channel {
            JianlaiDebugChannel::Normals => mats.get_debug_normals(),
            JianlaiDebugChannel::RoughnessMetallic => mats.get_debug_rough_metal(),
            JianlaiDebugChannel::Depth => mats.get_debug_depth(),
            JianlaiDebugChannel::FreestyleInkContour => mats.get_debug_freestyle_paper(),
        };
        let legacy: PbrMaterial = world
            .get_principled_materials()
            .get(override_mat as usize)
            .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
        let slots: Vec<(usize, u32)> = self.get_handles().get_scene_material_slots().clone();
        for (obj_idx, _) in slots {
            if let Some(obj) = world.get_mut_objects().get_mut(obj_idx) {
                let _: &mut SceneObject3D = obj
                    .set_principled_material_id(Some(override_mat))
                    .set_material(legacy);
            }
        }
        let freestyle_pass: bool = channel == JianlaiDebugChannel::FreestyleInkContour;
        let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_OUTLINES, freestyle_pass);
        if freestyle_pass {
            let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(12.0);
            let _: &mut DirectionalLight3D = sun
                .set_sky_zenith(Vec3::new(0.95, 0.94, 0.90))
                .set_sky_horizon(Vec3::new(0.97, 0.96, 0.92));
            let _: &mut World3D = world.set_sun(sun);
        }
        world.bump_world_revision();
    }

    /// Updates a dynamic world object and its linked `SceneNode3D` transform cleanly in O(1).
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world.
    /// - `usize` - Object index inside `World3D::objects`.
    /// - `Transform3D` - New world-space TRS transform.
    pub(crate) fn update_dynamic_object(world: &mut World3D, obj_idx: usize, tr: Transform3D) {
        let local_bounds: Option<AxisAlignedBox3D> = world
            .get_objects()
            .get(obj_idx)
            .and_then(|o: &SceneObject3D| world.get_mesh_library().get(o.get_mesh_id()))
            .and_then(|chain: &MeshLodChain| chain.get_levels().first())
            .map(Mesh3D::get_bounds);
        let node_opt: Option<u32> = world
            .get_objects()
            .get(obj_idx)
            .and_then(SceneObject3D::try_get_node_id);
        if let Some(obj) = world.get_mut_objects().get_mut(obj_idx) {
            let _: &mut SceneObject3D = obj.set_transform(tr);
            if let Some(lb) = local_bounds {
                let _: &mut SceneObject3D = obj.set_world_bounds(tr.transform_bounds(lb));
            }
        }
        if let Some(nid) = node_opt {
            world.get_mut_scene_graph().set_local_trs(
                nid,
                tr.get_position(),
                tr.get_rotation(),
                tr.get_scale(),
            );
        }
    }

    /// 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`.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world updated in place with zero steady-state allocations.
    /// - `f32` - Frame delta time in seconds.
    pub fn step(&mut self, world: &mut World3D, dt_secs: f32) {
        let dt: f32 = if dt_secs.is_finite() && dt_secs > 0.0 {
            dt_secs.clamp(0.001, 0.05)
        } else {
            1.0 / 60.0
        };
        let action: JianlaiAction = self.get_active_action();
        let dur: f32 = action.duration_secs().max(0.1);
        let next_action_t: f32 = (self.get_action_time_secs() + dt).rem_euclid(dur);
        let next_total_t: f32 = self.get_total_time_secs() + dt;
        let next_fade: f32 = (self.get_crossfade_remaining_secs() - dt).max(0.0);
        let next_trauma: f32 = (self.get_camera_trauma() - dt * 1.4).max(0.0);
        let _: &mut Self = self
            .set_action_time_secs(next_action_t)
            .set_total_time_secs(next_total_t)
            .set_crossfade_remaining_secs(next_fade)
            .set_camera_trauma(next_trauma);
        // 1. Advance NLA animation layers onto the 27-bone scene graph.
        let _: usize = world.tick_animations(dt);
        let bone_nodes: [u32; JIANLAI_BONE_COUNT] = self.get_handles().get_bone_node_ids();
        let rest_trans: [Vec3; JIANLAI_BONE_COUNT] =
            self.get_handles().get_bone_rest_translations();
        // 2. Live Sword-Tip IK (`IkSolver3D::solve_two_bone` + `IkSolver3D::solve_fabrik`) on right sword arm!
        let mut ik_err: f32 = 0.0;
        let mut ik_iters: usize = 0;
        if self.get_ik_enabled() {
            let shoulder_pos: Vec3 = world
                .get_scene_graph()
                .get_nodes()
                .get(bone_nodes[BONE_SHOULDER_R] as usize)
                .map_or(Vec3::new(0.14, 1.48, 0.0), |n: &SceneNode3D| {
                    n.get_world_matrix().mul_point3(Vec3::zero())
                });
            let upper_pos: Vec3 = world
                .get_scene_graph()
                .get_nodes()
                .get(bone_nodes[BONE_UPPER_ARM_R] as usize)
                .map_or(Vec3::new(0.26, 1.44, 0.0), |n: &SceneNode3D| {
                    n.get_world_matrix().mul_point3(Vec3::zero())
                });
            let phase: f32 = (next_action_t / dur) * TAU;
            let ik_target: Vec3 = match action {
                JianlaiAction::InkStance => upper_pos.add(Vec3::new(
                    0.34 + (phase).cos() * 0.06,
                    -0.16 + (phase * 2.0).sin() * 0.05,
                    0.26,
                )),
                JianlaiAction::FlowingSwordDance => upper_pos.add(Vec3::new(
                    0.38 * phase.cos(),
                    0.18 * (phase * 2.0).sin(),
                    0.38 * phase.sin().abs() + 0.14,
                )),
                JianlaiAction::MyriadSwordsReturn => {
                    upper_pos.add(Vec3::new(0.22, 0.34 + 0.08 * phase.sin(), 0.24))
                }
                JianlaiAction::SkyCleavingSwordQi => {
                    let norm_t: f32 = next_action_t / dur;
                    if norm_t < 0.32 {
                        upper_pos.add(Vec3::new(0.12, 0.44, -0.10))
                    } else if norm_t < 0.56 {
                        upper_pos.add(Vec3::new(0.24, -0.18, 0.42))
                    } else {
                        upper_pos.add(Vec3::new(0.32, -0.22, 0.30))
                    }
                }
                JianlaiAction::CloudStepGlide => {
                    upper_pos.add(Vec3::new(0.42, -0.06 + 0.05 * phase.sin(), 0.12))
                }
            };
            let upper_len: f32 = rest_trans[BONE_FOREARM_R].length().max(0.22);
            let lower_len: f32 = rest_trans[BONE_HAND_R].length().max(0.20);
            let pole: Vec3 = shoulder_pos.add(Vec3::new(0.35, -0.25, -0.45));
            let two_bone: IkTwoBoneResult =
                IkSolver3D::solve_two_bone(upper_pos, upper_len, lower_len, ik_target, pole);
            let mut chain_pts: [Vec3; 3] =
                [upper_pos, two_bone.get_joint_mid(), two_bone.get_effector()];
            let seg_lens: [f32; 2] = [upper_len, lower_len];
            let fabrik: IkChainResult =
                IkSolver3D::solve_fabrik(&mut chain_pts, &seg_lens, ik_target, 0.005, 8);
            ik_err = two_bone.get_error().min(fabrik.get_error());
            ik_iters = fabrik.get_iterations().max(1);
            let upper_q: Quat = two_bone.get_upper_rotation();
            let lower_rel: Quat = upper_q
                .conjugate()
                .mul_quat(two_bone.get_lower_rotation())
                .normalize();
            let sg: &mut SceneGraph3D = world.get_mut_scene_graph();
            if let Some(u_node) = sg.get_nodes().get(bone_nodes[BONE_UPPER_ARM_R] as usize) {
                let blended_u: Quat = u_node.get_local_rotation().slerp(upper_q, 0.32);
                let cur_t: Vec3 = u_node.get_local_translation();
                let cur_s: Vec3 = u_node.get_local_scale();
                sg.set_local_trs(bone_nodes[BONE_UPPER_ARM_R], cur_t, blended_u, cur_s);
            }
            if let Some(f_node) = sg.get_nodes().get(bone_nodes[BONE_FOREARM_R] as usize) {
                let blended_f: Quat = f_node.get_local_rotation().slerp(lower_rel, 0.32);
                let cur_t: Vec3 = f_node.get_local_translation();
                let cur_s: Vec3 = f_node.get_local_scale();
                sg.set_local_trs(bone_nodes[BONE_FOREARM_R], cur_t, blended_f, cur_s);
            }
        }
        let _: &mut Self = self
            .set_last_ik_error(ik_err)
            .set_last_ik_iterations(ik_iters);
        // 3. Step live Verlet cloth & hair ribbon physics and apply dynamic robe/hair bone sway.
        let pelvis_world: Vec3 = world
            .get_scene_graph()
            .get_nodes()
            .get(bone_nodes[BONE_PELVIS] as usize)
            .map_or(Vec3::new(0.0, 0.96, 0.0), |n: &SceneNode3D| {
                n.get_world_matrix().mul_point3(Vec3::zero())
            });
        let head_world: Vec3 = world
            .get_scene_graph()
            .get_nodes()
            .get(bone_nodes[BONE_HEAD] as usize)
            .map_or(Vec3::new(0.0, 1.72, 0.0), |n: &SceneNode3D| {
                n.get_world_matrix().mul_point3(Vec3::zero())
            });
        let qi_wind_boost: f32 = if action.is_ultimate() { 8.5 } else { 2.4 };
        let wind_vec: Vec3 = Vec3::new(
            (next_total_t * 1.7).sin() * 2.2,
            0.8 + (next_total_t * 2.9).cos() * 0.6,
            -qi_wind_boost - (next_total_t * 2.3).sin().abs() * 2.8,
        );
        if self.get_cloth_enabled() {
            let (hem_p, hem_r, hair_l, hair_r): (f32, f32, f32, f32) = self
                .get_mut_cloth_sim()
                .step_physics(dt, wind_vec, pelvis_world, head_world);
            let sg: &mut SceneGraph3D = world.get_mut_scene_graph();
            let cloth_bones: [(usize, Quat); 6] = [
                (
                    BONE_HEM_FRONT,
                    Quat::from_euler_yxz(0.0, -hem_p.abs() * 0.45, hem_r),
                ),
                (
                    BONE_HEM_BACK,
                    Quat::from_euler_yxz(0.0, hem_p.abs() * 0.85, -hem_r),
                ),
                (
                    BONE_HEM_LEFT,
                    Quat::from_euler_yxz(0.0, hem_p * 0.3, -hem_r.abs() - 0.16),
                ),
                (
                    BONE_HEM_RIGHT,
                    Quat::from_euler_yxz(0.0, hem_p * 0.3, hem_r.abs() + 0.16),
                ),
                (BONE_HAIR_L, Quat::from_euler_yxz(0.12, hair_l, -0.18)),
                (BONE_HAIR_R, Quat::from_euler_yxz(-0.12, hair_r, 0.18)),
            ];
            for (b_idx, b_rot) in cloth_bones {
                sg.set_local_trs(
                    bone_nodes[b_idx],
                    rest_trans[b_idx],
                    b_rot,
                    Vec3::splat(1.0),
                );
            }
        }
        // 4. Modulate live Shape Key battle aura surge during ultimates & propagate deformed meshes.
        let base_aura: f32 = self.get_morph_aura_weight();
        let effective_aura: f32 = if action.is_ultimate() {
            (base_aura + 0.45 * ((next_action_t / dur) * PI).sin()).clamp(0.0, 1.0)
        } else {
            base_aura
        };
        let wind_morph: f32 =
            (0.20 + effective_aura * 0.55 + (next_total_t * 2.4).sin().abs() * 0.25)
                .clamp(0.0, 1.0);
        let hero_node: u32 = self.get_handles().get_hero_node_id();
        world
            .get_mut_scene_graph()
            .update_morph_weights(hero_node, &[effective_aura, wind_morph]);
        if let Some(out_idx) = self.get_handles().get_hero_outline_obj_idx()
            && let Some(out_node) = world
                .get_objects()
                .get(out_idx)
                .and_then(SceneObject3D::try_get_node_id)
        {
            world
                .get_mut_scene_graph()
                .update_morph_weights(out_node, &[effective_aura, wind_morph]);
        }
        let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
        let _: usize = world.update_deformed_meshes();
        // 5. Update Primary Spirit Sword & Floating Scabbard from live `SwordSocket` bone world matrix.
        let socket_world: Mat4 = world
            .get_scene_graph()
            .get_nodes()
            .get(bone_nodes[BONE_SWORD_SOCKET] as usize)
            .map_or_else(Mat4::identity, SceneNode3D::get_world_matrix);
        let (sock_pos, sock_rot, _): (Vec3, Quat, Vec3) = socket_world.decompose_trs();
        let sword_tr: Transform3D = match action {
            JianlaiAction::CloudStepGlide => Transform3D::from_trs(
                pelvis_world.add(Vec3::new(0.0, -0.92, 0.12)),
                Quat::from_euler_yxz(0.0, FRAC_PI_2, 0.08 * (next_total_t * 2.4).sin()),
                Vec3::splat(1.32),
            ),
            JianlaiAction::MyriadSwordsReturn => Transform3D::from_trs(
                pelvis_world.add(Vec3::new(
                    0.85,
                    0.45 + 0.14 * (next_total_t * 3.0).sin(),
                    0.45,
                )),
                Quat::from_euler_yxz(next_total_t * 0.9, 0.35, -0.18),
                Vec3::splat(1.12),
            ),
            _ => Transform3D::from_trs(
                sock_pos,
                sock_rot
                    .mul_quat(Quat::from_euler_yxz(0.0, 0.72, -0.22))
                    .normalize(),
                Vec3::splat(1.06),
            ),
        };
        let sword_obj: usize = self.get_handles().get_sword_obj_idx();
        Self::update_dynamic_object(world, sword_obj, sword_tr);
        if let Some(out_idx) = self.get_handles().get_sword_outline_obj_idx() {
            Self::update_dynamic_object(world, out_idx, sword_tr);
        }
        let scabbard_tr: Transform3D = Transform3D::from_trs(
            pelvis_world.add(Vec3::new(
                -0.28,
                0.42 + (next_total_t * 2.1).sin() * 0.06,
                -0.36,
            )),
            Quat::from_euler_yxz(0.18, 0.06 * (next_total_t * 1.4).cos(), 0.44),
            Vec3::splat(1.0),
        );
        let scabbard_obj: usize = self.get_handles().get_scabbard_obj_idx();
        Self::update_dynamic_object(world, scabbard_obj, scabbard_tr);
        // 6. Animate Ultimate VFX: 18-Sword Bagua Halo, Sky-Cleaving Crescent Qi Wave, Ink Shockwave Ring, Sword Trail & Niagara Particles!
        self.update_ultimate_vfx(world, pelvis_world, sword_tr);
        // 7. Update all 26 Octahedral Armature Bone Visualizer prisms from live bone world positions.
        let prism_indices: Vec<usize> = self.get_handles().get_bone_prism_obj_indices().clone();
        for (slot_idx, prism_obj) in prism_indices.iter().enumerate() {
            let child_idx: usize = slot_idx + 1;
            let parent_idx: usize = JIANLAI_BONE_PARENTS[child_idx].unwrap_or(0);
            let p_pos: Vec3 = world
                .get_scene_graph()
                .get_nodes()
                .get(bone_nodes[parent_idx] as usize)
                .map_or(Vec3::zero(), |n: &SceneNode3D| {
                    n.get_world_matrix().mul_point3(Vec3::zero())
                });
            let c_pos: Vec3 = world
                .get_scene_graph()
                .get_nodes()
                .get(bone_nodes[child_idx] as usize)
                .map_or(Vec3::zero(), |n: &SceneNode3D| {
                    n.get_world_matrix().mul_point3(Vec3::zero())
                });
            let seg: Vec3 = c_pos.sub(p_pos);
            let len: f32 = seg.length().max(0.06);
            let dir: Vec3 = seg.scale(1.0 / len);
            let up_axis: Vec3 = Vec3::new(0.0, 1.0, 0.0);
            let rot: Quat = quat_between_unit_vectors(up_axis, dir);
            let bone_tr: Transform3D =
                Transform3D::from_trs(p_pos, rot, Vec3::new(len * 0.42, len, len * 0.42));
            Self::update_dynamic_object(world, *prism_obj, bone_tr);
        }
        // 8. Gently drift the 6 Xuan-paper ink-cloud mist ribbons around the cliff abyss.
        let cloud_indices: Vec<usize> = self.get_handles().get_cloud_ribbon_obj_indices().clone();
        for (idx, c_obj) in cloud_indices.iter().enumerate() {
            let base_ang: f32 = ((idx as f32) / 6.0) * TAU + next_total_t * 0.065;
            let rad: f32 = 8.4 + (idx as f32) * 1.45;
            let y_h: f32 =
                -1.55 + ((idx % 3) as f32) * 1.55 + (next_total_t * 0.5 + idx as f32).sin() * 0.22;
            let cl_tr: Transform3D = Transform3D::new(
                Vec3::new(rad * base_ang.cos(), y_h, rad * base_ang.sin()),
                base_ang + FRAC_PI_2,
                Vec3::new(1.28, 1.0, 1.28),
            );
            Self::update_dynamic_object(world, *c_obj, cl_tr);
        }
        // 9. Advance Niagara 3D ink droplets and golden sword-qi spark particles.
        let _: usize = world.get_mut_niagara().update(dt, 0.02);
        let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
        world.bump_world_revision();
    }

    /// Drives the 18-sword Bagua halo array, colossal Sky-Cleaving crescent wave, ink-splash shockwave ring, sword-arc trail, and Niagara bursts.
    ///
    /// # Arguments
    ///
    /// - `&mut World3D` - Mutable world owning VFX objects and `NiagaraSystem3D`.
    /// - `Vec3` - Hero pelvis world position.
    /// - `Transform3D` - Live primary spirit sword world transform.
    fn update_ultimate_vfx(
        &mut self,
        world: &mut World3D,
        pelvis_world: Vec3,
        sword_tr: Transform3D,
    ) {
        let action: JianlaiAction = self.get_active_action();
        let action_t: f32 = self.get_action_time_secs();
        let dur: f32 = action.duration_secs().max(0.1);
        let total_t: f32 = self.get_total_time_secs();
        let norm_t: f32 = (action_t / dur).clamp(0.0, 1.0);
        let myriad_indices: Vec<usize> = self.get_handles().get_myriad_sword_obj_indices().clone();
        let crescent_obj: usize = self.get_handles().get_crescent_qi_obj_idx();
        let shock_obj: usize = self.get_handles().get_shockwave_ring_obj_idx();
        let trail_obj: usize = self.get_handles().get_sword_trail_obj_idx();
        let parked: Transform3D =
            Transform3D::new(Vec3::new(0.0, -4.5, 0.0), 0.0, Vec3::splat(0.001));
        match action {
            JianlaiAction::MyriadSwordsReturn => {
                let deploy: f32 = (norm_t * 3.2).clamp(0.0, 1.0);
                let barrage_t: f32 = ((norm_t - 0.52) / 0.42).clamp(0.0, 1.0);
                let _: &mut Self = self.set_ultimate_charge((0.55 + 0.45 * deploy).clamp(0.0, 1.0));
                for (idx, s_obj) in myriad_indices.iter().enumerate() {
                    let is_inner: bool = idx < 6;
                    let ring_n: f32 = if is_inner { 6.0 } else { 12.0 };
                    let ring_i: f32 = if is_inner {
                        idx as f32
                    } else {
                        (idx - 6) as f32
                    };
                    let spin_dir: f32 = if is_inner { 1.35 } else { -0.95 };
                    let ang: f32 = (ring_i / ring_n) * TAU + total_t * spin_dir;
                    let base_rad: f32 = if is_inner { 1.55 } else { 2.55 };
                    let rad: f32 = base_rad * (0.35 + 0.65 * deploy);
                    let z_launch: f32 = -1.15 + barrage_t * (5.2 + (idx % 4) as f32 * 0.9);
                    let pos: Vec3 = Vec3::new(
                        pelvis_world.get_x() + rad * ang.cos(),
                        pelvis_world.get_y() + 1.15 + rad * ang.sin() * 0.78,
                        pelvis_world.get_z() + z_launch,
                    );
                    let pitch: f32 = if barrage_t > 0.05 { FRAC_PI_2 } else { 0.32 };
                    let s_tr: Transform3D = Transform3D::from_trs(
                        pos,
                        Quat::from_euler_yxz(0.0, pitch, ang - FRAC_PI_2),
                        Vec3::splat(0.82 * deploy.max(0.15)),
                    );
                    Self::update_dynamic_object(world, *s_obj, s_tr);
                }
                let halo_scale: f32 = 1.2 + deploy * 1.45;
                Self::update_dynamic_object(
                    world,
                    shock_obj,
                    Transform3D::from_trs(
                        pelvis_world.add(Vec3::new(0.0, 1.15, -1.25)),
                        Quat::from_euler_yxz(0.0, FRAC_PI_2, total_t * 1.1),
                        Vec3::splat(halo_scale),
                    ),
                );
                Self::update_dynamic_object(world, crescent_obj, parked);
                Self::update_dynamic_object(world, trail_obj, parked);
                let mut emitter: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
                let _: &mut NiagaraEmitterConfig3D = emitter
                    .set_origin(pelvis_world.add(Vec3::new(0.0, 1.2, -0.8)))
                    .set_base_velocity(Vec3::new(0.0, 0.8, 3.6))
                    .set_velocity_spread(2.4)
                    .set_start_size_m(0.09)
                    .set_end_size_m(0.02)
                    .set_start_color(Color::rgba(255, 214, 92, 235))
                    .set_end_color(Color::rgba(72, 236, 240, 40))
                    .set_emissive_boost(2.2);
                world.get_mut_niagara().emit_burst(6, &emitter);
            }
            JianlaiAction::SkyCleavingSwordQi => {
                let charge_phase: bool = norm_t < 0.34;
                let cleave_t: f32 = ((norm_t - 0.34) / 0.56).clamp(0.0, 1.0);
                let charge_val: f32 = if charge_phase {
                    (norm_t / 0.34).clamp(0.0, 1.0)
                } else {
                    (1.0 - cleave_t * 0.7).clamp(0.0, 1.0)
                };
                let _: &mut Self = self.set_ultimate_charge(charge_val);
                if norm_t > 0.33 && norm_t < 0.42 {
                    let _: &mut Self = self.set_camera_trauma(0.95);
                }
                for (idx, s_obj) in myriad_indices.iter().enumerate() {
                    let ang: f32 =
                        ((idx as f32) / (JIANLAI_MYRIAD_SWORD_COUNT as f32)) * TAU + total_t * 1.8;
                    let r: f32 = 2.8 - charge_val * 0.85;
                    let pos: Vec3 =
                        Vec3::new(r * ang.cos(), 0.45 + (idx % 3) as f32 * 0.45, r * ang.sin());
                    let scale_s: f32 = if idx < 6 { 0.55 } else { 0.001 };
                    Self::update_dynamic_object(
                        world,
                        *s_obj,
                        Transform3D::from_trs(
                            pos,
                            Quat::from_euler_yxz(-ang, 0.25, 0.0),
                            Vec3::splat(scale_s),
                        ),
                    );
                }
                if !charge_phase && cleave_t < 0.96 {
                    let wave_z: f32 = 0.85 + cleave_t * 11.5;
                    let wave_s: f32 = 0.65 + (cleave_t * PI).sin() * 1.15;
                    Self::update_dynamic_object(
                        world,
                        crescent_obj,
                        Transform3D::from_trs(
                            Vec3::new(0.0, 2.25, wave_z),
                            Quat::from_euler_yxz(0.0, 0.0, 0.16),
                            Vec3::splat(wave_s),
                        ),
                    );
                    let ring_s: f32 = 0.75 + cleave_t * 3.8;
                    Self::update_dynamic_object(
                        world,
                        shock_obj,
                        Transform3D::new(
                            Vec3::new(0.0, 0.16, 0.0),
                            total_t * 2.5,
                            Vec3::new(ring_s, 0.8, ring_s),
                        ),
                    );
                } else {
                    Self::update_dynamic_object(world, crescent_obj, parked);
                    let charge_ring: f32 = 0.55 + charge_val * 0.95;
                    Self::update_dynamic_object(
                        world,
                        shock_obj,
                        Transform3D::new(
                            Vec3::new(0.0, 0.18, 0.0),
                            -total_t * 3.2,
                            Vec3::new(charge_ring, 0.6, charge_ring),
                        ),
                    );
                }
                Self::update_dynamic_object(world, trail_obj, parked);
                let mut ink_emit: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
                let _: &mut NiagaraEmitterConfig3D = ink_emit
                    .set_origin(Vec3::new(0.0, 1.35, 0.55 + cleave_t * 4.5))
                    .set_base_velocity(Vec3::new(0.0, 1.4, 5.2))
                    .set_velocity_spread(3.2)
                    .set_start_size_m(0.12)
                    .set_end_size_m(0.03)
                    .set_start_color(Color::rgba(24, 30, 42, 240))
                    .set_end_color(Color::rgba(255, 198, 62, 60))
                    .set_emissive_boost(2.4);
                world.get_mut_niagara().emit_burst(8, &ink_emit);
            }
            JianlaiAction::FlowingSwordDance => {
                let _: &mut Self = self.set_ultimate_charge(0.35);
                for s_obj in myriad_indices.iter() {
                    Self::update_dynamic_object(world, *s_obj, parked);
                }
                Self::update_dynamic_object(world, crescent_obj, parked);
                Self::update_dynamic_object(world, shock_obj, parked);
                Self::update_dynamic_object(
                    world,
                    trail_obj,
                    Transform3D::from_trs(
                        pelvis_world.add(Vec3::new(0.0, 0.35, 0.0)),
                        Quat::from_euler_yxz(total_t * 4.2, 0.24 * (total_t * 2.0).sin(), 0.28),
                        Vec3::splat(1.05),
                    ),
                );
                let mut spark: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
                let _: &mut NiagaraEmitterConfig3D = spark
                    .set_origin(sword_tr.get_position())
                    .set_base_velocity(Vec3::new(0.0, 0.6, 0.4))
                    .set_velocity_spread(1.6)
                    .set_start_size_m(0.07)
                    .set_end_size_m(0.015)
                    .set_start_color(Color::rgba(82, 238, 244, 220))
                    .set_end_color(Color::rgba(240, 248, 250, 20))
                    .set_emissive_boost(1.8);
                world.get_mut_niagara().emit_burst(4, &spark);
            }
            JianlaiAction::InkStance | JianlaiAction::CloudStepGlide => {
                let _: &mut Self = self.set_ultimate_charge(0.12);
                for (idx, s_obj) in myriad_indices.iter().enumerate() {
                    if idx < 4 {
                        let ang: f32 = ((idx as f32) / 4.0) * TAU + total_t * 0.65;
                        let pos: Vec3 = pelvis_world.add(Vec3::new(
                            1.35 * ang.cos(),
                            0.65 + (total_t * 1.6 + idx as f32).sin() * 0.14,
                            -0.85 + 0.45 * ang.sin(),
                        ));
                        Self::update_dynamic_object(
                            world,
                            *s_obj,
                            Transform3D::from_trs(
                                pos,
                                Quat::from_euler_yxz(ang, 0.08, 0.0),
                                Vec3::splat(0.52),
                            ),
                        );
                    } else {
                        Self::update_dynamic_object(world, *s_obj, parked);
                    }
                }
                Self::update_dynamic_object(world, crescent_obj, parked);
                Self::update_dynamic_object(world, shock_obj, parked);
                Self::update_dynamic_object(world, trail_obj, parked);
                let mut mote: NiagaraEmitterConfig3D = NiagaraEmitterConfig3D::default();
                let _: &mut NiagaraEmitterConfig3D = mote
                    .set_origin(pelvis_world.add(Vec3::new(0.0, 0.2, 0.0)))
                    .set_base_velocity(Vec3::new(0.0, 0.55, -0.4))
                    .set_velocity_spread(0.85)
                    .set_start_size_m(0.06)
                    .set_end_size_m(0.015)
                    .set_start_color(Color::rgba(148, 234, 226, 180))
                    .set_end_color(Color::rgba(242, 246, 244, 10))
                    .set_emissive_boost(1.2);
                world.get_mut_niagara().emit_burst(2, &mote);
            }
        }
    }

    /// Captures a structured `JianlaiRigMetrics` telemetry snapshot from the controller and `world`.
    ///
    /// # Arguments
    ///
    /// - `&World3D` - Active world providing live Niagara particle counts.
    ///
    /// # Returns
    ///
    /// - `JianlaiRigMetrics` - Complete live rigging, physics, VFX, and geometry metrics.
    #[must_use]
    pub fn metrics(&self, world: &World3D) -> JianlaiRigMetrics {
        let action: JianlaiAction = self.get_active_action();
        let active_swords: usize = match action {
            JianlaiAction::MyriadSwordsReturn => JIANLAI_MYRIAD_SWORD_COUNT,
            JianlaiAction::SkyCleavingSwordQi => 6,
            JianlaiAction::InkStance | JianlaiAction::CloudStepGlide => 4,
            JianlaiAction::FlowingSwordDance => 1,
        };
        JianlaiRigMetrics {
            bone_count: JIANLAI_BONE_COUNT,
            hero_vertices: self.get_handles().get_hero_vertices(),
            hero_triangles: self.get_handles().get_hero_triangles(),
            stage_triangles: self.get_handles().get_stage_triangles(),
            total_triangles: self.get_handles().get_total_triangles(),
            active_action: action,
            render_mode: self.get_render_mode(),
            debug_channel: self.get_debug_channel(),
            skinning_mode: self.get_skinning_mode(),
            ik_enabled: self.get_ik_enabled(),
            ik_error_m: self.get_last_ik_error(),
            ik_iterations: self.get_last_ik_iterations(),
            cloth_enabled: self.get_cloth_enabled(),
            cloth_displacement_m: self.get_cloth_sim().get_average_displacement_m(),
            morph_aura_weight: self.get_morph_aura_weight(),
            freestyle_enabled: self.get_freestyle_enabled(),
            show_bones: self.get_show_bones(),
            niagara_particles: world.get_niagara().get_active_count(),
            flying_swords_active: active_swords,
            ultimate_charge: self.get_ultimate_charge(),
            camera_trauma: self.get_camera_trauma(),
            timeline_secs: self.get_action_time_secs(),
            clip_duration_secs: action.duration_secs(),
        }
    }
}