proof-engine 0.1.1

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

#![allow(dead_code)]

use std::{any::{Any, TypeId}, collections::HashMap};

// ---------------------------------------------------------------------------
// Component trait
// ---------------------------------------------------------------------------

/// Marker trait for ECS components. Implement this for any `'static + Send +
/// Sync + Clone` type to use it as a component.
pub trait Component: 'static + Send + Sync + Clone {}

// ---------------------------------------------------------------------------
// Entity (generational ID)
// ---------------------------------------------------------------------------

/// A lightweight generational handle identifying a live entity.
///
/// `index` is the slot in the allocator; `generation` differentiates reused
/// slots so stale handles can be detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Entity {
    /// Slot index.
    pub index: u32,
    /// Generation counter (incremented on free).
    pub generation: u32,
}

impl Entity {
    /// Constructs an entity from raw parts.
    #[inline] pub fn from_raw(index: u32, generation: u32) -> Self { Self { index, generation } }
    /// Returns the null sentinel (never alive).
    #[inline] pub fn null() -> Self { Self { index: u32::MAX, generation: u32::MAX } }
    /// True if this is the null sentinel.
    #[inline] pub fn is_null(self) -> bool { self.index == u32::MAX }
}

impl std::fmt::Display for Entity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Entity({}v{})", self.index, self.generation)
    }
}

// ---------------------------------------------------------------------------
// Entity allocator
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
struct EntityRecord { generation: u32, location: Option<EntityLocation> }

#[derive(Debug, Clone, Copy)]
struct EntityLocation { archetype_id: ArchetypeId, row: usize }

#[derive(Debug, Default)]
struct EntityAllocator { records: Vec<EntityRecord>, free: Vec<u32> }

impl EntityAllocator {
    fn alloc(&mut self) -> Entity {
        if let Some(idx) = self.free.pop() {
            let gen = self.records[idx as usize].generation;
            Entity { index: idx, generation: gen }
        } else {
            let idx = self.records.len() as u32;
            self.records.push(EntityRecord { generation: 0, location: None });
            Entity { index: idx, generation: 0 }
        }
    }
    fn free(&mut self, e: Entity) {
        let r = &mut self.records[e.index as usize];
        r.generation = r.generation.wrapping_add(1);
        r.location = None;
        self.free.push(e.index);
    }
    fn is_alive(&self, e: Entity) -> bool {
        self.records.get(e.index as usize)
            .map(|r| r.generation == e.generation && r.location.is_some())
            .unwrap_or(false)
    }
    fn location(&self, e: Entity) -> Option<EntityLocation> {
        self.records.get(e.index as usize)
            .filter(|r| r.generation == e.generation)
            .and_then(|r| r.location)
    }
    fn set_location(&mut self, e: Entity, loc: EntityLocation) {
        if let Some(r) = self.records.get_mut(e.index as usize) {
            if r.generation == e.generation { r.location = Some(loc); }
        }
    }
}

// ---------------------------------------------------------------------------
// AnyVec — type-erased dense vector
// ---------------------------------------------------------------------------

struct AnyVec {
    type_id: TypeId,
    len: usize,
    data: Vec<u8>,
    element_size: usize,
    element_align: usize,
    drop_fn: unsafe fn(*mut u8),
    clone_fn: unsafe fn(*const u8, *mut u8),
}
unsafe impl Send for AnyVec {}
unsafe impl Sync for AnyVec {}

impl AnyVec {
    fn new<T: Component>() -> Self {
        let align = std::mem::align_of::<T>();
        let size = std::mem::size_of::<T>();
        // Round element_size up to alignment so every slot is aligned
        let padded = if align > 0 && size > 0 { (size + align - 1) & !(align - 1) } else { size };
        Self {
            type_id: TypeId::of::<T>(),
            len: 0,
            data: Vec::new(),
            element_size: padded,
            element_align: align,
            drop_fn: |p| unsafe { std::ptr::drop_in_place(p as *mut T) },
            clone_fn: |s, d| unsafe { std::ptr::write(d as *mut T, (*(s as *const T)).clone()) },
        }
    }

    fn reserve_one(&mut self) {
        let sz = self.element_size;
        if sz == 0 { return; }
        let need = (self.len + 1) * sz + self.element_align; // extra for alignment padding
        if self.data.len() < need {
            self.data.resize(need.max(self.data.len() * 2).max(sz * 4 + self.element_align), 0);
        }
    }

    /// Return the base pointer, aligned to element_align.
    fn aligned_base(&self) -> *const u8 {
        let ptr = self.data.as_ptr() as usize;
        let align = self.element_align.max(1);
        let aligned = (ptr + align - 1) & !(align - 1);
        aligned as *const u8
    }

    fn aligned_base_mut(&mut self) -> *mut u8 {
        let ptr = self.data.as_mut_ptr() as usize;
        let align = self.element_align.max(1);
        let aligned = (ptr + align - 1) & !(align - 1);
        aligned as *mut u8
    }

    fn push<T: Component>(&mut self, v: T) {
        self.reserve_one();
        unsafe { std::ptr::write(self.aligned_base_mut().add(self.len * self.element_size) as *mut T, v); }
        self.len += 1;
    }

    fn get<T: Component>(&self, row: usize) -> &T {
        unsafe { &*(self.aligned_base().add(row * self.element_size) as *const T) }
    }

    fn get_mut<T: Component>(&mut self, row: usize) -> &mut T {
        unsafe { &mut *(self.aligned_base_mut().add(row * self.element_size) as *mut T) }
    }

    fn get_ptr(&self, row: usize) -> *const u8 {
        unsafe { self.aligned_base().add(row * self.element_size) }
    }

    fn swap_remove_raw(&mut self, row: usize) {
        let last = self.len - 1;
        let sz = self.element_size;
        unsafe {
            let base = self.aligned_base_mut();
            let dst = base.add(row * sz);
            (self.drop_fn)(dst);
            if row != last {
                let src = base.add(last * sz) as *const u8;
                std::ptr::copy_nonoverlapping(src, dst, sz);
            }
        }
        self.len -= 1;
    }
}

impl Drop for AnyVec {
    fn drop(&mut self) {
        for i in 0..self.len {
            unsafe { (self.drop_fn)(self.aligned_base_mut().add(i * self.element_size)); }
        }
    }
}

// ---------------------------------------------------------------------------
// ComponentStorage — column + change-detection ticks
// ---------------------------------------------------------------------------

struct ComponentStorage {
    column: AnyVec,
    added_ticks: Vec<u32>,
    changed_ticks: Vec<u32>,
}

impl ComponentStorage {
    fn new<T: Component>() -> Self {
        Self { column: AnyVec::new::<T>(), added_ticks: Vec::new(), changed_ticks: Vec::new() }
    }

    fn push<T: Component>(&mut self, v: T, tick: u32) {
        self.column.push(v);
        self.added_ticks.push(tick);
        self.changed_ticks.push(tick);
    }

    fn swap_remove(&mut self, row: usize) {
        self.column.swap_remove_raw(row);
        let last = self.added_ticks.len() - 1;
        self.added_ticks.swap(row, last); self.added_ticks.pop();
        let last = self.changed_ticks.len() - 1;
        self.changed_ticks.swap(row, last); self.changed_ticks.pop();
    }

    /// Clone row `row` from this storage into `dst`, appending it.
    fn clone_row_into(&self, row: usize, dst: &mut ComponentStorage, tick: u32) {
        let sz = self.column.element_size;
        let need = (dst.column.len + 1) * sz;
        if dst.column.data.len() < need {
            dst.column.data.resize(need.max(dst.column.data.len() * 2).max(sz * 4), 0);
        }
        unsafe {
            let s = self.column.aligned_base().add(row * sz);
            let d = dst.column.aligned_base_mut().add(dst.column.len * sz);
            (self.column.clone_fn)(s, d);
        }
        dst.column.len += 1;
        dst.added_ticks.push(self.added_ticks[row]);
        dst.changed_ticks.push(tick);
    }
}

// ---------------------------------------------------------------------------
// Archetype
// ---------------------------------------------------------------------------

/// Unique index into [`World::archetypes`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ArchetypeId(pub u32);

