plum

#treesitter#compiler#wasm

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

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


353a391 — Peter John 2026-11-10T12:28:03+05:30
Game: a Clickable trait for actors the pointer can hit
benchmarks/scene_trees/scene_tree.plum CHANGED
@@ -63,7 +63,7 @@ struct Rng(mut s: Int) =
63
63
  # with a `Place` field moved by a nested spread (`Bod(..self, at: self.at.moveTo(..))`)
64
64
  # each step allocates a cell, which FBIP doesn't reuse, and the step workload is about
65
65
  # 1.7 times slower.
66
- struct Bod(id: Int, x: Float, y: Float, vx: Float, vy: Float) is Actor[Int] =
66
+ struct Bod(id: Int, x: Float, y: Float, vx: Float, vy: Float) is Actor[Int], Clickable =
67
67
  fun key(self) -> Int = self.id
68
68
 
69
69
  fun place(self) -> Place = place.at(self.x, self.y)
@@ -81,7 +81,7 @@ struct Bod(id: Int, x: Float, y: Float, vx: Float, vy: Float) is Actor[Int] =
81
81
 
82
82
  # A leaf that never moves: `Bod` without a velocity, whose step is `Actor`'s default (it
83
83
  # returns the leaf as it is).
84
- struct Still(id: Int, x: Float, y: Float) is Actor[Int] =
84
+ struct Still(id: Int, x: Float, y: Float) is Actor[Int], Clickable =
85
85
  fun key(self) -> Int = self.id
86
86
 
87
87
  fun place(self) -> Place = place.at(self.x, self.y)
docs/game.md CHANGED
@@ -16,7 +16,7 @@ This builds the game, starts a local server and opens your browser. Press Enter
16
16
 
17
17
  There is one way to make a game: `main` returns a `Game[S, M]` ([`std/game/Game.plum`](../std/game/Game.plum)), made by `Game.start(tree, state)`. A game is three things you write, and `Game` runs the loop:
18
18
 
