liquidwar7core 0.2.0

Liquidwar7 core logic library, low-level things which are game-engine agnostic.
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
// Copyright (C) 2025 Christian Mauduit <ufoot@ufoot.org>

//! World management for the game.
//!
//! This module contains the [`World`] struct which is the central game state,
//! managing the QuadMesh (for gradients and walkability), Grid (for fighter occupation),
//! teams, cursors, and armies.

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use shortestpath::{Gradient, Mesh};
use std::collections::{HashMap, HashSet, VecDeque};
use std::time::Instant;

use crate::quad_mesh::QuadMesh;
use crate::{Armies, Color, Cursor, Cursor3D, Fighter, FighterStatus, GameState, Grid, StepTiming, Team};

/// Action points added to each fighter per step.
pub const ACTION_POINTS_PER_STEP: f32 = 1.0;

/// Cost of a single move action (in action points).
pub const MOVE_COST: f32 = 1.0;

/// Minimum distance to cursor before considering "arrived" (same-cell direct movement).
const CURSOR_ARRIVAL_THRESHOLD: f32 = 0.01;

/// Lookahead factor for validating same-cell moves.
/// A move that stays in the same cell is only valid if moving 1.5x further would reach a different cell.
const SAME_CELL_LOOKAHEAD: f32 = 1.5;

/// Maximum fraction of walkable cells a single team can occupy (40%).
/// Spawning is refused if this limit would be exceeded.
pub const MAX_TEAM_OCCUPATION: f32 = 0.4;

/// Default attack factor: health lost by enemy per attack.
pub const DEFAULT_ATTACK_FACTOR: f32 = 0.1;

/// Default heal factor: health gained by ally per heal.
pub const DEFAULT_HEAL_FACTOR: f32 = 0.05;

/// Default convert factor: health of a fighter when converted to attacker's team.
pub const DEFAULT_CONVERT_FACTOR: f32 = 0.5;

/// Error type for spawn operations.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum SpawnError {
    /// The place at the given position is already occupied by another fighter.
    Occupied,
    /// The given position is not walkable (wall or out of bounds).
    NotWalkable,
    /// Not enough free places to spawn all requested fighters.
    InsufficientPlaces(usize),
    /// Spawning would exceed the maximum team occupation limit.
    OccupationLimitExceeded {
        /// Current number of fighters for the team.
        current: usize,
        /// Maximum allowed fighters for the team.
        max_allowed: usize,
    },
}

/// The central game state containing all game entities.
///
/// A `World` manages:
/// - `gradient_mesh` (QuadMesh): For gradient computation, direction lookups, and walkability
/// - `grid` (Grid): Simple 3D array for tracking which fighter occupies each cell
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct World {
    /// Mesh for gradient computation and walkability checks.
    gradient_mesh: QuadMesh,
    /// Simple 3D grid for fighter occupation tracking only.
    grid: Grid,
    teams: HashMap<u64, Team>,
    cursors: HashMap<u64, Cursor3D>,
    armies: Armies,
    /// Attack factor: health lost by enemy per attack.
    attack_factor: f32,
    /// Heal factor: health gained by ally per heal.
    heal_factor: f32,
    /// Convert factor: health of a fighter when converted to attacker's team.
    convert_factor: f32,
    #[cfg_attr(feature = "serde", serde(skip))]
    timing: StepTiming,
}

impl World {
    /// Creates a new World from a gradient mesh.
    ///
    /// The Grid is created with the same dimensions as the QuadMesh.
    /// Walkability is determined by QuadMesh, Grid only tracks fighters.
    pub fn new(gradient_mesh: QuadMesh) -> Self {
        let (width, height, depth) = gradient_mesh.dimensions();
        let grid = Grid::new(width, height, depth);

        Self {
            gradient_mesh,
            grid,
            teams: HashMap::new(),
            cursors: HashMap::new(),
            armies: Armies::new(),
            attack_factor: DEFAULT_ATTACK_FACTOR,
            heal_factor: DEFAULT_HEAL_FACTOR,
            convert_factor: DEFAULT_CONVERT_FACTOR,
            timing: StepTiming::new(),
        }
    }

    /// Returns a reference to the gradient mesh.
    pub fn gradient_mesh(&self) -> &QuadMesh {
        &self.gradient_mesh
    }

    /// Returns a reference to the grid.
    pub fn grid(&self) -> &Grid {
        &self.grid
    }

    /// Returns a mutable reference to the grid.
    pub fn grid_mut(&mut self) -> &mut Grid {
        &mut self.grid
    }

    /// Returns a reference to the underlying mesh (alias for gradient_mesh for compatibility).
    pub fn mesh(&self) -> &QuadMesh {
        &self.gradient_mesh
    }

    /// Returns a reference to the step timing accumulator.
    pub fn timing(&self) -> &StepTiming {
        &self.timing
    }

    /// Returns a mutable reference to the step timing accumulator.
    pub fn timing_mut(&mut self) -> &mut StepTiming {
        &mut self.timing
    }

    /// Returns the attack factor (health lost by enemy per attack).
    pub fn attack_factor(&self) -> f32 {
        self.attack_factor
    }

    /// Sets the attack factor (health lost by enemy per attack).
    pub fn set_attack_factor(&mut self, factor: f32) {
        self.attack_factor = factor.max(0.0);
    }

    /// Returns the heal factor (health gained by ally per heal).
    pub fn heal_factor(&self) -> f32 {
        self.heal_factor
    }

    /// Sets the heal factor (health gained by ally per heal).
    pub fn set_heal_factor(&mut self, factor: f32) {
        self.heal_factor = factor.max(0.0);
    }

    /// Returns the convert factor (health when converted to attacker's team).
    pub fn convert_factor(&self) -> f32 {
        self.convert_factor
    }

    /// Sets the convert factor (health when converted to attacker's team).
    pub fn set_convert_factor(&mut self, factor: f32) {
        self.convert_factor = factor.clamp(0.0, 1.0);
    }

    /// Returns the grid/mesh dimensions.
    pub fn dimensions(&self) -> (usize, usize, usize) {
        self.gradient_mesh.dimensions()
    }

    /// Checks if a cell is walkable (has a QuadMesh cell).
    #[inline]
    pub fn is_walkable(&self, x: usize, y: usize, z: usize) -> bool {
        self.gradient_mesh.cell_at(x, y, z).is_some()
    }

