Initial commit

This commit is contained in:
Stan44 2024-12-26 04:11:32 -06:00
commit 73470225d0
14 changed files with 13232 additions and 0 deletions

16
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,16 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python Debugger: Current File",
"type": "debugpy",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal"
}
]
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

6
imports.py Normal file
View File

@ -0,0 +1,6 @@
#File Name: imports.py
import pygame
import json
import random
import time

445
particles.json Normal file
View File

@ -0,0 +1,445 @@
{
"sand": {
"name": "Sand",
"size": 1,
"hardness": 0.5,
"color": [255, 255, 0, 255],
"velocity": 0.5,
"mass": 0.5,
"conductivity": 0,
"heat_capacity": 1,
"flamability": 0.8,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0,
"pressure": 0,
"melt": "molten-Glass",
"melt_temperature": 1000,
"conductive": false,
"liquid": false,
"solid": true,
"is_gas": false
},
"water": {
"name": "Water",
"size": 1,
"hardness": 0.2,
"velocity": 0.3,
"conductivity": 1,
"heat_capacity": 1,
"color": [0, 0, 255, 255],
"mass": 1,
"flamability": 0,
"temperature": 22,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 1,
"viscosity": 1,
"pressure": 0.5,
"evaporate": "steam",
"evaporate_temperature": 145,
"freeze": "ice",
"freeze_temperature": 0,
"melt": "water",
"melt_temperature": 20,
"liquid": true,
"solid": false,
"is_gas": false
},
"steam": {
"name": "Steam",
"size": 1,
"hardness": 0.0,
"velocity": 0.2,
"conductivity": 1,
"heat_capacity": 1,
"color": [255, 255, 255, 255],
"mass": 0.01,
"flamability": 0,
"temperature": 100,
"solidify_temperature": 98,
"solidify": "water",
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": false,
"is_gas": true,
"conductive": false
},
"ice": {
"name": "Ice",
"size": 1,
"hardness": 1000,
"velocity": 0.0,
"conductivity": 0,
"heat_capacity": 0,
"color": [75, 75, 75, 255],
"mass": 1,
"flamability": 0.0,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 1,
"viscosity": 1,
"liquid": false,
"solid": true,
"is_gas": false
},
"mud": {
"name": "Mud",
"size": 1,
"hardness": 0.4,
"velocity": 0.5,
"conductivity": 1,
"heat_capacity": 1,
"color": [139, 69, 19, 255],
"mass": 0.5,
"flamability": 0,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 1,
"liquid": false,
"solid": true,
"is_gas": false
},
"fire": {
"name": "Fire",
"size": 1,
"hardness": 0.1,
"velocity": 0.1,
"conductivity": 0,
"heat_capacity": 1,
"color": [255, 0, 0, 255],
"mass": 0.1,
"flamability": 1,
"temperature": 1000,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.1,
"viscosity": 0.1,
"liquid": false,
"solid": false,
"is_gas": true
},
"smoke": {
"name": "Smoke",
"size": 1,
"hardness": 0.1,
"velocity": 0.1,
"conductivity": 0,
"heat_capacity": 1,
"color": [115, 113, 95, 255],
"mass": 0.01,
"flamability": 0,
"temperature": 85,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.4,
"viscosity": 0.1,
"lifetime": 90,
"liquid": false,
"solid": false,
"is_gas": true
},
"wall": {
"name": "Wall",
"size": 1,
"hardness": 1000,
"velocity": 0.0,
"conductivity": 0,
"heat_capacity": 0,
"color": [75, 75, 75, 255],
"mass": 1,
"flamability": 0.1,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 1,
"viscosity": 1,
"liquid": false,
"solid": true,
"is_gas": false
},
"dirt": {
"name": "Dirt",
"size": 1,
"hardness": 0.5,
"velocity": 0.5,
"conductivity": 0,
"heat_capacity": 1,
"color": [139, 69, 19, 255],
"mass": 0.5,
"flamability": 0,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": true,
"is_gas": false
},
"stone": {
"name": "Stone",
"size": 1,
"hardness": 0.7,
"velocity": 1.5,
"conductivity": 0,
"heat_capacity": 0,
"color": [128, 128, 128, 255],
"mass": 1,
"flamability": 0,
"melt": "molten-Stone",
"melt_temperature": 800,
"solidify": "stone",
"solidify_temperature": 799,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": true,
"is_gas": false
},
"snow": {
"name": "Snow",
"size": 1,
"hardness": 0.1,
"velocity": 0.2,
"conductivity": 1,
"heat_capacity": 1,
"color": [255, 255, 255, 255],
"mass": 0.01,
"flamability": 0,
"melt": "water",
"melt_temperature": 10,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.1,
"viscosity": 0.01,
"liquid": false,
"solid": true,
"is_gas": false
},
"wood": {
"name": "Wood",
"size": 1,
"hardness": 0.5,
"velocity": 0.5,
"conductivity": 0,
"heat_capacity": 1,
"color": [139, 69, 19, 255],
"mass": 0.5,
"flamability": 0.8,
"burning_temperature": 250,
"burning_rate": 0.01,
"burning_color": [255, 0, 0, 255],
"burning": false,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": true,
"is_gas": false
},
"burning-wood": {
"name": "Burning Wood",
"size": 1,
"hardness": 0.5,
"velocity": 0.5,
"conductivity": 0,
"heat_capacity": 1,
"color": [139, 69, 19, 255],
"mass": 0.5,
"flamability": 0.8,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": true,
"is_gas": false
},
"air": {
"name": "Air",
"size": 1,
"hardness": 0.0,
"velocity": 0.0,
"conductivity": 0,
"heat_capacity": 1,
"color": [25, 25, 25, 25],
"mass": 0.0,
"flamability": 0,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.0,
"viscosity": 0.0,
"liquid": false,
"solid": false,
"is_gas": true
},
"lava": {
"name": "Lava",
"size": 1,
"hardness": 0.2,
"velocity": 0.5,
"conductivity": 0,
"heat_capacity": 1,
"color": [255, 45, 24, 255],
"mass": 0.3,
"flamability": 0,
"temperature": 2700,
"solidify": "molten-rock",
"solidify_temperature": 799,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.8,
"viscosity": 0.8,
"liquid": true,
"solid": false,
"is_gas": false
},
"rock": {
"name": "Rock",
"size": 1,
"hardness": 0.2,
"velocity": 0.3,
"conductivity": 1,
"heat_capacity": 1,
"color": [128, 128, 128, 255],
"mass": 0.8,
"flamability": 0,
"melt": "molten-rock",
"melt_temperature": 799,
"temperature": 0,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [
0,
0,
0
],
"friction": 0.5,
"viscosity": 0.5,
"liquid": false,
"solid": true,
"is_gas": false
},
"molten-rock": {
"name": "Molten Rock",
"size": 1,
"hardness": 0.2,
"velocity": 0.3,
"conductivity": 1,
"heat_capacity": 1,
"color": [255, 140, 0, 255],
"mass": 0.8,
"flamability": 0,
"temperature": 799,
"melt": "lavaa",
"melt_temperature": 1200,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0,0,0],
"friction": 0.8,
"viscosity": 0.8,
"liquid": true,
"solid": false,
"is_gas": false,
"solidify": "rock",
"solidify_temperature": 200
},
"molten_stone": {
"name": "Molten Stone",
"size": 1,
"hardness": 0.2,
"velocity": 0.3,
"conductivity": 1,
"heat_capacity": 1,
"color": [255, 140, 0, 255],
"mass": 0.8,
"flamability": 0,
"temperature": 1200,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.8,
"viscosity": 0.8,
"liquid": true,
"solid": false,
"is_gas": false,
"solidify": "stone",
"solidify_temperature": 800
},
"molten_glass": {
"name": "Molten Glass",
"size": 1,
"hardness": 0.2,
"velocity": 0.4,
"conductivity": 0.8,
"heat_capacity": 1,
"color": [255, 200, 150, 200],
"mass": 0.6,
"flamability": 0,
"temperature": 1200,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.7,
"viscosity": 0.9,
"liquid": true,
"solid": false,
"is_gas": false,
"solidify": "glass",
"solidify_temperature": 800
},
"flame": {
"name": "Flame",
"size": 1,
"hardness": 0.0,
"velocity": 0.0,
"conductivity": 0,
"heat_capacity": 1,
"color": [255, 100, 0, 255],
"mass": 0.0,
"flamability": 0,
"temperature": 1000,
"explosive": false,
"explosion_radius": 0,
"explosion_color": [0, 0, 0],
"friction": 0.0,
"viscosity": 0.0,
"liquid": false,
"solid": false,
"is_gas": true
}
}

