3D engine that AI agents drive
Add input addon: open sources, named actions and axes, per-fixed-step sampling (#773)
Nguyen Xuan Ane459ce44f7b6
diff --git a/README.md b/README.mdindex 7211316b..43a5cca3 100644--- a/README.md+++ b/README.md@@ -139,6 +139,7 @@ Each addon is a separate import, so a page loads only what it uses.| Vehicles | `67js/addons/vehicle` | [Wheeled vehicles on a path](https://67js.codepawl.com/vehicle.md) || Physics | `67js/addons/physics` | [Rapier contacts and joints](docs/physics.md) recorded into a timeline || Live games | `67js/addons/runtime` | [Game loop](docs/runtime.md) with fixed or variable steps and pluggable systems |+| Live games | `67js/addons/input` | [Input](docs/input.md): keyboard, mouse, gamepad and custom sources mapped to named actions and axes || Modeling | `67js/addons/mesh`, `67js/addons/modeling`, `67js/addons/sculpt` | [Mesh editing](docs/mesh.md), [modeling](docs/modeling.md) and [sculpt brushes](https://67js.codepawl.com/sculpt.md) || Offline light | `67js/addons/path-tracer`, `67js/addons/light-bake` | [Path-traced stills](https://67js.codepawl.com/path-tracer.md) and [baked lightmaps](https://67js.codepawl.com/light-bake.md) || Post passes | `67js/addons/user-pass` | [Your own full-screen GLSL passes](docs/user-passes.md): dither, pixel downscale, quantise |diff --git a/bench/runtime-loop/main.js b/bench/runtime-loop/main.jsindex a9b8b7f4..7b3854b8 100644--- a/bench/runtime-loop/main.js+++ b/bench/runtime-loop/main.js@@ -2,12 +2,15 @@// shown live in each update mode. Open bench/runtime-loop/index.html with `npm run dev`; ?mode=fixed|variable|both picks the start mode.import { Renderer67, box, sphere } from '/src/index.js';import { createRuntime } from '/src/runtime.js';+import { createInput, gamepadSource, keyboardSource } from '/src/input.js';const GRAVITY = -9.8;const FIXED_RATE = 20; // Low on purpose, so the difference between fixed and interpolated is visible.const BOUNCE_ENERGY = 0.9;const BALL_RADIUS = 0.4;const SPIN_RADIANS_PER_SECOND = 1.5;+const CUBE_SPEED = 3; // World units per second along the moveX axis.+const JUMP_SPEED = 6;function translation(x, y, z, scale = 1) {return new Float32Array([scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, scale, 0, x, y, z, 1]);@@ -58,22 +61,46 @@ const physicsSystem = {}},fixedUpdate(stepSeconds) {+ if (input.wasPressed('jump')) this.velocity = JUMP_SPEED;this.integrate(stepSeconds);},// Variable mode never calls fixedUpdate, so the same physics runs on the frame time there.update(deltaSeconds, context) {- if (context.mode === 'variable') this.integrate(deltaSeconds);+ if (context.mode !== 'variable') return;+ if (input.wasPressed('jump')) this.velocity = JUMP_SPEED;+ this.integrate(deltaSeconds);},};const spinSystem = {name: 'cube-spin',angle: 0,- update(deltaSeconds) {+ x: 1.2,+ slide(deltaSeconds) {+ this.x = Math.max(-3.5, Math.min(3.5, this.x + input.getAxis('moveX') * CUBE_SPEED * deltaSeconds));+ },+ fixedUpdate(stepSeconds) {+ this.slide(stepSeconds);+ },+ update(deltaSeconds, context) {this.angle += SPIN_RADIANS_PER_SECOND * deltaSeconds;+ if (context.mode === 'variable') this.slide(deltaSeconds);},};+// Keys or a gamepad drive the sample: A/D or the arrow keys slide the cube, Space (or gamepad button 0) kicks the ball up.+const input = createInput({+ sources: [keyboardSource(), gamepadSource()],+ actions: { jump: ['keyboard/Space', 'gamepad/0.button0'] },+ axes: {+ moveX: [+ 'keyboard/KeyD', 'keyboard/ArrowRight',+ { control: 'keyboard/KeyA', scale: -1 }, { control: 'keyboard/ArrowLeft', scale: -1 },+ 'gamepad/0.axis0',+ ],+ },+});+const canvas = document.querySelector('canvas');const renderer = new Renderer67(canvas, parts, { samples: 4, memoryBudgetMiB: 256 });renderer.resize();@@ -83,7 +110,7 @@ function buildFrame(context) {const blend = context.alpha;const height = physicsSystem.previousHeight + (physicsSystem.height - physicsSystem.previousHeight) * blend;ballPart.matrix = translation(-1.2, height, 0, BALL_RADIUS);- cubePart.matrix = rotationAroundY(spinSystem.angle, 1.2, 0.5, 0);+ cubePart.matrix = rotationAroundY(spinSystem.angle, spinSystem.x, 0.5, 0);renderer.updateParts(parts);return { eye: [0, 3, 8], target: [0, 1.2, 0], up: [0, 1, 0], time: context.elapsedSeconds };}@@ -96,7 +123,7 @@ function startMode(mode) {mode,fixedRate: FIXED_RATE,frame: buildFrame,- systems: [physicsSystem, spinSystem],+ systems: [input, physicsSystem, spinSystem],});runtime.start();for (const button of document.querySelectorAll('button[data-mode]')) {@@ -116,6 +143,7 @@ setInterval(() => {`${stats.framesPerSecond.toFixed(0)} fps, ${stats.averageFrameMilliseconds.toFixed(1)} ms average, ${stats.maximumFrameMilliseconds.toFixed(1)} ms worst`,`update ${stats.updateMilliseconds.toFixed(2)} ms, render ${stats.renderMilliseconds.toFixed(2)} ms`,`fixed steps ${stats.fixedSteps}, alpha ${stats.alpha.toFixed(2)}`,+ 'A/D or arrows slide the cube, Space kicks the ball',].join('\n');}, 250);diff --git a/changes/773.md b/changes/773.mdnew file mode 100644index 00000000..fcbd11fb--- /dev/null+++ b/changes/773.md@@ -0,0 +1 @@+- `67js/addons/input` adds `createInput`, an open input layer: sources register, named actions and axes with rebinding and dead zones, keyboard, mouse and gamepad sources, and per-fixed-step sampling as a runtime system (#773)diff --git a/docs/input.md b/docs/input.mdnew file mode 100644index 00000000..46b78ade--- /dev/null+++ b/docs/input.md@@ -0,0 +1,72 @@+# Input: sources, actions and axes++`67js/addons/input` reads devices for a live game. Game logic asks for `jump` or `moveX`, never for `Space`. Any source can register, so a MIDI pad, a touch stick, a webcam tracker, a replay file or an agent plugs in the same way as a keyboard. Like the [runtime](runtime.md), it loads only when imported and adds no dependency.++```js+import { createRuntime } from '67js/addons/runtime';+import { createInput, keyboardSource, mouseSource, gamepadSource } from '67js/addons/input';++const input = createInput({+ sources: [keyboardSource(), mouseSource({ target: canvas }), gamepadSource()],+ actions: { jump: ['keyboard/Space', 'gamepad/0.button0'], shoot: ['mouse/button0'] },+ axes: {+ moveX: { bindings: ['keyboard/KeyD', { control: 'keyboard/KeyA', scale: -1 }, 'gamepad/0.axis0'], deadZone: 0.15 },+ },+});++const player = {+ name: 'player',+ fixedUpdate(step) {+ if (input.wasPressed('jump')) velocity = 6;+ x += input.getAxis('moveX') * speed * step;+ },+};+createRuntime(renderer, { systems: [input, player] }).start(); // input first, so game systems read this step's state+```++`input` is a runtime system. Put it first in `systems`. It attaches its sources in `init` and removes every listener in `dispose`.++## Controls and sampling++Every value has a control name, `<source>/<name>`: `keyboard/Space`, `mouse/button0`, `gamepad/0.axis1`. A button is 0 or 1; an axis is -1 to 1 (or any number, such as a pixel position). A control counts as down at `buttonThreshold` (default 0.5).++Events change the live state at any time, but game code reads a snapshot taken by `sample()`. The runtime calls it once per fixed step, so every system in that step sees the same state. When one frame runs several fixed steps, the first step sees the new press and release edges and later steps see none. A press and release between two samples still reports `wasPressed` and `wasReleased` once. In `'variable'` mode the input samples once per frame; in `'both'` mode `update` reads the last fixed-step snapshot.++| Call | Meaning |+| --- | --- |+| `isHeld(action)` | Any bound control is down |+| `wasPressed(action)`, `wasReleased(action)` | Went down or up since the previous sample |+| `getAxis(axis)` | Sum of `value * scale` over the bindings, clamped to -1 to 1, then dead zone applied |++## Actions, axes and rebinding++`bindAction(name, controls)` and `bindAxis(name, { bindings, deadZone })` add or replace a mapping at any time, which is rebinding. A binding is a control name or `{ control, scale }`. `unbindAction` and `unbindAxis` remove one. Reading a name that was never bound throws an error that shows the `bindAction` call to add.++## Built-in sources++- `keyboardSource({ target })`: `keyboard/<KeyboardEvent.code>`. Key repeat is ignored.+- `mouseSource({ target, pointerLockElement })`: `mouse/button0..`, `mouse/x`, `mouse/y` and `mouse/deltaX`, `mouse/deltaY`, which sum movement since the last sample. Pointer events cover touch and pen as `button0`. Pass `pointerLockElement` to request pointer lock on press.+- `gamepadSource({ getGamepads })`: polled each sample, `gamepad/<index>.button<n>` and `gamepad/<index>.axis<n>`. An unplugged pad reads 0.++Keyboard and mouse release everything held when the window loses focus.++## Custom and scripted input++A source is `{ name, attach(emit), poll(emit), endSample(emit), dispose() }`; only `name` is required. Call `emit(controlName, value)` from your own listeners, or from `poll` each sample, and `emit.releaseAll()` to release the source's controls.++```js+input.registerSource({+ name: 'midi',+ attach(emit) { port.onmessage = message => emit(`note${message.note}`, message.velocity / 127); },+ dispose() { port.onmessage = null; },+});+input.bindAction('kick', ['midi/note36']);+```++Tests, replays and agents drive a game through the same path with `input.press('script/start')`, `input.release(...)` or `input.setControl(name, value)`.++## Limits++16 sources, 512 controls, 128 actions, 64 axes, 16 bindings each (`INPUT_LIMITS`). Errors name the field and say what to pass.++A runnable sample is `bench/runtime-loop/index.html`: A/D or the arrow keys slide the cube, Space kicks the ball.diff --git a/package.json b/package.jsonindex 97aad972..93180ac7 100644--- a/package.json+++ b/package.json@@ -42,6 +42,7 @@"docs/modeling.md","docs/physics.md","docs/runtime.md",+ "docs/input.md","docs/scene-query.md","docs/user-passes.md","docs/skeleton-pose.md",@@ -118,6 +119,7 @@"./addons/texture-update": "./build/texture-update.js","./addons/cloth": "./build/cloth.js","./addons/runtime": "./build/runtime.js",+ "./addons/input": "./build/input.js","./addons/update-part-vertices": "./build/update-part-vertices.js","./package.json": "./package.json"},diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex c9bf2b87..c1736dd8 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -53,7 +53,7 @@ const sourceDocuments = ['vehicle.md','vegetation.md', 'terrain.md', 'grass.md', 'clutter.md', 'light-bake.md', 'path-tracer.md', 'gaussian-splats.md','camera-path.md', 'lighting.md', 'volumetric.md', 'film-physics.md',- 'runtime.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',+ 'runtime.md', 'input.md', 'surface-attachment.md', 'agent-scene.md', 'mcp.md', 'agent-look.md', 'agent-asset.md', 'agent-render-jobs.md', 'agent-motion.md', 'agent-character-motion.md', 'agent-review.md',];for (const name of sourceDocuments) {await copyFile(resolve(root, 'docs', name), resolve(root, 'public', name));diff --git a/src/docs-live.js b/src/docs-live.jsindex 7b34cce0..d98ebc38 100644--- a/src/docs-live.js+++ b/src/docs-live.js@@ -63,6 +63,7 @@ const addonLoaders = import.meta.glob(['./texture-update.js','./cloth.js','./runtime.js',+ './input.js','./update-part-vertices.js',]);const moduleCache = new Map();diff --git a/src/input.js b/src/input.jsnew file mode 100644index 00000000..50cb1ce2--- /dev/null+++ b/src/input.js@@ -0,0 +1,376 @@+// Live input layer: an open registry of input sources, named actions and axes, and a runtime system that samples them once+// per fixed step. A source is any object that emits named values (keyboard, mouse, gamepad, MIDI, a script, an agent).+// Nothing here is a fixed list: game code registers its own sources and maps controls to its own actions.+// Events write the live control state at any time; the snapshot game logic reads changes only when the runtime samples,+// so a fixed-step game sees the same state for the whole step. See docs/input.md.++export const INPUT_LIMITS = Object.freeze({+ maximumSources: 16,+ maximumControls: 512,+ maximumActions: 128,+ maximumAxes: 64,+ maximumBindings: 16,+ defaultButtonThreshold: 0.5,+ defaultDeadZone: 0.15,+});++function describe(value) {+ return value === null ? 'null' : typeof value;+}++function requireName(value, label) {+ if (typeof value !== 'string' || value === '') {+ throw new TypeError(`${label} must be a non-empty string, got ${describe(value)}.`);+ }+ return value;+}++function normalizeBindings(bindings, label) {+ if (!Array.isArray(bindings) || bindings.length === 0 || bindings.length > INPUT_LIMITS.maximumBindings) {+ throw new RangeError(`${label} must be an array of 1 to ${INPUT_LIMITS.maximumBindings} control names such as "keyboard/Space".`);+ }+ return bindings.map(binding => {+ const entry = typeof binding === 'string' ? { control: binding, scale: 1 } : binding;+ if (entry === null || typeof entry !== 'object') {+ throw new TypeError(`${label} entries must be a control name or { control, scale }, got ${describe(binding)}.`);+ }+ const scale = entry.scale === undefined ? 1 : entry.scale;+ if (!Number.isFinite(scale)) {+ throw new TypeError(`${label} scale must be a finite number, got ${String(entry.scale)}.`);+ }+ return { control: requireName(entry.control, `${label} control`), scale };+ });+}++function applyDeadZone(value, deadZone) {+ const magnitude = Math.abs(value);+ if (magnitude <= deadZone) return 0;+ return Math.sign(value) * Math.min(1, (magnitude - deadZone) / (1 - deadZone));+}++export function createInput(options = {}) {+ const buttonThreshold = options.buttonThreshold ?? INPUT_LIMITS.defaultButtonThreshold;+ if (!Number.isFinite(buttonThreshold) || buttonThreshold <= 0 || buttonThreshold > 1) {+ throw new RangeError(`createInput buttonThreshold must be a number above 0 and up to 1, got ${String(buttonThreshold)}.`);+ }++ const controls = new Map(); // "source/name" -> { value, pressedLatch, releasedLatch }+ const actionBindings = new Map();+ const axisBindings = new Map();+ const sources = new Map(); // name -> { source, emit, attached }+ let started = false;+ let disposed = false;+ let snapshot = { actions: new Map(), axes: new Map() };++ function assertAlive() {+ if (disposed) throw new Error('This input was disposed. Call createInput again.');+ }++ function setControl(controlName, value) {+ assertAlive();+ requireName(controlName, 'setControl control');+ if (!Number.isFinite(value)) {+ throw new TypeError(`setControl value for "${controlName}" must be a finite number (1 or 0 for a button), got ${String(value)}.`);+ }+ let control = controls.get(controlName);+ if (control === undefined) {+ if (controls.size >= INPUT_LIMITS.maximumControls) {+ throw new RangeError(`Input already has ${INPUT_LIMITS.maximumControls} controls. Reuse control names, or call releaseControls for sources that went away.`);+ }+ control = { value: 0, pressedLatch: false, releasedLatch: false };+ controls.set(controlName, control);+ }+ const wasDown = control.value >= buttonThreshold;+ const isDown = value >= buttonThreshold;+ if (isDown && !wasDown) control.pressedLatch = true;+ if (!isDown && wasDown) control.releasedLatch = true;+ control.value = value;+ }++ function releaseControls(sourceName) {+ for (const [controlName, control] of controls) {+ if (sourceName !== undefined && !controlName.startsWith(`${sourceName}/`)) continue;+ if (control.value !== 0) setControl(controlName, 0);+ }+ }++ function attach(entry) {+ if (entry.attached || typeof entry.source.attach !== 'function') {+ entry.attached = true;+ return;+ }+ entry.attached = true;+ entry.source.attach(entry.emit);+ }++ function registerSource(source) {+ assertAlive();+ if (source === null || typeof source !== 'object') {+ throw new TypeError(`An input source must be an object like { name, attach(emit), poll(emit), dispose() }, got ${describe(source)}.`);+ }+ const name = requireName(source.name, 'An input source name');+ if (name.includes('/')) throw new RangeError(`Input source name "${name}" must not contain "/". Use "midi", not "midi/1".`);+ for (const hook of ['attach', 'poll', 'endSample', 'dispose']) {+ if (source[hook] !== undefined && typeof source[hook] !== 'function') {+ throw new TypeError(`Input source "${name}" ${hook} must be a function or left out, got ${describe(source[hook])}.`);+ }+ }+ if (sources.has(name)) throw new RangeError(`An input source named "${name}" is already registered. Pass another name, or unregisterSource first.`);+ if (sources.size >= INPUT_LIMITS.maximumSources) {+ throw new RangeError(`Input already has ${INPUT_LIMITS.maximumSources} sources. Unregister one before adding "${name}".`);+ }+ const emit = (controlName, value) => setControl(`${name}/${controlName}`, value);+ emit.releaseAll = () => releaseControls(name);+ const entry = { source, emit, attached: false };+ sources.set(name, entry);+ if (started) attach(entry);+ return api;+ }++ function unregisterSource(name) {+ const entry = sources.get(name);+ if (entry === undefined) throw new RangeError(`No input source named "${String(name)}". Registered: ${[...sources.keys()].join(', ') || 'none'}.`);+ entry.source.dispose?.();+ sources.delete(name);+ releaseControls(name);+ for (const controlName of [...controls.keys()]) {+ if (controlName.startsWith(`${name}/`)) controls.delete(controlName);+ }+ return api;+ }++ function bindAction(name, bindings) {+ assertAlive();+ requireName(name, 'bindAction name');+ if (!actionBindings.has(name) && actionBindings.size >= INPUT_LIMITS.maximumActions) {+ throw new RangeError(`Input already has ${INPUT_LIMITS.maximumActions} actions. Reuse a name or unbindAction first.`);+ }+ actionBindings.set(name, normalizeBindings(bindings, `Action "${name}" bindings`));+ return api;+ }++ function bindAxis(name, definition) {+ assertAlive();+ requireName(name, 'bindAxis name');+ const bindings = Array.isArray(definition) ? definition : definition?.bindings;+ const deadZone = (Array.isArray(definition) ? undefined : definition?.deadZone) ?? INPUT_LIMITS.defaultDeadZone;+ if (!Number.isFinite(deadZone) || deadZone < 0 || deadZone >= 1) {+ throw new RangeError(`Axis "${name}" deadZone must be a number from 0 up to but not including 1, got ${String(deadZone)}.`);+ }+ if (!axisBindings.has(name) && axisBindings.size >= INPUT_LIMITS.maximumAxes) {+ throw new RangeError(`Input already has ${INPUT_LIMITS.maximumAxes} axes. Reuse a name or unbindAxis first.`);+ }+ axisBindings.set(name, { bindings: normalizeBindings(bindings, `Axis "${name}" bindings`), deadZone });+ return api;+ }++ function sample() {+ assertAlive();+ for (const entry of sources.values()) entry.source.poll?.(entry.emit);+ const actions = new Map();+ for (const [name, bindings] of actionBindings) {+ const state = { held: false, pressed: false, released: false };+ for (const { control: controlName } of bindings) {+ const control = controls.get(controlName);+ if (control === undefined) continue;+ if (control.value >= buttonThreshold) state.held = true;+ if (control.pressedLatch) state.pressed = true;+ if (control.releasedLatch) state.released = true;+ }+ actions.set(name, state);+ }+ const axes = new Map();+ for (const [name, { bindings, deadZone }] of axisBindings) {+ let total = 0;+ for (const { control: controlName, scale } of bindings) {+ total += (controls.get(controlName)?.value ?? 0) * scale;+ }+ axes.set(name, applyDeadZone(Math.max(-1, Math.min(1, total)), deadZone));+ }+ for (const control of controls.values()) {+ control.pressedLatch = false;+ control.releasedLatch = false;+ }+ for (const entry of sources.values()) entry.source.endSample?.(entry.emit);+ snapshot = { actions, axes };+ }++ function actionState(name) {+ const state = snapshot.actions.get(name);+ if (state !== undefined) return state;+ if (!actionBindings.has(name)) {+ throw new RangeError(`No action named "${String(name)}". Bind it first: input.bindAction("${String(name)}", ["keyboard/Space"]).`);+ }+ return { held: false, pressed: false, released: false }; // bound but not sampled yet+ }++ function getAxis(name) {+ const value = snapshot.axes.get(name);+ if (value !== undefined) return value;+ if (!axisBindings.has(name)) {+ throw new RangeError(`No axis named "${String(name)}". Bind it first: input.bindAxis("${String(name)}", { bindings: ["gamepad/0.axis0"] }).`);+ }+ return 0;+ }++ function dispose() {+ if (disposed) return;+ for (const entry of [...sources.values()].reverse()) entry.source.dispose?.();+ sources.clear();+ controls.clear();+ actionBindings.clear();+ axisBindings.clear();+ snapshot = { actions: new Map(), axes: new Map() };+ disposed = true;+ }++ const api = {+ name: options.name ?? 'input',+ registerSource,+ unregisterSource,+ bindAction,+ bindAxis,+ unbindAction: name => actionBindings.delete(name),+ unbindAxis: name => axisBindings.delete(name),+ setControl,+ press: controlName => setControl(controlName, 1),+ release: controlName => setControl(controlName, 0),+ releaseControls,+ sample,+ isHeld: name => actionState(name).held,+ wasPressed: name => actionState(name).pressed,+ wasReleased: name => actionState(name).released,+ getAxis,+ get sources() {+ return [...sources.keys()];+ },+ // Runtime system hooks. Fixed-step games sample once per fixed step; a variable-only loop samples once per frame.+ init() {+ assertAlive();+ started = true;+ for (const entry of sources.values()) attach(entry);+ },+ fixedUpdate() {+ sample();+ },+ update(delta, context) {+ if (context?.mode === 'variable') sample();+ },+ dispose,+ };++ for (const source of options.sources ?? []) registerSource(source);+ for (const [name, bindings] of Object.entries(options.actions ?? {})) bindAction(name, bindings);+ for (const [name, definition] of Object.entries(options.axes ?? {})) bindAxis(name, definition);+ return api;+}++// Keyboard: controls are "keyboard/<KeyboardEvent.code>", for example keyboard/Space or keyboard/KeyW.+export function keyboardSource(options = {}) {+ const target = options.target ?? globalThis;+ const blurTarget = options.blurTarget ?? globalThis;+ let handlers = null;+ return {+ name: 'keyboard',+ attach(emit) {+ assertTarget(target, 'keyboardSource target');+ handlers = {+ keydown: event => { if (!event.repeat) emit(event.code, 1); },+ keyup: event => emit(event.code, 0),+ blur: () => emit.releaseAll(),+ };+ target.addEventListener('keydown', handlers.keydown);+ target.addEventListener('keyup', handlers.keyup);+ blurTarget.addEventListener?.('blur', handlers.blur);+ },+ dispose() {+ if (handlers === null) return;+ target.removeEventListener('keydown', handlers.keydown);+ target.removeEventListener('keyup', handlers.keyup);+ blurTarget.removeEventListener?.('blur', handlers.blur);+ handlers = null;+ },+ };+}++// Mouse and pointer: "mouse/button0".. for buttons (touch and pen report as button0), "mouse/x" and "mouse/y" in client+// pixels, and "mouse/deltaX", "mouse/deltaY" as movement summed since the last sample (works under pointer lock).+export function mouseSource(options = {}) {+ const target = options.target ?? globalThis;+ const blurTarget = options.blurTarget ?? globalThis;+ let handlers = null;+ let movementX = 0;+ let movementY = 0;+ return {+ name: 'mouse',+ attach(emit) {+ assertTarget(target, 'mouseSource target');+ handlers = {+ pointerdown: event => {+ emit(`button${event.button ?? 0}`, 1);+ if (options.pointerLockElement?.requestPointerLock) options.pointerLockElement.requestPointerLock();+ },+ pointerup: event => emit(`button${event.button ?? 0}`, 0),+ pointermove: event => {+ emit('x', event.clientX ?? 0);+ emit('y', event.clientY ?? 0);+ movementX += event.movementX ?? 0;+ movementY += event.movementY ?? 0;+ emit('deltaX', movementX);+ emit('deltaY', movementY);+ },+ blur: () => emit.releaseAll(),+ };+ for (const type of ['pointerdown', 'pointerup', 'pointermove']) target.addEventListener(type, handlers[type]);+ blurTarget.addEventListener?.('blur', handlers.blur);+ },+ endSample(emit) {+ movementX = 0;+ movementY = 0;+ emit('deltaX', 0);+ emit('deltaY', 0);+ },+ dispose() {+ if (handlers === null) return;+ for (const type of ['pointerdown', 'pointerup', 'pointermove']) target.removeEventListener(type, handlers[type]);+ blurTarget.removeEventListener?.('blur', handlers.blur);+ handlers = null;+ },+ };+}++// Gamepad: polled at each sample. Controls are "gamepad/<index>.button<n>" (0 to 1) and "gamepad/<index>.axis<n>" (-1 to 1),+// for example gamepad/0.button0 and gamepad/0.axis1.+export function gamepadSource(options = {}) {+ const readGamepads = options.getGamepads ?? (() => (typeof navigator !== 'undefined' && navigator.getGamepads ? navigator.getGamepads() : []));+ let previousNames = new Set();+ return {+ name: 'gamepad',+ poll(emit) {+ const seen = new Set();+ for (const pad of readGamepads() ?? []) {+ if (!pad) continue;+ pad.buttons.forEach((button, index) => {+ const name = `${pad.index}.button${index}`;+ seen.add(name);+ emit(name, button.pressed ? 1 : button.value ?? 0);+ });+ pad.axes.forEach((value, index) => {+ const name = `${pad.index}.axis${index}`;+ seen.add(name);+ emit(name, value);+ });+ }+ for (const name of previousNames) {+ if (!seen.has(name)) emit(name, 0); // pad unplugged+ }+ previousNames = seen;+ },+ };+}++function assertTarget(target, label) {+ if (!target || typeof target.addEventListener !== 'function' || typeof target.removeEventListener !== 'function') {+ throw new TypeError(`${label} must have addEventListener and removeEventListener, such as window or a canvas.`);+ }+}diff --git a/tests/input.test.js b/tests/input.test.jsnew file mode 100644index 00000000..a011e3bb--- /dev/null+++ b/tests/input.test.js@@ -0,0 +1,215 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { createInput, gamepadSource, INPUT_LIMITS, keyboardSource, mouseSource } from '../src/input.js';+import { createRuntime } from '../src/runtime.js';++function createFakeTarget() {+ const listeners = new Map();+ return {+ addEventListener(type, handler) {+ if (!listeners.has(type)) listeners.set(type, new Set());+ listeners.get(type).add(handler);+ },+ removeEventListener(type, handler) {+ listeners.get(type)?.delete(handler);+ },+ dispatch(type, event = {}) {+ for (const handler of [...(listeners.get(type) ?? [])]) handler(event);+ },+ listenerCount() {+ let count = 0;+ for (const set of listeners.values()) count += set.size;+ return count;+ },+ };+}++function startedInput(options) {+ const input = createInput(options);+ input.init();+ return input;+}++function edges(input, name) {+ return [input.isHeld(name), input.wasPressed(name), input.wasReleased(name)];+}++test('keyboard events map to a named action with pressed, held and released edges across fixed steps', () => {+ const target = createFakeTarget();+ const input = startedInput({ sources: [keyboardSource({ target, blurTarget: createFakeTarget() })], actions: { jump: ['keyboard/Space'] } });++ input.fixedUpdate();+ assert.deepEqual(edges(input, 'jump'), [false, false, false]);++ target.dispatch('keydown', { code: 'Space' });+ assert.equal(input.isHeld('jump'), false, 'live events do not change the snapshot before sampling');+ input.fixedUpdate();+ assert.deepEqual(edges(input, 'jump'), [true, true, false]);++ input.fixedUpdate();+ assert.deepEqual(edges(input, 'jump'), [true, false, false]);++ target.dispatch('keydown', { code: 'Space', repeat: true });+ target.dispatch('keyup', { code: 'Space' });+ input.fixedUpdate();+ assert.deepEqual(edges(input, 'jump'), [false, false, true]);+});++test('a tap between two samples still reports pressed and released', () => {+ const target = createFakeTarget();+ const input = startedInput({ sources: [keyboardSource({ target, blurTarget: createFakeTarget() })], actions: { fire: ['keyboard/KeyF'] } });+ target.dispatch('keydown', { code: 'KeyF' });+ target.dispatch('keyup', { code: 'KeyF' });+ input.fixedUpdate();+ assert.deepEqual(edges(input, 'fire'), [false, true, true]);+});++test('axes combine keys and a gamepad stick, with a dead zone and rebinding', () => {+ const target = createFakeTarget();+ const pad = { index: 0, buttons: [{ pressed: false, value: 0 }], axes: [0.05] };+ const input = startedInput({+ sources: [keyboardSource({ target, blurTarget: createFakeTarget() }), gamepadSource({ getGamepads: () => [pad] })],+ axes: { moveX: { bindings: ['keyboard/KeyD', { control: 'keyboard/KeyA', scale: -1 }, 'gamepad/0.axis0'], deadZone: 0.1 } },+ });+ input.fixedUpdate();+ assert.equal(input.getAxis('moveX'), 0, 'stick drift inside the dead zone reads as zero');++ pad.axes[0] = 1;+ input.fixedUpdate();+ assert.equal(input.getAxis('moveX'), 1);++ pad.axes[0] = 0;+ target.dispatch('keydown', { code: 'KeyA' });+ input.fixedUpdate();+ assert.equal(input.getAxis('moveX'), -1);++ input.bindAxis('moveX', ['keyboard/KeyA']);+ input.fixedUpdate();+ assert.equal(input.getAxis('moveX'), 1, 'rebinding replaces the old mapping');+});++test('a gamepad button drives an action and an unplugged pad releases it', () => {+ const pad = { index: 0, buttons: [{ pressed: true, value: 1 }], axes: [] };+ let pads = [pad];+ const input = startedInput({ sources: [gamepadSource({ getGamepads: () => pads })], actions: { jump: ['gamepad/0.button0'] } });+ input.fixedUpdate();+ assert.equal(input.wasPressed('jump'), true);+ pads = [null];+ input.fixedUpdate();+ assert.deepEqual([input.isHeld('jump'), input.wasReleased('jump')], [false, true]);+});++test('mouse buttons and movement deltas are sampled and then cleared', () => {+ const target = createFakeTarget();+ const input = startedInput({+ sources: [mouseSource({ target, blurTarget: createFakeTarget() })],+ actions: { shoot: ['mouse/button0'] },+ axes: { lookX: { bindings: [{ control: 'mouse/deltaX', scale: 0.1 }], deadZone: 0 } },+ });+ target.dispatch('pointerdown', { button: 0 });+ target.dispatch('pointermove', { clientX: 10, clientY: 20, movementX: 4, movementY: 0 });+ target.dispatch('pointermove', { clientX: 14, clientY: 20, movementX: 4, movementY: 0 });+ input.fixedUpdate();+ assert.equal(input.wasPressed('shoot'), true);+ assert.ok(Math.abs(input.getAxis('lookX') - 0.8) < 1e-9);+ input.fixedUpdate();+ assert.equal(input.getAxis('lookX'), 0);+});++test('a custom source registers from game code and emits named values', () => {+ let emitter = null;+ let disposed = false;+ const midi = {+ name: 'midi',+ attach(emit) { emitter = emit; },+ dispose() { disposed = true; },+ };+ const input = createInput();+ input.registerSource(midi).bindAction('note', ['midi/note60']);+ assert.equal(emitter, null, 'sources attach when the runtime initialises the input');+ input.init();+ emitter('note60', 1);+ input.sample();+ assert.equal(input.wasPressed('note'), true);+ assert.deepEqual(input.sources, ['midi']);+ input.unregisterSource('midi');+ assert.equal(disposed, true);+ assert.deepEqual(input.sources, []);+});++test('programmatic input drives actions the same way as a device', () => {+ const input = startedInput({ actions: { start: ['script/start'] } });+ input.press('script/start');+ input.sample();+ assert.equal(input.wasPressed('start'), true);+ input.release('script/start');+ input.sample();+ assert.equal(input.wasReleased('start'), true);+});++test('focus loss releases held keys', () => {+ const target = createFakeTarget();+ const blurTarget = createFakeTarget();+ const input = startedInput({ sources: [keyboardSource({ target, blurTarget })], actions: { run: ['keyboard/ShiftLeft'] } });+ target.dispatch('keydown', { code: 'ShiftLeft' });+ input.sample();+ assert.equal(input.isHeld('run'), true);+ blurTarget.dispatch('blur');+ input.sample();+ assert.deepEqual([input.isHeld('run'), input.wasReleased('run')], [false, true]);+});++test('dispose removes every listener and the input rejects further use', () => {+ const target = createFakeTarget();+ const blurTarget = createFakeTarget();+ const input = startedInput({ sources: [keyboardSource({ target, blurTarget }), mouseSource({ target, blurTarget })] });+ assert.ok(target.listenerCount() > 0);+ input.dispose();+ assert.equal(target.listenerCount(), 0);+ assert.equal(blurTarget.listenerCount(), 0);+ assert.throws(() => input.sample(), /disposed/);+});++test('the input is a runtime system that samples once per fixed step', () => {+ const target = createFakeTarget();+ const input = createInput({ sources: [keyboardSource({ target, blurTarget: createFakeTarget() })], actions: { jump: ['keyboard/Space'] } });+ const seen = [];+ const game = { name: 'game', fixedUpdate: () => seen.push(input.wasPressed('jump')) };+ const runtime = createRuntime({ render() {} }, {+ mode: 'fixed',+ fixedRate: 100,+ systems: [input, game],++ scheduler: { request: () => 1, cancel() {} },+ visibility: { hidden: false, subscribe: () => () => {} },+ });+ runtime.start();+ target.dispatch('keydown', { code: 'Space' });+ runtime.step(35);+ assert.deepEqual(seen, [true, false, false], 'three steps in one frame share one edge');+ runtime.dispose();+ assert.equal(target.listenerCount(), 0);+});++test('errors name the field and the fix', () => {+ const input = createInput();+ assert.throws(() => input.registerSource({}), /source name must be a non-empty string/);+ assert.throws(() => input.registerSource({ name: 'a/b' }), /must not contain "\/"/);+ assert.throws(() => input.bindAction('x', []), /Action "x" bindings must be an array of 1 to 16/);+ assert.throws(() => input.bindAxis('x', { bindings: ['a/b'], deadZone: 1 }), /deadZone/);+ assert.throws(() => input.isHeld('missing'), /No action named "missing".*bindAction/);+ assert.throws(() => input.setControl('a/b', Number.NaN), /finite number/);+ assert.throws(() => createInput({ buttonThreshold: 0 }), /buttonThreshold/);+ assert.throws(() => keyboardSource({ target: {} }).attach(() => {}), /keyboardSource target/);+});++test('counts are bounded', () => {+ const input = createInput();+ for (let index = 0; index < INPUT_LIMITS.maximumSources; index += 1) input.registerSource({ name: `s${index}` });+ assert.throws(() => input.registerSource({ name: 'extra' }), /already has 16 sources/);+ for (let index = 0; index < INPUT_LIMITS.maximumControls; index += 1) input.setControl(`s0/c${index}`, 1);+ assert.throws(() => input.setControl('s0/overflow', 1), /already has 512 controls/);+ const actions = createInput();+ for (let index = 0; index < INPUT_LIMITS.maximumActions; index += 1) actions.bindAction(`a${index}`, ['s/x']);+ assert.throws(() => actions.bindAction('extra', ['s/x']), /already has 128 actions/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 77e18347..80d48ff3 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -106,6 +106,7 @@ export default defineConfig({'texture-update': 'src/texture-update.js',cloth: 'src/cloth.js',runtime: 'src/runtime.js',+ input: 'src/input.js','update-part-vertices':'src/update-part-vertices.js','replace-textured-parts': 'src/replace-textured-parts.js',// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.