/// A table of entities that share exactly the same component type set.
pub struct Archetype {
    /// Unique id for this archetype.
    pub id: ArchetypeId,
    /// Sorted, deduplicated component `TypeId`s.
    pub component_types: Vec<TypeId>,
    columns: HashMap<TypeId, ComponentStorage>,
    /// Entity handle at each row.
    pub entities: Vec<Entity>,
}

impl Archetype {
    fn new(id: ArchetypeId, types: Vec<TypeId>) -> Self {
        Self { id, component_types: types, columns: HashMap::new(), entities: Vec::new() }
    }

    fn register_column<T: Component>(&mut self) {
        self.columns.entry(TypeId::of::<T>()).or_insert_with(ComponentStorage::new::<T>);
    }

    /// Returns `true` if this archetype has a column for `tid`.
    pub fn contains(&self, tid: TypeId) -> bool { self.columns.contains_key(&tid) }

    /// Number of entities in this archetype.
    pub fn len(&self) -> usize { self.entities.len() }

    /// `true` if empty.
    pub fn is_empty(&self) -> bool { self.entities.is_empty() }

    /// Swap-removes row `row`. Returns the entity swapped into that row, if any.
    fn swap_remove(&mut self, row: usize) -> Option<Entity> {
        let last = self.entities.len() - 1;
        for col in self.columns.values_mut() { col.swap_remove(row); }
        self.entities.swap(row, last);
        self.entities.pop();
        if row < self.entities.len() { Some(self.entities[row]) } else { None }
    }
}

// ---------------------------------------------------------------------------
// Bundle
// ---------------------------------------------------------------------------

/// A heterogeneous set of components spawned together.
pub trait Bundle: 'static + Send + Sync {
    /// Sorted `TypeId`s of all components.
    fn type_ids() -> Vec<TypeId>;
    /// Ensure all columns exist on `arch`.
    fn register_columns(arch: &mut Archetype);
    /// Push all components into `arch`.
    fn insert_into(self, arch: &mut Archetype, tick: u32);
}

impl<C: Component> Bundle for C {
    fn type_ids() -> Vec<TypeId> { vec![TypeId::of::<C>()] }
    fn register_columns(a: &mut Archetype) { a.register_column::<C>(); }
    fn insert_into(self, a: &mut Archetype, tick: u32) {
        a.columns.get_mut(&TypeId::of::<C>()).expect("col missing").push(self, tick);
    }
}

macro_rules! impl_bundle {
    ($($C:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($C: Component),+> Bundle for ($($C,)+) {
            fn type_ids() -> Vec<TypeId> {
                let mut v = vec![$(TypeId::of::<$C>()),+]; v.sort(); v.dedup(); v
            }
            fn register_columns(a: &mut Archetype) { $(a.register_column::<$C>();)+ }
            fn insert_into(self, a: &mut Archetype, tick: u32) {
                let ($($C,)+) = self;
                $(a.columns.get_mut(&TypeId::of::<$C>()).expect("col missing").push($C, tick);)+
            }
        }
    };
}
impl_bundle!(A, B);
impl_bundle!(A, B, C);
impl_bundle!(A, B, C, D);
impl_bundle!(A, B, C, D, E);
impl_bundle!(A, B, C, D, E, F);
impl_bundle!(A, B, C, D, E, F, G);
impl_bundle!(A, B, C, D, E, F, G, H);

// ---------------------------------------------------------------------------
// Resources
// ---------------------------------------------------------------------------

/// Type-map of global singleton resources.
#[derive(Default)]
pub struct Resources {
    map: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
}

impl Resources {
    /// Creates an empty resource map.
    pub fn new() -> Self { Self::default() }
    /// Inserts (or replaces) a resource.
    pub fn insert<T: 'static + Send + Sync>(&mut self, v: T) {
        self.map.insert(TypeId::of::<T>(), Box::new(v));
    }
    /// Returns `&T` if present.
    pub fn get<T: 'static + Send + Sync>(&self) -> Option<&T> {
        self.map.get(&TypeId::of::<T>())?.downcast_ref()
    }
    /// Returns `&mut T` if present.
    pub fn get_mut<T: 'static + Send + Sync>(&mut self) -> Option<&mut T> {
        self.map.get_mut(&TypeId::of::<T>())?.downcast_mut()
    }
    /// Removes and returns `T`.
    pub fn remove<T: 'static + Send + Sync>(&mut self) -> Option<T> {
        self.map.remove(&TypeId::of::<T>())
            .and_then(|b| b.downcast::<T>().ok()).map(|b| *b)
    }
    /// `true` if resource `T` is present.
    pub fn contains<T: 'static + Send + Sync>(&self) -> bool {
        self.map.contains_key(&TypeId::of::<T>())
    }
}

// ---------------------------------------------------------------------------
// Res<T> / ResMut<T>
// ---------------------------------------------------------------------------

/// Immutable resource borrow.
pub struct Res<'a, T: 'static + Send + Sync> { inner: &'a T }
impl<'a, T: 'static + Send + Sync> Res<'a, T> {
    /// Wraps a reference.
    pub fn new(inner: &'a T) -> Self { Self { inner } }
}
impl<'a, T: 'static + Send + Sync> std::ops::Deref for Res<'a, T> {
    type Target = T; fn deref(&self) -> &T { self.inner }
}

/// Mutable resource borrow.
pub struct ResMut<'a, T: 'static + Send + Sync> { inner: &'a mut T }
impl<'a, T: 'static + Send + Sync> ResMut<'a, T> {
    /// Wraps a mutable reference.
    pub fn new(inner: &'a mut T) -> Self { Self { inner } }
}
impl<'a, T: 'static + Send + Sync> std::ops::Deref for ResMut<'a, T> {
    type Target = T; fn deref(&self) -> &T { self.inner }
}
impl<'a, T: 'static + Send + Sync> std::ops::DerefMut for ResMut<'a, T> {
    fn deref_mut(&mut self) -> &mut T { self.inner }
}

// ---------------------------------------------------------------------------
// Local<T>
// ---------------------------------------------------------------------------

/// System-local persistent state.
pub struct Local<T: Default + 'static> { value: T }
impl<T: Default + 'static> Local<T> {
    /// Initialises with `value`.
    pub fn new(value: T) -> Self { Self { value } }
    /// Initialises with `T::default()`.
    pub fn default_value() -> Self { Self { value: T::default() } }
}
impl<T: Default + 'static> std::ops::Deref for Local<T> {
    type Target = T; fn deref(&self) -> &T { &self.value }
}
impl<T: Default + 'static> std::ops::DerefMut for Local<T> {
    fn deref_mut(&mut self) -> &mut T { &mut self.value }
}

// ---------------------------------------------------------------------------
// Events<E>
// ---------------------------------------------------------------------------

/// Double-buffered typed event queue.
pub struct Events<E: 'static + Send + Sync> {
    buffers: [Vec<E>; 2],
    current: usize,
    event_count: usize,
    start_event_count: usize,
}

impl<E: 'static + Send + Sync> Default for Events<E> {
    fn default() -> Self {
        Self { buffers: [Vec::new(), Vec::new()], current: 0, event_count: 0, start_event_count: 0 }
    }
}

impl<E: 'static + Send + Sync> Events<E> {
    /// Creates a new empty queue.
    pub fn new() -> Self { Self::default() }
    /// Appends an event.
    pub fn send(&mut self, e: E) { self.buffers[self.current].push(e); self.event_count += 1; }
    /// Swaps buffers and clears the stale one (call once per frame).
    pub fn update(&mut self) {
        let next = 1 - self.current;
        self.buffers[next].clear();
        self.start_event_count = self.event_count - self.buffers[self.current].len();
        self.current = next;
    }
    /// Returns a cursor at the current end (reads only future events).
    pub fn get_reader(&self) -> EventCursor { EventCursor { last: self.event_count } }
    /// Returns a cursor at the oldest buffered event.
    pub fn get_reader_current(&self) -> EventCursor { EventCursor { last: self.start_event_count } }
    /// Reads all events since `cursor`, advancing it.
    pub fn read<'a>(&'a self, cursor: &mut EventCursor) -> impl Iterator<Item = &'a E> {
        let start = cursor.last;
        cursor.last = self.event_count;
        let old = &self.buffers[1 - self.current];
        let new = &self.buffers[self.current];
        let base = self.start_event_count;
        let sk0 = start.saturating_sub(base);
        let tk0 = old.len().saturating_sub(sk0);
        let sk1 = start.saturating_sub(base + old.len());
        let tk1 = new.len().saturating_sub(sk1);
        old.iter().skip(sk0).take(tk0).chain(new.iter().skip(sk1).take(tk1))
    }
    /// Total events sent since creation.
    pub fn len(&self) -> usize { self.event_count }
    /// `true` if both buffers are empty.
    pub fn is_empty(&self) -> bool { self.buffers[0].is_empty() && self.buffers[1].is_empty() }
    /// Clears all buffered events.
    pub fn clear(&mut self) { self.buffers[0].clear(); self.buffers[1].clear(); }
}

