
# Objective Fixes a part of #14274. Bevy has an incredibly inconsistent naming convention for its system sets, both internally and across the ecosystem. <img alt="System sets in Bevy" src="https://github.com/user-attachments/assets/d16e2027-793f-4ba4-9cc9-e780b14a5a1b" width="450" /> *Names of public system set types in Bevy* Most Bevy types use a naming of `FooSystem` or just `Foo`, but there are also a few `FooSystems` and `FooSet` types. In ecosystem crates on the other hand, `FooSet` is perhaps the most commonly used name in general. Conventions being so wildly inconsistent can make it harder for users to pick names for their own types, to search for system sets on docs.rs, or to even discern which types *are* system sets. To reign in the inconsistency a bit and help unify the ecosystem, it would be good to establish a common recommended naming convention for system sets in Bevy itself, similar to how plugins are commonly suffixed with `Plugin` (ex: `TimePlugin`). By adopting a consistent naming convention in first-party Bevy, we can softly nudge ecosystem crates to follow suit (for types where it makes sense to do so). Choosing a naming convention is also relevant now, as the [`bevy_cli` recently adopted lints](https://github.com/TheBevyFlock/bevy_cli/pull/345) to enforce naming for plugins and system sets, and the recommended naming used for system sets is still a bit open. ## Which Name To Use? Now the contentious part: what naming convention should we actually adopt? This was discussed on the Bevy Discord at the end of last year, starting [here](<https://discord.com/channels/691052431525675048/692572690833473578/1310659954683936789>). `FooSet` and `FooSystems` were the clear favorites, with `FooSet` very narrowly winning an unofficial poll. However, it seems to me like the consensus was broadly moving towards `FooSystems` at the end and after the poll, with Cart ([source](https://discord.com/channels/691052431525675048/692572690833473578/1311140204974706708)) and later Alice ([source](https://discord.com/channels/691052431525675048/692572690833473578/1311092530732859533)) and also me being in favor of it. Let's do a quick pros and cons list! Of course these are just what I thought of, so take it with a grain of salt. `FooSet`: - Pro: Nice and short! - Pro: Used by many ecosystem crates. - Pro: The `Set` suffix comes directly from the trait name `SystemSet`. - Pro: Pairs nicely with existing APIs like `in_set` and `configure_sets`. - Con: `Set` by itself doesn't actually indicate that it's related to systems *at all*, apart from the implemented trait. A set of what? - Con: Is `FooSet` a set of `Foo`s or a system set related to `Foo`? Ex: `ContactSet`, `MeshSet`, `EnemySet`... `FooSystems`: - Pro: Very clearly indicates that the type represents a collection of systems. The actual core concept, system(s), is in the name. - Pro: Parallels nicely with `FooPlugins` for plugin groups. - Pro: Low risk of conflicts with other names or misunderstandings about what the type is. - Pro: In most cases, reads *very* nicely and clearly. Ex: `PhysicsSystems` and `AnimationSystems` as opposed to `PhysicsSet` and `AnimationSet`. - Pro: Easy to search for on docs.rs. - Con: Usually results in longer names. - Con: Not yet as widely used. Really the big problem with `FooSet` is that it doesn't actually describe what it is. It describes what *kind of thing* it is (a set of something), but not *what it is a set of*, unless you know the type or check its docs or implemented traits. `FooSystems` on the other hand is much more self-descriptive in this regard, at the cost of being a bit longer to type. Ultimately, in some ways it comes down to preference and how you think of system sets. Personally, I was originally in favor of `FooSet`, but have been increasingly on the side of `FooSystems`, especially after seeing what the new names would actually look like in Avian and now Bevy. I prefer it because it usually reads better, is much more clearly related to groups of systems than `FooSet`, and overall *feels* more correct and natural to me in the long term. For these reasons, and because Alice and Cart also seemed to share a preference for it when it was previously being discussed, I propose that we adopt a `FooSystems` naming convention where applicable. ## Solution Rename Bevy's system set types to use a consistent `FooSet` naming where applicable. - `AccessibilitySystem` → `AccessibilitySystems` - `GizmoRenderSystem` → `GizmoRenderSystems` - `PickSet` → `PickingSystems` - `RunFixedMainLoopSystem` → `RunFixedMainLoopSystems` - `TransformSystem` → `TransformSystems` - `RemoteSet` → `RemoteSystems` - `RenderSet` → `RenderSystems` - `SpriteSystem` → `SpriteSystems` - `StateTransitionSteps` → `StateTransitionSystems` - `RenderUiSystem` → `RenderUiSystems` - `UiSystem` → `UiSystems` - `Animation` → `AnimationSystems` - `AssetEvents` → `AssetEventSystems` - `TrackAssets` → `AssetTrackingSystems` - `UpdateGizmoMeshes` → `GizmoMeshSystems` - `InputSystem` → `InputSystems` - `InputFocusSet` → `InputFocusSystems` - `ExtractMaterialsSet` → `MaterialExtractionSystems` - `ExtractMeshesSet` → `MeshExtractionSystems` - `RumbleSystem` → `RumbleSystems` - `CameraUpdateSystem` → `CameraUpdateSystems` - `ExtractAssetsSet` → `AssetExtractionSystems` - `Update2dText` → `Text2dUpdateSystems` - `TimeSystem` → `TimeSystems` - `AudioPlaySet` → `AudioPlaybackSystems` - `SendEvents` → `EventSenderSystems` - `EventUpdates` → `EventUpdateSystems` A lot of the names got slightly longer, but they are also a lot more consistent, and in my opinion the majority of them read much better. For a few of the names I took the liberty of rewording things a bit; definitely open to any further naming improvements. There are still also cases where the `FooSystems` naming doesn't really make sense, and those I left alone. This primarily includes system sets like `Interned<dyn SystemSet>`, `EnterSchedules<S>`, `ExitSchedules<S>`, or `TransitionSchedules<S>`, where the type has some special purpose and semantics. ## Todo - [x] Should I keep all the old names as deprecated type aliases? I can do this, but to avoid wasting work I'd prefer to first reach consensus on whether these renames are even desired. - [x] Migration guide - [x] Release notes
293 lines
10 KiB
Rust
293 lines
10 KiB
Rust
//! A compute shader that simulates Conway's Game of Life.
|
|
//!
|
|
//! Compute shaders use the GPU for computing arbitrary information, that may be independent of what
|
|
//! is rendered to the screen.
|
|
|
|
use bevy::{
|
|
prelude::*,
|
|
render::{
|
|
extract_resource::{ExtractResource, ExtractResourcePlugin},
|
|
render_asset::{RenderAssetUsages, RenderAssets},
|
|
render_graph::{self, RenderGraph, RenderLabel},
|
|
render_resource::{binding_types::texture_storage_2d, *},
|
|
renderer::{RenderContext, RenderDevice},
|
|
texture::GpuImage,
|
|
Render, RenderApp, RenderSystems,
|
|
},
|
|
};
|
|
use std::borrow::Cow;
|
|
|
|
/// This example uses a shader source file from the assets subdirectory
|
|
const SHADER_ASSET_PATH: &str = "shaders/game_of_life.wgsl";
|
|
|
|
const DISPLAY_FACTOR: u32 = 4;
|
|
const SIZE: (u32, u32) = (1280 / DISPLAY_FACTOR, 720 / DISPLAY_FACTOR);
|
|
const WORKGROUP_SIZE: u32 = 8;
|
|
|
|
fn main() {
|
|
App::new()
|
|
.insert_resource(ClearColor(Color::BLACK))
|
|
.add_plugins((
|
|
DefaultPlugins
|
|
.set(WindowPlugin {
|
|
primary_window: Some(Window {
|
|
resolution: (
|
|
(SIZE.0 * DISPLAY_FACTOR) as f32,
|
|
(SIZE.1 * DISPLAY_FACTOR) as f32,
|
|
)
|
|
.into(),
|
|
// uncomment for unthrottled FPS
|
|
// present_mode: bevy::window::PresentMode::AutoNoVsync,
|
|
..default()
|
|
}),
|
|
..default()
|
|
})
|
|
.set(ImagePlugin::default_nearest()),
|
|
GameOfLifeComputePlugin,
|
|
))
|
|
.add_systems(Startup, setup)
|
|
.add_systems(Update, switch_textures)
|
|
.run();
|
|
}
|
|
|
|
fn setup(mut commands: Commands, mut images: ResMut<Assets<Image>>) {
|
|
let mut image = Image::new_fill(
|
|
Extent3d {
|
|
width: SIZE.0,
|
|
height: SIZE.1,
|
|
depth_or_array_layers: 1,
|
|
},
|
|
TextureDimension::D2,
|
|
&[0, 0, 0, 255],
|
|
TextureFormat::R32Float,
|
|
RenderAssetUsages::RENDER_WORLD,
|
|
);
|
|
image.texture_descriptor.usage =
|
|
TextureUsages::COPY_DST | TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING;
|
|
let image0 = images.add(image.clone());
|
|
let image1 = images.add(image);
|
|
|
|
commands.spawn((
|
|
Sprite {
|
|
image: image0.clone(),
|
|
custom_size: Some(Vec2::new(SIZE.0 as f32, SIZE.1 as f32)),
|
|
..default()
|
|
},
|
|
Transform::from_scale(Vec3::splat(DISPLAY_FACTOR as f32)),
|
|
));
|
|
commands.spawn(Camera2d);
|
|
|
|
commands.insert_resource(GameOfLifeImages {
|
|
texture_a: image0,
|
|
texture_b: image1,
|
|
});
|
|
}
|
|
|
|
// Switch texture to display every frame to show the one that was written to most recently.
|
|
fn switch_textures(images: Res<GameOfLifeImages>, mut sprite: Single<&mut Sprite>) {
|
|
if sprite.image == images.texture_a {
|
|
sprite.image = images.texture_b.clone_weak();
|
|
} else {
|
|
sprite.image = images.texture_a.clone_weak();
|
|
}
|
|
}
|
|
|
|
struct GameOfLifeComputePlugin;
|
|
|
|
#[derive(Debug, Hash, PartialEq, Eq, Clone, RenderLabel)]
|
|
struct GameOfLifeLabel;
|
|
|
|
impl Plugin for GameOfLifeComputePlugin {
|
|
fn build(&self, app: &mut App) {
|
|
// Extract the game of life image resource from the main world into the render world
|
|
// for operation on by the compute shader and display on the sprite.
|
|
app.add_plugins(ExtractResourcePlugin::<GameOfLifeImages>::default());
|
|
let render_app = app.sub_app_mut(RenderApp);
|
|
render_app.add_systems(
|
|
Render,
|
|
prepare_bind_group.in_set(RenderSystems::PrepareBindGroups),
|
|
);
|
|
|
|
let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>();
|
|
render_graph.add_node(GameOfLifeLabel, GameOfLifeNode::default());
|
|
render_graph.add_node_edge(GameOfLifeLabel, bevy::render::graph::CameraDriverLabel);
|
|
}
|
|
|
|
fn finish(&self, app: &mut App) {
|
|
let render_app = app.sub_app_mut(RenderApp);
|
|
render_app.init_resource::<GameOfLifePipeline>();
|
|
}
|
|
}
|
|
|
|
#[derive(Resource, Clone, ExtractResource)]
|
|
struct GameOfLifeImages {
|
|
texture_a: Handle<Image>,
|
|
texture_b: Handle<Image>,
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
struct GameOfLifeImageBindGroups([BindGroup; 2]);
|
|
|
|
fn prepare_bind_group(
|
|
mut commands: Commands,
|
|
pipeline: Res<GameOfLifePipeline>,
|
|
gpu_images: Res<RenderAssets<GpuImage>>,
|
|
game_of_life_images: Res<GameOfLifeImages>,
|
|
render_device: Res<RenderDevice>,
|
|
) {
|
|
let view_a = gpu_images.get(&game_of_life_images.texture_a).unwrap();
|
|
let view_b = gpu_images.get(&game_of_life_images.texture_b).unwrap();
|
|
let bind_group_0 = render_device.create_bind_group(
|
|
None,
|
|
&pipeline.texture_bind_group_layout,
|
|
&BindGroupEntries::sequential((&view_a.texture_view, &view_b.texture_view)),
|
|
);
|
|
let bind_group_1 = render_device.create_bind_group(
|
|
None,
|
|
&pipeline.texture_bind_group_layout,
|
|
&BindGroupEntries::sequential((&view_b.texture_view, &view_a.texture_view)),
|
|
);
|
|
commands.insert_resource(GameOfLifeImageBindGroups([bind_group_0, bind_group_1]));
|
|
}
|
|
|
|
#[derive(Resource)]
|
|
struct GameOfLifePipeline {
|
|
texture_bind_group_layout: BindGroupLayout,
|
|
init_pipeline: CachedComputePipelineId,
|
|
update_pipeline: CachedComputePipelineId,
|
|
}
|
|
|
|
impl FromWorld for GameOfLifePipeline {
|
|
fn from_world(world: &mut World) -> Self {
|
|
let render_device = world.resource::<RenderDevice>();
|
|
let texture_bind_group_layout = render_device.create_bind_group_layout(
|
|
"GameOfLifeImages",
|
|
&BindGroupLayoutEntries::sequential(
|
|
ShaderStages::COMPUTE,
|
|
(
|
|
texture_storage_2d(TextureFormat::R32Float, StorageTextureAccess::ReadOnly),
|
|
texture_storage_2d(TextureFormat::R32Float, StorageTextureAccess::WriteOnly),
|
|
),
|
|
),
|
|
);
|
|
let shader = world.load_asset(SHADER_ASSET_PATH);
|
|
let pipeline_cache = world.resource::<PipelineCache>();
|
|
let init_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
|
label: None,
|
|
layout: vec![texture_bind_group_layout.clone()],
|
|
push_constant_ranges: Vec::new(),
|
|
shader: shader.clone(),
|
|
shader_defs: vec![],
|
|
entry_point: Cow::from("init"),
|
|
zero_initialize_workgroup_memory: false,
|
|
});
|
|
let update_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
|
label: None,
|
|
layout: vec![texture_bind_group_layout.clone()],
|
|
push_constant_ranges: Vec::new(),
|
|
shader,
|
|
shader_defs: vec![],
|
|
entry_point: Cow::from("update"),
|
|
zero_initialize_workgroup_memory: false,
|
|
});
|
|
|
|
GameOfLifePipeline {
|
|
texture_bind_group_layout,
|
|
init_pipeline,
|
|
update_pipeline,
|
|
}
|
|
}
|
|
}
|
|
|
|
enum GameOfLifeState {
|
|
Loading,
|
|
Init,
|
|
Update(usize),
|
|
}
|
|
|
|
struct GameOfLifeNode {
|
|
state: GameOfLifeState,
|
|
}
|
|
|
|
impl Default for GameOfLifeNode {
|
|
fn default() -> Self {
|
|
Self {
|
|
state: GameOfLifeState::Loading,
|
|
}
|
|
}
|
|
}
|
|
|
|
impl render_graph::Node for GameOfLifeNode {
|
|
fn update(&mut self, world: &mut World) {
|
|
let pipeline = world.resource::<GameOfLifePipeline>();
|
|
let pipeline_cache = world.resource::<PipelineCache>();
|
|
|
|
// if the corresponding pipeline has loaded, transition to the next stage
|
|
match self.state {
|
|
GameOfLifeState::Loading => {
|
|
match pipeline_cache.get_compute_pipeline_state(pipeline.init_pipeline) {
|
|
CachedPipelineState::Ok(_) => {
|
|
self.state = GameOfLifeState::Init;
|
|
}
|
|
CachedPipelineState::Err(err) => {
|
|
panic!("Initializing assets/{SHADER_ASSET_PATH}:\n{err}")
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
GameOfLifeState::Init => {
|
|
if let CachedPipelineState::Ok(_) =
|
|
pipeline_cache.get_compute_pipeline_state(pipeline.update_pipeline)
|
|
{
|
|
self.state = GameOfLifeState::Update(1);
|
|
}
|
|
}
|
|
GameOfLifeState::Update(0) => {
|
|
self.state = GameOfLifeState::Update(1);
|
|
}
|
|
GameOfLifeState::Update(1) => {
|
|
self.state = GameOfLifeState::Update(0);
|
|
}
|
|
GameOfLifeState::Update(_) => unreachable!(),
|
|
}
|
|
}
|
|
|
|
fn run(
|
|
&self,
|
|
_graph: &mut render_graph::RenderGraphContext,
|
|
render_context: &mut RenderContext,
|
|
world: &World,
|
|
) -> Result<(), render_graph::NodeRunError> {
|
|
let bind_groups = &world.resource::<GameOfLifeImageBindGroups>().0;
|
|
let pipeline_cache = world.resource::<PipelineCache>();
|
|
let pipeline = world.resource::<GameOfLifePipeline>();
|
|
|
|
let mut pass = render_context
|
|
.command_encoder()
|
|
.begin_compute_pass(&ComputePassDescriptor::default());
|
|
|
|
// select the pipeline based on the current state
|
|
match self.state {
|
|
GameOfLifeState::Loading => {}
|
|
GameOfLifeState::Init => {
|
|
let init_pipeline = pipeline_cache
|
|
.get_compute_pipeline(pipeline.init_pipeline)
|
|
.unwrap();
|
|
pass.set_bind_group(0, &bind_groups[0], &[]);
|
|
pass.set_pipeline(init_pipeline);
|
|
pass.dispatch_workgroups(SIZE.0 / WORKGROUP_SIZE, SIZE.1 / WORKGROUP_SIZE, 1);
|
|
}
|
|
GameOfLifeState::Update(index) => {
|
|
let update_pipeline = pipeline_cache
|
|
.get_compute_pipeline(pipeline.update_pipeline)
|
|
.unwrap();
|
|
pass.set_bind_group(0, &bind_groups[index], &[]);
|
|
pass.set_pipeline(update_pipeline);
|
|
pass.dispatch_workgroups(SIZE.0 / WORKGROUP_SIZE, SIZE.1 / WORKGROUP_SIZE, 1);
|
|
}
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
}
|