plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


2abfecc — Peter John 2026-11-09T14:54:58+05:30
std/game_enum_tree on trait Actor[M] (actor-trait task 6)
compiler/checker/src/stmt.rs CHANGED
@@ -114,11 +114,18 @@ pub(crate) fn checkStmtInner(
114
114
  bindLocal(env, name, TypeScheme::mono(declared.clone()));
115
115
  recordAnnotation(value, &declared);
116
116
  }
117
+ Err(msg) => {
117
- Err(msg) => errors.push(CheckError::at(
118
+ errors.push(CheckError::at(
118
- fn_pos.0,
119
+ fn_pos.0,
119
- fn_pos.1,
120
+ fn_pos.1,
120
- format!("fn '{}': assign '{}': {}", fn_name, name, msg),
121
+ format!("fn '{}': assign '{}': {}", fn_name, name, msg),
121
- )),
122
+ ));
123
+ // Still declared, as below: in a generic body's erased pass
124
+ // the mismatch is dropped (`b: Actor := t` with `t: T` is
125
+ // checked per instantiation), and the name must still be
126
+ // bound for its later uses.
127
+ bindLocal(env, name, TypeScheme::mono(declared.clone()));
128
+ }
122
129
  },
123
130
  Err(msg) => {
124
131
  errors.push(CheckError::at(
compiler/checker/src/unification.rs CHANGED
@@ -132,7 +132,7 @@ pub(crate) fn bindMatch(pattern: &PlumType, actual: &PlumType, b: &mut Binds) {
132
132
  if let Some((name, args)) = traits.traitObject(actual) {
133
133
  if let Some(e) = traits.entriesOf(pattern).into_iter().find(|e| e.trait_name == name) {
134
134
  for (p, a) in e.args.iter().zip(args) {
135
- bindMatch(p, a, b);
135
+ bindOpenArg(p, a, b);
136
136
  }
137
137
  }
138
138
  }
@@ -147,6 +147,31 @@ pub(crate) fn bindMatch(pattern: &PlumType, actual: &PlumType, b: &mut Binds) {
147
147
  }
148
148
  }
149
149
 
150
+ /// `bindMatch` of an implementer's own argument `p` from its trait object's `a`, where `a`
151
+ /// may itself still be open: `Holder.of(Box(id: 1))`, with `of(top: Thing[M])`, gives
152
+ /// `Box[_t1]` against `Thing[_t2]` before anything fixes `_t2`. The implementer's variable
153
+ /// is then bound to the trait's, so it resolves to whatever later fixes `_t2` (`h:
154
+ /// Holder[Int] := ..`) instead of defaulting to `Unit`, a type the trait object's
155
+ /// dispatch has no arm for.
156
+ fn bindOpenArg(p: &PlumType, a: &PlumType, b: &mut Binds) {
157
+ use PlumType::*;
158
+ match (p, a) {
159
+ (TVar(n), TVar(m)) if isInferVar(n) && isInferVar(m) => {
160
+ if b.contains_key(n) {
161
+ return;
162
+ }
163
+ // No cycle: `a` must not already resolve to `p`.
164
+ let seen = resolveRecorded(&substVars(a, b));
165
+ if matches!(&seen, TVar(x) if x == n) {
166
+ return;
167
+ }
168
+ b.insert(n.clone(), a.clone());
169
+ recordBind(n, a);
170
+ }
171
+ _ => bindMatch(p, a, b),
172
+ }
173
+ }
174
+
150
175
  pub fn unify(t1: &PlumType, t2: &PlumType, ctx: &CheckCtx) -> Result<(), String> {
151
176
  match (t1, t2) {
152
177
  (PlumType::TVar(_), _) | (_, PlumType::TVar(_)) => Ok(()),
compiler/wasm-codegen/src/matching.rs CHANGED
@@ -34,6 +34,11 @@ pub(crate) fn exprHasResult(expr: &ast::Expr, ctx: &LocalCtx) -> bool {
34
34
  return !s.ret.is_empty();
35
35
  }
36
36
  let obj_ty = inferLocalType(&attr.object, ctx);
37
+ // A call on a trait object: its dispatcher's result (a Unit method like
38
+ // `a.paint(..)` leaves nothing to drop).
39
+ if let Some(Ok((_, s))) = dispatcherFor(&obj_ty, &call.name) {
40
+ return !s.ret.is_empty();
41
+ }
37
42
  // `methodReceiverName` (not a bare `TNamed` match) so this also
38
43
  // covers a Unit-returning method called in statement position on
39
44
  // a BUILTIN primitive receiver (`Int`/`Float`/`Bool`/`Str`/`Byte`/
docs/backlog.md CHANGED
@@ -27,6 +27,8 @@ Open work, in the order the user queued it, plus smaller items found during buil
27
27
 
28
28
  ## Planned, not yet placed in the queue
29
29
 
30
+ - **Generics in `<>`, traits in `[]`** (user 2026-11-09, later): `struct Ship<M>[Actor<M>, Clickable](x: Float, y: Float)`, `fun map<B>(..) -> Option<B>`, `Slice<Jv>()`, `stage.updateAs<Orb>(id, f)`; replaces `[]` generics and the `is` clause. In expressions `<` is also less-than: parse `name<...>` as type arguments only when the matching `>` is directly followed by `(`, `.` or `)` (C#/Kotlin rule; `a < B > (c)` would compare a Bool), and split `>>` in nested types. Mechanical but touches every generic in std, examples, tests, docs, the parser, tree-sitter and type-printing snapshots; do it as one task. An intermediate option discussed: `struct Ship(Actor, Clickable)(x: Float, y: Float)` with `[]` generics kept.
31
+ - **Optional or automatic actor keys** (user 2026-11-09, after the actor-trait plan). Store does not replace `key`: the Store holds game state, while `key` names one actor in the tree for `Kill(id)`, `updateAs[T](id, f)`, `findAs[T](id)` and messages like `Collected(id)`. Most actors don't need one: self-removal uses `gone`, messages can carry data (`Collected(points: 10)`), and singletons can be found by type (`findAs[Player]()`). Options: (a) make `key` a default method `fun key(self) -> Option[Int] = None`, overridden only by actors a rule must pick out; (b) have the tree hand out ids itself: a counter in `SceneTree`, the id stored in the tree node next to the actor (not in the actor), given on `Spawn`, and returned by queries such as `findAll[Orb]() -> List[Pair[Int, Orb]]`. Use a counter, not a random id: it is unique, needs no `Random` and keeps replays deterministic. Not an index or path in the tree, which changes after a kill. Open: how a spawner learns its child's id (maybe `Spawn(actor, onId: fn(Int) -> M)`).
30
32
  - **Testing improvements** (user 2026-11-06, "All 3 please", and "Yes please add group"):
31
33
  - **`group "name"` blocks:** a naming and scope block with one level of nesting. It can hold helper functions and constants visible only inside it, stripped from normal builds. No `setUp` or `tearDown`, and no test classes. After T10 of the simpler language run.
32
34
  - **One test command:** runs every Rust test executable plus the sweep. Comes right after the current fix in the simpler language run.
@@ -75,6 +77,9 @@ Open work, in the order the user queued it, plus smaller items found during buil
75
77
  - **Fields declared inside `init` can't be `mut`** (`self.camX: Float = 0.0`) — such fields were moved into the record header. (T8)
76
78
  - **Benchmark harness can't pass `--no-fusion`** — `compiler/game/web-test` compiles without flags, so fusion-off numbers can't be taken since the env var was removed. (T11)
77
79
  - **`Orb`/`Mine` copy their shared `Node` per frame** in the pure game, because `Node`'s x/y/rotation stay immutable in std. Decide during FBIP. (T10)
80
+ - **A nested spread allocates in a trait step** (actor-trait task 7, 2026-11-09): `Bod(..self, at: self.at.moveTo(x, y))` with `at: Place` allocates a cell per step that FBIP doesn't remove (Ship.step in a probe: one `struct.new` with a nested `Pos` spread), so the scene benchmark's step workload ran 1.7x slower than with `x`/`y` fields and a `place()` that builds the `Place`. Matters for every `Actor` that keeps `at: Place` (orb_run_tree's kinds, task 8's ui widgets).
81
+ - **Struct fields have no defaults** (actor-trait task 6): the plan's `struct Place(x, y, scaleX: Float = 1.0, ..)` doesn't parse; std/game_enum_tree/Place has `place.at(x, y)` and `place.turned(x, y, s, r)` instead.
82
+ - **A generic call's result pinned only by a later parameter** (actor-trait task 6): `firstOf(Holder.of(Box(id: 5)).same())`, with `firstOf(h: Holder[Int])`, still instantiates `Box[Unit]` and fails codegen ("Box[Unit] has no compiled method 'key' for a call on Thing[Unit]"); an annotated local (`h: Holder[Int] := ..`) works. Likewise `EStage.of(Group(..))` with nothing fixing `M` is an `EStage[Unit]`: annotate it.
78
83
  - **Uniqueness precision** — `adv(Cell(..))` inlined into `main` reports "s used after its spread" although `s.x` is only read inside the spread value (a false "not in place"). (T10)
79
84
  - **Pattern-casing hint for union members** — "did you mean Foo?" doesn't cover a lowercase name that spells a union member (lookup lives in `compiler/core/src/unions.rs`). (T1)
80
85
  - **Constant `Anim` trees rebuilt every frame** in `games/functional/game_state_view.plum` (`renderTitle`, Ship render) — hoist them into `State` or constants. (F-T23-1)
docs/std.md CHANGED
@@ -121,7 +121,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
121
121
  - **`FFenwickTree`:** a prefix-sum tree: a segment tree specialised to `Int` sums, keeping only each node's left-half sum (what prefix queries read). The `i & -i` index trick needs an array, so it isn't used.
122
122
  - **`FQuadtree`, `FKdTree`, `FBvh`:** spatial trees over `Vec2` and `Aabb`. Leaf buckets and query results are cons lists. Balanced builds sort with a merge sort on `List` (`FKdTree`) or pick medians with a quickselect (`FBvh`).
123
123
  - **`FUnionFind`:** a persistent parent map (two `FAvlTree`s: parents and set sizes) with union by size and no path compression. `find`, `union` and `connected` are O(log² n). `union` returns the new forest.
124
- - **`FRoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`FRoseEmpty`, `FRoseNode(value, firstChild, nextSibling)`). `FRoseTree.leaf(v)` and `FRoseTree.of(v, kids)` build nodes, `FRoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; `fold`, `each`, `find`, `toList` and `chain` are tail calls along the siblings, while `map`, `filter`, `append` and `replace` recurse once per sibling. `filter`, `replace` and `update` return untouched subtrees as they were. std/game_enum_tree's stage is an `FRoseTree[Actor[K]]`.
124
+ - **`FRoseTree`:** a tree with any number of children per node, in left-child, right-sibling form (`FRoseEmpty`, `FRoseNode(value, firstChild, nextSibling)`). `FRoseTree.leaf(v)` and `FRoseTree.of(v, kids)` build nodes, `FRoseTree.chainOf(ns)` links a `List` of them as siblings. A value is a node with its later siblings; `fold`, `each`, `find`, `toList` and `chain` are tail calls along the siblings, while `map`, `filter`, `append` and `replace` recurse once per sibling. `filter`, `replace` and `update` return untouched subtrees as they were. std/game_enum_tree's stage is an `FRoseTree[Actor[M]]`, a tree of trait objects.
125
125
  - **`FLeftistHeap`, `FPairingHeap`:** priority queues with `fold` in place of an iterator. The pairing heap's two-pass `pop` is tail recursive, so a root with 100,000 children is fine.
126
126
 
127
127
  ## Option and Result
std/collections/functional/FRoseTree.plum CHANGED
@@ -35,7 +35,7 @@ import std/List
35
35
  # siblings (their values and subtrees are shared), O(children); `appendAll` adds a batch
36
36
  # for the cost of one.
37
37
  #
38
- # Nodes are referred to by what is in them (std/game_enum_tree's `Actor` has an `id`), not
38
+ # Nodes are referred to by what is in them (std/game_enum_tree's actors have a `key()`), not
39
39
  # by the node itself: after an update the old node is a different, older value.
40
40
  enum FRoseTree[T] =
41
41
  | FRoseEmpty
std/game_enum_tree/Actor.plum CHANGED
@@ -3,138 +3,73 @@ module std
3
3
  import std/Int
4
4
  import std/Float
5
5
  import std/Bool
6
- import std/math
7
6
  import std/Io
8
7
  import std/game/Vec2
9
8
  import std/game/Affine
10
9
  import std/game/Color
11
10
  import std/game/gfx
12
-
11
+ import std/game_enum_tree/Place
12
+ import std/game_enum_tree/ECtx
13
+
13
- # One body of a persistent scene tree (`FRoseTree[Actor[K]]` in an `EStage[K]`): what every
14
+ # One body of a persistent scene tree (`FRoseTree[Actor[M]]` in an `EStage[M]`). Each
14
- # body has, its id, its place in its parent (position, size, origin, scale, rotation), its
15
- # colour and its two flags, plus `kind: K`, the game's own payload. The stage does
16
- # everything these fields describe by itself: it finds bodies by `id`, drops a `dead` one
17
- # with its subtree, skips a hidden one (and its subtree) when it draws and hit tests,
15
+ # kind of body is its own type, with only its own fields, that `is Actor[M]`; `M` is the
18
- # turns the fields into the body's transform (`local`) and multiplies `color.a` down the
19
- # tree as the alpha. It asks the kind only for behaviour, through three methods:
16
+ # game's message type (what `ctx.send` takes). A kind must say which actor it is (`key`,
20
- #
21
- # step(self, a: Actor[K], ctx: ECtx[K], dt: Float) -> Actor[K] # the next actor
22
- # paint(self, a: Actor[K], io: Io, m: Affine, alpha: Float) # m: a's own coords to the stage
23
- # hit(self, a: Actor[K], p: Vec2) -> Bool # p in a's own coordinates
24
- #
25
- # `self` is `a.kind`, so a kind matches on itself and reads the common fields from `a`:
17
+ # the id the stage finds it by) and where it is in its parent (`place`); everything else
26
- #
27
- # enum Kind =
28
- # | Box
29
- # | Walker(speed: Float)
30
- #
31
- # fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
32
- # Walker(speed) => a.moveBy(speed * dt, 0.0)
33
- # Box => a
18
+ # has a default:
34
19
  #
20
+ # step the next version of it, once a tick (`ctx` is its parent's context)
35
- # fun paint(self, a: Actor[Kind], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
21
+ # paint draws it, seen through `m` (its own coordinates to the stage's) at `alpha`
22
+ # (the accumulated alpha, its own `opacity` included)
23
+ # hit whether `p`, in its own coordinates, is on it
24
+ # shown false: it and its subtree are not drawn or hit (but still stepped)
25
+ # gone true: it is dropped with its subtree (returned from `step`, in the same step)
26
+ # opacity its own alpha, multiplied down the tree
36
27
  #
28
+ # struct Walker(id: Int, at: Place, speed: Float) is Actor[Msg] =
29
+ # fun key(self) -> Int = self.id
30
+ # fun place(self) -> Place = self.at
37
- # fun hit(self, a: Actor[Kind], p: Vec2) -> Bool = a.hitBox(p)
31
+ # fun step(self, ctx: ECtx[Msg], dt: Float) -> Walker =
32
+ # Walker(..self, at: self.at.moveBy(self.speed * dt, 0.0))
38
33
  #
39
- # `paintBox` and `hitBox` are the plain behaviour (a filled `width` by `height` box, none
40
- # for a group with no size); std/game_enum_tree/EBox is a kind that has only that, for
41
- # scenes with no behaviour of their own. An actor is a value: a step returns the next one,
34
+ # An actor is a value: a step returns the next one, usually a spread (`Walker(..self,
42
- # made with the copy helpers below or a spread (`Actor(..a, x: 1.0, kind: k)`), which the
43
- # compiler writes in place when nothing else holds the old one.
35
+ # ..)`), which the compiler writes in place when nothing else holds the old one. The two
36
+ # std kinds below, `Group` and `Box`, are generic in `M` so any game's tree takes them.
44
- struct Actor[K](
37
+ trait Actor[M] =
45
- id: Int,
46
- x: Float, y: Float, width: Float, height: Float,
47
- originX: Float, originY: Float,
48
- scaleX: Float, scaleY: Float,
49
- rotation: Float,
50
- color: Color,
51
- visible: Bool,
52
- dead: Bool,
53
- kind: K) =
54
-
55
- # A group at (x, y), unscaled and unrotated: no size, so `paintBox` and `hitBox` do
56
- # nothing for it.
57
- fun group(id: Int, x: Float, y: Float, kind: K) -> Actor[K] =
58
- Actor(
59
- id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
60
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false,
61
- kind: kind)
62
-
63
- # A group at (x, y), scaled by `s` and turned by `r` radians about its own (0, 0).
64
- fun turned(id: Int, x: Float, y: Float, s: Float, r: Float, kind: K) -> Actor[K] =
65
- Actor(
66
- id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
67
- scaleX: s, scaleY: s, rotation: r, color: Color.White, visible: true, dead: false,
68
- kind: kind)
69
-
70
- # A `w` by `h` rectangle with its top-left at (x, y).
71
- fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color, kind: K) -> Actor[K] =
72
- Actor(
73
- id: id, x: x, y: y, width: w, height: h, originX: 0.0, originY: 0.0,
74
- scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: c, visible: true, dead: false,
75
- kind: kind)
76
-
77
- # Whether this actor and its subtree are drawn and hit: visible and not dead.
78
- fun shown(self) -> Bool = self.visible && !self.dead
79
-
80
- # Its own alpha, multiplied down the tree.
81
- fun opacity(self) -> Float = self.color.a
82
-
83
- # The transform into the parent's coordinates: translate to the position, rotate and
84
- # scale about the origin.
85
- fun local(self) -> Affine =
38
+ fun key(self) -> Int
86
- localOf(self.x, self.y, self.originX, self.originY, self.scaleX, self.scaleY, self.rotation)
87
39
 
88
- # Whether `p`, a point in this actor's own coordinates, is inside its width by height
89
- # box; a group with no size is never hit.
40
+ fun place(self) -> Place
90
- fun hitBox(self, p: Vec2) -> Bool = boxHit(self.width, self.height, p)
91
41
 
92
- # Its width by height box at (0, 0), seen through `m`, in its colour at `alpha` (the
93
- # accumulated alpha, which already includes its own `color.a`). Nothing for a group.
94
- fun paintBox(self, io: Io, m: Affine, alpha: Float) =
42
+ fun step(self, ctx: ECtx[M], dt: Float) -> Self = self
95
- if self.width > 0.0 && self.height > 0.0
96
- boxPaint(io, m, alpha, self.width, self.height, self.color.withAlpha(1.0))
97
43
 
98
- # Copies with one thing changed.
44
+ fun paint(self, io: Io, m: Affine, alpha: Float) = Unit
99
45
 
100
- fun at(self, x: Float, y: Float) -> Actor[K] = Actor(..self, x: x, y: y)
46
+ fun hit(self, p: Vec2) -> Bool = false
101
47
 
102
- fun moveBy(self, dx: Float, dy: Float) -> Actor[K] = Actor(..self, x: self.x + dx, y: self.y + dy)
48
+ fun shown(self) -> Bool = true
103
49
 
104
- fun rotateTo(self, r: Float) -> Actor[K] = Actor(..self, rotation: r)
50
+ fun gone(self) -> Bool = false
105
51
 
106
- fun scaleTo(self, sx: Float, sy: Float) -> Actor[K] = Actor(..self, scaleX: sx, scaleY: sy)
52
+ fun opacity(self) -> Float = 1.0
107
53
 
108
- fun resize(self, w: Float, h: Float) -> Actor[K] = Actor(..self, width: w, height: h)
54
+ # An actor that paints nothing and is never hit: a parent for others (a layer, a camera).
55
+ struct Group[M](id: Int, at: Place) is Actor[M] =
56
+ fun key(self) -> Int = self.id
109
57
 
110
- # Its rotation and scale about (ox, oy), in its own coordinates.
111
- fun pivotAt(self, ox: Float, oy: Float) -> Actor[K] = Actor(..self, originX: ox, originY: oy)
58
+ fun place(self) -> Place = self.at
112
59
 
60
+ # A filled `w` by `h` box in `color`, with its top-left at its place's (0, 0); hit inside
61
+ # it. Its opacity is its colour's alpha.
62
+ struct Box[M](id: Int, at: Place, w: Float, h: Float, color: Color) is Actor[M] =
113
- fun tint(self, c: Color) -> Actor[K] = Actor(..self, color: c)
63
+ fun key(self) -> Int = self.id
114
64
 
115
- # Its colour with the alpha `a`: its opacity, and its subtree's.
116
- fun fade(self, a: Float) -> Actor[K] = Actor(..self, color: self.color.withAlpha(a))
65
+ fun place(self) -> Place = self.at
117
66
 
118
- fun withVisible(self, v: Bool) -> Actor[K] = Actor(..self, visible: v)
119
-
120
- # Dead: returned from `step`, its parent drops it with its subtree.
121
- fun killed(self) -> Actor[K] = Actor(..self, dead: true)
67
+ fun opacity(self) -> Float = self.color.a
122
68
 
123
- fun withKind(self, k: K) -> Actor[K] = Actor(..self, kind: k)
69
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
70
+ boxPaint(io, m, alpha, self.w, self.h, self.color.withAlpha(1.0))
124
71
 
125
- # The transform of a body at (x, y) with its origin, scale and rotation (master's
126
- # `Actor.local`): translate to the position, rotate and scale about the origin.
72
+ fun hit(self, p: Vec2) -> Bool = boxHit(self.w, self.h, p)
127
- fun localOf(x: Float, y: Float, originX: Float, originY: Float, scaleX: Float, scaleY: Float, rotation: Float) -> Affine =
128
- cs := math.cos(rotation)
129
- sn := math.sin(rotation)
130
- a := cs * scaleX
131
- b := sn * scaleX
132
- c := 0.0 - sn * scaleY
133
- d := cs * scaleY
134
- Affine(
135
- a: a, b: b, c: c, d: d,
136
- e: x + originX - {a * originX + c * originY},
137
- f: y + originY - {b * originX + d * originY})
138
73
 
139
74
  # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
140
75
  fun boxHit(w: Float, h: Float, p: Vec2) -> Bool =
@@ -147,21 +82,20 @@ fun boxPaint(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
147
82
  p := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
148
83
  gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
149
84
 
150
- test "a rect actor is its size and hides when it is dead"
85
+ test "a box is hit inside its size, a group never"
151
- r := Actor.rect(7, 1.0, 2.0, 4.0, 3.0, Color.Red, 0)
86
+ b: Actor[Int] := Box(id: 7, at: place.at(1.0, 2.0), w: 4.0, h: 3.0, color: Color.Red.withAlpha(0.25))
152
- assert r.width == 4.0 && r.height == 3.0 && r.id == 7
153
- assert r.shown()
154
- assert !r.killed().shown()
87
+ assert b.key() == 7
155
- assert !r.withVisible(false).shown()
156
- assert r.moveBy(1.0, 2.0).x == 2.0
88
+ assert b.place().x == 1.0
157
- assert r.hitBox(Vec2(x: 2.0, y: 1.0))
89
+ assert b.hit(Vec2(x: 2.0, y: 1.0))
158
- assert !Actor.group(1, 0.0, 0.0, 0).hitBox(Vec2(x: 0.0, y: 0.0))
90
+ assert !b.hit(Vec2(x: 5.0, y: 1.0))
159
- assert r.fade(0.25).opacity() == 0.25
91
+ assert b.opacity() == 0.25
160
- assert r.withKind(5).kind == 5 && r.kind == 0
161
-
162
- test "local translates, then turns and scales about the origin"
163
- b := Actor.turned(1, 10.0, 20.0, 2.0, 0.0, 0).pivotAt(1.0, 1.0)
164
- p := b.local().apply(Vec2(x: 1.0, y: 1.0))
165
- assert p.x == 11.0 && p.y == 21.0
92
+ assert b.shown() && !b.gone()
93
+ g: Actor[Int] := Group(id: 1, at: place.at(0.0, 0.0))
166
- q := b.local().apply(Vec2(x: 2.0, y: 1.0))
94
+ assert !g.hit(Vec2(x: 0.0, y: 0.0))
95
+ assert g.opacity() == 1.0
96
+ assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
97
+
98
+ test "the default step returns the actor as it was"
99
+ b: Actor[Int] := Box(id: 3, at: place.at(1.0, 1.0), w: 4.0, h: 2.0, color: Color.Blue)
100
+ assert b.step(ECtx[Int](), 1.0) == b
167
- assert q.x == 13.0 && q.y == 21.0
101
+ assert b.step(ECtx[Int](), 1.0).place().x == 1.0
std/game_enum_tree/EBox.plum DELETED
@@ -1,42 +0,0 @@
1
- module std
2
-
3
- import std/Int
4
- import std/Float
5
- import std/Bool
6
- import std/Io
7
- import std/game/Vec2
8
- import std/game/Affine
9
- import std/game/Color
10
- import std/game_enum_tree/Actor
11
- import std/game_enum_tree/ECtx
12
-
13
- # The plain kind: an actor with no behaviour of its own. One with a size paints a filled
14
- # rectangle in its colour and is hit inside it; one without (a group) paints nothing and is
15
- # never hit. A scene with no behaviour is an `EStage[EBox]`:
16
- #
17
- # s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
18
- struct EBox() =
19
-
20
- # A group of plain actors at (x, y).
21
- fun group(id: Int, x: Float, y: Float) -> Actor[EBox] = Actor.group(id, x, y, EBox())
22
-
23
- # A plain group at (x, y), scaled by `s` and turned by `r` radians about its (0, 0).
24
- fun turned(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[EBox] = Actor.turned(id, x, y, s, r, EBox())
25
-
26
- # A plain `w` by `h` rectangle with its top-left at (x, y).
27
- fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color) -> Actor[EBox] = Actor.rect(id, x, y, w, h, c, EBox())
28
-
29
- # A plain actor doesn't change.
30
- fun step(self, a: Actor[EBox], ctx: ECtx[EBox], dt: Float) -> Actor[EBox] = a
31
-
32
- fun paint(self, a: Actor[EBox], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
33
-
34
- fun hit(self, a: Actor[EBox], p: Vec2) -> Bool = a.hitBox(p)
35
-
36
- test "a plain box steps to itself and is hit inside its size"
37
- r := EBox.rect(3, 1.0, 1.0, 4.0, 2.0, Color.Blue)
38
- assert r.kind.step(r, ECtx[EBox](), 1.0).x == 1.0
39
- assert r.kind.hit(r, Vec2(x: 3.0, y: 1.0))
40
- assert !r.kind.hit(r, Vec2(x: 5.0, y: 1.0))
41
- g := EBox.group(4, 0.0, 0.0)
42
- assert !g.kind.hit(g, Vec2(x: 0.0, y: 0.0))
std/game_enum_tree/ECtx.plum CHANGED
@@ -2,41 +2,42 @@ module std
2
2
 
3
3
  import std/Int
4
4
  import std/Float
5
+ import std/Str
6
+ import std/List
5
7
  import std/Slice
6
8
  import std/game/Affine
7
9
  import std/collections/functional/FRoseTree
8
10
  import std/game_enum_tree/Actor
9
11
 
10
- # What a step changes besides the actors, applied once the step's walk is over
12
+ # What a step changes besides the actors. `ESpawn` and `EKill` are applied once the
11
- # (`EStage.apply`): a new node under the actor `parent` (by id), on top of its children,
13
+ # step's walk is over (`EStage.apply`): a new node under the actor `parent` (by id), on
12
- # or the end of the actor `id` and its subtree. `K` is the stage's kind.
14
+ # top of its children, or the end of the actor `id` and its subtree. `ESend` is a message
15
+ # of the game's type `M` for the game's store: the stage leaves it in `ctx.out`, in order,
16
+ # for the game to take (`ctx.takeSends()`).
13
- enum ECmd[K] =
17
+ enum ECmd[M] =
14
- | ESpawn(parent: Int, node: FRoseTree[Actor[K]])
18
+ | ESpawn(parent: Int, node: FRoseTree[Actor[M]])
15
19
  | EKill(id: Int)
20
+ | ESend(msg: M)
16
21
 
17
- # What the step hands each actor's kind in place of a parent link: the context of the
22
+ # What the step hands each actor in place of a parent link: the context of the actor's
18
- # actor's parent. `up` is the parent's world transform and `alpha` its accumulated
23
+ # parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so an
19
- # opacity, so an actor's own world transform is `ctx.worldOf(a.local())` and its alpha
24
+ # actor's own world transform is `ctx.worldOf(self.place().local())` and its alpha
20
- # `ctx.alphaOf(a.opacity())`, computed only when it asks. `out` takes the commands a kind
25
+ # `ctx.alphaOf(self.opacity())`, computed only when it asks. `out` takes the commands an
21
- # pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`).
26
+ # actor pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`,
27
+ # `ctx.send(msg)`).
22
28
  #
23
- # fun step(self, a: Actor[Kind], ctx: ECtx[Kind], dt: Float) -> Actor[Kind] = match self
29
+ # fun step(self, ctx: ECtx[Msg], dt: Float) -> Gun =
24
- # Gun(rate) =>
25
- # ctx.out.push(ESpawn(parent: 0, node: FRoseTree.leaf(Actor.group(id, a.x, a.y, Bullet))))
30
+ # ctx.out.push(ESpawn(parent: 0, node: FRoseTree.leaf(Bullet(id: self.next, at: self.at))))
26
- # a
31
+ # Gun(..self, next: self.next + 1)
27
- # ..
28
32
  #
29
33
  # A context is a value. The walk makes one for each parent with children (`under`), with
30
34
  # one multiply, and hands it to every child: the lazy world transform of master's `ECtx`
31
35
  # without the cached field and the `retarget` that master needs to reuse one context.
32
- #
33
- # Master's context also carries the game's dispatcher (`actions`); the branch's game
34
- # library has none, so this one doesn't.
35
- struct ECtx[K](up: Affine, alpha: Float, out: Slice[ECmd[K]]) =
36
+ struct ECtx[M](up: Affine, alpha: Float, out: Slice[ECmd[M]]) =
36
37
 
37
38
  # The context above a stage's root: the identity transform, full opacity, no commands.
38
- fun init() -> ECtx[K] =
39
+ fun init() -> ECtx[M] =
39
- ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[K]]())
40
+ ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[M]]())
40
41
 
41
42
  # The world transform of a child whose own transform is `local`.
42
43
  fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
@@ -46,9 +47,44 @@ struct ECtx[K](up: Affine, alpha: Float, out: Slice[ECmd[K]]) =
46
47
 
47
48
  # The context for the children of a child with the transform `local` and opacity `a`:
48
49
  # the same commands, the child's world transform above them.
49
- fun under(self, local: Affine, a: Float) -> ECtx[K] =
50
+ fun under(self, local: Affine, a: Float) -> ECtx[M] =
50
51
  ECtx(up: self.up.mul(local), alpha: self.alpha * a, out: self.out)
51
52
 
53
+ # Sends `msg` to the game's store after the step.
54
+ fun send(self, msg: M) = self.out.push(ESend(msg: msg))
55
+
56
+ # The messages sent so far, oldest first, taken out of `out` (its other commands stay,
57
+ # in order).
58
+ fun takeSends(self) -> List[M] =
59
+ if self.out.length() == 0
60
+ Nil
61
+ else
62
+ msgs := ecmdSends(self.out, self.out.length() - 1, Nil)
63
+ ecmdKeepOnly(self.out, false)
64
+ msgs
65
+
66
+ # The messages of `cmds` up to index `i`, oldest first, in front of `acc`.
67
+ fun ecmdSends[M](cmds: Slice[ECmd[M]], i: Int, acc: List[M]) -> List[M] =
68
+ if i < 0
69
+ acc
70
+ else
71
+ match cmds.at(i)
72
+ ESend(m) => ecmdSends(cmds, i - 1, Cons(m, acc))
73
+ _ => ecmdSends(cmds, i - 1, acc)
74
+
75
+ # Keeps in `cmds` only its sends (`sends` true) or only its other commands, in order.
76
+ fun ecmdKeepOnly[M](cmds: Slice[ECmd[M]], sends: Bool) =
77
+ kept := Slice[ECmd[M]]()
78
+ for c := range cmds
79
+ if ecmdIsSend(c) == sends
80
+ kept.push(c)
81
+ cmds.clear()
82
+ cmds.add(kept)
83
+
84
+ fun ecmdIsSend[M](c: ECmd[M]) -> Bool = match c
85
+ ESend(_) => true
86
+ _ => false
87
+
52
88
  test "under multiplies the child's transform into the parent's"
53
89
  c := ECtx[Int]()
54
90
  m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
@@ -58,3 +94,15 @@ test "under multiplies the child's transform into the parent's"
58
94
  assert u.worldOf(m).e == 7.0
59
95
  u.out.push(EKill(id: 3))
60
96
  assert c.out.length() == 1
97
+
98
+ test "sends are taken out in order and the other commands stay"
99
+ c := ECtx[Str]()
100
+ c.send("a")
101
+ c.out.push(EKill(id: 3))
102
+ c.under(Affine.Identity, 1.0).send("b")
103
+ c.out.push(EKill(id: 4))
104
+ msgs := c.takeSends()
105
+ assert msgs.length() == 2 && msgs.get(0).unwrap() == "a" && msgs.get(1).unwrap() == "b"
106
+ assert c.out.length() == 2
107
+ assert c.takeSends().isEmpty()
108
+ assert c.out.length() == 2
std/game_enum_tree/EStage.plum CHANGED
@@ -18,28 +18,31 @@ import std/game/Color
18
18
  import std/game/gfx
19
19
  import std/collections/functional/FRoseTree
20
20
  import std/game_enum_tree/Actor
21
- import std/game_enum_tree/EBox
21
+ import std/game_enum_tree/Place
22
22
  import std/game_enum_tree/ECtx
23
23
 
24
- # A persistent scene tree: master's std/game_enum_tree `EStage`, over actors of the kind
24
+ # A persistent scene tree: master's std/game_enum_tree `EStage`, over actors of any kind
25
- # `K` (see std/game_enum_tree/Actor). The root is an `FRoseTree[Actor[K]]`, a left-child,
25
+ # that `is Actor[M]` (see std/game_enum_tree/Actor), `M` being the game's message type.
26
+ # The root is an `FRoseTree[Actor[M]]`, a left-child, right-sibling tree of actors, and a
26
- # right-sibling tree of actors, and a stage is a value: every change returns a new stage.
27
+ # stage is a value: every change returns a new stage. While something holds the old stage
27
- # While something holds the old stage it stays as it was, a snapshot; when nothing does,
28
+ # it stays as it was, a snapshot; when nothing does, the compiler reuses its cells for the
28
- # the compiler reuses its cells for the new one.
29
+ # new one.
29
30
  #
30
- # s := EStage.of(EBox.group(0, 0.0, 0.0)) # a root group, id 0
31
+ # s := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))) # a root group, id 0
31
- # s2 := s.add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
32
+ # s2 := s.add(0, FRoseTree.leaf(Box(id: 1, at: place.at(10.0, 5.0), w: 40.0, h: 20.0, color: Color.Red)))
32
- # ctx := ECtx[EBox]()
33
+ # ctx := ECtx[Msg]()
33
34
  # s3 := s2.step(ctx, dt) # every actor's next version, then the commands in ctx.out
34
35
  # s3.draw(io)
35
36
  #
36
- # The stage handles what every actor has: it finds actors by `id` (`add(parent, n)`,
37
+ # The stage uses only what the trait gives: it finds actors by `key()` (`add(parent, n)`,
37
38
  # `update(id, f)`, `find(id)`, `kill(id)`, `ESpawn(parent, n)`, `EKill(id)`, each by a
38
39
  # search down from the root, O(n); `step` applies all of a tick's commands in its own
39
- # walk), drops a `dead` actor with its subtree, skips a hidden one with its subtree when it
40
+ # walk), drops a `gone()` actor with its subtree, skips one that is not `shown()` (or is
40
- # draws and hit tests, and multiplies the transforms (`Actor.local`) and alphas
41
+ # gone) with its subtree when it draws and hit tests, and multiplies the transforms
42
+ # (`place().local()`) and alphas (`opacity()`) down the tree. Each actor's own type gives
43
+ # the behaviour: `step`, `paint` and `hit`. The stage never needs an actor's own type;
41
- # (`color.a`) down the tree. The kind `K` gives the behaviour: `a.kind.step(a, ctx, dt)`,
44
+ # game code that does uses `updateAs[T]` and `findAs[T]`, which act only on an actor of
42
- # `a.kind.paint(a, io, m, alpha)` and `a.kind.hit(a, p)`.
45
+ # the type `T`.
43
46
  #
44
47
  # Children are kept in draw order: a parent is drawn before its children, and siblings
45
48
  # first to last. Hit testing goes the other way, topmost first: children before their
@@ -50,84 +53,100 @@ import std/game_enum_tree/ECtx
50
53
  # and that use would stop the compiler from writing the new node into the old one's cell.
51
54
  # A step over a stage nothing else holds therefore allocates no link nodes at all, and
52
55
  # one over a kept stage copies all of them.
53
- struct EStage[K](root: FRoseTree[Actor[K]], camX: Float, camY: Float, camScale: Float) =
56
+ struct EStage[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScale: Float) =
54
57
 
55
58
  # A stage whose root is the actor `top`.
56
- fun of(top: Actor[K]) -> EStage[K] =
59
+ fun of(top: Actor[M]) -> EStage[M] =
57
60
  EStage(root: FRoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
58
61
 
59
62
  # The same camera over another tree.
60
- fun withRoot(self, r: FRoseTree[Actor[K]]) -> EStage[K] = EStage(..self, root: r)
63
+ fun withRoot(self, r: FRoseTree[Actor[M]]) -> EStage[M] = EStage(..self, root: r)
61
64
 
62
- fun pan(self, x: Float, y: Float) -> EStage[K] = EStage(..self, camX: x, camY: y)
65
+ fun pan(self, x: Float, y: Float) -> EStage[M] = EStage(..self, camX: x, camY: y)
63
66
 
64
- fun zoom(self, s: Float) -> EStage[K] = EStage(..self, camScale: s)
67
+ fun zoom(self, s: Float) -> EStage[M] = EStage(..self, camScale: s)
65
68
 
66
69
  # The number of actors.
67
70
  fun count(self) -> Int = self.root.count()
68
71
 
69
72
  # The actor with this id, if any.
70
- fun find(self, id: Int) -> Option[Actor[K]] = self.root.find(|a| a.id == id)
73
+ fun find(self, id: Int) -> Option[Actor[M]] = self.root.find(|a| a.key() == id)
74
+
75
+ # The actor with this id as its own type `T`, if there is one and it is a `T`:
76
+ # `stage.findAs[Ship](ShipId)`.
77
+ fun findAs[T](self, id: Int) -> Option[T] = match self.find(id)
78
+ Some(T as t) => Some(t)
79
+ _ => None
71
80
 
72
81
  # The stage with `n` added as the last child of the actor `parent`; unchanged if there
73
82
  # is no such actor.
74
- fun add(self, parent: Int, n: FRoseTree[Actor[K]]) -> EStage[K] =
83
+ fun add(self, parent: Int, n: FRoseTree[Actor[M]]) -> EStage[M] =
75
- self.withRoot(self.root.replace(|a| a.id == parent, |p| p.addChild(n)))
84
+ self.withRoot(self.root.replace(|a| a.key() == parent, |p| p.addChild(n)))
76
85
 
77
86
  # The stage with the actor `id` replaced by `f(actor)`; everything off its path is
78
87
  # shared.
79
- fun update(self, id: Int, f: fn(Actor[K]) -> Actor[K]) -> EStage[K] =
88
+ fun update(self, id: Int, f: fn(Actor[M]) -> Actor[M]) -> EStage[M] =
80
- self.withRoot(self.root.update(|a| a.id == id, f))
89
+ self.withRoot(self.root.update(|a| a.key() == id, f))
81
-
90
+
82
- # The stage with the kind of the actor `id` replaced by `f(kind)`.
91
+ # The stage with the actor `id` replaced by `f(actor)` if it is a `T`, and unchanged if
92
+ # it is not: `stage.updateAs[Orb](id, |o| Orb(..o, vx: 0.0))`.
83
- fun updateKind(self, id: Int, f: fn(K) -> K) -> EStage[K] =
93
+ fun updateAs[T](self, id: Int, f: fn(T) -> T) -> EStage[M] =
84
- self.withRoot(self.root.update(|a| a.id == id, |a| a.withKind(f(a.kind))))
94
+ self.withRoot(self.root.update(|a| a.key() == id, |a| match a
95
+ T as t =>
96
+ b: Actor[M] := f(t)
97
+ b
98
+ _ => a))
85
99
 
86
100
  # The stage without the actor `id` and its subtree.
87
- fun kill(self, id: Int) -> EStage[K] = self.withRoot(self.root.filter(|a| a.id != id))
101
+ fun kill(self, id: Int) -> EStage[M] = self.withRoot(self.root.filter(|a| a.key() != id))
88
102
 
89
- # The next tick: every live actor's `a.kind.step(a, ..)`, parents before children,
103
+ # The next tick: every live actor's `step`, parents before children, siblings in
90
- # siblings in order, each given its parent's context under `ctx` (the context above the
104
+ # order, each given its parent's context under `ctx` (the context above the root). An
91
- # root). An actor whose step returns it dead is dropped with its subtree. Every command in `ctx.out` takes
105
+ # actor whose step returns it gone is dropped with its subtree. Every `ESpawn` and
92
- # effect after the step, as `apply` would apply it, and `ctx.out` is left empty. Those
106
+ # `EKill` in `ctx.out` takes effect after the step, as `apply` would apply it. Those
93
107
  # pushed before the step are applied in its own walk: an actor killed this way is
94
108
  # dropped without its step, and a spawned node goes on top of its parent's children
95
- # unstepped. Those pushed during the step (by the kinds) are applied by `apply` once
109
+ # unstepped. Those pushed during the step (by the actors) are applied by `apply` once
96
- # the walk is over, as a second batch. Hidden actors are stepped too.
110
+ # the walk is over, as a second batch. Hidden actors are stepped too. `ctx.out` is left
111
+ # with only the `ESend`s, those pushed before the step first, in order, for the game to
112
+ # take (`ctx.takeSends()`).
97
- fun step(self, ctx: ECtx[K], dt: Float) -> EStage[K] =
113
+ fun step(self, ctx: ECtx[M], dt: Float) -> EStage[M] =
98
114
  w := EWalk.of(ctx.out)
99
- ctx.out.clear()
115
+ ectx.ecmdKeepOnly(ctx.out, true)
100
- empty: FRoseTree[Actor[K]] := FRoseEmpty
116
+ empty: FRoseTree[Actor[M]] := FRoseEmpty
101
117
  r := estep(self.root, ctx, dt, w, empty)
102
118
  s := EStage(..self, root: r).apply(ctx.out)
103
- ctx.out.clear()
119
+ ectx.ecmdKeepOnly(ctx.out, true)
104
120
  s
105
121
 
106
122
  # The stage with the commands applied, in one pass over the tree: every `EKill` actor
107
123
  # goes with its subtree, and every `ESpawn` node goes on top of its parent's children,
108
124
  # in the order pushed. A spawn whose parent is not on the stage, or is killed by the
109
- # same batch, is dropped.
125
+ # same batch, is dropped. `ESend`s are not the stage's, and are skipped.
110
- fun apply(self, cmds: Slice[ECmd[K]]) -> EStage[K] =
126
+ fun apply(self, cmds: Slice[ECmd[M]]) -> EStage[M] =
111
127
  if cmds.length() == 0
112
128
  self
113
129
  else
114
130
  w := EWalk.of(cmds)
131
+ if !w.hasKills && !w.hasSpawns
132
+ self
133
+ else
115
- empty: FRoseTree[Actor[K]] := FRoseEmpty
134
+ empty: FRoseTree[Actor[M]] := FRoseEmpty
116
- EStage(..self, root: eapply(self.root, w, empty))
135
+ EStage(..self, root: eapply(self.root, w, empty))
117
136
 
118
137
  # What `draw` would draw, in order: each shown actor with its stage transform and alpha,
119
138
  # a parent before its children, siblings first to last.
120
- fun flatten(self) -> Slice[EDrawn[K]] =
139
+ fun flatten(self) -> Slice[EDrawn[M]] =
121
- out := Slice[EDrawn[K]]()
140
+ out := Slice[EDrawn[M]]()
122
141
  ecollect(self.root, Affine.Identity, 1.0, out)
123
142
  out
124
143
 
125
- # The topmost shown actor at a stage point whose kind says it is hit there
144
+ # The topmost shown actor at a stage point that says it is hit there (`hit(p)`, with
126
- # (`a.kind.hit(a, p)`, with `p` in the actor's own coordinates).
145
+ # `p` in the actor's own coordinates).
127
- fun hit(self, x: Float, y: Float) -> Option[Actor[K]] = ehit(self.root, Vec2(x: x, y: y))
146
+ fun hit(self, x: Float, y: Float) -> Option[Actor[M]] = ehit(self.root, Vec2(x: x, y: y))
128
147
 
129
148
  # The id of that actor, if any.
130
- fun hitId(self, x: Float, y: Float) -> Option[Int] = self.hit(x, y).map(|a| a.id)
149
+ fun hitId(self, x: Float, y: Float) -> Option[Int] = self.hit(x, y).map(|a| a.key())
131
150
 
132
151
  fun draw(self, io: Io) =
133
152
  gfx.setCamera(io, self.camX, self.camY, self.camScale)
@@ -135,7 +154,7 @@ struct EStage[K](root: FRoseTree[Actor[K]], camX: Float, camY: Float, camScale:
135
154
  gfx.resetCamera(io)
136
155
 
137
156
  # One entry of the draw list: a shown actor, its stage transform and its alpha.
138
- struct EDrawn[K](actor: Actor[K], m: Affine, alpha: Float)
157
+ struct EDrawn[M](actor: Actor[M], m: Affine, alpha: Float)
139
158
 
140
159
  # The largest id range the bitsets cover is [0, 2^22).
141
160
  BitsCap = 4194304
@@ -153,29 +172,30 @@ struct EScan(mut top: Int, mut ok: Bool) =
153
172
  # and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
154
173
  # answers are a shift and a mask, and only an actor with spawns does a hash lookup. Ids
155
174
  # below 0 or from 2^22 up make that batch use the set and the map alone.
156
- struct EWalk[K](
175
+ struct EWalk[M](
157
- kills: Set[Int], spawns: Map[Int, Slice[FRoseTree[Actor[K]]]],
176
+ kills: Set[Int], spawns: Map[Int, Slice[FRoseTree[Actor[M]]]],
158
177
  hasKills: Bool, hasSpawns: Bool,
159
178
  bitsOk: Bool, killBits: Array[Int], spawnBits: Array[Int]) =
160
179
 
161
- fun of(cmds: Slice[ECmd[K]]) -> EWalk[K] =
180
+ fun of(cmds: Slice[ECmd[M]]) -> EWalk[M] =
162
181
  kills := Set[Int]()
163
- spawns: Map[Int, Slice[FRoseTree[Actor[K]]]] := Map.empty()
182
+ spawns: Map[Int, Slice[FRoseTree[Actor[M]]]] := Map.empty()
164
183
  scan := EScan(top: 0, ok: true)
165
184
  for c := range cmds
166
185
  match c
167
186
  EKill(id) =>
168
187
  kills.add(id)
169
188
  scan.see(id)
189
+ ESend(_) => Unit
170
190
  ESpawn(parent, node) =>
171
191
  scan.see(parent)
172
192
  if Some(xs) := spawns.get(parent)
173
193
  xs.push(node)
174
194
  else
175
- ys := Slice[FRoseTree[Actor[K]]]()
195
+ ys := Slice[FRoseTree[Actor[M]]]()
176
196
  ys.push(node)
177
197
  spawns.set(parent, ys)
178
- words := if scan.ok && cmds.length() > 0 then scan.top / 64 + 1 else 0
198
+ words := if scan.ok && {kills.length() > 0 || spawns.length() > 0} then scan.top / 64 + 1 else 0
179
199
  killBits := Array[Int]().resize(words)
180
200
  spawnBits := Array[Int]().resize(words)
181
201
  if words > 0
@@ -183,6 +203,7 @@ struct EWalk[K](
183
203
  match c
184
204
  EKill(id) => ewalkSet(killBits, id)
185
205
  ESpawn(parent, _) => ewalkSet(spawnBits, parent)
206
+ ESend(_) => Unit
186
207
  EWalk(
187
208
  kills: kills, spawns: spawns,
188
209
  hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
@@ -198,7 +219,7 @@ struct EWalk[K](
198
219
  self.kills.has(id)
199
220
 
200
221
  # The nodes to add under the actor `id`, as a chain in the order pushed (empty if none).
201
- fun spawnsUnder(self, id: Int) -> FRoseTree[Actor[K]] =
222
+ fun spawnsUnder(self, id: Int) -> FRoseTree[Actor[M]] =
202
223
  if !self.hasSpawns || {self.bitsOk && !ewalkHas(self.spawnBits, id)}
203
224
  FRoseEmpty
204
225
  else
@@ -226,19 +247,19 @@ fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
226
247
 
227
248
  # The chain `t` one step on, under `ctx` (the context of the chain's parent), without the
228
249
  # actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
229
- # children (or spawns) gets one context for them, made from its transform before its
250
+ # children (or spawns) gets one context for them, made from its place before its step.
230
- # step. Every kept node is rebuilt: in place when nothing else holds `t`.
251
+ # Every kept node is rebuilt: in place when nothing else holds `t`.
231
- fun estep[K](t: FRoseTree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra: FRoseTree[Actor[K]]) -> FRoseTree[Actor[K]] = match t
252
+ fun estep[M](t: FRoseTree[Actor[M]], ctx: ECtx[M], dt: Float, w: EWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
232
253
  FRoseEmpty => extra
233
254
  FRoseNode(a, k, n) =>
234
- if a.dead || {w.hasKills && w.killed(a.id)}
255
+ if a.gone() || {w.hasKills && w.killed(a.key())}
235
256
  estep(n, ctx, dt, w, extra)
236
257
  else
237
- xs := if w.hasSpawns then w.spawnsUnder(a.id) else FRoseEmpty
258
+ xs := if w.hasSpawns then w.spawnsUnder(a.key()) else FRoseEmpty
238
259
  walkKids := !k.isEmpty() || !xs.isEmpty()
239
- cc := if walkKids then ctx.under(a.local(), a.opacity()) else ctx
260
+ cc := if walkKids then ctx.under(a.place().local(), a.opacity()) else ctx
240
- na := a.kind.step(a, ctx, dt)
261
+ na := a.step(ctx, dt)
241
- if na.dead
262
+ if na.gone()
242
263
  estep(n, ctx, dt, w, extra)
243
264
  else
244
265
  k2 := if walkKids then estep(k, cc, dt, w, xs) else k
@@ -246,125 +267,152 @@ fun estep[K](t: FRoseTree[Actor[K]], ctx: ECtx[K], dt: Float, w: EWalk[K], extra
246
267
 
247
268
  # The chain `t` without the actors `w` kills and followed by `extra`, with the same done
248
269
  # in every subtree: `apply`'s walk.
249
- fun eapply[K](t: FRoseTree[Actor[K]], w: EWalk[K], extra: FRoseTree[Actor[K]]) -> FRoseTree[Actor[K]] = match t
270
+ fun eapply[M](t: FRoseTree[Actor[M]], w: EWalk[M], extra: FRoseTree[Actor[M]]) -> FRoseTree[Actor[M]] = match t
250
271
  FRoseEmpty => extra
251
272
  FRoseNode(a, k, n) =>
273
+ id := a.key()
252
- if w.killed(a.id)
274
+ if w.killed(id)
253
275
  eapply(n, w, extra)
254
276
  else
255
- xs := w.spawnsUnder(a.id)
277
+ xs := w.spawnsUnder(id)
256
278
  k2 := if k.isEmpty() && xs.isEmpty() then k else eapply(k, w, xs)
257
279
  FRoseNode(value: a, firstChild: k2, nextSibling: eapply(n, w, extra))
258
280
 
281
+ # Whether the walks that draw and hit test go into `a`: shown, and not gone.
282
+ fun eshown[M](a: Actor[M]) -> Bool = a.shown() && !a.gone()
283
+
259
- fun ecollect[K](t: FRoseTree[Actor[K]], parent: Affine, alpha: Float, out: Slice[EDrawn[K]]) =
284
+ fun ecollect[M](t: FRoseTree[Actor[M]], parent: Affine, alpha: Float, out: Slice[EDrawn[M]]) =
260
285
  if FRoseNode(a, k, n) := t
261
- if a.shown()
286
+ if eshown(a)
262
- m := parent.mul(a.local())
287
+ m := parent.mul(a.place().local())
263
288
  al := alpha * a.opacity()
264
289
  out.push(EDrawn(actor: a, m: m, alpha: al))
265
290
  ecollect(k, m, al, out)
266
291
  ecollect(n, parent, alpha, out)
267
292
 
268
- fun edraw[K](t: FRoseTree[Actor[K]], io: Io, parent: Affine, alpha: Float) =
293
+ fun edraw[M](t: FRoseTree[Actor[M]], io: Io, parent: Affine, alpha: Float) =
269
294
  if FRoseNode(a, k, n) := t
270
- if a.shown()
295
+ if eshown(a)
271
- m := parent.mul(a.local())
296
+ m := parent.mul(a.place().local())
272
297
  al := alpha * a.opacity()
273
- a.kind.paint(a, io, m, al)
298
+ a.paint(io, m, al)
274
299
  edraw(k, io, m, al)
275
300
  edraw(n, io, parent, alpha)
276
301
 
277
- # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that its
302
+ # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that
278
- # kind says is hit: later siblings first, and in each, its children before itself.
303
+ # says it is hit: later siblings first, and in each, its children before itself.
279
- fun ehit[K](t: FRoseTree[Actor[K]], p: Vec2) -> Option[Actor[K]] = match t
304
+ fun ehit[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
280
305
  FRoseEmpty => None
281
306
  FRoseNode(a, k, n) =>
282
307
  match ehit(n, p)
283
308
  Some(found) => Some(found)
284
309
  None =>
285
- if a.shown()
310
+ if eshown(a)
286
- q := a.local().inverse().apply(p)
311
+ q := a.place().local().inverse().apply(p)
287
312
  match ehit(k, q)
288
313
  Some(found) => Some(found)
289
- None => if a.kind.hit(a, q) then Some(a) else None
314
+ None => if a.hit(q) then Some(a) else None
290
315
  else
291
316
  None
292
317
 
293
318
  # --- tests ---
294
319
 
295
- # The kinds for the tests: a plain one, or one of four with behaviour.
296
- enum TKind =
297
- | TPlain
298
- # moves by vx per second; dies when `ttl` runs out (never if it starts at -1)
299
- | TDrifter(vx: Float, ttl: Int)
300
- # spawns a drifter under the root (id 0) each step, with ids from `next` on
301
- | TSpawner(next: Int)
302
- # keeps the world transform and alpha its context gave it in its last step
303
- | TProbe(seen: Affine, seenA: Float)
304
- # pushes `EKill(target)` in each step
305
- | TKiller(target: Int)
306
-
307
- fun step(self, a: Actor[TKind], ctx: ECtx[TKind], dt: Float) -> Actor[TKind] = match self
308
- TPlain => a
309
- TDrifter(vx, ttl) =>
310
- if ttl == 0
311
- a.killed()
312
- else
313
- Actor(..a, x: a.x + vx * dt, kind: TDrifter(vx: vx, ttl: if ttl > 0 then ttl - 1 else ttl))
314
- TSpawner(next) =>
315
- ctx.out.push(ESpawn(parent: 0, node: tdrifter(next, 0.0, 0.0, -1)))
316
- a.withKind(TSpawner(next: next + 1))
317
- TProbe(_, _) => a.withKind(TProbe(seen: ctx.worldOf(a.local()), seenA: ctx.alphaOf(a.opacity())))
318
- TKiller(target) =>
319
- ctx.out.push(EKill(id: target))
320
- a
321
-
322
- fun paint(self, a: Actor[TKind], io: Io, m: Affine, alpha: Float) = a.paintBox(io, m, alpha)
323
-
324
- fun hit(self, a: Actor[TKind], p: Vec2) -> Bool = a.hitBox(p)
325
-
326
- fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> FRoseTree[Actor[TKind]] =
327
- FRoseTree.leaf(Actor.rect(id, x, 0.0, 10.0, 10.0, Color.White, TDrifter(vx: vx, ttl: ttl)))
328
-
329
- fun tspawner(id: Int, next: Int) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.group(id, 0.0, 0.0, TSpawner(next: next)))
330
-
331
- fun tkiller(id: Int, target: Int) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.group(id, 0.0, 0.0, TKiller(target: target)))
332
-
333
- fun tprobe(id: Int, x: Float, y: Float, r: Float) -> Actor[TKind] =
334
- Actor(
335
- id: id, x: x, y: y, width: 1.0, height: 1.0, originX: 2.0, originY: 1.0,
336
- scaleX: 0.5, scaleY: 3.0, rotation: r, color: Color.White.withAlpha(0.5), visible: true, dead: false,
337
- kind: TProbe(seen: Affine.Identity, seenA: 0.0))
338
-
339
- fun trect(id: Int, x: Float, y: Float, w: Float) -> FRoseTree[Actor[TKind]] = FRoseTree.leaf(Actor.rect(id, x, y, w, w, Color.Red, TPlain))
340
-
341
- fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor[TKind] = Actor.turned(id, x, y, s, r, TPlain)
342
-
343
- fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[FRoseTree[Actor[TKind]]]) -> FRoseTree[Actor[TKind]] =
320
+ # The kinds for the tests, in a tree of `Actor[Int]` (the messages are Ints): a plain body,
321
+ # and four with behaviour.
322
+
323
+ # A `w` by `w` box (a group when `w` is 0) with its own alpha and flags.
324
+ struct TBody(id: Int, at: Place, w: Float, alpha: Float, visible: Bool, dead: Bool) is Actor[Int] =
325
+ fun key(self) -> Int = self.id
326
+ fun place(self) -> Place = self.at
327
+ fun opacity(self) -> Float = self.alpha
328
+ fun shown(self) -> Bool = self.visible
329
+ fun gone(self) -> Bool = self.dead
330
+ fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, self.w, self.w, Color.Red)
331
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.w, p)
332
+
333
+ # Moves by vx per second; dies when `ttl` runs out (never if it starts at -1).
334
+ struct TDrifter(id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bool) is Actor[Int] =
335
+ fun key(self) -> Int = self.id
336
+ fun place(self) -> Place = self.at
337
+ fun shown(self) -> Bool = self.visible
338
+ fun gone(self) -> Bool = self.dead
339
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
340
+ fun step(self, ctx: ECtx[Int], dt: Float) -> TDrifter =
341
+ if self.ttl == 0
342
+ TDrifter(..self, dead: true)
343
+ else
344
+ TDrifter(..self, at: self.at.moveBy(self.vx * dt, 0.0), ttl: if self.ttl > 0 then self.ttl - 1 else self.ttl)
345
+
346
+ # Spawns a drifter under the root (id 0) each step, with ids from `next` on, and sends
347
+ # the id it spawned.
348
+ struct TSpawner(id: Int, next: Int) is Actor[Int] =
349
+ fun key(self) -> Int = self.id
350
+ fun place(self) -> Place = place.at(0.0, 0.0)
351
+ fun step(self, ctx: ECtx[Int], dt: Float) -> TSpawner =
352
+ ctx.out.push(ESpawn(parent: 0, node: tdrifter(self.next, 0.0, 0.0, -1)))
353
+ ctx.send(self.next)
354
+ TSpawner(..self, next: self.next + 1)
355
+
356
+ # Keeps the world transform and alpha its context gave it in its last step.
357
+ struct TProbe(id: Int, at: Place, seen: Affine, seenA: Float) is Actor[Int] =
358
+ fun key(self) -> Int = self.id
359
+ fun place(self) -> Place = self.at
360
+ fun opacity(self) -> Float = 0.5
361
+ fun step(self, ctx: ECtx[Int], dt: Float) -> TProbe =
362
+ TProbe(..self, seen: ctx.worldOf(self.at.local()), seenA: ctx.alphaOf(self.opacity()))
363
+
364
+ # Pushes `EKill(target)` in each step.
365
+ struct TKiller(id: Int, target: Int) is Actor[Int] =
366
+ fun key(self) -> Int = self.id
367
+ fun place(self) -> Place = place.at(0.0, 0.0)
368
+ fun step(self, ctx: ECtx[Int], dt: Float) -> TKiller =
369
+ ctx.out.push(EKill(id: self.target))
370
+ self
371
+
372
+ fun tbody(id: Int, x: Float, y: Float, w: Float) -> TBody =
373
+ TBody(id: id, at: place.at(x, y), w: w, alpha: 1.0, visible: true, dead: false)
374
+
375
+ fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> FRoseTree[Actor[Int]] =
376
+ FRoseTree.leaf(TDrifter(id: id, at: place.at(x, 0.0), vx: vx, ttl: ttl, visible: true, dead: false))
377
+
378
+ fun tspawner(id: Int, next: Int) -> FRoseTree[Actor[Int]] = FRoseTree.leaf(TSpawner(id: id, next: next))
379
+
380
+ fun tkiller(id: Int, target: Int) -> FRoseTree[Actor[Int]] = FRoseTree.leaf(TKiller(id: id, target: target))
381
+
382
+ fun tprobe(id: Int, x: Float, y: Float, r: Float) -> TProbe =
383
+ at := Place(x: x, y: y, scaleX: 0.5, scaleY: 3.0, rotation: r, originX: 2.0, originY: 1.0)
384
+ TProbe(id: id, at: at, seen: Affine.Identity, seenA: 0.0)
385
+
386
+ fun trect(id: Int, x: Float, y: Float, w: Float) -> FRoseTree[Actor[Int]] = FRoseTree.leaf(tbody(id, x, y, w))
387
+
388
+ fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> TBody =
389
+ TBody(id: id, at: place.turned(x, y, s, r), w: 0.0, alpha: 1.0, visible: true, dead: false)
390
+
391
+ fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[FRoseTree[Actor[Int]]]) -> FRoseTree[Actor[Int]] =
344
392
  FRoseTree.of(tturned(id, x, y, s, r), kids)
345
393
 
346
- fun tstage() -> EStage[TKind] = EStage.of(Actor.group(0, 0.0, 0.0, TPlain))
394
+ fun tstage() -> EStage[Int] = EStage.of(tbody(0, 0.0, 0.0, 0.0))
347
395
 
348
- fun tids(s: EStage[TKind]) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.id}" else "{acc},{a.id}")
396
+ fun tids(s: EStage[Int]) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.key()}" else "{acc},{a.key()}")
349
397
 
350
- fun tx(s: EStage[TKind], id: Int) -> Float = s.find(id).unwrap().x
398
+ fun tx(s: EStage[Int], id: Int) -> Float = s.find(id).unwrap().place().x
351
399
 
352
400
  fun tnear(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.0001
353
401
 
354
402
  fun tsameM(a: Affine, b: Affine) -> Bool =
355
403
  tnear(a.a, b.a) && tnear(a.b, b.b) && tnear(a.c, b.c) && tnear(a.d, b.d) && tnear(a.e, b.e) && tnear(a.f, b.f)
356
404
 
357
- fun tseen(s: EStage[TKind], id: Int) -> Affine = match s.find(id).unwrap().kind
405
+ fun tseen(s: EStage[Int], id: Int) -> Affine = s.findAs[TProbe](id).unwrap().seen
358
- TProbe(seen, _) => seen
359
- _ => Affine.Identity
360
406
 
361
- fun tseenA(s: EStage[TKind], id: Int) -> Float = match s.find(id).unwrap().kind
407
+ fun tseenA(s: EStage[Int], id: Int) -> Float = s.findAs[TProbe](id).unwrap().seenA
408
+
362
- TProbe(_, a) => a
409
+ fun tfade(s: EStage[Int], id: Int, a: Float) -> EStage[Int] = s.updateAs[TBody](id, |b| TBody(..b, alpha: a))
410
+
363
- _ => 0.0
411
+ fun thide(s: EStage[Int], id: Int) -> EStage[Int] = s.updateAs[TBody](id, |b| TBody(..b, visible: false))
364
412
 
365
413
  test "step returns a new stage and leaves a kept one as it was"
366
414
  s0 := tstage().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
367
- ctx := ECtx[TKind]()
415
+ ctx := ECtx[Int]()
368
416
  s1 := s0.step(ctx, 0.5)
369
417
  s2 := s1.step(ctx, 0.5)
370
418
  assert tx(s0, 1) == 0.0
@@ -376,43 +424,52 @@ test "step returns a new stage and leaves a kept one as it was"
376
424
 
377
425
  test "a step that changes nothing keeps every actor"
378
426
  s0 := tstage().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 5.0)]))
379
- s1 := s0.step(ECtx[TKind](), 1.0)
427
+ s1 := s0.step(ECtx[Int](), 1.0)
380
428
  assert tids(s1) == "0,1,2,3"
381
429
  assert s1.find(3).unwrap() == s0.find(3).unwrap()
382
430
 
383
- test "an actor whose step returns it dead is dropped with its subtree in the same step"
431
+ test "an actor whose step returns it gone is dropped with its subtree in the same step"
384
432
  s := tstage().add(0, tdrifter(1, 0.0, 1.0, 1)).add(0, trect(2, 0.0, 0.0, 5.0)).add(1, trect(3, 0.0, 0.0, 5.0))
385
433
  assert tids(s) == "0,1,3,2"
386
- ctx := ECtx[TKind]()
434
+ ctx := ECtx[Int]()
387
435
  s1 := s.step(ctx, 1.0)
388
436
  assert tids(s1) == "0,1,3,2"
389
437
  s2 := s1.step(ctx, 1.0)
390
438
  assert tids(s2) == "0,2"
391
439
  assert s2.find(3).isNone()
392
440
 
393
- test "a dead or hidden actor: dead ones go with their subtree, hidden ones still step"
441
+ test "a gone or hidden actor: gone ones go with their subtree, hidden ones still step"
394
442
  s := tstage().add(0, tdrifter(1, 0.0, 1.0, -1)).add(1, trect(2, 0.0, 0.0, 5.0)).add(0, trect(3, 0.0, 0.0, 5.0))
395
- hidden := s.update(1, |a| a.withVisible(false))
443
+ hidden := s.updateAs[TDrifter](1, |d| TDrifter(..d, visible: false))
396
- h1 := hidden.step(ECtx[TKind](), 1.0)
444
+ h1 := hidden.step(ECtx[Int](), 1.0)
397
445
  assert tx(h1, 1) == 1.0
398
446
  assert h1.flatten().length() == 2
399
- assert h1.hit(1.0, 1.0).unwrap().id == 3
447
+ assert h1.hit(1.0, 1.0).unwrap().key() == 3
400
- dead := s.update(1, |a| a.killed()).step(ECtx[TKind](), 1.0)
448
+ gone := s.updateAs[TDrifter](1, |d| TDrifter(..d, dead: true))
449
+ # not drawn or hit before the step drops it
450
+ assert gone.flatten().length() == 2
401
- assert tids(dead) == "0,3"
451
+ assert tids(gone.step(ECtx[Int](), 1.0)) == "0,3"
402
452
 
403
- test "spawns pushed to ctx.out are added after the step, on top"
453
+ test "spawns pushed to ctx.out are added after the step, on top, and sends stay for the game"
404
454
  s := tstage().add(0, tspawner(1, 10))
405
- ctx := ECtx[TKind]()
455
+ ctx := ECtx[Int]()
456
+ ctx.send(99)
406
457
  s1 := s.step(ctx, 1.0)
407
458
  assert tids(s1) == "0,1,10"
459
+ assert ctx.out.length() == 2
460
+ s2 := s1.step(ctx, 1.0)
461
+ assert tids(s2) == "0,1,10,11"
462
+ sent := ctx.takeSends()
463
+ assert sent.length() == 3
464
+ assert sent.get(0).unwrap() == 99 && sent.get(1).unwrap() == 10 && sent.get(2).unwrap() == 11
408
465
  assert ctx.out.length() == 0
409
- assert tids(s1.step(ctx, 1.0)) == "0,1,10,11"
410
466
 
411
- test "apply kills and spawns in one pass, in order"
467
+ test "apply kills and spawns in one pass, in order, and skips sends"
412
468
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)])).add(0, trect(4, 0.0, 0.0, 1.0))
413
- cmds := Slice[ECmd[TKind]]()
469
+ cmds := Slice[ECmd[Int]]()
414
470
  cmds.push(EKill(id: 2))
