Skip to main content

EcsWorld

Struct EcsWorld 

pub struct EcsWorld { /* private fields */ }
Expand description

The central container for the entire ECS, holding all entities, components, and metadata.

Implementations§

§

impl World

pub fn new() -> World

Creates a new, empty World with pre-registered internal component types.

pub fn component_domain(&self, type_id: TypeId) -> Option<SemanticDomain>

Returns the [SemanticDomain] a component type was registered with, or None if it isn’t registered (yet) on this world. Used by the editor to categorise components in the “Add Component” menu and the inspector without hard-coding a per-type table.

pub fn component_layout(&self, type_id: TypeId) -> Option<LayoutPolicy>

The [LayoutPolicy] a component type is currently stored with. Defaults to Soa; the layout-adaptation pass may change it.

pub fn component_access_stats(&self, type_id: TypeId) -> Option<(u64, u64)>

Online access stats (query_count, rows_scanned) for a component type — the DCC / telemetry read these to drive memory-layout adaptation. The DCC only observes; it never mutates the layout (Data self-optimizes).

pub fn entity_count(&self) -> usize

The number of live entities — the coarse workload size n the DCC’s cost model fits agent execution time against.

pub fn component_access_snapshot(&self) -> Vec<(String, usize, u64, u64)>

A snapshot of every registered component’s access pattern as (type_name, size_bytes, query_count, rows_scanned). The hot path samples this at a low rate and publishes it through the observation tunnel; the DCC turns it into a read-only layout recommendation.

pub fn domain_epoch(&self, domain: SemanticDomain) -> u64

Current change epoch of domain — a monotonic counter bumped by every mutation entry point that can affect the domain’s semantic content. Equal epochs across two reads guarantee the domain’s data (and its query iteration order) is unchanged; a different value only means “possibly changed” (bumps are conservative). Flows use this to validate cached Views.

pub fn instance_id(&self) -> u64

Process-unique identifier of this World instance. Cache keys derived from domain_epoch must include it so that epochs from two different World instances never compare equal.

pub fn spawn<B>(&mut self, bundle: B) -> EntityId
where B: ComponentBundle,

Spawns a new entity with the given bundle of components.

This is the primary method for creating entities. It orchestrates the entire process:

  1. Allocates a new EntityId.
  2. Finds or creates a suitable ComponentPage for the component bundle.
  3. Pushes the component data into the page’s columns.
  4. Updates the entity’s metadata to point to the new data’s location.
  5. Updates domain bitsets and stats for the newly created entity components.

Returns the EntityId of the newly created entity.

pub fn despawn(&mut self, entity_id: EntityId) -> bool

Despawns an entity, removing all its components and freeing its ID for recycling.

This method performs the following steps:

  1. Verifies that the EntityId is valid by checking its index and generation.
  2. Removes the entity’s component data from all pages where it is stored.
  3. Marks the entity’s metadata slot as vacant and adds its index to the free list.

Returns true if the entity was valid and despawned, false otherwise.

pub fn query<'a, Q>(&'a self) -> Query<'a, Q>
where Q: WorldQuery,

Creates an iterator that queries the world for entities matching a set of components and filters.

This is the primary method for reading and writing data in the ECS. The query Q is specified as a tuple via turbofish syntax. It can include component references (e.g., &Position, &mut Velocity) and filters (e.g., Without<Parent>).

This method is very cheap to call. It performs an efficient search to identify all ComponentPages that satisfy the query’s criteria. The returned iterator then efficiently iterates over the data in only those pages.

§Examples
// Find all entities with a `Transform` and `GlobalTransform`.
for (transform, global) in world.query::<(&Transform, &GlobalTransform)>() {
    // ...
}

// Find all root entities (those with a `Transform` but without a `Parent`).
for (transform,) in world.query::<(&Transform, Without<Parent>)>() {
    // ...
}

pub fn query_mut<'a, Q>(&'a mut self) -> QueryMut<'a, Q>
where Q: WorldQuery,

Creates a mutable iterator that queries the world for entities matching a set of components and filters.

This method is similar to query, but it allows mutable access to the components. It uses the same dynamic plan re-finding to ensure thread-safe consistency.

pub fn register_component<T>(&mut self, domain: SemanticDomain)
where T: Component,

Registers a component type with a specific semantic domain.

This is a crucial setup step. Before a component of type T can be used in a bundle, it must be registered with the world to define which semantic page group its data will be stored in.

pub fn add_component<C>( &mut self, entity_id: EntityId, component: C, ) -> Result<Option<PageIndex>, AddComponentError>
where C: Component,

