@scratch/scratch-vm 11.0.0-beta.1

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.
Files changed (175) hide show
  1. package/.jsdoc.json +20 -0
  2. package/.nvmrc +1 -0
  3. package/CHANGELOG.md +7004 -0
  4. package/LICENSE +12 -0
  5. package/README.md +120 -0
  6. package/TRADEMARK +1 -0
  7. package/commitlint.config.js +4 -0
  8. package/docs/extensions.md +527 -0
  9. package/package.json +103 -0
  10. package/release.config.js +13 -0
  11. package/src/blocks/scratch3_control.js +206 -0
  12. package/src/blocks/scratch3_core_example.js +69 -0
  13. package/src/blocks/scratch3_data.js +257 -0
  14. package/src/blocks/scratch3_event.js +137 -0
  15. package/src/blocks/scratch3_looks.js +612 -0
  16. package/src/blocks/scratch3_motion.js +288 -0
  17. package/src/blocks/scratch3_operators.js +154 -0
  18. package/src/blocks/scratch3_procedures.js +79 -0
  19. package/src/blocks/scratch3_sensing.js +336 -0
  20. package/src/blocks/scratch3_sound.js +350 -0
  21. package/src/dispatch/central-dispatch.js +143 -0
  22. package/src/dispatch/shared-dispatch.js +235 -0
  23. package/src/dispatch/worker-dispatch.js +110 -0
  24. package/src/engine/adapter.js +176 -0
  25. package/src/engine/block-utility.js +242 -0
  26. package/src/engine/blocks-execute-cache.js +19 -0
  27. package/src/engine/blocks-runtime-cache.js +78 -0
  28. package/src/engine/blocks.js +1299 -0
  29. package/src/engine/comment.js +56 -0
  30. package/src/engine/execute.js +580 -0
  31. package/src/engine/monitor-record.js +23 -0
  32. package/src/engine/mutation-adapter.js +48 -0
  33. package/src/engine/profiler.js +390 -0
  34. package/src/engine/runtime.js +2686 -0
  35. package/src/engine/scratch-blocks-constants.js +27 -0
  36. package/src/engine/sequencer.js +361 -0
  37. package/src/engine/stage-layering.js +29 -0
  38. package/src/engine/target.js +799 -0
  39. package/src/engine/thread.js +404 -0
  40. package/src/engine/variable.js +70 -0
  41. package/src/extension-support/argument-type.js +47 -0
  42. package/src/extension-support/block-type.js +50 -0
  43. package/src/extension-support/define-messages.js +18 -0
  44. package/src/extension-support/extension-manager.js +440 -0
  45. package/src/extension-support/extension-metadata.js +64 -0
  46. package/src/extension-support/extension-worker.js +59 -0
  47. package/src/extension-support/reporter-scope.js +18 -0
  48. package/src/extension-support/target-type.js +17 -0
  49. package/src/extensions/scratch3_boost/index.js +2113 -0
  50. package/src/extensions/scratch3_ev3/index.js +1355 -0
  51. package/src/extensions/scratch3_gdx_for/index.js +981 -0
  52. package/src/extensions/scratch3_gdx_for/scratch-link-device-adapter.js +44 -0
  53. package/src/extensions/scratch3_makeymakey/index.js +396 -0
  54. package/src/extensions/scratch3_microbit/index.js +984 -0
  55. package/src/extensions/scratch3_music/assets/drums/1-snare.mp3 +0 -0
  56. package/src/extensions/scratch3_music/assets/drums/10-wood-block.mp3 +0 -0
  57. package/src/extensions/scratch3_music/assets/drums/11-cowbell.mp3 +0 -0
  58. package/src/extensions/scratch3_music/assets/drums/12-triangle.mp3 +0 -0
  59. package/src/extensions/scratch3_music/assets/drums/13-bongo.mp3 +0 -0
  60. package/src/extensions/scratch3_music/assets/drums/14-conga.mp3 +0 -0
  61. package/src/extensions/scratch3_music/assets/drums/15-cabasa.mp3 +0 -0
  62. package/src/extensions/scratch3_music/assets/drums/16-guiro.mp3 +0 -0
  63. package/src/extensions/scratch3_music/assets/drums/17-vibraslap.mp3 +0 -0
  64. package/src/extensions/scratch3_music/assets/drums/18-cuica.mp3 +0 -0
  65. package/src/extensions/scratch3_music/assets/drums/2-bass-drum.mp3 +0 -0
  66. package/src/extensions/scratch3_music/assets/drums/3-side-stick.mp3 +0 -0
  67. package/src/extensions/scratch3_music/assets/drums/4-crash-cymbal.mp3 +0 -0
  68. package/src/extensions/scratch3_music/assets/drums/5-open-hi-hat.mp3 +0 -0
  69. package/src/extensions/scratch3_music/assets/drums/6-closed-hi-hat.mp3 +0 -0
  70. package/src/extensions/scratch3_music/assets/drums/7-tambourine.mp3 +0 -0
  71. package/src/extensions/scratch3_music/assets/drums/8-hand-clap.mp3 +0 -0
  72. package/src/extensions/scratch3_music/assets/drums/9-claves.mp3 +0 -0
  73. package/src/extensions/scratch3_music/assets/instruments/1-piano/108.mp3 +0 -0
  74. package/src/extensions/scratch3_music/assets/instruments/1-piano/24.mp3 +0 -0
  75. package/src/extensions/scratch3_music/assets/instruments/1-piano/36.mp3 +0 -0
  76. package/src/extensions/scratch3_music/assets/instruments/1-piano/48.mp3 +0 -0
  77. package/src/extensions/scratch3_music/assets/instruments/1-piano/60.mp3 +0 -0
  78. package/src/extensions/scratch3_music/assets/instruments/1-piano/72.mp3 +0 -0
  79. package/src/extensions/scratch3_music/assets/instruments/1-piano/84.mp3 +0 -0
  80. package/src/extensions/scratch3_music/assets/instruments/1-piano/96.mp3 +0 -0
  81. package/src/extensions/scratch3_music/assets/instruments/10-clarinet/48.mp3 +0 -0
  82. package/src/extensions/scratch3_music/assets/instruments/10-clarinet/60.mp3 +0 -0
  83. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/36.mp3 +0 -0
  84. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/60.mp3 +0 -0
  85. package/src/extensions/scratch3_music/assets/instruments/11-saxophone/84.mp3 +0 -0
  86. package/src/extensions/scratch3_music/assets/instruments/12-flute/60.mp3 +0 -0
  87. package/src/extensions/scratch3_music/assets/instruments/12-flute/72.mp3 +0 -0
  88. package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/60.mp3 +0 -0
  89. package/src/extensions/scratch3_music/assets/instruments/13-wooden-flute/72.mp3 +0 -0
  90. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/36.mp3 +0 -0
  91. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/48.mp3 +0 -0
  92. package/src/extensions/scratch3_music/assets/instruments/14-bassoon/60.mp3 +0 -0
  93. package/src/extensions/scratch3_music/assets/instruments/15-choir/48.mp3 +0 -0
  94. package/src/extensions/scratch3_music/assets/instruments/15-choir/60.mp3 +0 -0
  95. package/src/extensions/scratch3_music/assets/instruments/15-choir/72.mp3 +0 -0
  96. package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/60.mp3 +0 -0
  97. package/src/extensions/scratch3_music/assets/instruments/16-vibraphone/72.mp3 +0 -0
  98. package/src/extensions/scratch3_music/assets/instruments/17-music-box/60.mp3 +0 -0
  99. package/src/extensions/scratch3_music/assets/instruments/18-steel-drum/60.mp3 +0 -0
  100. package/src/extensions/scratch3_music/assets/instruments/19-marimba/60.mp3 +0 -0
  101. package/src/extensions/scratch3_music/assets/instruments/2-electric-piano/60.mp3 +0 -0
  102. package/src/extensions/scratch3_music/assets/instruments/20-synth-lead/60.mp3 +0 -0
  103. package/src/extensions/scratch3_music/assets/instruments/21-synth-pad/60.mp3 +0 -0
  104. package/src/extensions/scratch3_music/assets/instruments/3-organ/60.mp3 +0 -0
  105. package/src/extensions/scratch3_music/assets/instruments/4-guitar/60.mp3 +0 -0
  106. package/src/extensions/scratch3_music/assets/instruments/5-electric-guitar/60.mp3 +0 -0
  107. package/src/extensions/scratch3_music/assets/instruments/6-bass/36.mp3 +0 -0
  108. package/src/extensions/scratch3_music/assets/instruments/6-bass/48.mp3 +0 -0
  109. package/src/extensions/scratch3_music/assets/instruments/7-pizzicato/60.mp3 +0 -0
  110. package/src/extensions/scratch3_music/assets/instruments/8-cello/36.mp3 +0 -0
  111. package/src/extensions/scratch3_music/assets/instruments/8-cello/48.mp3 +0 -0
  112. package/src/extensions/scratch3_music/assets/instruments/8-cello/60.mp3 +0 -0
  113. package/src/extensions/scratch3_music/assets/instruments/9-trombone/36.mp3 +0 -0
  114. package/src/extensions/scratch3_music/assets/instruments/9-trombone/48.mp3 +0 -0
  115. package/src/extensions/scratch3_music/assets/instruments/9-trombone/60.mp3 +0 -0
  116. package/src/extensions/scratch3_music/index.js +1333 -0
  117. package/src/extensions/scratch3_music/manifest.js +63 -0
  118. package/src/extensions/scratch3_pen/index.js +770 -0
  119. package/src/extensions/scratch3_speech2text/index.js +700 -0
  120. package/src/extensions/scratch3_text2speech/index.js +766 -0
  121. package/src/extensions/scratch3_translate/index.js +286 -0
  122. package/src/extensions/scratch3_video_sensing/debug.js +13 -0
  123. package/src/extensions/scratch3_video_sensing/index.js +594 -0
  124. package/src/extensions/scratch3_video_sensing/library.js +384 -0
  125. package/src/extensions/scratch3_video_sensing/math.js +76 -0
  126. package/src/extensions/scratch3_video_sensing/view.js +509 -0
  127. package/src/extensions/scratch3_wedo2/index.js +1616 -0
  128. package/src/import/load-costume.js +416 -0
  129. package/src/import/load-sound.js +116 -0
  130. package/src/index.js +10 -0
  131. package/src/io/ble.js +256 -0
  132. package/src/io/bt.js +202 -0
  133. package/src/io/clock.js +39 -0
  134. package/src/io/cloud.js +169 -0
  135. package/src/io/keyboard.js +146 -0
  136. package/src/io/mouse.js +145 -0
  137. package/src/io/mouseWheel.js +28 -0
  138. package/src/io/userData.js +24 -0
  139. package/src/io/video.js +210 -0
  140. package/src/playground/benchmark.css +83 -0
  141. package/src/playground/benchmark.js +753 -0
  142. package/src/playground/index.html +111 -0
  143. package/src/playground/suite.css +78 -0
  144. package/src/playground/suite.html +25 -0
  145. package/src/playground/suite.js +544 -0
  146. package/src/playground/video-sensing.html +18 -0
  147. package/src/playground/video-sensing.js +133 -0
  148. package/src/serialization/deserialize-assets.js +178 -0
  149. package/src/serialization/sb2.js +1295 -0
  150. package/src/serialization/sb2_specmap.js +1818 -0
  151. package/src/serialization/sb3.js +1320 -0
  152. package/src/serialization/serialize-assets.js +60 -0
  153. package/src/sprites/rendered-target.js +1115 -0
  154. package/src/sprites/sprite.js +177 -0
  155. package/src/util/base64-util.js +48 -0
  156. package/src/util/cast.js +218 -0
  157. package/src/util/clone.js +17 -0
  158. package/src/util/color.js +204 -0
  159. package/src/util/fetch-with-timeout.js +53 -0
  160. package/src/util/get-monitor-id.js +33 -0
  161. package/src/util/jsonrpc.js +114 -0
  162. package/src/util/log.js +4 -0
  163. package/src/util/math-util.js +122 -0
  164. package/src/util/maybe-format-message.js +18 -0
  165. package/src/util/new-block-ids.js +33 -0
  166. package/src/util/rateLimiter.js +73 -0
  167. package/src/util/scratch-link-websocket.js +133 -0
  168. package/src/util/string-util.js +94 -0
  169. package/src/util/task-queue.js +203 -0
  170. package/src/util/timer.js +103 -0
  171. package/src/util/uid.js +29 -0
  172. package/src/util/variable-util.js +48 -0
  173. package/src/util/xml-escape.js +33 -0
  174. package/src/virtual-machine.js +1586 -0
  175. package/webpack.config.js +134 -0
