scratch-vm

Scratch VM is a library for representing, running, and maintaining the state of computer programs written using Scratch Blocks.

Build Status Coverage Status Greenkeeper badge

Installation

This requires you to have Git and Node.js installed.

To install as a dependency for your own application:

npm install scratch-vm

To set up a development environment to edit scratch-vm yourself:

git clone https://github.com/LLK/scratch-vm.git
cd scratch-vm
npm install

Development Server

This requires Node.js to be installed.

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.

Running the Development Server

Open a Command Prompt or Terminal in the repository and run:

npm start

Playground

To view the Playground, make sure the dev server's running and go to http://localhost:8073/playground/ - you will be directed to the playground, which demonstrates various tools and internal state.

VM Playground Screenshot

Standalone Build

npm run build
<script src="/path/to/dist/web/scratch-vm.js"></script>
<script>
    var vm = new window.VirtualMachine();
    // do things
</script>

How to include in a Node.js App

For an extended setup example, check out the /src/playground directory, which includes a fully running VM instance.

var VirtualMachine = require('scratch-vm');
var vm = new VirtualMachine();

// Block events
Scratch.workspace.addChangeListener(vm.blockListener);

// Run threads
vm.start();

Abstract Syntax Tree

Overview

The Virtual Machine constructs and maintains the state of an Abstract Syntax Tree (AST) by listening to events emitted by the 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.

Anatomy of a Block

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:

{
  "_blocks": {
    "Q]PK~yJ@BTV8Y~FfISeo": {
      "id": "Q]PK~yJ@BTV8Y~FfISeo",
      "opcode": "event_whenkeypressed",
      "inputs": {
      },
      "fields": {
        "KEY_OPTION": {
          "name": "KEY_OPTION",
          "value": "space"
        }
      },
      "next": null,
      "topLevel": true,
      "parent": null,
      "shadow": false,
      "x": -69.333333333333,
      "y": 174
    }
  },
  "_scripts": [
    "Q]PK~yJ@BTV8Y~FfISeo"
  ]
}

Testing

npm test
npm run coverage

Publishing to GitHub Pages

npm run deploy

This will push the currently built playground to the gh-pages branch of the currently tracked remote. If you would like to change where to push to, add a repo url argument:

npm run deploy -- -r <your repo url>

Donate

We provide Scratch free of charge, and want to keep it that way! Please consider making a donation to support our continued engineering, design, community, and resource development efforts. Donations of any size are appreciated. Thank you!

engine/block-utility.js

Interface provided to block primitive functions for interacting with the runtime, thread, target, and convenient methods.

engine/blocks.js

Store and mutate the VM block representation, and handle updates from Scratch Blocks events.

engine/blocks-execute-cache.js

Access point for private method shared between blocks.js and execute.js for caching execute information.

engine/blocks-runtime-cache.js

The BlocksRuntimeCache caches data about the top block of scripts so that Runtime can iterate a targeted opcode and iterate the returned set faster. Many top blocks need to match fields as well as opcode, since that matching compares strings in uppercase we can go ahead and uppercase the cached value so we don't need to in the future.

engine/comment.js

Object representing a Scratch Comment (block or workspace).

engine/profiler.js

A way to profile Scratch internal performance. Like what blocks run during a step? How much time do they take? How much time is spent inbetween blocks?

Profiler aims for to spend as little time inside its functions while recording. For this it has a simple internal record structure that records a series of values for each START and STOP event in a single array. This lets all the values be pushed in one call for the array. This simplicity allows the contents of the start() and stop() calls to be inlined in areas that are called frequently enough to want even greater performance from Profiler so what is recorded better reflects on the profiled code and not Profiler itself.

engine/target.js

A Target is an abstract "code-running" object for the Scratch VM. Examples include sprites/clones or potentially physical-world devices.

engine/variable.js

Object representing a Scratch variable.

extensions/scratch3_video_sensing/debug.js

debug.js

extensions/scratch3_video_sensing/library.js

library.js

Tony Hwang and John Maloney, January 2011 Michael "Z" Goddard, March 2018

Video motion sensing primitives.

serialization/sb2_specmap.js

The specMap below handles a few pieces of "translation" work between the SB2 JSON format and the data we need to run a project in the Scratch 3.0 VM. Notably:

  • Map 2.0 and 1.4 opcodes (forward:) into 3.0-format (motion_movesteps).
  • Map ordered, unnamed args to unordered, named inputs and fields. Keep this up-to-date as 3.0 blocks are renamed, changed, etc. Originally this was generated largely by a hand-guided scripting process. The relevant data lives here: https://github.com/LLK/scratch-flash/blob/master/src/Specs.as (for the old opcode and argument order). and here: https://github.com/LLK/scratch-blocks/tree/develop/blocks_vertical (for the new opcodes and argument names). and here: https://github.com/LLK/scratch-blocks/blob/develop/tests/ (for the shadow blocks created for each block). I started with the commands array in Specs.as, and discarded irrelevant properties. By hand, I matched the opcode name to the 3.0 opcode. Finally, I filled in the expected arguments as below.

serialization/sb2.js

Partial implementation of an SB2 JSON importer. Parses provided JSON and then generates all needed scratch-vm runtime structures.

serialization/sb3.js

An SB3 serializer and deserializer. Parses provided JSON and then generates all needed scratch-vm runtime structures.

util/cast.js

Utilities for casting and comparing Scratch data-types. Scratch behaves slightly differently from JavaScript in many respects, and these differences should be encapsulated below. For example, in Scratch, add(1, join("hello", world")) -> 1. This is because "hello world" is cast to 0. In JavaScript, 1 + Number("hello" + "world") would give you NaN. Use when coercing a value before computation.

util/timer.js

A utility for accurately measuring time. To use:

var timer = new Timer(); timer.start(); ... pass some time ... var timeDifference = timer.timeElapsed();

Or, you can use the time and relativeTime to do some measurement yourself.

util/uid.js

UID generator, from Blockly.