This operation is designed to be fast. It performs the necessary data migration to move the entity’s components for the given SemanticDomain to a new ComponentPage that matches the new layout.

Crucially, it does NOT clean up the “hole” left in the old page. Instead, it returns the location of the orphaned data, delegating the cleanup task to an asynchronous garbage collection system.

§Returns
  • Ok(Option<PageIndex>): On success. The Option contains the location of orphaned data if a migration occurred, which should be sent to a garbage collector. It is None if no migration was needed (e.g., adding to a new domain).
  • Err(AddComponentError): If the operation failed (e.g., entity not alive, component not registered, or component already present).

pub fn remove_component<C>( &mut self, entity_id: EntityId, ) -> Result<Option<PageIndex>, RemoveComponentError>
where C: Component,

Removes a single component C from entity, preserving every other component the entity carries (in any domain).

Mirrors add_component in reverse: rebuilds the entity’s domain page signature without C, finds-or-creates a page matching the new signature, and copies the surviving same-domain components there. The old slot is orphaned and reported for the GC, exactly like an add migration.

Use this — not remove_component_domain — for surgical component removal (editor “delete component” button, set_parent unparenting, AGDF demotion). remove_component_domain is a low-level primitive that drops the entire domain bucket and should be reserved for entity teardown / GC paths.

§Returns
  • Ok(Some(PageIndex)) — old location to send to the GC.
  • Ok(None) — should not happen in practice (kept for symmetry with add_component).
  • Err(RemoveComponentError::EntityNotFound) — entity dead or stale.
  • Err(RemoveComponentError::ComponentNotRegistered) — type unknown.
  • Err(RemoveComponentError::ComponentNotPresent) — entity didn’t carry this component to begin with.

pub fn remove_component_domain<C>( &mut self, entity_id: EntityId, ) -> Option<PageIndex>
where C: Component,

Logically removes all components belonging to a specific SemanticDomain from an entity.

This is an extremely fast, O(1) operation that only modifies the entity’s metadata. It does not immediately deallocate or move any component data. The component data is “orphaned” and will be cleaned up later by a garbage collection process.

This method is generic over a component C to determine which domain to remove.

§Returns
  • Some(PageIndex): Contains the location of the orphaned data if the components were successfully removed. This can be sent to a garbage collector.
  • None: If the entity is not alive or did not have any components in the specified SemanticDomain.

pub fn get_mut<T>(&mut self, entity_id: EntityId) -> Option<&mut T>
where T: Component,

Gets a mutable reference to a single component T for a given entity.

This provides direct, “random” access to a component, which can be less performant than querying but is useful for targeted modifications.

§Returns

None if the entity is not alive or does not have the requested component.

pub fn get_many_mut<T, const N: usize>( &mut self, ids: [EntityId; N], ) -> [Option<&mut T>; N]
where T: Component,

Gets mutable references to components of type T for multiple entities simultaneously.

This is safer than get_mut in a loop because it allows retrieving multiple disjoint mutable references to components of the same type.

§Returns

An array of Option<&mut T>. If any entity is not found, does not have the component, or if there are duplicate requests for the same component instance, that entry will be None.

pub fn get<T>(&self, entity_id: EntityId) -> Option<&T>
where T: Component,

Gets an immutable reference to a single component T for a given entity.

This provides direct, “random” access to a component.

§Returns

None if the entity is not alive or does not have the requested component.

pub fn clone_component<T>(&self, entity_id: EntityId) -> Option<T>
where T: Component,

Reads a component by value, working for any physical layout (AoS or field-SoA). This is the layout-agnostic read path: a field-SoA component can’t hand out &T (its bytes aren’t a contiguous T), so callers that must work regardless of layout — the serialization recipe, the Soa<T> query — go through here. For AoS it simply clones the &T.

None if the entity is not alive or lacks the component.

pub fn set_component<T>(&mut self, entity_id: EntityId, value: T) -> bool
where T: Component,

Writes a component by value, working for any physical layout. The layout-agnostic write path (AoS assigns the slot; field-SoA scatters into its lanes). Returns false if the entity is not alive or lacks the component (nothing is written).

pub fn for_each_soa_column_mut<T>( &mut self, f: impl FnMut(&mut FieldSoaColumn<T>), )
where T: SoaLayout,

Runs f over every field-SoA column of component T in the world — the bulk SIMD entry point. Each call hands the kernel a [FieldSoaColumn] whose per-field f32 lanes are contiguous, so it can tile them into f32x8 without gather (the resident layout that reaches ~4×).

Iterates per page so each lane slice is a single archetype’s run. A no-op for any page whose T column is not field-SoA.

