@threenative/physics 0.2.1 → 0.3.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/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as rapier from '@dimforge/rapier3d-compat';
2
+ import { Vector3, Quaternion, Matrix4 } from 'three';
2
3
 
3
4
  // src/web.ts
4
5
 
@@ -30,10 +31,55 @@ var PHYSICS_TRANSFORM_STRIDE = 8;
30
31
  var PHYSICS_COLLISION_EVENT_STRIDE = 4;
31
32
  var PHYSICS_SLEEP_STATE_STRIDE = 2;
32
33
  var MAX_PHYSICS_QUERY_RESULTS = 1024;
34
+ var F32_EPSILON = Math.fround(2 ** -23);
35
+ var F32_EPSILON_SQUARED = Math.fround(F32_EPSILON * F32_EPSILON);
36
+ function f32LengthSquared(values) {
37
+ let lengthSquared = 0;
38
+ for (const value of values) {
39
+ const component = Math.fround(value);
40
+ lengthSquared = Math.fround(lengthSquared + Math.fround(component * component));
41
+ }
42
+ return lengthSquared;
43
+ }
33
44
  function requireFiniteVector(vector, label) {
34
45
  if (typeof vector?.x !== "number" || typeof vector.y !== "number" || typeof vector.z !== "number" || !Number.isFinite(vector.x) || !Number.isFinite(vector.y) || !Number.isFinite(vector.z))
35
46
  throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z }.`);
36
47
  }
48
+ function requireFiniteRotation(rotation, label) {
49
+ if (typeof rotation?.x !== "number" || typeof rotation.y !== "number" || typeof rotation.z !== "number" || typeof rotation.w !== "number" || !Number.isFinite(rotation.x) || !Number.isFinite(rotation.y) || !Number.isFinite(rotation.z) || !Number.isFinite(rotation.w))
50
+ throw new Error(`TN_PHYSICS_NON_FINITE: ${label} must be a finite { x, y, z, w }.`);
51
+ if (f32LengthSquared([rotation.x, rotation.y, rotation.z, rotation.w]) <= F32_EPSILON)
52
+ throw new Error(`TN_PHYSICS_INVALID: ${label} must not have zero length.`);
53
+ }
54
+ function requirePhysicsJointCreateOptions(options) {
55
+ if (typeof options !== "object" || options === null)
56
+ throw new Error("IPhysicsSimulation joint options must be an object.");
57
+ if (options.type !== "pin" && options.type !== "hinge" && options.type !== "fixed")
58
+ throw new Error("IPhysicsSimulation joint options have an unknown type.");
59
+ if (!Number.isSafeInteger(options.bodyA) || options.bodyA < 0 || !Number.isSafeInteger(options.bodyB) || options.bodyB < 0 || options.bodyA === options.bodyB)
60
+ throw new Error("IPhysicsSimulation joint options must reference two distinct body ids.");
61
+ requireFiniteVector(options.anchorA, "joint anchorA");
62
+ requireFiniteVector(options.anchorB, "joint anchorB");
63
+ if (options.type === "hinge") {
64
+ if (options.axis === void 0) throw new Error("IPhysicsSimulation hinge requires an axis.");
65
+ requireFiniteVector(options.axis, "joint axis");
66
+ if (f32LengthSquared([options.axis.x, options.axis.y, options.axis.z]) <= F32_EPSILON_SQUARED)
67
+ throw new Error("IPhysicsSimulation hinge axis must not have zero length.");
68
+ if (options.limit !== void 0) {
69
+ if (typeof options.limit !== "object" || options.limit === null)
70
+ throw new Error("IPhysicsSimulation hinge limit must contain ordered finite bounds.");
71
+ if (!Number.isFinite(options.limit.lower) || !Number.isFinite(options.limit.upper) || options.limit.lower > options.limit.upper)
72
+ throw new Error("IPhysicsSimulation hinge limit must contain ordered finite bounds.");
73
+ }
74
+ } else if (options.axis !== void 0 || options.limit !== void 0) {
75
+ throw new Error("IPhysicsSimulation joint limits and axes are only valid for a hinge.");
76
+ }
77
+ if (options.type !== "fixed" && (options.frameA !== void 0 || options.frameB !== void 0))
78
+ throw new Error("IPhysicsSimulation joint frames are only valid for a fixed joint.");
79
+ if (options.frameA !== void 0) requireFiniteRotation(options.frameA, "joint frameA");
80
+ if (options.frameB !== void 0) requireFiniteRotation(options.frameB, "joint frameB");
81
+ return options;
82
+ }
37
83
  var selectedBackend;
38
84
  function installPhysicsSimulationBackend(backend) {
39
85
  selectedBackend = backend;
@@ -87,6 +133,14 @@ function requirePhysicsBodySensor(options) {
87
133
  );
88
134
  return options.sensor;
89
135
  }
136
+ var kinematicScratch = {
137
+ target: { x: 0, y: 0, z: 0 },
138
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
139
+ desired: { x: 0, y: 0, z: 0 },
140
+ nextTranslation: { x: 0, y: 0, z: 0 }
141
+ };
142
+ var oneWayFilterLayers = 0;
143
+ var oneWayFilterPredicate = (collider) => (collider.collisionGroups() >>> 16 & oneWayFilterLayers) === 0;
90
144
  var QUERY_SHAPE_KINDS = /* @__PURE__ */ new Set([
91
145
  "box",
92
146
  "sphere",
@@ -217,29 +271,94 @@ function bodyDescription(rapier3, type, position, rotation, mass) {
217
271
  if (mass !== 0) description.setAdditionalMass(mass);
218
272
  return description;
219
273
  }
274
+ function jointDescription(rapier3, jointOptions) {
275
+ if (jointOptions.type === "pin")
276
+ return rapier3.JointData.spherical(jointOptions.anchorA, jointOptions.anchorB);
277
+ if (jointOptions.type === "hinge") {
278
+ return rapier3.JointData.revolute(
279
+ jointOptions.anchorA,
280
+ jointOptions.anchorB,
281
+ jointOptions.axis
282
+ );
283
+ }
284
+ return rapier3.JointData.fixed(
285
+ jointOptions.anchorA,
286
+ jointOptions.frameA ?? { x: 0, y: 0, z: 0, w: 1 },
287
+ jointOptions.anchorB,
288
+ jointOptions.frameB ?? { x: 0, y: 0, z: 0, w: 1 }
289
+ );
290
+ }
220
291
  function characterState(simulationBody, byCollider) {
292
+ const state = simulationBody.characterState;
221
293
  const controller = simulationBody.controller;
222
- if (controller === void 0) return { grounded: false };
294
+ if (controller === void 0) return state;
223
295
  let groundCollider;
296
+ let groundBody;
297
+ let groundNormal;
224
298
  for (let index = 0; index < controller.numComputedCollisions(); index += 1) {
225
299
  const collision = controller.computedCollision(index);
226
300
  if (collision?.collider === null || collision?.collider === void 0) continue;
227
301
  if ((collision.normal1.y ?? Number.NEGATIVE_INFINITY) >= 0.5) {
228
- groundCollider = byCollider.get(collision.collider.handle)?.id;
229
- if (groundCollider !== void 0) break;
302
+ const contacted = byCollider.get(collision.collider.handle);
303
+ if (contacted !== void 0) {
304
+ groundCollider = contacted.id;
305
+ groundBody = contacted.bodyHandle;
306
+ groundNormal = collision.normal1;
307
+ break;
308
+ }
230
309
  }
231
310
  }
232
311
  const grounded = controller.computedGrounded();
233
312
  if (groundCollider !== void 0) simulationBody.groundCollider = groundCollider;
234
313
  else if (!grounded) simulationBody.groundCollider = void 0;
235
- return { grounded, groundCollider: simulationBody.groundCollider };
314
+ state.grounded = grounded;
315
+ state.groundCollider = simulationBody.groundCollider;
316
+ if (groundBody !== void 0) state.groundBody = groundBody;
317
+ else if (!grounded) state.groundBody = void 0;
318
+ if (groundNormal !== void 0) {
319
+ state.groundNormal.x = groundNormal.x;
320
+ state.groundNormal.y = groundNormal.y;
321
+ state.groundNormal.z = groundNormal.z;
322
+ } else if (!grounded) {
323
+ state.groundNormal.x = 0;
324
+ state.groundNormal.y = 1;
325
+ state.groundNormal.z = 0;
326
+ }
327
+ return state;
328
+ }
329
+ function writeRapierTransformRecord(entry, renderBuffer, offset) {
330
+ const translation = entry.body.translation();
331
+ const rotation = entry.body.rotation();
332
+ renderBuffer[offset] = entry.id;
333
+ renderBuffer[offset + 1] = translation.x;
334
+ renderBuffer[offset + 2] = translation.y;
335
+ renderBuffer[offset + 3] = translation.z;
336
+ renderBuffer[offset + 4] = rotation.x;
337
+ renderBuffer[offset + 5] = rotation.y;
338
+ renderBuffer[offset + 6] = rotation.z;
339
+ renderBuffer[offset + 7] = rotation.w;
236
340
  }
237
341
  function createWebPhysicsSimulation(options) {
238
342
  const bodies = /* @__PURE__ */ new Map();
239
343
  const byCollider = /* @__PURE__ */ new Map();
344
+ const joints = /* @__PURE__ */ new Map();
240
345
  const dirtyBodies = /* @__PURE__ */ new Set();
346
+ const areaIntersections = /* @__PURE__ */ new Map();
347
+ const emptyAreaIntersections = /* @__PURE__ */ new Set();
348
+ let areaIntersectionId = -1;
349
+ let areaIntersectionMask = 0;
350
+ let areaIntersectionMembers;
351
+ const areaIntersectionCallback = (collider) => {
352
+ const members = areaIntersectionMembers;
353
+ if (members === void 0) return true;
354
+ const body = byCollider.get(collider.handle);
355
+ if (body !== void 0 && body.id !== areaIntersectionId && !collider.isSensor() && (collider.collisionGroups() >>> 16 & areaIntersectionMask) !== 0)
356
+ members.add(body.id);
357
+ return true;
358
+ };
241
359
  const pendingCollisionEvents = [];
242
360
  let nextId = 0;
361
+ let nextJointId = 0;
243
362
  let disposed = false;
244
363
  const requireLive = () => {
245
364
  if (disposed) throw new Error("Physics simulation is disposed.");
@@ -269,6 +388,13 @@ function createWebPhysicsSimulation(options) {
269
388
  position: { x: position.x, y: position.y, z: position.z }
270
389
  };
271
390
  };
391
+ const removeJointRecord = (id) => {
392
+ const record = joints.get(id);
393
+ if (record === void 0) return;
394
+ joints.delete(id);
395
+ const joint = options.world.impulseJoints.get(record.handle);
396
+ if (joint !== null) options.world.removeImpulseJoint(joint, true);
397
+ };
272
398
  const simulation = {
273
399
  version: options.version,
274
400
  rawWorld: options.world,
@@ -278,6 +404,8 @@ function createWebPhysicsSimulation(options) {
278
404
  const sensor = requirePhysicsBodySensor(bodyOptions);
279
405
  if (!Number.isFinite(bodyOptions.mass) || bodyOptions.mass < 0)
280
406
  throw new Error("Physics body mass must be a finite non-negative number.");
407
+ requireFiniteVector(bodyOptions.position, "body position");
408
+ requireFiniteRotation(bodyOptions.rotation, "body rotation");
281
409
  const id = nextId;
282
410
  nextId += 1;
283
411
  const rawShape = createWebPhysicsShape(options.rapier, bodyOptions.shape, sensor);
@@ -291,8 +419,11 @@ function createWebPhysicsSimulation(options) {
291
419
  )
292
420
  );
293
421
  const rawCollider = options.world.createCollider(rawShape, rawBody);
422
+ const bodyHandle = physicsBodyHandle(id, rawBody, bodyOptions.entity);
294
423
  const entry = {
295
424
  body: rawBody,
425
+ bodyHandle,
426
+ characterState: { grounded: false, groundNormal: { x: 0, y: 1, z: 0 } },
296
427
  collider: rawCollider,
297
428
  entity: bodyOptions.entity,
298
429
  id,
@@ -304,14 +435,45 @@ function createWebPhysicsSimulation(options) {
304
435
  }
305
436
  bodies.set(id, entry);
306
437
  byCollider.set(rawCollider.handle, entry);
438
+ if (bodyOptions.sensor) areaIntersections.set(id, /* @__PURE__ */ new Set());
307
439
  dirtyBodies.add(entry);
308
440
  return {
309
- body: physicsBodyHandle(id, rawBody, bodyOptions.entity),
441
+ body: bodyHandle,
310
442
  collider: physicsColliderHandle(id, rawCollider),
311
443
  controller: entry.controllerHandle,
312
444
  rawShape
313
445
  };
314
446
  },
447
+ createJoint: (jointOptions) => {
448
+ requireLive();
449
+ const normalized = requirePhysicsJointCreateOptions(jointOptions);
450
+ const bodyA = bodies.get(normalized.bodyA);
451
+ const bodyB = bodies.get(normalized.bodyB);
452
+ if (bodyA === void 0 || bodyB === void 0)
453
+ throw new Error("TN_PHYSICS_UNKNOWN_BODY: joint references an unknown body.");
454
+ if (!bodyA.body.isValid() || !bodyB.body.isValid())
455
+ throw new Error("TN_PHYSICS_INVALID_BODY: joint references an invalid body.");
456
+ const joint = options.world.createImpulseJoint(
457
+ jointDescription(options.rapier, normalized),
458
+ bodyA.body,
459
+ bodyB.body,
460
+ true
461
+ );
462
+ if (normalized.limit !== void 0) {
463
+ const revoluteJoint = joint;
464
+ if (typeof revoluteJoint.setLimits !== "function") {
465
+ options.world.removeImpulseJoint(joint, true);
466
+ throw new Error(
467
+ "TN_PHYSICS_JOINT_LIMIT_UNSUPPORTED: web backend cannot set hinge limits."
468
+ );
469
+ }
470
+ revoluteJoint.setLimits(normalized.limit.lower, normalized.limit.upper);
471
+ }
472
+ const id = nextJointId;
473
+ nextJointId += 1;
474
+ joints.set(id, { bodyA: normalized.bodyA, bodyB: normalized.bodyB, handle: joint.handle });
475
+ return id;
476
+ },
315
477
  configureCharacter: (id, characterOptions) => {
316
478
  requireLive();
317
479
  const entry = bodies.get(id);
@@ -342,12 +504,20 @@ function createWebPhysicsSimulation(options) {
342
504
  requireLive();
343
505
  const entry = bodies.get(id);
344
506
  if (entry === void 0) return;
507
+ for (const [jointId, joint] of joints) {
508
+ if (joint.bodyA === id || joint.bodyB === id) removeJointRecord(jointId);
509
+ }
345
510
  bodies.delete(id);
346
511
  byCollider.delete(entry.collider.handle);
512
+ areaIntersections.delete(id);
347
513
  dirtyBodies.delete(entry);
348
514
  if (entry.controller !== void 0) options.world.removeCharacterController(entry.controller);
349
515
  if (entry.body.isValid()) options.world.removeRigidBody(entry.body);
350
516
  },
517
+ removeJoint: (id) => {
518
+ if (disposed) return;
519
+ removeJointRecord(id);
520
+ },
351
521
  setBodyTransform: (id, position) => {
352
522
  requireLive();
353
523
  const entry = bodies.get(id);
@@ -367,6 +537,16 @@ function createWebPhysicsSimulation(options) {
367
537
  requireFiniteVector(force, "force");
368
538
  requireDynamic(bodies.get(id), id, "applyForce").body.addForce(force, true);
369
539
  },
540
+ applyBodyForceAtPoint: (id, force, point) => {
541
+ requireLive();
542
+ requireFiniteVector(force, "force");
543
+ requireFiniteVector(point, "force point");
544
+ requireDynamic(bodies.get(id), id, "applyForceAtPoint").body.addForceAtPoint(
545
+ force,
546
+ point,
547
+ true
548
+ );
549
+ },
370
550
  setBodyLinearVelocity: (id, velocity) => {
371
551
  requireLive();
372
552
  requireFiniteVector(velocity, "velocity");
@@ -386,34 +566,35 @@ function createWebPhysicsSimulation(options) {
386
566
  const id = inputSnapshot.kinematicTransforms[offset];
387
567
  const entry = bodies.get(id);
388
568
  if (entry === void 0) throw new Error("IPhysicsSimulation input body disappeared.");
389
- const target = {
390
- x: inputSnapshot.kinematicTransforms[offset + 1],
391
- y: inputSnapshot.kinematicTransforms[offset + 2],
392
- z: inputSnapshot.kinematicTransforms[offset + 3]
393
- };
394
- const rotation = {
395
- x: inputSnapshot.kinematicTransforms[offset + 4],
396
- y: inputSnapshot.kinematicTransforms[offset + 5],
397
- z: inputSnapshot.kinematicTransforms[offset + 6],
398
- w: inputSnapshot.kinematicTransforms[offset + 7]
399
- };
569
+ const { target, rotation } = kinematicScratch;
570
+ target.x = inputSnapshot.kinematicTransforms[offset + 1];
571
+ target.y = inputSnapshot.kinematicTransforms[offset + 2];
572
+ target.z = inputSnapshot.kinematicTransforms[offset + 3];
573
+ rotation.x = inputSnapshot.kinematicTransforms[offset + 4];
574
+ rotation.y = inputSnapshot.kinematicTransforms[offset + 5];
575
+ rotation.z = inputSnapshot.kinematicTransforms[offset + 6];
576
+ rotation.w = inputSnapshot.kinematicTransforms[offset + 7];
400
577
  if (entry.type === "character") {
401
578
  const controller = entry.controller;
402
579
  const config = entry.character;
403
580
  if (controller === void 0 || config === void 0)
404
581
  throw new Error("Physics character was not configured before stepping.");
405
582
  const current = entry.body.translation();
406
- const desired = {
407
- x: target.x - current.x,
408
- y: target.y - current.y,
409
- z: target.z - current.z
410
- };
583
+ const desired = kinematicScratch.desired;
584
+ desired.x = target.x - current.x;
585
+ desired.y = target.y - current.y;
586
+ desired.z = target.z - current.z;
411
587
  const characterGroups = entry.collider.collisionGroups();
412
- const filterGroups = config.oneWayLayers !== 0 && desired.y > 0 ? interactionGroups(
588
+ const oneWayActive = config.oneWayLayers !== 0 && desired.y > 0;
589
+ const filterGroups = oneWayActive ? interactionGroups(
413
590
  characterGroups >>> 16,
414
591
  characterGroups & 65535 & (65535 ^ config.oneWayLayers)
415
592
  ) : characterGroups;
416
- const filterPredicate = config.oneWayLayers !== 0 && desired.y > 0 ? (collider) => (collider.collisionGroups() >>> 16 & config.oneWayLayers) === 0 : void 0;
593
+ let filterPredicate;
594
+ if (oneWayActive) {
595
+ oneWayFilterLayers = config.oneWayLayers;
596
+ filterPredicate = oneWayFilterPredicate;
597
+ }
417
598
  controller.computeColliderMovement(
418
599
  entry.collider,
419
600
  desired,
@@ -422,11 +603,11 @@ function createWebPhysicsSimulation(options) {
422
603
  filterPredicate
423
604
  );
424
605
  const movement = controller.computedMovement();
425
- entry.body.setNextKinematicTranslation({
426
- x: current.x + movement.x,
427
- y: current.y + movement.y,
428
- z: current.z + movement.z
429
- });
606
+ const nextTranslation = kinematicScratch.nextTranslation;
607
+ nextTranslation.x = current.x + movement.x;
608
+ nextTranslation.y = current.y + movement.y;
609
+ nextTranslation.z = current.z + movement.z;
610
+ entry.body.setNextKinematicTranslation(nextTranslation);
430
611
  } else {
431
612
  if (!entry.body.isKinematic())
432
613
  throw new Error("IPhysicsSimulation received kinematic input for a dynamic body.");
@@ -437,6 +618,7 @@ function createWebPhysicsSimulation(options) {
437
618
  }
438
619
  options.world.timestep = deltaTime;
439
620
  options.world.step(options.eventQueue);
621
+ for (const entry of bodies.values()) entry.body.resetForces(true);
440
622
  dirtyBodies.clear();
441
623
  },
442
624
  readVisibleTransforms: (renderBuffer) => {
@@ -446,16 +628,7 @@ function createWebPhysicsSimulation(options) {
446
628
  for (const entry of bodies.values()) {
447
629
  if (!entry.body.isValid()) continue;
448
630
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
449
- const translation = entry.body.translation();
450
- const rotation = entry.body.rotation();
451
- renderBuffer[offset] = entry.id;
452
- renderBuffer[offset + 1] = translation.x;
453
- renderBuffer[offset + 2] = translation.y;
454
- renderBuffer[offset + 3] = translation.z;
455
- renderBuffer[offset + 4] = rotation.x;
456
- renderBuffer[offset + 5] = rotation.y;
457
- renderBuffer[offset + 6] = rotation.z;
458
- renderBuffer[offset + 7] = rotation.w;
631
+ writeRapierTransformRecord(entry, renderBuffer, offset);
459
632
  index += 1;
460
633
  }
461
634
  return index;
@@ -587,23 +760,27 @@ function createWebPhysicsSimulation(options) {
587
760
  areaIntersections: (id) => {
588
761
  requireLive();
589
762
  const area = bodies.get(id);
590
- if (area === void 0) return /* @__PURE__ */ new Set();
591
- const current = /* @__PURE__ */ new Set();
592
- const areaMask = area.collider.collisionGroups() & 65535;
593
- options.world.intersectionsWithShape(
594
- area.collider.translation(),
595
- area.collider.rotation(),
596
- area.collider.shape,
597
- (collider) => {
598
- const body = byCollider.get(collider.handle);
599
- if (body !== void 0 && body.id !== id && !collider.isSensor() && (collider.collisionGroups() >>> 16 & areaMask) !== 0)
600
- current.add(body.id);
601
- return true;
602
- },
603
- options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
604
- void 0,
605
- area.collider
606
- );
763
+ const current = areaIntersections.get(id);
764
+ if (area === void 0 || current === void 0) return emptyAreaIntersections;
765
+ current.clear();
766
+ areaIntersectionId = id;
767
+ areaIntersectionMask = area.collider.collisionGroups() & 65535;
768
+ areaIntersectionMembers = current;
769
+ try {
770
+ options.world.intersectionsWithShape(
771
+ area.collider.translation(),
772
+ area.collider.rotation(),
773
+ area.collider.shape,
774
+ areaIntersectionCallback,
775
+ options.rapier.QueryFilterFlags.EXCLUDE_SENSORS,
776
+ void 0,
777
+ area.collider
778
+ );
779
+ } finally {
780
+ areaIntersectionMembers = void 0;
781
+ areaIntersectionId = -1;
782
+ areaIntersectionMask = 0;
783
+ }
607
784
  return current;
608
785
  },
609
786
  drainCollisionEvents: (buffer) => {
@@ -612,15 +789,15 @@ function createWebPhysicsSimulation(options) {
612
789
  options.eventQueue.drainCollisionEvents((first, second, started) => {
613
790
  const left = byCollider.get(first)?.id;
614
791
  const right = byCollider.get(second)?.id;
615
- if (left !== void 0 && right !== void 0)
616
- pendingCollisionEvents.push([left, right, Number(started), 1]);
792
+ if (left !== void 0 && right !== void 0) {
793
+ pendingCollisionEvents.push(left, right, Number(started), 1);
794
+ }
617
795
  });
618
- if (buffer.length < pendingCollisionEvents.length * PHYSICS_COLLISION_EVENT_STRIDE)
796
+ const count = pendingCollisionEvents.length / PHYSICS_COLLISION_EVENT_STRIDE;
797
+ if (buffer.length < pendingCollisionEvents.length)
619
798
  throw new Error("IPhysicsSimulation collision event buffer is too small.");
620
- pendingCollisionEvents.forEach(
621
- (event, index) => buffer.set(event, index * PHYSICS_COLLISION_EVENT_STRIDE)
622
- );
623
- const count = pendingCollisionEvents.length;
799
+ for (let index = 0; index < pendingCollisionEvents.length; index += 1)
800
+ buffer[index] = pendingCollisionEvents[index];
624
801
  pendingCollisionEvents.length = 0;
625
802
  return count;
626
803
  },
@@ -634,7 +811,9 @@ function createWebPhysicsSimulation(options) {
634
811
  }
635
812
  bodies.clear();
636
813
  byCollider.clear();
814
+ joints.clear();
637
815
  dirtyBodies.clear();
816
+ areaIntersections.clear();
638
817
  pendingCollisionEvents.length = 0;
639
818
  options.eventQueue.free();
640
819
  options.world.free();
@@ -707,13 +886,27 @@ installPhysicsSimulationBackend({
707
886
  createShape: (shape) => createWebPhysicsShape(rapier, shape)
708
887
  });
709
888
 
889
+ // src/transformRecord.ts
890
+ function bulkTransformValue(values, index) {
891
+ const value = values[index];
892
+ if (value === void 0 || !Number.isFinite(value))
893
+ throw new Error("IPhysicsSimulation returned a malformed transform.");
894
+ return value;
895
+ }
896
+
710
897
  // src/Area3D.ts
711
898
  var MAX_CONTACT_LOG = 1e3;
712
- function finiteTransform(values, offset) {
713
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
714
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
715
- throw new Error("IPhysicsSimulation returned a malformed transform.");
716
- return result;
899
+ var IDENTITY_ROTATION = { w: 1, x: 0, y: 0, z: 0 };
900
+ function resolveInitialTransform(source, fallbackPosition) {
901
+ if (source.object !== void 0 && source.position !== void 0)
902
+ throw new Error("A physics node accepts either object or position, not both.");
903
+ if (source.object !== void 0)
904
+ return { position: source.object.position, rotation: source.object.quaternion };
905
+ if (source.position !== void 0)
906
+ return { position: source.position, rotation: IDENTITY_ROTATION };
907
+ if (fallbackPosition !== void 0)
908
+ return { position: fallbackPosition, rotation: IDENTITY_ROTATION };
909
+ throw new Error("A physics node requires either object or position.");
717
910
  }
718
911
  var Area3D = class {
719
912
  entity;
@@ -734,13 +927,18 @@ var Area3D = class {
734
927
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
735
928
  this.#physics = options.physics;
736
929
  this.entity = options.entity;
737
- Object.assign(this.#position, options.position ?? { x: 0, y: 0, z: 0 });
738
- const shape = options.shape.setSensor(true).descriptor;
739
- if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
740
- const layer = options.collisionLayer ?? shape.collisionLayer;
741
- const mask = options.collisionMask ?? shape.collisionMask;
742
- options.shape.setCollisionGroups(interactionGroups(layer, mask));
743
- }
930
+ Object.assign(this.#position, resolveInitialTransform(options, { x: 0, y: 0, z: 0 }).position);
931
+ const base = options.shape.descriptor;
932
+ const groups = interactionGroups(
933
+ options.collisionLayer ?? base.collisionLayer,
934
+ options.collisionMask ?? base.collisionMask
935
+ );
936
+ const shape = {
937
+ ...base,
938
+ collisionLayer: groups >>> 16,
939
+ collisionMask: groups & 65535,
940
+ sensor: true
941
+ };
744
942
  const registration = this.#simulation.createBody({
745
943
  mass: 0,
746
944
  entity: this.entity,
@@ -750,7 +948,6 @@ var Area3D = class {
750
948
  shape,
751
949
  type: "kinematic"
752
950
  });
753
- options.shape.bindRaw(registration.rawShape);
754
951
  this.body = registration.body;
755
952
  this.collider = registration.collider;
756
953
  this.#physics?.addArea(this);
@@ -777,14 +974,22 @@ var Area3D = class {
777
974
  /** Called by the shared plugin before a bulk step. */
778
975
  writeKinematic(buffer, offset) {
779
976
  if (this.#disposed) return;
780
- buffer.set(
781
- [this.body.id, this.#position.x, this.#position.y, this.#position.z, 0, 0, 0, 1],
782
- offset
783
- );
977
+ buffer[offset] = this.body.id;
978
+ buffer[offset + 1] = this.#position.x;
979
+ buffer[offset + 2] = this.#position.y;
980
+ buffer[offset + 3] = this.#position.z;
981
+ buffer[offset + 4] = 0;
982
+ buffer[offset + 5] = 0;
983
+ buffer[offset + 6] = 0;
984
+ buffer[offset + 7] = 1;
784
985
  }
785
986
  applyTransform(values, offset) {
786
- const [, x, y, z] = finiteTransform(values, offset);
787
- Object.assign(this.#position, { x, y, z });
987
+ const x = bulkTransformValue(values, offset + 1);
988
+ const y = bulkTransformValue(values, offset + 2);
989
+ const z = bulkTransformValue(values, offset + 3);
990
+ this.#position.x = x;
991
+ this.#position.y = y;
992
+ this.#position.z = z;
788
993
  }
789
994
  handleCollision(body, started) {
790
995
  if (this.#disposed || !this.#monitoring) return;
@@ -825,14 +1030,6 @@ var Area3D = class {
825
1030
  this.#listeners.bodyExited.clear();
826
1031
  }
827
1032
  };
828
-
829
- // src/CharacterBody3D.ts
830
- function finiteTransform2(values, offset) {
831
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
832
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
833
- throw new Error("IPhysicsSimulation returned a malformed transform.");
834
- return result;
835
- }
836
1033
  var CharacterBody3D = class {
837
1034
  body;
838
1035
  collider;
@@ -844,6 +1041,12 @@ var CharacterBody3D = class {
844
1041
  maxFallSpeed;
845
1042
  oneWayLayers;
846
1043
  grounded = false;
1044
+ /** Contact normal from the completed physics step; reset to +Y while airborne. */
1045
+ groundNormal = new Vector3(0, 1, 0);
1046
+ /** Portable handle for the body currently supporting this character. */
1047
+ groundBody;
1048
+ /** Radians between `groundNormal` and world up (+Y). */
1049
+ slopeAngle = 0;
847
1050
  #simulation;
848
1051
  #physics;
849
1052
  #desired = { x: 0, y: 0, z: 0 };
@@ -904,18 +1107,29 @@ var CharacterBody3D = class {
904
1107
  this.#physics?.add(this);
905
1108
  }
906
1109
  move(desiredTranslation) {
907
- this.#desired = { x: desiredTranslation.x, y: desiredTranslation.y, z: desiredTranslation.z };
1110
+ this.#desired.x = desiredTranslation.x;
1111
+ this.#desired.y = desiredTranslation.y;
1112
+ this.#desired.z = desiredTranslation.z;
908
1113
  this.#sliding = false;
909
1114
  }
1115
+ /**
1116
+ * Queue velocity-based motion for the shared bulk physics step.
1117
+ *
1118
+ * @remarks
1119
+ * This does not move `object` synchronously. The solver writes the transform after the step, so
1120
+ * reading `object.position` immediately after this call still observes the previous transform.
1121
+ * Three.js `Vector3` instances are mutable, so do not retain `object.position` itself as the
1122
+ * snapshot: use `const before = object.position.clone()` (or copy its `x`, `y`, and `z` scalars).
1123
+ * Compare that snapshot with `object.position` only after the deferred bulk physics step,
1124
+ * typically on the next frame, to measure the motion that the solver applied.
1125
+ */
910
1126
  moveAndSlide(dt) {
911
1127
  if (!Number.isFinite(dt) || dt < 0)
912
1128
  throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
913
1129
  this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
914
- this.#desired = {
915
- x: this.velocity.x * dt,
916
- y: this.velocity.y * dt,
917
- z: this.velocity.z * dt
918
- };
1130
+ this.#desired.x = this.velocity.x * dt;
1131
+ this.#desired.y = this.velocity.y * dt;
1132
+ this.#desired.z = this.velocity.z * dt;
919
1133
  this.#sliding = true;
920
1134
  }
921
1135
  /** Called by the shared plugin before a bulk step. */
@@ -924,19 +1138,17 @@ var CharacterBody3D = class {
924
1138
  this.#beforeY = this.object.position.y;
925
1139
  this.#desiredY = this.#desired.y;
926
1140
  const carry = this.#sliding && this.grounded && this.velocity.y <= 0 && this.#groundCollider !== void 0 ? this.#physics?.kinematicMotion?.(this.#groundCollider) : void 0;
927
- buffer.set(
928
- [
929
- this.body.id,
930
- this.object.position.x + this.#desired.x + (carry?.x ?? 0),
931
- this.object.position.y + this.#desired.y + (carry?.y ?? 0),
932
- this.object.position.z + this.#desired.z + (carry?.z ?? 0),
933
- this.object.quaternion.x,
934
- this.object.quaternion.y,
935
- this.object.quaternion.z,
936
- this.object.quaternion.w
937
- ],
938
- offset
939
- );
1141
+ const carryX = carry?.x ?? 0;
1142
+ const carryY = carry?.y ?? 0;
1143
+ const carryZ = carry?.z ?? 0;
1144
+ buffer[offset] = this.body.id;
1145
+ buffer[offset + 1] = this.object.position.x + this.#desired.x + carryX;
1146
+ buffer[offset + 2] = this.object.position.y + this.#desired.y + carryY;
1147
+ buffer[offset + 3] = this.object.position.z + this.#desired.z + carryZ;
1148
+ buffer[offset + 4] = this.object.quaternion.x;
1149
+ buffer[offset + 5] = this.object.quaternion.y;
1150
+ buffer[offset + 6] = this.object.quaternion.z;
1151
+ buffer[offset + 7] = this.object.quaternion.w;
940
1152
  }
941
1153
  syncToPhysics() {
942
1154
  }
@@ -947,24 +1159,44 @@ var CharacterBody3D = class {
947
1159
  this.#simulation.setBodyTransform(this.body.id, position);
948
1160
  this.object.position.set(position.x, position.y, position.z);
949
1161
  this.velocity.set(0, 0, 0);
950
- this.#desired = { x: 0, y: 0, z: 0 };
1162
+ this.#desired.x = 0;
1163
+ this.#desired.y = 0;
1164
+ this.#desired.z = 0;
951
1165
  this.#sliding = false;
952
- this.#groundCollider = void 0;
953
- this.grounded = false;
1166
+ this.#clearGroundState();
954
1167
  }
955
1168
  applyTransform(values, offset) {
956
- const [, x, y, z, qx, qy, qz, qw] = finiteTransform2(values, offset);
1169
+ const x = bulkTransformValue(values, offset + 1);
1170
+ const y = bulkTransformValue(values, offset + 2);
1171
+ const z = bulkTransformValue(values, offset + 3);
1172
+ const qx = bulkTransformValue(values, offset + 4);
1173
+ const qy = bulkTransformValue(values, offset + 5);
1174
+ const qz = bulkTransformValue(values, offset + 6);
1175
+ const qw = bulkTransformValue(values, offset + 7);
957
1176
  const state = this.#simulation.readCharacterState?.(this.body.id);
958
1177
  this.grounded = state?.grounded ?? (this.#sliding && this.#desiredY < 0 && y - this.#beforeY > this.#desiredY + 1e-4);
959
1178
  this.#groundCollider = state?.groundCollider;
1179
+ if (this.grounded && state?.groundNormal !== void 0) {
1180
+ this.groundNormal.set(state.groundNormal.x, state.groundNormal.y, state.groundNormal.z);
1181
+ this.groundBody = state.groundBody;
1182
+ this.slopeAngle = Math.acos(Math.max(-1, Math.min(1, this.groundNormal.y)));
1183
+ } else if (!this.grounded) {
1184
+ this.#clearGroundState();
1185
+ }
960
1186
  if (this.#sliding && this.grounded && this.velocity.y < 0) this.velocity.y = 0;
961
1187
  this.object.position.set(x, y, z);
962
1188
  this.object.quaternion.set(qx, qy, qz, qw);
963
- this.#desired = { x: 0, y: 0, z: 0 };
1189
+ this.#desired.x = 0;
1190
+ this.#desired.y = 0;
1191
+ this.#desired.z = 0;
964
1192
  this.#sliding = false;
965
1193
  }
966
1194
  syncFromPhysics() {
967
- const transform = this.#simulation.readBodyTransform?.(this.body.id);
1195
+ if (this.#simulation.readBodyTransform === void 0)
1196
+ throw new Error(
1197
+ "TN_PHYSICS_READ_TRANSFORM_MISSING: the active physics backend cannot read body transforms."
1198
+ );
1199
+ const transform = this.#simulation.readBodyTransform(this.body.id);
968
1200
  if (transform === void 0) return;
969
1201
  this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
970
1202
  this.object.quaternion.set(
@@ -979,6 +1211,14 @@ var CharacterBody3D = class {
979
1211
  this.#disposed = true;
980
1212
  this.#physics?.remove(this);
981
1213
  this.#simulation.removeBody(this.body.id);
1214
+ this.#clearGroundState();
1215
+ }
1216
+ #clearGroundState() {
1217
+ this.grounded = false;
1218
+ this.#groundCollider = void 0;
1219
+ this.groundBody = void 0;
1220
+ this.groundNormal.set(0, 1, 0);
1221
+ this.slopeAngle = 0;
982
1222
  }
983
1223
  };
984
1224
 
@@ -1178,6 +1418,227 @@ var CollisionShape3D = class _CollisionShape3D {
1178
1418
  return this;
1179
1419
  }
1180
1420
  };
1421
+ function finite(name, value) {
1422
+ if (typeof value !== "number" || !Number.isFinite(value))
1423
+ throw new Error(`Buoyancy3D.${name} must be finite.`);
1424
+ return value;
1425
+ }
1426
+ function nonNegative(name, value) {
1427
+ finite(name, value);
1428
+ if (value < 0) throw new Error(`Buoyancy3D.${name} must be non-negative.`);
1429
+ return value;
1430
+ }
1431
+ function positive(name, value) {
1432
+ finite(name, value);
1433
+ if (value <= 0) throw new Error(`Buoyancy3D.${name} must be positive.`);
1434
+ return value;
1435
+ }
1436
+ function pointVector(value) {
1437
+ let x;
1438
+ let y;
1439
+ let z;
1440
+ if ("x" in value) {
1441
+ x = value.x;
1442
+ y = value.y;
1443
+ z = value.z;
1444
+ } else {
1445
+ x = value[0];
1446
+ y = value[1];
1447
+ z = value[2];
1448
+ }
1449
+ return new Vector3(
1450
+ finite("hullPoints.position.x", x),
1451
+ finite("hullPoints.position.y", y),
1452
+ finite("hullPoints.position.z", z)
1453
+ );
1454
+ }
1455
+ function shapeVolume(body) {
1456
+ const shape = body.shape.descriptor;
1457
+ if (shape.kind === "box") return 8 * shape.x * shape.y * shape.z;
1458
+ if (shape.kind === "sphere") return 4 / 3 * Math.PI * shape.x ** 3;
1459
+ if (shape.kind === "capsule") return Math.PI * shape.y ** 2 * (2 * shape.x + 4 / 3 * shape.y);
1460
+ return 1;
1461
+ }
1462
+ function clamp01(value) {
1463
+ return Math.max(0, Math.min(1, value));
1464
+ }
1465
+ var Buoyancy3D = class {
1466
+ body;
1467
+ hullPoints;
1468
+ density;
1469
+ drag;
1470
+ gravity;
1471
+ #surface;
1472
+ #physics;
1473
+ #points;
1474
+ #rotation = new Quaternion();
1475
+ #elapsed = 0;
1476
+ #submergedFraction = 0;
1477
+ #enabled;
1478
+ #disposed = false;
1479
+ constructor(options) {
1480
+ if (options.hullPoints.length === 0)
1481
+ throw new Error("Buoyancy3D.hullPoints must contain at least one point.");
1482
+ const surface = options.surface ?? options.heightSource ?? options.field;
1483
+ if (surface === void 0) throw new Error("Buoyancy3D requires a surface height source.");
1484
+ const physics = options.physics ?? options.body.physics;
1485
+ if (physics === void 0 || physics.addBuoyancy === void 0)
1486
+ throw new Error("Buoyancy3D requires the body's physics context.");
1487
+ this.body = options.body;
1488
+ this.hullPoints = options.hullPoints;
1489
+ this.density = positive("density", options.density ?? 1e3);
1490
+ this.drag = nonNegative("drag", options.drag ?? 0);
1491
+ this.gravity = positive("gravity", options.gravity ?? 9.81);
1492
+ this.#surface = surface;
1493
+ this.#physics = physics;
1494
+ this.#enabled = options.buoyancy ?? true;
1495
+ const totalVolume = positive("volume", options.volume ?? shapeVolume(options.body));
1496
+ const yValues = options.hullPoints.map(({ position }) => pointVector(position).y);
1497
+ const minimumY = Math.min(...yValues);
1498
+ const maximumY = Math.max(...yValues);
1499
+ const defaultSpacing = options.pointSpacing ?? Math.max(maximumY - minimumY, 1);
1500
+ const pointVolume = totalVolume / options.hullPoints.length;
1501
+ this.#points = options.hullPoints.map((point) => {
1502
+ const position = pointVector(point.position);
1503
+ const volume = positive("hullPoints.volume", point.volume ?? pointVolume);
1504
+ const spacing = positive("hullPoints.spacing", point.spacing ?? defaultSpacing);
1505
+ return {
1506
+ force: { x: 0, y: 0, z: 0 },
1507
+ position,
1508
+ spacing,
1509
+ submergedFraction: 0,
1510
+ volume,
1511
+ worldPosition: new Vector3()
1512
+ };
1513
+ });
1514
+ this.body.buoyancy = this;
1515
+ physics.addBuoyancy(this);
1516
+ this.#measure();
1517
+ }
1518
+ get enabled() {
1519
+ return this.#enabled;
1520
+ }
1521
+ set enabled(value) {
1522
+ this.#enabled = value;
1523
+ }
1524
+ get buoyancy() {
1525
+ return this.#enabled;
1526
+ }
1527
+ set buoyancy(value) {
1528
+ this.#enabled = value;
1529
+ }
1530
+ get submergedFraction() {
1531
+ return this.#submergedFraction;
1532
+ }
1533
+ get time() {
1534
+ return this.#elapsed;
1535
+ }
1536
+ /** Called by `rapier()` immediately before its fixed-step backend call. */
1537
+ apply(deltaTime) {
1538
+ if (this.#disposed) return;
1539
+ if (!Number.isFinite(deltaTime) || deltaTime < 0)
1540
+ throw new Error("Buoyancy3D.apply requires a finite non-negative deltaTime.");
1541
+ this.#measure();
1542
+ if (this.#enabled) {
1543
+ const velocity = this.body.linearVelocity;
1544
+ for (const point of this.#points) {
1545
+ const submergedVolume = point.volume * point.submergedFraction;
1546
+ if (submergedVolume === 0) continue;
1547
+ point.force.x = -velocity.x * this.drag * submergedVolume;
1548
+ point.force.y = -velocity.y * this.drag * submergedVolume;
1549
+ point.force.z = -velocity.z * this.drag * submergedVolume;
1550
+ point.force.y += this.density * this.gravity * submergedVolume;
1551
+ this.body.applyForceAtPoint(point.force, point.worldPosition);
1552
+ }
1553
+ }
1554
+ this.#elapsed += deltaTime;
1555
+ if (!Number.isFinite(this.#elapsed)) throw new Error("Buoyancy3D time overflowed.");
1556
+ }
1557
+ dispose() {
1558
+ if (this.#disposed) return;
1559
+ this.#disposed = true;
1560
+ this.#physics.removeBuoyancy?.(this);
1561
+ if (this.body.buoyancy === this) this.body.buoyancy = void 0;
1562
+ }
1563
+ #measure() {
1564
+ const points = this.#points;
1565
+ const object = this.body.object;
1566
+ if (object === void 0) throw new Error("Buoyancy3D requires a body with an object.");
1567
+ this.#rotation.copy(object.quaternion);
1568
+ let volume = 0;
1569
+ let submerged = 0;
1570
+ for (const point of points) {
1571
+ point.worldPosition.copy(point.position).applyQuaternion(this.#rotation).add(object.position);
1572
+ const result = this.#surface.sample(
1573
+ point.worldPosition.x,
1574
+ point.worldPosition.z,
1575
+ this.#elapsed
1576
+ );
1577
+ const height = finite("surface.height", result.height);
1578
+ const fraction = clamp01(0.5 + (height - point.worldPosition.y) / point.spacing);
1579
+ point.submergedFraction = fraction;
1580
+ volume += point.volume;
1581
+ submerged += point.volume * fraction;
1582
+ }
1583
+ this.#submergedFraction = volume === 0 ? 0 : submerged / volume;
1584
+ }
1585
+ };
1586
+
1587
+ // src/Joint3D.ts
1588
+ var ZERO_ANCHOR = { x: 0, y: 0, z: 0 };
1589
+ var X_AXIS = { x: 1, y: 0, z: 0 };
1590
+ var IDENTITY_FRAME = { x: 0, y: 0, z: 0, w: 1 };
1591
+ function bodyId(value, label) {
1592
+ const candidate = typeof value === "object" && value !== null && "body" in value ? value.body : value;
1593
+ if (typeof candidate !== "object" || candidate === null || !("id" in candidate) || typeof candidate.id !== "number")
1594
+ throw new Error(`TN_PHYSICS_INVALID_BODY: ${label} must expose a body handle.`);
1595
+ return candidate.id;
1596
+ }
1597
+ var Joint3D = class _Joint3D {
1598
+ id;
1599
+ #simulation;
1600
+ #disposed = false;
1601
+ constructor(simulation, id) {
1602
+ this.#simulation = simulation;
1603
+ this.id = id;
1604
+ }
1605
+ static #create(options, type, extra = {}) {
1606
+ const simulation = requirePhysicsSimulation(options.physics, options.world);
1607
+ const jointOptions = {
1608
+ anchorA: options.anchorA ?? ZERO_ANCHOR,
1609
+ anchorB: options.anchorB ?? ZERO_ANCHOR,
1610
+ bodyA: bodyId(options.bodyA, "bodyA"),
1611
+ bodyB: bodyId(options.bodyB, "bodyB"),
1612
+ ...extra,
1613
+ type
1614
+ };
1615
+ requirePhysicsJointCreateOptions(jointOptions);
1616
+ const id = simulation.createJoint(jointOptions);
1617
+ if (!Number.isSafeInteger(id) || id < 0)
1618
+ throw new Error("TN_PHYSICS_INVALID_JOINT: backend returned an invalid joint id.");
1619
+ return new _Joint3D(simulation, id);
1620
+ }
1621
+ static pin(options) {
1622
+ return _Joint3D.#create(options, "pin");
1623
+ }
1624
+ static hinge(options) {
1625
+ return _Joint3D.#create(options, "hinge", {
1626
+ axis: options.axis ?? X_AXIS,
1627
+ limit: options.limit
1628
+ });
1629
+ }
1630
+ static fixed(options) {
1631
+ return _Joint3D.#create(options, "fixed", {
1632
+ frameA: options.frameA ?? IDENTITY_FRAME,
1633
+ frameB: options.frameB ?? IDENTITY_FRAME
1634
+ });
1635
+ }
1636
+ dispose() {
1637
+ if (this.#disposed) return;
1638
+ this.#disposed = true;
1639
+ this.#simulation.removeJoint(this.id);
1640
+ }
1641
+ };
1181
1642
 
1182
1643
  // src/PhysicsDirectSpaceState3D.ts
1183
1644
  function rayQuery(options) {
@@ -1220,28 +1681,107 @@ var PhysicsDirectSpaceState3D = class {
1220
1681
  return this.#simulation.intersectPoint(pointQuery(options));
1221
1682
  }
1222
1683
  };
1684
+ var ONE = new Vector3(1, 1, 1);
1685
+ var PhysicsSoftBodyCollision = class {
1686
+ capacity;
1687
+ #bodies;
1688
+ #bodyMatrix = new Matrix4();
1689
+ #localMatrix = new Matrix4();
1690
+ #corner = new Vector3();
1691
+ #minimum = new Vector3();
1692
+ #maximum = new Vector3();
1693
+ constructor(bodies) {
1694
+ if (bodies.length === 0)
1695
+ throw new Error("softBodyCollision requires at least one RigidBody3D.");
1696
+ for (const body of bodies) {
1697
+ if (body.shape.descriptor.kind !== "box")
1698
+ throw new Error("softBodyCollision currently supports box shapes only.");
1699
+ if (body.object === void 0)
1700
+ throw new Error("softBodyCollision requires an object transform for every body.");
1701
+ }
1702
+ this.#bodies = bodies;
1703
+ this.capacity = bodies.length;
1704
+ }
1705
+ writeBoxes(target, worldToLocal) {
1706
+ if (target.length !== this.capacity * 8)
1707
+ throw new Error(
1708
+ `softBodyCollision expected ${this.capacity * 8} packed values, received ${target.length}.`
1709
+ );
1710
+ for (let index = 0; index < this.#bodies.length; index += 1) {
1711
+ const body = this.#bodies[index];
1712
+ const object = body.object;
1713
+ if (object === void 0)
1714
+ throw new Error("softBodyCollision body lost its object transform.");
1715
+ this.#bodyMatrix.compose(object.position, object.quaternion, ONE);
1716
+ this.#localMatrix.multiplyMatrices(worldToLocal, this.#bodyMatrix);
1717
+ this.#minimum.set(
1718
+ Number.POSITIVE_INFINITY,
1719
+ Number.POSITIVE_INFINITY,
1720
+ Number.POSITIVE_INFINITY
1721
+ );
1722
+ this.#maximum.set(
1723
+ Number.NEGATIVE_INFINITY,
1724
+ Number.NEGATIVE_INFINITY,
1725
+ Number.NEGATIVE_INFINITY
1726
+ );
1727
+ const shape = body.shape.descriptor;
1728
+ for (let corner = 0; corner < 8; corner += 1) {
1729
+ this.#corner.set(
1730
+ (corner & 1) === 0 ? -shape.x : shape.x,
1731
+ (corner & 2) === 0 ? -shape.y : shape.y,
1732
+ (corner & 4) === 0 ? -shape.z : shape.z
1733
+ ).applyMatrix4(this.#localMatrix);
1734
+ this.#minimum.min(this.#corner);
1735
+ this.#maximum.max(this.#corner);
1736
+ }
1737
+ const offset = index * 8;
1738
+ target[offset] = (this.#minimum.x + this.#maximum.x) / 2;
1739
+ target[offset + 1] = (this.#minimum.y + this.#maximum.y) / 2;
1740
+ target[offset + 2] = (this.#minimum.z + this.#maximum.z) / 2;
1741
+ target[offset + 3] = 0;
1742
+ target[offset + 4] = (this.#maximum.x - this.#minimum.x) / 2;
1743
+ target[offset + 5] = (this.#maximum.y - this.#minimum.y) / 2;
1744
+ target[offset + 6] = (this.#maximum.z - this.#minimum.z) / 2;
1745
+ target[offset + 7] = 0;
1746
+ }
1747
+ return this.#bodies.length;
1748
+ }
1749
+ };
1750
+ function softBodyCollision(...bodies) {
1751
+ return new PhysicsSoftBodyCollision(bodies);
1752
+ }
1223
1753
 
1224
1754
  // src/RigidBody3D.ts
1225
- function finiteTransform3(values, offset) {
1226
- const result = Array.from({ length: 8 }, (_, index) => values[offset + index]);
1227
- if (result.some((value) => value === void 0 || !Number.isFinite(value)))
1228
- throw new Error("IPhysicsSimulation returned a malformed transform.");
1229
- return result;
1230
- }
1231
1755
  var RigidBody3D = class {
1232
1756
  body;
1233
1757
  collider;
1758
+ /** The supplied transform; position-only fixed bodies have no runtime object. */
1234
1759
  object;
1760
+ shape;
1235
1761
  type;
1762
+ mass;
1763
+ buoyancy;
1236
1764
  #simulation;
1237
1765
  #physics;
1766
+ #object;
1238
1767
  #lastPosition;
1768
+ // Scratch returned by kinematicMotion(); the plugin retains it only within one update pass.
1769
+ #motion = { x: 0, y: 0, z: 0 };
1770
+ #zeroMotion = { x: 0, y: 0, z: 0 };
1239
1771
  #disposed = false;
1240
1772
  constructor(options) {
1773
+ const initial = resolveInitialTransform(options);
1774
+ const type = options.type ?? "dynamic";
1775
+ if (options.object === void 0 && type !== "fixed")
1776
+ throw new Error("RigidBody3D position-only bodies must be fixed.");
1241
1777
  this.#simulation = requirePhysicsSimulation(options.physics, options.world);
1242
1778
  this.#physics = options.physics;
1243
1779
  this.object = options.object;
1244
- this.type = options.type ?? "dynamic";
1780
+ this.shape = options.shape;
1781
+ this.#object = options.object;
1782
+ this.type = type;
1783
+ this.mass = options.mass ?? 0;
1784
+ this.buoyancy = void 0;
1245
1785
  const shape = options.shape.descriptor;
1246
1786
  if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
1247
1787
  const layer = options.collisionLayer ?? shape.collisionLayer;
@@ -1250,9 +1790,9 @@ var RigidBody3D = class {
1250
1790
  }
1251
1791
  const registration = this.#simulation.createBody({
1252
1792
  entity: options.entity,
1253
- mass: options.mass ?? 0,
1254
- position: this.object.position,
1255
- rotation: this.object.quaternion,
1793
+ mass: this.mass,
1794
+ position: initial.position,
1795
+ rotation: initial.rotation,
1256
1796
  sensor: shape.sensor,
1257
1797
  shape,
1258
1798
  type: this.type
@@ -1261,36 +1801,36 @@ var RigidBody3D = class {
1261
1801
  this.body = registration.body;
1262
1802
  this.collider = registration.collider;
1263
1803
  this.#lastPosition = {
1264
- x: this.object.position.x,
1265
- y: this.object.position.y,
1266
- z: this.object.position.z
1804
+ x: initial.position.x,
1805
+ y: initial.position.y,
1806
+ z: initial.position.z
1267
1807
  };
1268
1808
  this.#physics?.add(this);
1269
1809
  }
1810
+ get physics() {
1811
+ return this.#physics;
1812
+ }
1270
1813
  /** Called by the shared plugin before a bulk step. */
1271
1814
  writeKinematic(buffer, offset) {
1272
- if (this.#disposed) return;
1273
- buffer.set(
1274
- [
1275
- this.body.id,
1276
- this.object.position.x,
1277
- this.object.position.y,
1278
- this.object.position.z,
1279
- this.object.quaternion.x,
1280
- this.object.quaternion.y,
1281
- this.object.quaternion.z,
1282
- this.object.quaternion.w
1283
- ],
1284
- offset
1285
- );
1815
+ const object = this.#object;
1816
+ if (this.#disposed || object === void 0) return;
1817
+ buffer[offset] = this.body.id;
1818
+ buffer[offset + 1] = object.position.x;
1819
+ buffer[offset + 2] = object.position.y;
1820
+ buffer[offset + 3] = object.position.z;
1821
+ buffer[offset + 4] = object.quaternion.x;
1822
+ buffer[offset + 5] = object.quaternion.y;
1823
+ buffer[offset + 6] = object.quaternion.z;
1824
+ buffer[offset + 7] = object.quaternion.w;
1286
1825
  }
1287
1826
  /** Displacement since the last backend transform, used for moving-platform carry. */
1288
1827
  kinematicMotion() {
1289
- return {
1290
- x: this.object.position.x - this.#lastPosition.x,
1291
- y: this.object.position.y - this.#lastPosition.y,
1292
- z: this.object.position.z - this.#lastPosition.z
1293
- };
1828
+ const object = this.#object;
1829
+ if (object === void 0) return this.#zeroMotion;
1830
+ this.#motion.x = object.position.x - this.#lastPosition.x;
1831
+ this.#motion.y = object.position.y - this.#lastPosition.y;
1832
+ this.#motion.z = object.position.z - this.#lastPosition.z;
1833
+ return this.#motion;
1294
1834
  }
1295
1835
  syncToPhysics() {
1296
1836
  }
@@ -1310,6 +1850,11 @@ var RigidBody3D = class {
1310
1850
  this.#requireLive("applyForce");
1311
1851
  this.#simulation.applyBodyForce(this.body.id, force);
1312
1852
  }
1853
+ /** Godot's force-at-position equivalent. Continuous push in world space; cleared each step. */
1854
+ applyForceAtPoint(force, point) {
1855
+ this.#requireLive("applyForceAtPoint");
1856
+ this.#simulation.applyBodyForceAtPoint(this.body.id, force, point);
1857
+ }
1313
1858
  /** Godot's `linear_velocity`. */
1314
1859
  get linearVelocity() {
1315
1860
  this.#requireLive("linearVelocity");
@@ -1323,26 +1868,46 @@ var RigidBody3D = class {
1323
1868
  if (this.#disposed) throw new Error(`RigidBody3D.${operation} cannot be used after dispose.`);
1324
1869
  }
1325
1870
  syncFromPhysics() {
1326
- const transform = this.#simulation.readBodyTransform?.(this.body.id);
1871
+ const object = this.#object;
1872
+ if (object === void 0) return;
1873
+ if (this.#simulation.readBodyTransform === void 0)
1874
+ throw new Error(
1875
+ "TN_PHYSICS_READ_TRANSFORM_MISSING: the active physics backend cannot read body transforms."
1876
+ );
1877
+ const transform = this.#simulation.readBodyTransform(this.body.id);
1327
1878
  if (transform === void 0) return;
1328
- this.object.position.set(transform.position.x, transform.position.y, transform.position.z);
1329
- this.object.quaternion.set(
1879
+ object.position.set(transform.position.x, transform.position.y, transform.position.z);
1880
+ object.quaternion.set(
1330
1881
  transform.rotation.x,
1331
1882
  transform.rotation.y,
1332
1883
  transform.rotation.z,
1333
1884
  transform.rotation.w
1334
1885
  );
1335
- this.#lastPosition = { ...transform.position };
1886
+ this.#lastPosition.x = transform.position.x;
1887
+ this.#lastPosition.y = transform.position.y;
1888
+ this.#lastPosition.z = transform.position.z;
1336
1889
  }
1337
1890
  applyTransform(values, offset) {
1338
- const [, x, y, z, qx, qy, qz, qw] = finiteTransform3(values, offset);
1339
- this.object.position.set(x, y, z);
1340
- this.object.quaternion.set(qx, qy, qz, qw);
1341
- this.#lastPosition = { x, y, z };
1891
+ const x = bulkTransformValue(values, offset + 1);
1892
+ const y = bulkTransformValue(values, offset + 2);
1893
+ const z = bulkTransformValue(values, offset + 3);
1894
+ const qx = bulkTransformValue(values, offset + 4);
1895
+ const qy = bulkTransformValue(values, offset + 5);
1896
+ const qz = bulkTransformValue(values, offset + 6);
1897
+ const qw = bulkTransformValue(values, offset + 7);
1898
+ const object = this.#object;
1899
+ if (object === void 0) return;
1900
+ object.position.set(x, y, z);
1901
+ object.quaternion.set(qx, qy, qz, qw);
1902
+ this.#lastPosition.x = x;
1903
+ this.#lastPosition.y = y;
1904
+ this.#lastPosition.z = z;
1342
1905
  }
1343
1906
  dispose() {
1344
1907
  if (this.#disposed) return;
1345
1908
  this.#disposed = true;
1909
+ this.buoyancy?.dispose();
1910
+ this.buoyancy = void 0;
1346
1911
  this.#physics?.remove(this);
1347
1912
  this.#simulation.removeBody(this.body.id);
1348
1913
  }
@@ -1351,6 +1916,7 @@ var RigidBody3D = class {
1351
1916
  // src/plugin.ts
1352
1917
  var PHYSICS_DEBUG_BODY_LIMIT = 100;
1353
1918
  var PHYSICS_DEBUG_SAMPLE_LIMIT = 100;
1919
+ var PHYSICS_BUFFER_RESIZE_ATTEMPTS = 12;
1354
1920
  function growFloat(buffer, records) {
1355
1921
  if (buffer.length >= records * PHYSICS_TRANSFORM_STRIDE) return buffer;
1356
1922
  return new Float32Array(
@@ -1379,6 +1945,8 @@ function rapier2(options = {}) {
1379
1945
  const bodies = /* @__PURE__ */ new Set();
1380
1946
  const bodiesById = /* @__PURE__ */ new Map();
1381
1947
  const areas = /* @__PURE__ */ new Map();
1948
+ const buoyancies = /* @__PURE__ */ new Set();
1949
+ const areaMembershipBuffers = /* @__PURE__ */ new Map();
1382
1950
  const kinematicMotions = /* @__PURE__ */ new Map();
1383
1951
  let kinematic = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
1384
1952
  let visible = new Float32Array(PHYSICS_TRANSFORM_STRIDE * 16);
@@ -1396,7 +1964,14 @@ function rapier2(options = {}) {
1396
1964
  bodies.add(body);
1397
1965
  bodiesById.set(body.body.id, body);
1398
1966
  },
1399
- addArea: (area) => areas.set(area.body.id, area),
1967
+ addArea: (area) => {
1968
+ areas.set(area.body.id, area);
1969
+ areaMembershipBuffers.set(area.body.id, {
1970
+ current: /* @__PURE__ */ new Map(),
1971
+ previous: /* @__PURE__ */ new Map()
1972
+ });
1973
+ },
1974
+ addBuoyancy: (buoyancy) => buoyancies.add(buoyancy),
1400
1975
  eventQueue: physicsHandle(selected.rawEventQueue),
1401
1976
  kinematicMotion: (colliderHandle) => kinematicMotions.get(colliderHandle),
1402
1977
  numBodies: () => bodies.size,
@@ -1407,8 +1982,10 @@ function rapier2(options = {}) {
1407
1982
  },
1408
1983
  removeArea: (area) => {
1409
1984
  areas.delete(area.body.id);
1985
+ areaMembershipBuffers.delete(area.body.id);
1410
1986
  removeContactsFor(area.body.id);
1411
1987
  },
1988
+ removeBuoyancy: (buoyancy) => buoyancies.delete(buoyancy),
1412
1989
  directSpaceState: new PhysicsDirectSpaceState3D(selected),
1413
1990
  simulation: selected,
1414
1991
  world: physicsWorldHandle(selected.rawWorld, selected)
@@ -1454,20 +2031,30 @@ function rapier2(options = {}) {
1454
2031
  kinematicCount: count,
1455
2032
  kinematicTransforms: kinematic
1456
2033
  };
2034
+ for (const buoyancy of buoyancies) buoyancy.apply(dt);
1457
2035
  simulation.step(dt, input);
1458
2036
  visible = growFloat(visible, bodies.size + areas.size);
1459
- visibleCount = simulation.readVisibleTransforms(visible);
2037
+ let visibleResizeAttempts = 0;
2038
+ for (; ; ) {
2039
+ try {
2040
+ visibleCount = simulation.readVisibleTransforms(visible);
2041
+ break;
2042
+ } catch (error) {
2043
+ if (!isSmallBufferError(error) || visibleResizeAttempts >= PHYSICS_BUFFER_RESIZE_ATTEMPTS)
2044
+ throw error;
2045
+ visibleResizeAttempts += 1;
2046
+ visible = growFloat(visible, Math.ceil(visible.length / PHYSICS_TRANSFORM_STRIDE) * 2);
2047
+ }
2048
+ }
1460
2049
  for (let index = 0; index < visibleCount; index += 1) {
1461
2050
  const offset = index * PHYSICS_TRANSFORM_STRIDE;
1462
2051
  const id = visibleId(visible, offset);
1463
2052
  const body = bodiesById.get(id);
1464
- if (body !== void 0) body.applyTransform(visible, offset);
1465
- else {
1466
- const area = areas.get(id);
1467
- if (area === void 0)
1468
- throw new Error("IPhysicsSimulation returned an unknown visible body id.");
1469
- area.applyTransform(visible, offset);
2053
+ if (body !== void 0) {
2054
+ body.applyTransform(visible, offset);
2055
+ continue;
1470
2056
  }
2057
+ areas.get(id)?.applyTransform(visible, offset);
1471
2058
  }
1472
2059
  events = growEvents(events, bodies.size + areas.size);
1473
2060
  const maximumEventValues = Math.max(
@@ -1505,12 +2092,18 @@ function rapier2(options = {}) {
1505
2092
  }
1506
2093
  if (simulation.areaIntersections !== void 0) {
1507
2094
  for (const area of areas.values()) {
1508
- const current = /* @__PURE__ */ new Map();
1509
- for (const bodyId of simulation.areaIntersections(area.body.id)) {
1510
- const body = bodiesById.get(bodyId);
1511
- if (body !== void 0) current.set(bodyId, body);
2095
+ const buffers = areaMembershipBuffers.get(area.body.id);
2096
+ if (buffers === void 0)
2097
+ throw new Error("Physics area membership buffers lost a registered area.");
2098
+ const current = buffers.current;
2099
+ current.clear();
2100
+ for (const bodyId2 of simulation.areaIntersections(area.body.id)) {
2101
+ const body = bodiesById.get(bodyId2);
2102
+ if (body !== void 0) current.set(bodyId2, body);
1512
2103
  }
1513
2104
  area.reconcileIntersections(current);
2105
+ buffers.current = buffers.previous;
2106
+ buffers.previous = current;
1514
2107
  }
1515
2108
  }
1516
2109
  kinematicMotions.clear();
@@ -1522,8 +2115,11 @@ function rapier2(options = {}) {
1522
2115
  // before any input. A scene therefore gets a pristine simulation, which makes restart
1523
2116
  // deterministic without a game having to discover an API for it.
1524
2117
  sceneExit: (ctx) => {
2118
+ for (const buoyancy of [...buoyancies]) buoyancy.dispose();
1525
2119
  for (const area of [...areas.values()]) area.dispose();
1526
2120
  for (const body of [...bodies]) body.dispose();
2121
+ areaMembershipBuffers.clear();
2122
+ buoyancies.clear();
1527
2123
  kinematicMotions.clear();
1528
2124
  activeContacts.clear();
1529
2125
  debugSeries = [];
@@ -1540,8 +2136,11 @@ function rapier2(options = {}) {
1540
2136
  dispose: () => {
1541
2137
  unregisterObservations?.();
1542
2138
  unregisterObservations = void 0;
2139
+ for (const buoyancy of [...buoyancies]) buoyancy.dispose();
1543
2140
  for (const area of [...areas.values()]) area.dispose();
1544
2141
  for (const body of [...bodies]) body.dispose();
2142
+ areaMembershipBuffers.clear();
2143
+ buoyancies.clear();
1545
2144
  simulation?.dispose();
1546
2145
  simulation = void 0;
1547
2146
  context = void 0;
@@ -1639,9 +2238,9 @@ function rapier2(options = {}) {
1639
2238
  }
1640
2239
  };
1641
2240
  }
1642
- function removeContactsFor(bodyId) {
2241
+ function removeContactsFor(bodyId2) {
1643
2242
  for (const [key, pair] of activeContacts) {
1644
- if (pair.includes(bodyId)) activeContacts.delete(key);
2243
+ if (pair.includes(bodyId2)) activeContacts.delete(key);
1645
2244
  }
1646
2245
  }
1647
2246
  }
@@ -1651,14 +2250,18 @@ function growSleepStates(buffer, bodyCount) {
1651
2250
  return new Float32Array(Math.max(required, buffer.length * 2));
1652
2251
  }
1653
2252
  function physicsEntityId(ctx, body) {
2253
+ const object = body.object;
2254
+ const stableId = body.body.entity ?? `physics.body.${body.body.id}`;
1654
2255
  for (const id of Object.keys(ctx.entities.snapshot())) {
1655
2256
  const entity = ctx.entities.get(id);
1656
- if (entity === body || entity === body.object) return id;
1657
- if (entity !== void 0 && Object.values(entity).some((value) => value === body || value === body.object)) {
2257
+ if (entity === body || object !== void 0 && entity === object) return id;
2258
+ if (entity !== void 0 && Object.values(entity).some(
2259
+ (value) => value === body || object !== void 0 && value === object
2260
+ )) {
1658
2261
  return id;
1659
2262
  }
1660
2263
  }
1661
- return `physics.body.${body.body.id}`;
2264
+ return stableId;
1662
2265
  }
1663
2266
 
1664
- export { Area3D, CharacterBody3D, CollisionShape3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, interactionGroups, rapier2 as rapier };
2267
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, interactionGroups, rapier2 as rapier, softBodyCollision };