archetype_ecs 1.2.0

Archetype ECS - High-performance Entity Component System with parallel execution
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
// Copyright 2024 Saptak Santra
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! World: central entity and archetype storage

use ahash::AHashMap;
use parking_lot::RwLock;
use slotmap::SlotMap;
use smallvec::SmallVec;
use std::any::TypeId;
use std::marker::PhantomData;
use std::ptr::NonNull;

#[cfg(feature = "profiling")]
use tracing::info_span;

use crate::archetype::{Archetype, ArchetypeSignature, ComponentColumn};
use crate::command::CommandBuffer;
use crate::component::{Bundle, Component, MAX_BUNDLE_COMPONENTS};
use crate::entity::{EntityId, EntityLocation};
use crate::error::{EcsError, Result};
use crate::event::{EntityEvent, EventQueue};
use crate::observer::{Observer, ObserverRegistry};
use crate::query::{Query, QueryFetch, QueryFetchMut, QueryFilter, QueryMut};

/// Central ECS world
pub struct World {
    entity_locations: SlotMap<EntityId, EntityLocation>,

    recycled_entities: usize,

    archetypes: Vec<Archetype>,

    arch_idx: AHashMap<ArchetypeSignature, usize>,

    event_queue: EventQueue,

    observers: ObserverRegistry,

    #[cfg(feature = "profiling")]
    observer_metrics: crate::observer::ObserverMetrics,

    pub component_tracker: AHashMap<EntityId, std::collections::HashSet<TypeId>>,

    global_event_bus: crate::event_bus::EventBus,

    pub tick: u32,

    removal_queue: Vec<EntityId>,

    resources: AHashMap<TypeId, Box<dyn std::any::Any + Send + Sync>>,

    query_cache: RwLock<AHashMap<crate::query::QuerySignature, crate::query::CachedQueryResult>>,
}

impl World {
    /// Create a new, empty world.
    pub fn new() -> Self {
        let mut world = Self {
            entity_locations: SlotMap::with_key(),
            recycled_entities: 0,

            // Start with reasonable defaults to avoid resize spikes
            archetypes: Vec::with_capacity(64),
            arch_idx: AHashMap::with_capacity(64),

            // Subsystems
            event_queue: EventQueue::new(),
            observers: ObserverRegistry::new(),
            #[cfg(feature = "profiling")]
            observer_metrics: crate::observer::ObserverMetrics::default(),
            component_tracker: AHashMap::new(),
            global_event_bus: crate::event_bus::EventBus::new(),

            tick: 1, // Tick 0 is reserved/unused to ensure change detection checks always pass for new things
            removal_queue: Vec::new(),
            resources: AHashMap::new(),
            // Pre-allocate query cache - trades memory for speed (most apps have <100 unique queries)
            query_cache: RwLock::new(AHashMap::with_capacity(32)),
        };

        // Bootstrap the empty archetype (entities with no components)
        // This is always at index 0 and simplifies logic elsewhere
        world.get_or_create_archetype_with(&ArchetypeSignature::new(), |arch| {
            arch.mark_columns_initialized();
        });
        world
    }

    pub fn tick(&self) -> u32 {
        self.tick
    }

    pub fn increment_tick(&mut self) {
        // Saturating add: prefer capped growth over panic
        self.tick = self.tick.saturating_add(1);
        // Reserve 0 for "never changed" state
        if self.tick == 0 {
            self.tick = 1;
        }
    }