415
471
  cmds.push(ESpawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
472
+ cmds.push(ESend(msg: 7))
416
473
  cmds.push(ESpawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
417
474
  cmds.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
418
475
  cmds.push(ESpawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
@@ -420,19 +477,40 @@ test "apply kills and spawns in one pass, in order"
420
477
  assert tids(s2) == "0,1,3,5,7,4,6"
421
478
  assert tids(s) == "0,1,2,3,4"
422
479
  assert s.kill(1).count() == 2
480
+ sends := Slice[ECmd[Int]]()
481
+ sends.push(ESend(msg: 1))
482
+ assert tids(s.apply(sends)) == "0,1,2,3,4"
423
483
 
424
484
  test "update by id changes one actor and shares its untouched siblings"
425
485
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
426
486
  s1 := s.add(0, tgroup(4, 0.0, 0.0, 1.0, 0.0, [trect(5, 0.0, 0.0, 1.0)]))
427
- u := s1.update(2, |a| a.at(9.0, 9.0).tint(Color.Blue))
487
+ u := s1.updateAs[TBody](2, |b| TBody(..b, at: b.at.moveTo(9.0, 9.0), w: 3.0))
428
488
  assert tx(u, 2) == 9.0
429
489
  assert tx(s1, 2) == 0.0
430
490
  # 2's later sibling (3) and 1's later sibling (the group 4) are the same nodes
431
491
  assert u.root.kids().kids().rest() == s1.root.kids().kids().rest()
432
492
  assert u.root.kids().rest() == s1.root.kids().rest()
433
- k := s1.updateKind(5, |_| TDrifter(vx: 2.0, ttl: -1)).step(ECtx[TKind](), 1.0)
493
+ k := s1.update(5, |a| TDrifter(id: a.key(), at: a.place(), vx: 2.0, ttl: -1, visible: true, dead: false)).step(ECtx[Int](), 1.0)
434
494
  assert tx(k, 5) == 2.0
435
495
 
496
+ test "updateAs and findAs act only on an actor of that type"
497
+ s := tstage().add(0, tdrifter(1, 0.0, 1.0, -1)).add(0, trect(2, 3.0, 0.0, 1.0))
498
+ assert s.findAs[TDrifter](1).unwrap().vx == 1.0
499
+ assert s.findAs[TBody](1).isNone()
500
+ assert s.findAs[TBody](2).unwrap().w == 1.0
501
+ assert s.findAs[TBody](42).isNone()
502
+ same := s.updateAs[TBody](1, |b| TBody(..b, w: 50.0))
503
+ assert same.find(1).unwrap() == s.find(1).unwrap()
504
+ assert same.find(2).unwrap() == s.find(2).unwrap()
505
+ t := s.updateAs[TDrifter](1, |d| TDrifter(..d, vx: 5.0)).step(ECtx[Int](), 1.0)
506
+ assert tx(t, 1) == 5.0
507
+ assert tx(t, 2) == 3.0
508
+ # std's own kinds
509
+ g: EStage[Int] := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))).add(0, FRoseTree.leaf(Box(id: 1, at: place.at(1.0, 0.0), w: 2.0, h: 2.0, color: Color.Red)))
510
+ moved := g.updateAs[Box[Int]](1, |b| Box(..b, at: b.at.moveBy(1.0, 0.0)))
511
+ assert moved.findAs[Box[Int]](1).unwrap().at.x == 2.0
512
+ assert moved.findAs[Group[Int]](0).unwrap().id == 0
513
+
436
514
  test "flatten gives each shown actor its stage transform, parents first"
