// Create the event loop and window
let event_loop = EventLoop::new();
let window = WindowBuilder::new()
.with_title("Falling Sand Simulator")
.with_inner_size(window_size)
.with_resizable(false) // Fixed size
.build(&event_loop)
.unwrap();
// Initialize the renderer and simulation
let mut renderer = pollster::block_on(Renderer::new(&window));
let mut simulation = Simulation::new();
// 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, .. } => {
if !renderer.input(event, &mut simulation) {
// Close window
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
_ => {}
}
}
}
_ => {}
}
});
Assistant
}
// material.rs
use bytemuck::{Pod, Zeroable};
#[repr(u32)]
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum Material {
Empty = 0,
Sand = 1,
Water = 2,
Earth = 3,
Lava = 4,
// Add more materials if needed
}
// SAFETY: Material is a field-less enum with a defined integer representation.
// All possible bit patterns from 0 to 4 are valid discriminants.
unsafe impl Zeroable for Material {}
unsafe impl Pod for Material {}
impl Material {
pub fn color(&self) -> [f32; 3] {
match self {
Material::Empty => [0.0, 0.0, 0.0], // Black
Material::Sand => [0.8, 0.7, 0.5], // Sandy color
Material::Water => [0.0, 0.5, 1.0], // Blue
Material::Earth => [0.4, 0.3, 0.2], // Brown
Material::Lava => [1.0, 0.3, 0.0], // Orange-red
}
}
}
// render.rs
use wgpu::util::DeviceExt;
use winit::window::Window;
use crate::simulation::{Simulation, SIM_HEIGHT, SIM_WIDTH};
use crate::material::Material;
impl Simulation {
pub fn new() -> Self {
// Initialize the grid with empty materials
let cells = vec![Material::Empty; (SIM_WIDTH * SIM_HEIGHT) as usize];
code
Self { cells }
}
pub fn update(&mut self) {
// Update the simulation state on CPU if needed
// In this case, we are handling the simulation on GPU, so this may be minimal
}
// Add methods to interact with the simulation (e.g., add material at position)
pub fn add_material(&mut self, x: u32, y: u32, material: Material) {
if x < SIM_WIDTH && y < SIM_HEIGHT {
let index = (y * SIM_WIDTH + x) as usize;
self.cells[index] = material;
}
}
[[stage(compute), workgroup_size(8, 8, 1)]]
fn main([[builtin(global_invocation_id)]] global_id: vec3) {
let x = global_id.x;
let y = global_id.y;
let index = y * $SIM_WIDTH + x;
code
// Check bounds
if x >= $SIM_WIDTH || y >= $SIM_HEIGHT {
return;
}
// Simple simulation logic: Sand falls down
if y + 1u < $SIM_HEIGHT {
let below_index = (y + 1u) * $SIM_WIDTH + x;
if cells[index] == 1u && cells[below_index] == 0u {
cells[below_index] = 1u;
cells[index] = 0u;
}
}
let pos = positions[vertex_index];
return vec4(pos, 0.0, 1.0);
}
fix the errors below, and fix all placeholders missing and enhance the script
➡ cargo run
Compiling falling_sand_simulator v0.1.0 (C:\Users\Enzo\Documents\falling_sand_simulator)
warning: unused import: wgpu::util::DeviceExt
--> src\render.rs:2:5
|
2 | use wgpu::util::DeviceExt;
| ^^^^^^^^^^^^^^^^^^^^^
|
= note: #[warn(unused_imports)] on by default
warning: falling_sand_simulator (lib) generated 1 warning (run cargo fix --lib -p falling_sand_simulator to apply 1 suggestion)
error[E0616]: field size of struct Renderer is private
--> src/main.rs:47:79
|
47 | Err(wgpu::SurfaceError::Lost) => renderer.resize(renderer.size),
| ^^^^ private field
For more information about this error, try rustc --explain E0616.
warning: falling_sand_simulator (bin "falling_sand_simulator") generated 1 warning (1 duplicate)
error: could not compile falling_sand_simulator (bin "falling_sand_simulator") due to 1 previous error; 1 warning emitted
The error you're encountering is due to the size field of the Renderer struct being private in render.rs, but you're trying to access it in main.rs. To fix this error, you need to make the size field public so it can be accessed outside of the render module.
Additionally, there are placeholders in your shader code (like $SIM_WIDTH, $SIM_HEIGHT, etc.) that need to be replaced with actual values. You also need to update your shader code to use the latest WGSL syntax, as the syntax has changed.
Here's how you can fix the errors and enhance the script:
Make the size field public in the Renderer struct:
In your render.rs file, modify the Renderer struct to make the size field public:
rust
// render.rs
pub struct Renderer {
device: wgpu::Device,
queue: wgpu::Queue,
surface: wgpu::Surface,
config: wgpu::SurfaceConfiguration,
pub size: winit::dpi::PhysicalSize<u32>, // Make this field public
render_pipeline: wgpu::RenderPipeline,
compute_pipeline: wgpu::ComputePipeline,
cell_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
}
Update the shader code to use the latest WGSL syntax and replace placeholders:
WGSL syntax has changed, and attributes now use the @ syntax instead of [[ ]]. Also, you need to ensure that all placeholders in your shader code are correctly replaced with actual values.
Update compute.wgsl:
wgsl
// compute.wgsl
const SIM_WIDTH: u32 = $SIM_WIDTH;
const SIM_HEIGHT: u32 = $SIM_HEIGHT;
@group(0) @binding(0)
var<storage, read_write> cells: array<u32>;
@compute @workgroup_size(8, 8, 1)
fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {
let x = global_id.x;
let y = global_id.y;
let index = y * SIM_WIDTH + x;
// Check bounds
if x >= SIM_WIDTH || y >= SIM_HEIGHT {
return;
}
// Simple simulation logic: Sand falls down
if y + 1u < SIM_HEIGHT {
let below_index = (y + 1u) * SIM_WIDTH + x;
if cells[index] == 1u && cells[below_index] == 0u {
cells[below_index] = 1u;
cells[index] = 0u;
}
}
}
Update fragment.wgsl:
wgsl
// fragment.wgsl
const SIM_WIDTH: u32 = $SIM_WIDTH;
const SIM_HEIGHT: u32 = $SIM_HEIGHT;
const WINDOW_WIDTH: f32 = $WINDOW_WIDTH;
const WINDOW_HEIGHT: f32 = $WINDOW_HEIGHT;
@group(0) @binding(0)
var<storage, read> cells: array<u32>;
@fragment
fn main(@builtin(position) frag_coord: vec4<f32>) -> @location(0) vec4<f32> {
let x = u32(frag_coord.x / WINDOW_WIDTH * f32(SIM_WIDTH));
let y = u32(frag_coord.y / WINDOW_HEIGHT * f32(SIM_HEIGHT));
// Check bounds
if x >= SIM_WIDTH || y >= SIM_HEIGHT {
discard;
}
let index = y * SIM_WIDTH + x;
let material = cells[index];
var color: vec3<f32>;
if material == 0u {
color = vec3(0.0, 0.0, 0.0); // Empty
} else if material == 1u {
color = vec3(0.8, 0.7, 0.5); // Sand
} else if material == 2u {
color = vec3(0.0, 0.5, 1.0); // Water
} else if material == 3u {
color = vec3(0.4, 0.3, 0.2); // Earth
} else if material == 4u {
color = vec3(1.0, 0.3, 0.0); // Lava
} else {
color = vec3(1.0, 1.0, 1.0); // Default
}
return vec4(color, 1.0);
}
Ensure all placeholders in the shaders are replaced in render.rs:
In your render.rs, you need to make sure that the placeholders in the shader source code are correctly replaced with actual values.
Update shader loading in render.rs:
rust
// render.rs
// Load shaders
let vertex_shader_source = include_str!("shaders/vertex.wgsl");
// No placeholders to replace in vertex shader source
let vertex_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Vertex Shader"),
source: wgpu::ShaderSource::Wgsl(vertex_shader_source.into()),
});
let fragment_shader_source = include_str!("shaders/fragment.wgsl");
// Replace placeholders with actual values
let fragment_shader_source = fragment_shader_source
.replace("$SIM_WIDTH", &SIM_WIDTH.to_string())
.replace("$SIM_HEIGHT", &SIM_HEIGHT.to_string())
.replace("$WINDOW_WIDTH", &self.size.width.to_string())
.replace("$WINDOW_HEIGHT", &self.size.height.to_string());
let fragment_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Fragment Shader"),
source: wgpu::ShaderSource::Wgsl(fragment_shader_source.into()),
});
let compute_shader_source = include_str!("shaders/compute.wgsl");
// Replace placeholders with actual values
let compute_shader_source = compute_shader_source
.replace("$SIM_WIDTH", &SIM_WIDTH.to_string())
.replace("$SIM_HEIGHT", &SIM_HEIGHT.to_string());
let compute_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Compute Shader"),
source: wgpu::ShaderSource::Wgsl(compute_shader_source.into()),
});
Remove or use the unused import in render.rs:
You're getting a warning about an unused import:
rust
use wgpu::util::DeviceExt;
Ensure that you use this import where necessary or remove it if it's not needed. For example, you can use it when creating buffers with DeviceExt::create_buffer_init.
Example of using DeviceExt:
rust
// render.rs
use wgpu::util::DeviceExt;
// When creating the cell_buffer
let cell_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("Cell Buffer"),
contents: &[0u8; cell_buffer_size as usize],
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC,
});
If you don't need DeviceExt, simply remove the import to eliminate the warning:
rust
// render.rs
// Remove the unused import
// use wgpu::util::DeviceExt;
Note: If you decide to use DeviceExt for buffer initialization, you may need to adjust the types accordingly.
Adjust the resize method if necessary:
Since you're making size public, the resize method should reflect any changes to size. Make sure the resize method updates the config and reconfigures the surface.
Currently, the simulation logic is minimal, and sand only falls down if there's empty space below. You can enhance the logic to allow for more complex behaviors, like sand sliding diagonally, interactions with other materials, etc.
Example of enhanced simulation logic in compute.wgsl:
wgsl
// compute.wgsl
// ... existing code ...
// Enhanced simulation logic: Sand can also move diagonally downwards
if cells[index] == 1u {
var moved = false;
// Try moving down
if y + 1u < SIM_HEIGHT {
let below_index = (y + 1u) * SIM_WIDTH + x;
if cells[below_index] == 0u {
cells[below_index] = 1u;
cells[index] = 0u;
moved = true;
}
}
// Try moving down-left
if !moved && x > 0u && y + 1u < SIM_HEIGHT {
let below_left_index = (y + 1u) * SIM_WIDTH + (x - 1u);
if cells[below_left_index] == 0u {
cells[below_left_index] = 1u;
cells[index] = 0u;
moved = true;
}
}
// Try moving down-right
if !moved && x + 1u < SIM_WIDTH && y + 1u < SIM_HEIGHT {
let below_right_index = (y + 1u) * SIM_WIDTH + (x + 1u);
if cells[below_right_index] == 0u {
cells[below_right_index] = 1u;
cells[index] = 0u;
moved = true;
}
}
}
Handle user input to add materials:
Currently, the input method in main.rs and Renderer is minimal. You can enhance it to handle mouse clicks to add materials to the simulation.
Example of handling mouse input in main.rs:
rust
// main.rs
event_loop.run(move |event, _, control_flow| {
// ... existing code ...
match event {
// ... existing cases ...
Event::WindowEvent { ref event, .. } => {
if !renderer.input(event, &mut simulation) {
// Close window
match event {
WindowEvent::CloseRequested => *control_flow = ControlFlow::Exit,
WindowEvent::CursorMoved { position, .. } => {
// Optionally handle cursor movement
}
WindowEvent::MouseInput { state, button, .. } => {
if *button == winit::event::MouseButton::Left && *state == winit::event::ElementState::Pressed {
let position = window.cursor_position().unwrap();
let x = (position.x / window_size.width as f64 * SIM_WIDTH as f64) as u32;
let y = (position.y / window_size.height as f64 * SIM_HEIGHT as f64) as u32;
simulation.add_material(x, y, Material::Sand);
}
}
_ => {}
}
}
}
_ => {}
}
});
Note: You'll need to adjust the input handling and possibly make the window variable accessible inside the event loop.
Test the application:
After making all these changes, build and run your application to ensure it works as expected.
bash
cargo run
You should now have a working falling sand simulator where sand falls and interacts according to your simulation logic. You can further enhance the simulation by adding more materials and interactions.
By addressing these points, you should be able to fix the compilation errors, ensure all placeholders are correctly replaced, and enhance the script to create a more interactive and robust simulation.
Not yet included in a published release.
Note: Since there are no placeholders in the vertex shader, you don't need to replace anything for it.