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