212
rendering.py Normal file
View File

@ -0,0 +1,212 @@
#File Name: rendering.py
from imports import pygame, json, random
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 Rendering:
def __init__(self, width, height):
self.screen = pygame.display.set_mode((width, height))
self.background = pygame.Surface((width, height))
self.background.fill((0, 0, 0))
self.width = width
self.height = height
self.particle_surface = pygame.Surface((width, height), pygame.SRCALPHA)
self.particle_colors = {}
self.button_width, self.button_height = 30, 30
self.particle_properties = particle_properties
self.buttons = {}
self.clear_screen_button = pygame.Rect(915, 10, 50, 30)
self.load_buttons() # Load buttons dynamically
self.particle_colors = {}
for name, properties in particle_properties.items():
if 'color' in properties:
self.particle_colors[name.lower()] = properties['color']
self.categories = {
'Solids': [],
'Liquids': [],
'Gases': [],
'Special': []
}
for particle_name, properties in self.particle_properties.items():
if properties.get('is_gas'):
self.categories['Gases'].append(particle_name)
elif properties.get('liquid'):
self.categories['Liquids'].append(particle_name)
elif properties.get('solid'):
self.categories['Solids'].append(particle_name)
else:
self.categories['Special'].append(particle_name)
self.current_category = 'Solids'
self.category_buttons = {}
self.setup_category_menu()
def setup_category_menu(self):
# Category buttons at the top
x_offset = self.width - 350
y_offset = 10
for category in self.categories:
button_rect = pygame.Rect(x_offset, y_offset, 80, 25)
self.category_buttons[category] = button_rect
x_offset += 90
def load_buttons(self):
x_offset = 10
y_offset = 10
for particle_type, properties in self.particle_properties.items():
if 'color' in properties:
button_rect = pygame.Rect(x_offset, y_offset, self.button_width, self.button_height)
self.buttons[particle_type.lower()] = button_rect
x_offset += self.button_width + 10 # Add spacing between buttons
def draw_particles(self, particles, active_particles, particle_size, particle_colors):
self.particle_surface = pygame.Surface((self.width, self.height), pygame.SRCALPHA)
self.particle_surface.fill((0, 0, 0, 0))
for x, y in active_particles:
particle = particles[x][y]
if not particle:
continue
base_color = particle_colors.get(particle.particle_type, (255, 255, 255))
color = list(base_color)
if particle.is_gas:
# Enhanced gas visibility
alpha = random.randint(128, 200)
color = list(color)
if len(color) < 4:
color.append(alpha)
else:
color[3] = alpha
# Add subtle movement effect
offset_x = random.randint(-1, 1)
offset_y = random.randint(-1, 1)
rect = (x * particle_size + offset_x, y * particle_size + offset_y,
particle_size, particle_size)
else:
rect = (x * particle_size, y * particle_size,
particle_size, particle_size)
pygame.draw.rect(self.particle_surface, color, rect)
self.screen.blit(self.background, (0, 0))
self.screen.blit(self.particle_surface, (0, 0))
def draw_debug_overlay(self, fps, particles):
# Get mouse position and convert to grid coordinates
mouse_x, mouse_y = pygame.mouse.get_pos()
grid_x = mouse_x // 3
grid_y = mouse_y // 3
# Get particle info under cursor
particle_info = "None"
if 0 <= grid_x < len(particles) and 0 <= grid_y < len(particles[0]):
particle = particles[grid_x][grid_y]
if particle:
# Include more detailed particle information
particle_info = f"Type: {particle.particle_type}"
if hasattr(particle, 'temperature'):
particle_info += f" | Temp: {particle.temperature}°C"
if hasattr(particle, 'liquid'):
particle_info += f" | Liquid: {particle.liquid}"
if hasattr(particle, 'is_gas'):
particle_info += f" | Gas: {particle.is_gas}"
if hasattr(particle, 'solid'):
particle_info += f" | Solid: {particle.solid}"
if hasattr(particle, 'mass'):
particle_info += f" | Mass: {particle.mass}"
if hasattr(particle, 'velocity'):
particle_info += f" | Velocity: {particle.velocity}"
if hasattr(particle, 'friction'):
particle_info += f" | Friction: {particle.friction}"
# Draw debug information
font = pygame.font.SysFont(None, 24)
debug_info = [
f"FPS: {int(fps)}",
f"Mouse: ({mouse_x}, {mouse_y})",
f"Grid: ({grid_x}, {grid_y})",
f"Particle: {particle_info}"
]
y_offset = 10
for info in debug_info:
debug_text = font.render(info, True, (255, 255, 255))
self.screen.blit(debug_text, (10, y_offset))
y_offset += 25
def draw_buttons(self):
self.buttons = {}
# Draw category buttons vertically on right
x_offset = self.width - 100
y_offset = 10
for category, button in self.category_buttons.items():
color = (200, 200, 200) if category == self.current_category else (150, 150, 150)
pygame.draw.rect(self.screen, color, button)
font = pygame.font.SysFont(None, 20)
label = font.render(category, True, (0, 0, 0))
self.screen.blit(label, (button.x + 5, button.y + 5))
# Draw particle buttons for current category
y_offset = 150 # Start particle buttons below categories
for particle_type in self.categories[self.current_category]:
if particle_type in self.particle_properties:
color = self.particle_properties[particle_type].get('color', (255, 255, 255))
button_rect = pygame.Rect(x_offset, y_offset, 80, 25)
self.buttons[particle_type] = button_rect
pygame.draw.rect(self.screen, color, button_rect)
pygame.draw.rect(self.screen, (0, 0, 0), button_rect, 2)
font = pygame.font.SysFont(None, 20)
label = font.render(particle_type, True, (0, 0, 0))
self.screen.blit(label, (x_offset + 5, y_offset + 5))
y_offset += 30 # Stack buttons vertically
# Draw clear screen button
self.clear_screen_button = pygame.Rect(x_offset, y_offset + 10, 80, 25)
pygame.draw.rect(self.screen, (255, 0, 0), self.clear_screen_button)
font = pygame.font.SysFont(None, 24)
label = font.render("Clear", True, (255, 255, 255))
self.screen.blit(label, (self.clear_screen_button.x + 5, self.clear_screen_button.y + 5))
def render_brush_curser(self, x, y, radius):
# Draw a circle cursor for brushsize
pygame.draw.circle(self.screen, (255, 255, 255), (x, y), radius)
def draw_brush_size_slider(self, brush_size):
# Draw the slider for brush size
pygame.draw.rect(self.screen, (255, 255, 255), (500, 10, 100, 20))
pygame.draw.rect(self.screen, (0, 0, 0), (500, 10, 100, 20), 2)
pygame.draw.rect(self.screen, (255, 0, 0), (500 + brush_size, 10, 100 - brush_size * 2, 20))
label = pygame.font.SysFont(None, 24).render(f"Brush Size: {brush_size}", True, (255, 255, 255))
self.screen.blit(label, (500, 10))
def clear_screen(self, sim):
# Store current particle type
current_type = sim.current_particle_type
# Reset simulation grid while preserving particle type
sim.particles = [[None for _ in range(sim.height)] for _ in range(sim.width)]
sim.active_particles.clear()
sim.current_particle_type = current_type
# Clear display surfaces
self.background.fill((0, 0, 0))
self.particle_surface.fill((0, 0, 0, 0))

