
# 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%:  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(); ```
271 lines
8.4 KiB
Rust
271 lines
8.4 KiB
Rust
//! A shader that uses dynamic data like the time since startup.
|
|
//!
|
|
//! This example uses a specialized pipeline.
|
|
|
|
use bevy::{
|
|
core_pipeline::core_3d::Transparent3d,
|
|
ecs::system::{
|
|
lifetimeless::{Read, SRes},
|
|
SystemParamItem,
|
|
},
|
|
pbr::{
|
|
DrawMesh, MeshPipeline, MeshPipelineKey, MeshUniform, SetMeshBindGroup,
|
|
SetMeshViewBindGroup,
|
|
},
|
|
prelude::*,
|
|
render::{
|
|
extract_component::{ExtractComponent, ExtractComponentPlugin},
|
|
extract_resource::{ExtractResource, ExtractResourcePlugin},
|
|
mesh::MeshVertexBufferLayout,
|
|
render_asset::RenderAssets,
|
|
render_phase::{
|
|
AddRenderCommand, DrawFunctions, EntityRenderCommand, RenderCommandResult, RenderPhase,
|
|
SetItemPipeline, TrackedRenderPass,
|
|
},
|
|
render_resource::*,
|
|
renderer::{RenderDevice, RenderQueue},
|
|
view::{ComputedVisibility, ExtractedView, Msaa, Visibility},
|
|
RenderApp, RenderStage,
|
|
},
|
|
};
|
|
|
|
fn main() {
|
|
App::new()
|
|
.add_plugins(DefaultPlugins)
|
|
.add_plugin(CustomMaterialPlugin)
|
|
.add_startup_system(setup)
|
|
.run();
|
|
}
|
|
|
|
fn setup(mut commands: Commands, mut meshes: ResMut<Assets<Mesh>>) {
|
|
// cube
|
|
commands.spawn((
|
|
meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
|
|
Transform::from_xyz(0.0, 0.5, 0.0),
|
|
GlobalTransform::default(),
|
|
CustomMaterial,
|
|
Visibility::default(),
|
|
ComputedVisibility::default(),
|
|
));
|
|
|
|
// camera
|
|
commands.spawn(Camera3dBundle {
|
|
transform: Transform::from_xyz(-2.0, 2.5, 5.0).looking_at(Vec3::ZERO, Vec3::Y),
|
|
..default()
|
|
});
|
|
}
|
|
|
|
#[derive(Component)]
|
|
struct CustomMaterial;
|
|
|
|
pub struct CustomMaterialPlugin;
|
|
|
|
impl Plugin for CustomMaterialPlugin {
|
|
fn build(&self, app: &mut App) {
|
|
let render_device = app.world.resource::<RenderDevice>();
|
|
let buffer = render_device.create_buffer(&BufferDescriptor {
|
|
label: Some("time uniform buffer"),
|
|
size: std::mem::size_of::<f32>() as u64,
|
|
usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
|
|
mapped_at_creation: false,
|
|
});
|
|
app.add_plugin(ExtractComponentPlugin::<CustomMaterial>::default())
|
|
.add_plugin(ExtractResourcePlugin::<ExtractedTime>::default());
|
|
|
|
app.sub_app_mut(RenderApp)
|
|
.add_render_command::<Transparent3d, DrawCustom>()
|
|
.insert_resource(TimeMeta {
|
|
buffer,
|
|
bind_group: None,
|
|
})
|
|
.init_resource::<CustomPipeline>()
|
|
.init_resource::<SpecializedMeshPipelines<CustomPipeline>>()
|
|
.add_system_to_stage(RenderStage::Prepare, prepare_time)
|
|
.add_system_to_stage(RenderStage::Queue, queue_custom)
|
|
.add_system_to_stage(RenderStage::Queue, queue_time_bind_group);
|
|
}
|
|
}
|
|
|
|
impl ExtractComponent for CustomMaterial {
|
|
type Query = Read<CustomMaterial>;
|
|
|
|
type Filter = ();
|
|
|
|
fn extract_component(_: bevy::ecs::query::QueryItem<Self::Query>) -> Self {
|
|
CustomMaterial
|
|
}
|
|
}
|
|
|
|
// add each entity with a mesh and a `CustomMaterial` to every view's `Transparent3d` render phase using the `CustomPipeline`
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn queue_custom(
|
|
transparent_3d_draw_functions: Res<DrawFunctions<Transparent3d>>,
|
|
custom_pipeline: Res<CustomPipeline>,
|
|
msaa: Res<Msaa>,
|
|
mut pipelines: ResMut<SpecializedMeshPipelines<CustomPipeline>>,
|
|
mut pipeline_cache: ResMut<PipelineCache>,
|
|
render_meshes: Res<RenderAssets<Mesh>>,
|
|
material_meshes: Query<(Entity, &MeshUniform, &Handle<Mesh>), With<CustomMaterial>>,
|
|
mut views: Query<(&ExtractedView, &mut RenderPhase<Transparent3d>)>,
|
|
) {
|
|
let draw_custom = transparent_3d_draw_functions
|
|
.read()
|
|
.get_id::<DrawCustom>()
|
|
.unwrap();
|
|
|
|
let key = MeshPipelineKey::from_msaa_samples(msaa.samples)
|
|
| MeshPipelineKey::from_primitive_topology(PrimitiveTopology::TriangleList);
|
|
|
|
for (view, mut transparent_phase) in &mut views {
|
|
let rangefinder = view.rangefinder3d();
|
|
for (entity, mesh_uniform, mesh_handle) in &material_meshes {
|
|
if let Some(mesh) = render_meshes.get(mesh_handle) {
|
|
let pipeline = pipelines
|
|
.specialize(&mut pipeline_cache, &custom_pipeline, key, &mesh.layout)
|
|
.unwrap();
|
|
transparent_phase.add(Transparent3d {
|
|
entity,
|
|
pipeline,
|
|
draw_function: draw_custom,
|
|
distance: rangefinder.distance(&mesh_uniform.transform),
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Default)]
|
|
struct ExtractedTime {
|
|
seconds_since_startup: f32,
|
|
}
|
|
|
|
impl ExtractResource for ExtractedTime {
|
|
type Source = Time;
|
|
|
|
fn extract_resource(time: &Self::Source) -> Self {
|
|
ExtractedTime {
|
|
seconds_since_startup: time.seconds_since_startup() as f32,
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
struct TimeMeta {
|
|
buffer: Buffer,
|
|
bind_group: Option<BindGroup>,
|
|
}
|
|
|
|
// write the extracted time into the corresponding uniform buffer
|
|
fn prepare_time(
|
|
time: Res<ExtractedTime>,
|
|
time_meta: ResMut<TimeMeta>,
|
|
render_queue: Res<RenderQueue>,
|
|
) {
|
|
render_queue.write_buffer(
|
|
&time_meta.buffer,
|
|
0,
|
|
bevy::core::cast_slice(&[time.seconds_since_startup]),
|
|
);
|
|
}
|
|
|
|
// create a bind group for the time uniform buffer
|
|
fn queue_time_bind_group(
|
|
render_device: Res<RenderDevice>,
|
|
mut time_meta: ResMut<TimeMeta>,
|
|
pipeline: Res<CustomPipeline>,
|
|
) {
|
|
let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
|
|
label: None,
|
|
layout: &pipeline.time_bind_group_layout,
|
|
entries: &[BindGroupEntry {
|
|
binding: 0,
|
|
resource: time_meta.buffer.as_entire_binding(),
|
|
}],
|
|
});
|
|
time_meta.bind_group = Some(bind_group);
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
pub struct CustomPipeline {
|
|
shader: Handle<Shader>,
|
|
mesh_pipeline: MeshPipeline,
|
|
time_bind_group_layout: BindGroupLayout,
|
|
}
|
|
|
|
impl FromWorld for CustomPipeline {
|
|
fn from_world(world: &mut World) -> Self {
|
|
let asset_server = world.resource::<AssetServer>();
|
|
let shader = asset_server.load("shaders/animate_shader.wgsl");
|
|
|
|
let render_device = world.resource::<RenderDevice>();
|
|
let time_bind_group_layout =
|
|
render_device.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
|
label: Some("time bind group"),
|
|
entries: &[BindGroupLayoutEntry {
|
|
binding: 0,
|
|
visibility: ShaderStages::FRAGMENT,
|
|
ty: BindingType::Buffer {
|
|
ty: BufferBindingType::Uniform,
|
|
has_dynamic_offset: false,
|
|
min_binding_size: BufferSize::new(std::mem::size_of::<f32>() as u64),
|
|
},
|
|
count: None,
|
|
}],
|
|
});
|
|
|
|
let mesh_pipeline = world.resource::<MeshPipeline>();
|
|
|
|
CustomPipeline {
|
|
shader,
|
|
mesh_pipeline: mesh_pipeline.clone(),
|
|
time_bind_group_layout,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl SpecializedMeshPipeline for CustomPipeline {
|
|
type Key = MeshPipelineKey;
|
|
|
|
fn specialize(
|
|
&self,
|
|
key: Self::Key,
|
|
layout: &MeshVertexBufferLayout,
|
|
) -> Result<RenderPipelineDescriptor, SpecializedMeshPipelineError> {
|
|
let mut descriptor = self.mesh_pipeline.specialize(key, layout)?;
|
|
descriptor.vertex.shader = self.shader.clone();
|
|
descriptor.fragment.as_mut().unwrap().shader = self.shader.clone();
|
|
descriptor.layout = Some(vec![
|
|
self.mesh_pipeline.view_layout.clone(),
|
|
self.mesh_pipeline.mesh_layout.clone(),
|
|
self.time_bind_group_layout.clone(),
|
|
]);
|
|
Ok(descriptor)
|
|
}
|
|
}
|
|
|
|
type DrawCustom = (
|
|
SetItemPipeline,
|
|
SetMeshViewBindGroup<0>,
|
|
SetMeshBindGroup<1>,
|
|
SetTimeBindGroup<2>,
|
|
DrawMesh,
|
|
);
|
|
|
|
struct SetTimeBindGroup<const I: usize>;
|
|
|
|
impl<const I: usize> EntityRenderCommand for SetTimeBindGroup<I> {
|
|
type Param = SRes<TimeMeta>;
|
|
|
|
fn render<'w>(
|
|
_view: Entity,
|
|
_item: Entity,
|
|
time_meta: SystemParamItem<'w, '_, Self::Param>,
|
|
pass: &mut TrackedRenderPass<'w>,
|
|
) -> RenderCommandResult {
|
|
let time_bind_group = time_meta.into_inner().bind_group.as_ref().unwrap();
|
|
pass.set_bind_group(I, time_bind_group, &[]);
|
|
|
|
RenderCommandResult::Success
|
|
}
|
|
}
|