alice-physics 1.1.0

Deterministic 128-bit Fixed-Point Physics Engine
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
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
//! Integrated CFD Solver (Session 3 S1)
//!
//! Wires together the Session 1-2 fluid modules into a single time-stepping
//! loop that a user can drive with `solver.step(dt)`. Combines:
//!
//! - MAC-grid velocity storage & pressure projection (`eulerian_grid`)
//! - Level-set fluid tracking + reinitialisation (`multiphase`, `interface_capture`)
//! - Continuum surface force (`surface_tension_csf`)
//! - Smagorinsky LES eddy viscosity (`turbulence`)
//! - Boussinesq buoyancy for hot fluid (`smoke_fire`)
//! - Gravity (uniform body force)
//!
//! # Step order
//!
//! ```text
//! 1. Add body forces  → gravity + buoyancy + CSF (into u/v/w)
//! 2. Turbulent viscosity → Smagorinsky ν_t (from local strain rate)
//! 3. Diffuse velocity (explicit Laplacian, coefficient = ν_mol + ν_t)
//! 4. Pressure projection (Jacobi from eulerian_grid)
//! 5. Advect level set (semi-Lagrangian, uniform velocity approx)
//! 6. Reinit level set (fast sweeping, every reinit_every_n steps)
//! ```
//!
//! This is a first-order operator-splitting scheme; adequate for engineering
//! demos and validation tests. Higher-order (BFECC advection, RK3 time,
//! multigrid pressure) is a future upgrade.

use crate::eulerian_grid::{
    g2p_velocity, project_pressure, sample_u_range, sample_u_trilinear, sample_v_range,
    sample_v_trilinear, sample_w_range, sample_w_trilinear, MacGrid,
};
use crate::interface_capture::fast_sweeping_reinit;
use crate::math::{Fix128, Vec3Fix};
use crate::multiphase::{trilinear_range, trilinear_sample, Grid3d};
use crate::surface_tension_csf::{compute_csf_field, SIGMA_WATER_AIR};
use crate::turbulence::{smagorinsky_eddy_viscosity, strain_rate_magnitude, SMAGORINSKY_CS};

/// Selects the advection scheme applied to velocity and temperature at
/// each solver step.
///
/// - `SemiLagrangian` (default): first-order back-trace with trilinear
///   sampling. Cheap, unconditionally stable, but adds numerical
///   diffusion on every step. Adequate for engineering demos and short
///   time horizons.
/// - `MacCormack`: two-pass predictor-corrector built on top of the
///   semi-Lagrangian primitive. Second-order accurate on smooth data,
///   preserving sharp gradients and small-scale features roughly one
///   order of magnitude longer than plain semi-Lagrangian. No monotone
///   flux limiter is applied — smooth initial data with the projection
///   stage tends to remain stable, but shocks or sharp discontinuities
///   can produce local over/under-shoots.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AdvectionScheme {
    /// Semi-Lagrangian back-trace with trilinear sampling (first-order).
    #[default]
    SemiLagrangian,
    /// MacCormack predictor-corrector (second-order, unlimited).
    MacCormack,
    /// **BFECC** (Back and Forth Error Compensation and Correction).
    ///
    /// Three semi-Lagrangian passes: predictor `φ̃ = A(φ_n)`, reverse
    /// `φ̂ = A⁻¹(φ̃)`, compensated `φ* = φ_n + ½ (φ_n − φ̂)`, final
    /// `φ_{n+1} = A(φ*)`. Second-order accurate on smooth data with
    /// noticeably less phase error than MacCormack; the extra pass
    /// costs ~30% more per step. Applied to both MAC-face velocity
    /// (`advect_velocity_bfecc`) and the temperature scalar field.
    Bfecc,
}

/// Complete CFD solver state.
pub struct CfdSolver {
    /// Velocity + pressure MAC grid.
    pub grid: MacGrid,
    /// Fluid level set (negative = liquid, positive = gas), optional.
    /// When present, CSF and level-set advection are executed.
    pub level_set: Option<Grid3d>,
    /// Temperature field (K), optional. Enables Boussinesq buoyancy.
    pub temperature: Option<Grid3d>,
    /// Advection scheme used for both velocity and temperature.
    pub advection_scheme: AdvectionScheme,
    /// Fluid density ρ (kg/m³).
    pub density_kg_m3: Fix128,
    /// Dynamic molecular viscosity μ (Pa·s).
    pub dynamic_viscosity_pas: Fix128,
    /// Gravity vector (m/s²), typically `(0, -9.81, 0)`.
    pub gravity: Vec3Fix,
    /// Surface tension σ (N/m), used only if `level_set` present.
    pub surface_tension_n_m: Fix128,
    /// Thermal expansion coefficient β (1/K), used only if `temperature` present.
    pub beta_per_k: Fix128,
    /// Reference temperature `T_0` (K) for Boussinesq.
    pub reference_temp_k: Fix128,
    /// Pressure-projection Jacobi iterations per step.
    pub jacobi_iterations: u32,
    /// Reinitialise the level set every N steps (0 = never).
    pub reinit_every_n_steps: u32,
    /// Simulation step counter.
    pub step_count: u64,
    /// Turbulence toggle: use Smagorinsky if `true`.
    pub use_turbulence: bool,
}

impl CfdSolver {
    /// Construct a solver with sensible default fluid = water at 20 °C.
    #[must_use]
    pub fn new(nx: usize, ny: usize, nz: usize, dx: Fix128) -> Self {
        Self {
            grid: MacGrid::new(nx, ny, nz, dx),
            level_set: None,
            temperature: None,
            advection_scheme: AdvectionScheme::SemiLagrangian,
            density_kg_m3: Fix128::from_int(1000),
            dynamic_viscosity_pas: Fix128::from_ratio(1, 1000), // 1e-3 (water)
            gravity: Vec3Fix::new(Fix128::ZERO, Fix128::from_ratio(-981, 100), Fix128::ZERO),
            surface_tension_n_m: SIGMA_WATER_AIR,
            beta_per_k: Fix128::from_ratio(34, 10_000), // air ≈ 3.4e-3
            reference_temp_k: Fix128::from_int(293),
            jacobi_iterations: 30,
            reinit_every_n_steps: 10,
            step_count: 0,
            use_turbulence: false,
        }
    }