/// An independent read cursor into [`Events<E>`].
#[derive(Debug, Clone, Default)]
pub struct EventCursor { last: usize }

/// Write handle for [`Events<E>`].
pub struct EventWriter<'a, E: 'static + Send + Sync> { events: &'a mut Events<E> }
impl<'a, E: 'static + Send + Sync> EventWriter<'a, E> {
    /// Creates a writer.
    pub fn new(events: &'a mut Events<E>) -> Self { Self { events } }
    /// Sends an event.
    pub fn send(&mut self, e: E) { self.events.send(e); }
    /// Sends events from an iterator.
    pub fn send_batch(&mut self, it: impl IntoIterator<Item = E>) { for e in it { self.events.send(e); } }
}

/// Read handle for [`Events<E>`] with its own cursor.
pub struct EventReader<'a, E: 'static + Send + Sync> { events: &'a Events<E>, cursor: EventCursor }
impl<'a, E: 'static + Send + Sync> EventReader<'a, E> {
    /// Reads only future events.
    pub fn new(events: &'a Events<E>) -> Self { Self { cursor: events.get_reader(), events } }
    /// Reads all buffered events.
    pub fn new_current(events: &'a Events<E>) -> Self { Self { cursor: events.get_reader_current(), events } }
    /// Returns an iterator over unread events.
    pub fn read(&mut self) -> impl Iterator<Item = &E> { self.events.read(&mut self.cursor) }
}

// ---------------------------------------------------------------------------
// Commands
// ---------------------------------------------------------------------------

enum Cmd {
    Spawn(Box<dyn FnOnce(&mut World) + Send + Sync>),
    Despawn(Entity),
    Insert(Box<dyn FnOnce(&mut World) + Send + Sync>),
    Remove(Entity, TypeId),
    InsertRes(Box<dyn FnOnce(&mut World) + Send + Sync>),
    RemoveRes(TypeId),
}

/// Deferred world mutations applied at end-of-frame.
pub struct Commands { queue: Vec<Cmd> }
impl Commands {
    /// Creates an empty command queue.
    pub fn new() -> Self { Self { queue: Vec::new() } }
    /// Queues a bundle spawn.
    pub fn spawn<B: Bundle>(&mut self, b: B) {
        self.queue.push(Cmd::Spawn(Box::new(move |w| { w.spawn(b); })));
    }
    /// Queues a despawn.
    pub fn despawn(&mut self, e: Entity) { self.queue.push(Cmd::Despawn(e)); }
    /// Queues a component insertion.
    pub fn insert<C: Component>(&mut self, e: Entity, c: C) {
        self.queue.push(Cmd::Insert(Box::new(move |w| w.insert(e, c))));
    }
    /// Queues a component removal.
    pub fn remove<C: Component>(&mut self, e: Entity) {
        self.queue.push(Cmd::Remove(e, TypeId::of::<C>()));
    }
    /// Queues a resource insertion.
    pub fn insert_resource<T: 'static + Send + Sync>(&mut self, v: T) {
        self.queue.push(Cmd::InsertRes(Box::new(move |w| w.resources.insert(v))));
    }
    /// Queues a resource removal.
    pub fn remove_resource<T: 'static + Send + Sync>(&mut self) {
        self.queue.push(Cmd::RemoveRes(TypeId::of::<T>()));
    }
    /// Applies all queued commands and clears the queue.
    pub fn apply(&mut self, world: &mut World) {
        for cmd in self.queue.drain(..) {
            match cmd {
                Cmd::Spawn(f) => f(world),
                Cmd::Despawn(e) => { world.despawn(e); }
                Cmd::Insert(f) => f(world),
                Cmd::Remove(e, tid) => world.remove_by_type_id(e, tid),
                Cmd::InsertRes(f) => f(world),
                Cmd::RemoveRes(tid) => { world.resources.map.remove(&tid); }
            }
        }
    }
    /// `true` if no commands are queued.
    pub fn is_empty(&self) -> bool { self.queue.is_empty() }
}
impl Default for Commands { fn default() -> Self { Self::new() } }

// ---------------------------------------------------------------------------
// Query filters
// ---------------------------------------------------------------------------

/// Requires component `T` to be present (not fetched).
pub struct With<T: Component>(std::marker::PhantomData<T>);
/// Requires component `T` to be absent.
pub struct Without<T: Component>(std::marker::PhantomData<T>);
/// Change-detection filter: component `T` was added.
pub struct Added<T: Component>(std::marker::PhantomData<T>);
/// Change-detection filter: component `T` was mutably accessed.
pub struct Changed<T: Component>(std::marker::PhantomData<T>);

/// Archetype-level filter for queries.
pub trait QueryFilter {
    /// `true` if the archetype passes this filter.
    fn matches_archetype(arch: &Archetype) -> bool;
}
impl QueryFilter for () { fn matches_archetype(_: &Archetype) -> bool { true } }
impl<T: Component> QueryFilter for With<T> {
    fn matches_archetype(a: &Archetype) -> bool { a.contains(TypeId::of::<T>()) }
}
impl<T: Component> QueryFilter for Without<T> {
    fn matches_archetype(a: &Archetype) -> bool { !a.contains(TypeId::of::<T>()) }
}
impl<A: QueryFilter, B: QueryFilter> QueryFilter for (A, B) {
    fn matches_archetype(a: &Archetype) -> bool { A::matches_archetype(a) && B::matches_archetype(a) }
}
impl<A: QueryFilter, B: QueryFilter, C: QueryFilter> QueryFilter for (A, B, C) {
    fn matches_archetype(a: &Archetype) -> bool {
        A::matches_archetype(a) && B::matches_archetype(a) && C::matches_archetype(a)
    }
}

// ---------------------------------------------------------------------------
// WorldQuery fetch markers and trait
// ---------------------------------------------------------------------------

/// Fetch marker: yields `&'w T`.
pub struct Read<T: Component>(std::marker::PhantomData<T>);
/// Fetch marker: yields `&'w mut T`.
pub struct Write<T: Component>(std::marker::PhantomData<T>);
/// Fetch marker: yields `Option<&'w T>` (entity need not have T).
pub struct OptionRead<T: Component>(std::marker::PhantomData<T>);

/// Trait for types that describe how to fetch data from an archetype row.
pub trait WorldQuery: 'static {
    /// The type yielded per entity.
    type Item<'w>;
    /// Required component `TypeId`s (must all be present in the archetype).
    fn required_types() -> Vec<TypeId>;
    /// `true` if `arch` satisfies this query.
    fn matches(arch: &Archetype) -> bool;
    /// Fetches the item for `row` in `arch`.
    ///
    /// # Safety
    /// `row` must be valid; aliasing rules must be upheld by the caller.
    unsafe fn fetch<'w>(arch: &'w Archetype, row: usize) -> Self::Item<'w>;
}

impl<T: Component> WorldQuery for Read<T> {
    type Item<'w> = &'w T;
    fn required_types() -> Vec<TypeId> { vec![TypeId::of::<T>()] }
    fn matches(a: &Archetype) -> bool { a.contains(TypeId::of::<T>()) }
    unsafe fn fetch<'w>(a: &'w Archetype, row: usize) -> &'w T {
        a.columns[&TypeId::of::<T>()].column.get::<T>(row)
    }
}

impl<T: Component> WorldQuery for Write<T> {
    type Item<'w> = &'w mut T;
    fn required_types() -> Vec<TypeId> { vec![TypeId::of::<T>()] }
    fn matches(a: &Archetype) -> bool { a.contains(TypeId::of::<T>()) }
    unsafe fn fetch<'w>(a: &'w Archetype, row: usize) -> &'w mut T {
        let ptr = a.columns.get(&TypeId::of::<T>()).unwrap().column.get_ptr(row) as *mut T;
        &mut *ptr
    }
}

