Skip to content

Scripting in DES

Use event-driven scripts to add custom material-flow behaviour that can continue from a saved run.

The examples on this page carry an AGPL header because they ship with the open-source core. A script you write yourself is part of your model. If you deliver realvirtual to others under AGPL and a script takes over code from the core or is tightly interwoven with it, the recipients must be able to get it under AGPL as well; see Licence.

A DES script is a WebComponent on a node of the model. It is stored in the GLB next to the node’s other data, so it travels with the model. A script that observes the whole model, like a KPI counter, can sit on an empty node of its own.

  • In the Editor, use Edit Script on the component in the Inspector, or open the Script Editor (component scripts) from the side toolbar and pick the node in its node selector.
  • Scripts in a model only run after Enable scripting (or a link with ?scripts). Until then the editor is read-only and shows that scripting is disabled.
  • The chip in the title bar shows DES-safe when the component sets DesSafe and continuous when it does not; see Code checks.

The Script Editor of the PalletYard example with the ShippingMonitor script: the node path PalletYard/PalletYardRoot/ShippingMonitor, the script selector, the continuous chip and 27 lines of JavaScript that declare state with self.persist, publish two values with self.statValue and subscribe to the sinks Sink_V1 and Sink_V2

The PalletYard demo carries this script as a teaching example: ShippingMonitor counts shipments that come later than twice the target takt and publishes the result as Late shipments. Logic that belongs to one project rather than to the model, such as a panel or a link to an external system, is project code instead; see Scripting for the three places code can live.

In DES, a script does nothing between events. The simulation calls it when something happens that concerns it, the script changes its state and schedules what comes next, and the simulation moves on to the next event.

Event, script handler and effect Four rows. A timer that the script scheduled with self.in, self.at or self.every calls des.on with the hook name; the script changes its persistent state and schedules the next hook. A part offered by the upstream station calls des.canAccept and then des.onAccept; the script schedules a hook for the end of processing and later passes the part on with self.transfer. A blocked output that frees up calls des.onDownstreamReady; the script passes on a waiting part. A part reaching a sink calls the callback registered with self.sink(...).on in setup; the script publishes a value with self.statValue, which can become an experiment KPI. Event at simulated time t Your handler Effect Timer is due self.in / at / every des.on(hook, mu, data) update self.persist state, schedule the next hook Part is offered by the upstream station des.canAccept(mu, port) des.onAccept(mu, port) self.in(time, 'done', mu), later self.transfer(mu, port) Output frees up after it was blocked des.onDownstreamReady (port) pass on a waiting part with self.transfer Part reaches a sink subscribed in setup() self.sink(name).on(cb) self.statValue(...) → Statistics, KPI
Every handler runs at the simulated time of its event; whatever it schedules becomes a new event in the queue.

setup(self) runs once when the script is bound for a run. It returns the handlers; everything else happens in them.

EventHandlerUse it to
A timer scheduled with self.in(delay, hook), self.at(time, hook) or self.every(interval, hook) is duedes.on(hook, mu, data)Run a step after a delay, repeat a cycle, end a processing time
An upstream station offers a partdes.canAccept(mu, port), then des.onAccept(mu, port)Make the node a station of its own: refuse parts while busy, start processing
A blocked output can take a part againdes.onDownstreamReady(port)Pass on a part that was waiting
A part reaches a sinkcallback of self.sink(name).on(cb), registered in setupCount shipments, measure gaps, feed a KPI
Another script sends a messageonMessage(topic, data, fromPath)Coordinate several scripts, for example a cell controller
The simulation is resetonReset()Clean up; pending timers are already cleared

A node becomes a material-flow station as soon as its script declares canAccept, onAccept or onDownstreamReady. Timers appear in the Event Queue as Script.Hook. Frame hooks such as continuous.fixedUpdate only run while the simulation is animated and must not change the model in DES; see Timers.

function setup(self) {
const st = self.persist({ cycles: 0 });
self.every(60, 'cycle'); // every simulated minute
return {
des: { on(hook) {
if (hook !== 'cycle') return;
st.cycles++;
self.statValue('Cycles', st.cycles);
} },
};
}
function setup(self) {
const st = self.persist({ busy: false });
return {
des: {
canAccept() { return !st.busy; },
onAccept(mu) {
st.busy = true;
self.in(self.prop.ProcessTime ?? 30, 'done', mu);
return true;
},
on(hook, mu) {
if (hook !== 'done') return;
const out = self.freeOutputs(mu)[0];
if (out) { self.transfer(mu, out); st.busy = false; }
},
onDownstreamReady(port) {
const mu = self.mus[0];
if (mu) { self.transfer(mu, port); st.busy = false; }
},
},
};
}

ProcessTime is a field on the same WebComponent; every primitive field there appears as self.prop.

The ShippingMonitor shown above subscribes to both shipping sinks in setup and publishes two values. They appear in the Scripts tab of the Statistics window, and + Add KPI in the Experiments window offers them as KPIs.

The Scripts tab of the Statistics window in the PalletYard example after about one simulated hour: the rows Late shipments with the value 3 and Longest shipping gap with 167.4 seconds

