@melonjs/rapier3d-adapter 0.0.0-stage → 1.0.1

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +21 -0
  3. package/README.md +341 -2
  4. package/build/Rapier3dAdapter.d.ts +396 -0
  5. package/build/Rapier3dAdapter.d.ts.map +1 -0
  6. package/build/Simulation.d.ts +35 -0
  7. package/build/Simulation.d.ts.map +1 -0
  8. package/build/bodies/Motion.d.ts +64 -0
  9. package/build/bodies/Motion.d.ts.map +1 -0
  10. package/build/bodies/RuntimeOverrides.d.ts +16 -0
  11. package/build/bodies/RuntimeOverrides.d.ts.map +1 -0
  12. package/build/bodies/helpers.d.ts +30 -0
  13. package/build/bodies/helpers.d.ts.map +1 -0
  14. package/build/bodies/pose.d.ts +34 -0
  15. package/build/bodies/pose.d.ts.map +1 -0
  16. package/build/colliders/CollisionFilters.d.ts +60 -0
  17. package/build/colliders/CollisionFilters.d.ts.map +1 -0
  18. package/build/colliders/footprint.d.ts +22 -0
  19. package/build/colliders/footprint.d.ts.map +1 -0
  20. package/build/colliders/shapes.d.ts +18 -0
  21. package/build/colliders/shapes.d.ts.map +1 -0
  22. package/build/colliders/types.d.ts +48 -0
  23. package/build/colliders/types.d.ts.map +1 -0
  24. package/build/contacts/ContactDispatcher.d.ts +80 -0
  25. package/build/contacts/ContactDispatcher.d.ts.map +1 -0
  26. package/build/index.d.ts +9 -0
  27. package/build/index.d.ts.map +1 -0
  28. package/build/index.js +1942 -0
  29. package/build/index.js.map +7 -0
  30. package/build/joints/Joints.d.ts +51 -0
  31. package/build/joints/Joints.d.ts.map +1 -0
  32. package/build/loader.d.ts +20 -0
  33. package/build/loader.d.ts.map +1 -0
  34. package/build/math/units.d.ts +44 -0
  35. package/build/math/units.d.ts.map +1 -0
  36. package/build/queries/queries.d.ts +40 -0
  37. package/build/queries/queries.d.ts.map +1 -0
  38. package/build/types.d.ts +77 -0
  39. package/build/types.d.ts.map +1 -0
  40. package/package.json +71 -5
