@threenative/physics 0.3.11 → 0.3.12

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.
@@ -359,6 +359,8 @@ declare class CollisionShape3D {
359
359
  y: number;
360
360
  z: number;
361
361
  }): CollisionShape3D;
362
+ /** Godot's ConcavePolygonShape3D: x, y, z vertex triples in body-local metres and triangle indices. */
363
+ static trimesh(vertices: Float32Array, indices: Uint32Array): CollisionShape3D;
362
364
  static fromMesh(mesh: Mesh, kind?: CollisionShapeKind): CollisionShape3D;
363
365
  setCollisionGroups(groups: number): this;
364
366
  setSensor(sensor: boolean): this;
@@ -556,7 +558,45 @@ interface ICharacterBody3DOptions {
556
558
  * which reads as a physics bug rather than a default.
557
559
  */
558
560
  readonly pushesDynamicBodies?: boolean;
559
- }
561
+ /**
562
+ * The water surface height in metres at world (x, z), or `undefined` where there is none. With
563
+ * it the body swims the way Unreal's CharacterMovementComponent does: once its centre is under
564
+ * the surface it is `swimming`, buoyancy and fluid friction replace gravity, and its horizontal
565
+ * speed is held to `maxSwimSpeed`; shallower water only slows it. Without it nothing changes.
566
+ */
567
+ readonly water?: CharacterWaterQuery;
568
+ /**
569
+ * The water's own velocity at world (x, z) in m/s, or `undefined` where there is none. While any
570
+ * part of the body is under water it is carried downstream, added to its horizontal motion before
571
+ * its own move input: a swimmer floats at the river's full speed, and a wader, whose feet hold the
572
+ * bed, takes a share that grows with depth until its centre goes under. Unreal pushes a body in a
573
+ * river towards the spline's own velocity while it moves slower than the water, so a floating body
574
+ * settles at the water's speed (UE 5.8.3:
575
+ * Engine/Plugins/Experimental/Water/Source/Runtime/Private/BuoyancyComponent.cpp:724-753).
576
+ * Without it nothing changes.
577
+ */
578
+ readonly waterCurrent?: CharacterWaterCurrentQuery;
579
+ /**
580
+ * Unreal's `Buoyancy`: the body floats where `buoyancy * immersionDepth = 1`. Default 1.6, which
581
+ * floats it with its centre just under the surface. Unreal ships 1.0, which is neutral: the body
582
+ * drifts to the bottom.
583
+ */
584
+ readonly buoyancy?: number;
585
+ /** Unreal's `MaxSwimSpeed` in m/s: half its walk speed. Default 3. */
586
+ readonly maxSwimSpeed?: number;
587
+ /**
588
+ * Unreal's water-volume `FluidFriction`, applied to vertical speed while swimming. Default 12,
589
+ * which settles a swimmer in about a second; Unreal's 0.3 bobs it for many seconds.
590
+ */
591
+ readonly fluidFriction?: number;
592
+ }
593
+ /** Water surface height at world (x, z), or `undefined` where there is no water. */
594
+ type CharacterWaterQuery = (x: number, z: number) => number | undefined;
595
+ /** The water's own velocity in m/s at world (x, z), or `undefined` where there is no water. */
596
+ type CharacterWaterCurrentQuery = (x: number, z: number) => {
597
+ x: number;
598
+ z: number;
599
+ } | undefined;
560
600
  declare class CharacterBody3D {
561
601
  #private;
562
602
  readonly body: IPhysicsBodyHandle;
@@ -575,6 +615,28 @@ declare class CharacterBody3D {
575
615
  groundBody: IPhysicsBodyHandle | undefined;
576
616
  /** Radians between `groundNormal` and world up (+Y). */
577
617
  slopeAngle: number;
618
+ /** See `ICharacterBody3DOptions.water`; assign it once the water exists. */
619
+ water: CharacterWaterQuery | undefined;
620
+ /** See `ICharacterBody3DOptions.waterCurrent`; assign it once the water exists. */
621
+ waterCurrent: CharacterWaterCurrentQuery | undefined;
622
+ /**
623
+ * The water's own velocity the last `moveAndSlide` applied, in m/s: the full current while
624
+ * swimming, a depth-weighted share of it while wading, `(0, 0)` out of water. Read it to tell a
625
+ * drift from a step.
626
+ */
627
+ readonly currentVelocity: {
628
+ x: number;
629
+ z: number;
630
+ };
631
+ buoyancy: number;
632
+ maxSwimSpeed: number;
633
+ fluidFriction: number;
634
+ /** True while the body's centre is under the water surface (Unreal's MOVE_Swimming). */
635
+ swimming: boolean;
636
+ /** Unreal's `ImmersionDepth`: the share of the collider's height under water, 0 to 1. */
637
+ immersionDepth: number;
638
+ /** The water surface height the last `moveAndSlide` read, or `undefined` out of water. */
639
+ waterSurface: number | undefined;
578
640
  /** Draw between solved ticks; false presents this body at its true tick pose. */
579
641
  get interpolate(): boolean;
580
642
  set interpolate(enabled: boolean);
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-AgKEDg0q.js';
2
- export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-AgKEDg0q.js';
3
- import { Object3D } from 'three';
1
+ import { I as IPhysicsContext, a as IPhysicsWorldHandle, b as IPhysicsBodyHandle, c as IPhysicsVector3, d as IPhysicsRotation, e as IPhysicsJointLimit, R as RigidBody3D, f as IPhysicsColliderHandle, P as PhysicsBody3D, C as CollisionShape3D, g as IPhysicsVehicleWheelOptions } from './Area3D-D03tyOlF.js';
2
+ export { A as Area3D, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, n as ICollisionShapeHandle, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, s as IPhysicsCharacterOptions, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, X as PhysicsQueryVector3, Y as PhysicsShapeKind, Z as RigidBodyType, _ as rapier } from './Area3D-D03tyOlF.js';
3
+ import { Object3D, BufferGeometry, Matrix4 } from 'three';
4
4
  import { ISoftBodyCollision } from '@threenative/core';
5
5
  import { ISnowFootprint, SnowField } from '@threenative/core/world';
6
6
  import 'recast-navigation';
@@ -70,6 +70,59 @@ type StaticColliderFilter = StaticColliderPredicate | IBuildStaticCollidersOptio
70
70
  */
71
71
  declare function buildStaticColliders(context: IStaticColliderContext, root: Object3D, filter?: StaticColliderFilter): readonly RigidBody3D[];
72
72
 
73
+ /** How one scattered instance collides. "auto" measures its geometry; the rest force a shape. */
74
+ type ScatterCollision = "auto" | "hull" | "trunk" | "none";
75
+ interface IScatterColliderInstance {
76
+ /** The solid part (stone, bark; not leaves or grass), local to the instance, base at the bottom. */
77
+ readonly geometry: BufferGeometry;
78
+ /** The instance's world transform. */
79
+ readonly matrix: Matrix4;
80
+ /** Named override of the measured shape. Default "auto". */
81
+ readonly collision?: ScatterCollision;
82
+ }
83
+ interface IScatterCollidersOptions {
84
+ readonly physics: IPhysicsContext;
85
+ readonly instances: Iterable<IScatterColliderInstance>;
86
+ /** The point bodies stream around, read on every update: usually the player. */
87
+ readonly follow: {
88
+ readonly position: {
89
+ readonly x: number;
90
+ readonly z: number;
91
+ };
92
+ };
93
+ /** Horizontal metres around `follow` that hold bodies. Default 40. */
94
+ readonly radius?: number;
95
+ readonly collisionLayer?: number;
96
+ readonly collisionMask?: number;
97
+ }
98
+ interface IScatterCollidersStats {
99
+ readonly instances: number;
100
+ readonly hulls: number;
101
+ readonly trunks: number;
102
+ readonly skipped: number;
103
+ readonly resident: number;
104
+ }
105
+ /**
106
+ * Fixed bodies for scattered props (rocks, trunks), created near a followed point and released
107
+ * past it, so 100k placements cost one cheap scan per few metres walked and only the nearby
108
+ * bodies live in the physics world. Unreal gives each foliage instance a body from its mesh's
109
+ * simple collision (UE 5.8.3: Engine/Source/Runtime/Engine/Private/InstancedStaticMesh.cpp:2847,
110
+ * :2875) and World Partition streams them with the cell; here the follow radius is the cell.
111
+ *
112
+ * Shapes are measured, never authored: a slender base becomes a capsule around the trunk (the
113
+ * crown and branch wood stay passable), anything else becomes the 18-DOP hull Unreal generates on
114
+ * import, and pieces under knee height or thinner than a stem get no body. `collision` on an
115
+ * instance overrides the measurement by name.
116
+ */
117
+ declare class ScatterColliders {
118
+ #private;
119
+ constructor(options: IScatterCollidersOptions);
120
+ /** Create the bodies the follow point nears and release the ones it left. Cheap to call per frame. */
121
+ update(): void;
122
+ stats(): IScatterCollidersStats;
123
+ dispose(): void;
124
+ }
125
+
73
126
  /** Adapt existing physics bodies into `SoftBody3D` collision input without a second shape API. */
74
127
  declare function softBodyCollision(...bodies: readonly RigidBody3D[]): ISoftBodyCollision;
75
128
 
@@ -270,4 +323,4 @@ declare class VehicleBody3D extends RigidBody3D {
270
323
  dispose(): void;
271
324
  }
272
325
 
273
- export { CollisionShape3D, type IBuildStaticCollidersOptions, type IFixedJoint3DOptions, type IHingeJoint3DOptions, type IJoint3DOptions, IPhysicsBodyHandle, IPhysicsColliderHandle, IPhysicsContext, IPhysicsJointLimit, IPhysicsRotation, IPhysicsVector3, IPhysicsWorldHandle, type IPinJoint3DOptions, type ISnowPhysicsBinding, type ISnowPhysicsObservation, type ISnowPhysicsOptions, type IStaticColliderContext, type IVehicleBody3DOptions, type IVehicleWheel3D, Joint3D, PhysicsBody3D, type PhysicsJointBody, RigidBody3D, type StaticColliderPredicate, VehicleBody3D, type VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision };
326
+ export { CollisionShape3D, type IBuildStaticCollidersOptions, type IFixedJoint3DOptions, type IHingeJoint3DOptions, type IJoint3DOptions, IPhysicsBodyHandle, IPhysicsColliderHandle, IPhysicsContext, IPhysicsJointLimit, IPhysicsRotation, IPhysicsVector3, IPhysicsWorldHandle, type IPinJoint3DOptions, type IScatterColliderInstance, type IScatterCollidersOptions, type IScatterCollidersStats, type ISnowPhysicsBinding, type ISnowPhysicsObservation, type ISnowPhysicsOptions, type IStaticColliderContext, type IVehicleBody3DOptions, type IVehicleWheel3D, Joint3D, PhysicsBody3D, type PhysicsJointBody, RigidBody3D, ScatterColliders, type ScatterCollision, type StaticColliderPredicate, VehicleBody3D, type VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as rapier from '@dimforge/rapier3d-compat';
2
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
2
+ import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
3
3
  import { snowDiscFootprint } from '@threenative/core/world';
4
4
 
5
5
  // src/web.ts
@@ -1357,6 +1357,10 @@ var Area3D = class {
1357
1357
  this.#listeners.bodyExited.clear();
1358
1358
  }
1359
1359
  };
1360
+ function halfHeightOf(shape) {
1361
+ const { kind, x, y } = shape.descriptor;
1362
+ return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
1363
+ }
1360
1364
  var CharacterBody3D = class {
1361
1365
  body;
1362
1366
  collider;
@@ -1374,6 +1378,26 @@ var CharacterBody3D = class {
1374
1378
  groundBody;
1375
1379
  /** Radians between `groundNormal` and world up (+Y). */
1376
1380
  slopeAngle = 0;
1381
+ /** See `ICharacterBody3DOptions.water`; assign it once the water exists. */
1382
+ water;
1383
+ /** See `ICharacterBody3DOptions.waterCurrent`; assign it once the water exists. */
1384
+ waterCurrent;
1385
+ /**
1386
+ * The water's own velocity the last `moveAndSlide` applied, in m/s: the full current while
1387
+ * swimming, a depth-weighted share of it while wading, `(0, 0)` out of water. Read it to tell a
1388
+ * drift from a step.
1389
+ */
1390
+ currentVelocity = { x: 0, z: 0 };
1391
+ buoyancy;
1392
+ maxSwimSpeed;
1393
+ fluidFriction;
1394
+ /** True while the body's centre is under the water surface (Unreal's MOVE_Swimming). */
1395
+ swimming = false;
1396
+ /** Unreal's `ImmersionDepth`: the share of the collider's height under water, 0 to 1. */
1397
+ immersionDepth = 0;
1398
+ /** The water surface height the last `moveAndSlide` read, or `undefined` out of water. */
1399
+ waterSurface;
1400
+ #halfHeight;
1377
1401
  #simulation;
1378
1402
  #physics;
1379
1403
  #desired = { x: 0, y: 0, z: 0 };
@@ -1403,6 +1427,16 @@ var CharacterBody3D = class {
1403
1427
  this.gravity = options.gravity ?? -9.81;
1404
1428
  this.maxFallSpeed = options.maxFallSpeed ?? 50;
1405
1429
  this.oneWayLayers = options.oneWayLayers ?? 0;
1430
+ this.water = options.water;
1431
+ this.waterCurrent = options.waterCurrent;
1432
+ this.buoyancy = options.buoyancy ?? 1.6;
1433
+ this.maxSwimSpeed = options.maxSwimSpeed ?? 3;
1434
+ this.fluidFriction = options.fluidFriction ?? 12;
1435
+ if (!(this.buoyancy >= 0 && this.maxSwimSpeed > 0 && this.fluidFriction >= 0))
1436
+ throw new Error(
1437
+ "CharacterBody3D needs buoyancy >= 0, maxSwimSpeed > 0 and fluidFriction >= 0."
1438
+ );
1439
+ this.#halfHeight = halfHeightOf(options.shape);
1406
1440
  const shape = options.shape.descriptor;
1407
1441
  if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
1408
1442
  const layer = options.collisionLayer ?? shape.collisionLayer;
@@ -1466,10 +1500,27 @@ var CharacterBody3D = class {
1466
1500
  moveAndSlide(dt) {
1467
1501
  if (!Number.isFinite(dt) || dt < 0)
1468
1502
  throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
1469
- this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
1470
- this.#desired.x = this.velocity.x * dt;
1503
+ const depth = this.#immerse();
1504
+ let fall = this.gravity;
1505
+ if (this.swimming) {
1506
+ const rise = 0.33 * this.maxSwimSpeed;
1507
+ if (this.velocity.y > rise) this.velocity.y = Math.max(rise, this.velocity.y * depth * depth);
1508
+ this.velocity.y *= 1 - Math.min(0.5 * this.fluidFriction * depth * dt, 1);
1509
+ fall *= 1 - this.buoyancy * depth;
1510
+ }
1511
+ this.velocity.y = Math.max(this.velocity.y + fall * dt, -this.maxFallSpeed);
1512
+ if (depth > 0) {
1513
+ const cap = this.maxSwimSpeed / Math.min(1, 2 * depth);
1514
+ const speed = Math.hypot(this.velocity.x, this.velocity.z);
1515
+ if (speed > cap) {
1516
+ this.velocity.x *= cap / speed;
1517
+ this.velocity.z *= cap / speed;
1518
+ }
1519
+ }
1520
+ this.#carry(depth);
1521
+ this.#desired.x = (this.velocity.x + this.currentVelocity.x) * dt;
1471
1522
  this.#desired.y = this.velocity.y * dt;
1472
- this.#desired.z = this.velocity.z * dt;
1523
+ this.#desired.z = (this.velocity.z + this.currentVelocity.z) * dt;
1473
1524
  this.#sliding = true;
1474
1525
  }
1475
1526
  /** Called by the shared plugin before a bulk step. */
@@ -1555,6 +1606,37 @@ var CharacterBody3D = class {
1555
1606
  this.#simulation.removeBody(this.body.id);
1556
1607
  this.#clearGroundState();
1557
1608
  }
1609
+ /**
1610
+ * UE 5.8.3 river forces settle a floating body at the water's own speed, so a swimmer (centre
1611
+ * under, `immersionDepth > 0.5`) takes the whole current. A wader's feet hold the bed: it takes
1612
+ * `(2 * depth)^2` of it, drag on the wetted height, which reaches the whole current exactly where
1613
+ * swimming starts, so stepping off the bed is not a jolt. A lake's current is zero.
1614
+ */
1615
+ #carry(depth) {
1616
+ const query = this.waterCurrent;
1617
+ const current = depth > 0 && query !== void 0 ? query(this.object.position.x, this.object.position.z) : void 0;
1618
+ if (current !== void 0 && (!Number.isFinite(current.x) || !Number.isFinite(current.z)))
1619
+ throw new Error(
1620
+ "CharacterBody3D.waterCurrent must return finite x and z in m/s, or undefined."
1621
+ );
1622
+ const share = Math.min(1, 2 * depth) ** 2;
1623
+ this.currentVelocity.x = current === void 0 ? 0 : current.x * share;
1624
+ this.currentVelocity.z = current === void 0 ? 0 : current.z * share;
1625
+ }
1626
+ /** UE 5.8.3 ImmersionDepth: the share of the collider below the surface, from top to bottom. */
1627
+ #immerse() {
1628
+ const { x, y, z } = this.object.position;
1629
+ const surface = this.water?.(x, z);
1630
+ if (surface !== void 0 && !Number.isFinite(surface))
1631
+ throw new Error("CharacterBody3D.water must return a finite surface height or undefined.");
1632
+ const half = this.#halfHeight;
1633
+ if (surface !== void 0 && half === void 0)
1634
+ throw new Error("CharacterBody3D.water needs a capsule, box or sphere shape to measure.");
1635
+ this.waterSurface = surface;
1636
+ this.immersionDepth = surface === void 0 || half === void 0 ? 0 : Math.min(1, Math.max(0, (surface - y + half) / (2 * half)));
1637
+ this.swimming = this.immersionDepth > 0.5;
1638
+ return this.immersionDepth;
1639
+ }
1558
1640
  #clearGroundState() {
1559
1641
  this.grounded = false;
1560
1642
  this.#groundCollider = void 0;
@@ -1700,6 +1782,22 @@ var CollisionShape3D = class _CollisionShape3D {
1700
1782
  scale
1701
1783
  });
1702
1784
  }
1785
+ /** Godot's ConcavePolygonShape3D: x, y, z vertex triples in body-local metres and triangle indices. */
1786
+ static trimesh(vertices, indices) {
1787
+ if (vertices.length < 9 || vertices.length % 3 !== 0 || indices.length < 3 || indices.length % 3 !== 0)
1788
+ throw new Error("CollisionShape3D.trimesh requires vertex triples and triangle indices.");
1789
+ return new _CollisionShape3D({
1790
+ collisionLayer: 1,
1791
+ collisionMask: 65535,
1792
+ kind: "trimesh",
1793
+ sensor: false,
1794
+ x: 0,
1795
+ y: 0,
1796
+ z: 0,
1797
+ vertices,
1798
+ indices
1799
+ });
1800
+ }
1703
1801
  static fromMesh(mesh, kind) {
1704
1802
  const geometry = mesh.geometry;
1705
1803
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
@@ -2326,6 +2424,233 @@ function buildStaticColliders(context, root, filter) {
2326
2424
  throw new Error("buildStaticColliders produced zero colliders; check the scene and predicate.");
2327
2425
  return bodies;
2328
2426
  }
2427
+ var MIN_HEIGHT = 0.25;
2428
+ var MIN_TRUNK_RADIUS = 0.05;
2429
+ var TRUNK_BAND = 0.1;
2430
+ var SLENDER = 0.15;
2431
+ var NONE = 0;
2432
+ var HULL = 1;
2433
+ var TRUNK = 2;
2434
+ var KDOP18 = [
2435
+ [1, 0, 0],
2436
+ [0, 1, 0],
2437
+ [0, 0, 1],
2438
+ [0, 1, 1],
2439
+ [0, 1, -1],
2440
+ [1, 0, 1],
2441
+ [1, 0, -1],
2442
+ [1, 1, 0],
2443
+ [1, -1, 0]
2444
+ ].flatMap(([x = 0, y = 0, z = 0]) => {
2445
+ const direction = new Vector3(x, y, z).normalize();
2446
+ return [direction, direction.clone().negate()];
2447
+ });
2448
+ function kdopCorners(extent, eps) {
2449
+ const corners = [];
2450
+ const [bc, ca, ab] = [new Vector3(), new Vector3(), new Vector3()];
2451
+ KDOP18.forEach((a, i) => {
2452
+ KDOP18.forEach((b, j) => {
2453
+ KDOP18.forEach((c, k) => {
2454
+ if (j <= i || k <= j) return;
2455
+ const det = a.dot(bc.crossVectors(b, c));
2456
+ if (Math.abs(det) < 1e-6) return;
2457
+ ca.crossVectors(c, a);
2458
+ ab.crossVectors(a, b);
2459
+ const corner = bc.clone().multiplyScalar(extent[i]).addScaledVector(ca, extent[j]).addScaledVector(ab, extent[k]).divideScalar(det);
2460
+ const outside = KDOP18.some((d, plane) => d.dot(corner) > extent[plane] + eps);
2461
+ if (!outside && !corners.some((seen) => seen.distanceTo(corner) < eps))
2462
+ corners.push(corner);
2463
+ });
2464
+ });
2465
+ });
2466
+ return corners;
2467
+ }
2468
+ function kdopSurface(points, size) {
2469
+ const extent = KDOP18.map(
2470
+ (direction) => points.reduce((max, point) => Math.max(max, direction.dot(point)), Number.NEGATIVE_INFINITY)
2471
+ );
2472
+ const eps = 1e-3 * size;
2473
+ const corners = kdopCorners(extent, eps);
2474
+ const indices = [];
2475
+ const [centre, u, v, offset] = [new Vector3(), new Vector3(), new Vector3(), new Vector3()];
2476
+ KDOP18.forEach((normal, plane) => {
2477
+ const face = corners.flatMap(
2478
+ (corner, index) => Math.abs(normal.dot(corner) - extent[plane]) <= eps ? [index] : []
2479
+ );
2480
+ if (face.length < 3) return;
2481
+ centre.set(0, 0, 0);
2482
+ for (const index of face) centre.add(corners[index]);
2483
+ centre.divideScalar(face.length);
2484
+ u.crossVectors(normal, Math.abs(normal.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0));
2485
+ v.crossVectors(normal, u);
2486
+ const angle = (index) => {
2487
+ offset.subVectors(corners[index], centre);
2488
+ return Math.atan2(offset.dot(v), offset.dot(u));
2489
+ };
2490
+ face.sort((left, right) => angle(left) - angle(right));
2491
+ for (let index = 1; index + 1 < face.length; index++)
2492
+ indices.push(face[0], face[index], face[index + 1]);
2493
+ });
2494
+ return { corners, indices: new Uint32Array(indices) };
2495
+ }
2496
+ var profiles = /* @__PURE__ */ new WeakMap();
2497
+ function profileOf(geometry) {
2498
+ const cached2 = profiles.get(geometry);
2499
+ if (cached2 !== void 0) return cached2;
2500
+ const position = geometry.getAttribute("position");
2501
+ if (position === void 0 || position.count < 4)
2502
+ throw new Error("ScatterColliders requires geometry with at least four vertex positions.");
2503
+ const points = Array.from(
2504
+ { length: position.count },
2505
+ (_, index) => new Vector3().fromBufferAttribute(position, index)
2506
+ );
2507
+ let [minY, maxY, reach, size] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 0, 1e-6];
2508
+ for (const point of points) {
2509
+ minY = Math.min(minY, point.y);
2510
+ maxY = Math.max(maxY, point.y);
2511
+ reach = Math.max(reach, Math.hypot(point.x, point.z));
2512
+ size = Math.max(size, Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
2513
+ }
2514
+ const height = maxY - minY;
2515
+ const band = points.filter((point) => point.y <= minY + TRUNK_BAND * height);
2516
+ const median = (axis) => band.map((point) => point[axis]).sort((a, b) => a - b)[band.length >> 1] ?? 0;
2517
+ const base = new Vector3(median("x"), minY, median("z"));
2518
+ const spread = band.map((point) => Math.hypot(point.x - base.x, point.z - base.z)).sort((a, b) => a - b);
2519
+ const radius = spread[Math.floor(spread.length * 0.9)] ?? 0;
2520
+ const profile = {
2521
+ minY,
2522
+ height,
2523
+ reach,
2524
+ base,
2525
+ radius,
2526
+ slender: radius <= SLENDER * height,
2527
+ hull: kdopSurface(points, size)
2528
+ };
2529
+ profiles.set(geometry, profile);
2530
+ return profile;
2531
+ }
2532
+ var column = new Vector3();
2533
+ function scales(matrix) {
2534
+ const x = column.setFromMatrixColumn(matrix, 0).length();
2535
+ const z = column.setFromMatrixColumn(matrix, 2).length();
2536
+ return { up: column.setFromMatrixColumn(matrix, 1).length(), across: Math.max(x, z) };
2537
+ }
2538
+ function classify(instance) {
2539
+ const collision = instance.collision ?? "auto";
2540
+ if (collision === "none") return NONE;
2541
+ if (collision === "hull") return HULL;
2542
+ if (collision === "trunk") return TRUNK;
2543
+ if (collision !== "auto")
2544
+ throw new Error(`ScatterColliders collision '${String(collision)}' is unknown.`);
2545
+ const profile = profileOf(instance.geometry);
2546
+ const { up, across } = scales(instance.matrix);
2547
+ if (profile.height * up < MIN_HEIGHT) return NONE;
2548
+ if (!profile.slender) return HULL;
2549
+ return profile.radius * across < MIN_TRUNK_RADIUS ? NONE : TRUNK;
2550
+ }
2551
+ var ScatterColliders = class {
2552
+ #physics;
2553
+ #follow;
2554
+ #radius;
2555
+ #layer;
2556
+ #mask;
2557
+ #instances = [];
2558
+ #resident = /* @__PURE__ */ new Map();
2559
+ #counts = { hulls: 0, trunks: 0, skipped: 0 };
2560
+ #lastX = Number.NaN;
2561
+ #lastZ = Number.NaN;
2562
+ #disposed = false;
2563
+ constructor(options) {
2564
+ if (options?.physics === void 0)
2565
+ throw new Error("ScatterColliders requires a physics context.");
2566
+ const radius = options.radius ?? 40;
2567
+ if (!Number.isFinite(radius) || radius <= 0)
2568
+ throw new Error(
2569
+ `ScatterColliders radius must be a positive finite number, received ${String(radius)}.`
2570
+ );
2571
+ this.#physics = options.physics;
2572
+ this.#follow = options.follow;
2573
+ this.#radius = radius;
2574
+ this.#layer = options.collisionLayer;
2575
+ this.#mask = options.collisionMask;
2576
+ for (const instance of options.instances) {
2577
+ const kind = classify(instance);
2578
+ if (kind === NONE) {
2579
+ this.#counts.skipped++;
2580
+ continue;
2581
+ }
2582
+ const x = instance.matrix.elements[12];
2583
+ const z = instance.matrix.elements[14];
2584
+ if (!Number.isFinite(x) || !Number.isFinite(z))
2585
+ throw new Error(
2586
+ `ScatterColliders instance ${this.#instances.length} has a non-finite position.`
2587
+ );
2588
+ const reach = profileOf(instance.geometry).reach * scales(instance.matrix).across;
2589
+ this.#instances.push({ instance, kind, x, z, reach });
2590
+ if (kind === HULL) this.#counts.hulls++;
2591
+ else this.#counts.trunks++;
2592
+ }
2593
+ console.info(`TN_SCATTER_COLLIDERS:${JSON.stringify({ ...this.#counts, radius })}`);
2594
+ }
2595
+ /** Create the bodies the follow point nears and release the ones it left. Cheap to call per frame. */
2596
+ update() {
2597
+ if (this.#disposed) return;
2598
+ const { x, z } = this.#follow.position;
2599
+ if (Math.hypot(x - this.#lastX, z - this.#lastZ) < this.#radius / 4) return;
2600
+ this.#lastX = x;
2601
+ this.#lastZ = z;
2602
+ this.#instances.forEach((entry, index) => {
2603
+ const gap = Math.hypot(entry.x - x, entry.z - z) - entry.reach;
2604
+ const body = this.#resident.get(index);
2605
+ if (gap <= this.#radius) {
2606
+ if (body === void 0) this.#resident.set(index, this.#create(entry.instance, entry.kind));
2607
+ } else if (body !== void 0 && gap > this.#radius * 1.25) {
2608
+ body.dispose();
2609
+ this.#resident.delete(index);
2610
+ }
2611
+ });
2612
+ }
2613
+ #create(instance, kind) {
2614
+ const profile = profileOf(instance.geometry);
2615
+ const origin = new Vector3().setFromMatrixPosition(instance.matrix);
2616
+ const linear = new Matrix3().setFromMatrix4(instance.matrix);
2617
+ const common = {
2618
+ physics: this.#physics,
2619
+ type: "fixed",
2620
+ collisionLayer: this.#layer,
2621
+ collisionMask: this.#mask
2622
+ };
2623
+ if (kind === TRUNK) {
2624
+ const { up, across } = scales(instance.matrix);
2625
+ const height = profile.height * up;
2626
+ const radius = Math.max(MIN_TRUNK_RADIUS, profile.radius * across);
2627
+ const base = profile.base.clone().applyMatrix3(linear).add(origin);
2628
+ return new RigidBody3D({
2629
+ ...common,
2630
+ position: { x: base.x, y: base.y + height / 2, z: base.z },
2631
+ shape: CollisionShape3D.capsule(Math.max(0, height / 2 - radius), radius)
2632
+ });
2633
+ }
2634
+ const vertices = new Float32Array(profile.hull.corners.length * 3);
2635
+ profile.hull.corners.forEach((corner, index) => {
2636
+ corner.clone().applyMatrix3(linear).toArray(vertices, index * 3);
2637
+ });
2638
+ return new RigidBody3D({
2639
+ ...common,
2640
+ position: origin,
2641
+ shape: CollisionShape3D.trimesh(vertices, profile.hull.indices)
2642
+ });
2643
+ }
2644
+ stats() {
2645
+ return { instances: this.#instances.length, ...this.#counts, resident: this.#resident.size };
2646
+ }
2647
+ dispose() {
2648
+ if (this.#disposed) return;
2649
+ this.#disposed = true;
2650
+ for (const body of this.#resident.values()) body.dispose();
2651
+ this.#resident.clear();
2652
+ }
2653
+ };
2329
2654
  var ONE = new Vector3(1, 1, 1);
2330
2655
  var PhysicsSoftBodyCollision = class {
2331
2656
  capacity;
@@ -2397,11 +2722,11 @@ function softBodyCollision(...bodies) {
2397
2722
  }
2398
2723
  function unionBounds(current, next) {
2399
2724
  if (current === void 0) return next;
2400
- const column = Math.min(current.column, next.column);
2725
+ const column2 = Math.min(current.column, next.column);
2401
2726
  const row = Math.min(current.row, next.row);
2402
2727
  return {
2403
- column,
2404
- columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2728
+ column: column2,
2729
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column2,
2405
2730
  row,
2406
2731
  rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2407
2732
  };
@@ -2595,10 +2920,10 @@ function attachSnowPhysics(options) {
2595
2920
  function windowGap(window) {
2596
2921
  let gap = 0;
2597
2922
  const rows = field.rows;
2598
- for (let column = window.column; column < window.column + window.columns; column += 1) {
2923
+ for (let column2 = window.column; column2 < window.column + window.columns; column2 += 1) {
2599
2924
  for (let row = window.row; row < window.row + window.rows; row += 1) {
2600
- const installed = colliderHeights[column * rows + row];
2601
- gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2925
+ const installed = colliderHeights[column2 * rows + row];
2926
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column2) - installed));
2602
2927
  }
2603
2928
  }
2604
2929
  return gap;
@@ -2758,8 +3083,8 @@ function footprintArea(footprint) {
2758
3083
  let area = 0;
2759
3084
  for (let row = 0; row < steps; row += 1) {
2760
3085
  const z = -footprint.extent + (row + 0.5) * step;
2761
- for (let column = 0; column < steps; column += 1) {
2762
- const x = -footprint.extent + (column + 0.5) * step;
3086
+ for (let column2 = 0; column2 < steps; column2 += 1) {
3087
+ const x = -footprint.extent + (column2 + 0.5) * step;
2763
3088
  area += footprint.sample(x, z).coverage * step * step;
2764
3089
  }
2765
3090
  }
@@ -3304,4 +3629,4 @@ var VehicleBody3D = class extends RigidBody3D {
3304
3629
  }
3305
3630
  };
3306
3631
 
3307
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier2 as rapier, softBodyCollision };
3632
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier2 as rapier, softBodyCollision };
@@ -1,5 +1,5 @@
1
- export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-AgKEDg0q.js';
2
- export { IBuildStaticCollidersOptions, IFixedJoint3DOptions, IHingeJoint3DOptions, IJoint3DOptions, IPinJoint3DOptions, ISnowPhysicsBinding, ISnowPhysicsObservation, ISnowPhysicsOptions, IStaticColliderContext, IVehicleBody3DOptions, IVehicleWheel3D, Joint3D, PhysicsJointBody, StaticColliderPredicate, VehicleBody3D, VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision } from '../index.js';
1
+ export { A as Area3D, $ as AreaEvent, a0 as AreaHandler, B as Buoyancy3D, h as BuoyancyPointPosition, i as CharacterBody3D, C as CollisionShape3D, a1 as CollisionShapeKind, a2 as IArea3DOptions, a3 as IAreaContact, j as IBuoyancy3DOptions, k as IBuoyancyHullPoint, l as IBuoyancySurface, m as IBuoyancySurfaceSample, a4 as ICharacterBody3DOptions, o as IIntersectPointOptions, p as IIntersectRayOptions, q as IIntersectShapeOptions, r as IPhysicsBodyCreateOptions, b as IPhysicsBodyHandle, s as IPhysicsCharacterOptions, f as IPhysicsColliderHandle, I as IPhysicsContext, t as IPhysicsHandle, u as IPhysicsInputSnapshot, v as IPhysicsJointCreateOptions, e as IPhysicsJointLimit, a5 as IPhysicsOptions, w as IPhysicsPointQuery, x as IPhysicsQueryHit, y as IPhysicsRayHit, z as IPhysicsRayQuery, d as IPhysicsRotation, D as IPhysicsRuntimeSimulation, E as IPhysicsShapeDescriptor, F as IPhysicsShapeQuery, G as IPhysicsSimulation, c as IPhysicsVector3, H as IPhysicsVehicleCreateOptions, J as IPhysicsVehicleInput, K as IPhysicsVehicleState, a as IPhysicsWorldHandle, L as IPointHit, M as IRayHit, N as IRigidBody3DOptions, O as IShapeHit, Q as MAX_PHYSICS_QUERY_RESULTS, S as PHYSICS_COLLISION_EVENT_STRIDE, T as PHYSICS_TRANSFORM_STRIDE, U as PHYSICS_VEHICLE_WHEEL_STRIDE, P as PhysicsBody3D, V as PhysicsDirectSpaceState3D, W as PhysicsJointKind, a6 as PhysicsPlugin, X as PhysicsQueryVector3, Y as PhysicsShapeKind, R as RigidBody3D, Z as RigidBodyType, _ as rapier } from '../Area3D-D03tyOlF.js';
2
+ export { IBuildStaticCollidersOptions, IFixedJoint3DOptions, IHingeJoint3DOptions, IJoint3DOptions, IPinJoint3DOptions, IScatterColliderInstance, IScatterCollidersOptions, IScatterCollidersStats, ISnowPhysicsBinding, ISnowPhysicsObservation, ISnowPhysicsOptions, IStaticColliderContext, IVehicleBody3DOptions, IVehicleWheel3D, Joint3D, PhysicsJointBody, ScatterColliders, ScatterCollision, StaticColliderPredicate, VehicleBody3D, VehicleForwardAxis, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, softBodyCollision } from '../index.js';
3
3
  import 'three';
4
4
  import '@threenative/core';
5
5
  import 'recast-navigation';
@@ -1,4 +1,4 @@
1
- import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh } from 'three';
1
+ import { Matrix4, Vector3, Quaternion, Box3, Object3D, Mesh, InstancedMesh, Matrix3 } from 'three';
2
2
  import { snowDiscFootprint } from '@threenative/core/world';
3
3
 
4
4
  // src/handles.ts
@@ -1054,6 +1054,10 @@ var Area3D = class {
1054
1054
  this.#listeners.bodyExited.clear();
1055
1055
  }
1056
1056
  };
1057
+ function halfHeightOf(shape) {
1058
+ const { kind, x, y } = shape.descriptor;
1059
+ return kind === "capsule" ? x + y : kind === "box" ? y : kind === "sphere" ? x : void 0;
1060
+ }
1057
1061
  var CharacterBody3D = class {
1058
1062
  body;
1059
1063
  collider;
@@ -1071,6 +1075,26 @@ var CharacterBody3D = class {
1071
1075
  groundBody;
1072
1076
  /** Radians between `groundNormal` and world up (+Y). */
1073
1077
  slopeAngle = 0;
1078
+ /** See `ICharacterBody3DOptions.water`; assign it once the water exists. */
1079
+ water;
1080
+ /** See `ICharacterBody3DOptions.waterCurrent`; assign it once the water exists. */
1081
+ waterCurrent;
1082
+ /**
1083
+ * The water's own velocity the last `moveAndSlide` applied, in m/s: the full current while
1084
+ * swimming, a depth-weighted share of it while wading, `(0, 0)` out of water. Read it to tell a
1085
+ * drift from a step.
1086
+ */
1087
+ currentVelocity = { x: 0, z: 0 };
1088
+ buoyancy;
1089
+ maxSwimSpeed;
1090
+ fluidFriction;
1091
+ /** True while the body's centre is under the water surface (Unreal's MOVE_Swimming). */
1092
+ swimming = false;
1093
+ /** Unreal's `ImmersionDepth`: the share of the collider's height under water, 0 to 1. */
1094
+ immersionDepth = 0;
1095
+ /** The water surface height the last `moveAndSlide` read, or `undefined` out of water. */
1096
+ waterSurface;
1097
+ #halfHeight;
1074
1098
  #simulation;
1075
1099
  #physics;
1076
1100
  #desired = { x: 0, y: 0, z: 0 };
@@ -1100,6 +1124,16 @@ var CharacterBody3D = class {
1100
1124
  this.gravity = options.gravity ?? -9.81;
1101
1125
  this.maxFallSpeed = options.maxFallSpeed ?? 50;
1102
1126
  this.oneWayLayers = options.oneWayLayers ?? 0;
1127
+ this.water = options.water;
1128
+ this.waterCurrent = options.waterCurrent;
1129
+ this.buoyancy = options.buoyancy ?? 1.6;
1130
+ this.maxSwimSpeed = options.maxSwimSpeed ?? 3;
1131
+ this.fluidFriction = options.fluidFriction ?? 12;
1132
+ if (!(this.buoyancy >= 0 && this.maxSwimSpeed > 0 && this.fluidFriction >= 0))
1133
+ throw new Error(
1134
+ "CharacterBody3D needs buoyancy >= 0, maxSwimSpeed > 0 and fluidFriction >= 0."
1135
+ );
1136
+ this.#halfHeight = halfHeightOf(options.shape);
1103
1137
  const shape = options.shape.descriptor;
1104
1138
  if (options.collisionLayer !== void 0 || options.collisionMask !== void 0) {
1105
1139
  const layer = options.collisionLayer ?? shape.collisionLayer;
@@ -1163,10 +1197,27 @@ var CharacterBody3D = class {
1163
1197
  moveAndSlide(dt) {
1164
1198
  if (!Number.isFinite(dt) || dt < 0)
1165
1199
  throw new Error("CharacterBody3D.moveAndSlide requires a finite non-negative dt.");
1166
- this.velocity.y = Math.max(this.velocity.y + this.gravity * dt, -this.maxFallSpeed);
1167
- this.#desired.x = this.velocity.x * dt;
1200
+ const depth = this.#immerse();
1201
+ let fall = this.gravity;
1202
+ if (this.swimming) {
1203
+ const rise = 0.33 * this.maxSwimSpeed;
1204
+ if (this.velocity.y > rise) this.velocity.y = Math.max(rise, this.velocity.y * depth * depth);
1205
+ this.velocity.y *= 1 - Math.min(0.5 * this.fluidFriction * depth * dt, 1);
1206
+ fall *= 1 - this.buoyancy * depth;
1207
+ }
1208
+ this.velocity.y = Math.max(this.velocity.y + fall * dt, -this.maxFallSpeed);
1209
+ if (depth > 0) {
1210
+ const cap = this.maxSwimSpeed / Math.min(1, 2 * depth);
1211
+ const speed = Math.hypot(this.velocity.x, this.velocity.z);
1212
+ if (speed > cap) {
1213
+ this.velocity.x *= cap / speed;
1214
+ this.velocity.z *= cap / speed;
1215
+ }
1216
+ }
1217
+ this.#carry(depth);
1218
+ this.#desired.x = (this.velocity.x + this.currentVelocity.x) * dt;
1168
1219
  this.#desired.y = this.velocity.y * dt;
1169
- this.#desired.z = this.velocity.z * dt;
1220
+ this.#desired.z = (this.velocity.z + this.currentVelocity.z) * dt;
1170
1221
  this.#sliding = true;
1171
1222
  }
1172
1223
  /** Called by the shared plugin before a bulk step. */
@@ -1252,6 +1303,37 @@ var CharacterBody3D = class {
1252
1303
  this.#simulation.removeBody(this.body.id);
1253
1304
  this.#clearGroundState();
1254
1305
  }
1306
+ /**
1307
+ * UE 5.8.3 river forces settle a floating body at the water's own speed, so a swimmer (centre
1308
+ * under, `immersionDepth > 0.5`) takes the whole current. A wader's feet hold the bed: it takes
1309
+ * `(2 * depth)^2` of it, drag on the wetted height, which reaches the whole current exactly where
1310
+ * swimming starts, so stepping off the bed is not a jolt. A lake's current is zero.
1311
+ */
1312
+ #carry(depth) {
1313
+ const query = this.waterCurrent;
1314
+ const current = depth > 0 && query !== void 0 ? query(this.object.position.x, this.object.position.z) : void 0;
1315
+ if (current !== void 0 && (!Number.isFinite(current.x) || !Number.isFinite(current.z)))
1316
+ throw new Error(
1317
+ "CharacterBody3D.waterCurrent must return finite x and z in m/s, or undefined."
1318
+ );
1319
+ const share = Math.min(1, 2 * depth) ** 2;
1320
+ this.currentVelocity.x = current === void 0 ? 0 : current.x * share;
1321
+ this.currentVelocity.z = current === void 0 ? 0 : current.z * share;
1322
+ }
1323
+ /** UE 5.8.3 ImmersionDepth: the share of the collider below the surface, from top to bottom. */
1324
+ #immerse() {
1325
+ const { x, y, z } = this.object.position;
1326
+ const surface = this.water?.(x, z);
1327
+ if (surface !== void 0 && !Number.isFinite(surface))
1328
+ throw new Error("CharacterBody3D.water must return a finite surface height or undefined.");
1329
+ const half = this.#halfHeight;
1330
+ if (surface !== void 0 && half === void 0)
1331
+ throw new Error("CharacterBody3D.water needs a capsule, box or sphere shape to measure.");
1332
+ this.waterSurface = surface;
1333
+ this.immersionDepth = surface === void 0 || half === void 0 ? 0 : Math.min(1, Math.max(0, (surface - y + half) / (2 * half)));
1334
+ this.swimming = this.immersionDepth > 0.5;
1335
+ return this.immersionDepth;
1336
+ }
1255
1337
  #clearGroundState() {
1256
1338
  this.grounded = false;
1257
1339
  this.#groundCollider = void 0;
@@ -1397,6 +1479,22 @@ var CollisionShape3D = class _CollisionShape3D {
1397
1479
  scale
1398
1480
  });
1399
1481
  }
1482
+ /** Godot's ConcavePolygonShape3D: x, y, z vertex triples in body-local metres and triangle indices. */
1483
+ static trimesh(vertices, indices) {
1484
+ if (vertices.length < 9 || vertices.length % 3 !== 0 || indices.length < 3 || indices.length % 3 !== 0)
1485
+ throw new Error("CollisionShape3D.trimesh requires vertex triples and triangle indices.");
1486
+ return new _CollisionShape3D({
1487
+ collisionLayer: 1,
1488
+ collisionMask: 65535,
1489
+ kind: "trimesh",
1490
+ sensor: false,
1491
+ x: 0,
1492
+ y: 0,
1493
+ z: 0,
1494
+ vertices,
1495
+ indices
1496
+ });
1497
+ }
1400
1498
  static fromMesh(mesh, kind) {
1401
1499
  const geometry = mesh.geometry;
1402
1500
  const inferred = kind ?? (geometry.type.toLowerCase().includes("sphere") ? "sphere" : geometry.type.toLowerCase().includes("capsule") ? "capsule" : "box");
@@ -2023,6 +2121,233 @@ function buildStaticColliders(context, root, filter) {
2023
2121
  throw new Error("buildStaticColliders produced zero colliders; check the scene and predicate.");
2024
2122
  return bodies;
2025
2123
  }
2124
+ var MIN_HEIGHT = 0.25;
2125
+ var MIN_TRUNK_RADIUS = 0.05;
2126
+ var TRUNK_BAND = 0.1;
2127
+ var SLENDER = 0.15;
2128
+ var NONE = 0;
2129
+ var HULL = 1;
2130
+ var TRUNK = 2;
2131
+ var KDOP18 = [
2132
+ [1, 0, 0],
2133
+ [0, 1, 0],
2134
+ [0, 0, 1],
2135
+ [0, 1, 1],
2136
+ [0, 1, -1],
2137
+ [1, 0, 1],
2138
+ [1, 0, -1],
2139
+ [1, 1, 0],
2140
+ [1, -1, 0]
2141
+ ].flatMap(([x = 0, y = 0, z = 0]) => {
2142
+ const direction = new Vector3(x, y, z).normalize();
2143
+ return [direction, direction.clone().negate()];
2144
+ });
2145
+ function kdopCorners(extent, eps) {
2146
+ const corners = [];
2147
+ const [bc, ca, ab] = [new Vector3(), new Vector3(), new Vector3()];
2148
+ KDOP18.forEach((a, i) => {
2149
+ KDOP18.forEach((b, j) => {
2150
+ KDOP18.forEach((c, k) => {
2151
+ if (j <= i || k <= j) return;
2152
+ const det = a.dot(bc.crossVectors(b, c));
2153
+ if (Math.abs(det) < 1e-6) return;
2154
+ ca.crossVectors(c, a);
2155
+ ab.crossVectors(a, b);
2156
+ const corner = bc.clone().multiplyScalar(extent[i]).addScaledVector(ca, extent[j]).addScaledVector(ab, extent[k]).divideScalar(det);
2157
+ const outside = KDOP18.some((d, plane) => d.dot(corner) > extent[plane] + eps);
2158
+ if (!outside && !corners.some((seen) => seen.distanceTo(corner) < eps))
2159
+ corners.push(corner);
2160
+ });
2161
+ });
2162
+ });
2163
+ return corners;
2164
+ }
2165
+ function kdopSurface(points, size) {
2166
+ const extent = KDOP18.map(
2167
+ (direction) => points.reduce((max, point) => Math.max(max, direction.dot(point)), Number.NEGATIVE_INFINITY)
2168
+ );
2169
+ const eps = 1e-3 * size;
2170
+ const corners = kdopCorners(extent, eps);
2171
+ const indices = [];
2172
+ const [centre, u, v, offset] = [new Vector3(), new Vector3(), new Vector3(), new Vector3()];
2173
+ KDOP18.forEach((normal, plane) => {
2174
+ const face = corners.flatMap(
2175
+ (corner, index) => Math.abs(normal.dot(corner) - extent[plane]) <= eps ? [index] : []
2176
+ );
2177
+ if (face.length < 3) return;
2178
+ centre.set(0, 0, 0);
2179
+ for (const index of face) centre.add(corners[index]);
2180
+ centre.divideScalar(face.length);
2181
+ u.crossVectors(normal, Math.abs(normal.x) < 0.9 ? new Vector3(1, 0, 0) : new Vector3(0, 1, 0));
2182
+ v.crossVectors(normal, u);
2183
+ const angle = (index) => {
2184
+ offset.subVectors(corners[index], centre);
2185
+ return Math.atan2(offset.dot(v), offset.dot(u));
2186
+ };
2187
+ face.sort((left, right) => angle(left) - angle(right));
2188
+ for (let index = 1; index + 1 < face.length; index++)
2189
+ indices.push(face[0], face[index], face[index + 1]);
2190
+ });
2191
+ return { corners, indices: new Uint32Array(indices) };
2192
+ }
2193
+ var profiles = /* @__PURE__ */ new WeakMap();
2194
+ function profileOf(geometry) {
2195
+ const cached2 = profiles.get(geometry);
2196
+ if (cached2 !== void 0) return cached2;
2197
+ const position = geometry.getAttribute("position");
2198
+ if (position === void 0 || position.count < 4)
2199
+ throw new Error("ScatterColliders requires geometry with at least four vertex positions.");
2200
+ const points = Array.from(
2201
+ { length: position.count },
2202
+ (_, index) => new Vector3().fromBufferAttribute(position, index)
2203
+ );
2204
+ let [minY, maxY, reach, size] = [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, 0, 1e-6];
2205
+ for (const point of points) {
2206
+ minY = Math.min(minY, point.y);
2207
+ maxY = Math.max(maxY, point.y);
2208
+ reach = Math.max(reach, Math.hypot(point.x, point.z));
2209
+ size = Math.max(size, Math.abs(point.x), Math.abs(point.y), Math.abs(point.z));
2210
+ }
2211
+ const height = maxY - minY;
2212
+ const band = points.filter((point) => point.y <= minY + TRUNK_BAND * height);
2213
+ const median = (axis) => band.map((point) => point[axis]).sort((a, b) => a - b)[band.length >> 1] ?? 0;
2214
+ const base = new Vector3(median("x"), minY, median("z"));
2215
+ const spread = band.map((point) => Math.hypot(point.x - base.x, point.z - base.z)).sort((a, b) => a - b);
2216
+ const radius = spread[Math.floor(spread.length * 0.9)] ?? 0;
2217
+ const profile = {
2218
+ minY,
2219
+ height,
2220
+ reach,
2221
+ base,
2222
+ radius,
2223
+ slender: radius <= SLENDER * height,
2224
+ hull: kdopSurface(points, size)
2225
+ };
2226
+ profiles.set(geometry, profile);
2227
+ return profile;
2228
+ }
2229
+ var column = new Vector3();
2230
+ function scales(matrix) {
2231
+ const x = column.setFromMatrixColumn(matrix, 0).length();
2232
+ const z = column.setFromMatrixColumn(matrix, 2).length();
2233
+ return { up: column.setFromMatrixColumn(matrix, 1).length(), across: Math.max(x, z) };
2234
+ }
2235
+ function classify(instance) {
2236
+ const collision = instance.collision ?? "auto";
2237
+ if (collision === "none") return NONE;
2238
+ if (collision === "hull") return HULL;
2239
+ if (collision === "trunk") return TRUNK;
2240
+ if (collision !== "auto")
2241
+ throw new Error(`ScatterColliders collision '${String(collision)}' is unknown.`);
2242
+ const profile = profileOf(instance.geometry);
2243
+ const { up, across } = scales(instance.matrix);
2244
+ if (profile.height * up < MIN_HEIGHT) return NONE;
2245
+ if (!profile.slender) return HULL;
2246
+ return profile.radius * across < MIN_TRUNK_RADIUS ? NONE : TRUNK;
2247
+ }
2248
+ var ScatterColliders = class {
2249
+ #physics;
2250
+ #follow;
2251
+ #radius;
2252
+ #layer;
2253
+ #mask;
2254
+ #instances = [];
2255
+ #resident = /* @__PURE__ */ new Map();
2256
+ #counts = { hulls: 0, trunks: 0, skipped: 0 };
2257
+ #lastX = Number.NaN;
2258
+ #lastZ = Number.NaN;
2259
+ #disposed = false;
2260
+ constructor(options) {
2261
+ if (options?.physics === void 0)
2262
+ throw new Error("ScatterColliders requires a physics context.");
2263
+ const radius = options.radius ?? 40;
2264
+ if (!Number.isFinite(radius) || radius <= 0)
2265
+ throw new Error(
2266
+ `ScatterColliders radius must be a positive finite number, received ${String(radius)}.`
2267
+ );
2268
+ this.#physics = options.physics;
2269
+ this.#follow = options.follow;
2270
+ this.#radius = radius;
2271
+ this.#layer = options.collisionLayer;
2272
+ this.#mask = options.collisionMask;
2273
+ for (const instance of options.instances) {
2274
+ const kind = classify(instance);
2275
+ if (kind === NONE) {
2276
+ this.#counts.skipped++;
2277
+ continue;
2278
+ }
2279
+ const x = instance.matrix.elements[12];
2280
+ const z = instance.matrix.elements[14];
2281
+ if (!Number.isFinite(x) || !Number.isFinite(z))
2282
+ throw new Error(
2283
+ `ScatterColliders instance ${this.#instances.length} has a non-finite position.`
2284
+ );
2285
+ const reach = profileOf(instance.geometry).reach * scales(instance.matrix).across;
2286
+ this.#instances.push({ instance, kind, x, z, reach });
2287
+ if (kind === HULL) this.#counts.hulls++;
2288
+ else this.#counts.trunks++;
2289
+ }
2290
+ console.info(`TN_SCATTER_COLLIDERS:${JSON.stringify({ ...this.#counts, radius })}`);
2291
+ }
2292
+ /** Create the bodies the follow point nears and release the ones it left. Cheap to call per frame. */
2293
+ update() {
2294
+ if (this.#disposed) return;
2295
+ const { x, z } = this.#follow.position;
2296
+ if (Math.hypot(x - this.#lastX, z - this.#lastZ) < this.#radius / 4) return;
2297
+ this.#lastX = x;
2298
+ this.#lastZ = z;
2299
+ this.#instances.forEach((entry, index) => {
2300
+ const gap = Math.hypot(entry.x - x, entry.z - z) - entry.reach;
2301
+ const body = this.#resident.get(index);
2302
+ if (gap <= this.#radius) {
2303
+ if (body === void 0) this.#resident.set(index, this.#create(entry.instance, entry.kind));
2304
+ } else if (body !== void 0 && gap > this.#radius * 1.25) {
2305
+ body.dispose();
2306
+ this.#resident.delete(index);
2307
+ }
2308
+ });
2309
+ }
2310
+ #create(instance, kind) {
2311
+ const profile = profileOf(instance.geometry);
2312
+ const origin = new Vector3().setFromMatrixPosition(instance.matrix);
2313
+ const linear = new Matrix3().setFromMatrix4(instance.matrix);
2314
+ const common = {
2315
+ physics: this.#physics,
2316
+ type: "fixed",
2317
+ collisionLayer: this.#layer,
2318
+ collisionMask: this.#mask
2319
+ };
2320
+ if (kind === TRUNK) {
2321
+ const { up, across } = scales(instance.matrix);
2322
+ const height = profile.height * up;
2323
+ const radius = Math.max(MIN_TRUNK_RADIUS, profile.radius * across);
2324
+ const base = profile.base.clone().applyMatrix3(linear).add(origin);
2325
+ return new RigidBody3D({
2326
+ ...common,
2327
+ position: { x: base.x, y: base.y + height / 2, z: base.z },
2328
+ shape: CollisionShape3D.capsule(Math.max(0, height / 2 - radius), radius)
2329
+ });
2330
+ }
2331
+ const vertices = new Float32Array(profile.hull.corners.length * 3);
2332
+ profile.hull.corners.forEach((corner, index) => {
2333
+ corner.clone().applyMatrix3(linear).toArray(vertices, index * 3);
2334
+ });
2335
+ return new RigidBody3D({
2336
+ ...common,
2337
+ position: origin,
2338
+ shape: CollisionShape3D.trimesh(vertices, profile.hull.indices)
2339
+ });
2340
+ }
2341
+ stats() {
2342
+ return { instances: this.#instances.length, ...this.#counts, resident: this.#resident.size };
2343
+ }
2344
+ dispose() {
2345
+ if (this.#disposed) return;
2346
+ this.#disposed = true;
2347
+ for (const body of this.#resident.values()) body.dispose();
2348
+ this.#resident.clear();
2349
+ }
2350
+ };
2026
2351
  var ONE = new Vector3(1, 1, 1);
2027
2352
  var PhysicsSoftBodyCollision = class {
2028
2353
  capacity;
@@ -2094,11 +2419,11 @@ function softBodyCollision(...bodies) {
2094
2419
  }
2095
2420
  function unionBounds(current, next) {
2096
2421
  if (current === void 0) return next;
2097
- const column = Math.min(current.column, next.column);
2422
+ const column2 = Math.min(current.column, next.column);
2098
2423
  const row = Math.min(current.row, next.row);
2099
2424
  return {
2100
- column,
2101
- columns: Math.max(current.column + current.columns, next.column + next.columns) - column,
2425
+ column: column2,
2426
+ columns: Math.max(current.column + current.columns, next.column + next.columns) - column2,
2102
2427
  row,
2103
2428
  rows: Math.max(current.row + current.rows, next.row + next.rows) - row
2104
2429
  };
@@ -2292,10 +2617,10 @@ function attachSnowPhysics(options) {
2292
2617
  function windowGap(window) {
2293
2618
  let gap = 0;
2294
2619
  const rows = field.rows;
2295
- for (let column = window.column; column < window.column + window.columns; column += 1) {
2620
+ for (let column2 = window.column; column2 < window.column + window.columns; column2 += 1) {
2296
2621
  for (let row = window.row; row < window.row + window.rows; row += 1) {
2297
- const installed = colliderHeights[column * rows + row];
2298
- gap = Math.max(gap, Math.abs(field.colliderHeight(row, column) - installed));
2622
+ const installed = colliderHeights[column2 * rows + row];
2623
+ gap = Math.max(gap, Math.abs(field.colliderHeight(row, column2) - installed));
2299
2624
  }
2300
2625
  }
2301
2626
  return gap;
@@ -2455,8 +2780,8 @@ function footprintArea(footprint) {
2455
2780
  let area = 0;
2456
2781
  for (let row = 0; row < steps; row += 1) {
2457
2782
  const z = -footprint.extent + (row + 0.5) * step;
2458
- for (let column = 0; column < steps; column += 1) {
2459
- const x = -footprint.extent + (column + 0.5) * step;
2783
+ for (let column2 = 0; column2 < steps; column2 += 1) {
2784
+ const x = -footprint.extent + (column2 + 0.5) * step;
2460
2785
  area += footprint.sample(x, z).coverage * step * step;
2461
2786
  }
2462
2787
  }
@@ -3001,4 +3326,4 @@ function physicsEntityId(ctx, body) {
3001
3326
  return stableId;
3002
3327
  }
3003
3328
 
3004
- export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier, softBodyCollision };
3329
+ export { Area3D, Buoyancy3D, CharacterBody3D, CollisionShape3D, Joint3D, MAX_PHYSICS_QUERY_RESULTS, PHYSICS_COLLISION_EVENT_STRIDE, PHYSICS_TRANSFORM_STRIDE, PHYSICS_VEHICLE_WHEEL_STRIDE, PhysicsDirectSpaceState3D, RigidBody3D, ScatterColliders, VehicleBody3D, attachSnowPhysics, boxFootprint, buildStaticColliders, capsuleFootprint, interactionGroups, rapier, softBodyCollision };
@@ -1,4 +1,4 @@
1
1
  import '@threenative/core';
2
2
  import 'recast-navigation';
3
- export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-AgKEDg0q.js';
3
+ export { a7 as INavigationAgent3DOptions, a8 as INavigationContext, a9 as INavigationObstacle3DOptions, aa as INavigationRegion3DOptions, ab as NavigationAgent3D, ac as NavigationAgentEvent, ad as NavigationAgentHandler, ae as NavigationObstacle3D, af as NavigationPlugin, ag as NavigationRegion3D, ah as recast } from '../Area3D-D03tyOlF.js';
4
4
  import 'three';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threenative/physics",
3
- "version": "0.3.11",
3
+ "version": "0.3.12",
4
4
  "license": "MIT",
5
5
  "description": "Thin Rapier physics bindings for ThreeNative games.",
6
6
  "keywords": [
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "repository": {
20
20
  "type": "git",
21
- "url": "git+https://github.com/ThreeNativeHQ/threenative.git",
21
+ "url": "git+https://github.com/ThreeNativeHQ/threenative-engine.git",
22
22
  "directory": "packages/physics"
23
23
  },
24
24
  "type": "module",
@@ -55,7 +55,7 @@
55
55
  "recast-navigation": "0.43.1"
56
56
  },
57
57
  "peerDependencies": {
58
- "@threenative/core": ">=0.3.11 <0.4.0",
58
+ "@threenative/core": ">=0.3.12 <0.4.0",
59
59
  "three": ">=0.187.0 <0.188.0"
60
60
  },
61
61
  "devDependencies": {
@@ -65,7 +65,7 @@
65
65
  "tsup": "8.5.1",
66
66
  "typescript": "npm:@typescript/typescript6@6.0.2",
67
67
  "@typescript/native": "npm:typescript@7.0.2",
68
- "@threenative/core": "0.3.11"
68
+ "@threenative/core": "0.3.12"
69
69
  },
70
70
  "scripts": {
71
71
  "build": "tsup --config tsup.config.ts && publint",