@pinkaphant/kolmo 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,145 +1,27 @@
1
- import { C as pilotedVehicleQuery, D as writeVehicleTelemetry, E as writeEntityKinematics, S as kolmoWorld, T as vehicleSimQuery, _ as VelocityTrait, a as G_SI, b as flipVehicleBodyUpright, c as evaluateNBodyGravity, d as InteractableTrait, f as PilotLink, g as VehicleTrait, h as VehicleTelemetryTrait, i as useOptionalKootaWorld, l as resolveAttractorMu, m as TransformTrait, n as KolmoPhysics, o as computeCircularOrbitSpeed, p as PilotedTag, r as useIsKolmoCustomGravity, s as createNBodyGravityField, t as KolmoGravityContext, u as ActorTrait, v as WorldSessionTrait, w as useActiveKolmoWorld, x as kolmoActions, y as ensureWorldSession } from "../physics-FhWvTBfH.js";
2
- import React, { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useReducer, useRef, useState, useSyncExternalStore } from "react";
3
- import { KeyboardControls, useKeyboardControls } from "@react-three/drei";
4
- import { Joystick, VirtualButton, useButtonStore, useJoystickStore } from "@pinkaphant/ecctrl/input";
1
+ import { A as writeEntityKinematics, C as flipVehicleBodyUpright, D as useActiveKolmoWorld, E as pilotedVehicleQuery, O as useOptionalKootaWorld, S as ensureWorldSession, T as kolmoWorld, _ as VehicleTelemetryTrait, a as computeCircularOrbitSpeed, b as WorldSessionTrait, c as evaluatePreparedNBodyGravity, d as ActorTrait, f as InteractableTrait, g as TransformTrait, h as PilotedTag, i as G_SI, j as writeVehicleTelemetry, k as vehicleSimQuery, l as prepareAttractors, m as PilotLink, n as KolmoPhysics, o as createNBodyGravityField, p as KolmoWorldContext, r as useIsKolmoCustomGravity, s as evaluateNBodyGravity, t as KolmoGravityContext, u as resolveAttractorMu, v as VehicleTrait, w as kolmoActions, x as createEmptyVehicleCmd, y as VelocityTrait } from "../physics-ZDFXaCli.js";
2
+ import { a as KOLMO_KEY_MAP, c as KolmoKeyboardContext, i as EMPTY_KOLMO_INPUT, l as useKolmoInput, n as KolmoSurface, o as KOLMO_STICK_DEADZONE, r as KolmoVehicle, s as KolmoKeyboardBridge, t as KolmoProp } from "../surface-DUol_5ml.js";
3
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react";
5
4
  import * as THREE from "three";
5
+ import { clone } from "three/examples/jsm/utils/SkeletonUtils.js";
6
6
  import { Canvas, useFrame, useThree } from "@react-three/fiber";
7
- import { CuboidCollider, RigidBody, useRapier } from "@react-three/rapier";
8
- import { WorldProvider, useHas, useQueryFirst } from "koota/react";
7
+ import { useRapier } from "@react-three/rapier";
8
+ import { WorldProvider, useQueryFirst } from "koota/react";
9
9
  import { Ecctrl } from "@pinkaphant/ecctrl";
10
10
  import { EcctrlCameraControls } from "@pinkaphant/ecctrl/camera";
11
+ import { assignRef, loadKhrGlb } from "@khr3/core";
11
12
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
- import { easing } from "maath";
13
- import { KhrAssembly, cloneKhrBundle, createKhrGltfPlugin, useKhrGlb } from "@khr3/core";
14
- import { KhrVehicle } from "@khr3/core/vehicle";
13
+ import { createPortal as createPortal$1 } from "react-dom";
14
+ import { KeyboardControls } from "@react-three/drei";
15
15
  import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
16
16
  import "koota";
17
+ import { Joystick, VirtualButton } from "@pinkaphant/ecctrl/input";
17
18
  import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
18
19
  import { KTX2Loader } from "three/examples/jsm/loaders/KTX2Loader.js";
19
20
  import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
20
- // src/engine/input.ts
21
- var KolmoKeyboardContext = createContext(null);
22
- function KolmoKeyboardBridge({ children }) {
23
- const [, getKeys] = useKeyboardControls();
24
- return React.createElement(KolmoKeyboardContext.Provider, { value: getKeys }, children);
25
- }
26
- var KOLMO_STICK_DEADZONE = .08;
27
- var EMPTY_KOLMO_INPUT = Object.freeze({
28
- forward: false,
29
- backward: false,
30
- left: false,
31
- right: false,
32
- brake: false,
33
- boost: false,
34
- interact: false,
35
- turnLeft: false,
36
- turnRight: false,
37
- descend: false,
38
- cameraView: false,
39
- reset: false,
40
- modeToggle: false,
41
- stickX: 0,
42
- stickY: 0
43
- });
44
- var KOLMO_KEY_MAP = [
45
- {
46
- name: "forward",
47
- keys: ["KeyW", "ArrowUp"]
48
- },
49
- {
50
- name: "backward",
51
- keys: ["KeyS", "ArrowDown"]
52
- },
53
- {
54
- name: "left",
55
- keys: ["KeyA", "ArrowLeft"]
56
- },
57
- {
58
- name: "right",
59
- keys: ["KeyD", "ArrowRight"]
60
- },
61
- {
62
- name: "brake",
63
- keys: ["Space"]
64
- },
65
- {
66
- name: "boost",
67
- keys: ["ShiftLeft", "ShiftRight"]
68
- },
69
- {
70
- name: "interact",
71
- keys: ["KeyF", "KeyE"]
72
- },
73
- {
74
- name: "turnLeft",
75
- keys: ["KeyQ"]
76
- },
77
- {
78
- name: "turnRight",
79
- keys: ["KeyC"]
80
- },
81
- {
82
- name: "descend",
83
- keys: ["KeyX", "ControlLeft"]
84
- },
85
- {
86
- name: "cameraView",
87
- keys: ["KeyV"]
88
- },
89
- {
90
- name: "reset",
91
- keys: ["KeyR"]
92
- },
93
- {
94
- name: "modeToggle",
95
- keys: ["KeyG"]
96
- }
97
- ];
98
- /**
99
- * Zero-allocation input reader merging Drei `<KeyboardControls>`, `@pinkaphant/ecctrl/input`
100
- * Zustand stores (`useJoystickStore` + `useButtonStore`), and optional `getInput()` overrides.
101
- */
102
- function useKolmoInput(getInput) {
103
- const getKeyboard = useContext(KolmoKeyboardContext);
104
- const getterRef = useRef(getInput);
105
- getterRef.current = getInput;
106
- const outRef = useRef({ ...EMPTY_KOLMO_INPUT });
107
- return useCallback(() => {
108
- const custom = getterRef.current?.();
109
- const k = getKeyboard ? getKeyboard() : EMPTY_KOLMO_INPUT;
110
- const rawStick = useJoystickStore.getState().joysticks.default;
111
- const btns = useButtonStore.getState().buttons;
112
- const rx = rawStick?.x ?? 0;
113
- const ry = rawStick?.y ?? 0;
114
- const mag = Math.hypot(rx, ry);
115
- const sx = custom?.stickX ?? (mag > .08 ? rx : 0);
116
- const sy = custom?.stickY ?? (mag > .08 ? ry : 0);
117
- const out = outRef.current;
118
- out.stickX = sx;
119
- out.stickY = sy;
120
- out.forward = Boolean(custom?.forward ?? (k.forward || sy > .2));
121
- out.backward = Boolean(custom?.backward ?? (k.backward || sy < -.2));
122
- out.left = Boolean(custom?.left ?? (k.left || sx < -.2));
123
- out.right = Boolean(custom?.right ?? (k.right || sx > .2));
124
- out.brake = Boolean(custom?.brake ?? (k.brake || btns.brake || btns.jump));
125
- out.boost = Boolean(custom?.boost ?? (k.boost || btns.boost || btns.run));
126
- out.interact = Boolean(custom?.interact ?? (k.interact || btns.interact));
127
- out.turnLeft = Boolean(custom?.turnLeft ?? (k.turnLeft || btns.turnLeft));
128
- out.turnRight = Boolean(custom?.turnRight ?? (k.turnRight || btns.turnRight));
129
- out.descend = Boolean(custom?.descend ?? (k.descend || btns.descend));
130
- out.cameraView = Boolean(custom?.cameraView ?? (k.cameraView || btns.cameraView));
131
- out.reset = Boolean(custom?.reset ?? (k.reset || btns.reset));
132
- out.modeToggle = Boolean(custom?.modeToggle ?? (k.modeToggle || btns.modeToggle));
133
- return out;
134
- }, [getKeyboard]);
135
- }
136
21
  // src/engine/actor.tsx