@@ -0,0 +1,416 @@
1
+ const StringUtil = require('../util/string-util');
2
+ const log = require('../util/log');
3
+ const {loadSvgString, serializeSvgToString} = require('@scratch/scratch-svg-renderer');
4
+
5
+ const loadVector_ = function (costume, runtime, rotationCenter, optVersion) {
6
+ return new Promise(resolve => {
7
+ let svgString = costume.asset.decodeText();
8
+ // SVG Renderer load fixes "quirks" associated with Scratch 2 projects
9
+ if (optVersion && optVersion === 2) {
10
+ // scratch-svg-renderer fixes syntax that causes loading issues,
11
+ // and if optVersion is 2, fixes "quirks" associated with Scratch 2 SVGs,
12
+ const fixedSvgString = serializeSvgToString(loadSvgString(svgString, true /* fromVersion2 */));
13
+
14
+ // If the string changed, put back into storage
15
+ if (svgString !== fixedSvgString) {
16
+ svgString = fixedSvgString;
17
+ const storage = runtime.storage;
18
+ costume.asset.encodeTextData(fixedSvgString, storage.DataFormat.SVG, true);
19
+ costume.assetId = costume.asset.assetId;
20
+ costume.md5 = `${costume.assetId}.${costume.dataFormat}`;
21
+ }
22
+ }
23
+
24
+ // createSVGSkin does the right thing if rotationCenter isn't provided, so it's okay if it's
25
+ // undefined here
26
+ costume.skinId = runtime.renderer.createSVGSkin(svgString, rotationCenter);
27
+ costume.size = runtime.renderer.getSkinSize(costume.skinId);
28
+ // Now we should have a rotationCenter even if we didn't before
29
+ if (!rotationCenter) {
30
+ rotationCenter = runtime.renderer.getSkinRotationCenter(costume.skinId);
31
+ costume.rotationCenterX = rotationCenter[0];
32
+ costume.rotationCenterY = rotationCenter[1];
33
+ costume.bitmapResolution = 1;
34
+ }
35
+
36
+ resolve(costume);
37
+ });
38
+ };
39
+
40
+ const canvasPool = (function () {
41
+ /**
42
+ * A pool of canvas objects that can be reused to reduce memory
43
+ * allocations. And time spent in those allocations and the later garbage
44
+ * collection.
45
+ */
46
+ class CanvasPool {
47
+ constructor () {
48
+ this.pool = [];
49
+ this.clearSoon = null;
50
+ }
51
+
52
+ /**
53
+ * After a short wait period clear the pool to let the VM collect
54
+ * garbage.
55
+ */
56
+ clear () {
57
+ if (!this.clearSoon) {
58
+ this.clearSoon = new Promise(resolve => setTimeout(resolve, 1000))
59
+ .then(() => {
60
+ this.pool.length = 0;
61
+ this.clearSoon = null;
62
+ });
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Return a canvas. Create the canvas if the pool is empty.
68
+ * @returns {HTMLCanvasElement} A canvas element.
69
+ */
70
+ create () {
71
+ return this.pool.pop() || document.createElement('canvas');
72
+ }
73
+
74
+ /**
75
+ * Release the canvas to be reused.
76
+ * @param {HTMLCanvasElement} canvas A canvas element.
77
+ */
78
+ release (canvas) {
79
+ this.clear();
80
+ this.pool.push(canvas);
81
+ }
82
+ }
83
+
84
+ return new CanvasPool();
85
+ }());
86
+
87
+ /**
88
+ * Return a promise to fetch a bitmap from storage and return it as a canvas
89
+ * If the costume has bitmapResolution 1, it will be converted to bitmapResolution 2 here (the standard for Scratch 3)
90
+ * If the costume has a text layer asset, which is a text part from Scratch 1.4, then this function
91
+ * will merge the two image assets. See the issue LLK/scratch-vm#672 for more information.
92
+ * @param {!object} costume - the Scratch costume object.
93
+ * @param {!Runtime} runtime - Scratch runtime, used to access the v2BitmapAdapter
94
+ * @param {?object} rotationCenter - optionally passed in coordinates for the center of rotation for the image. If
95
+ * none is given, the rotation center of the costume will be set to the middle of the costume later on.
96
+ * @property {number} costume.bitmapResolution - the resolution scale for a bitmap costume.
97
+ * @returns {?Promise} - a promise which will resolve to an object {canvas, rotationCenter, assetMatchesBase},
98
+ * or reject on error.
99
+ * assetMatchesBase is true if the asset matches the base layer; false if it required adjustment
100
+ */
101
+ const fetchBitmapCanvas_ = function (costume, runtime, rotationCenter) {
102
+ if (!costume || !costume.asset) { // TODO: We can probably remove this check...
103
+ // TODO: reject with an Error (breaking API change!)
104
+ // eslint-disable-next-line prefer-promise-reject-errors
105
+ return Promise.reject('Costume load failed. Assets were missing.');
106
+ }
107
+ if (!runtime.v2BitmapAdapter) {
108
+ // TODO: reject with an Error (breaking API change!)
109
+ // eslint-disable-next-line prefer-promise-reject-errors
110
+ return Promise.reject('No V2 Bitmap adapter present.');
111
+ }
112
+
113
+ return Promise.all([costume.asset, costume.textLayerAsset].map(asset => {
114
+ if (!asset) {
115
+ return null;
116
+ }
117
+
118
+ if (typeof createImageBitmap !== 'undefined') {
119
+ return createImageBitmap(
120
+ new Blob([asset.data], {type: asset.assetType.contentType})
121
+ );
122
+ }
123
+
124
+ return new Promise((resolve, reject) => {
125
+ const image = new Image();
126
+ image.onload = function () {
127
+ resolve(image);
128
+ image.onload = null;
129
+ image.onerror = null;
130
+ };
131
+ image.onerror = function () {
132
+ // TODO: reject with an Error (breaking API change!)
133
+ // eslint-disable-next-line prefer-promise-reject-errors
134
+ reject('Costume load failed. Asset could not be read.');
135
+ image.onload = null;
136
+ image.onerror = null;
137
+ };
138
+ image.src = asset.encodeDataURI();
139
+ });
140
+ }))
141
+ .then(([baseImageElement, textImageElement]) => {
142
+ const mergeCanvas = canvasPool.create();
143
+
144
+ const scale = costume.bitmapResolution === 1 ? 2 : 1;
145
+ mergeCanvas.width = baseImageElement.width;
146
+ mergeCanvas.height = baseImageElement.height;
147
+
148
+ const ctx = mergeCanvas.getContext('2d');
149
+ ctx.drawImage(baseImageElement, 0, 0);
150
+ if (textImageElement) {
151
+ ctx.drawImage(textImageElement, 0, 0);
152
+ }
153
+ // Track the canvas we merged the bitmaps onto separately from the
154
+ // canvas that we receive from resize if scale is not 1. We know
155
+ // resize treats mergeCanvas as read only data. We don't know when
156
+ // resize may use or modify the canvas. So we'll only release the
157
+ // mergeCanvas back into the canvas pool. Reusing the canvas from
158
+ // resize may cause errors.
159
+ let canvas = mergeCanvas;
160
+ if (scale !== 1) {
161
+ canvas = runtime.v2BitmapAdapter.resize(mergeCanvas, canvas.width * scale, canvas.height * scale);
162
+ }
163
+
164
+ // By scaling, we've converted it to bitmap resolution 2
165
+ if (rotationCenter) {
166
+ rotationCenter[0] = rotationCenter[0] * scale;
167
+ rotationCenter[1] = rotationCenter[1] * scale;
168
+ costume.rotationCenterX = rotationCenter[0];
169
+ costume.rotationCenterY = rotationCenter[1];
170
+ }
171
+ costume.bitmapResolution = 2;
172
+
173
+ // Clean up the costume object
174
+ delete costume.textLayerMD5;
175
+ delete costume.textLayerAsset;
176
+
177
+ return {
178
+ canvas,
179
+ mergeCanvas,
180
+ rotationCenter,
181
+ // True if the asset matches the base layer; false if it required adjustment
182
+ assetMatchesBase: scale === 1 && !textImageElement
183
+ };
184
+ })
185
+ .finally(() => {
186
+ // Clean up the text layer properties if it fails to load
187
+ delete costume.textLayerMD5;
188
+ delete costume.textLayerAsset;
189
+ });
190
+ };
191
+
192
+ const loadBitmap_ = function (costume, runtime, _rotationCenter) {
193
+ return fetchBitmapCanvas_(costume, runtime, _rotationCenter)
194
+ .then(fetched => {
195
+ const updateCostumeAsset = function (dataURI) {
196
+ if (!runtime.v2BitmapAdapter) {
197
+ // TODO: This might be a bad practice since the returned
198
+ // promise isn't acted on. If this is something we should be
199
+ // creating a rejected promise for we should also catch it
200
+ // somewhere and act on that error (like logging).
201
+ //
202
+ // Return a rejection to stop executing updateCostumeAsset.
203
+ // TODO: reject with an Error (breaking API change!)
204
+ // eslint-disable-next-line prefer-promise-reject-errors
205
+ return Promise.reject('No V2 Bitmap adapter present.');
206
+ }
207
+
208
+ const storage = runtime.storage;
209
+ costume.asset = storage.createAsset(
210
+ storage.AssetType.ImageBitmap,
211
+ storage.DataFormat.PNG,
212
+ runtime.v2BitmapAdapter.convertDataURIToBinary(dataURI),
213
+ null,
214
+ true // generate md5
215
+ );
216
+ costume.dataFormat = storage.DataFormat.PNG;
217
+ costume.assetId = costume.asset.assetId;
218
+ costume.md5 = `${costume.assetId}.${costume.dataFormat}`;
219
+ };
220
+
221
+ if (!fetched.assetMatchesBase) {
222
+ updateCostumeAsset(fetched.canvas.toDataURL());
223
+ }
224
+
225
+ return fetched;
226
+ })
227
+ .then(({canvas, mergeCanvas, rotationCenter}) => {
228
+ // createBitmapSkin does the right thing if costume.rotationCenter is undefined.
229
+ // That will be the case if you upload a bitmap asset or create one by taking a photo.
230
+ let center;
231
+ if (rotationCenter) {
232
+ // fetchBitmapCanvas will ensure that the costume's bitmap resolution is 2 and its rotation center is
233
+ // scaled to match, so it's okay to always divide by 2.
234
+ center = [
235
+ rotationCenter[0] / 2,
236
+ rotationCenter[1] / 2
237
+ ];
238
+ }
239
+
240
+ // TODO: costume.bitmapResolution will always be 2 at this point because of fetchBitmapCanvas_, so we don't
241
+ // need to pass it in here.
242
+ costume.skinId = runtime.renderer.createBitmapSkin(canvas, costume.bitmapResolution, center);
243
+ canvasPool.release(mergeCanvas);
244
+ const renderSize = runtime.renderer.getSkinSize(costume.skinId);
245
+ costume.size = [renderSize[0] * 2, renderSize[1] * 2]; // Actual size, since all bitmaps are resolution 2
246
+
247
+ if (!rotationCenter) {
248
+ rotationCenter = runtime.renderer.getSkinRotationCenter(costume.skinId);
249
+ // Actual rotation center, since all bitmaps are resolution 2
250
+ costume.rotationCenterX = rotationCenter[0] * 2;
251
+ costume.rotationCenterY = rotationCenter[1] * 2;
252
+ costume.bitmapResolution = 2;
253
+ }
254
+ return costume;
255
+ });
256
+ };
257
+
258
+ // Handle all manner of costume errors with a Gray Question Mark (default costume)
259
+ // and preserve as much of the original costume data as possible
260
+ // Returns a promise of a costume
261
+ const handleCostumeLoadError = function (costume, runtime) {
262
+ // Keep track of the old asset information until we're done loading the default costume
263
+ const oldAsset = costume.asset; // could be null
264
+ const oldAssetId = costume.assetId;
265
+ const oldRotationX = costume.rotationCenterX;
266
+ const oldRotationY = costume.rotationCenterY;
267
+ const oldBitmapResolution = costume.bitmapResolution;
268
+ const oldDataFormat = costume.dataFormat;
269
+
270
+ const AssetType = runtime.storage.AssetType;
271
+ const isVector = costume.dataFormat === AssetType.ImageVector.runtimeFormat;
272
+
273
+ // Use default asset if original fails to load
274
+ costume.assetId = isVector ?
275
+ runtime.storage.defaultAssetId.ImageVector :
276
+ runtime.storage.defaultAssetId.ImageBitmap;
277
+ costume.asset = runtime.storage.get(costume.assetId);
278
+ costume.md5 = `${costume.assetId}.${costume.asset.dataFormat}`;
279
+
280
+ const defaultCostumePromise = (isVector) ?
281
+ loadVector_(costume, runtime) : loadBitmap_(costume, runtime);
282
+
283
+ return defaultCostumePromise.then(loadedCostume => {
284
+ loadedCostume.broken = {};
285
+ loadedCostume.broken.assetId = oldAssetId;
286
+ loadedCostume.broken.md5 = `${oldAssetId}.${oldDataFormat}`;
287
+
288
+ // Should be null if we got here because the costume was missing
289
+ loadedCostume.broken.asset = oldAsset;
290
+ loadedCostume.broken.dataFormat = oldDataFormat;
291
+
292
+ loadedCostume.broken.rotationCenterX = oldRotationX;
293
+ loadedCostume.broken.rotationCenterY = oldRotationY;
294
+ loadedCostume.broken.bitmapResolution = oldBitmapResolution;
295
+ return loadedCostume;
296
+ });
297
+ };
298
+
299
+ /**
300
+ * Initialize a costume from an asset asynchronously.
301
+ * Do not call this unless there is a renderer attached.
302
+ * @param {!object} costume - the Scratch costume object.
303
+ * @property {int} skinId - the ID of the costume's render skin, once installed.
304
+ * @property {number} rotationCenterX - the X component of the costume's origin.
305
+ * @property {number} rotationCenterY - the Y component of the costume's origin.
306
+ * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume.
307
+ * @property {!Asset} costume.asset - the asset of the costume loaded from storage.
308
+ * @param {!Runtime} runtime - Scratch runtime, used to access the storage module.
309
+ * @param {?int} optVersion - Version of Scratch that the costume comes from. If this is set
310
+ * to 2, scratch 3 will perform an upgrade step to handle quirks in SVGs from Scratch 2.0.
311
+ * @returns {?Promise} - a promise which will resolve after skinId is set, or null on error.
312
+ */
313
+ const loadCostumeFromAsset = function (costume, runtime, optVersion) {
314
+ costume.assetId = costume.asset.assetId;
315
+ const renderer = runtime.renderer;
316
+ if (!renderer) {
317
+ log.warn('No rendering module present; cannot load costume: ', costume.name);
318
+ return Promise.resolve(costume);
319
+ }
320
+ const AssetType = runtime.storage.AssetType;
321
+ let rotationCenter;
322
+ // Use provided rotation center and resolution if they are defined. Bitmap resolution
323
+ // should only ever be 1 or 2.
324
+ if (typeof costume.rotationCenterX === 'number' && !isNaN(costume.rotationCenterX) &&
325
+ typeof costume.rotationCenterY === 'number' && !isNaN(costume.rotationCenterY)) {
326
+ rotationCenter = [costume.rotationCenterX, costume.rotationCenterY];
327
+ }
328
+ if (costume.asset.assetType.runtimeFormat === AssetType.ImageVector.runtimeFormat) {
329
+ return loadVector_(costume, runtime, rotationCenter, optVersion)
330
+ .catch(error => {
331
+ log.warn(`Error loading vector image: ${error}`);
332
+ return handleCostumeLoadError(costume, runtime);
333
+
334
+ });
335
+ }
336
+ return loadBitmap_(costume, runtime, rotationCenter, optVersion)
337
+ .catch(error => {
338
+ log.warn(`Error loading bitmap image: ${error}`);
339
+ return handleCostumeLoadError(costume, runtime);
340
+ });
341
+ };
342
+
343
+
344
+ /**
345
+ * Load a costume's asset into memory asynchronously.
346
+ * Do not call this unless there is a renderer attached.
347
+ * @param {!string} md5ext - the MD5 and extension of the costume to be loaded.
348
+ * @param {!object} costume - the Scratch costume object.
349
+ * @property {int} skinId - the ID of the costume's render skin, once installed.
350
+ * @property {number} rotationCenterX - the X component of the costume's origin.
351
+ * @property {number} rotationCenterY - the Y component of the costume's origin.
352
+ * @property {number} [bitmapResolution] - the resolution scale for a bitmap costume.
353
+ * @param {!Runtime} runtime - Scratch runtime, used to access the storage module.
354
+ * @param {?int} optVersion - Version of Scratch that the costume comes from. If this is set
355
+ * to 2, scratch 3 will perform an upgrade step to handle quirks in SVGs from Scratch 2.0.
356
+ * @returns {?Promise} - a promise which will resolve after skinId is set, or null on error.
357
+ */
358
+ const loadCostume = function (md5ext, costume, runtime, optVersion) {
359
+ const idParts = StringUtil.splitFirst(md5ext, '.');
360
+ const md5 = idParts[0];
361
+ const ext = idParts[1].toLowerCase();
362
+ costume.dataFormat = ext;
363
+
364
+ if (costume.asset) {
365
+ // Costume comes with asset. It could be coming from image upload, drag and drop, or file
366
+ return loadCostumeFromAsset(costume, runtime, optVersion);
367
+ }
368
+
369
+ // Need to load the costume from storage. The server should have a reference to this md5.
370
+ if (!runtime.storage) {
371
+ log.warn('No storage module present; cannot load costume asset: ', md5ext);
372
+ return Promise.resolve(costume);
373
+ }
374
+
375
+ if (!runtime.storage.defaultAssetId) {
376
+ log.warn(`No default assets found`);
377
+ return Promise.resolve(costume);
378
+ }
379
+
380
+ const AssetType = runtime.storage.AssetType;
381
+ const assetType = (ext === 'svg') ? AssetType.ImageVector : AssetType.ImageBitmap;
382
+
383
+ const costumePromise = runtime.storage.load(assetType, md5, ext);
384
+
385
+ let textLayerPromise;
386
+ if (costume.textLayerMD5) {
387
+ textLayerPromise = runtime.storage.load(AssetType.ImageBitmap, costume.textLayerMD5, 'png');
388
+ } else {
389
+ textLayerPromise = Promise.resolve(null);
390
+ }
391
+
392
+ return Promise.all([costumePromise, textLayerPromise])
393
+ .then(assetArray => {
394
+ if (assetArray[0]) {
395
+ costume.asset = assetArray[0];
396
+ } else {
397
+ return handleCostumeLoadError(costume, runtime);
398
+ }
399
+
400
+ if (assetArray[1]) {
401
+ costume.textLayerAsset = assetArray[1];
402
+ }
403
+ return loadCostumeFromAsset(costume, runtime, optVersion);
404
+ })
405
+ .catch(error => {
406
+ // Handle case where storage.load rejects with errors
407
+ // instead of resolving null
408
+ log.warn('Error loading costume: ', error);
409
+ return handleCostumeLoadError(costume, runtime);
410
+ });
411
+ };
412
+
413
+ module.exports = {
414
+ loadCostume,
415
+ loadCostumeFromAsset
416
+ };
@@ -0,0 +1,116 @@
1
+ const StringUtil = require('../util/string-util');
2
+ const log = require('../util/log');
3
+
4
+ /**
5
+ * Initialize a sound from an asset asynchronously.
6
+ * @param {!object} sound - the Scratch sound object.
7
+ * @property {string} md5 - the MD5 and extension of the sound to be loaded.
8
+ * @property {Buffer} data - sound data will be written here once loaded.
9
+ * @param {!Asset} soundAsset - the asset loaded from storage.
10
+ * @param {!Runtime} runtime - Scratch runtime, used to access the storage module.
11
+ * @param {SoundBank} soundBank - Scratch Audio SoundBank to add sounds to.
12
+ * @returns {!Promise} - a promise which will resolve to the sound when ready.
13
+ */
14
+ const loadSoundFromAsset = function (sound, soundAsset, runtime, soundBank) {
15
+ sound.assetId = soundAsset.assetId;
16
+ if (!runtime.audioEngine) {
17
+ log.warn('No audio engine present; cannot load sound asset: ', sound.md5);
18
+ return Promise.resolve(sound);
19
+ }
20
+ return runtime.audioEngine.decodeSoundPlayer(Object.assign(
21
+ {},
22
+ sound,
23
+ {data: soundAsset.data}
24
+ )).then(soundPlayer => {
25
+ sound.soundId = soundPlayer.id;
26
+ // Set the sound sample rate and sample count based on the
27
+ // the audio buffer from the audio engine since the sound
28
+ // gets resampled by the audio engine
29
+ const soundBuffer = soundPlayer.buffer;
30
+ sound.rate = soundBuffer.sampleRate;
31
+ sound.sampleCount = soundBuffer.length;
32
+
33
+ if (soundBank !== null) {
34
+ soundBank.addSoundPlayer(soundPlayer);
35
+ }
36
+
37
+ return sound;
38
+ });
39
+ };
40
+
41
+ // Handle sound loading errors by replacing the runtime sound with the
42
+ // default sound from storage, but keeping track of the original sound metadata
43
+ // in a `broken` field
44
+ const handleSoundLoadError = function (sound, runtime, soundBank) {
45
+ // Keep track of the old asset information until we're done loading the default sound
46
+ const oldAsset = sound.asset; // could be null
47
+ const oldAssetId = sound.assetId;
48
+ const oldSample = sound.sampleCount;
49
+ const oldRate = sound.rate;
50
+ const oldFormat = sound.format;
51
+ const oldDataFormat = sound.dataFormat;
52
+
53
+ // Use default asset if original fails to load
54
+ sound.assetId = runtime.storage.defaultAssetId.Sound;
55
+ sound.asset = runtime.storage.get(sound.assetId);
56
+ sound.md5 = `${sound.assetId}.${sound.asset.dataFormat}`;
57
+
58
+ return loadSoundFromAsset(sound, sound.asset, runtime, soundBank).then(loadedSound => {
59
+ loadedSound.broken = {};
60
+ loadedSound.broken.assetId = oldAssetId;
61
+ loadedSound.broken.md5 = `${oldAssetId}.${oldDataFormat}`;
62
+
63
+ // Should be null if we got here because the sound was missing
64
+ loadedSound.broken.asset = oldAsset;
65
+
66
+ loadedSound.broken.sampleCount = oldSample;
67
+ loadedSound.broken.rate = oldRate;
68
+ loadedSound.broken.format = oldFormat;
69
+ loadedSound.broken.dataFormat = oldDataFormat;
70
+
71
+ return loadedSound;
72
+ });
73
+ };
74
+
75
+ /**
76
+ * Load a sound's asset into memory asynchronously.
77
+ * @param {!object} sound - the Scratch sound object.
78
+ * @property {string} md5 - the MD5 and extension of the sound to be loaded.
79
+ * @property {Buffer} data - sound data will be written here once loaded.
80
+ * @param {!Runtime} runtime - Scratch runtime, used to access the storage module.
81
+ * @param {SoundBank} soundBank - Scratch Audio SoundBank to add sounds to.
82
+ * @returns {!Promise} - a promise which will resolve to the sound when ready.
83
+ */
84
+ const loadSound = function (sound, runtime, soundBank) {
85
+ if (!runtime.storage) {
86
+ log.warn('No storage module present; cannot load sound asset: ', sound.md5);
87
+ return Promise.resolve(sound);
88
+ }
89
+ const idParts = StringUtil.splitFirst(sound.md5, '.');
90
+ const md5 = idParts[0];
91
+ const ext = idParts[1].toLowerCase();
92
+ sound.dataFormat = ext;
93
+ return (
94
+ (sound.asset && Promise.resolve(sound.asset)) ||
95
+ runtime.storage.load(runtime.storage.AssetType.Sound, md5, ext)
96
+ )
97
+ .then(soundAsset => {
98
+ sound.asset = soundAsset;
99
+
100
+ if (!soundAsset) {
101
+ log.warn('Failed to find sound data: ', sound.md5);
102
+ return handleSoundLoadError(sound, runtime, soundBank);
103
+ }
104
+
105
+ return loadSoundFromAsset(sound, soundAsset, runtime, soundBank);
106
+ })
107
+ .catch(e => {
108
+ log.warn(`Failed to load sound: ${sound.md5} with error: ${e}`);
109
+ return handleSoundLoadError(sound, runtime, soundBank);
110
+ });
111
+ };
112
+
113
+ module.exports = {
114
+ loadSound,
115
+ loadSoundFromAsset
116
+ };
package/src/index.js ADDED
@@ -0,0 +1,10 @@
1
+ const VirtualMachine = require('./virtual-machine');
2
+
3
+ const ArgumentType = require('./extension-support/argument-type');
4
+ const BlockType = require('./extension-support/block-type');
5
+
6
+ module.exports = VirtualMachine;
7
+
8
+ // TODO: ESM named exports will save us all
9
+ module.exports.ArgumentType = ArgumentType;
10
+ module.exports.BlockType = BlockType;