437
515
  g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 10.0, 0.0, 10.0), trect(3, 0.0, 0.0, 30.0)])
438
516
  s := tstage().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
@@ -440,40 +518,40 @@ test "flatten gives each shown actor its stage transform, parents first"
440
518
  assert d.length() == 5
441
519
  ids := Slice[Int]()
442
520
  for e := range d
443
- ids.push(e.actor.id)
521
+ ids.push(e.actor.key())
444
522
  assert ids.toStr() == "[0,1,2,3,4]"
445
523
  # (0, 0) of rect 2 is (10, 0) in the group, turned a quarter and doubled: (100, 20)
446
524
  p := d.at(2).m.apply(Vec2(x: 0.0, y: 0.0))
447
525
  assert tnear(p.x, 100.0) && tnear(p.y, 20.0)
448
526
  assert tnear(d.at(4).m.e, 5.0)
449
- hidden := s.update(1, |a| a.withVisible(false))
450
- assert hidden.flatten().length() == 2
527
+ assert thide(s, 1).flatten().length() == 2
451
528
  # alphas multiply down the tree
452
- faded := s.update(1, |a| a.fade(0.5)).update(2, |a| a.fade(0.5)).flatten()
529
+ faded := tfade(tfade(s, 1, 0.5), 2, 0.5).flatten()
453
530
  assert faded.at(2).alpha == 0.25 && faded.at(3).alpha == 0.5 && faded.at(4).alpha == 1.0