102
sandpypi.py Normal file
View File

@ -0,0 +1,102 @@
#File Name: sandpypi.py
# Sandpypi by Stanton.
# Project name is a placeholder.
# This has been a multimonth or year project i have time blindness sorta.
# This is my most functional system for falling sand in python yet i took some things i learned in JS.
# This needs further optimizations to core performance sections.
from imports import pygame
from rendering import Rendering
from sim import Simulation
def main():
pygame.init()
clock = pygame.time.Clock()
pygame.display.set_mode((1024, 768), pygame.HWSURFACE | pygame.DOUBLEBUF)
sim = Simulation(1024, 768)
rendering = Rendering(1024, 768)
mouse_down_left = False
mouse_down_right = False
mouse_down_middle = False
mouse_down_wheel_up = False
mouse_down_wheel_down = False
over_button = False
running = True
while running:
fps = clock.get_fps()
dt = clock.tick(60) / 1000
# Handle events
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
if event.button == 4: # Mouse wheel up
sim.brush_size = min(sim.brush_size + 1, sim.max_brush_size)
elif event.button == 5: # Mouse wheel down
sim.brush_size = max(sim.brush_size - 1, 1)
elif event.button == 1: # Left click
over_button = False
# Check category buttons
for category, button in rendering.category_buttons.items():
if button.collidepoint(mouse_pos):
rendering.current_category = category
over_button = True
break
# Check particle buttons
if not over_button:
for particle_type, button in rendering.buttons.items():
if button.collidepoint(mouse_pos):
sim.current_particle_type = particle_type
over_button = True
break
# Check clear screen button
if rendering.clear_screen_button.collidepoint(mouse_pos):
rendering.clear_screen(sim)
over_button = True
if not over_button:
mouse_down_left = True
elif event.button == 3: # Right click
mouse_down_right = True
elif event.button == 2: # Middle click
mouse_down_middle = True
elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:
mouse_down_left = False
elif event.type == pygame.MOUSEBUTTONUP and event.button == 3:
mouse_down_right = False
elif event.type == pygame.MOUSEBUTTONUP and event.button == 2:
mouse_down_middle = False
elif event.type == pygame.QUIT:
running = False
if mouse_down_left and not over_button:
x, y = pygame.mouse.get_pos()
sim.create_particle_circle(x, y)
if mouse_down_right:
x, y = pygame.mouse.get_pos()
sim.clear_particles_circle(x, y)
if mouse_down_middle:
x, y = pygame.mouse.get_pos()
sim.create_particle(x, y)
sim.simulate_step(dt)
rendering.draw_particles(sim.particles, sim.active_particles, sim.particle_size, rendering.particle_colors)
rendering.draw_buttons()
rendering.draw_brush_size_slider(sim.brush_size)
rendering.draw_debug_overlay(fps, sim.particles)
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
main()