    /// Checks if a cell is walkable and has no fighter.
    #[inline]
    pub fn is_free(&self, x: usize, y: usize, z: usize) -> bool {
        self.is_walkable(x, y, z) && self.grid.is_cell_empty(x, y, z)
    }

    /// Generates a random u64 ID that doesn't collide with existing teams.
    fn generate_unique_team_id(&self) -> u64 {
        loop {
            let id = rand::random::<u64>();
            if !self.teams.contains_key(&id) {
                return id;
            }
        }
    }

    /// Generates a random u64 ID that doesn't collide with existing cursors.
    fn generate_unique_cursor_id(&self) -> u64 {
        loop {
            let id = rand::random::<u64>();
            if !self.cursors.contains_key(&id) {
                return id;
            }
        }
    }

    /// Adds a new team with the given color and name.
    pub fn add_team(&mut self, color: Color, name: String) -> u64 {
        let gradient = Gradient::from_mesh(&self.gradient_mesh);
        let team = Team::new(gradient, color, name);
        let team_id = self.generate_unique_team_id();
        self.teams.insert(team_id, team);
        team_id
    }

    /// Adds a new team with a specific ID.
    pub fn add_team_with_id(&mut self, team_id: u64, color: Color, name: String) {
        let gradient = Gradient::from_mesh(&self.gradient_mesh);
        let team = Team::new(gradient, color, name);
        self.teams.insert(team_id, team);
    }

    /// Removes a team by its ID.
    pub fn remove_team(&mut self, team_id: &u64) -> Option<Team> {
        self.teams.remove(team_id)
    }

    /// Returns a reference to the team with the given ID.
    pub fn get_team(&self, team_id: &u64) -> Option<&Team> {
        self.teams.get(team_id)
    }

    /// Returns a mutable reference to the team with the given ID.
    pub fn get_team_mut(&mut self, team_id: &u64) -> Option<&mut Team> {
        self.teams.get_mut(team_id)
    }

    /// Returns the number of teams.
    pub fn team_count(&self) -> usize {
        self.teams.len()
    }

    /// Returns an iterator over all teams.
    pub fn teams(&self) -> impl Iterator<Item = (&u64, &Team)> {
        self.teams.iter()
    }

    /// Adds a cursor for a team, placed at a corner position.
    pub fn add_cursor(&mut self, team_id: u64) -> Option<u64> {
        let (width, height, _) = self.dimensions();
        if width == 0 || height == 0 {
            return None;
        }

        // Find the best corner (farthest from existing cursors)
        let corners = [
            (0.5f32, 0.5f32),
            (width as f32 - 0.5, 0.5),
            (0.5, height as f32 - 0.5),
            (width as f32 - 0.5, height as f32 - 0.5),
        ];

        let best_corner = if self.cursors.is_empty() {
            corners[0]
        } else {
            corners
                .iter()
                .max_by(|a, b| {
                    let min_dist_a: f32 = self
                        .cursors
                        .values()
                        .map(|c| ((c.x() - a.0).powi(2) + (c.y() - a.1).powi(2)).sqrt())
                        .fold(f32::MAX, f32::min);
                    let min_dist_b: f32 = self
                        .cursors
                        .values()
                        .map(|c| ((c.x() - b.0).powi(2) + (c.y() - b.1).powi(2)).sqrt())
                        .fold(f32::MAX, f32::min);
                    min_dist_a.partial_cmp(&min_dist_b).unwrap()
                })
                .copied()
                .unwrap_or(corners[0])
        };

        let cursor = Cursor3D::new(team_id, best_corner.0, best_corner.1, 0.0);
        let cursor_id = self.generate_unique_cursor_id();
        self.cursors.insert(cursor_id, cursor);
        Some(cursor_id)
    }

    /// Adds a cursor with a specific ID.
    pub fn add_cursor_with_id(&mut self, cursor_id: u64, team_id: u64) {
        let (width, height, _) = self.dimensions();
        let x = width as f32 / 2.0;
        let y = height as f32 / 2.0;
        let cursor = Cursor3D::new(team_id, x, y, 0.0);
        self.cursors.insert(cursor_id, cursor);
    }

    /// Removes a cursor by its ID.
    pub fn remove_cursor(&mut self, cursor_id: &u64) -> Option<Cursor3D> {
        self.cursors.remove(cursor_id)
    }

    /// Returns a reference to the cursor with the given ID.
    pub fn get_cursor(&self, cursor_id: &u64) -> Option<&Cursor3D> {
        self.cursors.get(cursor_id)
    }

    /// Returns a mutable reference to the cursor with the given ID.
    pub fn get_cursor_mut(&mut self, cursor_id: &u64) -> Option<&mut Cursor3D> {
        self.cursors.get_mut(cursor_id)
    }

    /// Returns the number of cursors.
    pub fn cursor_count(&self) -> usize {
        self.cursors.len()
    }

    /// Returns an iterator over all cursors.
    pub fn cursors(&self) -> impl Iterator<Item = (&u64, &Cursor3D)> {
        self.cursors.iter()
    }

    /// Replaces all cursors (for network sync).
    pub fn set_cursors(&mut self, cursors: HashMap<u64, Cursor3D>) {
        self.cursors = cursors;
    }

    /// Returns the number of walkable places (from QuadMesh).
    pub fn place_count(&self) -> usize {
        self.gradient_mesh.len()
    }

    /// Returns the number of fighters.
    pub fn fighter_count(&self) -> usize {
        self.armies.fighter_count()
    }

    /// Returns the number of fighters belonging to a specific team.
    pub fn team_fighter_count(&self, team_id: u64) -> usize {
        self.armies
            .unsorted_iter()
            .filter(|f| f.team_id == team_id)
            .count()
    }

    /// Returns the maximum number of fighters a single team can have.
    ///
    /// This is based on [`MAX_TEAM_OCCUPATION`] fraction of walkable cells.
    pub fn max_fighters_per_team(&self) -> usize {
        let walkable = self.gradient_mesh.walkable_coords();
        (walkable as f32 * MAX_TEAM_OCCUPATION) as usize
    }

    /// Returns a reference to a fighter by ID.
    pub fn get_fighter(&self, fighter_id: &u64) -> Option<&Fighter> {
        self.armies.get_fighter(fighter_id)
    }

