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
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
const MathUtil = require('../util/math-util');
const StringUtil = require('../util/string-util');
const Cast = require('../util/cast');
const Clone = require('../util/clone');
const { translateForCamera } = require('../util/pos-math');
const Target = require('../engine/target');
const StageLayering = require('../engine/stage-layering');
const getCostumeUrl = require('../util/get-costume-url');
const xmlEscape = require('../util/xml-escape');

/**
 * Rendered target: instance of a sprite (clone), or the stage.
 */
class RenderedTarget extends Target {
    /**
     * @param {!Sprite} sprite Reference to the parent sprite.
     * @param {Runtime} runtime Reference to the runtime.
     * @constructor
     */
    constructor (sprite, runtime) {
        super(runtime, sprite.blocks);

        this.customId = 'pm-rendered-target';

        /**
         * Reference to the sprite that this is a render of.
         * @type {!Sprite}
         */
        this.sprite = sprite;
        /**
         * Reference to the global renderer for this VM, if one exists.
         * @type {?RenderWebGL}
         */
        this.renderer = null;
        if (this.runtime) {
            this.renderer = this.runtime.renderer;
        }
        /**
         * ID of the drawable for this rendered target,
         * returned by the renderer, if rendered.
         * @type {?Number}
         */
        this.drawableID = null;

        /**
         * Drag state of this rendered target. If true, x/y position can't be
         * changed by blocks.
         * @type {boolean}
         */
        this.dragging = false;

        /**
         * Map of current graphic effect values.
         * @type {!Object.<string, number>}
         */
        this.effects = {
            color: 0,
            fisheye: 0,
            whirl: 0,
            pixelate: 0,
            mosaic: 0,
            brightness: 0,
            ghost: 0,
            red: 0,
            green: 0,
            blue: 0,
            opaque: 0,
            saturation: 0,
            // we add 1 since 0x000000 = 0, effects set to 0 will not even be enabled in the shader 
            // (so we can never tint to black if we didnt add 1)
            tintColor: 0xffffff + 1 
        };

        /**
         * Whether this represents an "original" non-clone rendered-target for a sprite,
         * i.e., created by the editor and not clone blocks.
         * @type {boolean}
         */
        this.isOriginal = true;

        /**
         * Whether this rendered target represents the Scratch stage.
         * @type {boolean}
         */
        this.isStage = false;

        /**
         * Whether this rendered target has been disposed.
         * @type {boolean}
         */
        this.isDisposed = false;

        /**
         * Scratch X coordinate. Currently should range from -240 to 240.
         * @type {Number}
         */
        this.x = 0;

        /**
         * Scratch Y coordinate. Currently should range from -180 to 180.
         * @type {number}
         */
        this.y = 0;

        /**
         * the transform for this sprite.
         * @type {Array}
         */
        this.transform = [0, 0];

        /**
         * Scratch direction. Currently should range from -179 to 180.
         * @type {number}
         */
        this.direction = 90;

        /**
         * Whether the rendered target is draggable on the stage
         * @type {boolean}
         */
        this.draggable = false;

        /**
         * Whether the rendered target is currently visible.
         * @type {boolean}
         */
        this.visible = true;

        /**
         * Size of rendered target as a percent of costume size.
         * @type {number}
         */
        this.size = 100;

        /**
         * The stretch percent on each axis
         * @type {array}
         */
        this.stretch = [100, 100];

        /**
         * Currently selected costume index.
         * @type {number}
         */
        this.currentCostume = 0;

        /**
         * Current rotation style.
         * @type {!string}
         */
        this.rotationStyle = RenderedTarget.ROTATION_STYLE_ALL_AROUND;

        /**
         * Loudness for sound playback for this target, as a percentage.
         * @type {number}
         */
        this.volume = 100;

        /**
         * Current tempo (used by the music extension).
         * This property is global to the project and stored in the stage.
         * @type {number}
         */
        this.tempo = 60;

        /**
         * The transparency of the video (used by extensions with camera input).
         * This property is global to the project and stored in the stage.
         * @type {number}
         */
        this.videoTransparency = 50;

        /**
         * The state of the video input (used by extensions with camera input).
         * This property is global to the project and stored in the stage.
         *
         * Defaults to ON. This setting does not turn the video by itself. A
         * video extension once loaded will set the video device to this
         * setting. Set to ON when a video extension is added in the editor the
         * video will start ON. If the extension is loaded as part of loading a
         * saved project the extension will see the value set when the stage
         * was loaded from the saved values including the video state.
         *
         * @type {string}
         */
        this.videoState = RenderedTarget.VIDEO_STATE.ON;

        /**
         * The language to use for speech synthesis, in the text2speech extension.
         * It is initialized to null so that on extension load, we can check for
         * this and try setting it using the editor locale.
         * @type {string}
         */
        this.textToSpeechLanguage = null;

        // Node-style event emitters have non-zero performance overhead compared to function calls, so we
        // replace some very high frequency events with these specific methods that are overridden elsewhere.
        this.onTargetMoved = null;
        this.onTargetVisualChange = null;

        this.interpolationData = null;

        this.cameraBound = 'default';
    }
    cameraUpdateEvent() {
        const {direction, scale} = this._getRenderedDirectionAndScale();
        const translatedPos = this._translatePossitionToCamera();
        this.renderer.updateDrawablePosition(this.drawableID, translatedPos);
        this.renderer.updateDrawableDirectionScale(this.drawableID, direction, scale, this.transform);
        this.renderer.updateDrawableVisible(this.drawableID, this.visible);
    }

    /**
     * Create a drawable with the this.renderer.
     * @param {boolean} layerGroup The layer group this drawable should be added to
     */
    initDrawable (layerGroup) {
        if (this.renderer) {
            this.drawableID = this.renderer.createDrawable(layerGroup);
        }
        // If we're a clone, start the hats.
        if (!this.isOriginal) {
            this.runtime.startHats(
                'control_start_as_clone', null, this
            );
        }
    }

