Spaces:
Build error
Build error
File size: 53,137 Bytes
30c32c8 |
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 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 |
const formatMessage = require('format-message');
const BlockType = require('../../extension-support/block-type');
const ArgumentType = require('../../extension-support/argument-type');
const BufferUtil = new (require('../../util/array buffer'));
const Cast = require('../../util/cast');
const Color = require('../../util/color');
// ShovelUtils
let fps = 0;
/**
* Class for Runtime blocks
* @constructor
*/
class JgRuntimeBlocks {
constructor(runtime) {
/**
* The runtime instantiating this block package.
* @type {Runtime}
*/
this.runtime = runtime;
// SharkPool
this.pausedScripts = Object.create(null);
// ShovelUtils
// Based on from https://www.growingwiththeweb.com/2017/12/fast-simple-js-fps-counter.html
const times = [];
fps = this.runtime.frameLoop.framerate;
this.runtime.on('RUNTIME_STEP_START', () => {
const now = performance.now();
while (times.length > 0 && times[0] <= now - 1000) { times.shift() }
times.push(now);
fps = times.length;
});
this.runtime.on('PROJECT_STOP_ALL', () => { this.pausedScripts = Object.create(null) });
}
_typeIsBitmap(type) {
return (
type === 'image/png' || type === 'image/bmp' || type === 'image/jpg' || type === 'image/jpeg' ||
type === 'image/jfif' || type === 'image/webp' || type === 'image/gif'
);
}
/**
* @returns {object} metadata for this extension and its blocks.
*/
getInfo() {
return {
id: 'jgRuntime',
name: 'Runtime',
color1: '#777777',
color2: '#6a6a6a',
blocks: [
{
opcode: 'addSpriteUrl',
text: 'add sprite from [URL]',
blockType: BlockType.COMMAND,
arguments: {
URL: {
type: ArgumentType.STRING,
defaultValue: `https://corsproxy.io/?${encodeURIComponent('https://penguinmod.com/Sprite1.pms')}`
}
}
},
{
opcode: 'addCostumeUrl',
text: 'add costume [name] from [URL]',
blockType: BlockType.COMMAND,
arguments: {
URL: {
type: ArgumentType.STRING,
defaultValue: `https://corsproxy.io/?${encodeURIComponent('https://penguinmod.com/navicon.png')}`
},
name: {
type: ArgumentType.STRING,
defaultValue: 'penguinmod'
}
}
},
{
opcode: 'addCostumeUrlForceMime',
text: 'add [costtype] costume [name] from [URL]',
blockType: BlockType.COMMAND,
arguments: {
costtype: {
type: ArgumentType.STRING,
menu: "costumeMimeType"
},
URL: {
type: ArgumentType.STRING,
defaultValue: `https://corsproxy.io/?${encodeURIComponent('https://penguinmod.com/navicon.png')}`
},
name: {
type: ArgumentType.STRING,
defaultValue: 'penguinmod'
}
}
},
{
opcode: 'addSoundUrl',
text: 'add sound [NAME] from [URL]',
blockType: BlockType.COMMAND,
arguments: {
URL: {
type: ArgumentType.STRING,
defaultValue: 'https://extensions.turbowarp.org/meow.mp3'
},
NAME: {
type: ArgumentType.STRING,
defaultValue: 'Meow'
}
}
},
{
opcode: 'loadProjectDataUrl',
text: 'load project from [URL]',
blockType: BlockType.COMMAND,
arguments: {
URL: {
type: ArgumentType.STRING,
defaultValue: ''
}
}
},
{
opcode: 'getIndexOfCostume',
text: 'get costume index of [costume]',
blockType: BlockType.REPORTER,
arguments: {
costume: {
type: ArgumentType.STRING,
defaultValue: "costume1"
}
}
},
{
opcode: 'getIndexOfSound',
text: 'get sound index of [NAME]',
blockType: BlockType.REPORTER,
arguments: {
NAME: {
type: ArgumentType.STRING,
defaultValue: "Pop"
}
}
},
{
opcode: 'getProjectDataUrl',
text: 'get data url of project',
blockType: BlockType.REPORTER,
disableMonitor: true
},
'---',
{
opcode: 'setStageSize',
text: formatMessage({
id: 'jgRuntime.blocks.setStageSize',
default: 'set stage width: [WIDTH] height: [HEIGHT]',
description: 'Sets the width and height of the stage.'
}),
blockType: BlockType.COMMAND,
arguments: {
WIDTH: {
type: ArgumentType.NUMBER,
defaultValue: 480
},
HEIGHT: {
type: ArgumentType.NUMBER,
defaultValue: 360
}
}
},
{
opcode: 'getStageWidth',
text: formatMessage({
id: 'jgRuntime.blocks.getStageWidth',
default: 'stage width',
description: 'Block that returns the width of the stage.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getStageHeight',
text: formatMessage({
id: 'jgRuntime.blocks.getStageHeight',
default: 'stage height',
description: 'Block that returns the height of the stage.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
'---',
{
opcode: 'updateRuntimeConfig',
text: formatMessage({
id: 'jgRuntime.blocks.updateRuntimeConfig',
default: 'set [OPTION] to [ENABLED]',
description: 'Block that enables or disables configuration on the runtime like high quality pen or turbo mode.'
}),
disableMonitor: false,
blockType: BlockType.COMMAND,
arguments: {
OPTION: {
menu: 'runtimeConfig'
},
ENABLED: {
menu: 'onoff'
}
}
},
{
opcode: 'changeRenderingCapping',
text: formatMessage({
id: 'jgRuntime.blocks.changeRenderingCapping',
default: 'change render setting [OPTION] to [CAPPED]',
description: 'Block that updates configuration on the renderer like resolution for certain content.'
}),
disableMonitor: false,
blockType: BlockType.COMMAND,
arguments: {
OPTION: {
menu: 'renderConfigCappable'
},
CAPPED: {
menu: 'cappableSettings'
}
}
},
{
opcode: 'setRenderingNumber',
text: formatMessage({
id: 'jgRuntime.blocks.setRenderingNumber',
default: 'set render setting [OPTION] to [NUM]',
description: 'Block that sets configuration on the renderer like resolution for certain content.'
}),
disableMonitor: false,
blockType: BlockType.COMMAND,
arguments: {
OPTION: {
menu: 'renderConfigNumber'
},
NUM: {
type: ArgumentType.NUMBER,
defaultValue: 0
}
}
},
{
opcode: 'runtimeConfigEnabled',
text: formatMessage({
id: 'jgRuntime.blocks.runtimeConfigEnabled',
default: '[OPTION] enabled?',
description: 'Block that returns whether a runtime option like Turbo Mode is enabled on the project or not.'
}),
disableMonitor: false,
blockType: BlockType.BOOLEAN,
arguments: {
OPTION: {
menu: 'runtimeConfig'
}
}
},
{
opcode: 'turboModeEnabled',
text: formatMessage({
id: 'jgRuntime.blocks.turboModeEnabled',
default: 'turbo mode enabled?',
description: 'Block that returns whether Turbo Mode is enabled on the project or not.'
}),
disableMonitor: false,
hideFromPalette: true,
blockType: BlockType.BOOLEAN
},
'---',
{
opcode: 'setMaxClones',
text: formatMessage({
id: 'jgRuntime.blocks.setMaxClones',
default: 'set max clones to [MAX]',
description: 'Block that enables or disables configuration on the runtime like high quality pen or turbo mode.'
}),
disableMonitor: false,
blockType: BlockType.COMMAND,
arguments: {
MAX: {
menu: 'cloneLimit',
defaultValue: 300
}
}
},
{
opcode: 'maxAmountOfClones',
text: formatMessage({
id: 'jgRuntime.blocks.maxAmountOfClones',
default: 'max clone count',
description: 'Block that returns the maximum amount of clones that may exist.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'amountOfClones',
text: formatMessage({
id: 'jgRuntime.blocks.amountOfClones',
default: 'clone count',
description: 'Block that returns the amount of clones that currently exist.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getIsClone',
text: formatMessage({
id: 'jgRuntime.blocks.getIsClone',
default: 'is clone?',
description: 'Block that returns whether the sprite is a clone or not.'
}),
disableMonitor: true,
blockType: BlockType.BOOLEAN
},
'---',
{
opcode: 'setMaxFrameRate',
text: formatMessage({
id: 'jgRuntime.blocks.setMaxFrameRate',
default: 'set max framerate to: [FRAMERATE]',
description: 'Sets the max allowed framerate.'
}),
blockType: BlockType.COMMAND,
arguments: {
FRAMERATE: {
type: ArgumentType.NUMBER,
defaultValue: 30
}
}
},
{
opcode: 'getMaxFrameRate',
text: formatMessage({
id: 'jgRuntime.blocks.getMaxFrameRate',
default: 'max framerate',
description: 'Block that returns the amount of FPS allowed.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getFrameRate',
text: formatMessage({
id: 'jgRuntime.blocks.getFrameRate',
default: 'framerate',
description: 'Block that returns the amount of FPS.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
'---',
{
opcode: 'setBackgroundColor',
text: formatMessage({
id: 'jgRuntime.blocks.setBackgroundColor',
default: 'set stage background color to [COLOR]',
description: 'Sets the background color of the stage.'
}),
blockType: BlockType.COMMAND,
arguments: {
COLOR: {
type: ArgumentType.COLOR
}
}
},
{
opcode: 'getBackgroundColor',
text: formatMessage({
id: 'jgRuntime.blocks.getBackgroundColor',
default: 'stage background color',
description: 'Block that returns the stage background color in HEX.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER
},
"---",
{
opcode: "pauseScript",
blockType: BlockType.COMMAND,
text: "pause this script using name: [NAME]",
arguments: {
NAME: {
type: ArgumentType.STRING,
defaultValue: "my script",
},
}
},
{
opcode: "unpauseScript",
blockType: BlockType.COMMAND,
text: "unpause script named: [NAME]",
arguments: {
NAME: {
type: ArgumentType.STRING,
defaultValue: "my script",
},
}
},
{
opcode: "isScriptPaused",
blockType: BlockType.BOOLEAN,
text: "is script named [NAME] paused?",
arguments: {
NAME: {
type: ArgumentType.STRING,
defaultValue: "my script",
},
}
},
"---",
{
opcode: 'variables_createVariable',
text: 'create variable named [NAME] for [SCOPE]',
blockType: BlockType.COMMAND,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "my variable" },
SCOPE: { type: ArgumentType.STRING, menu: "variableScope" }
}
},
{
opcode: 'variables_createCloudVariable',
text: 'create cloud variable named [NAME]',
blockType: BlockType.COMMAND,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "cloud variable" },
}
},
{
opcode: 'variables_createList',
text: 'create list named [NAME] for [SCOPE]',
blockType: BlockType.COMMAND,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "list" },
SCOPE: { type: ArgumentType.STRING, menu: "variableScope" }
}
},
{
opcode: 'variables_getVariable',
text: 'get value of variable named [NAME] in [SCOPE]',
disableMonitor: true,
blockType: BlockType.REPORTER,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "my variable" },
SCOPE: { type: ArgumentType.STRING, menu: "variableTypes" }
}
},
{
opcode: 'variables_getList',
text: 'get array of list named [NAME] in [SCOPE]',
disableMonitor: true,
blockType: BlockType.REPORTER,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "list" },
SCOPE: { type: ArgumentType.STRING, menu: "variableScope" }
}
},
{
opcode: 'variables_existsVariable',
text: 'variable named [NAME] exists in [SCOPE]?',
disableMonitor: true,
blockType: BlockType.BOOLEAN,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "my variable" },
SCOPE: { type: ArgumentType.STRING, menu: "variableTypes" }
}
},
{
opcode: 'variables_existsList',
text: 'list named [NAME] exists in [SCOPE]?',
disableMonitor: true,
blockType: BlockType.BOOLEAN,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "list" },
SCOPE: { type: ArgumentType.STRING, menu: "variableScope" }
}
},
"---",
{
opcode: 'getDataOption',
text: formatMessage({
id: 'jgRuntime.blocks.getDataOption',
default: 'get binary data of [OPTION] named [NAME]',
description: 'Block that returns the binary data of a sprite, sound or costume.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER,
arguments: {
OPTION: {
type: ArgumentType.STRING,
menu: "objectType"
},
NAME: {
type: ArgumentType.STRING,
defaultValue: "Sprite1"
}
}
},
{
opcode: 'getDataUriOption',
text: formatMessage({
id: 'jgRuntime.blocks.getDataUriOption',
default: 'get data uri of [OPTION] named [NAME]',
description: 'Block that returns the data URI of a sprite, sound or costume.'
}),
disableMonitor: false,
blockType: BlockType.REPORTER,
arguments: {
OPTION: {
type: ArgumentType.STRING,
menu: "objectType"
},
NAME: {
type: ArgumentType.STRING,
defaultValue: "Sprite1"
}
}
},
"---",
{
opcode: 'getAllSprites',
text: 'get all sprites',
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getAllCostumes',
text: 'get all costumes',
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getAllSounds',
text: 'get all sounds',
disableMonitor: false,
blockType: BlockType.REPORTER
},
{
opcode: 'getAllFonts',
text: 'get all fonts',
disableMonitor: false,
blockType: BlockType.REPORTER
},
"---",
{
opcode: 'getAllVariables',
text: 'get all variables [ALLSCOPE]',
disableMonitor: false,
blockType: BlockType.REPORTER,
arguments: {
ALLSCOPE: {
type: ArgumentType.STRING,
menu: "allVariableType"
}
}
},
{
opcode: 'getAllLists',
text: 'get all lists [ALLSCOPE]',
disableMonitor: false,
blockType: BlockType.REPORTER,
arguments: {
ALLSCOPE: {
type: ArgumentType.STRING,
menu: "allVariableScope"
}
}
},
"---",
{
blockType: BlockType.LABEL,
text: "Potentially Dangerous"
},
{
opcode: 'deleteCostume',
text: formatMessage({
id: 'jgRuntime.blocks.deleteCostume',
default: 'delete costume at index [COSTUME]',
description: 'Deletes a costume at the specified index.'
}),
blockType: BlockType.COMMAND,
arguments: {
COSTUME: {
type: ArgumentType.NUMBER,
defaultValue: 1
}
}
},
{
opcode: 'deleteSound',
text: formatMessage({
id: 'jgRuntime.blocks.deleteSound',
default: 'delete sound at index [SOUND]',
description: 'Deletes a sound at the specified index.'
}),
blockType: BlockType.COMMAND,
arguments: {
SOUND: {
type: ArgumentType.NUMBER,
defaultValue: 1
}
}
},
"---",
{
opcode: 'variables_deleteVariable',
text: 'delete variable named [NAME] in [SCOPE]',
blockType: BlockType.COMMAND,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "my variable" },
SCOPE: { type: ArgumentType.STRING, menu: "variableTypes" }
}
},
{
opcode: 'variables_deleteList',
text: 'delete list named [NAME] in [SCOPE]',
blockType: BlockType.COMMAND,
arguments: {
NAME: { type: ArgumentType.STRING, defaultValue: "list" },
SCOPE: { type: ArgumentType.STRING, menu: "variableScope" }
}
},
"---",
{
opcode: 'deleteSprite',
text: formatMessage({
id: 'jgRuntime.blocks.deleteSprite',
default: 'delete sprite named [NAME]',
description: 'Deletes a sprite with the specified name.'
}),
blockType: BlockType.COMMAND,
arguments: {
NAME: {
type: ArgumentType.STRING,
defaultValue: "Sprite1"
}
}
},
],
menus: {
objectType: {
acceptReporters: true,
items: [
"sprite", "costume", "sound"
].map(item => ({ text: item, value: item }))
},
variableScope: {
acceptReporters: true,
items: [
"all sprites", "this sprite"
].map(item => ({ text: item, value: item }))
},
allVariableScope: {
acceptReporters: true,
items: [
"for all sprites", "in every sprite", "in this sprite"
].map(item => ({ text: item, value: item }))
},
allVariableType: {
acceptReporters: true,
items: [
"for all sprites", "in every sprite",
"in this sprite", "in the cloud"
].map(item => ({ text: item, value: item }))
},
variableTypes: {
acceptReporters: true,
items: [
"all sprites", "this sprite", "cloud"
].map(item => ({ text: item, value: item }))
},
cloneLimit: {
items: [
'100', '128', '300', '500',
'1000', '1024', '5000',
'10000', '16384', 'Infinity'
],
isTypeable: true,
isNumeric: true
},
runtimeConfig: {
acceptReporters: true,
items: [
"turbo mode",
"high quality pen",
"offscreen sprites",
"remove miscellaneous limits",
"disable offscreen rendering",
"interpolation",
"warp timer"
]
},
renderConfigCappable: {
acceptReporters: true,
items: ["animated text resolution"]
},
renderConfigNumber: {
acceptReporters: true,
items: ["animated text resolution"]
},
onoff: ["on", "off"],
costumeMimeType: ["png", "bmp", "jpg", "jpeg", "jfif", "webp", "gif", "vector"],
cappableSettings: ["uncapped", "capped", "fixed"]
}
};
}
// utils
_generateScratchId() {
const soup = "!#%()*+,-./:;=?@[]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const id = [];
for (let i = 0; i < 20; i++) { id[i] = soup.charAt(Math.random() * soup.length) }
return id.join("");
}
// blocks
addCostumeUrl(args, util) {
const targetId = util.target.id;
return new Promise(resolve => {
fetch(args.URL, { method: 'GET' }).then(x => x.blob().then(blob => {
const costumeHasForcedMime = !!args.costtype;
const costumeForcedMimeBitmap = args.costtype !== "vector";
if (!(
(this._typeIsBitmap(blob.type)) || (blob.type === 'image/svg+xml')
) && !costumeHasForcedMime) {
resolve();
throw new Error(`Invalid mime type: "${blob.type}"`);
}
const assetType = (costumeHasForcedMime ? costumeForcedMimeBitmap : this._typeIsBitmap(blob.type)) ? this.runtime.storage.AssetType.ImageBitmap : this.runtime.storage.AssetType.ImageVector;
const dataType = costumeHasForcedMime ? (costumeForcedMimeBitmap ? args.costtype : 'svg') : (blob.type === 'image/svg+xml' ? 'svg' : blob.type.split('/')[1]);
blob.arrayBuffer().then(buffer => {
const data = costumeHasForcedMime ? (!costumeForcedMimeBitmap ? buffer : new Uint8Array(buffer)) : (dataType === 'image/svg+xml'
? buffer : new Uint8Array(buffer));
const asset = this.runtime.storage.createAsset(assetType, dataType, data, null, true);
const name = `${asset.assetId}.${asset.dataFormat}`;
const spriteJson = { asset: asset, md5ext: name, name: args.name };
const request = vm.addCostume(name, spriteJson, targetId);
if (request.then) request.then(resolve);
else resolve();
})
.catch(err => {
console.error(`Failed to Load Costume: ${err}`);
resolve();
});
}));
});
}
addCostumeUrlForceMime(args, util) {
this.addCostumeUrl(args, util);
}
deleteCostume(args, util) {
const index = Math.round(Cast.toNumber(args.COSTUME)) - 1;
if (index < 0) return;
util.target.deleteCostume(index);
}
deleteSound(args, util) {
const index = Math.round(Cast.toNumber(args.SOUND)) - 1;
if (index < 0) return;
util.target.deleteSound(index);
}
getIndexOfCostume(args, util) { return util.target.getCostumeIndexByName(args.costume) + 1 }
getIndexOfSound(args, util) {
let index = 0;
const sounds = util.target.getSounds();
for (let i = 0; i < sounds.length; i++) {
if (sounds[i].name === args.NAME) index = i + 1;
}
return index;
}
setStageSize(args) {
if (vm) vm.setStageSize(
Math.max(1, Cast.toNumber(args.WIDTH)), Math.max(1, Cast.toNumber(args.HEIGHT))
);
}
turboModeEnabled() { return this.runtime.turboMode }
amountOfClones() { return this.runtime._cloneCounter }
getStageWidth() { return this.runtime.stageWidth }
getStageHeight() { return this.runtime.stageHeight }
getMaxFrameRate() { return this.runtime.frameLoop.framerate }
getIsClone(_, util) { return !(util.target.isOriginal) }
changeRenderingCapping(args) {
const option = Cast.toString(args.OPTION).toLowerCase();
const capping = Cast.toString(args.CAPPED).toLowerCase();
switch (option) {
case "animated text resolution": {
this.runtime.renderer.customRenderConfig.textCostumeResolution.fixed = false;
this.runtime.renderer.customRenderConfig.textCostumeResolution.capped = false;
if (capping === "fixed") this.runtime.renderer.customRenderConfig.textCostumeResolution.fixed = true;
else if (capping === "capped") this.runtime.renderer.customRenderConfig.textCostumeResolution.capped = true;
break;
}
}
this.runtime.renderer.dirty = true;
this.runtime.requestRedraw();
}
setRenderingNumber(args) {
const option = Cast.toString(args.OPTION).toLowerCase();
const number = Cast.toNumber(args.NUM);
switch (option) {
case "animated text resolution": {
this.runtime.renderer.customRenderConfig.textCostumeResolution.value = number;
break;
}
case "max texture scale for new svg images": {
this.runtime.renderer.setMaxTextureDimension(number);
break;
}
}
this.runtime.renderer.dirty = true;
this.runtime.requestRedraw();
}
updateRuntimeConfig(args) {
const enabled = Cast.toString(args.ENABLED).toLowerCase() === 'on';
switch (Cast.toString(args.OPTION).toLowerCase()) {
case 'turbo mode': return vm.setTurboMode(enabled);
case "high quality pen": return this.runtime.renderer.setUseHighQualityRender(enabled);
case "offscreen sprites": return this.runtime.setRuntimeOptions({ fencing: !enabled });
case "remove miscellaneous limits": return this.runtime.setRuntimeOptions({ miscLimits: !enabled });
case "disable offscreen rendering": return this.runtime.setRuntimeOptions({ disableOffscreenRendering: enabled });
case "interpolation": return vm.setInterpolation(enabled);
case "warp timer": return this.runtime.setCompilerOptions({ warpTimer: enabled });
}
}
runtimeConfigEnabled(args) {
switch (Cast.toString(args.OPTION).toLowerCase()) {
case 'turbo mode': return this.runtime.turboMode;
case "high quality pen": return this.runtime.renderer.useHighQualityRender;
case "offscreen sprites": return !this.runtime.runtimeOptions.fencing;
case "remove miscellaneous limits": return !this.runtime.runtimeOptions.miscLimits;
case "disable offscreen rendering": return this.runtime.runtimeOptions.disableOffscreenRendering;
case "interpolation": return this.runtime.interpolationEnabled;
case "warp timer": return this.runtime.compilerOptions.warpTimer;
default: return false;
}
}
setMaxClones(args) {
const limit = Math.round(Cast.toNumber(args.MAX));
this.runtime.vm.setRuntimeOptions({ maxClones: limit });
}
maxAmountOfClones() { return this.runtime.runtimeOptions.maxClones }
setBackgroundColor(args) {
let RGB;
if (typeof args.COLOR === "number") {
RGB = Cast.toRgbColorObject(args.COLOR);
this.runtime.renderer.setBackgroundColor(RGB.r / 255, RGB.g / 255, RGB.b / 255);
} else {
RGB = Cast.toString(args.COLOR);
RGB = RGB.startsWith("#") ? RGB.slice(1) : RGB;
this.runtime.renderer.setBackgroundColor(
parseInt(RGB.slice(0, 2), 16) / 255,
parseInt(RGB.slice(2, 4), 16) / 255,
parseInt(RGB.slice(4, 6), 16) / 255,
RGB.length === 8 ? parseInt(RGB.slice(6, 8), 16) / 255 : 1
)
}
}
getBackgroundColor() {
const colorArray = this.runtime.renderer._backgroundColor3b;
const colorObject = {
r: Math.round(Cast.toNumber(colorArray[0])),
g: Math.round(Cast.toNumber(colorArray[1])),
b: Math.round(Cast.toNumber(colorArray[2]))
};
const hex = Color.rgbToHex(colorObject);
return hex;
}
// SharkPool, edited by JeremyGamer13
pauseScript(args, util) {
const scriptName = Cast.toString(args.NAME);
const state = util.stackFrame.pausedScript;
if (!state) {
this.pausedScripts[scriptName] = true;
util.stackFrame.pausedScript = scriptName;
util.yield();
} else if (state in this.pausedScripts) {
util.yield();
}
}
unpauseScript(args) {
const scriptName = Cast.toString(args.NAME);
if (scriptName in this.pausedScripts) {
delete this.pausedScripts[scriptName];
}
}
isScriptPaused(args) {
const scriptName = Cast.toString(args.NAME);
return scriptName in this.pausedScripts;
}
setMaxFrameRate(args) {
let frameRate = Cast.toNumber(args.FRAMERATE);
this.runtime.frameLoop.setFramerate(frameRate);
}
deleteSprite(args) {
const target = this.runtime.getSpriteTargetByName(args.NAME);
if (!target) return;
vm.deleteSpriteInternal(target.id);
}
getDataOption(args, util) {
switch (args.OPTION) {
case "sprite": {
const sprites = this.runtime.targets.filter(target => target.isOriginal);
const sprite = sprites.filter(sprite => sprite.sprite.name === args.NAME)[0];
if (!sprite) return "[]";
return new Promise(resolve => {
vm.exportSprite(sprite.id).then(blob => {
blob.arrayBuffer().then(arrayBuffer => {
const array = BufferUtil.bufferToArray(arrayBuffer);
const stringified = JSON.stringify(array);
resolve(stringified);
}).catch(() => resolve("[]"));
}).catch(() => resolve("[]"));
});
}
case "costume": {
const costumes = util.target.getCostumes();
const index = util.target.getCostumeIndexByName(args.NAME);
if (!costumes[index]) return "[]";
const costume = costumes[index];
const data = costume.asset.data;
const array = BufferUtil.bufferToArray(data.buffer);
return JSON.stringify(array);
}
case "sound": {
const sounds = util.target.getSounds();
const index = this.getIndexOfSound(args, util) - 1;
if (!sounds[index]) return "[]";
const sound = sounds[index];
const data = sound.asset.data;
const array = BufferUtil.bufferToArray(data.buffer);
return JSON.stringify(array);
}
default: return "[]";
}
}
getDataUriOption(args, util) {
switch (args.OPTION) {
case "sprite": {
const sprites = this.runtime.targets.filter(target => target.isOriginal);
const sprite = sprites.filter(sprite => sprite.sprite.name === args.NAME)[0];
if (!sprite) return "";
return new Promise(resolve => {
vm.exportSprite(sprite.id).then(blob => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => resolve("");
reader.onabort = () => resolve("");
reader.readAsDataURL(blob);
}).catch(() => resolve(""));
});
}
case "costume": {
const costumes = util.target.getCostumes();
const index = util.target.getCostumeIndexByName(args.NAME);
if (!costumes[index]) return "";
const costume = costumes[index];
return costume.asset.encodeDataURI();
}
case "sound": {
const sounds = util.target.getSounds();
const index = this.getIndexOfSound(args, util) - 1;
if (!sounds[index]) return "";
const sound = sounds[index];
return sound.asset.encodeDataURI();
}
default: return "";
}
}
getAllSprites() {
return JSON.stringify(this.runtime.targets.filter(target => target.isOriginal && !target.isStage).map(target => target.sprite.name));
}
getAllCostumes(_, util) {
const costumes = util.target.getCostumes();
return JSON.stringify(costumes.map(costume => costume.name));
}
getAllSounds(_, util) {
const sounds = util.target.getSounds();
return JSON.stringify(sounds.map(sound => sound.name));
}
getAllFonts() {
const fonts = this.runtime.fontManager.getFonts();
return JSON.stringify(fonts.map(font => font.name));
}
loadProjectDataUrl(args) {
const url = Cast.toString(args.URL);
if (typeof ScratchBlocks !== "undefined") {
// We are in the editor. Ask before loading a new project to avoid unrecoverable data loss.
if (!confirm(`Runtime Extension - Editor: Are you sure you want to load a new project?\nEverything in the current project will be permanently deleted.`)) {
return;
}
}
console.log("Loading project from custom source...");
fetch(url)
.then((r) => r.arrayBuffer())
.then((buffer) => vm.loadProject(buffer))
.then(() => {
console.log("Loaded project!");
vm.greenFlag();
})
.catch((error) => {
console.log("Error loading custom project;", error);
});
}
getProjectDataUrl() {
return new Promise((resolve) => {
const failingUrl = 'data:application/octet-stream;base64,';
vm.saveProjectSb3().then(blob => {
const fileReader = new FileReader();
fileReader.onload = () => { resolve(fileReader.result); };
fileReader.onerror = () => { resolve(failingUrl) }
fileReader.readAsDataURL(blob);
}).catch(() => { resolve(failingUrl) });
});
}
getAllVariables(args, util) {
switch (args.ALLSCOPE) {
case "for all sprites": {
const stage = this.runtime.getTargetForStage();
if (!stage) return "[]";
const variables = stage.variables;
if (!variables) return "[]";
return JSON.stringify(Object.values(variables).filter(v => v.type !== "list").map(v => v.name));
}
case "in every sprite": {
const targets = this.runtime.targets;
if (!targets) return "[]";
const variables = targets.filter(t => t.isOriginal).map(t => t.variables);
if (!variables) return "[]";
return JSON.stringify(variables.map(v => Object.values(v)).map(v => v.filter(v => v.type !== "list").map(v => v.name)).flat(1));
}
case "in this sprite": {
const target = util.target;
if (!target) return "[]";
const variables = target.variables;
if (!variables) return "[]";
return JSON.stringify(Object.values(variables).filter(v => v.type !== "list").map(v => v.name));
}
case "in the cloud": {
const stage = this.runtime.getTargetForStage();
if (!stage) return "[]";
const variables = stage.variables;
if (!variables) return "[]";
return JSON.stringify(Object.values(variables).filter(v => v.type !== "list").filter(v => v.isCloud === true).map(v => v.name));
}
default: return "[]";
}
}
getAllLists(args, util) {
switch (args.ALLSCOPE) {
case "for all sprites": {
const stage = this.runtime.getTargetForStage();
if (!stage) return "[]";
const variables = stage.variables;
if (!variables) return "[]";
return JSON.stringify(Object.values(variables).filter(v => v.type === "list").map(v => v.name));
}
case "in every sprite": {
const targets = this.runtime.targets;
if (!targets) return "[]";
const variables = targets.filter(t => t.isOriginal).map(t => t.variables);
if (!variables) return "[]";
return JSON.stringify(variables.map(v => Object.values(v)).map(v => v.filter(v => v.type === "list").map(v => v.name)).flat(1));
}
case "in this sprite": {
const target = util.target;
if (!target) return "[]";
const variables = target.variables;
if (!variables) return "[]";
return JSON.stringify(Object.values(variables).filter(v => v.type === "list").map(v => v.name));
}
default: return "[]";
}
}
// ShovelUtils
getFrameRate() { return fps }
addSoundUrl(args, util) {
const targetId = util.target.id;
return new Promise((resolve) => {
fetch(args.URL)
.then((r) => r.arrayBuffer())
.then((arrayBuffer) => {
const storage = this.runtime.storage;
const asset = new storage.Asset(
storage.AssetType.Sound, null, storage.DataFormat.MP3,
new Uint8Array(arrayBuffer), true
);
resolve(vm.addSound({
md5: asset.assetId + '.' + asset.dataFormat,
asset: asset, name: args.NAME
}, targetId));
}).catch(resolve);
})
}
// GameUtils
addSpriteUrl(args) {
return new Promise((resolve) => {
fetch(args.URL).then(response => {
response.arrayBuffer().then(arrayBuffer => {
vm.addSprite(arrayBuffer).finally(resolve);
}).catch(resolve);
}).catch(resolve);
});
}
// variables
variables_createVariable(args, util) {
const variableName = args.NAME;
switch (args.SCOPE) {
case "all sprites": return this.runtime.createNewGlobalVariable(variableName);
case "this sprite": return util.target.createVariable(this._generateScratchId(), variableName, "");
}
}
variables_createCloudVariable(args) {
const variableName = `β ${args.NAME}`;
const stage = this.runtime.getTargetForStage();
if (!stage) return;
const id = this._generateScratchId();
stage.createVariable(id, variableName, "", true);
}
variables_createList(args, util) {
const variableName = args.NAME;
switch (args.SCOPE) {
case "all sprites": return this.runtime.createNewGlobalVariable(variableName, null, "list");
case "this sprite": return util.target.createVariable(this._generateScratchId(), variableName, "list");
}
}
variables_getVariable(args, util) {
const variableName = args.NAME;
let target;
let isCloud = false;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else if (args.SCOPE === "cloud") {
target = this.runtime.getTargetForStage();
isCloud = true;
} else return "";
const variables = Object.values(target.variables).filter(variable => variable.type !== "list").filter(variable => {
if (variable.isCloud) return String(variable.name).replace("β ", "") === variableName;
if (isCloud) return false; // above check should have already told us its a cloud variable
return variable.name === variableName;
});
if (!variables) return "";
const variable = variables[0];
if (!variable) return "";
return variable.value;
}
variables_getList(args, util) {
const variableName = args.NAME;
let target;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else return "[]";
const variables = Object.values(target.variables).filter(v => v.type === "list").filter(v => v.name === variableName);
if (!variables) return "[]";
const variable = variables[0];
if (!variable) return "[]";
return JSON.stringify(variable.value);
}
variables_deleteVariable(args, util) {
const variableName = args.NAME;
let target, isCloud = false;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else if (args.SCOPE === "cloud") {
target = this.runtime.getTargetForStage();
isCloud = true;
} else return;
const variables = Object.values(target.variables).filter(v => v.type !== "list").filter(variable => {
if (variable.isCloud) return String(variable.name).replace("β ", "") === variableName;
if (isCloud) return false; // above check should have already told us its a cloud variable
return variable.name === variableName;
});
if (!variables) return;
const variable = variables[0];
if (!variable) return;
return target.deleteVariable(variable.id);
}
variables_deleteList(args, util) {
const variableName = args.NAME;
let target;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else return;
const variables = Object.values(target.variables).filter(v => v.type === "list").filter(v => v.name === variableName);
if (!variables) return;
const variable = variables[0];
if (!variable) return;
return target.deleteVariable(variable.id);
}
variables_existsVariable(args, util) {
const variableName = args.NAME;
let target, isCloud = false;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else if (args.SCOPE === "cloud") {
target = this.runtime.getTargetForStage();
isCloud = true;
} else return false;
const variables = Object.values(target.variables).filter(v => v.type !== "list").filter(variable => {
if (variable.isCloud) return String(variable.name).replace("β ", "") === variableName;
if (isCloud) return false; // above check should have already told us its a cloud variable
return variable.name === variableName;
});
if (!variables) return false;
const variable = variables[0];
if (!variable) return false;
return true;
}
variables_existsList(args, util) {
const variableName = args.NAME;
let target;
if (args.SCOPE === "all sprites") target = this.runtime.getTargetForStage();
else if (args.SCOPE === "this sprite") target = util.target;
else return false;
const variables = Object.values(target.variables).filter(v => v.type === "list").filter(v => v.name === variableName);
if (!variables) return false;
const variable = variables[0];
if (!variable) return false;
return true;
}
}
module.exports = JgRuntimeBlocks;
|