    /// Returns a reference to the armies.
    pub fn armies(&self) -> &Armies {
        &self.armies
    }

    /// Returns a mutable reference to the armies.
    pub fn armies_mut(&mut self) -> &mut Armies {
        &mut self.armies
    }

    /// Returns an iterator over all fighters.
    pub fn fighters(&self) -> impl Iterator<Item = &Fighter> {
        self.armies.unsorted_iter()
    }

    /// Spawns a single fighter for a team at a specific cell position.
    pub fn spawn_fighter(
        &mut self,
        team_id: u64,
        x: usize,
        y: usize,
        z: usize,
    ) -> Result<u64, SpawnError> {
        // Check if cell is walkable (via QuadMesh)
        let Some(gradient_index) = self.gradient_mesh.cell_at(x, y, z) else {
            return Err(SpawnError::NotWalkable);
        };

        // Check if cell is occupied (via Grid)
        if self.grid.fighter_at(x, y, z).is_some() {
            return Err(SpawnError::Occupied);
        }

        // Create fighter at cell center
        let cx = x as f32 + 0.5;
        let cy = y as f32 + 0.5;
        let cz = z as f32;
        let fighter = Fighter::new(team_id, cx, cy, cz, gradient_index, 1.0);

        // Add fighter to armies (generates unique ID with collision check)
        let fighter_id = self.armies.add_fighter(fighter);

        // Mark cell as occupied
        self.grid.set_fighter(x, y, z, Some(fighter_id));

        Ok(fighter_id)
    }

    /// Spawns multiple fighters near a position using BFS.
    ///
    /// Returns an error if spawning would exceed [`MAX_TEAM_OCCUPATION`] limit.
    pub fn spawn_fighters_near(
        &mut self,
        team_id: u64,
        x: f32,
        y: f32,
        count: usize,
    ) -> Result<usize, SpawnError> {
        // Check occupation limit before attempting to spawn
        let current = self.team_fighter_count(team_id);
        let max_allowed = self.max_fighters_per_team();
        if current + count > max_allowed {
            return Err(SpawnError::OccupationLimitExceeded { current, max_allowed });
        }

        let (width, height, depth) = self.dimensions();
        let start_x = (x.max(0.0) as usize).min(width.saturating_sub(1));
        let start_y = (y.max(0.0) as usize).min(height.saturating_sub(1));
        let start_z = 0usize.min(depth.saturating_sub(1));

        // BFS to find nearby empty cells
        let mut spawned = 0;
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back((start_x, start_y, start_z));
        visited.insert((start_x, start_y, start_z));

        while let Some((cx, cy, cz)) = queue.pop_front() {
            if spawned >= count {
                break;
            }

            // Try to spawn at this cell
            if self.spawn_fighter(team_id, cx, cy, cz).is_ok() {
                spawned += 1;
            }

            // Add walkable neighbors to queue
            for (nx, ny, nz) in self.grid.neighbors(cx, cy, cz) {
                if !visited.contains(&(nx, ny, nz)) && self.is_walkable(nx, ny, nz) {
                    visited.insert((nx, ny, nz));
                    queue.push_back((nx, ny, nz));
                }
            }
        }

        if spawned == 0 {
            Err(SpawnError::InsufficientPlaces(0))
        } else if spawned < count {
            Err(SpawnError::InsufficientPlaces(spawned))
        } else {
            Ok(spawned)
        }
    }

    /// Spawns fighters for a team at their cursor position.
    ///
    /// Finds the team's cursor and spawns fighters near that position.
    /// If the team has no cursor, defaults to spawning at (0, 0).
    ///
    /// This is the recommended way to spawn fighters as it automatically
    /// uses the cursor position determined by `add_cursor`.
    pub fn spawn_fighters_for_team(
        &mut self,
        team_id: u64,
        count: usize,
    ) -> Result<usize, SpawnError> {
        // Find cursor position for this team
        let (x, y) = self
            .cursors
            .values()
            .find(|c| c.team_id() == team_id)
            .map(|c| (c.x(), c.y()))
            .unwrap_or((0.0, 0.0));

        self.spawn_fighters_near(team_id, x, y, count)
    }

    /// Removes a fighter from the grid (clears occupation).
    pub fn unplace_fighter(&mut self, fighter_id: &u64) {
        if let Some(fighter) = self.armies.get_fighter(fighter_id) {
            let (width, height, depth) = self.dimensions();
            let (cx, cy, cz) = fighter.cell(width, height, depth);
            // Only clear if this fighter is actually there
            if self.grid.fighter_at(cx, cy, cz) == Some(*fighter_id) {
                self.grid.set_fighter(cx, cy, cz, None);
            }
        }
    }

    /// Places a fighter (adds to armies and marks grid cell).
    pub fn place_fighter(&mut self, fighter_id: u64, fighter: Fighter) {
        let (width, height, depth) = self.dimensions();
        let (cx, cy, cz) = fighter.cell(width, height, depth);
        self.armies.set_fighter(fighter_id, fighter);
        self.grid.set_fighter(cx, cy, cz, Some(fighter_id));
    }

    /// Performs a single game step.
    pub fn do_step(&mut self, odd_even: bool, steps_count: u64) {
        // Apply cursor positions to gradients (updates gradient_increment)
        let t = Instant::now();
        self.do_step_apply_cursors();
        self.timing.add_other(t);

        // Spread gradients
        let t = Instant::now();
        self.do_step_spread_gradients(odd_even, steps_count);
        self.timing.add_spread(t);

        // Re-apply cursor positions after spreading (ensures cursor stays at 0)
        let t = Instant::now();
        self.do_step_reapply_cursors();
        self.timing.add_other(t);

        // Animate fighters
        let t = Instant::now();
        self.do_step_animate_fighters(odd_even, steps_count);
        self.timing.add_animate(t);

        // Update stats
        let t = Instant::now();
        self.do_step_update_stats();
        self.timing.add_other(t);
    }

    /// Performs only the gradient spreading phase of a step.
    ///
    /// Useful for isolated benchmarking. Includes cursor application.
    pub fn do_step_spread_only(&mut self, odd_even: bool, steps_count: u64) {
        self.do_step_apply_cursors();
        self.do_step_spread_gradients(odd_even, steps_count);
        self.do_step_reapply_cursors();
    }

