@bendyline/molen-client 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/aircraft.mjs CHANGED
@@ -1,6 +1,679 @@
1
1
  import { t as createModelSignalVisual } from "./model-signals-DLgvjBeZ.mjs";
2
- import { t as createVehicleInteriorVisual } from "./vehicle-interior-DfpZwWEh.mjs";
2
+ import { t as applyLivery } from "./livery-qcDLzbU9.mjs";
3
+ import { n as aircraftObstacleContacts, r as createAircraftDamageVisual, t as createVehicleInteriorVisual } from "./vehicle-interior-CeyzF5El.mjs";
3
4
  import * as THREE from "three";
5
+ //#region src/aircraft-controls.ts
6
+ /** Discover moving controls from their authored input bindings, never from instrument needles. */
7
+ function createAircraftCockpit(model, spec) {
8
+ const controls = [];
9
+ let interior = spec.visual.interior === void 0 ? void 0 : structuredClone(spec.visual.interior);
10
+ const nodes = /* @__PURE__ */ new Map();
11
+ model.traverse((node) => nodes.set(node.name, [...nodes.get(node.name) ?? [], node]));
12
+ const add = (action, label, names, engine) => {
13
+ const control = {
14
+ id: `${action}:${engine ?? controls.length}`,
15
+ action,
16
+ label,
17
+ nodes: names,
18
+ ...engine === void 0 ? {} : { engine }
19
+ };
20
+ controls.push(control);
21
+ return control;
22
+ };
23
+ const bound = (source, pattern) => [...new Set((interior?.bindings ?? []).filter((b) => b.source === source && b.property !== "visible" && pattern.test(b.node) && nodes.has(b.node)).map((b) => b.node))];
24
+ const sticks = [...new Set([...bound("pitchInput", /stick|yoke|cyclic|column|control|wheel/i), ...bound("rollInput", /stick|yoke|cyclic|column|control|wheel/i)])];
25
+ if (!sticks.length && spec.visual.controlStick) sticks.push(spec.visual.controlStick.node);
26
+ add("stick", "Yoke / stick", sticks);
27
+ add("yaw", "Rudder pedals", bound("yawInput", /pedal/i));
28
+ const powerNodes = bound("power", /throttle|power|lever|quadrant|collective|thrust/i).filter((name) => !/pointer|needle|gauge|indicator/i.test(name));
29
+ if (!powerNodes.length && spec.visual.collective) powerNodes.push(spec.visual.collective.node);
30
+ const engines = [...spec.engines ?? []].sort((a, b) => b.position[0] - a.position[0]);
31
+ const independent = engines.length > 1 && powerNodes.length === engines.length && !powerNodes.some((name) => /collective|thrust/i.test(name));
32
+ model.updateMatrixWorld(true);
33
+ const localX = (name) => {
34
+ const node = nodes.get(name)?.[0];
35
+ return node ? model.worldToLocal(node.getWorldPosition(new THREE.Vector3())).x : 0;
36
+ };
37
+ powerNodes.sort((a, b) => localX(b) - localX(a));
38
+ add("power", spec.model === "helicopter" ? "Collective" : "All throttles", independent ? [] : powerNodes);
39
+ for (const [index, engine] of engines.entries()) {
40
+ if (engines.length < 2) break;
41
+ const names = independent ? [powerNodes[index]] : [];
42
+ add("power", `Engine ${index + 1} throttle`, names, engine.id);
43
+ for (const binding of interior?.bindings ?? []) if (binding.source === "power" && names.includes(binding.node)) binding.source = `engines.${engine.id}.power`;
44
+ }
45
+ add("engine", "Engine master", []);
46
+ const bank = spec.engines ?? (spec.engine ? [{
47
+ ...spec.engine,
48
+ id: "main"
49
+ }] : []);
50
+ for (const action of ["mixture", "propeller"]) {
51
+ const supported = bank.filter((e) => e.propulsion !== "jet" && (action === "mixture" ? e.mixtureControl : e.propellerControl));
52
+ const label = action === "mixture" ? "Mixture" : "Propeller RPM";
53
+ if (bank.length === 1 && supported.length) add(action, label, bound(action, /mixture|prop/i));
54
+ else for (const engine of supported) add(action, `Engine ${engines.findIndex((e) => e.id === engine.id) + 1} ${label.toLowerCase()}`, bound(`engines.${engine.id}.${action}`, /mixture|prop|condition/i), engine.id);
55
+ }
56
+ if (engines.length > 1) for (const [index, engine] of engines.entries()) add("engine", `Engine ${index + 1}`, [], engine.id);
57
+ for (const [action, label] of [
58
+ ["speedBrake", "Speed brake"],
59
+ ["tailHook", "Tail hook"],
60
+ ["canopy", "Canopy"],
61
+ ["wipers", "Wipers"],
62
+ ["headlights", "Lights"]
63
+ ]) if (spec.actuators?.[action]) add(action, label, []);
64
+ if (spec.model === "airplane" && !spec.airplane?.fixedGear || spec.helicopter?.fixedGear === false) add("gear", "Landing gear", [...bound("gear", /handle|lever|selector/i), ...bound("gearPosition", /handle|lever|selector/i)]);
65
+ if (spec.model === "airplane" && (spec.airplane?.flapLift ?? 0) > 0) add("flaps", "Flaps", bound("flapPosition", /flap.*(?:handle|lever|selector|pump)|(?:lever|handle).*flap|Skylane-flap|ATR72-power-lever-4/i));
66
+ if (spec.model === "airplane") add("brake", "Parking brake", []);
67
+ if (spec.poweredLift) add("thrustVector", "Nozzle / nacelle angle", bound("thrustVector", /lever|thumb/i));
68
+ model.traverse((node) => {
69
+ const authored = node.userData.aircraftControl;
70
+ if (!authored || !node.name) return;
71
+ const control = controls.find((entry) => entry.action === authored.action && entry.engine === authored.engine);
72
+ if (!control) return;
73
+ if (!control.nodes.includes(node.name)) control.nodes.push(node.name);
74
+ const motion = authored.motion;
75
+ if (!motion || !["position", "rotation"].includes(motion.property) || ![
76
+ "x",
77
+ "y",
78
+ "z"
79
+ ].includes(motion.axis) || !Number.isFinite(motion.scale) || motion.offset !== void 0 && !Number.isFinite(motion.offset)) return;
80
+ interior ??= {
81
+ nodes: [],
82
+ bindings: []
83
+ };
84
+ const source = authored.engine ? `engines.${authored.engine}.${authored.action === "engine" ? "enabled" : authored.action}` : {
85
+ yaw: "yawInput",
86
+ gear: "gearCommand",
87
+ flaps: "flapCommand",
88
+ thrustVector: "vectorCommand"
89
+ }[authored.action] ?? authored.action;
90
+ interior.bindings.push({
91
+ node: node.name,
92
+ source,
93
+ ...motion
94
+ });
95
+ });
96
+ const targets = /* @__PURE__ */ new Map();
97
+ for (const control of controls) for (const name of control.nodes) for (const node of nodes.get(name) ?? []) targets.set(node, control);
98
+ const caster = new THREE.Raycaster();
99
+ return {
100
+ controls,
101
+ interior,
102
+ pick(ray) {
103
+ caster.ray.copy(ray);
104
+ model.updateWorldMatrix(true, true);
105
+ for (const hit of caster.intersectObject(model, true)) {
106
+ let hidden = false;
107
+ for (let node = hit.object; node; node = node.parent) if (!node.visible) hidden = true;
108
+ if (hidden) continue;
109
+ for (let node = hit.object; node; node = node.parent) {
110
+ const control = targets.get(node);
111
+ if (control) return control;
112
+ }
113
+ const mesh = hit.object;
114
+ if ((Array.isArray(mesh.material) ? mesh.material : [mesh.material]).some((material) => material && !(material.transparent && material.opacity < .8))) return void 0;
115
+ }
116
+ }
117
+ };
118
+ }
119
+ function aircraftControlValue(input, control) {
120
+ if ([
121
+ "speedBrake",
122
+ "tailHook",
123
+ "canopy",
124
+ "wipers",
125
+ "headlights"
126
+ ].includes(control.action)) return Number(input.actuators?.[control.action] ?? 0);
127
+ if (control.action === "stick") return input.roll;
128
+ if (control.action === "power") return control.engine ? input.engines?.[control.engine]?.power ?? input.power : input.power;
129
+ if (control.action === "mixture" || control.action === "propeller") return (control.engine ? input.engines?.[control.engine]?.[control.action] : void 0) ?? input[control.action] ?? 1;
130
+ if (control.action === "engine") return Number(control.engine ? input.engines?.[control.engine]?.enabled ?? true : input.engine);
131
+ return Number(input[control.action] ?? 0);
132
+ }
133
+ /** Immutable pilot input update; hosts still submit it through flyAircraft's seat/authority checks. */
134
+ function applyAircraftControl(input, change, spec, state) {
135
+ if (!Number.isFinite(change.value) || change.pitch !== void 0 && !Number.isFinite(change.pitch)) return input;
136
+ const { control, value } = change;
137
+ const bank = spec.engines ?? (spec.engine ? [{
138
+ ...spec.engine,
139
+ id: "main"
140
+ }] : []);
141
+ if (control.engine && !bank.some((engine) => engine.id === control.engine)) return input;
142
+ const clamp = (v, low = 0) => Math.max(low, Math.min(1, v));
143
+ const next = { ...input };
144
+ if ([
145
+ "speedBrake",
146
+ "tailHook",
147
+ "canopy",
148
+ "wipers",
149
+ "headlights"
150
+ ].includes(control.action)) return spec.actuators?.[control.action] ? {
151
+ ...next,
152
+ actuators: {
153
+ ...input.actuators,
154
+ [control.action]: clamp(value)
155
+ }
156
+ } : input;
157
+ switch (control.action) {
158
+ case "stick":
159
+ next.roll = clamp(value, -1);
160
+ next.pitch = clamp(change.pitch ?? input.pitch, -1);
161
+ break;
162
+ case "yaw":
163
+ next.yaw = clamp(value, -1);
164
+ break;
165
+ case "power":
166
+ if (control.engine) next.engines = {
167
+ ...input.engines,
168
+ [control.engine]: {
169
+ ...input.engines?.[control.engine],
170
+ power: clamp(value)
171
+ }
172
+ };
173
+ else {
174
+ next.power = clamp(value);
175
+ if (input.engines) next.engines = Object.fromEntries(Object.entries(input.engines).map(([id, entry]) => [id, Object.fromEntries(Object.entries(entry).filter(([key]) => key !== "power"))]));
176
+ }
177
+ break;
178
+ case "mixture":
179
+ case "propeller": {
180
+ const action = control.action;
181
+ const supported = bank.filter((e) => e.propulsion !== "jet" && (action === "mixture" ? e.mixtureControl : e.propellerControl));
182
+ if (!supported.length || control.engine && !supported.some((e) => e.id === control.engine)) return input;
183
+ if (control.engine) next.engines = {
184
+ ...input.engines,
185
+ [control.engine]: {
186
+ ...input.engines?.[control.engine],
187
+ [action]: clamp(value)
188
+ }
189
+ };
190
+ else {
191
+ next[action] = clamp(value);
192
+ if (input.engines) next.engines = Object.fromEntries(Object.entries(input.engines).map(([id, entry]) => [id, Object.fromEntries(Object.entries(entry).filter(([key]) => key !== action))]));
193
+ }
194
+ break;
195
+ }
196
+ case "engine":
197
+ if (control.engine) next.engines = {
198
+ ...input.engines,
199
+ [control.engine]: {
200
+ ...input.engines?.[control.engine],
201
+ enabled: value > 0
202
+ }
203
+ };
204
+ else next.engine = value > 0;
205
+ break;
206
+ case "gear":
207
+ if ((spec.model === "airplane" ? spec.airplane?.fixedGear : spec.helicopter?.fixedGear !== false) || !state || state.grounded) return input;
208
+ next.gear = value > 0;
209
+ break;
210
+ case "flaps":
211
+ if (spec.model !== "airplane" || !spec.airplane?.flapLift) return input;
212
+ next.flaps = clamp(value);
213
+ break;
214
+ case "brake":
215
+ next.brake = value > 0;
216
+ break;
217
+ case "thrustVector":
218
+ if (!spec.poweredLift) return input;
219
+ next.thrustVector = clamp(value);
220
+ break;
221
+ }
222
+ return next;
223
+ }
224
+ /** Transient pointer axes are mixed with keyboard/gamepad axes without latching after release. */
225
+ var AircraftPointerAxes = class {
226
+ pitch = 0;
227
+ roll = 0;
228
+ yaw = 0;
229
+ set(change) {
230
+ if (change.control.action === "stick") {
231
+ this.roll = change.value;
232
+ this.pitch = change.pitch ?? 0;
233
+ }
234
+ if (change.control.action === "yaw") this.yaw = change.value;
235
+ }
236
+ clear() {
237
+ this.pitch = this.roll = this.yaw = 0;
238
+ }
239
+ };
240
+ //#endregion
241
+ //#region src/aircraft-propellers.ts
242
+ function createAircraftPropellers(model, spec) {
243
+ const propellers = [];
244
+ const engines = spec.engines ?? (spec.engine ? [{
245
+ ...spec.engine,
246
+ id: "main"
247
+ }] : []);
248
+ if (spec.model === "airplane") {
249
+ model.updateWorldMatrix(true, true);
250
+ for (const binding of spec.visual.rotors) {
251
+ const engine = binding.engine === void 0 ? engines[0] : engines.find((e) => e.id === binding.engine);
252
+ if (!engine || engine.propulsion === "jet") continue;
253
+ const nodes = [];
254
+ model.traverse((node) => {
255
+ if (node.name === binding.node) nodes.push(node);
256
+ });
257
+ for (const node of nodes) {
258
+ if (ancestors(node).some((parent) => nodes.includes(parent))) continue;
259
+ const axis = binding.axis;
260
+ const u = axis === "x" ? "y" : "x";
261
+ const v = axis === "z" ? "y" : "z";
262
+ const inverse = node.matrixWorld.clone().invert();
263
+ const sources = [];
264
+ const markings = [];
265
+ let radius = 0;
266
+ node.traverse((mesh) => {
267
+ if (!(mesh instanceof THREE.Mesh)) return;
268
+ if (mesh.userData.liveryMarking) {
269
+ markings.push(mesh);
270
+ return;
271
+ }
272
+ const transform = inverse.clone().multiply(mesh.matrixWorld);
273
+ const geometry = mesh.geometry;
274
+ const position = geometry.getAttribute("position");
275
+ if (!position) return;
276
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
277
+ const count = geometry.index?.count ?? position.count;
278
+ const groups = Array.isArray(mesh.material) ? geometry.groups : [{
279
+ start: 0,
280
+ count,
281
+ materialIndex: 0
282
+ }];
283
+ const bands = [];
284
+ for (const group of groups) {
285
+ const material = materials[group.materialIndex ?? 0];
286
+ if (!material?.visible || material.opacity <= 0) continue;
287
+ let inner = Infinity, outer = 0, area = 0, depth = 0, vertices = 0;
288
+ const points = [
289
+ new THREE.Vector3(),
290
+ new THREE.Vector3(),
291
+ new THREE.Vector3()
292
+ ];
293
+ for (let i = group.start; i + 2 < Math.min(count, group.start + group.count); i += 3) {
294
+ for (const [j, p] of points.entries()) {
295
+ p.fromBufferAttribute(position, geometry.index?.getX(i + j) ?? i + j);
296
+ p.applyMatrix4(transform);
297
+ const r = Math.hypot(p[u], p[v]);
298
+ inner = Math.min(inner, r);
299
+ outer = Math.max(outer, r);
300
+ depth += p[axis];
301
+ vertices++;
302
+ }
303
+ const [a, b, c] = points;
304
+ area += Math.abs((b[u] - a[u]) * (c[v] - a[v]) - (b[v] - a[v]) * (c[u] - a[u])) / 4;
305
+ }
306
+ if (outer <= inner || !area) continue;
307
+ const color = material.color?.clone() ?? new THREE.Color(5592405);
308
+ bands.push({
309
+ inner,
310
+ outer,
311
+ area: area * material.opacity,
312
+ color,
313
+ depth: depth / vertices
314
+ });
315
+ radius = Math.max(radius, outer);
316
+ }
317
+ sources.push({
318
+ mesh,
319
+ bands
320
+ });
321
+ });
322
+ if (radius <= 0) continue;
323
+ const blades = sources.filter(({ bands }) => bands.some((b) => b.outer > radius * .35));
324
+ const bands = blades.flatMap((b) => b.bands);
325
+ if (!bands.length) continue;
326
+ for (const mesh of markings) if (ancestors(mesh).some((parent) => blades.some((blade) => blade.mesh === parent))) blades.push({
327
+ mesh,
328
+ bands: []
329
+ });
330
+ const disk = blurDisk(bands, radius, axis);
331
+ disk.name = `propeller-blur:${binding.node}`;
332
+ disk.userData.walkIgnore = true;
333
+ disk.userData.vehicleGeometry = true;
334
+ disk.raycast = () => {};
335
+ disk.visible = false;
336
+ node.add(disk);
337
+ const parents = [node, ...ancestors(node)];
338
+ propellers.push({
339
+ engine: engine.id,
340
+ speed: Math.abs(engine.rotorAngularSpeed * binding.multiplier),
341
+ parts: (spec.collisionParts ?? []).filter((part) => parents.some((p) => part.nodes.includes(p.userData.name ?? p.name))).map((part) => part.id),
342
+ disk,
343
+ blades: blades.map(({ mesh }) => {
344
+ const original = mesh.material;
345
+ return {
346
+ mesh,
347
+ original,
348
+ faded: (Array.isArray(original) ? original : [original]).map((m) => {
349
+ const clone = m.clone();
350
+ clone.transparent = true;
351
+ clone.depthWrite = false;
352
+ return clone;
353
+ }),
354
+ shadow: mesh.castShadow
355
+ };
356
+ })
357
+ });
358
+ }
359
+ }
360
+ }
361
+ return {
362
+ update(state) {
363
+ for (const prop of propellers) {
364
+ const rpm = (prop.engine === void 0 ? void 0 : state.engines?.[prop.engine])?.rpm ?? state.rpm;
365
+ const blend = prop.parts.some((part) => state.damage?.[part]?.detached) || !Number.isFinite(rpm) ? 0 : THREE.MathUtils.smoothstep(Math.abs(rpm * prop.speed), 20, 60);
366
+ prop.disk.visible = blend > 0;
367
+ prop.disk.material.opacity = blend;
368
+ for (const { mesh, original, faded, shadow } of prop.blades) {
369
+ const originals = Array.isArray(original) ? original : [original];
370
+ for (const [i, material] of faded.entries()) {
371
+ const source = originals[i];
372
+ material.opacity = source.opacity * (1 - blend);
373
+ material.visible = source.visible && blend < 1;
374
+ }
375
+ mesh.material = blend === 0 ? original : Array.isArray(original) ? faded : faded[0];
376
+ mesh.castShadow = shadow && blend === 0;
377
+ }
378
+ }
379
+ },
380
+ dispose() {
381
+ for (const prop of propellers) {
382
+ for (const { mesh, original, faded, shadow } of prop.blades) {
383
+ mesh.material = original;
384
+ mesh.castShadow = shadow;
385
+ for (const material of faded) material.dispose();
386
+ }
387
+ prop.disk.removeFromParent();
388
+ prop.disk.geometry.dispose();
389
+ prop.disk.material.dispose();
390
+ }
391
+ propellers.length = 0;
392
+ }
393
+ };
394
+ }
395
+ function ancestors(node) {
396
+ const parents = [];
397
+ for (let parent = node.parent; parent; parent = parent.parent) parents.push(parent);
398
+ return parents;
399
+ }
400
+ function blurDisk(bands, radius, axis) {
401
+ const rings = 48, segments = 64;
402
+ const geometry = new THREE.RingGeometry(0, radius, segments, rings);
403
+ const position = geometry.getAttribute("position");
404
+ const colors = new Float32Array(position.count * 4);
405
+ const totalArea = bands.reduce((sum, b) => sum + b.area, 0);
406
+ const depth = bands.reduce((sum, b) => sum + b.depth * b.area, 0) / totalArea;
407
+ for (let ring = 0; ring <= rings; ring++) {
408
+ const r = ring / rings * radius;
409
+ const color = new THREE.Color(0, 0, 0);
410
+ let alpha = 0;
411
+ for (const band of bands) {
412
+ const feather = Math.min(radius / rings, (band.outer - band.inner) / 2);
413
+ const coverage = band.area / (Math.PI * (band.outer ** 2 - band.inner ** 2)) * THREE.MathUtils.smoothstep(r, band.inner, band.inner + feather) * (1 - THREE.MathUtils.smoothstep(r, band.outer - feather, band.outer));
414
+ color.add(band.color.clone().multiplyScalar(coverage));
415
+ alpha += coverage;
416
+ }
417
+ if (alpha > 0) color.multiplyScalar(1 / alpha);
418
+ for (let segment = 0; segment <= segments; segment++) {
419
+ const i = ring * 65 + segment;
420
+ colors.set([
421
+ color.r,
422
+ color.g,
423
+ color.b,
424
+ Math.min(.45, alpha)
425
+ ], i * 4);
426
+ }
427
+ }
428
+ geometry.setAttribute("color", new THREE.BufferAttribute(colors, 4));
429
+ if (axis === "x") geometry.rotateY(Math.PI / 2);
430
+ else if (axis === "y") geometry.rotateX(-Math.PI / 2);
431
+ geometry.translate(axis === "x" ? depth : 0, axis === "y" ? depth : 0, axis === "z" ? depth : 0);
432
+ return new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
433
+ vertexColors: true,
434
+ transparent: true,
435
+ depthWrite: false,
436
+ side: THREE.DoubleSide,
437
+ forceSinglePass: true
438
+ }));
439
+ }
440
+ //#endregion
441
+ //#region src/aircraft-cockpit-pointer.ts
442
+ function bindAircraftCockpitPointer(options) {
443
+ let binding;
444
+ return {
445
+ update() {
446
+ if (!binding && options.session()) binding = bindActiveCockpitPointer(options);
447
+ binding?.update();
448
+ },
449
+ dispose() {
450
+ binding?.dispose();
451
+ binding = void 0;
452
+ }
453
+ };
454
+ }
455
+ function bindActiveCockpitPointer(options) {
456
+ const { element } = options;
457
+ const doc = element.ownerDocument;
458
+ const win = doc.defaultView;
459
+ const panel = doc.createElement("details");
460
+ panel.className = "molen-cockpit-controls";
461
+ panel.style.cssText = "position:absolute;right:12px;bottom:16px;z-index:20;max-width:320px;max-height:55%;overflow:auto;background:#101a22ed;color:#edf3f6;border:1px solid #647783;border-radius:8px;padding:9px 12px;font:12px/1.5 system-ui;box-shadow:0 4px 16px #0005;";
462
+ const summary = doc.createElement("summary");
463
+ summary.textContent = "Cockpit controls";
464
+ summary.style.cursor = "pointer";
465
+ panel.append(summary);
466
+ const content = doc.createElement("div");
467
+ panel.append(content);
468
+ if (options.companionPanel) (options.container ?? element.parentElement)?.append(panel);
469
+ panel.hidden = true;
470
+ const hint = doc.createElement("div");
471
+ hint.setAttribute("role", "status");
472
+ hint.style.cssText = "position:absolute;left:50%;bottom:18px;transform:translateX(-50%);z-index:21;pointer-events:none;background:#101a22e8;color:#fff;padding:5px 10px;border-radius:5px;font:12px system-ui;";
473
+ hint.hidden = true;
474
+ (options.container ?? element.parentElement)?.append(hint);
475
+ const caster = new THREE.Raycaster();
476
+ let active;
477
+ let drag;
478
+ const fields = [];
479
+ const originalCursor = element.style.cursor;
480
+ const cancel = () => {
481
+ const previous = drag;
482
+ drag = void 0;
483
+ previous?.session.release();
484
+ active?.release();
485
+ if (previous && element.hasPointerCapture(previous.pointer)) element.releasePointerCapture(previous.pointer);
486
+ element.style.cursor = originalCursor;
487
+ hint.hidden = true;
488
+ };
489
+ const usable = () => doc.hidden ? void 0 : options.session();
490
+ const showHint = (control, session) => {
491
+ hint.hidden = control === void 0;
492
+ if (control) {
493
+ const value = session ? aircraftControlValue(session.input, control) : 0;
494
+ hint.textContent = control.action === "gear" && session?.state?.grounded ? `${control.label} · locked while on the ground` : control.action === "stick" ? `${control.label} · drag to steer; release to center` : control.action === "yaw" ? `${control.label} · drag sideways; release to center` : `${control.label} · ${[
495
+ "gear",
496
+ "engine",
497
+ "brake"
498
+ ].includes(control.action) ? `${value ? "on" : "off"} · click to toggle` : `${Math.round(value * 100)}%${control.action === "mixture" && value === 0 ? " · idle cutoff" : ""} · drag up to increase`}`;
499
+ }
500
+ };
501
+ const pick = (event, session) => {
502
+ const rect = element.getBoundingClientRect();
503
+ if (!rect.width || !rect.height) return void 0;
504
+ options.camera.updateWorldMatrix(true, false);
505
+ caster.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, 1 - (event.clientY - rect.top) / rect.height * 2), options.camera);
506
+ return session.cockpit.pick(caster.ray);
507
+ };
508
+ const stop = (event) => {
509
+ event.preventDefault();
510
+ event.stopImmediatePropagation();
511
+ };
512
+ const down = (event) => {
513
+ if (event.button !== 0 || drag) return;
514
+ const session = usable();
515
+ if (!session) return;
516
+ const control = pick(event, session);
517
+ if (!control) return;
518
+ stop(event);
519
+ element.focus({ preventScroll: true });
520
+ const value = aircraftControlValue(session.input, control);
521
+ if ([
522
+ "gear",
523
+ "engine",
524
+ "brake"
525
+ ].includes(control.action)) {
526
+ session.change({
527
+ control,
528
+ value: Number(!value)
529
+ });
530
+ showHint(control, usable());
531
+ return;
532
+ }
533
+ drag = {
534
+ session,
535
+ control,
536
+ pointer: event.pointerId,
537
+ x: event.clientX,
538
+ y: event.clientY,
539
+ value,
540
+ pitch: session.input.pitch
541
+ };
542
+ element.setPointerCapture(event.pointerId);
543
+ element.style.cursor = "grabbing";
544
+ showHint(control, session);
545
+ };
546
+ const move = (event) => {
547
+ const session = usable();
548
+ if (drag && (!session || session.id !== drag.session.id || session.cockpit !== drag.session.cockpit)) cancel();
549
+ if (drag && event.pointerId === drag.pointer) {
550
+ stop(event);
551
+ const x = (event.clientX - drag.x) / 120, y = (event.clientY - drag.y) / 160;
552
+ const action = drag.control.action;
553
+ const value = action === "stick" || action === "yaw" ? Math.max(-1, Math.min(1, drag.value + x)) : Math.max(0, Math.min(1, drag.value - y));
554
+ drag.session.change({
555
+ control: drag.control,
556
+ value,
557
+ ...action === "stick" ? { pitch: Math.max(-1, Math.min(1, drag.pitch + y)) } : {}
558
+ });
559
+ showHint(drag.control, usable());
560
+ } else if (session && event.buttons === 0) {
561
+ const control = pick(event, session);
562
+ element.style.cursor = control ? "pointer" : originalCursor;
563
+ showHint(control, session);
564
+ }
565
+ };
566
+ const up = (event) => {
567
+ if (drag?.pointer === event.pointerId) {
568
+ stop(event);
569
+ cancel();
570
+ }
571
+ };
572
+ const lost = (event) => {
573
+ if (drag?.pointer === event.pointerId) cancel();
574
+ };
575
+ const rebuild = (session) => {
576
+ content.replaceChildren();
577
+ fields.length = 0;
578
+ const help = doc.createElement("p");
579
+ help.textContent = "Drag the yoke, pedals or throttle in the cockpit. Common power synchronizes all engines.";
580
+ content.append(help);
581
+ for (const control of session.cockpit.controls) {
582
+ if (control.action === "stick" || control.action === "yaw") continue;
583
+ const row = doc.createElement("label");
584
+ row.style.cssText = "display:grid;grid-template-columns:125px 1fr 38px;align-items:center;gap:7px;margin:6px 0;";
585
+ const name = doc.createElement("span");
586
+ name.textContent = control.label;
587
+ const output = doc.createElement("output");
588
+ const field = [
589
+ "gear",
590
+ "engine",
591
+ "brake"
592
+ ].includes(control.action) ? doc.createElement("button") : doc.createElement("input");
593
+ field.setAttribute("aria-label", control.label);
594
+ field.style.cssText = "min-width:0;width:100%;accent-color:#62c9ec;";
595
+ if (field instanceof HTMLInputElement) {
596
+ field.type = "range";
597
+ field.min = "0";
598
+ field.max = "1";
599
+ field.step = "0.01";
600
+ field.addEventListener("input", () => {
601
+ const current = usable();
602
+ if (current?.id === session.id && current.cockpit === session.cockpit) current.change({
603
+ control,
604
+ value: Number(field.value)
605
+ });
606
+ });
607
+ } else {
608
+ field.type = "button";
609
+ field.addEventListener("click", () => {
610
+ const current = usable();
611
+ if (current?.id === session.id && current.cockpit === session.cockpit) current.change({
612
+ control,
613
+ value: Number(!aircraftControlValue(current.input, control))
614
+ });
615
+ });
616
+ }
617
+ row.append(name, field, output);
618
+ content.append(row);
619
+ fields.push({
620
+ control,
621
+ field,
622
+ output
623
+ });
624
+ }
625
+ };
626
+ element.addEventListener("pointerdown", down, true);
627
+ element.addEventListener("pointermove", move, true);
628
+ element.addEventListener("pointerup", up, true);
629
+ element.addEventListener("pointercancel", up, true);
630
+ element.addEventListener("lostpointercapture", lost);
631
+ panel.addEventListener("keydown", (event) => event.stopPropagation());
632
+ panel.addEventListener("keyup", (event) => event.stopPropagation());
633
+ win?.addEventListener("blur", cancel);
634
+ doc.addEventListener("visibilitychange", cancel);
635
+ return {
636
+ update() {
637
+ const session = usable();
638
+ if (session?.id !== active?.id || session?.cockpit !== active?.cockpit) {
639
+ cancel();
640
+ active = session;
641
+ if (session) {
642
+ if (doc.pointerLockElement === element) doc.exitPointerLock();
643
+ rebuild(session);
644
+ }
645
+ }
646
+ panel.hidden = !session;
647
+ if (!session) return;
648
+ for (const { control, field, output } of fields) {
649
+ const value = aircraftControlValue(session.input, control);
650
+ const locked = control.action === "gear" && (!session.state || session.state.grounded);
651
+ field.disabled = locked;
652
+ if (field instanceof HTMLInputElement) {
653
+ field.value = String(value);
654
+ output.value = `${Math.round(value * 100)}%`;
655
+ } else {
656
+ field.textContent = control.action === "gear" ? value ? "Down" : "Up" : value ? "On" : "Off";
657
+ field.setAttribute("aria-pressed", String(value > 0));
658
+ output.value = locked ? "Locked" : "";
659
+ }
660
+ }
661
+ },
662
+ dispose() {
663
+ cancel();
664
+ element.removeEventListener("pointerdown", down, true);
665
+ element.removeEventListener("pointermove", move, true);
666
+ element.removeEventListener("pointerup", up, true);
667
+ element.removeEventListener("pointercancel", up, true);
668
+ element.removeEventListener("lostpointercapture", lost);
669
+ win?.removeEventListener("blur", cancel);
670
+ doc.removeEventListener("visibilitychange", cancel);
671
+ panel.remove();
672
+ hint.remove();
673
+ }
674
+ };
675
+ }
676
+ //#endregion
4
677
  //#region src/aircraft.ts