137
- function assignRefValue$2(ref, value) {
138
- if (typeof ref === "function") ref(value);
139
- else if (ref && typeof ref === "object") ref.current = value;
140
- }
141
22
  var _seatVec = new THREE.Vector3();
142
23
  var _camFwd = new THREE.Vector3();
24
+ var _worldUp = new THREE.Vector3(0, 1, 0);
143
25
  function findNearestInteractableVehicleId(world, actorPos) {
144
26
  let nearestId = null;
145
27
  let bestDistSq = 1e400;
@@ -162,13 +44,15 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
162
44
  0
163
45
  ], rotation, userData, children, ...ecctrlRest }) {
164
46
  const ctxCustomGravity = useContext(KolmoGravityContext);
47
+ const effCustomGravity = enableCustomGravity ?? ctxCustomGravity;
165
48
  const activeWorld = useActiveKolmoWorld();
166
49
  useLayoutEffect(() => {
167
50
  ensureWorldSession(activeWorld);
168
51
  }, [activeWorld]);
169
52
  const pilotedVehEnt = useQueryFirst(VehicleTrait, PilotedTag);
170
53
  const readInput = useKolmoInput(getInput);
171
- const hasDom = useThree((s) => typeof s.gl?.domElement?.setAttribute === "function");
54
+ const domElement = useThree((s) => s.gl?.domElement);
55
+ const hasDom = Boolean(domElement && typeof domElement.addEventListener === "function");
172
56
  const { world: rapierWorld } = useRapier();
173
57
  const actorEntRef = useRef(null);
174
58
  const ecctrlRef = useRef(null);
@@ -192,10 +76,7 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
192
76
  run: false,
193
77
  jump: false
194
78
  });
195
- const exitOverrideRef = useRef({
196
- pos: null,
197
- yaw: 0
198
- });
79
+ const [latchedExit, setLatchedExit] = useState(null);
199
80
  useLayoutEffect(() => {
200
81
  const ent = activeWorld.spawn(ActorTrait({
201
82
  id: "pilot",
@@ -210,10 +91,10 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
210
91
  const unsub = activeWorld.onChange(ActorTrait, (changed) => {
211
92
  if (changed !== ent) return;
212
93
  const d = ent.get(ActorTrait);
213
- if (d) exitOverrideRef.current = {
94
+ if (d?.exitSpawnPos) setLatchedExit({
214
95
  pos: d.exitSpawnPos,
215
96
  yaw: d.exitSpawnYaw
216
- };
97
+ });
217
98
  });
218
99
  return () => {
219
100
  unsub();
@@ -221,13 +102,17 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
221
102
  ent.destroy();
222
103
  };
223
104
  }, [activeWorld]);
105
+ const onFoot = enable && !pilotedVehEnt;
106
+ useLayoutEffect(() => {
107
+ if (!onFoot) camSyncedRef.current = false;
108
+ }, [onFoot]);
224
109
  useLayoutEffect(() => {
225
110
  const ent = actorEntRef.current;
226
111
  if (ent && pilotedVehEnt && !ent.has(PilotLink(pilotedVehEnt))) ent.add(PilotLink(pilotedVehEnt));
227
112
  }, [pilotedVehEnt]);
228
113
  const assignEcctrlRef = useCallback((handle) => {
229
114
  ecctrlRef.current = handle;
230
- assignRefValue$2(ref, handle);
115
+ assignRef(ref, handle);
231
116
  const ent = actorEntRef.current;
232
117
  if (!ent?.isAlive()) return;
233
118
  const cur = ent.get(ActorTrait);
@@ -236,18 +121,17 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
236
121
  y: cur.exitLinVel[1],
237
122
  z: cur.exitLinVel[2]
238
123
  }, true);
239
- if (handle?.body) exitOverrideRef.current.pos = null;
240
124
  ent.set(ActorTrait, {
241
125
  id: cur?.id ?? "pilot",
242
126
  handle,
243
- exitSpawnPos: handle?.body ? null : cur?.exitSpawnPos ?? null,
127
+ exitSpawnPos: cur?.exitSpawnPos ?? null,
244
128
  exitSpawnYaw: cur?.exitSpawnYaw ?? 0,
245
129
  exitLinVel: handle?.body ? null : cur?.exitLinVel ?? null
246
130
  });
247
131
  }, [ref]);
248
132
  const assignCamRef = useCallback((ctrl) => {
249
133
  camCtrlRef.current = ctrl;
250
- assignRefValue$2(cameraRef, ctrl);
134
+ assignRef(cameraRef, ctrl);
251
135
  }, [cameraRef]);
252
136
  const mergedUserData = useMemo(() => {
253
137
  const base = userData ?? {};
@@ -260,9 +144,7 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
260
144
  }
261
145
  };
262
146
  }, [userData]);
