@kubohiroya/turbowarp-aframe 0.2.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,1422 @@
1
+ // Name: TurboWarp-A-Frame
2
+ // ID: turbowarpaframe
3
+ // Description: A TurboWarp extension for declarative A-Frame scene graphs.
4
+ // By: Hiroya Kubo
5
+ // License: MPL-2.0
6
+
7
+ (function (Scratch) {
8
+ 'use strict';
9
+
10
+ //#region src/config.ts
11
+ var extensionConfig = {
12
+ id: "turbowarpaframe",
13
+ slug: "turbowarp-aframe",
14
+ name: "TurboWarp-A-Frame",
15
+ description: "A TurboWarp extension for declarative A-Frame scene graphs.",
16
+ author: "Hiroya Kubo",
17
+ license: "MPL-2.0",
18
+ unsandboxed: true,
19
+ docsURI: "https://kubohiroya.github.io/turbowarp-aframe/",
20
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNiIgeT0iOCIgd2lkdGg9IjM2IiBoZWlnaHQ9IjMyIiByeD0iNCIgZmlsbD0iIzEyMTgyNiIvPjxwYXRoIGQ9Ik0xNCAzMmw5LTE4IDkgMThoLTRsLTItNWgtNmwtMiA1aC00Wm03LjQtOGgzLjJsLTEuNi00LjEtMS42IDQuMVoiIGZpbGw9IiM0Q0ZGQjAiLz48Y2lyY2xlIGN4PSIzNiIgY3k9IjE0IiByPSI0IiBmaWxsPSIjRkZBQjE5Ii8+PC9zdmc+"
21
+ };
22
+ var block_definitions_default = {
23
+ extensionName: "TurboWarp-A-Frame",
24
+ blocks: [
25
+ {
26
+ "opcode": "createScene",
27
+ "blockType": "COMMAND",
28
+ "text": "create 3D scene with layer [LAYER] mode [MODE]",
29
+ "description": "Initializes the A-Frame scene host and emits the scene ready event.",
30
+ "arguments": {
31
+ "LAYER": {
32
+ "type": "STRING",
33
+ "defaultValue": "above-stage"
34
+ },
35
+ "MODE": {
36
+ "type": "STRING",
37
+ "defaultValue": "3d"
38
+ }
39
+ }
40
+ },
41
+ {
42
+ "opcode": "loadTemplate",
43
+ "blockType": "COMMAND",
44
+ "text": "load template [ID] from JSON [SOURCE]",
45
+ "description": "Stores a declarative scene graph template for later instantiation.",
46
+ "arguments": {
47
+ "ID": {
48
+ "type": "STRING",
49
+ "defaultValue": "monster"
50
+ },
51
+ "SOURCE": {
52
+ "type": "STRING",
53
+ "defaultValue": "{\"type\":\"box\",\"id\":\"body\",\"attributes\":{\"color\":\"#4cffb0\"}}"
54
+ }
55
+ }
56
+ },
57
+ {
58
+ "opcode": "createNode",
59
+ "blockType": "COMMAND",
60
+ "text": "create [TYPE] node id [ID] under [PARENT]",
61
+ "description": "Creates a primitive, model, text, light, camera, or group node.",
62
+ "arguments": {
63
+ "TYPE": {
64
+ "type": "STRING",
65
+ "defaultValue": "box"
66
+ },
67
+ "ID": {
68
+ "type": "STRING",
69
+ "defaultValue": "card"
70
+ },
71
+ "PARENT": {
72
+ "type": "STRING",
73
+ "defaultValue": "#scene"
74
+ }
75
+ }
76
+ },
77
+ {
78
+ "opcode": "createFromTemplate",
79
+ "blockType": "COMMAND",
80
+ "text": "create template [TEMPLATE] as [INSTANCE] under [PARENT]",
81
+ "description": "Instantiates a stored template under the first node matching the parent selector.",
82
+ "arguments": {
83
+ "TEMPLATE": {
84
+ "type": "STRING",
85
+ "defaultValue": "monster"
86
+ },
87
+ "INSTANCE": {
88
+ "type": "STRING",
89
+ "defaultValue": "monster-1"
90
+ },
91
+ "PARENT": {
92
+ "type": "STRING",
93
+ "defaultValue": "#scene"
94
+ }
95
+ }
96
+ },
97
+ {
98
+ "opcode": "setPosition",
99
+ "blockType": "COMMAND",
100
+ "text": "set selector [SELECTOR] position x [X] y [Y] z [Z]",
101
+ "description": "Sets local position on every node matching the selector.",
102
+ "arguments": {
103
+ "SELECTOR": {
104
+ "type": "STRING",
105
+ "defaultValue": "#card"
106
+ },
107
+ "X": {
108
+ "type": "NUMBER",
109
+ "defaultValue": 0
110
+ },
111
+ "Y": {
112
+ "type": "NUMBER",
113
+ "defaultValue": 1
114
+ },
115
+ "Z": {
116
+ "type": "NUMBER",
117
+ "defaultValue": -3
118
+ }
119
+ }
120
+ },
121
+ {
122
+ "opcode": "moveBy",
123
+ "blockType": "COMMAND",
124
+ "text": "move selector [SELECTOR] by x [X] y [Y] z [Z]",
125
+ "description": "Offsets local position on every node matching the selector.",
126
+ "arguments": {
127
+ "SELECTOR": {
128
+ "type": "STRING",
129
+ "defaultValue": "#card"
130
+ },
131
+ "X": {
132
+ "type": "NUMBER",
133
+ "defaultValue": 0
134
+ },
135
+ "Y": {
136
+ "type": "NUMBER",
137
+ "defaultValue": 0
138
+ },
139
+ "Z": {
140
+ "type": "NUMBER",
141
+ "defaultValue": 1
142
+ }
143
+ }
144
+ },
145
+ {
146
+ "opcode": "setRotation",
147
+ "blockType": "COMMAND",
148
+ "text": "set selector [SELECTOR] rotation x [X] y [Y] z [Z]",
149
+ "description": "Sets local Euler rotation in degrees on every node matching the selector.",
150
+ "arguments": {
151
+ "SELECTOR": {
152
+ "type": "STRING",
153
+ "defaultValue": "#card"
154
+ },
155
+ "X": {
156
+ "type": "NUMBER",
157
+ "defaultValue": 0
158
+ },
159
+ "Y": {
160
+ "type": "NUMBER",
161
+ "defaultValue": 45
162
+ },
163
+ "Z": {
164
+ "type": "NUMBER",
165
+ "defaultValue": 0
166
+ }
167
+ }
168
+ },
169
+ {
170
+ "opcode": "addClass",
171
+ "blockType": "COMMAND",
172
+ "text": "add class [CLASS] to selector [SELECTOR]",
173
+ "description": "Adds a CSS-style class to every node matching the selector.",
174
+ "arguments": {
175
+ "CLASS": {
176
+ "type": "STRING",
177
+ "defaultValue": "monster"
178
+ },
179
+ "SELECTOR": {
180
+ "type": "STRING",
181
+ "defaultValue": "#card"
182
+ }
183
+ }
184
+ },
185
+ {
186
+ "opcode": "setData",
187
+ "blockType": "COMMAND",
188
+ "text": "set selector [SELECTOR] data [KEY] to [VALUE]",
189
+ "description": "Sets a data-* value on every node matching the selector.",
190
+ "arguments": {
191
+ "SELECTOR": {
192
+ "type": "STRING",
193
+ "defaultValue": "#card"
194
+ },
195
+ "KEY": {
196
+ "type": "STRING",
197
+ "defaultValue": "zone"
198
+ },
199
+ "VALUE": {
200
+ "type": "STRING",
201
+ "defaultValue": "field"
202
+ }
203
+ }
204
+ },
205
+ {
206
+ "opcode": "setAttribute",
207
+ "blockType": "COMMAND",
208
+ "text": "set selector [SELECTOR] attribute [NAME] to [VALUE]",
209
+ "description": "Sets an A-Frame component or HTML attribute on every node matching the selector.",
210
+ "arguments": {
211
+ "SELECTOR": {
212
+ "type": "STRING",
213
+ "defaultValue": "#card"
214
+ },
215
+ "NAME": {
216
+ "type": "STRING",
217
+ "defaultValue": "visible"
218
+ },
219
+ "VALUE": {
220
+ "type": "STRING",
221
+ "defaultValue": "true"
222
+ }
223
+ }
224
+ },
225
+ {
226
+ "opcode": "deleteSelector",
227
+ "blockType": "COMMAND",
228
+ "text": "delete selector [SELECTOR]",
229
+ "description": "Deletes every non-root node matching the selector and its descendants.",
230
+ "arguments": { "SELECTOR": {
231
+ "type": "STRING",
232
+ "defaultValue": "#card"
233
+ } }
234
+ },
235
+ {
236
+ "opcode": "countSelector",
237
+ "blockType": "REPORTER",
238
+ "text": "count selector [SELECTOR]",
239
+ "description": "Returns the number of nodes matching a limited selector.",
240
+ "arguments": { "SELECTOR": {
241
+ "type": "STRING",
242
+ "defaultValue": ".monster"
243
+ } }
244
+ },
245
+ {
246
+ "opcode": "eventTargetId",
247
+ "blockType": "REPORTER",
248
+ "text": "event target id",
249
+ "description": "Returns the id of the most recently handled 3D event target.",
250
+ "arguments": {}
251
+ },
252
+ {
253
+ "opcode": "emitEvent",
254
+ "blockType": "COMMAND",
255
+ "text": "emit 3D event [TYPE] from selector [SELECTOR] with data [DATA]",
256
+ "description": "Queues and dispatches a 3D event from the first node matching the selector.",
257
+ "arguments": {
258
+ "TYPE": {
259
+ "type": "STRING",
260
+ "defaultValue": "attack"
261
+ },
262
+ "SELECTOR": {
263
+ "type": "STRING",
264
+ "defaultValue": "#card"
265
+ },
266
+ "DATA": {
267
+ "type": "STRING",
268
+ "defaultValue": "{}"
269
+ }
270
+ }
271
+ },
272
+ {
273
+ "opcode": "whenSceneReady",
274
+ "blockType": "HAT",
275
+ "text": "when 3D scene ready",
276
+ "description": "Fires once after create 3D scene initializes the scene host.",
277
+ "arguments": {}
278
+ },
279
+ {
280
+ "opcode": "whenEventOnSelector",
281
+ "blockType": "HAT",
282
+ "text": "when event [TYPE] on selector [SELECTOR]",
283
+ "description": "Fires when a queued 3D event of the given type targets a node matching the selector.",
284
+ "arguments": {
285
+ "TYPE": {
286
+ "type": "STRING",
287
+ "defaultValue": "attack"
288
+ },
289
+ "SELECTOR": {
290
+ "type": "STRING",
291
+ "defaultValue": ".monster"
292
+ }
293
+ }
294
+ },
295
+ {
296
+ "opcode": "createAnimationClip",
297
+ "blockType": "COMMAND",
298
+ "text": "create 3D animation clip [NAME] duration [DURATION]",
299
+ "description": "Creates or replaces a Three.js AnimationClip definition.",
300
+ "arguments": {
301
+ "NAME": {
302
+ "type": "STRING",
303
+ "defaultValue": "wave"
304
+ },
305
+ "DURATION": {
306
+ "type": "NUMBER",
307
+ "defaultValue": -1
308
+ }
309
+ }
310
+ },
311
+ {
312
+ "opcode": "deleteAnimationClip",
313
+ "blockType": "COMMAND",
314
+ "text": "delete 3D animation clip [NAME]",
315
+ "description": "Deletes a stored 3D animation clip definition and stops its active actions.",
316
+ "arguments": { "NAME": {
317
+ "type": "STRING",
318
+ "defaultValue": "wave"
319
+ } }
320
+ },
321
+ {
322
+ "opcode": "addVectorKeyframeTrack",
323
+ "blockType": "COMMAND",
324
+ "text": "add vector keyframe track to clip [CLIP] path [PATH] times [TIMES] values [VALUES]",
325
+ "description": "Adds a Three.js VectorKeyframeTrack definition with x y z values.",
326
+ "arguments": {
327
+ "CLIP": {
328
+ "type": "STRING",
329
+ "defaultValue": "move-up"
330
+ },
331
+ "PATH": {
332
+ "type": "STRING",
333
+ "defaultValue": ".position"
334
+ },
335
+ "TIMES": {
336
+ "type": "STRING",
337
+ "defaultValue": "0,0.5,1"
338
+ },
339
+ "VALUES": {
340
+ "type": "STRING",
341
+ "defaultValue": "0,1,-3, 0,1.5,-3, 0,1,-3"
342
+ }
343
+ }
344
+ },
345
+ {
346
+ "opcode": "addQuaternionKeyframeTrack",
347
+ "blockType": "COMMAND",
348
+ "text": "add quaternion keyframe track to clip [CLIP] path [PATH] times [TIMES] values [VALUES]",
349
+ "description": "Adds a Three.js QuaternionKeyframeTrack definition with x y z w values.",
350
+ "arguments": {
351
+ "CLIP": {
352
+ "type": "STRING",
353
+ "defaultValue": "wave"
354
+ },
355
+ "PATH": {
356
+ "type": "STRING",
357
+ "defaultValue": ".quaternion"
358
+ },
359
+ "TIMES": {
360
+ "type": "STRING",
361
+ "defaultValue": "0,0.5,1"
362
+ },
363
+ "VALUES": {
364
+ "type": "STRING",
365
+ "defaultValue": "0,0,0,1, 0,0,0.389,0.921, 0,0,0,1"
366
+ }
367
+ }
368
+ },
369
+ {
370
+ "opcode": "addEulerRotationKeyframeTrack",
371
+ "blockType": "COMMAND",
372
+ "text": "add euler rotation keyframe track to clip [CLIP] path [PATH] times [TIMES] values [VALUES] unit [UNIT]",
373
+ "description": "Adds a quaternion track converted from Euler x y z rotation values.",
374
+ "arguments": {
375
+ "CLIP": {
376
+ "type": "STRING",
377
+ "defaultValue": "wave"
378
+ },
379
+ "PATH": {
380
+ "type": "STRING",
381
+ "defaultValue": ".quaternion"
382
+ },
383
+ "TIMES": {
384
+ "type": "STRING",
385
+ "defaultValue": "0,0.25,0.5,0.75,1"
386
+ },
387
+ "VALUES": {
388
+ "type": "STRING",
389
+ "defaultValue": "0,0,0, 0,0,0.8, 0,0,0, 0,0,-0.8, 0,0,0"
390
+ },
391
+ "UNIT": {
392
+ "type": "STRING",
393
+ "defaultValue": "radians"
394
+ }
395
+ }
396
+ },
397
+ {
398
+ "opcode": "addPositionKeyframe",
399
+ "blockType": "COMMAND",
400
+ "text": "add position keyframe to clip [CLIP] at [TIME] x [X] y [Y] z [Z]",
401
+ "description": "Adds or replaces one position keyframe on the clip.",
402
+ "arguments": {
403
+ "CLIP": {
404
+ "type": "STRING",
405
+ "defaultValue": "move-up"
406
+ },
407
+ "TIME": {
408
+ "type": "NUMBER",
409
+ "defaultValue": 0
410
+ },
411
+ "X": {
412
+ "type": "NUMBER",
413
+ "defaultValue": 0
414
+ },
415
+ "Y": {
416
+ "type": "NUMBER",
417
+ "defaultValue": 1
418
+ },
419
+ "Z": {
420
+ "type": "NUMBER",
421
+ "defaultValue": -3
422
+ }
423
+ }
424
+ },
425
+ {
426
+ "opcode": "addScaleKeyframe",
427
+ "blockType": "COMMAND",
428
+ "text": "add scale keyframe to clip [CLIP] at [TIME] x [X] y [Y] z [Z]",
429
+ "description": "Adds or replaces one scale keyframe on the clip.",
430
+ "arguments": {
431
+ "CLIP": {
432
+ "type": "STRING",
433
+ "defaultValue": "pulse"
434
+ },
435
+ "TIME": {
436
+ "type": "NUMBER",
437
+ "defaultValue": 0
438
+ },
439
+ "X": {
440
+ "type": "NUMBER",
441
+ "defaultValue": 1
442
+ },
443
+ "Y": {
444
+ "type": "NUMBER",
445
+ "defaultValue": 1
446
+ },
447
+ "Z": {
448
+ "type": "NUMBER",
449
+ "defaultValue": 1
450
+ }
451
+ }
452
+ },
453
+ {
454
+ "opcode": "addEulerRotationKeyframe",
455
+ "blockType": "COMMAND",
456
+ "text": "add euler rotation keyframe to clip [CLIP] at [TIME] x [X] y [Y] z [Z] unit [UNIT]",
457
+ "description": "Adds or replaces one Euler rotation keyframe converted to quaternion values.",
458
+ "arguments": {
459
+ "CLIP": {
460
+ "type": "STRING",
461
+ "defaultValue": "wave"
462
+ },
463
+ "TIME": {
464
+ "type": "NUMBER",
465
+ "defaultValue": 0
466
+ },
467
+ "X": {
468
+ "type": "NUMBER",
469
+ "defaultValue": 0
470
+ },
471
+ "Y": {
472
+ "type": "NUMBER",
473
+ "defaultValue": 0
474
+ },
475
+ "Z": {
476
+ "type": "NUMBER",
477
+ "defaultValue": .8
478
+ },
479
+ "UNIT": {
480
+ "type": "STRING",
481
+ "defaultValue": "radians"
482
+ }
483
+ }
484
+ },
485
+ {
486
+ "opcode": "playAnimationClip",
487
+ "blockType": "COMMAND",
488
+ "text": "play 3D animation clip [CLIP] on selector [SELECTOR] loop [LOOP]",
489
+ "description": "Plays a stored 3D animation clip on every matching node.",
490
+ "arguments": {
491
+ "CLIP": {
492
+ "type": "STRING",
493
+ "defaultValue": "wave"
494
+ },
495
+ "SELECTOR": {
496
+ "type": "STRING",
497
+ "defaultValue": "#leftArm"
498
+ },
499
+ "LOOP": {
500
+ "type": "BOOLEAN",
501
+ "defaultValue": true
502
+ }
503
+ }
504
+ },
505
+ {
506
+ "opcode": "stopAnimationClip",
507
+ "blockType": "COMMAND",
508
+ "text": "stop 3D animation clip [CLIP] on selector [SELECTOR]",
509
+ "description": "Stops a stored 3D animation clip on every matching node.",
510
+ "arguments": {
511
+ "CLIP": {
512
+ "type": "STRING",
513
+ "defaultValue": "wave"
514
+ },
515
+ "SELECTOR": {
516
+ "type": "STRING",
517
+ "defaultValue": "#leftArm"
518
+ }
519
+ }
520
+ },
521
+ {
522
+ "opcode": "pauseAnimationClip",
523
+ "blockType": "COMMAND",
524
+ "text": "pause 3D animation clip [CLIP] on selector [SELECTOR]",
525
+ "description": "Pauses a stored 3D animation clip on every matching node.",
526
+ "arguments": {
527
+ "CLIP": {
528
+ "type": "STRING",
529
+ "defaultValue": "wave"
530
+ },
531
+ "SELECTOR": {
532
+ "type": "STRING",
533
+ "defaultValue": "#leftArm"
534
+ }
535
+ }
536
+ },
537
+ {
538
+ "opcode": "resumeAnimationClip",
539
+ "blockType": "COMMAND",
540
+ "text": "resume 3D animation clip [CLIP] on selector [SELECTOR]",
541
+ "description": "Resumes a paused 3D animation clip on every matching node.",
542
+ "arguments": {
543
+ "CLIP": {
544
+ "type": "STRING",
545
+ "defaultValue": "wave"
546
+ },
547
+ "SELECTOR": {
548
+ "type": "STRING",
549
+ "defaultValue": "#leftArm"
550
+ }
551
+ }
552
+ },
553
+ {
554
+ "opcode": "setAnimationTimeScale",
555
+ "blockType": "COMMAND",
556
+ "text": "set 3D animation clip [CLIP] on selector [SELECTOR] time scale [SCALE]",
557
+ "description": "Sets the playback speed for a stored 3D animation clip on every matching node.",
558
+ "arguments": {
559
+ "CLIP": {
560
+ "type": "STRING",
561
+ "defaultValue": "wave"
562
+ },
563
+ "SELECTOR": {
564
+ "type": "STRING",
565
+ "defaultValue": "#leftArm"
566
+ },
567
+ "SCALE": {
568
+ "type": "NUMBER",
569
+ "defaultValue": 1
570
+ }
571
+ }
572
+ },
573
+ {
574
+ "opcode": "isAnimationClipPlaying",
575
+ "blockType": "BOOLEAN",
576
+ "text": "is 3D animation clip [CLIP] playing on selector [SELECTOR]?",
577
+ "description": "Reports whether any matching node has the stored 3D animation clip playing.",
578
+ "arguments": {
579
+ "CLIP": {
580
+ "type": "STRING",
581
+ "defaultValue": "wave"
582
+ },
583
+ "SELECTOR": {
584
+ "type": "STRING",
585
+ "defaultValue": "#leftArm"
586
+ }
587
+ }
588
+ }
589
+ ]
590
+ };
591
+ //#endregion
592
+ //#region src/extension.ts
593
+ var blockDefinitions = block_definitions_default.blocks;
594
+ var ROOT_ID = "scene";
595
+ var DOM_EVENT_TYPES = [
596
+ "click",
597
+ "tap",
598
+ "pointerenter",
599
+ "pointerleave"
600
+ ];
601
+ var TEMPLATE_NODE_KEYS = /* @__PURE__ */ new Set([
602
+ "attributes",
603
+ "children",
604
+ "class",
605
+ "classes",
606
+ "data",
607
+ "id",
608
+ "type"
609
+ ]);
610
+ var TurboWarpAFrameExtension = class {
611
+ constructor() {
612
+ this.nodes = /* @__PURE__ */ new Map();
613
+ this.templates = /* @__PURE__ */ new Map();
614
+ this.animationClips = /* @__PURE__ */ new Map();
615
+ this.animationPlaybacks = /* @__PURE__ */ new Map();
616
+ this.eventQueue = [];
617
+ this.domEventTypes = new Set(DOM_EVENT_TYPES);
618
+ this.runtimeId = `twaframe-${Math.random().toString(36).slice(2)}`;
619
+ this.sceneOptions = {
620
+ layer: "above-stage",
621
+ mode: "3d"
622
+ };
623
+ this.rootElement = null;
624
+ this.sceneReadyPending = false;
625
+ this.lastEvent = null;
626
+ this.resetGraph();
627
+ }
628
+ getInfo() {
629
+ return {
630
+ id: extensionConfig.id,
631
+ name: Scratch.translate(block_definitions_default.extensionName),
632
+ docsURI: extensionConfig.docsURI,
633
+ blockIconURI: extensionConfig.blockIconURI,
634
+ blocks: blockDefinitions.map((block) => this.toScratchBlock(block))
635
+ };
636
+ }
637
+ createScene(args) {
638
+ this.sceneOptions = {
639
+ layer: Scratch.Cast.toString(args.LAYER) || "above-stage",
640
+ mode: Scratch.Cast.toString(args.MODE) || "3d"
641
+ };
642
+ this.resetGraph();
643
+ this.rootElement = this.createSceneElement();
644
+ const root = this.requireNode(ROOT_ID);
645
+ root.element = this.rootElement;
646
+ this.applyNodeToElement(root);
647
+ this.sceneReadyPending = true;
648
+ this.enqueueEvent({
649
+ type: "scene-ready",
650
+ targetId: ROOT_ID,
651
+ data: "{}"
652
+ });
653
+ }
654
+ loadTemplate(args) {
655
+ const id = this.normalizeId(Scratch.Cast.toString(args.ID));
656
+ const template = this.parseTemplate(Scratch.Cast.toString(args.SOURCE));
657
+ this.templates.set(id, template);
658
+ }
659
+ createNode(args) {
660
+ const parent = this.firstMatch(Scratch.Cast.toString(args.PARENT)) ?? this.requireNode(ROOT_ID);
661
+ this.addNode({
662
+ type: Scratch.Cast.toString(args.TYPE),
663
+ id: Scratch.Cast.toString(args.ID)
664
+ }, parent.id);
665
+ }
666
+ createFromTemplate(args) {
667
+ const templateId = this.normalizeId(Scratch.Cast.toString(args.TEMPLATE));
668
+ const instanceId = this.normalizeId(Scratch.Cast.toString(args.INSTANCE));
669
+ const template = this.templates.get(templateId);
670
+ if (template === void 0) throw new Error(`Unknown A-Frame template: ${templateId}`);
671
+ const parent = this.firstMatch(Scratch.Cast.toString(args.PARENT)) ?? this.requireNode(ROOT_ID);
672
+ const rootTemplate = {
673
+ ...template,
674
+ id: instanceId,
675
+ data: {
676
+ ...template.data,
677
+ template: templateId,
678
+ instance: instanceId
679
+ }
680
+ };
681
+ this.addNodeTree(rootTemplate, parent.id, instanceId);
682
+ }
683
+ setPosition(args) {
684
+ this.setVec3Attribute(Scratch.Cast.toString(args.SELECTOR), "position", this.argsToVec3(args));
685
+ }
686
+ moveBy(args) {
687
+ const delta = this.argsToVec3(args);
688
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
689
+ const current = this.parseVec3(node.attributes.get("position"));
690
+ this.setVec3(node, "position", {
691
+ x: current.x + delta.x,
692
+ y: current.y + delta.y,
693
+ z: current.z + delta.z
694
+ });
695
+ }
696
+ }
697
+ setRotation(args) {
698
+ this.setVec3Attribute(Scratch.Cast.toString(args.SELECTOR), "rotation", this.argsToVec3(args));
699
+ }
700
+ addClass(args) {
701
+ const className = this.normalizeToken(Scratch.Cast.toString(args.CLASS));
702
+ if (className.length === 0) return;
703
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
704
+ node.classes.add(className);
705
+ this.applyNodeToElement(node);
706
+ }
707
+ }
708
+ setData(args) {
709
+ const key = this.normalizeDataKey(Scratch.Cast.toString(args.KEY));
710
+ const value = Scratch.Cast.toString(args.VALUE);
711
+ if (key.length === 0) return;
712
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
713
+ node.data.set(key, value);
714
+ this.applyNodeToElement(node);
715
+ }
716
+ }
717
+ setAttribute(args) {
718
+ const name = this.normalizeAttributeName(Scratch.Cast.toString(args.NAME));
719
+ const value = Scratch.Cast.toString(args.VALUE);
720
+ if (name.length === 0) return;
721
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
722
+ node.attributes.set(name, value);
723
+ this.applyNodeToElement(node);
724
+ }
725
+ }
726
+ deleteSelector(args) {
727
+ const targets = this.matches(Scratch.Cast.toString(args.SELECTOR)).filter((node) => node.id !== ROOT_ID);
728
+ for (const node of targets) if (this.nodes.has(node.id)) this.deleteNode(node.id);
729
+ }
730
+ countSelector(args) {
731
+ return this.matches(Scratch.Cast.toString(args.SELECTOR)).length;
732
+ }
733
+ eventTargetId() {
734
+ return this.lastEvent?.targetId ?? "";
735
+ }
736
+ emitEvent(args) {
737
+ const target = this.firstMatch(Scratch.Cast.toString(args.SELECTOR));
738
+ if (target === void 0) return;
739
+ this.enqueueEvent({
740
+ type: Scratch.Cast.toString(args.TYPE),
741
+ targetId: target.id,
742
+ data: Scratch.Cast.toString(args.DATA)
743
+ });
744
+ }
745
+ whenSceneReady() {
746
+ if (!this.sceneReadyPending) return false;
747
+ this.sceneReadyPending = false;
748
+ this.lastEvent = {
749
+ type: "scene-ready",
750
+ targetId: ROOT_ID,
751
+ data: "{}"
752
+ };
753
+ return true;
754
+ }
755
+ whenEventOnSelector(args) {
756
+ const type = Scratch.Cast.toString(args.TYPE);
757
+ const selector = Scratch.Cast.toString(args.SELECTOR);
758
+ this.domEventTypes.add(type);
759
+ this.attachDomEventType(type);
760
+ const index = this.eventQueue.findIndex((event) => {
761
+ if (event.type !== type) return false;
762
+ const target = this.nodes.get(event.targetId);
763
+ return target !== void 0 && this.matchesSelector(target, selector);
764
+ });
765
+ if (index < 0) return false;
766
+ const [event] = this.eventQueue.splice(index, 1);
767
+ this.lastEvent = event ?? null;
768
+ return event !== void 0;
769
+ }
770
+ createAnimationClip(args) {
771
+ const name = this.normalizeId(Scratch.Cast.toString(args.NAME));
772
+ const duration = Scratch.Cast.toNumber(args.DURATION);
773
+ if (!Number.isFinite(duration) || duration < -1) throw new TypeError("Animation clip duration must be -1 or a non-negative number.");
774
+ this.stopClipEverywhere(name);
775
+ this.animationClips.set(name, {
776
+ name,
777
+ duration,
778
+ tracks: []
779
+ });
780
+ }
781
+ deleteAnimationClip(args) {
782
+ const name = this.normalizeId(Scratch.Cast.toString(args.NAME));
783
+ this.stopClipEverywhere(name);
784
+ this.animationClips.delete(name);
785
+ }
786
+ addVectorKeyframeTrack(args) {
787
+ this.addKeyframeTrack(args, "vector");
788
+ }
789
+ addQuaternionKeyframeTrack(args) {
790
+ this.addKeyframeTrack(args, "quaternion");
791
+ }
792
+ addEulerRotationKeyframeTrack(args) {
793
+ const times = this.parseNumberList(Scratch.Cast.toString(args.TIMES), "times");
794
+ const eulerValues = this.parseNumberList(Scratch.Cast.toString(args.VALUES), "values");
795
+ this.validateTrackNumbers(times, eulerValues, 3);
796
+ const unit = this.normalizeEulerUnit(Scratch.Cast.toString(args.UNIT));
797
+ const values = [];
798
+ for (let index = 0; index < eulerValues.length; index += 3) values.push(...this.eulerToQuaternion(eulerValues[index] ?? 0, eulerValues[index + 1] ?? 0, eulerValues[index + 2] ?? 0, unit));
799
+ this.pushKeyframeTrack({
800
+ clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
801
+ path: Scratch.Cast.toString(args.PATH),
802
+ trackType: "quaternion",
803
+ times,
804
+ values
805
+ });
806
+ }
807
+ addPositionKeyframe(args) {
808
+ this.insertVectorKeyframe(args, ".position");
809
+ }
810
+ addScaleKeyframe(args) {
811
+ this.insertVectorKeyframe(args, ".scale");
812
+ }
813
+ addEulerRotationKeyframe(args) {
814
+ const unit = this.normalizeEulerUnit(Scratch.Cast.toString(args.UNIT));
815
+ this.insertKeyframe({
816
+ clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
817
+ path: ".quaternion",
818
+ trackType: "quaternion",
819
+ time: Scratch.Cast.toNumber(args.TIME),
820
+ values: this.eulerToQuaternion(Scratch.Cast.toNumber(args.X), Scratch.Cast.toNumber(args.Y), Scratch.Cast.toNumber(args.Z), unit)
821
+ });
822
+ }
823
+ playAnimationClip(args) {
824
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
825
+ const clip = this.requireAnimationClip(clipName);
826
+ if (clip.tracks.length === 0) throw new Error(`3D animation clip has no keyframe tracks: ${clipName}`);
827
+ const loop = Scratch.Cast.toBoolean(args.LOOP);
828
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
829
+ const playback = this.createPlayback(node, clip, loop);
830
+ this.animationPlaybacks.set(this.playbackKey(node.id, clipName), playback);
831
+ }
832
+ this.ensureAnimationTickBridge();
833
+ }
834
+ stopAnimationClip(args) {
835
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
836
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) this.stopPlayback(this.playbackKey(node.id, clipName), true);
837
+ }
838
+ pauseAnimationClip(args) {
839
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
840
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
841
+ const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
842
+ if (playback === void 0) continue;
843
+ playback.paused = true;
844
+ if (playback.action !== null) playback.action.paused = true;
845
+ }
846
+ }
847
+ resumeAnimationClip(args) {
848
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
849
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
850
+ const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
851
+ if (playback === void 0 || !playback.active) continue;
852
+ playback.paused = false;
853
+ if (playback.action !== null) {
854
+ playback.action.paused = false;
855
+ playback.action.play?.();
856
+ }
857
+ }
858
+ }
859
+ setAnimationTimeScale(args) {
860
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
861
+ const scale = Scratch.Cast.toNumber(args.SCALE);
862
+ if (!Number.isFinite(scale)) throw new TypeError("Animation time scale must be a finite number.");
863
+ for (const node of this.matches(Scratch.Cast.toString(args.SELECTOR))) {
864
+ const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
865
+ if (playback === void 0) continue;
866
+ playback.timeScale = scale;
867
+ if (playback.action !== null) playback.action.timeScale = scale;
868
+ }
869
+ }
870
+ isAnimationClipPlaying(args) {
871
+ const clipName = this.normalizeId(Scratch.Cast.toString(args.CLIP));
872
+ return this.matches(Scratch.Cast.toString(args.SELECTOR)).some((node) => {
873
+ const playback = this.animationPlaybacks.get(this.playbackKey(node.id, clipName));
874
+ return playback?.active === true && playback.paused === false;
875
+ });
876
+ }
877
+ testStepAnimations(args) {
878
+ this.updateAnimationMixers(Scratch.Cast.toNumber(args.DELTA) / 1e3);
879
+ }
880
+ snapshot() {
881
+ return {
882
+ options: this.sceneOptions,
883
+ animationClips: [...this.animationClips.values()].map((clip) => ({
884
+ name: clip.name,
885
+ duration: clip.duration,
886
+ tracks: clip.tracks.map((track) => ({
887
+ type: track.type,
888
+ path: track.path,
889
+ times: [...track.times],
890
+ values: [...track.values]
891
+ }))
892
+ })),
893
+ animationPlaybacks: [...this.animationPlaybacks.values()].map((playback) => ({
894
+ nodeId: playback.nodeId,
895
+ clipName: playback.clipName,
896
+ loop: playback.loop,
897
+ active: playback.active,
898
+ playing: playback.active && !playback.paused,
899
+ paused: playback.paused,
900
+ timeScale: playback.timeScale,
901
+ hasMixer: playback.mixer !== null
902
+ })),
903
+ nodes: [...this.nodes.values()].map((node) => ({
904
+ id: node.id,
905
+ type: node.type,
906
+ parentId: node.parentId,
907
+ children: [...node.children],
908
+ classes: [...node.classes].sort(),
909
+ data: Object.fromEntries([...node.data.entries()].sort()),
910
+ attributes: Object.fromEntries([...node.attributes.entries()].sort())
911
+ }))
912
+ };
913
+ }
914
+ resetGraph() {
915
+ for (const key of [...this.animationPlaybacks.keys()]) this.stopPlayback(key, true);
916
+ this.nodes.clear();
917
+ this.nodes.set(ROOT_ID, {
918
+ id: ROOT_ID,
919
+ type: "scene",
920
+ parentId: null,
921
+ children: [],
922
+ classes: /* @__PURE__ */ new Set(),
923
+ data: /* @__PURE__ */ new Map(),
924
+ attributes: /* @__PURE__ */ new Map([["embedded", "true"], ["renderer", "alpha: true"]]),
925
+ element: null
926
+ });
927
+ this.eventQueue.length = 0;
928
+ this.lastEvent = null;
929
+ }
930
+ addNodeTree(template, parentId, fallbackId) {
931
+ const node = this.addNode({
932
+ ...template,
933
+ id: fallbackId
934
+ }, parentId);
935
+ for (const [index, child] of (template.children ?? []).entries()) {
936
+ const childId = child.id ?? child.type ?? String(index + 1);
937
+ this.addNodeTree(child, node.id, `${node.id}-${this.normalizeId(childId)}`);
938
+ }
939
+ return node;
940
+ }
941
+ addNode(template, parentId) {
942
+ const id = this.normalizeId(template.id ?? template.type ?? "node");
943
+ if (id === ROOT_ID || this.nodes.has(id)) throw new Error(`Duplicate A-Frame node id: ${id}`);
944
+ const parent = this.requireNode(parentId);
945
+ const node = {
946
+ id,
947
+ type: this.normalizeNodeType(template.type ?? "group"),
948
+ parentId,
949
+ children: [],
950
+ classes: new Set(this.normalizeClasses(template)),
951
+ data: new Map(this.normalizeRecord(template.data, this.normalizeDataKey.bind(this))),
952
+ attributes: new Map(this.normalizeRecord(template.attributes, this.normalizeAttributeName.bind(this))),
953
+ element: this.createElementForType(template.type ?? "group")
954
+ };
955
+ this.nodes.set(id, node);
956
+ parent.children.push(id);
957
+ this.attachElement(parent, node);
958
+ this.attachNodeEventListeners(node);
959
+ this.applyNodeToElement(node);
960
+ return node;
961
+ }
962
+ deleteNode(id) {
963
+ const node = this.requireNode(id);
964
+ for (const childId of [...node.children]) this.deleteNode(childId);
965
+ if (node.parentId !== null) {
966
+ const parent = this.requireNode(node.parentId);
967
+ parent.children = parent.children.filter((childId) => childId !== id);
968
+ }
969
+ node.element?.remove();
970
+ this.nodes.delete(id);
971
+ for (const key of [...this.animationPlaybacks.keys()]) if (key.startsWith(`${id}:`)) this.stopPlayback(key, true);
972
+ }
973
+ matches(selector) {
974
+ const normalized = selector.trim();
975
+ if (normalized.length === 0 || normalized === "*") return [...this.nodes.values()];
976
+ return [...this.nodes.values()].filter((node) => this.matchesSelector(node, normalized));
977
+ }
978
+ firstMatch(selector) {
979
+ return this.matches(selector)[0];
980
+ }
981
+ matchesSelector(node, selector) {
982
+ if (selector === "@event" || selector === "event target") return this.lastEvent?.targetId === node.id;
983
+ if (selector.startsWith("#")) return node.id === this.normalizeId(selector.slice(1));
984
+ if (selector.startsWith(".")) return node.classes.has(this.normalizeToken(selector.slice(1)));
985
+ const dataMatch = selector.match(/^\[data-([a-zA-Z0-9_-]+)=["']?([^"'\]]+)["']?\]$/);
986
+ if (dataMatch !== null) {
987
+ const [, key, value] = dataMatch;
988
+ return node.data.get(this.normalizeDataKey(key ?? "")) === value;
989
+ }
990
+ return node.id === this.normalizeId(selector);
991
+ }
992
+ enqueueEvent(event) {
993
+ this.pushEvent(event);
994
+ const element = this.nodes.get(event.targetId)?.element;
995
+ if (element !== null && element !== void 0) element.dispatchEvent(new CustomEvent(event.type, { detail: {
996
+ data: event.data,
997
+ targetId: event.targetId,
998
+ twAframeSynthetic: true
999
+ } }));
1000
+ }
1001
+ pushEvent(event) {
1002
+ this.eventQueue.push(event);
1003
+ }
1004
+ createSceneElement() {
1005
+ if (typeof document === "undefined") return null;
1006
+ document.getElementById("tw-aframe-root")?.remove();
1007
+ const host = document.createElement("div");
1008
+ host.id = "tw-aframe-root";
1009
+ host.dataset["twAframeLayer"] = this.sceneOptions.layer;
1010
+ host.dataset["twAframeMode"] = this.sceneOptions.mode;
1011
+ host.style.position = "absolute";
1012
+ host.style.inset = "0";
1013
+ host.style.pointerEvents = "auto";
1014
+ host.style.zIndex = this.sceneOptions.layer === "below-stage" ? "0" : "10";
1015
+ const scene = document.createElement("a-scene");
1016
+ host.append(scene);
1017
+ this.findStageMount().append(host);
1018
+ return scene;
1019
+ }
1020
+ createElementForType(type) {
1021
+ if (typeof document === "undefined") return null;
1022
+ return document.createElement(this.tagForType(this.normalizeNodeType(type)));
1023
+ }
1024
+ attachElement(parent, child) {
1025
+ if (parent.element === null || child.element === null) return;
1026
+ parent.element.append(child.element);
1027
+ }
1028
+ attachDomEventType(type) {
1029
+ for (const node of this.nodes.values()) this.attachNodeEventListener(node, type);
1030
+ }
1031
+ attachNodeEventListeners(node) {
1032
+ for (const type of this.domEventTypes) this.attachNodeEventListener(node, type);
1033
+ }
1034
+ attachNodeEventListener(node, type) {
1035
+ const element = node.element;
1036
+ if (element === null) return;
1037
+ const listenerKey = `twAframeListener${type}`;
1038
+ const elementWithState = element;
1039
+ if (elementWithState[listenerKey]) return;
1040
+ element.addEventListener(type, (event) => {
1041
+ if (event.target !== element) return;
1042
+ const detail = this.eventDetail(event);
1043
+ if (detail["twAframeSynthetic"] === true) return;
1044
+ this.pushEvent({
1045
+ type,
1046
+ targetId: node.id,
1047
+ data: JSON.stringify(detail)
1048
+ });
1049
+ });
1050
+ elementWithState[listenerKey] = true;
1051
+ }
1052
+ eventDetail(event) {
1053
+ if ("detail" in event && typeof event.detail === "object" && event.detail !== null) return event.detail;
1054
+ return {};
1055
+ }
1056
+ findStageMount() {
1057
+ for (const selector of [
1058
+ "[class*=\"stage_stage-wrapper\"]",
1059
+ "[class*=\"stage-wrapper\"]",
1060
+ "[class*=\"stage\"]",
1061
+ "#scratch-stage",
1062
+ "canvas"
1063
+ ]) {
1064
+ const match = document.querySelector(selector);
1065
+ const mount = match instanceof HTMLCanvasElement ? match.parentElement : match;
1066
+ if (mount instanceof HTMLElement) {
1067
+ if (getComputedStyle(mount).position === "static") mount.style.position = "relative";
1068
+ return mount;
1069
+ }
1070
+ }
1071
+ return document.body;
1072
+ }
1073
+ applyNodeToElement(node) {
1074
+ if (node.element === null) return;
1075
+ node.element.id = node.id;
1076
+ node.element.setAttribute("class", [...node.classes].sort().join(" "));
1077
+ for (const [key, value] of node.data) node.element.setAttribute(`data-${key}`, value);
1078
+ for (const [name, value] of node.attributes) node.element.setAttribute(name, value);
1079
+ }
1080
+ addKeyframeTrack(args, trackType) {
1081
+ const times = this.parseNumberList(Scratch.Cast.toString(args.TIMES), "times");
1082
+ const values = this.parseNumberList(Scratch.Cast.toString(args.VALUES), "values");
1083
+ this.validateTrackNumbers(times, values, trackType === "vector" ? 3 : 4);
1084
+ this.pushKeyframeTrack({
1085
+ clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
1086
+ path: Scratch.Cast.toString(args.PATH),
1087
+ trackType,
1088
+ times,
1089
+ values
1090
+ });
1091
+ }
1092
+ insertVectorKeyframe(args, path) {
1093
+ this.insertKeyframe({
1094
+ clipName: this.normalizeId(Scratch.Cast.toString(args.CLIP)),
1095
+ path,
1096
+ trackType: "vector",
1097
+ time: Scratch.Cast.toNumber(args.TIME),
1098
+ values: [
1099
+ Scratch.Cast.toNumber(args.X),
1100
+ Scratch.Cast.toNumber(args.Y),
1101
+ Scratch.Cast.toNumber(args.Z)
1102
+ ]
1103
+ });
1104
+ }
1105
+ insertKeyframe({ clipName, path, trackType, time, values }) {
1106
+ if (!Number.isFinite(time) || time < 0) throw new TypeError("Animation keyframe time must be a non-negative number.");
1107
+ if (values.some((value) => !Number.isFinite(value))) throw new TypeError("Animation keyframe values must be finite numbers.");
1108
+ const stride = trackType === "vector" ? 3 : 4;
1109
+ if (values.length !== stride) throw new TypeError(`Animation keyframe must contain ${stride} values.`);
1110
+ const clip = this.requireAnimationClip(clipName);
1111
+ const normalizedPath = this.normalizeTrackPath(path, trackType);
1112
+ let track = clip.tracks.find((item) => item.type === trackType && item.path === normalizedPath);
1113
+ if (track === void 0) {
1114
+ track = {
1115
+ type: trackType,
1116
+ path: normalizedPath,
1117
+ times: [],
1118
+ values: []
1119
+ };
1120
+ clip.tracks.push(track);
1121
+ }
1122
+ const insertAt = track.times.findIndex((existingTime) => existingTime >= time);
1123
+ const valueInsertAt = (insertAt < 0 ? track.times.length : insertAt) * stride;
1124
+ if (insertAt >= 0 && track.times[insertAt] === time) {
1125
+ track.values.splice(valueInsertAt, stride, ...values);
1126
+ return;
1127
+ }
1128
+ const timeInsertAt = insertAt < 0 ? track.times.length : insertAt;
1129
+ track.times.splice(timeInsertAt, 0, time);
1130
+ track.values.splice(valueInsertAt, 0, ...values);
1131
+ }
1132
+ pushKeyframeTrack({ clipName, path, trackType, times, values }) {
1133
+ const clip = this.requireAnimationClip(clipName);
1134
+ const normalizedPath = this.normalizeTrackPath(path, trackType);
1135
+ clip.tracks.push({
1136
+ type: trackType,
1137
+ path: normalizedPath,
1138
+ times: [...times],
1139
+ values: [...values]
1140
+ });
1141
+ }
1142
+ parseNumberList(source, label) {
1143
+ const trimmed = source.trim();
1144
+ if (trimmed.length === 0) throw new TypeError(`Animation ${label} must contain at least one number.`);
1145
+ const values = trimmed.split(/[\s,]+/).filter((part) => part.length > 0).map((part) => Number(part));
1146
+ if (values.length === 0 || values.some((value) => !Number.isFinite(value))) throw new TypeError(`Animation ${label} must contain only finite numbers.`);
1147
+ return values;
1148
+ }
1149
+ validateTrackNumbers(times, values, stride) {
1150
+ if (times.length === 0) throw new TypeError("Animation track times must not be empty.");
1151
+ for (let index = 1; index < times.length; index += 1) if ((times[index] ?? 0) < (times[index - 1] ?? 0)) throw new TypeError("Animation track times must be sorted in ascending order.");
1152
+ const expectedValues = times.length * stride;
1153
+ if (values.length !== expectedValues) throw new TypeError(`Animation track values length must be ${expectedValues} for ${times.length} keyframes.`);
1154
+ }
1155
+ normalizeTrackPath(path, trackType) {
1156
+ const normalized = path.trim();
1157
+ const allowed = trackType === "vector" ? /* @__PURE__ */ new Set([".position", ".scale"]) : /* @__PURE__ */ new Set([".quaternion"]);
1158
+ if (!allowed.has(normalized)) throw new TypeError(`Animation ${trackType} track path must be one of: ${[...allowed].join(", ")}.`);
1159
+ return normalized;
1160
+ }
1161
+ eulerToQuaternion(x, y, z, unit) {
1162
+ const scale = unit === "degrees" ? Math.PI / 180 : 1;
1163
+ const halfX = x * scale / 2;
1164
+ const halfY = y * scale / 2;
1165
+ const halfZ = z * scale / 2;
1166
+ const c1 = Math.cos(halfX);
1167
+ const c2 = Math.cos(halfY);
1168
+ const c3 = Math.cos(halfZ);
1169
+ const s1 = Math.sin(halfX);
1170
+ const s2 = Math.sin(halfY);
1171
+ const s3 = Math.sin(halfZ);
1172
+ return [
1173
+ s1 * c2 * c3 + c1 * s2 * s3,
1174
+ c1 * s2 * c3 - s1 * c2 * s3,
1175
+ c1 * c2 * s3 + s1 * s2 * c3,
1176
+ c1 * c2 * c3 - s1 * s2 * s3
1177
+ ];
1178
+ }
1179
+ normalizeEulerUnit(value) {
1180
+ const unit = value.trim().toLowerCase();
1181
+ if (unit !== "radians" && unit !== "degrees") throw new TypeError("Euler rotation keyframe unit must be radians or degrees.");
1182
+ return unit;
1183
+ }
1184
+ createPlayback(node, clip, loop) {
1185
+ const key = this.playbackKey(node.id, clip.name);
1186
+ this.stopPlayback(key, true);
1187
+ const playback = {
1188
+ nodeId: node.id,
1189
+ clipName: clip.name,
1190
+ loop,
1191
+ active: false,
1192
+ paused: false,
1193
+ timeScale: 1,
1194
+ mixer: null,
1195
+ action: null
1196
+ };
1197
+ const mixer = this.createMixer(node, clip, loop);
1198
+ if (mixer !== null) {
1199
+ playback.mixer = mixer.mixer;
1200
+ playback.action = mixer.action;
1201
+ playback.active = true;
1202
+ }
1203
+ return playback;
1204
+ }
1205
+ createMixer(node, clip, loop) {
1206
+ const object3D = this.object3DForNode(node);
1207
+ const THREE = this.getThree();
1208
+ if (object3D === null || THREE === null) return null;
1209
+ const threeClip = this.toThreeAnimationClip(THREE, clip);
1210
+ const mixer = new THREE.AnimationMixer(object3D);
1211
+ const action = mixer.clipAction(threeClip);
1212
+ if (action.setLoop !== void 0) action.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, loop ? Infinity : 1);
1213
+ action.paused = false;
1214
+ action.timeScale = 1;
1215
+ action.play?.();
1216
+ return {
1217
+ mixer,
1218
+ action
1219
+ };
1220
+ }
1221
+ toThreeAnimationClip(THREE, clip) {
1222
+ const tracks = clip.tracks.map((track) => {
1223
+ if (track.type === "vector") return new THREE.VectorKeyframeTrack(track.path, track.times, track.values);
1224
+ return new THREE.QuaternionKeyframeTrack(track.path, track.times, track.values);
1225
+ });
1226
+ return new THREE.AnimationClip(clip.name, clip.duration, tracks);
1227
+ }
1228
+ object3DForNode(node) {
1229
+ return node.element?.object3D ?? null;
1230
+ }
1231
+ stopPlayback(key, remove) {
1232
+ const playback = this.animationPlaybacks.get(key);
1233
+ if (playback === void 0) return;
1234
+ playback.action?.stop?.();
1235
+ playback.mixer?.stopAllAction?.();
1236
+ playback.active = false;
1237
+ playback.paused = false;
1238
+ if (remove) this.animationPlaybacks.delete(key);
1239
+ }
1240
+ stopClipEverywhere(clipName) {
1241
+ for (const [key, playback] of [...this.animationPlaybacks.entries()]) if (playback.clipName === clipName) this.stopPlayback(key, true);
1242
+ }
1243
+ updateAnimationMixers(deltaTime) {
1244
+ if (!Number.isFinite(deltaTime) || deltaTime < 0) return;
1245
+ for (const playback of this.animationPlaybacks.values()) {
1246
+ if (!playback.active || playback.paused) continue;
1247
+ playback.mixer?.update(deltaTime * playback.timeScale);
1248
+ }
1249
+ }
1250
+ ensureAnimationTickBridge() {
1251
+ const scene = this.rootElement;
1252
+ if (scene === null || this.getThree() === null) return;
1253
+ const AFRAME = this.getAFrame();
1254
+ if (AFRAME === null) return;
1255
+ this.animationRuntimeRegistry().set(this.runtimeId, this);
1256
+ if (AFRAME.components?.["tw-animation-runtime"] === void 0) AFRAME.registerComponent("tw-animation-runtime", {
1257
+ schema: { id: { type: "string" } },
1258
+ tick(_time, timeDelta) {
1259
+ animationRuntimeRegistry().get(this.data.id)?.updateAnimationMixers(timeDelta / 1e3);
1260
+ }
1261
+ });
1262
+ scene.setAttribute("tw-animation-runtime", `id: ${this.runtimeId}`);
1263
+ }
1264
+ animationRuntimeRegistry() {
1265
+ return animationRuntimeRegistry();
1266
+ }
1267
+ getAFrame() {
1268
+ return globalThis.AFRAME ?? null;
1269
+ }
1270
+ getThree() {
1271
+ return this.getAFrame()?.THREE ?? null;
1272
+ }
1273
+ playbackKey(nodeId, clipName) {
1274
+ return `${nodeId}:${clipName}`;
1275
+ }
1276
+ requireAnimationClip(name) {
1277
+ const clip = this.animationClips.get(name);
1278
+ if (clip === void 0) throw new Error(`Unknown 3D animation clip: ${name}`);
1279
+ return clip;
1280
+ }
1281
+ setVec3Attribute(selector, name, value) {
1282
+ for (const node of this.matches(selector)) this.setVec3(node, name, value);
1283
+ }
1284
+ setVec3(node, name, value) {
1285
+ node.attributes.set(name, `${value.x} ${value.y} ${value.z}`);
1286
+ this.applyNodeToElement(node);
1287
+ }
1288
+ argsToVec3(args) {
1289
+ return {
1290
+ x: Scratch.Cast.toNumber(args.X),
1291
+ y: Scratch.Cast.toNumber(args.Y),
1292
+ z: Scratch.Cast.toNumber(args.Z)
1293
+ };
1294
+ }
1295
+ parseVec3(value) {
1296
+ if (value === void 0) return {
1297
+ x: 0,
1298
+ y: 0,
1299
+ z: 0
1300
+ };
1301
+ const [x = 0, y = 0, z = 0] = value.split(/\s+/).map((part) => Number(part));
1302
+ return {
1303
+ x,
1304
+ y,
1305
+ z
1306
+ };
1307
+ }
1308
+ parseTemplate(source) {
1309
+ const value = JSON.parse(source);
1310
+ this.validateTemplateNode(value, "template");
1311
+ return value;
1312
+ }
1313
+ validateTemplateNode(value, path) {
1314
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`A-Frame ${path} must be an object.`);
1315
+ const node = value;
1316
+ for (const key of Object.keys(node)) if (!TEMPLATE_NODE_KEYS.has(key)) throw new TypeError(`A-Frame ${path}.${key} is not supported.`);
1317
+ this.validateOptionalString(node["type"], `${path}.type`);
1318
+ this.validateOptionalString(node["id"], `${path}.id`);
1319
+ this.validateTemplateClass(node["class"], `${path}.class`);
1320
+ this.validateOptionalStringArray(node["classes"], `${path}.classes`);
1321
+ this.validateStringRecord(node["data"], `${path}.data`);
1322
+ this.validateStringRecord(node["attributes"], `${path}.attributes`);
1323
+ const children = node["children"];
1324
+ if (children === void 0) return;
1325
+ if (!Array.isArray(children)) throw new TypeError(`A-Frame ${path}.children must be an array.`);
1326
+ children.forEach((child, index) => {
1327
+ this.validateTemplateNode(child, `${path}.children[${index}]`);
1328
+ });
1329
+ }
1330
+ validateTemplateClass(value, path) {
1331
+ if (value === void 0 || typeof value === "string") return;
1332
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return;
1333
+ throw new TypeError(`A-Frame ${path} must be a string or string array.`);
1334
+ }
1335
+ validateOptionalStringArray(value, path) {
1336
+ if (value === void 0) return;
1337
+ if (Array.isArray(value) && value.every((item) => typeof item === "string")) return;
1338
+ throw new TypeError(`A-Frame ${path} must be a string array.`);
1339
+ }
1340
+ validateOptionalString(value, path) {
1341
+ if (value === void 0 || typeof value === "string") return;
1342
+ throw new TypeError(`A-Frame ${path} must be a string.`);
1343
+ }
1344
+ validateStringRecord(value, path) {
1345
+ if (value === void 0) return;
1346
+ if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`A-Frame ${path} must be an object.`);
1347
+ for (const [key, recordValue] of Object.entries(value)) {
1348
+ if (key.trim().length === 0) throw new TypeError(`A-Frame ${path} keys must be non-empty strings.`);
1349
+ if (recordValue === void 0) throw new TypeError(`A-Frame ${path}.${key} must not be undefined.`);
1350
+ }
1351
+ }
1352
+ normalizeClasses(template) {
1353
+ return [...Array.isArray(template.class) ? template.class : String(template.class ?? "").split(/\s+/), ...template.classes ?? []].map((value) => this.normalizeToken(value)).filter((value) => value.length > 0);
1354
+ }
1355
+ normalizeRecord(value, normalizeKey) {
1356
+ return Object.entries(value ?? {}).map(([key, recordValue]) => [normalizeKey(key), String(recordValue)]);
1357
+ }
1358
+ normalizeNodeType(value) {
1359
+ const type = this.normalizeToken(value);
1360
+ return type.length === 0 ? "group" : type;
1361
+ }
1362
+ normalizeId(value) {
1363
+ return this.normalizeToken(value) || "node";
1364
+ }
1365
+ normalizeToken(value) {
1366
+ return value.trim().replace(/[^a-zA-Z0-9_-]/g, "-");
1367
+ }
1368
+ normalizeDataKey(value) {
1369
+ return this.normalizeToken(value).toLowerCase();
1370
+ }
1371
+ normalizeAttributeName(value) {
1372
+ return value.trim().replace(/[^a-zA-Z0-9_:-]/g, "-");
1373
+ }
1374
+ tagForType(type) {
1375
+ return {
1376
+ box: "a-box",
1377
+ camera: "a-camera",
1378
+ circle: "a-circle",
1379
+ cone: "a-cone",
1380
+ cylinder: "a-cylinder",
1381
+ empty: "a-entity",
1382
+ group: "a-entity",
1383
+ image: "a-image",
1384
+ "image-plane": "a-image",
1385
+ light: "a-light",
1386
+ model: "a-entity",
1387
+ plane: "a-plane",
1388
+ primitive: "a-entity",
1389
+ scene: "a-scene",
1390
+ sphere: "a-sphere",
1391
+ text: "a-text"
1392
+ }[type] ?? "a-entity";
1393
+ }
1394
+ requireNode(id) {
1395
+ const node = this.nodes.get(id);
1396
+ if (node === void 0) throw new Error(`Unknown A-Frame node: ${id}`);
1397
+ return node;
1398
+ }
1399
+ toScratchBlock(block) {
1400
+ return {
1401
+ opcode: block.opcode,
1402
+ blockType: Scratch.BlockType[block.blockType],
1403
+ text: Scratch.translate(block.text),
1404
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
1405
+ type: Scratch.ArgumentType[argument.type],
1406
+ defaultValue: argument.defaultValue
1407
+ }]))
1408
+ };
1409
+ }
1410
+ };
1411
+ function animationRuntimeRegistry() {
1412
+ const globalState = globalThis;
1413
+ globalState.__twAframeAnimationRuntimes ?? (globalState.__twAframeAnimationRuntimes = /* @__PURE__ */ new Map());
1414
+ return globalState.__twAframeAnimationRuntimes;
1415
+ }
1416
+ //#endregion
1417
+ //#region src/index.ts
1418
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
1419
+ Scratch.extensions.register(new TurboWarpAFrameExtension());
1420
+ //#endregion
1421
+
1422
+ })(Scratch);