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 dc5c2c5caf420..4608b2f9a73a6 100644 --- a/benches/benches/bevy_ecs/world/world_get.rs +++ b/benches/benches/bevy_ecs/world/world_get.rs @@ -1,7 +1,7 @@ use core::hint::black_box; use bevy_ecs::{ - bundle::{Bundle, NoBundleEffect}, + bundle::{Bundle, NoBundleEffect, StaticBundle}, component::Component, entity::Entity, system::{Query, SystemState}, @@ -38,7 +38,7 @@ fn setup(entity_count: u32) -> (World, Vec) { black_box((world, entities)) } -fn setup_wide + Default>( +fn setup_wide + StaticBundle + Default>( entity_count: u32, ) -> (World, Vec) { let mut world = World::default(); diff --git a/crates/bevy_app/src/app.rs b/crates/bevy_app/src/app.rs index 6985d9169af32..e9ce0cb55fb03 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, @@ -1378,7 +1379,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 c465e052d284b..c32e41670cd00 100644 --- a/crates/bevy_ecs/macros/src/lib.rs +++ b/crates/bevy_ecs/macros/src/lib.rs @@ -30,18 +30,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, } } } @@ -63,8 +66,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 { @@ -144,6 +151,30 @@ 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);)* + } + } + }); + let bundle_impl = quote! { // SAFETY: // - ComponentId is returned in field-definition-order. [get_components] uses field-definition-order @@ -152,17 +183,19 @@ 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);)* } } }; @@ -212,7 +245,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)] @@ -234,6 +267,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/impls.rs b/crates/bevy_ecs/src/bundle/impls.rs index 7cf74a86e324f..43c4a91d4e4f0 100644 --- a/crates/bevy_ecs/src/bundle/impls.rs +++ b/crates/bevy_ecs/src/bundle/impls.rs @@ -5,16 +5,16 @@ use core::mem::MaybeUninit; use variadics_please::all_tuples_enumerated; use crate::{ - bundle::{Bundle, BundleFromComponents, DynamicBundle, NoBundleEffect}, + bundle::{Bundle, BundleFromComponents, DynamicBundle, NoBundleEffect, StaticBundle}, component::{Component, ComponentId, Components, ComponentsRegistrator, StorageType}, query::DebugCheckedUnwrap, world::EntityWorldMut, }; // 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::()); } @@ -24,6 +24,27 @@ unsafe impl Bundle for C { } } +// 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); + } +} + // SAFETY: // - `Bundle::from_components` calls `func` exactly once for C, which is the exact value returned by `Bundle::component_ids`. unsafe impl BundleFromComponents for C { @@ -55,6 +76,30 @@ impl DynamicBundle for C { macro_rules! tuple_impl { ($(#[$meta:meta])* $(($index:tt, $name: ident, $alias: 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);)* + } + } + #[expect( clippy::allow_attributes, reason = "This is a tuple-related macro; as such, the lints below may not always apply." @@ -72,12 +117,24 @@ 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);)* } } diff --git a/crates/bevy_ecs/src/bundle/info.rs b/crates/bevy_ecs/src/bundle/info.rs index 589ec0b7c65e6..1f315cf6472a4 100644 --- a/crates/bevy_ecs/src/bundle/info.rs +++ b/crates/bevy_ecs/src/bundle/info.rs @@ -10,7 +10,7 @@ use indexmap::{IndexMap, IndexSet}; use crate::{ archetype::{Archetype, BundleComponentStatus, ComponentStatus}, - bundle::{Bundle, DynamicBundle}, + bundle::{Bundle, DynamicBundle, StaticBundle}, change_detection::MaybeLocation, component::{ ComponentId, Components, ComponentsRegistrator, RequiredComponentConstructor, StorageType, @@ -429,7 +429,7 @@ impl Bundles { /// /// [`World`]: crate::world::World #[deny(unsafe_op_in_unsafe_fn)] - pub(crate) unsafe fn register_info( + pub(crate) unsafe fn register_static_info( &mut self, components: &mut ComponentsRegistrator, storages: &mut Storages, @@ -450,6 +450,37 @@ impl Bundles { }) } + /// Registers a new [`BundleInfo`] for a statically known type. + /// + /// Also registers all the components in the bundle. + /// + /// # Safety + /// + /// `components` and `storages` must be from the same [`World`] as `self`. + /// + /// [`World`]: crate::world::World + pub(crate) unsafe 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(); + bundle.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`], which contains both explicit and required components for a statically known type. /// /// Also registers all the components in the bundle. @@ -460,7 +491,7 @@ impl Bundles { /// /// [`World`]: crate::world::World #[deny(unsafe_op_in_unsafe_fn)] - pub(crate) unsafe fn register_contributed_bundle_info( + pub(crate) unsafe fn register_contributed_bundle_info( &mut self, components: &mut ComponentsRegistrator, storages: &mut Storages, @@ -470,7 +501,8 @@ impl Bundles { } else { // SAFETY: as per the guarantees of this function, components and // storages are from the same world as self - let explicit_bundle_id = unsafe { self.register_info::(components, storages) }; + let explicit_bundle_id = + unsafe { 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 { diff --git a/crates/bevy_ecs/src/bundle/insert.rs b/crates/bevy_ecs/src/bundle/insert.rs index e104265380088..c569cd44a6520 100644 --- a/crates/bevy_ecs/src/bundle/insert.rs +++ b/crates/bevy_ecs/src/bundle/insert.rs @@ -9,7 +9,7 @@ use crate::{ }, bundle::{ArchetypeMoveType, Bundle, BundleId, BundleInfo, DynamicBundle, InsertMode}, change_detection::MaybeLocation, - component::{Components, StorageType, Tick}, + component::{Components, ComponentsRegistrator, StorageType, Tick}, entity::{Entities, Entity, EntityLocation}, event::EntityComponentsTrigger, lifecycle::{Add, Insert, Replace, ADD, INSERT, REPLACE}, @@ -34,12 +34,20 @@ pub(crate) struct BundleInserter<'w> { impl<'w> BundleInserter<'w> { #[inline] pub(crate) fn new( + bundle: &T, world: &'w mut World, archetype_id: ArchetypeId, change_tick: Tick, ) -> Self { - let bundle_id = world.register_bundle_info::(); - + // 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) }; + // SAFETY: `world.bundles`, `world.storages` and `registrator` are all created from the given `world` + let bundle_id = unsafe { + 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) } } diff --git a/crates/bevy_ecs/src/bundle/mod.rs b/crates/bevy_ecs/src/bundle/mod.rs index 17d894d40b660..ff6588c4d35c9 100644 --- a/crates/bevy_ecs/src/bundle/mod.rs +++ b/crates/bevy_ecs/src/bundle/mod.rs @@ -77,11 +77,13 @@ use crate::{ }; use bevy_ptr::OwningPtr; -/// 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. /// @@ -111,15 +113,6 @@ use bevy_ptr::OwningPtr; /// 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 @@ -192,21 +185,65 @@ use bevy_ptr::OwningPtr; // 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`", note = "consider annotating `{Self}` with `#[derive(Component)]` or `#[derive(Bundle)]`" )] pub unsafe trait Bundle: DynamicBundle + Send + Sync + 'static { - /// Gets this [`Bundle`]'s component ids, in the order of this bundle's [`Component`]s + /// Gets this [`Bundle`]'s component ids, in the order of this bundle's [`Component`](crate::component::Component)s + 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(&self, components: &Components, ids: &mut impl FnMut(Option)); +} + +/// 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). +/// +/// [`Component`]: crate::component::Component +// +// (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 [`Bundle`]'s component ids. This will be [`None`] if the component has not been registered. + /// 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)); } -/// Creates a [`Bundle`] by taking it from internal storage. +/// Creates a bundle by taking it from the internal storage. /// /// # Safety /// diff --git a/crates/bevy_ecs/src/bundle/remove.rs b/crates/bevy_ecs/src/bundle/remove.rs index f40c82c7f7d67..bae6f426fb5f5 100644 --- a/crates/bevy_ecs/src/bundle/remove.rs +++ b/crates/bevy_ecs/src/bundle/remove.rs @@ -4,7 +4,7 @@ use core::ptr::NonNull; use crate::{ archetype::{Archetype, ArchetypeCreated, ArchetypeId, Archetypes}, - bundle::{Bundle, BundleId, BundleInfo}, + bundle::{BundleId, BundleInfo, StaticBundle}, change_detection::MaybeLocation, component::{ComponentId, Components, StorageType}, entity::{Entity, EntityLocation}, @@ -35,7 +35,7 @@ impl<'w> BundleRemover<'w> { /// Caller must ensure that `archetype_id` is valid #[inline] #[deny(unsafe_op_in_unsafe_fn)] - pub(crate) unsafe fn new( + pub(crate) unsafe fn new( world: &'w mut World, archetype_id: ArchetypeId, require_all: bool, diff --git a/crates/bevy_ecs/src/bundle/spawner.rs b/crates/bevy_ecs/src/bundle/spawner.rs index b4f32147aecdf..d520d759dc764 100644 --- a/crates/bevy_ecs/src/bundle/spawner.rs +++ b/crates/bevy_ecs/src/bundle/spawner.rs @@ -4,9 +4,9 @@ use bevy_ptr::{ConstNonNull, MovingPtr}; use crate::{ archetype::{Archetype, ArchetypeCreated, ArchetypeId, SpawnBundleStatus}, - bundle::{Bundle, BundleId, BundleInfo, DynamicBundle, InsertMode}, + bundle::{Bundle, BundleId, BundleInfo, DynamicBundle, InsertMode, StaticBundle}, change_detection::MaybeLocation, - component::Tick, + component::{ComponentsRegistrator, Tick}, entity::{Entities, Entity, EntityLocation}, event::EntityComponentsTrigger, lifecycle::{Add, Insert, ADD, INSERT}, @@ -26,9 +26,23 @@ pub(crate) struct BundleSpawner<'w> { impl<'w> BundleSpawner<'w> { #[inline] - pub fn new(world: &'w mut World, change_tick: Tick) -> Self { - let bundle_id = world.register_bundle_info::(); + 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) }; + // SAFETY: `world.bundles`, `world.storages` and `registrator` are all created from the given `world` + let bundle_id = unsafe { + 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_static(world: &'w mut World, change_tick: Tick) -> Self { + let bundle_id = world.register_bundle_info::(); // SAFETY: we initialized this bundle_id in `init_info` unsafe { Self::new_with_id(world, bundle_id, change_tick) } } diff --git a/crates/bevy_ecs/src/entity/clone_entities.rs b/crates/bevy_ecs/src/entity/clone_entities.rs index 4c110d0057c9a..d5aea726fff40 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, BundleRemover, InsertMode}, + bundle::{BundleRemover, InsertMode, StaticBundle}, change_detection::MaybeLocation, component::{Component, ComponentCloneBehavior, ComponentCloneFn, ComponentId, ComponentInfo}, entity::{hash_map::EntityHashMap, Entities, Entity, EntityMapper}, @@ -911,7 +911,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_ids(bundle_id) } @@ -968,7 +968,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_ids(bundle_id) } @@ -979,7 +979,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_ids_if_new(bundle_id) } diff --git a/crates/bevy_ecs/src/lib.rs b/crates/bevy_ecs/src/lib.rs index 0d148b346895f..3b154c5effa25 100644 --- a/crates/bevy_ecs/src/lib.rs +++ b/crates/bevy_ecs/src/lib.rs @@ -158,7 +158,7 @@ pub struct HotPatchChanges; #[cfg(test)] mod tests { use crate::{ - bundle::Bundle, + bundle::{Bundle, StaticBundle}, change_detection::Ref, component::Component, entity::{Entity, EntityMapper}, @@ -249,11 +249,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, &[ @@ -262,6 +269,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"), @@ -300,10 +322,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, &[ @@ -314,6 +346,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), @@ -353,13 +402,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 3de8b486b880f..9938e169119f9 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, RequiredComponentsRegistrator, StorageType, }, @@ -219,7 +220,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(), @@ -430,7 +431,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 43edfdd4ccef6..a0d50c42e0e4d 100644 --- a/crates/bevy_ecs/src/observer/mod.rs +++ b/crates/bevy_ecs/src/observer/mod.rs @@ -15,6 +15,7 @@ pub use runner::*; pub use system_param::*; use crate::{ + bundle::StaticBundle, change_detection::MaybeLocation, event::Event, prelude::*, @@ -51,7 +52,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 dfffe3bec60cd..6eac8cabfdb72 100644 --- a/crates/bevy_ecs/src/observer/runner.rs +++ b/crates/bevy_ecs/src/observer/runner.rs @@ -3,6 +3,7 @@ use core::any::Any; use crate::{ + bundle::StaticBundle, error::ErrorContext, event::Event, observer::TriggerContext, @@ -32,7 +33,7 @@ pub type ObserverRunner = // NOTE: The way `Trigger` and `On` interact in this implementation is _subtle_ and _easily invalidated_ // from a soundness perspective. Please read and understand the safety comments before making any changes, // either here or in `On`. -pub(super) unsafe fn observer_system_runner>( +pub(super) unsafe fn observer_system_runner>( mut world: DeferredWorld, observer: Entity, trigger_context: &TriggerContext, diff --git a/crates/bevy_ecs/src/observer/system_param.rs b/crates/bevy_ecs/src/observer/system_param.rs index 1f3da164d9419..2bcd46f5cb6bb 100644 --- a/crates/bevy_ecs/src/observer/system_param.rs +++ b/crates/bevy_ecs/src/observer/system_param.rs @@ -1,7 +1,7 @@ //! System parameters for working with observers. use crate::{ - bundle::Bundle, + bundle::StaticBundle, change_detection::MaybeLocation, event::{Event, EventKey, PropagateEntityTrigger}, prelude::*, @@ -31,7 +31,7 @@ use core::{ // SAFETY WARNING! // this type must _never_ expose anything with the 'w lifetime // See the safety discussion on `Trigger` for more details. -pub struct On<'w, 't, E: Event, B: Bundle = ()> { +pub struct On<'w, 't, E: Event, B: StaticBundle = ()> { observer: Entity, // SAFETY WARNING: never expose this 'w lifetime event: &'w mut E, @@ -46,7 +46,7 @@ pub struct On<'w, 't, E: Event, B: Bundle = ()> { #[deprecated(since = "0.17.0", note = "Renamed to `On`.")] pub type Trigger<'w, 't, E, B = ()> = On<'w, 't, E, B>; -impl<'w, 't, E: Event, B: Bundle> On<'w, 't, E, B> { +impl<'w, 't, E: Event, B: StaticBundle> On<'w, 't, E, B> { /// Creates a new instance of [`On`] for the given triggered event. pub fn new( event: &'w mut E, @@ -130,7 +130,7 @@ impl< 't, const AUTO_PROPAGATE: bool, E: EntityEvent + for<'a> Event = PropagateEntityTrigger>, - B: Bundle, + B: StaticBundle, T: Traversal, > On<'w, 't, E, B> { @@ -178,7 +178,9 @@ impl< } } -impl<'w, 't, E: for<'a> Event: Debug> + Debug, B: Bundle> Debug for On<'w, 't, E, B> { +impl<'w, 't, E: for<'a> Event: Debug> + Debug, B: StaticBundle> Debug + for On<'w, 't, E, B> +{ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("On") .field("event", &self.event) @@ -188,7 +190,7 @@ impl<'w, 't, E: for<'a> Event: Debug> + Debug, B: Bundle> Debug for } } -impl<'w, 't, E: Event, B: Bundle> Deref for On<'w, 't, E, B> { +impl<'w, 't, E: Event, B: StaticBundle> Deref for On<'w, 't, E, B> { type Target = E; fn deref(&self) -> &Self::Target { @@ -196,7 +198,7 @@ impl<'w, 't, E: Event, B: Bundle> Deref for On<'w, 't, E, B> { } } -impl<'w, 't, E: Event, B: Bundle> DerefMut for On<'w, 't, E, B> { +impl<'w, 't, E: Event, B: StaticBundle> DerefMut for On<'w, 't, 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 0e868e0be3496..e2aa0d7a51041 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}, @@ -1155,7 +1155,7 @@ unsafe impl<'a, 'b> QueryData for FilteredEntityMut<'a, 'b> { /// are rejected. unsafe impl<'a, 'b, B> WorldQuery for EntityRefExcept<'a, 'b, B> where - B: Bundle, + B: StaticBundle, { type Fetch<'w> = EntityFetch<'w>; type State = Access; @@ -1233,7 +1233,7 @@ where /// SAFETY: `Self` is the same as `Self::ReadOnly`. unsafe impl<'a, 'b, B> QueryData for EntityRefExcept<'a, 'b, B> where - B: Bundle, + B: StaticBundle, { const IS_READ_ONLY: bool = true; type ReadOnly = Self; @@ -1261,14 +1261,14 @@ where /// SAFETY: `EntityRefExcept` enforces read-only access to its contained /// components. -unsafe impl ReadOnlyQueryData for EntityRefExcept<'_, '_, B> where B: Bundle {} +unsafe impl ReadOnlyQueryData for EntityRefExcept<'_, '_, 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, B> WorldQuery for EntityMutExcept<'a, 'b, B> where - B: Bundle, + B: StaticBundle, { type Fetch<'w> = EntityFetch<'w>; type State = Access; @@ -1347,7 +1347,7 @@ where /// `EntityMutExcept` provides. unsafe impl<'a, 'b, B> QueryData for EntityMutExcept<'a, 'b, B> where - B: Bundle, + B: StaticBundle, { const IS_READ_ONLY: bool = false; type ReadOnly = EntityRefExcept<'a, 'b, B>; diff --git a/crates/bevy_ecs/src/query/iter.rs b/crates/bevy_ecs/src/query/iter.rs index cab2ee9c9391d..cba708d088b71 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 72dc16b2fd181..78c39c1f68d0f 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 e9b7849441ece..689e2b1174a6d 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::{ @@ -358,7 +358,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(); @@ -553,7 +553,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 e4b7340c9ccfc..038596179a698 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, DynamicBundle, InsertMode, NoBundleEffect}, + bundle::{Bundle, DynamicBundle, InsertMode, NoBundleEffect, StaticBundle}, change_detection::MaybeLocation, entity::Entity, query::DebugCheckedUnwrap, @@ -56,7 +56,9 @@ pub trait SpawnableList: Sized { fn size_hint(&self) -> usize; } -impl> SpawnableList for Vec { +impl + StaticBundle> SpawnableList + for Vec +{ fn spawn(ptr: MovingPtr<'_, Self>, world: &mut World, entity: Entity) { let mapped_bundles = ptr.read().into_iter().map(|b| (R::from(entity), b)); world.spawn_batch(mapped_bundles); @@ -305,22 +307,43 @@ pub struct SpawnRelatedBundle> { marker: PhantomData, } +// SAFETY: This internally relies on the RelationshipTarget's Bundle 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); + } + + fn get_component_ids( + components: &crate::component::Components, + ids: &mut impl FnMut(Option), + ) { + ::get_component_ids(components, ids); + } +} + // 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); + ::component_ids(components, ids); } fn get_component_ids( + &self, components: &crate::component::Components, ids: &mut impl FnMut(Option), ) { - ::get_component_ids(components, ids); + ::get_component_ids(components, ids); } } @@ -399,21 +422,39 @@ impl DynamicBundle for SpawnOneRelated { entity.with_related::(effect.bundle); } } +// 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); + } + + fn get_component_ids( + components: &crate::component::Components, + ids: &mut impl FnMut(Option), + ) { + ::get_component_ids(components, ids); + } +} // 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); + ::component_ids(components, ids); } fn get_component_ids( + &self, components: &crate::component::Components, ids: &mut impl FnMut(Option), ) { - ::get_component_ids(components, ids); + ::get_component_ids(components, ids); } } diff --git a/crates/bevy_ecs/src/system/commands/command.rs b/crates/bevy_ecs/src/system/commands/command.rs index 764aa840d7e53..326f301daf562 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 4d79d789806a0..3f1d1cc4e27d8 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}, @@ -183,7 +183,7 @@ where /// 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); @@ -193,7 +193,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); @@ -219,9 +219,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); @@ -248,7 +248,7 @@ pub fn despawn() -> impl EntityCommand { /// watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`] /// targets this entity. #[track_caller] -pub fn observe( +pub fn observe( observer: impl IntoObserverSystem, ) -> impl EntityCommand { let caller = MaybeLocation::caller(); @@ -294,7 +294,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); } @@ -314,7 +314,7 @@ pub fn clone_components(target: Entity) -> impl EntityCommand { /// /// [`Ignore`]: crate::component::ComponentCloneBehavior::Ignore /// [`Custom`]: crate::component::ComponentCloneBehavior::Custom -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 13967a46ddf61..3ca7d35eae18f 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -16,7 +16,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}, @@ -536,7 +536,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)); } @@ -689,7 +689,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)); } @@ -720,7 +720,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)); } @@ -750,7 +750,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)); } @@ -781,7 +781,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)); } @@ -1131,7 +1131,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<'_> { @@ -1656,7 +1656,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) } @@ -1692,7 +1692,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 { @@ -1709,7 +1709,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 { @@ -1757,7 +1760,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_silenced(entity_command::remove::()) } @@ -1789,7 +1792,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::()) } @@ -1986,7 +1989,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::()) } @@ -2007,7 +2010,7 @@ impl<'a> EntityCommands<'a> { /// Creates an [`Observer`] watching for an [`EntityEvent`] of type `E` whose [`EntityEvent::event_target`] /// targets this entity. - pub fn observe( + pub fn observe( &mut self, observer: impl IntoObserverSystem, ) -> &mut Self { @@ -2237,7 +2240,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)) } @@ -2255,7 +2258,7 @@ impl<'a> EntityCommands<'a> { /// /// [`Ignore`]: crate::component::ComponentCloneBehavior::Ignore /// [`Custom`]: crate::component::ComponentCloneBehavior::Custom - 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 429f4df018ed6..5d4e9c98c3654 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, event::Event, prelude::On, system::System}; +use crate::{bundle::StaticBundle, event::Event, 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> { // Note: the fact that we must use a shared lifetime here is // a key piece of the complicated safety story documented above // the `&mut E::Trigger<'_>` cast in `observer_system_runner` and in diff --git a/crates/bevy_ecs/src/system/observer_system.rs b/crates/bevy_ecs/src/system/observer_system.rs index fe612a3d8bc53..c5d3db1efdeda 100644 --- a/crates/bevy_ecs/src/system/observer_system.rs +++ b/crates/bevy_ecs/src/system/observer_system.rs @@ -1,18 +1,14 @@ -use crate::{ - event::Event, - prelude::{Bundle, On}, - system::System, -}; +use crate::{bundle::StaticBundle, event::Event, prelude::On, system::System}; use super::IntoSystem; /// 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 { } @@ -29,7 +25,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; @@ -42,7 +38,7 @@ where S: IntoSystem, Out, M> + Send + 'static, S::System: ObserverSystem, E: 'static, - B: Bundle, + B: StaticBundle, { type System = S::System; diff --git a/crates/bevy_ecs/src/world/entity_ref.rs b/crates/bevy_ecs/src/world/entity_ref.rs index 59d8b97de7f3e..7ff2513c24093 100644 --- a/crates/bevy_ecs/src/world/entity_ref.rs +++ b/crates/bevy_ecs/src/world/entity_ref.rs @@ -2,6 +2,7 @@ use crate::{ archetype::Archetype, bundle::{ Bundle, BundleFromComponents, BundleInserter, BundleRemover, DynamicBundle, InsertMode, + StaticBundle, }, change_detection::{MaybeLocation, MutUntyped}, component::{Component, ComponentId, ComponentTicks, Components, Mutable, StorageType, Tick}, @@ -2036,7 +2037,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 and thus must currently exist in the source // archetype for this inserter and its location within the archetype. @@ -2204,7 +2205,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; @@ -2260,12 +2261,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) = @@ -2297,11 +2301,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 { @@ -2339,12 +2343,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 retained_bundle = self.world.register_bundle_info::(); let archetypes = &mut self.world.archetypes; @@ -2850,14 +2857,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, @@ -3088,7 +3095,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) @@ -3110,7 +3117,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) @@ -3760,7 +3767,7 @@ impl<'a> From<&'a EntityWorldMut<'_>> for FilteredEntityRef<'a, 'static> { } } -impl<'w, 's, B: Bundle> From<&'w EntityRefExcept<'_, 's, B>> for FilteredEntityRef<'w, 's> { +impl<'w, 's, B: StaticBundle> From<&'w EntityRefExcept<'_, 's, B>> for FilteredEntityRef<'w, 's> { fn from(value: &'w EntityRefExcept<'_, 's, B>) -> Self { // SAFETY: // - The FilteredEntityRef has the same component access as the given EntityRefExcept. @@ -4088,7 +4095,7 @@ impl<'a> From<&'a mut EntityWorldMut<'_>> for FilteredEntityMut<'a, 'static> { } } -impl<'w, 's, B: Bundle> From<&'w EntityMutExcept<'_, 's, B>> for FilteredEntityMut<'w, 's> { +impl<'w, 's, B: StaticBundle> From<&'w EntityMutExcept<'_, 's, B>> for FilteredEntityMut<'w, 's> { fn from(value: &'w EntityMutExcept<'_, 's, B>) -> Self { // SAFETY: // - The FilteredEntityMut has the same component access as the given EntityMutExcept. @@ -4152,7 +4159,7 @@ pub enum TryFromFilteredError { /// for an explicitly-enumerated set. pub struct EntityRefExcept<'w, 's, B> where - B: Bundle, + B: StaticBundle, { entity: UnsafeEntityCell<'w>, access: &'s Access, @@ -4161,7 +4168,7 @@ where impl<'w, 's, B> EntityRefExcept<'w, 's, B> where - B: Bundle, + B: StaticBundle, { /// # Safety /// Other users of `UnsafeEntityCell` must only have mutable access to the components in `B`. @@ -4323,7 +4330,7 @@ where impl<'w, 's, B> From<&'w EntityMutExcept<'_, 's, B>> for EntityRefExcept<'w, 's, B> where - B: Bundle, + B: StaticBundle, { fn from(entity: &'w EntityMutExcept<'_, 's, B>) -> Self { // SAFETY: All accesses that `EntityRefExcept` provides are also @@ -4332,23 +4339,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 { @@ -4356,26 +4363,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. @@ -4387,7 +4394,7 @@ unsafe impl EntityEquivalent for EntityRefExcept<'_, '_, B> {} /// [`Without`](`crate::query::Without`) filter. pub struct EntityMutExcept<'w, 's, B> where - B: Bundle, + B: StaticBundle, { entity: UnsafeEntityCell<'w>, access: &'s Access, @@ -4396,7 +4403,7 @@ where impl<'w, 's, B> EntityMutExcept<'w, 's, B> where - B: Bundle, + B: StaticBundle, { /// # Safety /// Other users of `UnsafeEntityCell` must not have access to any components not in `B`. @@ -4557,15 +4564,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 { @@ -4573,30 +4580,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 4c6d3c5455d51..60469e82895d5 100644 --- a/crates/bevy_ecs/src/world/mod.rs +++ b/crates/bevy_ecs/src/world/mod.rs @@ -33,7 +33,7 @@ use crate::{ archetype::{ArchetypeId, Archetypes}, bundle::{ Bundle, BundleId, BundleInfo, BundleInserter, BundleSpawner, Bundles, InsertMode, - NoBundleEffect, + NoBundleEffect, StaticBundle, }, change_detection::{MaybeLocation, MutUntyped, TicksMut}, component::{ @@ -1164,7 +1164,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); let (bundle, entity_location) = bundle.partial_move(|bundle| { // SAFETY: // - `B` matches `bundle_spawner`'s type @@ -1240,7 +1240,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()) } @@ -2256,7 +2256,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.insert_batch_with_caller(batch, InsertMode::Replace, MaybeLocation::caller()); } @@ -2281,7 +2281,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { self.insert_batch_with_caller(batch, InsertMode::Keep, MaybeLocation::caller()); } @@ -2300,7 +2300,7 @@ impl World { ) where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { struct InserterArchetypeCache<'w> { inserter: BundleInserter<'w>, @@ -2404,7 +2404,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()) } @@ -2426,7 +2426,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()) } @@ -2450,7 +2450,7 @@ impl World { where I: IntoIterator, I::IntoIter: Iterator, - B: Bundle, + B: Bundle + StaticBundle, { struct InserterArchetypeCache<'w> { inserter: BundleInserter<'w>, @@ -3085,14 +3085,14 @@ 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 { let id = self.register_bundle_info::(); // SAFETY: We just initialized the bundle so its id should definitely be valid. unsafe { self.bundles.get(id).debug_checked_unwrap() } } - pub(crate) fn register_bundle_info(&mut self) -> BundleId { + pub(crate) fn register_bundle_info(&mut self) -> BundleId { // 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) }; @@ -3100,11 +3100,11 @@ impl World { // SAFETY: `registrator`, `self.storages` and `self.bundles` all come from this world. unsafe { self.bundles - .register_info::(&mut registrator, &mut self.storages) + .register_static_info::(&mut registrator, &mut self.storages) } } - pub(crate) fn register_contributed_bundle_info(&mut self) -> BundleId { + pub(crate) fn register_contributed_bundle_info(&mut self) -> BundleId { // 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) }; diff --git a/crates/bevy_ecs/src/world/spawn_batch.rs b/crates/bevy_ecs/src/world/spawn_batch.rs index 9f9c87ee572b9..17d5f5d0689f2 100644 --- a/crates/bevy_ecs/src/world/spawn_batch.rs +++ b/crates/bevy_ecs/src/world/spawn_batch.rs @@ -1,7 +1,7 @@ use bevy_ptr::move_as_ptr; use crate::{ - bundle::{Bundle, BundleSpawner, NoBundleEffect}, + bundle::{Bundle, BundleSpawner, NoBundleEffect, StaticBundle}, change_detection::MaybeLocation, entity::{Entity, EntitySetIterator}, world::World, @@ -15,7 +15,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>, @@ -25,7 +25,7 @@ where impl<'w, I> SpawnBatchIter<'w, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { #[inline] #[track_caller] @@ -40,7 +40,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 { @@ -54,7 +54,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. @@ -68,7 +68,7 @@ where impl Iterator for SpawnBatchIter<'_, I> where I: Iterator, - I::Item: Bundle, + I::Item: Bundle + StaticBundle, { type Item = Entity; @@ -90,7 +90,7 @@ where impl ExactSizeIterator for SpawnBatchIter<'_, I> where I: ExactSizeIterator, - T: Bundle, + T: Bundle + StaticBundle, { fn len(&self) -> usize { self.inner.len() @@ -100,7 +100,7 @@ where impl FusedIterator for SpawnBatchIter<'_, I> where I: FusedIterator, - T: Bundle, + T: Bundle + StaticBundle, { } @@ -108,6 +108,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 ce656c357924e..c187f11ab1f7d 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_camera::visibility::ViewVisibility; 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`