pub struct World { /* private fields */ }Expand description
Sparse typed storage with generational entities and checked component borrows.
RefCell deliberately makes World !Sync. Parallel mutation should use separate worlds or explicit synchronization around the whole world.
Implementations§
Source§impl World
impl World
pub fn new() -> Self
pub fn len(&self) -> usize
pub fn is_empty(&self) -> bool
Sourcepub fn prepare_entities(&mut self, capacity: usize) -> Result<(), SpawnError>
pub fn prepare_entities(&mut self, capacity: usize) -> Result<(), SpawnError>
Prepares at least capacity total sparse entity slots and free-list entries.
This is a monotonic index budget, not an additional/live entity count.
Retired slots still occupy indices. It never creates entities, consumes
free slots or shrinks buffers. Ordinary spawn ignores this budget and
retains its existing growth behavior. Allocator rounding does not enlarge
the logical budget returned by Self::prepared_entity_capacity.
Returns SpawnError::IdentityCapacity for unrepresentable slot counts,
or SpawnError::AllocationFailed if a reservation fails. On error the
logical budget, identities and contents are unchanged, but an earlier
successful reservation may have enlarged a buffer. Allocator panics/aborts
are not caught. See Self::try_spawn_batch for a complete wave recipe.
use ferravex_ecs::{SpawnError, World};
let mut world = World::new();
world.prepare_entities(16)?;
world.prepare_entities(4)?; // Never shrinks the explicit budget.
assert_eq!(world.prepared_entity_capacity(), 16);
assert!(world.is_empty());Sourcepub fn prepared_entity_capacity(&self) -> usize
pub fn prepared_entity_capacity(&self) -> usize
Explicit sparse entity-slot budget; initially zero, unaffected by ordinary spawn.
See Self::prepare_entities for an executable example.
Sourcepub fn prepare_component<T: 'static>(
&mut self,
capacity: usize,
) -> Result<(), SpawnError>
pub fn prepare_component<T: 'static>( &mut self, capacity: usize, ) -> Result<(), SpawnError>
Registers T and prepares at least capacity sparse component slots.
Every selected entity index must fit, even when few entities contain T.
No component values are constructed, replaced or dropped. Preparation is
monotonic and independent of entity preparation. Ordinary insert/spawn may
grow storage but do not increase its explicit prepared budget.
Identity/reservation errors have the same meaning as Self::prepare_entities.
On a reported error, component values and the logical budget are unchanged;
map capacity may grow. New storage is inserted only after its vector is
reserved. Its Box allocation uses the ordinary allocator and may panic or
abort rather than returning an error. No arbitrary allocation guarantee is made.
use ferravex_ecs::{SpawnError, World};
let mut world = World::new();
world.prepare_component::<String>(16)?; // No String values are created.
world.prepare_component::<String>(4)?;
assert_eq!(world.prepared_component_capacity::<String>(), 16);
assert_eq!(world.prepared_component_capacity::<u8>(), 0);
assert!(world.is_empty());Sourcepub fn prepared_component_capacity<T: 'static>(&self) -> usize
pub fn prepared_component_capacity<T: 'static>(&self) -> usize
Explicit sparse budget for T; zero for unprepared/absent types.
See Self::prepare_component for an executable example.
Sourcepub fn try_spawn_batch<B: Bundle, const N: usize>(
&mut self,
bundles: [B; N],
output: &mut [Entity],
) -> Result<usize, (SpawnError, [B; N])>
pub fn try_spawn_batch<B: Bundle, const N: usize>( &mut self, bundles: [B; N], output: &mut [Entity], ) -> Result<usize, (SpawnError, [B; N])>
Spawns an owned fixed array in caller order, within explicitly prepared storage.
Writes exactly N handles into the output prefix and returns Ok(N).
Free slots are popped in the same LIFO order as ordinary spawn, followed
by new indices. Preflight inspects only those selected free slots, so an
unselected high index does not require component preparation for that index.
Explicit entity and component budgets must cover the highest selected
index plus one. Allocation rounding and ordinary storage growth do not
increase these budgets. See Self::prepare_entities and
Self::prepare_component.
§Errors and ownership
Checks, in order: duplicate component types (also for N == 0), output
length, identity arithmetic, entity budget, then component budgets in
bundle order. An empty valid batch needs no preparation and returns zero.
Every reported error returns (error, original_bundles) without moving
values out of that array, dropping components, registering storage,
changing entities/free-list order, or writing any output. The caller owns
the returned values and decides whether to retry or drop them. Unused
output is unchanged on both success and error; its initial handles need
not be valid entities.
§Allocation and panic limits
After successful preflight, the ECS does not grow entity, free-list, map or component buffers, allocate storage boxes or allocate metadata. Input construction happens before this call and can allocate/panic. This is an all-or-none guarantee for reported errors, not a panic transaction: panics/aborts are not caught or rolled back, and unconsumed owned values are dropped during unwinding. User construction/Drop is not infallible. Stack space is proportional to the caller-selected array size.
A first-party wave/projectile recipe: invoke the spawn step only on an
executed simulation tick, and emit feedback only after Ok admission.
Restart despawns existing entities while retaining prepared buffers.
use ferravex_ecs::{Entity, SpawnError, World};
struct Position(f32);
struct Bullet { velocity: f32, remaining: f32 }
let mut world = World::new();
world.prepare_entities(32)?;
world.prepare_component::<Position>(32)?;
world.prepare_component::<Bullet>(32)?;
let mut handles = [Entity::from_bits(0); 4];
let projectiles = std::array::from_fn::<_, 3, _>(|i| (
Position(i as f32), Bullet { velocity: 8.0, remaining: 1.0 },
));
let accepted = world.try_spawn_batch(projectiles, &mut handles)
.map_err(|(error, _owned_projectiles)| error)?;
assert_eq!(accepted, 3); // Now emit three accepted-shot feedback events.
let fixed_dt = 0.25;
for (mut position, mut bullet) in world.query::<(&mut Position, &mut Bullet)>() {
position.0 += bullet.velocity * fixed_dt;
bullet.remaining -= fixed_dt;
}
assert_eq!(world.get::<&Position>(handles[0]).unwrap().0, 2.0);
assert_eq!(world.get::<&Bullet>(handles[0]).unwrap().remaining, 0.75);
let old = handles[0];
world.despawn_many(&handles[..accepted]).unwrap();
world.try_spawn_batch([(Position(10.0), Bullet { velocity: 4.0, remaining: 2.0 })],
&mut handles).map_err(|(error, _)| error)?;
assert!(!world.contains(old));
assert_eq!(world.len(), 1);Sourcepub fn plan_duplication<B: CloneBundle, const N: usize>(
&self,
sources: [Entity; N],
) -> Result<DuplicationPlan<B, N>, DuplicationError>
pub fn plan_duplication<B: CloneBundle, const N: usize>( &self, sources: [Entity; N], ) -> Result<DuplicationPlan<B, N>, DuplicationError>
Captures selected Clone component types for a small set of source entities.
B is an owned tuple of zero to eight explicitly chosen component types.
Nothing else is copied, including transient handles, unless selected.
Entity identity is never copied automatically; an explicitly stored Entity
component is just a value. Embedded entity references retain their old
values until the host explicitly remaps them using the returned spawn map.
No reflection, serialization or hierarchy traversal is performed.
Checks duplicate component types (even for N == 0), all source identities
in order, then repeated sources, then reads in source/tuple order. Every
selected component is shared-borrowed before the first Clone call. Missing
components and outstanding mutable borrows are errors, never omissions.
Any reported error releases partial guards, calls no component Clone,
changes no ECS storage/identities and spawns nothing. Shared guards and
mutable guards of unselected components do not prevent capture.
The returned plan owns a snapshot and releases all read guards. It can
outlive source edits/despawns. No ECS metadata heap allocation is needed;
fixed-array stack space scales with N and B. User Clone can allocate,
mutate shared interior state or panic; no rollback of user effects or
promise about panicking Clone/Drop is made. Successful earlier clones
are dropped on unwind. Spawn capacity is checked later by the plan.
Handles remain world-local; a foreign matching identity cannot be detected.
This actor-template recipe omits a transient audio handle, explicitly remaps a partner reference, and despawns the duplicates for reset. Run authoring at a structural-edit boundary after query guards are released; derive gameplay feedback only from accepted spawns.
use ferravex_ecs::World;
#[derive(Clone)] struct Position(f32);
#[derive(Clone)] struct Health(u32);
#[derive(Clone)] struct Partner(ferravex_ecs::Entity);
struct AudioVoice; // Transient, deliberately not Clone or selected.
let mut world = World::new();
let first = world.spawn((Position(1.0), Health(10), AudioVoice));
let second = world.spawn((Position(3.0), Health(20), AudioVoice));
world.insert(first, (Partner(second),))?;
world.insert(second, (Partner(first),))?;
world.prepare_entities(4)?;
world.prepare_component::<Position>(4)?;
world.prepare_component::<Health>(4)?;
world.prepare_component::<Partner>(4)?;
let plan = world.plan_duplication::<(Position, Health, Partner), 2>([first, second])?;
let map = plan.try_spawn(&mut world).map_err(|(error, _plan)| error)?;
assert_eq!(map.map(|(old, _)| old), [first, second]);
let copies = map.map(|(_, new)| new);
for (old, new) in map {
assert_ne!(old, new);
assert!(!world.has::<AudioVoice>(new));
let mut partner = world.get::<&mut Partner>(new)?;
let replacement = map.iter().find(|(source, _)| *source == partner.0).unwrap().1;
partner.0 = replacement; // Explicit host remap, after all copies exist.
}
world.get::<&mut Position>(copies[0])?.0 += 5.0;
assert_eq!(world.get::<&Position>(first)?.0, 1.0);
assert_eq!(world.get::<&Position>(copies[0])?.0, 6.0);
assert_eq!(world.get::<&Health>(copies[1])?.0, 20);
assert_eq!(world.get::<&Partner>(copies[0])?.0, copies[1]);
assert_eq!(world.get::<&Partner>(first)?.0, second);
world.despawn_many(&copies)?; // Prepared buffers survive reset.
let again = world.plan_duplication::<(Position, Health), 1>([first])?
.try_spawn(&mut world).map_err(|(error, _)| error)?;
assert!(copies.iter().all(|old| !world.contains(*old)));
assert_eq!(world.get::<&Health>(again[0].1)?.0, 10);pub fn contains(&self, entity: Entity) -> bool
Sourcepub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity
pub fn spawn<B: Bundle>(&mut self, bundle: B) -> Entity
Spawns one entity containing zero to eight components. See Bundle
for a complete five-component actor recipe.
Panics if a bundle repeats a component type; no entity is allocated in that case.
pub fn try_spawn<B: Bundle>(&mut self, bundle: B) -> Result<Entity, Error>
Sourcepub fn despawn(&mut self, entity: Entity) -> Result<(), Error>
pub fn despawn(&mut self, entity: Entity) -> Result<(), Error>
Drops every component and invalidates the handle before reusing its slot.
Sourcepub fn despawn_many(&mut self, entities: &[Entity]) -> Result<usize, Error>
pub fn despawn_many(&mut self, entities: &[Entity]) -> Result<usize, Error>
Despawns a batch after validating every handle, returning the number removed.
Repeated live handles are accepted and removed exactly once, in order of
first occurrence. An empty slice returns Ok(0). Successful removal has
the same component cleanup and slot-reuse behavior as World::despawn.
The order in which different component types are dropped is unspecified.
Validation and duplicate handling use constant extra space, perform no allocation and do not scan unrelated entities. Removal may grow the world’s existing free-slot list, just like individual despawns.
§Errors
The first stale or invalid handle in input order returns
Error::NoSuchEntity before any mutation or component drops. Every
handle must be live at entry, including repeats. On Err, all entities,
components, generations and slot-reuse order remain unchanged. Handles
are world-local; matching identities from another world cannot be detected.
§Panics
Component destructors may panic. Such a panic is not rolled back: earlier removals remain applied, the current entity is invalidated and its slot retired, and unprocessed entities remain live, as with sequential despawns.
use ferravex_ecs::{Error, World};
let mut world = World::new();
let first = world.spawn((10_i32,));
let second = world.spawn((20_i32,));
let stale = world.spawn(());
world.despawn(stale)?;
assert_eq!(world.despawn_many(&[first, stale]), Err(Error::NoSuchEntity(stale)));
assert_eq!(*world.get::<&i32>(first)?, 10);
assert_eq!(world.despawn_many(&[second, first, second])?, 2);
assert!(world.is_empty());Structural removal requires exclusive access, including when guards came
from World::get_many:
use ferravex_ecs::World;
let mut world = World::new();
let entity = world.spawn((42_i32,));
let guards = world.get_many::<&mut i32, 1>([entity]).unwrap();
world.despawn_many(&[entity]).unwrap();
drop(guards);Sourcepub fn insert<B: Bundle>(
&mut self,
entity: Entity,
bundle: B,
) -> Result<(), Error>
pub fn insert<B: Bundle>( &mut self, entity: Entity, bundle: B, ) -> Result<(), Error>
Inserts or replaces a bundle’s components. Other components remain unchanged. Invalid identities and duplicate bundle types are rejected before any writes.
pub fn remove<T: 'static>(&mut self, entity: Entity) -> Result<T, Error>
pub fn has<T: 'static>(&self, entity: Entity) -> bool
Sourcepub fn get<A: Access>(&self, entity: Entity) -> Result<A::Item<'_>, Error>
pub fn get<A: Access>(&self, entity: Entity) -> Result<A::Item<'_>, Error>
Reads or mutates a typed component through an explicit access type.
Use get::<&T> or get::<&mut T>; returned guards enforce runtime aliasing.
Option<&T> and Option<&mut T> return None for an absent component.
Invalid entities and conflicting borrows still return errors.
use ferravex_ecs::{Error, World};
let mut world = World::new();
let entity = world.spawn(());
assert!(world.get::<Option<&i32>>(entity)?.is_none());
world.insert(entity, (10_i32,))?;
let mut health = world.get::<Option<&mut i32>>(entity)?.unwrap();
*health += 1;
assert!(matches!(world.get::<Option<&i32>>(entity), Err(Error::BorrowConflict(_))));
drop(health);
assert_eq!(*world.get::<Option<&i32>>(entity)?.unwrap(), 11);pub fn get_mut<T: 'static>( &self, entity: Entity, ) -> Result<RefMut<'_, T>, Error>
Sourcepub fn get_many<Q: Query, const N: usize>(
&self,
entities: [Entity; N],
) -> Result<[Q::Item<'_>; N], Error>
pub fn get_many<Q: Query, const N: usize>( &self, entities: [Entity; N], ) -> Result<[Q::Item<'_>; N], Error>
Borrows a fixed set of entities in the supplied order, without scanning the world.
Q accepts the same single access or tuple of up to eight accesses as
World::query. Returned guards borrow the world, not the input array.
This performs no heap allocation and uses stack space proportional to N.
An empty array succeeds if the query signature is valid.
§Errors
An overlapping mutable access within Q returns Error::ConflictingQuery.
Next, all handles are checked in input order: a despawned, reused or invalid
handle returns Error::NoSuchEntity before any components are borrowed.
Handles remain world-local; identities from another world cannot be detected.
Components are then borrowed in entity and tuple order. A missing required
component returns Error::MissingComponent; a missing optional component
yields None. Incompatible outstanding guards or a repeated entity with
mutable access to a present component return Error::BorrowConflict.
Repeated entities with absent optional mutable components are allowed.
Repeated entities are allowed for shared access and identity-only queries.
Any error releases every guard acquired by this call, including partial
tuple borrows. No components are changed and no partial result is returned.
use ferravex_ecs::{Error, World};
let mut world = World::new();
let donor = world.spawn((10_i32,));
let receiver = world.spawn((2_i32,));
{
let [mut from, mut to] = world.get_many::<&mut i32, 2>([donor, receiver])?;
*from -= 3;
*to += 3;
}
assert_eq!(*world.get::<&i32>(receiver)?, 5);
assert!(matches!(
world.get_many::<&mut i32, 2>([donor, donor]),
Err(Error::BorrowConflict(_))
));
// A tuple query can also retrieve several components of one known entity.
let [(id, health)] = world.get_many::<(ferravex_ecs::Entity, &i32), 1>([donor])?;
assert_eq!(id, donor);
assert_eq!(*health, 7);Optional accesses preserve the requested order and borrow only components that are present:
use ferravex_ecs::{Entity, Error, World};
let mut world = World::new();
let actor = world.spawn((10_i32,));
let scenery = world.spawn(());
let [(scenery_id, absent), (actor_id, health)] =
world.get_many::<(Entity, Option<&mut i32>), 2>([scenery, actor])?;
assert_eq!((scenery_id, actor_id), (scenery, actor));
assert!(absent.is_none());
*health.unwrap() += 1;
assert_eq!(*world.get::<&i32>(actor)?, 11);Sourcepub fn query<Q: Query>(&self) -> QueryBorrow<'_, Q>
pub fn query<Q: Query>(&self) -> QueryBorrow<'_, Q>
Queries up to eight access types, counting each Entity entry.
Repeated shared access is valid; any repeated mutable access is rejected.
Option<&T> yields Option<Ref<'_, T>>; Option<&mut T> yields
Option<RefMut<'_, T>>. Only required accesses filter entities: an
optional-only query visits every live entity, including componentless ones.
A missing optional component yields None, but an incompatible borrow of
a present component still fails. Use QueryBorrow::try_iter for fallible
iteration; ordinary iteration panics on borrow conflicts.
Optional access participates in signature validation even if the component
is absent everywhere. For example, (&T, Option<&mut T>) is rejected by
World::try_query with Error::ConflictingQuery.
This fixed-step recipe updates moving actors while retaining stationary scenery and optionally recording presentation changes:
use ferravex_ecs::{Entity, Error, World};
struct Position(f32);
struct Velocity(f32);
struct Presentation { updates: u32 }
let mut world = World::new();
let actor = world.spawn((Position(1.0), Velocity(2.0), Presentation { updates: 0 }));
let scenery = world.spawn((Position(5.0),));
world.spawn((Velocity(99.0),)); // No Position: excluded by the required access.
let mut visited = 0;
let fixed_dt = 0.5;
for row in world.query::<(Entity, &mut Position, Option<&Velocity>, Option<&mut Presentation>)>().try_iter() {
let (entity, mut position, velocity, presentation) = row?;
if let Some(velocity) = velocity {
position.0 += velocity.0 * fixed_dt;
if let Some(mut presentation) = presentation {
presentation.updates += 1;
}
}
assert!(entity == actor || entity == scenery);
visited += 1;
}
assert_eq!(visited, 2);
assert_eq!(world.get::<&Position>(actor)?.0, 2.0);
assert_eq!(world.get::<&Position>(scenery)?.0, 5.0);
assert_eq!(world.get::<&Presentation>(actor)?.updates, 1);pub fn try_query<Q: Query>(&self) -> Result<QueryBorrow<'_, Q>, Error>
Sourcepub fn query_filtered<Q: Query, F: QueryFilter>(&self) -> QueryBorrow<'_, Q, F>
pub fn query_filtered<Q: Query, F: QueryFilter>(&self) -> QueryBorrow<'_, Q, F>
Queries fetched accesses Q subject to structural component filter F.
Filters inspect presence only: they never borrow component values or add
accesses to Q’s alias checks. Both the filter and all required accesses
must match before any value is borrowed. With, Without, All,
Any and Not compose through tuples of up to four clauses per group.
() accepts every live entity; Any<()> accepts none. Nest groups for
larger expressions. There is no runtime filter storage or allocation;
expression size and nesting are fixed by the caller’s concrete type.
Live slots retain their normal order. Invalid fetched signatures panic;
use World::try_query_filtered to report them instead. As with
World::query, QueryBorrow::try_iter reports fetched borrow conflicts
and continues, while ordinary iteration panics on them. Contradictory
filters simply match nothing and never excuse an invalid Q signature.
This fixed-tick recipe moves active actors or projectiles, excludes frozen entities, and optionally records presentation updates. Holding a mutable marker guard does not interfere with filtering:
use ferravex_ecs::{All, Any, Entity, Error, Not, With, Without, World};
struct Position(f32);
struct Velocity(f32);
struct Presentation(u32);
struct Active;
struct Projectile;
struct Frozen;
let mut world = World::new();
let actor = world.spawn((Position(1.0), Velocity(2.0), Active, Presentation(0)));
let projectile = world.spawn((Position(4.0), Projectile));
let frozen = world.spawn((Position(9.0), Active, Frozen));
world.spawn((Position(20.0),)); // Neither Active nor Projectile.
let marker = world.get::<&mut Active>(actor)?;
type Moving = All<(Any<(With<Active>, With<Projectile>)>, Without<Frozen>)>;
let fixed_dt = 0.5; // Call once per executed simulation tick.
let mut visited = 0;
for row in world.query_filtered::<
(Entity, &mut Position, Option<&Velocity>, Option<&mut Presentation>), Moving
>().try_iter() {
let (entity, mut position, velocity, presentation) = row?;
if let Some(velocity) = velocity { position.0 += velocity.0 * fixed_dt; }
if let Some(mut presentation) = presentation { presentation.0 += 1; }
assert!(entity == actor || entity == projectile);
visited += 1;
}
assert_eq!(visited, 2);
assert_eq!(world.get::<&Position>(actor)?.0, 2.0);
assert_eq!(world.get::<&Presentation>(actor)?.0, 1);
assert_eq!(world.get::<&Position>(frozen)?.0, 9.0);
assert_eq!(world.query_filtered::<Entity, Not<Moving>>().iter().count(), 2);
drop(marker);Sourcepub fn try_query_filtered<Q: Query, F: QueryFilter>(
&self,
) -> Result<QueryBorrow<'_, Q, F>, Error>
pub fn try_query_filtered<Q: Query, F: QueryFilter>( &self, ) -> Result<QueryBorrow<'_, Q, F>, Error>
Validates fetched access aliases before returning a filtered query.
Presence filters introduce no borrow conflicts. Only Q is validated;
dynamic borrow errors arise when iterating matching entities. Validation
still runs on an empty world or a filter that excludes every entity.
use ferravex_ecs::{Any, Error, With, World};
let world = World::new();
assert!(matches!(
world.try_query_filtered::<(&mut i32, Option<&i32>), Any<()>>(),
Err(Error::ConflictingQuery(_))
));
assert_eq!(world.try_query_filtered::<&mut i32, With<i32>>()?.iter().count(), 0);