impl<T: Component> WorldQuery for OptionRead<T> {
    type Item<'w> = Option<&'w T>;
    fn required_types() -> Vec<TypeId> { vec![] }
    fn matches(_: &Archetype) -> bool { true }
    unsafe fn fetch<'w>(a: &'w Archetype, row: usize) -> Option<&'w T> {
        a.columns.get(&TypeId::of::<T>()).map(|c| c.column.get::<T>(row))
    }
}

impl WorldQuery for Entity {
    type Item<'w> = Entity;
    fn required_types() -> Vec<TypeId> { vec![] }
    fn matches(_: &Archetype) -> bool { true }
    unsafe fn fetch<'w>(a: &'w Archetype, row: usize) -> Entity { a.entities[row] }
}

macro_rules! impl_wq_tuple {
    ($($Q:ident),+) => {
        #[allow(non_snake_case)]
        impl<$($Q: WorldQuery),+> WorldQuery for ($($Q,)+) {
            type Item<'w> = ($($Q::Item<'w>,)+);
            fn required_types() -> Vec<TypeId> {
                let mut v = Vec::new(); $(v.extend($Q::required_types());)+ v.sort(); v.dedup(); v
            }
            fn matches(a: &Archetype) -> bool { $($Q::matches(a))&&+ }
            unsafe fn fetch<'w>(a: &'w Archetype, row: usize) -> ($($Q::Item<'w>,)+) {
                ($($Q::fetch(a, row),)+)
            }
        }
    };
}
impl_wq_tuple!(A);
impl_wq_tuple!(A, B);
impl_wq_tuple!(A, B, C);
impl_wq_tuple!(A, B, C, D);
impl_wq_tuple!(A, B, C, D, E);
impl_wq_tuple!(A, B, C, D, E, F);
impl_wq_tuple!(A, B, C, D, E, F, G);
impl_wq_tuple!(A, B, C, D, E, F, G, H);

// ---------------------------------------------------------------------------
// QueryIter
// ---------------------------------------------------------------------------

/// Iterator over archetypes matching query `Q` and filter `F`.
pub struct QueryIter<'w, Q: WorldQuery, F: QueryFilter> {
    archetypes: &'w [Archetype],
    arch_index: usize,
    row: usize,
    _q: std::marker::PhantomData<Q>,
    _f: std::marker::PhantomData<F>,
}
impl<'w, Q: WorldQuery, F: QueryFilter> QueryIter<'w, Q, F> {
    fn new(archetypes: &'w [Archetype]) -> Self {
        Self { archetypes, arch_index: 0, row: 0, _q: std::marker::PhantomData, _f: std::marker::PhantomData }
    }
}
impl<'w, Q: WorldQuery, F: QueryFilter> Iterator for QueryIter<'w, Q, F> {
    type Item = Q::Item<'w>;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            let arch = self.archetypes.get(self.arch_index)?;
            if !Q::matches(arch) || !F::matches_archetype(arch) {
                self.arch_index += 1; self.row = 0; continue;
            }
            if self.row >= arch.len() {
                self.arch_index += 1; self.row = 0; continue;
            }
            let row = self.row; self.row += 1;
            return Some(unsafe { Q::fetch(arch, row) });
        }
    }
}

// ---------------------------------------------------------------------------
// EntityRef / EntityMut
// ---------------------------------------------------------------------------

/// Read-only view into a single entity's components.
pub struct EntityRef<'w> { arch: &'w Archetype, row: usize }
impl<'w> EntityRef<'w> {
    fn new(arch: &'w Archetype, row: usize) -> Self { Self { arch, row } }
    /// The entity's handle.
    pub fn entity(&self) -> Entity { self.arch.entities[self.row] }
    /// Returns `&T` if the entity has component `T`.
    pub fn get<T: Component>(&self) -> Option<&T> {
        self.arch.columns.get(&TypeId::of::<T>()).map(|c| c.column.get::<T>(self.row))
    }
    /// `true` if the entity has component `T`.
    pub fn has<T: Component>(&self) -> bool { self.arch.contains(TypeId::of::<T>()) }
    /// All component types on this entity.
    pub fn component_types(&self) -> &[TypeId] { &self.arch.component_types }
}

/// Read-write view into a single entity's components.
pub struct EntityMut<'w> { arch: &'w mut Archetype, row: usize }
impl<'w> EntityMut<'w> {
    fn new(arch: &'w mut Archetype, row: usize) -> Self { Self { arch, row } }
    /// The entity's handle.
    pub fn entity(&self) -> Entity { self.arch.entities[self.row] }
    /// Returns `&T` if present.
    pub fn get<T: Component>(&self) -> Option<&T> {
        self.arch.columns.get(&TypeId::of::<T>()).map(|c| c.column.get::<T>(self.row))
    }
    /// Returns `&mut T` if present.
    pub fn get_mut<T: Component>(&mut self) -> Option<&mut T> {
        self.arch.columns.get_mut(&TypeId::of::<T>()).map(|c| c.column.get_mut::<T>(self.row))
    }
    /// `true` if the entity has component `T`.
    pub fn has<T: Component>(&self) -> bool { self.arch.contains(TypeId::of::<T>()) }
}

// ---------------------------------------------------------------------------
// World
// ---------------------------------------------------------------------------

/// The central ECS container: archetypes, entity allocator, resources, events.
pub struct World {
    archetypes: Vec<Archetype>,
    archetype_index: HashMap<Vec<TypeId>, usize>,
    entities: EntityAllocator,
    /// Global singleton resources.
    pub resources: Resources,
    events: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
    tick: u32,
}

impl World {
    /// Creates an empty world.
    pub fn new() -> Self {
        Self {
            archetypes: Vec::new(),
            archetype_index: HashMap::new(),
            entities: EntityAllocator::default(),
            resources: Resources::new(),
            events: HashMap::new(),
            tick: 0,
        }
    }

    /// Returns the current change-detection tick.
    pub fn tick(&self) -> u32 { self.tick }
    /// Advances the tick counter by 1.
    pub fn increment_tick(&mut self) { self.tick = self.tick.wrapping_add(1); }

    // -- Archetype helpers --------------------------------------------------

    fn get_or_create_archetype(&mut self, mut types: Vec<TypeId>) -> usize {
        types.sort(); types.dedup();
        if let Some(&i) = self.archetype_index.get(&types) { return i; }
        let id = ArchetypeId(self.archetypes.len() as u32);
        let arch = Archetype::new(id, types.clone());
        let i = self.archetypes.len();
        self.archetypes.push(arch);
        self.archetype_index.insert(types, i);
        i
    }

    // -- Spawn / despawn ----------------------------------------------------

    /// Spawns an entity with the given bundle and returns its handle.
    pub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity {
        let types = B::type_ids();
        let ai = self.get_or_create_archetype(types);
        let entity = self.entities.alloc();
        let tick = self.tick;
        let arch = &mut self.archetypes[ai];
        B::register_columns(arch);
        let row = arch.entities.len();
        arch.entities.push(entity);
        bundle.insert_into(arch, tick);
        self.entities.set_location(entity, EntityLocation { archetype_id: ArchetypeId(ai as u32), row });
        entity
    }

    /// Despawns an entity, returning `true` if it was alive.
    pub fn despawn(&mut self, entity: Entity) -> bool {
        let loc = match self.entities.location(entity) { Some(l) => l, None => return false };
        let ai = loc.archetype_id.0 as usize;
        let swapped = self.archetypes[ai].swap_remove(loc.row);
        self.entities.free(entity);
        if let Some(se) = swapped {
            self.entities.set_location(se, EntityLocation { archetype_id: loc.archetype_id, row: loc.row });
        }
        true
    }

    /// `true` if entity is currently alive.
    pub fn is_alive(&self, entity: Entity) -> bool { self.entities.is_alive(entity) }

    // -- Component insert / remove -----------------------------------------