    /// Spawn entity with components
    #[deprecated(
        since = "1.2.0",
        note = "Use spawn_entity() instead for better clarity"
    )]
    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> EntityId {
        self.spawn_entity(bundle)
    }

    /// Spawn entity with components
    /// Spawn a new entity with the given bundle of components.
    ///
    /// # Panics
    /// Panics if the Entity ID generator overflows (which is practically impossible).
    pub fn spawn_entity<B: Bundle>(&mut self, bundle: B) -> EntityId {
        self.try_spawn_entity(bundle).unwrap()
    }

    /// Try to spawn entity with components, returning detailed error information
    #[deprecated(
        since = "1.2.0",
        note = "Use try_spawn_entity() instead for better clarity"
    )]
    pub fn try_spawn<B: Bundle>(&mut self, bundle: B) -> crate::error::Result<EntityId> {
        self.try_spawn_entity(bundle)
    }

    /// Try to spawn entity with components, returning detailed error information
    ///
    /// # Errors
    /// Returns an error if:
    /// - Entity capacity is exhausted
    /// - Component registration fails  
    /// - Archetype creation fails
    pub fn try_spawn_entity<B: Bundle>(&mut self, bundle: B) -> crate::error::Result<EntityId> {
        // Ensure capacity before insertion
        self.ensure_entity_capacity()?;

        let placeholder = EntityLocation {
            archetype_id: usize::MAX,
            archetype_row: usize::MAX,
        };

        let id = self.entity_locations.insert(placeholder);

        if self.recycled_entities > 0 {
            self.recycled_entities -= 1;
        }
        let type_ids = B::type_ids();
        #[cfg(feature = "profiling")]
        let span = info_span!(
            "world.spawn",
            bundle_components = type_ids.len(),
            archetype_count = self.archetypes.len()
        );
        #[cfg(feature = "profiling")]
        let _span_guard = span.enter();

        let arch_id = self.get_or_create_archetype_with(&type_ids, |arch| {
            B::register_components(arch);
            arch.mark_columns_initialized();
        });
        let archetype = &mut self.archetypes[arch_id];

        // Allocate row in archetype
        let row = archetype.allocate_row(id, self.tick);

        // Pre-calculate column indices to avoid hash lookups in the hot path
        let mut column_indices = [usize::MAX; MAX_BUNDLE_COMPONENTS];
        let mut column_count = 0;
        for &type_id in type_ids.iter() {
            if let Some(idx) = archetype.column_index(type_id) {
                column_indices[column_count] = idx;
                column_count += 1;
            }
        }

        // Write component data using pre-calculated indices
        // SAFETY: We have exclusive access to these rows because we just allocated them
        let mut ptrs = [std::ptr::null_mut(); MAX_BUNDLE_COMPONENTS];
        for i in 0..column_count {
            let col_idx = column_indices[i];
            if let Some(column) = archetype.get_column_mut_by_index(col_idx) {
                ptrs[i] = column.get_ptr_mut(row);
            }
        }

        unsafe {
            bundle.write_components(&ptrs[..column_count]);
        }

        // Update entity location
        // Note: SlotMap insert happened earlier to get ID, now we update value
        if let Some(loc) = self.entity_locations.get_mut(id) {
            *loc = EntityLocation {
                archetype_id: arch_id,
                archetype_row: row,
            };
        }

        // Track components
        let mut component_set = std::collections::HashSet::with_capacity(type_ids.len());
        for &type_id in type_ids.iter() {
            component_set.insert(type_id);
        }
        self.component_tracker.insert(id, component_set);

        // Return entity ID
        Ok(id)
    }

    /// Check if an entity is alive
    ///
    /// Returns true if the entity handle is valid and the entity exists in the world.
    pub fn is_alive(&self, entity: EntityId) -> bool {
        self.entity_locations.contains_key(entity)
    }

    /// Despawn entity (deferred - queued for removal)
    ///
    /// Entities are not immediately removed to avoid issues during iteration.
    /// Call `flush_removals()` to process the removal queue.
    pub fn despawn_deferred(&mut self, entity: EntityId) -> Result<()> {
        // Validate entity exists
        if !self.entity_locations.contains_key(entity) {
            return Err(EcsError::EntityNotFound);
        }

        // Queue for deferred removal
        self.removal_queue.push(entity);
        Ok(())
    }

    /// Despawn entity immediately
    ///
    /// Removes the entity and all its components from the world.
    pub fn despawn(&mut self, entity: EntityId) -> Result<()> {
        // Fail fast on invalid entity
        if !self.entity_locations.contains_key(entity) {
            return Err(EcsError::EntityNotFound);
        }

        let location = self.entity_locations.remove(entity).unwrap();
        let archetype = &mut self.archetypes[location.archetype_id];
        unsafe {
            if let Some(swapped_entity) = archetype.remove_row(location.archetype_row) {
                if let Some(swapped_loc) = self.entity_locations.get_mut(swapped_entity) {
                    swapped_loc.archetype_row = location.archetype_row;
                }
            }
        }
        self.recycled_entities += 1;
        Ok(())
    }

    /// Convert World to an UnsafeWorldCell
    ///
    /// # Safety
    /// This provides unrestricted raw pointer access to world data.
    /// Internal tools use this for parallel execution after validating disjointness.
    pub unsafe fn as_unsafe_world_cell(&mut self) -> UnsafeWorldCell {
        UnsafeWorldCell::new(self)
    }

    /// Flush deferred removal queue
    pub fn flush_removals(&mut self) -> Result<()> {
        let to_remove: Vec<_> = self.removal_queue.drain(..).collect();

        // Early return for empty queue - common case optimization
        if to_remove.is_empty() {
            return Ok(());
        }

        // Validate first removal to catch queue corruption early
        // TODO: This is O(N) if we ever flush in the middle of a hot loop,
        // but for now deferred removal is rare enough that it's fine.
        let first = to_remove[0];
        if !self.entity_locations.contains_key(first) {
            return Err(EcsError::EntityNotFound);
        }

        self.despawn(first)?;

        // Subsequent entities may be duplicates or already removed (e.g., cascading despawns)
        // Skip gracefully to avoid crashing on valid scenarios
        for &entity in &to_remove[1..] {
            if self.entity_locations.contains_key(entity) {
                let _ = self.despawn(entity);
            }
        }

        Ok(())
    }

    /// Get entity location
    pub fn get_entity_location(&self, entity: EntityId) -> Option<EntityLocation> {
        self.entity_locations.get(entity).copied()
    }

    /// Get immutable reference to a component on an entity
    pub fn get_component<T: Component>(&self, entity: EntityId) -> Option<&T> {
        // Returns None for invalid entity - simpler API, caller decides error handling
        let location = self.entity_locations.get(entity)?;
        let archetype = self.archetypes.get(location.archetype_id)?;
        let column = archetype.get_column(TypeId::of::<T>())?;
        column.get::<T>(location.archetype_row)
    }

    /// Get mutable reference to a component on an entity
    pub fn get_component_mut<T: Component>(&mut self, entity: EntityId) -> Option<&mut T> {
        // BOUNDARY: Validate entity exists before component lookup
        let location = self.entity_locations.get(entity)?;
        let tick = self.tick;
        let archetype = self.archetypes.get_mut(location.archetype_id)?;
        let column = archetype.get_column_mut(TypeId::of::<T>())?;

        // Mark component as changed for change detection
        column.mark_changed(location.archetype_row, tick);

        column.get_mut::<T>(location.archetype_row)
    }

    /// Check if entity has a specific component
    pub fn has_component<T: Component>(&self, entity: EntityId) -> bool {
        if let Some(location) = self.entity_locations.get(entity) {
            if let Some(archetype) = self.archetypes.get(location.archetype_id) {
                return archetype.has_column(TypeId::of::<T>());
            }
        }
        false
    }

    /// Add a component to an entity
    ///
    /// This is an expensive operation as it moves the entity to a new archetype.
    pub fn add_component<T: Component>(&mut self, entity: EntityId, component: T) -> Result<()> {
        let location = *self
            .entity_locations
            .get(entity)
            .ok_or(EcsError::EntityNotFound)?;
        let old_archetype = &mut self.archetypes[location.archetype_id];

        // If component already exists, overwrite it
        if let Some(col) = old_archetype.get_column_mut(TypeId::of::<T>()) {
            let ptr = col.get_ptr_mut(location.archetype_row) as *mut T;
            unsafe {
                std::ptr::write(ptr, component);
            }
            return Ok(());
        }

        // Check cache first (fast path)
        let component_type = TypeId::of::<T>();

        if let Some(new_archetype_id) = old_archetype.get_add_edge(component_type) {
            // Fast path: archetype already exists in cache
            self.move_entity(entity, location, new_archetype_id, |archetype, row| {
                // Initialize new component
                if let Some(col) = archetype.get_column_mut(component_type) {
                    let ptr = col.get_ptr_mut(row) as *mut T;
                    unsafe {
                        std::ptr::write(ptr, component);
                    }
                }
            })?;
            return Ok(());
        }

        // Slow path: compute new archetype and cache it
        let mut new_signature = old_archetype.signature().clone();
        new_signature.push(component_type);

        // Capture existing columns to replicate them in new archetype
        // We need to do this before calling get_or_create_archetype as that requires mutable self access,
        // which would conflict with holding a reference to old_archetype.
        let mut columns_to_add = Vec::with_capacity(new_signature.len());
        for &type_id in old_archetype.signature() {
            if let Some(col) = old_archetype.get_column(type_id) {
                columns_to_add.push((type_id, col.clone_empty()));
            }
        }

        let new_archetype_id = self.get_or_create_archetype_with(&new_signature, |archetype| {
            for (type_id, col) in columns_to_add {
                archetype.add_column_raw(type_id, col);
            }
            archetype.register_component::<T>();
            archetype.mark_columns_initialized();
        });

        // Cache the transition for future use
        self.archetypes[location.archetype_id].set_add_edge(component_type, new_archetype_id);

        // Move entity
        self.move_entity(entity, location, new_archetype_id, |archetype, row| {
            // Initialize new component
            if let Some(col) = archetype.get_column_mut(TypeId::of::<T>()) {
                let ptr = col.get_ptr_mut(row) as *mut T;
                unsafe {
                    std::ptr::write(ptr, component);
                }
            }
        })
    }

    /// Remove a component from an entity
    ///
    /// This is an expensive operation as it moves the entity to a new archetype.
    pub fn remove_component<T: Component>(&mut self, entity: EntityId) -> Result<()> {
        let old_location = self
            .entity_locations
            .get(entity)
            .copied()
            .ok_or(EcsError::EntityNotFound)?;
        let old_archetype = &self.archetypes[old_location.archetype_id];

        // PRE-CONDITION: Verify component exists on entity
        let component_type_id = TypeId::of::<T>();
        if !old_archetype.has_column(component_type_id) {
            return Err(EcsError::ComponentNotFound);
        }

        // Check cache first (fast path)
        if let Some(new_archetype_id) = old_archetype.get_remove_edge(component_type_id) {
            self.move_entity(entity, old_location, new_archetype_id, |_, _| {})?;
            return Ok(());
        }

        // Build new signature (excluding component T)
        let mut new_signature = old_archetype.signature().clone();
        new_signature.retain(|tid| *tid != component_type_id);

        // Capture existing columns to replicate them in new archetype.
        // This must be done before we potentially push to self.archetypes.
        let mut columns_to_add = Vec::with_capacity(new_signature.len());
        for &type_id in &new_signature {
            if let Some(col) = old_archetype.get_column(type_id) {
                columns_to_add.push((type_id, col.clone_empty()));
            }
        }

        let new_archetype_id = self.get_or_create_archetype_with(&new_signature, |new_arch| {
            for (type_id, col) in columns_to_add {
                new_arch.add_column_raw(type_id, col);
            }
            new_arch.mark_columns_initialized();
        });

        // Cache the transition for future use
        self.archetypes[old_location.archetype_id]
            .set_remove_edge(component_type_id, new_archetype_id);

        // POST-CONDITION: Verify destination archetype is ready
        #[cfg(debug_assertions)]
        {
            let arch = &self.archetypes[new_archetype_id];
            debug_assert!(
                arch.columns_initialized(),
                "BUG: Destination archetype columns not initialized"
            );
            for &tid in arch.signature() {
                debug_assert!(
                    arch.has_column(tid),
                    "BUG: Destination archetype missing column for type {tid:?}"
                );
            }
        }

        // Safe migration: move entity and drop the removed component implicitly
        self.move_entity(entity, old_location, new_archetype_id, |_, _| {})
    }

    /// Get multiple immutable components at once using QueryFetch
    pub fn get_components<'a, Q>(&'a self, entity: EntityId) -> Option<<Q as QueryFetch<'a>>::Item>
    where
        Q: QueryFetch<'a>,
    {
        let location = self.entity_locations.get(entity)?;
        let archetype = self.archetypes.get(location.archetype_id)?;
        let state = Q::prepare(archetype, 0)?;
        unsafe { Q::fetch(&state, location.archetype_row) }
    }

    /// Get multiple mutable components at once using QueryFetchMut
    pub fn get_components_mut<'a, Q>(
        &'a mut self,
        entity: EntityId,
    ) -> Option<<Q as QueryFetchMut<'a>>::Item>
    where
        Q: QueryFetchMut<'a>,
    {
        let location = self.entity_locations.get(entity)?;
        let archetype = self.archetypes.get_mut(location.archetype_id)?;
        let mut state = Q::prepare(archetype, 0, self.tick)?;
        unsafe { Q::fetch(&mut state, location.archetype_row) }
    }

    /// Create an optimized view for query iteration
    ///
    /// Pre-calculates component pointers to speed up repeated iteration.
    pub fn view<'w, Q: QueryFilter + QueryFetch<'w>>(&'w self) -> crate::query::View<'w, Q> {
        crate::query::View::new(self, 0)
    }

    /// Create a mutable query wrapper for the provided filter
    pub fn query_mut<'w, Q>(&'w mut self) -> QueryMut<'w, Q>
    where
        Q: QueryFilter + QueryFetchMut<'w>,
    {
        QueryMut::new(self)
    }

    pub fn query<'w, Q>(&'w self) -> Query<'w, Q>
    where
        Q: QueryFilter + QueryFetch<'w>,
    {
        Query::new(self)
    }

    /// Create a parallel query wrapper for the provided filter
    ///
    /// Requires the "parallel" feature.
    #[cfg(feature = "parallel")]
    pub fn par_query_mut<'w, Q>(&'w mut self) -> crate::query::ParQuery<'w, Q>
    where
        Q: QueryFilter + QueryFetchMut<'w>,
    {
        crate::query::ParQuery::new(self.query_mut())
    }

    /// Internal: Move entity from one archetype to another
    fn move_entity<F>(
        &mut self,
        entity: EntityId,
        old_loc: EntityLocation,
        new_archetype_id: usize,
        on_new_location: F,
    ) -> Result<()>
    where
        F: FnOnce(&mut Archetype, usize),
    {
        if old_loc.archetype_id == new_archetype_id {
            return Ok(());
        }

        let tick = self.tick;
        // We need to ensure new archetype has space (it does via allocate_row logic usually, but let's be safe if reserve needed)
        // actually allocate_row just pushes.

        // Access both archetypes safely using split_at_mut
        // We need this to copy components from old to new.
        let (old_arch, new_arch) = if old_loc.archetype_id < new_archetype_id {
            let (left, right) = self.archetypes.split_at_mut(new_archetype_id);
            (&mut left[old_loc.archetype_id], &mut right[0])
        } else {
            let (left, right) = self.archetypes.split_at_mut(old_loc.archetype_id);
            (&mut right[0], &mut left[new_archetype_id])
        };

        // Allocate row in new archetype
        let new_row = new_arch.allocate_row(entity, tick);

        unsafe {
            let new_sig = new_arch.signature().to_vec();

            for &type_id in &new_sig {
                if let Some(old_col) = old_arch.get_column_mut(type_id) {
                    if let Some(new_col) = new_arch.get_column_mut(type_id) {
                        let src = old_col.get_ptr_mut(old_loc.archetype_row);
                        let dst = new_col.get_ptr_mut(new_row);
                        // Copy raw bytes
                        std::ptr::copy_nonoverlapping(src, dst, old_col.get_item_size());
                    }
                }
            }
        }

        on_new_location(new_arch, new_row);

        // Remove from old archetype
        unsafe {
            if let Some(swapped_entity) = old_arch.remove_row(old_loc.archetype_row) {
                if let Some(swapped_loc_ptr) = self.entity_locations.get_mut(swapped_entity) {
                    swapped_loc_ptr.archetype_row = old_loc.archetype_row;
                }
            }
        }

        // Update location of moved entity
        if let Some(loc) = self.entity_locations.get_mut(entity) {
            loc.archetype_id = new_archetype_id;
            loc.archetype_row = new_row;
        }

        Ok(())
    }

    /// Get cached query results (matched archetypes)
    ///
    /// This method manages the query cache, updating it incrementally if needed.
    /// It returns a vector of archetype indices that match the query.
    /// It returns a vector of archetype indices that match the query.
    pub(crate) fn get_cached_query_indices<Q: QueryFilter>(&self) -> Vec<usize> {
        let sig = Q::signature();

        // Fast path: existing state
        {
            let cache = self.query_cache.read();
            if let Some(cached) = cache.get(&sig) {
                if cached.seen_archetypes >= self.archetypes.len() {
                    return cached.matches.to_vec();
                }
            }
        }

        // Slow path: update or create
        let mut cache = self.query_cache.write();
        if let Some(cached) = cache.get_mut(&sig) {
            cached.update(self);
            return cached.matches.to_vec();
        }

        // Create new state
        let cached = crate::query::CachedQueryResult::new(sig.clone(), &self.archetypes);
        let indices = cached.matches.to_vec();
        cache.insert(sig, cached);
        indices
    }

    pub fn entity_exists(&self, entity: EntityId) -> bool {
        self.entity_locations.contains_key(entity)
    }

    /// Get archetype by ID
    pub fn get_archetype(&self, id: usize) -> Option<&Archetype> {
        self.archetypes.get(id)
    }

    /// Get archetype mutably
    pub fn get_archetype_mut(&mut self, id: usize) -> Option<&mut Archetype> {
        self.archetypes.get_mut(id)
    }

    /// Get all archetypes
    pub fn archetypes(&self) -> &[Archetype] {
        &self.archetypes
    }

    /// Internal helper to expose archetype pointers for query iteration
    pub(crate) fn archetype_ptr(&self, id: usize) -> Option<NonNull<Archetype>> {
        self.archetypes.get(id).map(NonNull::from)
    }

    /// Internal helper to expose archetype pointers for query iteration
    ///
    /// # Safety
    /// Returned pointer is valid for the lifetime of the world.
    /// Caller must ensure no aliasing violations when dereferencing.
    pub(crate) fn archetype_ptr_mut(&mut self, id: usize) -> Option<NonNull<Archetype>> {
        self.archetypes.get_mut(id).map(NonNull::from)
    }

    pub fn archetype_count(&self) -> usize {
        self.archetypes.len()
    }

    pub fn entity_count(&self) -> u32 {
        self.entity_locations.len() as u32
    }

    pub fn recycled_entity_count(&self) -> usize {
        self.recycled_entities
    }

    /// Flush command buffer
    pub fn flush_commands(&mut self, mut buffer: CommandBuffer) -> Result<()> {
        #[cfg(feature = "profiling")]
        let span = info_span!("world.flush_commands", queued = buffer.len());
        #[cfg(feature = "profiling")]
        let _span_guard = span.enter();

        buffer.apply(self)
    }

    /// Clear all entities
    pub fn clear(&mut self) {
        self.entity_locations.clear();
        self.recycled_entities = 0;
        self.archetypes.clear();
        self.arch_idx.clear();
        self.query_cache.write().clear();

        // Recreate empty archetype
        self.get_or_create_archetype(&[]); // FIXED
    }

    /// Get memory usage statistics
    pub fn memory_stats(&self) -> MemoryStats {
        let archetype_memory: usize = self
            .archetypes
            .iter()
            .map(|_a| std::mem::size_of::<Archetype>()) // FIXED: _a
            .sum();
        let entity_index_memory =
            self.entity_locations.capacity() * std::mem::size_of::<EntityLocation>();

        MemoryStats {
            entity_index_memory,
            archetype_memory,
            total_memory: archetype_memory + entity_index_memory,
        }
    }

    // ========== Resource API (Singleton State) ==========

    /// Insert a resource (singleton) into the world
    pub fn insert_resource<R: Send + Sync + 'static>(&mut self, resource: R) {
        self.resources.insert(TypeId::of::<R>(), Box::new(resource));
    }

    /// Get an immutable reference to a resource
    pub fn resource<R: 'static>(&self) -> Option<&R> {
        self.resources
            .get(&TypeId::of::<R>())
            .and_then(|r| r.downcast_ref())
    }

    /// Get a mutable reference to a resource
    ///
    /// Returns `None` if the resource doesn't exist.
    pub fn resource_mut<R: 'static>(&mut self) -> Option<&mut R> {
        self.resources
            .get_mut(&TypeId::of::<R>())
            .and_then(|r| r.downcast_mut())
    }

    /// Check if a resource exists
    pub fn has_resource<R: 'static>(&self) -> bool {
        self.resources.contains_key(&TypeId::of::<R>())
    }

    /// Remove a resource and return it
    pub fn remove_resource<R: 'static>(&mut self) -> Option<R> {
        self.resources
            .remove(&TypeId::of::<R>())
            .and_then(|r| r.downcast().ok())
            .map(|boxed| *boxed)
    }

    /// Get a mutable reference to a resource, inserting it if it doesn't exist
    pub fn get_or_insert_with<R: Send + Sync + 'static>(
        &mut self,
        f: impl FnOnce() -> R,
    ) -> &mut R {
        let type_id = TypeId::of::<R>();

        if !self.resources.contains_key(&type_id) {
            self.resources.insert(type_id, Box::new(f()));
        }

        // Internal helper - panic indicates programming error
        self.resources
            .get_mut(&type_id)
            .and_then(|r| r.downcast_mut())
            .expect("Resource should exist after init")
    }

    /// Insert a resource, returning error if it already exists
    ///
    /// Use this for setup-time initialization to prevent accidental overwrites.
    ///
    /// # Errors
    /// Returns `EcsError::ResourceAlreadyExists` if resource already exists
    pub fn init_resource<R: Send + Sync + 'static>(&mut self, resource: R) -> Result<()> {
        let type_id = TypeId::of::<R>();

        if self.resources.contains_key(&type_id) {
            return Err(EcsError::ResourceAlreadyExists(type_id));
        }

        self.resources.insert(type_id, Box::new(resource));
        Ok(())
    }

    /// Get or create archetype with caching for common signatures
    fn get_or_create_archetype(&mut self, signature: &[TypeId]) -> usize {
        // PARANOID: Prevent archetype explosion DoS attack
        if self.archetypes.len() >= 10_000 {
            panic!("Archetype limit exceeded (10,000) - possible DoS attempt or memory leak");
        }
        let signature_vec: ArchetypeSignature = SmallVec::from_slice(signature);
        self.get_or_create_archetype_with(&signature_vec, |_| {})
    }

    /// Get or create archetype with a callback for initialization
    fn get_or_create_archetype_with<F>(
        &mut self,
        signature: &ArchetypeSignature,
        on_create: F,
    ) -> usize
    where
        F: FnOnce(&mut Archetype),
    {
        // Sort signature to ensure canonical lookup (prevent archetype fragmentation)
        // This ensures that (A, B) and (B, A) map to the same archetype logic
        let mut sorted_signature = signature.clone();
        sorted_signature.sort();

        // Try to find in arch_idx first (more direct than cache)
        if let Some(&id) = self.arch_idx.get(&sorted_signature) {
            return id;
        }

        // Not found, create new archetype

        // Create new archetype with the sorted signature
        let mut archetype = Archetype::new(sorted_signature.clone());
        on_create(&mut archetype);

        // Push archetype FIRST to ensure it exists
        self.archetypes.push(archetype);
        let id = self.archetypes.len() - 1;

        // THEN cache the ID (prevents returning non-existent IDs)
        self.arch_idx.insert(sorted_signature, id);

        id
    }

    /// Spawn multiple entities with the same component bundle in a batch
    ///
    /// This is more efficient than calling `spawn` multiple times as it reduces
    /// the number of allocations and lookups.
    pub fn spawn_batch<B, I>(&mut self, bundles: I) -> Result<Vec<EntityId>>
    where
        B: Bundle,
        I: IntoIterator<Item = B>,
        I::IntoIter: ExactSizeIterator,
    {
        let bundles = bundles.into_iter();
        let count = bundles.len();

        // Limit batch size to prevent OOM and overflow (10M is generous but prevents DoS)
        if count > 10_000_000 {
            return Err(EcsError::BatchTooLarge);
        }

        if count == 0 {
            return Ok(Vec::new());
        }

        // Saturating add: prefer capped growth over overflow panic
        let current = self.entity_locations.len();
        let new_capacity = current.saturating_add(count).max(1024);

        if current + count > self.entity_locations.capacity() {
            let additional = new_capacity - current;
            self.entity_locations.reserve(additional);
        }

        // Get or create archetype first
        let type_ids = B::type_ids();
        let archetype_id = self.get_or_create_archetype_with(&type_ids, |archetype| {
            B::register_components(archetype);
            archetype.mark_columns_initialized();
        });

        // Get mutable reference to archetype after all lookups are done
        let archetype = &mut self.archetypes[archetype_id];
        let mut entity_ids = Vec::with_capacity(count);

        // Pre-allocate space in the archetype
        archetype.reserve_rows(count);

        // OPTIMIZATION: Pre-calculate column indices to avoid hash lookups in the hot loop
        let mut column_indices = [usize::MAX; MAX_BUNDLE_COMPONENTS];
        let mut col_count = 0;
        for &tid in type_ids.iter() {
            if let Some(idx) = archetype.column_index(tid) {
                column_indices[col_count] = idx;
                col_count += 1;
            }
        }

        // Process each bundle
        for bundle in bundles {
            let entity = self.entity_locations.insert(EntityLocation {
                archetype_id,
                archetype_row: 0, // Will be updated after allocation
            });

            // Allocate row in archetype
            let row = archetype.allocate_row(entity, self.tick);

            // Update entity location with correct row
            if let Some(loc) = self.entity_locations.get_mut(entity) {
                loc.archetype_row = row;
            }

            // Write component data using pre-calculated indices
            let mut ptrs = [std::ptr::null_mut(); MAX_BUNDLE_COMPONENTS];
            for i in 0..col_count {
                let col_idx = column_indices[i];
                if let Some(column) = archetype.get_column_mut_by_index(col_idx) {
                    ptrs[i] = column.get_ptr_mut(row);
                }
            }

            unsafe {
                bundle.write_components(&ptrs[..col_count]);
            }

            // Track components for change detection
            let mut component_set = std::collections::HashSet::new();
            for &tid in type_ids.iter() {
                component_set.insert(tid);
            }
            self.component_tracker.insert(entity, component_set);

            entity_ids.push(entity);
        }

        Ok(entity_ids)
    }

    /// Ensure we have enough capacity for new entities with an aggressive growth strategy
    fn ensure_entity_capacity(&mut self) -> crate::error::Result<()> {
        let len = self.entity_locations.len();

        // Check for overflow - indicates programming error, not user error
        if len == usize::MAX {
            return Err(crate::error::EcsError::SpawnError(
                crate::error::SpawnError::EntityCapacityExhausted {
                    attempted: 1,
                    capacity: usize::MAX,
                },
            ));
        }

        let cap = self.entity_locations.capacity();

        if len >= cap {
            // Aggressive growth to reduce reallocations
            let growth = (cap / 2).max(64);
            self.entity_locations.reserve(growth);
        }
        Ok(())
    }

    /// Spawn entity with components and trigger event
    pub fn spawn_with_event<B: Bundle>(&mut self, bundle: B) -> EntityId {
        let entity = self.spawn_entity(bundle);
        self.event_queue.push(EntityEvent::Spawned(entity));

        // Track components for this entity
        let type_ids = B::type_ids();
        let mut components = std::collections::HashSet::new();
        for &type_id in type_ids.iter() {
            components.insert(type_id);
            self.event_queue
                .push(EntityEvent::ComponentAdded(entity, type_id));
        }
        self.component_tracker.insert(entity, components);

        entity
    }

    /// Despawn entity and trigger event
    pub fn despawn_with_event(&mut self, entity: EntityId) -> Result<()> {
        self.despawn(entity)?;
        self.event_queue.push(EntityEvent::Despawned(entity));
        self.component_tracker.remove(&entity);
        Ok(())
    }

    /// Register observer
    pub fn register_observer(&mut self, mut observer: Box<dyn Observer>) -> Result<()> {
        // Call on_registered before storing
        observer.on_registered(self)?;
        self.observers.observers.push(observer);
        Ok(())
    }

    /// Process events with metrics collection (if enabled)
    pub fn process_events_with_metrics(&mut self) -> Result<()> {
        #[cfg(feature = "profiling")]
        {
            let start = std::time::Instant::now();
            self.process_events()?;
            let duration_us = start.elapsed().as_micros() as u64;
            self.observer_metrics.record_event("observer", duration_us);
            Ok(())
        }

        #[cfg(not(feature = "profiling"))]
        self.process_events()
    }

    /// Get observer metrics (if profiling enabled)
    pub fn get_observer_metrics(&self) -> Option<&crate::observer::ObserverMetrics> {
        #[cfg(feature = "profiling")]
        return Some(&self.observer_metrics);

        #[cfg(not(feature = "profiling"))]
        None
    }

    /// Reset observer metrics
    pub fn reset_observer_metrics(&mut self) {
        #[cfg(feature = "profiling")]
        self.observer_metrics.reset();
    }

    /// Process all pending events
    pub fn process_events(&mut self) -> Result<()> {
        // We need to work around Rust's borrow checker here.
        // We can't borrow event_queue and observers simultaneously since both are in self.
        // Solution: drain events into a temporary vector, then process with unsafe aliasing.
        let mut events_to_process = Vec::new();
        while let Some(event) = self.event_queue.pop() {
            events_to_process.push(event);
        }

        // Use unsafe to allow observers to access world (self) while we iterate observers
        // This is safe because:
        // 1. We're not modifying the observers vector itself during iteration
        // 2. Observers are expected to only read/write to specific parts of World
        // 3. This is similar to the parallel executor pattern
        let world_ptr = self as *mut World;

        for event in &events_to_process {
            for observer in &mut self.observers.observers {
                unsafe {
                    observer.on_event(event, &mut *world_ptr)?;
                }
            }
        }
        Ok(())
    }

    /// Manually trigger event
    pub fn trigger_event(&mut self, event: EntityEvent) {
        self.event_queue.push(event);
    }

    /// Get observer registry
    pub fn observers_mut(&mut self) -> &mut ObserverRegistry {
        &mut self.observers
    }

    /// Get event queue (for inspection)
    pub fn event_queue(&self) -> &EventQueue {
        &self.event_queue
    }

    // ========== Hierarchy Methods (Phase 5) ==========

    /// Get parent of entity
    pub fn get_parent(&self, entity: EntityId) -> Option<EntityId> {
        use crate::hierarchy::Parent;
        self.get_component::<Parent>(entity).map(|p| p.entity_id())
    }

    /// Get children of entity
    pub fn get_children(&self, entity: EntityId) -> Option<Vec<EntityId>> {
        use crate::hierarchy::Children;
        self.get_component::<Children>(entity)
            .map(|c| c.get_children())
    }

    /// Traverse hierarchy depth-first
    pub fn traverse_hierarchy<F>(&self, entity: EntityId, callback: &mut F) -> Result<()>
    where
        F: FnMut(EntityId) -> Result<()>,
    {
        use crate::hierarchy::Children;

        callback(entity)?;

        if let Some(children) = self.get_component::<Children>(entity) {
            for &child in children.iter() {
                self.traverse_hierarchy(child, callback)?;
            }
        }

        Ok(())
    }

    /// Get all descendants of entity
    pub fn get_descendants(&self, entity: EntityId) -> Result<Vec<EntityId>> {
        let mut descendants = Vec::new();

        self.traverse_hierarchy(entity, &mut |e| {
            if e != entity {
                // Don't include the entity itself
                descendants.push(e);
            }
            Ok(())
        })?;

        Ok(descendants)
    }

    /// Delete entity and all children recursively
    pub fn despawn_recursive(&mut self, entity: EntityId) -> Result<()> {
        // Get children before despawning
        let children = self.get_children(entity).unwrap_or_default();

        // Recursively despawn children
        for child in children {
            self.despawn_recursive(child)?;
        }

        // Despawn this entity
        self.despawn(entity)?;

        Ok(())
    }

    // ========== Global Event Bus Methods (Phase 6) ==========

    /// Get mutable reference to global event bus
    pub fn event_bus_mut(&mut self) -> &mut crate::event_bus::EventBus {
        &mut self.global_event_bus
    }

    /// Get immutable reference to global event bus
    pub fn event_bus(&self) -> &crate::event_bus::EventBus {
        &self.global_event_bus
    }

    /// Publish event to global event bus (convenience method)
    pub fn publish_global_event<E: crate::event_bus::Event + 'static>(
        &mut self,
        event: E,
    ) -> Result<()> {
        self.global_event_bus.publish_event(event)
    }

    /// Process all queued events in global event bus
    pub fn process_global_events(&mut self) -> Result<()> {
        self.global_event_bus.process_events()
    }

    // ========== Query Cache Management (Phase 2) ==========

    /// Get or update cached query results for a signature
    ///
    /// Uses incremental invalidation: only checks new archetypes since last cache update.
    /// This provides O(1) amortized performance for repeated queries.
    pub fn get_cached_query_indices_by_sig(
        &self,
        signature: &crate::query::QuerySignature,
    ) -> Vec<usize> {
        let current_archetype_count = self.archetypes.len();

        // Fast path: Try with read lock first
        {
            let cache = self.query_cache.read();
            if let Some(cached) = cache.get(signature) {
                if cached.seen_archetypes >= current_archetype_count {
                    return cached.matches.to_vec();
                }
            }
        }

        // Slow path: Need to initialize or update, take write lock
        let mut cache = self.query_cache.write();
        if let Some(cached) = cache.get_mut(signature) {
            if cached.seen_archetypes < current_archetype_count {
                cached.update(self);
            }
            cached.matches.to_vec()
        } else {
            let cached = crate::query::CachedQueryResult::new(signature.clone(), &self.archetypes);
            let indices = cached.matches.to_vec();
            cache.insert(signature.clone(), cached);
            indices
        }
    }

    /// Clear all cached query results
    ///
    /// Useful for testing or when you need to force cache invalidation.
    pub fn clear_query_cache(&self) {
        self.query_cache.write().clear();
    }

    /// Print entity state for debugging
    ///
    /// This method displays all components on an entity in a readable format.
    /// Useful for debugging entity state during development.
    ///
    /// # Example
    /// ```
    /// # let mut world = archetype_ecs::World::new();
    /// # let entity_id = world.spawn((1.0f32, 0.1f32));
    /// world.debug_print_entity(entity_id);
    /// // Output shows entity with its components
    /// ```
    pub fn debug_print_entity(&self, entity: EntityId) {
        if let Some(loc) = self.entity_locations.get(entity) {
            let archetype = &self.archetypes[loc.archetype_id];
            println!("Entity#? {{");

            // Print each component type ID
            for type_id in archetype.signature().iter() {
                println!("  {type_id:?}: <component data>");
            }

            println!("}}");
        } else {
            println!("Entity#?: <not found>");
        }
    }

    /// Print all entities that have a specific component
    ///
    /// Useful for finding entities with certain components during debugging.
    ///
    /// # Example
    /// ```
    /// # let mut world = archetype_ecs::World::new();
    /// # world.spawn((1.0f32, 0.1f32));
    /// # world.spawn((2.0f32, 0.2f32));
    /// world.debug_print_entities_with::<f32>();
    /// // Output shows all entities with f32 components
    /// ```
    pub fn debug_print_entities_with<T: Component>(&self) {
        let type_id = std::any::TypeId::of::<T>();
        let mut count = 0;

        for (_entity, loc) in self.entity_locations.iter() {
            let archetype = &self.archetypes[loc.archetype_id];
            if archetype.signature().contains(&type_id) {
                println!("Entity#? has component {:?}", std::any::type_name::<T>());
                count += 1;
            }
        }

        if count == 0 {
            println!(
                "No entities found with component {:?}",
                std::any::type_name::<T>()
            );
        } else {
            println!(
                "Found {} entities with component {:?}",
                count,
                std::any::type_name::<T>()
            );
        }
    }

    /// Print memory usage statistics for debugging
    ///
    /// This method provides insight into memory usage patterns and can help
    /// identify memory leaks or inefficient usage.
    pub fn debug_print_memory_stats(&self) {
        let stats = self.memory_stats();
        println!("=== Memory Usage Statistics ===");
        println!("Entity Index Memory: {} bytes", stats.entity_index_memory);
        println!("Archetype Memory: {} bytes", stats.archetype_memory);
        println!("Total Memory: {} bytes", stats.total_memory);
        println!("Entity Count: {}", self.entity_count());
        println!("Archetype Count: {}", self.archetype_count());
        println!("Recycled Entities: {}", self.recycled_entity_count());
        println!("==============================");
    }

    /// Print query cache statistics for debugging
    ///
    /// This method shows how the query cache is performing and can help
    /// identify cache hit/miss patterns.
    pub fn debug_print_query_cache_stats(&self) {
        let cache = self.query_cache.read();
        let total_cached_archetypes: usize =
            cache.values().map(|cached| cached.matches.len()).sum();

        println!("=== Query Cache Statistics ===");
        println!("Cached Queries: {}", cache.len());
        println!("Total Cached Archetypes: {total_cached_archetypes}");
        println!("Total Archetypes: {}", self.archetypes.len());
        println!(
            "Cache Efficiency: {:.1}%",
            (total_cached_archetypes as f64 / self.archetypes.len().max(1) as f64) * 100.0
        );
        println!("=============================");
    }

    /// Get query cache statistics
    ///
    /// Returns statistics about the query cache performance.
    pub fn query_cache_stats(&self) -> QueryCacheStats {
        let cache = self.query_cache.read();
        let total_cached_archetypes: usize =
            cache.values().map(|cached| cached.matches.len()).sum();

        QueryCacheStats {
            num_cached_queries: cache.len(),
            total_cached_archetypes,
            total_archetypes: self.archetypes.len(),
        }
    }
}