454
531
 
455
532
  test "hit finds the topmost actor: later siblings and children first"
456
533
  g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 0.0, 0.0, 30.0), trect(3, 10.0, 0.0, 10.0)])
457
534
  s := tstage().add(0, g)
458
- assert s.hit(90.0, 30.0).unwrap().id == 3
535
+ assert s.hit(90.0, 30.0).unwrap().key() == 3
459
- assert s.hit(70.0, 10.0).unwrap().id == 2
536
+ assert s.hit(70.0, 10.0).unwrap().key() == 2
460
537
  assert s.hit(10.0, 10.0).isNone()
461
538
  t := tstage().add(0, trect(5, 0.0, 0.0, 50.0)).add(0, trect(6, 25.0, 0.0, 50.0)).add(6, trect(7, 0.0, 0.0, 10.0))
462
- assert t.hit(10.0, 10.0).unwrap().id == 5
539
+ assert t.hit(10.0, 10.0).unwrap().key() == 5
463
- assert t.hit(30.0, 5.0).unwrap().id == 7
540
+ assert t.hit(30.0, 5.0).unwrap().key() == 7
464
541
  assert t.hitId(40.0, 10.0).unwrap() == 6
542
+ assert thide(t, 6).hitId(40.0, 10.0).unwrap() == 5
465
543
 
