338 lines
14 KiB
Python
338 lines
14 KiB
Python
#File Name: sim.py
|
|
|
|
#Load the imports. Pygame is what makes this even work and so simple may consider other engines for performance depends on learning curve.
|
|
from imports import json, random
|
|
|
|
|
|
|
|
# Load particle properties from json so we know what particles we got and how they should be simulated.
|
|
try:
|
|
with open('sandpypi/particles.json') as f:
|
|
particle_properties = json.load(f)
|
|
except (FileNotFoundError, json.JSONDecodeError):
|
|
print("Error loading particles.json")
|
|
particle_properties = {}
|
|
|
|
|
|
class Particle:
|
|
def __init__(self, position, velocity, mass, particle_type, properties, temperature=20):
|
|
self.position = position # (x, y)
|
|
self.velocity = velocity # (vx, vy)
|
|
self.mass = mass
|
|
self.particle_type = particle_type
|
|
self.temperature = temperature
|
|
|
|
# Initialize additional properties from the dictionary
|
|
self.flamability = properties.get("flamability", 0.0)
|
|
self.viscosity = properties.get("viscosity", 1.0)
|
|
self.is_gas = properties.get("is_gas", False)
|
|
self.electric_charge = properties.get("electric_charge", 0)
|
|
|
|
@classmethod
|
|
def from_type(cls, position, particle_type, properties):
|
|
default_velocity = [0, 0]
|
|
default_mass = properties.get("mass", 1.0)
|
|
return cls(position, default_velocity, default_mass, particle_type, properties)
|
|
|
|
|
|
class Simulation:
|
|
# the main class of the simulation.
|
|
def __init__(self, width, height, x=0, y=0):
|
|
self.x = x
|
|
self.y = y
|
|
self.new_x = 0
|
|
self.new_y = 0
|
|
self.width = width
|
|
self.height = height
|
|
self.particle_size = 3
|
|
self.particles = [[None for _ in range(height)] for _ in range(width)]
|
|
self.active_particles = set()
|
|
self.cell_size = 32
|
|
self.spatial_grid = {}
|
|
self.brush_size = 1
|
|
self.max_brush_size = 20
|
|
self.particle_properties = particle_properties
|
|
self.current_particle_type = 'sand'
|
|
self.gravity = 9.8 # m/s^2, adjustable based on the scale of simulation
|
|
self.wind = [0.0, 0.0] # Global wind vector (x, y)
|
|
|
|
|
|
def calculate_forces(self, particle, x, y):
|
|
"""Calculate net forces acting on a particle."""
|
|
fx, fy = 0.0, particle.mass * self.gravity # Start with gravity
|
|
|
|
# Apply wind force
|
|
fx += self.wind[0] * (1.0 if not particle.is_gas else 0.5) # Gases affected less
|
|
fy += self.wind[1] * (1.0 if not particle.is_gas else 0.5)
|
|
|
|
# Apply drag force (opposes velocity)
|
|
drag = particle.viscosity * -1
|
|
fx += drag * particle.velocity[0]
|
|
fy += drag * particle.velocity[1]
|
|
|
|
# Interactions with neighbors
|
|
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
|
nx, ny = x + dx, y + dy
|
|
if 0 <= nx < self.width and 0 <= ny < self.height:
|
|
neighbor = self.particles[nx][ny]
|
|
if neighbor:
|
|
if neighbor.temperature > particle.temperature:
|
|
fy += (neighbor.temperature - particle.temperature) * 0.1
|
|
if neighbor.is_gas and not particle.is_gas:
|
|
fx += dx * 0.1
|
|
fy += dy * 0.1
|
|
|
|
return fx, fy
|
|
|
|
|
|
def ignite_particle(self, particle):
|
|
"""Handle ignition and burning of flammable particles."""
|
|
if particle.flamability > 0.5 and particle.temperature > 150: #threshold
|
|
particle.type = 'fire'
|
|
particle.temperature += 200
|
|
|
|
|
|
def spread_fire(self):
|
|
"""Spread fire to neighboring particles."""
|
|
for x, y in list(self.active_particles):
|
|
particle = self.particles[x][y]
|
|
if particle and particle.type == 'fire':
|
|
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
|
|
nx, ny = x + dx, y + dy
|
|
if 0 <= nx < self.width and 0 <= ny < self.height:
|
|
neighbor = self.particles[nx][ny]
|
|
if neighbor and neighbor.flamability > 0:
|
|
self.ignite_particle(neighbor)
|
|
|
|
|
|
def simulate_step(self, dt):
|
|
"""Run a single step of the simulation."""
|
|
self.apply_physics(dt)
|
|
self.spread_fire()
|
|
|
|
|
|
def get_cell_key(self, x, y):
|
|
# Convert coordinates to grid cell
|
|
cell_x = x // self.cell_size
|
|
cell_y = y // self.cell_size
|
|
return (cell_x, cell_y)
|
|
|
|
|
|
def add_to_spatial_grid(self, particle, x, y):
|
|
cell_key = self.get_cell_key(x, y)
|
|
if cell_key not in self.spatial_grid:
|
|
self.spatial_grid[cell_key] = set()
|
|
self.spatial_grid[cell_key].add((x, y))
|
|
|
|
|
|
def remove_from_spatial_grid(self, x, y):
|
|
cell_key = self.get_cell_key(x, y)
|
|
if cell_key in self.spatial_grid:
|
|
self.spatial_grid[cell_key].discard((x, y))
|
|
|
|
|
|
def create_particle_circle(self, center_x, center_y):
|
|
brush_size = int(self.brush_size)
|
|
for dx in range(-brush_size, brush_size + 1):
|
|
for dy in range(-brush_size, brush_size + 1):
|
|
if dx*dx + dy*dy <= brush_size*brush_size: # Circle check
|
|
self.create_particle(center_x + dx * self.particle_size,
|
|
center_y + dy * self.particle_size)
|
|
|
|
|
|
def create_particle(self, x, y):
|
|
print(f"Creating particle at ({x}, {y})")
|
|
particle_type = self.current_particle_type.lower()
|
|
if particle_type in self.particle_properties:
|
|
grid_x = x // self.particle_size
|
|
grid_y = y // self.particle_size
|
|
if 0 <= grid_x < self.width and 0 <= grid_y < self.height:
|
|
properties = self.particle_properties[particle_type]
|
|
new_particle = type('Particle', (), {})
|
|
new_particle.x = grid_x
|
|
new_particle.y = grid_y
|
|
new_particle.type = particle_type
|
|
|
|
velocity_scalar = properties.get('velocity', 0)
|
|
new_particle.velocity = [0, velocity_scalar]
|
|
new_particle.acceleration = [0, self.gravity]
|
|
|
|
for key, value in properties.items():
|
|
if key != 'velocity':
|
|
setattr(new_particle, key, value)
|
|
|
|
if 0 <= grid_x < len(self.particles) and 0 <= grid_y < len(self.particles[0]):
|
|
self.particles[grid_x][grid_y] = new_particle
|
|
self.active_particles.add((grid_x, grid_y))
|
|
|
|
|
|
|
|
def apply_gravity(self, dt):
|
|
# Simplfied gravity which has enabled us to have a working system need improvement/more physics simulations.
|
|
self.spatial_grid.clear()
|
|
|
|
# Populate spatial grid
|
|
for x, y in self.active_particles:
|
|
self.add_to_spatial_grid(self.particles[x][y], x, y)
|
|
|
|
# Now we only check particles in nearby cells
|
|
for x, y in list(self.active_particles):
|
|
cell_key = self.get_cell_key(x, y)
|
|
nearby_cells = [
|
|
(cell_key[0] + dx, cell_key[1] + dy)
|
|
for dx in [-1, 0, 1]
|
|
for dy in [-1, 0, 1]
|
|
]
|
|
|
|
for x, y in list(self.active_particles):
|
|
particle = self.particles[x][y]
|
|
if not particle:
|
|
self.active_particles.discard((x, y))
|
|
continue
|
|
|
|
if particle.type == 'wall':
|
|
continue
|
|
|
|
new_x, new_y = x, y + 1
|
|
|
|
# Add boundary check before accessing array. This doesn't check the outer boundariers of the grid but instead boundaries in programming to ensure smooth run
|
|
# There does need to be a Boundary check system perfably something that can be enabled or disabled in a settings menu for the simulation.
|
|
# that system would be to ensure particles do not leave the boundaries of the grid
|
|
if not (0 <= new_x < self.width and 0 <= new_y < self.height):
|
|
continue
|
|
|
|
particle.velocity[1] += self.gravity * dt
|
|
|
|
if hasattr(particle, 'liquid') and particle.liquid:
|
|
# Try to move down first
|
|
if y + 1 < self.height and self.particles[x][y + 1] is None:
|
|
new_x, new_y = x, y + 1
|
|
# If can't move down, try to spread horizontally
|
|
elif y + 1 < self.height:
|
|
spread_directions = [(-1, 0), (1, 0)] # Left and right
|
|
random.shuffle(spread_directions) # Randomize flow direction
|
|
moved = False
|
|
for dx, dy in spread_directions:
|
|
new_x, new_y = x + dx, y
|
|
if (0 <= new_x < self.width and
|
|
self.particles[new_x][new_y] is None):
|
|
moved = True
|
|
break
|
|
if not moved:
|
|
continue
|
|
else:
|
|
continue
|
|
|
|
#placeholder for gas.
|
|
if hasattr(particle, 'Gas') and particle.Gas:
|
|
if new_x > 0 and self.particles[new_x - 1][new_y] is None:
|
|
new_x -= 1
|
|
elif new_x < self.width - 1 and self.particles[new_x + 1][new_y] is None:
|
|
new_x += 1
|
|
|
|
#placeholder for fire
|
|
if hasattr(particle, 'fire') and particle.fire:
|
|
# Check if there's a liquid
|
|
if y + 1 < self.height and self.particles[x][y + 1] is not None and self.particles[x][y + 1].liquid:
|
|
# Check if there's a flammable particle below
|
|
if y + 2 < self.height and self.particles[x][y + 2] is not None and self.particles[x][y + 2].flammable:
|
|
# Set the particle below to burning
|
|
self.particles[x][y + 1].burning = True
|
|
# Set the particle two below to flammable
|
|
self.ignite_particle(x, y + 2)
|
|
# Set the particle below to flammable
|
|
self.particles[x][y + 1].flammable = True
|
|
# Set the particle two below to flammable
|
|
self.particles[x][y + 2].flammable = True
|
|
# Check if Solid is flammable
|
|
|
|
# I believe this is being done horribly wrong plus the system isn't accounting for some of this yet.
|
|
if hasattr(particle, 'Solid') and particle.Solid:
|
|
if y + 1 < self.height and self.particles[x][y + 1] is not None and self.particles[x][y + 1].flammable:
|
|
self.particles[x][y + 1].burning = True
|
|
self.ignite_particle(x, y + 1)
|
|
self.ignite_particle(x, y + 2)
|
|
self.ignite_particle(x, y + 3)
|
|
|
|
|
|
|
|
if self.particles[new_x][new_y] is None:
|
|
self.particles[x][y] = None
|
|
self.particles[new_x][new_y] = particle
|
|
self.active_particles.add((new_x, new_y))
|
|
self.active_particles.discard((x, y))
|
|
particle.x, particle.y = new_x, new_y
|
|
|
|
"""
|
|
# Complicated physics engine non working ATM.
|
|
def apply_physics(self, dt):
|
|
#Apply all physics effects to active particles.
|
|
new_active_particles = set()
|
|
for x, y in list(self.active_particles):
|
|
particle = self.particles[x][y]
|
|
if not particle:
|
|
continue
|
|
|
|
# Update forces based on particle properties
|
|
fx, fy = self.calculate_forces(particle, x, y)
|
|
|
|
# Update velocity
|
|
particle.velocity[0] += (fx / particle.mass) * dt
|
|
particle.velocity[1] += (fy / particle.mass) * dt
|
|
|
|
# Apply friction (simplified as proportional to velocity)
|
|
particle.velocity[0] *= 1 - particle.friction
|
|
particle.velocity[1] *= 1 - particle.friction
|
|
|
|
# Update position
|
|
new_x = int(particle.position[0] + particle.velocity[0] * dt)
|
|
new_y = int(particle.position[1] + particle.velocity[1] * dt)
|
|
|
|
# Handle collisions and boundary conditions
|
|
if 0 <= new_x < self.width and 0 <= new_y < self.height:
|
|
if self.particles[new_x][new_y] is None: # Move particle
|
|
self.particles[x][y] = None
|
|
self.particles[new_x][new_y] = particle
|
|
particle.position = [new_x, new_y]
|
|
new_active_particles.add((new_x, new_y))
|
|
else: # Handle collisions (simple exchange of velocity)
|
|
particle.velocity[0] *= -0.5
|
|
particle.velocity[1] *= -0.5
|
|
else: # Boundary collision
|
|
particle.velocity[0] *= -0.5
|
|
particle.velocity[1] *= -0.5
|
|
|
|
self.active_particles = new_active_particles
|
|
"""
|
|
|
|
""" if particle.is_gas:
|
|
# Gas-specific movement
|
|
dx = random.uniform(-1, 1)
|
|
dy = random.uniform(-2, 0) # Bias upward
|
|
new_x = int(x + dx)
|
|
new_y = int(y + dy)
|
|
|
|
if 0 <= new_x < self.width and 0 <= new_y < self.height:
|
|
if self.particles[new_x][new_y] is None:
|
|
self.particles[x][y] = None
|
|
self.particles[new_x][new_y] = particle
|
|
new_active_particles.add((new_x, new_y))
|
|
self.active_particles.discard((x, y))
|
|
else:
|
|
# Regular particle physics
|
|
particle.velocity[0] += (fx / particle.mass) * dt
|
|
particle.velocity[1] += (fy / particle.mass) * dt
|
|
|
|
if particle.liquid:
|
|
# Enhanced liquid spreading
|
|
spread_chance = 0.8
|
|
if random.random() < spread_chance:
|
|
dx = random.choice([-1, 1])
|
|
if (0 <= x + dx < self.width and
|
|
self.particles[x + dx][y] is None):
|
|
new_x = x + dx
|
|
new_y = y
|
|
self.particles[x][y] = None
|
|
self.particles[new_x][new_y] = particle
|
|
new_active_particles.add((new_x, new_y))
|
|
continue""" |