bevy_ecs/component/
required.rs

1use alloc::{format, vec::Vec};
2use bevy_platform::{hash::FixedHasher, sync::Arc};
3use bevy_ptr::OwningPtr;
4use core::fmt::Debug;
5use indexmap::{IndexMap, IndexSet};
6use thiserror::Error;
7
8use crate::{
9    bundle::BundleInfo,
10    change_detection::{MaybeLocation, Tick},
11    component::{Component, ComponentId, Components, ComponentsRegistrator},
12    entity::Entity,
13    query::DebugCheckedUnwrap as _,
14    storage::{SparseSets, Table, TableRow},
15};
16
17/// Metadata associated with a required component. See [`Component`] for details.
18#[derive(Clone)]
19pub struct RequiredComponent {
20    /// The constructor used for the required component.
21    pub constructor: RequiredComponentConstructor,
22}
23
24/// A Required Component constructor. See [`Component`] for details.
25#[derive(Clone)]
26pub struct RequiredComponentConstructor(
27    // Note: this function makes `unsafe` assumptions, so it cannot be public.
28    Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
29);
30
31impl RequiredComponentConstructor {
32    /// Creates a new instance of `RequiredComponentConstructor` for the given type
33    ///
34    /// # Safety
35    ///
36    /// - `component_id` must be a valid component for type `C`.
37    pub unsafe fn new<C: Component>(component_id: ComponentId, constructor: fn() -> C) -> Self {
38        RequiredComponentConstructor({
39            // `portable-atomic-util` `Arc` is not able to coerce an unsized
40            // type like `std::sync::Arc` can. Creating a `Box` first does the
41            // coercion.
42            //
43            // This would be resolved by https://github.com/rust-lang/rust/issues/123430
44
45            #[cfg(not(target_has_atomic = "ptr"))]
46            use alloc::boxed::Box;
47
48            type Constructor = dyn for<'a, 'b> Fn(
49                &'a mut Table,
50                &'b mut SparseSets,
51                Tick,
52                TableRow,
53                Entity,
54                MaybeLocation,
55            );
56
57            #[cfg(not(target_has_atomic = "ptr"))]
58            type Intermediate<T> = Box<T>;
59
60            #[cfg(target_has_atomic = "ptr")]
61            type Intermediate<T> = Arc<T>;
62
63            let boxed: Intermediate<Constructor> = Intermediate::new(
64                move |table, sparse_sets, change_tick, table_row, entity, caller| {
65                    OwningPtr::make(constructor(), |ptr| {
66                        // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
67                        // pass in a valid table_row and entity requiring a C constructor
68                        // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
69                        // `ptr` points to valid `C` data, which matches the type associated with `component_id`
70                        unsafe {
71                            BundleInfo::initialize_required_component(
72                                table,
73                                sparse_sets,
74                                change_tick,
75                                table_row,
76                                entity,
77                                component_id,
78                                C::STORAGE_TYPE,
79                                ptr,
80                                caller,
81                            );
82                        }
83                    });
84                },
85            );
86
87            Arc::from(boxed)
88        })
89    }
90
91    /// # Safety
92    /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
93    /// Calling it _anywhere else_ should be considered unsafe.
94    ///
95    /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
96    /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
97    /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
98    ///
99    /// Again, don't call this anywhere but [`BundleInfo::write_components`].
100    pub(crate) unsafe fn initialize(
101        &self,
102        table: &mut Table,
103        sparse_sets: &mut SparseSets,
104        change_tick: Tick,
105        table_row: TableRow,
106        entity: Entity,
107        caller: MaybeLocation,
108    ) {
109        (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
110    }
111}
112
113/// The collection of metadata for components that are required for a given component.
114///
115/// For more information, see the "Required Components" section of [`Component`].
116#[derive(Default, Clone)]
117pub struct RequiredComponents {
118    /// The components that are directly required (i.e. excluding inherited ones), in the order of their precedence.
119    ///
120    /// # Safety
121    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
122    pub(crate) direct: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
123    /// All the components that are required (i.e. including inherited ones), in depth-first order. Most importantly,
124    /// components in this list always appear after all the components that they require.
125    ///
126    /// Note that the direct components are not necessarily at the end of this list, for example if A and C are directly
127    /// requires, and A requires B requires C, then `all` will hold [C, B, A].
128    ///
129    /// # Safety
130    /// The [`RequiredComponent`] instance associated to each ID must be valid for its component.
131    pub(crate) all: IndexMap<ComponentId, RequiredComponent, FixedHasher>,
132}
133
134impl Debug for RequiredComponents {
135    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
136        f.debug_struct("RequiredComponents")
137            .field("direct", &self.direct.keys())
138            .field("all", &self.all.keys())
139            .finish()
140    }
141}
142
143impl RequiredComponents {
144    /// Registers the [`Component`] `C` as an explicitly required component.
145    ///
146    /// If the component was not already registered as an explicit required component then it is added
147    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
148    ///
149    /// # Safety
150    ///
151    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
152    unsafe fn register<C: Component>(
153        &mut self,
154        components: &mut ComponentsRegistrator<'_>,
155        constructor: fn() -> C,
156    ) {
157        let id = components.register_component::<C>();
158        // SAFETY:
159        // - `id` was just registered in `components`;
160        // - the caller guarantees all other components were registered in `components`.
161        unsafe { self.register_by_id::<C>(id, components, constructor) };
162    }
163
164    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
165    ///
166    /// If the component was not already registered as an explicit required component then it is added
167    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
168    ///
169    /// # Safety
170    ///
171    /// - `component_id` must be a valid component in `components` for the type `C`;
172    /// - all other components in this [`RequiredComponents`] instance must have been registered in `components`.
173    unsafe fn register_by_id<C: Component>(
174        &mut self,
175        component_id: ComponentId,
176        components: &Components,
177        constructor: fn() -> C,
178    ) {
179        // SAFETY: the caller guarantees that `component_id` is valid for the type `C`.
180        let constructor =
181            || unsafe { RequiredComponentConstructor::new(component_id, constructor) };
182
183        // SAFETY:
184        // - the caller guarantees that `component_id` is valid in `components`
185        // - the caller guarantees all other components were registered in `components`;
186        // - constructor is guaranteed to create a valid constructor for the component with id `component_id`.
187        unsafe { self.register_dynamic_with(component_id, components, constructor) };
188    }
189
190    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
191    ///
192    /// If the component was not already registered as an explicit required component then it is added
193    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
194    ///
195    /// # Safety
196    ///
197    /// - `component_id` must be a valid component in `components`;
198    /// - all other components in `self` must have been registered in `components`;
199    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
200    ///   component with ID `component_id`.
201    unsafe fn register_dynamic_with(
202        &mut self,
203        component_id: ComponentId,
204        components: &Components,
205        constructor: impl FnOnce() -> RequiredComponentConstructor,
206    ) {
207        // If already registered as a direct required component then bail.
208        let entry = match self.direct.entry(component_id) {
209            indexmap::map::Entry::Vacant(entry) => entry,
210            indexmap::map::Entry::Occupied(_) =>
211                panic!("Error while registering required component {component_id:?}: already directly required"),
212        };
213
214        // Insert into `direct`.
215        let constructor = constructor();
216        let required_component = RequiredComponent { constructor };
217        entry.insert(required_component.clone());
218
219        // Register inherited required components.
220        // SAFETY:
221        // - the caller guarantees all components that were in `self` have been registered in `components`;
222        // - `component_id` has just been added, but is also guaranteed by the called to be valid in `components`.
223        unsafe {
224            Self::register_inherited_required_components_unchecked(
225                &mut self.all,
226                component_id,
227                required_component,
228                components,
229            );
230        }
231    }
232
233    /// Rebuild the `all` list
234    ///
235    /// # Safety
236    ///
237    /// - all components in `self` must have been registered in `components`.
238    unsafe fn rebuild_inherited_required_components(&mut self, components: &Components) {
239        // Clear `all`, we are re-initializing it.
240        self.all.clear();
241
242        // Register all inherited components as if we just registered all components in `direct` one-by-one.
243        for (&required_id, required_component) in &self.direct {
244            // SAFETY:
245            // - the caller guarantees that all components in this instance have been registered in `components`,
246            //   meaning both `all` and `required_id` have been registered in `components`;
247            // - `required_component` was associated to `required_id`, so it must hold a constructor valid for it.
248            unsafe {
249                Self::register_inherited_required_components_unchecked(
250                    &mut self.all,
251                    required_id,
252                    required_component.clone(),
253                    components,
254                );
255            }
256        }
257    }
258
259    /// Registers all the inherited required components from `required_id`.
260    ///
261    /// # Safety
262    ///
263    /// - all components in `all` must have been registered in `components`;
264    /// - `required_id` must have been registered in `components`;
265    /// - `required_component` must hold a valid constructor for the component with id `required_id`.
266    unsafe fn register_inherited_required_components_unchecked(
267        all: &mut IndexMap<ComponentId, RequiredComponent, FixedHasher>,
268        required_id: ComponentId,
269        required_component: RequiredComponent,
270        components: &Components,
271    ) {
272        // SAFETY: the caller guarantees that `required_id` is valid in `components`.
273        let info = unsafe { components.get_info(required_id).debug_checked_unwrap() };
274
275        // Now we need to "recursively" register the
276        // Small optimization: if the current required component was already required recursively
277        // by an earlier direct required component then all its inherited components have all already
278        // been inserted, so let's not try to reinsert them.
279        if !all.contains_key(&required_id) {
280            for (&inherited_id, inherited_required) in &info.required_components().all {
281                // This is an inherited required component: insert it only if not already present.
282                // By the invariants of `RequiredComponents`, `info.required_components().all` holds the required
283                // components in a depth-first order, and this makes us store the components in `self.all` also
284                // in depth-first order, as long as we don't overwrite existing ones.
285                //
286                // SAFETY:
287                // `inherited_required` was associated to `inherited_id`, so it must have been valid for its component.
288                all.entry(inherited_id)
289                    .or_insert_with(|| inherited_required.clone());
290            }
291        }
292
293        // For direct required components:
294        // - insert them after inherited components to follow the depth-first order;
295        // - insert them unconditionally in order to make their constructor the one that's used.
296        // Note that `insert` does not change the order of components, meaning `component_id` will still appear
297        // before any other component that requires it.
298        //
299        // SAFETY: the caller guarantees that `required_component` is valid for the component with ID `required_id`.
300        all.insert(required_id, required_component);
301    }
302
303    /// Iterates the ids of all required components. This includes recursive required components.
304    pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
305        self.all.keys().copied()
306    }
307}
308
309impl Components {
310    /// Registers the components in `required_components` as required by `requiree`.
311    ///
312    /// # Safety
313    ///
314    /// - `requiree` must have been registered in `self`
315    /// - all components in `required_components` must have been registered in `self`;
316    /// - this is called with `requiree` before being called on any component requiring `requiree`.
317    pub(crate) unsafe fn register_required_by(
318        &mut self,
319        requiree: ComponentId,
320        required_components: &RequiredComponents,
321    ) {
322        for &required in required_components.all.keys() {
323            // SAFETY: the caller guarantees that all components in `required_components` have been registered in `self`.
324            let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
325            // This preserves the invariant of `required_by` because:
326            // - components requiring `required` and required by `requiree` are already initialized at this point
327            //   and hence registered in `required_by` before `requiree`;
328            // - components requiring `requiree` cannot exist yet, as this is called on `requiree` before them.
329            required_by.insert(requiree);
330        }
331    }
332
333    /// Registers the given component `R` and [required components] inherited from it as required by `T`.
334    ///
335    /// When `T` is added to an entity, `R` will also be added if it was not already provided.
336    /// The given `constructor` will be used for the creation of `R`.
337    ///
338    /// [required components]: Component#required-components
339    ///
340    /// # Safety
341    ///
342    /// - the given component IDs `required` and `requiree` must be valid in `self`;
343    /// - the given component ID `required` must be valid for the component type `R`.
344    ///
345    ///
346    /// # Errors
347    ///
348    /// Returns a [`RequiredComponentsError`] if either of these are true:
349    /// - the `required` component is already a *directly* required component for the `requiree`; indirect
350    ///   requirements through other components are allowed. In those cases, the more specific
351    ///   registration will be used.
352    /// - the `requiree` component is already a (possibly indirect) required component for the `required` component.
353    pub(crate) unsafe fn register_required_components<R: Component>(
354        &mut self,
355        requiree: ComponentId,
356        required: ComponentId,
357        constructor: fn() -> R,
358    ) -> Result<(), RequiredComponentsError> {
359        // First step: validate inputs and return errors.
360
361        // SAFETY: The caller ensures that the `required` is valid.
362        let required_required_components = unsafe {
363            self.get_required_components(required)
364                .debug_checked_unwrap()
365        };
366
367        // Cannot create cyclic requirements.
368        if required_required_components.all.contains_key(&requiree) {
369            return Err(RequiredComponentsError::CyclicRequirement(
370                requiree, required,
371            ));
372        }
373
374        // SAFETY: The caller ensures that the `requiree` is valid.
375        let required_components = unsafe {
376            self.get_required_components_mut(requiree)
377                .debug_checked_unwrap()
378        };
379
380        // Cannot directly require the same component twice.
381        if required_components.direct.contains_key(&required) {
382            return Err(RequiredComponentsError::DuplicateRegistration(
383                requiree, required,
384            ));
385        }
386
387        // Second step: register the single requirement requiree->required
388
389        // Store the old count of (all) required components. This will help determine which ones are new.
390        let old_required_count = required_components.all.len();
391
392        // SAFETY: the caller guarantees that `requiree` is valid in `self`.
393        unsafe {
394            self.required_components_scope(requiree, |this, required_components| {
395                // SAFETY: the caller guarantees that `required` is valid for type `R` in `self`
396                required_components.register_by_id(required, this, constructor);
397            });
398        }
399        // Third step: update the required components and required_by of all the indirect requirements/requirees.
400
401        // Borrow again otherwise it conflicts with the `self.required_components_scope` call.
402        // SAFETY: The caller ensures that the `requiree` is valid.
403        let required_components = unsafe {
404            self.get_required_components_mut(requiree)
405                .debug_checked_unwrap()
406        };
407
408        // Optimization: get all the new required components, i.e. those that were appended.
409        // Other components that might be inherited when requiring `required` can be safely ignored because
410        // any component requiring `requiree` will already transitively require them.
411        // Note: the only small exception is for `required` itself, for which we cannot ignore the value of the
412        // constructor. But for simplicity we will rebuild any `RequiredComponents`
413        let new_required_components = required_components.all[old_required_count..]
414            .keys()
415            .copied()
416            .collect::<Vec<_>>();
417
418        // Get all the new requiree components, i.e. `requiree` and all the components that `requiree` is required by.
419        // SAFETY: The caller ensures that the `requiree` is valid.
420        let requiree_required_by = unsafe { self.get_required_by(requiree).debug_checked_unwrap() };
421        let new_requiree_components = [requiree]
422            .into_iter()
423            .chain(requiree_required_by.iter().copied())
424            .collect::<IndexSet<_, FixedHasher>>();
425
426        // We now need to update the required and required_by components of all the components
427        // directly or indirectly involved.
428        // Important: we need to be careful about the order we do these operations in.
429        // Since computing the required components of some component depends on the required components of
430        // other components, and while we do this operations not all required components are up-to-date, we need
431        // to ensure we update components in such a way that we update a component after the components it depends on.
432        // Luckily, `new_requiree_components` comes from `ComponentInfo::required_by`, which guarantees an order
433        // with that property.
434
435        // Update the inherited required components of all requiree components (directly or indirectly).
436        // Skip the first one (requiree) because we already updates it.
437        for &indirect_requiree in &new_requiree_components[1..] {
438            // SAFETY: `indirect_requiree` comes from `self` so it must be valid.
439            unsafe {
440                self.required_components_scope(indirect_requiree, |this, required_components| {
441                    // Rebuild the inherited required components.
442                    // SAFETY: `required_components` comes from `self`, so all its components must have be valid in `self`.
443                    required_components.rebuild_inherited_required_components(this);
444                });
445            }
446        }
447
448        // Update the `required_by` of all the components that were newly required (directly or indirectly).
449        for &indirect_required in &new_required_components {
450            // SAFETY: `indirect_required` comes from `self`, so it must be valid.
451            let required_by = unsafe {
452                self.get_required_by_mut(indirect_required)
453                    .debug_checked_unwrap()
454            };
455
456            // Remove and re-add all the components in `new_requiree_components`
457            // This preserves the invariant of `required_by` because `new_requiree_components`
458            // satisfies its invariant, due to being `requiree` followed by its `required_by` components,
459            // and because any component not in `new_requiree_components` cannot require a component in it,
460            // since if that was the case it would appear in the `required_by` for `requiree`.
461            required_by.retain(|id| !new_requiree_components.contains(id));
462            required_by.extend(&new_requiree_components);
463        }
464
465        Ok(())
466    }
467
468    /// Temporarily take out the [`RequiredComponents`] of the component with id `component_id`
469    /// and runs the given closure with mutable access to `self` and the given [`RequiredComponents`].
470    ///
471    /// SAFETY:
472    ///
473    /// `component_id` is valid in `self.components`
474    unsafe fn required_components_scope<R>(
475        &mut self,
476        component_id: ComponentId,
477        f: impl FnOnce(&mut Self, &mut RequiredComponents) -> R,
478    ) -> R {
479        struct DropGuard<'a> {
480            components: &'a mut Components,
481            component_id: ComponentId,
482            required_components: RequiredComponents,
483        }
484
485        impl Drop for DropGuard<'_> {
486            fn drop(&mut self) {
487                // SAFETY: The caller ensures that the `component_id` is valid.
488                let required_components = unsafe {
489                    self.components
490                        .get_required_components_mut(self.component_id)
491                        .debug_checked_unwrap()
492                };
493
494                debug_assert!(required_components.direct.is_empty());
495                debug_assert!(required_components.all.is_empty());
496
497                *required_components = core::mem::take(&mut self.required_components);
498            }
499        }
500
501        let mut guard = DropGuard {
502            component_id,
503            // SAFETY: The caller ensures that the `component_id` is valid.
504            required_components: core::mem::take(unsafe {
505                self.get_required_components_mut(component_id)
506                    .debug_checked_unwrap()
507            }),
508            components: self,
509        };
510
511        f(guard.components, &mut guard.required_components)
512    }
513}
514
515/// An error returned when the registration of a required component fails.
516#[derive(Error, Debug)]
517#[non_exhaustive]
518pub enum RequiredComponentsError {
519    /// The component is already a directly required component for the requiree.
520    #[error("Component {0:?} already directly requires component {1:?}")]
521    DuplicateRegistration(ComponentId, ComponentId),
522    /// Adding the given requirement would create a cycle.
523    #[error("Cyclic requirement found: the requiree component {0:?} is required by the required component {1:?}")]
524    CyclicRequirement(ComponentId, ComponentId),
525    /// An archetype with the component that requires other components already exists
526    #[error("An archetype with the component {0:?} that requires other components already exists")]
527    ArchetypeExists(ComponentId),
528}
529
530pub(super) fn enforce_no_required_components_recursion(
531    components: &Components,
532    recursion_check_stack: &[ComponentId],
533    required: ComponentId,
534) {
535    if let Some(direct_recursion) = recursion_check_stack
536        .iter()
537        .position(|&id| id == required)
538        .map(|index| index == recursion_check_stack.len() - 1)
539    {
540        panic!(
541            "Recursive required components detected: {}\nhelp: {}",
542            recursion_check_stack
543                .iter()
544                .map(|id| format!("{}", components.get_name(*id).unwrap().shortname()))
545                .collect::<Vec<_>>()
546                .join(" → "),
547            if direct_recursion {
548                format!(
549                    "Remove require({}).",
550                    components.get_name(required).unwrap().shortname()
551                )
552            } else {
553                "If this is intentional, consider merging the components.".into()
554            }
555        );
556    }
557}
558
559/// This is a safe handle around `ComponentsRegistrator` and `RequiredComponents` to register required components.
560pub struct RequiredComponentsRegistrator<'a, 'w> {
561    components: &'a mut ComponentsRegistrator<'w>,
562    required_components: &'a mut RequiredComponents,
563}
564
565impl<'a, 'w> RequiredComponentsRegistrator<'a, 'w> {
566    /// # Safety
567    ///
568    /// All components in `required_components` must have been registered in `components`
569    pub(super) unsafe fn new(
570        components: &'a mut ComponentsRegistrator<'w>,
571        required_components: &'a mut RequiredComponents,
572    ) -> Self {
573        Self {
574            components,
575            required_components,
576        }
577    }
578
579    /// Registers the [`Component`] `C` as an explicitly required component.
580    ///
581    /// If the component was not already registered as an explicit required component then it is added
582    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
583    pub fn register_required<C: Component>(&mut self, constructor: fn() -> C) {
584        // SAFETY: we internally guarantee that all components in `required_components`
585        // are registered in `components`
586        unsafe {
587            self.required_components
588                .register(self.components, constructor);
589        }
590    }
591
592    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
593    ///
594    /// If the component was not already registered as an explicit required component then it is added
595    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
596    ///
597    /// # Safety
598    ///
599    /// `component_id` must be a valid [`ComponentId`] for `C` in the [`Components`] instance of `self`.
600    pub unsafe fn register_required_by_id<C: Component>(
601        &mut self,
602        component_id: ComponentId,
603        constructor: fn() -> C,
604    ) {
605        // SAFETY:
606        // - the caller guarantees `component_id` is a valid component in `components` for `C`;
607        // - we internally guarantee all other components in `required_components` are registered in `components`.
608        unsafe {
609            self.required_components.register_by_id::<C>(
610                component_id,
611                self.components,
612                constructor,
613            );
614        }
615    }
616
617    /// Registers the [`Component`] with the given `component_id` ID as an explicitly required component.
618    ///
619    /// If the component was not already registered as an explicit required component then it is added
620    /// as one, potentially overriding the constructor of a inherited required component, otherwise panics.
621    ///
622    /// # Safety
623    ///
624    /// - `component_id` must be valid in the [`Components`] instance of `self`;
625    /// - `constructor` must return a [`RequiredComponentConstructor`] that constructs a valid instance for the
626    ///   component with ID `component_id`.
627    pub unsafe fn register_required_dynamic_with(
628        &mut self,
629        component_id: ComponentId,
630        constructor: impl FnOnce() -> RequiredComponentConstructor,
631    ) {
632        // SAFETY:
633        // - the caller guarantees `component_id` is valid in `components`;
634        // - the caller guarantees `constructor` returns a valid constructor for `component_id`;
635        // - we internally guarantee all other components in `required_components` are registered in `components`.
636        unsafe {
637            self.required_components.register_dynamic_with(
638                component_id,
639                self.components,
640                constructor,
641            );
642        }
643    }
644}
645
646#[cfg(test)]
647mod tests {
648    use alloc::string::{String, ToString};
649
650    use crate::{
651        bundle::Bundle,
652        component::{Component, RequiredComponentsError},
653        prelude::Resource,
654        world::World,
655    };
656
657    #[test]
658    fn required_components() {
659        #[derive(Component)]
660        #[require(Y)]
661        struct X;
662
663        #[derive(Component)]
664        #[require(Z = new_z())]
665        struct Y {
666            value: String,
667        }
668
669        #[derive(Component)]
670        struct Z(u32);
671
672        impl Default for Y {
673            fn default() -> Self {
674                Self {
675                    value: "hello".to_string(),
676                }
677            }
678        }
679
680        fn new_z() -> Z {
681            Z(7)
682        }
683
684        let mut world = World::new();
685        let id = world.spawn(X).id();
686        assert_eq!(
687            "hello",
688            world.entity(id).get::<Y>().unwrap().value,
689            "Y should have the default value"
690        );
691        assert_eq!(
692            7,
693            world.entity(id).get::<Z>().unwrap().0,
694            "Z should have the value provided by the constructor defined in Y"
695        );
696
697        let id = world
698            .spawn((
699                X,
700                Y {
701                    value: "foo".to_string(),
702                },
703            ))
704            .id();
705        assert_eq!(
706            "foo",
707            world.entity(id).get::<Y>().unwrap().value,
708            "Y should have the manually provided value"
709        );
710        assert_eq!(
711            7,
712            world.entity(id).get::<Z>().unwrap().0,
713            "Z should have the value provided by the constructor defined in Y"
714        );
715
716        let id = world.spawn((X, Z(8))).id();
717        assert_eq!(
718            "hello",
719            world.entity(id).get::<Y>().unwrap().value,
720            "Y should have the default value"
721        );
722        assert_eq!(
723            8,
724            world.entity(id).get::<Z>().unwrap().0,
725            "Z should have the manually provided value"
726        );
727    }
728
729    #[test]
730    fn generic_required_components() {
731        #[derive(Component)]
732        #[require(Y<usize>)]
733        struct X;
734
735        #[derive(Component, Default)]
736        struct Y<T> {
737            value: T,
738        }
739
740        let mut world = World::new();
741        let id = world.spawn(X).id();
742        assert_eq!(
743            0,
744            world.entity(id).get::<Y<usize>>().unwrap().value,
745            "Y should have the default value"
746        );
747    }
748
749    #[test]
750    fn required_components_spawn_nonexistent_hooks() {
751        #[derive(Component)]
752        #[require(Y)]
753        struct X;
754
755        #[derive(Component, Default)]
756        struct Y;
757
758        #[derive(Resource)]
759        struct A(usize);
760
761        #[derive(Resource)]
762        struct I(usize);
763
764        let mut world = World::new();
765        world.insert_resource(A(0));
766        world.insert_resource(I(0));
767        world
768            .register_component_hooks::<Y>()
769            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
770            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
771
772        // Spawn entity and ensure Y was added
773        assert!(world.spawn(X).contains::<Y>());
774
775        assert_eq!(world.resource::<A>().0, 1);
776        assert_eq!(world.resource::<I>().0, 1);
777    }
778
779    #[test]
780    fn required_components_insert_existing_hooks() {
781        #[derive(Component)]
782        #[require(Y)]
783        struct X;
784
785        #[derive(Component, Default)]
786        struct Y;
787
788        #[derive(Resource)]
789        struct A(usize);
790
791        #[derive(Resource)]
792        struct I(usize);
793
794        let mut world = World::new();
795        world.insert_resource(A(0));
796        world.insert_resource(I(0));
797        world
798            .register_component_hooks::<Y>()
799            .on_add(|mut world, _| world.resource_mut::<A>().0 += 1)
800            .on_insert(|mut world, _| world.resource_mut::<I>().0 += 1);
801
802        // Spawn entity and ensure Y was added
803        assert!(world.spawn_empty().insert(X).contains::<Y>());
804
805        assert_eq!(world.resource::<A>().0, 1);
806        assert_eq!(world.resource::<I>().0, 1);
807    }
808
809    #[test]
810    fn required_components_take_leaves_required() {
811        #[derive(Component)]
812        #[require(Y)]
813        struct X;
814
815        #[derive(Component, Default)]
816        struct Y;
817
818        let mut world = World::new();
819        let e = world.spawn(X).id();
820        let _ = world.entity_mut(e).take::<X>().unwrap();
821        assert!(world.entity_mut(e).contains::<Y>());
822    }
823
824    #[test]
825    fn required_components_retain_keeps_required() {
826        #[derive(Component)]
827        #[require(Y)]
828        struct X;
829
830        #[derive(Component, Default)]
831        struct Y;
832
833        #[derive(Component, Default)]
834        struct Z;
835
836        let mut world = World::new();
837        let e = world.spawn((X, Z)).id();
838        world.entity_mut(e).retain::<X>();
839        assert!(world.entity_mut(e).contains::<X>());
840        assert!(world.entity_mut(e).contains::<Y>());
841        assert!(!world.entity_mut(e).contains::<Z>());
842    }
843
844    #[test]
845    fn required_components_spawn_then_insert_no_overwrite() {
846        #[derive(Component)]
847        #[require(Y)]
848        struct X;
849
850        #[derive(Component, Default)]
851        struct Y(usize);
852
853        let mut world = World::new();
854        let id = world.spawn((X, Y(10))).id();
855        world.entity_mut(id).insert(X);
856
857        assert_eq!(
858            10,
859            world.entity(id).get::<Y>().unwrap().0,
860            "Y should still have the manually provided value"
861        );
862    }
863
864    #[test]
865    fn dynamic_required_components() {
866        #[derive(Component)]
867        #[require(Y)]
868        struct X;
869
870        #[derive(Component, Default)]
871        struct Y;
872
873        let mut world = World::new();
874        let x_id = world.register_component::<X>();
875
876        let mut e = world.spawn_empty();
877
878        // SAFETY: x_id is a valid component id
879        bevy_ptr::OwningPtr::make(X, |ptr| unsafe {
880            e.insert_by_id(x_id, ptr);
881        });
882
883        assert!(e.contains::<Y>());
884    }
885
886    #[test]
887    fn remove_component_and_its_runtime_required_components() {
888        #[derive(Component)]
889        struct X;
890
891        #[derive(Component, Default)]
892        struct Y;
893
894        #[derive(Component, Default)]
895        struct Z;
896
897        #[derive(Component)]
898        struct V;
899
900        let mut world = World::new();
901        world.register_required_components::<X, Y>();
902        world.register_required_components::<Y, Z>();
903
904        let e = world.spawn((X, V)).id();
905        assert!(world.entity(e).contains::<X>());
906        assert!(world.entity(e).contains::<Y>());
907        assert!(world.entity(e).contains::<Z>());
908        assert!(world.entity(e).contains::<V>());
909
910        //check that `remove` works as expected
911        world.entity_mut(e).remove::<X>();
912        assert!(!world.entity(e).contains::<X>());
913        assert!(world.entity(e).contains::<Y>());
914        assert!(world.entity(e).contains::<Z>());
915        assert!(world.entity(e).contains::<V>());
916
917        world.entity_mut(e).insert(X);
918        assert!(world.entity(e).contains::<X>());
919        assert!(world.entity(e).contains::<Y>());
920        assert!(world.entity(e).contains::<Z>());
921        assert!(world.entity(e).contains::<V>());
922
923        //remove `X` again and ensure that `Y` and `Z` was removed too
924        world.entity_mut(e).remove_with_requires::<X>();
925        assert!(!world.entity(e).contains::<X>());
926        assert!(!world.entity(e).contains::<Y>());
927        assert!(!world.entity(e).contains::<Z>());
928        assert!(world.entity(e).contains::<V>());
929    }
930
931    #[test]
932    fn remove_component_and_its_required_components() {
933        #[derive(Component)]
934        #[require(Y)]
935        struct X;
936
937        #[derive(Component, Default)]
938        #[require(Z)]
939        struct Y;
940
941        #[derive(Component, Default)]
942        struct Z;
943
944        #[derive(Component)]
945        struct V;
946
947        let mut world = World::new();
948
949        let e = world.spawn((X, V)).id();
950        assert!(world.entity(e).contains::<X>());
951        assert!(world.entity(e).contains::<Y>());
952        assert!(world.entity(e).contains::<Z>());
953        assert!(world.entity(e).contains::<V>());
954
955        //check that `remove` works as expected
956        world.entity_mut(e).remove::<X>();
957        assert!(!world.entity(e).contains::<X>());
958        assert!(world.entity(e).contains::<Y>());
959        assert!(world.entity(e).contains::<Z>());
960        assert!(world.entity(e).contains::<V>());
961
962        world.entity_mut(e).insert(X);
963        assert!(world.entity(e).contains::<X>());
964        assert!(world.entity(e).contains::<Y>());
965        assert!(world.entity(e).contains::<Z>());
966        assert!(world.entity(e).contains::<V>());
967
968        //remove `X` again and ensure that `Y` and `Z` was removed too
969        world.entity_mut(e).remove_with_requires::<X>();
970        assert!(!world.entity(e).contains::<X>());
971        assert!(!world.entity(e).contains::<Y>());
972        assert!(!world.entity(e).contains::<Z>());
973        assert!(world.entity(e).contains::<V>());
974    }
975
976    #[test]
977    fn remove_bundle_and_his_required_components() {
978        #[derive(Component, Default)]
979        #[require(Y)]
980        struct X;
981
982        #[derive(Component, Default)]
983        struct Y;
984
985        #[derive(Component, Default)]
986        #[require(W)]
987        struct Z;
988
989        #[derive(Component, Default)]
990        struct W;
991
992        #[derive(Component)]
993        struct V;
994
995        #[derive(Bundle, Default)]
996        struct TestBundle {
997            x: X,
998            z: Z,
999        }
1000
1001        let mut world = World::new();
1002        let e = world.spawn((TestBundle::default(), V)).id();
1003
1004        assert!(world.entity(e).contains::<X>());
1005        assert!(world.entity(e).contains::<Y>());
1006        assert!(world.entity(e).contains::<Z>());
1007        assert!(world.entity(e).contains::<W>());
1008        assert!(world.entity(e).contains::<V>());
1009
1010        world.entity_mut(e).remove_with_requires::<TestBundle>();
1011        assert!(!world.entity(e).contains::<X>());
1012        assert!(!world.entity(e).contains::<Y>());
1013        assert!(!world.entity(e).contains::<Z>());
1014        assert!(!world.entity(e).contains::<W>());
1015        assert!(world.entity(e).contains::<V>());
1016    }
1017
1018    #[test]
1019    fn runtime_required_components() {
1020        // Same as `required_components` test but with runtime registration
1021
1022        #[derive(Component)]
1023        struct X;
1024
1025        #[derive(Component)]
1026        struct Y {
1027            value: String,
1028        }
1029
1030        #[derive(Component)]
1031        struct Z(u32);
1032
1033        impl Default for Y {
1034            fn default() -> Self {
1035                Self {
1036                    value: "hello".to_string(),
1037                }
1038            }
1039        }
1040
1041        let mut world = World::new();
1042
1043        world.register_required_components::<X, Y>();
1044        world.register_required_components_with::<Y, Z>(|| Z(7));
1045
1046        let id = world.spawn(X).id();
1047
1048        assert_eq!(
1049            "hello",
1050            world.entity(id).get::<Y>().unwrap().value,
1051            "Y should have the default value"
1052        );
1053        assert_eq!(
1054            7,
1055            world.entity(id).get::<Z>().unwrap().0,
1056            "Z should have the value provided by the constructor defined in Y"
1057        );
1058
1059        let id = world
1060            .spawn((
1061                X,
1062                Y {
1063                    value: "foo".to_string(),
1064                },
1065            ))
1066            .id();
1067        assert_eq!(
1068            "foo",
1069            world.entity(id).get::<Y>().unwrap().value,
1070            "Y should have the manually provided value"
1071        );
1072        assert_eq!(
1073            7,
1074            world.entity(id).get::<Z>().unwrap().0,
1075            "Z should have the value provided by the constructor defined in Y"
1076        );
1077
1078        let id = world.spawn((X, Z(8))).id();
1079        assert_eq!(
1080            "hello",
1081            world.entity(id).get::<Y>().unwrap().value,
1082            "Y should have the default value"
1083        );
1084        assert_eq!(
1085            8,
1086            world.entity(id).get::<Z>().unwrap().0,
1087            "Z should have the manually provided value"
1088        );
1089    }
1090
1091    #[test]
1092    fn runtime_required_components_override_1() {
1093        #[derive(Component)]
1094        struct X;
1095
1096        #[derive(Component, Default)]
1097        struct Y;
1098
1099        #[derive(Component)]
1100        struct Z(u32);
1101
1102        let mut world = World::new();
1103
1104        // - X requires Y with default constructor
1105        // - Y requires Z with custom constructor
1106        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1107        world.register_required_components::<X, Y>();
1108        world.register_required_components_with::<Y, Z>(|| Z(5));
1109        world.register_required_components_with::<X, Z>(|| Z(7));
1110
1111        let id = world.spawn(X).id();
1112
1113        assert_eq!(
1114            7,
1115            world.entity(id).get::<Z>().unwrap().0,
1116            "Z should have the value provided by the constructor defined in X"
1117        );
1118    }
1119
1120    #[test]
1121    fn runtime_required_components_override_2() {
1122        // Same as `runtime_required_components_override_1` test but with different registration order
1123
1124        #[derive(Component)]
1125        struct X;
1126
1127        #[derive(Component, Default)]
1128        struct Y;
1129
1130        #[derive(Component)]
1131        struct Z(u32);
1132
1133        let mut world = World::new();
1134
1135        // - X requires Y with default constructor
1136        // - X requires Z with custom constructor (more specific than X -> Y -> Z)
1137        // - Y requires Z with custom constructor
1138        world.register_required_components::<X, Y>();
1139        world.register_required_components_with::<X, Z>(|| Z(7));
1140        world.register_required_components_with::<Y, Z>(|| Z(5));
1141
1142        let id = world.spawn(X).id();
1143
1144        assert_eq!(
1145            7,
1146            world.entity(id).get::<Z>().unwrap().0,
1147            "Z should have the value provided by the constructor defined in X"
1148        );
1149    }
1150
1151    #[test]
1152    fn runtime_required_components_propagate_up() {
1153        // `A` requires `B` directly.
1154        #[derive(Component)]
1155        #[require(B)]
1156        struct A;
1157
1158        #[derive(Component, Default)]
1159        struct B;
1160
1161        #[derive(Component, Default)]
1162        struct C;
1163
1164        let mut world = World::new();
1165
1166        // `B` requires `C` with a runtime registration.
1167        // `A` should also require `C` because it requires `B`.
1168        world.register_required_components::<B, C>();
1169
1170        let id = world.spawn(A).id();
1171
1172        assert!(world.entity(id).get::<C>().is_some());
1173    }
1174
1175    #[test]
1176    fn runtime_required_components_propagate_up_even_more() {
1177        #[derive(Component)]
1178        struct A;
1179
1180        #[derive(Component, Default)]
1181        struct B;
1182
1183        #[derive(Component, Default)]
1184        struct C;
1185
1186        #[derive(Component, Default)]
1187        struct D;
1188
1189        let mut world = World::new();
1190
1191        world.register_required_components::<A, B>();
1192        world.register_required_components::<B, C>();
1193        world.register_required_components::<C, D>();
1194
1195        let id = world.spawn(A).id();
1196
1197        assert!(world.entity(id).get::<D>().is_some());
1198    }
1199
1200    #[test]
1201    fn runtime_required_components_deep_require_does_not_override_shallow_require() {
1202        #[derive(Component)]
1203        struct A;
1204        #[derive(Component, Default)]
1205        struct B;
1206        #[derive(Component, Default)]
1207        struct C;
1208        #[derive(Component)]
1209        struct Counter(i32);
1210        #[derive(Component, Default)]
1211        struct D;
1212
1213        let mut world = World::new();
1214
1215        world.register_required_components::<A, B>();
1216        world.register_required_components::<B, C>();
1217        world.register_required_components::<C, D>();
1218        world.register_required_components_with::<D, Counter>(|| Counter(2));
1219        // This should replace the require constructor in A since it is
1220        // shallower.
1221        world.register_required_components_with::<C, Counter>(|| Counter(1));
1222
1223        let id = world.spawn(A).id();
1224
1225        // The "shallower" of the two components is used.
1226        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1227    }
1228
1229    #[test]
1230    fn runtime_required_components_deep_require_does_not_override_shallow_require_deep_subtree_after_shallow(
1231    ) {
1232        #[derive(Component)]
1233        struct A;
1234        #[derive(Component, Default)]
1235        struct B;
1236        #[derive(Component, Default)]
1237        struct C;
1238        #[derive(Component, Default)]
1239        struct D;
1240        #[derive(Component, Default)]
1241        struct E;
1242        #[derive(Component)]
1243        struct Counter(i32);
1244        #[derive(Component, Default)]
1245        struct F;
1246
1247        let mut world = World::new();
1248
1249        world.register_required_components::<A, B>();
1250        world.register_required_components::<B, C>();
1251        world.register_required_components::<C, D>();
1252        world.register_required_components::<D, E>();
1253        world.register_required_components_with::<E, Counter>(|| Counter(1));
1254        world.register_required_components_with::<F, Counter>(|| Counter(2));
1255        world.register_required_components::<E, F>();
1256
1257        let id = world.spawn(A).id();
1258
1259        // The "shallower" of the two components is used.
1260        assert_eq!(world.entity(id).get::<Counter>().unwrap().0, 1);
1261    }
1262
1263    #[test]
1264    fn runtime_required_components_existing_archetype() {
1265        #[derive(Component)]
1266        struct X;
1267
1268        #[derive(Component, Default)]
1269        struct Y;
1270
1271        let mut world = World::new();
1272
1273        // Registering required components after the archetype has already been created should panic.
1274        // This may change in the future.
1275        world.spawn(X);
1276        assert!(matches!(
1277            world.try_register_required_components::<X, Y>(),
1278            Err(RequiredComponentsError::ArchetypeExists(_))
1279        ));
1280    }
1281
1282    #[test]
1283    fn runtime_required_components_fail_with_duplicate() {
1284        #[derive(Component)]
1285        #[require(Y)]
1286        struct X;
1287
1288        #[derive(Component, Default)]
1289        struct Y;
1290
1291        let mut world = World::new();
1292
1293        // This should fail: Tried to register Y as a requirement for X, but the requirement already exists.
1294        assert!(matches!(
1295            world.try_register_required_components::<X, Y>(),
1296            Err(RequiredComponentsError::DuplicateRegistration(_, _))
1297        ));
1298    }
1299
1300    #[test]
1301    fn required_components_bundle_priority() {
1302        #[derive(Component, PartialEq, Eq, Clone, Copy, Debug)]
1303        struct MyRequired(bool);
1304
1305        #[derive(Component, Default)]
1306        #[require(MyRequired(false))]
1307        struct MiddleMan;
1308
1309        #[derive(Component, Default)]
1310        #[require(MiddleMan)]
1311        struct ConflictingRequire;
1312
1313        #[derive(Component, Default)]
1314        #[require(MyRequired(true))]
1315        struct MyComponent;
1316
1317        let mut world = World::new();
1318        let order_a = world
1319            .spawn((ConflictingRequire, MyComponent))
1320            .get::<MyRequired>()
1321            .cloned();
1322        let order_b = world
1323            .spawn((MyComponent, ConflictingRequire))
1324            .get::<MyRequired>()
1325            .cloned();
1326
1327        assert_eq!(order_a, Some(MyRequired(false)));
1328        assert_eq!(order_b, Some(MyRequired(true)));
1329    }
1330
1331    #[test]
1332    #[should_panic]
1333    fn required_components_recursion_errors() {
1334        #[derive(Component, Default)]
1335        #[require(B)]
1336        struct A;
1337
1338        #[derive(Component, Default)]
1339        #[require(C)]
1340        struct B;
1341
1342        #[derive(Component, Default)]
1343        #[require(B)]
1344        struct C;
1345
1346        World::new().register_component::<A>();
1347    }
1348
1349    #[test]
1350    #[should_panic]
1351    fn required_components_self_errors() {
1352        #[derive(Component, Default)]
1353        #[require(A)]
1354        struct A;
1355
1356        World::new().register_component::<A>();
1357    }
1358
1359    #[test]
1360    fn regression_19333() {
1361        #[derive(Component)]
1362        struct X(usize);
1363
1364        #[derive(Default, Component)]
1365        #[require(X(0))]
1366        struct Base;
1367
1368        #[derive(Default, Component)]
1369        #[require(X(1), Base)]
1370        struct A;
1371
1372        #[derive(Default, Component)]
1373        #[require(A, Base)]
1374        struct B;
1375
1376        #[derive(Default, Component)]
1377        #[require(B, Base)]
1378        struct C;
1379
1380        let mut w = World::new();
1381
1382        assert_eq!(w.spawn(B).get::<X>().unwrap().0, 1);
1383        assert_eq!(w.spawn(C).get::<X>().unwrap().0, 1);
1384    }
1385
1386    #[test]
1387    fn required_components_depth_first_2v1() {
1388        #[derive(Component)]
1389        struct X(usize);
1390
1391        #[derive(Component)]
1392        #[require(Left, Right)]
1393        struct Root;
1394
1395        #[derive(Component, Default)]
1396        #[require(LeftLeft)]
1397        struct Left;
1398
1399        #[derive(Component, Default)]
1400        #[require(X(0))] // This is at depth 2 but is more on the left of the tree
1401        struct LeftLeft;
1402
1403        #[derive(Component, Default)]
1404        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1405        struct Right;
1406
1407        let mut world = World::new();
1408
1409        // LeftLeft should have priority over Right
1410        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1411    }
1412
1413    #[test]
1414    fn required_components_depth_first_3v1() {
1415        #[derive(Component)]
1416        struct X(usize);
1417
1418        #[derive(Component)]
1419        #[require(Left, Right)]
1420        struct Root;
1421
1422        #[derive(Component, Default)]
1423        #[require(LeftLeft)]
1424        struct Left;
1425
1426        #[derive(Component, Default)]
1427        #[require(LeftLeftLeft)]
1428        struct LeftLeft;
1429
1430        #[derive(Component, Default)]
1431        #[require(X(0))] // This is at depth 3 but is more on the left of the tree
1432        struct LeftLeftLeft;
1433
1434        #[derive(Component, Default)]
1435        #[require(X(1))] //. This is at depth 1 but is more on the right of the tree
1436        struct Right;
1437
1438        let mut world = World::new();
1439
1440        // LeftLeftLeft should have priority over Right
1441        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1442    }
1443
1444    #[test]
1445    fn runtime_required_components_depth_first_2v1() {
1446        #[derive(Component)]
1447        struct X(usize);
1448
1449        #[derive(Component)]
1450        struct Root;
1451
1452        #[derive(Component, Default)]
1453        struct Left;
1454
1455        #[derive(Component, Default)]
1456        struct LeftLeft;
1457
1458        #[derive(Component, Default)]
1459        struct Right;
1460
1461        // Register bottom up: registering higher level components should pick up lower level ones.
1462        let mut world = World::new();
1463        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1464        world.register_required_components_with::<Right, X>(|| X(1));
1465        world.register_required_components::<Left, LeftLeft>();
1466        world.register_required_components::<Root, Left>();
1467        world.register_required_components::<Root, Right>();
1468        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1469
1470        // Register top down: registering lower components should propagate to higher ones
1471        let mut world = World::new();
1472        world.register_required_components::<Root, Left>(); // Note: still register Left before Right
1473        world.register_required_components::<Root, Right>();
1474        world.register_required_components::<Left, LeftLeft>();
1475        world.register_required_components_with::<Right, X>(|| X(1));
1476        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1477        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1478
1479        // Register top down again, but this time LeftLeft before Right
1480        let mut world = World::new();
1481        world.register_required_components::<Root, Left>();
1482        world.register_required_components::<Root, Right>();
1483        world.register_required_components::<Left, LeftLeft>();
1484        world.register_required_components_with::<LeftLeft, X>(|| X(0));
1485        world.register_required_components_with::<Right, X>(|| X(1));
1486        assert_eq!(world.spawn(Root).get::<X>().unwrap().0, 0);
1487    }
1488
1489    #[test]
1490    fn runtime_required_components_propagate_metadata_alternate() {
1491        #[derive(Component, Default)]
1492        #[require(L1)]
1493        struct L0;
1494
1495        #[derive(Component, Default)]
1496        struct L1;
1497
1498        #[derive(Component, Default)]
1499        #[require(L3)]
1500        struct L2;
1501
1502        #[derive(Component, Default)]
1503        struct L3;
1504
1505        #[derive(Component, Default)]
1506        #[require(L5)]
1507        struct L4;
1508
1509        #[derive(Component, Default)]
1510        struct L5;
1511
1512        // Try to piece the 3 requirements together
1513        let mut world = World::new();
1514        world.register_required_components::<L1, L2>();
1515        world.register_required_components::<L3, L4>();
1516        let e = world.spawn(L0).id();
1517        assert!(world
1518            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1519            .get(&world, e)
1520            .is_ok());
1521
1522        // Repeat but in the opposite order
1523        let mut world = World::new();
1524        world.register_required_components::<L3, L4>();
1525        world.register_required_components::<L1, L2>();
1526        let e = world.spawn(L0).id();
1527        assert!(world
1528            .query::<(&L0, &L1, &L2, &L3, &L4, &L5)>()
1529            .get(&world, e)
1530            .is_ok());
1531    }
1532
1533    #[test]
1534    fn runtime_required_components_propagate_metadata_chain() {
1535        #[derive(Component, Default)]
1536        #[require(L1)]
1537        struct L0;
1538
1539        #[derive(Component, Default)]
1540        struct L1;
1541
1542        #[derive(Component, Default)]
1543        struct L2;
1544
1545        #[derive(Component, Default)]
1546        #[require(L4)]
1547        struct L3;
1548
1549        #[derive(Component, Default)]
1550        struct L4;
1551
1552        // Try to piece the 3 requirements together
1553        let mut world = World::new();
1554        world.register_required_components::<L1, L2>();
1555        world.register_required_components::<L2, L3>();
1556        let e = world.spawn(L0).id();
1557        assert!(world
1558            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1559            .get(&world, e)
1560            .is_ok());
1561
1562        // Repeat but in the opposite order
1563        let mut world = World::new();
1564        world.register_required_components::<L2, L3>();
1565        world.register_required_components::<L1, L2>();
1566        let e = world.spawn(L0).id();
1567        assert!(world
1568            .query::<(&L0, &L1, &L2, &L3, &L4)>()
1569            .get(&world, e)
1570            .is_ok());
1571    }
1572
1573    #[test]
1574    fn runtime_required_components_cyclic() {
1575        #[derive(Component, Default)]
1576        #[require(B)]
1577        struct A;
1578
1579        #[derive(Component, Default)]
1580        struct B;
1581
1582        #[derive(Component, Default)]
1583        struct C;
1584
1585        let mut world = World::new();
1586
1587        assert!(world.try_register_required_components::<B, C>().is_ok());
1588        assert!(matches!(
1589            world.try_register_required_components::<C, A>(),
1590            Err(RequiredComponentsError::CyclicRequirement(_, _))
1591        ));
1592    }
1593}