@openbone/player 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 UX Century and OpenBone contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,224 @@
1
- # Temporary Holding Version
1
+ # @openbone/player
2
2
 
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.
3
+ A drop-in `<openbone-player>` web component and a `Player` class for OpenBone animations in the browser.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@openbone/player)](https://www.npmjs.com/package/@openbone/player)
6
+ [![MIT licence](https://img.shields.io/badge/licence-MIT-blue)](https://github.com/UXCentury/open-bone/blob/main/LICENSE)
7
+
8
+ [OpenBone](https://github.com/UXCentury/open-bone) is open-source 2D skeletal animation: Spine-style rigging,
9
+ Rive-style state machines and an MCP server for AI agents. This package is the quickest way to put an OpenBone file on
10
+ a web page. It loads a `.obone` or `.obonb` document and its images, runs the animation or state machine with
11
+ [`@openbone/runtime`](https://www.npmjs.com/package/@openbone/runtime), draws with
12
+ [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl) (falling back to
13
+ [`@openbone/render-canvas`](https://www.npmjs.com/package/@openbone/render-canvas) when WebGL2 is missing), routes
14
+ pointer events to state machine listeners, plays sounds with Web Audio and runs document scripts in the QuickJS sandbox
15
+ from [`@openbone/scripting`](https://www.npmjs.com/package/@openbone/scripting). For PixiJS, Phaser, Three.js or
16
+ CanvasKit, use the engine packages instead (see [Documentation](#documentation)).
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ npm install @openbone/player
22
+ ```
23
+
24
+ `esbuild` is an optional peer dependency. You only need it for `@openbone/player/bundle` (see
25
+ [Script-tag player](#script-tag-player-no-bundler)).
26
+
27
+ ## Quick start
28
+
29
+ With a bundler (Vite, webpack, esbuild…). The knight below is `examples/knight.obone` from the repository; its state
30
+ machine is called `knight`, with a `walk` boolean and `attack` and `salute` triggers.
31
+
32
+ ```html
33
+ <openbone-player src="/knight.obone" state-machine="knight" style="width: 600px; height: 400px"></openbone-player>
34
+ <button id="attack">Attack</button>
35
+
36
+ <script type="module">
37
+ import { definePlayerElement } from "@openbone/player";
38
+
39
+ definePlayerElement(); // registers <openbone-player>
40
+
41
+ const knight = document.querySelector("openbone-player");
42
+ knight.addEventListener("openbone-load", () => knight.setInput("walk", true));
43
+ knight.addEventListener("openbone-event", (e) => console.log("event", e.detail.name));
44
+ knight.addEventListener("openbone-state", (e) => console.log(e.detail.layer, e.detail.from, "->", e.detail.to));
45
+ document.querySelector("#attack").addEventListener("click", () => knight.fire("attack"));
46
+ </script>
47
+ ```
48
+
49
+ Images and sounds load relative to the document's URL. The element is 400 × 300 px unless you size it with CSS.
50
+
51
+ ## API
52
+
53
+ ### Exports
54
+
55
+ | Export | |
56
+ |---|---|
57
+ | `definePlayerElement(tag?)` | Registers the element (default tag `openbone-player`). Safe to call more than once. |
58
+ | `OpenBonePlayerElement` | The element class. |
59
+ | `Player` | Plays a document on a canvas you own. The element wraps one. |
60
+ | `PlayerOptions` | Options type for `Player`. |
61
+ | `setScriptHostFactory(factory)` | Replaces how players create the script sandbox (for example `() => Promise.resolve(null)` to never load QuickJS). |
62
+ | `WebAudioBackend`, `WebAudioOptions` | The Web Audio playback used by the player. Also at `@openbone/player/audio`. |
63
+
64
+ ### `<openbone-player>` attributes
65
+
66
+ | Attribute | Default | |
67
+ |---|---|---|
68
+ | `src` | | URL of a `.obone` (JSON) or `.obonb` (binary) file. Changing it reloads. |
69
+ | `state-machine` | first | State machine to run, by name or id. |
70
+ | `animation` | | Play this animation instead of a state machine. |
71
+ | `skin` | default skin | Skin (outfit) by name or id. Changing it switches the outfit without reloading. |
72
+ | `fit` | `contain` | `contain`, `cover` or `none` (actual size, centred). |
73
+ | `renderer` | `webgl` | `webgl` or `canvas`. WebGL falls back to Canvas 2D when WebGL2 is not available. |
74
+ | `background` | the file's | Any CSS colour (`#fff`, `rebeccapurple`, `rgb(0 0 0 / 50%)`, …), or `transparent` / `none`. |
75
+ | `autoplay` | on | `autoplay="false"` loads and draws the first frame, then waits for `play()`. |
76
+ | `scripts` | on | `scripts="none"` never runs the document's scripts. |
77
+ | `audio` / `muted` | on | `audio="off"` disables sound; `muted` loads sounds but starts muted. |
78
+
79
+ Changing `skin` switches the skin in place. Changing any other attribute, including setting `src` after the element is
80
+ on the page, reloads the player with the new settings.
81
+
82
+ ### Element methods and events
83
+
84
+ | Method | |
85
+ |---|---|
86
+ | `setInput(name, value)` | Set a state machine input (boolean, number or string). |
87
+ | `fire(name)` | Fire a trigger input. |
88
+ | `setText(slot, text)` | Show fixed text (or an `{input}` template) in a slot's text attachment; `null` restores it. |
89
+ | `setSkin(name)` | Switch skin (updates the `skin` attribute); `null` shows the default skin. |
90
+ | `play()` / `pause()` | Start or stop playback and sound. |
91
+ | `player` | The underlying `Player`, or `null` before the element is connected. |
92
+ | `audioContext` | An `AudioContext` to play through, set before `src`. Create and resume it in a click handler (a play button) and the player starts with sound even if it loads after that click. |
93
+
94
+ | Event | `detail` |
95
+ |---|---|
96
+ | `openbone-load` | none: the document, images and script sandbox are ready. |
97
+ | `openbone-event` | The fired event: `name`, `id`, `time`, `int`, `float`, `string`, `animation`. |
98
+ | `openbone-state` | A state change: `layer`, `from` (or `null`), `to`. |
99
+
100
+ Events bubble and cross the shadow root.
101
+
102
+ ### `Player`
103
+
104
+ ```ts
105
+ import { Player } from "@openbone/player";
106
+
107
+ const canvas = document.querySelector<HTMLCanvasElement>("#c")!; // give it a CSS size
108
+ const player = new Player({
109
+ canvas,
110
+ src: "/knight.obone",
111
+ stateMachine: "knight",
112
+ fit: "contain",
113
+ onEvent: (e) => console.log("event", e.name, e.int, e.float, e.string),
114
+ onStateChange: (e) => console.log(e.layer, e.from, "->", e.to),
115
+ });
116
+ await player.ready; // the document, its images and (if needed) the script sandbox are loaded
117
+
118
+ player.setInput("walk", true);
119
+ player.fire("salute");
120
+ player.speed = 0.5;
121
+ ```
122
+
123
+ `PlayerOptions`:
124
+
125
+ | Option | |
126
+ |---|---|
127
+ | `canvas` | The canvas to draw on. It follows its CSS size (a `ResizeObserver`) at the device pixel ratio. |
128
+ | `src` | A URL, or an already parsed `OpenBoneDocument`. |
129
+ | `baseUrl` | Folder for relative image and audio paths (default: the folder of `src`). |
130
+ | `resolveImageUrl(src)`, `resolveAudioUrl(asset)` | Map asset paths to URLs yourself (overrides `baseUrl`). |
131
+ | `stateMachine`, `animation`, `skin`, `autoplay`, `fit`, `renderer`, `background` | As the attributes above. `background: null` is transparent. |
132
+ | `scripts` | `"quickjs"` (default when the document has scripts), `"none"`, or your own `ScriptHost`. |
133
+ | `audio` | `true` (default), `false` or `"muted"`. |
134
+ | `audioContext` | Share an existing `AudioContext` instead of creating one. |
135
+ | `onEvent`, `onStateChange`, `onLoad` | Callbacks. |
136
+
137
+ Members: `ready` (promise), `play()`, `pause()`, `playing`, `speed` (sounds follow it), `setInput`, `getInput`,
138
+ `fire`, `setText`, `setSkin`, `skins`, `playAnimation(name, loop?)`, `setFit(fit)`, `setMuted(muted)`, `muted`,
139
+ `audio`, `instance` (the runtime `OpenBoneInstance`), `stateMachine`, `doc`, `clientToSkeleton(clientX, clientY)`,
140
+ `boundingBoxes()` and `dispose()`.
141
+
142
+ `boundingBoxes()` returns the active bounding boxes in skeleton space with point, segment, AABB and overlap queries
143
+ (see `@openbone/runtime`); `clientToSkeleton` converts page coordinates through the current fit:
144
+
145
+ ```ts
146
+ canvas.addEventListener("click", (e) => {
147
+ const hit = player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY));
148
+ if (hit) console.log("clicked", hit.slot.data.name);
149
+ });
150
+ ```
151
+
152
+ ### Pointer input
153
+
154
+ Pointer down, up and move over the canvas are converted to skeleton space and sent to the state machine, so listeners
155
+ on bounding boxes (hover, click) work without extra code. Leaving the canvas ends hovers.
156
+
157
+ ### Audio
158
+
159
+ Sounds load with the document and play through Web Audio. Browsers only allow sound after a user gesture, so audio
160
+ unlocks on the first click or key press; one-shot sounds requested before that are dropped. `pause()` pauses sounds
161
+ where they are and `play()` resumes them.
162
+
163
+ ### Scripts
164
+
165
+ Documents with scripts load the QuickJS sandbox on demand (a dynamic import of `@openbone/scripting`). Pass
166
+ `scripts: "none"` (or the `scripts="none"` attribute) to skip it. If your bundler pre-bundles dependencies, exclude
167
+ `quickjs-emscripten` so it can find its `.wasm` file; the repository's Vite configs use
168
+ `optimizeDeps: { exclude: ["quickjs-emscripten"] }`.
169
+
170
+ ### Disposal
171
+
172
+ Removing the element from the page disposes its player. With a `Player` of your own, call `dispose()`: it stops the
173
+ render loop and the sounds and frees the WebGL resources.
174
+
175
+ ## Script-tag player (no bundler)
176
+
177
+ The npm package ships ES modules, not a prebuilt script. `@openbone/player/bundle` (Node only, needs `esbuild`)
178
+ builds a self-contained player for plain `<script src>` use:
179
+
180
+ ```ts
181
+ import { mkdir, writeFile } from "node:fs/promises";
182
+ import { buildScriptsAddon, buildWebBundle, quickJsWasmBytes } from "@openbone/player/bundle";
183
+
184
+ await mkdir("public", { recursive: true });
185
+ // Classic script that defines <openbone-player> and window.OpenBone. "lazy": the script sandbox is fetched
186
+ // from next to the player, only for animations that have scripts.
187
+ await writeFile("public/openbone-player.js", await buildWebBundle({ format: "iife", scripts: "lazy" }));
188
+ await writeFile("public/openbone-scripts.js", await buildScriptsAddon());
189
+ await writeFile("public/quickjs.wasm", quickJsWasmBytes());
190
+ ```
191
+
192
+ ```html
193
+ <script src="openbone-player.js"></script>
194
+ <openbone-player src="walker.obone" state-machine="character" style="width: 600px; height: 380px"></openbone-player>
195
+ ```
196
+
197
+ Including the script registers `<openbone-player>` and sets `window.OpenBone` to `{ Player, OpenBonePlayerElement,
198
+ definePlayerElement, parseDocument, version }`.
199
+
200
+ `buildWebBundle` options: `format` (`"iife"` or `"esm"`), `minify` (default true) and `scripts` (`true` inlines
201
+ QuickJS in one file, `"lazy"` loads `openbone-scripts.js` and `quickjs.wasm` from the player's folder only when
202
+ needed, `false` leaves the sandbox out and skips scripts with a warning). Set `window.OPENBONE_SCRIPTS_BASE` to load
203
+ the lazy files from another folder. `buildPlayerBundle()` builds the variant used by the WebView packages.
204
+
205
+ You can also skip the build: the OpenBone editor's **Web** export (and the MCP server's `export_file` with format
206
+ `web`) writes the player, your animation and a demo page as a ZIP, or as one self-contained HTML file.
207
+
208
+ ## Documentation
209
+
210
+ - [Architecture](https://github.com/UXCentury/open-bone/blob/main/docs/architecture.md): runtime model, rendering, audio and scripts
211
+ - [File format](https://github.com/UXCentury/open-bone/blob/main/docs/format.md): `.obone` and `.obonb`
212
+ - [Engine exports](https://github.com/UXCentury/open-bone/blob/main/docs/engine-exports.md): WebView packages and the host bridge
213
+ - [Runtime specification](https://github.com/UXCentury/open-bone/blob/main/docs/runtime-spec.md)
214
+ - Related packages: [`@openbone/runtime`](https://www.npmjs.com/package/@openbone/runtime),
215
+ [`@openbone/render-webgl`](https://www.npmjs.com/package/@openbone/render-webgl),
216
+ [`@openbone/render-canvas`](https://www.npmjs.com/package/@openbone/render-canvas),
217
+ [`@openbone/pixi`](https://www.npmjs.com/package/@openbone/pixi),
218
+ [`@openbone/phaser`](https://www.npmjs.com/package/@openbone/phaser),
219
+ [`@openbone/three`](https://www.npmjs.com/package/@openbone/three),
220
+ [`@openbone/canvaskit`](https://www.npmjs.com/package/@openbone/canvaskit)
221
+
222
+ ## License
223
+
224
+ MIT, © UX Century and OpenBone contributors. See [LICENSE](https://github.com/UXCentury/open-bone/blob/main/LICENSE).
@@ -0,0 +1,101 @@
1
+ import { type AudioAsset, type OpenBoneDocument } from "@openbone/core";
2
+ import type { AudioCommand } from "@openbone/runtime";
3
+ export interface WebAudioOptions {
4
+ /** Base URL for relative audio paths. */
5
+ baseUrl?: string;
6
+ /** Map an asset to the URL to load (overrides baseUrl), e.g. for files read from disk. */
7
+ resolveUrl?: (asset: AudioAsset) => string;
8
+ /** Use an existing context instead of creating one on first use. */
9
+ context?: AudioContext;
10
+ /** Called for every command handled (and for dropped/failed ones), for debugging. */
11
+ onLog?: (message: string, cmd?: AudioCommand) => void;
12
+ }
13
+ /**
14
+ * Plays the runtime's AudioCommands with the Web Audio API: resolves and decodes assets (cached per URL),
15
+ * routes each sound through its bus into the master, applies fades, and follows the document's mix
16
+ * (call `syncMix()` after changing bus/master values). Browsers block audio until a user gesture, so the
17
+ * context is resumed by the first pointer/key event (see `unlock`); one-shots requested before that are skipped.
18
+ */
19
+ export declare class WebAudioBackend {
20
+ doc: OpenBoneDocument;
21
+ private opts;
22
+ ctx: AudioContext | null;
23
+ private master;
24
+ private buses;
25
+ private buffers;
26
+ private voices;
27
+ private hostMuted;
28
+ private unbind;
29
+ /** Looping sounds requested before audio was unlocked, by voice id; they start when the context runs. */
30
+ private pending;
31
+ private offline;
32
+ constructor(doc: OpenBoneDocument, opts?: WebAudioOptions);
33
+ /** True once the browser lets the context play. */
34
+ get unlocked(): boolean;
35
+ get muted(): boolean;
36
+ /** Mute everything (independent of the document's own mute). */
37
+ setMuted(m: boolean): void;
38
+ setDocument(doc: OpenBoneDocument): void;
39
+ setBaseUrl(url: string): void;
40
+ /** Create (if needed) and resume the context now. Call it from a user gesture (a click) so the browser allows sound. */
41
+ activate(): AudioContext | null;
42
+ private context;
43
+ /** Start the loops that were waiting for audio once the context runs (whoever resumed it). */
44
+ private watch;
45
+ private flushPending;
46
+ /**
47
+ * Where sounds are decoded: the live context once it exists, else an OfflineAudioContext, which the browser allows
48
+ * without a user gesture (decoded buffers play in any context).
49
+ */
50
+ private decoder;
51
+ private masterNode;
52
+ private busNode;
53
+ /** Mutes set while playing by "mix" commands (mute buttons): bus id, "" = master. They win over the document. */
54
+ private mixMutes;
55
+ private isMuted;
56
+ /** Apply the document's master/bus volumes and mutes (and the host mute, and mute buttons) to the graph. */
57
+ syncMix(): void;
58
+ /** Effective gain a sound on `busId` gets from the mix right now (master x bus, 0 when muted). */
59
+ busGain(busId: string | null): number;
60
+ url(asset: AudioAsset): string;
61
+ /** Fetch and decode an asset (cached by URL). */
62
+ load(asset: AudioAsset): Promise<AudioBuffer | null>;
63
+ /** Start decoding every asset in the document. */
64
+ preload(): Promise<(AudioBuffer | null)[]>;
65
+ /** Resume the context on the first user gesture on `target` (default: window). Safe to call more than once. */
66
+ unlock(target?: EventTarget): void;
67
+ /** Handle one runtime command. Pass this to `instance.on("audio", ...)`. */
68
+ handle: (cmd: AudioCommand) => void;
69
+ private play;
70
+ /** (Re)start a voice's buffer from `offset` seconds into the file, at the sound's rate × the backend's speed. */
71
+ private startSource;
72
+ /** Where a voice is in its file now (seconds). */
73
+ private position;
74
+ private speed;
75
+ private pausedAll;
76
+ /**
77
+ * Playback speed for everything this backend plays (sounds already playing change too), like a player's speed
78
+ * control: 2 plays twice as fast and an octave higher.
79
+ */
80
+ setSpeed(speed: number): void;
81
+ /** Pause every voice where it is (resumeAll continues them from there). */
82
+ pauseAll(): void;
83
+ /** Continue every paused voice from where it was paused. */
84
+ resumeAll(): void;
85
+ /**
86
+ * A short grain of a sound at `offset` seconds into its file, for scrubbing a timeline: fades in and out over a few
87
+ * milliseconds so dragging sounds like a tape head rather than clicks.
88
+ */
89
+ scrub(assetId: string, offset: number, o?: {
90
+ duration?: number;
91
+ volume?: number;
92
+ rate?: number;
93
+ bus?: string | null;
94
+ }): void;
95
+ private stop;
96
+ /** Stop every voice (optionally fading). */
97
+ stopAll(fade?: number): void;
98
+ /** Number of voices currently playing or loading. */
99
+ get activeVoices(): number;
100
+ dispose(): void;
101
+ }