pub fn iter_entities(&self) -> impl Iterator<Item = EntityId>

Returns an iterator over all currently living EntityIds in the world.

pub fn serialize_archetype(&self) -> Result<Vec<u8>, EncodeError>

Serializes the entire World state using a direct memory layout strategy.

This method is highly unsafe as it reads raw component memory.

pub fn deserialize_archetype( &mut self, data: &[u8], ) -> Result<(), DeserializeArchetypeError>

Deserializes and completely replaces the World state from a memory layout.

This method is highly unsafe as it writes raw bytes into component vectors.

Trait Implementations§

§

impl Default for World

§

fn default() -> World

Creates a new, empty World via World::new().

§

impl UiLayoutView for World

§

fn get_all_ui_entities(&self) -> Vec<EntityId>

Returns the IDs of all entities that should be considered for layout.
§

fn get_node(&self, entity: EntityId) -> Option<UiNode>

Returns the UI node definition for a given entity.
§

fn get_children(&self, entity: EntityId) -> Vec<EntityId>

Returns the children of a given entity.
§

fn has_parent(&self, entity: EntityId) -> bool

Returns true if the entity has a parent.
§

fn set_transform(&mut self, entity: EntityId, transform: UiTransform)

Writes the computed transform back to the entity.
§

fn viewport_size(&self) -> (u32, u32)

The available layout viewport in physical pixels (width, height). Read more

Auto Trait Implementations§

§

impl !Freeze for World

§

impl !RefUnwindSafe for World

§

impl Send for World

§

impl Sync for World

§

impl Unpin for World

§

impl UnsafeUnpin for World

§

impl !UnwindSafe for World

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<T> AppLifecycle for T
where T: ?Sized,

§

fn on_start(&mut self, ctx: &mut dyn AppContext)

Called once after the backend is up but before the first update. Apps install their theme / fonts here.
§

fn on_exit(&mut self)

Called once when the window is closing. Persist state here.
§

impl<T> AsAny for T
where T: Any,

§

fn as_any(&self) -> &(dyn Any + 'static)

Returns a reference to the inner value as &dyn Any.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
§

impl<T> Downcast<T> for T

§

fn downcast(&self) -> &T

§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> Downcast for T
where T: Any,

§

fn into_any(self: Box<T>) -> Box<dyn Any>

Converts Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>, which can then be downcast into Box<dyn ConcreteType> where ConcreteType implements Trait.
§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Converts Rc<Trait> (where Trait: Downcast) to Rc<Any>, which can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
§

fn as_any(&self) -> &(dyn Any + 'static)

Converts &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Converts &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
§

impl<T> DowncastSend for T
where T: Any + Send,

§

fn into_any_send(self: Box<T>) -> Box<dyn Any + Send>

Converts Box<Trait> (where Trait: DowncastSend) to Box<dyn Any + Send>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

§

fn into_any_sync(self: Box<T>) -> Box<dyn Any + Send + Sync>

Converts Box<Trait> (where Trait: DowncastSync) to Box<dyn Any + Send + Sync>, which can then be downcast into Box<ConcreteType> where ConcreteType implements Trait.
§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Converts Arc<Trait> (where Trait: DowncastSync) to Arc<Any>, which can then be downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<S> FromSample<S> for S

§

fn from_sample_(s: S) -> S

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

§

fn into_sample(self) -> T

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
§

impl<T, S> SimdFrom<T, S> for T
where S: Simd,

§

fn simd_from(value: T, _simd: S) -> T

§

impl<F, T, S> SimdInto<T, S> for F
where T: SimdFrom<F, S>, S: Simd,

§

fn simd_into(self, simd: S) -> T

§

impl<SS, SP> SupersetOf<SS> for SP
where SS: SubsetOf<SP>,

§

fn to_subset(&self) -> Option<SS>

The inverse inclusion map: attempts to construct self from the equivalent element of its superset. Read more
§

fn is_in_subset(&self) -> bool

Checks if self is actually part of its subset T (and can be converted to it).
§

fn to_subset_unchecked(&self) -> SS

Use with care! Same as self.to_subset but without any property checks. Always succeeds.
§

fn from_subset(element: &SS) -> SP

The inclusion map: converts self to the equivalent element of its superset.
§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

§

fn to_sample_(self) -> U

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> Upcast<T> for T

§

fn upcast(&self) -> Option<&T>

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,

§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

§

impl<T> WasmNotSend for T
where T: Send,

§

impl<T> WasmNotSendSync for T
where T: WasmNotSend + WasmNotSync,

§

impl<T> WasmNotSync for T
where T: Sync,