5
678
  /**
6
679
  * Takes ownership of a loaded library GLB. The named nodes remain editable in a DCC.
@@ -8,10 +681,12 @@ import * as THREE from "three";
8
681
  * The gear and flaps follow `state.gearPosition` and `state.flapPosition` as they travel, or the
9
682
  * selection in `input` when the state has no positions (helicopters, hosts that animate only).
10
683
  */
11
- function createAircraftVisual(model, spec) {
12
- const interior = spec.visual.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, spec.visual.interior);
684
+ function createAircraftVisual(model, spec, livery) {
685
+ const cockpit = createAircraftCockpit(model, spec);
686
+ const interior = cockpit.interior === void 0 ? void 0 : createVehicleInteriorVisual(model, cockpit.interior);
13
687
  const animation = spec.visual.animation === void 0 ? void 0 : createModelSignalVisual(model, spec.visual.animation);
14
688
  const moving = /* @__PURE__ */ new Map();
689
+ const articulatedGear = new Set((spec.visual.animation?.bindings ?? []).filter((binding) => binding.property === "rotation" || binding.property === "position").map((binding) => binding.node));
15
690
  model.traverse((o) => {
16
691
  o.userData.vehicleGeometry = true;
17
692
  if (o instanceof THREE.Mesh) {
@@ -25,8 +700,25 @@ function createAircraftVisual(model, spec) {
25
700
  const turn = (name, axis, angle) => {
26
701
  for (const node of moving.get(name) ?? []) node.rotation[axis] = angle;
27
702
  };
703
+ let appearance = livery === void 0 ? void 0 : applyLivery(model, livery);
704
+ const cabin = (spec.visual.interior?.nodes ?? []).flatMap((name) => moving.get(name) ?? []);
705
+ for (const node of cabin) node.traverse((object) => {
706
+ if (object.isMesh) object.userData.walkIgnore = true;
707
+ });
708
+ const cabinRange = Math.max(60, 3 * Math.max(spec.length, spec.span));
709
+ const damage = createAircraftDamageVisual(model, spec);
710
+ let propellers = createAircraftPropellers(model, spec);
711
+ let cabinShown = true;
28
712
  return {
713
+ setLivery(data) {
714
+ propellers.dispose();
715
+ appearance?.dispose();
716
+ damage.reset();
717
+ appearance = data === void 0 ? void 0 : applyLivery(model, data);
718
+ propellers = createAircraftPropellers(model, spec);
719
+ },
29
720
  object: model,
721
+ cockpit,
30
722
  interior,
31
723
  animation,
32
724
  update(state, input, altitude, signals, timeSeconds) {
@@ -36,16 +728,23 @@ function createAircraftVisual(model, spec) {
36
728
  const engine = binding.engine === void 0 ? void 0 : state.engines?.[binding.engine];
37
729
  turn(binding.node, binding.axis, (engine?.rotorAngle ?? state.rotorAngle) * binding.multiplier);
38
730
  }
39
- for (const name of spec.visual.gearNodes) for (const node of moving.get(name) ?? []) node.visible = gear > 0;
731
+ for (const name of spec.visual.gearNodes) {
732
+ if (articulatedGear.has(name)) continue;
733
+ for (const node of moving.get(name) ?? []) node.visible = gear > 0;
734
+ }
40
735
  for (const binding of spec.visual.flaps) turn(binding.node, binding.axis, flaps * binding.multiplier);
41
736
  for (const binding of spec.visual.ailerons) turn(binding.node, binding.axis, input.roll * binding.multiplier);
42
- if (interior === void 0 && spec.visual.controlStick !== void 0) {
737
+ if (spec.visual.interior === void 0 && spec.visual.controlStick !== void 0) {
43
738
  turn(spec.visual.controlStick.node, spec.visual.controlStick.pitchAxis, input.pitch * .22);
44
739
  turn(spec.visual.controlStick.node, spec.visual.controlStick.rollAxis, input.roll * .22);
45
740
  }
46
- if (interior === void 0 && spec.visual.collective !== void 0) turn(spec.visual.collective.node, spec.visual.collective.axis, input.power * spec.visual.collective.multiplier);
741
+ if (spec.visual.interior === void 0 && spec.visual.collective !== void 0) turn(spec.visual.collective.node, spec.visual.collective.axis, input.power * spec.visual.collective.multiplier);
47
742
  const engineSignals = Object.create(null);
48
- for (const engine of spec.engines ?? []) {
743
+ const bank = spec.engines ?? (spec.engine ? [{
744
+ ...spec.engine,
745
+ id: "main"
746
+ }] : []);
747
+ for (const engine of bank) {
49
748
  const reading = state.engines?.[engine.id];
50
749
  const prefix = `engines.${engine.id}.`;
51
750
  engineSignals[`${prefix}rpmNormalized`] = reading?.rpm;
@@ -53,6 +752,8 @@ function createAircraftVisual(model, spec) {
53
752
  engineSignals[`${prefix}failed`] = reading === void 0 ? void 0 : Number(reading.failed);
54
753
  engineSignals[`${prefix}thrustN`] = reading?.thrust;
55
754
  engineSignals[`${prefix}afterburner`] = reading?.afterburner ?? 0;
755
+ engineSignals[`${prefix}shaftPowerW`] = reading?.shaftPower;
756
+ engineSignals[`${prefix}combustion`] = reading?.combustion;
56
757
  }
57
758
  const telemetry = {
58
759
  airspeed: state.airspeed,
@@ -92,13 +793,41 @@ function createAircraftVisual(model, spec) {
92
793
  engine: Number(input.engine),
93
794
  brake: Number(input.brake),
94
795
  grounded: Number(state.grounded),
796
+ ...state.actuators,
95
797
  ...engineSignals,
96
798
  ...signals
97
799
  };
800
+ for (const engine of bank) {
801
+ telemetry[`engines.${engine.id}.power`] = input.engines?.[engine.id]?.power ?? input.power;
802
+ telemetry[`engines.${engine.id}.enabled`] = Number(input.engines?.[engine.id]?.enabled ?? true);
803
+ for (const action of ["mixture", "propeller"]) telemetry[`engines.${engine.id}.${action}`] = input.engines?.[engine.id]?.[action] ?? input[action] ?? 1;
804
+ }
805
+ Object.assign(telemetry, {
806
+ gearCommand: Number(input.gear),
807
+ flapCommand: Number(input.flaps),
808
+ vectorCommand: input.thrustVector ?? 0,
809
+ engine: Number(input.engine),
810
+ brake: Number(input.brake),
811
+ mixture: input.mixture ?? 1,
812
+ propeller: input.propeller ?? 1
813
+ });
98
814
  interior?.update(telemetry, timeSeconds);
99
815
  animation?.update(telemetry, timeSeconds);
816
+ propellers.update(state);
817
+ damage.update(state);
818
+ },
819
+ updateView(camera) {
820
+ if (cabin.length === 0) return;
821
+ const p = model.position;
822
+ const shown = Math.hypot(p.x - camera[0], p.y - camera[1], p.z - camera[2]) < cabinRange * (cabinShown ? 1.1 : 1);
823
+ if (shown === cabinShown) return;
824
+ cabinShown = shown;
825
+ for (const node of cabin) node.visible = shown;
100
826
  },
101
827
  dispose() {
828
+ damage.reset();
829
+ propellers.dispose();
830
+ appearance?.dispose();
102
831
  const geometries = /* @__PURE__ */ new Set(), materials = /* @__PURE__ */ new Set();
103
832
  model.traverse((o) => {
104
833
  if (o instanceof THREE.Mesh) {
@@ -142,4 +871,4 @@ function aircraftCameraPose(transform, spec, options) {
142
871
  };
143
872
  }
144
873
  //#endregion
145
- export { aircraftCameraPose, createAircraftVisual };
874
+ export { AircraftPointerAxes, aircraftCameraPose, aircraftControlValue, aircraftObstacleContacts, applyAircraftControl, bindAircraftCockpitPointer, createAircraftCockpit, createAircraftVisual };