    /// Performs only the fighter animation phase of a step.
    ///
    /// Useful for isolated benchmarking on pre-computed gradients.
    /// Call after gradients are already spread (e.g., after warmup steps).
    pub fn do_step_animate_only(&mut self, odd_even: bool, steps_count: u64) {
        self.do_step_animate_fighters(odd_even, steps_count);
    }

    /// Applies cursor positions to team gradients.
    ///
    /// For each cursor:
    /// 1. If no cached gradient_index, finds the closest walkable cell using BFS
    /// 2. Caches the gradient_index in the cursor
    /// 3. Updates gradient_increment based on distance (for responsive cursor movement)
    /// 4. Sets the gradient distance at that index to 0
    fn do_step_apply_cursors(&mut self) {
        use crate::team::MIN_GRADIENT_INCREMENT;

        // Calculate max distance value (mesh volume) for clamping
        let max_value = self.gradient_mesh.total_volume() as f32;

        // Collect cursor IDs to avoid borrow conflicts
        let cursor_ids: Vec<u64> = self.cursors.keys().copied().collect();

        for cursor_id in cursor_ids {
            // Get cursor data (read-only first to avoid borrow conflicts)
            let (team_id, cached_index, cx, cy, cz) = {
                let Some(cursor) = self.cursors.get(&cursor_id) else {
                    continue;
                };
                (
                    cursor.team_id(),
                    cursor.gradient_index(),
                    cursor.x() as usize,
                    cursor.y() as usize,
                    cursor.z() as usize,
                )
            };

            // Get or compute the gradient index
            let gradient_index = if let Some(idx) = cached_index {
                idx
            } else {
                // Find closest walkable cell using BFS
                let idx = self.find_closest_walkable_cell(cx, cy, cz);
                // Cache the result in the cursor
                if let Some(cursor) = self.cursors.get_mut(&cursor_id) {
                    cursor.set_gradient_index(idx);
                }
                match idx {
                    Some(i) => i,
                    None => continue,
                }
            };

            // Apply cursor to team gradient
            if let Some(team) = self.teams.get_mut(&team_id) {
                // Get current distance at cursor position
                let current_distance = team.gradient().get_distance(gradient_index);

                // Only update gradient_increment if the distance is valid (not infinite)
                // At startup or for unvisited cells, keep the previous increment
                if current_distance < max_value {
                    // Double it to account for decay, clamp to valid range
                    let doubled = (current_distance * 2.0).max(MIN_GRADIENT_INCREMENT);
                    // Average with previous increment for progressive decay
                    let previous_increment = team.gradient_increment();
                    let averaged_increment = (doubled + previous_increment) / 2.0;
                    team.set_gradient_increment(averaged_increment.min(max_value));
                }
                // Set cursor position to 0 distance
                team.gradient_mut().set_distance(gradient_index, 0.0);
            }
        }
    }

    /// Re-applies cursor positions after gradient spreading.
    ///
    /// This ensures cursor positions stay at distance 0 even after spreading
    /// might have affected them. Does not update gradient_increment.
    fn do_step_reapply_cursors(&mut self) {
        for cursor in self.cursors.values() {
            let team_id = cursor.team_id();
            if let Some(gradient_index) = cursor.gradient_index()
                && let Some(team) = self.teams.get_mut(&team_id)
            {
                team.gradient_mut().set_distance(gradient_index, 0.0);
            }
        }
    }

    /// Finds the closest walkable cell to a position using BFS.
    ///
    /// Searches through all z-levels to find a walkable cell, starting from
    /// the given position and expanding outward through neighbors.
    fn find_closest_walkable_cell(&self, x: usize, y: usize, z: usize) -> Option<usize> {
        let (width, height, depth) = self.gradient_mesh.dimensions();

        // Clamp starting position to valid bounds
        let start_x = x.min(width.saturating_sub(1));
        let start_y = y.min(height.saturating_sub(1));
        let start_z = z.min(depth.saturating_sub(1));

        // Try the exact position first
        if let Some(idx) = self.gradient_mesh.cell_at(start_x, start_y, start_z) {
            return Some(idx);
        }

        // BFS to find nearest walkable cell across all z-levels
        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();

        // Start from all z-levels at the given x,y
        for z_level in 0..depth {
            let pos = (start_x, start_y, z_level);
            if !visited.contains(&pos) {
                visited.insert(pos);
                queue.push_back(pos);
            }
        }

        while let Some((cx, cy, cz)) = queue.pop_front() {
            // Check if this cell is walkable
            if let Some(idx) = self.gradient_mesh.cell_at(cx, cy, cz) {
                return Some(idx);
            }

            // Add neighbors to queue (6 directions: ±x, ±y, ±z)
            let neighbors = [
                (cx.wrapping_sub(1), cy, cz),
                (cx + 1, cy, cz),
                (cx, cy.wrapping_sub(1), cz),
                (cx, cy + 1, cz),
                (cx, cy, cz.wrapping_sub(1)),
                (cx, cy, cz + 1),
            ];

            for (nx, ny, nz) in neighbors {
                if nx < width && ny < height && nz < depth && !visited.contains(&(nx, ny, nz)) {
                    visited.insert((nx, ny, nz));
                    queue.push_back((nx, ny, nz));
                }
            }
        }

        None
    }

    /// Spreads gradients for all teams.
    ///
    /// Alternates between forward and backward spreading based on odd_even.
    /// Uses each team's gradient_increment, which is updated based on cursor movement.
    /// Also adds semi-random variation based on step count to break cycling patterns.
    fn do_step_spread_gradients(&mut self, odd_even: bool, steps_count: u64) {
        use crate::team::min_gradient_increment_from_steps_count;
        // Add semi-random variation to break cycles
        let step_variation = min_gradient_increment_from_steps_count(steps_count);
        for team in self.teams.values_mut() {
            // Use team's increment (based on cursor distance) plus step variation
            let incr = team.gradient_increment().max(step_variation);
            if odd_even {
                team.gradient_mut()
                    .spread_backward(&self.gradient_mesh, incr);
            } else {
                team.gradient_mut()
                    .spread_forward(&self.gradient_mesh, incr);
            }
        }
    }