    get audioPlayer () {
        /* eslint-disable no-console */
        console.warn('get audioPlayer deprecated, please update to use .sprite.soundBank methods');
        console.warn(new Error('stack for debug').stack);
        /* eslint-enable no-console */
        const bank = this.sprite.soundBank;
        const audioPlayerProxy = {
            playSound: soundId => bank.play(this, soundId)
        };

        Object.defineProperty(this, 'audioPlayer', {
            configurable: false,
            enumerable: true,
            writable: false,
            value: audioPlayerProxy
        });

        return audioPlayerProxy;
    }

    /**
     * Initialize the audio player for this sprite or clone.
     */
    initAudio () {
    }

    /**
     * Rotation style for "all around"/spinning.
     * @type {string}
     */
    static get ROTATION_STYLE_ALL_AROUND () {
        return 'all around';
    }

    /**
     * pm: Rotation style for "look at"/flipping & spinning.
     * @type {string}
     */
    static get ROTATION_STYLE_LOOK_AT () {
        return 'look at';
    }

    /**
     * Rotation style for "left-right"/flipping.
     * @type {string}
     */
    static get ROTATION_STYLE_LEFT_RIGHT () {
        return 'left-right';
    }

    /**
     * pm: Rotation style for "up-down"/flipping.
     * @type {string}
     */
    static get ROTATION_STYLE_UP_DOWN () {
        return 'up-down';
    }

    /**
     * Rotation style for "no rotation."
     * @type {string}
     */
    static get ROTATION_STYLE_NONE () {
        return "don't rotate";
    }

    /**
     * Available states for video input.
     * @enum {string}
     */
    static get VIDEO_STATE () {
        return {
            OFF: 'off',
            ON: 'on',
            ON_FLIPPED: 'on-flipped'
        };
    }

    emitVisualChange () {
        if (this.onTargetVisualChange) {
            this.onTargetVisualChange(this);
        }
    }

    bindToCamera(screen) {
        this.cameraBound = screen;
        this.updateAllDrawableProperties();
    }

    removeCameraBinding() {
        this.cameraBound = null;
        this.updateAllDrawableProperties();
    }

    _translatePossitionToCamera() {
        if (!this.cameraBound) return [this.x, this.y];
        return translateForCamera(this.runtime, this.cameraBound, this.x, this.y);
    }

    /**
     * Set the X and Y coordinates.
     * @param {!number} x New X coordinate, in Scratch coordinates.
     * @param {!number} y New Y coordinate, in Scratch coordinates.
     * @param {?boolean} force Force setting X/Y, in case of dragging
     * @param {?boolean} ignoreFencing ignores fencing
     */
    setXY (x, y, force, ignoreFencing) { // used by compiler
        if (this.isStage) return;
        if (this.dragging && !force) return;
        const oldX = this.x;
        const oldY = this.y;
        if (this.renderer) {
            const position = this.runtime.runtimeOptions.fencing && !ignoreFencing ?
                this.renderer.getFencedPositionOfDrawable(this.drawableID, [x, y]) :
                [x, y];
            this.x = position[0];
            this.y = position[1];

            this.renderer.updateDrawablePosition(this.drawableID, this._translatePossitionToCamera());
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        } else {
            this.x = x;
            this.y = y;
        }
        if (this.onTargetMoved) {
            this.onTargetMoved(this, oldX, oldY, force);
        }
        this.runtime.requestTargetsUpdate(this);
    }