263
- const clonedScene = useMemo(() => bundle ? bundle.scene.clone(true) : null, [bundle]);
264
- const onFoot = enable && !pilotedVehEnt;
265
- if (!onFoot) camSyncedRef.current = false;
147
+ const clonedScene = useMemo(() => bundle ? clone(bundle.scene) : null, [bundle]);
266
148
  useFrame((state, delta) => {
267
149
  if (!enable) return;
268
150
  const dt = rapierWorld.timestep > 0 ? rapierWorld.timestep : Math.min(Math.max(delta, 1e-4), 1 / 30);
@@ -303,22 +185,20 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
303
185
  }
304
186
  const cam = camCtrlRef.current;
305
187
  if (cam && handle.currPos.lengthSq() > 0) {
306
- const hasValidUp = handle.upAxis.lengthSq() > .25;
307
- if (hasValidUp) followUp.current.copy(handle.upAxis).normalize();
188
+ if (handle.upAxis.lengthSq() > .25) followUp.current.copy(handle.upAxis).normalize();
189
+ else followUp.current.copy(_worldUp);
308
190
  followPos.current.copy(handle.currPos).addScaledVector(followUp.current, .55);
309
191
  if (!camSyncedRef.current) {
310
192
  camSyncedRef.current = true;
311
- if (hasValidUp) {
312
- state.camera.up.copy(followUp.current);
313
- cam.setUp(followUp.current);
314
- }
193
+ state.camera.up.copy(followUp.current);
194
+ cam.setUp(followUp.current);
315
195
  _camFwd.copy(handle.bodyZAxis).projectOnPlane(followUp.current);
316
196
  if (_camFwd.lengthSq() < 1e-4) _camFwd.set(0, 0, -1).projectOnPlane(followUp.current);
317
197
  _camFwd.normalize();
318
198
  cam.setLookAt(followPos.current.x - _camFwd.x * 7.5 + followUp.current.x * 2.4, followPos.current.y - _camFwd.y * 7.5 + followUp.current.y * 2.4, followPos.current.z - _camFwd.z * 7.5 + followUp.current.z * 2.4, followPos.current.x, followPos.current.y, followPos.current.z, false);
319
199
  } else {
320
200
  cam.moveTo(followPos.current.x, followPos.current.y, followPos.current.z, true);
321
- if (hasValidUp) {
201
+ if (effCustomGravity && state.camera.up.distanceToSquared(followUp.current) > 1e-6) {
322
202
  state.camera.up.lerp(followUp.current, 1 - Math.exp(-8 * dt)).normalize();
323
203
  cam.setUp(state.camera.up);
324
204
  }
@@ -326,10 +206,10 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
326
206
  }
327
207
  });
328
208
  if (!onFoot) return null;
329
- const spawnPos = exitOverrideRef.current.pos ?? position;
330
- const spawnRot = rotation ?? (exitOverrideRef.current.pos ? [
209
+ const spawnPos = latchedExit?.pos ?? position;
210
+ const spawnRot = rotation ?? (latchedExit ? [
331
211
  0,
332
- exitOverrideRef.current.yaw,
212
+ latchedExit.yaw,
333
213
  0
334
214
  ] : void 0);
335
215
  return /* @__PURE__ */ jsxs(Fragment, { children: [hasDom && cameraProps !== false && cameraProps !== null && /* @__PURE__ */ jsx(EcctrlCameraControls, {
@@ -342,7 +222,7 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
342
222
  }), /* @__PURE__ */ jsx(Ecctrl, {
343
223
  ref: assignEcctrlRef,
344
224
  enable,
345
- enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
225
+ enableCustomGravity: effCustomGravity,
346
226
  position: spawnPos,
347
227
  ...spawnRot === void 0 ? {} : { rotation: spawnRot },
348
228
  userData: mergedUserData,
@@ -350,511 +230,9 @@ function KolmoActor({ ref, cameraRef, cameraProps, getInput, bundle, enable = tr
350
230
  children: children ?? (clonedScene ? /* @__PURE__ */ jsx("primitive", { object: clonedScene }) : null)
351
231
  })] });
352
232
  }
353
- // src/engine/vehicle.tsx
354
- function assignRefValue$1(ref, value) {
355
- if (typeof ref === "function") ref(value);
356
- else if (ref && typeof ref === "object") ref.current = value;
357
- }
358
- function createEmptyVehicleCmd() {
359
- return {
360
- forward: false,
361
- backward: false,
362
- steerLeft: false,
363
- steerRight: false,
364
- brake: false,
365
- throttleUp: false,
366
- throttleDown: false,
367
- yawLeft: false,
368
- yawRight: false,
369
- pitchForward: false,
370
- pitchBackward: false,
371
- rollLeft: false,
372
- rollRight: false,
373
- joystickL: {
374
- x: 0,
375
- y: 0
376
- },
377
- joystickR: {
378
- x: 0,
379
- y: 0
380
- }
381
- };
382
- }
383
- function hasActiveCmd(c) {
384
- return Boolean(c.forward || c.backward || c.steerLeft || c.steerRight || c.brake || c.throttleUp || c.throttleDown || c.yawLeft || c.yawRight || c.pitchForward || c.pitchBackward || c.rollLeft || c.rollRight || c.joystickL && (c.joystickL.x !== 0 || c.joystickL.y !== 0) || c.joystickR && (c.joystickR.x !== 0 || c.joystickR.y !== 0));
385
- }
386
- var _up = new THREE.Vector3();
387
- var _fwd = new THREE.Vector3();
388
- var _camGoal = new THREE.Vector3();
389
- var _lookGoal = new THREE.Vector3();
390
- function KolmoVehicleMount({ ref, vehicleRef, jointsRef: outerJointsRef, id, sourceBundle, piloted = false, flightMode = false, vehicleMode, interactRadius = 4.2, enable = true, enableCustomGravity, wheelConfig, propellerConfig, droneConfig, getInput, driver, cameraController, children, ...khrRest }) {
391
- const ctxCustomGravity = useContext(KolmoGravityContext);
392
- const activeWorld = useActiveKolmoWorld();
393
- useLayoutEffect(() => {
394
- ensureWorldSession(activeWorld);
395
- }, [activeWorld]);
396
- const readInput = useKolmoInput(getInput);
397
- const bundle = useMemo(() => cloneKhrBundle(sourceBundle), [sourceBundle]);
398
- const jointsRef = useRef(null);
399
- const innerRef = useRef(null);
400
- const canHybridToggle = vehicleMode === void 0 && bundle.wheels.length > 0 && bundle.propellers.length > 0;
401
- const [hybridFlight, setHybridFlight] = useState(flightMode);
402
- useLayoutEffect(() => {
403
- setHybridFlight(flightMode);
404
- }, [flightMode]);
405
- const [boostThrustActive, setBoostThrustActive] = useState(false);
406
- const boostThrustRef = useRef(false);
407
- const isFlight = Boolean(vehicleMode === "rocket" || (canHybridToggle ? hybridFlight : flightMode) || vehicleMode !== "drive" && bundle.propellers.length > 0 && bundle.wheels.length === 0);
408
- const seatOffset = useMemo(() => {
409
- const dot = bundle.sockets.butt ?? bundle.sockets.driver_butt ?? bundle.sockets.seat ?? bundle.sockets.IK_Seat;
410
- return dot ? [
411
- dot[0],
412
- dot[1],
413
- dot[2]
414
- ] : [
415
- 0,
416
- .65,
417
- 0
418
- ];
419
- }, [bundle.sockets]);
420
- const exitOffset = useMemo(() => {
421
- const dot = bundle.sockets.exit ?? bundle.sockets.Socket_Exit;
422
- return dot ? [
423
- dot[0],
424
- dot[1],
425
- dot[2]
426
- ] : [
427
- -1.55,
428
- .45,
429
- 0
430
- ];
431
- }, [bundle.sockets]);
432
- const propActive = bundle.propellers.length > 0 && (isFlight || vehicleMode !== "drive" && boostThrustActive);
433
- const mergedWheelConfig = useMemo(() => {
434
- const wheelOverride = bundle.wheels.length > 0 && vehicleMode === "rocket" ? { enable: false } : void 0;
435
- return !wheelConfig && !wheelOverride ? void 0 : {
436
- ...wheelOverride,
437
- ...wheelConfig ?? {}
438
- };
439
- }, [
440
- bundle.wheels.length,
441
- vehicleMode,
442
- wheelConfig
443
- ]);
444
- const mergedPropellerConfig = useMemo(() => {
445
- const propOverride = bundle.propellers.length > 0 && !propActive ? { enable: false } : void 0;
446
- return !propellerConfig && !propOverride ? void 0 : {
447
- ...propOverride,
448
- ...propellerConfig ?? {}
449
- };
450
- }, [
451
- bundle.propellers.length,
452
- propActive,
453
- propellerConfig
454
- ]);
455
- const [vehEnt, setVehEnt] = useState(null);
456
- const vehEntRef = useRef(null);
457
- const camTargetRef = useRef(new THREE.Vector3());
458
- const cmdRef = useRef(createEmptyVehicleCmd());
459
- const stRef = useRef({
460
- camInit: false,
461
- cockpit: false,
462
- prevCam: false,
463
- prevReset: false,
464
- prevMode: false,
465
- wasPiloted: false
466
- });
467
- useLayoutEffect(() => {
468
- const ent = activeWorld.spawn(VehicleTrait({
469
- id,
470
- handle: innerRef.current,
471
- seatOffset,
472
- exitOffset,
473
- isFlight
474
- }), InteractableTrait({
475
- id,
476
- radius: interactRadius,
477
- kind: "vehicle"
478
- }), TransformTrait, VelocityTrait, VehicleTelemetryTrait);
479
- vehEntRef.current = ent;
480
- setVehEnt(ent);
481
- if (piloted && !activeWorld.queryFirst(pilotedVehicleQuery)) kolmoActions(activeWorld).boardVehicle(id);
482
- return () => {
483
- if (ent.isAlive() && ent.has(PilotedTag)) kolmoActions(activeWorld).exitVehicle();
484
- vehEntRef.current = null;
485
- ent.destroy();
486
- };
487
- }, [
488
- activeWorld,
489
- id,
490
- seatOffset,
491
- exitOffset,
492
- interactRadius,
493
- piloted
494
- ]);
495
- useLayoutEffect(() => {
496
- const ent = vehEntRef.current;
497
- if (!ent?.isAlive()) return;
498
- const v = ent.get(VehicleTrait);
499
- if (v && v.isFlight !== isFlight) ent.set(VehicleTrait, {
500
- ...v,
501
- isFlight
502
- });
503
- }, [isFlight]);
504
- const assignVehicleRef = useCallback((handle) => {
505
- innerRef.current = handle;
506
- assignRefValue$1(vehicleRef, handle);
507
- assignRefValue$1(ref, handle);
508
- const ent = vehEntRef.current;
509
- if (ent?.isAlive()) {
510
- const v = ent.get(VehicleTrait);
511
- if (v) ent.set(VehicleTrait, {
512
- ...v,
513
- handle
514
- });
515
- }
516
- }, [ref, vehicleRef]);
517
- const assignJointsRef = useCallback((jh) => {
518
- jointsRef.current = jh;
519
- assignRefValue$1(outerJointsRef, jh);
520
- }, [outerJointsRef]);
521
- const { world: rapierWorld } = useRapier();
522
- const isPiloted = useHas(vehEnt, PilotedTag) || piloted && vehEnt === null;
523
- useFrame((state, delta) => {
524
- const dt = rapierWorld.timestep > 0 ? rapierWorld.timestep : Math.min(Math.max(delta, 1e-4), 1 / 30);
525
- const veh = innerRef.current;
526
- if (!veh?.body) return;
527
- if (driver) {
528
- driver(veh, dt, state);
529
- cameraController?.(veh, dt, state);
530
- return;
531
- }
532
- const keys = readInput();
533
- const st = stRef.current;
534
- const cmd = cmdRef.current;
535
- const wantBoostProp = isPiloted && !isFlight && vehicleMode !== "drive" && bundle.propellers.length > 0 && keys.boost && (keys.forward || keys.brake);
536
- if (wantBoostProp !== boostThrustRef.current) {
537
- boostThrustRef.current = wantBoostProp;
538
- setBoostThrustActive(wantBoostProp);
539
- }
540
- if (isPiloted) {
541
- st.wasPiloted = true;
542
- if (keys.cameraView && !st.prevCam) st.cockpit = !st.cockpit;
543
- st.prevCam = keys.cameraView;
544
- if (keys.reset && !st.prevReset) {
545
- flipVehicleBodyUpright(veh);
546
- jointsRef.current?.syncBodiesToParent();
547
- }
548
- st.prevReset = keys.reset;
549
- if (keys.modeToggle && !st.prevMode && canHybridToggle) setHybridFlight((f) => !f);
550
- st.prevMode = keys.modeToggle;
551
- let anyGrounded = false;
552
- for (const w of veh.wheelsInfo.values()) if (w.current.rayHit) {
553
- anyGrounded = true;
554
- break;
555
- }
556
- if (isFlight) {
557
- cmd.pitchForward = keys.forward;
558
- cmd.pitchBackward = keys.backward;
559
- cmd.yawLeft = keys.left;
560
- cmd.yawRight = keys.right;
561
- cmd.rollLeft = keys.turnLeft;
562
- cmd.rollRight = keys.turnRight;
563
- cmd.throttleUp = keys.brake;
564
- cmd.throttleDown = keys.descend;
565
- cmd.forward = anyGrounded && keys.forward;
566
- cmd.backward = anyGrounded && keys.backward;
567
- cmd.steerLeft = anyGrounded && keys.left;
568
- cmd.steerRight = anyGrounded && keys.right;
569
- cmd.brake = false;
570
- cmd.joystickL = {
571
- x: 0,
572
- y: 0
573
- };
574
- cmd.joystickR = {
575
- x: keys.stickX,
576
- y: keys.stickY
577
- };
578
- veh.setMovement(cmd);
579
- } else {
580
- const fwdVel = veh.currLinVel.dot(veh.bodyZAxis);
581
- const revBraking = keys.backward && !keys.forward && fwdVel > 1;
582
- const fwdBraking = keys.forward && !keys.backward && fwdVel < -1;
583
- if ((keys.backward && !revBraking || keys.forward && Math.abs(fwdVel) < 2.5) && veh.gearIndex !== 0) veh.setGear(0);
584
- const boostProp = keys.boost && (bundle.propellers.length > 0 || veh.propellersInfo.size > 0) && veh.gravityMag > 1e-4;
585
- cmd.forward = keys.forward && !fwdBraking;
586
- cmd.backward = keys.backward && !revBraking;
587
- cmd.steerLeft = keys.left;
588
- cmd.steerRight = keys.right;
589
- cmd.brake = keys.brake || revBraking || fwdBraking;
590
- cmd.pitchForward = boostProp && keys.forward;
591
- cmd.pitchBackward = false;
592
- cmd.throttleUp = boostProp && !keys.forward && keys.brake;
593
- cmd.throttleDown = false;
594
- cmd.yawLeft = boostProp && keys.left;
595
- cmd.yawRight = boostProp && keys.right;
596
- cmd.rollLeft = cmd.rollRight = false;
597
- cmd.joystickL = {
598
- x: keys.stickX,
599
- y: 0
600
- };
601
- cmd.joystickR = {
602
- x: 0,
603
- y: 0
604
- };
605
- veh.setMovement(cmd);
606
- }
607
- } else {
608
- st.prevCam = st.prevReset = st.prevMode = false;
609
- if (st.wasPiloted || hasActiveCmd(cmd)) {
610
- st.wasPiloted = false;
611
- Object.assign(cmd, createEmptyVehicleCmd());
612
- veh.setMovement(cmd);
613
- }
614
- }
615
- let maxSlip = 0;
616
- for (const w of veh.wheelsInfo.values()) if (w.current.rayHit && w.current.slipStrength > maxSlip) maxSlip = w.current.slipStrength;
617
- const speedKmh = veh.currLinVel.length() * 3.6;
618
- const throttle = isPiloted ? +(keys.forward || isFlight && keys.brake) : 0;
619
- const boost = isPiloted && keys.boost && throttle > 0 ? 1 : 0;
620
- const rpm = Math.round(veh.engineRPM);
621
- const gear = veh.gearIndex + 1;
622
- if (vehEntRef.current?.isAlive()) {
623
- writeEntityKinematics(activeWorld, vehEntRef.current, veh.currPos, veh.currQuat, veh.currLinVel, speedKmh);
624
- writeVehicleTelemetry(activeWorld, vehEntRef.current, rpm, gear, throttle, boost, Math.min(1, maxSlip));
625
- }
626
- if (!isPiloted) return;
627
- if (cameraController) {
628
- cameraController(veh, dt, state);
629
- return;
630
- }
631
- _up.copy(veh.upAxis);
632
- if (_up.lengthSq() < 1e-6) _up.copy(veh.bodyYAxis);
633
- if (st.cockpit) {
634
- _camGoal.set(seatOffset[0], seatOffset[1] + .32, seatOffset[2]).applyQuaternion(veh.currQuat).add(veh.currPos);
635
- _lookGoal.copy(_camGoal).addScaledVector(veh.bodyZAxis, 24);
636
- easing.damp3(state.camera.position, _camGoal, .04, dt);
637
- easing.damp3(state.camera.up, veh.bodyYAxis, .08, dt);
638
- state.camera.lookAt(_lookGoal);
639
- return;
640
- }
641
- _fwd.copy(veh.bodyZAxis);
642
- if (!isFlight) _fwd.projectOnPlane(_up).normalize();
643
- if (_fwd.lengthSq() < 1e-6) _fwd.copy(veh.bodyZAxis);
644
- _camGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? -11.2 : -6.8).addScaledVector(_up, isFlight ? 3.1 : 2.15);
645
- _lookGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? 7.5 : 3.6).addScaledVector(_up, .65);
646
- if (!st.camInit) {
647
- state.camera.position.copy(_camGoal);
648
- camTargetRef.current.copy(_lookGoal);
649
- st.camInit = true;
650
- }
651
- easing.damp3(state.camera.position, _camGoal, .14, dt);
652
- easing.damp3(camTargetRef.current, _lookGoal, .08, dt);
653
- easing.damp3(state.camera.up, _up, .16, dt);
654
- state.camera.lookAt(camTargetRef.current);
655
- });
656
- return /* @__PURE__ */ jsx("group", {
657
- onClick: (e) => {
658
- if (e.delta <= 5 && jointsRef.current?.toggleHitObject(e.object)) e.stopPropagation();
659
- },
660
- children: /* @__PURE__ */ jsx(KhrVehicle, {
661
- ref: assignVehicleRef,
662
- jointsRef: assignJointsRef,
663
- bundle,
664
- enable,
665
- enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
666
- ...mergedWheelConfig === void 0 ? {} : { wheelConfig: mergedWheelConfig },
667
- ...mergedPropellerConfig === void 0 ? {} : { propellerConfig: mergedPropellerConfig },
668
- ...droneConfig === void 0 ? {} : { droneConfig },
669
- ...khrRest,
670
- children
671
- })
672
- });
673
- }
674
- function KolmoVehicleFromUrl(props) {
675
- const { src, ...rest } = props;
676
- const bundle = useKhrGlb(src);
677
- return /* @__PURE__ */ jsx(KolmoVehicleMount, {
678
- ...rest,
679
- sourceBundle: bundle
680
- });
681
- }
682
- function KolmoVehicle(props) {
683
- const reactId = useId();
684
- const id = props.id ?? `vehicle_${reactId.replace(/:/g, "")}`;
685
- const { src, bundle, ...rest } = props;
686
- if (bundle) return /* @__PURE__ */ jsx(KolmoVehicleMount, {
687
- ...rest,
688
- id,
689
- sourceBundle: bundle
690
- });
691
- if (src) return /* @__PURE__ */ jsx(KolmoVehicleFromUrl, {
692
- ...rest,
693
- id,
694
- src
695
- });
696
- return null;
697
- }
698
- // src/engine/surface.tsx
699
- function assignRefValue(ref, value) {
700
- if (typeof ref === "function") ref(value);
701
- else if (ref && typeof ref === "object") ref.current = value;
702
- }
703
- function ArenaSlab({ size, position, color = "#252b36" }) {
704
- const res = useMemo(() => ({
705
- geo: new THREE.BoxGeometry(size, 1, size),
706
- mat: new THREE.MeshStandardMaterial({
707
- color,
708
- roughness: .9,
709
- metalness: .05
710
- })
711
- }), [size, color]);
712
- useEffect(() => () => {
713
- res.geo.dispose();
714
- res.mat.dispose();
715
- }, [res]);
716
- return /* @__PURE__ */ jsxs(RigidBody, {
717
- type: "fixed",
718
- colliders: false,
719
- position: [
720
- position[0],
721
- position[1] - .5,
722
- position[2]
723
- ],
724
- friction: .9,
725
- children: [/* @__PURE__ */ jsx(CuboidCollider, {
726
- args: [
727
- size * .5,
728
- .5,
729
- size * .5
730
- ],
731
- restitution: .04
732
- }), /* @__PURE__ */ jsx("mesh", {
733
- geometry: res.geo,
734
- material: res.mat,
735
- receiveShadow: true
736
- })]
737
- });
738
- }
739
- function BundleSurface({ ref, bundle, position, ...rest }) {
740
- const cloned = useMemo(() => cloneKhrBundle(bundle), [bundle]);
741
- return /* @__PURE__ */ jsx(KhrAssembly, {
742
- ref,
743
- bundle: cloned,
744
- position,
745
- fixedRoot: true,
746
- ...rest
747
- });
748
- }
749
- function UrlSurface({ src, ...rest }) {
750
- const bundle = useKhrGlb(src);
751
- return /* @__PURE__ */ jsx(BundleSurface, {
752
- bundle,
753
- ...rest
754
- });
755
- }
756
- function KolmoSurface({ ref, src, bundle, size = 200, color, position = [
757
- 0,
758
- 0,
759
- 0
760
- ], ...rest }) {
761
- if (bundle) return /* @__PURE__ */ jsx(BundleSurface, {
762
- ref,
763
- bundle,
764
- position,
765
- ...rest
766
- });
767
- if (src) return /* @__PURE__ */ jsx(UrlSurface, {
768
- ref,
769
- src,
770
- position,
771
- ...rest
772
- });
773
- return /* @__PURE__ */ jsx(ArenaSlab, {
774
- size,
775
- position,
776
- color
777
- });
778
- }
779
- function resolveJointTargets(limits) {
780
- if (!limits) return {
781
- open: Math.PI / 2,
782
- closed: 0
783
- };
784
- const [lo, hi] = limits;
785
- return {
786
- open: Math.abs(hi) >= Math.abs(lo) ? hi : lo,
787
- closed: Math.min(hi, Math.max(lo, 0))
788
- };
789
- }
790
- function togglePropJoint(handle, bundle, openState, clickedObj, perBodyOpen) {
791
- if (!handle) return openState;
792
- if (clickedObj && perBodyOpen) {
793
- let cur = clickedObj;
794
- while (cur) {
795
- const hit = bundle.bodies.find((b) => b.object === cur && b.joint?.drive?.stiffness !== void 0);
796
- if (hit) {
797
- const nextOpen = !(perBodyOpen.get(hit.nodeName) ?? false);
798
- perBodyOpen.set(hit.nodeName, nextOpen);
799
- const { open, closed } = resolveJointTargets(hit.joint?.limits ?? null);
800
- handle.setJointTarget(hit.nodeName, nextOpen ? open : closed);
801
- return nextOpen;
802
- }
803
- cur = cur.parent;
804
- }
805
- }
806
- const nextAll = !openState;
807
- for (const b of bundle.bodies) {
808
- if (!b.joint?.drive || b.joint.drive.stiffness === void 0) continue;
809
- const { open, closed } = resolveJointTargets(b.joint.limits);
810
- perBodyOpen?.set(b.nodeName, nextAll);
811
- handle.setJointTarget(b.nodeName, nextAll ? open : closed);
812
- }
813
- return nextAll;
814
- }
815
- function BundleProp({ ref, bundle, fixed = false, onClick: userOnClick, ...rest }) {
816
- const asmRef = useRef(null);
817
- const openRef = useRef(false);
818
- const perBodyRef = useRef(/* @__PURE__ */ new Map());
819
- const cloned = useMemo(() => cloneKhrBundle(bundle), [bundle]);
820
- const assignAsmRef = useCallback((h) => {
821
- asmRef.current = h;
822
- assignRefValue(ref, h);
823
- }, [ref]);
824
- const onClick = useCallback((e) => {
825
- e.stopPropagation();
826
- openRef.current = togglePropJoint(asmRef.current, cloned, openRef.current, e.object, perBodyRef.current);
827
- userOnClick?.(e);
828
- }, [cloned, userOnClick]);
829
- return /* @__PURE__ */ jsx(KhrAssembly, {
830
- ref: assignAsmRef,
831
- bundle: cloned,
832
- fixedRoot: fixed,
833
- onClick,
834
- ...rest
835
- });
836
- }
837
- function UrlProp({ src, ...rest }) {
838
- const bundle = useKhrGlb(src);
839
- return /* @__PURE__ */ jsx(BundleProp, {
840
- bundle,
841
- ...rest
842
- });
843
- }
844
- function KolmoProp({ src, bundle, ...rest }) {
845
- if (bundle) return /* @__PURE__ */ jsx(BundleProp, {
846
- bundle,
847
- ...rest
848
- });
849
- if (src) return /* @__PURE__ */ jsx(UrlProp, {
850
- src,
851
- ...rest
852
- });
853
- return null;
854
- }
855
233
  // src/engine/world.tsx
856
234
  var KolmoInCanvasContext = createContext(false);
857
- var KolmoOverlayContext = createContext(null);
235
+ var KolmoOverlayPortalContext = createContext(null);
858
236
  function RoomEnvRig({ intensity = .65 }) {
859
237
  const { gl, scene } = useThree();
860
238
  useEffect(() => {
@@ -956,7 +334,14 @@ function KolmoWorld({ gravity = "planar", paused = false, timeScale = 1, maxDelt
956
334
  intensity: 1.85,
957
335
  color: "#fff3dc",
958
336
  castShadow: true,
959
- "shadow-mapSize": [1024, 1024]
337
+ "shadow-mapSize": [2048, 2048],
338
+ "shadow-bias": -4e-4,
339
+ "shadow-camera-left": -55,
340
+ "shadow-camera-right": 55,
341
+ "shadow-camera-top": 55,
342
+ "shadow-camera-bottom": -55,
343
+ "shadow-camera-near": 1,
344
+ "shadow-camera-far": 220
960
345
  })] }),
961
346
  /* @__PURE__ */ jsx(KolmoPhysics, {
962
347
  gravity,
@@ -964,7 +349,7 @@ function KolmoWorld({ gravity = "planar", paused = false, timeScale = 1, maxDelt
964
349
  timeScale,
965
350
  maxDelta,
966
351
  physicsDebug,
967
- world: null,
352
+ world: effectiveWorld,
968
353
  children
969
354
  })
970
355
  ]
@@ -976,9 +361,12 @@ function KolmoWorld({ gravity = "planar", paused = false, timeScale = 1, maxDelt
976
361
  value: null,
977
362
  children: inner
978
363
  });
979
- return effectiveWorld !== outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
980
- world: effectiveWorld,
981
- children: withKeyboard
364
+ return effectiveWorld !== outerWorld ? /* @__PURE__ */ jsx(KolmoWorldContext.Provider, {
365
+ value: effectiveWorld,
366
+ children: /* @__PURE__ */ jsx(WorldProvider, {
367
+ world: effectiveWorld,
368
+ children: withKeyboard
369
+ })
982
370
  }) : withKeyboard;
983
371
  }
984
372
  function useKolmoGame(explicitWorld) {
@@ -993,14 +381,12 @@ function useKolmoGame(explicitWorld) {
993
381
  const u3 = targetWorld.onRemove(PilotedTag, onChange);
994
382
  const u4 = targetWorld.onAdd(PilotLink, onChange);
995
383
  const u5 = targetWorld.onRemove(PilotLink, onChange);
996
- const u6 = targetWorld.onChange(VehicleTrait, onChange);
997
384
  return () => {
998
385
  u1();
999
386
  u2();
1000
387
  u3();
1001
388
  u4();
1002
389
  u5();
1003
- u6();
1004
390
  };
1005
391
  }, [targetWorld]);
1006
392
  const session = targetWorld.has(WorldSessionTrait) ? targetWorld.get(WorldSessionTrait) : void 0;
@@ -1020,52 +406,29 @@ function detectTouchDevice() {
1020
406
  if (typeof window === "undefined") return false;
1021
407
  return navigator.maxTouchPoints > 0 || window.matchMedia?.("(pointer: coarse)")?.matches === true;
1022
408
  }
1023
- function KolmoHudDom({ showTouchControls, style }) {
1024
- const world = useActiveKolmoWorld();
1025
- const telemetryRef = useRef(null);
1026
- const promptRef = useRef(null);
1027
- const [isTouch, setIsTouch] = useState(detectTouchDevice);
1028
- useEffect(() => {
1029
- setIsTouch(detectTouchDevice());
1030
- }, []);
1031
- const touchEnabled = showTouchControls ?? isTouch;
1032
- useEffect(() => {
1033
- let raf = 0;
1034
- let lastLine = "";
1035
- let lastPrompt = "";
1036
- const tick = () => {
1037
- const actor = world.queryFirst(ActorTrait);
1038
- const vehEnt = actor?.targetFor(PilotLink) ?? world.queryFirst(pilotedVehicleQuery);
1039
- let line;
1040
- let prompt;
1041
- if (vehEnt) {
1042
- const vd = vehEnt.get(VehicleTrait);
1043
- const vel = vehEnt.get(VelocityTrait);
1044
- const tel = vehEnt.get(VehicleTelemetryTrait);
1045
- const kmh = Math.round(vel?.speedKmh ?? 0);
1046
- const rpm = Math.round(tel?.rpm ?? 0);
1047
- const gear = tel?.gear ?? 1;
1048
- line = `${vd?.isFlight ? "Flight" : "Car"} · ${kmh} km/h · G${gear} · ${rpm} rpm`;
1049
- prompt = vd?.isFlight ? "[WASD] Fly · [Space/X] Rise/Dive · [Shift] Boost · [G] Mode · [V] Cam · [F] Exit" : "[WASD] Drive · [Shift] Boost · [Space] Brake · [V] Cam · [R] Flip · [F] Exit";
1050
- } else {
1051
- const vel = actor?.get(VelocityTrait);
1052
- const near = world.has(WorldSessionTrait) ? world.get(WorldSessionTrait)?.nearVehicleId : "";
1053
- line = `On foot · ${Math.round(vel?.speedKmh ?? 0)} km/h`;
1054
- prompt = near ? "[F] Board vehicle · [WASD] Walk · [Shift] Sprint · [Space] Jump" : "[WASD] Walk · [Shift] Sprint · [Space] Jump";
1055
- }
1056
- if (line !== lastLine && telemetryRef.current) {
1057
- telemetryRef.current.textContent = line;
1058
- lastLine = line;
1059
- }
1060
- if (prompt !== lastPrompt && promptRef.current) {
1061
- promptRef.current.textContent = prompt;
1062
- lastPrompt = prompt;
1063
- }
1064
- raf = requestAnimationFrame(tick);
409
+ function formatHudStrings(world) {
410
+ const actor = world.queryFirst(ActorTrait);
411
+ const vehEnt = actor?.targetFor(PilotLink) ?? world.queryFirst(pilotedVehicleQuery);
412
+ if (vehEnt) {
413
+ const vd = vehEnt.get(VehicleTrait);
414
+ const vel = vehEnt.get(VelocityTrait);
415
+ const tel = vehEnt.get(VehicleTelemetryTrait);
416
+ const kmh = Math.round(vel?.speedKmh ?? 0);
417
+ const rpm = Math.round(tel?.rpm ?? 0);
418
+ const gear = tel?.gear ?? 1;
419
+ return {
420
+ line: `${vd?.isFlight ? "Flight" : "Car"} · ${kmh} km/h · G${gear} · ${rpm} rpm`,
421
+ prompt: vd?.isFlight ? "[WASD] Fly · [Space/X] Rise/Dive · [Shift] Boost · [G] Mode · [V] Cam · [F] Exit" : "[WASD] Drive · [Shift] Boost · [Space] Brake · [V] Cam · [R] Flip · [F] Exit"
1065
422
  };
1066
- raf = requestAnimationFrame(tick);
1067
- return () => cancelAnimationFrame(raf);
1068
- }, [world]);
423
+ }
424
+ const vel = actor?.get(VelocityTrait);
425
+ const near = world.has(WorldSessionTrait) ? world.get(WorldSessionTrait)?.nearVehicleId : "";
426
+ return {
427
+ line: `On foot · ${Math.round(vel?.speedKmh ?? 0)} km/h`,
428
+ prompt: near ? "[F] Board vehicle · [WASD] Walk · [Shift] Sprint · [Space] Jump" : "[WASD] Walk · [Shift] Sprint · [Space] Jump"
429
+ };
430
+ }
431
+ function KolmoHudView({ telemetryRef, promptRef, touchEnabled, style }) {
1069
432
  return /* @__PURE__ */ jsxs("div", {
1070
433
  style: {
1071
434
  position: "fixed",
@@ -1140,60 +503,81 @@ function KolmoHudDom({ showTouchControls, style }) {
1140
503
  })]
1141
504
  });
1142
505
  }
1143
- function KolmoHud(props) {
1144
- const inCanvas = useContext(KolmoInCanvasContext);
1145
- const registerOverlay = useContext(KolmoOverlayContext);
1146
- const outerWorld = useOptionalKootaWorld();
1147
- const id = useId();
1148
- useLayoutEffect(() => {
1149
- if (!inCanvas || !registerOverlay) return;
1150
- const node = outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
1151
- world: outerWorld,
1152
- children: /* @__PURE__ */ jsx(KolmoHudDom, { ...props })
1153
- }) : /* @__PURE__ */ jsx(KolmoHudDom, { ...props });
1154
- registerOverlay(id, node);
1155
- return () => registerOverlay(id, null);
1156
- }, [
1157
- inCanvas,
1158
- registerOverlay,
1159
- outerWorld,
1160
- id,
1161
- props.showTouchControls,
1162
- props.style
1163
- ]);
1164
- return inCanvas ? null : /* @__PURE__ */ jsx(KolmoHudDom, { ...props });
1165
- }
1166
- function createOverlayStore() {
1167
- const map = /* @__PURE__ */ new Map();
1168
- const listeners = /* @__PURE__ */ new Set();
1169
- let snap = [];
1170
- return {
1171
- set(id, node) {
1172
- if (node === null) {
1173
- if (!map.delete(id)) return;
1174
- } else map.set(id, node);
1175
- snap = [...map.entries()];
1176
- for (const l of listeners) l();
1177
- },
1178
- subscribe(listener) {
1179
- listeners.add(listener);
1180
- return () => {
1181
- listeners.delete(listener);
1182
- };
1183
- },
1184
- getSnapshot: () => snap
1185
- };
506
+ function KolmoHudInCanvas({ showTouchControls, extraPrompt, style }) {
507
+ const portalTarget = useContext(KolmoOverlayPortalContext);
508
+ const world = useActiveKolmoWorld();
509
+ const telemetryRef = useRef(null);
510
+ const promptRef = useRef(null);
511
+ const lastRef = useRef({
512
+ line: "",
513
+ prompt: "",
514
+ elapsed: 0
515
+ });
516
+ const [isTouch, setIsTouch] = useState(detectTouchDevice);
517
+ useEffect(() => {
518
+ setIsTouch(detectTouchDevice());
519
+ }, []);
520
+ const touchEnabled = showTouchControls ?? isTouch;
521
+ useFrame((_, delta) => {
522
+ const st = lastRef.current;
523
+ st.elapsed += delta;
524
+ if (st.elapsed < .05) return;
525
+ st.elapsed = 0;
526
+ const { line, prompt } = formatHudStrings(world);
527
+ const fullPrompt = extraPrompt ? `${prompt} · ${extraPrompt}` : prompt;
528
+ if (line !== st.line && telemetryRef.current) {
529
+ telemetryRef.current.textContent = line;
530
+ st.line = line;
531
+ }
532
+ if (fullPrompt !== st.prompt && promptRef.current) {
533
+ promptRef.current.textContent = fullPrompt;
534
+ st.prompt = fullPrompt;
535
+ }
536
+ });
537
+ const target = portalTarget ?? (typeof document !== "undefined" ? document.body : null);
538
+ if (!target) return null;
539
+ return createPortal$1(/* @__PURE__ */ jsx(KolmoHudView, {
540
+ telemetryRef,
541
+ promptRef,
542
+ touchEnabled,
543
+ style
544
+ }), target);
545
+ }
546
+ function KolmoHudOutsideCanvas({ showTouchControls, extraPrompt, style }) {
547
+ const world = useActiveKolmoWorld();
548
+ const telemetryRef = useRef(null);
549
+ const promptRef = useRef(null);
550
+ const [isTouch, setIsTouch] = useState(detectTouchDevice);
551
+ useEffect(() => {
552
+ setIsTouch(detectTouchDevice());
553
+ }, []);
554
+ const touchEnabled = showTouchControls ?? isTouch;
555
+ useEffect(() => {
556
+ const sync = () => {
557
+ const { line, prompt } = formatHudStrings(world);
558
+ const fullPrompt = extraPrompt ? `${prompt} · ${extraPrompt}` : prompt;
559
+ if (telemetryRef.current) telemetryRef.current.textContent = line;
560
+ if (promptRef.current) promptRef.current.textContent = fullPrompt;
561
+ };
562
+ sync();
563
+ const id = window.setInterval(sync, 66);
564
+ return () => window.clearInterval(id);
565
+ }, [world, extraPrompt]);
566
+ return /* @__PURE__ */ jsx(KolmoHudView, {
567
+ telemetryRef,
568
+ promptRef,
569
+ touchEnabled,
570
+ style
571
+ });
1186
572
  }
1187
- function KolmoOverlayHost({ store }) {
1188
- const entries = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);
1189
- if (entries.length === 0) return null;
1190
- return /* @__PURE__ */ jsx(Fragment, { children: entries.map(([id, node]) => /* @__PURE__ */ jsx(React.Fragment, { children: node }, id)) });
573
+ function KolmoHud(props) {
574
+ return useContext(KolmoInCanvasContext) ? /* @__PURE__ */ jsx(KolmoHudInCanvas, { ...props }) : /* @__PURE__ */ jsx(KolmoHudOutsideCanvas, { ...props });
1191
575
  }
1192
576
  function KolmoGame({ gravity = "planar", skybox = "day", lighting = "default", fogExp2, paused = false, timeScale = 1, maxDelta, physicsDebug = false, dpr, roomEnv = .65, kootaWorld = kolmoWorld, style, className, children }) {
1193
577
  const outerWorld = useOptionalKootaWorld();
1194
- const store = useMemo(createOverlayStore, []);
1195
- const shell = /* @__PURE__ */ jsx(KolmoOverlayContext.Provider, {
1196
- value: store.set,
578
+ const [overlayEl, setOverlayEl] = useState(null);
579
+ const shell = /* @__PURE__ */ jsx(KolmoOverlayPortalContext.Provider, {
580
+ value: overlayEl,
1197
581
  children: /* @__PURE__ */ jsxs("div", {
1198
582
  className,
1199
583
  style: {
@@ -1220,51 +604,64 @@ function KolmoGame({ gravity = "planar", skybox = "day", lighting = "default", f
1220
604
  world: kootaWorld,
1221
605
  children
1222
606
  })
1223
- }), /* @__PURE__ */ jsx(KolmoOverlayHost, { store })]
607
+ }), /* @__PURE__ */ jsx("div", {
608
+ ref: setOverlayEl,
609
+ style: {
610
+ position: "absolute",
611
+ inset: 0,
612
+ pointerEvents: "none"
613
+ }
614
+ })]
1224
615
  })
1225
616
  });
