/
Simulation.js
272 lines (231 loc) · 7.27 KB
/
Simulation.js
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
// @flow
import Matter from 'matter-js';
import { Point, Pose, Robot } from '.';
import * as SimulationSchema from '../../SimulatorEditor/SimulationSchema';
type ExternalSensorHandler = (
eventName: 'collisionStart' | 'collisionEnd',
sensor: Matter.Body | Matter.Composite,
other: Matter.Body | Matter.Composite,
) => void | Promise<void>;
function setInitialPose(body: Matter.Body, pose: Pose | void) {
if (!body.plugin.hedgehog) body.plugin.hedgehog = {};
body.plugin.hedgehog.initialPose = pose ?? { ...body.position, angle: body.angle };
}
/**
* Manages a robot simulation.
* The simulation can contain multiple robots, and objects representing the environment.
* This class is responsible for managing the Matter.js simulation lifecycle
* and triggering robot behavior (accelerating the robots, setting values for their sensors).
*/
export default class Simulation {
world: Matter.World;
engine: Matter.Engine;
runner: Matter.Runner;
render: Matter.Render | null = null;
bounds: { min: Point, max: Point } | null = null;
// special bodies for simulation logic
robots: Map<string, Robot> = new Map();
sensorsCache: Set<Matter.Body> = new Set();
// timers waiting for simulated time to pass
timers: [number, () => void][] = [];
externalSensorHandlers: ExternalSensorHandler[] = [];
constructor() {
this.world = Matter.World.create({
gravity: { x: 0, y: 0 },
});
this.engine = Matter.Engine.create({ world: this.world });
this.runner = Matter.Runner.create();
// robot update on simulation tick
Matter.Events.on(this.runner, 'beforeUpdate', ({ timestamp }) => {
for (const robot of this.robots.values()) {
robot.beforeUpdate();
}
this.timers = this.timers.filter(([deadline, resolve]) => {
// keep timers that have not yet expired
if (deadline > timestamp) return true;
// process the timer and remove
resolve();
return false;
});
});
function extractBodyForSDK({
id,
label,
position,
speed,
velocity,
angle,
angularSpeed,
angularVelocity,
bounds,
}: Matter.Body) {
return {
id,
label,
position,
speed,
velocity,
angle,
angularSpeed,
angularVelocity,
bounds,
};
}
// check for line detection
const collisionHandler = ({ name, pairs }) => {
for (const { bodyA, bodyB } of pairs) {
for (const handler of this.externalSensorHandlers) {
handler(name, extractBodyForSDK(bodyA), extractBodyForSDK(bodyB));
}
let sensor = null;
let other = null;
if (this.sensorsCache.has(bodyA)) {
sensor = bodyA;
other = bodyB;
} else if (this.sensorsCache.has(bodyB)) {
sensor = bodyB;
other = bodyA;
} else {
continue;
}
sensor.plugin.hedgehog.sensor.handleCollision(name, other);
}
};
Matter.Events.on(this.engine, 'collisionStart', collisionHandler);
Matter.Events.on(this.engine, 'collisionEnd', collisionHandler);
}
async sleep(millis: number): Promise<void> {
return /* await */ new Promise(resolve => {
this.timers.push([this.engine.timing.timestamp + millis, resolve]);
});
}
jsonInit(schema: SimulationSchema.SimulatorJson) {
this.clear(false);
{
const {
center: { x, y },
// eslint-disable-next-line no-shadow
width,
// eslint-disable-next-line no-shadow
height,
} = schema.simulation;
this.lookAt({
min: { x: x - width / 2, y: y - height / 2 },
max: { x: x + width / 2, y: y + height / 2 },
});
}
for (const object of schema.objects) {
switch (object.type) {
case 'rectangle': {
// eslint-disable-next-line no-shadow
const { type: _type, width, height, ...options } = object;
const body = Matter.Bodies.rectangle(0, 0, width, height, options);
setInitialPose(body);
this.add([body]);
break;
}
case 'circle': {
const { type: _type, radius, ...options } = object;
const body = Matter.Bodies.circle(0, 0, radius, options);
setInitialPose(body);
this.add([body]);
break;
}
case 'robot': {
const {
name,
position: { x, y },
angle,
// color,
} = object;
const robot = new Robot();
const pose = { x, y, angle };
robot.setPose(pose);
setInitialPose(robot.body);
// TODO color
this.addRobot(name, robot);
break;
}
default:
console.warn('unknown simulation object:', object);
}
}
this.updateSensorCache();
}
mount(canvas: HTMLCanvasElement) {
this.unmount();
const dimension = {};
if (this.bounds !== null) {
dimension.width = this.bounds.max.x - this.bounds.min.x;
dimension.height = this.bounds.max.y - this.bounds.min.y;
}
// TODO creating a Render instance with a running Engine will error,
// as the Engine's internal state is recursive.
// mount() can therefore not be called after initially starting the simulation
this.render = Matter.Render.create({
canvas,
engine: this.engine,
options: { ...dimension, wireframes: false, background: '#eeeeee' },
});
if (this.bounds !== null) Matter.Render.lookAt(this.render, this.bounds);
}
unmount() {
if (this.render !== null) this.stopRender();
this.render = null;
}
startMatter() {
Matter.Runner.run(this.runner, this.engine);
}
startRender() {
Matter.Render.run(this.render);
}
stopMatter() {
Matter.Runner.stop(this.runner);
}
stopRender() {
Matter.Render.stop(this.render);
}
lookAt(bounds: { min: Point, max: Point }) {
this.bounds = bounds;
if (this.render !== null) Matter.Render.lookAt(this.render, bounds);
}
add(bodies: (Matter.Body | Matter.Composite)[]) {
Matter.World.add(this.world, bodies);
}
addSensorHandler(handler: ExternalSensorHandler) {
this.externalSensorHandlers.push(handler);
}
addRobot(name: string, robot: Robot) {
this.robots.set(name, robot);
this.add(robot.bodies);
}
// this method has to be called after adding one or more robots to the
// simulation, before using any new robot's sensors.
updateSensorCache() {
this.sensorsCache.clear();
for (const robot of this.robots.values()) {
for (const sensor of robot.collisionSensors) {
this.sensorsCache.add(sensor.sensorBody);
}
}
}
clear(keepStatic: boolean) {
Matter.Composite.clear(this.world, keepStatic);
this.robots.clear();
this.updateSensorCache();
}
reset() {
for (const composite of [
...Matter.Composite.allComposites(this.world),
...Matter.Composite.allBodies(this.world),
]) {
if (composite.plugin.hedgehog?.initialPose) {
const { x, y, angle } = composite.plugin.hedgehog.initialPose;
Matter.Body.setPosition(composite, { x, y });
Matter.Body.setAngle(composite, angle);
Matter.Body.setVelocity(composite, { x: 0, y: 0 });
Matter.Body.setAngularVelocity(composite, 0);
}
}
}
}