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

use std::any::TypeId;

impl World {
    /// Sisteme component ekleme — Veriyi archetype sütununa taşır.
    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);
        }

        // Table bazlı block move:
        let old_arch_id = match self.archetype_index.entity_archetype.get(&eid) {
            Some(&id) => id,
            None => {
                // Eğer entity önceden bomboşsa (sadece spawn edilmişse)
                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;
        }

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

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

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

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

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

    /// Raw Component Pointer alma (Reflection/Editor için)
    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) })
    }

    /// Mut mutable Component pointer alma (HierarchyExt vs için)
    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) })
    }

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

        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
        }

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

    /// 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;
    /// }
    /// ```
    ///
    /// Toplu (Batch) component ekleme. O(N) archetype lookup maliyetini O(1)'e düşürür.
    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);
                        }
                    }
                });
                continue;
            }

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

    /// Toplu (Batch) component çıkarma
    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); }
                }
            });
        }
    }
}

#[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());
    }
}