/// Statistics about the query cache
#[derive(Debug, Clone, Copy)]
pub struct QueryCacheStats {
    /// Number of unique query signatures cached
    pub num_cached_queries: usize,
    /// Total number of archetype matches across all cached queries
    pub total_cached_archetypes: usize,
    /// Total number of archetypes in the world
    pub total_archetypes: usize,
}

impl Default for World {
    fn default() -> Self {
        Self::new()
    }
}

/// Memory statistics for the world
#[derive(Debug, Clone)]
pub struct MemoryStats {
    pub entity_index_memory: usize,
    pub archetype_memory: usize,
    pub total_memory: usize,
}

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

    #[test]
    fn test_spawn_despawn() -> Result<()> {
        let mut world = World::new();

        let entity = world.spawn_entity((42i32,));
        assert!(world.get_entity_location(entity).is_some());

        world.despawn(entity).unwrap();
        world.flush_removals().unwrap(); // Process deferred removals
        assert!(world.get_entity_location(entity).is_none());
        Ok(())
    }

    #[test]
    fn test_archetype_segregation() {
        let mut world = World::new();

        struct A;
        struct B;
        struct C;

        world.spawn_entity((A, B));
        world.spawn_entity((A, C));
        world.spawn_entity((B, C));

        // Should create 4 archetypes (+ empty one)
        assert!(world.archetype_count() >= 4);
    }
}