    /// Largest `dt` satisfying `cfl_target = |u|_max · dt / dx`.
    ///
    /// Scans the current MAC-grid face velocities for the peak
    /// component magnitude, then inverts the Courant condition:
    ///
    /// ```text
    /// dt_max = cfl_target · dx / |u|_max
    /// ```
    ///
    /// Returns `Fix128::from_int(large_value)` if the velocity field is
    /// effectively zero (no CFL constraint), giving callers a
    /// well-defined upper bound to compare against a scheme-specific
    /// diffusion cap. `cfl_target` should typically be in `[0.5, 1.0]`
    /// for semi-Lagrangian and higher for BFECC / MacCormack when
    /// paired with a monotone clamp.
    #[must_use]
    pub fn compute_max_dt(&self, cfl_target: Fix128) -> Fix128 {
        let peak = self
            .grid
            .u
            .iter()
            .chain(self.grid.v.iter())
            .chain(self.grid.w.iter())
            .fold(Fix128::ZERO, |acc, &v| {
                let av = v.abs();
                if av > acc {
                    av
                } else {
                    acc
                }
            });
        if peak.is_zero() {
            return Fix128::from_int(1_000_000);
        }
        cfl_target * self.grid.dx / peak
    }

    /// Convenience — step with an automatically chosen `dt` from
    /// [`Self::compute_max_dt`], capped by `dt_ceiling`.
    ///
    /// Useful in engineering demos where the simulation should adapt
    /// to fast transients without the caller re-computing `dt` on each
    /// tick. Returns the `dt` that was actually integrated.
    pub fn step_adaptive(&mut self, cfl_target: Fix128, dt_ceiling: Fix128) -> Fix128 {
        let mut dt = self.compute_max_dt(cfl_target);
        if dt > dt_ceiling {
            dt = dt_ceiling;
        }
        self.step(dt);
        dt
    }

    /// One integrated time step.
    pub fn step(&mut self, dt_s: Fix128) {
        if dt_s.is_zero() {
            return;
        }
        match self.advection_scheme {
            AdvectionScheme::SemiLagrangian => self.advect_velocity(dt_s),
            AdvectionScheme::MacCormack => self.advect_velocity_maccormack(dt_s),
            AdvectionScheme::Bfecc => self.advect_velocity_bfecc(dt_s),
        }
        self.apply_body_forces(dt_s);
        if self.use_turbulence {
            self.apply_turbulent_diffusion(dt_s);
        } else {
            self.apply_molecular_diffusion(dt_s);
        }
        project_pressure(
            &mut self.grid,
            dt_s,
            self.density_kg_m3,
            self.jacobi_iterations,
        );
        if self.level_set.is_some() {
            self.advect_level_set(dt_s);
            if self.reinit_every_n_steps > 0
                && self.step_count > 0
                && self.step_count % u64::from(self.reinit_every_n_steps) == 0
            {
                if let Some(ls) = self.level_set.as_mut() {
                    fast_sweeping_reinit(ls, 2);
                }
            }
        }
        if self.temperature.is_some() {
            match self.advection_scheme {
                AdvectionScheme::SemiLagrangian => self.advect_temperature(dt_s),
                AdvectionScheme::MacCormack => self.advect_temperature_maccormack(dt_s),
                AdvectionScheme::Bfecc => self.advect_temperature_bfecc(dt_s),
            }
        }
        self.step_count += 1;
    }

