diff --git a/benches/benches/bevy_ecs/entity_cloning.rs b/benches/benches/bevy_ecs/entity_cloning.rs index 44ffa1d52b993..a35b68c27ef5d 100644 --- a/benches/benches/bevy_ecs/entity_cloning.rs +++ b/benches/benches/bevy_ecs/entity_cloning.rs @@ -1,7 +1,7 @@ use core::hint::black_box; use benches::bench; -use bevy_ecs::bundle::{Bundle, InsertMode}; +use bevy_ecs::bundle::{Bundle, InsertMode, StaticBundle}; use bevy_ecs::component::ComponentCloneBehavior; use bevy_ecs::entity::EntityCloner; use bevy_ecs::hierarchy::ChildOf; @@ -27,7 +27,7 @@ type ComplexBundle = (C<1>, C<2>, C<3>, C<4>, C<5>, C<6>, C<7>, C<8>, C<9>, C<10 /// Sets the [`ComponentCloneBehavior`] for all explicit and required components in a bundle `B` to /// use the [`Reflect`] trait instead of [`Clone`]. -fn reflection_cloner( +fn reflection_cloner( world: &mut World, linked_cloning: bool, ) -> EntityCloner { @@ -65,7 +65,7 @@ fn reflection_cloner( /// components (which is usually [`ComponentCloneBehavior::clone()`]). If `clone_via_reflect` /// is true, it will overwrite the handler for all components in the bundle to be /// [`ComponentCloneBehavior::reflect()`]. -fn bench_clone( +fn bench_clone( b: &mut Bencher, clone_via_reflect: bool, ) { @@ -96,7 +96,7 @@ fn bench_clone( /// For example, setting `height` to 5 and `children` to 1 creates a single chain of entities with /// no siblings. Alternatively, setting `height` to 1 and `children` to 5 will spawn 5 direct /// children of the root entity. -fn bench_clone_hierarchy( +fn bench_clone_hierarchy( b: &mut Bencher, height: usize, children: usize, @@ -268,7 +268,7 @@ const FILTER_SCENARIOS: [FilterScenario; 11] = [ /// /// The bundle must implement [`Default`], which is used to create the first entity that gets its components cloned /// in the benchmark. It may also be used to populate the target entity depending on the scenario. -fn bench_filter(b: &mut Bencher, scenario: FilterScenario) { +fn bench_filter(b: &mut Bencher, scenario: FilterScenario) { let mut world = World::default(); let mut spawn = |empty| match empty { false => world.spawn(B::default()).id(), diff --git a/benches/benches/bevy_ecs/world/world_get.rs b/benches/benches/bevy_ecs/world/world_get.rs index e6e2a0bb903ef..23f1dd9b9271c 100644 --- a/benches/benches/bevy_ecs/world/world_get.rs +++ b/benches/benches/bevy_ecs/world/world_get.rs @@ -2,7 +2,7 @@ use core::hint::black_box; use nonmax::NonMaxU32; use bevy_ecs::{ - bundle::{Bundle, NoBundleEffect}, + bundle::{Bundle, NoBundleEffect, StaticBundle}, component::Component, entity::{Entity, EntityRow}, system::{Query, SystemState}, @@ -37,7 +37,9 @@ fn setup(entity_count: u32) -> World { black_box(world) } -fn setup_wide + Default>(entity_count: u32) -> World { +fn setup_wide + StaticBundle + Default>( + entity_count: u32, +) -> World { let mut world = World::default(); world.spawn_batch((0..entity_count).map(|_| T::default())); black_box(world) diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 05f3de27b116f..0425a6f181410 100644 --- a/crates/bevy_app/src/app.rs +++ b/crates/bevy_app/src/app.rs @@ -9,6 +9,7 @@ use alloc::{ }; pub use bevy_derive::AppLabel; use bevy_ecs::{ + bundle::StaticBundle, component::RequiredComponentsError, error::{DefaultErrorHandler, ErrorHandler}, event::{event_update_system, EventCursor}, @@ -1340,7 +1341,7 @@ impl App { /// } /// }); /// ``` - pub fn add_observer( + pub fn add_observer( &mut self, observer: impl IntoObserverSystem, ) -> &mut Self { diff --git a/crates/bevy_ecs/macros/src/lib.rs b/crates/bevy_ecs/macros/src/lib.rs index 9bc3e5913e9ba..57d62da183646 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -28,18 +28,21 @@ enum BundleFieldKind { } const BUNDLE_ATTRIBUTE_NAME: &str = "bundle"; +const BUNDLE_ATTRIBUTE_DYNAMIC: &str = "dynamic"; const BUNDLE_ATTRIBUTE_IGNORE_NAME: &str = "ignore"; const BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS: &str = "ignore_from_components"; #[derive(Debug)] struct BundleAttributes { impl_from_components: bool, + dynamic: bool, } impl Default for BundleAttributes { fn default() -> Self { Self { impl_from_components: true, + dynamic: false, } } } @@ -61,8 +64,12 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { attributes.impl_from_components = false; return Ok(()); } + if meta.path.is_ident(BUNDLE_ATTRIBUTE_DYNAMIC) { + attributes.dynamic = true; + return Ok(()); + } - Err(meta.error(format!("Invalid bundle container attribute. Allowed attributes: `{BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS}`"))) + Err(meta.error(format!("Invalid bundle container attribute. Allowed attributes: `{BUNDLE_ATTRIBUTE_NO_FROM_COMPONENTS}`, `{BUNDLE_ATTRIBUTE_DYNAMIC}`"))) }); if let Err(error) = parsing { @@ -139,6 +146,37 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); let struct_name = &ast.ident; + let static_bundle_impl = (!attributes.dynamic).then(|| quote! { + // SAFETY: + // - all the active fields must implement `StaticBundle` for the function bodies to compile, and hence + // this bundle also represents a static set of components; + // - `component_ids` and `get_component_ids` delegate to the underlying implementation in the same order + // and hence are coherent; + #[allow(deprecated)] + unsafe impl #impl_generics #ecs_path::bundle::StaticBundle for #struct_name #ty_generics #where_clause { + fn component_ids( + components: &mut #ecs_path::component::ComponentsRegistrator, + ids: &mut impl FnMut(#ecs_path::component::ComponentId) + ){ + #(<#active_field_types as #ecs_path::bundle::StaticBundle>::component_ids(components, &mut *ids);)* + } + + fn get_component_ids( + components: &#ecs_path::component::Components, + ids: &mut impl FnMut(Option<#ecs_path::component::ComponentId>) + ){ + #(<#active_field_types as #ecs_path::bundle::StaticBundle>::get_component_ids(components, &mut *ids);)* + } + + fn register_required_components( + components: &mut #ecs_path::component::ComponentsRegistrator, + required_components: &mut #ecs_path::component::RequiredComponents + ){ + #(<#active_field_types as #ecs_path::bundle::StaticBundle>::register_required_components(components, &mut *required_components);)* + } + } + }); + let bundle_impl = quote! { // SAFETY: // - ComponentId is returned in field-definition-order. [get_components] uses field-definition-order @@ -147,24 +185,27 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { #[allow(deprecated)] unsafe impl #impl_generics #ecs_path::bundle::Bundle for #struct_name #ty_generics #where_clause { fn component_ids( + &self, components: &mut #ecs_path::component::ComponentsRegistrator, ids: &mut impl FnMut(#ecs_path::component::ComponentId) ) { - #(<#active_field_types as #ecs_path::bundle::Bundle>::component_ids(components, ids);)* + #(<#active_field_types as #ecs_path::bundle::Bundle>::component_ids(&self.#active_field_tokens, components, ids);)* } fn get_component_ids( + &self, components: &#ecs_path::component::Components, ids: &mut impl FnMut(Option<#ecs_path::component::ComponentId>) ) { - #(<#active_field_types as #ecs_path::bundle::Bundle>::get_component_ids(components, &mut *ids);)* + #(<#active_field_types as #ecs_path::bundle::Bundle>::get_component_ids(&self.#active_field_tokens, components, &mut *ids);)* } fn register_required_components( + &self, components: &mut #ecs_path::component::ComponentsRegistrator, required_components: &mut #ecs_path::component::RequiredComponents ) { - #(<#active_field_types as #ecs_path::bundle::Bundle>::register_required_components(components, required_components);)* + #(<#active_field_types as #ecs_path::bundle::Bundle>::register_required_components(&self.#active_field_tokens, components, required_components);)* } } }; @@ -184,7 +225,7 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { } }; - let from_components_impl = attributes.impl_from_components.then(|| quote! { + let from_components_impl = (attributes.impl_from_components && !attributes.dynamic).then(|| quote! { // SAFETY: // - ComponentId is returned in field-definition-order. [from_components] uses field-definition-order #[allow(deprecated)] @@ -206,6 +247,7 @@ pub fn derive_bundle(input: TokenStream) -> TokenStream { TokenStream::from(quote! { #(#attribute_errors)* + #static_bundle_impl #bundle_impl #from_components_impl #dynamic_bundle_impl diff --git a/crates/bevy_ecs/src/bundle.rs b/crates/bevy_ecs/src/bundle.rs index 8efdc60ad9345..61610cdd89d8a 100644 --- a/crates/bevy_ecs/src/bundle.rs +++ b/crates/bevy_ecs/src/bundle.rs @@ -81,11 +81,13 @@ use bevy_utils::TypeIdMap; use core::{any::TypeId, ptr::NonNull}; use variadics_please::all_tuples; -/// The `Bundle` trait enables insertion and removal of [`Component`]s from an entity. +/// A collection of components, whose identity may or may not be fixed at compile time. +/// +/// The `Bundle` trait enables insertion of [`Component`]s to an entity. +/// For the removal of [`Component`]s from an entity see the [`StaticBundle`]`trait`. /// /// Implementers of the `Bundle` trait are called 'bundles'. /// -/// Each bundle represents a static set of [`Component`] types. /// Currently, bundles can only contain one of each [`Component`], and will /// panic once initialized if this is not met. /// @@ -115,15 +117,6 @@ use variadics_please::all_tuples; /// contains the components of a bundle. /// Queries should instead only select the components they logically operate on. /// -/// ## Removal -/// -/// Bundles are also used when removing components from an entity. -/// -/// Removing a bundle from an entity will remove any of its components attached -/// to the entity from the entity. -/// That is, if the entity does not have all the components of the bundle, those -/// which are present will be removed. -/// /// # Implementers /// /// Every type which implements [`Component`] also implements `Bundle`, since @@ -195,6 +188,8 @@ use variadics_please::all_tuples; // bundle, in the _exact_ order that [`DynamicBundle::get_components`] is called. // - [`Bundle::from_components`] must call `func` exactly once for each [`ComponentId`] returned by // [`Bundle::component_ids`]. +// - [`Bundle::component_ids`], [`Bundle::get_component_ids`] and [`Bundle::register_required_components`] +// cannot depend on `self` for now. #[diagnostic::on_unimplemented( message = "`{Self}` is not a `Bundle`", label = "invalid `Bundle`", @@ -203,19 +198,68 @@ use variadics_please::all_tuples; pub unsafe trait Bundle: DynamicBundle + Send + Sync + 'static { /// Gets this [`Bundle`]'s component ids, in the order of this bundle's [`Component`]s #[doc(hidden)] - fn component_ids(components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)); + fn component_ids( + &self, + components: &mut ComponentsRegistrator, + ids: &mut impl FnMut(ComponentId), + ); /// Gets this [`Bundle`]'s component ids. This will be [`None`] if the component has not been registered. - fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)); + fn get_component_ids(&self, components: &Components, ids: &mut impl FnMut(Option)); /// Registers components that are required by the components in this [`Bundle`]. fn register_required_components( + &self, _components: &mut ComponentsRegistrator, _required_components: &mut RequiredComponents, ); } -/// Creates a [`Bundle`] by taking it from internal storage. +/// A static and fixed set of [`Component`] types. +/// See the [`Bundle`] trait for a possibly dynamic set of [`Component`] types. +/// +/// Implementers of the [`StaticBundle`] trait are called 'static bundles'. +/// +/// ## Removal +/// +/// Static bundles are used when removing components from an entity. +/// +/// Removing a bundle from an entity will remove any of its components attached +/// to the entity from the entity. +/// That is, if the entity does not have all the components of the bundle, those +/// which are present will be removed. +/// +/// # Safety +/// +/// Manual implementations of this trait are unsupported. +/// That is, there is no safe way to implement this trait, and you must not do so. +/// If you want a type to implement [`StaticBundle`], you must use [`derive@Bundle`](derive@Bundle). +// +// (bevy internal doc) Some safety points: +// - [`StaticBundle::component_ids`] and [`StaticBundle::get_component_ids`] must match the behavior of [`Bundle::component_ids`] +#[diagnostic::on_unimplemented( + message = "`{Self}` is not a `StaticBundle`", + label = "invalid `StaticBundle`", + note = "consider annotating `{Self}` with `#[derive(Component)]` or `#[derive(Bundle)]`" +)] +pub unsafe trait StaticBundle: Send + Sync + 'static { + /// Gets this [`StaticBundle`]'s component ids, in the order of this bundle's [`Component`]s + #[doc(hidden)] + fn component_ids(components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)); + + /// Gets this [`StaticBundle`]'s component ids. This will be [`None`] if the component has not been registered. + #[doc(hidden)] + fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)); + + /// Registers components that are required by the components in this [`StaticBundle`]. + #[doc(hidden)] + fn register_required_components( + _components: &mut ComponentsRegistrator, + _required_components: &mut RequiredComponents, + ); +} + +/// Creates a bundle by taking it from the internal storage. /// /// # Safety /// @@ -272,13 +316,17 @@ pub trait BundleEffect { } // SAFETY: -// - `Bundle::component_ids` calls `ids` for C's component id (and nothing else) -// - `Bundle::get_components` is called exactly once for C and passes the component's storage type based on its associated constant. -unsafe impl Bundle for C { +// - `C` always represents the set of components containing just `C` +// - `component_ids` and `get_component_ids` both call `ids` just once for C's component id (and nothing else). +unsafe impl StaticBundle for C { fn component_ids(components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)) { ids(components.register_component::()); } + fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)) { + ids(components.get_id(TypeId::of::())); + } + fn register_required_components( components: &mut ComponentsRegistrator, required_components: &mut RequiredComponents, @@ -292,9 +340,34 @@ unsafe impl Bundle for C { &mut Vec::new(), ); } +} - fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)) { - ids(components.get_id(TypeId::of::())); +// SAFETY: +// - `component_ids` calls `ids` for C's component id (and nothing else) +// - `get_components` is called exactly once for C and passes the component's storage type based on its associated constant. +unsafe impl Bundle for C { + fn component_ids( + &self, + components: &mut ComponentsRegistrator, + ids: &mut impl FnMut(ComponentId), + ) { + ::component_ids(components, ids); + } + + fn get_component_ids( + &self, + components: &Components, + ids: &mut impl FnMut(Option), + ) { + ::get_component_ids(components, ids); + } + + fn register_required_components( + &self, + components: &mut ComponentsRegistrator, + required_components: &mut RequiredComponents, + ) { + ::register_required_components(components, required_components); } } @@ -323,6 +396,37 @@ impl DynamicBundle for C { macro_rules! tuple_impl { ($(#[$meta:meta])* $($name: ident),*) => { + #[expect( + clippy::allow_attributes, + reason = "This is a tuple-related macro; as such, the lints below may not always apply." + )] + #[allow( + unused_mut, + unused_variables, + reason = "Zero-length tuples won't use any of the parameters." + )] + $(#[$meta])* + // SAFETY: + // - all the sub-bundles are static, and hence their combination is static too; + // - `component_ids` and `get_component_ids` both delegate to the sub-bundle's methods + // exactly once per sub-bundle, hence they are coherent. + unsafe impl<$($name: StaticBundle),*> StaticBundle for ($($name,)*) { + fn component_ids(components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)){ + $(<$name as StaticBundle>::component_ids(components, ids);)* + } + + fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)){ + $(<$name as StaticBundle>::get_component_ids(components, ids);)* + } + + fn register_required_components( + components: &mut ComponentsRegistrator, + required_components: &mut RequiredComponents, + ) { + $(<$name as StaticBundle>::register_required_components(components, required_components);)* + } + } + #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such, the lints below may not always apply." @@ -340,19 +444,38 @@ macro_rules! tuple_impl { // - `Bundle::get_components` is called exactly once for each member. Relies on the above implementation to pass the correct // `StorageType` into the callback. unsafe impl<$($name: Bundle),*> Bundle for ($($name,)*) { - fn component_ids(components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)){ - $(<$name as Bundle>::component_ids(components, ids);)* + fn component_ids(&self, components: &mut ComponentsRegistrator, ids: &mut impl FnMut(ComponentId)){ + #[allow( + non_snake_case, + reason = "The names of these variables are provided by the caller, not by us." + )] + let ($($name,)*) = self; + + $(<$name as Bundle>::component_ids($name, components, ids);)* } - fn get_component_ids(components: &Components, ids: &mut impl FnMut(Option)){ - $(<$name as Bundle>::get_component_ids(components, ids);)* + fn get_component_ids(&self, components: &Components, ids: &mut impl FnMut(Option)){ + #[allow( + non_snake_case, + reason = "The names of these variables are provided by the caller, not by us." + )] + let ($($name,)*) = self; + + $(<$name as Bundle>::get_component_ids($name, components, ids);)* } fn register_required_components( + &self, components: &mut ComponentsRegistrator, required_components: &mut RequiredComponents, ) { - $(<$name as Bundle>::register_required_components(components, required_components);)* + #[allow( + non_snake_case, + reason = "The names of these variables are provided by the caller, not by us." + )] + let ($($name,)*) = self; + + $(<$name as Bundle>::register_required_components($name, components, required_components);)* } } @@ -1057,6 +1180,7 @@ pub(crate) enum ArchetypeMoveType { impl<'w> BundleInserter<'w> { #[inline] pub(crate) fn new( + bundle: &T, world: &'w mut World, archetype_id: ArchetypeId, change_tick: Tick, @@ -1064,9 +1188,10 @@ impl<'w> BundleInserter<'w> { // SAFETY: These come from the same world. `world.components_registrator` can't be used since we borrow other fields too. let mut registrator = unsafe { ComponentsRegistrator::new(&mut world.components, &mut world.component_ids) }; - let bundle_id = world - .bundles - .register_info::(&mut registrator, &mut world.storages); + let bundle_id = + world + .bundles + .register_info::(bundle, &mut registrator, &mut world.storages); // SAFETY: We just ensured this bundle exists unsafe { Self::new_with_id(world, archetype_id, bundle_id, change_tick) } } @@ -1449,7 +1574,7 @@ impl<'w> BundleRemover<'w> { /// # Safety /// Caller must ensure that `archetype_id` is valid #[inline] - pub(crate) unsafe fn new( + pub(crate) unsafe fn new( world: &'w mut World, archetype_id: ArchetypeId, require_all: bool, @@ -1459,7 +1584,7 @@ impl<'w> BundleRemover<'w> { unsafe { ComponentsRegistrator::new(&mut world.components, &mut world.component_ids) }; let bundle_id = world .bundles - .register_info::(&mut registrator, &mut world.storages); + .register_static_info::(&mut registrator, &mut world.storages); // SAFETY: we initialized this bundle_id in `init_info`, and caller ensures archetype is valid. unsafe { Self::new_with_id(world, archetype_id, bundle_id, require_all) } } @@ -1720,14 +1845,25 @@ pub(crate) struct BundleSpawner<'w> { } impl<'w> BundleSpawner<'w> { + pub fn new(bundle: &T, world: &'w mut World, change_tick: Tick) -> Self { + // SAFETY: These come from the same world. `world.components_registrator` can't be used since we borrow other fields too. + let mut registrator = + unsafe { ComponentsRegistrator::new(&mut world.components, &mut world.component_ids) }; + let bundle_id = world + .bundles + .register_info(bundle, &mut registrator, &mut world.storages); + // SAFETY: we initialized this bundle_id in `init_info` + unsafe { Self::new_with_id(world, bundle_id, change_tick) } + } + #[inline] - pub fn new(world: &'w mut World, change_tick: Tick) -> Self { + pub fn new_static(world: &'w mut World, change_tick: Tick) -> Self { // SAFETY: These come from the same world. `world.components_registrator` can't be used since we borrow other fields too. let mut registrator = unsafe { ComponentsRegistrator::new(&mut world.components, &mut world.component_ids) }; let bundle_id = world .bundles - .register_info::(&mut registrator, &mut world.storages); + .register_static_info::(&mut registrator, &mut world.storages); // SAFETY: we initialized this bundle_id in `init_info` unsafe { Self::new_with_id(world, bundle_id, change_tick) } } @@ -1934,18 +2070,40 @@ impl Bundles { self.bundle_ids.get(&type_id).cloned() } + pub(crate) fn register_static_info( + &mut self, + components: &mut ComponentsRegistrator, + storages: &mut Storages, + ) -> BundleId { + let bundle_infos = &mut self.bundle_infos; + *self.bundle_ids.entry(TypeId::of::()).or_insert_with(|| { + let mut component_ids= Vec::new(); + T::component_ids(components, &mut |id| component_ids.push(id)); + let id = BundleId(bundle_infos.len()); + let bundle_info = + // SAFETY: T::component_id ensures: + // - its info was created + // - appropriate storage for it has been initialized. + // - it was created in the same order as the components in T + unsafe { BundleInfo::new(core::any::type_name::(), storages, components, component_ids, id) }; + bundle_infos.push(bundle_info); + id + }) + } + /// Registers a new [`BundleInfo`] for a statically known type. /// /// Also registers all the components in the bundle. pub(crate) fn register_info( &mut self, + bundle: &T, components: &mut ComponentsRegistrator, storages: &mut Storages, ) -> BundleId { let bundle_infos = &mut self.bundle_infos; *self.bundle_ids.entry(TypeId::of::()).or_insert_with(|| { let mut component_ids= Vec::new(); - T::component_ids(components, &mut |id| component_ids.push(id)); + bundle.component_ids(components, &mut |id| component_ids.push(id)); let id = BundleId(bundle_infos.len()); let bundle_info = // SAFETY: T::component_id ensures: @@ -1961,7 +2119,7 @@ impl Bundles { /// Registers a new [`BundleInfo`], which contains both explicit and required components for a statically known type. /// /// Also registers all the components in the bundle. - pub(crate) fn register_contributed_bundle_info( + pub(crate) fn register_contributed_bundle_info( &mut self, components: &mut ComponentsRegistrator, storages: &mut Storages, @@ -1969,7 +2127,7 @@ impl Bundles { if let Some(id) = self.contributed_bundle_ids.get(&TypeId::of::()).cloned() { id } else { - let explicit_bundle_id = self.register_info::(components, storages); + let explicit_bundle_id = self.register_static_info::(components, storages); // SAFETY: reading from `explicit_bundle_id` and creating new bundle in same time. Its valid because bundle hashmap allow this let id = unsafe { let (ptr, len) = { diff --git a/crates/bevy_ecs/src/entity/clone_entities.rs b/crates/bevy_ecs/src/entity/clone_entities.rs index 08da93c2619a3..79051f620c127 100644 --- a/crates/bevy_ecs/src/entity/clone_entities.rs +++ b/crates/bevy_ecs/src/entity/clone_entities.rs @@ -8,7 +8,7 @@ use derive_more::derive::From; use crate::{ archetype::Archetype, - bundle::{Bundle, BundleId, InsertMode}, + bundle::{BundleId, InsertMode, StaticBundle}, component::{Component, ComponentCloneBehavior, ComponentCloneFn, ComponentId, ComponentInfo}, entity::{hash_map::EntityHashMap, Entities, Entity, EntityMapper}, query::DebugCheckedUnwrap, @@ -793,7 +793,7 @@ impl<'w> EntityClonerBuilder<'w, OptOut> { /// If component `A` is denied here and component `B` requires `A`, then `A` /// is denied as well. See [`Self::without_required_by_components`] to alter /// this behavior. - pub fn deny(&mut self) -> &mut Self { + pub fn deny(&mut self) -> &mut Self { let bundle_id = self.world.register_bundle::().id(); self.deny_by_bundle_id(bundle_id) } @@ -863,7 +863,7 @@ impl<'w> EntityClonerBuilder<'w, OptIn> { /// If component `A` is allowed here and requires component `B`, then `B` /// is allowed as well. See [`Self::without_required_components`] /// to alter this behavior. - pub fn allow(&mut self) -> &mut Self { + pub fn allow(&mut self) -> &mut Self { let bundle_id = self.world.register_bundle::().id(); self.allow_by_bundle_id(bundle_id) } @@ -874,7 +874,7 @@ impl<'w> EntityClonerBuilder<'w, OptIn> { /// If component `A` is allowed here and requires component `B`, then `B` /// is allowed as well. See [`Self::without_required_components`] /// to alter this behavior. - pub fn allow_if_new(&mut self) -> &mut Self { + pub fn allow_if_new(&mut self) -> &mut Self { let bundle_id = self.world.register_bundle::().id(); self.allow_by_bundle_id_if_new(bundle_id) } diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index 86275cd87f4a3..9eb46d0e8a4ed 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -145,7 +145,7 @@ pub struct HotPatched; #[cfg(test)] mod tests { use crate::{ - bundle::Bundle, + bundle::{Bundle, StaticBundle}, change_detection::Ref, component::{Component, ComponentId, RequiredComponents, RequiredComponentsError}, entity::{Entity, EntityMapper}, @@ -241,11 +241,18 @@ mod tests { x: TableStored, y: SparseStored, } - let mut ids = Vec::new(); - ::component_ids(&mut world.components_registrator(), &mut |id| { - ids.push(id); - }); + let mut ids = Vec::new(); + ::component_ids( + &FooBundle { + x: TableStored("abc"), + y: SparseStored(123), + }, + &mut world.components_registrator(), + &mut |id| { + ids.push(id); + }, + ); assert_eq!( ids, &[ @@ -254,6 +261,21 @@ mod tests { ] ); + let mut static_ids = Vec::new(); + ::component_ids( + &mut world.components_registrator(), + &mut |id| { + static_ids.push(id); + }, + ); + assert_eq!( + static_ids, + &[ + world.register_component::(), + world.register_component::(), + ] + ); + let e1 = world .spawn(FooBundle { x: TableStored("abc"), @@ -292,10 +314,20 @@ mod tests { } let mut ids = Vec::new(); - ::component_ids(&mut world.components_registrator(), &mut |id| { - ids.push(id); - }); - + ::component_ids( + &NestedBundle { + a: A(1), + foo: FooBundle { + x: TableStored("ghi"), + y: SparseStored(789), + }, + b: B(2), + }, + &mut world.components_registrator(), + &mut |id| { + ids.push(id); + }, + ); assert_eq!( ids, &[ @@ -306,6 +338,23 @@ mod tests { ] ); + let mut static_ids = Vec::new(); + ::component_ids( + &mut world.components_registrator(), + &mut |id| { + static_ids.push(id); + }, + ); + assert_eq!( + static_ids, + &[ + world.register_component::(), + world.register_component::(), + world.register_component::(), + world.register_component::(), + ] + ); + let e3 = world .spawn(NestedBundle { a: A(1), @@ -345,13 +394,25 @@ mod tests { let mut ids = Vec::new(); ::component_ids( + &BundleWithIgnored { + c: C, + ignored: Ignored, + }, &mut world.components_registrator(), &mut |id| { ids.push(id); }, ); + assert_eq!(ids, &[world.register_component::()]); - assert_eq!(ids, &[world.register_component::(),]); + let mut static_ids = Vec::new(); + ::component_ids( + &mut world.components_registrator(), + &mut |id| { + static_ids.push(id); + }, + ); + assert_eq!(static_ids, &[world.register_component::()]); let e4 = world .spawn(BundleWithIgnored { diff --git a/crates/bevy_ecs/src/observer/distributed_storage.rs b/crates/bevy_ecs/src/observer/distributed_storage.rs index a9a36451211ed..37fc518bad671 100644 --- a/crates/bevy_ecs/src/observer/distributed_storage.rs +++ b/crates/bevy_ecs/src/observer/distributed_storage.rs @@ -12,6 +12,7 @@ use core::any::Any; use crate::{ + bundle::StaticBundle, component::{ComponentCloneBehavior, ComponentId, Mutable, StorageType}, entity::Entity, error::{ErrorContext, ErrorHandler}, @@ -217,7 +218,7 @@ impl Observer { /// # Panics /// /// Panics if the given system is an exclusive system. - pub fn new>(system: I) -> Self { + pub fn new>(system: I) -> Self { let system = Box::new(IntoObserverSystem::into_system(system)); assert!( !system.is_exclusive(), @@ -405,7 +406,7 @@ impl ObserverDescriptor { /// The type parameters of this function _must_ match those used to create the [`Observer`]. /// As such, it is recommended to only use this function within the [`Observer::new`] method to /// ensure type parameters match. -fn hook_on_add>( +fn hook_on_add>( mut world: DeferredWorld<'_>, HookContext { entity, .. }: HookContext, ) { diff --git a/crates/bevy_ecs/src/observer/mod.rs b/crates/bevy_ecs/src/observer/mod.rs index e9036eee74dcb..0288bda164351 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -143,6 +143,7 @@ pub use system_param::*; pub use trigger_targets::*; use crate::{ + bundle::StaticBundle, change_detection::MaybeLocation, component::ComponentId, prelude::*, @@ -179,7 +180,7 @@ impl World { /// # Panics /// /// Panics if the given system is an exclusive system. - pub fn add_observer( + pub fn add_observer( &mut self, system: impl IntoObserverSystem, ) -> EntityWorldMut { diff --git a/crates/bevy_ecs/src/observer/runner.rs b/crates/bevy_ecs/src/observer/runner.rs index acc2830a7d0a0..1c12feecca4f8 100644 --- a/crates/bevy_ecs/src/observer/runner.rs +++ b/crates/bevy_ecs/src/observer/runner.rs @@ -3,8 +3,8 @@ use core::any::Any; use crate::{ - error::ErrorContext, observer::ObserverTrigger, prelude::*, query::DebugCheckedUnwrap, - system::ObserverSystem, world::DeferredWorld, + bundle::StaticBundle, error::ErrorContext, observer::ObserverTrigger, prelude::*, + query::DebugCheckedUnwrap, system::ObserverSystem, world::DeferredWorld, }; use bevy_ptr::PtrMut; @@ -14,7 +14,7 @@ use bevy_ptr::PtrMut; /// but can be overridden for custom behavior. pub type ObserverRunner = fn(DeferredWorld, ObserverTrigger, PtrMut, propagate: &mut bool); -pub(super) fn observer_system_runner>( +pub(super) fn observer_system_runner>( mut world: DeferredWorld, observer_trigger: ObserverTrigger, ptr: PtrMut, diff --git a/crates/bevy_ecs/src/observer/system_param.rs b/crates/bevy_ecs/src/observer/system_param.rs index 27d6fef5b3a77..cfaffc56030fc 100644 --- a/crates/bevy_ecs/src/observer/system_param.rs +++ b/crates/bevy_ecs/src/observer/system_param.rs @@ -8,8 +8,8 @@ use bevy_ptr::Ptr; use smallvec::SmallVec; use crate::{ - bundle::Bundle, change_detection::MaybeLocation, component::ComponentId, event::EntityEvent, - prelude::*, + bundle::StaticBundle, change_detection::MaybeLocation, component::ComponentId, + event::EntityEvent, prelude::*, }; /// Type containing triggered [`Event`] information for a given run of an [`Observer`]. This contains the @@ -26,7 +26,7 @@ use crate::{ /// Providing multiple components in this bundle will cause this event to be triggered by any /// matching component in the bundle, /// [rather than requiring all of them to be present](https://github.com/bevyengine/bevy/issues/15325). -pub struct On<'w, E, B: Bundle = ()> { +pub struct On<'w, E, B: StaticBundle = ()> { event: &'w mut E, propagate: &'w mut bool, trigger: ObserverTrigger, @@ -37,7 +37,7 @@ pub struct On<'w, E, B: Bundle = ()> { #[deprecated(since = "0.17.0", note = "Renamed to `On`.")] pub type Trigger<'w, E, B = ()> = On<'w, E, B>; -impl<'w, E, B: Bundle> On<'w, E, B> { +impl<'w, E, B: StaticBundle> On<'w, E, B> { /// Creates a new instance of [`On`] for the given event and observer information. pub fn new(event: &'w mut E, propagate: &'w mut bool, trigger: ObserverTrigger) -> Self { Self { @@ -105,7 +105,7 @@ impl<'w, E, B: Bundle> On<'w, E, B> { } } -impl<'w, E: EntityEvent, B: Bundle> On<'w, E, B> { +impl<'w, E: EntityEvent, B: StaticBundle> On<'w, E, B> { /// Returns the [`Entity`] that was targeted by the `event` that triggered this observer. /// /// Note that if event propagation is enabled, this may not be the same as the original target of the event, @@ -149,7 +149,7 @@ impl<'w, E: EntityEvent, B: Bundle> On<'w, E, B> { } } -impl<'w, E: Debug, B: Bundle> Debug for On<'w, E, B> { +impl<'w, E: Debug, B: StaticBundle> Debug for On<'w, E, B> { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("On") .field("event", &self.event) @@ -160,7 +160,7 @@ impl<'w, E: Debug, B: Bundle> Debug for On<'w, E, B> { } } -impl<'w, E, B: Bundle> Deref for On<'w, E, B> { +impl<'w, E, B: StaticBundle> Deref for On<'w, E, B> { type Target = E; fn deref(&self) -> &Self::Target { @@ -168,7 +168,7 @@ impl<'w, E, B: Bundle> Deref for On<'w, E, B> { } } -impl<'w, E, B: Bundle> DerefMut for On<'w, E, B> { +impl<'w, E, B: StaticBundle> DerefMut for On<'w, E, B> { fn deref_mut(&mut self) -> &mut Self::Target { self.event } diff --git a/crates/bevy_ecs/src/query/fetch.rs b/crates/bevy_ecs/src/query/fetch.rs index 2564223972130..130620141780c 100644 --- a/crates/bevy_ecs/src/query/fetch.rs +++ b/crates/bevy_ecs/src/query/fetch.rs @@ -1,6 +1,6 @@ use crate::{ archetype::{Archetype, Archetypes}, - bundle::Bundle, + bundle::StaticBundle, change_detection::{MaybeLocation, Ticks, TicksMut}, component::{Component, ComponentId, Components, Mutable, StorageType, Tick}, entity::{Entities, Entity, EntityLocation}, @@ -1168,7 +1168,7 @@ unsafe impl<'a> QueryData for FilteredEntityMut<'a> { /// are rejected. unsafe impl<'a, B> WorldQuery for EntityRefExcept<'a, B> where - B: Bundle, + B: StaticBundle, { type Fetch<'w> = EntityFetch<'w>; type State = SmallVec<[ComponentId; 4]>; @@ -1243,7 +1243,7 @@ where /// SAFETY: `Self` is the same as `Self::ReadOnly`. unsafe impl<'a, B> QueryData for EntityRefExcept<'a, B> where - B: Bundle, + B: StaticBundle, { const IS_READ_ONLY: bool = true; type ReadOnly = Self; @@ -1271,14 +1271,14 @@ where /// SAFETY: `EntityRefExcept` enforces read-only access to its contained /// components. -unsafe impl<'a, B> ReadOnlyQueryData for EntityRefExcept<'a, B> where B: Bundle {} +unsafe impl<'a, B> ReadOnlyQueryData for EntityRefExcept<'a, B> where B: StaticBundle {} /// SAFETY: `EntityMutExcept` guards access to all components in the bundle `B` /// and populates `Access` values so that queries that conflict with this access /// are rejected. unsafe impl<'a, B> WorldQuery for EntityMutExcept<'a, B> where - B: Bundle, + B: StaticBundle, { type Fetch<'w> = EntityFetch<'w>; type State = SmallVec<[ComponentId; 4]>; @@ -1354,7 +1354,7 @@ where /// `EntityMutExcept` provides. unsafe impl<'a, B> QueryData for EntityMutExcept<'a, B> where - B: Bundle, + B: StaticBundle, { const IS_READ_ONLY: bool = false; type ReadOnly = EntityRefExcept<'a, B>; diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index eb49204434b6f..b2ea5eada7009 100644 --- a/crates/bevy_ecs/src/query/iter.rs +++ b/crates/bevy_ecs/src/query/iter.rs @@ -1,7 +1,7 @@ use super::{QueryData, QueryFilter, ReadOnlyQueryData}; use crate::{ archetype::{Archetype, ArchetypeEntity, Archetypes}, - bundle::Bundle, + bundle::StaticBundle, component::Tick, entity::{ContainsEntity, Entities, Entity, EntityEquivalent, EntitySet, EntitySetIterator}, query::{ArchetypeFilter, DebugCheckedUnwrap, QueryState, StorageId}, @@ -969,13 +969,13 @@ unsafe impl<'w, 's, F: QueryFilter> EntitySetIterator } // SAFETY: [`QueryIter`] is guaranteed to return every matching entity once and only once. -unsafe impl<'w, 's, F: QueryFilter, B: Bundle> EntitySetIterator +unsafe impl<'w, 's, F: QueryFilter, B: StaticBundle> EntitySetIterator for QueryIter<'w, 's, EntityRefExcept<'_, B>, F> { } // SAFETY: [`QueryIter`] is guaranteed to return every matching entity once and only once. -unsafe impl<'w, 's, F: QueryFilter, B: Bundle> EntitySetIterator +unsafe impl<'w, 's, F: QueryFilter, B: StaticBundle> EntitySetIterator for QueryIter<'w, 's, EntityMutExcept<'_, B>, F> { } diff --git a/crates/bevy_ecs/src/reflect/bundle.rs b/crates/bevy_ecs/src/reflect/bundle.rs index 133591c405ebf..d08a9f65e42db 100644 --- a/crates/bevy_ecs/src/reflect/bundle.rs +++ b/crates/bevy_ecs/src/reflect/bundle.rs @@ -9,7 +9,7 @@ use bevy_utils::prelude::DebugName; use core::any::{Any, TypeId}; use crate::{ - bundle::BundleFromComponents, + bundle::{BundleFromComponents, StaticBundle}, entity::EntityMapper, prelude::Bundle, relationship::RelationshipHookMode, @@ -57,7 +57,7 @@ impl ReflectBundleFns { /// /// This is useful if you want to start with the default implementation before overriding some /// of the functions to create a custom implementation. - pub fn new() -> Self { + pub fn new() -> Self { >::from_type().0 } } @@ -148,7 +148,9 @@ impl ReflectBundle { } } -impl FromType for ReflectBundle { +impl FromType + for ReflectBundle +{ fn from_type() -> Self { ReflectBundle(ReflectBundleFns { insert: |entity, reflected_bundle, registry| { diff --git a/crates/bevy_ecs/src/relationship/related_methods.rs b/crates/bevy_ecs/src/relationship/related_methods.rs index 8bae76a84e44b..2bfe1891d6cc7 100644 --- a/crates/bevy_ecs/src/relationship/related_methods.rs +++ b/crates/bevy_ecs/src/relationship/related_methods.rs @@ -1,5 +1,5 @@ use crate::{ - bundle::Bundle, + bundle::{Bundle, StaticBundle}, entity::{hash_set::EntityHashSet, Entity}, prelude::Children, relationship::{ @@ -355,7 +355,7 @@ impl<'w> EntityWorldMut<'w> { /// /// This method should only be called on relationships that form a tree-like structure. /// Any cycles will cause this method to loop infinitely. - pub fn remove_recursive(&mut self) -> &mut Self { + pub fn remove_recursive(&mut self) -> &mut Self { self.remove::(); if let Some(relationship_target) = self.get::() { let related_vec: Vec = relationship_target.iter().collect(); @@ -550,7 +550,7 @@ impl<'a> EntityCommands<'a> { /// /// This method should only be called on relationships that form a tree-like structure. /// Any cycles will cause this method to loop infinitely. - pub fn remove_recursive(&mut self) -> &mut Self { + pub fn remove_recursive(&mut self) -> &mut Self { self.queue(move |mut entity: EntityWorldMut| { entity.remove_recursive::(); }) diff --git a/crates/bevy_ecs/src/spawn.rs b/crates/bevy_ecs/src/spawn.rs index 0c30c14b9cc54..e62ba5b81e340 100644 --- a/crates/bevy_ecs/src/spawn.rs +++ b/crates/bevy_ecs/src/spawn.rs @@ -2,7 +2,7 @@ //! for the best entry points into these APIs and examples of how to use them. use crate::{ - bundle::{Bundle, BundleEffect, DynamicBundle, NoBundleEffect}, + bundle::{Bundle, BundleEffect, DynamicBundle, NoBundleEffect, StaticBundle}, entity::Entity, relationship::{RelatedSpawner, Relationship, RelationshipTarget}, world::{EntityWorldMut, World}, @@ -46,7 +46,9 @@ pub trait SpawnableList { fn size_hint(&self) -> usize; } -impl> SpawnableList for Vec { +impl + StaticBundle> SpawnableList + for Vec +{ fn spawn(self, world: &mut World, entity: Entity) { let mapped_bundles = self.into_iter().map(|b| (R::from(entity), b)); world.spawn_batch(mapped_bundles); @@ -182,35 +184,64 @@ impl> BundleEffect for SpawnRelatedBundle + Send + Sync + 'static> Bundle +// SAFETY: This internally relies on the RelationshipTarget's StaticBundle implementation, which is sound. +unsafe impl + Send + Sync + 'static> StaticBundle for SpawnRelatedBundle { fn component_ids( components: &mut crate::component::ComponentsRegistrator, ids: &mut impl FnMut(crate::component::ComponentId), ) { - ::component_ids(components, ids); + ::component_ids(components, ids); } fn get_component_ids( components: &crate::component::Components, ids: &mut impl FnMut(Option), ) { - ::get_component_ids(components, ids); + ::get_component_ids(components, ids); } fn register_required_components( components: &mut crate::component::ComponentsRegistrator, required_components: &mut crate::component::RequiredComponents, ) { - ::register_required_components( + ::register_required_components( components, required_components, ); } } +// SAFETY: This internally relies on the RelationshipTarget's Bundle implementation, which is sound. +unsafe impl + Send + Sync + 'static> Bundle + for SpawnRelatedBundle +{ + fn component_ids( + &self, + components: &mut crate::component::ComponentsRegistrator, + ids: &mut impl FnMut(crate::component::ComponentId), + ) { + ::component_ids(components, ids); + } + + fn get_component_ids( + &self, + components: &crate::component::Components, + ids: &mut impl FnMut(Option), + ) { + ::get_component_ids(components, ids); + } + + fn register_required_components( + &self, + components: &mut crate::component::ComponentsRegistrator, + required_components: &mut crate::component::RequiredComponents, + ) { + ::register_required_components(components, required_components); + } +} + impl> DynamicBundle for SpawnRelatedBundle { type Effect = Self; @@ -251,34 +282,60 @@ impl DynamicBundle for SpawnOneRelated { self } } - -// SAFETY: This internally relies on the RelationshipTarget's Bundle implementation, which is sound. -unsafe impl Bundle for SpawnOneRelated { +// SAFETY: This internally relies on the RelationshipTarget's StaticBundle implementation, which is sound. +unsafe impl StaticBundle for SpawnOneRelated { fn component_ids( components: &mut crate::component::ComponentsRegistrator, ids: &mut impl FnMut(crate::component::ComponentId), ) { - ::component_ids(components, ids); + ::component_ids(components, ids); } fn get_component_ids( components: &crate::component::Components, ids: &mut impl FnMut(Option), ) { - ::get_component_ids(components, ids); + ::get_component_ids(components, ids); } fn register_required_components( components: &mut crate::component::ComponentsRegistrator, required_components: &mut crate::component::RequiredComponents, ) { - ::register_required_components( + ::register_required_components( components, required_components, ); } } +// SAFETY: This internally relies on the RelationshipTarget's Bundle implementation, which is sound. +unsafe impl Bundle for SpawnOneRelated { + fn component_ids( + &self, + components: &mut crate::component::ComponentsRegistrator, + ids: &mut impl FnMut(crate::component::ComponentId), + ) { + ::component_ids(components, ids); + } + + fn get_component_ids( + &self, + components: &crate::component::Components, + ids: &mut impl FnMut(Option), + ) { + ::get_component_ids(components, ids); + } + + fn register_required_components( + &self, + components: &mut crate::component::ComponentsRegistrator, + required_components: &mut crate::component::RequiredComponents, + ) { + ::register_required_components(components, required_components); + } +} + /// [`RelationshipTarget`] methods that create a [`Bundle`] with a [`DynamicBundle::Effect`] that: /// /// 1. Contains the [`RelationshipTarget`] component, pre-allocated with the necessary space for spawned entities. diff --git a/crates/bevy_ecs/src/system/commands/command.rs b/crates/bevy_ecs/src/system/commands/command.rs index 5f1f611856b83..cb243b1e37086 100644 --- a/crates/bevy_ecs/src/system/commands/command.rs +++ b/crates/bevy_ecs/src/system/commands/command.rs @@ -5,7 +5,7 @@ //! [`Commands`](crate::system::Commands). use crate::{ - bundle::{Bundle, InsertMode, NoBundleEffect}, + bundle::{Bundle, InsertMode, NoBundleEffect, StaticBundle}, change_detection::MaybeLocation, entity::Entity, error::Result, @@ -70,7 +70,7 @@ where pub fn spawn_batch(bundles_iter: I) -> impl Command where I: IntoIterator + Send + Sync + 'static, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { let caller = MaybeLocation::caller(); move |world: &mut World| { @@ -88,7 +88,7 @@ where pub fn insert_batch(batch: I, insert_mode: InsertMode) -> impl Command where I: IntoIterator + Send + Sync + 'static, - B: Bundle, + B: Bundle + StaticBundle, { let caller = MaybeLocation::caller(); move |world: &mut World| -> Result { diff --git a/crates/bevy_ecs/src/system/commands/entity_command.rs b/crates/bevy_ecs/src/system/commands/entity_command.rs index 098493a148633..06e04062ea810 100644 --- a/crates/bevy_ecs/src/system/commands/entity_command.rs +++ b/crates/bevy_ecs/src/system/commands/entity_command.rs @@ -8,7 +8,7 @@ use alloc::vec::Vec; use log::info; use crate::{ - bundle::{Bundle, InsertMode}, + bundle::{Bundle, InsertMode, StaticBundle}, change_detection::MaybeLocation, component::{Component, ComponentId, ComponentInfo}, entity::{Entity, EntityClonerBuilder, OptIn, OptOut}, @@ -154,7 +154,7 @@ pub fn insert_from_world(mode: InsertMode) -> impl Ent /// An [`EntityCommand`] that removes the components in a [`Bundle`] from an entity. #[track_caller] -pub fn remove() -> impl EntityCommand { +pub fn remove() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.remove_with_caller::(caller); @@ -164,7 +164,7 @@ pub fn remove() -> impl EntityCommand { /// An [`EntityCommand`] that removes the components in a [`Bundle`] from an entity, /// as well as the required components for each component removed. #[track_caller] -pub fn remove_with_requires() -> impl EntityCommand { +pub fn remove_with_requires() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.remove_with_requires_with_caller::(caller); @@ -190,9 +190,9 @@ pub fn clear() -> impl EntityCommand { } /// An [`EntityCommand`] that removes all components from an entity, -/// except for those in the given [`Bundle`]. +/// except for those in the given [`StaticBundle`]. #[track_caller] -pub fn retain() -> impl EntityCommand { +pub fn retain() -> impl EntityCommand { let caller = MaybeLocation::caller(); move |mut entity: EntityWorldMut| { entity.retain_with_caller::(caller); @@ -218,7 +218,7 @@ pub fn despawn() -> impl EntityCommand { /// An [`EntityCommand`] that creates an [`Observer`](crate::observer::Observer) /// listening for events of type `E` targeting an entity #[track_caller] -pub fn observe( +pub fn observe( observer: impl IntoObserverSystem, ) -> impl EntityCommand { let caller = MaybeLocation::caller(); @@ -278,7 +278,7 @@ pub fn clone_with_opt_in( /// An [`EntityCommand`] that clones the specified components of an entity /// and inserts them into another entity. -pub fn clone_components(target: Entity) -> impl EntityCommand { +pub fn clone_components(target: Entity) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.clone_components::(target); } @@ -286,7 +286,7 @@ pub fn clone_components(target: Entity) -> impl EntityCommand { /// An [`EntityCommand`] that clones the specified components of an entity /// and inserts them into another entity, then removes them from the original entity. -pub fn move_components(target: Entity) -> impl EntityCommand { +pub fn move_components(target: Entity) -> impl EntityCommand { move |mut entity: EntityWorldMut| { entity.move_components::(target); } diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 0751e267708ad..02f21694c3654 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -15,7 +15,7 @@ use core::marker::PhantomData; use crate::{ self as bevy_ecs, - bundle::{Bundle, InsertMode, NoBundleEffect}, + bundle::{Bundle, InsertMode, NoBundleEffect, StaticBundle}, change_detection::{MaybeLocation, Mut}, component::{Component, ComponentId, Mutable}, entity::{Entities, Entity, EntityClonerBuilder, EntityDoesNotExistError, OptIn, OptOut}, @@ -533,7 +533,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn spawn_batch(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { self.queue(command::spawn_batch(batch)); } @@ -681,7 +681,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn insert_batch(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, - B: Bundle, + B: Bundle + StaticBundle, { self.queue(command::insert_batch(batch, InsertMode::Replace)); } @@ -712,7 +712,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn insert_batch_if_new(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, - B: Bundle, + B: Bundle + StaticBundle, { self.queue(command::insert_batch(batch, InsertMode::Keep)); } @@ -742,7 +742,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn try_insert_batch(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, - B: Bundle, + B: Bundle + StaticBundle, { self.queue(command::insert_batch(batch, InsertMode::Replace).handle_error_with(warn)); } @@ -773,7 +773,7 @@ impl<'w, 's> Commands<'w, 's> { pub fn try_insert_batch_if_new(&mut self, batch: I) where I: IntoIterator + Send + Sync + 'static, - B: Bundle, + B: Bundle + StaticBundle, { self.queue(command::insert_batch(batch, InsertMode::Keep).handle_error_with(warn)); } @@ -1114,7 +1114,7 @@ impl<'w, 's> Commands<'w, 's> { /// Panics if the given system is an exclusive system. /// /// [`On`]: crate::observer::On - pub fn add_observer( + pub fn add_observer( &mut self, observer: impl IntoObserverSystem, ) -> EntityCommands { @@ -1622,7 +1622,7 @@ impl<'a> EntityCommands<'a> { /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system); /// ``` #[track_caller] - pub fn remove(&mut self) -> &mut Self { + pub fn remove(&mut self) -> &mut Self { self.queue_handled(entity_command::remove::(), warn) } @@ -1658,7 +1658,7 @@ impl<'a> EntityCommands<'a> { /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system); /// ``` #[track_caller] - pub fn remove_if(&mut self, condition: impl FnOnce() -> bool) -> &mut Self { + pub fn remove_if(&mut self, condition: impl FnOnce() -> bool) -> &mut Self { if condition() { self.remove::() } else { @@ -1675,7 +1675,10 @@ impl<'a> EntityCommands<'a> { /// If the entity does not exist when this command is executed, /// the resulting error will be ignored. #[track_caller] - pub fn try_remove_if(&mut self, condition: impl FnOnce() -> bool) -> &mut Self { + pub fn try_remove_if( + &mut self, + condition: impl FnOnce() -> bool, + ) -> &mut Self { if condition() { self.try_remove::() } else { @@ -1723,7 +1726,7 @@ impl<'a> EntityCommands<'a> { /// } /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system); /// ``` - pub fn try_remove(&mut self) -> &mut Self { + pub fn try_remove(&mut self) -> &mut Self { self.queue_handled(entity_command::remove::(), ignore) } @@ -1755,7 +1758,7 @@ impl<'a> EntityCommands<'a> { /// # bevy_ecs::system::assert_is_system(remove_with_requires_system); /// ``` #[track_caller] - pub fn remove_with_requires(&mut self) -> &mut Self { + pub fn remove_with_requires(&mut self) -> &mut Self { self.queue(entity_command::remove_with_requires::()) } @@ -1940,7 +1943,7 @@ impl<'a> EntityCommands<'a> { /// # bevy_ecs::system::assert_is_system(remove_combat_stats_system); /// ``` #[track_caller] - pub fn retain(&mut self) -> &mut Self { + pub fn retain(&mut self) -> &mut Self { self.queue(entity_command::retain::()) } @@ -1968,7 +1971,7 @@ impl<'a> EntityCommands<'a> { } /// Creates an [`Observer`] listening for events of type `E` targeting this entity. - pub fn observe( + pub fn observe( &mut self, observer: impl IntoObserverSystem, ) -> &mut Self { @@ -2198,7 +2201,7 @@ impl<'a> EntityCommands<'a> { /// # Panics /// /// The command will panic when applied if the target entity does not exist. - pub fn clone_components(&mut self, target: Entity) -> &mut Self { + pub fn clone_components(&mut self, target: Entity) -> &mut Self { self.queue(entity_command::clone_components::(target)) } @@ -2211,7 +2214,7 @@ impl<'a> EntityCommands<'a> { /// # Panics /// /// The command will panic when applied if the target entity does not exist. - pub fn move_components(&mut self, target: Entity) -> &mut Self { + pub fn move_components(&mut self, target: Entity) -> &mut Self { self.queue(entity_command::move_components::(target)) } } diff --git a/crates/bevy_ecs/src/system/input.rs b/crates/bevy_ecs/src/system/input.rs index cb75016ee93b4..336b1ac6bc213 100644 --- a/crates/bevy_ecs/src/system/input.rs +++ b/crates/bevy_ecs/src/system/input.rs @@ -2,7 +2,7 @@ use core::ops::{Deref, DerefMut}; use variadics_please::all_tuples; -use crate::{bundle::Bundle, prelude::On, system::System}; +use crate::{bundle::StaticBundle, prelude::On, system::System}; /// Trait for types that can be used as input to [`System`]s. /// @@ -222,7 +222,7 @@ impl<'i, T: ?Sized> DerefMut for InMut<'i, T> { /// Used for [`ObserverSystem`]s. /// /// [`ObserverSystem`]: crate::system::ObserverSystem -impl SystemInput for On<'_, E, B> { +impl SystemInput for On<'_, E, B> { type Param<'i> = On<'i, E, B>; type Inner<'i> = On<'i, E, B>; diff --git a/crates/bevy_ecs/src/system/observer_system.rs b/crates/bevy_ecs/src/system/observer_system.rs index 243c2c3c3f6ae..3fb2a63f17b92 100644 --- a/crates/bevy_ecs/src/system/observer_system.rs +++ b/crates/bevy_ecs/src/system/observer_system.rs @@ -3,10 +3,11 @@ use bevy_utils::prelude::DebugName; use core::marker::PhantomData; use crate::{ + bundle::StaticBundle, component::{CheckChangeTicks, ComponentId, Tick}, error::Result, never::Never, - prelude::{Bundle, On}, + prelude::On, query::FilteredAccessSet, schedule::{Fallible, Infallible}, system::{input::SystemIn, System}, @@ -16,12 +17,12 @@ use crate::{ use super::{IntoSystem, SystemParamValidationError}; /// Implemented for [`System`]s that have [`On`] as the first argument. -pub trait ObserverSystem: +pub trait ObserverSystem: System, Out = Out> + Send + 'static { } -impl ObserverSystem for T where +impl ObserverSystem for T where T: System, Out = Out> + Send + 'static { } @@ -38,7 +39,7 @@ impl ObserverSystem for T where label = "the trait `IntoObserverSystem` is not implemented", note = "for function `ObserverSystem`s, ensure the first argument is `On` and any subsequent ones are `SystemParam`" )] -pub trait IntoObserverSystem: Send + 'static { +pub trait IntoObserverSystem: Send + 'static { /// The type of [`System`] that this instance converts into. type System: ObserverSystem; @@ -51,7 +52,7 @@ where S: IntoSystem, Out, M> + Send + 'static, S::System: ObserverSystem, E: 'static, - B: Bundle, + B: StaticBundle, { type System = S::System; @@ -65,7 +66,7 @@ where S: IntoSystem, (), M> + Send + 'static, S::System: ObserverSystem, E: Send + Sync + 'static, - B: Bundle, + B: StaticBundle, { type System = InfallibleObserverWrapper; @@ -78,7 +79,7 @@ impl IntoObserverSystem for S where S: IntoSystem, Never, M> + Send + 'static, E: Send + Sync + 'static, - B: Bundle, + B: StaticBundle, { type System = InfallibleObserverWrapper; @@ -107,7 +108,7 @@ impl System for InfallibleObserverWrapper where S: ObserverSystem, E: Send + Sync + 'static, - B: Bundle, + B: StaticBundle, Out: Send + Sync + 'static, { type In = On<'static, E, B>; diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 9b7f8eb551133..90df291bcd875 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -2,7 +2,7 @@ use crate::{ archetype::Archetype, bundle::{ Bundle, BundleEffect, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, - InsertMode, + InsertMode, StaticBundle, }, change_detection::{MaybeLocation, MutUntyped}, component::{ @@ -1849,7 +1849,7 @@ impl<'w> EntityWorldMut<'w> { let location = self.location(); let change_tick = self.world.change_tick(); let mut bundle_inserter = - BundleInserter::new::(self.world, location.archetype_id, change_tick); + BundleInserter::new::(&bundle, self.world, location.archetype_id, change_tick); // SAFETY: location matches current entity. `T` matches `bundle_info` let (location, after_effect) = unsafe { bundle_inserter.insert( @@ -2007,7 +2007,7 @@ impl<'w> EntityWorldMut<'w> { /// If the entity has been despawned while this `EntityWorldMut` is still alive. #[must_use] #[track_caller] - pub fn take(&mut self) -> Option { + pub fn take(&mut self) -> Option { let location = self.location(); let entity = self.entity; @@ -2063,12 +2063,15 @@ impl<'w> EntityWorldMut<'w> { /// /// If the entity has been despawned while this `EntityWorldMut` is still alive. #[track_caller] - pub fn remove(&mut self) -> &mut Self { + pub fn remove(&mut self) -> &mut Self { self.remove_with_caller::(MaybeLocation::caller()) } #[inline] - pub(crate) fn remove_with_caller(&mut self, caller: MaybeLocation) -> &mut Self { + pub(crate) fn remove_with_caller( + &mut self, + caller: MaybeLocation, + ) -> &mut Self { let location = self.location(); let Some(mut remover) = @@ -2100,11 +2103,11 @@ impl<'w> EntityWorldMut<'w> { /// /// If the entity has been despawned while this `EntityWorldMut` is still alive. #[track_caller] - pub fn remove_with_requires(&mut self) -> &mut Self { + pub fn remove_with_requires(&mut self) -> &mut Self { self.remove_with_requires_with_caller::(MaybeLocation::caller()) } - pub(crate) fn remove_with_requires_with_caller( + pub(crate) fn remove_with_requires_with_caller( &mut self, caller: MaybeLocation, ) -> &mut Self { @@ -2148,12 +2151,15 @@ impl<'w> EntityWorldMut<'w> { /// /// If the entity has been despawned while this `EntityWorldMut` is still alive. #[track_caller] - pub fn retain(&mut self) -> &mut Self { + pub fn retain(&mut self) -> &mut Self { self.retain_with_caller::(MaybeLocation::caller()) } #[inline] - pub(crate) fn retain_with_caller(&mut self, caller: MaybeLocation) -> &mut Self { + pub(crate) fn retain_with_caller( + &mut self, + caller: MaybeLocation, + ) -> &mut Self { let old_location = self.location(); let archetypes = &mut self.world.archetypes; let storages = &mut self.world.storages; @@ -2165,7 +2171,7 @@ impl<'w> EntityWorldMut<'w> { let retained_bundle = self .world .bundles - .register_info::(&mut registrator, storages); + .register_static_info::(&mut registrator, storages); // SAFETY: `retained_bundle` exists as we just initialized it. let retained_bundle_info = unsafe { self.world.bundles.get_unchecked(retained_bundle) }; let old_archetype = &mut archetypes[old_location.archetype_id]; @@ -2649,14 +2655,14 @@ impl<'w> EntityWorldMut<'w> { /// /// Panics if the given system is an exclusive system. #[track_caller] - pub fn observe( + pub fn observe( &mut self, observer: impl IntoObserverSystem, ) -> &mut Self { self.observe_with_caller(observer, MaybeLocation::caller()) } - pub(crate) fn observe_with_caller( + pub(crate) fn observe_with_caller( &mut self, observer: impl IntoObserverSystem, caller: MaybeLocation, @@ -2886,7 +2892,7 @@ impl<'w> EntityWorldMut<'w> { /// /// - If this entity has been despawned while this `EntityWorldMut` is still alive. /// - If the target entity does not exist. - pub fn clone_components(&mut self, target: Entity) -> &mut Self { + pub fn clone_components(&mut self, target: Entity) -> &mut Self { self.assert_not_despawned(); EntityCloner::build_opt_in(self.world) @@ -2908,7 +2914,7 @@ impl<'w> EntityWorldMut<'w> { /// /// - If this entity has been despawned while this `EntityWorldMut` is still alive. /// - If the target entity does not exist. - pub fn move_components(&mut self, target: Entity) -> &mut Self { + pub fn move_components(&mut self, target: Entity) -> &mut Self { self.assert_not_despawned(); EntityCloner::build_opt_in(self.world) @@ -3572,7 +3578,7 @@ impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a> { } } -impl<'a, B: Bundle> From<&'a EntityRefExcept<'_, B>> for FilteredEntityRef<'a> { +impl<'a, B: StaticBundle> From<&'a EntityRefExcept<'_, B>> for FilteredEntityRef<'a> { fn from(value: &'a EntityRefExcept<'_, B>) -> Self { // SAFETY: // - The FilteredEntityRef has the same component access as the given EntityRefExcept. @@ -3920,7 +3926,7 @@ impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a> { } } -impl<'a, B: Bundle> From<&'a EntityMutExcept<'_, B>> for FilteredEntityMut<'a> { +impl<'a, B: StaticBundle> From<&'a EntityMutExcept<'_, B>> for FilteredEntityMut<'a> { fn from(value: &'a EntityMutExcept<'_, B>) -> Self { // SAFETY: // - The FilteredEntityMut has the same component access as the given EntityMutExcept. @@ -3994,7 +4000,7 @@ pub enum TryFromFilteredError { /// for an explicitly-enumerated set. pub struct EntityRefExcept<'w, B> where - B: Bundle, + B: StaticBundle, { entity: UnsafeEntityCell<'w>, phantom: PhantomData, @@ -4002,7 +4008,7 @@ where impl<'w, B> EntityRefExcept<'w, B> where - B: Bundle, + B: StaticBundle, { /// # Safety /// Other users of `UnsafeEntityCell` must only have mutable access to the components in `B`. @@ -4163,7 +4169,7 @@ where impl<'a, B> From<&'a EntityMutExcept<'_, B>> for EntityRefExcept<'a, B> where - B: Bundle, + B: StaticBundle, { fn from(entity: &'a EntityMutExcept<'_, B>) -> Self { // SAFETY: All accesses that `EntityRefExcept` provides are also @@ -4172,23 +4178,23 @@ where } } -impl Clone for EntityRefExcept<'_, B> { +impl Clone for EntityRefExcept<'_, B> { fn clone(&self) -> Self { *self } } -impl Copy for EntityRefExcept<'_, B> {} +impl Copy for EntityRefExcept<'_, B> {} -impl PartialEq for EntityRefExcept<'_, B> { +impl PartialEq for EntityRefExcept<'_, B> { fn eq(&self, other: &Self) -> bool { self.entity() == other.entity() } } -impl Eq for EntityRefExcept<'_, B> {} +impl Eq for EntityRefExcept<'_, B> {} -impl PartialOrd for EntityRefExcept<'_, B> { +impl PartialOrd for EntityRefExcept<'_, B> { /// [`EntityRefExcept`]'s comparison trait implementations match the underlying [`Entity`], /// and cannot discern between different worlds. fn partial_cmp(&self, other: &Self) -> Option { @@ -4196,26 +4202,26 @@ impl PartialOrd for EntityRefExcept<'_, B> { } } -impl Ord for EntityRefExcept<'_, B> { +impl Ord for EntityRefExcept<'_, B> { fn cmp(&self, other: &Self) -> Ordering { self.entity().cmp(&other.entity()) } } -impl Hash for EntityRefExcept<'_, B> { +impl Hash for EntityRefExcept<'_, B> { fn hash(&self, state: &mut H) { self.entity().hash(state); } } -impl ContainsEntity for EntityRefExcept<'_, B> { +impl ContainsEntity for EntityRefExcept<'_, B> { fn entity(&self) -> Entity { self.id() } } // SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity. -unsafe impl EntityEquivalent for EntityRefExcept<'_, B> {} +unsafe impl EntityEquivalent for EntityRefExcept<'_, B> {} /// Provides mutable access to all components of an entity, with the exception /// of an explicit set. @@ -4227,7 +4233,7 @@ unsafe impl EntityEquivalent for EntityRefExcept<'_, B> {} /// [`crate::query::Without`] filter. pub struct EntityMutExcept<'w, B> where - B: Bundle, + B: StaticBundle, { entity: UnsafeEntityCell<'w>, phantom: PhantomData, @@ -4235,7 +4241,7 @@ where impl<'w, B> EntityMutExcept<'w, B> where - B: Bundle, + B: StaticBundle, { /// # Safety /// Other users of `UnsafeEntityCell` must not have access to any components not in `B`. @@ -4395,15 +4401,15 @@ where } } -impl PartialEq for EntityMutExcept<'_, B> { +impl PartialEq for EntityMutExcept<'_, B> { fn eq(&self, other: &Self) -> bool { self.entity() == other.entity() } } -impl Eq for EntityMutExcept<'_, B> {} +impl Eq for EntityMutExcept<'_, B> {} -impl PartialOrd for EntityMutExcept<'_, B> { +impl PartialOrd for EntityMutExcept<'_, B> { /// [`EntityMutExcept`]'s comparison trait implementations match the underlying [`Entity`], /// and cannot discern between different worlds. fn partial_cmp(&self, other: &Self) -> Option { @@ -4411,30 +4417,30 @@ impl PartialOrd for EntityMutExcept<'_, B> { } } -impl Ord for EntityMutExcept<'_, B> { +impl Ord for EntityMutExcept<'_, B> { fn cmp(&self, other: &Self) -> Ordering { self.entity().cmp(&other.entity()) } } -impl Hash for EntityMutExcept<'_, B> { +impl Hash for EntityMutExcept<'_, B> { fn hash(&self, state: &mut H) { self.entity().hash(state); } } -impl ContainsEntity for EntityMutExcept<'_, B> { +impl ContainsEntity for EntityMutExcept<'_, B> { fn entity(&self) -> Entity { self.id() } } // SAFETY: This type represents one Entity. We implement the comparison traits based on that Entity. -unsafe impl EntityEquivalent for EntityMutExcept<'_, B> {} +unsafe impl EntityEquivalent for EntityMutExcept<'_, B> {} fn bundle_contains_component(components: &Components, query_id: ComponentId) -> bool where - B: Bundle, + B: StaticBundle, { let mut found = false; B::get_component_ids(components, &mut |maybe_id| { diff --git a/crates/bevy_ecs/src/world/mod.rs b/crates/bevy_ecs/src/world/mod.rs index 714c5e1eaec8c..ab61a325b3cd4 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -40,7 +40,7 @@ use crate::{ archetype::{ArchetypeId, Archetypes}, bundle::{ Bundle, BundleEffect, BundleInfo, BundleInserter, BundleSpawner, Bundles, InsertMode, - NoBundleEffect, + NoBundleEffect, StaticBundle, }, change_detection::{MaybeLocation, MutUntyped, TicksMut}, component::{ @@ -1171,7 +1171,7 @@ impl World { self.flush(); let change_tick = self.change_tick(); let entity = self.entities.alloc(); - let mut bundle_spawner = BundleSpawner::new::(self, change_tick); + let mut bundle_spawner = BundleSpawner::new(&bundle, self, change_tick); // SAFETY: bundle's type matches `bundle_info`, entity is allocated but non-existent let (entity_location, after_effect) = unsafe { bundle_spawner.spawn_non_existent(entity, bundle, caller) }; @@ -1237,7 +1237,7 @@ impl World { pub fn spawn_batch(&mut self, iter: I) -> SpawnBatchIter<'_, I::IntoIter> where I: IntoIterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { SpawnBatchIter::new(self, iter.into_iter(), MaybeLocation::caller()) } @@ -2253,7 +2253,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller()); } @@ -2278,7 +2278,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller()); } @@ -2297,7 +2297,7 @@ impl World { ) where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { struct InserterArchetypeCache<'w> { inserter: BundleInserter<'w>, @@ -2311,7 +2311,7 @@ impl World { unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }; let bundle_id = self .bundles - .register_info::(&mut registrator, &mut self.storages); + .register_static_info::(&mut registrator, &mut self.storages); let mut batch_iter = batch.into_iter(); @@ -2396,7 +2396,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.try_insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller()) } @@ -2418,7 +2418,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.try_insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller()) } @@ -2442,7 +2442,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { struct InserterArchetypeCache<'w> { inserter: BundleInserter<'w>, @@ -2456,7 +2456,7 @@ impl World { unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }; let bundle_id = self .bundles - .register_info::(&mut registrator, &mut self.storages); + .register_static_info::(&mut registrator, &mut self.storages); let mut invalid_entities = Vec::::new(); let mut batch_iter = batch.into_iter(); @@ -3039,13 +3039,13 @@ impl World { /// This is largely equivalent to calling [`register_component`](Self::register_component) on each /// component in the bundle. #[inline] - pub fn register_bundle(&mut self) -> &BundleInfo { + pub fn register_bundle(&mut self) -> &BundleInfo { // SAFETY: These come from the same world. `Self.components_registrator` can't be used since we borrow other fields too. let mut registrator = unsafe { ComponentsRegistrator::new(&mut self.components, &mut self.component_ids) }; let id = self .bundles - .register_info::(&mut registrator, &mut self.storages); + .register_static_info::(&mut registrator, &mut self.storages); // SAFETY: We just initialized the bundle so its id should definitely be valid. unsafe { self.bundles.get(id).debug_checked_unwrap() } } diff --git a/crates/bevy_ecs/src/world/spawn_batch.rs b/crates/bevy_ecs/src/world/spawn_batch.rs index 16bd9bb8059b4..c2bbd8c0d05fd 100644 --- a/crates/bevy_ecs/src/world/spawn_batch.rs +++ b/crates/bevy_ecs/src/world/spawn_batch.rs @@ -1,5 +1,5 @@ use crate::{ - bundle::{Bundle, BundleSpawner, NoBundleEffect}, + bundle::{Bundle, BundleSpawner, NoBundleEffect, StaticBundle}, change_detection::MaybeLocation, entity::{Entity, EntitySetIterator}, world::World, @@ -13,7 +13,7 @@ use core::iter::FusedIterator; pub struct SpawnBatchIter<'w, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { inner: I, spawner: BundleSpawner<'w>, @@ -23,7 +23,7 @@ where impl<'w, I> SpawnBatchIter<'w, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { #[inline] #[track_caller] @@ -38,7 +38,7 @@ where let length = upper.unwrap_or(lower); world.entities.reserve(length as u32); - let mut spawner = BundleSpawner::new::(world, change_tick); + let mut spawner = BundleSpawner::new_static::(world, change_tick); spawner.reserve_storage(length); Self { @@ -52,7 +52,7 @@ where impl Drop for SpawnBatchIter<'_, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { fn drop(&mut self) { // Iterate through self in order to spawn remaining bundles. @@ -66,7 +66,7 @@ where impl Iterator for SpawnBatchIter<'_, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { type Item = Entity; @@ -84,7 +84,7 @@ where impl ExactSizeIterator for SpawnBatchIter<'_, I> where I: ExactSizeIterator, - T: Bundle, + T: Bundle + StaticBundle, { fn len(&self) -> usize { self.inner.len() @@ -94,7 +94,7 @@ where impl FusedIterator for SpawnBatchIter<'_, I> where I: FusedIterator, - T: Bundle, + T: Bundle + StaticBundle, { } @@ -102,6 +102,6 @@ where unsafe impl EntitySetIterator for SpawnBatchIter<'_, I> where I: FusedIterator, - T: Bundle, + T: Bundle + StaticBundle, { } diff --git a/crates/bevy_render/src/extract_component.rs b/crates/bevy_render/src/extract_component.rs index b7bb05e425d55..7e05d0ed16eff 100644 --- a/crates/bevy_render/src/extract_component.rs +++ b/crates/bevy_render/src/extract_component.rs @@ -8,7 +8,7 @@ use crate::{ }; use bevy_app::{App, Plugin}; use bevy_ecs::{ - bundle::NoBundleEffect, + bundle::{NoBundleEffect, StaticBundle}, component::Component, prelude::*, query::{QueryFilter, QueryItem, ReadOnlyQueryData}, @@ -54,7 +54,7 @@ pub trait ExtractComponent: Component { /// /// `Out` has a [`Bundle`] trait bound instead of a [`Component`] trait bound in order to allow use cases /// such as tuples of components as output. - type Out: Bundle; + type Out: Bundle + StaticBundle; // TODO: https://github.com/rust-lang/rust/issues/29661 // type Out: Component = Self; diff --git a/release-content/migration-guides/static-bundle-split.md b/release-content/migration-guides/static-bundle-split.md new file mode 100644 index 0000000000000..35ff7f2f52d4c --- /dev/null +++ b/release-content/migration-guides/static-bundle-split.md @@ -0,0 +1,55 @@ +--- +title: \`StaticBundle` has been split off from `Bundle` +pull_requests: [19491] +--- + +The `StaticBundle` trait has been split off from the `Bundle` trait to avoid conflating the concept of a type whose values can be inserted into an entity (`Bundle`) with the concept of a statically known set of components (`StaticBundle`). This required the update of existing APIs that were using `Bundle` as a statically known set of components to use `StaticBundle` instead. + +Changes for most users will be zero or pretty minimal, since `#[derive(Bundle)]` will automatically derive `StaticBundle` and most types that implemented `Bundle` will now also implement `StaticBundle`. The main exception will be generic APIs or types, which now will need to update or add a bound on `StaticBundle`. For example: + +```rs +// 0.16 +#[derive(Bundle)] +struct MyBundleWrapper { + inner: T +} + +fn my_register_bundle(world: &mut World) { + world.register_bundle::(); +} + + +// 0.17 +#[derive(Bundle)] +struct MyBundleWrapper { // Add a StaticBundle bound + inner: T +} + +fn my_register_bundle(world: &mut World) { // Replace Bundle with StaticBundle + world.register_bundle::(); +} +``` + +The following APIs now require the `StaticBundle` trait instead of the `Bundle` trait: + +- `World::register_bundle`, which has been renamed to `World::register_static_bundle` +- the `B` type parameter of `EntityRefExcept` and `EntityMutExcept` +- `EntityClonerBuilder::allow` and `EntityClonerBuilder::deny` +- `EntityCommands::clone_components` and `EntityCommands::move_components` +- `EntityWorldMut::clone_components` and `EntityWorldMut::move_components` +- the `B` type parameter of `IntoObserverSystem`, `Trigger`, `App::add_observer`, `World::add_observer`, `Observer::new`, `Commands::add_observer`, `EntityCommands::observe` and `EntityWorldMut::observe` +- `EntityWorldMut::remove_recursive` and `Commands::remove_recursive` +- `EntityCommands::remove`, `EntityCommands::remove_if`, `EntityCommands::try_remove_if`, `EntityCommands::try_remove`, `EntityCommands::remove_with_requires`, `EntityWorldMut::remove` and `EntityWorldMut::remove_with_requires` +- `EntityWorldMut::take` +- `EntityWorldMut::retain` and `EntityCommands::retain` + +The following APIs now require the `StaticBundle` trait in addition to the `Bundle` trait: + +- `Commands::spawn_batch`, `Commands::insert_batch`, `Commands::insert_batch_if_new`, `Commands::try_insert_batch`, `Commands::try_insert_batch_if_new`, `bevy::ecs::command::spawn_batch`, `bevy::ecs::command::insert_batch`, `World::spawn_batch`, `World::insert_batch`, `World::insert_batch_if_new`, `World::try_insert_batch` and `World::try_insert_batch_if_new` +- `ReflectBundle::new`, `impl FromType` for `ReflectBundle` and `#[reflect(Bundle)]` +- `ExtractComponent::Out` + +Moreover, some APIs have been renamed: + +- `World::register_bundle` has been renamed to `World::register_static_bundle` +- the `DynamicBundle` trait has been renamed to `ComponentsFromBundle`