Sure! Let's create a Rust falling sand simulator game that leverages the GPU using shaders. We'll use the wgpu crate for GPU rendering and compute shaders, and winit for window creation and event handling. We'll organize the code into multiple files for clarity.
Project Structure:
Cargo.toml: Project configuration and dependencies.
src/main.rs: Entry point of the application.
src/lib.rs: Module declarations.
src/render.rs: Rendering-related code.
src/simulation.rs: Simulation logic.
src/shaders/compute.wgsl: Compute shader for the simulation.
src/shaders/vertex.wgsl: Vertex shader.
src/shaders/fragment.wgsl: Fragment shader.
1. Setup Cargo.toml
First, create a new Rust project:
cargo new falling_sand_simulator
cd falling_sand_simulator
Replace the contents of Cargo.toml with:
[package]
name = "falling_sand_simulator"
version = "0.1.0"
edition = "2021"
[dependencies]
winit = "0.28.5"
wgpu = "0.16.0"
pollster = "0.3.1"
2. Create the Source Files
src/main.rs
use winit::{
dpi::PhysicalSize,
event::{Event, WindowEvent},
event_loop::{ControlFlow, EventLoop},
window::WindowBuilder,
};
mod render;
mod simulation;
use render::Renderer;
use simulation::Simulation;
fn main() {
// Create the event loop and window
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Falling Sand Simulator")
.with_inner_size(PhysicalSize::new(800, 600))
.build(&event_loop)
.unwrap();
// Initialize the renderer and simulation
let mut renderer = pollster::block_on(Renderer::new(&window));
let mut simulation = Simulation::new(renderer.size.width, renderer.size.height);
// Run the event loop
event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Poll;
match event {
Event::RedrawRequested(_) => {
// Update simulation
simulation.update();
// Render
match renderer.render(&simulation) {
Ok(_) => {}
// Recreate the surface if lost
Err(wgpu::SurfaceError::Lost) => renderer.resize(renderer.size),
// The system is out of memory, exit
Err(wgpu::SurfaceError::OutOfMemory) => *control_flow = ControlFlow::Exit,
// All other errors (Outdated, Timeout) should be resolved by the next frame
Err(e) => eprintln!("{:?}", e),
}
}
Event::MainEventsCleared => {
// Request a redraw
window.request_redraw();
}
Event::WindowEvent {
ref event,
window_id,
} if window_id == window.id() => {
if !renderer.input(event, &mut simulation) {
// Close window
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::Resized(physical_size) => {
// Resize renderer and simulation
renderer.resize(*physical_size);
simulation.resize(physical_size.width, physical_size.height);
}
WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
renderer.resize(**new_inner_size);
simulation.resize(new_inner_size.width, new_inner_size.height);
}
_ => {}
}
}
}
_ => {}
}
});
}
src/lib.rs
pub mod render;
pub mod simulation;
src/render.rs
use wgpu::util::DeviceExt;
use winit::event::WindowEvent;
use winit::window::Window;
use crate::simulation::Simulation;
pub struct Renderer {
pub size: winit::dpi::PhysicalSize<u32>,
surface: wgpu::Surface,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
render_pipeline: wgpu::RenderPipeline,
// Compute pipeline for simulation
compute_pipeline: wgpu::ComputePipeline,
// Buffers
vertex_buffer: wgpu::Buffer,
indices_buffer: wgpu::Buffer,
num_indices: u32,
simulation_bind_group: wgpu::BindGroup,
simulation_buffer: wgpu::Buffer,
}
impl Renderer {
pub async fn new(window: &Window) -> Self {
// Get the window size
let size = window.inner_size();
// Create an instance
let instance = wgpu::Instance::default();
// Create the surface
let surface = unsafe { instance.create_surface(window) }.unwrap();
// Request an adapter
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
})
.await
.expect("Failed to find an appropriate adapter");
// Request the device and queue
let (device, queue) = adapter
.request_device(
&wgpu::DeviceDescriptor {
label: None,
features: wgpu::Features::empty(),
limits: wgpu::Limits::downlevel_webgl2_defaults(),
},
None,
)
.await
.expect("Failed to create device");
// Configure the surface
let surface_caps = surface.get_capabilities(&adapter);
let surface_format = surface_caps.formats[0];
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width,
height: size.height,
present_mode: surface_caps.present_modes[0],
alpha_mode: surface_caps.alpha_modes[0],
view_formats: vec![],
};
surface.configure(&device, &config);
// Load shaders
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Render Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/fragment.wgsl").into()),
});
// Create render pipeline
let render_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Render Pipeline Layout"),
bind_group_layouts: &[],
push_constant_ranges: &[],
});
let render_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(&render_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: "vs_main",
buffers: &[],
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: "fs_main",
targets: &[Some(wgpu::ColorTargetState {
format: config.format,
blend: Some(wgpu::BlendState::REPLACE),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview: None,
});
// Create compute shader module
let compute_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Compute Shader"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/compute.wgsl").into()),
});
// Create simulation buffer
let simulation_buffer_size =
(size.width * size.height * std::mem::size_of::<u32>() as u32) as wgpu::BufferAddress;
let simulation_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Simulation Buffer"),
size: simulation_buffer_size,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
// Create bind group layout and bind group for compute shader
let simulation_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Simulation Bind Group Layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE | wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let simulation_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Simulation Bind Group"),
layout: &simulation_bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: simulation_buffer.as_entire_binding(),
}],
});
// Create compute pipeline
let compute_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Compute Pipeline Layout"),
bind_group_layouts: &[&simulation_bind_group_layout],
push_constant_ranges: &[],
});
let compute_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("Compute Pipeline"),
layout: Some(&compute_pipeline_layout),
module: &compute_shader,
entry_point: "main",
});
// Create vertex and index buffers (a full-screen triangle)
let vertex_data = [
// Positions
[-1.0, -1.0],
[3.0, -1.0],
[-1.0, 3.0],
];
let vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Vertex Buffer"),
contents: bytemuck::cast_slice(&vertex_data),
usage: wgpu::BufferUsages::VERTEX,
});
let num_indices = 3;
Self {
size,
surface,
device,
queue,
config,
render_pipeline,
compute_pipeline,
vertex_buffer,
indices_buffer: wgpu::Buffer::default(),
num_indices,
simulation_bind_group,
simulation_buffer,
}
}
pub fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
// Update size and reconfigure the surface
self.size = new_size;
self.config.width = new_size.width;
self.config.height = new_size.height;
self.surface.configure(&self.device, &self.config);
// Resize the simulation buffer
let simulation_buffer_size = (new_size.width
* new_size.height
* std::mem::size_of::<u32>() as u32)
as wgpu::BufferAddress;
self.simulation_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Simulation Buffer"),
size: simulation_buffer_size,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
// Update the bind group
self.simulation_bind_group = self.device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Simulation Bind Group"),
layout: &self.compute_pipeline.get_bind_group_layout(0),
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: self.simulation_buffer.as_entire_binding(),
}],
});
}
pub fn input(
&mut self,
event: &WindowEvent,
simulation: &mut Simulation,
) -> bool {
// Handle input events (e.g., mouse clicks to add particles)
false
}
pub fn render(&mut self, simulation: &Simulation) -> Result<(), wgpu::SurfaceError> {
// Update the simulation buffer with data from the CPU simulation (if needed)
// self.queue.write_buffer(
// &self.simulation_buffer,
// 0,
// bytemuck::cast_slice(&simulation.pixels),
// );
// Run compute shader to update the simulation on GPU
{
let mut encoder =
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Compute Encoder"),
});
{
let mut compute_pass =
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Compute Pass"),
});
compute_pass.set_pipeline(&self.compute_pipeline);
compute_pass.set_bind_group(0, &self.simulation_bind_group, &[]);
// Dispatch compute shader
let workgroup_size = (8, 8);
let dispatch_size = (
(self.size.width + workgroup_size.0 - 1) / workgroup_size.0,
(self.size.height + workgroup_size.1 - 1) / workgroup_size.1,
);
compute_pass.dispatch_workgroups(dispatch_size.0, dispatch_size.1, 1);
}
self.queue.submit(Some(encoder.finish()));
}
// Begin rendering
let output = self.surface.get_current_texture()?;
let view = output
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
let mut encoder =
self.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Render Encoder"),
});
{
let mut render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: true,
},
})],
depth_stencil_attachment: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.draw(0..self.num_indices, 0..1);
}
// Submit the commands
self.queue.submit(Some(encoder.finish()));
output.present();
Ok(())
}
}
src/simulation.rs
pub struct Simulation {
pub width: u32,
pub height: u32,
// You can add more fields, e.g., a pixel buffer
// pub pixels: Vec<u32>,
}
impl Simulation {
pub fn new(width: u32, height: u32) -> Self {
Self {
width,
height,
// pixels: vec![0; (width * height) as usize],
}
}
pub fn resize(&mut self, width: u32, height: u32) {
self.width = width;
self.height = height;
// Resize pixel buffer if used
// self.pixels = vec![0; (width * height) as usize];
}
pub fn update(&mut self) {
// Update the simulation state on CPU if needed
}
}
3. Create Shader Files
Create a directory src/shaders/ and add the following shader files.
src/shaders/compute.wgsl
// Workgroup size
const WORKGROUP_SIZE_X: u32 = 8;
const WORKGROUP_SIZE_Y: u32 = 8;
struct SimulationData {
pixels: array<u32>,
};
@group(0) @binding(0)
var<storage, read_write> simulation_data: SimulationData;
@compute @workgroup_size(WORKGROUP_SIZE_X, WORKGROUP_SIZE_Y)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let width = /* specify the simulation width */;
let height = /* specify the simulation height */;
let x = global_id.x;
let y = global_id.y;
if (x >= width || y >= height) {
return;
}
let index = y * width + x;
// Simple simulation logic: move pixels down if possible
if (y > 0u) {
let below_index = (y - 1u) * width + x;
if (simulation_data.pixels[below_index] == 0u) {
// Swap pixels
simulation_data.pixels[below_index] = simulation_data.pixels[index];
simulation_data.pixels[index] = 0u;
}
}
}
Note: You'll need to pass the simulation width and height to the shader or define them as constants.
src/shaders/vertex.wgsl
@vertex
fn vs_main(@builtin(vertex_index) vertex_index: u32) -> @builtin(position) vec4<f32> {
var positions = array<vec2<f32>, 3>(
vec2<f32>(-1.0, -1.0),
vec2<f32>(3.0, -1.0),
vec2<f32>(-1.0, 3.0),
);
let pos = positions[vertex_index];
return vec4<f32>(pos, 0.0, 1.0);
}
src/shaders/fragment.wgsl
struct SimulationData {
pixels: array<u32>,
};
@group(0) @binding(0)
var<storage, read> simulation_data: SimulationData;
@fragment
fn fs_main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let x = u32(frag_coord.x);
let y = u32(frag_coord.y);
let width = /* specify the simulation width */;
let index = y * width + x;
let value = simulation_data.pixels[index];
return vec4<f32>(f32(value) / 255.0, 0.0, 0.0, 1.0);
}
Note: Similar to the compute shader, you'll need to pass the simulation width to the fragment shader or define it as a constant.
4. Adjusting Shaders to Handle Simulation Size
Since the shaders need to know the simulation width and height, you can pass these values as uniforms or set them as constants in the shaders. For simplicity, let's define them as constants directly in the shader files.
Add the following to both compute.wgsl and fragment.wgsl:
const WIDTH: u32 = /* simulation width */;
const HEIGHT: u32 = /* simulation height */;
You'll need to replace /* simulation width */ and /* simulation height */ with actual values or pass them as uniforms.
5. Updating the Renderer for Shader Constants
Since hardcoding the simulation size isn't practical, a better approach is to use push constants or uniforms to pass the size to shaders. For brevity, let's continue with constants.
However, in a production environment, consider utilizing uniforms or buffer variables to pass dynamic data to shaders.
6. Final Adjustments
Ensure all placeholder comments like /* specify the simulation width */ are replaced with actual code or variables.
For example, you can define constants in your Rust code and include them in the shader source using macros or generate shader code dynamically.
7. Run the Simulator
Now, build and run the simulator:
cargo run
8. Complete Cargo.toml
Here is the complete Cargo.toml:
[package]
name = "falling_sand_simulator"
version = "0.1.0"
edition = "2021"
[dependencies]
winit = "0.28.5"
wgpu = "0.16.0"
pollster = "0.3.1"
[profile.dev]
debug = true
[profile.release]
debug = false
Note
- The provided code is a simplified starting point. Implementing a full-fledged falling sand simulator involves complex simulation logic for particle behavior, collision detection, and interaction with various elements (sand, water, fire, etc.).
- The compute shader currently contains basic logic to move pixels down, simulating gravity. You'll need to expand this logic to handle different particle types and interactions.
- Handling dynamic simulation sizes and passing data between CPU and GPU efficiently is crucial for performance.
Further Enhancements
- Particle Types: Implement different particle types with unique behaviors.
- User Interaction: Handle mouse input to add or remove particles interactively.
- Optimizations: Optimize compute shader performance and data structures.
- Graphics: Enhance rendering with textures, lighting, and other visual effects.
- Multithreading: Utilize Rust's multithreading capabilities for further performance improvements.
Feel free to ask if you need clarification on any part or assistance with further development!