/// A pointer to the world that can be used to bypass standard borrow checking.
///
/// # Safety
/// This is an extremely dangerous type. It is only safe to use when the scheduler
/// has guaranteed that no two systems will access the same component mutably.
#[derive(Copy, Clone)]
pub struct UnsafeWorldCell<'a> {
    world: NonNull<World>,
    _marker: PhantomData<&'a mut World>,
}

unsafe impl<'a> Send for UnsafeWorldCell<'a> {}
unsafe impl<'a> Sync for UnsafeWorldCell<'a> {}

impl<'a> UnsafeWorldCell<'a> {
    pub(crate) unsafe fn new(world: &mut World) -> Self {
        Self {
            world: NonNull::from(world),
            _marker: PhantomData,
        }
    }

    /// Get raw pointer to an archetype
    ///
    /// # Safety
    /// Caller must ensure no aliasing violations.
    pub unsafe fn get_archetype_ptr(&self, id: usize) -> Option<NonNull<Archetype>> {
        self.world.as_ref().archetypes.get(id).map(NonNull::from)
    }

    /// Get world tick
    pub fn tick(&self) -> u32 {
        unsafe { self.world.as_ref().tick }
    }

    /// Get raw pointer to a component column
    ///
    /// # Safety
    /// Caller must ensure no aliasing violations.
    pub unsafe fn get_column_raw(
        &self,
        archetype_id: usize,
        type_id: TypeId,
    ) -> Option<*const ComponentColumn> {
        let arch = self.world.as_ref().archetypes.get(archetype_id)?;
        arch.get_column_raw(type_id)
    }

    /// Get raw mutable pointer to a component column
    ///
    /// # Safety
    /// This is the core "unsafe" bypass. Caller must guarantee disjoint access
    /// to this component type across all threads using this cell.
    pub unsafe fn get_column_raw_mut(
        &self,
        archetype_id: usize,
        type_id: TypeId,
    ) -> Option<*mut ComponentColumn> {
        let world = &mut *self.world.as_ptr();
        let arch = world.archetypes.get_mut(archetype_id)?;
        arch.get_column_raw_mut(type_id)
    }

    /// Get pointer to the world
    pub fn world_ptr(&self) -> *mut World {
        self.world.as_ptr()
    }

    /// Get total number of archetypes
    pub fn archetype_count(&self) -> usize {
        unsafe { self.world.as_ref().archetypes.len() }
    }

    /// Get cached query indices (matched archetypes)
    pub fn get_cached_query_indices<Q: crate::query::QueryFilter>(&self) -> Vec<usize> {
        unsafe { (&*self.world.as_ptr()).get_cached_query_indices::<Q>() }
    }
}