gizmo-core 0.1.4

A custom ECS and physics engine aimed for realistic simulations.
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
use crate::archetype::index::ArchetypeIndex;
use crate::archetype::{Archetype, ComponentInfo, EntityLocation};
use crate::component::Component;
use crate::entity::Entity;

use std::any::TypeId;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::RwLock;

pub mod hooks;
pub mod resources;

pub use self::hooks::*;
pub use self::resources::*;
pub use crate::entity::allocator::Entities;

pub struct World {
    // Entity'den bağımsız global veriler (Time, WindowSize, Input vs.)
    resources: HashMap<TypeId, RwLock<Box<dyn std::any::Any + Send + Sync>>>,

    /// Entity ID → archetype konumu. Hızlı O(1) lookup sağlar.
    /// entity_id indeks olarak kullanılır.
    entity_locations: Vec<EntityLocation>,

    /// Archetype tabanlı depolama — tüm component verileri burada tutulur.
    pub(crate) archetype_index: ArchetypeIndex,

    /// Runtime component metadata cache'i. Archetype sütunları oluşturmak için gereklidir.
    component_infos: HashMap<TypeId, ComponentInfo>,

    pub(crate) component_hooks: HashMap<TypeId, ComponentHooks>,

    despawn_hooks: Vec<DespawnHook>,
    entities_to_despawn: Vec<Entity>,
    is_despawning: bool,
    pub tick: u32,
}

impl World {
    pub fn new() -> Self {
        let mut world = Self {
            resources: HashMap::new(),
            entity_locations: Vec::new(),
            archetype_index: ArchetypeIndex::new(),
            component_infos: HashMap::new(),
            component_hooks: HashMap::new(),
            despawn_hooks: Vec::new(),
            entities_to_despawn: Vec::new(),
            is_despawning: false,
            tick: 1,
        };
        world.insert_resource(crate::commands::CommandQueue::new());
        world.insert_resource(Entities::new());
        world
    }

    /// Increments the local tick counter, guaranteeing it skips 0 on wrap.
    pub fn increment_tick(&mut self) {
        self.tick = self.tick.wrapping_add(1);
        if self.tick == 0 {
            self.tick = 1;
        }

        // Apply topological memory alignment for caching locality
        self.sort_archetype_hierarchy();
    }

    /// Ertelenmiş komut kuyruğunu (CommandQueue) işler.
    /// Entity ekleme/çıkarma işlemleri bu sayede kilitlenme (deadlock) yaşamadan batch halinde uygulanır.
    pub fn apply_commands(&mut self) {
        let queue_opt = self
            .get_resource::<crate::commands::CommandQueue>()
            .map(|q| (*q).clone());
        if let Some(queue) = queue_opt {
            queue.apply(self);
        }
    }
}

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

impl World {
    /// Belirli bir component turunun runtime metadata'sini kaydeder.
    /// Archetype storage migration asamalarinda column olusturma icin kullanilir.
    #[inline]
    pub fn register_component_type<T: Component>(&mut self) {
        let type_id = TypeId::of::<T>();
        self.component_infos
            .entry(type_id)
            .or_insert_with(ComponentInfo::of::<T>);
    }

    /// Belirli bir component turu kayitli mi?
    #[inline]
    pub fn is_component_registered<T: Component>(&self) -> bool {
        self.component_infos.contains_key(&TypeId::of::<T>())
    }

    /// Kayitli component metadata sayisi.
    #[inline]
    pub fn registered_component_count(&self) -> usize {
        self.component_infos.len()
    }

    pub fn register_on_add<T: Component>(&mut self, hook: AddHook) {
        self.component_hooks
            .entry(TypeId::of::<T>())
            .or_default()
            .on_add
            .push(hook);
    }

    pub fn register_on_remove<T: Component>(&mut self, hook: RemoveHook) {
        self.component_hooks
            .entry(TypeId::of::<T>())
            .or_default()
            .on_remove
            .push(hook);
    }

    pub fn register_on_set<T: Component>(&mut self, hook: SetHook) {
        self.component_hooks
            .entry(TypeId::of::<T>())
            .or_default()
            .on_set
            .push(hook);
    }

    pub fn spawn(&mut self) -> Entity {
        let entity = {
            let entities = self
                .get_resource::<Entities>()
                .expect("Entities resource not initialized");
            entities.reserve_entity()
        };

        self.flush_spawn(entity);
        entity
    }

    /// Bir `Bundle`'ı tek seferde spawn eder — entity oluşturur ve tüm
    /// bileşenleri ekler.
    ///
    /// ```ignore
    /// let player = world.spawn_bundle(MeshBundle {
    ///     mesh: renderer.create_cube(),
    ///     material: Material::pbr(Color::BLUE, 0.5, 0.0),
    ///     name: "Oyuncu",
    ///     ..default()
    /// });
    /// ```
    pub fn spawn_bundle<B: crate::component::Bundle>(&mut self, bundle: B) -> Entity {
        let entity = self.spawn();
        bundle.apply(self, entity);
        entity
    }

