3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Draw a virtual touch stick under the finger on touch games (#2148)
Nguyen Xuan An3ca48f65304c
diff --git a/changes/2148.md b/changes/2148.mdnew file mode 100644index 00000000..5ebd59f7--- /dev/null+++ b/changes/2148.md@@ -0,0 +1 @@+- A touch game can draw its stick: `startGame` takes `touchControls`, and exported pages show a ring and knob under the finger on a phone (#2148)diff --git a/docs/game.md b/docs/game.mdindex 295ab17b..4082c8d3 100644--- a/docs/game.md+++ b/docs/game.md@@ -65,7 +65,7 @@ A player or NPC under a parent that rotates or scales is refused by `set-game` a`scene_export_web` writes one folder: `index.html`, `game.json` (the recipe) and `engine/` (the built Crucible modules, found by following the imports from `build/game.js`). It runs from any static host with no server code, and the folder is bounded: the engine stays under 12 MiB, the recipe under 1 MiB, and the newest four builds are kept. Placed catalog assets (and the assets whose clips a character retargets) are copied to `assets/<id>.glb`, up to 64 MiB together; grown vegetation is refused with the fix. The page shows the variables and the verdict in a corner label and exposes the running game as `window.__game` (`rules.state`, `controller.state`, `scene`, `runtime`).-`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins (each hidden by a rule) on a stone-pattern floor and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome, with a head-bob animation graph that the page must play. `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs puzzle` plays the [physics puzzle](#physics). `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs touch` exports the creature with `input: "touch"` and plays it in a Chrome context that emulates a phone (touch, mobile viewport) with real touch events: one finger drags the left-half stick up, a second finger taps to jump, and the game is won with no replay. It proves Chrome with touch emulation, not Safari or a real phone. `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera. The `character` sample walks a placed, retargeted humanoid (idle and walk clips of another file) to a goal, and checks that the page loads `assets/<id>.glb` and the character's limbs move. A game with a pattern or map material makes the export ship `engine/replace-textured-parts.js` and `startGame` load it; without it the first scene update and every hide or show fail with a replaceParts error, so the creature sample keeps a textured floor to catch that.+`index.html?replay=name.json` plays a recording (`recordInput`, see [input](input.md#custom-and-scripted-input)) from the same folder instead of the keyboard. `scripts/smoke-game-web.mjs` builds a creature that collects 3 coins (each hidden by a rule) on a stone-pattern floor and reaches a goal through the MCP tools, exports it, and wins it from a replay in headless Chrome, with a head-bob animation graph that the page must play. `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs puzzle` plays the [physics puzzle](#physics). `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs touch` exports the creature with `input: "touch"` and plays it in a Chrome context that emulates a phone (touch, mobile viewport) with real touch events: one finger drags the left-half stick up, a second finger taps to jump, and the game is won with no replay; while the first finger is down the smoke checks that the ring sits under it and the knob is cut back to the radius (`GAME_SMOKE_TOUCH_STILL=<png>` keeps that moment). It proves Chrome with touch emulation, not Safari or a real phone. `node scripts/smoke-game-web.mjs bin/crucible-mcp.mjs drive` does the same for a car that passes 3 gates and reaches a finish line under a `chase` camera. The `character` sample walks a placed, retargeted humanoid (idle and walk clips of another file) to a goal, and checks that the page loads `assets/<id>.glb` and the character's limbs move. A game with a pattern or map material makes the export ship `engine/replace-textured-parts.js` and `startGame` load it; without it the first scene update and every hide or show fail with a replaceParts error, so the creature sample keeps a textured floor to catch that.## From code@@ -75,6 +75,16 @@ const game = await startGame(canvas, recipe, { replay, showStatus: true });game.dispose();```+### Touch stick++A game with `input: "touch"` reads a stick in the left half of the canvas, but the area is invisible. Pass `touchControls: true` to `startGame` and the page draws it: a ring where the finger lands, a knob that follows the drag and stays inside the ring (the stick radius is 60 CSS pixels, so the ring is 120 px wide), and a fade-out of about a third of a second once the finger lifts. The drawing ignores touches, cannot be selected and keeps inside the safe area of a phone with a notch, so it never changes what the input sees. `touchControls` is off by default, is `false` for anything but an `input: "touch"` game without a replay, and must be a boolean. The page that `scene_export_web` writes turns it on when `matchMedia('(pointer: coarse)')` matches, so an exported touch game shows the stick on a phone and none on a desktop. There is no drawn action button: a tap on the right half still jumps.++```js+const game = await startGame(canvas, recipe, { touchControls: matchMedia('(pointer: coarse)').matches });+```++For your own page, `createTouchStickOverlay({ parent, source })` from `src/touch-stick-overlay.js` draws the sticks of any `touchSource(...)` (it reads `source.stickStates()`), and `createTouchStickModel` gives the ring and knob positions and opacity to draw them yourself.+The `scene` system sends each frame's poses through `scene.apply`, and sends only the poses that differ from the last frame it sent. A game standing still calls `scene.apply` zero times per frame.`startGame` loads the scene modules the recipe needs, builds the scene and renderer, and runs input, controller, camera rig and rules as [runtime](runtime.md) systems. A frame where a pose changed moves the node with `set-node`, so a large scene pays a scene update on those frames only. Not yet in the web build: sound and post effects.diff --git a/scripts/smoke-game-web.mjs b/scripts/smoke-game-web.mjsindex a80b8d8b..56828964 100644--- a/scripts/smoke-game-web.mjs+++ b/scripts/smoke-game-web.mjs@@ -272,6 +272,23 @@ function serveFolder(folder) {return new Promise(resolveListening => server.listen(0, '127.0.0.1', () => resolveListening(server)));}+// While the finger is down the page must draw the stick: a ring centred where the finger landed and a knob cut back to the stick radius+// (the finger is dragged 120 px up, the radius is 60). GAME_SMOKE_TOUCH_STILL names the PNG that keeps this moment.+async function expectStickUnderFinger(page, landed, dragged) {+ await page.waitForFunction(() => document.querySelector('[data-crucible-touch-stick]')?.children.length === 2, null, { timeout: 10000 });+ const drawn = await page.evaluate(() => {+ const [ring, knob] = document.querySelector('[data-crucible-touch-stick]').children;+ const centre = element => { const box = element.getBoundingClientRect(); return [box.left + box.width / 2, box.top + box.height / 2]; };+ return { ring: centre(ring), knob: centre(knob), opacity: Number(ring.style.opacity), ringWidth: ring.getBoundingClientRect().width };+ });+ assert.deepEqual(drawn.ring.map(Math.round), [landed.x, landed.y], 'the ring is under the finger that landed');+ assert.deepEqual(drawn.knob.map(Math.round), [dragged.x, landed.y - 60], 'the knob follows the drag, cut back to the radius');+ assert.equal(drawn.opacity, 1);+ assert.equal(drawn.ringWidth, 120);+ const stillPath = process.env.GAME_SMOKE_TOUCH_STILL;+ if (stillPath) await page.screenshot({ path: stillPath });+}+// Real touch events through the DevTools protocol: finger 1 presses in the left half and drags up past the stick radius (60 px),// and finger 2 taps in the right half while finger 1 stays down (touchEnd lists the points that lift), which the touch preset reads as a jump.async function holdStickUpAndTapToJump(page) {@@ -292,6 +309,7 @@ async function holdStickUpAndTapToJump(page) {await dispatch('touchStart', [stickStart]);await dispatch('touchMove', [stickHeld]);await page.waitForTimeout(500);+ await expectStickUnderFinger(page, stickStart, stickHeld);await Promise.all([dispatch('touchStart', [stickHeld, tapPoint]), dispatch('touchEnd', [tapPoint])]);await page.waitForFunction(() => window.__peakHeight > 0.05, null, { timeout: 10000 });await page.waitForFunction(() => window.__game.controller.state.position[2] < -0.2, null, { timeout: 30000 });diff --git a/scripts/web-export.mjs b/scripts/web-export.mjsindex 79460671..3fd060c0 100644--- a/scripts/web-export.mjs+++ b/scripts/web-export.mjs@@ -85,7 +85,8 @@ const recipe = await (await fetch('./game.json')).json();const replayName = new URLSearchParams(location.search).get('replay');const replay = /^[\\w.-]+\\.json$/.test(replayName ?? '') ? await (await fetch('./' + replayName)).json() : undefined;const assetUrls = ${JSON.stringify(assetUrls)};-${physicsUrl ? `const physicsUrl = ${JSON.stringify(physicsUrl)};\n` : ''}window.__game = await startGame(canvas, recipe, { replay, assetUrls${physicsUrl ? ', physicsUrl' : ''} });+${physicsUrl ? `const physicsUrl = ${JSON.stringify(physicsUrl)};\n` : ''}const touchControls = matchMedia('(pointer: coarse)').matches;+window.__game = await startGame(canvas, recipe, { replay, touchControls, assetUrls${physicsUrl ? ', physicsUrl' : ''} });</script></body></html>diff --git a/src/game.js b/src/game.jsindex 483c1412..1f608ed9 100644--- a/src/game.js+++ b/src/game.js@@ -6,6 +6,7 @@ import { groundBounceEnvironment } from './ground-bounce.js';import { createRuntime } from './runtime.js';import { createInput, gamepadSource, keyboardSource } from './input.js';import { replaySource, touchSource } from './input-sources.js';+import { createTouchStickOverlay } from './touch-stick-overlay.js';import { createCharacterController, createChaseCamera, createController, createCameraRigOfKind, createFirstPersonCamera, createFollowCamera, createTopDownCamera, createVehicleController } from './player.js';import { createGameRules } from './game-rules.js';import { hasTexturedMaterial, parentTranslation } from './game-needs.js';@@ -40,13 +41,20 @@ export function inputDefinition(preset) {return { actions, axes };}-function inputSources(preset, canvas) {+function inputSources(preset, touch) {const sources = [keyboardSource()];if (preset === 'gamepad') sources.push(gamepadSource());- if (preset === 'touch') sources.push(touchSource({ target: canvas, sticks: [MOVE_STICK] }));+ if (touch) sources.push(touch);return sources;}+function requireTouchControls(value) {+ if (typeof value !== 'boolean') {+ throw new TypeError(`startGame option touchControls must be true or false, got ${value === null ? 'null' : typeof value}. Pass true to draw the touch stick on a game with input "touch".`);+ }+ return value;+}+function cameraRigFor(kind, controller, input) {const rigOptions = { subject: controller.state, input };if (kind === 'first-person') return createFirstPersonCamera(rigOptions);@@ -141,7 +149,7 @@ async function loadAnimationRuntime() {/*** Start the game a recipe describes on a canvas and return its parts: `scene`, `runtime`, `rules`, `input`, `controller`, `renderer`,- * `restart()` (puts the player, camera, NPCs, animation graphs, physics bodies and rules back at the start; returns a promise that settles once the physics world is rebuilt) and `dispose()`. Options: `replay` (a recording from recordInput; the keyboard is not attached) `showStatus` (default true) `assets` (decoded catalog assets by assetCopyKey) or `assetUrls` (asset id to GLB URL, which startGame fetches and decodes), `physicsUrl` (where the page keeps jolt-physics.wasm.js, on its own origin; a recipe with game.physics true needs it unless the jolt-physics package resolves) and `createRenderer` (tests pass a stand-in for the WebGL renderer).+ * `restart()` (puts the player, camera, NPCs, animation graphs, physics bodies and rules back at the start; returns a promise that settles once the physics world is rebuilt) and `dispose()`. Options: `replay` (a recording from recordInput; the keyboard is not attached) `showStatus` (default true) `touchControls` (default false; true draws a virtual stick under the finger on a game with `input: "touch"`) `assets` (decoded catalog assets by assetCopyKey) or `assetUrls` (asset id to GLB URL, which startGame fetches and decodes), `physicsUrl` (where the page keeps jolt-physics.wasm.js, on its own origin; a recipe with game.physics true needs it unless the jolt-physics package resolves) and `createRenderer` (tests pass a stand-in for the WebGL renderer).*/export async function startGame(canvas, recipe, options = {}) {const cleanups = [];@@ -203,7 +211,7 @@ export function operationsToSend(operations, lastSentOperations) {return candidates.filter(operation => changedTargets.has(operationTarget(operation)));}-async function buildGame(canvas, recipe, { replay, showStatus = true, assets: providedAssets, assetUrls, physicsUrl, createRenderer = (...rendererArguments) => new CrucibleRenderer(...rendererArguments) }, cleanups) {+async function buildGame(canvas, recipe, { replay, showStatus = true, touchControls = false, assets: providedAssets, assetUrls, physicsUrl, createRenderer = (...rendererArguments) => new CrucibleRenderer(...rendererArguments) }, cleanups) {const setup = recipe.game;if (!setup) throw new Error('startGame needs a recipe with a game section. Add one with the set-game operation.');// Live physics replaces the recorded bake of the same section, so the scene is built without it.@@ -227,7 +235,13 @@ async function buildGame(canvas, recipe, { replay, showStatus = true, assets: prcleanups.push(() => renderer.dispose());const { actions, axes } = inputDefinition(game.input);- const input = createInput({ sources: replay ? [replaySource(replay)] : inputSources(game.input, canvas), actions, axes });+ const drawTouchStick = requireTouchControls(touchControls) && game.input === 'touch' && !replay;+ const touch = game.input === 'touch' && !replay ? touchSource({ target: canvas, sticks: [MOVE_STICK] }) : null;+ const input = createInput({ sources: replay ? [replaySource(replay)] : inputSources(game.input, touch), actions, axes });+ if (drawTouchStick) {+ const stickOverlay = createTouchStickOverlay({ parent: canvas.parentNode, source: touch });+ cleanups.push(() => stickOverlay.dispose());+ }const footOffset = game.player.footOffset;const start = nodeTranslation(recipe.nodes, game.player.node);const playerParentOffset = parentTranslation(recipe.nodes, game.player.node, 'game.player.node');diff --git a/src/input-sources.js b/src/input-sources.jsindex 413a78cd..1934f4e0 100644--- a/src/input-sources.js+++ b/src/input-sources.js@@ -122,7 +122,7 @@ export function touchSource(options = {}) {if (event.pointerType !== 'touch') return;const stick = findFreeStick(event.clientX, event.clientY);if (stick) {- stickTouches.set(event.pointerId, { stick, originX: event.clientX, originY: event.clientY });+ stickTouches.set(event.pointerId, { stick, originX: event.clientX, originY: event.clientY, dragX: 0, dragY: 0 });emit(`${stick.name}Active`, 1);return;}@@ -138,6 +138,8 @@ export function touchSource(options = {}) {function handlePointerMove(emit, event) {const stickTouch = stickTouches.get(event.pointerId);if (stickTouch) {+ stickTouch.dragX = event.clientX - stickTouch.originX;+ stickTouch.dragY = event.clientY - stickTouch.originY;emit(`${stickTouch.stick.name}X`, clampUnit((event.clientX - stickTouch.originX) / stickTouch.stick.radius));emit(`${stickTouch.stick.name}Y`, clampUnit((event.clientY - stickTouch.originY) / stickTouch.stick.radius));return;@@ -186,6 +188,10 @@ export function touchSource(options = {}) {for (const type of eventTypes) target.addEventListener(type, handlers[type]);blurTarget.addEventListener?.('blur', handlers.blur);},+ // Where each held stick sits, for a drawn overlay: client pixels of the touch-down point, the raw drag from it and the stick radius.+ stickStates() {+ return [...stickTouches.values()].map(({ stick, originX, originY, dragX, dragY }) => ({ name: stick.name, originX, originY, dragX, dragY, radius: stick.radius }));+ },endSample(emit) {for (const name of pulses) emit(name, 0);pulses = new Set();diff --git a/src/touch-stick-overlay.js b/src/touch-stick-overlay.jsnew file mode 100644index 00000000..f83eb369--- /dev/null+++ b/src/touch-stick-overlay.js@@ -0,0 +1,166 @@+// A drawn virtual stick for a touch game: a ring where the finger landed and a knob that follows the drag, fading out once the finger lifts.+// The drawing only reads `touchSource(...).stickStates()`; it never listens to touches, so it cannot change what the input source sees.+// docs/game.md shows how a game turns it on.++export const TOUCH_STICK_DEFAULT_FADE_MILLISECONDS = 350;+const MAXIMUM_FADE_MILLISECONDS = 5000;+const KNOB_DIAMETER_OVER_RING_DIAMETER = 0.42;++function describe(value) {+ return value === null ? 'null' : typeof value;+}++/** The knob's distance from the ring centre: the drag, cut back to `radius` when it is longer. Returns { x, y } in pixels. */+export function clampKnobOffset(dragX, dragY, radius) {+ if (![dragX, dragY].every(Number.isFinite)) {+ throw new TypeError(`clampKnobOffset needs finite dragX and dragY in pixels, got ${String(dragX)} and ${String(dragY)}.`);+ }+ if (!Number.isFinite(radius) || radius <= 0) {+ throw new RangeError(`clampKnobOffset radius must be a number above 0, got ${String(radius)}.`);+ }+ const length = Math.hypot(dragX, dragY);+ if (length <= radius) return { x: dragX, y: dragY };+ const scale = radius / length;+ return { x: dragX * scale, y: dragY * scale };+}++/** 1 while the finger is down, then a straight fall to 0 over `fadeMilliseconds` after it lifts. */+export function stickOpacity(held, millisecondsSinceRelease, fadeMilliseconds) {+ if (held) return 1;+ return Math.max(0, Math.min(1, 1 - millisecondsSinceRelease / fadeMilliseconds));+}++function requireFadeMilliseconds(value) {+ if (!Number.isFinite(value) || value <= 0 || value > MAXIMUM_FADE_MILLISECONDS) {+ throw new RangeError(`touch stick fadeMilliseconds must be a number from above 0 to ${MAXIMUM_FADE_MILLISECONDS}, got ${String(value)}.`);+ }+ return value;+}++/**+ * The state behind the drawing: feed it the stick states and the time, read what to draw. A stick that was let go keeps its last+ * place while it fades, so the ring does not jump when the finger lifts.+ */+export function createTouchStickModel({ fadeMilliseconds = TOUCH_STICK_DEFAULT_FADE_MILLISECONDS } = {}) {+ const fade = requireFadeMilliseconds(fadeMilliseconds);+ const lastPlaces = new Map(); // stick name -> { centerX, centerY, knobX, knobY, radius, releasedAt }+ return {+ update(stickStates, nowMilliseconds) {+ if (!Array.isArray(stickStates)) {+ throw new TypeError(`touch stick model update needs the array from touchSource(...).stickStates(), got ${describe(stickStates)}.`);+ }+ const heldNames = new Set();+ for (const { name, originX, originY, dragX, dragY, radius } of stickStates) {+ const offset = clampKnobOffset(dragX, dragY, radius);+ heldNames.add(name);+ lastPlaces.set(name, { centerX: originX, centerY: originY, knobX: originX + offset.x, knobY: originY + offset.y, radius, releasedAt: null });+ }+ const visuals = [];+ for (const [name, place] of lastPlaces) {+ if (!heldNames.has(name) && place.releasedAt === null) place.releasedAt = nowMilliseconds;+ const held = heldNames.has(name);+ const opacity = stickOpacity(held, held ? 0 : nowMilliseconds - place.releasedAt, fade);+ if (opacity === 0) {+ lastPlaces.delete(name);+ continue;+ }+ visuals.push({ name, held, opacity, centerX: place.centerX, centerY: place.centerY, knobX: place.knobX, knobY: place.knobY, radius: place.radius });+ }+ return visuals;+ },+ };+}++const CONTAINER_STYLE = [+ 'position:fixed',+ 'top:env(safe-area-inset-top,0px)',+ 'right:env(safe-area-inset-right,0px)',+ 'bottom:env(safe-area-inset-bottom,0px)',+ 'left:env(safe-area-inset-left,0px)',+ 'pointer-events:none',+ 'user-select:none',+ '-webkit-user-select:none',+ 'touch-action:none',+ 'overflow:hidden',+].join(';');++function circleStyle(diameter, extra) {+ return `position:absolute;left:0;top:0;width:${diameter}px;height:${diameter}px;margin:${-diameter / 2}px 0 0 ${-diameter / 2}px;border-radius:50%;box-sizing:border-box;pointer-events:none;will-change:transform,opacity;${extra}`;+}++/**+ * Draw the sticks of a touch source over a page. `parent` is the element the overlay is added to (the canvas's parent), `source` the+ * object from touchSource, and the sizes follow each stick's radius in CSS pixels. The overlay ignores touches (pointer-events none),+ * cannot be selected, and keeps inside the safe area of a phone with a notch. Returns { dispose() }.+ */+export function createTouchStickOverlay({ parent, source, fadeMilliseconds = TOUCH_STICK_DEFAULT_FADE_MILLISECONDS, requestFrame, cancelFrame, now } = {}) {+ if (!parent || typeof parent.appendChild !== 'function' || !parent.ownerDocument?.createElement) {+ throw new TypeError(`createTouchStickOverlay needs parent, a page element to draw into such as canvas.parentNode, got ${describe(parent)}.`);+ }+ if (!source || typeof source.stickStates !== 'function') {+ throw new TypeError('createTouchStickOverlay needs source, the object from touchSource(...), which has stickStates().');+ }+ const model = createTouchStickModel({ fadeMilliseconds });+ const schedule = requestFrame ?? globalThis.requestAnimationFrame?.bind(globalThis);+ const cancel = cancelFrame ?? globalThis.cancelAnimationFrame?.bind(globalThis);+ const clock = now ?? (() => globalThis.performance.now());+ if (typeof schedule !== 'function' || typeof cancel !== 'function') {+ throw new TypeError('createTouchStickOverlay needs requestFrame and cancelFrame (such as requestAnimationFrame) in a page without them.');+ }+ const documentOwner = parent.ownerDocument;+ const container = documentOwner.createElement('div');+ container.setAttribute('aria-hidden', 'true');+ container.setAttribute('data-crucible-touch-stick', '');+ container.style.cssText = CONTAINER_STYLE;+ parent.appendChild(container);+ const drawn = new Map(); // stick name -> { ring, knob }++ function elementsFor(name, radius) {+ if (drawn.has(name)) return drawn.get(name);+ const ring = documentOwner.createElement('div');+ ring.style.cssText = circleStyle(radius * 2, 'border:3px solid rgba(255,255,255,.85);background:rgba(255,255,255,.18);box-shadow:0 0 0 1px rgba(0,0,0,.45),inset 0 0 0 1px rgba(0,0,0,.25)');+ const knob = documentOwner.createElement('div');+ knob.style.cssText = circleStyle(radius * 2 * KNOB_DIAMETER_OVER_RING_DIAMETER, 'background:rgba(255,255,255,.92);box-shadow:0 0 0 1px rgba(0,0,0,.5),0 2px 6px rgba(0,0,0,.45)');+ container.appendChild(ring);+ container.appendChild(knob);+ const elements = { ring, knob };+ drawn.set(name, elements);+ return elements;+ }++ function draw(visuals) {+ const bounds = container.getBoundingClientRect?.() ?? { left: 0, top: 0 };+ const visibleNames = new Set();+ for (const visual of visuals) {+ visibleNames.add(visual.name);+ const { ring, knob } = elementsFor(visual.name, visual.radius);+ ring.style.opacity = String(visual.opacity);+ knob.style.opacity = String(visual.opacity);+ ring.style.transform = `translate(${visual.centerX - bounds.left}px,${visual.centerY - bounds.top}px)`;+ knob.style.transform = `translate(${visual.knobX - bounds.left}px,${visual.knobY - bounds.top}px)`;+ }+ for (const [name, { ring, knob }] of drawn) {+ if (visibleNames.has(name)) continue;+ ring.style.opacity = '0';+ knob.style.opacity = '0';+ }+ }++ let frameHandle = null;+ let disposed = false;+ function tick() {+ if (disposed) return;+ draw(model.update(source.stickStates(), clock()));+ frameHandle = schedule(tick);+ }+ frameHandle = schedule(tick);++ return {+ dispose() {+ if (disposed) return;+ disposed = true;+ if (frameHandle !== null) cancel(frameHandle);+ container.remove();+ },+ };+}diff --git a/tests/game-physics.test.js b/tests/game-physics.test.jsindex 30d00ba8..5473b623 100644--- a/tests/game-physics.test.js+++ b/tests/game-physics.test.js@@ -244,7 +244,8 @@ test('the web export bundles the physics engine and its wasm beside the page onlassert.ok(summary.bytes > 1024 * 1024 && summary.bytes < WEB_EXPORT_LIMITS.maxEngineBytes, `physics export bytes ${summary.bytes}`);const html = await (await import('node:fs/promises')).readFile(join(withPhysics, 'index.html'), 'utf8');assert.match(html, /const physicsUrl = "\.\/engine\/physics\/jolt-physics\.wasm\.js";/);- assert.match(html, /startGame\(canvas, recipe, \{ replay, assetUrls, physicsUrl \}\)/);+ assert.ok(html.includes('startGame(canvas, recipe, { replay, touchControls, assetUrls, physicsUrl })'));+ assert.ok(html.includes("const touchControls = matchMedia('(pointer: coarse)').matches;"));assert.doesNotMatch(html, /https?:\/\//);assert.doesNotMatch(indexHtml('plain'), /physicsUrl/);});diff --git a/tests/game-restart.test.js b/tests/game-restart.test.jsindex b08945bd..60911c57 100644--- a/tests/game-restart.test.js+++ b/tests/game-restart.test.js@@ -298,3 +298,37 @@ test('R and a tap do nothing while the game is playing, on a held key, on anotherestore();}});++test('touchControls draws the stick over a touch game only when asked, and removes it on dispose', async () => {+ const restore = withAnimationFrameStubs();+ const previous = { document: globalThis.document, add: globalThis.addEventListener, remove: globalThis.removeEventListener };+ globalThis.addEventListener = () => {};+ globalThis.removeEventListener = () => {};+ const documentOwner = { addEventListener() {}, removeEventListener() {}, createElement: () => fakeStickElement() };+ function fakeStickElement() {+ const element = { ownerDocument: documentOwner, style: {}, children: [], removed: false, setAttribute() {}, appendChild: child => element.children.push(child), remove() { element.removed = true; }, getBoundingClientRect: () => ({ left: 0, top: 0 }) };+ return element;+ }+ globalThis.document = documentOwner;+ const parent = fakeStickElement();+ const canvas = { parentNode: parent, addEventListener() {}, removeEventListener() {} };+ const touchRecipe = playerRecipe({ rules: [] });+ touchRecipe.game.input = 'touch';+ try {+ const plain = await startGame(canvas, touchRecipe, { showStatus: false, createRenderer: () => standInRenderer() });+ assert.equal(parent.children.length, 0, 'off by default');+ plain.dispose();+ const drawn = await startGame(canvas, touchRecipe, { showStatus: false, touchControls: true, createRenderer: () => standInRenderer() });+ assert.equal(parent.children.length, 1, 'one overlay container');+ drawn.dispose();+ assert.equal(parent.children[0].removed, true);+ const keyboardRecipe = playerRecipe({ rules: [] });+ const keyboard = await startGame(canvas, keyboardRecipe, { showStatus: false, touchControls: true, createRenderer: () => standInRenderer() });+ assert.equal(parent.children.length, 1, 'a keyboard game draws no stick');+ keyboard.dispose();+ await assert.rejects(startGame(canvas, touchRecipe, { showStatus: false, touchControls: 'yes', createRenderer: () => standInRenderer() }), /touchControls must be true or false, got string/);+ } finally {+ Object.assign(globalThis, { document: previous.document, addEventListener: previous.add, removeEventListener: previous.remove });+ restore();+ }+});diff --git a/tests/touch-stick-overlay.test.js b/tests/touch-stick-overlay.test.jsnew file mode 100644index 00000000..4036dae7--- /dev/null+++ b/tests/touch-stick-overlay.test.js@@ -0,0 +1,120 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { touchSource } from '../src/input-sources.js';+import { clampKnobOffset, createTouchStickModel, createTouchStickOverlay, stickOpacity } from '../src/touch-stick-overlay.js';++function fakeElement(documentOwner) {+ const element = {+ ownerDocument: documentOwner,+ style: {},+ children: [],+ attributes: {},+ removed: false,+ setAttribute(name, value) { element.attributes[name] = value; },+ appendChild(child) { element.children.push(child); return child; },+ remove() { element.removed = true; },+ getBoundingClientRect() { return { left: 0, top: 0 }; },+ };+ return element;+}++function fakePage() {+ const documentOwner = { createElement: () => fakeElement(documentOwner) };+ return fakeElement(documentOwner);+}++function fakeTouchTarget() {+ const listeners = new Map();+ return {+ innerWidth: 400,+ innerHeight: 800,+ addEventListener(type, handler) { listeners.set(type, handler); },+ removeEventListener(type) { listeners.delete(type); },+ dispatch(type, event) { listeners.get(type)(event); },+ };+}++test('the knob follows the drag and is cut back to the stick radius', () => {+ assert.deepEqual(clampKnobOffset(30, -40, 60), { x: 30, y: -40 });+ const far = clampKnobOffset(300, 400, 60);+ assert.ok(Math.abs(far.x - 36) < 1e-9 && Math.abs(far.y - 48) < 1e-9, `got ${JSON.stringify(far)}`);+ assert.equal(Math.hypot(far.x, far.y).toFixed(6), '60.000000');+ assert.throws(() => clampKnobOffset(Number.NaN, 0, 60), /finite dragX and dragY/);+ assert.throws(() => clampKnobOffset(1, 1, 0), /radius must be a number above 0/);+});++test('the stick is solid while held and fades to nothing after release', () => {+ assert.equal(stickOpacity(true, 0, 350), 1);+ assert.equal(stickOpacity(false, 0, 350), 1);+ assert.equal(stickOpacity(false, 175, 350), 0.5);+ assert.equal(stickOpacity(false, 350, 350), 0);+ assert.equal(stickOpacity(false, 9000, 350), 0);+});++test('the model keeps the last place while fading, then forgets it', () => {+ const model = createTouchStickModel({ fadeMilliseconds: 400 });+ const held = [{ name: 'touch/move', originX: 100, originY: 500, dragX: 0, dragY: -200, radius: 60 }];+ const [whileHeld] = model.update(held, 1000);+ assert.deepEqual([whileHeld.centerX, whileHeld.centerY, whileHeld.knobX, whileHeld.knobY, whileHeld.opacity], [100, 500, 100, 440, 1]);+ const [justReleased] = model.update([], 2000);+ assert.deepEqual([justReleased.knobY, justReleased.opacity], [440, 1]);+ const [halfway] = model.update([], 2200);+ assert.equal(halfway.opacity, 0.5);+ assert.deepEqual(model.update([], 2400), []);+ assert.deepEqual(model.update([], 5000), []);+ assert.throws(() => model.update(null, 0), /stickStates/);+ assert.throws(() => createTouchStickModel({ fadeMilliseconds: 0 }), /fadeMilliseconds/);+});++test('touchSource reports the held stick for the drawing', () => {+ const target = fakeTouchTarget();+ const source = touchSource({ target, blurTarget: fakeTouchTarget(), sticks: [{ name: 'move', area: { x: 0, y: 0, width: 0.5, height: 1 }, radius: 60 }] });+ source.attach(() => {});+ assert.deepEqual(source.stickStates(), []);+ target.dispatch('pointerdown', { pointerType: 'touch', pointerId: 1, clientX: 80, clientY: 600, timeStamp: 0 });+ target.dispatch('pointermove', { pointerType: 'touch', pointerId: 1, clientX: 80, clientY: 400, timeStamp: 10 });+ assert.deepEqual(source.stickStates(), [{ name: 'move', originX: 80, originY: 600, dragX: 0, dragY: -200, radius: 60 }]);+ target.dispatch('pointerup', { pointerType: 'touch', pointerId: 1, clientX: 80, clientY: 400, timeStamp: 20 });+ assert.deepEqual(source.stickStates(), []);+});++test('the overlay draws a ring and a knob that ignore touches, then removes itself', () => {+ const page = fakePage();+ let states = [{ name: 'move', originX: 100, originY: 500, dragX: 0, dragY: -200, radius: 60 }];+ let pendingFrame = null;+ let time = 0;+ const overlay = createTouchStickOverlay({+ parent: page,+ source: { stickStates: () => states },+ fadeMilliseconds: 400,+ requestFrame: callback => { pendingFrame = callback; return 7; },+ cancelFrame: handle => { assert.equal(handle, 7); pendingFrame = null; },+ now: () => time,+ });+ const [container] = page.children;+ assert.match(container.style.cssText, /pointer-events:none/);+ assert.match(container.style.cssText, /user-select:none/);+ assert.match(container.style.cssText, /touch-action:none/);+ assert.match(container.style.cssText, /env\(safe-area-inset-top/);+ pendingFrame();+ const [ring, knob] = container.children;+ assert.equal(ring.style.transform, 'translate(100px,500px)');+ assert.equal(knob.style.transform, 'translate(100px,440px)');+ assert.equal(ring.style.opacity, '1');+ assert.match(ring.style.cssText, /width:120px/);+ states = [];+ time = 200;+ pendingFrame();+ time = 600;+ pendingFrame();+ assert.equal(ring.style.opacity, '0');+ assert.equal(knob.style.opacity, '0');+ overlay.dispose();+ assert.equal(container.removed, true);+ assert.equal(pendingFrame, null);+});++test('the overlay names what to pass when its inputs are wrong', () => {+ assert.throws(() => createTouchStickOverlay({ source: { stickStates: () => [] } }), /needs parent/);+ assert.throws(() => createTouchStickOverlay({ parent: fakePage(), source: {} }), /stickStates\(\)/);+});