Repository navigation
Expand file tree
/
Copy pathInputFrameBridge.js
More file actions
213 lines (198 loc) · 7.69 KB
/
Copy pathInputFrameBridge.js
File metadata and controls
213 lines (198 loc) · 7.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import { requestMouseLock } from './FirstPersonInput.js';
const pointerPayload = (event) => ({
type: event.type,
pointerId: event.pointerId,
pointerType: event.pointerType,
button: event.button,
buttons: event.buttons,
clientX: event.clientX,
clientY: event.clientY,
movementX: event.movementX,
movementY: event.movementY,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
});
// Key events are dispatched on the worker's document stand-in, so worker-side
// shortcut handlers cannot see the focused element. Forward the bits their
// "is the user typing in a field?" checks read.
const keyTargetPayload = (target) => {
const tagName = typeof target?.tagName === 'string' ? target.tagName : '';
return tagName ? { tagName, isContentEditable: !!target.isContentEditable } : undefined;
};
const keyPayload = (event) => ({
type: event.type,
key: event.key,
code: event.code,
repeat: event.repeat,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
target: keyTargetPayload(event.target),
});
const TERRAIN_SHAPE_DRAG_TYPE = 'application/x-terrain-shape';
const hasTerrainShapeDrag = (event) => {
const types = event.dataTransfer?.types;
if (!types) return false;
if (typeof types.contains === 'function') return types.contains(TERRAIN_SHAPE_DRAG_TYPE);
return Array.from(types).includes(TERRAIN_SHAPE_DRAG_TYPE);
};
const dragPayload = (event) => ({
type: event.type,
clientX: event.clientX,
clientY: event.clientY,
ctrlKey: event.ctrlKey,
shiftKey: event.shiftKey,
altKey: event.altKey,
metaKey: event.metaKey,
dataTransfer: { dropEffect: 'copy' },
});
export class InputFrameBridge {
constructor({ canvas, send }) {
this.canvas = canvas;
this.send = send;
this.pointerEvents = [];
this.dragEvents = [];
this.keyEvents = [];
this.wheel = null;
this.frame = 0;
this.disposed = false;
this.listeners = [];
this.suppressContextMenuUntil = 0;
this.pointerLockEnabled = false;
this._bind();
}
_listen(target, type, handler, options) {
target?.addEventListener?.(type, handler, options);
this.listeners.push(() => target?.removeEventListener?.(type, handler, options));
}
_bind() {
// Pointer lock needs a real browser gesture, before input reaches the worker.
this._listen(this.canvas, 'click', (event) => {
if (!this.pointerLockEnabled || event.pointerType === 'touch' || event.button !== 0) return;
if (document.pointerLockElement === this.canvas) return;
requestMouseLock(this.canvas, event);
});
this._listen(document, 'pointerlockchange', () => this._flush());
this._listen(document, 'mousemove', (event) => {
if (document.pointerLockElement !== this.canvas) return;
this.pointerEvents.push({ ...pointerPayload(event), type: 'mousemove' });
this._schedule();
});
// Camera controls live inside the render worker, so their contextmenu
// handler runs against the worker DOM shim and cannot cancel the browser's
// native menu. Cancel it on the real canvas before forwarding input. The
// document listener also covers a right-drag released over landing/editor
// UI after it started on the canvas.
const onContextMenu = (event) => {
const path = event.composedPath?.() || [];
const fromCanvas = event.target === this.canvas || path.includes(this.canvas);
const followsCanvasRightPress = performance.now() <= this.suppressContextMenuUntil;
if (!fromCanvas && !followsCanvasRightPress) return;
event.preventDefault();
this.suppressContextMenuUntil = 0;
};
this._listen(this.canvas, 'contextmenu', onContextMenu);
this._listen(document, 'contextmenu', onContextMenu, true);
for (const type of ['pointerdown', 'pointermove', 'pointerup', 'pointercancel', 'pointerleave']) {
this._listen(this.canvas, type, (event) => {
if (type === 'pointerdown') {
// Worker-side setPointerCapture() is necessarily a no-op. Mirror it
// on the actual canvas so camera drags continue across UI overlays.
try { this.canvas.setPointerCapture?.(event.pointerId); } catch { /* unsupported pointer */ }
if (event.button === 2) {
this.suppressContextMenuUntil = performance.now() + 1500;
event.preventDefault();
}
} else if (type === 'pointerup' || type === 'pointercancel') {
try { this.canvas.releasePointerCapture?.(event.pointerId); } catch { /* already released */ }
}
this.pointerEvents.push(pointerPayload(event));
this._schedule();
}, { passive: type === 'pointermove' });
}
for (const type of ['dragover', 'drop']) {
this._listen(this.canvas, type, (event) => {
if (!hasTerrainShapeDrag(event)) return;
// A real dragover must be cancelled on the main thread or the browser
// will never emit drop. Forward a cloneable event to the render worker
// so ManualTerrainModeManager can update/commit its placement preview.
event.preventDefault();
event.dataTransfer.dropEffect = 'copy';
this.dragEvents.push(dragPayload(event));
if (type === 'drop') this._flush();
else this._schedule();
});
}
this._listen(this.canvas, 'wheel', (event) => {
event.preventDefault();
const current = this.wheel || { type: 'wheel', deltaX: 0, deltaY: 0, deltaMode: event.deltaMode };
current.deltaX += event.deltaX;
current.deltaY += event.deltaY;
current.clientX = event.clientX;
current.clientY = event.clientY;
this.wheel = current;
this._schedule();
}, { passive: false });
for (const type of ['keydown', 'keyup']) {
this._listen(document, type, (event) => {
this.keyEvents.push(keyPayload(event));
this._schedule();
}, true);
}
this._listen(document, 'visibilitychange', () => {
void this.send('setViewport', [{ visible: document.visibilityState === 'visible' }]);
});
this.resizeObserver = new ResizeObserver(() => this.sendViewport());
this.resizeObserver.observe(this.canvas.parentElement || this.canvas);
}
sendViewport() {
const rect = this.canvas.parentElement?.getBoundingClientRect?.() || this.canvas.getBoundingClientRect();
return this.send('setViewport', [{
width: Math.max(1, rect.width),
height: Math.max(1, rect.height),
pixelRatio: globalThis.devicePixelRatio || 1,
visible: document.visibilityState === 'visible',
}]);
}
_schedule() {
if (this.frame || this.disposed) return;
this.frame = requestAnimationFrame(() => {
this.frame = 0;
this._flush();
});
}
setPointerLockEnabled(enabled) {
this.pointerLockEnabled = !!enabled;
if (!this.pointerLockEnabled) this.exitPointerLock();
}
exitPointerLock() {
if (document.pointerLockElement === this.canvas) document.exitPointerLock?.();
}
_flush() {
if (this.disposed) return;
if (this.frame) cancelAnimationFrame(this.frame);
this.frame = 0;
const payload = {
pointerEvents: this.pointerEvents.splice(0),
dragEvents: this.dragEvents.splice(0),
keyEvents: this.keyEvents.splice(0),
wheel: this.wheel,
pointerLocked: document.pointerLockElement === this.canvas,
visible: document.visibilityState === 'visible',
};
this.wheel = null;
void this.send('applyInputFrame', [payload]);
}
dispose() {
this.disposed = true;
this.exitPointerLock();
if (this.frame) cancelAnimationFrame(this.frame);
this.frame = 0;
this.suppressContextMenuUntil = 0;
this.resizeObserver?.disconnect?.();
this.listeners.splice(0).forEach((dispose) => dispose());
}
}