    pub fn flush_spawn(&mut self, entity: Entity) {
        // Yeni entity'yi boş archetype'a kaydet
        self.archetype_index.on_spawn(entity.id());

        // Entity location tracking — boş archetype (id=0), row = entity'nin sırası
        let eid = entity.id();
        let loc_idx = eid as usize;
        let row = self.archetype_index.archetypes[0].len() as u32 - 1;

        if loc_idx >= self.entity_locations.len() {
            self.entity_locations
                .resize(loc_idx + 1, EntityLocation::INVALID);
        }
        self.entity_locations[loc_idx] = EntityLocation {
            archetype_id: 0,
            row,
        };
    }

    // Eski A3 bridge ve rebuild metodları silindi (Archetype artık authoritative).

    pub fn get_entity(&self, id: u32) -> Option<Entity> {
        let entities = self
            .get_resource::<Entities>()
            .expect("Entities resource not initialized");
        let state = entities.state.lock().expect("Entities mutex poisoned");
        if (id as usize) < state.generations.len() && !state.free_set.contains(&id) {
            return Some(Entity::new(id, state.generations[id as usize]));
        }
        None
    }

    /// Derin kopyalama (O(1) Prefab Splicing) işlemi.
    /// Var olan bir Entity'nin bulunduğu archetype tablosunda tamamen bitişik olarak N adet yeni kopyasını çıkarır.
    pub fn clone_entity(&mut self, source_id: u32, count: usize) -> Option<Vec<Entity>> {
        if count == 0 {
            return Some(Vec::new());
        }

        let loc = self.entity_locations.get(source_id as usize).copied()?;
        if !loc.is_valid() {
            return None;
        }

        let arch_id = loc.archetype_id as usize;
        let row = loc.row as usize;

        // Kilitlenmeleri engellemek için önce ID'leri üretelim
        let mut new_entities = Vec::with_capacity(count);
        let mut new_eids = Vec::with_capacity(count);

        {
            let entities_res = self
                .get_resource::<Entities>()
                .expect("Entities resource not initialized");
            for _ in 0..count {
                let e = entities_res.reserve_entity();
                new_eids.push(e.id());
                new_entities.push(e);
            }
        }

        // Seçilen Archetype içinde kopyalamayı batch halinde yapıyoruz
        let arch = &mut self.archetype_index.archetypes[arch_id];
        let tick = self.tick;
        let new_rows = unsafe { arch.batch_clone_row(row, count, &new_eids, tick) };

        // Location güncellemeleri
        for (i, &id) in new_eids.iter().enumerate() {
            let row = new_rows[i];
            let idx = id as usize;
            if idx >= self.entity_locations.len() {
                self.entity_locations
                    .resize(idx + 1, EntityLocation::INVALID);
            }
            self.entity_locations[idx] = EntityLocation {
                archetype_id: arch_id as u32,
                row,
            };
            self.archetype_index.entity_archetype.insert(id, arch_id);
            // NOT: on_spawn çağırmıyoruz çünkü batch_clone_row zaten entity'yi
            // doğru archetype'a ekledi. on_spawn boş archetype'a (0) tekrar eklerdi.
        }

        Some(new_entities)
    }

    pub fn register_despawn_hook(&mut self, hook: DespawnHook) {
        self.despawn_hooks.push(hook);
    }

    pub fn despawn(&mut self, entity: Entity) {
        self.entities_to_despawn.push(entity);
        if self.is_despawning {
            return;
        }
        self.is_despawning = true;

        while let Some(e) = self.entities_to_despawn.pop() {
            if !self.is_alive(e) {
                continue;
            }

            let hooks = self.despawn_hooks.clone();
            for hook in hooks {
                hook(self, e);
            }

            let id = e.id();
            let loc = self.entity_locations[id as usize];

            if loc.is_valid() {
                // Call OnRemove hooks for all currently held components
                let comp_types = {
                    let arch = &self.archetype_index.archetypes[loc.archetype_id as usize];
                    arch.component_types()
                };
                for t in comp_types {
                    let c_hooks = self.component_hooks.get(&t).cloned();
                    if let Some(c_hooks) = c_hooks {
                        for hook in c_hooks.on_remove {
                            hook(self, e);
                        }
                    }
                }

                // Re-fetch location safely after hooks might have mutated state
                let loc = self.entity_locations[id as usize];
                if loc.is_valid() {
                    // Archetype'tan verileri temizle
                    if let Some(moved_eid) = self.archetype_index.archetypes
                        [loc.archetype_id as usize]
                        .swap_remove_entity(loc.row as usize)
                    {
                        // Kayan entity'nin location bilgisini güncelle
                        self.entity_locations[moved_eid as usize].row = loc.row;
                    }
                }
            }

            {
                let entities = self
                    .get_resource::<Entities>()
                    .expect("Entities resource not initialized");
                entities.free(e);
            }

            self.archetype_index.entity_archetype.remove(&id);
            self.entity_locations[id as usize] = EntityLocation::INVALID;
        }
        self.is_despawning = false;
    }

