2022-05-30 15:57:25 +00:00
|
|
|
//! A compute shader that simulates Conway's Game of Life.
|
2022-05-16 13:53:20 +00:00
|
|
|
//!
|
|
|
|
//! Compute shaders use the GPU for computing arbitrary information, that may be independent of what
|
|
|
|
//! is rendered to the screen.
|
|
|
|
|
2022-01-05 19:43:11 +00:00
|
|
|
use bevy::{
|
|
|
|
core_pipeline::node::MAIN_PASS_DEPENDENCIES,
|
|
|
|
prelude::*,
|
|
|
|
render::{
|
|
|
|
render_asset::RenderAssets,
|
|
|
|
render_graph::{self, RenderGraph},
|
|
|
|
render_resource::*,
|
|
|
|
renderer::{RenderContext, RenderDevice},
|
|
|
|
RenderApp, RenderStage,
|
|
|
|
},
|
|
|
|
window::WindowDescriptor,
|
|
|
|
};
|
2022-03-23 00:27:26 +00:00
|
|
|
use std::borrow::Cow;
|
2022-01-05 19:43:11 +00:00
|
|
|
|
|
|
|
const SIZE: (u32, u32) = (1280, 720);
|
|
|
|
const WORKGROUP_SIZE: u32 = 8;
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
App::new()
|
|
|
|
.insert_resource(ClearColor(Color::BLACK))
|
|
|
|
.insert_resource(WindowDescriptor {
|
|
|
|
// uncomment for unthrottled FPS
|
|
|
|
// vsync: false,
|
2022-03-01 20:52:09 +00:00
|
|
|
..default()
|
2022-01-05 19:43:11 +00:00
|
|
|
})
|
|
|
|
.add_plugins(DefaultPlugins)
|
|
|
|
.add_plugin(GameOfLifeComputePlugin)
|
|
|
|
.add_startup_system(setup)
|
|
|
|
.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::Rgba8Unorm,
|
|
|
|
);
|
|
|
|
image.texture_descriptor.usage =
|
|
|
|
TextureUsages::COPY_DST | TextureUsages::STORAGE_BINDING | TextureUsages::TEXTURE_BINDING;
|
|
|
|
let image = images.add(image);
|
|
|
|
|
|
|
|
commands.spawn_bundle(SpriteBundle {
|
|
|
|
sprite: Sprite {
|
|
|
|
custom_size: Some(Vec2::new(SIZE.0 as f32, SIZE.1 as f32)),
|
2022-03-01 20:52:09 +00:00
|
|
|
..default()
|
2022-01-05 19:43:11 +00:00
|
|
|
},
|
|
|
|
texture: image.clone(),
|
2022-03-01 20:52:09 +00:00
|
|
|
..default()
|
2022-01-05 19:43:11 +00:00
|
|
|
});
|
|
|
|
commands.spawn_bundle(OrthographicCameraBundle::new_2d());
|
|
|
|
|
2022-02-13 22:33:55 +00:00
|
|
|
commands.insert_resource(GameOfLifeImage(image));
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub struct GameOfLifeComputePlugin;
|
|
|
|
|
|
|
|
impl Plugin for GameOfLifeComputePlugin {
|
|
|
|
fn build(&self, app: &mut App) {
|
|
|
|
let render_app = app.sub_app_mut(RenderApp);
|
|
|
|
render_app
|
|
|
|
.init_resource::<GameOfLifePipeline>()
|
|
|
|
.add_system_to_stage(RenderStage::Extract, extract_game_of_life_image)
|
|
|
|
.add_system_to_stage(RenderStage::Queue, queue_bind_group);
|
|
|
|
|
2022-02-27 22:37:18 +00:00
|
|
|
let mut render_graph = render_app.world.resource_mut::<RenderGraph>();
|
2022-03-23 00:27:26 +00:00
|
|
|
render_graph.add_node("game_of_life", GameOfLifeNode::default());
|
2022-01-05 19:43:11 +00:00
|
|
|
render_graph
|
|
|
|
.add_node_edge("game_of_life", MAIN_PASS_DEPENDENCIES)
|
|
|
|
.unwrap();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
bevy_derive: Add derives for `Deref` and `DerefMut` (#4328)
# Objective
A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like:
```rust
#[derive(Component)]
struct Items(Vec<String>);
fn give_sword(query: Query<&mut Items>) {
query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```
> We could then define another struct that wraps `Vec<String>` without anything clashing in the query.
However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this.
Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations.
## Solution
Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field:
```rust
#[derive(Deref)]
struct Foo(String);
#[derive(Deref, DerefMut)]
struct Bar {
name: String,
}
```
This allows us to then remove that pesky `.0`:
```rust
#[derive(Component, Deref, DerefMut)]
struct Items(Vec<String>);
fn give_sword(query: Query<&mut Items>) {
query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```
### Alternatives
There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now).
### Considerations
One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree.
### Additional Context
Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630))
---
## Changelog
- Add `Deref` derive macro (exported to prelude)
- Add `DerefMut` derive macro (exported to prelude)
- Updated most newtypes in examples to use one or both derives
Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-03-29 02:10:06 +00:00
|
|
|
#[derive(Deref)]
|
2022-01-05 19:43:11 +00:00
|
|
|
struct GameOfLifeImage(Handle<Image>);
|
2022-05-16 13:53:20 +00:00
|
|
|
|
2022-01-05 19:43:11 +00:00
|
|
|
struct GameOfLifeImageBindGroup(BindGroup);
|
|
|
|
|
|
|
|
fn extract_game_of_life_image(mut commands: Commands, image: Res<GameOfLifeImage>) {
|
bevy_derive: Add derives for `Deref` and `DerefMut` (#4328)
# Objective
A common pattern in Rust is the [newtype](https://doc.rust-lang.org/rust-by-example/generics/new_types.html). This is an especially useful pattern in Bevy as it allows us to give common/foreign types different semantics (such as allowing it to implement `Component` or `FromWorld`) or to simply treat them as a "new type" (clever). For example, it allows us to wrap a common `Vec<String>` and do things like:
```rust
#[derive(Component)]
struct Items(Vec<String>);
fn give_sword(query: Query<&mut Items>) {
query.single_mut().0.push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```
> We could then define another struct that wraps `Vec<String>` without anything clashing in the query.
However, one of the worst parts of this pattern is the ugly `.0` we have to write in order to access the type we actually care about. This is why people often implement `Deref` and `DerefMut` in order to get around this.
Since it's such a common pattern, especially for Bevy, it makes sense to add a derive macro to automatically add those implementations.
## Solution
Added a derive macro for `Deref` and another for `DerefMut` (both exported into the prelude). This works on all structs (including tuple structs) as long as they only contain a single field:
```rust
#[derive(Deref)]
struct Foo(String);
#[derive(Deref, DerefMut)]
struct Bar {
name: String,
}
```
This allows us to then remove that pesky `.0`:
```rust
#[derive(Component, Deref, DerefMut)]
struct Items(Vec<String>);
fn give_sword(query: Query<&mut Items>) {
query.single_mut().push(String::from("Flaming Poisoning Raging Sword of Doom"));
}
```
### Alternatives
There are other alternatives to this such as by using the [`derive_more`](https://crates.io/crates/derive_more) crate. However, it doesn't seem like we need an entire crate just yet since we only need `Deref` and `DerefMut` (for now).
### Considerations
One thing to consider is that the Rust std library recommends _not_ using `Deref` and `DerefMut` for things like this: "`Deref` should only be implemented for smart pointers to avoid confusion" ([reference](https://doc.rust-lang.org/std/ops/trait.Deref.html)). Personally, I believe it makes sense to use it in the way described above, but others may disagree.
### Additional Context
Discord: https://discord.com/channels/691052431525675048/692572690833473578/956648422163746827 (controversiality discussed [here](https://discord.com/channels/691052431525675048/692572690833473578/956711911481835630))
---
## Changelog
- Add `Deref` derive macro (exported to prelude)
- Add `DerefMut` derive macro (exported to prelude)
- Updated most newtypes in examples to use one or both derives
Co-authored-by: MrGVSV <49806985+MrGVSV@users.noreply.github.com>
2022-03-29 02:10:06 +00:00
|
|
|
commands.insert_resource(GameOfLifeImage(image.clone()));
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
2022-03-23 00:27:26 +00:00
|
|
|
|
2022-01-05 19:43:11 +00:00
|
|
|
fn queue_bind_group(
|
|
|
|
mut commands: Commands,
|
|
|
|
pipeline: Res<GameOfLifePipeline>,
|
|
|
|
gpu_images: Res<RenderAssets<Image>>,
|
|
|
|
game_of_life_image: Res<GameOfLifeImage>,
|
|
|
|
render_device: Res<RenderDevice>,
|
|
|
|
) {
|
|
|
|
let view = &gpu_images[&game_of_life_image.0];
|
|
|
|
let bind_group = render_device.create_bind_group(&BindGroupDescriptor {
|
|
|
|
label: None,
|
|
|
|
layout: &pipeline.texture_bind_group_layout,
|
|
|
|
entries: &[BindGroupEntry {
|
|
|
|
binding: 0,
|
|
|
|
resource: BindingResource::TextureView(&view.texture_view),
|
|
|
|
}],
|
|
|
|
});
|
|
|
|
commands.insert_resource(GameOfLifeImageBindGroup(bind_group));
|
|
|
|
}
|
|
|
|
|
|
|
|
pub struct GameOfLifePipeline {
|
|
|
|
texture_bind_group_layout: BindGroupLayout,
|
2022-03-23 00:27:26 +00:00
|
|
|
init_pipeline: CachedComputePipelineId,
|
|
|
|
update_pipeline: CachedComputePipelineId,
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
impl FromWorld for GameOfLifePipeline {
|
|
|
|
fn from_world(world: &mut World) -> Self {
|
|
|
|
let texture_bind_group_layout =
|
2022-03-23 00:27:26 +00:00
|
|
|
world
|
|
|
|
.resource::<RenderDevice>()
|
|
|
|
.create_bind_group_layout(&BindGroupLayoutDescriptor {
|
|
|
|
label: None,
|
|
|
|
entries: &[BindGroupLayoutEntry {
|
|
|
|
binding: 0,
|
|
|
|
visibility: ShaderStages::COMPUTE,
|
|
|
|
ty: BindingType::StorageTexture {
|
|
|
|
access: StorageTextureAccess::ReadWrite,
|
|
|
|
format: TextureFormat::Rgba8Unorm,
|
|
|
|
view_dimension: TextureViewDimension::D2,
|
|
|
|
},
|
|
|
|
count: None,
|
|
|
|
}],
|
|
|
|
});
|
|
|
|
let shader = world
|
|
|
|
.resource::<AssetServer>()
|
|
|
|
.load("shaders/game_of_life.wgsl");
|
|
|
|
let mut pipeline_cache = world.resource_mut::<PipelineCache>();
|
|
|
|
let init_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
2022-01-05 19:43:11 +00:00
|
|
|
label: None,
|
2022-03-23 00:27:26 +00:00
|
|
|
layout: Some(vec![texture_bind_group_layout.clone()]),
|
|
|
|
shader: shader.clone(),
|
|
|
|
shader_defs: vec![],
|
|
|
|
entry_point: Cow::from("init"),
|
2022-01-05 19:43:11 +00:00
|
|
|
});
|
2022-03-23 00:27:26 +00:00
|
|
|
let update_pipeline = pipeline_cache.queue_compute_pipeline(ComputePipelineDescriptor {
|
2022-01-05 19:43:11 +00:00
|
|
|
label: None,
|
2022-03-23 00:27:26 +00:00
|
|
|
layout: Some(vec![texture_bind_group_layout.clone()]),
|
|
|
|
shader,
|
|
|
|
shader_defs: vec![],
|
|
|
|
entry_point: Cow::from("update"),
|
2022-01-05 19:43:11 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
GameOfLifePipeline {
|
|
|
|
texture_bind_group_layout,
|
2022-03-23 00:27:26 +00:00
|
|
|
init_pipeline,
|
|
|
|
update_pipeline,
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-23 00:27:26 +00:00
|
|
|
enum GameOfLifeState {
|
|
|
|
Loading,
|
|
|
|
Init,
|
|
|
|
Update,
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
|
2022-03-23 00:27:26 +00:00
|
|
|
struct GameOfLifeNode {
|
|
|
|
state: GameOfLifeState,
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
2022-03-23 00:27:26 +00:00
|
|
|
|
|
|
|
impl Default for GameOfLifeNode {
|
2022-01-05 19:43:11 +00:00
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
2022-03-23 00:27:26 +00:00
|
|
|
state: GameOfLifeState::Loading,
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-03-23 00:27:26 +00:00
|
|
|
|
|
|
|
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 => {
|
|
|
|
if let CachedPipelineState::Ok(_) =
|
|
|
|
pipeline_cache.get_compute_pipeline_state(pipeline.init_pipeline)
|
|
|
|
{
|
|
|
|
self.state = GameOfLifeState::Init
|
|
|
|
}
|
|
|
|
}
|
|
|
|
GameOfLifeState::Init => {
|
|
|
|
if let CachedPipelineState::Ok(_) =
|
|
|
|
pipeline_cache.get_compute_pipeline_state(pipeline.update_pipeline)
|
|
|
|
{
|
|
|
|
self.state = GameOfLifeState::Update
|
|
|
|
}
|
|
|
|
}
|
|
|
|
GameOfLifeState::Update => {}
|
2022-01-05 19:43:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn run(
|
|
|
|
&self,
|
|
|
|
_graph: &mut render_graph::RenderGraphContext,
|
|
|
|
render_context: &mut RenderContext,
|
|
|
|
world: &World,
|
|
|
|
) -> Result<(), render_graph::NodeRunError> {
|
2022-02-27 22:37:18 +00:00
|
|
|
let texture_bind_group = &world.resource::<GameOfLifeImageBindGroup>().0;
|
2022-03-23 00:27:26 +00:00
|
|
|
let pipeline_cache = world.resource::<PipelineCache>();
|
|
|
|
let pipeline = world.resource::<GameOfLifePipeline>();
|
2022-01-05 19:43:11 +00:00
|
|
|
|
|
|
|
let mut pass = render_context
|
|
|
|
.command_encoder
|
|
|
|
.begin_compute_pass(&ComputePassDescriptor::default());
|
|
|
|
|
|
|
|
pass.set_bind_group(0, texture_bind_group, &[]);
|
2022-03-23 00:27:26 +00:00
|
|
|
|
|
|
|
// 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_pipeline(init_pipeline);
|
|
|
|
pass.dispatch(SIZE.0 / WORKGROUP_SIZE, SIZE.1 / WORKGROUP_SIZE, 1);
|
|
|
|
}
|
|
|
|
GameOfLifeState::Update => {
|
|
|
|
let update_pipeline = pipeline_cache
|
|
|
|
.get_compute_pipeline(pipeline.update_pipeline)
|
|
|
|
.unwrap();
|
|
|
|
pass.set_pipeline(update_pipeline);
|
|
|
|
pass.dispatch(SIZE.0 / WORKGROUP_SIZE, SIZE.1 / WORKGROUP_SIZE, 1);
|
|
|
|
}
|
|
|
|
}
|
2022-01-05 19:43:11 +00:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
}
|