466
544
  test "an actor's world transform is computed when it asks, and matches the eager product"
467
545
  gb := tturned(1, 100.0, 30.0, 2.0, 0.7)
468
- hb := tturned(2, -20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0)
546
+ hb := TBody(..tturned(2, -20.0, 5.0, 1.5, -1.1), at: place.turned(-20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0))
469
547
  p := tprobe(3, 7.0, -2.0, 2.5)
470
548
  q := tprobe(4, 1.0, 1.0, 0.0)
471
549
  s := tstage().add(0, FRoseTree.of(gb, [FRoseTree.of(hb, [FRoseTree.leaf(p), FRoseTree.leaf(q)])]))
472
- s1 := s.step(ECtx[TKind](), 1.0)
550
+ s1 := s.step(ECtx[Int](), 1.0)
473
- assert tsameM(tseen(s1, 3), gb.local().mul(hb.local()).mul(p.local()))
551
+ assert tsameM(tseen(s1, 3), gb.at.local().mul(hb.at.local()).mul(p.at.local()))
474
552
  assert tnear(tseenA(s1, 3), 0.5)
475
553
  # the sibling got its own transform from the same context
476
- assert tsameM(tseen(s1, 4), gb.local().mul(hb.local()).mul(q.local()))
554
+ assert tsameM(tseen(s1, 4), gb.at.local().mul(hb.at.local()).mul(q.at.local()))
477
555
 