    /// Hafızadaki boşlukları sıkıştırır ve kullanılmayan (boş) Archetype tablolarını silerek
    /// RAM'i ve sistem performansını ilk baştaki defregmante (temiz) haline getirir.
    /// Yükleme (Loading) ekranlarında veya düşük yoğunluklu anlarda çağrılması önerilir.
    pub fn compact(&mut self) {
        // 1. Önce eski, kullanılmayan boş archetype'ları silelim (GC)
        self.archetype_index
            .gc_empty_archetypes(&mut self.entity_locations);

        // 2. Kalan archetype'ların kapasitelerini minimuma indirelim (Shrink To Fit)
        for arch in &mut self.archetype_index.archetypes {
            arch.shrink_to_fit();
        }

        self.archetype_index.archetypes.shrink_to_fit();

        // 3. World seviyesindeki listeleri daraltalım.
        self.entities_to_despawn.shrink_to_fit();
        self.entity_locations.shrink_to_fit();

        let entities = self
            .get_resource::<Entities>()
            .expect("Entities resource not initialized");
        let mut state = entities.state.lock().expect("Entities mutex poisoned");
        state.generations.shrink_to_fit();
        state.free_ids.shrink_to_fit();
        state.free_set.shrink_to_fit();
    }

    pub fn despawn_by_id(&mut self, id: u32) {
        if let Some(entity) = self.get_entity(id) {
            self.despawn(entity);
        }
    }

    /// Yaşayan (despawn olmamış) tüm Entity'leri döndüren iterator.
    /// Uyarı: İterasyon boyunca Entities mutex kilidi tutulur!
    pub fn iter_alive_entities(&self) -> Vec<Entity> {
        let entities = self
            .get_resource::<Entities>()
            .expect("Entities resource not initialized");
        let state = entities.state.lock().expect("Entities mutex poisoned");
        let mut alive = Vec::new();
        for id in 0..state.next_entity_id {
            if !state.free_set.contains(&id) {
                alive.push(Entity::new(id, state.generations[id as usize]));
            }
        }
        alive
    }

    #[inline]
    pub fn is_alive(&self, entity: Entity) -> bool {
        self.get_resource::<Entities>()
            .expect("Entities resource not initialized")
            .is_alive(entity)
    }

    /// Sisteme component ekleme — Veriyi archetype sütununa taşır.
    pub fn add_component<T: Component>(&mut self, entity: Entity, component: T) {
        if !self.is_alive(entity) {
            return;
        }

        let eid = entity.id();
        self.register_component_type::<T>();
        let type_id = TypeId::of::<T>();

        // 1. Hedef archetype'ı belirle
        let target_arch_id =
            match self
                .archetype_index
                .get_add_component_target(eid, type_id, &self.component_infos)
            {
                Some(id) => id,
                None => return,
            };
        let old_loc = self.entity_locations[eid as usize];

        if old_loc.archetype_id == target_arch_id as u32 {
            // Zaten bu archetype'ta (aynı tip tekrar eklenmiş olabilir) — sadece üzerine yaz
            {
                let arch = &self.archetype_index.archetypes[target_arch_id];
                let col = arch
                    .get_column_mut(type_id)
                    .expect("component column missing in current archetype");
                unsafe {
                    let ptr = col.get_ptr(old_loc.row as usize) as *mut T;
                    *ptr = component;
                    col.ticks_ptr_mut()
                        .add(old_loc.row as usize)
                        .write(crate::archetype::ComponentTicks::new(self.tick));
                }
            }
            // Trigger OnSet hooks
            let hooks = self.component_hooks.get(&type_id).cloned();
            if let Some(hooks) = hooks {
                for hook in hooks.on_set {
                    hook(self, entity);
                }
            }
            return;
        }

        // 2. Migration: Verileri eski archetype'tan hedef archetype'a taşı
        let (eid, old_arch_id, old_row) = (
            entity.id(),
            old_loc.archetype_id as usize,
            old_loc.row as usize,
        );

        let (new_row, moved_eid) = unsafe {
            // Raw pointer ile iki archetype'ı ödünç alıyoruz (farklı indeksler olduğu garantidir)
            let old_arch_ptr = &mut self.archetype_index.archetypes[old_arch_id] as *mut Archetype;
            let target_arch_ptr =
                &mut self.archetype_index.archetypes[target_arch_id] as *mut Archetype;

            (&mut *old_arch_ptr).move_entity_to(old_row, &mut *target_arch_ptr)
        };

        if let Some(moved) = moved_eid {
            self.entity_locations[moved as usize].row = old_row as u32;
        }

        // 3. Yeni component'ı hedef archetype'a ekle
        {
            let arch = &self.archetype_index.archetypes[target_arch_id];
            let col = arch
                .get_column_mut(type_id)
                .expect("Mandatory component column missing");
            unsafe {
                let ptr = col.get_ptr(new_row as usize) as *mut T;
                std::ptr::write(ptr, component);
                col.ticks_ptr_mut()
                    .add(new_row as usize)
                    .write(crate::archetype::ComponentTicks::new(self.tick));
            }
        }

        // 4. Location güncellemeleri
        self.entity_locations[eid as usize] = EntityLocation {
            archetype_id: target_arch_id as u32,
            row: new_row,
        };
        self.archetype_index
            .entity_archetype
            .insert(eid, target_arch_id);

        let hooks = self.component_hooks.get(&type_id).cloned();
        if let Some(hooks) = hooks {
            for hook in hooks.on_add {
                hook(self, entity);
            }
            for hook in hooks.on_set {
                hook(self, entity);
            }
        }
    }

