Upload 819 files
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .browserslistrc +6 -0
- .editorconfig +11 -0
- .eslintignore +5 -0
- .eslintrc.js +3 -0
- .gitattributes +47 -59
- .github/ISSUE_TEMPLATE.md +15 -0
- .github/PULL_REQUEST_TEMPLATE.md +15 -0
- .github/workflows/nodejs.yml +20 -0
- .gitignore +22 -0
- .gitpod.yml +11 -0
- .idx/dev.nix +50 -0
- .jsdoc.json +20 -0
- .npmignore +19 -0
- .travis.yml +74 -0
- .tx/config +8 -0
- LICENSE +14 -0
- README.md +152 -0
- TRADEMARK +1 -0
- docs/extensions.md +527 -0
- package-lock.json +0 -0
- package.json +105 -0
- renovate.json5 +7 -0
- src/.eslintrc.js +32 -0
- src/blocks/pm_live tests.js +38 -0
- src/blocks/scratch3_control.js +345 -0
- src/blocks/scratch3_core_example.js +86 -0
- src/blocks/scratch3_data.js +327 -0
- src/blocks/scratch3_event.js +219 -0
- src/blocks/scratch3_looks.js +996 -0
- src/blocks/scratch3_motion.js +532 -0
- src/blocks/scratch3_operators.js +412 -0
- src/blocks/scratch3_procedures.js +124 -0
- src/blocks/scratch3_sensing.js +659 -0
- src/blocks/scratch3_sound.js +537 -0
- src/cli/index.js +41 -0
- src/compiler/compat-block-utility.js +62 -0
- src/compiler/compat-blocks.js +170 -0
- src/compiler/compile.js +37 -0
- src/compiler/environment.js +20 -0
- src/compiler/intermediate.js +115 -0
- src/compiler/irgen.js +2475 -0
- src/compiler/jsexecute.js +715 -0
- src/compiler/jsgen.js +2114 -0
- src/compiler/variable-pool.js +21 -0
- src/dispatch/central-dispatch.js +141 -0
- src/dispatch/shared-dispatch.js +237 -0
- src/dispatch/worker-dispatch.js +113 -0
- src/engine/adapter.js +185 -0
- src/engine/block-utility.js +261 -0
- src/engine/blocks-execute-cache.js +19 -0
.browserslistrc
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chrome >= 70
|
2 |
+
chromeandroid >= 70
|
3 |
+
ios >= 12
|
4 |
+
safari >= 12
|
5 |
+
edge >= 17
|
6 |
+
firefox >= 68
|
.editorconfig
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
root = true
|
2 |
+
|
3 |
+
[*]
|
4 |
+
end_of_line = lf
|
5 |
+
insert_final_newline = true
|
6 |
+
charset = utf-8
|
7 |
+
indent_size = 4
|
8 |
+
trim_trailing_whitespace = true
|
9 |
+
|
10 |
+
[*.{js,html}]
|
11 |
+
indent_style = space
|
.eslintignore
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
coverage/*
|
2 |
+
dist/*
|
3 |
+
node_modules/*
|
4 |
+
playground/*
|
5 |
+
benchmark/*
|
.eslintrc.js
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
module.exports = {
|
2 |
+
extends: ['scratch', 'scratch/node', 'scratch/es6']
|
3 |
+
};
|
.gitattributes
CHANGED
@@ -1,59 +1,47 @@
|
|
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 |
-
# Image files - uncompressed
|
49 |
-
*.bmp filter=lfs diff=lfs merge=lfs -text
|
50 |
-
*.gif filter=lfs diff=lfs merge=lfs -text
|
51 |
-
*.png filter=lfs diff=lfs merge=lfs -text
|
52 |
-
*.tiff filter=lfs diff=lfs merge=lfs -text
|
53 |
-
# Image files - compressed
|
54 |
-
*.jpg filter=lfs diff=lfs merge=lfs -text
|
55 |
-
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
56 |
-
*.webp filter=lfs diff=lfs merge=lfs -text
|
57 |
-
# Video files - compressed
|
58 |
-
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
59 |
-
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
1 |
+
# Set the default behavior, in case people don't have core.autocrlf set.
|
2 |
+
* text=auto
|
3 |
+
|
4 |
+
# Explicitly specify line endings for as many files as possible.
|
5 |
+
# People who (for example) rsync between Windows and Linux need this.
|
6 |
+
|
7 |
+
# File types which we know are binary
|
8 |
+
*.sb2 binary
|
9 |
+
|
10 |
+
# Prefer LF for most file types
|
11 |
+
*.css text eol=lf
|
12 |
+
*.frag text eol=lf
|
13 |
+
*.htm text eol=lf
|
14 |
+
*.html text eol=lf
|
15 |
+
*.iml text eol=lf
|
16 |
+
*.js text eol=lf
|
17 |
+
*.js.map text eol=lf
|
18 |
+
*.json text eol=lf
|
19 |
+
*.json5 text eol=lf
|
20 |
+
*.md text eol=lf
|
21 |
+
*.vert text eol=lf
|
22 |
+
*.xml text eol=lf
|
23 |
+
*.yml text eol=lf
|
24 |
+
|
25 |
+
# Prefer LF for these files
|
26 |
+
.editorconfig text eol=lf
|
27 |
+
.eslintignore text eol=lf
|
28 |
+
.eslintrc text eol=lf
|
29 |
+
.gitattributes text eol=lf
|
30 |
+
.gitignore text eol=lf
|
31 |
+
.gitmodules text eol=lf
|
32 |
+
.npmignore text eol=lf
|
33 |
+
LICENSE text eol=lf
|
34 |
+
Makefile text eol=lf
|
35 |
+
README text eol=lf
|
36 |
+
TRADEMARK text eol=lf
|
37 |
+
|
38 |
+
# Use CRLF for Windows-specific file types
|
39 |
+
src/extensions/jg_3dVr/headset.pdn filter=lfs diff=lfs merge=lfs -text
|
40 |
+
test/fixtures/complex.sb2 filter=lfs diff=lfs merge=lfs -text
|
41 |
+
test/fixtures/event.sb2 filter=lfs diff=lfs merge=lfs -text
|
42 |
+
test/fixtures/execute/sprite-number-name.sb2 filter=lfs diff=lfs merge=lfs -text
|
43 |
+
test/fixtures/load-extensions/confirm-load/pen-dolphin-3d.sb2 filter=lfs diff=lfs merge=lfs -text
|
44 |
+
test/fixtures/load-extensions/confirm-load/pen-dolphin-3d.sb3 filter=lfs diff=lfs merge=lfs -text
|
45 |
+
test/fixtures/looks.sb2 filter=lfs diff=lfs merge=lfs -text
|
46 |
+
test/fixtures/ordering.sb2 filter=lfs diff=lfs merge=lfs -text
|
47 |
+
test/fixtures/pen.sb2 filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
.github/ISSUE_TEMPLATE.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Expected Behavior
|
2 |
+
|
3 |
+
_Please describe what should happen_
|
4 |
+
|
5 |
+
### Actual Behavior
|
6 |
+
|
7 |
+
_Describe what actually happens_
|
8 |
+
|
9 |
+
### Steps to Reproduce
|
10 |
+
|
11 |
+
_Explain what someone needs to do in order to see what's described in *Actual behavior* above_
|
12 |
+
|
13 |
+
### Operating System and Browser
|
14 |
+
|
15 |
+
_e.g. Mac OS 10.11.6 Safari 10.0_
|
.github/PULL_REQUEST_TEMPLATE.md
ADDED
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Resolves
|
2 |
+
|
3 |
+
_What Github issue does this resolve (please include link)?_
|
4 |
+
|
5 |
+
### Proposed Changes
|
6 |
+
|
7 |
+
_Describe what this Pull Request does_
|
8 |
+
|
9 |
+
### Reason for Changes
|
10 |
+
|
11 |
+
_Explain why these changes should be made_
|
12 |
+
|
13 |
+
### Test Coverage
|
14 |
+
|
15 |
+
_Please show how you have added tests to cover your changes_
|
.github/workflows/nodejs.yml
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Remote Dispatch Action Initiator
|
2 |
+
#test
|
3 |
+
on: [push]
|
4 |
+
|
5 |
+
jobs:
|
6 |
+
ping-pong:
|
7 |
+
runs-on: ubuntu-latest
|
8 |
+
steps:
|
9 |
+
- name: Repository Dispatch
|
10 |
+
uses: peter-evans/[email protected]
|
11 |
+
with:
|
12 |
+
token: ${{ secrets.t }}
|
13 |
+
event-type: update
|
14 |
+
repository: PenguinMod/penguinmod.github.io
|
15 |
+
- name: Repository Dispatch2
|
16 |
+
uses: peter-evans/[email protected]
|
17 |
+
with:
|
18 |
+
token: ${{ secrets.t }}
|
19 |
+
event-type: update
|
20 |
+
repository: PenguinMod/PenguinMod-Packager
|
.gitignore
ADDED
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Mac OS
|
2 |
+
.DS_Store
|
3 |
+
|
4 |
+
# NPM
|
5 |
+
/node_modules
|
6 |
+
npm-*
|
7 |
+
|
8 |
+
# Testing
|
9 |
+
/.nyc_output
|
10 |
+
/coverage
|
11 |
+
|
12 |
+
# Editor
|
13 |
+
/.idea
|
14 |
+
/.vscode
|
15 |
+
|
16 |
+
# Build
|
17 |
+
/dist
|
18 |
+
/playground
|
19 |
+
/benchmark
|
20 |
+
|
21 |
+
# Localization
|
22 |
+
/translations
|
.gitpod.yml
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# This configuration file was automatically generated by Gitpod.
|
2 |
+
# Please adjust to your needs (see https://www.gitpod.io/docs/introduction/learn-gitpod/gitpod-yaml)
|
3 |
+
# and commit this file to your remote git repository to share the goodness with others.
|
4 |
+
|
5 |
+
# Learn more from ready-to-use templates: https://www.gitpod.io/docs/introduction/getting-started/quickstart
|
6 |
+
|
7 |
+
tasks:
|
8 |
+
- init: npm install && npm run build
|
9 |
+
command: npm run start
|
10 |
+
|
11 |
+
|
.idx/dev.nix
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# To learn more about how to use Nix to configure your environment
|
2 |
+
# see: https://developers.google.com/idx/guides/customize-idx-env
|
3 |
+
{ pkgs, ... }: {
|
4 |
+
# Which nixpkgs channel to use.
|
5 |
+
channel = "stable-24.05"; # or "unstable"
|
6 |
+
|
7 |
+
# Use https://search.nixos.org/packages to find packages
|
8 |
+
packages = [
|
9 |
+
pkgs.nodejs_20
|
10 |
+
];
|
11 |
+
|
12 |
+
# Sets environment variables in the workspace
|
13 |
+
env = {};
|
14 |
+
idx = {
|
15 |
+
# Search for the extensions you want on https://open-vsx.org/ and use "publisher.id"
|
16 |
+
extensions = [
|
17 |
+
# "vscodevim.vim"
|
18 |
+
];
|
19 |
+
|
20 |
+
# Enable previews
|
21 |
+
previews = {
|
22 |
+
enable = true;
|
23 |
+
previews = {
|
24 |
+
# web = {
|
25 |
+
# # Example: run "npm run dev" with PORT set to IDX's defined port for previews,
|
26 |
+
# # and show it in IDX's web preview panel
|
27 |
+
# command = ["npm" "run" "dev"];
|
28 |
+
# manager = "web";
|
29 |
+
# env = {
|
30 |
+
# # Environment variables to set for your server
|
31 |
+
# PORT = "$PORT";
|
32 |
+
# };
|
33 |
+
# };
|
34 |
+
};
|
35 |
+
};
|
36 |
+
|
37 |
+
# Workspace lifecycle hooks
|
38 |
+
workspace = {
|
39 |
+
# Runs when a workspace is first created
|
40 |
+
onCreate = {
|
41 |
+
npm-install = "npm install";
|
42 |
+
};
|
43 |
+
# Runs when the workspace is (re)started
|
44 |
+
onStart = {
|
45 |
+
# Example: start a background task to watch and re-build backend code
|
46 |
+
# watch-backend = "npm run watch-backend";
|
47 |
+
};
|
48 |
+
};
|
49 |
+
};
|
50 |
+
}
|
.jsdoc.json
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"plugins": ["plugins/markdown"],
|
3 |
+
"templates": {
|
4 |
+
"default": {
|
5 |
+
"includeDate": false,
|
6 |
+
"outputSourceFiles": false
|
7 |
+
}
|
8 |
+
},
|
9 |
+
"source": {
|
10 |
+
"include": ["src"]
|
11 |
+
},
|
12 |
+
"opts": {
|
13 |
+
"destination": "playground/docs",
|
14 |
+
"pedantic": true,
|
15 |
+
"private": true,
|
16 |
+
"readme": "README.md",
|
17 |
+
"recurse": true,
|
18 |
+
"template": "node_modules/docdash"
|
19 |
+
}
|
20 |
+
}
|
.npmignore
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Development files
|
2 |
+
.eslintrc.js
|
3 |
+
/.editorconfig
|
4 |
+
/.eslintignore
|
5 |
+
/.gitattributes
|
6 |
+
/.github
|
7 |
+
/.travis.yml
|
8 |
+
/.tx
|
9 |
+
/test
|
10 |
+
|
11 |
+
# Build created files
|
12 |
+
/playground
|
13 |
+
|
14 |
+
# Coverage created files
|
15 |
+
/.nyc_output
|
16 |
+
/coverage
|
17 |
+
|
18 |
+
# Exclude already built packages from testing with npm pack
|
19 |
+
/scratch-vm-*.{tar,tgz}
|
.travis.yml
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
language: node_js
|
2 |
+
node_js:
|
3 |
+
- lts/*
|
4 |
+
env:
|
5 |
+
global:
|
6 |
+
- NODE_ENV=production
|
7 |
+
- NPM_TAG=latest
|
8 |
+
- RELEASE_TIMESTAMP="$(date +'%Y%m%d%H%M%S')"
|
9 |
+
matrix:
|
10 |
+
- NPM_SCRIPT="tap:unit -- --jobs=4"
|
11 |
+
- NPM_SCRIPT="tap:integration -- --jobs=4"
|
12 |
+
cache:
|
13 |
+
directories:
|
14 |
+
- "$HOME/.npm"
|
15 |
+
install:
|
16 |
+
- npm ci --production=false
|
17 |
+
script: npm run $NPM_SCRIPT
|
18 |
+
jobs:
|
19 |
+
include:
|
20 |
+
- env: NPM_SCRIPT=lint
|
21 |
+
- env: NPM_SCRIPT=build
|
22 |
+
if: not (type != pull_request AND (branch =~ /^(develop|master|hotfix\/)/))
|
23 |
+
- stage: release
|
24 |
+
env: NPM_SCRIPT=build
|
25 |
+
before_deploy:
|
26 |
+
- >
|
27 |
+
if [ -z "$BEFORE_DEPLOY_RAN" ]; then
|
28 |
+
VPKG=$($(npm bin)/json -f package.json version)
|
29 |
+
export RELEASE_VERSION=${VPKG}-prerelease.${RELEASE_TIMESTAMP}
|
30 |
+
npm --no-git-tag-version version $RELEASE_VERSION
|
31 |
+
if [[ "$TRAVIS_BRANCH" == hotfix/* ]]; then # double brackets are important for matching the wildcard
|
32 |
+
export NPM_TAG=hotfix
|
33 |
+
fi
|
34 |
+
git config --global user.email "$(git log --pretty=format:"%ae" -n1)"
|
35 |
+
git config --global user.name "$(git log --pretty=format:"%an" -n1)"
|
36 |
+
export BEFORE_DEPLOY_RAN=true
|
37 |
+
fi
|
38 |
+
deploy:
|
39 |
+
- provider: npm
|
40 |
+
on:
|
41 |
+
branch:
|
42 |
+
- master
|
43 |
+
- develop
|
44 |
+
- hotfix/*
|
45 |
+
condition: $TRAVIS_EVENT_TYPE != cron
|
46 |
+
skip_cleanup: true
|
47 |
+
email: $NPM_EMAIL
|
48 |
+
api_key: $NPM_TOKEN
|
49 |
+
tag: $NPM_TAG
|
50 |
+
- provider: script
|
51 |
+
on:
|
52 |
+
branch:
|
53 |
+
- master
|
54 |
+
- develop
|
55 |
+
- hotfix/*
|
56 |
+
condition: $TRAVIS_EVENT_TYPE != cron
|
57 |
+
skip_cleanup: true
|
58 |
+
script: if npm info | grep -q $RELEASE_VERSION; then git tag $RELEASE_VERSION && git push https://${GH_TOKEN}@github.com/${TRAVIS_REPO_SLUG}.git $RELEASE_VERSION; fi
|
59 |
+
- provider: script
|
60 |
+
on:
|
61 |
+
all_branches: true
|
62 |
+
condition: $TRAVIS_EVENT_TYPE != cron
|
63 |
+
skip_cleanup: true
|
64 |
+
script: npm run --silent deploy -- -x -r $GH_PAGES_REPO
|
65 |
+
- provider: script
|
66 |
+
on:
|
67 |
+
branch: develop
|
68 |
+
condition: $TRAVIS_EVENT_TYPE == cron
|
69 |
+
skip_cleanup: true
|
70 |
+
script: npm run i18n:src && npm run i18n:push
|
71 |
+
stages:
|
72 |
+
- test
|
73 |
+
- name: release
|
74 |
+
if: type != pull_request AND (branch =~ /^(develop|master|hotfix\/)/)
|
.tx/config
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[main]
|
2 |
+
host = https://www.transifex.com
|
3 |
+
|
4 |
+
[scratch-editor.extensions]
|
5 |
+
file_filter = translations/core/<lang>.json
|
6 |
+
source_file = translations/core/en.json
|
7 |
+
source_lang = en
|
8 |
+
type = CHROME
|
LICENSE
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2016, Massachusetts Institute of Technology
|
2 |
+
Copyright (c) 2020-2022, Thomas Weber
|
3 |
+
Copyright (c) 2023-2024 Penguinmod
|
4 |
+
All rights reserved.
|
5 |
+
|
6 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
7 |
+
|
8 |
+
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
9 |
+
|
10 |
+
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
11 |
+
|
12 |
+
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
13 |
+
|
14 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
README.md
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## PenguinMod/PenguinMod-Vm
|
2 |
+
|
3 |
+
Modified Scratch VM with a JIT compiler and more features.
|
4 |
+
|
5 |
+
This is a drop-in replacement for LLK/scratch-vm.
|
6 |
+
|
7 |
+
## Setup
|
8 |
+
|
9 |
+
See https://github.com/TurboWarp/scratch-gui/wiki/Getting-Started to setup the complete TurboWarp environment.
|
10 |
+
|
11 |
+
If you just want to play with the VM then it's the same process as upstream scratch-vm.
|
12 |
+
|
13 |
+
## Extension authors
|
14 |
+
|
15 |
+
If you only use the standard reporter, boolean, and command block types, everything should just work without any changes.
|
16 |
+
|
17 |
+
## Compiler Overview
|
18 |
+
|
19 |
+
For a high-level overview of how the compiler works, see https://docs.turbowarp.org/how
|
20 |
+
|
21 |
+
For more technical information, read the code in src/compiler.
|
22 |
+
|
23 |
+
## Public API
|
24 |
+
|
25 |
+
This section was too out of date to be useful. We hope to re-add it as some point.
|
26 |
+
|
27 |
+
<!--
|
28 |
+
|
29 |
+
## scratch-vm
|
30 |
+
#### Scratch VM is a library for representing, running, and maintaining the state of computer programs written using [Scratch Blocks](https://github.com/LLK/scratch-blocks).
|
31 |
+
|
32 |
+
[](https://travis-ci.org/LLK/scratch-vm)
|
33 |
+
[](https://coveralls.io/github/LLK/scratch-vm?branch=develop)
|
34 |
+
|
35 |
+
## Installation
|
36 |
+
This requires you to have Git and Node.js installed.
|
37 |
+
|
38 |
+
To install as a dependency for your own application:
|
39 |
+
```bash
|
40 |
+
npm install scratch-vm
|
41 |
+
```
|
42 |
+
To set up a development environment to edit scratch-vm yourself:
|
43 |
+
```bash
|
44 |
+
git clone https://github.com/LLK/scratch-vm.git
|
45 |
+
cd scratch-vm
|
46 |
+
npm install
|
47 |
+
```
|
48 |
+
|
49 |
+
## Development Server
|
50 |
+
This requires Node.js to be installed.
|
51 |
+
|
52 |
+
For convenience, we've included a development server with the VM. This is sometimes useful when running in an environment that's loading remote resources (e.g., SVGs from the Scratch server). If you would like to use your modified VM with the full Scratch 3.0 GUI, [follow the instructions to link the VM to the GUI](https://github.com/LLK/scratch-gui/wiki/Getting-Started).
|
53 |
+
|
54 |
+
## Running the Development Server
|
55 |
+
Open a Command Prompt or Terminal in the repository and run:
|
56 |
+
```bash
|
57 |
+
npm start
|
58 |
+
```
|
59 |
+
|
60 |
+
## Playground
|
61 |
+
To view the Playground, make sure the dev server's running and go to [http://localhost:8073/playground/](http://localhost:8073/playground/) - you will be directed to the playground, which demonstrates various tools and internal state.
|
62 |
+
|
63 |
+

|
64 |
+
|
65 |
+
|
66 |
+
## Standalone Build
|
67 |
+
```bash
|
68 |
+
npm run build
|
69 |
+
```
|
70 |
+
|
71 |
+
```html
|
72 |
+
<script src="/path/to/dist/web/scratch-vm.js"></script>
|
73 |
+
<script>
|
74 |
+
var vm = new window.VirtualMachine();
|
75 |
+
// do things
|
76 |
+
</script>
|
77 |
+
```
|
78 |
+
|
79 |
+
## How to include in a Node.js App
|
80 |
+
For an extended setup example, check out the /src/playground directory, which includes a fully running VM instance.
|
81 |
+
```js
|
82 |
+
var VirtualMachine = require('scratch-vm');
|
83 |
+
var vm = new VirtualMachine();
|
84 |
+
|
85 |
+
// Block events
|
86 |
+
Scratch.workspace.addChangeListener(vm.blockListener);
|
87 |
+
|
88 |
+
// Run threads
|
89 |
+
vm.start();
|
90 |
+
```
|
91 |
+
|
92 |
+
## Abstract Syntax Tree
|
93 |
+
|
94 |
+
#### Overview
|
95 |
+
The Virtual Machine constructs and maintains the state of an [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree) (AST) by listening to events emitted by the [scratch-blocks](https://github.com/LLK/scratch-blocks) workspace via the `blockListener`. Each target (code-running object, for example, a sprite) keeps an AST for its blocks. At any time, the current state of an AST can be viewed by inspecting the `vm.runtime.targets[...].blocks` object.
|
96 |
+
|
97 |
+
#### Anatomy of a Block
|
98 |
+
The VM's block representation contains all the important information for execution and storage. Here's an example representing the "when key pressed" script on a workspace:
|
99 |
+
```json
|
100 |
+
{
|
101 |
+
"_blocks": {
|
102 |
+
"Q]PK~yJ@BTV8Y~FfISeo": {
|
103 |
+
"id": "Q]PK~yJ@BTV8Y~FfISeo",
|
104 |
+
"opcode": "event_whenkeypressed",
|
105 |
+
"inputs": {
|
106 |
+
},
|
107 |
+
"fields": {
|
108 |
+
"KEY_OPTION": {
|
109 |
+
"name": "KEY_OPTION",
|
110 |
+
"value": "space"
|
111 |
+
}
|
112 |
+
},
|
113 |
+
"next": null,
|
114 |
+
"topLevel": true,
|
115 |
+
"parent": null,
|
116 |
+
"shadow": false,
|
117 |
+
"x": -69.333333333333,
|
118 |
+
"y": 174
|
119 |
+
}
|
120 |
+
},
|
121 |
+
"_scripts": [
|
122 |
+
"Q]PK~yJ@BTV8Y~FfISeo"
|
123 |
+
]
|
124 |
+
}
|
125 |
+
```
|
126 |
+
|
127 |
+
## Testing
|
128 |
+
```bash
|
129 |
+
npm test
|
130 |
+
```
|
131 |
+
|
132 |
+
```bash
|
133 |
+
npm run coverage
|
134 |
+
```
|
135 |
+
|
136 |
+
## Publishing to GitHub Pages
|
137 |
+
```bash
|
138 |
+
npm run deploy
|
139 |
+
```
|
140 |
+
|
141 |
+
This will push the currently built playground to the gh-pages branch of the
|
142 |
+
currently tracked remote. If you would like to change where to push to, add
|
143 |
+
a repo url argument:
|
144 |
+
```bash
|
145 |
+
npm run deploy -- -r <your repo url>
|
146 |
+
```
|
147 |
+
|
148 |
+
## Donate
|
149 |
+
We provide [Scratch](https://scratch.mit.edu) free of charge, and want to keep it that way! Please consider making a [donation](https://secure.donationpay.org/scratchfoundation/) to support our continued engineering, design, community, and resource development efforts. Donations of any size are appreciated. Thank you!
|
150 |
+
|
151 |
+
-->
|
152 |
+
e
|
TRADEMARK
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
The Scratch trademarks, including the Scratch name, logo, the Scratch Cat, Gobo, Pico, Nano, Tera and Giga graphics (the "Marks"), are property of the Massachusetts Institute of Technology (MIT). Marks may not be used to endorse or promote products derived from this software without specific prior written permission.
|
docs/extensions.md
ADDED
@@ -0,0 +1,527 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ratch 3.0 extension development, including the Scratch 3.0
|
4 |
+
extension specification.
|
5 |
+
|
6 |
+
## Types of Extensions
|
7 |
+
|
8 |
+
There are four types of extensions that can define everything from the Scratch's core library (such as the "Looks" and
|
9 |
+
"Operators" categories) to unofficial extensions that can be loaded from a remote URL.
|
10 |
+
|
11 |
+
**Scratch 3.0 does not yet support unofficial extensions.**
|
12 |
+
|
13 |
+
| | Core | Team | Official | Unofficial |
|
14 |
+
| ------------------------------ | ---- | ---- | -------- | ---------- |
|
15 |
+
| Developed by Scratch Team | √ | √ | O | X |
|
16 |
+
| Maintained by Scratch Team | √ | √ | O | X |
|
17 |
+
| Shown in Library | X | √ | √ | X |
|
18 |
+
| Sandboxed | X | X | √ | √ |
|
19 |
+
| Can save projects to community | √ | √ | √ | X |
|
20 |
+
|
21 |
+
## JavaScript Environment
|
22 |
+
|
23 |
+
Most Scratch 3.0 is written using JavaScript features not yet commonly supported by browsers. For compatibility we
|
24 |
+
transpile the code to ES5 before publishing or deploying. Any extension included in the `scratch-vm` repository may
|
25 |
+
use ES6+ features and may use `require` to reference other code within the `scratch-vm` repository.
|
26 |
+
|
27 |
+
Unofficial extensions must be self-contained. Authors of unofficial extensions are responsible for ensuring browser
|
28 |
+
compatibility for those extensions, including transpiling if necessary.
|
29 |
+
|
30 |
+
## Translation
|
31 |
+
|
32 |
+
Scratch extensions use the [ICU message format](http://userguide.icu-project.org/formatparse/messages) to handle
|
33 |
+
translation across languages. For **core, team, and official** extensions, the function `formatMessage` is used to
|
34 |
+
wrap any ICU messages that need to be exported to the [Scratch Transifex group](https://www.transifex.com/llk/public/)
|
35 |
+
for translation.
|
36 |
+
|
37 |
+
**All extensions** may additionally define a `translation_map` object within the `getInfo` function which can provide
|
38 |
+
translations within an extension itself. The "Annotated Example" below provides a more complete illustration of how
|
39 |
+
translation within an extension can be managed. **WARNING:** the `translation_map` feature is currently in the
|
40 |
+
proposal phase and may change before implementation.
|
41 |
+
|
42 |
+
## Backwards Compatibility
|
43 |
+
|
44 |
+
Scratch is designed to be fully backwards compatible. Because of this, block definitions and opcodes should *never*
|
45 |
+
change in a way that could cause previously saved projects to fail to load or to act in unexpected / inconsistent
|
46 |
+
ways.
|
47 |
+
|
48 |
+
## Defining an Extension
|
49 |
+
|
50 |
+
Scratch extensions are defined as a single Javascript class which accepts either a reference to the Scratch
|
51 |
+
[VM](https://github.com/llk/scratch-vm) runtime or a "runtime proxy" which handles communication with the Scratch VM
|
52 |
+
across a well defined worker boundary (i.e. the sandbox).
|
53 |
+
|
54 |
+
```js
|
55 |
+
class SomeBlocks {
|
56 |
+
constructor (runtime) {
|
57 |
+
/**
|
58 |
+
* Store this for later communication with the Scratch VM runtime.
|
59 |
+
* If this extension is running in a sandbox then `runtime` is an async proxy object.
|
60 |
+
* @type {Runtime}
|
61 |
+
*/
|
62 |
+
this.runtime = runtime;
|
63 |
+
}
|
64 |
+
|
65 |
+
// ...
|
66 |
+
}
|
67 |
+
```
|
68 |
+
|
69 |
+
All extensions must define a function called `getInfo` which returns an object that contains the information needed to
|
70 |
+
render both the blocks and the extension itself.
|
71 |
+
|
72 |
+
```js
|
73 |
+
// Core, Team, and Official extensions can `require` VM code:
|
74 |
+
const ArgumentType = require('../../extension-support/argument-type');
|
75 |
+
const BlockType = require('../../extension-support/block-type');
|
76 |
+
|
77 |
+
class SomeBlocks {
|
78 |
+
// ...
|
79 |
+
getInfo () {
|
80 |
+
return {
|
81 |
+
id: 'someBlocks',
|
82 |
+
name: 'Some Blocks',
|
83 |
+
blocks: [
|
84 |
+
{
|
85 |
+
opcode: 'myReporter',
|
86 |
+
blockType: BlockType.REPORTER,
|
87 |
+
text: 'letter [LETTER_NUM] of [TEXT]',
|
88 |
+
arguments: {
|
89 |
+
LETTER_NUM: {
|
90 |
+
type: ArgumentType.STRING,
|
91 |
+
defaultValue: '1'
|
92 |
+
},
|
93 |
+
TEXT: {
|
94 |
+
type: ArgumentType.STRING,
|
95 |
+
defaultValue: 'text'
|
96 |
+
}
|
97 |
+
}
|
98 |
+
}
|
99 |
+
]
|
100 |
+
};
|
101 |
+
}
|
102 |
+
// ...
|
103 |
+
}
|
104 |
+
```
|
105 |
+
|
106 |
+
Finally the extension must define a function for any "opcode" defined in the blocks. For example:
|
107 |
+
|
108 |
+
```js
|
109 |
+
class SomeBlocks {
|
110 |
+
// ...
|
111 |
+
myReporter (args) {
|
112 |
+
return args.TEXT.charAt(args.LETTER_NUM);
|
113 |
+
};
|
114 |
+
// ...
|
115 |
+
}
|
116 |
+
```
|
117 |
+
### Block Arguments
|
118 |
+
In addition to displaying text, blocks can have arguments in the form of slots to take other blocks getting plugged in, or dropdown menus to select an argument value from a list of possible values.
|
119 |
+
|
120 |
+
The possible types of block arguments are as follows:
|
121 |
+
|
122 |
+
- String - a string input, this is a type-able field which also accepts other reporter blocks to be plugged in
|
123 |
+
- Number - an input similar to the string input, but the type-able values are constrained to numbers.
|
124 |
+
- Angle - an input similar to the number input, but it has an additional UI to be able to pick an angle from a
|
125 |
+
circular dial
|
126 |
+
- Boolean - an input for a boolean (hexagonal shaped) reporter block. This field is not type-able.
|
127 |
+
- Color - an input which displays a color swatch. This field has additional UI to pick a color by choosing values for the color's hue, saturation and brightness. Optionally, the defaultValue for the color picker can also be chosen if the extension developer wishes to display the same color every time the extension is added. If the defaultValue is left out, the default behavior of picking a random color when the extension is loaded will be used.
|
128 |
+
- Matrix - an input which displays a 5 x 5 matrix of cells, where each cell can be filled in or clear.
|
129 |
+
- Note - a numeric input which can select a musical note. This field has additional UI to select a note from a
|
130 |
+
visual keyboard.
|
131 |
+
- Image - an inline image displayed on a block. This is a special argument type in that it does not represent a value and does not accept other blocks to be plugged-in in place of this block field. See the section below about "Adding an Inline Image".
|
132 |
+
|
133 |
+
#### Adding an Inline Image
|
134 |
+
In addition to specifying block arguments (an example of string arguments shown in the code snippet above),
|
135 |
+
you can also specify an inline image for the block. You must include a dataURI for the image. If left unspecified, blank space will be allocated for the image and a warning will be logged in the console.
|
136 |
+
You can optionally also specify `flipRTL`, a property indicating whether the image should be flipped horizontally when the editor has a right to left language selected as its locale. By default, the image is not flipped.
|
137 |
+
|
138 |
+
```js
|
139 |
+
return {
|
140 |
+
// ...
|
141 |
+
blocks: [
|
142 |
+
{
|
143 |
+
//...
|
144 |
+
arguments: {
|
145 |
+
MY_IMAGE: {
|
146 |
+
type: ArgumentType.IMAGE,
|
147 |
+
dataURI: 'myImageData',
|
148 |
+
alt: 'This is an image',
|
149 |
+
flipRTL: true
|
150 |
+
}
|
151 |
+
}
|
152 |
+
}
|
153 |
+
]
|
154 |
+
}
|
155 |
+
```
|
156 |
+
|
157 |
+
|
158 |
+
|
159 |
+
|
160 |
+
#### Defining a Menu
|
161 |
+
|
162 |
+
To display a drop-down menu for a block argument, specify the `menu` property of that argument and a matching item in
|
163 |
+
the `menus` section of your extension's definition:
|
164 |
+
|
165 |
+
```js
|
166 |
+
return {
|
167 |
+
// ...
|
168 |
+
blocks: [
|
169 |
+
{
|
170 |
+
// ...
|
171 |
+
arguments: {
|
172 |
+
FOO: {
|
173 |
+
type: ArgumentType.NUMBER,
|
174 |
+
menu: 'fooMenu'
|
175 |
+
}
|
176 |
+
}
|
177 |
+
}
|
178 |
+
],
|
179 |
+
menus: {
|
180 |
+
fooMenu: {
|
181 |
+
items: ['a', 'b', 'c']
|
182 |
+
}
|
183 |
+
}
|
184 |
+
}
|
185 |
+
```
|
186 |
+
|
187 |
+
The items in a menu may be specified with an array or with the name of a function which returns an array. The two
|
188 |
+
simplest forms for menu definitions are:
|
189 |
+
|
190 |
+
```js
|
191 |
+
getInfo () {
|
192 |
+
return {
|
193 |
+
menus: {
|
194 |
+
staticMenu: ['static 1', 'static 2', 'static 3'],
|
195 |
+
dynamicMenu: 'getDynamicMenuItems'
|
196 |
+
}
|
197 |
+
};
|
198 |
+
}
|
199 |
+
// this member function will be called each time the menu opens
|
200 |
+
getDynamicMenuItems () {
|
201 |
+
return ['dynamic 1', 'dynamic 2', 'dynamic 3'];
|
202 |
+
}
|
203 |
+
```
|
204 |
+
|
205 |
+
The examples above are shorthand for these equivalent definitions:
|
206 |
+
|
207 |
+
```js
|
208 |
+
getInfo () {
|
209 |
+
return {
|
210 |
+
menus: {
|
211 |
+
staticMenu: {
|
212 |
+
items: ['static 1', 'static 2', 'static 3']
|
213 |
+
},
|
214 |
+
dynamicMenu: {
|
215 |
+
items: 'getDynamicMenuItems'
|
216 |
+
}
|
217 |
+
}
|
218 |
+
};
|
219 |
+
}
|
220 |
+
// this member function will be called each time the menu opens
|
221 |
+
getDynamicMenuItems () {
|
222 |
+
return ['dynamic 1', 'dynamic 2', 'dynamic 3'];
|
223 |
+
}
|
224 |
+
```
|
225 |
+
|
226 |
+
If a menu item needs a label that doesn't match its value -- for example, if the label needs to be displayed in the
|
227 |
+
user's language but the value needs to stay constant -- the menu item may be an object instead of a string. This works
|
228 |
+
for both static and dynamic menu items:
|
229 |
+
|
230 |
+
```js
|
231 |
+
menus: {
|
232 |
+
staticMenu: [
|
233 |
+
{
|
234 |
+
text: formatMessage(/* ... */),
|
235 |
+
value: 42
|
236 |
+
}
|
237 |
+
]
|
238 |
+
}
|
239 |
+
```
|
240 |
+
|
241 |
+
##### Accepting reporters ("droppable" menus)
|
242 |
+
|
243 |
+
By default it is not possible to specify the value of a dropdown menu by inserting a reporter block. While we
|
244 |
+
encourage extension authors to make their menus accept reporters when possible, doing so requires careful
|
245 |
+
consideration to avoid confusion and frustration on the part of those using the extension.
|
246 |
+
|
247 |
+
A few of these considerations include:
|
248 |
+
|
249 |
+
* The valid values for the menu should not change when the user changes the Scratch language setting.
|
250 |
+
* In particular, changing languages should never break a working project.
|
251 |
+
* The average Scratch user should be able to figure out the valid values for this input without referring to extension
|
252 |
+
documentation.
|
253 |
+
* One way to ensure this is to make an item's text match or include the item's value. For example, the official Music
|
254 |
+
extension contains menu items with names like "(1) Piano" with value 1, "(8) Cello" with value 8, and so on.
|
255 |
+
* The block should accept any value as input, even "invalid" values.
|
256 |
+
* Scratch has no concept of a runtime error!
|
257 |
+
* For a command block, sometimes the best option is to do nothing.
|
258 |
+
* For a reporter, returning zero or the empty string might make sense.
|
259 |
+
* The block should be forgiving in its interpretation of inputs.
|
260 |
+
* For example, if the block expects a string and receives a number it may make sense to interpret the number as a
|
261 |
+
string instead of treating it as invalid input.
|
262 |
+
|
263 |
+
The `acceptReporters` flag indicates that the user can drop a reporter onto the menu input:
|
264 |
+
|
265 |
+
```js
|
266 |
+
menus: {
|
267 |
+
staticMenu: {
|
268 |
+
acceptReporters: true,
|
269 |
+
items: [/*...*/]
|
270 |
+
},
|
271 |
+
dynamicMenu: {
|
272 |
+
acceptReporters: true,
|
273 |
+
items: 'getDynamicMenuItems'
|
274 |
+
}
|
275 |
+
}
|
276 |
+
```
|
277 |
+
|
278 |
+
## Annotated Example
|
279 |
+
|
280 |
+
```js
|
281 |
+
// Core, Team, and Official extensions can `require` VM code:
|
282 |
+
const ArgumentType = require('../../extension-support/argument-type');
|
283 |
+
const BlockType = require('../../extension-support/block-type');
|
284 |
+
const TargetType = require('../../extension-support/target-type');
|
285 |
+
|
286 |
+
// ...or VM dependencies:
|
287 |
+
const formatMessage = require('format-message');
|
288 |
+
|
289 |
+
// Core, Team, and Official extension classes should be registered statically with the Extension Manager.
|
290 |
+
// See: scratch-vm/src/extension-support/extension-manager.js
|
291 |
+
class SomeBlocks {
|
292 |
+
constructor (runtime) {
|
293 |
+
/**
|
294 |
+
* Store this for later communication with the Scratch VM runtime.
|
295 |
+
* If this extension is running in a sandbox then `runtime` is an async proxy object.
|
296 |
+
* @type {Runtime}
|
297 |
+
*/
|
298 |
+
this.runtime = runtime;
|
299 |
+
}
|
300 |
+
|
301 |
+
/**
|
302 |
+
* @return {object} This extension's metadata.
|
303 |
+
*/
|
304 |
+
getInfo () {
|
305 |
+
return {
|
306 |
+
// Required: the machine-readable name of this extension.
|
307 |
+
// Will be used as the extension's namespace.
|
308 |
+
// Allowed characters are those matching the regular expression [\w-]: A-Z, a-z, 0-9, and hyphen ("-").
|
309 |
+
id: 'someBlocks',
|
310 |
+
|
311 |
+
// Core extensions only: override the default extension block colors.
|
312 |
+
color1: '#FF8C1A',
|
313 |
+
color2: '#DB6E00',
|
314 |
+
|
315 |
+
// Optional: the human-readable name of this extension as string.
|
316 |
+
// This and any other string to be displayed in the Scratch UI may either be
|
317 |
+
// a string or a call to `formatMessage`; a plain string will not be
|
318 |
+
// translated whereas a call to `formatMessage` will connect the string
|
319 |
+
// to the translation map (see below). The `formatMessage` call is
|
320 |
+
// similar to `formatMessage` from `react-intl` in form, but will actually
|
321 |
+
// call some extension support code to do its magic. For example, we will
|
322 |
+
// internally namespace the messages such that two extensions could have
|
323 |
+
// messages with the same ID without colliding.
|
324 |
+
// See also: https://github.com/yahoo/react-intl/wiki/API#formatmessage
|
325 |
+
name: formatMessage({
|
326 |
+
id: 'extensionName',
|
327 |
+
defaultMessage: 'Some Blocks',
|
328 |
+
description: 'The name of the "Some Blocks" extension'
|
329 |
+
}),
|
330 |
+
|
331 |
+
// Optional: URI for a block icon, to display at the edge of each block for this
|
332 |
+
// extension. Data URI OK.
|
333 |
+
// TODO: what file types are OK? All web images? Just PNG?
|
334 |
+
blockIconURI: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAAAAACyOJm3AAAAFklEQVQYV2P4DwMMEMgAI/+DEUIMBgAEWB7i7uidhAAAAABJRU5ErkJggg==',
|
335 |
+
|
336 |
+
// Optional: URI for an icon to be displayed in the blocks category menu.
|
337 |
+
// If not present, the menu will display the block icon, if one is present.
|
338 |
+
// Otherwise, the category menu shows its default filled circle.
|
339 |
+
// Data URI OK.
|
340 |
+
// TODO: what file types are OK? All web images? Just PNG?
|
341 |
+
menuIconURI: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAFCAAAAACyOJm3AAAAFklEQVQYV2P4DwMMEMgAI/+DEUIMBgAEWB7i7uidhAAAAABJRU5ErkJggg==',
|
342 |
+
|
343 |
+
// Optional: Link to documentation content for this extension.
|
344 |
+
// If not present, offer no link.
|
345 |
+
docsURI: 'https://....',
|
346 |
+
|
347 |
+
// Required: the list of blocks implemented by this extension,
|
348 |
+
// in the order intended for display.
|
349 |
+
blocks: [
|
350 |
+
{
|
351 |
+
// Required: the machine-readable name of this operation.
|
352 |
+
// This will appear in project JSON.
|
353 |
+
opcode: 'myReporter', // becomes 'someBlocks.myReporter'
|
354 |
+
|
355 |
+
// Required: the kind of block we're defining, from a predefined list.
|
356 |
+
// Fully supported block types:
|
357 |
+
// BlockType.BOOLEAN - same as REPORTER but returns a Boolean value
|
358 |
+
// BlockType.COMMAND - a normal command block, like "move {} steps"
|
359 |
+
// BlockType.HAT - starts a stack if its value changes from falsy to truthy ("edge triggered")
|
360 |
+
// BlockType.REPORTER - returns a value, like "direction"
|
361 |
+
// Block types in development or for internal use only:
|
362 |
+
// BlockType.BUTTON - place a button in the block palette
|
363 |
+
// BlockType.CONDITIONAL - control flow, like "if {}" or "if {} else {}"
|
364 |
+
// A CONDITIONAL block may return the one-based index of a branch to
|
365 |
+
// run, or it may return zero/falsy to run no branch.
|
366 |
+
// BlockType.EVENT - starts a stack in response to an event (full spec TBD)
|
367 |
+
// BlockType.LOOP - control flow, like "repeat {} {}" or "forever {}"
|
368 |
+
// A LOOP block is like a CONDITIONAL block with two differences:
|
369 |
+
// - the block is assumed to have exactly one child branch, and
|
370 |
+
// - each time a child branch finishes, the loop block is called again.
|
371 |
+
blockType: BlockType.REPORTER,
|
372 |
+
|
373 |
+
// Required for CONDITIONAL blocks, ignored for others: the number of
|
374 |
+
// child branches this block controls. An "if" or "repeat" block would
|
375 |
+
// specify a branch count of 1; an "if-else" block would specify a
|
376 |
+
// branch count of 2.
|
377 |
+
// TODO: should we support dynamic branch count for "switch"-likes?
|
378 |
+
branchCount: 0,
|
379 |
+
|
380 |
+
// Optional, default false: whether or not this block ends a stack.
|
381 |
+
// The "forever" and "stop all" blocks would specify true here.
|
382 |
+
terminal: true,
|
383 |
+
|
384 |
+
// Optional, default false: whether or not to block all threads while
|
385 |
+
// this block is busy. This is for things like the "touching color"
|
386 |
+
// block in compatibility mode, and is only needed if the VM runs in a
|
387 |
+
// worker. We might even consider omitting it from extension docs...
|
388 |
+
blockAllThreads: false,
|
389 |
+
|
390 |
+
// Required: the human-readable text on this block, including argument
|
391 |
+
// placeholders. Argument placeholders should be in [MACRO_CASE] and
|
392 |
+
// must be [ENCLOSED_WITHIN_SQUARE_BRACKETS].
|
393 |
+
text: formatMessage({
|
394 |
+
id: 'myReporter',
|
395 |
+
defaultMessage: 'letter [LETTER_NUM] of [TEXT]',
|
396 |
+
description: 'Label on the "myReporter" block'
|
397 |
+
}),
|
398 |
+
|
399 |
+
// Required: describe each argument.
|
400 |
+
// Argument order may change during translation, so arguments are
|
401 |
+
// identified by their placeholder name. In those situations where
|
402 |
+
// arguments must be ordered or assigned an ordinal, such as interaction
|
403 |
+
// with Scratch Blocks, arguments are ordered as they are in the default
|
404 |
+
// translation (probably English).
|
405 |
+
arguments: {
|
406 |
+
// Required: the ID of the argument, which will be the name in the
|
407 |
+
// args object passed to the implementation function.
|
408 |
+
LETTER_NUM: {
|
409 |
+
// Required: type of the argument / shape of the block input
|
410 |
+
type: ArgumentType.NUMBER,
|
411 |
+
|
412 |
+
// Optional: the default value of the argument
|
413 |
+
default: 1
|
414 |
+
},
|
415 |
+
|
416 |
+
// Required: the ID of the argument, which will be the name in the
|
417 |
+
// args object passed to the implementation function.
|
418 |
+
TEXT: {
|
419 |
+
// Required: type of the argument / shape of the block input
|
420 |
+
type: ArgumentType.STRING,
|
421 |
+
|
422 |
+
// Optional: the default value of the argument
|
423 |
+
default: formatMessage({
|
424 |
+
id: 'myReporter.TEXT_default',
|
425 |
+
defaultMessage: 'text',
|
426 |
+
description: 'Default for "TEXT" argument of "someBlocks.myReporter"'
|
427 |
+
})
|
428 |
+
}
|
429 |
+
},
|
430 |
+
|
431 |
+
// Optional: the function implementing this block.
|
432 |
+
// If absent, assume `func` is the same as `opcode`.
|
433 |
+
func: 'myReporter',
|
434 |
+
|
435 |
+
// Optional: list of target types for which this block should appear.
|
436 |
+
// If absent, assume it applies to all builtin targets -- that is:
|
437 |
+
// [TargetType.SPRITE, TargetType.STAGE]
|
438 |
+
filter: [TargetType.SPRITE]
|
439 |
+
},
|
440 |
+
{
|
441 |
+
// Another block...
|
442 |
+
}
|
443 |
+
],
|
444 |
+
|
445 |
+
// Optional: define extension-specific menus here.
|
446 |
+
menus: {
|
447 |
+
// Required: an identifier for this menu, unique within this extension.
|
448 |
+
menuA: [
|
449 |
+
// Static menu: list items which should appear in the menu.
|
450 |
+
{
|
451 |
+
// Required: the value of the menu item when it is chosen.
|
452 |
+
value: 'itemId1',
|
453 |
+
|
454 |
+
// Optional: the human-readable label for this item.
|
455 |
+
// Use `value` as the text if this is absent.
|
456 |
+
text: formatMessage({
|
457 |
+
id: 'menuA_item1',
|
458 |
+
defaultMessage: 'Item One',
|
459 |
+
description: 'Label for item 1 of menu A in "Some Blocks" extension'
|
460 |
+
})
|
461 |
+
},
|
462 |
+
|
463 |
+
// The simplest form of a list item is a string which will be used as
|
464 |
+
// both value and text.
|
465 |
+
'itemId2'
|
466 |
+
],
|
467 |
+
|
468 |
+
// Dynamic menu: returns an array as above.
|
469 |
+
// Called each time the menu is opened.
|
470 |
+
menuB: 'getItemsForMenuB',
|
471 |
+
|
472 |
+
// The examples above are shorthand for setting only the `items` property in this full form:
|
473 |
+
menuC: {
|
474 |
+
// This flag makes a "droppable" menu: the menu will allow dropping a reporter in for the input.
|
475 |
+
acceptReporters: true,
|
476 |
+
|
477 |
+
// The `item` property may be an array or function name as in previous menu examples.
|
478 |
+
items: [/*...*/] || 'getItemsForMenuC'
|
479 |
+
}
|
480 |
+
},
|
481 |
+
|
482 |
+
// Optional: translations (UNSTABLE - NOT YET SUPPORTED)
|
483 |
+
translation_map: {
|
484 |
+
de: {
|
485 |
+
'extensionName': 'Einige Blöcke',
|
486 |
+
'myReporter': 'Buchstabe [LETTER_NUM] von [TEXT]',
|
487 |
+
'myReporter.TEXT_default': 'Text',
|
488 |
+
'menuA_item1': 'Artikel eins',
|
489 |
+
|
490 |
+
// Dynamic menus can be translated too
|
491 |
+
'menuB_example': 'Beispiel',
|
492 |
+
|
493 |
+
// This message contains ICU placeholders (see `myReporter()` below)
|
494 |
+
'myReporter.result': 'Buchstabe {LETTER_NUM} von {TEXT} ist {LETTER}.'
|
495 |
+
},
|
496 |
+
it: {
|
497 |
+
// ...
|
498 |
+
}
|
499 |
+
}
|
500 |
+
};
|
501 |
+
};
|
502 |
+
|
503 |
+
/**
|
504 |
+
* Implement myReporter.
|
505 |
+
* @param {object} args - the block's arguments.
|
506 |
+
* @property {string} MY_ARG - the string value of the argument.
|
507 |
+
* @returns {string} a string which includes the block argument value.
|
508 |
+
*/
|
509 |
+
myReporter (args) {
|
510 |
+
// This message contains ICU placeholders, not Scratch placeholders
|
511 |
+
const message = formatMessage({
|
512 |
+
id: 'myReporter.result',
|
513 |
+
defaultMessage: 'Letter {LETTER_NUM} of {TEXT} is {LETTER}.',
|
514 |
+
description: 'The text template for the "myReporter" block result'
|
515 |
+
});
|
516 |
+
|
517 |
+
// Note: this implementation is not Unicode-clean; it's just here as an example.
|
518 |
+
const result = args.TEXT.charAt(args.LETTER_NUM);
|
519 |
+
|
520 |
+
return message.format({
|
521 |
+
LETTER_NUM: args.LETTER_NUM,
|
522 |
+
TEXT: args.TEXT,
|
523 |
+
LETTER: result
|
524 |
+
});
|
525 |
+
};
|
526 |
+
}
|
527 |
+
```
|
package-lock.json
ADDED
The diff for this file is too large to render.
See raw diff
|
|
package.json
ADDED
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"name": "scratch-vm",
|
3 |
+
"version": "0.2.0",
|
4 |
+
"description": "Virtual Machine for Scratch 3.0",
|
5 |
+
"author": "Massachusetts Institute of Technology",
|
6 |
+
"license": "BSD-3-Clause",
|
7 |
+
"homepage": "https://github.com/LLK/scratch-vm#readme",
|
8 |
+
"repository": {
|
9 |
+
"type": "git",
|
10 |
+
"url": "git+ssh://[email protected]/LLK/scratch-vm.git"
|
11 |
+
},
|
12 |
+
"main": "./src/index.js",
|
13 |
+
"browser": "./src/index.js",
|
14 |
+
"scripts": {
|
15 |
+
"build": "npm run docs && webpack --progress --colors --bail",
|
16 |
+
"coverage": "tap ./test/{unit,integration}/*.js --coverage --coverage-report=lcov",
|
17 |
+
"deploy": "touch playground/.nojekyll && gh-pages -t -d playground -m \"Build for $(git log --pretty=format:%H -n1)\"",
|
18 |
+
"docs": "exit 0 || jsdoc -c .jsdoc.json",
|
19 |
+
"i18n:src": "mkdirp translations/core && format-message extract --out-file translations/core/en.json src/extensions/**/index.js",
|
20 |
+
"i18n:push": "tx-push-src scratch-editor extensions translations/core/en.json",
|
21 |
+
"lint": "exit 0 || eslint . && format-message lint src/**/*.js",
|
22 |
+
"prepublishOnly": "in-publish && npm run build || not-in-publish",
|
23 |
+
"start": "webpack-dev-server",
|
24 |
+
"tap": "tap ./test/{unit,integration}/*.js",
|
25 |
+
"tap:unit": "tap ./test/unit/*.js",
|
26 |
+
"tap:integration": "tap ./test/integration/*.js",
|
27 |
+
"test": "npm run lint && npm run docs && npm run tap",
|
28 |
+
"watch": "webpack --progress --colors --watch",
|
29 |
+
"version": "json -f package.json -I -e \"this.repository.sha = '$(git log -n1 --pretty=format:%H)'\""
|
30 |
+
},
|
31 |
+
"dependencies": {
|
32 |
+
"@turbowarp/json": "^0.1.2",
|
33 |
+
"@vernier/godirect": "1.5.0",
|
34 |
+
"arraybuffer-loader": "^1.0.6",
|
35 |
+
"atob": "2.1.2",
|
36 |
+
"btoa": "1.2.1",
|
37 |
+
"cannon-es": "0.20.0",
|
38 |
+
"canvas-toBlob": "1.0.0",
|
39 |
+
"decode-html": "2.0.0",
|
40 |
+
"diff-match-patch": "1.0.4",
|
41 |
+
"dompurify": "^3.0.9",
|
42 |
+
"format-message": "6.2.1",
|
43 |
+
"htmlparser2": "^3.10.0",
|
44 |
+
"immutable": "3.8.2",
|
45 |
+
"jszip": "^3.1.5",
|
46 |
+
"lz-string": "^1.5.0",
|
47 |
+
"mathjs": "11.11.1",
|
48 |
+
"matter-js": "^0.20.0",
|
49 |
+
"mersenne-twister": "^1.1.0",
|
50 |
+
"minilog": "3.1.0",
|
51 |
+
"pathfinding": "^0.4.18",
|
52 |
+
"schema-utils": "^2.7.1",
|
53 |
+
"scratch-parser": "git+https://github.com/PenguinMod/PenguinMod-Parser.git#master",
|
54 |
+
"scratch-sb1-converter": "0.2.7",
|
55 |
+
"scratch-translate-extension-languages": "0.0.20191118205314",
|
56 |
+
"simplex-noise": "^4.0.1",
|
57 |
+
"text-encoding": "0.7.0",
|
58 |
+
"three": "0.153.0",
|
59 |
+
"three-mesh-bvh": "0.6.0",
|
60 |
+
"tone": "^14.7.77",
|
61 |
+
"worker-loader": "^1.1.1"
|
62 |
+
},
|
63 |
+
"peerDependencies": {
|
64 |
+
"scratch-svg-renderer": "^0.2.0-prerelease"
|
65 |
+
},
|
66 |
+
"devDependencies": {
|
67 |
+
"@babel/core": "7.13.10",
|
68 |
+
"@babel/preset-env": "7.14.8",
|
69 |
+
"adm-zip": "0.4.11",
|
70 |
+
"babel-eslint": "10.1.0",
|
71 |
+
"babel-loader": "8.2.2",
|
72 |
+
"callsite": "1.0.0",
|
73 |
+
"copy-webpack-plugin": "4.5.4",
|
74 |
+
"docdash": "1.2.0",
|
75 |
+
"eslint": "5.3.0",
|
76 |
+
"eslint-config-scratch": "5.1.0",
|
77 |
+
"expose-loader": "0.7.5",
|
78 |
+
"file-loader": "2.0.0",
|
79 |
+
"format-message-cli": "6.2.0",
|
80 |
+
"gh-pages": "1.2.0",
|
81 |
+
"in-publish": "2.0.1",
|
82 |
+
"js-md5": "0.7.3",
|
83 |
+
"jsdoc": "3.6.6",
|
84 |
+
"json": "^9.0.4",
|
85 |
+
"lodash.defaultsdeep": "4.6.1",
|
86 |
+
"pngjs": "3.3.3",
|
87 |
+
"ml5": "^0.12.2",
|
88 |
+
"scratch-audio": "0.1.0-prerelease.20200528195344",
|
89 |
+
"scratch-blocks": "git+https://github.com/PenguinMod/PenguinMod-Blocks.git#develop-builds",
|
90 |
+
"scratch-l10n": "3.14.20220526031602",
|
91 |
+
"scratch-render": "0.1.0-prerelease.20211028200436",
|
92 |
+
"scratch-render-fonts": "github:PenguinMod/penguinmod-render-fonts#master",
|
93 |
+
"scratch-storage": "git+https://github.com/PenguinMod/PenguinMod-Storage.git#develop",
|
94 |
+
"scratch-svg-renderer": "0.2.0-prerelease.20210727023023",
|
95 |
+
"script-loader": "0.7.2",
|
96 |
+
"stats.js": "0.17.0",
|
97 |
+
"tap": "12.0.1",
|
98 |
+
"tiny-worker": "2.3.0",
|
99 |
+
"uglifyjs-webpack-plugin": "1.2.7",
|
100 |
+
"webpack": "4.46.0",
|
101 |
+
"webpack-cli": "3.1.0",
|
102 |
+
"webpack-dev-server": "3.11.2"
|
103 |
+
},
|
104 |
+
"private": true
|
105 |
+
}
|
renovate.json5
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
3 |
+
|
4 |
+
"extends": [
|
5 |
+
"github>LLK/scratch-renovate-config:conservative"
|
6 |
+
]
|
7 |
+
}
|
src/.eslintrc.js
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
module.exports = {
|
2 |
+
root: true,
|
3 |
+
extends: ['scratch', 'scratch/es6'],
|
4 |
+
env: {
|
5 |
+
browser: true
|
6 |
+
},
|
7 |
+
rules: {
|
8 |
+
'no-case-declarations': 'off',
|
9 |
+
'no-console': 'off',
|
10 |
+
'no-shadow': 'off',
|
11 |
+
'quotes': 'off',
|
12 |
+
'prefer-template': 'warn',
|
13 |
+
'linebreak-style': 'off',
|
14 |
+
'no-alert': 'off',
|
15 |
+
'quote-props': 'off',
|
16 |
+
'no-trailing-spaces': 'off',
|
17 |
+
'object-curly-spacing': 'off',
|
18 |
+
'curly': 'off',
|
19 |
+
'operator-linebreak': 'off',
|
20 |
+
'one-var': 'off',
|
21 |
+
'brace-style': 'off',
|
22 |
+
'camelcase': 'off',
|
23 |
+
'comma-spacing': 'off',
|
24 |
+
'no-negated-condition': 'off',
|
25 |
+
// @todo please jg, stop having your formater REMOVE THE SPACES
|
26 |
+
'space-before-function-paren': 'off',
|
27 |
+
'no-throw-literal': 'off'
|
28 |
+
},
|
29 |
+
"globals": {
|
30 |
+
"vm": true
|
31 |
+
},
|
32 |
+
};
|
src/blocks/pm_live tests.js
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/*
|
2 |
+
compiled blocks:
|
3 |
+
sensing_set_of: jsgen.js@1195, irgen.js@1420
|
4 |
+
*/
|
5 |
+
const Cast = require('../util/cast');
|
6 |
+
|
7 |
+
class pmLiveTests {
|
8 |
+
constructor (runtime) {
|
9 |
+
/**
|
10 |
+
* The runtime instantiating this block package.
|
11 |
+
* @type {Runtime}
|
12 |
+
*/
|
13 |
+
this.runtime = runtime;
|
14 |
+
}
|
15 |
+
|
16 |
+
/**
|
17 |
+
* Retrieve the block primitives implemented by this package.
|
18 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
19 |
+
*/
|
20 |
+
getPrimitives () {
|
21 |
+
return {
|
22 |
+
looks_setVertTransform: this.setVerticalTransform,
|
23 |
+
looks_setHorizTransform: this.setHorizontalTransform
|
24 |
+
};
|
25 |
+
}
|
26 |
+
|
27 |
+
setVerticalTransform (args, {target}) {
|
28 |
+
const percent = Cast.toNumber(args.PERCENT) / 100;
|
29 |
+
target.setTransform([percent, target.transform[1]]);
|
30 |
+
}
|
31 |
+
|
32 |
+
setHorizontalTransform (args, {target}) {
|
33 |
+
const percent = Cast.toNumber(args.PERCENT) / 100;
|
34 |
+
target.setTransform([target.transform[0], percent]);
|
35 |
+
}
|
36 |
+
}
|
37 |
+
|
38 |
+
module.exports = pmLiveTests;
|
src/blocks/scratch3_control.js
ADDED
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const SandboxRunner = require('../util/sandboxed-javascript-runner.js');
|
3 |
+
|
4 |
+
class Scratch3ControlBlocks {
|
5 |
+
constructor (runtime) {
|
6 |
+
/**
|
7 |
+
* The runtime instantiating this block package.
|
8 |
+
* @type {Runtime}
|
9 |
+
*/
|
10 |
+
this.runtime = runtime;
|
11 |
+
|
12 |
+
/**
|
13 |
+
* The "counter" block value. For compatibility with 2.0.
|
14 |
+
* @type {number}
|
15 |
+
*/
|
16 |
+
this._counter = 0; // used by compiler
|
17 |
+
|
18 |
+
/**
|
19 |
+
* The "error" block value.
|
20 |
+
* @type {string}
|
21 |
+
*/
|
22 |
+
this._error = ''; // used by compiler
|
23 |
+
|
24 |
+
this.runtime.on('RUNTIME_DISPOSED', this.clearCounter.bind(this));
|
25 |
+
}
|
26 |
+
|
27 |
+
/**
|
28 |
+
* Retrieve the block primitives implemented by this package.
|
29 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
30 |
+
*/
|
31 |
+
getPrimitives () {
|
32 |
+
return {
|
33 |
+
control_repeat: this.repeat,
|
34 |
+
control_repeat_until: this.repeatUntil,
|
35 |
+
control_while: this.repeatWhile,
|
36 |
+
control_for_each: this.forEach,
|
37 |
+
control_forever: this.forever,
|
38 |
+
control_wait: this.wait,
|
39 |
+
control_repeatForSeconds: this.repeatForSeconds,
|
40 |
+
control_waittick: this.waitTick,
|
41 |
+
control_waitsecondsoruntil: this.waitOrUntil,
|
42 |
+
control_wait_until: this.waitUntil,
|
43 |
+
control_if: this.if,
|
44 |
+
control_if_else: this.ifElse,
|
45 |
+
control_stop: this.stop,
|
46 |
+
control_stop_sprite: this.stopSprite,
|
47 |
+
control_create_clone_of: this.createClone,
|
48 |
+
control_delete_this_clone: this.deleteClone,
|
49 |
+
control_delete_clones_of: this.deleteClonesOf,
|
50 |
+
control_get_counter: this.getCounter,
|
51 |
+
control_incr_counter: this.incrCounter,
|
52 |
+
control_decr_counter: this.decrCounter,
|
53 |
+
control_set_counter: this.setCounter,
|
54 |
+
control_clear_counter: this.clearCounter,
|
55 |
+
control_all_at_once: this.allAtOnce,
|
56 |
+
control_backToGreenFlag: this.backToGreenFlag,
|
57 |
+
control_if_return_else_return: this.if_return_else_return,
|
58 |
+
control_javascript_command: this.runJavascript
|
59 |
+
};
|
60 |
+
}
|
61 |
+
|
62 |
+
getMonitored () {
|
63 |
+
return {
|
64 |
+
control_get_counter: {
|
65 |
+
getId: () => 'get_counter'
|
66 |
+
}
|
67 |
+
};
|
68 |
+
}
|
69 |
+
|
70 |
+
backToGreenFlag(_, util) {
|
71 |
+
const thisThread = util.thread.topBlock;
|
72 |
+
this.runtime.emit("PROJECT_START_BEFORE_RESET");
|
73 |
+
this.runtime.threads
|
74 |
+
.filter(thread => thread.topBlock !== thisThread)
|
75 |
+
.forEach(thread => thread.stopThisScript());
|
76 |
+
// green flag behaviour
|
77 |
+
this.runtime.emit("PROJECT_START");
|
78 |
+
this.runtime.updateCurrentMSecs();
|
79 |
+
this.runtime.ioDevices.clock.resetProjectTimer();
|
80 |
+
this.runtime.targets.forEach(target => target.clearEdgeActivatedValues());
|
81 |
+
for (let i = this.runtime.targets.length - 1; i >= 0; i--) {
|
82 |
+
const thisTarget = this.runtime.targets[i];
|
83 |
+
thisTarget.onGreenFlag();
|
84 |
+
if (!thisTarget.isOriginal) {
|
85 |
+
this.runtime.disposeTarget(thisTarget);
|
86 |
+
this.runtime.stopForTarget(thisTarget);
|
87 |
+
}
|
88 |
+
}
|
89 |
+
this.runtime.startHats("event_whenflagclicked");
|
90 |
+
}
|
91 |
+
|
92 |
+
if_return_else_return (args) {
|
93 |
+
return Cast.toBoolean(args.boolean) ? args.TEXT1 : args.TEXT2;
|
94 |
+
}
|
95 |
+
|
96 |
+
getHats () {
|
97 |
+
return {
|
98 |
+
control_start_as_clone: {
|
99 |
+
restartExistingThreads: false
|
100 |
+
}
|
101 |
+
};
|
102 |
+
}
|
103 |
+
|
104 |
+
runJavascript(args) {
|
105 |
+
return new Promise((resolve) => {
|
106 |
+
const js = Cast.toString(args.JS);
|
107 |
+
SandboxRunner.execute(js).then(result => {
|
108 |
+
resolve(result.value);
|
109 |
+
});
|
110 |
+
});
|
111 |
+
}
|
112 |
+
|
113 |
+
repeat (args, util) {
|
114 |
+
const times = Math.round(Cast.toNumber(args.TIMES));
|
115 |
+
// Initialize loop
|
116 |
+
if (typeof util.stackFrame.loopCounter === 'undefined') {
|
117 |
+
util.stackFrame.loopCounter = times;
|
118 |
+
}
|
119 |
+
// Only execute once per frame.
|
120 |
+
// When the branch finishes, `repeat` will be executed again and
|
121 |
+
// the second branch will be taken, yielding for the rest of the frame.
|
122 |
+
// Decrease counter
|
123 |
+
util.stackFrame.loopCounter--;
|
124 |
+
// If we still have some left, start the branch.
|
125 |
+
if (util.stackFrame.loopCounter >= 0) {
|
126 |
+
util.startBranch(1, true);
|
127 |
+
}
|
128 |
+
}
|
129 |
+
|
130 |
+
repeatUntil (args, util) {
|
131 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
132 |
+
// If the condition is false (repeat UNTIL), start the branch.
|
133 |
+
if (!condition) {
|
134 |
+
util.startBranch(1, true);
|
135 |
+
}
|
136 |
+
}
|
137 |
+
|
138 |
+
repeatWhile (args, util) {
|
139 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
140 |
+
// If the condition is true (repeat WHILE), start the branch.
|
141 |
+
if (condition) {
|
142 |
+
util.startBranch(1, true);
|
143 |
+
}
|
144 |
+
}
|
145 |
+
|
146 |
+
forEach (args, util) {
|
147 |
+
const variable = util.target.lookupOrCreateVariable(
|
148 |
+
args.VARIABLE.id, args.VARIABLE.name);
|
149 |
+
|
150 |
+
if (typeof util.stackFrame.index === 'undefined') {
|
151 |
+
util.stackFrame.index = 0;
|
152 |
+
}
|
153 |
+
|
154 |
+
if (util.stackFrame.index < Number(args.VALUE)) {
|
155 |
+
util.stackFrame.index++;
|
156 |
+
variable.value = util.stackFrame.index;
|
157 |
+
util.startBranch(1, true);
|
158 |
+
}
|
159 |
+
}
|
160 |
+
|
161 |
+
waitUntil (args, util) {
|
162 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
163 |
+
if (!condition) {
|
164 |
+
util.yield();
|
165 |
+
}
|
166 |
+
}
|
167 |
+
|
168 |
+
forever (args, util) {
|
169 |
+
util.startBranch(1, true);
|
170 |
+
}
|
171 |
+
|
172 |
+
wait (args, util) {
|
173 |
+
if (util.stackTimerNeedsInit()) {
|
174 |
+
const duration = Math.max(0, 1000 * Cast.toNumber(args.DURATION));
|
175 |
+
|
176 |
+
util.startStackTimer(duration);
|
177 |
+
this.runtime.requestRedraw();
|
178 |
+
util.yield();
|
179 |
+
} else if (!util.stackTimerFinished()) {
|
180 |
+
util.yield();
|
181 |
+
}
|
182 |
+
}
|
183 |
+
|
184 |
+
repeatForSeconds (args, util) {
|
185 |
+
if (util.stackTimerNeedsInit()) {
|
186 |
+
const duration = Math.max(0, 1000 * Cast.toNumber(args.TIMES));
|
187 |
+
|
188 |
+
util.startStackTimer(duration);
|
189 |
+
this.runtime.requestRedraw();
|
190 |
+
util.startBranch(1, true);
|
191 |
+
util.yield();
|
192 |
+
} else if (!util.stackTimerFinished()) {
|
193 |
+
util.startBranch(1, true);
|
194 |
+
util.yield();
|
195 |
+
}
|
196 |
+
}
|
197 |
+
|
198 |
+
waitTick (_, util) {
|
199 |
+
util.yieldTick();
|
200 |
+
}
|
201 |
+
|
202 |
+
waitOrUntil (args, util) {
|
203 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
204 |
+
if (!condition) {
|
205 |
+
if (util.stackTimerNeedsInit()) {
|
206 |
+
const duration = Math.max(0, 1000 * Cast.toNumber(args.DURATION));
|
207 |
+
|
208 |
+
util.startStackTimer(duration);
|
209 |
+
this.runtime.requestRedraw();
|
210 |
+
util.yield();
|
211 |
+
return;
|
212 |
+
}
|
213 |
+
if (!util.stackTimerFinished()) {
|
214 |
+
util.yield();
|
215 |
+
}
|
216 |
+
}
|
217 |
+
}
|
218 |
+
|
219 |
+
if (args, util) {
|
220 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
221 |
+
if (condition) {
|
222 |
+
util.startBranch(1, false);
|
223 |
+
}
|
224 |
+
}
|
225 |
+
|
226 |
+
ifElse (args, util) {
|
227 |
+
const condition = Cast.toBoolean(args.CONDITION);
|
228 |
+
if (condition) {
|
229 |
+
util.startBranch(1, false);
|
230 |
+
} else {
|
231 |
+
util.startBranch(2, false);
|
232 |
+
}
|
233 |
+
}
|
234 |
+
|
235 |
+
stop (args, util) {
|
236 |
+
const option = args.STOP_OPTION;
|
237 |
+
if (option === 'all') {
|
238 |
+
util.stopAll();
|
239 |
+
} else if (option === 'other scripts in sprite' ||
|
240 |
+
option === 'other scripts in stage') {
|
241 |
+
util.stopOtherTargetThreads();
|
242 |
+
} else if (option === 'this script') {
|
243 |
+
util.stopThisScript();
|
244 |
+
}
|
245 |
+
}
|
246 |
+
|
247 |
+
stopSprite (args, util) {
|
248 |
+
const option = args.STOP_OPTION;
|
249 |
+
// Set target
|
250 |
+
let target;
|
251 |
+
if (option === '_myself_') {
|
252 |
+
target = util.target;
|
253 |
+
} else if (option === '_stage_') {
|
254 |
+
target = this.runtime.getTargetForStage();
|
255 |
+
} else {
|
256 |
+
target = this.runtime.getSpriteTargetByName(option);
|
257 |
+
}
|
258 |
+
if (!target) return;
|
259 |
+
this.runtime.stopForTarget(target);
|
260 |
+
}
|
261 |
+
|
262 |
+
createClone (args, util) {
|
263 |
+
this._createClone(Cast.toString(args.CLONE_OPTION), util.target);
|
264 |
+
}
|
265 |
+
_createClone (cloneOption, target) { // used by compiler
|
266 |
+
// Set clone target
|
267 |
+
let cloneTarget;
|
268 |
+
if (cloneOption === '_myself_') {
|
269 |
+
cloneTarget = target;
|
270 |
+
} else {
|
271 |
+
cloneTarget = this.runtime.getSpriteTargetByName(cloneOption);
|
272 |
+
}
|
273 |
+
|
274 |
+
// If clone target is not found, return
|
275 |
+
if (!cloneTarget) return;
|
276 |
+
|
277 |
+
// Create clone
|
278 |
+
const newClone = cloneTarget.makeClone();
|
279 |
+
if (newClone) {
|
280 |
+
this.runtime.addTarget(newClone);
|
281 |
+
|
282 |
+
// Place behind the original target.
|
283 |
+
newClone.goBehindOther(cloneTarget);
|
284 |
+
}
|
285 |
+
}
|
286 |
+
|
287 |
+
deleteClone (args, util) {
|
288 |
+
if (util.target.isOriginal) return;
|
289 |
+
this.runtime.disposeTarget(util.target);
|
290 |
+
this.runtime.stopForTarget(util.target);
|
291 |
+
}
|
292 |
+
|
293 |
+
deleteClonesOf (args, util) {
|
294 |
+
const cloneOption = Cast.toString(args.CLONE_OPTION);
|
295 |
+
// Set clone target
|
296 |
+
let cloneTarget;
|
297 |
+
if (cloneOption === '_myself_') {
|
298 |
+
cloneTarget = util.target;
|
299 |
+
} else {
|
300 |
+
cloneTarget = this.runtime.getSpriteTargetByName(cloneOption);
|
301 |
+
}
|
302 |
+
|
303 |
+
// If clone target is not found, return
|
304 |
+
if (!cloneTarget) return;
|
305 |
+
const sprite = cloneTarget.sprite;
|
306 |
+
if (!sprite) return;
|
307 |
+
if (!sprite.clones) return;
|
308 |
+
const cloneList = [].concat(sprite.clones);
|
309 |
+
cloneList.forEach(clone => {
|
310 |
+
if (clone.isOriginal) return;
|
311 |
+
if (clone.isStage) return;
|
312 |
+
this.runtime.disposeTarget(clone);
|
313 |
+
this.runtime.stopForTarget(clone);
|
314 |
+
})
|
315 |
+
}
|
316 |
+
|
317 |
+
getCounter () {
|
318 |
+
return this._counter;
|
319 |
+
}
|
320 |
+
|
321 |
+
setCounter (args) {
|
322 |
+
const num = Cast.toNumber(args.VALUE);
|
323 |
+
this._counter = num;
|
324 |
+
}
|
325 |
+
|
326 |
+
clearCounter () {
|
327 |
+
this._counter = 0;
|
328 |
+
}
|
329 |
+
|
330 |
+
incrCounter () {
|
331 |
+
this._counter++;
|
332 |
+
}
|
333 |
+
|
334 |
+
decrCounter () {
|
335 |
+
this._counter--;
|
336 |
+
}
|
337 |
+
|
338 |
+
allAtOnce (util) {
|
339 |
+
util.thread.peekStackFrame().warpMode = false;
|
340 |
+
util.startBranch(1, false);
|
341 |
+
util.thread.peekStackFrame().warpMode = true;
|
342 |
+
}
|
343 |
+
}
|
344 |
+
|
345 |
+
module.exports = Scratch3ControlBlocks;
|
src/blocks/scratch3_core_example.js
ADDED
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const BlockType = require('../extension-support/block-type');
|
2 |
+
const ArgumentType = require('../extension-support/argument-type');
|
3 |
+
|
4 |
+
/* eslint-disable-next-line max-len */
|
5 |
+
const blockIconURI = 'data:image/svg+xml,%3Csvg id="rotate-counter-clockwise" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%233d79cc;%7D.cls-2%7Bfill:%23fff;%7D%3C/style%3E%3C/defs%3E%3Ctitle%3Erotate-counter-clockwise%3C/title%3E%3Cpath class="cls-1" d="M22.68,12.2a1.6,1.6,0,0,1-1.27.63H13.72a1.59,1.59,0,0,1-1.16-2.58l1.12-1.41a4.82,4.82,0,0,0-3.14-.77,4.31,4.31,0,0,0-2,.8,4.25,4.25,0,0,0-1.34,1.73,5.06,5.06,0,0,0,.54,4.62A5.58,5.58,0,0,0,12,17.74h0a2.26,2.26,0,0,1-.16,4.52A10.25,10.25,0,0,1,3.74,18,10.14,10.14,0,0,1,2.25,8.78,9.7,9.7,0,0,1,5.08,4.64,9.92,9.92,0,0,1,9.66,2.5a10.66,10.66,0,0,1,7.72,1.68l1.08-1.35a1.57,1.57,0,0,1,1.24-.6,1.6,1.6,0,0,1,1.54,1.21l1.7,7.37A1.57,1.57,0,0,1,22.68,12.2Z"/%3E%3Cpath class="cls-2" d="M21.38,11.83H13.77a.59.59,0,0,1-.43-1l1.75-2.19a5.9,5.9,0,0,0-4.7-1.58,5.07,5.07,0,0,0-4.11,3.17A6,6,0,0,0,7,15.77a6.51,6.51,0,0,0,5,2.92,1.31,1.31,0,0,1-.08,2.62,9.3,9.3,0,0,1-7.35-3.82A9.16,9.16,0,0,1,3.17,9.12,8.51,8.51,0,0,1,5.71,5.4,8.76,8.76,0,0,1,9.82,3.48a9.71,9.71,0,0,1,7.75,2.07l1.67-2.1a.59.59,0,0,1,1,.21L22,11.08A.59.59,0,0,1,21.38,11.83Z"/%3E%3C/svg%3E';
|
6 |
+
|
7 |
+
/**
|
8 |
+
* An example core block implemented using the extension spec.
|
9 |
+
* This is not loaded as part of the core blocks in the VM but it is provided
|
10 |
+
* and used as part of tests.
|
11 |
+
*/
|
12 |
+
class Scratch3CoreExample {
|
13 |
+
constructor (runtime) {
|
14 |
+
/**
|
15 |
+
* The runtime instantiating this block package.
|
16 |
+
* @type {Runtime}
|
17 |
+
*/
|
18 |
+
this.runtime = runtime;
|
19 |
+
}
|
20 |
+
|
21 |
+
/**
|
22 |
+
* @returns {object} metadata for this extension and its blocks.
|
23 |
+
*/
|
24 |
+
getInfo () {
|
25 |
+
return {
|
26 |
+
id: 'coreExample',
|
27 |
+
name: 'CoreEx', // This string does not need to be translated as this extension is only used as an example.
|
28 |
+
blocks: [
|
29 |
+
{
|
30 |
+
opcode: 'exampleOpcode',
|
31 |
+
blockType: BlockType.REPORTER,
|
32 |
+
text: 'example block'
|
33 |
+
},
|
34 |
+
{
|
35 |
+
opcode: 'exampleWithInlineImage',
|
36 |
+
blockType: BlockType.COMMAND,
|
37 |
+
text: 'block with image [CLOCKWISE] inline',
|
38 |
+
arguments: {
|
39 |
+
CLOCKWISE: {
|
40 |
+
type: ArgumentType.IMAGE,
|
41 |
+
dataURI: blockIconURI
|
42 |
+
}
|
43 |
+
}
|
44 |
+
},
|
45 |
+
{
|
46 |
+
opcode: 'exampleNodeInputs',
|
47 |
+
blockType: BlockType.COMMAND,
|
48 |
+
text: 'block with some node inputs [CLOCKWISE]',
|
49 |
+
arguments: {
|
50 |
+
CLOCKWISE: {
|
51 |
+
type: ArgumentType.POLYGON,
|
52 |
+
nodes: 3
|
53 |
+
}
|
54 |
+
}
|
55 |
+
}
|
56 |
+
]
|
57 |
+
};
|
58 |
+
}
|
59 |
+
|
60 |
+
/**
|
61 |
+
* Example opcode just returns the name of the stage target.
|
62 |
+
* @returns {string} The name of the first target in the project.
|
63 |
+
*/
|
64 |
+
exampleOpcode () {
|
65 |
+
const stage = this.runtime.getTargetForStage();
|
66 |
+
return stage ? stage.getName() : 'no stage yet';
|
67 |
+
}
|
68 |
+
|
69 |
+
exampleWithInlineImage () {
|
70 |
+
return;
|
71 |
+
}
|
72 |
+
|
73 |
+
exampleNodeInputs (args, util) {
|
74 |
+
const nodes = args.CLOCKWISE;
|
75 |
+
this.runtime.ext_pen._penUp(util.target);
|
76 |
+
this.runtime.ext_pen.clear();
|
77 |
+
util.target.setXY(nodes[0].x, nodes[0].y);
|
78 |
+
this.runtime.ext_pen._penDown(util.target);
|
79 |
+
nodes.forEach(node => {
|
80 |
+
util.target.setXY(node.x, node.y);
|
81 |
+
});
|
82 |
+
util.target.setXY(nodes[0].x, nodes[0].y);
|
83 |
+
}
|
84 |
+
}
|
85 |
+
|
86 |
+
module.exports = Scratch3CoreExample;
|
src/blocks/scratch3_data.js
ADDED
@@ -0,0 +1,327 @@
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const { validateArray } = require('../util/json-block-utilities');
|
3 |
+
|
4 |
+
class Scratch3DataBlocks {
|
5 |
+
constructor (runtime) {
|
6 |
+
/**
|
7 |
+
* The runtime instantiating this block package.
|
8 |
+
* @type {Runtime}
|
9 |
+
*/
|
10 |
+
this.runtime = runtime;
|
11 |
+
}
|
12 |
+
|
13 |
+
/**
|
14 |
+
* Retrieve the block primitives implemented by this package.
|
15 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
16 |
+
*/
|
17 |
+
getPrimitives () {
|
18 |
+
return {
|
19 |
+
data_variable: this.getVariable,
|
20 |
+
data_setvariableto: this.setVariableTo,
|
21 |
+
data_changevariableby: this.changeVariableBy,
|
22 |
+
data_hidevariable: this.hideVariable,
|
23 |
+
data_showvariable: this.showVariable,
|
24 |
+
data_listcontents: this.getListContents,
|
25 |
+
data_addtolist: this.addToList,
|
26 |
+
data_deleteoflist: this.deleteOfList,
|
27 |
+
data_deletealloflist: this.deleteAllOfList,
|
28 |
+
data_insertatlist: this.insertAtList,
|
29 |
+
data_replaceitemoflist: this.replaceItemOfList,
|
30 |
+
data_itemoflist: this.getItemOfList,
|
31 |
+
data_itemnumoflist: this.getItemNumOfList,
|
32 |
+
data_lengthoflist: this.lengthOfList,
|
33 |
+
data_listcontainsitem: this.listContainsItem,
|
34 |
+
data_hidelist: this.hideList,
|
35 |
+
data_showlist: this.showList,
|
36 |
+
data_reverselist: this.data_reverselist,
|
37 |
+
data_itemexistslist: this.data_itemexistslist,
|
38 |
+
data_listisempty: this.data_listisempty,
|
39 |
+
data_listarray: this.data_listarray,
|
40 |
+
data_arraylist: this.data_arraylist,
|
41 |
+
data_listforeachnum: this.data_listforeachnum,
|
42 |
+
data_listforeachitem: this.data_listforeachitem
|
43 |
+
};
|
44 |
+
}
|
45 |
+
|
46 |
+
data_reverselist (args, util) {
|
47 |
+
const list = util.target.lookupOrCreateList(
|
48 |
+
args.LIST.id, args.LIST.name);
|
49 |
+
list.value.reverse();
|
50 |
+
list._monitorUpToDate = false;
|
51 |
+
}
|
52 |
+
data_itemexistslist (args, util) {
|
53 |
+
const list = util.target.lookupOrCreateList(
|
54 |
+
args.LIST.id, args.LIST.name);
|
55 |
+
const index = Cast.toListIndex(args.INDEX, list.value.length, false);
|
56 |
+
if (index === Cast.LIST_INVALID) {
|
57 |
+
return false;
|
58 |
+
}
|
59 |
+
return true;
|
60 |
+
}
|
61 |
+
data_listisempty (args, util) {
|
62 |
+
const list = util.target.lookupOrCreateList(
|
63 |
+
args.LIST.id, args.LIST.name);
|
64 |
+
return list.value.length < 1;
|
65 |
+
}
|
66 |
+
data_listarray (args, util) {
|
67 |
+
const list = util.target.lookupOrCreateList(
|
68 |
+
args.LIST.id, args.LIST.name);
|
69 |
+
return JSON.stringify(list.value);
|
70 |
+
}
|
71 |
+
data_arraylist (args, util) {
|
72 |
+
const list = util.target.lookupOrCreateList(
|
73 |
+
args.LIST.id, args.LIST.name);
|
74 |
+
const array = validateArray(args.VALUE).array
|
75 |
+
.map(v => {
|
76 |
+
if (typeof v === 'object') return JSON.stringify(v);
|
77 |
+
return String(v);
|
78 |
+
});
|
79 |
+
list.value = array;
|
80 |
+
}
|
81 |
+
data_listforeachnum (args, util) {
|
82 |
+
const list = util.target.lookupOrCreateList(
|
83 |
+
args.LIST.id, args.LIST.name);
|
84 |
+
if (typeof util.stackFrame.loopCounter === 'undefined') {
|
85 |
+
util.stackFrame.loopCounter = list.value.length;
|
86 |
+
}
|
87 |
+
// Only execute once per frame.
|
88 |
+
// When the branch finishes, `repeat` will be executed again and
|
89 |
+
// the second branch will be taken, yielding for the rest of the frame.
|
90 |
+
// Decrease counter
|
91 |
+
util.stackFrame.loopCounter--;
|
92 |
+
// If we still have some left, start the branch.
|
93 |
+
if (util.stackFrame.loopCounter >= 0) {
|
94 |
+
this.setVariableTo({
|
95 |
+
VARIABLE: args.INDEX,
|
96 |
+
VALUE: util.stackFrame.loopCounter
|
97 |
+
}, util);
|
98 |
+
util.startBranch(1, true);
|
99 |
+
}
|
100 |
+
}
|
101 |
+
data_listforeachitem (args, util) {
|
102 |
+
const list = util.target.lookupOrCreateList(
|
103 |
+
args.LIST.id, args.LIST.name);
|
104 |
+
if (typeof util.stackFrame.loopCounter === 'undefined') {
|
105 |
+
util.stackFrame.loopCounter = list.value.length;
|
106 |
+
}
|
107 |
+
// Only execute once per frame.
|
108 |
+
// When the branch finishes, `repeat` will be executed again and
|
109 |
+
// the second branch will be taken, yielding for the rest of the frame.
|
110 |
+
// Decrease counter
|
111 |
+
util.stackFrame.loopCounter--;
|
112 |
+
// If we still have some left, start the branch.
|
113 |
+
if (util.stackFrame.loopCounter >= 0) {
|
114 |
+
this.setVariableTo({
|
115 |
+
VARIABLE: args.INDEX,
|
116 |
+
VALUE: list.value[util.stackFrame.loopCounter]
|
117 |
+
}, util);
|
118 |
+
util.startBranch(1, true);
|
119 |
+
}
|
120 |
+
}
|
121 |
+
|
122 |
+
getVariable (args, util) {
|
123 |
+
const variable = util.target.lookupOrCreateVariable(
|
124 |
+
args.VARIABLE.id, args.VARIABLE.name);
|
125 |
+
return variable.value;
|
126 |
+
}
|
127 |
+
|
128 |
+
setVariableTo (args, util) {
|
129 |
+
const variable = util.target.lookupOrCreateVariable(
|
130 |
+
args.VARIABLE.id, args.VARIABLE.name);
|
131 |
+
variable.value = args.VALUE;
|
132 |
+
|
133 |
+
if (variable.isCloud) {
|
134 |
+
util.ioQuery('cloud', 'requestUpdateVariable', [variable.name, args.VALUE]);
|
135 |
+
}
|
136 |
+
}
|
137 |
+
|
138 |
+
changeVariableBy (args, util) {
|
139 |
+
const variable = util.target.lookupOrCreateVariable(
|
140 |
+
args.VARIABLE.id, args.VARIABLE.name);
|
141 |
+
const castedValue = Cast.toNumber(variable.value);
|
142 |
+
const dValue = Cast.toNumber(args.VALUE);
|
143 |
+
const newValue = castedValue + dValue;
|
144 |
+
variable.value = newValue;
|
145 |
+
|
146 |
+
if (variable.isCloud) {
|
147 |
+
util.ioQuery('cloud', 'requestUpdateVariable', [variable.name, newValue]);
|
148 |
+
}
|
149 |
+
}
|
150 |
+
|
151 |
+
changeMonitorVisibility (id, visible) {
|
152 |
+
// Send the monitor blocks an event like the flyout checkbox event.
|
153 |
+
// This both updates the monitor state and changes the isMonitored block flag.
|
154 |
+
this.runtime.monitorBlocks.changeBlock({
|
155 |
+
id: id, // Monitor blocks for variables are the variable ID.
|
156 |
+
element: 'checkbox', // Mimic checkbox event from flyout.
|
157 |
+
value: visible
|
158 |
+
}, this.runtime);
|
159 |
+
}
|
160 |
+
|
161 |
+
showVariable (args) {
|
162 |
+
this.changeMonitorVisibility(args.VARIABLE.id, true);
|
163 |
+
}
|
164 |
+
|
165 |
+
hideVariable (args) {
|
166 |
+
this.changeMonitorVisibility(args.VARIABLE.id, false);
|
167 |
+
}
|
168 |
+
|
169 |
+
showList (args) {
|
170 |
+
this.changeMonitorVisibility(args.LIST.id, true);
|
171 |
+
}
|
172 |
+
|
173 |
+
hideList (args) {
|
174 |
+
this.changeMonitorVisibility(args.LIST.id, false);
|
175 |
+
}
|
176 |
+
|
177 |
+
getListContents (args, util) {
|
178 |
+
const list = util.target.lookupOrCreateList(
|
179 |
+
args.LIST.id, args.LIST.name);
|
180 |
+
|
181 |
+
// If block is running for monitors, return copy of list as an array if changed.
|
182 |
+
if (util.thread.updateMonitor) {
|
183 |
+
// Return original list value if up-to-date, which doesn't trigger monitor update.
|
184 |
+
if (list._monitorUpToDate) return list.value;
|
185 |
+
// If value changed, reset the flag and return a copy to trigger monitor update.
|
186 |
+
// Because monitors use Immutable data structures, only new objects trigger updates.
|
187 |
+
list._monitorUpToDate = true;
|
188 |
+
return list.value.slice();
|
189 |
+
}
|
190 |
+
|
191 |
+
// Determine if the list is all single letters.
|
192 |
+
// If it is, report contents joined together with no separator.
|
193 |
+
// If it's not, report contents joined together with a space.
|
194 |
+
let allSingleLetters = true;
|
195 |
+
for (let i = 0; i < list.value.length; i++) {
|
196 |
+
const listItem = list.value[i];
|
197 |
+
if (!((typeof listItem === 'string') &&
|
198 |
+
(listItem.length === 1))) {
|
199 |
+
allSingleLetters = false;
|
200 |
+
break;
|
201 |
+
}
|
202 |
+
}
|
203 |
+
if (allSingleLetters) {
|
204 |
+
return list.value.join('');
|
205 |
+
}
|
206 |
+
return list.value.join(' ');
|
207 |
+
|
208 |
+
}
|
209 |
+
|
210 |
+
addToList (args, util) {
|
211 |
+
const list = util.target.lookupOrCreateList(
|
212 |
+
args.LIST.id, args.LIST.name);
|
213 |
+
list.value.push(args.ITEM);
|
214 |
+
list._monitorUpToDate = false;
|
215 |
+
}
|
216 |
+
|
217 |
+
deleteOfList (args, util) {
|
218 |
+
const list = util.target.lookupOrCreateList(
|
219 |
+
args.LIST.id, args.LIST.name);
|
220 |
+
const index = Cast.toListIndex(args.INDEX, list.value.length, true);
|
221 |
+
if (index === Cast.LIST_INVALID) {
|
222 |
+
return;
|
223 |
+
} else if (index === Cast.LIST_ALL) {
|
224 |
+
list.value = [];
|
225 |
+
return;
|
226 |
+
}
|
227 |
+
list.value.splice(index - 1, 1);
|
228 |
+
list._monitorUpToDate = false;
|
229 |
+
}
|
230 |
+
|
231 |
+
deleteAllOfList (args, util) {
|
232 |
+
const list = util.target.lookupOrCreateList(
|
233 |
+
args.LIST.id, args.LIST.name);
|
234 |
+
list.value = [];
|
235 |
+
return;
|
236 |
+
}
|
237 |
+
|
238 |
+
insertAtList (args, util) {
|
239 |
+
const item = args.ITEM;
|
240 |
+
const list = util.target.lookupOrCreateList(
|
241 |
+
args.LIST.id, args.LIST.name);
|
242 |
+
const index = Cast.toListIndex(args.INDEX, list.value.length + 1, false);
|
243 |
+
if (index === Cast.LIST_INVALID) {
|
244 |
+
return;
|
245 |
+
}
|
246 |
+
list.value.splice(index - 1, 0, item);
|
247 |
+
list._monitorUpToDate = false;
|
248 |
+
}
|
249 |
+
|
250 |
+
replaceItemOfList (args, util) {
|
251 |
+
const item = args.ITEM;
|
252 |
+
const list = util.target.lookupOrCreateList(
|
253 |
+
args.LIST.id, args.LIST.name);
|
254 |
+
const index = Cast.toListIndex(args.INDEX, list.value.length, false);
|
255 |
+
if (index === Cast.LIST_INVALID) {
|
256 |
+
return;
|
257 |
+
}
|
258 |
+
list.value[index - 1] = item;
|
259 |
+
list._monitorUpToDate = false;
|
260 |
+
}
|
261 |
+
|
262 |
+
getItemOfList (args, util) {
|
263 |
+
const list = util.target.lookupOrCreateList(
|
264 |
+
args.LIST.id, args.LIST.name);
|
265 |
+
const index = Cast.toListIndex(args.INDEX, list.value.length, false);
|
266 |
+
if (index === Cast.LIST_INVALID) {
|
267 |
+
return '';
|
268 |
+
}
|
269 |
+
return list.value[index - 1];
|
270 |
+
}
|
271 |
+
|
272 |
+
getItemNumOfList (args, util) {
|
273 |
+
const item = args.ITEM;
|
274 |
+
const list = util.target.lookupOrCreateList(
|
275 |
+
args.LIST.id, args.LIST.name);
|
276 |
+
|
277 |
+
// Go through the list items one-by-one using Cast.compare. This is for
|
278 |
+
// cases like checking if 123 is contained in a list [4, 7, '123'] --
|
279 |
+
// Scratch considers 123 and '123' to be equal.
|
280 |
+
for (let i = 0; i < list.value.length; i++) {
|
281 |
+
if (Cast.compare(list.value[i], item) === 0) {
|
282 |
+
return i + 1;
|
283 |
+
}
|
284 |
+
}
|
285 |
+
|
286 |
+
// We don't bother using .indexOf() at all, because it would end up with
|
287 |
+
// edge cases such as the index of '123' in [4, 7, 123, '123', 9].
|
288 |
+
// If we use indexOf(), this block would return 4 instead of 3, because
|
289 |
+
// indexOf() sees the first occurence of the string 123 as the fourth
|
290 |
+
// item in the list. With Scratch, this would be confusing -- after all,
|
291 |
+
// '123' and 123 look the same, so one would expect the block to say
|
292 |
+
// that the first occurrence of '123' (or 123) to be the third item.
|
293 |
+
|
294 |
+
// Default to 0 if there's no match. Since Scratch lists are 1-indexed,
|
295 |
+
// we don't have to worry about this conflicting with the "this item is
|
296 |
+
// the first value" number (in JS that is 0, but in Scratch it's 1).
|
297 |
+
return 0;
|
298 |
+
}
|
299 |
+
|
300 |
+
lengthOfList (args, util) {
|
301 |
+
const list = util.target.lookupOrCreateList(
|
302 |
+
args.LIST.id, args.LIST.name);
|
303 |
+
return list.value.length;
|
304 |
+
}
|
305 |
+
|
306 |
+
listContainsItem (args, util) {
|
307 |
+
const item = args.ITEM;
|
308 |
+
const list = util.target.lookupOrCreateList(
|
309 |
+
args.LIST.id, args.LIST.name);
|
310 |
+
if (list.value.indexOf(item) >= 0) {
|
311 |
+
return true;
|
312 |
+
}
|
313 |
+
// Try using Scratch comparison operator on each item.
|
314 |
+
// (Scratch considers the string '123' equal to the number 123).
|
315 |
+
for (let i = 0; i < list.value.length; i++) {
|
316 |
+
if (Cast.compare(list.value[i], item) === 0) {
|
317 |
+
return true;
|
318 |
+
}
|
319 |
+
}
|
320 |
+
return false;
|
321 |
+
}
|
322 |
+
|
323 |
+
_listFilterItem = ""
|
324 |
+
_listFilterIndex = 0
|
325 |
+
}
|
326 |
+
|
327 |
+
module.exports = Scratch3DataBlocks;
|
src/blocks/scratch3_event.js
ADDED
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const SandboxRunner = require('../util/sandboxed-javascript-runner.js');
|
3 |
+
|
4 |
+
class Scratch3EventBlocks {
|
5 |
+
constructor (runtime) {
|
6 |
+
/**
|
7 |
+
* The runtime instantiating this block package.
|
8 |
+
* @type {Runtime}
|
9 |
+
*/
|
10 |
+
this.runtime = runtime;
|
11 |
+
|
12 |
+
this.runtime.on('KEY_PRESSED', key => {
|
13 |
+
this.runtime.startHats('event_whenkeypressed', {
|
14 |
+
KEY_OPTION: key
|
15 |
+
});
|
16 |
+
this.runtime.startHats('event_whenkeypressed', {
|
17 |
+
KEY_OPTION: 'any'
|
18 |
+
});
|
19 |
+
});
|
20 |
+
|
21 |
+
this.runtime.on('KEY_HIT', key => {
|
22 |
+
this.runtime.startHats('event_whenkeyhit', {
|
23 |
+
KEY_OPTION: key
|
24 |
+
});
|
25 |
+
this.runtime.startHats('event_whenkeyhit', {
|
26 |
+
KEY_OPTION: 'any'
|
27 |
+
});
|
28 |
+
});
|
29 |
+
|
30 |
+
this.isStarting = false;
|
31 |
+
this.runtime.on('PROJECT_START_BEFORE_RESET', () => {
|
32 |
+
// we need to remember that the project is starting
|
33 |
+
// otherwise the stop block will run when flag is clicked
|
34 |
+
this.isStarting = true;
|
35 |
+
});
|
36 |
+
this.runtime.on('PROJECT_STOP_ALL', () => {
|
37 |
+
// if green flag is clicked, dont bother starting the hat
|
38 |
+
if (this.isStarting) {
|
39 |
+
this.isStarting = false;
|
40 |
+
return;
|
41 |
+
}
|
42 |
+
// we need to wait for runtime to step once
|
43 |
+
// otherwise the hat will be stopped as soon as it starts
|
44 |
+
this.runtime.once('RUNTIME_STEP_START', () => {
|
45 |
+
this.runtime.startHats('event_whenstopclicked');
|
46 |
+
})
|
47 |
+
this.isStarting = false;
|
48 |
+
});
|
49 |
+
this.runtime.on('RUNTIME_STEP_START', () => {
|
50 |
+
this.runtime.startHats('event_always');
|
51 |
+
});
|
52 |
+
|
53 |
+
this.runtime.on("AFTER_EXECUTE", () => {
|
54 |
+
// Use a timeout as regular Block Threads and Events Blocks dont run at the Same Speed
|
55 |
+
setTimeout(() => {
|
56 |
+
const stage = this.runtime.getTargetForStage();
|
57 |
+
if (!stage) return; // happens when project is loading
|
58 |
+
const stageVars = stage.variables;
|
59 |
+
for (const key in stageVars) {
|
60 |
+
if (stageVars[key].isSent !== undefined) stageVars[key].isSent = false;
|
61 |
+
}
|
62 |
+
}, 10);
|
63 |
+
});
|
64 |
+
}
|
65 |
+
|
66 |
+
/**
|
67 |
+
* Retrieve the block primitives implemented by this package.
|
68 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
69 |
+
*/
|
70 |
+
getPrimitives () {
|
71 |
+
return {
|
72 |
+
event_whenanything: this.whenanything,
|
73 |
+
event_whenjavascript: this.whenjavascript,
|
74 |
+
event_whentouchingobject: this.touchingObject,
|
75 |
+
event_broadcast: this.broadcast,
|
76 |
+
event_broadcastandwait: this.broadcastAndWait,
|
77 |
+
event_whengreaterthan: this.hatGreaterThanPredicate
|
78 |
+
};
|
79 |
+
}
|
80 |
+
|
81 |
+
whenanything (args) {
|
82 |
+
return Cast.toBoolean(args.ANYTHING);
|
83 |
+
}
|
84 |
+
|
85 |
+
whenjavascript (args) {
|
86 |
+
return new Promise((resolve) => {
|
87 |
+
const js = Cast.toString(args.JS);
|
88 |
+
SandboxRunner.execute(js).then(result => {
|
89 |
+
resolve(result.value === true);
|
90 |
+
})
|
91 |
+
})
|
92 |
+
}
|
93 |
+
|
94 |
+
getHats () {
|
95 |
+
return {
|
96 |
+
event_whenflagclicked: {
|
97 |
+
restartExistingThreads: true
|
98 |
+
},
|
99 |
+
event_whenstopclicked: {
|
100 |
+
restartExistingThreads: true
|
101 |
+
},
|
102 |
+
event_always: {
|
103 |
+
restartExistingThreads: false
|
104 |
+
},
|
105 |
+
event_whenkeypressed: {
|
106 |
+
restartExistingThreads: false
|
107 |
+
},
|
108 |
+
event_whenkeyhit: {
|
109 |
+
restartExistingThreads: false
|
110 |
+
},
|
111 |
+
event_whenmousescrolled: {
|
112 |
+
restartExistingThreads: false
|
113 |
+
},
|
114 |
+
event_whenanything: {
|
115 |
+
restartExistingThreads: false,
|
116 |
+
edgeActivated: true
|
117 |
+
},
|
118 |
+
event_whenjavascript: {
|
119 |
+
restartExistingThreads: false,
|
120 |
+
edgeActivated: true
|
121 |
+
},
|
122 |
+
event_whenthisspriteclicked: {
|
123 |
+
restartExistingThreads: true
|
124 |
+
},
|
125 |
+
event_whentouchingobject: {
|
126 |
+
restartExistingThreads: false,
|
127 |
+
edgeActivated: true
|
128 |
+
},
|
129 |
+
event_whenstageclicked: {
|
130 |
+
restartExistingThreads: true
|
131 |
+
},
|
132 |
+
event_whenbackdropswitchesto: {
|
133 |
+
restartExistingThreads: true
|
134 |
+
},
|
135 |
+
event_whengreaterthan: {
|
136 |
+
restartExistingThreads: false,
|
137 |
+
edgeActivated: true
|
138 |
+
},
|
139 |
+
event_whenbroadcastreceived: {
|
140 |
+
restartExistingThreads: true
|
141 |
+
}
|
142 |
+
};
|
143 |
+
}
|
144 |
+
|
145 |
+
touchingObject (args, util) {
|
146 |
+
return util.target.isTouchingObject(args.TOUCHINGOBJECTMENU);
|
147 |
+
}
|
148 |
+
|
149 |
+
hatGreaterThanPredicate (args, util) {
|
150 |
+
const option = Cast.toString(args.WHENGREATERTHANMENU).toLowerCase();
|
151 |
+
const value = Cast.toNumber(args.VALUE);
|
152 |
+
switch (option) {
|
153 |
+
case 'timer':
|
154 |
+
return util.ioQuery('clock', 'projectTimer') > value;
|
155 |
+
case 'loudness':
|
156 |
+
return this.runtime.audioEngine && this.runtime.audioEngine.getLoudness() > value;
|
157 |
+
}
|
158 |
+
return false;
|
159 |
+
}
|
160 |
+
|
161 |
+
broadcast (args, util) {
|
162 |
+
const broadcastVar = util.runtime.getTargetForStage().lookupBroadcastMsg(
|
163 |
+
args.BROADCAST_OPTION.id, args.BROADCAST_OPTION.name);
|
164 |
+
if (broadcastVar) {
|
165 |
+
const broadcastOption = broadcastVar.name;
|
166 |
+
broadcastVar.isSent = true;
|
167 |
+
util.startHats('event_whenbroadcastreceived', {
|
168 |
+
BROADCAST_OPTION: broadcastOption
|
169 |
+
});
|
170 |
+
}
|
171 |
+
}
|
172 |
+
|
173 |
+
broadcastAndWait (args, util) {
|
174 |
+
if (!util.stackFrame.broadcastVar) {
|
175 |
+
util.stackFrame.broadcastVar = util.runtime.getTargetForStage().lookupBroadcastMsg(
|
176 |
+
args.BROADCAST_OPTION.id, args.BROADCAST_OPTION.name);
|
177 |
+
}
|
178 |
+
if (util.stackFrame.broadcastVar) {
|
179 |
+
const broadcastOption = util.stackFrame.broadcastVar.name;
|
180 |
+
// Have we run before, starting threads?
|
181 |
+
if (!util.stackFrame.startedThreads) {
|
182 |
+
broadcastVar.isSent = true;
|
183 |
+
// No - start hats for this broadcast.
|
184 |
+
util.stackFrame.startedThreads = util.startHats(
|
185 |
+
'event_whenbroadcastreceived', {
|
186 |
+
BROADCAST_OPTION: broadcastOption
|
187 |
+
}
|
188 |
+
);
|
189 |
+
if (util.stackFrame.startedThreads.length === 0) {
|
190 |
+
// Nothing was started.
|
191 |
+
return;
|
192 |
+
}
|
193 |
+
}
|
194 |
+
// We've run before; check if the wait is still going on.
|
195 |
+
const instance = this;
|
196 |
+
// Scratch 2 considers threads to be waiting if they are still in
|
197 |
+
// runtime.threads. Threads that have run all their blocks, or are
|
198 |
+
// marked done but still in runtime.threads are still considered to
|
199 |
+
// be waiting.
|
200 |
+
const waiting = util.stackFrame.startedThreads
|
201 |
+
.some(thread => instance.runtime.threads.indexOf(thread) !== -1);
|
202 |
+
if (waiting) {
|
203 |
+
// If all threads are waiting for the next tick or later yield
|
204 |
+
// for a tick as well. Otherwise yield until the next loop of
|
205 |
+
// the threads.
|
206 |
+
if (
|
207 |
+
util.stackFrame.startedThreads
|
208 |
+
.every(thread => instance.runtime.isWaitingThread(thread))
|
209 |
+
) {
|
210 |
+
util.yieldTick();
|
211 |
+
} else {
|
212 |
+
util.yield();
|
213 |
+
}
|
214 |
+
}
|
215 |
+
}
|
216 |
+
}
|
217 |
+
}
|
218 |
+
|
219 |
+
module.exports = Scratch3EventBlocks;
|
src/blocks/scratch3_looks.js
ADDED
@@ -0,0 +1,996 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const Color = require('../util/color');
|
3 |
+
const Clone = require('../util/clone');
|
4 |
+
const uid = require('../util/uid');
|
5 |
+
const StageLayering = require('../engine/stage-layering');
|
6 |
+
const getMonitorIdForBlockWithArgs = require('../util/get-monitor-id');
|
7 |
+
const MathUtil = require('../util/math-util');
|
8 |
+
|
9 |
+
/**
|
10 |
+
* @typedef {object} BubbleState - the bubble state associated with a particular target.
|
11 |
+
* @property {Boolean} onSpriteRight - tracks whether the bubble is right or left of the sprite.
|
12 |
+
* @property {?int} drawableId - the ID of the associated bubble Drawable, null if none.
|
13 |
+
* @property {string} text - the text of the bubble.
|
14 |
+
* @property {string} type - the type of the bubble, "say" or "think"
|
15 |
+
* @property {?string} usageId - ID indicating the most recent usage of the say/think bubble.
|
16 |
+
* Used for comparison when determining whether to clear a say/think bubble.
|
17 |
+
*/
|
18 |
+
|
19 |
+
class Scratch3LooksBlocks {
|
20 |
+
constructor (runtime) {
|
21 |
+
/**
|
22 |
+
* The runtime instantiating this block package.
|
23 |
+
* @type {Runtime}
|
24 |
+
*/
|
25 |
+
this.runtime = runtime;
|
26 |
+
|
27 |
+
this._onTargetChanged = this._onTargetChanged.bind(this);
|
28 |
+
this._onResetBubbles = this._onResetBubbles.bind(this);
|
29 |
+
this._onTargetWillExit = this._onTargetWillExit.bind(this);
|
30 |
+
this._updateBubble = this._updateBubble.bind(this);
|
31 |
+
|
32 |
+
this.SAY_BUBBLE_LIMITdefault = 330;
|
33 |
+
this.SAY_BUBBLE_LIMIT = this.SAY_BUBBLE_LIMITdefault;
|
34 |
+
this.defaultBubble = {
|
35 |
+
MAX_LINE_WIDTH: 170, // Maximum width, in Scratch pixels, of a single line of text
|
36 |
+
|
37 |
+
MIN_WIDTH: 50, // Minimum width, in Scratch pixels, of a text bubble
|
38 |
+
STROKE_WIDTH: 4, // Thickness of the stroke around the bubble.
|
39 |
+
// Only half's visible because it's drawn under the fill
|
40 |
+
PADDING: 10, // Padding around the text area
|
41 |
+
CORNER_RADIUS: 16, // Radius of the rounded corners
|
42 |
+
TAIL_HEIGHT: 12, // Height of the speech bubble's "tail". Probably should be a constant.
|
43 |
+
|
44 |
+
FONT: 'Helvetica', // Font to render the text with
|
45 |
+
FONT_SIZE: 14, // Font size, in Scratch pixels
|
46 |
+
FONT_HEIGHT_RATIO: 0.9, // Height, in Scratch pixels, of the text, as a proportion of the font's size
|
47 |
+
LINE_HEIGHT: 16, // Spacing between each line of text
|
48 |
+
|
49 |
+
COLORS: {
|
50 |
+
BUBBLE_FILL: 'white',
|
51 |
+
BUBBLE_STROKE: 'rgba(0, 0, 0, 0.15)',
|
52 |
+
TEXT_FILL: '#575E75'
|
53 |
+
}
|
54 |
+
};
|
55 |
+
|
56 |
+
// Reset all bubbles on start/stop
|
57 |
+
this.runtime.on('PROJECT_STOP_ALL', this._onResetBubbles);
|
58 |
+
this.runtime.on('targetWasRemoved', this._onTargetWillExit);
|
59 |
+
|
60 |
+
// Enable other blocks to use bubbles like ask/answer
|
61 |
+
this.runtime.on(Scratch3LooksBlocks.SAY_OR_THINK, this._updateBubble);
|
62 |
+
}
|
63 |
+
|
64 |
+
/**
|
65 |
+
* The default bubble state, to be used when a target has no existing bubble state.
|
66 |
+
* @type {BubbleState}
|
67 |
+
*/
|
68 |
+
static get DEFAULT_BUBBLE_STATE () {
|
69 |
+
return {
|
70 |
+
drawableId: null,
|
71 |
+
onSpriteRight: true,
|
72 |
+
skinId: null,
|
73 |
+
text: '',
|
74 |
+
type: 'say',
|
75 |
+
usageId: null,
|
76 |
+
// @todo make this read from renderer
|
77 |
+
props: this.defaultBubble
|
78 |
+
};
|
79 |
+
}
|
80 |
+
|
81 |
+
/**
|
82 |
+
* The key to load & store a target's bubble-related state.
|
83 |
+
* @type {string}
|
84 |
+
*/
|
85 |
+
static get STATE_KEY () {
|
86 |
+
return 'Scratch.looks';
|
87 |
+
}
|
88 |
+
|
89 |
+
/**
|
90 |
+
* Event name for a text bubble being created or updated.
|
91 |
+
* @const {string}
|
92 |
+
*/
|
93 |
+
static get SAY_OR_THINK () {
|
94 |
+
// There are currently many places in the codebase which explicitly refer to this event by the string 'SAY',
|
95 |
+
// so keep this as the string 'SAY' for now rather than changing it to 'SAY_OR_THINK' and breaking things.
|
96 |
+
return 'SAY';
|
97 |
+
}
|
98 |
+
|
99 |
+
/**
|
100 |
+
* Limit for ghost effect
|
101 |
+
* @const {object}
|
102 |
+
*/
|
103 |
+
static get EFFECT_GHOST_LIMIT (){
|
104 |
+
return {min: 0, max: 100};
|
105 |
+
}
|
106 |
+
|
107 |
+
/**
|
108 |
+
* Limit for brightness effect
|
109 |
+
* @const {object}
|
110 |
+
*/
|
111 |
+
static get EFFECT_BRIGHTNESS_LIMIT (){
|
112 |
+
return {min: -100, max: 100};
|
113 |
+
}
|
114 |
+
|
115 |
+
/**
|
116 |
+
* @param {Target} target - collect bubble state for this target. Probably, but not necessarily, a RenderedTarget.
|
117 |
+
* @returns {BubbleState} the mutable bubble state associated with that target. This will be created if necessary.
|
118 |
+
* @private
|
119 |
+
*/
|
120 |
+
_getBubbleState (target) {
|
121 |
+
let bubbleState = target.getCustomState(Scratch3LooksBlocks.STATE_KEY);
|
122 |
+
if (!bubbleState) {
|
123 |
+
bubbleState = Clone.simple(Scratch3LooksBlocks.DEFAULT_BUBBLE_STATE);
|
124 |
+
target.setCustomState(Scratch3LooksBlocks.STATE_KEY, bubbleState);
|
125 |
+
}
|
126 |
+
return bubbleState;
|
127 |
+
}
|
128 |
+
|
129 |
+
/**
|
130 |
+
* resets the text bubble of a sprite
|
131 |
+
* @param {Target} target the target to reset
|
132 |
+
*/
|
133 |
+
_resetBubbles (target) {
|
134 |
+
const state = this._getBubbleState(target);
|
135 |
+
this.SAY_BUBBLE_LIMIT = this.SAY_BUBBLE_LIMITdefault;
|
136 |
+
state.props = this.defaultBubble;
|
137 |
+
}
|
138 |
+
|
139 |
+
/**
|
140 |
+
* set any property of the text bubble of any given target
|
141 |
+
* @param {Target} target the target to modify
|
142 |
+
* @param {array} props the property names to change
|
143 |
+
* @param {array} value the values the set the properties to
|
144 |
+
*/
|
145 |
+
_setBubbleProperty (target, props, value) {
|
146 |
+
const object = this._getBubbleState(target);
|
147 |
+
if (!object.props) object.props = this.defaultBubble;
|
148 |
+
props.forEach((prop, index) => {
|
149 |
+
if (prop.startsWith('COLORS')) {
|
150 |
+
object.props.COLORS[prop.split('.')[1]] = value[index];
|
151 |
+
} else {
|
152 |
+
object.props[prop] = value[index];
|
153 |
+
}
|
154 |
+
});
|
155 |
+
|
156 |
+
target.setCustomState(Scratch3LooksBlocks.STATE_KEY, object);
|
157 |
+
}
|
158 |
+
|
159 |
+
/**
|
160 |
+
* Handle a target which has moved.
|
161 |
+
* @param {RenderedTarget} target - the target which has moved.
|
162 |
+
* @private
|
163 |
+
*/
|
164 |
+
_onTargetChanged (target) {
|
165 |
+
const bubbleState = this._getBubbleState(target);
|
166 |
+
if (bubbleState.drawableId) {
|
167 |
+
this._positionBubble(target);
|
168 |
+
}
|
169 |
+
}
|
170 |
+
|
171 |
+
/**
|
172 |
+
* Handle a target which is exiting.
|
173 |
+
* @param {RenderedTarget} target - the target.
|
174 |
+
* @private
|
175 |
+
*/
|
176 |
+
_onTargetWillExit (target) {
|
177 |
+
const bubbleState = this._getBubbleState(target);
|
178 |
+
if (bubbleState.drawableId && bubbleState.skinId) {
|
179 |
+
this.runtime.renderer.destroyDrawable(bubbleState.drawableId, StageLayering.SPRITE_LAYER);
|
180 |
+
this.runtime.renderer.destroySkin(bubbleState.skinId);
|
181 |
+
bubbleState.drawableId = null;
|
182 |
+
bubbleState.skinId = null;
|
183 |
+
this.runtime.requestRedraw();
|
184 |
+
}
|
185 |
+
target.onTargetVisualChange = null;
|
186 |
+
}
|
187 |
+
|
188 |
+
/**
|
189 |
+
* Handle project start/stop by clearing all visible bubbles.
|
190 |
+
* @private
|
191 |
+
*/
|
192 |
+
_onResetBubbles () {
|
193 |
+
for (let n = 0; n < this.runtime.targets.length; n++) {
|
194 |
+
const bubbleState = this._getBubbleState(this.runtime.targets[n]);
|
195 |
+
bubbleState.text = '';
|
196 |
+
this._onTargetWillExit(this.runtime.targets[n]);
|
197 |
+
}
|
198 |
+
clearTimeout(this._bubbleTimeout);
|
199 |
+
}
|
200 |
+
|
201 |
+
/**
|
202 |
+
* Position the bubble of a target. If it doesn't fit on the specified side, flip and rerender.
|
203 |
+
* @param {!Target} target Target whose bubble needs positioning.
|
204 |
+
* @private
|
205 |
+
*/
|
206 |
+
_positionBubble (target) {
|
207 |
+
if (!target.visible) return;
|
208 |
+
const bubbleState = this._getBubbleState(target);
|
209 |
+
const [bubbleWidth, bubbleHeight] = this.runtime.renderer.getCurrentSkinSize(bubbleState.drawableId);
|
210 |
+
let targetBounds;
|
211 |
+
try {
|
212 |
+
targetBounds = target.getBoundsForBubble();
|
213 |
+
} catch (error_) {
|
214 |
+
// Bounds calculation could fail (e.g. on empty costumes), in that case
|
215 |
+
// use the x/y position of the target.
|
216 |
+
targetBounds = {
|
217 |
+
left: target.x,
|
218 |
+
right: target.x,
|
219 |
+
top: target.y,
|
220 |
+
bottom: target.y
|
221 |
+
};
|
222 |
+
}
|
223 |
+
const stageSize = this.runtime.renderer.getNativeSize();
|
224 |
+
const stageBounds = {
|
225 |
+
left: -stageSize[0] / 2,
|
226 |
+
right: stageSize[0] / 2,
|
227 |
+
top: stageSize[1] / 2,
|
228 |
+
bottom: -stageSize[1] / 2
|
229 |
+
};
|
230 |
+
if (bubbleState.onSpriteRight && bubbleWidth + targetBounds.right > stageBounds.right &&
|
231 |
+
(targetBounds.left - bubbleWidth > stageBounds.left)) { // Only flip if it would fit
|
232 |
+
bubbleState.onSpriteRight = false;
|
233 |
+
this._renderBubble(target);
|
234 |
+
} else if (!bubbleState.onSpriteRight && targetBounds.left - bubbleWidth < stageBounds.left &&
|
235 |
+
(bubbleWidth + targetBounds.right < stageBounds.right)) { // Only flip if it would fit
|
236 |
+
bubbleState.onSpriteRight = true;
|
237 |
+
this._renderBubble(target);
|
238 |
+
} else {
|
239 |
+
this.runtime.renderer.updateDrawablePosition(bubbleState.drawableId, [
|
240 |
+
bubbleState.onSpriteRight ? (
|
241 |
+
Math.max(
|
242 |
+
stageBounds.left, // Bubble should not extend past left edge of stage
|
243 |
+
Math.min(stageBounds.right - bubbleWidth, targetBounds.right)
|
244 |
+
)
|
245 |
+
) : (
|
246 |
+
Math.min(
|
247 |
+
stageBounds.right - bubbleWidth, // Bubble should not extend past right edge of stage
|
248 |
+
Math.max(stageBounds.left, targetBounds.left - bubbleWidth)
|
249 |
+
)
|
250 |
+
),
|
251 |
+
// Bubble should not extend past the top of the stage
|
252 |
+
Math.min(stageBounds.top, targetBounds.bottom + bubbleHeight)
|
253 |
+
]);
|
254 |
+
this.runtime.requestRedraw();
|
255 |
+
}
|
256 |
+
}
|
257 |
+
|
258 |
+
/**
|
259 |
+
* Create a visible bubble for a target. If a bubble exists for the target,
|
260 |
+
* just set it to visible and update the type/text. Otherwise create a new
|
261 |
+
* bubble and update the relevant custom state.
|
262 |
+
* @param {!Target} target Target who needs a bubble.
|
263 |
+
* @return {undefined} Early return if text is empty string.
|
264 |
+
* @private
|
265 |
+
*/
|
266 |
+
_renderBubble (target) { // used by compiler
|
267 |
+
if (!this.runtime.renderer) return;
|
268 |
+
|
269 |
+
const bubbleState = this._getBubbleState(target);
|
270 |
+
const {type, text, onSpriteRight} = bubbleState;
|
271 |
+
|
272 |
+
// Remove the bubble if target is not visible, or text is being set to blank.
|
273 |
+
if (!target.visible || text === '') {
|
274 |
+
this._onTargetWillExit(target);
|
275 |
+
return;
|
276 |
+
}
|
277 |
+
|
278 |
+
if (bubbleState.skinId) {
|
279 |
+
this.runtime.renderer.updateTextSkin(bubbleState.skinId, type, text, onSpriteRight, bubbleState.props);
|
280 |
+
} else {
|
281 |
+
target.onTargetVisualChange = this._onTargetChanged;
|
282 |
+
bubbleState.drawableId = this.runtime.renderer.createDrawable(StageLayering.SPRITE_LAYER);
|
283 |
+
bubbleState.skinId = this.runtime.renderer.createTextSkin(type, text,
|
284 |
+
bubbleState.onSpriteRight, bubbleState.props);
|
285 |
+
this.runtime.renderer.updateDrawableSkinId(bubbleState.drawableId, bubbleState.skinId);
|
286 |
+
}
|
287 |
+
|
288 |
+
this._positionBubble(target);
|
289 |
+
}
|
290 |
+
|
291 |
+
/**
|
292 |
+
* Properly format text for a text bubble.
|
293 |
+
* @param {string} text The text to be formatted
|
294 |
+
* @return {string} The formatted text
|
295 |
+
* @private
|
296 |
+
*/
|
297 |
+
_formatBubbleText (text) {
|
298 |
+
if (text === '') return text;
|
299 |
+
|
300 |
+
// Non-integers should be rounded to 2 decimal places (no more, no less), unless they're small enough that
|
301 |
+
// rounding would display them as 0.00. This matches 2.0's behavior:
|
302 |
+
// https://github.com/LLK/scratch-flash/blob/2e4a402ceb205a042887f54b26eebe1c2e6da6c0/src/scratch/ScratchSprite.as#L579-L585
|
303 |
+
if (typeof text === 'number' &&
|
304 |
+
Math.abs(text) >= 0.01 && text % 1 !== 0) {
|
305 |
+
text = text.toFixed(2);
|
306 |
+
}
|
307 |
+
|
308 |
+
// Limit the length of the string.
|
309 |
+
text = String(text).slice(0, this.SAY_BUBBLE_LIMIT);
|
310 |
+
|
311 |
+
return text;
|
312 |
+
}
|
313 |
+
|
314 |
+
/**
|
315 |
+
* The entry point for say/think blocks. Clears existing bubble if the text is empty.
|
316 |
+
* Set the bubble custom state and then call _renderBubble.
|
317 |
+
* @param {!Target} target Target that say/think blocks are being called on.
|
318 |
+
* @param {!string} type Either "say" or "think"
|
319 |
+
* @param {!string} text The text for the bubble, empty string clears the bubble.
|
320 |
+
* @private
|
321 |
+
*/
|
322 |
+
_updateBubble (target, type, text) {
|
323 |
+
const bubbleState = this._getBubbleState(target);
|
324 |
+
bubbleState.type = type;
|
325 |
+
bubbleState.text = this._formatBubbleText(text);
|
326 |
+
bubbleState.usageId = uid();
|
327 |
+
this._renderBubble(target);
|
328 |
+
}
|
329 |
+
_percentToRatio (percent) {
|
330 |
+
return percent / 100;
|
331 |
+
}
|
332 |
+
_doesFontSuport (size, font) {
|
333 |
+
const check = size + 'px ' + font;
|
334 |
+
return document.fonts.check(check);
|
335 |
+
}
|
336 |
+
|
337 |
+
/**
|
338 |
+
* Retrieve the block primitives implemented by this package.
|
339 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
340 |
+
*/
|
341 |
+
getPrimitives () {
|
342 |
+
return {
|
343 |
+
looks_say: this.say,
|
344 |
+
looks_sayforsecs: this.sayforsecs,
|
345 |
+
looks_think: this.think,
|
346 |
+
looks_thinkforsecs: this.thinkforsecs,
|
347 |
+
looks_setFont: this.setFont,
|
348 |
+
looks_setColor: this.setColor,
|
349 |
+
looks_setShape: this.setShape,
|
350 |
+
looks_show: this.show,
|
351 |
+
looks_hide: this.hide,
|
352 |
+
looks_getSpriteVisible: this.getSpriteVisible,
|
353 |
+
looks_getOtherSpriteVisible: this.getOtherSpriteVisible,
|
354 |
+
looks_hideallsprites: () => {}, // legacy no-op block
|
355 |
+
looks_switchcostumeto: this.switchCostume,
|
356 |
+
looks_switchbackdropto: this.switchBackdrop,
|
357 |
+
looks_switchbackdroptoandwait: this.switchBackdropAndWait,
|
358 |
+
looks_nextcostume: this.nextCostume,
|
359 |
+
looks_nextbackdrop: this.nextBackdrop,
|
360 |
+
looks_previouscostume: this.previousCostume,
|
361 |
+
looks_previousbackdrop: this.previousBackdrop,
|
362 |
+
looks_changeeffectby: this.changeEffect,
|
363 |
+
looks_seteffectto: this.setEffect,
|
364 |
+
looks_cleargraphiceffects: this.clearEffects,
|
365 |
+
looks_getEffectValue: this.getEffectValue,
|
366 |
+
looks_changesizeby: this.changeSize,
|
367 |
+
looks_setsizeto: this.setSize,
|
368 |
+
looks_changestretchby: () => {},
|
369 |
+
looks_setstretchto: this.stretchSet,
|
370 |
+
looks_gotofrontback: this.goToFrontBack,
|
371 |
+
looks_goforwardbackwardlayers: this.goForwardBackwardLayers,
|
372 |
+
looks_goTargetLayer: this.goTargetLayer,
|
373 |
+
looks_layersSetLayer: this.setSpriteLayer,
|
374 |
+
looks_layersGetLayer: this.getSpriteLayer,
|
375 |
+
looks_size: this.getSize,
|
376 |
+
looks_costumenumbername: this.getCostumeNumberName,
|
377 |
+
looks_backdropnumbername: this.getBackdropNumberName,
|
378 |
+
looks_setStretch: this.stretchSet,
|
379 |
+
looks_changeStretch: this.changeStretch,
|
380 |
+
looks_stretchGetX: this.getStretchX,
|
381 |
+
looks_stretchGetY: this.getStretchY,
|
382 |
+
looks_sayWidth: this.getBubbleWidth,
|
383 |
+
looks_sayHeight: this.getBubbleHeight,
|
384 |
+
looks_changeVisibilityOfSprite: this.showOrHideSprite,
|
385 |
+
looks_changeVisibilityOfSpriteShow: this.showSprite,
|
386 |
+
looks_changeVisibilityOfSpriteHide: this.hideSprite,
|
387 |
+
looks_stoptalking: this.stopTalking,
|
388 |
+
looks_getinputofcostume: this.getCostumeValue,
|
389 |
+
looks_tintColor: this.getTintColor,
|
390 |
+
looks_setTintColor: this.setTintColor
|
391 |
+
};
|
392 |
+
}
|
393 |
+
|
394 |
+
getSpriteLayer (_, util) {
|
395 |
+
const target = util.target;
|
396 |
+
return target.getLayerOrder();
|
397 |
+
}
|
398 |
+
|
399 |
+
setSpriteLayer (args, util) {
|
400 |
+
const target = util.target;
|
401 |
+
const targetLayer = Cast.toNumber(args.NUM);
|
402 |
+
const currentLayer = target.getLayerOrder();
|
403 |
+
// i dont know how to set layer lol
|
404 |
+
target.goForwardLayers(targetLayer - currentLayer);
|
405 |
+
}
|
406 |
+
|
407 |
+
_getBubbleSize (target) {
|
408 |
+
const bubbleState = this._getBubbleState(target);
|
409 |
+
return this.runtime.renderer.getSkinSize(bubbleState.skinId);
|
410 |
+
}
|
411 |
+
|
412 |
+
getBubbleWidth (_, util) {
|
413 |
+
const target = util.target;
|
414 |
+
let val = 0;
|
415 |
+
try {
|
416 |
+
val = this._getBubbleSize(target)[0];
|
417 |
+
} catch {
|
418 |
+
val = 0;
|
419 |
+
}
|
420 |
+
return val;
|
421 |
+
}
|
422 |
+
|
423 |
+
getBubbleHeight (_, util) {
|
424 |
+
const target = util.target;
|
425 |
+
let val = 0;
|
426 |
+
try {
|
427 |
+
val = this._getBubbleSize(target)[1];
|
428 |
+
} catch {
|
429 |
+
val = 0;
|
430 |
+
}
|
431 |
+
return val;
|
432 |
+
}
|
433 |
+
|
434 |
+
getStretchY (args, util) {
|
435 |
+
return util.target._getRenderedDirectionAndScale().stretch[1];
|
436 |
+
}
|
437 |
+
getStretchX (args, util) {
|
438 |
+
return util.target._getRenderedDirectionAndScale().stretch[0];
|
439 |
+
}
|
440 |
+
|
441 |
+
stretchSet (args, util) {
|
442 |
+
util.target.setStretch(args.X, args.Y);
|
443 |
+
}
|
444 |
+
|
445 |
+
changeStretch(args, util) {
|
446 |
+
let [x, y] = util.target._getRenderedDirectionAndScale().stretch;
|
447 |
+
let new_x = x + Cast.toNumber(args.X)
|
448 |
+
let new_y = y + Cast.toNumber(args.Y)
|
449 |
+
util.target.setStretch(new_x, new_y)
|
450 |
+
}
|
451 |
+
|
452 |
+
setFont (args, util) {
|
453 |
+
this._setBubbleProperty(
|
454 |
+
util.target,
|
455 |
+
['FONT', 'FONT_SIZE'],
|
456 |
+
[args.font, args.size]
|
457 |
+
);
|
458 |
+
}
|
459 |
+
setColor (args, util) {
|
460 |
+
const numColor = Number(args.color);
|
461 |
+
if (!isNaN(numColor)) {
|
462 |
+
args.color = Color.decimalToHex(numColor);
|
463 |
+
}
|
464 |
+
this._setBubbleProperty(
|
465 |
+
util.target,
|
466 |
+
['COLORS.' + args.prop],
|
467 |
+
[args.color]
|
468 |
+
);
|
469 |
+
}
|
470 |
+
setShape (args, util) {
|
471 |
+
if (args.prop === 'texlim') {
|
472 |
+
this.SAY_BUBBLE_LIMIT = Math.max(args.color, 1);
|
473 |
+
return;
|
474 |
+
}
|
475 |
+
this._setBubbleProperty(
|
476 |
+
util.target,
|
477 |
+
[args.prop],
|
478 |
+
[args.color]
|
479 |
+
);
|
480 |
+
}
|
481 |
+
|
482 |
+
getMonitored () {
|
483 |
+
return {
|
484 |
+
looks_size: {
|
485 |
+
isSpriteSpecific: true,
|
486 |
+
getId: targetId => `${targetId}_size`
|
487 |
+
},
|
488 |
+
looks_stretchGetX: {
|
489 |
+
isSpriteSpecific: true,
|
490 |
+
getId: targetId => `${targetId}_stretchX`
|
491 |
+
},
|
492 |
+
looks_stretchGetY: {
|
493 |
+
isSpriteSpecific: true,
|
494 |
+
getId: targetId => `${targetId}_stretchY`
|
495 |
+
},
|
496 |
+
looks_sayWidth: {
|
497 |
+
isSpriteSpecific: true,
|
498 |
+
getId: targetId => `${targetId}_sayWidth`
|
499 |
+
},
|
500 |
+
looks_sayHeight: {
|
501 |
+
isSpriteSpecific: true,
|
502 |
+
getId: targetId => `${targetId}_sayHeight`
|
503 |
+
},
|
504 |
+
looks_getEffectValue: {
|
505 |
+
isSpriteSpecific: true,
|
506 |
+
getId: (targetId, fields) => getMonitorIdForBlockWithArgs(`${targetId}_getEffectValue`, fields)
|
507 |
+
},
|
508 |
+
looks_tintColor: {
|
509 |
+
isSpriteSpecific: true,
|
510 |
+
getId: targetId => `${targetId}_tintColor`
|
511 |
+
},
|
512 |
+
looks_getSpriteVisible: {
|
513 |
+
isSpriteSpecific: true,
|
514 |
+
getId: targetId => `${targetId}_getSpriteVisible`
|
515 |
+
},
|
516 |
+
looks_layersGetLayer: {
|
517 |
+
isSpriteSpecific: true,
|
518 |
+
getId: targetId => `${targetId}_layersGetLayer`
|
519 |
+
},
|
520 |
+
looks_costumenumbername: {
|
521 |
+
isSpriteSpecific: true,
|
522 |
+
getId: (targetId, fields) => getMonitorIdForBlockWithArgs(`${targetId}_costumenumbername`, fields)
|
523 |
+
},
|
524 |
+
looks_backdropnumbername: {
|
525 |
+
getId: (_, fields) => getMonitorIdForBlockWithArgs('backdropnumbername', fields)
|
526 |
+
}
|
527 |
+
};
|
528 |
+
}
|
529 |
+
|
530 |
+
say (args, util) {
|
531 |
+
// @TODO in 2.0 calling say/think resets the right/left bias of the bubble
|
532 |
+
const message = args.MESSAGE;
|
533 |
+
this._say(message, util.target);
|
534 |
+
}
|
535 |
+
_say (message, target) { // used by compiler
|
536 |
+
this.runtime.emit(Scratch3LooksBlocks.SAY_OR_THINK, target, 'say', message);
|
537 |
+
}
|
538 |
+
|
539 |
+
stopTalking (_, util) {
|
540 |
+
this.say({ MESSAGE: '' }, util);
|
541 |
+
}
|
542 |
+
|
543 |
+
sayforsecs (args, util) {
|
544 |
+
this.say(args, util);
|
545 |
+
const target = util.target;
|
546 |
+
const usageId = this._getBubbleState(target).usageId;
|
547 |
+
return new Promise(resolve => {
|
548 |
+
this._bubbleTimeout = setTimeout(() => {
|
549 |
+
this._bubbleTimeout = null;
|
550 |
+
// Clear say bubble if it hasn't been changed and proceed.
|
551 |
+
if (this._getBubbleState(target).usageId === usageId) {
|
552 |
+
this._updateBubble(target, 'say', '');
|
553 |
+
}
|
554 |
+
resolve();
|
555 |
+
}, 1000 * args.SECS);
|
556 |
+
});
|
557 |
+
}
|
558 |
+
|
559 |
+
think (args, util) {
|
560 |
+
this.runtime.emit(Scratch3LooksBlocks.SAY_OR_THINK, util.target, 'think', args.MESSAGE);
|
561 |
+
}
|
562 |
+
|
563 |
+
thinkforsecs (args, util) {
|
564 |
+
this.think(args, util);
|
565 |
+
const target = util.target;
|
566 |
+
const usageId = this._getBubbleState(target).usageId;
|
567 |
+
return new Promise(resolve => {
|
568 |
+
this._bubbleTimeout = setTimeout(() => {
|
569 |
+
this._bubbleTimeout = null;
|
570 |
+
// Clear think bubble if it hasn't been changed and proceed.
|
571 |
+
if (this._getBubbleState(target).usageId === usageId) {
|
572 |
+
this._updateBubble(target, 'think', '');
|
573 |
+
}
|
574 |
+
resolve();
|
575 |
+
}, 1000 * args.SECS);
|
576 |
+
});
|
577 |
+
}
|
578 |
+
|
579 |
+
show (args, util) {
|
580 |
+
util.target.setVisible(true);
|
581 |
+
this._renderBubble(util.target);
|
582 |
+
}
|
583 |
+
|
584 |
+
hide (args, util) {
|
585 |
+
util.target.setVisible(false);
|
586 |
+
this._renderBubble(util.target);
|
587 |
+
}
|
588 |
+
|
589 |
+
showOrHideSprite (args, util) {
|
590 |
+
const option = args.VISIBLE_OPTION;
|
591 |
+
const visibleOption = Cast.toString(args.VISIBLE_TYPE).toLowerCase();
|
592 |
+
// Set target
|
593 |
+
let target;
|
594 |
+
if (option === '_myself_') {
|
595 |
+
target = util.target;
|
596 |
+
} else if (option === '_stage_') {
|
597 |
+
target = this.runtime.getTargetForStage();
|
598 |
+
} else {
|
599 |
+
target = this.runtime.getSpriteTargetByName(option);
|
600 |
+
}
|
601 |
+
if (!target) return;
|
602 |
+
target.setVisible(visibleOption === 'show');
|
603 |
+
this._renderBubble(target);
|
604 |
+
}
|
605 |
+
|
606 |
+
showSprite (args, util) {
|
607 |
+
this.showOrHideSprite({ VISIBLE_OPTION: args.VISIBLE_OPTION, VISIBLE_TYPE: "show" }, util);
|
608 |
+
}
|
609 |
+
hideSprite (args, util) {
|
610 |
+
this.showOrHideSprite({ VISIBLE_OPTION: args.VISIBLE_OPTION, VISIBLE_TYPE: "hide" }, util);
|
611 |
+
}
|
612 |
+
|
613 |
+
getSpriteVisible (args, util) {
|
614 |
+
return util.target.visible;
|
615 |
+
}
|
616 |
+
|
617 |
+
getOtherSpriteVisible (args, util) {
|
618 |
+
const option = args.VISIBLE_OPTION;
|
619 |
+
// Set target
|
620 |
+
let target;
|
621 |
+
if (option === '_myself_') {
|
622 |
+
target = util.target;
|
623 |
+
} else if (option === '_stage_') {
|
624 |
+
target = this.runtime.getTargetForStage();
|
625 |
+
} else {
|
626 |
+
target = this.runtime.getSpriteTargetByName(option);
|
627 |
+
}
|
628 |
+
if (!target) return;
|
629 |
+
return target.visible;
|
630 |
+
}
|
631 |
+
|
632 |
+
getEffectValue (args, util) {
|
633 |
+
const effect = Cast.toString(args.EFFECT).toLowerCase();
|
634 |
+
const effects = util.target.effects;
|
635 |
+
if (!effects.hasOwnProperty(effect)) return 0;
|
636 |
+
const value = Cast.toNumber(effects[effect]);
|
637 |
+
return value;
|
638 |
+
}
|
639 |
+
|
640 |
+
getTintColor (_, util) {
|
641 |
+
const effects = util.target.effects;
|
642 |
+
if (typeof effects.tintColor !== 'number') return '#ffffff';
|
643 |
+
return Color.decimalToHex(effects.tintColor - 1);
|
644 |
+
}
|
645 |
+
setTintColor (args, util) { // used by compiler
|
646 |
+
const rgb = Cast.toRgbColorObject(args.color);
|
647 |
+
const decimal = Color.rgbToDecimal(rgb);
|
648 |
+
util.target.setEffect("tintColor", decimal + 1);
|
649 |
+
}
|
650 |
+
|
651 |
+
/**
|
652 |
+
* Utility function to set the costume of a target.
|
653 |
+
* Matches the behavior of Scratch 2.0 for different types of arguments.
|
654 |
+
* @param {!Target} target Target to set costume to.
|
655 |
+
* @param {Any} requestedCostume Costume requested, e.g., 0, 'name', etc.
|
656 |
+
* @param {boolean=} optZeroIndex Set to zero-index the requestedCostume.
|
657 |
+
* @return {Array.<!Thread>} Any threads started by this switch.
|
658 |
+
*/
|
659 |
+
_setCostume (target, requestedCostume, optZeroIndex) { // used by compiler
|
660 |
+
if (typeof requestedCostume === 'number') {
|
661 |
+
// Numbers should be treated as costume indices, always
|
662 |
+
target.setCostume(optZeroIndex ? requestedCostume : requestedCostume - 1);
|
663 |
+
} else {
|
664 |
+
// Strings should be treated as costume names, where possible
|
665 |
+
const costumeIndex = target.getCostumeIndexByName(requestedCostume.toString());
|
666 |
+
|
667 |
+
if (costumeIndex !== -1) {
|
668 |
+
target.setCostume(costumeIndex);
|
669 |
+
} else if (requestedCostume === 'next costume') {
|
670 |
+
target.setCostume(target.currentCostume + 1);
|
671 |
+
} else if (requestedCostume === 'previous costume') {
|
672 |
+
target.setCostume(target.currentCostume - 1);
|
673 |
+
// Try to cast the string to a number (and treat it as a costume index)
|
674 |
+
// Pure whitespace should not be treated as a number
|
675 |
+
// Note: isNaN will cast the string to a number before checking if it's NaN
|
676 |
+
} else if (requestedCostume === 'random costume') {
|
677 |
+
let randomIndex = MathUtil.inclusiveRandIntWithout(
|
678 |
+
0,
|
679 |
+
target.sprite.costumes_.length - 1,
|
680 |
+
target.currentCostume
|
681 |
+
)
|
682 |
+
if (randomIndex >= target.sprite.costumes_.length) {
|
683 |
+
randomIndex = 0;
|
684 |
+
// This really only accounts for if there's only 1
|
685 |
+
// costume.
|
686 |
+
}
|
687 |
+
target.setCostume(randomIndex);
|
688 |
+
} else if (!(isNaN(requestedCostume) || Cast.isWhiteSpace(requestedCostume))) {
|
689 |
+
target.setCostume(optZeroIndex ? Number(requestedCostume) : Number(requestedCostume) - 1);
|
690 |
+
}
|
691 |
+
}
|
692 |
+
|
693 |
+
// Per 2.0, 'switch costume' can't start threads even in the Stage.
|
694 |
+
return [];
|
695 |
+
}
|
696 |
+
|
697 |
+
costumeValueToDefaultNone (value) {
|
698 |
+
switch (value) {
|
699 |
+
case 'width':
|
700 |
+
case 'height':
|
701 |
+
case 'rotation center x':
|
702 |
+
case 'rotation center y':
|
703 |
+
return 0;
|
704 |
+
default:
|
705 |
+
return '';
|
706 |
+
}
|
707 |
+
}
|
708 |
+
getCostumeValue (args, util) {
|
709 |
+
let costumeIndex = 0;
|
710 |
+
const target = util.target
|
711 |
+
const requestedCostume = args.COSTUME;
|
712 |
+
const requestedValue = Cast.toString(args.INPUT);
|
713 |
+
if (typeof requestedCostume === 'number') {
|
714 |
+
// Numbers should be treated as costume indices, always
|
715 |
+
costumeIndex = (requestedCostume === 0) ? 0 : requestedCostume - 1;
|
716 |
+
} else {
|
717 |
+
let noun = target.isStage ? "backdrop" : "costume";
|
718 |
+
switch (Cast.toString(requestedCostume)) {
|
719 |
+
case "next " + noun:
|
720 |
+
costumeIndex = target.currentCostume + 1;
|
721 |
+
if (costumeIndex >= target.sprite.costumes_.length) {
|
722 |
+
costumeIndex = 0
|
723 |
+
// loop around to front
|
724 |
+
}
|
725 |
+
break;
|
726 |
+
case "previous " + noun:
|
727 |
+
costumeIndex = target.currentCostume - 1;
|
728 |
+
if (costumeIndex < 0) {
|
729 |
+
costumeIndex = target.sprite.costumes_.length - 1;
|
730 |
+
// Loop around to back
|
731 |
+
}
|
732 |
+
break;
|
733 |
+
case "random " + noun:
|
734 |
+
costumeIndex = MathUtil.inclusiveRandIntWithout(
|
735 |
+
0,
|
736 |
+
target.sprite.costumes_.length - 1,
|
737 |
+
target.currentCostume
|
738 |
+
)
|
739 |
+
if (costumeIndex >= target.sprite.costumes_.length) {
|
740 |
+
costumeIndex = 0;
|
741 |
+
// This really only accounts for if there's only 1
|
742 |
+
// costume.
|
743 |
+
}
|
744 |
+
break;
|
745 |
+
default:
|
746 |
+
costumeIndex = target.getCostumeIndexByName(Cast.toString(requestedCostume));
|
747 |
+
}
|
748 |
+
}
|
749 |
+
if (costumeIndex < 0) return this.costumeValueToDefaultNone(requestedValue);
|
750 |
+
if (!target.sprite) return this.costumeValueToDefaultNone(requestedValue);
|
751 |
+
if (!target.sprite.costumes_) return this.costumeValueToDefaultNone(requestedValue);
|
752 |
+
const costume = target.sprite.costumes_[costumeIndex];
|
753 |
+
if (!costume) return this.costumeValueToDefaultNone(requestedValue);
|
754 |
+
switch (requestedValue) {
|
755 |
+
case 'width':
|
756 |
+
return costume.size[0];
|
757 |
+
case 'height':
|
758 |
+
return costume.size[1];
|
759 |
+
case 'rotation center x':
|
760 |
+
return costume.rotationCenterX;
|
761 |
+
case 'rotation center y':
|
762 |
+
return costume.rotationCenterY;
|
763 |
+
case 'drawing mode':
|
764 |
+
return ((costume.dataFormat === "svg") ? "Vector" : "Bitmap");
|
765 |
+
default:
|
766 |
+
return '';
|
767 |
+
}
|
768 |
+
}
|
769 |
+
|
770 |
+
/**
|
771 |
+
* Utility function to set the backdrop of a target.
|
772 |
+
* Matches the behavior of Scratch 2.0 for different types of arguments.
|
773 |
+
* @param {!Target} stage Target to set backdrop to.
|
774 |
+
* @param {Any} requestedBackdrop Backdrop requested, e.g., 0, 'name', etc.
|
775 |
+
* @param {boolean=} optZeroIndex Set to zero-index the requestedBackdrop.
|
776 |
+
* @return {Array.<!Thread>} Any threads started by this switch.
|
777 |
+
*/
|
778 |
+
_setBackdrop (stage, requestedBackdrop, optZeroIndex) { // used by compiler
|
779 |
+
if (typeof requestedBackdrop === 'number') {
|
780 |
+
// Numbers should be treated as backdrop indices, always
|
781 |
+
stage.setCostume(optZeroIndex ? requestedBackdrop : requestedBackdrop - 1);
|
782 |
+
} else {
|
783 |
+
// Strings should be treated as backdrop names where possible
|
784 |
+
const costumeIndex = stage.getCostumeIndexByName(requestedBackdrop.toString());
|
785 |
+
|
786 |
+
if (costumeIndex !== -1) {
|
787 |
+
stage.setCostume(costumeIndex);
|
788 |
+
} else if (requestedBackdrop === 'next backdrop') {
|
789 |
+
stage.setCostume(stage.currentCostume + 1);
|
790 |
+
} else if (requestedBackdrop === 'previous backdrop') {
|
791 |
+
stage.setCostume(stage.currentCostume - 1);
|
792 |
+
} else if (requestedBackdrop === 'random backdrop') {
|
793 |
+
const numCostumes = stage.getCostumes().length;
|
794 |
+
if (numCostumes > 1) {
|
795 |
+
// Don't pick the current backdrop, so that the block
|
796 |
+
// will always have an observable effect.
|
797 |
+
const lowerBound = 0;
|
798 |
+
const upperBound = numCostumes - 1;
|
799 |
+
const costumeToExclude = stage.currentCostume;
|
800 |
+
|
801 |
+
const nextCostume = MathUtil.inclusiveRandIntWithout(lowerBound, upperBound, costumeToExclude);
|
802 |
+
|
803 |
+
stage.setCostume(nextCostume);
|
804 |
+
}
|
805 |
+
// Try to cast the string to a number (and treat it as a costume index)
|
806 |
+
// Pure whitespace should not be treated as a number
|
807 |
+
// Note: isNaN will cast the string to a number before checking if it's NaN
|
808 |
+
} else if (!(isNaN(requestedBackdrop) || Cast.isWhiteSpace(requestedBackdrop))) {
|
809 |
+
stage.setCostume(optZeroIndex ? Number(requestedBackdrop) : Number(requestedBackdrop) - 1);
|
810 |
+
}
|
811 |
+
}
|
812 |
+
|
813 |
+
const newName = stage.getCostumes()[stage.currentCostume].name;
|
814 |
+
return this.runtime.startHats('event_whenbackdropswitchesto', {
|
815 |
+
BACKDROP: newName
|
816 |
+
});
|
817 |
+
}
|
818 |
+
|
819 |
+
switchCostume (args, util) {
|
820 |
+
this._setCostume(util.target, args.COSTUME); // used by compiler
|
821 |
+
}
|
822 |
+
|
823 |
+
nextCostume (args, util) {
|
824 |
+
this._setCostume(
|
825 |
+
util.target, util.target.currentCostume + 1, true
|
826 |
+
);
|
827 |
+
}
|
828 |
+
|
829 |
+
previousCostume (args, util) {
|
830 |
+
this._setCostume(
|
831 |
+
util.target, util.target.currentCostume - 1, true
|
832 |
+
);
|
833 |
+
}
|
834 |
+
|
835 |
+
switchBackdrop (args) {
|
836 |
+
this._setBackdrop(this.runtime.getTargetForStage(), args.BACKDROP);
|
837 |
+
}
|
838 |
+
|
839 |
+
switchBackdropAndWait (args, util) {
|
840 |
+
// Have we run before, starting threads?
|
841 |
+
if (!util.stackFrame.startedThreads) {
|
842 |
+
// No - switch the backdrop.
|
843 |
+
util.stackFrame.startedThreads = (
|
844 |
+
this._setBackdrop(
|
845 |
+
this.runtime.getTargetForStage(),
|
846 |
+
args.BACKDROP
|
847 |
+
)
|
848 |
+
);
|
849 |
+
if (util.stackFrame.startedThreads.length === 0) {
|
850 |
+
// Nothing was started.
|
851 |
+
return;
|
852 |
+
}
|
853 |
+
}
|
854 |
+
// We've run before; check if the wait is still going on.
|
855 |
+
const instance = this;
|
856 |
+
// Scratch 2 considers threads to be waiting if they are still in
|
857 |
+
// runtime.threads. Threads that have run all their blocks, or are
|
858 |
+
// marked done but still in runtime.threads are still considered to
|
859 |
+
// be waiting.
|
860 |
+
const waiting = util.stackFrame.startedThreads
|
861 |
+
.some(thread => instance.runtime.threads.indexOf(thread) !== -1);
|
862 |
+
if (waiting) {
|
863 |
+
// If all threads are waiting for the next tick or later yield
|
864 |
+
// for a tick as well. Otherwise yield until the next loop of
|
865 |
+
// the threads.
|
866 |
+
if (
|
867 |
+
util.stackFrame.startedThreads
|
868 |
+
.every(thread => instance.runtime.isWaitingThread(thread))
|
869 |
+
) {
|
870 |
+
util.yieldTick();
|
871 |
+
} else {
|
872 |
+
util.yield();
|
873 |
+
}
|
874 |
+
}
|
875 |
+
}
|
876 |
+
|
877 |
+
nextBackdrop () {
|
878 |
+
const stage = this.runtime.getTargetForStage();
|
879 |
+
this._setBackdrop(
|
880 |
+
stage, stage.currentCostume + 1, true
|
881 |
+
);
|
882 |
+
}
|
883 |
+
|
884 |
+
previousBackdrop() {
|
885 |
+
const stage = this.runtime.getTargetForStage();
|
886 |
+
this._setBackdrop(
|
887 |
+
stage, stage.currentCostume - 1, true
|
888 |
+
);
|
889 |
+
}
|
890 |
+
|
891 |
+
clampEffect (effect, value) { // used by compiler
|
892 |
+
let clampedValue = value;
|
893 |
+
switch (effect) {
|
894 |
+
case 'ghost':
|
895 |
+
clampedValue = MathUtil.clamp(value,
|
896 |
+
Scratch3LooksBlocks.EFFECT_GHOST_LIMIT.min,
|
897 |
+
Scratch3LooksBlocks.EFFECT_GHOST_LIMIT.max);
|
898 |
+
break;
|
899 |
+
case 'brightness':
|
900 |
+
clampedValue = MathUtil.clamp(value,
|
901 |
+
Scratch3LooksBlocks.EFFECT_BRIGHTNESS_LIMIT.min,
|
902 |
+
Scratch3LooksBlocks.EFFECT_BRIGHTNESS_LIMIT.max);
|
903 |
+
break;
|
904 |
+
}
|
905 |
+
return clampedValue;
|
906 |
+
}
|
907 |
+
|
908 |
+
changeEffect (args, util) {
|
909 |
+
const effect = Cast.toString(args.EFFECT).toLowerCase();
|
910 |
+
const change = Cast.toNumber(args.CHANGE);
|
911 |
+
if (!util.target.effects.hasOwnProperty(effect)) return;
|
912 |
+
let newValue = change + util.target.effects[effect];
|
913 |
+
newValue = this.clampEffect(effect, newValue);
|
914 |
+
util.target.setEffect(effect, newValue);
|
915 |
+
}
|
916 |
+
|
917 |
+
setEffect (args, util) {
|
918 |
+
const effect = Cast.toString(args.EFFECT).toLowerCase();
|
919 |
+
let value = Cast.toNumber(args.VALUE);
|
920 |
+
value = this.clampEffect(effect, value);
|
921 |
+
util.target.setEffect(effect, value);
|
922 |
+
}
|
923 |
+
|
924 |
+
clearEffects (args, util) {
|
925 |
+
util.target.clearEffects();
|
926 |
+
this._resetBubbles(util.target);
|
927 |
+
}
|
928 |
+
|
929 |
+
changeSize (args, util) {
|
930 |
+
const change = Cast.toNumber(args.CHANGE);
|
931 |
+
util.target.setSize(util.target.size + change);
|
932 |
+
}
|
933 |
+
|
934 |
+
setSize (args, util) {
|
935 |
+
const size = Cast.toNumber(args.SIZE);
|
936 |
+
util.target.setSize(size);
|
937 |
+
}
|
938 |
+
|
939 |
+
goToFrontBack (args, util) {
|
940 |
+
if (!util.target.isStage) {
|
941 |
+
if (args.FRONT_BACK === 'front') {
|
942 |
+
util.target.goToFront();
|
943 |
+
} else {
|
944 |
+
util.target.goToBack();
|
945 |
+
}
|
946 |
+
}
|
947 |
+
}
|
948 |
+
|
949 |
+
goForwardBackwardLayers (args, util) {
|
950 |
+
if (!util.target.isStage) {
|
951 |
+
if (args.FORWARD_BACKWARD === 'forward') {
|
952 |
+
util.target.goForwardLayers(Cast.toNumber(args.NUM));
|
953 |
+
} else {
|
954 |
+
util.target.goBackwardLayers(Cast.toNumber(args.NUM));
|
955 |
+
}
|
956 |
+
}
|
957 |
+
}
|
958 |
+
|
959 |
+
goTargetLayer (args, util) {
|
960 |
+
let target;
|
961 |
+
const option = args.VISIBLE_OPTION;
|
962 |
+
if (option === '_stage_') target = this.runtime.getTargetForStage();
|
963 |
+
else target = this.runtime.getSpriteTargetByName(option);
|
964 |
+
if (!util.target.isStage && target) {
|
965 |
+
if (args.FORWARD_BACKWARD === 'infront') {
|
966 |
+
util.target.goBehindOther(target);
|
967 |
+
util.target.goForwardLayers(1);
|
968 |
+
} else {
|
969 |
+
util.target.goBehindOther(target);
|
970 |
+
}
|
971 |
+
}
|
972 |
+
}
|
973 |
+
|
974 |
+
getSize (args, util) {
|
975 |
+
return Math.round(util.target.size);
|
976 |
+
}
|
977 |
+
|
978 |
+
getBackdropNumberName (args) {
|
979 |
+
const stage = this.runtime.getTargetForStage();
|
980 |
+
if (args.NUMBER_NAME === 'number') {
|
981 |
+
return stage.currentCostume + 1;
|
982 |
+
}
|
983 |
+
// Else return name
|
984 |
+
return stage.getCostumes()[stage.currentCostume].name;
|
985 |
+
}
|
986 |
+
|
987 |
+
getCostumeNumberName (args, util) {
|
988 |
+
if (args.NUMBER_NAME === 'number') {
|
989 |
+
return util.target.currentCostume + 1;
|
990 |
+
}
|
991 |
+
// Else return name
|
992 |
+
return util.target.getCostumes()[util.target.currentCostume].name;
|
993 |
+
}
|
994 |
+
}
|
995 |
+
|
996 |
+
module.exports = Scratch3LooksBlocks;
|
src/blocks/scratch3_motion.js
ADDED
@@ -0,0 +1,532 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const MathUtil = require('../util/math-util');
|
3 |
+
const Timer = require('../util/timer');
|
4 |
+
|
5 |
+
const STAGE_ALIGNMENT = {
|
6 |
+
TOP_LEFT: 'top-left',
|
7 |
+
TOP_RIGHT: 'top-right',
|
8 |
+
BOTTOM_LEFT: 'bottom-left',
|
9 |
+
BOTTOM_RIGHT: 'bottom-right',
|
10 |
+
TOP: 'top',
|
11 |
+
LEFT: 'left',
|
12 |
+
RIGHT: 'right',
|
13 |
+
MIDDLE: 'middle',
|
14 |
+
BOTTOM: 'bottom'
|
15 |
+
};
|
16 |
+
|
17 |
+
class Scratch3MotionBlocks {
|
18 |
+
constructor (runtime) {
|
19 |
+
/**
|
20 |
+
* The runtime instantiating this block package.
|
21 |
+
* @type {Runtime}
|
22 |
+
*/
|
23 |
+
this.runtime = runtime;
|
24 |
+
}
|
25 |
+
|
26 |
+
/**
|
27 |
+
* Retrieve the block primitives implemented by this package.
|
28 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
29 |
+
*/
|
30 |
+
getPrimitives () {
|
31 |
+
return {
|
32 |
+
motion_movesteps: this.moveSteps,
|
33 |
+
motion_movebacksteps: this.moveStepsBack,
|
34 |
+
motion_moveupdownsteps: this.moveStepsUpDown,
|
35 |
+
motion_gotoxy: this.goToXY,
|
36 |
+
motion_goto: this.goTo,
|
37 |
+
motion_turnright: this.turnRight,
|
38 |
+
motion_turnleft: this.turnLeft,
|
39 |
+
motion_turnrightaroundxy: this.turnRightAround,
|
40 |
+
motion_turnleftaroundxy: this.turnLeftAround,
|
41 |
+
motion_turnaround: this.turnAround,
|
42 |
+
motion_pointinrandomdirection: this.pointInDirectionRandom,
|
43 |
+
motion_pointtowardsxy: this.pointTowardsXY,
|
44 |
+
motion_pointindirection: this.pointInDirection,
|
45 |
+
motion_pointtowards: this.pointTowards,
|
46 |
+
motion_glidesecstoxy: this.glide,
|
47 |
+
motion_glideto: this.glideTo,
|
48 |
+
motion_ifonedgebounce: this.ifOnEdgeBounce,
|
49 |
+
motion_ifonxybounce: this.ifOnXYBounce,
|
50 |
+
motion_ifonspritebounce: this.ifOnSpriteBounce,
|
51 |
+
motion_setrotationstyle: this.setRotationStyle,
|
52 |
+
motion_changexby: this.changeX,
|
53 |
+
motion_setx: this.setX,
|
54 |
+
motion_changeyby: this.changeY,
|
55 |
+
motion_sety: this.setY,
|
56 |
+
motion_changebyxy: this.changeXY,
|
57 |
+
motion_xposition: this.getX,
|
58 |
+
motion_yposition: this.getY,
|
59 |
+
motion_direction: this.getDirection,
|
60 |
+
motion_move_sprite_to_scene_side: this.moveToStageSide,
|
61 |
+
// Legacy no-op blocks:
|
62 |
+
motion_scroll_right: () => {},
|
63 |
+
motion_scroll_up: () => {},
|
64 |
+
motion_align_scene: () => {},
|
65 |
+
motion_xscroll: () => {},
|
66 |
+
motion_yscroll: () => {}
|
67 |
+
};
|
68 |
+
}
|
69 |
+
|
70 |
+
moveToStageSide(args, util) {
|
71 |
+
if (!this.runtime.renderer) return;
|
72 |
+
const side = Cast.toString(args.ALIGNMENT);
|
73 |
+
const stageWidth = this.runtime.stageWidth / 2;
|
74 |
+
const stageHeight = this.runtime.stageHeight / 2;
|
75 |
+
const snap = [];
|
76 |
+
switch (side) {
|
77 |
+
case STAGE_ALIGNMENT.TOP:
|
78 |
+
util.target.setXY(0, stageHeight);
|
79 |
+
snap.push('top');
|
80 |
+
break;
|
81 |
+
case STAGE_ALIGNMENT.LEFT:
|
82 |
+
util.target.setXY(0 - stageWidth, 0);
|
83 |
+
snap.push('left');
|
84 |
+
break;
|
85 |
+
case STAGE_ALIGNMENT.MIDDLE:
|
86 |
+
util.target.setXY(0, 0);
|
87 |
+
break;
|
88 |
+
case STAGE_ALIGNMENT.RIGHT:
|
89 |
+
util.target.setXY(stageWidth, 0);
|
90 |
+
snap.push('right');
|
91 |
+
break;
|
92 |
+
case STAGE_ALIGNMENT.BOTTOM:
|
93 |
+
util.target.setXY(0, 0 - stageHeight);
|
94 |
+
snap.push('bottom');
|
95 |
+
break;
|
96 |
+
case STAGE_ALIGNMENT.TOP_LEFT:
|
97 |
+
util.target.setXY(0 - stageWidth, stageHeight);
|
98 |
+
snap.push('top');
|
99 |
+
snap.push('left');
|
100 |
+
break;
|
101 |
+
case STAGE_ALIGNMENT.TOP_RIGHT:
|
102 |
+
util.target.setXY(stageWidth, stageHeight);
|
103 |
+
snap.push('top');
|
104 |
+
snap.push('right');
|
105 |
+
break;
|
106 |
+
case STAGE_ALIGNMENT.BOTTOM_LEFT:
|
107 |
+
util.target.setXY(0 - stageWidth, 0 - stageHeight);
|
108 |
+
snap.push('bottom');
|
109 |
+
snap.push('left');
|
110 |
+
break;
|
111 |
+
case STAGE_ALIGNMENT.BOTTOM_RIGHT:
|
112 |
+
util.target.setXY(stageWidth, 0 - stageHeight);
|
113 |
+
snap.push('bottom');
|
114 |
+
snap.push('right');
|
115 |
+
break;
|
116 |
+
}
|
117 |
+
const drawableID = util.target.drawableID;
|
118 |
+
const drawable = this.runtime.renderer._allDrawables[drawableID];
|
119 |
+
const boundingBox = drawable._skin.getFenceBounds(drawable);
|
120 |
+
snap.forEach(side => {
|
121 |
+
switch (side) {
|
122 |
+
case 'top':
|
123 |
+
util.target.setXY(util.target.x, boundingBox.bottom);
|
124 |
+
break;
|
125 |
+
case 'bottom':
|
126 |
+
util.target.setXY(util.target.x, boundingBox.top);
|
127 |
+
break;
|
128 |
+
case 'left':
|
129 |
+
util.target.setXY(boundingBox.right, util.target.y);
|
130 |
+
break;
|
131 |
+
case 'right':
|
132 |
+
util.target.setXY(boundingBox.left, util.target.y);
|
133 |
+
break;
|
134 |
+
}
|
135 |
+
});
|
136 |
+
}
|
137 |
+
|
138 |
+
getMonitored () {
|
139 |
+
return {
|
140 |
+
motion_xposition: {
|
141 |
+
isSpriteSpecific: true,
|
142 |
+
getId: targetId => `${targetId}_xposition`
|
143 |
+
},
|
144 |
+
motion_yposition: {
|
145 |
+
isSpriteSpecific: true,
|
146 |
+
getId: targetId => `${targetId}_yposition`
|
147 |
+
},
|
148 |
+
motion_direction: {
|
149 |
+
isSpriteSpecific: true,
|
150 |
+
getId: targetId => `${targetId}_direction`
|
151 |
+
}
|
152 |
+
};
|
153 |
+
}
|
154 |
+
|
155 |
+
moveSteps (args, util) {
|
156 |
+
const steps = Cast.toNumber(args.STEPS);
|
157 |
+
this._moveSteps(steps, util.target);
|
158 |
+
}
|
159 |
+
moveStepsBack (args, util) {
|
160 |
+
const steps = Cast.toNumber(args.STEPS);
|
161 |
+
this._moveSteps(0 - steps, util.target);
|
162 |
+
}
|
163 |
+
moveStepsUpDown (args, util) {
|
164 |
+
const direction = Cast.toString(args.DIRECTION);
|
165 |
+
const steps = Cast.toNumber(args.STEPS);
|
166 |
+
this.turnLeft({ DEGREES: 90 }, util);
|
167 |
+
if (direction === 'up') {
|
168 |
+
this._moveSteps(steps, util.target);
|
169 |
+
} else if (direction === 'down') {
|
170 |
+
this._moveSteps(0 - steps, util.target);
|
171 |
+
}
|
172 |
+
this.turnRight({ DEGREES: 90 }, util);
|
173 |
+
}
|
174 |
+
_moveSteps (steps, target) { // used by compiler
|
175 |
+
const radians = MathUtil.degToRad(90 - target.direction);
|
176 |
+
const dx = steps * Math.cos(radians);
|
177 |
+
const dy = steps * Math.sin(radians);
|
178 |
+
target.setXY(target.x + dx, target.y + dy);
|
179 |
+
}
|
180 |
+
|
181 |
+
goToXY (args, util) {
|
182 |
+
const x = Cast.toNumber(args.X);
|
183 |
+
const y = Cast.toNumber(args.Y);
|
184 |
+
util.target.setXY(x, y);
|
185 |
+
}
|
186 |
+
|
187 |
+
getTargetXY (targetName, util) {
|
188 |
+
let targetX = 0;
|
189 |
+
let targetY = 0;
|
190 |
+
if (targetName === '_mouse_') {
|
191 |
+
targetX = util.ioQuery('mouse', 'getScratchX');
|
192 |
+
targetY = util.ioQuery('mouse', 'getScratchY');
|
193 |
+
} else if (targetName === '_random_') {
|
194 |
+
const stageWidth = this.runtime.stageWidth;
|
195 |
+
const stageHeight = this.runtime.stageHeight;
|
196 |
+
targetX = Math.round(stageWidth * (Math.random() - 0.5));
|
197 |
+
targetY = Math.round(stageHeight * (Math.random() - 0.5));
|
198 |
+
} else {
|
199 |
+
targetName = Cast.toString(targetName);
|
200 |
+
const goToTarget = this.runtime.getSpriteTargetByName(targetName);
|
201 |
+
if (!goToTarget) return;
|
202 |
+
targetX = goToTarget.x;
|
203 |
+
targetY = goToTarget.y;
|
204 |
+
}
|
205 |
+
return [targetX, targetY];
|
206 |
+
}
|
207 |
+
|
208 |
+
goTo (args, util) {
|
209 |
+
const targetXY = this.getTargetXY(args.TO, util);
|
210 |
+
if (targetXY) {
|
211 |
+
util.target.setXY(targetXY[0], targetXY[1]);
|
212 |
+
}
|
213 |
+
}
|
214 |
+
|
215 |
+
turnRight (args, util) {
|
216 |
+
const degrees = Cast.toNumber(args.DEGREES);
|
217 |
+
util.target.setDirection(util.target.direction + degrees);
|
218 |
+
}
|
219 |
+
|
220 |
+
turnLeft (args, util) {
|
221 |
+
const degrees = Cast.toNumber(args.DEGREES);
|
222 |
+
util.target.setDirection(util.target.direction - degrees);
|
223 |
+
}
|
224 |
+
|
225 |
+
turnRightAround (args, util) {
|
226 |
+
this.turnLeftAround({
|
227 |
+
DEGREES: -Cast.toNumber(args.DEGREES),
|
228 |
+
X: Cast.toNumber(args.X),
|
229 |
+
Y: Cast.toNumber(args.Y)
|
230 |
+
}, util);
|
231 |
+
}
|
232 |
+
|
233 |
+
turnLeftAround (args, util) {
|
234 |
+
const degrees = Cast.toNumber(args.DEGREES);
|
235 |
+
|
236 |
+
const center = {
|
237 |
+
x: Cast.toNumber(args.X),
|
238 |
+
y: Cast.toNumber(args.Y)
|
239 |
+
};
|
240 |
+
const radians = (Math.PI * degrees) / 180;
|
241 |
+
const cos = Math.cos(radians);
|
242 |
+
const sin = Math.sin(radians);
|
243 |
+
const dx = util.target.x - center.x;
|
244 |
+
const dy = util.target.y - center.y;
|
245 |
+
const newPosition = {
|
246 |
+
x: (cos * dx) - (sin * dy) + center.x,
|
247 |
+
y: (cos * dy) + (sin * dx) + center.y
|
248 |
+
};
|
249 |
+
util.target.setXY(newPosition.x, newPosition.y);
|
250 |
+
}
|
251 |
+
|
252 |
+
pointInDirection (args, util) {
|
253 |
+
const direction = Cast.toNumber(args.DIRECTION);
|
254 |
+
util.target.setDirection(direction);
|
255 |
+
}
|
256 |
+
|
257 |
+
turnAround (_, util) {
|
258 |
+
this.turnRight({ DEGREES: 180 }, util);
|
259 |
+
}
|
260 |
+
|
261 |
+
pointInDirectionRandom (_, util) {
|
262 |
+
this.pointTowards({ TOWARDS: '_random_' }, util);
|
263 |
+
}
|
264 |
+
|
265 |
+
pointTowardsXY (args, util) {
|
266 |
+
const targetX = Cast.toNumber(args.X);
|
267 |
+
const targetY = Cast.toNumber(args.Y);
|
268 |
+
|
269 |
+
const dx = targetX - util.target.x;
|
270 |
+
const dy = targetY - util.target.y;
|
271 |
+
const direction = 90 - MathUtil.radToDeg(Math.atan2(dy, dx));
|
272 |
+
util.target.setDirection(direction);
|
273 |
+
}
|
274 |
+
|
275 |
+
pointTowards (args, util) {
|
276 |
+
let targetX = 0;
|
277 |
+
let targetY = 0;
|
278 |
+
if (args.TOWARDS === '_mouse_') {
|
279 |
+
targetX = util.ioQuery('mouse', 'getScratchX');
|
280 |
+
targetY = util.ioQuery('mouse', 'getScratchY');
|
281 |
+
} else if (args.TOWARDS === '_random_') {
|
282 |
+
util.target.setDirection(Math.round(Math.random() * 360) - 180);
|
283 |
+
return;
|
284 |
+
} else {
|
285 |
+
args.TOWARDS = Cast.toString(args.TOWARDS);
|
286 |
+
const pointTarget = this.runtime.getSpriteTargetByName(args.TOWARDS);
|
287 |
+
if (!pointTarget) return;
|
288 |
+
targetX = pointTarget.x;
|
289 |
+
targetY = pointTarget.y;
|
290 |
+
}
|
291 |
+
|
292 |
+
const dx = targetX - util.target.x;
|
293 |
+
const dy = targetY - util.target.y;
|
294 |
+
const direction = 90 - MathUtil.radToDeg(Math.atan2(dy, dx));
|
295 |
+
util.target.setDirection(direction);
|
296 |
+
}
|
297 |
+
|
298 |
+
glide (args, util) {
|
299 |
+
if (util.stackFrame.timer) {
|
300 |
+
const timeElapsed = util.stackFrame.timer.timeElapsed();
|
301 |
+
if (timeElapsed < util.stackFrame.duration * 1000) {
|
302 |
+
// In progress: move to intermediate position.
|
303 |
+
const frac = timeElapsed / (util.stackFrame.duration * 1000);
|
304 |
+
const dx = frac * (util.stackFrame.endX - util.stackFrame.startX);
|
305 |
+
const dy = frac * (util.stackFrame.endY - util.stackFrame.startY);
|
306 |
+
util.target.setXY(
|
307 |
+
util.stackFrame.startX + dx,
|
308 |
+
util.stackFrame.startY + dy
|
309 |
+
);
|
310 |
+
util.yield();
|
311 |
+
} else {
|
312 |
+
// Finished: move to final position.
|
313 |
+
util.target.setXY(util.stackFrame.endX, util.stackFrame.endY);
|
314 |
+
}
|
315 |
+
} else {
|
316 |
+
// First time: save data for future use.
|
317 |
+
util.stackFrame.timer = new Timer();
|
318 |
+
util.stackFrame.timer.start();
|
319 |
+
util.stackFrame.duration = Cast.toNumber(args.SECS);
|
320 |
+
util.stackFrame.startX = util.target.x;
|
321 |
+
util.stackFrame.startY = util.target.y;
|
322 |
+
util.stackFrame.endX = Cast.toNumber(args.X);
|
323 |
+
util.stackFrame.endY = Cast.toNumber(args.Y);
|
324 |
+
if (util.stackFrame.duration <= 0) {
|
325 |
+
// Duration too short to glide.
|
326 |
+
util.target.setXY(util.stackFrame.endX, util.stackFrame.endY);
|
327 |
+
return;
|
328 |
+
}
|
329 |
+
util.yield();
|
330 |
+
}
|
331 |
+
}
|
332 |
+
|
333 |
+
glideTo (args, util) {
|
334 |
+
const targetXY = this.getTargetXY(args.TO, util);
|
335 |
+
if (targetXY) {
|
336 |
+
this.glide({SECS: args.SECS, X: targetXY[0], Y: targetXY[1]}, util);
|
337 |
+
}
|
338 |
+
}
|
339 |
+
|
340 |
+
ifOnEdgeBounce (args, util) {
|
341 |
+
this._ifOnEdgeBounce(util.target);
|
342 |
+
}
|
343 |
+
_ifOnEdgeBounce (target) { // used by compiler
|
344 |
+
const bounds = target.getBounds();
|
345 |
+
if (!bounds) {
|
346 |
+
return;
|
347 |
+
}
|
348 |
+
// Measure distance to edges.
|
349 |
+
// Values are positive when the sprite is far away,
|
350 |
+
// and clamped to zero when the sprite is beyond.
|
351 |
+
const stageWidth = this.runtime.stageWidth;
|
352 |
+
const stageHeight = this.runtime.stageHeight;
|
353 |
+
const distLeft = Math.max(0, (stageWidth / 2) + bounds.left);
|
354 |
+
const distTop = Math.max(0, (stageHeight / 2) - bounds.top);
|
355 |
+
const distRight = Math.max(0, (stageWidth / 2) - bounds.right);
|
356 |
+
const distBottom = Math.max(0, (stageHeight / 2) + bounds.bottom);
|
357 |
+
// Find the nearest edge.
|
358 |
+
let nearestEdge = '';
|
359 |
+
let minDist = Infinity;
|
360 |
+
if (distLeft < minDist) {
|
361 |
+
minDist = distLeft;
|
362 |
+
nearestEdge = 'left';
|
363 |
+
}
|
364 |
+
if (distTop < minDist) {
|
365 |
+
minDist = distTop;
|
366 |
+
nearestEdge = 'top';
|
367 |
+
}
|
368 |
+
if (distRight < minDist) {
|
369 |
+
minDist = distRight;
|
370 |
+
nearestEdge = 'right';
|
371 |
+
}
|
372 |
+
if (distBottom < minDist) {
|
373 |
+
minDist = distBottom;
|
374 |
+
nearestEdge = 'bottom';
|
375 |
+
}
|
376 |
+
if (minDist > 0) {
|
377 |
+
return; // Not touching any edge.
|
378 |
+
}
|
379 |
+
// Point away from the nearest edge.
|
380 |
+
const radians = MathUtil.degToRad(90 - target.direction);
|
381 |
+
let dx = Math.cos(radians);
|
382 |
+
let dy = -Math.sin(radians);
|
383 |
+
if (nearestEdge === 'left') {
|
384 |
+
dx = Math.max(0.2, Math.abs(dx));
|
385 |
+
} else if (nearestEdge === 'top') {
|
386 |
+
dy = Math.max(0.2, Math.abs(dy));
|
387 |
+
} else if (nearestEdge === 'right') {
|
388 |
+
dx = 0 - Math.max(0.2, Math.abs(dx));
|
389 |
+
} else if (nearestEdge === 'bottom') {
|
390 |
+
dy = 0 - Math.max(0.2, Math.abs(dy));
|
391 |
+
}
|
392 |
+
const newDirection = MathUtil.radToDeg(Math.atan2(dy, dx)) + 90;
|
393 |
+
target.setDirection(newDirection);
|
394 |
+
// Keep within the stage.
|
395 |
+
const fencedPosition = target.keepInFence(target.x, target.y);
|
396 |
+
target.setXY(fencedPosition[0], fencedPosition[1]);
|
397 |
+
}
|
398 |
+
ifOnXYBounce(args, util, _, __, ___, touchingCondition) {
|
399 |
+
const x = Cast.toNumber(args.X);
|
400 |
+
const y = Cast.toNumber(args.Y);
|
401 |
+
const target = util.target;
|
402 |
+
const bounds = target.getBounds();
|
403 |
+
if (!bounds) {
|
404 |
+
return;
|
405 |
+
}
|
406 |
+
// Check to see if the point is inside the bounding box.
|
407 |
+
const xInBounds = (x >= bounds.left) && (x <= bounds.right);
|
408 |
+
const yInBounds = (y >= bounds.bottom) && (y <= bounds.top);
|
409 |
+
if (touchingCondition !== true) {
|
410 |
+
if (!(xInBounds && yInBounds)) {
|
411 |
+
return; // Not inside the bounding box.
|
412 |
+
}
|
413 |
+
}
|
414 |
+
// Find the distance to the point for all sides.
|
415 |
+
// We use this to figure out which side to bounce on.
|
416 |
+
let nearestEdge = '';
|
417 |
+
let minDist = Infinity;
|
418 |
+
for (let i = 0; i < 4; i++) {
|
419 |
+
const sides = ['left', 'top', 'right', 'bottom'];
|
420 |
+
let distx;
|
421 |
+
let disty;
|
422 |
+
switch (sides[i]) {
|
423 |
+
case 'left':
|
424 |
+
case 'right':
|
425 |
+
distx = x - bounds[sides[i]];
|
426 |
+
disty = y - target.y;
|
427 |
+
break;
|
428 |
+
case 'top':
|
429 |
+
case 'bottom':
|
430 |
+
distx = x - target.x;
|
431 |
+
disty = y - bounds[sides[i]];
|
432 |
+
break;
|
433 |
+
}
|
434 |
+
const distance = Math.sqrt((distx * distx) + (disty * disty));
|
435 |
+
if (distance < minDist) {
|
436 |
+
minDist = distance;
|
437 |
+
nearestEdge = sides[i];
|
438 |
+
}
|
439 |
+
}
|
440 |
+
// Point away from the nearest edge.
|
441 |
+
const radians = MathUtil.degToRad(90 - target.direction);
|
442 |
+
let dx = Math.cos(radians);
|
443 |
+
let dy = -Math.sin(radians);
|
444 |
+
if (nearestEdge === 'left') {
|
445 |
+
dx = Math.max(0.2, Math.abs(dx));
|
446 |
+
} else if (nearestEdge === 'top') {
|
447 |
+
dy = Math.max(0.2, Math.abs(dy));
|
448 |
+
} else if (nearestEdge === 'right') {
|
449 |
+
dx = 0 - Math.max(0.2, Math.abs(dx));
|
450 |
+
} else if (nearestEdge === 'bottom') {
|
451 |
+
dy = 0 - Math.max(0.2, Math.abs(dy));
|
452 |
+
}
|
453 |
+
const newDirection = MathUtil.radToDeg(Math.atan2(dy, dx)) + 90;
|
454 |
+
target.setDirection(newDirection);
|
455 |
+
// Keep within the stage.
|
456 |
+
const fencedPosition = target.keepInFence(target.x, target.y);
|
457 |
+
target.setXY(fencedPosition[0], fencedPosition[1]);
|
458 |
+
}
|
459 |
+
ifOnSpriteBounce (args, util) {
|
460 |
+
if (args.SPRITE === '_mouse_') {
|
461 |
+
const x = util.ioQuery('mouse', 'getScratchX');
|
462 |
+
const y = util.ioQuery('mouse', 'getScratchY');
|
463 |
+
return this.ifOnXYBounce({ X: x, Y: y }, util);
|
464 |
+
} else if (args.SPRITE === '_random_') {
|
465 |
+
const stageWidth = this.runtime.stageWidth;
|
466 |
+
const stageHeight = this.runtime.stageHeight;
|
467 |
+
const x = Math.round(stageWidth * (Math.random() - 0.5));
|
468 |
+
const y = Math.round(stageHeight * (Math.random() - 0.5));
|
469 |
+
return this.ifOnXYBounce({ X: x, Y: y }, util);
|
470 |
+
}
|
471 |
+
const spriteName = Cast.toString(args.SPRITE);
|
472 |
+
const bounceTarget = this.runtime.getSpriteTargetByName(spriteName);
|
473 |
+
if (!bounceTarget) return;
|
474 |
+
const point = util.target.spriteTouchingPoint(spriteName);
|
475 |
+
if (!point) return;
|
476 |
+
return this.ifOnXYBounce({ X: point[0], Y: point[1] }, util);
|
477 |
+
|
478 |
+
}
|
479 |
+
|
480 |
+
setRotationStyle (args, util) {
|
481 |
+
util.target.setRotationStyle(args.STYLE);
|
482 |
+
}
|
483 |
+
|
484 |
+
changeX (args, util) {
|
485 |
+
const dx = Cast.toNumber(args.DX);
|
486 |
+
util.target.setXY(util.target.x + dx, util.target.y);
|
487 |
+
}
|
488 |
+
|
489 |
+
setX (args, util) {
|
490 |
+
const x = Cast.toNumber(args.X);
|
491 |
+
util.target.setXY(x, util.target.y);
|
492 |
+
}
|
493 |
+
|
494 |
+
changeY (args, util) {
|
495 |
+
const dy = Cast.toNumber(args.DY);
|
496 |
+
util.target.setXY(util.target.x, util.target.y + dy);
|
497 |
+
}
|
498 |
+
|
499 |
+
setY (args, util) {
|
500 |
+
const y = Cast.toNumber(args.Y);
|
501 |
+
util.target.setXY(util.target.x, y);
|
502 |
+
}
|
503 |
+
|
504 |
+
changeXY (args, util) {
|
505 |
+
const dx = Cast.toNumber(args.DX);
|
506 |
+
const dy = Cast.toNumber(args.DY);
|
507 |
+
util.target.setXY(util.target.x + dx, util.target.y + dy);
|
508 |
+
}
|
509 |
+
|
510 |
+
getX (args, util) {
|
511 |
+
return this.limitPrecision(util.target.x);
|
512 |
+
}
|
513 |
+
|
514 |
+
getY (args, util) {
|
515 |
+
return this.limitPrecision(util.target.y);
|
516 |
+
}
|
517 |
+
|
518 |
+
getDirection (args, util) {
|
519 |
+
return util.target.direction;
|
520 |
+
}
|
521 |
+
|
522 |
+
// This corresponds to snapToInteger in Scratch 2
|
523 |
+
limitPrecision (coordinate) {
|
524 |
+
const rounded = Math.round(coordinate);
|
525 |
+
const delta = coordinate - rounded;
|
526 |
+
const limitedCoord = (Math.abs(delta) < 1e-9) ? rounded : coordinate;
|
527 |
+
|
528 |
+
return limitedCoord;
|
529 |
+
}
|
530 |
+
}
|
531 |
+
|
532 |
+
module.exports = Scratch3MotionBlocks;
|
src/blocks/scratch3_operators.js
ADDED
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast.js');
|
2 |
+
const MathUtil = require('../util/math-util.js');
|
3 |
+
const SandboxRunner = require('../util/sandboxed-javascript-runner.js');
|
4 |
+
const { validateRegex } = require('../util/json-block-utilities');
|
5 |
+
|
6 |
+
class Scratch3OperatorsBlocks {
|
7 |
+
constructor (runtime) {
|
8 |
+
/**
|
9 |
+
* The runtime instantiating this block package.
|
10 |
+
* @type {Runtime}
|
11 |
+
*/
|
12 |
+
this.runtime = runtime;
|
13 |
+
}
|
14 |
+
|
15 |
+
/**
|
16 |
+
* Retrieve the block primitives implemented by this package.
|
17 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
18 |
+
*/
|
19 |
+
//
|
20 |
+
getPrimitives () {
|
21 |
+
return {
|
22 |
+
operator_add: this.add,
|
23 |
+
operator_subtract: this.subtract,
|
24 |
+
operator_multiply: this.multiply,
|
25 |
+
operator_divide: this.divide,
|
26 |
+
operator_power: this.power,
|
27 |
+
operator_lt: this.lt,
|
28 |
+
operator_equals: this.equals,
|
29 |
+
operator_notequal: this.notequals,
|
30 |
+
operator_gt: this.gt,
|
31 |
+
operator_ltorequal: this.ltorequal,
|
32 |
+
operator_gtorequal: this.gtorequal,
|
33 |
+
operator_and: this.and,
|
34 |
+
operator_nand: this.nand,
|
35 |
+
operator_nor: this.nor,
|
36 |
+
operator_xor: this.xor,
|
37 |
+
operator_xnor: this.xnor,
|
38 |
+
operator_or: this.or,
|
39 |
+
operator_not: this.not,
|
40 |
+
operator_random: this.random,
|
41 |
+
operator_join: this.join,
|
42 |
+
operator_join3: this.join3,
|
43 |
+
operator_letter_of: this.letterOf,
|
44 |
+
operator_length: this.length,
|
45 |
+
operator_contains: this.contains,
|
46 |
+
operator_mod: this.mod,
|
47 |
+
operator_round: this.round,
|
48 |
+
operator_mathop: this.mathop,
|
49 |
+
operator_advlog: this.advlog,
|
50 |
+
operator_regexmatch: this.regexmatch,
|
51 |
+
operator_replaceAll: this.replaceAll,
|
52 |
+
operator_replaceFirst: this.replaceFirst,
|
53 |
+
operator_getLettersFromIndexToIndexInText: this.getLettersFromIndexToIndexInText,
|
54 |
+
operator_getLettersFromIndexToIndexInTextFixed: this.getLettersFromIndexToIndexInTextFixed,
|
55 |
+
operator_readLineInMultilineText: this.readLineInMultilineText,
|
56 |
+
operator_newLine: this.newLine,
|
57 |
+
operator_tabCharacter: this.tabCharacter,
|
58 |
+
operator_stringify: this.stringify,
|
59 |
+
operator_boolify: this.boolify,
|
60 |
+
operator_lerpFunc: this.lerpFunc,
|
61 |
+
operator_advMath: this.advMath,
|
62 |
+
operator_advMathExpanded: this.advMathExpanded,
|
63 |
+
operator_constrainnumber: this.constrainnumber,
|
64 |
+
operator_trueBoolean: this.true,
|
65 |
+
operator_falseBoolean: this.false,
|
66 |
+
operator_randomBoolean: this.randomBoolean,
|
67 |
+
operator_indexOfTextInText: this.indexOfTextInText,
|
68 |
+
operator_lastIndexOfTextInText: this.lastIndexOfTextInText,
|
69 |
+
operator_toUpperLowerCase: this.toCase,
|
70 |
+
operator_character_to_code: this.charToCode,
|
71 |
+
operator_code_to_character: this.codeToChar,
|
72 |
+
operator_textStartsOrEndsWith: this.textStartsOrEndsWith,
|
73 |
+
operator_countAppearTimes: this.countAppearTimes,
|
74 |
+
operator_textIncludesLetterFrom: this.textIncludesLetterFrom,
|
75 |
+
operator_javascript_output: this.javascriptOutput,
|
76 |
+
operator_javascript_boolean: this.javascriptBoolean
|
77 |
+
};
|
78 |
+
}
|
79 |
+
|
80 |
+
|
81 |
+
javascriptOutput (args) {
|
82 |
+
return new Promise((resolve, reject) => {
|
83 |
+
const js = Cast.toString(args.JS);
|
84 |
+
SandboxRunner.execute(js).then(result => {
|
85 |
+
resolve(result.value)
|
86 |
+
})
|
87 |
+
})
|
88 |
+
}
|
89 |
+
javascriptBoolean(args) {
|
90 |
+
return new Promise((resolve, reject) => {
|
91 |
+
const js = Cast.toString(args.JS);
|
92 |
+
SandboxRunner.execute(js).then(result => {
|
93 |
+
resolve(result.value === true)
|
94 |
+
})
|
95 |
+
})
|
96 |
+
}
|
97 |
+
|
98 |
+
charToCode (args) {
|
99 |
+
const char = Cast.toString(args.ONE);
|
100 |
+
if (!char) return NaN;
|
101 |
+
return char.charCodeAt(0);
|
102 |
+
}
|
103 |
+
codeToChar (args) {
|
104 |
+
const code = Cast.toNumber(args.ONE);
|
105 |
+
return String.fromCharCode(code);
|
106 |
+
}
|
107 |
+
|
108 |
+
toCase (args) {
|
109 |
+
const text = Cast.toString(args.TEXT);
|
110 |
+
switch (args.OPTION) {
|
111 |
+
case 'upper':
|
112 |
+
return text.toUpperCase();
|
113 |
+
case 'lower':
|
114 |
+
return text.toLowerCase();
|
115 |
+
}
|
116 |
+
}
|
117 |
+
|
118 |
+
indexOfTextInText (args) {
|
119 |
+
const lookfor = Cast.toString(args.TEXT1);
|
120 |
+
const searchin = Cast.toString(args.TEXT2);
|
121 |
+
let index = 0;
|
122 |
+
if (searchin.includes(lookfor)) {
|
123 |
+
index = searchin.indexOf(lookfor) + 1;
|
124 |
+
}
|
125 |
+
return index;
|
126 |
+
}
|
127 |
+
|
128 |
+
lastIndexOfTextInText (args) {
|
129 |
+
const lookfor = Cast.toString(args.TEXT1);
|
130 |
+
const searchin = Cast.toString(args.TEXT2);
|
131 |
+
let index = 0;
|
132 |
+
if (searchin.includes(lookfor)) {
|
133 |
+
index = searchin.lastIndexOf(lookfor) + 1;
|
134 |
+
}
|
135 |
+
return index;
|
136 |
+
}
|
137 |
+
|
138 |
+
textStartsOrEndsWith (args) {
|
139 |
+
const text = Cast.toString(args.TEXT1);
|
140 |
+
const startsOrEnds = Cast.toString(args.OPTION);
|
141 |
+
const withh = Cast.toString(args.TEXT2);
|
142 |
+
return (startsOrEnds === "starts") ? (text.startsWith(withh)) : (text.endsWith(withh));
|
143 |
+
}
|
144 |
+
|
145 |
+
countAppearTimes (args) {
|
146 |
+
const text = Cast.toString(args.TEXT2);
|
147 |
+
const otherText = Cast.toString(args.TEXT1);
|
148 |
+
|
149 |
+
const aray = text.split(otherText);
|
150 |
+
if (aray.length <= 1) {
|
151 |
+
return 0;
|
152 |
+
}
|
153 |
+
|
154 |
+
return aray.length - 1;
|
155 |
+
}
|
156 |
+
|
157 |
+
textIncludesLetterFrom (args) {
|
158 |
+
const text = Cast.toString(args.TEXT1);
|
159 |
+
const from = Cast.toString(args.TEXT2);
|
160 |
+
|
161 |
+
let includes = false;
|
162 |
+
|
163 |
+
const aray = from.split("");
|
164 |
+
aray.forEach(i => {
|
165 |
+
if (text.includes(i)) includes = true;
|
166 |
+
})
|
167 |
+
|
168 |
+
return includes;
|
169 |
+
}
|
170 |
+
|
171 |
+
true () { return true; }
|
172 |
+
false () { return false; }
|
173 |
+
randomBoolean () { return Boolean(Math.round(Math.random())); }
|
174 |
+
|
175 |
+
constrainnumber (args) {
|
176 |
+
return Math.min(Math.max(args.min, args.inp), args.max);
|
177 |
+
}
|
178 |
+
|
179 |
+
lerpFunc (args) {
|
180 |
+
const one = Cast.toNumber(args.ONE);
|
181 |
+
const two = Cast.toNumber(args.TWO);
|
182 |
+
const amount = Cast.toNumber(args.AMOUNT);
|
183 |
+
return ((two - one) * amount) + one;
|
184 |
+
}
|
185 |
+
advMath (args) {
|
186 |
+
const one = isNaN(Cast.toNumber(args.ONE)) ? 0 : Cast.toNumber(args.ONE);
|
187 |
+
const two = isNaN(Cast.toNumber(args.TWO)) ? 0 : Cast.toNumber(args.TWO);
|
188 |
+
const operator = Cast.toString(args.OPTION);
|
189 |
+
switch (operator) {
|
190 |
+
case "^": return one ** two;
|
191 |
+
case "root": return one ** 1 / two;
|
192 |
+
case "log": return Math.log(two) / Math.log(one);
|
193 |
+
default: return 0;
|
194 |
+
}
|
195 |
+
}
|
196 |
+
advMathExpanded (args) {
|
197 |
+
const one = Cast.toNumber(args.ONE);
|
198 |
+
const two = Cast.toNumber(args.TWO);
|
199 |
+
const three = Cast.toNumber(args.THREE);
|
200 |
+
const operator = Cast.toString(args.OPTION);
|
201 |
+
switch (operator) {
|
202 |
+
case "root": return one * Math.pow(three, 1 / two);
|
203 |
+
case "log": return one * Math.log(three) / Math.log(two);
|
204 |
+
default: return 0;
|
205 |
+
}
|
206 |
+
}
|
207 |
+
|
208 |
+
stringify (args) { return Cast.toString(args.ONE); }
|
209 |
+
|
210 |
+
boolify (args) { return Cast.toBoolean(args.ONE); }
|
211 |
+
|
212 |
+
newLine () { return "\n"; }
|
213 |
+
|
214 |
+
tabCharacter () { return "\t"; }
|
215 |
+
|
216 |
+
readLineInMultilineText (args) {
|
217 |
+
const line = (Cast.toNumber(args.LINE) ? Cast.toNumber(args.LINE) : 1) - 1;
|
218 |
+
const text = Cast.toString(args.TEXT);
|
219 |
+
const readline = text.split("\n")[line] || "";
|
220 |
+
return readline;
|
221 |
+
}
|
222 |
+
|
223 |
+
getLettersFromIndexToIndexInTextFixed (args) {
|
224 |
+
const index1 = (Cast.toNumber(args.INDEX1) ? Cast.toNumber(args.INDEX1) : 1) - 1;
|
225 |
+
const index2 = (Cast.toNumber(args.INDEX2) ? Cast.toNumber(args.INDEX2) : 1);
|
226 |
+
const string = Cast.toString(args.TEXT);
|
227 |
+
const substring = string.substring(index1, index2);
|
228 |
+
return substring;
|
229 |
+
}
|
230 |
+
getLettersFromIndexToIndexInText (args) {
|
231 |
+
const index1 = (Cast.toNumber(args.INDEX1) ? Cast.toNumber(args.INDEX1) : 1) - 1;
|
232 |
+
const index2 = (Cast.toNumber(args.INDEX2) ? Cast.toNumber(args.INDEX2) : 1) - 1;
|
233 |
+
const string = Cast.toString(args.TEXT);
|
234 |
+
const substring = string.substring(index1, index2);
|
235 |
+
return substring;
|
236 |
+
}
|
237 |
+
|
238 |
+
replaceAll (args) {
|
239 |
+
return Cast.toString(args.text).replaceAll(args.term, args.res);
|
240 |
+
}
|
241 |
+
replaceFirst (args) {
|
242 |
+
return Cast.toString(args.text).replace(args.term, args.res);
|
243 |
+
}
|
244 |
+
|
245 |
+
regexmatch (args) {
|
246 |
+
if (!validateRegex(args.reg, args.regrule)) return "[]";
|
247 |
+
const regex = new RegExp(args.reg, args.regrule);
|
248 |
+
const matches = args.text.match(regex);
|
249 |
+
return JSON.stringify(matches ? matches : []);
|
250 |
+
}
|
251 |
+
|
252 |
+
add (args) {
|
253 |
+
return Cast.toNumber(args.NUM1) + Cast.toNumber(args.NUM2);
|
254 |
+
}
|
255 |
+
|
256 |
+
subtract (args) {
|
257 |
+
return Cast.toNumber(args.NUM1) - Cast.toNumber(args.NUM2);
|
258 |
+
}
|
259 |
+
|
260 |
+
multiply (args) {
|
261 |
+
return Cast.toNumber(args.NUM1) * Cast.toNumber(args.NUM2);
|
262 |
+
}
|
263 |
+
|
264 |
+
divide (args) {
|
265 |
+
return Cast.toNumber(args.NUM1) / Cast.toNumber(args.NUM2);
|
266 |
+
}
|
267 |
+
|
268 |
+
power (args) {
|
269 |
+
return Math.pow(Cast.toNumber(args.NUM1), Cast.toNumber(args.NUM2));
|
270 |
+
}
|
271 |
+
|
272 |
+
lt (args) {
|
273 |
+
return Cast.compare(args.OPERAND1, args.OPERAND2) < 0;
|
274 |
+
}
|
275 |
+
|
276 |
+
equals (args) {
|
277 |
+
return Cast.compare(args.OPERAND1, args.OPERAND2) === 0;
|
278 |
+
}
|
279 |
+
|
280 |
+
notequals (args) {
|
281 |
+
return !this.equals(args);
|
282 |
+
}
|
283 |
+
|
284 |
+
gt (args) {
|
285 |
+
return Cast.compare(args.OPERAND1, args.OPERAND2) > 0;
|
286 |
+
}
|
287 |
+
|
288 |
+
gtorequal (args) {
|
289 |
+
return !this.lt(args);
|
290 |
+
}
|
291 |
+
|
292 |
+
ltorequal (args) {
|
293 |
+
return !this.gt(args);
|
294 |
+
}
|
295 |
+
|
296 |
+
and (args) {
|
297 |
+
return Cast.toBoolean(args.OPERAND1) && Cast.toBoolean(args.OPERAND2);
|
298 |
+
}
|
299 |
+
|
300 |
+
nand (args) {
|
301 |
+
return !(Cast.toBoolean(args.OPERAND1) && Cast.toBoolean(args.OPERAND2));
|
302 |
+
}
|
303 |
+
|
304 |
+
nor (args) {
|
305 |
+
return !(Cast.toBoolean(args.OPERAND1) || Cast.toBoolean(args.OPERAND2));
|
306 |
+
}
|
307 |
+
|
308 |
+
xor (args) {
|
309 |
+
const op1 = Cast.toBoolean(args.OPERAND1);
|
310 |
+
const op2 = Cast.toBoolean(args.OPERAND2);
|
311 |
+
return (op1 ? !op2 : op2);
|
312 |
+
}
|
313 |
+
|
314 |
+
xnor (args) {
|
315 |
+
return !this.xor(args);
|
316 |
+
}
|
317 |
+
|
318 |
+
or (args) {
|
319 |
+
return Cast.toBoolean(args.OPERAND1) || Cast.toBoolean(args.OPERAND2);
|
320 |
+
}
|
321 |
+
|
322 |
+
not (args) {
|
323 |
+
return !Cast.toBoolean(args.OPERAND);
|
324 |
+
}
|
325 |
+
|
326 |
+
random (args) {
|
327 |
+
return this._random(args.FROM, args.TO);
|
328 |
+
}
|
329 |
+
_random (from, to) { // used by compiler
|
330 |
+
const nFrom = Cast.toNumber(from);
|
331 |
+
const nTo = Cast.toNumber(to);
|
332 |
+
const low = nFrom <= nTo ? nFrom : nTo;
|
333 |
+
const high = nFrom <= nTo ? nTo : nFrom;
|
334 |
+
if (low === high) return low;
|
335 |
+
// If both arguments are ints, truncate the result to an int.
|
336 |
+
if (Cast.isInt(from) && Cast.isInt(to)) {
|
337 |
+
return low + Math.floor(Math.random() * ((high + 1) - low));
|
338 |
+
}
|
339 |
+
return (Math.random() * (high - low)) + low;
|
340 |
+
}
|
341 |
+
|
342 |
+
join (args) {
|
343 |
+
return Cast.toString(args.STRING1) + Cast.toString(args.STRING2);
|
344 |
+
}
|
345 |
+
|
346 |
+
join3 (args) {
|
347 |
+
return Cast.toString(args.STRING1) + Cast.toString(args.STRING2) + Cast.toString(args.STRING3);
|
348 |
+
}
|
349 |
+
|
350 |
+
letterOf (args) {
|
351 |
+
const index = Cast.toNumber(args.LETTER) - 1;
|
352 |
+
const str = Cast.toString(args.STRING);
|
353 |
+
// Out of bounds?
|
354 |
+
if (index < 0 || index >= str.length) {
|
355 |
+
return '';
|
356 |
+
}
|
357 |
+
return str.charAt(index);
|
358 |
+
}
|
359 |
+
|
360 |
+
length (args) {
|
361 |
+
return Cast.toString(args.STRING).length;
|
362 |
+
}
|
363 |
+
|
364 |
+
contains (args) {
|
365 |
+
const format = function (string) {
|
366 |
+
return Cast.toString(string).toLowerCase();
|
367 |
+
};
|
368 |
+
return format(args.STRING1).includes(format(args.STRING2));
|
369 |
+
}
|
370 |
+
|
371 |
+
mod (args) {
|
372 |
+
const n = Cast.toNumber(args.NUM1);
|
373 |
+
const modulus = Cast.toNumber(args.NUM2);
|
374 |
+
let result = n % modulus;
|
375 |
+
// Scratch mod uses floored division instead of truncated division.
|
376 |
+
if (result / modulus < 0) result += modulus;
|
377 |
+
return result;
|
378 |
+
}
|
379 |
+
|
380 |
+
round (args) {
|
381 |
+
return Math.round(Cast.toNumber(args.NUM));
|
382 |
+
}
|
383 |
+
|
384 |
+
mathop (args) {
|
385 |
+
const operator = Cast.toString(args.OPERATOR).toLowerCase();
|
386 |
+
const n = Cast.toNumber(args.NUM);
|
387 |
+
switch (operator) {
|
388 |
+
case 'abs': return Math.abs(n);
|
389 |
+
case 'floor': return Math.floor(n);
|
390 |
+
case 'ceiling': return Math.ceil(n);
|
391 |
+
case 'sqrt': return Math.sqrt(n);
|
392 |
+
case 'sin': return Math.round(Math.sin((Math.PI * n) / 180) * 1e10) / 1e10;
|
393 |
+
case 'cos': return Math.round(Math.cos((Math.PI * n) / 180) * 1e10) / 1e10;
|
394 |
+
case 'tan': return MathUtil.tan(n);
|
395 |
+
case 'asin': return (Math.asin(n) * 180) / Math.PI;
|
396 |
+
case 'acos': return (Math.acos(n) * 180) / Math.PI;
|
397 |
+
case 'atan': return (Math.atan(n) * 180) / Math.PI;
|
398 |
+
case 'ln': return Math.log(n);
|
399 |
+
case 'log': return Math.log(n) / Math.LN10;
|
400 |
+
case 'log2': return Math.log2(n);
|
401 |
+
case 'e ^': return Math.exp(n);
|
402 |
+
case '10 ^': return Math.pow(10, n);
|
403 |
+
}
|
404 |
+
return 0;
|
405 |
+
}
|
406 |
+
|
407 |
+
advlog (args) {
|
408 |
+
return (Math.log(Cast.toNumber(args.NUM2)) / Math.log(Cast.toNumber(args.NUM1)));
|
409 |
+
}
|
410 |
+
}
|
411 |
+
|
412 |
+
module.exports = Scratch3OperatorsBlocks;
|
src/blocks/scratch3_procedures.js
ADDED
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
class Scratch3ProcedureBlocks {
|
3 |
+
constructor(runtime) {
|
4 |
+
/**
|
5 |
+
* The runtime instantiating this block package.
|
6 |
+
* @type {Runtime}
|
7 |
+
*/
|
8 |
+
this.runtime = runtime;
|
9 |
+
}
|
10 |
+
|
11 |
+
/**
|
12 |
+
* Retrieve the block primitives implemented by this package.
|
13 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
14 |
+
*/
|
15 |
+
getPrimitives() {
|
16 |
+
return {
|
17 |
+
procedures_definition: this.definition,
|
18 |
+
procedures_call: this.call,
|
19 |
+
procedures_set: this.set,
|
20 |
+
argument_reporter_string_number: this.argumentReporterStringNumber,
|
21 |
+
argument_reporter_boolean: this.argumentReporterBoolean,
|
22 |
+
argument_reporter_command: this.argumentReporterCommand
|
23 |
+
};
|
24 |
+
}
|
25 |
+
|
26 |
+
definition() {
|
27 |
+
// No-op: execute the blocks.
|
28 |
+
}
|
29 |
+
|
30 |
+
call (args, util) {
|
31 |
+
if (!util.stackFrame.executed) {
|
32 |
+
const procedureCode = args.mutation.proccode;
|
33 |
+
const paramNamesIdsAndDefaults = util.getProcedureParamNamesIdsAndDefaults(procedureCode);
|
34 |
+
|
35 |
+
// If null, procedure could not be found, which can happen if custom
|
36 |
+
// block is dragged between sprites without the definition.
|
37 |
+
// Match Scratch 2.0 behavior and noop.
|
38 |
+
if (paramNamesIdsAndDefaults === null) {
|
39 |
+
return;
|
40 |
+
}
|
41 |
+
|
42 |
+
const [paramNames, paramIds, paramDefaults] = paramNamesIdsAndDefaults;
|
43 |
+
|
44 |
+
// Initialize params for the current stackFrame to {}, even if the procedure does
|
45 |
+
// not take any arguments. This is so that `getParam` down the line does not look
|
46 |
+
// at earlier stack frames for the values of a given parameter (#1729)
|
47 |
+
util.initParams();
|
48 |
+
for (let i = 0; i < paramIds.length; i++) {
|
49 |
+
if (args.hasOwnProperty(paramIds[i])) {
|
50 |
+
util.pushParam(paramNames[i], args[paramIds[i]]);
|
51 |
+
} else {
|
52 |
+
util.pushParam(paramNames[i], paramDefaults[i]);
|
53 |
+
}
|
54 |
+
}
|
55 |
+
|
56 |
+
const addonBlock = util.runtime.getAddonBlock(procedureCode);
|
57 |
+
if (addonBlock) {
|
58 |
+
const result = addonBlock.callback(util.thread.getAllparams(), util);
|
59 |
+
if (util.thread.status === 1 /* STATUS_PROMISE_WAIT */) {
|
60 |
+
// If the addon block is using STATUS_PROMISE_WAIT to force us to sleep,
|
61 |
+
// make sure to not re-run this block when we resume.
|
62 |
+
util.stackFrame.executed = true;
|
63 |
+
}
|
64 |
+
return result;
|
65 |
+
}
|
66 |
+
|
67 |
+
util.stackFrame.executed = true;
|
68 |
+
|
69 |
+
util.startProcedure(procedureCode);
|
70 |
+
}
|
71 |
+
}
|
72 |
+
|
73 |
+
set(args, util) {
|
74 |
+
const contain = util.thread.blockContainer;
|
75 |
+
const block = contain.getBlock(util.thread.isCompiled ? util.thread.peekStack() : util.thread.peekStackFrame().op.id);
|
76 |
+
if (!block) return;
|
77 |
+
const thread = util.thread;
|
78 |
+
const param = contain.getBlock(block.inputs.PARAM?.block);
|
79 |
+
if (param) {
|
80 |
+
try {
|
81 |
+
const curParams = thread.stackFrames[0].params;
|
82 |
+
if (curParams !== null) thread.stackFrames[0].params[param.fields.VALUE.value] = args.VALUE;
|
83 |
+
else thread.stackFrames[0].params = { [param.fields.VALUE.value]: args.VALUE }
|
84 |
+
} catch { /* shouldn't happen */ }
|
85 |
+
}
|
86 |
+
}
|
87 |
+
|
88 |
+
argumentReporterStringNumber(args, util) {
|
89 |
+
const value = util.getParam(args.VALUE);
|
90 |
+
if (value === null) {
|
91 |
+
// When the parameter is not found in the most recent procedure
|
92 |
+
// call, the default is always 0.
|
93 |
+
return 0;
|
94 |
+
}
|
95 |
+
return value;
|
96 |
+
}
|
97 |
+
|
98 |
+
argumentReporterBoolean(args, util) {
|
99 |
+
const value = util.getParam(args.VALUE);
|
100 |
+
if (value === null) {
|
101 |
+
// When the parameter is not found in the most recent procedure
|
102 |
+
// call, the default is always 0.
|
103 |
+
return 0;
|
104 |
+
}
|
105 |
+
return value;
|
106 |
+
}
|
107 |
+
|
108 |
+
argumentReporterCommand(args, util) {
|
109 |
+
const branchInfo = util.getParam(args.VALUE) || {};
|
110 |
+
if (branchInfo.entry === null) return;
|
111 |
+
const [branchId, target] = util.getBranchAndTarget(
|
112 |
+
branchInfo.callerId,
|
113 |
+
branchInfo.entry
|
114 |
+
) || [];
|
115 |
+
if (branchId) {
|
116 |
+
// Push branch ID to the thread's stack.
|
117 |
+
util.thread.pushStack(branchId, target);
|
118 |
+
} else {
|
119 |
+
util.thread.pushStack(null);
|
120 |
+
}
|
121 |
+
}
|
122 |
+
}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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const Timer = require('../util/timer');
|
3 |
+
const MathUtil = require('../util/math-util');
|
4 |
+
const getMonitorIdForBlockWithArgs = require('../util/get-monitor-id');
|
5 |
+
const { validateRegex } = require('../util/json-block-utilities');
|
6 |
+
|
7 |
+
class Scratch3SensingBlocks {
|
8 |
+
constructor (runtime) {
|
9 |
+
/**
|
10 |
+
* The runtime instantiating this block package.
|
11 |
+
* @type {Runtime}
|
12 |
+
*/
|
13 |
+
this.runtime = runtime;
|
14 |
+
|
15 |
+
/**
|
16 |
+
* The "answer" block value.
|
17 |
+
* @type {string}
|
18 |
+
*/
|
19 |
+
this._answer = ''; // used by compiler
|
20 |
+
|
21 |
+
/**
|
22 |
+
* The timer utility.
|
23 |
+
* @type {Timer}
|
24 |
+
*/
|
25 |
+
this._timer = new Timer();
|
26 |
+
|
27 |
+
/**
|
28 |
+
* The stored microphone loudness measurement.
|
29 |
+
* @type {number}
|
30 |
+
*/
|
31 |
+
this._cachedLoudness = -1;
|
32 |
+
|
33 |
+
/**
|
34 |
+
* The time of the most recent microphone loudness measurement.
|
35 |
+
* @type {number}
|
36 |
+
*/
|
37 |
+
this._cachedLoudnessTimestamp = 0;
|
38 |
+
|
39 |
+
/**
|
40 |
+
* The list of loudness values to determine the average.
|
41 |
+
* @type {!Array}
|
42 |
+
*/
|
43 |
+
this._loudnessList = [];
|
44 |
+
|
45 |
+
/**
|
46 |
+
* The list of queued questions and respective `resolve` callbacks.
|
47 |
+
* @type {!Array}
|
48 |
+
*/
|
49 |
+
this._questionList = [];
|
50 |
+
|
51 |
+
this.runtime.on('ANSWER', this._onAnswer.bind(this));
|
52 |
+
this.runtime.on('PROJECT_START', this._resetAnswer.bind(this));
|
53 |
+
this.runtime.on('PROJECT_STOP_ALL', this._clearAllQuestions.bind(this));
|
54 |
+
this.runtime.on('STOP_FOR_TARGET', this._clearTargetQuestions.bind(this));
|
55 |
+
this.runtime.on('RUNTIME_DISPOSED', this._resetAnswer.bind(this));
|
56 |
+
}
|
57 |
+
|
58 |
+
/**
|
59 |
+
* Retrieve the block primitives implemented by this package.
|
60 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
61 |
+
*/
|
62 |
+
getPrimitives () {
|
63 |
+
return {
|
64 |
+
sensing_objecttouchingobject: this.objectTouchingObject,
|
65 |
+
sensing_objecttouchingclonesprite: this.objectTouchingCloneOfSprite,
|
66 |
+
sensing_touchingobject: this.touchingObject,
|
67 |
+
sensing_touchingcolor: this.touchingColor,
|
68 |
+
sensing_coloristouchingcolor: this.colorTouchingColor,
|
69 |
+
sensing_distanceto: this.distanceTo,
|
70 |
+
sensing_timer: this.getTimer,
|
71 |
+
sensing_resettimer: this.resetTimer,
|
72 |
+
sensing_of: this.getAttributeOf,
|
73 |
+
sensing_mousex: this.getMouseX,
|
74 |
+
sensing_mousey: this.getMouseY,
|
75 |
+
sensing_setdragmode: this.setDragMode,
|
76 |
+
sensing_mousedown: this.getMouseDown,
|
77 |
+
sensing_keypressed: this.getKeyPressed,
|
78 |
+
sensing_current: this.current,
|
79 |
+
sensing_dayssince2000: this.daysSince2000,
|
80 |
+
sensing_loudness: this.getLoudness,
|
81 |
+
sensing_loud: this.isLoud,
|
82 |
+
sensing_askandwait: this.askAndWait,
|
83 |
+
sensing_answer: this.getAnswer,
|
84 |
+
sensing_username: this.getUsername,
|
85 |
+
sensing_loggedin: this.getLoggedIn,
|
86 |
+
sensing_userid: () => {}, // legacy no-op block
|
87 |
+
sensing_regextest: this.regextest,
|
88 |
+
sensing_thing_is_number: this.thing_is_number,
|
89 |
+
sensing_thing_has_number: this.thing_has_number,
|
90 |
+
sensing_mobile: this.mobile,
|
91 |
+
sensing_thing_is_text: this.thing_is_text,
|
92 |
+
sensing_getspritewithattrib: this.getspritewithattrib,
|
93 |
+
sensing_directionTo: this.getDirectionToFrom,
|
94 |
+
sensing_distanceTo: this.getDistanceToFrom,
|
95 |
+
sensing_isUpperCase: this.isCharecterUppercase,
|
96 |
+
sensing_mouseclicked: this.mouseClicked,
|
97 |
+
sensing_keyhit: this.keyHit,
|
98 |
+
sensing_mousescrolling: this.mouseScrolling,
|
99 |
+
sensing_fingerdown: this.fingerDown,
|
100 |
+
sensing_fingertapped: this.fingerTapped,
|
101 |
+
sensing_fingerx: this.getFingerX,
|
102 |
+
sensing_fingery: this.getFingerY,
|
103 |
+
sensing_setclipboard: this.setClipboard,
|
104 |
+
sensing_getclipboard: this.getClipboard,
|
105 |
+
sensing_getdragmode: this.getDragMode,
|
106 |
+
sensing_getoperatingsystem: this.getOS,
|
107 |
+
sensing_getbrowser: this.getBrowser,
|
108 |
+
sensing_geturl: this.getUrl,
|
109 |
+
sensing_getxyoftouchingsprite: this.getXYOfTouchingSprite
|
110 |
+
};
|
111 |
+
}
|
112 |
+
|
113 |
+
getOS () {
|
114 |
+
if (!('userAgent' in navigator)) return 'Unknown';
|
115 |
+
const agent = navigator.userAgent;
|
116 |
+
if (agent.includes('Windows')) {
|
117 |
+
return 'Windows';
|
118 |
+
}
|
119 |
+
if (agent.includes('Android')) {
|
120 |
+
return 'Android';
|
121 |
+
}
|
122 |
+
if (agent.includes('iPad') || agent.includes('iPod') || agent.includes('iPhone')) {
|
123 |
+
return 'iOS';
|
124 |
+
}
|
125 |
+
if (agent.includes('Linux')) {
|
126 |
+
return 'Linux';
|
127 |
+
}
|
128 |
+
if (agent.includes('CrOS')) {
|
129 |
+
return 'ChromeOS';
|
130 |
+
}
|
131 |
+
if (agent.includes('Mac OS')) {
|
132 |
+
return 'MacOS';
|
133 |
+
}
|
134 |
+
return 'Unknown';
|
135 |
+
}
|
136 |
+
getBrowser () {
|
137 |
+
if (!('userAgent' in navigator)) return 'Unknown';
|
138 |
+
const agent = navigator.userAgent;
|
139 |
+
if ('userAgentData' in navigator) {
|
140 |
+
const agentData = JSON.stringify(navigator.userAgentData.brands);
|
141 |
+
if (agentData.includes('Google Chrome')) {
|
142 |
+
return 'Chrome';
|
143 |
+
}
|
144 |
+
if (agentData.includes('Opera')) {
|
145 |
+
return 'Opera';
|
146 |
+
}
|
147 |
+
if (agentData.includes('Microsoft Edge')) {
|
148 |
+
return 'Edge';
|
149 |
+
}
|
150 |
+
}
|
151 |
+
if (agent.includes('Chrome')) {
|
152 |
+
return 'Chrome';
|
153 |
+
}
|
154 |
+
if (agent.includes('Firefox')) {
|
155 |
+
return 'Firefox';
|
156 |
+
}
|
157 |
+
// PenguinMod cannot be loaded in IE 11 (the last supported version)
|
158 |
+
// if (agent.includes('MSIE') || agent.includes('rv:')) {
|
159 |
+
// return 'Internet Explorer';
|
160 |
+
// }
|
161 |
+
if (agent.includes('Safari')) {
|
162 |
+
return 'Safari';
|
163 |
+
}
|
164 |
+
return 'Unknown';
|
165 |
+
}
|
166 |
+
getUrl () {
|
167 |
+
if (!('href' in location)) return '';
|
168 |
+
return location.href;
|
169 |
+
}
|
170 |
+
|
171 |
+
setClipboard (args) {
|
172 |
+
const text = Cast.toString(args.ITEM);
|
173 |
+
if (!navigator) return;
|
174 |
+
if (('clipboard' in navigator) && ('writeText' in navigator.clipboard)) {
|
175 |
+
navigator.clipboard.writeText(text);
|
176 |
+
}
|
177 |
+
}
|
178 |
+
getClipboard () {
|
179 |
+
if (!navigator) return '';
|
180 |
+
if (('clipboard' in navigator) && ('readText' in navigator.clipboard)) {
|
181 |
+
return navigator.clipboard.readText();
|
182 |
+
} else {
|
183 |
+
return '';
|
184 |
+
}
|
185 |
+
}
|
186 |
+
|
187 |
+
getDragMode (_, util) {
|
188 |
+
return util.target.draggable;
|
189 |
+
}
|
190 |
+
|
191 |
+
mouseClicked (_, util) {
|
192 |
+
return util.ioQuery('mouse', 'getIsClicked');
|
193 |
+
}
|
194 |
+
keyHit (args, util) {
|
195 |
+
return util.ioQuery('keyboard', 'getKeyIsHit', [args.KEY_OPTION]);
|
196 |
+
}
|
197 |
+
mouseScrolling (args, util) {
|
198 |
+
const delta = util.ioQuery('mouseWheel', 'getScrollDelta');
|
199 |
+
const option = args.SCROLL_OPTION;
|
200 |
+
switch (option) {
|
201 |
+
case "up":
|
202 |
+
return delta < 0;
|
203 |
+
case "down":
|
204 |
+
return delta > 0;
|
205 |
+
default:
|
206 |
+
return false;
|
207 |
+
}
|
208 |
+
}
|
209 |
+
|
210 |
+
isCharecterUppercase (args) {
|
211 |
+
return (/[A-Z]/g).test(args.text);
|
212 |
+
}
|
213 |
+
|
214 |
+
getDirectionToFrom (args) {
|
215 |
+
const dx = args.x2 - args.x1;
|
216 |
+
const dy = args.y2 - args.y1;
|
217 |
+
const direction = MathUtil.wrapClamp(90 - MathUtil.radToDeg(Math.atan2(dy, dx)), -179, 180);
|
218 |
+
return direction;
|
219 |
+
}
|
220 |
+
|
221 |
+
getDistanceToFrom (args) {
|
222 |
+
const dx = args.x2 - args.x1;
|
223 |
+
const dy = args.y2 - args.y1;
|
224 |
+
return Math.sqrt((dx * dx) + (dy * dy));
|
225 |
+
}
|
226 |
+
|
227 |
+
getspritewithattrib (args, util) {
|
228 |
+
// strip out usless data
|
229 |
+
const sprites = util.runtime.targets.map(x => ({
|
230 |
+
id: x.id,
|
231 |
+
name: x.sprite ? x.sprite.name : "Unknown",
|
232 |
+
variables: Object.values(x.variables).reduce((obj, value) => {
|
233 |
+
if (!value.name) return obj;
|
234 |
+
obj[value.name] = String(value.value);
|
235 |
+
return obj;
|
236 |
+
}, {})
|
237 |
+
}));
|
238 |
+
// get the target with variable x set to y
|
239 |
+
let res = "No sprites found";
|
240 |
+
for (
|
241 |
+
// define the index and the sprite
|
242 |
+
let idx = 1, sprite = sprites[0];
|
243 |
+
// standard for loop thing
|
244 |
+
idx < sprites.length;
|
245 |
+
// set sprite to a new item
|
246 |
+
sprite = sprites[idx++]
|
247 |
+
) {
|
248 |
+
if (sprite.variables[args.var] === args.val) {
|
249 |
+
res = `{"id": "${sprite.id}", "name": "${sprite.name}"}`;
|
250 |
+
break;
|
251 |
+
}
|
252 |
+
}
|
253 |
+
|
254 |
+
return res;
|
255 |
+
}
|
256 |
+
thing_is_number (args) {
|
257 |
+
// i hate js
|
258 |
+
// i also hate regex
|
259 |
+
// so im gonna do this the lazy way
|
260 |
+
// no. String(Number(value)) === value does infact do the job X)
|
261 |
+
// also what was originaly here was inificiant as hell
|
262 |
+
|
263 |
+
// jg: why dont you literally just do what "is text" did but the opposite
|
264 |
+
// except also account for numbers that end with . (that aint a number)
|
265 |
+
if (Cast.toString(args.TEXT1).trim().endsWith(".")) {
|
266 |
+
return false;
|
267 |
+
}
|
268 |
+
return !this.thing_is_text(args);
|
269 |
+
}
|
270 |
+
thing_is_text (args) {
|
271 |
+
// WHY IS NAN NOT EQUAL TO ITSELF
|
272 |
+
// HOW IS NAN A NUMBER
|
273 |
+
// because nan is how numbers say the value put into me is not a number
|
274 |
+
return isNaN(Number(args.TEXT1));
|
275 |
+
}
|
276 |
+
|
277 |
+
thing_has_number(args) {
|
278 |
+
return /\d/.test(Cast.toString(args.TEXT1));
|
279 |
+
}
|
280 |
+
|
281 |
+
mobile () {
|
282 |
+
return typeof window !== 'undefined' && 'ontouchstart' in window;
|
283 |
+
}
|
284 |
+
|
285 |
+
regextest (args) {
|
286 |
+
if (!validateRegex(args.reg, args.regrule)) return false;
|
287 |
+
const regex = new RegExp(args.reg, args.regrule);
|
288 |
+
return regex.test(args.text);
|
289 |
+
}
|
290 |
+
|
291 |
+
getMonitored () {
|
292 |
+
return {
|
293 |
+
sensing_answer: {
|
294 |
+
getId: () => 'answer'
|
295 |
+
},
|
296 |
+
sensing_mousedown: {
|
297 |
+
getId: () => 'mousedown'
|
298 |
+
},
|
299 |
+
sensing_mouseclicked: {
|
300 |
+
getId: () => 'mouseclicked'
|
301 |
+
},
|
302 |
+
sensing_mousex: {
|
303 |
+
getId: () => 'mousex'
|
304 |
+
},
|
305 |
+
sensing_mousey: {
|
306 |
+
getId: () => 'mousey'
|
307 |
+
},
|
308 |
+
sensing_getclipboard: {
|
309 |
+
getId: () => 'getclipboard'
|
310 |
+
},
|
311 |
+
sensing_getdragmode: {
|
312 |
+
isSpriteSpecific: true,
|
313 |
+
getId: targetId => `${targetId}_getdragmode`
|
314 |
+
},
|
315 |
+
sensing_loudness: {
|
316 |
+
getId: () => 'loudness'
|
317 |
+
},
|
318 |
+
sensing_loud: {
|
319 |
+
getId: () => 'loud'
|
320 |
+
},
|
321 |
+
sensing_timer: {
|
322 |
+
getId: () => 'timer'
|
323 |
+
},
|
324 |
+
sensing_dayssince2000: {
|
325 |
+
getId: () => 'dayssince2000'
|
326 |
+
},
|
327 |
+
sensing_current: {
|
328 |
+
// This is different from the default toolbox xml id in order to support
|
329 |
+
// importing multiple monitors from the same opcode from sb2 files,
|
330 |
+
// something that is not currently supported in scratch 3.
|
331 |
+
getId: (_, fields) => getMonitorIdForBlockWithArgs('current', fields) // _${param}`
|
332 |
+
},
|
333 |
+
sensing_loggedin: {
|
334 |
+
getId: () => 'loggedin'
|
335 |
+
},
|
336 |
+
};
|
337 |
+
}
|
338 |
+
|
339 |
+
_onAnswer (answer) {
|
340 |
+
this._answer = answer;
|
341 |
+
const questionObj = this._questionList.shift();
|
342 |
+
if (questionObj) {
|
343 |
+
const [_question, resolve, target, wasVisible, wasStage] = questionObj;
|
344 |
+
// If the target was visible when asked, hide the say bubble unless the target was the stage.
|
345 |
+
if (wasVisible && !wasStage) {
|
346 |
+
this.runtime.emit('SAY', target, 'say', '');
|
347 |
+
}
|
348 |
+
resolve();
|
349 |
+
this._askNextQuestion();
|
350 |
+
}
|
351 |
+
}
|
352 |
+
|
353 |
+
_resetAnswer () {
|
354 |
+
this._answer = '';
|
355 |
+
}
|
356 |
+
|
357 |
+
_enqueueAsk (question, resolve, target, wasVisible, wasStage) {
|
358 |
+
this._questionList.push([question, resolve, target, wasVisible, wasStage]);
|
359 |
+
}
|
360 |
+
|
361 |
+
_askNextQuestion () {
|
362 |
+
if (this._questionList.length > 0) {
|
363 |
+
const [question, _resolve, target, wasVisible, wasStage] = this._questionList[0];
|
364 |
+
// If the target is visible, emit a blank question and use the
|
365 |
+
// say event to trigger a bubble unless the target was the stage.
|
366 |
+
if (wasVisible && !wasStage) {
|
367 |
+
this.runtime.emit('SAY', target, 'say', question);
|
368 |
+
this.runtime.emit('QUESTION', '');
|
369 |
+
} else {
|
370 |
+
this.runtime.emit('QUESTION', question);
|
371 |
+
}
|
372 |
+
}
|
373 |
+
}
|
374 |
+
|
375 |
+
_clearAllQuestions () {
|
376 |
+
this._questionList = [];
|
377 |
+
this.runtime.emit('QUESTION', null);
|
378 |
+
}
|
379 |
+
|
380 |
+
_clearTargetQuestions (stopTarget) {
|
381 |
+
const currentlyAsking = this._questionList.length > 0 && this._questionList[0][2] === stopTarget;
|
382 |
+
this._questionList = this._questionList.filter(question => (
|
383 |
+
question[2] !== stopTarget
|
384 |
+
));
|
385 |
+
|
386 |
+
if (currentlyAsking) {
|
387 |
+
this.runtime.emit('SAY', stopTarget, 'say', '');
|
388 |
+
if (this._questionList.length > 0) {
|
389 |
+
this._askNextQuestion();
|
390 |
+
} else {
|
391 |
+
this.runtime.emit('QUESTION', null);
|
392 |
+
}
|
393 |
+
}
|
394 |
+
}
|
395 |
+
|
396 |
+
askAndWait (args, util) {
|
397 |
+
const _target = util.target;
|
398 |
+
return new Promise(resolve => {
|
399 |
+
const isQuestionAsked = this._questionList.length > 0;
|
400 |
+
this._enqueueAsk(String(args.QUESTION), resolve, _target, _target.visible, _target.isStage);
|
401 |
+
if (!isQuestionAsked) {
|
402 |
+
this._askNextQuestion();
|
403 |
+
}
|
404 |
+
});
|
405 |
+
}
|
406 |
+
|
407 |
+
getAnswer () {
|
408 |
+
return this._answer;
|
409 |
+
}
|
410 |
+
|
411 |
+
objectTouchingObject (args, util) {
|
412 |
+
const object1 = (args.FULLTOUCHINGOBJECTMENU) === "_myself_" ? util.target.getName() : args.FULLTOUCHINGOBJECTMENU;
|
413 |
+
const object2 = args.SPRITETOUCHINGOBJECTMENU;
|
414 |
+
if (object2 === "_myself_") {
|
415 |
+
return util.target.isTouchingObject(object1);
|
416 |
+
}
|
417 |
+
const target = this.runtime.getSpriteTargetByName(object2);
|
418 |
+
if (!target) return false;
|
419 |
+
return target.isTouchingObject(object1);
|
420 |
+
}
|
421 |
+
objectTouchingCloneOfSprite (args, util) {
|
422 |
+
const object1 = args.FULLTOUCHINGOBJECTMENU;
|
423 |
+
let object2 = args.SPRITETOUCHINGOBJECTMENU;
|
424 |
+
if (object2 === "_myself_") {
|
425 |
+
object2 = util.target.getName();
|
426 |
+
}
|
427 |
+
if (object1 === "_myself_") {
|
428 |
+
return util.target.isTouchingObject(object2, true);
|
429 |
+
}
|
430 |
+
|
431 |
+
const target = this.runtime.getSpriteTargetByName(object2);
|
432 |
+
if (!target) return false;
|
433 |
+
if (object1 === "_mouse_") {
|
434 |
+
if (!this.runtime.ioDevices.mouse) return false;
|
435 |
+
const mouseX = this.runtime.ioDevices.mouse.getClientX();
|
436 |
+
const mouseY = this.runtime.ioDevices.mouse.getClientY();
|
437 |
+
const clones = target.sprite.clones.filter(clone => !clone.isOriginal && clone.isTouchingPoint(mouseX, mouseY));
|
438 |
+
return clones.length > 0;
|
439 |
+
} else if (object1 === '_edge_') {
|
440 |
+
const clones = target.sprite.clones.filter(clone => !clone.isOriginal && clone.isTouchingEdge());
|
441 |
+
return clones.length > 0;
|
442 |
+
}
|
443 |
+
|
444 |
+
const originalSprite = this.runtime.getSpriteTargetByName(object1);
|
445 |
+
if (!originalSprite) return false;
|
446 |
+
return originalSprite.isTouchingObject(object2, true);
|
447 |
+
}
|
448 |
+
|
449 |
+
touchingObject (args, util) {
|
450 |
+
return util.target.isTouchingObject(args.TOUCHINGOBJECTMENU);
|
451 |
+
}
|
452 |
+
|
453 |
+
getXYOfTouchingSprite (args, util) {
|
454 |
+
const object = args.SPRITE;
|
455 |
+
if (object === '_mouse_') {
|
456 |
+
// we can just return mouse pos
|
457 |
+
// if mouse is touching us, the mouse size is practically 1x1 anyways
|
458 |
+
const x = util.ioQuery('mouse', 'getScratchX');
|
459 |
+
const y = util.ioQuery('mouse', 'getScratchY');
|
460 |
+
if (args.XY === 'y') return y;
|
461 |
+
return x;
|
462 |
+
}
|
463 |
+
const point = util.target.spriteTouchingPoint(object);
|
464 |
+
if (!point) return '';
|
465 |
+
if (args.XY === 'y') return point[1];
|
466 |
+
return point[0];
|
467 |
+
}
|
468 |
+
|
469 |
+
touchingColor (args, util) {
|
470 |
+
const color = Cast.toRgbColorList(args.COLOR);
|
471 |
+
return util.target.isTouchingColor(color);
|
472 |
+
}
|
473 |
+
|
474 |
+
colorTouchingColor (args, util) {
|
475 |
+
const maskColor = Cast.toRgbColorList(args.COLOR);
|
476 |
+
const targetColor = Cast.toRgbColorList(args.COLOR2);
|
477 |
+
return util.target.colorIsTouchingColor(targetColor, maskColor);
|
478 |
+
}
|
479 |
+
|
480 |
+
distanceTo (args, util) {
|
481 |
+
if (util.target.isStage) return 10000;
|
482 |
+
|
483 |
+
let targetX = 0;
|
484 |
+
let targetY = 0;
|
485 |
+
if (args.DISTANCETOMENU === '_mouse_') {
|
486 |
+
targetX = util.ioQuery('mouse', 'getScratchX');
|
487 |
+
targetY = util.ioQuery('mouse', 'getScratchY');
|
488 |
+
} else {
|
489 |
+
args.DISTANCETOMENU = Cast.toString(args.DISTANCETOMENU);
|
490 |
+
const distTarget = this.runtime.getSpriteTargetByName(
|
491 |
+
args.DISTANCETOMENU
|
492 |
+
);
|
493 |
+
if (!distTarget) return 10000;
|
494 |
+
targetX = distTarget.x;
|
495 |
+
targetY = distTarget.y;
|
496 |
+
}
|
497 |
+
|
498 |
+
const dx = util.target.x - targetX;
|
499 |
+
const dy = util.target.y - targetY;
|
500 |
+
return Math.sqrt((dx * dx) + (dy * dy));
|
501 |
+
}
|
502 |
+
|
503 |
+
setDragMode (args, util) {
|
504 |
+
util.target.setDraggable(args.DRAG_MODE === 'draggable');
|
505 |
+
}
|
506 |
+
|
507 |
+
getTimer (args, util) {
|
508 |
+
return util.ioQuery('clock', 'projectTimer');
|
509 |
+
}
|
510 |
+
|
511 |
+
resetTimer (args, util) {
|
512 |
+
util.ioQuery('clock', 'resetProjectTimer');
|
513 |
+
}
|
514 |
+
|
515 |
+
getMouseX (args, util) {
|
516 |
+
return util.ioQuery('mouse', 'getScratchX');
|
517 |
+
}
|
518 |
+
|
519 |
+
getMouseY (args, util) {
|
520 |
+
return util.ioQuery('mouse', 'getScratchY');
|
521 |
+
}
|
522 |
+
|
523 |
+
getMouseDown (args, util) {
|
524 |
+
return util.ioQuery('mouse', 'getIsDown');
|
525 |
+
}
|
526 |
+
|
527 |
+
getFingerX (args, util) {
|
528 |
+
return util.ioQuery('touch', 'getScratchX', [Cast.toNumber(args.FINGER_OPTION) - 1]);
|
529 |
+
}
|
530 |
+
|
531 |
+
getFingerY (args, util) {
|
532 |
+
return util.ioQuery('touch', 'getScratchY', [Cast.toNumber(args.FINGER_OPTION) - 1]);
|
533 |
+
}
|
534 |
+
|
535 |
+
fingerDown (args, util) {
|
536 |
+
return util.ioQuery('touch', 'getIsDown', [Cast.toNumber(args.FINGER_OPTION) - 1]);
|
537 |
+
}
|
538 |
+
|
539 |
+
fingerTapped (args, util) {
|
540 |
+
return util.ioQuery('touch', 'getIsTapped', [Cast.toNumber(args.FINGER_OPTION) - 1]);
|
541 |
+
}
|
542 |
+
|
543 |
+
current (args) {
|
544 |
+
const menuOption = Cast.toString(args.CURRENTMENU).toLowerCase();
|
545 |
+
const date = new Date();
|
546 |
+
switch (menuOption) {
|
547 |
+
case 'year': return date.getFullYear();
|
548 |
+
case 'month': return date.getMonth() + 1; // getMonth is zero-based
|
549 |
+
case 'date': return date.getDate();
|
550 |
+
case 'dayofweek': return date.getDay() + 1; // getDay is zero-based, Sun=0
|
551 |
+
case 'hour': return date.getHours();
|
552 |
+
case 'minute': return date.getMinutes();
|
553 |
+
case 'second': return date.getSeconds();
|
554 |
+
}
|
555 |
+
return 0;
|
556 |
+
}
|
557 |
+
|
558 |
+
getKeyPressed (args, util) {
|
559 |
+
return util.ioQuery('keyboard', 'getKeyIsDown', [args.KEY_OPTION]);
|
560 |
+
}
|
561 |
+
|
562 |
+
daysSince2000 () {
|
563 |
+
const msPerDay = 24 * 60 * 60 * 1000;
|
564 |
+
const start = new Date(2000, 0, 1); // Months are 0-indexed.
|
565 |
+
const today = new Date();
|
566 |
+
const dstAdjust = today.getTimezoneOffset() - start.getTimezoneOffset();
|
567 |
+
let mSecsSinceStart = today.valueOf() - start.valueOf();
|
568 |
+
mSecsSinceStart += ((today.getTimezoneOffset() - dstAdjust) * 60 * 1000);
|
569 |
+
return mSecsSinceStart / msPerDay;
|
570 |
+
}
|
571 |
+
|
572 |
+
getLoudness () {
|
573 |
+
if (typeof this.runtime.audioEngine === 'undefined') return -1;
|
574 |
+
if (this.runtime.currentStepTime === null) return -1;
|
575 |
+
|
576 |
+
// Only measure loudness once per step
|
577 |
+
const timeSinceLoudness = this._timer.time() - this._cachedLoudnessTimestamp;
|
578 |
+
if (timeSinceLoudness < this.runtime.currentStepTime) {
|
579 |
+
return this._cachedLoudness;
|
580 |
+
}
|
581 |
+
|
582 |
+
this._cachedLoudnessTimestamp = this._timer.time();
|
583 |
+
this._cachedLoudness = this.runtime.audioEngine.getLoudness();
|
584 |
+
this.pushLoudness(this._cachedLoudness);
|
585 |
+
return this._cachedLoudness;
|
586 |
+
}
|
587 |
+
|
588 |
+
isLoud () {
|
589 |
+
this.pushLoudness();
|
590 |
+
let sum = this._loudnessList.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
|
591 |
+
sum /= this._loudnessList.length;
|
592 |
+
return this.getLoudness() > sum + 15;
|
593 |
+
}
|
594 |
+
pushLoudness (value) {
|
595 |
+
if (this._loudnessList.length >= 30) this._loudnessList.shift(); // remove first item
|
596 |
+
this._loudnessList.push(value ?? this.getLoudness());
|
597 |
+
}
|
598 |
+
|
599 |
+
getAttributeOf (args) {
|
600 |
+
let attrTarget;
|
601 |
+
|
602 |
+
if (args.OBJECT === '_stage_') {
|
603 |
+
attrTarget = this.runtime.getTargetForStage();
|
604 |
+
} else {
|
605 |
+
args.OBJECT = Cast.toString(args.OBJECT);
|
606 |
+
attrTarget = this.runtime.getSpriteTargetByName(args.OBJECT);
|
607 |
+
}
|
608 |
+
|
609 |
+
// attrTarget can be undefined if the target does not exist
|
610 |
+
// (e.g. single sprite uploaded from larger project referencing
|
611 |
+
// another sprite that wasn't uploaded)
|
612 |
+
if (!attrTarget) return 0;
|
613 |
+
|
614 |
+
// Generic attributes
|
615 |
+
if (attrTarget.isStage) {
|
616 |
+
switch (args.PROPERTY) {
|
617 |
+
// Scratch 1.4 support
|
618 |
+
case 'background #': return attrTarget.currentCostume + 1;
|
619 |
+
|
620 |
+
case 'backdrop #': return attrTarget.currentCostume + 1;
|
621 |
+
case 'backdrop name':
|
622 |
+
return attrTarget.getCostumes()[attrTarget.currentCostume].name;
|
623 |
+
case 'volume': return attrTarget.volume;
|
624 |
+
}
|
625 |
+
} else {
|
626 |
+
switch (args.PROPERTY) {
|
627 |
+
case 'x position': return attrTarget.x;
|
628 |
+
case 'y position': return attrTarget.y;
|
629 |
+
case 'direction': return attrTarget.direction;
|
630 |
+
case 'costume #': return attrTarget.currentCostume + 1;
|
631 |
+
case 'costume name':
|
632 |
+
return attrTarget.getCostumes()[attrTarget.currentCostume].name;
|
633 |
+
case 'layer': return attrTarget.getLayerOrder();
|
634 |
+
case 'size': return attrTarget.size;
|
635 |
+
case 'volume': return attrTarget.volume;
|
636 |
+
}
|
637 |
+
}
|
638 |
+
|
639 |
+
// Target variables.
|
640 |
+
const varName = args.PROPERTY;
|
641 |
+
const variable = attrTarget.lookupVariableByNameAndType(varName, '', true);
|
642 |
+
if (variable) {
|
643 |
+
return variable.value;
|
644 |
+
}
|
645 |
+
|
646 |
+
// Otherwise, 0
|
647 |
+
return 0;
|
648 |
+
}
|
649 |
+
|
650 |
+
getUsername (args, util) {
|
651 |
+
return util.ioQuery('userData', 'getUsername');
|
652 |
+
}
|
653 |
+
|
654 |
+
getLoggedIn(args, util) {
|
655 |
+
return util.ioQuery('userData', 'getLoggedIn');
|
656 |
+
}
|
657 |
+
}
|
658 |
+
|
659 |
+
module.exports = Scratch3SensingBlocks;
|
src/blocks/scratch3_sound.js
ADDED
@@ -0,0 +1,537 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const MathUtil = require('../util/math-util');
|
2 |
+
const Cast = require('../util/cast');
|
3 |
+
const Clone = require('../util/clone');
|
4 |
+
const getMonitorIdForBlockWithArgs = require('../util/get-monitor-id');
|
5 |
+
|
6 |
+
/**
|
7 |
+
* Occluded boolean value to make its use more understandable.
|
8 |
+
* @const {boolean}
|
9 |
+
*/
|
10 |
+
const STORE_WAITING = true;
|
11 |
+
|
12 |
+
class Scratch3SoundBlocks {
|
13 |
+
constructor (runtime) {
|
14 |
+
/**
|
15 |
+
* The runtime instantiating this block package.
|
16 |
+
* @type {Runtime}
|
17 |
+
*/
|
18 |
+
this.runtime = runtime;
|
19 |
+
|
20 |
+
this.waitingSounds = {};
|
21 |
+
|
22 |
+
// Clear sound effects on green flag and stop button events.
|
23 |
+
this.stopAllSounds = this.stopAllSounds.bind(this);
|
24 |
+
this._stopWaitingSoundsForTarget = this._stopWaitingSoundsForTarget.bind(this);
|
25 |
+
this._clearEffectsForAllTargets = this._clearEffectsForAllTargets.bind(this);
|
26 |
+
if (this.runtime) {
|
27 |
+
this.runtime.on('PROJECT_STOP_ALL', this.stopAllSounds);
|
28 |
+
this.runtime.on('PROJECT_STOP_ALL', this._clearEffectsForAllTargets);
|
29 |
+
this.runtime.on('STOP_FOR_TARGET', this._stopWaitingSoundsForTarget);
|
30 |
+
this.runtime.on('PROJECT_START', this._clearEffectsForAllTargets);
|
31 |
+
}
|
32 |
+
|
33 |
+
this._onTargetCreated = this._onTargetCreated.bind(this);
|
34 |
+
if (this.runtime) {
|
35 |
+
runtime.on('targetWasCreated', this._onTargetCreated);
|
36 |
+
}
|
37 |
+
}
|
38 |
+
|
39 |
+
/**
|
40 |
+
* The key to load & store a target's sound-related state.
|
41 |
+
* @type {string}
|
42 |
+
*/
|
43 |
+
static get STATE_KEY () {
|
44 |
+
return 'Scratch.sound';
|
45 |
+
}
|
46 |
+
|
47 |
+
/**
|
48 |
+
* The default sound-related state, to be used when a target has no existing sound state.
|
49 |
+
* @type {SoundState}
|
50 |
+
*/
|
51 |
+
static get DEFAULT_SOUND_STATE () {
|
52 |
+
return {
|
53 |
+
effects: {
|
54 |
+
pitch: 0,
|
55 |
+
pan: 0
|
56 |
+
}
|
57 |
+
};
|
58 |
+
}
|
59 |
+
|
60 |
+
/**
|
61 |
+
* The minimum and maximum MIDI note numbers, for clamping the input to play note.
|
62 |
+
* @type {{min: number, max: number}}
|
63 |
+
*/
|
64 |
+
static get MIDI_NOTE_RANGE () {
|
65 |
+
return {min: 36, max: 96}; // C2 to C7
|
66 |
+
}
|
67 |
+
|
68 |
+
/**
|
69 |
+
* The minimum and maximum beat values, for clamping the duration of play note, play drum and rest.
|
70 |
+
* 100 beats at the default tempo of 60bpm is 100 seconds.
|
71 |
+
* @type {{min: number, max: number}}
|
72 |
+
*/
|
73 |
+
static get BEAT_RANGE () {
|
74 |
+
return {min: 0, max: 100};
|
75 |
+
}
|
76 |
+
|
77 |
+
/** The minimum and maximum tempo values, in bpm.
|
78 |
+
* @type {{min: number, max: number}}
|
79 |
+
*/
|
80 |
+
static get TEMPO_RANGE () {
|
81 |
+
return {min: 20, max: 500};
|
82 |
+
}
|
83 |
+
|
84 |
+
/** The minimum and maximum values for each sound effect.
|
85 |
+
* @type {{effect:{min: number, max: number}}}
|
86 |
+
*/
|
87 |
+
static get EFFECT_RANGE () {
|
88 |
+
return {
|
89 |
+
pitch: {min: -360, max: 360}, // -3 to 3 octaves
|
90 |
+
pan: {min: -100, max: 100} // 100% left to 100% right
|
91 |
+
};
|
92 |
+
}
|
93 |
+
|
94 |
+
/** The minimum and maximum values for sound effects when miscellaneous limits are removed. */
|
95 |
+
static get LARGER_EFFECT_RANGE () {
|
96 |
+
return {
|
97 |
+
// scratch-audio throws if pitch is too big because some math results in Infinity
|
98 |
+
pitch: {min: -1000, max: 1000},
|
99 |
+
|
100 |
+
// No reason for these to go beyond 100
|
101 |
+
pan: {min: -100, max: 100}
|
102 |
+
};
|
103 |
+
}
|
104 |
+
|
105 |
+
/**
|
106 |
+
* @param {Target} target - collect sound state for this target.
|
107 |
+
* @returns {SoundState} the mutable sound state associated with that target. This will be created if necessary.
|
108 |
+
* @private
|
109 |
+
*/
|
110 |
+
_getSoundState (target) {
|
111 |
+
let soundState = target.getCustomState(Scratch3SoundBlocks.STATE_KEY);
|
112 |
+
if (!soundState) {
|
113 |
+
soundState = Clone.simple(Scratch3SoundBlocks.DEFAULT_SOUND_STATE);
|
114 |
+
target.setCustomState(Scratch3SoundBlocks.STATE_KEY, soundState);
|
115 |
+
target.soundEffects = soundState.effects;
|
116 |
+
}
|
117 |
+
return soundState;
|
118 |
+
}
|
119 |
+
|
120 |
+
/**
|
121 |
+
* When a Target is cloned, clone the sound state.
|
122 |
+
* @param {Target} newTarget - the newly created target.
|
123 |
+
* @param {Target} [sourceTarget] - the target used as a source for the new clone, if any.
|
124 |
+
* @listens Runtime#event:targetWasCreated
|
125 |
+
* @private
|
126 |
+
*/
|
127 |
+
_onTargetCreated (newTarget, sourceTarget) {
|
128 |
+
if (sourceTarget) {
|
129 |
+
const soundState = sourceTarget.getCustomState(Scratch3SoundBlocks.STATE_KEY);
|
130 |
+
if (soundState && newTarget) {
|
131 |
+
newTarget.setCustomState(Scratch3SoundBlocks.STATE_KEY, Clone.simple(soundState));
|
132 |
+
this._syncEffectsForTarget(newTarget);
|
133 |
+
}
|
134 |
+
}
|
135 |
+
}
|
136 |
+
|
137 |
+
/**
|
138 |
+
* Retrieve the block primitives implemented by this package.
|
139 |
+
* @return {object.<string, Function>} Mapping of opcode to Function.
|
140 |
+
*/
|
141 |
+
getPrimitives () {
|
142 |
+
return {
|
143 |
+
sound_play: this.playSound,
|
144 |
+
sound_playallsounds: this.playSoundAllLolOpAOIUHFoiubea87fge87iufwhef87wye87fn,
|
145 |
+
sound_playuntildone: this.playSoundAndWait,
|
146 |
+
sound_stop: this.stopSpecificSound,
|
147 |
+
sound_stopallsounds: this.stopAllSounds,
|
148 |
+
sound_seteffectto: this.setEffect,
|
149 |
+
sound_changeeffectby: this.changeEffect,
|
150 |
+
sound_cleareffects: this.clearEffects,
|
151 |
+
sound_sounds_menu: this.soundsMenu,
|
152 |
+
sound_beats_menu: this.beatsMenu,
|
153 |
+
sound_effects_menu: this.effectsMenu,
|
154 |
+
sound_setvolumeto: this.setVolume,
|
155 |
+
sound_changevolumeby: this.changeVolume,
|
156 |
+
sound_volume: this.getVolume,
|
157 |
+
sound_isSoundPlaying: this.isSoundPlaying,
|
158 |
+
sound_getEffectValue: this.getEffectValue,
|
159 |
+
sound_getLength: this.getLength,
|
160 |
+
sound_set_stop_fadeout_to: this.setStopFadeout,
|
161 |
+
sound_play_at_seconds: this.playAtSeconds,
|
162 |
+
sound_play_at_seconds_until_done: this.playAtSecondsAndWait,
|
163 |
+
sound_getSoundVolume: this.currentSoundVolume
|
164 |
+
};
|
165 |
+
}
|
166 |
+
|
167 |
+
getMonitored () {
|
168 |
+
return {
|
169 |
+
sound_volume: {
|
170 |
+
isSpriteSpecific: true,
|
171 |
+
getId: targetId => `${targetId}_volume`
|
172 |
+
},
|
173 |
+
sound_getEffectValue: {
|
174 |
+
isSpriteSpecific: true,
|
175 |
+
getId: (targetId, fields) => getMonitorIdForBlockWithArgs(`${targetId}_getEffectValue`, fields)
|
176 |
+
},
|
177 |
+
};
|
178 |
+
}
|
179 |
+
|
180 |
+
currentSoundVolume (args, util) {
|
181 |
+
|
182 |
+
}
|
183 |
+
|
184 |
+
playAtSeconds (args, util) {
|
185 |
+
const seconds = Cast.toNumber(args.VALUE);
|
186 |
+
if (seconds < 0) {
|
187 |
+
return;
|
188 |
+
}
|
189 |
+
|
190 |
+
this._playSoundAtTimePosition({
|
191 |
+
sound: Cast.toString(args.SOUND_MENU),
|
192 |
+
seconds: seconds
|
193 |
+
}, util, STORE_WAITING);
|
194 |
+
}
|
195 |
+
playAtSecondsAndWait (args, util) {
|
196 |
+
// return promise
|
197 |
+
const seconds = Cast.toNumber(args.VALUE);
|
198 |
+
if (seconds < 0) {
|
199 |
+
return;
|
200 |
+
}
|
201 |
+
|
202 |
+
return this._playSoundAtTimePosition({
|
203 |
+
sound: Cast.toString(args.SOUND_MENU),
|
204 |
+
seconds: seconds
|
205 |
+
}, util, STORE_WAITING);
|
206 |
+
}
|
207 |
+
|
208 |
+
_playSoundAtTimePosition ({ sound, seconds }, util, storeWaiting) {
|
209 |
+
const index = this._getSoundIndex(sound, util);
|
210 |
+
if (index >= 0) {
|
211 |
+
const {target} = util;
|
212 |
+
const {sprite} = target;
|
213 |
+
const {soundId} = sprite.sounds[index];
|
214 |
+
if (sprite.soundBank) {
|
215 |
+
if (storeWaiting === STORE_WAITING) {
|
216 |
+
this._addWaitingSound(target.id, soundId);
|
217 |
+
} else {
|
218 |
+
this._removeWaitingSound(target.id, soundId);
|
219 |
+
}
|
220 |
+
return sprite.soundBank.playSound(target, soundId, seconds);
|
221 |
+
}
|
222 |
+
}
|
223 |
+
}
|
224 |
+
|
225 |
+
setStopFadeout (args, util) {
|
226 |
+
const id = Cast.toString(args.SOUND_MENU);
|
227 |
+
const index = this._getSoundIndex(id, util);
|
228 |
+
if (index < 0) return;
|
229 |
+
|
230 |
+
const target = util.target;
|
231 |
+
const sprite = target.sprite;
|
232 |
+
if (!sprite) return;
|
233 |
+
if (!sprite.sounds) return;
|
234 |
+
|
235 |
+
const { soundId } = sprite.sounds[index];
|
236 |
+
|
237 |
+
const soundBank = sprite.soundBank
|
238 |
+
if (!soundBank) return;
|
239 |
+
|
240 |
+
const decayTime = Cast.toNumber(args.VALUE);
|
241 |
+
if (decayTime <= 0) {
|
242 |
+
soundBank.soundPlayers[soundId].stopFadeDecay = 0;
|
243 |
+
return;
|
244 |
+
}
|
245 |
+
|
246 |
+
soundBank.soundPlayers[soundId].stopFadeDecay = decayTime;
|
247 |
+
}
|
248 |
+
|
249 |
+
getEffectValue (args, util) {
|
250 |
+
const target = util.target;
|
251 |
+
|
252 |
+
const effects = target.soundEffects;
|
253 |
+
if (!effects) return 0;
|
254 |
+
|
255 |
+
const effect = Cast.toString(args.EFFECT).toLowerCase();
|
256 |
+
if (!effects.hasOwnProperty(effect)) return 0;
|
257 |
+
const value = Cast.toNumber(effects[effect]);
|
258 |
+
|
259 |
+
return value;
|
260 |
+
}
|
261 |
+
|
262 |
+
isSoundPlaying (args, util) {
|
263 |
+
const index = this._getSoundIndex(args.SOUND_MENU, util);
|
264 |
+
if (index < 0) return false;
|
265 |
+
|
266 |
+
const target = util.target;
|
267 |
+
const sprite = target.sprite;
|
268 |
+
if (!sprite) return false;
|
269 |
+
|
270 |
+
const { soundId } = sprite.sounds[index];
|
271 |
+
|
272 |
+
const soundBank = sprite.soundBank
|
273 |
+
if (!soundBank) return false;
|
274 |
+
const players = soundBank.soundPlayers;
|
275 |
+
if (!players) return false;
|
276 |
+
if (!players.hasOwnProperty(soundId)) return false;
|
277 |
+
|
278 |
+
return players[soundId].isPlaying == true;
|
279 |
+
}
|
280 |
+
|
281 |
+
getLength (args, util) {
|
282 |
+
const index = this._getSoundIndex(args.SOUND_MENU, util);
|
283 |
+
if (index < 0) return 0;
|
284 |
+
|
285 |
+
const target = util.target;
|
286 |
+
const sprite = target.sprite;
|
287 |
+
if (!sprite) return 0;
|
288 |
+
|
289 |
+
const { soundId } = sprite.sounds[index];
|
290 |
+
|
291 |
+
const soundBank = sprite.soundBank
|
292 |
+
if (!soundBank) return 0;
|
293 |
+
const players = soundBank.soundPlayers;
|
294 |
+
if (!players) return 0;
|
295 |
+
if (!players.hasOwnProperty(soundId)) return 0;
|
296 |
+
const buffer = players[soundId].buffer;
|
297 |
+
if (!buffer) return 0;
|
298 |
+
|
299 |
+
return Cast.toNumber(buffer.duration);
|
300 |
+
}
|
301 |
+
|
302 |
+
stopSpecificSound (args, util) {
|
303 |
+
const index = this._getSoundIndex(args.SOUND_MENU, util);
|
304 |
+
if (index < 0) return;
|
305 |
+
|
306 |
+
const target = util.target;
|
307 |
+
const sprite = target.sprite;
|
308 |
+
if (!sprite) return;
|
309 |
+
|
310 |
+
const { soundId } = sprite.sounds[index];
|
311 |
+
|
312 |
+
const soundBank = sprite.soundBank
|
313 |
+
if (!soundBank) return;
|
314 |
+
|
315 |
+
soundBank.stop(target, soundId);
|
316 |
+
}
|
317 |
+
|
318 |
+
playSound (args, util) {
|
319 |
+
// Don't return the promise, it's the only difference for AndWait
|
320 |
+
this._playSound(args, util);
|
321 |
+
}
|
322 |
+
|
323 |
+
playSoundAndWait (args, util) {
|
324 |
+
return this._playSound(args, util, STORE_WAITING);
|
325 |
+
}
|
326 |
+
|
327 |
+
_playSound (args, util, storeWaiting) {
|
328 |
+
const index = this._getSoundIndex(args.SOUND_MENU, util);
|
329 |
+
if (index >= 0) {
|
330 |
+
const {target} = util;
|
331 |
+
const {sprite} = target;
|
332 |
+
const {soundId} = sprite.sounds[index];
|
333 |
+
if (sprite.soundBank) {
|
334 |
+
if (storeWaiting === STORE_WAITING) {
|
335 |
+
this._addWaitingSound(target.id, soundId);
|
336 |
+
} else {
|
337 |
+
this._removeWaitingSound(target.id, soundId);
|
338 |
+
}
|
339 |
+
return sprite.soundBank.playSound(target, soundId);
|
340 |
+
}
|
341 |
+
}
|
342 |
+
}
|
343 |
+
|
344 |
+
_addWaitingSound (targetId, soundId) {
|
345 |
+
if (!this.waitingSounds[targetId]) {
|
346 |
+
this.waitingSounds[targetId] = new Set();
|
347 |
+
}
|
348 |
+
this.waitingSounds[targetId].add(soundId);
|
349 |
+
}
|
350 |
+
|
351 |
+
_removeWaitingSound (targetId, soundId) {
|
352 |
+
if (!this.waitingSounds[targetId]) {
|
353 |
+
return;
|
354 |
+
}
|
355 |
+
this.waitingSounds[targetId].delete(soundId);
|
356 |
+
}
|
357 |
+
|
358 |
+
_getSoundIndex (soundName, util) {
|
359 |
+
// if the sprite has no sounds, return -1
|
360 |
+
const len = util.target.sprite.sounds.length;
|
361 |
+
if (len === 0) {
|
362 |
+
return -1;
|
363 |
+
}
|
364 |
+
|
365 |
+
// look up by name first
|
366 |
+
const index = this.getSoundIndexByName(soundName, util);
|
367 |
+
if (index !== -1) {
|
368 |
+
return index;
|
369 |
+
}
|
370 |
+
|
371 |
+
// then try using the sound name as a 1-indexed index
|
372 |
+
const oneIndexedIndex = parseInt(soundName, 10);
|
373 |
+
if (!isNaN(oneIndexedIndex)) {
|
374 |
+
return MathUtil.wrapClamp(oneIndexedIndex - 1, 0, len - 1);
|
375 |
+
}
|
376 |
+
|
377 |
+
// could not be found as a name or converted to index, return -1
|
378 |
+
return -1;
|
379 |
+
}
|
380 |
+
|
381 |
+
getSoundIndexByName (soundName, util) {
|
382 |
+
const sounds = util.target.sprite.sounds;
|
383 |
+
for (let i = 0; i < sounds.length; i++) {
|
384 |
+
if (sounds[i].name === soundName) {
|
385 |
+
return i;
|
386 |
+
}
|
387 |
+
}
|
388 |
+
// if there is no sound by that name, return -1
|
389 |
+
return -1;
|
390 |
+
}
|
391 |
+
|
392 |
+
stopAllSounds () {
|
393 |
+
if (this.runtime.targets === null) return;
|
394 |
+
const allTargets = this.runtime.targets;
|
395 |
+
for (let i = 0; i < allTargets.length; i++) {
|
396 |
+
this._stopAllSoundsForTarget(allTargets[i]);
|
397 |
+
}
|
398 |
+
}
|
399 |
+
|
400 |
+
playSoundAllLolOpAOIUHFoiubea87fge87iufwhef87wye87fn (_, util) {
|
401 |
+
const target = util.target;
|
402 |
+
const sprite = target.sprite;
|
403 |
+
if (!sprite) return;
|
404 |
+
for (let i = 0; i < sprite.sounds.length; i++) {
|
405 |
+
const { soundId } = sprite.sounds[i];
|
406 |
+
if (sprite.soundBank) {
|
407 |
+
sprite.soundBank.playSound(target, soundId);
|
408 |
+
}
|
409 |
+
}
|
410 |
+
}
|
411 |
+
|
412 |
+
_stopAllSoundsForTarget (target) {
|
413 |
+
if (target.sprite.soundBank) {
|
414 |
+
target.sprite.soundBank.stopAllSounds(target);
|
415 |
+
if (this.waitingSounds[target.id]) {
|
416 |
+
this.waitingSounds[target.id].clear();
|
417 |
+
}
|
418 |
+
}
|
419 |
+
}
|
420 |
+
|
421 |
+
_stopWaitingSoundsForTarget (target) {
|
422 |
+
if (target.sprite.soundBank) {
|
423 |
+
if (this.waitingSounds[target.id]) {
|
424 |
+
for (const soundId of this.waitingSounds[target.id].values()) {
|
425 |
+
target.sprite.soundBank.stop(target, soundId);
|
426 |
+
}
|
427 |
+
this.waitingSounds[target.id].clear();
|
428 |
+
}
|
429 |
+
}
|
430 |
+
}
|
431 |
+
|
432 |
+
setEffect (args, util) {
|
433 |
+
return this._updateEffect(args, util, false);
|
434 |
+
}
|
435 |
+
|
436 |
+
changeEffect (args, util) {
|
437 |
+
return this._updateEffect(args, util, true);
|
438 |
+
}
|
439 |
+
|
440 |
+
_updateEffect (args, util, change) {
|
441 |
+
const effect = Cast.toString(args.EFFECT).toLowerCase();
|
442 |
+
const value = Cast.toNumber(args.VALUE);
|
443 |
+
|
444 |
+
const soundState = this._getSoundState(util.target);
|
445 |
+
if (!soundState.effects.hasOwnProperty(effect)) return;
|
446 |
+
|
447 |
+
if (change) {
|
448 |
+
soundState.effects[effect] += value;
|
449 |
+
} else {
|
450 |
+
soundState.effects[effect] = value;
|
451 |
+
}
|
452 |
+
|
453 |
+
const miscLimits = this.runtime.runtimeOptions.miscLimits;
|
454 |
+
const {min, max} = miscLimits ?
|
455 |
+
Scratch3SoundBlocks.EFFECT_RANGE[effect] :
|
456 |
+
Scratch3SoundBlocks.LARGER_EFFECT_RANGE[effect];
|
457 |
+
soundState.effects[effect] = MathUtil.clamp(soundState.effects[effect], min, max);
|
458 |
+
|
459 |
+
this._syncEffectsForTarget(util.target);
|
460 |
+
if (miscLimits) {
|
461 |
+
// Yield until the next tick.
|
462 |
+
return Promise.resolve();
|
463 |
+
}
|
464 |
+
|
465 |
+
// Requesting a redraw makes sure that "forever: change pitch by 1" still work but without
|
466 |
+
// yielding unnecessarily in other cases
|
467 |
+
this.runtime.requestRedraw();
|
468 |
+
}
|
469 |
+
|
470 |
+
_syncEffectsForTarget (target) {
|
471 |
+
if (!target || !target.sprite.soundBank) return;
|
472 |
+
target.soundEffects = this._getSoundState(target).effects;
|
473 |
+
|
474 |
+
target.sprite.soundBank.setEffects(target);
|
475 |
+
}
|
476 |
+
|
477 |
+
clearEffects (args, util) {
|
478 |
+
this._clearEffectsForTarget(util.target);
|
479 |
+
}
|
480 |
+
|
481 |
+
_clearEffectsForTarget (target) {
|
482 |
+
const soundState = this._getSoundState(target);
|
483 |
+
for (const effect in soundState.effects) {
|
484 |
+
if (!soundState.effects.hasOwnProperty(effect)) continue;
|
485 |
+
soundState.effects[effect] = 0;
|
486 |
+
}
|
487 |
+
this._syncEffectsForTarget(target);
|
488 |
+
}
|
489 |
+
|
490 |
+
_clearEffectsForAllTargets () {
|
491 |
+
if (this.runtime.targets === null) return;
|
492 |
+
const allTargets = this.runtime.targets;
|
493 |
+
for (let i = 0; i < allTargets.length; i++) {
|
494 |
+
this._clearEffectsForTarget(allTargets[i]);
|
495 |
+
}
|
496 |
+
}
|
497 |
+
|
498 |
+
setVolume (args, util) {
|
499 |
+
const volume = Cast.toNumber(args.VOLUME);
|
500 |
+
return this._updateVolume(volume, util.target);
|
501 |
+
}
|
502 |
+
|
503 |
+
changeVolume (args, util) {
|
504 |
+
const volume = Cast.toNumber(args.VOLUME) + util.target.volume;
|
505 |
+
return this._updateVolume(volume, util.target);
|
506 |
+
}
|
507 |
+
|
508 |
+
_updateVolume (volume, target) {
|
509 |
+
volume = MathUtil.clamp(volume, 0, 100);
|
510 |
+
target.volume = volume;
|
511 |
+
this._syncEffectsForTarget(target);
|
512 |
+
|
513 |
+
if (this.runtime.runtimeOptions.miscLimits) {
|
514 |
+
// Yield until the next tick.
|
515 |
+
return Promise.resolve();
|
516 |
+
}
|
517 |
+
this.runtime.requestRedraw();
|
518 |
+
}
|
519 |
+
|
520 |
+
getVolume (args, util) {
|
521 |
+
return util.target.volume;
|
522 |
+
}
|
523 |
+
|
524 |
+
soundsMenu (args) {
|
525 |
+
return args.SOUND_MENU;
|
526 |
+
}
|
527 |
+
|
528 |
+
beatsMenu (args) {
|
529 |
+
return args.BEATS;
|
530 |
+
}
|
531 |
+
|
532 |
+
effectsMenu (args) {
|
533 |
+
return args.EFFECT;
|
534 |
+
}
|
535 |
+
}
|
536 |
+
|
537 |
+
module.exports = Scratch3SoundBlocks;
|
src/cli/index.js
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const fs = require('fs');
|
2 |
+
const VirtualMachine = require('../index');
|
3 |
+
|
4 |
+
/* eslint-env node */
|
5 |
+
/* eslint-disable no-console */
|
6 |
+
|
7 |
+
const file = process.argv[2];
|
8 |
+
if (!file) {
|
9 |
+
throw new Error('Invalid file');
|
10 |
+
}
|
11 |
+
|
12 |
+
const runProject = async buffer => {
|
13 |
+
const vm = new VirtualMachine();
|
14 |
+
vm.runtime.on('SAY', (target, type, text) => {
|
15 |
+
console.log(text);
|
16 |
+
});
|
17 |
+
vm.setCompatibilityMode(true);
|
18 |
+
vm.clear();
|
19 |
+
await vm.loadProject(buffer);
|
20 |
+
vm.start();
|
21 |
+
vm.greenFlag();
|
22 |
+
await new Promise(resolve => {
|
23 |
+
const interval = setInterval(() => {
|
24 |
+
let active = 0;
|
25 |
+
const threads = vm.runtime.threads;
|
26 |
+
for (let i = 0; i < threads.length; i++) {
|
27 |
+
if (!threads[i].updateMonitor) {
|
28 |
+
active += 1;
|
29 |
+
}
|
30 |
+
}
|
31 |
+
if (active === 0) {
|
32 |
+
clearInterval(interval);
|
33 |
+
resolve();
|
34 |
+
}
|
35 |
+
}, 50);
|
36 |
+
});
|
37 |
+
vm.stopAll();
|
38 |
+
vm.stop();
|
39 |
+
};
|
40 |
+
|
41 |
+
runProject(fs.readFileSync(file));
|
src/compiler/compat-block-utility.js
ADDED
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const BlockUtility = require('../engine/block-utility');
|
2 |
+
|
3 |
+
class CompatibilityLayerBlockUtility extends BlockUtility {
|
4 |
+
constructor () {
|
5 |
+
super();
|
6 |
+
this._startedBranch = null;
|
7 |
+
}
|
8 |
+
|
9 |
+
get stackFrame () {
|
10 |
+
return this.thread.compatibilityStackFrame;
|
11 |
+
}
|
12 |
+
|
13 |
+
startBranch (branchNumber, isLoop, onEnd) {
|
14 |
+
if (this._branchInfo && onEnd) this._branchInfo.onEnd.push(onEnd);
|
15 |
+
this._startedBranch = [branchNumber, isLoop];
|
16 |
+
}
|
17 |
+
|
18 |
+
/**
|
19 |
+
* runs any given procedure
|
20 |
+
* @param {String} proccode the procedure to start
|
21 |
+
* @param {Object} args
|
22 |
+
* @returns the return value of the procedure, returns undefined if statement
|
23 |
+
*/
|
24 |
+
startProcedure (proccode, args) {
|
25 |
+
if (!args)
|
26 |
+
return this.thread.procedures[proccode]();
|
27 |
+
if (!(typeof args === 'object'))
|
28 |
+
throw new Error(`procedure arguments can only be of type undefined|object. instead got "${typeof args}"`);
|
29 |
+
let evaluate = `this.thread.procedures[proccode](`;
|
30 |
+
const inputs = [];
|
31 |
+
for (const arg in args) {
|
32 |
+
inputs.push(String(args[arg]));
|
33 |
+
}
|
34 |
+
evaluate += `${inputs.join(',')})`;
|
35 |
+
return new Function(`Procedure ${proccode}`, evaluate)();
|
36 |
+
}
|
37 |
+
|
38 |
+
/*
|
39 |
+
// Parameters are not used by compiled scripts.
|
40 |
+
initParams () {
|
41 |
+
throw new Error('initParams is not supported by this BlockUtility');
|
42 |
+
}
|
43 |
+
pushParam () {
|
44 |
+
throw new Error('pushParam is not supported by this BlockUtility');
|
45 |
+
}
|
46 |
+
getParam () {
|
47 |
+
throw new Error('getParam is not supported by this BlockUtility');
|
48 |
+
}
|
49 |
+
*/
|
50 |
+
|
51 |
+
init (thread, fakeBlockId, stackFrame, branchInfo) {
|
52 |
+
this.thread = thread;
|
53 |
+
this.sequencer = thread.target.runtime.sequencer;
|
54 |
+
this._startedBranch = null;
|
55 |
+
this._branchInfo = branchInfo;
|
56 |
+
thread.stack[0] = fakeBlockId;
|
57 |
+
thread.compatibilityStackFrame = stackFrame;
|
58 |
+
}
|
59 |
+
}
|
60 |
+
|
61 |
+
// Export a single instance to be reused.
|
62 |
+
module.exports = new CompatibilityLayerBlockUtility();
|
src/compiler/compat-blocks.js
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* @fileoverview List of blocks to be supported in the compiler compatibility layer.
|
3 |
+
* This is only for native blocks. Extensions should not be listed here.
|
4 |
+
*/
|
5 |
+
|
6 |
+
// Please keep these lists alphabetical.
|
7 |
+
// no >:(
|
8 |
+
// haha cry about it - jerem
|
9 |
+
|
10 |
+
const statementBlocks = [
|
11 |
+
'looks_hideallsprites',
|
12 |
+
'looks_say',
|
13 |
+
'looks_sayforsecs',
|
14 |
+
'looks_setstretchto',
|
15 |
+
'looks_switchbackdroptoandwait',
|
16 |
+
'looks_think',
|
17 |
+
'looks_thinkforsecs',
|
18 |
+
'motion_align_scene',
|
19 |
+
'motion_glidesecstoxy',
|
20 |
+
'motion_glideto',
|
21 |
+
'motion_goto',
|
22 |
+
'motion_pointtowards',
|
23 |
+
'motion_scroll_right',
|
24 |
+
'motion_scroll_up',
|
25 |
+
'sensing_askandwait',
|
26 |
+
'sensing_setdragmode',
|
27 |
+
'sound_changeeffectby',
|
28 |
+
'sound_changevolumeby',
|
29 |
+
'sound_cleareffects',
|
30 |
+
'sound_play',
|
31 |
+
'sound_playuntildone',
|
32 |
+
'sound_stop',
|
33 |
+
'sound_seteffectto',
|
34 |
+
'sound_setvolumeto',
|
35 |
+
'sound_stopallsounds',
|
36 |
+
"looks_setStretch",
|
37 |
+
"looks_changeStretch",
|
38 |
+
"data_reverselist",
|
39 |
+
"data_arraylist",
|
40 |
+
"control_switch",
|
41 |
+
"control_switch_default",
|
42 |
+
"control_case",
|
43 |
+
"control_exitCase",
|
44 |
+
"control_case_next",
|
45 |
+
"control_backToGreenFlag",
|
46 |
+
'looks_setHorizTransform',
|
47 |
+
'looks_setVertTransform',
|
48 |
+
'looks_layersSetLayer',
|
49 |
+
'control_waitsecondsoruntil',
|
50 |
+
'control_delete_clones_of',
|
51 |
+
'control_stop_sprite',
|
52 |
+
'looks_changeVisibilityOfSprite',
|
53 |
+
'looks_previouscostume',
|
54 |
+
'looks_previousbackdrop',
|
55 |
+
'motion_pointinrandomdirection',
|
56 |
+
'motion_move_sprite_to_scene_side',
|
57 |
+
'sound_playallsounds',
|
58 |
+
'looks_stoptalking',
|
59 |
+
'sensing_setclipboard',
|
60 |
+
'motion_movebacksteps',
|
61 |
+
'motion_moveupdownsteps',
|
62 |
+
'motion_turnrightaroundxy',
|
63 |
+
'motion_turnleftaroundxy',
|
64 |
+
'motion_turnaround',
|
65 |
+
'motion_pointinrandomdirection',
|
66 |
+
'motion_pointtowardsxy',
|
67 |
+
'motion_glidedirectionstepsinseconds',
|
68 |
+
'motion_changebyxy',
|
69 |
+
'motion_ifonspritebounce',
|
70 |
+
'motion_ifonxybounce',
|
71 |
+
'motion_move_sprite_to_scene_side',
|
72 |
+
'control_javascript_command',
|
73 |
+
'looks_changeVisibilityOfSpriteShow',
|
74 |
+
'looks_changeVisibilityOfSpriteHide',
|
75 |
+
'sound_pause',
|
76 |
+
'sound_set_stop_fadeout_to',
|
77 |
+
'sound_play_at_seconds',
|
78 |
+
'sound_play_at_seconds_until_done',
|
79 |
+
'sound_pauseallsounds',
|
80 |
+
'argument_reporter_command'
|
81 |
+
];
|
82 |
+
|
83 |
+
const outputBlocks = [
|
84 |
+
'motion_xscroll',
|
85 |
+
'motion_yscroll',
|
86 |
+
'sensing_loud',
|
87 |
+
'sensing_loudness',
|
88 |
+
'sensing_userid',
|
89 |
+
'sound_volume',
|
90 |
+
"control_if_return_else_return",
|
91 |
+
"looks_stretchGetX",
|
92 |
+
"looks_stretchGetY",
|
93 |
+
"sensing_getspritewithattrib",
|
94 |
+
"sensing_thing_is_text",
|
95 |
+
"sensing_mobile",
|
96 |
+
"sensing_thing_is_number",
|
97 |
+
"sensing_regextest",
|
98 |
+
"operator_indexOfTextInText",
|
99 |
+
"operator_constrainnumber",
|
100 |
+
"operator_advMath",
|
101 |
+
"operator_advMathExpanded",
|
102 |
+
"operator_lerpFunc",
|
103 |
+
"operator_stringify",
|
104 |
+
"operator_newLine",
|
105 |
+
"operator_readLineInMultilineText",
|
106 |
+
"operator_getLettersFromIndexToIndexInText",
|
107 |
+
"operator_getLettersFromIndexToIndexInTextFixed",
|
108 |
+
"operator_replaceAll",
|
109 |
+
"operator_regexmatch",
|
110 |
+
"data_itemexistslist",
|
111 |
+
"data_listisempty",
|
112 |
+
"data_listarray",
|
113 |
+
"looks_sayHeight",
|
114 |
+
"looks_sayWidth",
|
115 |
+
"sensing_isUpperCase",
|
116 |
+
"operator_toUpperLowerCase",
|
117 |
+
"looks_getSpriteVisible",
|
118 |
+
"looks_getEffectValue",
|
119 |
+
'looks_layersGetLayer',
|
120 |
+
'sound_isSoundPlaying',
|
121 |
+
'sound_getEffectValue',
|
122 |
+
'sound_getLength',
|
123 |
+
"sensing_directionTo",
|
124 |
+
"sensing_distanceTo",
|
125 |
+
"operator_boolify",
|
126 |
+
"operator_tabCharacter",
|
127 |
+
"operator_character_to_code",
|
128 |
+
"operator_code_to_character",
|
129 |
+
"sensing_keyhit",
|
130 |
+
"sensing_mousescrolling",
|
131 |
+
"sensing_mouseclicked",
|
132 |
+
"sensing_thing_has_text",
|
133 |
+
"sensing_thing_has_number",
|
134 |
+
"sensing_objecttouchingobject",
|
135 |
+
"sensing_objecttouchingclonesprite",
|
136 |
+
'looks_getOtherSpriteVisible',
|
137 |
+
'operator_gtorequal',
|
138 |
+
'operator_ltorequal',
|
139 |
+
'operator_notequal',
|
140 |
+
'operator_join3',
|
141 |
+
'operator_replaceFirst',
|
142 |
+
'operator_lastIndexOfTextInText',
|
143 |
+
'operator_countAppearTimes',
|
144 |
+
'operator_textIncludesLetterFrom',
|
145 |
+
'operator_textStartsOrEndsWith',
|
146 |
+
'sensing_fingerdown',
|
147 |
+
'sensing_fingertapped',
|
148 |
+
'sensing_fingerx',
|
149 |
+
'sensing_fingery',
|
150 |
+
'sensing_getclipboard',
|
151 |
+
'sensing_getdragmode',
|
152 |
+
'sensing_getoperatingsystem',
|
153 |
+
'sensing_getbrowser',
|
154 |
+
'sensing_geturl',
|
155 |
+
'operator_javascript_output',
|
156 |
+
'operator_javascript_boolean',
|
157 |
+
'sensing_getxyoftouchingsprite',
|
158 |
+
'operator_nand',
|
159 |
+
'operator_nor',
|
160 |
+
'operator_xor',
|
161 |
+
'operator_xnor',
|
162 |
+
'looks_getinputofcostume',
|
163 |
+
'sound_getTimePosition',
|
164 |
+
'sound_getSoundVolume'
|
165 |
+
];
|
166 |
+
|
167 |
+
module.exports = {
|
168 |
+
statementBlocks,
|
169 |
+
outputBlocks
|
170 |
+
};
|
src/compiler/compile.js
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const IRGenerator = require('./irgen');
|
2 |
+
const JSGenerator = require('./jsgen');
|
3 |
+
|
4 |
+
const compile = thread => {
|
5 |
+
const irGenerator = new IRGenerator(thread);
|
6 |
+
const ir = irGenerator.generate();
|
7 |
+
|
8 |
+
const procedures = {};
|
9 |
+
const target = thread.target;
|
10 |
+
|
11 |
+
const compileScript = script => {
|
12 |
+
if (script.cachedCompileResult) {
|
13 |
+
return script.cachedCompileResult;
|
14 |
+
}
|
15 |
+
|
16 |
+
const compiler = new JSGenerator(script, ir, target);
|
17 |
+
const result = compiler.compile();
|
18 |
+
script.cachedCompileResult = result;
|
19 |
+
return result;
|
20 |
+
};
|
21 |
+
|
22 |
+
const entry = compileScript(ir.entry);
|
23 |
+
|
24 |
+
for (const procedureVariant of Object.keys(ir.procedures)) {
|
25 |
+
const procedureData = ir.procedures[procedureVariant];
|
26 |
+
const procedureTree = compileScript(procedureData);
|
27 |
+
procedures[procedureVariant] = procedureTree;
|
28 |
+
}
|
29 |
+
|
30 |
+
return {
|
31 |
+
startingFunction: entry,
|
32 |
+
procedures,
|
33 |
+
executableHat: ir.entry.executableHat
|
34 |
+
};
|
35 |
+
};
|
36 |
+
|
37 |
+
module.exports = compile;
|
src/compiler/environment.js
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/* eslint-disable no-eval */
|
2 |
+
|
3 |
+
/**
|
4 |
+
* @returns {boolean} true if the nullish coalescing operator (x ?? y) is supported.
|
5 |
+
* See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator
|
6 |
+
*/
|
7 |
+
const supportsNullishCoalescing = () => {
|
8 |
+
try {
|
9 |
+
// eslint-disable-next-line no-unused-vars
|
10 |
+
const fn = new Function('undefined ?? 3');
|
11 |
+
// if function construction succeeds, the browser understood the syntax.
|
12 |
+
return true;
|
13 |
+
} catch (e) {
|
14 |
+
return false;
|
15 |
+
}
|
16 |
+
};
|
17 |
+
|
18 |
+
module.exports = {
|
19 |
+
supportsNullishCoalescing: supportsNullishCoalescing()
|
20 |
+
};
|
src/compiler/intermediate.js
ADDED
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* @fileoverview Common intermediates shared amongst parts of the compiler.
|
3 |
+
*/
|
4 |
+
|
5 |
+
/**
|
6 |
+
* An IntermediateScript describes a single script.
|
7 |
+
* Scripts do not necessarily have hats.
|
8 |
+
*/
|
9 |
+
class IntermediateScript {
|
10 |
+
constructor () {
|
11 |
+
/**
|
12 |
+
* The ID of the top block of this script.
|
13 |
+
* @type {string}
|
14 |
+
*/
|
15 |
+
this.topBlockId = null;
|
16 |
+
|
17 |
+
/**
|
18 |
+
* List of nodes that make up this script.
|
19 |
+
* @type {Array|null}
|
20 |
+
*/
|
21 |
+
this.stack = null;
|
22 |
+
|
23 |
+
/**
|
24 |
+
* Whether this script is a procedure.
|
25 |
+
* @type {boolean}
|
26 |
+
*/
|
27 |
+
this.isProcedure = false;
|
28 |
+
|
29 |
+
/**
|
30 |
+
* This procedure's code, if any.
|
31 |
+
* @type {string}
|
32 |
+
*/
|
33 |
+
this.procedureCode = '';
|
34 |
+
|
35 |
+
/**
|
36 |
+
* List of names of arguments accepted by this function, if it is a procedure.
|
37 |
+
* @type {string[]}
|
38 |
+
*/
|
39 |
+
this.arguments = [];
|
40 |
+
|
41 |
+
/**
|
42 |
+
* Whether this script should be run in warp mode.
|
43 |
+
* @type {boolean}
|
44 |
+
*/
|
45 |
+
this.isWarp = false;
|
46 |
+
|
47 |
+
/**
|
48 |
+
* pm: Whether this script should use dangerous optimizations.
|
49 |
+
* @type {boolean}
|
50 |
+
*/
|
51 |
+
this.isOptimized = false;
|
52 |
+
|
53 |
+
/**
|
54 |
+
* pm: An object containing stuff for optimization.
|
55 |
+
* @type {object}
|
56 |
+
*/
|
57 |
+
this.optimizationUtil = {};
|
58 |
+
|
59 |
+
/**
|
60 |
+
* Whether this script can `yield`
|
61 |
+
* If false, this script will be compiled as a regular JavaScript function (function)
|
62 |
+
* If true, this script will be compiled as a generator function (function*)
|
63 |
+
* @type {boolean}
|
64 |
+
*/
|
65 |
+
this.yields = true;
|
66 |
+
|
67 |
+
/**
|
68 |
+
* Whether this script should use the "warp timer"
|
69 |
+
* @type {boolean}
|
70 |
+
*/
|
71 |
+
this.warpTimer = false;
|
72 |
+
|
73 |
+
/**
|
74 |
+
* List of procedure IDs that this script needs.
|
75 |
+
* @readonly
|
76 |
+
*/
|
77 |
+
this.dependedProcedures = [];
|
78 |
+
|
79 |
+
/**
|
80 |
+
* Cached result of compiling this script.
|
81 |
+
* @type {Function|null}
|
82 |
+
*/
|
83 |
+
this.cachedCompileResult = null;
|
84 |
+
|
85 |
+
/**
|
86 |
+
* Whether the top block of this script is an executable hat.
|
87 |
+
* @type {boolean}
|
88 |
+
*/
|
89 |
+
this.executableHat = false;
|
90 |
+
}
|
91 |
+
}
|
92 |
+
|
93 |
+
/**
|
94 |
+
* An IntermediateRepresentation contains scripts.
|
95 |
+
*/
|
96 |
+
class IntermediateRepresentation {
|
97 |
+
constructor () {
|
98 |
+
/**
|
99 |
+
* The entry point of this IR.
|
100 |
+
* @type {IntermediateScript}
|
101 |
+
*/
|
102 |
+
this.entry = null;
|
103 |
+
|
104 |
+
/**
|
105 |
+
* Maps procedure variants to their intermediate script.
|
106 |
+
* @type {Object.<string, IntermediateScript>}
|
107 |
+
*/
|
108 |
+
this.procedures = {};
|
109 |
+
}
|
110 |
+
}
|
111 |
+
|
112 |
+
module.exports = {
|
113 |
+
IntermediateScript,
|
114 |
+
IntermediateRepresentation
|
115 |
+
};
|
src/compiler/irgen.js
ADDED
@@ -0,0 +1,2475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const Cast = require('../util/cast');
|
2 |
+
const StringUtil = require('../util/string-util');
|
3 |
+
const BlockType = require('../extension-support/block-type');
|
4 |
+
const Sequencer = require('../engine/sequencer');
|
5 |
+
const BlockUtility = require('../engine/block-utility');
|
6 |
+
const Variable = require('../engine/variable');
|
7 |
+
const Color = require('../util/color');
|
8 |
+
const log = require('../util/log');
|
9 |
+
const Clone = require('../util/clone');
|
10 |
+
const {IntermediateScript, IntermediateRepresentation} = require('./intermediate');
|
11 |
+
const compatBlocks = require('./compat-blocks');
|
12 |
+
|
13 |
+
/**
|
14 |
+
* @fileoverview Generate intermediate representations from Scratch blocks.
|
15 |
+
*/
|
16 |
+
|
17 |
+
const SCALAR_TYPE = '';
|
18 |
+
const LIST_TYPE = 'list';
|
19 |
+
|
20 |
+
/**
|
21 |
+
* @typedef {Object.<string, *>} Node
|
22 |
+
* @property {string} kind
|
23 |
+
*/
|
24 |
+
|
25 |
+
/**
|
26 |
+
* Create a variable codegen object.
|
27 |
+
* @param {'target'|'stage'} scope The scope of this variable -- which object owns it.
|
28 |
+
* @param {import('../engine/variable.js')} varObj The Scratch Variable
|
29 |
+
* @returns {*} A variable codegen object.
|
30 |
+
*/
|
31 |
+
const createVariableData = (scope, varObj) => ({
|
32 |
+
scope,
|
33 |
+
id: varObj.id,
|
34 |
+
name: varObj.name,
|
35 |
+
isCloud: varObj.isCloud
|
36 |
+
});
|
37 |
+
|
38 |
+
/**
|
39 |
+
* @param {string} code
|
40 |
+
* @param {boolean} warp
|
41 |
+
* @returns {string}
|
42 |
+
*/
|
43 |
+
const generateProcedureVariant = (code, warp) => {
|
44 |
+
if (warp) {
|
45 |
+
return `W${code}`;
|
46 |
+
}
|
47 |
+
return `Z${code}`;
|
48 |
+
};
|
49 |
+
|
50 |
+
/**
|
51 |
+
* @param {string} variant Variant generated by generateProcedureVariant()
|
52 |
+
* @returns {string} original procedure code
|
53 |
+
*/
|
54 |
+
const parseProcedureCode = variant => variant.substring(1);
|
55 |
+
|
56 |
+
/**
|
57 |
+
* @param {string} variant Variant generated by generateProcedureVariant()
|
58 |
+
* @returns {boolean} true if warp enabled
|
59 |
+
*/
|
60 |
+
const parseIsWarp = variant => variant.charAt(0) === 'W';
|
61 |
+
|
62 |
+
class ScriptTreeGenerator {
|
63 |
+
constructor (thread) {
|
64 |
+
/** @private */
|
65 |
+
this.thread = thread;
|
66 |
+
/** @private */
|
67 |
+
this.target = thread.target;
|
68 |
+
/** @private */
|
69 |
+
this.blocks = thread.blockContainer;
|
70 |
+
/** @private */
|
71 |
+
this.runtime = this.target.runtime;
|
72 |
+
/** @private */
|
73 |
+
this.stage = this.runtime.getTargetForStage();
|
74 |
+
/** @private */
|
75 |
+
this.util = new BlockUtility(this.runtime.sequencer, this.thread);
|
76 |
+
|
77 |
+
/**
|
78 |
+
* This script's intermediate representation.
|
79 |
+
*/
|
80 |
+
this.script = new IntermediateScript();
|
81 |
+
this.script.warpTimer = this.target.runtime.compilerOptions.warpTimer;
|
82 |
+
this.script.isOptimized = this.target.runtime.runtimeOptions.dangerousOptimizations;
|
83 |
+
this.script.optimizationUtil = this.target.runtime.optimizationUtil;
|
84 |
+
|
85 |
+
/**
|
86 |
+
* Cache of variable ID to variable data object.
|
87 |
+
* @type {Object.<string, object>}
|
88 |
+
* @private
|
89 |
+
*/
|
90 |
+
this.variableCache = {};
|
91 |
+
|
92 |
+
this.usesTimer = false;
|
93 |
+
}
|
94 |
+
|
95 |
+
setProcedureVariant (procedureVariant) {
|
96 |
+
const procedureCode = parseProcedureCode(procedureVariant);
|
97 |
+
|
98 |
+
this.script.procedureCode = procedureCode;
|
99 |
+
this.script.isProcedure = true;
|
100 |
+
this.script.yields = false;
|
101 |
+
|
102 |
+
const paramNamesIdsAndDefaults = this.blocks.getProcedureParamNamesIdsAndDefaults(procedureCode);
|
103 |
+
if (paramNamesIdsAndDefaults === null) {
|
104 |
+
throw new Error(`IR: cannot find procedure: ${procedureVariant}`);
|
105 |
+
}
|
106 |
+
|
107 |
+
const [paramNames, _paramIds, _paramDefaults] = paramNamesIdsAndDefaults;
|
108 |
+
this.script.arguments = paramNames;
|
109 |
+
}
|
110 |
+
|
111 |
+
enableWarp () {
|
112 |
+
this.script.isWarp = true;
|
113 |
+
}
|
114 |
+
|
115 |
+
getBlockById (blockId) {
|
116 |
+
// Flyout blocks are stored in a special container.
|
117 |
+
return this.blocks.getBlock(blockId) || this.blocks.runtime.flyoutBlocks.getBlock(blockId);
|
118 |
+
}
|
119 |
+
|
120 |
+
getBlockInfo (fullOpcode) {
|
121 |
+
const [category, opcode] = StringUtil.splitFirst(fullOpcode, '_');
|
122 |
+
if (!category || !opcode) {
|
123 |
+
return null;
|
124 |
+
}
|
125 |
+
const categoryInfo = this.runtime._blockInfo.find(ci => ci.id === category);
|
126 |
+
if (!categoryInfo) {
|
127 |
+
return null;
|
128 |
+
}
|
129 |
+
const blockInfo = categoryInfo.blocks.find(b => b.info.opcode === opcode);
|
130 |
+
if (!blockInfo) {
|
131 |
+
return null;
|
132 |
+
}
|
133 |
+
return blockInfo;
|
134 |
+
}
|
135 |
+
|
136 |
+
/**
|
137 |
+
* Descend into a child input of a block. (eg. the input STRING of "length of ( )")
|
138 |
+
* @param {*} parentBlock The parent Scratch block that contains the input.
|
139 |
+
* @param {string} inputName The name of the input to descend into.
|
140 |
+
* @private
|
141 |
+
* @returns {Node} Compiled input node for this input.
|
142 |
+
*/
|
143 |
+
descendInputOfBlock (parentBlock, inputName) {
|
144 |
+
const input = parentBlock.inputs[inputName];
|
145 |
+
if (!input) {
|
146 |
+
log.warn(`IR: ${parentBlock.opcode}: missing input ${inputName}`, parentBlock);
|
147 |
+
return {
|
148 |
+
kind: 'constant',
|
149 |
+
value: 0
|
150 |
+
};
|
151 |
+
}
|
152 |
+
const inputId = input.block;
|
153 |
+
const block = this.getBlockById(inputId);
|
154 |
+
if (!block) {
|
155 |
+
log.warn(`IR: ${parentBlock.opcode}: could not find input ${inputName} with ID ${inputId}`);
|
156 |
+
return {
|
157 |
+
kind: 'constant',
|
158 |
+
value: 0
|
159 |
+
};
|
160 |
+
}
|
161 |
+
|
162 |
+
return this.descendInput(block);
|
163 |
+
}
|
164 |
+
|
165 |
+
/**
|
166 |
+
* Descend into an input. (eg. "length of ( )")
|
167 |
+
* @param {*} block The parent Scratch block input.
|
168 |
+
* @private
|
169 |
+
* @returns {Node} Compiled input node for this input.
|
170 |
+
*/
|
171 |
+
descendInput (block) {
|
172 |
+
// check if we have extension ir for this opcode
|
173 |
+
const extensionId = String(block.opcode).split('_')[0];
|
174 |
+
const blockId = String(block.opcode).replace(extensionId + '_', '');
|
175 |
+
if (IRGenerator.hasExtensionIr(extensionId) && IRGenerator.getExtensionIr(extensionId)[blockId]) {
|
176 |
+
// this is an extension block that wants to be compiled
|
177 |
+
const irFunc = IRGenerator.getExtensionIr(extensionId)[blockId];
|
178 |
+
let irData = null;
|
179 |
+
// make sure irFunc isnt broken
|
180 |
+
try {
|
181 |
+
irData = irFunc(this, block);
|
182 |
+
} catch (err) {
|
183 |
+
log.warn(extensionId + '_' + blockId, 'failed to create IR data;', err);
|
184 |
+
}
|
185 |
+
if (irData) {
|
186 |
+
// check if it is this type, we dont want to descend a stack as an input
|
187 |
+
if (irData.kind === 'input') {
|
188 |
+
// set proper kind
|
189 |
+
irData.kind = extensionId + '.' + blockId;
|
190 |
+
return irData;
|
191 |
+
}
|
192 |
+
}
|
193 |
+
}
|
194 |
+
|
195 |
+
switch (block.opcode) {
|
196 |
+
case 'colour_picker':
|
197 |
+
return {
|
198 |
+
kind: 'constant',
|
199 |
+
value: block.fields.COLOUR.value
|
200 |
+
};
|
201 |
+
case 'math_angle':
|
202 |
+
case 'math_integer':
|
203 |
+
case 'math_number':
|
204 |
+
case 'math_positive_number':
|
205 |
+
case 'math_whole_number':
|
206 |
+
return {
|
207 |
+
kind: 'constant',
|
208 |
+
value: block.fields.NUM.value
|
209 |
+
};
|
210 |
+
case 'text':
|
211 |
+
return {
|
212 |
+
kind: 'constant',
|
213 |
+
value: block.fields.TEXT.value
|
214 |
+
};
|
215 |
+
case 'polygon':
|
216 |
+
const points = [];
|
217 |
+
for (let point = 1; point <= block.mutation.points; point++) {
|
218 |
+
const xn = `x${point}`;
|
219 |
+
const yn = `y${point}`;
|
220 |
+
points.push({
|
221 |
+
x: this.descendInputOfBlock(block, xn),
|
222 |
+
y: this.descendInputOfBlock(block, yn)
|
223 |
+
});
|
224 |
+
}
|
225 |
+
return {
|
226 |
+
kind: 'math.polygon',
|
227 |
+
points
|
228 |
+
};
|
229 |
+
|
230 |
+
case 'argument_reporter_string_number': {
|
231 |
+
const name = block.fields.VALUE.value;
|
232 |
+
// lastIndexOf because multiple parameters with the same name will use the value of the last definition
|
233 |
+
const index = this.script.arguments.lastIndexOf(name);
|
234 |
+
if (index === -1) {
|
235 |
+
// Legacy support
|
236 |
+
if (name.toLowerCase() === 'last key pressed') {
|
237 |
+
return {
|
238 |
+
kind: 'tw.lastKeyPressed'
|
239 |
+
};
|
240 |
+
}
|
241 |
+
}
|
242 |
+
if (index === -1) {
|
243 |
+
return {
|
244 |
+
kind: 'constant',
|
245 |
+
value: 0
|
246 |
+
};
|
247 |
+
}
|
248 |
+
return {
|
249 |
+
kind: 'args.stringNumber',
|
250 |
+
index: index
|
251 |
+
};
|
252 |
+
}
|
253 |
+
case 'argument_reporter_boolean': {
|
254 |
+
// see argument_reporter_string_number above
|
255 |
+
const name = block.fields.VALUE.value;
|
256 |
+
const index = this.script.arguments.lastIndexOf(name);
|
257 |
+
if (index === -1) {
|
258 |
+
if (name.toLowerCase() === 'is compiled?' ||
|
259 |
+
name.toLowerCase() === 'is turbowarp?' ||
|
260 |
+
name.toLowerCase() === 'is penguinmod or turbowarp?') {
|
261 |
+
return {
|
262 |
+
kind: 'constant',
|
263 |
+
value: true
|
264 |
+
};
|
265 |
+
}
|
266 |
+
return {
|
267 |
+
kind: 'constant',
|
268 |
+
value: 0
|
269 |
+
};
|
270 |
+
}
|
271 |
+
return {
|
272 |
+
kind: 'args.boolean',
|
273 |
+
index: index
|
274 |
+
};
|
275 |
+
}
|
276 |
+
|
277 |
+
case 'control_get_counter':
|
278 |
+
return {
|
279 |
+
kind: 'counter.get'
|
280 |
+
};
|
281 |
+
case 'control_error':
|
282 |
+
return {
|
283 |
+
kind: 'control.error'
|
284 |
+
};
|
285 |
+
case 'control_is_clone':
|
286 |
+
return {
|
287 |
+
kind: 'control.isclone'
|
288 |
+
};
|
289 |
+
|
290 |
+
case 'data_variable':
|
291 |
+
return {
|
292 |
+
kind: 'var.get',
|
293 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE)
|
294 |
+
};
|
295 |
+
case 'data_itemoflist':
|
296 |
+
return {
|
297 |
+
kind: 'list.get',
|
298 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
299 |
+
index: this.descendInputOfBlock(block, 'INDEX')
|
300 |
+
};
|
301 |
+
case 'data_lengthoflist':
|
302 |
+
return {
|
303 |
+
kind: 'list.length',
|
304 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
305 |
+
};
|
306 |
+
case 'data_listcontainsitem':
|
307 |
+
return {
|
308 |
+
kind: 'list.contains',
|
309 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
310 |
+
item: this.descendInputOfBlock(block, 'ITEM')
|
311 |
+
};
|
312 |
+
case 'data_itemnumoflist':
|
313 |
+
return {
|
314 |
+
kind: 'list.indexOf',
|
315 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
316 |
+
item: this.descendInputOfBlock(block, 'ITEM')
|
317 |
+
};
|
318 |
+
case 'data_amountinlist':
|
319 |
+
return {
|
320 |
+
kind: 'list.amountOf',
|
321 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
322 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
323 |
+
};
|
324 |
+
case 'data_listcontents':
|
325 |
+
return {
|
326 |
+
kind: 'list.contents',
|
327 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
328 |
+
};
|
329 |
+
case 'data_filterlistitem':
|
330 |
+
return {
|
331 |
+
kind: 'list.filteritem'
|
332 |
+
};
|
333 |
+
case 'data_filterlistindex':
|
334 |
+
return {
|
335 |
+
kind: 'list.filterindex'
|
336 |
+
};
|
337 |
+
|
338 |
+
case 'event_broadcast_menu': {
|
339 |
+
const broadcastOption = block.fields.BROADCAST_OPTION;
|
340 |
+
const broadcastVariable = this.target.lookupBroadcastMsg(broadcastOption.id, broadcastOption.value);
|
341 |
+
// TODO: empty string probably isn't the correct fallback
|
342 |
+
const broadcastName = broadcastVariable ? broadcastVariable.name : '';
|
343 |
+
return {
|
344 |
+
kind: 'constant',
|
345 |
+
value: broadcastName
|
346 |
+
};
|
347 |
+
}
|
348 |
+
|
349 |
+
case 'pmEventsExpansion_broadcastFunction':
|
350 |
+
this.script.yields = true;
|
351 |
+
return {
|
352 |
+
kind: 'pmEventsExpansion.broadcastFunction',
|
353 |
+
broadcast: this.descendInputOfBlock(block, 'BROADCAST')
|
354 |
+
};
|
355 |
+
case 'pmEventsExpansion_broadcastFunctionArgs':
|
356 |
+
this.script.yields = true;
|
357 |
+
return {
|
358 |
+
kind: 'pmEventsExpansion.broadcastFunctionArgs',
|
359 |
+
broadcast: this.descendInputOfBlock(block, 'BROADCAST'),
|
360 |
+
args: this.descendInputOfBlock(block, 'ARGS')
|
361 |
+
};
|
362 |
+
|
363 |
+
case 'control_inline_stack_output':
|
364 |
+
return {
|
365 |
+
kind: 'control.inlineStackOutput',
|
366 |
+
code: this.descendSubstack(block, 'SUBSTACK')
|
367 |
+
};
|
368 |
+
|
369 |
+
case 'looks_backdropnumbername':
|
370 |
+
if (block.fields.NUMBER_NAME.value === 'number') {
|
371 |
+
return {
|
372 |
+
kind: 'looks.backdropNumber'
|
373 |
+
};
|
374 |
+
}
|
375 |
+
return {
|
376 |
+
kind: 'looks.backdropName'
|
377 |
+
};
|
378 |
+
case 'looks_costumenumbername':
|
379 |
+
if (block.fields.NUMBER_NAME.value === 'number') {
|
380 |
+
return {
|
381 |
+
kind: 'looks.costumeNumber'
|
382 |
+
};
|
383 |
+
}
|
384 |
+
return {
|
385 |
+
kind: 'looks.costumeName'
|
386 |
+
};
|
387 |
+
case 'looks_size':
|
388 |
+
return {
|
389 |
+
kind: 'looks.size'
|
390 |
+
};
|
391 |
+
case 'looks_tintColor':
|
392 |
+
return {
|
393 |
+
kind: 'looks.tintColor'
|
394 |
+
};
|
395 |
+
case 'motion_direction':
|
396 |
+
return {
|
397 |
+
kind: 'motion.direction'
|
398 |
+
};
|
399 |
+
case 'motion_xposition':
|
400 |
+
return {
|
401 |
+
kind: 'motion.x'
|
402 |
+
};
|
403 |
+
case 'motion_yposition':
|
404 |
+
return {
|
405 |
+
kind: 'motion.y'
|
406 |
+
};
|
407 |
+
|
408 |
+
case 'operator_add':
|
409 |
+
return {
|
410 |
+
kind: 'op.add',
|
411 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
412 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
413 |
+
};
|
414 |
+
case 'operator_and':
|
415 |
+
return {
|
416 |
+
kind: 'op.and',
|
417 |
+
left: this.descendInputOfBlock(block, 'OPERAND1'),
|
418 |
+
right: this.descendInputOfBlock(block, 'OPERAND2')
|
419 |
+
};
|
420 |
+
case 'operator_contains':
|
421 |
+
return {
|
422 |
+
kind: 'op.contains',
|
423 |
+
string: this.descendInputOfBlock(block, 'STRING1'),
|
424 |
+
contains: this.descendInputOfBlock(block, 'STRING2')
|
425 |
+
};
|
426 |
+
case 'operator_divide':
|
427 |
+
return {
|
428 |
+
kind: 'op.divide',
|
429 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
430 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
431 |
+
};
|
432 |
+
case 'operator_power':
|
433 |
+
return {
|
434 |
+
kind: 'op.power',
|
435 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
436 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
437 |
+
};
|
438 |
+
case 'operator_equals':
|
439 |
+
return {
|
440 |
+
kind: 'op.equals',
|
441 |
+
left: this.descendInputOfBlock(block, 'OPERAND1'),
|
442 |
+
right: this.descendInputOfBlock(block, 'OPERAND2')
|
443 |
+
};
|
444 |
+
case 'operator_gt':
|
445 |
+
return {
|
446 |
+
kind: 'op.greater',
|
447 |
+
left: this.descendInputOfBlock(block, 'OPERAND1'),
|
448 |
+
right: this.descendInputOfBlock(block, 'OPERAND2')
|
449 |
+
};
|
450 |
+
case 'operator_join':
|
451 |
+
return {
|
452 |
+
kind: 'op.join',
|
453 |
+
left: this.descendInputOfBlock(block, 'STRING1'),
|
454 |
+
right: this.descendInputOfBlock(block, 'STRING2')
|
455 |
+
};
|
456 |
+
case 'operator_length':
|
457 |
+
return {
|
458 |
+
kind: 'op.length',
|
459 |
+
string: this.descendInputOfBlock(block, 'STRING')
|
460 |
+
};
|
461 |
+
case 'operator_letter_of':
|
462 |
+
return {
|
463 |
+
kind: 'op.letterOf',
|
464 |
+
letter: this.descendInputOfBlock(block, 'LETTER'),
|
465 |
+
string: this.descendInputOfBlock(block, 'STRING')
|
466 |
+
};
|
467 |
+
case 'operator_lt':
|
468 |
+
return {
|
469 |
+
kind: 'op.less',
|
470 |
+
left: this.descendInputOfBlock(block, 'OPERAND1'),
|
471 |
+
right: this.descendInputOfBlock(block, 'OPERAND2')
|
472 |
+
};
|
473 |
+
case 'operator_mathop': {
|
474 |
+
const value = this.descendInputOfBlock(block, 'NUM');
|
475 |
+
const operator = block.fields.OPERATOR.value.toLowerCase();
|
476 |
+
switch (operator) {
|
477 |
+
case 'abs': return {
|
478 |
+
kind: 'op.abs',
|
479 |
+
value
|
480 |
+
};
|
481 |
+
case 'floor': return {
|
482 |
+
kind: 'op.floor',
|
483 |
+
value
|
484 |
+
};
|
485 |
+
case 'ceiling': return {
|
486 |
+
kind: 'op.ceiling',
|
487 |
+
value
|
488 |
+
};
|
489 |
+
case 'sign': return {
|
490 |
+
kind: 'op.sign',
|
491 |
+
value
|
492 |
+
};
|
493 |
+
case 'sqrt': return {
|
494 |
+
kind: 'op.sqrt',
|
495 |
+
value
|
496 |
+
};
|
497 |
+
case 'sin': return {
|
498 |
+
kind: 'op.sin',
|
499 |
+
value
|
500 |
+
};
|
501 |
+
case 'cos': return {
|
502 |
+
kind: 'op.cos',
|
503 |
+
value
|
504 |
+
};
|
505 |
+
case 'tan': return {
|
506 |
+
kind: 'op.tan',
|
507 |
+
value
|
508 |
+
};
|
509 |
+
case 'asin': return {
|
510 |
+
kind: 'op.asin',
|
511 |
+
value
|
512 |
+
};
|
513 |
+
case 'acos': return {
|
514 |
+
kind: 'op.acos',
|
515 |
+
value
|
516 |
+
};
|
517 |
+
case 'atan': return {
|
518 |
+
kind: 'op.atan',
|
519 |
+
value
|
520 |
+
};
|
521 |
+
case 'ln': return {
|
522 |
+
kind: 'op.ln',
|
523 |
+
value
|
524 |
+
};
|
525 |
+
case 'log': return {
|
526 |
+
kind: 'op.log',
|
527 |
+
value
|
528 |
+
};
|
529 |
+
case 'log2': return {
|
530 |
+
kind: 'op.log2',
|
531 |
+
value
|
532 |
+
};
|
533 |
+
case 'e ^': return {
|
534 |
+
kind: 'op.e^',
|
535 |
+
value
|
536 |
+
};
|
537 |
+
case '10 ^': return {
|
538 |
+
kind: 'op.10^',
|
539 |
+
value
|
540 |
+
};
|
541 |
+
default: return {
|
542 |
+
kind: 'constant',
|
543 |
+
value: 0
|
544 |
+
};
|
545 |
+
}
|
546 |
+
}
|
547 |
+
case 'operator_advlog':
|
548 |
+
return {
|
549 |
+
kind: 'op.advlog',
|
550 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
551 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
552 |
+
};
|
553 |
+
case 'operator_mod':
|
554 |
+
return {
|
555 |
+
kind: 'op.mod',
|
556 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
557 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
558 |
+
};
|
559 |
+
case 'operator_multiply':
|
560 |
+
return {
|
561 |
+
kind: 'op.multiply',
|
562 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
563 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
564 |
+
};
|
565 |
+
case 'operator_not':
|
566 |
+
return {
|
567 |
+
kind: 'op.not',
|
568 |
+
operand: this.descendInputOfBlock(block, 'OPERAND')
|
569 |
+
};
|
570 |
+
case 'operator_or':
|
571 |
+
return {
|
572 |
+
kind: 'op.or',
|
573 |
+
left: this.descendInputOfBlock(block, 'OPERAND1'),
|
574 |
+
right: this.descendInputOfBlock(block, 'OPERAND2')
|
575 |
+
};
|
576 |
+
case 'operator_random': {
|
577 |
+
const from = this.descendInputOfBlock(block, 'FROM');
|
578 |
+
const to = this.descendInputOfBlock(block, 'TO');
|
579 |
+
// If both values are known at compile time, we can do some optimizations.
|
580 |
+
// TODO: move optimizations to jsgen?
|
581 |
+
if (from.kind === 'constant' && to.kind === 'constant') {
|
582 |
+
const sFrom = from.value;
|
583 |
+
const sTo = to.value;
|
584 |
+
const nFrom = Cast.toNumber(sFrom);
|
585 |
+
const nTo = Cast.toNumber(sTo);
|
586 |
+
// If both numbers are the same, random is unnecessary.
|
587 |
+
// todo: this probably never happens so consider removing
|
588 |
+
if (nFrom === nTo) {
|
589 |
+
return {
|
590 |
+
kind: 'constant',
|
591 |
+
value: nFrom
|
592 |
+
};
|
593 |
+
}
|
594 |
+
// If both are ints, hint this to the compiler
|
595 |
+
if (Cast.isInt(sFrom) && Cast.isInt(sTo)) {
|
596 |
+
return {
|
597 |
+
kind: 'op.random',
|
598 |
+
low: nFrom <= nTo ? from : to,
|
599 |
+
high: nFrom <= nTo ? to : from,
|
600 |
+
useInts: true,
|
601 |
+
useFloats: false
|
602 |
+
};
|
603 |
+
}
|
604 |
+
// Otherwise hint that these are floats
|
605 |
+
return {
|
606 |
+
kind: 'op.random',
|
607 |
+
low: nFrom <= nTo ? from : to,
|
608 |
+
high: nFrom <= nTo ? to : from,
|
609 |
+
useInts: false,
|
610 |
+
useFloats: true
|
611 |
+
};
|
612 |
+
} else if (from.kind === 'constant') {
|
613 |
+
// If only one value is known at compile-time, we can still attempt some optimizations.
|
614 |
+
if (!Cast.isInt(Cast.toNumber(from.value))) {
|
615 |
+
return {
|
616 |
+
kind: 'op.random',
|
617 |
+
low: from,
|
618 |
+
high: to,
|
619 |
+
useInts: false,
|
620 |
+
useFloats: true
|
621 |
+
};
|
622 |
+
}
|
623 |
+
} else if (to.kind === 'constant') {
|
624 |
+
if (!Cast.isInt(Cast.toNumber(to.value))) {
|
625 |
+
return {
|
626 |
+
kind: 'op.random',
|
627 |
+
low: from,
|
628 |
+
high: to,
|
629 |
+
useInts: false,
|
630 |
+
useFloats: true
|
631 |
+
};
|
632 |
+
}
|
633 |
+
}
|
634 |
+
// No optimizations possible
|
635 |
+
return {
|
636 |
+
kind: 'op.random',
|
637 |
+
low: from,
|
638 |
+
high: to,
|
639 |
+
useInts: false,
|
640 |
+
useFloats: false
|
641 |
+
};
|
642 |
+
}
|
643 |
+
case 'operator_round':
|
644 |
+
return {
|
645 |
+
kind: 'op.round',
|
646 |
+
value: this.descendInputOfBlock(block, 'NUM')
|
647 |
+
};
|
648 |
+
case 'operator_subtract':
|
649 |
+
return {
|
650 |
+
kind: 'op.subtract',
|
651 |
+
left: this.descendInputOfBlock(block, 'NUM1'),
|
652 |
+
right: this.descendInputOfBlock(block, 'NUM2')
|
653 |
+
};
|
654 |
+
|
655 |
+
case 'sensing_answer':
|
656 |
+
return {
|
657 |
+
kind: 'sensing.answer'
|
658 |
+
};
|
659 |
+
case 'sensing_coloristouchingcolor':
|
660 |
+
return {
|
661 |
+
kind: 'sensing.colorTouchingColor',
|
662 |
+
target: this.descendInputOfBlock(block, 'COLOR2'),
|
663 |
+
mask: this.descendInputOfBlock(block, 'COLOR')
|
664 |
+
};
|
665 |
+
case 'sensing_current':
|
666 |
+
switch (block.fields.CURRENTMENU.value.toLowerCase()) {
|
667 |
+
case 'year':
|
668 |
+
return {
|
669 |
+
kind: 'sensing.year'
|
670 |
+
};
|
671 |
+
case 'month':
|
672 |
+
return {
|
673 |
+
kind: 'sensing.month'
|
674 |
+
};
|
675 |
+
case 'date':
|
676 |
+
return {
|
677 |
+
kind: 'sensing.date'
|
678 |
+
};
|
679 |
+
case 'dayofweek':
|
680 |
+
return {
|
681 |
+
kind: 'sensing.dayofweek'
|
682 |
+
};
|
683 |
+
case 'hour':
|
684 |
+
return {
|
685 |
+
kind: 'sensing.hour'
|
686 |
+
};
|
687 |
+
case 'minute':
|
688 |
+
return {
|
689 |
+
kind: 'sensing.minute'
|
690 |
+
};
|
691 |
+
case 'second':
|
692 |
+
return {
|
693 |
+
kind: 'sensing.second'
|
694 |
+
};
|
695 |
+
case 'timestamp':
|
696 |
+
return {
|
697 |
+
kind: 'sensing.timestamp'
|
698 |
+
};
|
699 |
+
}
|
700 |
+
|
701 |
+
return {
|
702 |
+
kind: 'constant',
|
703 |
+
value: 0
|
704 |
+
};
|
705 |
+
case 'sensing_dayssince2000':
|
706 |
+
return {
|
707 |
+
kind: 'sensing.daysSince2000'
|
708 |
+
};
|
709 |
+
case 'sensing_distanceto':
|
710 |
+
return {
|
711 |
+
kind: 'sensing.distance',
|
712 |
+
target: this.descendInputOfBlock(block, 'DISTANCETOMENU')
|
713 |
+
};
|
714 |
+
case 'sensing_keypressed':
|
715 |
+
return {
|
716 |
+
kind: 'keyboard.pressed',
|
717 |
+
key: this.descendInputOfBlock(block, 'KEY_OPTION')
|
718 |
+
};
|
719 |
+
case 'sensing_mousedown':
|
720 |
+
return {
|
721 |
+
kind: 'mouse.down'
|
722 |
+
};
|
723 |
+
case 'sensing_mousex':
|
724 |
+
return {
|
725 |
+
kind: 'mouse.x'
|
726 |
+
};
|
727 |
+
case 'sensing_mousey':
|
728 |
+
return {
|
729 |
+
kind: 'mouse.y'
|
730 |
+
};
|
731 |
+
case 'sensing_of':
|
732 |
+
return {
|
733 |
+
kind: 'sensing.of',
|
734 |
+
property: block.fields.PROPERTY.value,
|
735 |
+
object: this.descendInputOfBlock(block, 'OBJECT')
|
736 |
+
};
|
737 |
+
case 'sensing_timer':
|
738 |
+
this.usesTimer = true;
|
739 |
+
return {
|
740 |
+
kind: 'timer.get'
|
741 |
+
};
|
742 |
+
case 'sensing_touchingcolor':
|
743 |
+
return {
|
744 |
+
kind: 'sensing.touchingColor',
|
745 |
+
color: this.descendInputOfBlock(block, 'COLOR')
|
746 |
+
};
|
747 |
+
case 'sensing_touchingobject':
|
748 |
+
return {
|
749 |
+
kind: 'sensing.touching',
|
750 |
+
object: this.descendInputOfBlock(block, 'TOUCHINGOBJECTMENU')
|
751 |
+
};
|
752 |
+
case 'sensing_username':
|
753 |
+
return {
|
754 |
+
kind: 'sensing.username'
|
755 |
+
};
|
756 |
+
case 'sensing_loggedin':
|
757 |
+
return {
|
758 |
+
kind: 'sensing.loggedin'
|
759 |
+
};
|
760 |
+
case 'operator_trueBoolean':
|
761 |
+
return {
|
762 |
+
kind: 'op.true'
|
763 |
+
};
|
764 |
+
case 'operator_falseBoolean':
|
765 |
+
return {
|
766 |
+
kind: 'op.false'
|
767 |
+
};
|
768 |
+
case 'operator_randomBoolean':
|
769 |
+
return {
|
770 |
+
kind: 'op.randbool'
|
771 |
+
};
|
772 |
+
|
773 |
+
case 'sound_sounds_menu':
|
774 |
+
return {
|
775 |
+
kind: 'constant',
|
776 |
+
value: block.fields.SOUND_MENU.value
|
777 |
+
};
|
778 |
+
|
779 |
+
case 'lmsTempVars2_getRuntimeVariable':
|
780 |
+
return {
|
781 |
+
kind: 'tempVars.get',
|
782 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
783 |
+
runtime: true
|
784 |
+
};
|
785 |
+
case 'lmsTempVars2_getThreadVariable':
|
786 |
+
return {
|
787 |
+
kind: 'tempVars.get',
|
788 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
789 |
+
thread: true
|
790 |
+
};
|
791 |
+
case 'tempVars_getVariable':
|
792 |
+
return {
|
793 |
+
kind: 'tempVars.get',
|
794 |
+
var: this.descendInputOfBlock(block, 'name')
|
795 |
+
};
|
796 |
+
|
797 |
+
case 'lmsTempVars2_runtimeVariableExists':
|
798 |
+
return {
|
799 |
+
kind: 'tempVars.exists',
|
800 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
801 |
+
runtime: true
|
802 |
+
};
|
803 |
+
case 'lmsTempVars2_threadVariableExists':
|
804 |
+
return {
|
805 |
+
kind: 'tempVars.exists',
|
806 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
807 |
+
thread: true
|
808 |
+
};
|
809 |
+
case 'tempVars_variableExists':
|
810 |
+
// This menu is special compared to other menus -- it actually has an opcode function.
|
811 |
+
return {
|
812 |
+
kind: 'tempVars.exists',
|
813 |
+
var: this.descendInputOfBlock(block, 'name')
|
814 |
+
};
|
815 |
+
|
816 |
+
case 'lmsTempVars2_listRuntimeVariables':
|
817 |
+
return {
|
818 |
+
kind: 'tempVars.all',
|
819 |
+
runtime: true
|
820 |
+
};
|
821 |
+
case 'lmsTempVars2_listThreadVariables':
|
822 |
+
return {
|
823 |
+
kind: 'tempVars.all',
|
824 |
+
thread: true
|
825 |
+
};
|
826 |
+
case 'tempVars_allVariables':
|
827 |
+
return {
|
828 |
+
kind: 'tempVars.all'
|
829 |
+
};
|
830 |
+
|
831 |
+
// used by the stacked version of this block to run as an input block
|
832 |
+
// despite there being a stacked version
|
833 |
+
case 'procedures_call_return':
|
834 |
+
case 'procedures_call': {
|
835 |
+
// setting of yields will be handled later in the analysis phase
|
836 |
+
|
837 |
+
const procedureCode = block.mutation.proccode;
|
838 |
+
if (procedureCode === 'tw:debugger;') {
|
839 |
+
return {
|
840 |
+
kind: 'tw.debugger'
|
841 |
+
};
|
842 |
+
}
|
843 |
+
const paramNamesIdsAndDefaults = this.blocks.getProcedureParamNamesIdsAndDefaults(procedureCode);
|
844 |
+
if (paramNamesIdsAndDefaults === null) {
|
845 |
+
return {
|
846 |
+
kind: 'noop'
|
847 |
+
};
|
848 |
+
}
|
849 |
+
|
850 |
+
const [paramNames, paramIds, paramDefaults] = paramNamesIdsAndDefaults;
|
851 |
+
|
852 |
+
const addonBlock = this.runtime.getAddonBlock(procedureCode);
|
853 |
+
if (addonBlock) {
|
854 |
+
this.script.yields = true;
|
855 |
+
const args = {};
|
856 |
+
for (let i = 0; i < paramIds.length; i++) {
|
857 |
+
let value;
|
858 |
+
if (block.inputs[paramIds[i]] && block.inputs[paramIds[i]].block) {
|
859 |
+
value = this.descendInputOfBlock(block, paramIds[i]);
|
860 |
+
} else {
|
861 |
+
value = {
|
862 |
+
kind: 'constant',
|
863 |
+
value: paramDefaults[i]
|
864 |
+
};
|
865 |
+
}
|
866 |
+
args[paramNames[i]] = value;
|
867 |
+
}
|
868 |
+
return {
|
869 |
+
kind: 'addons.call',
|
870 |
+
code: procedureCode,
|
871 |
+
arguments: args,
|
872 |
+
blockId: block.id
|
873 |
+
};
|
874 |
+
}
|
875 |
+
|
876 |
+
const definitionId = this.blocks.getProcedureDefinition(procedureCode);
|
877 |
+
const definitionBlock = this.blocks.getBlock(definitionId);
|
878 |
+
if (!definitionBlock) {
|
879 |
+
return {
|
880 |
+
kind: 'noop'
|
881 |
+
};
|
882 |
+
}
|
883 |
+
const innerDefinition = this.blocks.getBlock(definitionBlock.inputs.custom_block.block);
|
884 |
+
|
885 |
+
let isWarp = this.script.isWarp;
|
886 |
+
if (!isWarp) {
|
887 |
+
if (innerDefinition && innerDefinition.mutation) {
|
888 |
+
const warp = innerDefinition.mutation.warp;
|
889 |
+
if (typeof warp === 'boolean') {
|
890 |
+
isWarp = warp;
|
891 |
+
} else if (typeof warp === 'string') {
|
892 |
+
isWarp = JSON.parse(warp);
|
893 |
+
}
|
894 |
+
}
|
895 |
+
}
|
896 |
+
|
897 |
+
const variant = generateProcedureVariant(procedureCode, isWarp);
|
898 |
+
|
899 |
+
if (!this.script.dependedProcedures.includes(variant)) {
|
900 |
+
this.script.dependedProcedures.push(variant);
|
901 |
+
}
|
902 |
+
|
903 |
+
// Non-warp direct recursion yields.
|
904 |
+
if (!this.script.isWarp) {
|
905 |
+
if (procedureCode === this.script.procedureCode) {
|
906 |
+
this.script.yields = true;
|
907 |
+
}
|
908 |
+
}
|
909 |
+
|
910 |
+
const args = [];
|
911 |
+
for (let i = 0; i < paramIds.length; i++) {
|
912 |
+
let value;
|
913 |
+
if (block.inputs[paramIds[i]] && block.inputs[paramIds[i]].block) {
|
914 |
+
if (paramIds[i].startsWith("SUBSTACK")) {
|
915 |
+
value = this.descendSubstack(block, paramIds[i])
|
916 |
+
} else {
|
917 |
+
value = this.descendInputOfBlock(block, paramIds[i]);
|
918 |
+
}
|
919 |
+
} else {
|
920 |
+
value = {
|
921 |
+
kind: 'constant',
|
922 |
+
value: paramDefaults[i]
|
923 |
+
};
|
924 |
+
}
|
925 |
+
args.push(value);
|
926 |
+
}
|
927 |
+
|
928 |
+
return {
|
929 |
+
kind: 'procedures.call',
|
930 |
+
code: procedureCode,
|
931 |
+
variant,
|
932 |
+
returns: true,
|
933 |
+
arguments: args,
|
934 |
+
type: JSON.parse(block.mutation.opType || '"string"')
|
935 |
+
};
|
936 |
+
}
|
937 |
+
|
938 |
+
case 'tw_getLastKeyPressed':
|
939 |
+
return {
|
940 |
+
kind: 'tw.lastKeyPressed'
|
941 |
+
};
|
942 |
+
|
943 |
+
case 'control_dualblock':
|
944 |
+
return {
|
945 |
+
kind: 'control.dualBlock'
|
946 |
+
};
|
947 |
+
|
948 |
+
default: {
|
949 |
+
const opcodeFunction = this.runtime.getOpcodeFunction(block.opcode);
|
950 |
+
if (opcodeFunction) {
|
951 |
+
// It might be a non-compiled primitive from a standard category
|
952 |
+
if (compatBlocks.outputBlocks.includes(block.opcode)) {
|
953 |
+
return this.descendCompatLayer(block);
|
954 |
+
}
|
955 |
+
// It might be an extension block.
|
956 |
+
const blockInfo = this.getBlockInfo(block.opcode);
|
957 |
+
if (blockInfo) {
|
958 |
+
const type = blockInfo.info.blockType;
|
959 |
+
const args = this.descendCompatLayer(block);
|
960 |
+
args.block = block;
|
961 |
+
if (block.mutation) args.mutation = block.mutation;
|
962 |
+
if (type === BlockType.REPORTER || type === BlockType.BOOLEAN) {
|
963 |
+
return args;
|
964 |
+
}
|
965 |
+
}
|
966 |
+
}
|
967 |
+
|
968 |
+
// It might be a menu.
|
969 |
+
const inputs = Object.keys(block.inputs);
|
970 |
+
const fields = Object.keys(block.fields);
|
971 |
+
if (inputs.length === 0 && fields.length === 1) {
|
972 |
+
return {
|
973 |
+
kind: 'constant',
|
974 |
+
value: block.fields[fields[0]].value
|
975 |
+
};
|
976 |
+
}
|
977 |
+
|
978 |
+
log.warn(`IR: Unknown input: ${block.opcode}`, block);
|
979 |
+
throw new Error(`IR: Unknown input: ${block.opcode}`);
|
980 |
+
}
|
981 |
+
}
|
982 |
+
}
|
983 |
+
|
984 |
+
/**
|
985 |
+
* Descend into a stacked block. (eg. "move ( ) steps")
|
986 |
+
* @param {*} block The Scratch block to parse.
|
987 |
+
* @private
|
988 |
+
* @returns {Node} Compiled node for this block.
|
989 |
+
*/
|
990 |
+
descendStackedBlock (block) {
|
991 |
+
// check if we have extension ir for this opcode
|
992 |
+
const extensionId = String(block.opcode).split('_')[0];
|
993 |
+
const blockId = String(block.opcode).replace(extensionId + '_', '');
|
994 |
+
if (IRGenerator.hasExtensionIr(extensionId) && IRGenerator.getExtensionIr(extensionId)[blockId]) {
|
995 |
+
// this is an extension block that wants to be compiled
|
996 |
+
const irFunc = IRGenerator.getExtensionIr(extensionId)[blockId];
|
997 |
+
let irData = null;
|
998 |
+
// make sure irFunc isnt broken
|
999 |
+
try {
|
1000 |
+
irData = irFunc(this, block);
|
1001 |
+
} catch (err) {
|
1002 |
+
log.warn(extensionId + '_' + blockId, 'failed to create IR data;', err);
|
1003 |
+
}
|
1004 |
+
if (irData) {
|
1005 |
+
// check if it is this type, we dont want to descend an input as a stack
|
1006 |
+
if (irData.kind === 'stack') {
|
1007 |
+
// set proper kind
|
1008 |
+
irData.kind = extensionId + '.' + blockId;
|
1009 |
+
return irData;
|
1010 |
+
}
|
1011 |
+
}
|
1012 |
+
}
|
1013 |
+
|
1014 |
+
switch (block.opcode) {
|
1015 |
+
case 'your_mom':
|
1016 |
+
return {
|
1017 |
+
kind: 'your mom'
|
1018 |
+
};
|
1019 |
+
case 'control_switch':
|
1020 |
+
return {
|
1021 |
+
kind: 'control.switch',
|
1022 |
+
test: this.descendInputOfBlock(block, 'CONDITION'),
|
1023 |
+
conditions: this.descendSubstack(block, 'SUBSTACK'),
|
1024 |
+
default: []
|
1025 |
+
};
|
1026 |
+
case 'control_switch_default':
|
1027 |
+
return {
|
1028 |
+
kind: 'control.switch',
|
1029 |
+
test: this.descendInputOfBlock(block, 'CONDITION'),
|
1030 |
+
conditions: this.descendSubstack(block, 'SUBSTACK1'),
|
1031 |
+
default: this.descendSubstack(block, 'SUBSTACK2')
|
1032 |
+
};
|
1033 |
+
case 'control_case_next':
|
1034 |
+
return {
|
1035 |
+
kind: 'control.case',
|
1036 |
+
condition: this.descendInputOfBlock(block, 'CONDITION'),
|
1037 |
+
code: this.descendSubstack(block, 'SUBSTACK'),
|
1038 |
+
runsNext: true
|
1039 |
+
};
|
1040 |
+
case 'control_case':
|
1041 |
+
return {
|
1042 |
+
kind: 'control.case',
|
1043 |
+
condition: this.descendInputOfBlock(block, 'CONDITION'),
|
1044 |
+
code: this.descendSubstack(block, 'SUBSTACK'),
|
1045 |
+
runsNext: false
|
1046 |
+
};
|
1047 |
+
case 'control_exitCase':
|
1048 |
+
return {
|
1049 |
+
kind: 'control.exitCase'
|
1050 |
+
};
|
1051 |
+
case 'control_exitLoop':
|
1052 |
+
return {
|
1053 |
+
kind: 'control.exitLoop'
|
1054 |
+
};
|
1055 |
+
case 'control_continueLoop':
|
1056 |
+
return {
|
1057 |
+
kind: 'control.continueLoop'
|
1058 |
+
};
|
1059 |
+
case 'control_all_at_once':
|
1060 |
+
// In Scratch 3, this block behaves like "if 1 = 1"
|
1061 |
+
// WE ARE IN PM NOW IT BEHAVES PROPERLY LESS GO
|
1062 |
+
return {
|
1063 |
+
kind: 'control.allAtOnce',
|
1064 |
+
condition: {
|
1065 |
+
kind: 'constant',
|
1066 |
+
value: true
|
1067 |
+
},
|
1068 |
+
code: this.descendSubstack(block, 'SUBSTACK')
|
1069 |
+
};
|
1070 |
+
case 'control_clear_counter':
|
1071 |
+
return {
|
1072 |
+
kind: 'counter.clear'
|
1073 |
+
};
|
1074 |
+
case 'control_create_clone_of':
|
1075 |
+
return {
|
1076 |
+
kind: 'control.createClone',
|
1077 |
+
target: this.descendInputOfBlock(block, 'CLONE_OPTION')
|
1078 |
+
};
|
1079 |
+
case 'control_delete_this_clone':
|
1080 |
+
this.script.yields = true;
|
1081 |
+
return {
|
1082 |
+
kind: 'control.deleteClone'
|
1083 |
+
};
|
1084 |
+
case 'control_forever':
|
1085 |
+
this.analyzeLoop();
|
1086 |
+
return {
|
1087 |
+
kind: 'control.while',
|
1088 |
+
condition: {
|
1089 |
+
kind: 'constant',
|
1090 |
+
value: true
|
1091 |
+
},
|
1092 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1093 |
+
};
|
1094 |
+
case 'control_for_each':
|
1095 |
+
this.analyzeLoop();
|
1096 |
+
return {
|
1097 |
+
kind: 'control.for',
|
1098 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE),
|
1099 |
+
count: this.descendInputOfBlock(block, 'VALUE'),
|
1100 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1101 |
+
};
|
1102 |
+
case 'control_if':
|
1103 |
+
return {
|
1104 |
+
kind: 'control.if',
|
1105 |
+
condition: this.descendInputOfBlock(block, 'CONDITION'),
|
1106 |
+
whenTrue: this.descendSubstack(block, 'SUBSTACK'),
|
1107 |
+
whenFalse: []
|
1108 |
+
};
|
1109 |
+
case 'control_if_else':
|
1110 |
+
return {
|
1111 |
+
kind: 'control.if',
|
1112 |
+
condition: this.descendInputOfBlock(block, 'CONDITION'),
|
1113 |
+
whenTrue: this.descendSubstack(block, 'SUBSTACK'),
|
1114 |
+
whenFalse: this.descendSubstack(block, 'SUBSTACK2')
|
1115 |
+
};
|
1116 |
+
case 'control_try_catch':
|
1117 |
+
return {
|
1118 |
+
kind: 'control.trycatch',
|
1119 |
+
try: this.descendSubstack(block, 'SUBSTACK'),
|
1120 |
+
catch: this.descendSubstack(block, 'SUBSTACK2')
|
1121 |
+
};
|
1122 |
+
case 'control_throw_error':
|
1123 |
+
return {
|
1124 |
+
kind: 'control.throwError',
|
1125 |
+
error: this.descendInputOfBlock(block, 'ERROR'),
|
1126 |
+
};
|
1127 |
+
case 'control_incr_counter':
|
1128 |
+
return {
|
1129 |
+
kind: 'counter.increment'
|
1130 |
+
};
|
1131 |
+
case 'control_decr_counter':
|
1132 |
+
return {
|
1133 |
+
kind: 'counter.decrement'
|
1134 |
+
};
|
1135 |
+
case 'control_set_counter':
|
1136 |
+
return {
|
1137 |
+
kind: 'counter.set',
|
1138 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1139 |
+
};
|
1140 |
+
case 'control_repeat':
|
1141 |
+
this.analyzeLoop();
|
1142 |
+
return {
|
1143 |
+
kind: 'control.repeat',
|
1144 |
+
times: this.descendInputOfBlock(block, 'TIMES'),
|
1145 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1146 |
+
};
|
1147 |
+
case 'control_repeatForSeconds':
|
1148 |
+
this.analyzeLoop();
|
1149 |
+
return {
|
1150 |
+
kind: 'control.repeatForSeconds',
|
1151 |
+
times: this.descendInputOfBlock(block, 'TIMES'),
|
1152 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1153 |
+
};
|
1154 |
+
case 'control_repeat_until': {
|
1155 |
+
this.analyzeLoop();
|
1156 |
+
// Dirty hack: automatically enable warp timer for this block if it uses timer
|
1157 |
+
// This fixes project that do things like "repeat until timer > 0.5"
|
1158 |
+
this.usesTimer = false;
|
1159 |
+
const condition = this.descendInputOfBlock(block, 'CONDITION');
|
1160 |
+
const needsWarpTimer = this.usesTimer;
|
1161 |
+
if (needsWarpTimer) {
|
1162 |
+
this.script.yields = true;
|
1163 |
+
}
|
1164 |
+
return {
|
1165 |
+
kind: 'control.while',
|
1166 |
+
condition: {
|
1167 |
+
kind: 'op.not',
|
1168 |
+
operand: condition
|
1169 |
+
},
|
1170 |
+
do: this.descendSubstack(block, 'SUBSTACK'),
|
1171 |
+
warpTimer: needsWarpTimer
|
1172 |
+
};
|
1173 |
+
}
|
1174 |
+
case 'control_stop': {
|
1175 |
+
const level = block.fields.STOP_OPTION.value;
|
1176 |
+
if (level === 'all') {
|
1177 |
+
this.script.yields = true;
|
1178 |
+
return {
|
1179 |
+
kind: 'control.stopAll'
|
1180 |
+
};
|
1181 |
+
} else if (level === 'other scripts in sprite' || level === 'other scripts in stage') {
|
1182 |
+
return {
|
1183 |
+
kind: 'control.stopOthers'
|
1184 |
+
};
|
1185 |
+
} else if (level === 'this script') {
|
1186 |
+
return {
|
1187 |
+
kind: 'control.stopScript'
|
1188 |
+
};
|
1189 |
+
}
|
1190 |
+
return {
|
1191 |
+
kind: 'noop'
|
1192 |
+
};
|
1193 |
+
}
|
1194 |
+
case 'control_wait':
|
1195 |
+
this.script.yields = true;
|
1196 |
+
return {
|
1197 |
+
kind: 'control.wait',
|
1198 |
+
seconds: this.descendInputOfBlock(block, 'DURATION')
|
1199 |
+
};
|
1200 |
+
case 'control_waittick':
|
1201 |
+
this.script.yields = true;
|
1202 |
+
return {
|
1203 |
+
kind: 'control.waitTick'
|
1204 |
+
};
|
1205 |
+
case 'control_wait_until':
|
1206 |
+
this.script.yields = true;
|
1207 |
+
return {
|
1208 |
+
kind: 'control.waitUntil',
|
1209 |
+
condition: this.descendInputOfBlock(block, 'CONDITION')
|
1210 |
+
};
|
1211 |
+
case 'control_waitsecondsoruntil':
|
1212 |
+
this.script.yields = true;
|
1213 |
+
return {
|
1214 |
+
kind: 'control.waitOrUntil',
|
1215 |
+
seconds: this.descendInputOfBlock(block, 'DURATION'),
|
1216 |
+
condition: this.descendInputOfBlock(block, 'CONDITION')
|
1217 |
+
};
|
1218 |
+
case 'control_while':
|
1219 |
+
this.analyzeLoop();
|
1220 |
+
return {
|
1221 |
+
kind: 'control.while',
|
1222 |
+
condition: this.descendInputOfBlock(block, 'CONDITION'),
|
1223 |
+
do: this.descendSubstack(block, 'SUBSTACK'),
|
1224 |
+
// We should consider analyzing this like we do for control_repeat_until
|
1225 |
+
warpTimer: false
|
1226 |
+
};
|
1227 |
+
case 'control_run_as_sprite':
|
1228 |
+
return {
|
1229 |
+
kind: 'control.runAsSprite',
|
1230 |
+
sprite: this.descendInputOfBlock(block, 'RUN_AS_OPTION'),
|
1231 |
+
substack: this.descendSubstack(block, 'SUBSTACK')
|
1232 |
+
};
|
1233 |
+
case 'control_new_script':
|
1234 |
+
return {
|
1235 |
+
kind: 'control.newScript',
|
1236 |
+
substack: this.descendSubstack(block, 'SUBSTACK')
|
1237 |
+
};
|
1238 |
+
case 'data_addtolist':
|
1239 |
+
return {
|
1240 |
+
kind: 'list.add',
|
1241 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1242 |
+
item: this.descendInputOfBlock(block, 'ITEM')
|
1243 |
+
};
|
1244 |
+
case 'data_changevariableby': {
|
1245 |
+
const variable = this.descendVariable(block, 'VARIABLE', SCALAR_TYPE);
|
1246 |
+
return {
|
1247 |
+
kind: 'var.set',
|
1248 |
+
variable,
|
1249 |
+
value: {
|
1250 |
+
kind: 'op.add',
|
1251 |
+
left: {
|
1252 |
+
kind: 'var.get',
|
1253 |
+
variable
|
1254 |
+
},
|
1255 |
+
right: this.descendInputOfBlock(block, 'VALUE')
|
1256 |
+
}
|
1257 |
+
};
|
1258 |
+
}
|
1259 |
+
case 'data_deletealloflist':
|
1260 |
+
return {
|
1261 |
+
kind: 'list.deleteAll',
|
1262 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
1263 |
+
};
|
1264 |
+
case 'data_listforeachnum':
|
1265 |
+
this.analyzeLoop();
|
1266 |
+
return {
|
1267 |
+
kind: 'list.forEach',
|
1268 |
+
num: true,
|
1269 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1270 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE),
|
1271 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1272 |
+
};
|
1273 |
+
case 'data_listforeachitem':
|
1274 |
+
this.analyzeLoop();
|
1275 |
+
return {
|
1276 |
+
kind: 'list.forEach',
|
1277 |
+
num: false,
|
1278 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1279 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE),
|
1280 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1281 |
+
};
|
1282 |
+
case 'data_deleteoflist': {
|
1283 |
+
const index = this.descendInputOfBlock(block, 'INDEX');
|
1284 |
+
if (index.kind === 'constant' && index.value === 'all') {
|
1285 |
+
return {
|
1286 |
+
kind: 'list.deleteAll',
|
1287 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
1288 |
+
};
|
1289 |
+
}
|
1290 |
+
return {
|
1291 |
+
kind: 'list.delete',
|
1292 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1293 |
+
index: index
|
1294 |
+
};
|
1295 |
+
}
|
1296 |
+
case 'data_shiftlist': {
|
1297 |
+
return {
|
1298 |
+
kind: 'list.shift',
|
1299 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1300 |
+
index: this.descendInputOfBlock(block, 'INDEX')
|
1301 |
+
};
|
1302 |
+
}
|
1303 |
+
case 'data_hidelist':
|
1304 |
+
return {
|
1305 |
+
kind: 'list.hide',
|
1306 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
1307 |
+
};
|
1308 |
+
case 'data_hidevariable':
|
1309 |
+
return {
|
1310 |
+
kind: 'var.hide',
|
1311 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE)
|
1312 |
+
};
|
1313 |
+
case 'data_insertatlist':
|
1314 |
+
return {
|
1315 |
+
kind: 'list.insert',
|
1316 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1317 |
+
index: this.descendInputOfBlock(block, 'INDEX'),
|
1318 |
+
item: this.descendInputOfBlock(block, 'ITEM')
|
1319 |
+
};
|
1320 |
+
case 'data_replaceitemoflist':
|
1321 |
+
return {
|
1322 |
+
kind: 'list.replace',
|
1323 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1324 |
+
index: this.descendInputOfBlock(block, 'INDEX'),
|
1325 |
+
item: this.descendInputOfBlock(block, 'ITEM')
|
1326 |
+
};
|
1327 |
+
case 'data_setvariableto':
|
1328 |
+
return {
|
1329 |
+
kind: 'var.set',
|
1330 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE),
|
1331 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1332 |
+
};
|
1333 |
+
case 'data_showlist':
|
1334 |
+
return {
|
1335 |
+
kind: 'list.show',
|
1336 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE)
|
1337 |
+
};
|
1338 |
+
case 'data_showvariable':
|
1339 |
+
return {
|
1340 |
+
kind: 'var.show',
|
1341 |
+
variable: this.descendVariable(block, 'VARIABLE', SCALAR_TYPE)
|
1342 |
+
};
|
1343 |
+
case 'data_filterlist':
|
1344 |
+
return {
|
1345 |
+
kind: 'list.filter',
|
1346 |
+
list: this.descendVariable(block, 'LIST', LIST_TYPE),
|
1347 |
+
bool: this.descendInputOfBlock(block, 'BOOL')
|
1348 |
+
};
|
1349 |
+
|
1350 |
+
case 'event_broadcast':
|
1351 |
+
return {
|
1352 |
+
kind: 'event.broadcast',
|
1353 |
+
broadcast: this.descendInputOfBlock(block, 'BROADCAST_INPUT')
|
1354 |
+
};
|
1355 |
+
case 'event_broadcastandwait':
|
1356 |
+
this.script.yields = true;
|
1357 |
+
return {
|
1358 |
+
kind: 'event.broadcastAndWait',
|
1359 |
+
broadcast: this.descendInputOfBlock(block, 'BROADCAST_INPUT')
|
1360 |
+
};
|
1361 |
+
|
1362 |
+
case 'looks_changeeffectby':
|
1363 |
+
return {
|
1364 |
+
kind: 'looks.changeEffect',
|
1365 |
+
effect: block.fields.EFFECT.value.toLowerCase(),
|
1366 |
+
value: this.descendInputOfBlock(block, 'CHANGE')
|
1367 |
+
};
|
1368 |
+
case 'looks_changesizeby':
|
1369 |
+
return {
|
1370 |
+
kind: 'looks.changeSize',
|
1371 |
+
size: this.descendInputOfBlock(block, 'CHANGE')
|
1372 |
+
};
|
1373 |
+
case 'looks_cleargraphiceffects':
|
1374 |
+
return {
|
1375 |
+
kind: 'looks.clearEffects'
|
1376 |
+
};
|
1377 |
+
case 'looks_goforwardbackwardlayers':
|
1378 |
+
if (block.fields.FORWARD_BACKWARD.value === 'forward') {
|
1379 |
+
return {
|
1380 |
+
kind: 'looks.forwardLayers',
|
1381 |
+
layers: this.descendInputOfBlock(block, 'NUM')
|
1382 |
+
};
|
1383 |
+
}
|
1384 |
+
return {
|
1385 |
+
kind: 'looks.backwardLayers',
|
1386 |
+
layers: this.descendInputOfBlock(block, 'NUM')
|
1387 |
+
};
|
1388 |
+
case 'looks_goTargetLayer':
|
1389 |
+
if (block.fields.FORWARD_BACKWARD.value === 'infront') {
|
1390 |
+
return {
|
1391 |
+
kind: 'looks.targetFront',
|
1392 |
+
layers: this.descendInputOfBlock(block, 'VISIBLE_OPTION')
|
1393 |
+
};
|
1394 |
+
}
|
1395 |
+
return {
|
1396 |
+
kind: 'looks.targetBack',
|
1397 |
+
layers: this.descendInputOfBlock(block, 'VISIBLE_OPTION')
|
1398 |
+
};
|
1399 |
+
case 'looks_gotofrontback':
|
1400 |
+
if (block.fields.FRONT_BACK.value === 'front') {
|
1401 |
+
return {
|
1402 |
+
kind: 'looks.goToFront'
|
1403 |
+
};
|
1404 |
+
}
|
1405 |
+
return {
|
1406 |
+
kind: 'looks.goToBack'
|
1407 |
+
};
|
1408 |
+
case 'looks_hide':
|
1409 |
+
return {
|
1410 |
+
kind: 'looks.hide'
|
1411 |
+
};
|
1412 |
+
case 'looks_nextbackdrop':
|
1413 |
+
return {
|
1414 |
+
kind: 'looks.nextBackdrop'
|
1415 |
+
};
|
1416 |
+
case 'looks_nextcostume':
|
1417 |
+
return {
|
1418 |
+
kind: 'looks.nextCostume'
|
1419 |
+
};
|
1420 |
+
case 'looks_seteffectto':
|
1421 |
+
return {
|
1422 |
+
kind: 'looks.setEffect',
|
1423 |
+
effect: block.fields.EFFECT.value.toLowerCase(),
|
1424 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1425 |
+
};
|
1426 |
+
case 'looks_setsizeto':
|
1427 |
+
return {
|
1428 |
+
kind: 'looks.setSize',
|
1429 |
+
size: this.descendInputOfBlock(block, 'SIZE')
|
1430 |
+
};
|
1431 |
+
case "looks_setFont":
|
1432 |
+
return {
|
1433 |
+
kind: 'looks.setFont',
|
1434 |
+
font: this.descendInputOfBlock(block, 'font'),
|
1435 |
+
size: this.descendInputOfBlock(block, 'size')
|
1436 |
+
};
|
1437 |
+
case "looks_setColor":
|
1438 |
+
return {
|
1439 |
+
kind: 'looks.setColor',
|
1440 |
+
prop: block.fields.prop.value,
|
1441 |
+
color: this.descendInputOfBlock(block, 'color')
|
1442 |
+
};
|
1443 |
+
case "looks_setTintColor":
|
1444 |
+
return {
|
1445 |
+
kind: 'looks.setTintColor',
|
1446 |
+
color: this.descendInputOfBlock(block, 'color')
|
1447 |
+
};
|
1448 |
+
case "looks_setShape":
|
1449 |
+
return {
|
1450 |
+
kind: 'looks.setShape',
|
1451 |
+
prop: block.fields.prop.value,
|
1452 |
+
value: this.descendInputOfBlock(block, 'color')
|
1453 |
+
};
|
1454 |
+
case 'looks_show':
|
1455 |
+
return {
|
1456 |
+
kind: 'looks.show'
|
1457 |
+
};
|
1458 |
+
case 'looks_switchbackdropto':
|
1459 |
+
return {
|
1460 |
+
kind: 'looks.switchBackdrop',
|
1461 |
+
backdrop: this.descendInputOfBlock(block, 'BACKDROP')
|
1462 |
+
};
|
1463 |
+
case 'looks_switchcostumeto':
|
1464 |
+
return {
|
1465 |
+
kind: 'looks.switchCostume',
|
1466 |
+
costume: this.descendInputOfBlock(block, 'COSTUME')
|
1467 |
+
};
|
1468 |
+
|
1469 |
+
case 'motion_changexby':
|
1470 |
+
return {
|
1471 |
+
kind: 'motion.changeX',
|
1472 |
+
dx: this.descendInputOfBlock(block, 'DX')
|
1473 |
+
};
|
1474 |
+
case 'motion_changeyby':
|
1475 |
+
return {
|
1476 |
+
kind: 'motion.changeY',
|
1477 |
+
dy: this.descendInputOfBlock(block, 'DY')
|
1478 |
+
};
|
1479 |
+
case 'motion_gotoxy':
|
1480 |
+
return {
|
1481 |
+
kind: 'motion.setXY',
|
1482 |
+
x: this.descendInputOfBlock(block, 'X'),
|
1483 |
+
y: this.descendInputOfBlock(block, 'Y')
|
1484 |
+
};
|
1485 |
+
case 'motion_ifonedgebounce':
|
1486 |
+
return {
|
1487 |
+
kind: 'motion.ifOnEdgeBounce'
|
1488 |
+
};
|
1489 |
+
case 'motion_movesteps':
|
1490 |
+
return {
|
1491 |
+
kind: 'motion.step',
|
1492 |
+
steps: this.descendInputOfBlock(block, 'STEPS')
|
1493 |
+
};
|
1494 |
+
case 'motion_pointindirection':
|
1495 |
+
return {
|
1496 |
+
kind: 'motion.setDirection',
|
1497 |
+
direction: this.descendInputOfBlock(block, 'DIRECTION')
|
1498 |
+
};
|
1499 |
+
case 'motion_setrotationstyle':
|
1500 |
+
return {
|
1501 |
+
kind: 'motion.setRotationStyle',
|
1502 |
+
style: block.fields.STYLE.value
|
1503 |
+
};
|
1504 |
+
case 'motion_setx':
|
1505 |
+
return {
|
1506 |
+
kind: 'motion.setX',
|
1507 |
+
x: this.descendInputOfBlock(block, 'X')
|
1508 |
+
};
|
1509 |
+
case 'motion_sety':
|
1510 |
+
return {
|
1511 |
+
kind: 'motion.setY',
|
1512 |
+
y: this.descendInputOfBlock(block, 'Y')
|
1513 |
+
};
|
1514 |
+
case 'motion_turnleft':
|
1515 |
+
return {
|
1516 |
+
kind: 'motion.setDirection',
|
1517 |
+
direction: {
|
1518 |
+
kind: 'op.subtract',
|
1519 |
+
left: {
|
1520 |
+
kind: 'motion.direction'
|
1521 |
+
},
|
1522 |
+
right: this.descendInputOfBlock(block, 'DEGREES')
|
1523 |
+
}
|
1524 |
+
};
|
1525 |
+
case 'motion_turnright':
|
1526 |
+
return {
|
1527 |
+
kind: 'motion.setDirection',
|
1528 |
+
direction: {
|
1529 |
+
kind: 'op.add',
|
1530 |
+
left: {
|
1531 |
+
kind: 'motion.direction'
|
1532 |
+
},
|
1533 |
+
right: this.descendInputOfBlock(block, 'DEGREES')
|
1534 |
+
}
|
1535 |
+
};
|
1536 |
+
|
1537 |
+
case 'pen_clear':
|
1538 |
+
return {
|
1539 |
+
kind: 'pen.clear'
|
1540 |
+
};
|
1541 |
+
case 'pen_changePenColorParamBy':
|
1542 |
+
return {
|
1543 |
+
kind: 'pen.changeParam',
|
1544 |
+
param: this.descendInputOfBlock(block, 'COLOR_PARAM'),
|
1545 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1546 |
+
};
|
1547 |
+
case 'pen_changePenHueBy':
|
1548 |
+
return {
|
1549 |
+
kind: 'pen.legacyChangeHue',
|
1550 |
+
hue: this.descendInputOfBlock(block, 'HUE')
|
1551 |
+
};
|
1552 |
+
case 'pen_changePenShadeBy':
|
1553 |
+
return {
|
1554 |
+
kind: 'pen.legacyChangeShade',
|
1555 |
+
shade: this.descendInputOfBlock(block, 'SHADE')
|
1556 |
+
};
|
1557 |
+
case 'pen_penDown':
|
1558 |
+
return {
|
1559 |
+
kind: 'pen.down'
|
1560 |
+
};
|
1561 |
+
case 'pen_penUp':
|
1562 |
+
return {
|
1563 |
+
kind: 'pen.up'
|
1564 |
+
};
|
1565 |
+
case 'pen_setPenColorParamTo':
|
1566 |
+
return {
|
1567 |
+
kind: 'pen.setParam',
|
1568 |
+
param: this.descendInputOfBlock(block, 'COLOR_PARAM'),
|
1569 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1570 |
+
};
|
1571 |
+
case 'pen_setPenColorToColor':
|
1572 |
+
return {
|
1573 |
+
kind: 'pen.setColor',
|
1574 |
+
color: this.descendInputOfBlock(block, 'COLOR')
|
1575 |
+
};
|
1576 |
+
case 'pen_setPenHueToNumber':
|
1577 |
+
return {
|
1578 |
+
kind: 'pen.legacySetHue',
|
1579 |
+
hue: this.descendInputOfBlock(block, 'HUE')
|
1580 |
+
};
|
1581 |
+
case 'pen_setPenShadeToNumber':
|
1582 |
+
return {
|
1583 |
+
kind: 'pen.legacySetShade',
|
1584 |
+
shade: this.descendInputOfBlock(block, 'SHADE')
|
1585 |
+
};
|
1586 |
+
case 'pen_setPenSizeTo':
|
1587 |
+
return {
|
1588 |
+
kind: 'pen.setSize',
|
1589 |
+
size: this.descendInputOfBlock(block, 'SIZE')
|
1590 |
+
};
|
1591 |
+
case 'pen_changePenSizeBy':
|
1592 |
+
return {
|
1593 |
+
kind: 'pen.changeSize',
|
1594 |
+
size: this.descendInputOfBlock(block, 'SIZE')
|
1595 |
+
};
|
1596 |
+
case 'pen_stamp':
|
1597 |
+
return {
|
1598 |
+
kind: 'pen.stamp'
|
1599 |
+
};
|
1600 |
+
case 'procedures_return':
|
1601 |
+
return {
|
1602 |
+
kind: 'procedures.return',
|
1603 |
+
return: this.descendInputOfBlock(block, 'return')
|
1604 |
+
};
|
1605 |
+
case 'procedures_set':
|
1606 |
+
return {
|
1607 |
+
kind: 'procedures.set',
|
1608 |
+
param: this.descendInputOfBlock(block, "PARAM"),
|
1609 |
+
val: this.descendInputOfBlock(block, "VALUE")
|
1610 |
+
};
|
1611 |
+
case 'procedures_call': {
|
1612 |
+
// setting of yields will be handled later in the analysis phase
|
1613 |
+
// patches output previewing
|
1614 |
+
if (block.mutation.returns === 'true') {
|
1615 |
+
const Block = Clone.simple(block);
|
1616 |
+
Block.opcode = 'procedures_call_return';
|
1617 |
+
return this.descendStackedBlock(Block);
|
1618 |
+
}
|
1619 |
+
|
1620 |
+
const procedureCode = block.mutation.proccode;
|
1621 |
+
if (procedureCode === 'tw:debugger;') {
|
1622 |
+
return {
|
1623 |
+
kind: 'tw.debugger'
|
1624 |
+
};
|
1625 |
+
}
|
1626 |
+
const paramNamesIdsAndDefaults = this.blocks.getProcedureParamNamesIdsAndDefaults(procedureCode);
|
1627 |
+
if (paramNamesIdsAndDefaults === null) {
|
1628 |
+
return {
|
1629 |
+
kind: 'noop'
|
1630 |
+
};
|
1631 |
+
}
|
1632 |
+
|
1633 |
+
const [paramNames, paramIds, paramDefaults] = paramNamesIdsAndDefaults;
|
1634 |
+
|
1635 |
+
const addonBlock = this.runtime.getAddonBlock(procedureCode);
|
1636 |
+
if (addonBlock) {
|
1637 |
+
this.script.yields = true;
|
1638 |
+
const args = {};
|
1639 |
+
for (let i = 0; i < paramIds.length; i++) {
|
1640 |
+
let value;
|
1641 |
+
if (block.inputs[paramIds[i]] && block.inputs[paramIds[i]].block) {
|
1642 |
+
value = this.descendInputOfBlock(block, paramIds[i]);
|
1643 |
+
} else {
|
1644 |
+
value = {
|
1645 |
+
kind: 'constant',
|
1646 |
+
value: paramDefaults[i]
|
1647 |
+
};
|
1648 |
+
}
|
1649 |
+
args[paramNames[i]] = value;
|
1650 |
+
}
|
1651 |
+
return {
|
1652 |
+
kind: 'addons.call',
|
1653 |
+
code: procedureCode,
|
1654 |
+
arguments: args,
|
1655 |
+
blockId: block.id
|
1656 |
+
};
|
1657 |
+
}
|
1658 |
+
|
1659 |
+
const definitionId = this.blocks.getProcedureDefinition(procedureCode);
|
1660 |
+
const definitionBlock = this.blocks.getBlock(definitionId);
|
1661 |
+
if (!definitionBlock) {
|
1662 |
+
return {
|
1663 |
+
kind: 'noop'
|
1664 |
+
};
|
1665 |
+
}
|
1666 |
+
const innerDefinition = this.blocks.getBlock(definitionBlock.inputs.custom_block.block);
|
1667 |
+
|
1668 |
+
let isWarp = this.script.isWarp;
|
1669 |
+
if (!isWarp) {
|
1670 |
+
if (innerDefinition && innerDefinition.mutation) {
|
1671 |
+
const warp = innerDefinition.mutation.warp;
|
1672 |
+
if (typeof warp === 'boolean') {
|
1673 |
+
isWarp = warp;
|
1674 |
+
} else if (typeof warp === 'string') {
|
1675 |
+
isWarp = JSON.parse(warp);
|
1676 |
+
}
|
1677 |
+
}
|
1678 |
+
}
|
1679 |
+
|
1680 |
+
const variant = generateProcedureVariant(procedureCode, isWarp);
|
1681 |
+
|
1682 |
+
if (!this.script.dependedProcedures.includes(variant)) {
|
1683 |
+
this.script.dependedProcedures.push(variant);
|
1684 |
+
}
|
1685 |
+
|
1686 |
+
// Non-warp direct recursion yields.
|
1687 |
+
if (!this.script.isWarp) {
|
1688 |
+
if (procedureCode === this.script.procedureCode) {
|
1689 |
+
this.script.yields = true;
|
1690 |
+
}
|
1691 |
+
}
|
1692 |
+
|
1693 |
+
const args = [];
|
1694 |
+
for (let i = 0; i < paramIds.length; i++) {
|
1695 |
+
let value;
|
1696 |
+
if (block.inputs[paramIds[i]] && block.inputs[paramIds[i]].block) {
|
1697 |
+
if (paramIds[i].startsWith("SUBSTACK")) {
|
1698 |
+
value = this.descendSubstack(block, paramIds[i])
|
1699 |
+
} else {
|
1700 |
+
value = this.descendInputOfBlock(block, paramIds[i]);
|
1701 |
+
}
|
1702 |
+
} else {
|
1703 |
+
value = {
|
1704 |
+
kind: 'constant',
|
1705 |
+
value: paramDefaults[i]
|
1706 |
+
};
|
1707 |
+
}
|
1708 |
+
args.push(value);
|
1709 |
+
}
|
1710 |
+
|
1711 |
+
return {
|
1712 |
+
kind: 'procedures.call',
|
1713 |
+
code: procedureCode,
|
1714 |
+
variant,
|
1715 |
+
returns: false,
|
1716 |
+
arguments: args,
|
1717 |
+
type: JSON.parse(block.mutation.optype || '"statement"')
|
1718 |
+
};
|
1719 |
+
}
|
1720 |
+
|
1721 |
+
case 'sensing_set_of':
|
1722 |
+
return {
|
1723 |
+
kind: 'sensing.set.of',
|
1724 |
+
property: block.fields.PROPERTY.value,
|
1725 |
+
object: this.descendInputOfBlock(block, 'OBJECT'),
|
1726 |
+
value: this.descendInputOfBlock(block, 'VALUE')
|
1727 |
+
};
|
1728 |
+
case 'sensing_resettimer':
|
1729 |
+
return {
|
1730 |
+
kind: 'timer.reset'
|
1731 |
+
};
|
1732 |
+
|
1733 |
+
/*
|
1734 |
+
can someone set up the jsgen for these, i dont want to rn
|
1735 |
+
case "sensing_regextest":
|
1736 |
+
return {
|
1737 |
+
kind: "sensing.regextest",
|
1738 |
+
regex: this.descendInputOfBlock(block, 'reg'),
|
1739 |
+
text: this.descendInputOfBlock(block, 'text')
|
1740 |
+
}
|
1741 |
+
case "sensing_thing_is_number":
|
1742 |
+
return {
|
1743 |
+
kind: "sensing.thing.is.number",
|
1744 |
+
text: this.descendInputOfBlock(block, 'TEXT1')
|
1745 |
+
}
|
1746 |
+
case "sensing_mobile":
|
1747 |
+
return {
|
1748 |
+
kind: "sensing.mobile",
|
1749 |
+
}
|
1750 |
+
case "sensing_thing_is_text":
|
1751 |
+
return {
|
1752 |
+
kind: "sensing.thing.is.text",
|
1753 |
+
text: this.descendInputOfBlock(block, 'TEXT1')
|
1754 |
+
}
|
1755 |
+
case "sensing_getspritewithattrib":
|
1756 |
+
return {
|
1757 |
+
kind: "sensing.getspritewithattrib",
|
1758 |
+
variable: this.descendInputOfBlock(block, 'var'),
|
1759 |
+
value: this.descendInputOfBlock(block, 'val')
|
1760 |
+
}
|
1761 |
+
|
1762 |
+
case "operator_regexmatch":
|
1763 |
+
return {
|
1764 |
+
kind: "operator.regexmatch",
|
1765 |
+
regex: this.descendInputOfBlock(block, 'reg'),
|
1766 |
+
text: this.descendInputOfBlock(block, 'text')
|
1767 |
+
}
|
1768 |
+
case "operator_replaceAll":
|
1769 |
+
return {
|
1770 |
+
kind: "operator.replaceAll",
|
1771 |
+
text: this.descendInputOfBlock(block, 'term'),
|
1772 |
+
with: this.descendInputOfBlock(block, 'res'),
|
1773 |
+
in: this.descendInputOfBlock(block, 'text')
|
1774 |
+
}
|
1775 |
+
case "operator_getLettersFromIndexToIndexInTextFixed":
|
1776 |
+
case "operator_getLettersFromIndexToIndexInText":
|
1777 |
+
return {
|
1778 |
+
kind: "operator.getLettersFromIndexToIndexInText",
|
1779 |
+
from: this.descendInputOfBlock(block, 'INDEX1'),
|
1780 |
+
to: this.descendInputOfBlock(block, 'INDEX2'),
|
1781 |
+
ammount: this.descendInputOfBlock(block, 'TEXT')
|
1782 |
+
}
|
1783 |
+
case "operator_readLineInMultilineText":
|
1784 |
+
return {
|
1785 |
+
kind: "operator.readLineInMultilineText",
|
1786 |
+
line: this.descendInputOfBlock(block, 'LINE'),
|
1787 |
+
text: this.descendInputOfBlock(block, 'TEXT')
|
1788 |
+
}
|
1789 |
+
case "operator_newLine":
|
1790 |
+
return {
|
1791 |
+
kind: "operator.newLine",
|
1792 |
+
}
|
1793 |
+
case "operator_stringify":
|
1794 |
+
return {
|
1795 |
+
kind: "operator.stringify",
|
1796 |
+
pass: this.descendInputOfBlock(block, 'ONE')
|
1797 |
+
}
|
1798 |
+
case "operator_lerpFunc":
|
1799 |
+
return {
|
1800 |
+
kind: "operator.lerpFunc",
|
1801 |
+
from: this.descendInputOfBlock(block, 'ONE'),
|
1802 |
+
to: this.descendInputOfBlock(block, 'TWO'),
|
1803 |
+
ammount: this.descendInputOfBlock(block, 'AMOUNT')
|
1804 |
+
}
|
1805 |
+
case "operator_advMath":
|
1806 |
+
return {
|
1807 |
+
kind: "operator.advMath",
|
1808 |
+
num1: this.descendInputOfBlock(block, 'ONE'),
|
1809 |
+
num2: this.descendInputOfBlock(block, 'TWO'),
|
1810 |
+
op: block.fields.OPTION.value
|
1811 |
+
}
|
1812 |
+
case "operator_constrainnumber":
|
1813 |
+
return {
|
1814 |
+
kind: "operator.constrainnumber",
|
1815 |
+
number: this.descendInputOfBlock(block, 'inp'),
|
1816 |
+
min: this.descendInputOfBlock(block, 'min'),
|
1817 |
+
max: this.descendInputOfBlock(block, 'max')
|
1818 |
+
}
|
1819 |
+
case "operator_trueBoolean":
|
1820 |
+
return {
|
1821 |
+
kind: "operator.trueBoolean",
|
1822 |
+
}
|
1823 |
+
case "operator_falseBoolean":
|
1824 |
+
return {
|
1825 |
+
kind: "operator.falseBoolean",
|
1826 |
+
}
|
1827 |
+
case "operator_randomBoolean":
|
1828 |
+
return {
|
1829 |
+
kind: "operator.randomBoolean",
|
1830 |
+
}
|
1831 |
+
case "operator_indexOfTextInText":
|
1832 |
+
return {
|
1833 |
+
kind: "operator.indexOfTextInText",
|
1834 |
+
check: this.descendInputOfBlock(block, 'TEXT1'),
|
1835 |
+
text: this.descendInputOfBlock(block, 'TEXT2')
|
1836 |
+
}
|
1837 |
+
|
1838 |
+
case "event_whenanything":
|
1839 |
+
return {
|
1840 |
+
kind: "event.whenanything",
|
1841 |
+
}
|
1842 |
+
case "event_always":
|
1843 |
+
return {
|
1844 |
+
kind: "event.always",
|
1845 |
+
event: this.descendInputOfBlock(block, 'ANYTHING')
|
1846 |
+
}
|
1847 |
+
|
1848 |
+
case "control_backToGreenFlag":
|
1849 |
+
return {
|
1850 |
+
kind: "control.backToGreenFlag",
|
1851 |
+
}
|
1852 |
+
case "control_if_return_else_return":
|
1853 |
+
return {
|
1854 |
+
kind: "control.if.return.else.return",
|
1855 |
+
if: this.descendInputOfBlock(block, 'boolean'),
|
1856 |
+
true: this.descendInputOfBlock(block, 'TEXT1'),
|
1857 |
+
false: this.descendInputOfBlock(block, 'TEXT2'),
|
1858 |
+
}
|
1859 |
+
all the names so you dont have to get them
|
1860 |
+
sensing.regextest
|
1861 |
+
sensing.thing.is.number
|
1862 |
+
sensing.mobile
|
1863 |
+
sensing.thing.is.text
|
1864 |
+
sensing.getspritewithattrib
|
1865 |
+
|
1866 |
+
operator.regexmatch
|
1867 |
+
operator.replaceAll
|
1868 |
+
operator.getLettersFromIndexToIndexInText
|
1869 |
+
operator.readLineInMultilineText
|
1870 |
+
operator.newLine
|
1871 |
+
operator.stringify
|
1872 |
+
operator.lerpFunc
|
1873 |
+
operator.advMath
|
1874 |
+
operator.constrainnumber
|
1875 |
+
operator.trueBoolean
|
1876 |
+
operator.falseBoolean
|
1877 |
+
operator.randomBoolean
|
1878 |
+
operator.indexOfTextInText
|
1879 |
+
|
1880 |
+
event.whenanything
|
1881 |
+
event.always
|
1882 |
+
|
1883 |
+
control.backToGreenFlag
|
1884 |
+
control.if.return.else.return
|
1885 |
+
*/
|
1886 |
+
|
1887 |
+
case 'lmsTempVars2_setRuntimeVariable':
|
1888 |
+
return {
|
1889 |
+
kind: 'tempVars.set',
|
1890 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
1891 |
+
val: this.descendInputOfBlock(block, 'STRING'),
|
1892 |
+
runtime: true
|
1893 |
+
};
|
1894 |
+
case 'lmsTempVars2_setThreadVariable':
|
1895 |
+
return {
|
1896 |
+
kind: 'tempVars.set',
|
1897 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
1898 |
+
val: this.descendInputOfBlock(block, 'STRING'),
|
1899 |
+
thread: true
|
1900 |
+
};
|
1901 |
+
case 'tempVars_setVariable':
|
1902 |
+
return {
|
1903 |
+
kind: 'tempVars.set',
|
1904 |
+
var: this.descendInputOfBlock(block, 'name'),
|
1905 |
+
val: this.descendInputOfBlock(block, 'value')
|
1906 |
+
};
|
1907 |
+
|
1908 |
+
case 'lmsTempVars2_changeRuntimeVariable':
|
1909 |
+
const name = this.descendInputOfBlock(block, 'VAR');
|
1910 |
+
return {
|
1911 |
+
kind: 'tempVars.set',
|
1912 |
+
var: name,
|
1913 |
+
val: {
|
1914 |
+
kind: 'op.add',
|
1915 |
+
left: {
|
1916 |
+
kind: 'tempVars.get',
|
1917 |
+
var: name,
|
1918 |
+
runtime: true
|
1919 |
+
},
|
1920 |
+
right: this.descendInputOfBlock(block, 'NUM')
|
1921 |
+
},
|
1922 |
+
runtime: true
|
1923 |
+
};
|
1924 |
+
case 'lmsTempVars2_changeThreadVariable': {
|
1925 |
+
const name = this.descendInputOfBlock(block, 'VAR');
|
1926 |
+
return {
|
1927 |
+
kind: 'tempVars.set',
|
1928 |
+
var: name,
|
1929 |
+
val: {
|
1930 |
+
kind: 'op.add',
|
1931 |
+
left: {
|
1932 |
+
kind: 'tempVars.get',
|
1933 |
+
var: name,
|
1934 |
+
thread: true
|
1935 |
+
},
|
1936 |
+
right: this.descendInputOfBlock(block, 'NUM')
|
1937 |
+
},
|
1938 |
+
thread: true
|
1939 |
+
};
|
1940 |
+
}
|
1941 |
+
case 'tempVars_changeVariable': {
|
1942 |
+
const name = this.descendInputOfBlock(block, 'name');
|
1943 |
+
return {
|
1944 |
+
kind: 'tempVars.set',
|
1945 |
+
var: name,
|
1946 |
+
val: {
|
1947 |
+
kind: 'op.add',
|
1948 |
+
left: {
|
1949 |
+
kind: 'tempVars.get',
|
1950 |
+
var: name
|
1951 |
+
},
|
1952 |
+
right: this.descendInputOfBlock(block, 'value')
|
1953 |
+
}
|
1954 |
+
};
|
1955 |
+
}
|
1956 |
+
|
1957 |
+
case 'lmsTempVars2_deleteRuntimeVariable':
|
1958 |
+
return {
|
1959 |
+
kind: 'tempVars.delete',
|
1960 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
1961 |
+
runtime: true
|
1962 |
+
};
|
1963 |
+
case 'tempVars_deleteVariable':
|
1964 |
+
return {
|
1965 |
+
kind: 'tempVars.delete',
|
1966 |
+
var: this.descendInputOfBlock(block, 'name')
|
1967 |
+
};
|
1968 |
+
|
1969 |
+
case 'lmsTempVars2_deleteAllRuntimeVariables':
|
1970 |
+
return {
|
1971 |
+
kind: 'tempVars.deleteAll',
|
1972 |
+
runtime: true
|
1973 |
+
};
|
1974 |
+
case 'tempVars_deleteAllVariables':
|
1975 |
+
return {
|
1976 |
+
kind: 'tempVars.deleteAll'
|
1977 |
+
};
|
1978 |
+
|
1979 |
+
case 'lmsTempVars2_forEachThreadVariable':
|
1980 |
+
return {
|
1981 |
+
kind: 'tempVars.forEach',
|
1982 |
+
var: this.descendInputOfBlock(block, 'VAR'),
|
1983 |
+
loops: this.descendInputOfBlock(block, 'NUM'),
|
1984 |
+
do: this.descendSubstack(block, 'SUBSTACK'),
|
1985 |
+
thread: true
|
1986 |
+
};
|
1987 |
+
case 'tempVars_forEachTempVar':
|
1988 |
+
this.analyzeLoop();
|
1989 |
+
return {
|
1990 |
+
kind: 'tempVars.forEach',
|
1991 |
+
var: this.descendInputOfBlock(block, 'NAME'),
|
1992 |
+
loops: this.descendInputOfBlock(block, 'REPEAT'),
|
1993 |
+
do: this.descendSubstack(block, 'SUBSTACK')
|
1994 |
+
};
|
1995 |
+
case 'control_dualblock':
|
1996 |
+
return {
|
1997 |
+
kind: 'control.dualBlock'
|
1998 |
+
};
|
1999 |
+
|
2000 |
+
default: {
|
2001 |
+
const opcodeFunction = this.runtime.getOpcodeFunction(block.opcode);
|
2002 |
+
if (opcodeFunction) {
|
2003 |
+
// It might be a non-compiled primitive from a standard category
|
2004 |
+
if (compatBlocks.statementBlocks.includes(block.opcode)) {
|
2005 |
+
return this.descendCompatLayer(block);
|
2006 |
+
}
|
2007 |
+
// It might be an extension block.
|
2008 |
+
const blockInfo = this.getBlockInfo(block.opcode);
|
2009 |
+
if (blockInfo) {
|
2010 |
+
const type = blockInfo.info.blockType;
|
2011 |
+
const args = this.descendCompatLayer(block, blockInfo.info);
|
2012 |
+
args.block = block;
|
2013 |
+
if (block.mutation) args.mutation = block.mutation;
|
2014 |
+
if (type === BlockType.COMMAND || type === BlockType.CONDITIONAL || type === BlockType.LOOP) {
|
2015 |
+
return args;
|
2016 |
+
}
|
2017 |
+
}
|
2018 |
+
}
|
2019 |
+
|
2020 |
+
// When this thread was triggered by a stack click, attempt to compile as an input.
|
2021 |
+
// TODO: perhaps this should be moved to generate()?
|
2022 |
+
if (this.thread.stackClick) {
|
2023 |
+
try {
|
2024 |
+
const inputNode = this.descendInput(block);
|
2025 |
+
return {
|
2026 |
+
kind: 'visualReport',
|
2027 |
+
input: inputNode
|
2028 |
+
};
|
2029 |
+
} catch (e) {
|
2030 |
+
// Ignore
|
2031 |
+
}
|
2032 |
+
}
|
2033 |
+
|
2034 |
+
log.warn(`IR: Unknown stacked block: ${block.opcode}`, block);
|
2035 |
+
throw new Error(`IR: Unknown stacked block: ${block.opcode}`);
|
2036 |
+
}
|
2037 |
+
}
|
2038 |
+
}
|
2039 |
+
|
2040 |
+
/**
|
2041 |
+
* Descend into a stack of blocks (eg. the blocks contained within an "if" block)
|
2042 |
+
* @param {*} parentBlock The parent Scratch block that contains the stack to parse.
|
2043 |
+
* @param {*} substackName The name of the stack to descend into.
|
2044 |
+
* @private
|
2045 |
+
* @returns {Node[]} List of stacked block nodes.
|
2046 |
+
*/
|
2047 |
+
descendSubstack (parentBlock, substackName) {
|
2048 |
+
const input = parentBlock.inputs[substackName];
|
2049 |
+
if (!input) {
|
2050 |
+
return [];
|
2051 |
+
}
|
2052 |
+
const stackId = input.block;
|
2053 |
+
return this.walkStack(stackId);
|
2054 |
+
}
|
2055 |
+
|
2056 |
+
/**
|
2057 |
+
* Descend into and walk the siblings of a stack.
|
2058 |
+
* @param {string} startingBlockId The ID of the first block of a stack.
|
2059 |
+
* @private
|
2060 |
+
* @returns {Node[]} List of stacked block nodes.
|
2061 |
+
*/
|
2062 |
+
walkStack (startingBlockId) {
|
2063 |
+
const result = [];
|
2064 |
+
let blockId = startingBlockId;
|
2065 |
+
|
2066 |
+
while (blockId !== null) {
|
2067 |
+
const block = this.getBlockById(blockId);
|
2068 |
+
if (!block) {
|
2069 |
+
break;
|
2070 |
+
}
|
2071 |
+
|
2072 |
+
const node = this.descendStackedBlock(block);
|
2073 |
+
result.push(node);
|
2074 |
+
|
2075 |
+
blockId = block.next;
|
2076 |
+
}
|
2077 |
+
|
2078 |
+
return result;
|
2079 |
+
}
|
2080 |
+
|
2081 |
+
/**
|
2082 |
+
* Descend into a variable.
|
2083 |
+
* @param {*} block The block that has the variable.
|
2084 |
+
* @param {string} fieldName The name of the field that the variable is stored in.
|
2085 |
+
* @param {''|'list'} type Variable type, '' for scalar and 'list' for list.
|
2086 |
+
* @private
|
2087 |
+
* @returns {*} A parsed variable object.
|
2088 |
+
*/
|
2089 |
+
descendVariable (block, fieldName, type) {
|
2090 |
+
const variable = block.fields[fieldName];
|
2091 |
+
const id = variable.id;
|
2092 |
+
|
2093 |
+
if (this.variableCache.hasOwnProperty(id)) {
|
2094 |
+
return this.variableCache[id];
|
2095 |
+
}
|
2096 |
+
|
2097 |
+
const data = this._descendVariable(id, variable.value, type);
|
2098 |
+
this.variableCache[id] = data;
|
2099 |
+
return data;
|
2100 |
+
}
|
2101 |
+
|
2102 |
+
/**
|
2103 |
+
* @param {string} id The ID of the variable.
|
2104 |
+
* @param {string} name The name of the variable.
|
2105 |
+
* @param {''|'list'} type The variable type.
|
2106 |
+
* @private
|
2107 |
+
* @returns {*} A parsed variable object.
|
2108 |
+
*/
|
2109 |
+
_descendVariable (id, name, type) {
|
2110 |
+
const target = this.target;
|
2111 |
+
const stage = this.stage;
|
2112 |
+
|
2113 |
+
// Look for by ID in target...
|
2114 |
+
if (target.variables.hasOwnProperty(id)) {
|
2115 |
+
return createVariableData('target', target.variables[id]);
|
2116 |
+
}
|
2117 |
+
|
2118 |
+
// Look for by ID in stage...
|
2119 |
+
if (!target.isStage) {
|
2120 |
+
if (stage && stage.variables.hasOwnProperty(id)) {
|
2121 |
+
return createVariableData('stage', stage.variables[id]);
|
2122 |
+
}
|
2123 |
+
}
|
2124 |
+
|
2125 |
+
// Look for by name and type in target...
|
2126 |
+
for (const varId in target.variables) {
|
2127 |
+
if (target.variables.hasOwnProperty(varId)) {
|
2128 |
+
const currVar = target.variables[varId];
|
2129 |
+
if (currVar.name === name && currVar.type === type) {
|
2130 |
+
return createVariableData('target', currVar);
|
2131 |
+
}
|
2132 |
+
}
|
2133 |
+
}
|
2134 |
+
|
2135 |
+
// Look for by name and type in stage...
|
2136 |
+
if (!target.isStage && stage) {
|
2137 |
+
for (const varId in stage.variables) {
|
2138 |
+
if (stage.variables.hasOwnProperty(varId)) {
|
2139 |
+
const currVar = stage.variables[varId];
|
2140 |
+
if (currVar.name === name && currVar.type === type) {
|
2141 |
+
return createVariableData('stage', currVar);
|
2142 |
+
}
|
2143 |
+
}
|
2144 |
+
}
|
2145 |
+
}
|
2146 |
+
|
2147 |
+
// Create it locally...
|
2148 |
+
const newVariable = this.runtime.newVariableInstance(type, id, name, false);
|
2149 |
+
target.variables[id] = newVariable;
|
2150 |
+
|
2151 |
+
if (target.sprite) {
|
2152 |
+
// Create the variable in all instances of this sprite.
|
2153 |
+
// This is necessary because the script cache is shared between clones.
|
2154 |
+
// sprite.clones has all instances of this sprite including the original and all clones
|
2155 |
+
for (const clone of target.sprite.clones) {
|
2156 |
+
if (!clone.variables.hasOwnProperty(id)) {
|
2157 |
+
clone.variables[id] = this.runtime.newVariableInstance(type, id, name, false);
|
2158 |
+
}
|
2159 |
+
}
|
2160 |
+
}
|
2161 |
+
|
2162 |
+
return createVariableData('target', newVariable);
|
2163 |
+
}
|
2164 |
+
|
2165 |
+
/**
|
2166 |
+
* Descend into a block that uses the compatibility layer.
|
2167 |
+
* @param {*} block The block to use the compatibility layer for.
|
2168 |
+
* @private
|
2169 |
+
* @returns {Node} The parsed node.
|
2170 |
+
*/
|
2171 |
+
descendCompatLayer (block, blockInfo) {
|
2172 |
+
this.script.yields = true;
|
2173 |
+
if (!blockInfo) {
|
2174 |
+
blockInfo = this.getBlockInfo(block.opcode);
|
2175 |
+
blockInfo = blockInfo ? blockInfo.info : null;
|
2176 |
+
}
|
2177 |
+
|
2178 |
+
const inputs = {};
|
2179 |
+
for (const name of Object.keys(block.inputs)) {
|
2180 |
+
if (!name.startsWith('SUBSTACK')) {
|
2181 |
+
inputs[name] = this.descendInputOfBlock(block, name);
|
2182 |
+
}
|
2183 |
+
}
|
2184 |
+
|
2185 |
+
const fields = {};
|
2186 |
+
const substacks = [];
|
2187 |
+
const blockType = (blockInfo && blockInfo.blockType) || BlockType.COMMAND;
|
2188 |
+
if (blockType === BlockType.CONDITIONAL || blockType === BlockType.LOOP) {
|
2189 |
+
for (let i in (blockInfo.branches || [])) {
|
2190 |
+
const inputName = i === "0" ? 'SUBSTACK' : `SUBSTACK${Number(i) + 1}`;
|
2191 |
+
substacks.push(this.descendSubstack(block, inputName));
|
2192 |
+
}
|
2193 |
+
}
|
2194 |
+
for (const name of Object.keys(block.fields)) {
|
2195 |
+
const type = block.fields[name].variableType;
|
2196 |
+
if (typeof type !== 'undefined') {
|
2197 |
+
const data = this.descendVariable(block, name, type);
|
2198 |
+
fields[name] = data;
|
2199 |
+
continue;
|
2200 |
+
}
|
2201 |
+
fields[name] = block.fields[name].value;
|
2202 |
+
}
|
2203 |
+
return {
|
2204 |
+
kind: 'compat',
|
2205 |
+
id: block.id,
|
2206 |
+
opcode: block.opcode,
|
2207 |
+
blockType,
|
2208 |
+
inputs,
|
2209 |
+
fields,
|
2210 |
+
substacks
|
2211 |
+
};
|
2212 |
+
}
|
2213 |
+
|
2214 |
+
analyzeLoop () {
|
2215 |
+
if (!this.script.isWarp || this.script.warpTimer) {
|
2216 |
+
this.script.yields = true;
|
2217 |
+
}
|
2218 |
+
}
|
2219 |
+
|
2220 |
+
readTopBlockComment (commentId) {
|
2221 |
+
const comment = this.target.comments[commentId];
|
2222 |
+
if (!comment) {
|
2223 |
+
// can't find the comment
|
2224 |
+
// this is safe to ignore
|
2225 |
+
return;
|
2226 |
+
}
|
2227 |
+
|
2228 |
+
const text = comment.text;
|
2229 |
+
|
2230 |
+
for (const line of text.split('\n')) {
|
2231 |
+
if (!/^tw\b/.test(line)) {
|
2232 |
+
continue;
|
2233 |
+
}
|
2234 |
+
|
2235 |
+
const flags = line.split(' ');
|
2236 |
+
for (const flag of flags) {
|
2237 |
+
switch (flag) {
|
2238 |
+
case 'nocompile':
|
2239 |
+
throw new Error('Script explicitly disables compilation');
|
2240 |
+
case 'stuck':
|
2241 |
+
this.script.warpTimer = true;
|
2242 |
+
break;
|
2243 |
+
}
|
2244 |
+
}
|
2245 |
+
|
2246 |
+
// Only the first 'tw' line is parsed.
|
2247 |
+
break;
|
2248 |
+
}
|
2249 |
+
}
|
2250 |
+
|
2251 |
+
/**
|
2252 |
+
* @param {Block} hatBlock
|
2253 |
+
*/
|
2254 |
+
walkHat(hatBlock) {
|
2255 |
+
const nextBlock = hatBlock.next;
|
2256 |
+
const opcode = hatBlock.opcode;
|
2257 |
+
const hatInfo = this.runtime._hats[opcode];
|
2258 |
+
|
2259 |
+
if (this.thread.stackClick) {
|
2260 |
+
// We still need to treat the hat as a normal block (so executableHat should be false) for
|
2261 |
+
// interpreter parity, but the reuslt is ignored.
|
2262 |
+
const opcodeFunction = this.runtime.getOpcodeFunction(opcode);
|
2263 |
+
if (opcodeFunction) {
|
2264 |
+
return [
|
2265 |
+
this.descendCompatLayer(hatBlock),
|
2266 |
+
...this.walkStack(nextBlock)
|
2267 |
+
];
|
2268 |
+
}
|
2269 |
+
return this.walkStack(nextBlock);
|
2270 |
+
}
|
2271 |
+
|
2272 |
+
if (hatInfo.edgeActivated) {
|
2273 |
+
// Edge-activated HAT
|
2274 |
+
this.script.yields = true;
|
2275 |
+
this.script.executableHat = true;
|
2276 |
+
return [
|
2277 |
+
{
|
2278 |
+
kind: 'hat.edge',
|
2279 |
+
id: hatBlock.id,
|
2280 |
+
condition: this.descendCompatLayer(hatBlock)
|
2281 |
+
},
|
2282 |
+
...this.walkStack(nextBlock)
|
2283 |
+
];
|
2284 |
+
}
|
2285 |
+
|
2286 |
+
const opcodeFunction = this.runtime.getOpcodeFunction(opcode);
|
2287 |
+
if (opcodeFunction) {
|
2288 |
+
// Predicate-based HAT
|
2289 |
+
this.script.yields = true;
|
2290 |
+
this.script.executableHat = true;
|
2291 |
+
return [
|
2292 |
+
{
|
2293 |
+
kind: 'hat.predicate',
|
2294 |
+
condition: this.descendCompatLayer(hatBlock)
|
2295 |
+
},
|
2296 |
+
...this.walkStack(nextBlock)
|
2297 |
+
];
|
2298 |
+
}
|
2299 |
+
|
2300 |
+
return this.walkStack(nextBlock);
|
2301 |
+
}
|
2302 |
+
|
2303 |
+
/**
|
2304 |
+
* @param {string} topBlockId The ID of the top block of the script.
|
2305 |
+
* @returns {IntermediateScript}
|
2306 |
+
*/
|
2307 |
+
generate (topBlockId) {
|
2308 |
+
this.blocks.populateProcedureCache();
|
2309 |
+
|
2310 |
+
this.script.topBlockId = topBlockId;
|
2311 |
+
|
2312 |
+
const topBlock = this.getBlockById(topBlockId);
|
2313 |
+
if (!topBlock) {
|
2314 |
+
if (this.script.isProcedure) {
|
2315 |
+
// Empty procedure
|
2316 |
+
return this.script;
|
2317 |
+
}
|
2318 |
+
throw new Error('Cannot find top block');
|
2319 |
+
}
|
2320 |
+
|
2321 |
+
if (topBlock.comment) {
|
2322 |
+
this.readTopBlockComment(topBlock.comment);
|
2323 |
+
}
|
2324 |
+
|
2325 |
+
// We do need to evaluate empty hats
|
2326 |
+
const hatInfo = this.runtime._hats[topBlock.opcode];
|
2327 |
+
const isHat = !!hatInfo;
|
2328 |
+
if (isHat) {
|
2329 |
+
this.script.stack = this.walkHat(topBlock);
|
2330 |
+
} else {
|
2331 |
+
// We don't evaluate the procedures_definition top block as it never does anything
|
2332 |
+
// We also don't want it to be treated like a hat block
|
2333 |
+
let entryBlock;
|
2334 |
+
if (
|
2335 |
+
topBlock.opcode === 'procedures_definition'
|
2336 |
+
|| topBlock.opcode === 'procedures_definition_return'
|
2337 |
+
) {
|
2338 |
+
entryBlock = topBlock.next;
|
2339 |
+
} else {
|
2340 |
+
entryBlock = topBlockId;
|
2341 |
+
}
|
2342 |
+
|
2343 |
+
if (entryBlock) {
|
2344 |
+
this.script.stack = this.walkStack(entryBlock);
|
2345 |
+
}
|
2346 |
+
}
|
2347 |
+
|
2348 |
+
return this.script;
|
2349 |
+
}
|
2350 |
+
}
|
2351 |
+
|
2352 |
+
class IRGenerator {
|
2353 |
+
constructor (thread) {
|
2354 |
+
this.thread = thread;
|
2355 |
+
this.blocks = thread.blockContainer;
|
2356 |
+
|
2357 |
+
this.proceduresToCompile = new Map();
|
2358 |
+
this.compilingProcedures = new Map();
|
2359 |
+
/** @type {Object.<string, IntermediateScript>} */
|
2360 |
+
this.procedures = {};
|
2361 |
+
|
2362 |
+
this.analyzedProcedures = [];
|
2363 |
+
}
|
2364 |
+
|
2365 |
+
static _extensionIRInfo = {};
|
2366 |
+
static setExtensionIr(id, data) {
|
2367 |
+
IRGenerator._extensionIRInfo[id] = data;
|
2368 |
+
}
|
2369 |
+
static hasExtensionIr(id) {
|
2370 |
+
return Boolean(IRGenerator._extensionIRInfo[id]);
|
2371 |
+
}
|
2372 |
+
static getExtensionIr(id) {
|
2373 |
+
return IRGenerator._extensionIRInfo[id];
|
2374 |
+
}
|
2375 |
+
|
2376 |
+
addProcedureDependencies (dependencies) {
|
2377 |
+
for (const procedureVariant of dependencies) {
|
2378 |
+
if (this.procedures.hasOwnProperty(procedureVariant)) {
|
2379 |
+
continue;
|
2380 |
+
}
|
2381 |
+
if (this.compilingProcedures.has(procedureVariant)) {
|
2382 |
+
continue;
|
2383 |
+
}
|
2384 |
+
if (this.proceduresToCompile.has(procedureVariant)) {
|
2385 |
+
continue;
|
2386 |
+
}
|
2387 |
+
const procedureCode = parseProcedureCode(procedureVariant);
|
2388 |
+
const definition = this.blocks.getProcedureDefinition(procedureCode);
|
2389 |
+
this.proceduresToCompile.set(procedureVariant, definition);
|
2390 |
+
}
|
2391 |
+
}
|
2392 |
+
|
2393 |
+
/**
|
2394 |
+
* @param {ScriptTreeGenerator} generator The generator to run.
|
2395 |
+
* @param {string} topBlockId The ID of the top block in the stack.
|
2396 |
+
* @returns {IntermediateScript} Intermediate script.
|
2397 |
+
*/
|
2398 |
+
generateScriptTree (generator, topBlockId) {
|
2399 |
+
const result = generator.generate(topBlockId);
|
2400 |
+
this.addProcedureDependencies(result.dependedProcedures);
|
2401 |
+
return result;
|
2402 |
+
}
|
2403 |
+
|
2404 |
+
/**
|
2405 |
+
* Recursively analyze a script and its dependencies.
|
2406 |
+
* @param {IntermediateScript} script Intermediate script.
|
2407 |
+
*/
|
2408 |
+
analyzeScript (script) {
|
2409 |
+
let madeChanges = false;
|
2410 |
+
for (const procedureCode of script.dependedProcedures) {
|
2411 |
+
const procedureData = this.procedures[procedureCode];
|
2412 |
+
|
2413 |
+
// Analyze newly found procedures.
|
2414 |
+
if (!this.analyzedProcedures.includes(procedureCode)) {
|
2415 |
+
this.analyzedProcedures.push(procedureCode);
|
2416 |
+
if (this.analyzeScript(procedureData)) {
|
2417 |
+
madeChanges = true;
|
2418 |
+
}
|
2419 |
+
this.analyzedProcedures.pop();
|
2420 |
+
}
|
2421 |
+
|
2422 |
+
// If a procedure used by a script may yield, the script itself may yield.
|
2423 |
+
if (procedureData.yields && !script.yields) {
|
2424 |
+
script.yields = true;
|
2425 |
+
madeChanges = true;
|
2426 |
+
}
|
2427 |
+
}
|
2428 |
+
return madeChanges;
|
2429 |
+
}
|
2430 |
+
|
2431 |
+
/**
|
2432 |
+
* @returns {IntermediateRepresentation} Intermediate representation.
|
2433 |
+
*/
|
2434 |
+
generate () {
|
2435 |
+
const entry = this.generateScriptTree(new ScriptTreeGenerator(this.thread), this.thread.topBlock);
|
2436 |
+
|
2437 |
+
// Compile any required procedures.
|
2438 |
+
// As procedures can depend on other procedures, this process may take several iterations.
|
2439 |
+
const procedureTreeCache = this.blocks._cache.compiledProcedures;
|
2440 |
+
while (this.proceduresToCompile.size > 0) {
|
2441 |
+
this.compilingProcedures = this.proceduresToCompile;
|
2442 |
+
this.proceduresToCompile = new Map();
|
2443 |
+
|
2444 |
+
for (const [procedureVariant, definitionId] of this.compilingProcedures.entries()) {
|
2445 |
+
if (procedureTreeCache[procedureVariant]) {
|
2446 |
+
const result = procedureTreeCache[procedureVariant];
|
2447 |
+
this.procedures[procedureVariant] = result;
|
2448 |
+
this.addProcedureDependencies(result.dependedProcedures);
|
2449 |
+
} else {
|
2450 |
+
const isWarp = parseIsWarp(procedureVariant);
|
2451 |
+
const generator = new ScriptTreeGenerator(this.thread);
|
2452 |
+
generator.setProcedureVariant(procedureVariant);
|
2453 |
+
if (isWarp) generator.enableWarp();
|
2454 |
+
const compiledProcedure = this.generateScriptTree(generator, definitionId);
|
2455 |
+
this.procedures[procedureVariant] = compiledProcedure;
|
2456 |
+
procedureTreeCache[procedureVariant] = compiledProcedure;
|
2457 |
+
}
|
2458 |
+
}
|
2459 |
+
}
|
2460 |
+
|
2461 |
+
// Analyze scripts until no changes are made.
|
2462 |
+
while (this.analyzeScript(entry));
|
2463 |
+
|
2464 |
+
const ir = new IntermediateRepresentation();
|
2465 |
+
ir.entry = entry;
|
2466 |
+
ir.procedures = this.procedures;
|
2467 |
+
return ir;
|
2468 |
+
}
|
2469 |
+
|
2470 |
+
static exports = {
|
2471 |
+
ScriptTreeGenerator
|
2472 |
+
}
|
2473 |
+
}
|
2474 |
+
|
2475 |
+
module.exports = IRGenerator;
|
src/compiler/jsexecute.js
ADDED
@@ -0,0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* @fileoverview Runtime for scripts generated by jsgen
|
3 |
+
*/
|
4 |
+
|
5 |
+
/* eslint-disable no-unused-vars */
|
6 |
+
/* eslint-disable prefer-template */
|
7 |
+
/* eslint-disable valid-jsdoc */
|
8 |
+
/* eslint-disable max-len */
|
9 |
+
|
10 |
+
const globalState = {
|
11 |
+
Timer: require('../util/timer'),
|
12 |
+
Cast: require('../util/cast'),
|
13 |
+
log: require('../util/log'),
|
14 |
+
blockUtility: require('./compat-block-utility'),
|
15 |
+
thread: null
|
16 |
+
};
|
17 |
+
|
18 |
+
let baseRuntime = '';
|
19 |
+
const runtimeFunctions = {};
|
20 |
+
|
21 |
+
/**
|
22 |
+
* Determine whether the current tick is likely stuck.
|
23 |
+
* This implements similar functionality to the warp timer found in Scratch.
|
24 |
+
* @returns {boolean} true if the current tick is likely stuck.
|
25 |
+
*/
|
26 |
+
baseRuntime += `let stuckCounter = 0;
|
27 |
+
const isStuck = () => {
|
28 |
+
// The real time is not checked on every call for performance.
|
29 |
+
stuckCounter++;
|
30 |
+
if (stuckCounter === 100) {
|
31 |
+
stuckCounter = 0;
|
32 |
+
return globalState.thread.target.runtime.sequencer.timer.timeElapsed() > 500;
|
33 |
+
}
|
34 |
+
return false;
|
35 |
+
};`;
|
36 |
+
|
37 |
+
/**
|
38 |
+
* Alternative for nullish Coalescing
|
39 |
+
* @param {string} name The variable to get
|
40 |
+
* @returns {any} The value of the temp var or an empty string if its nullish
|
41 |
+
*/
|
42 |
+
runtimeFunctions.nullish = `const nullish = (check, alt) => {
|
43 |
+
if (!check) {
|
44 |
+
if (val === undefined) return alt
|
45 |
+
if (val === null) return alt
|
46 |
+
return check
|
47 |
+
} else {
|
48 |
+
return check
|
49 |
+
}
|
50 |
+
}`;
|
51 |
+
|
52 |
+
/**
|
53 |
+
* Start hats by opcode.
|
54 |
+
* @param {string} requestedHat The opcode of the hat to start.
|
55 |
+
* @param {*} optMatchFields Fields to match.
|
56 |
+
* @returns {Array} A list of threads that were started.
|
57 |
+
*/
|
58 |
+
runtimeFunctions.startHats = `const startHats = (requestedHat, optMatchFields) => {
|
59 |
+
const thread = globalState.thread;
|
60 |
+
const threads = thread.target.runtime.startHats(requestedHat, optMatchFields);
|
61 |
+
return threads;
|
62 |
+
}`;
|
63 |
+
|
64 |
+
/**
|
65 |
+
* Implements "thread waiting", where scripts are halted until all the scripts have finished executing.
|
66 |
+
* @param {Array} threads The list of threads.
|
67 |
+
*/
|
68 |
+
runtimeFunctions.waitThreads = `const waitThreads = function*(threads) {
|
69 |
+
const thread = globalState.thread;
|
70 |
+
const runtime = thread.target.runtime;
|
71 |
+
|
72 |
+
while (true) {
|
73 |
+
// determine whether any threads are running
|
74 |
+
let anyRunning = false;
|
75 |
+
for (let i = 0; i < threads.length; i++) {
|
76 |
+
if (runtime.threads.indexOf(threads[i]) !== -1) {
|
77 |
+
anyRunning = true;
|
78 |
+
break;
|
79 |
+
}
|
80 |
+
}
|
81 |
+
if (!anyRunning) {
|
82 |
+
// all threads are finished, can resume
|
83 |
+
return;
|
84 |
+
}
|
85 |
+
|
86 |
+
let allWaiting = true;
|
87 |
+
for (let i = 0; i < threads.length; i++) {
|
88 |
+
if (!runtime.isWaitingThread(threads[i])) {
|
89 |
+
allWaiting = false;
|
90 |
+
break;
|
91 |
+
}
|
92 |
+
}
|
93 |
+
if (allWaiting) {
|
94 |
+
thread.status = 3; // STATUS_YIELD_TICK
|
95 |
+
}
|
96 |
+
|
97 |
+
yield;
|
98 |
+
}
|
99 |
+
}`;
|
100 |
+
|
101 |
+
/**
|
102 |
+
* waitPromise: Wait until a Promise resolves or rejects before continuing.
|
103 |
+
* @param {Promise} promise The promise to wait for.
|
104 |
+
* @returns {*} the value that the promise resolves to, otherwise undefined if the promise rejects
|
105 |
+
*/
|
106 |
+
runtimeFunctions.waitPromise = `
|
107 |
+
const waitPromise = function*(promise) {
|
108 |
+
const thread = globalState.thread;
|
109 |
+
let returnValue;
|
110 |
+
let errorReturn;
|
111 |
+
|
112 |
+
promise
|
113 |
+
.then(value => {
|
114 |
+
returnValue = value;
|
115 |
+
thread.status = 0; // STATUS_RUNNING
|
116 |
+
})
|
117 |
+
.catch(error => {
|
118 |
+
errorReturn = error;
|
119 |
+
// i realized, i dont actually know what would happen if we never do this but throw and exit anyways
|
120 |
+
thread.status = 0; // STATUS_RUNNING
|
121 |
+
});
|
122 |
+
|
123 |
+
// enter STATUS_PROMISE_WAIT and yield
|
124 |
+
// this will stop script execution until the promise handlers reset the thread status
|
125 |
+
thread.status = 1; // STATUS_PROMISE_WAIT
|
126 |
+
yield;
|
127 |
+
|
128 |
+
// throw the promise error if ee got one
|
129 |
+
if (errorReturn) throw errorReturn
|
130 |
+
return returnValue;
|
131 |
+
}`;
|
132 |
+
|
133 |
+
/**
|
134 |
+
* isPromise: Determine if a value is Promise-like
|
135 |
+
* @param {unknown} promise The value to check
|
136 |
+
* @returns {promise is PromiseLike} True if the value is Promise-like (has a .then())
|
137 |
+
*/
|
138 |
+
|
139 |
+
/**
|
140 |
+
* executeInCompatibilityLayer: Execute a scratch-vm primitive.
|
141 |
+
* @param {*} inputs The inputs to pass to the block.
|
142 |
+
* @param {function} blockFunction The primitive's function.
|
143 |
+
* @param {boolean} useFlags Whether to set flags (hasResumedFromPromise)
|
144 |
+
* @param {string} blockId Block ID to set on the emulated block utility.
|
145 |
+
* @param {*|null} branchInfo Extra information object for CONDITIONAL and LOOP blocks. See createBranchInfo().
|
146 |
+
* @returns {*} the value returned by the block, if any.
|
147 |
+
*/
|
148 |
+
runtimeFunctions.executeInCompatibilityLayer = `let hasResumedFromPromise = false;
|
149 |
+
|
150 |
+
const isPromise = value => (
|
151 |
+
// see engine/execute.js
|
152 |
+
value !== null &&
|
153 |
+
typeof value === 'object' &&
|
154 |
+
typeof value.then === 'function'
|
155 |
+
);
|
156 |
+
const executeInCompatibilityLayer = function*(inputs, blockFunction, isWarp, useFlags, blockId, branchInfo, visualReport) {
|
157 |
+
const thread = globalState.thread;
|
158 |
+
const blockUtility = globalState.blockUtility;
|
159 |
+
const stackFrame = branchInfo ? branchInfo.stackFrame : {};
|
160 |
+
const finish = (returnValue) => {
|
161 |
+
if (branchInfo) {
|
162 |
+
if (typeof returnValue === 'undefined' && blockUtility._startedBranch) {
|
163 |
+
branchInfo.isLoop = blockUtility._startedBranch[1];
|
164 |
+
return blockUtility._startedBranch[0];
|
165 |
+
}
|
166 |
+
branchInfo.isLoop = branchInfo.defaultIsLoop;
|
167 |
+
return returnValue;
|
168 |
+
}
|
169 |
+
return returnValue;
|
170 |
+
};
|
171 |
+
|
172 |
+
// reset the stackframe
|
173 |
+
// we only ever use one stackframe at a time, so this shouldn't cause issues
|
174 |
+
thread.stackFrames[thread.stackFrames.length - 1].reuse(isWarp);
|
175 |
+
|
176 |
+
const executeBlock = () => {
|
177 |
+
blockUtility.init(thread, blockId, stackFrame, branchInfo);
|
178 |
+
return blockFunction(inputs, blockUtility, visualReport);
|
179 |
+
};
|
180 |
+
|
181 |
+
let returnValue = executeBlock();
|
182 |
+
if (isPromise(returnValue)) {
|
183 |
+
returnValue = finish(yield* waitPromise(returnValue));
|
184 |
+
if (useFlags) hasResumedFromPromise = true;
|
185 |
+
return returnValue;
|
186 |
+
}
|
187 |
+
|
188 |
+
if (thread.status === 1 /* STATUS_PROMISE_WAIT */ || thread.status === 4 /* STATUS_DONE */) {
|
189 |
+
// Something external is forcing us to stop
|
190 |
+
yield;
|
191 |
+
// Make up a return value because whatever is forcing us to stop can't specify one
|
192 |
+
return '';
|
193 |
+
}
|
194 |
+
|
195 |
+
while (thread.status === 2 /* STATUS_YIELD */ || thread.status === 3 /* STATUS_YIELD_TICK */) {
|
196 |
+
// Yielded threads will run next iteration.
|
197 |
+
if (thread.status === 2 /* STATUS_YIELD */) {
|
198 |
+
thread.status = 0; // STATUS_RUNNING
|
199 |
+
// Yield back to the event loop when stuck or not in warp mode.
|
200 |
+
if (!isWarp || isStuck()) {
|
201 |
+
yield;
|
202 |
+
}
|
203 |
+
} else {
|
204 |
+
// status is STATUS_YIELD_TICK, always yield to the event loop
|
205 |
+
yield;
|
206 |
+
}
|
207 |
+
|
208 |
+
returnValue = executeBlock();
|
209 |
+
if (isPromise(returnValue)) {
|
210 |
+
returnValue = finish(yield* waitPromise(returnValue));
|
211 |
+
if (useFlags) hasResumedFromPromise = true;
|
212 |
+
return returnValue;
|
213 |
+
}
|
214 |
+
|
215 |
+
if (thread.status === 1 /* STATUS_PROMISE_WAIT */ || thread.status === 4 /* STATUS_DONE */) {
|
216 |
+
yield;
|
217 |
+
return finish('');
|
218 |
+
}
|
219 |
+
}
|
220 |
+
return finish(returnValue);
|
221 |
+
}`;
|
222 |
+
|
223 |
+
/**
|
224 |
+
* @param {boolean} isLoop True if the block is a LOOP by default (can be overridden by startBranch() call)
|
225 |
+
* @returns {unknown} Branch info object for compatibility layer.
|
226 |
+
*/
|
227 |
+
runtimeFunctions.createBranchInfo = `const createBranchInfo = (isLoop) => ({
|
228 |
+
defaultIsLoop: isLoop,
|
229 |
+
isLoop: false,
|
230 |
+
branch: 0,
|
231 |
+
stackFrame: {},
|
232 |
+
onEnd: [],
|
233 |
+
});`;
|
234 |
+
|
235 |
+
/**
|
236 |
+
* End the current script.
|
237 |
+
*/
|
238 |
+
runtimeFunctions.retire = `const retire = () => {
|
239 |
+
const thread = globalState.thread;
|
240 |
+
thread.target.runtime.sequencer.retireThread(thread);
|
241 |
+
}`;
|
242 |
+
|
243 |
+
/**
|
244 |
+
* Scratch cast to boolean.
|
245 |
+
* Similar to Cast.toBoolean()
|
246 |
+
* @param {*} value The value to cast
|
247 |
+
* @returns {boolean} The value cast to a boolean
|
248 |
+
*/
|
249 |
+
runtimeFunctions.toBoolean = `const toBoolean = value => {
|
250 |
+
if (typeof value === 'boolean') {
|
251 |
+
return value;
|
252 |
+
}
|
253 |
+
if (typeof value === 'string') {
|
254 |
+
if (value === '' || value === '0' || value.toLowerCase() === 'false') {
|
255 |
+
return false;
|
256 |
+
}
|
257 |
+
return true;
|
258 |
+
}
|
259 |
+
return !!value;
|
260 |
+
}`;
|
261 |
+
|
262 |
+
/**
|
263 |
+
* If a number is very close to a whole number, round to that whole number.
|
264 |
+
* @param {number} value Value to round
|
265 |
+
* @returns {number} Rounded number or original number
|
266 |
+
*/
|
267 |
+
runtimeFunctions.limitPrecision = `const limitPrecision = value => {
|
268 |
+
const rounded = Math.round(value);
|
269 |
+
const delta = value - rounded;
|
270 |
+
return (Math.abs(delta) < 1e-9) ? rounded : value;
|
271 |
+
}`;
|
272 |
+
|
273 |
+
/**
|
274 |
+
* Used internally by the compare family of function.
|
275 |
+
* See similar method in cast.js.
|
276 |
+
* @param {*} val A value that evaluates to 0 in JS string-to-number conversation such as empty string, 0, or tab.
|
277 |
+
* @returns {boolean} True if the value should not be treated as the number zero.
|
278 |
+
*/
|
279 |
+
baseRuntime += `const isNotActuallyZero = val => {
|
280 |
+
if (typeof val !== 'string') return false;
|
281 |
+
for (let i = 0; i < val.length; i++) {
|
282 |
+
const code = val.charCodeAt(i);
|
283 |
+
if (code === 48 || code === 9) {
|
284 |
+
return false;
|
285 |
+
}
|
286 |
+
}
|
287 |
+
return true;
|
288 |
+
};`;
|
289 |
+
|
290 |
+
/**
|
291 |
+
* Determine if two values are equal.
|
292 |
+
* @param {*} v1 First value
|
293 |
+
* @param {*} v2 Second value
|
294 |
+
* @returns {boolean} true if v1 is equal to v2
|
295 |
+
*/
|
296 |
+
baseRuntime += `const compareEqualSlow = (v1, v2) => {
|
297 |
+
const n1 = +v1;
|
298 |
+
if (isNaN(n1) || (n1 === 0 && isNotActuallyZero(v1))) return ('' + v1).toLowerCase() === ('' + v2).toLowerCase();
|
299 |
+
const n2 = +v2;
|
300 |
+
if (isNaN(n2) || (n2 === 0 && isNotActuallyZero(v2))) return ('' + v1).toLowerCase() === ('' + v2).toLowerCase();
|
301 |
+
return n1 === n2;
|
302 |
+
};
|
303 |
+
const compareEqual = (v1, v2) => (typeof v1 === 'number' && typeof v2 === 'number' && !isNaN(v1) && !isNaN(v2) || v1 === v2) ? v1 === v2 : compareEqualSlow(v1, v2);`;
|
304 |
+
|
305 |
+
/**
|
306 |
+
* Determine if one value is greater than another.
|
307 |
+
* @param {*} v1 First value
|
308 |
+
* @param {*} v2 Second value
|
309 |
+
* @returns {boolean} true if v1 is greater than v2
|
310 |
+
*/
|
311 |
+
runtimeFunctions.compareGreaterThan = `const compareGreaterThanSlow = (v1, v2) => {
|
312 |
+
let n1 = +v1;
|
313 |
+
let n2 = +v2;
|
314 |
+
if (n1 === 0 && isNotActuallyZero(v1)) {
|
315 |
+
n1 = NaN;
|
316 |
+
} else if (n2 === 0 && isNotActuallyZero(v2)) {
|
317 |
+
n2 = NaN;
|
318 |
+
}
|
319 |
+
if (isNaN(n1) || isNaN(n2)) {
|
320 |
+
const s1 = ('' + v1).toLowerCase();
|
321 |
+
const s2 = ('' + v2).toLowerCase();
|
322 |
+
return s1 > s2;
|
323 |
+
}
|
324 |
+
return n1 > n2;
|
325 |
+
};
|
326 |
+
const compareGreaterThan = (v1, v2) => typeof v1 === 'number' && typeof v2 === 'number' && !isNaN(v1) ? v1 > v2 : compareGreaterThanSlow(v1, v2)`;
|
327 |
+
|
328 |
+
/**
|
329 |
+
* Determine if one value is less than another.
|
330 |
+
* @param {*} v1 First value
|
331 |
+
* @param {*} v2 Second value
|
332 |
+
* @returns {boolean} true if v1 is less than v2
|
333 |
+
*/
|
334 |
+
runtimeFunctions.compareLessThan = `const compareLessThanSlow = (v1, v2) => {
|
335 |
+
let n1 = +v1;
|
336 |
+
let n2 = +v2;
|
337 |
+
if (n1 === 0 && isNotActuallyZero(v1)) {
|
338 |
+
n1 = NaN;
|
339 |
+
} else if (n2 === 0 && isNotActuallyZero(v2)) {
|
340 |
+
n2 = NaN;
|
341 |
+
}
|
342 |
+
if (isNaN(n1) || isNaN(n2)) {
|
343 |
+
const s1 = ('' + v1).toLowerCase();
|
344 |
+
const s2 = ('' + v2).toLowerCase();
|
345 |
+
return s1 < s2;
|
346 |
+
}
|
347 |
+
return n1 < n2;
|
348 |
+
};
|
349 |
+
const compareLessThan = (v1, v2) => typeof v1 === 'number' && typeof v2 === 'number' && !isNaN(v2) ? v1 < v2 : compareLessThanSlow(v1, v2)`;
|
350 |
+
|
351 |
+
/**
|
352 |
+
* Generate a random integer.
|
353 |
+
* @param {number} low Lower bound
|
354 |
+
* @param {number} high Upper bound
|
355 |
+
* @returns {number} A random integer between low and high, inclusive.
|
356 |
+
*/
|
357 |
+
runtimeFunctions.randomInt = `const randomInt = (low, high) => low + Math.floor(Math.random() * ((high + 1) - low))`;
|
358 |
+
|
359 |
+
/**
|
360 |
+
* Generate a random float.
|
361 |
+
* @param {number} low Lower bound
|
362 |
+
* @param {number} high Upper bound
|
363 |
+
* @returns {number} A random floating point number between low and high.
|
364 |
+
*/
|
365 |
+
runtimeFunctions.randomFloat = `const randomFloat = (low, high) => (Math.random() * (high - low)) + low`;
|
366 |
+
|
367 |
+
/**
|
368 |
+
* Create and start a timer.
|
369 |
+
* @returns {Timer} A started timer
|
370 |
+
*/
|
371 |
+
runtimeFunctions.timer = `const timer = () => {
|
372 |
+
const t = new globalState.Timer({
|
373 |
+
now: () => globalState.thread.target.runtime.currentMSecs
|
374 |
+
});
|
375 |
+
t.start();
|
376 |
+
return t;
|
377 |
+
}`;
|
378 |
+
|
379 |
+
/**
|
380 |
+
* Returns the amount of days since January 1st, 2000.
|
381 |
+
* @returns {number} Days since 2000.
|
382 |
+
*/
|
383 |
+
// Date.UTC(2000, 0, 1) === 946684800000
|
384 |
+
// Hardcoding it is marginally faster
|
385 |
+
runtimeFunctions.daysSince2000 = `const daysSince2000 = () => (Date.now() - 946684800000) / (24 * 60 * 60 * 1000)`;
|
386 |
+
|
387 |
+
/**
|
388 |
+
* Determine distance to a sprite or point.
|
389 |
+
* @param {string} menu The name of the sprite or location to find.
|
390 |
+
* @returns {number} Distance to the point, or 10000 if it cannot be calculated.
|
391 |
+
*/
|
392 |
+
runtimeFunctions.distance = `const distance = menu => {
|
393 |
+
const thread = globalState.thread;
|
394 |
+
if (thread.target.isStage) return 10000;
|
395 |
+
|
396 |
+
let targetX = 0;
|
397 |
+
let targetY = 0;
|
398 |
+
if (menu === '_mouse_') {
|
399 |
+
targetX = thread.target.runtime.ioDevices.mouse.getScratchX();
|
400 |
+
targetY = thread.target.runtime.ioDevices.mouse.getScratchY();
|
401 |
+
} else {
|
402 |
+
const distTarget = thread.target.runtime.getSpriteTargetByName(menu);
|
403 |
+
if (!distTarget) return 10000;
|
404 |
+
targetX = distTarget.x;
|
405 |
+
targetY = distTarget.y;
|
406 |
+
}
|
407 |
+
|
408 |
+
const dx = thread.target.x - targetX;
|
409 |
+
const dy = thread.target.y - targetY;
|
410 |
+
return Math.sqrt((dx * dx) + (dy * dy));
|
411 |
+
}`;
|
412 |
+
|
413 |
+
/**
|
414 |
+
* Convert a Scratch list index to a JavaScript list index.
|
415 |
+
* "all" is not considered as a list index.
|
416 |
+
* Similar to Cast.toListIndex()
|
417 |
+
* @param {number} index Scratch list index.
|
418 |
+
* @param {number} length Length of the list.
|
419 |
+
* @returns {number} 0 based list index, or -1 if invalid.
|
420 |
+
*/
|
421 |
+
baseRuntime += `const listIndexSlow = (index, length) => {
|
422 |
+
if (index === 'last') {
|
423 |
+
return length - 1;
|
424 |
+
} else if (index === 'random' || index === 'any') {
|
425 |
+
if (length > 0) {
|
426 |
+
return (Math.random() * length) | 0;
|
427 |
+
}
|
428 |
+
return -1;
|
429 |
+
}
|
430 |
+
index = (+index || 0) | 0;
|
431 |
+
if (index < 1 || index > length) {
|
432 |
+
return -1;
|
433 |
+
}
|
434 |
+
return index - 1;
|
435 |
+
};
|
436 |
+
const listIndex = (index, length) => {
|
437 |
+
if (typeof index !== 'number') {
|
438 |
+
return listIndexSlow(index, length);
|
439 |
+
}
|
440 |
+
index = index | 0;
|
441 |
+
return index < 1 || index > length ? -1 : index - 1;
|
442 |
+
};`;
|
443 |
+
|
444 |
+
/**
|
445 |
+
* Get a value from a list.
|
446 |
+
* @param {Array} list The list
|
447 |
+
* @param {*} idx The 1-indexed index in the list.
|
448 |
+
* @returns {*} The list item, otherwise empty string if it does not exist.
|
449 |
+
*/
|
450 |
+
runtimeFunctions.listGet = `const listGet = (list, idx) => {
|
451 |
+
const index = listIndex(idx, list.length);
|
452 |
+
if (index === -1) {
|
453 |
+
return '';
|
454 |
+
}
|
455 |
+
return list[index];
|
456 |
+
}`;
|
457 |
+
|
458 |
+
/**
|
459 |
+
* Replace a value in a list.
|
460 |
+
* @param {import('../engine/variable')} list The list
|
461 |
+
* @param {*} idx List index, Scratch style.
|
462 |
+
* @param {*} value The new value.
|
463 |
+
*/
|
464 |
+
runtimeFunctions.listReplace = `const listReplace = (list, idx, value) => {
|
465 |
+
const index = listIndex(idx, list.value.length);
|
466 |
+
if (index === -1) {
|
467 |
+
return;
|
468 |
+
}
|
469 |
+
list.value[index] = value;
|
470 |
+
list._monitorUpToDate = false;
|
471 |
+
}`;
|
472 |
+
|
473 |
+
/**
|
474 |
+
* Insert a value in a list.
|
475 |
+
* @param {import('../engine/variable')} list The list.
|
476 |
+
* @param {*} idx The Scratch index in the list.
|
477 |
+
* @param {*} value The value to insert.
|
478 |
+
*/
|
479 |
+
runtimeFunctions.listInsert = `const listInsert = (list, idx, value) => {
|
480 |
+
const index = listIndex(idx, list.value.length + 1);
|
481 |
+
if (index === -1) {
|
482 |
+
return;
|
483 |
+
}
|
484 |
+
list.value.splice(index, 0, value);
|
485 |
+
list._monitorUpToDate = false;
|
486 |
+
}`;
|
487 |
+
|
488 |
+
/**
|
489 |
+
* Delete a value from a list.
|
490 |
+
* @param {import('../engine/variable')} list The list.
|
491 |
+
* @param {*} idx The Scratch index in the list.
|
492 |
+
*/
|
493 |
+
runtimeFunctions.listDelete = `const listDelete = (list, idx) => {
|
494 |
+
if (idx === 'all') {
|
495 |
+
list.value = [];
|
496 |
+
return;
|
497 |
+
}
|
498 |
+
const index = listIndex(idx, list.value.length);
|
499 |
+
if (index === -1) {
|
500 |
+
return;
|
501 |
+
}
|
502 |
+
list.value.splice(index, 1);
|
503 |
+
list._monitorUpToDate = false;
|
504 |
+
}`;
|
505 |
+
|
506 |
+
/**
|
507 |
+
* Return whether a list contains a value.
|
508 |
+
* @param {import('../engine/variable')} list The list.
|
509 |
+
* @param {*} item The value to search for.
|
510 |
+
* @returns {boolean} True if the list contains the item
|
511 |
+
*/
|
512 |
+
runtimeFunctions.listContains = `const listContains = (list, item) => {
|
513 |
+
// TODO: evaluate whether indexOf is worthwhile here
|
514 |
+
if (list.value.indexOf(item) !== -1) {
|
515 |
+
return true;
|
516 |
+
}
|
517 |
+
for (let i = 0; i < list.value.length; i++) {
|
518 |
+
if (compareEqual(list.value[i], item)) {
|
519 |
+
return true;
|
520 |
+
}
|
521 |
+
}
|
522 |
+
return false;
|
523 |
+
}`;
|
524 |
+
|
525 |
+
/**
|
526 |
+
* pm: Returns whether a list contains a value, using Array.some
|
527 |
+
* @param {import('../engine/variable')} list The list.
|
528 |
+
* @param {*} item The value to search for.
|
529 |
+
* @returns {boolean} True if the list contains the item
|
530 |
+
*/
|
531 |
+
runtimeFunctions.listContainsFastest = `const listContainsFastest = (list, item) => {
|
532 |
+
return list.value.some(litem => compareEqual(litem, item));
|
533 |
+
}`;
|
534 |
+
|
535 |
+
/**
|
536 |
+
* Find the 1-indexed index of an item in a list.
|
537 |
+
* @param {import('../engine/variable')} list The list.
|
538 |
+
* @param {*} item The item to search for
|
539 |
+
* @returns {number} The 1-indexed index of the item in the list, otherwise 0
|
540 |
+
*/
|
541 |
+
runtimeFunctions.listIndexOf = `const listIndexOf = (list, item) => {
|
542 |
+
for (let i = 0; i < list.value.length; i++) {
|
543 |
+
if (compareEqual(list.value[i], item)) {
|
544 |
+
return i + 1;
|
545 |
+
}
|
546 |
+
}
|
547 |
+
return 0;
|
548 |
+
}`;
|
549 |
+
|
550 |
+
/**
|
551 |
+
* Get the stringified form of a list.
|
552 |
+
* @param {import('../engine/variable')} list The list.
|
553 |
+
* @returns {string} Stringified form of the list.
|
554 |
+
*/
|
555 |
+
runtimeFunctions.listContents = `const listContents = list => {
|
556 |
+
for (let i = 0; i < list.value.length; i++) {
|
557 |
+
const listItem = list.value[i];
|
558 |
+
// this is an intentional break from what scratch 3 does to address our automatic string -> number conversions
|
559 |
+
// it fixes more than it breaks
|
560 |
+
if ((listItem + '').length !== 1) {
|
561 |
+
return list.value.join(' ');
|
562 |
+
}
|
563 |
+
}
|
564 |
+
return list.value.join('');
|
565 |
+
}`;
|
566 |
+
|
567 |
+
/**
|
568 |
+
* Convert a color to an RGB list
|
569 |
+
* @param {*} color The color value to convert
|
570 |
+
* @return {Array.<number>} [r,g,b], values between 0-255.
|
571 |
+
*/
|
572 |
+
runtimeFunctions.colorToList = `const colorToList = color => globalState.Cast.toRgbColorList(color)`;
|
573 |
+
|
574 |
+
/**
|
575 |
+
* Implements Scratch modulo (floored division instead of truncated division)
|
576 |
+
* @param {number} n Number
|
577 |
+
* @param {number} modulus Base
|
578 |
+
* @returns {number} n % modulus (floored division)
|
579 |
+
*/
|
580 |
+
runtimeFunctions.mod = `const mod = (n, modulus) => {
|
581 |
+
let result = n % modulus;
|
582 |
+
if (result / modulus < 0) result += modulus;
|
583 |
+
return result;
|
584 |
+
}`;
|
585 |
+
|
586 |
+
/**
|
587 |
+
* Implements Scratch tangent.
|
588 |
+
* @param {number} angle Angle in degrees.
|
589 |
+
* @returns {number} value of tangent or Infinity or -Infinity
|
590 |
+
*/
|
591 |
+
runtimeFunctions.tan = `const tan = (angle) => {
|
592 |
+
switch (angle % 360) {
|
593 |
+
case -270: case 90: return Infinity;
|
594 |
+
case -90: case 270: return -Infinity;
|
595 |
+
}
|
596 |
+
return Math.round(Math.tan((Math.PI * angle) / 180) * 1e10) / 1e10;
|
597 |
+
}`;
|
598 |
+
|
599 |
+
runtimeFunctions.resolveImageURL = `const resolveImageURL = imgURL =>
|
600 |
+
typeof imgURL === 'object' && imgURL.type === 'canvas'
|
601 |
+
? Promise.resolve(imgURL.canvas)
|
602 |
+
: new Promise(resolve => {
|
603 |
+
const image = new Image();
|
604 |
+
image.crossOrigin = "anonymous";
|
605 |
+
image.onload = resolve(image);
|
606 |
+
image.onerror = resolve; // ignore loading errors lol!
|
607 |
+
image.src = ''+imgURL;
|
608 |
+
})`;
|
609 |
+
|
610 |
+
runtimeFunctions.parseJSONSafe = `const parseJSONSafe = json => {
|
611 |
+
try return JSON.parse(json)
|
612 |
+
catch return {}
|
613 |
+
}`;
|
614 |
+
|
615 |
+
runtimeFunctions._resolveKeyPath = `const _resolveKeyPath = (obj, keyPath) => {
|
616 |
+
const path = keyPath.matchAll(/(\\.|^)(?<key>[^.[]+)|\\[(?<litkey>(\\\\\\]|\\\\|[^]])+)\\]/g);
|
617 |
+
let top = obj;
|
618 |
+
let pre;
|
619 |
+
let tok;
|
620 |
+
let key;
|
621 |
+
while (!(tok = path.next()).done) {
|
622 |
+
key = tok.value.groups.key ?? tok.value.groups.litKey.replaceAll('\\\\\\\\', '\\\\').replaceAll('\\\\]', ']');
|
623 |
+
pre = top;
|
624 |
+
top = top?.get?.(key) ?? top?.[key];
|
625 |
+
if (top === undefined) return [obj, keyPath];
|
626 |
+
}
|
627 |
+
return [pre, key];
|
628 |
+
}`;
|
629 |
+
|
630 |
+
runtimeFunctions.get = `const get = (obj, keyPath) => {
|
631 |
+
const [root, key] = _resolveKeyPath(obj, keyPath);
|
632 |
+
return typeof root === 'undefined'
|
633 |
+
? ''
|
634 |
+
: root.get?.(key) ?? root[key];
|
635 |
+
}`;
|
636 |
+
|
637 |
+
runtimeFunctions.set = `const set = (obj, keyPath, val) => {
|
638 |
+
const [root, key] = _resolveKeyPath(obj, keyPath);
|
639 |
+
return typeof root === 'undefined'
|
640 |
+
? ''
|
641 |
+
: root.set?.(key) ?? (root[key] = val);
|
642 |
+
}`;
|
643 |
+
|
644 |
+
runtimeFunctions.remove = `const remove = (obj, keyPath) => {
|
645 |
+
const [root, key] = _resolveKeyPath(obj, keyPath);
|
646 |
+
return typeof root === 'undefined'
|
647 |
+
? ''
|
648 |
+
: root.delete?.(key) ?? root.remove?.(key) ?? (delete root[key]);
|
649 |
+
}`;
|
650 |
+
|
651 |
+
runtimeFunctions.includes = `const includes = (obj, keyPath) => {
|
652 |
+
const [root, key] = _resolveKeyPath(obj, keyPath);
|
653 |
+
return typeof root === 'undefined'
|
654 |
+
? ''
|
655 |
+
: root.has?.(key) ?? (key in root);
|
656 |
+
}`;
|
657 |
+
|
658 |
+
/**
|
659 |
+
* Step a compiled thread.
|
660 |
+
* @param {Thread} thread The thread to step.
|
661 |
+
*/
|
662 |
+
const execute = thread => {
|
663 |
+
globalState.thread = thread;
|
664 |
+
thread.generator.next();
|
665 |
+
};
|
666 |
+
|
667 |
+
const threadStack = [];
|
668 |
+
const saveGlobalState = () => {
|
669 |
+
threadStack.push(globalState.thread);
|
670 |
+
};
|
671 |
+
const restoreGlobalState = () => {
|
672 |
+
globalState.thread = threadStack.pop();
|
673 |
+
};
|
674 |
+
|
675 |
+
const insertRuntime = source => {
|
676 |
+
let result = baseRuntime;
|
677 |
+
for (const functionName of Object.keys(runtimeFunctions)) {
|
678 |
+
if (source.includes(functionName)) {
|
679 |
+
result += `${runtimeFunctions[functionName]};`;
|
680 |
+
}
|
681 |
+
}
|
682 |
+
if (result.includes('executeInCompatibilityLayer') && !result.includes('const waitPromise')) {
|
683 |
+
result = result.replace('let hasResumedFromPromise = false;', `let hasResumedFromPromise = false;\n${runtimeFunctions.waitPromise}`);
|
684 |
+
}
|
685 |
+
if (result.includes('_resolveKeyPath') && !result.includes('const _resolveKeyPath')) {
|
686 |
+
result = runtimeFunctions._resolveKeyPath + ';' + result;
|
687 |
+
}
|
688 |
+
result += `return ${source}`;
|
689 |
+
return result;
|
690 |
+
};
|
691 |
+
|
692 |
+
/**
|
693 |
+
* Evaluate arbitrary JS in the context of the runtime.
|
694 |
+
* @param {string} source The string to evaluate.
|
695 |
+
* @returns {*} The result of evaluating the string.
|
696 |
+
*/
|
697 |
+
const scopedEval = source => {
|
698 |
+
const withRuntime = insertRuntime(source);
|
699 |
+
try {
|
700 |
+
return new Function('globalState', withRuntime)(globalState);
|
701 |
+
} catch (e) {
|
702 |
+
globalState.log.error('was unable to compile script', withRuntime);
|
703 |
+
console.log(e);
|
704 |
+
throw e;
|
705 |
+
}
|
706 |
+
};
|
707 |
+
|
708 |
+
execute.scopedEval = scopedEval;
|
709 |
+
execute.runtimeFunctions = runtimeFunctions;
|
710 |
+
execute.saveGlobalState = saveGlobalState;
|
711 |
+
execute.restoreGlobalState = restoreGlobalState;
|
712 |
+
// not actually used, this is an export for extensions
|
713 |
+
execute.globalState = globalState;
|
714 |
+
|
715 |
+
module.exports = execute;
|
src/compiler/jsgen.js
ADDED
@@ -0,0 +1,2114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const log = require('../util/log');
|
2 |
+
const Cast = require('../util/cast');
|
3 |
+
const BlockType = require('../extension-support/block-type');
|
4 |
+
const VariablePool = require('./variable-pool');
|
5 |
+
const jsexecute = require('./jsexecute');
|
6 |
+
const environment = require('./environment');
|
7 |
+
|
8 |
+
// Imported for JSDoc types, not to actually use
|
9 |
+
// eslint-disable-next-line no-unused-vars
|
10 |
+
const {IntermediateScript, IntermediateRepresentation} = require('./intermediate');
|
11 |
+
|
12 |
+
/**
|
13 |
+
* @fileoverview Convert intermediate representations to JavaScript functions.
|
14 |
+
*/
|
15 |
+
|
16 |
+
/* eslint-disable max-len */
|
17 |
+
/* eslint-disable prefer-template */
|
18 |
+
|
19 |
+
const sanitize = string => {
|
20 |
+
if (typeof string !== 'string') {
|
21 |
+
log.warn(`sanitize got unexpected type: ${typeof string}`);
|
22 |
+
string = '' + string;
|
23 |
+
}
|
24 |
+
return JSON.stringify(string).slice(1, -1);
|
25 |
+
};
|
26 |
+
|
27 |
+
const TYPE_NUMBER = 1;
|
28 |
+
const TYPE_STRING = 2;
|
29 |
+
const TYPE_BOOLEAN = 3;
|
30 |
+
const TYPE_UNKNOWN = 4;
|
31 |
+
const TYPE_NUMBER_NAN = 5;
|
32 |
+
|
33 |
+
|
34 |
+
// Pen-related constants
|
35 |
+
const PEN_EXT = 'runtime.ext_pen';
|
36 |
+
const PEN_STATE = `${PEN_EXT}._getPenState(target)`;
|
37 |
+
|
38 |
+
/**
|
39 |
+
* Variable pool used for factory function names.
|
40 |
+
*/
|
41 |
+
const factoryNameVariablePool = new VariablePool('factory');
|
42 |
+
|
43 |
+
/**
|
44 |
+
* Variable pool used for generated functions (non-generator)
|
45 |
+
*/
|
46 |
+
const functionNameVariablePool = new VariablePool('fun');
|
47 |
+
|
48 |
+
/**
|
49 |
+
* Variable pool used for generated generator functions.
|
50 |
+
*/
|
51 |
+
const generatorNameVariablePool = new VariablePool('gen');
|
52 |
+
|
53 |
+
/**
|
54 |
+
* @typedef Input
|
55 |
+
* @property {() => string} asNumber
|
56 |
+
* @property {() => string} asNumberOrNaN
|
57 |
+
* @property {() => string} asString
|
58 |
+
* @property {() => string} asBoolean
|
59 |
+
* @property {() => string} asColor
|
60 |
+
* @property {() => string} asUnknown
|
61 |
+
* @property {() => string} asSafe
|
62 |
+
* @property {() => boolean} isAlwaysNumber
|
63 |
+
* @property {() => boolean} isAlwaysNumberOrNaN
|
64 |
+
* @property {() => boolean} isNeverNumber
|
65 |
+
*/
|
66 |
+
|
67 |
+
/**
|
68 |
+
* @implements {Input}
|
69 |
+
*/
|
70 |
+
class TypedInput {
|
71 |
+
constructor (source, type) {
|
72 |
+
this.source = source;
|
73 |
+
this.type = type;
|
74 |
+
}
|
75 |
+
|
76 |
+
asNumber () {
|
77 |
+
if (this.type === TYPE_NUMBER) return this.source;
|
78 |
+
if (this.type === TYPE_NUMBER_NAN) return `(${this.source} || 0)`;
|
79 |
+
return `(+${this.source} || 0)`;
|
80 |
+
}
|
81 |
+
|
82 |
+
asNumberOrNaN () {
|
83 |
+
if (this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN) return this.source;
|
84 |
+
return `(+${this.source})`;
|
85 |
+
}
|
86 |
+
|
87 |
+
asString () {
|
88 |
+
if (this.type === TYPE_STRING) return this.source;
|
89 |
+
return `("" + ${this.source})`;
|
90 |
+
}
|
91 |
+
|
92 |
+
asBoolean () {
|
93 |
+
if (this.type === TYPE_UNKNOWN) return `toBoolean(${this.source})`;
|
94 |
+
if (this.type === TYPE_STRING) return `${this.source} === 'false' || ${this.source} === '0' ? false : true`;
|
95 |
+
if (this.type === TYPE_NUMBER) return `${this.source} !== 0`;
|
96 |
+
if (this.type === TYPE_NUMBER_NAN) return `(${this.source} || 0) !== 0`;
|
97 |
+
|
98 |
+
return this.source;
|
99 |
+
}
|
100 |
+
|
101 |
+
asColor () {
|
102 |
+
return this.asUnknown();
|
103 |
+
}
|
104 |
+
|
105 |
+
asUnknown () {
|
106 |
+
return this.source;
|
107 |
+
}
|
108 |
+
|
109 |
+
asSafe () {
|
110 |
+
return this.asUnknown();
|
111 |
+
}
|
112 |
+
|
113 |
+
isAlwaysNumber () {
|
114 |
+
return this.type === TYPE_NUMBER;
|
115 |
+
}
|
116 |
+
|
117 |
+
isAlwaysNumberOrNaN () {
|
118 |
+
return this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN;
|
119 |
+
}
|
120 |
+
|
121 |
+
isNeverNumber () {
|
122 |
+
return false;
|
123 |
+
}
|
124 |
+
}
|
125 |
+
|
126 |
+
/**
|
127 |
+
* @implements {Input}
|
128 |
+
*/
|
129 |
+
class ConstantInput {
|
130 |
+
constructor (constantValue, safe) {
|
131 |
+
this.constantValue = constantValue;
|
132 |
+
this.safe = safe;
|
133 |
+
}
|
134 |
+
|
135 |
+
asNumber () {
|
136 |
+
// Compute at compilation time
|
137 |
+
const numberValue = +this.constantValue;
|
138 |
+
if (numberValue) {
|
139 |
+
// It's important that we use the number's stringified value and not the constant value
|
140 |
+
// Using the constant value allows numbers such as "010" to be interpreted as 8 (or SyntaxError in strict mode) instead of 10.
|
141 |
+
return numberValue.toString();
|
142 |
+
}
|
143 |
+
// numberValue is one of 0, -0, or NaN
|
144 |
+
if (Object.is(numberValue, -0)) {
|
145 |
+
return '-0';
|
146 |
+
}
|
147 |
+
return '0';
|
148 |
+
}
|
149 |
+
|
150 |
+
asNumberOrNaN () {
|
151 |
+
return this.asNumber();
|
152 |
+
}
|
153 |
+
|
154 |
+
asString () {
|
155 |
+
return `"${sanitize('' + this.constantValue)}"`;
|
156 |
+
}
|
157 |
+
|
158 |
+
asBoolean () {
|
159 |
+
// Compute at compilation time
|
160 |
+
return Cast.toBoolean(this.constantValue).toString();
|
161 |
+
}
|
162 |
+
|
163 |
+
asColor () {
|
164 |
+
// Attempt to parse hex code at compilation time
|
165 |
+
if (/^#[0-9a-f]{6,8}$/i.test(this.constantValue)) {
|
166 |
+
const hex = this.constantValue.slice(1);
|
167 |
+
return Number.parseInt(hex, 16).toString();
|
168 |
+
}
|
169 |
+
return this.asUnknown();
|
170 |
+
}
|
171 |
+
|
172 |
+
asUnknown () {
|
173 |
+
// Attempt to convert strings to numbers if it is unlikely to break things
|
174 |
+
if (typeof this.constantValue === 'number') {
|
175 |
+
// todo: handle NaN?
|
176 |
+
return this.constantValue;
|
177 |
+
}
|
178 |
+
const numberValue = +this.constantValue;
|
179 |
+
if (numberValue.toString() === this.constantValue) {
|
180 |
+
return this.constantValue;
|
181 |
+
}
|
182 |
+
return this.asString();
|
183 |
+
}
|
184 |
+
|
185 |
+
asSafe () {
|
186 |
+
if (this.safe) {
|
187 |
+
return this.asUnknown();
|
188 |
+
}
|
189 |
+
return this.asString();
|
190 |
+
}
|
191 |
+
|
192 |
+
isAlwaysNumber () {
|
193 |
+
const value = +this.constantValue;
|
194 |
+
if (Number.isNaN(value)) {
|
195 |
+
return false;
|
196 |
+
}
|
197 |
+
// Empty strings evaluate to 0 but should not be considered a number.
|
198 |
+
if (value === 0) {
|
199 |
+
return this.constantValue.toString().trim() !== '';
|
200 |
+
}
|
201 |
+
return true;
|
202 |
+
}
|
203 |
+
|
204 |
+
isAlwaysNumberOrNaN () {
|
205 |
+
return this.isAlwaysNumber();
|
206 |
+
}
|
207 |
+
|
208 |
+
isNeverNumber () {
|
209 |
+
return Number.isNaN(+this.constantValue);
|
210 |
+
}
|
211 |
+
}
|
212 |
+
|
213 |
+
/**
|
214 |
+
* @implements {Input}
|
215 |
+
*/
|
216 |
+
class VariableInput {
|
217 |
+
constructor (source) {
|
218 |
+
this.source = source;
|
219 |
+
this.type = TYPE_UNKNOWN;
|
220 |
+
/**
|
221 |
+
* The value this variable was most recently set to, if any.
|
222 |
+
* @type {Input}
|
223 |
+
* @private
|
224 |
+
*/
|
225 |
+
this._value = null;
|
226 |
+
}
|
227 |
+
|
228 |
+
/**
|
229 |
+
* @param {Input} input The input this variable was most recently set to.
|
230 |
+
*/
|
231 |
+
setInput (input) {
|
232 |
+
if (input instanceof VariableInput) {
|
233 |
+
// When being set to another variable, extract the value it was set to.
|
234 |
+
// Otherwise, you may end up with infinite recursion in analysis methods when a variable is set to itself.
|
235 |
+
if (input._value) {
|
236 |
+
input = input._value;
|
237 |
+
} else {
|
238 |
+
this.type = TYPE_UNKNOWN;
|
239 |
+
this._value = null;
|
240 |
+
return;
|
241 |
+
}
|
242 |
+
}
|
243 |
+
this._value = input;
|
244 |
+
if (input instanceof TypedInput) {
|
245 |
+
this.type = input.type;
|
246 |
+
} else {
|
247 |
+
this.type = TYPE_UNKNOWN;
|
248 |
+
}
|
249 |
+
}
|
250 |
+
|
251 |
+
asNumber () {
|
252 |
+
if (this.type === TYPE_NUMBER) return this.source;
|
253 |
+
if (this.type === TYPE_NUMBER_NAN) return `(${this.source} || 0)`;
|
254 |
+
return `(+${this.source} || 0)`;
|
255 |
+
}
|
256 |
+
|
257 |
+
asNumberOrNaN () {
|
258 |
+
if (this.type === TYPE_NUMBER || this.type === TYPE_NUMBER_NAN) return this.source;
|
259 |
+
return `(+${this.source})`;
|
260 |
+
}
|
261 |
+
|
262 |
+
asString () {
|
263 |
+
if (this.type === TYPE_STRING) return this.source;
|
264 |
+
return `("" + ${this.source})`;
|
265 |
+
}
|
266 |
+
|
267 |
+
asBoolean () {
|
268 |
+
if (this.type === TYPE_BOOLEAN) return this.source;
|
269 |
+
return `toBoolean(${this.source})`;
|
270 |
+
}
|
271 |
+
|
272 |
+
asColor () {
|
273 |
+
return this.asUnknown();
|
274 |
+
}
|
275 |
+
|
276 |
+
asUnknown () {
|
277 |
+
return this.source;
|
278 |
+
}
|
279 |
+
|
280 |
+
asSafe () {
|
281 |
+
return this.asUnknown();
|
282 |
+
}
|
283 |
+
|
284 |
+
isAlwaysNumber () {
|
285 |
+
if (this._value) {
|
286 |
+
return this._value.isAlwaysNumber();
|
287 |
+
}
|
288 |
+
return false;
|
289 |
+
}
|
290 |
+
|
291 |
+
isAlwaysNumberOrNaN () {
|
292 |
+
if (this._value) {
|
293 |
+
return this._value.isAlwaysNumberOrNaN();
|
294 |
+
}
|
295 |
+
return false;
|
296 |
+
}
|
297 |
+
|
298 |
+
isNeverNumber () {
|
299 |
+
if (this._value) {
|
300 |
+
return this._value.isNeverNumber();
|
301 |
+
}
|
302 |
+
return false;
|
303 |
+
}
|
304 |
+
}
|
305 |
+
|
306 |
+
const getNamesOfCostumesAndSounds = runtime => {
|
307 |
+
const result = new Set();
|
308 |
+
for (const target of runtime.targets) {
|
309 |
+
if (target.isOriginal) {
|
310 |
+
const sprite = target.sprite;
|
311 |
+
for (const costume of sprite.costumes) {
|
312 |
+
result.add(costume.name);
|
313 |
+
}
|
314 |
+
for (const sound of sprite.sounds) {
|
315 |
+
result.add(sound.name);
|
316 |
+
}
|
317 |
+
}
|
318 |
+
}
|
319 |
+
return result;
|
320 |
+
};
|
321 |
+
|
322 |
+
const isSafeConstantForEqualsOptimization = input => {
|
323 |
+
const numberValue = +input.constantValue;
|
324 |
+
// Do not optimize 0
|
325 |
+
if (!numberValue) {
|
326 |
+
return false;
|
327 |
+
}
|
328 |
+
// Do not optimize numbers when the original form does not match
|
329 |
+
return numberValue.toString() === input.constantValue.toString();
|
330 |
+
};
|
331 |
+
|
332 |
+
/**
|
333 |
+
* A frame contains some information about the current substack being compiled.
|
334 |
+
*/
|
335 |
+
class Frame {
|
336 |
+
constructor (isLoop, parentKind) {
|
337 |
+
/**
|
338 |
+
* Whether the current stack runs in a loop (while, for)
|
339 |
+
* @type {boolean}
|
340 |
+
* @readonly
|
341 |
+
*/
|
342 |
+
this.isLoop = isLoop;
|
343 |
+
|
344 |
+
/**
|
345 |
+
* Whether the current block is the last block in the stack.
|
346 |
+
* @type {boolean}
|
347 |
+
*/
|
348 |
+
this.isLastBlock = false;
|
349 |
+
|
350 |
+
/**
|
351 |
+
* General important data that needs to be carried down from other threads.
|
352 |
+
* @type {boolean}
|
353 |
+
*/
|
354 |
+
this.importantData = {
|
355 |
+
parents: [parentKind]
|
356 |
+
};
|
357 |
+
if (isLoop)
|
358 |
+
this.importantData.containedByLoop = isLoop;
|
359 |
+
|
360 |
+
/**
|
361 |
+
* the block who created this frame
|
362 |
+
* @type {string}
|
363 |
+
* @readonly
|
364 |
+
*/
|
365 |
+
this.parent = parentKind;
|
366 |
+
}
|
367 |
+
|
368 |
+
assignData(obj) {
|
369 |
+
if (obj instanceof Frame) {
|
370 |
+
obj = obj.importantData;
|
371 |
+
obj.parents = obj.parents.concat(this.importantData.parents);
|
372 |
+
}
|
373 |
+
Object.assign(this.importantData, obj);
|
374 |
+
}
|
375 |
+
}
|
376 |
+
|
377 |
+
class JSGenerator {
|
378 |
+
/**
|
379 |
+
* @param {IntermediateScript} script
|
380 |
+
* @param {IntermediateRepresentation} ir
|
381 |
+
* @param {Target} target
|
382 |
+
*/
|
383 |
+
constructor (script, ir, target) {
|
384 |
+
this.script = script;
|
385 |
+
this.ir = ir;
|
386 |
+
this.target = target;
|
387 |
+
this.source = '';
|
388 |
+
|
389 |
+
/**
|
390 |
+
* @type {Object.<string, VariableInput>}
|
391 |
+
*/
|
392 |
+
this.variableInputs = {};
|
393 |
+
|
394 |
+
this.isWarp = script.isWarp;
|
395 |
+
this.isOptimized = script.isOptimized;
|
396 |
+
this.optimizationUtil = script.optimizationUtil;
|
397 |
+
this.isProcedure = script.isProcedure;
|
398 |
+
this.warpTimer = script.warpTimer;
|
399 |
+
|
400 |
+
/**
|
401 |
+
* Stack of frames, most recent is last item.
|
402 |
+
* @type {Frame[]}
|
403 |
+
*/
|
404 |
+
this.frames = [];
|
405 |
+
|
406 |
+
/**
|
407 |
+
* The current Frame.
|
408 |
+
* @type {Frame}
|
409 |
+
*/
|
410 |
+
this.currentFrame = null;
|
411 |
+
|
412 |
+
this.namesOfCostumesAndSounds = getNamesOfCostumesAndSounds(target.runtime);
|
413 |
+
|
414 |
+
this.localVariables = new VariablePool('a');
|
415 |
+
this._setupVariablesPool = new VariablePool('b');
|
416 |
+
this._setupVariables = {};
|
417 |
+
|
418 |
+
this.descendedIntoModulo = false;
|
419 |
+
this.isInHat = false;
|
420 |
+
|
421 |
+
this.debug = this.target.runtime.debug;
|
422 |
+
}
|
423 |
+
|
424 |
+
static exports = {
|
425 |
+
TypedInput,
|
426 |
+
ConstantInput,
|
427 |
+
VariableInput,
|
428 |
+
Frame,
|
429 |
+
VariablePool,
|
430 |
+
TYPE_NUMBER,
|
431 |
+
TYPE_STRING,
|
432 |
+
TYPE_BOOLEAN,
|
433 |
+
TYPE_UNKNOWN,
|
434 |
+
TYPE_NUMBER_NAN,
|
435 |
+
PEN_EXT,
|
436 |
+
PEN_STATE,
|
437 |
+
factoryNameVariablePool,
|
438 |
+
functionNameVariablePool,
|
439 |
+
generatorNameVariablePool
|
440 |
+
}
|
441 |
+
|
442 |
+
static _extensionJSInfo = {};
|
443 |
+
static setExtensionJs(id, data) {
|
444 |
+
JSGenerator._extensionJSInfo[id] = data;
|
445 |
+
}
|
446 |
+
static hasExtensionJs(id) {
|
447 |
+
return Boolean(JSGenerator._extensionJSInfo[id]);
|
448 |
+
}
|
449 |
+
static getExtensionJs(id) {
|
450 |
+
return JSGenerator._extensionJSInfo[id];
|
451 |
+
}
|
452 |
+
|
453 |
+
static getExtensionImports() {
|
454 |
+
// used so extensions have things like the Frame class
|
455 |
+
return {
|
456 |
+
Frame: Frame,
|
457 |
+
TypedInput: TypedInput,
|
458 |
+
VariableInput: VariableInput,
|
459 |
+
ConstantInput: ConstantInput,
|
460 |
+
VariablePool: VariablePool,
|
461 |
+
|
462 |
+
TYPE_NUMBER: TYPE_NUMBER,
|
463 |
+
TYPE_STRING: TYPE_STRING,
|
464 |
+
TYPE_BOOLEAN: TYPE_BOOLEAN,
|
465 |
+
TYPE_UNKNOWN: TYPE_UNKNOWN,
|
466 |
+
TYPE_NUMBER_NAN: TYPE_NUMBER_NAN
|
467 |
+
};
|
468 |
+
}
|
469 |
+
|
470 |
+
/**
|
471 |
+
* Enter a new frame
|
472 |
+
* @param {Frame} frame New frame.
|
473 |
+
*/
|
474 |
+
pushFrame (frame) {
|
475 |
+
this.frames.push(frame);
|
476 |
+
this.currentFrame = frame;
|
477 |
+
}
|
478 |
+
|
479 |
+
/**
|
480 |
+
* Exit the current frame
|
481 |
+
*/
|
482 |
+
popFrame () {
|
483 |
+
this.frames.pop();
|
484 |
+
this.currentFrame = this.frames[this.frames.length - 1];
|
485 |
+
}
|
486 |
+
|
487 |
+
/**
|
488 |
+
* @returns {boolean} true if the current block is the last command of a loop
|
489 |
+
*/
|
490 |
+
isLastBlockInLoop () {
|
491 |
+
for (let i = this.frames.length - 1; i >= 0; i--) {
|
492 |
+
const frame = this.frames[i];
|
493 |
+
if (!frame.isLastBlock) {
|
494 |
+
return false;
|
495 |
+
}
|
496 |
+
if (frame.isLoop) {
|
497 |
+
return true;
|
498 |
+
}
|
499 |
+
}
|
500 |
+
return false;
|
501 |
+
}
|
502 |
+
|
503 |
+
/**
|
504 |
+
* @param {object} node Input node to compile.
|
505 |
+
* @param {boolean} visualReport if this is being called to get visual reporter content
|
506 |
+
* @returns {Input} Compiled input.
|
507 |
+
*/
|
508 |
+
descendInput (node, visualReport = false) {
|
509 |
+
// check if we have extension js for this kind
|
510 |
+
const extensionId = String(node.kind).split('.')[0];
|
511 |
+
const blockId = String(node.kind).replace(extensionId + '.', '');
|
512 |
+
if (JSGenerator.hasExtensionJs(extensionId) && JSGenerator.getExtensionJs(extensionId)[blockId]) {
|
513 |
+
// this is an extension block that wants to be compiled
|
514 |
+
const imports = JSGenerator.getExtensionImports();
|
515 |
+
const jsFunc = JSGenerator.getExtensionJs(extensionId)[blockId];
|
516 |
+
// return the input
|
517 |
+
let input = null;
|
518 |
+
try {
|
519 |
+
input = jsFunc(node, this, imports);
|
520 |
+
} catch (err) {
|
521 |
+
log.warn(extensionId + '_' + blockId, 'failed to compile JavaScript;', err);
|
522 |
+
}
|
523 |
+
// log.log(input);
|
524 |
+
return input;
|
525 |
+
}
|
526 |
+
|
527 |
+
switch (node.kind) {
|
528 |
+
case 'args.boolean':
|
529 |
+
return new TypedInput(`toBoolean(p${node.index})`, TYPE_BOOLEAN);
|
530 |
+
case 'args.stringNumber':
|
531 |
+
return new TypedInput(`p${node.index}`, TYPE_UNKNOWN);
|
532 |
+
|
533 |
+
case 'compat':
|
534 |
+
// Compatibility layer inputs never use flags.
|
535 |
+
// log.log('compat')
|
536 |
+
return new TypedInput(`(${this.generateCompatibilityLayerCall(node, false, null, visualReport)})`, TYPE_UNKNOWN);
|
537 |
+
|
538 |
+
case 'constant':
|
539 |
+
return this.safeConstantInput(node.value);
|
540 |
+
case 'counter.get':
|
541 |
+
return new TypedInput('runtime.ext_scratch3_control._counter', TYPE_NUMBER);
|
542 |
+
case 'control.error':
|
543 |
+
return new TypedInput('runtime.ext_scratch3_control._error', TYPE_STRING);
|
544 |
+
case 'control.isclone':
|
545 |
+
return new TypedInput('(!target.isOriginal)', TYPE_BOOLEAN);
|
546 |
+
case 'math.polygon':
|
547 |
+
let points = JSON.stringify(node.points.map((point, num) => ({x: `x${num}`, y: `y${num}`})));
|
548 |
+
for (let num = 0; num < node.points.length; num++) {
|
549 |
+
const point = node.points[num];
|
550 |
+
const xn = `"x${num}"`;
|
551 |
+
const yn = `"y${num}"`;
|
552 |
+
points = points
|
553 |
+
.replace(xn, this.descendInput(point.x).asNumber())
|
554 |
+
.replace(yn, this.descendInput(point.y).asNumber());
|
555 |
+
}
|
556 |
+
return new TypedInput(points, TYPE_UNKNOWN);
|
557 |
+
|
558 |
+
case 'control.inlineStackOutput': {
|
559 |
+
// reset this.source but save it
|
560 |
+
const originalSource = this.source;
|
561 |
+
this.source = '(yield* (function*() {';
|
562 |
+
// descend now since descendStack modifies source
|
563 |
+
this.descendStack(node.code, new Frame(false, 'control.inlineStackOutput'));
|
564 |
+
this.source += '})())';
|
565 |
+
// save edited
|
566 |
+
const stackSource = this.source;
|
567 |
+
this.source = originalSource;
|
568 |
+
return new TypedInput(stackSource, TYPE_UNKNOWN);
|
569 |
+
}
|
570 |
+
|
571 |
+
case 'keyboard.pressed':
|
572 |
+
return new TypedInput(`runtime.ioDevices.keyboard.getKeyIsDown(${this.descendInput(node.key).asSafe()})`, TYPE_BOOLEAN);
|
573 |
+
|
574 |
+
case 'list.contains':
|
575 |
+
if (this.isOptimized) {
|
576 |
+
// pm: we can use a better function here
|
577 |
+
return new TypedInput(`listContainsFastest(${this.referenceVariable(node.list)}, ${this.descendInput(node.item).asUnknown()})`, TYPE_BOOLEAN);
|
578 |
+
}
|
579 |
+
return new TypedInput(`listContains(${this.referenceVariable(node.list)}, ${this.descendInput(node.item).asUnknown()})`, TYPE_BOOLEAN);
|
580 |
+
case 'list.contents':
|
581 |
+
if (this.isOptimized) {
|
582 |
+
// pm: its more consistent to just return the list with spaces inbetween
|
583 |
+
return new TypedInput(`(${this.referenceVariable(node.list)}.value.join(' '))`, TYPE_STRING);
|
584 |
+
}
|
585 |
+
return new TypedInput(`listContents(${this.referenceVariable(node.list)})`, TYPE_STRING);
|
586 |
+
case 'list.get': {
|
587 |
+
const index = this.descendInput(node.index);
|
588 |
+
if (environment.supportsNullishCoalescing) {
|
589 |
+
if (index.isAlwaysNumberOrNaN()) {
|
590 |
+
return new TypedInput(`(${this.referenceVariable(node.list)}.value[(${index.asNumber()} | 0) - 1] ?? "")`, TYPE_UNKNOWN);
|
591 |
+
}
|
592 |
+
if (index instanceof ConstantInput && index.constantValue === 'last') {
|
593 |
+
return new TypedInput(`(${this.referenceVariable(node.list)}.value[${this.referenceVariable(node.list)}.value.length - 1] ?? "")`, TYPE_UNKNOWN);
|
594 |
+
}
|
595 |
+
}
|
596 |
+
if (this.isOptimized) {
|
597 |
+
// pm: we can just use this as an index ignoring the string input, the nullish coalescing operator will just make sure we dont return undefined
|
598 |
+
return new TypedInput(`(${this.referenceVariable(node.list)}.value[${index.asUnknown()} - 1] ?? "")`, TYPE_UNKNOWN);
|
599 |
+
}
|
600 |
+
return new TypedInput(`listGet(${this.referenceVariable(node.list)}.value, ${index.asUnknown()})`, TYPE_UNKNOWN);
|
601 |
+
}
|
602 |
+
case 'list.indexOf':
|
603 |
+
return new TypedInput(`listIndexOf(${this.referenceVariable(node.list)}, ${this.descendInput(node.item).asUnknown()})`, TYPE_NUMBER);
|
604 |
+
case 'list.amountOf':
|
605 |
+
return new TypedInput(`${this.referenceVariable(node.list)}.value.filter((x) => x == ${this.descendInput(node.value).asUnknown()}).length`, TYPE_NUMBER);
|
606 |
+
case 'list.length':
|
607 |
+
return new TypedInput(`${this.referenceVariable(node.list)}.value.length`, TYPE_NUMBER);
|
608 |
+
|
609 |
+
case 'list.filteritem':
|
610 |
+
return new TypedInput('runtime.ext_scratch3_data._listFilterItem', TYPE_UNKNOWN);
|
611 |
+
case 'list.filterindex':
|
612 |
+
return new TypedInput('runtime.ext_scratch3_data._listFilterIndex', TYPE_UNKNOWN);
|
613 |
+
|
614 |
+
case 'looks.size':
|
615 |
+
return new TypedInput('target.size', TYPE_NUMBER);
|
616 |
+
case 'looks.tintColor':
|
617 |
+
return new TypedInput('runtime.ext_scratch3_looks.getTintColor(null, { target: target })', TYPE_NUMBER);
|
618 |
+
case 'looks.backdropName':
|
619 |
+
return new TypedInput('stage.getCostumes()[stage.currentCostume].name', TYPE_STRING);
|
620 |
+
case 'looks.backdropNumber':
|
621 |
+
return new TypedInput('(stage.currentCostume + 1)', TYPE_NUMBER);
|
622 |
+
case 'looks.costumeName':
|
623 |
+
return new TypedInput('target.getCostumes()[target.currentCostume].name', TYPE_STRING);
|
624 |
+
case 'looks.costumeNumber':
|
625 |
+
return new TypedInput('(target.currentCostume + 1)', TYPE_NUMBER);
|
626 |
+
|
627 |
+
case 'motion.direction':
|
628 |
+
return new TypedInput('target.direction', TYPE_NUMBER);
|
629 |
+
|
630 |
+
case 'motion.x':
|
631 |
+
if (this.isOptimized) {
|
632 |
+
return new TypedInput('(target.x)', TYPE_NUMBER);
|
633 |
+
}
|
634 |
+
return new TypedInput('limitPrecision(target.x)', TYPE_NUMBER);
|
635 |
+
case 'motion.y':
|
636 |
+
if (this.isOptimized) {
|
637 |
+
return new TypedInput('(target.y)', TYPE_NUMBER);
|
638 |
+
}
|
639 |
+
return new TypedInput('limitPrecision(target.y)', TYPE_NUMBER);
|
640 |
+
|
641 |
+
case 'mouse.down':
|
642 |
+
return new TypedInput('runtime.ioDevices.mouse.getIsDown()', TYPE_BOOLEAN);
|
643 |
+
case 'mouse.x':
|
644 |
+
return new TypedInput('runtime.ioDevices.mouse.getScratchX()', TYPE_NUMBER);
|
645 |
+
case 'mouse.y':
|
646 |
+
return new TypedInput('runtime.ioDevices.mouse.getScratchY()', TYPE_NUMBER);
|
647 |
+
|
648 |
+
case 'op.true':
|
649 |
+
return new TypedInput('(true)', TYPE_BOOLEAN);
|
650 |
+
case 'op.false':
|
651 |
+
return new TypedInput('(false)', TYPE_BOOLEAN);
|
652 |
+
case 'op.randbool':
|
653 |
+
return new TypedInput('(Boolean(Math.round(Math.random())))', TYPE_BOOLEAN);
|
654 |
+
|
655 |
+
case 'pmEventsExpansion.broadcastFunction':
|
656 |
+
// we need to do function otherwise this block would be stupidly long
|
657 |
+
let source = '(yield* (function*() {';
|
658 |
+
source += `var broadcastVar = runtime.getTargetForStage().lookupBroadcastMsg("", ${this.descendInput(node.broadcast).asString()} );`;
|
659 |
+
source += `if (broadcastVar) broadcastVar.isSent = true;`;
|
660 |
+
const threads = this.localVariables.next();
|
661 |
+
source += `var ${threads} = startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} });`;
|
662 |
+
const threadVar = this.localVariables.next();
|
663 |
+
source += `for (const ${threadVar} of ${threads}) { ${threadVar}.__evex_recievedDataa = '' };`;
|
664 |
+
source += `yield* waitThreads(${threads});`;
|
665 |
+
// wait an extra frame so the thread has the new value
|
666 |
+
if (this.isWarp) {
|
667 |
+
source += 'if (isStuck()) yield;\n';
|
668 |
+
} else {
|
669 |
+
source += 'yield;\n';
|
670 |
+
}
|
671 |
+
// Control may have been yielded to another script -- all bets are off.
|
672 |
+
this.resetVariableInputs();
|
673 |
+
// get value
|
674 |
+
const value = this.localVariables.next();
|
675 |
+
const thread = this.localVariables.next();
|
676 |
+
source += `var ${value} = undefined;`;
|
677 |
+
source += `for (var ${thread} of ${threads}) {`;
|
678 |
+
// if not undefined, return value
|
679 |
+
source += `if (typeof ${thread}.__evex_returnDataa !== 'undefined') {`;
|
680 |
+
source += `return ${thread}.__evex_returnDataa;`;
|
681 |
+
source += `}`;
|
682 |
+
source += `}`;
|
683 |
+
// no value, return empty value
|
684 |
+
source += `return '';`;
|
685 |
+
source += '})())';
|
686 |
+
return new TypedInput(source, TYPE_STRING);
|
687 |
+
case 'pmEventsExpansion.broadcastFunctionArgs': {
|
688 |
+
// we need to do function otherwise this block would be stupidly long
|
689 |
+
let source = '(yield* (function*() {';
|
690 |
+
const threads = this.localVariables.next();
|
691 |
+
source += `var broadcastVar = runtime.getTargetForStage().lookupBroadcastMsg("", ${this.descendInput(node.broadcast).asString()} );`;
|
692 |
+
source += `if (broadcastVar) broadcastVar.isSent = true;`;
|
693 |
+
source += `var ${threads} = startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} });`;
|
694 |
+
const threadVar = this.localVariables.next();
|
695 |
+
source += `for (const ${threadVar} of ${threads}) { ${threadVar}.__evex_recievedDataa = ${this.descendInput(node.args).asString()} };`;
|
696 |
+
source += `yield* waitThreads(${threads});`;
|
697 |
+
// wait an extra frame so the thread has the new value
|
698 |
+
if (this.isWarp) {
|
699 |
+
source += 'if (isStuck()) yield;\n';
|
700 |
+
} else {
|
701 |
+
source += 'yield;\n';
|
702 |
+
}
|
703 |
+
// Control may have been yielded to another script -- all bets are off.
|
704 |
+
this.resetVariableInputs();
|
705 |
+
// get value
|
706 |
+
const value = this.localVariables.next();
|
707 |
+
const thread = this.localVariables.next();
|
708 |
+
source += `var ${value} = undefined;`;
|
709 |
+
source += `for (var ${thread} of ${threads}) {`;
|
710 |
+
// if not undefined, return value
|
711 |
+
source += `if (typeof ${thread}.__evex_returnDataa !== 'undefined') {`;
|
712 |
+
source += `return ${thread}.__evex_returnDataa;`;
|
713 |
+
source += `}`;
|
714 |
+
source += `}`;
|
715 |
+
// no value, return empty value
|
716 |
+
source += `return '';`;
|
717 |
+
source += '})())';
|
718 |
+
return new TypedInput(source, TYPE_STRING);
|
719 |
+
}
|
720 |
+
case 'op.abs':
|
721 |
+
return new TypedInput(`Math.abs(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
722 |
+
case 'op.acos':
|
723 |
+
// Needs to be marked as NaN because Math.acos(1.0001) === NaN
|
724 |
+
return new TypedInput(`((Math.acos(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER_NAN);
|
725 |
+
case 'op.add':
|
726 |
+
// Needs to be marked as NaN because Infinity + -Infinity === NaN
|
727 |
+
return new TypedInput(`(${this.descendInput(node.left).asNumber()} + ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
|
728 |
+
case 'op.and':
|
729 |
+
return new TypedInput(`(${this.descendInput(node.left).asBoolean()} && ${this.descendInput(node.right).asBoolean()})`, TYPE_BOOLEAN);
|
730 |
+
case 'op.asin':
|
731 |
+
// Needs to be marked as NaN because Math.asin(1.0001) === NaN
|
732 |
+
return new TypedInput(`((Math.asin(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER_NAN);
|
733 |
+
case 'op.atan':
|
734 |
+
return new TypedInput(`((Math.atan(${this.descendInput(node.value).asNumber()}) * 180) / Math.PI)`, TYPE_NUMBER);
|
735 |
+
case 'op.ceiling':
|
736 |
+
return new TypedInput(`Math.ceil(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
737 |
+
case 'op.contains':
|
738 |
+
return new TypedInput(`(${this.descendInput(node.string).asString()}.toLowerCase().indexOf(${this.descendInput(node.contains).asString()}.toLowerCase()) !== -1)`, TYPE_BOOLEAN);
|
739 |
+
case 'op.cos':
|
740 |
+
// pm: optimizations allow us to use a premade list for sin values on integers
|
741 |
+
if (this.isOptimized) {
|
742 |
+
const value = `${this.descendInput(node.value).asNumber()}`;
|
743 |
+
return new TypedInput(`(Number.isInteger(${value}) ? runtime.optimizationUtil.cos[((${value} % 360) + 360) % 360] : (Math.round(Math.cos((Math.PI * ${value}) / 180) * 1e10) / 1e10))`, TYPE_NUMBER_NAN);
|
744 |
+
}
|
745 |
+
return new TypedInput(`(Math.round(Math.cos((Math.PI * ${this.descendInput(node.value).asNumber()}) / 180) * 1e10) / 1e10)`, TYPE_NUMBER_NAN);
|
746 |
+
case 'op.divide':
|
747 |
+
// Needs to be marked as NaN because 0 / 0 === NaN
|
748 |
+
return new TypedInput(`(${this.descendInput(node.left).asNumber()} / ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
|
749 |
+
case 'op.power':
|
750 |
+
// Needs to be marked as NaN because -1 ** 0.5 === NaN
|
751 |
+
return new TypedInput(`(Math.pow(${this.descendInput(node.left).asNumber()}, ${this.descendInput(node.right).asNumber()}))`, TYPE_NUMBER_NAN);
|
752 |
+
case 'op.equals': {
|
753 |
+
const left = this.descendInput(node.left);
|
754 |
+
const right = this.descendInput(node.right);
|
755 |
+
// When both operands are known to never be numbers, only use string comparison to avoid all number parsing.
|
756 |
+
if (left.isNeverNumber() || right.isNeverNumber()) {
|
757 |
+
return new TypedInput(`(${left.asString()}.toLowerCase() === ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
|
758 |
+
}
|
759 |
+
const leftAlwaysNumber = left.isAlwaysNumber();
|
760 |
+
const rightAlwaysNumber = right.isAlwaysNumber();
|
761 |
+
// When both operands are known to be numbers, we can use ===
|
762 |
+
if (leftAlwaysNumber && rightAlwaysNumber) {
|
763 |
+
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
|
764 |
+
}
|
765 |
+
// In certain conditions, we can use === when one of the operands is known to be a safe number.
|
766 |
+
if (leftAlwaysNumber && left instanceof ConstantInput && isSafeConstantForEqualsOptimization(left)) {
|
767 |
+
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
|
768 |
+
}
|
769 |
+
if (rightAlwaysNumber && right instanceof ConstantInput && isSafeConstantForEqualsOptimization(right)) {
|
770 |
+
return new TypedInput(`(${left.asNumber()} === ${right.asNumber()})`, TYPE_BOOLEAN);
|
771 |
+
}
|
772 |
+
// No compile-time optimizations possible - use fallback method.
|
773 |
+
return new TypedInput(`compareEqual(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
|
774 |
+
}
|
775 |
+
case 'op.e^':
|
776 |
+
return new TypedInput(`Math.exp(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
777 |
+
case 'op.floor':
|
778 |
+
return new TypedInput(`Math.floor(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
779 |
+
case 'op.greater': {
|
780 |
+
const left = this.descendInput(node.left);
|
781 |
+
const right = this.descendInput(node.right);
|
782 |
+
// When the left operand is a number and the right operand is a number or NaN, we can use >
|
783 |
+
if (left.isAlwaysNumber() && right.isAlwaysNumberOrNaN()) {
|
784 |
+
return new TypedInput(`(${left.asNumber()} > ${right.asNumberOrNaN()})`, TYPE_BOOLEAN);
|
785 |
+
}
|
786 |
+
// When the left operand is a number or NaN and the right operand is a number, we can negate <=
|
787 |
+
if (left.isAlwaysNumberOrNaN() && right.isAlwaysNumber()) {
|
788 |
+
return new TypedInput(`!(${left.asNumberOrNaN()} <= ${right.asNumber()})`, TYPE_BOOLEAN);
|
789 |
+
}
|
790 |
+
// When either operand is known to never be a number, avoid all number parsing.
|
791 |
+
if (left.isNeverNumber() || right.isNeverNumber()) {
|
792 |
+
return new TypedInput(`(${left.asString()}.toLowerCase() > ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
|
793 |
+
}
|
794 |
+
// No compile-time optimizations possible - use fallback method.
|
795 |
+
return new TypedInput(`compareGreaterThan(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
|
796 |
+
}
|
797 |
+
case 'op.join':
|
798 |
+
return new TypedInput(`(${this.descendInput(node.left).asString()} + ${this.descendInput(node.right).asString()})`, TYPE_STRING);
|
799 |
+
case 'op.length':
|
800 |
+
return new TypedInput(`${this.descendInput(node.string).asString()}.length`, TYPE_NUMBER);
|
801 |
+
case 'op.less': {
|
802 |
+
const left = this.descendInput(node.left);
|
803 |
+
const right = this.descendInput(node.right);
|
804 |
+
// When the left operand is a number or NaN and the right operand is a number, we can use <
|
805 |
+
if (left.isAlwaysNumberOrNaN() && right.isAlwaysNumber()) {
|
806 |
+
return new TypedInput(`(${left.asNumberOrNaN()} < ${right.asNumber()})`, TYPE_BOOLEAN);
|
807 |
+
}
|
808 |
+
// When the left operand is a number and the right operand is a number or NaN, we can negate >=
|
809 |
+
if (left.isAlwaysNumber() && right.isAlwaysNumberOrNaN()) {
|
810 |
+
return new TypedInput(`!(${left.asNumber()} >= ${right.asNumberOrNaN()})`, TYPE_BOOLEAN);
|
811 |
+
}
|
812 |
+
// When either operand is known to never be a number, avoid all number parsing.
|
813 |
+
if (left.isNeverNumber() || right.isNeverNumber()) {
|
814 |
+
return new TypedInput(`(${left.asString()}.toLowerCase() < ${right.asString()}.toLowerCase())`, TYPE_BOOLEAN);
|
815 |
+
}
|
816 |
+
// No compile-time optimizations possible - use fallback method.
|
817 |
+
return new TypedInput(`compareLessThan(${left.asUnknown()}, ${right.asUnknown()})`, TYPE_BOOLEAN);
|
818 |
+
}
|
819 |
+
case 'op.letterOf':
|
820 |
+
return new TypedInput(`((${this.descendInput(node.string).asString()})[(${this.descendInput(node.letter).asNumber()} | 0) - 1] || "")`, TYPE_STRING);
|
821 |
+
case 'op.ln':
|
822 |
+
// Needs to be marked as NaN because Math.log(-1) == NaN
|
823 |
+
return new TypedInput(`Math.log(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
|
824 |
+
case 'op.log':
|
825 |
+
// Needs to be marked as NaN because Math.log(-1) == NaN
|
826 |
+
return new TypedInput(`(Math.log(${this.descendInput(node.value).asNumber()}) / Math.LN10)`, TYPE_NUMBER_NAN);
|
827 |
+
case 'op.log2':
|
828 |
+
// Needs to be marked as NaN because Math.log2(-1) == NaN
|
829 |
+
return new TypedInput(`Math.log2(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
|
830 |
+
case 'op.advlog':
|
831 |
+
// Needs to be marked as NaN because Math.log(-1) == NaN
|
832 |
+
return new TypedInput(`(Math.log(${this.descendInput(node.right).asNumber()}) / (Math.log(${this.descendInput(node.left).asNumber()}))`, TYPE_NUMBER_NAN);
|
833 |
+
case 'op.mod':
|
834 |
+
this.descendedIntoModulo = true;
|
835 |
+
// Needs to be marked as NaN because mod(0, 0) (and others) == NaN
|
836 |
+
return new TypedInput(`mod(${this.descendInput(node.left).asNumber()}, ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
|
837 |
+
case 'op.multiply':
|
838 |
+
// Needs to be marked as NaN because Infinity * 0 === NaN
|
839 |
+
return new TypedInput(`(${this.descendInput(node.left).asNumber()} * ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
|
840 |
+
case 'op.not':
|
841 |
+
return new TypedInput(`!${this.descendInput(node.operand).asBoolean()}`, TYPE_BOOLEAN);
|
842 |
+
case 'op.or':
|
843 |
+
return new TypedInput(`(${this.descendInput(node.left).asBoolean()} || ${this.descendInput(node.right).asBoolean()})`, TYPE_BOOLEAN);
|
844 |
+
case 'op.random':
|
845 |
+
if (node.useInts) {
|
846 |
+
// Both inputs are ints, so we know neither are NaN
|
847 |
+
return new TypedInput(`randomInt(${this.descendInput(node.low).asNumber()}, ${this.descendInput(node.high).asNumber()})`, TYPE_NUMBER);
|
848 |
+
}
|
849 |
+
if (node.useFloats) {
|
850 |
+
return new TypedInput(`randomFloat(${this.descendInput(node.low).asNumber()}, ${this.descendInput(node.high).asNumber()})`, TYPE_NUMBER_NAN);
|
851 |
+
}
|
852 |
+
return new TypedInput(`runtime.ext_scratch3_operators._random(${this.descendInput(node.low).asUnknown()}, ${this.descendInput(node.high).asUnknown()})`, TYPE_NUMBER_NAN);
|
853 |
+
case 'op.round':
|
854 |
+
return new TypedInput(`Math.round(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
855 |
+
case 'op.sign':
|
856 |
+
return new TypedInput(`Math.sign(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
857 |
+
case 'op.sin':
|
858 |
+
// pm: optimizations allow us to use a premade list for sin values on integers
|
859 |
+
if (this.isOptimized) {
|
860 |
+
const value = `${this.descendInput(node.value).asNumber()}`;
|
861 |
+
return new TypedInput(`(Number.isInteger(${value}) ? runtime.optimizationUtil.sin[((${value} % 360) + 360) % 360] : (Math.round(Math.sin((Math.PI * ${value}) / 180) * 1e10) / 1e10))`, TYPE_NUMBER_NAN);
|
862 |
+
}
|
863 |
+
return new TypedInput(`(Math.round(Math.sin((Math.PI * ${this.descendInput(node.value).asNumber()}) / 180) * 1e10) / 1e10)`, TYPE_NUMBER_NAN);
|
864 |
+
case 'op.sqrt':
|
865 |
+
// Needs to be marked as NaN because Math.sqrt(-1) === NaN
|
866 |
+
return new TypedInput(`Math.sqrt(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
|
867 |
+
case 'op.subtract':
|
868 |
+
// Needs to be marked as NaN because Infinity - Infinity === NaN
|
869 |
+
return new TypedInput(`(${this.descendInput(node.left).asNumber()} - ${this.descendInput(node.right).asNumber()})`, TYPE_NUMBER_NAN);
|
870 |
+
case 'op.tan':
|
871 |
+
return new TypedInput(`tan(${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER_NAN);
|
872 |
+
case 'op.10^':
|
873 |
+
return new TypedInput(`(10 ** ${this.descendInput(node.value).asNumber()})`, TYPE_NUMBER);
|
874 |
+
|
875 |
+
case 'sensing.answer':
|
876 |
+
return new TypedInput(`runtime.ext_scratch3_sensing._answer`, TYPE_STRING);
|
877 |
+
case 'sensing.colorTouchingColor':
|
878 |
+
return new TypedInput(`target.colorIsTouchingColor(colorToList(${this.descendInput(node.target).asColor()}), colorToList(${this.descendInput(node.mask).asColor()}))`, TYPE_BOOLEAN);
|
879 |
+
case 'sensing.date':
|
880 |
+
return new TypedInput(`(new Date().getDate())`, TYPE_NUMBER);
|
881 |
+
case 'sensing.dayofweek':
|
882 |
+
return new TypedInput(`(new Date().getDay() + 1)`, TYPE_NUMBER);
|
883 |
+
case 'sensing.daysSince2000':
|
884 |
+
return new TypedInput('daysSince2000()', TYPE_NUMBER);
|
885 |
+
case 'sensing.distance':
|
886 |
+
// TODO: on stages, this can be computed at compile time
|
887 |
+
return new TypedInput(`distance(${this.descendInput(node.target).asString()})`, TYPE_NUMBER);
|
888 |
+
case 'sensing.hour':
|
889 |
+
return new TypedInput(`(new Date().getHours())`, TYPE_NUMBER);
|
890 |
+
case 'sensing.minute':
|
891 |
+
return new TypedInput(`(new Date().getMinutes())`, TYPE_NUMBER);
|
892 |
+
case 'sensing.month':
|
893 |
+
return new TypedInput(`(new Date().getMonth() + 1)`, TYPE_NUMBER);
|
894 |
+
case 'sensing.of': {
|
895 |
+
const object = this.descendInput(node.object).asString();
|
896 |
+
const property = node.property;
|
897 |
+
if (node.object.kind === 'constant') {
|
898 |
+
const isStage = node.object.value === '_stage_';
|
899 |
+
// Note that if target isn't a stage, we can't assume it exists
|
900 |
+
const objectReference = isStage ? 'stage' : this.evaluateOnce(`runtime.getSpriteTargetByName(${object})`);
|
901 |
+
if (property === 'volume') {
|
902 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.volume : 0)`, TYPE_NUMBER);
|
903 |
+
}
|
904 |
+
if (isStage) {
|
905 |
+
switch (property) {
|
906 |
+
case 'background #':
|
907 |
+
// fallthrough for scratch 1.0 compatibility
|
908 |
+
case 'backdrop #':
|
909 |
+
return new TypedInput(`(${objectReference}.currentCostume + 1)`, TYPE_NUMBER);
|
910 |
+
case 'backdrop name':
|
911 |
+
return new TypedInput(`${objectReference}.getCostumes()[${objectReference}.currentCostume].name`, TYPE_STRING);
|
912 |
+
}
|
913 |
+
} else {
|
914 |
+
switch (property) {
|
915 |
+
case 'x position':
|
916 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.x : 0)`, TYPE_NUMBER);
|
917 |
+
case 'y position':
|
918 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.y : 0)`, TYPE_NUMBER);
|
919 |
+
case 'direction':
|
920 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.direction : 0)`, TYPE_NUMBER);
|
921 |
+
case 'costume #':
|
922 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.currentCostume + 1 : 0)`, TYPE_NUMBER);
|
923 |
+
case 'costume name':
|
924 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.getCostumes()[${objectReference}.currentCostume].name : 0)`, TYPE_UNKNOWN);
|
925 |
+
case 'layer':
|
926 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.getLayerOrder() : 0)`, TYPE_NUMBER);
|
927 |
+
case 'size':
|
928 |
+
return new TypedInput(`(${objectReference} ? ${objectReference}.size : 0)`, TYPE_NUMBER);
|
929 |
+
}
|
930 |
+
}
|
931 |
+
const variableReference = this.evaluateOnce(`${objectReference} && ${objectReference}.lookupVariableByNameAndType("${sanitize(property)}", "", true)`);
|
932 |
+
return new TypedInput(`(${variableReference} ? ${variableReference}.value : 0)`, TYPE_UNKNOWN);
|
933 |
+
}
|
934 |
+
return new TypedInput(`runtime.ext_scratch3_sensing.getAttributeOf({OBJECT: ${object}, PROPERTY: "${sanitize(property)}" })`, TYPE_UNKNOWN);
|
935 |
+
}
|
936 |
+
case 'sensing.second':
|
937 |
+
return new TypedInput(`(new Date().getSeconds())`, TYPE_NUMBER);
|
938 |
+
case 'sensing.timestamp':
|
939 |
+
return new TypedInput(`(Date.now())`, TYPE_NUMBER);
|
940 |
+
case 'sensing.touching':
|
941 |
+
return new TypedInput(`target.isTouchingObject(${this.descendInput(node.object).asUnknown()})`, TYPE_BOOLEAN);
|
942 |
+
case 'sensing.touchingColor':
|
943 |
+
return new TypedInput(`target.isTouchingColor(colorToList(${this.descendInput(node.color).asColor()}))`, TYPE_BOOLEAN);
|
944 |
+
case 'sensing.username':
|
945 |
+
return new TypedInput('runtime.ioDevices.userData.getUsername()', TYPE_STRING);
|
946 |
+
case 'sensing.loggedin':
|
947 |
+
return new TypedInput('runtime.ioDevices.userData.getLoggedIn()', TYPE_STRING);
|
948 |
+
case 'sensing.year':
|
949 |
+
return new TypedInput(`(new Date().getFullYear())`, TYPE_NUMBER);
|
950 |
+
|
951 |
+
case 'timer.get':
|
952 |
+
return new TypedInput('runtime.ioDevices.clock.projectTimer()', TYPE_NUMBER);
|
953 |
+
|
954 |
+
case 'tw.lastKeyPressed':
|
955 |
+
return new TypedInput('runtime.ioDevices.keyboard.getLastKeyPressed()', TYPE_STRING);
|
956 |
+
|
957 |
+
case 'var.get':
|
958 |
+
return this.descendVariable(node.variable);
|
959 |
+
|
960 |
+
case 'procedures.call': {
|
961 |
+
const procedureCode = node.code;
|
962 |
+
const procedureVariant = node.variant;
|
963 |
+
let source = '(';
|
964 |
+
// Do not generate any code for empty procedures.
|
965 |
+
const procedureData = this.ir.procedures[procedureVariant];
|
966 |
+
if (procedureData.stack === null) return new TypedInput('""', TYPE_STRING);
|
967 |
+
|
968 |
+
const yieldForRecursion = !this.isWarp && procedureCode === this.script.procedureCode;
|
969 |
+
const yieldForHat = this.isInHat;
|
970 |
+
if (yieldForRecursion || yieldForHat) {
|
971 |
+
// Direct recursion yields.
|
972 |
+
this.yieldNotWarp();
|
973 |
+
}
|
974 |
+
if (procedureData.yields) {
|
975 |
+
source += 'yield* ';
|
976 |
+
if (!this.script.yields) {
|
977 |
+
throw new Error('Script uses yielding procedure but is not marked as yielding.');
|
978 |
+
}
|
979 |
+
}
|
980 |
+
source += `thread.procedures["${sanitize(procedureVariant)}"](`;
|
981 |
+
// Only include arguments if the procedure accepts any.
|
982 |
+
if (procedureData.arguments.length) {
|
983 |
+
const args = [];
|
984 |
+
for (const input of node.arguments) {
|
985 |
+
args.push(this.descendInput(input).asSafe());
|
986 |
+
}
|
987 |
+
source += args.join(',');
|
988 |
+
}
|
989 |
+
source += `))`;
|
990 |
+
// Variable input types may have changes after a procedure call.
|
991 |
+
this.resetVariableInputs();
|
992 |
+
return new TypedInput(source, TYPE_UNKNOWN);
|
993 |
+
}
|
994 |
+
|
995 |
+
case 'noop':
|
996 |
+
console.warn('unexpected noop');
|
997 |
+
return new TypedInput('""', TYPE_UNKNOWN);
|
998 |
+
|
999 |
+
case 'tempVars.get': {
|
1000 |
+
const name = this.descendInput(node.var);
|
1001 |
+
const hostObj = node.runtime
|
1002 |
+
? 'runtime.variables'
|
1003 |
+
: node.thread
|
1004 |
+
? 'thread.variables'
|
1005 |
+
: 'tempVars';
|
1006 |
+
const code = this.isOptimized
|
1007 |
+
? `${hostObj}[${name.asString()}]`
|
1008 |
+
: `get(${hostObj}, ${name.asString()})`;
|
1009 |
+
if (environment.supportsNullishCoalescing) {
|
1010 |
+
return new TypedInput(`(${code} ?? "")`, TYPE_UNKNOWN);
|
1011 |
+
}
|
1012 |
+
return new TypedInput(`nullish(${code}, "")`, TYPE_UNKNOWN);
|
1013 |
+
}
|
1014 |
+
case 'tempVars.exists': {
|
1015 |
+
const name = this.descendInput(node.var);
|
1016 |
+
const hostObj = node.runtime
|
1017 |
+
? 'runtime.variables'
|
1018 |
+
: node.thread
|
1019 |
+
? 'thread.variables'
|
1020 |
+
: 'tempVars';
|
1021 |
+
const code = this.isOptimized
|
1022 |
+
? `${name.asString()} in ${hostObj}`
|
1023 |
+
: `includes(${hostObj}, ${name.asString()})`;
|
1024 |
+
return new TypedInput(code, TYPE_BOOLEAN);
|
1025 |
+
}
|
1026 |
+
case 'tempVars.all':
|
1027 |
+
const hostObj = node.runtime
|
1028 |
+
? 'runtime.variables'
|
1029 |
+
: node.thread
|
1030 |
+
? 'thread.variables'
|
1031 |
+
: 'tempVars';
|
1032 |
+
if (node.runtime || node.thread) {
|
1033 |
+
return new TypedInput(`Object.keys(${hostObj}).join(',')`, TYPE_STRING);
|
1034 |
+
}
|
1035 |
+
return new TypedInput(`JSON.stringify(Object.keys(tempVars))`, TYPE_STRING);
|
1036 |
+
case 'control.dualBlock':
|
1037 |
+
return new TypedInput('"dual block works!"', TYPE_STRING);
|
1038 |
+
|
1039 |
+
default:
|
1040 |
+
log.warn(`JS: Unknown input: ${node.kind}`, node);
|
1041 |
+
throw new Error(`JS: Unknown input: ${node.kind}`);
|
1042 |
+
}
|
1043 |
+
}
|
1044 |
+
|
1045 |
+
/**
|
1046 |
+
* @param {*} node Stacked node to compile.
|
1047 |
+
*/
|
1048 |
+
descendStackedBlock (node) {
|
1049 |
+
// check if we have extension js for this kind
|
1050 |
+
const extensionId = String(node.kind).split('.')[0];
|
1051 |
+
const blockId = String(node.kind).replace(extensionId + '.', '');
|
1052 |
+
if (JSGenerator.hasExtensionJs(extensionId) && JSGenerator.getExtensionJs(extensionId)[blockId]) {
|
1053 |
+
// this is an extension block that wants to be compiled
|
1054 |
+
const imports = JSGenerator.getExtensionImports();
|
1055 |
+
const jsFunc = JSGenerator.getExtensionJs(extensionId)[blockId];
|
1056 |
+
// add to source
|
1057 |
+
try {
|
1058 |
+
jsFunc(node, this, imports);
|
1059 |
+
} catch (err) {
|
1060 |
+
log.warn(extensionId + '_' + blockId, 'failed to compile JavaScript;', err);
|
1061 |
+
}
|
1062 |
+
return;
|
1063 |
+
}
|
1064 |
+
|
1065 |
+
switch (node.kind) {
|
1066 |
+
case 'your mom':
|
1067 |
+
const urmom = 'https://penguinmod.com/dump/urmom-your-mom.mp4';
|
1068 |
+
const yaTried = 'https://penguinmod.com/dump/chips.mp4';
|
1069 |
+
const MISTERBEAST = 'https://penguinmod.com/dump/MISTER_BEAST.webm';
|
1070 |
+
const createVideo = url => `\`<video src="${url}" height="\${height}" autoplay loop style="alignment:center;"></video>\``;
|
1071 |
+
this.source += `
|
1072 |
+
const stage = document.getElementsByClassName('stage_stage_1fD7k box_box_2jjDp')[0].children[0]
|
1073 |
+
const height = stage.children[0].style.height
|
1074 |
+
stage.innerHTML = ${createVideo(urmom)}
|
1075 |
+
runtime.on('PROJECT_STOP_ALL', () => document.body.innerHTML = ${createVideo(yaTried)})
|
1076 |
+
stage.children[0].addEventListener('mousedown', () => stage.innerHTML = ${createVideo(MISTERBEAST)});
|
1077 |
+
`;
|
1078 |
+
break;
|
1079 |
+
case 'addons.call': {
|
1080 |
+
const inputs = this.descendInputRecord(node.arguments);
|
1081 |
+
const blockFunction = `runtime.getAddonBlock("${sanitize(node.code)}").callback`;
|
1082 |
+
const blockId = `"${sanitize(node.blockId)}"`;
|
1083 |
+
this.source += `yield* executeInCompatibilityLayer(${inputs}, ${blockFunction}, ${this.isWarp}, false, ${blockId});\n`;
|
1084 |
+
break;
|
1085 |
+
}
|
1086 |
+
case 'compat': {
|
1087 |
+
// If the last command in a loop returns a promise, immediately continue to the next iteration.
|
1088 |
+
// If you don't do this, the loop effectively yields twice per iteration and will run at half-speed.
|
1089 |
+
const isLastInLoop = this.isLastBlockInLoop();
|
1090 |
+
|
1091 |
+
const blockType = node.blockType;
|
1092 |
+
if (blockType === BlockType.COMMAND || blockType === BlockType.HAT) {
|
1093 |
+
this.source += `${this.generateCompatibilityLayerCall(node, isLastInLoop)};\n`;
|
1094 |
+
} else if (blockType === BlockType.CONDITIONAL || blockType === BlockType.LOOP) {
|
1095 |
+
const branchVariable = this.localVariables.next();
|
1096 |
+
this.source += `const ${branchVariable} = createBranchInfo(${blockType === BlockType.LOOP});\n`;
|
1097 |
+
this.source += `while (${branchVariable}.branch = +(${this.generateCompatibilityLayerCall(node, false, branchVariable)})) {\n`;
|
1098 |
+
this.source += `switch (${branchVariable}.branch) {\n`;
|
1099 |
+
for (let i = 0; i < node.substacks.length; i++) {
|
1100 |
+
this.source += `case ${i + 1}: {\n`;
|
1101 |
+
this.descendStack(node.substacks[i], new Frame(false));
|
1102 |
+
this.source += `break;\n`;
|
1103 |
+
this.source += `}\n`; // close case
|
1104 |
+
}
|
1105 |
+
this.source += '}\n'; // close switch
|
1106 |
+
this.source += `if (${branchVariable}.onEnd[0]) yield ${branchVariable}.onEnd.shift()(${branchVariable});\n`;
|
1107 |
+
this.source += `if (!${branchVariable}.isLoop) break;\n`;
|
1108 |
+
this.yieldLoop();
|
1109 |
+
this.source += '}\n'; // close while
|
1110 |
+
} else {
|
1111 |
+
throw new Error(`Unknown block type: ${blockType}`);
|
1112 |
+
}
|
1113 |
+
|
1114 |
+
if (isLastInLoop) {
|
1115 |
+
this.source += 'if (hasResumedFromPromise) {hasResumedFromPromise = false;continue;}\n';
|
1116 |
+
}
|
1117 |
+
break;
|
1118 |
+
}
|
1119 |
+
case 'procedures.set':
|
1120 |
+
const val = this.descendInput(node.val);
|
1121 |
+
const i = node.param.index;
|
1122 |
+
if (i !== undefined) this.source += `p${i} = ${val.asSafe()};\n`;
|
1123 |
+
break;
|
1124 |
+
case 'control.createClone':
|
1125 |
+
this.source += `runtime.ext_scratch3_control._createClone(${this.descendInput(node.target).asString()}, target);\n`;
|
1126 |
+
break;
|
1127 |
+
case 'control.deleteClone':
|
1128 |
+
this.source += 'if (!target.isOriginal) {\n';
|
1129 |
+
this.source += ' runtime.disposeTarget(target);\n';
|
1130 |
+
this.source += ' runtime.stopForTarget(target);\n';
|
1131 |
+
this.retire();
|
1132 |
+
this.source += '}\n';
|
1133 |
+
break;
|
1134 |
+
case 'control.for': {
|
1135 |
+
this.resetVariableInputs();
|
1136 |
+
const index = this.localVariables.next();
|
1137 |
+
this.source += `var ${index} = 0; `;
|
1138 |
+
this.source += `while (${index} < ${this.descendInput(node.count).asNumber()}) { `;
|
1139 |
+
this.source += `${index}++; `;
|
1140 |
+
this.source += `${this.referenceVariable(node.variable)}.value = ${index};\n`;
|
1141 |
+
this.descendStack(node.do, new Frame(true, 'control.for'));
|
1142 |
+
this.yieldLoop();
|
1143 |
+
this.source += '}\n';
|
1144 |
+
break;
|
1145 |
+
}
|
1146 |
+
case 'control.switch':
|
1147 |
+
this.source += `switch (${this.descendInput(node.test).asString()}) {\n`;
|
1148 |
+
this.descendStack(node.conditions, new Frame(false, 'control.switch'));
|
1149 |
+
// only add the else branch if it won't be empty
|
1150 |
+
// this makes scripts have a bit less useless noise in them
|
1151 |
+
if (node.default.length) {
|
1152 |
+
this.source += `default:\n`;
|
1153 |
+
this.descendStack(node.default, new Frame(false, 'control.switch'));
|
1154 |
+
}
|
1155 |
+
this.source += `}\n`;
|
1156 |
+
break;
|
1157 |
+
case 'control.case':
|
1158 |
+
if (this.currentFrame.parent !== 'control.switch') {
|
1159 |
+
this.source += `throw 'All "case" blocks must be inside of a "switch" block.';`;
|
1160 |
+
break;
|
1161 |
+
}
|
1162 |
+
this.source += `case ${this.descendInput(node.condition).asString()}:\n`;
|
1163 |
+
if (!node.runsNext){
|
1164 |
+
const frame = new Frame(false, 'control.case');
|
1165 |
+
frame.assignData({
|
1166 |
+
containedByCase: true
|
1167 |
+
});
|
1168 |
+
this.descendStack(node.code, frame);
|
1169 |
+
this.source += `break;\n`;
|
1170 |
+
}
|
1171 |
+
break;
|
1172 |
+
case 'control.allAtOnce': {
|
1173 |
+
const ooldWarp = this.isWarp;
|
1174 |
+
this.isWarp = true;
|
1175 |
+
this.descendStack(node.code, new Frame(false, 'control.allAtOnce'));
|
1176 |
+
this.isWarp = ooldWarp;
|
1177 |
+
break;
|
1178 |
+
}
|
1179 |
+
case 'control.newScript': {
|
1180 |
+
const currentBlockId = this.localVariables.next();
|
1181 |
+
const branchBlock = this.localVariables.next();
|
1182 |
+
// get block id so we can get branch
|
1183 |
+
this.source += `var ${currentBlockId} = thread.peekStack();`;
|
1184 |
+
this.source += `var ${branchBlock} = thread.target.blocks.getBranch(${currentBlockId}, 0);`;
|
1185 |
+
// push new thread if we found a branch
|
1186 |
+
this.source += `if (${branchBlock}) {`;
|
1187 |
+
this.source += `runtime._pushThread(${branchBlock}, target, {});`;
|
1188 |
+
this.source += `}`;
|
1189 |
+
break;
|
1190 |
+
}
|
1191 |
+
case 'control.exitCase':
|
1192 |
+
if (!this.currentFrame.importantData.containedByCase) {
|
1193 |
+
this.source += `throw 'All "exit case" blocks must be inside of a "case" block.';`;
|
1194 |
+
break;
|
1195 |
+
}
|
1196 |
+
this.source += `break;\n`;
|
1197 |
+
break;
|
1198 |
+
case 'control.exitLoop':
|
1199 |
+
if (!this.currentFrame.importantData.containedByLoop) {
|
1200 |
+
this.source += `throw 'All "escape loop" blocks must be inside of a looping block.';`;
|
1201 |
+
break;
|
1202 |
+
}
|
1203 |
+
this.source += `break;\n`;
|
1204 |
+
break;
|
1205 |
+
case 'control.continueLoop':
|
1206 |
+
if (!this.currentFrame.importantData.containedByLoop) {
|
1207 |
+
this.source += `throw 'All "continue loop" blocks must be inside of a looping block.';`;
|
1208 |
+
break;
|
1209 |
+
}
|
1210 |
+
this.source += `continue;\n`;
|
1211 |
+
break;
|
1212 |
+
case 'control.if':
|
1213 |
+
this.source += `if (${this.descendInput(node.condition).asBoolean()}) {\n`;
|
1214 |
+
this.descendStack(node.whenTrue, new Frame(false, 'control.if'));
|
1215 |
+
// only add the else branch if it won't be empty
|
1216 |
+
// this makes scripts have a bit less useless noise in them
|
1217 |
+
if (node.whenFalse.length) {
|
1218 |
+
this.source += `} else {\n`;
|
1219 |
+
this.descendStack(node.whenFalse, new Frame(false, 'control.if'));
|
1220 |
+
}
|
1221 |
+
this.source += `}\n`;
|
1222 |
+
break;
|
1223 |
+
case 'control.trycatch':
|
1224 |
+
this.source += `try {\n`;
|
1225 |
+
this.descendStack(node.try, new Frame(false, 'control.trycatch'));
|
1226 |
+
const error = this.localVariables.next();
|
1227 |
+
this.source += `} catch (${error}) {\n`;
|
1228 |
+
this.source += `runtime.ext_scratch3_control._error = String(${error});\n`;
|
1229 |
+
this.descendStack(node.catch, new Frame(false, 'control.trycatch'));
|
1230 |
+
this.source += `}\n`;
|
1231 |
+
break;
|
1232 |
+
case 'control.throwError': {
|
1233 |
+
const error = this.descendInput(node.error).asString();
|
1234 |
+
this.source += `throw ${error};\n`;
|
1235 |
+
break;
|
1236 |
+
}
|
1237 |
+
case 'control.repeat': {
|
1238 |
+
const i = this.localVariables.next();
|
1239 |
+
this.source += `for (var ${i} = ${this.descendInput(node.times).asNumber()}; ${i} >= 0.5; ${i}--) {\n`;
|
1240 |
+
this.descendStack(node.do, new Frame(true, 'control.repeat'));
|
1241 |
+
this.yieldLoop();
|
1242 |
+
this.source += `}\n`;
|
1243 |
+
break;
|
1244 |
+
}
|
1245 |
+
case 'control.repeatForSeconds': {
|
1246 |
+
const duration = this.localVariables.next();
|
1247 |
+
this.source += `thread.timer2 = timer();\n`;
|
1248 |
+
this.source += `var ${duration} = Math.max(0, 1000 * ${this.descendInput(node.times).asNumber()});\n`;
|
1249 |
+
this.requestRedraw();
|
1250 |
+
this.source += `while (thread.timer2.timeElapsed() < ${duration}) {\n`;
|
1251 |
+
this.descendStack(node.do, new Frame(true, 'control.repeatForSeconds'));
|
1252 |
+
this.yieldLoop();
|
1253 |
+
this.source += `}\n`;
|
1254 |
+
this.source += 'thread.timer2 = null;\n';
|
1255 |
+
break;
|
1256 |
+
}
|
1257 |
+
case 'control.stopAll':
|
1258 |
+
this.source += 'runtime.stopAll();\n';
|
1259 |
+
this.retire();
|
1260 |
+
break;
|
1261 |
+
case 'control.stopOthers':
|
1262 |
+
this.source += 'runtime.stopForTarget(target, thread);\n';
|
1263 |
+
break;
|
1264 |
+
case 'control.stopScript':
|
1265 |
+
if (this.isProcedure) {
|
1266 |
+
this.source += 'return;\n';
|
1267 |
+
} else {
|
1268 |
+
this.retire();
|
1269 |
+
}
|
1270 |
+
break;
|
1271 |
+
case 'control.wait': {
|
1272 |
+
const duration = this.localVariables.next();
|
1273 |
+
this.source += `thread.timer = timer();\n`;
|
1274 |
+
this.source += `var ${duration} = Math.max(0, 1000 * ${this.descendInput(node.seconds).asNumber()});\n`;
|
1275 |
+
this.requestRedraw();
|
1276 |
+
// always yield at least once, even on 0 second durations
|
1277 |
+
this.yieldNotWarp();
|
1278 |
+
this.source += `while (thread.timer.timeElapsed() < ${duration}) {\n`;
|
1279 |
+
this.yieldStuckOrNotWarp();
|
1280 |
+
this.source += '}\n';
|
1281 |
+
this.source += 'thread.timer = null;\n';
|
1282 |
+
break;
|
1283 |
+
}
|
1284 |
+
case 'control.waitTick': {
|
1285 |
+
this.yieldNotWarp();
|
1286 |
+
break;
|
1287 |
+
}
|
1288 |
+
case 'control.waitUntil': {
|
1289 |
+
this.resetVariableInputs();
|
1290 |
+
this.source += `while (!${this.descendInput(node.condition).asBoolean()}) {\n`;
|
1291 |
+
this.yieldStuckOrNotWarp();
|
1292 |
+
this.source += `}\n`;
|
1293 |
+
break;
|
1294 |
+
}
|
1295 |
+
case 'control.waitOrUntil': {
|
1296 |
+
const duration = this.localVariables.next();
|
1297 |
+
const condition = this.descendInput(node.condition).asBoolean();
|
1298 |
+
this.source += `thread.timer = timer();\n`;
|
1299 |
+
this.source += `var ${duration} = Math.max(0, 1000 * ${this.descendInput(node.seconds).asNumber()});\n`;
|
1300 |
+
this.requestRedraw();
|
1301 |
+
// always yield at least once, even on 0 second durations
|
1302 |
+
this.yieldNotWarp();
|
1303 |
+
this.source += `while ((thread.timer.timeElapsed() < ${duration}) && (!(${condition}))) {\n`;
|
1304 |
+
this.yieldStuckOrNotWarp();
|
1305 |
+
this.source += '}\n';
|
1306 |
+
this.source += 'thread.timer = null;\n';
|
1307 |
+
break;
|
1308 |
+
}
|
1309 |
+
case 'control.while':
|
1310 |
+
this.resetVariableInputs();
|
1311 |
+
this.source += `while (${this.descendInput(node.condition).asBoolean()}) {\n`;
|
1312 |
+
this.descendStack(node.do, new Frame(true, 'control.while'));
|
1313 |
+
if (node.warpTimer) {
|
1314 |
+
this.yieldStuckOrNotWarp();
|
1315 |
+
} else {
|
1316 |
+
this.yieldLoop();
|
1317 |
+
}
|
1318 |
+
this.source += `}\n`;
|
1319 |
+
break;
|
1320 |
+
case 'control.runAsSprite':
|
1321 |
+
const stage = 'runtime.getTargetForStage()';
|
1322 |
+
const sprite = this.descendInput(node.sprite).asString();
|
1323 |
+
const isStage = sprite === '"_stage_"';
|
1324 |
+
|
1325 |
+
// save the original target
|
1326 |
+
const originalTarget = this.localVariables.next();
|
1327 |
+
this.source += `const ${originalTarget} = target;\n`;
|
1328 |
+
// pm: unknown behavior may appear so lets use try catch
|
1329 |
+
this.source += `try {\n`;
|
1330 |
+
// set target
|
1331 |
+
const evaluatedName = this.localVariables.next()
|
1332 |
+
this.source += `var ${evaluatedName} = ${sprite};\n`
|
1333 |
+
const targetSprite = isStage ? stage : `runtime.getSpriteTargetByName(${evaluatedName}) || runtime.getTargetById(${evaluatedName})`;
|
1334 |
+
this.source += `const target = (${targetSprite});\n`;
|
1335 |
+
// only run if target is found
|
1336 |
+
this.source += `if (target) {\n`;
|
1337 |
+
// set thread target (for compat blocks)
|
1338 |
+
this.source += `thread.target = target;\n`;
|
1339 |
+
// tell thread we are spoofing (for custom blocks)
|
1340 |
+
// we could already be spoofing tho so save that first
|
1341 |
+
const alreadySpoofing = this.localVariables.next();
|
1342 |
+
const alreadySpoofTarget = this.localVariables.next();
|
1343 |
+
this.source += `var ${alreadySpoofing} = thread.spoofing;\n`;
|
1344 |
+
this.source += `var ${alreadySpoofTarget} = thread.spoofTarget;\n`;
|
1345 |
+
|
1346 |
+
this.source += `thread.spoofing = true;\n`;
|
1347 |
+
this.source += `thread.spoofTarget = target;\n`;
|
1348 |
+
|
1349 |
+
// descendle stackle
|
1350 |
+
this.descendStack(node.substack, new Frame(false, 'control.runAsSprite'));
|
1351 |
+
|
1352 |
+
// undo thread target & spoofing change
|
1353 |
+
this.source += `thread.target = ${originalTarget};\n`;
|
1354 |
+
this.source += `thread.spoofing = ${alreadySpoofing};\n`;
|
1355 |
+
this.source += `thread.spoofTarget = ${alreadySpoofTarget};\n`;
|
1356 |
+
|
1357 |
+
this.source += `}\n`;
|
1358 |
+
this.source += `} catch (e) {\nconsole.log('as sprite function failed;', e);\n`;
|
1359 |
+
|
1360 |
+
// same as last undo
|
1361 |
+
this.source += `thread.target = ${originalTarget};\n`;
|
1362 |
+
this.source += `thread.spoofing = ${alreadySpoofing};\n`;
|
1363 |
+
this.source += `thread.spoofTarget = ${alreadySpoofTarget};\n`;
|
1364 |
+
|
1365 |
+
this.source += `}\n`;
|
1366 |
+
break;
|
1367 |
+
case 'counter.clear':
|
1368 |
+
this.source += 'runtime.ext_scratch3_control._counter = 0;\n';
|
1369 |
+
break;
|
1370 |
+
case 'counter.increment':
|
1371 |
+
this.source += 'runtime.ext_scratch3_control._counter++;\n';
|
1372 |
+
break;
|
1373 |
+
case 'counter.decrement':
|
1374 |
+
this.source += 'runtime.ext_scratch3_control._counter--;\n';
|
1375 |
+
break;
|
1376 |
+
case 'counter.set':
|
1377 |
+
this.source += `runtime.ext_scratch3_control._counter = ${this.descendInput(node.value).asNumber()};\n`;
|
1378 |
+
break;
|
1379 |
+
case 'hat.edge':
|
1380 |
+
this.isInHat = true;
|
1381 |
+
this.source += '{\n';
|
1382 |
+
// For exact Scratch parity, evaluate the input before checking old edge state.
|
1383 |
+
// Can matter if the input is not instantly evaluated.
|
1384 |
+
this.source += `const resolvedValue = ${this.descendInput(node.condition).asBoolean()};\n`;
|
1385 |
+
this.source += `const id = "${sanitize(node.id)}";\n`;
|
1386 |
+
this.source += 'const hasOldEdgeValue = target.hasEdgeActivatedValue(id);\n';
|
1387 |
+
this.source += `const oldEdgeValue = target.updateEdgeActivatedValue(id, resolvedValue);\n`;
|
1388 |
+
this.source += `const edgeWasActivated = hasOldEdgeValue ? (!oldEdgeValue && resolvedValue) : resolvedValue;\n`;
|
1389 |
+
this.source += `if (!edgeWasActivated) {\n`;
|
1390 |
+
this.retire();
|
1391 |
+
this.source += '}\n';
|
1392 |
+
this.source += 'yield;\n';
|
1393 |
+
this.source += '}\n';
|
1394 |
+
this.isInHat = false;
|
1395 |
+
break;
|
1396 |
+
case 'hat.predicate':
|
1397 |
+
this.isInHat = true;
|
1398 |
+
this.source += `if (!${this.descendInput(node.condition).asBoolean()}) {\n`;
|
1399 |
+
this.retire();
|
1400 |
+
this.source += '}\n';
|
1401 |
+
this.source += 'yield;\n';
|
1402 |
+
this.isInHat = false;
|
1403 |
+
break;
|
1404 |
+
case 'event.broadcast':
|
1405 |
+
this.source += `var broadcastVar = runtime.getTargetForStage().lookupBroadcastMsg("", ${this.descendInput(node.broadcast).asString()} );`;
|
1406 |
+
this.source += `if (broadcastVar) broadcastVar.isSent = true;`;
|
1407 |
+
this.source += `startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} });\n`;
|
1408 |
+
this.resetVariableInputs();
|
1409 |
+
break;
|
1410 |
+
case 'event.broadcastAndWait':
|
1411 |
+
this.source += `var broadcastVar = runtime.getTargetForStage().lookupBroadcastMsg("", ${this.descendInput(node.broadcast).asString()} );`;
|
1412 |
+
this.source += `if (broadcastVar) broadcastVar.isSent = true;`;
|
1413 |
+
this.source += `yield* waitThreads(startHats("event_whenbroadcastreceived", { BROADCAST_OPTION: ${this.descendInput(node.broadcast).asString()} }));\n`;
|
1414 |
+
this.yielded();
|
1415 |
+
break;
|
1416 |
+
case 'list.forEach': {
|
1417 |
+
const list = this.referenceVariable(node.list);
|
1418 |
+
const set = this.descendVariable(node.variable);
|
1419 |
+
const to = node.num ? 'index + 1' : 'value';
|
1420 |
+
this.source +=
|
1421 |
+
`for (let index = 0; index < ${list}.value.length; index++) {` +
|
1422 |
+
`const value = ${list}.value[index];` +
|
1423 |
+
`${set.source} = ${to};`;
|
1424 |
+
this.descendStack(node.do, new Frame(true, 'list.forEach'));
|
1425 |
+
this.source += `};\n`;
|
1426 |
+
break;
|
1427 |
+
}
|
1428 |
+
case 'list.add': {
|
1429 |
+
const list = this.referenceVariable(node.list);
|
1430 |
+
this.source += `${list}.value.push(${this.descendInput(node.item).asSafe()});\n`;
|
1431 |
+
this.source += `${list}._monitorUpToDate = false;\n`;
|
1432 |
+
break;
|
1433 |
+
}
|
1434 |
+
case 'list.delete': {
|
1435 |
+
const list = this.referenceVariable(node.list);
|
1436 |
+
const index = this.descendInput(node.index);
|
1437 |
+
if (index instanceof ConstantInput) {
|
1438 |
+
if (index.constantValue === 'last') {
|
1439 |
+
this.source += `${list}.value.pop();\n`;
|
1440 |
+
this.source += `${list}._monitorUpToDate = false;\n`;
|
1441 |
+
break;
|
1442 |
+
}
|
1443 |
+
if (+index.constantValue === 1) {
|
1444 |
+
this.source += `${list}.value.shift();\n`;
|
1445 |
+
this.source += `${list}._monitorUpToDate = false;\n`;
|
1446 |
+
break;
|
1447 |
+
}
|
1448 |
+
// do not need a special case for all as that is handled in IR generation (list.deleteAll)
|
1449 |
+
}
|
1450 |
+
this.source += `listDelete(${list}, ${index.asUnknown()});\n`;
|
1451 |
+
break;
|
1452 |
+
}
|
1453 |
+
case 'list.deleteAll':
|
1454 |
+
this.source += `${this.referenceVariable(node.list)}.value = [];\n`;
|
1455 |
+
break;
|
1456 |
+
case 'list.shift':
|
1457 |
+
const list = this.referenceVariable(node.list);
|
1458 |
+
const index = this.descendInput(node.index).asNumber();
|
1459 |
+
if (index <= 0) break;
|
1460 |
+
this.source += `${list}.value = ${list}.value.slice(${index});\n`
|
1461 |
+
this.source += `${list}._monitorUpToDate = false;\n`
|
1462 |
+
break
|
1463 |
+
case 'list.hide':
|
1464 |
+
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.list.id)}", element: "checkbox", value: false }, runtime);\n`;
|
1465 |
+
break;
|
1466 |
+
case 'list.insert': {
|
1467 |
+
const list = this.referenceVariable(node.list);
|
1468 |
+
const index = this.descendInput(node.index);
|
1469 |
+
const item = this.descendInput(node.item);
|
1470 |
+
if (index instanceof ConstantInput && +index.constantValue === 1) {
|
1471 |
+
this.source += `${list}.value.unshift(${item.asSafe()});\n`;
|
1472 |
+
this.source += `${list}._monitorUpToDate = false;\n`;
|
1473 |
+
break;
|
1474 |
+
}
|
1475 |
+
this.source += `listInsert(${list}, ${index.asUnknown()}, ${item.asSafe()});\n`;
|
1476 |
+
break;
|
1477 |
+
}
|
1478 |
+
case 'list.replace':
|
1479 |
+
this.source += `listReplace(${this.referenceVariable(node.list)}, ${this.descendInput(node.index).asUnknown()}, ${this.descendInput(node.item).asSafe()});\n`;
|
1480 |
+
break;
|
1481 |
+
case 'list.show':
|
1482 |
+
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.list.id)}", element: "checkbox", value: true }, runtime);\n`;
|
1483 |
+
break;
|
1484 |
+
|
1485 |
+
case 'list.filter':
|
1486 |
+
this.source += `${this.referenceVariable(node.list)}.value = ${this.referenceVariable(node.list)}.value.filter(function* (item, index) {`;
|
1487 |
+
this.source += ` runtime.ext_scratch3_data._listFilterItem = item;`;
|
1488 |
+
this.source += ` runtime.ext_scratch3_data._listFilterIndex = index + 1;`;
|
1489 |
+
this.source += ` return ${this.descendInput(node.bool).asBoolean()};`;
|
1490 |
+
this.source += `})`;
|
1491 |
+
this.source += `runtime.ext_scratch3_data._listFilterItem = "";`;
|
1492 |
+
this.source += `runtime.ext_scratch3_data._listFilterIndex = 0;`;
|
1493 |
+
break;
|
1494 |
+
|
1495 |
+
case 'looks.backwardLayers':
|
1496 |
+
if (!this.target.isStage) {
|
1497 |
+
this.source += `target.goBackwardLayers(${this.descendInput(node.layers).asNumber()});\n`;
|
1498 |
+
}
|
1499 |
+
break;
|
1500 |
+
case 'looks.clearEffects':
|
1501 |
+
this.source += 'target.clearEffects();\nruntime.ext_scratch3_looks._resetBubbles(target)\n';
|
1502 |
+
break;
|
1503 |
+
case 'looks.changeEffect':
|
1504 |
+
if (this.target.effects.hasOwnProperty(node.effect)) {
|
1505 |
+
this.source += `target.setEffect("${sanitize(node.effect)}", runtime.ext_scratch3_looks.clampEffect("${sanitize(node.effect)}", ${this.descendInput(node.value).asNumber()} + target.effects["${sanitize(node.effect)}"]));\n`;
|
1506 |
+
}
|
1507 |
+
break;
|
1508 |
+
case 'looks.changeSize':
|
1509 |
+
this.source += `target.setSize(target.size + ${this.descendInput(node.size).asNumber()});\n`;
|
1510 |
+
break;
|
1511 |
+
case 'looks.forwardLayers':
|
1512 |
+
if (!this.target.isStage) {
|
1513 |
+
this.source += `target.goForwardLayers(${this.descendInput(node.layers).asNumber()});\n`;
|
1514 |
+
}
|
1515 |
+
break;
|
1516 |
+
case 'looks.goToBack':
|
1517 |
+
if (!this.target.isStage) {
|
1518 |
+
this.source += 'target.goToBack();\n';
|
1519 |
+
}
|
1520 |
+
break;
|
1521 |
+
case 'looks.goToFront':
|
1522 |
+
if (!this.target.isStage) {
|
1523 |
+
this.source += 'target.goToFront();\n';
|
1524 |
+
}
|
1525 |
+
break;
|
1526 |
+
case 'looks.targetFront':
|
1527 |
+
if (!this.target.isStage) {
|
1528 |
+
const reqTarget = this.target.runtime.getSpriteTargetByName(node.layers.value);
|
1529 |
+
if (reqTarget) {
|
1530 |
+
this.source += `target.goBehindOther(${JSON.stringify(reqTarget)});\n`;
|
1531 |
+
this.source += `target.goForwardLayers(1);\n`;
|
1532 |
+
}
|
1533 |
+
}
|
1534 |
+
break;
|
1535 |
+
case 'looks.targetBack':
|
1536 |
+
if (!this.target.isStage) {
|
1537 |
+
const reqTarget = this.target.runtime.getSpriteTargetByName(node.layers.value);
|
1538 |
+
if (reqTarget && reqTarget.getLayerOrder() < this.target.getLayerOrder()) {
|
1539 |
+
this.source += `target.goBehindOther(${JSON.stringify(reqTarget)});\n`;
|
1540 |
+
}
|
1541 |
+
}
|
1542 |
+
break;
|
1543 |
+
case 'looks.hide':
|
1544 |
+
this.source += 'target.setVisible(false);\n';
|
1545 |
+
this.source += 'runtime.ext_scratch3_looks._renderBubble(target);\n';
|
1546 |
+
break;
|
1547 |
+
case 'looks.nextBackdrop':
|
1548 |
+
this.source += 'runtime.ext_scratch3_looks._setBackdrop(stage, stage.currentCostume + 1, true);\n';
|
1549 |
+
break;
|
1550 |
+
case 'looks.nextCostume':
|
1551 |
+
this.source += 'target.setCostume(target.currentCostume + 1);\n';
|
1552 |
+
break;
|
1553 |
+
case 'looks.setEffect':
|
1554 |
+
if (this.target.effects.hasOwnProperty(node.effect)) {
|
1555 |
+
this.source += `target.setEffect("${sanitize(node.effect)}", runtime.ext_scratch3_looks.clampEffect("${sanitize(node.effect)}", ${this.descendInput(node.value).asNumber()}));\n`;
|
1556 |
+
}
|
1557 |
+
break;
|
1558 |
+
case 'looks.setSize':
|
1559 |
+
this.source += `target.setSize(${this.descendInput(node.size).asNumber()});\n`;
|
1560 |
+
break;
|
1561 |
+
case 'looks.setFont':
|
1562 |
+
this.source += `runtime.ext_scratch3_looks.setFont({ font: ${this.descendInput(node.font).asString()}, size: ${this.descendInput(node.size).asNumber()} }, { target: target });\n`;
|
1563 |
+
break;
|
1564 |
+
case 'looks.setColor':
|
1565 |
+
this.source += `runtime.ext_scratch3_looks.setColor({ prop: "${sanitize(node.prop)}", color: ${this.descendInput(node.color).asColor()} }, { target: target });\n`;
|
1566 |
+
break;
|
1567 |
+
case 'looks.setTintColor':
|
1568 |
+
this.source += `runtime.ext_scratch3_looks.setTintColor({ color: ${this.descendInput(node.color).asColor()} }, { target: target });\n`;
|
1569 |
+
break;
|
1570 |
+
case 'looks.setShape':
|
1571 |
+
this.source += `runtime.ext_scratch3_looks.setShape({ prop: "${sanitize(node.prop)}", color: ${this.descendInput(node.value).asColor()} }, { target: target });\n`;
|
1572 |
+
break;
|
1573 |
+
case 'looks.show':
|
1574 |
+
this.source += 'target.setVisible(true);\n';
|
1575 |
+
this.source += 'runtime.ext_scratch3_looks._renderBubble(target);\n';
|
1576 |
+
break;
|
1577 |
+
case 'looks.switchBackdrop':
|
1578 |
+
this.source += `runtime.ext_scratch3_looks._setBackdrop(stage, ${this.descendInput(node.backdrop).asSafe()});\n`;
|
1579 |
+
break;
|
1580 |
+
case 'looks.switchCostume':
|
1581 |
+
this.source += `runtime.ext_scratch3_looks._setCostume(target, ${this.descendInput(node.costume).asSafe()});\n`;
|
1582 |
+
break;
|
1583 |
+
|
1584 |
+
case 'motion.changeX':
|
1585 |
+
this.source += `target.setXY(target.x + ${this.descendInput(node.dx).asNumber()}, target.y);\n`;
|
1586 |
+
break;
|
1587 |
+
case 'motion.changeY':
|
1588 |
+
this.source += `target.setXY(target.x, target.y + ${this.descendInput(node.dy).asNumber()});\n`;
|
1589 |
+
break;
|
1590 |
+
case 'motion.ifOnEdgeBounce':
|
1591 |
+
this.source += `runtime.ext_scratch3_motion._ifOnEdgeBounce(target);\n`;
|
1592 |
+
break;
|
1593 |
+
case 'motion.setDirection':
|
1594 |
+
this.source += `target.setDirection(${this.descendInput(node.direction).asNumber()});\n`;
|
1595 |
+
break;
|
1596 |
+
case 'motion.setRotationStyle':
|
1597 |
+
this.source += `target.setRotationStyle("${sanitize(node.style)}");\n`;
|
1598 |
+
break;
|
1599 |
+
case 'motion.setX': // fallthrough
|
1600 |
+
case 'motion.setY': // fallthrough
|
1601 |
+
case 'motion.setXY': {
|
1602 |
+
this.descendedIntoModulo = false;
|
1603 |
+
const x = 'x' in node ? this.descendInput(node.x).asNumber() : 'target.x';
|
1604 |
+
const y = 'y' in node ? this.descendInput(node.y).asNumber() : 'target.y';
|
1605 |
+
this.source += `target.setXY(${x}, ${y});\n`;
|
1606 |
+
if (this.descendedIntoModulo) {
|
1607 |
+
this.source += `if (target.interpolationData) target.interpolationData = null;\n`;
|
1608 |
+
}
|
1609 |
+
break;
|
1610 |
+
}
|
1611 |
+
case 'motion.step':
|
1612 |
+
this.source += `runtime.ext_scratch3_motion._moveSteps(${this.descendInput(node.steps).asNumber()}, target);\n`;
|
1613 |
+
break;
|
1614 |
+
|
1615 |
+
case 'noop':
|
1616 |
+
console.warn('unexpected noop');
|
1617 |
+
break;
|
1618 |
+
|
1619 |
+
case 'pen.clear':
|
1620 |
+
this.source += `${PEN_EXT}.clear();\n`;
|
1621 |
+
break;
|
1622 |
+
case 'pen.down':
|
1623 |
+
this.source += `${PEN_EXT}._penDown(target);\n`;
|
1624 |
+
break;
|
1625 |
+
case 'pen.changeParam':
|
1626 |
+
this.source += `${PEN_EXT}._setOrChangeColorParam(${this.descendInput(node.param).asString()}, ${this.descendInput(node.value).asNumber()}, ${PEN_STATE}, true);\n`;
|
1627 |
+
break;
|
1628 |
+
case 'pen.changeSize':
|
1629 |
+
this.source += `${PEN_EXT}._changePenSizeBy(${this.descendInput(node.size).asNumber()}, target);\n`;
|
1630 |
+
break;
|
1631 |
+
case 'pen.legacyChangeHue':
|
1632 |
+
this.source += `${PEN_EXT}._changePenHueBy(${this.descendInput(node.hue).asNumber()}, target);\n`;
|
1633 |
+
break;
|
1634 |
+
case 'pen.legacyChangeShade':
|
1635 |
+
this.source += `${PEN_EXT}._changePenShadeBy(${this.descendInput(node.shade).asNumber()}, target);\n`;
|
1636 |
+
break;
|
1637 |
+
case 'pen.legacySetHue':
|
1638 |
+
this.source += `${PEN_EXT}._setPenHueToNumber(${this.descendInput(node.hue).asNumber()}, target);\n`;
|
1639 |
+
break;
|
1640 |
+
case 'pen.legacySetShade':
|
1641 |
+
this.source += `${PEN_EXT}._setPenShadeToNumber(${this.descendInput(node.shade).asNumber()}, target);\n`;
|
1642 |
+
break;
|
1643 |
+
case 'pen.setColor':
|
1644 |
+
this.source += `${PEN_EXT}._setPenColorToColor(${this.descendInput(node.color).asColor()}, target);\n`;
|
1645 |
+
break;
|
1646 |
+
case 'pen.setParam':
|
1647 |
+
this.source += `${PEN_EXT}._setOrChangeColorParam(${this.descendInput(node.param).asString()}, ${this.descendInput(node.value).asNumber()}, ${PEN_STATE}, false);\n`;
|
1648 |
+
break;
|
1649 |
+
case 'pen.setSize':
|
1650 |
+
this.source += `${PEN_EXT}._setPenSizeTo(${this.descendInput(node.size).asNumber()}, target);\n`;
|
1651 |
+
break;
|
1652 |
+
case 'pen.stamp':
|
1653 |
+
this.source += `${PEN_EXT}._stamp(target);\n`;
|
1654 |
+
break;
|
1655 |
+
case 'pen.up':
|
1656 |
+
this.source += `${PEN_EXT}._penUp(target);\n`;
|
1657 |
+
break;
|
1658 |
+
|
1659 |
+
case 'procedures.return':
|
1660 |
+
this.source += `return ${this.descendInput(node.return).asUnknown()};`;
|
1661 |
+
break;
|
1662 |
+
case 'procedures.call': {
|
1663 |
+
const procedureCode = node.code;
|
1664 |
+
const procedureVariant = node.variant;
|
1665 |
+
// Do not generate any code for empty procedures.
|
1666 |
+
const procedureData = this.ir.procedures[procedureVariant];
|
1667 |
+
if (procedureData.stack === null) {
|
1668 |
+
break;
|
1669 |
+
}
|
1670 |
+
if (!this.isWarp && procedureCode === this.script.procedureCode) {
|
1671 |
+
// Direct recursion yields.
|
1672 |
+
this.yieldNotWarp();
|
1673 |
+
}
|
1674 |
+
if (procedureData.yields) {
|
1675 |
+
this.source += 'yield* ';
|
1676 |
+
if (!this.script.yields) {
|
1677 |
+
throw new Error('Script uses yielding procedure but is not marked as yielding.');
|
1678 |
+
}
|
1679 |
+
}
|
1680 |
+
this.source += `thread.procedures["${sanitize(procedureVariant)}"](`;
|
1681 |
+
// Only include arguments if the procedure accepts any.
|
1682 |
+
if (procedureData.arguments.length) {
|
1683 |
+
const args = [];
|
1684 |
+
for (const input of node.arguments) {
|
1685 |
+
args.push(this.descendInput(input).asSafe());
|
1686 |
+
}
|
1687 |
+
this.source += args.join(',');
|
1688 |
+
}
|
1689 |
+
this.source += `);\n`;
|
1690 |
+
if (node.type === 'hat') {
|
1691 |
+
throw new Error('Custom hat blocks are not supported');
|
1692 |
+
}
|
1693 |
+
// Variable input types may have changes after a procedure call.
|
1694 |
+
this.resetVariableInputs();
|
1695 |
+
break;
|
1696 |
+
}
|
1697 |
+
|
1698 |
+
case 'timer.reset':
|
1699 |
+
this.source += 'runtime.ioDevices.clock.resetProjectTimer();\n';
|
1700 |
+
break;
|
1701 |
+
|
1702 |
+
case 'tw.debugger':
|
1703 |
+
this.source += 'debugger;\n';
|
1704 |
+
break;
|
1705 |
+
|
1706 |
+
case 'var.hide':
|
1707 |
+
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.variable.id)}", element: "checkbox", value: false }, runtime);\n`;
|
1708 |
+
break;
|
1709 |
+
case 'var.set': {
|
1710 |
+
const variable = this.descendVariable(node.variable);
|
1711 |
+
const value = this.descendInput(node.value);
|
1712 |
+
variable.setInput(value);
|
1713 |
+
this.source += `${variable.source} = ${value.asSafe()};\n`;
|
1714 |
+
if (node.variable.isCloud) {
|
1715 |
+
this.source += `runtime.ioDevices.cloud.requestUpdateVariable("${sanitize(node.variable.name)}", ${variable.source});\n`;
|
1716 |
+
}
|
1717 |
+
break;
|
1718 |
+
}
|
1719 |
+
case 'var.show':
|
1720 |
+
this.source += `runtime.monitorBlocks.changeBlock({ id: "${sanitize(node.variable.id)}", element: "checkbox", value: true }, runtime);\n`;
|
1721 |
+
break;
|
1722 |
+
|
1723 |
+
case 'visualReport': {
|
1724 |
+
const value = this.localVariables.next();
|
1725 |
+
this.source += `const ${value} = ${this.descendInput(node.input, true).asUnknown()};`;
|
1726 |
+
// blocks like legacy no-ops can return a literal `undefined`
|
1727 |
+
this.source += `if (${value} !== undefined) runtime.visualReport("${sanitize(this.script.topBlockId)}", ${value});\n`;
|
1728 |
+
break;
|
1729 |
+
}
|
1730 |
+
case 'sensing.set.of': {
|
1731 |
+
const object = this.descendInput(node.object).asString();
|
1732 |
+
const value = this.descendInput(node.value);
|
1733 |
+
const property = node.property;
|
1734 |
+
const isStage = node.object.value === '_stage_';
|
1735 |
+
const objectReference = isStage ? 'stage' : this.evaluateOnce(`runtime.getSpriteTargetByName(${object})`);
|
1736 |
+
|
1737 |
+
this.source += `if (${objectReference})`;
|
1738 |
+
|
1739 |
+
switch (property) {
|
1740 |
+
case 'volume':
|
1741 |
+
this.source += `runtime.ext_scratch3_sound._updateVolume(${value.asNumber()}, ${objectReference});`;
|
1742 |
+
break;
|
1743 |
+
case 'x position':
|
1744 |
+
// comment
|
1745 |
+
this.source += `${objectReference}.setXY(${value.asNumber()}, ${objectReference}.y);`;
|
1746 |
+
break;
|
1747 |
+
case 'y position':
|
1748 |
+
this.source += `${objectReference}.setXY(${objectReference}.x, ${value.asNumber()});`;
|
1749 |
+
break;
|
1750 |
+
case 'direction':
|
1751 |
+
this.source += `${objectReference}.setDirection(${value.asNumber()});`;
|
1752 |
+
break;
|
1753 |
+
case 'costume':
|
1754 |
+
const costume = value.type === TYPE_NUMBER
|
1755 |
+
? value.asNumber()
|
1756 |
+
: value.asString();
|
1757 |
+
this.source += `runtime.ext_scratch3_looks._setCostume(${objectReference}, ${costume});`;
|
1758 |
+
break;
|
1759 |
+
case 'backdrop':
|
1760 |
+
const backdrop = value.type === TYPE_NUMBER
|
1761 |
+
? value.asNumber()
|
1762 |
+
: value.asString();
|
1763 |
+
this.source += `runtime.ext_scratch3_looks._setBackdrop(${objectReference}, ${backdrop});`;
|
1764 |
+
break;
|
1765 |
+
case 'size':
|
1766 |
+
this.source += `${objectReference}.setSize(${value.asNumber()});`;
|
1767 |
+
break;
|
1768 |
+
default:
|
1769 |
+
const variableReference = this.evaluateOnce(`${objectReference} && ${objectReference}.lookupVariableByNameAndType("${sanitize(property)}", "", true)`);
|
1770 |
+
this.source += `if (${variableReference}) `;
|
1771 |
+
this.source += `${variableReference}.value = ${value.asString()};`;
|
1772 |
+
break;
|
1773 |
+
}
|
1774 |
+
break;
|
1775 |
+
}
|
1776 |
+
|
1777 |
+
case 'tempVars.set': {
|
1778 |
+
const name = this.descendInput(node.var);
|
1779 |
+
const val = this.descendInput(node.val);
|
1780 |
+
const hostObj = node.runtime
|
1781 |
+
? 'runtime.variables'
|
1782 |
+
: node.thread
|
1783 |
+
? 'thread.variables'
|
1784 |
+
: 'tempVars';
|
1785 |
+
this.source += this.isOptimized
|
1786 |
+
? `${hostObj}[${name.asString()}] = ${val.asUnknown()};`
|
1787 |
+
: `set(${hostObj}, ${name.asString()}, ${val.asUnknown()});`;
|
1788 |
+
break;
|
1789 |
+
}
|
1790 |
+
case 'tempVars.delete': {
|
1791 |
+
const name = this.descendInput(node.var);
|
1792 |
+
const hostObj = node.runtime
|
1793 |
+
? 'runtime.variables'
|
1794 |
+
: node.thread
|
1795 |
+
? 'thread.variables'
|
1796 |
+
: 'tempVars';
|
1797 |
+
this.source += this.isOptimized
|
1798 |
+
? `delete ${hostObj}[${name.asString()}];`
|
1799 |
+
: `remove(${hostObj}, ${name.asString()});`;
|
1800 |
+
break;
|
1801 |
+
}
|
1802 |
+
case 'tempVars.deleteAll': {
|
1803 |
+
const hostObj = node.runtime
|
1804 |
+
? 'runtime.variables'
|
1805 |
+
: node.thread
|
1806 |
+
? 'thread.variables'
|
1807 |
+
: 'tempVars';
|
1808 |
+
this.source += `${hostObj} = Object.create(null);`;
|
1809 |
+
break;
|
1810 |
+
}
|
1811 |
+
case 'tempVars.forEach': {
|
1812 |
+
const name = this.descendInput(node.var);
|
1813 |
+
const loops = this.descendInput(node.loops);
|
1814 |
+
const hostObj = node.runtime
|
1815 |
+
? 'runtime.variables'
|
1816 |
+
: node.thread
|
1817 |
+
? 'thread.variables'
|
1818 |
+
: 'tempVars';
|
1819 |
+
const rootVar = this.localVariables.next();
|
1820 |
+
const keyVar = this.localVariables.next();
|
1821 |
+
const index = this.isOptimized
|
1822 |
+
? `${hostObj}[${name.asString()}]`
|
1823 |
+
: `${rootVar}[${keyVar}]`;
|
1824 |
+
if (!this.isOptimized)
|
1825 |
+
this.source += `const [${rootVar},${keyVar}] = _resolveKeyPath(${hostObj}, ${name.asString()}); `;
|
1826 |
+
this.source += `${index} = 0; `;
|
1827 |
+
this.source += `while (${index} < ${loops.asNumber()}) { `;
|
1828 |
+
this.source += `${index}++;\n`;
|
1829 |
+
this.descendStack(node.do, new Frame(true, 'tempVars.forEach'));
|
1830 |
+
this.yieldLoop();
|
1831 |
+
this.source += '}\n';
|
1832 |
+
break;
|
1833 |
+
}
|
1834 |
+
case 'control.dualBlock':
|
1835 |
+
this.source += `console.log("dual block works");`
|
1836 |
+
break
|
1837 |
+
|
1838 |
+
default:
|
1839 |
+
log.warn(`JS: Unknown stacked block: ${node.kind}`, node);
|
1840 |
+
throw new Error(`JS: Unknown stacked block: ${node.kind}`);
|
1841 |
+
}
|
1842 |
+
}
|
1843 |
+
|
1844 |
+
/**
|
1845 |
+
* Compile a Record of input objects into a safe JS string.
|
1846 |
+
* @param {Record<string, unknown>} inputs
|
1847 |
+
* @returns {string}
|
1848 |
+
*/
|
1849 |
+
descendInputRecord (inputs) {
|
1850 |
+
let result = '{';
|
1851 |
+
for (const name of Object.keys(inputs)) {
|
1852 |
+
const node = inputs[name];
|
1853 |
+
result += `"${sanitize(name)}":${this.descendInput(node).asSafe()},`;
|
1854 |
+
}
|
1855 |
+
result += '}';
|
1856 |
+
return result;
|
1857 |
+
}
|
1858 |
+
|
1859 |
+
resetVariableInputs () {
|
1860 |
+
this.variableInputs = {};
|
1861 |
+
}
|
1862 |
+
|
1863 |
+
descendStack (nodes, frame) {
|
1864 |
+
// Entering a stack -- all bets are off.
|
1865 |
+
// TODO: allow if/else to inherit values
|
1866 |
+
this.resetVariableInputs();
|
1867 |
+
frame.assignData(this.currentFrame);
|
1868 |
+
this.pushFrame(frame);
|
1869 |
+
|
1870 |
+
for (let i = 0; i < nodes.length; i++) {
|
1871 |
+
frame.isLastBlock = i === nodes.length - 1;
|
1872 |
+
this.descendStackedBlock(nodes[i]);
|
1873 |
+
}
|
1874 |
+
|
1875 |
+
// Leaving a stack -- any assumptions made in the current stack do not apply outside of it
|
1876 |
+
// TODO: in if/else this might create an extra unused object
|
1877 |
+
this.resetVariableInputs();
|
1878 |
+
this.popFrame();
|
1879 |
+
}
|
1880 |
+
|
1881 |
+
descendVariable (variable) {
|
1882 |
+
if (this.variableInputs.hasOwnProperty(variable.id)) {
|
1883 |
+
return this.variableInputs[variable.id];
|
1884 |
+
}
|
1885 |
+
const input = new VariableInput(`${this.referenceVariable(variable)}.value`);
|
1886 |
+
this.variableInputs[variable.id] = input;
|
1887 |
+
return input;
|
1888 |
+
}
|
1889 |
+
|
1890 |
+
referenceVariable (variable) {
|
1891 |
+
if (variable.scope === 'target') {
|
1892 |
+
return this.evaluateOnce(`target.variables["${sanitize(variable.id)}"]`);
|
1893 |
+
}
|
1894 |
+
return this.evaluateOnce(`stage.variables["${sanitize(variable.id)}"]`);
|
1895 |
+
}
|
1896 |
+
|
1897 |
+
evaluateOnce (source) {
|
1898 |
+
if (this._setupVariables.hasOwnProperty(source)) {
|
1899 |
+
return this._setupVariables[source];
|
1900 |
+
}
|
1901 |
+
const variable = this._setupVariablesPool.next();
|
1902 |
+
this._setupVariables[source] = variable;
|
1903 |
+
return variable;
|
1904 |
+
}
|
1905 |
+
|
1906 |
+
retire () {
|
1907 |
+
// After running retire() (sets thread status and cleans up some unused data), we need to return to the event loop.
|
1908 |
+
// When in a procedure, return will only send us back to the previous procedure, so instead we yield back to the sequencer.
|
1909 |
+
// Outside of a procedure, return will correctly bring us back to the sequencer.
|
1910 |
+
if (this.isProcedure) {
|
1911 |
+
this.source += 'retire(); yield;\n';
|
1912 |
+
} else {
|
1913 |
+
this.source += 'retire(); return;\n';
|
1914 |
+
}
|
1915 |
+
}
|
1916 |
+
|
1917 |
+
yieldLoop () {
|
1918 |
+
if (this.warpTimer) {
|
1919 |
+
this.yieldStuckOrNotWarp();
|
1920 |
+
} else {
|
1921 |
+
this.yieldNotWarp();
|
1922 |
+
}
|
1923 |
+
}
|
1924 |
+
|
1925 |
+
/**
|
1926 |
+
* Write JS to yield the current thread if warp mode is disabled.
|
1927 |
+
*/
|
1928 |
+
yieldNotWarp () {
|
1929 |
+
if (!this.isWarp) {
|
1930 |
+
this.source += 'yield;\n';
|
1931 |
+
this.yielded();
|
1932 |
+
}
|
1933 |
+
}
|
1934 |
+
|
1935 |
+
/**
|
1936 |
+
* Write JS to yield the current thread if warp mode is disabled or if the script seems to be stuck.
|
1937 |
+
*/
|
1938 |
+
yieldStuckOrNotWarp () {
|
1939 |
+
if (this.isWarp) {
|
1940 |
+
this.source += 'if (isStuck()) yield;\n';
|
1941 |
+
} else {
|
1942 |
+
this.source += 'yield;\n';
|
1943 |
+
}
|
1944 |
+
this.yielded();
|
1945 |
+
}
|
1946 |
+
|
1947 |
+
yielded () {
|
1948 |
+
if (!this.script.yields) {
|
1949 |
+
throw new Error('Script yielded but is not marked as yielding.');
|
1950 |
+
}
|
1951 |
+
// Control may have been yielded to another script -- all bets are off.
|
1952 |
+
this.resetVariableInputs();
|
1953 |
+
}
|
1954 |
+
|
1955 |
+
/**
|
1956 |
+
* Write JS to request a redraw.
|
1957 |
+
*/
|
1958 |
+
requestRedraw () {
|
1959 |
+
this.source += 'runtime.requestRedraw();\n';
|
1960 |
+
}
|
1961 |
+
|
1962 |
+
safeConstantInput (value) {
|
1963 |
+
const unsafe = typeof value === 'string' && this.namesOfCostumesAndSounds.has(value);
|
1964 |
+
return new ConstantInput(value, !unsafe);
|
1965 |
+
}
|
1966 |
+
|
1967 |
+
/**
|
1968 |
+
* Generate a call into the compatibility layer.
|
1969 |
+
* @param {*} node The "compat" kind node to generate from.
|
1970 |
+
* @param {boolean} setFlags Whether flags should be set describing how this function was processed.
|
1971 |
+
* @param {string|null} [frameName] Name of the stack frame variable, if any
|
1972 |
+
* @param {boolean} visualReport if this is being called to get visual reporter content
|
1973 |
+
* @returns {string} The JS of the call.
|
1974 |
+
*/
|
1975 |
+
generateCompatibilityLayerCall (node, setFlags, frameName = null, visualReport) {
|
1976 |
+
const opcode = node.opcode;
|
1977 |
+
|
1978 |
+
let result = 'yield* executeInCompatibilityLayer({';
|
1979 |
+
|
1980 |
+
for (const inputName of Object.keys(node.inputs)) {
|
1981 |
+
const input = node.inputs[inputName];
|
1982 |
+
if (inputName.startsWith('substack')) {
|
1983 |
+
result += `"${sanitize(inputName.toLowerCase())}":(function* () {\n`;
|
1984 |
+
this.descendStack(input, new Frame(true, opcode));
|
1985 |
+
result += '}),';
|
1986 |
+
continue;
|
1987 |
+
}
|
1988 |
+
const compiledInput = this.descendInput(input).asSafe();
|
1989 |
+
result += `"${sanitize(inputName)}":${compiledInput},`;
|
1990 |
+
}
|
1991 |
+
for (const fieldName of Object.keys(node.fields)) {
|
1992 |
+
const field = node.fields[fieldName];
|
1993 |
+
if (typeof field !== 'string') {
|
1994 |
+
result += `"${sanitize(fieldName)}":${JSON.stringify(field)},`;
|
1995 |
+
continue;
|
1996 |
+
}
|
1997 |
+
result += `"${sanitize(fieldName)}":"${sanitize(field)}",`;
|
1998 |
+
}
|
1999 |
+
result += `"mutation":${JSON.stringify(node.mutation)},`;
|
2000 |
+
const opcodeFunction = this.evaluateOnce(`runtime.getOpcodeFunction("${sanitize(opcode)}")`);
|
2001 |
+
result += `}, ${opcodeFunction}, ${this.isWarp}, ${setFlags}, "${sanitize(node.id)}", ${frameName}, ${visualReport})`;
|
2002 |
+
|
2003 |
+
return result;
|
2004 |
+
}
|
2005 |
+
|
2006 |
+
getScriptFactoryName () {
|
2007 |
+
return factoryNameVariablePool.next();
|
2008 |
+
}
|
2009 |
+
|
2010 |
+
getScriptName (yields) {
|
2011 |
+
let name = yields ? generatorNameVariablePool.next() : functionNameVariablePool.next();
|
2012 |
+
if (this.isProcedure) {
|
2013 |
+
const simplifiedProcedureCode = this.script.procedureCode
|
2014 |
+
.replace(/%[\w]/g, '') // remove arguments
|
2015 |
+
.replace(/[^a-zA-Z0-9]/g, '_') // remove unsafe
|
2016 |
+
.substring(0, 20); // keep length reasonable
|
2017 |
+
name += `_${simplifiedProcedureCode}`;
|
2018 |
+
}
|
2019 |
+
return name;
|
2020 |
+
}
|
2021 |
+
|
2022 |
+
/**
|
2023 |
+
* Generate the JS to pass into eval() based on the current state of the compiler.
|
2024 |
+
* @returns {string} JS to pass into eval()
|
2025 |
+
*/
|
2026 |
+
createScriptFactory () {
|
2027 |
+
let script = '';
|
2028 |
+
|
2029 |
+
// Setup the factory
|
2030 |
+
script += `(function ${this.getScriptFactoryName()}(thread) { `;
|
2031 |
+
script += 'let __target = thread.target; ';
|
2032 |
+
script += 'let target = __target; ';
|
2033 |
+
script += 'const runtime = __target.runtime; ';
|
2034 |
+
script += 'const stage = runtime.getTargetForStage();\n';
|
2035 |
+
for (const varValue of Object.keys(this._setupVariables)) {
|
2036 |
+
const varName = this._setupVariables[varValue];
|
2037 |
+
script += `const ${varName} = ${varValue};\n`;
|
2038 |
+
}
|
2039 |
+
|
2040 |
+
// Generated script
|
2041 |
+
script += 'return ';
|
2042 |
+
if (this.script.yields) {
|
2043 |
+
script += `function* `;
|
2044 |
+
} else {
|
2045 |
+
script += `function `;
|
2046 |
+
}
|
2047 |
+
script += this.getScriptName(this.script.yields);
|
2048 |
+
script += ' (';
|
2049 |
+
if (this.script.arguments.length) {
|
2050 |
+
const args = [];
|
2051 |
+
for (let i = 0; i < this.script.arguments.length; i++) {
|
2052 |
+
args.push(`p${i}`);
|
2053 |
+
}
|
2054 |
+
script += args.join(',');
|
2055 |
+
}
|
2056 |
+
script += ') {\n';
|
2057 |
+
script += 'let tempVars = Object.create(null);';
|
2058 |
+
|
2059 |
+
// pm: check if we are spoofing the target
|
2060 |
+
// ex: as (Sprite) {} block needs to replace the target
|
2061 |
+
// with a different one
|
2062 |
+
|
2063 |
+
// create new var with target so we can define target as the current one
|
2064 |
+
script += `let target = __target;\n`;
|
2065 |
+
script += `if (thread.spoofing) {\n`;
|
2066 |
+
script += `target = thread.spoofTarget;\n`;
|
2067 |
+
script += `};\n`;
|
2068 |
+
script += 'try {\n';
|
2069 |
+
|
2070 |
+
script += this.source;
|
2071 |
+
|
2072 |
+
script += '} catch (err) {';
|
2073 |
+
script += `console.log("${sanitize(script)}");`;
|
2074 |
+
script += 'console.error(err);';
|
2075 |
+
script += `runtime.emit("BLOCK_STACK_ERROR", {`;
|
2076 |
+
script += `id:"${sanitize(this.script.topBlockId)}",`;
|
2077 |
+
script += `value:String(err)`;
|
2078 |
+
script += `});`;
|
2079 |
+
script += '}\n';
|
2080 |
+
if (!this.isProcedure) {
|
2081 |
+
script += 'retire();\n';
|
2082 |
+
}
|
2083 |
+
script += '}; })';
|
2084 |
+
return script;
|
2085 |
+
}
|
2086 |
+
|
2087 |
+
/**
|
2088 |
+
* Compile this script.
|
2089 |
+
* @returns {Function} The factory function for the script.
|
2090 |
+
*/
|
2091 |
+
compile () {
|
2092 |
+
if (this.script.stack) {
|
2093 |
+
this.descendStack(this.script.stack, new Frame(false));
|
2094 |
+
}
|
2095 |
+
|
2096 |
+
const factory = this.createScriptFactory();
|
2097 |
+
const fn = jsexecute.scopedEval(factory);
|
2098 |
+
|
2099 |
+
if (this.debug) {
|
2100 |
+
log.info(`JS: ${this.target.getName()}: compiled ${this.script.procedureCode || 'script'}`, factory);
|
2101 |
+
}
|
2102 |
+
|
2103 |
+
if (JSGenerator.testingApparatus) {
|
2104 |
+
JSGenerator.testingApparatus.report(this, factory);
|
2105 |
+
}
|
2106 |
+
|
2107 |
+
return fn;
|
2108 |
+
}
|
2109 |
+
}
|
2110 |
+
|
2111 |
+
// Test hook used by automated snapshot testing.
|
2112 |
+
JSGenerator.testingApparatus = null;
|
2113 |
+
|
2114 |
+
module.exports = JSGenerator;
|
src/compiler/variable-pool.js
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class VariablePool {
|
2 |
+
/**
|
3 |
+
* @param {string} prefix The prefix at the start of the variable name.
|
4 |
+
*/
|
5 |
+
constructor (prefix) {
|
6 |
+
if (prefix.trim().length === 0) {
|
7 |
+
throw new Error('prefix cannot be empty');
|
8 |
+
}
|
9 |
+
this.prefix = prefix;
|
10 |
+
/**
|
11 |
+
* @private
|
12 |
+
*/
|
13 |
+
this.count = 0;
|
14 |
+
}
|
15 |
+
|
16 |
+
next () {
|
17 |
+
return `${this.prefix}${this.count++}`;
|
18 |
+
}
|
19 |
+
}
|
20 |
+
|
21 |
+
module.exports = VariablePool;
|
src/dispatch/central-dispatch.js
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const SharedDispatch = require('./shared-dispatch');
|
2 |
+
|
3 |
+
const log = require('../util/log');
|
4 |
+
|
5 |
+
/**
|
6 |
+
* This class serves as the central broker for message dispatch. It expects to operate on the main thread / Window and
|
7 |
+
* it must be informed of any Worker threads which will participate in the messaging system. From any context in the
|
8 |
+
* messaging system, the dispatcher's "call" method can call any method on any "service" provided in any participating
|
9 |
+
* context. The dispatch system will forward function arguments and return values across worker boundaries as needed.
|
10 |
+
* @see {WorkerDispatch}
|
11 |
+
*/
|
12 |
+
class CentralDispatch extends SharedDispatch {
|
13 |
+
constructor () {
|
14 |
+
super();
|
15 |
+
|
16 |
+
/**
|
17 |
+
* Map of channel name to worker or local service provider.
|
18 |
+
* If the entry is a Worker, the service is provided by an object on that worker.
|
19 |
+
* Otherwise, the service is provided locally and methods on the service will be called directly.
|
20 |
+
* @see {setService}
|
21 |
+
* @type {object.<Worker|object>}
|
22 |
+
*/
|
23 |
+
this.services = {};
|
24 |
+
|
25 |
+
/**
|
26 |
+
* The constructor we will use to recognize workers.
|
27 |
+
* @type {Function}
|
28 |
+
*/
|
29 |
+
this.workerClass = (typeof Worker === 'undefined' ? null : Worker);
|
30 |
+
|
31 |
+
/**
|
32 |
+
* List of workers attached to this dispatcher.
|
33 |
+
* @type {Array}
|
34 |
+
*/
|
35 |
+
this.workers = [];
|
36 |
+
}
|
37 |
+
|
38 |
+
/**
|
39 |
+
* Synchronously call a particular method on a particular service provided locally.
|
40 |
+
* Calling this function on a remote service will fail.
|
41 |
+
* @param {string} service - the name of the service.
|
42 |
+
* @param {string} method - the name of the method.
|
43 |
+
* @param {*} [args] - the arguments to be copied to the method, if any.
|
44 |
+
* @returns {*} - the return value of the service method.
|
45 |
+
*/
|
46 |
+
callSync (service, method, ...args) {
|
47 |
+
const {provider, isRemote} = this._getServiceProvider(service);
|
48 |
+
if (provider) {
|
49 |
+
if (isRemote) {
|
50 |
+
throw new Error(`Cannot use 'callSync' on remote provider for service ${service}.`);
|
51 |
+
}
|
52 |
+
|
53 |
+
return provider[method].apply(provider, args);
|
54 |
+
}
|
55 |
+
throw new Error(`Provider not found for service: ${service}`);
|
56 |
+
}
|
57 |
+
|
58 |
+
/**
|
59 |
+
* Synchronously set a local object as the global provider of the specified service.
|
60 |
+
* WARNING: Any method on the provider can be called from any worker within the dispatch system.
|
61 |
+
* @param {string} service - a globally unique string identifying this service. Examples: 'vm', 'gui', 'extension9'.
|
62 |
+
* @param {object} provider - a local object which provides this service.
|
63 |
+
*/
|
64 |
+
setServiceSync (service, provider) {
|
65 |
+
if (this.services.hasOwnProperty(service)) {
|
66 |
+
log.warn(`Central dispatch replacing existing service provider for ${service}`);
|
67 |
+
}
|
68 |
+
this.services[service] = provider;
|
69 |
+
}
|
70 |
+
|
71 |
+
/**
|
72 |
+
* Set a local object as the global provider of the specified service.
|
73 |
+
* WARNING: Any method on the provider can be called from any worker within the dispatch system.
|
74 |
+
* @param {string} service - a globally unique string identifying this service. Examples: 'vm', 'gui', 'extension9'.
|
75 |
+
* @param {object} provider - a local object which provides this service.
|
76 |
+
* @returns {Promise} - a promise which will resolve once the service is registered.
|
77 |
+
*/
|
78 |
+
setService (service, provider) {
|
79 |
+
/** Return a promise for consistency with {@link WorkerDispatch#setService} */
|
80 |
+
try {
|
81 |
+
this.setServiceSync(service, provider);
|
82 |
+
return Promise.resolve();
|
83 |
+
} catch (e) {
|
84 |
+
return Promise.reject(e);
|
85 |
+
}
|
86 |
+
}
|
87 |
+
|
88 |
+
/**
|
89 |
+
* Add a worker to the message dispatch system. The worker must implement a compatible message dispatch framework.
|
90 |
+
* The dispatcher will immediately attempt to "handshake" with the worker.
|
91 |
+
* @param {Worker} worker - the worker to add into the dispatch system.
|
92 |
+
*/
|
93 |
+
addWorker (worker) {
|
94 |
+
if (this.workers.indexOf(worker) === -1) {
|
95 |
+
this.workers.push(worker);
|
96 |
+
worker.onmessage = this._onMessage.bind(this, worker);
|
97 |
+
this._remoteCall(worker, 'dispatch', 'handshake').catch(e => {
|
98 |
+
log.error(`Could not handshake with worker: ${e}`);
|
99 |
+
});
|
100 |
+
} else {
|
101 |
+
log.warn('Central dispatch ignoring attempt to add duplicate worker');
|
102 |
+
}
|
103 |
+
}
|
104 |
+
|
105 |
+
/**
|
106 |
+
* Fetch the service provider object for a particular service name.
|
107 |
+
* @override
|
108 |
+
* @param {string} service - the name of the service to look up
|
109 |
+
* @returns {{provider:(object|Worker), isRemote:boolean}} - the means to contact the service, if found
|
110 |
+
* @protected
|
111 |
+
*/
|
112 |
+
_getServiceProvider (service) {
|
113 |
+
const provider = this.services[service];
|
114 |
+
return provider && {
|
115 |
+
provider,
|
116 |
+
isRemote: Boolean((this.workerClass && provider instanceof this.workerClass) || provider.isRemote)
|
117 |
+
};
|
118 |
+
}
|
119 |
+
|
120 |
+
/**
|
121 |
+
* Handle a call message sent to the dispatch service itself
|
122 |
+
* @override
|
123 |
+
* @param {Worker} worker - the worker which sent the message.
|
124 |
+
* @param {DispatchCallMessage} message - the message to be handled.
|
125 |
+
* @returns {Promise|undefined} - a promise for the results of this operation, if appropriate
|
126 |
+
* @protected
|
127 |
+
*/
|
128 |
+
_onDispatchMessage (worker, message) {
|
129 |
+
let promise;
|
130 |
+
switch (message.method) {
|
131 |
+
case 'setService':
|
132 |
+
promise = this.setService(message.args[0], worker);
|
133 |
+
break;
|
134 |
+
default:
|
135 |
+
log.error(`Central dispatch received message for unknown method: ${message.method}`);
|
136 |
+
}
|
137 |
+
return promise;
|
138 |
+
}
|
139 |
+
}
|
140 |
+
|
141 |
+
module.exports = new CentralDispatch();
|
src/dispatch/shared-dispatch.js
ADDED
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const log = require('../util/log');
|
2 |
+
|
3 |
+
/**
|
4 |
+
* @typedef {object} DispatchCallMessage - a message to the dispatch system representing a service method call
|
5 |
+
* @property {*} responseId - send a response message with this response ID. See {@link DispatchResponseMessage}
|
6 |
+
* @property {string} service - the name of the service to be called
|
7 |
+
* @property {string} method - the name of the method to be called
|
8 |
+
* @property {Array|undefined} args - the arguments to be passed to the method
|
9 |
+
*/
|
10 |
+
|
11 |
+
/**
|
12 |
+
* @typedef {object} DispatchResponseMessage - a message to the dispatch system representing the results of a call
|
13 |
+
* @property {*} responseId - a copy of the response ID from the call which generated this response
|
14 |
+
* @property {*|undefined} error - if this is truthy, then it contains results from a failed call (such as an exception)
|
15 |
+
* @property {*|undefined} result - if error is not truthy, then this contains the return value of the call (if any)
|
16 |
+
*/
|
17 |
+
|
18 |
+
/**
|
19 |
+
* @typedef {DispatchCallMessage|DispatchResponseMessage} DispatchMessage
|
20 |
+
* Any message to the dispatch system.
|
21 |
+
*/
|
22 |
+
|
23 |
+
/**
|
24 |
+
* The SharedDispatch class is responsible for dispatch features shared by
|
25 |
+
* {@link CentralDispatch} and {@link WorkerDispatch}.
|
26 |
+
*/
|
27 |
+
class SharedDispatch {
|
28 |
+
constructor () {
|
29 |
+
/**
|
30 |
+
* List of callback registrations for promises waiting for a response from a call to a service on another
|
31 |
+
* worker. A callback registration is an array of [resolve,reject] Promise functions.
|
32 |
+
* Calls to local services don't enter this list.
|
33 |
+
* @type {Array.<Function[]>}
|
34 |
+
*/
|
35 |
+
this.callbacks = [];
|
36 |
+
|
37 |
+
/**
|
38 |
+
* The next response ID to be used.
|
39 |
+
* @type {int}
|
40 |
+
*/
|
41 |
+
this.nextResponseId = 0;
|
42 |
+
}
|
43 |
+
|
44 |
+
/**
|
45 |
+
* Call a particular method on a particular service, regardless of whether that service is provided locally or on
|
46 |
+
* a worker. If the service is provided by a worker, the `args` will be copied using the Structured Clone
|
47 |
+
* algorithm, except for any items which are also in the `transfer` list. Ownership of those items will be
|
48 |
+
* transferred to the worker, and they should not be used after this call.
|
49 |
+
* @example
|
50 |
+
* dispatcher.call('vm', 'setData', 'cat', 42);
|
51 |
+
* // this finds the worker for the 'vm' service, then on that worker calls:
|
52 |
+
* vm.setData('cat', 42);
|
53 |
+
* @param {string} service - the name of the service.
|
54 |
+
* @param {string} method - the name of the method.
|
55 |
+
* @param {*} [args] - the arguments to be copied to the method, if any.
|
56 |
+
* @returns {Promise} - a promise for the return value of the service method.
|
57 |
+
*/
|
58 |
+
call (service, method, ...args) {
|
59 |
+
return this.transferCall(service, method, null, ...args);
|
60 |
+
}
|
61 |
+
|
62 |
+
/**
|
63 |
+
* Call a particular method on a particular service, regardless of whether that service is provided locally or on
|
64 |
+
* a worker. If the service is provided by a worker, the `args` will be copied using the Structured Clone
|
65 |
+
* algorithm, except for any items which are also in the `transfer` list. Ownership of those items will be
|
66 |
+
* transferred to the worker, and they should not be used after this call.
|
67 |
+
* @example
|
68 |
+
* dispatcher.transferCall('vm', 'setData', [myArrayBuffer], 'cat', myArrayBuffer);
|
69 |
+
* // this finds the worker for the 'vm' service, transfers `myArrayBuffer` to it, then on that worker calls:
|
70 |
+
* vm.setData('cat', myArrayBuffer);
|
71 |
+
* @param {string} service - the name of the service.
|
72 |
+
* @param {string} method - the name of the method.
|
73 |
+
* @param {Array} [transfer] - objects to be transferred instead of copied. Must be present in `args` to be useful.
|
74 |
+
* @param {*} [args] - the arguments to be copied to the method, if any.
|
75 |
+
* @returns {Promise} - a promise for the return value of the service method.
|
76 |
+
*/
|
77 |
+
transferCall (service, method, transfer, ...args) {
|
78 |
+
try {
|
79 |
+
const {provider, isRemote} = this._getServiceProvider(service);
|
80 |
+
if (provider) {
|
81 |
+
if (isRemote) {
|
82 |
+
return this._remoteTransferCall(provider, service, method, transfer, ...args);
|
83 |
+
}
|
84 |
+
|
85 |
+
const result = provider[method].apply(provider, args);
|
86 |
+
return Promise.resolve(result);
|
87 |
+
}
|
88 |
+
return Promise.reject(new Error(`Service not found: ${service}`));
|
89 |
+
} catch (e) {
|
90 |
+
return Promise.reject(e);
|
91 |
+
}
|
92 |
+
}
|
93 |
+
|
94 |
+
/**
|
95 |
+
* Check if a particular service lives on another worker.
|
96 |
+
* @param {string} service - the service to check.
|
97 |
+
* @returns {boolean} - true if the service is remote (calls must cross a Worker boundary), false otherwise.
|
98 |
+
* @private
|
99 |
+
*/
|
100 |
+
_isRemoteService (service) {
|
101 |
+
return this._getServiceProvider(service).isRemote;
|
102 |
+
}
|
103 |
+
|
104 |
+
/**
|
105 |
+
* Like {@link call}, but force the call to be posted through a particular communication channel.
|
106 |
+
* @param {object} provider - send the call through this object's `postMessage` function.
|
107 |
+
* @param {string} service - the name of the service.
|
108 |
+
* @param {string} method - the name of the method.
|
109 |
+
* @param {*} [args] - the arguments to be copied to the method, if any.
|
110 |
+
* @returns {Promise} - a promise for the return value of the service method.
|
111 |
+
*/
|
112 |
+
_remoteCall (provider, service, method, ...args) {
|
113 |
+
return this._remoteTransferCall(provider, service, method, null, ...args);
|
114 |
+
}
|
115 |
+
|
116 |
+
/**
|
117 |
+
* Like {@link transferCall}, but force the call to be posted through a particular communication channel.
|
118 |
+
* @param {object} provider - send the call through this object's `postMessage` function.
|
119 |
+
* @param {string} service - the name of the service.
|
120 |
+
* @param {string} method - the name of the method.
|
121 |
+
* @param {Array} [transfer] - objects to be transferred instead of copied. Must be present in `args` to be useful.
|
122 |
+
* @param {*} [args] - the arguments to be copied to the method, if any.
|
123 |
+
* @returns {Promise} - a promise for the return value of the service method.
|
124 |
+
*/
|
125 |
+
_remoteTransferCall (provider, service, method, transfer, ...args) {
|
126 |
+
return new Promise((resolve, reject) => {
|
127 |
+
const responseId = this._storeCallbacks(resolve, reject);
|
128 |
+
|
129 |
+
/** @TODO: remove this hack! this is just here so we don't try to send `util` to a worker */
|
130 |
+
// tw: upstream's logic is broken
|
131 |
+
// Args is actually a 3 length list of [args, util, real block info]
|
132 |
+
// We only want to send args. The others will throw errors when they try to be cloned
|
133 |
+
if ((args.length > 0) && (typeof args[args.length - 1].func === 'function')) {
|
134 |
+
args.pop();
|
135 |
+
args.pop();
|
136 |
+
}
|
137 |
+
|
138 |
+
if (transfer) {
|
139 |
+
provider.postMessage({service, method, responseId, args}, transfer);
|
140 |
+
} else {
|
141 |
+
provider.postMessage({service, method, responseId, args});
|
142 |
+
}
|
143 |
+
});
|
144 |
+
}
|
145 |
+
|
146 |
+
/**
|
147 |
+
* Store callback functions pending a response message.
|
148 |
+
* @param {Function} resolve - function to call if the service method returns.
|
149 |
+
* @param {Function} reject - function to call if the service method throws.
|
150 |
+
* @returns {*} - a unique response ID for this set of callbacks. See {@link _deliverResponse}.
|
151 |
+
* @protected
|
152 |
+
*/
|
153 |
+
_storeCallbacks (resolve, reject) {
|
154 |
+
const responseId = this.nextResponseId++;
|
155 |
+
this.callbacks[responseId] = [resolve, reject];
|
156 |
+
return responseId;
|
157 |
+
}
|
158 |
+
|
159 |
+
/**
|
160 |
+
* Deliver call response from a worker. This should only be called as the result of a message from a worker.
|
161 |
+
* @param {int} responseId - the response ID of the callback set to call.
|
162 |
+
* @param {DispatchResponseMessage} message - the message containing the response value(s).
|
163 |
+
* @protected
|
164 |
+
*/
|
165 |
+
_deliverResponse (responseId, message) {
|
166 |
+
try {
|
167 |
+
const [resolve, reject] = this.callbacks[responseId];
|
168 |
+
delete this.callbacks[responseId];
|
169 |
+
if (message.error) {
|
170 |
+
reject(message.error);
|
171 |
+
} else {
|
172 |
+
resolve(message.result);
|
173 |
+
}
|
174 |
+
} catch (e) {
|
175 |
+
log.error(`Dispatch callback failed: ${e}`);
|
176 |
+
}
|
177 |
+
}
|
178 |
+
|
179 |
+
/**
|
180 |
+
* Handle a message event received from a connected worker.
|
181 |
+
* @param {Worker} worker - the worker which sent the message, or the global object if running in a worker.
|
182 |
+
* @param {MessageEvent} event - the message event to be handled.
|
183 |
+
* @protected
|
184 |
+
*/
|
185 |
+
_onMessage (worker, event) {
|
186 |
+
/** @type {DispatchMessage} */
|
187 |
+
const message = event.data;
|
188 |
+
message.args = message.args || [];
|
189 |
+
let promise;
|
190 |
+
if (message.service) {
|
191 |
+
if (message.service === 'dispatch') {
|
192 |
+
promise = this._onDispatchMessage(worker, message);
|
193 |
+
} else {
|
194 |
+
promise = this.call(message.service, message.method, ...message.args);
|
195 |
+
}
|
196 |
+
} else if (typeof message.responseId === 'undefined') {
|
197 |
+
log.error(`Dispatch caught malformed message from a worker: ${JSON.stringify(event)}`);
|
198 |
+
} else {
|
199 |
+
this._deliverResponse(message.responseId, message);
|
200 |
+
}
|
201 |
+
if (promise) {
|
202 |
+
if (typeof message.responseId === 'undefined') {
|
203 |
+
log.error(`Dispatch message missing required response ID: ${JSON.stringify(event)}`);
|
204 |
+
} else {
|
205 |
+
promise.then(
|
206 |
+
result => worker.postMessage({responseId: message.responseId, result}),
|
207 |
+
error => worker.postMessage({responseId: message.responseId, error: `${error}`})
|
208 |
+
);
|
209 |
+
}
|
210 |
+
}
|
211 |
+
}
|
212 |
+
|
213 |
+
/**
|
214 |
+
* Fetch the service provider object for a particular service name.
|
215 |
+
* @abstract
|
216 |
+
* @param {string} service - the name of the service to look up
|
217 |
+
* @returns {{provider:(object|Worker), isRemote:boolean}} - the means to contact the service, if found
|
218 |
+
* @protected
|
219 |
+
*/
|
220 |
+
_getServiceProvider (service) {
|
221 |
+
throw new Error(`Could not get provider for ${service}: _getServiceProvider not implemented`);
|
222 |
+
}
|
223 |
+
|
224 |
+
/**
|
225 |
+
* Handle a call message sent to the dispatch service itself
|
226 |
+
* @abstract
|
227 |
+
* @param {Worker} worker - the worker which sent the message.
|
228 |
+
* @param {DispatchCallMessage} message - the message to be handled.
|
229 |
+
* @returns {Promise|undefined} - a promise for the results of this operation, if appropriate
|
230 |
+
* @private
|
231 |
+
*/
|
232 |
+
_onDispatchMessage (worker, message) {
|
233 |
+
throw new Error(`Unimplemented dispatch message handler cannot handle ${message.method} method`);
|
234 |
+
}
|
235 |
+
}
|
236 |
+
|
237 |
+
module.exports = SharedDispatch;
|
src/dispatch/worker-dispatch.js
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const SharedDispatch = require('./shared-dispatch');
|
2 |
+
|
3 |
+
const log = require('../util/log');
|
4 |
+
const {centralDispatchService} = require('../extension-support/tw-extension-worker-context');
|
5 |
+
|
6 |
+
/**
|
7 |
+
* This class provides a Worker with the means to participate in the message dispatch system managed by CentralDispatch.
|
8 |
+
* From any context in the messaging system, the dispatcher's "call" method can call any method on any "service"
|
9 |
+
* provided in any participating context. The dispatch system will forward function arguments and return values across
|
10 |
+
* worker boundaries as needed.
|
11 |
+
* @see {CentralDispatch}
|
12 |
+
*/
|
13 |
+
class WorkerDispatch extends SharedDispatch {
|
14 |
+
constructor () {
|
15 |
+
super();
|
16 |
+
|
17 |
+
/**
|
18 |
+
* This promise will be resolved when we have successfully connected to central dispatch.
|
19 |
+
* @type {Promise}
|
20 |
+
* @see {waitForConnection}
|
21 |
+
* @private
|
22 |
+
*/
|
23 |
+
this._connectionPromise = new Promise(resolve => {
|
24 |
+
this._onConnect = resolve;
|
25 |
+
});
|
26 |
+
|
27 |
+
/**
|
28 |
+
* Map of service name to local service provider.
|
29 |
+
* If a service is not listed here, it is assumed to be provided by another context (another Worker or the main
|
30 |
+
* thread).
|
31 |
+
* @see {setService}
|
32 |
+
* @type {object}
|
33 |
+
*/
|
34 |
+
this.services = {};
|
35 |
+
|
36 |
+
this._onMessage = this._onMessage.bind(this, centralDispatchService);
|
37 |
+
if (typeof self !== 'undefined') {
|
38 |
+
self.onmessage = this._onMessage;
|
39 |
+
}
|
40 |
+
}
|
41 |
+
|
42 |
+
/**
|
43 |
+
* @returns {Promise} a promise which will resolve upon connection to central dispatch. If you need to make a call
|
44 |
+
* immediately on "startup" you can attach a 'then' to this promise.
|
45 |
+
* @example
|
46 |
+
* dispatch.waitForConnection.then(() => {
|
47 |
+
* dispatch.call('myService', 'hello');
|
48 |
+
* })
|
49 |
+
*/
|
50 |
+
get waitForConnection () {
|
51 |
+
return this._connectionPromise;
|
52 |
+
}
|
53 |
+
|
54 |
+
/**
|
55 |
+
* Set a local object as the global provider of the specified service.
|
56 |
+
* WARNING: Any method on the provider can be called from any worker within the dispatch system.
|
57 |
+
* @param {string} service - a globally unique string identifying this service. Examples: 'vm', 'gui', 'extension9'.
|
58 |
+
* @param {object} provider - a local object which provides this service.
|
59 |
+
* @returns {Promise} - a promise which will resolve once the service is registered.
|
60 |
+
*/
|
61 |
+
setService (service, provider) {
|
62 |
+
if (this.services.hasOwnProperty(service)) {
|
63 |
+
log.warn(`Worker dispatch replacing existing service provider for ${service}`);
|
64 |
+
}
|
65 |
+
this.services[service] = provider;
|
66 |
+
return this.waitForConnection.then(() => (
|
67 |
+
this._remoteCall(centralDispatchService, 'dispatch', 'setService', service)
|
68 |
+
));
|
69 |
+
}
|
70 |
+
|
71 |
+
/**
|
72 |
+
* Fetch the service provider object for a particular service name.
|
73 |
+
* @override
|
74 |
+
* @param {string} service - the name of the service to look up
|
75 |
+
* @returns {{provider:(object|Worker), isRemote:boolean}} - the means to contact the service, if found
|
76 |
+
* @protected
|
77 |
+
*/
|
78 |
+
_getServiceProvider (service) {
|
79 |
+
// if we don't have a local service by this name, contact central dispatch by calling `postMessage` on self
|
80 |
+
const provider = this.services[service];
|
81 |
+
return {
|
82 |
+
provider: provider || centralDispatchService,
|
83 |
+
isRemote: !provider
|
84 |
+
};
|
85 |
+
}
|
86 |
+
|
87 |
+
/**
|
88 |
+
* Handle a call message sent to the dispatch service itself
|
89 |
+
* @override
|
90 |
+
* @param {Worker} worker - the worker which sent the message.
|
91 |
+
* @param {DispatchCallMessage} message - the message to be handled.
|
92 |
+
* @returns {Promise|undefined} - a promise for the results of this operation, if appropriate
|
93 |
+
* @protected
|
94 |
+
*/
|
95 |
+
_onDispatchMessage (worker, message) {
|
96 |
+
let promise;
|
97 |
+
switch (message.method) {
|
98 |
+
case 'handshake':
|
99 |
+
promise = this._onConnect();
|
100 |
+
break;
|
101 |
+
case 'terminate':
|
102 |
+
// Don't close until next tick, after sending confirmation back
|
103 |
+
setTimeout(() => self.close(), 0);
|
104 |
+
promise = Promise.resolve();
|
105 |
+
break;
|
106 |
+
default:
|
107 |
+
log.error(`Worker dispatch received message for unknown method: ${message.method}`);
|
108 |
+
}
|
109 |
+
return promise;
|
110 |
+
}
|
111 |
+
}
|
112 |
+
|
113 |
+
module.exports = new WorkerDispatch();
|
src/engine/adapter.js
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
const mutationAdapter = require('./mutation-adapter');
|
2 |
+
const uid = require('../util/uid');
|
3 |
+
|
4 |
+
/**
|
5 |
+
* Convert and an individual block DOM to the representation tree.
|
6 |
+
* Based on Blockly's `domToBlockHeadless_`.
|
7 |
+
* @param {Element} blockDOM DOM tree for an individual block.
|
8 |
+
* @param {object} blocks Collection of blocks to add to.
|
9 |
+
* @param {boolean} isTopBlock Whether blocks at this level are "top blocks."
|
10 |
+
* @param {?string} parent Parent block ID.
|
11 |
+
* @return {undefined}
|
12 |
+
*/
|
13 |
+
const domToBlock = function (blockDOM, blocks, isTopBlock, parent) {
|
14 |
+
if (!blockDOM.attributes.id) {
|
15 |
+
blockDOM.attributes.id = {};
|
16 |
+
blockDOM.attributes.id.value = uid();
|
17 |
+
}
|
18 |
+
|
19 |
+
// make sure errors arnt thrown when there is no postion
|
20 |
+
blockDOM.attributes.x ??= {};
|
21 |
+
blockDOM.attributes.y ??= {};
|
22 |
+
|
23 |
+
// Block skeleton.
|
24 |
+
const block = {
|
25 |
+
id: blockDOM.attributes.id.value, // Block ID
|
26 |
+
opcode: blockDOM.attributes.type.value, // For execution, "event_whengreenflag".
|
27 |
+
inputs: {}, // Inputs to this block and the blocks they point to.
|
28 |
+
fields: {}, // Fields on this block and their values.
|
29 |
+
next: null, // Next block in the stack, if one exists.
|
30 |
+
topLevel: isTopBlock, // If this block starts a stack.
|
31 |
+
parent: parent, // Parent block ID, if available.
|
32 |
+
shadow: blockDOM.tagName === 'shadow', // If this represents a shadow/slot.
|
33 |
+
x: blockDOM.attributes.x.value, // X position of script, if top-level.
|
34 |
+
y: blockDOM.attributes.y.value // Y position of script, if top-level.
|
35 |
+
};
|
36 |
+
|
37 |
+
// Add the block to the representation tree.
|
38 |
+
blocks[block.id] = block;
|
39 |
+
|
40 |
+
// Process XML children and find enclosed blocks, fields, etc.
|
41 |
+
for (let i = 0; i < blockDOM.children.length; i++) {
|
42 |
+
const xmlChild = blockDOM.children[i];
|
43 |
+
// Enclosed blocks and shadows
|
44 |
+
let childBlockNode = null;
|
45 |
+
let childShadowNode = null;
|
46 |
+
for (let j = 0; j < xmlChild.children.length; j++) {
|
47 |
+
const grandChildNode = xmlChild.children[j];
|
48 |
+
if (!grandChildNode.tagName) {
|
49 |
+
// Non-XML tag node.
|
50 |
+
continue;
|
51 |
+
}
|
52 |
+
const grandChildNodeName = grandChildNode.tagName;
|
53 |
+
if (grandChildNodeName === 'block') {
|
54 |
+
childBlockNode = grandChildNode;
|
55 |
+
} else if (grandChildNodeName === 'shadow') {
|
56 |
+
childShadowNode = grandChildNode;
|
57 |
+
}
|
58 |
+
}
|
59 |
+
|
60 |
+
// Use shadow block only if there's no real block node.
|
61 |
+
if (!childBlockNode && childShadowNode) {
|
62 |
+
childBlockNode = childShadowNode;
|
63 |
+
}
|
64 |
+
|
65 |
+
// Not all Blockly-type blocks are handled here,
|
66 |
+
// as we won't be using all of them for Scratch.
|
67 |
+
switch (xmlChild.tagName) {
|
68 |
+
case 'field':
|
69 |
+
{
|
70 |
+
// Add the field to this block.
|
71 |
+
const fieldName = xmlChild.attributes.name.value;
|
72 |
+
// make sure the id exists and is valid nomatter what
|
73 |
+
xmlChild.attributes.id ??= { value: uid() };
|
74 |
+
// Add id in case it is a variable field
|
75 |
+
const fieldId = xmlChild.attributes.id.value;
|
76 |
+
let fieldData = '';
|
77 |
+
if (xmlChild.innerHTML) {
|
78 |
+
fieldData = xmlChild.textContent;
|
79 |
+
} else {
|
80 |
+
// If the child of the field with a data property
|
81 |
+
// doesn't exist, set the data to an empty string.
|
82 |
+
fieldData = '';
|
83 |
+
}
|
84 |
+
block.fields[fieldName] = {
|
85 |
+
name: fieldName,
|
86 |
+
id: fieldId,
|
87 |
+
value: fieldData
|
88 |
+
};
|
89 |
+
xmlChild.attributes.variabletype ??= {};
|
90 |
+
const fieldVarType = xmlChild.attributes.variabletype.value;
|
91 |
+
if (typeof fieldVarType === 'string') {
|
92 |
+
block.fields[fieldName].variableType = fieldVarType;
|
93 |
+
}
|
94 |
+
break;
|
95 |
+
}
|
96 |
+
case 'comment':
|
97 |
+
{
|
98 |
+
block.comment = xmlChild.attributes.id.value;
|
99 |
+
break;
|
100 |
+
}
|
101 |
+
case 'value':
|
102 |
+
case 'statement':
|
103 |
+
{
|
104 |
+
// Recursively generate block structure for input block.
|
105 |
+
domToBlock(childBlockNode, blocks, false, block.id);
|
106 |
+
if (childShadowNode && childBlockNode !== childShadowNode) {
|
107 |
+
// Also generate the shadow block.
|
108 |
+
domToBlock(childShadowNode, blocks, false, block.id);
|
109 |
+
}
|
110 |
+
// Link this block's input to the child block.
|
111 |
+
const inputName = xmlChild.attributes.name.value;
|
112 |
+
block.inputs[inputName] = {
|
113 |
+
name: inputName,
|
114 |
+
block: childBlockNode.attributes.id.value,
|
115 |
+
shadow: childShadowNode ? childShadowNode.attributes.id.value : null
|
116 |
+
};
|
117 |
+
break;
|
118 |
+
}
|
119 |
+
case 'next':
|
120 |
+
{
|
121 |
+
if (!childBlockNode || !childBlockNode.attributes) {
|
122 |
+
// Invalid child block.
|
123 |
+
continue;
|
124 |
+
}
|
125 |
+
// Recursively generate block structure for next block.
|
126 |
+
domToBlock(childBlockNode, blocks, false, block.id);
|
127 |
+
// Link next block to this block.
|
128 |
+
block.next = childBlockNode.attributes.id.value;
|
129 |
+
break;
|
130 |
+
}
|
131 |
+
case 'mutation':
|
132 |
+
{
|
133 |
+
block.mutation = mutationAdapter(xmlChild);
|
134 |
+
break;
|
135 |
+
}
|
136 |
+
}
|
137 |
+
}
|
138 |
+
};
|
139 |
+
|
140 |
+
/**
|
141 |
+
* Convert outer blocks DOM from a Blockly CREATE event
|
142 |
+
* to a usable form for the Scratch runtime.
|
143 |
+
* This structure is based on Blockly xml.js:`domToWorkspace` and `domToBlock`.
|
144 |
+
* @param {Element} blocksDOM DOM tree for this event.
|
145 |
+
* @return {Array.<object>} Usable list of blocks from this CREATE event.
|
146 |
+
*/
|
147 |
+
const domToBlocks = function (blocksDOM) {
|
148 |
+
// At this level, there could be multiple blocks adjacent in the DOM tree.
|
149 |
+
const blocks = {};
|
150 |
+
for (let i = 0; i < blocksDOM.length; i++) {
|
151 |
+
const block = blocksDOM[i];
|
152 |
+
|
153 |
+
if (!block.tagName || !block.attributes) {
|
154 |
+
continue;
|
155 |
+
}
|
156 |
+
const tagName = block.tagName;
|
157 |
+
if (tagName === 'block' || tagName === 'shadow') {
|
158 |
+
domToBlock(block, blocks, true, null);
|
159 |
+
}
|
160 |
+
}
|
161 |
+
// Flatten blocks object into a list.
|
162 |
+
const blocksList = [];
|
163 |
+
for (const b in blocks) {
|
164 |
+
if (!blocks.hasOwnProperty(b)) continue;
|
165 |
+
blocksList.push(blocks[b]);
|
166 |
+
}
|
167 |
+
return blocksList;
|
168 |
+
};
|
169 |
+
|
170 |
+
/**
|
171 |
+
* Adapter between block creation events and block representation which can be
|
172 |
+
* used by the Scratch runtime.
|
173 |
+
* @param {object} e `Blockly.events.create` or `Blockly.events.endDrag`
|
174 |
+
* @return {Array.<object>} List of blocks from this CREATE event.
|
175 |
+
*/
|
176 |
+
const adapter = function (e) {
|
177 |
+
// Validate input
|
178 |
+
if (typeof e !== 'object') return;
|
179 |
+
if (typeof e.xml !== 'object') return;
|
180 |
+
const parser = new DOMParser();
|
181 |
+
const doc = parser.parseFromString(e.xml.outerHTML, "application/xml");
|
182 |
+
return domToBlocks(doc.childNodes);
|
183 |
+
};
|
184 |
+
|
185 |
+
module.exports = adapter;
|
src/engine/block-utility.js
ADDED
@@ -0,0 +1,261 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
4 |
+
/**
|
5 |
+
* @fileoverview
|
6 |
+
* Interface provided to block primitive functions for interacting with the
|
7 |
+
* runtime, thread, target, and convenient methods.
|
8 |
+
*/
|
9 |
+
|
10 |
+
class BlockUtility {
|
11 |
+
constructor (sequencer = null, thread = null) {
|
12 |
+
/**
|
13 |
+
* A sequencer block primitives use to branch or start procedures with
|
14 |
+
* @type {?Sequencer}
|
15 |
+
*/
|
16 |
+
this.sequencer = sequencer;
|
17 |
+
|
18 |
+
/**
|
19 |
+
* The block primitives thread with the block's target, stackFrame and
|
20 |
+
* modifiable status.
|
21 |
+
* @type {?Thread}
|
22 |
+
*/
|
23 |
+
this.thread = thread;
|
24 |
+
|
25 |
+
this._nowObj = {
|
26 |
+
now: () => this.sequencer.runtime.currentMSecs
|
27 |
+
};
|
28 |
+
}
|
29 |
+
|
30 |
+
/**
|
31 |
+
* The target the primitive is working on.
|
32 |
+
* @type {Target}
|
33 |
+
*/
|
34 |
+
get target () {
|
35 |
+
return this.thread.target;
|
36 |
+
}
|
37 |
+
|
38 |
+
/**
|
39 |
+
* The runtime the block primitive is running in.
|
40 |
+
* @type {Runtime}
|
41 |
+
*/
|
42 |
+
get runtime () {
|
43 |
+
return this.sequencer.runtime;
|
44 |
+
}
|
45 |
+
|
46 |
+
/**
|
47 |
+
* Use the runtime's currentMSecs value as a timestamp value for now
|
48 |
+
* This is useful in some cases where we need compatibility with Scratch 2
|
49 |
+
* @type {function}
|
50 |
+
*/
|
51 |
+
get nowObj () {
|
52 |
+
if (this.runtime) {
|
53 |
+
return this._nowObj;
|
54 |
+
}
|
55 |
+
return null;
|
56 |
+
}
|
57 |
+
|
58 |
+
/**
|
59 |
+
* The stack frame used by loop and other blocks to track internal state.
|
60 |
+
* @type {object}
|
61 |
+
*/
|
62 |
+
get stackFrame () {
|
63 |
+
const frame = this.thread.peekStackFrame();
|
64 |
+
if (frame.executionContext === null) {
|
65 |
+
frame.executionContext = {};
|
66 |
+
}
|
67 |
+
return frame.executionContext;
|
68 |
+
}
|
69 |
+
|
70 |
+
/**
|
71 |
+
* Check the stack timer and return a boolean based on whether it has finished or not.
|
72 |
+
* @return {boolean} - true if the stack timer has finished.
|
73 |
+
*/
|
74 |
+
stackTimerFinished () {
|
75 |
+
const timeElapsed = this.stackFrame.timer.timeElapsed();
|
76 |
+
if (timeElapsed < this.stackFrame.duration) {
|
77 |
+
return false;
|
78 |
+
}
|
79 |
+
return true;
|
80 |
+
}
|
81 |
+
|
82 |
+
/**
|
83 |
+
* Check if the stack timer needs initialization.
|
84 |
+
* @return {boolean} - true if the stack timer needs to be initialized.
|
85 |
+
*/
|
86 |
+
stackTimerNeedsInit () {
|
87 |
+
return !this.stackFrame.timer;
|
88 |
+
}
|
89 |
+
|
90 |
+
/**
|
91 |
+
* Create and start a stack timer
|
92 |
+
* @param {number} duration - a duration in milliseconds to set the timer for.
|
93 |
+
*/
|
94 |
+
startStackTimer (duration) {
|
95 |
+
if (this.nowObj) {
|
96 |
+
this.stackFrame.timer = new Timer(this.nowObj);
|
97 |
+
} else {
|
98 |
+
this.stackFrame.timer = new Timer();
|
99 |
+
}
|
100 |
+
this.stackFrame.timer.start();
|
101 |
+
this.stackFrame.duration = duration;
|
102 |
+
}
|
103 |
+
|
104 |
+
/**
|
105 |
+
* Set the thread to yield.
|
106 |
+
*/
|
107 |
+
yield () {
|
108 |
+
this.thread.status = Thread.STATUS_YIELD;
|
109 |
+
}
|
110 |
+
|
111 |
+
/**
|
112 |
+
* pm: Set the thread to the running state.
|
113 |
+
*/
|
114 |
+
defaultStatus () {
|
115 |
+
this.thread.status = Thread.STATUS_RUNNING;
|
116 |
+
}
|
117 |
+
|
118 |
+
/**
|
119 |
+
* Set the thread to yield until the next tick of the runtime.
|
120 |
+
*/
|
121 |
+
yieldTick () {
|
122 |
+
this.thread.status = Thread.STATUS_YIELD_TICK;
|
123 |
+
}
|
124 |
+
|
125 |
+
/**
|
126 |
+
* Start a branch in the current block.
|
127 |
+
* @param {number} branchNum Which branch to step to (i.e., 1, 2).
|
128 |
+
* @param {boolean} isLoop Whether this block is a loop.
|
129 |
+
*/
|
130 |
+
startBranch (branchNum, isLoop) {
|
131 |
+
this.sequencer.stepToBranch(this.thread, branchNum, isLoop);
|
132 |
+
}
|
133 |
+
|
134 |
+
/**
|
135 |
+
* Get the branch for a particular C-shaped block, and it's target.
|
136 |
+
* @param {string} id ID for block to get the branch for.
|
137 |
+
* @param {string} branchId Which branch to select (e.g. for if-else).
|
138 |
+
* @return {string} ID of block in the branch.
|
139 |
+
*/
|
140 |
+
getBranchAndTarget (id, branchId) {
|
141 |
+
const result = this.thread.blockContainer.getBranch(id, branchId);
|
142 |
+
if (result) {
|
143 |
+
return [result, this.thread.target];
|
144 |
+
}
|
145 |
+
return this.sequencer.runtime.getBranchAndTarget(id, branchId);
|
146 |
+
}
|
147 |
+
|
148 |
+
/**
|
149 |
+
* Stop all threads.
|
150 |
+
*/
|
151 |
+
stopAll () {
|
152 |
+
this.sequencer.runtime.stopAll();
|
153 |
+
}
|
154 |
+
|
155 |
+
/**
|
156 |
+
* Stop threads other on this target other than the thread holding the
|
157 |
+
* executed block.
|
158 |
+
*/
|
159 |
+
stopOtherTargetThreads () {
|
160 |
+
this.sequencer.runtime.stopForTarget(this.thread.target, this.thread);
|
161 |
+
}
|
162 |
+
|
163 |
+
/**
|
164 |
+
* Stop this thread.
|
165 |
+
*/
|
166 |
+
stopThisScript () {
|
167 |
+
this.thread.stopThisScript();
|
168 |
+
}
|
169 |
+
|
170 |
+
/**
|
171 |
+
* Start a specified procedure on this thread.
|
172 |
+
* @param {string} procedureCode Procedure code for procedure to start.
|
173 |
+
*/
|
174 |
+
startProcedure (procedureCode) {
|
175 |
+
this.sequencer.stepToProcedure(this.thread, procedureCode);
|
176 |
+
}
|
177 |
+
|
178 |
+
/**
|
179 |
+
* Get names and ids of parameters for the given procedure.
|
180 |
+
* @param {string} procedureCode Procedure code for procedure to query.
|
181 |
+
* @return {Array.<string>} List of param names for a procedure.
|
182 |
+
*/
|
183 |
+
getProcedureParamNamesAndIds (procedureCode) {
|
184 |
+
return this.thread.target.blocks.getProcedureParamNamesAndIds(procedureCode);
|
185 |
+
}
|
186 |
+
|
187 |
+
/**
|
188 |
+
* Get names, ids, and defaults of parameters for the given procedure.
|
189 |
+
* @param {string} procedureCode Procedure code for procedure to query.
|
190 |
+
* @return {Array.<string>} List of param names for a procedure.
|
191 |
+
*/
|
192 |
+
getProcedureParamNamesIdsAndDefaults (procedureCode) {
|
193 |
+
return this.thread.target.blocks.getProcedureParamNamesIdsAndDefaults(procedureCode);
|
194 |
+
}
|
195 |
+
|
196 |
+
/**
|
197 |
+
* Initialize procedure parameters in the thread before pushing parameters.
|
198 |
+
*/
|
199 |
+
initParams () {
|
200 |
+
this.thread.initParams();
|
201 |
+
}
|
202 |
+
|
203 |
+
/**
|
204 |
+
* Store a procedure parameter value by its name.
|
205 |
+
* @param {string} paramName The procedure's parameter name.
|
206 |
+
* @param {*} paramValue The procedure's parameter value.
|
207 |
+
*/
|
208 |
+
pushParam (paramName, paramValue) {
|
209 |
+
this.thread.pushParam(paramName, paramValue);
|
210 |
+
}
|
211 |
+
|
212 |
+
/**
|
213 |
+
* Retrieve the stored parameter value for a given parameter name.
|
214 |
+
* @param {string} paramName The procedure's parameter name.
|
215 |
+
* @return {*} The parameter's current stored value.
|
216 |
+
*/
|
217 |
+
getParam (paramName) {
|
218 |
+
return this.thread.getParam(paramName);
|
219 |
+
}
|
220 |
+
|
221 |
+
/**
|
222 |
+
* Start all relevant hats.
|
223 |
+
* @param {!string} requestedHat Opcode of hats to start.
|
224 |
+
* @param {object=} optMatchFields Optionally, fields to match on the hat.
|
225 |
+
* @param {Target=} optTarget Optionally, a target to restrict to.
|
226 |
+
* @return {Array.<Thread>} List of threads started by this function.
|
227 |
+
*/
|
228 |
+
startHats (requestedHat, optMatchFields, optTarget) {
|
229 |
+
// Store thread and sequencer to ensure we can return to the calling block's context.
|
230 |
+
// startHats may execute further blocks and dirty the BlockUtility's execution context
|
231 |
+
// and confuse the calling block when we return to it.
|
232 |
+
const callerThread = this.thread;
|
233 |
+
const callerSequencer = this.sequencer;
|
234 |
+
const result = this.sequencer.runtime.startHats(requestedHat, optMatchFields, optTarget);
|
235 |
+
|
236 |
+
// Restore thread and sequencer to prior values before we return to the calling block.
|
237 |
+
this.thread = callerThread;
|
238 |
+
this.sequencer = callerSequencer;
|
239 |
+
|
240 |
+
return result;
|
241 |
+
}
|
242 |
+
|
243 |
+
/**
|
244 |
+
* Query a named IO device.
|
245 |
+
* @param {string} device The name of like the device, like keyboard.
|
246 |
+
* @param {string} func The name of the device's function to query.
|
247 |
+
* @param {Array.<*>} args Arguments to pass to the device's function.
|
248 |
+
* @return {*} The expected output for the device's function.
|
249 |
+
*/
|
250 |
+
ioQuery (device, func, args) {
|
251 |
+
// Find the I/O device and execute the query/function call.
|
252 |
+
if (
|
253 |
+
this.sequencer.runtime.ioDevices[device] &&
|
254 |
+
this.sequencer.runtime.ioDevices[device][func]) {
|
255 |
+
const devObject = this.sequencer.runtime.ioDevices[device];
|
256 |
+
return devObject[func].apply(devObject, args);
|
257 |
+
}
|
258 |
+
}
|
259 |
+
}
|
260 |
+
|
261 |
+
module.exports = BlockUtility;
|
src/engine/blocks-execute-cache.js
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
/**
|
2 |
+
* @fileoverview
|
3 |
+
* Access point for private method shared between blocks.js and execute.js for
|
4 |
+
* caching execute information.
|
5 |
+
*/
|
6 |
+
|
7 |
+
/**
|
8 |
+
* A private method shared with execute to build an object containing the block
|
9 |
+
* information execute needs and that is reset when other cached Blocks info is
|
10 |
+
* reset.
|
11 |
+
* @param {Blocks} blocks Blocks containing the expected blockId
|
12 |
+
* @param {string} blockId blockId for the desired execute cache
|
13 |
+
*/
|
14 |
+
exports.getCached = function () {
|
15 |
+
throw new Error('blocks.js has not initialized BlocksExecuteCache');
|
16 |
+
};
|
17 |
+
|
18 |
+
// Call after the default throwing getCached is assigned for Blocks to replace.
|
19 |
+
require('./blocks');
|