478
556
  test "siblings with children each give their children their own world transform"
479
557
  g1 := tturned(1, 100.0, 30.0, 2.0, 0.7)
@@ -481,13 +559,13 @@ test "siblings with children each give their children their own world transform"
481
559
  p1 := tprobe(3, 7.0, -2.0, 2.5)
482
560
  p2 := tprobe(4, 1.0, 9.0, 0.3)
483
561
  s := tstage().add(0, FRoseTree.of(g1, [FRoseTree.leaf(p1)])).add(0, FRoseTree.of(g2, [FRoseTree.leaf(p2)]))
484
- s1 := s.step(ECtx[TKind](), 1.0)
562
+ s1 := s.step(ECtx[Int](), 1.0)
485
- assert tsameM(tseen(s1, 3), g1.local().mul(p1.local()))
563
+ assert tsameM(tseen(s1, 3), g1.at.local().mul(p1.at.local()))
486
- assert tsameM(tseen(s1, 4), g2.local().mul(p2.local()))
564
+ assert tsameM(tseen(s1, 4), g2.at.local().mul(p2.at.local()))
487
565
 
488
566
  test "a kill pushed before the step drops the actor in the step's own walk, unstepped"
489
567
  s := tstage().add(0, tspawner(1, 10)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 1.0)]))