    /// Adds action points to fighters and moves them.
    fn do_step_animate_fighters(&mut self, odd_even: bool, _steps_count: u64) {
        // Add action points
        for (_, fighter) in self.armies.iter_mut(odd_even) {
            fighter.action_points += ACTION_POINTS_PER_STEP;
        }

        // Collect fighter IDs to avoid borrow conflicts
        let fighter_ids: Vec<u64> = self.armies.iter(odd_even).map(|(id, _)| *id).collect();

        for fighter_id in fighter_ids {
            self.move_fighter_once(&fighter_id, odd_even);
        }
    }

    /// Attempts to move a fighter once.
    fn move_fighter_once(&mut self, fighter_id: &u64, odd_even: bool) {
        let (width, height, depth) = self.dimensions();

        // Get fighter data
        let (team_id, current_grad_index, current_x, current_y, current_z) = {
            let Some(fighter) = self.armies.get_fighter(fighter_id) else {
                return;
            };
            if fighter.action_points < MOVE_COST {
                return;
            }
            (
                fighter.team_id,
                fighter.gradient_index,
                fighter.x,
                fighter.y,
                fighter.z,
            )
        };

        let (current_cx, current_cy, current_cz) = (
            (current_x.max(0.0) as usize).min(width.saturating_sub(1)),
            (current_y.max(0.0) as usize).min(height.saturating_sub(1)),
            (current_z.max(0.0) as usize).min(depth.saturating_sub(1)),
        );

        // Check if fighter is in the same cell as cursor - if so, move directly to cursor
        let fighter_cell_index = self
            .gradient_mesh
            .cell_at(current_cx, current_cy, current_cz);
        let direct_to_cursor: Option<(f32, f32, f32)> =
            fighter_cell_index.and_then(|fighter_idx| {
                self.cursors
                    .values()
                    .find(|c| c.team_id() == team_id)
                    .and_then(|cursor| {
                        let cursor_cx = cursor.x() as usize;
                        let cursor_cy = cursor.y() as usize;
                        let cursor_cell_index =
                            self.gradient_mesh.cell_at(cursor_cx, cursor_cy, 0)?;
                        if cursor_cell_index == fighter_idx {
                            // Same cell - compute direct direction to cursor
                            let dx = cursor.x() - current_x;
                            let dy = cursor.y() - current_y;
                            let dist = (dx * dx + dy * dy).sqrt();
                            if dist > CURSOR_ARRIVAL_THRESHOLD {
                                Some((dx / dist, dy / dist, 0.0))
                            } else {
                                None // Already at cursor
                            }
                        } else {
                            None
                        }
                    })
            });

        // If direct-to-cursor, use that direction; otherwise use gradient
        if let Some((dir_x, dir_y, dir_z)) = direct_to_cursor {
            let (moved, blocked_by) = self.try_move_in_direction(
                fighter_id,
                current_x,
                current_y,
                current_z,
                current_cx,
                current_cy,
                current_cz,
                current_grad_index,
                dir_x,
                dir_y,
                dir_z,
                width,
                height,
                depth,
            );
            if !moved {
                // Couldn't move - center and mark as stalled
                if let Some(fighter) = self.armies.get_fighter_mut(fighter_id) {
                    fighter.x = current_cx as f32 + 0.5;
                    fighter.y = current_cy as f32 + 0.5;
                    fighter.z = current_cz as f32 + 0.5;
                    fighter.status = FighterStatus::Stalled;
                }
                // If blocked by another fighter, attack (enemy) or heal (ally)
                if let Some(blocker_id) = blocked_by {
                    self.interact_with_blocker(fighter_id, team_id, blocker_id);
                }
            }
            return;
        }

        // Get moves from gradient
        let moves: Vec<_> = if let Some(team) = self.teams.get(&team_id) {
            team.gradient()
                .moves(&self.gradient_mesh, current_grad_index, odd_even)
        } else {
            return;
        };

        // Track the blocker at the BEST position (first one found, since moves are sorted by gradient)
        let mut best_blocker: Option<u64> = None;

        // Try each move direction (sorted by gradient distance - best/closest first)
        for gate in moves {
            let target_grad_index = gate.target();

            // Get direction vector from gradient_mesh
            let Some((dir_x, dir_y, dir_z)) = self
                .gradient_mesh
                .direction_to_neighbor(current_grad_index, target_grad_index)
            else {
                continue;
            };

            // Calculate new position (move by 1.0)
            let new_x = current_x + dir_x * MOVE_COST;
            let new_y = current_y + dir_y * MOVE_COST;
            let new_z = current_z + dir_z * MOVE_COST;

            // Get new cell coordinates (clamped to bounds)
            let new_cx = (new_x.max(0.0) as usize).min(width.saturating_sub(1));
            let new_cy = (new_y.max(0.0) as usize).min(height.saturating_sub(1));
            let new_cz = (new_z.max(0.0) as usize).min(depth.saturating_sub(1));

            // Determine the "target cell" for occupancy checks
            // If move stays in same cell, use lookahead to find the real destination
            let same_cell = new_cx == current_cx && new_cy == current_cy && new_cz == current_cz;
            let (target_cx, target_cy, target_cz) = if same_cell {
                let lookahead_x = current_x + dir_x * MOVE_COST * SAME_CELL_LOOKAHEAD;
                let lookahead_y = current_y + dir_y * MOVE_COST * SAME_CELL_LOOKAHEAD;
                let lookahead_z = current_z + dir_z * MOVE_COST * SAME_CELL_LOOKAHEAD;
                (
                    (lookahead_x.max(0.0) as usize).min(width.saturating_sub(1)),
                    (lookahead_y.max(0.0) as usize).min(height.saturating_sub(1)),
                    (lookahead_z.max(0.0) as usize).min(depth.saturating_sub(1)),
                )
            } else {
                (new_cx, new_cy, new_cz)
            };

            // If lookahead still in same cell, this move goes nowhere - skip it
            if target_cx == current_cx && target_cy == current_cy && target_cz == current_cz {
                continue;
            }

            // Check if target cell is walkable (via QuadMesh)
            if self
                .gradient_mesh
                .cell_at(target_cx, target_cy, target_cz)
                .is_none()
            {
                continue;
            }

            // Check if target cell is occupied - don't even start moving if destination is busy
            if let Some(blocker_id) = self.grid.fighter_at(target_cx, target_cy, target_cz) {
                // Record blocker at BEST position only (first one found)
                best_blocker.get_or_insert(blocker_id);
                continue;
            }

            // Move is valid - only update grid if actually crossing into new cell
            if !same_cell {
                self.grid
                    .set_fighter(current_cx, current_cy, current_cz, None);
                self.grid
                    .set_fighter(new_cx, new_cy, new_cz, Some(*fighter_id));
            }

            // Determine new gradient_index based on actual position (new_x/y/z)
            let new_grad_index = if self
                .gradient_mesh
                .cell(current_grad_index)
                .is_some_and(|c| c.contains(new_cx, new_cy, new_cz))
            {
                current_grad_index
            } else if self
                .gradient_mesh
                .cell(target_grad_index)
                .is_some_and(|c| c.contains(new_cx, new_cy, new_cz))
            {
                target_grad_index
            } else {
                // Fall back to mesh lookup for actual position
                self.gradient_mesh
                    .cell_at(new_cx, new_cy, new_cz)
                    .unwrap_or(current_grad_index)
            };

            // Update fighter - move succeeded
            if let Some(fighter) = self.armies.get_fighter_mut(fighter_id) {
                // Clamp position to stay within the target cell
                // x and y: clamp to [cx, cx+1) range
                fighter.x = new_x.clamp(new_cx as f32, new_cx as f32 + 0.999);
                fighter.y = new_y.clamp(new_cy as f32, new_cy as f32 + 0.999);
                // z: clamp to [cz, cz+1) range, but for top layer (cz=0) keep above 0.5
                let z_min = if new_cz == 0 { 0.5 } else { new_cz as f32 };
                fighter.z = new_z.clamp(z_min, new_cz as f32 + 0.999);

                // When vertical movement is near zero, gradually converge to stable z level
                // This prevents fighters from "floating" at wrong heights after horizontal moves
                const Z_CONVERGENCE_FACTOR: f32 = 0.2;
                const Z_VELOCITY_THRESHOLD: f32 = 0.01;
                if dir_z.abs() < Z_VELOCITY_THRESHOLD {
                    let stable_z = new_cz as f32 + 0.5;
                    let z_diff = stable_z - fighter.z;
                    fighter.z += z_diff * Z_CONVERGENCE_FACTOR;
                }

                fighter.gradient_index = new_grad_index;
                fighter.action_points -= MOVE_COST;
                fighter.status = FighterStatus::Moving;
            }

            return; // Move succeeded
        }

        // No valid move found - center the fighter on its current cell and mark as stalled
        if let Some(fighter) = self.armies.get_fighter_mut(fighter_id) {
            fighter.x = current_cx as f32 + 0.5;
            fighter.y = current_cy as f32 + 0.5;
            fighter.z = current_cz as f32 + 0.5;
            fighter.status = FighterStatus::Stalled;
        }

        // Attack/heal the blocker at the BEST position (closest to cursor)
        if let Some(blocker_id) = best_blocker {
            self.interact_with_blocker(fighter_id, team_id, blocker_id);
        }
    }