    /// Inserts component `C` onto an entity, migrating its archetype if needed.
    pub fn insert<C: Component>(&mut self, entity: Entity, component: C) {
        let loc = match self.entities.location(entity) { Some(l) => l, None => return };
        let ai = loc.archetype_id.0 as usize;
        // Fast path: replace in-place.
        if self.archetypes[ai].contains(TypeId::of::<C>()) {
            let tick = self.tick;
            let col = self.archetypes[ai].columns.get_mut(&TypeId::of::<C>()).unwrap();
            *col.column.get_mut::<C>(loc.row) = component;
            col.changed_ticks[loc.row] = tick;
            return;
        }
        // Slow path: migrate to larger archetype.
        let mut new_types = self.archetypes[ai].component_types.clone();
        new_types.push(TypeId::of::<C>());
        let new_ai = self.get_or_create_archetype(new_types);
        let tick = self.tick;
        self.migrate_add::<C>(entity, loc, new_ai, component, tick);
    }

    fn migrate_add<C: Component>(
        &mut self, entity: Entity, loc: EntityLocation, new_ai: usize, extra: C, tick: u32,
    ) {
        let old_ai = loc.archetype_id.0 as usize;
        let row = loc.row;
        let old_types: Vec<TypeId> = self.archetypes[old_ai].component_types.clone();
        // Ensure destination columns exist.
        self.ensure_cols(old_ai, new_ai, &old_types);
        if !self.archetypes[new_ai].columns.contains_key(&TypeId::of::<C>()) {
            self.archetypes[new_ai].register_column::<C>();
        }
        let new_row = self.archetypes[new_ai].entities.len();
        for &tid in &old_types {
            Self::copy_row(&mut self.archetypes, old_ai, new_ai, tid, row, tick);
        }
        self.archetypes[new_ai].columns.get_mut(&TypeId::of::<C>()).unwrap().push(extra, tick);
        self.archetypes[new_ai].entities.push(entity);
        let swapped = self.archetypes[old_ai].swap_remove(row);
        self.entities.set_location(entity, EntityLocation { archetype_id: ArchetypeId(new_ai as u32), row: new_row });
        if let Some(se) = swapped {
            self.entities.set_location(se, EntityLocation { archetype_id: loc.archetype_id, row });
        }
    }

    fn ensure_cols(&mut self, src: usize, dst: usize, types: &[TypeId]) {
        for &tid in types {
            if self.archetypes[dst].columns.contains_key(&tid) { continue; }
            let s = &self.archetypes[src].columns[&tid];
            let nc = ComponentStorage {
                column: AnyVec {
                    type_id: s.column.type_id, len: 0, data: Vec::new(),
                    element_size: s.column.element_size,
                    element_align: s.column.element_align,
                    drop_fn: s.column.drop_fn, clone_fn: s.column.clone_fn,
                },
                added_ticks: Vec::new(), changed_ticks: Vec::new(),
            };
            self.archetypes[dst].columns.insert(tid, nc);
        }
    }

    fn copy_row(archetypes: &mut Vec<Archetype>, src: usize, dst: usize, tid: TypeId, row: usize, tick: u32) {
        let (sa, da) = if src < dst {
            let (l, r) = archetypes.split_at_mut(dst); (&l[src], &mut r[0])
        } else {
            let (l, r) = archetypes.split_at_mut(src); (&r[0], &mut l[dst])
        };
        if let (Some(sc), Some(dc)) = (sa.columns.get(&tid), da.columns.get_mut(&tid)) {
            sc.clone_row_into(row, dc, tick);
        }
    }

    /// Removes component `C` from an entity.
    pub fn remove<C: Component>(&mut self, entity: Entity) {
        self.remove_by_type_id(entity, TypeId::of::<C>());
    }

    /// Removes component by raw `TypeId`.
    pub(crate) fn remove_by_type_id(&mut self, entity: Entity, tid: TypeId) {
        let loc = match self.entities.location(entity) { Some(l) => l, None => return };
        let old_ai = loc.archetype_id.0 as usize;
        if !self.archetypes[old_ai].contains(tid) { return; }
        let row = loc.row;
        let new_types: Vec<TypeId> = self.archetypes[old_ai].component_types.iter()
            .copied().filter(|&t| t != tid).collect();
        let new_ai = self.get_or_create_archetype(new_types.clone());
        let tick = self.tick;
        let old_types: Vec<TypeId> = self.archetypes[old_ai].component_types.clone();
        self.ensure_cols(old_ai, new_ai, &new_types);
        let new_row = self.archetypes[new_ai].entities.len();
        for &t in &old_types {
            if t == tid { continue; }
            Self::copy_row(&mut self.archetypes, old_ai, new_ai, t, row, tick);
        }
        self.archetypes[new_ai].entities.push(entity);
        let swapped = self.archetypes[old_ai].swap_remove(row);
        self.entities.set_location(entity, EntityLocation { archetype_id: ArchetypeId(new_ai as u32), row: new_row });
        if let Some(se) = swapped {
            self.entities.set_location(se, EntityLocation { archetype_id: loc.archetype_id, row });
        }
    }

    // -- Component access --------------------------------------------------

    /// Returns `&C` for `entity`, or `None`.
    pub fn get<C: Component>(&self, entity: Entity) -> Option<&C> {
        let loc = self.entities.location(entity)?;
        self.archetypes[loc.archetype_id.0 as usize]
            .columns.get(&TypeId::of::<C>()).map(|c| c.column.get::<C>(loc.row))
    }

    /// Returns `&mut C` for `entity`, updating changed tick.
    pub fn get_mut<C: Component>(&mut self, entity: Entity) -> Option<&mut C> {
        let loc = self.entities.location(entity)?;
        let tick = self.tick;
        let arch = &mut self.archetypes[loc.archetype_id.0 as usize];
        arch.columns.get_mut(&TypeId::of::<C>()).map(|c| {
            c.changed_ticks[loc.row] = tick;
            c.column.get_mut::<C>(loc.row)
        })
    }

    /// Read-only view of an entity's components.
    pub fn entity_ref(&self, entity: Entity) -> Option<EntityRef<'_>> {
        let loc = self.entities.location(entity)?;
        Some(EntityRef::new(&self.archetypes[loc.archetype_id.0 as usize], loc.row))
    }

    /// Read-write view of an entity's components.
    pub fn entity_mut(&mut self, entity: Entity) -> Option<EntityMut<'_>> {
        let loc = self.entities.location(entity)?;
        let ai = loc.archetype_id.0 as usize;
        Some(EntityMut::new(&mut self.archetypes[ai], loc.row))
    }

    // -- Queries -----------------------------------------------------------

    /// Returns an iterator over entities matching `Q` and filter `F`.
    pub fn query<Q: WorldQuery, F: QueryFilter>(&self) -> QueryIter<'_, Q, F> {
        QueryIter::new(&self.archetypes)
    }

    /// Query with no filter.
    pub fn query_all<Q: WorldQuery>(&self) -> QueryIter<'_, Q, ()> {
        QueryIter::new(&self.archetypes)
    }

    /// Returns the single matching entity, or `None` if zero or multiple.
    pub fn query_single<Q: WorldQuery>(&self) -> Option<Q::Item<'_>> {
        let mut it = self.query::<Q, ()>();
        let first = it.next()?;
        if it.next().is_some() { return None; }
        Some(first)
    }

    // -- Resources ---------------------------------------------------------

    /// Inserts a resource.
    pub fn insert_resource<T: 'static + Send + Sync>(&mut self, v: T) { self.resources.insert(v); }
    /// Returns `Res<T>`.
    pub fn resource<T: 'static + Send + Sync>(&self) -> Option<Res<'_, T>> {
        self.resources.get::<T>().map(Res::new)
    }
    /// Returns `ResMut<T>`.
    pub fn resource_mut<T: 'static + Send + Sync>(&mut self) -> Option<ResMut<'_, T>> {
        self.resources.get_mut::<T>().map(ResMut::new)
    }
    /// Removes and returns `T`.
    pub fn remove_resource<T: 'static + Send + Sync>(&mut self) -> Option<T> { self.resources.remove::<T>() }

    // -- Events ------------------------------------------------------------

    /// Registers event type `E`.
    pub fn add_event<E: 'static + Send + Sync>(&mut self) {
        self.events.entry(TypeId::of::<Events<E>>())
            .or_insert_with(|| Box::new(Events::<E>::new()));
    }
    /// Returns `&Events<E>`.
    pub fn events<E: 'static + Send + Sync>(&self) -> Option<&Events<E>> {
        self.events.get(&TypeId::of::<Events<E>>())?.downcast_ref()
    }
    /// Returns `&mut Events<E>`.
    pub fn events_mut<E: 'static + Send + Sync>(&mut self) -> Option<&mut Events<E>> {
        self.events.get_mut(&TypeId::of::<Events<E>>())?.downcast_mut()
    }
    /// Sends event `E` (auto-creates queue).
    pub fn send_event<E: 'static + Send + Sync>(&mut self, event: E) {
        self.events.entry(TypeId::of::<Events<E>>())
            .or_insert_with(|| Box::new(Events::<E>::new()))
            .downcast_mut::<Events<E>>().unwrap().send(event);
    }

    // -- Entity iteration --------------------------------------------------

    /// Iterator over all live entities.
    pub fn entities(&self) -> impl Iterator<Item = Entity> + '_ {
        self.archetypes.iter().flat_map(|a| a.entities.iter().copied())
    }
    /// Total number of live entities.
    pub fn entity_count(&self) -> usize { self.archetypes.iter().map(|a| a.len()).sum() }
    /// Number of archetypes.
    pub fn archetype_count(&self) -> usize { self.archetypes.len() }
}

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