package/build/index.js ADDED
@@ -0,0 +1,1942 @@
1
+ /*!
2
+ * melonJS physics adapter for Rapier 3D (WebAssembly) - 1.0.1
3
+ * http://www.melonjs.org
4
+ * @melonjs/rapier3d-adapter is licensed under the MIT License.
5
+ * http://www.opensource.org/licenses/mit-license
6
+ * @copyright (C) 2011 - 2026 Olivier Biot (AltByte Pte Ltd)
7
+ */
8
+
9
+ // src/Rapier3dAdapter.ts
10
+ import {
11
+ collision as collision2,
12
+ version as melonjsVersion,
13
+ Quaternion as Quaternion3,
14
+ state,
15
+ utils,
16
+ Vector2d,
17
+ Vector3d as Vector3d3
18
+ } from "melonjs";
19
+
20
+ // src/bodies/helpers.ts
21
+ function spliceHelpers(ctx, renderable, body, colliders) {
22
+ const { adapter, sim, motion, filters, overrides } = ctx;
23
+ const proto = sim.rapier.RigidBody.prototype;
24
+ const helpers = {
25
+ setVelocity: (x, y, z) => {
26
+ motion.setVelocity(body, x, y, z);
27
+ },
28
+ getVelocity: (out) => {
29
+ return adapter.getVelocity(renderable, out);
30
+ },
31
+ getVelocity3d: (out) => {
32
+ return adapter.getVelocity3d(renderable, out);
33
+ },
34
+ applyForce: (x, y, pointX, pointY) => {
35
+ motion.addForce(
36
+ body,
37
+ { x, y },
38
+ typeof pointX === "number" && typeof pointY === "number" ? { x: pointX, y: pointY } : void 0
39
+ );
40
+ },
41
+ applyImpulse: (x, y, z) => {
42
+ proto.applyImpulse.call(body, sim.units.inMeters(x, y, z ?? 0), true);
43
+ },
44
+ setSensor: (isSensor = true) => {
45
+ adapter.setSensor(renderable, isSensor);
46
+ },
47
+ setStatic: (isStatic = true) => {
48
+ adapter.setStatic(renderable, isStatic);
49
+ },
50
+ setCollisionMask: (mask) => {
51
+ adapter.setCollisionMask(renderable, mask);
52
+ },
53
+ setCollisionType: (type) => {
54
+ adapter.setCollisionType(renderable, type);
55
+ },
56
+ /**
57
+ * Set the body's mass, keeping how it is spread over its shapes: every
58
+ * collider's density is scaled by the same factor.
59
+ * @param m - the new mass, in kilograms
60
+ */
61
+ setMass: (m) => {
62
+ const current = body.mass();
63
+ if (current > 0) {
64
+ const k = m / current;
65
+ for (const collider of colliders) {
66
+ collider.setDensity(collider.density() * k);
67
+ }
68
+ body.recomputeMassPropertiesFromColliders();
69
+ }
70
+ },
71
+ setBounce: (r) => {
72
+ overrides.of(renderable).restitution = r;
73
+ for (const collider of colliders) {
74
+ collider.setRestitution(r);
75
+ }
76
+ },
77
+ setGravityScale: (scale) => {
78
+ adapter.setGravityScale(renderable, scale);
79
+ },
80
+ setAngle: (rad) => {
81
+ adapter.setAngle(renderable, rad);
82
+ },
83
+ getAngle: () => {
84
+ return adapter.getAngle(renderable);
85
+ },
86
+ setAngularVelocity: (omega) => {
87
+ adapter.setAngularVelocity(renderable, omega);
88
+ },
89
+ getAngularVelocity: () => {
90
+ return adapter.getAngularVelocity(renderable);
91
+ },
92
+ applyTorque: (torque) => {
93
+ adapter.applyTorque(renderable, torque);
94
+ }
95
+ };
96
+ Object.assign(body, helpers);
97
+ const first = () => {
98
+ return colliders[0];
99
+ };
100
+ Object.defineProperties(body, {
101
+ collisionType: {
102
+ get: () => {
103
+ const c = first();
104
+ return c ? filters.get(c.handle)?.category ?? 0 : 0;
105
+ },
106
+ set: (v) => {
107
+ adapter.setCollisionType(renderable, v);
108
+ },
109
+ configurable: true,
110
+ enumerable: true
111
+ },
112
+ collisionMask: {
113
+ get: () => {
114
+ const c = first();
115
+ return c ? filters.get(c.handle)?.mask ?? 0 : 0;
116
+ },
117
+ set: (v) => {
118
+ adapter.setCollisionMask(renderable, v);
119
+ },
120
+ configurable: true,
121
+ enumerable: true
122
+ }
123
+ });
124
+ }
125
+
126
+ // src/math/units.ts
127
+ function zOf(v) {
128
+ return typeof v.z === "number" ? v.z : void 0;
129
+ }
130
+ var Units = class {
131
+ pixelsPerMeter;
132
+ /**
133
+ * @param pixelsPerMeter - how many pixels make a meter
134
+ */
135
+ constructor(pixelsPerMeter) {
136
+ this.pixelsPerMeter = pixelsPerMeter;
137
+ }
138
+ /**
139
+ * @param px - a length in pixels
140
+ * @returns the same length in meters
141
+ */
142
+ toMeters(px) {
143
+ return px / this.pixelsPerMeter;
144
+ }
145
+ /**
146
+ * @param m - a length in meters
147
+ * @returns the same length in pixels
148
+ */
149
+ toPixels(m) {
150
+ return m * this.pixelsPerMeter;
151
+ }
152
+ /**
153
+ * A point or a vector in pixels, in meters.
154
+ * @param x - along X, in pixels
155
+ * @param y - along Y, in pixels
156
+ * @param z - along Z, in pixels
157
+ * @returns a new point in meters
158
+ */
159
+ inMeters(x, y, z) {
160
+ return { x: this.toMeters(x), y: this.toMeters(y), z: this.toMeters(z) };
161
+ }
162
+ };
163
+
164
+ // src/bodies/Motion.ts
165
+ var Motion = class {
166
+ /** each body's speed cap, per axis, in pixels per second */
167
+ limits = /* @__PURE__ */ new Map();
168
+ sim;
169
+ /** bodies with a force or torque to clear once the frame is stepped */
170
+ forced = /* @__PURE__ */ new Set();
171
+ /**
172
+ * @param sim - the simulation whose bodies it moves
173
+ */
174
+ constructor(sim) {
175
+ this.sim = sim;
176
+ }
177
+ /**
178
+ * Set a body's velocity in pixels per second; a `z` left out keeps the
179
+ * depth velocity.
180
+ * @param body - the body
181
+ * @param x - along X
182
+ * @param y - along Y
183
+ * @param [z] - along Z
184
+ */
185
+ setVelocity(body, x, y, z) {
186
+ const { units } = this.sim;
187
+ body.setLinvel(
188
+ {
189
+ x: units.toMeters(x),
190
+ y: units.toMeters(y),
191
+ z: typeof z === "number" ? units.toMeters(z) : body.linvel().z
192
+ },
193
+ true
194
+ );
195
+ }
196
+ /**
197
+ * Add a force for this frame, in pixels: at a world point, it also turns
198
+ * the body. A force or a point with no `z` acts in the plane of the body.
199
+ * @param body - the body
200
+ * @param force - the force
201
+ * @param [point] - where it pushes, in world pixels
202
+ */
203
+ addForce(body, force, point) {
204
+ const f = this.sim.units.inMeters(force.x, force.y, zOf(force) ?? 0);
205
+ if (point) {
206
+ body.addForceAtPoint(f, this.pointInMeters(body, point), true);
207
+ } else {
208
+ body.addForce(f, true);
209
+ }
210
+ this.forced.add(body);
211
+ }
212
+ /**
213
+ * Add a torque for this frame: a number about Z, a vector about each axis.
214
+ * In Rapier's own unit (N·m), not scaled.
215
+ * @param body - the body
216
+ * @param torque - the torque
217
+ */
218
+ addTorque(body, torque) {
219
+ body.addTorque(
220
+ typeof torque === "number" ? { x: 0, y: 0, z: torque } : { x: torque.x, y: torque.y, z: torque.z ?? 0 },
221
+ true
222
+ );
223
+ this.forced.add(body);
224
+ }
225
+ /**
226
+ * A world point in meters; one with no depth is in the plane of the body.
227
+ * @param body - the body it acts on
228
+ * @param point - the point in world pixels
229
+ * @returns the point in meters
230
+ */
231
+ pointInMeters(body, point) {
232
+ const { units } = this.sim;
233
+ const z = point.z;
234
+ return {
235
+ x: units.toMeters(point.x),
236
+ y: units.toMeters(point.y),
237
+ z: typeof z === "number" ? units.toMeters(z) : body.translation().z
238
+ };
239
+ }
240
+ /** A force is for one frame, across every sub-step: clear them all. */
241
+ clearForces() {
242
+ for (const body of this.forced) {
243
+ if (body.isValid()) {
244
+ body.resetForces(false);
245
+ body.resetTorques(false);
246
+ }
247
+ }
248
+ this.forced.clear();
249
+ }
250
+ /** Hold every capped body to its cap. */
251
+ clampVelocities() {
252
+ const { units, bodies } = this.sim;
253
+ for (const [renderable, limit] of this.limits) {
254
+ const body = bodies.get(renderable);
255
+ if (!body) continue;
256
+ const v = body.linvel();
257
+ const clamp = (value, px) => {
258
+ if (typeof px !== "number" || Number.isNaN(px)) return value;
259
+ const m = units.toMeters(Math.abs(px));
260
+ return Math.max(-m, Math.min(m, value));
261
+ };
262
+ const vx = clamp(v.x, limit.x);
263
+ const vy = clamp(v.y, limit.y);
264
+ const vz = clamp(v.z, limit.z);
265
+ if (vx !== v.x || vy !== v.y || vz !== v.z) {
266
+ body.setLinvel({ x: vx, y: vy, z: vz }, false);
267
+ }
268
+ }
269
+ }
270
+ /**
271
+ * Forget a body that left the world.
272
+ * @param renderable - its renderable
273
+ * @param body - the body
274
+ */
275
+ forget(renderable, body) {
276
+ this.forced.delete(body);
277
+ this.limits.delete(renderable);
278
+ }
279
+ /** Forget every body. */
280
+ clear() {
281
+ this.forced.clear();
282
+ this.limits.clear();
283
+ }
284
+ };
285
+
286
+ // src/bodies/pose.ts
287
+ import { Mesh, Quaternion } from "melonjs";
288
+ var _turn = new Quaternion();
289
+ function poseOf(renderable) {
290
+ return {
291
+ base: renderable.currentTransform.clone(),
292
+ bridge: renderable instanceof Mesh ? (
293
+ // a mesh turns in its source's Y-up space (see Mesh)
294
+ [1, -1, renderable.rightHanded ? -1 : 1]
295
+ ) : [1, 1, 1]
296
+ };
297
+ }
298
+ function writePose(renderable, body, pose, units) {
299
+ if (!renderable.pos) {
300
+ return;
301
+ }
302
+ const p = body.translation();
303
+ renderable.setPosition(
304
+ units.toPixels(p.x),
305
+ units.toPixels(p.y),
306
+ units.toPixels(p.z)
307
+ );
308
+ renderable.isDirty = true;
309
+ if (pose === void 0) {
310
+ return;
311
+ }
312
+ const { x, y, z, w } = body.rotation();
313
+ const [d0, d1, d2] = pose.bridge;
314
+ const det = d0 * d1 * d2;
315
+ _turn.set(det * d0 * x, det * d1 * y, det * d2 * z, w);
316
+ renderable.currentTransform.identity().rotate(_turn).multiply(pose.base);
317
+ renderable.isDirty = true;
318
+ }
319
+
320
+ // src/bodies/RuntimeOverrides.ts
321
+ var RuntimeOverrides = class extends Map {
322
+ /**
323
+ * A body's record, to write to.
324
+ * @param renderable - the body's renderable
325
+ * @returns its record, made when there is none
326
+ */
327
+ of(renderable) {
328
+ let over = this.get(renderable);
329
+ if (over === void 0) {
330
+ over = {};
331
+ this.set(renderable, over);
332
+ }
333
+ return over;
334
+ }
335
+ };
336
+
337
+ // src/colliders/CollisionFilters.ts
338
+ import { collision } from "melonjs";
339
+ var DEFAULT_CATEGORY = 1;
340
+ var CollisionFilters = class {
341
+ /** The hooks Rapier calls for a pair that needs the full 32 bits. */
342
+ hooks;
343
+ rapier;
344
+ /** collider handle -> its type and mask */
345
+ filters = /* @__PURE__ */ new Map();
346
+ /**
347
+ * @param rapier - the Rapier module
348
+ */
349
+ constructor(rapier2) {
350
+ this.rapier = rapier2;
351
+ const computeImpulse = rapier2.SolverFlags.COMPUTE_IMPULSE;
352
+ this.hooks = {
353
+ filterContactPair: (c1, c2) => {
354
+ return this.passes(c1, c2) ? computeImpulse : null;
355
+ },
356
+ filterIntersectionPair: (c1, c2) => {
357
+ return this.passes(c1, c2);
358
+ }
359
+ };
360
+ }
361
+ /**
362
+ * A collider's type and mask.
363
+ * @param handle - the collider handle
364
+ * @returns its filter, if it has one
365
+ */
366
+ get(handle) {
367
+ return this.filters.get(handle);
368
+ }
369
+ /**
370
+ * Give a collider its melonJS collision type and mask.
371
+ * @param collider - the collider to configure
372
+ * @param category - its collision type
373
+ * @param mask - the collision types it collides with
374
+ */
375
+ apply(collider, category, mask) {
376
+ this.filters.set(collider.handle, { category, mask });
377
+ const { ActiveHooks } = this.rapier;
378
+ const needsHooks = category >>> 16 !== 0 || mask >>> 16 !== 0 && (mask & 65535) === 0;
379
+ if (needsHooks) {
380
+ collider.setCollisionGroups(4294967295);
381
+ collider.setActiveHooks(
382
+ ActiveHooks.FILTER_CONTACT_PAIRS | ActiveHooks.FILTER_INTERSECTION_PAIRS
383
+ );
384
+ } else {
385
+ collider.setCollisionGroups(
386
+ ((category & 65535) << 16 | mask & 65535) >>> 0
387
+ );
388
+ collider.setActiveHooks(ActiveHooks.NONE);
389
+ }
390
+ }
391
+ /**
392
+ * Change the type and/or the mask of several colliders.
393
+ * @param colliders - the colliders
394
+ * @param category - the new type, or undefined to keep each collider's
395
+ * @param mask - the new mask, or undefined to keep each collider's
396
+ */
397
+ update(colliders, category, mask) {
398
+ for (const collider of colliders) {
399
+ const current = this.filters.get(collider.handle);
400
+ this.apply(
401
+ collider,
402
+ category ?? current?.category ?? DEFAULT_CATEGORY,
403
+ mask ?? current?.mask ?? collision.types.ALL_OBJECT
404
+ );
405
+ }
406
+ }
407
+ /**
408
+ * Forget a collider that left the world.
409
+ * @param handle - its handle
410
+ */
411
+ forget(handle) {
412
+ this.filters.delete(handle);
413
+ }
414
+ /** Forget every collider. */
415
+ clear() {
416
+ this.filters.clear();
417
+ }
418
+ /**
419
+ * Whether two colliders collide, by their full 32-bit types and masks.
420
+ * @param c1 - a collider handle
421
+ * @param c2 - the other
422
+ * @returns true when each one's mask includes the other's type
423
+ */
424
+ passes(c1, c2) {
425
+ const f1 = this.filters.get(c1);
426
+ const f2 = this.filters.get(c2);
427
+ if (f1 === void 0 || f2 === void 0) {
428
+ return true;
429
+ }
430
+ return (f1.mask & f2.category) !== 0 && (f2.mask & f1.category) !== 0;
431
+ }
432
+ };
433
+
434
+ // src/colliders/footprint.ts
435
+ function emptyFootprint() {
436
+ return [Infinity, Infinity, -Infinity, -Infinity];
437
+ }
438
+ function growFootprint(entry, q, box) {
439
+ const { min, max, round } = entry;
440
+ const r = round?.r ?? 0;
441
+ const { x, y, z, w } = q;
442
+ const r00 = 1 - 2 * (y * y + z * z);
443
+ const r01 = 2 * (x * y - w * z);
444
+ const r02 = 2 * (x * z + w * y);
445
+ const r10 = 2 * (x * y + w * z);
446
+ const r11 = 1 - 2 * (x * x + z * z);
447
+ const r12 = 2 * (y * z - w * x);
448
+ for (let i = 0; i < (round ? 2 : 8); i++) {
449
+ let px;
450
+ let py;
451
+ let pz;
452
+ if (round) {
453
+ const end = i === 0 ? round.a : round.b;
454
+ px = end.x;
455
+ py = end.y;
456
+ pz = end.z;
457
+ } else {
458
+ px = i & 1 ? max.x : min.x;
459
+ py = i & 2 ? max.y : min.y;
460
+ pz = i & 4 ? max.z : min.z;
461
+ }
462
+ const tx = r00 * px + r01 * py + r02 * pz;
463
+ const ty = r10 * px + r11 * py + r12 * pz;
464
+ if (tx - r < box[0]) box[0] = tx - r;
465
+ if (ty - r < box[1]) box[1] = ty - r;
466
+ if (tx + r > box[2]) box[2] = tx + r;
467
+ if (ty + r > box[3]) box[3] = ty + r;
468
+ }
469
+ }
470
+
471
+ // src/colliders/shapes.ts
472
+ import {
473
+ Box3d,
474
+ Capsule3d,
475
+ ConvexHull3d,
476
+ Sphere,
477
+ TriangleMesh3d
478
+ } from "melonjs";
479
+ function unsupportedShapeMessage(shape) {
480
+ const name = shape.type ?? shape.constructor.name;
481
+ return `Rapier3dAdapter: unsupported shape type ${name}. A 3D world needs a shape with depth: this adapter builds colliders from Box3d, Sphere, Capsule3d, ConvexHull3d and TriangleMesh3d. A Rect becomes a Box3d of the same footprint, an Ellipse a Sphere.`;
482
+ }
483
+ function buildColliderParts(rapier2, units, shapes) {
484
+ const parts = [];
485
+ for (const [index, shape] of shapes.entries()) {
486
+ if (shape.isActive === false) {
487
+ continue;
488
+ }
489
+ parts.push({ shape, index, ...shapeToCollider(rapier2, units, shape) });
490
+ }
491
+ return parts;
492
+ }
493
+ function shapeToCollider(rapier2, units, shape) {
494
+ const { ColliderDesc } = rapier2;
495
+ const m = (px) => {
496
+ return units.toMeters(px);
497
+ };
498
+ const box = (c, hx, hy, hz) => {
499
+ return {
500
+ min: { x: c.x - hx, y: c.y - hy, z: c.z - hz },
501
+ max: { x: c.x + hx, y: c.y + hy, z: c.z + hz }
502
+ };
503
+ };
504
+ const at = (desc, c) => {
505
+ return desc.setTranslation(m(c.x), m(c.y), m(c.z));
506
+ };
507
+ if (shape instanceof Box3d) {
508
+ const h = shape.halfExtents;
509
+ return {
510
+ desc: at(ColliderDesc.cuboid(m(h.x), m(h.y), m(h.z)), shape.pos),
511
+ ...box(shape.pos, h.x, h.y, h.z)
512
+ };
513
+ }
514
+ if (shape instanceof Sphere) {
515
+ const r = shape.radius;
516
+ const { x, y, z } = shape.pos;
517
+ return {
518
+ desc: at(ColliderDesc.ball(m(r)), shape.pos),
519
+ ...box(shape.pos, r, r, r),
520
+ round: { a: { x, y, z }, b: { x, y, z }, r }
521
+ };
522
+ }
523
+ if (shape instanceof Capsule3d) {
524
+ const r = shape.radius;
525
+ const half = shape.halfSegment;
526
+ const { x, y, z } = shape.pos;
527
+ return {
528
+ desc: at(ColliderDesc.capsule(m(half), m(r)), shape.pos),
529
+ ...box(shape.pos, r, half + r, r),
530
+ round: { a: { x, y: y - half, z }, b: { x, y: y + half, z }, r }
531
+ };
532
+ }
533
+ if (shape instanceof TriangleMesh3d || shape instanceof ConvexHull3d) {
534
+ const source = shape instanceof TriangleMesh3d ? shape.vertices : shape.points;
535
+ const meters = new Float32Array(source.length);
536
+ const { x: ox, y: oy, z: oz } = shape.pos;
537
+ for (let i = 0; i < source.length; i += 3) {
538
+ meters[i] = m(source[i] + ox);
539
+ meters[i + 1] = m(source[i + 1] + oy);
540
+ meters[i + 2] = m(source[i + 2] + oz);
541
+ }
542
+ const b = shape.getBounds3d();
543
+ const bounds = {
544
+ min: { x: b.min.x, y: b.min.y, z: b.min.z },
545
+ max: { x: b.max.x, y: b.max.y, z: b.max.z }
546
+ };
547
+ if (shape instanceof TriangleMesh3d) {
548
+ return { desc: ColliderDesc.trimesh(meters, shape.indices), ...bounds };
549
+ }
550
+ const hull = ColliderDesc.convexHull(meters);
551
+ if (hull !== null) {
552
+ return { desc: hull, ...bounds };
553
+ }
554
+ const c = {
555
+ x: (bounds.min.x + bounds.max.x) / 2,
556
+ y: (bounds.min.y + bounds.max.y) / 2,
557
+ z: (bounds.min.z + bounds.max.z) / 2
558
+ };
559
+ const half = (lo, hi) => {
560
+ return Math.max((hi - lo) / 2, 0.5);
561
+ };
562
+ const hx = half(bounds.min.x, bounds.max.x);
563
+ const hy = half(bounds.min.y, bounds.max.y);
564
+ const hz = half(bounds.min.z, bounds.max.z);
565
+ return {
566
+ desc: at(ColliderDesc.cuboid(m(hx), m(hy), m(hz)), c),
567
+ ...box(c, hx, hy, hz)
568
+ };
569
+ }
570
+ throw new Error(unsupportedShapeMessage(shape));
571
+ }
572
+
573
+ // src/contacts/ContactDispatcher.ts
574
+ var SIDE_A = 1;
575
+ var SIDE_B = 2;
576
+ var SHAPE_A = 4;
577
+ var SHAPE_B = 8;
578
+ var EVERY_SIDE = SIDE_A | SIDE_B | SHAPE_A | SHAPE_B;
579
+ function pairKey(h1, h2) {
580
+ return h1 < h2 ? `${h1}:${h2}` : `${h2}:${h1}`;
581
+ }
582
+ var ContactDispatcher = class {
583
+ /** touching pairs, from Rapier's start events until their end */
584
+ activePairs = /* @__PURE__ */ new Map();
585
+ sim;
586
+ eventQueue;
587
+ /** a step's events, collected before any is dispatched */
588
+ pendingEvents = [];
589
+ /** the pairs whose start or active hooks are running, innermost last */
590
+ dispatching = [];
591
+ /**
592
+ * @param sim - the simulation it reports on
593
+ */
594
+ constructor(sim) {
595
+ this.sim = sim;
596
+ }
597
+ /**
598
+ * The queue Rapier writes a step's start and end events to.
599
+ * @returns the event queue to pass to `world.step`
600
+ */
601
+ get queue() {
602
+ return this.eventQueue;
603
+ }
604
+ /** Make the event queue, with the Rapier world. */
605
+ open() {
606
+ this.eventQueue = new this.sim.rapier.EventQueue(true);
607
+ }
608
+ /** Free the event queue, and forget every pair. */
609
+ close() {
610
+ this.eventQueue.free();
611
+ this.activePairs.clear();
612
+ this.pendingEvents.length = 0;
613
+ this.dispatching.length = 0;
614
+ }
615
+ /**
616
+ * Dispatch the start and end events Rapier queued during the last step.
617
+ * They are all read before any is dispatched, so a handler that removes a
618
+ * body cannot disturb the queue.
619
+ */
620
+ dispatchQueuedEvents() {
621
+ const events = this.pendingEvents;
622
+ events.length = 0;
623
+ this.eventQueue.drainCollisionEvents((h1, h2, started) => {
624
+ events.push(h1, h2, started ? 1 : 0);
625
+ });
626
+ for (let i = 0; i < events.length; i += 3) {
627
+ const h1 = events[i];
628
+ const h2 = events[i + 1];
629
+ const key = pairKey(h1, h2);
630
+ if (events[i + 2] === 1) {
631
+ if (this.sim.colliders.has(h1) && this.sim.colliders.has(h2)) {
632
+ this.activePairs.set(key, [h1, h2]);
633
+ this.dispatchPair(h1, h2, "start");
634
+ }
635
+ } else if (this.activePairs.delete(key)) {
636
+ this.dispatchPair(h1, h2, "end");
637
+ }
638
+ }
639
+ }
640
+ /** Once per frame: the active hooks of every pair still touching. */
641
+ dispatchActiveContacts() {
642
+ for (const [h1, h2] of this.activePairs.values()) {
643
+ this.dispatchPair(h1, h2, "active");
644
+ }
645
+ }
646
+ /**
647
+ * Tell the pairs touching colliders that are about to go that their
648
+ * contact ended. The colliders must still be known: forget them after.
649
+ * @param colliders - the colliders leaving the world
650
+ */
651
+ endContacts(colliders) {
652
+ const handles = new Set(
653
+ colliders.map((c) => {
654
+ return c.handle;
655
+ })
656
+ );
657
+ for (const d of this.dispatching) {
658
+ const going = (handles.has(d.h1) ? SIDE_A | SHAPE_A : 0) | (handles.has(d.h2) ? SIDE_B | SHAPE_B : 0);
659
+ if (going !== 0 && (this.activePairs.delete(d.key) || d.ended)) {
660
+ d.ended = true;
661
+ const sides = going & d.reached & ~d.told;
662
+ d.told |= sides;
663
+ this.dispatch(d.e1, d.e2, d.h1, d.h2, "end", sides);
664
+ }
665
+ }
666
+ for (const [key, [h1, h2]] of this.activePairs) {
667
+ if (handles.has(h1) || handles.has(h2)) {
668
+ this.activePairs.delete(key);
669
+ this.dispatchPair(h1, h2, "end");
670
+ }
671
+ }
672
+ }
673
+ /**
674
+ * Fire the hooks of one pair of colliders, on both renderables. A start or
675
+ * active hook may take a body of the pair out: see {@link Dispatch}.
676
+ * @param h1 - the first collider handle
677
+ * @param h2 - the second
678
+ * @param phase - which lifecycle hook to fire
679
+ */
680
+ dispatchPair(h1, h2, phase) {
681
+ const e1 = this.sim.colliders.get(h1);
682
+ const e2 = this.sim.colliders.get(h2);
683
+ if (e1 === void 0 || e2 === void 0) return;
684
+ if (phase === "end") {
685
+ this.dispatch(e1, e2, h1, h2, phase, EVERY_SIDE);
686
+ return;
687
+ }
688
+ const current = {
689
+ key: pairKey(h1, h2),
690
+ h1,
691
+ h2,
692
+ e1,
693
+ e2,
694
+ // a pair already active had its start on every side
695
+ reached: phase === "start" ? 0 : EVERY_SIDE,
696
+ told: 0,
697
+ ended: false
698
+ };
699
+ this.dispatching.push(current);
700
+ try {
701
+ this.dispatch(
702
+ e1,
703
+ e2,
704
+ h1,
705
+ h2,
706
+ phase,
707
+ EVERY_SIDE,
708
+ phase === "start" ? current : void 0
709
+ );
710
+ } finally {
711
+ this.dispatching.splice(this.dispatching.indexOf(current), 1);
712
+ }
713
+ if (current.ended) {
714
+ this.dispatch(e1, e2, h1, h2, "end", current.reached & ~current.told);
715
+ }
716
+ }
717
+ /**
718
+ * Fire one phase of a pair's hooks: the shape-level ones, then the
719
+ * renderables' own. A renderable whose body is gone hears nothing.
720
+ * @param e1 - the first collider's entry
721
+ * @param e2 - the second collider's entry
722
+ * @param h1 - the first collider handle
723
+ * @param h2 - the second
724
+ * @param phase - which lifecycle hook to fire
725
+ * @param sides - the sides and levels to fire it on, as bits
726
+ * @param [record] - where to note each side reached, before its hook runs
727
+ */
728
+ dispatch(e1, e2, h1, h2, phase, sides, record) {
729
+ const rA = e1.renderable;
730
+ const rB = e2.renderable;
731
+ const ancA = rA.ancestor;
732
+ const ancB = rB.ancestor;
733
+ const aDetached = ancA === null;
734
+ const bDetached = ancB === null;
735
+ if (phase === "end") {
736
+ if (aDetached && bDetached) return;
737
+ } else if (aDetached || bDetached) {
738
+ return;
739
+ }
740
+ const reaches = (side, receiver, detached) => {
741
+ if ((sides & side) === 0 || detached || !this.sim.bodies.has(receiver)) {
742
+ return false;
743
+ }
744
+ if (record !== void 0) {
745
+ record.reached |= side;
746
+ }
747
+ return true;
748
+ };
749
+ const { nx, ny, nz, depth } = phase === "end" ? { nx: 0, ny: 0, nz: 0, depth: 0 } : this.contact(h1, h2);
750
+ const shapeMethod = phase === "start" ? "onShapeCollisionStart" : phase === "end" ? "onShapeCollisionEnd" : "onShapeCollisionActive";
751
+ const isTrigger = e1.shape.isTrigger === true || e2.shape.isTrigger === true;
752
+ const emitShape = (own, other, sign) => {
753
+ const receiver = own.renderable;
754
+ const fn = receiver[shapeMethod];
755
+ if (typeof fn !== "function") return;
756
+ const ownNx = sign * nx + 0;
757
+ const ownNy = sign * ny + 0;
758
+ const ownNz = sign * nz + 0;
759
+ fn.call(
760
+ receiver,
761
+ {
762
+ a: receiver,
763
+ b: other.renderable,
764
+ shapeA: own.shape,
765
+ shapeB: other.shape,
766
+ indexShapeA: own.index,
767
+ indexShapeB: other.index,
768
+ isTrigger,
769
+ depth,
770
+ overlap: depth,
771
+ normal: { x: ownNx, y: ownNy },
772
+ normalZ: ownNz,
773
+ // the SAT fields, in the builtin's convention
774
+ overlapN: { x: -ownNx + 0, y: -ownNy + 0 },
775
+ overlapNZ: -ownNz + 0,
776
+ overlapV: { x: -ownNx * depth + 0, y: -ownNy * depth + 0 },
777
+ overlapZ: -ownNz * depth + 0
778
+ },
779
+ other.renderable
780
+ );
781
+ };
782
+ if (reaches(SHAPE_A, rA, aDetached)) {
783
+ emitShape(e1, e2, -1);
784
+ }
785
+ if (reaches(SHAPE_B, rB, bDetached)) {
786
+ emitShape(e2, e1, 1);
787
+ }
788
+ const bodyMethod = (receiver) => {
789
+ if (phase === "start") return "onCollisionStart";
790
+ if (phase === "end") return "onCollisionEnd";
791
+ return typeof receiver.onCollisionActive === "function" ? "onCollisionActive" : "onCollision";
792
+ };
793
+ const pair = { collider1: h1, collider2: h2 };
794
+ const emit = (receiver, other, sign) => {
795
+ const fn = receiver[bodyMethod(receiver)];
796
+ if (typeof fn !== "function") return;
797
+ fn.call(
798
+ receiver,
799
+ {
800
+ a: receiver,
801
+ b: other,
802
+ normal: { x: sign * nx + 0, y: sign * ny + 0, z: sign * nz + 0 },
803
+ depth,
804
+ pair
805
+ },
806
+ other
807
+ );
808
+ };
809
+ if (reaches(SIDE_A, rA, aDetached)) {
810
+ emit(rA, rB, -1);
811
+ }
812
+ if (reaches(SIDE_B, rB, bDetached)) {
813
+ emit(rB, rA, 1);
814
+ }
815
+ }
816
+ /**
817
+ * The contact between two colliders: the normal from the first to the
818
+ * second, and how deep they overlap, in pixels. Zero for a sensor pair,
819
+ * which Rapier computes no contact for.
820
+ * @param h1 - the first collider handle
821
+ * @param h2 - the second
822
+ * @returns the normal and the depth
823
+ */
824
+ contact(h1, h2) {
825
+ const { world, units } = this.sim;
826
+ const c1 = world.getCollider(h1);
827
+ const c2 = world.getCollider(h2);
828
+ let nx = 0;
829
+ let ny = 0;
830
+ let nz = 0;
831
+ let depth = 0;
832
+ if (c1.isSensor() || c2.isSensor()) {
833
+ return { nx, ny, nz, depth };
834
+ }
835
+ world.contactPair(c1, c2, (manifold, flipped) => {
836
+ const count = manifold.numContacts();
837
+ if (count === 0) return;
838
+ const n = manifold.normal();
839
+ let deepest = 0;
840
+ for (let i = 0; i < count; i++) {
841
+ const d = -manifold.contactDist(i);
842
+ if (d > deepest) deepest = d;
843
+ }
844
+ if (deepest >= depth) {
845
+ depth = deepest;
846
+ const s = flipped ? -1 : 1;
847
+ nx = s * n.x;
848
+ ny = s * n.y;
849
+ nz = s * n.z;
850
+ }
851
+ });
852
+ return { nx, ny, nz, depth: units.toPixels(depth) };
853
+ }
854
+ };
855
+
856
+ // src/joints/Joints.ts
857
+ import { Quaternion as Quaternion2, Vector3d } from "melonjs";
858
+ var NO_TURN = { x: 0, y: 0, z: 0, w: 1 };
859
+ var Joints = class {
860
+ sim;
861
+ /** the joints made here that are still alive */
862
+ made = /* @__PURE__ */ new Set();
863
+ /**
864
+ * @param sim - the simulation whose bodies it joins
865
+ */
866
+ constructor(sim) {
867
+ this.sim = sim;
868
+ }
869
+ /**
870
+ * Make a joint between two bodies. Anchors are in each renderable's own
871
+ * space, relative to its `pos`, in pixels, and the axis in `a`'s; a `z`
872
+ * left out is `0`.
873
+ * @param def - what to join, and how, in pixels and radians
874
+ * @returns the Rapier joint
875
+ */
876
+ add(def) {
877
+ const { bodies, rapier: rapier2, units, world } = this.sim;
878
+ const bodyA = bodies.get(def.a);
879
+ const bodyB = bodies.get(def.b);
880
+ if (bodyA === void 0 || bodyB === void 0) {
881
+ throw new Error(
882
+ "@melonjs/rapier3d-adapter: addJoint() needs both renderables to have a body in the world; add them with addChild() first."
883
+ );
884
+ }
885
+ const { JointData } = rapier2;
886
+ const anchorB = this.localAnchor(def.anchorB);
887
+ const anchorA = def.anchorA === void 0 && def.type !== "rope" ? localPoint(bodyA, worldPoint(bodyB, anchorB)) : this.localAnchor(def.anchorA);
888
+ def.anchorA ??= {
889
+ x: units.toPixels(anchorA.x),
890
+ y: units.toPixels(anchorA.y),
891
+ z: units.toPixels(anchorA.z)
892
+ };
893
+ def.anchorB ??= { x: 0, y: 0, z: 0 };
894
+ const aInB = turnOf(bodyB).invert().multiply(turnOf(bodyA));
895
+ let data;
896
+ switch (def.type) {
897
+ case "hinge": {
898
+ const axis = unitAxis(def.axis, { x: 0, y: 0, z: 1 });
899
+ data = JointData.revoluteWithAxes(
900
+ anchorA,
901
+ anchorB,
902
+ axis,
903
+ aInB.apply(new Vector3d(axis.x, axis.y, axis.z))
904
+ );
905
+ break;
906
+ }
907
+ case "rope": {
908
+ if (def.maxLength === void 0) {
909
+ const pa = worldPoint(bodyA, anchorA);
910
+ const pb = worldPoint(bodyB, anchorB);
911
+ def.maxLength = units.toPixels(
912
+ Math.hypot(pb.x - pa.x, pb.y - pa.y, pb.z - pa.z)
913
+ );
914
+ }
915
+ data = JointData.rope(units.toMeters(def.maxLength), anchorA, anchorB);
916
+ break;
917
+ }
918
+ case "weld":
919
+ data = JointData.fixed(anchorA, NO_TURN, anchorB, aInB);
920
+ break;
921
+ case "slider":
922
+ data = JointData.prismatic(
923
+ anchorA,
924
+ anchorB,
925
+ unitAxis(def.axis, { x: 1, y: 0, z: 0 })
926
+ );
927
+ break;
928
+ default:
929
+ throw new Error(
930
+ `@melonjs/rapier3d-adapter: unknown joint type "${String(def.type)}"; use "hinge", "rope", "weld" or "slider".`
931
+ );
932
+ }
933
+ const joint = world.createImpulseJoint(data, bodyA, bodyB, true);
934
+ if (def.type === "slider") {
935
+ const frame = joint.frameX1();
936
+ joint.setFrameX2(
937
+ aInB.clone().multiply(new Quaternion2(frame.x, frame.y, frame.z, frame.w))
938
+ );
939
+ }
940
+ joint.setContactsEnabled(def.collideConnected === true);
941
+ if (def.limits !== void 0 && (def.type === "hinge" || def.type === "slider")) {
942
+ const scale = def.type === "slider" ? 1 / units.pixelsPerMeter : 1;
943
+ joint.setLimits(
944
+ def.limits.min * scale,
945
+ def.limits.max * scale
946
+ );
947
+ }
948
+ this.made.add(joint);
949
+ return joint;
950
+ }
951
+ /**
952
+ * Remove a joint made here. A joint already gone, with one of its bodies,
953
+ * is ignored.
954
+ * @param joint - the Rapier joint
955
+ */
956
+ remove(joint) {
957
+ if (this.made.delete(joint) && joint.isValid()) {
958
+ this.sim.world.removeImpulseJoint(joint, true);
959
+ }
960
+ }
961
+ /**
962
+ * Forget the joints of a body about to be removed: Rapier removes them
963
+ * with it.
964
+ * @param body - the body
965
+ */
966
+ forgetJointsOf(body) {
967
+ for (const joint of this.made) {
968
+ if (!joint.isValid() || joint.body1().handle === body.handle || joint.body2().handle === body.handle) {
969
+ this.made.delete(joint);
970
+ }
971
+ }
972
+ }
973
+ /** Forget every joint. */
974
+ clear() {
975
+ this.made.clear();
976
+ }
977
+ /**
978
+ * A joint anchor in pixels as a point on its body in meters. No anchor is
979
+ * the body's origin, its renderable's `pos`.
980
+ * @param anchor - the anchor in pixels, or undefined
981
+ * @returns the body-local anchor
982
+ */
983
+ localAnchor(anchor) {
984
+ if (anchor === void 0) {
985
+ return { x: 0, y: 0, z: 0 };
986
+ }
987
+ return this.sim.units.inMeters(anchor.x, anchor.y, anchor.z ?? 0);
988
+ }
989
+ };
990
+ function unitAxis(axis, fallback) {
991
+ if (axis === void 0) {
992
+ return fallback;
993
+ }
994
+ const z = axis.z ?? 0;
995
+ const length = Math.hypot(axis.x, axis.y, z);
996
+ if (!(length > 0) || !Number.isFinite(length)) {
997
+ throw new Error(
998
+ "@melonjs/rapier3d-adapter: a joint axis needs a length; got a zero or non-finite vector."
999
+ );
1000
+ }
1001
+ return { x: axis.x / length, y: axis.y / length, z: z / length };
1002
+ }
1003
+ function localPoint(body, world) {
1004
+ const t = body.translation();
1005
+ return turnOf(body).applyInverse(
1006
+ new Vector3d(world.x - t.x, world.y - t.y, world.z - t.z)
1007
+ );
1008
+ }
1009
+ function worldPoint(body, local) {
1010
+ const t = body.translation();
1011
+ const p = turnOf(body).apply(new Vector3d(local.x, local.y, local.z));
1012
+ return { x: t.x + p.x, y: t.y + p.y, z: t.z + p.z };
1013
+ }
1014
+ function turnOf(body) {
1015
+ const q = body.rotation();
1016
+ return new Quaternion2(q.x, q.y, q.z, q.w);
1017
+ }
1018
+
1019
+ // src/loader.ts
1020
+ var rapier;
1021
+ var loading;
1022
+ function loadRapier() {
1023
+ loading ??= import("@dimforge/rapier3d-compat").then(async (module) => {
1024
+ await module.init();
1025
+ rapier = module;
1026
+ }).catch((error) => {
1027
+ loading = void 0;
1028
+ throw error;
1029
+ });
1030
+ return loading;
1031
+ }
1032
+ function loadedRapier() {
1033
+ return rapier;
1034
+ }
1035
+
1036
+ // src/queries/queries.ts
1037
+ import {
1038
+ Sphere as Sphere2,
1039
+ Vector3d as Vector3d2
1040
+ } from "melonjs";
1041
+ var GROUND_NORMAL_Y = 0.1;
1042
+ var QUERY_HALF_DEPTH = 1e7;
1043
+ function raycast3d(sim, from, to) {
1044
+ if (!sim.alive) return null;
1045
+ const { units, world } = sim;
1046
+ const origin = units.inMeters(from.x, from.y, from.z);
1047
+ const dir = units.inMeters(to.x - from.x, to.y - from.y, to.z - from.z);
1048
+ if (dir.x === 0 && dir.y === 0 && dir.z === 0) return null;
1049
+ const ray = new sim.rapier.Ray(origin, dir);
1050
+ const hit = world.castRayAndGetNormal(
1051
+ ray,
1052
+ 1,
1053
+ true,
1054
+ void 0,
1055
+ void 0,
1056
+ void 0,
1057
+ void 0,
1058
+ (collider) => {
1059
+ return !collider.containsPoint(origin);
1060
+ }
1061
+ );
1062
+ if (hit === null) return null;
1063
+ const entry = sim.colliders.get(hit.collider.handle);
1064
+ if (entry === void 0) return null;
1065
+ const toi = hit.timeOfImpact;
1066
+ return {
1067
+ renderable: entry.renderable,
1068
+ point: new Vector3d2(
1069
+ units.toPixels(origin.x + dir.x * toi),
1070
+ units.toPixels(origin.y + dir.y * toi),
1071
+ units.toPixels(origin.z + dir.z * toi)
1072
+ ),
1073
+ normal: new Vector3d2(hit.normal.x, hit.normal.y, hit.normal.z),
1074
+ fraction: toi
1075
+ };
1076
+ }
1077
+ function queryAABB(sim, rect) {
1078
+ const { units, world } = sim;
1079
+ const { x, y } = rect.pos;
1080
+ return collect(sim, (visit) => {
1081
+ world.collidersWithAabbIntersectingAabb(
1082
+ {
1083
+ x: units.toMeters(x + rect.width / 2),
1084
+ y: units.toMeters(y + rect.height / 2),
1085
+ z: 0
1086
+ },
1087
+ {
1088
+ x: units.toMeters(rect.width / 2),
1089
+ y: units.toMeters(rect.height / 2),
1090
+ z: QUERY_HALF_DEPTH
1091
+ },
1092
+ (collider) => {
1093
+ const entry = sim.colliders.get(collider.handle);
1094
+ const body = collider.parent();
1095
+ if (entry === void 0 || body === null) return true;
1096
+ const box = emptyFootprint();
1097
+ growFootprint(entry, body.rotation(), box);
1098
+ const t = body.translation();
1099
+ const bx = units.toPixels(t.x);
1100
+ const by = units.toPixels(t.y);
1101
+ return bx + box[0] <= x + rect.width && bx + box[2] >= x && by + box[1] <= y + rect.height && by + box[3] >= y ? visit(collider) : true;
1102
+ }
1103
+ );
1104
+ });
1105
+ }
1106
+ function querySphere(sim, center, radius) {
1107
+ const { units } = sim;
1108
+ const isSphere = center instanceof Sphere2;
1109
+ const c = isSphere ? center.pos : center;
1110
+ const r = isSphere ? center.radius : radius ?? 0;
1111
+ const ball = new sim.rapier.Ball(units.toMeters(Math.max(r, 0)));
1112
+ return collect(sim, (visit) => {
1113
+ sim.world.intersectionsWithShape(
1114
+ units.inMeters(c.x, c.y, c.z),
1115
+ { x: 0, y: 0, z: 0, w: 1 },
1116
+ ball,
1117
+ visit
1118
+ );
1119
+ });
1120
+ }
1121
+ function isGrounded(sim, renderable) {
1122
+ const body = sim.bodies.get(renderable);
1123
+ if (!body) return false;
1124
+ const { world } = sim;
1125
+ const bodyY = body.translation().y;
1126
+ for (const collider of sim.collidersOf.get(renderable) ?? []) {
1127
+ let grounded = false;
1128
+ world.intersectionPairsWith(collider, (other) => {
1129
+ const parent = other.parent();
1130
+ if (!grounded && parent !== null && world.intersectionPair(collider, other) && parent.translation().y > bodyY) {
1131
+ grounded = true;
1132
+ }
1133
+ });
1134
+ world.contactPairsWith(collider, (other) => {
1135
+ if (grounded) return;
1136
+ world.contactPair(collider, other, (manifold, flipped) => {
1137
+ if (manifold.numContacts() === 0) return;
1138
+ const ny = flipped ? -manifold.normal().y : manifold.normal().y;
1139
+ if (-ny < -GROUND_NORMAL_Y) {
1140
+ grounded = true;
1141
+ }
1142
+ });
1143
+ });
1144
+ if (grounded) return true;
1145
+ }
1146
+ return false;
1147
+ }
1148
+ function collect(sim, query) {
1149
+ const result = [];
1150
+ if (!sim.alive) return result;
1151
+ const seen = /* @__PURE__ */ new Set();
1152
+ query((collider) => {
1153
+ const entry = sim.colliders.get(collider.handle);
1154
+ if (entry !== void 0 && !seen.has(entry.renderable)) {
1155
+ seen.add(entry.renderable);
1156
+ result.push(entry.renderable);
1157
+ }
1158
+ return true;
1159
+ });
1160
+ return result;
1161
+ }
1162
+
1163
+ // src/Simulation.ts
1164
+ var Simulation = class {
1165
+ rapier;
1166
+ units;
1167
+ /** The Rapier world: made by {@link open}, freed by {@link close}. */
1168
+ world;
1169
+ /** true between {@link open} and {@link close}: the Rapier world exists */
1170
+ alive = false;
1171
+ /** each renderable's body */
1172
+ bodies = /* @__PURE__ */ new Map();
1173
+ /** each renderable's colliders, one per active shape */
1174
+ collidersOf = /* @__PURE__ */ new Map();
1175
+ /** collider handle -> its renderable, shape and box */
1176
+ colliders = /* @__PURE__ */ new Map();
1177
+ /**
1178
+ * @param rapier - the loaded Rapier module
1179
+ * @param units - the scale between pixels and meters
1180
+ */
1181
+ constructor(rapier2, units) {
1182
+ this.rapier = rapier2;
1183
+ this.units = units;
1184
+ }
1185
+ /**
1186
+ * Make the Rapier world.
1187
+ * @param gravity - its gravity, in meters per second²
1188
+ */
1189
+ open(gravity) {
1190
+ this.world = new this.rapier.World(gravity);
1191
+ this.alive = true;
1192
+ }
1193
+ /** Free the Rapier world, and forget every body and collider. */
1194
+ close() {
1195
+ this.alive = false;
1196
+ this.world.free();
1197
+ this.bodies.clear();
1198
+ this.collidersOf.clear();
1199
+ this.colliders.clear();
1200
+ }
1201
+ };
1202
+
1203
+ // src/types.ts
1204
+ var REQUIRED_MELONJS_VERSION = "20.16.0";
1205
+
1206
+ // src/Rapier3dAdapter.ts
1207
+ var _turn2 = new Quaternion3();
1208
+ var Rapier3dAdapter = class {
1209
+ physicLabel = "rapier3d";
1210
+ name = "@melonjs/rapier3d-adapter";
1211
+ version = "1.0.1";
1212
+ url = "https://www.npmjs.com/package/@melonjs/rapier3d-adapter";
1213
+ capabilities = {
1214
+ constraints: true,
1215
+ // opt-in per body: `(body as Rapier3dAdapter.Body).enableCcd(true)`
1216
+ continuousCollisionDetection: true,
1217
+ sleepingBodies: true,
1218
+ // a 3D world is queried with `raycast3d`
1219
+ raycasts: false,
1220
+ raycasts3d: true,
1221
+ velocityLimit: true,
1222
+ isGrounded: true,
1223
+ bodies3d: true
1224
+ };
1225
+ /**
1226
+ * World gravity, in pixels per second². Change it at any time; read at
1227
+ * every step.
1228
+ */
1229
+ gravity;
1230
+ /**
1231
+ * The Rapier module: an escape hatch for what the portable
1232
+ * {@link PhysicsAdapter} interface does not cover (other joints, the
1233
+ * character controller, native queries). See the README.
1234
+ * @see {@link https://rapier.rs/docs/user_guides/javascript/getting_started_js Rapier JavaScript user guide}
1235
+ */
1236
+ rapier;
1237
+ /** Spatial conversion factor between melonJS pixels and Rapier meters. */
1238
+ pixelsPerMeter;
1239
+ /** Back-reference to the owning melonJS world (set in {@link init}). */
1240
+ melonWorld;
1241
+ subSteps;
1242
+ sim;
1243
+ filters;
1244
+ contacts;
1245
+ motion;
1246
+ joints;
1247
+ /** what was set on every collider of a body at run time */
1248
+ overrides = new RuntimeOverrides();
1249
+ /** each body's definition, which `updateShape()` builds from again */
1250
+ defs = /* @__PURE__ */ new Map();
1251
+ /** each renderable's transform when its body was made, and its bridge */
1252
+ poses = /* @__PURE__ */ new Map();
1253
+ /** the shapes {@link Rapier3dAdapter.getBodyShapes} reports */
1254
+ reportedShapes = /* @__PURE__ */ new Map();
1255
+ /**
1256
+ * Download and compile Rapier's WebAssembly. Every call returns the same
1257
+ * promise, so it can be started early and awaited wherever it is needed;
1258
+ * a failed load rejects, and a later call tries again.
1259
+ *
1260
+ * Rapier is imported with `import()`, so bundlers put it in a chunk of its
1261
+ * own, downloaded only when this is called.
1262
+ * @returns a promise that resolves once the adapter can be constructed
1263
+ * @example
1264
+ * const rapierReady = Rapier3dAdapter.load();
1265
+ * await loader.preload(assets);
1266
+ * await rapierReady;
1267
+ * app.world.setAdapter(new Rapier3dAdapter());
1268
+ */
1269
+ static load() {
1270
+ return loadRapier();
1271
+ }
1272
+ /**
1273
+ * Whether {@link Rapier3dAdapter.load} has finished, so that
1274
+ * `new Rapier3dAdapter()` can be called.
1275
+ * @returns true once Rapier is compiled
1276
+ */
1277
+ static get loaded() {
1278
+ return loadedRapier() !== void 0;
1279
+ }
1280
+ /**
1281
+ * Create an adapter, the same way for every adapter: wait for
1282
+ * {@link Rapier3dAdapter.load}, then construct it.
1283
+ * @param options - the constructor's options
1284
+ * @returns the new adapter, an instance of the class `create` is called on
1285
+ */
1286
+ static async create(options) {
1287
+ await this.load();
1288
+ return new this(options);
1289
+ }
1290
+ /**
1291
+ * Construct an adapter. Rapier must be loaded first: use
1292
+ * {@link Rapier3dAdapter.create}, or await {@link Rapier3dAdapter.load}.
1293
+ * @param options - see {@link Rapier3dAdapterOptions}
1294
+ */
1295
+ constructor(options = {}) {
1296
+ if (utils.checkVersion(REQUIRED_MELONJS_VERSION, melonjsVersion) > 0) {
1297
+ throw new Error(
1298
+ `@melonjs/rapier3d-adapter requires melonJS >= ${REQUIRED_MELONJS_VERSION}, but the loaded melonJS is ${melonjsVersion}.`
1299
+ );
1300
+ }
1301
+ const rapier2 = loadedRapier();
1302
+ if (rapier2 === void 0) {
1303
+ throw new Error(
1304
+ "@melonjs/rapier3d-adapter: Rapier is not loaded yet. Use `await Rapier3dAdapter.create(options)`, or `await Rapier3dAdapter.load()` before `new Rapier3dAdapter(options)`."
1305
+ );
1306
+ }
1307
+ this.rapier = rapier2;
1308
+ const ppm = options.pixelsPerMeter ?? 32;
1309
+ if (!(ppm > 0) || !Number.isFinite(ppm)) {
1310
+ throw new Error(
1311
+ `@melonjs/rapier3d-adapter: pixelsPerMeter must be a positive number (got ${ppm}).`
1312
+ );
1313
+ }
1314
+ this.pixelsPerMeter = ppm;
1315
+ this.subSteps = Math.max(1, Math.floor(options.subSteps ?? 1));
1316
+ const g = options.gravity ?? { x: 0, y: 320, z: 0 };
1317
+ this.gravity = new Vector3d3(g.x, g.y, g.z ?? 0);
1318
+ this.sim = new Simulation(rapier2, new Units(ppm));
1319
+ this.filters = new CollisionFilters(rapier2);
1320
+ this.contacts = new ContactDispatcher(this.sim);
1321
+ this.motion = new Motion(this.sim);
1322
+ this.joints = new Joints(this.sim);
1323
+ }
1324
+ /** The Rapier world; exposed for advanced use. Made in {@link init}. */
1325
+ get world() {
1326
+ return this.sim.world;
1327
+ }
1328
+ // ── lifecycle ───────────────────────────────────────────────────────────
1329
+ init(world) {
1330
+ this.melonWorld = world;
1331
+ this.sim.open(this.gravityInMeters());
1332
+ this.contacts.open();
1333
+ }
1334
+ destroy() {
1335
+ if (!this.sim.alive) {
1336
+ return;
1337
+ }
1338
+ this.contacts.close();
1339
+ this.sim.close();
1340
+ this.filters.clear();
1341
+ this.motion.clear();
1342
+ this.joints.clear();
1343
+ this.overrides.clear();
1344
+ this.defs.clear();
1345
+ this.poses.clear();
1346
+ this.reportedShapes.clear();
1347
+ }
1348
+ step(dt) {
1349
+ if (!this.sim.alive) {
1350
+ throw new Error(
1351
+ "@melonjs/rapier3d-adapter: step() on an adapter with no Rapier world: it was destroyed, or never installed with `world.setAdapter()`."
1352
+ );
1353
+ }
1354
+ if (state.isPaused()) {
1355
+ return;
1356
+ }
1357
+ if (!(dt > 0) || !Number.isFinite(dt)) {
1358
+ return;
1359
+ }
1360
+ const { world } = this.sim;
1361
+ world.gravity = this.gravityInMeters();
1362
+ world.timestep = dt / 1e3 / this.subSteps;
1363
+ for (let i = 0; i < this.subSteps; i++) {
1364
+ world.step(this.contacts.queue, this.filters.hooks);
1365
+ this.contacts.dispatchQueuedEvents();
1366
+ }
1367
+ this.motion.clearForces();
1368
+ this.motion.clampVelocities();
1369
+ this.contacts.dispatchActiveContacts();
1370
+ }
1371
+ syncFromPhysics() {
1372
+ for (const [renderable, body] of this.sim.bodies) {
1373
+ if (body.isFixed() || body.isSleeping()) {
1374
+ continue;
1375
+ }
1376
+ this.writePose(renderable, body);
1377
+ }
1378
+ }
1379
+ // ── bodies ──────────────────────────────────────────────────────────────
1380
+ addBody(renderable, def) {
1381
+ const { rapier: rapier2, units, world } = this.sim;
1382
+ const parts = buildColliderParts(rapier2, units, def.shapes);
1383
+ this.removeBody(renderable);
1384
+ const { RigidBodyDesc } = rapier2;
1385
+ const desc = def.type === "static" ? RigidBodyDesc.fixed() : def.type === "kinematic" ? (
1386
+ // moved by its velocity, as on the other adapters
1387
+ RigidBodyDesc.kinematicVelocityBased()
1388
+ ) : RigidBodyDesc.dynamic();
1389
+ desc.setTranslation(
1390
+ units.toMeters(renderable.pos.x),
1391
+ units.toMeters(renderable.pos.y),
1392
+ units.toMeters(renderable.depth)
1393
+ );
1394
+ const damping = averageOf(def.frictionAir) ?? 0;
1395
+ desc.setLinearDamping(damping);
1396
+ desc.setAngularDamping(damping);
1397
+ desc.setGravityScale(def.gravityScale ?? 1);
1398
+ if (def.fixedRotation === true) {
1399
+ desc.lockRotations();
1400
+ }
1401
+ const body = world.createRigidBody(desc);
1402
+ const colliders = [];
1403
+ this.sim.bodies.set(renderable, body);
1404
+ this.sim.collidersOf.set(renderable, colliders);
1405
+ this.defs.set(renderable, def);
1406
+ this.createColliders(renderable, body, def, parts, colliders);
1407
+ if (def.maxVelocity) {
1408
+ this.setMaxVelocity(renderable, def.maxVelocity);
1409
+ }
1410
+ this.poses.set(renderable, poseOf(renderable));
1411
+ spliceHelpers(this.helperContext(), renderable, body, colliders);
1412
+ const adapterBody = body;
1413
+ renderable.body = adapterBody;
1414
+ renderable.isKinematic = false;
1415
+ return adapterBody;
1416
+ }
1417
+ removeBody(renderable) {
1418
+ const body = this.sim.bodies.get(renderable);
1419
+ if (body === void 0) {
1420
+ return;
1421
+ }
1422
+ this.forgetColliders(this.sim.collidersOf.get(renderable) ?? []);
1423
+ if (this.sim.bodies.get(renderable) !== body) {
1424
+ return;
1425
+ }
1426
+ this.joints.forgetJointsOf(body);
1427
+ this.sim.world.removeRigidBody(body);
1428
+ this.motion.forget(renderable, body);
1429
+ this.sim.bodies.delete(renderable);
1430
+ this.sim.collidersOf.delete(renderable);
1431
+ this.defs.delete(renderable);
1432
+ this.poses.delete(renderable);
1433
+ this.reportedShapes.delete(renderable);
1434
+ this.overrides.delete(renderable);
1435
+ }
1436
+ /**
1437
+ * Give a body new shapes. The body itself stays: its position, turn and
1438
+ * velocities, its joints, what was changed on it at run time (static or
1439
+ * not, gravity scale, damping, sensor, collision type and mask, bounce,
1440
+ * speed cap, Rapier's own settings such as CCD) and the handle on
1441
+ * `renderable.body`. Its colliders are replaced, so the pairs touching
1442
+ * it end and start again, and its mass is that of the new shapes.
1443
+ *
1444
+ * A shape this adapter cannot build throws before anything is changed.
1445
+ * @param renderable - the body's renderable
1446
+ * @param shapes - the new shapes, relative to `pos`
1447
+ */
1448
+ updateShape(renderable, shapes) {
1449
+ const def = this.defs.get(renderable);
1450
+ const body = this.sim.bodies.get(renderable);
1451
+ const colliders = this.sim.collidersOf.get(renderable);
1452
+ if (!def || !body || !colliders) {
1453
+ return;
1454
+ }
1455
+ const parts = buildColliderParts(this.sim.rapier, this.sim.units, shapes);
1456
+ this.forgetColliders(colliders);
1457
+ if (this.sim.bodies.get(renderable) !== body) {
1458
+ return;
1459
+ }
1460
+ for (const collider of colliders) {
1461
+ this.sim.world.removeCollider(collider, false);
1462
+ }
1463
+ colliders.length = 0;
1464
+ const next = { ...def, shapes };
1465
+ this.defs.set(renderable, next);
1466
+ this.reportedShapes.delete(renderable);
1467
+ this.createColliders(renderable, body, next, parts, colliders);
1468
+ body.recomputeMassPropertiesFromColliders();
1469
+ body.wakeUp();
1470
+ }
1471
+ // ── joints ──────────────────────────────────────────────────────────────
1472
+ /**
1473
+ * Make a joint between two bodies: what `world.addJoint()` calls, which
1474
+ * game code uses instead. A `"hinge"` is a Rapier revolute joint about
1475
+ * `axis` (default Z), a `"rope"` a rope joint, a `"weld"` a fixed joint
1476
+ * and a `"slider"` a prismatic joint along `axis` (default X). Anchors
1477
+ * are in each renderable's own space, relative to its `pos`, in pixels,
1478
+ * and the axis in `a`'s; a `z` left out is `0`.
1479
+ *
1480
+ * The bodies are joined as they stand, however each is turned: a weld
1481
+ * and a slider keep the turn between them, and a hinge leaves them only
1482
+ * the turn about its axis.
1483
+ * @param def - what to join, and how, in pixels and radians
1484
+ * @returns the Rapier joint
1485
+ */
1486
+ addJoint(def) {
1487
+ return this.joints.add(def);
1488
+ }
1489
+ /**
1490
+ * Remove a joint {@link Rapier3dAdapter.addJoint} made: what
1491
+ * `world.removeJoint()` calls. A joint already gone, with one of its
1492
+ * bodies, is ignored.
1493
+ * @param joint - the Rapier joint
1494
+ */
1495
+ removeJoint(joint) {
1496
+ this.joints.remove(joint);
1497
+ }
1498
+ // ── velocity, forces and position ───────────────────────────────────────
1499
+ getVelocity(renderable, out) {
1500
+ const target = out ?? new Vector2d();
1501
+ const v = this.sim.bodies.get(renderable)?.linvel();
1502
+ const { units } = this.sim;
1503
+ return v ? target.set(units.toPixels(v.x), units.toPixels(v.y)) : target.set(0, 0);
1504
+ }
1505
+ /**
1506
+ * The body's velocity on all three axes, in pixels per second.
1507
+ * @param renderable - the body's renderable
1508
+ * @param [out] - the vector to write into
1509
+ * @returns the velocity; zero for a renderable with no body here
1510
+ */
1511
+ getVelocity3d(renderable, out) {
1512
+ const target = out ?? new Vector3d3();
1513
+ const v = this.sim.bodies.get(renderable)?.linvel();
1514
+ const { units } = this.sim;
1515
+ return v ? target.set(
1516
+ units.toPixels(v.x),
1517
+ units.toPixels(v.y),
1518
+ units.toPixels(v.z)
1519
+ ) : target.set(0, 0, 0);
1520
+ }
1521
+ /**
1522
+ * Set the body's velocity, in pixels per second. A {@link Vector3d} sets
1523
+ * all three axes; a {@link Vector2d} sets x and y and keeps the depth
1524
+ * velocity as it was.
1525
+ * @param renderable - the body's renderable
1526
+ * @param v - the velocity
1527
+ */
1528
+ setVelocity(renderable, v) {
1529
+ const body = this.sim.bodies.get(renderable);
1530
+ if (body) {
1531
+ this.motion.setVelocity(body, v.x, v.y, zOf(v));
1532
+ }
1533
+ }
1534
+ /**
1535
+ * Push the body for this frame, across every sub-step: it accelerates by
1536
+ * `force / mass` pixels per second². A force at `point` (in world pixels)
1537
+ * also turns it. A force or point given as a {@link Vector2d} acts in
1538
+ * the plane of the body.
1539
+ * @param renderable - the body's renderable
1540
+ * @param force - the force
1541
+ * @param [point] - where it pushes, in world space
1542
+ */
1543
+ applyForce(renderable, force, point) {
1544
+ const body = this.sim.bodies.get(renderable);
1545
+ if (body) {
1546
+ this.motion.addForce(body, force, point);
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Strike the body once: its velocity changes by `impulse / mass` pixels
1551
+ * per second, at once. An impulse at `point` (in world pixels) also turns
1552
+ * it. A {@link Vector2d} strikes in the plane of the body.
1553
+ * @param renderable - the body's renderable
1554
+ * @param impulse - the impulse
1555
+ * @param [point] - where it strikes, in world space
1556
+ */
1557
+ applyImpulse(renderable, impulse, point) {
1558
+ const body = this.sim.bodies.get(renderable);
1559
+ if (!body) return;
1560
+ const j = this.sim.units.inMeters(impulse.x, impulse.y, zOf(impulse) ?? 0);
1561
+ if (point) {
1562
+ body.applyImpulseAtPoint(j, this.motion.pointInMeters(body, point), true);
1563
+ } else {
1564
+ this.rapier.RigidBody.prototype.applyImpulse.call(body, j, true);
1565
+ }
1566
+ }
1567
+ /**
1568
+ * Move the body and its renderable, at once. A {@link Vector3d} sets the
1569
+ * depth too; a {@link Vector2d} keeps it. A renderable with no body here
1570
+ * is moved all the same, as on every adapter. A coordinate that is not a
1571
+ * finite number leaves the body and its renderable where they are.
1572
+ * @param renderable - the body's renderable
1573
+ * @param p - the new position, in `renderable.pos` space
1574
+ */
1575
+ setPosition(renderable, p) {
1576
+ const depth = zOf(p) ?? renderable.depth;
1577
+ if (!Number.isFinite(p.x) || !Number.isFinite(p.y) || !Number.isFinite(depth)) {
1578
+ return;
1579
+ }
1580
+ renderable.setPosition(p.x, p.y, depth);
1581
+ renderable.isDirty = true;
1582
+ this.sim.bodies.get(renderable)?.setTranslation(this.sim.units.inMeters(p.x, p.y, depth), true);
1583
+ }
1584
+ // ── turn and spin ───────────────────────────────────────────────────────
1585
+ /**
1586
+ * The body's orientation, from the one it had when it was made.
1587
+ * @param renderable - the body's renderable
1588
+ * @param [out] - the quaternion to write into
1589
+ * @returns the orientation; identity for a renderable with no body here
1590
+ */
1591
+ getRotation(renderable, out) {
1592
+ const target = out ?? new Quaternion3();
1593
+ const body = this.sim.bodies.get(renderable);
1594
+ if (!body) {
1595
+ return target.identity();
1596
+ }
1597
+ const q = body.rotation();
1598
+ return target.set(q.x, q.y, q.z, q.w);
1599
+ }
1600
+ /**
1601
+ * Turn the body, and its renderable with it, to an orientation, from the
1602
+ * one it had when it was made.
1603
+ * @param renderable - the body's renderable
1604
+ * @param q - the orientation
1605
+ */
1606
+ setRotation(renderable, q) {
1607
+ const body = this.sim.bodies.get(renderable);
1608
+ if (!body) return;
1609
+ const n = q.clone().normalize();
1610
+ body.setRotation({ x: n.x, y: n.y, z: n.z, w: n.w }, true);
1611
+ this.writePose(renderable, body);
1612
+ }
1613
+ /**
1614
+ * Turn the body to `angle` about Z, the turn a 2D game knows, leaving out
1615
+ * any other.
1616
+ * @param renderable - the body's renderable
1617
+ * @param angle - in radians
1618
+ */
1619
+ setAngle(renderable, angle) {
1620
+ const body = this.sim.bodies.get(renderable);
1621
+ if (!body || !Number.isFinite(angle)) return;
1622
+ body.setRotation(_turn2.identity().rotate(angle), true);
1623
+ this.writePose(renderable, body);
1624
+ }
1625
+ /**
1626
+ * The body's turn about Z: the angle +X is turned through, seen down Z.
1627
+ * @param renderable - the body's renderable
1628
+ * @returns in radians; `0` for a renderable with no body here
1629
+ */
1630
+ getAngle(renderable) {
1631
+ const body = this.sim.bodies.get(renderable);
1632
+ if (!body) return 0;
1633
+ const { x, y, z, w } = body.rotation();
1634
+ const tx = 1 - 2 * (y * y + z * z);
1635
+ const ty = 2 * (x * y + w * z);
1636
+ return tx * tx + ty * ty < 1e-12 ? 0 : Math.atan2(ty, tx);
1637
+ }
1638
+ /**
1639
+ * Set the body's spin, in radians per second: a {@link Vector3d} about
1640
+ * each axis, a number about Z, keeping the spin about X and Y.
1641
+ * @param renderable - the body's renderable
1642
+ * @param omega - the spin
1643
+ */
1644
+ setAngularVelocity(renderable, omega) {
1645
+ const body = this.sim.bodies.get(renderable);
1646
+ if (!body) return;
1647
+ if (typeof omega === "number") {
1648
+ const w = body.angvel();
1649
+ body.setAngvel({ x: w.x, y: w.y, z: omega }, true);
1650
+ } else {
1651
+ body.setAngvel({ x: omega.x, y: omega.y, z: omega.z }, true);
1652
+ }
1653
+ }
1654
+ getAngularVelocity(renderable) {
1655
+ return this.sim.bodies.get(renderable)?.angvel().z ?? 0;
1656
+ }
1657
+ /**
1658
+ * The body's spin about each axis, in radians per second.
1659
+ * @param renderable - the body's renderable
1660
+ * @param [out] - the vector to write into
1661
+ * @returns the spin; zero for a renderable with no body here
1662
+ */
1663
+ getAngularVelocity3d(renderable, out) {
1664
+ const target = out ?? new Vector3d3();
1665
+ const w = this.sim.bodies.get(renderable)?.angvel();
1666
+ return w ? target.set(w.x, w.y, w.z) : target.set(0, 0, 0);
1667
+ }
1668
+ /**
1669
+ * Twist the body for this frame: a number about Z, a {@link Vector3d}
1670
+ * about each axis. In Rapier's own unit (N·m, not scaled by
1671
+ * `pixelsPerMeter`), as on the 2D Rapier adapter.
1672
+ * @param renderable - the body's renderable
1673
+ * @param torque - the torque
1674
+ */
1675
+ applyTorque(renderable, torque) {
1676
+ const body = this.sim.bodies.get(renderable);
1677
+ if (body) {
1678
+ this.motion.addTorque(body, torque);
1679
+ }
1680
+ }
1681
+ // ── what a body is ──────────────────────────────────────────────────────
1682
+ setStatic(renderable, isStatic) {
1683
+ const { RigidBodyType } = this.rapier;
1684
+ this.sim.bodies.get(renderable)?.setBodyType(
1685
+ isStatic ? RigidBodyType.Fixed : RigidBodyType.Dynamic,
1686
+ true
1687
+ );
1688
+ }
1689
+ setGravityScale(renderable, scale) {
1690
+ const body = this.sim.bodies.get(renderable);
1691
+ if (body) {
1692
+ this.rapier.RigidBody.prototype.setGravityScale.call(body, scale, true);
1693
+ }
1694
+ }
1695
+ setSensor(renderable, isSensor) {
1696
+ const colliders = this.sim.collidersOf.get(renderable);
1697
+ if (colliders === void 0) return;
1698
+ this.overrides.of(renderable).sensor = isSensor;
1699
+ for (const collider of colliders) {
1700
+ collider.setSensor(isSensor);
1701
+ }
1702
+ }
1703
+ setFrictionAir(renderable, friction) {
1704
+ const body = this.sim.bodies.get(renderable);
1705
+ if (!body) return;
1706
+ const damping = averageOf(friction) ?? 0;
1707
+ body.setLinearDamping(damping);
1708
+ body.setAngularDamping(damping);
1709
+ }
1710
+ /**
1711
+ * Cap the body's speed on each axis, in pixels per second. A `z` caps
1712
+ * the depth axis too; left out, that axis has no cap.
1713
+ * @param renderable - the body's renderable
1714
+ * @param limit - the cap
1715
+ */
1716
+ setMaxVelocity(renderable, limit) {
1717
+ if (!this.sim.bodies.has(renderable)) return;
1718
+ this.motion.limits.set(renderable, {
1719
+ x: limit.x,
1720
+ y: limit.y,
1721
+ z: limit.z
1722
+ });
1723
+ }
1724
+ getMaxVelocity(renderable) {
1725
+ const limit = this.motion.limits.get(renderable);
1726
+ return {
1727
+ x: limit?.x ?? Infinity,
1728
+ y: limit?.y ?? Infinity,
1729
+ z: limit?.z ?? Infinity
1730
+ };
1731
+ }
1732
+ setCollisionType(renderable, type) {
1733
+ this.setFilter(renderable, type, void 0);
1734
+ }
1735
+ setCollisionMask(renderable, mask) {
1736
+ this.setFilter(renderable, void 0, mask);
1737
+ }
1738
+ // ── reading bodies, and querying the world ──────────────────────────────
1739
+ /**
1740
+ * The body's XY bounds in renderable-local pixels, relative to `pos`: the
1741
+ * footprint of its colliders as the body is turned now. Exact for a
1742
+ * box, a sphere and a capsule; for a hull or a triangle mesh, that of its
1743
+ * bounding box, turned.
1744
+ * @param renderable - the renderable whose body bounds to read
1745
+ * @param out - destination `Bounds` (filled in place, also returned)
1746
+ */
1747
+ getBodyAABB(renderable, out) {
1748
+ const body = this.sim.bodies.get(renderable);
1749
+ const colliders = this.sim.collidersOf.get(renderable);
1750
+ if (body === void 0 || colliders === void 0) {
1751
+ return void 0;
1752
+ }
1753
+ if (colliders.length === 0) {
1754
+ return void 0;
1755
+ }
1756
+ const q = body.rotation();
1757
+ const box = emptyFootprint();
1758
+ for (const collider of colliders) {
1759
+ const entry = this.sim.colliders.get(collider.handle);
1760
+ if (entry !== void 0) {
1761
+ growFootprint(entry, q, box);
1762
+ }
1763
+ }
1764
+ out.setMinMax(box[0], box[1], box[2], box[3]);
1765
+ return out;
1766
+ }
1767
+ /**
1768
+ * The body's collision shapes, as given in its `bodyDef`, relative to
1769
+ * `pos` and before the body turns (the turn is
1770
+ * {@link Rapier3dAdapter.getRotation}). A shape with `isActive: false`
1771
+ * is left out.
1772
+ * @param renderable - the renderable whose body shapes to read
1773
+ */
1774
+ getBodyShapes(renderable) {
1775
+ const colliders = this.sim.collidersOf.get(renderable);
1776
+ if (colliders === void 0) {
1777
+ return [];
1778
+ }
1779
+ let cached = this.reportedShapes.get(renderable);
1780
+ if (cached === void 0) {
1781
+ cached = [];
1782
+ for (const collider of colliders) {
1783
+ const entry = this.sim.colliders.get(collider.handle);
1784
+ if (entry !== void 0) {
1785
+ cached.push(entry.shape);
1786
+ }
1787
+ }
1788
+ this.reportedShapes.set(renderable, cached);
1789
+ }
1790
+ return cached;
1791
+ }
1792
+ /**
1793
+ * Whether Rapier has put the body to sleep: a dynamic body at rest, left
1794
+ * out of the step until a contact or a write to it (a velocity, a force,
1795
+ * an impulse, a position or a rotation, which all wake it) moves it
1796
+ * again. `false` for a fixed or kinematic body, and for a renderable this
1797
+ * adapter does not know, including every one once it is destroyed.
1798
+ * @param renderable - the renderable whose body to read
1799
+ * @returns `true` while the body sleeps
1800
+ * @example
1801
+ * // the shot is over once every block has come to rest
1802
+ * const settled = blocks.every((b) => adapter.isSleeping(b));
1803
+ */
1804
+ isSleeping(renderable) {
1805
+ const body = this.sim.bodies.get(renderable);
1806
+ return body !== void 0 && body.isDynamic() && body.isSleeping();
1807
+ }
1808
+ isGrounded(renderable) {
1809
+ return isGrounded(this.sim, renderable);
1810
+ }
1811
+ /**
1812
+ * The first collider a segment meets, from `from` to `to`, in world
1813
+ * pixels: the exact shape, not a bounding volume. A shape the ray starts
1814
+ * inside is skipped, so a body casting from its own centre does not hit
1815
+ * itself. Sensors are hit like any other body.
1816
+ * @param from - where the ray starts
1817
+ * @param to - where it ends
1818
+ * @returns the hit, or `null`
1819
+ */
1820
+ raycast3d(from, to) {
1821
+ return raycast3d(this.sim, from, to);
1822
+ }
1823
+ /**
1824
+ * The renderables whose colliders' boxes overlap a rectangle in XY, at
1825
+ * any depth: the boxes {@link Rapier3dAdapter.getBodyAABB} reports.
1826
+ * @param rect - the rectangle, in world pixels
1827
+ * @returns the renderables, each once
1828
+ */
1829
+ queryAABB(rect) {
1830
+ return queryAABB(this.sim, rect);
1831
+ }
1832
+ /**
1833
+ * The renderables whose colliders overlap a sphere: their exact shapes.
1834
+ * @param center - the centre in world pixels, or a {@link Sphere}
1835
+ * @param [radius] - the radius in pixels, with a centre; none, or less
1836
+ * than none, is a point
1837
+ * @returns the renderables, each once
1838
+ */
1839
+ querySphere(center, radius) {
1840
+ return querySphere(this.sim, center, radius);
1841
+ }
1842
+ // ── internals ───────────────────────────────────────────────────────────
1843
+ /**
1844
+ * The gravity in meters per second², for Rapier.
1845
+ * @returns the gravity
1846
+ */
1847
+ gravityInMeters() {
1848
+ const { x, y, z } = this.gravity;
1849
+ return this.sim.units.inMeters(x, y, z);
1850
+ }
1851
+ /**
1852
+ * Write a body's place and turn back onto its renderable.
1853
+ * @param renderable - the renderable
1854
+ * @param body - its body
1855
+ */
1856
+ writePose(renderable, body) {
1857
+ writePose(renderable, body, this.poses.get(renderable), this.sim.units);
1858
+ }
1859
+ /**
1860
+ * Make a body's colliders, with the body definition's material and
1861
+ * filter, a shape's own settings over them, and what was set on the
1862
+ * whole body at run time over both.
1863
+ * @param renderable - the body's renderable
1864
+ * @param body - the body
1865
+ * @param def - its definition
1866
+ * @param parts - the colliders to make
1867
+ * @param colliders - the body's list of colliders, added to
1868
+ */
1869
+ createColliders(renderable, body, def, parts, colliders) {
1870
+ const over = this.overrides.get(renderable);
1871
+ const bodyType = typeof def.collisionType === "number" ? def.collisionType : 1;
1872
+ const bodyMask = typeof def.collisionMask === "number" ? def.collisionMask : collision2.types.ALL_OBJECT;
1873
+ for (const { shape, index, desc, min, max, round } of parts) {
1874
+ const shapeType = shape.collisionType;
1875
+ const shapeMask = shape.collisionMask;
1876
+ const trigger = shape.isTrigger === true;
1877
+ desc.setDensity(def.density ?? 1).setFriction(def.friction ?? 0.2).setRestitution(over?.restitution ?? def.restitution ?? 0).setSensor(over?.sensor ?? (def.isSensor === true || trigger)).setActiveEvents(this.rapier.ActiveEvents.COLLISION_EVENTS);
1878
+ const collider = this.sim.world.createCollider(desc, body);
1879
+ this.filters.apply(
1880
+ collider,
1881
+ over?.category ?? (typeof shapeType === "number" ? shapeType : bodyType),
1882
+ over?.mask ?? (typeof shapeMask === "number" ? shapeMask : bodyMask)
1883
+ );
1884
+ const entry = { renderable, shape, index, min, max };
1885
+ if (round !== void 0) {
1886
+ entry.round = round;
1887
+ }
1888
+ this.sim.colliders.set(collider.handle, entry);
1889
+ colliders.push(collider);
1890
+ }
1891
+ }
1892
+ /**
1893
+ * Tell the pairs touching colliders that are about to go that their
1894
+ * contact ended, then forget the colliders.
1895
+ * @param colliders - the colliders leaving the world
1896
+ */
1897
+ forgetColliders(colliders) {
1898
+ this.contacts.endContacts(colliders);
1899
+ for (const collider of colliders) {
1900
+ this.sim.colliders.delete(collider.handle);
1901
+ this.filters.forget(collider.handle);
1902
+ }
1903
+ }
1904
+ /**
1905
+ * Change the collision type and/or mask of every collider of a body, and
1906
+ * keep it for the colliders `updateShape()` makes.
1907
+ * @param renderable - the body's renderable
1908
+ * @param category - the new type, or undefined to keep each collider's
1909
+ * @param mask - the new mask, or undefined to keep each collider's
1910
+ */
1911
+ setFilter(renderable, category, mask) {
1912
+ const colliders = this.sim.collidersOf.get(renderable);
1913
+ if (colliders === void 0) return;
1914
+ const over = this.overrides.of(renderable);
1915
+ if (category !== void 0) over.category = category;
1916
+ if (mask !== void 0) over.mask = mask;
1917
+ this.filters.update(colliders, category, mask);
1918
+ }
1919
+ /**
1920
+ * What the helpers spliced onto a body act through.
1921
+ * @returns the context
1922
+ */
1923
+ helperContext() {
1924
+ return {
1925
+ adapter: this,
1926
+ sim: this.sim,
1927
+ motion: this.motion,
1928
+ filters: this.filters,
1929
+ overrides: this.overrides
1930
+ };
1931
+ }
1932
+ };
1933
+ function averageOf(v) {
1934
+ if (v === void 0) return void 0;
1935
+ if (typeof v === "number") return v;
1936
+ return (v.x + v.y) / 2;
1937
+ }
1938
+ export {
1939
+ REQUIRED_MELONJS_VERSION,
1940
+ Rapier3dAdapter
1941
+ };
1942
+ //# sourceMappingURL=index.js.map