@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.
@@ -0,0 +1,1582 @@
1
+ import * as THREE from "three";
2
+ import { create } from "zustand";
3
+ import { JointRegistryContext, cloneKhrBundle, isJointOpen, openTargetForLimits, useKhrGlb } from "@khr3/core";
4
+ import { DOOR_HINGE_SPEC, SIDE_METRES, STEP_METRES, STOREY_METRES, canPlace, latticePose, poseToFloat, snapPose, socketFor, triangleCorners, worldSockets, wrapYaw } from "@khr3/c12";
5
+ import { useCallback, useContext, useEffect, useImperativeHandle, useMemo, useRef } from "react";
6
+ import { createPortal, useFrame, useThree } from "@react-three/fiber";
7
+ import { ConvexHullCollider, CuboidCollider, RigidBody, useRapier } from "@react-three/rapier";
8
+ import { easing } from "maath";
9
+ import { D as useActiveKolmoWorld, E as pilotedVehicleQuery, d as ActorTrait, h as PilotedTag, v as VehicleTrait } from "./physics-ZDFXaCli.js";
10
+ import { r as KolmoVehicle, t as KolmoProp } from "./surface-DUol_5ml.js";
11
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
+ // src/toolgun/store.ts
13
+ var TOOLGUN_MODES = [
14
+ "spawn",
15
+ "weld",
16
+ "hinge",
17
+ "rig",
18
+ "build",
19
+ "delete"
20
+ ];
21
+ var TOOLGUN_BUILD_KINDS = [
22
+ "FoundationSquare",
23
+ "FoundationTriangle",
24
+ "Wall",
25
+ "Doorway",
26
+ "Floor",
27
+ "FloorTriangle",
28
+ "Roof",
29
+ "RoofTriangle",
30
+ "Stairs"
31
+ ];
32
+ var TOOLGUN_SKIN_PRESETS = {
33
+ cobalt: {
34
+ bodyHex: "#1e293b",
35
+ accentHex: "#38bdf8",
36
+ emissiveHex: "#0ea5e9",
37
+ metalness: .65,
38
+ roughness: .32
39
+ },
40
+ hazard: {
41
+ bodyHex: "#292524",
42
+ accentHex: "#f59e0b",
43
+ emissiveHex: "#d97706",
44
+ metalness: .55,
45
+ roughness: .38
46
+ },
47
+ stealth: {
48
+ bodyHex: "#0f172a",
49
+ accentHex: "#64748b",
50
+ emissiveHex: "#38bdf8",
51
+ metalness: .72,
52
+ roughness: .28
53
+ },
54
+ chrome: {
55
+ bodyHex: "#cbd5e1",
56
+ accentHex: "#0284c7",
57
+ emissiveHex: "#38bdf8",
58
+ metalness: .92,
59
+ roughness: .14
60
+ },
61
+ arctic: {
62
+ bodyHex: "#f1f5f9",
63
+ accentHex: "#06b6d4",
64
+ emissiveHex: "#22d3ee",
65
+ metalness: .35,
66
+ roughness: .42
67
+ },
68
+ ember: {
69
+ bodyHex: "#1c1917",
70
+ accentHex: "#ef4444",
71
+ emissiveHex: "#f97316",
72
+ metalness: .62,
73
+ roughness: .34
74
+ }
75
+ };
76
+ var _upDefault = new THREE.Vector3(0, 1, 0);
77
+ var _nrmVec = new THREE.Vector3();
78
+ var _alignQuat = new THREE.Quaternion();
79
+ var _yawQuat = new THREE.Quaternion();
80
+ var _qA = new THREE.Quaternion();
81
+ var _qB = new THREE.Quaternion();
82
+ var _qInvA = new THREE.Quaternion();
83
+ var _qInvB = new THREE.Quaternion();
84
+ var _qRel = new THREE.Quaternion();
85
+ var _vA = new THREE.Vector3();
86
+ var _vB = new THREE.Vector3();
87
+ var _axLocal = new THREE.Vector3();
88
+ var _axWorldB = new THREE.Vector3();
89
+ /**
90
+ * Casts a solid ray against Rapier WASM colliders, ignoring sensors and the optional actor RigidBody.
91
+ */
92
+ function castToolgunRay(rapier, world, origin, direction, maxRange = 80, excludeBody) {
93
+ const dirLen = Math.hypot(direction[0], direction[1], direction[2]);
94
+ if (dirLen < 1e-8 || maxRange <= 0) return null;
95
+ const dx = direction[0] / dirLen;
96
+ const dy = direction[1] / dirLen;
97
+ const dz = direction[2] / dirLen;
98
+ const ray = new rapier.Ray({
99
+ x: origin[0],
100
+ y: origin[1],
101
+ z: origin[2]
102
+ }, {
103
+ x: dx,
104
+ y: dy,
105
+ z: dz
106
+ });
107
+ const hit = world.castRayAndGetNormal(ray, maxRange, true, rapier.QueryFilterFlags.EXCLUDE_SENSORS, void 0, void 0, excludeBody ?? void 0);
108
+ if (!hit) return null;
109
+ const nLen = Math.hypot(hit.normal.x, hit.normal.y, hit.normal.z);
110
+ const nx = nLen > 1e-6 ? hit.normal.x / nLen : 0;
111
+ const ny = nLen > 1e-6 ? hit.normal.y / nLen : 1;
112
+ const nz = nLen > 1e-6 ? hit.normal.z / nLen : 0;
113
+ return {
114
+ point: [
115
+ origin[0] + dx * hit.timeOfImpact,
116
+ origin[1] + dy * hit.timeOfImpact,
117
+ origin[2] + dz * hit.timeOfImpact
118
+ ],
119
+ normal: [
120
+ nx,
121
+ ny,
122
+ nz
123
+ ],
124
+ toi: hit.timeOfImpact,
125
+ collider: hit.collider,
126
+ body: hit.collider.parent()
127
+ };
128
+ }
129
+ /**
130
+ * Aligns a spawned asset's +Y axis to `surfaceNormal` (when sloped) composed with exact 30° `yaw12` turn.
131
+ */
132
+ function computeAlignedSpawnPose(point, yaw12, surfaceNormal = [
133
+ 0,
134
+ 1,
135
+ 0
136
+ ], clearanceM = .04) {
137
+ _nrmVec.set(surfaceNormal[0], surfaceNormal[1], surfaceNormal[2]);
138
+ if (_nrmVec.lengthSq() < 1e-6) _nrmVec.set(0, 1, 0);
139
+ else _nrmVec.normalize();
140
+ if (_nrmVec.y < .57) _nrmVec.set(0, 1, 0);
141
+ _alignQuat.setFromUnitVectors(_upDefault, _nrmVec);
142
+ const yawRad = wrapYaw(yaw12) * Math.PI / 6;
143
+ _yawQuat.setFromAxisAngle(_upDefault, yawRad);
144
+ _alignQuat.multiply(_yawQuat).normalize();
145
+ return {
146
+ position: [
147
+ point[0] + _nrmVec.x * clearanceM,
148
+ point[1] + _nrmVec.y * clearanceM,
149
+ point[2] + _nrmVec.z * clearanceM
150
+ ],
151
+ quaternion: [
152
+ _alignQuat.x,
153
+ _alignQuat.y,
154
+ _alignQuat.z,
155
+ _alignQuat.w
156
+ ]
157
+ };
158
+ }
159
+ /**
160
+ * Creates a real Rapier WASM Fixed `ImpulseJoint` locking `bodyA` and `bodyB` at their current relative 6-DOF pose.
161
+ */
162
+ function createWeldImpulseJoint(rapier, world, bodyA, bodyB, worldAnchor) {
163
+ const tA = bodyA.translation();
164
+ const rA = bodyA.rotation();
165
+ const tB = bodyB.translation();
166
+ const rB = bodyB.rotation();
167
+ _qA.set(rA.x, rA.y, rA.z, rA.w).normalize();
168
+ _qB.set(rB.x, rB.y, rB.z, rB.w).normalize();
169
+ _qInvA.copy(_qA).invert();
170
+ _qInvB.copy(_qB).invert();
171
+ _vA.set(worldAnchor[0] - tA.x, worldAnchor[1] - tA.y, worldAnchor[2] - tA.z).applyQuaternion(_qInvA);
172
+ _vB.set(worldAnchor[0] - tB.x, worldAnchor[1] - tB.y, worldAnchor[2] - tB.z).applyQuaternion(_qInvB);
173
+ _qRel.copy(_qInvA).multiply(_qB).normalize();
174
+ const data = rapier.JointData.fixed({
175
+ x: _vA.x,
176
+ y: _vA.y,
177
+ z: _vA.z
178
+ }, {
179
+ x: _qRel.x,
180
+ y: _qRel.y,
181
+ z: _qRel.z,
182
+ w: _qRel.w
183
+ }, {
184
+ x: _vB.x,
185
+ y: _vB.y,
186
+ z: _vB.z
187
+ }, {
188
+ x: 0,
189
+ y: 0,
190
+ z: 0,
191
+ w: 1
192
+ });
193
+ const imp = world.createImpulseJoint(data, bodyA, bodyB, true);
194
+ imp.setContactsEnabled(false);
195
+ if (bodyA.isDynamic()) bodyA.wakeUp();
196
+ if (bodyB.isDynamic()) bodyB.wakeUp();
197
+ return imp;
198
+ }
199
+ /**
200
+ * Creates a real Rapier WASM Revolute `ImpulseJoint` around `worldAxis` through `worldAnchor`.
201
+ * Aligns `bodyB`'s hinge shaft to `worldAxis` about `worldAnchor` when `bodyB` is tilted off-axis so `t=0` has zero snap error.
202
+ */
203
+ function createHingeImpulseJoint(rapier, world, bodyA, bodyB, worldAnchor, worldAxis = [
204
+ 0,
205
+ 1,
206
+ 0
207
+ ]) {
208
+ _nrmVec.set(worldAxis[0], worldAxis[1], worldAxis[2]);
209
+ if (_nrmVec.lengthSq() < 1e-8) _nrmVec.set(0, 1, 0);
210
+ else _nrmVec.normalize();
211
+ const tA = bodyA.translation();
212
+ const rA = bodyA.rotation();
213
+ const tB = bodyB.translation();
214
+ const rB = bodyB.rotation();
215
+ _qA.set(rA.x, rA.y, rA.z, rA.w).normalize();
216
+ _qB.set(rB.x, rB.y, rB.z, rB.w).normalize();
217
+ _qInvA.copy(_qA).invert();
218
+ _qInvB.copy(_qB).invert();
219
+ _vA.set(worldAnchor[0] - tA.x, worldAnchor[1] - tA.y, worldAnchor[2] - tA.z).applyQuaternion(_qInvA);
220
+ _vB.set(worldAnchor[0] - tB.x, worldAnchor[1] - tB.y, worldAnchor[2] - tB.z).applyQuaternion(_qInvB);
221
+ _axLocal.copy(_nrmVec).applyQuaternion(_qInvA).normalize();
222
+ _axWorldB.copy(_axLocal).applyQuaternion(_qB).normalize();
223
+ if (_axWorldB.dot(_nrmVec) < .99999 && bodyB.isDynamic()) {
224
+ _alignQuat.setFromUnitVectors(_axWorldB, _nrmVec).multiply(_qB).normalize();
225
+ const worldOffsetB = _axWorldB.copy(_vB).applyQuaternion(_alignQuat);
226
+ bodyB.setRotation({
227
+ x: _alignQuat.x,
228
+ y: _alignQuat.y,
229
+ z: _alignQuat.z,
230
+ w: _alignQuat.w
231
+ }, true);
232
+ bodyB.setTranslation({
233
+ x: worldAnchor[0] - worldOffsetB.x,
234
+ y: worldAnchor[1] - worldOffsetB.y,
235
+ z: worldAnchor[2] - worldOffsetB.z
236
+ }, true);
237
+ }
238
+ const data = rapier.JointData.revolute({
239
+ x: _vA.x,
240
+ y: _vA.y,
241
+ z: _vA.z
242
+ }, {
243
+ x: _vB.x,
244
+ y: _vB.y,
245
+ z: _vB.z
246
+ }, {
247
+ x: _axLocal.x,
248
+ y: _axLocal.y,
249
+ z: _axLocal.z
250
+ });
251
+ const imp = world.createImpulseJoint(data, bodyA, bodyB, true);
252
+ imp.setContactsEnabled(false);
253
+ if (bodyA.isDynamic()) bodyA.wakeUp();
254
+ if (bodyB.isDynamic()) bodyB.wakeUp();
255
+ return imp;
256
+ }
257
+ /**
258
+ * Toggles or breaks an articulated `@khr3/core` `JointRuntime`.
259
+ */
260
+ function rigJointRuntime(rt, severBreakaway = false) {
261
+ if (rt.detached) return `${rt.nodeName} already detached`;
262
+ if (severBreakaway) {
263
+ if (rt.applyImpactImpulse(Number.POSITIVE_INFINITY) === "detached") return `Detached ${rt.nodeName}`;
264
+ }
265
+ if (rt.drive?.stiffness !== void 0) {
266
+ const limits = rt.limits ?? [0, Math.PI / 2];
267
+ const nextOpen = !isJointOpen(rt);
268
+ const target = nextOpen ? openTargetForLimits(limits) : Math.min(limits[1], Math.max(limits[0], 0));
269
+ rt.applyTarget(target);
270
+ return `${nextOpen ? "Opened" : "Closed"} ${rt.nodeName}`;
271
+ }
272
+ return rt.applyImpactImpulse(Number.POSITIVE_INFINITY) === "detached" ? `Detached ${rt.nodeName}` : `Joint ${rt.nodeName} (${rt.kind})`;
273
+ }
274
+ /**
275
+ * Computes the nearest exact `@khr3/c12` socket-snapped or ground-lattice `BuildSnapCandidate` for `kind`.
276
+ */
277
+ function computeBuildCandidate(placedPieces, aimPoint, kind, yaw12, snapRadiusM = 2.6) {
278
+ const wantedSocketKind = socketFor(kind);
279
+ const maxDistSq = snapRadiusM * snapRadiusM;
280
+ let bestSocket = null;
281
+ let bestDistSq = maxDistSq;
282
+ for (const placed of placedPieces) {
283
+ const socks = worldSockets(placed.kind, placed.pose);
284
+ for (const s of socks) {
285
+ if (kind === "FoundationSquare" || kind === "FoundationTriangle") {
286
+ if (s.kind !== "edge") continue;
287
+ } else if (s.kind !== wantedSocketKind) continue;
288
+ const flt = poseToFloat({
289
+ pos: s.mid,
290
+ yaw: s.yaw
291
+ });
292
+ const dx = flt.position[0] - aimPoint[0];
293
+ const dy = flt.position[1] - aimPoint[1];
294
+ const dz = flt.position[2] - aimPoint[2];
295
+ const dSq = dx * dx + dy * dy + dz * dz;
296
+ if (dSq < bestDistSq) {
297
+ const testOwn = kind === "Stairs" ? Math.floor(wrapYaw(yaw12) / 3) : wrapYaw(yaw12);
298
+ const candidatePose = snapPose(kind, s, testOwn);
299
+ if (canPlace(placedPieces, kind, candidatePose).ok) {
300
+ bestDistSq = dSq;
301
+ bestSocket = s;
302
+ }
303
+ }
304
+ }
305
+ }
306
+ let pose;
307
+ let snappedSocket = false;
308
+ if (bestSocket) {
309
+ const own = kind === "Stairs" ? Math.floor(wrapYaw(yaw12) / 3) : wrapYaw(yaw12);
310
+ pose = snapPose(kind, bestSocket, own);
311
+ snappedSocket = true;
312
+ } else {
313
+ const xSteps = Math.round(aimPoint[0] / STEP_METRES);
314
+ const ySteps = Math.max(0, Math.round(aimPoint[1] / STEP_METRES));
315
+ const zSteps = Math.round(aimPoint[2] / STEP_METRES);
316
+ pose = latticePose(xSteps, zSteps, wrapYaw(yaw12), ySteps);
317
+ }
318
+ const check = canPlace(placedPieces, kind, pose);
319
+ const flt = poseToFloat(pose);
320
+ return {
321
+ kind,
322
+ pose,
323
+ position: flt.position,
324
+ quaternion: flt.quaternion,
325
+ snappedSocket,
326
+ valid: check.ok,
327
+ reason: check.reason
328
+ };
329
+ }
330
+ var nextSeq = 1;
331
+ function createToolgunStore() {
332
+ return create((set, get) => ({
333
+ mode: "spawn",
334
+ skinPreset: "cobalt",
335
+ yaw12: 0,
336
+ buildKind: "FoundationSquare",
337
+ zoomed: false,
338
+ armedAsset: null,
339
+ target: null,
340
+ buildPreview: null,
341
+ pendingAnchor: null,
342
+ spawnedEntities: [],
343
+ placedPieces: [],
344
+ createdJoints: [],
345
+ history: [],
346
+ statusText: "READY",
347
+ fireCount: 0,
348
+ setMode: (mode) => set({
349
+ mode,
350
+ pendingAnchor: null,
351
+ statusText: `MODE: ${mode.toUpperCase()}`
352
+ }),
353
+ cycleMode: (delta = 1) => {
354
+ const next = TOOLGUN_MODES[((TOOLGUN_MODES.indexOf(get().mode) + delta) % TOOLGUN_MODES.length + TOOLGUN_MODES.length) % TOOLGUN_MODES.length];
355
+ set({
356
+ mode: next,
357
+ pendingAnchor: null,
358
+ statusText: `MODE: ${next.toUpperCase()}`
359
+ });
360
+ },
361
+ setSkinPreset: (skinPreset) => set({ skinPreset }),
362
+ rotateYaw12: (stepsDelta = 1) => {
363
+ const nextYaw = wrapYaw(get().yaw12 + stepsDelta);
364
+ set({
365
+ yaw12: nextYaw,
366
+ statusText: `YAW: ${nextYaw * 30}°`
367
+ });
368
+ },
369
+ setBuildKind: (buildKind) => set({
370
+ buildKind,
371
+ mode: "build",
372
+ statusText: `BUILD: ${buildKind}`
373
+ }),
374
+ cycleBuildKind: (delta = 1) => {
375
+ const next = TOOLGUN_BUILD_KINDS[((TOOLGUN_BUILD_KINDS.indexOf(get().buildKind) + delta) % TOOLGUN_BUILD_KINDS.length + TOOLGUN_BUILD_KINDS.length) % TOOLGUN_BUILD_KINDS.length];
376
+ set({
377
+ buildKind: next,
378
+ statusText: `BUILD: ${next}`
379
+ });
380
+ },
381
+ setZoomed: (zoomed) => set({ zoomed }),
382
+ armAsset: (armedAsset) => set({
383
+ armedAsset,
384
+ ...armedAsset ? { statusText: `ARMED: ${armedAsset.name}` } : {}
385
+ }),
386
+ setTarget: (target) => set({ target }),
387
+ setBuildPreview: (buildPreview) => set({ buildPreview }),
388
+ setPendingAnchor: (pendingAnchor) => set({ pendingAnchor }),
389
+ recordSpawn: (entry) => set((s) => ({
390
+ spawnedEntities: [...s.spawnedEntities, entry],
391
+ history: [...s.history, {
392
+ type: "spawn",
393
+ id: entry.id
394
+ }],
395
+ statusText: `SPAWNED ${entry.name}`,
396
+ fireCount: s.fireCount + 1
397
+ })),
398
+ placeBuildPiece: (candidate) => {
399
+ const st = get();
400
+ const check = canPlace(st.placedPieces, candidate.kind, candidate.pose);
401
+ if (!check.ok) {
402
+ set({
403
+ statusText: check.reason.toUpperCase(),
404
+ fireCount: st.fireCount + 1
405
+ });
406
+ return null;
407
+ }
408
+ const piece = {
409
+ id: `c12_${nextSeq++}`,
410
+ kind: candidate.kind,
411
+ pose: candidate.pose
412
+ };
413
+ set((s) => ({
414
+ placedPieces: [...s.placedPieces, piece],
415
+ history: [...s.history, {
416
+ type: "piece",
417
+ id: piece.id
418
+ }],
419
+ statusText: `PLACED ${piece.kind}`,
420
+ fireCount: s.fireCount + 1
421
+ }));
422
+ return piece;
423
+ },
424
+ recordJoint: (entry) => set((s) => ({
425
+ createdJoints: [...s.createdJoints, entry],
426
+ history: [...s.history, {
427
+ type: "joint",
428
+ id: entry.id
429
+ }],
430
+ pendingAnchor: null,
431
+ statusText: `${entry.kind === "weld" ? "WELDED" : "HINGED"} #${entry.handle}`,
432
+ fireCount: s.fireCount + 1
433
+ })),
434
+ removeEntityById: (id) => {
435
+ if (!get().spawnedEntities.some((e) => e.id === id)) return false;
436
+ set((s) => ({
437
+ spawnedEntities: s.spawnedEntities.filter((e) => e.id !== id),
438
+ history: s.history.filter((h) => !(h.type === "spawn" && h.id === id)),
439
+ statusText: `DELETED ${id}`,
440
+ fireCount: s.fireCount + 1
441
+ }));
442
+ return true;
443
+ },
444
+ removePieceById: (id) => {
445
+ if (!get().placedPieces.some((p) => p.id === id)) return false;
446
+ set((s) => ({
447
+ placedPieces: s.placedPieces.filter((p) => p.id !== id),
448
+ history: s.history.filter((h) => !(h.type === "piece" && h.id === id)),
449
+ statusText: `REMOVED ${id}`,
450
+ fireCount: s.fireCount + 1
451
+ }));
452
+ return true;
453
+ },
454
+ removeJointByBody: (world, body) => {
455
+ const keep = [];
456
+ const removedIds = /* @__PURE__ */ new Set();
457
+ for (const cj of get().createdJoints) {
458
+ const live = world.getImpulseJoint(cj.joint.handle);
459
+ if (!live) {
460
+ removedIds.add(cj.id);
461
+ continue;
462
+ }
463
+ if (live.body1().handle === body.handle || live.body2().handle === body.handle) {
464
+ world.removeImpulseJoint(live, true);
465
+ removedIds.add(cj.id);
466
+ } else keep.push(cj);
467
+ }
468
+ if (removedIds.size > 0) set((s) => ({
469
+ createdJoints: keep,
470
+ history: s.history.filter((h) => !(h.type === "joint" && removedIds.has(h.id))),
471
+ statusText: `UNWELDED (${removedIds.size})`,
472
+ fireCount: s.fireCount + 1
473
+ }));
474
+ return removedIds.size;
475
+ },
476
+ undoLast: (world) => {
477
+ const st = get();
478
+ const last = st.history[st.history.length - 1];
479
+ if (!last) return "NOTHING TO UNDO";
480
+ const nextHistory = st.history.slice(0, -1);
481
+ if (last.type === "spawn") {
482
+ set({
483
+ spawnedEntities: st.spawnedEntities.filter((e) => e.id !== last.id),
484
+ history: nextHistory,
485
+ statusText: `UNDO SPAWN ${last.id}`
486
+ });
487
+ return `UNDO SPAWN ${last.id}`;
488
+ }
489
+ if (last.type === "piece") {
490
+ set({
491
+ placedPieces: st.placedPieces.filter((p) => p.id !== last.id),
492
+ history: nextHistory,
493
+ statusText: `UNDO PIECE ${last.id}`
494
+ });
495
+ return `UNDO PIECE ${last.id}`;
496
+ }
497
+ const jEntry = st.createdJoints.find((j) => j.id === last.id);
498
+ if (jEntry && world && world.getImpulseJoint(jEntry.joint.handle)) world.removeImpulseJoint(jEntry.joint, true);
499
+ set({
500
+ createdJoints: st.createdJoints.filter((j) => j.id !== last.id),
501
+ history: nextHistory,
502
+ statusText: `UNDO JOINT ${last.id}`
503
+ });
504
+ return `UNDO JOINT ${last.id}`;
505
+ },
506
+ bumpFire: (statusText) => set((s) => ({
507
+ statusText,
508
+ fireCount: s.fireCount + 1
509
+ })),
510
+ resetAll: (world) => {
511
+ if (world) {
512
+ for (const cj of get().createdJoints) if (world.getImpulseJoint(cj.joint.handle)) world.removeImpulseJoint(cj.joint, true);
513
+ }
514
+ set({
515
+ pendingAnchor: null,
516
+ spawnedEntities: [],
517
+ placedPieces: [],
518
+ createdJoints: [],
519
+ history: [],
520
+ statusText: "CLEARED"
521
+ });
522
+ }
523
+ }));
524
+ }
525
+ var useToolgunStore = createToolgunStore();
526
+ // src/toolgun/Toolgun.tsx
527
+ var LCD_W = 256;
528
+ var LCD_H = 192;
529
+ var WALL_THICK = .2;
530
+ var SLAB_THICK = .2;
531
+ function measureToolgunViewmodel(sourceScene) {
532
+ const cloned = sourceScene.clone(true);
533
+ cloned.updateMatrixWorld(true);
534
+ const invRoot = cloned.matrixWorld.clone().invert();
535
+ let grip = [
536
+ 0,
537
+ 0,
538
+ 0
539
+ ];
540
+ let muzzle = [
541
+ 0,
542
+ .04,
543
+ -.24
544
+ ];
545
+ let screenPos = [
546
+ 0,
547
+ .068,
548
+ .095
549
+ ];
550
+ let screenQuat = [
551
+ 0,
552
+ 0,
553
+ 0,
554
+ 1
555
+ ];
556
+ let screenSize = [.068, .051];
557
+ const tmpPos = new THREE.Vector3();
558
+ const tmpQuat = new THREE.Quaternion();
559
+ cloned.traverse((node) => {
560
+ const low = node.name.toLowerCase();
561
+ if (low === "ik_palm_primary" || low === "grip" || low === "socket_grip") {
562
+ node.getWorldPosition(tmpPos).applyMatrix4(invRoot);
563
+ grip = [
564
+ -tmpPos.x,
565
+ -tmpPos.y,
566
+ -tmpPos.z
567
+ ];
568
+ } else if (low === "socket_muzzle" || low === "muzzle") {
569
+ node.getWorldPosition(tmpPos).applyMatrix4(invRoot);
570
+ muzzle = [
571
+ tmpPos.x,
572
+ tmpPos.y,
573
+ tmpPos.z
574
+ ];
575
+ } else if (low === "screen_rect" || low === "lcd_screen") {
576
+ node.getWorldPosition(tmpPos).applyMatrix4(invRoot);
577
+ node.getWorldQuaternion(tmpQuat);
578
+ screenPos = [
579
+ tmpPos.x,
580
+ tmpPos.y,
581
+ tmpPos.z + .001
582
+ ];
583
+ screenQuat = [
584
+ tmpQuat.x,
585
+ tmpQuat.y,
586
+ tmpQuat.z,
587
+ tmpQuat.w
588
+ ];
589
+ const mesh = node;
590
+ if (mesh.isMesh && mesh.geometry) {
591
+ mesh.geometry.computeBoundingBox();
592
+ const bb = mesh.geometry.boundingBox;
593
+ if (bb) {
594
+ const sz = bb.getSize(new THREE.Vector3());
595
+ screenSize = [Math.max(.025, sz.x), Math.max(.02, sz.y)];
596
+ }
597
+ }
598
+ }
599
+ });
600
+ return {
601
+ scene: cloned,
602
+ gripOffset: grip,
603
+ muzzleLocal: muzzle,
604
+ screenPos,
605
+ screenQuat,
606
+ screenSize
607
+ };
608
+ }
609
+ function createLcdSurface() {
610
+ if (typeof document === "undefined") return {
611
+ texture: null,
612
+ draw: () => {},
613
+ dispose: () => {}
614
+ };
615
+ const canvas = document.createElement("canvas");
616
+ canvas.width = LCD_W;
617
+ canvas.height = LCD_H;
618
+ const ctx = canvas.getContext("2d");
619
+ const texture = new THREE.CanvasTexture(canvas);
620
+ texture.colorSpace = THREE.SRGBColorSpace;
621
+ texture.minFilter = THREE.LinearFilter;
622
+ texture.magFilter = THREE.LinearFilter;
623
+ texture.generateMipmaps = false;
624
+ let prevSig = "";
625
+ return {
626
+ texture,
627
+ draw: ({ mode, yawDeg, detail, targetLabel, status, accentHex }) => {
628
+ if (!ctx) return;
629
+ const sig = `${mode}|${yawDeg}|${detail}|${targetLabel}|${status}|${accentHex}`;
630
+ if (sig === prevSig) return;
631
+ prevSig = sig;
632
+ ctx.fillStyle = "#070d19";
633
+ ctx.fillRect(0, 0, LCD_W, LCD_H);
634
+ ctx.strokeStyle = accentHex;
635
+ ctx.lineWidth = 3;
636
+ ctx.strokeRect(4, 4, 248, 184);
637
+ ctx.fillStyle = accentHex;
638
+ ctx.fillRect(4, 4, 248, 28);
639
+ ctx.fillStyle = "#040812";
640
+ ctx.font = "bold 15px ui-monospace, SFMono-Regular, Menlo, monospace";
641
+ ctx.fillText(`KOLMO // ${mode.toUpperCase()}`, 12, 23);
642
+ ctx.textAlign = "right";
643
+ ctx.fillText(`${yawDeg}°`, 244, 23);
644
+ ctx.textAlign = "left";
645
+ ctx.fillStyle = "#e2e8f0";
646
+ ctx.font = "bold 13px ui-monospace, SFMono-Regular, Menlo, monospace";
647
+ ctx.fillText(detail.slice(0, 26), 12, 58);
648
+ ctx.fillStyle = "#7dd3fc";
649
+ ctx.font = "12px ui-monospace, SFMono-Regular, Menlo, monospace";
650
+ ctx.fillText(targetLabel.slice(0, 28), 12, 86);
651
+ ctx.strokeStyle = "rgba(148, 163, 184, 0.28)";
652
+ ctx.lineWidth = 1;
653
+ ctx.beginPath();
654
+ ctx.moveTo(12, 106);
655
+ ctx.lineTo(244, 106);
656
+ ctx.stroke();
657
+ ctx.fillStyle = "#34d399";
658
+ ctx.font = "bold 12px ui-monospace, SFMono-Regular, Menlo, monospace";
659
+ ctx.fillText(status.slice(0, 28), 12, 130);
660
+ ctx.fillStyle = "#94a3b8";
661
+ ctx.font = "10px ui-monospace, SFMono-Regular, Menlo, monospace";
662
+ ctx.fillText("[1-6/Q] MODE [R] +30° [Z] UNDO", 12, 160);
663
+ ctx.fillText("[LMB] FIRE [RMB] ZOOM [[/]] C12", 12, 176);
664
+ texture.needsUpdate = true;
665
+ },
666
+ dispose: () => {
667
+ texture.dispose();
668
+ }
669
+ };
670
+ }
671
+ function createTriangleExtrudedGeometry(thicknessM) {
672
+ const corners = triangleCorners();
673
+ const y0 = 0;
674
+ const y1 = thicknessM;
675
+ const positions = [];
676
+ const pushTri = (a, b, c) => {
677
+ positions.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]);
678
+ };
679
+ const bot = corners.map(([x, , z]) => [
680
+ x,
681
+ y0,
682
+ z
683
+ ]);
684
+ const top = corners.map(([x, , z]) => [
685
+ x,
686
+ y1,
687
+ z
688
+ ]);
689
+ pushTri(top[0], top[1], top[2]);
690
+ pushTri(bot[0], bot[2], bot[1]);
691
+ for (let i = 0; i < 3; i++) {
692
+ const j = (i + 1) % 3;
693
+ pushTri(bot[i], bot[j], top[j]);
694
+ pushTri(bot[i], top[j], top[i]);
695
+ }
696
+ const geo = new THREE.BufferGeometry();
697
+ geo.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
698
+ geo.computeVertexNormals();
699
+ return geo;
700
+ }
701
+ function buildTriangleHullVertices(thicknessM) {
702
+ const corners = triangleCorners();
703
+ const verts = [];
704
+ for (const [x, , z] of corners) verts.push(x, 0, z, x, thicknessM, z);
705
+ return new Float32Array(verts);
706
+ }
707
+ function C12PieceColliderAndMesh({ piece }) {
708
+ const flt = useMemo(() => poseToFloat(piece.pose), [piece.pose]);
709
+ const userData = useMemo(() => ({
710
+ kolmoPlacedPieceId: piece.id,
711
+ name: piece.kind
712
+ }), [piece.id, piece.kind]);
713
+ const triGeo = useMemo(() => piece.kind === "FoundationTriangle" || piece.kind === "FloorTriangle" || piece.kind === "RoofTriangle" ? createTriangleExtrudedGeometry(SLAB_THICK) : null, [piece.kind]);
714
+ const triVerts = useMemo(() => triGeo ? buildTriangleHullVertices(SLAB_THICK) : null, [triGeo]);
715
+ useEffect(() => () => triGeo?.dispose(), [triGeo]);
716
+ if (piece.kind === "FoundationSquare" || piece.kind === "Floor" || piece.kind === "Roof" || piece.kind === "Street") {
717
+ const yOff = piece.kind === "FoundationSquare" || piece.kind === "Street" ? SLAB_THICK * .5 : -.1;
718
+ const color = piece.kind === "Roof" ? "#475569" : piece.kind === "Street" ? "#334155" : "#64748b";
719
+ return /* @__PURE__ */ jsxs(RigidBody, {
720
+ type: "fixed",
721
+ colliders: false,
722
+ position: flt.position,
723
+ quaternion: flt.quaternion,
724
+ friction: .6,
725
+ restitution: .1,
726
+ userData,
727
+ children: [/* @__PURE__ */ jsx(CuboidCollider, {
728
+ args: [
729
+ SIDE_METRES * .5,
730
+ SLAB_THICK * .5,
731
+ SIDE_METRES * .5
732
+ ],
733
+ position: [
734
+ 0,
735
+ yOff,
736
+ 0
737
+ ]
738
+ }), /* @__PURE__ */ jsxs("mesh", {
739
+ position: [
740
+ 0,
741
+ yOff,
742
+ 0
743
+ ],
744
+ castShadow: true,
745
+ receiveShadow: true,
746
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
747
+ SIDE_METRES,
748
+ SLAB_THICK,
749
+ SIDE_METRES
750
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
751
+ color,
752
+ roughness: .82,
753
+ metalness: .08
754
+ })]
755
+ })]
756
+ });
757
+ }
758
+ if (triGeo && triVerts) return /* @__PURE__ */ jsxs(RigidBody, {
759
+ type: "fixed",
760
+ colliders: false,
761
+ position: flt.position,
762
+ quaternion: flt.quaternion,
763
+ friction: .6,
764
+ restitution: .1,
765
+ userData,
766
+ children: [/* @__PURE__ */ jsx(ConvexHullCollider, { args: [triVerts] }), /* @__PURE__ */ jsx("mesh", {
767
+ geometry: triGeo,
768
+ castShadow: true,
769
+ receiveShadow: true,
770
+ children: /* @__PURE__ */ jsx("meshStandardMaterial", {
771
+ color: "#64748b",
772
+ roughness: .82,
773
+ metalness: .08
774
+ })
775
+ })]
776
+ });
777
+ if (piece.kind === "Wall") return /* @__PURE__ */ jsxs(RigidBody, {
778
+ type: "fixed",
779
+ colliders: false,
780
+ position: flt.position,
781
+ quaternion: flt.quaternion,
782
+ friction: .6,
783
+ restitution: .1,
784
+ userData,
785
+ children: [/* @__PURE__ */ jsx(CuboidCollider, {
786
+ args: [
787
+ SIDE_METRES * .5,
788
+ STOREY_METRES * .5,
789
+ WALL_THICK * .5
790
+ ],
791
+ position: [
792
+ 0,
793
+ STOREY_METRES * .5,
794
+ 0
795
+ ]
796
+ }), /* @__PURE__ */ jsxs("mesh", {
797
+ position: [
798
+ 0,
799
+ STOREY_METRES * .5,
800
+ 0
801
+ ],
802
+ castShadow: true,
803
+ receiveShadow: true,
804
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
805
+ SIDE_METRES,
806
+ STOREY_METRES,
807
+ WALL_THICK
808
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
809
+ color: "#94a3b8",
810
+ roughness: .78,
811
+ metalness: .06
812
+ })]
813
+ })]
814
+ });
815
+ if (piece.kind === "Doorway") {
816
+ const openW = DOOR_HINGE_SPEC.openingWidthM;
817
+ const openH = DOOR_HINGE_SPEC.openingHeightM;
818
+ const jambW = (SIDE_METRES - openW) * .5;
819
+ const lintelH = STOREY_METRES - openH;
820
+ const jambX = openW * .5 + jambW * .5;
821
+ return /* @__PURE__ */ jsxs(RigidBody, {
822
+ type: "fixed",
823
+ colliders: false,
824
+ position: flt.position,
825
+ quaternion: flt.quaternion,
826
+ friction: .6,
827
+ restitution: .1,
828
+ userData,
829
+ children: [
830
+ /* @__PURE__ */ jsx(CuboidCollider, {
831
+ args: [
832
+ jambW * .5,
833
+ openH * .5,
834
+ WALL_THICK * .5
835
+ ],
836
+ position: [
837
+ -jambX,
838
+ openH * .5,
839
+ 0
840
+ ]
841
+ }),
842
+ /* @__PURE__ */ jsx(CuboidCollider, {
843
+ args: [
844
+ jambW * .5,
845
+ openH * .5,
846
+ WALL_THICK * .5
847
+ ],
848
+ position: [
849
+ jambX,
850
+ openH * .5,
851
+ 0
852
+ ]
853
+ }),
854
+ /* @__PURE__ */ jsx(CuboidCollider, {
855
+ args: [
856
+ SIDE_METRES * .5,
857
+ lintelH * .5,
858
+ WALL_THICK * .5
859
+ ],
860
+ position: [
861
+ 0,
862
+ openH + lintelH * .5,
863
+ 0
864
+ ]
865
+ }),
866
+ /* @__PURE__ */ jsxs("mesh", {
867
+ position: [
868
+ -jambX,
869
+ openH * .5,
870
+ 0
871
+ ],
872
+ castShadow: true,
873
+ receiveShadow: true,
874
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
875
+ jambW,
876
+ openH,
877
+ WALL_THICK
878
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
879
+ color: "#94a3b8",
880
+ roughness: .78
881
+ })]
882
+ }),
883
+ /* @__PURE__ */ jsxs("mesh", {
884
+ position: [
885
+ jambX,
886
+ openH * .5,
887
+ 0
888
+ ],
889
+ castShadow: true,
890
+ receiveShadow: true,
891
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
892
+ jambW,
893
+ openH,
894
+ WALL_THICK
895
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
896
+ color: "#94a3b8",
897
+ roughness: .78
898
+ })]
899
+ }),
900
+ /* @__PURE__ */ jsxs("mesh", {
901
+ position: [
902
+ 0,
903
+ openH + lintelH * .5,
904
+ 0
905
+ ],
906
+ castShadow: true,
907
+ receiveShadow: true,
908
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
909
+ SIDE_METRES,
910
+ lintelH,
911
+ WALL_THICK
912
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
913
+ color: "#94a3b8",
914
+ roughness: .78
915
+ })]
916
+ })
917
+ ]
918
+ });
919
+ }
920
+ const rampLen = Math.hypot(SIDE_METRES, STOREY_METRES);
921
+ const rampPitch = -Math.atan2(STOREY_METRES, SIDE_METRES);
922
+ return /* @__PURE__ */ jsxs(RigidBody, {
923
+ type: "fixed",
924
+ colliders: false,
925
+ position: flt.position,
926
+ quaternion: flt.quaternion,
927
+ friction: .85,
928
+ restitution: .05,
929
+ userData,
930
+ children: [/* @__PURE__ */ jsx(CuboidCollider, {
931
+ args: [
932
+ SIDE_METRES * .45,
933
+ SLAB_THICK * .5,
934
+ rampLen * .5
935
+ ],
936
+ position: [
937
+ 0,
938
+ STOREY_METRES * .5,
939
+ 0
940
+ ],
941
+ rotation: [
942
+ rampPitch,
943
+ 0,
944
+ 0
945
+ ]
946
+ }), /* @__PURE__ */ jsxs("mesh", {
947
+ position: [
948
+ 0,
949
+ STOREY_METRES * .5,
950
+ 0
951
+ ],
952
+ rotation: [
953
+ rampPitch,
954
+ 0,
955
+ 0
956
+ ],
957
+ castShadow: true,
958
+ receiveShadow: true,
959
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
960
+ SIDE_METRES * .9,
961
+ SLAB_THICK,
962
+ rampLen
963
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
964
+ color: "#cbd5e1",
965
+ roughness: .75
966
+ })]
967
+ })]
968
+ });
969
+ }
970
+ function BuildGhostPreview({ candidate }) {
971
+ const color = candidate.valid ? "#34d399" : "#ef4444";
972
+ const isSlab = candidate.kind === "FoundationSquare" || candidate.kind === "Floor" || candidate.kind === "Roof";
973
+ const isTri = candidate.kind === "FoundationTriangle" || candidate.kind === "FloorTriangle" || candidate.kind === "RoofTriangle";
974
+ const triGeo = useMemo(() => isTri ? createTriangleExtrudedGeometry(SLAB_THICK) : null, [isTri]);
975
+ useEffect(() => () => triGeo?.dispose(), [triGeo]);
976
+ const dims = isSlab ? [
977
+ SIDE_METRES,
978
+ SLAB_THICK,
979
+ SIDE_METRES
980
+ ] : candidate.kind === "Stairs" ? [
981
+ SIDE_METRES * .9,
982
+ STOREY_METRES,
983
+ SIDE_METRES
984
+ ] : [
985
+ SIDE_METRES,
986
+ STOREY_METRES,
987
+ WALL_THICK
988
+ ];
989
+ const yCenter = isSlab ? SLAB_THICK * .5 : STOREY_METRES * .5;
990
+ return /* @__PURE__ */ jsx("group", {
991
+ position: candidate.position,
992
+ quaternion: candidate.quaternion,
993
+ children: triGeo ? /* @__PURE__ */ jsx("mesh", {
994
+ geometry: triGeo,
995
+ children: /* @__PURE__ */ jsx("meshBasicMaterial", {
996
+ color,
997
+ transparent: true,
998
+ opacity: .36,
999
+ depthWrite: false
1000
+ })
1001
+ }) : /* @__PURE__ */ jsxs("mesh", {
1002
+ position: [
1003
+ 0,
1004
+ yCenter,
1005
+ 0
1006
+ ],
1007
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: dims }), /* @__PURE__ */ jsx("meshBasicMaterial", {
1008
+ color,
1009
+ transparent: true,
1010
+ opacity: .36,
1011
+ depthWrite: false
1012
+ })]
1013
+ })
1014
+ });
1015
+ }
1016
+ function ProceduralToolgunBody({ skinPreset, lcdTexture }) {
1017
+ const skin = TOOLGUN_SKIN_PRESETS[skinPreset];
1018
+ return /* @__PURE__ */ jsxs("group", { children: [
1019
+ /* @__PURE__ */ jsxs("mesh", {
1020
+ position: [
1021
+ 0,
1022
+ .032,
1023
+ -.04
1024
+ ],
1025
+ castShadow: true,
1026
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
1027
+ .056,
1028
+ .062,
1029
+ .22
1030
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
1031
+ color: skin.bodyHex,
1032
+ metalness: skin.metalness,
1033
+ roughness: skin.roughness
1034
+ })]
1035
+ }),
1036
+ /* @__PURE__ */ jsxs("mesh", {
1037
+ position: [
1038
+ 0,
1039
+ .038,
1040
+ -.2
1041
+ ],
1042
+ rotation: [
1043
+ Math.PI / 2,
1044
+ 0,
1045
+ 0
1046
+ ],
1047
+ castShadow: true,
1048
+ children: [/* @__PURE__ */ jsx("cylinderGeometry", { args: [
1049
+ .014,
1050
+ .018,
1051
+ .14,
1052
+ 12
1053
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
1054
+ color: skin.accentHex,
1055
+ emissive: skin.emissiveHex,
1056
+ emissiveIntensity: .6,
1057
+ metalness: .8,
1058
+ roughness: .2
1059
+ })]
1060
+ }),
1061
+ /* @__PURE__ */ jsxs("mesh", {
1062
+ position: [
1063
+ 0,
1064
+ -.042,
1065
+ .03
1066
+ ],
1067
+ rotation: [
1068
+ .24,
1069
+ 0,
1070
+ 0
1071
+ ],
1072
+ castShadow: true,
1073
+ children: [/* @__PURE__ */ jsx("boxGeometry", { args: [
1074
+ .042,
1075
+ .11,
1076
+ .048
1077
+ ] }), /* @__PURE__ */ jsx("meshStandardMaterial", {
1078
+ color: "#0f172a",
1079
+ roughness: .75,
1080
+ metalness: .2
1081
+ })]
1082
+ }),
1083
+ /* @__PURE__ */ jsxs("mesh", {
1084
+ position: [
1085
+ 0,
1086
+ .052,
1087
+ .072
1088
+ ],
1089
+ children: [/* @__PURE__ */ jsx("planeGeometry", { args: [.064, .048] }), /* @__PURE__ */ jsx("meshBasicMaterial", {
1090
+ ...lcdTexture ? { map: lcdTexture } : { color: skin.accentHex },
1091
+ toneMapped: false
1092
+ })]
1093
+ })
1094
+ ] });
1095
+ }
1096
+ var _camPos = new THREE.Vector3();
1097
+ var _camDir = new THREE.Vector3();
1098
+ var _muzzleWorld = new THREE.Vector3();
1099
+ var _beamEndVec = new THREE.Vector3();
1100
+ var _targetOffset = new THREE.Vector3();
1101
+ function ToolgunCore({ ref, viewmodelBundle, actorRef, skinPreset: skinProp, defaultArmedAsset, maxRangeM = 75, hipOffset = [
1102
+ .24,
1103
+ -.21,
1104
+ -.42
1105
+ ], zoomOffset = [
1106
+ 0,
1107
+ -.055,
1108
+ -.22
1109
+ ], enableShortcuts = true, mountWorldOutlets = true, enable = true }) {
1110
+ const { rapier, world: rapierWorld } = useRapier();
1111
+ const camera = useThree((s) => s.camera);
1112
+ const gl = useThree((s) => s.gl);
1113
+ const kootaWorld = useActiveKolmoWorld();
1114
+ const jointRegistry = useContext(JointRegistryContext);
1115
+ const mode = useToolgunStore((s) => s.mode);
1116
+ const storeSkin = useToolgunStore((s) => s.skinPreset);
1117
+ const buildPreview = useToolgunStore((s) => s.buildPreview);
1118
+ const spawnedEntities = useToolgunStore((s) => s.spawnedEntities);
1119
+ const placedPieces = useToolgunStore((s) => s.placedPieces);
1120
+ const effSkin = skinProp ?? storeSkin;
1121
+ useEffect(() => {
1122
+ if (defaultArmedAsset && !useToolgunStore.getState().armedAsset) useToolgunStore.getState().armAsset(defaultArmedAsset);
1123
+ }, [defaultArmedAsset]);
1124
+ const measured = useMemo(() => viewmodelBundle ? measureToolgunViewmodel(viewmodelBundle.scene) : null, [viewmodelBundle]);
1125
+ const lcd = useMemo(createLcdSurface, []);
1126
+ useEffect(() => () => lcd.dispose(), [lcd]);
1127
+ const holderRef = useRef(null);
1128
+ const recoilRef = useRef(0);
1129
+ const beamTimerRef = useRef(0);
1130
+ const beamMatRef = useRef(null);
1131
+ const beamGeo = useMemo(() => {
1132
+ const g = new THREE.BufferGeometry();
1133
+ g.setAttribute("position", new THREE.Float32BufferAttribute([
1134
+ 0,
1135
+ 0,
1136
+ 0,
1137
+ 0,
1138
+ 0,
1139
+ -1
1140
+ ], 3));
1141
+ return g;
1142
+ }, []);
1143
+ const beamLine = useMemo(() => {
1144
+ const mat = new THREE.LineBasicMaterial({
1145
+ color: "#38bdf8",
1146
+ transparent: true,
1147
+ opacity: 0,
1148
+ depthTest: false
1149
+ });
1150
+ beamMatRef.current = mat;
1151
+ const line = new THREE.Line(beamGeo, mat);
1152
+ line.frustumCulled = false;
1153
+ line.visible = false;
1154
+ return line;
1155
+ }, [beamGeo]);
1156
+ useEffect(() => () => {
1157
+ beamGeo.dispose();
1158
+ beamMatRef.current?.dispose();
1159
+ }, [beamGeo]);
1160
+ const resolvePlayerBody = useCallback(() => {
1161
+ if (actorRef?.current?.body) return actorRef.current.body;
1162
+ return kootaWorld.queryFirst(ActorTrait)?.get(ActorTrait)?.handle?.body ?? null;
1163
+ }, [actorRef, kootaWorld]);
1164
+ const findJointForBody = useCallback((body) => {
1165
+ if (!body || !jointRegistry) return null;
1166
+ for (const rt of jointRegistry) if (!rt.detached && rt.childBody?.handle === body.handle) return rt;
1167
+ return null;
1168
+ }, [jointRegistry]);
1169
+ const fire = useCallback((shiftKey = false) => {
1170
+ camera.getWorldPosition(_camPos);
1171
+ camera.getWorldDirection(_camDir);
1172
+ const st = useToolgunStore.getState();
1173
+ const playerBody = resolvePlayerBody();
1174
+ const rawHit = castToolgunRay(rapier, rapierWorld, [
1175
+ _camPos.x,
1176
+ _camPos.y,
1177
+ _camPos.z
1178
+ ], [
1179
+ _camDir.x,
1180
+ _camDir.y,
1181
+ _camDir.z
1182
+ ], maxRangeM, playerBody);
1183
+ let fallbackPoint = [
1184
+ _camPos.x + _camDir.x * 5,
1185
+ Math.max(0, _camPos.y + _camDir.y * 5),
1186
+ _camPos.z + _camDir.z * 5
1187
+ ];
1188
+ if (_camDir.y < -.02 && _camPos.y > 0) {
1189
+ const tGround = -_camPos.y / _camDir.y;
1190
+ if (tGround > .1 && tGround <= maxRangeM) fallbackPoint = [
1191
+ _camPos.x + _camDir.x * tGround,
1192
+ 0,
1193
+ _camPos.z + _camDir.z * tGround
1194
+ ];
1195
+ }
1196
+ const aimPoint = rawHit ? rawHit.point : fallbackPoint;
1197
+ const aimNormal = rawHit ? rawHit.normal : [
1198
+ 0,
1199
+ 1,
1200
+ 0
1201
+ ];
1202
+ recoilRef.current = 1;
1203
+ beamTimerRef.current = .09;
1204
+ _beamEndVec.set(aimPoint[0], aimPoint[1], aimPoint[2]);
1205
+ if (holderRef.current) {
1206
+ const mLocal = measured?.muzzleLocal ?? [
1207
+ 0,
1208
+ .038,
1209
+ -.26
1210
+ ];
1211
+ _muzzleWorld.set(mLocal[0], mLocal[1], mLocal[2]).applyMatrix4(holderRef.current.matrixWorld);
1212
+ } else _muzzleWorld.copy(_camPos).addScaledVector(_camDir, .35);
1213
+ const posAttr = beamGeo.getAttribute("position");
1214
+ posAttr.setXYZ(0, _muzzleWorld.x, _muzzleWorld.y, _muzzleWorld.z);
1215
+ posAttr.setXYZ(1, _beamEndVec.x, _beamEndVec.y, _beamEndVec.z);
1216
+ posAttr.needsUpdate = true;
1217
+ beamLine.visible = true;
1218
+ if (st.mode === "spawn") {
1219
+ const asset = st.armedAsset;
1220
+ if (!asset || !asset.bundle && !asset.src) {
1221
+ st.bumpFire("NO ASSET ARMED");
1222
+ return {
1223
+ ok: false,
1224
+ status: "NO ASSET ARMED",
1225
+ beamEnd: aimPoint
1226
+ };
1227
+ }
1228
+ const pose = computeAlignedSpawnPose(aimPoint, st.yaw12, aimNormal, .08);
1229
+ const isVehicle = asset.kind === "vehicle" || asset.kind !== "prop" && Boolean(asset.bundle && (asset.bundle.wheels.length > 0 || asset.bundle.propellers.length > 0));
1230
+ const id = `tg_ent_${Date.now().toString(36)}_${st.fireCount}`;
1231
+ st.recordSpawn({
1232
+ id,
1233
+ name: asset.name,
1234
+ kind: isVehicle ? "vehicle" : "prop",
1235
+ ...asset.src ? { src: asset.src } : {},
1236
+ ...asset.bundle ? { bundle: asset.bundle } : {},
1237
+ fixed: Boolean(asset.fixed),
1238
+ position: pose.position,
1239
+ quaternion: pose.quaternion
1240
+ });
1241
+ return {
1242
+ ok: true,
1243
+ status: `SPAWNED ${asset.name}`,
1244
+ beamEnd: aimPoint
1245
+ };
1246
+ }
1247
+ if (st.mode === "build") {
1248
+ const candidate = computeBuildCandidate(st.placedPieces, aimPoint, st.buildKind, st.yaw12);
1249
+ const placed = st.placeBuildPiece(candidate);
1250
+ return {
1251
+ ok: placed !== null,
1252
+ status: placed ? `PLACED ${placed.kind}` : candidate.reason.toUpperCase(),
1253
+ beamEnd: candidate.position
1254
+ };
1255
+ }
1256
+ if (st.mode === "rig") {
1257
+ const hitJoint = findJointForBody(rawHit?.body ?? null);
1258
+ if (!hitJoint) {
1259
+ st.bumpFire("NO KHR JOINT HIT");
1260
+ return {
1261
+ ok: false,
1262
+ status: "NO KHR JOINT HIT",
1263
+ beamEnd: aimPoint
1264
+ };
1265
+ }
1266
+ const status = rigJointRuntime(hitJoint, shiftKey);
1267
+ st.bumpFire(status.toUpperCase());
1268
+ return {
1269
+ ok: true,
1270
+ status,
1271
+ beamEnd: aimPoint
1272
+ };
1273
+ }
1274
+ if (st.mode === "weld" || st.mode === "hinge") {
1275
+ if (!rawHit?.body) {
1276
+ st.setPendingAnchor(null);
1277
+ st.bumpFire("MISS — CLEARED ANCHOR");
1278
+ return {
1279
+ ok: false,
1280
+ status: "MISS — CLEARED ANCHOR",
1281
+ beamEnd: aimPoint
1282
+ };
1283
+ }
1284
+ const pending = st.pendingAnchor;
1285
+ if (!pending) {
1286
+ const label = rawHit.body.userData?.name ?? `body_${rawHit.body.handle}`;
1287
+ st.setPendingAnchor({
1288
+ body: rawHit.body,
1289
+ worldPoint: rawHit.point,
1290
+ worldNormal: rawHit.normal,
1291
+ label
1292
+ });
1293
+ st.bumpFire(`LOCKED A: ${label}`);
1294
+ return {
1295
+ ok: true,
1296
+ status: `LOCKED A: ${label}`,
1297
+ beamEnd: aimPoint
1298
+ };
1299
+ }
1300
+ if (pending.body.handle === rawHit.body.handle) {
1301
+ st.setPendingAnchor(null);
1302
+ st.bumpFire("SAME BODY — CANCELLED");
1303
+ return {
1304
+ ok: false,
1305
+ status: "SAME BODY — CANCELLED",
1306
+ beamEnd: aimPoint
1307
+ };
1308
+ }
1309
+ const anchorMid = [
1310
+ .5 * (pending.worldPoint[0] + rawHit.point[0]),
1311
+ .5 * (pending.worldPoint[1] + rawHit.point[1]),
1312
+ .5 * (pending.worldPoint[2] + rawHit.point[2])
1313
+ ];
1314
+ const imp = st.mode === "weld" ? createWeldImpulseJoint(rapier, rapierWorld, pending.body, rawHit.body, anchorMid) : createHingeImpulseJoint(rapier, rapierWorld, pending.body, rawHit.body, anchorMid, pending.worldNormal);
1315
+ const id = `tg_${st.mode}_${imp.handle}`;
1316
+ st.recordJoint({
1317
+ id,
1318
+ kind: st.mode,
1319
+ handle: imp.handle,
1320
+ joint: imp,
1321
+ anchorWorld: anchorMid
1322
+ });
1323
+ return {
1324
+ ok: true,
1325
+ status: `${st.mode.toUpperCase()} CREATED`,
1326
+ beamEnd: anchorMid
1327
+ };
1328
+ }
1329
+ if (!rawHit) {
1330
+ st.bumpFire("NOTHING HIT");
1331
+ return {
1332
+ ok: false,
1333
+ status: "NOTHING HIT",
1334
+ beamEnd: aimPoint
1335
+ };
1336
+ }
1337
+ const ud = rawHit.body?.userData ?? {};
1338
+ if (ud.kolmoPlacedPieceId && st.removePieceById(ud.kolmoPlacedPieceId)) return {
1339
+ ok: true,
1340
+ status: `REMOVED ${ud.kolmoPlacedPieceId}`,
1341
+ beamEnd: aimPoint
1342
+ };
1343
+ if (ud.kolmoSpawnedId && st.removeEntityById(ud.kolmoSpawnedId)) return {
1344
+ ok: true,
1345
+ status: `DELETED ${ud.kolmoSpawnedId}`,
1346
+ beamEnd: aimPoint
1347
+ };
1348
+ if (rawHit.body) {
1349
+ const removedJoints = st.removeJointByBody(rapierWorld, rawHit.body);
1350
+ if (removedJoints > 0) return {
1351
+ ok: true,
1352
+ status: `REMOVED ${removedJoints} JOINT(S)`,
1353
+ beamEnd: aimPoint
1354
+ };
1355
+ }
1356
+ st.bumpFire("STATIC WORLD TARGET");
1357
+ return {
1358
+ ok: false,
1359
+ status: "STATIC WORLD TARGET",
1360
+ beamEnd: aimPoint
1361
+ };
1362
+ }, [
1363
+ camera,
1364
+ rapier,
1365
+ rapierWorld,
1366
+ maxRangeM,
1367
+ resolvePlayerBody,
1368
+ findJointForBody,
1369
+ measured,
1370
+ beamGeo,
1371
+ beamLine
1372
+ ]);
1373
+ useImperativeHandle(ref, () => ({
1374
+ fire,
1375
+ undo: () => useToolgunStore.getState().undoLast(rapierWorld)
1376
+ }), [fire, rapierWorld]);
1377
+ useEffect(() => {
1378
+ if (!enable || !enableShortcuts || typeof window === "undefined") return;
1379
+ const isEditable = (el) => {
1380
+ if (!el) return false;
1381
+ const tag = el.tagName;
1382
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || Boolean(el.isContentEditable);
1383
+ };
1384
+ const onKeyDown = (e) => {
1385
+ if (isEditable(document.activeElement)) return;
1386
+ if (kootaWorld.queryFirst(pilotedVehicleQuery)) return;
1387
+ const st = useToolgunStore.getState();
1388
+ if (e.code >= "Digit1" && e.code <= "Digit6") {
1389
+ const idx = Number(e.code.slice(5)) - 1;
1390
+ if (TOOLGUN_MODES[idx]) st.setMode(TOOLGUN_MODES[idx]);
1391
+ return;
1392
+ }
1393
+ if (e.code === "KeyQ" && !e.metaKey && !e.ctrlKey) st.cycleMode(e.shiftKey ? -1 : 1);
1394
+ else if (e.code === "KeyR" && !e.metaKey && !e.ctrlKey) st.rotateYaw12(e.shiftKey ? -1 : 1);
1395
+ else if (e.code === "BracketLeft") st.cycleBuildKind(-1);
1396
+ else if (e.code === "BracketRight") st.cycleBuildKind(1);
1397
+ else if (e.code === "KeyZ" && !e.metaKey && !e.ctrlKey) st.undoLast(rapierWorld);
1398
+ else if (e.code === "Tab") {
1399
+ e.preventDefault();
1400
+ st.setZoomed(!st.zoomed);
1401
+ }
1402
+ };
1403
+ const dom = gl?.domElement;
1404
+ let downPos = null;
1405
+ const onPointerDown = (e) => {
1406
+ if (kootaWorld.queryFirst(pilotedVehicleQuery)) return;
1407
+ if (e.button === 2) useToolgunStore.getState().setZoomed(true);
1408
+ else if (e.button === 0) downPos = [e.clientX, e.clientY];
1409
+ };
1410
+ const onPointerUp = (e) => {
1411
+ if (e.button === 2) {
1412
+ useToolgunStore.getState().setZoomed(false);
1413
+ return;
1414
+ }
1415
+ if (e.button === 0 && downPos && !kootaWorld.queryFirst(pilotedVehicleQuery)) {
1416
+ const moved = Math.hypot(e.clientX - downPos[0], e.clientY - downPos[1]);
1417
+ downPos = null;
1418
+ if (moved <= 6) fire(e.shiftKey);
1419
+ }
1420
+ };
1421
+ const onContextMenu = (e) => {
1422
+ if (!kootaWorld.queryFirst(pilotedVehicleQuery)) e.preventDefault();
1423
+ };
1424
+ window.addEventListener("keydown", onKeyDown);
1425
+ dom?.addEventListener("pointerdown", onPointerDown);
1426
+ window.addEventListener("pointerup", onPointerUp);
1427
+ dom?.addEventListener("contextmenu", onContextMenu);
1428
+ return () => {
1429
+ window.removeEventListener("keydown", onKeyDown);
1430
+ dom?.removeEventListener("pointerdown", onPointerDown);
1431
+ window.removeEventListener("pointerup", onPointerUp);
1432
+ dom?.removeEventListener("contextmenu", onContextMenu);
1433
+ };
1434
+ }, [
1435
+ enable,
1436
+ enableShortcuts,
1437
+ gl,
1438
+ kootaWorld,
1439
+ rapierWorld,
1440
+ fire
1441
+ ]);
1442
+ useFrame((_, delta) => {
1443
+ const dt = Math.min(Math.max(delta, 1e-4), .05);
1444
+ const piloted = Boolean(kootaWorld.queryFirst(pilotedVehicleQuery));
1445
+ const holder = holderRef.current;
1446
+ if (holder) holder.visible = enable && !piloted;
1447
+ if (!enable || piloted) {
1448
+ beamLine.visible = false;
1449
+ return;
1450
+ }
1451
+ const st = useToolgunStore.getState();
1452
+ if (recoilRef.current > 0) recoilRef.current = Math.max(0, recoilRef.current - dt * 7.5);
1453
+ if (beamTimerRef.current > 0) {
1454
+ beamTimerRef.current = Math.max(0, beamTimerRef.current - dt);
1455
+ if (beamMatRef.current) beamMatRef.current.opacity = Math.min(1, beamTimerRef.current * 12);
1456
+ if (beamTimerRef.current <= 0) beamLine.visible = false;
1457
+ }
1458
+ if (holder) {
1459
+ const goal = st.zoomed ? zoomOffset : hipOffset;
1460
+ _targetOffset.set(goal[0], goal[1] - recoilRef.current * .012, goal[2] + recoilRef.current * .038);
1461
+ easing.damp3(holder.position, _targetOffset, .09, dt);
1462
+ holder.rotation.set(recoilRef.current * .14, 0, 0);
1463
+ }
1464
+ camera.getWorldPosition(_camPos);
1465
+ camera.getWorldDirection(_camDir);
1466
+ const playerBody = resolvePlayerBody();
1467
+ const hit = castToolgunRay(rapier, rapierWorld, [
1468
+ _camPos.x,
1469
+ _camPos.y,
1470
+ _camPos.z
1471
+ ], [
1472
+ _camDir.x,
1473
+ _camDir.y,
1474
+ _camDir.z
1475
+ ], maxRangeM, playerBody);
1476
+ let targetLabel = "NO TARGET";
1477
+ if (hit) {
1478
+ const jRt = findJointForBody(hit.body);
1479
+ const ud = hit.body?.userData ?? {};
1480
+ targetLabel = `${jRt ? `JOINT:${jRt.nodeName}` : ud.name ?? ud.kolmoPlacedPieceId ?? ud.kolmoSpawnedId ?? "SURFACE"} (${hit.toi.toFixed(1)}m)`;
1481
+ }
1482
+ if (st.mode === "build") {
1483
+ let fallbackPt = [
1484
+ _camPos.x + _camDir.x * 5,
1485
+ Math.max(0, _camPos.y + _camDir.y * 5),
1486
+ _camPos.z + _camDir.z * 5
1487
+ ];
1488
+ if (!hit && _camDir.y < -.02 && _camPos.y > 0) {
1489
+ const tFloor = -_camPos.y / _camDir.y;
1490
+ if (tFloor > .1 && tFloor <= maxRangeM) fallbackPt = [
1491
+ _camPos.x + _camDir.x * tFloor,
1492
+ 0,
1493
+ _camPos.z + _camDir.z * tFloor
1494
+ ];
1495
+ }
1496
+ const cand = computeBuildCandidate(st.placedPieces, hit ? hit.point : fallbackPt, st.buildKind, st.yaw12);
1497
+ const prev = st.buildPreview;
1498
+ if (!prev || prev.kind !== cand.kind || prev.valid !== cand.valid || Math.abs(prev.position[0] - cand.position[0]) > 1e-4 || Math.abs(prev.position[1] - cand.position[1]) > 1e-4 || Math.abs(prev.position[2] - cand.position[2]) > 1e-4 || Math.abs(prev.quaternion[1] - cand.quaternion[1]) > 1e-4) st.setBuildPreview(cand);
1499
+ } else if (st.buildPreview !== null) st.setBuildPreview(null);
1500
+ const detail = st.mode === "build" ? st.buildKind : st.mode === "spawn" ? st.armedAsset?.name ?? "UNARMED" : st.pendingAnchor ? `A: ${st.pendingAnchor.label}` : `${st.mode.toUpperCase()} READY`;
1501
+ lcd.draw({
1502
+ mode: st.mode,
1503
+ yawDeg: st.yaw12 * 30,
1504
+ detail,
1505
+ targetLabel,
1506
+ status: st.statusText,
1507
+ accentHex: TOOLGUN_SKIN_PRESETS[effSkin].accentHex
1508
+ });
1509
+ });
1510
+ const isPiloted = Boolean(useActiveKolmoWorld().queryFirst(VehicleTrait, PilotedTag));
1511
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1512
+ createPortal(/* @__PURE__ */ jsx("group", {
1513
+ ref: holderRef,
1514
+ position: [
1515
+ hipOffset[0],
1516
+ hipOffset[1],
1517
+ hipOffset[2]
1518
+ ],
1519
+ children: measured ? /* @__PURE__ */ jsxs("group", {
1520
+ position: measured.gripOffset,
1521
+ children: [/* @__PURE__ */ jsx("primitive", { object: measured.scene }), /* @__PURE__ */ jsxs("mesh", {
1522
+ position: measured.screenPos,
1523
+ quaternion: measured.screenQuat,
1524
+ children: [/* @__PURE__ */ jsx("planeGeometry", { args: measured.screenSize }), /* @__PURE__ */ jsx("meshBasicMaterial", {
1525
+ ...lcd.texture ? { map: lcd.texture } : { color: "#38bdf8" },
1526
+ toneMapped: false
1527
+ })]
1528
+ })]
1529
+ }) : /* @__PURE__ */ jsx(ProceduralToolgunBody, {
1530
+ skinPreset: effSkin,
1531
+ lcdTexture: lcd.texture
1532
+ })
1533
+ }), camera),
1534
+ /* @__PURE__ */ jsx("primitive", { object: beamLine }),
1535
+ enable && !isPiloted && mode === "build" && buildPreview && /* @__PURE__ */ jsx(BuildGhostPreview, { candidate: buildPreview }),
1536
+ mountWorldOutlets && /* @__PURE__ */ jsxs("group", {
1537
+ name: "kolmo_toolgun_outlets",
1538
+ children: [spawnedEntities.map((entry) => entry.kind === "vehicle" ? /* @__PURE__ */ jsx(KolmoVehicle, {
1539
+ id: entry.id,
1540
+ ...entry.bundle ? { bundle: entry.bundle } : {},
1541
+ ...entry.src ? { src: entry.src } : {},
1542
+ position: entry.position,
1543
+ quaternion: entry.quaternion,
1544
+ userData: {
1545
+ kolmoSpawnedId: entry.id,
1546
+ name: entry.name
1547
+ }
1548
+ }, entry.id) : /* @__PURE__ */ jsx(KolmoProp, {
1549
+ ...entry.bundle ? { bundle: entry.bundle } : {},
1550
+ ...entry.src ? { src: entry.src } : {},
1551
+ fixed: entry.fixed,
1552
+ position: entry.position,
1553
+ quaternion: entry.quaternion,
1554
+ rigidBodyProps: { userData: {
1555
+ kolmoSpawnedId: entry.id,
1556
+ name: entry.name
1557
+ } }
1558
+ }, entry.id)), placedPieces.map((piece) => /* @__PURE__ */ jsx(C12PieceColliderAndMesh, { piece }, piece.id))]
1559
+ })
1560
+ ] });
1561
+ }
1562
+ function ToolgunFromUrl({ src, ...rest }) {
1563
+ const bundle = useKhrGlb(src);
1564
+ return /* @__PURE__ */ jsx(ToolgunCore, {
1565
+ ...rest,
1566
+ viewmodelBundle: bundle
1567
+ });
1568
+ }
1569
+ function KolmoToolgun({ src, bundle, ...rest }) {
1570
+ const cloned = useMemo(() => bundle ? cloneKhrBundle(bundle) : null, [bundle]);
1571
+ if (src) return /* @__PURE__ */ jsx(ToolgunFromUrl, {
1572
+ src,
1573
+ ...rest
1574
+ });
1575
+ return /* @__PURE__ */ jsx(ToolgunCore, {
1576
+ ...rest,
1577
+ viewmodelBundle: cloned
1578
+ });
1579
+ }
1580
+ export { TOOLGUN_SKIN_PRESETS as a, computeBuildCandidate as c, createWeldImpulseJoint as d, rigJointRuntime as f, TOOLGUN_MODES as i, createHingeImpulseJoint as l, measureToolgunViewmodel as n, castToolgunRay as o, useToolgunStore as p, TOOLGUN_BUILD_KINDS as r, computeAlignedSpawnPose as s, KolmoToolgun as t, createToolgunStore as u };
1581
+
1582
+ //# sourceMappingURL=toolgun-BfcCIAQx.js.map