19
- - **Actors.** Each thing on the screen is its own struct that `is Actor[M]` ([Scenes](#scenes)), with its own `step` (its next version, every tick), `paint`, and `input` (a pointer event on it).
19
+ - **Actors.** Each thing on the screen is its own struct that `is Actor[M]` ([Scenes](#scenes)), with its own `step` (its next version, every tick), `paint`, and `input` (a pointer event on it). One the pointer can hit is `Clickable` too, and says where with `hit`.
20
20
  - **Screens.** The game's tree of actors has a root whose children are the screens (a title, the play, a game over). A screen is a struct that `is Screen[S, M]`, an actor too, and its subtree is what it shows. Only one screen is shown at a time, the one the state names. A screen's `rules` run after the actors stepped (collisions, keys), its `react` shows a new state after each message, its `enter` sets it up when the state switches to it, its `transition` says how it comes in, and its `draw` draws the frame ([Screens and transitions](#screens-and-transitions)). By convention a screen's struct name ends in `Screen`.
21
21
  - **A reducer.** The game's state `S` is a `Reducer[M]` ([`std/game/Store.plum`](../std/game/Store.plum)). `update(self, msg)` is the rules of the state: pure, with no `io`. `handle(self, io, msg)` is the effects of a message (a sound, a save), run after the tick. `screen(self)` names the screen to show. `M` is the game's message type: actors and rules send messages with `ctx.send(msg)`, and a button sends its `onClick`.
22
22
 
@@ -98,7 +98,7 @@ This is [`examples/games/clicks.plum`](../examples/games/clicks.plum), a game of
98
98
 
99
99
  Each tick, `Game.update(io, input, dt)` does this, in this order:
100
100
 
101
- 1. Each pointer event of the tick goes to the topmost shown actor of the current screen under it that says it is hit (`hit`), through its `input`, then to each of its parents up to the root. Each gets the event in its own coordinates. A `PointerMove` that leaves the pointer where it was goes to no actor.
101
+ 1. Each pointer event of the tick goes to the topmost shown `Clickable` actor of the current screen under it that says it is hit (`hit`), through its `input`, then to each of its parents up to the root. Each gets the event in its own coordinates. A `PointerMove` that leaves the pointer where it was goes to no actor.
102
102
  2. The root and the current screen's actors step (`step`), parents before children, then the screen's `rules` run. Both see the tick's input in `ctx.input` (held keys, the pointer) and the screen's size in `ctx.view`.
103
103
  3. The spawns and kills apply to the root and the current screen (`ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`): those pushed by `input`, then by the steps, then by the rules.
104
104
  4. Each message sent, in order: the store reduces it (`update`), then the current screen `react`s to the new state.
@@ -253,10 +253,26 @@ Each kind of actor is its own struct, with only its own fields, that `is Actor[M
253
253
  - `step(self, ctx, dt)` returns its next version, once a tick. `ctx` ([`Ctx.plum`](../std/game/scene/Ctx.plum)) has its parent's world transform and alpha, the tick's input (`ctx.input`) and the screen's size (`ctx.view`), and takes commands for after the step: `ctx.out.push(Spawn(parent, node))`, `ctx.out.push(Kill(id))`, `ctx.send(msg)`, `ctx.out.push(Restart)` and `ctx.out.push(Exit)`.
254
254
  - `input(self, ctx, e)` returns its next version after a pointer event on it or on one of its children, before the tick's steps. `e` is in its own coordinates.
255
255
  - `paint(self, io, m, alpha)` draws it in its own coordinates seen through `m`. `Actor.plum` has helpers for boxes, circles, lines, sprites and text (`actor.boxPaint(io, m, alpha, w, h, color)`, ...).
256
- - `hit(self, p)` says whether a point in its own coordinates is on it. Only an actor that says so gets pointer events, and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first.
257
256
  - `shown`, `gone` and `opacity`: a hidden actor isn't drawn or hit, a gone one is dropped with its subtree, and opacities multiply down the tree.
258
257
 
259
- Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. An actor that doesn't change should return `self` from `step` and `input` (the defaults do), not a copy: an `input` that returns the actor as it was leaves the tree as it was (`ref.same`, see [std](std.md#utilities)), and a screen's `react` that returns its tree as it was (the default) leaves the game's tree as it was. std gives `Group` (a parent that paints nothing) and `Box`; [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button` (`ui.button(id, x, y, w, h, label, onClick)`). A button shows the pointer over it and a press on it, and a press and a release on it send its `onClick` message.
258
+ An actor the pointer can hit says so with a second trait, `Clickable` (also in `Actor.plum`): `struct Target(..) is Actor[Msg], Clickable =`, with `hit(self, p) -> Bool`, whether a point in its own coordinates is on it. Only a `Clickable` actor that says it is hit gets a pointer event (and its parents after it, clickable or not), and is found by `tree.hit(x, y)` and `tree.hitId(x, y)`, topmost first. The tree's pointer walk skips every other actor with one type-tag test, and computes the transform of one only when it has children (who may be clickable). A `hit` on an actor that isn't `Clickable` is a plain method the tree never calls, and nothing warns about it: if an actor gets no clicks, check its `is` list.
259
+
260
+ ```plum
261
+ struct Target(id: Int, x: Float, y: Float) is Actor[Msg], Clickable =
262
+ fun key(self) -> Int = self.id
263
+
264
+ fun place(self) -> Place = place.at(self.x, self.y)
265
+
266
+ fun hit(self, p: Vec2) -> Bool = actor.circleHit(0.0, 0.0, 16.0, p)
267
+
268
+ fun input(self, ctx: Ctx[Msg], e: InputEvent) -> Target = match e
269
+ PointerDown(_, _) =>
270
+ ctx.send(Hit(id: self.id))
271
+ self
272
+ _ => self
273
+ ```
274
+
275
+ Keep an actor's position in plain fields (`x: Float, y: Float`) and build its `Place` in `place`, as `place.at(self.x, self.y)`: a `Place` field costs a step about 1.7 times as much. An actor that doesn't change should return `self` from `step` and `input` (the defaults do), not a copy: an `input` that returns the actor as it was leaves the tree as it was (`ref.same`, see [std](std.md#utilities)), and a screen's `react` that returns its tree as it was (the default) leaves the game's tree as it was. std gives `Group` (a parent that paints nothing) and `Box` (`Clickable`, hit inside it); [`std/game/ui.plum`](../std/game/ui.plum) gives `Label` and `Button` (`Clickable`) (`ui.button(id, x, y, w, h, label, onClick)`). A button shows the pointer over it and a press on it, and a press and a release on it send its `onClick` message.
260
276
 
261
277
  The tree's `step(ctx, dt)` steps every actor, parents before children, then applies the spawns and kills; `input(ctx, e)` routes one pointer event. `Game` calls both. `add`, `update`, `kill` and `find` work by id, and `updateAs[T](id, f)` and `findAs[T](id)` act on an actor of the type `T` only, which is how a screen's `rules` and `react` read and change one kind's own fields in its subtree. `allAs[T]()` is every actor of the type `T`, in tree order, and `kidsAs[T](parent)` the `T`s among one actor's children (a layer: `t.kidsAs[Balloon](BalloonLayer)`), which is how `rules` reads one kind's actors. `subtree(id)` is an actor with its subtree as a tree of its own, and `withTop(a)` a tree with its root actor replaced. A pattern `Orb as o` on an `Actor[M]` matches an `Orb`.
262
278
 
docs/std.md CHANGED
@@ -131,7 +131,7 @@ Only true tail calls run in constant stack; other recursion overflows at a few t
131
131
  - **`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.
132
132
  - **`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`).
133
133
  - **`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.
134
- - **`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; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `filter`, `replace` and `update` return untouched subtrees as they were. std/game/scene's `SceneTree[M]` is an `FRoseTree[Actor[M]]`, a tree of trait objects.
134
+ - **`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; every walk runs in constant stack along the siblings (a node with 200,000 children is fine), and only the tree's depth takes stack. `filter`, `replace` and `update` return untouched subtrees as they were. std/game/scene's `SceneTree[M]` is an `FRoseTree[Actor[M]]`, a tree of trait objects. An actor the pointer can hit is `Clickable` as well (`is Actor[M], Clickable`), and the tree's pointer walk tells it from the others with a downcast (`Clickable as c`, one type-tag test).
135
135
  - **`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.
136
136
 
137
137
  ## Option and Result
examples/games/kids/balloon_pop.plum CHANGED
@@ -5,15 +5,15 @@
5
5
  # confetti. There is no way to lose and no timer.
6
6
  #
7
7
  # The game is a `Game` (std/game/Game) with one screen, `SkyScreen`, in a tree of actors
8
- # (std/game/scene) that lives from frame to frame. Each balloon is a `Balloon` actor that rises
8
+ # (std/game/scene) that lives from frame to frame. Each balloon is a `Balloon` actor that
9
- # in its own `step` and is the only actor that is ever hit: the game routes a pointer
9
+ # rises in its own `step` and is the only `Clickable` actor, so the only one ever hit
10
+ # (`hit`, its own shape): the game routes a pointer press to the balloon under it
10
- # press to the balloon under it (`input`), which bursts and sends `Popped(id)` to the
11
+ # (`input`), which bursts and sends `Popped(id)` to the store. The screen's `rules` send
11
- # store. The screen's `rules` send the tick (`Tick`) and ask for every balloon that is
12
+ # the tick (`Tick`) and ask for every balloon that is done to come back (`Renew(id)`).
12
- # done to come back (`Renew(id)`). `State` is the store's state: the pops, the party, the
13
+ # `State` is the store's state: the pops, the party, the clock and the `Random`; it says
13
- # clock and the `Random`; it says where a renewed balloon goes, and the screen `react`s by
14
+ # where a renewed balloon goes, and the screen `react`s by putting it in the tree and
14
- # putting it in the tree and showing the pops on the hud and the party. The sounds are the
15
+ # showing the pops on the hud and the party. The sounds are the effects of the messages
15
- # effects of the messages (`handle`). A press pops at once: small children tap, they do
16
+ # (`handle`). A press pops at once: small children tap, they do not click.
16
- # not click.
17
17
  #
18
18
  # 0 root (the camera that fits the arena on screen)
19
19
  # └─ 5 the screen
@@ -120,7 +120,7 @@ struct Camera(id: Int, x: Float, y: Float, zoom: Float) is Actor[Msg] =
120
120
 
121
121
  # One balloon. `poppedAt` is the clock time it was popped, or negative while whole;
122
122
  # `clock` is the game's clock, which it keeps in its own step.
123
- struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, poppedAt: Float, clock: Float) is Actor[Msg] =
123
+ struct Balloon(id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, poppedAt: Float, clock: Float) is Actor[Msg], Clickable =
124
124
 
125
125
  # A fresh balloon below the bottom edge, `depth` further down so they do not
126
126
  # all arrive together, at the game's `clock`.
examples/games/orb_run.plum CHANGED
@@ -11,8 +11,8 @@
11
11
  # screen fades in over the title. Every kind of body is its own struct (`Ship`, `Orb`,
12
12
  # `Mine`, `Star`, `Icon`, ..) with only its own fields, and `is Actor[Msg]`: it says which
13
13
  # actor it is (`key`) and where (`place`, made from its plain `x` and `y`), and writes
14
- # only the behaviour it has: its next version (`step`), its drawing (`paint`), its hit
14
+ # only the behaviour it has: its next version (`step`), its drawing (`paint`). None of
15
- # test (`hit`). The ship steers itself from the tick's held keys (`ctx.input`) and the
15
+ # them is `Clickable`, so the pointer passes them by. The ship steers itself from the tick's held keys (`ctx.input`) and the
16
16
  # root camera fits itself to the screen (`ctx.view`). The backdrop and the dimmer are
17
17
  # std's `Box`, the layers std's `Group`, the text std/game/ui's `Label` and the buttons
18
18
  # ui's `Button`, which send their `onClick` message when clicked.
@@ -206,9 +206,9 @@ fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Floa
206
206
 
207
207
  # Each kind of body is its own struct with only its own fields, and `is Actor[Msg]`: the
208
208
  # tree asks it for its id (`key`), its place in its parent (`place`), its next version
209
- # (`step`), its drawing (`paint`, in its own coordinates seen through `m`) and its hit test
209
+ # (`step`), its drawing (`paint`, in its own coordinates seen through `m`), and whether it
210
- # (`hit`), and whether it is shown and how opaque it is. A kind writes only what differs
210
+ # is shown and how opaque it is. A kind writes only what differs from the trait's
211
- # from the trait's defaults. Orbs, mines and the ship are centred on their (x, y) and turn
211
+ # defaults; none is `Clickable` (`hit`), as only std's `Box` and ui's `Button` are here. Orbs, mines and the ship are centred on their (x, y) and turn
212
212
  # about it. The backdrop and the dimmer are std's `Box`, the layers and the hud std's
213
213
  # `Group`, the text ui's `Label` and the buttons ui's `Button`.
214
214
 
std/game/Game.plum CHANGED
@@ -537,7 +537,7 @@ fun gname(m: GMsg) -> Str = match m
537
537
 
538
538
  # A 10 by 10 box at (x, 0) that notes its pointer events and its steps, and sends one of
539
539
  # each to the store; on its step it sends `GGo` once `go` is set.
540
- struct GProbe(id: Int, x: Float, log: Slice[Str], go: Bool) is Actor[GMsg] =
540
+ struct GProbe(id: Int, x: Float, log: Slice[Str], go: Bool) is Actor[GMsg], Clickable =
541
541
  fun key(self) -> Int = self.id
542
542
 
543
543
  fun place(self) -> Place = place.at(self.x, 0.0)
std/game/scene/Actor.plum CHANGED
@@ -26,7 +26,6 @@ import std/game/scene/Ctx
26
26
  # runs before the tick's steps
27
27
  # paint draws it, seen through `m` (its own coordinates to the tree's) at `alpha`
28
28
  # (the accumulated alpha, its own `opacity` included)
29
- # hit whether `p`, in its own coordinates, is on it
30
29
  # shown false: it and its subtree are not drawn or hit (but still stepped)
31
30
  # gone true: it is dropped with its subtree (returned from `step`, in the same step)
32
31
  # opacity its own alpha, multiplied down the tree
@@ -43,6 +42,8 @@ import std/game/scene/Ctx
43
42
  # moved by a nested spread (`at: self.at.moveTo(..)`) costs a step about 1.7 times as
44
43
  # much. The std kinds below, `Group` and `Box` (and std/game/ui's `Button` and `Label`),
45
44
  # are generic in `M` so any game's tree takes them.
45
+ #
46
+ # An actor the pointer can hit is also `Clickable` (below): only those get pointer events.
46
47
  trait Actor[M] =
47
48
  fun key(self) -> Int
48
49
 
@@ -54,14 +55,21 @@ trait Actor[M] =
54
55
 
55
56
  fun paint(self, io: Io, m: Affine, alpha: Float) = Unit
56
57
 
57
- fun hit(self, p: Vec2) -> Bool = false
58
-
59
58
  fun shown(self) -> Bool = true
60
59
 
61
60
  fun gone(self) -> Bool = false
62
61
 
63
62
  fun opacity(self) -> Float = 1.0
64
63
 
64
+ # An actor the pointer can hit, as well as an `Actor[M]`: `struct Button[M](..) is Actor[M],
65
+ # Clickable`. `hit` says whether `p`, in the actor's own coordinates, is on it. Only a
66
+ # `Clickable` actor gets pointer events (`SceneTree.input`) and is found by
67
+ # `SceneTree.hit`; the tree's pointer walk skips every other actor without a test, and
68
+ # computes no transform for one without children. A `hit` on an actor that isn't
69
+ # `Clickable` is a plain method the tree never calls.
70
+ trait Clickable =
71
+ fun hit(self, p: Vec2) -> Bool
72
+
65
73
  # An actor that paints nothing and is never hit: a parent for others (a layer).
66
74
  struct Group[M](id: Int, x: Float, y: Float) is Actor[M] =
67
75
  fun key(self) -> Int = self.id
@@ -70,7 +78,7 @@ struct Group[M](id: Int, x: Float, y: Float) is Actor[M] =
70
78
 
71
79
  # A filled `w` by `h` box in `color`, with its top-left at (x, y); hit inside it. Its
72
80
  # opacity is its colour's alpha.
73
- struct Box[M](id: Int, x: Float, y: Float, w: Float, h: Float, color: Color) is Actor[M] =
81
+ struct Box[M](id: Int, x: Float, y: Float, w: Float, h: Float, color: Color) is Actor[M], Clickable =
74
82
  fun key(self) -> Int = self.id
75
83
 
76
84
  fun place(self) -> Place = place.at(self.x, self.y)
@@ -137,16 +145,25 @@ fun textPaint(io: Io, m: Affine, alpha: Float, text: Str, x: Float, y: Float, si
137
145
  p := m.apply(Vec2(x: x, y: y))
138
146
  gfx.drawText(io, text, p.x, p.y, size * m.scaleY(), c.withAlpha(c.a * alpha))
139
147
 
148
+ # Whether `a` is clickable and hit at `p`.
149
+ fun thitAt[M](a: Actor[M], p: Vec2) -> Bool = match a
150
+ Clickable as c => c.hit(p)
151
+ _ => false
152
+
153
+ fun isClickable[M](a: Actor[M]) -> Bool = match a
154
+ Clickable as c => true
155
+ _ => false
156
+
140
- test "a box is hit inside its size, a group never"
157
+ test "a box is hit inside its size, a group is not clickable"
141
158
  b: Actor[Int] := Box(id: 7, x: 1.0, y: 2.0, w: 4.0, h: 3.0, color: Color.Red.withAlpha(0.25))
142
159
  assert b.key() == 7
143
160
  assert b.place().x == 1.0
144
- assert b.hit(Vec2(x: 2.0, y: 1.0))
161
+ assert thitAt(b, Vec2(x: 2.0, y: 1.0))
145
- assert !b.hit(Vec2(x: 5.0, y: 1.0))
162
+ assert !thitAt(b, Vec2(x: 5.0, y: 1.0))
146
163
  assert b.opacity() == 0.25
147
164
  assert b.shown() && !b.gone()
148
165
  g: Actor[Int] := Group(id: 1, x: 0.0, y: 0.0)
149
- assert !g.hit(Vec2(x: 0.0, y: 0.0))
166
+ assert isClickable(b) && !isClickable(g)
150
167
  assert g.opacity() == 1.0
151
168
  assert !boxHit(0.0, 3.0, Vec2(x: 0.0, y: 0.0))
152
169
 
std/game/scene/SceneTree.plum CHANGED
@@ -41,9 +41,9 @@ import std/game/scene/Ctx
41
41
  # walk), drops a `gone()` actor with its subtree, skips one that is not `shown()` (or is
42
42
  # gone) with its subtree when it draws and hit tests, and multiplies the transforms
43
43
  # (`place().local()`) and alphas (`opacity()`) down the tree. Each actor's own type gives
44
- # the behaviour: `step`, `paint` and `hit`. The tree never needs an actor's own type;
44
+ # the behaviour: `step`, `paint`, and `hit` for one that is also `Clickable` (only those
45
+ # get pointer events). The tree never needs an actor's own type; game code that does uses
45
- # game code that does uses `updateAs[T]` and `findAs[T]`, which act only on an actor of
46
+ # `updateAs[T]` and `findAs[T]`, which act only on an actor of the type `T`.
46
- # the type `T`.
47
47
  #
48
48
  # Children are kept in draw order: a parent is drawn before its children, and siblings
49
49
  # first to last. Hit testing goes the other way, topmost first: children before their
@@ -175,12 +175,13 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
175
175
  self.withRoot(applyChain(self.root, w, empty))
176
176
 
177
177
  # The tree after the pointer event `e` (in tree coordinates; a key event changes
178
- # nothing): the topmost shown actor under it that says it is hit (as `hit` finds it)
178
+ # nothing): the topmost shown `Clickable` actor under it that says it is hit (as `hit`
179
- # gets it through `input`, then each of its parents up to the root. Each gets `e` in its
179
+ # finds it) gets it through `input`, then each of its parents up to the root, clickable
180
- # own coordinates (as `hit` gets its point) and its parent's context under `ctx` (as
180
+ # or not. Each gets `e` in its own coordinates (as `hit` gets its point) and its
181
- # `step` gives it). With no actor under the pointer the tree is returned as it was.
181
+ # parent's context under `ctx` (as `step` gives it). With no actor under the pointer
182
- # The hit actor is found first, with no context built (`hitPath`); then only the nodes
182
+ # the tree is returned as it was. The hit actor is found first, with no context built
183
- # on its path are walked again, each child's context made from its parent's.
183
+ # (`hitPath`); then only the nodes on its path are walked again, each child's context
184
+ # made from its parent's.
184
185
  fun input(self, ctx: Ctx[M], e: InputEvent) -> SceneTree[M] = match e.position()
185
186
  None => self
186
187
  Some(p) => match hitPath(self.root, p, 0)
@@ -196,8 +197,8 @@ struct SceneTree[M](root: FRoseTree[Actor[M]], camX: Float, camY: Float, camScal
196
197
  collectChain(self.root, Affine.Identity, 1.0, out)
197
198
  out
198
199
 
199
- # The topmost shown actor at a tree point that says it is hit there (`hit(p)`, with
200
+ # The topmost shown `Clickable` actor at a tree point that says it is hit there
200
- # `p` in the actor's own coordinates).
201
+ # (`hit(p)`, with `p` in the actor's own coordinates).
201
202
  fun hit(self, x: Float, y: Float) -> Option[Actor[M]] = hitChain(self.root, Vec2(x: x, y: y))
202
203
 
203
204
  # The id of that actor, if any.
@@ -433,21 +434,33 @@ fun toLocal(pl: Place, p: Vec2) -> Vec2 =
433
434
 
434
435
  # Where the actor `hitChain` finds under `p` is in the chain `t` (whose first node is the
435
436
  # `i`-th of its siblings): its index among its siblings at each depth, from the chain down.
437
+ # Only a `Clickable` actor can be hit: any other is skipped with no transform computed,
438
+ # unless it has children, whose coordinates its place gives.
436
439
  fun hitPath[M](t: FRoseTree[Actor[M]], p: Vec2, i: Int) -> Option[List[Int]] = match t
437
440
  FRoseEmpty => None
438
441
  FRoseNode(a, k, n) => match hitPath(n, p, i + 1)
439
442
  Some(path) => Some(path)
440
443
  None =>
444
+ # One tag test per node; a flag computed at spawn would replace it once comptime lands.
445
+ match a
446
+ Clickable as c =>
441
- if !isShown(a)
447
+ if !isShown(a)
442
- None
448
+ None
443
- else
449
+ else
444
- q := toLocal(a.place(), p)
450
+ q := toLocal(a.place(), p)
445
- below := if k.isEmpty() then None else hitPath(k, q, 0)
451
+ below := if k.isEmpty() then None else hitPath(k, q, 0)
446
- match below
452
+ match below
447
- Some(path) => Some(Cons(head: i, tail: path))
453
+ Some(path) => Some(Cons(head: i, tail: path))
448
- None =>
454
+ None =>
449
- nil: List[Int] := Nil
455
+ nil: List[Int] := Nil
450
- if a.hit(q) then Some(Cons(head: i, tail: nil)) else None
456
+ if c.hit(q) then Some(Cons(head: i, tail: nil)) else None
457
+ _ =>
458
+ if k.isEmpty() || !isShown(a)
459
+ None
460
+ else
461
+ match hitPath(k, toLocal(a.place(), p), 0)
462
+ Some(path) => Some(Cons(head: i, tail: path))
463
+ None => None
451
464
 
452
465
  # The chain `t` after the pointer event `e` at `p` (in the chain's parent's coordinates)
453
466
  # went to the actor at `i`, then `path` below it (as `hitPath` found it): that actor's
@@ -472,21 +485,26 @@ fun routeChain[M](t: FRoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent, i
472
485
  na := a.input(ctx, InputEvent.pointerAt(e, q))
473
486
  if ref.same(na, a) then t else FRoseNode(value: na, firstChild: k, nextSibling: n)
474
487
 
475
- # The topmost shown actor under `p` (a point in the chain's parent's coordinates) that
488
+ # The topmost shown `Clickable` actor under `p` (a point in the chain's parent's
476
- # says it is hit: later siblings first, and in each, its children before itself.
489
+ # coordinates) that says it is hit: later siblings first, and in each, its children before
490
+ # itself. Other actors are skipped as `hitPath` skips them.
477
491
  fun hitChain[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
478
492
  FRoseEmpty => None
479
493
  FRoseNode(a, k, n) =>
480
494
  match hitChain(n, p)
481
495
  Some(found) => Some(found)
482
496
  None =>
497
+ # One tag test per node; a flag computed at spawn would replace it once comptime lands.
498
+ match a
499
+ Clickable as c =>
483
- if isShown(a)
500
+ if isShown(a)
484
- q := toLocal(a.place(), p)
501
+ q := toLocal(a.place(), p)
485
- match hitChain(k, q)
502
+ match hitChain(k, q)
486
- Some(found) => Some(found)
503
+ Some(found) => Some(found)
487
- None => if a.hit(q) then Some(a) else None
504
+ None => if c.hit(q) then Some(a) else None
488
- else
505
+ else
489
- None
506
+ None
507
+ _ => if k.isEmpty() || !isShown(a) then None else hitChain(k, toLocal(a.place(), p))
490
508
 
491
509
  # --- tests ---
492
510
 
@@ -494,7 +512,7 @@ fun hitChain[M](t: FRoseTree[Actor[M]], p: Vec2) -> Option[Actor[M]] = match t
494
512
  # and four with behaviour.
495
513
 
496
514
  # A `w` by `w` box (a group when `w` is 0) with its own alpha and flags.
497
- struct TBody(id: Int, at: Place, w: Float, alpha: Float, visible: Bool, dead: Bool) is Actor[Int] =
515
+ struct TBody(id: Int, at: Place, w: Float, alpha: Float, visible: Bool, dead: Bool) is Actor[Int], Clickable =
498
516
  fun key(self) -> Int = self.id
499
517
  fun place(self) -> Place = self.at
500
518
  fun opacity(self) -> Float = self.alpha
@@ -504,7 +522,7 @@ struct TBody(id: Int, at: Place, w: Float, alpha: Float, visible: Bool, dead: Bo
504
522
  fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.w, p)
505
523
 
506
524
  # Moves by vx per second; dies when `ttl` runs out (never if it starts at -1).
507
- struct TDrifter(id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bool) is Actor[Int] =
525
+ struct TDrifter(id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bool) is Actor[Int], Clickable =
508
526
  fun key(self) -> Int = self.id
509
527
  fun place(self) -> Place = self.at
510
528
  fun shown(self) -> Bool = self.visible
@@ -535,7 +553,7 @@ struct TProbe(id: Int, at: Place, seen: Affine, seenA: Float) is Actor[Int] =
535
553
  TProbe(..self, seen: ctx.worldOf(self.at.local()), seenA: ctx.alphaOf(self.opacity()))
536
554
 
537
555
  # A 10 by 10 box at (x, 0) that counts the pointer events it gets.
538
- struct TClicker(id: Int, x: Float, clicks: Int) is Actor[Int] =
556
+ struct TClicker(id: Int, x: Float, clicks: Int) is Actor[Int], Clickable =
539
557
  fun key(self) -> Int = self.id
540
558
  fun place(self) -> Place = place.at(self.x, 0.0)
541
559
  fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
@@ -543,6 +561,16 @@ struct TClicker(id: Int, x: Float, clicks: Int) is Actor[Int] =
543
561
 
544
562
  fun tclicker(id: Int, x: Float) -> FRoseTree[Actor[Int]] = FRoseTree.leaf(TClicker(id: id, x: x, clicks: 0))
545
563
 
564
+ # Not `Clickable`, though it has a `hit` that says yes everywhere: a plain method the tree
565
+ # never calls. It counts the pointer events it gets (as a parent on a hit actor's path).
566
+ struct TPlain(id: Int, at: Place, inputs: Int) is Actor[Int] =
567
+ fun key(self) -> Int = self.id
568
+ fun place(self) -> Place = self.at
569
+ fun hit(self, p: Vec2) -> Bool = true
570
+ fun input(self, ctx: Ctx[Int], e: InputEvent) -> TPlain = TPlain(..self, inputs: self.inputs + 1)
571
+
572
+ fun tplain(id: Int, at: Place, kids: List[FRoseTree[Actor[Int]]]) -> FRoseTree[Actor[Int]] = FRoseTree.of(TPlain(id: id, at: at, inputs: 0), kids)
573
+
546
574
  # Pushes `Kill(target)` in each step.
547
575
  struct TKiller(id: Int, target: Int) is Actor[Int] =
548
576
  fun key(self) -> Int = self.id
@@ -863,6 +891,35 @@ test "a plain tree of std's Group and Box: add, step, draw list"
863
891
  assert s1.flatten().at(1).m.e == 10.0
864
892
  assert s1.hit(20.0, 10.0).unwrap().key() == 1
865
893
 
894
+ test "only a Clickable actor is hit: a plain one with a hit method never is, its clickable child is"
895
+ s := ttree().add(0, tplain(1, place.at(0.0, 0.0), [tclicker(2, 20.0)])).add(0, tplain(3, place.at(200.0, 0.0), []))
896
+ assert s.hitId(25.0, 5.0).unwrapOr(-1) == 2
897
+ assert s.hitId(5.0, 5.0).isNone() && s.hitId(205.0, 5.0).isNone()
898
+ assert TPlain(id: 9, at: place.at(0.0, 0.0), inputs: 0).hit(Vec2(x: 0.0, y: 0.0))
899
+ # A press on the plain parent alone goes nowhere; one on the child goes to it, then to
900
+ # the parent on its way up.
901
+ assert ref.same(s.input(Ctx[Int](), PointerDown(x: 5.0, y: 5.0)), s)
902
+ assert ref.same(s.input(Ctx[Int](), PointerDown(x: 205.0, y: 5.0)), s)
903
+ s1 := s.input(Ctx[Int](), PointerDown(x: 25.0, y: 5.0))
904
+ assert s1.findAs[TClicker](2).unwrap().clicks == 1
905
+ assert s1.findAs[TPlain](1).unwrap().inputs == 1
906
+ assert s1.findAs[TPlain](3).unwrap().inputs == 0
907
+
908
+ test "a clickable actor under a moved, scaled and turned plain parent is hit where it is drawn"
909
+ # The parent at (100, 0), doubled and turned a quarter: (x, y) in it is (100 - 2y, 2x).
910
+ s := ttree().add(0, tplain(1, place.turned(100.0, 0.0, 2.0, Float.HalfPi), [tclicker(2, 10.0)]))
911
+ # (2, 1) in the clicker is (12, 1) in the parent: (98, 24) in the tree.
912
+ assert s.hitId(98.0, 24.0).unwrapOr(-1) == 2
913
+ # (2, -1) in the clicker, just off it: (102, 24).
914
+ assert s.hitId(102.0, 24.0).isNone()
915
+ # Where an unturned parent would put it: nothing.
916
+ assert s.hitId(112.0, 1.0).isNone()
917
+ d := s.flatten()
918
+ q := d.at(2).m.apply(Vec2(x: 2.0, y: 1.0))
919
+ assert tnear(q.x, 98.0) && tnear(q.y, 24.0)
920
+ s1 := s.input(Ctx[Int](), PointerDown(x: 98.0, y: 24.0))
921
+ assert s1.findAs[TClicker](2).unwrap().clicks == 1 && s1.findAs[TPlain](1).unwrap().inputs == 1
922
+
866
923
  test "allAs gives every actor of a type in tree order, kidsAs one layer of it"
867
924
  s := ttree().add(0, tgroup(10, 0.0, 0.0, 1.0, 0.0, [trect(11, 0.0, 0.0, 1.0), tclicker(12, 0.0), trect(13, 0.0, 0.0, 1.0)])).add(0, trect(14, 0.0, 0.0, 1.0)).add(11, trect(15, 0.0, 0.0, 1.0))
868
925
  bodies := s.allAs[TBody]()
std/game/ui.plum CHANGED
@@ -27,7 +27,7 @@ import std/game/scene/SceneTree
27
27
  # A button `w` by `h` with its top-left at (x, y) that sends `onClick` when clicked.
28
28
  # `look` is how it shows the pointer, 0 idle, 1 hovered, 2 pressed; `armed` is whether a
29
29
  # press on it is held. Make one with `ui.button`.
30
- struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int, armed: Bool) is Actor[M] =
30
+ struct Button[M](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int, armed: Bool) is Actor[M], Clickable =
31
31
  fun key(self) -> Int = self.id
32
32
 
33
33
  fun place(self) -> Place = place.at(self.x, self.y)