@pinkaphant/kolmo 0.5.0 → 0.5.2

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.
@@ -0,0 +1,1020 @@
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, b as WorldSessionTrait, d as ActorTrait, f as InteractableTrait, g as TransformTrait, h as PilotedTag, j as writeVehicleTelemetry, m as PilotLink, n as KolmoPhysics, p as KolmoWorldContext, t as KolmoGravityContext, v as VehicleTrait, w as kolmoActions, x as createEmptyVehicleCmd, y as VelocityTrait } from "./physics-CA1abDCY.js";
2
+ import React, { createContext, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useReducer, useRef, useState } from "react";
3
+ import * as THREE from "three";
4
+ import "koota";
5
+ import { KeyboardControls, useKeyboardControls } from "@react-three/drei";
6
+ import { Joystick, VirtualButton, useButtonStore, useJoystickStore } from "@pinkaphant/ecctrl/input";
7
+ import { Canvas, addEffect, useFrame, useThree } from "@react-three/fiber";
8
+ import { CuboidCollider, RigidBody, useRapier } from "@react-three/rapier";
9
+ import { WorldProvider, useHas } from "koota/react";
10
+ import { KhrAssembly, assignRef, cloneKhrBundle, useKhrGlb } from "@khr3/core";
11
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
+ import { easing } from "maath";
13
+ import { KhrVehicle } from "@khr3/core/vehicle";
14
+ import { createPortal as createPortal$1 } from "react-dom";
15
+ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
16
+ // src/engine/input.ts
17
+ var KolmoKeyboardContext = createContext(null);
18
+ function KolmoKeyboardBridge({ children }) {
19
+ const [, getKeys] = useKeyboardControls();
20
+ return React.createElement(KolmoKeyboardContext.Provider, { value: getKeys }, children);
21
+ }
22
+ var KOLMO_STICK_DEADZONE = .08;
23
+ var EMPTY_KEYS = Object.freeze({
24
+ forward: false,
25
+ backward: false,
26
+ left: false,
27
+ right: false,
28
+ brake: false,
29
+ boost: false,
30
+ interact: false,
31
+ turnLeft: false,
32
+ turnRight: false,
33
+ descend: false,
34
+ cameraView: false,
35
+ reset: false,
36
+ modeToggle: false
37
+ });
38
+ var EMPTY_KOLMO_INPUT = Object.freeze({
39
+ ...EMPTY_KEYS,
40
+ stickX: 0,
41
+ stickY: 0
42
+ });
43
+ var KOLMO_KEY_MAP = [
44
+ {
45
+ name: "forward",
46
+ keys: ["KeyW", "ArrowUp"]
47
+ },
48
+ {
49
+ name: "backward",
50
+ keys: ["KeyS", "ArrowDown"]
51
+ },
52
+ {
53
+ name: "left",
54
+ keys: ["KeyA", "ArrowLeft"]
55
+ },
56
+ {
57
+ name: "right",
58
+ keys: ["KeyD", "ArrowRight"]
59
+ },
60
+ {
61
+ name: "brake",
62
+ keys: ["Space"]
63
+ },
64
+ {
65
+ name: "boost",
66
+ keys: ["ShiftLeft", "ShiftRight"]
67
+ },
68
+ {
69
+ name: "interact",
70
+ keys: ["KeyF"]
71
+ },
72
+ {
73
+ name: "turnLeft",
74
+ keys: ["KeyQ"]
75
+ },
76
+ {
77
+ name: "turnRight",
78
+ keys: ["KeyC"]
79
+ },
80
+ {
81
+ name: "descend",
82
+ keys: ["KeyX", "ControlLeft"]
83
+ },
84
+ {
85
+ name: "cameraView",
86
+ keys: ["KeyV"]
87
+ },
88
+ {
89
+ name: "reset",
90
+ keys: ["KeyR"]
91
+ },
92
+ {
93
+ name: "modeToggle",
94
+ keys: ["KeyG"]
95
+ }
96
+ ];
97
+ /**
98
+ * Input reader merging Drei `<KeyboardControls>`, `@pinkaphant/ecctrl/input`
99
+ * Zustand stores (`useJoystickStore` + `useButtonStore`), and optional `getInput()` overrides.
100
+ * Analog thumbstick values stay analog (`stickX`, `stickY`) rather than slamming digital WASD booleans.
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_KEYS;
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 scaled = mag > .08 ? (Math.min(1, mag) - KOLMO_STICK_DEADZONE) / (.92 * mag) : 0;
116
+ const out = outRef.current;
117
+ out.stickX = custom?.stickX ?? rx * scaled;
118
+ out.stickY = custom?.stickY ?? ry * scaled;
119
+ out.forward = Boolean(custom?.forward ?? k.forward);
120
+ out.backward = Boolean(custom?.backward ?? k.backward);
121
+ out.left = Boolean(custom?.left ?? k.left);
122
+ out.right = Boolean(custom?.right ?? k.right);
123
+ out.brake = Boolean(custom?.brake ?? (k.brake || btns.brake || btns.jump));
124
+ out.boost = Boolean(custom?.boost ?? (k.boost || btns.boost || btns.run));
125
+ out.interact = Boolean(custom?.interact ?? (k.interact || btns.interact));
126
+ out.turnLeft = Boolean(custom?.turnLeft ?? (k.turnLeft || btns.turnLeft));
127
+ out.turnRight = Boolean(custom?.turnRight ?? (k.turnRight || btns.turnRight));
128
+ out.descend = Boolean(custom?.descend ?? (k.descend || btns.descend));
129
+ out.cameraView = Boolean(custom?.cameraView ?? (k.cameraView || btns.cameraView));
130
+ out.reset = Boolean(custom?.reset ?? (k.reset || btns.reset));
131
+ out.modeToggle = Boolean(custom?.modeToggle ?? (k.modeToggle || btns.modeToggle));
132
+ return out;
133
+ }, [getKeyboard]);
134
+ }
135
+ // src/engine/vehicle.tsx
136
+ function hasActiveCmd(c) {
137
+ 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));
138
+ }
139
+ function clearCmdInPlace(cmd, stickL, stickR) {
140
+ cmd.forward = false;
141
+ cmd.backward = false;
142
+ cmd.steerLeft = false;
143
+ cmd.steerRight = false;
144
+ cmd.brake = false;
145
+ cmd.throttleUp = false;
146
+ cmd.throttleDown = false;
147
+ cmd.yawLeft = false;
148
+ cmd.yawRight = false;
149
+ cmd.pitchForward = false;
150
+ cmd.pitchBackward = false;
151
+ cmd.rollLeft = false;
152
+ cmd.rollRight = false;
153
+ stickL.x = 0;
154
+ stickL.y = 0;
155
+ stickR.x = 0;
156
+ stickR.y = 0;
157
+ cmd.joystickL = stickL;
158
+ cmd.joystickR = stickR;
159
+ }
160
+ var _up = new THREE.Vector3();
161
+ var _fwd = new THREE.Vector3();
162
+ var _camGoal = new THREE.Vector3();
163
+ var _lookGoal = new THREE.Vector3();
164
+ function KolmoVehicleMount({ ref, vehicleRef, jointsRef: outerJointsRef, id, sourceBundle, alreadyCloned = false, piloted = false, flightMode = false, vehicleMode, interactRadius = 4.2, enable = true, enableCustomGravity, carConfig, wheelConfig, propellerConfig, droneConfig, getInput, driver, cameraController, children, ...khrRest }) {
165
+ const ctxCustomGravity = useContext(KolmoGravityContext);
166
+ const activeWorld = useActiveKolmoWorld();
167
+ useLayoutEffect(() => {
168
+ ensureWorldSession(activeWorld);
169
+ }, [activeWorld]);
170
+ const readInput = useKolmoInput(getInput);
171
+ const bundle = useMemo(() => alreadyCloned ? sourceBundle : cloneKhrBundle(sourceBundle), [sourceBundle, alreadyCloned]);
172
+ const jointsRef = useRef(null);
173
+ const innerRef = useRef(null);
174
+ const canHybridToggle = vehicleMode === void 0 && bundle.wheels.length > 0 && bundle.propellers.length > 0;
175
+ const [hybridFlight, setHybridFlight] = useState(flightMode);
176
+ useLayoutEffect(() => {
177
+ setHybridFlight(flightMode);
178
+ }, [flightMode]);
179
+ const [boostThrustActive, setBoostThrustActive] = useState(false);
180
+ const boostThrustRef = useRef(false);
181
+ const isFlight = Boolean(vehicleMode === "rocket" || (canHybridToggle ? hybridFlight : flightMode) || vehicleMode !== "drive" && bundle.propellers.length > 0 && bundle.wheels.length === 0);
182
+ const isManualTrans = (carConfig?.transmissionMode ?? bundle.tune?.transmissionMode) === "manual";
183
+ const seatOffset = useMemo(() => {
184
+ const dot = bundle.sockets.IK_Seat ?? bundle.sockets.seat ?? bundle.sockets.driver_butt ?? bundle.sockets.butt;
185
+ return dot ? [
186
+ dot[0],
187
+ dot[1],
188
+ dot[2]
189
+ ] : [
190
+ 0,
191
+ .65,
192
+ 0
193
+ ];
194
+ }, [bundle.sockets]);
195
+ const exitOffset = useMemo(() => {
196
+ const dot = bundle.sockets.Socket_Exit ?? bundle.sockets.exit;
197
+ return dot ? [
198
+ dot[0],
199
+ dot[1],
200
+ dot[2]
201
+ ] : [
202
+ -1.55,
203
+ .45,
204
+ 0
205
+ ];
206
+ }, [bundle.sockets]);
207
+ const propActive = bundle.propellers.length > 0 && (isFlight || vehicleMode !== "drive" && boostThrustActive);
208
+ const mergedWheelConfig = useMemo(() => {
209
+ const wheelOverride = bundle.wheels.length > 0 && vehicleMode === "rocket" ? { enable: false } : void 0;
210
+ return !wheelConfig && !wheelOverride ? void 0 : {
211
+ ...wheelOverride,
212
+ ...wheelConfig ?? {}
213
+ };
214
+ }, [
215
+ bundle.wheels.length,
216
+ vehicleMode,
217
+ wheelConfig
218
+ ]);
219
+ const mergedPropellerConfig = useMemo(() => {
220
+ const propOverride = bundle.propellers.length > 0 && !propActive ? { enable: false } : void 0;
221
+ return !propellerConfig && !propOverride ? void 0 : {
222
+ ...propOverride,
223
+ ...propellerConfig ?? {}
224
+ };
225
+ }, [
226
+ bundle.propellers.length,
227
+ propActive,
228
+ propellerConfig
229
+ ]);
230
+ const [vehEnt, setVehEnt] = useState(null);
231
+ const vehEntRef = useRef(null);
232
+ const camTargetRef = useRef(new THREE.Vector3());
233
+ const stickLRef = useRef({
234
+ x: 0,
235
+ y: 0
236
+ });
237
+ const stickRRef = useRef({
238
+ x: 0,
239
+ y: 0
240
+ });
241
+ const cmdRef = useRef(createEmptyVehicleCmd(false));
242
+ const stRef = useRef({
243
+ camInit: false,
244
+ cockpit: false,
245
+ prevCam: false,
246
+ prevReset: false,
247
+ prevMode: false,
248
+ wasPiloted: false
249
+ });
250
+ useLayoutEffect(() => {
251
+ const ent = activeWorld.spawn(VehicleTrait({
252
+ id,
253
+ handle: innerRef.current,
254
+ jointsHandle: jointsRef.current,
255
+ seatOffset,
256
+ exitOffset,
257
+ isFlight
258
+ }), InteractableTrait({
259
+ id,
260
+ radius: interactRadius,
261
+ kind: "vehicle"
262
+ }), TransformTrait, VelocityTrait, VehicleTelemetryTrait);
263
+ vehEntRef.current = ent;
264
+ setVehEnt(ent);
265
+ if (piloted && !activeWorld.queryFirst(pilotedVehicleQuery)) kolmoActions(activeWorld).boardVehicle(id);
266
+ return () => {
267
+ if (ent.isAlive() && ent.has(PilotedTag)) kolmoActions(activeWorld).exitVehicle();
268
+ vehEntRef.current = null;
269
+ ent.destroy();
270
+ };
271
+ }, [activeWorld, id]);
272
+ useLayoutEffect(() => {
273
+ const ent = vehEntRef.current;
274
+ if (!ent?.isAlive()) return;
275
+ const v = ent.get(VehicleTrait);
276
+ if (v) ent.set(VehicleTrait, {
277
+ ...v,
278
+ seatOffset,
279
+ exitOffset,
280
+ isFlight
281
+ });
282
+ ent.set(InteractableTrait, {
283
+ id,
284
+ radius: interactRadius,
285
+ kind: "vehicle"
286
+ });
287
+ }, [
288
+ id,
289
+ seatOffset,
290
+ exitOffset,
291
+ interactRadius,
292
+ isFlight
293
+ ]);
294
+ const assignVehicleRef = useCallback((handle) => {
295
+ innerRef.current = handle;
296
+ assignRef(vehicleRef, handle);
297
+ assignRef(ref, handle);
298
+ const ent = vehEntRef.current;
299
+ if (ent?.isAlive()) {
300
+ const v = ent.get(VehicleTrait);
301
+ if (v) ent.set(VehicleTrait, {
302
+ ...v,
303
+ handle
304
+ });
305
+ }
306
+ }, [ref, vehicleRef]);
307
+ const assignJointsRef = useCallback((jh) => {
308
+ jointsRef.current = jh;
309
+ assignRef(outerJointsRef, jh);
310
+ const ent = vehEntRef.current;
311
+ if (ent?.isAlive()) {
312
+ const v = ent.get(VehicleTrait);
313
+ if (v) ent.set(VehicleTrait, {
314
+ ...v,
315
+ jointsHandle: jh
316
+ });
317
+ }
318
+ }, [outerJointsRef]);
319
+ const { world: rapierWorld } = useRapier();
320
+ const isPiloted = useHas(vehEnt, PilotedTag) || piloted && vehEnt === null;
321
+ const recordKinematicsAndTelemetry = (veh, throttle, boost) => {
322
+ if (!vehEntRef.current?.isAlive()) return;
323
+ let maxSlip = 0;
324
+ for (const w of veh.wheelsInfo.values()) if (w.current.rayHit && w.current.slipStrength > maxSlip) maxSlip = w.current.slipStrength;
325
+ writeEntityKinematics(activeWorld, vehEntRef.current, veh.currPos, veh.currQuat, veh.currLinVel, veh.currLinVel.length() * 3.6);
326
+ writeVehicleTelemetry(activeWorld, vehEntRef.current, Math.round(veh.engineRPM), veh.gearIndex + 1, throttle, boost, Math.min(1, maxSlip));
327
+ };
328
+ useFrame((state, delta) => {
329
+ const dt = rapierWorld.timestep > 0 ? rapierWorld.timestep : Math.min(Math.max(delta, 1e-4), 1 / 30);
330
+ const veh = innerRef.current;
331
+ if (!veh?.body) return;
332
+ if (driver) {
333
+ driver(veh, dt, state);
334
+ recordKinematicsAndTelemetry(veh, 0, 0);
335
+ cameraController?.(veh, dt, state);
336
+ return;
337
+ }
338
+ const keys = readInput();
339
+ const st = stRef.current;
340
+ const cmd = cmdRef.current;
341
+ const stickL = stickLRef.current;
342
+ const stickR = stickRRef.current;
343
+ const wantBoostProp = isPiloted && !isFlight && vehicleMode !== "drive" && bundle.propellers.length > 0 && keys.boost && (keys.forward || keys.brake);
344
+ if (wantBoostProp !== boostThrustRef.current) {
345
+ boostThrustRef.current = wantBoostProp;
346
+ setBoostThrustActive(wantBoostProp);
347
+ }
348
+ if (isPiloted) {
349
+ st.wasPiloted = true;
350
+ if (keys.cameraView && !st.prevCam) st.cockpit = !st.cockpit;
351
+ st.prevCam = keys.cameraView;
352
+ if (keys.reset && !st.prevReset) flipVehicleBodyUpright(veh, jointsRef.current);
353
+ st.prevReset = keys.reset;
354
+ if (keys.modeToggle && !st.prevMode && canHybridToggle) setHybridFlight((f) => !f);
355
+ st.prevMode = keys.modeToggle;
356
+ let anyGrounded = false;
357
+ for (const w of veh.wheelsInfo.values()) if (w.current.rayHit) {
358
+ anyGrounded = true;
359
+ break;
360
+ }
361
+ if (isFlight) {
362
+ cmd.pitchForward = keys.forward;
363
+ cmd.pitchBackward = keys.backward;
364
+ cmd.yawLeft = keys.left;
365
+ cmd.yawRight = keys.right;
366
+ cmd.rollLeft = keys.turnLeft;
367
+ cmd.rollRight = keys.turnRight;
368
+ cmd.throttleUp = keys.brake;
369
+ cmd.throttleDown = keys.descend;
370
+ cmd.forward = anyGrounded && keys.forward;
371
+ cmd.backward = anyGrounded && keys.backward;
372
+ cmd.steerLeft = anyGrounded && keys.left;
373
+ cmd.steerRight = anyGrounded && keys.right;
374
+ cmd.brake = false;
375
+ stickL.x = 0;
376
+ stickL.y = 0;
377
+ stickR.x = keys.stickX;
378
+ stickR.y = keys.stickY;
379
+ cmd.joystickL = stickL;
380
+ cmd.joystickR = stickR;
381
+ veh.setMovement(cmd);
382
+ } else {
383
+ const fwdVel = veh.currLinVel.dot(veh.bodyZAxis);
384
+ const effForward = keys.forward || keys.stickY > .15;
385
+ const effBackward = keys.backward || keys.stickY < -.15;
386
+ const revBraking = effBackward && !effForward && fwdVel > 1;
387
+ const fwdBraking = effForward && !effBackward && fwdVel < -1;
388
+ if (!isManualTrans && (effBackward && !revBraking || effForward && Math.abs(fwdVel) < 2.5) && veh.gearIndex !== 0) veh.setGear(0);
389
+ const boostProp = keys.boost && (bundle.propellers.length > 0 || veh.propellersInfo.size > 0) && veh.gravityMag > 1e-4;
390
+ cmd.forward = effForward && !fwdBraking;
391
+ cmd.backward = effBackward && !revBraking;
392
+ cmd.steerLeft = keys.left;
393
+ cmd.steerRight = keys.right;
394
+ cmd.brake = keys.brake || revBraking || fwdBraking;
395
+ cmd.pitchForward = boostProp && effForward;
396
+ cmd.pitchBackward = false;
397
+ cmd.throttleUp = boostProp && !effForward && keys.brake;
398
+ cmd.throttleDown = false;
399
+ cmd.yawLeft = boostProp && keys.left;
400
+ cmd.yawRight = boostProp && keys.right;
401
+ cmd.rollLeft = false;
402
+ cmd.rollRight = false;
403
+ stickL.x = keys.stickX;
404
+ stickL.y = 0;
405
+ stickR.x = 0;
406
+ stickR.y = 0;
407
+ cmd.joystickL = stickL;
408
+ cmd.joystickR = stickR;
409
+ veh.setMovement(cmd);
410
+ }
411
+ } else {
412
+ st.prevCam = st.prevReset = st.prevMode = false;
413
+ if (st.wasPiloted || hasActiveCmd(cmd)) {
414
+ st.wasPiloted = false;
415
+ clearCmdInPlace(cmd, stickL, stickR);
416
+ veh.setMovement(cmd);
417
+ }
418
+ }
419
+ const throttle = isPiloted ? +(keys.forward || keys.stickY > .15 || isFlight && keys.brake) : 0;
420
+ const boost = isPiloted && keys.boost && throttle > 0 ? 1 : 0;
421
+ recordKinematicsAndTelemetry(veh, throttle, boost);
422
+ if (!isPiloted) return;
423
+ if (cameraController) {
424
+ cameraController(veh, dt, state);
425
+ return;
426
+ }
427
+ _up.copy(veh.upAxis);
428
+ if (_up.lengthSq() < 1e-6) _up.copy(veh.bodyYAxis);
429
+ if (st.cockpit) {
430
+ _camGoal.set(seatOffset[0], seatOffset[1] + .32, seatOffset[2]).applyQuaternion(veh.currQuat).add(veh.currPos);
431
+ _lookGoal.copy(_camGoal).addScaledVector(veh.bodyZAxis, 24);
432
+ easing.damp3(state.camera.position, _camGoal, .04, dt);
433
+ easing.damp3(state.camera.up, veh.bodyYAxis, .08, dt);
434
+ state.camera.lookAt(_lookGoal);
435
+ return;
436
+ }
437
+ _fwd.copy(veh.bodyZAxis);
438
+ if (!isFlight) _fwd.projectOnPlane(_up).normalize();
439
+ if (_fwd.lengthSq() < 1e-6) _fwd.copy(veh.bodyZAxis);
440
+ _camGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? -11.2 : -6.8).addScaledVector(_up, isFlight ? 3.1 : 2.15);
441
+ _lookGoal.copy(veh.currPos).addScaledVector(_fwd, isFlight ? 7.5 : 3.6).addScaledVector(_up, .65);
442
+ if (!st.camInit) {
443
+ state.camera.position.copy(_camGoal);
444
+ camTargetRef.current.copy(_lookGoal);
445
+ st.camInit = true;
446
+ }
447
+ easing.damp3(state.camera.position, _camGoal, .14, dt);
448
+ easing.damp3(camTargetRef.current, _lookGoal, .08, dt);
449
+ easing.damp3(state.camera.up, _up, .16, dt);
450
+ state.camera.lookAt(camTargetRef.current);
451
+ });
452
+ return /* @__PURE__ */ jsx(KhrVehicle, {
453
+ ref: assignVehicleRef,
454
+ jointsRef: assignJointsRef,
455
+ bundle,
456
+ enable,
457
+ enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
458
+ ...carConfig === void 0 ? {} : { carConfig },
459
+ ...mergedWheelConfig === void 0 ? {} : { wheelConfig: mergedWheelConfig },
460
+ ...mergedPropellerConfig === void 0 ? {} : { propellerConfig: mergedPropellerConfig },
461
+ ...droneConfig === void 0 ? {} : { droneConfig },
462
+ ...khrRest,
463
+ children
464
+ });
465
+ }
466
+ function KolmoVehicleFromUrl(props) {
467
+ const { src, ...rest } = props;
468
+ const bundle = useKhrGlb(src);
469
+ return /* @__PURE__ */ jsx(KolmoVehicleMount, {
470
+ ...rest,
471
+ sourceBundle: bundle,
472
+ alreadyCloned: true
473
+ });
474
+ }
475
+ function KolmoVehicle(props) {
476
+ const reactId = useId();
477
+ const id = props.id ?? `vehicle_${reactId.replace(/:/g, "")}`;
478
+ const { src, bundle, ...rest } = props;
479
+ if (bundle) return /* @__PURE__ */ jsx(KolmoVehicleMount, {
480
+ ...rest,
481
+ id,
482
+ sourceBundle: bundle
483
+ });
484
+ if (src) return /* @__PURE__ */ jsx(KolmoVehicleFromUrl, {
485
+ ...rest,
486
+ id,
487
+ src
488
+ });
489
+ return null;
490
+ }
491
+ // src/engine/surface.tsx
492
+ function ArenaSlab({ size, position, color = "#252b36" }) {
493
+ const res = useMemo(() => ({
494
+ geo: new THREE.BoxGeometry(size, 1, size),
495
+ mat: new THREE.MeshStandardMaterial({
496
+ color,
497
+ roughness: .9,
498
+ metalness: .05
499
+ })
500
+ }), [size, color]);
501
+ useEffect(() => () => {
502
+ res.geo.dispose();
503
+ res.mat.dispose();
504
+ }, [res]);
505
+ return /* @__PURE__ */ jsxs(RigidBody, {
506
+ type: "fixed",
507
+ colliders: false,
508
+ position: [
509
+ position[0],
510
+ position[1] - .5,
511
+ position[2]
512
+ ],
513
+ friction: .9,
514
+ children: [/* @__PURE__ */ jsx(CuboidCollider, {
515
+ args: [
516
+ size * .5,
517
+ .5,
518
+ size * .5
519
+ ],
520
+ restitution: .04
521
+ }), /* @__PURE__ */ jsx("mesh", {
522
+ geometry: res.geo,
523
+ material: res.mat,
524
+ receiveShadow: true
525
+ })]
526
+ });
527
+ }
528
+ function BundleSurface({ ref, bundle, alreadyCloned = false, position, enableCustomGravity, ...rest }) {
529
+ const ctxCustomGravity = useContext(KolmoGravityContext);
530
+ const cloned = useMemo(() => alreadyCloned ? bundle : cloneKhrBundle(bundle), [bundle, alreadyCloned]);
531
+ return /* @__PURE__ */ jsx(KhrAssembly, {
532
+ ref,
533
+ bundle: cloned,
534
+ position,
535
+ fixedRoot: true,
536
+ enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
537
+ ...rest
538
+ });
539
+ }
540
+ function UrlSurface({ src, ...rest }) {
541
+ const bundle = useKhrGlb(src);
542
+ return /* @__PURE__ */ jsx(BundleSurface, {
543
+ bundle,
544
+ alreadyCloned: true,
545
+ ...rest
546
+ });
547
+ }
548
+ function KolmoSurface({ ref, src, bundle, size = 200, color, position = [
549
+ 0,
550
+ 0,
551
+ 0
552
+ ], ...rest }) {
553
+ if (bundle) return /* @__PURE__ */ jsx(BundleSurface, {
554
+ ref,
555
+ bundle,
556
+ position,
557
+ ...rest
558
+ });
559
+ if (src) return /* @__PURE__ */ jsx(UrlSurface, {
560
+ ref,
561
+ src,
562
+ position,
563
+ ...rest
564
+ });
565
+ return /* @__PURE__ */ jsx(ArenaSlab, {
566
+ size,
567
+ position,
568
+ color
569
+ });
570
+ }
571
+ function BundleProp({ ref, bundle, alreadyCloned = false, fixed = false, enableCustomGravity, onClick: userOnClick, ...rest }) {
572
+ const ctxCustomGravity = useContext(KolmoGravityContext);
573
+ const asmRef = useRef(null);
574
+ const cloned = useMemo(() => alreadyCloned ? bundle : cloneKhrBundle(bundle), [bundle, alreadyCloned]);
575
+ const assignAsmRef = useCallback((h) => {
576
+ asmRef.current = h;
577
+ assignRef(ref, h);
578
+ }, [ref]);
579
+ const onClick = useCallback((e) => {
580
+ if (e.delta <= 5 && asmRef.current?.toggleHitObject(e.object)) e.stopPropagation();
581
+ userOnClick?.(e);
582
+ }, [userOnClick]);
583
+ return /* @__PURE__ */ jsx(KhrAssembly, {
584
+ ref: assignAsmRef,
585
+ bundle: cloned,
586
+ fixedRoot: fixed,
587
+ enableCustomGravity: enableCustomGravity ?? ctxCustomGravity,
588
+ onClick,
589
+ ...rest
590
+ });
591
+ }
592
+ function UrlProp({ src, ...rest }) {
593
+ const bundle = useKhrGlb(src);
594
+ return /* @__PURE__ */ jsx(BundleProp, {
595
+ bundle,
596
+ alreadyCloned: true,
597
+ ...rest
598
+ });
599
+ }
600
+ function KolmoProp({ src, bundle, ...rest }) {
601
+ if (bundle) return /* @__PURE__ */ jsx(BundleProp, {
602
+ bundle,
603
+ ...rest
604
+ });
605
+ if (src) return /* @__PURE__ */ jsx(UrlProp, {
606
+ src,
607
+ ...rest
608
+ });
609
+ return null;
610
+ }
611
+ // src/engine/world.tsx
612
+ var KolmoInCanvasContext = createContext(false);
613
+ var KolmoOverlayPortalContext = createContext(null);
614
+ function RoomEnvRig({ intensity = .65 }) {
615
+ const { gl, scene } = useThree();
616
+ useEffect(() => {
617
+ const pmrem = new THREE.PMREMGenerator(gl);
618
+ const room = new RoomEnvironment();
619
+ const rt = pmrem.fromScene(room, .04);
620
+ const prevEnv = scene.environment;
621
+ const prevInt = scene.environmentIntensity;
622
+ scene.environment = rt.texture;
623
+ scene.environmentIntensity = intensity;
624
+ room.dispose();
625
+ pmrem.dispose();
626
+ return () => {
627
+ scene.environment = prevEnv;
628
+ scene.environmentIntensity = prevInt;
629
+ rt.dispose();
630
+ };
631
+ }, [
632
+ gl,
633
+ scene,
634
+ intensity
635
+ ]);
636
+ return null;
637
+ }
638
+ function KolmoCanvas({ children, className, style, fov = 56, near = .15, far = 4e3, cameraPosition = [
639
+ 0,
640
+ 3.2,
641
+ -8.5
642
+ ], dpr = [1, 1.5], frameloop = "always", shadows = true, antialias = true, toneMapping, roomEnv = .65 }) {
643
+ return /* @__PURE__ */ jsxs(Canvas, {
644
+ className,
645
+ style: {
646
+ width: "100%",
647
+ height: "100%",
648
+ display: "block",
649
+ touchAction: "none",
650
+ userSelect: "none",
651
+ ...style
652
+ },
653
+ shadows,
654
+ dpr,
655
+ frameloop,
656
+ gl: {
657
+ antialias,
658
+ powerPreference: "high-performance",
659
+ ...toneMapping === void 0 ? {} : { toneMapping }
660
+ },
661
+ camera: {
662
+ fov,
663
+ near,
664
+ far,
665
+ position: cameraPosition
666
+ },
667
+ onCreated: ({ gl }) => {
668
+ gl.outputColorSpace = THREE.SRGBColorSpace;
669
+ },
670
+ children: [roomEnv !== false && /* @__PURE__ */ jsx(RoomEnvRig, { intensity: typeof roomEnv === "number" ? roomEnv : .65 }), children]
671
+ });
672
+ }
673
+ function KolmoWorld({ gravity = "planar", paused = false, timeScale = 1, maxDelta, physicsDebug = false, skybox = "day", lighting = "default", fogExp2, sunLightRef, world = kolmoWorld, keyboardMap = KOLMO_KEY_MAP, children }) {
674
+ const outerWorld = useOptionalKootaWorld();
675
+ const effectiveWorld = world ?? outerWorld ?? kolmoWorld;
676
+ useLayoutEffect(() => {
677
+ ensureWorldSession(effectiveWorld);
678
+ }, [effectiveWorld]);
679
+ const inner = /* @__PURE__ */ jsxs(KolmoInCanvasContext.Provider, {
680
+ value: true,
681
+ children: [
682
+ skybox === "day" && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("color", {
683
+ attach: "background",
684
+ args: ["#6ba6d6"]
685
+ }), !fogExp2 && /* @__PURE__ */ jsx("fog", {
686
+ attach: "fog",
687
+ args: [
688
+ "#9dc4e2",
689
+ 110,
690
+ 520
691
+ ]
692
+ })] }),
693
+ skybox === "night" && /* @__PURE__ */ jsx("color", {
694
+ attach: "background",
695
+ args: ["#090d16"]
696
+ }),
697
+ fogExp2 && /* @__PURE__ */ jsx("fogExp2", {
698
+ attach: "fog",
699
+ args: fogExp2
700
+ }),
701
+ lighting === "default" && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("hemisphereLight", { args: [
702
+ "#b8dcff",
703
+ "#241d30",
704
+ .8
705
+ ] }), /* @__PURE__ */ jsx("directionalLight", {
706
+ ref: sunLightRef,
707
+ position: [
708
+ 48,
709
+ 76,
710
+ 36
711
+ ],
712
+ intensity: 1.85,
713
+ color: "#fff3dc",
714
+ castShadow: true,
715
+ "shadow-mapSize": [2048, 2048],
716
+ "shadow-bias": -4e-4,
717
+ "shadow-camera-left": -55,
718
+ "shadow-camera-right": 55,
719
+ "shadow-camera-top": 55,
720
+ "shadow-camera-bottom": -55,
721
+ "shadow-camera-near": 1,
722
+ "shadow-camera-far": 220
723
+ })] }),
724
+ /* @__PURE__ */ jsx(KolmoPhysics, {
725
+ gravity,
726
+ paused,
727
+ timeScale,
728
+ maxDelta,
729
+ physicsDebug,
730
+ world: effectiveWorld,
731
+ children
732
+ })
733
+ ]
734
+ });
735
+ const withKeyboard = keyboardMap ? /* @__PURE__ */ jsx(KeyboardControls, {
736
+ map: keyboardMap,
737
+ children: /* @__PURE__ */ jsx(KolmoKeyboardBridge, { children: inner })
738
+ }) : /* @__PURE__ */ jsx(KolmoKeyboardContext.Provider, {
739
+ value: null,
740
+ children: inner
741
+ });
742
+ return effectiveWorld !== outerWorld ? /* @__PURE__ */ jsx(KolmoWorldContext.Provider, {
743
+ value: effectiveWorld,
744
+ children: /* @__PURE__ */ jsx(WorldProvider, {
745
+ world: effectiveWorld,
746
+ children: withKeyboard
747
+ })
748
+ }) : withKeyboard;
749
+ }
750
+ function useKolmoGame(explicitWorld) {
751
+ const active = useActiveKolmoWorld();
752
+ const targetWorld = explicitWorld ?? active;
753
+ const [, bump] = useReducer((x) => x + 1, 0);
754
+ useEffect(() => {
755
+ ensureWorldSession(targetWorld);
756
+ const onChange = () => bump();
757
+ const u1 = targetWorld.onChange(WorldSessionTrait, onChange);
758
+ const u2 = targetWorld.onAdd(PilotedTag, onChange);
759
+ const u3 = targetWorld.onRemove(PilotedTag, onChange);
760
+ const u4 = targetWorld.onAdd(PilotLink, onChange);
761
+ const u5 = targetWorld.onRemove(PilotLink, onChange);
762
+ const u6 = targetWorld.onChange(VehicleTrait, onChange);
763
+ return () => {
764
+ u1();
765
+ u2();
766
+ u3();
767
+ u4();
768
+ u5();
769
+ u6();
770
+ };
771
+ }, [targetWorld]);
772
+ const session = targetWorld.has(WorldSessionTrait) ? targetWorld.get(WorldSessionTrait) : void 0;
773
+ const pilotedData = (targetWorld.queryFirst(ActorTrait)?.targetFor(PilotLink) ?? targetWorld.queryFirst(pilotedVehicleQuery))?.get(VehicleTrait);
774
+ const actions = kolmoActions(targetWorld);
775
+ return {
776
+ world: targetWorld,
777
+ mode: pilotedData ? pilotedData.isFlight ? "flight" : "car" : "foot",
778
+ activeVehicleId: pilotedData?.id ?? "",
779
+ nearVehicleId: session?.nearVehicleId || null,
780
+ boardVehicle: actions.boardVehicle,
781
+ exitVehicle: actions.exitVehicle,
782
+ resetVehicle: actions.resetVehicle
783
+ };
784
+ }
785
+ function detectTouchDevice() {
786
+ if (typeof window === "undefined") return false;
787
+ return navigator.maxTouchPoints > 0 || window.matchMedia?.("(pointer: coarse)")?.matches === true;
788
+ }
789
+ function formatHudStrings(world) {
790
+ const actor = world.queryFirst(ActorTrait);
791
+ const vehEnt = actor?.targetFor(PilotLink) ?? world.queryFirst(pilotedVehicleQuery);
792
+ if (vehEnt) {
793
+ const vd = vehEnt.get(VehicleTrait);
794
+ const vel = vehEnt.get(VelocityTrait);
795
+ const tel = vehEnt.get(VehicleTelemetryTrait);
796
+ const kmh = Math.round(vel?.speedKmh ?? 0);
797
+ const rpm = Math.round(tel?.rpm ?? 0);
798
+ const gear = tel?.gear ?? 1;
799
+ return {
800
+ line: `${vd?.isFlight ? "Flight" : "Car"} · ${kmh} km/h · G${gear} · ${rpm} rpm`,
801
+ 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"
802
+ };
803
+ }
804
+ const vel = actor?.get(VelocityTrait);
805
+ const near = world.has(WorldSessionTrait) ? world.get(WorldSessionTrait)?.nearVehicleId : "";
806
+ return {
807
+ line: `On foot · ${Math.round(vel?.speedKmh ?? 0)} km/h`,
808
+ prompt: near ? "[F] Board vehicle · [WASD] Walk · [Shift] Sprint · [Space] Jump" : "[WASD] Walk · [Shift] Sprint · [Space] Jump"
809
+ };
810
+ }
811
+ function KolmoHudView({ telemetryRef, promptRef, touchEnabled, style }) {
812
+ return /* @__PURE__ */ jsxs("div", {
813
+ style: {
814
+ position: "fixed",
815
+ inset: 0,
816
+ pointerEvents: "none",
817
+ zIndex: 30,
818
+ fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace",
819
+ color: "#e6edf3",
820
+ ...style
821
+ },
822
+ children: [/* @__PURE__ */ jsx("div", {
823
+ ref: telemetryRef,
824
+ style: {
825
+ position: "absolute",
826
+ top: "max(10px, env(safe-area-inset-top))",
827
+ left: "max(12px, env(safe-area-inset-left))",
828
+ padding: "6px 10px",
829
+ background: "rgba(9, 13, 22, 0.82)",
830
+ border: "1px solid #38bdf8",
831
+ borderRadius: 4,
832
+ fontSize: 12,
833
+ fontWeight: 700
834
+ },
835
+ children: "On foot · 0 km/h"
836
+ }), !touchEnabled ? /* @__PURE__ */ jsx("div", {
837
+ ref: promptRef,
838
+ style: {
839
+ position: "absolute",
840
+ bottom: "max(12px, env(safe-area-inset-bottom))",
841
+ left: "50%",
842
+ transform: "translateX(-50%)",
843
+ padding: "5px 10px",
844
+ background: "rgba(9, 13, 22, 0.78)",
845
+ border: "1px solid rgba(255,255,255,0.16)",
846
+ borderRadius: 4,
847
+ fontSize: 11,
848
+ whiteSpace: "nowrap"
849
+ },
850
+ children: "[WASD] Walk · [Shift] Sprint · [Space] Jump"
851
+ }) : /* @__PURE__ */ jsxs("div", {
852
+ style: { pointerEvents: "auto" },
853
+ children: [
854
+ /* @__PURE__ */ jsx(Joystick, {}),
855
+ /* @__PURE__ */ jsx(VirtualButton, {
856
+ id: "jump",
857
+ label: "JMP",
858
+ buttonWrapperStyle: {
859
+ position: "fixed",
860
+ right: 20,
861
+ bottom: 24
862
+ }
863
+ }),
864
+ /* @__PURE__ */ jsx(VirtualButton, {
865
+ id: "boost",
866
+ label: "BST",
867
+ buttonWrapperStyle: {
868
+ position: "fixed",
869
+ right: 88,
870
+ bottom: 24
871
+ }
872
+ }),
873
+ /* @__PURE__ */ jsx(VirtualButton, {
874
+ id: "interact",
875
+ label: "USE",
876
+ buttonWrapperStyle: {
877
+ position: "fixed",
878
+ right: 20,
879
+ bottom: 92
880
+ }
881
+ })
882
+ ]
883
+ })]
884
+ });
885
+ }
886
+ function KolmoHudInCanvas({ showTouchControls, extraPrompt, style }) {
887
+ const portalTarget = useContext(KolmoOverlayPortalContext);
888
+ const world = useActiveKolmoWorld();
889
+ const telemetryRef = useRef(null);
890
+ const promptRef = useRef(null);
891
+ const elapsedRef = useRef(0);
892
+ const [isTouch, setIsTouch] = useState(detectTouchDevice);
893
+ useEffect(() => {
894
+ setIsTouch(detectTouchDevice());
895
+ }, []);
896
+ const touchEnabled = showTouchControls ?? isTouch;
897
+ useFrame((_, delta) => {
898
+ elapsedRef.current += delta;
899
+ if (elapsedRef.current < .05) return;
900
+ elapsedRef.current = 0;
901
+ const { line, prompt } = formatHudStrings(world);
902
+ const fullPrompt = extraPrompt ? `${prompt} · ${extraPrompt}` : prompt;
903
+ if (telemetryRef.current && telemetryRef.current.textContent !== line) telemetryRef.current.textContent = line;
904
+ if (promptRef.current && promptRef.current.textContent !== fullPrompt) promptRef.current.textContent = fullPrompt;
905
+ });
906
+ const target = portalTarget ?? (typeof document !== "undefined" ? document.body : null);
907
+ if (!target) return null;
908
+ return createPortal$1(/* @__PURE__ */ jsx(KolmoHudView, {
909
+ telemetryRef,
910
+ promptRef,
911
+ touchEnabled,
912
+ style
913
+ }), target);
914
+ }
915
+ function KolmoHudOutsideCanvas({ showTouchControls, extraPrompt, style }) {
916
+ const world = useActiveKolmoWorld();
917
+ const telemetryRef = useRef(null);
918
+ const promptRef = useRef(null);
919
+ const lastMsRef = useRef(-1e400);
920
+ const [isTouch, setIsTouch] = useState(detectTouchDevice);
921
+ useEffect(() => {
922
+ setIsTouch(detectTouchDevice());
923
+ }, []);
924
+ const touchEnabled = showTouchControls ?? isTouch;
925
+ useEffect(() => {
926
+ ensureWorldSession(world);
927
+ const sync = () => {
928
+ const { line, prompt } = formatHudStrings(world);
929
+ const fullPrompt = extraPrompt ? `${prompt} · ${extraPrompt}` : prompt;
930
+ if (telemetryRef.current && telemetryRef.current.textContent !== line) telemetryRef.current.textContent = line;
931
+ if (promptRef.current && promptRef.current.textContent !== fullPrompt) promptRef.current.textContent = fullPrompt;
932
+ };
933
+ sync();
934
+ const u1 = world.onChange(WorldSessionTrait, sync);
935
+ const u2 = world.onAdd(PilotedTag, sync);
936
+ const u3 = world.onRemove(PilotedTag, sync);
937
+ const u4 = world.onAdd(PilotLink, sync);
938
+ const u5 = world.onRemove(PilotLink, sync);
939
+ const u6 = world.onChange(VehicleTrait, sync);
940
+ const unsubFrame = addEffect((now) => {
941
+ if (Math.abs(now - lastMsRef.current) < 50) return;
942
+ lastMsRef.current = now;
943
+ sync();
944
+ });
945
+ return () => {
946
+ u1();
947
+ u2();
948
+ u3();
949
+ u4();
950
+ u5();
951
+ u6();
952
+ unsubFrame();
953
+ };
954
+ }, [
955
+ world,
956
+ extraPrompt,
957
+ touchEnabled
958
+ ]);
959
+ return /* @__PURE__ */ jsx(KolmoHudView, {
960
+ telemetryRef,
961
+ promptRef,
962
+ touchEnabled,
963
+ style
964
+ });
965
+ }
966
+ function KolmoHud(props) {
967
+ return useContext(KolmoInCanvasContext) ? /* @__PURE__ */ jsx(KolmoHudInCanvas, { ...props }) : /* @__PURE__ */ jsx(KolmoHudOutsideCanvas, { ...props });
968
+ }
969
+ function KolmoGame({ gravity = "planar", skybox = "day", lighting = "default", fogExp2, paused = false, timeScale = 1, maxDelta, physicsDebug = false, dpr, roomEnv = .65, kootaWorld = kolmoWorld, style, className, children }) {
970
+ const outerWorld = useOptionalKootaWorld();
971
+ const [overlayEl, setOverlayEl] = useState(null);
972
+ const shell = /* @__PURE__ */ jsx(KolmoOverlayPortalContext.Provider, {
973
+ value: overlayEl,
974
+ children: /* @__PURE__ */ jsxs("div", {
975
+ className,
976
+ style: {
977
+ position: "relative",
978
+ width: "100vw",
979
+ height: "100dvh",
980
+ overflow: "hidden",
981
+ touchAction: "none",
982
+ userSelect: "none",
983
+ ...style
984
+ },
985
+ children: [/* @__PURE__ */ jsx(KolmoCanvas, {
986
+ dpr,
987
+ roomEnv,
988
+ children: /* @__PURE__ */ jsx(KolmoWorld, {
989
+ gravity,
990
+ paused,
991
+ timeScale,
992
+ maxDelta,
993
+ skybox,
994
+ lighting,
995
+ fogExp2,
996
+ physicsDebug,
997
+ world: kootaWorld,
998
+ children
999
+ })
1000
+ }), /* @__PURE__ */ jsx("div", {
1001
+ ref: setOverlayEl,
1002
+ style: {
1003
+ position: "absolute",
1004
+ inset: 0,
1005
+ pointerEvents: "none"
1006
+ }
1007
+ })]
1008
+ })
1009
+ });
1010
+ return kootaWorld !== outerWorld ? /* @__PURE__ */ jsx(KolmoWorldContext.Provider, {
1011
+ value: kootaWorld,
1012
+ children: /* @__PURE__ */ jsx(WorldProvider, {
1013
+ world: kootaWorld,
1014
+ children: shell
1015
+ })
1016
+ }) : shell;
1017
+ }
1018
+ export { useKolmoInput as _, KolmoOverlayPortalContext as a, useKolmoGame as c, KolmoVehicle as d, EMPTY_KOLMO_INPUT as f, KolmoKeyboardContext as g, KolmoKeyboardBridge as h, KolmoInCanvasContext as i, KolmoProp as l, KOLMO_STICK_DEADZONE as m, KolmoGame as n, KolmoWorld as o, KOLMO_KEY_MAP as p, KolmoHud as r, RoomEnvRig as s, KolmoCanvas as t, KolmoSurface as u };
1019
+
1020
+ //# sourceMappingURL=world-BljtS6Fb.js.map