gizmo-core 0.10.0

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
use super::World;
use crate::archetype::{ComponentInfo, EntityLocation};
use crate::component::Component;
use crate::entity::Entity;

use std::any::TypeId;

impl World {
    /// Adding a component to the system — moves the data into the archetype column.
    ///
    /// A dead entity is a silent no-op, and so is an entity whose id was *reserved* from the
    /// allocator but never handed to [`World::flush_spawn`] (what `Commands::spawn` produces
    /// before its queue is applied): it is [`World::is_alive`] yet owns no archetype row, so
    /// there is nowhere to write. That mirrors [`World::add_component`]'s documented
    /// behaviour for the same entity state.
    ///
    /// Hooks: an all-`Table` bundle takes the block-move fast path and fires **no**
    /// `on_add`/`on_set` hooks — observers registered with [`World::add_observer`] do not see
    /// it. A bundle carrying a `SparseSet` component is routed through
    /// [`crate::component::Bundle::apply`] instead and does fire them per component. See
    /// [`crate::world::hooks::ComponentHooks`] for the full list of hook-free paths.
    pub fn add_bundle<B: crate::component::Bundle>(&mut self, entity: Entity, bundle: B) {
        if !self.is_alive(entity) { return; }
        let eid = entity.id();
        let infos = B::get_infos();

        // The block-move fast path below writes every component into an archetype
        // column, which has no home for SparseSet components (they live in
        // `sparse_sets`). If the bundle carries any sparse component, route the
        // whole bundle through `apply` — per-component `add_component`, which
        // places each component in its correct storage. All-table bundles keep the
        // single-migration fast path.
        if infos
            .iter()
            .any(|i| i.storage_type == crate::component::StorageType::SparseSet)
        {
            bundle.apply(self, entity);
            return;
        }

        for info in &infos {
            self.component_infos.entry(info.type_id).or_insert_with(|| *info);
        }

        // An id RESERVED from the allocator but never flushed (`Commands::spawn` hands one
        // out before its queued `flush_spawn` runs) is `is_alive` yet owns no archetype row.
        // Every path below indexes `entity_locations[eid]` raw, so such an entity panicked:
        // out of bounds when the slot was never allocated, or — for a recycled id, whose
        // slot exists but holds `EntityLocation::INVALID` — it fed `row == u32::MAX` into
        // `move_entity_to`. Bail out instead, which is exactly what `add_component` and
        // `Bundle::apply` already do for Table components on such an entity.
        //
        // Flushing here instead would be WRONG: `Commands::spawn` has already queued a
        // `flush_spawn` for this id and `flush_spawn` must run exactly once — a second call
        // pushes another empty-archetype row and overwrites the location, orphaning storage.
        if !self.entity_location(eid).is_valid() {
            tracing::warn!(
                entity = eid,
                "add_bundle: entity has no archetype row (reserved but not flushed); bundle dropped"
            );
            return;
        }

        // Table bazlı block move:
        let old_arch_id = match self.archetype_index.entity_archetype.get(&eid) {
            Some(&id) => id,
            None => {
                // Unreachable for a live, flushed entity: `flush_spawn` → `on_spawn` always
                // inserts `entity_archetype[eid] = 0`, so even a component-less entity takes
                // the `Some(0)` arm. Kept as a defensive fallback to the empty archetype.
                let _arch = &mut self.archetype_index.archetypes[0];
                0
            }
        };

        let mut new_types = self.archetype_index.archetypes[old_arch_id].sorted_component_types();
        for info in &infos {
            if let Err(pos) = new_types.binary_search(&info.type_id) {
                new_types.insert(pos, info.type_id);
            }
        }

        let target_arch_id = if let Some(&id) = self.archetype_index.set_to_id.get(&new_types) {
            id
        } else {
            let id = self.archetype_index.archetypes.len();
            let mut new_infos = Vec::new();
            for &t in &new_types {
                new_infos.push(self.component_infos.get(&t).cloned().unwrap());
            }
            self.archetype_index.archetypes.push(crate::archetype::Archetype::new(id as u32, &new_infos));
            self.archetype_index.set_to_id.insert(new_types, id);
            id
        };

        if old_arch_id == target_arch_id {
            // Sadece override
            let loc = self.entity_locations[eid as usize];
            let arch = &mut self.archetype_index.archetypes[target_arch_id];
            unsafe { bundle.write_to_archetype(arch, loc.row as usize, self.tick); }
            return;
        }

        tracing::trace!(
            entity = eid,
            from = old_arch_id,
            to = target_arch_id,
            "add_bundle: archetype migration"
        );

        let old_loc = self.entity_locations[eid as usize];
        let (new_row, moved_eid) = {
            // İki archetype'ı FARKLI indekslerden disjoint ödünç al. Aynı Vec'ten
            // iki `&mut ...[i] as *mut` almak, ikinci retag ile ilk pointer'ın
            // provenance'ını geçersiz kılıp onu kullanınca UB üretiyordu (Miri
            // Stacked Borrows). `get_disjoint_mut` aliasing'siz iki &mut verir.
            let [old_arch, target_arch] = self
                .archetype_index
                .archetypes
                .get_disjoint_mut([old_arch_id, target_arch_id])
                .expect("old and target archetype indices are distinct and in bounds");
            // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
            unsafe { old_arch.move_entity_to(old_loc.row as usize, target_arch) }
        };

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

        let arch = &mut self.archetype_index.archetypes[target_arch_id];
        unsafe { bundle.write_to_archetype(arch, new_row as usize, self.tick); }

        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);
    }

    /// Removes every component listed by `B` from `entity` in one archetype migration.
    ///
    /// Only `B`'s *type list* is used, never any value, hence the turbofish:
    /// `world.remove_bundle::<(Transform, Velocity)>(e)`. Components of `B` the entity does
    /// not have are ignored, and a dead entity is a silent no-op.
    ///
    /// The migration swap-removes the entity's old row, so another entity in the source
    /// archetype may change position (its data is preserved).
    ///
    /// Hook asymmetry to know about: `on_remove` fires for `B`'s `SparseSet`-storage
    /// components, but its Table-storage components are detached by the archetype migration
    /// with no hook at all. [`World::remove_component`] fires `on_remove` for both.
    pub fn remove_bundle<B: crate::component::Bundle>(&mut self, entity: Entity) {
        if !self.is_alive(entity) { return; }
        let eid = entity.id();
        let infos = B::get_infos();

        // SparseSet components live in `sparse_sets`, not archetype columns, so the
        // block-move below never touches them — remove them explicitly (mirrors
        // remove_component's sparse branch, on_remove hooks included).
        for info in &infos {
            if info.storage_type == crate::component::StorageType::SparseSet {
                let removed = self
                    .sparse_sets
                    .get_mut(&info.type_id)
                    .is_some_and(|set| set.remove(eid));
                if removed {
                    let tid = info.type_id;
                    self.run_hooks(tid, |h, w| {
                        for hook in &mut h.on_remove {
                            hook(w, entity);
                        }
                    });
                }
            }
        }

        let old_arch_id = match self.archetype_index.entity_archetype.get(&eid) {
            Some(&id) => id,
            None => return,
        };

        let mut new_types = self.archetype_index.archetypes[old_arch_id].sorted_component_types();
        for info in &infos {
            if let Ok(pos) = new_types.binary_search(&info.type_id) {
                new_types.remove(pos);
            }
        }

        let target_arch_id = if let Some(&id) = self.archetype_index.set_to_id.get(&new_types) {
            id
        } else {
            let id = self.archetype_index.archetypes.len();
            let mut new_infos = Vec::new();
            for &t in &new_types {
                new_infos.push(self.component_infos.get(&t).cloned().unwrap());
            }
            self.archetype_index.archetypes.push(crate::archetype::Archetype::new(id as u32, &new_infos));
            self.archetype_index.set_to_id.insert(new_types, id);
            id
        };

        if old_arch_id == target_arch_id { return; }

        tracing::trace!(
            entity = eid,
            from = old_arch_id,
            to = target_arch_id,
            "remove_bundle: archetype migration"
        );

        let old_loc = self.entity_locations[eid as usize];
        let (new_row, moved_eid) = {
            // İki archetype'ı FARKLI indekslerden disjoint ödünç al. Aynı Vec'ten
            // iki `&mut ...[i] as *mut` almak, ikinci retag ile ilk pointer'ın
            // provenance'ını geçersiz kılıp onu kullanınca UB üretiyordu (Miri
            // Stacked Borrows). `get_disjoint_mut` aliasing'siz iki &mut verir.
            let [old_arch, target_arch] = self
                .archetype_index
                .archetypes
                .get_disjoint_mut([old_arch_id, target_arch_id])
                .expect("old and target archetype indices are distinct and in bounds");
            // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
            unsafe { old_arch.move_entity_to(old_loc.row as usize, target_arch) }
        };

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

        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);
    }

    /// Attaches `component` to `entity`, overwriting any value already there, and registers
    /// `T`'s runtime metadata with the world as a side effect (so
    /// [`World::register_component_type`] is never strictly required first).
    ///
    /// A dead entity is a silent no-op. An overwrite assigns over the existing slot, which
    /// drops the previous value — no leak for a `T` that owns a heap allocation. A first
    /// attach migrates the entity to the archetype with `T` added, swap-removing its old
    /// row, so another entity in the source archetype may change position.
    ///
    /// Hooks: a first attach fires `on_add` then `on_set`; an overwrite fires `on_set`
    /// only. That holds identically for `Table` and `SparseSet` storage.
    ///
    /// One asymmetry to watch for on entities whose id was *reserved* from the allocator but
    /// never passed to [`World::flush_spawn`]: they are [`World::is_alive`] but have no
    /// archetype row, so a `Table`-storage component is dropped silently while a `SparseSet`
    /// one is stored anyway, since sparse sets live outside the archetype.
    ///
    /// # Panics
    /// If the target archetype turns out to lack `T`'s column, which would mean the
    /// archetype index and the component metadata registry have diverged.
    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>();

        if T::storage_type() == crate::component::StorageType::SparseSet {
            let info = self.component_infos.get(&type_id).copied().unwrap_or_else(|| ComponentInfo::of::<T>());
            let set = self.sparse_sets.entry(type_id).or_insert_with(|| {
                crate::archetype::sparse_set::ComponentSparseSet::new(info)
            });
            // Overwrite vs. new insert: fire on_add ONLY when the entity did not already
            // have the component, matching the Table-storage path below (overwrite → on_set
            // only). Previously SparseSet unconditionally fired on_add, so re-adding a
            // SparseSet component double-fired Insert observers — storage-dependent behavior.
            let existed = set.contains(eid);
            let ptr = &component as *const T as *const u8;
            // SAFETY: `ptr`, set'in `info.layout`'u ile birebir eşleşen `T` bileşenini gösterir;
            // sahiplik set'e devredilir ve aşağıda `forget` ile çift-drop engellenir.
            unsafe { set.insert(eid, ptr, self.tick); }
            std::mem::forget(component);

            self.run_hooks(type_id, |h, w| {
                if !existed {
                    for hook in &mut h.on_add { hook(w, entity); }
                }
                for hook in &mut h.on_set { hook(w, entity); }
            });
            return;
        }

        // Original logic follows but skip register and eid assignments



        // 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];
                // SAFETY: query/scheduler bu archetype sütununa ayrık erişimi garanti eder.
                let col = unsafe { 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 mut hooks = self.component_hooks.remove(&type_id);
            if let Some(ref mut h) = hooks {
                for hook in &mut h.on_set {
                    hook(self, entity);
                }
            }
            if let Some(h) = hooks {
                if let Some(existing) = self.component_hooks.get_mut(&type_id) {
                    existing.on_add.extend(h.on_add);
                    existing.on_set.extend(h.on_set);
                    existing.on_remove.extend(h.on_remove);
                } else {
                    self.component_hooks.insert(type_id, h);
                }
            }
            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,
        );
        tracing::trace!(
            entity = eid,
            from = old_arch_id,
            to = target_arch_id,
            "add_component: archetype migration"
        );

        // İki archetype'ı FARKLI indekslerden disjoint olarak ödünç al. Önceki hal
        // aynı Vec'ten iki `&mut ...[i] as *mut` alıyordu; ikinci retag ilk
        // pointer'ın provenance'ını geçersiz kılıp onu kullanınca UB üretiyordu
        // (Miri Stacked Borrows ihlali). `get_disjoint_mut` iki ayrı indekse
        // aliasing'siz `&mut` verir — unsafe'e gerek yok.
        let (new_row, moved_eid) = {
            let [old_arch, target_arch] = self
                .archetype_index
                .archetypes
                .get_disjoint_mut([old_arch_id, target_arch_id])
                .expect("old and target archetype indices must be distinct and in bounds");
            // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
            unsafe { old_arch.move_entity_to(old_row, target_arch) }
        };

        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];
            // SAFETY: yeni satır bu archetype'a az önce ayrıldı; sütuna tekil erişim.
            let col = unsafe { 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 mut hooks = self.component_hooks.remove(&type_id);
        if let Some(ref mut h) = hooks {
            for hook in &mut h.on_add {
                hook(self, entity);
            }
            for hook in &mut h.on_set {
                hook(self, entity);
            }
        }
        if let Some(h) = hooks {
            if let Some(existing) = self.component_hooks.get_mut(&type_id) {
                existing.on_add.extend(h.on_add);
                existing.on_set.extend(h.on_set);
                existing.on_remove.extend(h.on_remove);
            } else {
                self.component_hooks.insert(type_id, h);
            }
        }
    }

    /// Getting a raw Component Pointer (for Reflection/Editor)
    pub fn get_component_ptr(&self, entity: Entity, type_id: TypeId) -> Option<*const u8> {
        // SparseSet components live outside the archetype — otherwise type-erased
        // access (reflection, scene serialization) can't see them.
        if let Some(set) = self.sparse_sets.get(&type_id) {
            if let Some(p) = set.get_ptr(entity.id()) {
                return Some(p);
            }
        }
        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) })
    }

    /// Getting a Mut mutable Component pointer (for HierarchyExt etc.)
    pub fn get_component_mut_ptr(&mut self, entity: Entity, type_id: TypeId) -> Option<*mut u8> {
        if let Some(set) = self.sparse_sets.get_mut(&type_id) {
            if let Some(p) = set.get_ptr_mut(entity.id()) {
                return Some(p);
            }
        }
        let loc = self.entity_locations.get(entity.id() as usize).copied()?;
        if !loc.is_valid() {
            return None;
        }
        let arch = &mut self.archetype_index.archetypes[loc.archetype_id as usize];
        // SAFETY: &mut self ile tekil archetype erişimi; sütuna tekil &mut.
        let col = unsafe { arch.get_column_mut(type_id) }?;
        Some(unsafe { col.get_mut_ptr(loc.row as usize) })
    }

    /// Deleting a component from the system
    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>();

        if T::storage_type() == crate::component::StorageType::SparseSet {
            if let Some(set) = self.sparse_sets.get_mut(&type_id) {
                if set.remove(eid) {
                    self.run_hooks(type_id, |h, w| {
                        for hook in &mut h.on_remove { hook(w, entity); }
                    });
                }
            }
            return;
        }


        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
        }

        tracing::trace!(
            entity = eid,
            from = old_loc.archetype_id,
            to = target_arch_id,
            "remove_component: archetype migration"
        );

        // 2. Migration — iki archetype'ı FARKLI indekslerden disjoint ödünç al
        // (aynı Vec'ten iki `&mut ... as *mut` = geçersiz-kılınan-provenance UB'si).
        let (new_row, moved_eid) = {
            let [old_arch, target_arch] = self
                .archetype_index
                .archetypes
                .get_disjoint_mut([old_loc.archetype_id as usize, target_arch_id])
                .expect("old and target archetype indices are distinct and in bounds");
            // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
            unsafe { old_arch.move_entity_to(old_loc.row as usize, target_arch) }
        };

        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);

        self.run_hooks(type_id, |h, w| {
            for hook in &mut h.on_remove {
                hook(w, entity);
            }
        });
    }

    /// Batch component insertion. It reduces the O(N) archetype lookup cost to O(1).
    ///
    /// # Example
    /// ```
    /// # use gizmo_core::prelude::*;
    /// # #[derive(Clone, Copy)] struct Health(u32);
    /// # #[derive(Clone, Copy)] struct Team(u8);
    /// # gizmo_core::impl_component!(Health, Team);
    /// # let mut world = World::new();
    /// let ids: Vec<Entity> = (0..3).map(|_| world.spawn_bundle(Health(100))).collect();
    /// world.insert_batch(&ids, Team(2)); // one archetype lookup for the whole group
    ///
    /// let q = world.query::<&Team>().unwrap();
    /// assert_eq!(q.iter().count(), 3);
    /// assert_eq!(q.get(ids[2].id()).unwrap().0, 2);
    /// ```
    #[tracing::instrument(skip_all, name = "insert_batch")]
    pub fn insert_batch<T: Component + Clone>(&mut self, entities: &[Entity], component: T) {
        if T::storage_type() == crate::component::StorageType::SparseSet {
            for &e in entities {
                self.add_component(e, component.clone());
            }
            return;
        }

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

        // 1. Gruplama: source_arch_id -> Vec<Entity>
        let mut groups: std::collections::HashMap<u32, Vec<Entity>> = std::collections::HashMap::new();

        for &e in entities {
            if !self.is_alive(e) { continue; }
            let loc = self.entity_locations[e.id() as usize];
            if !loc.is_valid() { continue; }
            groups.entry(loc.archetype_id).or_default().push(e);
        }

        for (source_arch_id, group_entities) in groups {
            let target_arch_id = match self.archetype_index.get_add_component_target(
                group_entities[0].id(), type_id, &self.component_infos
            ) {
                Some(id) => id,
                None => continue,
            };

            if source_arch_id == target_arch_id as u32 {
                let arch = &self.archetype_index.archetypes[target_arch_id];
                // SAFETY: batch insert sırasında bu sütuna tekil erişim.
                let col = unsafe { arch.get_column_mut(type_id) }.unwrap();
                for e in &group_entities {
                    let row = self.entity_locations[e.id() as usize].row as usize;
                    unsafe {
                        // Same-archetype overwrite: the slot already holds a live `T`.
                        // Assignment (`*ptr = ..`) drops the old value; `ptr::write` would
                        // leak it for any `T: Drop` (e.g. String/Vec/Handle re-asserted each
                        // frame → unbounded heap growth). Mirrors `add_component`'s path.
                        *(col.get_ptr(row) as *mut T) = component.clone();
                        col.ticks_ptr_mut().add(row).write(crate::archetype::ComponentTicks::new(self.tick));
                    }
                }
                self.run_hooks(type_id, |h, w| {
                    for e in &group_entities {
                        for hook in &mut h.on_set {
                            hook(w, *e);
                        }
                    }
                });
                tracing::debug!(
                    count = group_entities.len(),
                    archetype = target_arch_id,
                    "insert_batch: same-archetype overwrite group"
                );
                continue;
            }

            let migrated = group_entities.len();
            for e in &group_entities {
                let eid = e.id();
                let old_loc = self.entity_locations[eid as usize];
                let old_row = old_loc.row as usize;

                // Disjoint ödünç (source != target, yukarıda 422'de guard'landı).
                let (new_row, moved_eid) = {
                    let [old_arch, target_arch] = self
                        .archetype_index
                        .archetypes
                        .get_disjoint_mut([source_arch_id as usize, target_arch_id])
                        .expect("source and target archetype indices are distinct and in bounds");
                    // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
                    unsafe { old_arch.move_entity_to(old_row, target_arch) }
                };

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

                {
                    let arch = &self.archetype_index.archetypes[target_arch_id];
                    // SAFETY: yeni ayrılan satır; sütuna tekil erişim.
                    let col = unsafe { arch.get_column_mut(type_id) }.unwrap();
                    unsafe {
                        std::ptr::write(col.get_ptr(new_row as usize) as *mut T, component.clone());
                        col.ticks_ptr_mut().add(new_row as usize).write(crate::archetype::ComponentTicks::new(self.tick));
                    }
                }

                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);
            }

            self.run_hooks(type_id, |h, w| {
                for e in &group_entities {
                    for hook in &mut h.on_add { hook(w, *e); }
                    for hook in &mut h.on_set { hook(w, *e); }
                }
            });
            tracing::debug!(
                count = migrated,
                from = source_arch_id,
                to = target_arch_id,
                "insert_batch: migrated group to new archetype"
            );
        }
    }

    /// Batch component removal
    #[tracing::instrument(skip_all, name = "remove_batch")]
    pub fn remove_batch<T: Component>(&mut self, entities: &[Entity]) {
        if T::storage_type() == crate::component::StorageType::SparseSet {
            for &e in entities {
                self.remove_component::<T>(e);
            }
            return;
        }

        let type_id = TypeId::of::<T>();
        let mut groups: std::collections::HashMap<u32, Vec<Entity>> = std::collections::HashMap::new();

        for &e in entities {
            if !self.is_alive(e) { continue; }
            let loc = self.entity_locations[e.id() as usize];
            if !loc.is_valid() { continue; }
            groups.entry(loc.archetype_id).or_default().push(e);
        }

        for (source_arch_id, group_entities) in groups {
            let target_arch_id = match self.archetype_index.get_remove_component_target(
                group_entities[0].id(), type_id, &self.component_infos
            ) {
                Some(id) => id,
                None => continue,
            };

            if source_arch_id == target_arch_id as u32 {
                continue;
            }

            for e in &group_entities {
                let eid = e.id();
                let old_loc = self.entity_locations[eid as usize];

                // Disjoint ödünç (source != target, yukarıda 520'de guard'landı).
                let (new_row, moved_eid) = {
                    let [old_arch, target_arch] = self
                        .archetype_index
                        .archetypes
                        .get_disjoint_mut([source_arch_id as usize, target_arch_id])
                        .expect("source and target archetype indices are distinct and in bounds");
                    // SAFETY: move_entity_to raw sütun kopyaları yapar; ödünçler disjoint.
                    unsafe { old_arch.move_entity_to(old_loc.row as usize, target_arch) }
                };

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

                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);
            }

            self.run_hooks(type_id, |h, w| {
                for e in &group_entities {
                    for hook in &mut h.on_remove { hook(w, *e); }
                }
            });
            tracing::debug!(
                count = group_entities.len(),
                from = source_arch_id,
                to = target_arch_id,
                "remove_batch: migrated group to new archetype"
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use crate::component::Component;
    use crate::world::World;

    #[derive(Clone, PartialEq, Debug)]
    struct Pos(i32);
    impl Component for Pos {}
    #[derive(Clone, PartialEq, Debug)]
    struct Vel(i32);
    impl Component for Vel {}

    /// Migrating an entity between archetypes needs mutable access to two distinct
    /// archetypes stored in the same `Vec`. The old code took two
    /// `&mut archetypes[i] as *mut` — the second retag invalidated the first
    /// pointer's provenance, so using it was aliasing UB (caught by Miri). The fix
    /// uses `get_disjoint_mut`. This test drives the swap-remove `moved_eid`
    /// relocation path and must stay green under `cargo miri test` (see the Miri
    /// CI job) to fence the invariant.
    #[test]
    fn archetype_migration_preserves_all_components() {
        let mut world = World::new();
        let e0 = world.spawn();
        world.add_component(e0, Pos(0));
        let e1 = world.spawn();
        world.add_component(e1, Pos(1));
        let e2 = world.spawn();
        world.add_component(e2, Pos(2));

        // All three share archetype {Pos}. Adding Vel to the MIDDLE entity migrates
        // e1 to {Pos,Vel}; e2 swap-fills e1's vacated row in {Pos} (moved_eid path).
        world.add_component(e1, Vel(10));

        assert_eq!(world.borrow::<Pos>().get(e0.id()).unwrap().0, 0);
        assert_eq!(world.borrow::<Pos>().get(e1.id()).unwrap().0, 1);
        assert_eq!(world.borrow::<Pos>().get(e2.id()).unwrap().0, 2);
        assert_eq!(world.borrow::<Vel>().get(e1.id()).unwrap().0, 10);
        assert!(world.borrow::<Vel>().get(e0.id()).is_none());
        assert!(world.borrow::<Vel>().get(e2.id()).is_none());

        // Remove Vel → e1 migrates back to {Pos}; every entity's data stays intact.
        world.remove_component::<Vel>(e1);
        assert_eq!(world.borrow::<Pos>().get(e0.id()).unwrap().0, 0);
        assert_eq!(world.borrow::<Pos>().get(e1.id()).unwrap().0, 1);
        assert_eq!(world.borrow::<Pos>().get(e2.id()).unwrap().0, 2);
        assert!(world.borrow::<Vel>().get(e1.id()).is_none());
    }

    /// `add_bundle` on a reserved-but-unflushed id must not panic.
    ///
    /// `Commands::spawn` reserves the id immediately and only queues `flush_spawn`, so
    /// between those two moments the entity is `is_alive` with NO `entity_locations` slot —
    /// the same legal state `despawn_reserved_but_unflushed_entity_does_not_panic` covers.
    /// `add_bundle` indexed that slot raw and panicked with "index out of bounds".
    /// `add_component` on the same entity is a documented silent no-op; the bundle path now
    /// matches it instead of crashing.
    #[test]
    fn add_bundle_on_reserved_but_unflushed_entity_does_not_panic() {
        let mut world = World::new();
        let reserved = {
            let entities = world
                .get_resource::<crate::entity::allocator::Entities>()
                .expect("Entities resource");
            entities.reserve_entity()
        };
        assert!(world.is_alive(reserved), "a reserved entity is considered alive");

        world.add_bundle(reserved, (Pos(1), Vel(2))); // panicked here (entity_locations OOB)

        assert!(
            world.entity_component_types(reserved).is_empty(),
            "no storage exists for an unflushed id, so nothing can have been attached"
        );
        // The world must still be usable — the dropped bundle left no half-built archetype.
        let ok = world.spawn();
        world.add_component(ok, Pos(7));
        assert_eq!(world.borrow::<Pos>().get(ok.id()).unwrap().0, 7);
    }

    /// The recycled-id half of the same defect: here the `entity_locations` slot EXISTS
    /// (despawn wrote `EntityLocation::INVALID` into it), so the raw index did not trip —
    /// it read `row == u32::MAX` and handed that to `move_entity_to` as a source row, which
    /// is worse than a panic. The liveness/validity guard covers both shapes.
    #[test]
    fn add_bundle_on_recycled_unflushed_id_does_not_corrupt() {
        let mut world = World::new();
        let victim = world.spawn();
        world.add_component(victim, Pos(1));
        let survivor = world.spawn();
        world.add_component(survivor, Pos(2));
        world.despawn(victim); // frees the id; its location slot becomes INVALID

        // The allocator hands the freed id straight back, un-flushed.
        let recycled = {
            let entities = world
                .get_resource::<crate::entity::allocator::Entities>()
                .expect("Entities resource");
            entities.reserve_entity()
        };
        assert_eq!(recycled.id(), victim.id(), "id was recycled as expected");
        assert!(!world.entity_location(recycled.id()).is_valid());

        world.add_bundle(recycled, (Pos(3), Vel(4)));

        // Survivor untouched: no bogus row move happened.
        assert_eq!(world.borrow::<Pos>().get(survivor.id()).unwrap().0, 2);
        assert!(world.entity_component_types(recycled).is_empty());
    }
}