    /// Handles interaction when a fighter is blocked by another fighter at the BEST position.
    /// The blocker is always the one at the best gradient position (closest to cursor).
    /// - If blocker is enemy: attack (reduce health by attack_factor), attacker status set to Attacking.
    ///   If health reaches 0, the blocker is converted to attacker's team with convert_factor health.
    /// - If blocker is ally: heal (increase health by heal_factor), attacker status stays Stalled.
    fn interact_with_blocker(&mut self, attacker_id: &u64, attacker_team_id: u64, blocker_id: u64) {
        let is_enemy = {
            let Some(blocker) = self.armies.get_fighter(&blocker_id) else {
                return;
            };
            blocker.team_id != attacker_team_id
        };

        if is_enemy {
            // Set attacker status to Attacking
            if let Some(attacker) = self.armies.get_fighter_mut(attacker_id) {
                attacker.status = FighterStatus::Attacking;
            }

            // Attack: reduce blocker's health
            let new_health = {
                let Some(blocker) = self.armies.get_fighter_mut(&blocker_id) else {
                    return;
                };
                blocker.health = (blocker.health - self.attack_factor).max(0.0);
                blocker.health
            };

            // If health reached 0, convert fighter to attacker's team
            if new_health <= 0.0
                && let Some(blocker) = self.armies.get_fighter_mut(&blocker_id)
            {
                blocker.team_id = attacker_team_id;
                blocker.health = self.convert_factor;
            }
        } else {
            // Heal: increase blocker's health (same team)
            // Attacker status stays Stalled (set by caller)
            if let Some(blocker) = self.armies.get_fighter_mut(&blocker_id) {
                blocker.health = (blocker.health + self.heal_factor).min(1.0);
            }
        }
    }

