@margoengine/input 0.1.0 → 1.0.0

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.
Files changed (4) hide show
  1. package/LICENSE +201 -201
  2. package/NOTICE +4 -4
  3. package/README.md +609 -370
  4. package/package.json +105 -105
package/README.md CHANGED
@@ -1,370 +1,609 @@
1
- # @margoengine/input
2
-
3
- Import `margoengine/input` from the `margoengine` package, or `@margoengine/input` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
-
5
- Semantic actions combine keyboard codes, mouse buttons and relative motion, gamepad axes/buttons, and touch controls.
6
-
7
- ```ts
8
- import {Input} from 'margoengine/input';
9
- const input = new Input({jump: [{type: 'key', code: 'Space'}]});
10
- input.update();
11
- const {pressed, value} = input.state('jump');
12
- ```
13
-
14
- Call update once per simulation tick. State objects are reused. Opposing bindings sum and clamp to -1..1; gamepad axes use a configurable deadzone. createStick(parent, id) creates a pointer-captured virtual stick; bindTouchButton(button, id) supports pointer and keyboard activation. rumble(durationMs, strength, gamepadIndex) returns false when no actuator is available. dispose removes listeners and owned stick elements. Editable fields do not trigger gameplay key-down actions. Mouse motion is relative, not an absolute screen cursor.
15
-
16
- ## Chords, contexts, rebinding and prompts
17
-
18
- ```ts
19
- import {Input, bindingLabel} from 'margoengine/input';
20
- const input = new Input(
21
- {
22
- jump: [{type: 'key', code: 'Space'}],
23
- save: [{type: 'key', code: 'KeyS', modifiers: ['ctrl']}],
24
- confirm: [{type: 'key', code: 'Enter'}],
25
- },
26
- {contexts: {game: ['jump'], menu: ['confirm']}},
27
- );
28
- input.setContext('game', false); // a menu opened: jump reads 0 and releases; confirm keeps working
29
- const prompt = bindingLabel(input.actions.save[0]); // "Ctrl+S"; gamepad buttons use 'xbox' | 'playstation' | 'generic' names
30
- const pressed = input.captureBinding({signal: AbortSignal.timeout(10_000)}); // "press a key to rebind"
31
- window.dispatchEvent(new KeyboardEvent('keydown', {code: 'KeyJ'})); // stands in for the player's key press
32
- const binding = await pressed;
33
- input.rebind('jump', [binding]);
34
- localStorage.setItem('bindings', JSON.stringify(input.exportBindings()));
35
- input.importBindings(localStorage.getItem('bindings')!); // unknown actions are ignored; invalid data changes nothing
36
- input.resetBindings();
37
- ```
38
-
39
- - `modifiers` (`'shift' | 'ctrl' | 'alt' | 'meta'`) on a `key` binding makes a chord: the key counts only while every modifier is held.
40
- - `contexts` (option) group actions; an action owned by contexts reads 0 unless one is enabled. Unlisted actions are always active.
41
- - `captureBinding` resolves with the next key (with held modifiers), mouse button or gamepad button; Escape or the signal rejects with `AbortError`. A modifier pressed alone waits: Ctrl then S gives Ctrl+S, and Shift pressed and released alone gives Shift. A gamepad button already held when the prompt opens counts only after it is released and pressed again.
42
- - Mouse buttons follow Pointer Events chords: a second button pressed or released during a drag counts, though the browser sends it as a `pointermove`.
43
-
44
- ## Tap, hold, slow tap and double press
45
-
46
- `@margoengine/input/interactions` turns a press into what the player meant. Rules are named, like actions, and read any action, or one binding of it:
47
-
48
- ```ts
49
- import {Input} from 'margoengine/input';
50
- import {Interactions} from 'margoengine/input/interactions';
51
-
52
- const input = new Input({
53
- use: [{type: 'key', code: 'KeyE'}, {type: 'gamepad-button', index: 2}],
54
- dodge: [{type: 'key', code: 'KeyD'}],
55
- fire: [{type: 'gamepad-button', index: 7}],
56
- });
57
- const rules = new Interactions(input, {
58
- open: {type: 'tap', action: 'use'},
59
- inspect: {type: 'hold', action: 'use', time: 600},
60
- dash: {type: 'double-press', action: 'dodge'},
61
- heavy: {type: 'slow-tap', action: 'fire', threshold: 0.8},
62
- padOnly: {type: 'hold', action: 'use', binding: 1},
63
- });
64
- function tick() {
65
- input.update();
66
- rules.update();
67
- if (rules.state('open').performed) console.log('open');
68
- if (rules.state('dash').performed) console.log('dash');
69
- const charge = rules.state('heavy').progress; // 0 to 1, for a charge bar
70
- console.log(charge);
71
- }
72
- tick();
73
- ```
74
-
75
- - `tap`: pressed and released within `time` (default 200 ms). Performed on release.
76
- - `hold`: held for `time` (default 400 ms). Performed while still held.
77
- - `slow-tap`: held for at least `time` (default 500 ms), then released. Performed on release.
78
- - `double-press`: `count` presses (default 2), each shorter than `time` (default 200 ms), each within `gap` (default 300 ms) of the last release. Performed on the last press.
79
- - `binding` (default: the whole action): an index into `input.actions[action]`, so a rule can read one device; after a rebind it reads what is bound there.
80
- - `threshold` (default 0.5): magnitude that counts as pressed, for triggers and sticks. The press ends at three quarters of it, so noise at the press point cannot flicker.
81
- - Option `now` (default `performance.now`): the clock in milliseconds.
82
-
83
- `state(rule)` gives `started`, `performed` and `canceled` (each true for one update), `active`, `progress` and `duration`. `reset()` drops every press in progress. Rules do not wait for each other, so one press can start a tap and a hold and each ends by its own rule. To tell a single press from a double, act on the double press's `canceled`, which comes `gap` after a lone press. Time is read once per update, so a rule is as exact as your tick. `input.bindingValue(action, index)` reads one binding yourself.
84
-
85
- A press and release between two updates counts for one update on keys, mouse buttons and touch buttons, so a short tap is not lost on a slow frame. Gamepads are polled, so a gamepad press shorter than one update can still pass unseen.
86
-
87
- ## Local multiplayer
88
-
89
- `@margoengine/input/players` gives each player devices of their own and a full `Input`, all made from one action map:
90
-
91
- ```ts
92
- import {LocalPlayers} from 'margoengine/input/players';
93
-
94
- const party = new LocalPlayers(
95
- {
96
- move: [
97
- {type: 'key', code: 'KeyD'},
98
- {type: 'key', code: 'KeyA', scale: -1},
99
- {type: 'gamepad-axis', index: 0},
100
- ],
101
- jump: [{type: 'key', code: 'Space'}, {type: 'gamepad-button', index: 0}],
102
- start: [{type: 'key', code: 'Enter'}, {type: 'gamepad-button', index: 9}],
103
- },
104
- {
105
- joinAction: 'start', // a press on a device nobody owns adds a player
106
- schemes: {
107
- arrows: {
108
- move: [
109
- {type: 'key', code: 'ArrowRight'},
110
- {type: 'key', code: 'ArrowLeft', scale: -1},
111
- ],
112
- jump: [{type: 'key', code: 'ArrowUp'}],
113
- start: [{type: 'key', code: 'ShiftRight'}],
114
- },
115
- },
116
- },
117
- );
118
- party.on('join', ({player, device}) => console.log('player', player.index, 'joined on', device));
119
- party.on('lost', ({player}) => console.log('pause: player', player.index, 'lost a gamepad'));
120
- function tick() {
121
- party.update(); // in place of input.update()
122
- for (const player of party.players) {
123
- if (player.input.state('jump').pressed) void player.rumble(100);
124
- console.log(player.index, player.input.state('move').value);
125
- }
126
- }
127
- tick();
128
- ```
129
-
130
- A device is `'keyboard'` (the key, mouse and pointer bindings), `'keyboard:<scheme>'` (that entry of `schemes`, for two players on one keyboard), `'gamepad:<n>'` (the gamepad bindings, pointed at gamepad `n`), `'touch'` or `'control:<id>'` (the bindings to that control). A device has one owner; a player can own several.
131
-
132
- - `party.add(device?)`, `party.remove(player)`: add in the lowest free slot, or remove. `player.index` stays put while others come and go.
133
- - `party.assign(player, device)`, `party.unassign(device)`, `party.owner(device)`: move devices at any time. `assign` rebuilds that player's bindings from the shared map, so apply saved bindings after it.
134
- - `player.input` is a real `Input`: contexts, rebinding, touch controls, `Interactions` and recording are per player. An action with no binding on the player's devices reads 0.
135
- - `party.on(type, handler)` hears `join`, `leave`, `lost` and `regained`, and returns the function that stops listening. An unplugged gamepad keeps its owner and comes back to them on the same index.
136
- - The press that joins does not read as `pressed`, so Start does not also pause.
137
- - Options: `maxPlayers` (default 4), `schemes` (default none), `joinAction` (default none: only `add` adds), `gamepadSlots` (gamepad indices `joinAction` watches, default 4), and `target`, `gamepads`, `deadzone` and `contexts`, which go to every player's `Input`.
138
-
139
- ## Gyro aiming and steering
140
-
141
- `@margoengine/input/motion` turns the device's gyroscope and tilt into aim and steering, in the screen's frame, so portrait and landscape read alike:
142
-
143
- ```ts
144
- import {Input} from 'margoengine/input';
145
- import {Gyro} from 'margoengine/input/motion';
146
-
147
- const button = document.createElement('button');
148
- const input = new Input({
149
- aimX: [{type: 'pointer', axis: 'x', scale: 0.01}, {type: 'control', id: 'gyro', axis: 'yaw'}],
150
- steer: [{type: 'key', code: 'KeyD'}, {type: 'control', id: 'gyro', axis: 'steer'}],
151
- aiming: [{type: 'mouse', button: 2}],
152
- });
153
- using gyro = new Gyro();
154
- gyro.attach(input);
155
- button.onclick = async () => {
156
- if (await Gyro.requestPermission()) await gyro.calibrate({duration: 500}); // iOS asks only from a tap
157
- };
158
- let heading = 0;
159
- function tick() {
160
- gyro.enabled = input.state('aiming').down; // aim with the gyro only while aiming, as console games do
161
- gyro.update(); // before input.update()
162
- input.update();
163
- heading += gyro.yaw; // radians turned since the last update: add them straight onto the camera
164
- console.log(heading, input.state('steer').value);
165
- }
166
- tick();
167
- ```
168
-
169
- - `gyro.yaw`, `pitch`, `roll`: radians turned since the last update; positive is right, up and clockwise. Use these for aiming, as they do not clamp.
170
- - `gyro.steer`: tilt like a wheel, -1 to 1, reaching 1 at `maxTilt`. `recenter()` takes the present tilt as straight ahead. Reads 0 while the device lies flat.
171
- - Bindings: `{type: 'control', id: 'gyro', axis}` with `axis` `'yaw'`, `'pitch'` or `'roll'` (rate as a share of `maxRate`) or `'steer'`.
172
- - `calibrate({duration, signal})` measures the gyroscope's resting error with the device still, and subtracts it. `enabled = false` ignores the sensors. `available` turns true once a real reading arrives; `Gyro.supported()` says whether the browser has the events at all.
173
- - Options: `maxRate` (degrees per second reading 1, default 180), `maxTilt` (degrees reading 1, default 45), `deadzone` (degrees per second reading 0, default 1), `target` (default `window`), `screenAngle` and `now`.
174
-
175
- `input.control(id)` is the general form of this: it returns an object of numbers that `{type: 'control', id, axis}` bindings read (`axis` defaults to `'value'`), so any code can feed an action. `input.removeControl(id)` removes it.
176
-
177
- ## Recording and replay
178
-
179
- `@margoengine/input/replay` records what every binding gave, tick by tick, and plays it back into an `Input`. Game code does not change: it reads the same actions, so tests and attract-mode demos run the real thing.
180
-
181
- ```ts
182
- import {Input} from 'margoengine/input';
183
- import {Interactions} from 'margoengine/input/interactions';
184
- import {InputRecorder, InputReplay} from 'margoengine/input/replay';
185
-
186
- const input = new Input({jump: [{type: 'key', code: 'Space'}]});
187
- const recorder = new InputRecorder(input);
188
- for (let tick = 0; tick < 3; tick++) {
189
- input.update();
190
- recorder.capture(); // once per tick, after input.update()
191
- }
192
- const saved = JSON.stringify(recorder.clip());
193
-
194
- const replay = new InputReplay(input, saved, {signal: AbortSignal.timeout(60_000)});
195
- const rules = new Interactions(input, {hop: {type: 'tap', action: 'jump'}}, {now: () => replay.time});
196
- while (replay.frame + 1 < replay.frames) {
197
- input.update(); // takes the next recorded tick; the devices are ignored
198
- rules.update();
199
- }
200
- input.update(); // past the end: the Input goes back to its devices
201
- await replay.finished;
202
- ```
203
-
204
- - A clip is plain JSON: action and binding channels, the time of each tick, and only the values that changed, so a held key costs nothing per tick. It holds binding values, so rules on one binding replay too.
205
- - Each `input.update()` plays one tick. Ticks replay in order at whatever rate you call `update`; the recorded time is `replay.time`, so give timing rules that clock and the results match the live run, tick for tick.
206
- - `new InputReplay(input, clip, {loop, signal})` takes the clip or its JSON text and checks all of it first. `loop` (default false) repeats it, with `time` still rising. `replay.stop()` hands the Input back; `finished` resolves at the end or on `stop`, and rejects if `signal` aborts.
207
- - Contexts apply during a replay as they do live. An action the clip does not hold reads 0; an action this Input lacks is refused. With `LocalPlayers`, record each `player.input`.
208
- - `input.setFeed(feed)` is what replay uses: an object with `begin()` and `read(action, binding)` in place of the devices, and `null` to go back.
209
-
210
- ## Pen pressure and tilt
211
-
212
- `@margoengine/input/pen` reads a stylus for painting and sculpting, as action values and as every sample of a stroke. Mouse and touch are ignored. Set `touch-action: none` on the element.
213
-
214
- ```ts
215
- import {Input} from 'margoengine/input';
216
- import {Pen} from 'margoengine/input/pen';
217
-
218
- const canvas = document.querySelector('canvas')!;
219
- const input = new Input({
220
- size: [{type: 'control', id: 'pen', axis: 'pressure'}],
221
- lean: [{type: 'control', id: 'pen', axis: 'tiltX'}],
222
- erase: [{type: 'control', id: 'pen', axis: 'eraser'}],
223
- });
224
- using pen = new Pen(canvas, {curve: (pressure) => pressure ** 1.5});
225
- pen.attach(input);
226
- function tick() {
227
- pen.update(); // before input.update()
228
- input.update();
229
- console.log(input.state('size').value, input.state('lean').value);
230
- for (const {x, y, pressure, azimuth, altitude} of pen.take()) console.log(x, y, pressure, azimuth, altitude);
231
- }
232
- tick();
233
- ```
234
-
235
- - Bindings: `{type: 'control', id: 'pen', axis}` with `axis` `'pressure'` (0 to 1), `'tiltX'` and `'tiltY'` (-1 to 1, a share of 90 degrees), `'altitude'` (0 flat to 1 upright), `'azimuth'` and `'twist'` (share of a full turn), `'tangential'` (-1 to 1), or `'down'`, `'barrel'`, `'eraser'` and `'hover'` (0 or 1). Tilt reads while hovering, for a brush preview.
236
- - `pen.take()` returns every sample since the last call at the pen's own rate, unpacking the browser's coalesced events, so a fast stroke keeps its points. A sample with `down` false after true ends a stroke. `pen.latest` is the newest sample and `pen.inRange` says whether the pen is near.
237
- - Tilt and altitude with azimuth are both filled in, whichever the browser gives.
238
- - A dab between two updates still reads `down` for one update.
239
- - Options: `curve` (shapes pressure within 0 to 1, default none) and `maxSamples` (kept between `take` calls, oldest dropped, default 4096).
240
-
241
- ## Gestures
242
-
243
- ```ts
244
- import {Gestures} from 'margoengine/input';
245
- const canvas = document.querySelector('canvas')!;
246
- let zoom = 1;
247
- using gestures = new Gestures(canvas, {swipeDistance: 60});
248
- gestures.on('pinch', (e) => (zoom *= e.scale!));
249
- gestures.on('swipe', (e) => console.log(e.direction, e.velocity));
250
- gestures.on('doubletap', () => (zoom = 1));
251
- ```
252
-
253
- Touch and pen only (mouse never triggers them, so they never fight orbit controls): `tap`, `doubletap`, `swipe` (direction and px/s), two-finger `pinch` (scale since the last event) and `rotate` (radians). Thresholds are options with defaults. Set `touch-action: none` on the element.
254
-
255
- ## Webcam landmarks
256
-
257
- `@margoengine/input/landmarks` turns any face, hand or pose detector's output into one `LandmarkFrame` stream, an async iterator with a timestamp per frame. Margo ships no trained weights and no detector and never downloads one: the app loads its own (MediaPipe Tasks' FaceLandmarker, HandLandmarker or PoseLandmarker, or anything that gives points) and passes its results in.
258
-
259
- ```ts
260
- import {fromMediaPipe, landmarkStream, OneEuroFilter, webcamLandmarks, type LandmarkSource} from 'margoengine/input/landmarks';
261
-
262
- // A recorded FaceLandmarker result; with MediaPipe Tasks, detect would return
263
- // fromMediaPipe({face: faceLandmarker.detectForVideo(video, time)}, time).
264
- const recorded = {face: {faceLandmarks: [[{x: 0.5, y: 0.5, z: 0}]], faceBlendshapes: [{categories: [{categoryName: 'jawOpen', score: 0.4}]}]}};
265
- const detect = (_video: unknown, time: number) => fromMediaPipe(recorded, time);
266
-
267
- const controller = new AbortController();
268
- let source: LandmarkSource;
269
- try {
270
- source = await webcamLandmarks({detect, signal: controller.signal});
271
- } catch (error) {
272
- // No camera, or permission refused: play the recording instead.
273
- console.warn('No webcam:', (error as Error).message);
274
- const replay = landmarkStream({buffer: 8});
275
- for (let time = 0; time <= 99; time += 33) replay.push(fromMediaPipe(recorded, time));
276
- replay.close();
277
- source = replay;
278
- }
279
- const jaw = new OneEuroFilter({minCutoff: 1, beta: 0.5});
280
- for await (const frame of source) {
281
- console.log(frame.time, jaw.filter(frame.faces[0]?.blendshapes?.jawOpen ?? 0, frame.time / 1000));
282
- if (frame.time > 60) break; // break, dispose() or the signal stops the camera
283
- }
284
- ```
285
-
286
- - `LandmarkFrame`: `time` (ms), `faces` (`landmarks`, optional `blendshapes` by ARKit name, `transform`, `score`), `hands` (`landmarks`, `worldLandmarks`, `handedness` `'left'` or `'right'` for the subject's hand, `score`) and `poses` (`landmarks`, `worldLandmarks`). Points are `{x, y, z, visibility?, presence?}`: image points normalised 0..1 (y down), world points in metres.
287
- - `fromMediaPipe({face, hands, pose}, time, {mirroredHandedness})` reads MediaPipe Tasks Vision results as they come from `detectForVideo`: `faceLandmarks`, `faceBlendshapes` (`_neutral` dropped), `facialTransformationMatrixes`, `landmarks`, `worldLandmarks` and `handedness` (or the older `handednesses`). MediaPipe labels hands as if the picture were mirrored, so `mirroredHandedness` (default true) swaps them for an unmirrored webcam frame.
288
- - `landmarkStream({buffer = 1, signal})` is a source the app pushes frames into (`push`, `close`, `dispose`); a slow reader gets the newest `buffer` frames, older ones are dropped.
289
- - `startWebcam({onFrame, video, constraints, signal, mediaDevices})` opens the camera (`getUserMedia`, default `{facingMode: 'user', width: 640, height: 480}`), plays it muted and inline into `video` (default a new element) and calls `onFrame(video, time)` once per new picture (`requestVideoFrameCallback`, else animation frames). `stop()`, `using` or the signal stops every track.
290
- - `webcamLandmarks({detect, buffer, ...webcam})` is both together: the source the drivers read. A detector that throws stops the camera and its error comes out of the next read.
291
- - `OneEuroFilter({minCutoff = 1, beta = 0.007, dCutoff = 1})` is the one-euro filter (Casiez, Roussel and Vogel, CHI 2012): `filter(value, seconds)` smooths one number, cutting jitter at rest and lag in motion; raise `beta` for less lag, lower `minCutoff` for less jitter. `reset()` forgets the history.
292
-
293
- ## Webcam face to morph targets
294
-
295
- `@margoengine/input/face` drives ARKit-named morph targets (the 52 names face rigs commonly use) and gives the head rotation from face frames. It takes a detector's blendshape scores when they are there (MediaPipe's FaceLandmarker with `outputFaceBlendshapes`) and otherwise measures the face mesh: the eye aspect ratio for blinks, the lip gap for the jaw, mouth width and corners for smiles, frowns and puckers, and brow height.
296
-
297
- ```ts
298
- import {FaceDriver} from 'margoengine/input/face';
299
- import {fromMediaPipe} from 'margoengine/input/landmarks';
300
-
301
- // Any model with named morph targets: a loaded glTF model's primitives fit.
302
- const model = {primitives: [{targetNames: ['jawOpen', 'eyeBlinkLeft', 'Smile_L'], weights: [0, 0, 0]}]};
303
- using face = new FaceDriver({names: {mouthSmileLeft: 'Smile_L'}});
304
-
305
- // Two recorded FaceLandmarker results: a resting face (to calibrate on), then a smile with the jaw open.
306
- const result = (jaw: number, smile: number) => ({
307
- faceLandmarks: [[]],
308
- faceBlendshapes: [{categories: [{categoryName: 'jawOpen', score: jaw}, {categoryName: 'mouthSmileLeft', score: smile}]}],
309
- facialTransformationMatrixes: [{data: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -40, 1]}],
310
- });
311
- face.calibrate(fromMediaPipe({face: result(0.05, 0)}, 0));
312
- for (let time = 33; time <= 330; time += 33) face.update(fromMediaPipe({face: result(0.6, 0.8)}, time));
313
- face.apply(model);
314
- console.log(model.primitives[0].weights, face.state.rotation);
315
- // From a webcam: await face.drive(await webcamLandmarks({detect}), model, {signal}).
316
- ```
317
-
318
- - `update(frame or face, time?)` reads the frame's first face and returns `{weights, rotation, tracked, time}`; `apply(model or models)` writes each weight to the targets named after it (case-insensitive, through `names`), leaving other targets alone. `drive(source, model, {signal, onUpdate})` does both for every frame of a `LandmarkSource`.
319
- - `calibrate(frame)`: take a relaxed face looking at the camera as neutral. Scores are rescaled from the person's resting value, landmark measures are taken against their own face, and the head rotation is measured from that pose.
320
- - Options: `names` (ARKit name to morph name, default the ARKit names), `source` (`'auto'` scores when given else landmarks, `'blendshapes'`, `'landmarks'`), `minScore` (0.5: a weaker face holds the last good values), `hold` (0.5 s, then back to neutral), `smoothing` (one-euro `{minCutoff: 1.5, beta: 0.5}`, or false), `mirror` (false; swaps left and right for a selfie picture) and `aspect` (1; the frame's width over height, for landmark measures).
321
- - Landmarks alone give `LANDMARK_BLENDSHAPES` (blinks, wide eyes, jaw, smiles, frowns, pucker and brows); scores give all 52. `measureFace`, `faceWeightsFromLandmarks` and `headRotation` are the measures on their own. The head rotation is in a y-up frame looking along +z with the face's left at +x; with a face transform from the detector it is that transform's rotation.
322
-
323
- ARKit is a trademark of Apple Inc.; only its published blendshape names are used.
324
-
325
- ## Webcam hands and body to a skeleton
326
-
327
- `@margoengine/input/body` poses a humanoid skeleton from Pose Landmarker (33 points) and Hand Landmarker (21 points per hand) frames: each mapped bone turns from its rest direction onto the landmark direction, a second direction fixes the twist of the hips, chest and hands, and each joint stays within its limit. Bones are the VRM humanoid names; `humanoidBones` in `@margoengine/rigging/retarget` maps Mixamo, Godot and other rigs onto them.
328
-
329
- ```ts
330
- import {Skeleton} from 'margoengine/animation';
331
- import {BodyDriver} from 'margoengine/input/body';
332
- import {landmarkStream, type Landmark} from 'margoengine/input/landmarks';
333
-
334
- // A T-pose arm: shoulder, upper arm, forearm and hand, its left at +x (a loaded skin's skeleton fits).
335
- const skeleton = new Skeleton([
336
- {name: 'upperChest', parent: -1, translation: [0, 1.3, 0]},
337
- {name: 'leftUpperArm', parent: 0, translation: [0.17, 0.1, 0]},
338
- {name: 'leftLowerArm', parent: 1, translation: [0.27, 0, 0]},
339
- {name: 'leftHand', parent: 2, translation: [0.25, 0, 0]},
340
- ]);
341
- using body = new BodyDriver(skeleton, {parts: ['pose']});
342
-
343
- // Recorded PoseLandmarker world points (metres, y down): a T-pose, then the forearm raised.
344
- const point = (x: number, y: number, z = 0): Landmark => ({x, y, z, visibility: 0.99});
345
- const pose = (wrist: Landmark) => {
346
- const points = Array.from({length: 33}, () => point(0, 0));
347
- points[11] = point(0.17, -0.45);
348
- points[13] = point(0.44, -0.45);
349
- points[15] = wrist;
350
- return points;
351
- };
352
- const frame = (time: number, points: Landmark[]) => ({time, faces: [], hands: [], poses: [{landmarks: points, worldLandmarks: points}]});
353
- body.calibrate(frame(0, pose(point(0.69, -0.45))));
354
-
355
- const source = landmarkStream({buffer: 30});
356
- for (let time = 33; time <= 990; time += 33) source.push(frame(time, pose(point(0.44, -0.7))));
357
- source.close();
358
- await body.drive(source, {signal: AbortSignal.timeout(5000)});
359
- console.log(skeleton.getPose(2).rotation); // the elbow bent 90 degrees about +z
360
- ```
361
-
362
- - `update(frame, time?)` poses the bones from the frame's first pose and one hand per side and returns `{tracked, driven, time}`; `drive(source, {signal, onUpdate})` does it for every frame of a `LandmarkSource`, such as `webcamLandmarks`.
363
- - `calibrate(frame)`: the person stands in the skeleton's rest pose (T-pose or A-pose) and their landmark directions become the rest directions, so proportions and camera tilt drop out. Uncalibrated, the skeleton's own rest directions are used.
364
- - Options: `bones` (humanoid name to skeleton name, or the index map `humanoidBones` returns; default the humanoid names, case-insensitive), `parts` (`['pose', 'hands']`), `minVisibility` (0.5: a hidden point leaves its bone where it was), `minScore` (0.5), `hold` (0.5 s, then back to the rest pose), `smoothing` (one-euro `{minCutoff: 1.5, beta: 0.3}` on each direction, or false), `mirror` (false; swaps left and right for a selfie picture), `aspect` (1; for image points when the detector gives no world points) and `limits` (radians per bone name, 0 to pi). A point that is hidden or not a finite number leaves its bone where it was.
365
- - `POSE_TARGETS` and `handTargets(side)` list the driven bones with their landmarks and default limits (elbows and knees 2.7 rad, fingers 1.6 to 1.9, chest and neck 1). A limit bounds the turn from the bone's rest rotation relative to its parent, as a cone about the rest pose; hinge axes are not enforced. Twist about a bone is kept only where a side direction gives it (hips, chest, hands): upper arms and legs take the shortest turn.
366
-
367
- Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
368
-
369
- Build and unit tests: npm test --workspace @margoengine/input
370
-
1
+ # @margoengine/input
2
+
3
+ Import `margoengine/input` from the `margoengine` package, or `@margoengine/input` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ Semantic actions combine keyboard codes, mouse buttons and relative motion, gamepad axes/buttons, and touch controls.
6
+
7
+ ```ts
8
+ import {Input} from 'margoengine/input';
9
+ const input = new Input({jump: [{type: 'key', code: 'Space'}]});
10
+ input.update();
11
+ const {pressed, value} = input.state('jump');
12
+ ```
13
+
14
+ Call update once per simulation tick. State objects are reused. Opposing bindings sum and clamp to -1..1; gamepad axes use a configurable deadzone. createStick(parent, id) creates a pointer-captured virtual stick; bindTouchButton(button, id) supports pointer and keyboard activation. rumble(durationMs, strength, gamepadIndex) returns false when no actuator is available. dispose removes listeners and owned stick elements. Editable fields do not trigger gameplay key-down actions. Mouse motion is relative, not an absolute screen cursor.
15
+
16
+ ## Chords, contexts, rebinding and prompts
17
+
18
+ ```ts
19
+ import {Input, bindingLabel} from 'margoengine/input';
20
+ const input = new Input(
21
+ {
22
+ jump: [{type: 'key', code: 'Space'}],
23
+ save: [{type: 'key', code: 'KeyS', modifiers: ['ctrl']}],
24
+ confirm: [{type: 'key', code: 'Enter'}],
25
+ },
26
+ {contexts: {game: ['jump'], menu: ['confirm']}},
27
+ );
28
+ input.setContext('game', false); // a menu opened: jump reads 0 and releases; confirm keeps working
29
+ const prompt = bindingLabel(input.actions.save[0]); // "Ctrl+S"; gamepad buttons use 'xbox' | 'playstation' | 'generic' names
30
+ const pressed = input.captureBinding({signal: AbortSignal.timeout(10_000)}); // "press a key to rebind"
31
+ window.dispatchEvent(new KeyboardEvent('keydown', {code: 'KeyJ'})); // stands in for the player's key press
32
+ const binding = await pressed;
33
+ input.rebind('jump', [binding]);
34
+ localStorage.setItem('bindings', JSON.stringify(input.exportBindings()));
35
+ input.importBindings(localStorage.getItem('bindings')!); // unknown actions are ignored; invalid data changes nothing
36
+ input.resetBindings();
37
+ ```
38
+
39
+ - `modifiers` (`'shift' | 'ctrl' | 'alt' | 'meta'`) on a `key` binding makes a chord: the key counts only while every modifier is held.
40
+ - `contexts` (option) group actions; an action owned by contexts reads 0 unless one is enabled. Unlisted actions are always active.
41
+ - `captureBinding` resolves with the next key (with held modifiers), mouse button or gamepad button; Escape or the signal rejects with `AbortError`. A modifier pressed alone waits: Ctrl then S gives Ctrl+S, and Shift pressed and released alone gives Shift. A gamepad button already held when the prompt opens counts only after it is released and pressed again.
42
+ - Mouse buttons follow Pointer Events chords: a second button pressed or released during a drag counts, though the browser sends it as a `pointermove`.
43
+
44
+ ## Tap, hold, slow tap and double press
45
+
46
+ `@margoengine/input/interactions` turns a press into what the player meant. Rules are named, like actions, and read any action, or one binding of it:
47
+
48
+ ```ts
49
+ import {Input} from 'margoengine/input';
50
+ import {Interactions} from 'margoengine/input/interactions';
51
+
52
+ const input = new Input({
53
+ use: [{type: 'key', code: 'KeyE'}, {type: 'gamepad-button', index: 2}],
54
+ dodge: [{type: 'key', code: 'KeyD'}],
55
+ fire: [{type: 'gamepad-button', index: 7}],
56
+ });
57
+ const rules = new Interactions(input, {
58
+ open: {type: 'tap', action: 'use'},
59
+ inspect: {type: 'hold', action: 'use', time: 600},
60
+ dash: {type: 'double-press', action: 'dodge'},
61
+ heavy: {type: 'slow-tap', action: 'fire', threshold: 0.8},
62
+ padOnly: {type: 'hold', action: 'use', binding: 1},
63
+ });
64
+ function tick() {
65
+ input.update();
66
+ rules.update();
67
+ if (rules.state('open').performed) console.log('open');
68
+ if (rules.state('dash').performed) console.log('dash');
69
+ const charge = rules.state('heavy').progress; // 0 to 1, for a charge bar
70
+ console.log(charge);
71
+ }
72
+ tick();
73
+ ```
74
+
75
+ - `tap`: pressed and released within `time` (default 200 ms). Performed on release.
76
+ - `hold`: held for `time` (default 400 ms). Performed while still held.
77
+ - `slow-tap`: held for at least `time` (default 500 ms), then released. Performed on release.
78
+ - `double-press`: `count` presses (default 2), each shorter than `time` (default 200 ms), each within `gap` (default 300 ms) of the last release. Performed on the last press.
79
+ - `binding` (default: the whole action): an index into `input.actions[action]`, so a rule can read one device; after a rebind it reads what is bound there.
80
+ - `threshold` (default 0.5): magnitude that counts as pressed, for triggers and sticks. The press ends at three quarters of it, so noise at the press point cannot flicker.
81
+ - Option `now` (default `performance.now`): the clock in milliseconds.
82
+
83
+ `state(rule)` gives `started`, `performed` and `canceled` (each true for one update), `active`, `progress` and `duration`. `reset()` drops every press in progress. Rules do not wait for each other, so one press can start a tap and a hold and each ends by its own rule. To tell a single press from a double, act on the double press's `canceled`, which comes `gap` after a lone press. Time is read once per update, so a rule is as exact as your tick. `input.bindingValue(action, index)` reads one binding yourself.
84
+
85
+ A press and release between two updates counts for one update on keys, mouse buttons and touch buttons, so a short tap is not lost on a slow frame. Gamepads are polled, so a gamepad press shorter than one update can still pass unseen.
86
+
87
+ ## Local multiplayer
88
+
89
+ `@margoengine/input/players` gives each player devices of their own and a full `Input`, all made from one action map:
90
+
91
+ ```ts
92
+ import {LocalPlayers} from 'margoengine/input/players';
93
+
94
+ const party = new LocalPlayers(
95
+ {
96
+ move: [
97
+ {type: 'key', code: 'KeyD'},
98
+ {type: 'key', code: 'KeyA', scale: -1},
99
+ {type: 'gamepad-axis', index: 0},
100
+ ],
101
+ jump: [{type: 'key', code: 'Space'}, {type: 'gamepad-button', index: 0}],
102
+ start: [{type: 'key', code: 'Enter'}, {type: 'gamepad-button', index: 9}],
103
+ },
104
+ {
105
+ joinAction: 'start', // a press on a device nobody owns adds a player
106
+ schemes: {
107
+ arrows: {
108
+ move: [
109
+ {type: 'key', code: 'ArrowRight'},
110
+ {type: 'key', code: 'ArrowLeft', scale: -1},
111
+ ],
112
+ jump: [{type: 'key', code: 'ArrowUp'}],
113
+ start: [{type: 'key', code: 'ShiftRight'}],
114
+ },
115
+ },
116
+ },
117
+ );
118
+ party.on('join', ({player, device}) => console.log('player', player.index, 'joined on', device));
119
+ party.on('lost', ({player}) => console.log('pause: player', player.index, 'lost a gamepad'));
120
+ function tick() {
121
+ party.update(); // in place of input.update()
122
+ for (const player of party.players) {
123
+ if (player.input.state('jump').pressed) void player.rumble(100);
124
+ console.log(player.index, player.input.state('move').value);
125
+ }
126
+ }
127
+ tick();
128
+ ```
129
+
130
+ A device is `'keyboard'` (the key, mouse and pointer bindings), `'keyboard:<scheme>'` (that entry of `schemes`, for two players on one keyboard), `'gamepad:<n>'` (the gamepad bindings, pointed at gamepad `n`), `'touch'` or `'control:<id>'` (the bindings to that control). A device has one owner; a player can own several.
131
+
132
+ - `party.add(device?)`, `party.remove(player)`: add in the lowest free slot, or remove. `player.index` stays put while others come and go.
133
+ - `party.assign(player, device)`, `party.unassign(device)`, `party.owner(device)`: move devices at any time. `assign` rebuilds that player's bindings from the shared map, so apply saved bindings after it.
134
+ - `player.input` is a real `Input`: contexts, rebinding, touch controls, `Interactions` and recording are per player. An action with no binding on the player's devices reads 0.
135
+ - `party.on(type, handler)` hears `join`, `leave`, `lost` and `regained`, and returns the function that stops listening. An unplugged gamepad keeps its owner and comes back to them on the same index.
136
+ - The press that joins does not read as `pressed`, so Start does not also pause.
137
+ - Options: `maxPlayers` (default 4), `schemes` (default none), `joinAction` (default none: only `add` adds), `gamepadSlots` (gamepad indices `joinAction` watches, default 4), and `target`, `gamepads`, `deadzone` and `contexts`, which go to every player's `Input`.
138
+
139
+ ## Gyro aiming and steering
140
+
141
+ `@margoengine/input/motion` turns the device's gyroscope and tilt into aim and steering, in the screen's frame, so portrait and landscape read alike:
142
+
143
+ ```ts
144
+ import {Input} from 'margoengine/input';
145
+ import {Gyro} from 'margoengine/input/motion';
146
+
147
+ const button = document.createElement('button');
148
+ const input = new Input({
149
+ aimX: [{type: 'pointer', axis: 'x', scale: 0.01}, {type: 'control', id: 'gyro', axis: 'yaw'}],
150
+ steer: [{type: 'key', code: 'KeyD'}, {type: 'control', id: 'gyro', axis: 'steer'}],
151
+ aiming: [{type: 'mouse', button: 2}],
152
+ });
153
+ using gyro = new Gyro();
154
+ gyro.attach(input);
155
+ button.onclick = async () => {
156
+ if (await Gyro.requestPermission()) await gyro.calibrate({duration: 500}); // iOS asks only from a tap
157
+ };
158
+ let heading = 0;
159
+ function tick() {
160
+ gyro.enabled = input.state('aiming').down; // aim with the gyro only while aiming, as console games do
161
+ gyro.update(); // before input.update()
162
+ input.update();
163
+ heading += gyro.yaw; // radians turned since the last update: add them straight onto the camera
164
+ console.log(heading, input.state('steer').value);
165
+ }
166
+ tick();
167
+ ```
168
+
169
+ - `gyro.yaw`, `pitch`, `roll`: radians turned since the last update; positive is right, up and clockwise. Use these for aiming, as they do not clamp.
170
+ - `gyro.steer`: tilt like a wheel, -1 to 1, reaching 1 at `maxTilt`. `recenter()` takes the present tilt as straight ahead. Reads 0 while the device lies flat.
171
+ - Bindings: `{type: 'control', id: 'gyro', axis}` with `axis` `'yaw'`, `'pitch'` or `'roll'` (rate as a share of `maxRate`) or `'steer'`.
172
+ - `calibrate({duration, signal})` measures the gyroscope's resting error with the device still, and subtracts it. `enabled = false` ignores the sensors. `available` turns true once a real reading arrives; `Gyro.supported()` says whether the browser has the events at all.
173
+ - Options: `maxRate` (degrees per second reading 1, default 180), `maxTilt` (degrees reading 1, default 45), `deadzone` (degrees per second reading 0, default 1), `target` (default `window`), `screenAngle` and `now`.
174
+
175
+ `input.control(id)` is the general form of this: it returns an object of numbers that `{type: 'control', id, axis}` bindings read (`axis` defaults to `'value'`), so any code can feed an action. `input.removeControl(id)` removes it.
176
+
177
+ ## Recording and replay
178
+
179
+ `@margoengine/input/replay` records what every binding gave, tick by tick, and plays it back into an `Input`. Game code does not change: it reads the same actions, so tests and attract-mode demos run the real thing.
180
+
181
+ ```ts
182
+ import {Input} from 'margoengine/input';
183
+ import {Interactions} from 'margoengine/input/interactions';
184
+ import {InputRecorder, InputReplay} from 'margoengine/input/replay';
185
+
186
+ const input = new Input({jump: [{type: 'key', code: 'Space'}]});
187
+ const recorder = new InputRecorder(input);
188
+ for (let tick = 0; tick < 3; tick++) {
189
+ input.update();
190
+ recorder.capture(); // once per tick, after input.update()
191
+ }
192
+ const saved = JSON.stringify(recorder.clip());
193
+
194
+ const replay = new InputReplay(input, saved, {signal: AbortSignal.timeout(60_000)});
195
+ const rules = new Interactions(input, {hop: {type: 'tap', action: 'jump'}}, {now: () => replay.time});
196
+ while (replay.frame + 1 < replay.frames) {
197
+ input.update(); // takes the next recorded tick; the devices are ignored
198
+ rules.update();
199
+ }
200
+ input.update(); // past the end: the Input goes back to its devices
201
+ await replay.finished;
202
+ ```
203
+
204
+ - A clip is plain JSON: action and binding channels, the time of each tick, and only the values that changed, so a held key costs nothing per tick. It holds binding values, so rules on one binding replay too.
205
+ - Each `input.update()` plays one tick. Ticks replay in order at whatever rate you call `update`; the recorded time is `replay.time`, so give timing rules that clock and the results match the live run, tick for tick.
206
+ - `new InputReplay(input, clip, {loop, signal})` takes the clip or its JSON text and checks all of it first. `loop` (default false) repeats it, with `time` still rising. `replay.stop()` hands the Input back; `finished` resolves at the end or on `stop`, and rejects if `signal` aborts.
207
+ - Contexts apply during a replay as they do live. An action the clip does not hold reads 0; an action this Input lacks is refused. With `LocalPlayers`, record each `player.input`.
208
+ - `input.setFeed(feed)` is what replay uses: an object with `begin()` and `read(action, binding)` in place of the devices, and `null` to go back.
209
+
210
+ ## Pen pressure and tilt
211
+
212
+ `@margoengine/input/pen` reads a stylus for painting and sculpting, as action values and as every sample of a stroke. Mouse and touch are ignored. Set `touch-action: none` on the element.
213
+
214
+ ```ts
215
+ import {Input} from 'margoengine/input';
216
+ import {Pen} from 'margoengine/input/pen';
217
+
218
+ const canvas = document.querySelector('canvas')!;
219
+ const input = new Input({
220
+ size: [{type: 'control', id: 'pen', axis: 'pressure'}],
221
+ lean: [{type: 'control', id: 'pen', axis: 'tiltX'}],
222
+ erase: [{type: 'control', id: 'pen', axis: 'eraser'}],
223
+ });
224
+ using pen = new Pen(canvas, {curve: (pressure) => pressure ** 1.5});
225
+ pen.attach(input);
226
+ function tick() {
227
+ pen.update(); // before input.update()
228
+ input.update();
229
+ console.log(input.state('size').value, input.state('lean').value);
230
+ for (const {x, y, pressure, azimuth, altitude} of pen.take()) console.log(x, y, pressure, azimuth, altitude);
231
+ }
232
+ tick();
233
+ ```
234
+
235
+ - Bindings: `{type: 'control', id: 'pen', axis}` with `axis` `'pressure'` (0 to 1), `'tiltX'` and `'tiltY'` (-1 to 1, a share of 90 degrees), `'altitude'` (0 flat to 1 upright), `'azimuth'` and `'twist'` (share of a full turn), `'tangential'` (-1 to 1), or `'down'`, `'barrel'`, `'eraser'` and `'hover'` (0 or 1). Tilt reads while hovering, for a brush preview.
236
+ - `pen.take()` returns every sample since the last call at the pen's own rate, unpacking the browser's coalesced events, so a fast stroke keeps its points. A sample with `down` false after true ends a stroke. `pen.latest` is the newest sample and `pen.inRange` says whether the pen is near.
237
+ - Tilt and altitude with azimuth are both filled in, whichever the browser gives, by the Pointer Events conversion.
238
+ Directions are the screen's: `tiltX` is positive leaning right (+x), `tiltY` leaning down the screen (+y), and
239
+ `azimuth` turns from +x toward +y (0.25 of a turn is straight down the screen). When the browser sends altitude and
240
+ azimuth they are kept as sent, and tilt is computed from them only when both tilts arrive as 0.
241
+ - A pen lying flat is ambiguous: from tilt, a flat lean straight along one axis (90 degrees on one tilt, 0 on the other)
242
+ gives altitude 0 and that axis's azimuth, while a flat lean on both axes gives altitude 0 and azimuth 0, the
243
+ specification's fallback. From altitude 0, tilt takes 90 degrees toward each axis the azimuth leans to, and exactly 0
244
+ on the other axis when the azimuth lies on one.
245
+ - A dab between two updates still reads `down` for one update.
246
+ - Options: `curve` (shapes pressure within 0 to 1, default none) and `maxSamples` (kept between `take` calls, oldest dropped, default 4096).
247
+
248
+ ## Sticks from keys and axes (`margoengine/input/vector`)
249
+
250
+ `VectorInput` is an `Input` with named two-axis actions: movement from WASD, a gamepad stick, or both. Each vector sums
251
+ its `x` and `y` bindings, then applies one radial deadzone to the pair, so a diagonal is as long as a straight push
252
+ and the stick has no square corners. Positive `y` is down, as on gamepads.
253
+
254
+ ```ts
255
+ import { VectorInput, wasd } from 'margoengine/input/vector';
256
+
257
+ const input = new VectorInput(
258
+ {
259
+ move: { ...wasd(), x: [...wasd().x, { type: 'gamepad-axis', index: 0 }], y: [...wasd().y, { type: 'gamepad-axis', index: 1 }] },
260
+ aim: { x: [{ type: 'key', code: 'ArrowRight' }], y: [{ type: 'key', code: 'ArrowDown' }], normalize: true, deadzone: 0.2 },
261
+ },
262
+ { actions: { jump: [{ type: 'key', code: 'Space' }] } }, // ordinary actions alongside
263
+ );
264
+ const key = (type: string, code: string) => window.dispatchEvent(new KeyboardEvent(type, { code }));
265
+ key('keydown', 'KeyD'); // stands in for the player's keys
266
+ key('keydown', 'KeyW');
267
+ input.update();
268
+ const move = input.vector('move'); // the same object every tick
269
+ console.log(move.x.toFixed(3), move.y.toFixed(3), move.magnitude, move.pressed); // '0.707' '-0.707' 1 true
270
+ key('keydown', 'KeyA'); // A against D cancels
271
+ input.update();
272
+ console.log(move.x, move.y, move.magnitude); // 0 -1 1
273
+ console.log(Object.keys(input.actions)); // ['jump', 'move.x', 'move.y', 'aim.x', 'aim.y']
274
+ for (const code of ['KeyA', 'KeyD', 'KeyW']) key('keyup', code);
275
+ input.update();
276
+ console.log(move.released, move.down); // true false
277
+ input.dispose();
278
+ ```
279
+
280
+ - A vector's state is `{ x, y, magnitude, down, pressed, released }`. `magnitude` is 0 inside `deadzone` (default
281
+ 0.15), then rises from 0 to 1 between the deadzone and the unit circle, `(min(1, length) - deadzone) /
282
+ (1 - deadzone)`, so a stick has no jump at the deadzone edge; `x` and `y` keep the push's direction.
283
+ `normalize: true` makes every push outside the deadzone length 1 (eight-way keys, or a menu cursor). `down` is any
284
+ magnitude above zero.
285
+ - Each vector becomes two scalar actions, `<name>.x` and `<name>.y`, so `contexts`, `rebind`, `exportBindings`,
286
+ `InputRecorder` and `InputReplay` work with them unchanged; rebind `move.x` to move the horizontal axis. The `Input`
287
+ axis deadzone is not used: each vector's radial one replaces it.
288
+ - An empty name, an empty axis, or a name whose `.x` or `.y` clashes with another action throws a `TypeError`; a
289
+ deadzone outside 0 (inclusive) to 1 throws a `RangeError`. `reset()` (also on window blur) zeroes vectors at once
290
+ and reports `released` for those that were down.
291
+
292
+ ## XR controllers and hands (`margoengine/input/xr`)
293
+
294
+ `XRBindings` turns a WebXR session's controllers and hands into ordinary `Input` controls: buttons (analogue value,
295
+ pressed or touched), thumbstick axes, select and squeeze, a hand pinch, and the grip pose. Mix them with keys and
296
+ gamepads in one action map; recording and replay need no headset.
297
+
298
+ ```ts
299
+ import { Input } from 'margoengine/input';
300
+ import { XRBindings } from 'margoengine/input/xr';
301
+
302
+ // A stand-in session; pass the real XRSession, and call update(frame, referenceSpace) in its frame loop.
303
+ const right = {
304
+ handedness: 'right' as const,
305
+ gamepad: { axes: [0, 0, 0.5, -1], buttons: [{ value: 0.8, pressed: true, touched: true }] },
306
+ gripSpace: {},
307
+ };
308
+ const left = { handedness: 'left' as const, hand: { get: (joint: string) => ({ joint }) } };
309
+ const session = Object.assign(new EventTarget(), { inputSources: [left, right] });
310
+ let gap = 0.015; // metres between thumb and index tips
311
+ const frame = {
312
+ getJointPose: (joint: object) => ({ transform: { position: { x: (joint as { joint: string }).joint === 'thumb-tip' ? 0 : gap, y: 0, z: 0 } } }),
313
+ getPose: () => ({ transform: { position: { x: 0, y: 1.4, z: -0.3 }, orientation: { x: 0, y: 0, z: 0, w: 1 } } }),
314
+ };
315
+ const space = {};
316
+
317
+ const xr = new XRBindings(session);
318
+ const input = new Input(
319
+ xr.map({
320
+ fire: [{ type: 'xr-button', hand: 'right', index: 0 }, { type: 'key', code: 'Space' }],
321
+ turn: [{ type: 'xr-axis', hand: 'right', index: 2 }],
322
+ select: [{ type: 'xr-select', hand: 'right' }],
323
+ pinch: [{ type: 'xr-pinch', hand: 'left' }],
324
+ gripY: [{ type: 'xr-grip-pose', hand: 'right', component: 'y' }],
325
+ }),
326
+ );
327
+ xr.attach(input);
328
+ const select = (type: string) => session.dispatchEvent(Object.assign(new Event(type), { inputSource: right }));
329
+ select('selectstart'); // a tap: start and end before the next frame
330
+ select('selectend');
331
+
332
+ xr.update(frame, space); // first, then input.update()
333
+ input.update();
334
+ console.log(input.state('fire').value, input.state('turn').value, input.state('select').pressed); // 0.8 0.5 true: the tap still counts once
335
+ console.log(input.state('pinch').down, input.state('gripY').value, input.bindingValue('gripY', 0)); // true 1 1.4: actions clamp
336
+ gap = 0.025; // between pinchStart and pinchEnd: the pinch holds
337
+ xr.update(frame, space);
338
+ input.update();
339
+ console.log(input.state('select').down, input.state('pinch').down); // false true
340
+ gap = 0.035;
341
+ xr.update(frame, space);
342
+ input.update();
343
+ console.log(input.state('pinch').down); // false
344
+ xr.dispose(); // removes its listeners and controls
345
+ ```
346
+
347
+ | Descriptor | Reads |
348
+ | --- | --- |
349
+ | `{ type: 'xr-button', index, value }` | `gamepad.buttons[index]`: `'value'` (default, 0 to 1), `'pressed'` or `'touched'` (0 or 1) |
350
+ | `{ type: 'xr-axis', index }` | `gamepad.axes[index]`, -1 to 1 (2 and 3 are the thumbstick on the xr-standard mapping) |
351
+ | `{ type: 'xr-select' }`, `{ type: 'xr-grip' }` | 1 while the session's select or squeeze is held, and for one update after a tap shorter than a frame |
352
+ | `{ type: 'xr-pinch' }` | 1 while the thumb and index tips are within `pinchStart` (default 0.02 m), until they part past `pinchEnd` (0.03 m) |
353
+ | `{ type: 'xr-grip-pose', component }` | the grip pose in the reference space: `'x'`, `'y'`, `'z'` (metres), `'qx'` to `'qw'`, or `'tracked'` (0 or 1) |
354
+
355
+ - Every descriptor also takes `hand` (`'left'`, `'right'` or `'none'`; default any), `source` (the nth matching source
356
+ in session order, default 0) and `scale` (default 1). An invalid one throws a `TypeError`.
357
+ - `map(actions)` converts the XR descriptors in a mixed map and passes native bindings through; `binding(descriptor)`
358
+ converts one. `attach(input)` publishes to an `Input` or `VectorInput` once and returns a detach function. Several
359
+ `XRBindings` need distinct `id`s (default `'xr'`).
360
+ - A missing, untracked or disconnected source reads 0, and the session's `end` zeroes everything. An action clamps to
361
+ -1 to 1, so read a grip position beyond a metre with `input.bindingValue(action, index)`, which is not clamped.
362
+ `update` after `dispose()` throws a `MargoError` with code `'disposed'`.
363
+
364
+ ## Pointer lock (`margoengine/input/lock`)
365
+
366
+ `PointerLock` asks for pointer lock on an element, with raw mouse movement (no operating-system acceleration) where
367
+ the browser offers it, and hands each tick's relative mouse counts to an `Input` as control `'lock'`, axes `'x'` and
368
+ `'y'`. It is separate from camera controls, so any look or aim code can use it.
369
+
370
+ ```ts
371
+ import { Input } from 'margoengine/input';
372
+ import { PointerLock } from 'margoengine/input/lock';
373
+
374
+ const canvas = document.createElement('canvas');
375
+ document.body.append(canvas);
376
+ const lock = new PointerLock(canvas); // listens on canvas.ownerDocument; requests nothing yet
377
+ const input = new Input({ lookX: [{ type: 'control', id: 'lock', axis: 'x', scale: 0.01 }] });
378
+ lock.attach(input);
379
+ console.log(lock.supported, lock.locked); // true false in a browser with the Pointer Lock API
380
+
381
+ canvas.addEventListener('click', async () => {
382
+ try {
383
+ await lock.request({ timeout: 5000 }); // from the click: browsers need a user gesture
384
+ console.log(lock.locked, lock.raw); // true, and true for raw movement (false adjusted, null unknown)
385
+ } catch (error) {
386
+ console.log((error as Error).name); // 'OperationError' refused, 'TimeoutError', 'AbortError', ...
387
+ }
388
+ });
389
+ function tick() {
390
+ lock.update(); // before input.update(): this tick's counts
391
+ input.update();
392
+ console.log(lock.x, lock.y, input.state('lookX').value); // counts, and the action after scale and clamp
393
+ }
394
+ tick();
395
+ lock.dispose(); // or `using`: releases the lock, cancels a wait, removes listeners and the control
396
+ ```
397
+
398
+ - `request({ unadjustedMovement, fallback, signal, timeout })`: `unadjustedMovement` (default true) asks for raw
399
+ movement, and `fallback` (default true) asks again without it when the browser answers `NotSupportedError`.
400
+ `timeout` (default 5000 ms, positive) bounds the whole request; `signal` cancels it, and a lock granted after the
401
+ cancel is released at once. A second request while one waits throws `InvalidStateError`; no Pointer Lock API
402
+ throws `NotSupportedError`. Older browsers whose `requestPointerLock` returns nothing work too, with `raw` null.
403
+ - `x` and `y` are the mouse counts summed since the last `update()`, unbounded; they read 0 while this element does
404
+ not hold the lock, and losing the lock (Escape) clears them. `release()` exits only this element's lock.
405
+ - `attach(input, id)` publishes to one `Input` per call (default id `'lock'`) and returns a detach function.
406
+
407
+ ## Layout-aware key prompts (`margoengine/input/layout`)
408
+
409
+ Bindings use physical key codes, so `KeyW` is the key above Tab on every layout. `KeyboardLabels` reads the browser's
410
+ Keyboard Map to show what that key is labelled on the player's keyboard: Z on AZERTY, for example. The binding never
411
+ changes; only the prompt does.
412
+
413
+ ```ts
414
+ import { KeyboardLabels, layoutBindingLabel } from 'margoengine/input/layout';
415
+
416
+ // A stand-in for navigator.keyboard (the default) on a French AZERTY layout.
417
+ const azerty = new Map([['KeyQ', 'a'], ['KeyW', 'z'], ['KeyA', 'q'], ['Digit2', 'é']]);
418
+ const keyboard = Object.assign(new EventTarget(), { getLayoutMap: async () => azerty });
419
+
420
+ const labels = new KeyboardLabels({ keyboard });
421
+ labels.addEventListener('change', () => console.log('redraw prompts')); // also after a layout change
422
+ console.log(labels.label({ type: 'key', code: 'KeyW' })); // 'W': no map yet, the standard label
423
+ console.log(await labels.refresh()); // logs 'redraw prompts', then true
424
+ console.log(labels.label({ type: 'key', code: 'KeyW' }), labels.label({ type: 'key', code: 'KeyQ', modifiers: ['ctrl'] })); // 'Z' 'Ctrl+A'
425
+ console.log(labels.label({ type: 'key', code: 'Digit2' }), labels.label({ type: 'key', code: 'Space' })); // 'é' 'Space'
426
+ console.log(layoutBindingLabel({ type: 'key', code: 'KeyW' }, labels.map)); // 'Z': the same, with a map you hold
427
+ labels.dispose();
428
+ ```
429
+
430
+ - `refresh({ signal })` loads the map and returns true, or false when the browser has no Keyboard Map (Firefox and
431
+ Safari), the page may not read it (`SecurityError`, `NotAllowedError`, a frame without permission), or a newer
432
+ refresh started; the labels then fall back to `bindingLabel`. A wait past `timeout` (default 5000 ms) rejects with
433
+ `TimeoutError`, `signal` with its reason, and any other error is thrown and kept in `lastError`.
434
+ - Where the browser fires `layoutchange`, the labels refresh by themselves: `change` on success, `error` (with
435
+ `lastError`) on failure. `supported` says whether the API exists, `available` whether a map was read, and `map` is
436
+ the snapshot or null.
437
+ - Letters are shown in capitals, other glyphs as the map gives them; a blank or control-character glyph falls back.
438
+ Modifiers, mouse and gamepad labels are unchanged (pass the gamepad layout, `'xbox'` by default).
439
+ - `keyboard: null` turns the lookup off. After `dispose()`, `label` and `refresh` throw a `MargoError` with code
440
+ `'disposed'`.
441
+
442
+ ## Trigger rumble (`margoengine/input/haptics`)
443
+
444
+ `triggerRumble(gamepad, options)` plays the browser's trigger-rumble effect: the motors in each trigger (as on Xbox
445
+ Wireless Controllers) and the two handle motors, each with its own strength. It never stands in a plain dual rumble
446
+ where triggers are missing.
447
+
448
+ ```ts
449
+ import { supportsTriggerRumble, triggerRumble } from 'margoengine/input/haptics';
450
+
451
+ // A stand-in pad; pass navigator.getGamepads()[0].
452
+ const played: object[] = [];
453
+ const pad = {
454
+ connected: true,
455
+ vibrationActuator: {
456
+ effects: ['dual-rumble', 'trigger-rumble'],
457
+ playEffect: async (_type: 'trigger-rumble', effect: object) => (played.push(effect), 'complete' as const),
458
+ reset: async () => 'complete' as const,
459
+ },
460
+ };
461
+ console.log(supportsTriggerRumble(pad), supportsTriggerRumble(null)); // true false
462
+ console.log(await triggerRumble(pad, { duration: 120, leftTrigger: 0, rightTrigger: 0.6 })); // true: played to the end
463
+ console.log(played[0]); // { duration: 120, startDelay: 0, strongMagnitude: 0, weakMagnitude: 0, leftTrigger: 0, rightTrigger: 0.6 }
464
+
465
+ const controller = new AbortController();
466
+ const kick = triggerRumble(pad, { duration: 2000, strongMagnitude: 1, signal: controller.signal });
467
+ controller.abort(); // stops the effect if it is still this call's
468
+ await kick.catch((error) => console.log((error as Error).name)); // 'AbortError'
469
+ ```
470
+
471
+ - Options and defaults: `duration` 100 ms, `startDelay` 0 (whole milliseconds, 0 or more), `strongMagnitude` and
472
+ `weakMagnitude` 0, `leftTrigger` and `rightTrigger` 1 (each 0 to 1), `timeout` 6000 ms (raise it for longer effects)
473
+ and `signal`. A value out of range throws a `RangeError`.
474
+ - The promise gives true when the effect ran to the end, false when the pad has no trigger motors, is disconnected,
475
+ or a newer effect took over (`'preempted'`). `supportsTriggerRumble` is true or false from the actuator's `effects`,
476
+ or undefined for an older actuator with no list, which `triggerRumble` then just tries.
477
+ - An abort or timeout stops the effect with `reset()` (or a zero effect) only when it is still this call's, bounded at
478
+ 1000 ms; if stopping fails too you get an `AggregateError` with both errors. Browsers may cap `duration`.
479
+
480
+ ## Gestures
481
+
482
+ ```ts
483
+ import {Gestures} from 'margoengine/input';
484
+ const canvas = document.querySelector('canvas')!;
485
+ let zoom = 1;
486
+ using gestures = new Gestures(canvas, {swipeDistance: 60});
487
+ gestures.on('pinch', (e) => (zoom *= e.scale!));
488
+ gestures.on('swipe', (e) => console.log(e.direction, e.velocity));
489
+ gestures.on('doubletap', () => (zoom = 1));
490
+ ```
491
+
492
+ Touch and pen only (mouse never triggers them, so they never fight orbit controls): `tap`, `doubletap`, `swipe` (direction and px/s), two-finger `pinch` (scale since the last event) and `rotate` (radians). Thresholds are options with defaults. Set `touch-action: none` on the element.
493
+
494
+ ## Webcam landmarks
495
+
496
+ `@margoengine/input/landmarks` turns any face, hand or pose detector's output into one `LandmarkFrame` stream, an async iterator with a timestamp per frame. Margo ships no trained weights and no detector and never downloads one: the app loads its own (MediaPipe Tasks' FaceLandmarker, HandLandmarker or PoseLandmarker, or anything that gives points) and passes its results in.
497
+
498
+ ```ts
499
+ import {fromMediaPipe, landmarkStream, OneEuroFilter, webcamLandmarks, type LandmarkSource} from 'margoengine/input/landmarks';
500
+
501
+ // A recorded FaceLandmarker result; with MediaPipe Tasks, detect would return
502
+ // fromMediaPipe({face: faceLandmarker.detectForVideo(video, time)}, time).
503
+ const recorded = {face: {faceLandmarks: [[{x: 0.5, y: 0.5, z: 0}]], faceBlendshapes: [{categories: [{categoryName: 'jawOpen', score: 0.4}]}]}};
504
+ const detect = (_video: unknown, time: number) => fromMediaPipe(recorded, time);
505
+
506
+ const controller = new AbortController();
507
+ let source: LandmarkSource;
508
+ try {
509
+ source = await webcamLandmarks({detect, signal: controller.signal});
510
+ } catch (error) {
511
+ // No camera, or permission refused: play the recording instead.
512
+ console.warn('No webcam:', (error as Error).message);
513
+ const replay = landmarkStream({buffer: 8});
514
+ for (let time = 0; time <= 99; time += 33) replay.push(fromMediaPipe(recorded, time));
515
+ replay.close();
516
+ source = replay;
517
+ }
518
+ const jaw = new OneEuroFilter({minCutoff: 1, beta: 0.5});
519
+ for await (const frame of source) {
520
+ console.log(frame.time, jaw.filter(frame.faces[0]?.blendshapes?.jawOpen ?? 0, frame.time / 1000));
521
+ if (frame.time > 60) break; // break, dispose() or the signal stops the camera
522
+ }
523
+ ```
524
+
525
+ - `LandmarkFrame`: `time` (ms), `faces` (`landmarks`, optional `blendshapes` by ARKit name, `transform`, `score`), `hands` (`landmarks`, `worldLandmarks`, `handedness` `'left'` or `'right'` for the subject's hand, `score`) and `poses` (`landmarks`, `worldLandmarks`). Points are `{x, y, z, visibility?, presence?}`: image points normalised 0..1 (y down), world points in metres.
526
+ - `fromMediaPipe({face, hands, pose}, time, {mirroredHandedness})` reads MediaPipe Tasks Vision results as they come from `detectForVideo`: `faceLandmarks`, `faceBlendshapes` (`_neutral` dropped), `facialTransformationMatrixes`, `landmarks`, `worldLandmarks` and `handedness` (or the older `handednesses`). MediaPipe labels hands as if the picture were mirrored, so `mirroredHandedness` (default true) swaps them for an unmirrored webcam frame.
527
+ - `landmarkStream({buffer = 1, signal})` is a source the app pushes frames into (`push`, `close`, `dispose`); a slow reader gets the newest `buffer` frames, older ones are dropped.
528
+ - `startWebcam({onFrame, video, constraints, signal, mediaDevices})` opens the camera (`getUserMedia`, default `{facingMode: 'user', width: 640, height: 480}`), plays it muted and inline into `video` (default a new element) and calls `onFrame(video, time)` once per new picture (`requestVideoFrameCallback`, else animation frames). `stop()`, `using` or the signal stops every track.
529
+ - `webcamLandmarks({detect, buffer, ...webcam})` is both together: the source the drivers read. A detector that throws stops the camera and its error comes out of the next read.
530
+ - `OneEuroFilter({minCutoff = 1, beta = 0.007, dCutoff = 1})` is the one-euro filter (Casiez, Roussel and Vogel, CHI 2012): `filter(value, seconds)` smooths one number, cutting jitter at rest and lag in motion; raise `beta` for less lag, lower `minCutoff` for less jitter. `reset()` forgets the history.
531
+
532
+ ## Webcam face to morph targets
533
+
534
+ `@margoengine/input/face` drives ARKit-named morph targets (the 52 names face rigs commonly use) and gives the head rotation from face frames. It takes a detector's blendshape scores when they are there (MediaPipe's FaceLandmarker with `outputFaceBlendshapes`) and otherwise measures the face mesh: the eye aspect ratio for blinks, the lip gap for the jaw, mouth width and corners for smiles, frowns and puckers, and brow height.
535
+
536
+ ```ts
537
+ import {FaceDriver} from 'margoengine/input/face';
538
+ import {fromMediaPipe} from 'margoengine/input/landmarks';
539
+
540
+ // Any model with named morph targets: a loaded glTF model's primitives fit.
541
+ const model = {primitives: [{targetNames: ['jawOpen', 'eyeBlinkLeft', 'Smile_L'], weights: [0, 0, 0]}]};
542
+ using face = new FaceDriver({names: {mouthSmileLeft: 'Smile_L'}});
543
+
544
+ // Two recorded FaceLandmarker results: a resting face (to calibrate on), then a smile with the jaw open.
545
+ const result = (jaw: number, smile: number) => ({
546
+ faceLandmarks: [[]],
547
+ faceBlendshapes: [{categories: [{categoryName: 'jawOpen', score: jaw}, {categoryName: 'mouthSmileLeft', score: smile}]}],
548
+ facialTransformationMatrixes: [{data: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -40, 1]}],
549
+ });
550
+ face.calibrate(fromMediaPipe({face: result(0.05, 0)}, 0));
551
+ for (let time = 33; time <= 330; time += 33) face.update(fromMediaPipe({face: result(0.6, 0.8)}, time));
552
+ face.apply(model);
553
+ console.log(model.primitives[0].weights, face.state.rotation);
554
+ // From a webcam: await face.drive(await webcamLandmarks({detect}), model, {signal}).
555
+ ```
556
+
557
+ - `update(frame or face, time?)` reads the frame's first face and returns `{weights, rotation, tracked, time}`; `apply(model or models)` writes each weight to the targets named after it (case-insensitive, through `names`), leaving other targets alone. `drive(source, model, {signal, onUpdate})` does both for every frame of a `LandmarkSource`.
558
+ - `calibrate(frame)`: take a relaxed face looking at the camera as neutral. Scores are rescaled from the person's resting value, landmark measures are taken against their own face, and the head rotation is measured from that pose.
559
+ - Options: `names` (ARKit name to morph name, default the ARKit names), `source` (`'auto'` scores when given else landmarks, `'blendshapes'`, `'landmarks'`), `minScore` (0.5: a weaker face holds the last good values), `hold` (0.5 s, then back to neutral), `smoothing` (one-euro `{minCutoff: 1.5, beta: 0.5}`, or false), `mirror` (false; swaps left and right for a selfie picture) and `aspect` (1; the frame's width over height, for landmark measures).
560
+ - Landmarks alone give `LANDMARK_BLENDSHAPES` (blinks, wide eyes, jaw, smiles, frowns, pucker and brows); scores give all 52. `measureFace`, `faceWeightsFromLandmarks` and `headRotation` are the measures on their own. The head rotation is in a y-up frame looking along +z with the face's left at +x; with a face transform from the detector it is that transform's rotation.
561
+
562
+ ARKit is a trademark of Apple Inc.; only its published blendshape names are used.
563
+
564
+ ## Webcam hands and body to a skeleton
565
+
566
+ `@margoengine/input/body` poses a humanoid skeleton from Pose Landmarker (33 points) and Hand Landmarker (21 points per hand) frames: each mapped bone turns from its rest direction onto the landmark direction, a second direction fixes the twist of the hips, chest and hands, and each joint stays within its limit. Bones are the VRM humanoid names; `humanoidBones` in `@margoengine/rigging/retarget` maps Mixamo, Godot and other rigs onto them.
567
+
568
+ ```ts
569
+ import {Skeleton} from 'margoengine/animation';
570
+ import {BodyDriver} from 'margoengine/input/body';
571
+ import {landmarkStream, type Landmark} from 'margoengine/input/landmarks';
572
+
573
+ // A T-pose arm: shoulder, upper arm, forearm and hand, its left at +x (a loaded skin's skeleton fits).
574
+ const skeleton = new Skeleton([
575
+ {name: 'upperChest', parent: -1, translation: [0, 1.3, 0]},
576
+ {name: 'leftUpperArm', parent: 0, translation: [0.17, 0.1, 0]},
577
+ {name: 'leftLowerArm', parent: 1, translation: [0.27, 0, 0]},
578
+ {name: 'leftHand', parent: 2, translation: [0.25, 0, 0]},
579
+ ]);
580
+ using body = new BodyDriver(skeleton, {parts: ['pose']});
581
+
582
+ // Recorded PoseLandmarker world points (metres, y down): a T-pose, then the forearm raised.
583
+ const point = (x: number, y: number, z = 0): Landmark => ({x, y, z, visibility: 0.99});
584
+ const pose = (wrist: Landmark) => {
585
+ const points = Array.from({length: 33}, () => point(0, 0));
586
+ points[11] = point(0.17, -0.45);
587
+ points[13] = point(0.44, -0.45);
588
+ points[15] = wrist;
589
+ return points;
590
+ };
591
+ const frame = (time: number, points: Landmark[]) => ({time, faces: [], hands: [], poses: [{landmarks: points, worldLandmarks: points}]});
592
+ body.calibrate(frame(0, pose(point(0.69, -0.45))));
593
+
594
+ const source = landmarkStream({buffer: 30});
595
+ for (let time = 33; time <= 990; time += 33) source.push(frame(time, pose(point(0.44, -0.7))));
596
+ source.close();
597
+ await body.drive(source, {signal: AbortSignal.timeout(5000)});
598
+ console.log(skeleton.getPose(2).rotation); // the elbow bent 90 degrees about +z
599
+ ```
600
+
601
+ - `update(frame, time?)` poses the bones from the frame's first pose and one hand per side and returns `{tracked, driven, time}`; `drive(source, {signal, onUpdate})` does it for every frame of a `LandmarkSource`, such as `webcamLandmarks`.
602
+ - `calibrate(frame)`: the person stands in the skeleton's rest pose (T-pose or A-pose) and their landmark directions become the rest directions, so proportions and camera tilt drop out. Uncalibrated, the skeleton's own rest directions are used.
603
+ - Options: `bones` (humanoid name to skeleton name, or the index map `humanoidBones` returns; default the humanoid names, case-insensitive), `parts` (`['pose', 'hands']`), `minVisibility` (0.5: a hidden point leaves its bone where it was), `minScore` (0.5), `hold` (0.5 s, then back to the rest pose), `smoothing` (one-euro `{minCutoff: 1.5, beta: 0.3}` on each direction, or false), `mirror` (false; swaps left and right for a selfie picture), `aspect` (1; for image points when the detector gives no world points) and `limits` (radians per bone name, 0 to pi). A point that is hidden or not a finite number leaves its bone where it was.
604
+ - `POSE_TARGETS` and `handTargets(side)` list the driven bones with their landmarks and default limits (elbows and knees 2.7 rad, fingers 1.6 to 1.9, chest and neck 1). A limit bounds the turn from the bone's rest rotation relative to its parent, as a cone about the rest pose; hinge axes are not enforced. Twist about a bone is kept only where a side direction gives it (hips, chest, hands): upper arms and legs take the shortest turn.
605
+
606
+ Apache-2.0. Optional, tree-shakable package; core peer: ^0.1.0 || ^1.0.0.
607
+
608
+ Build and unit tests: npm test --workspace @margoengine/input
609
+