@margoengine/physics2d 0.1.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +566 -521
- package/dist/body.d.ts +19 -7
- package/dist/composites.d.ts +161 -0
- package/dist/composites.js +183 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +446 -101
- package/dist/joint.d.ts +129 -2
- package/dist/{kernel-D6zM0ozJ.js → kernel-DkjP8dvA.js} +1 -1
- package/dist/kernel.d.ts +5 -0
- package/dist/physics.d.ts +68 -0
- package/dist/physics2d-scalar.wasm +0 -0
- package/dist/physics2d.wasm +0 -0
- package/dist/shapes.d.ts +7 -0
- package/package.json +64 -60
package/README.md
CHANGED
|
@@ -1,521 +1,566 @@
|
|
|
1
|
-
# @margoengine/physics2d
|
|
2
|
-
|
|
3
|
-
Import `margoengine/physics2d` from the `margoengine` package, or `@margoengine/physics2d` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
-
|
|
5
|
-
2D rigid-body physics for Margo Engine on its own 2D kernel (Rust compiled to Wasm with SIMD): a fixed-step engine plugin with interpolation, bodies that drive sprites, box, circle, capsule, polygon (convex or concave) and polyline colliders, joints, scene queries, collision and contact force events, sensors, collision groups, continuous collision, a character controller and tile map colliders in one call. Nothing else to install: the kernel's WebAssembly is a file of this package, `dist/physics2d.wasm`.
|
|
6
|
-
|
|
7
|
-
World units are sprite pixels, y points down and angles are radians, clockwise on screen. `pixelsPerMeter` (default 32) maps them to the kernel's metres, so a 16 pixel tile is half a metre. Mass, density, force and impulse use kernel units (kilograms, metres, seconds).
|
|
8
|
-
|
|
9
|
-
```ts
|
|
10
|
-
import {Physics2D} from 'margoengine/physics2d';
|
|
11
|
-
|
|
12
|
-
await Physics2D.load();
|
|
13
|
-
const physics = new Physics2D(null); // or new Physics2D(engine, ...) to step with the engine
|
|
14
|
-
|
|
15
|
-
// A tile map: tiles with collision shapes (or a `solid: true` property) become one fixed body.
|
|
16
|
-
physics.addTileMap({
|
|
17
|
-
tileWidth: 16, tileHeight: 16,
|
|
18
|
-
tilesets: [{firstGid: 1, tileCount: 1, tileWidth: 16, tileHeight: 16, tiles: [{id: 0, properties: {solid: true}}]}],
|
|
19
|
-
layers: [{type: 'tile', name: 'ground', width: 8, height: 4, data: new Uint32Array(32).fill(1, 24)}],
|
|
20
|
-
});
|
|
21
|
-
|
|
22
|
-
// A body that drives a sprite: each frame the interpolated pose is written to sprite.x, sprite.y and sprite.rotation.
|
|
23
|
-
const sprite = {x: 64, y: 0, rotation: 0};
|
|
24
|
-
const crate = physics.addBody(sprite, {colliders: {shape: 'box', width: 16, height: 16, restitution: 0.2}});
|
|
25
|
-
physics.on('contactstart', ({bodyA, bodyB}) => {});
|
|
26
|
-
physics.update(1 / 60); // or let the engine call it every frame
|
|
27
|
-
crate.applyImpulse([0, -2]);
|
|
28
|
-
physics.raycast([64, 0], [0, 1])?.point;
|
|
29
|
-
|
|
30
|
-
// A hinge with limits, and a character on a kinematic body.
|
|
31
|
-
const pole = physics.addBody(null, {type: 'fixed', position: [32, 8], colliders: []});
|
|
32
|
-
physics.addJoint(pole, crate, {type: 'revolute', anchorB: [-8, 0], limits: [-1, 1]});
|
|
33
|
-
const hero = physics.addBody({x: 20, y: 40, rotation: 0}, {type: 'kinematicPosition', colliders: {shape: 'capsule', radius: 5, height: 20}});
|
|
34
|
-
const controller = physics.createCharacterController(hero, {snapToGround: 2});
|
|
35
|
-
physics.on('beforestep', dt => controller.move([60 * dt, 200 * dt]));
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
It exports `Physics2D`, `Body2D`, `Joint2D`, `CharacterController2D`, `interactionGroups` and `tileMapColliders`, the collider list `addTileMap` builds. `addTileMap` accepts a `TileMapData` from `@margoengine/tilemap`, or any object of the `TileMapSource` shape. Whole-cell solid tiles merge into outline loops so bodies slide across tile seams without catching; other collision shapes (rectangles, ellipses, polygons, polylines), tile flips and layer offsets are kept. Very fast bodies on a tile map need `ccd: true`, because outlines have no thickness.
|
|
39
|
-
|
|
40
|
-
**One load per app.** `await Physics2D.load()` compiles the kernel, then `new Physics2D(engine)` stays synchronous. Later calls resolve at once, calls during a load share it, a failed load is tried again by the next call, and `{signal}` stops one caller's wait; when no other call waits on the load, it also cancels the download. The loader is a dynamic import and the Wasm a separate file (`dist/physics2d.wasm`) that bundlers emit as an asset and the browser compiles while it downloads when served as `application/wasm`. `{wasm}` points at another copy: a URL (your server or a CDN), a fetched `Response`, its bytes or a compiled `WebAssembly.Module`. It must be the bundled build; any other Wasm rejects with a `MargoError` of code `failed`, as does a missing file, and nothing is loaded. The package carries two builds of the kernel, each a file of its own: `dist/physics2d.wasm` with Wasm SIMD and `dist/physics2d-scalar.wasm` for engines that cannot compile it. `Physics2D.load()` probes the engine and fetches the one it can run (`load({simd: false})` forces the scalar one, to test it; `wasm` still names any file yourself, and a page then loads whichever you name). They are one kernel and step a world to the same bits, which a test holds on the hash of a 600-step world's snapshot; the scalar build takes its square roots from integer arithmetic that matches the hardware instruction bit for bit, and is larger and slower, never different.
|
|
41
|
-
|
|
42
|
-
```ts
|
|
43
|
-
import {Physics2D} from '@margoengine/physics2d';
|
|
44
|
-
|
|
45
|
-
// The package's own copy found through Node's resolver; in a page, pass the URL your server or CDN serves it from.
|
|
46
|
-
const wasm = new URL('physics2d.wasm', import.meta.resolve('@margoengine/physics2d'));
|
|
47
|
-
await Physics2D.load({wasm, signal: AbortSignal.timeout(30_000)});
|
|
48
|
-
const physics = new Physics2D(null, {gravity: [0, 320]});
|
|
49
|
-
physics.dispose();
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
`body.maxAngularSpeed` caps a body's spin (default 0, none: Rapier's default cap, which its `allowFastRotation` lifts, is not needed because a fast spinner with `ccd` is swept along its turn). `physics.setSolver({ maxCcdSubsteps: n })` lets a `ccd` body keep going after an impact inside one step, up to `n` impacts (default 1: it stops where it touches; 0 turns continuous collision off). `body.additionalSolverIterations = n` gives the body's island `n` more substeps each step (Rapier's `additional_solver_iterations`: solved as a world at that substep count would solve it, the other islands untouched). `body.additionalPgsIterations = n` gives the body's island `n` more solver passes each substep over its own contacts and joints (Rapier's `additional_pgs_iterations`; the island runs the most any of its awake bodies asks for, no other island is touched, and with none asking the step is unchanged). `body.enabled = false` takes a body out of the simulation (it keeps its pose and velocity, touches nothing, no query finds it, its joints rest) and `true` puts it back. `body.setAdditionalMassProperties(mass, centre, inertia)` adds a solid to what the colliders weigh by the parallel axis theorem (the older `additionalMass` adds in proportion), and `raycastAll(origin, direction)` lists every collider a ray meets, nearest first, and a filter's `excludeCollider` leaves one collider out where `exclude` leaves a body. Queries (`raycast`, `overlapPoint`, `overlapShape`, `castShape`) see every collider added or moved since the last step, and a `teleport` or `moveTo` at once. `castShape` and `overlapShape` take a box, circle, capsule, segment or a convex polygon of at most 8 points.
|
|
53
|
-
|
|
54
|
-
Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0. The kernel is Margo's own, written from papers (`docs/clean-room.md`); it holds no third-party code.
|
|
55
|
-
|
|
56
|
-
Build and unit tests: npm test --workspace @margoengine/physics2d
|
|
57
|
-
|
|
58
|
-
## Parity with Rapier 2D
|
|
59
|
-
|
|
60
|
-
`Physics2D` runs on Margo's own 2D kernel (`kernel/`, Rust to Wasm); it no longer uses Rapier. The capabilities below are listed from Rapier 2D's public user guide (rapier.rs/docs), never from its source. Status: **full** (kernel, facade and a test), **partial** (what is missing is named), **missing**. Docs: [limits](../../docs/limits.md), [known bugs](../../docs/known-bugs.md).
|
|
61
|
-
|
|
62
|
-
| Area | Rapier 2D capability | Where in Margo | Status |
|
|
63
|
-
| --- | --- | --- | --- |
|
|
64
|
-
| Shapes | ball, cuboid, capsule, segment | `box`, `circle`, `capsule`, `segment` colliders | full |
|
|
65
|
-
| Shapes | convex polygon, convex decomposition of concave or large input | `polygon` (convex hull to 8 corners; concave or larger split by ear clipping and Hertel-Mehlhorn) | full |
|
|
66
|
-
| Shapes | polyline | `polyline` (chains with ghost vertices: bodies slide over the joins) | full |
|
|
67
|
-
| Shapes | triangle, round (border radius) cuboid, triangle and convex polygon, trimesh with its flags | `triangle`, `borderRadius` on `box`, `polygon` and `triangle`, `trimesh` (triangles by index, `fixInternalEdges` and the clean-up flags) | full |
|
|
68
|
-
| Shapes | heightfield, halfspace, compound, voxels, shared shapes | `heightfield` (a smooth chain), `halfspace` (a polygon 200,000 units across), `compound` (parts with their own placement), `voxels` (merged outlines for contact, the cells themselves for queries); shape options are plain values, so one can be reused on any number of colliders | full, with the accepted differences in limits |
|
|
69
|
-
| Shapes | oriented (one-sided) polyline | `polyline` with `oneSided: true` | full |
|
|
70
|
-
| Collision | broad phase, narrow phase, manifolds, islands, sleeping | kernel box tree, SAT and clipping, SIMD solver | full |
|
|
71
|
-
| Collision | continuous collision detection | `ccd` against fixed, kinematic and dynamic bodies (a dynamic one it meets is put back to the same time) | full |
|
|
72
|
-
| Collision | soft CCD (a prediction distance per body) | `softCcd` (world units a body's contacts reach ahead) | full |
|
|
73
|
-
| Collision | sensors | `sensor: true` (senses fixed and kinematic bodies too) | full |
|
|
74
|
-
| Collision | collision groups, solver groups, active collision types | `collisionGroups`, `solverGroups`, `activeCollisionTypes` | full |
|
|
75
|
-
| Collision | collision events, contact force events | `contactstart`, `contactend`, `intersectionstart`, `intersectionend`, `contactforce` (`contactForceThreshold`) | full |
|
|
76
|
-
| Collision | physics hooks (filter and modify contact pairs, one-way platforms) | `physics.hooks = {filterPair, filterIntersection, modifyContact}` for colliders with `hooks` set (`filterPair` for a pair of solids, `filterIntersection` for a pair with a sensor in it; `collider.setActiveHooks` changes what a collider asks); `oneWay`, `friction`, `restitution`, `tangentVelocity` (conveyors), `solverActive` per contact | full |
|
|
77
|
-
| Queries | ray cast with normal (solid or not), every hit along a ray (`raycastAll`, nearest first), point, shape intersection, shape cast, project point, box intersection, filters | `raycast`, `overlapPoint`, `overlapShape`, `castShape`, `projectPoint`, `intersectionsWithBox`, `QueryFilter2D` | full |
|
|
78
|
-
| Queries | contact pairs of a collider, the contact between two colliders, intersection pairs of sensors | `contactPairs(collider)`, `contactPair(a, b)`, `intersectionPair(a, b)`, `intersectionPairsWith(collider)` | full |
|
|
79
|
-
| Bodies | dynamic, fixed, kinematic position, kinematic velocity | `type` | full |
|
|
80
|
-
| Bodies | damping, gravity scale, locked rotation, can sleep, dominance, body type changes | `BodyOptions2D`, the same names as setters on `Body2D`, `setType` | full |
|
|
81
|
-
| Bodies | forces, torques, impulses (at the centre or a point), forces at a point, resetting the torque or both, velocities, wake and sleep | `applyForce`, `applyForceAtPoint`, `applyTorque`, `applyImpulse`, `applyImpulseAtPoint`, `applyTorqueImpulse`, `resetForces`, `resetTorques`, and the velocity setters | full |
|
|
82
|
-
|
|
|
83
|
-
|
|
|
84
|
-
|
|
|
85
|
-
| Bodies |
|
|
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
|
-
physics.
|
|
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
|
-
import {
|
|
276
|
-
|
|
277
|
-
await Physics2D.load();
|
|
278
|
-
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
0.
|
|
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
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
const
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
const
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
[
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
1
|
+
# @margoengine/physics2d
|
|
2
|
+
|
|
3
|
+
Import `margoengine/physics2d` from the `margoengine` package, or `@margoengine/physics2d` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
|
|
4
|
+
|
|
5
|
+
2D rigid-body physics for Margo Engine on its own 2D kernel (Rust compiled to Wasm with SIMD): a fixed-step engine plugin with interpolation, bodies that drive sprites, box, circle, capsule, polygon (convex or concave) and polyline colliders, joints, scene queries, collision and contact force events, sensors, collision groups, continuous collision, a character controller and tile map colliders in one call. Nothing else to install: the kernel's WebAssembly is a file of this package, `dist/physics2d.wasm`.
|
|
6
|
+
|
|
7
|
+
World units are sprite pixels, y points down and angles are radians, clockwise on screen. `pixelsPerMeter` (default 32) maps them to the kernel's metres, so a 16 pixel tile is half a metre. Mass, density, force and impulse use kernel units (kilograms, metres, seconds).
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import {Physics2D} from 'margoengine/physics2d';
|
|
11
|
+
|
|
12
|
+
await Physics2D.load();
|
|
13
|
+
const physics = new Physics2D(null); // or new Physics2D(engine, ...) to step with the engine
|
|
14
|
+
|
|
15
|
+
// A tile map: tiles with collision shapes (or a `solid: true` property) become one fixed body.
|
|
16
|
+
physics.addTileMap({
|
|
17
|
+
tileWidth: 16, tileHeight: 16,
|
|
18
|
+
tilesets: [{firstGid: 1, tileCount: 1, tileWidth: 16, tileHeight: 16, tiles: [{id: 0, properties: {solid: true}}]}],
|
|
19
|
+
layers: [{type: 'tile', name: 'ground', width: 8, height: 4, data: new Uint32Array(32).fill(1, 24)}],
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
// A body that drives a sprite: each frame the interpolated pose is written to sprite.x, sprite.y and sprite.rotation.
|
|
23
|
+
const sprite = {x: 64, y: 0, rotation: 0};
|
|
24
|
+
const crate = physics.addBody(sprite, {colliders: {shape: 'box', width: 16, height: 16, restitution: 0.2}});
|
|
25
|
+
physics.on('contactstart', ({bodyA, bodyB}) => {});
|
|
26
|
+
physics.update(1 / 60); // or let the engine call it every frame
|
|
27
|
+
crate.applyImpulse([0, -2]);
|
|
28
|
+
physics.raycast([64, 0], [0, 1])?.point;
|
|
29
|
+
|
|
30
|
+
// A hinge with limits, and a character on a kinematic body.
|
|
31
|
+
const pole = physics.addBody(null, {type: 'fixed', position: [32, 8], colliders: []});
|
|
32
|
+
physics.addJoint(pole, crate, {type: 'revolute', anchorB: [-8, 0], limits: [-1, 1]});
|
|
33
|
+
const hero = physics.addBody({x: 20, y: 40, rotation: 0}, {type: 'kinematicPosition', colliders: {shape: 'capsule', radius: 5, height: 20}});
|
|
34
|
+
const controller = physics.createCharacterController(hero, {snapToGround: 2});
|
|
35
|
+
physics.on('beforestep', dt => controller.move([60 * dt, 200 * dt]));
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
It exports `Physics2D`, `Body2D`, `Joint2D`, `CharacterController2D`, `interactionGroups` and `tileMapColliders`, the collider list `addTileMap` builds. `addTileMap` accepts a `TileMapData` from `@margoengine/tilemap`, or any object of the `TileMapSource` shape. Whole-cell solid tiles merge into outline loops so bodies slide across tile seams without catching; other collision shapes (rectangles, ellipses, polygons, polylines), tile flips and layer offsets are kept. Very fast bodies on a tile map need `ccd: true`, because outlines have no thickness.
|
|
39
|
+
|
|
40
|
+
**One load per app.** `await Physics2D.load()` compiles the kernel, then `new Physics2D(engine)` stays synchronous. Later calls resolve at once, calls during a load share it, a failed load is tried again by the next call, and `{signal}` stops one caller's wait; when no other call waits on the load, it also cancels the download. The loader is a dynamic import and the Wasm a separate file (`dist/physics2d.wasm`) that bundlers emit as an asset and the browser compiles while it downloads when served as `application/wasm`. `{wasm}` points at another copy: a URL (your server or a CDN), a fetched `Response`, its bytes or a compiled `WebAssembly.Module`. It must be the bundled build; any other Wasm rejects with a `MargoError` of code `failed`, as does a missing file, and nothing is loaded. The package carries two builds of the kernel, each a file of its own: `dist/physics2d.wasm` with Wasm SIMD and `dist/physics2d-scalar.wasm` for engines that cannot compile it. `Physics2D.load()` probes the engine and fetches the one it can run (`load({simd: false})` forces the scalar one, to test it; `wasm` still names any file yourself, and a page then loads whichever you name). They are one kernel and step a world to the same bits, which a test holds on the hash of a 600-step world's snapshot; the scalar build takes its square roots from integer arithmetic that matches the hardware instruction bit for bit, and is larger and slower, never different.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import {Physics2D} from '@margoengine/physics2d';
|
|
44
|
+
|
|
45
|
+
// The package's own copy found through Node's resolver; in a page, pass the URL your server or CDN serves it from.
|
|
46
|
+
const wasm = new URL('physics2d.wasm', import.meta.resolve('@margoengine/physics2d'));
|
|
47
|
+
await Physics2D.load({wasm, signal: AbortSignal.timeout(30_000)});
|
|
48
|
+
const physics = new Physics2D(null, {gravity: [0, 320]});
|
|
49
|
+
physics.dispose();
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
`body.maxAngularSpeed` caps a body's spin (default 0, none: Rapier's default cap, which its `allowFastRotation` lifts, is not needed because a fast spinner with `ccd` is swept along its turn). `physics.setSolver({ maxCcdSubsteps: n })` lets a `ccd` body keep going after an impact inside one step, up to `n` impacts (default 1: it stops where it touches; 0 turns continuous collision off). `body.additionalSolverIterations = n` gives the body's island `n` more substeps each step (Rapier's `additional_solver_iterations`: solved as a world at that substep count would solve it, the other islands untouched). `body.additionalPgsIterations = n` gives the body's island `n` more solver passes each substep over its own contacts and joints (Rapier's `additional_pgs_iterations`; the island runs the most any of its awake bodies asks for, no other island is touched, and with none asking the step is unchanged). `body.enabled = false` takes a body out of the simulation (it keeps its pose and velocity, touches nothing, no query finds it, its joints rest) and `true` puts it back. `body.setAdditionalMassProperties(mass, centre, inertia)` adds a solid to what the colliders weigh by the parallel axis theorem (the older `additionalMass` adds in proportion), and `raycastAll(origin, direction)` lists every collider a ray meets, nearest first, and a filter's `excludeCollider` leaves one collider out where `exclude` leaves a body. Queries (`raycast`, `overlapPoint`, `overlapShape`, `castShape`) see every collider added or moved since the last step, and a `teleport` or `moveTo` at once. `castShape` and `overlapShape` take a box, circle, capsule, segment or a convex polygon of at most 8 points.
|
|
53
|
+
|
|
54
|
+
Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0. The kernel is Margo's own, written from papers (`docs/clean-room.md`); it holds no third-party code.
|
|
55
|
+
|
|
56
|
+
Build and unit tests: npm test --workspace @margoengine/physics2d
|
|
57
|
+
|
|
58
|
+
## Parity with Rapier 2D
|
|
59
|
+
|
|
60
|
+
`Physics2D` runs on Margo's own 2D kernel (`kernel/`, Rust to Wasm); it no longer uses Rapier. The capabilities below are listed from Rapier 2D's public user guide (rapier.rs/docs), never from its source. Status: **full** (kernel, facade and a test), **partial** (what is missing is named), **missing**. Docs: [limits](../../docs/limits.md), [known bugs](../../docs/known-bugs.md).
|
|
61
|
+
|
|
62
|
+
| Area | Rapier 2D capability | Where in Margo | Status |
|
|
63
|
+
| --- | --- | --- | --- |
|
|
64
|
+
| Shapes | ball, cuboid, capsule, segment | `box`, `circle`, `capsule`, `segment` colliders | full |
|
|
65
|
+
| Shapes | convex polygon, convex decomposition of concave or large input | `polygon` (convex hull to 8 corners; concave or larger split by ear clipping and Hertel-Mehlhorn) | full |
|
|
66
|
+
| Shapes | polyline | `polyline` (chains with ghost vertices: bodies slide over the joins) | full |
|
|
67
|
+
| Shapes | triangle, round (border radius) cuboid, triangle and convex polygon, trimesh with its flags | `triangle`, `borderRadius` on `box`, `polygon` and `triangle`, `trimesh` (triangles by index, `fixInternalEdges` and the clean-up flags) | full |
|
|
68
|
+
| Shapes | heightfield, halfspace, compound, voxels, shared shapes | `heightfield` (a smooth chain), `halfspace` (a polygon 200,000 units across), `compound` (parts with their own placement), `voxels` (merged outlines for contact, the cells themselves for queries); shape options are plain values, so one can be reused on any number of colliders | full, with the accepted differences in limits |
|
|
69
|
+
| Shapes | oriented (one-sided) polyline | `polyline` with `oneSided: true` | full |
|
|
70
|
+
| Collision | broad phase, narrow phase, manifolds, islands, sleeping | kernel box tree, SAT and clipping, SIMD solver | full |
|
|
71
|
+
| Collision | continuous collision detection | `ccd` against fixed, kinematic and dynamic bodies (a dynamic one it meets is put back to the same time) | full |
|
|
72
|
+
| Collision | soft CCD (a prediction distance per body) | `softCcd` (world units a body's contacts reach ahead) | full |
|
|
73
|
+
| Collision | sensors | `sensor: true` (senses fixed and kinematic bodies too) | full |
|
|
74
|
+
| Collision | collision groups, solver groups, active collision types | `collisionGroups`, `solverGroups`, `activeCollisionTypes` | full |
|
|
75
|
+
| Collision | collision events, contact force events | `contactstart`, `contactend`, `intersectionstart`, `intersectionend`, `contactforce` (`contactForceThreshold`) | full |
|
|
76
|
+
| Collision | physics hooks (filter and modify contact pairs, one-way platforms) | `physics.hooks = {filterPair, filterIntersection, modifyContact}` for colliders with `hooks` set (`filterPair` for a pair of solids, `filterIntersection` for a pair with a sensor in it; `collider.setActiveHooks` changes what a collider asks); `oneWay`, `friction`, `restitution`, `tangentVelocity` (conveyors), `solverActive` per contact | full |
|
|
77
|
+
| Queries | ray cast with normal (solid or not), every hit along a ray (`raycastAll`, nearest first), point, shape intersection, shape cast, project point, box intersection, filters | `raycast`, `overlapPoint`, `overlapShape`, `castShape`, `projectPoint`, `intersectionsWithBox`, `QueryFilter2D` | full |
|
|
78
|
+
| Queries | contact pairs of a collider, the contact between two colliders, intersection pairs of sensors | `contactPairs(collider)`, `contactPair(a, b)`, `intersectionPair(a, b)`, `intersectionPairsWith(collider)` | full |
|
|
79
|
+
| Bodies | dynamic, fixed, kinematic position, kinematic velocity | `type` | full |
|
|
80
|
+
| Bodies | damping, gravity scale, locked rotation, can sleep, dominance, body type changes | `BodyOptions2D`, the same names as setters on `Body2D`, `setType` | full |
|
|
81
|
+
| Bodies | forces, torques, impulses (at the centre or a point), forces at a point, resetting the torque or both, velocities, wake and sleep | `applyForce`, `applyForceAtPoint`, `applyTorque`, `applyImpulse`, `applyImpulseAtPoint`, `applyTorqueImpulse`, `resetForces`, `resetTorques`, and the velocity setters | full |
|
|
82
|
+
| Colliders | rolling resistance (Box2D): a contact resists the bodies' relative turn by up to a coefficient times its normal force times the rolling radius, so a rolling ball slows and stops and holds on a gentle slope | `rollingResistance` on a collider, `setRollingResistance`, `rollingResistance()`; of two colliders the larger applies | full |
|
|
83
|
+
| Collision | a contact's start with its normal, points and approach speed (Box2D's hit events, Planck.js's world manifold, Matter.js's collision) | `contactstart`'s `contact` (a `ContactPair2D`), `ContactPair2D.approachSpeed` | full |
|
|
84
|
+
| Bodies | sleep and wake events (Matter.js's `sleepStart`, `sleepEnd`; Box2D's move events' fell-asleep flag) | `physics.on('sleep' \| 'wake', ({body}) => ...)`, watched only while a listener is on | full |
|
|
85
|
+
| Bodies | explosions (Box2D): a radial push by the width a shape shows the blast, with a falloff and a filter | `physics.explode({position, radius, falloff, impulsePerLength, filter})`, which returns the colliders it pushed | full |
|
|
86
|
+
| Tools | composites (Matter.js): stack, pyramid, chain, mesh, Newton's cradle, car, soft body, a group that moves, turns and removes as one | `@margoengine/physics2d/composites` (`stack`, `pyramid`, `chain`, `mesh`, `newtonsCradle`, `car`, `softBody`, `Composite2D`) | full |
|
|
87
|
+
| Bodies | additional mass | `additionalMass` | full |
|
|
88
|
+
| Bodies | locked translation axes, locked rotation after creation | `lockTranslation` (an exact joint constraint that follows teleports), `lockRotation(locked)` | full |
|
|
89
|
+
| Colliders | collision types, events and the contact force threshold, changed after creation | `setActiveCollisionTypes`, `setActiveEvents`, `setContactForceEventThreshold` and their readers | full |
|
|
90
|
+
| Joints | fixed, revolute, prismatic, rope, spring, limits, motors in the force or the acceleration model (`motor: {model}`; the force model is the default, the acceleration model per unit of effective mass so a light body and a heavy one follow it alike), contacts between jointed bodies | `addJoint` | full |
|
|
91
|
+
| Joints | a joint's reaction force and torque; breaking on a force or torque threshold, with an event (Box2D's joint force threshold) | `joint.force`, `joint.torque`; `breakForce`, `breakTorque` and the `jointbreak` event | full |
|
|
92
|
+
| Joints | mouse joint (Box2D, Planck.js), mouse constraint (Matter.js): a body pulled to a moving target by a spring of its own frequency, capped at a force | `type: 'target'` (`target`, `hertz`, `damping`, `maxForce`), `joint.setTarget` | full |
|
|
93
|
+
| Joints | motor joint (Box2D, Planck.js): a body driven by force to an offset and angle from another, capped; friction joint (Box2D, Planck.js): a top-down ground's friction, the relative speed and spin held at zero up to a force and torque | `type: 'motor'` (`linearOffset`, `angularOffset`, `maxForce`, `maxTorque`, `correctionFactor`, default 0.3), `type: 'friction'` (`maxForce`, `maxTorque`). A motor joint is a velocity servo: capped below what stopping in time needs, it overshoots and swings about its offset, as Box2D's does; give it the force to spare or a lower `correctionFactor` | full |
|
|
94
|
+
| Joints | wheel joint (Box2D, Planck.js): a wheel on a line with a suspension spring of a frequency, travel limits and a motor on its turn | `type: 'wheel'` (`axis`, `hertz` default 1, `damping` default 0.7, `limits`, `motor`), `setLimits`, `setMotor` | full |
|
|
95
|
+
| Joints | distance joint (Box2D, Planck.js): a length held rigidly or by a spring of a frequency, between a minimum and a maximum, with a motor on it | `type: 'distance'` (`length` default the anchors' distance now, `spring: {hertz, damping}`, `limits`, `motor`), `setLimits`, `setMotor` | full |
|
|
96
|
+
| Joints | pulley joint (Box2D, Planck.js): a rope over two pulleys fixed in the world, with a ratio for a block and tackle | `type: 'pulley'` (`groundA`, `groundB`, `ratio` default 1, `length` default the strands' lengths now); `force` reads the pull on B | full |
|
|
97
|
+
| Joints | gear joint (Planck.js): two revolute or prismatic joints geared at a ratio (meshing gears, rack and pinion), wound past any number of turns | `type: 'gear'` (`jointA`, `jointB`, `ratio` default 1); each joint's carrier (its body A) may move, as gears on a car's body; removing either joint removes the gear | full |
|
|
98
|
+
| Joints | soft weld (Box2D, Planck.js): a weld as a spring on its point and its angle | `type: 'fixed'` with `linearHertz`, `angularHertz`, `linearDampingRatio`, `angularDampingRatio` (default 0, 0, 1, 1: rigid) | full |
|
|
99
|
+
| Joints | generic joint (any mix of the x, y and angle locks, in turned frames), pin-slot | `type: 'generic'`, `type: 'slot'` | full |
|
|
100
|
+
| Joints | multibody joints: joint space, joint motors and limits, kinematics, inverse kinematics | `addArticulation` (`Articulation2D`: positions and velocities, motors, limits, forward and inverse kinematics, Jacobian) over exact maximal-coordinate trees: chains and branched trees solve in one sweep, so a 1000:1 mass ratio across a branch keeps every joint closed | full, see limits |
|
|
101
|
+
| Tools | PID controller | `PidController2D` | full |
|
|
102
|
+
| Character | kinematic character controller: slide, autostep (`maxHeight`, `minWidth`, `includeDynamic`), snap to ground, slope climb and slide, push dynamic bodies, up vector, a query filter (`filter` option, `move(delta, filter)`) | `createCharacterController` | full |
|
|
103
|
+
| World | fixed timestep, interpolation, determinism (bit-identical native and Wasm) | `Physics2D`, kernel tests | full |
|
|
104
|
+
| World | snapshots (serialise and restore the world) | `snapshot()`, `restore()`: a restored world steps bit for bit as the original | full |
|
|
105
|
+
| World | debug render data: shapes, joints, contacts, boxes, body axes, solver contacts, a colour style (`rgba` a line) and a body filter | `debugRender({axes, solverContacts, style, filter})` | full |
|
|
106
|
+
| Tools | tile map and sprite outline colliders | `addTileMap`, `outlineColliders` | full |
|
|
107
|
+
|
|
108
|
+
## Lists of what a world holds
|
|
109
|
+
|
|
110
|
+
`physics.getBodies()`, `getColliders()` and `getJoints()` list what the world holds (bodies and joints in the order they were added, colliders in the order their shapes were made), and `bodyCount`, `colliderCount` and `jointCount` count them; a removed body leaves the lists with its colliders and joints. Any number of worlds run side by side in the one Wasm instance, each with its own `name` and nothing shared:
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
import {Physics2D} from 'margoengine/physics2d';
|
|
114
|
+
|
|
115
|
+
await Physics2D.load();
|
|
116
|
+
const earth = new Physics2D(null, {gravity: [0, 400]});
|
|
117
|
+
const moon = new Physics2D(null, {gravity: [0, 40], name: 'moon'});
|
|
118
|
+
const stone = earth.addBody(null, {colliders: {shape: 'circle', radius: 1}});
|
|
119
|
+
moon.addBody(null, {colliders: {shape: 'circle', radius: 1}});
|
|
120
|
+
earth.step();
|
|
121
|
+
moon.step();
|
|
122
|
+
console.log(earth.bodyCount, moon.bodyCount, earth.getColliders().length, stone.position[1] > 0); // 1 1 1 true
|
|
123
|
+
earth.dispose();
|
|
124
|
+
moon.dispose();
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
## Solver settings
|
|
128
|
+
|
|
129
|
+
`physics.setSolver(options)` changes the solver and `physics.solver` reads it, with the names the 3D world uses: `substeps` a step (default 4), `iterations` (pushing passes a substep, each followed by as many relaxing ones, default 1), the contact spring `contactHertz` and `contactDamping`, `contactMaxPush` (the fastest a depth is pushed out), `restitutionThreshold` (under this approach speed a contact does not bounce), `sleepThreshold` and `sleepTime` with `canSleep`, `blockSolver` (Rapier's block solver: the two points of a contact solved together as one 2 by 2 problem, on by default; off, one point at a time), the joint spring `jointHertz`, `jointDamping`, `jointMaxPush` with `jointGeometricStiffness`, `maxCcdSubsteps` (how many impacts continuous collision handles in a step: default 1, 0 for off; see below), the sweep's `minCcdDt`, `ccdTolerance` and `ccdMaxAdvances` with the 3D world's names and meanings, `warmStart` (the share of last step's contact impulses a step starts from, 0 to 1, default 1), `allowedPenetration` (how deep a contact may overlap before it is pushed apart, default 0), `predictionDistance` (how far apart two colliders get contact points, default 2 cm) and a contact spring for contacts with fixed and kinematic bodies, `staticContactHertz` and `staticContactDamping` (default `null`: the contact spring; a softer one lets bodies settle into the ground while stacks keep the stiff spring). Speeds and distances are in world units. A name left out keeps its value, and a refused one (a count that is not a whole number from 1 to 65535 (0 to 65535 for `maxCcdSubsteps`), a negative or non-finite number, a `warmStart` outside 0 to 1) throws a `RangeError` and changes nothing. The settings are part of a snapshot.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import {Physics2D} from 'margoengine/physics2d';
|
|
133
|
+
|
|
134
|
+
await Physics2D.load();
|
|
135
|
+
const physics = new Physics2D(null);
|
|
136
|
+
physics.addBody(null, {type: 'fixed', position: [0, 100], colliders: {shape: 'box', width: 1000, height: 20}});
|
|
137
|
+
physics.addBody(null, {position: [0, 80], colliders: {shape: 'box', width: 20, height: 20}});
|
|
138
|
+
physics.setSolver({substeps: 8, blockSolver: false, allowedPenetration: 0.5, staticContactHertz: 10});
|
|
139
|
+
for (let i = 0; i < 30; i++) physics.step();
|
|
140
|
+
const {substeps, blockSolver, staticContactDamping} = physics.solver;
|
|
141
|
+
console.log(substeps, blockSolver, staticContactDamping, physics.counts.blockSolves); // 8 false null 0
|
|
142
|
+
physics.dispose();
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
## Casts, projections and continuous collision
|
|
146
|
+
|
|
147
|
+
`castShape(shape, position, direction, maxDistance, filter, rotation, {targetDistance, stopAtPenetration})` slides a shape until it is `targetDistance` from a collider (default 0: touching) and returns the hit with the closest points of both shapes (`witnessA`, `witnessB`), their normals, the `gap` between them and a `status`; with `stopAtPenetration` false, a collider the shape already overlaps and is leaving is not a hit. `projectPoint(point, filter, solid)` puts a point inside a collider on its own spot (`solid`, the default) or on the nearest point of its surface. A body with `ccd` is stopped by what it would pass through in a step; `setSolver({maxCcdSubsteps: n})` lets it bounce off up to `n` impacts inside one step.
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import {Physics2D} from 'margoengine/physics2d';
|
|
151
|
+
|
|
152
|
+
await Physics2D.load();
|
|
153
|
+
const physics = new Physics2D(null, {gravity: [0, 0], pixelsPerMeter: 1});
|
|
154
|
+
physics.addBody(null, {type: 'fixed', position: [0, 0], colliders: {shape: 'box', width: 20, height: 2}});
|
|
155
|
+
const hit = physics.castShape({shape: 'circle', radius: 0.5}, [0, 5], [0, -1], 20, undefined, 0, {targetDistance: 0.25});
|
|
156
|
+
console.log(hit?.distance, hit?.gap); // 3.25 0.25: stopped a quarter above the box's top face
|
|
157
|
+
console.log(physics.projectPoint([0.5, 0.2], undefined, false)?.point); // [0.5, 1]: the top face, not the point itself
|
|
158
|
+
physics.dispose();
|
|
159
|
+
|
|
160
|
+
// A ball at 1000 m/s between two thin walls 6 m apart: with 4 impacts a step it bounces three times inside the one step.
|
|
161
|
+
const corridor = new Physics2D(null, {gravity: [0, 0], pixelsPerMeter: 1});
|
|
162
|
+
for (const x of [-3, 3]) corridor.addBody(null, {type: 'fixed', position: [x, 0], colliders: {shape: 'box', width: 0.1, height: 10, restitution: 1}});
|
|
163
|
+
corridor.setSolver({maxCcdSubsteps: 4});
|
|
164
|
+
const ball = corridor.addBody(null, {ccd: true, linearVelocity: [1000, 0], colliders: {shape: 'circle', radius: 0.1, restitution: 1}});
|
|
165
|
+
corridor.step();
|
|
166
|
+
console.log(Math.round(ball.position[0] * 10) / 10, ball.linearVelocity[0]); // 0.4 -1000: now going left
|
|
167
|
+
corridor.dispose();
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## What a step did and how long it took
|
|
171
|
+
|
|
172
|
+
`physics.counts` reads the work the last step did as whole numbers that do not depend on the machine: `awake` bodies, `islands` (groups of dynamic bodies with an awake body in them; a fixed body is no island and a sleeping group is no work), `boxesCompared`, `pairs`, `manifolds`, `coldPoints` (manifold points that found no point in the last manifold and start with no impulse), `contactsSolved`, `blockSolves` and `sequentialSolves` (two-point contacts solved together or one point at a time), `colours` and `uncoloured`, `treeJoints`, `events` and `steps`. `physics.timing` reads how long the phases took in milliseconds, Rapier's `timingStep` and its siblings: `step` is the whole of it, then `begin`, `broad`, `narrow`, `islands`, `solver`, `ccd` and `events`, which add up to it; `assembly`, `resolution`, `update` and `writeback` split `solver` and `ccdBroad`, `ccdToi` and `ccdSolver` split `ccd`, as sums over the substeps and the bodies. Everything reads zero before the first step. The clock is not part of the world: a snapshot and the replay hash leave timings out, and two worlds built the same way give the same counts.
|
|
173
|
+
|
|
174
|
+
```ts
|
|
175
|
+
import {Physics2D} from 'margoengine/physics2d';
|
|
176
|
+
|
|
177
|
+
await Physics2D.load();
|
|
178
|
+
const physics = new Physics2D(null);
|
|
179
|
+
physics.addBody(null, {type: 'fixed', position: [0, 100], colliders: {shape: 'box', width: 1000, height: 20}});
|
|
180
|
+
for (let i = 0; i < 4; i++) {
|
|
181
|
+
physics.addBody(null, {position: [0, 70 - i * 21], colliders: {shape: 'box', width: 20, height: 20}});
|
|
182
|
+
}
|
|
183
|
+
for (let i = 0; i < 30; i++) physics.step();
|
|
184
|
+
const {awake, islands, contactsSolved, steps} = physics.counts;
|
|
185
|
+
console.log(awake, islands, contactsSolved > 0, steps); // 4 1 true 30
|
|
186
|
+
console.log(physics.timing.step >= physics.timing.solver); // true
|
|
187
|
+
physics.dispose();
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
## Triangle meshes
|
|
191
|
+
|
|
192
|
+
A `trimesh` collider takes triangles by index into its vertices. Each triangle collides alone, so a body sliding over the
|
|
193
|
+
edge two triangles share can catch on it; `fixInternalEdges: true` joins them into one solid for contacts (Rapier's
|
|
194
|
+
`TriMeshFlags.FIX_INTERNAL_EDGES`, which in Rapier 2D changes nothing: its box catches on the same strip with the flag or
|
|
195
|
+
without it). A shared edge then makes no contact, and a contact on a triangle takes only the normals the mesh's outline has
|
|
196
|
+
there, so boxes and balls slide across the joins and still meet the mesh's real corners. Shared edges are found by exact
|
|
197
|
+
positions. The clean-up flags run first, in Rapier's order: `mergeDuplicateVertices`, `deleteDegenerateTriangles` (a flat
|
|
198
|
+
triangle otherwise collides along its line, as in Rapier), `deleteDuplicateTriangles` and `deleteBadTopologyTriangles`.
|
|
199
|
+
All are off by default.
|
|
200
|
+
|
|
201
|
+
```ts
|
|
202
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
203
|
+
|
|
204
|
+
await Physics2D.load();
|
|
205
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 100 });
|
|
206
|
+
const vertices: [number, number][] = [],
|
|
207
|
+
indices: number[] = [];
|
|
208
|
+
for (let i = 0; i <= 20; i++) vertices.push([i * 50, 0], [i * 50, 100]);
|
|
209
|
+
for (let i = 0; i < 20; i++) indices.push(2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 1, 2 * i + 3, 2 * i + 2);
|
|
210
|
+
physics.addBody(null, { type: 'fixed', colliders: { shape: 'trimesh', vertices, indices, friction: 0, fixInternalEdges: true } });
|
|
211
|
+
const box = physics.addBody(null, {
|
|
212
|
+
position: [30, -10],
|
|
213
|
+
linearVelocity: [200, 0],
|
|
214
|
+
colliders: { shape: 'box', width: 20, height: 20, friction: 0 },
|
|
215
|
+
});
|
|
216
|
+
for (let i = 0; i < 120; i++) physics.step();
|
|
217
|
+
console.log(Math.round(box.linearVelocity[0]), Math.abs(box.rotation) < 0.05); // 200 true
|
|
218
|
+
physics.dispose();
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## Vehicles (`@margoengine/physics2d/vehicle`)
|
|
222
|
+
|
|
223
|
+
`new Vehicle2D(physics, chassis, { wheels })` is Rapier's ray cast vehicle seen from the side: a hill-climb car, a cart or
|
|
224
|
+
a truck. Each wheel casts a ray from its `position` on the chassis along its `direction` (default down on screen); a
|
|
225
|
+
spring (`suspensionStiffness`, default 5.88 as Rapier's) and dampers (`suspensionCompression` 0.83, `suspensionRelaxation`
|
|
226
|
+
0.88) on the suspension (`suspensionRestLength` default 0.3 m, `maxSuspensionTravel` 5 m, `maxSuspensionForce` 6000 N) hold
|
|
227
|
+
the chassis up, and the tyre drives and brakes along the ground inside what its load can hold (`frictionSlip`, default
|
|
228
|
+
10.5). `engineForce` and `brake` (newtons per wheel, or `setInput({ throttle, brake })` against `maxEngineForce` and
|
|
229
|
+
`maxBrakeForce`) drive it; `speed` is the chassis's speed along `forward` (Rapier's `currentVehicleSpeed`), and
|
|
230
|
+
`vehicle.wheel(i)` gives `inContact`, `contactPoint`, `contactNormal`, `ground`, `hardPoint`, `suspensionLength`,
|
|
231
|
+
`suspensionForce`, `forwardImpulse` and the wheel's `rotation`; `wheelCenter(i)` is where to draw it. The pushes are held on
|
|
232
|
+
the chassis (and on a dynamic body under a wheel, unless `groundReaction: false`) as forces over each step, so they act in
|
|
233
|
+
every substep as gravity does. There is no steering and no sideways grip: in a side view the axle points out of the screen.
|
|
234
|
+
`body.inertia` reads a body's moment of inertia (Rapier's `principalInertia`).
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
238
|
+
import { Vehicle2D } from '@margoengine/physics2d/vehicle';
|
|
239
|
+
|
|
240
|
+
await Physics2D.load();
|
|
241
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
242
|
+
physics.addBody(null, { type: 'fixed', position: [0, 1], colliders: { shape: 'box', width: 400, height: 1 } });
|
|
243
|
+
const chassis = physics.addBody(null, {
|
|
244
|
+
position: [0, -0.2],
|
|
245
|
+
colliders: { shape: 'box', width: 2, height: 0.5, mass: 800 },
|
|
246
|
+
});
|
|
247
|
+
const wheel = (x: number) => ({
|
|
248
|
+
position: [x, 0.25] as [number, number],
|
|
249
|
+
radius: 0.3,
|
|
250
|
+
suspensionStiffness: 40,
|
|
251
|
+
suspensionCompression: 4,
|
|
252
|
+
suspensionRelaxation: 4,
|
|
253
|
+
});
|
|
254
|
+
using car = new Vehicle2D(physics, chassis, { wheels: [wheel(-0.8), wheel(0.8)] });
|
|
255
|
+
for (let i = 0; i < 60; i++) physics.step(); // settles on its springs
|
|
256
|
+
car.setInput({ throttle: 1 });
|
|
257
|
+
for (let i = 0; i < 120; i++) physics.step();
|
|
258
|
+
console.log(car.speed > 2, car.wheel(0).inContact); // true true
|
|
259
|
+
physics.dispose();
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
## Composites (`@margoengine/physics2d/composites`)
|
|
263
|
+
|
|
264
|
+
Matter.js's `Composites`, as functions that take the world and return a `Composite2D` (its `bodies` and `joints`, which
|
|
265
|
+
`translate`, `rotate` and `remove` as one; `using` removes it): `stack` (a grid of cells, each body from a callback that
|
|
266
|
+
may leave a cell empty), `pyramid` (Box2D's pyramid: a base row and one fewer a row up, each half a cell in), `chain`
|
|
267
|
+
(each body joined to the next at two anchors, by a revolute joint or any link), `mesh` (a full stack's neighbours joined,
|
|
268
|
+
cross-braced if asked; a spring's rest length defaults to the gap), `newtonsCradle`, `car` (a box on two wheel joints with
|
|
269
|
+
a suspension) and `softBody` (circle particles meshed by springs of a frequency on a particle's mass). The cradle's balls
|
|
270
|
+
hang 3 cm apart by default: two shapes get a contact within 2 cm, and touching balls are solved together in one step and
|
|
271
|
+
share the blow (as in Box2D and Rapier), where balls a gap apart strike one by one, as in an ideal cradle.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
275
|
+
import { newtonsCradle, pyramid, softBody } from '@margoengine/physics2d/composites';
|
|
276
|
+
|
|
277
|
+
await Physics2D.load();
|
|
278
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
279
|
+
physics.addBody(null, { type: 'fixed', position: [0, 0.5], colliders: { shape: 'box', width: 40, height: 1 } });
|
|
280
|
+
pyramid(physics, {
|
|
281
|
+
position: [-5, 0],
|
|
282
|
+
base: 6,
|
|
283
|
+
cell: [0.5, 0.5],
|
|
284
|
+
body: () => ({ colliders: { shape: 'box', width: 0.5, height: 0.5 } }),
|
|
285
|
+
});
|
|
286
|
+
softBody(physics, { position: [5, -3], columns: 4, rows: 4, radius: 0.1 });
|
|
287
|
+
const cradle = newtonsCradle(physics, { position: [0, -6], radius: 0.1, length: 2 });
|
|
288
|
+
const [, first] = cradle.bodies; // bodies[0] holds the pivots
|
|
289
|
+
first.teleport([-2 * Math.sin(0.5), -6 + 2 * Math.cos(0.5)], 0.5); // swing it out with its arm
|
|
290
|
+
for (let i = 0; i < 120; i++) physics.step();
|
|
291
|
+
console.log(cradle.bodies.length, Math.abs(cradle.bodies[5].linearVelocity[0]) > 1); // 6 true
|
|
292
|
+
physics.dispose();
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
## Forces at a point, locked rotation and collider settings
|
|
296
|
+
|
|
297
|
+
`body.applyForceAtPoint(force, point)` holds a force that acts every step and turns the body by the arm from its centre of mass, as Rapier's `addForceAtPoint` does; `resetTorques()` clears the turning and keeps the push, `resetForces()` clears both. `body.lockRotation(locked = true)` holds the angle and takes the spin away until `lockRotation(false)`. A collider's `setActiveCollisionTypes(bits)` chooses the pairs it meets (1 dynamic with dynamic, 2 dynamic with kinematic, 4 dynamic with fixed, 8 kinematic with kinematic, 16 kinematic with fixed, 32 fixed with fixed; the default is 7), `setActiveEvents({collision, contactForce})` the events it asks for, and `setContactForceEventThreshold(newtons)` how hard a contact must press to raise `contactforce`.
|
|
298
|
+
|
|
299
|
+
```ts
|
|
300
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
301
|
+
|
|
302
|
+
await Physics2D.load();
|
|
303
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1, gravity: [0, 0] });
|
|
304
|
+
const disc = physics.addBody(null, { colliders: { shape: 'circle', radius: 1, mass: 2 } });
|
|
305
|
+
disc.applyForceAtPoint([0, 4], [1, 0]); // pushes at 2 m/s^2 and turns at 4 rad/s^2
|
|
306
|
+
physics.step();
|
|
307
|
+
disc.resetTorques(); // the push goes on, nothing turns it any more
|
|
308
|
+
disc.lockRotation(); // and the angle is held whatever pushes at it
|
|
309
|
+
console.log(disc.linearVelocity, disc.angularVelocity);
|
|
310
|
+
physics.dispose();
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
A collider's outline can change after it is made: `collider.setShape(shape)` takes any shape a collider is
|
|
314
|
+
made with (`circle`, `box`, `capsule`, `segment`, `triangle`, convex or concave `polygon`, `polyline`, `trimesh`,
|
|
315
|
+
`heightfield`, `compound`, `voxels` or `halfspace`), at the collider's own offset and turn. Its material, density, mass mode
|
|
316
|
+
and filtering stay, the body's mass follows the new outline, and active contact pairs are carried across the swap without
|
|
317
|
+
raising a duplicate start event, as Rapier's `setShape` does.
|
|
318
|
+
|
|
319
|
+
```ts
|
|
320
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
321
|
+
|
|
322
|
+
await Physics2D.load();
|
|
323
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
324
|
+
const body = physics.addBody(null, { colliders: { shape: 'box', width: 0.5, height: 0.5, density: 2 } });
|
|
325
|
+
body.colliders[0].setShape({ shape: 'circle', radius: 0.6 });
|
|
326
|
+
console.log(body.mass.toFixed(3)); // '2.262': 2 kg/m^2 over a disc of 0.6 m
|
|
327
|
+
physics.dispose();
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
A contact combines two colliders' friction and restitution by their combine rules, as Rapier's do:
|
|
331
|
+
`CoefficientCombineRule2D.Average` by default, or `Min`, `Multiply`, `Max`, `ClampedSum` (the sum held to 0 to 1) or
|
|
332
|
+
`GeometricMean`; of two colliders' rules the later in that list wins. Set them with the `frictionCombineRule` and
|
|
333
|
+
`restitutionCombineRule` options or `setFrictionCombineRule` and `setRestitutionCombineRule`. A ball of restitution
|
|
334
|
+
0.8 on a floor of 0 bounces at 0.4 by the average; give the ball `Max` to bounce at 0.8.
|
|
335
|
+
|
|
336
|
+
```ts
|
|
337
|
+
import { CoefficientCombineRule2D, Physics2D } from '@margoengine/physics2d';
|
|
338
|
+
|
|
339
|
+
await Physics2D.load();
|
|
340
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
341
|
+
const ball = physics.addBody(null, {
|
|
342
|
+
colliders: { shape: 'circle', radius: 0.25, restitution: 0.8, restitutionCombineRule: CoefficientCombineRule2D.Max },
|
|
343
|
+
});
|
|
344
|
+
console.log(ball.colliders[0].restitutionCombineRule() === CoefficientCombineRule2D.Max); // true
|
|
345
|
+
physics.dispose();
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
`contactSkin` (or `setContactSkin`) is Rapier's contact skin: the collider's contacts start that much farther out and
|
|
349
|
+
the solver holds it that far off what it touches, so two colliders rest the sum of their skins apart. It is in world
|
|
350
|
+
units, and queries still meet the outline itself.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
354
|
+
|
|
355
|
+
await Physics2D.load();
|
|
356
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
357
|
+
const crate = physics.addBody(null, { colliders: { shape: 'box', width: 1, height: 1, contactSkin: 0.02 } });
|
|
358
|
+
crate.colliders[0].setContactSkin(0.05); // rests 5 cm off what it lands on
|
|
359
|
+
console.log(crate.colliders[0].contactSkin().toFixed(2)); // '0.05'
|
|
360
|
+
physics.dispose();
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
A collider moves on its body after it is made: `setTranslationWrtParent([x, y])` and `setRotationWrtParent(angle)`, in
|
|
364
|
+
the body's frame, as Rapier's; the body's mass and centre of mass follow. `translationWrtParent()` and
|
|
365
|
+
`rotationWrtParent()` read the place back.
|
|
366
|
+
|
|
367
|
+
```ts
|
|
368
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
369
|
+
|
|
370
|
+
await Physics2D.load();
|
|
371
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
372
|
+
const door = physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', width: 2, height: 0.2 } });
|
|
373
|
+
door.colliders[0].setRotationWrtParent(Math.PI / 2); // the bar now stands
|
|
374
|
+
console.log(door.colliders[0].rotationWrtParent().toFixed(3)); // '1.571'
|
|
375
|
+
physics.dispose();
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
A collider's mass can be its own rather than its density's: `setMass(kilograms)` (or the `mass` option) holds whatever
|
|
379
|
+
the outline, its centre and inertia the outline's at that mass; `setMassProperties(mass, centre, inertia)` gives them
|
|
380
|
+
outright, the centre in the collider's frame; `setDensity` goes back; `mass()` reads it. As Rapier's.
|
|
381
|
+
|
|
382
|
+
```ts
|
|
383
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
384
|
+
|
|
385
|
+
await Physics2D.load();
|
|
386
|
+
const physics = new Physics2D(null, { pixelsPerMeter: 1 });
|
|
387
|
+
const crate = physics.addBody(null, { colliders: { shape: 'box', width: 1, height: 1 } });
|
|
388
|
+
crate.colliders[0].setMass(12);
|
|
389
|
+
crate.colliders[0].setShape({ shape: 'circle', radius: 2 }); // still 12 kg
|
|
390
|
+
console.log(crate.mass.toFixed(1)); // '12.0'
|
|
391
|
+
physics.dispose();
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
## Articulations
|
|
395
|
+
|
|
396
|
+
`physics.addArticulation(root, links)` joins bodies into a tree of revolute and prismatic joints and gives it a joint space: positions, velocities, motors, limits, forward and inverse kinematics.
|
|
397
|
+
|
|
398
|
+
```ts
|
|
399
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
400
|
+
|
|
401
|
+
await Physics2D.load();
|
|
402
|
+
const physics = new Physics2D(null, { gravity: [0, 0] });
|
|
403
|
+
const base = physics.addBody(null, { type: 'fixed', colliders: [] });
|
|
404
|
+
const link = (x: number) => physics.addBody(null, { position: [x, 0], colliders: { shape: 'box', width: 40, height: 6, collisionGroups: 0 } });
|
|
405
|
+
const [upper, lower] = [link(20), link(60)];
|
|
406
|
+
const arm = physics.addArticulation(base, [
|
|
407
|
+
{ body: upper, joint: { type: 'revolute', anchorChild: [-20, 0], limits: [-2.5, 2.5] } },
|
|
408
|
+
{ body: lower, parent: 0, joint: { type: 'revolute', anchorParent: [20, 0], anchorChild: [-20, 0], limits: [-2.5, 2.5] } },
|
|
409
|
+
]);
|
|
410
|
+
// Joint positions that put the lower arm's tip on a point, then let the motors take the arm there.
|
|
411
|
+
const { q, reached } = arm.solveIK(1, [20, 0], [50, 40]);
|
|
412
|
+
arm.driveTo(q);
|
|
413
|
+
for (let i = 0; i < 240; i++) physics.step();
|
|
414
|
+
console.log(reached, arm.pointAt(1, [20, 0]));
|
|
415
|
+
physics.dispose();
|
|
416
|
+
```
|
|
417
|
+
|
|
418
|
+
The links stay ordinary bodies and the kernel's joints hold them together, solved exactly in one sweep over the whole tree (Baraff 1996: sparse block elimination over the tree), so a 1000:1 mass ratio across a branch keeps every joint closed and contacts of any link act on the whole arm. Margo uses exact maximal-coordinate trees rather than reduced coordinates so that contacts stay in the one solver; [limits](../../docs/limits.md) has the measured accuracy against the closed forms and against Rapier 2D.
|
|
419
|
+
|
|
420
|
+
## Colliders from a sprite's alpha (`@margoengine/physics2d/outline`)
|
|
421
|
+
|
|
422
|
+
`outlineColliders(image, options)` turns the alpha of an image into colliders that follow what is drawn, holes and hollows included, so a ball can rest in a cup. `image` is RGBA8 straight alpha, row by row from the top: `ImageData` fits.
|
|
423
|
+
|
|
424
|
+
```ts
|
|
425
|
+
import { Physics2D } from '@margoengine/physics2d';
|
|
426
|
+
import { outlineColliders } from '@margoengine/physics2d/outline';
|
|
427
|
+
|
|
428
|
+
// Any drawing works; drawImage a sprite here.
|
|
429
|
+
const context = new OffscreenCanvas(64, 64).getContext('2d')!;
|
|
430
|
+
context.arc(32, 32, 24, 0, Math.PI * 2);
|
|
431
|
+
context.fill();
|
|
432
|
+
const imageData = context.getImageData(0, 0, 64, 64);
|
|
433
|
+
|
|
434
|
+
await Physics2D.load();
|
|
435
|
+
const physics = new Physics2D(null, { gravity: [0, 980] });
|
|
436
|
+
const colliders = outlineColliders(imageData, { friction: 0.4 });
|
|
437
|
+
physics.addBody(null, { type: 'fixed', colliders });
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
Pass `sprite` and the colliders land on the sprite's pivot and scale, and its `rect` picks the frame of an atlas: `physics.addBody(sprite, {colliders: outlineColliders(imageData, {sprite})})`. `traceOutlines(image, options)` gives the outlines alone, in pixels from the top left of the traced area, each with its holes.
|
|
441
|
+
|
|
442
|
+
| Option | Default | What it does |
|
|
443
|
+
| --- | --- | --- |
|
|
444
|
+
| `threshold` | 128 | Alpha from 1 to 255 that counts as solid; the edge is placed between pixels by their alpha |
|
|
445
|
+
| `tolerance` | 1 | Farthest the thinned outline may stray from the traced one, in pixels; 0 keeps every point off a straight line |
|
|
446
|
+
| `minArea` | 4 | Outlines and holes under this many square pixels are left out |
|
|
447
|
+
| `rect` | whole image | `[x, y, width, height]` in pixels |
|
|
448
|
+
| `sprite` | none | Places the colliders, as `addBody(sprite)` places a fitted box |
|
|
449
|
+
| `edges` | false | False gives filled convex `polygon` colliders; true gives one closed `polyline` per outline and hole, for fixed terrain |
|
|
450
|
+
|
|
451
|
+
Any other collider setting (`friction`, `restitution`, `sensor`, `density` and the rest) goes on every collider. Limits are in [docs/limits.md](../../docs/limits.md).
|
|
452
|
+
|
|
453
|
+
## Kernel development
|
|
454
|
+
|
|
455
|
+
The Rust kernel under `kernel/` is what the TypeScript facade above calls through `dist/physics2d.wasm` (its C interface is `kernel/src/api.rs`; rebuild the committed Wasm with `node scripts/wasm-blueprints.mjs --rebuild --only=physics2d-kernel`). Its world batches four
|
|
456
|
+
awake quad contacts through exact SIMD SAT and clipping. A rectangle certified from its current vertices and normals
|
|
457
|
+
uses support corners for SAT; separated cores can certify the original preferred clipped face from conservative
|
|
458
|
+
distance bounds. Uncertified cases use the complete closest-distance path. The
|
|
459
|
+
[floating-point proof](../../docs/architecture/physics2d-manifold-proof.md) describes the guards and fallback.
|
|
460
|
+
Other shapes, chains and short tails retain their collision paths. `manifold::collide_four` has a runnable Rust
|
|
461
|
+
example in [its API documentation](kernel/src/manifold/four.rs); every lane's manifold is bit-identical to the
|
|
462
|
+
scalar call, including signed zeros and unused point slots. Run the native and shipped Wasm checks from the root:
|
|
463
|
+
|
|
464
|
+
```sh
|
|
465
|
+
npm run test:physics2d-kernel
|
|
466
|
+
npm run check:rust-kernels -- --packages=physics2d
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
[Performance history](../../docs/whitepaper/perf-history.md) records the modest paired gain and the remaining Box2D
|
|
470
|
+
loss; the 0.35 ms narrow-phase target has not been met. Browser evidence covers Edge WebGPU/WebGL2 and Firefox
|
|
471
|
+
WebGL2; Firefox WebGPU has no adapter on the test installation.
|
|
472
|
+
|
|
473
|
+
Rapier 2D is not a dependency of this package. `tests/oracle-rapier.test.js` compares scenes with it live when `RAPIER2D_MODULE` names the `rapier.mjs` of a `@dimforge/rapier2d-compat` 0.21 you installed outside the repository (a black box, for comparison only); without it those tests are listed as not run.
|
|
474
|
+
|
|
475
|
+
### Checked Rust input
|
|
476
|
+
|
|
477
|
+
The raw Rust world and collision APIs return `Result<_, PhysicsError>`. Handle errors with `?` or inspect
|
|
478
|
+
`error.code()` and `error.help()`; the [input contract](../../docs/limits.md#own-2d-input-validation) lists the
|
|
479
|
+
codes and representability rules. This API belongs to `kernel/`; the TypeScript facade above
|
|
480
|
+
keeps its existing API and units.
|
|
481
|
+
|
|
482
|
+
```rust
|
|
483
|
+
use margoengine_physics2d_kernel::{
|
|
484
|
+
error::PhysicsError,
|
|
485
|
+
math::{V2, v2},
|
|
486
|
+
shape::Core,
|
|
487
|
+
world::{BodyDef, ShapeDef, World},
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
fn main() -> Result<(), PhysicsError> {
|
|
491
|
+
let mut world = World::default();
|
|
492
|
+
let body = world.create_body(&BodyDef {
|
|
493
|
+
position: v2(0.0, 0.5),
|
|
494
|
+
..BodyDef::default()
|
|
495
|
+
})?;
|
|
496
|
+
let core = Core::rect(0.5, 0.5, V2::ZERO, 1.0, 0.0, 0.0)?;
|
|
497
|
+
world.create_shape(body, core, &ShapeDef::default())?;
|
|
498
|
+
world.step(1.0 / 60.0)?;
|
|
499
|
+
|
|
500
|
+
let error = world.create_shape(body, core, &ShapeDef {
|
|
501
|
+
density: f32::INFINITY,
|
|
502
|
+
..ShapeDef::default()
|
|
503
|
+
}).unwrap_err();
|
|
504
|
+
assert_eq!(error.code(), "PHYSICS2D_NOT_FINITE");
|
|
505
|
+
assert_eq!(world.shapes.len(), 1); // The refused shape was never published.
|
|
506
|
+
Ok(())
|
|
507
|
+
}
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
Body, shape and whole-chain creation refuse invalid input before publishing a partial result. Finite positive
|
|
511
|
+
density alone is insufficient: derived mass, inertia, centres and reciprocals must also remain representable.
|
|
512
|
+
The inverse metric's reciprocal and the reconstructed rounded origin are checked too. Finite friction coefficients
|
|
513
|
+
use an overflow-safe geometric mean; used cached normal impulses cannot be negative.
|
|
514
|
+
Contact normal/tangent metrics are checked before inversion, including sums of individually valid inverse masses.
|
|
515
|
+
Rotation normalization scales exceptional finite pairs to preserve their direction across overflow/underflow;
|
|
516
|
+
nonfinite integration arithmetic returns the coded error. A directly mutated zero body rotation is refused.
|
|
517
|
+
Genuine zero density or zero area retains its documented zero-mass behavior; positive mass or inertia rounded
|
|
518
|
+
to zero is refused. Before stepping, the world checks current public data and handles, including edits made
|
|
519
|
+
after creation. A reported arithmetic error during simulation does not promise rollback of the whole step.
|
|
520
|
+
|
|
521
|
+
Direct Rust `solver::solve` calls check the same current inputs and derived solver outputs. `World::step`
|
|
522
|
+
uses the private already-checked solver entry after its preflight, so a normal step checks each boundary once.
|
|
523
|
+
Unlike the world's nonpositive-step no-op, the direct solver requires a positive representable substep.
|
|
524
|
+
|
|
525
|
+
Collision calls (`collide`, `collide_coherent`, `collide_four` and `collide_smooth`) refuse nonfinite poses or
|
|
526
|
+
cutoffs and invalid current core data instead of indexing a missing face or returning an invented contact.
|
|
527
|
+
The existing [four-pair Rust doctest](kernel/src/manifold/four.rs) demonstrates the checked collision call.
|
|
528
|
+
Run `cargo test --locked --manifest-path packages/physics2d/kernel/Cargo.toml --doc` for both examples. Native
|
|
529
|
+
input/manifold regression commands are in [reproduce.md](../../docs/whitepaper/reproduce.md#own-2d-input-validation).
|
|
530
|
+
Input validation preserves the retained manifold reference and the prior valid hashes. The separate support
|
|
531
|
+
correction below intentionally re-pins the mixed scene. Owned-2D CCD is separate T-11 / 127.y work.
|
|
532
|
+
|
|
533
|
+
### Sustained contact support in the owned kernel
|
|
534
|
+
|
|
535
|
+
The default 3 m/s recovery cap limits recovery demand independently of sustained elastic support. The spring
|
|
536
|
+
root, four substeps, one pass and all accuracy thresholds remain unchanged. A certified supported contact path
|
|
537
|
+
uses a coupled equilibrium correction with physical masses; general graphs retain capped contact dynamics.
|
|
538
|
+
Sleep also observes the motion actually integrated, so relaxation cannot hide continuing correction.
|
|
539
|
+
|
|
540
|
+
The required 1:1000 centered contact stack now holds the same 3% spring-sag, 0.1 mm top drift, 10 mm post-one-second
|
|
541
|
+
creep and sleep predicates as 1:100. Run `cargo test --locked --manifest-path packages/physics2d/kernel/Cargo.toml --test world`.
|
|
542
|
+
All original physical bars remain required. The mixed-scene hash is deliberately re-pinned for this correction;
|
|
543
|
+
pyramid and joint-grid hashes stay unchanged. The [proof and method domain](../../docs/architecture/physics2d-support-proof.md)
|
|
544
|
+
distinguish axial support from the preserved soft model's [lateral bending limit](../../docs/architecture/physics2d-support-bending.md).
|
|
545
|
+
This is a correctness change; Box2D browser speed parity remains unproven.
|
|
546
|
+
|
|
547
|
+
The support planner rebuilds its current graph each frame and retains flat scratch buffers between steps.
|
|
548
|
+
It preserves contact order, eligibility decisions and floating arithmetic. Retained planner capacity follows
|
|
549
|
+
the largest body/contact counts seen by the world; changing component order cannot accumulate a separate
|
|
550
|
+
high-water allocation for every component. Accepted components still allocate local solve buffers.
|
|
551
|
+
The native `planner_allocations` example measures whole-step allocation requests on the unchanged 100-row
|
|
552
|
+
scene; [reproduce.md](../../docs/whitepaper/reproduce.md) records its paired-control procedure and timing limits.
|
|
553
|
+
|
|
554
|
+
The four-lane normal solver also omits finite predicates already implied by its exact caller expressions.
|
|
555
|
+
Its [IEEE proof](../../docs/architecture/physics2d-finite-certificates.md) states that contract and the checks
|
|
556
|
+
retained for mutable arithmetic, cap membership and scalar fallback. The compiled finite-predicate count
|
|
557
|
+
falls while all current hashes and physical bars remain unchanged; a browser speed gain is unproven.
|
|
558
|
+
|
|
559
|
+
Private broad-phase refits reuse the same call-stack input preflight while public bounds and every step
|
|
560
|
+
remain checked. The planner also skips pure eligibility predicates after rejecting a component, retaining
|
|
561
|
+
its entire traversal. The [frame-preparation proof](../../docs/architecture/physics2d-frame-preparation.md)
|
|
562
|
+
records exact work, accuracy and measurement limits; the Box2D browser loss remains open.
|
|
563
|
+
|
|
564
|
+
## Content Security Policy
|
|
565
|
+
|
|
566
|
+
Wasm initialization needs `'wasm-unsafe-eval'` in `script-src` on restricted pages and worker responses. Blocked compilation rejects with MargoError code `failed` and a help link. See [the exact header and package requirements](../../docs/csp.md).
|