    /// Step 1: Add body forces (gravity + buoyancy + surface tension).
    fn apply_body_forces(&mut self, dt_s: Fix128) {
        let g = self.gravity;
        // Uniform gravity to each face
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let ix = i + (self.grid.nx + 1) * (j + self.grid.ny * k);
                    if ix < self.grid.u.len() {
                        self.grid.u[ix] = self.grid.u[ix] + g.x * dt_s;
                    }
                }
            }
        }
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let ix = i + self.grid.nx * (j + (self.grid.ny + 1) * k);
                    if ix < self.grid.v.len() {
                        self.grid.v[ix] = self.grid.v[ix] + g.y * dt_s;
                    }
                }
            }
        }
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let ix = i + self.grid.nx * (j + self.grid.ny * k);
                    if ix < self.grid.w.len() {
                        self.grid.w[ix] = self.grid.w[ix] + g.z * dt_s;
                    }
                }
            }
        }

        // Boussinesq: add buoyancy from temperature deviation
        if let Some(temp) = self.temperature.as_ref() {
            for k in 0..self.grid.nz {
                for j in 0..=self.grid.ny {
                    for i in 0..self.grid.nx {
                        // Sample cell-centre temperature
                        let jj = if j == 0 { 0 } else { j - 1 };
                        let t = temp.get(i, jj, k);
                        let dt_temp = t - self.reference_temp_k;
                        let f = self.density_kg_m3 * self.beta_per_k * dt_temp * self.gravity.y;
                        let ix = i + self.grid.nx * (j + (self.grid.ny + 1) * k);
                        if ix < self.grid.v.len() {
                            self.grid.v[ix] = self.grid.v[ix] - f * dt_s / self.density_kg_m3;
                        }
                    }
                }
            }
        }

        // Continuum surface force from level set
        if let Some(ls) = self.level_set.as_ref() {
            let (fx, _fy, _fz) = compute_csf_field(
                ls,
                self.surface_tension_n_m,
                self.grid.dx * Fix128::from_ratio(15, 10),
            );
            // Apply to u faces (approximate; treats fx as cell-centered)
            for k in 0..self.grid.nz {
                for j in 0..self.grid.ny {
                    for i in 0..self.grid.nx {
                        let cell_idx = i + self.grid.nx * (j + self.grid.ny * k);
                        let force = fx[cell_idx];
                        // Distribute to two u faces (like p2g_nearest)
                        let ix_lo = i + (self.grid.nx + 1) * (j + self.grid.ny * k);
                        let ix_hi = (i + 1) + (self.grid.nx + 1) * (j + self.grid.ny * k);
                        if ix_lo < self.grid.u.len() {
                            self.grid.u[ix_lo] = self.grid.u[ix_lo]
                                + force * dt_s * Fix128::from_ratio(1, 2) / self.density_kg_m3;
                        }
                        if ix_hi < self.grid.u.len() {
                            self.grid.u[ix_hi] = self.grid.u[ix_hi]
                                + force * dt_s * Fix128::from_ratio(1, 2) / self.density_kg_m3;
                        }
                    }
                }
            }
        }
    }

    /// Molecular-only viscous diffusion via explicit Laplacian.
    fn apply_molecular_diffusion(&mut self, dt_s: Fix128) {
        if self.density_kg_m3.is_zero() {
            return;
        }
        let nu = self.dynamic_viscosity_pas / self.density_kg_m3;
        self.diffuse_velocity(nu, dt_s);
    }

    /// Smagorinsky-augmented diffusion: `ν_eff = ν_mol + ν_t`.
    fn apply_turbulent_diffusion(&mut self, dt_s: Fix128) {
        if self.density_kg_m3.is_zero() {
            return;
        }
        let nu_mol = self.dynamic_viscosity_pas / self.density_kg_m3;
        // Compute strain-rate magnitude at cell centres and take max as an
        // upper-bound proxy for the SGS eddy viscosity (simplification).
        let mut max_strain = Fix128::ZERO;
        for k in 1..self.grid.nz - 1 {
            for j in 1..self.grid.ny - 1 {
                for i in 1..self.grid.nx - 1 {
                    let s11 = (self.grid.u(i + 1, j, k) - self.grid.u(i, j, k)) / self.grid.dx;
                    let s22 = (self.grid.v(i, j + 1, k) - self.grid.v(i, j, k)) / self.grid.dx;
                    let s33 = (self.grid.w(i, j, k + 1) - self.grid.w(i, j, k)) / self.grid.dx;
                    let s = strain_rate_magnitude(
                        s11,
                        s22,
                        s33,
                        Fix128::ZERO,
                        Fix128::ZERO,
                        Fix128::ZERO,
                    );
                    if s > max_strain {
                        max_strain = s;
                    }
                }
            }
        }
        let nu_t = smagorinsky_eddy_viscosity(self.grid.dx, max_strain);
        let _ = SMAGORINSKY_CS; // referenced via smagorinsky_eddy_viscosity
        self.diffuse_velocity(nu_mol + nu_t, dt_s);
    }

    /// Explicit Laplacian: `u_new = u + dt·ν·∇²u`.
    fn diffuse_velocity(&mut self, nu: Fix128, dt_s: Fix128) {
        if nu.is_zero() || self.grid.dx.is_zero() {
            return;
        }
        let coeff = nu * dt_s / (self.grid.dx * self.grid.dx);

        // u faces
        let mut u_next = self.grid.u.clone();
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 1..self.grid.nx {
                    let center = self.grid.u(i, j, k);
                    let left = self.grid.u(i - 1, j, k);
                    let right = self.grid.u(i + 1, j, k);
                    let down = if j > 0 {
                        self.grid.u(i, j - 1, k)
                    } else {
                        center
                    };
                    let up = if j + 1 < self.grid.ny {
                        self.grid.u(i, j + 1, k)
                    } else {
                        center
                    };
                    let back = if k > 0 {
                        self.grid.u(i, j, k - 1)
                    } else {
                        center
                    };
                    let fwd = if k + 1 < self.grid.nz {
                        self.grid.u(i, j, k + 1)
                    } else {
                        center
                    };
                    let laplacian =
                        left + right + down + up + back + fwd - center * Fix128::from_int(6);
                    let ix = i + (self.grid.nx + 1) * (j + self.grid.ny * k);
                    u_next[ix] = center + coeff * laplacian;
                }
            }
        }
        self.grid.u = u_next;

        // v faces
        let mut v_next = self.grid.v.clone();
        for k in 0..self.grid.nz {
            for j in 1..self.grid.ny {
                for i in 0..self.grid.nx {
                    let center = self.grid.v(i, j, k);
                    let left = if i > 0 {
                        self.grid.v(i - 1, j, k)
                    } else {
                        center
                    };
                    let right = if i + 1 < self.grid.nx {
                        self.grid.v(i + 1, j, k)
                    } else {
                        center
                    };
                    let down = self.grid.v(i, j - 1, k);
                    let up = self.grid.v(i, j + 1, k);
                    let back = if k > 0 {
                        self.grid.v(i, j, k - 1)
                    } else {
                        center
                    };
                    let fwd = if k + 1 < self.grid.nz {
                        self.grid.v(i, j, k + 1)
                    } else {
                        center
                    };
                    let laplacian =
                        left + right + down + up + back + fwd - center * Fix128::from_int(6);
                    let ix = i + self.grid.nx * (j + (self.grid.ny + 1) * k);
                    v_next[ix] = center + coeff * laplacian;
                }
            }
        }
        self.grid.v = v_next;

        // w faces analogous
        let mut w_next = self.grid.w.clone();
        for k in 1..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let center = self.grid.w(i, j, k);
                    let left = if i > 0 {
                        self.grid.w(i - 1, j, k)
                    } else {
                        center
                    };
                    let right = if i + 1 < self.grid.nx {
                        self.grid.w(i + 1, j, k)
                    } else {
                        center
                    };
                    let down = if j > 0 {
                        self.grid.w(i, j - 1, k)
                    } else {
                        center
                    };
                    let up = if j + 1 < self.grid.ny {
                        self.grid.w(i, j + 1, k)
                    } else {
                        center
                    };
                    let back = self.grid.w(i, j, k - 1);
                    let fwd = self.grid.w(i, j, k + 1);
                    let laplacian =
                        left + right + down + up + back + fwd - center * Fix128::from_int(6);
                    let ix = i + self.grid.nx * (j + self.grid.ny * k);
                    w_next[ix] = center + coeff * laplacian;
                }
            }
        }
        self.grid.w = w_next;
    }

    /// Semi-Lagrangian self-advection of the MAC velocity field.
    ///
    /// Implements the `u · ∇u` transport term of the Navier–Stokes / Euler
    /// momentum equation. For each u/v/w face, back-traces along the current
    /// velocity by `dt_s` and resamples the corresponding face component
    /// from the pre-advection snapshot via trilinear interpolation on the
    /// respective staggered grid.
    ///
    /// Called at the start of `step` so that all subsequent operator stages
    /// (body forces, diffusion, projection) act on the transported field.
    /// This scheme is first-order in time and diffusive on coarse grids;
    /// higher-order variants (BFECC, MacCormack, RK3) are future upgrades.
    fn advect_velocity(&mut self, dt_s: Fix128) {
        let old = self.grid.clone();
        let dx = self.grid.dx;
        let half = Fix128::from_ratio(1, 2);

        // u faces
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&old, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let new_u = sample_u_trilinear(&old, back);
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < self.grid.u.len() {
                        self.grid.u[ix] = new_u;
                    }
                }
            }
        }

        // v faces
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&old, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let new_v = sample_v_trilinear(&old, back);
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < self.grid.v.len() {
                        self.grid.v[ix] = new_v;
                    }
                }
            }
        }

        // w faces
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&old, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let new_w = sample_w_trilinear(&old, back);
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < self.grid.w.len() {
                        self.grid.w[ix] = new_w;
                    }
                }
            }
        }
    }

    /// MacCormack predictor-corrector for MAC velocity self-advection.
    ///
    /// Runs one semi-Lagrangian pass forward (`φ̂ = SL(φ_n, dt)`), then
    /// reverse-advects `φ̂` by `-dt` using the pre-advection velocity
    /// `u_n` as the advecting field (`φ̃ = SL(φ̂, -dt; u_n)`), and applies
    /// the second-order MacCormack correction
    ///
    /// ```text
    /// φ_{n+1} = φ̂ + ½ · (φ_n − φ̃)
    /// ```
    ///
    /// followed by a Fedkiw-style monotone limiter: for each face the
    /// corrected value is clamped to the `[min, max]` interval spanned
    /// by the 8 neighbouring face-value corners on `u_n` at the back-
    /// traced position. Without this limiter the unlimited corrector
    /// injects super-linear vorticity growth on the paper's
    /// axisymmetric swirl setup and diverges within tens of steps.
    fn advect_velocity_maccormack(&mut self, dt_s: Fix128) {
        let u_n = self.grid.clone();

        // Predictor: reuse the existing semi-Lagrangian pass.
        self.advect_velocity(dt_s);
        let phi_hat = self.grid.clone();

        // Corrector: reverse-advect phi_hat using u_n's velocity by
        // forward-tracing with +dt (equivalent to back-trace with -dt).
        let dx = self.grid.dx;
        let half = Fix128::from_ratio(1, 2);
        let mut u_tilde = vec![Fix128::ZERO; self.grid.u.len()];
        let mut v_tilde = vec![Fix128::ZERO; self.grid.v.len()];
        let mut w_tilde = vec![Fix128::ZERO; self.grid.w.len()];

        // u faces
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < u_tilde.len() {
                        u_tilde[ix] = sample_u_trilinear(&phi_hat, forward);
                    }
                }
            }
        }
        // v faces
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < v_tilde.len() {
                        v_tilde[ix] = sample_v_trilinear(&phi_hat, forward);
                    }
                }
            }
        }
        // w faces
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < w_tilde.len() {
                        w_tilde[ix] = sample_w_trilinear(&phi_hat, forward);
                    }
                }
            }
        }

        // Apply MacCormack correction: φ_{n+1} = φ̂ + ½ · (φ_n − φ̃).
        for ((dst, &hat), (&n_val, &tilde)) in self
            .grid
            .u
            .iter_mut()
            .zip(phi_hat.u.iter())
            .zip(u_n.u.iter().zip(u_tilde.iter()))
        {
            *dst = hat + half * (n_val - tilde);
        }
        for ((dst, &hat), (&n_val, &tilde)) in self
            .grid
            .v
            .iter_mut()
            .zip(phi_hat.v.iter())
            .zip(u_n.v.iter().zip(v_tilde.iter()))
        {
            *dst = hat + half * (n_val - tilde);
        }
        for ((dst, &hat), (&n_val, &tilde)) in self
            .grid
            .w
            .iter_mut()
            .zip(phi_hat.w.iter())
            .zip(u_n.w.iter().zip(w_tilde.iter()))
        {
            *dst = hat + half * (n_val - tilde);
        }

        // Monotonicity guard: clamp each face component to the local
        // pre-advection range at the back-traced position on `u_n`.
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_u_range(&u_n, back);
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < self.grid.u.len() {
                        let val = self.grid.u[ix];
                        self.grid.u[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_v_range(&u_n, back);
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < self.grid.v.len() {
                        let val = self.grid.v[ix];
                        self.grid.v[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_w_range(&u_n, back);
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < self.grid.w.len() {
                        let val = self.grid.w[ix];
                        self.grid.w[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
    }

    /// MacCormack predictor-corrector for the temperature scalar field.
    ///
    /// Mirrors `advect_velocity_maccormack` on a single cell-centred
    /// scalar. The advecting velocity is `self.grid` at call time (the
    /// projected divergence-free field), consistent with the
    /// semi-Lagrangian variant.
    fn advect_temperature_maccormack(&mut self, dt_s: Fix128) {
        if self.temperature.is_none() {
            return;
        }
        let phi_n = self
            .temperature
            .as_ref()
            .map(|t| t.data.clone())
            .unwrap_or_default();

        // Predictor: reuse existing SL pass.
        self.advect_temperature(dt_s);

        // Snapshot phi_hat and prepare reverse sampling grid.
        let (nx_t, ny_t, nz_t, dx_t, phi_hat) = {
            let temp = self
                .temperature
                .as_ref()
                .expect("temperature checked above");
            (temp.nx, temp.ny, temp.nz, temp.dx, temp.data.clone())
        };
        let phi_hat_grid = Grid3d {
            nx: nx_t,
            ny: ny_t,
            nz: nz_t,
            dx: dx_t,
            data: phi_hat.clone(),
        };
        let inv_dx = Fix128::ONE / dx_t;
        let half = Fix128::from_ratio(1, 2);
        let mut phi_tilde = vec![Fix128::ZERO; phi_hat.len()];
        for k in 0..nz_t {
            for j in 0..ny_t {
                for i in 0..nx_t {
                    let (uc, vc, wc) = self.grid.cell_velocity(
                        i.min(self.grid.nx - 1),
                        j.min(self.grid.ny - 1),
                        k.min(self.grid.nz - 1),
                    );
                    // Forward-trace = reverse advection with -dt.
                    let cx = Fix128::from_int(i as i64) + uc * dt_s * inv_dx;
                    let cy = Fix128::from_int(j as i64) + vc * dt_s * inv_dx;
                    let cz = Fix128::from_int(k as i64) + wc * dt_s * inv_dx;
                    let sampled = trilinear_sample(&phi_hat_grid, cx, cy, cz);
                    phi_tilde[i + nx_t * (j + ny_t * k)] = sampled;
                }
            }
        }

        // Apply MacCormack correction.
        if let Some(temp) = self.temperature.as_mut() {
            for ((dst, &hat), (&n_val, &tilde)) in temp
                .data
                .iter_mut()
                .zip(phi_hat.iter())
                .zip(phi_n.iter().zip(phi_tilde.iter()))
            {
                *dst = hat + half * (n_val - tilde);
            }
        }

        // Monotonicity guard: clamp to pre-advection range at back-trace
        // position on the pre-advection temperature field.
        let phi_n_grid = Grid3d {
            nx: nx_t,
            ny: ny_t,
            nz: nz_t,
            dx: dx_t,
            data: phi_n,
        };
        if let Some(temp) = self.temperature.as_mut() {
            for k in 0..nz_t {
                for j in 0..ny_t {
                    for i in 0..nx_t {
                        let (uc, vc, wc) = self.grid.cell_velocity(
                            i.min(self.grid.nx - 1),
                            j.min(self.grid.ny - 1),
                            k.min(self.grid.nz - 1),
                        );
                        let cx = Fix128::from_int(i as i64) - uc * dt_s * inv_dx;
                        let cy = Fix128::from_int(j as i64) - vc * dt_s * inv_dx;
                        let cz = Fix128::from_int(k as i64) - wc * dt_s * inv_dx;
                        let (lo, hi) = trilinear_range(&phi_n_grid, cx, cy, cz);
                        let ix = i + nx_t * (j + ny_t * k);
                        let val = temp.data[ix];
                        temp.data[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
    }

    /// BFECC advection of the MAC velocity field (u/v/w faces).
    ///
    /// Full three-pass BFECC on all three staggered components:
    ///
    /// ```text
    /// φ̂  = SL(φ_n, +dt; u_n)      // predictor
    /// φ̃  = SL(φ̂, -dt; u_n)       // reverse
    /// φ*  = φ_n + ½ (φ_n − φ̃)     // compensated input
    /// φ_{n+1} = SL(φ*, +dt; u_n)   // final SL from the compensated field
    /// ```
    ///
    /// The final result is clipped to the pre-advection back-trace range
    /// on `u_n` for monotonicity, matching the MacCormack limiter
    /// convention already applied in [`advect_velocity_maccormack`].
    ///
    /// Compared to MacCormack, BFECC pays one extra semi-Lagrangian
    /// pass but removes the phase-error residual on the compensator,
    /// giving cleaner spectra on smooth flow.
    #[allow(clippy::too_many_lines)] // canonical 3-pass BFECC structure
    fn advect_velocity_bfecc(&mut self, dt_s: Fix128) {
        let u_n = self.grid.clone();
        let dx = self.grid.dx;
        let half = Fix128::from_ratio(1, 2);

        // Pass 1 — forward SL: φ̂ = SL(φ_n, +dt).
        self.advect_velocity(dt_s);
        let phi_hat = self.grid.clone();

        // Pass 2 — reverse SL on φ̂ using u_n's advecting field:
        // φ̃ = SL(φ̂, -dt; u_n).
        let mut u_tilde = vec![Fix128::ZERO; self.grid.u.len()];
        let mut v_tilde = vec![Fix128::ZERO; self.grid.v.len()];
        let mut w_tilde = vec![Fix128::ZERO; self.grid.w.len()];
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < u_tilde.len() {
                        u_tilde[ix] = sample_u_trilinear(&phi_hat, forward);
                    }
                }
            }
        }
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < v_tilde.len() {
                        v_tilde[ix] = sample_v_trilinear(&phi_hat, forward);
                    }
                }
            }
        }
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let forward = Vec3Fix::new(
                        pos.x + dt_s * vel.x,
                        pos.y + dt_s * vel.y,
                        pos.z + dt_s * vel.z,
                    );
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < w_tilde.len() {
                        w_tilde[ix] = sample_w_trilinear(&phi_hat, forward);
                    }
                }
            }
        }

        // Pass 3 — build the compensated input φ* = φ_n + ½(φ_n − φ̃).
        // 演算順序は index 版と同一 (決定論性維持): un + half * (un - ut)
        let mut phi_star = u_n.clone();
        for (ps, (un, ut)) in phi_star.u.iter_mut().zip(u_n.u.iter().zip(u_tilde.iter())) {
            *ps = *un + half * (*un - *ut);
        }
        for (ps, (un, ut)) in phi_star.v.iter_mut().zip(u_n.v.iter().zip(v_tilde.iter())) {
            *ps = *un + half * (*un - *ut);
        }
        for (ps, (un, ut)) in phi_star.w.iter_mut().zip(u_n.w.iter().zip(w_tilde.iter())) {
            *ps = *un + half * (*un - *ut);
        }

        // Pass 4 — final SL from φ* using u_n's advecting field.
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < self.grid.u.len() {
                        self.grid.u[ix] = sample_u_trilinear(&phi_star, back);
                    }
                }
            }
        }
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < self.grid.v.len() {
                        self.grid.v[ix] = sample_v_trilinear(&phi_star, back);
                    }
                }
            }
        }
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < self.grid.w.len() {
                        self.grid.w[ix] = sample_w_trilinear(&phi_star, back);
                    }
                }
            }
        }

        // Monotonicity guard — clamp each face component to the local
        // pre-advection range at the back-traced position on `u_n`.
        for k in 0..self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..=self.grid.nx {
                    let px = Fix128::from_int(i as i64) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_u_range(&u_n, back);
                    let ix = self.grid.idx_u(i, j, k);
                    if ix < self.grid.u.len() {
                        let val = self.grid.u[ix];
                        self.grid.u[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
        for k in 0..self.grid.nz {
            for j in 0..=self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = Fix128::from_int(j as i64) * dx;
                    let pz = (Fix128::from_int(k as i64) + half) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_v_range(&u_n, back);
                    let ix = self.grid.idx_v(i, j, k);
                    if ix < self.grid.v.len() {
                        let val = self.grid.v[ix];
                        self.grid.v[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
        for k in 0..=self.grid.nz {
            for j in 0..self.grid.ny {
                for i in 0..self.grid.nx {
                    let px = (Fix128::from_int(i as i64) + half) * dx;
                    let py = (Fix128::from_int(j as i64) + half) * dx;
                    let pz = Fix128::from_int(k as i64) * dx;
                    let pos = Vec3Fix::new(px, py, pz);
                    let vel = g2p_velocity(&u_n, pos);
                    let back = Vec3Fix::new(
                        pos.x - dt_s * vel.x,
                        pos.y - dt_s * vel.y,
                        pos.z - dt_s * vel.z,
                    );
                    let (lo, hi) = sample_w_range(&u_n, back);
                    let ix = self.grid.idx_w(i, j, k);
                    if ix < self.grid.w.len() {
                        let val = self.grid.w[ix];
                        self.grid.w[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
    }

    /// BFECC advection of the temperature scalar field.
    ///
    /// Implements the three-pass Back-and-Forth Error Compensation and
    /// Correction scheme: forward SL, reverse SL, compensate, final SL.
    /// Under smooth flow the phase error is one order lower than plain
    /// semi-Lagrangian and slightly better than MacCormack; a
    /// monotonicity clamp against the pre-advection field prevents
    /// runaway over/undershoots.
    fn advect_temperature_bfecc(&mut self, dt_s: Fix128) {
        if self.temperature.is_none() {
            return;
        }
        let phi_n = self
            .temperature
            .as_ref()
            .map(|t| t.data.clone())
            .unwrap_or_default();
        let (nx_t, ny_t, nz_t, dx_t) = {
            let temp = self
                .temperature
                .as_ref()
                .expect("temperature checked above");
            (temp.nx, temp.ny, temp.nz, temp.dx)
        };
        let inv_dx = Fix128::ONE / dx_t;
        let half = Fix128::from_ratio(1, 2);

        // Pass 1 — forward SL predictor: φ̃ = A(φ_n) in place.
        self.advect_temperature(dt_s);
        let phi_hat = self
            .temperature
            .as_ref()
            .map(|t| t.data.clone())
            .unwrap_or_default();
        let phi_hat_grid = Grid3d {
            nx: nx_t,
            ny: ny_t,
            nz: nz_t,
            dx: dx_t,
            data: phi_hat.clone(),
        };

        // Pass 2 — reverse SL: φ̂ = A⁻¹(φ̃), by forward-tracing.
        let mut phi_reverse = vec![Fix128::ZERO; phi_hat.len()];
        for k in 0..nz_t {
            for j in 0..ny_t {
                for i in 0..nx_t {
                    let (uc, vc, wc) = self.grid.cell_velocity(
                        i.min(self.grid.nx - 1),
                        j.min(self.grid.ny - 1),
                        k.min(self.grid.nz - 1),
                    );
                    let cx = Fix128::from_int(i as i64) + uc * dt_s * inv_dx;
                    let cy = Fix128::from_int(j as i64) + vc * dt_s * inv_dx;
                    let cz = Fix128::from_int(k as i64) + wc * dt_s * inv_dx;
                    phi_reverse[i + nx_t * (j + ny_t * k)] =
                        trilinear_sample(&phi_hat_grid, cx, cy, cz);
                }
            }
        }

        // Pass 3 — compensate the input: φ* = φ_n + ½ (φ_n − φ̂) at each cell,
        // then run one more forward SL from φ*.
        let mut phi_star = vec![Fix128::ZERO; phi_n.len()];
        for i in 0..phi_n.len() {
            phi_star[i] = phi_n[i] + half * (phi_n[i] - phi_reverse[i]);
        }
        let phi_star_grid = Grid3d {
            nx: nx_t,
            ny: ny_t,
            nz: nz_t,
            dx: dx_t,
            data: phi_star,
        };
        if let Some(temp) = self.temperature.as_mut() {
            for k in 0..nz_t {
                for j in 0..ny_t {
                    for i in 0..nx_t {
                        let (uc, vc, wc) = self.grid.cell_velocity(
                            i.min(self.grid.nx - 1),
                            j.min(self.grid.ny - 1),
                            k.min(self.grid.nz - 1),
                        );
                        let cx = Fix128::from_int(i as i64) - uc * dt_s * inv_dx;
                        let cy = Fix128::from_int(j as i64) - vc * dt_s * inv_dx;
                        let cz = Fix128::from_int(k as i64) - wc * dt_s * inv_dx;
                        let sampled = trilinear_sample(&phi_star_grid, cx, cy, cz);
                        let ix = temp.idx(i, j, k);
                        temp.data[ix] = sampled;
                    }
                }
            }
        }

        // Monotonicity guard against the pre-advection field.
        let phi_n_grid = Grid3d {
            nx: nx_t,
            ny: ny_t,
            nz: nz_t,
            dx: dx_t,
            data: phi_n,
        };
        if let Some(temp) = self.temperature.as_mut() {
            for k in 0..nz_t {
                for j in 0..ny_t {
                    for i in 0..nx_t {
                        let (uc, vc, wc) = self.grid.cell_velocity(
                            i.min(self.grid.nx - 1),
                            j.min(self.grid.ny - 1),
                            k.min(self.grid.nz - 1),
                        );
                        let cx = Fix128::from_int(i as i64) - uc * dt_s * inv_dx;
                        let cy = Fix128::from_int(j as i64) - vc * dt_s * inv_dx;
                        let cz = Fix128::from_int(k as i64) - wc * dt_s * inv_dx;
                        let (lo, hi) = trilinear_range(&phi_n_grid, cx, cy, cz);
                        let ix = i + nx_t * (j + ny_t * k);
                        let val = temp.data[ix];
                        temp.data[ix] = clamp(val, lo, hi);
                    }
                }
            }
        }
    }

    /// Semi-Lagrangian advection of the temperature field using cell-centred
    /// velocity from the projected MAC grid.
    ///
    /// Called after `project_pressure` on each step when `temperature` is
    /// present. Implements the `∂_t θ + u · ∇θ = 0` transport half of the
    /// Boussinesq system; the buoyancy source is handled by
    /// `apply_body_forces` and pairs with this term to complete the
    /// physically consistent inviscid Boussinesq step.
    fn advect_temperature(&mut self, dt_s: Fix128) {
        let temp = match self.temperature.as_mut() {
            Some(t) => t,
            None => return,
        };
        let old = temp.data.clone();
        let old_grid = Grid3d {
            nx: temp.nx,
            ny: temp.ny,
            nz: temp.nz,
            dx: temp.dx,
            data: old,
        };
        let inv_dx = Fix128::ONE / temp.dx;
        for k in 0..temp.nz {
            for j in 0..temp.ny {
                for i in 0..temp.nx {
                    let (uc, vc, wc) = self.grid.cell_velocity(
                        i.min(self.grid.nx - 1),
                        j.min(self.grid.ny - 1),
                        k.min(self.grid.nz - 1),
                    );
                    let cx = Fix128::from_int(i as i64) - uc * dt_s * inv_dx;
                    let cy = Fix128::from_int(j as i64) - vc * dt_s * inv_dx;
                    let cz = Fix128::from_int(k as i64) - wc * dt_s * inv_dx;
                    let sampled = trilinear_sample(&old_grid, cx, cy, cz);
                    let ix = temp.idx(i, j, k);
                    temp.data[ix] = sampled;
                }
            }
        }
    }

    /// Semi-Lagrangian advection of the level set using cell-centred velocity.
    fn advect_level_set(&mut self, dt_s: Fix128) {
        let ls = match self.level_set.as_mut() {
            Some(ls) => ls,
            None => return,
        };
        let old = ls.data.clone();
        let old_grid = Grid3d {
            nx: ls.nx,
            ny: ls.ny,
            nz: ls.nz,
            dx: ls.dx,
            data: old,
        };
        let inv_dx = Fix128::ONE / ls.dx;
        for k in 0..ls.nz {
            for j in 0..ls.ny {
                for i in 0..ls.nx {
                    // Cell-centred velocity from the MAC grid
                    let (uc, vc, wc) = self.grid.cell_velocity(
                        i.min(self.grid.nx - 1),
                        j.min(self.grid.ny - 1),
                        k.min(self.grid.nz - 1),
                    );
                    let cx = Fix128::from_int(i as i64) - uc * dt_s * inv_dx;
                    let cy = Fix128::from_int(j as i64) - vc * dt_s * inv_dx;
                    let cz = Fix128::from_int(k as i64) - wc * dt_s * inv_dx;
                    let sampled = trilinear_sample(&old_grid, cx, cy, cz);
                    let ix = ls.idx(i, j, k);
                    ls.data[ix] = sampled;
                }
            }
        }
    }
}

fn clamp(value: Fix128, lo: Fix128, hi: Fix128) -> Fix128 {
    if value < lo {
        lo
    } else if value > hi {
        hi
    } else {
        value
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn solver_new_default_water() {
        let s = CfdSolver::new(4, 4, 4, Fix128::ONE);
        assert_eq!(s.density_kg_m3, Fix128::from_int(1000));
        assert!(s.dynamic_viscosity_pas > Fix128::ZERO);
        assert_eq!(s.step_count, 0);
    }

    #[test]
    fn step_zero_dt_no_op() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::ONE);
        s.step(Fix128::ZERO);
        assert_eq!(s.step_count, 0);
    }

    #[test]
    fn gravity_accelerates_velocity_downward() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::ONE);
        // Take a small step
        s.step(Fix128::from_ratio(1, 100));
        // v-faces should now have some negative velocity due to gravity
        let mut some_neg = false;
        for &vv in &s.grid.v {
            if vv < Fix128::ZERO {
                some_neg = true;
                break;
            }
        }
        assert!(some_neg, "Expected downward velocity component");
    }

    #[test]
    fn step_count_increments() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::ONE);
        for _ in 0..3 {
            s.step(Fix128::from_ratio(1, 100));
        }
        assert_eq!(s.step_count, 3);
    }

    #[test]
    fn projection_reduces_divergence_after_step() {
        // Set an artificial divergent velocity field
        let mut s = CfdSolver::new(4, 4, 4, Fix128::ONE);
        for i in 0..=4 {
            for j in 0..4 {
                for k in 0..4 {
                    let ix = i + 5 * (j + 4 * k);
                    if ix < s.grid.u.len() {
                        s.grid.u[ix] = Fix128::from_int(i as i64);
                    }
                }
            }
        }
        let div_before = s.grid.divergence(2, 2, 2).abs();
        s.step(Fix128::from_ratio(1, 100));
        let div_after = s.grid.divergence(2, 2, 2).abs();
        // After step (gravity + projection), divergence should decrease
        assert!(div_after < div_before);
    }

    #[test]
    fn turbulence_toggle_changes_effective_viscosity() {
        // Without turbulence, molecular only; with, larger effective ν.
        // Difficult to directly assert, but confirm no crash + step_count.
        let mut s = CfdSolver::new(6, 6, 6, Fix128::ONE);
        s.use_turbulence = true;
        // Give it a nonzero velocity so strain rate > 0
        for i in 1..6 {
            s.grid.u[i + 7 * (2 + 6 * 2)] = Fix128::from_int(i as i64);
        }
        s.step(Fix128::from_ratio(1, 1000));
        assert_eq!(s.step_count, 1);
    }

    #[test]
    fn level_set_advection_moves_interface() {
        let mut s = CfdSolver::new(6, 6, 6, Fix128::ONE);
        // Initialise a level set (sphere at (3,3,3), r=2)
        let mut ls = Grid3d::new(6, 6, 6, Fix128::ONE, Fix128::ZERO);
        crate::multiphase::initialize_level_set_sphere(
            &mut ls,
            Fix128::from_int(3),
            Fix128::from_int(3),
            Fix128::from_int(3),
            Fix128::from_int(2),
        );
        s.level_set = Some(ls);
        // Prescribe a positive u velocity everywhere
        for u in s.grid.u.iter_mut() {
            *u = Fix128::ONE;
        }
        let before = s.level_set.as_ref().unwrap().data.clone();
        s.step(Fix128::from_ratio(5, 10));
        let after = &s.level_set.as_ref().unwrap().data;
        // Field should change somewhere
        let mut changed = false;
        for i in 0..before.len() {
            if before[i] != after[i] {
                changed = true;
                break;
            }
        }
        assert!(changed);
    }

    // ---- BFECC advection tests -----------------------------------------

    fn setup_bfecc_solver(nx: usize) -> CfdSolver {
        let mut s = CfdSolver::new(nx, nx, nx, Fix128::from_ratio(1, 10));
        s.gravity = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        s.temperature = Some(Grid3d::new(nx, nx, nx, s.grid.dx, Fix128::from_int(293)));
        // Uniform u = 1 m/s along +x, everything else zero.
        for u in s.grid.u.iter_mut() {
            *u = Fix128::from_ratio(1, 2);
        }
        s
    }

    #[test]
    fn bfecc_advection_scheme_step_runs() {
        let mut s = setup_bfecc_solver(4);
        s.advection_scheme = AdvectionScheme::Bfecc;
        s.step(Fix128::from_ratio(1, 100));
        assert_eq!(s.step_count, 1);
    }

    #[test]
    fn bfecc_conserves_uniform_temperature_field() {
        let mut s = setup_bfecc_solver(4);
        s.advection_scheme = AdvectionScheme::Bfecc;
        // Ensure temperature is truly uniform (293 K) prior to step.
        let expected = Fix128::from_int(293);
        s.step(Fix128::from_ratio(1, 100));
        for &t in &s.temperature.as_ref().unwrap().data {
            assert!(
                (t - expected).abs() < Fix128::from_ratio(1, 100),
                "temp drift {:?}",
                t
            );
        }
    }

    #[test]
    fn bfecc_transports_temperature_bump() {
        let mut s = setup_bfecc_solver(6);
        s.advection_scheme = AdvectionScheme::Bfecc;
        // Place a hot cell at (1, 3, 3); after +x advection, some cell
        // downstream should exceed the reference by more than the pure
        // semi-Lagrangian smearing would allow.
        if let Some(temp) = s.temperature.as_mut() {
            let idx = temp.idx(1, 3, 3);
            temp.data[idx] = Fix128::from_int(500);
        }
        let before_max = s
            .temperature
            .as_ref()
            .unwrap()
            .data
            .iter()
            .copied()
            .fold(Fix128::ZERO, |acc, x| if x > acc { x } else { acc });
        for _ in 0..3 {
            s.step(Fix128::from_ratio(1, 100));
        }
        let after_max = s
            .temperature
            .as_ref()
            .unwrap()
            .data
            .iter()
            .copied()
            .fold(Fix128::ZERO, |acc, x| if x > acc { x } else { acc });
        // BFECC preserves the sharp bump much better than SL — the peak
        // must remain above 250 K (well above the reference of 293 K
        // and clearly non-diffused into oblivion).
        assert!(
            after_max > Fix128::from_int(250),
            "peak dropped: {:?}",
            after_max
        );
        // Bounded by pre-advection extremum (monotonicity guard).
        assert!(after_max <= before_max);
    }

    #[test]
    fn compute_max_dt_returns_large_dt_on_zero_velocity() {
        let s = CfdSolver::new(4, 4, 4, Fix128::from_ratio(1, 10));
        let dt = s.compute_max_dt(Fix128::from_ratio(5, 10));
        // With zero velocity the CFL is inactive; expect a big cap.
        assert!(dt > Fix128::from_int(1000));
    }

    #[test]
    fn compute_max_dt_inverts_cfl_condition() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::from_ratio(1, 10));
        for u in s.grid.u.iter_mut() {
            *u = Fix128::ONE; // 1 m/s uniform
        }
        // dx = 0.1, CFL = 0.5, dt = 0.5 * 0.1 / 1.0 = 0.05
        let dt = s.compute_max_dt(Fix128::from_ratio(5, 10));
        assert!((dt - Fix128::from_ratio(5, 100)).abs() < Fix128::from_ratio(1, 1000));
    }

    #[test]
    fn step_adaptive_respects_ceiling() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::from_ratio(1, 10));
        s.gravity = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        // Zero velocity → compute_max_dt returns huge; ceiling should
        // clamp the actually-integrated dt.
        let ceiling = Fix128::from_ratio(1, 100);
        let dt_used = s.step_adaptive(Fix128::from_ratio(5, 10), ceiling);
        assert_eq!(dt_used, ceiling);
        assert_eq!(s.step_count, 1);
    }

    #[test]
    fn bfecc_velocity_preserves_zero_field() {
        let mut s = CfdSolver::new(4, 4, 4, Fix128::from_ratio(1, 10));
        s.gravity = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        s.advection_scheme = AdvectionScheme::Bfecc;
        s.step(Fix128::from_ratio(1, 100));
        for &u in &s.grid.u {
            assert!(u.abs() < Fix128::from_ratio(1, 100));
        }
    }

    #[test]
    fn bfecc_velocity_transports_uniform_flow() {
        // Uniform u = 0.5 m/s along +x should remain approximately
        // uniform under BFECC self-advection (no gradient to advect).
        let mut s = CfdSolver::new(6, 6, 6, Fix128::from_ratio(1, 10));
        s.gravity = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        s.advection_scheme = AdvectionScheme::Bfecc;
        for u in s.grid.u.iter_mut() {
            *u = Fix128::from_ratio(1, 2);
        }
        s.step(Fix128::from_ratio(1, 100));
        // Interior u values should stay close to 0.5 (small boundary
        // clamping and projection deviations are acceptable).
        let mid = 3;
        let interior_u = s.grid.u[s.grid.idx_u(3, mid, mid)];
        assert!(
            (interior_u - Fix128::from_ratio(1, 2)).abs() < Fix128::from_ratio(1, 10),
            "interior u drifted: {interior_u:?}"
        );
    }

    #[test]
    fn bfecc_velocity_monotonicity_bounded_by_pre_advection() {
        // Give a smooth Gaussian-like u profile and step once — the
        // BFECC clamp should keep each face value bounded by its
        // back-traced pre-advection range.
        let mut s = CfdSolver::new(6, 6, 6, Fix128::from_ratio(1, 10));
        s.gravity = Vec3Fix::new(Fix128::ZERO, Fix128::ZERO, Fix128::ZERO);
        s.advection_scheme = AdvectionScheme::Bfecc;
        for i in 0..=6 {
            for j in 0..6 {
                for k in 0..6 {
                    let ix = s.grid.idx_u(i, j, k);
                    if ix < s.grid.u.len() {
                        // triangular ramp along x, peak = 1 at i=3
                        let dist = (i as i64 - 3).abs();
                        s.grid.u[ix] = Fix128::from_ratio(3 - dist, 3);
                    }
                }
            }
        }
        let pre_max = s
            .grid
            .u
            .iter()
            .fold(Fix128::ZERO, |a, &b| if b > a { b } else { a });
        s.step(Fix128::from_ratio(1, 100));
        let post_max = s
            .grid
            .u
            .iter()
            .fold(Fix128::ZERO, |a, &b| if b > a { b } else { a });
        // BFECC must not overshoot the initial peak by more than a
        // small tolerance (projection stage may nudge by ε).
        assert!(
            post_max <= pre_max + Fix128::from_ratio(1, 50),
            "overshoot: post={post_max:?} pre={pre_max:?}"
        );
    }
}