    /// Entity üzerindeki tüm bileşenlerin TypeId'lerini döndürür.
    pub fn get_entity_component_types(&self, entity: Entity) -> Vec<TypeId> {
        if !self.is_alive(entity) {
            return Vec::new();
        }
        if let Some(&loc) = self.entity_locations.get(entity.id() as usize) {
            if loc.is_valid() {
                let arch = &self.archetype_index.archetypes[loc.archetype_id as usize];
                return arch.component_types();
            }
        }
        Vec::new()
    }

    /// Raw Component Pointer alma (Reflection/Editor için)
    pub fn get_component_ptr(&self, entity: Entity, type_id: TypeId) -> Option<*const u8> {
        let loc = self.entity_locations.get(entity.id() as usize).copied()?;
        if !loc.is_valid() {
            return None;
        }
        let arch = &self.archetype_index.archetypes[loc.archetype_id as usize];
        let col = arch.get_column(type_id)?;
        Some(unsafe { col.get_ptr(loc.row as usize) })
    }

    /// Sistemden component silme
    pub fn remove_component<T: Component>(&mut self, entity: Entity) {
        if !self.is_alive(entity) {
            return;
        }

        let eid = entity.id();
        let type_id = TypeId::of::<T>();
        let old_loc = self.entity_locations[eid as usize];

        // 1. Hedef archetype'ı belirle
        let target_arch_id_opt =
            self.archetype_index
                .get_remove_component_target(eid, type_id, &self.component_infos);
        let target_arch_id = match target_arch_id_opt {
            Some(id) => id,
            None => return, // Zaten yok veya hata
        };

        if old_loc.archetype_id == target_arch_id as u32 {
            return; // Zaten yok
        }

        // 2. Migration
        let (new_row, moved_eid) = unsafe {
            let old_arch_ptr = &mut self.archetype_index.archetypes[old_loc.archetype_id as usize]
                as *mut Archetype;
            let target_arch_ptr =
                &mut self.archetype_index.archetypes[target_arch_id] as *mut Archetype;
            (&mut *old_arch_ptr).move_entity_to(old_loc.row as usize, &mut *target_arch_ptr)
        };

        if let Some(moved) = moved_eid {
            self.entity_locations[moved as usize].row = old_loc.row;
        }

        // 3. Location güncelle
        self.entity_locations[eid as usize] = EntityLocation {
            archetype_id: target_arch_id as u32,
            row: new_row,
        };
        self.archetype_index
            .entity_archetype
            .insert(eid, target_arch_id);

        let hooks = self.component_hooks.get(&type_id).cloned();
        if let Some(hooks) = hooks {
            for hook in hooks.on_remove {
                hook(self, entity);
            }
        }
    }



    // ==========================================================
    // ERGONOMİK SORGULAR (QUERY API)
    // ==========================================================

