Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
173 lines (150 loc) · 6.61 KB
/
Copy pathapp.py
File metadata and controls
173 lines (150 loc) · 6.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
"""Application — top-level orchestrator: window, main loop, world, input."""
from __future__ import annotations
from dataclasses import dataclass
import pygame
from config import AppConfig
from entities.factory import BodyFactory
from physics.bounds import Bounds
from physics.broad_phase import UniformGrid
from physics.particles import ParticleSystem
from physics.vector import Vector2
from physics.world import GravityMode, World
from rendering.renderer import Renderer
from ui.fonts import FontCache
from ui.hud import Hud
from ui.interaction import InteractionController
from utils.clock import FrameClock
# Slow-motion factor when toggled with Tab. 0.25 = quarter speed.
_SLOW_MO_FACTOR = 0.25
# Penetration threshold (px) above which we treat a contact as a fresh
# impact and emit a particle burst. Resting / settled contacts have
# penetration near the resolver's positional slop (~0.05 px), so anything
# above ~1 px is a real collision.
_IMPACT_PENETRATION_THRESHOLD = 1.0
@dataclass(slots=True)
class SimulationState:
"""Mutable simulation control state owned by Application."""
paused: bool = False
time_scale: float = 1.0
gravity_enabled: bool = True
class Application:
def __init__(self, config: AppConfig) -> None:
self._config = config
self._running = False
pygame.init()
pygame.display.set_caption(config.window.title)
self._surface = self._create_surface()
self._clock = FrameClock(config.simulation.target_fps)
self._fonts = FontCache()
self._world = World(
gravity=config.physics.gravity,
linear_damping=config.physics.linear_damping,
max_dt=config.physics.max_dt,
collision_iterations=config.physics.collision_iterations,
substeps=config.physics.substeps,
grid=UniformGrid(cell_size=config.physics.grid_cell_size),
bounds=Bounds.from_size(*self._surface.get_size()),
)
self._renderer = Renderer(self._surface, config.theme)
self._hud = Hud(config.theme, self._fonts)
self._factory = BodyFactory()
self._interaction = InteractionController(self._world, self._factory)
self._particles = ParticleSystem()
self._state = SimulationState()
# Cached gravity for the G toggle so we can restore the original value.
self._configured_gravity = config.physics.gravity
def run(self) -> None:
self._running = True
try:
while self._running:
dt = self._clock.tick()
self._handle_events()
self._update(dt)
self._render()
finally:
pygame.quit()
# --------------------------------------------------------------- setup
def _create_surface(self) -> pygame.Surface:
flags = pygame.RESIZABLE if self._config.window.resizable else 0
size = (self._config.window.width, self._config.window.height)
return pygame.display.set_mode(size, flags)
# --------------------------------------------------------------- events
def _handle_events(self) -> None:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self._running = False
elif event.type == pygame.KEYDOWN:
self._on_keydown(event.key)
elif event.type == pygame.VIDEORESIZE:
self._on_resize(event.w, event.h)
elif event.type == pygame.MOUSEBUTTONDOWN:
self._interaction.on_mouse_down(event.button, _to_vec(event.pos))
elif event.type == pygame.MOUSEBUTTONUP:
self._interaction.on_mouse_up(event.button, _to_vec(event.pos))
def _on_keydown(self, key: int) -> None:
if key == pygame.K_ESCAPE:
self._running = False
elif key == pygame.K_v:
self._renderer.settings.show_vectors = not self._renderer.settings.show_vectors
elif key == pygame.K_e:
self._renderer.settings.show_education = not self._renderer.settings.show_education
elif key == pygame.K_t:
settings = self._renderer.settings
settings.show_trails = not settings.show_trails
self._renderer.trails.enabled = settings.show_trails
if not settings.show_trails:
self._renderer.trails.clear()
elif key == pygame.K_SPACE:
self._state.paused = not self._state.paused
elif key == pygame.K_r:
self._world.clear()
self._interaction.reset()
self._renderer.trails.clear()
self._particles.clear()
elif key == pygame.K_g:
self._state.gravity_enabled = not self._state.gravity_enabled
self._world.gravity = (
self._configured_gravity if self._state.gravity_enabled else Vector2.zero()
)
elif key == pygame.K_TAB:
self._state.time_scale = (
_SLOW_MO_FACTOR if self._state.time_scale == 1.0 else 1.0
)
elif key == pygame.K_p:
self._interaction.spawn_pendulum(_to_vec(pygame.mouse.get_pos()))
elif key == pygame.K_o:
self._world.gravity_mode = (
GravityMode.PLANET if self._world.gravity_mode == GravityMode.LINEAR
else GravityMode.LINEAR
)
def _on_resize(self, width: int, height: int) -> None:
w = max(width, self._config.window.min_width)
h = max(height, self._config.window.min_height)
self._surface = pygame.display.set_mode((w, h), pygame.RESIZABLE)
self._renderer.attach_surface(self._surface)
self._world.bounds = Bounds.from_size(w, h)
# --------------------------------------------------------------- frame
def _update(self, dt: float) -> None:
self._interaction.update(_to_vec(pygame.mouse.get_pos()))
if self._state.paused:
return
scaled_dt = dt * self._state.time_scale
self._world.step(scaled_dt)
for contact in self._world.last_contacts:
if contact.penetration >= _IMPACT_PENETRATION_THRESHOLD:
self._particles.emit_burst(contact.point)
self._particles.step(scaled_dt)
def _render(self) -> None:
self._renderer.begin_frame()
self._renderer.draw_world(self._world)
self._renderer.draw_particles(self._particles.particles)
self._hud.draw(
self._surface,
self._clock,
self._world,
self._renderer.settings,
self._state,
)
pygame.display.flip()
def _to_vec(pos: tuple[int, int]) -> Vector2:
return Vector2(float(pos[0]), float(pos[1]))