    /// Attempts to move a fighter in a specific direction (used for direct-to-cursor movement).
    ///
    /// Returns (moved, blocked_by):
    /// - `moved`: true if the move was successful
    /// - `blocked_by`: Some(fighter_id) if blocked by another fighter
    #[allow(clippy::too_many_arguments)]
    fn try_move_in_direction(
        &mut self,
        fighter_id: &u64,
        current_x: f32,
        current_y: f32,
        current_z: f32,
        current_cx: usize,
        current_cy: usize,
        current_cz: usize,
        current_grad_index: usize,
        dir_x: f32,
        dir_y: f32,
        dir_z: f32,
        width: usize,
        height: usize,
        depth: usize,
    ) -> (bool, Option<u64>) {
        // Calculate new position
        let new_x = current_x + dir_x * MOVE_COST;
        let new_y = current_y + dir_y * MOVE_COST;
        let new_z = current_z + dir_z * MOVE_COST;

        // Get new cell coordinates (clamped to bounds)
        let new_cx = (new_x.max(0.0) as usize).min(width.saturating_sub(1));
        let new_cy = (new_y.max(0.0) as usize).min(height.saturating_sub(1));
        let new_cz = (new_z.max(0.0) as usize).min(depth.saturating_sub(1));

        // Check if new cell is walkable (via QuadMesh)
        let Some(new_grad_index_from_mesh) = self.gradient_mesh.cell_at(new_cx, new_cy, new_cz)
        else {
            return (false, None);
        };

        // Check if new cell is occupied (only if different from current)
        let same_cell = new_cx == current_cx && new_cy == current_cy && new_cz == current_cz;
        if !same_cell
            && let Some(blocker_id) = self.grid.fighter_at(new_cx, new_cy, new_cz)
        {
            return (false, Some(blocker_id));
        }

        // Move is valid - update grid occupation
        if !same_cell {
            self.grid
                .set_fighter(current_cx, current_cy, current_cz, None);
            self.grid
                .set_fighter(new_cx, new_cy, new_cz, Some(*fighter_id));
        }

        // Determine new gradient_index - for same-cell movement, stay in same gradient cell
        let new_grad_index = if self
            .gradient_mesh
            .cell(current_grad_index)
            .is_some_and(|c| c.contains(new_cx, new_cy, new_cz))
        {
            current_grad_index
        } else {
            new_grad_index_from_mesh
        };

        // Update fighter - move succeeded
        if let Some(fighter) = self.armies.get_fighter_mut(fighter_id) {
            // Clamp position to stay within the target cell
            // x and y: clamp to [cx, cx+1) range
            fighter.x = new_x.clamp(new_cx as f32, new_cx as f32 + 0.999);
            fighter.y = new_y.clamp(new_cy as f32, new_cy as f32 + 0.999);
            // z: clamp to [cz, cz+1) range, but for top layer (cz=0) keep above 0.5
            let z_min = if new_cz == 0 { 0.5 } else { new_cz as f32 };
            fighter.z = new_z.clamp(z_min, new_cz as f32 + 0.999);

            // When vertical movement is near zero, gradually converge to stable z level
            const Z_CONVERGENCE_FACTOR: f32 = 0.2;
            const Z_VELOCITY_THRESHOLD: f32 = 0.01;
            if dir_z.abs() < Z_VELOCITY_THRESHOLD {
                let stable_z = new_cz as f32 + 0.5;
                let z_diff = stable_z - fighter.z;
                fighter.z += z_diff * Z_CONVERGENCE_FACTOR;
            }

            fighter.gradient_index = new_grad_index;
            fighter.action_points -= MOVE_COST;
            fighter.status = FighterStatus::Moving;
        }

        (true, None)
    }

    /// Updates team statistics.
    fn do_step_update_stats(&mut self) {
        let mut stats: HashMap<u64, (usize, f32)> = HashMap::new();

        for fighter in self.armies.unsorted_iter() {
            let entry = stats.entry(fighter.team_id).or_insert((0, 0.0));
            entry.0 += 1;
            entry.1 += fighter.health;
        }

        for (team_id, team) in &mut self.teams {
            if let Some((count, total_health)) = stats.get(team_id) {
                team.set_fighter_count(*count);
                if *count > 0 {
                    team.set_average_health(total_health / *count as f32);
                } else {
                    team.set_average_health(0.0);
                }
            } else {
                team.set_fighter_count(0);
                team.set_average_health(0.0);
            }
        }
    }

    /// Finds the nearest empty cell using BFS.
    pub fn find_nearest_empty(
        &self,
        x: usize,
        y: usize,
        z: usize,
    ) -> Option<(usize, usize, usize)> {
        if self.is_free(x, y, z) {
            return Some((x, y, z));
        }

        let mut visited = HashSet::new();
        let mut queue = VecDeque::new();
        queue.push_back((x, y, z));
        visited.insert((x, y, z));

        while let Some((cx, cy, cz)) = queue.pop_front() {
            for (nx, ny, nz) in self.grid.neighbors(cx, cy, cz) {
                if visited.contains(&(nx, ny, nz)) {
                    continue;
                }
                visited.insert((nx, ny, nz));

                // Only consider walkable cells
                if !self.is_walkable(nx, ny, nz) {
                    continue;
                }

                if self.grid.is_cell_empty(nx, ny, nz) {
                    return Some((nx, ny, nz));
                }
                queue.push_back((nx, ny, nz));
            }
        }

        None
    }
}

