@ignifx/physics 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,4493 @@
1
+ import { Component, IgnifxError, MeshAsset, Phase, Quat, Signal, Vec3, array, asset, bool, createDefaults, createServiceKey, defineExtension, defineSchema, describeSchema, enumOf, f32, lerp, map, optional, record, str, u32, vec3 } from "@ignifx/core";
2
+ import { addPhysicsShapeChild, applyPhysicsBodyForce, applyPhysicsBodyImpulse, createHavokWorld, createHeightFieldShape, createNullEngine, createPhysicsBody, createPhysicsCharacterController, createPhysicsShape, createPhysicsViewer, createSceneContext, disposePhysics, disposePhysicsViewer, disposeScene, getPhysicsBodyAngularVelocity, getPhysicsBodyLinearVelocity, lockPhysicsBodyRotationAxes, onPhysicsAfterStep, onPhysicsCollision, onPhysicsTriggerBodies, physicsRaycast, releasePhysicsShape, removePhysicsBody, setPhysicsBodyAngularVelocity, setPhysicsBodyCollisionEventsEnabled, setPhysicsBodyLinearVelocity, setPhysicsBodyMass, setPhysicsBodyPrestepType, setPhysicsBodyShape, setPhysicsBodyTransform, setPhysicsGravity, setPhysicsShapeFilterCollideMask, setPhysicsShapeFilterMembershipMask, setPhysicsShapeIsTrigger, setPhysicsShapeMaterial, setPhysicsTimestep, setPhysicsVelocityLimits, shapeCast, shapeProximity, showPhysicsBody, stepScene, unlockPhysicsBodyRotationAxes } from "@babylonjs/lite";
3
+ import HavokPhysics from "@babylonjs/havok";
4
+ //#region src/runtime/runtime-key.ts
5
+ /**
6
+ * The key the extension registers its runtime holder under, so that `Rigidbody`, the colliders, and
7
+ * `CharacterController` can reach the runtime from `this.app.services` without a module-level
8
+ * singleton (`CONSTITUTION.md` §3.6: no globals, two apps in one process).
9
+ *
10
+ * The **holder** is registered rather than the runtime itself, because everything an extension
11
+ * contributes is declared in `register` (`docs/architecture/04-extensions.md` §1) and the runtime
12
+ * does not exist until `onStart`.
13
+ *
14
+ * @internal
15
+ */
16
+ const PhysicsHostKey = createServiceKey("@ignifx/physics:host");
17
+ //#endregion
18
+ //#region src/components/rigidbody.ts
19
+ /**
20
+ * The `Rigidbody` component (`docs/architecture/09-physics.md` §2.1): what makes an entity's
21
+ * colliders a simulated, kinematic, or explicitly static Havok body.
22
+ *
23
+ * ## Corrections to §2.1, all forced by `@babylonjs/lite@1.27.0`
24
+ *
25
+ * - **`collisionEvents` is a three-valued enum, not a boolean.** §2.1 describes a field whose value
26
+ * is "auto"; a schema field has one kind and one value (ADR-0004), so the field is
27
+ * `"auto" | "on" | "off"` and `"auto"` is the default. `"auto"` is what §2.1 actually specifies:
28
+ * recomputed from `ctx.entityImplements` whenever a component is added to or removed from the
29
+ * entity.
30
+ * - **`velocityLimits` is not a per-body field.** Lite exposes `setPhysicsVelocityLimits(world, …)`
31
+ * only (`index.d.ts` 10880) — there is no per-body clamp — so the limits live in the `physics`
32
+ * settings section and the field is absent.
33
+ * - **A body's entity must be a root entity.** Lite's post-step sync writes `node.position` and
34
+ * `node.rotationQuaternion`, which are *local* values (`lib/physics/havok.js:_syncBodyToNode`), so
35
+ * a parented entity would be simulated in its parent's space. The extension reports `IGX-0907`
36
+ * and simulates it anyway rather than silently misplacing it.
37
+ *
38
+ * Not available in Lite 1.27.0 and therefore absent, as §2.1 already records: per-body damping,
39
+ * per-body gravity factor, sleep thresholds, and an explicit `wakeUp()`.
40
+ */
41
+ /**
42
+ * How a body moves.
43
+ *
44
+ * @public
45
+ */
46
+ const BODY_TYPES = [
47
+ "dynamic",
48
+ "kinematic",
49
+ "static"
50
+ ];
51
+ /**
52
+ * Whether a body's display pose is interpolated between fixed steps.
53
+ *
54
+ * @public
55
+ */
56
+ const INTERPOLATION_MODES = ["none", "interpolate"];
57
+ /**
58
+ * Whether collision callbacks are delivered for this body.
59
+ *
60
+ * @public
61
+ */
62
+ const COLLISION_EVENT_MODES = [
63
+ "auto",
64
+ "on",
65
+ "off"
66
+ ];
67
+ /**
68
+ * How a moved kinematic node reaches Havok.
69
+ *
70
+ * @public
71
+ */
72
+ const KINEMATIC_SYNC_MODES = ["teleport", "velocity"];
73
+ /**
74
+ * Makes an entity's colliders a Havok body (`09-physics.md` §2.1).
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * const crate = world.createEntity("Crate");
79
+ * crate.transform.position = { x: 0, y: 5, z: 0 };
80
+ * crate.addComponent(BoxCollider, { size: { x: 1, y: 1, z: 1 } });
81
+ * crate.addComponent(Rigidbody, { mass: 2 });
82
+ * ```
83
+ *
84
+ * @public
85
+ */
86
+ var Rigidbody = class Rigidbody extends Component {
87
+ /** The namespaced registration id. */
88
+ static typeId = "ignifx/Rigidbody";
89
+ /** One body per entity. */
90
+ static allowMultiple = false;
91
+ /** The serialized field declarations (ADR-0004). */
92
+ static schema = rigidbodySchema();
93
+ /** Applies the schema defaults, exactly as `Component.define` would. */
94
+ constructor() {
95
+ super();
96
+ Object.assign(this, createDefaults(Rigidbody.schema));
97
+ }
98
+ /** Marks the entity's body for a rebuild at the start of the next fixed step. */
99
+ onAttach() {
100
+ this.rebuild();
101
+ }
102
+ /** Marks the entity's body for a rebuild, which turns it back into an implicit static body. */
103
+ onDetach() {
104
+ this.rebuild();
105
+ }
106
+ /**
107
+ * Rebuilds the body at the start of the next fixed step. Call it after changing `bodyType`,
108
+ * `mass`, `freezeRotation`, or the entity's scale.
109
+ */
110
+ rebuild() {
111
+ this.#runtime()?.markDirty(this.entity);
112
+ }
113
+ /**
114
+ * The Babylon Lite handles this component owns.
115
+ *
116
+ * @returns The Havok body, or `null` before the first fixed step built it.
117
+ */
118
+ get lite() {
119
+ return { body: this.#runtime()?.bodyHandleOf(this.entity) ?? null };
120
+ }
121
+ /**
122
+ * The body's linear velocity in metres per second.
123
+ *
124
+ * @returns A freshly allocated vector; use {@link Rigidbody.linearVelocityToRef} in hot code.
125
+ */
126
+ get linearVelocity() {
127
+ const out = new Vec3();
128
+ this.linearVelocityToRef(out);
129
+ return out;
130
+ }
131
+ /**
132
+ * Replaces the body's linear velocity.
133
+ *
134
+ * @param value - Metres per second, world space.
135
+ */
136
+ set linearVelocity(value) {
137
+ this.#runtime()?.setLinearVelocity(this.entity, value);
138
+ }
139
+ /**
140
+ * Reads the linear velocity without allocating.
141
+ *
142
+ * @param out - The vector to write.
143
+ * @returns `out`.
144
+ */
145
+ linearVelocityToRef(out) {
146
+ this.#runtime()?.readLinear(this.entity, out);
147
+ return out;
148
+ }
149
+ /**
150
+ * The body's angular velocity in radians per second.
151
+ *
152
+ * @returns A freshly allocated vector; use {@link Rigidbody.angularVelocityToRef} in hot code.
153
+ */
154
+ get angularVelocity() {
155
+ const out = new Vec3();
156
+ this.angularVelocityToRef(out);
157
+ return out;
158
+ }
159
+ /**
160
+ * Replaces the body's angular velocity.
161
+ *
162
+ * @param value - Radians per second, world space.
163
+ */
164
+ set angularVelocity(value) {
165
+ this.#runtime()?.setAngularVelocity(this.entity, value);
166
+ }
167
+ /**
168
+ * Reads the angular velocity without allocating.
169
+ *
170
+ * @param out - The vector to write.
171
+ * @returns `out`.
172
+ */
173
+ angularVelocityToRef(out) {
174
+ this.#runtime()?.readAngular(this.entity, out);
175
+ return out;
176
+ }
177
+ /**
178
+ * Applies a force for one fixed step. Call it from `fixedUpdate`.
179
+ *
180
+ * @param force - Newtons, world space.
181
+ * @param point - Where to apply it; defaults to the entity's world position.
182
+ *
183
+ * @example
184
+ * ```ts
185
+ * fixedUpdate(): void {
186
+ * this.body.addForce({ x: 0, y: 20, z: 0 });
187
+ * }
188
+ * ```
189
+ */
190
+ addForce(force, point) {
191
+ this.#runtime()?.addForce(this.entity, force, point ?? this.transform.position);
192
+ }
193
+ /**
194
+ * Applies an instantaneous impulse.
195
+ *
196
+ * @param impulse - Newton-seconds, world space.
197
+ * @param point - Where to apply it; defaults to the entity's world position.
198
+ */
199
+ addImpulse(impulse, point) {
200
+ this.#runtime()?.addImpulse(this.entity, impulse, point ?? this.transform.position);
201
+ }
202
+ /**
203
+ * Moves the body without integrating a velocity, and resets the interpolation history so the
204
+ * display pose does not slide across the gap.
205
+ *
206
+ * @param position - The new world position.
207
+ * @param rotation - The new world rotation; defaults to the current one.
208
+ */
209
+ teleport(position, rotation) {
210
+ this.#runtime()?.teleport(this.entity, position, rotation ?? this.transform.rotation);
211
+ }
212
+ /**
213
+ * The runtime, or `null` when the extension is not registered on this app.
214
+ *
215
+ * @returns The runtime.
216
+ */
217
+ #runtime() {
218
+ return this.app.services.tryGet(PhysicsHostKey)?.runtime ?? null;
219
+ }
220
+ };
221
+ /**
222
+ * Builds the `Rigidbody` schema.
223
+ *
224
+ * @returns The schema.
225
+ */
226
+ function rigidbodySchema() {
227
+ return defineSchema({
228
+ bodyType: enumOf(BODY_TYPES, "dynamic"),
229
+ mass: f32(1, { min: 0 }),
230
+ startAsleep: bool(false),
231
+ freezeRotation: record({
232
+ x: bool(false),
233
+ y: bool(false),
234
+ z: bool(false)
235
+ }),
236
+ interpolation: enumOf(INTERPOLATION_MODES, "interpolate"),
237
+ collisionEvents: enumOf(COLLISION_EVENT_MODES, "auto"),
238
+ kinematicSync: enumOf(KINEMATIC_SYNC_MODES, "teleport")
239
+ });
240
+ }
241
+ //#endregion
242
+ //#region src/components/character-controller.ts
243
+ /**
244
+ * The `CharacterController` component (`docs/architecture/09-physics.md` §2.3): Lite's kinematic
245
+ * capsule with collide-and-slide, support detection, and dynamic-body pushing.
246
+ *
247
+ * ## How it is driven
248
+ *
249
+ * Call {@link CharacterController.move} from `fixedUpdate`. The requested displacements of one step
250
+ * are summed and handed to Lite's `moveWithCollisions` by the step system, so two scripts moving the
251
+ * same character compose instead of fighting. After the step the controller owns the entity's world
252
+ * **position**; rotation stays user-controlled.
253
+ *
254
+ * ## Corrections to §2.3
255
+ *
256
+ * - `supportState` is read from the last step's `checkSupport` probe, which the step system runs
257
+ * once per step; reading it does not probe again.
258
+ * - Gravity is **not** applied by this component. §2.3 already says so: a bare controller is purely
259
+ * kinematic and the 3D toolkit's controllers integrate gravity through `checkSupport` +
260
+ * `integrate` (Phase 7). {@link CharacterController.move} is the whole input.
261
+ * - `pushStrength` scales Lite's `characterStrength`, whose default is `1e38` — effectively
262
+ * "infinite". A `pushStrength` of `1` therefore means "Lite's default", not "one newton".
263
+ */
264
+ /**
265
+ * How the character is supported by whatever is under it.
266
+ *
267
+ * @public
268
+ */
269
+ const SUPPORT_STATES = [
270
+ "unsupported",
271
+ "sliding",
272
+ "supported"
273
+ ];
274
+ /**
275
+ * A kinematic capsule that walks, slides, and pushes (`09-physics.md` §2.3).
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * class Walk extends Script implements ScriptCallbacks {
280
+ * static typeId = "mygame/Walk";
281
+ * fixedUpdate(dt: number): void {
282
+ * const controller = this.entity.requireComponent(CharacterController);
283
+ * controller.move({ x: 2 * dt, y: 0, z: 0 });
284
+ * }
285
+ * }
286
+ * ```
287
+ *
288
+ * @public
289
+ */
290
+ var CharacterController = class CharacterController extends Component {
291
+ /** The namespaced registration id. */
292
+ static typeId = "ignifx/CharacterController";
293
+ /** One controller per entity. */
294
+ static allowMultiple = false;
295
+ /** The serialized field declarations (ADR-0004). */
296
+ static schema = characterSchema();
297
+ /** The displacement requested so far this fixed step. */
298
+ #pendingMove = new Vec3();
299
+ /** The averaged normal of the supporting surface, written by the step system. */
300
+ #groundNormal = new Vec3(0, 1, 0);
301
+ /** How the character was supported at the end of the last step. */
302
+ #supportState = "unsupported";
303
+ /** Emitted for every dynamic body the character pushed; created on first access. */
304
+ #onCollided = null;
305
+ /** Applies the schema defaults. */
306
+ constructor() {
307
+ super();
308
+ Object.assign(this, createDefaults(CharacterController.schema));
309
+ }
310
+ /** Creates the Lite controller at the start of the next fixed step. */
311
+ onAttach() {
312
+ this.rebuild();
313
+ }
314
+ /** Releases the Lite controller. */
315
+ onDetach() {
316
+ this.#runtime()?.releaseController(this);
317
+ }
318
+ /** Rebuilds the capsule at the start of the next fixed step. */
319
+ rebuild() {
320
+ this.#runtime()?.markControllerDirty(this);
321
+ }
322
+ /**
323
+ * Requests a displacement for this fixed step. Displacements accumulate until the step runs.
324
+ *
325
+ * @param displacement - The world-space displacement to attempt.
326
+ */
327
+ move(displacement) {
328
+ this.#pendingMove.set(this.#pendingMove.x + displacement.x, this.#pendingMove.y + displacement.y, this.#pendingMove.z + displacement.z);
329
+ }
330
+ /**
331
+ * Sets the controller's velocity, which is what `integrate` advances.
332
+ *
333
+ * @param velocity - Metres per second, world space.
334
+ */
335
+ setVelocity(velocity) {
336
+ this.#runtime()?.setControllerVelocity(this, velocity);
337
+ }
338
+ /**
339
+ * The controller's current velocity.
340
+ *
341
+ * @returns A freshly allocated vector.
342
+ */
343
+ get velocity() {
344
+ const out = new Vec3();
345
+ this.#runtime()?.readControllerVelocity(this, out);
346
+ return out;
347
+ }
348
+ /**
349
+ * Whether the character is standing on a walkable surface.
350
+ *
351
+ * @returns `true` when the last step's probe reported `supported`.
352
+ */
353
+ get isGrounded() {
354
+ return this.#supportState === "supported";
355
+ }
356
+ /**
357
+ * How the character was supported at the end of the last step.
358
+ *
359
+ * @returns `"unsupported"`, `"sliding"`, or `"supported"`.
360
+ */
361
+ get supportState() {
362
+ return this.#supportState;
363
+ }
364
+ /**
365
+ * The averaged normal of the supporting surface.
366
+ *
367
+ * @returns A live view; copy it if you keep it.
368
+ */
369
+ get groundNormal() {
370
+ return this.#groundNormal;
371
+ }
372
+ /**
373
+ * Emitted once per dynamic body the character pushed during a step.
374
+ *
375
+ * @returns The signal, created on first access.
376
+ */
377
+ get onCollided() {
378
+ this.#onCollided ??= new Signal();
379
+ return this.#onCollided;
380
+ }
381
+ /**
382
+ * Changes the capsule height without losing the controller's state — the crouch primitive.
383
+ *
384
+ * @param height - The new total height, tip to tip.
385
+ * @param preserveFeet - Whether the foot position stays fixed; defaults to `true`.
386
+ */
387
+ setHeight(height, preserveFeet = true) {
388
+ this.height = height;
389
+ this.#runtime()?.resizeController(this, preserveFeet);
390
+ }
391
+ /**
392
+ * Teleports the character, clearing any swept motion and the interpolation history.
393
+ *
394
+ * @param position - The new world position of the entity.
395
+ */
396
+ teleport(position) {
397
+ this.#runtime()?.teleportController(this, position);
398
+ }
399
+ /**
400
+ * The displacement requested so far this step, consumed by the step system.
401
+ *
402
+ * @returns A live view of the accumulator.
403
+ *
404
+ * @internal
405
+ */
406
+ takePendingMove() {
407
+ return this.#pendingMove;
408
+ }
409
+ /**
410
+ * Records the outcome of a step.
411
+ *
412
+ * @param state - The support classification.
413
+ * @param normal - The averaged supporting normal.
414
+ *
415
+ * @internal
416
+ */
417
+ applyStepResult(state, normal) {
418
+ this.#supportState = state;
419
+ this.#groundNormal.set(normal.x, normal.y, normal.z);
420
+ this.#pendingMove.set(0, 0, 0);
421
+ }
422
+ /**
423
+ * Emits `onCollided` if anything is listening.
424
+ *
425
+ * @param collision - The push to report.
426
+ *
427
+ * @internal
428
+ */
429
+ reportPush(collision) {
430
+ this.#onCollided?.emit(collision);
431
+ }
432
+ /**
433
+ * The runtime, or `null` when the extension is not registered on this app.
434
+ *
435
+ * @returns The runtime.
436
+ */
437
+ #runtime() {
438
+ return this.app.services.tryGet(PhysicsHostKey)?.runtime ?? null;
439
+ }
440
+ };
441
+ /**
442
+ * Builds the `CharacterController` schema.
443
+ *
444
+ * @returns The schema.
445
+ */
446
+ function characterSchema() {
447
+ return defineSchema({
448
+ radius: f32(.4, { min: 0 }),
449
+ height: f32(1.8, { min: 0 }),
450
+ center: vec3(),
451
+ slopeLimit: f32(45, {
452
+ min: 0,
453
+ max: 90
454
+ }),
455
+ skinWidth: f32(.05, { min: 0 }),
456
+ pushStrength: f32(1, { min: 0 }),
457
+ interpolation: enumOf(INTERPOLATION_MODES, "interpolate")
458
+ });
459
+ }
460
+ //#endregion
461
+ //#region src/errors.ts
462
+ /**
463
+ * The diagnostic codes `@ignifx/physics` owns. The package sits in the `09` subsystem range of
464
+ * `docs/architecture/15-devtools-and-diagnostics.md` §1, so every code reads `IGX-09##`.
465
+ *
466
+ * The table lives here rather than in `@ignifx/core`'s `CoreErrorCode`: an extension owns its own
467
+ * codes and hands them to the app through `ExtensionContext.registerErrorCodes`
468
+ * (`docs/architecture/04-extensions.md` §3).
469
+ */
470
+ /**
471
+ * Every diagnostic code `@ignifx/physics` can throw or report, keyed by an intention-revealing name
472
+ * so call sites read as prose and the compiler catches typos (coding standards §5.2).
473
+ *
474
+ * @example
475
+ * ```ts
476
+ * throw physicsError(PhysicsErrorCode.queryBeforeStep, "raycast() ran before the first step.", {
477
+ * context: { query: "raycast" },
478
+ * });
479
+ * ```
480
+ *
481
+ * @public
482
+ */
483
+ const PhysicsErrorCode = {
484
+ /** An entity with colliders but no `Rigidbody` moved after its implicit static body was placed. */
485
+ movedStaticBody: "IGX-0901",
486
+ /** A query ran before the first completed fixed step, so Havok has no broadphase yet. */
487
+ queryBeforeStep: "IGX-0902",
488
+ /** The Havok WebAssembly module could not be loaded. */
489
+ havokUnavailable: "IGX-0903",
490
+ /** A `.physicsmaterial.json` file is not an `ignifx.physicsmaterial` document this build reads. */
491
+ invalidMaterialFile: "IGX-0904",
492
+ /** The `physics.collisionMatrix` setting names a layer the project does not declare. */
493
+ unknownLayer: "IGX-0905",
494
+ /** A `MeshCollider` has no geometry to build a shape from. */
495
+ colliderGeometryUnavailable: "IGX-0906",
496
+ /** A physics body was built for an entity that has a parent, whose node pose is not world space. */
497
+ bodyOnChildEntity: "IGX-0907",
498
+ /** The ADR-0013 collision drain refused to bind because Babylon Lite's internals moved. */
499
+ internalDrainUnavailable: "IGX-0908"
500
+ };
501
+ /**
502
+ * The one-line message template of every code, as `ExtensionContext.registerErrorCodes` wants it.
503
+ * Context keys appear in braces, matching the core table's convention.
504
+ *
505
+ * @public
506
+ */
507
+ const PHYSICS_ERROR_MESSAGES = Object.freeze({
508
+ "IGX-0901": "{entity} has colliders but no Rigidbody, and it moved after its static body was placed.",
509
+ "IGX-0902": "{query} needs at least one completed fixed step before Havok can answer it.",
510
+ "IGX-0903": "The Havok WebAssembly module could not be loaded from {url}.",
511
+ "IGX-0904": "{file} is not an ignifx.physicsmaterial document this build can read.",
512
+ "IGX-0905": "physics.collisionMatrix names the layer {layer}, which the project does not declare.",
513
+ "IGX-0906": "{entity} has a MeshCollider with no geometry to build a shape from.",
514
+ "IGX-0907": "{entity} carries a physics body but is not a root entity; Havok writes its local pose.",
515
+ "IGX-0908": "The adapter-internal collision drain does not recognise Babylon Lite {version}."
516
+ });
517
+ /**
518
+ * Builds an `IgnifxError` carrying one of this package's codes.
519
+ *
520
+ * @param code - The code from the `PhysicsErrorCode` table.
521
+ * @param message - The actionable development sentence.
522
+ * @param options - Context identifiers, a remedy hint, and the wrapped cause.
523
+ * @returns The error to throw or to reject with.
524
+ *
525
+ * @example
526
+ * ```ts
527
+ * throw physicsError(PhysicsErrorCode.unknownLayer, "physics.collisionMatrix names Enemy.", {
528
+ * context: { layer: "Enemy" },
529
+ * });
530
+ * ```
531
+ *
532
+ * @public
533
+ */
534
+ function physicsError(code, message, options) {
535
+ return new IgnifxError(code, message, {
536
+ ...options?.context === void 0 ? {} : { context: options.context },
537
+ ...options?.hint === void 0 ? {} : { hint: options.hint },
538
+ ...options?.cause === void 0 ? {} : { cause: options.cause }
539
+ });
540
+ }
541
+ //#endregion
542
+ //#region src/material.ts
543
+ /**
544
+ * The `ignifx.physicsmaterial` asset (`docs/architecture/09-physics.md` §2.4,
545
+ * `05-assets-and-loading.md` §5): a surface's friction and bounciness, saved next to the scene that
546
+ * uses it so an artist can retune a floor without touching code.
547
+ */
548
+ /**
549
+ * The asset type name `.physicsmaterial.json` addresses resolve to.
550
+ *
551
+ * @public
552
+ */
553
+ const PHYSICS_MATERIAL_ASSET_TYPE = "physicsmaterial";
554
+ /**
555
+ * The address suffix that selects the loader.
556
+ *
557
+ * @public
558
+ */
559
+ const PHYSICS_MATERIAL_FILE_EXTENSION = ".physicsmaterial.json";
560
+ /**
561
+ * The `format` string every physics-material document declares.
562
+ *
563
+ * @public
564
+ */
565
+ const PHYSICS_MATERIAL_FILE_FORMAT = "ignifx.physicsmaterial";
566
+ /**
567
+ * The file format version; `1` before ignifx 1.0.
568
+ *
569
+ * @public
570
+ */
571
+ const PHYSICS_MATERIAL_FORMAT_VERSION = 1;
572
+ /**
573
+ * A loaded surface material. The values are the ones Havok's `setPhysicsShapeMaterial` takes
574
+ * (`index.d.ts` 10853).
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * const ice = await app.assets.load<PhysicsMaterial>("materials/ice.physicsmaterial.json");
579
+ * floor.addComponent(BoxCollider, { size: { x: 10, y: 1, z: 10 }, material: ice });
580
+ * ```
581
+ *
582
+ * @public
583
+ */
584
+ var PhysicsMaterial = class PhysicsMaterial {
585
+ /** The asset type token, so `asset(PhysicsMaterial)` fields resolve. */
586
+ static assetType = PHYSICS_MATERIAL_ASSET_TYPE;
587
+ /** A human-readable name, used in diagnostics. */
588
+ name;
589
+ /** The dynamic friction coefficient. */
590
+ friction;
591
+ /** The static friction coefficient. */
592
+ staticFriction;
593
+ /** How much of the approach speed is returned, `0` to `1`. */
594
+ restitution;
595
+ /**
596
+ * Wraps parsed values. The loader constructs these; game code uses
597
+ * {@link PhysicsMaterial.fromValues} when it wants one in code.
598
+ *
599
+ * @param name - A human-readable name.
600
+ * @param values - Friction, static friction, and restitution.
601
+ */
602
+ constructor(name, values) {
603
+ this.name = name;
604
+ this.friction = values.friction;
605
+ this.staticFriction = values.staticFriction;
606
+ this.restitution = values.restitution;
607
+ }
608
+ /**
609
+ * Builds a material in code, filling in the fields the caller omitted.
610
+ *
611
+ * @param name - A human-readable name.
612
+ * @param values - Any subset of the three coefficients.
613
+ * @returns The material.
614
+ *
615
+ * @example
616
+ * ```ts
617
+ * const bouncy = PhysicsMaterial.fromValues("bouncy", { restitution: 0.9 });
618
+ * ```
619
+ */
620
+ static fromValues(name, values) {
621
+ const friction = values.friction ?? .6;
622
+ return new PhysicsMaterial(name, {
623
+ friction,
624
+ staticFriction: values.staticFriction ?? friction,
625
+ restitution: values.restitution ?? 0
626
+ });
627
+ }
628
+ };
629
+ /**
630
+ * Builds the loader for `.physicsmaterial.json` files.
631
+ *
632
+ * @returns The loader, ready for `ctx.registerAssetLoader`.
633
+ *
634
+ * @public
635
+ */
636
+ function createPhysicsMaterialLoader() {
637
+ return {
638
+ type: PHYSICS_MATERIAL_ASSET_TYPE,
639
+ extensions: [PHYSICS_MATERIAL_FILE_EXTENSION],
640
+ load: async (ctx) => {
641
+ const document = await ctx.fetchJson();
642
+ return parsePhysicsMaterial(ctx.address, document);
643
+ }
644
+ };
645
+ }
646
+ /**
647
+ * Parses one `ignifx.physicsmaterial` document.
648
+ *
649
+ * @param address - The address it came from, for the diagnostic.
650
+ * @param document - The parsed JSON.
651
+ * @returns The material.
652
+ * @throws IgnifxError with code `IGX-0904` when the document is not one this build can read.
653
+ *
654
+ * @public
655
+ */
656
+ function parsePhysicsMaterial(address, document) {
657
+ const object = asObject(document);
658
+ if (object === null || object["format"] !== "ignifx.physicsmaterial") throw physicsError(PhysicsErrorCode.invalidMaterialFile, `${address} is not an ${PHYSICS_MATERIAL_FILE_FORMAT}.`, {
659
+ context: { file: address },
660
+ hint: `Add "format": "${PHYSICS_MATERIAL_FILE_FORMAT}" to the document.`
661
+ });
662
+ const version = numberAt(object, "formatVersion", 1);
663
+ if (version > 1) throw physicsError(PhysicsErrorCode.invalidMaterialFile, `${address} is version ${String(version)}.`, {
664
+ context: {
665
+ file: address,
666
+ version
667
+ },
668
+ hint: "Upgrade @ignifx/physics, or re-save the material from this version of the editor."
669
+ });
670
+ const friction = numberAt(object, "friction", .6);
671
+ return new PhysicsMaterial(typeof object["name"] === "string" ? object["name"] : address, {
672
+ friction,
673
+ staticFriction: numberAt(object, "staticFriction", friction),
674
+ restitution: numberAt(object, "restitution", 0)
675
+ });
676
+ }
677
+ /**
678
+ * Describes the `ignifx.physicsmaterial` file format for the documentation harness
679
+ * (`docs/architecture/16-docs-harness-and-skill.md` §3).
680
+ *
681
+ * @returns The description of the top-level file fields.
682
+ *
683
+ * @public
684
+ */
685
+ function describePhysicsMaterialFileFormat() {
686
+ return {
687
+ title: "Physics material file",
688
+ format: PHYSICS_MATERIAL_FILE_FORMAT,
689
+ description: "A surface's friction and bounciness, referenced by a collider's material field.",
690
+ fields: {
691
+ format: {
692
+ kind: "str",
693
+ default: PHYSICS_MATERIAL_FILE_FORMAT,
694
+ description: `Always "${PHYSICS_MATERIAL_FILE_FORMAT}".`
695
+ },
696
+ formatVersion: {
697
+ kind: "u32",
698
+ default: 1,
699
+ description: "The file format version; 1 before ignifx 1.0."
700
+ },
701
+ name: {
702
+ kind: "str",
703
+ default: "",
704
+ description: "A human-readable name; defaults to the address."
705
+ },
706
+ friction: {
707
+ kind: "f32",
708
+ default: .6,
709
+ description: "The dynamic friction coefficient."
710
+ },
711
+ staticFriction: {
712
+ kind: "f32",
713
+ default: .6,
714
+ description: "The static friction coefficient; defaults to friction."
715
+ },
716
+ restitution: {
717
+ kind: "f32",
718
+ default: 0,
719
+ description: "How much approach speed is returned, 0 to 1."
720
+ }
721
+ }
722
+ };
723
+ }
724
+ /**
725
+ * Views a JSON value as an object.
726
+ *
727
+ * @param value - The parsed JSON.
728
+ * @returns The object, or `null` when the value is not one.
729
+ */
730
+ function asObject(value) {
731
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
732
+ return value;
733
+ }
734
+ /**
735
+ * Reads a numeric property, tolerating its absence.
736
+ *
737
+ * @param object - The document.
738
+ * @param key - The property name.
739
+ * @param fallback - What to use when the property is missing or not a number.
740
+ * @returns The value.
741
+ */
742
+ function numberAt(object, key, fallback) {
743
+ const value = object[key];
744
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
745
+ }
746
+ //#endregion
747
+ //#region src/components/collider.ts
748
+ /**
749
+ * The collider contract (`docs/architecture/09-physics.md` §2.2). Every collider shares four
750
+ * fields — `center`, `isTrigger`, a material, and a layer override — and answers two questions the
751
+ * body builder asks: what Havok shape it is, and how big its local bounding box is.
752
+ *
753
+ * ## The one correction to §2.2
754
+ *
755
+ * §2.2 writes the material field as `material: asset(PhysicsMaterial) | inline { … }`. A schema
756
+ * field has exactly one kind (ADR-0004), so the union is split into two fields:
757
+ * {@link Collider.material} (an asset reference) and {@link Collider.inlineMaterial} (a record).
758
+ * The asset wins, the inline record is the fallback, and `physics.defaultMaterial` is the last
759
+ * resort.
760
+ *
761
+ * ## Shape sizes and scale
762
+ *
763
+ * Sizes are authored in local units and multiplied by the entity's lossy scale when the shape is
764
+ * built. Havok has no way to rescale a built shape, so changing the scale afterwards needs
765
+ * {@link Collider.rebuild}, exactly as §2.2 says.
766
+ */
767
+ /**
768
+ * The fields every collider declares. It is a function because a field kind is a function call and
769
+ * module scope holds declarations only (`CONSTITUTION.md` §3.5).
770
+ *
771
+ * @returns The shared field declarations, ready to spread into a collider's own schema.
772
+ *
773
+ * @public
774
+ */
775
+ function colliderFields() {
776
+ return {
777
+ center: vec3(),
778
+ isTrigger: bool(false),
779
+ material: asset(PhysicsMaterial),
780
+ inlineMaterial: optional(record({
781
+ friction: f32(.6, { min: 0 }),
782
+ staticFriction: f32(.6, { min: 0 }),
783
+ restitution: f32(0, {
784
+ min: 0,
785
+ max: 1
786
+ })
787
+ })),
788
+ layerOverride: str("")
789
+ };
790
+ }
791
+ /**
792
+ * The base class of every collider. It is never registered on its own; `entity.getComponents` and
793
+ * `world.components` accept it because the concrete colliders extend it.
794
+ *
795
+ * @public
796
+ */
797
+ var Collider = class extends Component {
798
+ /** Several colliders on one entity form one compound body (`09-physics.md` §2.2). */
799
+ static allowMultiple = true;
800
+ /**
801
+ * Applies the shared defaults. A concrete collider calls `super()` and then applies its own.
802
+ */
803
+ constructor() {
804
+ super();
805
+ Object.assign(this, createDefaults(colliderFields()));
806
+ }
807
+ /** Marks the entity's body for a rebuild at the start of the next fixed step. */
808
+ onAttach() {
809
+ this.rebuild();
810
+ }
811
+ /** Marks the entity's body for a rebuild, which removes this collider from it. */
812
+ onDetach() {
813
+ this.rebuild();
814
+ }
815
+ /**
816
+ * Rebuilds the entity's body and shapes at the start of the next fixed step. Call it after
817
+ * changing a size, a centre, `isTrigger`, or the entity's scale.
818
+ *
819
+ * @example
820
+ * ```ts
821
+ * box.size = { x: 2, y: 2, z: 2 };
822
+ * box.rebuild();
823
+ * ```
824
+ */
825
+ rebuild() {
826
+ this.app.services.tryGet(PhysicsHostKey)?.runtime?.markDirty(this.entity);
827
+ }
828
+ /**
829
+ * Resolves the surface this collider presents to Havok.
830
+ *
831
+ * @param fallback - The world's `physics.defaultMaterial`.
832
+ * @returns The asset's values, the inline values, or the fallback.
833
+ */
834
+ resolveMaterial(fallback) {
835
+ return this.material?.value ?? this.inlineMaterial ?? fallback;
836
+ }
837
+ };
838
+ //#endregion
839
+ //#region src/lite/havok.ts
840
+ /**
841
+ * How a body moves, in ignifx's vocabulary. The numbers are Lite's `PhysicsMotionType` values
842
+ * (`index.d.ts` 8543) so no translation table is needed on a per-body path.
843
+ *
844
+ * @internal
845
+ */
846
+ const BodyMotion = {
847
+ /** Immovable; `PhysicsMotionType.STATIC`. */
848
+ static: 0,
849
+ /** Driven by the node transform; `PhysicsMotionType.ANIMATED`. */
850
+ kinematic: 1,
851
+ /** Simulated; `PhysicsMotionType.DYNAMIC`. */
852
+ dynamic: 2
853
+ };
854
+ /**
855
+ * How a moved node reaches its body before a step; Lite's `PhysicsPrestepType` (8557).
856
+ *
857
+ * @internal
858
+ */
859
+ const PrestepMode = {
860
+ /** No sync at all. */
861
+ disabled: 0,
862
+ /** Snap the body onto the node. */
863
+ teleport: 1,
864
+ /** Give the body the velocity that reaches the node, so resting bodies are dragged along. */
865
+ velocity: 2
866
+ };
867
+ /**
868
+ * The shape geometries this package builds; Lite's `PhysicsShapeType` (8606).
869
+ *
870
+ * @internal
871
+ */
872
+ const ShapeGeometry = {
873
+ /** A sphere. */
874
+ sphere: 0,
875
+ /** A capsule between two points. */
876
+ capsule: 1,
877
+ /** A cylinder between two points. */
878
+ cylinder: 2,
879
+ /** An axis-aligned box in shape space. */
880
+ box: 3,
881
+ /** The convex hull of a node's meshes. */
882
+ convexHull: 4,
883
+ /** A compound of child shapes. */
884
+ container: 5,
885
+ /** A triangle mesh built from a node's meshes. */
886
+ mesh: 6
887
+ };
888
+ /**
889
+ * Creates the null-engine scene the Havok world is hosted on (`09-physics.md` §1, spike S4.1).
890
+ *
891
+ * @returns The engine and scene. Release with {@link disposeSimulation}.
892
+ *
893
+ * @internal
894
+ */
895
+ function createSimulation() {
896
+ const engine = createNullEngine();
897
+ return {
898
+ engine,
899
+ scene: createSceneContext(engine, { defaultRenderTask: false })
900
+ };
901
+ }
902
+ /**
903
+ * Releases the simulation scene. The null engine owns no GPU resource and must not be handed to
904
+ * Lite's `disposeEngine` (ADR-0009 Validation).
905
+ *
906
+ * @param handles - What {@link createSimulation} returned.
907
+ *
908
+ * @internal
909
+ */
910
+ function disposeSimulation(handles) {
911
+ disposeScene(handles.scene);
912
+ }
913
+ /**
914
+ * Advances the simulation scene by exactly one Havok step.
915
+ *
916
+ * @param handles - The engine and scene.
917
+ * @param deltaMs - The fixed step in milliseconds.
918
+ *
919
+ * @internal
920
+ */
921
+ function stepSimulation(handles, deltaMs) {
922
+ stepScene(handles.engine, handles.scene, deltaMs);
923
+ }
924
+ /**
925
+ * Creates the Havok world on a simulation scene.
926
+ *
927
+ * @param scene - The simulation scene.
928
+ * @param havok - The instantiated Havok WebAssembly module; Lite types it as `any`.
929
+ * @param gravity - The world gravity.
930
+ * @returns The world handle.
931
+ *
932
+ * @internal
933
+ */
934
+ function createWorld(scene, havok, gravity) {
935
+ return createHavokWorld(scene, havok, {
936
+ x: gravity.x,
937
+ y: gravity.y,
938
+ z: gravity.z
939
+ });
940
+ }
941
+ /**
942
+ * Releases every body and the native world. Call it before the simulation scene is disposed
943
+ * (`docs/architecture/07-rendering.md` §7 ordering).
944
+ *
945
+ * @param world - The world handle.
946
+ *
947
+ * @internal
948
+ */
949
+ function destroyWorld(world) {
950
+ disposePhysics(world);
951
+ }
952
+ /**
953
+ * Pins Lite's per-step delta to ignifx's fixed step, so the two never disagree.
954
+ *
955
+ * @param world - The world handle.
956
+ * @param seconds - The fixed step in seconds.
957
+ *
958
+ * @internal
959
+ */
960
+ function setTimestep(world, seconds) {
961
+ setPhysicsTimestep(world, seconds);
962
+ }
963
+ /**
964
+ * Sets world gravity.
965
+ *
966
+ * @param world - The world handle.
967
+ * @param gravity - The acceleration vector, in metres per second squared.
968
+ *
969
+ * @internal
970
+ */
971
+ function setGravity(world, gravity) {
972
+ setPhysicsGravity(world, {
973
+ x: gravity.x,
974
+ y: gravity.y,
975
+ z: gravity.z
976
+ });
977
+ }
978
+ /**
979
+ * Sets the world-wide speed limits.
980
+ *
981
+ * @param world - The world handle.
982
+ * @param linear - Maximum linear speed, in metres per second.
983
+ * @param angular - Maximum angular speed, in radians per second.
984
+ *
985
+ * @internal
986
+ */
987
+ function setVelocityLimits(world, linear, angular) {
988
+ setPhysicsVelocityLimits(world, linear, angular);
989
+ }
990
+ /**
991
+ * Creates a body bound to a scene node.
992
+ *
993
+ * @param world - The world handle.
994
+ * @param node - The node whose local pose is the body pose.
995
+ * @param motion - How the body moves.
996
+ * @param startsAsleep - Whether the body starts asleep.
997
+ * @returns The body handle.
998
+ *
999
+ * @internal
1000
+ */
1001
+ function createBody(world, node, motion, startsAsleep) {
1002
+ return createPhysicsBody(world, node, motion, startsAsleep);
1003
+ }
1004
+ /**
1005
+ * Removes a body from the world.
1006
+ *
1007
+ * @param world - The world handle.
1008
+ * @param body - The body to remove.
1009
+ *
1010
+ * @internal
1011
+ */
1012
+ function destroyBody(world, body) {
1013
+ removePhysicsBody(world, body);
1014
+ }
1015
+ /**
1016
+ * Attaches a shape to a body.
1017
+ *
1018
+ * @param world - The world handle.
1019
+ * @param body - The body.
1020
+ * @param shape - The shape.
1021
+ *
1022
+ * @internal
1023
+ */
1024
+ function setBodyShape(world, body, shape) {
1025
+ setPhysicsBodyShape(world, body, shape);
1026
+ }
1027
+ /**
1028
+ * Sets a body's mass. Havok recomputes the shape-derived inertia around it.
1029
+ *
1030
+ * @param world - The world handle.
1031
+ * @param body - The body.
1032
+ * @param mass - The mass in kilograms; `0` for an infinite-mass body.
1033
+ *
1034
+ * @internal
1035
+ */
1036
+ function setBodyMass(world, body, mass) {
1037
+ setPhysicsBodyMass(world, body, mass);
1038
+ }
1039
+ /**
1040
+ * Chooses how a moved node reaches the body before the next step.
1041
+ *
1042
+ * @param body - The body.
1043
+ * @param mode - The prestep mode.
1044
+ *
1045
+ * @internal
1046
+ */
1047
+ function setBodyPrestep(body, mode) {
1048
+ setPhysicsBodyPrestepType(body, mode);
1049
+ }
1050
+ /**
1051
+ * Turns collision-event reporting on or off for one body.
1052
+ *
1053
+ * @param world - The world handle.
1054
+ * @param body - The body.
1055
+ * @param enabled - Whether the body contributes to the collision stream.
1056
+ *
1057
+ * @internal
1058
+ */
1059
+ function setBodyCollisionEvents(world, body, enabled) {
1060
+ setPhysicsBodyCollisionEventsEnabled(world, body, enabled);
1061
+ }
1062
+ /**
1063
+ * Teleports a body, keeping the node it drives consistent.
1064
+ *
1065
+ * @param world - The world handle.
1066
+ * @param body - The body.
1067
+ * @param position - The world position.
1068
+ * @param rotation - The world rotation.
1069
+ *
1070
+ * @internal
1071
+ */
1072
+ function setBodyTransform(world, body, position, rotation) {
1073
+ setPhysicsBodyTransform(world, body, {
1074
+ x: position.x,
1075
+ y: position.y,
1076
+ z: position.z
1077
+ }, {
1078
+ x: rotation.x,
1079
+ y: rotation.y,
1080
+ z: rotation.z,
1081
+ w: rotation.w
1082
+ });
1083
+ }
1084
+ /**
1085
+ * Reads a body's linear velocity into an out parameter (coding standards §7).
1086
+ *
1087
+ * @param world - The world handle.
1088
+ * @param body - The body.
1089
+ * @param out - The vector to write.
1090
+ *
1091
+ * @internal
1092
+ */
1093
+ function readLinearVelocity(world, body, out) {
1094
+ const value = getPhysicsBodyLinearVelocity(world, body);
1095
+ out.set(value.x, value.y, value.z);
1096
+ }
1097
+ /**
1098
+ * Reads a body's angular velocity into an out parameter.
1099
+ *
1100
+ * @param world - The world handle.
1101
+ * @param body - The body.
1102
+ * @param out - The vector to write.
1103
+ *
1104
+ * @internal
1105
+ */
1106
+ function readAngularVelocity(world, body, out) {
1107
+ const value = getPhysicsBodyAngularVelocity(world, body);
1108
+ out.set(value.x, value.y, value.z);
1109
+ }
1110
+ /**
1111
+ * Sets a body's linear velocity.
1112
+ *
1113
+ * @param world - The world handle.
1114
+ * @param body - The body.
1115
+ * @param velocity - Metres per second, world space.
1116
+ *
1117
+ * @internal
1118
+ */
1119
+ function writeLinearVelocity(world, body, velocity) {
1120
+ setPhysicsBodyLinearVelocity(world, body, {
1121
+ x: velocity.x,
1122
+ y: velocity.y,
1123
+ z: velocity.z
1124
+ });
1125
+ }
1126
+ /**
1127
+ * Sets a body's angular velocity.
1128
+ *
1129
+ * @param world - The world handle.
1130
+ * @param body - The body.
1131
+ * @param velocity - Radians per second, world space.
1132
+ *
1133
+ * @internal
1134
+ */
1135
+ function writeAngularVelocity(world, body, velocity) {
1136
+ setPhysicsBodyAngularVelocity(world, body, {
1137
+ x: velocity.x,
1138
+ y: velocity.y,
1139
+ z: velocity.z
1140
+ });
1141
+ }
1142
+ /**
1143
+ * Applies a force for one fixed step.
1144
+ *
1145
+ * @param world - The world handle.
1146
+ * @param body - The body.
1147
+ * @param force - Newtons, world space.
1148
+ * @param point - The world-space application point.
1149
+ *
1150
+ * @internal
1151
+ */
1152
+ function applyForce(world, body, force, point) {
1153
+ applyPhysicsBodyForce(world, body, {
1154
+ x: force.x,
1155
+ y: force.y,
1156
+ z: force.z
1157
+ }, {
1158
+ x: point.x,
1159
+ y: point.y,
1160
+ z: point.z
1161
+ });
1162
+ }
1163
+ /**
1164
+ * Applies an instantaneous impulse.
1165
+ *
1166
+ * @param body - The body.
1167
+ * @param impulse - Newton-seconds, world space.
1168
+ * @param point - The world-space application point.
1169
+ *
1170
+ * @internal
1171
+ */
1172
+ function applyImpulse(body, impulse, point) {
1173
+ applyPhysicsBodyImpulse(body, {
1174
+ x: impulse.x,
1175
+ y: impulse.y,
1176
+ z: impulse.z
1177
+ }, {
1178
+ x: point.x,
1179
+ y: point.y,
1180
+ z: point.z
1181
+ });
1182
+ }
1183
+ /**
1184
+ * Locks or unlocks a body's rotation axes. Havok expresses a locked degree of freedom as zero
1185
+ * inertia (`index.d.ts` 6956).
1186
+ *
1187
+ * @param world - The world handle.
1188
+ * @param body - The body.
1189
+ * @param locked - The axes to lock; every other axis is unlocked.
1190
+ *
1191
+ * @internal
1192
+ */
1193
+ function setRotationLocks(world, body, locked) {
1194
+ const free = [];
1195
+ for (const axis of ROTATION_AXES) if (!locked.includes(axis)) free.push(axis);
1196
+ if (free.length > 0) unlockPhysicsBodyRotationAxes(world, body, free);
1197
+ if (locked.length > 0) lockPhysicsBodyRotationAxes(world, body, locked);
1198
+ }
1199
+ /** The three rotation axes Lite names, in a stable order. */
1200
+ const ROTATION_AXES = Object.freeze([
1201
+ "x",
1202
+ "y",
1203
+ "z"
1204
+ ]);
1205
+ /**
1206
+ * Creates a primitive collision shape.
1207
+ *
1208
+ * @param world - The world handle.
1209
+ * @param geometry - Which primitive to build.
1210
+ * @param parameters - Its geometry parameters.
1211
+ * @returns The shape handle.
1212
+ *
1213
+ * @internal
1214
+ */
1215
+ function createShape(world, geometry, parameters) {
1216
+ return createPhysicsShape(world, {
1217
+ type: geometry,
1218
+ parameters: { ...parameters }
1219
+ });
1220
+ }
1221
+ /**
1222
+ * Creates a triangle-mesh or convex-hull shape from a node's meshes.
1223
+ *
1224
+ * @remarks
1225
+ * Lite documents this as unsupported on the null engine (`index.d.ts` 2781: "Mesh/convex-hull
1226
+ * colliders that require `node.worldMatrix`"), and a headless `MeshAsset` uploads no geometry at
1227
+ * all, so the extension refuses with `IGX-0906` rather than building an empty shape.
1228
+ *
1229
+ * @param world - The world handle.
1230
+ * @param node - The node whose meshes supply the geometry.
1231
+ * @param convex - `true` for a convex hull, `false` for a triangle mesh.
1232
+ * @param includeChildren - Whether descendant meshes are accumulated.
1233
+ * @returns The shape handle.
1234
+ *
1235
+ * @internal
1236
+ */
1237
+ function createMeshShape(world, node, convex, includeChildren) {
1238
+ return createPhysicsShape(world, {
1239
+ type: convex ? ShapeGeometry.convexHull : ShapeGeometry.mesh,
1240
+ mesh: node,
1241
+ includeChildMeshes: includeChildren
1242
+ });
1243
+ }
1244
+ /**
1245
+ * Creates a heightfield shape from an explicit sample grid (`index.d.ts` 2601, 6266).
1246
+ *
1247
+ * @remarks
1248
+ * The explicit path only calls `hknp._malloc` and `HP_Shape_CreateHeightField`
1249
+ * (`lib/physics/havok-heightfield.js:4-22`), so it works on the null engine; the `groundMesh` path
1250
+ * reads `mesh._cpuPositions` and `worldMatrix` and does not.
1251
+ *
1252
+ * @param world - The world handle.
1253
+ * @param samplesX - How many samples along X.
1254
+ * @param samplesZ - How many samples along Z.
1255
+ * @param sizeX - The world-space size along X.
1256
+ * @param sizeZ - The world-space size along Z.
1257
+ * @param heights - `samplesX * samplesZ` row-major height samples.
1258
+ * @returns The shape handle.
1259
+ *
1260
+ * @internal
1261
+ */
1262
+ function createHeightfieldShape(world, samplesX, samplesZ, sizeX, sizeZ, heights) {
1263
+ return createHeightFieldShape(world, {
1264
+ numHeightFieldSamplesX: samplesX,
1265
+ numHeightFieldSamplesZ: samplesZ,
1266
+ heightFieldSizeX: sizeX,
1267
+ heightFieldSizeZ: sizeZ,
1268
+ heightFieldData: heights
1269
+ });
1270
+ }
1271
+ /**
1272
+ * Creates the empty compound shape several colliders on one entity are added to.
1273
+ *
1274
+ * @param world - The world handle.
1275
+ * @returns The container shape.
1276
+ *
1277
+ * @internal
1278
+ */
1279
+ function createContainer(world) {
1280
+ return createPhysicsShape(world, { type: ShapeGeometry.container });
1281
+ }
1282
+ /**
1283
+ * Adds a child shape to a container at a local offset.
1284
+ *
1285
+ * @param world - The world handle.
1286
+ * @param container - The container shape.
1287
+ * @param child - The child shape.
1288
+ * @param translation - The child's offset inside the container.
1289
+ * @param rotation - The child's rotation inside the container.
1290
+ *
1291
+ * @internal
1292
+ */
1293
+ function addContainerChild(world, container, child, translation, rotation) {
1294
+ addPhysicsShapeChild(world, container, child, {
1295
+ x: translation.x,
1296
+ y: translation.y,
1297
+ z: translation.z
1298
+ }, {
1299
+ x: rotation.x,
1300
+ y: rotation.y,
1301
+ z: rotation.z,
1302
+ w: rotation.w
1303
+ });
1304
+ }
1305
+ /**
1306
+ * Releases a shape no body references any more.
1307
+ *
1308
+ * @param world - The world handle.
1309
+ * @param shape - The shape.
1310
+ *
1311
+ * @internal
1312
+ */
1313
+ function destroyShape(world, shape) {
1314
+ releasePhysicsShape(world, shape);
1315
+ }
1316
+ /**
1317
+ * Marks a shape as a trigger volume: it reports overlaps and resolves no contacts.
1318
+ *
1319
+ * @param world - The world handle.
1320
+ * @param shape - The shape.
1321
+ * @param isTrigger - Whether the shape is a trigger.
1322
+ *
1323
+ * @internal
1324
+ */
1325
+ function setShapeTrigger(world, shape, isTrigger) {
1326
+ setPhysicsShapeIsTrigger(world, shape, isTrigger);
1327
+ }
1328
+ /**
1329
+ * Sets a shape's surface material.
1330
+ *
1331
+ * @param world - The world handle.
1332
+ * @param shape - The shape.
1333
+ * @param friction - The dynamic friction coefficient.
1334
+ * @param restitution - The bounciness, `0` to `1`.
1335
+ * @param staticFriction - The static friction coefficient.
1336
+ *
1337
+ * @internal
1338
+ */
1339
+ function setShapeMaterial(world, shape, friction, restitution, staticFriction) {
1340
+ setPhysicsShapeMaterial(world, shape, friction, restitution, staticFriction);
1341
+ }
1342
+ /**
1343
+ * Sets a shape's collision filter masks (`09-physics.md` §3).
1344
+ *
1345
+ * @param world - The world handle.
1346
+ * @param shape - The shape.
1347
+ * @param membership - The 32-bit membership mask, `1 << entity.layer`.
1348
+ * @param collideWith - The 32-bit mask of layers the shape collides with.
1349
+ *
1350
+ * @internal
1351
+ */
1352
+ function setShapeFilter(world, shape, membership, collideWith) {
1353
+ setPhysicsShapeFilterMembershipMask(world, shape, membership);
1354
+ setPhysicsShapeFilterCollideMask(world, shape, collideWith);
1355
+ }
1356
+ /**
1357
+ * Reads a node's local pose into out parameters.
1358
+ *
1359
+ * @param node - The node.
1360
+ * @param position - The vector to write the position into.
1361
+ * @param rotation - The quaternion to write the rotation into.
1362
+ *
1363
+ * @internal
1364
+ */
1365
+ function readNodePose(node, position, rotation) {
1366
+ const local = node.position;
1367
+ const quaternion = node.rotationQuaternion;
1368
+ position.set(local.x, local.y, local.z);
1369
+ rotation.set(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
1370
+ }
1371
+ /**
1372
+ * Writes a node's local pose.
1373
+ *
1374
+ * @param node - The node.
1375
+ * @param position - The position to write.
1376
+ * @param rotation - The rotation to write.
1377
+ *
1378
+ * @internal
1379
+ */
1380
+ function writeNodePose(node, position, rotation) {
1381
+ node.position.set(position.x, position.y, position.z);
1382
+ node.rotationQuaternion.set(rotation.x, rotation.y, rotation.z, rotation.w);
1383
+ }
1384
+ /**
1385
+ * Registers the trigger drain (`index.d.ts` 7787). It runs inside `stepScene`, from Lite's
1386
+ * post-step hook, so the callback must only buffer.
1387
+ *
1388
+ * @param world - The world handle.
1389
+ * @param sink - Called once per trigger event.
1390
+ * @returns A disposer that removes the drain.
1391
+ *
1392
+ * @internal
1393
+ */
1394
+ function onTriggerEvents(world, sink) {
1395
+ return onPhysicsTriggerBodies(world, (info) => {
1396
+ sink({
1397
+ entered: info.type === "ENTERED",
1398
+ nodeA: info.bodyA === null ? null : info.bodyA.node,
1399
+ nodeB: info.bodyB === null ? null : info.bodyB.node
1400
+ });
1401
+ });
1402
+ }
1403
+ /**
1404
+ * Registers the upstream collision drain (`index.d.ts` 7764). It reports contact data with no body
1405
+ * identities, which is exactly what `09-physics.md` §4 documents for the default mode.
1406
+ *
1407
+ * @param world - The world handle.
1408
+ * @param sink - Called once per collision event.
1409
+ *
1410
+ * @internal
1411
+ */
1412
+ function onCollisionEvents(world, sink) {
1413
+ onPhysicsCollision(world, (info) => {
1414
+ sink({
1415
+ phase: info.type === "STARTED" ? 0 : info.type === "CONTINUED" ? 1 : 2,
1416
+ point: info.point,
1417
+ normal: info.normal,
1418
+ impulse: info.impulse,
1419
+ nodeA: null,
1420
+ nodeB: null
1421
+ });
1422
+ });
1423
+ }
1424
+ /**
1425
+ * Registers a callback that runs after every Havok step (`index.d.ts` 7753). Lite's own drains use
1426
+ * the same hook, and the hooks run in registration order, so the extension's buffer flush is
1427
+ * registered last and sees everything the drains produced.
1428
+ *
1429
+ * @param world - The world handle.
1430
+ * @param callback - What to run after each step.
1431
+ *
1432
+ * @internal
1433
+ */
1434
+ function afterStep(world, callback) {
1435
+ onPhysicsAfterStep(world, () => {
1436
+ callback();
1437
+ });
1438
+ }
1439
+ //#endregion
1440
+ //#region src/components/colliders.ts
1441
+ /**
1442
+ * The concrete colliders (`docs/architecture/09-physics.md` §2.2). Each one maps to exactly one
1443
+ * Havok shape type (`index.d.ts` 8606) and bakes its `center` into the shape's own parameters, so a
1444
+ * single collider needs no compound wrapper.
1445
+ *
1446
+ * Sizes are authored in local units and multiplied by the entity's lossy scale when the shape is
1447
+ * built; Havok cannot rescale a built shape, so a later scale change needs `collider.rebuild()`.
1448
+ */
1449
+ /**
1450
+ * The axis a capsule stands along.
1451
+ *
1452
+ * @public
1453
+ */
1454
+ const CAPSULE_DIRECTIONS = [
1455
+ "x",
1456
+ "y",
1457
+ "z"
1458
+ ];
1459
+ /**
1460
+ * A box collider, sized in local units (`09-physics.md` §2.2).
1461
+ *
1462
+ * @example
1463
+ * ```ts
1464
+ * const floor = world.createEntity("Floor");
1465
+ * floor.addComponent(BoxCollider, { size: { x: 20, y: 1, z: 20 } });
1466
+ * ```
1467
+ *
1468
+ * @public
1469
+ */
1470
+ var BoxCollider = class BoxCollider extends Collider {
1471
+ /** The namespaced registration id. */
1472
+ static typeId = "ignifx/BoxCollider";
1473
+ /** The serialized field declarations (ADR-0004). */
1474
+ static schema = boxSchema();
1475
+ /** Applies this collider's defaults on top of the shared ones. */
1476
+ constructor() {
1477
+ super();
1478
+ Object.assign(this, createDefaults(BoxCollider.schema));
1479
+ }
1480
+ /**
1481
+ * Builds this collider's Havok shape.
1482
+ *
1483
+ * @param world - The Havok world the shape belongs to.
1484
+ * @param scale - The entity's lossy scale, applied to the authored dimensions.
1485
+ * @returns The shape handle.
1486
+ */
1487
+ createShape(world, scale) {
1488
+ return createShape(world, ShapeGeometry.box, {
1489
+ extents: {
1490
+ x: this.size.x * abs(scale.x),
1491
+ y: this.size.y * abs(scale.y),
1492
+ z: this.size.z * abs(scale.z)
1493
+ },
1494
+ center: scaled(this.center, scale),
1495
+ rotation: new Quat()
1496
+ });
1497
+ }
1498
+ /**
1499
+ * Writes half the size of this collider's local bounding box, scale applied.
1500
+ *
1501
+ * @param scale - The entity's lossy scale.
1502
+ * @param out - The vector to write.
1503
+ */
1504
+ halfExtentsToRef(scale, out) {
1505
+ out.set(this.size.x * abs(scale.x) / 2, this.size.y * abs(scale.y) / 2, this.size.z * abs(scale.z) / 2);
1506
+ }
1507
+ };
1508
+ /**
1509
+ * A sphere collider. Non-uniform scale is not representable as a sphere, so the largest scale axis
1510
+ * wins — the same rule Unity applies.
1511
+ *
1512
+ * @public
1513
+ */
1514
+ var SphereCollider = class SphereCollider extends Collider {
1515
+ /** The namespaced registration id. */
1516
+ static typeId = "ignifx/SphereCollider";
1517
+ /** The serialized field declarations. */
1518
+ static schema = sphereSchema();
1519
+ /** Applies this collider's defaults on top of the shared ones. */
1520
+ constructor() {
1521
+ super();
1522
+ Object.assign(this, createDefaults(SphereCollider.schema));
1523
+ }
1524
+ /**
1525
+ * Builds this collider's Havok shape.
1526
+ *
1527
+ * @param world - The Havok world the shape belongs to.
1528
+ * @param scale - The entity's lossy scale, applied to the authored dimensions.
1529
+ * @returns The shape handle.
1530
+ */
1531
+ createShape(world, scale) {
1532
+ return createShape(world, ShapeGeometry.sphere, {
1533
+ radius: this.radius * maxAxis(scale),
1534
+ center: scaled(this.center, scale)
1535
+ });
1536
+ }
1537
+ /**
1538
+ * Writes half the size of this collider's local bounding box, scale applied.
1539
+ *
1540
+ * @param scale - The entity's lossy scale.
1541
+ * @param out - The vector to write.
1542
+ */
1543
+ halfExtentsToRef(scale, out) {
1544
+ const radius = this.radius * maxAxis(scale);
1545
+ out.set(radius, radius, radius);
1546
+ }
1547
+ };
1548
+ /**
1549
+ * A capsule collider: a cylinder with hemispherical caps, standing along one axis.
1550
+ *
1551
+ * @remarks
1552
+ * `height` is the **total** tip-to-tip height, so a capsule shorter than `2 * radius` degenerates to
1553
+ * a sphere of that radius rather than inverting.
1554
+ *
1555
+ * @public
1556
+ */
1557
+ var CapsuleCollider = class CapsuleCollider extends Collider {
1558
+ /** The namespaced registration id. */
1559
+ static typeId = "ignifx/CapsuleCollider";
1560
+ /** The serialized field declarations. */
1561
+ static schema = capsuleSchema();
1562
+ /** Applies this collider's defaults on top of the shared ones. */
1563
+ constructor() {
1564
+ super();
1565
+ Object.assign(this, createDefaults(CapsuleCollider.schema));
1566
+ }
1567
+ /**
1568
+ * Builds this collider's Havok shape.
1569
+ *
1570
+ * @param world - The Havok world the shape belongs to.
1571
+ * @param scale - The entity's lossy scale, applied to the authored dimensions.
1572
+ * @returns The shape handle.
1573
+ */
1574
+ createShape(world, scale) {
1575
+ const radius = this.radius * radialScale(this.direction, scale);
1576
+ const half = Math.max(0, this.height * axisScale(this.direction, scale) / 2 - radius);
1577
+ const center = scaled(this.center, scale);
1578
+ return createShape(world, ShapeGeometry.capsule, {
1579
+ radius,
1580
+ pointA: offsetAlong(center, this.direction, -half),
1581
+ pointB: offsetAlong(center, this.direction, half)
1582
+ });
1583
+ }
1584
+ /**
1585
+ * Writes half the size of this collider's local bounding box, scale applied.
1586
+ *
1587
+ * @param scale - The entity's lossy scale.
1588
+ * @param out - The vector to write.
1589
+ */
1590
+ halfExtentsToRef(scale, out) {
1591
+ const radius = this.radius * radialScale(this.direction, scale);
1592
+ const half = Math.max(radius, this.height * axisScale(this.direction, scale) / 2);
1593
+ out.set(this.direction === "x" ? half : radius, this.direction === "y" ? half : radius, this.direction === "z" ? half : radius);
1594
+ }
1595
+ };
1596
+ /**
1597
+ * A cylinder collider standing along Y.
1598
+ *
1599
+ * @public
1600
+ */
1601
+ var CylinderCollider = class CylinderCollider extends Collider {
1602
+ /** The namespaced registration id. */
1603
+ static typeId = "ignifx/CylinderCollider";
1604
+ /** The serialized field declarations. */
1605
+ static schema = cylinderSchema();
1606
+ /** Applies this collider's defaults on top of the shared ones. */
1607
+ constructor() {
1608
+ super();
1609
+ Object.assign(this, createDefaults(CylinderCollider.schema));
1610
+ }
1611
+ /**
1612
+ * Builds this collider's Havok shape.
1613
+ *
1614
+ * @param world - The Havok world the shape belongs to.
1615
+ * @param scale - The entity's lossy scale, applied to the authored dimensions.
1616
+ * @returns The shape handle.
1617
+ */
1618
+ createShape(world, scale) {
1619
+ const radius = this.radius * Math.max(abs(scale.x), abs(scale.z));
1620
+ const half = this.height * abs(scale.y) / 2;
1621
+ const center = scaled(this.center, scale);
1622
+ return createShape(world, ShapeGeometry.cylinder, {
1623
+ radius,
1624
+ pointA: {
1625
+ x: center.x,
1626
+ y: center.y - half,
1627
+ z: center.z
1628
+ },
1629
+ pointB: {
1630
+ x: center.x,
1631
+ y: center.y + half,
1632
+ z: center.z
1633
+ }
1634
+ });
1635
+ }
1636
+ /**
1637
+ * Writes half the size of this collider's local bounding box, scale applied.
1638
+ *
1639
+ * @param scale - The entity's lossy scale.
1640
+ * @param out - The vector to write.
1641
+ */
1642
+ halfExtentsToRef(scale, out) {
1643
+ const radius = this.radius * Math.max(abs(scale.x), abs(scale.z));
1644
+ out.set(radius, this.height * abs(scale.y) / 2, radius);
1645
+ }
1646
+ };
1647
+ /**
1648
+ * A collider built from real geometry: either an explicit `MeshAsset` or, when `mesh` is
1649
+ * `null`, whatever the entity's `MeshRenderer`/`Model` put under its node.
1650
+ *
1651
+ * @remarks
1652
+ * **Headless is not supported.** `@babylonjs/lite@1.27.0` documents mesh and convex-hull colliders
1653
+ * as unavailable on the null engine (`index.d.ts` 2781), and a headless `MeshAsset` uploads no
1654
+ * geometry at all (`MeshAsset.lite.mesh` is `null`), so building one reports `IGX-0906` instead of
1655
+ * producing an empty shape. Use a primitive collider in headless tests.
1656
+ *
1657
+ * @public
1658
+ */
1659
+ var MeshCollider = class MeshCollider extends Collider {
1660
+ /** The namespaced registration id. */
1661
+ static typeId = "ignifx/MeshCollider";
1662
+ /** The serialized field declarations. */
1663
+ static schema = meshSchema();
1664
+ /** Applies this collider's defaults on top of the shared ones. */
1665
+ constructor() {
1666
+ super();
1667
+ Object.assign(this, createDefaults(MeshCollider.schema));
1668
+ }
1669
+ /**
1670
+ * Builds this collider's Havok shape from real geometry.
1671
+ *
1672
+ * @param world - The Havok world the shape belongs to.
1673
+ * @param _scale - Unused: a mesh shape carries the geometry's own world scale.
1674
+ * @param node - The entity's node, whose meshes supply the vertices when `mesh` is `null`.
1675
+ * @returns The shape handle.
1676
+ */
1677
+ createShape(world, _scale, node) {
1678
+ return createMeshShape(world, this.#sourceNode(node), this.convex, this.includeChildren);
1679
+ }
1680
+ /**
1681
+ * Writes half the size of this collider's local bounding box — zero, because measuring a triangle
1682
+ * soup means reading its vertices, which is GPU territory.
1683
+ *
1684
+ * @param _scale - Unused.
1685
+ * @param out - The vector to write.
1686
+ */
1687
+ halfExtentsToRef(_scale, out) {
1688
+ out.set(0, 0, 0);
1689
+ }
1690
+ /**
1691
+ * The node whose meshes supply the geometry.
1692
+ *
1693
+ * @param entityNode - The entity's own node.
1694
+ * @returns The node to hand Lite.
1695
+ * @throws IgnifxError with code `IGX-0906` when there is no geometry to read.
1696
+ */
1697
+ #sourceNode(entityNode) {
1698
+ const explicit = this.mesh?.value.lite.mesh ?? null;
1699
+ if (explicit !== null) return explicit;
1700
+ if (this.mesh !== null) throw physicsError(PhysicsErrorCode.colliderGeometryUnavailable, "The MeshCollider's mesh asset has no geometry.", {
1701
+ context: { entity: this.entity.name },
1702
+ hint: "Mesh colliders need a GPU app; a headless MeshAsset uploads nothing to build a shape from."
1703
+ });
1704
+ if (entityNode.children.length === 0) throw physicsError(PhysicsErrorCode.colliderGeometryUnavailable, "The MeshCollider has no mesh to read.", {
1705
+ context: { entity: this.entity.name },
1706
+ hint: "Add a MeshRenderer or Model to the entity, or set the collider's mesh field."
1707
+ });
1708
+ return entityNode;
1709
+ }
1710
+ };
1711
+ /**
1712
+ * A heightfield collider: a regular grid of height samples in the XZ plane, which is what a terrain
1713
+ * uses (`index.d.ts` 2601, 6266).
1714
+ *
1715
+ * @remarks
1716
+ * Only Lite's **explicit** heightfield path is used, because the `groundMesh` path reads
1717
+ * `mesh._cpuPositions` and `worldMatrix` and therefore needs a GPU. `heights` is row-major with
1718
+ * `samplesX * samplesZ` entries.
1719
+ *
1720
+ * @public
1721
+ */
1722
+ var HeightfieldCollider = class HeightfieldCollider extends Collider {
1723
+ /** The namespaced registration id. */
1724
+ static typeId = "ignifx/HeightfieldCollider";
1725
+ /** The serialized field declarations. */
1726
+ static schema = heightfieldSchema();
1727
+ /** Applies this collider's defaults on top of the shared ones. */
1728
+ constructor() {
1729
+ super();
1730
+ Object.assign(this, createDefaults(HeightfieldCollider.schema));
1731
+ }
1732
+ /**
1733
+ * Builds this collider's Havok shape.
1734
+ *
1735
+ * @param world - The Havok world the shape belongs to.
1736
+ * @param scale - The entity's lossy scale, applied to the authored dimensions.
1737
+ * @returns The shape handle.
1738
+ */
1739
+ createShape(world, scale) {
1740
+ const expected = this.samplesX * this.samplesZ;
1741
+ if (this.samplesX < 2 || this.samplesZ < 2 || this.heights.length !== expected) throw physicsError(PhysicsErrorCode.colliderGeometryUnavailable, "The HeightfieldCollider's sample grid is invalid.", {
1742
+ context: {
1743
+ entity: this.entity.name,
1744
+ expected,
1745
+ actual: this.heights.length
1746
+ },
1747
+ hint: "heights must hold samplesX * samplesZ values, and both counts must be at least 2."
1748
+ });
1749
+ const data = new Float32Array(expected);
1750
+ for (let index = 0; index < expected; index += 1) data[index] = (this.heights[index] ?? 0) * abs(scale.y);
1751
+ return createHeightfieldShape(world, this.samplesX, this.samplesZ, this.size.x * abs(scale.x), this.size.z * abs(scale.z), data);
1752
+ }
1753
+ /**
1754
+ * Writes half the size of this collider's local bounding box, scale applied.
1755
+ *
1756
+ * @param scale - The entity's lossy scale.
1757
+ * @param out - The vector to write.
1758
+ */
1759
+ halfExtentsToRef(scale, out) {
1760
+ out.set(this.size.x * abs(scale.x) / 2, this.size.y * abs(scale.y) / 2, this.size.z * abs(scale.z) / 2);
1761
+ }
1762
+ };
1763
+ /**
1764
+ * Builds the `BoxCollider` schema.
1765
+ *
1766
+ * @returns The schema.
1767
+ */
1768
+ function boxSchema() {
1769
+ return defineSchema({
1770
+ ...colliderFields(),
1771
+ size: vec3({
1772
+ x: 1,
1773
+ y: 1,
1774
+ z: 1
1775
+ })
1776
+ });
1777
+ }
1778
+ /**
1779
+ * Builds the `SphereCollider` schema.
1780
+ *
1781
+ * @returns The schema.
1782
+ */
1783
+ function sphereSchema() {
1784
+ return defineSchema({
1785
+ ...colliderFields(),
1786
+ radius: f32(.5, { min: 0 })
1787
+ });
1788
+ }
1789
+ /**
1790
+ * Builds the `CapsuleCollider` schema.
1791
+ *
1792
+ * @returns The schema.
1793
+ */
1794
+ function capsuleSchema() {
1795
+ return defineSchema({
1796
+ ...colliderFields(),
1797
+ radius: f32(.5, { min: 0 }),
1798
+ height: f32(2, { min: 0 }),
1799
+ direction: enumOf(CAPSULE_DIRECTIONS, "y")
1800
+ });
1801
+ }
1802
+ /**
1803
+ * Builds the `CylinderCollider` schema.
1804
+ *
1805
+ * @returns The schema.
1806
+ */
1807
+ function cylinderSchema() {
1808
+ return defineSchema({
1809
+ ...colliderFields(),
1810
+ radius: f32(.5, { min: 0 }),
1811
+ height: f32(2, { min: 0 })
1812
+ });
1813
+ }
1814
+ /**
1815
+ * Builds the `MeshCollider` schema.
1816
+ *
1817
+ * @returns The schema.
1818
+ */
1819
+ function meshSchema() {
1820
+ return defineSchema({
1821
+ ...colliderFields(),
1822
+ mesh: asset(MeshAsset),
1823
+ convex: bool(false),
1824
+ includeChildren: bool(true)
1825
+ });
1826
+ }
1827
+ /**
1828
+ * Builds the `HeightfieldCollider` schema.
1829
+ *
1830
+ * @returns The schema.
1831
+ */
1832
+ function heightfieldSchema() {
1833
+ return defineSchema({
1834
+ ...colliderFields(),
1835
+ heights: array(f32()),
1836
+ samplesX: u32(2, { min: 2 }),
1837
+ samplesZ: u32(2, { min: 2 }),
1838
+ size: vec3({
1839
+ x: 1,
1840
+ y: 1,
1841
+ z: 1
1842
+ })
1843
+ });
1844
+ }
1845
+ /**
1846
+ * The absolute value of a scale component; a negative scale mirrors geometry, which Havok cannot
1847
+ * represent, so the shape uses the magnitude (`09-physics.md` §2.2).
1848
+ *
1849
+ * @param value - The scale component.
1850
+ * @returns Its magnitude.
1851
+ */
1852
+ function abs(value) {
1853
+ return Math.abs(value);
1854
+ }
1855
+ /**
1856
+ * The largest scale magnitude, used by shapes that have one radius.
1857
+ *
1858
+ * @param scale - The lossy scale.
1859
+ * @returns The largest magnitude.
1860
+ */
1861
+ function maxAxis(scale) {
1862
+ return Math.max(abs(scale.x), abs(scale.y), abs(scale.z));
1863
+ }
1864
+ /**
1865
+ * Scales a local offset into shape space.
1866
+ *
1867
+ * @param center - The authored offset.
1868
+ * @param scale - The lossy scale.
1869
+ * @returns A fresh vector; shape construction is not a per-frame path.
1870
+ */
1871
+ function scaled(center, scale) {
1872
+ return new Vec3(center.x * scale.x, center.y * scale.y, center.z * scale.z);
1873
+ }
1874
+ /**
1875
+ * The scale along a capsule's own axis.
1876
+ *
1877
+ * @param direction - The capsule axis.
1878
+ * @param scale - The lossy scale.
1879
+ * @returns The magnitude along that axis.
1880
+ */
1881
+ function axisScale(direction, scale) {
1882
+ if (direction === "x") return abs(scale.x);
1883
+ return direction === "y" ? abs(scale.y) : abs(scale.z);
1884
+ }
1885
+ /**
1886
+ * The scale across a capsule's axis, which drives its radius.
1887
+ *
1888
+ * @param direction - The capsule axis.
1889
+ * @param scale - The lossy scale.
1890
+ * @returns The larger of the two perpendicular magnitudes.
1891
+ */
1892
+ function radialScale(direction, scale) {
1893
+ if (direction === "x") return Math.max(abs(scale.y), abs(scale.z));
1894
+ return direction === "y" ? Math.max(abs(scale.x), abs(scale.z)) : Math.max(abs(scale.x), abs(scale.y));
1895
+ }
1896
+ /**
1897
+ * Offsets a point along one axis.
1898
+ *
1899
+ * @param center - The starting point.
1900
+ * @param direction - Which axis to move along.
1901
+ * @param distance - How far to move.
1902
+ * @returns A fresh vector.
1903
+ */
1904
+ function offsetAlong(center, direction, distance) {
1905
+ return new Vec3(center.x + (direction === "x" ? distance : 0), center.y + (direction === "y" ? distance : 0), center.z + (direction === "z" ? distance : 0));
1906
+ }
1907
+ //#endregion
1908
+ //#region src/lite/havok-module.ts
1909
+ /**
1910
+ * Loading the Havok WebAssembly module (`docs/architecture/09-physics.md` §7, ADR-0003 Validation).
1911
+ *
1912
+ * `@babylonjs/havok@1.3.14`'s ESM build hard-codes `ENVIRONMENT_IS_WEB = true` and fetches its
1913
+ * `.wasm` with `fetch(scriptDirectory + path)`, so `locateFile` cannot help under Node — Node's
1914
+ * `fetch` refuses `file:` URLs. Emscripten's `wasmBinary` option is the supported escape and is what
1915
+ * this module always uses: the bytes are obtained first (from the caller, from `fetch`, or from
1916
+ * `node:fs`) and handed to the factory. `app.isHeadless` therefore only changes *where the bytes
1917
+ * come from*, exactly as the Phase 4 brief requires.
1918
+ *
1919
+ * The `@babylonjs/havok` import lives here because this file is under `src/lite/`, the only place
1920
+ * `ignifx/no-lite-outside-adapter` and dependency-cruiser allow a native backend.
1921
+ *
1922
+ * Everything here is `@internal`.
1923
+ */
1924
+ /**
1925
+ * The unhashed file name the Vite plugin copies into the public asset path, and therefore the
1926
+ * address `app.assets.resolveUrl` answers for.
1927
+ *
1928
+ * @remarks
1929
+ * Extension public assets are copied by **base name** (`packages/vite-plugin/src/plugin.ts`,
1930
+ * `generateBundle`), into the same directory the default asset root points at, so the address is the
1931
+ * bare file name and not a package-scoped path.
1932
+ *
1933
+ * @internal
1934
+ */
1935
+ const HAVOK_WASM_FILE_NAME = "HavokPhysics.wasm";
1936
+ /**
1937
+ * Instantiates Havok.
1938
+ *
1939
+ * @param source - An instantiated module, explicit bytes, or a URL to read them from.
1940
+ * @returns The module, typed as `unknown` because Lite types its own parameter as `any`.
1941
+ * @throws IgnifxError with code `IGX-0903` when the bytes cannot be obtained or the module fails to
1942
+ * instantiate.
1943
+ *
1944
+ * @example
1945
+ * ```ts
1946
+ * const havok = await loadHavok({ url: app.assets.resolveUrl(HAVOK_WASM_FILE_NAME) });
1947
+ * ```
1948
+ *
1949
+ * @internal
1950
+ */
1951
+ async function loadHavok(source) {
1952
+ if (source.module !== void 0 && source.module !== null) return source.module;
1953
+ const url = source.url ?? "HavokPhysics.wasm";
1954
+ const wasmBinary = source.wasmBinary ?? await readWasmBytes(url);
1955
+ try {
1956
+ return await HavokPhysics({ wasmBinary });
1957
+ } catch (cause) {
1958
+ throw physicsError(PhysicsErrorCode.havokUnavailable, "Havok failed to instantiate from the supplied bytes.", {
1959
+ context: { url },
1960
+ hint: "Check that HavokPhysics.wasm matches the installed @babylonjs/havok version.",
1961
+ cause
1962
+ });
1963
+ }
1964
+ }
1965
+ /**
1966
+ * Reads the `.wasm` bytes, preferring `fetch` and falling back to the file system under Node.
1967
+ *
1968
+ * @param url - The URL or path.
1969
+ * @returns The bytes as a plain `ArrayBuffer`, which is what Emscripten wants.
1970
+ * @throws IgnifxError with code `IGX-0903` when neither route produces bytes.
1971
+ */
1972
+ async function readWasmBytes(url) {
1973
+ let fetchFailure = null;
1974
+ if (typeof globalThis.fetch === "function") try {
1975
+ const response = await globalThis.fetch(url);
1976
+ if (response.ok) return await response.arrayBuffer();
1977
+ fetchFailure = /* @__PURE__ */ new Error(`${String(response.status)} ${response.statusText}`);
1978
+ } catch (cause) {
1979
+ fetchFailure = cause;
1980
+ }
1981
+ const fromDisk = await readFromDisk(url);
1982
+ if (fromDisk !== null) return fromDisk;
1983
+ const fromPackage = await readFromPackage();
1984
+ if (fromPackage !== null) return fromPackage;
1985
+ throw physicsError(PhysicsErrorCode.havokUnavailable, "The Havok WebAssembly bytes could not be read.", {
1986
+ context: { url },
1987
+ hint: "Set physics({ havokWasm: \"<url>\" }) or hand physics({ wasmBinary }) the bytes yourself.",
1988
+ ...fetchFailure === null ? {} : { cause: fetchFailure }
1989
+ });
1990
+ }
1991
+ /**
1992
+ * Reads a file through `node:fs` when the host is Node, and reports `null` everywhere else.
1993
+ *
1994
+ * @remarks
1995
+ * The specifier is held in a constant so that browser bundlers leave the import alone: a bundler
1996
+ * only rewrites a `import("…")` whose argument is a string literal, and this branch is unreachable
1997
+ * in a browser anyway.
1998
+ *
1999
+ * @param path - The file path.
2000
+ * @returns The bytes, or `null` when there is no file system to read from, or the file is
2001
+ * unreadable. A browser fails the import itself, which is the same answer.
2002
+ */
2003
+ async function readFromDisk(path) {
2004
+ try {
2005
+ const bytes = await (await import(
2006
+ /* @vite-ignore */
2007
+ NODE_FS_SPECIFIER
2008
+ )).readFile(path);
2009
+ const copy = new ArrayBuffer(bytes.byteLength);
2010
+ new Uint8Array(copy).set(bytes);
2011
+ return copy;
2012
+ } catch {
2013
+ return null;
2014
+ }
2015
+ }
2016
+ /** The `node:fs/promises` specifier, held in a constant so bundlers do not follow it. */
2017
+ const NODE_FS_SPECIFIER = "node:fs/promises";
2018
+ /** Where `@babylonjs/havok@1.3.14` keeps the binary its ESM build would otherwise `fetch`. */
2019
+ const HAVOK_PACKAGE_WASM = "@babylonjs/havok/lib/esm/HavokPhysics.wasm";
2020
+ /**
2021
+ * Reads the binary straight out of the installed `@babylonjs/havok` package, which is what makes a
2022
+ * headless Node app work with no configuration at all: `app.isHeadless` only changes *where the
2023
+ * bytes come from* (Phase 4 brief), and under Node the answer is the package itself.
2024
+ *
2025
+ * @returns The bytes, or `null` when `import.meta.resolve` is unavailable or the package cannot be
2026
+ * resolved.
2027
+ */
2028
+ async function readFromPackage() {
2029
+ try {
2030
+ const resolved = import.meta.resolve(HAVOK_PACKAGE_WASM);
2031
+ return await readFromDisk(resolved.startsWith("file://") ? fileUrlToPath(resolved) : resolved);
2032
+ } catch {
2033
+ return null;
2034
+ }
2035
+ }
2036
+ /**
2037
+ * Turns a `file:` URL into a path `node:fs` accepts.
2038
+ *
2039
+ * @param url - The `file:` URL.
2040
+ * @returns The decoded path.
2041
+ */
2042
+ function fileUrlToPath(url) {
2043
+ return decodeURIComponent(new URL(url).pathname);
2044
+ }
2045
+ //#endregion
2046
+ //#region src/runtime/host.ts
2047
+ /**
2048
+ * The one mutable cell between `register` and `onStart`.
2049
+ *
2050
+ * `Extension.register` runs **before** `createApp` builds the Lite engine and the world
2051
+ * (`packages/core/src/app/app.ts`, `initialize`), and the Havok world needs both. So the extension
2052
+ * declares its systems and its service in `register` — which is where `04-extensions.md` §1 says
2053
+ * everything is declared — and they all read the runtime through this holder, which `onStart` fills
2054
+ * in once Havok has loaded.
2055
+ *
2056
+ * @internal
2057
+ */
2058
+ var PhysicsHost = class {
2059
+ /** The runtime, or `null` until `onStart` has built it. */
2060
+ runtime = null;
2061
+ };
2062
+ //#endregion
2063
+ //#region src/lite/character.ts
2064
+ /**
2065
+ * How the character is supported by whatever is under it; Lite's `CharacterSupportedState` (1615).
2066
+ *
2067
+ * @internal
2068
+ */
2069
+ const SupportState = {
2070
+ /** Nothing within reach. */
2071
+ unsupported: 0,
2072
+ /** Touching a surface too steep to stand on. */
2073
+ sliding: 1,
2074
+ /** Standing on a walkable surface. */
2075
+ supported: 2
2076
+ };
2077
+ /**
2078
+ * Creates a controller.
2079
+ *
2080
+ * @param world - The Havok world.
2081
+ * @param position - The starting world position of the capsule centre.
2082
+ * @param height - Total capsule height, tip to tip.
2083
+ * @param radius - Capsule radius.
2084
+ * @returns The controller.
2085
+ *
2086
+ * @internal
2087
+ */
2088
+ function createController(world, position, height, radius) {
2089
+ return createPhysicsCharacterController(world, {
2090
+ x: position.x,
2091
+ y: position.y,
2092
+ z: position.z
2093
+ }, {
2094
+ capsuleHeight: height,
2095
+ capsuleRadius: radius
2096
+ });
2097
+ }
2098
+ /**
2099
+ * Applies the tuning fields `CharacterController` exposes.
2100
+ *
2101
+ * @param controller - The controller.
2102
+ * @param slopeCosine - The cosine of the steepest walkable slope.
2103
+ * @param skinWidth - The separation kept from surfaces, in metres.
2104
+ * @param strength - The push strength applied to dynamic bodies.
2105
+ *
2106
+ * @internal
2107
+ */
2108
+ function tuneController(controller, slopeCosine, skinWidth, strength) {
2109
+ controller.maxSlopeCosine = slopeCosine;
2110
+ controller.keepDistance = skinWidth;
2111
+ controller.characterStrength = strength;
2112
+ }
2113
+ /**
2114
+ * Rebuilds the capsule without losing the controller's position, velocity, or subscriptions.
2115
+ *
2116
+ * @param controller - The controller.
2117
+ * @param height - The new total height.
2118
+ * @param radius - The new radius.
2119
+ * @param preserveFeet - Whether the foot position stays fixed as the height changes.
2120
+ *
2121
+ * @internal
2122
+ */
2123
+ function resizeController(controller, height, radius, preserveFeet) {
2124
+ controller.setShapeOptions({
2125
+ capsuleHeight: height,
2126
+ capsuleRadius: radius
2127
+ }, preserveFeet);
2128
+ }
2129
+ /**
2130
+ * Moves the character by a displacement, sliding along whatever it meets.
2131
+ *
2132
+ * @param controller - The controller.
2133
+ * @param displacement - The requested world-space displacement for this step.
2134
+ *
2135
+ * @internal
2136
+ */
2137
+ function moveController(controller, displacement) {
2138
+ controller.moveWithCollisions({
2139
+ x: displacement.x,
2140
+ y: displacement.y,
2141
+ z: displacement.z
2142
+ });
2143
+ }
2144
+ /**
2145
+ * Probes the surface under the character without moving it.
2146
+ *
2147
+ * @param controller - The controller.
2148
+ * @param deltaSeconds - The fixed step.
2149
+ * @param gravity - The probe direction, normally gravity.
2150
+ * @param groundNormal - Written with the averaged supporting normal.
2151
+ * @returns The support classification.
2152
+ *
2153
+ * @internal
2154
+ */
2155
+ function probeSupport(controller, deltaSeconds, gravity, groundNormal) {
2156
+ const surface = controller.checkSupport(deltaSeconds, {
2157
+ x: gravity.x,
2158
+ y: gravity.y,
2159
+ z: gravity.z
2160
+ });
2161
+ const normal = surface.averageSurfaceNormal;
2162
+ groundNormal.set(normal.x, normal.y, normal.z);
2163
+ return toSupportState(surface.supportedState);
2164
+ }
2165
+ /**
2166
+ * Reads the controller's resolved position.
2167
+ *
2168
+ * @param controller - The controller.
2169
+ * @param out - The vector to write.
2170
+ *
2171
+ * @internal
2172
+ */
2173
+ function readControllerPosition(controller, out) {
2174
+ const position = controller.getPosition();
2175
+ out.set(position.x, position.y, position.z);
2176
+ }
2177
+ /**
2178
+ * Teleports the controller, clearing any swept motion.
2179
+ *
2180
+ * @param controller - The controller.
2181
+ * @param position - The new world position.
2182
+ *
2183
+ * @internal
2184
+ */
2185
+ function writeControllerPosition(controller, position) {
2186
+ controller.setPosition({
2187
+ x: position.x,
2188
+ y: position.y,
2189
+ z: position.z
2190
+ });
2191
+ }
2192
+ /**
2193
+ * Reads the controller's velocity.
2194
+ *
2195
+ * @param controller - The controller.
2196
+ * @param out - The vector to write.
2197
+ *
2198
+ * @internal
2199
+ */
2200
+ function readControllerVelocity(controller, out) {
2201
+ const velocity = controller.getVelocity();
2202
+ out.set(velocity.x, velocity.y, velocity.z);
2203
+ }
2204
+ /**
2205
+ * Sets the controller's velocity.
2206
+ *
2207
+ * @param controller - The controller.
2208
+ * @param velocity - The new world-space velocity.
2209
+ *
2210
+ * @internal
2211
+ */
2212
+ function writeControllerVelocity(controller, velocity) {
2213
+ controller.setVelocity({
2214
+ x: velocity.x,
2215
+ y: velocity.y,
2216
+ z: velocity.z
2217
+ });
2218
+ }
2219
+ /**
2220
+ * Subscribes to the dynamic bodies the character pushes.
2221
+ *
2222
+ * @param controller - The controller.
2223
+ * @param sink - Called once per pushed body, during the step.
2224
+ * @returns A disposer that removes the subscription.
2225
+ *
2226
+ * @internal
2227
+ */
2228
+ function onControllerPush(controller, sink) {
2229
+ return controller.onTriggerCollisionObservable.add((event) => {
2230
+ sink({
2231
+ node: event.collider.node,
2232
+ impulse: event.impulse,
2233
+ point: event.impulsePosition
2234
+ });
2235
+ });
2236
+ }
2237
+ /**
2238
+ * Releases the controller's body, shape, and query collectors.
2239
+ *
2240
+ * @param controller - The controller.
2241
+ *
2242
+ * @internal
2243
+ */
2244
+ function disposeController(controller) {
2245
+ controller.dispose();
2246
+ }
2247
+ /**
2248
+ * Narrows Lite's support enum to {@link SupportState}.
2249
+ *
2250
+ * @param value - Lite's value.
2251
+ * @returns The matching state, defaulting to `unsupported`.
2252
+ */
2253
+ function toSupportState(value) {
2254
+ if (value === SupportState.supported) return SupportState.supported;
2255
+ return value === SupportState.sliding ? SupportState.sliding : SupportState.unsupported;
2256
+ }
2257
+ //#endregion
2258
+ //#region src/lite/internal/collision-drain.ts
2259
+ /** Lite's `offA`: where the first contact's slots begin. */
2260
+ const OFFSET_A = 2;
2261
+ /** Lite's `offB`: where the second contact's slots begin. */
2262
+ const OFFSET_B = 18;
2263
+ /** The Babylon Lite version this drain was written and tested against. */
2264
+ const PINNED_LITE_VERSION = "1.27.0";
2265
+ /**
2266
+ * Reports whether a world exposes the internals this drain reads.
2267
+ *
2268
+ * @param world - The Havok world handle.
2269
+ * @returns `true` when every field the drain needs is present and of the expected kind.
2270
+ *
2271
+ * @internal
2272
+ */
2273
+ function probeCollisionLayout(world) {
2274
+ const internals = asWorldInternals(world);
2275
+ const havok = internals._hknp;
2276
+ if (havok === void 0 || internals._hkWorld === void 0 || !Array.isArray(internals._bodies)) return false;
2277
+ if (typeof havok.HP_World_GetCollisionEvents !== "function") return false;
2278
+ if (typeof havok.HP_World_GetNextCollisionEvent !== "function") return false;
2279
+ const started = havok.EventType["COLLISION_STARTED"];
2280
+ const continued = havok.EventType["COLLISION_CONTINUED"];
2281
+ return typeof started?.value === "number" && typeof continued?.value === "number";
2282
+ }
2283
+ /**
2284
+ * Registers the internal drain on a world's post-step hook.
2285
+ *
2286
+ * @param world - The Havok world handle.
2287
+ * @param sink - Called once per collision event, with both nodes resolved.
2288
+ * @throws IgnifxError with code `IGX-0908` when {@link probeCollisionLayout} says the internals
2289
+ * moved, which is what makes a Babylon Lite upgrade fail loudly rather than silently.
2290
+ *
2291
+ * @internal
2292
+ */
2293
+ function drainCollisionsWithBodies(world, sink) {
2294
+ if (!probeCollisionLayout(world)) throw physicsError(PhysicsErrorCode.internalDrainUnavailable, "physics({ collisionIdentities: \"internal\" }) needs Babylon Lite's Havok internals, which this version does not expose.", {
2295
+ context: { version: PINNED_LITE_VERSION },
2296
+ hint: "Pin @babylonjs/lite to 1.27.0, or use the default collisionIdentities: \"upstream\"."
2297
+ });
2298
+ const internals = asWorldInternals(world);
2299
+ const havok = internals._hknp;
2300
+ const native = internals._hkWorld;
2301
+ if (havok === void 0 || native === void 0) return;
2302
+ const startedValue = havok.EventType["COLLISION_STARTED"]?.value ?? -1;
2303
+ const continuedValue = havok.EventType["COLLISION_CONTINUED"]?.value ?? -1;
2304
+ afterStep(world, () => {
2305
+ let address = havok.HP_World_GetCollisionEvents(native)[1];
2306
+ while (address !== 0) {
2307
+ const ints = new Int32Array(havok.HEAPU8.buffer, address);
2308
+ const floats = new Float32Array(havok.HEAPU8.buffer, address);
2309
+ const type = ints[0] ?? -1;
2310
+ sink({
2311
+ phase: type === startedValue ? 0 : type === continuedValue ? 1 : 2,
2312
+ point: {
2313
+ x: floats[10] ?? 0,
2314
+ y: floats[11] ?? 0,
2315
+ z: floats[12] ?? 0
2316
+ },
2317
+ normal: {
2318
+ x: floats[13] ?? 0,
2319
+ y: floats[14] ?? 0,
2320
+ z: floats[15] ?? 0
2321
+ },
2322
+ impulse: floats[34] ?? 0,
2323
+ nodeA: nodeById(internals, ints[OFFSET_A] ?? 0),
2324
+ nodeB: nodeById(internals, ints[OFFSET_B] ?? 0)
2325
+ });
2326
+ address = havok.HP_World_GetNextCollisionEvent(native, address);
2327
+ }
2328
+ });
2329
+ }
2330
+ /**
2331
+ * Resolves a native body id to the node Lite bound it to, the same linear scan Lite's own
2332
+ * `findBodyById` performs (`lib/physics/havok-trigger.js`, `havok-queries.js`).
2333
+ *
2334
+ * @param internals - The world internals.
2335
+ * @param id - The native body id from the event buffer.
2336
+ * @returns The node, or `null` when the body is no longer tracked.
2337
+ */
2338
+ function nodeById(internals, id) {
2339
+ const bodies = internals._bodies ?? [];
2340
+ for (let index = 0; index < bodies.length; index += 1) {
2341
+ const body = bodies[index];
2342
+ const native = body?._hkBody?.[0];
2343
+ if (native === id) return body?.node ?? null;
2344
+ if (typeof native === "bigint" && native === BigInt(id)) return body?.node ?? null;
2345
+ }
2346
+ return null;
2347
+ }
2348
+ /**
2349
+ * Views a Lite world as the internal record this drain reads.
2350
+ *
2351
+ * @remarks
2352
+ * The waived boundary crossing of ADR-0013, in one expression. It needs no assertion: Lite declares
2353
+ * `PhysicsWorld` as an empty interface and every field below is optional, so the view is structural
2354
+ * — and {@link probeCollisionLayout} is what makes reading it safe.
2355
+ *
2356
+ * @param world - The opaque handle.
2357
+ * @returns The same object, typed.
2358
+ */
2359
+ function asWorldInternals(world) {
2360
+ return world;
2361
+ }
2362
+ //#endregion
2363
+ //#region src/runtime/runtime.ts
2364
+ /**
2365
+ * The per-app physics runtime: the Havok world, the bodies, the character controllers, the event
2366
+ * drains, and the three things the systems ask it to do each frame — restore, step, interpolate
2367
+ * (`docs/architecture/09-physics.md` §1).
2368
+ *
2369
+ * Everything here is `@internal`; the public surface is `PhysicsService`, `Rigidbody`, the
2370
+ * colliders, and `CharacterController`.
2371
+ */
2372
+ /**
2373
+ * How collision events learn which bodies took part (`09-physics.md` §4, ADR-0013).
2374
+ *
2375
+ * @public
2376
+ */
2377
+ const COLLISION_IDENTITY_MODES = ["upstream", "internal"];
2378
+ /**
2379
+ * The counters `09-physics.md` §9 and the plan's diagnostics deliverable name.
2380
+ *
2381
+ * @public
2382
+ */
2383
+ const PHYSICS_DIAGNOSTICS_COUNTERS = Object.freeze([
2384
+ "bodies",
2385
+ "activeBodies",
2386
+ "stepsThisFrame",
2387
+ "collisionEvents",
2388
+ "triggerEvents",
2389
+ "queries",
2390
+ "stepMs"
2391
+ ]);
2392
+ /**
2393
+ * The diagnostics group name.
2394
+ *
2395
+ * @public
2396
+ */
2397
+ const PHYSICS_DIAGNOSTICS_GROUP = "physics";
2398
+ /** How many layers a project can declare, and therefore how wide a filter mask is. */
2399
+ const LAYER_COUNT = 32;
2400
+ /** Milliseconds in one second. */
2401
+ const MILLISECONDS_PER_SECOND = 1e3;
2402
+ /** How far a body may move before the implicit-static diagnostic considers it moved. */
2403
+ const STATIC_MOVE_EPSILON = 1e-6;
2404
+ /**
2405
+ * The per-app physics runtime.
2406
+ *
2407
+ * @internal
2408
+ */
2409
+ var PhysicsRuntime = class {
2410
+ #ctx;
2411
+ #settings;
2412
+ #simulation;
2413
+ #world;
2414
+ #identities;
2415
+ #counters;
2416
+ #records = [];
2417
+ #byEntity = /* @__PURE__ */ new Map();
2418
+ #byNode = /* @__PURE__ */ new Map();
2419
+ #dirty = /* @__PURE__ */ new Set();
2420
+ #controllers = [];
2421
+ #dirtyControllers = /* @__PURE__ */ new Set();
2422
+ #collideMasks = new Int32Array(LAYER_COUNT).fill(-1);
2423
+ #triggerSlots = [];
2424
+ #contactSlots = [];
2425
+ #triggerEvent = null;
2426
+ #contactPoint = {
2427
+ point: new Vec3(),
2428
+ normal: new Vec3(),
2429
+ impulse: 0
2430
+ };
2431
+ #contacts = [];
2432
+ #collision = null;
2433
+ #scratchPosition = new Vec3();
2434
+ #scratchRotation = new Quat();
2435
+ #scratchVector = new Vec3();
2436
+ #scratchOther = new Vec3();
2437
+ #relativeVelocity = new Vec3();
2438
+ #gravityDirection = new Vec3(0, -1, 0);
2439
+ #triggerCount = 0;
2440
+ #contactCount = 0;
2441
+ #stepped = false;
2442
+ #disposed = false;
2443
+ #queries = 0;
2444
+ #stepsThisFrame = 0;
2445
+ #stepMs = 0;
2446
+ #collisionEventCount = 0;
2447
+ #triggerEventCount = 0;
2448
+ #activeBodies = 0;
2449
+ /**
2450
+ * Builds the runtime, applies the world settings, and registers the event drains.
2451
+ *
2452
+ * @param options - The context, settings, scene, world, identity mode, and counters.
2453
+ * @throws IgnifxError with code `IGX-0905` when the collision matrix names an unknown layer, or
2454
+ * `IGX-0908` when the internal drain does not recognise this Babylon Lite build.
2455
+ */
2456
+ constructor(options) {
2457
+ this.#ctx = options.ctx;
2458
+ this.#settings = options.settings;
2459
+ this.#simulation = options.simulation;
2460
+ this.#world = options.world;
2461
+ this.#identities = options.collisionIdentities;
2462
+ this.#counters = options.counters;
2463
+ this.#contacts.push(this.#contactPoint);
2464
+ setGravity(this.#world, this.#settings.gravity);
2465
+ const gravity = this.#settings.gravity;
2466
+ const magnitude = Math.hypot(gravity.x, gravity.y, gravity.z);
2467
+ if (magnitude > 0) this.#gravityDirection.set(gravity.x / magnitude, gravity.y / magnitude, gravity.z / magnitude);
2468
+ const limits = this.#settings.velocityLimits;
2469
+ if (limits.linear > 0 || limits.angular > 0) setVelocityLimits(this.#world, limits.linear, limits.angular);
2470
+ this.#buildCollideMasks();
2471
+ onTriggerEvents(this.#world, (record) => {
2472
+ this.#bufferTrigger(record);
2473
+ });
2474
+ if (this.#identities === "internal") drainCollisionsWithBodies(this.#world, (record) => {
2475
+ this.#bufferContact(record);
2476
+ });
2477
+ else onCollisionEvents(this.#world, (record) => {
2478
+ this.#bufferContact(record);
2479
+ });
2480
+ afterStep(this.#world, () => {});
2481
+ }
2482
+ /**
2483
+ * The Havok world, for the query and viewer paths.
2484
+ *
2485
+ * @returns The world handle.
2486
+ */
2487
+ get world() {
2488
+ return this.#world;
2489
+ }
2490
+ /**
2491
+ * Whether at least one fixed step has run, which is what Havok's broadphase needs before a query
2492
+ * can answer (`09-physics.md` §5).
2493
+ *
2494
+ * @returns `true` once a step has completed.
2495
+ */
2496
+ get hasStepped() {
2497
+ return this.#stepped;
2498
+ }
2499
+ /**
2500
+ * Every body, in creation order.
2501
+ *
2502
+ * @returns The records.
2503
+ */
2504
+ get records() {
2505
+ return this.#records;
2506
+ }
2507
+ /**
2508
+ * The resolved settings.
2509
+ *
2510
+ * @returns The `physics` section.
2511
+ */
2512
+ get settings() {
2513
+ return this.#settings;
2514
+ }
2515
+ /**
2516
+ * Replaces world gravity.
2517
+ *
2518
+ * @param gravity - The new acceleration vector.
2519
+ */
2520
+ setGravity(gravity) {
2521
+ setGravity(this.#world, gravity);
2522
+ }
2523
+ /**
2524
+ * Marks an entity's body for a rebuild at the start of the next fixed step.
2525
+ *
2526
+ * @param entity - The entity whose colliders or `Rigidbody` changed.
2527
+ */
2528
+ markDirty(entity) {
2529
+ if (!this.#disposed && !entity.isDestroyed) this.#dirty.add(entity);
2530
+ }
2531
+ /**
2532
+ * Marks a character controller for a rebuild at the start of the next fixed step.
2533
+ *
2534
+ * @param component - The controller component.
2535
+ */
2536
+ markControllerDirty(component) {
2537
+ if (!this.#disposed) this.#dirtyControllers.add(component);
2538
+ }
2539
+ /**
2540
+ * Restores the authoritative pose of every interpolated body and controller, undoing the display
2541
+ * pose the `PreRender` system wrote (`09-physics.md` §1, spike S4.3).
2542
+ */
2543
+ restorePoses() {
2544
+ for (let index = 0; index < this.#records.length; index += 1) {
2545
+ const record = this.#records[index];
2546
+ if (record !== void 0 && record.interpolate) writeNodePose(record.node, record.currentPosition, record.currentRotation);
2547
+ }
2548
+ for (let index = 0; index < this.#controllers.length; index += 1) {
2549
+ const record = this.#controllers[index];
2550
+ if (record !== void 0 && record.interpolate) this.#writeControllerTransform(record, record.currentPosition);
2551
+ }
2552
+ }
2553
+ /**
2554
+ * Runs one fixed step: reconcile, step Havok, snapshot poses, dispatch events.
2555
+ *
2556
+ * @param fixedDeltaSeconds - The fixed step in seconds.
2557
+ */
2558
+ step(fixedDeltaSeconds) {
2559
+ this.#syncLayers();
2560
+ this.#reconcile();
2561
+ this.#applyControllerMoves(fixedDeltaSeconds);
2562
+ setTimestep(this.#world, fixedDeltaSeconds);
2563
+ this.#triggerCount = 0;
2564
+ this.#contactCount = 0;
2565
+ const started = now();
2566
+ stepSimulation(this.#simulation, fixedDeltaSeconds * MILLISECONDS_PER_SECOND);
2567
+ this.#stepMs += now() - started;
2568
+ this.#stepsThisFrame += 1;
2569
+ this.#stepped = true;
2570
+ this.#snapshot(fixedDeltaSeconds);
2571
+ this.#dispatchTriggers();
2572
+ this.#dispatchContacts();
2573
+ }
2574
+ /**
2575
+ * Writes the interpolated display pose of every interpolated body and controller.
2576
+ *
2577
+ * @param alpha - `time.fixedStepAlpha`, in `[0, 1)`.
2578
+ */
2579
+ interpolate(alpha) {
2580
+ this.#publishCounters();
2581
+ for (let index = 0; index < this.#records.length; index += 1) {
2582
+ const record = this.#records[index];
2583
+ if (record === void 0 || !record.interpolate) continue;
2584
+ const position = this.#scratchPosition;
2585
+ position.set(lerp(record.previousPosition.x, record.currentPosition.x, alpha), lerp(record.previousPosition.y, record.currentPosition.y, alpha), lerp(record.previousPosition.z, record.currentPosition.z, alpha));
2586
+ Quat.slerpToRef(record.previousRotation, record.currentRotation, alpha, this.#scratchRotation);
2587
+ writeNodePose(record.node, position, this.#scratchRotation);
2588
+ }
2589
+ for (let index = 0; index < this.#controllers.length; index += 1) {
2590
+ const record = this.#controllers[index];
2591
+ if (record === void 0 || !record.interpolate) continue;
2592
+ this.#scratchPosition.set(lerp(record.previousPosition.x, record.currentPosition.x, alpha), lerp(record.previousPosition.y, record.currentPosition.y, alpha), lerp(record.previousPosition.z, record.currentPosition.z, alpha));
2593
+ this.#writeControllerTransform(record, this.#scratchPosition);
2594
+ }
2595
+ }
2596
+ /**
2597
+ * The Havok body of an entity, for the `.lite` escape hatch and the debug viewer.
2598
+ *
2599
+ * @param entity - The entity.
2600
+ * @returns The body handle, or `null`.
2601
+ */
2602
+ bodyHandleOf(entity) {
2603
+ return this.#byEntity.get(entity)?.body ?? null;
2604
+ }
2605
+ /**
2606
+ * The record an entity owns.
2607
+ *
2608
+ * @param entity - The entity.
2609
+ * @returns The record, or `null`.
2610
+ */
2611
+ recordOf(entity) {
2612
+ return this.#byEntity.get(entity) ?? null;
2613
+ }
2614
+ /**
2615
+ * The record a Lite node belongs to, which is how a Havok event or query result becomes an entity.
2616
+ *
2617
+ * @param node - The node.
2618
+ * @returns The record, or `null`.
2619
+ */
2620
+ recordOfNode(node) {
2621
+ return node === null ? null : this.#byNode.get(node) ?? null;
2622
+ }
2623
+ /** Counts one query for the diagnostics group. */
2624
+ countQuery() {
2625
+ this.#queries += 1;
2626
+ }
2627
+ /**
2628
+ * Reads a body's linear velocity.
2629
+ *
2630
+ * @param entity - The entity.
2631
+ * @param out - The vector to write; left untouched when there is no body.
2632
+ */
2633
+ readLinear(entity, out) {
2634
+ const record = this.#byEntity.get(entity);
2635
+ if (record !== void 0) readLinearVelocity(this.#world, record.body, out);
2636
+ }
2637
+ /**
2638
+ * Reads a body's angular velocity.
2639
+ *
2640
+ * @param entity - The entity.
2641
+ * @param out - The vector to write.
2642
+ */
2643
+ readAngular(entity, out) {
2644
+ const record = this.#byEntity.get(entity);
2645
+ if (record !== void 0) readAngularVelocity(this.#world, record.body, out);
2646
+ }
2647
+ /**
2648
+ * Sets a body's linear velocity.
2649
+ *
2650
+ * @param entity - The entity.
2651
+ * @param velocity - Metres per second, world space.
2652
+ */
2653
+ setLinearVelocity(entity, velocity) {
2654
+ const record = this.#byEntity.get(entity);
2655
+ if (record !== void 0) writeLinearVelocity(this.#world, record.body, velocity);
2656
+ }
2657
+ /**
2658
+ * Sets a body's angular velocity.
2659
+ *
2660
+ * @param entity - The entity.
2661
+ * @param velocity - Radians per second, world space.
2662
+ */
2663
+ setAngularVelocity(entity, velocity) {
2664
+ const record = this.#byEntity.get(entity);
2665
+ if (record !== void 0) writeAngularVelocity(this.#world, record.body, velocity);
2666
+ }
2667
+ /**
2668
+ * Applies a force for one fixed step.
2669
+ *
2670
+ * @param entity - The entity.
2671
+ * @param force - Newtons, world space.
2672
+ * @param point - The application point.
2673
+ */
2674
+ addForce(entity, force, point) {
2675
+ const record = this.#byEntity.get(entity);
2676
+ if (record !== void 0) applyForce(this.#world, record.body, force, point);
2677
+ }
2678
+ /**
2679
+ * Applies an impulse.
2680
+ *
2681
+ * @param entity - The entity.
2682
+ * @param impulse - Newton-seconds, world space.
2683
+ * @param point - The application point.
2684
+ */
2685
+ addImpulse(entity, impulse, point) {
2686
+ const record = this.#byEntity.get(entity);
2687
+ if (record !== void 0) applyImpulse(record.body, impulse, point);
2688
+ }
2689
+ /**
2690
+ * Teleports a body and resets its interpolation history.
2691
+ *
2692
+ * @param entity - The entity.
2693
+ * @param position - The new world position.
2694
+ * @param rotation - The new world rotation.
2695
+ */
2696
+ teleport(entity, position, rotation) {
2697
+ const record = this.#byEntity.get(entity);
2698
+ if (record === void 0) {
2699
+ writeNodePose(entity.transform.lite, position, rotation);
2700
+ return;
2701
+ }
2702
+ setBodyTransform(this.#world, record.body, position, rotation);
2703
+ writeNodePose(record.node, position, rotation);
2704
+ record.currentPosition.set(position.x, position.y, position.z);
2705
+ record.currentRotation.set(rotation.x, rotation.y, rotation.z, rotation.w);
2706
+ record.previousPosition.set(position.x, position.y, position.z);
2707
+ record.previousRotation.set(rotation.x, rotation.y, rotation.z, rotation.w);
2708
+ }
2709
+ /**
2710
+ * Sets a character controller's velocity.
2711
+ *
2712
+ * @param component - The controller component.
2713
+ * @param velocity - Metres per second, world space.
2714
+ */
2715
+ setControllerVelocity(component, velocity) {
2716
+ const record = this.#controllerOf(component);
2717
+ if (record !== null) writeControllerVelocity(record.controller, velocity);
2718
+ }
2719
+ /**
2720
+ * Reads a character controller's velocity.
2721
+ *
2722
+ * @param component - The controller component.
2723
+ * @param out - The vector to write.
2724
+ */
2725
+ readControllerVelocity(component, out) {
2726
+ const record = this.#controllerOf(component);
2727
+ if (record !== null) readControllerVelocity(record.controller, out);
2728
+ }
2729
+ /**
2730
+ * Reads a character controller's world position.
2731
+ *
2732
+ * @param component - The controller component.
2733
+ * @param out - The vector to write.
2734
+ */
2735
+ readControllerPosition(component, out) {
2736
+ const record = this.#controllerOf(component);
2737
+ if (record !== null) readControllerPosition(record.controller, out);
2738
+ }
2739
+ /**
2740
+ * Rebuilds a controller's capsule in place.
2741
+ *
2742
+ * @param component - The controller component.
2743
+ * @param preserveFeet - Whether the foot position stays fixed.
2744
+ */
2745
+ resizeController(component, preserveFeet) {
2746
+ const record = this.#controllerOf(component);
2747
+ if (record !== null) resizeController(record.controller, component.height, component.radius, preserveFeet);
2748
+ }
2749
+ /**
2750
+ * Teleports a controller and resets its interpolation history.
2751
+ *
2752
+ * @param component - The controller component.
2753
+ * @param position - The new entity world position.
2754
+ */
2755
+ teleportController(component, position) {
2756
+ const record = this.#controllerOf(component);
2757
+ if (record === null) {
2758
+ component.transform.position = position;
2759
+ return;
2760
+ }
2761
+ const centre = this.#scratchVector;
2762
+ centre.set(position.x + component.center.x, position.y + component.center.y, position.z + component.center.z);
2763
+ writeControllerPosition(record.controller, centre);
2764
+ record.currentPosition.set(centre.x, centre.y, centre.z);
2765
+ record.previousPosition.set(centre.x, centre.y, centre.z);
2766
+ this.#writeControllerTransform(record, centre);
2767
+ }
2768
+ /**
2769
+ * Releases a controller's Lite resources.
2770
+ *
2771
+ * @param component - The controller component.
2772
+ */
2773
+ releaseController(component) {
2774
+ this.#dirtyControllers.delete(component);
2775
+ for (let index = 0; index < this.#controllers.length; index += 1) {
2776
+ const record = this.#controllers[index];
2777
+ if (record?.component === component) {
2778
+ record.disconnect();
2779
+ disposeController(record.controller);
2780
+ this.#controllers.splice(index, 1);
2781
+ return;
2782
+ }
2783
+ }
2784
+ }
2785
+ /**
2786
+ * Tears every body and controller down, then releases the Havok world **before** the simulation
2787
+ * scene, which is the order `docs/architecture/07-rendering.md` §7 requires.
2788
+ */
2789
+ dispose() {
2790
+ if (this.#disposed) return;
2791
+ this.#disposed = true;
2792
+ for (let index = this.#controllers.length - 1; index >= 0; index -= 1) {
2793
+ const record = this.#controllers[index];
2794
+ if (record !== void 0) {
2795
+ record.disconnect();
2796
+ disposeController(record.controller);
2797
+ }
2798
+ }
2799
+ this.#controllers.length = 0;
2800
+ for (let index = this.#records.length - 1; index >= 0; index -= 1) {
2801
+ const record = this.#records[index];
2802
+ if (record !== void 0) this.#teardown(record);
2803
+ }
2804
+ this.#records.length = 0;
2805
+ this.#byEntity.clear();
2806
+ this.#byNode.clear();
2807
+ destroyWorld(this.#world);
2808
+ disposeSimulation(this.#simulation);
2809
+ }
2810
+ /**
2811
+ * Publishes the frame's counters and zeroes the accumulators. The kernel resets `FrameSample` each
2812
+ * frame but not diagnostics **groups** (`Diagnostics.beginFrame`), so a group that reports
2813
+ * per-frame totals resets itself — and `PreRender` is where a frame's fixed steps are all done.
2814
+ */
2815
+ #publishCounters() {
2816
+ this.#counters.set(this.#index("bodies"), this.#records.length);
2817
+ this.#counters.set(this.#index("activeBodies"), this.#activeBodies);
2818
+ this.#counters.set(this.#index("stepsThisFrame"), this.#stepsThisFrame);
2819
+ this.#counters.set(this.#index("collisionEvents"), this.#collisionEventCount);
2820
+ this.#counters.set(this.#index("triggerEvents"), this.#triggerEventCount);
2821
+ this.#counters.set(this.#index("queries"), this.#queries);
2822
+ this.#counters.set(this.#index("stepMs"), this.#stepMs);
2823
+ this.#stepsThisFrame = 0;
2824
+ this.#collisionEventCount = 0;
2825
+ this.#triggerEventCount = 0;
2826
+ this.#queries = 0;
2827
+ this.#stepMs = 0;
2828
+ }
2829
+ /**
2830
+ * Resolves a counter name to its index. Called with literal names only, from paths that run once
2831
+ * per step rather than once per body.
2832
+ *
2833
+ * @param counter - The counter name.
2834
+ * @returns Its index.
2835
+ */
2836
+ #index(counter) {
2837
+ return this.#counters.index(counter);
2838
+ }
2839
+ /**
2840
+ * Builds the per-layer collide masks from `physics.collisionMatrix` (`09-physics.md` §3).
2841
+ *
2842
+ * @remarks
2843
+ * A layer the matrix does not mention keeps `~0`, so a default project needs no matrix at all.
2844
+ * Havok tests the pair in both directions, so one side listing the other is enough to *allow* the
2845
+ * pair and one side omitting it is enough to *block* it.
2846
+ *
2847
+ * @throws IgnifxError with code `IGX-0905` when a name is not a declared layer.
2848
+ */
2849
+ #buildCollideMasks() {
2850
+ const layers = this.#ctx.app.world.layers;
2851
+ for (const [name, others] of Object.entries(this.#settings.collisionMatrix)) {
2852
+ const index = layers.indexOf(name);
2853
+ if (index < 0) throw unknownLayer(name);
2854
+ let mask = 0;
2855
+ for (const other of others) {
2856
+ const otherIndex = layers.indexOf(other);
2857
+ if (otherIndex < 0) throw unknownLayer(other);
2858
+ mask |= 1 << otherIndex;
2859
+ }
2860
+ this.#collideMasks[index] = mask;
2861
+ }
2862
+ }
2863
+ /**
2864
+ * Rebuilds every body marked dirty, and every controller.
2865
+ */
2866
+ #reconcile() {
2867
+ if (this.#dirty.size > 0) {
2868
+ const pending = [...this.#dirty];
2869
+ this.#dirty.clear();
2870
+ for (const entity of pending) this.#rebuildEntity(entity);
2871
+ }
2872
+ if (this.#dirtyControllers.size > 0) {
2873
+ const pending = [...this.#dirtyControllers];
2874
+ this.#dirtyControllers.clear();
2875
+ for (const component of pending) this.#rebuildController(component);
2876
+ }
2877
+ }
2878
+ /**
2879
+ * Tears an entity's body down and builds a new one from its current colliders.
2880
+ *
2881
+ * @param entity - The entity to rebuild.
2882
+ */
2883
+ #rebuildEntity(entity) {
2884
+ const existing = this.#byEntity.get(entity);
2885
+ let carriedLinear = null;
2886
+ let carriedAngular = null;
2887
+ if (existing !== void 0) {
2888
+ if (existing.motion === BodyMotion.dynamic) {
2889
+ carriedLinear = new Vec3();
2890
+ carriedAngular = new Vec3();
2891
+ readLinearVelocity(this.#world, existing.body, carriedLinear);
2892
+ readAngularVelocity(this.#world, existing.body, carriedAngular);
2893
+ }
2894
+ this.#teardown(existing);
2895
+ const index = this.#records.indexOf(existing);
2896
+ if (index >= 0) this.#records.splice(index, 1);
2897
+ this.#byEntity.delete(entity);
2898
+ this.#byNode.delete(existing.node);
2899
+ }
2900
+ if (entity.isDestroyed || !entity.activeInHierarchy) return;
2901
+ const colliders = collidersOf(entity);
2902
+ if (colliders.length === 0) return;
2903
+ const rigidbody = entity.getComponent(Rigidbody);
2904
+ if (entity.parent !== null) this.#ctx.log.warn(`${PhysicsErrorCode.bodyOnChildEntity}: {entity} carries a physics body but is not a root entity; Havok writes its local pose.`, entity.name);
2905
+ const record = this.#build(entity, rigidbody, colliders);
2906
+ this.#records.push(record);
2907
+ if (record.motion === BodyMotion.dynamic && carriedLinear !== null && carriedAngular !== null) {
2908
+ writeLinearVelocity(this.#world, record.body, carriedLinear);
2909
+ writeAngularVelocity(this.#world, record.body, carriedAngular);
2910
+ }
2911
+ }
2912
+ /**
2913
+ * Drops an entity's body immediately. `markDirty` refuses a destroyed entity — by the time
2914
+ * `onDestroyed` fires the entity is already gone — so destruction takes this path instead.
2915
+ *
2916
+ * @param entity - The entity whose body goes away.
2917
+ */
2918
+ #removeRecord(entity) {
2919
+ const record = this.#byEntity.get(entity);
2920
+ if (record === void 0) return;
2921
+ this.#teardown(record);
2922
+ const index = this.#records.indexOf(record);
2923
+ if (index >= 0) this.#records.splice(index, 1);
2924
+ this.#byEntity.delete(entity);
2925
+ this.#byNode.delete(record.node);
2926
+ this.#dirty.delete(entity);
2927
+ }
2928
+ /**
2929
+ * Builds one body from an entity's colliders.
2930
+ *
2931
+ * @param entity - The entity.
2932
+ * @param rigidbody - Its `Rigidbody`, or `null` for an implicit static body.
2933
+ * @param colliders - Its colliders, in component order.
2934
+ * @returns The new record.
2935
+ */
2936
+ #build(entity, rigidbody, colliders) {
2937
+ const node = entity.transform.lite;
2938
+ const scale = entity.transform.lossyScale;
2939
+ const layer = entity.layer;
2940
+ const shapes = this.#buildShapeTree(colliders, scale, node, layer);
2941
+ const root = shapes.at(-1);
2942
+ if (root === void 0) throw new Error("a body needs at least one collider");
2943
+ const motion = motionOf(rigidbody);
2944
+ const body = this.#createBody(node, root, rigidbody, motion);
2945
+ const record = {
2946
+ entity,
2947
+ node,
2948
+ rigidbody,
2949
+ colliders: [...colliders],
2950
+ body,
2951
+ shapes,
2952
+ motion,
2953
+ interpolate: this.#shouldInterpolate(rigidbody, motion),
2954
+ layer,
2955
+ collisionEvents: false,
2956
+ previousPosition: new Vec3(),
2957
+ previousRotation: new Quat(),
2958
+ currentPosition: new Vec3(),
2959
+ currentRotation: new Quat(),
2960
+ halfExtents: boundsOf(colliders, scale),
2961
+ staticVersion: entity.transform.worldMatrixVersion,
2962
+ reportedMove: false,
2963
+ disconnects: []
2964
+ };
2965
+ readNodePose(node, record.currentPosition, record.currentRotation);
2966
+ record.previousPosition.copyFrom(record.currentPosition);
2967
+ record.previousRotation.copyFrom(record.currentRotation);
2968
+ this.#byEntity.set(entity, record);
2969
+ this.#byNode.set(node, record);
2970
+ this.#applyCollisionEvents(record);
2971
+ this.#watchEntity(record);
2972
+ return record;
2973
+ }
2974
+ /**
2975
+ * Keeps a record in step with its entity: component changes rebuild, destruction removes.
2976
+ *
2977
+ * @param record - The record to watch.
2978
+ */
2979
+ #watchEntity(record) {
2980
+ const entity = record.entity;
2981
+ record.disconnects.push(entity.onComponentAdded.connect((component) => {
2982
+ this.#onComponentChanged(record, component);
2983
+ }), entity.onComponentRemoved.connect((component) => {
2984
+ this.#onComponentChanged(record, component);
2985
+ }), entity.onDestroyed.connect(() => {
2986
+ this.#removeRecord(entity);
2987
+ }));
2988
+ }
2989
+ /**
2990
+ * Builds the shapes for a body: one shape for a single collider, or a container holding a child
2991
+ * per collider. The root shape is the **last** entry.
2992
+ *
2993
+ * @param colliders - The colliders, in component order.
2994
+ * @param scale - The entity's lossy scale.
2995
+ * @param node - The entity's Lite node.
2996
+ * @param layer - The entity's layer.
2997
+ * @returns Every shape created, root last, for release when the body goes.
2998
+ */
2999
+ #buildShapeTree(colliders, scale, node, layer) {
3000
+ const defaults = this.#settings.defaultMaterial;
3001
+ const shapes = [];
3002
+ const only = colliders.length === 1 ? colliders[0] : void 0;
3003
+ if (only !== void 0) {
3004
+ shapes.push(this.#buildShape(only, scale, node, layer, defaults));
3005
+ return shapes;
3006
+ }
3007
+ const root = createContainer(this.#world);
3008
+ for (const collider of colliders) {
3009
+ const child = this.#buildShape(collider, scale, node, layer, defaults);
3010
+ shapes.push(child);
3011
+ addContainerChild(this.#world, root, child, Vec3.zero(), Quat.identity());
3012
+ }
3013
+ setShapeFilter(this.#world, root, membershipOf(layer), this.#collideMaskOf(layer));
3014
+ shapes.push(root);
3015
+ return shapes;
3016
+ }
3017
+ /**
3018
+ * Creates the Havok body for a record and applies its motion-dependent settings.
3019
+ *
3020
+ * @param node - The entity's Lite node.
3021
+ * @param root - The root shape.
3022
+ * @param rigidbody - The `Rigidbody`, or `null` for an implicit static body.
3023
+ * @param motion - The motion type derived from the rigidbody.
3024
+ * @returns The body.
3025
+ */
3026
+ #createBody(node, root, rigidbody, motion) {
3027
+ const body = createBody(this.#world, node, motion, rigidbody?.startAsleep ?? false);
3028
+ setBodyShape(this.#world, body, root);
3029
+ if (motion === BodyMotion.dynamic) setBodyMass(this.#world, body, rigidbody?.mass ?? 1);
3030
+ if (motion === BodyMotion.kinematic) setBodyPrestep(body, rigidbody?.kinematicSync === "velocity" ? PrestepMode.velocity : PrestepMode.teleport);
3031
+ if (rigidbody !== null) setRotationLocks(this.#world, body, lockedAxes(rigidbody));
3032
+ return body;
3033
+ }
3034
+ /**
3035
+ * Builds one collider's shape and applies its filter, material, and trigger flag.
3036
+ *
3037
+ * @param collider - The collider.
3038
+ * @param scale - The entity's lossy scale.
3039
+ * @param node - The entity's node.
3040
+ * @param layer - The entity's layer.
3041
+ * @param defaults - The world's default material.
3042
+ * @returns The shape.
3043
+ */
3044
+ #buildShape(collider, scale, node, layer, defaults) {
3045
+ const shape = collider.createShape(this.#world, scale, node);
3046
+ const effective = this.#layerOf(collider, layer);
3047
+ setShapeFilter(this.#world, shape, membershipOf(effective), this.#collideMaskOf(effective));
3048
+ const material = collider.resolveMaterial(defaults);
3049
+ setShapeMaterial(this.#world, shape, material.friction, material.restitution, material.staticFriction);
3050
+ if (collider.isTrigger) setShapeTrigger(this.#world, shape, true);
3051
+ return shape;
3052
+ }
3053
+ /**
3054
+ * The layer a collider filters as: its override, or its entity's.
3055
+ *
3056
+ * @param collider - The collider.
3057
+ * @param fallback - The entity's layer.
3058
+ * @returns The layer index.
3059
+ * @throws IgnifxError with code `IGX-0905` when the override names an undeclared layer.
3060
+ */
3061
+ #layerOf(collider, fallback) {
3062
+ if (collider.layerOverride === "") return fallback;
3063
+ const index = this.#ctx.app.world.layers.indexOf(collider.layerOverride);
3064
+ if (index < 0) throw unknownLayer(collider.layerOverride);
3065
+ return index;
3066
+ }
3067
+ /**
3068
+ * The collide mask of a layer.
3069
+ *
3070
+ * @param layer - The layer index.
3071
+ * @returns The 32-bit mask.
3072
+ */
3073
+ #collideMaskOf(layer) {
3074
+ return this.#collideMasks[layer] ?? -1;
3075
+ }
3076
+ /**
3077
+ * Whether a body's display pose is interpolated.
3078
+ *
3079
+ * @param rigidbody - The `Rigidbody`, or `null`.
3080
+ * @param motion - The motion type.
3081
+ * @returns `true` when interpolation applies.
3082
+ */
3083
+ #shouldInterpolate(rigidbody, motion) {
3084
+ if (!this.#settings.interpolation || motion === BodyMotion.static || rigidbody === null) return false;
3085
+ return rigidbody.interpolation === "interpolate";
3086
+ }
3087
+ /**
3088
+ * Recomputes `collisionEvents` when a component joins or leaves the entity (`09-physics.md` §2.1).
3089
+ *
3090
+ * @param record - The body record.
3091
+ * @param component - The component that changed.
3092
+ */
3093
+ #onComponentChanged(record, component) {
3094
+ if (component instanceof Collider || component instanceof Rigidbody) {
3095
+ this.markDirty(record.entity);
3096
+ return;
3097
+ }
3098
+ this.#applyCollisionEvents(record);
3099
+ }
3100
+ /**
3101
+ * Pushes the effective `collisionEvents` value to Havok.
3102
+ *
3103
+ * @param record - The body record.
3104
+ */
3105
+ #applyCollisionEvents(record) {
3106
+ const mode = record.rigidbody?.collisionEvents ?? "auto";
3107
+ const enabled = mode === "on" ? true : mode === "off" ? false : this.#entityWantsCollisions(record.entity);
3108
+ if (enabled !== record.collisionEvents) {
3109
+ record.collisionEvents = enabled;
3110
+ setBodyCollisionEvents(this.#world, record.body, enabled);
3111
+ }
3112
+ }
3113
+ /**
3114
+ * Whether any script on an entity implements a collision callback.
3115
+ *
3116
+ * @param entity - The entity.
3117
+ * @returns `true` when at least one does.
3118
+ */
3119
+ #entityWantsCollisions(entity) {
3120
+ return this.#ctx.entityImplements(entity, "onCollisionEnter") || this.#ctx.entityImplements(entity, "onCollisionStay") || this.#ctx.entityImplements(entity, "onCollisionExit");
3121
+ }
3122
+ /**
3123
+ * Applies a runtime `entity.layer` change to the filter masks, which `09-physics.md` §3 says
3124
+ * happens on the next fixed step.
3125
+ */
3126
+ #syncLayers() {
3127
+ for (let index = 0; index < this.#records.length; index += 1) {
3128
+ const record = this.#records[index];
3129
+ if (record === void 0 || record.entity.layer === record.layer) continue;
3130
+ this.markDirty(record.entity);
3131
+ }
3132
+ }
3133
+ /**
3134
+ * Snapshots every body's authoritative pose and reports implicit-static bodies that moved.
3135
+ *
3136
+ * @param fixedDeltaSeconds - The fixed step, used to probe controller support.
3137
+ */
3138
+ #snapshot(fixedDeltaSeconds) {
3139
+ let active = 0;
3140
+ for (let index = 0; index < this.#records.length; index += 1) {
3141
+ const record = this.#records[index];
3142
+ if (record === void 0) continue;
3143
+ record.previousPosition.copyFrom(record.currentPosition);
3144
+ record.previousRotation.copyFrom(record.currentRotation);
3145
+ readNodePose(record.node, record.currentPosition, record.currentRotation);
3146
+ if (record.motion === BodyMotion.dynamic && !nearlyEqual(record.previousPosition, record.currentPosition)) active += 1;
3147
+ if (record.rigidbody === null) this.#checkStaticMove(record);
3148
+ }
3149
+ this.#activeBodies = active;
3150
+ this.#snapshotControllers(fixedDeltaSeconds);
3151
+ }
3152
+ /**
3153
+ * Reports `IGX-0901` once for an implicit static body whose transform moved.
3154
+ *
3155
+ * @param record - The body record.
3156
+ */
3157
+ #checkStaticMove(record) {
3158
+ const version = record.entity.transform.worldMatrixVersion;
3159
+ if (version === record.staticVersion || record.reportedMove) return;
3160
+ record.staticVersion = version;
3161
+ record.reportedMove = true;
3162
+ this.#ctx.log.warn(`${PhysicsErrorCode.movedStaticBody}: {entity} has colliders but no Rigidbody, and it moved after its static body was placed.`, record.entity.name);
3163
+ }
3164
+ /**
3165
+ * Reads every controller's resolved position into the entity transform and probes its support.
3166
+ *
3167
+ * @param fixedDeltaSeconds - The fixed step.
3168
+ */
3169
+ #snapshotControllers(fixedDeltaSeconds) {
3170
+ for (let index = 0; index < this.#controllers.length; index += 1) {
3171
+ const record = this.#controllers[index];
3172
+ if (record === void 0) continue;
3173
+ record.previousPosition.copyFrom(record.currentPosition);
3174
+ readControllerPosition(record.controller, record.currentPosition);
3175
+ const state = probeSupport(record.controller, fixedDeltaSeconds, this.#settings.gravity, this.#scratchVector);
3176
+ record.component.applyStepResult(supportName(state), this.#scratchVector);
3177
+ this.#writeControllerTransform(record, record.currentPosition);
3178
+ }
3179
+ }
3180
+ /**
3181
+ * Hands every controller its accumulated displacement.
3182
+ *
3183
+ * @param fixedDeltaSeconds - The fixed step, unused by `moveWithCollisions` but kept for symmetry.
3184
+ */
3185
+ #applyControllerMoves(fixedDeltaSeconds) {
3186
+ for (let index = 0; index < this.#controllers.length; index += 1) {
3187
+ const record = this.#controllers[index];
3188
+ if (record === void 0) continue;
3189
+ moveController(record.controller, record.component.takePendingMove());
3190
+ }
3191
+ }
3192
+ /**
3193
+ * Writes a controller's capsule centre back onto its entity, undoing the component's `center`.
3194
+ *
3195
+ * @param record - The controller record.
3196
+ * @param centre - The capsule centre in world space.
3197
+ */
3198
+ #writeControllerTransform(record, centre) {
3199
+ const component = record.component;
3200
+ this.#scratchOther.set(centre.x - component.center.x, centre.y - component.center.y, centre.z - component.center.z);
3201
+ component.transform.position = this.#scratchOther;
3202
+ }
3203
+ /**
3204
+ * Builds or rebuilds one controller.
3205
+ *
3206
+ * @param component - The controller component.
3207
+ */
3208
+ #rebuildController(component) {
3209
+ this.releaseController(component);
3210
+ if (component.isDestroyed || !component.isEnabledInHierarchy) return;
3211
+ const position = component.transform.position;
3212
+ const centre = new Vec3(position.x + component.center.x, position.y + component.center.y, position.z + component.center.z);
3213
+ const controller = createController(this.#world, centre, component.height, component.radius);
3214
+ tuneController(controller, Math.cos(component.slopeLimit * Math.PI / 180), component.skinWidth, component.pushStrength * DEFAULT_CHARACTER_STRENGTH);
3215
+ const record = {
3216
+ component,
3217
+ controller,
3218
+ previousPosition: centre.clone(),
3219
+ currentPosition: centre.clone(),
3220
+ interpolate: this.#settings.interpolation && component.interpolation === "interpolate",
3221
+ disconnect: () => {}
3222
+ };
3223
+ record.disconnect = onControllerPush(controller, (push) => {
3224
+ this.#reportPush(record, push);
3225
+ });
3226
+ this.#controllers.push(record);
3227
+ }
3228
+ /**
3229
+ * Turns one Lite push event into a `CharacterCollision`.
3230
+ *
3231
+ * @param record - The controller record.
3232
+ * @param push - What Lite reported.
3233
+ */
3234
+ #reportPush(record, push) {
3235
+ record.component.reportPush({
3236
+ other: this.recordOfNode(push.node)?.entity ?? null,
3237
+ impulse: push.impulse,
3238
+ point: push.point
3239
+ });
3240
+ }
3241
+ /**
3242
+ * The runtime state of a controller component.
3243
+ *
3244
+ * @param component - The component.
3245
+ * @returns The record, or `null`.
3246
+ */
3247
+ #controllerOf(component) {
3248
+ for (let index = 0; index < this.#controllers.length; index += 1) {
3249
+ const record = this.#controllers[index];
3250
+ if (record?.component === component) return record;
3251
+ }
3252
+ return null;
3253
+ }
3254
+ /**
3255
+ * Buffers a trigger event. It runs inside `stepScene`, so it only records.
3256
+ *
3257
+ * @param event - What Lite reported.
3258
+ */
3259
+ #bufferTrigger(event) {
3260
+ const slot = this.#triggerSlot(this.#triggerCount);
3261
+ slot.entered = event.entered;
3262
+ slot.first = this.recordOfNode(event.nodeA);
3263
+ slot.second = this.recordOfNode(event.nodeB);
3264
+ this.#triggerCount += 1;
3265
+ }
3266
+ /**
3267
+ * Buffers a collision event.
3268
+ *
3269
+ * @param event - What the active drain reported.
3270
+ */
3271
+ #bufferContact(event) {
3272
+ const slot = this.#contactSlot(this.#contactCount);
3273
+ slot.phase = event.phase;
3274
+ slot.point.set(event.point.x, event.point.y, event.point.z);
3275
+ slot.normal.set(event.normal.x, event.normal.y, event.normal.z);
3276
+ slot.impulse = event.impulse;
3277
+ slot.first = this.recordOfNode(event.nodeA);
3278
+ slot.second = this.recordOfNode(event.nodeB);
3279
+ this.#contactCount += 1;
3280
+ }
3281
+ /**
3282
+ * Grows the trigger pool on demand and returns one slot.
3283
+ *
3284
+ * @param index - The slot index.
3285
+ * @returns The slot.
3286
+ */
3287
+ #triggerSlot(index) {
3288
+ let slot = this.#triggerSlots[index];
3289
+ if (slot === void 0) {
3290
+ slot = {
3291
+ entered: false,
3292
+ first: null,
3293
+ second: null
3294
+ };
3295
+ this.#triggerSlots.push(slot);
3296
+ }
3297
+ return slot;
3298
+ }
3299
+ /**
3300
+ * Grows the contact pool on demand and returns one slot.
3301
+ *
3302
+ * @param index - The slot index.
3303
+ * @returns The slot.
3304
+ */
3305
+ #contactSlot(index) {
3306
+ let slot = this.#contactSlots[index];
3307
+ if (slot === void 0) {
3308
+ slot = {
3309
+ phase: 0,
3310
+ point: new Vec3(),
3311
+ normal: new Vec3(),
3312
+ impulse: 0,
3313
+ first: null,
3314
+ second: null
3315
+ };
3316
+ this.#contactSlots.push(slot);
3317
+ }
3318
+ return slot;
3319
+ }
3320
+ /** Delivers the buffered trigger events to both participants' scripts. */
3321
+ #dispatchTriggers() {
3322
+ this.#triggerEventCount += this.#triggerCount;
3323
+ for (let index = 0; index < this.#triggerCount; index += 1) {
3324
+ const slot = this.#triggerSlots[index];
3325
+ if (slot === void 0) continue;
3326
+ const kind = slot.entered ? "onTriggerEnter" : "onTriggerExit";
3327
+ this.#deliverTrigger(slot.first, slot.second, kind);
3328
+ this.#deliverTrigger(slot.second, slot.first, kind);
3329
+ }
3330
+ }
3331
+ /**
3332
+ * Delivers one trigger event to one entity.
3333
+ *
3334
+ * @param target - The record whose scripts receive it, or `null`.
3335
+ * @param other - The other participant, or `null`.
3336
+ * @param kind - Which callback to deliver.
3337
+ */
3338
+ #deliverTrigger(target, other, kind) {
3339
+ if (target === null || target.entity.isDestroyed) return;
3340
+ const event = this.#triggerEvent ??= {
3341
+ other: null,
3342
+ otherCollider: null,
3343
+ self: target.entity
3344
+ };
3345
+ event.self = target.entity;
3346
+ event.other = other?.entity ?? null;
3347
+ event.otherCollider = other?.colliders[0] ?? null;
3348
+ this.#ctx.dispatchScriptCallback(target.entity, kind, event);
3349
+ }
3350
+ /** Delivers the buffered collision events. */
3351
+ #dispatchContacts() {
3352
+ this.#collisionEventCount += this.#contactCount;
3353
+ for (let index = 0; index < this.#contactCount; index += 1) {
3354
+ const slot = this.#contactSlots[index];
3355
+ if (slot === void 0) continue;
3356
+ const kind = contactCallback(slot.phase);
3357
+ if (slot.first === null && slot.second === null) {
3358
+ this.#broadcastContact(slot, kind);
3359
+ continue;
3360
+ }
3361
+ this.#deliverContact(slot, slot.first, slot.second, kind);
3362
+ this.#deliverContact(slot, slot.second, slot.first, kind);
3363
+ }
3364
+ }
3365
+ /**
3366
+ * Delivers one collision to every entity that opted into collision events — the only thing that
3367
+ * can be done in `"upstream"` mode, where Lite reports no identities at all (`09-physics.md` §4).
3368
+ *
3369
+ * @param slot - The buffered contact.
3370
+ * @param kind - Which callback to deliver.
3371
+ */
3372
+ #broadcastContact(slot, kind) {
3373
+ for (let index = 0; index < this.#records.length; index += 1) {
3374
+ const record = this.#records[index];
3375
+ if (record !== void 0 && record.collisionEvents) this.#deliverContact(slot, record, null, kind);
3376
+ }
3377
+ }
3378
+ /**
3379
+ * Delivers one collision to one entity.
3380
+ *
3381
+ * @param slot - The buffered contact.
3382
+ * @param target - The record whose scripts receive it, or `null`.
3383
+ * @param other - The other participant, or `null`.
3384
+ * @param kind - Which callback to deliver.
3385
+ */
3386
+ #deliverContact(slot, target, other, kind) {
3387
+ if (target === null || target.entity.isDestroyed || !target.collisionEvents) return;
3388
+ this.#contactPoint.point.copyFrom(slot.point);
3389
+ this.#contactPoint.normal.copyFrom(slot.normal);
3390
+ this.#contactPoint.impulse = slot.impulse;
3391
+ const collision = this.#collision ??= {
3392
+ other: null,
3393
+ otherCollider: null,
3394
+ self: target.entity,
3395
+ contacts: this.#contacts,
3396
+ relativeVelocity: null
3397
+ };
3398
+ collision.self = target.entity;
3399
+ collision.other = other?.entity ?? null;
3400
+ collision.otherCollider = other?.colliders[0] ?? null;
3401
+ collision.relativeVelocity = other === null ? null : this.#relativeVelocityOf(target, other);
3402
+ this.#ctx.dispatchScriptCallback(target.entity, kind, collision);
3403
+ }
3404
+ /**
3405
+ * The relative velocity of two bodies at the moment of a contact.
3406
+ *
3407
+ * @param target - The receiving body.
3408
+ * @param other - The other body.
3409
+ * @returns A pooled vector.
3410
+ */
3411
+ #relativeVelocityOf(target, other) {
3412
+ readLinearVelocity(this.#world, target.body, this.#scratchVector);
3413
+ readLinearVelocity(this.#world, other.body, this.#scratchOther);
3414
+ this.#relativeVelocity.set(this.#scratchVector.x - this.#scratchOther.x, this.#scratchVector.y - this.#scratchOther.y, this.#scratchVector.z - this.#scratchOther.z);
3415
+ return this.#relativeVelocity;
3416
+ }
3417
+ /**
3418
+ * Releases one record's Lite resources and signal connections.
3419
+ *
3420
+ * @param record - The record to tear down.
3421
+ */
3422
+ #teardown(record) {
3423
+ for (const disconnect of record.disconnects) disconnect();
3424
+ record.disconnects = [];
3425
+ destroyBody(this.#world, record.body);
3426
+ for (let index = record.shapes.length - 1; index >= 0; index -= 1) {
3427
+ const shape = record.shapes[index];
3428
+ if (shape !== void 0) destroyShape(this.#world, shape);
3429
+ }
3430
+ record.shapes = [];
3431
+ }
3432
+ };
3433
+ /** Lite's own `characterStrength` default, which `pushStrength: 1` reproduces (`index.d.ts` 8320). */
3434
+ const DEFAULT_CHARACTER_STRENGTH = 1e38;
3435
+ /**
3436
+ * The colliders that make up an entity's body: every enabled `Collider` on the entity itself.
3437
+ *
3438
+ * @param entity - The entity.
3439
+ * @returns The colliders, in component order.
3440
+ */
3441
+ function collidersOf(entity) {
3442
+ const found = [];
3443
+ const components = entity.components;
3444
+ for (let index = 0; index < components.length; index += 1) {
3445
+ const component = components[index];
3446
+ if (component instanceof Collider && component.enabled && !component.isDestroyed) found.push(component);
3447
+ }
3448
+ return found;
3449
+ }
3450
+ /**
3451
+ * The motion type a `Rigidbody` asks for.
3452
+ *
3453
+ * @param rigidbody - The component, or `null` for the implicit static body.
3454
+ * @returns The Lite motion type.
3455
+ */
3456
+ function motionOf(rigidbody) {
3457
+ if (rigidbody === null || rigidbody.bodyType === "static") return BodyMotion.static;
3458
+ return rigidbody.bodyType === "kinematic" ? BodyMotion.kinematic : BodyMotion.dynamic;
3459
+ }
3460
+ /**
3461
+ * The rotation axes a `Rigidbody` freezes.
3462
+ *
3463
+ * @param rigidbody - The component.
3464
+ * @returns The locked axes, in a stable order.
3465
+ */
3466
+ function lockedAxes(rigidbody) {
3467
+ const locked = [];
3468
+ if (rigidbody.freezeRotation.x) locked.push("x");
3469
+ if (rigidbody.freezeRotation.y) locked.push("y");
3470
+ if (rigidbody.freezeRotation.z) locked.push("z");
3471
+ return locked;
3472
+ }
3473
+ /**
3474
+ * The membership mask of a layer (`09-physics.md` §3).
3475
+ *
3476
+ * @param layer - The layer index.
3477
+ * @returns `1 << layer`.
3478
+ */
3479
+ function membershipOf(layer) {
3480
+ return 1 << layer;
3481
+ }
3482
+ /**
3483
+ * The half-extents of the union of an entity's colliders, for the bounds index.
3484
+ *
3485
+ * @param colliders - The colliders.
3486
+ * @param scale - The entity's lossy scale.
3487
+ * @returns A fresh vector.
3488
+ */
3489
+ function boundsOf(colliders, scale) {
3490
+ const bounds = new Vec3();
3491
+ const scratch = new Vec3();
3492
+ for (let index = 0; index < colliders.length; index += 1) {
3493
+ const collider = colliders[index];
3494
+ if (collider === void 0) continue;
3495
+ collider.halfExtentsToRef(scale, scratch);
3496
+ bounds.set(Math.max(bounds.x, Math.abs(collider.center.x * scale.x) + scratch.x), Math.max(bounds.y, Math.abs(collider.center.y * scale.y) + scratch.y), Math.max(bounds.z, Math.abs(collider.center.z * scale.z) + scratch.z));
3497
+ }
3498
+ return bounds;
3499
+ }
3500
+ /**
3501
+ * Which callback a contact phase maps to.
3502
+ *
3503
+ * @param phase - `0` started, `1` continued, `2` finished.
3504
+ * @returns The callback name.
3505
+ */
3506
+ function contactCallback(phase) {
3507
+ if (phase === 0) return "onCollisionEnter";
3508
+ return phase === 2 ? "onCollisionExit" : "onCollisionStay";
3509
+ }
3510
+ /**
3511
+ * The name of a Lite support state.
3512
+ *
3513
+ * @param state - Lite's value.
3514
+ * @returns The ignifx name.
3515
+ */
3516
+ function supportName(state) {
3517
+ if (state === SupportState.supported) return "supported";
3518
+ return state === SupportState.sliding ? "sliding" : "unsupported";
3519
+ }
3520
+ /**
3521
+ * Whether two positions are the same to within the static-move epsilon.
3522
+ *
3523
+ * @param first - The first position.
3524
+ * @param second - The second position.
3525
+ * @returns `true` when they match.
3526
+ */
3527
+ function nearlyEqual(first, second) {
3528
+ return Math.abs(first.x - second.x) < STATIC_MOVE_EPSILON && Math.abs(first.y - second.y) < STATIC_MOVE_EPSILON && Math.abs(first.z - second.z) < STATIC_MOVE_EPSILON;
3529
+ }
3530
+ /**
3531
+ * A monotonic millisecond reading for the `stepMs` counter. It never feeds the simulation, so it
3532
+ * does not break the "no wall-clock reads" rule of `09-physics.md` §8.
3533
+ *
3534
+ * @returns Milliseconds since the process started.
3535
+ */
3536
+ function now() {
3537
+ return performance.now();
3538
+ }
3539
+ /**
3540
+ * Builds the "that is not a layer" failure.
3541
+ *
3542
+ * @param name - The offending layer name.
3543
+ * @returns The error to throw.
3544
+ */
3545
+ function unknownLayer(name) {
3546
+ return physicsError(PhysicsErrorCode.unknownLayer, `${name} is not a layer this project declares.`, {
3547
+ context: { layer: name },
3548
+ hint: "Add the layer to the layers settings section, or fix the name in physics.collisionMatrix."
3549
+ });
3550
+ }
3551
+ //#endregion
3552
+ //#region src/runtime/systems.ts
3553
+ /**
3554
+ * The three systems `docs/architecture/01-lifecycle-and-time.md` §3 step 4 and `09-physics.md` §1
3555
+ * put physics in the frame with:
3556
+ *
3557
+ * ```
3558
+ * Systems(FixedUpdate, -100) restore the authoritative pose of interpolated bodies
3559
+ * scripts.fixedUpdate(dt) forces, velocities, CharacterController.move()
3560
+ * Systems(FixedUpdate, 100) step Havok, snapshot poses, dispatch collision and trigger events
3561
+ * Systems(PreRender, -500) write lerp(prev, cur, time.fixedStepAlpha)
3562
+ * ```
3563
+ *
3564
+ * Everything here is `@internal`.
3565
+ */
3566
+ /** The `FixedUpdate` order the restore system runs at. */
3567
+ const PHYSICS_RESTORE_ORDER = -100;
3568
+ /** The `PreRender` order the interpolation system runs at. */
3569
+ const PHYSICS_INTERPOLATE_ORDER = -500;
3570
+ /**
3571
+ * Undoes the display pose the interpolation system wrote, so `fixedUpdate` and Havok both see the
3572
+ * authoritative pose (spike S4.3).
3573
+ *
3574
+ * @internal
3575
+ */
3576
+ var PhysicsRestoreSystem = class {
3577
+ /** The name diagnostics and error reports use. */
3578
+ name = "physics-restore";
3579
+ #host;
3580
+ /**
3581
+ * Binds the system to the runtime holder.
3582
+ *
3583
+ * @param host - The holder the runtime lands in.
3584
+ */
3585
+ constructor(host) {
3586
+ this.#host = host;
3587
+ }
3588
+ /** Restores every interpolated body's authoritative pose. */
3589
+ update() {
3590
+ this.#host.runtime?.restorePoses();
3591
+ }
3592
+ };
3593
+ /**
3594
+ * Steps Havok once, snapshots the poses, and dispatches the step's events.
3595
+ *
3596
+ * @internal
3597
+ */
3598
+ var PhysicsStepSystem = class {
3599
+ /** The name diagnostics and error reports use. */
3600
+ name = "physics-step";
3601
+ #host;
3602
+ /**
3603
+ * Binds the system to the runtime holder.
3604
+ *
3605
+ * @param host - The holder the runtime lands in.
3606
+ */
3607
+ constructor(host) {
3608
+ this.#host = host;
3609
+ }
3610
+ /**
3611
+ * Runs one fixed step.
3612
+ *
3613
+ * @param ctx - The world, clock, phase, and fixed delta.
3614
+ */
3615
+ update(ctx) {
3616
+ this.#host.runtime?.step(ctx.dt);
3617
+ }
3618
+ };
3619
+ /**
3620
+ * Writes the interpolated display pose once per frame.
3621
+ *
3622
+ * @internal
3623
+ */
3624
+ var PhysicsInterpolationSystem = class {
3625
+ /** The name diagnostics and error reports use. */
3626
+ name = "physics-interpolate";
3627
+ #host;
3628
+ /**
3629
+ * Binds the system to the runtime holder.
3630
+ *
3631
+ * @param host - The holder the runtime lands in.
3632
+ */
3633
+ constructor(host) {
3634
+ this.#host = host;
3635
+ }
3636
+ /**
3637
+ * Writes `lerp(prev, cur, alpha)` into every interpolated body's node.
3638
+ *
3639
+ * @param ctx - The world, clock, phase, and frame delta.
3640
+ */
3641
+ update(ctx) {
3642
+ this.#host.runtime?.interpolate(ctx.time.fixedStepAlpha);
3643
+ }
3644
+ };
3645
+ //#endregion
3646
+ //#region src/lite/gpu/viewer.ts
3647
+ /**
3648
+ * Creates a viewer on the render scene.
3649
+ *
3650
+ * @param scene - The render scene the wireframes are drawn into.
3651
+ * @param world - The Havok world being visualised.
3652
+ * @returns The viewer handle.
3653
+ *
3654
+ * @internal
3655
+ */
3656
+ function createViewer(scene, world) {
3657
+ return createPhysicsViewer(scene, world);
3658
+ }
3659
+ /**
3660
+ * Starts drawing one body.
3661
+ *
3662
+ * @param viewer - The viewer.
3663
+ * @param body - The body to show.
3664
+ *
3665
+ * @internal
3666
+ */
3667
+ function showBody(viewer, body) {
3668
+ showPhysicsBody(viewer, body);
3669
+ }
3670
+ /**
3671
+ * Disposes every debug mesh and unregisters the viewer's update hook.
3672
+ *
3673
+ * @param viewer - The viewer.
3674
+ *
3675
+ * @internal
3676
+ */
3677
+ function destroyViewer(viewer) {
3678
+ disposePhysicsViewer(viewer);
3679
+ }
3680
+ //#endregion
3681
+ //#region src/lite/queries.ts
3682
+ /**
3683
+ * Casts a ray and writes the contact into out parameters (coding standards §7: no allocation on a
3684
+ * query path beyond Lite's own result object).
3685
+ *
3686
+ * @param world - The world handle.
3687
+ * @param from - The world-space origin.
3688
+ * @param to - The world-space end point.
3689
+ * @param membership - The querying mask; `~0` for "belongs to everything".
3690
+ * @param collideWith - The mask of layers the ray may hit.
3691
+ * @param hitTriggers - Whether trigger volumes count as hits.
3692
+ * @param point - Written with the contact point.
3693
+ * @param normal - Written with the contact normal.
3694
+ * @param out - Written with the hit flag, node, distance, and triangle index.
3695
+ *
3696
+ * @internal
3697
+ */
3698
+ function castRay(world, from, to, membership, collideWith, hitTriggers, point, normal, out) {
3699
+ const result = physicsRaycast(world, {
3700
+ x: from.x,
3701
+ y: from.y,
3702
+ z: from.z
3703
+ }, {
3704
+ x: to.x,
3705
+ y: to.y,
3706
+ z: to.z
3707
+ }, {
3708
+ membership,
3709
+ collideWith,
3710
+ shouldHitTriggers: hitTriggers
3711
+ });
3712
+ out.hit = result.hasHit;
3713
+ out.node = bodyNodeOf(result.body);
3714
+ out.distance = result.hitDistance;
3715
+ out.triangleIndex = result.triangleIndex;
3716
+ point.set(result.hitPoint.x, result.hitPoint.y, result.hitPoint.z);
3717
+ normal.set(result.hitNormal.x, result.hitNormal.y, result.hitNormal.z);
3718
+ }
3719
+ /**
3720
+ * Sweeps a shape from one position to another.
3721
+ *
3722
+ * @param world - The world handle.
3723
+ * @param shape - The shape to sweep.
3724
+ * @param rotation - The orientation held constant during the sweep.
3725
+ * @param from - The start position.
3726
+ * @param to - The end position.
3727
+ * @param hitTriggers - Whether trigger volumes count as hits.
3728
+ * @param point - Written with the contact point on the hit body.
3729
+ * @param normal - Written with the contact normal on the hit body.
3730
+ * @param out - Written with the hit flag and the sweep fraction.
3731
+ *
3732
+ * @internal
3733
+ */
3734
+ function sweepShape(world, shape, rotation, from, to, hitTriggers, point, normal, out) {
3735
+ const result = shapeCast(world, {
3736
+ shape,
3737
+ rotation: {
3738
+ x: rotation.x,
3739
+ y: rotation.y,
3740
+ z: rotation.z,
3741
+ w: rotation.w
3742
+ },
3743
+ startPosition: {
3744
+ x: from.x,
3745
+ y: from.y,
3746
+ z: from.z
3747
+ },
3748
+ endPosition: {
3749
+ x: to.x,
3750
+ y: to.y,
3751
+ z: to.z
3752
+ },
3753
+ shouldHitTriggers: hitTriggers
3754
+ });
3755
+ out.hit = result.hasHit;
3756
+ out.fraction = result.fraction;
3757
+ point.set(result.hitPoint.x, result.hitPoint.y, result.hitPoint.z);
3758
+ normal.set(result.hitNormal.x, result.hitNormal.y, result.hitNormal.z);
3759
+ }
3760
+ /**
3761
+ * Finds the distance from a positioned shape to the nearest body, which is what Lite's
3762
+ * `shapeProximity` reports. It is used as a cheap "is anything in range at all" test; the entities
3763
+ * themselves come from the service's own body index.
3764
+ *
3765
+ * @param world - The world handle.
3766
+ * @param shape - The query shape.
3767
+ * @param position - Its world position.
3768
+ * @param rotation - Its world rotation.
3769
+ * @param maxDistance - How far to search.
3770
+ * @param hitTriggers - Whether trigger volumes count.
3771
+ * @returns The distance to the nearest body, or `Number.POSITIVE_INFINITY` when nothing is in range.
3772
+ *
3773
+ * @internal
3774
+ */
3775
+ function nearestDistance(world, shape, position, rotation, maxDistance, hitTriggers) {
3776
+ const result = shapeProximity(world, {
3777
+ shape,
3778
+ position: {
3779
+ x: position.x,
3780
+ y: position.y,
3781
+ z: position.z
3782
+ },
3783
+ rotation: {
3784
+ x: rotation.x,
3785
+ y: rotation.y,
3786
+ z: rotation.z,
3787
+ w: rotation.w
3788
+ },
3789
+ maxDistance,
3790
+ shouldHitTriggers: hitTriggers
3791
+ });
3792
+ return result.hasHit ? result.distance : Number.POSITIVE_INFINITY;
3793
+ }
3794
+ /**
3795
+ * Reads the node off an optional body handle.
3796
+ *
3797
+ * @param body - The body Lite reported, or `null`.
3798
+ * @returns The node, or `null`.
3799
+ */
3800
+ function bodyNodeOf(body) {
3801
+ return body === null ? null : body.node;
3802
+ }
3803
+ //#endregion
3804
+ //#region src/service.ts
3805
+ /**
3806
+ * `app.physics` (`docs/architecture/09-physics.md` §5, §6, §9): gravity, the queries, the debug
3807
+ * viewer, and the Babylon Lite escape hatch.
3808
+ */
3809
+ /** How far a ray travels when the caller names no distance, in metres. */
3810
+ const DEFAULT_RAY_DISTANCE = 1e4;
3811
+ /** How much slack the bounds index allows when it resolves a sweep contact to an entity. */
3812
+ const BOUNDS_EPSILON = .001;
3813
+ /** Every bit set: the mask a query uses when the caller names no layers. */
3814
+ const ALL_LAYERS = -1;
3815
+ /**
3816
+ * The service behind `app.physics`.
3817
+ *
3818
+ * @example
3819
+ * ```ts
3820
+ * const hit = app.physics.raycast({ x: 0, y: 10, z: 0 }, { x: 0, y: -1, z: 0 }, 20);
3821
+ * if (hit !== null) {
3822
+ * app.log.info("ray hit {name} at {y}", hit.entity.name, hit.point.y);
3823
+ * }
3824
+ * ```
3825
+ *
3826
+ * @public
3827
+ */
3828
+ var PhysicsService = class {
3829
+ #app;
3830
+ #host;
3831
+ #gravity = new Vec3();
3832
+ #rayResult = {
3833
+ hit: false,
3834
+ node: null,
3835
+ distance: 0,
3836
+ triangleIndex: -1
3837
+ };
3838
+ #sweepResult = {
3839
+ hit: false,
3840
+ fraction: 0
3841
+ };
3842
+ #point = new Vec3();
3843
+ #normal = new Vec3();
3844
+ #overlapExtents = new Vec3();
3845
+ #overlapResults = [];
3846
+ #debugViewer;
3847
+ #viewer = null;
3848
+ /**
3849
+ * Wraps the holder the extension fills in from `onStart`.
3850
+ *
3851
+ * @param app - The app the service belongs to.
3852
+ * @param host - The holder the runtime lands in.
3853
+ * @param settings - The resolved `physics` settings section.
3854
+ *
3855
+ * @internal
3856
+ */
3857
+ constructor(app, host, settings) {
3858
+ this.#app = app;
3859
+ this.#host = host;
3860
+ const gravity = settings.gravity;
3861
+ this.#gravity.set(gravity.x, gravity.y, gravity.z);
3862
+ this.#debugViewer = new DebugViewerToggle(this);
3863
+ }
3864
+ /**
3865
+ * World gravity in metres per second squared.
3866
+ *
3867
+ * @returns A live view; writing to it does nothing, assign the property instead.
3868
+ */
3869
+ get gravity() {
3870
+ return this.#gravity;
3871
+ }
3872
+ /**
3873
+ * Replaces world gravity, which every body feels from the next fixed step.
3874
+ *
3875
+ * @param value - The new acceleration vector, in metres per second squared.
3876
+ */
3877
+ set gravity(value) {
3878
+ this.#gravity.set(value.x, value.y, value.z);
3879
+ this.#rt().setGravity(this.#gravity);
3880
+ }
3881
+ /**
3882
+ * The wireframe overlay.
3883
+ *
3884
+ * @returns The viewer toggle.
3885
+ */
3886
+ get debugViewer() {
3887
+ return this.#debugViewer;
3888
+ }
3889
+ /**
3890
+ * The Babylon Lite handles.
3891
+ *
3892
+ * @returns The Havok world and the simulation scene.
3893
+ */
3894
+ get lite() {
3895
+ return {
3896
+ world: this.#rt().world,
3897
+ simulationScene: this.#app.world.lite.simulationScene ?? this.#app.lite.scene
3898
+ };
3899
+ }
3900
+ /**
3901
+ * Casts a ray and returns the first entity it hits (`09-physics.md` §5).
3902
+ *
3903
+ * @param origin - The world-space origin.
3904
+ * @param direction - The direction; it is normalised for you.
3905
+ * @param maxDistance - How far to travel; defaults to 10 km.
3906
+ * @param options - Layer mask and trigger behaviour.
3907
+ * @returns The hit, or `null` when the ray clears everything.
3908
+ * @throws IgnifxError with code `IGX-0902` in development when no fixed step has run yet.
3909
+ */
3910
+ raycast(origin, direction, maxDistance = DEFAULT_RAY_DISTANCE, options) {
3911
+ this.#requireStep("raycast");
3912
+ this.#rt().countQuery();
3913
+ const length = Math.hypot(direction.x, direction.y, direction.z);
3914
+ if (length === 0) return null;
3915
+ const scale = maxDistance / length;
3916
+ const to = {
3917
+ x: origin.x + direction.x * scale,
3918
+ y: origin.y + direction.y * scale,
3919
+ z: origin.z + direction.z * scale
3920
+ };
3921
+ castRay(this.#rt().world, origin, to, ALL_LAYERS, maskOf(options), options?.hitTriggers === true, this.#point, this.#normal, this.#rayResult);
3922
+ if (!this.#rayResult.hit) return null;
3923
+ const record = this.#rt().recordOfNode(this.#rayResult.node);
3924
+ if (record === null) return null;
3925
+ return {
3926
+ entity: record.entity,
3927
+ collider: record.colliders[0] ?? null,
3928
+ point: this.#point.clone(),
3929
+ normal: this.#normal.clone(),
3930
+ distance: this.#rayResult.distance,
3931
+ triangleIndex: this.#rayResult.triangleIndex
3932
+ };
3933
+ }
3934
+ /**
3935
+ * Sweeps a shape and returns the first contact (`09-physics.md` §5).
3936
+ *
3937
+ * @remarks
3938
+ * Lite's `shapeCast` reports no body (`index.d.ts` 11497), so `entity` is resolved against the
3939
+ * extension's body-bounds index and is bounds-accurate rather than shape-accurate.
3940
+ *
3941
+ * @param shape - The shape to sweep.
3942
+ * @param from - The start position.
3943
+ * @param to - The end position.
3944
+ * @param options - Layer mask and trigger behaviour.
3945
+ * @returns The hit, or `null`.
3946
+ * @throws IgnifxError with code `IGX-0902` in development when no fixed step has run yet.
3947
+ */
3948
+ shapeCast(shape, from, to, options) {
3949
+ this.#requireStep("shapeCast");
3950
+ this.#rt().countQuery();
3951
+ const handle = this.#buildQueryShape(shape);
3952
+ try {
3953
+ sweepShape(this.#rt().world, handle, Quat.identity(), from, to, options?.hitTriggers === true, this.#point, this.#normal, this.#sweepResult);
3954
+ } finally {
3955
+ destroyShape(this.#rt().world, handle);
3956
+ }
3957
+ if (!this.#sweepResult.hit) return null;
3958
+ const record = this.#recordAt(this.#point, options);
3959
+ const distance = Math.hypot(to.x - from.x, to.y - from.y, to.z - from.z) * this.#sweepResult.fraction;
3960
+ return {
3961
+ entity: record?.entity ?? null,
3962
+ collider: record?.colliders[0] ?? null,
3963
+ point: this.#point.clone(),
3964
+ normal: this.#normal.clone(),
3965
+ fraction: this.#sweepResult.fraction,
3966
+ distance
3967
+ };
3968
+ }
3969
+ /**
3970
+ * Lists the entities a positioned shape overlaps (`09-physics.md` §5).
3971
+ *
3972
+ * @remarks
3973
+ * Lite's `shapeProximity` reports one hit and no identity (`index.d.ts` 11540,
3974
+ * `lib/physics/havok-queries.js:7`), so this is answered from the extension's own bounds index:
3975
+ * every registered body whose world bounding box intersects the query shape's. It is conservative
3976
+ * — a body whose box overlaps but whose shape does not is listed.
3977
+ *
3978
+ * @param shape - The query shape.
3979
+ * @param position - Its world position.
3980
+ * @param rotation - Its world rotation; accepted for forward compatibility and currently unused,
3981
+ * because the bounds test is axis-aligned.
3982
+ * @param options - Layer mask and trigger behaviour.
3983
+ * @returns The overlapping entities, in body creation order. The array is reused between calls.
3984
+ * @throws IgnifxError with code `IGX-0902` in development when no fixed step has run yet.
3985
+ */
3986
+ overlap(shape, position, rotation, options) {
3987
+ this.#requireStep("overlap");
3988
+ this.#rt().countQuery();
3989
+ queryHalfExtents(shape, this.#overlapExtents);
3990
+ this.#overlapResults.length = 0;
3991
+ const records = this.#rt().records;
3992
+ for (let index = 0; index < records.length; index += 1) {
3993
+ const record = records[index];
3994
+ if (record === void 0 || !this.#accepts(record, options)) continue;
3995
+ if (boxesOverlap(position, this.#overlapExtents, record.currentPosition, record.halfExtents)) this.#overlapResults.push(record.entity);
3996
+ }
3997
+ return this.#overlapResults;
3998
+ }
3999
+ /**
4000
+ * How far the nearest body is from a positioned shape, which is the one thing Lite's
4001
+ * `shapeProximity` answers exactly.
4002
+ *
4003
+ * @param shape - The query shape.
4004
+ * @param position - Its world position.
4005
+ * @param maxDistance - How far to search.
4006
+ * @param options - Trigger behaviour.
4007
+ * @returns The distance, or `Number.POSITIVE_INFINITY` when nothing is in range.
4008
+ * @throws IgnifxError with code `IGX-0902` in development when no fixed step has run yet.
4009
+ */
4010
+ distanceToNearest(shape, position, maxDistance, options) {
4011
+ this.#requireStep("distanceToNearest");
4012
+ this.#rt().countQuery();
4013
+ const handle = this.#buildQueryShape(shape);
4014
+ try {
4015
+ return nearestDistance(this.#rt().world, handle, position, Quat.identity(), maxDistance, options?.hitTriggers === true);
4016
+ } finally {
4017
+ destroyShape(this.#rt().world, handle);
4018
+ }
4019
+ }
4020
+ /**
4021
+ * Shows or hides Lite's wireframe bodies.
4022
+ *
4023
+ * @param enabled - Whether the viewer draws.
4024
+ */
4025
+ setDebugViewerEnabled(enabled) {
4026
+ if (enabled === (this.#viewer !== null) || enabled && this.#host.runtime === null) return;
4027
+ if (!enabled) {
4028
+ if (this.#viewer !== null) {
4029
+ destroyViewer(this.#viewer);
4030
+ this.#viewer = null;
4031
+ }
4032
+ return;
4033
+ }
4034
+ if (this.#app.isHeadless) {
4035
+ this.#app.log.warn("The physics debug viewer needs a GPU device; a headless app has none.");
4036
+ return;
4037
+ }
4038
+ const viewer = createViewer(this.#app.lite.scene, this.#rt().world);
4039
+ this.#viewer = viewer;
4040
+ const records = this.#rt().records;
4041
+ for (let index = 0; index < records.length; index += 1) {
4042
+ const record = records[index];
4043
+ if (record !== void 0) showBody(viewer, record.body);
4044
+ }
4045
+ }
4046
+ /**
4047
+ * Whether the viewer is currently drawing.
4048
+ *
4049
+ * @returns `true` when a viewer exists.
4050
+ */
4051
+ isDebugViewerEnabled() {
4052
+ return this.#viewer !== null;
4053
+ }
4054
+ /** Releases the viewer, if one is up. Called from the extension's `dispose`. */
4055
+ dispose() {
4056
+ this.setDebugViewerEnabled(false);
4057
+ }
4058
+ /**
4059
+ * The runtime, once `onStart` has built it.
4060
+ *
4061
+ * @returns The runtime.
4062
+ * @throws IgnifxError with code `IGX-0903` when Havok has not finished loading, which is only
4063
+ * reachable from an extension `onStart` that runs before this one.
4064
+ */
4065
+ #rt() {
4066
+ const runtime = this.#host.runtime;
4067
+ if (runtime === null) throw physicsError(PhysicsErrorCode.havokUnavailable, "The physics world does not exist yet.", { hint: "app.physics is usable from the first frame onwards; await app.start() first." });
4068
+ return runtime;
4069
+ }
4070
+ /**
4071
+ * Refuses a query that ran before Havok built its broadphase (`09-physics.md` §5).
4072
+ *
4073
+ * @param query - The query name, for the diagnostic.
4074
+ * @throws IgnifxError with code `IGX-0902` when no step has completed.
4075
+ */
4076
+ #requireStep(query) {
4077
+ if (this.#rt().hasStepped) return;
4078
+ throw physicsError(PhysicsErrorCode.queryBeforeStep, `${query}() ran before the first fixed step.`, {
4079
+ context: { query },
4080
+ hint: "Step the app at least once (app.step(1 / 60)) before querying; Havok builds its broadphase in the first step."
4081
+ });
4082
+ }
4083
+ /**
4084
+ * Builds a temporary Havok shape for one query. Query shapes are not a per-frame path, so the
4085
+ * allocation is deliberate and the shape is released in a `finally`.
4086
+ *
4087
+ * @param shape - The description.
4088
+ * @returns The shape handle.
4089
+ */
4090
+ #buildQueryShape(shape) {
4091
+ const world = this.#rt().world;
4092
+ if (shape.kind === "sphere") return createShape(world, ShapeGeometry.sphere, { radius: shape.radius });
4093
+ if (shape.kind === "box") return createShape(world, ShapeGeometry.box, {
4094
+ extents: shape.size,
4095
+ center: {
4096
+ x: 0,
4097
+ y: 0,
4098
+ z: 0
4099
+ },
4100
+ rotation: Quat.identity()
4101
+ });
4102
+ const half = Math.max(0, shape.height / 2 - shape.radius);
4103
+ return createShape(world, ShapeGeometry.capsule, {
4104
+ radius: shape.radius,
4105
+ pointA: {
4106
+ x: 0,
4107
+ y: -half,
4108
+ z: 0
4109
+ },
4110
+ pointB: {
4111
+ x: 0,
4112
+ y: half,
4113
+ z: 0
4114
+ }
4115
+ });
4116
+ }
4117
+ /**
4118
+ * Resolves a world-space point to the body whose bounds contain it.
4119
+ *
4120
+ * @param point - The point.
4121
+ * @param options - Layer mask and trigger behaviour.
4122
+ * @returns The record, or `null`.
4123
+ */
4124
+ #recordAt(point, options) {
4125
+ const records = this.#rt().records;
4126
+ let best = null;
4127
+ let bestDistance = Number.POSITIVE_INFINITY;
4128
+ for (let index = 0; index < records.length; index += 1) {
4129
+ const record = records[index];
4130
+ if (record === void 0 || !this.#accepts(record, options)) continue;
4131
+ const centre = record.currentPosition;
4132
+ const extents = record.halfExtents;
4133
+ if (Math.abs(point.x - centre.x) > extents.x + BOUNDS_EPSILON || Math.abs(point.y - centre.y) > extents.y + BOUNDS_EPSILON || Math.abs(point.z - centre.z) > extents.z + BOUNDS_EPSILON) continue;
4134
+ const distance = Math.hypot(point.x - centre.x, point.y - centre.y, point.z - centre.z);
4135
+ if (distance < bestDistance) {
4136
+ bestDistance = distance;
4137
+ best = record;
4138
+ }
4139
+ }
4140
+ return best;
4141
+ }
4142
+ /**
4143
+ * Whether a body passes a query's layer and trigger filters.
4144
+ *
4145
+ * @param record - The body.
4146
+ * @param options - The query options.
4147
+ * @returns `true` when the body may be reported.
4148
+ */
4149
+ #accepts(record, options) {
4150
+ if ((maskOf(options) & 1 << record.layer) === 0) return false;
4151
+ return options?.hitTriggers === true || !allTriggers(record.colliders);
4152
+ }
4153
+ };
4154
+ /**
4155
+ * The `{ enabled }` object `app.physics.debugViewer` hands out: a property pair rather than two
4156
+ * methods, because that is how `09-physics.md` §9 and `@ignifx/devtools` name it.
4157
+ */
4158
+ var DebugViewerToggle = class {
4159
+ #service;
4160
+ /**
4161
+ * Binds the toggle to its service.
4162
+ *
4163
+ * @param service - The service that owns the viewer.
4164
+ */
4165
+ constructor(service) {
4166
+ this.#service = service;
4167
+ }
4168
+ /**
4169
+ * Whether the viewer is drawing.
4170
+ *
4171
+ * @returns `true` when a viewer is up.
4172
+ */
4173
+ get enabled() {
4174
+ return this.#service.isDebugViewerEnabled();
4175
+ }
4176
+ set enabled(value) {
4177
+ this.#service.setDebugViewerEnabled(value);
4178
+ }
4179
+ };
4180
+ /**
4181
+ * The 32-bit layer mask a query filters with.
4182
+ *
4183
+ * @param options - The query options.
4184
+ * @returns The mask; every bit when the caller named none.
4185
+ */
4186
+ function maskOf(options) {
4187
+ return options?.layerMask?.bits ?? ALL_LAYERS;
4188
+ }
4189
+ /**
4190
+ * Whether every collider of a body is a trigger, which is what makes the body a trigger volume.
4191
+ *
4192
+ * @param colliders - The body's colliders.
4193
+ * @returns `true` when they are all triggers.
4194
+ */
4195
+ function allTriggers(colliders) {
4196
+ if (colliders.length === 0) return false;
4197
+ for (let index = 0; index < colliders.length; index += 1) if (colliders[index]?.isTrigger !== true) return false;
4198
+ return true;
4199
+ }
4200
+ /**
4201
+ * The half-extents of a query shape's bounding box.
4202
+ *
4203
+ * @param shape - The description.
4204
+ * @param out - The vector to write.
4205
+ */
4206
+ function queryHalfExtents(shape, out) {
4207
+ if (shape.kind === "sphere") {
4208
+ out.set(shape.radius, shape.radius, shape.radius);
4209
+ return;
4210
+ }
4211
+ if (shape.kind === "box") {
4212
+ out.set(shape.size.x / 2, shape.size.y / 2, shape.size.z / 2);
4213
+ return;
4214
+ }
4215
+ out.set(shape.radius, Math.max(shape.radius, shape.height / 2), shape.radius);
4216
+ }
4217
+ /**
4218
+ * Whether two axis-aligned boxes overlap.
4219
+ *
4220
+ * @param firstCentre - The first box's centre.
4221
+ * @param firstExtents - The first box's half-extents.
4222
+ * @param secondCentre - The second box's centre.
4223
+ * @param secondExtents - The second box's half-extents.
4224
+ * @returns `true` when they intersect.
4225
+ */
4226
+ function boxesOverlap(firstCentre, firstExtents, secondCentre, secondExtents) {
4227
+ return Math.abs(firstCentre.x - secondCentre.x) <= firstExtents.x + secondExtents.x && Math.abs(firstCentre.y - secondCentre.y) <= firstExtents.y + secondExtents.y && Math.abs(firstCentre.z - secondCentre.z) <= firstExtents.z + secondExtents.z;
4228
+ }
4229
+ //#endregion
4230
+ //#region src/settings.ts
4231
+ /**
4232
+ * The `physics` project settings section (`docs/architecture/09-physics.md` §6). `fixedDeltaTime` is
4233
+ * **not** here: the fixed step is shared with the core `time` section, and the extension reads it
4234
+ * from `app.time.fixedDeltaTime` on every step so a game that changes it at runtime keeps Lite's
4235
+ * per-step delta in sync.
4236
+ */
4237
+ /**
4238
+ * The section name as it appears in `ignifx.config.ts`.
4239
+ *
4240
+ * @public
4241
+ */
4242
+ const PHYSICS_SETTINGS_SECTION = "physics";
4243
+ /**
4244
+ * The value {@link PhysicsSettings.havokWasm} carries when the address comes from the manifest.
4245
+ *
4246
+ * @public
4247
+ */
4248
+ const HAVOK_WASM_AUTO = "auto";
4249
+ /** Standard gravity, matching Lite's own Havok default. */
4250
+ const DEFAULT_GRAVITY = Object.freeze({
4251
+ x: 0,
4252
+ y: -9.81,
4253
+ z: 0
4254
+ });
4255
+ /** The default surface: ordinary friction, no bounce. */
4256
+ const DEFAULT_MATERIAL = Object.freeze({
4257
+ friction: .6,
4258
+ staticFriction: .6,
4259
+ restitution: 0
4260
+ });
4261
+ /** No clamps beyond Havok's own. */
4262
+ const DEFAULT_VELOCITY_LIMITS = Object.freeze({
4263
+ linear: 0,
4264
+ angular: 0
4265
+ });
4266
+ /** An empty matrix, which means "everything collides with everything". */
4267
+ const DEFAULT_COLLISION_MATRIX = Object.freeze({});
4268
+ /**
4269
+ * Builds the schema the `physics` section is validated against.
4270
+ *
4271
+ * @remarks
4272
+ * It is a function, not a module-level constant: every field kind is a function call, and module
4273
+ * scope holds declarations and immutable constants only (`CONSTITUTION.md` §3.5).
4274
+ *
4275
+ * @returns The schema.
4276
+ *
4277
+ * @public
4278
+ */
4279
+ function physicsSettingsSchema() {
4280
+ return defineSchema({
4281
+ gravity: vec3(DEFAULT_GRAVITY),
4282
+ collisionMatrix: map(array(str())),
4283
+ defaultMaterial: record({
4284
+ friction: f32(DEFAULT_MATERIAL.friction, { min: 0 }),
4285
+ staticFriction: f32(DEFAULT_MATERIAL.staticFriction, { min: 0 }),
4286
+ restitution: f32(DEFAULT_MATERIAL.restitution, {
4287
+ min: 0,
4288
+ max: 1
4289
+ })
4290
+ }),
4291
+ velocityLimits: record({
4292
+ linear: f32(DEFAULT_VELOCITY_LIMITS.linear, { min: 0 }),
4293
+ angular: f32(DEFAULT_VELOCITY_LIMITS.angular, { min: 0 })
4294
+ }),
4295
+ interpolation: bool(true),
4296
+ havokWasm: str(HAVOK_WASM_AUTO)
4297
+ });
4298
+ }
4299
+ /**
4300
+ * The values used when a project omits the `physics` section.
4301
+ *
4302
+ * @returns A fresh defaults object.
4303
+ *
4304
+ * @public
4305
+ */
4306
+ function defaultPhysicsSettings() {
4307
+ return {
4308
+ gravity: DEFAULT_GRAVITY,
4309
+ collisionMatrix: DEFAULT_COLLISION_MATRIX,
4310
+ defaultMaterial: DEFAULT_MATERIAL,
4311
+ velocityLimits: DEFAULT_VELOCITY_LIMITS,
4312
+ interpolation: true,
4313
+ havokWasm: HAVOK_WASM_AUTO
4314
+ };
4315
+ }
4316
+ //#endregion
4317
+ //#region src/extension.ts
4318
+ /**
4319
+ * Builds the physics extension.
4320
+ *
4321
+ * @param options - The collision-identity mode and, optionally, where Havok comes from.
4322
+ * @returns The extension descriptor.
4323
+ *
4324
+ * @example
4325
+ * ```ts
4326
+ * const app = await createApp({ headless: true, extensions: [physics()] });
4327
+ * ```
4328
+ *
4329
+ * @public
4330
+ */
4331
+ const physics = defineExtension((options = {}) => {
4332
+ const host = new PhysicsHost();
4333
+ let context = null;
4334
+ let service = null;
4335
+ return {
4336
+ name: "@ignifx/physics",
4337
+ version: "0.0.0",
4338
+ engine: ">=0.0.0 <1.0.0",
4339
+ requires: [],
4340
+ optional: ["@ignifx/devtools"],
4341
+ register(ctx) {
4342
+ context = ctx;
4343
+ ctx.registerErrorCodes(PHYSICS_ERROR_MESSAGES);
4344
+ ctx.registerSettings(PHYSICS_SETTINGS_SECTION, physicsSettingsSchema(), defaultPhysicsSettings());
4345
+ ctx.registerComponents(PHYSICS_COMPONENTS);
4346
+ ctx.registerAssetLoader(createPhysicsMaterialLoader());
4347
+ const settings = ctx.settings(PHYSICS_SETTINGS_SECTION);
4348
+ service = new PhysicsService(ctx.app, host, settings);
4349
+ ctx.registerService(PhysicsHostKey, host);
4350
+ ctx.registerService(PhysicsService, service);
4351
+ ctx.defineAppProperty("physics", () => service);
4352
+ ctx.registerSystem(new PhysicsRestoreSystem(host), {
4353
+ phase: Phase.FixedUpdate,
4354
+ order: PHYSICS_RESTORE_ORDER
4355
+ });
4356
+ ctx.registerSystem(new PhysicsStepSystem(host), {
4357
+ phase: Phase.FixedUpdate,
4358
+ order: 100
4359
+ });
4360
+ ctx.registerSystem(new PhysicsInterpolationSystem(host), {
4361
+ phase: Phase.PreRender,
4362
+ order: PHYSICS_INTERPOLATE_ORDER
4363
+ });
4364
+ },
4365
+ async onStart(app) {
4366
+ const ctx = context;
4367
+ if (ctx === null) return;
4368
+ const settings = ctx.settings(PHYSICS_SETTINGS_SECTION);
4369
+ const havok = await loadHavok({
4370
+ ...options.havok === void 0 ? {} : { module: options.havok },
4371
+ ...options.wasmBinary === void 0 ? {} : { wasmBinary: options.wasmBinary },
4372
+ url: settings.havokWasm === "auto" ? app.assets.resolveUrl(HAVOK_WASM_FILE_NAME) : settings.havokWasm
4373
+ });
4374
+ const simulation = createSimulation();
4375
+ let world;
4376
+ try {
4377
+ world = createWorld(simulation.scene, havok, settings.gravity);
4378
+ } catch (cause) {
4379
+ disposeSimulation(simulation);
4380
+ throw cause;
4381
+ }
4382
+ const counters = app.diagnostics.registerGroup(PHYSICS_DIAGNOSTICS_GROUP, PHYSICS_DIAGNOSTICS_COUNTERS);
4383
+ host.runtime = new PhysicsRuntime({
4384
+ ctx,
4385
+ settings,
4386
+ simulation,
4387
+ world,
4388
+ collisionIdentities: options.collisionIdentities ?? "upstream",
4389
+ counters
4390
+ });
4391
+ ctx.setSimulationScene(simulation.scene);
4392
+ seedExistingBodies(app, host);
4393
+ },
4394
+ dispose() {
4395
+ context?.setSimulationScene(null);
4396
+ service?.dispose();
4397
+ host.runtime?.dispose();
4398
+ host.runtime = null;
4399
+ context = null;
4400
+ service = null;
4401
+ }
4402
+ };
4403
+ });
4404
+ /** Every component this extension registers, in a stable order. */
4405
+ const PHYSICS_COMPONENTS = Object.freeze([
4406
+ Rigidbody,
4407
+ BoxCollider,
4408
+ SphereCollider,
4409
+ CapsuleCollider,
4410
+ CylinderCollider,
4411
+ MeshCollider,
4412
+ HeightfieldCollider,
4413
+ CharacterController
4414
+ ]);
4415
+ /** The collider classes the seed pass walks, in registration order. */
4416
+ const COLLIDER_TYPES = Object.freeze([
4417
+ BoxCollider,
4418
+ SphereCollider,
4419
+ CapsuleCollider,
4420
+ CylinderCollider,
4421
+ MeshCollider,
4422
+ HeightfieldCollider
4423
+ ]);
4424
+ /**
4425
+ * Marks every collider and controller that already exists when the runtime is built.
4426
+ *
4427
+ * @remarks
4428
+ * A component attached before `onStart` — from a scene the `assets.preload` list pulled in, say —
4429
+ * called `markDirty` while `app.services.tryGet(PhysicsRuntimeKey)` was still `null`. This is the
4430
+ * catch-up pass that makes those bodies exist, and it walks the component store in registration
4431
+ * order so body creation order stays deterministic (`09-physics.md` §8).
4432
+ *
4433
+ * @param app - The app being started.
4434
+ * @param host - The holder the runtime landed in.
4435
+ */
4436
+ function seedExistingBodies(app, host) {
4437
+ const runtime = host.runtime;
4438
+ if (runtime === null) return;
4439
+ for (const type of COLLIDER_TYPES) {
4440
+ const components = app.world.components(type);
4441
+ for (let index = 0; index < components.length; index += 1) {
4442
+ const collider = components[index];
4443
+ if (collider !== void 0) runtime.markDirty(collider.entity);
4444
+ }
4445
+ }
4446
+ const controllers = app.world.components(CharacterController);
4447
+ for (let index = 0; index < controllers.length; index += 1) {
4448
+ const controller = controllers[index];
4449
+ if (controller !== void 0) runtime.markControllerDirty(controller);
4450
+ }
4451
+ }
4452
+ //#endregion
4453
+ //#region src/schemas.ts
4454
+ /**
4455
+ * The documentation harness's view of everything `@ignifx/physics` declares
4456
+ * (`docs/architecture/16-docs-harness-and-skill.md` §3, `scripts/README.md`).
4457
+ *
4458
+ * `pnpm docs:schemas` imports the built entry point, calls {@link describeSchemas}, and turns the
4459
+ * result into `skills/ignifx/references/formats/<format>.md`. Keys are namespaced `<package>/<Name>`
4460
+ * type ids; the file format is keyed `ignifx/physicsmaterial-file` for the same reason `@ignifx/core`
4461
+ * keys its file formats that way — the harness rejects a key with no `/` and groups pages by
4462
+ * `format`.
4463
+ */
4464
+ /**
4465
+ * Describes every component and file format this package declares.
4466
+ *
4467
+ * @returns The records, keyed by namespaced type id.
4468
+ *
4469
+ * @example
4470
+ * ```ts
4471
+ * const schemas = describeSchemas();
4472
+ * schemas["ignifx/Rigidbody"].fields["mass"].default; // 1
4473
+ * ```
4474
+ *
4475
+ * @public
4476
+ */
4477
+ function describeSchemas() {
4478
+ return {
4479
+ "ignifx/Rigidbody": describeSchema("ignifx/Rigidbody", Rigidbody.schema, { description: "Makes an entity's colliders a dynamic, kinematic, or static Havok body." }),
4480
+ "ignifx/BoxCollider": describeSchema("ignifx/BoxCollider", BoxCollider.schema, { description: "A box collision shape, sized in local units and scaled by the entity." }),
4481
+ "ignifx/SphereCollider": describeSchema("ignifx/SphereCollider", SphereCollider.schema, { description: "A sphere collision shape; the largest scale axis wins." }),
4482
+ "ignifx/CapsuleCollider": describeSchema("ignifx/CapsuleCollider", CapsuleCollider.schema, { description: "A capsule collision shape standing along X, Y, or Z." }),
4483
+ "ignifx/CylinderCollider": describeSchema("ignifx/CylinderCollider", CylinderCollider.schema, { description: "A cylinder collision shape standing along Y." }),
4484
+ "ignifx/MeshCollider": describeSchema("ignifx/MeshCollider", MeshCollider.schema, { description: "A triangle-mesh or convex-hull shape built from real geometry; needs a GPU app." }),
4485
+ "ignifx/HeightfieldCollider": describeSchema("ignifx/HeightfieldCollider", HeightfieldCollider.schema, { description: "A terrain collision shape built from a regular grid of height samples." }),
4486
+ "ignifx/CharacterController": describeSchema("ignifx/CharacterController", CharacterController.schema, { description: "A kinematic capsule with collide-and-slide, support detection, and body pushing." }),
4487
+ "ignifx/physicsmaterial-file": describePhysicsMaterialFileFormat()
4488
+ };
4489
+ }
4490
+ //#endregion
4491
+ export { BODY_TYPES, BoxCollider, CAPSULE_DIRECTIONS, COLLISION_EVENT_MODES, COLLISION_IDENTITY_MODES, CapsuleCollider, CharacterController, Collider, CylinderCollider, HAVOK_WASM_AUTO, HeightfieldCollider, INTERPOLATION_MODES, KINEMATIC_SYNC_MODES, MeshCollider, PHYSICS_DIAGNOSTICS_COUNTERS, PHYSICS_DIAGNOSTICS_GROUP, PHYSICS_ERROR_MESSAGES, PHYSICS_MATERIAL_ASSET_TYPE, PHYSICS_MATERIAL_FILE_EXTENSION, PHYSICS_MATERIAL_FILE_FORMAT, PHYSICS_MATERIAL_FORMAT_VERSION, PHYSICS_SETTINGS_SECTION, PhysicsErrorCode, PhysicsMaterial, PhysicsService, Rigidbody, SUPPORT_STATES, SphereCollider, colliderFields, createPhysicsMaterialLoader, defaultPhysicsSettings, describePhysicsMaterialFileFormat, describeSchemas, parsePhysicsMaterial, physics, physicsError, physicsSettingsSchema };
4492
+
4493
+ //# sourceMappingURL=index.js.map