@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.
@@ -0,0 +1,126 @@
1
+ import { Player } from "./player.js";
2
+ /**
3
+ * <openbone-player src="hero.obone" state-machine="ui" animation="idle" skin="red" fit="contain" renderer="webgl">
4
+ * Events: "openbone-event" (detail = FiredEvent), "openbone-state" (detail = state change), "openbone-load".
5
+ * Methods: setInput(name, value), fire(name), setText(slot, text), setSkin(name), play(), pause(),
6
+ * setMuted(muted), setBusMuted(bus, muted | "toggle"), toggleBus(bus), isBusMuted(bus), buses, player (the underlying Player).
7
+ * Audio plays after the first click/key press; `muted` attribute starts muted, `audio="off"` disables it.
8
+ * Changing the `skin` attribute switches the outfit without reloading.
9
+ */
10
+ export class OpenBonePlayerElement extends HTMLElement {
11
+ /** `skin` switches skins in place; any other of these reloads the player with the new settings. */
12
+ static observedAttributes = ["src", "skin", "animation", "state-machine", "fit", "renderer", "autoplay", "background", "scripts", "audio", "muted"];
13
+ player = null;
14
+ /**
15
+ * An AudioContext to play through instead of creating one, set before `src`. Create and resume it in a click
16
+ * handler (a play button) and the player starts with sound even when it loads after that click.
17
+ */
18
+ audioContext = null;
19
+ canvas;
20
+ constructor() {
21
+ super();
22
+ const root = this.attachShadow({ mode: "open" });
23
+ root.innerHTML = `<style>:host{display:inline-block;width:400px;height:300px;position:relative}canvas{width:100%;height:100%;display:block;touch-action:none}</style>`;
24
+ this.canvas = document.createElement("canvas");
25
+ root.appendChild(this.canvas);
26
+ }
27
+ connectedCallback() {
28
+ // An upgraded element may already have loaded from attributeChangedCallback.
29
+ if (!this.player)
30
+ this.init();
31
+ }
32
+ disconnectedCallback() {
33
+ this.player?.dispose();
34
+ this.player = null;
35
+ }
36
+ attributeChangedCallback(n, old, val) {
37
+ if (old === val || !this.isConnected)
38
+ return;
39
+ if (n === "skin")
40
+ this.player?.setSkin(val);
41
+ // Includes `src` set for the first time after the element was added to the page. Upgrading an element reports each
42
+ // attribute it already has; those match what the player was built with, so they don't reload it.
43
+ else if (this.settings() !== this.loadedWith)
44
+ this.init();
45
+ }
46
+ /** The attributes the current player was built with (everything observed except `skin`). */
47
+ loadedWith;
48
+ settings() {
49
+ return JSON.stringify(OpenBonePlayerElement.observedAttributes.filter((a) => a !== "skin").map((a) => this.getAttribute(a)));
50
+ }
51
+ init() {
52
+ const src = this.getAttribute("src");
53
+ this.player?.dispose();
54
+ this.player = null;
55
+ this.loadedWith = this.settings();
56
+ if (!src)
57
+ return;
58
+ this.player = new Player({
59
+ canvas: this.canvas,
60
+ src,
61
+ stateMachine: this.getAttribute("state-machine") ?? undefined,
62
+ animation: this.getAttribute("animation") ?? undefined,
63
+ skin: this.getAttribute("skin") ?? undefined,
64
+ fit: this.getAttribute("fit") ?? "contain",
65
+ renderer: this.getAttribute("renderer") ?? "webgl",
66
+ autoplay: this.getAttribute("autoplay") !== "false",
67
+ background: this.background(),
68
+ scripts: this.getAttribute("scripts") === "none" ? "none" : "quickjs",
69
+ audio: this.getAttribute("audio") === "off" ? false : this.hasAttribute("muted") ? "muted" : true,
70
+ ...(this.audioContext ? { audioContext: this.audioContext } : {}),
71
+ onEvent: (e) => this.dispatchEvent(new CustomEvent("openbone-event", { detail: e, bubbles: true, composed: true })),
72
+ onStateChange: (e) => this.dispatchEvent(new CustomEvent("openbone-state", { detail: e, bubbles: true, composed: true })),
73
+ onLoad: () => this.dispatchEvent(new CustomEvent("openbone-load", { bubbles: true, composed: true })),
74
+ });
75
+ this.player.ready.catch((e) => console.error(e));
76
+ }
77
+ /** `background` attribute: a colour, "transparent"/"none" for no background, absent for the file's own. */
78
+ background() {
79
+ if (!this.hasAttribute("background"))
80
+ return undefined;
81
+ const v = this.getAttribute("background")?.trim() ?? "";
82
+ return v === "" || v === "transparent" || v === "none" ? null : v;
83
+ }
84
+ setInput(name, value) {
85
+ this.player?.setInput(name, value);
86
+ }
87
+ setText(slot, text) {
88
+ this.player?.setText(slot, text);
89
+ }
90
+ fire(name) {
91
+ this.player?.fire(name);
92
+ }
93
+ setSkin(name) {
94
+ if (name)
95
+ this.setAttribute("skin", name);
96
+ else
97
+ this.removeAttribute("skin");
98
+ }
99
+ play() {
100
+ this.player?.play();
101
+ }
102
+ /** Mute or unmute everything. */
103
+ setMuted(muted) {
104
+ this.player?.setMuted(muted);
105
+ }
106
+ /** Mute, unmute or toggle a sound bus by name ("music", "sfx"…); null or "master" = the master. */
107
+ setBusMuted(bus, muted = true) {
108
+ return this.player?.setBusMuted(bus, muted) ?? null;
109
+ }
110
+ toggleBus(bus) {
111
+ return this.player?.toggleBus(bus) ?? null;
112
+ }
113
+ isBusMuted(bus) {
114
+ return this.player?.isBusMuted(bus) ?? null;
115
+ }
116
+ get buses() {
117
+ return this.player?.buses ?? [];
118
+ }
119
+ pause() {
120
+ this.player?.pause();
121
+ }
122
+ }
123
+ export function definePlayerElement(tag = "openbone-player") {
124
+ if (!customElements.get(tag))
125
+ customElements.define(tag, OpenBonePlayerElement);
126
+ }
@@ -0,0 +1,3 @@
1
+ export { Player, type PlayerOptions, setScriptHostFactory } from "./player.js";
2
+ export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
+ export { WebAudioBackend, type WebAudioOptions } from "./audio.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Player, setScriptHostFactory } from "./player.js";
2
+ export { OpenBonePlayerElement, definePlayerElement } from "./element.js";
3
+ export { WebAudioBackend } from "./audio.js";
@@ -0,0 +1,122 @@
1
+ import { type AudioAsset, type OpenBoneDocument } from "@openbone/core";
2
+ import { type FiredEvent, OpenBoneInstance, type ScriptHost, type SkeletonBounds, type StateMachineInstance } from "@openbone/runtime";
3
+ import { WebAudioBackend } from "./audio.js";
4
+ export interface PlayerOptions {
5
+ canvas: HTMLCanvasElement;
6
+ /** URL of a .obone file, or a parsed document. */
7
+ src: string | OpenBoneDocument;
8
+ /** Base URL for relative image paths (defaults to the src URL's folder). */
9
+ baseUrl?: string;
10
+ stateMachine?: string;
11
+ animation?: string;
12
+ /** Skin (outfit) to show, by name or id. Attachments not in it fall back to the default skin. */
13
+ skin?: string;
14
+ autoplay?: boolean;
15
+ /** "quickjs" (sandboxed, default when the doc has scripts), "none", or a custom host. */
16
+ scripts?: "quickjs" | "none" | ScriptHost;
17
+ renderer?: "webgl" | "canvas";
18
+ fit?: "contain" | "cover" | "none";
19
+ background?: string | null;
20
+ /** Play the document's sounds (default true). "muted" loads them but starts muted. Audio unlocks on the first click or key press. */
21
+ audio?: boolean | "muted";
22
+ /** Share an existing AudioContext (e.g. one already unlocked by a click), instead of creating one. */
23
+ audioContext?: AudioContext;
24
+ /** Map an audio asset to the URL to load (overrides baseUrl), e.g. for files read from disk. */
25
+ resolveAudioUrl?: (asset: AudioAsset) => string;
26
+ /** Map an image src to the URL to load (overrides baseUrl). */
27
+ resolveImageUrl?: (src: string) => string;
28
+ onEvent?: (e: FiredEvent) => void;
29
+ onStateChange?: (e: {
30
+ layer: string;
31
+ from: string | null;
32
+ to: string;
33
+ }) => void;
34
+ onLoad?: (p: Player) => void;
35
+ }
36
+ /**
37
+ * Replace how players create the sandbox for documents with scripts (default: load `@openbone/scripting`).
38
+ * Bundles use it to supply an inlined QuickJS build, or `() => Promise.resolve(null)` to run without scripts.
39
+ */
40
+ export declare function setScriptHostFactory(factory: (() => Promise<ScriptHost | null>) | null): void;
41
+ /** Plays an OpenBone document on a canvas, with pointer input routed to its state machine. */
42
+ export declare class Player {
43
+ private opts;
44
+ instance: OpenBoneInstance;
45
+ doc: OpenBoneDocument;
46
+ private images;
47
+ private raf;
48
+ private last;
49
+ private gl;
50
+ private c2d;
51
+ private view;
52
+ private ro;
53
+ playing: boolean;
54
+ /** Playback rate (1 = real time). */
55
+ private _speed;
56
+ /** Playback speed (1 = normal). Sounds follow it: 2× plays them twice as fast and an octave higher. */
57
+ get speed(): number;
58
+ set speed(v: number);
59
+ ready: Promise<void>;
60
+ /** Web Audio playback of the document's sounds (null when audio is off or the document has none). */
61
+ audio: WebAudioBackend | null;
62
+ constructor(opts: PlayerOptions);
63
+ get stateMachine(): StateMachineInstance | null;
64
+ private load;
65
+ private setupRenderer;
66
+ private resize;
67
+ private toSkeleton;
68
+ /** Page (client) coordinates, e.g. a pointer event's clientX/clientY, to skeleton space (y up), through the current fit. */
69
+ clientToSkeleton(clientX: number, clientY: number): [number, number];
70
+ /**
71
+ * The active bounding boxes in the current pose (skeleton space), with point / segment / AABB / overlap queries:
72
+ * `player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY))`.
73
+ */
74
+ boundingBoxes(): SkeletonBounds;
75
+ private bindPointer;
76
+ private draw;
77
+ play(): void;
78
+ /** Change how the artboard fits the canvas ("none" = actual size, centred). */
79
+ setFit(fit: "contain" | "cover" | "none"): void;
80
+ /** Pause the animation and its sounds (play() continues both from where they were). */
81
+ pause(): void;
82
+ /** Mute or unmute this player's sounds. */
83
+ setMuted(muted: boolean): void;
84
+ get muted(): boolean;
85
+ /**
86
+ * Mute, unmute or toggle one sound bus by name or id ("music", "sfx"…), or the master with null / "master", e.g.
87
+ * from music and sound-effect buttons on your page. Same as a mute-button listener inside the artboard, so both
88
+ * stay in step. Returns the new state, or null when the file has no such bus (or hasn't loaded yet).
89
+ */
90
+ setBusMuted(bus: string | null, muted?: boolean | "toggle"): boolean | null;
91
+ /** Flip a bus's mute (see setBusMuted). Returns the new state. */
92
+ toggleBus(bus: string | null): boolean | null;
93
+ /** Whether a bus (name or id; null / "master" = master) is muted right now; null when there is no such bus. */
94
+ isBusMuted(bus: string | null): boolean | null;
95
+ /** The file's sound buses with their current mute state. */
96
+ get buses(): {
97
+ name: string;
98
+ muted: boolean;
99
+ }[];
100
+ setInput(name: string, value: boolean | number | string): void;
101
+ /**
102
+ * Show fixed text (or a `{input}` template) in a slot's text attachment instead of its own; null restores it.
103
+ * Works with or without a state machine.
104
+ */
105
+ setText(slot: string, text: string | null): void;
106
+ fire(name: string): void;
107
+ getInput(name: string): import("@openbone/core").InputValue | undefined;
108
+ /** Show a skin (outfit) by name or id; null shows the default skin only. */
109
+ setSkin(name: string | null): void;
110
+ /** Names of the document's skins (the first is the default skin). */
111
+ get skins(): string[];
112
+ playAnimation(name: string, loop?: boolean): void;
113
+ dispose(): void;
114
+ }
115
+ type GlColor = [number, number, number, number];
116
+ /**
117
+ * Any CSS colour (#rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/hsl(), named colours…) as premultiplied RGBA for WebGL.
118
+ * Hex is parsed directly; anything else goes through a 2D context, which normalises it the way CSS does. Cached, since
119
+ * draw() asks every frame.
120
+ */
121
+ export declare function colorToGl(color: string): GlColor;
122
+ export {};
package/dist/player.js ADDED
@@ -0,0 +1,337 @@
1
+ import { parseDocument, textureAssets } from "@openbone/core";
2
+ import { CanvasRenderer } from "@openbone/render-canvas";
3
+ import { WebGLRenderer } from "@openbone/render-webgl";
4
+ import { OpenBoneInstance } from "@openbone/runtime";
5
+ import { WebAudioBackend } from "./audio.js";
6
+ let scriptHostFactory = null;
7
+ /**
8
+ * Replace how players create the sandbox for documents with scripts (default: load `@openbone/scripting`).
9
+ * Bundles use it to supply an inlined QuickJS build, or `() => Promise.resolve(null)` to run without scripts.
10
+ */
11
+ export function setScriptHostFactory(factory) {
12
+ scriptHostFactory = factory;
13
+ }
14
+ /** Plays an OpenBone document on a canvas, with pointer input routed to its state machine. */
15
+ export class Player {
16
+ opts;
17
+ instance;
18
+ doc;
19
+ images = new Map();
20
+ raf = 0;
21
+ last = 0;
22
+ gl = null;
23
+ c2d = null;
24
+ view = { x: 0, y: 0, zoom: 1 };
25
+ ro = null;
26
+ playing = false;
27
+ /** Playback rate (1 = real time). */
28
+ _speed = 1;
29
+ /** Playback speed (1 = normal). Sounds follow it: 2× plays them twice as fast and an octave higher. */
30
+ get speed() {
31
+ return this._speed;
32
+ }
33
+ set speed(v) {
34
+ this._speed = v;
35
+ this.audio?.setSpeed(v);
36
+ }
37
+ ready;
38
+ /** Web Audio playback of the document's sounds (null when audio is off or the document has none). */
39
+ audio = null;
40
+ constructor(opts) {
41
+ this.opts = opts;
42
+ this.ready = this.load();
43
+ }
44
+ get stateMachine() {
45
+ return this.instance?.stateMachine ?? null;
46
+ }
47
+ async load() {
48
+ const o = this.opts;
49
+ let base = o.baseUrl ?? "";
50
+ if (typeof o.src === "string") {
51
+ const res = await fetch(o.src);
52
+ if (!res.ok)
53
+ throw new Error(`OpenBone: failed to load ${o.src} (${res.status})`);
54
+ // .obone (JSON) or .obonb (binary), detected from the bytes.
55
+ this.doc = parseDocument(new Uint8Array(await res.arrayBuffer()));
56
+ if (!o.baseUrl) {
57
+ // blob:/data: URLs have no folder to resolve relative image paths against.
58
+ try {
59
+ base = new URL(".", new URL(o.src, location.href)).href;
60
+ }
61
+ catch {
62
+ base = "";
63
+ }
64
+ }
65
+ }
66
+ else
67
+ this.doc = o.src;
68
+ await Promise.all(textureAssets(this.doc).map((img) => new Promise((resolve) => {
69
+ const el = new Image();
70
+ el.crossOrigin = "anonymous";
71
+ el.onload = () => {
72
+ this.images.set(img.id, el);
73
+ resolve();
74
+ };
75
+ el.onerror = () => resolve();
76
+ el.src = o.resolveImageUrl ? o.resolveImageUrl(img.src) : /^(data:|https?:|blob:|\/)/.test(img.src) ? img.src : base + img.src;
77
+ })));
78
+ // null: scripts off on purpose ("none", no scripts, or no sandbox in this build, which warns above).
79
+ let scriptHost = null;
80
+ if (typeof o.scripts === "object")
81
+ scriptHost = o.scripts;
82
+ else if (o.scripts !== "none" && this.doc.scripts.length) {
83
+ if (scriptHostFactory) {
84
+ scriptHost = (await scriptHostFactory()) ?? null;
85
+ if (!scriptHost)
86
+ console.warn("OpenBone: this player build has no script sandbox; the document's scripts will not run.");
87
+ }
88
+ else {
89
+ const { createQuickJsHost } = await import("@openbone/scripting");
90
+ scriptHost = await createQuickJsHost();
91
+ }
92
+ }
93
+ this.instance = new OpenBoneInstance(this.doc, { scriptHost });
94
+ if (o.audio !== false && this.doc.audio?.assets.length && typeof AudioContext !== "undefined") {
95
+ this.audio = new WebAudioBackend(this.doc, { baseUrl: base, context: o.audioContext, resolveUrl: o.resolveAudioUrl });
96
+ this.audio.setMuted(o.audio === "muted");
97
+ this.audio.setSpeed(this._speed);
98
+ this.audio.unlock(o.canvas.ownerDocument?.defaultView ?? window);
99
+ void this.audio.preload();
100
+ this.instance.on("audio", this.audio.handle);
101
+ }
102
+ if (o.skin)
103
+ this.instance.skeleton.setSkin(o.skin);
104
+ if (o.onEvent)
105
+ this.instance.on("event", o.onEvent);
106
+ if (o.onStateChange)
107
+ this.instance.on("stateChange", o.onStateChange);
108
+ if (o.animation)
109
+ this.instance.play(o.animation);
110
+ else if (this.doc.stateMachines.length)
111
+ this.instance.useStateMachine(o.stateMachine);
112
+ else if (this.doc.animations.length)
113
+ this.instance.play(this.doc.animations[0].name);
114
+ this.setupRenderer();
115
+ this.bindPointer();
116
+ this.ro = new ResizeObserver(() => this.resize());
117
+ this.ro.observe(o.canvas);
118
+ this.resize();
119
+ this.instance.advance(0);
120
+ this.draw();
121
+ if (o.autoplay !== false)
122
+ this.play();
123
+ o.onLoad?.(this);
124
+ }
125
+ setupRenderer() {
126
+ const img = (id) => this.images.get(id) ?? null;
127
+ if (this.opts.renderer !== "canvas") {
128
+ try {
129
+ this.gl = new WebGLRenderer(this.opts.canvas, img);
130
+ return;
131
+ }
132
+ catch {
133
+ /* fall back to 2D */
134
+ }
135
+ }
136
+ this.c2d = new CanvasRenderer(this.opts.canvas.getContext("2d"), img);
137
+ }
138
+ resize() {
139
+ const c = this.opts.canvas;
140
+ const dpr = window.devicePixelRatio || 1;
141
+ const w = c.clientWidth || this.doc.width;
142
+ const h = c.clientHeight || this.doc.height;
143
+ c.width = Math.round(w * dpr);
144
+ c.height = Math.round(h * dpr);
145
+ const fit = this.opts.fit ?? "contain";
146
+ const z = fit === "none" ? 1 : (fit === "cover" ? Math.max : Math.min)(w / this.doc.width, h / this.doc.height);
147
+ this.view = { zoom: z, x: (w - this.doc.width * z) / 2, y: (h - this.doc.height * z) / 2 };
148
+ if (!this.playing)
149
+ this.draw();
150
+ }
151
+ toSkeleton(e) {
152
+ return this.clientToSkeleton(e.clientX, e.clientY);
153
+ }
154
+ /** Page (client) coordinates, e.g. a pointer event's clientX/clientY, to skeleton space (y up), through the current fit. */
155
+ clientToSkeleton(clientX, clientY) {
156
+ const r = this.opts.canvas.getBoundingClientRect();
157
+ const ax = (clientX - r.left - this.view.x) / this.view.zoom;
158
+ const ay = (clientY - r.top - this.view.y) / this.view.zoom;
159
+ return this.instance.artboardToSkeleton(ax, ay);
160
+ }
161
+ /**
162
+ * The active bounding boxes in the current pose (skeleton space), with point / segment / AABB / overlap queries:
163
+ * `player.boundingBoxes().containsPoint(...player.clientToSkeleton(e.clientX, e.clientY))`.
164
+ */
165
+ boundingBoxes() {
166
+ return this.instance.boundingBoxes();
167
+ }
168
+ bindPointer() {
169
+ const c = this.opts.canvas;
170
+ const send = (type) => (e) => this.instance.pointer(type, ...this.toSkeleton(e));
171
+ c.addEventListener("pointerdown", send("down"));
172
+ c.addEventListener("pointerup", send("up"));
173
+ c.addEventListener("pointermove", send("move"));
174
+ c.addEventListener("pointerleave", (e) => this.instance.pointer("move", -1e9, -1e9) ?? e);
175
+ }
176
+ draw() {
177
+ const dpr = window.devicePixelRatio || 1;
178
+ const v = { x: this.view.x * dpr, y: this.view.y * dpr, zoom: this.view.zoom * dpr };
179
+ const bg = this.opts.background === undefined ? this.doc.background : this.opts.background;
180
+ if (this.gl) {
181
+ const col = bg ? colorToGl(bg) : [0, 0, 0, 0];
182
+ this.gl.render(this.instance.skeleton, v, col);
183
+ }
184
+ else if (this.c2d) {
185
+ const ctx = this.c2d.ctx;
186
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
187
+ ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
188
+ if (bg) {
189
+ ctx.fillStyle = bg;
190
+ ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
191
+ }
192
+ this.c2d.render(this.instance.skeleton, { view: v, clear: false });
193
+ }
194
+ }
195
+ play() {
196
+ if (this.playing)
197
+ return;
198
+ this.playing = true;
199
+ this.audio?.resumeAll();
200
+ this.last = performance.now();
201
+ const tick = (now) => {
202
+ if (!this.playing)
203
+ return;
204
+ const dt = Math.min(0.1, (now - this.last) / 1000);
205
+ this.last = now;
206
+ this.instance.advance(dt * this.speed);
207
+ this.draw();
208
+ this.raf = requestAnimationFrame(tick);
209
+ };
210
+ this.raf = requestAnimationFrame(tick);
211
+ }
212
+ /** Change how the artboard fits the canvas ("none" = actual size, centred). */
213
+ setFit(fit) {
214
+ this.opts.fit = fit;
215
+ if (this.doc)
216
+ this.resize();
217
+ }
218
+ /** Pause the animation and its sounds (play() continues both from where they were). */
219
+ pause() {
220
+ this.playing = false;
221
+ cancelAnimationFrame(this.raf);
222
+ this.audio?.pauseAll();
223
+ }
224
+ /** Mute or unmute this player's sounds. */
225
+ setMuted(muted) {
226
+ this.audio?.setMuted(muted);
227
+ }
228
+ get muted() {
229
+ return this.audio?.muted ?? false;
230
+ }
231
+ /**
232
+ * Mute, unmute or toggle one sound bus by name or id ("music", "sfx"…), or the master with null / "master", e.g.
233
+ * from music and sound-effect buttons on your page. Same as a mute-button listener inside the artboard, so both
234
+ * stay in step. Returns the new state, or null when the file has no such bus (or hasn't loaded yet).
235
+ */
236
+ setBusMuted(bus, muted = true) {
237
+ return this.instance?.setBusMuted(bus, muted) ?? null;
238
+ }
239
+ /** Flip a bus's mute (see setBusMuted). Returns the new state. */
240
+ toggleBus(bus) {
241
+ return this.setBusMuted(bus, "toggle");
242
+ }
243
+ /** Whether a bus (name or id; null / "master" = master) is muted right now; null when there is no such bus. */
244
+ isBusMuted(bus) {
245
+ return this.instance?.isBusMuted(bus) ?? null;
246
+ }
247
+ /** The file's sound buses with their current mute state. */
248
+ get buses() {
249
+ return (this.doc?.audio?.buses ?? []).map((b) => ({ name: b.name, muted: this.isBusMuted(b.id) ?? b.muted }));
250
+ }
251
+ // ---- convenience API (Rive-like) ----
252
+ setInput(name, value) {
253
+ this.stateMachine?.setInput(name, value);
254
+ }
255
+ /**
256
+ * Show fixed text (or a `{input}` template) in a slot's text attachment instead of its own; null restores it.
257
+ * Works with or without a state machine.
258
+ */
259
+ setText(slot, text) {
260
+ this.instance?.skeleton.setText(slot, text);
261
+ if (!this.playing && this.instance)
262
+ this.draw();
263
+ }
264
+ fire(name) {
265
+ this.stateMachine?.fire(name);
266
+ }
267
+ getInput(name) {
268
+ return this.stateMachine?.getInput(name);
269
+ }
270
+ /** Show a skin (outfit) by name or id; null shows the default skin only. */
271
+ setSkin(name) {
272
+ if (!this.instance) {
273
+ this.opts.skin = name ?? undefined;
274
+ return;
275
+ }
276
+ this.instance.skeleton.setSkin(name);
277
+ if (name && !this.instance.skeleton.skin)
278
+ console.warn(`OpenBone: skin "${name}" not found`);
279
+ if (!this.playing) {
280
+ this.instance.advance(0);
281
+ this.draw();
282
+ }
283
+ }
284
+ /** Names of the document's skins (the first is the default skin). */
285
+ get skins() {
286
+ return this.doc?.skeleton.skins.map((s) => s.name) ?? [];
287
+ }
288
+ playAnimation(name, loop = true) {
289
+ this.instance.play(name, loop);
290
+ }
291
+ dispose() {
292
+ this.pause();
293
+ this.ro?.disconnect();
294
+ this.instance?.dispose();
295
+ this.audio?.dispose();
296
+ this.gl?.dispose();
297
+ }
298
+ }
299
+ const glColors = new Map();
300
+ /**
301
+ * Any CSS colour (#rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/hsl(), named colours…) as premultiplied RGBA for WebGL.
302
+ * Hex is parsed directly; anything else goes through a 2D context, which normalises it the way CSS does. Cached, since
303
+ * draw() asks every frame.
304
+ */
305
+ export function colorToGl(color) {
306
+ const hit = glColors.get(color);
307
+ if (hit)
308
+ return hit;
309
+ let rgba = parseHex(color);
310
+ if (!rgba && typeof document !== "undefined") {
311
+ const ctx = document.createElement("canvas").getContext("2d");
312
+ if (ctx) {
313
+ ctx.fillStyle = "#000000";
314
+ ctx.fillStyle = color; // invalid colours leave it unchanged
315
+ rgba = parseHex(ctx.fillStyle) ?? parseRgbFunction(ctx.fillStyle);
316
+ }
317
+ }
318
+ const [r, g, b, a] = rgba ?? [0, 0, 0, 1];
319
+ const out = [r * a, g * a, b * a, a];
320
+ glColors.set(color, out);
321
+ return out;
322
+ }
323
+ function parseHex(color) {
324
+ const m = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(color.trim());
325
+ if (!m)
326
+ return null;
327
+ let h = m[1];
328
+ if (h.length <= 4)
329
+ h = [...h].map((c) => c + c).join("");
330
+ const n = (i) => parseInt(h.slice(i, i + 2), 16) / 255;
331
+ return [n(0), n(2), n(4), h.length === 8 ? n(6) : 1];
332
+ }
333
+ /** "rgb(r, g, b)" / "rgba(r, g, b, a)", as a 2D context reports colours with transparency. */
334
+ function parseRgbFunction(color) {
335
+ const m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+))?\s*\)$/.exec(color.trim());
336
+ return m ? [Number(m[1]) / 255, Number(m[2]) / 255, Number(m[3]) / 255, m[4] === undefined ? 1 : Number(m[4])] : null;
337
+ }
package/package.json CHANGED
@@ -1,6 +1,74 @@
1
1
  {
2
2
  "name": "@openbone/player",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.0",
4
+ "description": "Drop-in <openbone-player> web component and JS API for OpenBone animations",
5
+ "keywords": [
6
+ "openbone",
7
+ "skeletal-animation",
8
+ "2d-animation",
9
+ "animation",
10
+ "player",
11
+ "web-component",
12
+ "custom-element"
13
+ ],
14
+ "homepage": "https://github.com/UXCentury/open-bone/tree/main/packages/player#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/UXCentury/open-bone/issues"
17
+ },
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/UXCentury/open-bone.git",
21
+ "directory": "packages/player"
22
+ },
23
+ "license": "MIT",
24
+ "type": "module",
25
+ "sideEffects": [
26
+ "./src/bundle/*",
27
+ "./dist/bundle/*"
28
+ ],
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "default": "./dist/index.js"
33
+ },
34
+ "./audio": {
35
+ "types": "./dist/audio.d.ts",
36
+ "default": "./dist/audio.js"
37
+ },
38
+ "./bundle": {
39
+ "types": "./dist/bundle/build.d.ts",
40
+ "default": "./dist/bundle/build.js"
41
+ }
42
+ },
43
+ "files": [
44
+ "dist"
45
+ ],
46
+ "publishConfig": {
47
+ "access": "public"
48
+ },
49
+ "dependencies": {
50
+ "quickjs-emscripten": "^0.32.0",
51
+ "@openbone/core": "0.4.0",
52
+ "@openbone/render-canvas": "0.4.0",
53
+ "@openbone/scripting": "0.4.0",
54
+ "@openbone/runtime": "0.4.0",
55
+ "@openbone/render-webgl": "0.4.0"
56
+ },
57
+ "peerDependencies": {
58
+ "esbuild": ">=0.25.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "esbuild": {
62
+ "optional": true
63
+ }
64
+ },
65
+ "devDependencies": {
66
+ "esbuild": "^0.28.2"
67
+ },
68
+ "scripts": {
69
+ "build:bundle": "tsx src/bundle/build.ts",
70
+ "build": "node ../build.mjs"
71
+ },
72
+ "main": "./dist/index.js",
73
+ "types": "./dist/index.d.ts"
6
74
  }