plum

#treesitter#compiler#wasm

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

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


8b44046 — Peter John 2026-11-10T22:12:15+05:30
tests/port/game: pointer routing and button hover against a brute-force reference
Files changed (1) hide show
  1. tests/port/game/routing.plum +417 -0
tests/port/game/routing.plum ADDED
@@ -0,0 +1,417 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/Slice
7
+ import std/collections/List
8
+ import std/collections/RoseTree
9
+ import std/math/Vec2
10
+ import std/math/Affine
11
+ import std/game/input
12
+ import std/game/Place
13
+ import std/game/Actor
14
+ import std/game/Clickable
15
+ import std/game/Ctx
16
+ import std/game/SceneTree
17
+ import std/game/ui
18
+
19
+ # The scene tree's pointer routing against a brute-force reference. `SceneTree.input` finds
20
+ # the hit actor first (`hitPath`: only `Clickable` actors are tested, a translate-only
21
+ # place is a subtraction, a plain leaf is skipped with no transform), then walks only the
22
+ # hit actor's path. The reference knows nothing of that: from a flat table of what was
23
+ # built it gives every node its world transform (the product of the places above it),
24
+ # tests every clickable node whose ancestors are all shown at the point through the
25
+ # inverse of that transform, and takes the last one in draw order.
26
+ #
27
+ # Each random tree mixes clickable and plain nodes, hidden and gone ones, places that
28
+ # only move, that scale (also mirrored), and that turn and scale about a pivot, nested up
29
+ # to five deep, with boxes that overlap. The "exact" trees use whole-number moves and
30
+ # points only, where both sides compute without rounding, so a point exactly on a box's
31
+ # edge must give the same answer; in the others a point within 1e-6 of an edge is skipped.
32
+
33
+ # What an actor got: its id, the kind of event (0 down, 1 up, 2 move) and where, in its
34
+ # own coordinates.
35
+ struct Got(id: Int, kind: Int, x: Float, y: Float)
36
+
37
+ fun kindOf(e: InputEvent) -> Int = match e
38
+ PointerDown(_, _) => 0
39
+ PointerUp(_, _) => 1
40
+ _ => 2
41
+
42
+ # A clickable `w` by `h` box that counts and reports the events it gets.
43
+ struct RBox[Actor<Got>, Clickable](id: Int, at: Place, w: Float, h: Float, visible: Bool, dead: Bool, seen: Int) =
44
+ fun key(self) -> Int = self.id
45
+
46
+ fun place(self) -> Place = self.at
47
+
48
+ fun shown(self) -> Bool = self.visible
49
+
50
+ fun gone(self) -> Bool = self.dead
51
+
52
+ fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.h, p)
53
+
54
+ fun input(self, ctx: Ctx<Got>, e: InputEvent) -> RBox =
55
+ p := e.position().unwrap()
56
+ ctx.send(Got(id: self.id, kind: kindOf(e), x: p.x, y: p.y))
57
+ RBox(..self, seen: self.seen + 1)
58
+
59
+ # The same without `Clickable`: its `hit` says yes everywhere, and the tree must never ask.
60
+ struct RPlain[Actor<Got>](id: Int, at: Place, visible: Bool, dead: Bool, seen: Int) =
61
+ fun key(self) -> Int = self.id
62
+
63
+ fun place(self) -> Place = self.at
64
+
65
+ fun shown(self) -> Bool = self.visible
66
+
67
+ fun gone(self) -> Bool = self.dead
68
+
69
+ fun hit(self, p: Vec2) -> Bool = true
70
+
71
+ fun input(self, ctx: Ctx<Got>, e: InputEvent) -> RPlain =
72
+ p := e.position().unwrap()
73
+ ctx.send(Got(id: self.id, kind: kindOf(e), x: p.x, y: p.y))
74
+ RPlain(..self, seen: self.seen + 1)
75
+
76
+ # What was built, one entry per node in draw order (a node's id is its index): the
77
+ # reference reads only this.
78
+ struct Spec(parent: Int, at: Place, w: Float, h: Float, clickable: Bool, visible: Bool, dead: Bool)
79
+
80
+ # A small generator the tests can read: the same seed gives the same trees everywhere.
81
+ struct Gen(mut s: Int) =
82
+ fun next(self) -> Int =
83
+ self.s = {self.s * 1103515245 + 12345} % 2147483648
84
+ self.s / 65536
85
+
86
+ fun below(self, n: Int) -> Int = self.next() % n
87
+
88
+ # In [0, 1).
89
+ fun unit(self) -> Float = Float(self.next()) / 32768.0
90
+
91
+ fun chance(self, percent: Int) -> Bool = self.below(100) < percent
92
+
93
+ fun scaleOf(g: Gen) -> Float =
94
+ k := g.below(5)
95
+ if k == 0
96
+ 0.5
97
+ else if k == 1
98
+ 2.0
99
+ else if k == 2
100
+ -1.5
101
+ else if k == 3
102
+ 1.0
103
+ else
104
+ 0.75 + g.unit()
105
+
106
+ # A place: one that only moves (half of them; in an exact tree all, by whole numbers,
107
+ # some about a pivot, which is the same move off the tree's subtraction path), one that
108
+ # scales, or one that turns and scales about a pivot.
109
+ fun placeOf(g: Gen, exact: Bool) -> Place =
110
+ x := Float(g.below(200) - 60)
111
+ y := Float(g.below(200) - 60)
112
+ kind := g.below(8)
113
+ if exact
114
+ if kind < 6 then place.at(x, y) else place.at(x, y).pivotAt(Float(g.below(30)), Float(g.below(30)))
115
+ else if kind < 4
116
+ place.at(x + g.unit(), y)
117
+ else if kind < 6
118
+ sx := scaleOf(g)
119
+ sy := scaleOf(g)
120
+ place.at(x, y + g.unit()).scaleTo(sx, sy)
121
+ else
122
+ sx := scaleOf(g)
123
+ sy := scaleOf(g)
124
+ r := g.unit() * 6.0 - 3.0
125
+ place.at(x, y).scaleTo(sx, sy).rotateTo(r).pivotAt(Float(g.below(30)), Float(g.below(30)))
126
+
127
+ fun actorOf(id: Int, s: Spec, buttons: Bool) -> Actor<Got> =
128
+ if s.clickable && buttons
129
+ ui.button(id, s.at.x, s.at.y, s.w, s.h, "", Got(id: id, kind: -1, x: 0.0, y: 0.0))
130
+ else if s.clickable
131
+ RBox(id: id, at: s.at, w: s.w, h: s.h, visible: s.visible, dead: s.dead, seen: 0)
132
+ else
133
+ RPlain(id: id, at: s.at, visible: s.visible, dead: s.dead, seen: 0)
134
+
135
+ # A random node under `parent` with its subtree, each node noted in `specs` as it is made
136
+ # (so in draw order). With `buttons`, the clickable nodes are `ui.button`s, which are
137
+ # always shown and only move.
138
+ fun grow(g: Gen, specs: Slice<Spec>, parent: Int, depth: Int, exact: Bool, buttons: Bool) -> RoseTree<Actor<Got>> =
139
+ id := specs.length()
140
+ drawn := placeOf(g, exact)
141
+ w := Float(10 + g.below(120))
142
+ h := Float(10 + g.below(120))
143
+ clickable := g.chance(60)
144
+ button := clickable && buttons
145
+ at := if button then place.at(drawn.x, drawn.y) else drawn
146
+ visible := button || !g.chance(12)
147
+ dead := !button && g.chance(6)
148
+ s := Spec(parent: parent, at: at, w: w, h: h, clickable: clickable, visible: visible, dead: dead)
149
+ specs.push(s)
150
+ n := if depth == 0 then 2 + g.below(4) else if depth >= 4 then 0 else g.below(4)
151
+ kids := Slice<RoseTree<Actor<Got>>>()
152
+ for _ := range n
153
+ kids.push(grow(g, specs, id, depth + 1, exact, buttons))
154
+ RoseTree.of(actorOf(id, s, buttons), List.fromSlice(kids))
155
+
156
+ # The reference's view of every node: its world transform, and whether it and all its
157
+ # ancestors are shown and not gone.
158
+ struct World(m: Slice<Affine>, shown: Slice<Bool>)
159
+
160
+ fun worldOf(specs: Slice<Spec>) -> World =
161
+ m := Slice<Affine>()
162
+ shown := Slice<Bool>()
163
+ for i := range specs.length()
164
+ s := specs.at(i)
165
+ up := if s.parent < 0 then Affine.Identity else m.at(s.parent)
166
+ upShown := if s.parent < 0 then true else shown.at(s.parent)
167
+ m.push(up.mul(s.at.local()))
168
+ shown.push(upShown && s.visible && !s.dead)
169
+ World(m: m, shown: shown)
170
+
171
+ # The topmost node hit at `p`, -1 if none: every node is transformed and tested, and the
172
+ # last in draw order wins.
173
+ fun refHit(specs: Slice<Spec>, w: World, p: Vec2) -> Int =
174
+ 0.until(specs.length()).fold(-1, |best, i|
175
+ s := specs.at(i)
176
+ q := w.m.at(i).inverse().apply(p)
177
+ if s.clickable && w.shown.at(i) && actor.boxHit(s.w, s.h, q) then i else best
178
+ )
179
+
180
+ # Whether `p` is within 1e-6 of an edge of some clickable node's box, where rounding may
181
+ # decide the answer.
182
+ fun onAnEdge(specs: Slice<Spec>, w: World, p: Vec2) -> Bool =
183
+ 0.until(specs.length()).find(|i|
184
+ s := specs.at(i)
185
+ q := w.m.at(i).inverse().apply(p)
186
+ d := q.x.abs().min({q.x - s.w}.abs()).min(q.y.abs()).min({q.y - s.h}.abs())
187
+ s.clickable && d < 0.000001
188
+ ).isSome()
189
+
190
+ # A point: most often in or just around a random node's box (so that hits and edges are
191
+ # common), else anywhere.
192
+ fun pointOf(g: Gen, specs: Slice<Spec>, w: World, exact: Bool) -> Vec2 =
193
+ if g.chance(75)
194
+ i := g.below(specs.length())
195
+ s := specs.at(i)
196
+ local := if exact
197
+ lx := Float(g.below(Int(s.w) + 11) - 5)
198
+ ly := Float(g.below(Int(s.h) + 11) - 5)
199
+ Vec2(x: lx, y: ly)
200
+ else
201
+ lx := s.w * {g.unit() * 1.4 - 0.2}
202
+ ly := s.h * {g.unit() * 1.4 - 0.2}
203
+ Vec2(x: lx, y: ly)
204
+ w.m.at(i).apply(local)
205
+ else
206
+ x := Float(g.below(700) - 250)
207
+ y := Float(g.below(700) - 250)
208
+ Vec2(x: x, y: y)
209
+
210
+ fun eventOf(kind: Int, p: Vec2) -> InputEvent =
211
+ if kind == 0
212
+ PointerDown(x: p.x, y: p.y)
213
+ else if kind == 1
214
+ PointerUp(x: p.x, y: p.y)
215
+ else
216
+ PointerMove(x: p.x, y: p.y)
217
+
218
+ fun seenOf(a: Actor<Got>) -> Int = match a
219
+ RBox as b => b.seen
220
+ RPlain as q => q.seen
221
+ _ => -1000
222
+
223
+ fun close(a: Float, b: Float) -> Bool = {a - b}.abs() <= 0.000001 * {1.0 + b.abs()}
224
+
225
+ # What is wrong with the events the actors got, "" if nothing: they must be the hit node,
226
+ # then each of its parents up to the root, each with the event's kind and the point in its
227
+ # own coordinates.
228
+ fun pathError(specs: Slice<Spec>, w: World, got: List<Got>, hit: Int, kind: Int, p: Vec2, exact: Bool) -> Str = match got
229
+ Nil => if hit < 0 then "" else "node {hit} and its parents up got no event"
230
+ Cons(e, rest) =>
231
+ if hit < 0
232
+ "node {e.id} got an event past the root"
233
+ else if e.id != hit
234
+ "node {e.id} got the event where node {hit} was next"
235
+ else if e.kind != kind
236
+ "node {hit} got an event of kind {e.kind}, not {kind}"
237
+ else
238
+ q := w.m.at(hit).inverse().apply(p)
239
+ same := if exact then e.x == q.x && e.y == q.y else close(e.x, q.x) && close(e.y, q.y)
240
+ if same
241
+ pathError(specs, w, rest, specs.at(hit).parent, kind, p, exact)
242
+ else
243
+ "node {hit} got the point ({e.x}, {e.y}), the reference says ({q.x}, {q.y})"
244
+
245
+ # What the checks counted.
246
+ struct Tally(mut cases: Int, mut hits: Int, mut deep: Int, mut misses: Int, mut skipped: Int, mut edges: Int)
247
+
248
+ # One point on one tree: `hitId`, `hit` and `input` against the reference. "" if they
249
+ # agree, else what differs.
250
+ fun checkPoint(t: SceneTree<Got>, specs: Slice<Spec>, w: World, p: Vec2, kind: Int, exact: Bool, tally: Tally) -> Str =
251
+ want := refHit(specs, w, p)
252
+ ctx := Ctx<Got>()
253
+ after := t.input(ctx, eventOf(kind, p))
254
+ got := ctx.takeSends()
255
+ found := t.hitId(p.x, p.y).unwrapOr(-1)
256
+ viaHit := t.hit(p.x, p.y).map(|a| a.key()).unwrapOr(-1)
257
+ tally.cases = tally.cases + 1
258
+ if want >= 0
259
+ tally.hits = tally.hits + 1
260
+ if specs.at(want).parent > 0
261
+ tally.deep = tally.deep + 1
262
+ else
263
+ tally.misses = tally.misses + 1
264
+ seen := after.root.fold(0, |n, a| n + seenOf(a))
265
+ order := after.root.fold(0, |n, a| if a.key() == n then n + 1 else -1000000)
266
+ wrongPath := pathError(specs, w, got, want, kind, p, exact)
267
+ if found != want
268
+ "hitId gives {found}, the reference {want}"
269
+ else if viaHit != want
270
+ "hit gives {viaHit}, the reference {want}"
271
+ else if wrongPath != ""
272
+ wrongPath
273
+ else if seen != got.length()
274
+ "{got.length()} events were sent and the new tree's actors count {seen}"
275
+ else if order != specs.length()
276
+ "the tree after input has other actors, or another order"
277
+ else if want < 0 && !@sameRef(after, t)
278
+ "a miss returned another tree"
279
+ else if t.root.fold(0, |n, a| n + seenOf(a)) != 0
280
+ "input changed the tree it was called on"
281
+ else
282
+ ""
283
+
284
+ # `trees` random trees from `seed`, three points each. The first difference, "" if none.
285
+ fun checkTrees(seed: Int, trees: Int, exact: Bool, tally: Tally) -> Str =
286
+ g := Gen(s: seed)
287
+ 0.until(trees).fold("", |err, n|
288
+ if err != ""
289
+ err
290
+ else
291
+ specs := Slice<Spec>()
292
+ t := treeOf(grow(g, specs, -1, 0, exact, false))
293
+ w := worldOf(specs)
294
+ 0.until(3).fold("", |e, k|
295
+ p := pointOf(g, specs, w, exact)
296
+ kind := g.below(3)
297
+ edge := onAnEdge(specs, w, p)
298
+ if e != ""
299
+ e
300
+ else if edge && !exact
301
+ tally.skipped = tally.skipped + 1
302
+ ""
303
+ else
304
+ if edge
305
+ tally.edges = tally.edges + 1
306
+ why := checkPoint(t, specs, w, p, kind, exact, tally)
307
+ if why == "" then "" else "tree {n} of seed {seed} ({specs.length()} nodes), point ({p.x}, {p.y}): {why}"
308
+ )
309
+ )
310
+
311
+ fun treeOf(root: RoseTree<Actor<Got>>) -> SceneTree<Got> =
312
+ SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
313
+
314
+ # Whether node `i` and all its ancestors are not gone (so `step` keeps it), from the specs.
315
+ fun kept(specs: Slice<Spec>, i: Int) -> Bool =
316
+ if i < 0 then true else !specs.at(i).dead && kept(specs, specs.at(i).parent)
317
+
318
+ # A button's look after a step with the pointer at `p` and the mouse up, against the
319
+ # reference: hovered (1) exactly when `p` is in its box through its world transform,
320
+ # whatever is drawn over it and whether a parent is hidden (a button's `step` tests only
321
+ # itself). "" if every kept button agrees.
322
+ fun hoverError(t: SceneTree<Got>, specs: Slice<Spec>, w: World, p: Vec2) -> Str =
323
+ i := Input(held: Held(mouse: false, keys: Slice<Int>()), events: Slice<InputEvent>(), pos: p, wheel: 0.0)
324
+ ctx: Ctx<Got> := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
325
+ s := t.step(ctx, 1.0 / 60.0)
326
+ 0.until(specs.length()).fold("", |err, n|
327
+ sp := specs.at(n)
328
+ if err != "" || !sp.clickable || !kept(specs, n)
329
+ err
330
+ else
331
+ want := if actor.boxHit(sp.w, sp.h, w.m.at(n).inverse().apply(p)) then 1 else 0
332
+ match s.findAs<Button<Got>>(n)
333
+ Some(b) => if b.look == want then "" else "button {n} looks {b.look}, the reference says {want}"
334
+ None => "button {n} is not on the stepped tree"
335
+ )
336
+
337
+ # `trees` random trees of buttons from `seed`, three pointer positions each; the hovered
338
+ # ones counted in `tally.hits`. The first difference, "" if none.
339
+ fun checkHover(seed: Int, trees: Int, tally: Tally) -> Str =
340
+ g := Gen(s: seed)
341
+ 0.until(trees).fold("", |err, n|
342
+ if err != ""
343
+ err
344
+ else
345
+ specs := Slice<Spec>()
346
+ t := treeOf(grow(g, specs, -1, 0, false, true))
347
+ w := worldOf(specs)
348
+ 0.until(3).fold("", |e, k|
349
+ p := pointOf(g, specs, w, false)
350
+ if e != ""
351
+ e
352
+ else if onAnEdge(specs, w, p)
353
+ tally.skipped = tally.skipped + 1
354
+ ""
355
+ else
356
+ tally.cases = tally.cases + 1
357
+ if refHit(specs, w, p) >= 0
358
+ tally.hits = tally.hits + 1
359
+ why := hoverError(t, specs, w, p)
360
+ if why == "" then "" else "tree {n} of seed {seed} ({specs.length()} nodes), point ({p.x}, {p.y}): {why}"
361
+ )
362
+ )
363
+
364
+ fun newTally() -> Tally = Tally(cases: 0, hits: 0, deep: 0, misses: 0, skipped: 0, edges: 0)
365
+
366
+ test "routing agrees with the brute-force reference on 600 random trees of moved, scaled and turned places"
367
+ tally := newTally()
368
+ assert checkTrees(1, 300, false, tally) == ""
369
+ assert checkTrees(20261110, 300, false, tally) == ""
370
+ # 1800 points less the few on an edge; hits (many below the root's children) and misses both
371
+ assert tally.cases + tally.skipped == 1800 && tally.skipped < 40
372
+ assert tally.hits > 400 && tally.deep > 200 && tally.misses > 200
373
+
374
+ test "routing agrees with the reference exactly on 500 trees of whole-number moves, edges included"
375
+ tally := newTally()
376
+ assert checkTrees(7, 250, true, tally) == ""
377
+ assert checkTrees(99, 250, true, tally) == ""
378
+ assert tally.cases == 1500 && tally.skipped == 0
379
+ assert tally.hits > 400 && tally.deep > 200 && tally.misses > 200
380
+ # points exactly on a box's edge were among them
381
+ assert tally.edges > 50
382
+
383
+ test "the reference itself: a hidden parent hides its children, the last drawn wins"
384
+ specs := Slice<Spec>()
385
+ specs.push(Spec(parent: -1, at: place.at(0.0, 0.0), w: 0.0, h: 0.0, clickable: false, visible: true, dead: false))
386
+ specs.push(Spec(parent: 0, at: place.at(0.0, 0.0), w: 50.0, h: 50.0, clickable: true, visible: true, dead: false))
387
+ specs.push(Spec(parent: 0, at: place.at(10.0, 0.0), w: 50.0, h: 50.0, clickable: false, visible: false, dead: false))
388
+ specs.push(Spec(parent: 2, at: place.at(0.0, 0.0), w: 50.0, h: 50.0, clickable: true, visible: true, dead: false))
389
+ specs.push(Spec(parent: 0, at: place.at(40.0, 0.0), w: 50.0, h: 50.0, clickable: true, visible: true, dead: false))
390
+ w := worldOf(specs)
391
+ assert refHit(specs, w, Vec2(x: 20.0, y: 20.0)) == 1
392
+ assert refHit(specs, w, Vec2(x: 45.0, y: 20.0)) == 4
393
+ assert refHit(specs, w, Vec2(x: 200.0, y: 20.0)) == -1
394
+ assert onAnEdge(specs, w, Vec2(x: 50.0, y: 20.0)) && !onAnEdge(specs, w, Vec2(x: 45.0, y: 20.0))
395
+
396
+ test "a button's hover agrees with the reference on 400 random trees under moved, scaled and turned parents"
397
+ tally := newTally()
398
+ assert checkHover(3, 200, tally) == ""
399
+ assert checkHover(4242, 200, tally) == ""
400
+ assert tally.cases + tally.skipped == 1200 && tally.skipped < 30
401
+ assert tally.hits > 300
402
+
403
+ test "routing agrees with the reference on trees of buttons too"
404
+ tally := newTally()
405
+ g := Gen(s: 11)
406
+ err := 0.until(200).fold("", |e, n|
407
+ specs := Slice<Spec>()
408
+ t := treeOf(grow(g, specs, -1, 0, false, true))
409
+ w := worldOf(specs)
410
+ p := pointOf(g, specs, w, false)
411
+ if e != "" || onAnEdge(specs, w, p)
412
+ e
413
+ else
414
+ hitNow := t.hitId(p.x, p.y).unwrapOr(-1)
415
+ if hitNow == refHit(specs, w, p) then "" else "tree {n}: hitId {hitNow}, the reference {refHit(specs, w, p)}"
416
+ )
417
+ assert err == ""