hyperion/world.rs
1use crate::component_storage::{Component, ComponentStorage, ComponentStorageTrait};
2use crate::entity::{Entity, EntityAllocator};
3use crate::resources::{ResourceHandle, ResourceRegistry};
4use std::any::TypeId;
5use std::collections::HashMap;
6
7/// The ECS world, managing entities and their components.
8///
9/// # Fields
10/// - `entity_allocator`: Allocator tracking entity ids and generations.
11/// - `storages`: Type-erased component storages keyed by their `TypeId`.
12/// - `resource_registry`: Type-erased registry for arbitrary resources (including unique ones).
13///
14/// # Safety
15/// - All public APIs enforce Rust's borrowing rules across component storages.
16/// - Type erasure is limited to internal maps; downcasting is guarded by `TypeId`
17/// checks in accessor methods to prevent type confusion.
18pub struct World {
19 pub(crate) entity_allocator: EntityAllocator,
20 storages: HashMap<TypeId, Box<dyn ComponentStorageTrait>>,
21 resource_registry: ResourceRegistry,
22}
23
24impl World {
25 /// Creates a new empty world.
26 ///
27 /// # Returns
28 /// - `World`: A new world with no entities, components, or resources.
29 pub fn new() -> Self {
30 Self {
31 entity_allocator: EntityAllocator::default(),
32 storages: HashMap::new(),
33 resource_registry: ResourceRegistry::new(),
34 }
35 }
36
37 /// Purges the world: removes all components and resets the entity allocator.
38 /// After purge, no entities are alive and the next created entity will start
39 /// from id 0 with generation 0.
40 ///
41 /// # Effects
42 /// - Clears all component storages and resources.
43 /// - Resets the entity allocator (no free ids, no generations).
44 ///
45 /// # Notes
46 /// - Any previously held `Entity` values are invalid after purge.
47 pub fn purge(&mut self) {
48 self.storages.clear();
49 self.entity_allocator = EntityAllocator::default();
50 self.resource_registry = ResourceRegistry::new();
51 }
52
53 /// Gets the current number of alive entities.
54 ///
55 /// # Returns
56 /// - `usize`: Count of currently alive entities.
57 pub fn entity_count(&self) -> usize {
58 self.entity_allocator.generations.len() - self.entity_allocator.free_ids.len()
59 }
60
61 /// Returns the number of IDs ready to be recycled.
62 ///
63 /// # Returns
64 /// - `usize`: Count of free IDs currently available for reuse.
65 pub fn free_id_count(&self) -> usize {
66 self.entity_allocator.free_ids.len()
67 }
68
69 /// Creates a new entity.
70 ///
71 /// # Returns
72 /// - `Entity`: The newly created entity identifier.
73 pub fn create_entity(&mut self) -> Entity {
74 self.entity_allocator.create()
75 }
76
77 /// Creates a new entity and adds the provided component to it.
78 ///
79 /// # Type Parameters
80 /// - `T`: The component type to add to the new entity.
81 ///
82 /// # Parameters
83 /// - `component`: The component instance to attach to the newly created entity.
84 ///
85 /// # Returns
86 /// - `Entity`: The newly created entity.
87 pub fn create_entity_and_add_component<T: Component>(&mut self, component: T) -> Entity {
88 let entity = self.create_entity();
89 self.add_component(entity, component);
90 return entity;
91 }
92
93 /// Destroys an entity, marking it dead and removing all components associated with it.
94 ///
95 /// # Parameters
96 /// - `entity`: The entity to destroy. Safe to call multiple times; additional calls are no-ops.
97 pub fn destroy_entity(&mut self, entity: Entity) {
98 self.entity_allocator.destroy(entity);
99
100 for storage in self.storages.values_mut() {
101 storage.remove_entity(entity);
102 }
103 }
104
105 /// Adds a component of type `T` to an entity, creating storage if necessary.
106 ///
107 /// # Type Parameters
108 /// - `T`: The component type to insert. Must implement `Component` and be `'static`.
109 ///
110 /// # Parameters
111 /// - `entity`: The target entity to receive the component.
112 /// - `component`: The component instance to add (replaces existing component of `T` on this entity).
113 ///
114 /// # Effects
115 /// - Creates the component storage for `T` if it does not yet exist.
116 /// - If the entity already has a `T`, it is replaced with the new value.
117 pub fn add_component<T: Component>(&mut self, entity: Entity, component: T) {
118 let storage = self.get_or_create_storage::<T>();
119 storage.insert(entity, component);
120 }
121
122 /// Checks whether an entity has a component of type `T`.
123 ///
124 /// # Type Parameters
125 /// - `T`: The component type to check for.
126 ///
127 /// # Parameters
128 /// - `entity`: The entity to query.
129 ///
130 /// # Returns
131 /// - `bool`: `true` if the entity currently has a `T` component; otherwise `false`.
132 pub fn entity_has_component<T: Component>(&self, entity: Entity) -> bool {
133 self.get_storage::<T>()
134 .map(|storage| storage.has(entity))
135 .unwrap_or(false)
136 }
137
138 /// Retrieves an immutable reference to a component of type `T` for an `entity`.
139 ///
140 /// # Type Parameters
141 /// - `T`: The component type to retrieve.
142 ///
143 /// # Parameters
144 /// - `entity`: The entity whose component is being requested.
145 ///
146 /// # Returns
147 /// - `Option<&T>`: `Some(&T)` if the entity currently has a `T` component; `None` otherwise.
148 pub fn get_component<T: Component>(&self, entity: Entity) -> Option<&T> {
149 self.get_storage::<T>()
150 .and_then(|storage| storage.get(entity))
151 }
152
153 /// Retrieves a mutable reference to a component of type `T` for an `entity`.
154 ///
155 /// # Type Parameters
156 /// - `T`: The component type to retrieve mutably.
157 ///
158 /// # Parameters
159 /// - `entity`: The entity whose component is being requested mutably.
160 ///
161 /// # Returns
162 /// - `Option<&mut T>`: `Some(&mut T)` if the entity currently has a `T` component; `None` otherwise.
163 ///
164 /// # Notes
165 /// - Borrowing rules apply across all storages; this method requires `&mut self` to ensure
166 /// mutable aliasing rules are respected.
167 pub fn get_component_mut<T: Component>(&mut self, entity: Entity) -> Option<&mut T> {
168 self.get_storage_mut::<T>()
169 .and_then(|storage| storage.get_mut(entity))
170 }
171
172 /// Gets an immutable reference to the concrete storage for components of type `T`.
173 ///
174 /// # Type Parameters
175 /// - `T`: The component type whose storage is requested.
176 ///
177 /// # Returns
178 /// - `Option<&ComponentStorage<T>>`: `Some(&ComponentStorage<T>)` if a storage for `T` exists; `None` otherwise.
179 ///
180 /// # Safety
181 /// - Internally relies on type-erased downcasting guarded by `TypeId`. The downcast is only
182 /// attempted after the `TypeId` lookup succeeds, ensuring the cast is sound.
183 fn get_storage<T: Component>(&self) -> Option<&ComponentStorage<T>> {
184 self.storages
185 .get(&TypeId::of::<T>())
186 .and_then(|boxed| boxed.as_any().downcast_ref::<ComponentStorage<T>>())
187 }
188
189 /// Gets a mutable reference to the concrete storage for components of type `T`.
190 ///
191 /// # Type Parameters
192 /// - `T`: The component type whose storage is requested mutably.
193 ///
194 /// # Returns
195 /// - `Option<&mut ComponentStorage<T>>`: `Some(&mut ComponentStorage<T>)` if a storage for `T` exists; `None` otherwise.
196 ///
197 /// # Safety
198 /// - Uses type-erased downcasting guarded by `TypeId` checks to ensure soundness.
199 /// - Requires `&mut self` to uphold Rust's aliasing rules across all component storages.
200 pub(crate) fn get_storage_mut<T: Component>(&mut self) -> Option<&mut ComponentStorage<T>> {
201 self.storages
202 .get_mut(&TypeId::of::<T>())
203 .and_then(|boxed| boxed.as_any_mut().downcast_mut::<ComponentStorage<T>>())
204 }
205
206 /// Returns all components of type `T` paired with their owning entities.
207 ///
208 /// # Type Parameters
209 /// - `T`: The component type to iterate over.
210 ///
211 /// # Returns
212 /// - `Vec<(Entity, &T)>`: A vector of `(Entity, &T)` pairs for every `T` stored.
213 ///
214 /// # Ordering
215 /// - Follows the dense storage order of `ComponentStorage<T>`, which is generally insertion
216 /// order preserved via swap-remove when deletions occur.
217 pub fn get_all_components_with_entities<T: Component>(&self) -> Vec<(Entity, &T)> {
218 if let Some(storage) = self.get_storage::<T>() {
219 storage.iter_with_entities().collect()
220 } else {
221 Vec::new()
222 }
223 }
224
225 /// Returns all components of type `T` mutably paired with their owning entities.
226 ///
227 /// # Type Parameters
228 /// - `T`: The component type to iterate over mutably.
229 ///
230 /// # Returns
231 /// - `Vec<(Entity, &mut T)>`: A vector of `(Entity, &mut T)` pairs for every `T` stored.
232 ///
233 /// # Ordering
234 /// - Follows the dense storage order of `ComponentStorage<T>`;
235 ///
236 /// # Notes
237 /// - Requires `&mut self` to guarantee sound mutable access to components.
238 pub fn get_all_components_with_entities_mut<T: Component>(&mut self) -> Vec<(Entity, &mut T)> {
239 if let Some(storage) = self.get_storage_mut::<T>() {
240 storage.iter_with_entities_mut().collect()
241 } else {
242 Vec::new()
243 }
244 }
245
246 /// Returns the list of entities that have component `T`.
247 ///
248 /// # Type Parameters
249 /// - `T`: The component type to search for.
250 ///
251 /// # Returns
252 /// - `Vec<Entity>`: All entities that currently have a `T` component.
253 pub fn get_entities_for<T: Component>(&self) -> Vec<Entity> {
254 if let Some(storage) = self.get_storage::<T>() {
255 storage
256 .iter_with_entities()
257 .map(|(entity, _)| entity)
258 .collect()
259 } else {
260 Vec::new()
261 }
262 }
263
264 /// Returns entities that have both component types `T1` and `T2`.
265 ///
266 /// # Type Parameters
267 /// - `T1`: First component type.
268 /// - `T2`: Second component type.
269 ///
270 /// # Returns
271 /// - `Vec<Entity>`: Entities that contain both `T1` and `T2`.
272 pub fn get_entities_with_2<T1: Component, T2: Component>(&self) -> Vec<Entity> {
273 let storage1 = self.get_storage::<T1>();
274 let storage2 = self.get_storage::<T2>();
275
276 match (storage1, storage2) {
277 (Some(s1), Some(s2)) => s1
278 .iter_with_entities()
279 .filter_map(
280 |(entity, _)| {
281 if s2.has(entity) { Some(entity) } else { None }
282 },
283 )
284 .collect(),
285 _ => Vec::new(),
286 }
287 }
288
289 /// Returns entities that have component types `T1`, `T2`, and `T3`.
290 ///
291 /// # Type Parameters
292 /// - `T1`: First component type.
293 /// - `T2`: Second component type.
294 /// - `T3`: Third component type.
295 ///
296 /// # Returns
297 /// - `Vec<Entity>`: Entities that contain `T1`, `T2`, and `T3`.
298 pub fn get_entities_with_3<T1: Component, T2: Component, T3: Component>(&self) -> Vec<Entity> {
299 let storage1 = self.get_storage::<T1>();
300 let storage2 = self.get_storage::<T2>();
301 let storage3 = self.get_storage::<T3>();
302
303 match (storage1, storage2, storage3) {
304 (Some(s1), Some(s2), Some(s3)) => s1
305 .iter_with_entities()
306 .filter_map(|(entity, _)| {
307 if s2.has(entity) && s3.has(entity) {
308 Some(entity)
309 } else {
310 None
311 }
312 })
313 .collect(),
314 _ => Vec::new(),
315 }
316 }
317
318 /// Returns entities that have component types `T1`, `T2`, `T3`, and `T4`.
319 ///
320 /// # Type Parameters
321 /// - `T1`: First component type.
322 /// - `T2`: Second component type.
323 /// - `T3`: Third component type.
324 /// - `T4`: Fourth component type.
325 ///
326 /// # Returns
327 /// - `Vec<Entity>`: Entities that contain `T1`, `T2`, `T3`, and `T4`.
328 pub fn get_entities_with_4<T1: Component, T2: Component, T3: Component, T4: Component>(
329 &self,
330 ) -> Vec<Entity> {
331 let storage1 = self.get_storage::<T1>();
332 let storage2 = self.get_storage::<T2>();
333 let storage3 = self.get_storage::<T3>();
334 let storage4 = self.get_storage::<T4>();
335
336 match (storage1, storage2, storage3, storage4) {
337 (Some(s1), Some(s2), Some(s3), Some(s4)) => s1
338 .iter_with_entities()
339 .filter_map(|(entity, _)| {
340 if s2.has(entity) && s3.has(entity) && s4.has(entity) {
341 Some(entity)
342 } else {
343 None
344 }
345 })
346 .collect(),
347 _ => Vec::new(),
348 }
349 }
350
351 /// Returns entities that have component types `T1`, `T2`, `T3`, `T4`, and `T5`.
352 ///
353 /// # Type Parameters
354 /// - `T1`: First component type.
355 /// - `T2`: Second component type.
356 /// - `T3`: Third component type.
357 /// - `T4`: Fourth component type.
358 /// - `T5`: Fifth component type.
359 ///
360 /// # Returns
361 /// - `Vec<Entity>`: Entities that contain `T1`, `T2`, `T3`, `T4`, and `T5`.
362 pub fn get_entities_with_5<
363 T1: Component,
364 T2: Component,
365 T3: Component,
366 T4: Component,
367 T5: Component,
368 >(
369 &self,
370 ) -> Vec<Entity> {
371 let storage1 = self.get_storage::<T1>();
372 let storage2 = self.get_storage::<T2>();
373 let storage3 = self.get_storage::<T3>();
374 let storage4 = self.get_storage::<T4>();
375 let storage5 = self.get_storage::<T5>();
376
377 match (storage1, storage2, storage3, storage4, storage5) {
378 (Some(s1), Some(s2), Some(s3), Some(s4), Some(s5)) => s1
379 .iter_with_entities()
380 .filter_map(|(entity, _)| {
381 if s2.has(entity) && s3.has(entity) && s4.has(entity) && s5.has(entity) {
382 Some(entity)
383 } else {
384 None
385 }
386 })
387 .collect(),
388 _ => Vec::new(),
389 }
390 }
391
392 /// Returns entities with both components and their component references.
393 ///
394 /// # Type Parameters
395 /// - `T1`: First component type.
396 /// - `T2`: Second component type.
397 ///
398 /// # Returns
399 /// - `Vec<(Entity, &T1, &T2)>`: Tuples of the entity and references to both components.
400 ///
401 /// # Ordering
402 /// - The iteration order follows the dense storage of `T1`.
403 pub fn get_entities_and_components_with_2<T1: Component, T2: Component>(
404 &self,
405 ) -> Vec<(Entity, &T1, &T2)> {
406 let storage1 = self.get_storage::<T1>();
407 let storage2 = self.get_storage::<T2>();
408
409 match (storage1, storage2) {
410 (Some(s1), Some(s2)) => s1
411 .iter_with_entities()
412 .filter_map(|(entity, c1)| s2.get(entity).map(|c2| (entity, c1, c2)))
413 .collect(),
414 _ => Vec::new(),
415 }
416 }
417
418 /// Returns entities with components `T1`, `T2`, and `T3` and their references.
419 ///
420 /// # Type Parameters
421 /// - `T1`: First component type.
422 /// - `T2`: Second component type.
423 /// - `T3`: Third component type.
424 ///
425 /// # Returns
426 /// - `Vec<(Entity, &T1, &T2, &T3)>`: Tuples of the entity and three component references.
427 ///
428 /// # Ordering
429 /// - The iteration order follows the dense storage of `T1`.
430 pub fn get_entities_and_components_with_3<T1: Component, T2: Component, T3: Component>(
431 &self,
432 ) -> Vec<(Entity, &T1, &T2, &T3)> {
433 let storage1 = self.get_storage::<T1>();
434 let storage2 = self.get_storage::<T2>();
435 let storage3 = self.get_storage::<T3>();
436
437 match (storage1, storage2, storage3) {
438 (Some(s1), Some(s2), Some(s3)) => s1
439 .iter_with_entities()
440 .filter_map(|(entity, c1)| {
441 if let (Some(c2), Some(c3)) = (s2.get(entity), s3.get(entity)) {
442 Some((entity, c1, c2, c3))
443 } else {
444 None
445 }
446 })
447 .collect(),
448 _ => Vec::new(),
449 }
450 }
451
452 /// Returns entities with components `T1`, `T2`, `T3`, and `T4` and their references.
453 ///
454 /// # Type Parameters
455 /// - `T1`: First component type.
456 /// - `T2`: Second component type.
457 /// - `T3`: Third component type.
458 /// - `T4`: Fourth component type.
459 ///
460 /// # Returns
461 /// - `Vec<(Entity, &T1, &T2, &T3, &T4)>`: Tuples of the entity and four component references.
462 ///
463 /// # Ordering
464 /// - The iteration order follows the dense storage of `T1`.
465 pub fn get_entities_and_components_with_4<
466 T1: Component,
467 T2: Component,
468 T3: Component,
469 T4: Component,
470 >(
471 &self,
472 ) -> Vec<(Entity, &T1, &T2, &T3, &T4)> {
473 let storage1 = self.get_storage::<T1>();
474 let storage2 = self.get_storage::<T2>();
475 let storage3 = self.get_storage::<T3>();
476 let storage4 = self.get_storage::<T4>();
477
478 match (storage1, storage2, storage3, storage4) {
479 (Some(s1), Some(s2), Some(s3), Some(s4)) => s1
480 .iter_with_entities()
481 .filter_map(|(entity, c1)| {
482 if let (Some(c2), Some(c3), Some(c4)) =
483 (s2.get(entity), s3.get(entity), s4.get(entity))
484 {
485 Some((entity, c1, c2, c3, c4))
486 } else {
487 None
488 }
489 })
490 .collect(),
491 _ => Vec::new(),
492 }
493 }
494
495 /// Returns entities with components `T1`, `T2`, `T3`, `T4`, and `T5` and their references.
496 ///
497 /// # Type Parameters
498 /// - `T1`: First component type.
499 /// - `T2`: Second component type.
500 /// - `T3`: Third component type.
501 /// - `T4`: Fourth component type.
502 /// - `T5`: Fifth component type.
503 ///
504 /// # Returns
505 /// - `Vec<(Entity, &T1, &T2, &T3, &T4, &T5)>`: Tuples of the entity and five component references.
506 ///
507 /// # Ordering
508 /// - The iteration order follows the dense storage of `T1`.
509 pub fn get_entities_and_components_with_5<
510 T1: Component,
511 T2: Component,
512 T3: Component,
513 T4: Component,
514 T5: Component,
515 >(
516 &self,
517 ) -> Vec<(Entity, &T1, &T2, &T3, &T4, &T5)> {
518 let storage1 = self.get_storage::<T1>();
519 let storage2 = self.get_storage::<T2>();
520 let storage3 = self.get_storage::<T3>();
521 let storage4 = self.get_storage::<T4>();
522 let storage5 = self.get_storage::<T5>();
523
524 match (storage1, storage2, storage3, storage4, storage5) {
525 (Some(s1), Some(s2), Some(s3), Some(s4), Some(s5)) => s1
526 .iter_with_entities()
527 .filter_map(|(entity, c1)| {
528 if let (Some(c2), Some(c3), Some(c4), Some(c5)) = (
529 s2.get(entity),
530 s3.get(entity),
531 s4.get(entity),
532 s5.get(entity),
533 ) {
534 Some((entity, c1, c2, c3, c4, c5))
535 } else {
536 None
537 }
538 })
539 .collect(),
540 _ => Vec::new(),
541 }
542 }
543
544 /// Returns only components for entities that have both components, aligned by entity.
545 ///
546 /// # Type Parameters
547 /// - `T1`: First component type.
548 /// - `T2`: Second component type.
549 ///
550 /// # Returns
551 /// - `(Vec<&T1>, Vec<&T2>)`: Two vectors with matching indices corresponding to the same entity.
552 ///
553 /// # Ordering
554 /// - The ordering follows the dense storage order of `T1` filtered by presence in `T2`.
555 pub fn get_components_with_2<T1: Component, T2: Component>(&self) -> (Vec<&T1>, Vec<&T2>) {
556 let storage1 = self.get_storage::<T1>();
557 let storage2 = self.get_storage::<T2>();
558
559 match (storage1, storage2) {
560 (Some(s1), Some(s2)) => {
561 let mut v1: Vec<&T1> = Vec::new();
562 let mut v2: Vec<&T2> = Vec::new();
563 for (entity, c1) in s1.iter_with_entities() {
564 if let Some(c2) = s2.get(entity) {
565 v1.push(c1);
566 v2.push(c2);
567 }
568 }
569 (v1, v2)
570 }
571 _ => (Vec::new(), Vec::new()),
572 }
573 }
574
575 /// Returns only components for entities that have all three components, aligned by entity.
576 ///
577 /// # Type Parameters
578 /// - `T1`: First component type.
579 /// - `T2`: Second component type.
580 /// - `T3`: Third component type.
581 ///
582 /// # Returns
583 /// - `(Vec<&T1>, Vec<&T2>, Vec<&T3>)`: Three vectors with matching indices for the same entities.
584 ///
585 /// # Ordering
586 /// - The ordering follows the dense storage of `T1` filtered by entities also having `T2` and `T3`.
587 pub fn get_components_with_3<T1: Component, T2: Component, T3: Component>(
588 &self,
589 ) -> (Vec<&T1>, Vec<&T2>, Vec<&T3>) {
590 let storage1 = self.get_storage::<T1>();
591 let storage2 = self.get_storage::<T2>();
592 let storage3 = self.get_storage::<T3>();
593
594 match (storage1, storage2, storage3) {
595 (Some(s1), Some(s2), Some(s3)) => {
596 let mut v1: Vec<&T1> = Vec::new();
597 let mut v2: Vec<&T2> = Vec::new();
598 let mut v3: Vec<&T3> = Vec::new();
599 for (entity, c1) in s1.iter_with_entities() {
600 if let (Some(c2), Some(c3)) = (s2.get(entity), s3.get(entity)) {
601 v1.push(c1);
602 v2.push(c2);
603 v3.push(c3);
604 }
605 }
606 (v1, v2, v3)
607 }
608 _ => (Vec::new(), Vec::new(), Vec::new()),
609 }
610 }
611
612 /// Returns only components for entities that have all four components, aligned by entity.
613 ///
614 /// # Type Parameters
615 /// - `T1`: First component type.
616 /// - `T2`: Second component type.
617 /// - `T3`: Third component type.
618 /// - `T4`: Fourth component type.
619 ///
620 /// # Returns
621 /// - `(Vec<&T1>, Vec<&T2>, Vec<&T3>, Vec<&T4>)`: Four vectors with matching indices for the same entities.
622 ///
623 /// # Ordering
624 /// - The ordering follows the dense storage of `T1` filtered by entities also having `T2`, `T3`, and `T4`.
625 pub fn get_components_with_4<T1: Component, T2: Component, T3: Component, T4: Component>(
626 &self,
627 ) -> (Vec<&T1>, Vec<&T2>, Vec<&T3>, Vec<&T4>) {
628 let storage1 = self.get_storage::<T1>();
629 let storage2 = self.get_storage::<T2>();
630 let storage3 = self.get_storage::<T3>();
631 let storage4 = self.get_storage::<T4>();
632
633 match (storage1, storage2, storage3, storage4) {
634 (Some(s1), Some(s2), Some(s3), Some(s4)) => {
635 let mut v1: Vec<&T1> = Vec::new();
636 let mut v2: Vec<&T2> = Vec::new();
637 let mut v3: Vec<&T3> = Vec::new();
638 let mut v4: Vec<&T4> = Vec::new();
639 for (entity, c1) in s1.iter_with_entities() {
640 if let (Some(c2), Some(c3), Some(c4)) =
641 (s2.get(entity), s3.get(entity), s4.get(entity))
642 {
643 v1.push(c1);
644 v2.push(c2);
645 v3.push(c3);
646 v4.push(c4);
647 }
648 }
649 (v1, v2, v3, v4)
650 }
651 _ => (Vec::new(), Vec::new(), Vec::new(), Vec::new()),
652 }
653 }
654
655 /// Returns only components for entities that have all five components, aligned by entity.
656 ///
657 /// # Type Parameters
658 /// - `T1`: First component type.
659 /// - `T2`: Second component type.
660 /// - `T3`: Third component type.
661 /// - `T4`: Fourth component type.
662 /// - `T5`: Fifth component type.
663 ///
664 /// # Returns
665 /// - `(Vec<&T1>, Vec<&T2>, Vec<&T3>, Vec<&T4>, Vec<&T5>)`: Five vectors with matching indices for the same entities.
666 ///
667 /// # Ordering
668 /// - The ordering follows the dense storage of `T1` filtered by entities also having `T2`, `T3`, `T4`, and `T5`.
669 pub fn get_components_with_5<
670 T1: Component,
671 T2: Component,
672 T3: Component,
673 T4: Component,
674 T5: Component,
675 >(
676 &self,
677 ) -> (Vec<&T1>, Vec<&T2>, Vec<&T3>, Vec<&T4>, Vec<&T5>) {
678 let storage1 = self.get_storage::<T1>();
679 let storage2 = self.get_storage::<T2>();
680 let storage3 = self.get_storage::<T3>();
681 let storage4 = self.get_storage::<T4>();
682 let storage5 = self.get_storage::<T5>();
683
684 match (storage1, storage2, storage3, storage4, storage5) {
685 (Some(s1), Some(s2), Some(s3), Some(s4), Some(s5)) => {
686 let mut v1: Vec<&T1> = Vec::new();
687 let mut v2: Vec<&T2> = Vec::new();
688 let mut v3: Vec<&T3> = Vec::new();
689 let mut v4: Vec<&T4> = Vec::new();
690 let mut v5: Vec<&T5> = Vec::new();
691 for (entity, c1) in s1.iter_with_entities() {
692 if let (Some(c2), Some(c3), Some(c4), Some(c5)) = (
693 s2.get(entity),
694 s3.get(entity),
695 s4.get(entity),
696 s5.get(entity),
697 ) {
698 v1.push(c1);
699 v2.push(c2);
700 v3.push(c3);
701 v4.push(c4);
702 v5.push(c5);
703 }
704 }
705 (v1, v2, v3, v4, v5)
706 }
707 _ => (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()),
708 }
709 }
710
711 /// Gets or creates the component storage for components of type `T`.
712 ///
713 /// # Type Parameters
714 /// - `T`: The component type whose storage is requested or to be created.
715 ///
716 /// # Returns
717 /// - `&mut ComponentStorage<T>`: A mutable reference to the storage for `T`, creating it if missing.
718 ///
719 /// # Effects
720 /// - If no storage for `T` exists yet, it will be inserted into the world's storage map.
721 ///
722 /// # Safety
723 /// - Internally performs type-erased insertion keyed by `TypeId` and immediately downcasts back
724 /// via `get_storage_mut::<T>()`, which is guarded by the same `TypeId`, making the cast sound.
725 fn get_or_create_storage<T: Component>(&mut self) -> &mut ComponentStorage<T> {
726 if !self.storages.contains_key(&TypeId::of::<T>()) {
727 self.storages
728 .insert(TypeId::of::<T>(), Box::new(ComponentStorage::<T>::new()));
729 }
730 self.get_storage_mut::<T>().unwrap()
731 }
732
733 /// Returns immutable references to all components of type `T` currently stored in the world.
734 ///
735 /// # Type Parameters
736 /// - `T`: The component type to retrieve.
737 ///
738 /// # Returns
739 /// - `Vec<&T>`: All components of type `T`. Empty if no storage exists.
740 ///
741 /// # Ordering
742 /// - Follows the dense storage order of `ComponentStorage<T>`.
743 pub fn get_all_components<T: Component>(&self) -> Vec<&T> {
744 if let Some(storage) = self.get_storage::<T>() {
745 storage.get_all()
746 } else {
747 Vec::new()
748 }
749 }
750
751 /// Returns mutable references to all components of type `T` currently stored in the world.
752 ///
753 /// # Type Parameters
754 /// - `T`: The component type to retrieve mutably.
755 ///
756 /// # Returns
757 /// - `Vec<&mut T>`: All components of type `T` as mutable references. Empty if no storage exists.
758 ///
759 /// # Ordering
760 /// - Follows the dense storage order of `ComponentStorage<T>`.
761 ///
762 /// # Notes
763 /// - Requires `&mut self` to ensure sound mutable access across all storages.
764 pub fn get_all_components_mut<T: Component>(&mut self) -> Vec<&mut T> {
765 if let Some(storage) = self.get_storage_mut::<T>() {
766 storage.get_all_mut()
767 } else {
768 Vec::new()
769 }
770 }
771
772 /// Given a reference to a component of type `T`, returns the owning `Entity`.
773 ///
774 /// # Type Parameters
775 /// - `T`: The component type of the provided reference.
776 ///
777 /// # Parameters
778 /// - `component`: A reference to a component previously obtained from the world.
779 ///
780 /// # Returns
781 /// - `Option<Entity>`: The entity that owns the component, if found.
782 ///
783 /// # Complexity
784 /// - O(n) in the number of `T` components; implemented by pointer-identity scan of the dense storage.
785 ///
786 /// # Notes
787 /// - Intended for convenience or debugging; prefer entity-centric access patterns when possible.
788 pub fn get_entity_for<T: Component>(&self, component: &T) -> Option<Entity> {
789 self.get_storage::<T>()
790 .and_then(|storage| storage.get_entity_for_component(component))
791 }
792
793 /// Registers a resource of any type `T` into the resource registry.
794 /// Returns a `ResourceHandle` that can be used to retrieve the resource later.
795 ///
796 /// # Type Parameters
797 /// - `T`: The type of the resource. Must be `'static` so it can be stored in a type-erased container.
798 ///
799 /// # Parameters
800 /// - `res`: The resource instance to register.
801 ///
802 /// # Returns
803 /// - `ResourceHandle`: A unique handle used to retrieve or mutate the resource later.
804 pub fn register_resource<T: 'static>(&mut self, res: T) -> ResourceHandle {
805 self.resource_registry.register_resource(res)
806 }
807
808 /// Retrieves an immutable reference to a registered resource of type `T`
809 /// using its `ResourceHandle`.
810 ///
811 /// # Type Parameters
812 /// - `T`: The expected type of the resource. Must match the type used in `register_resource`.
813 ///
814 /// # Parameters
815 /// - `handle`: The handle returned by `register_resource`.
816 ///
817 /// # Returns
818 /// - `Option<&T>`: `Some(&T)` if the handle is valid and the type matches, otherwise `None`.
819 pub fn get_resource<T: 'static>(&self, handle: ResourceHandle) -> Option<&T> {
820 self.resource_registry.get_resource::<T>(handle)
821 }
822
823 /// Retrieves a mutable reference to a registered resource of type `T`
824 /// using its `ResourceHandle`.
825 ///
826 /// # Type Parameters
827 /// - `T`: The expected type of the resource. Must match the type used in `register_resource`.
828 ///
829 /// # Parameters
830 /// - `handle`: The handle returned by `register_resource`.
831 ///
832 /// # Returns
833 /// - `Option<&mut T>`: `Some(&mut T)` if the handle is valid and the type matches, otherwise `None`.
834 pub fn get_resource_mut<T: 'static>(&mut self, handle: ResourceHandle) -> Option<&mut T> {
835 self.resource_registry.get_resource_mut::<T>(handle)
836 }
837
838 /// Removes a resource of type `T` from the world's resource registry.
839 ///
840 /// # Type Parameters
841 /// - `T`: The type of the resource to remove.
842 ///
843 /// # Parameters
844 /// - `handle`: The handle associated with the resource to be removed.
845 ///
846 /// # Returns
847 /// - `Some(T)`: If the resource was successfully removed.
848 /// - `None`: If the handle was invalid or the type mismatched.
849 pub fn remove_resource<T: 'static>(&mut self, handle: ResourceHandle) -> Option<T> {
850 self.resource_registry.remove_resource::<T>(handle)
851 }
852
853 /// Registers or overwrites the unique resource of type `T` in the world.
854 ///
855 /// # Parameters
856 /// - `resource`: The resource instance to register as unique.
857 pub fn register_unique<T: 'static>(&mut self, resource: T) {
858 self.resource_registry.register_unique(resource);
859 }
860
861 /// Gets an immutable reference to the unique resource of type `T` from the world.
862 ///
863 /// # Returns
864 /// - `Option<&T>`: Some reference if the unique resource is present, None otherwise.
865 pub fn get_unique<T: 'static>(&self) -> Option<&T> {
866 self.resource_registry.get_unique::<T>()
867 }
868
869 /// Gets a mutable reference to the unique resource of type `T` from the world.
870 ///
871 /// # Returns
872 /// - `Option<&mut T>`: Some mutable reference if the unique resource is present, None otherwise.
873 pub fn get_unique_mut<T: 'static>(&mut self) -> Option<&mut T> {
874 self.resource_registry.get_unique_mut::<T>()
875 }
876
877 /// Removes the unique resource of type `T` from the world and returns it.
878 ///
879 /// # Returns
880 /// - `Option<T>`: The removed resource if it was present, None otherwise.
881 pub fn remove_unique<T: 'static>(&mut self) -> Option<T> {
882 self.resource_registry.remove_unique::<T>()
883 }
884}