impl GameState for World {
    fn do_step(&mut self, odd_even: bool, steps_count: u64) {
        World::do_step(self, odd_even, steps_count)
    }
}

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

    fn create_test_world() -> World {
        let gradient_mesh = QuadMesh::new(10, 10, 1, |_, _, _| true).unwrap();
        World::new(gradient_mesh)
    }

    #[test]
    fn test_world_creation() {
        let world = create_test_world();
        // Depth is 2: 1 user layer + 1 ground layer
        assert_eq!(world.dimensions(), (10, 10, 2));
        // With compaction, 10x10 uniform mesh compacts significantly
        // 8x8 region becomes 1 cell, plus edge cells
        assert!(world.place_count() < 100, "Should be compacted");
        assert!(world.place_count() > 0, "Should have some cells");
        assert_eq!(world.team_count(), 0);
        assert_eq!(world.cursor_count(), 0);
    }

    #[test]
    fn test_add_team() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());
        assert_eq!(world.team_count(), 1);
        assert!(world.get_team(&team_id).is_some());
    }

    #[test]
    fn test_add_cursor() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());
        let cursor_id = world.add_cursor(team_id);
        assert!(cursor_id.is_some());
        assert_eq!(world.cursor_count(), 1);
    }

    #[test]
    fn test_spawn_fighter() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());
        let result = world.spawn_fighter(team_id, 5, 5, 0);
        assert!(result.is_ok());
        assert_eq!(world.fighter_count(), 1);

        // Verify fighter position
        let fighter_id = result.unwrap();
        let fighter = world.get_fighter(&fighter_id).unwrap();
        assert_eq!(fighter.position(), (5.5, 5.5, 0.0));
    }

    #[test]
    fn test_spawn_fighter_occupied() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());

        // First spawn succeeds
        assert!(world.spawn_fighter(team_id, 5, 5, 0).is_ok());

        // Second spawn at same location fails
        let result = world.spawn_fighter(team_id, 5, 5, 0);
        assert_eq!(result, Err(SpawnError::Occupied));
    }

    #[test]
    fn test_spawn_fighters_near() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());
        let result = world.spawn_fighters_near(team_id, 5.0, 5.0, 10);
        assert!(result.is_ok());
        assert_eq!(world.fighter_count(), 10);
    }

    #[test]
    fn test_spawn_occupation_limit() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());

        // Get the max allowed fighters
        let max_allowed = world.max_fighters_per_team();
        assert!(max_allowed > 0, "Should have some capacity");

        // Spawn up to the limit should succeed
        let result = world.spawn_fighters_near(team_id, 5.0, 5.0, max_allowed);
        assert!(result.is_ok(), "Spawning up to limit should succeed");
        assert_eq!(world.team_fighter_count(team_id), max_allowed);

        // Trying to spawn even one more should fail
        let result = world.spawn_fighters_near(team_id, 5.0, 5.0, 1);
        assert!(
            matches!(result, Err(SpawnError::OccupationLimitExceeded { .. })),
            "Spawning over limit should fail with OccupationLimitExceeded"
        );

        // Count should not have changed
        assert_eq!(world.team_fighter_count(team_id), max_allowed);
    }

    #[test]
    fn test_spawn_occupation_limit_multiple_teams() {
        let mut world = create_test_world();
        let team1_id = world.add_team(crate::RED, "Red".to_string());
        let team2_id = world.add_team(crate::BLUE, "Blue".to_string());

        let max_allowed = world.max_fighters_per_team();

        // Team 1 spawns to their limit
        let result = world.spawn_fighters_near(team1_id, 2.0, 2.0, max_allowed);
        assert!(result.is_ok());

        // Team 2 should also be able to spawn to their limit (different team)
        let result = world.spawn_fighters_near(team2_id, 8.0, 8.0, max_allowed);
        // This might fail with InsufficientPlaces if the map is too small,
        // but should NOT fail with OccupationLimitExceeded
        assert!(
            !matches!(result, Err(SpawnError::OccupationLimitExceeded { .. })),
            "Each team has independent occupation limit"
        );
    }

    #[test]
    fn test_fighter_cell_bounds() {
        let fighter = Fighter::new(0x1234567890abcdef_u64, 5.5, 5.5, 0.0, 0, 1.0);
        assert_eq!(fighter.cell(10, 10, 1), (5, 5, 0));

        // Test clamping at upper bound
        let fighter2 = Fighter::new(0xfedcba0987654321_u64, 15.0, 15.0, 5.0, 0, 1.0);
        assert_eq!(fighter2.cell(10, 10, 1), (9, 9, 0));

        // Test clamping at lower bound
        let fighter3 = Fighter::new(0xabcdef1234567890_u64, -5.0, -5.0, -1.0, 0, 1.0);
        assert_eq!(fighter3.cell(10, 10, 1), (0, 0, 0));
    }

    #[test]
    fn test_move_fighter() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());
        let cursor_id = world.add_cursor(team_id).unwrap();

        // Spawn fighter
        let fighter_id = world.spawn_fighter(team_id, 5, 5, 0).unwrap();

        // Set cursor at corner
        if let Some(cursor) = world.get_cursor_mut(&cursor_id) {
            cursor.set_position(0.5, 0.5, 0.0);
        }

        // Get initial position
        let initial_pos = world.get_fighter(&fighter_id).unwrap().position();

        // Run a step
        world.do_step(false, 1);

        // Fighter should have moved
        let new_pos = world.get_fighter(&fighter_id).unwrap().position();
        println!("Initial: {:?}, New: {:?}", initial_pos, new_pos);
    }

    #[test]
    fn test_is_walkable() {
        let world = create_test_world();
        // All cells should be walkable in test world
        assert!(world.is_walkable(5, 5, 0));
        assert!(world.is_walkable(0, 0, 0));
        assert!(world.is_walkable(9, 9, 0));
        // Out of bounds should not be walkable
        assert!(!world.is_walkable(10, 10, 0));
    }

    #[test]
    fn test_is_free() {
        let mut world = create_test_world();
        let team_id = world.add_team(crate::RED, "Red".to_string());

        // Empty cell should be free
        assert!(world.is_free(5, 5, 0));

        // Spawn fighter
        world.spawn_fighter(team_id, 5, 5, 0).unwrap();

        // Cell with fighter should not be free
        assert!(!world.is_free(5, 5, 0));

        // Adjacent empty cell should still be free
        assert!(world.is_free(5, 6, 0));
    }

    #[test]
    fn test_attacking_status_when_blocked_by_enemy() {
        let mut world = create_test_world();

        // Create two teams
        let red_team_id = world.add_team(crate::RED, "Red".to_string());
        let blue_team_id = world.add_team(crate::BLUE, "Blue".to_string());

        // Add cursors for both teams
        let red_cursor_id = world.add_cursor(red_team_id).unwrap();
        let blue_cursor_id = world.add_cursor(blue_team_id).unwrap();

        // Set cursors first so gradient can propagate
        if let Some(cursor) = world.get_cursor_mut(&red_cursor_id) {
            cursor.set_position(4.5, 5.5, 0.0);
        }
        if let Some(cursor) = world.get_cursor_mut(&blue_cursor_id) {
            cursor.set_position(4.5, 5.5, 0.0);
        }

        // Run a few steps to let gradient propagate before spawning fighters
        for i in 0..10 {
            world.do_step(i % 2 == 0, i as u64);
        }

        // Spawn red fighter at (5, 5)
        let red_fighter_id = world.spawn_fighter(red_team_id, 5, 5, 0).unwrap();
        // Spawn blue fighter at cursor - blocks red's destination
        let blue_fighter_id = world.spawn_fighter(blue_team_id, 4, 5, 0).unwrap();

        // Track if blue loses health from attacks
        let mut saw_health_decrease = false;
        let initial_blue_health = world.get_fighter(&blue_fighter_id).unwrap().health;

        // Run steps - process BOTH odd and even each iteration to ensure all fighters move
        for i in 0..100 {
            // Process both odd and even fighters each iteration
            world.do_step(false, (i * 2) as u64); // even step
            world.do_step(true, (i * 2 + 1) as u64); // odd step

            let blue_fighter = world.get_fighter(&blue_fighter_id).unwrap();

            if blue_fighter.health < initial_blue_health {
                saw_health_decrease = true;
            }

            // Check if blue fighter changed teams (converted)
            if blue_fighter.team_id == red_team_id {
                break;
            }
        }

        // Blue's health should have decreased (attack worked)
        assert!(
            saw_health_decrease,
            "Blue should have lost health from red's attacks"
        );
    }
}