Scripts keep working across a restore if every value that changes during the run is stored in one object declared with self.persist.

// SPDX-License-Identifier: AGPL-3.0-only
// Snapshot contract: keep all runtime state in one JSON-only self.persist object.
// No module-scope let/var. The SDK restores the timer and RNG; do not re-arm
// timers in onRestore (that would duplicate the pending tick).
function setup(self) {
const st = self.persist({ counter: 0, history: [], timerId: 0 });
st.timerId = self.every(1, 'beat');
return {
des: { on(hook) {
if (hook !== 'beat') return;
st.counter++;
st.history.push([self.now, Math.round(self.random() * 1000000)]);
if (st.history.length > 4) st.history.shift();
} },
state() { return st; },
};
}

The example counts a simulated-second heartbeat and keeps its last four random draws.

  • Call self.persist once, during setup, and keep the returned object. A restore refills this same object.
  • It holds plain JSON data only: finite numbers, strings, booleans, null, arrays and plain objects. No NaN, Infinity, -0, Map, Set, functions, shared references or circular references.
  • self.prop is read-only configuration. Changes to it are not saved.

Use self.in, self.at and self.every. Pending timers are part of the snapshot and fire at the same times after a restore, so do not start them again after a restore: that would run every tick twice. self.every returns an id; keep it in the persist object if you need to cancel the timer later. setTimeout, setInterval, Date and Math.random do not exist in scripts, and timers that count down in fixedUpdate do not work in event-based DES.

When you save a script, and when DES binds it, the script is checked for state that would be lost. Findings read des-script-undeclared-state: line N: …; use self.persist(...). Without DesSafe they are warnings: the script runs on the DES clock, but a snapshot of the run is refused until its state is declared. When the component sets DesSafe, they are errors and DES does not run the script.

  • changing variables declared outside the handlers (let count = 0, arrays, objects, Map, Set at the top of the script or in setup)
  • classes declared at the top of the script or in setup
  • writing to a variable of an outer function, to a global, or to properties of captured objects
  • handlers created by a function call (on: makeHandler()) instead of written out in setup
  • calling a helper function during setup to build state

Constants, SDK handles such as self.drive(...), self, and scratch variables inside a handler are fine.

// Before: state in a closure variable is lost on restore
let count = 0;
function setup(self) {
return { des: { on() { count++; } } };
}
// After: state in self.persist
function setup(self) {
const st = self.persist({ count: 0 });
return { des: { on() { st.count++; } } };
}

Move every changing value into the persist object, write handlers out in place, and look up SDK handles inside the handler instead of storing them. The older onSnapshot and onRestore hooks still work, but they do not exempt a script from the check.

Use self.random() for seeded random draws. With RNG v2, each script seed is derived from the run’s master seed, its component ID and the purpose script, so the same model and seed reproduce the sequence on each run. In v1 the default script seed comes from its component path, rather than the master seed. Draws during setup, and scripts created after a run starts, use their initial path seed (or an explicit SDK seed) until the next reset or run start.

des.on(hook, mu, data) receives scheduled hooks; the example handles beat. Its state() function returns the persistent object. The SDK also saves its own state-machine state, random position and timer IDs. onSnapshot and onRestore are a synchronous legacy facade; they do not make hidden closure state safe or replace self.persist.

A restore refills the existing persistent object and restores pending timers. Script KPI state-time statistics are not saved. Callbacks registered after setup are not saved; register them during setup.

A model script runs in a sandbox: a QuickJS interpreter compiled to WebAssembly, with no access to the DOM, the network or the wall clock, and with a limit of 5 ms per call. That keeps a model from an unknown source safe and makes every script part of the DES snapshot and seed contract. For short component logic this costs nothing you would notice. For logic that computes a lot per event, such as a dispatcher that searches orders, routes or storage places, the sandbox is the slower path.

The other path is project code: TypeScript modules in the project’s plugins/ folder, bound to a document in project.json and loaded as native code. See Scripting for how it is bound and loaded.

Model script compared with TypeScript project code Left, a model script: JavaScript stored in the GLB on a WebComponent runs in a QuickJS sandbox and reaches the viewer only through the self SDK. It travels with the GLB, takes part in DES snapshots and seeded random streams, and each call is limited to 5 milliseconds. Right, project code: TypeScript in the project's plugins folder is compiled to a JavaScript module and runs natively in the browser with the full viewer API. The compiler checks types in your IDE; in a micro-benchmark a computing handler ran about 100 times faster; the code is unsandboxed and the viewer asks once per project before running it; it is not covered by the snapshot contract automatically. Model script TypeScript project code JS in the GLB WebComponent.Code QuickJS sandbox self SDK only plugins/line.ts compiled to .js native in the browser full viewer API + travels with the GLB + DES snapshots and seeded streams + safe for models from others − interpreted, 5 ms per call − types checked in the editor only + compiler checks types in your IDE + modules, imports, refactoring + native speed, no call limit − not in snapshots automatically − unsandboxed: asked once per project
Both paths can live in one project: model scripts for component behaviour, TypeScript for the heavy logic around it.

See Scripting for the SDK and editor, and Saving and restoring a run for model checks and snapshot limits.