    setTransform (transform) {
        if (!Array.isArray(transform) || transform.length !== 2) 
            throw new TypeError('Expected an Array of length 2 for the transform input');
        if (this.isStage) {
            return;
        }
        this.transform = [transform[0], transform[1]];
        if (this.renderer) {
            const {direction: renderedDirection, scale} = this._getRenderedDirectionAndScale();
            this.renderer.updateDrawableDirectionScale(this.drawableID, renderedDirection, scale, this.transform);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Get the rendered direction and scale, after applying rotation style.
     * @return {object<string, number>} Direction and scale to render.
     */
    _getRenderedDirectionAndScale () {
        const cameraState = this.runtime.getCamera(this.cameraBound);
        // Default: no changes to `this.direction` or `this.scale`.
        let finalDirection = this.direction;
        let finalScale = [this.size, this.size];
        if (this.rotationStyle === RenderedTarget.ROTATION_STYLE_NONE) {
            // Force rendered direction to be 90.
            finalDirection = 90;
        } else if (this.rotationStyle === RenderedTarget.ROTATION_STYLE_LEFT_RIGHT) {
            // Force rendered direction to be 90, and flip drawable if needed.
            finalDirection = 90;
            const scaleFlip = (this.direction < 0) ? -1 : 1;
            finalScale = [scaleFlip * this.size, this.size];
        } else if (this.rotationStyle === RenderedTarget.ROTATION_STYLE_UP_DOWN) {
            // pm: Force rendered direction to be 90, and flip drawable if needed.
            finalDirection = 90;
            const scaleFlip = ((this.direction > 90) || (this.direction < -90)) ? -1 : 1;
            finalScale = [this.size, scaleFlip * this.size];
        } else if (this.rotationStyle === RenderedTarget.ROTATION_STYLE_LOOK_AT) {
            // pm: Flip drawable if we are looking left.
            const scaleFlip = (this.direction < 0) ? -1 : 1;
            finalScale = [this.size, scaleFlip * this.size];
        }
        finalScale[0] *= this.stretch[0] / 100;
        finalScale[1] *= this.stretch[1] / 100;

        if (this.cameraBound) {
            finalScale[0] *= cameraState.scale;
            finalScale[1] *= cameraState.scale;
            finalDirection -= cameraState.dir;
        }
        return {direction: finalDirection, scale: finalScale, stretch: this.stretch};
    }

    /**
     * set the stretch of this sprite
     * @param {number} x the stretch percentage on the x axis
     * @param {number} y the stretch percentage on the y axis
     */
    setStretch (x, y) {
        if (this.isStage) {
            return;
        }

        this.stretch = [x, y];
        if (this.renderer) {
            const {direction: renderedDirection, scale} = this._getRenderedDirectionAndScale();
            this.renderer.updateDrawableDirectionScale(this.drawableID, renderedDirection, scale, this.transform);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Set the direction.
     * @param {!number} direction New direction.
     */
    setDirection (direction) { // used by compiler
        if (this.isStage) {
            return;
        }
        if (!isFinite(direction)) {
            return;
        }
        // Keep direction between -179 and +180.
        this.direction = MathUtil.wrapClamp(direction, -179, 180);
        if (this.renderer) {
            const {direction: renderedDirection, scale} = this._getRenderedDirectionAndScale();
            this.renderer.updateDrawableDirectionScale(this.drawableID, renderedDirection, scale, this.transform);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Set draggability; i.e., whether it's able to be dragged in the player
     * @param {!boolean} draggable True if should be draggable.
     */
    setDraggable (draggable) {
        if (this.isStage) return;
        this.draggable = !!draggable;
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Set visibility; i.e., whether it's shown or hidden.
     * @param {!boolean} visible True if should be shown.
     */
    setVisible (visible) { // used by compiler
        if (this.isStage) {
            return;
        }
        this.visible = !!visible;
        if (this.renderer) {
            this.renderer.updateDrawableVisible(this.drawableID, this.visible);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Set size, as a percentage of the costume size.
     * @param {!number} size Size of rendered target, as % of costume size.
     */
    setSize (size) { // used by compiler
        if (this.isStage) {
            return;
        }
        if (this.renderer) {
            this.size = Math.max(0, size);
            const {direction, scale} = this._getRenderedDirectionAndScale();
            this.renderer.updateDrawableDirectionScale(this.drawableID, direction, scale, this.transform);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        } else {
            // tw: setSize should update size even without a renderer
            // needed by tw-change-size-does-not-use-rounded-size.sb3 test
            this.size = size;
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Set a particular graphic effect value.
     * @param {!string} effectName Name of effect (see `RenderedTarget.prototype.effects`).
     * @param {!number} value Numerical magnitude of effect.
     */
    setEffect (effectName, value) { // used by compiler
        if (!this.effects.hasOwnProperty(effectName)) return;
        this.effects[effectName] = value;
        if (this.renderer) {
            this.renderer.updateDrawableEffect(this.drawableID, effectName, value);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
    }

    /**
     * Clear all graphic effects on this rendered target.
     */
    clearEffects () { // used by compiler
        for (const effectName in this.effects) {
            if (!this.effects.hasOwnProperty(effectName)) continue;
            this.effects[effectName] = 0;
        }
        if (this.renderer) {
            for (const effectName in this.effects) {
                if (!this.effects.hasOwnProperty(effectName)) continue;
                this.renderer.updateDrawableEffect(this.drawableID, effectName, 0);
            }
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
    }

    /**
     * Set the current costume.
     * @param {number} index New index of costume.
     */
    setCostume (index) {
        // Keep the costume index within possible values.
        index = Math.round(index);
        if (index === Infinity || index === -Infinity || !index) {
            index = 0;
        }

        this.currentCostume = MathUtil.wrapClamp(
            index, 0, this.sprite.costumes.length - 1
        );
        if (this.renderer) {
            const costume = this.sprite.costumes[this.currentCostume];
            this.renderer.updateDrawableSkinId(this.drawableID, costume.skinId);

            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Add a costume, taking care to avoid duplicate names.
     * @param {!object} costumeObject Object representing the costume.
     * @param {?int} index Index at which to add costume
     */
    addCostume (costumeObject, index) {
        if (typeof index === 'number' && !isNaN(index)) {
            this.sprite.addCostumeAt(costumeObject, index);
        } else {
            this.sprite.addCostumeAt(costumeObject, this.sprite.costumes.length);
        }
    }

    /**
     * Rename a costume, taking care to avoid duplicate names.
     * @param {int} costumeIndex - the index of the costume to be renamed.
     * @param {string} newName - the desired new name of the costume (will be modified if already in use).
     */
    renameCostume (costumeIndex, newName) {
        const usedNames = this.sprite.costumes
            .filter((costume, index) => costumeIndex !== index)
            .map(costume => costume.name);
        const oldName = this.getCostumes()[costumeIndex].name;
        const newUnusedName = StringUtil.unusedName(newName, usedNames);
        this.getCostumes()[costumeIndex].name = newUnusedName;

        if (this.isStage) {
            // Since this is a backdrop, go through all targets and
            // update any blocks referencing the old backdrop name
            const targets = this.runtime.targets;
            for (let i = 0; i < targets.length; i++) {
                const currTarget = targets[i];
                currTarget.blocks.updateAssetName(oldName, newUnusedName, 'backdrop');
            }
        } else {
            this.blocks.updateAssetName(oldName, newUnusedName, 'costume');
        }

    }

    /**
     * Delete a costume by index.
     * @param {number} index Costume index to be deleted
     * @return {?object} The costume that was deleted or null
     * if the index was out of bounds of the costumes list or
     * this target only has one costume.
     */
    deleteCostume (index) {
        const originalCostumeCount = this.sprite.costumes.length;
        if (originalCostumeCount === 1) return null;

        if (index < 0 || index >= originalCostumeCount) {
            return null;
        }

        const deletedCostume = this.sprite.deleteCostumeAt(index);

        if (index === this.currentCostume && index === originalCostumeCount - 1) {
            this.setCostume(index - 1);
        } else if (index < this.currentCostume) {
            this.setCostume(this.currentCostume - 1);
        } else {
            this.setCostume(this.currentCostume);
        }

        this.runtime.requestTargetsUpdate(this);
        return deletedCostume;
    }

    /**
     * Add a sound, taking care to avoid duplicate names.
     * @param {!object} soundObject Object representing the sound.
     * @param {?int} index Index at which to add costume
     */
    addSound (soundObject, index) {
        const usedNames = this.sprite.sounds.map(sound => sound.name);
        soundObject.name = StringUtil.unusedName(soundObject.name, usedNames);
        if (typeof index === 'number' && !isNaN(index)) {
            this.sprite.sounds.splice(index, 0, soundObject);
        } else {
            this.sprite.sounds.push(soundObject);
        }
    }

    /**
     * Rename a sound, taking care to avoid duplicate names.
     * @param {int} soundIndex - the index of the sound to be renamed.
     * @param {string} newName - the desired new name of the sound (will be modified if already in use).
     */
    renameSound (soundIndex, newName) {
        const usedNames = this.sprite.sounds
            .filter((sound, index) => soundIndex !== index)
            .map(sound => sound.name);
        const oldName = this.sprite.sounds[soundIndex].name;
        const newUnusedName = StringUtil.unusedName(newName, usedNames);
        this.sprite.sounds[soundIndex].name = newUnusedName;
        this.blocks.updateAssetName(oldName, newUnusedName, 'sound');
    }

    /**
     * Delete a sound by index.
     * @param {number} index Sound index to be deleted
     * @return {object} The deleted sound object, or null if no sound was deleted.
     */
    deleteSound (index) {
        // Make sure the sound index is not out of bounds
        if (index < 0 || index >= this.sprite.sounds.length) {
            return null;
        }
        // Delete the sound at the given index
        const deletedSound = this.sprite.sounds.splice(index, 1)[0];
        this.runtime.requestTargetsUpdate(this);
        return deletedSound;
    }

    /**
     * Update the rotation style.
     * @param {!string} rotationStyle New rotation style.
     */
    setRotationStyle (rotationStyle) { // used by compiler
        if (rotationStyle === RenderedTarget.ROTATION_STYLE_NONE) {
            this.rotationStyle = RenderedTarget.ROTATION_STYLE_NONE;
        } else if (rotationStyle === RenderedTarget.ROTATION_STYLE_ALL_AROUND) {
            this.rotationStyle = RenderedTarget.ROTATION_STYLE_ALL_AROUND;
        } else if (rotationStyle === RenderedTarget.ROTATION_STYLE_LEFT_RIGHT) {
            this.rotationStyle = RenderedTarget.ROTATION_STYLE_LEFT_RIGHT;
        } else if (rotationStyle === RenderedTarget.ROTATION_STYLE_UP_DOWN) {
            this.rotationStyle = RenderedTarget.ROTATION_STYLE_UP_DOWN;
        } else if (rotationStyle === RenderedTarget.ROTATION_STYLE_LOOK_AT) {
            this.rotationStyle = RenderedTarget.ROTATION_STYLE_LOOK_AT;
        }
        if (this.renderer) {
            const {direction, scale} = this._getRenderedDirectionAndScale();
            this.renderer.updateDrawableDirectionScale(this.drawableID, direction, scale, this.transform);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Get a costume index of this rendered target, by name of the costume.
     * @param {?string} costumeName Name of a costume.
     * @return {number} Index of the named costume, or -1 if not present.
     */
    getCostumeIndexByName (costumeName) {
        const costumes = this.getCostumes();
        for (let i = 0; i < costumes.length; i++) {
            if (costumes[i].name === costumeName) {
                return i;
            }
        }
        return -1;
    }

    /**
     * Get a costume of this rendered target by id.
     * @return {object} current costume
     */
    getCurrentCostume () {
        return this.getCostumes()[this.currentCostume];
    }

    /**
     * Get full costume list
     * @return {object[]} list of costumes
     */
    getCostumes () { // used by compiler
        return this.sprite.costumes;
    }

    /**
     * Reorder costume list by moving costume at costumeIndex to newIndex.
     * @param {!number} costumeIndex Index of the costume to move.
     * @param {!number} newIndex New index for that costume.
     * @returns {boolean} If a change occurred (i.e. if the indices do not match)
     */
    reorderCostume (costumeIndex, newIndex) {
        newIndex = MathUtil.clamp(newIndex, 0, this.sprite.costumes.length - 1);
        costumeIndex = MathUtil.clamp(costumeIndex, 0, this.sprite.costumes.length - 1);

        if (newIndex === costumeIndex) return false;

        const currentCostume = this.getCurrentCostume();
        const costume = this.sprite.costumes[costumeIndex];

        // Use the sprite method for deleting costumes because setCostume is handled manually
        this.sprite.deleteCostumeAt(costumeIndex);

        this.addCostume(costume, newIndex);
        this.currentCostume = this.getCostumeIndexByName(currentCostume.name);
        return true;
    }

    /**
     * Reorder sound list by moving sound at soundIndex to newIndex.
     * @param {!number} soundIndex Index of the sound to move.
     * @param {!number} newIndex New index for that sound.
     * @returns {boolean} If a change occurred (i.e. if the indices do not match)
     */
    reorderSound (soundIndex, newIndex) {
        newIndex = MathUtil.clamp(newIndex, 0, this.sprite.sounds.length - 1);
        soundIndex = MathUtil.clamp(soundIndex, 0, this.sprite.sounds.length - 1);

        if (newIndex === soundIndex) return false;

        const sound = this.sprite.sounds[soundIndex];
        this.deleteSound(soundIndex);
        this.addSound(sound, newIndex);
        return true;
    }

    /**
     * Get full sound list
     * @return {object[]} list of sounds
     */
    getSounds () {
        return this.sprite.sounds;
    }
    getSoundIndexByName (soundName) {
        const sounds = this.getSounds();
        for (let i = 0; i < sounds.length; i++) {
            if (sounds[i].name === soundName) {
                return i;
            }
        }
        // if there is no sound by that name, return -1
        return -1;
    }

    /**
     * Update all drawable properties for this rendered target.
     * Use when a batch has changed, e.g., when the drawable is first created.
     */
    updateAllDrawableProperties () {
        if (this.renderer) {
            const {direction, scale} = this._getRenderedDirectionAndScale();
            const translatedPos = this._translatePossitionToCamera();
            this.renderer.updateDrawablePosition(this.drawableID, translatedPos);
            this.renderer.updateDrawableDirectionScale(this.drawableID, direction, scale, this.transform);
            this.renderer.updateDrawableVisible(this.drawableID, this.visible);

            const costume = this.getCostumes()[this.currentCostume];
            this.renderer.updateDrawableSkinId(this.drawableID, costume.skinId);

            for (const effectName in this.effects) {
                if (!this.effects.hasOwnProperty(effectName)) continue;
                this.renderer.updateDrawableEffect(this.drawableID, effectName, this.effects[effectName]);
            }

            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
        this.runtime.requestTargetsUpdate(this);
    }

    /**
     * Return the human-readable name for this rendered target, e.g., the sprite's name.
     * @override
     * @returns {string} Human-readable name.
     */
    getName () {
        return this.sprite.name;
    }

    /**
     * Return whether this rendered target is a sprite (not a clone, not the stage).
     * @return {boolean} True if not a clone and not the stage.
     */
    isSprite () {
        return !this.isStage && this.isOriginal;
    }

    /**
     * Return the rendered target's tight bounding box.
     * Includes top, left, bottom, right attributes in Scratch coordinates.
     * @return {?object} Tight bounding box, or null.
     */
    getBounds () {
        if (this.renderer) {
            return this.runtime.renderer.getBounds(this.drawableID);
        }
        return null;
    }

    /**
     * Return the bounding box around a slice of the top 8px of the rendered target.
     * Includes top, left, bottom, right attributes in Scratch coordinates.
     * @return {?object} Tight bounding box, or null.
     */
    getBoundsForBubble () {
        if (this.renderer) {
            return this.runtime.renderer.getBoundsForBubble(this.drawableID);
        }
        return null;
    }

    /**
     * Return whether this target is touching the mouse, an edge, or a sprite.
     * @param {string} requestedObject an id for mouse or edge, or a sprite name.
     * @param {boolean?} unoriginalOnly if true, will use isTouchingSpriteUnoriginals when checking sprites.
     * @return {boolean} True if the sprite is touching the object.
     */
    isTouchingObject (requestedObject, unoriginalOnly) { // used by compiler
        if (requestedObject === '_mouse_') {
            if (!this.runtime.ioDevices.mouse) return false;
            const mouseX = this.runtime.ioDevices.mouse.getClientX();
            const mouseY = this.runtime.ioDevices.mouse.getClientY();
            return this.isTouchingPoint(mouseX, mouseY);
        } else if (requestedObject === '_edge_') {
            return this.isTouchingEdge();
        }

        if (unoriginalOnly) {
            return this.isTouchingSpriteUnoriginals(requestedObject);
        } else {
            return this.isTouchingSprite(requestedObject);
        }
    }

    /**
     * Return whether touching a point.
     * @param {number} x X coordinate of test point.
     * @param {number} y Y coordinate of test point.
     * @return {boolean} True iff the rendered target is touching the point.
     */
    isTouchingPoint (x, y) {
        if (this.renderer) {
            return this.renderer.drawableTouching(this.drawableID, x, y);
        }
        return false;
    }

    /**
     * Return whether touching a stage edge.
     * @return {boolean} True iff the rendered target is touching the stage edge.
     */
    isTouchingEdge () {
        if (this.renderer) {
            const stageWidth = this.runtime.stageWidth;
            const stageHeight = this.runtime.stageHeight;
            const bounds = this.getBounds();
            if (bounds.left < -stageWidth / 2 ||
                bounds.right > stageWidth / 2 ||
                bounds.top > stageHeight / 2 ||
                bounds.bottom < -stageHeight / 2) {
                return true;
            }
        }
        return false;
    }

    /**
     * Return whether touching any of a named sprite's clones.
     * @param {string} spriteName Name of the sprite.
     * @return {boolean} True if touching a clone of the sprite.
     */
    isTouchingSprite (spriteName) {
        spriteName = Cast.toString(spriteName);
        const firstClone = this.runtime.getSpriteTargetByName(spriteName);
        if (!firstClone || !this.renderer) {
            return false;
        }
        // Filter out dragging targets. This means a sprite that is being dragged
        // can detect other sprites using touching <sprite>, but cannot be detected
        // by other sprites while it is being dragged. This matches Scratch 2.0 behavior.
        const drawableCandidates = firstClone.sprite.clones.filter(clone => !clone.dragging)
            .map(clone => clone.drawableID);
        return this.renderer.isTouchingDrawables(
            this.drawableID, drawableCandidates);
    }

    /**
     * Return whether touching a target.
     * @param {string} targetId ID of the target
     * @return {boolean} True if touching the target
     */
    isTouchingTarget (targetId) {
        targetId = Cast.toString(targetId);
        const target = this.runtime.getTargetById(targetId);
        if (!target || !this.renderer || target.dragging) {
            return false;
        }
        return this.renderer.isTouchingDrawables(
            this.drawableID, [target.drawableID]);
    }

    /**
     * Return whether touching any of a named sprite's unoriginal clones.
     * @param {string} spriteName Name of the sprite.
     * @return {boolean} True if touching a clone of the sprite with isOriginal set to false.
     */
    isTouchingSpriteUnoriginals (spriteName) {
        spriteName = Cast.toString(spriteName);
        const firstClone = this.runtime.getSpriteTargetByName(spriteName);
        if (!firstClone || !this.renderer) {
            return false;
        }
        // Filter out dragging targets. This means a sprite that is being dragged
        // can detect other sprites using touching <sprite>, but cannot be detected
        // by other sprites while it is being dragged. This matches Scratch 2.0 behavior.
        const drawableCandidates = firstClone.sprite.clones.filter(clone => !clone.dragging && !clone.isOriginal)
            .map(clone => clone.drawableID);
        return this.renderer.isTouchingDrawables(
            this.drawableID, drawableCandidates);
    }

    /**
     * Return whether touching any of a named sprite's clones.
     * @param {string} spriteName Name of the sprite.
     * @return {boolean} True iff touching a clone of the sprite.
     */
    spriteTouchingPoint (spriteName) {
        spriteName = Cast.toString(spriteName);
        const firstClone = this.runtime.getSpriteTargetByName(spriteName);
        if (!firstClone || !this.renderer) {
            return null;
        }
        // Filter out dragging targets. This means a sprite that is being dragged
        // can detect other sprites using touching <sprite>, but cannot be detected
        // by other sprites while it is being dragged. This matches Scratch 2.0 behavior.
        const drawableCandidates = firstClone.sprite.clones.filter(clone => !clone.dragging)
            .map(clone => clone.drawableID);
        return this.renderer.getTouchingDrawablesPoint(
            this.drawableID, drawableCandidates);
    }

    /**
     * Return whether touching a color.
     * @param {Array.<number>} rgb [r,g,b], values between 0-255.
     * @return {Promise.<boolean>} True iff the rendered target is touching the color.
     */
    isTouchingColor (rgb) { // used by compiler
        if (this.renderer) {
            return this.renderer.isTouchingColor(this.drawableID, rgb);
        }
        return false;
    }

    /**
     * Return whether rendered target's color is touching a color.
     * @param {object} targetRgb {Array.<number>} [r,g,b], values between 0-255.
     * @param {object} maskRgb {Array.<number>} [r,g,b], values between 0-255.
     * @return {Promise.<boolean>} True iff the color is touching the color.
     */
    colorIsTouchingColor (targetRgb, maskRgb) { // used by compiler
        if (this.renderer) {
            return this.renderer.isTouchingColor(
                this.drawableID,
                targetRgb,
                maskRgb
            );
        }
        return false;
    }

    getLayerOrder () {
        if (this.renderer) {
            return this.renderer.getDrawableOrder(this.drawableID);
        }
        return null;
    }

    /**
     * Move to the front layer.
     */
    goToFront () { // This should only ever be used for sprites // used by compiler
        if (this.renderer) {
            // Let the renderer re-order the sprite based on its knowledge
            // of what layers are present
            this.renderer.setDrawableOrder(this.drawableID, Infinity, StageLayering.SPRITE_LAYER);
        }

        this.runtime.setExecutablePosition(this, Infinity);
    }

    /**
     * Move to the back layer.
     */
    goToBack () { // This should only ever be used for sprites // used by compiler
        if (this.renderer) {
            // Let the renderer re-order the sprite based on its knowledge
            // of what layers are present
            this.renderer.setDrawableOrder(this.drawableID, -Infinity, StageLayering.SPRITE_LAYER, false);
        }

        this.runtime.setExecutablePosition(this, -Infinity);
    }

    /**
     * Move forward a number of layers.
     * @param {number} nLayers How many layers to go forward.
     */
    goForwardLayers (nLayers) { // used by compiler
        if (this.renderer) {
            this.renderer.setDrawableOrder(this.drawableID, nLayers, StageLayering.SPRITE_LAYER, true);
        }

        this.runtime.moveExecutable(this, nLayers);
    }

    /**
     * Move backward a number of layers.
     * @param {number} nLayers How many layers to go backward.
     */
    goBackwardLayers (nLayers) { // used by compiler
        if (this.renderer) {
            this.renderer.setDrawableOrder(this.drawableID, -nLayers, StageLayering.SPRITE_LAYER, true);
        }

        this.runtime.moveExecutable(this, -nLayers);
    }

    /**
     * Move behind some other rendered target.
     * @param {!RenderedTarget} other Other rendered target to move behind.
     */
    goBehindOther (other) {
        if (this.renderer) {
            const otherLayer = this.renderer.setDrawableOrder(
                other.drawableID, 0, StageLayering.SPRITE_LAYER, true);
            this.renderer.setDrawableOrder(this.drawableID, otherLayer, StageLayering.SPRITE_LAYER);
        }

        const executionPosition = this.runtime.executableTargets.indexOf(other);
        this.runtime.setExecutablePosition(this, executionPosition);
    }

    /**
     * Keep a desired position within a fence.
     * @param {number} newX New desired X position.
     * @param {number} newY New desired Y position.
     * @param {object=} optFence Optional fence with left, right, top bottom.
     * @return {Array.<number>} Fenced X and Y coordinates.
     */
    keepInFence (newX, newY, optFence) {
        let fence = optFence;
        if (!fence) {
            fence = {
                left: -this.runtime.stageWidth / 2,
                right: this.runtime.stageWidth / 2,
                top: this.runtime.stageHeight / 2,
                bottom: -this.runtime.stageHeight / 2
            };
        }
        const bounds = this.getBounds();
        if (!bounds) return;
        // Adjust the known bounds to the target position.
        bounds.left += (newX - this.x);
        bounds.right += (newX - this.x);
        bounds.top += (newY - this.y);
        bounds.bottom += (newY - this.y);
        // Find how far we need to move the target position.
        let dx = 0;
        let dy = 0;
        if (bounds.left < fence.left) {
            dx += fence.left - bounds.left;
        }
        if (bounds.right > fence.right) {
            dx += fence.right - bounds.right;
        }
        if (bounds.top > fence.top) {
            dy += fence.top - bounds.top;
        }
        if (bounds.bottom < fence.bottom) {
            dy += fence.bottom - bounds.bottom;
        }
        return [newX + dx, newY + dy];
    }

    /**
     * Make a clone, copying any run-time properties.
     * If we've hit the global clone limit, returns null.
     * @return {RenderedTarget} New clone.
     */
    makeClone () {
        if (!this.runtime.clonesAvailable() || this.isStage) {
            return null; // Hit max clone limit, or this is the stage.
        }
        this.runtime.changeCloneCounter(1);
        const newClone = this.sprite.createClone();
        // Copy all properties.
        newClone.x = this.x;
        newClone.y = this.y;
        newClone.direction = this.direction;
        newClone.draggable = this.draggable;
        newClone.visible = this.visible;
        newClone.size = this.size;
        newClone.stretch = this.stretch;
        newClone.currentCostume = this.currentCostume;
        newClone.rotationStyle = this.rotationStyle;
        newClone.effects = Clone.simple(this.effects);
        newClone.variables = this.duplicateVariables();
        newClone.cameraBound = this.cameraBound;
        newClone._edgeActivatedHatValues = Clone.simple(this._edgeActivatedHatValues);
        newClone.initDrawable(StageLayering.SPRITE_LAYER);
        newClone.updateAllDrawableProperties();
        return newClone;
    }

    /**
     * Make a duplicate using a duplicate sprite.
     * @return {RenderedTarget} New clone.
     */
    duplicate () {
        return this.sprite.duplicate().then(newSprite => {
            const newTarget = newSprite.createClone();
            // Copy all properties.
            // @todo refactor with clone methods
            newTarget.x = (Math.random() - 0.5) * 400 / 2;
            newTarget.y = (Math.random() - 0.5) * 300 / 2;
            newTarget.direction = this.direction;
            newTarget.draggable = this.draggable;
            newTarget.visible = this.visible;
            newTarget.size = this.size;
            newTarget.stretch = this.stretch;
            newTarget.currentCostume = this.currentCostume;
            newTarget.rotationStyle = this.rotationStyle;
            newTarget.effects = JSON.parse(JSON.stringify(this.effects));
            newTarget.variables = this.duplicateVariables(newTarget.blocks);
            newTarget.cameraBound = this.cameraBound;
            newTarget.updateAllDrawableProperties();
            return newTarget;
        });
    }

    /**
     * Called when the project receives a "green flag."
     * For a rendered target, this clears graphic effects.
     */
    onGreenFlag () {
        this.clearEffects();
    }

    /**
     * Called when the project receives a "stop all"
     * Stop all sounds and clear graphic effects.
     */
    onStopAll () {
        this.clearEffects();
    }

    /**
     * Post/edit sprite info.
     * @param {object} data An object with sprite info data to set.
     */
    postSpriteInfo (data) {
        const force = data.hasOwnProperty('force') ? data.force : null;
        const isXChanged = data.hasOwnProperty('x');
        const isYChanged = data.hasOwnProperty('y');
        if (isXChanged || isYChanged) {
            this.setXY(isXChanged ? data.x : this.x, isYChanged ? data.y : this.y, force);
        }
        if (data.hasOwnProperty('direction')) {
            this.setDirection(data.direction);
        }
        if (data.hasOwnProperty('draggable')) {
            this.setDraggable(data.draggable);
        }
        if (data.hasOwnProperty('rotationStyle')) {
            this.setRotationStyle(data.rotationStyle);
        }
        if (data.hasOwnProperty('visible')) {
            this.setVisible(data.visible);
        }
        if (data.hasOwnProperty('size')) {
            this.setSize(data.size);
        }
    }

    /**
     * Put the sprite into the drag state. While in effect, setXY must be forced
     */
    startDrag () {
        this.dragging = true;
    }

    /**
     * Remove the sprite from the drag state.
     */
    stopDrag () {
        this.dragging = false;
    }


    /**
     * Serialize sprite info, used when emitting events about the sprite
     * @returns {object} Sprite data as a simple object
     */
    toJSON () {
        const costumes = this.getCostumes();
        return {
            id: this.id,
            name: this.getName(),
            isStage: this.isStage,
            isDisposed: this.isDisposed,
            x: this.x,
            y: this.y,
            size: this.size,
            direction: this.direction,
            draggable: this.draggable,
            currentCostume: this.currentCostume,
            costume: costumes[this.currentCostume],
            costumeCount: costumes.length,
            visible: this.visible,
            rotationStyle: this.rotationStyle,
            comments: this.comments,
            blocks: this.blocks._blocks,
            variables: this.variables,
            costumes: costumes,
            sounds: this.getSounds(),
            textToSpeechLanguage: this.textToSpeechLanguage,
            tempo: this.tempo,
            volume: this.volume,
            videoTransparency: this.videoTransparency,
            videoState: this.videoState

        };
    }

    /**
     * Dispose, destroying any run-time properties.
     */
    dispose () {
        // pm: remove this event
        this.runtime.removeListener('CAMERA_CHANGED', this.cameraUpdateEvent);

        if (!this.isOriginal) {
            this.runtime.changeCloneCounter(-1);
        }
        this.isDisposed = true;
        this.runtime.stopForTarget(this);
        this.runtime.removeExecutable(this);
        this.sprite.removeClone(this);
        if (this.renderer && this.drawableID !== null) {
            this.renderer.destroyDrawable(this.drawableID, this.isStage ?
                StageLayering.BACKGROUND_LAYER :
                StageLayering.SPRITE_LAYER);
            if (this.visible) {
                this.emitVisualChange();
                this.runtime.requestRedraw();
            }
        }
    }

    // custom type implement so that targets can just be the returned without any prior setup
    getCostumeType(idx) {
        const owner = this;
        const ent = this.getCostumes()[idx];
        if (!ent) return;
        ent.customId = 'pm-costume-asset';
        // ensures that when this type is later reused it correctly expresses any changes
        Object.defineProperty(ent, '_monitorUpToDate', {
            get() {
                if (this._oldName !== this.name) return false;
                if (this._oldSizeX !== this.size[0]) return false;
                if (this._oldSizeY !== this.size[1]) return false;
                if (this._oldAssetId !== this.assetId) return false;
                if (this._oldIndex !== owner.getCostumeIndexByName(this.name)) return false;
                return true;
            }
        });
        ent.toReporterContent = function() {
            this._oldName = this.name;
            this._oldSizeX = this.size[0];
            this._oldSizeY = this.size[1];
            this._oldAssetId = this.assetId;
            this._oldIndex = owner.getCostumeIndexByName(this.name);
            const wrap = document.createElement('div');
            wrap.innerHTML = `<div style="
                box-sizing: border-box;
                width: 5rem;
                height: 5rem;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                font-size: 0.625rem;
                overflow: hidden;
                border: 2px solid hsla(0, 0%, 0%, 0.15);
                border-radius: 0.5rem;
                color: hsla(225, 15%, 40%, 1);
                user-select: none;
            ">
                <div style="
                    width: 100%; 
                    height: 100%; 
                    display: flex; 
                    align-items: center; 
                    justify-content: center;
                ">
                    <div style="
                        position: absolute; 
                        font-weight: bold; 
                        left: 0.45rem; 
                        top: 0.55rem; 
                        width: 1em; 
                        height: 1em;
                        white-space: nowrap;
                    ">
                        ${xmlEscape(((owner.getCostumeIndexByName(this.name) +1) || 'X').toString())}
                    </div>
                    <img 
                        style="max-width: 32px; max-height: 32px;" 
                        src="${xmlEscape(getCostumeUrl(this.asset))}"
                    ></img>
                </div>
                <div style="padding: 0.25rem; text-overflow: ellipsis; white-space: nowrap;">
                    ${xmlEscape(this.name)}
                    <div style="font-size: 0.5rem; margin-top: 0.125rem">
                        ${xmlEscape(Math.round(this.size[0]).toString())} x ${xmlEscape(Math.round(this.size[1]).toString())}
                    </div>
                </div>
            </div>`;
            return wrap;
        };
        return ent;
    }
    getSoundType(idx) {
        const owner = this;
        const ent = this.getSounds()[idx];
        if (!ent) return;
        ent.customId = 'pm-sound-asset';
        Object.defineProperty(ent, '_monitorUpToDate', {
            get() {
                if (this._oldName !== this.name) return false;
                if (this._oldAssetId !== this.assetId) return false;
                if (this._oldSampleRate !== this.rate) return false;
                if (this._oldSampleCount !== this.sampleCount) return false;
                if (this._oldIndex !== owner.getSoundIndexByName(this.name)) return false;
                return true;
            }
        });
        ent.toReporterContent = function() {
            this._oldName = this.name;
            this._oldAssetId = this.assetId;
            this._oldSampleRate = this.rate;
            this._oldSampleCount = this.sampleCount;
            this._oldIndex = owner.getSoundIndexByName(this.name);
            const wrap = document.createElement('div');
            wrap.innerHTML = `<div style="
                box-sizing: border-box;
                width: 5rem;
                height: 5rem;
                display: flex;
                flex-direction: column;
                justify-content: flex-start;
                font-size: 0.625rem;
                overflow: hidden;
                border: 2px solid hsla(0, 0%, 0%, 0.15);
                border-radius: 0.5rem;
                color: hsla(225, 15%, 40%, 1);
                user-select: none;
            ">
                <div style="
                    width: 100%; 
                    height: 100%; 
                    display: flex; 
                    align-items: center; 
                    justify-content: center;
                ">
                    <div style="
                        position: absolute; 
                        font-weight: bold; 
                        left: 0.45rem; 
                        top: 0.55rem; 
                        width: 1em; 
                        height: 1em;
                        white-space: nowrap;
                    ">
                        ${xmlEscape(((owner.getSoundIndexByName(this.name) +1) || 'X').toString())}
                    </div>
                    <img 
                        style="max-width: 32px; max-height: 32px;" 
                        src="static/assets/63e5827c1506216bd7c9927a4e5eb558.svg"
                    ></img>
                </div>
                <div style="padding: 0.25rem; text-overflow: ellipsis; white-space: nowrap;">
                    ${xmlEscape(this.name)}
                    <div style="font-size: 0.5rem; margin-top: 0.125rem">
                        ${xmlEscape((this.sampleCount / this.rate).toFixed(2))}
                    </div>
                </div>
            </div>`;
            return wrap;
        };
        return ent;
    }

    get _monitorUpToDate() {
        if (this._oldName !== this.getName()) return false;
        if (this._oldCostumeIdx !== this.currentCostume) return false;
        if (this._oldCostumeAssetId !== this.getCurrentCostume().assetId) return false;
        return true;
    }
    toString() { return this.getName(); }
    toReporterContent() {
        this._oldName = this.getName();
        this._oldCostumeIdx = this.currentCostume;
        this._oldCostumeAssetId = this.getCurrentCostume().assetId;
        const wrap = document.createElement('div');
        wrap.innerHTML = `<div style="
            box-sizing: border-box;
            width: 4rem;
            height: 4rem;
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            font-size: 0.625rem;
            overflow: hidden;
            cursor: pointer;
            border: 2px solid hsla(0, 0%, 0%, 0.15);
            border-radius: 0.5rem;
            color: hsla(225, 15%, 40%, 1);
            user-select: none;
        ">
            <div style="
                width: 100%; 
                height: 100%; 
                display: flex; 
                align-items: center; 
                justify-content: center;
            ">
                <img 
                    style="max-width: 32px; max-height: 32px;" 
                    src="${xmlEscape(getCostumeUrl(this.getCurrentCostume().asset))}"
                ></img>
            </div>
            <div style="padding: 0.25rem; text-overflow: ellipsis; white-space: nowrap;">
                ${xmlEscape(this.getName())}
            </div>
        </div>`;
        wrap.onclick = () => 
            this.runtime.vm.setEditingTarget(this.id);
        return wrap;
    }
}

module.exports = RenderedTarget;