@kubohiroya/turbowarp-aframe 0.2.0 → 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/README.ja.md +31 -3
- package/README.md +77 -4
- package/THIRD_PARTY_NOTICES.md +17 -0
- package/dist/extension-manifest.json +60 -0
- package/dist/turbowarp-aframe.js +6442 -5
- package/docs/architecture.ja.md +11 -1
- package/docs/architecture.md +11 -1
- package/package.json +19 -13
- package/src/aframe-loader.ts +74 -0
- package/src/block-definitions.json +42 -1
- package/src/extension.ts +122 -3
- package/src/globals.d.ts +13 -0
- package/src/runtime-capability.ts +105 -0
- package/src/vrm.ts +143 -0
package/docs/architecture.ja.md
CHANGED
|
@@ -22,8 +22,18 @@ src/config.ts + src/block-definitions.json
|
|
|
22
22
|
|
|
23
23
|
生成される JavaScript は unsandboxed TurboWarp 拡張です。manifest は block API contract として互換性確認に使います。
|
|
24
24
|
|
|
25
|
+
## version付きruntime capability
|
|
26
|
+
|
|
27
|
+
機能拡張は`Scratch.vm.runtime.turbowarpAFrameCapability`を公開します。version 2は、`loadTemplate`、`createFromTemplate`、`setPosition`、`setRotation`、`emitEvent`、`deleteSelector`、`countSelector`に、`loadVrm`、`setVrmBoneRotation`、`vrmBoneNames`、`vrmStatus`を加えた、freezeされた狭い型付きportです。scene操作だけを持っていたversion 1は、version 2と並べて残さず0.4.0で撤去しました。正しく保つ契約を1つにするためです。
|
|
28
|
+
|
|
29
|
+
各port methodは対応するblock handlerへ委譲します。そのため、block呼び出しと複合機能拡張からの呼び出しは、cast、validation、selector matching、event queue、機能拡張所有のscene stateを共有します。portはDOM element、A-Frame/Three.js object、glTF内部実装を公開しません。
|
|
30
|
+
|
|
31
|
+
consumerは利用前に`requireVersion(2)`を呼ぶ必要があります。1を含むそれ以外のversionは、互換fallbackを試さず例外になります。`dispose()`はruntimeからcapabilityを削除し、実行中のanimation playbackを停止し、scene hostを除去して、dispose前にconsumerが保持した参照も恒久的に無効化します。disposeの反復呼び出しは安全です。
|
|
32
|
+
|
|
25
33
|
## シーン初期化
|
|
26
34
|
|
|
35
|
+
`createScene`はsceneを作る前に、ページにA-Frame 1.8.0があることを確かめます。なければ`https://cdn.jsdelivr.net/npm/aframe@1.8.0/dist/aframe-v1.8.0.min.js`のscriptを、SHA-384のsubresource integrityと`crossorigin="anonymous"`付きで追加して待ちます。CDN上のファイルが変わっていれば拒否され、blockはA-Frameの準備ができてから完了します。同時に作られたsceneは1回の読み込みを共有し、失敗またはtimeout(30秒)した読み込みはscriptを取り除いて、次の呼び出しで再試行できるようにします。ページにA-Frame 1.8.0がすでにあれば何も読み込まず、自前のコピーを配信するオフライン会場でも動きます。ほかのversionがあれば拒否します。2つ目のA-Frameは並べて動かせず、three-vrmは1.8.0のThree.jsでしか確かめていないためです。A-Frameはbundleしません。
|
|
36
|
+
|
|
27
37
|
`createScene` は root の `#scene` ノードを作り、ブラウザ DOM がある場合は `#tw-aframe-root > a-scene` を作成します。host は最初に検出できた TurboWarp stage wrapper または canvas の親へ mount し、stage らしい要素が見つからない場合だけ `document.body` に fallback します。
|
|
28
38
|
|
|
29
39
|
初期 layer は文字列です。Book/API 側で語彙を調整しても block shape を変えずに済むようにしています。
|
|
@@ -103,7 +113,7 @@ track の `times` と `values` は comma または whitespace 区切りの numbe
|
|
|
103
113
|
|
|
104
114
|
single-keyframe helper block はブロック優先の authoring path です。`.position`、`.scale`、`.quaternion` の keyframe を 1 つずつ挿入し、time 順に並べ、同じ clip、path、time の keyframe は後から追加した値で置き換えます。comma-separated full-track block は、Three.js 形式の配列をすでに持っている advanced user 向けに残します。
|
|
105
115
|
|
|
106
|
-
再生は Scratch sprite ではなく一致した node に紐づきます。browser DOM、A-Frame、`AFRAME.THREE` が利用可能な場合、`play 3D animation clip` は対象 node の root `object3D` ごとに `AnimationMixer` を作成し、clip action を開始し、scene 上の小さな A-Frame bridge component から active mixer を更新します。glTF bone、child object path、material property、blending、cross-fade control は初期実装の外に置きます。DOM のない test environment では、Three.js object を作らず registry と validation を検証できます。
|
|
116
|
+
再生は Scratch sprite ではなく一致した node に紐づきます。browser DOM、A-Frame、`AFRAME.THREE` が利用可能な場合、`play 3D animation clip` は対象 node の root `object3D` ごとに `AnimationMixer` を作成し、clip action を開始し、scene 上の小さな A-Frame bridge component から active mixer を更新します。glTF bone、child object path、material property、blending、cross-fade control は初期実装の外に置きます。VRMのヒューマノイドのボーンは、animation clipではなくVRMのブロックで回します。DOM のない test environment では、Three.js object を作らず registry と validation を検証できます。
|
|
107
117
|
|
|
108
118
|
既存の `rotation` ブロックは A-Frame attribute を書くため degree-based のまま維持します。Quaternion animation は Three.js object state を使うため、A-Frame Euler attribute rotation とは別の機能として扱います。
|
|
109
119
|
|
package/docs/architecture.md
CHANGED
|
@@ -22,8 +22,18 @@ src/config.ts + src/block-definitions.json
|
|
|
22
22
|
|
|
23
23
|
The generated JavaScript bundle is an unsandboxed TurboWarp extension. The manifest records the block API contract for compatibility checks.
|
|
24
24
|
|
|
25
|
+
## Versioned Runtime Capability
|
|
26
|
+
|
|
27
|
+
The extension publishes `Scratch.vm.runtime.turbowarpAFrameCapability`. Version 2 is a narrow typed, frozen port containing `loadTemplate`, `createFromTemplate`, `setPosition`, `setRotation`, `emitEvent`, `deleteSelector`, and `countSelector`, plus `loadVrm`, `setVrmBoneRotation`, `vrmBoneNames`, and `vrmStatus`. Version 1, which had only the scene operations, was removed in 0.4.0 rather than kept beside version 2, so there is a single contract to keep correct.
|
|
28
|
+
|
|
29
|
+
Each port method delegates to the corresponding block handler. Consequently, block calls and composite-extension calls share casting, validation, selector matching, event queuing, and the extension-owned scene state. The port never exposes DOM elements, A-Frame/Three.js objects, or glTF internals.
|
|
30
|
+
|
|
31
|
+
Consumers must call `requireVersion(2)` before use. Any other version, including 1, throws instead of attempting compatibility fallback. `dispose()` removes the capability from the runtime, stops active animation playbacks, removes the scene host, and permanently invalidates references that a consumer retained before disposal. Repeated disposal is safe.
|
|
32
|
+
|
|
25
33
|
## Scene initialization
|
|
26
34
|
|
|
35
|
+
Before building the scene, `createScene` makes sure A-Frame 1.8.0 is on the page. It adds a script for `https://cdn.jsdelivr.net/npm/aframe@1.8.0/dist/aframe-v1.8.0.min.js` with a SHA-384 subresource integrity hash and `crossorigin="anonymous"`, so a changed file on the CDN is refused, and waits for it; the block resolves only after A-Frame is ready. Concurrent scenes share one load, and a failed or timed-out load (30 s) removes its script so the next call can try again. A page that already has A-Frame 1.8.0 loads nothing, which keeps an offline venue that serves its own copy working. Any other version on the page is refused, because a second A-Frame cannot run beside it and three-vrm is verified on the Three.js of 1.8.0 only. A-Frame is never bundled.
|
|
36
|
+
|
|
27
37
|
`createScene` creates a root `#scene` node and, when a browser DOM exists, a `#tw-aframe-root > a-scene` host. The host is mounted inside the first detected TurboWarp stage wrapper or canvas parent, falling back to `document.body` only when no stage-like element is found.
|
|
28
38
|
|
|
29
39
|
The initial layer values are strings so the book/API can refine the vocabulary without changing the block shape:
|
|
@@ -103,7 +113,7 @@ Track `times` and `values` are passed as comma- or whitespace-separated number l
|
|
|
103
113
|
|
|
104
114
|
Single-keyframe helper blocks provide the block-first authoring path. They insert one `.position`, `.scale`, or `.quaternion` keyframe at a time, keep keyframes sorted, and replace an existing keyframe when the clip, path, and time match. The comma-separated full-track blocks remain available for advanced users who already have Three.js-style arrays.
|
|
105
115
|
|
|
106
|
-
Playback is attached to matching nodes, not Scratch sprites. When browser DOM, A-Frame, and `AFRAME.THREE` are available, `play 3D animation clip` creates an `AnimationMixer` for each target node root `object3D`, starts a clip action, and updates active mixers through a small A-Frame bridge component on the scene. glTF bones, child object paths, material properties, blending, and cross-fade controls are left outside the first implementation. In non-DOM test environments, the registry and validation behavior remain testable without constructing Three.js objects.
|
|
116
|
+
Playback is attached to matching nodes, not Scratch sprites. When browser DOM, A-Frame, and `AFRAME.THREE` are available, `play 3D animation clip` creates an `AnimationMixer` for each target node root `object3D`, starts a clip action, and updates active mixers through a small A-Frame bridge component on the scene. glTF bones, child object paths, material properties, blending, and cross-fade controls are left outside the first implementation. VRM humanoid bones are turned by the VRM blocks rather than by animation clips. In non-DOM test environments, the registry and validation behavior remain testable without constructing Three.js objects.
|
|
107
117
|
|
|
108
118
|
The existing `rotation` block remains degree-based because it writes A-Frame attributes. Quaternion animation uses Three.js object state and should be documented as separate from A-Frame Euler attribute rotation.
|
|
109
119
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/turbowarp-aframe",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "A TurboWarp extension for declarative A-Frame scene graphs.",
|
|
5
5
|
"author": "Hiroya Kubo <hiroya@cuc.ac.jp>",
|
|
6
6
|
"license": "MPL-2.0",
|
|
@@ -31,30 +31,23 @@
|
|
|
31
31
|
"src/",
|
|
32
32
|
"README.md",
|
|
33
33
|
"README.ja.md",
|
|
34
|
-
"LICENSE"
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"THIRD_PARTY_NOTICES.md"
|
|
35
36
|
],
|
|
36
37
|
"publishConfig": {
|
|
37
38
|
"access": "public",
|
|
38
39
|
"registry": "https://registry.npmjs.org/"
|
|
39
40
|
},
|
|
41
|
+
"packageManager": "pnpm@11.11.0",
|
|
40
42
|
"engines": {
|
|
41
43
|
"node": ">=22.18.0"
|
|
42
44
|
},
|
|
43
|
-
"devDependencies": {
|
|
44
|
-
"@eslint/js": "^9.39.5",
|
|
45
|
-
"@kubohiroya/vite-plugin-turbowarp-extension": "0.4.0",
|
|
46
|
-
"@types/node": "^24.13.3",
|
|
47
|
-
"eslint": "^9.39.5",
|
|
48
|
-
"typescript": "^5.9.3",
|
|
49
|
-
"typescript-eslint": "^8.66.0",
|
|
50
|
-
"vite": "^8.2.2",
|
|
51
|
-
"vitest": "^4.1.10"
|
|
52
|
-
},
|
|
53
45
|
"scripts": {
|
|
54
46
|
"dev": "vite build --watch",
|
|
55
47
|
"typecheck": "tsc --noEmit",
|
|
56
48
|
"build": "vite build",
|
|
57
49
|
"lint": "eslint src tests vite.config.ts",
|
|
50
|
+
"format": "eslint src tests vite.config.ts --fix",
|
|
58
51
|
"test": "vitest run",
|
|
59
52
|
"docs": "node scripts/generate-readme.ts",
|
|
60
53
|
"docs:check": "pnpm run docs && git diff --exit-code -- README.md",
|
|
@@ -62,5 +55,18 @@
|
|
|
62
55
|
"pack:check": "npm pack --dry-run --ignore-scripts",
|
|
63
56
|
"check": "pnpm run typecheck && pnpm run lint && pnpm run test && pnpm run docs:check && pnpm run check:dist && pnpm run repo:check && pnpm run pack:check",
|
|
64
57
|
"check:dist": "pnpm run build && node scripts/check-dist.ts"
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@eslint/js": "^9.39.5",
|
|
61
|
+
"@kubohiroya/vite-plugin-turbowarp-extension": "0.4.0",
|
|
62
|
+
"@pixiv/three-vrm": "3.5.5",
|
|
63
|
+
"@types/node": "^24.13.3",
|
|
64
|
+
"@types/three": "0.184.0",
|
|
65
|
+
"eslint": "^9.39.5",
|
|
66
|
+
"super-three": "0.184.0",
|
|
67
|
+
"typescript": "^5.9.3",
|
|
68
|
+
"typescript-eslint": "^8.66.0",
|
|
69
|
+
"vite": "^8.2.2",
|
|
70
|
+
"vitest": "^4.1.10"
|
|
65
71
|
}
|
|
66
|
-
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** The A-Frame this extension is built and tested against, including three-vrm on its Three.js. */
|
|
2
|
+
export const aframeVersion = '1.8.0';
|
|
3
|
+
export const aframeUrl = `https://cdn.jsdelivr.net/npm/aframe@${aframeVersion}/dist/aframe-v${aframeVersion}.min.js`;
|
|
4
|
+
/** Subresource integrity of `aframeUrl`, so a changed file on the CDN is refused. */
|
|
5
|
+
export const aframeIntegrity =
|
|
6
|
+
'sha384-d2HJ2eWTxYenz2Vcmsy7gDZW7G2Gq51k1M15G7vv2O/S60nSNYZVjtgGzPnd3sG+';
|
|
7
|
+
const loadTimeoutMs = 30_000;
|
|
8
|
+
|
|
9
|
+
interface AFrameGlobal {
|
|
10
|
+
AFRAME?: {version?: string};
|
|
11
|
+
__twAframeLoading?: Promise<void>;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Makes sure A-Frame 1.8.0 is on the page, loading it from jsDelivr when it is not.
|
|
16
|
+
*
|
|
17
|
+
* A page that already has A-Frame 1.8.0, such as an offline venue that serves its own copy,
|
|
18
|
+
* loads nothing. Any other A-Frame version is refused, because a second copy cannot be
|
|
19
|
+
* loaded beside it and three-vrm is verified on 1.8.0 only. Without a document, as in tests
|
|
20
|
+
* and non-browser runtimes, the scene graph works without A-Frame and nothing is loaded.
|
|
21
|
+
*/
|
|
22
|
+
export async function ensureAFrame(): Promise<void> {
|
|
23
|
+
const state = globalThis as AFrameGlobal;
|
|
24
|
+
if (state.AFRAME !== undefined) {
|
|
25
|
+
requireVersion(state.AFRAME);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const head = typeof document === 'undefined' ? undefined : document.head;
|
|
29
|
+
if (head === undefined || head === null) return;
|
|
30
|
+
state.__twAframeLoading ??= load(head).catch((error: unknown) => {
|
|
31
|
+
delete state.__twAframeLoading;
|
|
32
|
+
throw error;
|
|
33
|
+
});
|
|
34
|
+
await state.__twAframeLoading;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function load(head: HTMLElement): Promise<void> {
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const script = document.createElement('script');
|
|
40
|
+
const fail = (reason: string) => {
|
|
41
|
+
clearTimeout(timer);
|
|
42
|
+
script.remove();
|
|
43
|
+
reject(new Error(`Could not load A-Frame ${aframeVersion} from ${aframeUrl}: ${reason}`));
|
|
44
|
+
};
|
|
45
|
+
const timer = setTimeout(() => fail(`no response in ${loadTimeoutMs / 1000} s`), loadTimeoutMs);
|
|
46
|
+
script.src = aframeUrl;
|
|
47
|
+
script.integrity = aframeIntegrity;
|
|
48
|
+
script.crossOrigin = 'anonymous';
|
|
49
|
+
script.onload = () => {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
const loaded = (globalThis as AFrameGlobal).AFRAME;
|
|
52
|
+
if (loaded === undefined) {
|
|
53
|
+
reject(new Error(`A-Frame ${aframeVersion} loaded but did not define AFRAME.`));
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
requireVersion(loaded);
|
|
58
|
+
resolve();
|
|
59
|
+
} catch (error) {
|
|
60
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
script.onerror = () => fail('the request failed or the file did not match its integrity hash');
|
|
64
|
+
head.append(script);
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function requireVersion(aframe: {version?: string}): void {
|
|
69
|
+
if (aframe.version !== aframeVersion) {
|
|
70
|
+
throw new Error(
|
|
71
|
+
`A-Frame ${aframe.version ?? '(unknown version)'} is already on the page; TurboWarp-A-Frame needs ${aframeVersion}.`
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"opcode": "createScene",
|
|
6
6
|
"blockType": "COMMAND",
|
|
7
7
|
"text": "create 3D scene with layer [LAYER] mode [MODE]",
|
|
8
|
-
"description": "
|
|
8
|
+
"description": "Loads A-Frame 1.8.0 from jsDelivr when the page does not have it, initializes the A-Frame scene host, and emits the scene ready event.",
|
|
9
9
|
"arguments": {
|
|
10
10
|
"LAYER": {"type": "STRING", "defaultValue": "above-stage"},
|
|
11
11
|
"MODE": {"type": "STRING", "defaultValue": "3d"}
|
|
@@ -324,6 +324,47 @@
|
|
|
324
324
|
"CLIP": {"type": "STRING", "defaultValue": "wave"},
|
|
325
325
|
"SELECTOR": {"type": "STRING", "defaultValue": "#leftArm"}
|
|
326
326
|
}
|
|
327
|
+
},
|
|
328
|
+
{
|
|
329
|
+
"opcode": "loadVrm",
|
|
330
|
+
"blockType": "COMMAND",
|
|
331
|
+
"text": "load VRM [URL] onto [SELECTOR]",
|
|
332
|
+
"description": "Loads a VRM avatar with three-vrm on the A-Frame Three.js and attaches it to the first matching node. The block waits until the model is ready.",
|
|
333
|
+
"arguments": {
|
|
334
|
+
"URL": {"type": "STRING", "defaultValue": "avatar.vrm"},
|
|
335
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
|
|
336
|
+
}
|
|
337
|
+
},
|
|
338
|
+
{
|
|
339
|
+
"opcode": "setVrmBoneRotation",
|
|
340
|
+
"blockType": "COMMAND",
|
|
341
|
+
"text": "set VRM [SELECTOR] bone [BONE] rotation x [X] y [Y] z [Z]",
|
|
342
|
+
"description": "Sets the Euler rotation in degrees of a normalized VRM humanoid bone, relative to the T-pose, on every matching node whose VRM is ready.",
|
|
343
|
+
"arguments": {
|
|
344
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"},
|
|
345
|
+
"BONE": {"type": "STRING", "defaultValue": "leftUpperArm"},
|
|
346
|
+
"X": {"type": "NUMBER", "defaultValue": 0},
|
|
347
|
+
"Y": {"type": "NUMBER", "defaultValue": 0},
|
|
348
|
+
"Z": {"type": "NUMBER", "defaultValue": -60}
|
|
349
|
+
}
|
|
350
|
+
},
|
|
351
|
+
{
|
|
352
|
+
"opcode": "vrmBoneNames",
|
|
353
|
+
"blockType": "REPORTER",
|
|
354
|
+
"text": "VRM [SELECTOR] humanoid bones",
|
|
355
|
+
"description": "Returns the humanoid bone names of the first matching node's VRM as a JSON array.",
|
|
356
|
+
"arguments": {
|
|
357
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
{
|
|
361
|
+
"opcode": "vrmState",
|
|
362
|
+
"blockType": "REPORTER",
|
|
363
|
+
"text": "VRM [SELECTOR] state",
|
|
364
|
+
"description": "Returns none, loading, ready, or error with its reason for the first matching node.",
|
|
365
|
+
"arguments": {
|
|
366
|
+
"SELECTOR": {"type": "STRING", "defaultValue": "#avatar"}
|
|
367
|
+
}
|
|
327
368
|
}
|
|
328
369
|
]
|
|
329
370
|
}
|
package/src/extension.ts
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import {extensionConfig} from './config';
|
|
2
2
|
import definitions from './block-definitions.json';
|
|
3
|
+
import {
|
|
4
|
+
createRuntimeCapability,
|
|
5
|
+
runtimeCapabilityKey,
|
|
6
|
+
type AFrameRuntimeCapabilityV2,
|
|
7
|
+
type AFrameVrmStatus
|
|
8
|
+
} from './runtime-capability.js';
|
|
9
|
+
import {ensureAFrame} from './aframe-loader.js';
|
|
10
|
+
import {VrmAvatars, type VrmThreeApi} from './vrm.js';
|
|
3
11
|
|
|
4
12
|
type BlockTypeName = 'COMMAND' | 'REPORTER' | 'HAT' | 'BOOLEAN';
|
|
5
13
|
type ArgumentTypeName = 'STRING' | 'NUMBER' | 'BOOLEAN';
|
|
@@ -105,6 +113,11 @@ type AFrameApi = {
|
|
|
105
113
|
registerComponent(name: string, definition: unknown): void;
|
|
106
114
|
};
|
|
107
115
|
|
|
116
|
+
interface VrmHostElement {
|
|
117
|
+
object3D?: {add(object: object): void};
|
|
118
|
+
setObject3D?(name: string, object: object): void;
|
|
119
|
+
}
|
|
120
|
+
|
|
108
121
|
const blockDefinitions = definitions.blocks as readonly BlockDefinition[];
|
|
109
122
|
const ROOT_ID = 'scene';
|
|
110
123
|
const DOM_EVENT_TYPES = ['click', 'tap', 'pointerenter', 'pointerleave'] as const;
|
|
@@ -130,9 +143,35 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
130
143
|
private rootElement: Element | null = null;
|
|
131
144
|
private sceneReadyPending = false;
|
|
132
145
|
private lastEvent: SceneEvent | null = null;
|
|
146
|
+
private readonly runtimeCapability: AFrameRuntimeCapabilityV2;
|
|
147
|
+
private disposed = false;
|
|
148
|
+
private readonly vrms = new VrmAvatars(() => this.getThree() as unknown as VrmThreeApi | null);
|
|
133
149
|
|
|
134
150
|
public constructor() {
|
|
135
151
|
this.resetGraph();
|
|
152
|
+
this.runtimeCapability = createRuntimeCapability(
|
|
153
|
+
{
|
|
154
|
+
loadTemplate: (id, source) => this.loadTemplate({ID: id, SOURCE: source}),
|
|
155
|
+
createFromTemplate: (template, instance, parent) =>
|
|
156
|
+
this.createFromTemplate({TEMPLATE: template, INSTANCE: instance, PARENT: parent}),
|
|
157
|
+
setPosition: (selector, x, y, z) =>
|
|
158
|
+
this.setPosition({SELECTOR: selector, X: x, Y: y, Z: z}),
|
|
159
|
+
setRotation: (selector, x, y, z) =>
|
|
160
|
+
this.setRotation({SELECTOR: selector, X: x, Y: y, Z: z}),
|
|
161
|
+
emitEvent: (type, selector, data) =>
|
|
162
|
+
this.emitEvent({TYPE: type, SELECTOR: selector, DATA: data}),
|
|
163
|
+
deleteSelector: (selector) => this.deleteSelector({SELECTOR: selector}),
|
|
164
|
+
countSelector: (selector) => this.countSelector({SELECTOR: selector}),
|
|
165
|
+
loadVrm: (url, selector) => this.loadVrm({URL: url, SELECTOR: selector}),
|
|
166
|
+
setVrmBoneRotation: (selector, bone, x, y, z) =>
|
|
167
|
+
this.setVrmBoneRotation({SELECTOR: selector, BONE: bone, X: x, Y: y, Z: z}),
|
|
168
|
+
vrmBoneNames: (selector) => this.vrmBoneNamesFor(Scratch.Cast.toString(selector)),
|
|
169
|
+
vrmStatus: (selector) => this.vrmStatusFor(Scratch.Cast.toString(selector))
|
|
170
|
+
},
|
|
171
|
+
() => this.assertActive()
|
|
172
|
+
);
|
|
173
|
+
const runtime = Scratch.vm?.runtime;
|
|
174
|
+
if (runtime) runtime[runtimeCapabilityKey] = this.runtimeCapability;
|
|
136
175
|
}
|
|
137
176
|
|
|
138
177
|
public getInfo(): Record<string, unknown> {
|
|
@@ -145,7 +184,8 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
145
184
|
};
|
|
146
185
|
}
|
|
147
186
|
|
|
148
|
-
public createScene(args: {LAYER: unknown; MODE: unknown}): void {
|
|
187
|
+
public async createScene(args: {LAYER: unknown; MODE: unknown}): Promise<void> {
|
|
188
|
+
await ensureAFrame();
|
|
149
189
|
this.sceneOptions = {
|
|
150
190
|
layer: Scratch.Cast.toString(args.LAYER) || 'above-stage',
|
|
151
191
|
mode: Scratch.Cast.toString(args.MODE) || '3d'
|
|
@@ -475,8 +515,48 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
475
515
|
});
|
|
476
516
|
}
|
|
477
517
|
|
|
518
|
+
public async loadVrm(args: {URL: unknown; SELECTOR: unknown}): Promise<void> {
|
|
519
|
+
const selector = Scratch.Cast.toString(args.SELECTOR);
|
|
520
|
+
const node = this.firstMatch(selector);
|
|
521
|
+
if (node === undefined) throw new Error(`No A-Frame node matches: ${selector}`);
|
|
522
|
+
const element = node.element as (Element & VrmHostElement) | null;
|
|
523
|
+
if (element === null) throw new Error('VRM avatars need a scene in the browser.');
|
|
524
|
+
this.ensureAnimationTickBridge();
|
|
525
|
+
await this.vrms.load(node.id, Scratch.Cast.toString(args.URL), (scene) => {
|
|
526
|
+
if (element.setObject3D !== undefined) {
|
|
527
|
+
element.setObject3D('vrm', scene);
|
|
528
|
+
} else {
|
|
529
|
+
element.object3D?.add(scene);
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
public setVrmBoneRotation(args: {
|
|
535
|
+
SELECTOR: unknown;
|
|
536
|
+
BONE: unknown;
|
|
537
|
+
X: unknown;
|
|
538
|
+
Y: unknown;
|
|
539
|
+
Z: unknown;
|
|
540
|
+
}): void {
|
|
541
|
+
const bone = Scratch.Cast.toString(args.BONE).trim();
|
|
542
|
+
const rotation = this.argsToVec3(args);
|
|
543
|
+
for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
|
|
544
|
+
if (this.vrms.state(node.id) !== 'ready') continue;
|
|
545
|
+
this.vrms.setBoneRotation(node.id, bone, rotation);
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
public vrmBoneNames(args: {SELECTOR: unknown}): string {
|
|
550
|
+
return JSON.stringify(this.vrmBoneNamesFor(Scratch.Cast.toString(args.SELECTOR)));
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
public vrmState(args: {SELECTOR: unknown}): string {
|
|
554
|
+
const {state, error} = this.vrmStatusFor(Scratch.Cast.toString(args.SELECTOR));
|
|
555
|
+
return state === 'error' ? `error: ${error}` : state;
|
|
556
|
+
}
|
|
557
|
+
|
|
478
558
|
public testStepAnimations(args: {DELTA: unknown}): void {
|
|
479
|
-
this.
|
|
559
|
+
this.updateFrame(Scratch.Cast.toNumber(args.DELTA) / 1000);
|
|
480
560
|
}
|
|
481
561
|
|
|
482
562
|
public snapshot(): Record<string, unknown> {
|
|
@@ -514,10 +594,32 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
514
594
|
};
|
|
515
595
|
}
|
|
516
596
|
|
|
597
|
+
public dispose(): void {
|
|
598
|
+
if (this.disposed) return;
|
|
599
|
+
this.disposed = true;
|
|
600
|
+
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
601
|
+
this.stopPlayback(key, true);
|
|
602
|
+
}
|
|
603
|
+
this.vrms.clear();
|
|
604
|
+
this.rootElement?.parentElement?.remove();
|
|
605
|
+
this.rootElement = null;
|
|
606
|
+
const runtime = Scratch.vm?.runtime;
|
|
607
|
+
if (runtime?.[runtimeCapabilityKey] === this.runtimeCapability) {
|
|
608
|
+
delete runtime[runtimeCapabilityKey];
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
private assertActive(): void {
|
|
613
|
+
if (this.disposed) {
|
|
614
|
+
throw new Error('A-Frame runtime capability is disposed.');
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
517
618
|
private resetGraph(): void {
|
|
518
619
|
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
519
620
|
this.stopPlayback(key, true);
|
|
520
621
|
}
|
|
622
|
+
this.vrms.clear();
|
|
521
623
|
this.nodes.clear();
|
|
522
624
|
this.nodes.set(ROOT_ID, {
|
|
523
625
|
id: ROOT_ID,
|
|
@@ -582,6 +684,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
582
684
|
}
|
|
583
685
|
node.element?.remove();
|
|
584
686
|
this.nodes.delete(id);
|
|
687
|
+
this.vrms.remove(id);
|
|
585
688
|
for (const key of [...this.animationPlaybacks.keys()]) {
|
|
586
689
|
if (key.startsWith(`${id}:`)) {
|
|
587
690
|
this.stopPlayback(key, true);
|
|
@@ -989,6 +1092,22 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
989
1092
|
}
|
|
990
1093
|
}
|
|
991
1094
|
|
|
1095
|
+
private vrmBoneNamesFor(selector: string): string[] {
|
|
1096
|
+
const node = this.firstMatch(selector);
|
|
1097
|
+
return node === undefined ? [] : this.vrms.boneNames(node.id);
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
private vrmStatusFor(selector: string): AFrameVrmStatus {
|
|
1101
|
+
const node = this.firstMatch(selector);
|
|
1102
|
+
if (node === undefined) return {state: 'none', error: ''};
|
|
1103
|
+
return {state: this.vrms.state(node.id), error: this.vrms.error(node.id)};
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
private updateFrame(deltaTime: number): void {
|
|
1107
|
+
this.updateAnimationMixers(deltaTime);
|
|
1108
|
+
if (Number.isFinite(deltaTime) && deltaTime >= 0) this.vrms.update(deltaTime);
|
|
1109
|
+
}
|
|
1110
|
+
|
|
992
1111
|
private updateAnimationMixers(deltaTime: number): void {
|
|
993
1112
|
if (!Number.isFinite(deltaTime) || deltaTime < 0) return;
|
|
994
1113
|
for (const playback of this.animationPlaybacks.values()) {
|
|
@@ -1009,7 +1128,7 @@ export class TurboWarpAFrameExtension implements TurboWarpExtension {
|
|
|
1009
1128
|
schema: {id: {type: 'string'}},
|
|
1010
1129
|
tick(this: {data: {id: string}}, _time: number, timeDelta: number) {
|
|
1011
1130
|
const extension = animationRuntimeRegistry().get(this.data.id);
|
|
1012
|
-
extension?.
|
|
1131
|
+
extension?.updateFrame(timeDelta / 1000);
|
|
1013
1132
|
}
|
|
1014
1133
|
});
|
|
1015
1134
|
}
|
package/src/globals.d.ts
CHANGED
|
@@ -20,6 +20,19 @@ interface ScratchApi {
|
|
|
20
20
|
toBoolean(value: unknown): boolean;
|
|
21
21
|
};
|
|
22
22
|
translate: ScratchTranslate;
|
|
23
|
+
vm?: {
|
|
24
|
+
runtime?: Record<string, unknown>;
|
|
25
|
+
};
|
|
23
26
|
}
|
|
24
27
|
|
|
25
28
|
declare const Scratch: ScratchApi;
|
|
29
|
+
|
|
30
|
+
declare module 'virtual:three-vrm-factory' {
|
|
31
|
+
export function createThreeVrm(THREE: unknown): {
|
|
32
|
+
VRMLoaderPlugin: new (parser: never) => unknown;
|
|
33
|
+
VRMUtils: {
|
|
34
|
+
deepDispose(object: never): void;
|
|
35
|
+
rotateVRM0(vrm: never): void;
|
|
36
|
+
};
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** The only capability version this build provides; any other requested version is refused. */
|
|
2
|
+
export const runtimeCapabilityVersion = 2 as const;
|
|
3
|
+
export const runtimeCapabilityKey = 'turbowarpAFrameCapability';
|
|
4
|
+
|
|
5
|
+
export interface AFrameScenePort {
|
|
6
|
+
loadTemplate(id: string, source: string): void;
|
|
7
|
+
createFromTemplate(template: string, instance: string, parent: string): void;
|
|
8
|
+
setPosition(selector: string, x: number, y: number, z: number): void;
|
|
9
|
+
setRotation(selector: string, x: number, y: number, z: number): void;
|
|
10
|
+
emitEvent(type: string, selector: string, data: string): void;
|
|
11
|
+
deleteSelector(selector: string): void;
|
|
12
|
+
countSelector(selector: string): number;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export type AFrameVrmState = 'none' | 'loading' | 'ready' | 'error';
|
|
16
|
+
|
|
17
|
+
export interface AFrameVrmStatus {
|
|
18
|
+
state: AFrameVrmState;
|
|
19
|
+
error: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface AFrameVrmPort {
|
|
23
|
+
/** Loads a VRM onto the first node matching the selector; resolves when it is ready. */
|
|
24
|
+
loadVrm(url: string, selector: string): Promise<void>;
|
|
25
|
+
/** Euler degrees on a normalized humanoid bone, relative to the T-pose. */
|
|
26
|
+
setVrmBoneRotation(selector: string, bone: string, x: number, y: number, z: number): void;
|
|
27
|
+
vrmBoneNames(selector: string): string[];
|
|
28
|
+
vrmStatus(selector: string): AFrameVrmStatus;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface AFrameRuntimeCapabilityV2 extends AFrameScenePort, AFrameVrmPort {
|
|
32
|
+
readonly version: typeof runtimeCapabilityVersion;
|
|
33
|
+
requireVersion(version: number): AFrameRuntimeCapabilityV2;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createRuntimeCapability(
|
|
37
|
+
scene: AFrameScenePort & AFrameVrmPort,
|
|
38
|
+
assertActive: () => void
|
|
39
|
+
): AFrameRuntimeCapabilityV2 {
|
|
40
|
+
const scenePort: AFrameScenePort = {
|
|
41
|
+
loadTemplate(id, source) {
|
|
42
|
+
assertActive();
|
|
43
|
+
scene.loadTemplate(id, source);
|
|
44
|
+
},
|
|
45
|
+
createFromTemplate(template, instance, parent) {
|
|
46
|
+
assertActive();
|
|
47
|
+
scene.createFromTemplate(template, instance, parent);
|
|
48
|
+
},
|
|
49
|
+
setPosition(selector, x, y, z) {
|
|
50
|
+
assertActive();
|
|
51
|
+
scene.setPosition(selector, x, y, z);
|
|
52
|
+
},
|
|
53
|
+
setRotation(selector, x, y, z) {
|
|
54
|
+
assertActive();
|
|
55
|
+
scene.setRotation(selector, x, y, z);
|
|
56
|
+
},
|
|
57
|
+
emitEvent(type, selector, data) {
|
|
58
|
+
assertActive();
|
|
59
|
+
scene.emitEvent(type, selector, data);
|
|
60
|
+
},
|
|
61
|
+
deleteSelector(selector) {
|
|
62
|
+
assertActive();
|
|
63
|
+
scene.deleteSelector(selector);
|
|
64
|
+
},
|
|
65
|
+
countSelector(selector) {
|
|
66
|
+
assertActive();
|
|
67
|
+
return scene.countSelector(selector);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
const vrmPort: AFrameVrmPort = {
|
|
72
|
+
async loadVrm(url, selector) {
|
|
73
|
+
assertActive();
|
|
74
|
+
await scene.loadVrm(url, selector);
|
|
75
|
+
},
|
|
76
|
+
setVrmBoneRotation(selector, bone, x, y, z) {
|
|
77
|
+
assertActive();
|
|
78
|
+
scene.setVrmBoneRotation(selector, bone, x, y, z);
|
|
79
|
+
},
|
|
80
|
+
vrmBoneNames(selector) {
|
|
81
|
+
assertActive();
|
|
82
|
+
return scene.vrmBoneNames(selector);
|
|
83
|
+
},
|
|
84
|
+
vrmStatus(selector) {
|
|
85
|
+
assertActive();
|
|
86
|
+
return scene.vrmStatus(selector);
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const capability: AFrameRuntimeCapabilityV2 = Object.freeze({
|
|
91
|
+
version: runtimeCapabilityVersion,
|
|
92
|
+
requireVersion(version: number) {
|
|
93
|
+
assertActive();
|
|
94
|
+
if (version !== runtimeCapabilityVersion) {
|
|
95
|
+
throw new Error(
|
|
96
|
+
`Unsupported A-Frame runtime capability version: ${version}; supported version is ${runtimeCapabilityVersion}.`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
return capability;
|
|
100
|
+
},
|
|
101
|
+
...scenePort,
|
|
102
|
+
...vrmPort
|
|
103
|
+
});
|
|
104
|
+
return capability;
|
|
105
|
+
}
|