@pixel-studio/core 0.2.0-alpha.2 → 0.2.0-alpha.3

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/README.md CHANGED
@@ -21,7 +21,7 @@ Docs and live demos: **[pixel-studio.sh](https://pixel-studio.sh)**.
21
21
 
22
22
  > **Status: alpha.** The engine, CLI and web components work and are tested, and every page of pixel-studio.sh runs
23
23
  > on them. The spec and bundle formats may still change before 1.0; each change is listed in the
24
- > [changelog](../../CHANGELOG.md).
24
+ > [changelog](https://pixel-studio.sh/changelog/).
25
25
 
26
26
  ## Five minutes to a goose on your page
27
27
 
@@ -89,6 +89,7 @@ Start with [docs/getting-started.md](docs/getting-started.md), or read everythin
89
89
  | [docs/figures.md](docs/figures.md) | Figures, motion models, follow-through, writing a new figure. |
90
90
  | [docs/runtime.md](docs/runtime.md) | `<pixel-sprite>`, the bundle format, events, attachment points, state machines, skins, moving sprites on a page. |
91
91
  | [docs/stage.md](docs/stage.md) | `<pixel-stage>`: characters that walk, jump, climb, sit and hide on a real page. |
92
+ | [docs/performance.md](docs/performance.md) | What characters cost a page: sizes, load impact, time per frame, memory, measured. |
92
93
  | [docs/cli.md](docs/cli.md) | Every CLI command and flag. |
93
94
  | [docs/api.md](docs/api.md) | The JavaScript API. |
94
95
  | [docs/playground.md](docs/playground.md) | The playground page: a character set up entirely by its URL, for people and browser agents. |
package/bin/pixel.mjs CHANGED
@@ -10,8 +10,10 @@
10
10
  // sprite sheet PNG + JSON metadata
11
11
  // pixel export <spec.json> [--res 32] [--out dir] [--format aseprite]
12
12
  // sheet PNG + Aseprite JSON (Phaser, PixiJS)
13
- // pixel bundle <spec.json> [--res 16,32,64] [--views front,back|none] [--external] [--out file.bundle.json]
14
- // self-contained web bundle for <pixel-sprite> (all skins);
13
+ // pixel bundle <spec.json> [--res 16,32,64] [--views front,back|all] [--anims idle,walk|stage] [--external]
14
+ // [--out file.bundle.json] self-contained web bundle for <pixel-sprite> (all skins);
15
+ // side view only unless --views; --anims keeps only those
16
+ // animations (stage: what <pixel-stage> uses);
15
17
  // --external writes the sheets as PNG files beside it
16
18
  // pixel resolve <variant.json> [--out full.json] print a variant ("extends") merged with its base
17
19
  // pixel where <spec.json> [--anim a] [--frame f] [--part id --point x,y]
@@ -246,9 +248,20 @@ switch (cmd) {
246
248
  }
247
249
  case 'bundle': {
248
250
  const c = compileOrExit(await loadSpec(args._[0]));
249
- // --views front | front,back | none: which extra views (front, back, …) to ship; default all.
250
- const views = args.views == null ? undefined : String(args.views) === 'none' ? [] : String(args.views).split(',').map((s) => s.trim()).filter(Boolean);
251
- const bundle = await buildBundle(c, { resolutions: resList(args.res, '16,32,64'), overrides: overridesFrom(args), encode: pngDataURL, views });
251
+ // --views front | front,back | all | none: which extra views (front, back, …) to ship; default none (the side
252
+ // view only): they are for <pixel-stage> turning a character to the reader, and each about doubles the sheets.
253
+ const has = [...new Set(Object.keys(c.animations).filter((n) => n.startsWith('turn@')).map((n) => n.slice(5)))];
254
+ if (args.views === true) fail('--views needs a value: front, back, all or none');
255
+ const asked = args.views == null ? 'none' : String(args.views).trim();
256
+ const views = asked === 'all' ? undefined : asked === 'none' ? [] : asked.split(',').map((s) => s.trim()).filter(Boolean);
257
+ for (const v of views ?? []) if (!has.includes(v)) fail(`--views: no view "${v}" (${has.length ? `views: ${has.join(', ')}, all or none` : 'this character has only the side view'})`);
258
+ if (args.views == null && has.length) console.error(`note: side view only; --views all (or ${has.join(', ')}) adds the character's other views`);
259
+ // --anims idle,waddle | stage: only those animations, with their views, turns and transitions.
260
+ if (args.anims === true) fail('--anims needs a list, e.g. --anims idle,walk (or --anims stage)');
261
+ const animations = args.anims == null ? undefined : String(args.anims).split(',').map((s) => s.trim()).filter(Boolean);
262
+ const bundle = await buildBundle(c, { resolutions: resList(args.res, '16,32,64'), overrides: overridesFrom(args), encode: pngDataURL, views, animations });
263
+ const dropped = Object.keys(c.states?.nodes ?? {}).filter((n) => !bundle.states?.nodes[n]);
264
+ if (dropped.length) console.error(`note: states: ${bundle.states ? `dropped node${dropped.length > 1 ? 's' : ''} ${dropped.join(', ')} (no animation left to play)` : 'dropped the state machine (no node has an animation left)'}`);
252
265
  const out = args.out || `${stem(args._[0])}.bundle.json`;
253
266
  mkdirSync(dirname(resolve(out)), { recursive: true });
254
267
  // --external: sheets as PNG files next to the bundle, so a page downloads only the one it shows.
package/docs/README.md CHANGED
@@ -8,6 +8,7 @@
8
8
  | make characters move realistically | [figures.md](figures.md): figure library, motion models, follow-through, writing a figure |
9
9
  | put a character on a web page | [runtime.md](runtime.md): `<pixel-sprite>`, bundles, events, attachment points, state machines, skins, moving sprites at the right speed |
10
10
  | let characters walk, climb and hide on a page | [stage.md](stage.md): `<pixel-stage>` and the `data-pixel-*` attributes |
11
+ | know what characters cost a page | [performance.md](performance.md): download sizes, load impact, time per frame, memory, and how to keep them small |
11
12
  | use characters in a game engine | [cli.md](cli.md#export): `pixel export` writes Aseprite-format JSON that Phaser and PixiJS load |
12
13
  | use the command line | [cli.md](cli.md): every `pixel` command and flag |
13
14
  | call the engine from JavaScript | [api.md](api.md): every export, data shapes, examples |
package/docs/SPEC.md CHANGED
@@ -351,6 +351,8 @@ A side-view character can also be drawn from other angles. Each view dresses its
351
351
  - The view's animations are named `<animation>@<view>` (`idle@front`); name them like the side ones. No
352
352
  `animations` gives every motion of the view's figure. `turn@front` and `unturn@front` (side ↔ view) are generated.
353
353
  - `look` (optional) puts the view's head on the side body: `look@front`, a three-quarter glance.
354
+ - `pixel bundle` ships the side view only; `--views all` (or `--views front`) keeps the views, for a `<pixel-stage>`
355
+ character that turns to the reader.
354
356
  - For a back view, dress `goose-front` the other way round. Variants patch views like the main spec (`"back": null`
355
357
  drops one). `examples/goose-base.json` has front and back. Details: [figures.md](figures.md#views-the-same-character-from-other-angles).
356
358
 
@@ -455,7 +457,7 @@ node bin/pixel.mjs preview spec.json --res 32 --cell 384 --out face.png # zoom
455
457
  node bin/pixel.mjs ascii spec.json --res 24 --anim idle --frame 0 # text view if you can't see images
456
458
  node bin/pixel.mjs where spec.json --anim hack --frame 0 # world positions of pivots (pick reach targets)
457
459
  node bin/pixel.mjs resolve variant.json # a variant merged with its base
458
- node bin/pixel.mjs bundle spec.json --out site/hero.bundle.json # ship it
460
+ node bin/pixel.mjs bundle spec.json --out site/hero.bundle.json # ship it (side view; --views all, --anims idle,walk)
459
461
  ```
460
462
 
461
463
  Iterate: draw → preview → critique silhouette, proportions, contrast, motion → adjust → preview again.
package/docs/api.md CHANGED
@@ -1550,7 +1550,7 @@ The value of `format` in every bundle `buildBundle` produces.
1550
1550
  ### `buildBundle`
1551
1551
 
1552
1552
  ```ts
1553
- buildBundle(compiled: CompiledSpec, options: { resolutions?, overrides?, encode, views?, deltas? }): Promise<Bundle>
1553
+ buildBundle(compiled: CompiledSpec, options: { resolutions?, overrides?, encode, views?, animations?, deltas? }): Promise<Bundle>
1554
1554
  ```
1555
1555
 
1556
1556
  Renders one sprite sheet per resolution (and per resolution again for each skin in
@@ -1565,12 +1565,19 @@ described in [runtime.md](runtime.md).
1565
1565
  | `options.resolutions` | number[] | `[16, 32, 64]` | Sheet heights in pixels. Rendered and listed in ascending order. Duplicates are not removed. |
1566
1566
  | `options.overrides` | object | `{}` | Passed to `resolveStyle` for every resolution. |
1567
1567
  | `options.encode` | `(w, h, rgba) => string \| Promise<string>` | required | Turns a sheet into the `image` string: a PNG data URL, or a URL if you store sheets as separate files. Awaited. [`pngBytes`](#pngbytes) makes small (indexed) PNGs in any host. |
1568
- | `options.views` | string[] \| false | all | Which extra views to ship (`["front"]`); `[]` or `false` leaves only the main (side) view. Their animations (`idle@back`, `turn@back`, …) are dropped before rendering. Each view adds about a full set of animations to the sheets. |
1568
+ | `options.views` | string[] \| false | all | Which extra views to ship (`["front"]`); `[]` or `false` leaves only the main (side) view. Their animations (`idle@back`, `turn@back`, …) are dropped before rendering. Each view adds about a full set of animations to the sheets. (`pixel bundle` defaults to the side view only; this default is every view.) |
1569
+ | `options.animations` | string[] | all | Only these animations (`["idle", "waddle", "honk"]`), plus what they need: their views (`idle@front`, if that view is shipped), the `turn@`, `unturn@` and `look@` clips of each view that keeps an animation, and the transition clips between two kept animations (`waddle>idle`). `"stage"` stands for what `<pixel-stage>` plays: for each role the first animation the character has. Dropped before rendering, like views. |
1569
1570
  | `options.deltas` | boolean | `true` | Store a skin as a change to the default sheet (`recolor`, `overlay`) when that is smaller than its own sheet. See [Bundle](#bundle). |
1570
1571
 
1571
1572
  **Returns** a promise of a bundle. `animations` comes from the smallest resolution's sheet meta. `skins`, `states` and `points` are present only when the compiled spec has them. `skinPoints` holds the baked points of each skin whose table differs from the default one (a skin that moves the parts points ride on); it is absent when no skin does.
1572
1573
 
1574
+ A `states` node whose animation is not in the bundle (left out by `animations` or `views`) is dropped with the
1575
+ transitions to it, its entries in other transitions' `from` and the `random` fidgets that play a missing animation; a
1576
+ `then` that pointed to a dropped node becomes `"previous"`, a dropped `initial` the first node left, and with no node
1577
+ left the bundle has no `states`.
1578
+
1573
1579
  **Errors**: a missing `encode` rejects immediately with `buildBundle needs an encode(w, h, rgba) function ...`.
1580
+ An `animations` name the character does not have rejects with `no animation "quack" in <name> (have: idle, walk, …)`.
1574
1581
  Rendering errors propagate.
1575
1582
 
1576
1583
  In Node, encode with [`encodePNG`](#encodepng):
@@ -98,7 +98,7 @@ into a whole compiled character of its own, so the renderer still sees only plai
98
98
  | `textures.js` | Procedural textures sampled in part-local pixel space. | `TEXTURES`, `sampleTexture`, `hash2` |
99
99
  | `image.js` | RGBA image helpers and the contact sheet used by `preview`. | `contactSheet`, `createImage`, `blit`, `checker` (not re-exported from `index.js`) |
100
100
  | `ascii.js` | A frame as text (one letter per material, `#` outline, `.` empty). | `frameToAscii` |
101
- | `bundle.js` | Render one sheet per resolution (and per skin, stored as a colour swap + overlay of the default sheet when smaller) and package them for the runtime with `size`, `ground`, baked points and `states`; optionally without some views. | `buildBundle`, `bakePoints`, `skinDelta`, `keepViews`, `BUNDLE_FORMAT` (`'pixel-sprite/1'`) |
101
+ | `bundle.js` | Render one sheet per resolution (and per skin, stored as a colour swap + overlay of the default sheet when smaller) and package them for the runtime with `size`, `ground`, baked points and `states`; optionally without some views or animations. | `buildBundle`, `bakePoints`, `skinDelta`, `keepViews`, `selectAnimations`, `keepAnimations`, `pruneStates`, `STAGE_ROLES`, `BUNDLE_FORMAT` (`'pixel-sprite/1'`) |
102
102
  | `export.js` | One sheet plus Aseprite "hash" JSON for game engines (Phaser, PixiJS): frames, tags, slices for points, Pixel Studio extras. | `exportSheet` |
103
103
  | `mix.js` | Transition clips (`mixes`): a few frames that interpolate the pose from the end of one animation to the start of another, added to the compiled animations as `"from>to"`. | `buildMixes` |
104
104
  | `plugins.js` | Extension points: register shapes, textures and motion models; they join the built-in tables so validation and `pixel brief` treat them like built-ins. Read-only snapshots of those tables. | `registerShape`, `registerTexture`, `registerMotion`, `registeredPlugins`, `usePlugin`, `shapeTypes`, `textures`, `motionModels`, `leggedModels` |
@@ -109,13 +109,14 @@ into a whole compiled character of its own, so the renderer still sees only plai
109
109
  | File | Responsibility | Main exports / entry |
110
110
  |---|---|---|
111
111
  | `src/node/png.js` | `pngBytes` with `node:zlib` deflate level 9. Node-only. | `encodePNG(w, h, rgba) → Buffer` |
112
- | `packages/runtime/src/pixel-sprite.js` | `<pixel-sprite>` web component: loads a bundle, picks a variant (and skin), plays frames from the sheet, fires baked events, runs the bundle's state machine, and exports the shared frame clock. Does not import the engine. | `PixelSprite`, `clock`, `pickVariant`, `deviceScale`, `checkBundle`, `StateMachine`, `parseCondition`, `BurstDetector`, `BUNDLE_FORMAT` |
113
- | `packages/runtime/src/pixel-stage.js` | `<pixel-stage>` and `<pixel-actor>`: characters that roam a page, standing on, jumping between, climbing and hiding behind opted-in elements. Imports only `clock` from `pixel-sprite.js`. | `PixelStage`, `PixelActor`, `World`, `checkScene`, `runScene`, `jumpArc`, `cells` |
112
+ | `packages/runtime/src/pixel-sprite.js` | `<pixel-sprite>` web component: loads a bundle, picks a variant (and skin), plays frames from the sheet, fires baked events, runs the bundle's state machine, and exports the shared frame clock. Does not import the engine. | `PixelSprite`, `clock`, `pickVariant`, `deviceScale`, `checkBundle`, `StateMachine`, `parseCondition`, `BurstDetector`, `BUNDLE_FORMAT`, `SPRITE_EVENTS`, `TOUCH_HOVER_MS` |
113
+ | `packages/runtime/src/pixel-stage.js` | `<pixel-stage>` and `<pixel-actor>`: characters that roam a page, standing on, jumping between, climbing and hiding behind opted-in elements. Imports only `clock` from `pixel-sprite.js`. | `PixelStage`, `PixelActor`, `World`, `checkScene`, `runScene`, `jumpArc`, `cells`, `GESTURE`, `Gesture`, `throwVelocity` |
114
114
  | `bin/pixel.mjs` | CLI: `validate`, `preview`, `ascii`, `render`, `export`, `bundle`, `resolve`, `where`, `figures`, `brief`. Loads files, calls `resolveSpec`, then the core. | `pixel` bin (see `package.json`) |
115
115
  | `scripts/build-demo.mjs` | Builds `demo/assets/*.bundle.json` from `examples/*.json` at 16/32/64 px, writes a 64 px poster of each (`demo/assets/*.poster.png`) and a 32 px `exportSheet` sheet for `goose-root`, copies both runtimes (`pixel-sprite.js`, `pixel-stage.js`), and with `--previews` writes `previews/*.png`. | `npm run build:demo`, `npm run previews` |
116
116
  | `demo/index.html`, `demo/flock.html`, `demo/stage.html`, `demo/runner.html` | Demo pages: sprites on a site (including a state machine and skins section), the goose flock, `<pixel-stage>` characters roaming a page, and a tiny runner game played by the fox. | pages |
117
117
  | `scripts/serve.mjs` | Zero-dependency static server for the repo root (studio and demo), port `PORT` or 5173. | `npm run studio` |
118
- | `studio/app.js` | Studio UI: editor → `resolveSpec` → `validate` → `compile` → `checkBounds` → render (current view, LOD strip at 16/24/32/48/64 px, sheet), rig overlay, export with a canvas PNG encoder. | browser module |
118
+ | `studio/app.js` | Studio UI: editor → `resolveSpec` → `validate` → `compile` → `checkBounds` → render (current view or a skin, LOD strip at 16/24/32/48/64 px, sheet), rig overlay, export with a canvas PNG encoder. `?c=<example>&skin=&anim=&res=` (the playground's names) opens an example in the simple view (the preview, a few pickers, then Customise, Create with Claude or Export) without saving it over the spec in localStorage; `&edit` opens it in the full editor. | browser module |
119
+ | `studio/site.js` | The studio pages' links back to the website (logo, Docs): the live site's URLs, or `/` and `/docs/` when served under `/apps/`. | classic script |
119
120
  | `studio/agent.js` | Agent tab: calls the Anthropic SDK from the browser (loaded lazily from esm.sh), validation-repair loop, contact-sheet critique. | `initAgent`, `extractSpec` |
120
121
  | `studio/goose.html` | Goose workbench: resolves `{extends: <goose>, …features}` in the page, renders frames on demand with `renderFrame`, hides parts/shapes on a copy of the compiled spec (bones stay), exports a variant spec and checks it builds. Features live in `studio/goose-features.json`. | page |
121
122
  | `studio/figures.html` | Figure viewer: inline module that draws each figure's skeleton with `samplePoseAt` + `followOffsets` (smooth time, trails, onion skin). | page |
@@ -594,9 +595,11 @@ Both passes run after shading.
594
595
  - **`animationMeta(anim)`** (`render.js`) is the playback description shared by sheets, bundles and
595
596
  the CLI's `render` JSON: `frames`, `fps`, `loop`, plus `speed`, `speedY`, `wall`, `mix`
596
597
  (`{from, to}`, on transition clips) and `events` when set, and `durations` (ms per frame, `1000/fps × hold`) only when the animation has `holds`.
597
- - **`buildBundle(compiled, {resolutions = [16, 32, 64], overrides, encode, views, deltas = true})`**
598
- (`bundle.js`) first drops the views not listed in `views` (**`keepViews`**: animations named
599
- `x@view`), then sorts the resolutions ascending and renders a sheet per resolution. It encodes each
598
+ - **`buildBundle(compiled, {resolutions = [16, 32, 64], overrides, encode, views, animations, deltas = true})`**
599
+ (`bundle.js`) first keeps only the `animations` asked for (**`selectAnimations`** adds their views, the views'
600
+ turns and the transitions between kept ones, and expands `"stage"` with **`STAGE_ROLES`**, a copy of the stage's
601
+ role table; **`keepAnimations`** filters), then drops the views not listed in `views` (**`keepViews`**: animations
602
+ named `x@view`), then sorts the resolutions ascending and renders a sheet per resolution. It encodes each
600
603
  sheet with the host-supplied `encode(w, h, rgba)`: `encodePNG` → data URL in Node, `pngBytes` with
601
604
  `CompressionStream` in the studio. Each skin in `compiled.skins` gets the same resolutions again,
602
605
  appended as variants tagged `skin`. **`skinDelta(base, skin)`** tries to express a skin sheet as
@@ -604,6 +607,7 @@ Both passes run after shading.
604
607
  pixels still different; it gives up (null) if the skin makes an opaque pixel transparent. The delta
605
608
  is used when its encoded size is below the full sheet's. It returns
606
609
  `{format: 'pixel-sprite/1', name, size, ground, animations, skins?, states?, points?, skinPoints?, variants: [{res, lod, frameW, frameH, image, skin?}]}`.
610
+ `states` goes through **`pruneStates`**, which drops the nodes whose animation is not in the bundle.
607
611
  `ground` is `compiled.ground`, or `groundFromPixels`: the bottom of the lowest opaque row of the
608
612
  first frame of the largest sheet, in units. `points` comes from **`bakePoints(compiled)`**, which
609
613
  poses every frame with `samplePose` + `worldMatrices` and records `[x, y, rotDeg]` per point, animation
@@ -844,6 +848,7 @@ The test suite uses `node:test` and `node:assert/strict`. The engine tests impor
844
848
  | `test/rig.test.mjs` | Reach: the tip hits a per-frame target, `aim` fixes the end orientation, limits are respected, validation messages. Bounds warnings with frames and edges. `extends`: material merge, part patch/add/remove with descendants, animation merge, `materialMap`, chained `resolveExtends`. |
845
849
  | `test/figure.test.mjs` | Every figure expands cleanly: no errors, no warnings, no motion notes, no bounds warnings. Gait feet move backward at exactly `speed`. `pose` keeps feet planted. Dressing and `bone` layers ride their bones, and tracks layer on the motion. Figure errors point at paths. Follow-through lags during the gait and stays still at rest. Every example resolves and validates. Front view: planted feet, foreshortening. Hop: gravity arc, volume-preserving squash, shadow shrink. Events: footsteps at touchdowns, hop takeoff/land, jump launch/land, author events. Climb: feet planted on the wall at `speedY`. Ground line from the figure, fitted and overridable. Points baked per frame, with validation messages. Holds become `durations`; bundles carry ground, size, events, points, `speedY`. Variants merge points by name. States validated against animations and inputs; skins compile as patched characters. `exportSheet`: Aseprite frames and tags, PixiJS map, slices, extras. |
846
850
  | `test/runtime.test.mjs` | `pickVariant`: integer scale ≥ 2, most detail within 20%, closest fit otherwise. The shared clock (a throwing subscriber cannot stop it; dt clamp and reset), `checkBundle` errors, `deviceScale` at fractional DPRs. `jumpArc` lands on time at the apex height; `cells` splits overlapping cut-outs into disjoint cells. `parseCondition` and `StateMachine` (inputs, `sync`, waiting for `footstep`, triggers, `then: "previous"`, random fidgets). |
851
+ | `test/gesture.test.mjs` (runtime) | Gestures on characters (`Gesture`, `throwVelocity`, and the stage's input wiring on a fake document and clock): tap vs touch hold vs swipe vs mouse drag, throw velocity, the same `pixel-tap` / `pixel-burst` / `pixel-grab` / `pixel-throw` for mouse, pen and touch, nothing prevented during a swipe, `pointercancel` and pinches; a `<pixel-sprite>` state machine on touch (a tap enters, clicks, and leaves later). |
847
852
  | `test/plugins.test.mjs` | Plug-ins, in their own file because registrations are process-wide: a registered shape, texture and motion validate, render and animate like built-ins; registration errors are clear. |
848
853
  | `test/references.test.mjs` | The reference registry (`references/`, checked by `scripts/references.mjs`): every source is cited and every logged value matches, `references/CREDITS.md` is up to date with `sources.json`, and the checks catch bad licences, drifted values, unknown sources and measurement files that do not say who, when and how. |
849
854
  | `test/browser/runtime.html` | 24 in-browser checks of `<pixel-sprite>` (open it on real devices; passes in Chromium and the iOS 18.1 Safari simulator): single load on upgrade, reserved box, errors and `reload()`, races, shared sheets, device-pixel scaling, decorative `alt`, touch and mouse input, one-shots, the clock, footstep events, holds, `point()` with `flip`, `groundOffset`, `hitTest()`, the state machine, skins, transition clips, rage clicks. Run in Firefox and WebKit with `scripts/browser-check.mjs`. |
package/docs/cli.md CHANGED
@@ -285,15 +285,16 @@ An excerpt of `fox.32.json`:
285
285
  ## bundle
286
286
 
287
287
  ```
288
- node bin/pixel.mjs bundle <spec.json> [--res 16,32,64] [--views front,back|none] [--external] [--out file.bundle.json] [style flags]
288
+ node bin/pixel.mjs bundle <spec.json> [--res 16,32,64] [--views front,back|all|none] [--anims idle,walk|stage] [--external] [--out file.bundle.json] [style flags]
289
289
  ```
290
290
 
291
- Builds a self-contained `pixel-sprite/1` bundle: every animation at every resolution, with each sprite sheet embedded as a PNG data URL. Besides the animation table and the variants, the bundle carries the canvas `size` and the foot line `ground` (both in spec units), the attachment `points` baked per animation and frame, the names of the `skins` and the `states` machine when the spec has them, and, for each skin, one extra variant per resolution tagged with `skin` (stored as a colour swap and overlay of the default sheet when that is smaller). Sheets are indexed PNGs when they have at most 256 colours. The format is described in [runtime.md](runtime.md#bundle-format-pixel-sprite1).
291
+ Builds a self-contained `pixel-sprite/1` bundle: every animation at every resolution (seen from the side; see `--views`), with each sprite sheet embedded as a PNG data URL. Besides the animation table and the variants, the bundle carries the canvas `size` and the foot line `ground` (both in spec units), the attachment `points` baked per animation and frame, the names of the `skins` and the `states` machine when the spec has them, and, for each skin, one extra variant per resolution tagged with `skin` (stored as a colour swap and overlay of the default sheet when that is smaller). Sheets are indexed PNGs when they have at most 256 colours. The format is described in [runtime.md](runtime.md#bundle-format-pixel-sprite1).
292
292
 
293
293
  | Flag | Default | Description |
294
294
  |---|---|---|
295
295
  | `--res` | `16,32,64` | Comma-separated resolutions, one variant each. Sorted ascending in the output. |
296
- | `--views` | every view | Which extra views to ship (`front`, `front,back`); `none` keeps only the main (side) view. Each view adds about a full set of animations. |
296
+ | `--views` | `none` | Which extra views to ship besides the main (side) view: `front`, `front,back`, or `all`. Views are what [`<pixel-stage>`](stage.md) uses to turn a character to the reader (`idle@front`, `turn@front`, …); each adds about a full set of animations. A name the character does not have is an error. When the spec has views and you leave them out, a note on stderr says which. |
297
+ | `--anims` | every animation | Only these animations (`idle,waddle,honk`), plus what they need: their views (`idle@front`, when views are shipped), the views' `turn@`, `unturn@` and `look@` clips, and the transition clips between two kept animations (`waddle>idle`). `stage` keeps what `<pixel-stage>` plays: for each role (idle, walk, run, rush, jump, fall, sit, duck, peek, climb, react) the first animation the character has, as the [stage looks them up](stage.md#elements-and-attributes). Names and `stage` combine: `--anims stage,hack`. An unknown name is an error that lists the character's animations. |
297
298
  | `--external` | off | Write each sheet (and skin overlay) as a PNG file next to the bundle (`<name>.32.png`, `<name>.32.party.overlay.png`) instead of embedding it, so a page downloads only the size it shows. |
298
299
  | `--out` | `<spec name>.bundle.json` in the current directory | Output file. Parent directories are created. |
299
300
  | style flags | | Applied to every variant. `--lod` forces the same tier for all of them. See [Style override flags](#style-override-flags). |
@@ -302,17 +303,43 @@ Prints the output path, the size of the JSON in KB, and the resolution of every
302
303
 
303
304
  ```
304
305
  $ node bin/pixel.mjs bundle examples/fox.json --out $OUT/fox.bundle.json
305
- wrote $OUT/fox.bundle.json (60.3 KB, variants: 16, 32, 64)
306
+ wrote $OUT/fox.bundle.json (61.1 KB, variants: 16, 32, 64)
306
307
 
307
308
  $ node bin/pixel.mjs bundle examples/goose-root.json --res 48,24 --out $OUT/root.bundle.json
308
- wrote $OUT/root.bundle.json (100.4 KB, variants: 24, 48, 24 (party), 48 (party), 24 (redteam), 48 (redteam))
309
+ note: side view only; --views all (or front, back) adds the character's other views
310
+ wrote $OUT/root.bundle.json (53.5 KB, variants: 24, 48, 24 (party), 48 (party), 24 (redteam), 48 (redteam))
309
311
 
310
- $ node bin/pixel.mjs bundle examples/goose-root.json --views none --res 32 --external --out $OUT/web/root.bundle.json
312
+ $ node bin/pixel.mjs bundle examples/goose-root.json --res 32 --external --out $OUT/web/root.bundle.json
313
+ note: side view only; --views all (or front, back) adds the character's other views
311
314
  wrote $OUT/web/root.bundle.json (10.2 KB, variants: 32, 32 (party), 32 (redteam))
312
315
  $ ls $OUT/web
313
316
  root.32.party.overlay.png root.32.png root.32.redteam.overlay.png root.bundle.json
314
317
  ```
315
318
 
319
+ For a character on a [`<pixel-stage>`](stage.md) that turns to face the reader, ship its views, and only what the stage plays:
320
+
321
+ ```
322
+ $ node bin/pixel.mjs bundle examples/goose-root.json --views all --anims stage --res 32 --out $OUT/root.bundle.json
323
+ note: states: dropped node hack (no animation left to play)
324
+ wrote $OUT/root.bundle.json (42.1 KB, variants: 32, 32 (party), 32 (redteam))
325
+ ```
326
+
327
+ **The state machine follows the animations.** A `states` node whose animation is not in the bundle (left out by
328
+ `--anims`, or a view left out by `--views`) is dropped, with the transitions to it, its `from` entries in other
329
+ transitions, and `random` fidgets that play a missing animation. A node whose `then` was dropped returns to the
330
+ previous node instead, and a dropped `initial` becomes the first node left. With no node left, the bundle has no
331
+ state machine. A note on stderr names the dropped nodes. To keep a node, name its animation in `--anims`.
332
+
333
+ ```
334
+ $ node bin/pixel.mjs bundle examples/goose-root.json --anims idle,waddle,honk --out $OUT/root.bundle.json
335
+ note: side view only; --views all (or front, back) adds the character's other views
336
+ note: states: dropped nodes run, panic, hack (no animation left to play)
337
+ wrote $OUT/root.bundle.json (24.2 KB, variants: 16, 32, 64, 16 (party), 32 (party), 64 (party), 16 (redteam), 32 (redteam), 64 (redteam))
338
+
339
+ $ node bin/pixel.mjs bundle examples/goose-root.json --anims idle,quack
340
+ error: no animation "quack" in root (hacker goose) (have: idle, waddle, run, rush, honk, jump, fall, sit, duck, peek, climb, flap, fly, hack; or "stage" for what <pixel-stage> uses)
341
+ ```
342
+
316
343
  `--res` must be whole numbers from 1 to 512; anything else is an error:
317
344
 
318
345
  ```
@@ -487,8 +514,10 @@ Pixel Studio CLI — the agent's hands and eyes.
487
514
  sprite sheet PNG + JSON metadata
488
515
  pixel export <spec.json> [--res 32] [--out dir] [--format aseprite]
489
516
  sheet PNG + Aseprite JSON (Phaser, PixiJS)
490
- pixel bundle <spec.json> [--res 16,32,64] [--views front,back|none] [--external] [--out file.bundle.json]
491
- self-contained web bundle for <pixel-sprite> (all skins);
517
+ pixel bundle <spec.json> [--res 16,32,64] [--views front,back|all] [--anims idle,walk|stage] [--external]
518
+ [--out file.bundle.json] self-contained web bundle for <pixel-sprite> (all skins);
519
+ side view only unless --views; --anims keeps only those
520
+ animations (stage: what <pixel-stage> uses);
492
521
  --external writes the sheets as PNG files beside it
493
522
  pixel resolve <variant.json> [--out full.json] print a variant ("extends") merged with its base
494
523
  pixel where <spec.json> [--anim a] [--frame f] [--part id --point x,y]
package/docs/figures.md CHANGED
@@ -178,8 +178,9 @@ view dresses its own figure (a front-view one) with the same materials:
178
178
  - Top-level parts hidden by default (`"show": 0`, a prop like root's server rack) stay hidden through the turns.
179
179
  - `examples/goose-base.json` has front and back views; the whole flock inherits them. `studio/goose.html` shows them,
180
180
  and its features have front and back versions.
181
- - Views make bundles bigger: each adds about a full set of animations. Ship only the ones a page uses:
182
- `pixel bundle goose.json --views front` (or `--views none`), `buildBundle(c, {views: ['front']})`.
181
+ - Views make bundles bigger: each adds about a full set of animations. `pixel bundle` ships the side view only;
182
+ ask for the ones a page uses: `pixel bundle goose.json --views front` (or `--views all`),
183
+ `buildBundle(c, {views: ['front']})` (`buildBundle` ships every view unless told otherwise).
183
184
 
184
185
  ### Speed
185
186
 
@@ -61,6 +61,7 @@ attachment points (the beak) and the foot line. It is the only thing the page ne
61
61
  ```html
62
62
  <!doctype html>
63
63
  <meta charset="utf-8">
64
+ <style>pixel-sprite:not(:defined) { display: inline-block; vertical-align: bottom; width: 128px; height: 128px }</style>
64
65
  <script type="module" src="node_modules/@pixel-studio/runtime/src/pixel-sprite.js"></script>
65
66
  <pixel-sprite src="my-goose.bundle.json" anim="idle" size="128"
66
67
  hover-anim="waddle" click-anim="honk" alt="Marigold, a yellow goose"></pixel-sprite>
@@ -69,6 +70,8 @@ attachment points (the beak) and the foot line. It is the only thing the page ne
69
70
  Serve the folder (modules and `fetch` need http, not `file://`), for example `python3 -m http.server`, and open it.
70
71
  The goose idles, waddles while the mouse is over it, and honks when clicked. The runtime picks the sharpest sheet
71
72
  for the size and the screen, scales in whole device pixels, pauses off-screen and respects reduced motion.
73
+ The `<style>` line gives the goose its 128 × 128 box before the script has run, so the page does not jump when it
74
+ appears. For a character far down a long page, add `loading="lazy"`: it loads when it comes near.
72
75
 
73
76
  In production, copy `pixel-sprite.js` and the bundle next to your page; the runtime is one file with no imports.
74
77
 
@@ -0,0 +1,301 @@
1
+ # Performance: what characters cost a page
2
+
3
+ Measured numbers for deciding whether to put Pixel Studio characters on a site: what a page downloads, what that does
4
+ to loading, what playing costs per frame, and how much memory it takes. Every number here comes from a script in
5
+ [`scripts/bench/`](../../../scripts/bench/), with the command to rerun it next to each table.
6
+
7
+ - [In short](#in-short)
8
+ - [Download size](#download-size)
9
+ - [Load impact](#load-impact)
10
+ - [Cost per frame](#cost-per-frame)
11
+ - [Touch scrolling](#touch-scrolling)
12
+ - [Memory](#memory)
13
+ - [Keeping it small](#keeping-it-small)
14
+ - [How it was measured](#how-it-was-measured)
15
+
16
+ ## In short
17
+
18
+ - **Download:** 14 KB of script for `<pixel-sprite>`, 42 KB for `<pixel-stage>` (brotli; 16 and 48 KB gzip), plus
19
+ one bundle per character: 9 to 43 KB for the five non-goose examples, 75 to 105 KB for a goose with every view and
20
+ resolution, 55 KB for the same goose as `pixel bundle` builds it by default (the side view only), and 14 KB with
21
+ `--res 32` (4 KB with only the three animations a page plays, `--anims idle,waddle,honk`).
22
+ - **Loading:** no measurable change to LCP or TBT on a throttled mobile profile. One sprite causes a small layout
23
+ shift (CLS 0.03) unless its box is reserved in CSS.
24
+ - **Playing:** under 0.1 ms of main thread per frame for one sprite, 0.4 ms for 50, 0.3 ms for a stage with three
25
+ actors (under 7% of a frame for 50 sprites with the CPU slowed down four times). Off-screen, paused and
26
+ reduced-motion sprites cost nothing measurable per frame; a playing stage keeps moving its characters off-screen.
27
+ - **Memory:** the decoded sprite sheet is the large part: 0.1 to 2 MB at 32 px for most characters, and about
28
+ 8 MB for a goose at 64 px (20 MB for the greylag, whose longest animation has almost three times as many frames).
29
+ It is shared by every sprite of that character.
30
+ - **Below the fold:** by default a sprite fetches and decodes its bundle as soon as it is in the page, even far
31
+ below the fold. On long pages, [`loading="lazy"`](#keeping-it-small) waits until it comes near.
32
+
33
+ ## Download size
34
+
35
+ A page with characters downloads the runtime once and one bundle per character (a JSON file with the sprite sheets as
36
+ PNG data URLs). Sprites that share a bundle URL share one fetch and one decoded sheet. Rerun with
37
+ `node scripts/bench/sizes.mjs` (after `npm run build:demo`). The tables below are generated from it (`npm run docs:gen`
38
+ in `website/`), and the website build fails when they no longer match the files in the repository. KB = 1024 bytes;
39
+ gzip at level 9, brotli at quality 11.
40
+
41
+ The runtime, as published in `@pixel-studio/runtime` (readable source with comments, not minified). `pixel-stage.js`
42
+ imports `pixel-sprite.js`, so a page with a stage loads both.
43
+
44
+ <!-- gen:sizes table=runtime -->
45
+ | File | Raw | gzip | brotli |
46
+ |---|--:|--:|--:|
47
+ | `pixel-sprite.js` | 48.6 KB | 16.1 KB | 14.1 KB |
48
+ | `pixel-stage.js` | 99.7 KB | 31.9 KB | 27.8 KB |
49
+ | both (a page with `<pixel-stage>`) | 148.3 KB | 48.0 KB | 41.9 KB |
50
+ <!-- /gen -->
51
+
52
+ The example characters as built for the demos (16, 32 and 64 px, every view, every skin: `buildBundle`'s defaults, or
53
+ `pixel bundle --views all`).
54
+ Bundles are mostly PNG data, which is already compressed: gzip and brotli save 30 to 45% (mostly the base64
55
+ overhead), not the two thirds they save on script. A sprite decodes only the one sheet it shows, as RGBA in memory:
56
+ the last two columns (see [Memory](#memory)).
57
+
58
+ <!-- gen:sizes table=bundles -->
59
+ | Bundle | Animations | Raw | gzip | brotli | Decoded 32 px sheet | Decoded 64 px sheet |
60
+ |---|--:|--:|--:|--:|--:|--:|
61
+ | `fox` | 9 | 61.1 KB | 43.6 KB | 42.7 KB | 0.4 MB | 1.7 MB |
62
+ | `goose-base` | 41 | 134.8 KB | 89.5 KB | 87.8 KB | 1.9 MB | 7.7 MB |
63
+ | `goose-greylag` | 41 | 146.7 KB | 93.5 KB | 91.0 KB | 5.1 MB | 20.5 MB |
64
+ | `goose-kiddie` | 40 | 120.6 KB | 77.3 KB | 75.5 KB | 1.9 MB | 7.5 MB |
65
+ | `goose-phreak` | 42 | 146.6 KB | 98.4 KB | 96.6 KB | 2.0 MB | 7.9 MB |
66
+ | `goose-root` | 42 | 160.2 KB | 104.9 KB | 102.8 KB | 2.0 MB | 7.9 MB |
67
+ | `goose-sudo` | 42 | 158.8 KB | 107.2 KB | 105.4 KB | 2.0 MB | 7.9 MB |
68
+ | `moss` | 12 | 17.3 KB | 9.8 KB | 9.6 KB | 0.8 MB | 3.0 MB |
69
+ | `pip` | 9 | 36.1 KB | 24.7 KB | 23.9 KB | 0.4 MB | 1.7 MB |
70
+ | `robot` | 3 | 13.5 KB | 9.4 KB | 9.1 KB | 0.1 MB | 0.6 MB |
71
+ | `slime` | 5 | 21.3 KB | 15.5 KB | 15.1 KB | 0.2 MB | 0.9 MB |
72
+ <!-- /gen -->
73
+
74
+ The geese carry front and back views (`idle@front`, `turn@back`, …, used by `<pixel-stage>` to face the viewer) and,
75
+ for `goose-root`, two skins: that is most of their weight. The same goose built with other options ("gzip saved" is
76
+ against the first row, the demo build; `pixel bundle` without `--views` ships the side view only):
77
+
78
+ <!-- gen:sizes table=goose -->
79
+ | `pixel bundle goose-root.json` with | Animations | Raw | gzip | brotli | gzip saved | Largest sheet decoded |
80
+ |---|--:|--:|--:|--:|--:|--:|
81
+ | `--views all` (as built for the demos) | 42 | 160.2 KB | 104.9 KB | 102.8 KB | | 7.9 MB (64 px) |
82
+ | (default: `--res 16,32,64`, side view only) | 17 | 83.4 KB | 56.8 KB | 55.3 KB | 46% | 3.2 MB (64 px) |
83
+ | `--anims stage` | 14 | 68.6 KB | 47.0 KB | 45.7 KB | 55% | 2.6 MB (64 px) |
84
+ | `--anims idle,waddle,honk` | 5 | 24.2 KB | 16.4 KB | 15.8 KB | 84% | 0.8 MB (64 px) |
85
+ | `--views all --anims stage` | 37 | 138.7 KB | 91.1 KB | 89.2 KB | 13% | 6.9 MB (64 px) |
86
+ | `--res 32 --views all` | 42 | 48.4 KB | 25.2 KB | 23.5 KB | 76% | 2.0 MB (32 px) |
87
+ | `--res 32` | 17 | 25.0 KB | 15.0 KB | 13.7 KB | 86% | 0.8 MB (32 px) |
88
+ | `--res 32 --anims idle,waddle,honk` | 5 | 7.4 KB | 4.6 KB | 4.2 KB | 96% | 0.2 MB (32 px) |
89
+ | `--res 32 --external` | 17 | 19.5 KB | 12.7 KB | 12.2 KB | 88% | 0.8 MB (32 px) |
90
+ <!-- /gen -->
91
+
92
+ The `--external` row counts the JSON and the one PNG a page downloads (the 32 px sheet); PNG files are served as they
93
+ are, without further compression. A stage actor built without `--views` cannot turn to face the reader; everything
94
+ else works. `--anims stage` keeps what a stage actor plays (here everything but `flap`, `fly` and `hack`).
95
+
96
+ ## Load impact
97
+
98
+ What adding characters does to a small page's Core Web Vitals, with Lighthouse's mobile profile (slow 4G, a CPU four
99
+ times slower than the test machine). LCP and TBT are given twice: with Lighthouse's default simulated throttling,
100
+ and with the throttling applied in the browser, which times what really happens. Rerun with
101
+ `node scripts/bench/browser.mjs --only load` ([how](#how-it-was-measured)).
102
+
103
+ | Page | LCP, simulated | LCP, applied | TBT, simulated | TBT, applied | CLS | Transferred | Requests |
104
+ |---|--:|--:|--:|--:|--:|--:|--:|
105
+ | Plain page (no characters) | 622 ms | 686 ms | 0 ms | 0 ms | 0.000 | 1.3 KB | 2 |
106
+ | 1 sprite | 626 ms | 695 ms | 0 ms | 0 ms | 0.031 | 60.6 KB | 5 |
107
+ | 1 sprite, box reserved in CSS | 628 ms | 703 ms | 0 ms | 0 ms | 0.003 | 60.7 KB | 5 |
108
+ | Stage with 3 actors | 1085 ms | 700 ms | 0 ms | 0 ms | 0.000 | 191.1 KB | 10 |
109
+
110
+ The sprite is the 64 px fox (`fox.bundle.json`, built with the defaults); the stage has a goose, Pip and a slime.
111
+ Requests include the page and a favicon request.
112
+
113
+ - **LCP.** The runtime is a module script, which does not block rendering: the page's text paints first. With
114
+ applied throttling the characters move LCP by 10 to 20 ms, within the spread between runs. Lighthouse's
115
+ simulation adds 460 ms for the stage, because it counts the requests that start before the first paint (here the
116
+ two runtime files) as if they delayed it; that is the number a Lighthouse report shows by default.
117
+ - **TBT.** 0 ms in every run. No task over 50 ms comes from the runtime: the few long tasks Lighthouse saw (50 to
118
+ 90 ms) appear on the plain page too.
119
+ - **CLS.** 0.03 for one sprite: before its script runs the element has no size, then takes its box and pushes the
120
+ content below down. The CSS rule in [Keeping it small](#keeping-it-small) brings it to 0.003; a poster image with
121
+ `width` and `height` also reserves the box from the first paint. What is left is the device pixel ratio of the
122
+ profile's phone, 1.75: whole device pixels per sprite pixel make the 64 px fox 73 px tall once it has loaded
123
+ ([why](runtime.md#device-pixels-and-scaling)). At a device pixel ratio of 1, 2 or 3 the same page shifts by 0.000
124
+ (measured in Chrome 156 with a `layout-shift` `PerformanceObserver`, which gives the same 0.031 and 0.003 at 1.75).
125
+ The stage adds no shift: its characters are drawn in a layer above the page.
126
+ - **Bytes.** The 1-sprite page transfers the runtime (15 KB gzip) and the fox's bundle (44 KB gzip); the stage page
127
+ the two runtime files (44 KB) and three bundles (145 KB, 105 KB of it the goose).
128
+
129
+ ## Cost per frame
130
+
131
+ Main-thread time per rendered frame, in Chrome, with every character on screen and animating. "Added" is what the
132
+ characters add to the same page without them, and its share of a 60 Hz frame (16.7 ms). The 4x CPU columns slow
133
+ the same machine down four times, roughly a mid-range phone. Every case held 60 frames per second and had no long
134
+ tasks (over 50 ms) while playing. Rerun with `node scripts/bench/browser.mjs --only runtime` ([how](#how-it-was-measured)).
135
+
136
+ | Case | Characters on screen | Per frame | Added (share of a frame) | Per frame, 4x CPU | Added, 4x CPU |
137
+ |---|--:|--:|--:|--:|--:|
138
+ | Plain page | 0 | 0.15 ms | | 0.21 ms | |
139
+ | 1 sprite | 1 | 0.21 ms | 0.06 ms (0.4%) | 0.29 ms | 0.09 ms (0.5%) |
140
+ | 10 sprites | 10 | 0.33 ms | 0.17 ms (1.0%) | 0.61 ms | 0.40 ms (2.4%) |
141
+ | 50 sprites | 50 | 0.59 ms | 0.43 ms (2.6%) | 1.24 ms | 1.03 ms (6.2%) |
142
+ | 50 sprites, all off-screen | 0 | 0.17 ms | 0.02 ms (0.1%) | 0.22 ms | 0.01 ms (0.1%) |
143
+ | 50 sprites, reduced motion | 50 | 0.17 ms | 0.02 ms (0.1%) | 0.26 ms | 0.05 ms (0.3%) |
144
+ | Stage with 3 actors walking | 3 | 0.46 ms | 0.31 ms (1.9%) | 1.13 ms | 0.92 ms (5.5%) |
145
+
146
+ The sprites are 64 px foxes sharing one bundle, half walking and half trotting. The stage has a goose (80 px), Pip
147
+ (72 px) and a slime (56 px) wandering, climbing and sitting on three cards; a stage costs more per character than a
148
+ sprite because it also moves the characters across the page and decides what each does next.
149
+
150
+ - **Off-screen and reduced motion cost nothing measurable.** Sprites off-screen (one shared `IntersectionObserver`)
151
+ or under `prefers-reduced-motion` leave the shared frame loop, and the loop stops when it is empty. A paused sprite
152
+ (`paused`, `pause()`) leaves the loop the same way, and so does a paused stage (its button, `stage.pause()`).
153
+ A playing stage keeps moving its characters while they are off-screen (they go on wandering), so a stage is not
154
+ free when scrolled away; that case was not measured.
155
+ - **The cost grows with the number of characters drawing**, at about 0.007 ms per sprite per frame on this machine
156
+ (0.016 ms with 4x CPU), on top of a fixed cost for the loop and the first sprite.
157
+ - These are main-thread numbers. Compositing the canvases takes GPU and compositor time as well, which is not
158
+ included.
159
+
160
+ ## Touch scrolling
161
+
162
+ So that a finger can pick a character up, a stage with `grab="on"` (the default) keeps one non-passive `touchmove`
163
+ listener on the document. It does nothing unless a character is held, but the browser has to wait for it before a
164
+ swipe can start scrolling. Measured on `demo/stage.html` in Chrome (headless, Pixel 7 profile, real touch input),
165
+ 15 swipes per case that start off the characters, interleaved: time from `touchstart` to the first `scroll` event,
166
+ and frames over 50 ms during the fling that follows.
167
+
168
+ | Case | Swipe to first scroll (median) | 4x CPU | Long frames in the fling |
169
+ |---|--:|--:|--:|
170
+ | Stage, `grab="on"` (touch listener) | 66 ms | 64 ms | 0 |
171
+ | Stage, `grab="off"` (no touch listener) | 49 ms | 47 ms | 0 |
172
+ | Same page without a stage | 32 ms | 31 ms | 0 |
173
+
174
+ - The touch listener makes a swipe start scrolling one frame later (16 ms, with or without CPU throttling); the
175
+ fling that follows is not affected. A paused stage, `prefers-reduced-motion`, `grab="mouse"` and `grab="off"`
176
+ register no touch listener and do not pay it.
177
+ - The rest of the stage (its pointer listeners and per-frame work) accounts for one more frame against a page with no
178
+ stage at all.
179
+ - The listener cannot wait for a hold to begin: Chrome honours one added mid-gesture, but WebKit (by its design; not tested here) decides when a
180
+ touch starts whether its moves can be cancelled, so on iPhones the page would scroll away under a held character.
181
+ Pick-up as shipped (the listener registered up front) has been checked by hand on a real iPhone in Safari.
182
+ - The test driver sends each touch point and waits for the browser to acknowledge it, so these are upper bounds
183
+ measured in whole frames; a real finger's swipe overlaps them. The script is not in `scripts/bench/` yet.
184
+
185
+ ## Memory
186
+
187
+ Rerun with `node scripts/bench/browser.mjs --only runtime`. Measured after a forced garbage collection, as the
188
+ difference from the plain page.
189
+
190
+ | Case | JS heap | All browser processes |
191
+ |---|--:|--:|
192
+ | 1 sprite | +0.3 MB | +10 MB |
193
+ | 10 sprites | +0.3 MB | +12 MB |
194
+ | 50 sprites | +0.4 MB | +23 MB |
195
+ | 50 sprites, all off-screen | +0.3 MB | +12 MB |
196
+ | 50 sprites, reduced motion | +0.3 MB | +12 MB |
197
+ | Stage with 3 actors | +0.9 MB | +30 MB |
198
+
199
+ "All browser processes" is the resident memory of every Chrome process (the page, the GPU process, the browser); it
200
+ moves by a few MB between runs, so read it to the nearest 5 MB. Most of it is not JavaScript:
201
+
202
+ - **The decoded sheet.** A sprite decodes only the sheet it shows, once per bundle and resolution, shared by every
203
+ sprite that uses it. In memory it is width × height × 4 bytes, much more than the PNG: the last two columns of
204
+ the [bundles table](#download-size). A 64 px goose sheet with front and back views is about 8 MB decoded; the
205
+ [goose table](#download-size) shows how leaving out views, animations and resolutions shrinks it. A 32 px sheet is a quarter of
206
+ the 64 px one.
207
+ - **One canvas per sprite**, the displayed size in device pixels × 4 bytes: 256 KB for a 128 × 128 px sprite on a 2x screen.
208
+ - Off-screen sprites keep their decoded sheet and canvas: the 50 off-screen sprites above hold the same memory as
209
+ 10 visible ones. A sprite with `loading="lazy"` that has not yet come near holds neither (and has downloaded
210
+ nothing).
211
+
212
+ ## Keeping it small
213
+
214
+ - **Ship only the resolutions you show.** A sprite at `size` 64 uses the 32 px sheet, at 128 the 64 px one
215
+ ([how the variant is chosen](runtime.md#how-the-resolution-variant-is-chosen)). `pixel bundle --res 32` drops the
216
+ others: three quarters of a goose's bundle. Keep two resolutions if the same character appears at very different
217
+ sizes, or on a page that changes `size`.
218
+ - **Bundle only the animations you use.** A `<pixel-sprite>` that idles, waddles on hover and honks on click needs
219
+ three of a goose's fourteen animations: `pixel bundle goose.json --anims idle,waddle,honk` is under a third of the
220
+ side-view bundle. For a `<pixel-stage>` actor, `--anims stage` keeps what the stage plays (one animation per role:
221
+ idle, walk, run, jump, fall, sit, duck, peek, climb, …). Transition clips between kept animations stay, and a state
222
+ machine loses the nodes whose animation is gone ([details](cli.md#bundle)).
223
+ - **Ship views only for a stage that turns.** Front and back views are for `<pixel-stage>` turning a character to
224
+ face the reader, and they double a goose. `pixel bundle` leaves them out unless you ask: `--views all` (or
225
+ `--views front`) for a stage actor that should turn.
226
+ - **Keeping several resolutions? Use `--external`.** The sheets become PNG files next to the bundle and a page downloads
227
+ only the one it shows. Put them on the same origin, or send `Access-Control-Allow-Origin` ([details](runtime.md#loading-errors-and-fallbacks)).
228
+ - **Share one bundle.** Ten sprites of the same character with the same `src` make one request and decode one sheet.
229
+ Ten different characters make ten of each.
230
+ - **Serve with compression.** Static hosts and CDNs usually compress `.js` and `.json`; check that yours does. The
231
+ runtime files shrink to a third (they are readable source with comments, not minified). If you bundle your site's
232
+ JavaScript, your bundler can minify them too.
233
+ - **Reserve the box before the script runs.** The element is reserved at `size` × `size` once its script has run;
234
+ before that it is an unknown inline element with no size, and the content below it moves when it appears (CLS 0.03
235
+ for one 64 px sprite in the [load test](#load-impact)). A CSS rule removes it (0.003 on a phone with a fractional
236
+ device pixel ratio, 0 otherwise), with one line per `size` you use:
237
+
238
+ ```css
239
+ pixel-sprite:not(:defined) { display: inline-block; vertical-align: bottom; width: 128px; height: 128px; }
240
+ pixel-sprite:not(:defined)[size="64"] { width: 64px; height: 64px; }
241
+ ```
242
+
243
+ `vertical-align: bottom` matches the element's own style; without it a sprite in a line of text still shifts it
244
+ a little (0.002) when the script runs. For no shift at all after load, use a `size` that is a whole multiple of
245
+ the sheet it shows (64 for the 32 px sheet, 128 for the 64 px one). A poster image with `width` and `height` inside the element ([fallbacks](runtime.md#loading-errors-and-fallbacks))
246
+ reserves the space too, and shows the character before the bundle arrives and when JavaScript is off.
247
+ - **Reduced motion and the pause button cost nothing per frame.** They stop drawing, which is where the cost is. The stage's
248
+ pause button is on by default; for sprites that loop for more than five seconds, give readers a way to call
249
+ `pause()` (WCAG 2.2.2, see [accessibility](runtime.md#accessibility)).
250
+ - **Load characters far down the page lazily.** By default a sprite fetches its bundle and decodes its sheet as
251
+ soon as it is in the document, even when it is far below the fold; only the drawing waits until it scrolls into
252
+ view. On a long page with characters near the bottom, add `loading="lazy"`:
253
+
254
+ ```html
255
+ <pixel-sprite src="fox.bundle.json" size="64" alt="A fox" loading="lazy"></pixel-sprite>
256
+ ```
257
+
258
+ It waits, with its box reserved, until it is within one viewport of being seen, then loads
259
+ ([details](runtime.md#lazy-loading)). Until then it costs no request, no download (the fox's 44 KB gzip, a goose's
260
+ 75 to 105 KB), no decoded sheet (0.4 MB for the fox at `size` 64; 2 MB for a goose at 64, 8 MB at 128) and no canvas.
261
+ Sprites that share a bundle with one already loaded have nothing left to save. Stage actors always load at once;
262
+ for a stage, add the `<pixel-stage>` element (or its script) once the page has loaded, for example in a `load`
263
+ event listener.
264
+
265
+ ## How it was measured
266
+
267
+ Machine: MacBook Pro with an Intel Core i9-9980HK (8 cores, 2.4 GHz), 64 GB, macOS 26.6; Google Chrome 156,
268
+ headless; Node 24. Medians of 5 runs; each run starts a fresh browser. Measured on 2026-11-22 at the commit that added
269
+ this page. Your numbers will differ with the machine; the differences between rows are the useful part.
270
+
271
+ - **Sizes** (`node scripts/bench/sizes.mjs`, Node only): the runtime files from `packages/runtime/src/`, the bundles
272
+ from `demo/assets/` (`npm run build:demo`), gzip level 9 and brotli quality 11 from `node:zlib`. The goose rows
273
+ build `goose-root.json` in process with the same `buildBundle` options as the `pixel bundle` flags in each row. "Decoded" is the PNG's
274
+ width × height × 4.
275
+ - **Load and runtime** (`scripts/bench/browser.mjs`): a small static page (a heading, three paragraphs, three
276
+ cards; [`scripts/bench/page.html`](../../../scripts/bench/page.html)) with nothing, sprites or a stage added as
277
+ plain markup, served from the repository root by the script itself with gzip, like a static host.
278
+ - Load: Lighthouse 13 (performance category, default mobile profile: Moto G Power screen, slow 4G at 150 ms RTT
279
+ and 1.6 Mbit/s, 4x CPU slowdown), once with its default simulated throttling and once with throttling applied
280
+ in the browser (`throttlingMethod: 'devtools'`).
281
+ - Runtime: Playwright drives Chrome at 1280 × 900, device pixel ratio 1. After the characters are ready and 1.5 s
282
+ of warm-up, the main thread's busy time (Chrome's `TaskDuration` metric over the DevTools protocol) is summed
283
+ over 4 s and divided by the frames rendered in that time (counted with `requestAnimationFrame`, on every page,
284
+ the plain one too). Then the same with the CPU slowed down four times (`Emulation.setCPUThrottlingRate`). Long
285
+ tasks are counted with a `PerformanceObserver`. Memory: the JS heap after a forced garbage collection, and the
286
+ resident memory (`ps`) of every Chrome process.
287
+
288
+ Lighthouse and Playwright are not dependencies of this project. To rerun everything:
289
+
290
+ ```sh
291
+ npm run build:demo
292
+ mkdir /tmp/bench && cd /tmp/bench && npm i lighthouse playwright-core
293
+ node /path/to/pixel-studio/scripts/bench/browser.mjs --runs 5 # about 25 minutes; --only load or --only runtime
294
+ node /path/to/pixel-studio/scripts/bench/browser.mjs --serve # just serve the test pages, to profile them by hand
295
+ ```
296
+
297
+ It uses the installed Google Chrome; `--chrome <path>` (or `CHROME_PATH`) picks another Chromium.
298
+
299
+ Not measured: Firefox and Safari (the runtime numbers use a Chrome-only protocol; the runtime is checked for
300
+ behaviour in both, see [runtime.md](runtime.md#testing-on-devices)), real phones, and a stage whose actors are
301
+ all off-screen.
package/docs/runtime.md CHANGED
@@ -67,6 +67,7 @@ The module exports:
67
67
  | `parseCondition(when)` | Parses a transition's `when` into a function `(inputs, triggers) → boolean`; throws on bad syntax. |
68
68
  | `BUNDLE_FORMAT` | `"pixel-sprite/1"`. |
69
69
  | `SPRITE_EVENTS` | The events the element fires, without the `pixel-` prefix: `ready`, `error`, `statechange`, `end`, `event`, `burst`, `calm` (frozen). |
70
+ | `TOUCH_HOVER_MS` | How long a tap on a touch screen counts as hovering for a state machine's `enter` / `leave`: 3000 ([Touch screens](#touch-screens)). |
70
71
 
71
72
  It can be imported in Node: without `HTMLElement`, the class extends an empty class and the element is not registered. The tests use this for the helpers and the clock.
72
73
 
@@ -99,8 +100,9 @@ If both are present, `src` wins. The inline JSON is read once, when the element
99
100
  | `burst` | on | read on click | `burst="off"` turns off rapid-click detection (see [Bursts](#bursts-rage-clicks)). |
100
101
  | `skin` | none | yes | A skin baked into the bundle (see [Skins](#skins)). Unknown names show the default look. |
101
102
  | `states` | on | at load | `states="off"` ignores the bundle's state machine (pages and `<pixel-stage>` that choose animations themselves set this). |
103
+ | `loading` | `eager` | yes | `loading="lazy"` waits to fetch the bundle and decode its sheet until the sprite comes within about one viewport of being seen, like `<img loading="lazy">` (see [Lazy loading](#lazy-loading)). Switching a waiting sprite to `eager` loads it at once. Also `el.loading`. |
102
104
  | `alt` | none | yes | Text alternative, copied into `aria-label`. `alt=""` marks the sprite as decorative (see [Accessibility](#accessibility)). |
103
- | `status` | set by the element | — | `loading`, `ready` or `error`. Absent before the first load starts. Use it for CSS, e.g. `pixel-sprite[status=error] { display: none }`. (Also mirrored to the legacy `state` attribute until 0.2.0-alpha is out; see [Renamed in 0.2.0-alpha](#renamed-in-020-alpha).) |
105
+ | `status` | set by the element | — | `loading`, `ready` or `error`. Absent before the first load starts (also while a lazy sprite waits). Use it for CSS, e.g. `pixel-sprite[status=error] { display: none }`. (Also mirrored to the legacy `state` attribute until 0.2.0-alpha is out; see [Renamed in 0.2.0-alpha](#renamed-in-020-alpha).) |
104
106
 
105
107
  Attribute changes made before the element is first connected (including the attribute callbacks of an upgrade) are folded into the single first load.
106
108
 
@@ -112,7 +114,7 @@ Attribute changes made before the element is first connected (including the attr
112
114
  | `el.animations` | Array of animation names in the bundle (`[]` before load). |
113
115
  | `el.currentAnim` | Name of the animation showing now (`null` before load). |
114
116
  | `el.frame` | Index of the frame showing now. |
115
- | `el.status` | Load status: `'idle'` (nothing loaded yet), `'loading'`, `'ready'` or `'error'`. Not to be confused with the state machine (`el.stateNode`). |
117
+ | `el.status` | Load status: `'idle'` (nothing loaded yet, or a lazy sprite still waiting), `'loading'`, `'ready'` or `'error'`. Not to be confused with the state machine (`el.stateNode`). |
116
118
  | `el.displaySize` | `{ width, height }` in CSS px as displayed, or `null` before load. |
117
119
  | `el.pxPerSecond(name = currentAnim)` | CSS px per second that animation should travel for its feet not to slide, at the displayed size; `null` if it has no `speed`. |
118
120
  | `el.play(name, { once = false, restart = once, mix = true } = {})` | Play `name`. If the bundle has a transition clip from the current animation to `name` (`waddle>idle`) and the switch happens at a boundary (the current animation is on its first frame, i.e. a loop's end, or a one-shot finished), the clip plays first; `mix: false` skips it. With `once: true` it plays to the end, fires `pixel-end`, then returns to `hover-anim` (if a mouse is over it) or the base animation. If `name` is already playing (looping, not a one-shot) the call does nothing unless `restart: true`, so hovering in and out does not restart a walk cycle. Returns `false` for unknown names or before load. Does not change the `anim` attribute. |
@@ -139,7 +141,7 @@ listeners outside it). Names start with `pixel-`.
139
141
  | `pixel-end` | `{ anim }` | A one-shot animation (`play(name, { once: true })`, `click-anim`, or a tap) reached its end, or a non-looping animation (`loop: false`) played as a normal animation reached its last frame. Also fired under reduced motion and while off-screen, after the animation's duration, so code waiting for it never hangs. |
140
142
  | `pixel-event` | `{ anim, frame, name, data }` | A frame with a baked event is shown: `footstep`, `land`, `launch`, an author's `honk` (see [Events](#events-attachment-points-and-the-foot-line)). |
141
143
  | `pixel-statechange` | `{ from, to }` | The state machine moved to another node. |
142
- | `pixel-burst` | `{ count, rate }` | The third and every further click (or tap) that comes within 450 ms of the previous one. `rate` is a suggested speed-up: 1.35, then +0.35 per click, up to 3. |
144
+ | `pixel-burst` | `{ count, rate }` | The third and every further click (or tap: the same on every device) that comes within 450 ms of the previous one. `rate` is a suggested speed-up: 1.35, then +0.35 per click, up to 3. |
143
145
  | `pixel-calm` | `{ count }` | The clicking stopped (450 ms after the last burst click). Any burst speed-up ends. |
144
146
 
145
147
  Because events bubble, one listener can watch every sprite on a page (from `demo/index.html`). The sprites
@@ -170,7 +172,7 @@ did not bubble, and no old name is composed). They will be removed after 0.2.0-a
170
172
 
171
173
  ## Loading, errors and fallbacks
172
174
 
173
- - **The box is reserved at once.** Before the bundle arrives the element is `size × size` CSS px (the canvas starts at 0 × 0, not the browser's default 300 × 150), so the page does not jump when it loads. After load the box takes the displayed size. If it fails, the box stays reserved.
175
+ - **The box is reserved at once.** Before the bundle arrives the element is `size × size` CSS px (the canvas starts at 0 × 0, not the browser's default 300 × 150), so the page does not jump when it loads. After load the box takes the displayed size: the same as `size` when `size` is a whole multiple of the sheet's resolution and the screen's device pixel ratio is a whole number, otherwise a few pixels off (see [Device pixels](#device-pixels-and-scaling)). If it fails, the box stays reserved.
174
176
  - **Fallback content.** Children of the element (other than the inline bundle script) are shown until the sprite is `ready`, and again on `error`. A poster image is the usual choice; it also shows when JavaScript is off:
175
177
 
176
178
  ```html
@@ -180,13 +182,49 @@ did not bubble, and no old name is composed). They will be removed after 0.2.0-a
180
182
  ```
181
183
 
182
184
  Slotted `<img>` elements fill the box with `image-rendering: pixelated`. Any still of the character works as a poster (for example one frame cut from a `pixel render` sheet).
183
- - **Before the script runs** the element is an unknown inline element. To reserve its space even then, add a rule such as `pixel-sprite:not(:defined) { display: inline-block; width: 128px; height: 128px }`.
185
+ - **Before the script runs** the element is an unknown inline element with no size, and the content below it moves down when it gets its box (CLS 0.03 for one sprite, see [performance.md](performance.md#load-impact)). To reserve the space from the first paint, put this in the page's CSS, with one line for each `size` you use:
186
+
187
+ ```css
188
+ pixel-sprite:not(:defined) { display: inline-block; vertical-align: bottom; width: 128px; height: 128px; }
189
+ pixel-sprite:not(:defined)[size="64"] { width: 64px; height: 64px; }
190
+ ```
191
+
192
+ The first line matches the element's own style once it is defined (`vertical-align: bottom` matters for a sprite inside a line of text) and its default `size`.
193
+ - **Lazy loading.** See [below](#lazy-loading).
184
194
  - **Races.** Each load carries a token; a load that is overtaken by a newer `src` is dropped. A new bundle, its variant and its sheet are committed together, so no frame ever sees a bundle with an animation from another one.
185
195
  - **Shared work.** Bundles are fetched once per URL and each variant sheet is decoded once (into an `ImageBitmap` where supported) and shared by every sprite that uses it.
186
196
  - **Not JSON.** A server that answers a missing bundle with an HTML page (a common single-page-app fallback) gets a `pixel-error` naming the URL and saying it got HTML, rather than a bare JSON parse error.
187
197
  - **Sheets on another origin.** Sheets that are not data URLs (`pixel bundle --external`) are loaded with `crossOrigin="anonymous"`. If they live on another origin (a CDN), it must send `Access-Control-Allow-Origin`; otherwise skins stored as deltas, `hitTest` and `topAt` cannot read the pixels.
188
198
  - **Content Security Policy.** Bundles with data-URL sheets (the default) need `img-src data:`; fetched bundles need `connect-src` for their URL. For a strict CSP, build bundles whose `image` fields point at separate PNG files.
189
199
 
200
+ ### Lazy loading
201
+
202
+ A sprite fetches its bundle and decodes its sheet as soon as it is in the document, even far below the fold. For
203
+ characters further down a long page, add `loading="lazy"`:
204
+
205
+ ```html
206
+ <pixel-sprite src="fox.bundle.json" size="64" alt="A fox" loading="lazy"></pixel-sprite>
207
+ ```
208
+
209
+ - **When it loads.** A second shared `IntersectionObserver`, with a margin of one viewport, starts the load when the
210
+ sprite comes within one screen height (or width) of the visible area, so it is usually ready by the time it scrolls
211
+ in. Until then nothing is fetched or decoded, its box is reserved from `size`, fallback content (a poster) shows,
212
+ and `status` stays absent (`el.status` is `'idle'`).
213
+ - **Once is enough.** After it has come near once, the sprite behaves like an eager one: a later `src` change or
214
+ `reload()` loads at once, wherever it is. While it waits, `src` changes and `reload()` only change what will be
215
+ loaded: the last `src` is fetched once.
216
+ - **Attributes set while it waits apply when it loads** (`anim`, `size`, `skin`, `paused` and `pause()`, `rate`, ...),
217
+ and `pixel-ready` fires as usual. `play()`, `set()` and `fire()` need the bundle, as for any sprite before
218
+ `pixel-ready`: they do nothing (`play()` returns `false`); set `anim` instead, or call them from a `pixel-ready`
219
+ listener.
220
+ - **Removed while it waits**, it stops being watched; put back, it waits again.
221
+ - **Hidden sprites** (`display: none`, or inside a closed `<details>`) never intersect, so they wait until shown.
222
+ - **Without `IntersectionObserver`** (very old browsers) a lazy sprite loads at once.
223
+ - **Off-screen pausing and reduced motion** work as before, once it has loaded.
224
+ - **Not for stage actors.** `<pixel-actor>` does not pass `loading` on: an actor always loads at once, because the
225
+ stage needs its size and animations to place it and route it, and it walks on and off the screen. To delay a
226
+ whole stage, add the `<pixel-stage>` element (or its script) later, for example in a `load` event listener.
227
+
190
228
  ## Animation playback
191
229
 
192
230
  All sprites on a page share one frame loop (the exported `clock`). It runs only while something is subscribed. Each frame it computes one `dt` (ms since the last frame, capped at `clock.maxDt` = 100 ms) and passes it to every subscriber. The next frame is requested before subscribers run, and each subscriber runs in its own `try`/`catch`: a sprite that throws goes to `state="error"` and leaves the loop, and every other sprite keeps playing. `dt` restarts from 0 when the page becomes visible again or is restored from the back/forward cache.
@@ -308,7 +346,7 @@ goose.addEventListener('pixel-statechange', (e) => console.log(e.detail.from, '
308
346
  | `transitions[].from` / `to` | A node, a list of nodes, or `"*"`. The first matching transition wins. |
309
347
  | `transitions[].when` | `name`, `!name`, or `name op value` (`== != > < >= <=`), joined with `&&` or `and`. A value is a number, `true`, `false`, or a word, quoted or not (`mood == happy`, `mood == 'happy'`). No `when`: always true. |
310
348
  | `transitions[].at` | When to switch: `now` (default), `end` (when the animation finishes or loops), `sync` (keep the cycle's phase: walk → run without a hitch), or an event name such as `footstep`. A waiting switch is dropped if its condition stops being true. |
311
- | `interactions` | `on`: `click` (taps too), `enter`, `leave` (mouse and pen), `burst` (a quick run of clicks), `calm` (the run is over); then `fire` a trigger and/or `set` inputs (`"$count"`, `"$rate"` take the burst's values). They replace `hover-anim` and `click-anim`. |
349
+ | `interactions` | `on`: `click` (taps too), `enter`, `leave` (mouse and pen; on touch screens a tap enters and leaves 3 s after the last tap, see [Touch screens](#touch-screens)), `burst` (a quick run of clicks), `calm` (the run is over); then `fire` a trigger and/or `set` inputs (`"$count"`, `"$rate"` take the burst's values). They replace `hover-anim` and `click-anim`. |
312
350
 
313
351
  `play()` still works and overrides the machine until its next transition. While the machine runs, changes to the
314
352
  `anim` attribute are ignored. `states="off"` turns the machine off. The machine is a plain class, exported as
@@ -381,14 +419,25 @@ To keep the pixels aligned when you move a sprite, round positions to device pix
381
419
  - **Reduced motion.** While `prefers-reduced-motion: reduce` matches, no sprite steps through frames: looping animations show frame 0. One-shots and non-looping animations are not left hanging: a one-shot shows its middle frame, a non-looping animation its last frame, and after the animation's nominal duration (`frames / fps`) the element fires `pixel-end` and moves on as usual. The setting is watched live: turning it on or off takes effect immediately.
382
420
  - **Off-screen.** One shared `IntersectionObserver` (with a 50 px margin, so sprites start just before they scroll in) takes sprites out of the frame loop while they are off-screen. They resume from the same frame. A one-shot started off-screen still ends (and fires `pixel-end`) after its duration, as under reduced motion.
383
421
  - **Removed from the document.** The sprite leaves the frame loop and the observer. If it is put back (for example, moved to another container), it resumes where it was instead of reloading.
422
+ - **Loading is eager by default.** Off-screen sprites stop drawing, but a sprite fetches its bundle and decodes its sheet as soon as it is connected, even far below the fold, unless it has [`loading="lazy"`](#lazy-loading). [performance.md](performance.md) has the measured costs (download, time per frame, memory).
384
423
 
385
424
  ## Touch screens
386
425
 
387
- On touch screens `pointerenter` and `pointerleave` fire around every tap, so a hover animation would only flash while the finger is down. The element therefore:
426
+ On touch screens `pointerenter` and `pointerleave` fire around every tap, so a hover animation would only flash while the finger is down. The element therefore gives every interaction a touch equivalent:
388
427
 
389
- - runs `hover-anim` on hover only for mouse and pen pointers;
390
- - on a tap, plays `click-anim` once, or, if there is none, plays `hover-anim` once, so touch users see it too;
391
- - never calls `preventDefault` and does not set `touch-action`, so sprites never block scrolling.
428
+ | interaction | mouse and pen | touch |
429
+ |---|---|---|
430
+ | `hover-anim` | plays while the pointer is over the sprite | a tap plays it once (when there is no `click-anim`) |
431
+ | `click-anim` | a click plays it once | a tap plays it once |
432
+ | state machine `enter` / `leave` | the pointer comes over the sprite / leaves it | a tap is `enter` (then `click`); `leave` follows 3 s after the last tap (`TOUCH_HOVER_MS`), so a state like goose-root's `hovered` (it hacks) lasts long enough to see |
433
+ | state machine `click` | a click | a tap |
434
+ | bursts (`pixel-burst`, `pixel-calm`, `burst` / `calm` interactions) | quick clicks | quick taps, the same counts and timing |
435
+
436
+ - The sprite never calls `preventDefault` and does not set `touch-action`, so sprites never block scrolling or zooming.
437
+ - A sprite is an image (`role="img"`, or `aria-hidden` when decorative) and takes no keyboard focus. If an animation is
438
+ something a reader should be able to trigger, put the sprite in a `<button>` and call `play()` from its click handler:
439
+ the button gets keyboard, screen reader and touch support for free.
440
+ - Characters on a [`<pixel-stage>`](stage.md#interactions-on-every-device) can also be picked up and thrown by touch: press and hold.
392
441
 
393
442
  Make tappable sprites at least 44 × 44 CSS px, or give them padding.
394
443
 
@@ -538,6 +587,16 @@ Inline in text:
538
587
  <style>.inline-sprite { vertical-align: -6px; }</style>
539
588
  ```
540
589
 
590
+ Far down a long page: nothing is fetched until it comes near, and its box is kept from the first paint:
591
+
592
+ ```html
593
+ <style>
594
+ pixel-sprite:not(:defined) { display: inline-block; vertical-align: bottom; width: 128px; height: 128px; }
595
+ pixel-sprite:not(:defined)[size="64"] { width: 64px; height: 64px; }
596
+ </style>
597
+ <pixel-sprite src="assets/fox.bundle.json" anim="walk" size="64" alt="Fox" loading="lazy"></pixel-sprite>
598
+ ```
599
+
541
600
  Created from script, with `play(..., { once: true })` (from `demo/flock.html`):
542
601
 
543
602
  ```js
@@ -553,7 +612,7 @@ sprite.play('honk', { once: true }); // returns to idle (or hover-anim) when d
553
612
 
554
613
  ## Bundle format `pixel-sprite/1`
555
614
 
556
- A bundle is one JSON object. It is produced by `buildBundle()` in [`src/core/bundle.js`](../src/core/bundle.js), by `pixel bundle` ([cli.md](cli.md#bundle)), by `npm run build:demo`, and by the studio's export button. Example (from `pixel bundle examples/goose-root.json`, 161 KB; abridged, images shortened):
615
+ A bundle is one JSON object. It is produced by `buildBundle()` in [`src/core/bundle.js`](../src/core/bundle.js), by `pixel bundle` ([cli.md](cli.md#bundle)), by `npm run build:demo`, and by the studio's export button. Example (from `pixel bundle examples/goose-root.json --views all`, 160 KB; abridged, images shortened):
557
616
 
558
617
  ```json
559
618
  {
@@ -604,7 +663,8 @@ A bundle is one JSON object. It is produced by `buildBundle()` in [`src/core/bun
604
663
  `turn@<view>` and `unturn@<view>` (one-shots from the side to that view and back) and, for views with a `look`,
605
664
  `look@<view>` (the side idle with the head turned). They are ordinary animations to the element: `play('idle@front')`.
606
665
  [`<pixel-stage>`](stage.md) uses them for `actor.face('viewer')`. Each view adds about a full set of rows to the
607
- sheets; `pixel bundle --views front` (or `--views none`) ships fewer. See
666
+ sheets, so `pixel bundle` leaves them out unless asked (`--views front`, `--views all`); `buildBundle` keeps them
667
+ all unless given `views`. See
608
668
  [figures.md](figures.md#views-the-same-character-from-other-angles).
609
669
 
610
670
  ### Top level
package/docs/stage.md CHANGED
@@ -18,6 +18,8 @@ Demo: `npm run studio` and open `http://localhost:5173/demo/stage.html`. The des
18
18
  - [What the characters do](#what-the-characters-do)
19
19
  - [What a character needs from its bundle](#what-a-character-needs-from-its-bundle)
20
20
  - [How it works](#how-it-works)
21
+ - [Rage taps and fast scrolls](#rage-taps-and-fast-scrolls)
22
+ - [Interactions on every device](#interactions-on-every-device)
21
23
  - [Phones, accessibility and performance](#phones-accessibility-and-performance)
22
24
  - [Limits](#limits)
23
25
 
@@ -72,6 +74,7 @@ Layout tips, learned building the demo:
72
74
  | `label` | `character` or `characters` | The word on the button: "Pause characters" / "Play characters". Without it, the button says `character` when the stage has one actor. |
73
75
  | `floor` | `document` | `none`: no floor at the bottom of the page. |
74
76
  | `roam` | `viewport` | `page`: wander anywhere, not just near what is on screen. |
77
+ | `grab` | `on` | Who can pick characters up ([Interactions](#interactions-on-every-device)): `on` (a hold, or a mouse or pen drag), `mouse` (mouse and pen only, as in 0.2.0-alpha: a finger only taps, and the stage adds no touch listener), `off` (nobody; taps still shoo). Also `stage.grab`. |
75
78
 
76
79
  `<pixel-actor>`
77
80
 
@@ -135,7 +138,9 @@ stage.world.invalidate(); // after movi
135
138
 
136
139
  The module also exports `World`, `PixelStage`, `PixelActor`, `checkScene(scene, castNames?)`, `runScene(scene, env)`,
137
140
  `sceneEventName(name, onActorOrStage)` (a scene's short event name → the DOM event it listens to),
138
- `jumpArc(x0, y0, x1, y1, lift, seconds)` and `cells(rects, w, h)`.
141
+ `jumpArc(x0, y0, x1, y1, lift, seconds)`, `cells(rects, w, h)`, and the gesture logic behind
142
+ [Interactions](#interactions-on-every-device): `GESTURE` (its timings and distances), `Gesture` (one press, without the DOM)
143
+ and `throwVelocity(samples, cap?, releaseT?)`.
139
144
 
140
145
  ### Events
141
146
 
@@ -145,9 +150,11 @@ with `pixel-`; `e.target` is the actor (or the stage).
145
150
  | on | event | `detail` | when |
146
151
  |---|---|---|---|
147
152
  | actor | `pixel-activity` | `{from, to}` | `actor.activity` changed (`idle` → `walking`, …). |
148
- | actor | `pixel-tap` | `{count}` | Tapped or clicked on its opaque pixels; `count` counts quick taps. |
149
- | actor | `pixel-burst` | `{count, rate}` | Rage taps (the third quick tap on): it panics. |
153
+ | actor | `pixel-tap` | `{count, pointerType}` | Tapped or clicked on its opaque pixels; `count` counts quick taps; `pointerType` is `mouse`, `pen` or `touch`. |
154
+ | actor | `pixel-burst` | `{count, rate, pointerType}` | Rage taps (the third quick tap on): it panics. |
150
155
  | actor | `pixel-calm` | none | The rage taps stopped. |
156
+ | actor | `pixel-grab` | `{pointerType}` | The reader picked it up (a hold, or a mouse or pen drag; see [Interactions](#interactions-on-every-device)). |
157
+ | actor | `pixel-throw` | `{vx, vy, pointerType}` | The reader let go: it flies at `vx`, `vy` px/s (0, 0 when it was let go still, or when the browser took the pointer). |
151
158
  | actor | `pixel-arrive` | none | The end of a `goTo`. |
152
159
  | actor | `pixel-land` | none | Landed from a jump or a fall. |
153
160
  | actor | `pixel-catchup` | `{from: {x, y}}` | Coming back into view (`keep-in-view`, `catchUp()`); `from` is where it was. |
@@ -168,6 +175,7 @@ actor's shadow root, so a listener on the actor (or above it) hears each thing o
168
175
 
169
176
  The old names still fire for one alpha release (without bubbling, as before) and will be removed after 0.2.0-alpha.
170
177
  Scenes keep their short names (`"waitFor": "tap"`, `"event": "arrive"`): they are mapped to the `pixel-` events.
178
+ `grab` and `throw` (added later) have no old name, but scenes can use them too.
171
179
 
172
180
  | Old | New |
173
181
  |---|---|
@@ -343,6 +351,18 @@ Everything the stage uses is baked into the bundle by the engine (see [runtime.m
343
351
  The figure library has presets for all of it (`jump`, `fall`, `sit`, `duck`, `peek`, `climb`; see [figures.md](figures.md)).
344
352
  List them in the spec's animations, for example `"jump": {"motion": "jump"}`.
345
353
 
354
+ Build an actor's bundle with what the stage uses, and its views if it should turn to the reader (`pixel bundle`
355
+ ships the side view only unless asked):
356
+
357
+ ```sh
358
+ npx pixel bundle goose.json --views all --anims stage --res 32 --out site/goose.bundle.json
359
+ ```
360
+
361
+ `--anims stage` keeps, for each role, the animation the stage plays (the first of the names in
362
+ [the roles table](#elements-and-attributes) the character has), with their views, turns and transitions; add the
363
+ names a scene plays itself (`--anims stage,hack`). Without `--views` the character still does everything except turn
364
+ (`face('viewer')` and `gaze` then do nothing). Sizes: [performance.md](performance.md#keeping-it-small).
365
+
346
366
  ## How it works
347
367
 
348
368
  - **The world is read rarely.** Element boxes are read in one batch only when something changed: a `ResizeObserver` on
@@ -353,15 +373,15 @@ List them in the spec's animations, for example `"jump": {"motion": "jump"}`.
353
373
  character's `transform`, `z-index` and `clip-path`, only when they changed.
354
374
  - **Occlusion** is a `clip-path: path(evenodd, …)` on the character: its box minus every occluder that overlaps it,
355
375
  split into disjoint cells so overlapping occluders don't cancel out, and rounded to device pixels. The page is not touched.
356
- - **Clicks go through.** The stage and its characters have `pointer-events: none`. A capture-phase listener tests taps
357
- against the character's opaque pixels (`hitTest`); only a tap on the character itself shoos it, and that one click does
358
- not reach the page.
376
+ - **Clicks go through.** The stage and its characters have `pointer-events: none`. Capture-phase listeners on the
377
+ document test presses against the character's opaque pixels (`hitTest`); only a tap on the character itself shoos it,
378
+ and that one click (the click of that press) does not reach the page.
359
379
  - **One clock.** Movement uses the same frame clock and `dt` as the sprites' frame stepping (see [runtime.md](runtime.md)).
360
380
 
361
381
  ## Rage taps and fast scrolls
362
382
 
363
- - **Rage taps.** Three or more quick taps or clicks on a character (each within 450 ms of the last) are a burst: the
364
- character panics. It plays and moves faster with every tap (1.35×, then +0.35 per tap, up to 3×), keeps running away
383
+ - **Rage taps.** Three or more quick taps or clicks on a character (each within 450 ms of the last, with a finger, a
384
+ mouse or a pen alike) are a burst: the character panics. It plays and moves faster with every tap (1.35×, then +0.35 per tap, up to 3×), keeps running away
365
385
  from the latest tap, and the actor fires `pixel-burst` `{count, rate}`. When the taps stop, it fires `pixel-calm` and slows down.
366
386
  Movement always scales with the playback rate, so the feet stay planted at any speed.
367
387
  - **Fast scrolls.** The stage tracks scroll speed (`stage.scrollSpeed`) and fires `pixel-fastscroll` and `pixel-scrollsettle`.
@@ -372,19 +392,62 @@ stage.addEventListener('pixel-fastscroll', () => goose.say('wait for me!'));
372
392
  goose.addEventListener('pixel-burst', (e) => { if (e.detail.count >= 8) goose.say('OK OK OK'); });
373
393
  ```
374
394
 
395
+ ## Interactions on every device
396
+
397
+ Every interaction works with a mouse, a pen and a finger, and fires the same events (with `pointerType` in the detail).
398
+ Only presses on a character's opaque pixels count; everything else reaches the page as usual.
399
+
400
+ | action | mouse | pen | touch | keyboard, screen reader | events |
401
+ |---|---|---|---|---|---|
402
+ | shoo | click | tap | tap | none (decorative) | `pixel-tap` |
403
+ | rage taps | 3+ quick clicks | 3+ quick taps | 3+ quick taps | none | `pixel-tap`, `pixel-burst`, `pixel-calm` |
404
+ | pick up | press and drag 6 px, or press still for 400 ms | same as mouse | press still for 400 ms (it may wobble 10 px) | none | `pixel-grab` |
405
+ | carry | move | move | move the finger (the page does not scroll) | none | `pixel-activity` (`dragged`) |
406
+ | throw | let go | let go | lift the finger | none | `pixel-throw` `{vx, vy}` |
407
+ | scroll the page | wheel | as the device does | swipe, also one that starts on a character | as usual | none |
408
+ | pause everything | the pause button | the pause button | the pause button | the pause button (a `<button>` in the tab order) | none |
409
+
410
+ - **Picking up.** Press on a character and keep still for 400 ms (`GESTURE.holdMs`), or with a mouse or pen just drag it:
411
+ it is lifted (it dangles, using its `fall` animation), and on Android phones the device gives a short buzz
412
+ (`navigator.vibrate`; iOS has none). Then it follows the pointer, and letting go throws it with the speed of the last
413
+ 100 ms of movement (capped at 30 of its heights a second): it flies, falls and lands on the first surface below. Let go
414
+ without moving and it simply drops. A press that is neither a tap nor a hold does nothing.
415
+ - **Why touch waits.** A finger that moves more than 10 px before the 400 ms are up is scrolling: the stage lets it go and
416
+ the page scrolls as it always does. Only after a completed hold does the stage cancel `touchmove`, so the finger carries
417
+ the character instead of the page. Nothing calls `preventDefault` on `pointerdown` or `touchstart` for touch, and
418
+ `touch-action` is never set. For this the stage keeps one non-passive `touchmove` listener on the document, which does
419
+ nothing unless a character is held. It is there only while a finger can pick a character up (`grab="on"`, not paused,
420
+ no reduced motion), and it has a small cost: in Chrome a swipe anywhere on the page starts scrolling about one frame
421
+ (16 ms) later (measured in [performance.md](performance.md#touch-scrolling)). It cannot be added only once a hold
422
+ begins, because WebKit decides when a touch starts whether its moves can be cancelled (by its design; Chrome does
423
+ honour a listener added mid-gesture). `grab="mouse"` or
424
+ `grab="off"` removes it.
425
+ - **No long-press side effects.** While a finger or pen rests on a character, the page's `user-select` and
426
+ `-webkit-touch-callout` are `none` (no text selection, magnifier or link callout on iOS), and the context menu of a long
427
+ press is suppressed. The page's own inline values come back when the press ends or turns into a scroll. Mouse
428
+ right-clicks are never touched.
429
+ - **When the browser takes the pointer** (`pointercancel`: a system gesture, a scroll that began), a held character
430
+ drops where it is (`pixel-throw` with 0, 0). A second finger while waiting for a hold is a pinch: no pick-up.
431
+ - **Off while paused, under reduced motion, or with `grab="off"`** (and for fingers with `grab="mouse"`): picking up
432
+ is off, nothing special happens on a long press, and taps still shoo.
433
+ - **Keyboard and screen readers.** The characters are decorative: their layer is `aria-hidden`, and they take no focus,
434
+ because a moving focus target that runs away when activated would be a trap, not a control. The accessible control is
435
+ the pause button. If a character's reaction matters to your page, give the page a real button that calls
436
+ `actor.shoo()` or `actor.say()`.
437
+
375
438
  ## Phones, accessibility and performance
376
439
 
377
- - Touch works like a mouse click: a tap on a character shoos it. Characters never call `preventDefault` on touch and never
378
- set `touch-action`, so scrolling and zooming are unaffected.
379
- - With a mouse or pen, press on a character and drag to pick it up (it dangles, using its `fall` animation); let go to
380
- throw it with the pointer's speed. It flies, falls and lands on the first surface below. A press without a drag is a
381
- click, which shoos it. Dragging is off while paused or under reduced motion. Touch never drags, so a finger on a
382
- character still scrolls the page.
440
+ - Every interaction works by touch (see [Interactions on every device](#interactions-on-every-device)); scrolling and
441
+ zooming are unaffected, also when a swipe starts on a character.
383
442
  - The pause button is a real `<button>` in the tab order, above the characters, clear of the iPhone home indicator. The
384
443
  choice is stored in `localStorage` (`pixel-stage:paused`). This is what WCAG 2.2.2 (Pause, Stop, Hide) asks for.
385
444
  - With `prefers-reduced-motion: reduce` the characters are placed and stand still; the setting is watched live.
386
445
  - The characters' layer is `aria-hidden`; the button is not.
387
- - Checked in desktop Chromium and in iOS 18.1 Safari (iPhone 16 simulator).
446
+ - Checked in desktop Chromium and in iOS 18.1 Safari (iPhone 16 simulator). The touch gestures were checked with real
447
+ touch input in Chromium (Pixel 7 emulation: a swipe from a character scrolls, a hold picks up and does not scroll) and
448
+ in WebKit (iPhone 13 emulation: taps; a hold, drag and throw from synthesized pointer events).
449
+ - What a stage costs (the two runtime files, each actor's bundle, main-thread time per frame while they walk, memory)
450
+ is measured in [performance.md](performance.md), with ways to make bundles smaller.
388
451
 
389
452
  ## Limits
390
453
 
package/examples/fox.json CHANGED
@@ -7,7 +7,7 @@
7
7
  "tail2": {"from": [25, 49], "to": [18, 30], "follow": {"freq": 2.8, "damping": 0.35, "amount": 0.6, "max": 20}},
8
8
  "neck": {"from": [60, 57], "to": [64, 49]},
9
9
  "head": {"from": [64, 49], "to": [86, 52]},
10
- "ear": {"from": [73, 34], "to": [72, 15]}
10
+ "ear": {"from": [60, 34], "to": [58, 14]}
11
11
  }
12
12
  },
13
13
  "size": [100, 100],
@@ -55,15 +55,15 @@
55
55
 
56
56
  {"id": "neck", "shapes": [{"type": "capsule", "x1": 60, "y1": 57, "x2": 64, "y2": 49, "r": 7, "material": "fur"}]},
57
57
  {"id": "head", "shapes": [
58
- {"type": "polygon", "points": [[56, 38], [57, 16], [68, 32]], "r": 1.5, "material": "fur", "shade": -0.3},
58
+ {"type": "polygon", "points": [[65, 33], [73, 16], [78, 34]], "r": 1.5, "material": "fur", "shade": -0.3},
59
59
  {"type": "circle", "cx": 66, "cy": 44, "r": 14, "material": "fur"},
60
60
  {"type": "polygon", "points": [[72, 42], [86, 50], [85, 54], [72, 55]], "r": 2, "material": "fur"},
61
61
  {"type": "polygon", "points": [[56, 52], [68, 50], [86, 54], [78, 59], [60, 60]], "r": 2, "material": "cream"},
62
62
  {"type": "circle", "cx": 86, "cy": 51, "r": 2.2, "material": "nose"}
63
63
  ]},
64
64
  {"id": "ear", "shapes": [
65
- {"type": "polygon", "points": [[63, 34], [72, 14], [79, 35]], "r": 1.5, "material": "fur"},
66
- {"type": "polygon", "points": [[69, 31], [72, 21], [75, 31]], "material": "cream", "minDetail": 3}
65
+ {"type": "polygon", "points": [[51, 36], [58, 14], [68, 33]], "r": 1.5, "material": "fur"},
66
+ {"type": "polygon", "points": [[56, 32], [58, 21], [62, 31]], "material": "cream", "minDetail": 3}
67
67
  ]},
68
68
  {"id": "eye", "bone": "head", "pivot": [72, 42], "shapes": [
69
69
  {"type": "ellipse", "cx": 72, "cy": 42, "rx": 2.6, "ry": 3.6, "material": "eye"},
@@ -17,9 +17,9 @@
17
17
  "skins": {
18
18
  "party": {
19
19
  "materials": {"partyHat": {"color": "#ff5fa2", "texture": "stripes", "textureStrength": 0.5}, "pompom": {"color": "#ffd84a"}},
20
- "parts": [{"id": "hat", "parent": "head", "pivot": [68, 19], "z": 8, "shapes": [
21
- {"type": "polygon", "points": [[62.5, 20], [73.5, 20], [69, 6]], "material": "partyHat"},
22
- {"type": "circle", "cx": 69, "cy": 6, "r": 2.4, "material": "pompom"}
20
+ "parts": [{"id": "hat", "parent": "head", "pivot": [64, 17], "z": 8, "shapes": [
21
+ {"type": "polygon", "points": [[59.5, 17.5], [68.5, 17.5], [64.5, 4]], "material": "partyHat"},
22
+ {"type": "circle", "cx": 64.5, "cy": 4, "r": 2.4, "material": "pompom"}
23
23
  ]}]
24
24
  },
25
25
  "redteam": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pixel-studio/core",
3
- "version": "0.2.0-alpha.2",
3
+ "version": "0.2.0-alpha.3",
4
4
  "description": "Agents describe characters as JSON rigs; a zero-dependency engine renders them as pixel-art animations at every level of detail, with realistic skeleton motion; websites play them with one tag.",
5
5
  "keywords": [
6
6
  "pixel-art",
@@ -47,7 +47,7 @@
47
47
  "test": "node --test test/*.test.mjs"
48
48
  },
49
49
  "dependencies": {
50
- "@pixel-studio/runtime": "0.2.0-alpha.2"
50
+ "@pixel-studio/runtime": "0.2.0-alpha.3"
51
51
  },
52
52
  "engines": {
53
53
  "node": ">=20"
@@ -18,11 +18,14 @@ const r2 = (v) => Math.round(v * 100) / 100;
18
18
  * encode(w, h, rgba) → PNG data URL. Supplied by the host (canvas in browsers, zlib in Node).
19
19
  * views: which extra views to ship (["front"]; [] or false: the side view only; default all): each
20
20
  * view roughly adds a full set of animations to the sheets.
21
+ * animations: which animations to ship (["idle", "waddle"], or "stage" for what <pixel-stage> uses; default all),
22
+ * with what they need (see selectAnimations). States nodes that play a dropped animation are pruned.
21
23
  * deltas: store a skin as a change to the default sheet when smaller (default true).
22
24
  */
23
- export async function buildBundle(compiled, { resolutions = [16, 32, 64], overrides = {}, encode, views, deltas = true } = {}) {
24
- compiled = keepViews(compiled, views);
25
+ export async function buildBundle(compiled, { resolutions = [16, 32, 64], overrides = {}, encode, views, animations: only, deltas = true } = {}) {
25
26
  if (typeof encode !== 'function') throw new Error('buildBundle needs an encode(w, h, rgba) function that returns an image URL (see encodePNG for Node)');
27
+ if (only != null) compiled = keepAnimations(compiled, selectAnimations(compiled, only));
28
+ compiled = keepViews(compiled, views);
26
29
  const variants = [];
27
30
  let animations = null, top = null;
28
31
  const sheets = new Map();
@@ -59,7 +62,9 @@ export async function buildBundle(compiled, { resolutions = [16, 32, 64], overri
59
62
  const bundle = { format: BUNDLE_FORMAT, name: compiled.name, size: compiled.size,
60
63
  ground: compiled.ground ?? groundFromPixels(top, compiled.size), animations };
61
64
  if (compiled.skins) bundle.skins = Object.keys(compiled.skins);
62
- if (compiled.states) bundle.states = compiled.states;
65
+ // Fewer animations (or views) can leave state nodes with nothing to play: those go, with the transitions to them.
66
+ const states = compiled.states && pruneStates(compiled.states, animations);
67
+ if (states) bundle.states = states;
63
68
  const points = bakePoints(compiled);
64
69
  if (points) bundle.points = points;
65
70
  // A skin that moves the parts points ride on gets its own table (only when it differs).
@@ -107,6 +112,96 @@ export function keepViews(compiled, views) {
107
112
  return out;
108
113
  }
109
114
 
115
+ /**
116
+ * What <pixel-stage> looks up for each role, in order: the first one a character has is the one it plays.
117
+ * Keep in step with ROLES in packages/runtime/src/pixel-stage.js (a test compares them).
118
+ */
119
+ export const STAGE_ROLES = Object.freeze({
120
+ idle: ['idle'], walk: ['walk', 'waddle', 'trot', 'travel'], run: ['run', 'trot', 'travel', 'walk', 'waddle'],
121
+ rush: ['rush'], jump: ['jump'], fall: ['fall'], sit: ['sit'], duck: ['duck', 'sneak'], peek: ['peek'], climb: ['climb'],
122
+ react: ['honk', 'wave', 'hop'],
123
+ });
124
+
125
+ // Generated per view: the turns and the ¾ look. Every other "x@view" is the view's version of "x".
126
+ const VIEW_CLIP = /^((un)?turn|look)@/;
127
+
128
+ /**
129
+ * The names of the animations to ship for `wanted` (names, and/or "stage": the one <pixel-stage> plays for each
130
+ * role the character has), in spec order, with what they need to stay playable: each one's views ("idle@front"),
131
+ * the turns and look of every view that keeps an animation ("turn@front", "unturn@front", "look@front"), and the
132
+ * transitions between two kept animations ("waddle>idle"). Throws on a name the character does not have.
133
+ */
134
+ export function selectAnimations(compiled, wanted) {
135
+ const all = Object.keys(compiled.animations);
136
+ const own = all.filter((n) => !n.includes('@') && !n.includes('>'));
137
+ const list = typeof wanted === 'string' ? wanted.split(',') : wanted;
138
+ if (!Array.isArray(list)) throw new Error('animations must be a list of names, e.g. ["idle", "walk"] or ["stage"]');
139
+ const keep = new Set();
140
+ for (const raw of list) {
141
+ const w = String(raw).trim();
142
+ if (!w) continue;
143
+ if (w === 'stage' && !compiled.animations.stage) {
144
+ for (const names of Object.values(STAGE_ROLES)) { const n = names.find((x) => compiled.animations[x]); if (n) keep.add(n); }
145
+ // A stage without an idle stands in the first animation.
146
+ if (!STAGE_ROLES.idle.some((x) => compiled.animations[x]) && own.length) keep.add(own[0]);
147
+ continue;
148
+ }
149
+ if (!Object.hasOwn(compiled.animations, w)) throw new Error(`no animation "${w}" in ${compiled.name ?? 'this character'} (have: ${own.join(', ')}; or "stage" for what <pixel-stage> uses)`);
150
+ keep.add(w);
151
+ }
152
+ if (!keep.size) throw new Error(`no animations to keep (have: ${own.join(', ')})`);
153
+ const at = (n) => n.indexOf('@');
154
+ for (const n of all) if (at(n) > 0 && !n.includes('>') && !VIEW_CLIP.test(n) && keep.has(n.slice(0, at(n)))) keep.add(n);
155
+ const views = new Set([...keep].filter((n) => at(n) > 0 && !n.includes('>')).map((n) => n.slice(at(n) + 1)));
156
+ for (const n of all) if (VIEW_CLIP.test(n) && views.has(n.slice(at(n) + 1))) keep.add(n);
157
+ for (const n of all) if (n.includes('>')) { const [a, b] = n.split('>'); if (keep.has(a) && keep.has(b)) keep.add(n); }
158
+ return all.filter((n) => keep.has(n));
159
+ }
160
+
161
+ /** The compiled spec (and its skins) with only the named animations. */
162
+ export function keepAnimations(compiled, names) {
163
+ const keep = new Set(names);
164
+ const filter = (c) => ({ ...c, animations: Object.fromEntries(Object.entries(c.animations).filter(([n]) => keep.has(n))) });
165
+ const out = filter(compiled);
166
+ if (compiled.skins) out.skins = Object.fromEntries(Object.entries(compiled.skins).map(([k, sc]) => [k, filter(sc)]));
167
+ return out;
168
+ }
169
+
170
+ /**
171
+ * The state machine without the nodes whose animation is not in `animations` (and the transitions to or from only
172
+ * those, and random fidgets that play one). A node whose `then` was dropped goes back to the previous node instead;
173
+ * a dropped `initial` becomes the first node left. null when no node is left. Unchanged when nothing is dropped.
174
+ */
175
+ export function pruneStates(states, animations) {
176
+ const has = (n) => typeof n === 'string' && Object.hasOwn(animations, n);
177
+ const entries = Object.entries(states.nodes ?? {});
178
+ const kept = entries.filter(([, node]) => has(node?.anim));
179
+ const fidgetsOk = kept.every(([, node]) => !Array.isArray(node.random) || node.random.every((f) => has(f?.anim)));
180
+ if (kept.length === entries.length && fidgetsOk) return states;
181
+ if (!kept.length) return null;
182
+ const names = new Set(kept.map(([n]) => n));
183
+ const nodes = Object.fromEntries(kept.map(([n, node]) => {
184
+ const out = { ...node };
185
+ if (Array.isArray(node.random)) {
186
+ out.random = node.random.filter((f) => has(f?.anim));
187
+ if (!out.random.length) delete out.random;
188
+ }
189
+ if (out.then != null && out.then !== 'previous' && !names.has(out.then)) out.then = 'previous';
190
+ return [n, out];
191
+ }));
192
+ const out = { ...states, nodes };
193
+ if (states.initial != null && !names.has(states.initial)) out.initial = kept[0][0];
194
+ if (Array.isArray(states.transitions)) {
195
+ out.transitions = states.transitions.flatMap((t) => {
196
+ if (!names.has(t?.to)) return [];
197
+ if (t.from == null || t.from === '*') return [t];
198
+ const from = [].concat(t.from).filter((f) => f === '*' || names.has(f));
199
+ return from.length ? [{ ...t, from: Array.isArray(t.from) ? from : from[0] }] : [];
200
+ });
201
+ }
202
+ return out;
203
+ }
204
+
110
205
  /**
111
206
  * A skin sheet as a change to the default one: { recolor: [[from, to], ...] as "rrggbbaa" hex, overlay?: rgba }.
112
207
  * Each default colour is swapped for the skin colour it most often becomes; the overlay holds the pixels