490
- ctx := ECtx[TKind]()
568
+ ctx := ECtx[Int]()
491
569
  ctx.out.push(EKill(id: 1))
492
570
  s2 := s.step(ctx, 1.0)
493
571
  # the spawner was not stepped, so it spawned nothing
@@ -502,7 +580,7 @@ test "a kill pushed before the step drops the actor in the step's own walk, unst
502
580
  test "spawns pushed before the step go on top of their parents, in order, unstepped"
503
581
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
504
582
  s1 := s.add(0, trect(4, 0.0, 0.0, 1.0)).add(0, tgroup(9, 0.0, 0.0, 1.0, 0.0, [trect(10, 0.0, 0.0, 1.0)]))
505
- ctx := ECtx[TKind]()
583
+ ctx := ECtx[Int]()
506
584
  ctx.out.push(ESpawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
507
585
  ctx.out.push(ESpawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
508
586
  ctx.out.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
@@ -517,14 +595,14 @@ test "spawns pushed before the step go on top of their parents, in order, unstep
517
595
  ctx.out.push(ESpawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
518
596
  s3 := s2.step(ctx, 1.0)
519
597
  ids := s3.root.kids().rest().kids().fold(Slice[Int](), |acc, a|
520
- acc.push(a.id)
598
+ acc.push(a.key())
521
599
  acc
522
600
  )
523
601
  assert ids.length() == 51 && ids.at(0) == 6 && ids.at(1) == 100 && ids.at(50) == 149
524
602
 
525
603
  test "a kill and a spawn of the same id before the step: the old actor goes, the new one stays"
526
604
  s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
527
- ctx := ECtx[TKind]()
605
+ ctx := ECtx[Int]()
528
606
  ctx.out.push(EKill(id: 2))
529
607
  ctx.out.push(ESpawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
530
608
  s2 := s.step(ctx, 1.0)
@@ -539,7 +617,7 @@ test "a kill and a spawn of the same id before the step: the old actor goes, the
539
617
 
540
618
  test "commands pushed during the step apply after those pushed before it"
541
619
  s := tstage().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
542
- ctx := ECtx[TKind]()
620
+ ctx := ECtx[Int]()
543
621
  # spawned by the batch before the step, then killed by an actor during it
544
622
  ctx.out.push(ESpawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
545
623
  s2 := s.step(ctx, 1.0)
@@ -550,7 +628,7 @@ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids pas
550
628
  big := 4194303
551
629
  s := tstage().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
552
630
  s1 := s.add(0, tgroup(big + 1, 0.0, 0.0, 1.0, 0.0, [trect(63, 0.0, 0.0, 1.0), trect(64, 0.0, 0.0, 1.0)]))
553
- ctx := ECtx[TKind]()
631
+ ctx := ECtx[Int]()
554
632
  # in the bitsets' range: the last bit of the last word, and a word boundary
555
633
  ctx.out.push(EKill(id: big - 1))
556
634
  ctx.out.push(EKill(id: 64))
@@ -567,9 +645,9 @@ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids pas
567
645
  ctx.out.push(EKill(id: big + 100))
568
646
  assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
569
647
 
570
- test "a plain EBox stage: add, step, draw list"
648
+ test "a plain stage of std's Group and Box: add, step, draw list"
571
- s := EStage.of(EBox.group(0, 0.0, 0.0)).add(0, FRoseTree.leaf(EBox.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
649
+ s: EStage[Int] := EStage.of(Group(id: 0, at: place.at(0.0, 0.0))).add(0, FRoseTree.leaf(Box(id: 1, at: place.at(10.0, 5.0), w: 40.0, h: 20.0, color: Color.Red)))
572
- s1 := s.step(ECtx[EBox](), 1.0)
650
+ s1 := s.step(ECtx[Int](), 1.0)
573
651
  assert s1.count() == 2
574
652
  assert s1.flatten().at(1).m.e == 10.0
575
- assert s1.hit(20.0, 10.0).unwrap().id == 1
653
+ assert s1.hit(20.0, 10.0).unwrap().key() == 1
std/game_enum_tree/Place.plum ADDED
@@ -0,0 +1,73 @@
1
+ module std
2
+
3
+ import std/Float
4
+ import std/math
5
+ import std/game/Vec2
6
+ import std/game/Affine
7
+
8
+ # Where an actor is in its parent: its position, its scale and rotation, and the origin
9
+ # (in its own coordinates) it turns and scales about. Every actor has one (`Actor.place`);
10
+ # the stage turns it into the actor's transform with `local`.
11
+ #
12
+ # p := place.at(10.0, 20.0) # unscaled, unturned
13
+ # q := place.at(400.0, 300.0).rotateTo(0.5)
14
+ # r := Place(..place.at(0.0, 0.0), scaleX: 2.0)
15
+ #
16
+ # (Struct fields have no defaults in the language yet, so `at` and `turned` stand in for
17
+ # them.)
18
+ struct Place(
19
+ x: Float, y: Float,
20
+ scaleX: Float, scaleY: Float,
21
+ rotation: Float,
22
+ originX: Float, originY: Float) =
23
+
24
+ # The transform into the parent's coordinates: translate to the position, rotate and
25
+ # scale about the origin.
26
+ fun local(self) -> Affine =
27
+ cs := math.cos(self.rotation)
28
+ sn := math.sin(self.rotation)
29
+ a := cs * self.scaleX
30
+ b := sn * self.scaleX
31
+ c := 0.0 - sn * self.scaleY
32
+ d := cs * self.scaleY
33
+ Affine(
34
+ a: a, b: b, c: c, d: d,
35
+ e: self.x + self.originX - {a * self.originX + c * self.originY},
36
+ f: self.y + self.originY - {b * self.originX + d * self.originY})
37
+
38
+ # Copies with one thing changed.
39
+
40
+ fun moveTo(self, x: Float, y: Float) -> Place = Place(..self, x: x, y: y)
41
+
42
+ fun moveBy(self, dx: Float, dy: Float) -> Place = Place(..self, x: self.x + dx, y: self.y + dy)
43
+
44
+ fun rotateTo(self, r: Float) -> Place = Place(..self, rotation: r)
45
+
46
+ fun scaleTo(self, sx: Float, sy: Float) -> Place = Place(..self, scaleX: sx, scaleY: sy)
47
+
48
+ # Its rotation and scale about (ox, oy), in its own coordinates.
49
+ fun pivotAt(self, ox: Float, oy: Float) -> Place = Place(..self, originX: ox, originY: oy)
50
+
51
+ # At (x, y), unscaled and unturned.
52
+ fun at(x: Float, y: Float) -> Place =
53
+ Place(x: x, y: y, scaleX: 1.0, scaleY: 1.0, rotation: 0.0, originX: 0.0, originY: 0.0)
54
+
55
+ # At (x, y), scaled by `s` and turned by `r` radians about its own (0, 0).
56
+ fun turned(x: Float, y: Float, s: Float, r: Float) -> Place =
57
+ Place(x: x, y: y, scaleX: s, scaleY: s, rotation: r, originX: 0.0, originY: 0.0)
58
+
59
+ test "local translates, then turns and scales about the origin"
60
+ b := turned(10.0, 20.0, 2.0, 0.0).pivotAt(1.0, 1.0)
61
+ p := b.local().apply(Vec2(x: 1.0, y: 1.0))
62
+ assert p.x == 11.0 && p.y == 21.0
63
+ q := b.local().apply(Vec2(x: 2.0, y: 1.0))
64
+ assert q.x == 13.0 && q.y == 21.0
65
+
66
+ test "the copies change one thing"
67
+ p := at(1.0, 2.0)
68
+ assert p.scaleX == 1.0 && p.rotation == 0.0 && p.originX == 0.0
69
+ assert p.moveBy(1.0, 2.0).x == 2.0 && p.moveBy(1.0, 2.0).y == 4.0
70
+ assert p.moveTo(5.0, 6.0).y == 6.0
71
+ assert p.rotateTo(0.5).rotation == 0.5 && p.rotateTo(0.5).x == 1.0
72
+ assert p.scaleTo(2.0, 3.0).scaleY == 3.0
73
+ assert p.local().e == 1.0 && p.local().f == 2.0
tests/traits/late_pin.plum ADDED
@@ -0,0 +1,27 @@
1
+ import std/Int
2
+ import std/List
3
+ import std/Option
4
+
5
+ # A generic implementer built bare where a still-open trait object is expected
6
+ # (`Holder.of(Box(..))`, with `of(top: Thing[M])`) takes the trait's argument once a
7
+ # later use fixes it, not `Unit`.
8
+
9
+ trait Thing[M] =
10
+ fun key(self) -> Int
11
+
12
+ struct Box[M](id: Int) is Thing[M] =
13
+ fun key(self) -> Int = self.id
14
+
15
+ struct Holder[M](top: Thing[M], more: List[Thing[M]]) =
16
+ fun of(top: Thing[M]) -> Holder[M] = Holder(top: top, more: [])
17
+ fun with(self, t: Thing[M]) -> Holder[M] = Holder(..self, more: Cons(t, self.more))
18
+ fun same(self) -> Holder[M] = self
19
+ fun sum(self) -> Int = self.more.fold(self.top.key(), |n, t| n + t.key())
20
+
21
+ test "pinned only after a method call on the result"
22
+ h: Holder[Int] := Holder.of(Box(id: 3)).same()
23
+ assert h.sum() == 3
24
+
25
+ test "pinned through a chain of calls, each taking a bare implementer"
26
+ h: Holder[Int] := Holder.of(Box(id: 1)).with(Box(id: 2)).with(Box(id: 4))
27
+ assert h.sum() == 7
tests/traits/type_args.plum CHANGED
@@ -40,6 +40,14 @@ struct Stage(xs: List[Actor]) =
40
40
 
41
41
  fun pair[A, B](a: A, b: B) -> Int = 2
42
42
 
43
+ # An annotated local of a generic value as a trait object, in a generic body (not a
44
+ # closure): checked per instantiation, and still bound for its later uses.
45
+ fun updOne[T](a: Actor, f: fn(T) -> T) -> Actor = match a
46
+ T as t =>
47
+ b: Actor := f(t)
48
+ b
49
+ _ => a
50
+
43
51
  fun isA[T](a: Actor) -> Bool = match a
44
52
  T as t => true
45
53
  _ => false
@@ -64,3 +72,8 @@ test "a type parameter used only in the body"
64
72
  o: Actor := Orb(id: 1, vx: 2.0)
65
73
  assert isA[Orb](o)
66
74
  assert !isA[Label](o)
75
+
76
+ test "an annotated trait object local of a T in a generic body"
77
+ o: Actor := Orb(id: 1, vx: 2.0)
78
+ assert findAs[Orb]([updOne[Orb](o, |x| Orb(..x, vx: 3.0))], 1).unwrap().vx == 3.0
79
+ assert updOne[Label](o, |l| Label(..l, text: "no")) == o
tests/traits/unit_stmt.plum ADDED
@@ -0,0 +1,29 @@
1
+ import std/Int
2
+ import std/List
3
+ import std/Slice
4
+
5
+ # A Unit method called on a trait object as a statement leaves nothing to drop, whether the
6
+ # type has its own method or takes the trait's default.
7
+
8
+ trait Painter =
9
+ fun key(self) -> Int
10
+ fun paint(self, out: Slice[Int], n: Int) = Unit
11
+
12
+ struct Quiet(id: Int) is Painter =
13
+ fun key(self) -> Int = self.id
14
+
15
+ struct Loud(id: Int) is Painter =
16
+ fun key(self) -> Int = self.id
17
+ fun paint(self, out: Slice[Int], n: Int) = out.push(self.id * 10 + n)
18
+
19
+ fun paintAll(xs: List[Painter], out: Slice[Int], n: Int) =
20
+ if Cons(a, rest) := xs
21
+ a.paint(out, n)
22
+ paintAll(rest, out, n + 1)
23
+
24
+ test "a Unit trait method as a statement"
25
+ out := Slice[Int]()
26
+ xs: List[Painter] := [Quiet(id: 1), Loud(id: 2), Quiet(id: 3), Loud(id: 4)]
27
+ paintAll(xs, out, 0)
28
+ assert out.length() == 2
29
+ assert out.at(0) == 21 && out.at(1) == 43