// ---------------------------------------------------------------------------
// SystemParam trait
// ---------------------------------------------------------------------------

/// Types extractable from a [`World`] as system parameters.
pub trait SystemParam: Sized {
    /// Per-system persistent state.
    type State: Default + Send + Sync + 'static;
    /// Initialises state from the world.
    fn init_state(world: &mut World) -> Self::State;
}

// ---------------------------------------------------------------------------
// System trait
// ---------------------------------------------------------------------------

/// A unit of logic operating on the [`World`].
pub trait System: Send + Sync + 'static {
    /// Executes the system.
    fn run(&mut self, world: &mut World);
    /// Human-readable name.
    fn name(&self) -> &str;
}

/// A system wrapping a plain closure.
pub struct FunctionSystem<F: FnMut(&mut World) + Send + Sync + 'static> { f: F, name: String }
impl<F: FnMut(&mut World) + Send + Sync + 'static> FunctionSystem<F> {
    /// Creates a named function system.
    pub fn new(name: impl Into<String>, f: F) -> Self { Self { f, name: name.into() } }
}
impl<F: FnMut(&mut World) + Send + Sync + 'static> System for FunctionSystem<F> {
    fn run(&mut self, w: &mut World) { (self.f)(w); }
    fn name(&self) -> &str { &self.name }
}

/// Wraps a closure as a boxed `System`.
pub fn into_system(name: impl Into<String>, f: impl FnMut(&mut World) + Send + Sync + 'static) -> Box<dyn System> {
    Box::new(FunctionSystem::new(name, f))
}

// ---------------------------------------------------------------------------
// Schedule
// ---------------------------------------------------------------------------

/// A human-readable system identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SystemLabel(pub String);
impl SystemLabel {
    /// Creates a new label.
    pub fn new(s: impl Into<String>) -> Self { Self(s.into()) }
}
impl<S: Into<String>> From<S> for SystemLabel { fn from(s: S) -> Self { Self(s.into()) } }

/// Boxed run-condition closure.
pub type RunCondition = Box<dyn Fn(&World) -> bool + Send + Sync>;

struct SystemEntry { system: Box<dyn System>, label: Option<SystemLabel>, run_if: Option<RunCondition> }

/// Ordered list of systems with optional labels and run conditions.
pub struct Schedule { systems: Vec<SystemEntry> }
impl Schedule {
    /// Creates an empty schedule.
    pub fn new() -> Self { Self { systems: Vec::new() } }
    /// Adds a system.
    pub fn add_system(&mut self, s: Box<dyn System>) -> &mut Self {
        self.systems.push(SystemEntry { system: s, label: None, run_if: None }); self
    }
    /// Adds a labelled system.
    pub fn add_system_with_label(&mut self, s: Box<dyn System>, label: impl Into<SystemLabel>) -> &mut Self {
        self.systems.push(SystemEntry { system: s, label: Some(label.into()), run_if: None }); self
    }
    /// Adds a system with a run condition.
    pub fn add_system_with_condition(
        &mut self, s: Box<dyn System>,
        cond: impl Fn(&World) -> bool + Send + Sync + 'static,
    ) -> &mut Self {
        self.systems.push(SystemEntry { system: s, label: None, run_if: Some(Box::new(cond)) }); self
    }
    /// Adds a labelled system with a run condition.
    pub fn add_system_full(
        &mut self, s: Box<dyn System>, label: impl Into<SystemLabel>,
        cond: impl Fn(&World) -> bool + Send + Sync + 'static,
    ) -> &mut Self {
        self.systems.push(SystemEntry { system: s, label: Some(label.into()), run_if: Some(Box::new(cond)) }); self
    }
    /// Removes all systems with `label`.
    pub fn remove_system(&mut self, label: &SystemLabel) {
        self.systems.retain(|e| e.label.as_ref() != Some(label));
    }
    /// Number of system slots.
    pub fn system_count(&self) -> usize { self.systems.len() }
    /// Runs all systems, incrementing the world tick first.
    pub fn run(&mut self, world: &mut World) {
        world.increment_tick();
        for e in &mut self.systems {
            if e.run_if.as_ref().map(|c| c(world)).unwrap_or(true) { e.system.run(world); }
        }
    }
    /// Labels of all systems in order.
    pub fn labels(&self) -> Vec<Option<&SystemLabel>> { self.systems.iter().map(|e| e.label.as_ref()).collect() }
}
impl Default for Schedule { fn default() -> Self { Self::new() } }

// ---------------------------------------------------------------------------
// Change-detection helpers
// ---------------------------------------------------------------------------

/// `true` if component `C` on `entity` was added after tick `since`.
pub fn was_added<C: Component>(w: &World, entity: Entity, since: u32) -> bool {
    let loc = match w.entities.location(entity) { Some(l) => l, None => return false };
    w.archetypes[loc.archetype_id.0 as usize].columns
        .get(&TypeId::of::<C>()).map(|c| c.added_ticks[loc.row] > since).unwrap_or(false)
}

/// `true` if component `C` on `entity` was changed after tick `since`.
pub fn was_changed<C: Component>(w: &World, entity: Entity, since: u32) -> bool {
    let loc = match w.entities.location(entity) { Some(l) => l, None => return false };
    w.archetypes[loc.archetype_id.0 as usize].columns
        .get(&TypeId::of::<C>()).map(|c| c.changed_ticks[loc.row] > since).unwrap_or(false)
}

/// Entities with `C` added after tick `since`.
pub fn query_added<C: Component>(w: &World, since: u32) -> impl Iterator<Item = Entity> + '_ {
    w.archetypes.iter().flat_map(move |arch| {
        if !arch.contains(TypeId::of::<C>()) { return vec![]; }
        let col = &arch.columns[&TypeId::of::<C>()];
        arch.entities.iter().enumerate()
            .filter(move |(r, _)| col.added_ticks[*r] > since)
            .map(|(_, &e)| e).collect::<Vec<_>>()
    })
}

/// Entities with `C` changed after tick `since`.
pub fn query_changed<C: Component>(w: &World, since: u32) -> impl Iterator<Item = Entity> + '_ {
    w.archetypes.iter().flat_map(move |arch| {
        if !arch.contains(TypeId::of::<C>()) { return vec![]; }
        let col = &arch.columns[&TypeId::of::<C>()];
        arch.entities.iter().enumerate()
            .filter(move |(r, _)| col.changed_ticks[*r] > since)
            .map(|(_, &e)| e).collect::<Vec<_>>()
    })
}

// ---------------------------------------------------------------------------
// Prelude
// ---------------------------------------------------------------------------

/// Common ECS re-exports.
pub mod prelude {
    pub use super::{
        Component, Entity, World, Bundle,
        Archetype, ArchetypeId, EntityRef, EntityMut,
        Resources, Res, ResMut, Local,
        Events, EventCursor, EventWriter, EventReader,
        Commands, With, Without, Added, Changed,
        Read, Write, OptionRead,
        WorldQuery, QueryFilter, QueryIter,
        System, SystemParam, FunctionSystem, into_system,
        Schedule, SystemLabel,
        was_added, was_changed, query_added, query_changed,
    };
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[derive(Debug, Clone, PartialEq)] struct Position { x: f32, y: f32 }
    impl Component for Position {}

