Entity systems, one system at a time
A hands-on introduction to ecs, the entity system library that ships with this toolchain. You build one night garden full of fireflies, a little at a time. Every lesson ends with code that compiles and shows the console it prints, taken from running that lesson's code with the real ecs. By the last lesson the garden uses every part of ecs.
1. Three words to learn
A game has many things that behave alike: raindrops, coins, falling leaves, sparks. An entity system is a way to write the behavior once and run it on all of them. Three words describe it.
| Word | Meaning | Example |
|---|---|---|
| Entity | One thing in the game. It is a plain table of data, with no code of its own. | a firefly |
| Component | One piece of an entity's data, such as where it is or how fast it moves. An entity has a component when that field is set. | position, velocity |
| System | Code that runs on every entity with the components it needs, once a frame. | "move everything that has a velocity" |
Note
The three words are the name. Together they make an Entity Component System, or ECS, which is where ecs gets its name. This tutorial shortens it to entity system.
A fourth word holds them together: a world is the list of entities and the list of systems that run on them.
Try it
- A coin spins, and a magnet pulls it toward the player. Which components would the coin need, and which systems?
Answer
- A
position, aspinand something that marks it as pulled, such asmagnetic. One system turns everything that has aspin, and another moves everything that ismagnetictoward the player. A raindrop with apositionand nospinis skipped by the first system without a singleif.
2. Why bother?
The usual way to write a firefly is one object with an update that asks every question about it, every frame:
interface Bug {
x: number;
vx: number;
glow: number;
resting: boolean;
lit: boolean;
}
export function updateBug(bug: Bug, dt: number): void {
if (!bug.resting) {
bug.x += bug.vx * dt;
}
if (bug.lit) {
bug.glow -= dt;
if (bug.glow <= 0) {
bug.lit = false;
}
}
}It works for one firefly. Now give the garden moths that fly but never glow, and lanterns that glow but never move. Each kind gets its own update with its own copy of the same branches, or one update grows a branch for every kind. A new behavior, such as fleeing from the cursor, means editing every one of them.
An entity system turns this inside out. The moving code lives in one place and runs on everything that has a velocity. The glowing code lives in another and runs on everything that has a light. A lantern has a light and no velocity, so the moving code never sees it, and nobody had to write if (!lantern).
Try it
- In
updateBug, what does a resting firefly that is not lit cost each frame?
Answer
- Two checks that both say no. With a thousand of them, that is two thousand questions a frame with nothing to do. A system holds only the entities it works on, so a resting firefly that is not lit costs the moving and glowing systems nothing.
3. Your first world
Start with fireflies that drift. Make a file named garden.ts:
import { processingSystem, requireAll, update, world } from "@defold-typescript/types/ecs";
export interface Firefly {
readonly name: string;
readonly position: Vector3;
velocity?: Vector3;
}
export const WIDTH = 960;
export const HEIGHT = 640;
/** Moves each firefly that has a velocity. */
export const drift = processingSystem<Firefly>()(requireAll("velocity"), {
process(e, dt) {
e.position.x += e.velocity.x * dt;
e.position.y += e.velocity.y * dt;
},
});
const flick: Firefly = {
name: "Flick",
position: vmath.vector3(WIDTH / 2, HEIGHT / 2, 0),
velocity: vmath.vector3(20, 10, 0),
};
const dot: Firefly = { name: "Dot", position: vmath.vector3(100, 100, 0) };
const garden = world<Firefly>(drift, flick, dot);
update(garden, 1);
print(flick.position.x, dot.position.x);interface Fireflyis the entity type: every field one firefly can have.nameandpositionare always there.velocityis optional, because a component is present only when its field is set.processingSystembuilds a system that runsprocessonce for each entity it holds, with the frame's time stepdt.requireAll("velocity")is the system's filter: it takes the entities that have avelocity. Insideprocess, TypeScript knowse.velocityis set, so no check is needed.worldmakes a world that holds the system and both fireflies.update(garden, 1)runs one frame that lasts one second. It prints500 100: Flick moved 20 to the right, and Dot, with no velocity, never reachedprocess.
Require garden.ts from any script, and loading it prints:
500 100Note
Why two sets of parentheses? In processingSystem<Firefly>()(filter, { ... }) the first call names the entity type. The second takes the filter and the definition, and TypeScript works out from the filter which components are present. It is a TypeScript limitation, so always write it this way.
Try it
- Change
requireAll("velocity")torequireAll("speed"). What happens? - Give Dot a velocity of
vmath.vector3(0, 5, 0). What does the last line print?
Answer
- It fails to compile:
speedis not a field ofFirefly. A filter can only name components the entity type has. 500 100again. Dot moves up, alongy, and the line printsx.
4. Putting it in a Defold game
So far the garden runs once, at the bottom of its file. In a game it runs every frame, on game objects. Two changes get it there.
Step 1. garden.ts defines the firefly and its systems, and runs nothing:
import { processingSystem, requireAll, update, world } from "@defold-typescript/types/ecs";
import { processingSystem, requireAll } from "@defold-typescript/types/ecs";
export interface Firefly {
readonly name: string;
id: Hash;
readonly position: Vector3;
// ...
/** Moves each firefly that has a velocity. */
export const drift = processingSystem<Firefly>()(requireAll("velocity"), {
process(e, dt) {
e.position.x += e.velocity.x * dt;
e.position.y += e.velocity.y * dt;
},
});
export function drift() {
return processingSystem<Firefly>()(requireAll("velocity"), {
process(e, dt) {
e.position.x += e.velocity.x * dt;
e.position.y += e.velocity.y * dt;
go.set_position(e.position, e.id);
},
});
}
const flick: Firefly = {
name: "Flick",
position: vmath.vector3(WIDTH / 2, HEIGHT / 2, 0),
velocity: vmath.vector3(20, 10, 0),
};
const dot: Firefly = { name: "Dot", position: vmath.vector3(100, 100, 0) };
const garden = world<Firefly>(drift, flick, dot);
update(garden, 1);
print(flick.position.x, dot.position.x); id: Hashis the firefly's game object, andgo.set_positionmoves that object to the firefly's position.driftis a function now. A system belongs to one world at a time, so each world needs its own. Callingdrift()builds a new one.- The lines at the bottom are gone. The script below makes the world.
Step 2. Make the script, fireflies.ts, next to it:
import { defineScript } from "@defold-typescript/types";
import { addEntity, update, type World, world } from "@defold-typescript/types/ecs";
import { drift, type Firefly, HEIGHT, WIDTH } from "./garden";
let born = 0;
function spawn(garden: World<Firefly>): Firefly | undefined {
const position = vmath.vector3(math.random(0, WIDTH), math.random(0, HEIGHT), 0);
const id = factory.create("#factory", position);
if (id === undefined) {
return undefined;
}
born += 1;
return addEntity(garden, {
name: `firefly ${born}`,
id,
position,
velocity: vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0),
});
}
export default defineScript({
init() {
const garden = world<Firefly>(drift());
for (let i = 0; i < 20; i++) {
spawn(garden);
}
return { garden };
},
update(self, dt) {
update(self.garden, dt);
},
});initbuilds a world for this game object and keeps it onself, so a second garden would get a world of its own. See Where script state lives.spawnmakes a game object with the factory and adds a firefly for it withaddEntity, which returns the firefly it was given.updateruns one frame of the world each time Defold runs one frame of the game.
To see it, add a firefly.go game object file with a sprite, and a game object named garden to your main collection. Give garden the script built from fireflies.ts, and a factory component named factory whose prototype is firefly.go. Twenty fireflies appear at random and drift off.
Run it for one frame, and the console reads:
ecs garden frame 0: inspecting [0]
ecs garden frame 0: system 1 adds entity 1, holds 1
ecs garden frame 0: system 1 adds entity 2, holds 2
...
ecs garden frame 0: system 1 adds entity 20, holds 20Your script prints none of this yet. These lines come from inspect, a debug tool lesson 15 adds to the script, and every console in the lessons before it was printed with inspect watching the garden. Each line names a system by its place in the world, so system 1 is drift, and an entity by the order the inspector first saw it, which here is the order the fireflies were born. holds is how many entities the system has now. Your own night differs from the one shown, since Defold seeds its random numbers.
Warning
A new firefly joins at the next update. addEntity and every other change to a world waits for the next update, so no system ever sees its list change halfway through a loop.
Try it
- You put two
gardengame objects in the collection. How many worlds are there, and how manydriftsystems? - Why can't
driftstay aconst, as it was in lesson 3?
Answer
- Two of each.
initruns once per game object, and each run builds a world and callsdrift()once. - The second
initwould add the same system to a second world, and adding a system that already belongs to a world throws.
5. One loop over everyone
A processing system sees one firefly at a time. Some work needs all of them at once: to fly as a swarm, each firefly steers toward the middle of the group, and finding the middle takes every position.
That is a job for a plain system. It has one update per frame, and its entities field lists every entity it holds:
import { processingSystem, requireAll } from "@defold-typescript/types/ecs";
import { processingSystem, requireAll, system } from "@defold-typescript/types/ecs";
// ...
});
}
/** Steers each firefly toward the middle of the swarm. */
export function swarm() {
return system<Firefly>()(requireAll("velocity"), {
update(dt) {
const flock = this.entities;
if (flock === undefined || flock.length === 0) {
return;
}
let x = 0;
let y = 0;
for (const e of flock) {
x += e.position.x;
y += e.position.y;
}
x /= flock.length;
y /= flock.length;
for (const e of flock) {
if (e.velocity !== undefined) {
e.velocity.x += (x - e.position.x) * 0.2 * dt;
e.velocity.y += (y - e.position.y) * 0.2 * dt;
}
}
},
});
} update(dt)runs once a frame, however many fireflies there are.thisinside a callback is the system, andthis.entitiesis the list of entities its filter took.e.velocity !== undefinedis a checkprocessnever needed.this.entitiesis typed by the entity type alone, so a component the filter requires is still optional to TypeScript there.
Add the swarm to the world:
import { defineScript } from "@defold-typescript/types";
import { addEntity, update, type World, world } from "@defold-typescript/types/ecs";
import { drift, type Firefly, HEIGHT, WIDTH } from "./garden";
import { drift, type Firefly, HEIGHT, swarm, WIDTH } from "./garden";
// ...
export default defineScript({
init() {
const garden = world<Firefly>(drift());
const garden = world<Firefly>(drift(), swarm());
for (let i = 0; i < 20; i++) {The world runs its systems in the order it got them: drift first, then swarm. Run it for one frame, and each firefly joins both, in that order:
ecs garden frame 0: inspecting [0, 0]
ecs garden frame 0: system 1 adds entity 1, holds 1
ecs garden frame 0: system 2 adds entity 1, holds 1
...
ecs garden frame 0: system 1 adds entity 20, holds 20
ecs garden frame 0: system 2 adds entity 20, holds 20Try it
- Could
swarmbe a processing system? - What does
swarmdo with a world that holds no fireflies?
Answer
- Not easily.
processsees one firefly, and the middle of the swarm needs all of them before any firefly steers. - Nothing.
this.entitiesis empty, so thereturnat the top skips the rest.
6. Choosing who a system sees
Real fireflies rest on leaves, and some glow while others are dark. Give the firefly two more components:
import { processingSystem, requireAll, system } from "@defold-typescript/types/ecs";
import {
filter,
processingSystem,
rejectAll,
requireAll,
requireAny,
system,
tryFilter,
} from "@defold-typescript/types/ecs";
// ...
readonly position: Vector3;
velocity?: Vector3;
light?: number;
flying?: true;
}
// ...
export const HEIGHT = 640;
/** Moves each firefly that has a velocity. */
/** Moves each flying firefly. */
export function drift() {
return processingSystem<Firefly>()(requireAll("velocity"), {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
process(e, dt) {
// ...
}
/** Steers each firefly toward the middle of the swarm. */
/** Steers each flying firefly toward the middle of the swarm. */
export function swarm() {
return system<Firefly>()(requireAll("velocity"), {
return system<Firefly>()(requireAll("velocity", "flying"), {
update(dt) {lightis how bright a lit firefly glows, from 0 to 1. A dark firefly has none.flying: truemarks a firefly in the air. One on a leaf has noflying. A marker component is typedtrueand taken away withundefined, since a filter treatsfalseas present.driftandswarmnow requireflyingas well, so a resting firefly stays where it is.
requireAll is one of four filters, and each takes the names of components:
| Filter | Takes an entity that |
|---|---|
requireAll(...) | has every one |
requireAny(...) | has at least one |
rejectAll(...) | lacks at least one |
rejectAny(...) | has none |
A filter can take other filters in place of names, as in requireAll("light", rejectAny("flying")). Only the names a top-level requireAll gives are known to be present inside the system.
Two systems use the new filters:
}
},
});
}
/** Writes how many fireflies are awake: lit, or flying. */
export function counter() {
return system<Firefly>()(requireAny("light", "flying"), {
update() {
label.set_text("/hud#awake", `${this.entities?.length ?? 0} awake`);
},
});
}
/** Holds the fireflies you can catch: each one that is dark or not flying. */
export function catchable() {
return system<Firefly>()(rejectAll("light", "flying"), {});
} countertakes a firefly that is lit or flying, and writes how many there are to a label.catchabletakes a firefly that lacks a light or lacksflying: the ones that are easy to catch. It does nothing yet, and lesson 7 gives it work.
A filter can also be a string, a pattern as tiny-ecs writes it: & is and, | is or, ! is not. filter reads a pattern you write in the code, and tryFilter reads one that comes from somewhere else:
return system<Firefly>()(rejectAll("light", "flying"), {});
}
/** Swells each lit firefly that sits still, as much as it glows. */
export function beacons() {
return processingSystem<Firefly>()(filter("light&!flying"), {
process(e) {
if (e.light !== undefined) {
go.set_scale(1 + e.light / 2, e.id);
}
},
});
}
/** Counts the fireflies `pattern` takes, or returns `undefined` for a pattern that does not parse. */
export function watch(pattern: string) {
const parsed = tryFilter(pattern);
if (!parsed.ok) {
print(`garden.watch: ${parsed.error}`);
return undefined;
}
return system<Firefly>()(parsed.filter, {
update() {
label.set_text("/hud#watch", `${pattern}: ${this.entities?.length ?? 0}`);
},
});
} filter("light&!flying")takes a lit firefly on a leaf. A string filter narrows nothing, sobeaconscheckse.lightbefore it reads it.tryFilter(pattern)returns{ ok: true, filter }or{ ok: false, error }.filterwould throw on a pattern that does not parse, and a pattern typed in a settings file can be wrong.
Now the script. Fireflies start lit or dark, flying or resting, and a click asks whether the firefly under the pointer is catchable:
import { defineScript } from "@defold-typescript/types";
import { addEntity, update, type World, world } from "@defold-typescript/types/ecs";
import { drift, type Firefly, HEIGHT, swarm, WIDTH } from "./garden";
import { add, addEntity, update, type World, world } from "@defold-typescript/types/ecs";
import {
beacons,
catchable,
counter,
drift,
type Firefly,
HEIGHT,
swarm,
WIDTH,
watch,
} from "./garden";
const TOUCH = hash("touch");
let born = 0;
// ...
position,
velocity: vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0),
light: math.random() < 0.5 ? 1 : undefined,
flying: math.random() < 0.5 ? true : undefined,
});
// ...
export default defineScript({
init() {
const garden = world<Firefly>(drift(), swarm());
msg.post(".", "acquire_input_focus");
const net = catchable();
const garden = world<Firefly>(
drift(),
swarm(),
beacons(),
counter(),
net,
);
const watcher = watch(sys.get_config_string("garden.watch", "light&flying"));
if (watcher !== undefined) {
add(garden, watcher);
}
for (let i = 0; i < 20; i++) {
spawn(garden);
}
return { garden };
return { garden, net };
},
// ...
update(self.garden, dt);
},
on_input(self, action_id, action) {
const x = action.x ?? 0;
const y = action.y ?? 0;
if (action_id === TOUCH && action.pressed) {
for (const f of self.garden.entities) {
const near = math.abs(f.position.x - x) < 20 && math.abs(f.position.y - y) < 20;
if (near) {
const catchable = self.net.filter?.(self.net, f) === true;
print(`${f.name}: ${catchable ? "you can catch it" : "too quick"}`);
}
}
}
},
});sys.get_config_string("garden.watch", ...)reads awatchsetting from a[garden]section ingame.project, so you can change what the label counts without touching code.addputs the watch system into the world. It takes systems and entities alike.self.net.filteris the filtercatchablewas built with. The factory stores it in the system'sfilterfield, and calling it asfilter(system, entity)asks whether the system would take that firefly.
Add a hud game object with labels named awake and watch, and a touch action on the left mouse button to your input bindings.
Run it for one frame, then click firefly 1 and firefly 4:
ecs garden frame 0: inspecting [0, 0, 0, 0, 0]
ecs garden frame 0: system 1 adds entity 1, holds 1
ecs garden frame 0: system 2 adds entity 1, holds 1
ecs garden frame 0: system 4 adds entity 1, holds 1
ecs garden frame 0: system 6 adds entity 1, holds 1
...
firefly 1: too quick
firefly 4: you can catch itThe world starts with five systems, and add puts the watch system sixth at the first update. Firefly 1 is lit and flying, so it joins drift, swarm, counter and the watch, and it is too quick to catch. Firefly 4 flies with no light, so catchable holds it.
Try it
- A firefly is lit and resting. Which of
drift,counter,catchableandbeaconstake it? - Set
watch = light|ingame.project. What happens? - Write
filter("light&!flyng")inbeacons. When do you find out?
Answer
counter, because it is lit;catchable, because it is not flying; andbeacons, because it is lit and not flying.driftneedsflying.tryFilterreturns an error,watchprints it and returnsundefined, and the garden runs without the watch label.- At once: a literal pattern is checked when it compiles, and
flyngis not a field ofFirefly.
7. Coming and going
Entities join and leave systems as their components change, and the world can tell a system when. Each system may define two hooks:
onAdd(e)runs when an entity joins the system, with the filter's components present.onRemove(e)runs when it leaves. The entity may have lost those components by then.
That is enough to make lights work. Each firefly game object gets two more sprites, light and hint, that start disabled:
import {
changed,
filter,
processingSystem,
rejectAll,
removeEntity,
requireAll,
// ...
e.position.y += e.velocity.y * dt;
go.set_position(e.position, e.id);
const gone =
e.position.x < 0 || e.position.x > WIDTH || e.position.y < 0 || e.position.y > HEIGHT;
if (gone && this.world !== undefined) {
removeEntity(this.world, e);
}
},
// ...
/** Holds the fireflies you can catch: each one that is dark or not flying. */
export function catchable() {
return system<Firefly>()(rejectAll("light", "flying"), {});
return system<Firefly>()(rejectAll("light", "flying"), {
onAdd(e) {
msg.post(msg.url(undefined, e.id, "hint"), "enable");
},
onRemove(e) {
msg.post(msg.url(undefined, e.id, "hint"), "disable");
},
});
}
// ...
export function beacons() {
return processingSystem<Firefly>()(filter("light&!flying"), {
onRemove(e) {
go.set_scale(1, e.id);
},
process(e) {
// ...
label.set_text("/hud#watch", `${pattern}: ${this.entities?.length ?? 0}`);
},
});
}
/** Deletes the game object of each firefly that leaves the world. */
export function bodies() {
return system<Firefly>()(requireAll("id"), {
onRemove(e) {
go.delete(e.id);
},
});
}
function lampOf(e: Firefly): Url {
return msg.url(undefined, e.id, "light");
}
/** Shows the light sprite of each lit firefly, as bright as it glows. */
export function lamps() {
return processingSystem<Firefly>()(requireAll("light"), {
onAdd(e) {
msg.post(lampOf(e), "enable");
},
onRemove(e) {
msg.post(lampOf(e), "disable");
},
process(e) {
go.set(lampOf(e), "tint.w", e.light);
},
});
}
/** Dims each light, and takes it away when it runs out. */
export function fade() {
return processingSystem<Firefly>()(requireAll("light"), {
process(e, dt) {
e.light -= dt / 4;
if (e.light <= 0 && this.world !== undefined) {
const dark: Firefly = e;
dark.light = undefined;
changed(this.world, dark);
}
},
});
} catchableshows the hint over a firefly while it can be caught, and hides it when it can't.beaconsputs back the scale it changed when a firefly leaves.lampsshows the light sprite of each lit firefly and sets its alpha to the light.fadedims every light. When one runs out, it takes thelightcomponent away and callschanged, which tells each system to check the firefly again at the next update.eis typed withlightpresent, sofadetakes it away through a plainFirefly.drifttakes a firefly that leaves the screen out of the world withremoveEntity.this.worldis the world the system belongs to.bodiesholds every firefly and deletes its game object when it leaves the world. Every way out of the garden ends inonRemove, so this one system tidies up for all of them.
The script adds the new systems and catches a firefly on a click:
import { defineScript } from "@defold-typescript/types";
import { add, addEntity, update, type World, world } from "@defold-typescript/types/ecs";
import {
add,
addEntity,
refresh,
remove,
update,
type World,
world,
} from "@defold-typescript/types/ecs";
import {
beacons,
bodies,
catchable,
counter,
drift,
fade,
type Firefly,
HEIGHT,
lamps,
swarm,
// ...
drift(),
swarm(),
lamps(),
beacons(),
counter(),
net,
fade(),
bodies(),
);
// ...
spawn(garden);
}
return { garden, net };
return { garden, net, caught: 0 };
},
// ...
const y = action.y ?? 0;
if (action_id === TOUCH && action.pressed) {
let picked: Firefly | undefined;
for (const f of self.garden.entities) {
const near = math.abs(f.position.x - x) < 20 && math.abs(f.position.y - y) < 20;
if (near) {
const catchable = self.net.filter?.(self.net, f) === true;
print(`${f.name}: ${catchable ? "you can catch it" : "too quick"}`);
if (near && self.net.filter?.(self.net, f) === true) {
picked = f;
}
}
if (picked !== undefined) {
remove(self.garden, picked);
refresh(self.garden);
self.caught += 1;
label.set_text("/hud#caught", `${self.caught} caught`);
}
}removetakes the caught firefly out of the world. It takes systems and entities alike.refreshapplies the waiting changes now. Without it, the caught firefly would stay inself.garden.entitiesuntil the next update, and a second click in the same frame could catch it again.fadecomes afterlamps. A firefly whose light runs out stays in the systems afterfadeuntil the next update, withlightalreadyundefined.
Add a label named caught to the hud.
Run it for one frame, then click firefly 4 to catch it. refresh applies the catch at once, so it leaves every system that held it in the same frame:
ecs garden frame 0: inspecting [0, 0, 0, 0, 0, 0, 0, 0]
...
ecs garden frame 1: system 1 removes entity 4, holds 13
ecs garden frame 1: system 2 removes entity 4, holds 13
ecs garden frame 1: system 5 removes entity 4, holds 16
ecs garden frame 1: system 6 removes entity 4, holds 9
ecs garden frame 1: system 8 removes entity 4, holds 19Those are drift, swarm, counter, catchable and bodies. Leaving catchable hides the firefly's hint, and leaving bodies deletes its game object.
Try it
- A lit firefly flies until its light runs out. Which hooks run, and when?
- Why does
bodiesrequireid, which every firefly has?
Answer
- At the next update after
fadetakes its light, the firefly leaveslamps, whoseonRemovehides its light sprite, and joinscatchable, whoseonAddshows its hint. It leavesfadetoo, which has no hooks, and stays incounter, since it still flies. - To hold every firefly. It leaves
bodiesonly by leaving the world, so itsonRemovemeans "gone for good".
8. Before and after
A frame has more moments than update, and a system can hook into each of them. See One frame for the full order.
The awake counter writes its label every frame, though the number only changes when a firefly joins or leaves. onModify runs only then:
export function counter() {
return system<Firefly>()(requireAny("light", "flying"), {
update() {
onModify() {
label.set_text("/hud#awake", `${this.entities?.length ?? 0} awake`);The world sets a system's modified flag when its entities change, runs onModify while the flag is set, and clears the flag after the system updates. A system that just joined counts as changed, so the label is right from the first frame. Lesson 10 sets the flag by hand.
A processing system has two more hooks, around its loop, and every system has two around the whole frame:
changed(this.world, dark);
}
},
});
}
/** Tints `sprite` by how much light the fireflies give together. */
export function glowSum(sprite: Url) {
return processingSystem<Firefly>()(requireAll("light"), {
total: 0,
preProcess() {
this.total = 0;
},
process(e) {
this.total += e.light;
},
postProcess() {
go.set(sprite, "tint.w", math.min(1, this.total / 5));
},
});
}
/** Writes how long each world update takes, from before the first update to after the last. */
export function stopwatch() {
return system<Firefly>()({
started: 0,
preWrap() {
this.started = os.clock();
},
postWrap() {
const spent = os.clock() - this.started;
label.set_text("/hud#time", `${math.floor(spent * 1000000)} microseconds`);
},
});
} preProcessruns before the loop andpostProcessafter it.glowSumempties its total, adds up every light, then tints a sprite by the result: the grass glows as brightly as the fireflies do together.preWrapruns before any system updates, andpostWrapafter they all have.stopwatchtimes the update pass between them.stopwatchhas no filter. A system without one holds no entities and still runs every hook.
Add both to the world, with stopwatch first:
fade,
type Firefly,
glowSum,
HEIGHT,
lamps,
stopwatch,
swarm,
// ...
const net = catchable();
const garden = world<Firefly>(
stopwatch(),
drift(),
swarm(),
lamps(),
glowSum(msg.url("/grass#sprite")),
beacons(),Add a grass game object with a sprite, and a time label to the hud.
Run it for two frames:
ecs garden frame 0: inspecting [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ecs garden frame 0: system 2 adds entity 1, holds 1
...
ecs garden frame 0: system 7 onModify, holds 17counter, system 7, runs onModify once, at the first update, after every firefly has joined. The second frame changes nobody, so it prints nothing. stopwatch is system 1 and never shows up: with no filter, it holds no fireflies.
Try it
stopwatchsits first in the world. Does itspreWraprun before the other systems'preWrap?- What would the grass do if
glowSumhad nopreProcess?
Answer
- After them.
preWrapruns from the last system to the first. It doesn't matter here: everypreWrapruns before anyupdate. - Grow brighter every frame until it is fully lit, and stay that way. The total would keep every frame's lights.
9. Every so often
Some work should happen now and then, not every frame. A system with an interval runs update once each time that much time has passed:
processingSystem,
rejectAll,
rejectAny,
removeEntity,
// ...
label.set_text("/hud#time", `${math.floor(spent * 1000000)} microseconds`);
},
});
}
/** Lights one dark firefly at a time, at a pace that changes after each one. */
export function blink() {
return system<Firefly>()(rejectAny("light"), {
interval: 1,
update() {
const dark = this.entities;
if (dark !== undefined && dark.length > 0 && this.world !== undefined) {
const e = dark[math.random(0, dark.length - 1)];
e.light = 1;
changed(this.world, e);
}
this.interval = 0.5 + math.random();
},
});
} interval: 1runsupdateonce a second, with1asdt. On a slow frame it can run twice, and on most frames not at all.this.intervalcan change at any time.blinkpicks a new pause after each firefly it lights, so the garden never blinks in step.rejectAny("light")takes the dark fireflies, andblinklights one of them. Giving it a light is a change of components, so it callschanged.
The script adds blink, keeps it on self, and gets two new keys:
add,
addEntity,
changed,
refresh,
// ...
import {
beacons,
blink,
bodies,
// ...
const TOUCH = hash("touch");
const CLAP = hash("clap");
const BLINK = hash("blink");
let born = 0;
// ...
init() {
msg.post(".", "acquire_input_focus");
const blinker = blink();
const net = catchable();
// ...
beacons(),
counter(),
blinker,
net,
// ...
spawn(garden);
}
return { garden, net, caught: 0 };
return { garden, blinker, net, caught: 0 };
},
// ...
label.set_text("/hud#caught", `${self.caught} caught`);
}
} else if (action_id === CLAP && action.pressed) {
for (const f of self.garden.entities) {
f.light = undefined;
changed(self.garden, f);
}
self.blinker.bufferedTime = 0;
} else if (action_id === BLINK && action.pressed) {
self.blinker.active = !self.blinker.active;
}clapputs every light out. The world kept count of the time toward the next blink inbufferedTime, and setting it to0makes the dark garden wait a full interval before the first new blink.blinkturns blinking off and on withactive. An inactive system skips every hook of the frame, and it still gains and loses entities, so it is up to date when it starts again.
Add clap and blink actions on two keys.
Run it for one frame, press clap, and wait a second:
...
ecs garden frame 1: system 4 removes entity 1, holds 12
ecs garden frame 1: system 5 removes entity 1, holds 12
ecs garden frame 1: system 8 adds entity 1, holds 8
...
ecs garden frame 61: system 4 adds entity 14, holds 1
ecs garden frame 61: system 5 adds entity 14, holds 1
ecs garden frame 61: system 6 adds entity 14, holds 1
ecs garden frame 61: system 7 adds entity 14, holds 15
ecs garden frame 61: system 8 removes entity 14, holds 19
ecs garden frame 61: system 10 adds entity 14, holds 1
ecs garden frame 61: system 7 onModify, holds 15The clap puts out every light, so each lit firefly leaves lamps and glowSum, systems 4 and 5, and joins blink, system 8. A full interval later blink lights firefly 14, and it moves back: into lamps, glowSum, beacons, since it rests, counter and fade, and out of blink.
Try it
intervalis 1 and a frame takes 2.5 seconds. How many times doesupdaterun, and what isbufferedTimeafterward?- You turn
blinkoff, and three lights go out. Doesblinkknow when you turn it back on?
Answer
- Twice, and
bufferedTimeis0.5, which counts toward the next run. - Yes. The three dark fireflies joined
blinkwhile it was off, since an inactive system still gains entities.
10. In order
Systems run in order, but the entities inside one run in whatever order they joined. When order matters, sort them. sortedSystem and sortedProcessingSystem keep their entities in the order a compare function gives.
First, a label that names the brightest firefly:
requireAll,
requireAny,
sortedProcessingSystem,
sortedSystem,
system,
// ...
this.interval = 0.5 + math.random();
},
});
}
/** Writes the name of the brightest firefly. */
export function byLight() {
return sortedSystem<Firefly>()(requireAll("light"), {
compare(a, b) {
return a.light > b.light;
},
update() {
const brightest = this.entities?.[0];
label.set_text("/hud#brightest", brightest === undefined ? "" : brightest.name);
},
postWrap() {
this.modified = true;
},
});
} compare(a, b)returns whetheragoes beforeb. Brighter goes first, sothis.entities[0]is the brightest.- A sorted system sorts when its entities change.
fadechanges every light every frame without changing who is lit, sobyLightsetsthis.modifiedinpostWrapand sorts again at the next update. Set inupdate, the flag would be cleared at once, since the world clears it after each system's update.
Then the order the fireflies are drawn in. Lower on the screen means nearer, so a firefly lower down should cover one above it:
this.modified = true;
},
});
}
/** Draws the fireflies lower on the screen in front of the ones above them. */
export function depth() {
return sortedProcessingSystem<Firefly>()(requireAll("position"), {
nocache: false,
rank: 0,
compare(a, b) {
return a.position.y > b.position.y;
},
preProcess() {
this.rank = 0;
},
process(e) {
e.position.z = this.rank / 1000;
this.rank += 1;
go.set_position(e.position, e.id);
},
postWrap() {
this.modified = true;
},
});
} depthprocesses the fireflies from the top of the screen down and gives each a higherz, so the lower ones draw in front.nocache: falsesays what is always true of a sorted system: it keeps its list, because the order lives in that list.nocache: truefails to compile here. Lesson 12 shows whatnocachedoes on a system that can have it.
The script adds both and uses depth's order to pick which firefly a click catches:
blink,
bodies,
byLight,
catchable,
counter,
depth,
drift,
// ...
const blinker = blink();
const net = catchable();
const layers = depth();
print(`layers keeps its list: ${layers.nocache === false}`);
const garden = world<Firefly>(
// ...
drift(),
swarm(),
layers,
lamps(),
glowSum(msg.url("/grass#sprite")),
byLight(),
beacons(),
// ...
spawn(garden);
}
return { garden, blinker, net, caught: 0 };
return { garden, blinker, net, layers, caught: 0 };
},
// ...
const near = math.abs(f.position.x - x) < 20 && math.abs(f.position.y - y) < 20;
if (near && self.net.filter?.(self.net, f) === true) {
picked = f;
if (picked === undefined || self.layers.sortDelegate?.(picked, f) === true) {
picked = f;
}
}sortDelegateiscomparebound to the system, made at its first sort. The click keeps the catchable firefly thatdepthwould draw last, the one in front.layers.nocachereads back thefalsefrom the definition. A sorted system's ownnocachefield is typedfalseas well, so evenlayers.nocache === truefails to compile.
Add a brightest label to the hud.
Run it for one frame:
layers keeps its list: true
ecs garden frame 0: inspecting [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
...
ecs garden frame 0: system 9 onModify, holds 17
ecs garden frame 0: system 7 onModify, holds 13
ecs garden frame 0: system 4 onModify, holds 20init prints the first line before the world runs. At the first update byLight, system 7, and layers, system 4, run onModify beside counter: a sorted system sorts in its onModify.
Try it
- Take
postWrapout ofbyLight. What does the label show? - Two fireflies are at the same height. Which one does
depthdraw in front?
Answer
- The brightest firefly at the last moment one joined or left
byLight, not the brightest now. - The one that came second in the list before the sort. The sort is stable: when neither goes first, they keep their order.
11. Systems come and go
A world can gain and lose systems while it runs, just as it does entities. Make a gust of wind that blows for four seconds and then leaves:
changed,
filter,
getSystemCount,
processingSystem,
// ...
rejectAny,
removeEntity,
removeSystem,
requireAll,
// ...
go.set_position(e.position, e.id);
},
postWrap() {
this.modified = true;
},
});
}
/** Blows the flying fireflies sideways, with a sound, for four seconds after it joins a world. */
export function wind() {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
left: 0,
onAddToWorld(world) {
this.left = 4;
msg.post("/wind#sound", "play_sound");
print(`the wind is system ${this.index} of ${getSystemCount(world)}`);
},
onRemoveFromWorld() {
msg.post("/wind#sound", "stop_sound");
},
preProcess(dt) {
this.left -= dt;
if (this.left <= 0 && this.world !== undefined) {
removeSystem(this.world, this);
}
},
process(e, dt) {
e.velocity.x += 30 * dt;
},
});
} onAddToWorld(world)runs when the system joins a world, before it takes the world's entities. The wind starts its sound and prints where it stands:indexis its 1-based place among the world's systems, andgetSystemCountsays how many there are.onRemoveFromWorld()runs when the system leaves, after its entities left it. The wind stops its sound.removeSystemtakes the wind out when its time is up. Like every change, it waits for the next update.this.worldis set while the system belongs to a world, andundefinedonce it has left.
The gust key adds the wind, or takes it away early:
add,
addEntity,
addSystem,
changed,
refresh,
remove,
setSystemIndex,
update,
// ...
WIDTH,
watch,
wind,
} from "./garden";
// ...
const CLAP = hash("clap");
const BLINK = hash("blink");
const GUST = hash("gust");
let born = 0;
// ...
spawn(garden);
}
return { garden, blinker, net, layers, caught: 0 };
return { garden, blinker, net, layers, gust: wind(), caught: 0 };
},
// ...
} else if (action_id === BLINK && action.pressed) {
self.blinker.active = !self.blinker.active;
} else if (action_id === GUST && action.pressed) {
if (self.gust.world === undefined) {
addSystem(self.garden, self.gust);
setSystemIndex(self.garden, self.gust, 1);
} else {
remove(self.garden, self.gust);
}
}addSystemputs the wind at the end of the list, and it setsworldat once, so a second press in the same frame sees it.setSystemIndexmoves it to the front, so it pushes the fireflies beforedriftmoves them. It applies the waiting add first, and returns the old index.removetakes a system as easily as it takes a firefly.
Add a wind game object with a sound component named sound, and a gust action.
Run it for one frame, press gust, and let the wind blow out:
...
ecs garden frame 242: system 1 removes entity 20, holds 9
ecs garden frame 242: system 1 removes entity 2, holds 8
...
ecs garden frame 242: system 1 removes entity 15, holds 0
...The wind sits first, as setSystemIndex put it. When its four seconds are up, it lets go of every firefly it still holds, and onRemoveFromWorld stops its sound.
Try it
- What does the wind print when it joins?
- You press
gusttwice in one second. What happens?
Answer
the wind is system 15 of 15, with the watch system in the garden.setSystemIndexfirst applies the waiting add, which puts the wind at the end and runsonAddToWorldthere, and only then moves it to the front.- The first press adds the wind, and the second takes it away at the next update, which runs its
onRemoveFromWorldand stops the sound.
12. Counting and asking
Fireflies should flee from the pointer. Which ones are near it changes every frame, though no component changes, so a filter that reads the pointer would need changed on every firefly every frame. A nocache system skips that: it keeps no list, and runs its filter on every entity of the world at every update:
e.velocity.x += 30 * dt;
},
});
}
/** Pushes each flying firefly near `cursor` away from it. */
export function scare(cursor: Vector3) {
return processingSystem<Firefly>()(
(_system: unknown, e: Firefly) =>
e.flying === true &&
math.abs(e.position.x - cursor.x) < 60 &&
math.abs(e.position.y - cursor.y) < 60,
{
nocache: true,
process(e, dt) {
if (e.velocity !== undefined) {
e.velocity.x += (e.position.x - cursor.x) * 4 * dt;
e.velocity.y += (e.position.y - cursor.y) * 4 * dt;
}
},
},
);
} - The filter is a function
(system, entity) => boolean. Any function of that shape is a filter, and like a string filter it narrows nothing. nocache: truemakesscarefilter the whole world each update. It gets noonAddoronRemove, since nothing joins or leaves.cursoris a vector the script updates as the pointer moves. The filter reads it each time it runs.
The script feeds the cursor, and a census key prints what the world holds:
addSystem,
changed,
getEntityCount,
getSystemCount,
hasEntity,
refresh,
// ...
HEIGHT,
lamps,
scare,
stopwatch,
// ...
const BLINK = hash("blink");
const GUST = hash("gust");
const CENSUS = hash("census");
let born = 0;
// ...
init() {
msg.post(".", "acquire_input_focus");
const cursor = vmath.vector3();
const blinker = blink();
// ...
drift(),
swarm(),
scare(cursor),
layers,
// ...
add(garden, watcher);
}
let first: Firefly | undefined;
for (let i = 0; i < 20; i++) {
spawn(garden);
const f = spawn(garden);
first ??= f;
}
return { garden, blinker, net, layers, gust: wind(), caught: 0 };
return { garden, cursor, first, blinker, net, layers, gust: wind(), caught: 0 };
},
// ...
const x = action.x ?? 0;
const y = action.y ?? 0;
if (action_id === TOUCH && action.pressed) {
if (action_id === undefined) {
self.cursor.x = x;
self.cursor.y = y;
} else if (action_id === TOUCH && action.pressed) {
let picked: Firefly | undefined;
// ...
remove(self.garden, self.gust);
}
} else if (action_id === CENSUS && action.pressed) {
print(`${getEntityCount(self.garden)} fireflies, ${getSystemCount(self.garden)} systems`);
for (const s of self.garden.systems) {
if (s.nocache === true) {
print(`system ${s.index}: no list (entities ${s.entities}, indices ${s.indices})`);
} else {
print(`system ${s.index}: ${s.entities?.length ?? 0} fireflies`);
}
}
if (self.first !== undefined) {
print(`${self.first.name} is ${hasEntity(self.garden, self.first) ? "here" : "gone"}`);
}
}- A mouse move reaches
on_inputwith no action, soaction_id === undefinedupdates the cursor. getEntityCountandgetSystemCountcount what the world holds, as of its last update.self.garden.systemslists the systems in order, andself.garden.entitiesthe fireflies.- A system that keeps a list has
entitiesandindices, which finds each entity's place in that list so a firefly can leave quickly.scarehas neither, so the census printsnilfor both. hasEntityasks whether the world holds the first firefly, as of its last update.
Add a census action.
Run it for one frame and press census:
layers keeps its list: true
ecs garden frame 0: inspecting [0, 0, 0, -, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
...
20 fireflies, 15 systems
system 1: 0 fireflies
system 2: 14 fireflies
...
system 4: no list (entities nil, indices nil)
...
firefly 1 is herestopwatch, system 1, has no filter and holds nobody, and scare, system 4, keeps no list. The inspector's first line marks scare the same way, with a - where a count would be.
Try it
- Why doesn't
scarerequireflyingwithrequireAll, asdriftdoes? - You catch the first firefly and press
censusin the same frame. Does it sayhereorgone?
Answer
- A filter is one function, and
scare's is the pointer test. It checksflyingitself. gone. Catching callsrefresh, so the world no longer holds it.
13. A fresh night
Two last world controls. The first freezes every firefly in place while the lights keep blinking. update takes a third argument, a filter that picks the systems to run, called as filter(world, system) so the names it tests are fields of the system:
export function drift() {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
process(e, dt) {
// ...
export function swarm() {
return system<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
update(dt) {
// ...
export function wind() {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
left: 0,
// ...
math.abs(e.position.y - cursor.y) < 60,
{
moving: true,
nocache: true,Each system that moves fireflies gets a moving field. The script leaves those out while frozen, and adds a dawn key that starts the night over:
addSystem,
changed,
clearEntities,
clearSystems,
getEntityCount,
// ...
hasEntity,
refresh,
rejectAny,
remove,
// ...
const GUST = hash("gust");
const CENSUS = hash("census");
const FREEZE = hash("freeze");
const DAWN = hash("dawn");
const STILL = rejectAny("moving");
let born = 0;
// ...
first ??= f;
}
return { garden, cursor, first, blinker, net, layers, gust: wind(), caught: 0 };
return { garden, cursor, first, blinker, net, layers, gust: wind(), caught: 0, frozen: false };
},
update(self, dt) {
update(self.garden, dt);
update(self.garden, dt, self.frozen ? STILL : undefined);
},
// ...
print(`${self.first.name} is ${hasEntity(self.garden, self.first) ? "here" : "gone"}`);
}
} else if (action_id === FREEZE && action.pressed) {
self.frozen = !self.frozen;
} else if (action_id === DAWN && action.pressed) {
clearEntities(self.garden);
for (let i = 0; i < 20; i++) {
spawn(self.garden);
}
}
},
final(self) {
clearSystems(self.garden);
refresh(self.garden);
},
});rejectAny("moving")takes every system without amovingfield. Build it once, asSTILLis, rather than every frame.- The left-out systems skip
preWrap,updateandpostWrap.onModifystill runs on every active system. clearEntitiestakes every firefly away at the next update, andbodiesdeletes their game objects. The twenty new ones join at that same update.clearSystemsinfinalmakes every system leave, so eachonRemoveandonRemoveFromWorldruns:bodiesdeletes the fireflies, which the factory made and the garden's game object does not own, and the wind stops its sound.refreshapplies it at once, since no update comes afterfinal.
Add freeze and dawn actions.
Run it for one frame, press dawn, and run one more:
...
ecs garden frame 1: system 14 adds entity 21, holds 21
...
ecs garden frame 1: system 14 adds entity 40, holds 40
...
ecs garden frame 1: system 14 removes entity 20, holds 20
...At that one update, the twenty new fireflies join bodies, system 14, and then the twenty old ones leave it, and bodies deletes their game objects.
Try it
- While frozen, does a resting firefly still light up?
- You press
dawntwice in one frame. How many fireflies are there at the next update?
Answer
- Yes.
blink,lampsandfadehave nomovingfield, so they still run. - Forty.
clearEntitiestakes only the fireflies the world held at its last update, and both presses each add twenty new ones.
14. The world's own methods
Every function that takes the world first, except hasEntity, is also a method of the world. update(garden, dt) is garden.update(dt), and in Lua it is garden:update(dt), the way most tiny-ecs code is written. The World reference lists them all. Use whichever reads better; the rest of this lesson uses methods.
Build a jar for the fireflies you catch. The jar is a second world, and building it is a review of everything so far:
const FREEZE = hash("freeze");
const DAWN = hash("dawn");
const SHAKE = hash("shake");
const RELEASE = hash("release");
const EMPTY = hash("empty");
const STILL = rejectAny("moving");
// ...
first ??= f;
}
return { garden, cursor, first, blinker, net, layers, gust: wind(), caught: 0, frozen: false };
const jar = world<Firefly>();
jar.add(fade());
return {
garden,
jar,
shine: glowSum(msg.url("/jar#sprite")),
cursor,
first,
blinker,
net,
layers,
gust: wind(),
frozen: false,
};
},
update(self, dt) {
update(self.garden, dt, self.frozen ? STILL : undefined);
self.jar.update(dt);
},
// ...
remove(self.garden, picked);
refresh(self.garden);
self.caught += 1;
label.set_text("/hud#caught", `${self.caught} caught`);
self.jar.refresh();
if (self.shine.world === undefined) {
self.jar.addSystem(self.shine);
self.jar.setSystemIndex(self.shine, 1);
print(`the jar runs ${self.jar.getSystemCount()} systems`);
}
self.jar.addEntity(picked);
self.jar.refresh();
label.set_text("/hud#jar", `${self.jar.getEntityCount()} in the jar`);
}
// ...
spawn(self.garden);
}
} else if (action_id === SHAKE && action.pressed) {
for (const f of self.jar.entities) {
f.light = 1;
self.jar.changed(f);
}
} else if (action_id === RELEASE && action.pressed) {
const f = self.jar.entities[0];
if (f !== undefined) {
self.jar.removeEntity(f);
self.jar.refresh();
if (self.jar.getEntityCount() === 0 && self.shine.world === self.jar) {
self.jar.removeSystem(self.shine);
}
spawn(self.garden);
}
} else if (action_id === EMPTY && action.pressed) {
self.jar.clearEntities();
if (self.shine.world === self.jar) {
self.jar.remove(self.shine);
}
}
// ...
clearSystems(self.garden);
refresh(self.garden);
self.jar.clearSystems();
self.jar.refresh();
},jar.add(fade())gives the jar its ownfade: one system belongs to one world.self.jar.addSystem(self.shine)adds the jar's glow with the first catch, andself.jar.setSystemIndex(self.shine, 1)puts it beforefade, which would put out a light it is about to read.setSystemIndexapplies the waiting add, sogetSystemCount()already counts the shine.self.jar.refresh()runs first, so areleaseoremptyearlier in the same frame has already taken the shine out when the catch checks for it.self.jar.addEntity(picked)keeps the caught firefly, andself.jar.refresh()applies it sogetEntityCount()is right in the label. The garden'sbodieshas deleted its game object; in the jar it is only a light.shakerelights every firefly in the jar withself.jar.changed(f).releasetakes one out withself.jar.removeEntity(f), and a new firefly hatches in the garden. The last one out takes the shine with it, throughself.jar.removeSystem(self.shine), but only while the jar holds it, since anemptyearlier in the same frame may already have taken it.emptylets them all go withself.jar.clearEntities(), andself.jar.remove(self.shine)takes the shine. It runs only while the shine is in the jar: the shine joins with the first catch and leaves with the last firefly out, and a world throws when asked to remove a system it does not hold.self.jar.update(dt)runs the jar every frame, andfinalclears its systems as it clears the garden's.
Add a jar game object with a sprite, a jar label to the hud, and shake, release and empty actions.
Run it for one frame, catch firefly 4, press release, and run one more frame:
...
ecs garden frame 1: system 14 removes entity 4, holds 19
...
ecs garden frame 1: system 14 adds entity 21, holds 20
ecs garden frame 1: system 5 onModify, holds 20The inspector watches the garden alone, so the jar's own changes print nothing. The garden loses firefly 4 when you catch it, and the firefly that hatches when you let it go joins the garden at the next update.
Try it
- What does the jar print the first time you catch a firefly?
- Why does
releasecallrefreshbefore it counts?
Answer
the jar runs 2 systems:shineandfade.getEntityCountcounts as of the last update, when the released firefly was still in the jar.
15. Watch it run
A world is easier to trust when you can see it work. inspect from @defold-typescript/types/ecs/debug logs every firefly that joins or leaves a system, and every onModify, and its draw shows each system's count above a game object:
world,
} from "@defold-typescript/types/ecs";
import { inspect } from "@defold-typescript/types/ecs/debug";
import {
// ...
gust: wind(),
frozen: false,
inspector: inspect(garden, "garden"),
};
// ...
update(self.garden, dt, self.frozen ? STILL : undefined);
self.jar.update(dt);
self.inspector.draw(".");
},inspect(garden, "garden")prints one line now, then one line for each change the world applies, such asecs garden frame 12: system 9 adds entity 4, holds 7.self.inspector.draw(".")draws the label and each system's entity count above the garden's game object,-forscare, which keeps no list.- Systems are named by their index and entities by the order the inspector first saw them.
- In a release build both do nothing, so the calls can stay.
Run it for two frames, and your own script prints the lines the earlier lessons showed:
layers keeps its list: true
ecs garden frame 0: inspecting [0, 0, 0, -, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
ecs garden frame 0: system 2 adds entity 1, holds 1
...
ecs garden frame 0: system 10 onModify, holds 17
ecs garden frame 0: system 8 onModify, holds 13
ecs garden frame 0: system 5 onModify, holds 20
ecs garden frame 1: system 8 onModify, holds 13
ecs garden frame 1: system 5 onModify, holds 20Try it
- The console prints an
onModifyline for two systems at every frame. Which ones, and why? - A flying firefly's light runs out. Which systems print an
addsor aremovesline for it? - Why does the frame number in the log only go up while
drawis called?
Answer
layersandbyLight. A sorted system'sonModifyis its sort, and both setmodifiedinpostWrap, so both sort at every update.lamps,glowSum,byLightandfadeprintremoves, andblinkandcatchableprintadds.- The inspector counts frames by its own
drawcalls, so it tracksupdatewhen you draw every frame.
16. A machine in each firefly
So far a firefly rests or flies forever, as it was born. A state machine can decide that: fly for a while, rest for a while, and get caught from either. The bridge in @defold-typescript/types/ecs/hsm lets the machine's states set components, so each state moves the firefly in and out of systems. See ecs and hsm together for the whole bridge.
Make firefly-machine.ts:
import type { World } from "@defold-typescript/types/ecs";
import { leave, member } from "@defold-typescript/types/ecs/hsm";
import { defineMachine } from "@defold-typescript/types/hsm";
import type { Firefly } from "./garden";
export type FireflyEvent = { type: "CATCH" };
export function fireflyMachine(garden: World<Firefly>) {
return defineMachine<Firefly, FireflyEvent>()({
initial: "/flying",
states: {
flying: {
...member(garden, "flying"),
after: { 8: "/resting" },
on: { CATCH: "/caught" },
},
resting: {
after: { 4: "/flying" },
on: { CATCH: "/caught" },
},
caught: {
enter: leave(garden),
},
},
});
}
export type FireflyMachine = ReturnType<typeof fireflyMachine>;member(garden, "flying")returns anenterhook that setsflyingand anexithook that takes it away, both callingchangedfor you. Spread intoflying, they make the firefly joindrift,swarmand the rest while it flies.leave(garden)is a hook that takes the firefly out of the world. A caught firefly leaves the garden.aftermoves on after a few seconds, as the state machine tutorial shows.
The firefly carries its machine as a component:
tryFilter,
} from "@defold-typescript/types/ecs";
import type { MachineInstance } from "@defold-typescript/types/hsm";
import type { FireflyEvent } from "./firefly-machine";
// ...
light?: number;
flying?: true;
fsm?: MachineInstance<Firefly, FireflyEvent>;
}The script starts a machine for each new firefly, ticks every machine from the world, and sends CATCH in place of removing the firefly:
} from "@defold-typescript/types/ecs";
import { inspect } from "@defold-typescript/types/ecs/debug";
import { tickMachines } from "@defold-typescript/types/ecs/hsm";
import { type FireflyMachine, fireflyMachine } from "./firefly-machine";
import {
// ...
let born = 0;
function spawn(garden: World<Firefly>): Firefly | undefined {
function spawn(garden: World<Firefly>, machine: FireflyMachine): Firefly | undefined {
const position = vmath.vector3(math.random(0, WIDTH), math.random(0, HEIGHT), 0);
// ...
}
born += 1;
return addEntity(garden, {
const f: Firefly = addEntity(garden, {
name: `firefly ${born}`,
// ...
velocity: vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0),
light: math.random() < 0.5 ? 1 : undefined,
flying: math.random() < 0.5 ? true : undefined,
});
f.fsm = machine.start(f);
return f;
}
// ...
const garden = world<Firefly>(
stopwatch(),
tickMachines<Firefly>("fsm"),
drift(),
// ...
add(garden, watcher);
}
const machine = fireflyMachine(garden);
let first: Firefly | undefined;
for (let i = 0; i < 20; i++) {
const f = spawn(garden);
const f = spawn(garden, machine);
first ??= f;
// ...
jar,
shine: glowSum(msg.url("/jar#sprite")),
machine,
cursor,
// ...
}
if (picked !== undefined) {
remove(self.garden, picked);
picked.fsm?.send({ type: "CATCH" });
refresh(self.garden);
// ...
clearEntities(self.garden);
for (let i = 0; i < 20; i++) {
spawn(self.garden);
spawn(self.garden, self.machine);
}
// ...
self.jar.removeSystem(self.shine);
}
spawn(self.garden);
spawn(self.garden, self.machine);
}tickMachines<Firefly>("fsm")is a system that callsupdate(dt)on each firefly's machine, so its timers run with the world. A change its hooks make shows at the next update. It has nomovingfield, so the machines keep time while the garden is frozen.spawnstarts the machine, which entersflyingat once and sets the flag before the firefly joins.spawnno longer setsflyingitself: the machine decides.picked.fsm?.send({ type: "CATCH" })moves the machine tocaught, whose hook takes the firefly out of the garden;refreshapplies it.
An object spread compiles to a helper from lualib_bundle, so the build now writes that file too. The flying state also needs code of its own: a new heading each time it takes off. Name the two hooks instead, and call enter from a hook of your own. A released firefly can then fly back:
import type { World } from "@defold-typescript/types/ecs";
import { leave, member } from "@defold-typescript/types/ecs/hsm";
import { join, leave, member } from "@defold-typescript/types/ecs/hsm";
import { defineMachine } from "@defold-typescript/types/hsm";
import type { Firefly } from "./garden";
export type FireflyEvent = { type: "CATCH" };
export type FireflyEvent = { type: "CATCH" } | { type: "RELEASE" };
export function fireflyMachine(garden: World<Firefly>) {
const flight = member(garden, "flying");
return defineMachine<Firefly, FireflyEvent>()({
// ...
states: {
flying: {
...member(garden, "flying"),
enter: (ctx) => {
flight.enter(ctx);
ctx.velocity = vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0);
},
exit: flight.exit,
after: { 8: "/resting" },
// ...
caught: {
enter: leave(garden),
exit: join(garden),
on: { RELEASE: "/flying" },
},flight.enter(ctx)setsflyingas the spread did, and the new heading follows it.exit: flight.exittakes the flag away on landing.join(garden)is the opposite ofleave: leavingcaughtputs the firefly back in the garden.
The script gives a released firefly a new game object and sends RELEASE:
self.jar.removeSystem(self.shine);
}
spawn(self.garden, self.machine);
const id = factory.create("#factory", vmath.vector3(880, 80, 0));
if (id !== undefined) {
f.id = id;
f.position.x = 880;
f.position.y = 80;
f.fsm?.send({ type: "RELEASE" });
}
}The garden now uses every function and every field of ecs.
The finished garden
import {
changed,
filter,
getSystemCount,
processingSystem,
rejectAll,
rejectAny,
removeEntity,
removeSystem,
requireAll,
requireAny,
sortedProcessingSystem,
sortedSystem,
system,
tryFilter,
} from "@defold-typescript/types/ecs";
import type { MachineInstance } from "@defold-typescript/types/hsm";
import type { FireflyEvent } from "./firefly-machine";
export interface Firefly {
readonly name: string;
id: Hash;
readonly position: Vector3;
velocity?: Vector3;
light?: number;
flying?: true;
fsm?: MachineInstance<Firefly, FireflyEvent>;
}
export const WIDTH = 960;
export const HEIGHT = 640;
/** Moves each flying firefly. */
export function drift() {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
process(e, dt) {
e.position.x += e.velocity.x * dt;
e.position.y += e.velocity.y * dt;
go.set_position(e.position, e.id);
const gone =
e.position.x < 0 || e.position.x > WIDTH || e.position.y < 0 || e.position.y > HEIGHT;
if (gone && this.world !== undefined) {
removeEntity(this.world, e);
}
},
});
}
/** Steers each flying firefly toward the middle of the swarm. */
export function swarm() {
return system<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
update(dt) {
const flock = this.entities;
if (flock === undefined || flock.length === 0) {
return;
}
let x = 0;
let y = 0;
for (const e of flock) {
x += e.position.x;
y += e.position.y;
}
x /= flock.length;
y /= flock.length;
for (const e of flock) {
if (e.velocity !== undefined) {
e.velocity.x += (x - e.position.x) * 0.2 * dt;
e.velocity.y += (y - e.position.y) * 0.2 * dt;
}
}
},
});
}
/** Writes how many fireflies are awake: lit, or flying. */
export function counter() {
return system<Firefly>()(requireAny("light", "flying"), {
onModify() {
label.set_text("/hud#awake", `${this.entities?.length ?? 0} awake`);
},
});
}
/** Holds the fireflies you can catch: each one that is dark or not flying. */
export function catchable() {
return system<Firefly>()(rejectAll("light", "flying"), {
onAdd(e) {
msg.post(msg.url(undefined, e.id, "hint"), "enable");
},
onRemove(e) {
msg.post(msg.url(undefined, e.id, "hint"), "disable");
},
});
}
/** Swells each lit firefly that sits still, as much as it glows. */
export function beacons() {
return processingSystem<Firefly>()(filter("light&!flying"), {
onRemove(e) {
go.set_scale(1, e.id);
},
process(e) {
if (e.light !== undefined) {
go.set_scale(1 + e.light / 2, e.id);
}
},
});
}
/** Counts the fireflies `pattern` takes, or returns `undefined` for a pattern that does not parse. */
export function watch(pattern: string) {
const parsed = tryFilter(pattern);
if (!parsed.ok) {
print(`garden.watch: ${parsed.error}`);
return undefined;
}
return system<Firefly>()(parsed.filter, {
update() {
label.set_text("/hud#watch", `${pattern}: ${this.entities?.length ?? 0}`);
},
});
}
/** Deletes the game object of each firefly that leaves the world. */
export function bodies() {
return system<Firefly>()(requireAll("id"), {
onRemove(e) {
go.delete(e.id);
},
});
}
function lampOf(e: Firefly): Url {
return msg.url(undefined, e.id, "light");
}
/** Shows the light sprite of each lit firefly, as bright as it glows. */
export function lamps() {
return processingSystem<Firefly>()(requireAll("light"), {
onAdd(e) {
msg.post(lampOf(e), "enable");
},
onRemove(e) {
msg.post(lampOf(e), "disable");
},
process(e) {
go.set(lampOf(e), "tint.w", e.light);
},
});
}
/** Dims each light, and takes it away when it runs out. */
export function fade() {
return processingSystem<Firefly>()(requireAll("light"), {
process(e, dt) {
e.light -= dt / 4;
if (e.light <= 0 && this.world !== undefined) {
const dark: Firefly = e;
dark.light = undefined;
changed(this.world, dark);
}
},
});
}
/** Tints `sprite` by how much light the fireflies give together. */
export function glowSum(sprite: Url) {
return processingSystem<Firefly>()(requireAll("light"), {
total: 0,
preProcess() {
this.total = 0;
},
process(e) {
this.total += e.light;
},
postProcess() {
go.set(sprite, "tint.w", math.min(1, this.total / 5));
},
});
}
/** Writes how long each world update takes, from before the first update to after the last. */
export function stopwatch() {
return system<Firefly>()({
started: 0,
preWrap() {
this.started = os.clock();
},
postWrap() {
const spent = os.clock() - this.started;
label.set_text("/hud#time", `${math.floor(spent * 1000000)} microseconds`);
},
});
}
/** Lights one dark firefly at a time, at a pace that changes after each one. */
export function blink() {
return system<Firefly>()(rejectAny("light"), {
interval: 1,
update() {
const dark = this.entities;
if (dark !== undefined && dark.length > 0 && this.world !== undefined) {
const e = dark[math.random(0, dark.length - 1)];
e.light = 1;
changed(this.world, e);
}
this.interval = 0.5 + math.random();
},
});
}
/** Writes the name of the brightest firefly. */
export function byLight() {
return sortedSystem<Firefly>()(requireAll("light"), {
compare(a, b) {
return a.light > b.light;
},
update() {
const brightest = this.entities?.[0];
label.set_text("/hud#brightest", brightest === undefined ? "" : brightest.name);
},
postWrap() {
this.modified = true;
},
});
}
/** Draws the fireflies lower on the screen in front of the ones above them. */
export function depth() {
return sortedProcessingSystem<Firefly>()(requireAll("position"), {
nocache: false,
rank: 0,
compare(a, b) {
return a.position.y > b.position.y;
},
preProcess() {
this.rank = 0;
},
process(e) {
e.position.z = this.rank / 1000;
this.rank += 1;
go.set_position(e.position, e.id);
},
postWrap() {
this.modified = true;
},
});
}
/** Blows the flying fireflies sideways, with a sound, for four seconds after it joins a world. */
export function wind() {
return processingSystem<Firefly>()(requireAll("velocity", "flying"), {
moving: true,
left: 0,
onAddToWorld(world) {
this.left = 4;
msg.post("/wind#sound", "play_sound");
print(`the wind is system ${this.index} of ${getSystemCount(world)}`);
},
onRemoveFromWorld() {
msg.post("/wind#sound", "stop_sound");
},
preProcess(dt) {
this.left -= dt;
if (this.left <= 0 && this.world !== undefined) {
removeSystem(this.world, this);
}
},
process(e, dt) {
e.velocity.x += 30 * dt;
},
});
}
/** Pushes each flying firefly near `cursor` away from it. */
export function scare(cursor: Vector3) {
return processingSystem<Firefly>()(
(_system: unknown, e: Firefly) =>
e.flying === true &&
math.abs(e.position.x - cursor.x) < 60 &&
math.abs(e.position.y - cursor.y) < 60,
{
moving: true,
nocache: true,
process(e, dt) {
if (e.velocity !== undefined) {
e.velocity.x += (e.position.x - cursor.x) * 4 * dt;
e.velocity.y += (e.position.y - cursor.y) * 4 * dt;
}
},
},
);
}import { defineScript } from "@defold-typescript/types";
import {
add,
addEntity,
addSystem,
changed,
clearEntities,
clearSystems,
getEntityCount,
getSystemCount,
hasEntity,
refresh,
rejectAny,
remove,
setSystemIndex,
update,
type World,
world,
} from "@defold-typescript/types/ecs";
import { inspect } from "@defold-typescript/types/ecs/debug";
import { tickMachines } from "@defold-typescript/types/ecs/hsm";
import { type FireflyMachine, fireflyMachine } from "./firefly-machine";
import {
beacons,
blink,
bodies,
byLight,
catchable,
counter,
depth,
drift,
fade,
type Firefly,
glowSum,
HEIGHT,
lamps,
scare,
stopwatch,
swarm,
WIDTH,
watch,
wind,
} from "./garden";
const TOUCH = hash("touch");
const CLAP = hash("clap");
const BLINK = hash("blink");
const GUST = hash("gust");
const CENSUS = hash("census");
const FREEZE = hash("freeze");
const DAWN = hash("dawn");
const SHAKE = hash("shake");
const RELEASE = hash("release");
const EMPTY = hash("empty");
const STILL = rejectAny("moving");
let born = 0;
function spawn(garden: World<Firefly>, machine: FireflyMachine): Firefly | undefined {
const position = vmath.vector3(math.random(0, WIDTH), math.random(0, HEIGHT), 0);
const id = factory.create("#factory", position);
if (id === undefined) {
return undefined;
}
born += 1;
const f: Firefly = addEntity(garden, {
name: `firefly ${born}`,
id,
position,
velocity: vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0),
light: math.random() < 0.5 ? 1 : undefined,
});
f.fsm = machine.start(f);
return f;
}
export default defineScript({
init() {
msg.post(".", "acquire_input_focus");
const cursor = vmath.vector3();
const blinker = blink();
const net = catchable();
const layers = depth();
print(`layers keeps its list: ${layers.nocache === false}`);
const garden = world<Firefly>(
stopwatch(),
tickMachines<Firefly>("fsm"),
drift(),
swarm(),
scare(cursor),
layers,
lamps(),
glowSum(msg.url("/grass#sprite")),
byLight(),
beacons(),
counter(),
blinker,
net,
fade(),
bodies(),
);
const watcher = watch(sys.get_config_string("garden.watch", "light&flying"));
if (watcher !== undefined) {
add(garden, watcher);
}
const machine = fireflyMachine(garden);
let first: Firefly | undefined;
for (let i = 0; i < 20; i++) {
const f = spawn(garden, machine);
first ??= f;
}
const jar = world<Firefly>();
jar.add(fade());
return {
garden,
jar,
shine: glowSum(msg.url("/jar#sprite")),
machine,
cursor,
first,
blinker,
net,
layers,
gust: wind(),
frozen: false,
inspector: inspect(garden, "garden"),
};
},
update(self, dt) {
update(self.garden, dt, self.frozen ? STILL : undefined);
self.jar.update(dt);
self.inspector.draw(".");
},
on_input(self, action_id, action) {
const x = action.x ?? 0;
const y = action.y ?? 0;
if (action_id === undefined) {
self.cursor.x = x;
self.cursor.y = y;
} else if (action_id === TOUCH && action.pressed) {
let picked: Firefly | undefined;
for (const f of self.garden.entities) {
const near = math.abs(f.position.x - x) < 20 && math.abs(f.position.y - y) < 20;
if (near && self.net.filter?.(self.net, f) === true) {
if (picked === undefined || self.layers.sortDelegate?.(picked, f) === true) {
picked = f;
}
}
}
if (picked !== undefined) {
picked.fsm?.send({ type: "CATCH" });
refresh(self.garden);
self.jar.refresh();
if (self.shine.world === undefined) {
self.jar.addSystem(self.shine);
self.jar.setSystemIndex(self.shine, 1);
print(`the jar runs ${self.jar.getSystemCount()} systems`);
}
self.jar.addEntity(picked);
self.jar.refresh();
label.set_text("/hud#jar", `${self.jar.getEntityCount()} in the jar`);
}
} else if (action_id === CLAP && action.pressed) {
for (const f of self.garden.entities) {
f.light = undefined;
changed(self.garden, f);
}
self.blinker.bufferedTime = 0;
} else if (action_id === BLINK && action.pressed) {
self.blinker.active = !self.blinker.active;
} else if (action_id === GUST && action.pressed) {
if (self.gust.world === undefined) {
addSystem(self.garden, self.gust);
setSystemIndex(self.garden, self.gust, 1);
} else {
remove(self.garden, self.gust);
}
} else if (action_id === CENSUS && action.pressed) {
print(`${getEntityCount(self.garden)} fireflies, ${getSystemCount(self.garden)} systems`);
for (const s of self.garden.systems) {
if (s.nocache === true) {
print(`system ${s.index}: no list (entities ${s.entities}, indices ${s.indices})`);
} else {
print(`system ${s.index}: ${s.entities?.length ?? 0} fireflies`);
}
}
if (self.first !== undefined) {
print(`${self.first.name} is ${hasEntity(self.garden, self.first) ? "here" : "gone"}`);
}
} else if (action_id === FREEZE && action.pressed) {
self.frozen = !self.frozen;
} else if (action_id === DAWN && action.pressed) {
clearEntities(self.garden);
for (let i = 0; i < 20; i++) {
spawn(self.garden, self.machine);
}
} else if (action_id === SHAKE && action.pressed) {
for (const f of self.jar.entities) {
f.light = 1;
self.jar.changed(f);
}
} else if (action_id === RELEASE && action.pressed) {
const f = self.jar.entities[0];
if (f !== undefined) {
self.jar.removeEntity(f);
self.jar.refresh();
if (self.jar.getEntityCount() === 0 && self.shine.world === self.jar) {
self.jar.removeSystem(self.shine);
}
const id = factory.create("#factory", vmath.vector3(880, 80, 0));
if (id !== undefined) {
f.id = id;
f.position.x = 880;
f.position.y = 80;
f.fsm?.send({ type: "RELEASE" });
}
}
} else if (action_id === EMPTY && action.pressed) {
self.jar.clearEntities();
if (self.shine.world === self.jar) {
self.jar.remove(self.shine);
}
}
},
final(self) {
clearSystems(self.garden);
refresh(self.garden);
self.jar.clearSystems();
self.jar.refresh();
},
});import type { World } from "@defold-typescript/types/ecs";
import { join, leave, member } from "@defold-typescript/types/ecs/hsm";
import { defineMachine } from "@defold-typescript/types/hsm";
import type { Firefly } from "./garden";
export type FireflyEvent = { type: "CATCH" } | { type: "RELEASE" };
export function fireflyMachine(garden: World<Firefly>) {
const flight = member(garden, "flying");
return defineMachine<Firefly, FireflyEvent>()({
initial: "/flying",
states: {
flying: {
enter: (ctx) => {
flight.enter(ctx);
ctx.velocity = vmath.vector3(math.random(-40, 40), math.random(-40, 40), 0);
},
exit: flight.exit,
after: { 8: "/resting" },
on: { CATCH: "/caught" },
},
resting: {
after: { 4: "/flying" },
on: { CATCH: "/caught" },
},
caught: {
enter: leave(garden),
exit: join(garden),
on: { RELEASE: "/flying" },
},
},
});
}
export type FireflyMachine = ReturnType<typeof fireflyMachine>;Run the finished garden for eight seconds. Every machine entered flying at the same moment, so every firefly lands at once:
...
ecs garden frame 481: system 3 removes entity 1, holds 15
ecs garden frame 481: system 4 removes entity 1, holds 15
ecs garden frame 481: system 10 adds entity 1, holds 1
ecs garden frame 481: system 13 adds entity 1, holds 13
ecs garden frame 481: system 16 removes entity 1, holds 3
...flight.exit takes away flying, so firefly 1 leaves drift and swarm, systems 3 and 4, and the watch. It is lit, so it joins beacons and catchable. Four seconds later its machine enters flying again, and it rejoins drift and swarm.
To watch the same night in your browser, run bunx @defold-typescript/cli view fireflies.ts: the Worlds tab lists the fireflies each system holds, frame by frame.
Try it
- A firefly is caught while it rests. Which hooks run?
- Why does
releaseset the firefly'sidbefore it sendsRELEASE?
Answer
restinghas none, so onlycaught'senter, which takes the firefly out of the garden.flyingwas already left, and itsexittook the flag away then.bodiesdeleted the old game object when the firefly was caught. Leavingcaughtadds the firefly to the garden, and every system that moves or lights it needs a game object to work on.