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