rig-play 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,685 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="assets/banner.svg" alt="rig-play - plays rigc's compiled model as DOM elements or one canvas" width="100%" />
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ <p align="center">
6
+ <a href="https://www.npmjs.com/package/rig-play"><img src="https://img.shields.io/npm/v/rig-play.svg?style=flat-square&color=FF6B4A" alt="npm version" /></a>
7
+ <a href="https://www.npmjs.com/package/rig-play"><img src="https://img.shields.io/npm/dm/rig-play.svg?style=flat-square&color=EC4899" alt="npm downloads" /></a>
8
+ <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-38BDF8.svg?style=flat-square" alt="license" /></a>
9
+ </p>
10
+
11
+ Plays the rigs [rigc](https://github.com/firejune/rigc) builds — the compiled model
12
+ document `rigc build` writes, `skeleton.model.json` — as **plain DOM**: one
13
+ absolutely-positioned `<img>` per rigid slot, posed with a single CSS `matrix()` write
14
+ per frame, deforming meshes on small per-part canvases; or as **one canvas** per player.
15
+ `spine-html` is the same package under the name it first shipped as.
16
+
17
+ ## Why
18
+
19
+ The package began in 0.x as `spine-html`, an experiment in drawing Spine skeletons
20
+ without a canvas. Every Spine web runtime rasterizes into one, yet the pose itself is
21
+ computed on the CPU, and for a **region attachment** (a rigid part) the bone transform is
22
+ a plain affine map that CSS `transform: matrix()` expresses *exactly* — so the rigid tier
23
+ could live in the DOM, composited by the browser, inspectable in devtools, styled with
24
+ CSS. The idea had been floated on the Spine forum three times since 2014 and never built;
25
+ the blockers named were meshes, clipping and DOM update overhead, and the 0.x line
26
+ answered each of them (per-part mesh canvases, element-level `clip-path`, dirty-skip).
27
+
28
+ At 1.0 it stopped being a Spine runtime. It plays the model document `rigc build` writes,
29
+ poses it through `rig-c/core` — rigc's own posing core, bundled into the package — and
30
+ links nothing from Esoteric Software; a Spine export is refused by name. It gained a
31
+ second render mode that draws the whole frame into one canvas. And it took the name
32
+ `rig-play`, which says what it is; `spine-html` keeps being published with the same
33
+ files, so links to the old name keep working.
34
+
35
+ ### Measured
36
+
37
+ Measured on the 0.x line, on the spineboy exports it then played (PoC, Apple silicon —
38
+ headless and on-device numbers are labeled, they do **not** substitute for each other).
39
+ The renderer tiers they describe carried over; they have not been re-measured since the
40
+ player moved to rigc's model (#60):
41
+
42
+ - Rigid only (spineboy-ess), headless Chromium: 10 skeletons / 180 slot images at
43
+ **~0.03 ms skeleton math + ~0.22 ms DOM writes per frame** — about 1.5% of a
44
+ 60 fps frame budget. On-device Safari: 10 rigid skeletons hold **60 fps**.
45
+ - With meshes (spineboy-pro), headless Chromium: 1 skeleton = **~0.05 ms + ~0.5 ms
46
+ render** (8 mesh canvases, 323 triangles); 10 running skeletons = **~3.5 ms/frame**
47
+ total, smooth.
48
+ - Dirty-skip: 10 *static* skeletons (pose held) = **~0.4 ms/frame** headless and
49
+ **~0.6 ms** on-device Safari — unchanged meshes reuse their raster, so idle or
50
+ held parts cost nothing anywhere.
51
+ - Real Safari (on-device), canvas2d mesh backend: in-callback JS stays **~4–5
52
+ ms/frame** for 10 running meshed skeletons — but the rAF rate tells the real
53
+ story: **meshed ×1 = 37 fps, meshed ×10 = 3–4 fps** (rigid-only ×10 = 60 fps).
54
+ The cost lives outside the frame callback, in the compositor/GPU process:
55
+ Safari antialiases canvas2d **clip paths**, so every triangle pays for an AA
56
+ mask. Chromium doesn't antialias clips and stays smooth. This is what the
57
+ optional WebGL mesh backend (below) removes.
58
+ - Real Safari (on-device), **webgl mesh backend**: meshed ×1 holds **60 fps**
59
+ (vs 37 on canvas2d), and the meshed ×10 stress scene jumps **3–4 → 45 fps** —
60
+ 80 mesh canvases / 3230 triangles redrawn every frame (0 reused, the worst
61
+ case), in-callback JS ~5.8 ms at dpr=1. The per-triangle clip-AA tax is gone;
62
+ the remaining gap to 60 is the blit/compositing cost of a 10-skeleton stress
63
+ scene, not a per-triangle cost.
64
+ - Headless-WebKit numbers are a **software rasterizer** and measured up to 28×
65
+ off real Safari in both directions — useful for visual regression only, never
66
+ as Safari perf evidence.
67
+
68
+ ## Status
69
+
70
+ **Production.** The questions this started as a PoC to answer — how far does the
71
+ DOM actually go, and how cheap is it — are answered with on-device numbers: the
72
+ practical scenario (a character or two, mostly holding pose, a few parts
73
+ deforming) holds **60 fps on every engine measured**, and the 10-skeleton
74
+ stress scene holds 45 fps on the weakest one (Safari, webgl backend). Ships
75
+ with a self-contained test suite (backend visual parity + invariants) and CI.
76
+
77
+ **Two render modes.** `mode: 'dom'` (the default, everything below) draws a rig
78
+ as elements. `mode: 'canvas'` draws the whole frame into **one `<canvas>`** per
79
+ player: every slot as textured triangles from its atlas page through the same
80
+ shared WebGL context the mesh tier's `webgl` backend uses, into one rect, then
81
+ one `drawImage` onto the player's canvas. Tint and dark (two-colour) tint are
82
+ vertex colours, blend modes are batch state, clips are cut on the CPU by
83
+ `rig-c/core`'s clipper — no `clip-path`, no SVG filter, no per-slot element.
84
+ `RigPlayer` swaps between the two in place (`player.mode = 'canvas'`). The
85
+ canvas mode is held against the DOM tier pixel for pixel on the parity suite's
86
+ frozen poses (bad pixels ≤ 1.6% of drawn content, measured, macOS Chromium and
87
+ WebKit); which mode is faster where is **not measured on a device yet**, so the
88
+ default stays `dom`.
89
+
90
+ - ✅ Region attachments (rigid parts): exact affine mapping, draw-order via `z-index`,
91
+ attachment swaps, alpha
92
+ - ✅ Atlas unpacking at load time (90°-packed regions restored to the orientation
93
+ the region's UVs name, held against hand-written UVs on a rigc build whose region
94
+ is packed turned),
95
+ so the rigid per-frame path never touches a canvas — a region that covers its whole
96
+ page is passed through uncut, and `revokeRegions()` frees the rest when a skeleton
97
+ is unloaded
98
+ - ✅ Mesh attachments (deform tier): small per-part canvases sized to the mesh's world
99
+ bounds, interleaved with the rigid `<img>` slots in one stacking context — the DOM
100
+ handles the bones, a rasterizer handles the warps
101
+ - ✅ Blend modes via `mix-blend-mode` (additive = `plus-lighter`)
102
+ - ✅ Crack-free mesh seams on clip-antialiasing browsers (Safari): each triangle's
103
+ clip polygon is expanded 0.5px from its centroid so neighbours overlap — the
104
+ texture is continuous across shared edges, so the overlap is invisible
105
+ (`?expand=0` shows the cracks for comparison)
106
+ - ✅ RGB tinting (skeleton × slot × attachment color) via an SVG `feColorMatrix`
107
+ reference filter per element — an exact channel multiply that works identically on
108
+ `<img>` and `<canvas>` without touching the raster (needs reference-filter support,
109
+ Safari 15+; verified pixel-level on Chromium and WebKit). Dark/two-color tint is
110
+ not expressible this way and stays out of scope
111
+ - ✅ DPR-aware mesh canvas backing store: `renderer.pixelRatio` (defaults to
112
+ `devicePixelRatio`; if you scale the root element, fold that scale in)
113
+ - ✅ Dirty-skip: a mesh whose canvas-space vertices didn't change reuses last frame's
114
+ raster — the CSS translate still tracks it, so parts that hold a pose (or move by
115
+ whole pixels) pay zero raster. 10 frozen spineboys: WebKit ~141 → ~0.5 ms/frame
116
+ - ✅ Clipping attachments as element-level CSS `clip-path`: spine-core's semantics
117
+ (one active clip at a time, applied from the clip's slot through its end slot
118
+ inclusive), with the polygon expressed in each element's own local frame — the
119
+ inverse of the `<img>` matrix for rigid slots, the canvas translate for mesh
120
+ slots. Covers **part masks** (a clip with a real end slot, like the figure test
121
+ rig's `mask` animation) and **whole-skeleton clips** (an end slot that never
122
+ arrives, which takes a fast path: one `clip-path` on the root instead of one per
123
+ element). **Inverse clips** are supported too: the region they keep has a hole
124
+ in it, so it needs two rings, and `polygon()` carries only one — a box and a
125
+ polygon listed inside one `polygon()` become a single self-intersecting ring
126
+ whose even-odd fill leaves a wedge along the seam between them (measured, on a
127
+ corner of spineboy's boot). So an inverse clip is written as a two-subpath
128
+ `path(evenodd, …)` whose outer ring is the element's own box. The whole feature
129
+ is element-level, so both mesh backends see the same thing and neither raster
130
+ path knows clipping exists; `renderer.clipping = false`
131
+ restores the old counted-and-skipped behaviour. Concave polygons go to CSS as
132
+ authored — the convex decomposition spine's CPU clipper performs exists to feed a
133
+ triangle rasterizer and has no job here. Two things this does not do: Spine's
134
+ clipper convexifies an *inverse* polygon (convex hull) where CSS clips it as
135
+ authored, so the two agree exactly when that polygon is convex — which is the
136
+ shape `inverse` is meant for; and the cost of many simultaneous `clip-path`s on
137
+ real-device Safari is **not measured** (the headless numbers that exist are not
138
+ Safari evidence — see Measured above)
139
+ - ✅ Safari mesh cost root-caused by on-device triangulation (two corrections deep):
140
+ the early "~15× slower per-triangle path" was a **headless-WebKit artifact**
141
+ (software rasterization), and the follow-up "on par with Chromium" held only for
142
+ in-callback JS time. Real-Safari rAF rates — rigid ×10 = 60 fps, meshed ×1 =
143
+ 37 fps, meshed ×10 = 3–4 fps with JS flat at ~4–5 ms — put the real cost in the
144
+ GPU process: Safari antialiases canvas2d **clip paths**, so the per-triangle clip
145
+ mapping pays a per-triangle AA-mask tax (the same AA that caused the seam cracks)
146
+ - ✅ Optional WebGL blit backend for the mesh tier: `renderer.meshBackend =
147
+ 'webgl'` (default stays `'canvas2d'`). All dirty meshes are shelf-packed into
148
+ **one shared offscreen WebGL context** (module-level — browsers cap contexts at
149
+ ~16), drawn as textured triangles with premultiplied alpha, then rect-blitted
150
+ onto the same per-part canvases with an unclipped `drawImage` — cheap on Safari.
151
+ Everything element-level is unchanged: z-index interleave, tint filter,
152
+ `mix-blend-mode`, dirty-skip, grow-only backing. GL rasterizes shared triangle
153
+ edges seamlessly, so this path needs no crack overdraw. Falls back to canvas2d
154
+ when WebGL is unavailable or the context is lost. Backend parity verified by
155
+ headless Chromium+WebKit screenshot diffs (glow / clipping / tint scenes;
156
+ sub-pixel edge differences only). On-device Safari, meshed ×10 with every mesh
157
+ redrawn per frame: **3–4 fps (canvas2d) → 45 fps (webgl)**
158
+
159
+ ## Install
160
+
161
+ ```bash
162
+ npm i rig-play
163
+ npm i -D rig-c # the build tool: `rigc build` writes the model rig-play loads
164
+ ```
165
+
166
+ The package plays rigs built by [rigc](https://github.com/firejune/rigc):
167
+ `rigc build` writes a compiled model document, `skeleton.model.json` (spec
168
+ `rigc-compiled/3`), next to the Spine pair and the atlas pages. That document
169
+ is what the player loads, and it states everything posing and drawing need —
170
+ the skeleton, the animations, and where every region sits on its page — so the
171
+ `.atlas` and `skeleton.json` beside it are not fetched. Poses are computed by
172
+ `rig-c/core`, rigc's own posing core, which is bundled into this package: there
173
+ is nothing else to install.
174
+
175
+ ```ts
176
+ import { loadModel, RigPlayer } from 'rig-play';
177
+
178
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
179
+
180
+ // A positioned element becomes the rig's world origin (Y-up: the rig grows
181
+ // upward from it). Layout and scaling are the caller's.
182
+ const player = new RigPlayer(rootElement, assets);
183
+ player.play('walk'); // looping; { loop: false } holds at the end
184
+
185
+ function frame(delta: number) {
186
+ player.frame(delta); // step the track by delta × timeScale, draw
187
+ }
188
+
189
+ // Unloading (a cutscene ends, a level swaps): elements first, bitmaps second.
190
+ // The unpacked regions are blob URLs — nothing else frees them.
191
+ player.dispose();
192
+ assets.dispose();
193
+ ```
194
+
195
+ The player owns one track: `play(name, { loop })` opens an animation at its first
196
+ pose, `frame(dt)` steps it (or `advance(dt)` then `draw()`, to time the two
197
+ apart), `pause()` / `resume()` hold and release it, `timeScale` scales every
198
+ step, and `seek(t)` moves it to a time. A seek is "reopen, then step to the
199
+ time" in `seekStep` increments (1/60 s by default) — never a jump, because a
200
+ physics rig has history and its pose at a time depends on the steps that
201
+ reached it. `on('event', …)` receives the event keys each step crosses, in the
202
+ runtime's order across a loop's wrap; `on('complete', …)` fires once a step
203
+ completes a cycle. `skin` (a constructor option) poses under a named skin;
204
+ without it the rig is posed the way a fresh Spine skeleton is, with no skin
205
+ set. `player.color` multiplies a whole-rig colour into every slot's tint.
206
+ `player.renderer` is the `DomRenderer` underneath, whose knobs and counters
207
+ are below.
208
+
209
+ **What it refuses, by name.** A Spine export (`.json`, `.skel`) is refused
210
+ before anything is fetched: this package reads compiled models and nothing
211
+ else. A document whose `spec` is not one `rig-c/core` reads is refused with the
212
+ core's own sentence plus "build it with `rigc build`", and so is a
213
+ `rigc-compiled/1` document, which predates the `pages` section.
214
+
215
+ `rig-play` is a third-party renderer and is not affiliated with or endorsed by
216
+ Esoteric Software.
217
+
218
+ ### Drawing your own frames
219
+
220
+ `RigPlayer` is the convenient path; the renderer underneath takes a plain
221
+ record, so anything that can produce one can draw through it:
222
+
223
+ ```ts
224
+ import { DomRenderer, type PosedFrame } from 'rig-play';
225
+
226
+ const renderer = new DomRenderer(rootElement, assets.regionImages, assets.pageImages);
227
+ renderer.render(frame); // frame: PosedFrame
228
+ ```
229
+
230
+ ```ts
231
+ PosedFrame { order: PosedSlot[] } // the slots that draw, in draw order
232
+ PosedSlot = { slot; z; blend: 'Normal'|'Additive'|'Multiply'|'Screen';
233
+ tint: [r, g, b, a]; dark?: [r, g, b];
234
+ clip?: { polygon: number[]; inverse: boolean; convex: boolean } } // world space, Y up
235
+ & ( { kind: 'region'; region: string; corners: number[] /* BL, UL, UR, BR */;
236
+ page: string; pma: boolean; uvs: number[] /* page UVs at the corners */ }
237
+ | { kind: 'mesh'; page: string; pma: boolean; vertices: number[];
238
+ uvs: number[]; triangles: number[]; sequence: number } )
239
+ ```
240
+
241
+ `player.posedFrame()` returns the record the player would draw. Two things the
242
+ renderer reads off it by identity rather than by value: every slot a clip
243
+ covers carries the **same** `clip` object (one that covers every slot of the
244
+ frame takes the one-`clip-path`-on-the-root path), and a mesh's `uvs` and
245
+ `triangles` are the same arrays from frame to frame for the same texture
246
+ mapping (a new array re-rasters the mesh).
247
+
248
+ ### One load, several players
249
+
250
+ One `loadModel` backs any number of players: the regions are cut once, and
251
+ every player draws from the one `regionImages` map. A player owns none of it —
252
+ disposing a player leaves the bitmaps alive for the others — so there is exactly
253
+ one `assets.dispose()`, after the last player is gone:
254
+
255
+ ```ts
256
+ const assets = await loadModel({ modelUrl: '/rigs/walk/skeleton.model.json' });
257
+ const a = new RigPlayer(rootA, assets);
258
+ const b = new RigPlayer(rootB, assets, { skin: 'winter' });
259
+
260
+ a.dispose();
261
+ b.dispose();
262
+ assets.dispose();
263
+ ```
264
+
265
+ A document is one rig. Two rigs whose builds share page images load as two
266
+ documents; the images are fetched by URL, so a page both name at the same URL
267
+ is loaded once by the browser — but each load cuts its own regions and owns its
268
+ own blob URLs.
269
+
270
+ ### Loading it yourself
271
+
272
+ `loadModel` is a convenience over two calls the package exports: read the
273
+ document, load its pages, and cut the regions with `unpackRegions`, which takes
274
+ the document's `pages` section — `{ name, width, height, pma, regions: [{ name,
275
+ x, y, width, height, degrees }] }` per page — and a map of page images keyed by
276
+ those names. Use it when the page images do not come from a URL (`resolvePage`
277
+ on `loadModel` covers the ones that come from another URL), and pair it with
278
+ `revokeRegions` on unload.
279
+
280
+ A region the packer stored turned (`degrees: 90`) is cut upright again, and
281
+ which way round that is comes from the UVs a runtime assigns such a region,
282
+ not from the cut: its corners carry `(u2, v2), (u, v2), (u, v), (u2, v)` in the
283
+ order BL, UL, UR, BR, so the artwork's top-left corner sits at the packed rect's
284
+ bottom-left and unpacking it is a clockwise turn. Every release up to 0.7.0
285
+ turned it the other way and drew rotated rigid parts 180° round (#49).
286
+
287
+ `unpackRegions` mints one blob URL per region; `revokeRegions` is its
288
+ counterpart. It only frees URLs `unpackRegions` created, so a map you built
289
+ yourself and page images reused by the whole-page pass-through survive it — and
290
+ calling it twice is a no-op. Load once for the page's lifetime and you can
291
+ ignore it; load and unload repeatedly without it and you leak an atlas per
292
+ cycle.
293
+
294
+ ### Pages that ship at another resolution
295
+
296
+ A page image may ship at a resolution its document does not declare — a
297
+ half-resolution texture build, or an @2x variant, with the page's `width` and
298
+ `height` left as the build wrote them. Nothing here needs a flag for that. A
299
+ region's bounds are read **relative to the declared page size** and scaled onto
300
+ the image's natural size, which is how the page UVs the mesh tier samples with
301
+ are derived too (`u = x / page.width`), so both tiers land on the same pixels at
302
+ any resolution.
303
+
304
+ Each unpacked bitmap comes out at the **native resolution of the pixels it was
305
+ cut from** — half-resolution pages cost a quarter of the cut pixels, and
306
+ nothing is upscaled back — while `RegionImage.width`/`height` stay in **atlas
307
+ units**. Those two numbers are the `<img>` layout box and the denominator of
308
+ its CSS matrix, so the rig poses identically and the browser scales the
309
+ smaller bitmap into the same box, the way a GPU samples a smaller texture
310
+ through the same UVs. Ship one build and swap the images per device if you
311
+ like (`resolvePage`).
312
+
313
+ ### Premultiplied pages (`pma`)
314
+
315
+ A page's `pma` flag in the document's `pages` section — the build copies it from
316
+ the atlas's `pma: true` line — says its RGB is already multiplied by its alpha,
317
+ and nothing is asked of you: each tier is handed the page in the convention it
318
+ actually consumes. The `webgl` mesh backend uploads the texels unconverted (its
319
+ blend already expects premultiplied source — lossless). The DOM and canvas2d
320
+ tiers cannot: an `<img>` and `drawImage` composite straight alpha by definition,
321
+ so they read a straight-alpha derivation of the page —
322
+ `rgb = round(rgb * 255 / a)`, computed once and shared by the region cuts and
323
+ the mesh raster. Without it every semi-transparent texel is multiplied by its
324
+ alpha a second time and draws darker than it was authored: soft edges, soft
325
+ shadows, glows.
326
+
327
+ What it costs: **one page-sized canvas per premultiplied page image**
328
+ (width × height × 4 bytes — 1 MiB for a 1024×256 page, 16 MiB for a 2048×2048
329
+ one), alive as long as the page image is and released with it; the cache is
330
+ weak, so there is nothing to free by hand. A page without the flag derives
331
+ nothing. The division is 8-bit and starts from a canvas read, which has itself
332
+ quantized a premultiplied texel, so a very transparent texel can land a few
333
+ levels off — exact at alpha 0 and 255, within one level of 255 above alpha 128,
334
+ and a little more below that, by an amount that belongs to the browser's canvas
335
+ rather than to this package. It is invisible wherever the texel is: a texel at
336
+ alpha 11 is ~4% opaque. The `webgl` backend, having no such step, is exact.
337
+
338
+ One consequence worth knowing if your build is one part per page: a whole-page
339
+ region on a premultiplied page is **cut** rather than handed through, because
340
+ the page's own URL holds premultiplied pixels (see below).
341
+
342
+ ### What unloading frees
343
+
344
+ `revokeRegions()` — and `assets.dispose()`, which calls it — frees the blob URLs
345
+ `unpackRegions` minted, and nothing else. The page images are held by
346
+ `assets.pageImages` and by every player drawing from them, so a page is
347
+ released once you drop the assets and every player is disposed. With the
348
+ `webgl` mesh backend the shared blitter also uploads each page image on first
349
+ use, but that GL texture is not the module's forever: every renderer drawing
350
+ the page holds a reference to it, `player.dispose()` hands those back, and the
351
+ texture is deleted once the last renderer using that page is disposed — a later
352
+ frame that needs the page uploads it again. The cache is keyed weakly by the
353
+ page image, so a renderer dropped without `dispose()` costs GPU memory until
354
+ the context is lost, but never keeps the image itself alive.
355
+
356
+ A rig with meshes samples its page bitmaps every frame, so their decoded form
357
+ stays in use: a floor on the order of `page width × page height × 4` bytes per
358
+ page. A rigid-only rig draws nothing from the pages after `unpackRegions`, and
359
+ what a merely reachable, undrawn image costs is up to the browser, not
360
+ measurable from script.
361
+
362
+ Unload in this order:
363
+
364
+ 1. `player.dispose()`, for every player using the assets.
365
+ 2. `assets.dispose()` (or `revokeRegions(regionImages)`).
366
+ 3. Drop your references to the assets.
367
+
368
+ ### One part per page
369
+
370
+ `rigc build` writes one page per part by default — each part PNG is its own
371
+ page, its one region covering it — and `rigc build --pack` arranges the parts
372
+ onto shared pages instead. Both play here, unchanged:
373
+
374
+ - Regions that cover their whole page are handed straight through by
375
+ `unpackRegions` instead of being cut and re-encoded — at any image resolution,
376
+ since covering the page is a statement about the declared size. Load cost for
377
+ this shape is just the image loads. The exception is a page marked `pma`: its
378
+ URL holds premultiplied pixels, which an `<img>` would composite as straight
379
+ alpha, so those regions are cut from the straight-alpha derivation like any
380
+ other (and the blob is revoked by `revokeRegions` like any other).
381
+ - A packed build cuts every region from its page once, at load, and its meshes
382
+ sample the shared page through page UVs.
383
+
384
+ ### Runtime knobs and what they cost
385
+
386
+ - `player.mode` / `new RigPlayer(root, assets, { mode })` — `'dom'` (default)
387
+ or `'canvas'`. Changing it disposes the current renderer (elements removed,
388
+ GPU pages handed back) and creates the other over the same root and assets;
389
+ `pixelRatio` and `clipping` carry over and the held pose is redrawn at once.
390
+ `player.renderer` is then a `CanvasRenderer`, whose knobs are `pixelRatio`,
391
+ `clipping`, `viewport` and `backend`. What each mode costs, as counters:
392
+ - **dom** — one element per drawn slot, one style write per changed slot,
393
+ and the mesh tier's rasters (the knobs below).
394
+ - **canvas** — one canvas element per player and, per frame that changed,
395
+ one pass over every slot: `drawCalls` (one per run of one page under one
396
+ blend), `blendFlushes` (runs a blend change ended), `trianglesDrawn`,
397
+ `blits` (one), or `framesReused` (one) when the record did not change and
398
+ nothing is drawn. It never creates a WebGL context of its own, so any number
399
+ of players stays under the browser's ~16-context cap (20 players, one
400
+ context — `tests/canvas-mode.spec.ts`). The canvas covers a rect of the
401
+ root's coordinates that grows (never shrinks) to what the frames draw —
402
+ `canvasReallocCount` settles at zero — or a fixed `renderer.viewport` (world
403
+ units, Y up) when you set one. Blends are composed inside that canvas, which
404
+ starts transparent: an additive slot adds onto the slots under it and is
405
+ then composited onto the page normally, where the DOM tier's
406
+ `plus-lighter` adds onto the page itself. Where WebGL is unavailable or the
407
+ context is lost, the frame is drawn with canvas2d on the same canvas so it
408
+ never draws nothing — **alpha tint only, RGB and dark tint unsupported
409
+ there** — and that fallback is **not the measured path** (`backendActive`
410
+ says which ran).
411
+
412
+ - `renderer.pixelRatio` — mesh-canvas backing pixels per CSS pixel (defaults to
413
+ `devicePixelRatio`; if you scale the root element, fold that scale in so the
414
+ raster matches the screen: `devicePixelRatio * rootScale`). **Writing it
415
+ reallocates every mesh canvas backing store on the next frame**, and each
416
+ reallocation recreates a GPU surface — the cost that took real Safari to ~3 fps
417
+ when it happened per frame. Each canvas is then sized from what the new ratio
418
+ needs, in both directions: lowering the ratio gives the backing pixels back
419
+ (the backing is grow-only *within* a ratio, not across a change of one). Set
420
+ it when a layout settles, never per frame:
421
+ debounce resize drags and quantize the value instead of tracking it
422
+ continuously. `renderer.canvasReallocCount` is the check — it must fall back to
423
+ zero within a second or two.
424
+ - `renderer.syncPixelRatio()` — measures the root's effective on-screen scale
425
+ and sets `pixelRatio` to `devicePixelRatio × scale`, returning the ratio now
426
+ in effect. It appends a hidden 100 px box to the root, reads its box once and
427
+ removes it (the root itself is usually 0×0), so it is **one forced layout per
428
+ call** — which is exactly why the renderer never calls it for you: there is no
429
+ per-frame layout read anywhere in this library. Call it when a zoom or a
430
+ layout *settles* (gesture end, debounced resize), not during the drag. A
431
+ change under 0.1% is ignored, so layout jitter cannot churn GPU surfaces, and
432
+ a root that is not laid out (a `display: none` ancestor) leaves the ratio
433
+ alone. Under an ancestor rotation the measured box is inflated and the ratio
434
+ errs high — oversampling costs pixels, undersampling costs picture.
435
+ - `renderer.meshBackingPixels` — allocated mesh-canvas backing pixels
436
+ (Σ width × height), computed on demand. This is what `pixelRatio` moves
437
+ quadratically, and the cheapest way to see an oversampling stage; the demo
438
+ prints it in the stats line as `backing N Mpx`.
439
+ - `renderer.meshBackend` — `'canvas2d'` (default) or `'webgl'`; same output, but
440
+ heavy deforming scenes on Safari want `'webgl'` (see Measured above). Falls back
441
+ to canvas2d automatically when WebGL is unavailable. Switching re-rasters every
442
+ mesh once (no reallocation), so it is fine to expose as a user setting.
443
+ - `renderer.triangleExpand` — clip overdraw in px that closes antialiased mesh
444
+ seams (default 0.5). Also re-rasters every mesh once when changed.
445
+ - `renderer.clipping` — apply the clips the frame carries (default `true`).
446
+ Which slots a clip covers is decided where the frame is made — the player's
447
+ adapter walks the draw order the way the runtime's draw loop does (one clip in
448
+ force at a time, a second one met while one is in force ignored, the end slot
449
+ inside its own clip). What the renderer writes is one CSS `clip-path` per
450
+ element a clip covers, in that
451
+ element's own local frame; nothing reaches the raster backends, and a clip is
452
+ not part of the mesh dirty signature, so a mesh that held still keeps reusing
453
+ its raster under a moving clip. **Writes happen on change only**: each
454
+ clip-path is cached exactly as `transform` is, coordinates are quantized to
455
+ 1/1000 of a local unit so float jitter cannot defeat that cache, and a static
456
+ polygon over a static pose therefore costs **zero style writes per frame after
457
+ the first** — `renderer.clipWriteCount` is the check, alongside
458
+ `clipCount` (clips applied) and `clipSkipCount` (clips in the frame not
459
+ applied: switched off, or a degenerate polygon; a clip the runtime itself
460
+ ignores never reaches the frame). **The whole-skeleton fast path**: when one
461
+ clip covers every slot of the frame, one `clip-path` goes on the root instead
462
+ of one per element. The root is *your* element, so its inline `clip-path` is **borrowed,
463
+ not taken** — saved on the first write and put back verbatim when the clip
464
+ stops covering the frame, when `clipping` goes `false`, and by `dispose()`.
465
+ Per-element clip-paths and the root clip-path are never both in force for the
466
+ same clip. Two things to know about that path: the polygon is written in the
467
+ root's **border box** frame, which is where absolutely-positioned slot elements
468
+ start too *unless the root has a CSS border* (a border would offset the
469
+ whole-skeleton clip by its width — keep borders off the render root, which is
470
+ the normal shape for a 0×0 origin element); and an inverse clip never takes it,
471
+ because its CSS form needs an outer ring around a box and the root has none.
472
+ One further consequence of that path: a `clip-path` other than `none` makes an
473
+ element a stacking context (CSS Masking), so a whole-skeleton clip isolates
474
+ `mix-blend-mode` slots from backdrops *outside* the root — which a root
475
+ carrying a `transform` (the usual pan/zoom stage) already does. Per-element
476
+ clips do not change blending, since a blended slot is its own stacking context
477
+ either way. Setting `clipping = false` removes every clip-path this renderer
478
+ wrote.
479
+
480
+ **A zoomable stage.** The mesh tier rasters at `world × pixelRatio` in the
481
+ root's own coordinates, and it cannot see a CSS transform above the root — so
482
+ the most natural pan/zoom stage, `transform: scale(zoom)` on an ancestor, makes
483
+ it oversample by `1/zoom²` in backing pixels until the zoom is folded in. The
484
+ picture stays correct throughout, which is what makes this easy to ship: only
485
+ the allocation and the frame rate move. Call `syncPixelRatio()` when the zoom
486
+ settles, or set `pixelRatio = devicePixelRatio * zoom` yourself. Measured
487
+ on-device (Chromium, dpr 2, stage under `scale(0.25)`, ~2.2 M CSS px on screen):
488
+
489
+ | scene | `pixelRatio` | `meshBackingPixels` | fps |
490
+ | --- | --- | --- | --- |
491
+ | 57 meshes | `devicePixelRatio` (2) | 139.1 Mpx | 14–21 |
492
+ | 57 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 61 |
493
+ | 92 meshes | `devicePixelRatio` (2) | 141.1 Mpx | 36–39 |
494
+ | 92 meshes | `dpr × zoom` (0.5) | 9.1 Mpx | 60–61 |
495
+
496
+ ## Demo (this repository)
497
+
498
+ ```bash
499
+ bun install
500
+ bun run dev
501
+ ```
502
+
503
+ The demo plays rigc's own gallery rigs (`walk`, `flex`, `squash`, `portrait`,
504
+ `nod`, `look`, `ride`), each built by `rigc build` from a pinned rigc tag into
505
+ `public/rigs/<name>/` on first `dev`/`build` — and each again with `--pack` into
506
+ `public/rigs/<name>-packed/`. The same step builds this repository's test rigs
507
+ (`tests/rigs/`: `figure`, `glow`, `turned`), which `?rig=` also reaches; nothing
508
+ is downloaded but the rigc tag's gallery sources. `bun run fetch-assets` runs it
509
+ manually, and it is idempotent.
510
+
511
+ Debug knobs (query string): `?rig=flex` `?anim=wave` `?count=10` pick the scene,
512
+ `?tint=ff8080` tints the whole rig, `?dpr=2` overrides the mesh-canvas backing
513
+ ratio, `?timescale=0` freezes the pose (every mesh should report "reused"),
514
+ `?expand=0` disables the crack-closing clip overdraw, `?backend=webgl` rasterizes
515
+ meshes through the shared WebGL blitter (also a live header select; the stats line
516
+ names the active backend), `?clipping=0` turns clips back off (they are then
517
+ counted and skipped), and `?time=1.2` seeks every instance to the same pose for
518
+ deterministic captures.
519
+
520
+ ## Tests
521
+
522
+ ```bash
523
+ bun run test # builds + serves the demo, then runs chromium + webkit
524
+ ```
525
+
526
+ Playwright drives the demo (`tests/`, config in `playwright.config.ts`; CI
527
+ runs the same suite on ubuntu, one job). Every scene is a rig built by
528
+ `rigc build` and posed by `rig-c/core` through `RigPlayer` — rigc's gallery rigs,
529
+ and three test rigs authored in this repository (`tests/rigs/`) for what the
530
+ gallery does not carry: `figure` (clipping attachments in rigc's format —
531
+ convex, inverse, nested, whole-skeleton — rigid parts on turned bones, two grid
532
+ meshes), `glow` (additive slots with slot colours over two weighted meshes) and
533
+ `turned` (a region packed turned 90° on a hand-packed page). No Spine runtime
534
+ is installed or compared against: the pose is rig-c's, held to spine-core at
535
+ tolerance 0 by rig-c's own CI, and a pose doubt is a rigc issue. The visual
536
+ checks are **A/B within one run**: no golden snapshots are committed (they rot
537
+ across platforms/GPUs) — instead the same deterministic pose (`?time` +
538
+ `?timescale=0`) is screenshotted twice in the same engine and the buffers are
539
+ diffed directly with a shift-tolerant comparison, so missing parts, wrong
540
+ colors, and tint/blend/clip divergence fail regardless of platform.
541
+
542
+ **The picture gate** is the two render modes drawing the same picture: every
543
+ scene captured in the DOM mode and in the canvas mode and diffed — bad pixels at
544
+ most 1.5% of drawn content on the test-rig scenes (measured floors 0.007–0.524%,
545
+ macOS Chromium; each scene's own feature dropped from the canvas mode — tint,
546
+ additive blend, clipping, a mesh — scores 4.2–77%) and 2.5% on the gallery
547
+ scenes (floors 0.585–1.553%, Chromium and WebKit). The DOM tier's two mesh
548
+ backends get the same A/B (`?backend=canvas2d` against `?backend=webgl`, at most
549
+ 0.5%). Hairline seams are guarded by a deterministic canary (`?expand=0` must
550
+ change the canvas2d raster), the canvas2d source sub-rect by another (expand 32
551
+ against 8), and counter tests pin the dirty-skip / grow-only-backing /
552
+ clip-counter invariants plus the region corner order (BL, UL, UR, BR) and the
553
+ turned-region UVs, read off rig-c's pose against hand-written numbers.
554
+
555
+ Clipping gets its own oracle (`tests/clipping.spec.ts`), because a clip-path
556
+ that went through the wrong transform still parses and still counts as applied.
557
+ A clipped capture is compared against the **unclipped** capture of the same
558
+ slots masked in **screen space** by the world polygon — built once through the
559
+ stage transform, never through an element's local frame, so the check cannot
560
+ agree with the renderer by sharing its mistake. What it asserts is occupancy,
561
+ not pixel values: outside a 3 px band around the polygon's outline (where the
562
+ browser's clip-path antialiasing and the canvas `ctx.clip()` the oracle uses
563
+ legitimately differ), **no artwork may survive where the polygon excludes it
564
+ and none may go missing where it does not** — both counts absolute, no budget.
565
+ Pixel values are logged but not asserted, because a clipped element is drawn
566
+ through a mask and its silhouettes come out a shade different all over the
567
+ picture; a control capture, clipped by a polygon that removes nothing, pins
568
+ that down by coming back byte-identical to the unclipped one.
569
+
570
+ The loading path is not observable in a rendered frame, so it gets its own
571
+ page (`tests/harness.html`, a second build entry) that exposes the library to
572
+ the specs directly. Its oracle is the browser: a revoked object URL stops
573
+ resolving, so blob ownership — every unpacked URL freed, nothing the caller
574
+ owns touched, nothing stranded by a failed load — is asserted rather than
575
+ assumed.
576
+
577
+ ## Benchmark: DOM mode vs canvas mode
578
+
579
+ ```bash
580
+ bun run bench:dev # the page, for a person to watch (and for Safari)
581
+ bun run bench # drives it in a headed Chromium and writes a report
582
+ ```
583
+
584
+ `bench/` is a separate vite project — not part of the library, and not part of
585
+ what `bun run build` emits — that plays the same rigc gallery build in both
586
+ render modes side by side, each with its own stats line in the demo's style.
587
+ Scenes by query string: `?scene=mesh` (`portrait-packed` turning its head, the
588
+ deform tier working every frame), `?scene=held` (the same pose frozen, where
589
+ unchanged meshes reuse their raster and an unchanged frame is reused),
590
+ `?scene=rigid` (`walk-packed`, region attachments only) and
591
+ `?scene=many&count=N` independent players; `?rig=` and `?model=` name another
592
+ build. All four take `&count=N` up to 64 (a page limit, so that a cell stays
593
+ something you can see), laid out on one grid whose per-rig scale shrinks with
594
+ the column count, so a step up in count adds rigs rather than cropping the ones
595
+ already there.
596
+
597
+ **The two sides draw the same picture.** Both place rigs with one derivation and
598
+ clip each to the same rect — the pane for a grid, the rig's own cell for `many`
599
+ — with `overflow: hidden` on a box, the way a page embeds a player, and then
600
+ *check* it: each side reports `origin Δpx`, the largest gap between where the
601
+ grid puts a rig and where that side drew it, and the report table carries it per
602
+ row. (`contain: layout paint` is deliberately not used: paint containment clips
603
+ to the same edge `overflow: hidden` does, and what it adds past the clip — a
604
+ stacking context, a containing block, an independent formatting context —
605
+ changes how one side is composited and buys the comparison nothing.) Both modes
606
+ share the package's single WebGL context however many players there are; the
607
+ canvas side's stats line says how many contexts the page holds.
608
+
609
+ `scripts/bench.mjs` walks `bench/scenes.json`, opens each scene in a **headed**
610
+ Chromium (a hidden page throttles `requestAnimationFrame`, so a headless
611
+ reading would be the browser's power policy rather than either mode's cost),
612
+ runs a fixed number of frames per mode — one at a time, because rAF has a single
613
+ cadence per document — and writes JSON plus a markdown table with the
614
+ conditions attached: browser version, device pixel ratio, window size, GPU
615
+ string, and the load average before and after. Over a threshold it stamps the
616
+ whole report `INVALID: load average too high` and exits non-zero, because a
617
+ benchmark on a busy machine measures the machine. `--corpus <dir>` points it at
618
+ local rigc builds that never enter this repository.
619
+
620
+ > **Numbers pending.** No comparison table is published yet. A reading taken on
621
+ > a loaded machine, a CI runner or a headless browser would not be worth
622
+ > printing. The table will be taken the way every other number in this README
623
+ > was: the two stats lines read on a real device, on a quiet machine, per scene
624
+ > and per engine — including Safari, which stays manual because no automation
625
+ > preserves what is being measured there. Until then the instrument exists and
626
+ > the measurement does not.
627
+
628
+ The server is part of the test: a run tests whatever is being served on its
629
+ port. Two checkouts of this repository on one machine (a worktree, a second
630
+ clone) default to the same port 4321 and reuse an existing server, so the
631
+ second run quietly tests the first one's build — green, and about the wrong
632
+ tree. Give each concurrent checkout its own port with `TEST_PORT`
633
+ (`TEST_PORT=4333 bun run test`); setting it also disables server reuse, so a
634
+ busy port fails the run instead of being borrowed. Unset, nothing changes:
635
+ port 4321, reuse unless `CI`.
636
+
637
+ Standing rule: **headless numbers are never Safari performance evidence** —
638
+ nothing in the suite asserts timing, and headless-WebKit fps/ms readings do
639
+ not transfer (software rasterizer, measured up to 28× off real Safari). The
640
+ perf oracle is the demo's stats line on a real device.
641
+
642
+ ## How it works
643
+
644
+ 1. `loadModel` reads the rig's compiled model document (`rig-c/core`'s `readModel`),
645
+ and `RigPlayer` opens an animation on a live track (`openTrack`): bones,
646
+ constraints, physics, deform and draw order are posed by the core — all
647
+ CPU-side, renderer-agnostic — one `dt` at a time.
648
+ 2. At load time each region of the document's `pages` section is cut into its own
649
+ bitmap (rotation restored), one blob URL per region — except regions that already
650
+ cover their whole page, which are used as they are.
651
+ 3. Per frame, the pose becomes a `PosedFrame`: for each slot in draw order, a region's
652
+ four world corners (order **BL, UL, UR, BR**) or a mesh's world vertices, page UVs
653
+ and triangles, its tint, blend and clip. For a region: flip Y (the frame is Y-up),
654
+ derive the affine from three corners, write one `matrix()` string. That's the
655
+ whole rigid render path.
656
+
657
+ ## License
658
+
659
+ rig-play's own code is MIT (see [LICENSE](LICENSE)). That says nothing about Spine,
660
+ so here is what is true of this package and this repository, stated plainly:
661
+
662
+ 1. The published package — `rig-play`, and `spine-html`, the same files — **links
663
+ nothing from Esoteric Software**. Its one module bundles the renderer and
664
+ `rig-c/core` (MIT), which poses rigc's model document; no part of the
665
+ [Spine Runtimes](https://github.com/EsotericSoftware/spine-runtimes) is in it or
666
+ required beside it.
667
+ 2. This repository links no Spine runtime either, since #63: no package of Esoteric
668
+ Software's npm scope is a dependency of any kind, and the lockfile names none.
669
+ `tests/package.spec.ts` asserts both.
670
+ 3. `rigc build`, which this repository runs to make its fixtures, also writes Spine
671
+ skeleton data (`skeleton.json` and `skeleton.atlas`) beside each model document.
672
+ Nothing here reads it, and it is neither committed nor published.
673
+ 4. A product that plays that Spine data with a Spine Runtime has integrated the Spine
674
+ Runtimes, whose licence permits it **under Section 2 of the
675
+ [Spine Editor License Agreement](https://esotericsoftware.com/spine-editor-license)**,
676
+ or otherwise on the condition that **each user of the product obtains their own
677
+ Spine Editor license** — the licence's own two routes, restated, not a term of
678
+ this project.
679
+
680
+ > **What a consumer does with rigc's Spine-format output is governed by Esoteric
681
+ > Software's terms**, not by this package — rig-play neither adds those terms nor
682
+ > removes them.
683
+
684
+ No example assets of Esoteric Software's are fetched or redistributed. See
685
+ [NOTICE.md](NOTICE.md) for the full notice.