-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtext2.js
More file actions
854 lines (755 loc) · 29.9 KB
/
text2.js
File metadata and controls
854 lines (755 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
(function (Scratch) {
'use strict';
// This extension was created by making projects with https://lab.scratch.mit.edu/text/
// To determine block and argument IDs, we extracted project.json and examined the result.
// To determine block behaviors we simply experiment with Scratch Labs and made sure our
// blocks do the same things.
// This extension's code is not based on the source code of Scratch Labs.
// by @LukeManiaStudios
const blockIconURI = 'data:image/svg+xml;,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22284.242%22%20height%3D%22284.242%22%3E%3Cg%20fill-rule%3D%22evenodd%22%20stroke-miterlimit%3D%2210%22%20data-paper-data%3D%22%7B%26quot%3BisPaintingLayer%26quot%3B%3Atrue%7D%22%20style%3D%22mix-blend-mode%3Anormal%22%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M188.894%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.48%209.888a1671.47%201671.47%200%200%200-4.174%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.83%20522.83%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.329%20157.508H225.43l-9.636-26.111h-54.08l-9.636%2026.11h-43.432l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22%2396f%22%20stroke%3D%22%237240d6%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%2229%22%20d%3D%22M188.894%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.48%209.888a1671.47%201671.47%200%200%200-4.174%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.83%20522.83%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.329%20157.508H225.43l-9.636-26.111h-54.08l-9.636%2026.11h-43.432l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M188.894%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.48%209.888a1671.47%201671.47%200%200%200-4.174%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.302%20408.302%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.329%20157.508H225.43l-9.636-26.111h-54.08l-9.636%2026.11h-43.432l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22%23ffa24d%22%20stroke%3D%22%23fff%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%229%22%20d%3D%22M188.894%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.48%209.888a1671.47%201671.47%200%200%200-4.174%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.302%20408.302%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.329%20157.508H225.43l-9.636-26.111h-54.08l-9.636%2026.11h-43.432l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M143.696%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888a1671.47%201671.47%200%200%200-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.33%20157.508h-44.312l-9.637-26.111h-54.08l-9.636%2026.11H63.448l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22%2396f%22%20stroke%3D%22%237240d6%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%2229%22%20d%3D%22M143.696%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888a1671.47%201671.47%200%200%200-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.33%20157.508h-44.312l-9.637-26.111h-54.08l-9.636%2026.11H63.448l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M143.696%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888a1671.47%201671.47%200%200%200-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.33%20157.508h-44.312l-9.637-26.111h-54.08l-9.636%2026.11H63.448l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22%23ff774d%22%20stroke%3D%22%23fff%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%229%22%20d%3D%22M143.696%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888a1671.47%201671.47%200%200%200-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.827%20522.827%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.519-56.092%2062.33%20157.508h-44.312l-9.637-26.111h-54.08l-9.636%2026.11H63.448l62.768-157.507Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M94.748%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888-1.27%203.442-2.66%207.263-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.885%20522.885%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.52-56.092%2062.328%20157.508h-44.311l-9.637-26.111h-54.08l-9.635%2026.11H14.5L77.269%2063.368Z%22%2F%3E%3Cpath%20fill%3D%22%2396f%22%20stroke%3D%22%237240d6%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%2229%22%20d%3D%22M94.748%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888-1.27%203.442-2.66%207.263-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.885%20522.885%200%200%201-4.065-11.242%20408.343%20408.343%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.52-56.092%2062.328%20157.508h-44.311l-9.637-26.111h-54.08l-9.635%2026.11H14.5L77.269%2063.368Z%22%2F%3E%3Cpath%20fill%3D%22none%22%20d%3D%22M94.748%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888-1.27%203.442-2.66%207.263-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.885%20522.885%200%200%201-4.065-11.242%20408.302%20408.302%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.52-56.092%2062.328%20157.508h-44.311l-9.637-26.111h-54.08l-9.635%2026.11H14.5L77.269%2063.368Z%22%2F%3E%3Cpath%20fill%3D%22%23ff4c4c%22%20stroke%3D%22%23fff%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%229%22%20d%3D%22M94.748%20119.459c-.706%202.378-1.43%204.69-2.172%206.933-1.05%203.15-2.21%206.445-3.479%209.888-1.27%203.442-2.66%207.263-4.175%2011.462l-5.73%2015.528h30.833l-5.73-15.528a522.885%20522.885%200%200%201-4.065-11.242%20408.302%20408.302%200%200%201-3.37-10.108%20350.767%20350.767%200%200%201-2.112-6.933zm18.52-56.092%2062.328%20157.508h-44.311l-9.637-26.111h-54.08l-9.635%2026.11H14.5L77.269%2063.368Z%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E';
const CUSTOM_STATE_KEY = Symbol();
const ALIGN_LEFT = 0;
const ALIGN_RIGHT = 1;
const ALIGN_CENTER = 2;
const vm = Scratch.vm;
const renderer = vm.renderer;
const gl = renderer.gl;
const NATIVE_FONTS = [
'Sans Serif',
'Serif',
'Handwriting',
'Marker',
'Curly',
'Pixel',
];
const DEFAULT_COLOR = '#575e75';
const DEFAULT_FONT = 'Handwriting';
const DEFAULT_WIDTH = vm.runtime.stageWidth;
const DEFAULT_ALIGN = ALIGN_CENTER;
const DEFAULT_FONT_SIZE = 24;
const TYPE_DELAY = 1000 / 15;
const RAINBOW_TIME_PER = 1000;
const RAINBOW_DURATION = 2000;
const ZOOM_DURATION = 500;
let globalFrameTime = 0;
/**
* @typedef TextState
* @property {TextCostumeSkin} skin
*/
// temporary
if (!renderer.exports || !renderer.exports.Skin || !vm.exports) {
alert('VM is too old for animated text extension');
throw new Error('VM is too old');
}
const Skin = renderer.exports.Skin;
const CanvasMeasurementProvider = renderer.exports.CanvasMeasurementProvider;
const twgl = renderer.exports.twgl;
const RenderedTarget = vm.exports.RenderedTarget;
/**
* @param {number} c
* @returns {string}
*/
const formatComponent = (c) => Math.round(c).toString(16).padStart(2, '0');
/**
* @param {[number, number, number]} color
* @returns {string}
*/
const formatColor = (color) => `#${formatComponent(color[0])}${formatComponent(color[1])}${formatComponent(color[2])}`;
/**
* @param {number} h hue from 0-1
* @param {number} s saturation from 0-1
* @param {number} v value from 0-1
* @returns {[number, number, number]} RGB channels from 0-255
*/
const hsvToRGB = (h, s, v) => {
// https://en.wikipedia.org/wiki/HSL_and_HSV
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [r * 255 | 0, g * 255 | 0, b * 255 | 0];
};
/**
* @param {CanvasGradient} gradient
* @param {number} offset number of cycles to offset by
*/
const addRainbowStops = (gradient, offset) => {
const NUMBER_STOPS = 20;
for (let i = 0; i < NUMBER_STOPS; i++) {
const exactPosition = i / NUMBER_STOPS;
let offsetPosition = (exactPosition - offset) % 1;
if (offsetPosition < 0) {
offsetPosition += 1;
}
const rgb = hsvToRGB(offsetPosition, 1, 1);
gradient.addColorStop(exactPosition, formatColor(rgb));
}
};
class TextCostumeSkin extends Skin {
constructor(id, drawable) {
super(id, renderer);
/** @type {RenderWebGL.Drawable} */
this.drawable = drawable;
/** @type {number} */
this._previousDrawableXScale = 100;
this.canvas = document.createElement('canvas');
this.canvas.width = 0;
this.canvas.height = 0;
this.ctx = this.canvas.getContext('2d');
this.text = '';
this.color = DEFAULT_COLOR;
this.textWidth = DEFAULT_WIDTH;
this.fontFamily = DEFAULT_FONT;
this.baseFontSize = DEFAULT_FONT_SIZE;
this.align = DEFAULT_ALIGN;
/** @type {Array<{text: string; width: number;}>} */
this.lines = [];
/** @type {[number, number]} */
this._size = [0, 0];
/** @type {[number, number]} */
this._rotationCenter = [0, 0];
// Updated in _updateFontDimensions
this.calculatedFontSize = 0;
this.lineHeight = 0;
this.verticalPadding = 0;
this.wrapWidth = 0;
this._textDirty = false;
this._textureDirty = false;
this._renderedAtScale = 1;
this._renderTime = 0;
this._reflowTime = 0;
this.typeAnimationInterval = null;
this.isRainbow = false;
this.rainbowStartTime = 0;
this.rainbowTimeout = null;
this.isZooming = false;
this.zoomStartTime = 0;
this.zoomTimeout = null;
/** @type {(() => void)|null} */
this.resolveOngoingAnimation = null;
}
// Part of Skin API
dispose() {
if (this._texture) {
gl.deleteTexture(this._texture);
this._texture = null;
}
this.canvas = null;
this.ctx = null;
super.dispose();
}
// Part of Skin API
get size() {
if (this._needsReflow()) {
this._reflowText();
}
return this._size;
}
// Part of Skin API
useNearest() {
return false;
}
_needsReflow() {
return (
this._textDirty ||
(this.isZooming && this._reflowTime !== globalFrameTime) ||
this._previousDrawableXScale !== Math.abs(this.drawable.scale[0])
);
}
_updateFontDimensions() {
this.calculatedFontSize = this.baseFontSize;
if (this.isZooming) {
// TODO: it looks like Scratch's animation always starts at least a little visible
const time = globalFrameTime - this.zoomStartTime;
const progress = Math.max(0, Math.min(1, time / ZOOM_DURATION));
this.calculatedFontSize *= progress;
}
this.lineHeight = this.baseFontSize * 8 / 7;
// Always use the base size for padding. This makes the zoom animation look better.
this.verticalPadding = this.baseFontSize / 7;
// Only use horizontal scale for wrap width for compatibility with stretch extension.
this.wrapWidth = this.textWidth / (Math.abs(this.drawable.scale[0]) / 100);
}
_getFontStyle() {
return `${this.calculatedFontSize}px "${this.fontFamily}", sans-serif`;
}
_reflowText() {
this._textDirty = false;
this._textureDirty = true;
this._reflowTime = globalFrameTime;
this._previousDrawableXScale = Math.abs(this.drawable.scale[0]);
this._updateFontDimensions();
this.ctx.font = this._getFontStyle();
// need to make new ones each time to avoid caching incorrectly across fonts
const measurementProvider = new CanvasMeasurementProvider(this.ctx);
/** @type {RenderWebGL.TextWrapper} */
const textWrapper = renderer.createTextWrapper(measurementProvider);
const lines = textWrapper.wrapText(this.wrapWidth, this.text);
this.lines = lines.map(line => {
const trimmed = line.trimEnd();
return {
text: trimmed,
width: measurementProvider.measureText(trimmed)
};
});
this._size[0] = this.wrapWidth;
this._size[1] = this.lines.length * this.lineHeight + 2 * this.verticalPadding;
// Centered horizontally
this._rotationCenter[0] = this._size[0] / 2;
// Vertical center is roughly below the first line of text
this._rotationCenter[1] = this.calculatedFontSize * 0.9 + this.verticalPadding;
}
_renderAtScale(requestedScale) {
this._renderedAtScale = requestedScale;
this._textureDirty = false;
this._renderTime = globalFrameTime;
const scratchWidth = this._size[0];
const scratchHeight = this._size[1];
// Renderer's requested scale is accounted for at this point. Do not touch `requestedScale`
// ever after this point.
this.canvas.width = Math.ceil(scratchWidth * requestedScale);
this.canvas.height = Math.ceil(scratchHeight * requestedScale);
this.ctx.scale(requestedScale, requestedScale);
const rainbowOffset = this.isRainbow ? (globalFrameTime - this.rainbowStartTime) / RAINBOW_TIME_PER : 0;
this.ctx.fillStyle = this.color;
this.ctx.font = this._getFontStyle();
for (let i = 0; i < this.lines.length; i++) {
const line = this.lines[i];
const text = line.text;
const lineWidth = line.width;
let xOffset = 0;
if (this.align === ALIGN_LEFT) {
// already correct
} else if (this.align === ALIGN_CENTER) {
xOffset = (this.wrapWidth - lineWidth) / 2;
} else {
xOffset = this.wrapWidth - lineWidth;
}
if (this.isRainbow) {
const gradient = this.ctx.createLinearGradient(xOffset, 0, xOffset + lineWidth, 0);
addRainbowStops(gradient, rainbowOffset);
this.ctx.fillStyle = gradient;
}
// TODO: something here is wrong
this.ctx.fillText(
text,
xOffset,
this.verticalPadding + i * this.lineHeight + this.baseFontSize
);
}
if (!this._texture) {
// @ts-expect-error - twgl not typed yet
this._texture = twgl.createTexture(gl, {
auto: false,
wrap: gl.CLAMP_TO_EDGE
});
}
this._setTexture(this.canvas);
}
_invalidateTexture() {
this._textureDirty = true;
this._renderTime = 0;
this.emitWasAltered();
}
_invalidateText() {
this._textDirty = true;
this._textureDirty = true;
this._reflowTime = 0;
this.emitWasAltered();
}
setText(text) {
if (text !== this.text) {
this.text = text;
this._invalidateText();
}
}
setColor(color) {
if (color !== this.color) {
this.color = color;
this._invalidateTexture();
}
}
setAlign(align) {
if (align !== this.align) {
this.align = align;
this._invalidateTexture();
}
}
setWidth(width) {
if (width !== this.textWidth) {
this.textWidth = width;
this._invalidateText();
}
}
setFontFamily(font) {
if (font !== this.fontFamily) {
this.fontFamily = font;
this._invalidateText();
}
}
getFontFamily() {
return this.fontFamily;
}
getColor() {
return this.color;
}
getWidth() {
return this.textWidth;
}
_oneAnimationAtATime(newCallback) {
this.cancelAnimation();
return new Promise(resolve => {
this.resolveOngoingAnimation = () => {
this.resolveOngoingAnimation = null;
resolve();
};
newCallback(this.resolveOngoingAnimation);
});
}
startTypeAnimation() {
return this._oneAnimationAtATime(resolve => {
const originalText = this.text;
let i = 1;
const update = () => {
this.setText(originalText.substring(0, i));
};
update();
this.typeAnimationInterval = setInterval(() => {
i++;
update();
if (i >= originalText.length) {
clearInterval(this.typeAnimationInterval);
resolve();
}
}, TYPE_DELAY);
});
}
startRainbowAnimation() {
return this._oneAnimationAtATime(resolve => {
this.isRainbow = true;
this.rainbowStartTime = Date.now();
this._invalidateTexture();
this.rainbowTimeout = setTimeout(() => {
this.isRainbow = false;
resolve();
this._invalidateTexture();
}, RAINBOW_DURATION);
});
}
startZoomAnimation() {
return this._oneAnimationAtATime(resolve => {
this.isZooming = true;
this.zoomStartTime = Date.now();
this._invalidateText();
this.zoomTimeout = setTimeout(() => {
this.isZooming = false;
resolve();
this._invalidateText();
}, ZOOM_DURATION);
});
}
cancelAnimation() {
if (this.resolveOngoingAnimation) {
this.resolveOngoingAnimation();
this.resolveOngoingAnimation = null;
clearInterval(this.typeAnimationInterval);
this.isRainbow = false;
clearTimeout(this.rainbowTimeout);
this.isZooming = false;
clearTimeout(this.zoomTimeout);
// TODO: sometimes we only need to invalidate the texture at this point
this._invalidateText();
}
}
// Part of Skin API
updateSilhouette(scale) {
this.getTexture(scale);
this._silhouette.unlazy();
}
// Part of Skin API
getTexture(scale) {
const MAX_SCALE = 10;
const upperScale = scale ? Math.max(Math.abs(scale[0]), Math.abs(scale[1])) : 100;
const calculatedScale = Math.min(MAX_SCALE, upperScale / 100);
if (this._needsReflow()) {
this._reflowText();
}
if (
this._textureDirty ||
(this.isRainbow && this._renderTime !== globalFrameTime) ||
calculatedScale !== this._renderedAtScale
) {
this._renderAtScale(calculatedScale);
}
return this._texture;
}
}
/**
* Note that the returned skin is only usable by the given target. Things will break if another
* target tries to use it.
* @param {VM.Target} target
* @returns {TextCostumeSkin}
*/
const createTextCostumeSkin = (target) => {
const drawable = renderer._allDrawables[target.drawableID];
const id = renderer._nextSkinId++;
const skin = new TextCostumeSkin(id, drawable);
renderer._allSkins[id] = skin;
return skin;
};
vm.runtime.on('BEFORE_EXECUTE', () => {
globalFrameTime = Date.now();
for (let i = 0; i < renderer._allSkins.length; i++) {
const skin = renderer._allSkins[i];
if (skin instanceof TextCostumeSkin && (skin.isRainbow || skin.isZooming)) {
skin.emitWasAltered();
}
}
});
class AnimatedText {
constructor() {
vm.runtime.on('PROJECT_START', () => {
this._hideAllText();
});
vm.runtime.on('PROJECT_STOP_ALL', () => {
this._hideAllText();
});
// targetWasCreated does not work because it runs before the Drawable is set up
const extension = this;
const originalMakeClone = RenderedTarget.prototype.makeClone;
RenderedTarget.prototype.makeClone = function () {
const newClone = originalMakeClone.call(this);
if (extension._hasState(this)) {
// TODO: creates much unneeded state
const originalSkin = extension._getState(this).skin;
const newSkin = extension._getState(newClone).skin;
newSkin.setAlign(originalSkin.align);
newSkin.setColor(originalSkin.color);
newSkin.setFontFamily(originalSkin.fontFamily);
newSkin.setWidth(originalSkin.textWidth);
newSkin.setText(originalSkin.text);
if (renderer._allDrawables[this.drawableID].skin instanceof TextCostumeSkin) {
renderer.updateDrawableSkinId(newClone.drawableID, newSkin.id);
}
}
return newClone;
};
vm.runtime.on('targetWasRemoved', (target) => {
if (this._hasState(target)) {
const state = this._getState(target);
renderer.destroySkin(state.skin.id);
}
});
}
getInfo() {
return {
id: 'text2',
name: 'Animated Text',
blockIconURI: blockIconURI,
blocks: [
{
"opcode": "setText",
"blockType": Scratch.BlockType.COMMAND,
"text": "显示文本 [TEXT]",
"arguments": {
"TEXT": {
"type": Scratch.ArgumentType.STRING,
"defaultValue": "欢迎来到我的项目!"
}
}
},
{
"opcode": "animateText",
"blockType": Scratch.BlockType.COMMAND,
"text": "[ANIMATE] 文本 [TEXT]",
"arguments": {
"ANIMATE": {
"type": Scratch.ArgumentType.STRING,
"menu": "animate",
"defaultValue": "rainbow"
},
"TEXT": {
"type": Scratch.ArgumentType.STRING,
"defaultValue": "开始吧!"
}
}
},
{
"opcode": "clearText",
"blockType": Scratch.BlockType.COMMAND,
"text": "显示角色"
},
"---",
{
"opcode": "setFont",
"blockType": Scratch.BlockType.COMMAND,
"text": "将字体设为 [FONT]",
"arguments": {
"FONT": {
"type": Scratch.ArgumentType.STRING,
"menu": "font"
}
}
},
// {
// "opcode": "setFont2",
// "blockType": Scratch.BlockType.COMMAND,
// "text": "将字体设为 [FONT]",
// "arguments": {
// "FONT": {
// "type": Scratch.ArgumentType.STRING,
// "defaultValue": "Courier"
// }
// }
// },
{
"opcode": "setColor",
"blockType": Scratch.BlockType.COMMAND,
"text": "将文本颜色设为 [COLOR]",
"arguments": {
"COLOR": {
"type": Scratch.ArgumentType.COLOR
}
}
},
{
"opcode": "setWidth",
"blockType": Scratch.BlockType.COMMAND,
"text": "将宽度设为 [WIDTH] 对齐方式 [ALIGN]",
"arguments": {
"WIDTH": {
"type": Scratch.ArgumentType.NUMBER,
"defaultValue": "200"
},
"ALIGN": {
"type": Scratch.ArgumentType.STRING,
"menu": "align"
}
}
},
{
"opcode": "labelNewBlocks",
"blockType": Scratch.BlockType.LABEL,
"text": "与 Scratch Lab 不兼容:"
},
{
"opcode": "textActive",
"blockType": Scratch.BlockType.BOOLEAN,
"text": "正在显示文本?"
},
{
"opcode": "getTextAttribute",
"blockType": Scratch.BlockType.REPORTER,
"text": "文本 [ATTRIBUTE]",
"arguments": {
"ATTRIBUTE": {
"type": Scratch.ArgumentType.STRING,
"menu": "attribute"
}
},
"disableMonitor": true
}
],
menus: {
// These all need acceptReporters: false for parity with the Scratch Labs version.
animate: {
acceptReporters: false,
items: [
{
text: '打字',
value: 'type'
},
{
text: '彩虹',
value: 'rainbow'
},
{
text: '快速移动',
value: 'zoom'
}
]
},
font: {
acceptReporters: false,
items: [
...NATIVE_FONTS,
{
text: '随机',
value: 'Random'
}
]
},
align: {
acceptReporters: false,
items: [
{
text: '左',
value: 'left'
},
{
text: '中',
value: 'center'
},
{
text: '右',
value: 'right'
}
]
},
attribute: {
acceptReporters: false,
items: [
{
text: '字体',
value: 'font'
},
{
text: '颜色',
value: 'color'
},
{
text: '宽度',
value: 'width'
}
]
}
}
};
}
/**
* @param {VM.Target} target
* @returns {TextState}
*/
_getState(target) {
const state = target[CUSTOM_STATE_KEY];
if (!state) {
/** @type {TextState} */
const newState = {
skin: createTextCostumeSkin(target)
};
target[CUSTOM_STATE_KEY] = newState;
return newState;
}
return state;
}
/**
* @param {VM.Target} target
* @returns {boolean}
*/
_hasState(target) {
return !!target[CUSTOM_STATE_KEY];
}
_hideAllText() {
for (const target of vm.runtime.targets) {
if (this._hasState(target)) {
this._hideText(target, this._getState(target));
}
}
}
/**
* @param {VM.Target} target
* @param {TextState} state
*/
_renderText(target, state) {
state.skin.cancelAnimation();
renderer.updateDrawableSkinId(target.drawableID, state.skin.id);
}
/**
* @param {VM.Target} target
* @param {TextState} state
*/
_hideText(target, state) {
state.skin.cancelAnimation();
target.setCostume(target.currentCostume);
}
setText({ TEXT }, util) {
const state = this._getState(util.target);
this._renderText(util.target, state);
state.skin.setText(Scratch.Cast.toString(TEXT));
// Scratch forces 1 frame delay by returning promise. I think that's silly.
util.runtime.requestRedraw();
}
animateText({ ANIMATE, TEXT }, util) {
const state = this._getState(util.target);
this._renderText(util.target, state);
state.skin.setText(Scratch.Cast.toString(TEXT));
state.skin.cancelAnimation();
if (ANIMATE === 'type') {
return state.skin.startTypeAnimation();
} else if (ANIMATE === 'rainbow') {
return state.skin.startRainbowAnimation();
} else if (ANIMATE === 'zoom') {
return state.skin.startZoomAnimation();
} else {
// Scratch does nothing here
}
}
clearText(args, util) {
if (this._hasState(util.target)) {
const state = this._getState(util.target);
this._hideText(util.target, state);
}
// Scratch forces 1 frame delay by returning promise. I think that's silly.
util.runtime.requestRedraw();
}
setFont({ FONT }, util) {
const state = this._getState(util.target);
if (FONT === 'Random') {
// Random font always switches to a new font, never the same one
const possibleFonts = NATIVE_FONTS.filter(i => i !== state.skin.fontFamily);
state.skin.setFontFamily(possibleFonts[Math.floor(Math.random() * possibleFonts.length)]);
} else {
state.skin.setFontFamily(Scratch.Cast.toString(FONT));
}
}
setFont2({ FONT }, util) {
setFont({ FONT }, util)
}
setColor({ COLOR }, util) {
const state = this._getState(util.target);
state.skin.setColor(Scratch.Cast.toString(COLOR));
}
setWidth({ WIDTH, ALIGN }, util) {
const state = this._getState(util.target);
if (ALIGN === 'center') {
state.skin.setAlign(ALIGN_CENTER);
} else if (ALIGN === 'right') {
state.skin.setAlign(ALIGN_RIGHT);
} else {
// Scratch treats unknown values as left alignment.
state.skin.setAlign(ALIGN_LEFT);
}
state.skin.setWidth(Scratch.Cast.toNumber(WIDTH));
}
textActive(args, util) {
const drawableID = util.target.drawableID;
const skin = renderer._allDrawables[drawableID].skin;
return skin instanceof TextCostumeSkin;
}
getTextAttribute(args, util) {
const state = this._getState(util.target);
const attrib = args.ATTRIBUTE;
if (attrib === 'font') {
return state.skin.getFontFamily();
} else if (attrib === 'color') {
return state.skin.getColor();
} else if (attrib === 'width') {
return state.skin.getWidth();
} else {
// should never happen
return '';
}
}
}
Scratch.extensions.register(new AnimatedText());
})(Scratch);