-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo.py
352 lines (262 loc) · 9.41 KB
/
demo.py
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import numpy as np
import pygame
from arbiter import Arbiter
from body import Body, DTYPE
from joint import Joint
from world import World
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
PPM = 10.0
SCREEN_OFFSET_X = int(SCREEN_WIDTH / 2 / PPM)
# SCREEN_OFFSET_Y = int(SCREEN_HEIGHT / 2 / PPM)
# SCREEN_OFFSET_X = 0.0
SCREEN_OFFSET_Y = 0.0
TARGET_FPS = 30
TIMESTEP = 1.0 / TARGET_FPS
IMPULSE_ITERATIONS = 10
GRAVITY = np.array([0.0, -10.0], dtype=DTYPE)
def to_screen(vertices):
return [(int((SCREEN_OFFSET_X + v[0]) * PPM),
SCREEN_HEIGHT - int((SCREEN_OFFSET_Y + v[1]) * PPM))
for v in vertices]
# def to_world(vertices):
# return [(float(v[0]) / PPM - SCREEN_OFFSET_X,
# (SCREEN_OFFSET_Y - float(v[1]) / PPM))
# for v in vertices]
class Bomb(Body):
pass
def draw_test(x: int, y: int, text: str) -> None:
pass # TODO
def draw_body(screen: pygame.Surface, body: Body) -> None:
R = body.rotation_matrix()
x = body.position
h = 0.5 * body.width
v1 = x + R @ -h
v2 = x + R @ np.array([h[0], -h[1]])
v3 = x + R @ h
v4 = x + R @ np.array([-h[0], h[1]])
vertices = to_screen((v1, v2, v3, v4))
# print(sum((v1, v2, v3, v4)) / 4, '->', sum(np.array(vertices)) / 4)
if isinstance(body, Bomb):
color = (102, 230, 102)
else:
color = (204, 204, 230)
fill_color = (102, 102, 115)
pygame.draw.polygon(screen, fill_color, vertices, 0)
pygame.draw.polygon(screen, color, vertices, 1)
def draw_joint(screen: pygame.Surface, joint: Joint) -> None:
b1 = joint.body_1
b2 = joint.body_2
R1 = b1.rotation_matrix()
R2 = b2.rotation_matrix()
x1 = b1.position
p1 = x1 + R1 @ joint.local_anchor_1
x1, p1 = to_screen((x1, p1))
x2 = b2.position
p2 = x2 + R2 @ joint.local_anchor_2
x2, p2 = to_screen((x2, p2))
color = (128, 128, 204)
pygame.draw.line(screen, color, x1, p1)
pygame.draw.line(screen, color, p1, x2)
pygame.draw.line(screen, color, x2, p2)
def draw_arbiter(screen: pygame.Surface, arbiter: Arbiter) -> None:
color = (255, 0, 0)
for c in arbiter.contacts:
p = to_screen([c.position])[0]
pygame.draw.circle(screen, color, p, 3.0, 0)
def draw_world(screen: pygame.Surface, world: World) -> None:
for body in world.bodies:
draw_body(screen, body)
for joint in world.joints:
draw_joint(screen, joint)
for arbiter in world.arbiters.values():
draw_arbiter(screen, arbiter)
def launch_bomb(world: World) -> None:
# remove previous bomb
for i, b in enumerate(world.bodies):
if isinstance(b, Bomb):
del world.bodies[i]
world.arbiters = {key: arb for key, arb in world.arbiters.items()
if not isinstance(arb.body_1, Bomb) and not isinstance(arb.body_2, Bomb)}
bomb = Bomb([3.0, 3.0], 50.0)
bomb.friction = 0.2
bomb.position = np.array([np.random.rand() * 100 - 50, 50.0])
bomb.rotation = np.random.rand() * 3 - 1.5
bomb.velocity = -1.5 * bomb.position
bomb.angular_velocity = np.random.rand() * 40 - 20
world.add_body(bomb)
def main() -> None:
"""
Main loop.
Updates the world and then the screen.
"""
world = demo_1()
cur_demo = 1
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
font = pygame.font.Font(None, 16)
running = True
clock = pygame.time.Clock()
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and
event.key == pygame.K_ESCAPE):
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
launch_bomb(world)
elif event.key == pygame.K_1:
world = demo_1()
cur_demo = 1
elif event.key == pygame.K_2:
world = demo_2()
cur_demo = 2
elif event.key == pygame.K_3:
world = demo_3()
cur_demo = 3
elif event.key == pygame.K_4:
world = demo_4()
cur_demo = 4
# elif event.key == pygame.K_5:
# world = demo_5()
# cur_demo = 5
elif event.key == pygame.K_6:
world = demo_6()
cur_demo = 6
elif event.key == pygame.K_7:
world = demo_7()
cur_demo = 7
# elif event.key == pygame.K_8:
# world = demo_8()
# elif event.key == pygame.K_9:
# world = demo_9()
screen.fill((0, 0, 0))
text_line = 10
# display fps
fps = clock.get_fps()
fps_str = f'{fps:.1f} FPS'
fps_render = font.render(fps_str, True, pygame.Color('coral'))
screen.blit(fps_render, (10, text_line))
text_line += 15
# print(fps_str, end='\r')
# display information
info_str = f'Press keys 1-4 for demos. Current demo: {cur_demo}.'
info_render = font.render(info_str, True, pygame.Color('coral'))
screen.blit(info_render, (10, text_line))
text_line += 15
info_str = f'Press SPACE to launch the bomb.'
info_render = font.render(info_str, True, pygame.Color('coral'))
screen.blit(info_render, (10, text_line))
# step the world
world.step(TIMESTEP)
draw_world(screen, world)
pygame.display.flip()
clock.tick(TARGET_FPS)
def demo_1() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
body_1 = Body([100.0, 20.0])
body_1.position = np.array([0.0, 0.5 * body_1.width[1]])
world.add_body(body_1)
body_2 = Body([5.0, 5.0], 200.0)
body_2.position = np.array([0.0, 40.0])
world.add_body(body_2)
return world
def demo_2() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
body_1 = Body([100.0, 10.0])
body_1.position = np.array([0.0, 0.5 * body_1.width[1]])
body_1.friction = 0.2
body_1.rotation = 0.0
world.add_body(body_1)
body_2 = Body([5.0, 5.0], 100.0)
body_2.position = np.array([45.0, 60.0])
body_2.friction = 0.2
body_2.rotation = 0.0
world.add_body(body_2)
joint = Joint(body_1, body_2, body_2.position * [0, 1])
world.add_joint(joint)
return world
def demo_3() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
body_1 = Body([100.0, 1.0])
body_1.position = np.array([0.0, 20.0])
body_1.rotation = -0.25
world.add_body(body_1)
frictions = [0.75, 0.5, 0.35, 0.1, 0.0]
for i, fric in enumerate(frictions):
body = Body([3.0, 3.0], 25.0)
body.friction = fric
body.position = np.array([-45.0 + 10.0 * i, 40.0])
world.add_body(body)
return world
def demo_4() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
body_1 = Body([100.0, 10.0])
body_1.position = np.array([0.0, 0.5 * body_1.width[1]])
world.add_body(body_1)
for i in range(8):
body = Body([3.0, 3.0], 1.0)
body.friction = 0.2
x = np.random.rand() - 0.5
body.position = np.array([x, 12.0 + 3.5 * i])
world.add_body(body)
return world
def demo_5() -> World:
pass
def demo_6() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
Ground = Body([100.0, 10.0])
Ground.position = np.array([0.0, 0.5 * Ground.width[1]])
world.add_body(Ground)
teeter = Body([60.0, 1.25], 100.0)
teeter.position = np.array([0.0, 15.0])
world.add_body(teeter)
small = Body([2.5, 2.5], 25.0)
small.position = np.array([-27.5, 20.0])
world.add_body(small)
big = Body([5.0, 5.0], 100.0)
big.position = np.array([27.5, 85.0])
world.add_body(big)
j = Joint(Ground, teeter, teeter.position)
world.add_joint(j)
return world
def demo_7() -> World:
world = World(gravity=GRAVITY, iterations=IMPULSE_ITERATIONS)
Ground = Body([100.0, 10.0])
Ground.position = np.array([0.0, 0.5 * Ground.width[1]])
world.add_body(Ground)
PLANK_COUNT = 15
PLANK_MASS = 50.0
PLANK_WIDTH = 5.0
GAP = 1.25
period = PLANK_WIDTH+GAP
deck_length = period*PLANK_COUNT - GAP
deck_startx = -deck_length/2
joint_startx = -deck_length/2 - GAP/2
planks = []
for i in range(PLANK_COUNT):
p = Body([PLANK_WIDTH, 0.25*5], PLANK_MASS)
p.position = np.array([deck_startx+PLANK_WIDTH/2+period*i, 25.0])
planks.append(p)
world.add_body(p)
# Joint Tuning
FREQUENCY_HERTZ = 2.0
frequency_radians = 2.0*np.pi*FREQUENCY_HERTZ
DAMPING_RATIO = 0.7
damping_coeffcient = 2.0*PLANK_MASS*DAMPING_RATIO*frequency_radians
stiffness = PLANK_MASS*frequency_radians**2
softness = 1/(damping_coeffcient+TIMESTEP*stiffness)
bias_factor = TIMESTEP*stiffness/(damping_coeffcient+TIMESTEP*stiffness)
limbs = [Ground]+planks+[Ground]
for i,(limb1,limb2) in enumerate(zip(limbs,limbs[1:])):
j = Joint(limb1, limb2, np.array([joint_startx+period*i, 25.0]))
j.softness = softness
j.bias_factor = bias_factor
world.add_joint(j)
return world
def demo_8() -> World:
pass
def demo_9() -> World:
pass
if __name__ == '__main__':
main()