hecs/
world.rs

1// Copyright 2019 Google LLC
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use crate::alloc::{vec, vec::Vec};
9use core::any::TypeId;
10use core::borrow::Borrow;
11use core::convert::TryFrom;
12use core::hash::{BuildHasherDefault, Hasher};
13use spin::Mutex;
14
15use core::{fmt, ptr};
16
17#[cfg(feature = "std")]
18use std::error::Error;
19
20use hashbrown::hash_map::{Entry, HashMap};
21
22use crate::alloc::boxed::Box;
23use crate::archetype::{Archetype, TypeIdMap, TypeInfo};
24use crate::entities::{Entities, EntityMeta, Location, ReserveEntitiesIterator};
25use crate::query::{assert_borrow, assert_distinct};
26use crate::{
27    Bundle, ColumnBatch, ComponentRef, DynamicBundle, Entity, EntityRef, Fetch, MissingComponent,
28    NoSuchEntity, Query, QueryBorrow, QueryMut, QueryOne, TakenEntity, View, ViewBorrow,
29};
30
31/// An unordered collection of entities, each having any number of distinctly typed components
32///
33/// Similar to `HashMap<Entity, Vec<Box<dyn Any>>>` where each `Vec` never contains two of the same
34/// type, but far more efficient to traverse.
35///
36/// The components of entities who have the same set of component types are stored in contiguous
37/// runs, allowing for extremely fast, cache-friendly iteration.
38///
39/// There is a maximum number of unique entity IDs, which means that there is a maximum number of live
40/// entities. When old entities are despawned, their IDs will be reused on a future entity, and
41/// old `Entity` values with that ID will be invalidated.
42///
43/// ### Collisions
44///
45/// If an entity is despawned and its `Entity` handle is preserved over the course of billions of
46/// following spawns and despawns, that handle may, in rare circumstances, collide with a
47/// newly-allocated `Entity` handle. Very long-lived applications should therefore limit the period
48/// over which they may retain handles of despawned entities.
49pub struct World {
50    entities: Entities,
51    archetypes: ArchetypeSet,
52    /// Maps statically-typed bundle types to archetypes
53    bundle_to_archetype: TypeIdMap<u32>,
54    /// Maps source archetype and static bundle types to the archetype that an entity is moved to
55    /// after inserting the components from that bundle.
56    insert_edges: IndexTypeIdMap<InsertTarget>,
57    /// Maps source archetype and static bundle types to the archetype that an entity is moved to
58    /// after removing the components from that bundle.
59    remove_edges: IndexTypeIdMap<u32>,
60    id: u64,
61}
62
63impl World {
64    /// Create an empty world
65    pub fn new() -> Self {
66        // AtomicU64 is unsupported on 32-bit MIPS and PPC architectures
67        // For compatibility, use Mutex<u64>
68        static ID: Mutex<u64> = Mutex::new(1);
69        let id = {
70            let mut id = ID.lock();
71            let next = id.checked_add(1).unwrap();
72            *id = next;
73            next
74        };
75        Self {
76            entities: Entities::default(),
77            archetypes: ArchetypeSet::new(),
78            bundle_to_archetype: HashMap::default(),
79            insert_edges: HashMap::default(),
80            remove_edges: HashMap::default(),
81            id,
82        }
83    }
84
85    /// Create an entity with certain components
86    ///
87    /// Returns the ID of the newly created entity.
88    ///
89    /// Arguments can be tuples, structs annotated with [`#[derive(Bundle)]`](macro@Bundle), or the
90    /// result of calling [`build`](crate::EntityBuilder::build) on an
91    /// [`EntityBuilder`](crate::EntityBuilder), which is useful if the set of components isn't
92    /// statically known. To spawn an entity with only one component, use a one-element tuple like
93    /// `(x,)`.
94    ///
95    /// Any type that satisfies `Send + Sync + 'static` can be used as a component.
96    ///
97    /// # Example
98    /// ```
99    /// # use hecs::*;
100    /// let mut world = World::new();
101    /// let a = world.spawn((123, "abc"));
102    /// let b = world.spawn((456, true));
103    /// ```
104    pub fn spawn(&mut self, components: impl DynamicBundle) -> Entity {
105        // Ensure all entity allocations are accounted for so `self.entities` can realloc if
106        // necessary
107        self.flush();
108
109        let entity = self.entities.alloc();
110
111        self.spawn_inner(entity, components);
112
113        entity
114    }
115
116    /// Create an entity with certain components and a specific [`Entity`] handle.
117    ///
118    /// See [`spawn`](Self::spawn).
119    ///
120    /// Despawns any existing entity with the same [`Entity::id`].
121    ///
122    /// Useful for easy handle-preserving deserialization. Be cautious resurrecting old `Entity`
123    /// handles in already-populated worlds as it vastly increases the likelihood of collisions.
124    ///
125    /// # Example
126    /// ```
127    /// # use hecs::*;
128    /// let mut world = World::new();
129    /// let a = world.spawn((123, "abc"));
130    /// let b = world.spawn((456, true));
131    /// world.despawn(a);
132    /// assert!(!world.contains(a));
133    /// // all previous Entity values pointing to 'a' will be live again, instead pointing to the new entity.
134    /// world.spawn_at(a, (789, "ABC"));
135    /// assert!(world.contains(a));
136    /// ```
137    pub fn spawn_at(&mut self, handle: Entity, components: impl DynamicBundle) {
138        // Ensure all entity allocations are accounted for so `self.entities` can realloc if
139        // necessary
140        self.flush();
141
142        let loc = self.entities.alloc_at(handle);
143        if let Some(loc) = loc {
144            if let Some(moved) = unsafe {
145                self.archetypes.archetypes[loc.archetype as usize].remove(loc.index, true)
146            } {
147                self.entities.meta[moved as usize].location.index = loc.index;
148            }
149        }
150
151        self.spawn_inner(handle, components);
152    }
153
154    fn spawn_inner(&mut self, entity: Entity, components: impl DynamicBundle) {
155        let archetype_id = match components.key() {
156            Some(k) => {
157                let archetypes = &mut self.archetypes;
158                *self.bundle_to_archetype.entry(k).or_insert_with(|| {
159                    components.with_ids(|ids| archetypes.get(ids, || components.type_info()))
160                })
161            }
162            None => components.with_ids(|ids| self.archetypes.get(ids, || components.type_info())),
163        };
164
165        let archetype = &mut self.archetypes.archetypes[archetype_id as usize];
166        unsafe {
167            let index = archetype.allocate(entity.id);
168            components.put(|ptr, ty| {
169                archetype.put_dynamic(ptr, ty.id(), ty.layout().size(), index);
170            });
171            self.entities.meta[entity.id as usize].location = Location {
172                archetype: archetype_id,
173                index,
174            };
175        }
176    }
177
178    /// Efficiently spawn a large number of entities with the same statically-typed components
179    ///
180    /// Faster than calling [`spawn`](Self::spawn) repeatedly with the same components, but requires
181    /// that component types are known at compile time.
182    ///
183    /// # Example
184    /// ```
185    /// # use hecs::*;
186    /// let mut world = World::new();
187    /// let entities = world.spawn_batch((0..1_000).map(|i| (i, "abc"))).collect::<Vec<_>>();
188    /// for i in 0..1_000 {
189    ///     assert_eq!(*world.get::<&i32>(entities[i]).unwrap(), i as i32);
190    /// }
191    /// ```
192    pub fn spawn_batch<I>(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter>
193    where
194        I: IntoIterator,
195        I::Item: Bundle + 'static,
196    {
197        // Ensure all entity allocations are accounted for so `self.entities` can realloc if
198        // necessary
199        self.flush();
200
201        let iter = iter.into_iter();
202        let (lower, upper) = iter.size_hint();
203        let archetype_id = self.reserve_inner::<I::Item>(
204            u32::try_from(upper.unwrap_or(lower)).expect("iterator too large"),
205        );
206
207        SpawnBatchIter {
208            inner: iter,
209            entities: &mut self.entities,
210            archetype_id,
211            archetype: &mut self.archetypes.archetypes[archetype_id as usize],
212        }
213    }
214
215    /// Super-efficiently spawn the contents of a [`ColumnBatch`]
216    ///
217    /// The fastest, but most specialized, way to spawn large numbers of entities. Useful for high
218    /// performance deserialization. Supports dynamic component types.
219    pub fn spawn_column_batch(&mut self, batch: ColumnBatch) -> SpawnColumnBatchIter<'_> {
220        self.flush();
221
222        let archetype = batch.0;
223        let entity_count = archetype.len();
224        // Store component data
225        let (archetype_id, base) = self.archetypes.insert_batch(archetype);
226
227        let archetype = &mut self.archetypes.archetypes[archetype_id as usize];
228        let id_alloc = self.entities.alloc_many(entity_count, archetype_id, base);
229
230        // Fix up entity IDs
231        let mut id_alloc_clone = id_alloc.clone();
232        let mut index = base as usize;
233        while let Some(id) = id_alloc_clone.next(&self.entities) {
234            archetype.set_entity_id(index, id);
235            index += 1;
236        }
237
238        // Return iterator over new IDs
239        SpawnColumnBatchIter {
240            pending_end: id_alloc.pending_end,
241            id_alloc,
242            entities: &mut self.entities,
243        }
244    }
245
246    /// Hybrid of [`spawn_column_batch`](Self::spawn_column_batch) and [`spawn_at`](Self::spawn_at)
247    pub fn spawn_column_batch_at(&mut self, handles: &[Entity], batch: ColumnBatch) {
248        let archetype = batch.0;
249        assert_eq!(
250            handles.len(),
251            archetype.len() as usize,
252            "number of entity IDs {} must match number of entities {}",
253            handles.len(),
254            archetype.len()
255        );
256
257        // Drop components of entities that will be replaced
258        for &handle in handles {
259            let loc = self.entities.alloc_at(handle);
260            if let Some(loc) = loc {
261                if let Some(moved) = unsafe {
262                    self.archetypes.archetypes[loc.archetype as usize].remove(loc.index, true)
263                } {
264                    self.entities.meta[moved as usize].location.index = loc.index;
265                }
266            }
267        }
268
269        // Store components
270        let (archetype_id, base) = self.archetypes.insert_batch(archetype);
271
272        // Fix up entity IDs
273        let archetype = &mut self.archetypes.archetypes[archetype_id as usize];
274        for (&handle, index) in handles.iter().zip(base as usize..) {
275            archetype.set_entity_id(index, handle.id());
276            self.entities.meta[handle.id() as usize].location = Location {
277                archetype: archetype_id,
278                index: index as u32,
279            };
280        }
281    }
282
283    /// Allocate many entities ID concurrently
284    ///
285    /// Unlike [`spawn`](Self::spawn), this can be called concurrently with other operations on the
286    /// [`World`] such as queries, but does not immediately create the entities. Reserved entities
287    /// are not visible to queries or world iteration, but can be otherwise operated on
288    /// freely. Operations that add or remove components or entities, such as `insert` or `despawn`,
289    /// will cause all outstanding reserved entities to become real entities before proceeding. This
290    /// can also be done explicitly by calling [`flush`](Self::flush).
291    ///
292    /// Useful for reserving an ID that will later have components attached to it with `insert`.
293    pub fn reserve_entities(&self, count: u32) -> ReserveEntitiesIterator {
294        self.entities.reserve_entities(count)
295    }
296
297    /// Allocate an entity ID concurrently
298    ///
299    /// See [`reserve_entities`](Self::reserve_entities).
300    pub fn reserve_entity(&self) -> Entity {
301        self.entities.reserve_entity()
302    }
303
304    /// Destroy an entity and all its components
305    ///
306    /// See also [`take`](Self::take).
307    pub fn despawn(&mut self, entity: Entity) -> Result<(), NoSuchEntity> {
308        self.flush();
309        let loc = self.entities.free(entity)?;
310        if let Some(moved) =
311            unsafe { self.archetypes.archetypes[loc.archetype as usize].remove(loc.index, true) }
312        {
313            self.entities.meta[moved as usize].location.index = loc.index;
314        }
315        Ok(())
316    }
317
318    /// Ensure at least `additional` entities with exact components `T` can be spawned without reallocating
319    pub fn reserve<T: Bundle + 'static>(&mut self, additional: u32) {
320        self.reserve_inner::<T>(additional);
321    }
322
323    fn reserve_inner<T: Bundle + 'static>(&mut self, additional: u32) -> u32 {
324        self.flush();
325        self.entities.reserve(additional);
326
327        let archetypes = &mut self.archetypes;
328        let archetype_id = *self
329            .bundle_to_archetype
330            .entry(TypeId::of::<T>())
331            .or_insert_with(|| {
332                T::with_static_ids(|ids| {
333                    archetypes.get(ids, || T::with_static_type_info(|info| info.to_vec()))
334                })
335            });
336
337        self.archetypes.archetypes[archetype_id as usize].reserve(additional);
338        archetype_id
339    }
340
341    /// Despawn all entities
342    ///
343    /// Preserves allocated storage for reuse but clears metadata so that [`Entity`] values will repeat (in contrast to [`despawn`][Self::despawn]).
344    pub fn clear(&mut self) {
345        for x in &mut self.archetypes.archetypes {
346            x.clear();
347        }
348        self.entities.clear();
349    }
350
351    /// Whether `entity` still exists
352    pub fn contains(&self, entity: Entity) -> bool {
353        self.entities.contains(entity)
354    }
355
356    /// Efficiently iterate over all entities that have certain components, using dynamic borrow
357    /// checking
358    ///
359    /// Prefer [`query_mut`](Self::query_mut) when concurrent access to the [`World`] is not required.
360    ///
361    /// Calling `iter` on the returned value yields `(Entity, Q)` tuples, where `Q` is some query
362    /// type. A query type is any type for which an implementation of [`Query`] exists, e.g. `&T`,
363    /// `&mut T`, a tuple of query types, or an `Option` wrapping a query type, where `T` is any
364    /// component type. Components queried with `&mut` must only appear once. Entities which do not
365    /// have a component type referenced outside of an `Option` will be skipped.
366    ///
367    /// Entities are yielded in arbitrary order.
368    ///
369    /// The returned [`QueryBorrow`] can be further transformed with combinator methods; see its
370    /// documentation for details.
371    ///
372    /// Iterating a query will panic if it would violate an existing unique reference or construct
373    /// an invalid unique reference. This occurs when two simultaneously-active queries could expose
374    /// the same entity. Simultaneous queries can access the same component type if and only if the
375    /// world contains no entities that have all components required by both queries, assuming no
376    /// other component borrows are outstanding.
377    ///
378    /// Iterating a query yields references with lifetimes bound to the [`QueryBorrow`] returned
379    /// here. To ensure those are invalidated, the return value of this method must be dropped for
380    /// its dynamic borrows from the world to be released. Similarly, lifetime rules ensure that
381    /// references obtained from a query cannot outlive the [`QueryBorrow`].
382    ///
383    /// # Example
384    /// ```
385    /// # use hecs::*;
386    /// let mut world = World::new();
387    /// let a = world.spawn((123, true, "abc"));
388    /// let b = world.spawn((456, false));
389    /// let c = world.spawn((42, "def"));
390    /// let entities = world.query::<(&i32, &bool)>()
391    ///     .iter()
392    ///     .map(|(e, (&i, &b))| (e, i, b)) // Copy out of the world
393    ///     .collect::<Vec<_>>();
394    /// assert_eq!(entities.len(), 2);
395    /// assert!(entities.contains(&(a, 123, true)));
396    /// assert!(entities.contains(&(b, 456, false)));
397    /// ```
398    pub fn query<Q: Query>(&self) -> QueryBorrow<'_, Q> {
399        QueryBorrow::new(self)
400    }
401
402    /// Provide random access to any entity for a given Query.
403    pub fn view<Q: Query>(&self) -> ViewBorrow<'_, Q> {
404        ViewBorrow::new(self)
405    }
406
407    /// Provide random access to any entity for a given Query on a uniquely
408    /// borrowed world. Like [`view`](Self::view), but faster because dynamic borrow checks can be skipped.
409    pub fn view_mut<Q: Query>(&mut self) -> View<'_, Q> {
410        assert_borrow::<Q>();
411        unsafe { View::<Q>::new(self.entities_meta(), self.archetypes_inner()) }
412    }
413
414    /// Query a uniquely borrowed world
415    ///
416    /// Like [`query`](Self::query), but faster because dynamic borrow checks can be skipped. Note
417    /// that, unlike [`query`](Self::query), this returns an `IntoIterator` which can be passed
418    /// directly to a `for` loop.
419    pub fn query_mut<Q: Query>(&mut self) -> QueryMut<'_, Q> {
420        QueryMut::new(self)
421    }
422
423    pub(crate) fn memo(&self) -> (u64, u32) {
424        (self.id, self.archetypes.generation())
425    }
426
427    #[inline(always)]
428    pub(crate) fn entities_meta(&self) -> &[EntityMeta] {
429        &self.entities.meta
430    }
431
432    #[inline(always)]
433    pub(crate) fn archetypes_inner(&self) -> &[Archetype] {
434        &self.archetypes.archetypes
435    }
436
437    /// Prepare a query against a single entity, using dynamic borrow checking
438    ///
439    /// Prefer [`query_one_mut`](Self::query_one_mut) when concurrent access to the [`World`] is not
440    /// required.
441    ///
442    /// Call [`get`](QueryOne::get) on the resulting [`QueryOne`] to actually execute the query. The
443    /// [`QueryOne`] value is responsible for releasing the dynamically-checked borrow made by
444    /// `get`, so it can't be dropped while references returned by `get` are live.
445    ///
446    /// Handy for accessing multiple components simultaneously.
447    ///
448    /// # Example
449    /// ```
450    /// # use hecs::*;
451    /// let mut world = World::new();
452    /// let a = world.spawn((123, true, "abc"));
453    /// // The returned query must outlive the borrow made by `get`
454    /// let mut query = world.query_one::<(&mut i32, &bool)>(a).unwrap();
455    /// let (number, flag) = query.get().unwrap();
456    /// if *flag { *number *= 2; }
457    /// assert_eq!(*number, 246);
458    /// ```
459    pub fn query_one<Q: Query>(&self, entity: Entity) -> Result<QueryOne<'_, Q>, NoSuchEntity> {
460        let loc = self.entities.get(entity)?;
461        Ok(unsafe {
462            QueryOne::new(
463                &self.archetypes.archetypes[loc.archetype as usize],
464                loc.index,
465            )
466        })
467    }
468
469    /// Query a single entity in a uniquely borrowed world
470    ///
471    /// Like [`query_one`](Self::query_one), but faster because dynamic borrow checks can be
472    /// skipped. Note that, unlike [`query_one`](Self::query_one), on success this returns the
473    /// query's results directly.
474    pub fn query_one_mut<Q: Query>(
475        &mut self,
476        entity: Entity,
477    ) -> Result<Q::Item<'_>, QueryOneError> {
478        assert_borrow::<Q>();
479
480        let loc = self.entities.get(entity)?;
481        let archetype = &self.archetypes.archetypes[loc.archetype as usize];
482        let state = Q::Fetch::prepare(archetype).ok_or(QueryOneError::Unsatisfied)?;
483        let fetch = Q::Fetch::execute(archetype, state);
484        unsafe { Ok(Q::get(&fetch, loc.index as usize)) }
485    }
486
487    /// Query a fixed number of distinct entities in a uniquely borrowed world
488    ///
489    /// Like [`query_one_mut`](Self::query_one_mut), but for multiple entities, which would
490    /// otherwise be forbidden by the unique borrow. Panics if the same entity occurs more than
491    /// once.
492    pub fn query_many_mut<Q: Query, const N: usize>(
493        &mut self,
494        entities: [Entity; N],
495    ) -> [Result<Q::Item<'_>, QueryOneError>; N] {
496        assert_borrow::<Q>();
497        assert_distinct(&entities);
498
499        entities.map(|entity| {
500            let loc = self.entities.get(entity)?;
501            let archetype = &self.archetypes.archetypes[loc.archetype as usize];
502            let state = Q::Fetch::prepare(archetype).ok_or(QueryOneError::Unsatisfied)?;
503            let fetch = Q::Fetch::execute(archetype, state);
504            unsafe { Ok(Q::get(&fetch, loc.index as usize)) }
505        })
506    }
507
508    /// Short-hand for [`entity`](Self::entity) followed by [`EntityRef::get`]
509    pub fn get<'a, T: ComponentRef<'a>>(
510        &'a self,
511        entity: Entity,
512    ) -> Result<T::Ref, ComponentError> {
513        Ok(self
514            .entity(entity)?
515            .get::<T>()
516            .ok_or_else(MissingComponent::new::<T::Component>)?)
517    }
518
519    /// Short-hand for [`entity`](Self::entity) followed by [`EntityRef::satisfies`]
520    pub fn satisfies<Q: Query>(&self, entity: Entity) -> Result<bool, NoSuchEntity> {
521        Ok(self.entity(entity)?.satisfies::<Q>())
522    }
523
524    /// Access an entity regardless of its component types
525    ///
526    /// Does not immediately borrow any component.
527    pub fn entity(&self, entity: Entity) -> Result<EntityRef<'_>, NoSuchEntity> {
528        let loc = self.entities.get(entity)?;
529        unsafe {
530            Ok(EntityRef::new(
531                &self.archetypes.archetypes[loc.archetype as usize],
532                entity,
533                loc.index,
534            ))
535        }
536    }
537
538    /// Given an id obtained from [`Entity::id`], reconstruct the still-live [`Entity`].
539    ///
540    /// # Safety
541    ///
542    /// `id` must correspond to a currently live [`Entity`]. A despawned or never-allocated `id`
543    /// will produce undefined behavior.
544    pub unsafe fn find_entity_from_id(&self, id: u32) -> Entity {
545        self.entities.resolve_unknown_gen(id)
546    }
547
548    /// Iterate over all entities in the world
549    ///
550    /// Entities are yielded in arbitrary order. Prefer [`query`](Self::query) for better
551    /// performance when components will be accessed in predictable patterns.
552    ///
553    /// # Example
554    /// ```
555    /// # use hecs::*;
556    /// let mut world = World::new();
557    /// let a = world.spawn(());
558    /// let b = world.spawn(());
559    /// let ids = world.iter().map(|entity_ref| entity_ref.entity()).collect::<Vec<_>>();
560    /// assert_eq!(ids.len(), 2);
561    /// assert!(ids.contains(&a));
562    /// assert!(ids.contains(&b));
563    /// ```
564    pub fn iter(&self) -> Iter<'_> {
565        Iter::new(&self.archetypes.archetypes, &self.entities)
566    }
567
568    /// Add `components` to `entity`
569    ///
570    /// Computational cost is proportional to the number of components `entity` has. If an entity
571    /// already has a component of a certain type, it is dropped and replaced.
572    ///
573    /// When inserting a single component, see [`insert_one`](Self::insert_one) for convenience.
574    ///
575    /// # Example
576    /// ```
577    /// # use hecs::*;
578    /// let mut world = World::new();
579    /// let e = world.spawn((123, "abc"));
580    /// world.insert(e, (456, true));
581    /// assert_eq!(*world.get::<&i32>(e).unwrap(), 456);
582    /// assert_eq!(*world.get::<&bool>(e).unwrap(), true);
583    /// ```
584    pub fn insert(
585        &mut self,
586        entity: Entity,
587        components: impl DynamicBundle,
588    ) -> Result<(), NoSuchEntity> {
589        self.flush();
590
591        let loc = self.entities.get(entity)?;
592        self.insert_inner(entity, components, loc.archetype, loc);
593        Ok(())
594    }
595
596    /// The implementation backing [`insert`](Self::insert) exposed so that it can also be used by [`exchange`](Self::exchange).
597    ///
598    /// Note that `graph_origin` is always equal to `loc.archetype` during insertion. Only for exchange, `graph_origin` identifies
599    /// the intermediate archetype which would be reached after removal and before insertion even though
600    /// the actual component data still resides in `loc.archetype`.
601    fn insert_inner(
602        &mut self,
603        entity: Entity,
604        components: impl DynamicBundle,
605        graph_origin: u32,
606        loc: Location,
607    ) {
608        let target_storage;
609        let target = match components.key() {
610            None => {
611                target_storage = self.archetypes.get_insert_target(graph_origin, &components);
612                &target_storage
613            }
614            Some(key) => match self.insert_edges.entry((graph_origin, key)) {
615                Entry::Occupied(entry) => entry.into_mut(),
616                Entry::Vacant(entry) => {
617                    let target = self.archetypes.get_insert_target(graph_origin, &components);
618                    entry.insert(target)
619                }
620            },
621        };
622
623        let source_arch = &mut self.archetypes.archetypes[loc.archetype as usize];
624        unsafe {
625            // Drop the components we're overwriting
626            for &ty in &target.replaced {
627                let ptr = source_arch
628                    .get_dynamic(ty.id(), ty.layout().size(), loc.index)
629                    .unwrap();
630                ty.drop(ptr.as_ptr());
631            }
632
633            if target.index == loc.archetype {
634                // Update components in the current archetype
635                let arch = &mut self.archetypes.archetypes[loc.archetype as usize];
636                components.put(|ptr, ty| {
637                    arch.put_dynamic(ptr, ty.id(), ty.layout().size(), loc.index);
638                });
639                return;
640            }
641
642            let (source_arch, target_arch) = index2(
643                &mut self.archetypes.archetypes,
644                loc.archetype as usize,
645                target.index as usize,
646            );
647
648            // Allocate storage in the archetype and update the entity's location to address it
649            let target_index = target_arch.allocate(entity.id);
650            let meta = &mut self.entities.meta[entity.id as usize];
651            meta.location.archetype = target.index;
652            meta.location.index = target_index;
653
654            // Move the new components
655            components.put(|ptr, ty| {
656                target_arch.put_dynamic(ptr, ty.id(), ty.layout().size(), target_index);
657            });
658
659            // Move the components we're keeping
660            for &ty in &target.retained {
661                let src = source_arch
662                    .get_dynamic(ty.id(), ty.layout().size(), loc.index)
663                    .unwrap();
664                target_arch.put_dynamic(src.as_ptr(), ty.id(), ty.layout().size(), target_index)
665            }
666
667            // Free storage in the old archetype
668            if let Some(moved) = source_arch.remove(loc.index, false) {
669                self.entities.meta[moved as usize].location.index = loc.index;
670            }
671        }
672    }
673
674    /// Add `component` to `entity`
675    ///
676    /// See [`insert`](Self::insert).
677    pub fn insert_one(
678        &mut self,
679        entity: Entity,
680        component: impl Component,
681    ) -> Result<(), NoSuchEntity> {
682        self.insert(entity, (component,))
683    }
684
685    /// Remove components from `entity`
686    ///
687    /// Computational cost is proportional to the number of components `entity` has. The entity
688    /// itself is not removed, even if no components remain; use `despawn` for that. If any
689    /// component in `T` is not present in `entity`, no components are removed and an error is
690    /// returned.
691    ///
692    /// When removing a single component, see [`remove_one`](Self::remove_one) for convenience.
693    ///
694    /// # Example
695    /// ```
696    /// # use hecs::*;
697    /// let mut world = World::new();
698    /// let e = world.spawn((123, "abc", true));
699    /// assert_eq!(world.remove::<(i32, &str)>(e), Ok((123, "abc")));
700    /// assert!(world.get::<&i32>(e).is_err());
701    /// assert!(world.get::<&&str>(e).is_err());
702    /// assert_eq!(*world.get::<&bool>(e).unwrap(), true);
703    /// ```
704    pub fn remove<T: Bundle + 'static>(&mut self, entity: Entity) -> Result<T, ComponentError> {
705        self.flush();
706
707        // Gather current metadata
708        let loc = self.entities.get_mut(entity)?;
709        let old_index = loc.index;
710        let source_arch = &self.archetypes.archetypes[loc.archetype as usize];
711
712        // Move out of the source archetype, or bail out if a component is missing
713        let bundle = unsafe {
714            T::get(|ty| source_arch.get_dynamic(ty.id(), ty.layout().size(), old_index))?
715        };
716
717        // Find the target archetype ID
718        let target =
719            Self::remove_target::<T>(&mut self.archetypes, &mut self.remove_edges, loc.archetype);
720
721        // Store components to the target archetype and update metadata
722        if loc.archetype != target {
723            // If we actually removed any components, the entity needs to be moved into a new archetype
724            let (source_arch, target_arch) = index2(
725                &mut self.archetypes.archetypes,
726                loc.archetype as usize,
727                target as usize,
728            );
729            let target_index = unsafe { target_arch.allocate(entity.id) };
730            loc.archetype = target;
731            loc.index = target_index;
732            if let Some(moved) = unsafe {
733                source_arch.move_to(old_index, |src, ty, size| {
734                    // Only move the components present in the target archetype, i.e. the non-removed ones.
735                    if let Some(dst) = target_arch.get_dynamic(ty, size, target_index) {
736                        ptr::copy_nonoverlapping(src, dst.as_ptr(), size);
737                    }
738                })
739            } {
740                self.entities.meta[moved as usize].location.index = old_index;
741            }
742        }
743
744        Ok(bundle)
745    }
746
747    fn remove_target<T: Bundle + 'static>(
748        archetypes: &mut ArchetypeSet,
749        remove_edges: &mut IndexTypeIdMap<u32>,
750        old_archetype: u32,
751    ) -> u32 {
752        match remove_edges.entry((old_archetype, TypeId::of::<T>())) {
753            Entry::Occupied(entry) => *entry.into_mut(),
754            Entry::Vacant(entry) => {
755                let info = T::with_static_type_info(|removed| {
756                    archetypes.archetypes[old_archetype as usize]
757                        .types()
758                        .iter()
759                        .filter(|x| removed.binary_search(x).is_err())
760                        .cloned()
761                        .collect::<Vec<_>>()
762                });
763                let elements = info.iter().map(|x| x.id()).collect::<Box<_>>();
764                let index = archetypes.get(&*elements, move || info);
765                *entry.insert(index)
766            }
767        }
768    }
769
770    /// Remove the `T` component from `entity`
771    ///
772    /// See [`remove`](Self::remove).
773    pub fn remove_one<T: Component>(&mut self, entity: Entity) -> Result<T, ComponentError> {
774        self.remove::<(T,)>(entity).map(|(x,)| x)
775    }
776
777    /// Remove `S` components from `entity` and then add `components`
778    ///
779    /// This has the same effect as calling [`remove::<S>`](Self::remove) and then [`insert::<T>`](Self::insert),
780    /// but is more efficient as the intermediate archetype after removal but before insertion is skipped.
781    pub fn exchange<S: Bundle + 'static, T: DynamicBundle>(
782        &mut self,
783        entity: Entity,
784        components: T,
785    ) -> Result<S, ComponentError> {
786        self.flush();
787
788        // Gather current metadata
789        let loc = self.entities.get(entity)?;
790
791        // Move out of the source archetype, or bail out if a component is missing
792        let source_arch = &self.archetypes.archetypes[loc.archetype as usize];
793
794        let bundle = unsafe {
795            S::get(|ty| source_arch.get_dynamic(ty.id(), ty.layout().size(), loc.index))?
796        };
797
798        // Find the intermediate archetype ID
799        let intermediate =
800            Self::remove_target::<S>(&mut self.archetypes, &mut self.remove_edges, loc.archetype);
801
802        self.insert_inner(entity, components, intermediate, loc);
803
804        Ok(bundle)
805    }
806
807    /// Remove the `S` component from `entity` and then add `component`
808    ///
809    /// See [`exchange`](Self::exchange).
810    pub fn exchange_one<S: Component, T: Component>(
811        &mut self,
812        entity: Entity,
813        component: T,
814    ) -> Result<S, ComponentError> {
815        self.exchange::<(S,), (T,)>(entity, (component,))
816            .map(|(x,)| x)
817    }
818
819    /// Borrow a single component of `entity` without safety checks
820    ///
821    /// `T` must be a shared or unique reference to a component type.
822    ///
823    /// Should only be used as a building block for safe abstractions.
824    ///
825    /// # Safety
826    ///
827    /// `entity` must have been previously obtained from this [`World`], and no unique borrow of the
828    /// same component of `entity` may be live simultaneous to the returned reference.
829    pub unsafe fn get_unchecked<'a, T: ComponentRef<'a>>(
830        &'a self,
831        entity: Entity,
832    ) -> Result<T, ComponentError> {
833        let loc = self.entities.get(entity)?;
834        let archetype = &self.archetypes.archetypes[loc.archetype as usize];
835        let state = archetype
836            .get_state::<T::Component>()
837            .ok_or_else(MissingComponent::new::<T::Component>)?;
838        Ok(T::from_raw(
839            archetype
840                .get_base::<T::Component>(state)
841                .as_ptr()
842                .add(loc.index as usize),
843        ))
844    }
845
846    /// Convert all reserved entities into empty entities that can be iterated and accessed
847    ///
848    /// Invoked implicitly by operations that add or remove components or entities, i.e. all
849    /// variations of `spawn`, `despawn`, `insert`, and `remove`.
850    pub fn flush(&mut self) {
851        let arch = &mut self.archetypes.archetypes[0];
852        self.entities
853            .flush(|id, location| location.index = unsafe { arch.allocate(id) });
854    }
855
856    /// Inspect the archetypes that entities are organized into
857    ///
858    /// Useful for dynamically scheduling concurrent queries by checking borrows in advance, and for
859    /// efficient serialization.
860    #[inline(always)]
861    pub fn archetypes(&self) -> impl ExactSizeIterator<Item = &'_ Archetype> + '_ {
862        self.archetypes_inner().iter()
863    }
864
865    /// Despawn `entity`, yielding a [`DynamicBundle`] of its components
866    ///
867    /// Useful for moving entities between worlds.
868    pub fn take(&mut self, entity: Entity) -> Result<TakenEntity<'_>, NoSuchEntity> {
869        self.flush();
870        let loc = self.entities.get(entity)?;
871        let archetype = &mut self.archetypes.archetypes[loc.archetype as usize];
872        unsafe {
873            Ok(TakenEntity::new(
874                &mut self.entities,
875                entity,
876                archetype,
877                loc.index,
878            ))
879        }
880    }
881
882    /// Returns a distinct value after `archetypes` is changed
883    ///
884    /// Store the current value after deriving information from [`archetypes`](Self::archetypes),
885    /// then check whether the value returned by this function differs before attempting an
886    /// operation that relies on its correctness. Useful for determining whether e.g. a concurrent
887    /// query execution plan is still correct.
888    ///
889    /// The generation may be, but is not necessarily, changed as a result of adding or removing any
890    /// entity or component.
891    ///
892    /// # Example
893    /// ```
894    /// # use hecs::*;
895    /// let mut world = World::new();
896    /// let initial_gen = world.archetypes_generation();
897    /// world.spawn((123, "abc"));
898    /// assert_ne!(initial_gen, world.archetypes_generation());
899    /// ```
900    pub fn archetypes_generation(&self) -> ArchetypesGeneration {
901        ArchetypesGeneration(self.archetypes.generation())
902    }
903
904    /// Number of currently live entities
905    #[inline]
906    pub fn len(&self) -> u32 {
907        self.entities.len()
908    }
909
910    /// Whether no entities are live
911    #[inline]
912    pub fn is_empty(&self) -> bool {
913        self.len() == 0
914    }
915}
916
917unsafe impl Send for World {}
918unsafe impl Sync for World {}
919
920impl Default for World {
921    fn default() -> Self {
922        Self::new()
923    }
924}
925
926impl<'a> IntoIterator for &'a World {
927    type IntoIter = Iter<'a>;
928    type Item = EntityRef<'a>;
929    fn into_iter(self) -> Iter<'a> {
930        self.iter()
931    }
932}
933
934fn index2<T>(x: &mut [T], i: usize, j: usize) -> (&mut T, &mut T) {
935    assert!(i != j);
936    assert!(i < x.len());
937    assert!(j < x.len());
938    let ptr = x.as_mut_ptr();
939    unsafe { (&mut *ptr.add(i), &mut *ptr.add(j)) }
940}
941
942/// Errors that arise when accessing components
943#[derive(Debug, Clone, Eq, PartialEq, Hash)]
944pub enum ComponentError {
945    /// The entity was already despawned
946    NoSuchEntity,
947    /// The entity did not have a requested component
948    MissingComponent(MissingComponent),
949}
950
951#[cfg(feature = "std")]
952impl Error for ComponentError {}
953
954impl fmt::Display for ComponentError {
955    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
956        use ComponentError::*;
957        match *self {
958            NoSuchEntity => f.write_str("no such entity"),
959            MissingComponent(ref x) => x.fmt(f),
960        }
961    }
962}
963
964impl From<NoSuchEntity> for ComponentError {
965    fn from(NoSuchEntity: NoSuchEntity) -> Self {
966        ComponentError::NoSuchEntity
967    }
968}
969
970impl From<MissingComponent> for ComponentError {
971    fn from(x: MissingComponent) -> Self {
972        ComponentError::MissingComponent(x)
973    }
974}
975
976/// Errors that arise when querying a single entity
977#[derive(Debug, Clone, Eq, PartialEq, Hash)]
978pub enum QueryOneError {
979    /// The entity was already despawned
980    NoSuchEntity,
981    /// The entity exists but does not satisfy the query
982    Unsatisfied,
983}
984
985#[cfg(feature = "std")]
986impl Error for QueryOneError {}
987
988impl fmt::Display for QueryOneError {
989    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
990        use QueryOneError::*;
991        match *self {
992            NoSuchEntity => f.write_str("no such entity"),
993            Unsatisfied => f.write_str("unsatisfied"),
994        }
995    }
996}
997
998impl From<NoSuchEntity> for QueryOneError {
999    fn from(NoSuchEntity: NoSuchEntity) -> Self {
1000        QueryOneError::NoSuchEntity
1001    }
1002}
1003
1004/// Types that can be components, implemented automatically for all `Send + Sync + 'static` types
1005///
1006/// This is just a convenient shorthand for `Send + Sync + 'static`, and never needs to be
1007/// implemented manually.
1008pub trait Component: Send + Sync + 'static {}
1009impl<T: Send + Sync + 'static> Component for T {}
1010
1011/// Iterator over all of a world's entities
1012pub struct Iter<'a> {
1013    archetypes: core::slice::Iter<'a, Archetype>,
1014    entities: &'a Entities,
1015    current: Option<&'a Archetype>,
1016    index: u32,
1017}
1018
1019impl<'a> Iter<'a> {
1020    fn new(archetypes: &'a [Archetype], entities: &'a Entities) -> Self {
1021        Self {
1022            archetypes: archetypes.iter(),
1023            entities,
1024            current: None,
1025            index: 0,
1026        }
1027    }
1028}
1029
1030unsafe impl Send for Iter<'_> {}
1031unsafe impl Sync for Iter<'_> {}
1032
1033impl<'a> Iterator for Iter<'a> {
1034    type Item = EntityRef<'a>;
1035    fn next(&mut self) -> Option<Self::Item> {
1036        loop {
1037            match self.current {
1038                None => {
1039                    self.current = Some(self.archetypes.next()?);
1040                    self.index = 0;
1041                }
1042                Some(current) => {
1043                    if self.index == current.len() {
1044                        self.current = None;
1045                        continue;
1046                    }
1047                    let index = self.index;
1048                    self.index += 1;
1049                    let id = current.entity_id(index);
1050                    return Some(unsafe {
1051                        EntityRef::new(
1052                            current,
1053                            Entity {
1054                                id,
1055                                generation: self.entities.meta[id as usize].generation,
1056                            },
1057                            index,
1058                        )
1059                    });
1060                }
1061            }
1062        }
1063    }
1064
1065    fn size_hint(&self) -> (usize, Option<usize>) {
1066        (self.len(), Some(self.len()))
1067    }
1068}
1069
1070impl ExactSizeIterator for Iter<'_> {
1071    #[inline]
1072    fn len(&self) -> usize {
1073        self.entities.len() as usize
1074    }
1075}
1076
1077impl<A: DynamicBundle> Extend<A> for World {
1078    fn extend<T>(&mut self, iter: T)
1079    where
1080        T: IntoIterator<Item = A>,
1081    {
1082        for x in iter {
1083            self.spawn(x);
1084        }
1085    }
1086}
1087
1088impl<A: DynamicBundle> core::iter::FromIterator<A> for World {
1089    fn from_iter<I: IntoIterator<Item = A>>(iter: I) -> Self {
1090        let mut world = World::new();
1091        world.extend(iter);
1092        world
1093    }
1094}
1095
1096/// Determines freshness of information derived from [`World::archetypes`]
1097#[derive(Debug, Copy, Clone, Eq, PartialEq)]
1098pub struct ArchetypesGeneration(u32);
1099
1100/// Entity IDs created by [`World::spawn_batch`]
1101pub struct SpawnBatchIter<'a, I>
1102where
1103    I: Iterator,
1104    I::Item: Bundle,
1105{
1106    inner: I,
1107    entities: &'a mut Entities,
1108    archetype_id: u32,
1109    archetype: &'a mut Archetype,
1110}
1111
1112impl<I> Drop for SpawnBatchIter<'_, I>
1113where
1114    I: Iterator,
1115    I::Item: Bundle,
1116{
1117    fn drop(&mut self) {
1118        for _ in self {}
1119    }
1120}
1121
1122impl<I> Iterator for SpawnBatchIter<'_, I>
1123where
1124    I: Iterator,
1125    I::Item: Bundle,
1126{
1127    type Item = Entity;
1128
1129    fn next(&mut self) -> Option<Entity> {
1130        let components = self.inner.next()?;
1131        let entity = self.entities.alloc();
1132        let index = unsafe { self.archetype.allocate(entity.id) };
1133        unsafe {
1134            components.put(|ptr, ty| {
1135                self.archetype
1136                    .put_dynamic(ptr, ty.id(), ty.layout().size(), index);
1137            });
1138        }
1139        self.entities.meta[entity.id as usize].location = Location {
1140            archetype: self.archetype_id,
1141            index,
1142        };
1143        Some(entity)
1144    }
1145
1146    fn size_hint(&self) -> (usize, Option<usize>) {
1147        self.inner.size_hint()
1148    }
1149}
1150
1151impl<I, T> ExactSizeIterator for SpawnBatchIter<'_, I>
1152where
1153    I: ExactSizeIterator<Item = T>,
1154    T: Bundle,
1155{
1156    fn len(&self) -> usize {
1157        self.inner.len()
1158    }
1159}
1160
1161/// Iterator over [`Entity`]s spawned by [`World::spawn_column_batch()`]
1162pub struct SpawnColumnBatchIter<'a> {
1163    pending_end: usize,
1164    id_alloc: crate::entities::AllocManyState,
1165    entities: &'a mut Entities,
1166}
1167
1168impl Iterator for SpawnColumnBatchIter<'_> {
1169    type Item = Entity;
1170
1171    fn next(&mut self) -> Option<Entity> {
1172        let id = self.id_alloc.next(self.entities)?;
1173        Some(unsafe { self.entities.resolve_unknown_gen(id) })
1174    }
1175
1176    fn size_hint(&self) -> (usize, Option<usize>) {
1177        (self.len(), Some(self.len()))
1178    }
1179}
1180
1181impl ExactSizeIterator for SpawnColumnBatchIter<'_> {
1182    fn len(&self) -> usize {
1183        self.id_alloc.len(self.entities)
1184    }
1185}
1186
1187impl Drop for SpawnColumnBatchIter<'_> {
1188    fn drop(&mut self) {
1189        // Consume used freelist entries
1190        self.entities.finish_alloc_many(self.pending_end);
1191    }
1192}
1193
1194struct ArchetypeSet {
1195    /// Maps sorted component type sets to archetypes
1196    index: HashMap<Box<[TypeId]>, u32>,
1197    archetypes: Vec<Archetype>,
1198}
1199
1200impl ArchetypeSet {
1201    fn new() -> Self {
1202        // `flush` assumes archetype 0 always exists, representing entities with no components.
1203        Self {
1204            index: Some((Box::default(), 0)).into_iter().collect(),
1205            archetypes: vec![Archetype::new(Vec::new())],
1206        }
1207    }
1208
1209    /// Find the archetype ID that has exactly `components`
1210    fn get<T: Borrow<[TypeId]> + Into<Box<[TypeId]>>>(
1211        &mut self,
1212        components: T,
1213        info: impl FnOnce() -> Vec<TypeInfo>,
1214    ) -> u32 {
1215        self.index
1216            .get(components.borrow())
1217            .copied()
1218            .unwrap_or_else(|| self.insert(components.into(), info()))
1219    }
1220
1221    fn insert(&mut self, components: Box<[TypeId]>, info: Vec<TypeInfo>) -> u32 {
1222        let x = self.archetypes.len() as u32;
1223        self.archetypes.push(Archetype::new(info));
1224        let old = self.index.insert(components, x);
1225        debug_assert!(old.is_none(), "inserted duplicate archetype");
1226        x
1227    }
1228
1229    /// Returns archetype ID and starting location index
1230    fn insert_batch(&mut self, archetype: Archetype) -> (u32, u32) {
1231        let ids = archetype
1232            .types()
1233            .iter()
1234            .map(|info| info.id())
1235            .collect::<Box<_>>();
1236
1237        match self.index.entry(ids) {
1238            Entry::Occupied(x) => {
1239                // Duplicate of existing archetype
1240                let existing = &mut self.archetypes[*x.get() as usize];
1241                let base = existing.len();
1242                unsafe {
1243                    existing.merge(archetype);
1244                }
1245                (*x.get(), base)
1246            }
1247            Entry::Vacant(x) => {
1248                // Brand new archetype
1249                let id = self.archetypes.len() as u32;
1250                self.archetypes.push(archetype);
1251                x.insert(id);
1252                (id, 0)
1253            }
1254        }
1255    }
1256
1257    fn generation(&self) -> u32 {
1258        self.archetypes.len() as u32
1259    }
1260
1261    fn get_insert_target(&mut self, src: u32, components: &impl DynamicBundle) -> InsertTarget {
1262        // Assemble Vec<TypeInfo> for the final entity
1263        let arch = &mut self.archetypes[src as usize];
1264        let mut info = arch.types().to_vec();
1265        let mut replaced = Vec::new(); // Elements in both archetype.types() and components.type_info()
1266        let mut retained = Vec::new(); // Elements in archetype.types() but not components.type_info()
1267
1268        // Because both `components.type_info()` and `arch.types()` are
1269        // ordered, we can identify elements in one but not the other efficiently with parallel
1270        // iteration.
1271        let mut src_ty = 0;
1272        for ty in components.type_info() {
1273            while src_ty < arch.types().len() && arch.types()[src_ty] <= ty {
1274                if arch.types()[src_ty] != ty {
1275                    retained.push(arch.types()[src_ty]);
1276                }
1277                src_ty += 1;
1278            }
1279            if arch.has_dynamic(ty.id()) {
1280                replaced.push(ty);
1281            } else {
1282                info.push(ty);
1283            }
1284        }
1285        info.sort_unstable();
1286        retained.extend_from_slice(&arch.types()[src_ty..]);
1287
1288        // Find the archetype it'll live in
1289        let elements = info.iter().map(|x| x.id()).collect::<Box<_>>();
1290        let index = self.get(elements, move || info);
1291        InsertTarget {
1292            replaced,
1293            retained,
1294            index,
1295        }
1296    }
1297}
1298
1299/// Metadata cached for inserting components into entities from this archetype
1300struct InsertTarget {
1301    /// Components from the current archetype that are replaced by the insert
1302    replaced: Vec<TypeInfo>,
1303    /// Components from the current archetype that are moved by the insert
1304    retained: Vec<TypeInfo>,
1305    /// ID of the target archetype
1306    index: u32,
1307}
1308
1309type IndexTypeIdMap<V> = HashMap<(u32, TypeId), V, BuildHasherDefault<IndexTypeIdHasher>>;
1310
1311#[derive(Default)]
1312struct IndexTypeIdHasher(u64);
1313
1314impl Hasher for IndexTypeIdHasher {
1315    fn write_u32(&mut self, index: u32) {
1316        self.0 ^= u64::from(index);
1317    }
1318
1319    fn write_u64(&mut self, type_id: u64) {
1320        self.0 ^= type_id;
1321    }
1322
1323    fn write(&mut self, _bytes: &[u8]) {
1324        unreachable!()
1325    }
1326
1327    fn finish(&self) -> u64 {
1328        self.0
1329    }
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334    use super::*;
1335
1336    #[test]
1337    fn reuse_empty() {
1338        let mut world = World::new();
1339        let a = world.spawn(());
1340        world.despawn(a).unwrap();
1341        let b = world.spawn(());
1342        assert_eq!(a.id, b.id);
1343        assert_ne!(a.generation, b.generation);
1344    }
1345
1346    #[test]
1347    fn clear_repeats_entity_id() {
1348        let mut world = World::new();
1349        let a = world.spawn(());
1350        world.clear();
1351        let b = world.spawn(());
1352        assert_eq!(a.id, b.id);
1353        assert_eq!(a.generation, b.generation);
1354    }
1355
1356    #[test]
1357    fn spawn_at() {
1358        let mut world = World::new();
1359        let a = world.spawn(());
1360        world.despawn(a).unwrap();
1361        let b = world.spawn(());
1362        assert!(world.contains(b));
1363        assert_eq!(a.id, b.id);
1364        assert_ne!(a.generation, b.generation);
1365        world.spawn_at(a, ());
1366        assert!(!world.contains(b));
1367        assert_eq!(b.id, a.id);
1368        assert_ne!(b.generation, a.generation);
1369    }
1370
1371    #[test]
1372    fn reuse_populated() {
1373        let mut world = World::new();
1374        let a = world.spawn((42,));
1375        assert_eq!(*world.get::<&i32>(a).unwrap(), 42);
1376        world.despawn(a).unwrap();
1377        let b = world.spawn((true,));
1378        assert_eq!(a.id, b.id);
1379        assert_ne!(a.generation, b.generation);
1380        assert!(world.get::<&i32>(b).is_err());
1381        assert!(*world.get::<&bool>(b).unwrap());
1382    }
1383
1384    #[test]
1385    fn remove_nothing() {
1386        let mut world = World::new();
1387        let a = world.spawn(("abc", 123));
1388        world.remove::<()>(a).unwrap();
1389    }
1390
1391    #[test]
1392    fn bad_insert() {
1393        let mut world = World::new();
1394        assert!(world.insert_one(Entity::DANGLING, ()).is_err());
1395    }
1396}