Creating a game like OE Cake, where you can draw materials on the screen with realistic fluid dynamics and soft-body physics, is a complex task that involves advanced physics simulations. However, we can create a simplified version using Rust that allows you to draw particles (like water) on the screen, toggle gravity and walls, and switch between drawing and erasing.
We'll use the ggez crate for the game framework, which provides easy-to-use 2D graphics rendering and input handling. Below is the Rust code for a basic particle simulation that meets your requirements.
Code Implementation
Cargo.toml
First, set up your Cargo.toml file with the necessary dependencies:
[package]
name = "oe_cake_clone"
version = "0.1.0"
authors = ["Your Name <you@example.com>"]
edition = "2021"
[dependencies]
ggez = "0.7.0"
glam = "0.20.0"
src/main.rs
Now, create a src/main.rs file and add the following code:
use ggez::{
conf, event,
event::{EventHandler, KeyCode, MouseButton},
graphics::{self, Color, DrawMode, Mesh},
input,
nalgebra::Point2,
Context, ContextBuilder, GameResult,
};
use glam::Vec2;
use std::collections::HashSet;
const PARTICLE_RADIUS: f32 = 2.0;
const GRAVITY: Vec2 = Vec2::new(0.0, 980.0); // Pixels per second squared
const MAX_PARTICLES: usize = 5000;
struct Particle {
position: Vec2,
velocity: Vec2,
}
impl Particle {
fn new(position: Vec2) -> Self {
Self {
position,
velocity: Vec2::ZERO,
}
}
}
enum Material {
Water,
Eraser,
}
struct MainState {
particles: Vec<Particle>,
gravity_enabled: bool,
walls_enabled: bool,
current_material: Material,
mouse_down: bool,
mouse_pos: Vec2,
keys_pressed: HashSet<KeyCode>,
}
impl MainState {
fn new() -> GameResult<MainState> {
let s = MainState {
particles: Vec::new(),
gravity_enabled: true,
walls_enabled: true,
current_material: Material::Water,
mouse_down: false,
mouse_pos: Vec2::ZERO,
keys_pressed: HashSet::new(),
};
Ok(s)
}
fn toggle_gravity(&mut self) {
self.gravity_enabled = !self.gravity_enabled;
}
fn toggle_walls(&mut self) {
self.walls_enabled = !self.walls_enabled;
}
fn switch_material(&mut self) {
self.current_material = match self.current_material {
Material::Water => Material::Eraser,
Material::Eraser => Material::Water,
};
}
fn add_particle(&mut self, position: Vec2) {
if self.particles.len() < MAX_PARTICLES {
self.particles.push(Particle::new(position));
}
}
fn erase_particles(&mut self, position: Vec2) {
let radius_sq = (PARTICLE_RADIUS * 5.0).powi(2);
self.particles.retain(|p| (p.position - position).length_squared() > radius_sq);
}
}
impl EventHandler for MainState {
fn update(&mut self, ctx: &mut Context) -> GameResult {
let dt = ggez::timer::delta(ctx).as_secs_f32();
// Update particles
for particle in &mut self.particles {
if self.gravity_enabled {
particle.velocity += GRAVITY * dt;
}
particle.position += particle.velocity * dt;
if self.walls_enabled {
// Collision with walls
let (width, height) = graphics::drawable_size(ctx);
if particle.position.x <= PARTICLE_RADIUS {
particle.position.x = PARTICLE_RADIUS;
particle.velocity.x *= -0.5;
} else if particle.position.x >= width - PARTICLE_RADIUS {
particle.position.x = width - PARTICLE_RADIUS;
particle.velocity.x *= -0.5;
}
if particle.position.y <= PARTICLE_RADIUS {
particle.position.y = PARTICLE_RADIUS;
particle.velocity.y *= -0.5;
} else if particle.position.y >= height - PARTICLE_RADIUS {
particle.position.y = height - PARTICLE_RADIUS;
particle.velocity.y *= -0.5;
}
} else {
// Remove particles that go off-screen
let (width, height) = graphics::drawable_size(ctx);
if particle.position.x < 0.0
|| particle.position.x > width
|| particle.position.y < 0.0
|| particle.position.y > height
{
particle.position = Vec2::new(-1000.0, -1000.0); // Move off-screen
}
}
}
// Remove off-screen particles
self.particles
.retain(|p| p.position.x >= 0.0 && p.position.y >= 0.0);
// Handle drawing and erasing
if self.mouse_down {
match self.current_material {
Material::Water => {
self.add_particle(self.mouse_pos);
}
Material::Eraser => {
self.erase_particles(self.mouse_pos);
}
}
}
Ok(())
}
fn draw(&mut self, ctx: &mut Context) -> GameResult {
graphics::clear(ctx, Color::BLACK);
// Draw particles
for particle in &self.particles {
let circle = Mesh::new_circle(
ctx,
DrawMode::fill(),
Point2::new(particle.position.x, particle.position.y),
PARTICLE_RADIUS,
0.1,
Color::from_rgb(0, 0, 255),
)?;
graphics::draw(ctx, &circle, (Point2::new(0.0, 0.0),))?;
}
graphics::present(ctx)?;
Ok(())
}
fn mouse_button_down_event(
&mut self,
_ctx: &mut Context,
button: MouseButton,
x: f32,
y: f32,
) {
if button == MouseButton::Left {
self.mouse_down = true;
self.mouse_pos = Vec2::new(x, y);
}
}
fn mouse_button_up_event(&mut self, _ctx: &mut Context, button: MouseButton, _x: f32, _y: f32) {
if button == MouseButton::Left {
self.mouse_down = false;
}
}
fn mouse_motion_event(
&mut self,
_ctx: &mut Context,
x: f32,
y: f32,
_dx: f32,
_dy: f32,
) {
self.mouse_pos = Vec2::new(x, y);
}
fn key_down_event(
&mut self,
_ctx: &mut Context,
keycode: KeyCode,
_keymods: input::keyboard::KeyMods,
_repeat: bool,
) {
self.keys_pressed.insert(keycode);
match keycode {
KeyCode::G => self.toggle_gravity(),
KeyCode::W => self.toggle_walls(),
KeyCode::M => self.switch_material(),
_ => {}
}
}
fn key_up_event(
&mut self,
_ctx: &mut Context,
keycode: KeyCode,
_keymods: input::keyboard::KeyMods,
) {
self.keys_pressed.remove(&keycode);
}
}
fn main() -> GameResult {
let (ctx, event_loop) = &mut ContextBuilder::new("oe_cake_clone", "Your Name")
.window_setup(conf::WindowSetup::default().title("OE Cake Clone"))
.window_mode(conf::WindowMode::default().dimensions(800.0, 600.0))
.build()?;
let state = &mut MainState::new()?;
event::run(ctx, event_loop, state)
}
Explanation
Dependencies
ggez: A lightweight game framework for Rust that handles window creation, input, graphics, and more.
glam: A fast and efficient math library for games and graphics that provides vector types like Vec2.
Core Components
- Particles: Each particle has a position and velocity. Particles are stored in a vector.
- Gravity: Particles are affected by gravity if it is enabled.
- Walls: Particles collide with the edges of the window if walls are enabled.
- Materials: You can switch between drawing water (
Material::Water) and an eraser (Material::Eraser).
- Input Handling:
- Left mouse button presses and movements are used to draw or erase particles.
- Key presses (
G, W, M) are used to toggle gravity, walls, and switch materials.
Controls
- Left Mouse Button: Draws particles (water) or erases them, depending on the current material.
G Key: Toggles gravity on and off.
W Key: Toggles walls (edge collisions) on and off.
M Key: Switches between Water and Eraser modes.
How to Run the Program
Prerequisites
Steps
-
Create a New Project Directory:
Open a terminal and create a new directory for your project:
mkdir oe_cake_clone
cd oe_cake_clone
-
Initialize a New Cargo Project:
cargo init --bin
-
Edit Cargo.toml:
Open Cargo.toml and add the dependencies as shown above. Alternatively, you can add them using Cargo commands:
cargo add ggez
cargo add glam
-
Replace src/main.rs:
Replace the contents of src/main.rs with the code provided above.
-
Build and Run:
Build and run the project using:
cargo run
If everything is set up correctly, a window titled "OE Cake Clone" should appear.
Playing the Game
- Drawing Water:
- Ensure the current material is set to Water (press
M if not).
- Click and hold the left mouse button to draw water particles on the screen.
- Erasing Particles:
- Press
M to switch to Eraser mode.
- Click and hold the left mouse button to erase particles.
- Toggle Gravity:
- Press
G to toggle gravity on or off.
- Toggle Walls:
- Press
W to enable or disable wall collisions.
- Switch Materials:
- Press
M to switch between Water and Eraser modes.
Notes
- This is a simplified simulation and does not include advanced physics like fluid dynamics or soft-body mechanics.
- Implementing real-time fluid dynamics requires complex algorithms and is beyond the scope of this example.
- Performance may degrade with a large number of particles due to the lack of optimization.
Further Improvements
To create a more realistic simulation, consider the following enhancements:
- Fluid Dynamics: Implement Smoothed Particle Hydrodynamics (SPH) for a realistic fluid simulation.
- Optimization: Use spatial partitioning (like a grid or quadtree) to optimize collision detection and interaction between particles.
- Physics Libraries: Integrate a physics engine like
rapier or nphysics for more advanced physics features.
Additional Resources
By following the steps above, you should have a basic interactive application where you can draw and erase particles, toggle gravity and walls, and switch materials. This should provide a foundation that you can build upon to create more complex simulations.
Enjoy coding your game!