    #[derive(Debug, Clone, PartialEq)] struct Velocity { dx: f32, dy: f32 }
    impl Component for Velocity {}

    #[derive(Debug, Clone, PartialEq)] struct Health(f32);
    impl Component for Health {}

    #[derive(Debug, Clone)] struct Tag; impl Component for Tag {}
    #[derive(Debug, Clone)] struct Enemy; impl Component for Enemy {}
    #[derive(Debug, Clone)] struct Player; impl Component for Player {}

    // Entity lifecycle
    #[test] fn test_spawn_alive() {
        let mut w = World::new();
        let e = w.spawn(Position { x: 1.0, y: 2.0 });
        assert!(w.is_alive(e)); assert_eq!(w.entity_count(), 1);
    }
    #[test] fn test_despawn() {
        let mut w = World::new();
        let e = w.spawn(Position { x: 0.0, y: 0.0 });
        assert!(w.despawn(e)); assert!(!w.is_alive(e)); assert_eq!(w.entity_count(), 0);
    }
    #[test] fn test_despawn_nonexistent() {
        let mut w = World::new(); assert!(!w.despawn(Entity::from_raw(99, 99)));
    }
    #[test] fn test_null_entity() {
        assert!(Entity::null().is_null()); assert!(!Entity::from_raw(0,0).is_null());
    }
    #[test] fn test_generation_reuse() {
        let mut w = World::new();
        let e1 = w.spawn(Position { x: 0.0, y: 0.0 }); w.despawn(e1);
        let e2 = w.spawn(Position { x: 1.0, y: 0.0 });
        assert_eq!(e1.index, e2.index); assert_ne!(e1.generation, e2.generation);
        assert!(!w.is_alive(e1)); assert!(w.is_alive(e2));
    }
    #[test] fn test_entity_display() { assert_eq!(format!("{}", Entity::from_raw(5,2)), "Entity(5v2)"); }

    // Component access
    #[test] fn test_get_component() {
        let mut w = World::new(); let e = w.spawn(Position { x: 3.0, y: 4.0 });
        assert_eq!(w.get::<Position>(e).unwrap().x, 3.0);
    }
    #[test] fn test_get_mut_component() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        w.get_mut::<Position>(e).unwrap().x = 10.0;
        assert_eq!(w.get::<Position>(e).unwrap().x, 10.0);
    }
    #[test] fn test_missing_component_none() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        assert!(w.get::<Velocity>(e).is_none());
    }
    #[test] fn test_entity_ref() {
        let mut w = World::new(); let e = w.spawn((Position { x: 1.0, y: 2.0 }, Health(100.0)));
        let er = w.entity_ref(e).unwrap();
        assert_eq!(er.get::<Position>().unwrap(), &Position { x: 1.0, y: 2.0 });
        assert!(er.has::<Position>()); assert!(!er.has::<Velocity>());
    }
    #[test] fn test_entity_mut() {
        let mut w = World::new(); let e = w.spawn(Health(50.0));
        w.entity_mut(e).unwrap().get_mut::<Health>().unwrap().0 = 75.0;
        assert_eq!(w.get::<Health>(e).unwrap().0, 75.0);
    }

    // Bundle
    #[test] fn test_spawn_tuple_bundle() {
        let mut w = World::new();
        let e = w.spawn((Position { x: 1.0, y: 0.0 }, Velocity { dx: 0.5, dy: 0.0 }, Health(100.0)));
        assert!(w.get::<Position>(e).is_some()); assert!(w.get::<Velocity>(e).is_some()); assert!(w.get::<Health>(e).is_some());
    }
    #[test] fn test_same_archetype() {
        let mut w = World::new();
        let e1 = w.spawn((Position { x: 0.0, y: 0.0 }, Velocity { dx: 1.0, dy: 0.0 }));
        let e2 = w.spawn((Position { x: 5.0, y: 5.0 }, Velocity { dx: -1.0, dy: 0.0 }));
        assert_eq!(w.archetype_count(), 1);
        assert_eq!(w.get::<Position>(e1).unwrap().x, 0.0);
        assert_eq!(w.get::<Position>(e2).unwrap().x, 5.0);
    }

    // Insert / remove
    #[test] fn test_insert_new_component() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        w.insert(e, Velocity { dx: 1.0, dy: 0.0 });
        assert!(w.get::<Velocity>(e).is_some()); assert!(w.get::<Position>(e).is_some());
    }
    #[test] fn test_insert_replaces() {
        let mut w = World::new(); let e = w.spawn(Health(100.0));
        w.insert(e, Health(50.0)); assert_eq!(w.get::<Health>(e).unwrap().0, 50.0);
    }
    #[test] fn test_remove_component() {
        let mut w = World::new();
        let e = w.spawn((Position { x: 0.0, y: 0.0 }, Velocity { dx: 1.0, dy: 0.0 }));
        w.remove::<Velocity>(e);
        assert!(w.get::<Velocity>(e).is_none()); assert!(w.get::<Position>(e).is_some());
    }
    #[test] fn test_remove_missing_noop() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        w.remove::<Velocity>(e); assert!(w.is_alive(e));
    }
    #[test] fn test_insert_remove_roundtrip() {
        let mut w = World::new(); let e = w.spawn(Position { x: 1.0, y: 2.0 });
        w.insert(e, Health(99.0)); assert_eq!(w.get::<Health>(e).unwrap().0, 99.0);
        w.remove::<Health>(e); assert!(w.get::<Health>(e).is_none());
        assert_eq!(w.get::<Position>(e).unwrap().x, 1.0);
    }

    // Queries
    #[test] fn test_query_single_component() {
        let mut w = World::new();
        w.spawn(Position { x: 1.0, y: 0.0 }); w.spawn(Position { x: 2.0, y: 0.0 }); w.spawn(Position { x: 3.0, y: 0.0 });
        assert_eq!(w.query::<Read<Position>, ()>().count(), 3);
    }
    #[test] fn test_query_tuple() {
        let mut w = World::new();
        w.spawn((Position { x: 0.0, y: 0.0 }, Velocity { dx: 1.0, dy: 0.0 }));
        w.spawn(Position { x: 5.0, y: 0.0 });
        assert_eq!(w.query::<(Read<Position>, Read<Velocity>), ()>().count(), 1);
    }
    #[test] fn test_query_with_filter() {
        let mut w = World::new();
        w.spawn((Position { x: 0.0, y: 0.0 }, Tag)); w.spawn(Position { x: 1.0, y: 0.0 });
        assert_eq!(w.query::<Read<Position>, With<Tag>>().count(), 1);
    }
    #[test] fn test_query_without_filter() {
        let mut w = World::new();
        w.spawn((Position { x: 0.0, y: 0.0 }, Enemy));
        w.spawn((Position { x: 1.0, y: 0.0 }, Player));
        w.spawn(Position { x: 2.0, y: 0.0 });
        assert_eq!(w.query::<Read<Position>, Without<Enemy>>().count(), 2);
    }
    #[test] fn test_query_option_read() {
        let mut w = World::new();
        w.spawn((Position { x: 0.0, y: 0.0 }, Health(100.0))); w.spawn(Position { x: 1.0, y: 0.0 });
        let r: Vec<_> = w.query::<(Read<Position>, OptionRead<Health>), ()>().collect();
        assert_eq!(r.len(), 2); assert_eq!(r.iter().filter(|(_, h)| h.is_some()).count(), 1);
    }
    #[test] fn test_query_entity() {
        let mut w = World::new();
        let e1 = w.spawn(Position { x: 0.0, y: 0.0 }); let e2 = w.spawn(Position { x: 1.0, y: 0.0 });
        let es: Vec<Entity> = w.query::<Entity, ()>().collect();
        assert!(es.contains(&e1)); assert!(es.contains(&e2));
    }
    #[test] fn test_query_mutable() {
        let mut w = World::new();
        w.spawn(Position { x: 0.0, y: 0.0 }); w.spawn(Position { x: 1.0, y: 0.0 });
        for p in w.query::<Write<Position>, ()>() { p.x += 10.0; }
        assert!(w.query::<Read<Position>, ()>().all(|p| p.x >= 10.0));
    }
    #[test] fn test_query_single() {
        let mut w = World::new(); w.spawn(Player);
        assert!(w.query_single::<Read<Player>>().is_some());
    }
    #[test] fn test_query_single_none_multiple() {
        let mut w = World::new(); w.spawn(Player); w.spawn(Player);
        assert!(w.query_single::<Read<Player>>().is_none());
    }

    // Resources
    #[test] fn test_resource_insert_get() {
        let mut w = World::new(); w.insert_resource(42u32);
        assert_eq!(*w.resource::<u32>().unwrap(), 42);
    }
    #[test] fn test_resource_mut() {
        let mut w = World::new(); w.insert_resource(0u32);
        *w.resource_mut::<u32>().unwrap() = 99;
        assert_eq!(*w.resource::<u32>().unwrap(), 99);
    }
    #[test] fn test_resource_remove() {
        let mut w = World::new(); w.insert_resource(42u32);
        assert_eq!(w.remove_resource::<u32>(), Some(42));
        assert!(w.resource::<u32>().is_none());
    }
    #[test] fn test_resources_standalone() {
        let mut r = Resources::new(); r.insert(42u32);
        assert!(r.contains::<u32>()); assert!(!r.contains::<i32>());
        r.remove::<u32>(); assert!(!r.contains::<u32>());
    }

    // Commands
    #[test] fn test_commands_spawn() {
        let mut w = World::new(); let mut c = Commands::new();
        c.spawn(Position { x: 7.0, y: 8.0 }); c.apply(&mut w);
        assert_eq!(w.query_single::<Read<Position>>().unwrap().x, 7.0);
    }
    #[test] fn test_commands_despawn() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        let mut c = Commands::new(); c.despawn(e); c.apply(&mut w); assert!(!w.is_alive(e));
    }
    #[test] fn test_commands_insert() {
        let mut w = World::new(); let e = w.spawn(Position { x: 0.0, y: 0.0 });
        let mut c = Commands::new(); c.insert(e, Health(50.0)); c.apply(&mut w);
        assert_eq!(w.get::<Health>(e).unwrap().0, 50.0);
    }
    #[test] fn test_commands_remove() {
        let mut w = World::new(); let e = w.spawn((Position { x: 0.0, y: 0.0 }, Health(100.0)));
        let mut c = Commands::new(); c.remove::<Health>(e); c.apply(&mut w);
        assert!(w.get::<Health>(e).is_none());
    }
    #[test] fn test_commands_insert_resource() {
        let mut w = World::new(); let mut c = Commands::new();
        c.insert_resource(100i32); c.apply(&mut w);
        assert_eq!(*w.resource::<i32>().unwrap(), 100);
    }

    // Events
    #[derive(Debug, Clone, PartialEq)] struct Dmg { amount: f32 }
    #[test] fn test_events_send_read() {
        let mut ev: Events<Dmg> = Events::new(); let mut cur = ev.get_reader_current();
        ev.send(Dmg { amount: 10.0 }); ev.send(Dmg { amount: 20.0 });
        let r: Vec<_> = ev.read(&mut cur).collect();
        assert_eq!(r.len(), 2); assert_eq!(r[0].amount, 10.0);
    }
    #[test] fn test_events_update_clears() {
        let mut ev: Events<Dmg> = Events::new(); ev.send(Dmg { amount: 5.0 });
        ev.update(); ev.update(); assert!(ev.is_empty());
    }
    #[test] fn test_event_writer_reader() {
        let mut ev: Events<Dmg> = Events::new();
        EventWriter::new(&mut ev).send(Dmg { amount: 42.0 });
        let mut reader = EventReader::new_current(&ev);
        let r: Vec<_> = reader.read().collect();
        assert_eq!(r.len(), 1); assert_eq!(r[0].amount, 42.0);
    }
    #[test] fn test_world_events() {
        let mut w = World::new(); w.add_event::<Dmg>();
        w.send_event(Dmg { amount: 99.0 }); assert!(!w.events::<Dmg>().unwrap().is_empty());
    }

    // Schedule
    #[test] fn test_schedule_runs_systems() {
        let mut w = World::new(); w.insert_resource(0u32);
        let mut s = Schedule::new();
        s.add_system(into_system("inc", |w| { *w.resource_mut::<u32>().unwrap() += 1; }));
        s.run(&mut w); s.run(&mut w); assert_eq!(*w.resource::<u32>().unwrap(), 2);
    }
    #[test] fn test_schedule_run_condition() {
        let mut w = World::new(); w.insert_resource(0u32); w.insert_resource(false);
        let mut s = Schedule::new();
        s.add_system_with_condition(
            into_system("g", |w| { *w.resource_mut::<u32>().unwrap() += 1; }),
            |w| *w.resource::<bool>().unwrap(),
        );
        s.run(&mut w); assert_eq!(*w.resource::<u32>().unwrap(), 0);
        *w.resource_mut::<bool>().unwrap() = true;
        s.run(&mut w); assert_eq!(*w.resource::<u32>().unwrap(), 1);
    }
    #[test] fn test_schedule_remove_label() {
        let mut s = Schedule::new();
        s.add_system_with_label(into_system("n", |_|{}), "lbl");
        assert_eq!(s.system_count(), 1);
        s.remove_system(&SystemLabel::new("lbl"));
        assert_eq!(s.system_count(), 0);
    }
    #[test] fn test_schedule_tick_increment() {
        let mut w = World::new(); let mut s = Schedule::new();
        s.run(&mut w); assert_eq!(w.tick(), 1); s.run(&mut w); assert_eq!(w.tick(), 2);
    }

    // Change detection
    #[test] fn test_was_added() {
        let mut w = World::new(); w.increment_tick();
        let e = w.spawn(Health(100.0));
        assert!(was_added::<Health>(&w, e, 0)); assert!(!was_added::<Health>(&w, e, 1));
    }
    #[test] fn test_was_changed() {
        let mut w = World::new(); w.increment_tick();
        let e = w.spawn(Health(100.0)); w.increment_tick();
        w.get_mut::<Health>(e).unwrap().0 = 50.0;
        assert!(was_changed::<Health>(&w, e, 1)); assert!(!was_changed::<Health>(&w, e, 2));
    }
    #[test] fn test_query_added() {
        let mut w = World::new(); w.increment_tick();
        let e1 = w.spawn(Health(100.0)); w.increment_tick(); let _e2 = w.spawn(Health(50.0));
        let added: Vec<_> = query_added::<Health>(&w, 1).collect();
        assert_eq!(added.len(), 1); assert!(!added.contains(&e1));
    }

    // Local
    #[test] fn test_local() {
        let mut l: Local<u32> = Local::default_value();
        assert_eq!(*l, 0); *l += 5; assert_eq!(*l, 5);
    }

    // Structural
    #[test] fn test_swap_remove_updates_location() {
        let mut w = World::new();
        let e1 = w.spawn(Position { x: 1.0, y: 0.0 });
        let _e2 = w.spawn(Position { x: 2.0, y: 0.0 });
        let e3 = w.spawn(Position { x: 3.0, y: 0.0 });
        w.despawn(e1);
        assert!(w.is_alive(e3)); assert_eq!(w.get::<Position>(e3).unwrap().x, 3.0);
    }
    #[test] fn test_spawn_many() {
        let mut w = World::new();
        for i in 0..1000u32 { w.spawn(Position { x: i as f32, y: 0.0 }); }
        assert_eq!(w.entity_count(), 1000);
        assert_eq!(w.query::<Read<Position>, ()>().count(), 1000);
    }
    #[test] fn test_world_default() { let w = World::default(); assert_eq!(w.entity_count(), 0); }
    #[test] fn test_multiple_archetypes() {
        let mut w = World::new();
        w.spawn(Position { x: 0.0, y: 0.0 }); w.spawn(Health(100.0));
        w.spawn((Position { x: 1.0, y: 0.0 }, Health(50.0)));
        assert_eq!(w.archetype_count(), 3);
        assert_eq!(w.query::<Read<Position>, ()>().count(), 2);
        assert_eq!(w.query::<Read<Health>, ()>().count(), 2);
        assert_eq!(w.query::<(Read<Position>, Read<Health>), ()>().count(), 1);
    }
    #[test] fn test_entity_count_after_despawn() {
        let mut w = World::new();
        let es: Vec<Entity> = (0..10).map(|i| w.spawn(Health(i as f32))).collect();
        for &e in &es[..5] { w.despawn(e); }
        assert_eq!(w.entity_count(), 5);
    }
}