@margoengine/input 0.0.0-stage → 0.1.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +370 -3
- package/dist/body.d.ts +117 -0
- package/dist/body.js +446 -0
- package/dist/face.d.ts +136 -0
- package/dist/face.js +344 -0
- package/dist/gestures.d.ts +68 -0
- package/dist/haptics.d.ts +52 -0
- package/dist/haptics.js +59 -0
- package/dist/index.d.ts +205 -0
- package/dist/index.js +3 -0
- package/dist/interactions.d.ts +92 -0
- package/dist/interactions.js +93 -0
- package/dist/labels-DZOEJBkX.js +70 -0
- package/dist/labels.d.ts +8 -0
- package/dist/landmarks.d.ts +197 -0
- package/dist/landmarks.js +183 -0
- package/dist/layout.d.ts +62 -0
- package/dist/layout.js +76 -0
- package/dist/lock.d.ts +72 -0
- package/dist/lock.js +91 -0
- package/dist/motion.d.ts +97 -0
- package/dist/motion.js +98 -0
- package/dist/pen.d.ts +86 -0
- package/dist/pen.js +111 -0
- package/dist/players.d.ts +129 -0
- package/dist/players.js +161 -0
- package/dist/replay.d.ts +109 -0
- package/dist/replay.js +99 -0
- package/dist/src-eYqyrCA7.js +459 -0
- package/dist/vector.d.ts +44 -0
- package/dist/vector.js +66 -0
- package/dist/xr.d.ts +124 -0
- package/dist/xr.js +154 -0
- package/package.json +105 -6
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Scott Campbell
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/NOTICE
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,370 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
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
|
+
|