@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 +21 -0
- package/README.md +223 -2
- package/dist/audio.d.ts +101 -0
- package/dist/audio.js +439 -0
- package/dist/bridge.d.ts +115 -0
- package/dist/bridge.js +126 -0
- package/dist/bundle/build.d.ts +33 -0
- package/dist/bundle/build.js +149 -0
- package/dist/bundle/core-lite.d.ts +6 -0
- package/dist/bundle/core-lite.js +6 -0
- package/dist/bundle/sandbox-lazy.d.ts +7 -0
- package/dist/bundle/sandbox-lazy.js +54 -0
- package/dist/bundle/sandbox-none.d.ts +3 -0
- package/dist/bundle/sandbox-none.js +3 -0
- package/dist/bundle/sandbox-quickjs.d.ts +3 -0
- package/dist/bundle/sandbox-quickjs.js +7 -0
- package/dist/bundle/scripting-stub.d.ts +2 -0
- package/dist/bundle/scripting-stub.js +4 -0
- package/dist/bundle/scripts-addon.d.ts +1 -0
- package/dist/bundle/scripts-addon.js +15 -0
- package/dist/bundle/web.d.ts +15 -0
- package/dist/bundle/web.js +19 -0
- package/dist/bundle/webview.d.ts +19 -0
- package/dist/bundle/webview.js +161 -0
- package/dist/element.d.ts +47 -0
- package/dist/element.js +126 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/player.d.ts +122 -0
- package/dist/player.js +337 -0
- package/package.json +71 -3
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare const BUNDLE_ENTRY: string;
|
|
2
|
+
/** Folder whose changes invalidate the bundle (player, runtime, renderers, core, scripting sources). */
|
|
3
|
+
export declare const BUNDLE_SOURCES: string;
|
|
4
|
+
export declare function quickJsWasmPath(): string;
|
|
5
|
+
/** Build the bundle and return its source. */
|
|
6
|
+
export declare function buildPlayerBundle(opts?: {
|
|
7
|
+
minify?: boolean;
|
|
8
|
+
}): Promise<string>;
|
|
9
|
+
export type WebBundleFormat = "iife" | "esm";
|
|
10
|
+
export interface WebBundleOptions {
|
|
11
|
+
/** "iife": classic `<script src>` exposing `window.OpenBone`; "esm": an ES module with named exports. */
|
|
12
|
+
format?: WebBundleFormat;
|
|
13
|
+
minify?: boolean;
|
|
14
|
+
/**
|
|
15
|
+
* Script sandbox: true inlines QuickJS (one file, +0.7 MB); "lazy" loads `openbone-scripts.js` + `quickjs.wasm`
|
|
16
|
+
* from next to the player only when an animation has scripts (see buildScriptsAddon); false leaves it out.
|
|
17
|
+
*/
|
|
18
|
+
scripts?: boolean | "lazy";
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Build the web player library (`<openbone-player>` + `OpenBone.Player`) for websites: classic script or ES module,
|
|
22
|
+
* minified or readable, with or without the script sandbox. Returns the source.
|
|
23
|
+
*/
|
|
24
|
+
export declare function buildWebBundle(opts?: WebBundleOptions): Promise<string>;
|
|
25
|
+
/**
|
|
26
|
+
* `openbone-scripts.js`: the QuickJS sandbox add-on loaded by "lazy" web players (classic script, any page).
|
|
27
|
+
* Ship it with `quickjs.wasm` (quickJsWasmBytes) next to the player.
|
|
28
|
+
*/
|
|
29
|
+
export declare function buildScriptsAddon(opts?: {
|
|
30
|
+
minify?: boolean;
|
|
31
|
+
}): Promise<string>;
|
|
32
|
+
/** The QuickJS .wasm the sandbox add-on fetches. */
|
|
33
|
+
export declare function quickJsWasmBytes(): Uint8Array;
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build the self-contained WebView player bundle: one classic (non-module) script with the player, renderers,
|
|
3
|
+
* runtime and the QuickJS script sandbox (its .wasm inlined), so it runs from file:// in any WebView.
|
|
4
|
+
*
|
|
5
|
+
* pnpm build:player-bundle -> packages/player/dist/openbone-player.js
|
|
6
|
+
*
|
|
7
|
+
* The editor builds the same bundle through a Vite plugin (apps/editor/vite.config.ts), so exports never need
|
|
8
|
+
* a prebuilt file and work offline.
|
|
9
|
+
*/
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import { createRequire } from "node:module";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
import { build } from "esbuild";
|
|
15
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
16
|
+
// ".ts" when run from the sources (monorepo), ".js" when run from the compiled npm package (dist/bundle).
|
|
17
|
+
const ext = path.extname(fileURLToPath(import.meta.url)) || ".js";
|
|
18
|
+
const entry = (name) => path.join(here, `${name}${ext}`);
|
|
19
|
+
export const BUNDLE_ENTRY = entry("webview");
|
|
20
|
+
/** Folder whose changes invalidate the bundle (player, runtime, renderers, core, scripting sources). */
|
|
21
|
+
export const BUNDLE_SOURCES = path.resolve(here, "../../..");
|
|
22
|
+
export function quickJsWasmPath() {
|
|
23
|
+
const req = createRequire(import.meta.url);
|
|
24
|
+
const qjs = req.resolve("quickjs-emscripten");
|
|
25
|
+
const variant = createRequire(qjs).resolve("@jitl/quickjs-wasmfile-release-sync");
|
|
26
|
+
return path.join(path.dirname(variant), "emscripten-module.wasm");
|
|
27
|
+
}
|
|
28
|
+
/** Build the bundle and return its source. */
|
|
29
|
+
export async function buildPlayerBundle(opts = {}) {
|
|
30
|
+
const wasm = quickJsWasmPath();
|
|
31
|
+
const result = await build({
|
|
32
|
+
entryPoints: [BUNDLE_ENTRY],
|
|
33
|
+
bundle: true,
|
|
34
|
+
write: false,
|
|
35
|
+
format: "iife",
|
|
36
|
+
platform: "browser",
|
|
37
|
+
target: "es2020",
|
|
38
|
+
minify: opts.minify ?? true,
|
|
39
|
+
legalComments: "none",
|
|
40
|
+
// Emscripten builds a .wasm URL from import.meta.url even when given the bytes. Classic scripts have no
|
|
41
|
+
// import.meta, and the page URL can be blob:/about: (not a valid base), so use a fixed, never-fetched URL.
|
|
42
|
+
define: { "import.meta.url": JSON.stringify("file:///openbone-player.js") },
|
|
43
|
+
logLevel: "silent",
|
|
44
|
+
banner: { js: "/*! OpenBone player bundle (MIT). Includes quickjs-emscripten (MIT). https://github.com/UXCentury/open-bone */" },
|
|
45
|
+
plugins: [
|
|
46
|
+
{
|
|
47
|
+
name: "openbone-quickjs-wasm",
|
|
48
|
+
setup(b) {
|
|
49
|
+
b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
|
|
50
|
+
b.onResolve({ filter: /^openbone:quickjs-wasm$/ }, () => ({ path: wasm, namespace: "openbone-wasm" }));
|
|
51
|
+
b.onLoad({ filter: /.*/, namespace: "openbone-wasm" }, () => ({ contents: fs.readFileSync(wasm), loader: "binary" }));
|
|
52
|
+
},
|
|
53
|
+
},
|
|
54
|
+
],
|
|
55
|
+
});
|
|
56
|
+
return result.outputFiles[0].text;
|
|
57
|
+
}
|
|
58
|
+
function packageVersion() {
|
|
59
|
+
try {
|
|
60
|
+
return JSON.parse(fs.readFileSync(path.resolve(here, "../../package.json"), "utf8")).version ?? "0.0.0";
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return "0.0.0";
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Build the web player library (`<openbone-player>` + `OpenBone.Player`) for websites: classic script or ES module,
|
|
68
|
+
* minified or readable, with or without the script sandbox. Returns the source.
|
|
69
|
+
*/
|
|
70
|
+
export async function buildWebBundle(opts = {}) {
|
|
71
|
+
const format = opts.format ?? "iife";
|
|
72
|
+
const scripts = opts.scripts ?? true;
|
|
73
|
+
const minify = opts.minify ?? true;
|
|
74
|
+
const sandbox = scripts === "lazy" ? "sandbox-lazy" : scripts ? "sandbox-quickjs" : "sandbox-none";
|
|
75
|
+
const result = await build({
|
|
76
|
+
entryPoints: [entry("web")],
|
|
77
|
+
bundle: true,
|
|
78
|
+
write: false,
|
|
79
|
+
format,
|
|
80
|
+
...(format === "iife" ? { globalName: "OpenBone" } : {}),
|
|
81
|
+
platform: "browser",
|
|
82
|
+
target: "es2020",
|
|
83
|
+
minify,
|
|
84
|
+
legalComments: "none",
|
|
85
|
+
define: {
|
|
86
|
+
// Emscripten (inlined sandbox) needs some URL; the lazy loader reads the real one in ES modules.
|
|
87
|
+
...(scripts === "lazy" && format === "esm" ? {} : { "import.meta.url": JSON.stringify("file:///openbone-player.js") }),
|
|
88
|
+
__OPENBONE_VERSION__: JSON.stringify(packageVersion()),
|
|
89
|
+
},
|
|
90
|
+
logLevel: "silent",
|
|
91
|
+
banner: {
|
|
92
|
+
js: `/*! OpenBone web player ${packageVersion()} (MIT)${scripts === true ? ". Includes quickjs-emscripten (MIT)" : ""}. https://github.com/UXCentury/open-bone */`,
|
|
93
|
+
},
|
|
94
|
+
plugins: [
|
|
95
|
+
{
|
|
96
|
+
name: "openbone-web",
|
|
97
|
+
setup(b) {
|
|
98
|
+
b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
|
|
99
|
+
b.onResolve({ filter: /^openbone:script-sandbox$/ }, () => ({ path: entry(sandbox) }));
|
|
100
|
+
if (scripts !== true)
|
|
101
|
+
b.onResolve({ filter: /^@openbone\/scripting$/ }, () => ({ path: entry("scripting-stub") }));
|
|
102
|
+
b.onResolve({ filter: /^openbone:quickjs-wasm$/ }, () => ({ path: quickJsWasmPath(), namespace: "openbone-wasm" }));
|
|
103
|
+
b.onLoad({ filter: /.*/, namespace: "openbone-wasm" }, () => ({ contents: fs.readFileSync(quickJsWasmPath()), loader: "binary" }));
|
|
104
|
+
},
|
|
105
|
+
},
|
|
106
|
+
],
|
|
107
|
+
});
|
|
108
|
+
return result.outputFiles[0].text;
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* `openbone-scripts.js`: the QuickJS sandbox add-on loaded by "lazy" web players (classic script, any page).
|
|
112
|
+
* Ship it with `quickjs.wasm` (quickJsWasmBytes) next to the player.
|
|
113
|
+
*/
|
|
114
|
+
export async function buildScriptsAddon(opts = {}) {
|
|
115
|
+
const result = await build({
|
|
116
|
+
entryPoints: [entry("scripts-addon")],
|
|
117
|
+
bundle: true,
|
|
118
|
+
write: false,
|
|
119
|
+
format: "iife",
|
|
120
|
+
platform: "browser",
|
|
121
|
+
target: "es2020",
|
|
122
|
+
minify: opts.minify ?? true,
|
|
123
|
+
legalComments: "none",
|
|
124
|
+
define: { "import.meta.url": JSON.stringify("file:///openbone-scripts.js") },
|
|
125
|
+
logLevel: "silent",
|
|
126
|
+
banner: { js: `/*! OpenBone script sandbox ${packageVersion()} (MIT). Includes quickjs-emscripten (MIT). https://github.com/UXCentury/open-bone */` },
|
|
127
|
+
plugins: [
|
|
128
|
+
{
|
|
129
|
+
name: "openbone-scripts",
|
|
130
|
+
setup(b) {
|
|
131
|
+
b.onResolve({ filter: /^@openbone\/core$/ }, () => ({ path: entry("core-lite") }));
|
|
132
|
+
},
|
|
133
|
+
},
|
|
134
|
+
],
|
|
135
|
+
});
|
|
136
|
+
return result.outputFiles[0].text;
|
|
137
|
+
}
|
|
138
|
+
/** The QuickJS .wasm the sandbox add-on fetches. */
|
|
139
|
+
export function quickJsWasmBytes() {
|
|
140
|
+
return new Uint8Array(fs.readFileSync(quickJsWasmPath()));
|
|
141
|
+
}
|
|
142
|
+
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
143
|
+
if (isMain) {
|
|
144
|
+
const out = path.resolve(here, "../../dist/openbone-player.js");
|
|
145
|
+
const code = await buildPlayerBundle();
|
|
146
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
147
|
+
fs.writeFileSync(out, code);
|
|
148
|
+
console.log(`Wrote ${path.relative(process.cwd(), out)} (${(code.length / 1024).toFixed(0)} KB)`);
|
|
149
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@openbone/core` without the op registry and DocumentStore (they pull in zod, ~450 KB, and are only needed for
|
|
3
|
+
* editing). The bundle build aliases `@openbone/core` to this file; esbuild fails the build if a player module
|
|
4
|
+
* imports something not re-exported here.
|
|
5
|
+
*/
|
|
6
|
+
export * from "@openbone/core/lite";
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@openbone/core` without the op registry and DocumentStore (they pull in zod, ~450 KB, and are only needed for
|
|
3
|
+
* editing). The bundle build aliases `@openbone/core` to this file; esbuild fails the build if a player module
|
|
4
|
+
* imports something not re-exported here.
|
|
5
|
+
*/
|
|
6
|
+
export * from "@openbone/core/lite";
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Script sandbox for web bundles that ship QuickJS as separate files: `openbone-scripts.js` (the sandbox glue) and
|
|
3
|
+
* `quickjs.wasm`, next to the player. They are loaded only when an animation actually has scripts, so pages
|
|
4
|
+
* without scripts never download them. Set `window.OPENBONE_SCRIPTS_BASE` to load them from another folder.
|
|
5
|
+
*/
|
|
6
|
+
import type { ScriptHost } from "@openbone/runtime";
|
|
7
|
+
export declare function sandboxFactory(): Promise<ScriptHost | null>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Where the player was loaded from: classic scripts know their own <script> element; modules know import.meta.url.
|
|
2
|
+
const playerUrl = (() => {
|
|
3
|
+
try {
|
|
4
|
+
const s = typeof document !== "undefined" ? document.currentScript : null;
|
|
5
|
+
if (s?.src)
|
|
6
|
+
return s.src;
|
|
7
|
+
}
|
|
8
|
+
catch {
|
|
9
|
+
/* ignore */
|
|
10
|
+
}
|
|
11
|
+
try {
|
|
12
|
+
const u = import.meta.url;
|
|
13
|
+
if (u && !u.startsWith("file:///openbone-player"))
|
|
14
|
+
return u;
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
/* ignore */
|
|
18
|
+
}
|
|
19
|
+
return typeof location !== "undefined" ? location.href : "";
|
|
20
|
+
})();
|
|
21
|
+
/** Folder holding openbone-scripts.js and quickjs.wasm (default: the player's folder). */
|
|
22
|
+
function folder() {
|
|
23
|
+
const g = globalThis;
|
|
24
|
+
const b = g.OPENBONE_SCRIPTS_BASE ?? new URL(".", playerUrl).href;
|
|
25
|
+
return b.endsWith("/") ? b : `${b}/`;
|
|
26
|
+
}
|
|
27
|
+
let loading = null;
|
|
28
|
+
function loadAddon() {
|
|
29
|
+
const g = globalThis;
|
|
30
|
+
if (g.OpenBoneScripts)
|
|
31
|
+
return Promise.resolve(g.OpenBoneScripts);
|
|
32
|
+
loading ??= new Promise((resolve, reject) => {
|
|
33
|
+
const s = document.createElement("script");
|
|
34
|
+
s.src = `${folder()}openbone-scripts.js`;
|
|
35
|
+
s.async = true;
|
|
36
|
+
s.onload = () => (g.OpenBoneScripts ? resolve(g.OpenBoneScripts) : reject(new Error("openbone-scripts.js did not register")));
|
|
37
|
+
s.onerror = () => reject(new Error(`could not load ${s.src}`));
|
|
38
|
+
document.head.append(s);
|
|
39
|
+
}).catch((e) => {
|
|
40
|
+
loading = null;
|
|
41
|
+
throw e;
|
|
42
|
+
});
|
|
43
|
+
return loading;
|
|
44
|
+
}
|
|
45
|
+
export async function sandboxFactory() {
|
|
46
|
+
try {
|
|
47
|
+
const addon = await loadAddon();
|
|
48
|
+
return await addon.createHost(`${folder()}quickjs.wasm`);
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
console.warn("OpenBone: could not load the script sandbox (openbone-scripts.js + quickjs.wasm next to the player); scripts will not run.", e);
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createQuickJsHost } from "@openbone/scripting";
|
|
2
|
+
import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
|
|
3
|
+
import wasmBinary from "openbone:quickjs-wasm";
|
|
4
|
+
export async function sandboxFactory() {
|
|
5
|
+
const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary: wasmBinary.slice().buffer }));
|
|
6
|
+
return createQuickJsHost({ module });
|
|
7
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `openbone-scripts.js`: the QuickJS script sandbox as an add-on for the web player. The player loads it (and
|
|
3
|
+
* `quickjs.wasm`) only when an animation has scripts; see sandbox-lazy.ts. Registers `globalThis.OpenBoneScripts`.
|
|
4
|
+
*/
|
|
5
|
+
import { createQuickJsHost } from "@openbone/scripting";
|
|
6
|
+
import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
|
|
7
|
+
async function createHost(wasmUrl) {
|
|
8
|
+
const res = await fetch(wasmUrl);
|
|
9
|
+
if (!res.ok)
|
|
10
|
+
throw new Error(`${wasmUrl}: HTTP ${res.status}`);
|
|
11
|
+
const wasmBinary = await res.arrayBuffer();
|
|
12
|
+
const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary }));
|
|
13
|
+
return createQuickJsHost({ module });
|
|
14
|
+
}
|
|
15
|
+
globalThis.OpenBoneScripts = { createHost };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of the web player library (`openbone-player.js` / `.mjs`) shipped by the editor's Web export.
|
|
3
|
+
*
|
|
4
|
+
* Including it defines `<openbone-player>` (unless something already did) and exposes the API:
|
|
5
|
+
* - classic script: `window.OpenBone` = { Player, OpenBonePlayerElement, definePlayerElement, parseDocument, version }
|
|
6
|
+
* - ES module: the same names as exports.
|
|
7
|
+
*
|
|
8
|
+
* Built in two flavours: with the QuickJS script sandbox inlined (scripts run), or without it (smaller; documents
|
|
9
|
+
* with scripts still play, their scripts are skipped with a console warning). See build.ts.
|
|
10
|
+
*/
|
|
11
|
+
import { parseDocument } from "@openbone/core";
|
|
12
|
+
import { OpenBonePlayerElement, definePlayerElement } from "../element.js";
|
|
13
|
+
import { Player } from "../player.js";
|
|
14
|
+
export declare const version: string;
|
|
15
|
+
export { OpenBonePlayerElement, Player, definePlayerElement, parseDocument };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of the web player library (`openbone-player.js` / `.mjs`) shipped by the editor's Web export.
|
|
3
|
+
*
|
|
4
|
+
* Including it defines `<openbone-player>` (unless something already did) and exposes the API:
|
|
5
|
+
* - classic script: `window.OpenBone` = { Player, OpenBonePlayerElement, definePlayerElement, parseDocument, version }
|
|
6
|
+
* - ES module: the same names as exports.
|
|
7
|
+
*
|
|
8
|
+
* Built in two flavours: with the QuickJS script sandbox inlined (scripts run), or without it (smaller; documents
|
|
9
|
+
* with scripts still play, their scripts are skipped with a console warning). See build.ts.
|
|
10
|
+
*/
|
|
11
|
+
import { parseDocument } from "@openbone/core";
|
|
12
|
+
import { OpenBonePlayerElement, definePlayerElement } from "../element.js";
|
|
13
|
+
import { Player, setScriptHostFactory } from "../player.js";
|
|
14
|
+
import { sandboxFactory } from "openbone:script-sandbox";
|
|
15
|
+
export const version = __OPENBONE_VERSION__;
|
|
16
|
+
setScriptHostFactory(sandboxFactory);
|
|
17
|
+
if (typeof customElements !== "undefined" && !customElements.get("openbone-player"))
|
|
18
|
+
definePlayerElement();
|
|
19
|
+
export { OpenBonePlayerElement, Player, definePlayerElement, parseDocument };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of the self-contained player bundle (`openbone-player.js`) used by the WebView packages.
|
|
3
|
+
*
|
|
4
|
+
* The page provides the document in one of these ways (first found wins):
|
|
5
|
+
* - `<script type="application/octet-stream" id="openbone-data">BASE64</script>` (.obone or .obonb bytes)
|
|
6
|
+
* - `?src=url` in the page URL (fetched; needs http(s), not file://)
|
|
7
|
+
* - `window.OPENBONE_SRC` (a URL or a parsed document)
|
|
8
|
+
* Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
|
|
9
|
+
* data-background ("none" = transparent), data-renderer.
|
|
10
|
+
*
|
|
11
|
+
* It exposes `window.OpenBone` (see bridge.ts for the message format).
|
|
12
|
+
*/
|
|
13
|
+
import { type OpenBoneDocument } from "@openbone/core";
|
|
14
|
+
declare global {
|
|
15
|
+
interface Window {
|
|
16
|
+
OPENBONE_SRC?: string | OpenBoneDocument;
|
|
17
|
+
OpenBone?: unknown;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Entry of the self-contained player bundle (`openbone-player.js`) used by the WebView packages.
|
|
3
|
+
*
|
|
4
|
+
* The page provides the document in one of these ways (first found wins):
|
|
5
|
+
* - `<script type="application/octet-stream" id="openbone-data">BASE64</script>` (.obone or .obonb bytes)
|
|
6
|
+
* - `?src=url` in the page URL (fetched; needs http(s), not file://)
|
|
7
|
+
* - `window.OPENBONE_SRC` (a URL or a parsed document)
|
|
8
|
+
* Options come from `data-*` attributes on `<body>`: data-state-machine, data-animation, data-skin, data-fit,
|
|
9
|
+
* data-background ("none" = transparent), data-renderer.
|
|
10
|
+
*
|
|
11
|
+
* It exposes `window.OpenBone` (see bridge.ts for the message format).
|
|
12
|
+
*/
|
|
13
|
+
import { parseDocument } from "@openbone/core";
|
|
14
|
+
import { createQuickJsHost } from "@openbone/scripting";
|
|
15
|
+
import { RELEASE_SYNC, newQuickJSWASMModuleFromVariant, newVariant } from "quickjs-emscripten";
|
|
16
|
+
// Resolved by the bundle build to the QuickJS .wasm bytes (esbuild `binary` loader).
|
|
17
|
+
import wasmBinary from "openbone:quickjs-wasm";
|
|
18
|
+
import { Player } from "../player.js";
|
|
19
|
+
import { applyCommand, parseCommand, postToHost } from "../bridge.js";
|
|
20
|
+
function base64ToBytes(b64) {
|
|
21
|
+
const bin = atob(b64.replace(/\s+/g, ""));
|
|
22
|
+
const out = new Uint8Array(bin.length);
|
|
23
|
+
for (let i = 0; i < bin.length; i++)
|
|
24
|
+
out[i] = bin.charCodeAt(i);
|
|
25
|
+
return out;
|
|
26
|
+
}
|
|
27
|
+
function findSource() {
|
|
28
|
+
const el = document.getElementById("openbone-data");
|
|
29
|
+
if (el?.textContent?.trim())
|
|
30
|
+
return parseDocument(base64ToBytes(el.textContent));
|
|
31
|
+
const q = new URLSearchParams(location.search).get("src");
|
|
32
|
+
if (q)
|
|
33
|
+
return q;
|
|
34
|
+
return window.OPENBONE_SRC ?? null;
|
|
35
|
+
}
|
|
36
|
+
async function scriptHostFor() {
|
|
37
|
+
const module = await newQuickJSWASMModuleFromVariant(newVariant(RELEASE_SYNC, { wasmBinary: wasmBinary.slice().buffer }));
|
|
38
|
+
return createQuickJsHost({ module });
|
|
39
|
+
}
|
|
40
|
+
function start() {
|
|
41
|
+
const body = document.body;
|
|
42
|
+
const opt = (k) => body.dataset[k] || undefined;
|
|
43
|
+
let canvas = document.querySelector("canvas#openbone");
|
|
44
|
+
if (!canvas) {
|
|
45
|
+
canvas = document.createElement("canvas");
|
|
46
|
+
canvas.id = "openbone";
|
|
47
|
+
body.append(canvas);
|
|
48
|
+
}
|
|
49
|
+
let player = null;
|
|
50
|
+
const queue = [];
|
|
51
|
+
const inputs = () => {
|
|
52
|
+
const sm = player?.stateMachine;
|
|
53
|
+
if (!sm)
|
|
54
|
+
return [];
|
|
55
|
+
return sm.data.inputs.map((i) => ({ name: i.name, type: i.type, value: i.type === "trigger" ? null : (sm.getInput(i.name) ?? null) }));
|
|
56
|
+
};
|
|
57
|
+
const adapter = {
|
|
58
|
+
setInput: (n, v) => player?.setInput(n, v),
|
|
59
|
+
fire: (n) => player?.fire(n),
|
|
60
|
+
play: () => player?.play(),
|
|
61
|
+
pause: () => player?.pause(),
|
|
62
|
+
playAnimation: (n, loop) => player?.playAnimation(n, loop),
|
|
63
|
+
setSkin: (n) => player?.setSkin(n),
|
|
64
|
+
useStateMachine: (n) => {
|
|
65
|
+
if (!player)
|
|
66
|
+
return;
|
|
67
|
+
player.instance.useStateMachine(n);
|
|
68
|
+
watchInputs();
|
|
69
|
+
},
|
|
70
|
+
setMuted: (m) => player?.setMuted(m),
|
|
71
|
+
setBusMuted: (b, m) => player?.setBusMuted(b, m),
|
|
72
|
+
inputs,
|
|
73
|
+
};
|
|
74
|
+
const watchInputs = () => player?.stateMachine?.on("inputChange", () => postToHost({ type: "inputs", inputs: inputs() }));
|
|
75
|
+
/** Run a command now, or once the document has loaded. Errors go to the host as `error` messages. */
|
|
76
|
+
const run = (cmd) => {
|
|
77
|
+
try {
|
|
78
|
+
const c = parseCommand(cmd);
|
|
79
|
+
if (!player?.instance) {
|
|
80
|
+
queue.push(c);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const reply = applyCommand(adapter, c);
|
|
84
|
+
if (reply)
|
|
85
|
+
postToHost(reply);
|
|
86
|
+
}
|
|
87
|
+
catch (e) {
|
|
88
|
+
postToHost({ type: "error", message: e.message });
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
window.OpenBone = {
|
|
92
|
+
/** Host entry point: a JSON string or object command. */
|
|
93
|
+
receive: run,
|
|
94
|
+
setInput: (name, value) => run({ type: "setInput", name, value }),
|
|
95
|
+
fire: (name) => run({ type: "fire", name }),
|
|
96
|
+
setMuted: (muted) => run({ type: "setMuted", muted }),
|
|
97
|
+
setBusMuted: (bus, muted = true) => run({ type: "setBusMuted", bus, muted }),
|
|
98
|
+
play: (animation, loop) => run({ type: "play", animation, loop }),
|
|
99
|
+
pause: () => run({ type: "pause" }),
|
|
100
|
+
setSkin: (name) => run({ type: "setSkin", name }),
|
|
101
|
+
useStateMachine: (name) => run({ type: "useStateMachine", name }),
|
|
102
|
+
getInputs: () => inputs(),
|
|
103
|
+
get player() {
|
|
104
|
+
return player;
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
// iframe hosts can send commands with postMessage({ openbone: command }).
|
|
108
|
+
window.addEventListener("message", (e) => {
|
|
109
|
+
const d = e.data;
|
|
110
|
+
if (d && typeof d === "object" && "openbone" in d)
|
|
111
|
+
run(d.openbone);
|
|
112
|
+
});
|
|
113
|
+
let src;
|
|
114
|
+
try {
|
|
115
|
+
src = findSource();
|
|
116
|
+
}
|
|
117
|
+
catch (e) {
|
|
118
|
+
postToHost({ type: "error", message: `Could not read the embedded document: ${e.message}` });
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
if (!src) {
|
|
122
|
+
postToHost({ type: "error", message: "No document: embed one in #openbone-data, or pass ?src=" });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const bg = opt("background");
|
|
126
|
+
const hasScripts = typeof src === "object" ? src.scripts.length > 0 : true;
|
|
127
|
+
(hasScripts ? scriptHostFor() : Promise.resolve(undefined)).then((host) => {
|
|
128
|
+
player = new Player({
|
|
129
|
+
canvas: canvas,
|
|
130
|
+
src: src,
|
|
131
|
+
stateMachine: opt("stateMachine"),
|
|
132
|
+
animation: opt("animation"),
|
|
133
|
+
skin: opt("skin"),
|
|
134
|
+
fit: opt("fit") ?? "contain",
|
|
135
|
+
renderer: opt("renderer") ?? "webgl",
|
|
136
|
+
...(bg !== undefined ? { background: bg === "none" ? null : bg } : {}),
|
|
137
|
+
scripts: host ?? "none",
|
|
138
|
+
onEvent: (e) => postToHost({ type: "event", name: e.name, int: e.int, float: e.float, string: e.string, time: e.time }),
|
|
139
|
+
onStateChange: (e) => postToHost({ type: "stateChange", layer: e.layer, from: e.from, to: e.to }),
|
|
140
|
+
});
|
|
141
|
+
player.ready.then(() => {
|
|
142
|
+
const p = player;
|
|
143
|
+
watchInputs();
|
|
144
|
+
postToHost({
|
|
145
|
+
type: "ready",
|
|
146
|
+
animations: p.doc.animations.map((a) => a.name),
|
|
147
|
+
stateMachines: p.doc.stateMachines.map((s) => s.name),
|
|
148
|
+
inputs: inputs(),
|
|
149
|
+
skins: p.skins,
|
|
150
|
+
width: p.doc.width,
|
|
151
|
+
height: p.doc.height,
|
|
152
|
+
});
|
|
153
|
+
for (const c of queue.splice(0))
|
|
154
|
+
run(c);
|
|
155
|
+
}, (e) => postToHost({ type: "error", message: e.message }));
|
|
156
|
+
}, (e) => postToHost({ type: "error", message: `Script engine failed to start: ${e.message}` }));
|
|
157
|
+
}
|
|
158
|
+
if (document.readyState === "loading")
|
|
159
|
+
document.addEventListener("DOMContentLoaded", start);
|
|
160
|
+
else
|
|
161
|
+
start();
|
|
@@ -0,0 +1,47 @@
|
|
|
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 declare class OpenBonePlayerElement extends HTMLElement {
|
|
11
|
+
/** `skin` switches skins in place; any other of these reloads the player with the new settings. */
|
|
12
|
+
static observedAttributes: string[];
|
|
13
|
+
player: 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: AudioContext | null;
|
|
19
|
+
private canvas;
|
|
20
|
+
constructor();
|
|
21
|
+
connectedCallback(): void;
|
|
22
|
+
disconnectedCallback(): void;
|
|
23
|
+
attributeChangedCallback(n: string, old: string | null, val: string | null): void;
|
|
24
|
+
/** The attributes the current player was built with (everything observed except `skin`). */
|
|
25
|
+
private loadedWith;
|
|
26
|
+
private settings;
|
|
27
|
+
private init;
|
|
28
|
+
/** `background` attribute: a colour, "transparent"/"none" for no background, absent for the file's own. */
|
|
29
|
+
private background;
|
|
30
|
+
setInput(name: string, value: boolean | number | string): void;
|
|
31
|
+
setText(slot: string, text: string | null): void;
|
|
32
|
+
fire(name: string): void;
|
|
33
|
+
setSkin(name: string | null): void;
|
|
34
|
+
play(): void;
|
|
35
|
+
/** Mute or unmute everything. */
|
|
36
|
+
setMuted(muted: boolean): void;
|
|
37
|
+
/** Mute, unmute or toggle a sound bus by name ("music", "sfx"…); null or "master" = the master. */
|
|
38
|
+
setBusMuted(bus: string | null, muted?: boolean | "toggle"): boolean | null;
|
|
39
|
+
toggleBus(bus: string | null): boolean | null;
|
|
40
|
+
isBusMuted(bus: string | null): boolean | null;
|
|
41
|
+
get buses(): {
|
|
42
|
+
name: string;
|
|
43
|
+
muted: boolean;
|
|
44
|
+
}[];
|
|
45
|
+
pause(): void;
|
|
46
|
+
}
|
|
47
|
+
export declare function definePlayerElement(tag?: string): void;
|