Skip to content

Commit

Permalink
Spawn now takes a Bundle (#6054)
Browse files Browse the repository at this point in the history
# Objective

Now that we can consolidate Bundles and Components under a single insert (thanks to #2975 and #6039), almost 100% of world spawns now look like `world.spawn().insert((Some, Tuple, Here))`. Spawning an entity without any components is an extremely uncommon pattern, so it makes sense to give spawn the "first class" ergonomic api. This consolidated api should be made consistent across all spawn apis (such as World and Commands).

## Solution

All `spawn` apis (`World::spawn`, `Commands:;spawn`, `ChildBuilder::spawn`, and `WorldChildBuilder::spawn`) now accept a bundle as input:

```rust
// before:
commands
  .spawn()
  .insert((A, B, C));
world
  .spawn()
  .insert((A, B, C);

// after
commands.spawn((A, B, C));
world.spawn((A, B, C));
```

All existing instances of `spawn_bundle` have been deprecated in favor of the new `spawn` api. A new `spawn_empty` has been added, replacing the old `spawn` api.  

By allowing `world.spawn(some_bundle)` to replace `world.spawn().insert(some_bundle)`, this opened the door to removing the initial entity allocation in the "empty" archetype / table done in `spawn()` (and subsequent move to the actual archetype in `.insert(some_bundle)`).

This improves spawn performance by over 10%:
![image](https://user-images.githubusercontent.com/2694663/191627587-4ab2f949-4ccd-4231-80eb-80dd4d9ad6b9.png)

To take this measurement, I added a new `world_spawn` benchmark.

Unfortunately, optimizing `Commands::spawn` is slightly less trivial, as Commands expose the Entity id of spawned entities prior to actually spawning. Doing the optimization would (naively) require assurances that the `spawn(some_bundle)` command is applied before all other commands involving the entity (which would not necessarily be true, if memory serves). Optimizing `Commands::spawn` this way does feel possible, but it will require careful thought (and maybe some additional checks), which deserves its own PR. For now, it has the same performance characteristics of the current `Commands::spawn_bundle` on main.

**Note that 99% of this PR is simple renames and refactors. The only code that needs careful scrutiny is the new `World::spawn()` impl, which is relatively straightforward, but it has some new unsafe code (which re-uses battle tested BundlerSpawner code path).** 

---

## Changelog

- All `spawn` apis (`World::spawn`, `Commands:;spawn`, `ChildBuilder::spawn`, and `WorldChildBuilder::spawn`) now accept a bundle as input
- All instances of `spawn_bundle` have been deprecated in favor of the new `spawn` api
- World and Commands now have `spawn_empty()`, which is equivalent to the old `spawn()` behavior.  

## Migration Guide

```rust
// Old (0.8):
commands
  .spawn()
  .insert_bundle((A, B, C));
// New (0.9)
commands.spawn((A, B, C));

// Old (0.8):
commands.spawn_bundle((A, B, C));
// New (0.9)
commands.spawn((A, B, C));

// Old (0.8):
let entity = commands.spawn().id();
// New (0.9)
let entity = commands.spawn_empty().id();

// Old (0.8)
let entity = world.spawn().id();
// New (0.9)
let entity = world.spawn_empty();
```
  • Loading branch information
cart committed Sep 23, 2022
1 parent fb74ca3 commit 01aedc8
Show file tree
Hide file tree
Showing 164 changed files with 1,500 additions and 1,378 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ impl Benchmark {
for _ in 0..10_000 {
entities.push(
world
.spawn()
.insert((
.spawn((
A(Mat4::from_scale(Vec3::ONE)),
B(Mat4::from_scale(Vec3::ONE)),
C(Mat4::from_scale(Vec3::ONE)),
Expand Down
3 changes: 1 addition & 2 deletions benches/benches/bevy_ecs/components/add_remove_big_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ impl Benchmark {
for _ in 0..10_000 {
entities.push(
world
.spawn()
.insert((
.spawn((
A(Mat4::from_scale(Vec3::ONE)),
B(Mat4::from_scale(Vec3::ONE)),
C(Mat4::from_scale(Vec3::ONE)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ impl Benchmark {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(world.spawn().insert(A(0.0)).id());
entities.push(world.spawn(A(0.0)).id());
}

Self(world, entities)
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/components/add_remove_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ impl Benchmark {
let mut world = World::default();
let mut entities = Vec::with_capacity(10_000);
for _ in 0..10_000 {
entities.push(world.spawn().insert(A(0.0)).id());
entities.push(world.spawn(A(0.0)).id());
}

Self(world, entities)
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/components/archetype_updates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ fn setup(system_count: usize) -> (World, SystemStage) {
/// create `count` entities with distinct archetypes
fn add_archetypes(world: &mut World, count: u16) {
for i in 0..count {
let mut e = world.spawn();
let mut e = world.spawn_empty();
if i & 1 << 0 != 0 {
e.insert(A::<0>(1.0));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl Benchmark {
pub fn run(&mut self) {
let mut world = World::new();
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_frag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn().insert(($variants(0.0), Data(1.0)));
$world.spawn(($variants(0.0), Data(1.0)));
}
)*
};
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_frag_foreach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn().insert(($variants(0.0), Data(1.0)));
$world.spawn(($variants(0.0), Data(1.0)));
}
)*
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn().insert($variants(0.0));
$world.spawn($variants(0.0));
}
)*
};
Expand All @@ -21,7 +21,7 @@ impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn().insert(Data(1.0));
world.spawn(Data(1.0));
}

create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn().insert((
$world.spawn((
$variants(0.0),
Data::<0>(1.0),
Data::<1>(1.0),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn().insert($variants(0.0));
$world.spawn($variants(0.0));
}
)*
};
Expand Down Expand Up @@ -36,7 +36,7 @@ impl<'w> Benchmark<'w> {
pub fn new() -> Self {
let mut world = World::new();
for _ in 0..5 {
world.spawn().insert((
world.spawn((
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Expand Down
4 changes: 2 additions & 2 deletions benches/benches/bevy_ecs/iteration/iter_frag_sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn().insert($variants(0.0));
$world.spawn($variants(0.0));
}
)*
};
Expand All @@ -21,7 +21,7 @@ impl<'w> Benchmark<'w> {
let mut world = World::new();

for _ in 0..5 {
world.spawn().insert(Data(1.0));
world.spawn(Data(1.0));
}

create_entities!(world; C00, C01, C02, C03, C04, C05, C06, C07, C08, C09);
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_frag_wide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..20 {
$world.spawn().insert((
$world.spawn((
$variants(0.0),
Data::<0>(1.0),
Data::<1>(1.0),
Expand Down
4 changes: 2 additions & 2 deletions benches/benches/bevy_ecs/iteration/iter_frag_wide_sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ macro_rules! create_entities {
#[derive(Component)]
struct $variants(f32);
for _ in 0..5 {
$world.spawn().insert($variants(0.0));
$world.spawn($variants(0.0));
}
)*
};
Expand Down Expand Up @@ -36,7 +36,7 @@ impl<'w> Benchmark<'w> {
let mut world = World::new();

for _ in 0..5 {
world.spawn().insert((
world.spawn((
Data::<0>(1.0),
Data::<1>(1.0),
Data::<2>(1.0),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_simple_foreach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_simple_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl Benchmark {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Position(Vec3::X),
Rotation(Vec3::X),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/iteration/iter_simple_wide.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ impl<'w> Benchmark<'w> {

// TODO: batch this
for _ in 0..10_000 {
world.spawn().insert((
world.spawn((
Transform(Mat4::from_scale(Vec3::ONE)),
Rotation(Vec3::X),
Position::<0>(Vec3::X),
Expand Down
2 changes: 1 addition & 1 deletion benches/benches/bevy_ecs/scheduling/run_criteria.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ struct TestBool(pub bool);

pub fn run_criteria_yes_with_query(criterion: &mut Criterion) {
let mut world = World::new();
world.spawn().insert(TestBool(true));
world.spawn(TestBool(true));
let mut group = criterion.benchmark_group("run_criteria/yes_using_query");
group.warm_up_time(std::time::Duration::from_millis(500));
group.measurement_time(std::time::Duration::from_secs(3));
Expand Down
6 changes: 3 additions & 3 deletions benches/benches/bevy_ecs/world/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn spawn_commands(criterion: &mut Criterion) {
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..entity_count {
let mut entity = commands.spawn();
let mut entity = commands.spawn_empty();

if black_box(i % 2 == 0) {
entity.insert(A);
Expand Down Expand Up @@ -87,7 +87,7 @@ pub fn insert_commands(criterion: &mut Criterion) {
let mut command_queue = CommandQueue::default();
let mut entities = Vec::new();
for _ in 0..entity_count {
entities.push(world.spawn().id());
entities.push(world.spawn_empty().id());
}

bencher.iter(|| {
Expand All @@ -106,7 +106,7 @@ pub fn insert_commands(criterion: &mut Criterion) {
let mut command_queue = CommandQueue::default();
let mut entities = Vec::new();
for _ in 0..entity_count {
entities.push(world.spawn().id());
entities.push(world.spawn_empty().id());
}

bencher.iter(|| {
Expand Down
3 changes: 3 additions & 0 deletions benches/benches/bevy_ecs/world/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
use criterion::criterion_group;

mod commands;
mod spawn;
mod world_get;

use commands::*;
use spawn::*;
use world_get::*;

criterion_group!(
Expand All @@ -21,6 +23,7 @@ criterion_group!(
world_query_get,
world_query_iter,
world_query_for_each,
world_spawn,
query_get_component_simple,
query_get_component,
query_get,
Expand Down
27 changes: 27 additions & 0 deletions benches/benches/bevy_ecs/world/spawn.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use bevy_ecs::prelude::*;
use criterion::Criterion;
use glam::*;

#[derive(Component)]
struct A(Mat4);
#[derive(Component)]
struct B(Vec4);

pub fn world_spawn(criterion: &mut Criterion) {
let mut group = criterion.benchmark_group("spawn_world");
group.warm_up_time(std::time::Duration::from_millis(500));
group.measurement_time(std::time::Duration::from_secs(4));

for entity_count in (0..5).map(|i| 10_u32.pow(i)) {
group.bench_function(format!("{}_entities", entity_count), |bencher| {
let mut world = World::default();
bencher.iter(|| {
for _ in 0..entity_count {
world.spawn((A(Mat4::default()), B(Vec4::default())));
}
});
});
}

group.finish();
}
4 changes: 2 additions & 2 deletions benches/benches/bevy_ecs/world/world_get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ pub fn query_get_component_simple(criterion: &mut Criterion) {
group.bench_function("unchecked", |bencher| {
let mut world = World::new();

let entity = world.spawn().insert(A(0.0)).id();
let entity = world.spawn(A(0.0)).id();
let mut query = world.query::<&mut A>();

bencher.iter(|| {
Expand All @@ -281,7 +281,7 @@ pub fn query_get_component_simple(criterion: &mut Criterion) {
group.bench_function("system", |bencher| {
let mut world = World::new();

let entity = world.spawn().insert(A(0.0)).id();
let entity = world.spawn(A(0.0)).id();
fn query_system(In(entity): In<Entity>, mut query: Query<&mut A>) {
for _ in 0..100_000 {
let mut a = query.get_mut(entity).unwrap();
Expand Down
16 changes: 8 additions & 8 deletions crates/bevy_ecs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,8 @@ struct Velocity { x: f32, y: f32 }

let mut world = World::new();

let entity = world.spawn()
.insert(Position { x: 0.0, y: 0.0 })
.insert(Velocity { x: 1.0, y: 0.0 })
let entity = world
.spawn((Position { x: 0.0, y: 0.0 }, Velocity { x: 1.0, y: 0.0 }))
.id();

let entity_ref = world.entity(entity);
Expand Down Expand Up @@ -141,9 +140,10 @@ fn main() {
let mut world = World::new();

// Spawn an entity with Position and Velocity components
world.spawn()
.insert(Position { x: 0.0, y: 0.0 })
.insert(Velocity { x: 1.0, y: 0.0 });
world.spawn((
Position { x: 0.0, y: 0.0 },
Velocity { x: 1.0, y: 0.0 },
));

// Create a new Schedule, which defines an execution strategy for Systems
let mut schedule = Schedule::default();
Expand Down Expand Up @@ -276,10 +276,10 @@ struct PlayerBundle {
let mut world = World::new();

// Spawn a new entity and insert the default PlayerBundle
world.spawn().insert(PlayerBundle::default());
world.spawn(PlayerBundle::default());

// Bundles play well with Rust's struct update syntax
world.spawn().insert(PlayerBundle {
world.spawn(PlayerBundle {
position: Position { x: 1.0, y: 1.0 },
..Default::default()
});
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_ecs/examples/change_detection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ enum SimulationSystem {
// If an entity gets spawned, we increase the counter in the EntityCounter resource
fn spawn_entities(mut commands: Commands, mut entity_counter: ResMut<EntityCounter>) {
if rand::thread_rng().gen_bool(0.6) {
let entity_id = commands.spawn_bundle(Age::default()).id();
let entity_id = commands.spawn(Age::default()).id();
println!(" spawning {:?}", entity_id);
entity_counter.value += 1;
}
Expand Down
Loading

0 comments on commit 01aedc8

Please sign in to comment.