    pub fn query<'w, Q: crate::query::WorldQuery>(&'w self) -> Option<crate::query::Query<'w, Q>> {
        crate::query::Query::new(self)
    }

    /// Geriye uyumluluk için StorageView alternatifi
    #[inline]
    pub fn borrow<'w, T: Component>(&'w self) -> crate::query::Query<'w, &'w T> {
        self.query::<&T>().expect("Failed to create borrow Query")
    }

    /// Geriye uyumluluk için StorageViewMut alternatifi
    #[inline]
    pub fn borrow_mut<'w, T: Component>(&'w self) -> crate::query::Query<'w, crate::query::Mut<'w, T>> {
        self.query::<crate::query::Mut<T>>().expect("Failed to create borrow_mut Query")
    }

    /// Cache'li query — archetype indeks cache'ini kullanır.
    /// &mut self gerektirdiği için sadece World sahibiyken çağrılabilir.
    pub fn query_cached<'w, Q: crate::query::WorldQuery>(
        &'w mut self,
    ) -> Option<crate::query::Query<'w, Q>> {
        crate::query::Query::new_cached(self)
    }

    /// Tek bir entity üzerinde `Query` çalıştırıp anında sonuç almanızı sağlar.
    ///
    /// # Örnek
    /// ```ignore
    /// if let Some((mut t, mut v)) = world.query_entity_mut::<(Mut<Transform>, Mut<Velocity>)>(id) {
    ///     t.position += v.linear * dt;
    /// }
    /// ```
    pub fn query_entity_mut<'w, Q: crate::query::WorldQuery>(
        &'w mut self,
        entity_id: u32,
    ) -> Option<Q::Item<'w>> {
        let loc = self.entity_location(entity_id);
        if !loc.is_valid() {
            return None;
        }
        let arch = &self.archetype_index.archetypes[loc.archetype_id as usize];
        if !Q::matches_archetype(arch) {
            return None;
        }
        unsafe {
            let fetch = Q::fetch_raw(arch, self.tick)?;
            if !Q::filter_row(fetch, loc.row as usize, self.tick) {
                return None;
            }
            Some(Q::get_item(fetch, loc.row as usize))
        }
    }

    /// Tek bir entity üzerinde read-only `Query` çalıştırıp anında sonuç almanızı sağlar.
    pub fn query_entity<'w, Q: crate::query::WorldQuery>(
        &'w self,
        entity_id: u32,
    ) -> Option<Q::Item<'w>> {
        let loc = self.entity_location(entity_id);
        if !loc.is_valid() {
            return None;
        }
        let arch = &self.archetype_index.archetypes[loc.archetype_id as usize];
        if !Q::matches_archetype(arch) {
            return None;
        }
        unsafe {
            let fetch = Q::fetch_raw(arch, self.tick)?;
            if !Q::filter_row(fetch, loc.row as usize, self.tick) {
                return None;
            }
            Some(Q::get_item(fetch, loc.row as usize))
        }
    }

    /// Entity'nin archetype konumunu döndürür — O(1) lookup.
    #[inline]
    pub fn entity_location(&self, entity_id: u32) -> EntityLocation {
        let loc_idx = entity_id as usize;
        if loc_idx < self.entity_locations.len() {
            self.entity_locations[loc_idx]
        } else {
            EntityLocation::INVALID
        }
    }

    /// Toplam yaşayan entity sayısı
    #[inline]
    pub fn entity_count(&self) -> u32 {
        let entities = self
            .get_resource::<Entities>()
            .expect("Entities resource not initialized");
        let state = entities.state.lock().expect("Entities mutex poisoned");
        state
            .next_entity_id
            .saturating_sub(state.free_ids.len() as u32)
    }

    // ==========================================================
    // RESOURCE SİSTEMİ (GLOBAL VERİLER)
    // ==========================================================

    /// Sisteme global bir Resource ekler veya üzerine yazar.
    pub fn insert_resource<T: Send + Sync + 'static>(&mut self, resource: T) {
        let type_id = TypeId::of::<T>();
        self.resources
            .insert(type_id, RwLock::new(Box::new(resource)));
    }

    /// Global bir Resource'u okumak için çağrılır (Immutable Borrow)
    pub fn get_resource<T: 'static>(&self) -> Option<ResourceReadGuard<'_, T>> {
        self.try_get_resource::<T>().ok()
    }

    /// Global bir Resource'u değiştirmek için çağrılır (Mutable Borrow)
    pub fn get_resource_mut<T: 'static>(&self) -> Option<ResourceWriteGuard<'_, T>> {
        self.try_get_resource_mut::<T>().ok()
    }

    /// `get_resource` ile aynı işlev, ama hata sebebini `Result` ile taşır.
    pub fn try_get_resource<T: 'static>(
        &self,
    ) -> Result<ResourceReadGuard<'_, T>, ResourceFetchError> {
        let type_id = TypeId::of::<T>();
        let storage = self
            .resources
            .get(&type_id)
            .ok_or(ResourceFetchError::NotFound(type_id))?;
        let guard = storage
            .try_read()
            .map_err(|_| ResourceFetchError::BorrowConflict(type_id))?;
        Ok(ResourceReadGuard {
            guard,
            _marker: PhantomData,
        })
    }

    /// `get_resource_mut` ile aynı işlev, ama hata sebebini `Result` ile taşır.
    pub fn try_get_resource_mut<T: 'static>(
        &self,
    ) -> Result<ResourceWriteGuard<'_, T>, ResourceFetchError> {
        let type_id = TypeId::of::<T>();
        let storage = self
            .resources
            .get(&type_id)
            .ok_or(ResourceFetchError::NotFound(type_id))?;
        let guard = storage
            .try_write()
            .map_err(|_| ResourceFetchError::BorrowConflict(type_id))?;
        Ok(ResourceWriteGuard {
            guard,
            _marker: PhantomData,
        })
    }

    /// Global bir Resource yoksa Default olarak oluşturur, ardından Mutable Borrow döndürür.
    /// World mutable borrow gerektirir, böylece hashmap'e güvenle kayıt yapılabilir.
    pub fn get_resource_mut_or_default<T: Default + Send + Sync + 'static>(
        &mut self,
    ) -> ResourceWriteGuard<'_, T> {
        let type_id = TypeId::of::<T>();
        self.resources
            .entry(type_id)
            .or_insert_with(|| RwLock::new(Box::new(T::default())));

        let storage = self
            .resources
            .get(&type_id)
            .expect("resource just inserted");
        let guard = storage.write().expect("resource write lock poisoned");
        ResourceWriteGuard {
            guard,
            _marker: PhantomData,
        }
    }

    /// Global bir Resource'u ECS'ten tamamen çıkartır ve sahipliğini döndürür
    pub fn remove_resource<T: 'static>(&mut self) -> Option<T> {
        let type_id = TypeId::of::<T>();
        let cell = self.resources.remove(&type_id)?;
        let boxed_any = cell.into_inner().ok()?;
        match boxed_any.downcast::<T>() {
            Ok(boxed_t) => Some(*boxed_t),
            Err(_) => None,
        }
    }

    /// Bir resource'u geçici olarak world'den çıkarıp closure'a geçirir ve sonra geri koyar.
    /// Bu, resource'un içindeyken `&mut World` kullanmanız gerektiğinde borrow checker'ı
    /// mutlu etmenin en temiz yoludur (Bevy'deki `resource_scope` benzeri).
    ///
    /// # Örnek
    /// ```ignore
    /// world.resource_scope::<PoolManager, ()>(|world, pool| {
    ///     pool.instantiate(world, "enemy");
    /// });
    /// ```
    pub fn resource_scope<T: Send + Sync + 'static, U, F>(&mut self, f: F) -> Option<U>
    where
        F: FnOnce(&mut World, &mut T) -> U,
    {
        let resource = self.remove_resource::<T>()?;

        // Panic güvenliği: Closure panic yaparsa bile resource geri yerleştirilir.
        // Drop guard, stack unwind sırasında resource'u tekrar world'e koyar.
        struct Guard<'a, T: Send + Sync + 'static> {
            world: *mut World,
            resource: Option<T>,
            _marker: std::marker::PhantomData<&'a mut World>,
        }
        impl<'a, T: Send + Sync + 'static> Drop for Guard<'a, T> {
            fn drop(&mut self) {
                if let Some(resource) = self.resource.take() {
                    // SAFETY: self.world is valid for the lifetime of the Guard.
                    unsafe { &mut *self.world }.insert_resource(resource);
                }
            }
        }

        let mut guard = Guard::<T> {
            world: self as *mut World,
            resource: Some(resource),
            _marker: std::marker::PhantomData,
        };

        let result = f(self, guard.resource.as_mut().unwrap());

        // Normal dönüş: guard.drop() resource'u geri koyacak.
        Some(result)
    }

    /// Belirli bir Archetype içindeki iki satırı güvenli bir şekilde takaslar ve entity lokasyonlarını günceller.
    pub fn swap_archetype_rows(&mut self, arch_id: u32, row_a: usize, row_b: usize) {
        if row_a == row_b {
            return;
        }

        let arch = &self.archetype_index.archetypes[arch_id as usize];
        if row_a >= arch.len() || row_b >= arch.len() {
            return;
        }

        let entity_a = arch.entities()[row_a];
        let entity_b = arch.entities()[row_b];

        unsafe {
            let mut_arch = &mut self.archetype_index.archetypes[arch_id as usize];
            mut_arch.swap_rows(row_a, row_b);
        }

        self.entity_locations[entity_a as usize].row = row_b as u32;
        self.entity_locations[entity_b as usize].row = row_a as u32;
    }

    /// Aynı archetype'da bulunan ebeveyn ve çocuk düğümleri bellekte sırt sırta verecek şekilde kümelendirir. O(N) cache swap.
    pub fn sort_archetype_hierarchy(&mut self) {
        let type_id = std::any::TypeId::of::<crate::component::Children>();
        let mut arches_to_sort: Vec<usize> = Vec::new();

        for (idx, arch) in self.archetype_index.archetypes.iter().enumerate() {
            if arch.has_component(type_id) {
                arches_to_sort.push(idx);
            }
        }

        for arch_idx in arches_to_sort {
            let arch_len = self.archetype_index.archetypes[arch_idx].len();
            if arch_len <= 1 {
                continue;
            }

            let mut visited = std::collections::HashSet::new();

            for row in 0..arch_len {
                let parent_entity_id = self.archetype_index.archetypes[arch_idx].entities()[row];

                if visited.contains(&parent_entity_id) {
                    continue;
                }
                visited.insert(parent_entity_id);

                let children_opt = {
                    let fetch = unsafe {
                        <&crate::component::Children as crate::query::FetchComponent>::fetch_raw(
                            &self.archetype_index.archetypes[arch_idx],
                            self.tick,
                        )
                    };
                    fetch.map(|f| unsafe {
                        <&crate::component::Children as crate::query::FetchComponent>::get_item(
                            f, row,
                        )
                    })
                };

                let children_list = match children_opt {
                    Some(c) => c.0.clone(),
                    None => continue,
                };

                let mut current_insert_row = row + 1;
                for child_id in children_list {
                    let loc = self.entity_location(child_id);
                    if loc.is_valid() && loc.archetype_id == arch_idx as u32 {
                        let child_row = loc.row as usize;
                        if child_row > current_insert_row {
                            self.swap_archetype_rows(
                                arch_idx as u32,
                                current_insert_row,
                                child_row,
                            );
                            visited.insert(child_id);
                            current_insert_row += 1;
                        } else if child_row == current_insert_row {
                            visited.insert(child_id);
                            current_insert_row += 1;
                        }
                    }
                }
            }
        }
    }
}

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

    #[derive(Clone, PartialEq, Debug)]
    struct Transform(f32);
    impl crate::component::Component for Transform {}

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

        // 5 entity oluşturalım: e0, e1, e2, e3, e4
        let e0 = world.spawn();
        let e1 = world.spawn();
        let e2 = world.spawn();
        let e3 = world.spawn();
        let e4 = world.spawn();

        // Hepsi aynı bileşenlere sahip olsun (aynı archetype'a girmeleri için)
        // Sırasıyla Transform ekliyoruz:
        world.add_component(e0, Transform(0.0));
        world.add_component(e1, Transform(1.0));
        world.add_component(e2, Transform(2.0));
        world.add_component(e3, Transform(3.0));
        world.add_component(e4, Transform(4.0));

        // Hiyerarşi kuralım: e0'ın çocukları e3 ve e4 olsun.
        // Başlangıçta e0(0), e1(1), e2(2), e3(3), e4(4) sırasıyla dizilidir.
        world.add_component(e0, Children(vec![e3.id(), e4.id()]));

        // Sadece e0'da Children olunca farklı archetype'a geçer (Archetype değişimi).
        // Bu yüzden hepsine Children eklemeliyiz ki AYNI archetype'da kalsınlar.
        world.add_component(e1, Children(vec![]));
        world.add_component(e2, Children(vec![]));
        world.add_component(e3, Children(vec![]));
        world.add_component(e4, Children(vec![]));

        // Şu an hepsi (Transform, Children) archetype'ında.
        // Beklenen indeksler: e0, e1, e2, e3, e4.

        // Hiyerarşi kaydırmasını çalıştır!
        world.sort_archetype_hierarchy();

        // Kontrol edelim. e0'dan hemen sonra e3 ve e4 gelmeli.
        let loc0 = world.entity_location(e0.id());
        let loc3 = world.entity_location(e3.id());
        let loc4 = world.entity_location(e4.id());

        assert_eq!(
            loc0.row + 1,
            loc3.row,
            "e3 (child), e0 (parent)'dan hemen sonra gelmeli"
        );
        assert_eq!(
            loc0.row + 2,
            loc4.row,
            "e4 (child), e3'ten hemen sonra gelmeli"
        );

        // Diğerleri (e1 ve e2) kaydırılmış olmalı.
        let loc1 = world.entity_location(e1.id());
        let loc2 = world.entity_location(e2.id());
        assert!(
            loc1.row > loc4.row || loc2.row > loc4.row,
            "Bağımsız entityler sona itilmeli"
        );
    }

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

        let e0 = world.spawn();
        let e1 = world.spawn();
        let e2 = world.spawn();
        let e3 = world.spawn();

        world.add_component(e0, Transform(0.0));
        world.add_component(e1, Transform(1.0));
        world.add_component(e2, Transform(2.0));
        world.add_component(e3, Transform(3.0));

        // e0 -> e1 -> e2 -> e3 zinciri
        world.add_component(e0, Children(vec![e1.id()]));
        world.add_component(e1, Children(vec![e2.id()]));
        world.add_component(e2, Children(vec![e3.id()]));
        world.add_component(e3, Children(vec![]));

        world.sort_archetype_hierarchy();

        let l0 = world.entity_location(e0.id());
        let l1 = world.entity_location(e1.id());
        let l2 = world.entity_location(e2.id());
        let l3 = world.entity_location(e3.id());

        assert_eq!(l0.row + 1, l1.row);
        // Not: Algoritma şu an sadece doğrudan çocukları hemen arkasına koyar.
        // e1 işlendiğinde e2 onun arkasına geçer, e2 işlendiğinde e3 onun arkasına geçer.
        // Sonuçta e0, e1, e2, e3 dizilimi kendiliğinden oluşur (visited mantığı).
        assert_eq!(l1.row + 1, l2.row);
        assert_eq!(l2.row + 1, l3.row);
    }


    #[test]
    fn spawn_despawn_generation() {
        let mut world = World::new();
        let e1 = world.spawn();
        world.despawn(e1);
        
        let e2 = world.spawn(); // aynı id, farklı generation
        assert_eq!(e1.id(), e2.id());
        assert_ne!(e1.generation(), e2.generation());
        
        // Eski handle artık geçersiz
        assert!(!world.is_alive(e1));
        assert!(world.is_alive(e2));
    }

    #[test]
    fn despawn_updates_swapped_entity_location() {
        #[derive(Clone)]
        struct TestComp(i32);
        impl crate::component::Component for TestComp {}

        let mut world = World::new();
        world.register_component_type::<TestComp>();
        
        let e1 = world.spawn(); world.add_component(e1, TestComp(1));
        let e2 = world.spawn(); world.add_component(e2, TestComp(2));
        let e3 = world.spawn(); world.add_component(e3, TestComp(3));
        
        // e2'yi despawn et — e3 onun yerine swap_remove ile gelir
        world.despawn(e2);
        
        // e3 hâlâ erişilebilir olmalı
        let comps = world.borrow::<TestComp>();
        let val = comps.get(e3.id()).unwrap();
        assert_eq!(val.0, 3);
    }

    #[test]
    fn add_component_migrates_archetype() {
        #[derive(Clone, Debug, PartialEq)]
        struct TestCompI32(i32);
        impl crate::component::Component for TestCompI32 {}

        #[derive(Clone, Debug, PartialEq)]
        struct TestCompF32(f32);
        impl crate::component::Component for TestCompF32 {}

        let mut world = World::new();
        world.register_component_type::<TestCompI32>();
        world.register_component_type::<TestCompF32>();
        
        let e = world.spawn();
        world.add_component(e, TestCompI32(10));
        
        let loc1 = world.entity_location(e.id());
        
        world.add_component(e, TestCompF32(3.14));
        
        let loc2 = world.entity_location(e.id());
        assert_ne!(loc1.archetype_id, loc2.archetype_id);
        
        assert_eq!(world.borrow::<TestCompI32>().get(e.id()).unwrap().0, 10);
        assert_eq!(world.borrow::<TestCompF32>().get(e.id()).unwrap().0, 3.14);
    }

    #[test]
    fn add_same_component_overwrites() {
        #[derive(Clone, Debug, PartialEq)]
        struct TestCompI32(i32);
        impl crate::component::Component for TestCompI32 {}

        let mut world = World::new();
        world.register_component_type::<TestCompI32>();
        
        let e = world.spawn();
        world.add_component(e, TestCompI32(1));
        world.add_component(e, TestCompI32(99)); // overwrite
        
        assert_eq!(world.borrow::<TestCompI32>().get(e.id()).unwrap().0, 99);
    }

    #[test]
    fn archetype_graph_reuses_archetypes() {
        #[derive(Clone, Debug, PartialEq)]
        struct TestCompI32(i32);
        impl crate::component::Component for TestCompI32 {}

        #[derive(Clone, Debug, PartialEq)]
        struct TestCompF32(f32);
        impl crate::component::Component for TestCompF32 {}

        let mut world = World::new();
        world.register_component_type::<TestCompI32>();
        world.register_component_type::<TestCompF32>();
        
        let e1 = world.spawn(); world.add_component(e1, TestCompI32(1)); world.add_component(e1, TestCompF32(1.0));
        let e2 = world.spawn(); world.add_component(e2, TestCompI32(2)); world.add_component(e2, TestCompF32(2.0));
        
        let loc1 = world.entity_location(e1.id());
        let loc2 = world.entity_location(e2.id());
        assert_eq!(loc1.archetype_id, loc2.archetype_id);
        
        assert!(world.archetype_index.archetypes.len() < 5);
    }

    #[test]
    fn query_finds_matching_archetypes() {
        #[derive(Clone)]
        struct TestCompI32(i32);
        impl crate::component::Component for TestCompI32 {}

        #[derive(Clone)]
        struct TestCompF32(f32);
        impl crate::component::Component for TestCompF32 {}

        #[derive(Clone)]
        struct TestCompBool(bool);
        impl crate::component::Component for TestCompBool {}

        let mut world = World::new();
        world.register_component_type::<TestCompI32>();
        world.register_component_type::<TestCompF32>();
        world.register_component_type::<TestCompBool>();
        
        let e1 = world.spawn(); world.add_component(e1, TestCompI32(1)); world.add_component(e1, TestCompF32(1.0));
        let e2 = world.spawn(); world.add_component(e2, TestCompI32(2)); world.add_component(e2, TestCompBool(true));
        let e3 = world.spawn(); world.add_component(e3, TestCompI32(3)); // sadece i32
        
        // i32 query'si 3 entity'yi de bulmalı
        let count = world.query::<&TestCompI32>().unwrap().iter().count();
        assert_eq!(count, 3);
        
        // (i32, f32) query'si sadece e1'i bulmalı
        let count = world.query::<(&TestCompI32, &TestCompF32)>().unwrap().iter().count();
        assert_eq!(count, 1);
    }

    #[test]
    fn query_mut_modifies_data() {
        #[derive(Clone)]
        struct TestCompI32(i32);
        impl crate::component::Component for TestCompI32 {}

        let mut world = World::new();
        world.register_component_type::<TestCompI32>();
        
        let e1 = world.spawn(); world.add_component(e1, TestCompI32(1));
        let e2 = world.spawn(); world.add_component(e2, TestCompI32(2));
        
        // Query ile tüm i32'leri iki katına çıkar
        if let Some(mut q) = world.query::<crate::query::Mut<TestCompI32>>() {
            for (_, mut val) in q.iter_mut() {
                val.0 *= 2;
            }
        }
        
        assert_eq!(world.borrow::<TestCompI32>().get(e1.id()).unwrap().0, 2);
        assert_eq!(world.borrow::<TestCompI32>().get(e2.id()).unwrap().0, 4);
    }

    #[test]
    fn query_skips_non_matching() {
        #[derive(Clone)]
        struct CompA;
        impl crate::component::Component for CompA {}
        #[derive(Clone)]
        struct CompB;
        impl crate::component::Component for CompB {}

        let mut world = World::new();
        world.register_component_type::<CompA>();
        world.register_component_type::<CompB>();

        for _ in 0..100 {
            let e = world.spawn();
            world.add_component(e, CompA);
        }

        for _ in 0..50 {
            let e = world.spawn();
            world.add_component(e, CompB);
        }

        let a_count = world.query::<&CompA>().unwrap().iter().count();
        let b_count = world.query::<&CompB>().unwrap().iter().count();
        let both_count = world.query::<(&CompA, &CompB)>().unwrap().iter().count();

        assert_eq!(a_count, 100);
        assert_eq!(b_count, 50);
        assert_eq!(both_count, 0);
    }

    #[test]
    fn spawn_despawn_10k_entities_archetype_stability() {
        #[derive(Clone)]
        struct CompA(i32);
        impl crate::component::Component for CompA {}
        #[derive(Clone)]
        struct CompB(f32);
        impl crate::component::Component for CompB {}

        let mut world = World::new();
        world.register_component_type::<CompA>();
        world.register_component_type::<CompB>();

        let initial_archetypes = world.archetype_index.archetypes.len();

        // Spawn 10k entities
        let mut entities = Vec::new();
        for i in 0..10_000 {
            let e = world.spawn();
            world.add_component(e, CompA(i as i32));
            if i % 2 == 0 {
                world.add_component(e, CompB(i as f32));
            }
            entities.push(e);
        }

        // Despawn all
        for e in entities {
            world.despawn(e.id());
        }

        // Archetype sayısı aynı kalmalı
        let final_archetypes = world.archetype_index.archetypes.len();
        // 1 empty, 1 for CompA, 1 for (CompA, CompB) = 3 total usually.
        assert!(final_archetypes <= initial_archetypes + 2);
    }
}