6
setup.py Normal file
View File

@ -0,0 +1,6 @@
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize("sandpypi/simulation_core.pyx"),
)

614
sim.py Normal file
View File

@ -0,0 +1,614 @@
#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, time
# 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
# Core properties
self.size = properties.get("size", 1)
self.hardness = properties.get("hardness", 0.5)
self.color = properties.get("color", [255, 255, 255, 255])
self.temperature = properties.get("temperature", temperature)
# Physics properties
self.conductivity = properties.get("conductivity", 0)
self.heat_capacity = properties.get("heat_capacity", 1)
self.flamability = properties.get("flamability", 0.0)
self.friction = properties.get("friction", 0.5)
self.viscosity = properties.get("viscosity", 1.0)
self.pressure = properties.get("pressure", 0)
# State properties
self.liquid = properties.get("liquid", False)
self.solid = properties.get("solid", True)
self.is_gas = properties.get("is_gas", False)
# Temperature transition properties
self.melt = properties.get("melt", None)
self.melt_temperature = properties.get("melt_temperature", None)
self.solidify = properties.get("solidify", None)
self.solidify_temperature = properties.get("solidify_temperature", None)
self.evaporate = properties.get("evaporate", None)
self.evaporate_temperature = properties.get("evaporate_temperature", None)
self.freeze = properties.get("freeze", None)
self.freeze_temperature = properties.get("freeze_temperature", None)
# Special properties
self.explosive = properties.get("explosive", False)
self.explosion_radius = properties.get("explosion_radius", 0)
self.explosion_color = properties.get("explosion_color", [0, 0, 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 handle_phase_transitions(self, particle, x, y):
"""Handle all phase transitions for a particle"""
# Check evaporation
if hasattr(particle, 'evaporate_temperature') and particle.evaporate_temperature is not None:
if particle.temperature >= particle.evaporate_temperature and particle.evaporate:
self.transform_particle(x, y, particle.evaporate)
# Check melting
if hasattr(particle, 'melt_temperature') and particle.melt_temperature is not None:
if particle.temperature >= particle.melt_temperature and particle.melt:
self.transform_particle(x, y, particle.melt)
# Check freezing
if hasattr(particle, 'freeze_temperature') and particle.freeze_temperature is not None:
if particle.temperature <= particle.freeze_temperature and particle.freeze:
self.transform_particle(x, y, particle.freeze)
# Check solidification
if hasattr(particle, 'solidify_temperature') and particle.solidify_temperature is not None:
if particle.temperature <= particle.solidify_temperature and particle.solidify:
self.transform_particle(x, y, particle.solidify)
def handle_particle_interactions(self, dt):
"""Handle interactions between different particle types"""
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if not particle:
continue
# Check neighboring particles
for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, -1), (-1, 1), (1, 1)]:
nx, ny = x + dx, y + dy
if 0 <= nx < self.width and 0 <= ny < self.height:
neighbor = self.particles[nx][ny]
if neighbor:
self.process_interaction(particle, neighbor, x, y, nx, ny)
def process_interaction(self, particle1, particle2, x1, y1, x2, y2):
"""Process specific interactions between two particles"""
# Water + Sand = Mud
if (particle1.particle_type == 'water' and particle2.particle_type == 'sand' or
particle2.particle_type == 'water' and particle1.particle_type == 'sand'):
self.create_mud(x1, y1)
self.particles[x2][y2] = None
self.active_particles.discard((x2, y2))
# Lava/Fire effects
if particle1.particle_type in ['lava', 'fire', 'flame'] or particle2.particle_type in ['lava', 'fire', 'flame']:
target = particle2 if particle1.particle_type in ['lava', 'fire', 'flame'] else particle1
target_x, target_y = (x2, y2) if particle1.particle_type in ['lava', 'fire', 'flame'] else (x1, y1)
# Water to Steam
if target.particle_type == 'water':
self.transform_particle(target_x, target_y, 'steam')
# Wood to Fire
elif target.particle_type == 'wood':
if random.random() < 0.3: # 30% chance to ignite
self.transform_particle(target_x, target_y, 'fire')
def create_mud(self, x, y):
"""Create mud particle from water and sand interaction"""
if 'mud' in self.particle_properties:
properties = self.particle_properties['mud']
new_particle = Particle.from_type((x, y), 'mud', properties)
self.particles[x][y] = new_particle
self.active_particles.add((x, y))
def transform_particle(self, x, y, new_type):
"""Transform a particle into a different type"""
if new_type in self.particle_properties:
properties = self.particle_properties[new_type]
new_particle = Particle.from_type((x, y), new_type, properties)
self.particles[x][y] = new_particle
self.active_particles.add((x, y))
def handle_gas_movement(self, particle, x, y):
"""Handle gas particle movement"""
if particle.is_gas:
dx = random.uniform(-1, 1)
dy = random.uniform(-2, 0) # Bias upward movement
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
self.active_particles.add((new_x, new_y))
self.active_particles.discard((x, y))
def temperature(self, dt):
"""Handle temperature changes and state transitions"""
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if not particle:
continue
if particle.temperature > 1100:
# Transition to gas
particle.is_gas = True
particle.temperature = 1100
particle.velocity = [random.uniform(-1, 1), random.uniform(-1, 1)]
particle.temperature < 1100
particle.is_gas = False
def calculate_forces(self, particle, x, y):
"""Calculate net forces acting on a particle."""
fx, fy = 0.0, 0.0 # Initialize forces
# Apply wind force
fx += self.wind[0] * (1.0 if not particle.is_gas else 0.5)
fy += self.wind[1] * (1.0 if not particle.is_gas else 0.5)
# Apply drag force
drag = particle.viscosity * -1
fx += drag * particle.velocity[0]
fy += drag * particle.velocity[1]
# Check neighboring particles
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:
# Temperature effects
if hasattr(neighbor, 'temperature') and hasattr(particle, 'temperature'):
if neighbor.temperature > particle.temperature:
fy += (neighbor.temperature - particle.temperature) * 0.1
# Gas pressure effects
if hasattr(neighbor, 'is_gas') and hasattr(particle, 'is_gas'):
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 hasattr(particle, 'flamability') and particle.flamability > 0.5:
if hasattr(particle, 'temperature') and particle.temperature > 150:
particle.type = 'fire'
particle.temperature += 200
# Add burning effect for wood
if particle.type == 'wood':
particle.burning = True
particle.burn_time = 100 # Adjust burn time as needed
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.particle_type == 'fire' or getattr(particle, 'burning', False)):
# Check all neighboring cells including diagonals
for dx in [-1, 0, 1]:
for dy in [-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 hasattr(neighbor, 'flamability'):
if neighbor.particle_type == 'wood':
# Higher chance to ignite wood
if random.random() < 0.3: # 30% chance to spread
self.ignite_particle(neighbor)
elif neighbor.flamability > 0:
if random.random() < 0.1: # 10% chance for other materials
self.ignite_particle(neighbor)
def handle_temperature(self, dt):
"""Handle temperature changes and state transitions"""
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if not particle:
continue
# Check for melting with proper attribute validation
if (hasattr(particle, 'melt') and hasattr(particle, 'melt_temperature')
and particle.melt_temperature is not None):
if particle.temperature >= particle.melt_temperature:
new_type = particle.melt
if new_type in self.particle_properties:
self.transform_particle(x, y, new_type)
# Check for solidification with proper attribute validation
if (hasattr(particle, 'solidify') and hasattr(particle, 'solidify_temperature')
and particle.solidify_temperature is not None):
if particle.temperature <= particle.solidify_temperature:
new_type = particle.solidify
if new_type in self.particle_properties:
self.transform_particle(x, y, new_type)
# Temperature spread to 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 and hasattr(neighbor, 'temperature')
and neighbor.temperature is not None):
temp_diff = particle.temperature - neighbor.temperature
heat_transfer = temp_diff * 0.1 * dt
particle.temperature -= heat_transfer
neighbor.temperature += heat_transfer
def burning(self):
"""Handle burning of particles."""
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if particle and hasattr(particle, 'burning') and particle.burning:
particle.temperature += 10
if particle.temperature > 1000:
self.particles[x][y] = None
self.active_particles.remove((x, y))
self.spatial_grid.pop((x, y), None)
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):
"""Create a new particle with full property support"""
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]
position = (grid_x, grid_y)
new_particle = Particle(
position=position,
velocity=[0, 0],
mass=properties.get('mass', 1.0),
particle_type=particle_type,
properties=properties
)
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 update_spatial_grid(self):
"""Update spatial grid for optimized collision detection"""
self.spatial_grid.clear()
for x, y in self.active_particles:
self.add_to_spatial_grid(self.particles[x][y], x, y)
def apply_gravity(self, dt):
"""Handle only gravity and basic particle movement"""
self.spatial_grid.clear()
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if not particle or particle.particle_type == 'wall':
continue
# Apply gravity
new_y = y + 1
new_x = x
# Check boundaries
if not (0 <= new_x < self.width and 0 <= new_y < self.height):
continue
# Handle granular materials (sand, dirt)
if particle.particle_type in ['sand', 'dirt']:
if self.particles[x][new_y] is None:
new_x, new_y = x, y + 1
else:
# Try diagonal movement with randomization
diagonal_dirs = [(-1, 1), (1, 1)]
random.shuffle(diagonal_dirs)
for dx, dy in diagonal_dirs:
test_x = x + dx
test_y = y + dy
if (0 <= test_x < self.width and 0 <= test_y < self.height and
self.particles[test_x][test_y] is None):
if random.random() < 0.8: # 80% chance to move diagonally
new_x = test_x
new_y = test_y
break
# Handle liquid movement (water, lava)
elif particle.liquid:
if self.particles[x][new_y] is None:
new_x = x
new_y = y + 1
else:
spread_directions = [(-1, 0), (1, 0)]
random.shuffle(spread_directions)
for dx, _ in spread_directions:
test_x = x + dx
if (0 <= test_x < self.width and
self.particles[test_x][y] is None):
new_x = test_x
new_y = y
break
# Move particle if destination is empty
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.position = (new_x, new_y)
def handle_special_particles(self, particle, x, y):
"""Handle special particle behaviors"""
if particle.particle_type in ['fire', 'flame', 'smoke']:
if random.random() < 0.6: # % chance
self.particles[x][y] = None
self.active_particles.discard((x, y))
if particle.particle_type in ['fire', 'flame', 'lava']:
# Create smoke above with proper physics
if random.random() < 0.65 and y > 0: # % chance for smoke
properties = self.particle_properties['smoke']
new_smoke = Particle.from_type((x, y-1), 'smoke', properties)
if self.particles[x][y-1] is None:
self.particles[x][y-1] = new_smoke
self.active_particles.add((x, y-1))
else:
# Handle collision with water
if particle.particle_type == 'water':
self.particles[x][y-1] = None
self.active_particles.discard((x, y-1))
self.particles[x][y] = None
self.active_particles.discard((x, y))
self.particles[x][y] = Particle.from_type((x, y), 'water', self.particle_properties['water'])
self.active_particles.add((x, y))
def apply_physics(self, dt):
"""Handle all physics effects"""
new_active_particles = set()
for x, y in list(self.active_particles):
particle = self.particles[x][y]
if not particle:
continue
# Skip wall physics - walls are immutable
if particle.particle_type == 'wall':
new_active_particles.add((x, y))
continue
# Handle dissipating particles
if particle.particle_type in ['fire', 'flame']:
# Clear current position first
self.particles[x][y] = None
self.active_particles.discard((x, y))
# Handle fire movement
dx = random.uniform(-0.5, 0.5)
dy = random.uniform(-1.5, -0.5) # Upward drift
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[new_x][new_y] = particle
new_active_particles.add((new_x, new_y))
# Generate smoke above the new fire position
if random.random() < 0.25 and new_y > 0:
properties = self.particle_properties['smoke']
new_smoke = Particle(
position=(new_x, new_y-1),
velocity=[random.uniform(-0.5, 0.5), -1],
mass=properties.get('mass', 0.1),
particle_type='smoke',
properties=properties
)
if self.particles[new_x][new_y-1] is None:
self.particles[new_x][new_y-1] = new_smoke
new_active_particles.add((new_x, new_y-1))
# Dissipation chance
if random.random() < 0.02:
continue
continue
# Air handling - particles can pass through
if particle.particle_type == 'air':
continue
# Handle phase transitions
self.handle_phase_transitions(particle, x, y)
# Calculate forces
fx, fy = self.calculate_forces(particle, x, y)
# handle gas 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)
self.particles[x][y] = None
self.active_particles.discard((x, y))
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))
continue
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
# Update position for non-liquid particles
new_x = int(x + particle.velocity[0] * dt)
new_y = int(y + particle.velocity[1] * dt)
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
else:
new_active_particles.add((x, y))
self.active_particles = new_active_particles
def clear_particles_circle(self, center_x, center_y):
"""Clear particles in a circle around the given point based on brush size"""
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
grid_x = (center_x + dx * self.particle_size) // self.particle_size
grid_y = (center_y + dy * self.particle_size) // self.particle_size
if 0 <= grid_x < self.width and 0 <= grid_y < self.height:
if self.particles[grid_x][grid_y]:
self.particles[grid_x][grid_y] = None
self.active_particles.discard((grid_x, grid_y))
self.remove_from_spatial_grid(grid_x, grid_y)
def mix_liquids(self, liquid1, liquid2):
"""Handle liquid mixing interactions"""
if liquid1.temperature != liquid2.temperature:
avg_temp = (liquid1.temperature + liquid2.temperature) / 2
liquid1.temperature = avg_temp
liquid2.temperature = avg_temp
liquid1.density = self.calculate_density(liquid1.temperature)
liquid2.density = self.calculate_density(liquid2.temperature)
liquid1.viscosity = self.calculate_viscosity(liquid1.temperature)
liquid2.viscosity = self.calculate_viscosity(liquid2.temperature)
liquid1.color = self.calculate_color(liquid1.temperature)
liquid2.color = self.calculate_color(liquid2.temperature)
def simulate_step(self, dt):
"""Run a single step of the simulation"""
# Update particle positions and physics
self.apply_gravity(dt)
self.apply_physics(dt)
# Handle state changes and interactions
self.handle_temperature(dt)
self.handle_particle_interactions(dt)
self.burning()
self.spread_fire()
# Update spatial grid
self.update_spatial_grid()

11458
simulation_core.c Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

35
simulation_core.pyx Normal file
View File

@ -0,0 +1,35 @@
# simulation_core.pyx
cimport cython
from libc.math cimport sqrt
cdef class CParticle:
cdef float x, y, vx, vy, mass, gravity
def __init__(self, float x, float y, float vx, float vy, float mass, float gravity):
self.x = x
self.y = y
self.vx = vx
self.vy = vy
self.mass = mass
self.gravity = gravity
cpdef void apply_gravity(self, float dt):
self.vy += self.gravity * dt
self.y += self.vy * dt
self.x += self.vx * dt
cdef class SimulationCore:
cdef list particles
def __init__(self):
self.particles = []
cpdef void add_particle(self, CParticle particle):
self.particles.append(particle)
cpdef void update(self, float dt):
cdef CParticle particle
for particle in self.particles:
particle.apply_gravity(dt)

338
testcode.py Normal file
View File

@ -0,0 +1,338 @@
#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"""