1226
- return kootaWorld !== outerWorld ? /* @__PURE__ */ jsx(WorldProvider, {
1227
- world: kootaWorld,
1228
- children: shell
617
+ return kootaWorld !== outerWorld ? /* @__PURE__ */ jsx(KolmoWorldContext.Provider, {
618
+ value: kootaWorld,
619
+ children: /* @__PURE__ */ jsx(WorldProvider, {
620
+ world: kootaWorld,
621
+ children: shell
622
+ })
1229
623
  }) : shell;
1230
624
  }
1231
625
  // src/engine/gltfLoader.ts
1232
- var sharedKtx2Loader = null;
1233
- var sharedKtx2Path = "";
1234
- function getOrCreateKtx2Loader(renderer, transcoderPath) {
1235
- if (!sharedKtx2Loader || sharedKtx2Path !== transcoderPath) {
1236
- sharedKtx2Loader?.dispose();
1237
- sharedKtx2Loader = new KTX2Loader();
1238
- sharedKtx2Loader.setTranscoderPath(transcoderPath);
1239
- sharedKtx2Path = transcoderPath;
626
+ var ktx2ByRenderer = /* @__PURE__ */ new WeakMap();
627
+ function getScopedKtx2Loader(renderer, transcoderPath) {
628
+ let byPath = ktx2ByRenderer.get(renderer);
629
+ if (!byPath) {
630
+ byPath = /* @__PURE__ */ new Map();
631
+ ktx2ByRenderer.set(renderer, byPath);
1240
632
  }
1241
- sharedKtx2Loader.detectSupport(renderer);
1242
- return sharedKtx2Loader;
633
+ let ktx2 = byPath.get(transcoderPath);
634
+ if (!ktx2) {
635
+ ktx2 = new KTX2Loader();
636
+ ktx2.setTranscoderPath(transcoderPath);
637
+ ktx2.detectSupport(renderer);
638
+ byPath.set(transcoderPath, ktx2);
639
+ }
640
+ return ktx2;
1243
641
  }
1244
642
  /**
1245
- * Khronos-compliant `GLTFLoader` configured with `EXT_meshopt_compression` (`MeshoptDecoder`),
1246
- * `KHR_texture_basisu` (`KTX2Loader` when a renderer is supplied), and `@khr3/core` physics plugin.
1247
- * Never mounts legacy `DRACOLoader`.
643
+ * Khronos-compliant `GLTFLoader` configured with `EXT_meshopt_compression` (`MeshoptDecoder`)
644
+ * and `KHR_texture_basisu` (`KTX2Loader` when a renderer is supplied).
1248
645
  */
1249
646
  function createKolmoGltfLoader(options) {
1250
647
  const loader = new GLTFLoader();
1251
648
  loader.setMeshoptDecoder(MeshoptDecoder);
1252
- loader.register(createKhrGltfPlugin(options?.khrOptions));
1253
- if (options?.renderer) loader.setKTX2Loader(getOrCreateKtx2Loader(options.renderer, options.basisTranscoderPath ?? "/basis/"));
649
+ if (options?.renderer) loader.setKTX2Loader(getScopedKtx2Loader(options.renderer, options.basisTranscoderPath ?? "/basis/"));
1254
650
  return loader;
1255
651
  }
1256
652
  async function parseKolmoGlbBuffer(buffer, options) {
1257
- if (buffer.byteLength < 12) throw new Error("Invalid binary .glb buffer: truncated header (< 12 bytes).");
1258
- const view = new DataView(buffer);
1259
- if (view.getUint32(0, true) !== 0x46546c67 || view.getUint32(4, true) !== 2) throw new Error("Invalid binary .glb magic or glTF version (expected glTF 2.0).");
1260
- if (typeof MeshoptDecoder.ready?.then === "function") await MeshoptDecoder.ready;
1261
- return (await createKolmoGltfLoader(options).parseAsync(buffer, "")).scene;
653
+ await MeshoptDecoder.ready;
654
+ const loader = createKolmoGltfLoader(options);
655
+ return loadKhrGlb(buffer, {
656
+ ...options?.khrOptions,
657
+ loader
658
+ });
1262
659
  }
1263
660
  async function loadKolmoGlbUrl(url, options) {
1264
661
  const res = await fetch(url);
1265
662
  if (!res.ok) throw new Error(`Failed to fetch GLB (${res.status}): ${url}`);
1266
663
  return parseKolmoGlbBuffer(await res.arrayBuffer(), options);
1267
664
  }
1268
- export { ActorTrait, EMPTY_KOLMO_INPUT, G_SI, InteractableTrait, KOLMO_KEY_MAP, KOLMO_STICK_DEADZONE, KolmoActor, KolmoCanvas, KolmoGame, KolmoGravityContext, KolmoHud, KolmoInCanvasContext, KolmoKeyboardBridge, KolmoKeyboardContext, KolmoOverlayContext, KolmoPhysics, KolmoProp, KolmoSurface, KolmoVehicle, KolmoWorld, PilotLink, PilotedTag, RoomEnvRig, TransformTrait, VehicleTelemetryTrait, VehicleTrait, VelocityTrait, WorldSessionTrait, computeCircularOrbitSpeed, createKolmoGltfLoader, createNBodyGravityField, ensureWorldSession, evaluateNBodyGravity, flipVehicleBodyUpright, kolmoActions, kolmoWorld, loadKolmoGlbUrl, parseKolmoGlbBuffer, pilotedVehicleQuery, resolveAttractorMu, togglePropJoint, useActiveKolmoWorld, useIsKolmoCustomGravity, useKolmoGame, useKolmoInput, useOptionalKootaWorld, vehicleSimQuery, writeEntityKinematics, writeVehicleTelemetry };
665
+ export { ActorTrait, EMPTY_KOLMO_INPUT, G_SI, InteractableTrait, KOLMO_KEY_MAP, KOLMO_STICK_DEADZONE, KolmoActor, KolmoCanvas, KolmoGame, KolmoGravityContext, KolmoHud, KolmoInCanvasContext, KolmoKeyboardBridge, KolmoKeyboardContext, KolmoOverlayPortalContext, KolmoPhysics, KolmoProp, KolmoSurface, KolmoVehicle, KolmoWorld, KolmoWorldContext, PilotLink, PilotedTag, RoomEnvRig, TransformTrait, VehicleTelemetryTrait, VehicleTrait, VelocityTrait, WorldSessionTrait, computeCircularOrbitSpeed, createEmptyVehicleCmd, createKolmoGltfLoader, createNBodyGravityField, ensureWorldSession, evaluateNBodyGravity, evaluatePreparedNBodyGravity, flipVehicleBodyUpright, kolmoActions, kolmoWorld, loadKolmoGlbUrl, parseKolmoGlbBuffer, pilotedVehicleQuery, prepareAttractors, resolveAttractorMu, useActiveKolmoWorld, useIsKolmoCustomGravity, useKolmoGame, useKolmoInput, useOptionalKootaWorld, vehicleSimQuery, writeEntityKinematics, writeVehicleTelemetry };
1269
666
 
1270
667
  //# sourceMappingURL=index.js.map