plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
987ff11
— Peter John
2026-11-12T22:52:08+05:30
checker: a subtrait may give a supertrait's method a default of its own
- benchmarks/scene_trees/master/game_enum_tree_kept.plum +0 -297
- benchmarks/scene_trees/run.py +0 -138
- benchmarks/scene_trees/scene_tree.plum +0 -340
- compiler/checker/src/traits.rs +27 -4
- compiler/core/src/trait_defaults.rs +29 -0
- compiler/game/web-test/fixtures/stress_scene_port.plum +0 -144
- compiler/game/web-test/fixtures/stress_world.plum +0 -132
- examples/games/kids/balloon_pop.plum +0 -458
- examples/games/orb_run.plum +0 -1031
- examples/games/{assets → orbitrunner/assets}/gameover.wav +0 -0
- examples/games/{assets → orbitrunner/assets}/hit.wav +0 -0
- examples/games/{assets → orbitrunner/assets}/music.wav +0 -0
- examples/games/{assets → orbitrunner/assets}/pickup.wav +0 -0
- examples/games/{assets → orbitrunner/assets}/sprites.png +0 -0
- std/game/Clickable.plum +0 -13
- std/game/Ctx.plum +0 -188
- std/game/SceneTree.plum +0 -1003
- std/game/Store.plum +0 -116
- std/game/ui.plum +0 -193
- tests/traits/subtrait_defaults.plum +78 -0
benchmarks/scene_trees/master/game_enum_tree_kept.plum
DELETED
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Float
|
|
3
|
-
import std/Bool
|
|
4
|
-
import std/Str
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/Option
|
|
7
|
-
import std/collections/List
|
|
8
|
-
import std/math/Vec2
|
|
9
|
-
import std/math/Affine
|
|
10
|
-
import std/game/Color
|
|
11
|
-
import std/game_enum_tree/ETree
|
|
12
|
-
import std/game_enum_tree/EBody
|
|
13
|
-
import std/game_enum_tree/ECtx
|
|
14
|
-
import std/game_enum_tree/EGroup
|
|
15
|
-
import std/game_enum_tree/ERect
|
|
16
|
-
import std/game_enum_tree/EStage
|
|
17
|
-
|
|
18
|
-
# A copy of master's benchmarks/scene_trees/game_enum_tree.plum (at e0ccfc7) with two more
|
|
19
|
-
# workloads, 8 and 9: 1 and 2 with the last 60 stages kept in a ring, the snapshot variant
|
|
20
|
-
# the branch's version also runs. Build it with master's compiler and master's std
|
|
21
|
-
# (benchmarks/scene_trees/run.py does). The rest of this header is master's.
|
|
22
|
-
#
|
|
23
|
-
# Scene-tree benchmark, std/game_enum_tree version: a persistent tree of immutable bodies,
|
|
24
|
-
# referred to by id; every step makes a new tree.
|
|
25
|
-
# The three versions (game.plum, game_tree.plum, game_enum_tree.plum) build the same scene
|
|
26
|
-
# from the same random numbers, do the same work and print the same checksum; see
|
|
27
|
-
# docs/benchmarks/2026-11-08-scene-trees.md and run.py. With two arguments, a workload and
|
|
28
|
-
# N (`plum run game.plum -- 1 10000`), it runs that one, otherwise all seven at N = 100.
|
|
29
|
-
#
|
|
30
|
-
# The scene: a root, 10 groups (moved, scaled and turned), and N - 11 leaves, 20 by 20
|
|
31
|
-
# rectangles, spread over the groups in turn. Workloads:
|
|
32
|
-
# 1 step: 1000 ticks; every leaf moves by its velocity and bounces in its group's box.
|
|
33
|
-
# 2 churn: 1000 ticks; a step, then 1% of the leaves (at least one) die and as many are
|
|
34
|
-
# born, picked and placed by the same random numbers.
|
|
35
|
-
# 3 draw: 1000 flattens of the tree to the draw list, with transforms.
|
|
36
|
-
# 4 hit: 1000 hit tests at random stage points.
|
|
37
|
-
# Variants that split step's cost (a version a variant doesn't apply to runs its base):
|
|
38
|
-
# 5 step, no transforms: the tree versions walk with one context for every node, so no
|
|
39
|
-
# node's world transform is computed; std/game's is the same as 1.
|
|
40
|
-
# 6 step, eager transforms: every node's world transform (parent * local()) is computed
|
|
41
|
-
# each tick: std/game's walk computes it, the tree versions' walk asks every
|
|
42
|
-
# node's lazy context for it (`ctx.world()`).
|
|
43
|
-
# 7 churn, apply after: std/game_enum_tree pushes the tick's kills and spawns after its
|
|
44
|
-
# step and applies them with a second walk (`EStage.apply`), as before T30;
|
|
45
|
-
# std/game and std/game_tree run 2.
|
|
46
|
-
|
|
47
|
-
struct Rng(s: Int) =
|
|
48
|
-
fun next(&self, k: Int) -> Int
|
|
49
|
-
self.s = {self.s * 1103515245 + 12345} % 2147483648
|
|
50
|
-
return {self.s / 65536} % k
|
|
51
|
-
|
|
52
|
-
fun float(&self, k: Int) -> Float
|
|
53
|
-
return Float(self.next(k * 10)) / 10.0
|
|
54
|
-
|
|
55
|
-
struct Leaf(EBody(id, x, y, width, height, originX, originY, scaleX, scaleY, rotation, color, visible, dead), vx: Float, vy: Float) =
|
|
56
|
-
override fun step(self, ctx: ECtx, dt: Float) -> EBody
|
|
57
|
-
nx := self.x + self.vx * dt
|
|
58
|
-
ny := self.y + self.vy * dt
|
|
59
|
-
vx := self.vx
|
|
60
|
-
vy := self.vy
|
|
61
|
-
if nx < 0.0 || nx > 200.0
|
|
62
|
-
vx = 0.0 - vx
|
|
63
|
-
if ny < 0.0 || ny > 200.0
|
|
64
|
-
vy = 0.0 - vy
|
|
65
|
-
return Leaf(..self, x: nx, y: ny, vx: vx, vy: vy)
|
|
66
|
-
|
|
67
|
-
struct Bench(stage: EStage, live: List[Int], rng: Rng, nextId: Int)
|
|
68
|
-
|
|
69
|
-
fun newLeaf(rng: Rng, id: Int) -> ETree[EBody]
|
|
70
|
-
x := rng.float(200)
|
|
71
|
-
y := rng.float(200)
|
|
72
|
-
vx := rng.float(100) - 50.0
|
|
73
|
-
vy := rng.float(100) - 50.0
|
|
74
|
-
b: EBody := Leaf(
|
|
75
|
-
id: id, x: x, y: y, width: 20.0, height: 20.0, originX: 0.0, originY: 0.0,
|
|
76
|
-
scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.Red, visible: true, dead: false,
|
|
77
|
-
vx: vx, vy: vy)
|
|
78
|
-
return etree.leaf(b)
|
|
79
|
-
|
|
80
|
-
# Built bottom up, as a persistent tree is: each group's children first, then the groups
|
|
81
|
-
# under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
|
|
82
|
-
fun build(n: Int) -> Bench
|
|
83
|
-
rng := Rng(s: 12345)
|
|
84
|
-
kids := List[List[ETree[EBody]]]()
|
|
85
|
-
for g := range 10
|
|
86
|
-
kids.push(List[ETree[EBody]]())
|
|
87
|
-
live := List[Int]()
|
|
88
|
-
for i := range n - 11
|
|
89
|
-
l := newLeaf(rng, 11 + i)
|
|
90
|
-
kids.at(i % 10).push(l)
|
|
91
|
-
live.push(11 + i)
|
|
92
|
-
groups := List[ETree[EBody]]()
|
|
93
|
-
for g := range 10
|
|
94
|
-
s := 1.0 + 0.05 * Float(g)
|
|
95
|
-
gb: EBody := EGroup.turned(g + 1, Float(100 + 300 * {g % 5}), Float(100 + 300 * {g / 5}), s, 0.1 * Float(g))
|
|
96
|
-
groups.push(etree.of(gb, kids.at(g)))
|
|
97
|
-
stage := EStage.create()
|
|
98
|
-
stage = stage.withRoot(stage.root.addChildren(groups))
|
|
99
|
-
return Bench(stage: stage, live: live, rng: rng, nextId: n)
|
|
100
|
-
|
|
101
|
-
# Every node's position, in preorder, folded into one number.
|
|
102
|
-
fun hashTree(t: ETree[EBody], h: Int) -> Int
|
|
103
|
-
return t.fold(h, |r0, b|
|
|
104
|
-
r := {r0 * 31 + Int(b.x * 1000.0)} % 1000000007
|
|
105
|
-
return {r * 31 + Int(b.y * 1000.0)} % 1000000007
|
|
106
|
-
)
|
|
107
|
-
|
|
108
|
-
# EStage.step's walk (estepChain) with one context, `ctx`, for every body instead of
|
|
109
|
-
# `ctx.under(b)`: no world transform is computed. Otherwise the same: a new body and link
|
|
110
|
-
# node for every changed one, the unchanged tail of a chain shared.
|
|
111
|
-
fun stepFlat(t: ETree[EBody], ctx: ECtx, dt: Float) -> ETree[EBody]
|
|
112
|
-
vals := List[EBody]()
|
|
113
|
-
kids := List[ETree[EBody]]()
|
|
114
|
-
upTo := 0
|
|
115
|
-
tail := t
|
|
116
|
-
cur := t
|
|
117
|
-
while ENode(b, k, n) := cur
|
|
118
|
-
keep := false
|
|
119
|
-
if !b.dead
|
|
120
|
-
nb := b.step(ctx, dt)
|
|
121
|
-
if !nb.dead
|
|
122
|
-
keep = true
|
|
123
|
-
k2 := k
|
|
124
|
-
if !k.isEmpty()
|
|
125
|
-
k2 = stepFlat(k, ctx, dt)
|
|
126
|
-
vals.push(nb)
|
|
127
|
-
kids.push(k2)
|
|
128
|
-
if nb != b || k2 != k
|
|
129
|
-
upTo = vals.length()
|
|
130
|
-
tail = n
|
|
131
|
-
if !keep
|
|
132
|
-
upTo = vals.length()
|
|
133
|
-
tail = n
|
|
134
|
-
cur = n
|
|
135
|
-
if tail == t
|
|
136
|
-
return t
|
|
137
|
-
return etree.etreeLink(vals, kids, upTo, tail)
|
|
138
|
-
|
|
139
|
-
# EStage.step's walk (estepChain, without commands) with every body asking for its world
|
|
140
|
-
# transform: what the step costs when every body reads `ctx.world()`.
|
|
141
|
-
fun stepEager(t: ETree[EBody], ctx: ECtx, dt: Float) -> ETree[EBody]
|
|
142
|
-
vals := List[EBody]()
|
|
143
|
-
kids := List[ETree[EBody]]()
|
|
144
|
-
upTo := 0
|
|
145
|
-
tail := t
|
|
146
|
-
cur := t
|
|
147
|
-
c := ctx
|
|
148
|
-
first := true
|
|
149
|
-
seen := 0.0
|
|
150
|
-
while ENode(b, k, n) := cur
|
|
151
|
-
keep := false
|
|
152
|
-
if !b.dead
|
|
153
|
-
if first
|
|
154
|
-
c = ctx.under(b)
|
|
155
|
-
first = false
|
|
156
|
-
else
|
|
157
|
-
c.retarget(ctx, b)
|
|
158
|
-
seen = seen + c.world().e
|
|
159
|
-
nb := b.step(c, dt)
|
|
160
|
-
if !nb.dead
|
|
161
|
-
keep = true
|
|
162
|
-
k2 := k
|
|
163
|
-
if !k.isEmpty()
|
|
164
|
-
k2 = stepEager(k, c, dt)
|
|
165
|
-
vals.push(nb)
|
|
166
|
-
kids.push(k2)
|
|
167
|
-
if nb != b || k2 != k
|
|
168
|
-
upTo = vals.length()
|
|
169
|
-
tail = n
|
|
170
|
-
if !keep
|
|
171
|
-
upTo = vals.length()
|
|
172
|
-
tail = n
|
|
173
|
-
cur = n
|
|
174
|
-
# never true; it keeps the transforms in use
|
|
175
|
-
if seen < -1.0e30
|
|
176
|
-
return t
|
|
177
|
-
if tail == t
|
|
178
|
-
return t
|
|
179
|
-
return etree.etreeLink(vals, kids, upTo, tail)
|
|
180
|
-
|
|
181
|
-
# Keeps `stage` in `kept`, a ring of the last 60 stages.
|
|
182
|
-
fun keepStage(kept: List[EStage], stage: EStage, t: Int)
|
|
183
|
-
if kept.length() < 60
|
|
184
|
-
kept.push(stage)
|
|
185
|
-
else
|
|
186
|
-
_ := kept.set(t % 60, stage)
|
|
187
|
-
|
|
188
|
-
# Runs workload `w` on `sc`, a scene of `n` nodes, and returns its checksum.
|
|
189
|
-
fun work(sc: Bench, wl: Int, n: Int) -> Int
|
|
190
|
-
dt := 1.0 / 60.0
|
|
191
|
-
sum := 0
|
|
192
|
-
ctx := ECtx.blank()
|
|
193
|
-
stage := sc.stage
|
|
194
|
-
nextId := sc.nextId
|
|
195
|
-
w := wl
|
|
196
|
-
# 8 and 9: 1 and 2 with the last 60 stages kept in a ring
|
|
197
|
-
kept := List[EStage]()
|
|
198
|
-
keepOn := false
|
|
199
|
-
if w == 8
|
|
200
|
-
w = 1
|
|
201
|
-
keepOn = true
|
|
202
|
-
if w == 9
|
|
203
|
-
w = 2
|
|
204
|
-
keepOn = true
|
|
205
|
-
if w == 6
|
|
206
|
-
for t := range 1000
|
|
207
|
-
stage = stage.withRoot(stepEager(stage.root, ctx, dt))
|
|
208
|
-
sum = hashTree(stage.root, 0)
|
|
209
|
-
if w == 5
|
|
210
|
-
for t := range 1000
|
|
211
|
-
stage = stage.withRoot(stepFlat(stage.root, ctx, dt))
|
|
212
|
-
sum = hashTree(stage.root, 0)
|
|
213
|
-
if w == 1
|
|
214
|
-
for t := range 1000
|
|
215
|
-
if keepOn
|
|
216
|
-
keepStage(kept, stage, t)
|
|
217
|
-
stage = stage.step(ctx, dt)
|
|
218
|
-
sum = hashTree(stage.root, 0)
|
|
219
|
-
if w == 2 || w == 7
|
|
220
|
-
k := {n - 11} / 100
|
|
221
|
-
if k < 1
|
|
222
|
-
k = 1
|
|
223
|
-
for t := range 1000
|
|
224
|
-
# churn: the tick's kills and spawns are pushed before the step, which applies them
|
|
225
|
-
# in its own walk (after the bodies' steps, as `apply` would); 7 pushes them after
|
|
226
|
-
# the step and applies them with a second walk, `apply`. The picks depend only on
|
|
227
|
-
# the random numbers and the live list, so both make the same tree.
|
|
228
|
-
if keepOn
|
|
229
|
-
keepStage(kept, stage, t)
|
|
230
|
-
if w == 7
|
|
231
|
-
stage = stage.step(ctx, dt)
|
|
232
|
-
for j := range k
|
|
233
|
-
i := sc.rng.next(sc.live.length())
|
|
234
|
-
victim := sc.live.at(i)
|
|
235
|
-
_ := sc.live.set(i, sc.live.at(sc.live.length() - 1))
|
|
236
|
-
_ := sc.live.pop()
|
|
237
|
-
ctx.out.push(EKill(id: victim))
|
|
238
|
-
for j := range k
|
|
239
|
-
g := sc.rng.next(10)
|
|
240
|
-
id := nextId
|
|
241
|
-
nextId = id + 1
|
|
242
|
-
ctx.out.push(ESpawn(parent: g + 1, node: newLeaf(sc.rng, id)))
|
|
243
|
-
sc.live.push(id)
|
|
244
|
-
if w == 7
|
|
245
|
-
stage = stage.apply(ctx.out)
|
|
246
|
-
ctx.out.clear()
|
|
247
|
-
else
|
|
248
|
-
stage = stage.step(ctx, dt)
|
|
249
|
-
sum = hashTree(stage.root, 0) + sc.live.length()
|
|
250
|
-
if w == 3
|
|
251
|
-
total := 0
|
|
252
|
-
last := 0.0
|
|
253
|
-
for r := range 1000
|
|
254
|
-
d := stage.flatten()
|
|
255
|
-
total = total + d.length()
|
|
256
|
-
if r == 999
|
|
257
|
-
for e := range d
|
|
258
|
-
last = last + e.m.e + e.m.f
|
|
259
|
-
sum = total + Int(last)
|
|
260
|
-
if w == 4
|
|
261
|
-
for q := range 1000
|
|
262
|
-
x := sc.rng.float(1600)
|
|
263
|
-
y := sc.rng.float(800)
|
|
264
|
-
if Some(a) := stage.hit(x, y)
|
|
265
|
-
sum = {sum * 31 + Int(a.x * 100.0) + 7 * Int(a.y * 100.0)} % 1000000007
|
|
266
|
-
else
|
|
267
|
-
sum = {sum * 31 + 1} % 1000000007
|
|
268
|
-
return sum
|
|
269
|
-
|
|
270
|
-
# Builds the scene, then times the workload alone with the wall clock.
|
|
271
|
-
fun run(w: Int, n: Int, io: Io) -> Int
|
|
272
|
-
sc := build(n)
|
|
273
|
-
t0 := io.nowMicros()
|
|
274
|
-
sum := work(sc, w, n)
|
|
275
|
-
us := io.nowMicros() - t0
|
|
276
|
-
io.printLn("game_enum_tree w{w} n{n} ms {Float(us) / 1000.0} checksum {sum}")
|
|
277
|
-
return sum
|
|
278
|
-
|
|
279
|
-
fun main(io: Io)
|
|
280
|
-
args := io.args()
|
|
281
|
-
if args.length() == 2
|
|
282
|
-
_ := run(Int.parse(args.at(0)).unwrap(), Int.parse(args.at(1)).unwrap(), io)
|
|
283
|
-
else
|
|
284
|
-
for w := range 7
|
|
285
|
-
_ := run(w + 1, 100, io)
|
|
286
|
-
|
|
287
|
-
# The same checksums in all three versions (game.plum, game_tree.plum, game_enum_tree.plum).
|
|
288
|
-
test "the nine workloads at N = 100 give the shared checksums"
|
|
289
|
-
assert work(build(100), 1, 100) == 809683012
|
|
290
|
-
assert work(build(100), 2, 100) == 998134459
|
|
291
|
-
assert work(build(100), 3, 100) == 211827
|
|
292
|
-
assert work(build(100), 4, 100) == 462421202
|
|
293
|
-
assert work(build(100), 5, 100) == 809683012
|
|
294
|
-
assert work(build(100), 6, 100) == 809683012
|
|
295
|
-
assert work(build(100), 7, 100) == 998134459
|
|
296
|
-
assert work(build(100), 8, 100) == 809683012
|
|
297
|
-
assert work(build(100), 9, 100) == 998134459
|
benchmarks/scene_trees/run.py
DELETED
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""Times the persistent scene tree on this branch, on its own or against master's three
|
|
3
|
-
scene trees.
|
|
4
|
-
|
|
5
|
-
usage: python3 benchmarks/scene_trees/run.py [--runs 5] [--sizes 100,1000,10000]
|
|
6
|
-
[--workloads 1,...,11] [--out target/scene_trees]
|
|
7
|
-
[--plum target/debug/plum]
|
|
8
|
-
[--master DIR [--master-plum DIR/target/debug/plum]]
|
|
9
|
-
|
|
10
|
-
Run from the repository root of this branch, after `cargo build -p plum-cli`. By default
|
|
11
|
-
only the branch's three builds run (a quick run: `--runs 1 --sizes 100,1000`). With
|
|
12
|
-
`--master`, a checkout of master (e0ccfc7 or later) with its compiler built
|
|
13
|
-
(`cargo build -p plum-cli` there), master's three programs run too; a copy made with
|
|
14
|
-
`git archive` works, and keeps the build out of your own master checkout:
|
|
15
|
-
|
|
16
|
-
mkdir -p target/master-src
|
|
17
|
-
git archive e0ccfc7 | tar -x -C target/master-src # from a clone that has master
|
|
18
|
-
(cd target/master-src && cargo build -p plum-cli)
|
|
19
|
-
python3 benchmarks/scene_trees/run.py --master target/master-src
|
|
20
|
-
|
|
21
|
-
Versions:
|
|
22
|
-
game, game_tree master's benchmarks/scene_trees/game.plum and game_tree.plum
|
|
23
|
-
enum_tree benchmarks/scene_trees/master/game_enum_tree_kept.plum: master's
|
|
24
|
-
game_enum_tree.plum plus workloads 8 and 9 (master's compiler)
|
|
25
|
-
branch benchmarks/scene_trees/scene_tree.plum, this branch's default
|
|
26
|
-
branch --no-fbip the same without in-place updates or cell reuse
|
|
27
|
-
branch --no-fusion the same without fusion
|
|
28
|
-
|
|
29
|
-
Each is built once with `plum build` (a native executable that runs the wasm under
|
|
30
|
-
wasmtime). Then every (workload, N, version) runs once per round, in a rotated order, for
|
|
31
|
-
`--runs` rounds, each a fresh process. Every program takes the workload and N as
|
|
32
|
-
arguments and times with the microsecond clock. The table gives the median ms with the
|
|
33
|
-
range, and fails if two runs that should agree print different checksums. Workloads 8 and 9 (snapshots kept) only run on the persistent trees,
|
|
34
|
-
and 10 and 11 (mostly still: 1% of the leaves move, spread over the groups or all in one)
|
|
35
|
-
only on the branch: master's programs have no still leaves.
|
|
36
|
-
"""
|
|
37
|
-
import argparse
|
|
38
|
-
import os
|
|
39
|
-
import re
|
|
40
|
-
import statistics
|
|
41
|
-
import subprocess
|
|
42
|
-
import sys
|
|
43
|
-
|
|
44
|
-
WORKLOADS = {1: "step", 2: "churn", 3: "draw", 4: "hit",
|
|
45
|
-
5: "step, no transforms", 6: "step, eager transforms", 7: "churn, apply after",
|
|
46
|
-
8: "step, 60 kept", 9: "churn, 60 kept", 10: "mostly still", 11: "mostly still, one group"}
|
|
47
|
-
MASTER = ["game", "game_tree", "enum_tree"]
|
|
48
|
-
BRANCH = [("branch", []), ("branch --no-fbip", ["--no-fbip"]), ("branch --no-fusion", ["--no-fusion"])]
|
|
49
|
-
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
def fmt(ms):
|
|
53
|
-
"""Whole ms from 10 ms up, one decimal below."""
|
|
54
|
-
return f"{ms:.0f}" if ms >= 10 else f"{ms:.1f}"
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
def build(plum, src, exe, flags, cwd, lib=None):
|
|
58
|
-
cmd = [plum, "build", *flags, src, "-o", exe]
|
|
59
|
-
if lib:
|
|
60
|
-
cmd += ["--lib-path", lib]
|
|
61
|
-
subprocess.run(cmd, check=True, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def main():
|
|
65
|
-
ap = argparse.ArgumentParser()
|
|
66
|
-
ap.add_argument("--master", help="a built checkout of master, to compare against")
|
|
67
|
-
ap.add_argument("--runs", type=int, default=5)
|
|
68
|
-
ap.add_argument("--sizes", default="100,1000,10000")
|
|
69
|
-
ap.add_argument("--workloads", default="1,2,3,4,5,6,7,8,9,10,11")
|
|
70
|
-
ap.add_argument("--out", default="target/scene_trees")
|
|
71
|
-
ap.add_argument("--plum", default="target/debug/plum", help="this branch's compiler")
|
|
72
|
-
ap.add_argument("--master-plum", help="master's compiler (default: DIR/target/debug/plum)")
|
|
73
|
-
args = ap.parse_args()
|
|
74
|
-
if args.master_plum and not args.master:
|
|
75
|
-
sys.exit("--master-plum needs --master")
|
|
76
|
-
plum = os.path.abspath(args.plum)
|
|
77
|
-
out = os.path.abspath(args.out)
|
|
78
|
-
os.makedirs(out, exist_ok=True)
|
|
79
|
-
exes = {}
|
|
80
|
-
masters = []
|
|
81
|
-
if args.master:
|
|
82
|
-
master = os.path.abspath(args.master)
|
|
83
|
-
mplum = os.path.abspath(args.master_plum) if args.master_plum else os.path.join(master, "target/debug/plum")
|
|
84
|
-
srcs = {v: os.path.join(master, "benchmarks/scene_trees", v + ".plum") for v in ("game", "game_tree")}
|
|
85
|
-
srcs["enum_tree"] = os.path.join(HERE, "master/game_enum_tree_kept.plum")
|
|
86
|
-
for v in MASTER:
|
|
87
|
-
# A master program that is gone or no longer builds there is left out, and said so.
|
|
88
|
-
exes[v] = os.path.join(out, "m_" + v)
|
|
89
|
-
try:
|
|
90
|
-
build(mplum, srcs[v], exes[v], [], master, master if v == "enum_tree" else None)
|
|
91
|
-
masters.append(v)
|
|
92
|
-
except subprocess.CalledProcessError:
|
|
93
|
-
print(f"master {v}: {srcs[v]} does not build on master, left out", file=sys.stderr)
|
|
94
|
-
for name, flags in BRANCH:
|
|
95
|
-
exes[name] = os.path.join(out, "b" + "".join(flags).replace("-", "_"))
|
|
96
|
-
build(plum, os.path.join(HERE, "scene_tree.plum"), exes[name], flags, ".")
|
|
97
|
-
versions = masters + [b for b, _ in BRANCH]
|
|
98
|
-
sizes = [int(x) for x in args.sizes.split(",")]
|
|
99
|
-
workloads = [int(x) for x in args.workloads.split(",")]
|
|
100
|
-
cells = [(w, n) for w in workloads for n in sizes]
|
|
101
|
-
times, sums = {}, {}
|
|
102
|
-
for r in range(args.runs):
|
|
103
|
-
for w, n in cells:
|
|
104
|
-
vs = [v for v in versions if (w < 8 or v not in ("game", "game_tree")) and (w < 10 or v not in MASTER)]
|
|
105
|
-
k = r % len(vs)
|
|
106
|
-
for v in vs[k:] + vs[:k]:
|
|
107
|
-
res = subprocess.run([exes[v], str(w), str(n)], check=True, capture_output=True, text=True, cwd=out)
|
|
108
|
-
m = re.search(r"w(\d+) n(\d+) ms (\S+) checksum (\S+)", res.stdout)
|
|
109
|
-
if not m or (int(m.group(1)), int(m.group(2))) != (w, n):
|
|
110
|
-
sys.exit(f"no result from {v} w{w} n{n}: {res.stdout!r}")
|
|
111
|
-
times.setdefault((w, n, v), []).append(float(m.group(3)))
|
|
112
|
-
sums.setdefault((w, n), set()).add(m.group(4))
|
|
113
|
-
print(f"round {r + 1}: {WORKLOADS[w]} N={n} done", file=sys.stderr)
|
|
114
|
-
base = "enum_tree" if "enum_tree" in masters else (masters[0] if masters else None)
|
|
115
|
-
ratio = f" branch / {base} |" if masters else ""
|
|
116
|
-
print("| workload | N | " + " | ".join(versions) + " |" + ratio + " checksum |")
|
|
117
|
-
print("|---|---|" + "---|" * (len(versions) + (2 if masters else 1)))
|
|
118
|
-
for w, n in cells:
|
|
119
|
-
row = f"| {WORKLOADS[w]} | {n} |"
|
|
120
|
-
for v in versions:
|
|
121
|
-
ts = times.get((w, n, v))
|
|
122
|
-
if not ts:
|
|
123
|
-
row += " - |"
|
|
124
|
-
continue
|
|
125
|
-
row += f" {fmt(statistics.median(ts))} ({fmt(min(ts))}-{fmt(max(ts))}) |"
|
|
126
|
-
if masters:
|
|
127
|
-
e = statistics.median(times[(w, n, base)]) if (w, n, base) in times else 0
|
|
128
|
-
b = statistics.median(times[(w, n, "branch")])
|
|
129
|
-
row += f" {b / e:.2f}x |" if e > 0 else " - |"
|
|
130
|
-
row += f" {', '.join(sorted(sums[(w, n)]))} |"
|
|
131
|
-
print(row)
|
|
132
|
-
bad = [(w, n, s) for (w, n), s in sums.items() if len(s) != 1]
|
|
133
|
-
if bad:
|
|
134
|
-
sys.exit(f"checksums disagree: {bad}")
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if __name__ == "__main__":
|
|
138
|
-
main()
|
benchmarks/scene_trees/scene_tree.plum
DELETED
|
@@ -1,340 +0,0 @@
|
|
|
1
|
-
import std/Int
|
|
2
|
-
import std/Float
|
|
3
|
-
import std/Bool
|
|
4
|
-
import std/Str
|
|
5
|
-
import std/Io
|
|
6
|
-
import std/Option
|
|
7
|
-
import std/Result
|
|
8
|
-
import std/collections/List
|
|
9
|
-
import std/Slice
|
|
10
|
-
import std/math/Vec2
|
|
11
|
-
import std/math/Affine
|
|
12
|
-
import std/game/Color
|
|
13
|
-
import std/collections/RoseTree
|
|
14
|
-
import std/game/Place
|
|
15
|
-
import std/game/Actor
|
|
16
|
-
import std/game/Clickable
|
|
17
|
-
import std/game/Ctx
|
|
18
|
-
import std/game/SceneTree
|
|
19
|
-
|
|
20
|
-
# Scene-tree benchmark, branch version: master's benchmarks/scene_trees/game_enum_tree.plum
|
|
21
|
-
# (a persistent tree of immutable bodies, referred to by id) in the branch's language, on
|
|
22
|
-
# the branch's scene tree (std/game/SceneTree). It builds the same scene from the same random numbers as
|
|
23
|
-
# master's three programs and prints the same checksums; see
|
|
24
|
-
# docs/benchmarks/2026-11-08-scene-trees-branch.md and run.py.
|
|
25
|
-
#
|
|
26
|
-
# It takes the workload and N as arguments, as master's do (`scene_tree 4 1000`); without
|
|
27
|
-
# them it runs workloads 1 to 4 at N = 100. It times with the microsecond clock.
|
|
28
|
-
#
|
|
29
|
-
# The scene: a root, 10 groups (moved, scaled and turned), and N - 11 leaves, 20 by 20
|
|
30
|
-
# rectangles, spread over the groups in turn. Workloads (the numbers are master's):
|
|
31
|
-
# 1 step: 1000 ticks; every leaf moves by its velocity and bounces in its group's box.
|
|
32
|
-
# 2 churn: 1000 ticks; 1% of the leaves (at least one) die and as many are born, picked
|
|
33
|
-
# and placed by the same random numbers, pushed before a step that applies them
|
|
34
|
-
# in its walk.
|
|
35
|
-
# 3 draw: 1000 flattens of the tree to the draw list, with transforms.
|
|
36
|
-
# 4 hit: 1000 hit tests at random stage points.
|
|
37
|
-
# 5 step, no transforms: the walk hands every body the root's context, so no parent's
|
|
38
|
-
# world transform is computed.
|
|
39
|
-
# 6 step, eager transforms: every body's world transform is computed each tick.
|
|
40
|
-
# 7 churn, apply after: the kills and spawns are pushed after the step and applied with
|
|
41
|
-
# a second walk (`SceneTree.apply`).
|
|
42
|
-
# 8 step, 60 kept: 1 with the last 60 stages kept (a ring of snapshots), so nothing is
|
|
43
|
-
# only held once and no cell can be reused.
|
|
44
|
-
# 9 churn, 60 kept: 2 with the last 60 stages kept.
|
|
45
|
-
# 10 mostly still: 1 with only 1% of the leaves moving (every 101st, so spread over all
|
|
46
|
-
# the groups); the others are `Still`s, whose step returns them as they are.
|
|
47
|
-
# 11 mostly still, one group: 10 with the moving 1% all in the first group (every 10th of
|
|
48
|
-
# its leaves), the other nine groups still: a HUD or a menu beside the action.
|
|
49
|
-
# Workloads 10 and 11 are the branch's own: master's programs have no still leaves.
|
|
50
|
-
|
|
51
|
-
struct Rng(mut s: Int) =
|
|
52
|
-
fun next(self, k: Int) -> Int =
|
|
53
|
-
self.s = {self.s * 1103515245 + 12345} % 2147483648
|
|
54
|
-
{self.s / 65536} % k
|
|
55
|
-
|
|
56
|
-
fun float(self, k: Int) -> Float = Float(self.next(k * 10)) / 10.0
|
|
57
|
-
|
|
58
|
-
# The scene's actors are `Actor<Int>` (the benchmark sends no messages): the groups are
|
|
59
|
-
# `Turned`s, which a step returns as they are, and the leaves are `Bod`s, master's `Leaf`
|
|
60
|
-
# (master's `EBody` fields and the velocity): a 20 by 20 red box that moves by (vx, vy) and
|
|
61
|
-
# bounces. A leaf keeps its position in its own fields and makes its `Place` when asked:
|
|
62
|
-
# with a `Place` field moved by a nested spread (`Bod(..self, at: self.at.moveTo(..))`)
|
|
63
|
-
# each step allocates a cell, which FBIP doesn't reuse, and the step workload is about
|
|
64
|
-
# 1.7 times slower.
|
|
65
|
-
struct Bod[Actor<Int>, Clickable](id: Int, x: Float, y: Float, vx: Float, vy: Float) =
|
|
66
|
-
fun key(self) -> Int = self.id
|
|
67
|
-
|
|
68
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
69
|
-
|
|
70
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, 20.0, 20.0, Color.Red)
|
|
71
|
-
|
|
72
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(20.0, 20.0, p)
|
|
73
|
-
|
|
74
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> Bod =
|
|
75
|
-
nx := self.x + self.vx * dt
|
|
76
|
-
ny := self.y + self.vy * dt
|
|
77
|
-
vx := if nx < 0.0 || nx > 200.0 then 0.0 - self.vx else self.vx
|
|
78
|
-
vy := if ny < 0.0 || ny > 200.0 then 0.0 - self.vy else self.vy
|
|
79
|
-
Bod(..self, x: nx, y: ny, vx: vx, vy: vy)
|
|
80
|
-
|
|
81
|
-
# A leaf that never moves: `Bod` without a velocity, whose step is `Actor`'s default (it
|
|
82
|
-
# returns the leaf as it is).
|
|
83
|
-
struct Still[Actor<Int>, Clickable](id: Int, x: Float, y: Float) =
|
|
84
|
-
fun key(self) -> Int = self.id
|
|
85
|
-
|
|
86
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
87
|
-
|
|
88
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, 20.0, 20.0, Color.Red)
|
|
89
|
-
|
|
90
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(20.0, 20.0, p)
|
|
91
|
-
|
|
92
|
-
# A group at (x, y), scaled by `s` and turned by `r` radians: it paints nothing.
|
|
93
|
-
struct Turned[Actor<Int>](id: Int, x: Float, y: Float, s: Float, r: Float) =
|
|
94
|
-
fun key(self) -> Int = self.id
|
|
95
|
-
|
|
96
|
-
fun place(self) -> Place = place.turned(self.x, self.y, self.s, self.r)
|
|
97
|
-
|
|
98
|
-
fun group(id: Int, x: Float, y: Float, s: Float, r: Float) -> Actor<Int> =
|
|
99
|
-
Turned(id: id, x: x, y: y, s: s, r: r)
|
|
100
|
-
|
|
101
|
-
fun newLeaf(rng: Rng, id: Int) -> RoseTree<Actor<Int>> = leafOf(rng, id, true)
|
|
102
|
-
|
|
103
|
-
# `newLeaf`, a `Still` at the same place unless `moves` (the same random numbers either way).
|
|
104
|
-
fun leafOf(rng: Rng, id: Int, moves: Bool) -> RoseTree<Actor<Int>> =
|
|
105
|
-
x := rng.float(200)
|
|
106
|
-
y := rng.float(200)
|
|
107
|
-
vx := rng.float(100) - 50.0
|
|
108
|
-
vy := rng.float(100) - 50.0
|
|
109
|
-
a: Actor<Int> := if moves then Bod(id: id, x: x, y: y, vx: vx, vy: vy) else Still(id: id, x: x, y: y)
|
|
110
|
-
RoseTree.leaf(a)
|
|
111
|
-
|
|
112
|
-
# Whether leaf `i` (from 0) moves in workload `w`: all of them but in 10 and 11.
|
|
113
|
-
fun moving(w: Int, i: Int) -> Bool =
|
|
114
|
-
if w == 10
|
|
115
|
-
i % 101 == 0
|
|
116
|
-
else if w == 11
|
|
117
|
-
i % 10 == 0 && {i / 10} % 10 == 0
|
|
118
|
-
else
|
|
119
|
-
true
|
|
120
|
-
|
|
121
|
-
# What the workloads change besides the stage: the live ids, the random numbers, the next
|
|
122
|
-
# id to give out.
|
|
123
|
-
struct Bench(live: Slice<Int>, rng: Rng, mut nextId: Int)
|
|
124
|
-
|
|
125
|
-
fun bench(n: Int) -> Bench = Bench(live: Slice<Int>(), rng: Rng(s: 12345), nextId: n)
|
|
126
|
-
|
|
127
|
-
# The scene, built bottom up as master builds it: each group's children first, then the
|
|
128
|
-
# groups under the root. Ids: the root 0, the groups 1 to 10, the leaves from 11.
|
|
129
|
-
fun build(n: Int, sc: Bench, w: Int) -> SceneTree<Int> =
|
|
130
|
-
kids := Slice<Slice<RoseTree<Actor<Int>>>>()
|
|
131
|
-
for g := range 10
|
|
132
|
-
kids.push(Slice<RoseTree<Actor<Int>>>())
|
|
133
|
-
for i := range n - 11
|
|
134
|
-
kids.at(i % 10).push(leafOf(sc.rng, 11 + i, moving(w, i)))
|
|
135
|
-
sc.live.push(11 + i)
|
|
136
|
-
groups := Slice<RoseTree<Actor<Int>>>()
|
|
137
|
-
for g := range 10
|
|
138
|
-
gb := group(g + 1, Float(100 + 300 * {g % 5}), Float(100 + 300 * {g / 5}), 1.0 + 0.05 * Float(g), 0.1 * Float(g))
|
|
139
|
-
empty: RoseTree<Actor<Int>> := RoseEmpty
|
|
140
|
-
groups.push(RoseNode(value: gb, firstChild: scenetree.chainFrom(kids.at(g), 0), nextSibling: empty))
|
|
141
|
-
empty: RoseTree<Actor<Int>> := RoseEmpty
|
|
142
|
-
root := RoseNode(value: group(0, 0.0, 0.0, 1.0, 0.0), firstChild: scenetree.chainFrom(groups, 0), nextSibling: empty)
|
|
143
|
-
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
144
|
-
|
|
145
|
-
# Every node's position, in preorder, folded into one number.
|
|
146
|
-
fun hashTree(t: RoseTree<Actor<Int>>, h: Int) -> Int =
|
|
147
|
-
t.fold(h, |r0, b|
|
|
148
|
-
p := b.place()
|
|
149
|
-
r := {r0 * 31 + Int(p.x * 1000.0)} % 1000000007
|
|
150
|
-
{r * 31 + Int(p.y * 1000.0)} % 1000000007
|
|
151
|
-
)
|
|
152
|
-
|
|
153
|
-
# `t` ticks of `stage.step`.
|
|
154
|
-
fun steps(stage: SceneTree<Int>, ctx: Ctx<Int>, dt: Float, t: Int) -> SceneTree<Int> =
|
|
155
|
-
if t == 0 then stage else steps(stage.step(ctx, dt), ctx, dt, t - 1)
|
|
156
|
-
|
|
157
|
-
# `steps` with each tick's stage also stored in `kept`, a ring of the last 60.
|
|
158
|
-
fun stepsKept(stage: SceneTree<Int>, ctx: Ctx<Int>, dt: Float, t: Int, kept: Slice<SceneTree<Int>>) -> SceneTree<Int> =
|
|
159
|
-
if t == 0
|
|
160
|
-
stage
|
|
161
|
-
else
|
|
162
|
-
keep(kept, stage, t)
|
|
163
|
-
stepsKept(stage.step(ctx, dt), ctx, dt, t - 1, kept)
|
|
164
|
-
|
|
165
|
-
fun keep(kept: Slice<SceneTree<Int>>, stage: SceneTree<Int>, t: Int) =
|
|
166
|
-
if kept.length() < 60
|
|
167
|
-
kept.push(stage)
|
|
168
|
-
else
|
|
169
|
-
_ := kept.set(t % 60, stage)
|
|
170
|
-
|
|
171
|
-
# Pushes the tick's kills and spawns to `ctx.out`: `k` random live leaves die and `k` new
|
|
172
|
-
# ones are born under random groups.
|
|
173
|
-
fun pushChurn(sc: Bench, ctx: Ctx<Int>, k: Int) =
|
|
174
|
-
for j := range k
|
|
175
|
-
i := sc.rng.next(sc.live.length())
|
|
176
|
-
victim := sc.live.at(i)
|
|
177
|
-
_ := sc.live.set(i, sc.live.at(sc.live.length() - 1))
|
|
178
|
-
_ := sc.live.pop()
|
|
179
|
-
ctx.out.push(Kill(id: victim))
|
|
180
|
-
for j := range k
|
|
181
|
-
g := sc.rng.next(10)
|
|
182
|
-
id := sc.nextId
|
|
183
|
-
sc.nextId = id + 1
|
|
184
|
-
ctx.out.push(Spawn(parent: g + 1, node: newLeaf(sc.rng, id)))
|
|
185
|
-
sc.live.push(id)
|
|
186
|
-
|
|
187
|
-
# `t` ticks of churn: the commands pushed, then a step that applies them in its walk, or
|
|
188
|
-
# (`after`) a step, then the commands pushed and applied with a second walk.
|
|
189
|
-
fun churns(stage: SceneTree<Int>, sc: Bench, ctx: Ctx<Int>, dt: Float, k: Int, t: Int, after: Bool) -> SceneTree<Int> =
|
|
190
|
-
if t == 0
|
|
191
|
-
stage
|
|
192
|
-
else if after
|
|
193
|
-
s1 := stage.step(ctx, dt)
|
|
194
|
-
pushChurn(sc, ctx, k)
|
|
195
|
-
s2 := s1.apply(ctx.out)
|
|
196
|
-
ctx.out.clear()
|
|
197
|
-
churns(s2, sc, ctx, dt, k, t - 1, after)
|
|
198
|
-
else
|
|
199
|
-
pushChurn(sc, ctx, k)
|
|
200
|
-
churns(stage.step(ctx, dt), sc, ctx, dt, k, t - 1, after)
|
|
201
|
-
|
|
202
|
-
# `churns` (commands before the step) with each tick's stage also kept in a ring of 60.
|
|
203
|
-
fun churnsKept(stage: SceneTree<Int>, sc: Bench, ctx: Ctx<Int>, dt: Float, k: Int, t: Int, kept: Slice<SceneTree<Int>>) -> SceneTree<Int> =
|
|
204
|
-
if t == 0
|
|
205
|
-
stage
|
|
206
|
-
else
|
|
207
|
-
keep(kept, stage, t)
|
|
208
|
-
pushChurn(sc, ctx, k)
|
|
209
|
-
churnsKept(stage.step(ctx, dt), sc, ctx, dt, k, t - 1, kept)
|
|
210
|
-
|
|
211
|
-
# SceneTree's walk with no commands and the root's context for every body: no parent's world
|
|
212
|
-
# transform is computed.
|
|
213
|
-
fun stepFlat(t: RoseTree<Actor<Int>>, ctx: Ctx<Int>, dt: Float) -> RoseTree<Actor<Int>> = match t
|
|
214
|
-
RoseEmpty => t
|
|
215
|
-
RoseNode(b, k, n) =>
|
|
216
|
-
nb := b.step(ctx, dt)
|
|
217
|
-
if nb.gone()
|
|
218
|
-
stepFlat(n, ctx, dt)
|
|
219
|
-
else
|
|
220
|
-
k2 := if k.isEmpty() then k else stepFlat(k, ctx, dt)
|
|
221
|
-
RoseNode(value: nb, firstChild: k2, nextSibling: stepFlat(n, ctx, dt))
|
|
222
|
-
|
|
223
|
-
# SceneTree's walk with no commands, every body's world transform computed (and checked, so
|
|
224
|
-
# it is used).
|
|
225
|
-
fun stepEager(t: RoseTree<Actor<Int>>, ctx: Ctx<Int>, dt: Float) -> RoseTree<Actor<Int>> = match t
|
|
226
|
-
RoseEmpty => t
|
|
227
|
-
RoseNode(b, k, n) =>
|
|
228
|
-
m := ctx.worldOf(b.place().local())
|
|
229
|
-
assert m.e > -1.0e30
|
|
230
|
-
cc := ctx.under(b.place().local(), b.opacity())
|
|
231
|
-
nb := b.step(ctx, dt)
|
|
232
|
-
if nb.gone()
|
|
233
|
-
stepEager(n, ctx, dt)
|
|
234
|
-
else
|
|
235
|
-
k2 := if k.isEmpty() then k else stepEager(k, cc, dt)
|
|
236
|
-
RoseNode(value: nb, firstChild: k2, nextSibling: stepEager(n, ctx, dt))
|
|
237
|
-
|
|
238
|
-
fun walks(stage: SceneTree<Int>, ctx: Ctx<Int>, dt: Float, t: Int, eager: Bool) -> SceneTree<Int> =
|
|
239
|
-
if t == 0
|
|
240
|
-
stage
|
|
241
|
-
else if eager
|
|
242
|
-
walks(stage.withRoot(stepEager(stage.root, ctx, dt)), ctx, dt, t - 1, eager)
|
|
243
|
-
else
|
|
244
|
-
walks(stage.withRoot(stepFlat(stage.root, ctx, dt)), ctx, dt, t - 1, eager)
|
|
245
|
-
|
|
246
|
-
# 1000 flattens: the entries over all of them plus the summed translations of the last.
|
|
247
|
-
fun draws(stage: SceneTree<Int>, r: Int, total: Int) -> Int =
|
|
248
|
-
d := stage.flatten()
|
|
249
|
-
if r == 999
|
|
250
|
-
last := lastSum(d, 0, 0.0)
|
|
251
|
-
total + d.length() + Int(last)
|
|
252
|
-
else
|
|
253
|
-
draws(stage, r + 1, total + d.length())
|
|
254
|
-
|
|
255
|
-
fun lastSum(d: Slice<Drawn<Int>>, i: Int, acc: Float) -> Float =
|
|
256
|
-
if i >= d.length() then acc else lastSum(d, i + 1, acc + d.at(i).m.e + d.at(i).m.f)
|
|
257
|
-
|
|
258
|
-
# 1000 hit tests at random stage points: the positions of the bodies hit, in order.
|
|
259
|
-
fun hits(stage: SceneTree<Int>, rng: Rng, q: Int, sum: Int) -> Int =
|
|
260
|
-
if q == 1000
|
|
261
|
-
sum
|
|
262
|
-
else
|
|
263
|
-
x := rng.float(1600)
|
|
264
|
-
y := rng.float(800)
|
|
265
|
-
next := match stage.hit(x, y)
|
|
266
|
-
Some(a) =>
|
|
267
|
-
p := a.place()
|
|
268
|
-
{sum * 31 + Int(p.x * 100.0) + 7 * Int(p.y * 100.0)} % 1000000007
|
|
269
|
-
None => {sum * 31 + 1} % 1000000007
|
|
270
|
-
hits(stage, rng, q + 1, next)
|
|
271
|
-
|
|
272
|
-
# Runs workload `w` on `stage`, a scene of `n` nodes, and returns its checksum.
|
|
273
|
-
fun work(stage: SceneTree<Int>, sc: Bench, w: Int, n: Int) -> Int =
|
|
274
|
-
dt := 1.0 / 60.0
|
|
275
|
-
ctx := Ctx<Int>()
|
|
276
|
-
k := {{n - 11} / 100}.max(1)
|
|
277
|
-
if w == 1 || w == 10 || w == 11
|
|
278
|
-
hashTree(steps(stage, ctx, dt, 1000).root, 0)
|
|
279
|
-
else if w == 2 || w == 7
|
|
280
|
-
hashTree(churns(stage, sc, ctx, dt, k, 1000, w == 7).root, 0) + sc.live.length()
|
|
281
|
-
else if w == 3
|
|
282
|
-
draws(stage, 0, 0)
|
|
283
|
-
else if w == 4
|
|
284
|
-
hits(stage, sc.rng, 0, 0)
|
|
285
|
-
else if w == 5 || w == 6
|
|
286
|
-
hashTree(walks(stage, ctx, dt, 1000, w == 6).root, 0)
|
|
287
|
-
else if w == 8
|
|
288
|
-
hashTree(stepsKept(stage, ctx, dt, 1000, Slice<SceneTree<Int>>()).root, 0)
|
|
289
|
-
else
|
|
290
|
-
hashTree(churnsKept(stage, sc, ctx, dt, k, 1000, Slice<SceneTree<Int>>()).root, 0) + sc.live.length()
|
|
291
|
-
|
|
292
|
-
# Builds the scene, then times the workload alone with the wall clock.
|
|
293
|
-
fun run(io: Io, w: Int, n: Int) -> Int =
|
|
294
|
-
sc := bench(n)
|
|
295
|
-
stage := build(n, sc, w)
|
|
296
|
-
t0 := io.nowMicros()
|
|
297
|
-
sum := work(stage, sc, w, n)
|
|
298
|
-
ms := {io.nowMicros() - t0} / 1000.0
|
|
299
|
-
io.printLn("scene_tree w{w} n{n} ms {ms} checksum {sum}")
|
|
300
|
-
sum
|
|
301
|
-
|
|
302
|
-
fun main(io: Io) =
|
|
303
|
-
args := io.args()
|
|
304
|
-
if args.length() == 2
|
|
305
|
-
_ := run(io, Int.parse(args.at(0)).unwrapOr(1), Int.parse(args.at(1)).unwrapOr(100))
|
|
306
|
-
else
|
|
307
|
-
for w := range 4
|
|
308
|
-
_ := run(io, w + 1, 100)
|
|
309
|
-
|
|
310
|
-
fun check(w: Int) -> Int =
|
|
311
|
-
sc := bench(100)
|
|
312
|
-
work(build(100, sc, w), sc, w, 100)
|
|
313
|
-
|
|
314
|
-
# The same checksums as master's three versions.
|
|
315
|
-
test "the nine workloads at N = 100 give master's checksums"
|
|
316
|
-
assert check(1) == 809683012
|
|
317
|
-
assert check(2) == 998134459
|
|
318
|
-
assert check(3) == 211827
|
|
319
|
-
assert check(4) == 462421202
|
|
320
|
-
assert check(5) == 809683012
|
|
321
|
-
assert check(6) == 809683012
|
|
322
|
-
assert check(7) == 998134459
|
|
323
|
-
assert check(8) == 809683012
|
|
324
|
-
assert check(9) == 998134459
|
|
325
|
-
|
|
326
|
-
test "mostly still: the still leaves stay where they are, the moving ones move"
|
|
327
|
-
sc := bench(1000)
|
|
328
|
-
stage := build(1000, sc, 10)
|
|
329
|
-
ctx := Ctx<Int>()
|
|
330
|
-
later := steps(stage, ctx, 1.0 / 60.0, 30)
|
|
331
|
-
assert later.count() == stage.count()
|
|
332
|
-
moved := stage.root.fold(0, |acc, a|
|
|
333
|
-
match later.find(a.key())
|
|
334
|
-
Some(b) => if a.place().x != b.place().x || a.place().y != b.place().y then acc + 1 else acc
|
|
335
|
-
None => acc)
|
|
336
|
-
# Leaves 0, 101, .. 909 of 989: 10 move (a bounce never brings one back exactly).
|
|
337
|
-
assert moved == 10
|
|
338
|
-
sc2 := bench(1000)
|
|
339
|
-
still := build(1000, sc2, 11)
|
|
340
|
-
assert hashTree(steps(still, ctx, 1.0 / 60.0, 30).root, 0) != hashTree(still.root, 0)
|
compiler/checker/src/traits.rs
CHANGED
|
@@ -621,16 +621,39 @@ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &M
|
|
|
621
621
|
errors.push(at(format!("trait '{}' extends itself (through {})", t.name, st.name)));
|
|
622
622
|
continue;
|
|
623
623
|
}
|
|
624
|
+
// A subtrait may give a supertrait's method a default of its own, with
|
|
625
|
+
// the same signature: its implementers take it in place of the
|
|
626
|
+
// supertrait's (`plum_core::trait_defaults`). Anything else is an error.
|
|
627
|
+
let supArgs: Vec<PlumType> = traits
|
|
628
|
+
.traits
|
|
629
|
+
.get(&t.name)
|
|
630
|
+
.and_then(|ti| ti.supers.iter().find_map(|s| traits.traitObject(s).filter(|(n, _)| *n == st.name).map(|(_, a)| a.to_vec())))
|
|
631
|
+
.unwrap_or_default();
|
|
624
632
|
for m in &t.methods {
|
|
625
633
|
if let Some(sm) = traits.traits.get(&st.name).and_then(|x| x.method(&m.sig.name)) {
|
|
626
634
|
let owner = sm.from.clone().unwrap_or_else(|| st.name.clone());
|
|
635
|
+
let supSig = if st.generics.len() == supArgs.len() {
|
|
636
|
+
Some(types::substitute(&sm.sig, &appSubst(&st.generics, &supArgs)))
|
|
637
|
+
} else {
|
|
638
|
+
None
|
|
639
|
+
};
|
|
640
|
+
let own = traits.traits.get(&t.name).and_then(|ti| ti.method(&m.sig.name)).filter(|o| o.from.is_none());
|
|
641
|
+
let sameSig = match (own, supSig) {
|
|
642
|
+
(Some(o), Some(s)) => o.sig == s && o.hasSelf == sm.hasSelf,
|
|
643
|
+
_ => false,
|
|
644
|
+
};
|
|
645
|
+
if m.hasDefault && sameSig {
|
|
646
|
+
continue;
|
|
647
|
+
}
|
|
648
|
+
let why = if m.hasDefault {
|
|
649
|
+
"; a subtrait may give it a default only with the same signature"
|
|
650
|
+
} else {
|
|
651
|
+
"; override it in the types instead, or give it a default here with the same signature"
|
|
652
|
+
};
|
|
627
653
|
errors.push(CheckError::resolution(
|
|
628
654
|
m.sig.line,
|
|
629
655
|
m.sig.column,
|
|
630
|
-
format!(
|
|
631
|
-
|
|
656
|
+
format!("trait '{}': method '{}' is already a method of its supertrait {}{why}", t.name, m.sig.name, owner),
|
|
632
|
-
t.name, m.sig.name, owner
|
|
633
|
-
),
|
|
634
657
|
));
|
|
635
658
|
}
|
|
636
659
|
}
|
compiler/core/src/trait_defaults.rs
CHANGED
|
@@ -125,6 +125,16 @@ fn expandDefaultsOnly(src: &Source) -> Option<Source> {
|
|
|
125
125
|
if owned.contains(&key) {
|
|
126
126
|
continue;
|
|
127
127
|
}
|
|
128
|
+
// Another of the type's traits that extends this one and gives the method
|
|
129
|
+
// a default of its own: that default is the type's.
|
|
130
|
+
let overridden = e.implements.iter().any(|o| {
|
|
131
|
+
o.name != t.name
|
|
132
|
+
&& extendsByName(&traits, &o.name, &t.name)
|
|
133
|
+
&& traits.get(o.name.as_str()).is_some_and(|ot| ot.methods.iter().any(|om| om.hasDefault && om.sig.name == m.sig.name))
|
|
134
|
+
});
|
|
135
|
+
if overridden {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
128
138
|
let Some(d) = defaults.get(&(t.name.as_str(), m.sig.name.as_str())) else { continue };
|
|
129
139
|
let mut f = (*d).clone();
|
|
130
140
|
selfTypeNamesTo(&mut f.body, &e.name);
|
|
@@ -159,6 +169,25 @@ fn expandDefaultsOnly(src: &Source) -> Option<Source> {
|
|
|
159
169
|
Some(out)
|
|
160
170
|
}
|
|
161
171
|
|
|
172
|
+
/// Whether the trait `sub` has `sup` among its supertraits, transitively, by name.
|
|
173
|
+
fn extendsByName(traits: &HashMap<&str, &Trait>, sub: &str, sup: &str) -> bool {
|
|
174
|
+
let mut todo = vec![sub.to_string()];
|
|
175
|
+
let mut seen: HashSet<String> = HashSet::new();
|
|
176
|
+
while let Some(n) = todo.pop() {
|
|
177
|
+
if !seen.insert(n.clone()) {
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
let Some(t) = traits.get(n.as_str()) else { continue };
|
|
181
|
+
for s in &t.supers {
|
|
182
|
+
if s.name == sup {
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
todo.push(s.name.clone());
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
false
|
|
189
|
+
}
|
|
190
|
+
|
|
162
191
|
/// The suffix of a method's copy for calls on a trait object (`split$dyn`).
|
|
163
192
|
pub const DYN_SUFFIX: &str = "$dyn";
|
|
164
193
|
|
compiler/game/web-test/fixtures/stress_scene_port.plum
DELETED
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
# The scene-tree port of master's imperative stress_scene, drawing the same scene call
|
|
2
|
-
# for call: 5000 sprites in 50 slowly rotating groups, 500 rect shapes, 200 circle shapes
|
|
3
|
-
# and 50 texts with a changing number, through a 0.8 camera. The scene is a
|
|
4
|
-
# `SceneTree<Int>` of actors that lives from frame to frame; each kind moves itself by a
|
|
5
|
-
# fixed step in its own `step` (a spread), and the tree's `draw` paints them. Motion is
|
|
6
|
-
# per frame, as in the original. The text is rebuilt in the step and input is polled
|
|
7
|
-
# every frame, also as in the original, so the update and draw split stays comparable.
|
|
8
|
-
# It is a `Game` with one screen and a state that never changes.
|
|
9
|
-
# Written the plain way and not tuned for speed.
|
|
10
|
-
module stress_scene_port
|
|
11
|
-
import std/Str
|
|
12
|
-
import std/Int
|
|
13
|
-
import std/Float
|
|
14
|
-
import std/collections/List
|
|
15
|
-
import std/math/Vec2
|
|
16
|
-
import std/math/Affine
|
|
17
|
-
import std/game/Color
|
|
18
|
-
import std/game/gfx
|
|
19
|
-
import std/game/input
|
|
20
|
-
import std/collections/RoseTree
|
|
21
|
-
import std/game/Store
|
|
22
|
-
import std/game/Game
|
|
23
|
-
import std/game/Place
|
|
24
|
-
import std/game/Actor
|
|
25
|
-
import std/game/Ctx
|
|
26
|
-
import std/game/SceneTree
|
|
27
|
-
import std/Io
|
|
28
|
-
|
|
29
|
-
Sprites = 5000
|
|
30
|
-
Rects = 500
|
|
31
|
-
Circles = 200
|
|
32
|
-
Texts = 50
|
|
33
|
-
Groups = 50
|
|
34
|
-
WorldW = 1600.0
|
|
35
|
-
WorldH = 900.0
|
|
36
|
-
|
|
37
|
-
# A sprite of the sheet inside its group, turning about its centre.
|
|
38
|
-
struct Dancer[Actor<Int>](id: Int, x: Float, y: Float, rotation: Float, srcX: Float, sheet: Texture) =
|
|
39
|
-
fun key(self) -> Int = self.id
|
|
40
|
-
|
|
41
|
-
fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(8.0, 8.0)
|
|
42
|
-
|
|
43
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> Dancer =
|
|
44
|
-
r := self.rotation + 0.02
|
|
45
|
-
Dancer(..self, rotation: r, srcX: Float(Int(r * 50.0) / 6 % 4 * 16))
|
|
46
|
-
|
|
47
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
48
|
-
actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
|
|
49
|
-
|
|
50
|
-
# A group of dancers turning about (75, 85).
|
|
51
|
-
struct Spin[Actor<Int>](id: Int, x: Float, y: Float, rotation: Float) =
|
|
52
|
-
fun key(self) -> Int = self.id
|
|
53
|
-
|
|
54
|
-
fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation).pivotAt(75.0, 85.0)
|
|
55
|
-
|
|
56
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> Spin = Spin(..self, rotation: self.rotation + 0.004)
|
|
57
|
-
|
|
58
|
-
fun wrap(v: Float, limit: Float) -> Float =
|
|
59
|
-
if v > limit then v - limit else v
|
|
60
|
-
|
|
61
|
-
# A 12 by 8 rect drifting right.
|
|
62
|
-
struct DriftRect[Actor<Int>](id: Int, x: Float, y: Float, color: Color) =
|
|
63
|
-
fun key(self) -> Int = self.id
|
|
64
|
-
|
|
65
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
66
|
-
|
|
67
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> DriftRect = DriftRect(..self, x: wrap(self.x + 2.0, WorldW))
|
|
68
|
-
|
|
69
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, 12.0, 8.0, self.color)
|
|
70
|
-
|
|
71
|
-
# A circle of radius 6 drifting down and right.
|
|
72
|
-
struct DriftCircle[Actor<Int>](id: Int, x: Float, y: Float, color: Color) =
|
|
73
|
-
fun key(self) -> Int = self.id
|
|
74
|
-
|
|
75
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
76
|
-
|
|
77
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> DriftCircle =
|
|
78
|
-
DriftCircle(..self, x: wrap(self.x + 3.0, WorldW), y: wrap(self.y + 1.0, WorldH))
|
|
79
|
-
|
|
80
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.circlePaint(io, m, alpha, 6.0, 6.0, 6.0, self.color)
|
|
81
|
-
|
|
82
|
-
# Shows "n <count>" and counts up each frame.
|
|
83
|
-
struct Count[Actor<Int>](id: Int, x: Float, y: Float, n: Int, text: Str) =
|
|
84
|
-
fun key(self) -> Int = self.id
|
|
85
|
-
|
|
86
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
87
|
-
|
|
88
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> Count =
|
|
89
|
-
n := self.n + 1
|
|
90
|
-
Count(..self, n: n, text: "n {n}")
|
|
91
|
-
|
|
92
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.textPaint(io, m, alpha, self.text, 0.0, 0.0, 14.0, Color.White)
|
|
93
|
-
|
|
94
|
-
fun hue(i: Int) -> Color =
|
|
95
|
-
Color(r: Float(i % 7) / 7.0, g: Float(i % 5) / 5.0, b: 0.4 + Float(i % 3) / 5.0, a: 0.8)
|
|
96
|
-
|
|
97
|
-
fun buildFrom(i: Int, n: Int, f: fn(Int) -> RoseTree<Actor<Int>>) -> List<RoseTree<Actor<Int>>> =
|
|
98
|
-
if i >= n then Nil else Cons(head: f(i), tail: buildFrom(i + 1, n, f))
|
|
99
|
-
|
|
100
|
-
# The nodes f(0), f(1) ... f(n - 1).
|
|
101
|
-
fun build(n: Int, f: fn(Int) -> RoseTree<Actor<Int>>) -> List<RoseTree<Actor<Int>>> =
|
|
102
|
-
buildFrom(0, n, f)
|
|
103
|
-
|
|
104
|
-
fun newDancer(sheet: Texture, gi: Int, j: Int) -> RoseTree<Actor<Int>> =
|
|
105
|
-
i := gi * {Sprites / Groups} + j
|
|
106
|
-
RoseTree.leaf(Dancer(id: 1000 + i, x: Float({j * j * 13 + j * 37} % 150), y: Float({j * j * 29 + j * 53} % 170), rotation: Float(i), srcX: Float(i % 4 * 16), sheet: sheet))
|
|
107
|
-
|
|
108
|
-
fun newSpin(sheet: Texture, gi: Int) -> RoseTree<Actor<Int>> =
|
|
109
|
-
RoseTree.of(Spin(id: 100 + gi, x: Float(gi % 10 * 160), y: Float(gi / 10 * 180), rotation: 0.0), build(Sprites / Groups, |j| newDancer(sheet, gi, j)))
|
|
110
|
-
|
|
111
|
-
fun newTree(sheet: Texture) -> SceneTree<Int> =
|
|
112
|
-
rects := build(Rects, |i| RoseTree.leaf(DriftRect(id: 10000 + i, x: Float(i * 61 % 1600), y: Float(i * 29 % 900), color: hue(i))))
|
|
113
|
-
circles := build(Circles, |i| RoseTree.leaf(DriftCircle(id: 20000 + i, x: Float(i * 83 % 1600), y: Float(i * 47 % 900), color: hue(i + 3))))
|
|
114
|
-
counts := build(Texts, |i| RoseTree.leaf(Count(id: 30000 + i, x: Float(i * 30 % 1600), y: Float(i * 17 % 900), n: i, text: "n {i}")))
|
|
115
|
-
kids := build(Groups, |gi| newSpin(sheet, gi)).append(rects).append(circles).append(counts)
|
|
116
|
-
SceneTree(root: RoseTree.of(Group(id: 0, x: 0.0, y: 0.0), kids), camX: 0.0, camY: 0.0, camScale: 0.8)
|
|
117
|
-
|
|
118
|
-
# The game sends no messages, so its state never changes.
|
|
119
|
-
struct Quiet[Reducer<Int>](n: Int) =
|
|
120
|
-
fun update(self, msg: Int) -> Quiet = self
|
|
121
|
-
|
|
122
|
-
# The one screen: the tree, drawn through its camera.
|
|
123
|
-
struct WorldScreen[Screen<Quiet, Int>](id: Int) =
|
|
124
|
-
fun key(self) -> Int = self.id
|
|
125
|
-
|
|
126
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
127
|
-
|
|
128
|
-
fun draw(self, io: Io, shown: SceneTree<Int>) =
|
|
129
|
-
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
130
|
-
shown.draw(io)
|
|
131
|
-
|
|
132
|
-
# The game's tree: the one screen over `t`'s actors, through `t`'s camera.
|
|
133
|
-
fun screenOf(t: SceneTree<Int>) -> SceneTree<Int> =
|
|
134
|
-
SceneTree.ofScreens([RoseTree.of(WorldScreen(id: -2), [t.root])]).pan(t.camX, t.camY).zoom(t.camScale)
|
|
135
|
-
|
|
136
|
-
fun main(io: Io) -> Game<Quiet, Int> =
|
|
137
|
-
Game.start(screenOf(newTree(gfx.loadTexture(io, "sprites.png"))), Quiet(n: 0))
|
|
138
|
-
|
|
139
|
-
test "the tree holds every actor and steps them"
|
|
140
|
-
t := newTree(Texture(id: -1))
|
|
141
|
-
assert t.count() == 1 + 50 + 5000 + 500 + 200 + 50
|
|
142
|
-
s := t.step(Ctx<Int>(), 0.016).step(Ctx<Int>(), 0.016)
|
|
143
|
-
assert s.findAs<Count>(30003).unwrap().text == "n 5"
|
|
144
|
-
assert s.findAs<DriftRect>(10000).unwrap().x == 4.0
|
compiler/game/web-test/fixtures/stress_world.plum
DELETED
|
@@ -1,132 +0,0 @@
|
|
|
1
|
-
# A large y-sorted world on a scene tree: 20000 sprites in one world layer, about 2000
|
|
2
|
-
# of them in the 1280x720 view. Every frame a few hundred sprites walk, the layer's
|
|
3
|
-
# children are sorted by y, and only the sprites in the view are drawn. The tree is a
|
|
4
|
-
# `SceneTree<Int>` whose root is the camera (a `Group` at minus the camera's position);
|
|
5
|
-
# each sprite is an `Spr` actor that walks in its own `step` and paints itself only when
|
|
6
|
-
# it is in the view. It is a `Game` with one screen, `WorldScreen`, whose `rules` sort the
|
|
7
|
-
# layer and move the camera after the steps; its state never changes.
|
|
8
|
-
module stress_world
|
|
9
|
-
import std/Str
|
|
10
|
-
import std/Int
|
|
11
|
-
import std/Float
|
|
12
|
-
import std/Bool
|
|
13
|
-
import std/math/math
|
|
14
|
-
import std/collections/List
|
|
15
|
-
import std/Slice
|
|
16
|
-
import std/math/Vec2
|
|
17
|
-
import std/math/Affine
|
|
18
|
-
import std/game/Color
|
|
19
|
-
import std/game/gfx
|
|
20
|
-
import std/collections/RoseTree
|
|
21
|
-
import std/game/Store
|
|
22
|
-
import std/game/Game
|
|
23
|
-
import std/game/Place
|
|
24
|
-
import std/game/Actor
|
|
25
|
-
import std/game/Ctx
|
|
26
|
-
import std/game/SceneTree
|
|
27
|
-
import std/Io
|
|
28
|
-
import std/game/input
|
|
29
|
-
|
|
30
|
-
Sprites = 20000
|
|
31
|
-
Walkers = 500
|
|
32
|
-
Width = 4000
|
|
33
|
-
Height = 2300
|
|
34
|
-
ViewW = 1280.0
|
|
35
|
-
ViewH = 720.0
|
|
36
|
-
|
|
37
|
-
# `walker` is the index among the walking sprites, or -1 for one that stands still;
|
|
38
|
-
# `frame` is the frame it last walked on.
|
|
39
|
-
struct Spr[Actor<Int>](id: Int, x: Float, y: Float, srcX: Float, walker: Int, frame: Int, sheet: Texture) =
|
|
40
|
-
fun key(self) -> Int = self.id
|
|
41
|
-
|
|
42
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
43
|
-
|
|
44
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> Spr =
|
|
45
|
-
if self.walker < 0
|
|
46
|
-
self
|
|
47
|
-
else
|
|
48
|
-
frame := self.frame + 1
|
|
49
|
-
Spr(..self, y: self.y + math.sin(Float(frame) * 0.05 + Float(self.walker)), frame: frame)
|
|
50
|
-
|
|
51
|
-
# Only a sprite in the view is drawn: `m` takes its (0, 0) to the screen.
|
|
52
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
53
|
-
p := m.apply(Vec2(x: 0.0, y: 0.0))
|
|
54
|
-
if p.x + 16.0 >= 0.0 && p.x <= ViewW && p.y + 16.0 >= 0.0 && p.y <= ViewH
|
|
55
|
-
actor.spritePaint(io, m, alpha, self.sheet, 0.0, 0.0, 16.0, 16.0, self.srcX, 0.0, 16.0, 16.0, Color.White)
|
|
56
|
-
|
|
57
|
-
# The one screen: the tree, the frame and the camera.
|
|
58
|
-
struct WorldScreen[Screen<Quiet, Int>](id: Int, frame: Int, camX: Float, camY: Float) =
|
|
59
|
-
fun key(self) -> Int = self.id
|
|
60
|
-
|
|
61
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
62
|
-
|
|
63
|
-
# After the walkers walked: the camera drifts and the layer (group 0) is sorted by y.
|
|
64
|
-
fun rules(self, tree: SceneTree<Int>, ctx: Ctx<Int>, state: Quiet, dt: Float) -> SceneTree<Int> =
|
|
65
|
-
frame := self.frame + 1
|
|
66
|
-
t := Float(frame) * 0.01
|
|
67
|
-
camX := 1300.0 + 600.0 * math.sin(t)
|
|
68
|
-
camY := 800.0 + 350.0 * math.cos(t * 0.7)
|
|
69
|
-
layer := tree.root.kids()
|
|
70
|
-
sorted := match layer
|
|
71
|
-
RoseNode(v, k, n) => RoseNode(value: v, firstChild: sortedByY(k), nextSibling: n)
|
|
72
|
-
RoseEmpty => layer
|
|
73
|
-
top: Actor<Int> := WorldScreen(..self, frame: frame, camX: camX, camY: camY)
|
|
74
|
-
empty: RoseTree<Actor<Int>> := RoseEmpty
|
|
75
|
-
world: RoseTree<Actor<Int>> := RoseNode(value: top, firstChild: sorted, nextSibling: empty)
|
|
76
|
-
tree.withRoot(world).updateAs<Group<Int>>(0, |g| Group(..g, x: 0.0 - camX, y: 0.0 - camY))
|
|
77
|
-
|
|
78
|
-
fun draw(self, io: Io, shown: SceneTree<Int>) =
|
|
79
|
-
gfx.clear(io, Color.rgb(0.05, 0.06, 0.1))
|
|
80
|
-
shown.draw(io)
|
|
81
|
-
|
|
82
|
-
# The game sends no messages, so its state never changes.
|
|
83
|
-
struct Quiet[Reducer<Int>](n: Int) =
|
|
84
|
-
fun update(self, msg: Int) -> Quiet = self
|
|
85
|
-
|
|
86
|
-
fun walkerOf(i: Int) -> Int =
|
|
87
|
-
if i % 37 == 0 && i / 37 < Walkers then i / 37 else -1
|
|
88
|
-
|
|
89
|
-
fun spriteAt(sheet: Texture, i: Int) -> RoseTree<Actor<Int>> =
|
|
90
|
-
RoseTree.leaf(Spr(id: 1 + i, x: Float({i * 7919 + 13} % Width), y: Float({i * i * 31 / 7 + i * 1013} % Height), srcX: Float(i % 4 * 16), walker: walkerOf(i), frame: 0, sheet: sheet))
|
|
91
|
-
|
|
92
|
-
fun spritesFrom(sheet: Texture, i: Int) -> List<RoseTree<Actor<Int>>> =
|
|
93
|
-
if i >= Sprites then Nil else Cons(head: spriteAt(sheet, i), tail: spritesFrom(sheet, i + 1))
|
|
94
|
-
|
|
95
|
-
# The game's tree: the one screen over the layer (group 0) of sprites.
|
|
96
|
-
fun newWorld(sheet: Texture) -> SceneTree<Int> =
|
|
97
|
-
layer: RoseTree<Actor<Int>> := RoseTree.of(Group(id: 0, x: 0.0, y: 0.0), spritesFrom(sheet, 0))
|
|
98
|
-
SceneTree.ofScreens([RoseTree.of(WorldScreen(id: -2, frame: 0, camX: 0.0, camY: 0.0), [layer])])
|
|
99
|
-
|
|
100
|
-
fun yOf(n: RoseTree<Actor<Int>>) -> Float = match n
|
|
101
|
-
RoseNode(a, _, _) => a.place().y
|
|
102
|
-
RoseEmpty => 0.0
|
|
103
|
-
|
|
104
|
-
# The chain of nodes `t` sorted by y.
|
|
105
|
-
fun sortedByY(t: RoseTree<Actor<Int>>) -> RoseTree<Actor<Int>> =
|
|
106
|
-
RoseTree.chainOf(List.fromSlice(t.chain().toSlice().sort(|a, b| yOf(a) < yOf(b))))
|
|
107
|
-
|
|
108
|
-
fun inView(s: WorldScreen, a: Actor<Int>) -> Bool =
|
|
109
|
-
p := a.place()
|
|
110
|
-
p.x + 16.0 >= s.camX && p.x <= s.camX + ViewW && p.y + 16.0 >= s.camY && p.y <= s.camY + ViewH
|
|
111
|
-
|
|
112
|
-
fun main(io: Io) -> Game<Quiet, Int> =
|
|
113
|
-
Game.start(newWorld(gfx.loadTexture(io, "sprites.png")), Quiet(n: 0))
|
|
114
|
-
|
|
115
|
-
# --- tests ---
|
|
116
|
-
|
|
117
|
-
test "about 2000 of the 20000 sprites are in view, sorted by y"
|
|
118
|
-
g0: Game<Quiet, Int> := Game.start(newWorld(Texture(id: -1)), Quiet(n: 0))
|
|
119
|
-
g := g0.step(io, Input.create(), 1.0 / 60.0, Vec2(x: 1280.0, y: 720.0))
|
|
120
|
-
tr := g.screenTree()
|
|
121
|
-
s := match tr.root.top()
|
|
122
|
-
Some(a) => match a
|
|
123
|
-
WorldScreen as w => w
|
|
124
|
-
_ => WorldScreen(id: 0, frame: -1, camX: 0.0, camY: 0.0)
|
|
125
|
-
None => WorldScreen(id: 0, frame: -1, camX: 0.0, camY: 0.0)
|
|
126
|
-
assert s.frame == 1
|
|
127
|
-
kids := tr.root.kids().kids().chain().toSlice()
|
|
128
|
-
assert kids.length() == 20000
|
|
129
|
-
for i := range 19999
|
|
130
|
-
assert yOf(kids.at(i)) <= yOf(kids.at(i + 1))
|
|
131
|
-
shown := tr.root.kids().kids().fold(0, |n, a| if inView(s, a) then n + 1 else n)
|
|
132
|
-
assert shown > 1500 && shown < 2600
|
examples/games/kids/balloon_pop.plum
DELETED
|
@@ -1,458 +0,0 @@
|
|
|
1
|
-
# Balloon Pop (`plum run examples/games/kids/balloon_pop.plum`): a
|
|
2
|
-
# game for small children. Balloons float up the sky; tap or click one to pop it.
|
|
3
|
-
# A popped balloon bursts into dots and its colour's name floats up ("Red!"), so the
|
|
4
|
-
# child hears the pop and sees the word. Every 10 pops a "Hooray!" party with
|
|
5
|
-
# confetti. There is no way to lose and no timer.
|
|
6
|
-
#
|
|
7
|
-
# The game is a `Game` (std/game/Game) with one screen, `SkyScreen`, in a tree of actors
|
|
8
|
-
# (std/game/SceneTree) that lives from frame to frame. Each balloon is a `Balloon` actor that
|
|
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
|
|
11
|
-
# (`input`), which bursts and sends `Popped(id)` to the store. The screen's `rules` send
|
|
12
|
-
# the tick (`Tick`) and ask for every balloon that is done to come back (`Renew(id)`).
|
|
13
|
-
# `State` is the store's state: the pops, the party, the clock and the `Random`; it says
|
|
14
|
-
# where a renewed balloon goes, and the screen `react`s by putting it in the tree and
|
|
15
|
-
# showing the pops on the hud and the party. The sounds are the effects of the messages
|
|
16
|
-
# (`handle`). A press pops at once: small children tap, they do not click.
|
|
17
|
-
#
|
|
18
|
-
# 0 root (the camera that fits the arena on screen)
|
|
19
|
-
# └─ 5 the screen
|
|
20
|
-
# ├─ 1 sky
|
|
21
|
-
# ├─ 2 balloons ─ 100..105
|
|
22
|
-
# ├─ 3 hud
|
|
23
|
-
# └─ 4 party (shown while partying)
|
|
24
|
-
module balloon_pop
|
|
25
|
-
import std/Str
|
|
26
|
-
import std/Int
|
|
27
|
-
import std/Float
|
|
28
|
-
import std/Bool
|
|
29
|
-
import std/Slice
|
|
30
|
-
import std/Option
|
|
31
|
-
import std/collections/List
|
|
32
|
-
import std/math/math
|
|
33
|
-
import std/math/Random
|
|
34
|
-
import std/math/Vec2
|
|
35
|
-
import std/math/Affine
|
|
36
|
-
import std/game/Color
|
|
37
|
-
import std/game/gfx
|
|
38
|
-
import std/game/audio
|
|
39
|
-
import std/game/Anim
|
|
40
|
-
import std/game/input
|
|
41
|
-
import std/game/Store
|
|
42
|
-
import std/game/Game
|
|
43
|
-
import std/collections/RoseTree
|
|
44
|
-
import std/game/Place
|
|
45
|
-
import std/game/Actor
|
|
46
|
-
import std/game/Clickable
|
|
47
|
-
import std/game/Ctx
|
|
48
|
-
import std/game/SceneTree
|
|
49
|
-
import std/Io
|
|
50
|
-
|
|
51
|
-
ArenaW = 800.0
|
|
52
|
-
ArenaH = 600.0
|
|
53
|
-
Count = 6
|
|
54
|
-
Radius = 40.0
|
|
55
|
-
MinSpeed = 35.0
|
|
56
|
-
MaxSpeed = 70.0
|
|
57
|
-
PopTime = 0.6
|
|
58
|
-
PartyEvery = 10
|
|
59
|
-
PartyTime = 2.5
|
|
60
|
-
|
|
61
|
-
RootId = 0
|
|
62
|
-
ScreenId = 5
|
|
63
|
-
SkyId = 1
|
|
64
|
-
BalloonLayer = 2
|
|
65
|
-
HudId = 3
|
|
66
|
-
PartyId = 4
|
|
67
|
-
BalloonId = 100
|
|
68
|
-
|
|
69
|
-
# The balloon colours a child can name.
|
|
70
|
-
struct Hue(name: Str, color: Color) =
|
|
71
|
-
fun palette() -> List<Hue> =
|
|
72
|
-
[
|
|
73
|
-
Hue(name: "Red", color: Color.rgb(0.93, 0.2, 0.22)),
|
|
74
|
-
Hue(name: "Blue", color: Color.rgb(0.2, 0.45, 0.95)),
|
|
75
|
-
Hue(name: "Yellow", color: Color.rgb(1.0, 0.85, 0.15)),
|
|
76
|
-
Hue(name: "Green", color: Color.rgb(0.25, 0.75, 0.3)),
|
|
77
|
-
Hue(name: "Orange", color: Color.rgb(1.0, 0.55, 0.1)),
|
|
78
|
-
Hue(name: "Purple", color: Color.rgb(0.6, 0.3, 0.85)),
|
|
79
|
-
Hue(name: "Pink", color: Color.rgb(1.0, 0.5, 0.75))
|
|
80
|
-
]
|
|
81
|
-
|
|
82
|
-
fun of(i: Int) -> Hue =
|
|
83
|
-
hues := Hue.palette()
|
|
84
|
-
hues.at(i % hues.length())
|
|
85
|
-
|
|
86
|
-
fun count() -> Int =
|
|
87
|
-
Hue.palette().length()
|
|
88
|
-
|
|
89
|
-
# --- small pure helpers ---
|
|
90
|
-
|
|
91
|
-
# Text centred on `cx` (the host font is about 0.6 of its size wide per letter).
|
|
92
|
-
fun centred(io: Io, m: Affine, s: Str, cx: Float, y: Float, size: Float, color: Color) =
|
|
93
|
-
actor.textPaint(io, m, 1.0, s, cx - size * 0.3 * Float(s.length()), y, size, color)
|
|
94
|
-
|
|
95
|
-
# Grows in, then pulses gently.
|
|
96
|
-
PartyAnim = Seq(
|
|
97
|
-
steps: [
|
|
98
|
-
ScaleTo(sx: 1.4, sy: 1.4, secs: 0.25),
|
|
99
|
-
Forever(anim: Seq(steps: [ScaleTo(sx: 0.85, sy: 0.85, secs: 0.4), ScaleTo(sx: 1.0 / 0.85, sy: 1.0 / 0.85, secs: 0.4)]))
|
|
100
|
-
]
|
|
101
|
-
)
|
|
102
|
-
|
|
103
|
-
fun zoomOf(sw: Float, sh: Float) -> Float =
|
|
104
|
-
{sw / ArenaW}.min(sh / ArenaH)
|
|
105
|
-
|
|
106
|
-
# --- the actors ---
|
|
107
|
-
|
|
108
|
-
# The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
|
|
109
|
-
# It fits the screen in its step.
|
|
110
|
-
struct Camera[Actor<Msg>](id: Int, x: Float, y: Float, zoom: Float) =
|
|
111
|
-
fun key(self) -> Int = self.id
|
|
112
|
-
|
|
113
|
-
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
|
|
114
|
-
|
|
115
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Camera = self.fitted(ctx.view.x, ctx.view.y)
|
|
116
|
-
|
|
117
|
-
# Fitting a `sw` by `sh` screen.
|
|
118
|
-
fun fitted(self, sw: Float, sh: Float) -> Camera =
|
|
119
|
-
z := zoomOf(sw, sh)
|
|
120
|
-
Camera(..self, x: {sw - z * ArenaW} / 2.0, y: {sh - z * ArenaH} / 2.0, zoom: z)
|
|
121
|
-
|
|
122
|
-
# One balloon. `poppedAt` is the clock time it was popped, or negative while whole;
|
|
123
|
-
# `clock` is the game's clock, which it keeps in its own step.
|
|
124
|
-
struct Balloon[Actor<Msg>, Clickable](id: Int, x: Float, y: Float, speed: Float, hue: Int, phase: Float, poppedAt: Float, clock: Float) =
|
|
125
|
-
|
|
126
|
-
# A fresh balloon below the bottom edge, `depth` further down so they do not
|
|
127
|
-
# all arrive together, at the game's `clock`.
|
|
128
|
-
fun spawn(id: Int, rng: Random, depth: Float, clock: Float) -> Spawned =
|
|
129
|
-
rx := rng.nextFloat()
|
|
130
|
-
rs := rx.rng.nextFloat()
|
|
131
|
-
rh := rs.rng.nextIntBelow(Hue.count())
|
|
132
|
-
x := 60.0 + rx.value * {ArenaW - 120.0}
|
|
133
|
-
speed := MinSpeed + rs.value * {MaxSpeed - MinSpeed}
|
|
134
|
-
b := Balloon(id: id, x: x, y: ArenaH + Radius + depth, speed: speed, hue: rh.value, phase: rx.value * Float.Tau, poppedAt: -1.0, clock: clock)
|
|
135
|
-
Spawned(balloon: b, rng: rh.rng)
|
|
136
|
-
|
|
137
|
-
fun key(self) -> Int = self.id
|
|
138
|
-
|
|
139
|
-
# It sways side to side as it rises; once popped it stays where it burst.
|
|
140
|
-
fun place(self) -> Place =
|
|
141
|
-
if self.popped() then place.at(self.x, self.y) else place.at(self.swayX(self.clock), self.y)
|
|
142
|
-
|
|
143
|
-
# A press on a whole balloon bursts it, at its clock (the game's), and tells the store.
|
|
144
|
-
fun input(self, ctx: Ctx<Msg>, e: InputEvent) -> Balloon = match e
|
|
145
|
-
PointerDown(_, _) =>
|
|
146
|
-
if self.popped()
|
|
147
|
-
self
|
|
148
|
-
else
|
|
149
|
-
ctx.send(Popped(id: self.id))
|
|
150
|
-
self.poppedAtClock(self.clock)
|
|
151
|
-
_ => self
|
|
152
|
-
|
|
153
|
-
# Rises while whole.
|
|
154
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Balloon =
|
|
155
|
-
if self.popped() then Balloon(..self, clock: self.clock + dt) else Balloon(..self, y: self.y - self.speed * dt, clock: self.clock + dt)
|
|
156
|
-
|
|
157
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
158
|
-
if self.popped() then self.paintBurst(io, m, self.clock - self.poppedAt) else self.paintWhole(io, m)
|
|
159
|
-
|
|
160
|
-
# A whole balloon is hit on itself, its knot or its string (its shine is inside it, so
|
|
161
|
-
# it needs no test of its own). The cheapest tests come first: the string needs a sine.
|
|
162
|
-
fun hit(self, p: Vec2) -> Bool =
|
|
163
|
-
r := Radius
|
|
164
|
-
!self.popped() && {
|
|
165
|
-
actor.circleHit(0.0, 0.0, r, p)
|
|
166
|
-
|| actor.circleHit(0.0, r + 2.0, 6.0, p)
|
|
167
|
-
|| actor.lineHit(0.0, r, 6.0 * math.sin(self.clock * 3.0 + self.phase), r * 2.6, 2.0, p)}
|
|
168
|
-
|
|
169
|
-
fun popped(self) -> Bool =
|
|
170
|
-
self.poppedAt >= 0.0
|
|
171
|
-
|
|
172
|
-
# Where the balloon is drawn while whole.
|
|
173
|
-
fun swayX(self, clock: Float) -> Float =
|
|
174
|
-
self.x + 14.0 * math.sin(clock * 1.3 + self.phase)
|
|
175
|
-
|
|
176
|
-
# Popped at `clock`, where it is drawn then.
|
|
177
|
-
fun poppedAtClock(self, clock: Float) -> Balloon = Balloon(..self, x: self.swayX(clock), poppedAt: clock)
|
|
178
|
-
|
|
179
|
-
# Gone off the top, or popped long enough ago that the burst has faded.
|
|
180
|
-
fun done(self, clock: Float) -> Bool =
|
|
181
|
-
self.y < 0.0 - Radius * 3.0 || {self.popped() && clock - self.poppedAt > PopTime}
|
|
182
|
-
|
|
183
|
-
fun paintWhole(self, io: Io, m: Affine) =
|
|
184
|
-
r := Radius
|
|
185
|
-
c := Hue.of(self.hue).color
|
|
186
|
-
actor.linePaint(io, m, 1.0, 0.0, r, 6.0 * math.sin(self.clock * 3.0 + self.phase), r * 2.6, 2.0, Color.rgb(0.35, 0.35, 0.35))
|
|
187
|
-
actor.circlePaint(io, m, 1.0, 0.0, r + 2.0, 6.0, c)
|
|
188
|
-
actor.circlePaint(io, m, 1.0, 0.0, 0.0, r, c)
|
|
189
|
-
actor.circlePaint(io, m, 1.0, 0.0 - r * 0.35, 0.0 - r * 0.4, r * 0.22, Color.White.withAlpha(0.55))
|
|
190
|
-
|
|
191
|
-
# Eight dots fly out and fade, and the colour's name floats up.
|
|
192
|
-
fun paintBurst(self, io: Io, m: Affine, age: Float) =
|
|
193
|
-
t := {age / PopTime}.min(1.0)
|
|
194
|
-
fade := 1.0 - t
|
|
195
|
-
hue := Hue.of(self.hue)
|
|
196
|
-
reach := 20.0 + 70.0 * t
|
|
197
|
-
centred(io, m, "{hue.name}!", 0.0, -20.0 - 60.0 * t, 40.0, Color.rgb(0.15, 0.15, 0.3).withAlpha(fade))
|
|
198
|
-
c := hue.color.withAlpha(fade)
|
|
199
|
-
for i := range 8
|
|
200
|
-
a := Float(i) * Float.Tau / 8.0
|
|
201
|
-
actor.circlePaint(io, m, 1.0, math.cos(a) * reach, math.sin(a) * reach, 8.0, c)
|
|
202
|
-
|
|
203
|
-
struct Spawned(balloon: Balloon, rng: Random)
|
|
204
|
-
|
|
205
|
-
# Sky, two drifting clouds and the grass. `clock` is the game's clock.
|
|
206
|
-
struct SkyBox[Actor<Msg>](id: Int, clock: Float) =
|
|
207
|
-
fun key(self) -> Int = self.id
|
|
208
|
-
|
|
209
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
210
|
-
|
|
211
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> SkyBox = SkyBox(..self, clock: self.clock + dt)
|
|
212
|
-
|
|
213
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
214
|
-
actor.rectPaint(io, m, 1.0, 0.0, 0.0, ArenaW, ArenaH, Color.rgb(0.55, 0.8, 1.0))
|
|
215
|
-
actor.rectPaint(io, m, 1.0, 0.0, 0.0, ArenaW, 200.0, Color.rgb(0.45, 0.72, 0.98))
|
|
216
|
-
actor.circlePaint(io, m, 1.0, 690.0, 90.0, 46.0, Color.rgb(1.0, 0.9, 0.35))
|
|
217
|
-
paintCloud(io, m, wrapX(120.0 + self.clock * 12.0), 130.0)
|
|
218
|
-
paintCloud(io, m, wrapX(520.0 + self.clock * 8.0), 220.0)
|
|
219
|
-
actor.rectPaint(io, m, 1.0, 0.0, ArenaH - 50.0, ArenaW, 50.0, Color.rgb(0.4, 0.78, 0.35))
|
|
220
|
-
|
|
221
|
-
fun wrapX(x: Float) -> Float =
|
|
222
|
-
span := ArenaW + 200.0
|
|
223
|
-
x - span * Float(Int(x / span)) - 100.0
|
|
224
|
-
|
|
225
|
-
fun paintCloud(io: Io, m: Affine, x: Float, y: Float) =
|
|
226
|
-
white := Color.White.withAlpha(0.9)
|
|
227
|
-
c := m.mul(place.at(x, y).local())
|
|
228
|
-
actor.circlePaint(io, c, 1.0, -30.0, 8.0, 24.0, white)
|
|
229
|
-
actor.circlePaint(io, c, 1.0, 0.0, 0.0, 32.0, white)
|
|
230
|
-
actor.circlePaint(io, c, 1.0, 32.0, 8.0, 24.0, white)
|
|
231
|
-
|
|
232
|
-
# The pop count, top left.
|
|
233
|
-
struct Hud[Actor<Msg>](id: Int, pops: Int) =
|
|
234
|
-
fun key(self) -> Int = self.id
|
|
235
|
-
|
|
236
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
237
|
-
|
|
238
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
239
|
-
actor.rectPaint(io, m, 1.0, 16.0, 14.0, 170.0, 56.0, Color.White.withAlpha(0.7))
|
|
240
|
-
actor.circlePaint(io, m, 1.0, 46.0, 42.0, 18.0, Hue.of(0).color)
|
|
241
|
-
actor.textPaint(io, m, 1.0, "{self.pops}", 80.0, 20.0, 44.0, Color.rgb(0.15, 0.15, 0.3))
|
|
242
|
-
|
|
243
|
-
# The "Hooray!" party that began at `partyAt` on the game's `clock`: shown for
|
|
244
|
-
# `PartyTime`, with confetti and the pop count.
|
|
245
|
-
struct Party[Actor<Msg>](id: Int, partyAt: Float, clock: Float, pops: Int) =
|
|
246
|
-
fun key(self) -> Int = self.id
|
|
247
|
-
|
|
248
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
249
|
-
|
|
250
|
-
fun shown(self) -> Bool = self.clock - self.partyAt < PartyTime
|
|
251
|
-
|
|
252
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Party = Party(..self, clock: self.clock + dt)
|
|
253
|
-
|
|
254
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
255
|
-
age := self.clock - self.partyAt
|
|
256
|
-
p := Anim.at(PartyAnim, age)
|
|
257
|
-
paintConfetti(io, m, age)
|
|
258
|
-
c := m.mul(place.at(ArenaW / 2.0, 250.0).scaleTo(p.scaleX, p.scaleY).local())
|
|
259
|
-
centred(io, c, "Hooray!", 0.0, -40.0, 72.0, Color.rgb(0.95, 0.3, 0.5))
|
|
260
|
-
centred(io, c, "{self.pops} balloons!", 0.0, 40.0, 40.0, Color.rgb(0.15, 0.15, 0.3))
|
|
261
|
-
|
|
262
|
-
# 30 confetti squares falling from the top, `age` seconds into the party.
|
|
263
|
-
fun paintConfetti(io: Io, m: Affine, age: Float) =
|
|
264
|
-
for i := range 30
|
|
265
|
-
x := Float({i * 7919} % 800)
|
|
266
|
-
y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
|
|
267
|
-
wob := 10.0 * math.sin(age * 4.0 + Float(i))
|
|
268
|
-
actor.rectPaint(io, m, 1.0, x + wob, y, 12.0, 12.0, Hue.of(i).color)
|
|
269
|
-
|
|
270
|
-
# What can happen to the game: a tick of time, a balloon popped, a balloon to bring back.
|
|
271
|
-
enum Msg =
|
|
272
|
-
| Tick(dt: Float)
|
|
273
|
-
| Popped(id: Int)
|
|
274
|
-
| Renew(id: Int)
|
|
275
|
-
|
|
276
|
-
# The store's state: the pops, when the last party began, the game's clock, the
|
|
277
|
-
# randomness, the balloon the last `Renew` made, and the sounds its effects play.
|
|
278
|
-
struct State[Reducer<Msg>](rng: Random, pops: Int, clock: Float, partyAt: Float, renewed: Balloon, popSound: Sound, partySound: Sound) =
|
|
279
|
-
|
|
280
|
-
fun start(seed: Int, popSound: Sound, partySound: Sound) -> State =
|
|
281
|
-
none := Balloon(id: -1, x: 0.0, y: 0.0, speed: 0.0, hue: 0, phase: 0.0, poppedAt: -1.0, clock: 0.0)
|
|
282
|
-
State(rng: Random.seeded(seed), pops: 0, clock: 0.0, partyAt: -100.0, renewed: none, popSound: popSound, partySound: partySound)
|
|
283
|
-
|
|
284
|
-
fun update(self, msg: Msg) -> State = match msg
|
|
285
|
-
Tick(dt) => State(..self, clock: self.clock + dt)
|
|
286
|
-
Popped(_) =>
|
|
287
|
-
pops := self.pops + 1
|
|
288
|
-
State(..self, pops: pops, partyAt: if pops % PartyEvery == 0 then self.clock else self.partyAt)
|
|
289
|
-
Renew(id) =>
|
|
290
|
-
sp := Balloon.spawn(id, self.rng, 0.0, self.clock)
|
|
291
|
-
State(..self, renewed: sp.balloon, rng: sp.rng)
|
|
292
|
-
|
|
293
|
-
# A pop, and a fanfare when it starts a party (a tick has at most one pop).
|
|
294
|
-
fun handle(self, io: Io, msg: Msg) = match msg
|
|
295
|
-
Popped(_) =>
|
|
296
|
-
self.popSound.play(io, 0.9)
|
|
297
|
-
if self.pops % PartyEvery == 0
|
|
298
|
-
self.partySound.play(io, 0.6)
|
|
299
|
-
_ => Unit
|
|
300
|
-
|
|
301
|
-
fun partying(self) -> Bool =
|
|
302
|
-
self.clock - self.partyAt < PartyTime
|
|
303
|
-
|
|
304
|
-
# The first balloons, spread out below the screen, and the generator after them.
|
|
305
|
-
fun firstBalloons(self, i: Int, acc: List<RoseTree<Actor<Msg>>>) -> Filled =
|
|
306
|
-
if i >= Count
|
|
307
|
-
Filled(nodes: acc.reverse(), state: self)
|
|
308
|
-
else
|
|
309
|
-
sp := Balloon.spawn(BalloonId + i, self.rng, Float(i) * 110.0 - ArenaH * 0.6, self.clock)
|
|
310
|
-
State(..self, rng: sp.rng).firstBalloons(i + 1, Cons(head: RoseTree.leaf(sp.balloon), tail: acc))
|
|
311
|
-
|
|
312
|
-
struct Filled(nodes: List<RoseTree<Actor<Msg>>>, state: State)
|
|
313
|
-
|
|
314
|
-
# The one screen, `SkyScreen`: the sky, the balloons, the hud and the party.
|
|
315
|
-
struct SkyScreen[Screen<State, Msg>](id: Int) =
|
|
316
|
-
# The tree and the state of a new game: the camera over the one screen, the balloons
|
|
317
|
-
# spread out below the screen.
|
|
318
|
-
fun start(state: State) -> Play =
|
|
319
|
-
filled := state.firstBalloons(0, Nil)
|
|
320
|
-
sky: RoseTree<Actor<Msg>> := RoseTree.of(SkyScreen(id: ScreenId), [
|
|
321
|
-
RoseTree.leaf(SkyBox(id: SkyId, clock: 0.0)),
|
|
322
|
-
RoseTree.of(Group(id: BalloonLayer, x: 0.0, y: 0.0), filled.nodes),
|
|
323
|
-
RoseTree.leaf(Hud(id: HudId, pops: 0)),
|
|
324
|
-
RoseTree.leaf(Party(id: PartyId, partyAt: -100.0, clock: 0.0, pops: 0))])
|
|
325
|
-
root: RoseTree<Actor<Msg>> := RoseTree.of(Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(ArenaW, ArenaH), [sky])
|
|
326
|
-
Play(tree: SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0), state: filled.state)
|
|
327
|
-
|
|
328
|
-
fun key(self) -> Int = self.id
|
|
329
|
-
|
|
330
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
331
|
-
|
|
332
|
-
# The tick, then a `Renew` for each balloon that is done, in tree order.
|
|
333
|
-
fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
|
|
334
|
-
ctx.send(Tick(dt: dt))
|
|
335
|
-
for b := range balloonsOf(t)
|
|
336
|
-
if b.done(b.clock)
|
|
337
|
-
ctx.send(Renew(id: b.id))
|
|
338
|
-
t
|
|
339
|
-
|
|
340
|
-
fun react(self, t: SceneTree<Msg>, state: State, msg: Msg) -> SceneTree<Msg> = match msg
|
|
341
|
-
Popped(_) =>
|
|
342
|
-
pops := state.pops
|
|
343
|
-
partyAt := state.partyAt
|
|
344
|
-
t.updateAs<Hud>(HudId, |h| Hud(..h, pops: pops)).updateAs<Party>(PartyId, |p| Party(..p, partyAt: partyAt, pops: pops))
|
|
345
|
-
Renew(id) =>
|
|
346
|
-
b := state.renewed
|
|
347
|
-
t.updateAs<Balloon>(id, |x| b)
|
|
348
|
-
_ => t
|
|
349
|
-
|
|
350
|
-
fun draw(self, io: Io, shown: SceneTree<Msg>) =
|
|
351
|
-
gfx.clear(io, Color.rgb(0.55, 0.8, 1.0))
|
|
352
|
-
shown.draw(io)
|
|
353
|
-
|
|
354
|
-
# The balloons of `t`, in tree order: the children of their layer.
|
|
355
|
-
fun balloonsOf(t: SceneTree<Msg>) -> List<Balloon> = t.kidsAs<Balloon>(BalloonLayer)
|
|
356
|
-
|
|
357
|
-
fun firstBalloon(t: SceneTree<Msg>) -> Balloon = t.kidsAs<Balloon>(BalloonLayer).at(0)
|
|
358
|
-
|
|
359
|
-
# A new game's tree and state.
|
|
360
|
-
struct Play(tree: SceneTree<Msg>, state: State)
|
|
361
|
-
|
|
362
|
-
fun main(io: Io) -> Game<State, Msg> =
|
|
363
|
-
play := SkyScreen.start(State.start(io.randomSeed(), audio.loadSound(io, "pickup.wav"), audio.loadSound(io, "gameover.wav")))
|
|
364
|
-
music := audio.loadSound(io, "music.wav")
|
|
365
|
-
music.loop(io, 0.2)
|
|
366
|
-
Game.start(play.tree, play.state)
|
|
367
|
-
|
|
368
|
-
# --- tests ---
|
|
369
|
-
|
|
370
|
-
View800 = Vec2(x: 800.0, y: 600.0)
|
|
371
|
-
|
|
372
|
-
fun newGame() -> Game<State, Msg> =
|
|
373
|
-
play := SkyScreen.start(State.start(3, Sound.Silent, Sound.Silent))
|
|
374
|
-
Game.start(play.tree, play.state)
|
|
375
|
-
|
|
376
|
-
fun first(g: Game<State, Msg>) -> Balloon =
|
|
377
|
-
firstBalloon(g.screenTree())
|
|
378
|
-
|
|
379
|
-
# A tick of `dt` with `events` on a `view` screen.
|
|
380
|
-
fun tickOn(io: Io, g: Game<State, Msg>, events: List<InputEvent>, dt: Float, view: Vec2) -> Game<State, Msg> =
|
|
381
|
-
g.step(io, Input(held: Held.none(), events: events.toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0), dt, view)
|
|
382
|
-
|
|
383
|
-
fun tick(io: Io, g: Game<State, Msg>, events: List<InputEvent>, dt: Float) -> Game<State, Msg> = tickOn(io, g, events, dt, View800)
|
|
384
|
-
|
|
385
|
-
# A game whose first balloon is still and in the middle of the screen.
|
|
386
|
-
fun withCentred(g: Game<State, Msg>) -> Game<State, Msg> =
|
|
387
|
-
Game(..g, tree: g.tree.updateAs<Balloon>(BalloonId, |b| Balloon(..b, x: 400.0, y: 300.0, speed: 0.0, phase: 0.0)))
|
|
388
|
-
|
|
389
|
-
fun pressAt(x: Float, y: Float) -> List<InputEvent> = [PointerDown(x: x, y: y)]
|
|
390
|
-
|
|
391
|
-
test "a new game has its balloons below the screen and no pops"
|
|
392
|
-
g := newGame()
|
|
393
|
-
bs := balloonsOf(g.screenTree())
|
|
394
|
-
assert bs.length() == Count
|
|
395
|
-
assert g.state().pops == 0
|
|
396
|
-
assert bs.fold(true, |ok, b| ok && b.y > ArenaH * 0.4)
|
|
397
|
-
|
|
398
|
-
test "balloons rise"
|
|
399
|
-
g := newGame()
|
|
400
|
-
t := tick(io, g, Nil, 1.0)
|
|
401
|
-
assert first(t).y < first(g).y
|
|
402
|
-
assert first(g).y == first(newGame()).y
|
|
403
|
-
assert t.state().clock == 1.0
|
|
404
|
-
|
|
405
|
-
test "pressing a balloon pops it and counts"
|
|
406
|
-
g := withCentred(newGame())
|
|
407
|
-
t := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
408
|
-
assert t.state().pops == 1
|
|
409
|
-
assert first(t).popped()
|
|
410
|
-
again := tick(io, t, pressAt(400.0, 300.0), 0.01)
|
|
411
|
-
assert again.state().pops == 1
|
|
412
|
-
|
|
413
|
-
test "a balloon is hit on itself, its shine, its knot and its string, and only there"
|
|
414
|
-
b := Balloon(id: 1, x: 0.0, y: 0.0, speed: 0.0, hue: 0, phase: 0.0, poppedAt: -1.0, clock: 0.0)
|
|
415
|
-
r := Radius
|
|
416
|
-
assert b.hit(Vec2(x: 0.0, y: 0.0)) && b.hit(Vec2(x: 0.0 - r * 0.35, y: 0.0 - r * 0.4))
|
|
417
|
-
assert b.hit(Vec2(x: 0.0 - r * 0.35 - r * 0.21, y: 0.0 - r * 0.4))
|
|
418
|
-
assert b.hit(Vec2(x: 0.0, y: r + 6.0)) && b.hit(Vec2(x: 0.0, y: r * 2.5))
|
|
419
|
-
assert !b.hit(Vec2(x: r * 0.8, y: r * 0.8)) && !b.hit(Vec2(x: 0.0, y: r * 2.7))
|
|
420
|
-
assert !Balloon(..b, poppedAt: 0.0).hit(Vec2(x: 0.0, y: 0.0))
|
|
421
|
-
|
|
422
|
-
test "pressing the sky does nothing"
|
|
423
|
-
g := withCentred(newGame())
|
|
424
|
-
t := tick(io, g, pressAt(50.0, 560.0), 0.01)
|
|
425
|
-
assert t.state().pops == 0
|
|
426
|
-
|
|
427
|
-
test "a popped balloon comes back at the bottom"
|
|
428
|
-
g := tick(io, withCentred(newGame()), pressAt(400.0, 300.0), 0.01)
|
|
429
|
-
assert first(g).popped()
|
|
430
|
-
t := tick(io, g, Nil, PopTime + 0.1)
|
|
431
|
-
assert !first(t).popped()
|
|
432
|
-
assert first(t).y > ArenaH
|
|
433
|
-
|
|
434
|
-
test "every tenth pop starts a party that ends"
|
|
435
|
-
fresh := withCentred(newGame())
|
|
436
|
-
g := Game(..fresh, store: Store.of(State(..fresh.state(), pops: 9)))
|
|
437
|
-
assert !g.state().partying()
|
|
438
|
-
assert !g.tree.find(PartyId).unwrap().shown()
|
|
439
|
-
t := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
440
|
-
assert t.state().pops == 10
|
|
441
|
-
assert t.state().partying()
|
|
442
|
-
assert t.tree.find(PartyId).unwrap().shown()
|
|
443
|
-
u := tick(io, t, Nil, PartyTime + 0.1)
|
|
444
|
-
assert !u.state().partying()
|
|
445
|
-
assert !u.tree.find(PartyId).unwrap().shown()
|
|
446
|
-
|
|
447
|
-
test "the press is found through the camera"
|
|
448
|
-
g := tickOn(io, withCentred(newGame()), Nil, 0.01, Vec2(x: 1600.0, y: 600.0))
|
|
449
|
-
miss := tick(io, g, pressAt(400.0, 300.0), 0.01)
|
|
450
|
-
assert miss.state().pops == 0
|
|
451
|
-
hit := tick(io, g, pressAt(800.0, 300.0), 0.01)
|
|
452
|
-
assert hit.state().pops == 1
|
|
453
|
-
|
|
454
|
-
test "the same seed gives the same balloons"
|
|
455
|
-
a := SkyScreen.start(State.start(9, Sound.Silent, Sound.Silent))
|
|
456
|
-
b := SkyScreen.start(State.start(9, Sound.Silent, Sound.Silent))
|
|
457
|
-
assert firstBalloon(a.tree).x == firstBalloon(b.tree).x
|
|
458
|
-
assert firstBalloon(a.tree).hue == firstBalloon(b.tree).hue
|
examples/games/orb_run.plum
DELETED
|
@@ -1,1031 +0,0 @@
|
|
|
1
|
-
# Orb Run (`plum run examples/games/orb_run.plum`). Steer the ship with the arrow keys or
|
|
2
|
-
# WASD, collect the drifting orbs and avoid the mines. Three lives. Enter, R or the "Play"
|
|
3
|
-
# button starts a run from the title; Enter, R or the "Again" button starts another after
|
|
4
|
-
# the game is over, and Escape goes back to the title.
|
|
5
|
-
#
|
|
6
|
-
# The game is a `Game` (std/game/Game) of three screens, `TitleScreen`, `PlayScreen` and
|
|
7
|
-
# `GameOverScreen`, over a store of `State` (std/game/Store). The screens live in one tree
|
|
8
|
-
# of actors (std/game/SceneTree) that lives from frame to frame, under the root camera that
|
|
9
|
-
# fits the arena on screen; the state names the one shown (`State.on`, set by `update`:
|
|
10
|
-
# `PlayScreen.name()` when a run starts), and only that one steps and is drawn. The play
|
|
11
|
-
# screen fades in over the title. Every kind of body is its own struct (`Ship`, `Orb`,
|
|
12
|
-
# `Mine`, `Star`, `Icon`, ..) with only its own fields, and implements `Actor<Msg>`: it
|
|
13
|
-
# says which actor it is (`key`) and where (`place`, made from its plain `x` and `y`), and
|
|
14
|
-
# writes only the behaviour it has: its next version (`step`), its drawing (`paint`). None
|
|
15
|
-
# of them is `Clickable`, so the pointer passes them by. The ship steers itself from the
|
|
16
|
-
# tick's held keys (`ctx.input`) and the root camera fits itself to the screen
|
|
17
|
-
# (`ctx.view`). The backdrop and the dimmer are
|
|
18
|
-
# std's `Box`, the layers std's `Group`, the text std/game/ui's `Label` and the buttons
|
|
19
|
-
# ui's `Button`, which send their `onClick` message when clicked.
|
|
20
|
-
#
|
|
21
|
-
# The tree:
|
|
22
|
-
#
|
|
23
|
-
# 0 root (the camera that fits the arena on screen)
|
|
24
|
-
# ├─ 900 title ─ 1 backdrop, 2 stars ─ 20..59, 15 name, 16 help, 17 "Play"
|
|
25
|
-
# ├─ 901 play
|
|
26
|
-
# │ ├─ 1 backdrop
|
|
27
|
-
# │ ├─ 2 stars ─ 20..59
|
|
28
|
-
# │ ├─ 3 mines ─ 200..
|
|
29
|
-
# │ ├─ 4 orbs ─ 100..102
|
|
30
|
-
# │ ├─ 5 ship
|
|
31
|
-
# │ └─ 6 hud ─ 8 score, 9 best, 300..302 lives
|
|
32
|
-
# └─ 902 game over ─ the play screen's actors when the run ended, with the ship
|
|
33
|
-
# hidden and the bodies stopped, and `7 panel ─ 13 dim, 11 title,
|
|
34
|
-
# 12 prompt, 14 "Again"` on top
|
|
35
|
-
#
|
|
36
|
-
# Play builds a fresh run each time the state switches to it (`enter`), and game over
|
|
37
|
-
# copies the play screen's actors when it comes up.
|
|
38
|
-
#
|
|
39
|
-
# What is between bodies is in the play screen's `rules`, after every actor stepped: the
|
|
40
|
-
# orbs the ship touches (`Collected`), the mines to add as the score grows (`Grow`), a
|
|
41
|
-
# mine that hits the ship (`Hurt`). Those are messages to the store: `State.update` is
|
|
42
|
-
# the rules of the score, the lives and every random spot (all the randomness is the
|
|
43
|
-
# `Random` in `State`, seeded once in `main`, so one seed and one list of inputs give the
|
|
44
|
-
# same game). The screen `react`s to the new state: an orb moves to its new spot, the
|
|
45
|
-
# hud shows the score, a mine is added, the ship flashes and loses an icon. The state goes
|
|
46
|
-
# from the title to play (`Start`), from play to game over (the last `Hurt`) and back to
|
|
47
|
-
# play (`Again`). The sounds are the messages' effects (`State.handle`).
|
|
48
|
-
module orb_run
|
|
49
|
-
import std/Str
|
|
50
|
-
import std/Int
|
|
51
|
-
import std/Float
|
|
52
|
-
import std/Bool
|
|
53
|
-
import std/Slice
|
|
54
|
-
import std/Option
|
|
55
|
-
import std/collections/List
|
|
56
|
-
import std/math/math
|
|
57
|
-
import std/math/Random
|
|
58
|
-
import std/math/Vec2
|
|
59
|
-
import std/math/Affine
|
|
60
|
-
import std/game/Color
|
|
61
|
-
import std/game/gfx
|
|
62
|
-
import std/game/audio
|
|
63
|
-
import std/game/Anim
|
|
64
|
-
import std/game/ui
|
|
65
|
-
import std/game/input
|
|
66
|
-
import std/game/Store
|
|
67
|
-
import std/game/Game
|
|
68
|
-
import std/collections/RoseTree
|
|
69
|
-
import std/game/Place
|
|
70
|
-
import std/game/Actor
|
|
71
|
-
import std/game/Ctx
|
|
72
|
-
import std/game/SceneTree
|
|
73
|
-
import std/Io
|
|
74
|
-
|
|
75
|
-
ArenaW = 800.0
|
|
76
|
-
ArenaH = 600.0
|
|
77
|
-
ShipRadius = 10.0
|
|
78
|
-
OrbRadius = 10.0
|
|
79
|
-
MineRadius = 11.0
|
|
80
|
-
Thrust = 900.0
|
|
81
|
-
Drag = 2.2
|
|
82
|
-
OrbCount = 3
|
|
83
|
-
StartLives = 3
|
|
84
|
-
HurtTime = 1.5
|
|
85
|
-
OrbPoints = 10
|
|
86
|
-
SheetCell = 16.0
|
|
87
|
-
SpriteSize = 48.0
|
|
88
|
-
SpriteHalf = 24.0
|
|
89
|
-
StarCount = 40
|
|
90
|
-
|
|
91
|
-
# Actor ids: the tree's fixed nodes, then the ranges. Orb `i` is `OrbId + i`, mine `i` is
|
|
92
|
-
# `MineId + i`, star `i` is `StarId + i` and life icon `i` is `LifeId + i`.
|
|
93
|
-
RootId = 0
|
|
94
|
-
BackId = 1
|
|
95
|
-
StarLayer = 2
|
|
96
|
-
MineLayer = 3
|
|
97
|
-
OrbLayer = 4
|
|
98
|
-
ShipId = 5
|
|
99
|
-
HudId = 6
|
|
100
|
-
PanelId = 7
|
|
101
|
-
ScoreId = 8
|
|
102
|
-
BestId = 9
|
|
103
|
-
TitleId = 11
|
|
104
|
-
PromptId = 12
|
|
105
|
-
DimId = 13
|
|
106
|
-
RestartId = 14
|
|
107
|
-
NameId = 15
|
|
108
|
-
HelpId = 16
|
|
109
|
-
PlayId = 17
|
|
110
|
-
StarId = 20
|
|
111
|
-
OrbId = 100
|
|
112
|
-
MineId = 200
|
|
113
|
-
LifeId = 300
|
|
114
|
-
TitleScreenId = 900
|
|
115
|
-
PlayScreenId = 901
|
|
116
|
-
GameOverScreenId = 902
|
|
117
|
-
|
|
118
|
-
# A position and velocity: what a spawn returns and what drifters are bounced with.
|
|
119
|
-
struct Motion(x: Float, y: Float, vx: Float, vy: Float)
|
|
120
|
-
|
|
121
|
-
# A random spot and the generator to continue from.
|
|
122
|
-
struct Spawned(at: Motion, rng: Random)
|
|
123
|
-
|
|
124
|
-
# --- small pure helpers ---
|
|
125
|
-
|
|
126
|
-
# Which of `count` animation frames is showing after `clock` seconds at `fps` frames per second.
|
|
127
|
-
fun frameOf(clock: Float, count: Int, fps: Float) -> Int =
|
|
128
|
-
Int(clock * fps) % count
|
|
129
|
-
|
|
130
|
-
fun overlaps(ax: Float, ay: Float, ra: Float, bx: Float, by: Float, rb: Float) -> Bool =
|
|
131
|
-
math.hypot(ax - bx, ay - by) < ra + rb
|
|
132
|
-
|
|
133
|
-
# A random spot at least `gap` away from (ax, ay), drifting at up to `speed`.
|
|
134
|
-
fun spawn(rng: Random, ax: Float, ay: Float, gap: Float, speed: Float) -> Spawned =
|
|
135
|
-
spot := findSpot(rng, ax, ay, gap, 20)
|
|
136
|
-
dh := spot.rng.nextFloat()
|
|
137
|
-
dp := dh.rng.nextFloat()
|
|
138
|
-
heading := dh.value * Float.Tau
|
|
139
|
-
pace := speed * {0.4 + 0.6 * dp.value}
|
|
140
|
-
Spawned(at: Motion(x: spot.at.x, y: spot.at.y, vx: math.cos(heading) * pace, vy: math.sin(heading) * pace), rng: dp.rng)
|
|
141
|
-
|
|
142
|
-
# A random spot at least `gap` away from (ax, ay); after `tries` draws the last one stands.
|
|
143
|
-
fun findSpot(rng: Random, ax: Float, ay: Float, gap: Float, tries: Int) -> Spawned =
|
|
144
|
-
margin := 30.0
|
|
145
|
-
dx := rng.nextFloat()
|
|
146
|
-
dy := dx.rng.nextFloat()
|
|
147
|
-
x := margin + dx.value * {ArenaW - 2.0 * margin}
|
|
148
|
-
y := margin + dy.value * {ArenaH - 2.0 * margin}
|
|
149
|
-
if tries <= 1 || math.hypot(x - ax, y - ay) >= gap
|
|
150
|
-
Spawned(at: Motion(x: x, y: y, vx: 0.0, vy: 0.0), rng: dy.rng)
|
|
151
|
-
else
|
|
152
|
-
findSpot(dy.rng, ax, ay, gap, tries - 1)
|
|
153
|
-
|
|
154
|
-
# `b` moved for `dt` seconds and bounced off the arena walls.
|
|
155
|
-
fun driftOf(b: Motion, r: Float, dt: Float) -> Motion =
|
|
156
|
-
x0 := b.x + b.vx * dt
|
|
157
|
-
y0 := b.y + b.vy * dt
|
|
158
|
-
x := x0.max(r).min(ArenaW - r)
|
|
159
|
-
y := y0.max(r).min(ArenaH - r)
|
|
160
|
-
Motion(x: x, y: y, vx: if x != x0 then 0.0 - b.vx else b.vx, vy: if y != y0 then 0.0 - b.vy else b.vy)
|
|
161
|
-
|
|
162
|
-
# How many mines are out: more as the score grows.
|
|
163
|
-
fun mineCount(score: Int) -> Int =
|
|
164
|
-
{3 + score / 50}.min(8)
|
|
165
|
-
|
|
166
|
-
# The hurt flash: the ship shrinks and recovers every 0.1 s (the scale returns to 1 each lap).
|
|
167
|
-
# A constant, built once, not on every frame that asks for a pose.
|
|
168
|
-
HitFlash = Forever(anim: Seq(steps: [ScaleTo(sx: 0.4, sy: 0.4, secs: 0.05), ScaleTo(sx: 2.5, sy: 2.5, secs: 0.05)]))
|
|
169
|
-
|
|
170
|
-
fun flashPose(t: Float) -> AnimPose =
|
|
171
|
-
Anim.at(HitFlash, t)
|
|
172
|
-
|
|
173
|
-
# The game-over title: grows to 1.3x, then pulses between 1.17x and 1.3x.
|
|
174
|
-
TitleAnim = Seq(
|
|
175
|
-
steps: [
|
|
176
|
-
ScaleTo(sx: 1.3, sy: 1.3, secs: 0.3),
|
|
177
|
-
Forever(anim: Seq(steps: [ScaleTo(sx: 0.9, sy: 0.9, secs: 0.5), ScaleTo(sx: 1.0 / 0.9, sy: 1.0 / 0.9, secs: 0.5)]))
|
|
178
|
-
]
|
|
179
|
-
)
|
|
180
|
-
|
|
181
|
-
fun titlePose(t: Float) -> AnimPose =
|
|
182
|
-
Anim.at(TitleAnim, t)
|
|
183
|
-
|
|
184
|
-
# The zoom that fits the arena into a `sw` by `sh` screen, and where its corner lands.
|
|
185
|
-
fun fitZoom(sw: Float, sh: Float) -> Float =
|
|
186
|
-
{sw / ArenaW}.min(sh / ArenaH)
|
|
187
|
-
|
|
188
|
-
fun fitX(sw: Float, sh: Float) -> Float =
|
|
189
|
-
{sw - fitZoom(sw, sh) * ArenaW} / 2.0
|
|
190
|
-
|
|
191
|
-
fun fitY(sw: Float, sh: Float) -> Float =
|
|
192
|
-
{sh - fitZoom(sw, sh) * ArenaH} / 2.0
|
|
193
|
-
|
|
194
|
-
# --- painting: an actor paints in its own coordinates, seen through `m` (std/game/Actor
|
|
195
|
-
# has boxes, circles, lines and text) ---
|
|
196
|
-
|
|
197
|
-
# A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y).
|
|
198
|
-
fun paintCell(io: Io, m: Affine, alpha: Float, sheet: Texture, x: Float, y: Float, size: Float, col: Int, row: Int) =
|
|
199
|
-
sw := size * m.scaleX()
|
|
200
|
-
sh := size * m.scaleY()
|
|
201
|
-
c := m.apply(Vec2(x: x + size / 2.0, y: y + size / 2.0))
|
|
202
|
-
gfx.drawTextureEx(
|
|
203
|
-
io, sheet.id, Float(col) * SheetCell, Float(row) * SheetCell, SheetCell, SheetCell,
|
|
204
|
-
c.x - sw / 2.0, c.y - sh / 2.0, sw, sh, m.rotation(), false, Color.White.withAlpha(alpha))
|
|
205
|
-
|
|
206
|
-
# --- the kinds ---
|
|
207
|
-
|
|
208
|
-
# Each kind of body is its own struct with only its own fields, and implements `Actor<Msg>`: the
|
|
209
|
-
# tree asks it for its id (`key`), its place in its parent (`place`), its next version
|
|
210
|
-
# (`step`), its drawing (`paint`, in its own coordinates seen through `m`), and whether it
|
|
211
|
-
# is shown and how opaque it is. A kind writes only what differs from the trait's
|
|
212
|
-
# 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
|
|
213
|
-
# about it. The backdrop and the dimmer are std's `Box`, the layers and the hud std's
|
|
214
|
-
# `Group`, the text ui's `Label` and the buttons ui's `Button`.
|
|
215
|
-
|
|
216
|
-
# The root: the camera that fits the arena on the screen, at (x, y) and scaled by `zoom`.
|
|
217
|
-
# It fits the screen in its step.
|
|
218
|
-
struct Camera[Actor<Msg>](id: Int, x: Float, y: Float, zoom: Float) =
|
|
219
|
-
fun key(self) -> Int = self.id
|
|
220
|
-
|
|
221
|
-
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.zoom, self.zoom)
|
|
222
|
-
|
|
223
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Camera = self.fitted(ctx.view.x, ctx.view.y)
|
|
224
|
-
|
|
225
|
-
# Fitting a `sw` by `sh` screen.
|
|
226
|
-
fun fitted(self, sw: Float, sh: Float) -> Camera = Camera(..self, x: fitX(sw, sh), y: fitY(sw, sh), zoom: fitZoom(sw, sh))
|
|
227
|
-
|
|
228
|
-
# A twinkling background star at its fixed spot.
|
|
229
|
-
struct Star[Actor<Msg>](id: Int, i: Int, clock: Float) =
|
|
230
|
-
fun key(self) -> Int = self.id
|
|
231
|
-
|
|
232
|
-
fun place(self) -> Place = place.at(Float({self.i * 7919} % 800), Float({self.i * 104729} % 600))
|
|
233
|
-
|
|
234
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Star = Star(..self, clock: self.clock + dt)
|
|
235
|
-
|
|
236
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
237
|
-
twinkle := 0.25 + 0.2 * math.sin(self.clock * 2.0 + Float(self.i))
|
|
238
|
-
actor.circlePaint(io, m, alpha, 0.0, 0.0, 1.0 + Float(self.i % 3) * 0.5, Color(r: 0.7, g: 0.8, b: 1.0, a: twinkle))
|
|
239
|
-
|
|
240
|
-
# A glowing orb at (x, y) drifting at (vx, vy). `phase` offsets its animation from the
|
|
241
|
-
# other orbs.
|
|
242
|
-
struct Orb[Actor<Msg>](id: Int, x: Float, y: Float, vx: Float, vy: Float, phase: Float, clock: Float, sheet: Texture) =
|
|
243
|
-
fun key(self) -> Int = self.id
|
|
244
|
-
|
|
245
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
246
|
-
|
|
247
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Orb =
|
|
248
|
-
m := driftOf(Motion(x: self.x, y: self.y, vx: self.vx, vy: self.vy), OrbRadius, dt)
|
|
249
|
-
Orb(..self, x: m.x, y: m.y, vx: m.vx, vy: m.vy, clock: self.clock + dt)
|
|
250
|
-
|
|
251
|
-
# The glow is drawn additively, then the sprite on top.
|
|
252
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
253
|
-
gfx.blendMode(io, Blend.Add)
|
|
254
|
-
actor.circlePaint(io, m, alpha, 0.0, 0.0, 26.0, Color(r: 0.35, g: 0.22, b: 0.0, a: 0.5))
|
|
255
|
-
actor.circlePaint(io, m, alpha, 0.0, 0.0, 17.0, Color(r: 0.6, g: 0.4, b: 0.05, a: 0.5))
|
|
256
|
-
gfx.blendMode(io, Blend.Normal)
|
|
257
|
-
paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock + self.phase, 4, 8.0), 1)
|
|
258
|
-
|
|
259
|
-
# Put at `to`, drifting with its velocity.
|
|
260
|
-
fun placed(self, to: Motion) -> Orb = Orb(..self, x: to.x, y: to.y, vx: to.vx, vy: to.vy)
|
|
261
|
-
|
|
262
|
-
# Stopped; it still animates.
|
|
263
|
-
fun still(self) -> Orb = Orb(..self, vx: 0.0, vy: 0.0)
|
|
264
|
-
|
|
265
|
-
# A mine at (x, y) turned by `rotation`, drifting at (vx, vy) and turning at `spin`
|
|
266
|
-
# radians per second.
|
|
267
|
-
struct Mine[Actor<Msg>](id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float, spin: Float, clock: Float, sheet: Texture) =
|
|
268
|
-
fun key(self) -> Int = self.id
|
|
269
|
-
|
|
270
|
-
fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation)
|
|
271
|
-
|
|
272
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Mine =
|
|
273
|
-
m := driftOf(Motion(x: self.x, y: self.y, vx: self.vx, vy: self.vy), MineRadius, dt)
|
|
274
|
-
Mine(..self, x: m.x, y: m.y, rotation: self.rotation + self.spin * dt, vx: m.vx, vy: m.vy, clock: self.clock + dt)
|
|
275
|
-
|
|
276
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
277
|
-
paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 4.0), 2)
|
|
278
|
-
|
|
279
|
-
fun placed(self, to: Motion) -> Mine = Mine(..self, x: to.x, y: to.y, vx: to.vx, vy: to.vy)
|
|
280
|
-
|
|
281
|
-
# Stopped and no longer turning; it still animates.
|
|
282
|
-
fun still(self) -> Mine = Mine(..self, vx: 0.0, vy: 0.0, spin: 0.0)
|
|
283
|
-
|
|
284
|
-
# The player, at (x, y) turned by `rotation`, steered by the held arrow or WASD keys;
|
|
285
|
-
# `hurt` is the time left of its hurt flash and `hurtAge` the time since the hit. Hidden
|
|
286
|
-
# at game over, when it stops.
|
|
287
|
-
struct Ship[Actor<Msg>](
|
|
288
|
-
id: Int, x: Float, y: Float, rotation: Float, vx: Float, vy: Float,
|
|
289
|
-
hurt: Float, hurtAge: Float, clock: Float, sheet: Texture, visible: Bool) =
|
|
290
|
-
|
|
291
|
-
fun key(self) -> Int = self.id
|
|
292
|
-
|
|
293
|
-
fun place(self) -> Place = place.at(self.x, self.y).rotateTo(self.rotation)
|
|
294
|
-
|
|
295
|
-
fun shown(self) -> Bool = self.visible
|
|
296
|
-
|
|
297
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Ship =
|
|
298
|
-
held := ctx.input.held
|
|
299
|
-
self.moved(axisX(held), axisY(held), dt)
|
|
300
|
-
|
|
301
|
-
# Steered by the axes `ax` and `ay` for `dt`: it accelerates by them, drag slows it and
|
|
302
|
-
# the walls stop it.
|
|
303
|
-
fun moved(self, ax: Float, ay: Float, dt: Float) -> Ship =
|
|
304
|
-
if !self.visible
|
|
305
|
-
self
|
|
306
|
-
else
|
|
307
|
-
keep := {1.0 - Drag * dt}.max(0.0)
|
|
308
|
-
r := ShipRadius
|
|
309
|
-
vx0 := {self.vx + ax * Thrust * dt} * keep
|
|
310
|
-
vy0 := {self.vy + ay * Thrust * dt} * keep
|
|
311
|
-
x0 := self.x + vx0 * dt
|
|
312
|
-
y0 := self.y + vy0 * dt
|
|
313
|
-
x := x0.max(r).min(ArenaW - r)
|
|
314
|
-
y := y0.max(r).min(ArenaH - r)
|
|
315
|
-
nvx := if x != x0 then 0.0 else vx0
|
|
316
|
-
nvy := if y != y0 then 0.0 else vy0
|
|
317
|
-
rot := if nvx * nvx + nvy * nvy > 400.0 then math.atan2(nvx, 0.0 - nvy) else self.rotation
|
|
318
|
-
Ship(
|
|
319
|
-
..self, x: x, y: y, rotation: rot, vx: nvx, vy: nvy,
|
|
320
|
-
hurt: {self.hurt - dt}.max(0.0), hurtAge: self.hurtAge + dt, clock: self.clock + dt)
|
|
321
|
-
|
|
322
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
323
|
-
if !self.blinking()
|
|
324
|
-
actor.circlePaint(io, m, alpha, 0.0, 0.0, 17.0, Color(r: 0.4, g: 0.8, b: 1.0, a: 0.12))
|
|
325
|
-
paintCell(io, m, alpha, self.sheet, 0.0 - SpriteHalf, 0.0 - SpriteHalf, SpriteSize, frameOf(self.clock, 4, 14.0), 0)
|
|
326
|
-
|
|
327
|
-
# It blinks off while hurt.
|
|
328
|
-
fun blinking(self) -> Bool = self.hurt > 0.0 && flashPose(self.hurtAge).scaleX < 0.7
|
|
329
|
-
|
|
330
|
-
# Just hit: hurt for `HurtTime`, its flash from the start.
|
|
331
|
-
fun struck(self) -> Ship = Ship(..self, hurt: HurtTime, hurtAge: 0.0)
|
|
332
|
-
|
|
333
|
-
fun hidden(self) -> Ship = Ship(..self, visible: false)
|
|
334
|
-
|
|
335
|
-
# A `size` square cell (col, row) of the sprite sheet with its top-left at (x, y): a life
|
|
336
|
-
# icon.
|
|
337
|
-
struct Icon[Actor<Msg>](id: Int, x: Float, y: Float, size: Float, col: Int, row: Int, sheet: Texture) =
|
|
338
|
-
fun key(self) -> Int = self.id
|
|
339
|
-
|
|
340
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
341
|
-
|
|
342
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = paintCell(io, m, alpha, self.sheet, 0.0, 0.0, self.size, self.col, self.row)
|
|
343
|
-
|
|
344
|
-
# The game-over title centred on (x, y): its scale is `titlePose` of its age.
|
|
345
|
-
struct Banner[Actor<Msg>](id: Int, x: Float, y: Float, scaleX: Float, scaleY: Float, age: Float, color: Color) =
|
|
346
|
-
fun key(self) -> Int = self.id
|
|
347
|
-
|
|
348
|
-
fun place(self) -> Place = place.at(self.x, self.y).scaleTo(self.scaleX, self.scaleY)
|
|
349
|
-
|
|
350
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Banner =
|
|
351
|
-
p := titlePose(self.age + dt)
|
|
352
|
-
Banner(..self, scaleX: p.scaleX, scaleY: p.scaleY, age: self.age + dt)
|
|
353
|
-
|
|
354
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
355
|
-
actor.textPaint(io, m, alpha, "Game over", -100.0, -24.0, 48.0, self.color.withAlpha(1.0))
|
|
356
|
-
|
|
357
|
-
# The game-over panel: its opacity fades in over half a second of its age, and so do its
|
|
358
|
-
# children.
|
|
359
|
-
struct Panel[Actor<Msg>](id: Int, age: Float, alpha: Float) =
|
|
360
|
-
fun key(self) -> Int = self.id
|
|
361
|
-
|
|
362
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
363
|
-
|
|
364
|
-
fun opacity(self) -> Float = self.alpha
|
|
365
|
-
|
|
366
|
-
fun step(self, ctx: Ctx<Msg>, dt: Float) -> Panel =
|
|
367
|
-
Panel(..self, alpha: {{self.age + dt} * 2.0}.min(1.0), age: self.age + dt)
|
|
368
|
-
|
|
369
|
-
# An orb or a mine stopped (the others as they are): what game over does to every body.
|
|
370
|
-
fun stilled(a: Actor<Msg>) -> Actor<Msg> = match a
|
|
371
|
-
Orb as o => o.still()
|
|
372
|
-
Mine as m => m.still()
|
|
373
|
-
_ => a
|
|
374
|
-
|
|
375
|
-
# An orb or a mine put at `to` (the others as they are).
|
|
376
|
-
fun placedAt(a: Actor<Msg>, to: Motion) -> Actor<Msg> = match a
|
|
377
|
-
Orb as o => o.placed(to)
|
|
378
|
-
Mine as m => m.placed(to)
|
|
379
|
-
_ => a
|
|
380
|
-
|
|
381
|
-
# The steering axes from the held arrow or WASD keys.
|
|
382
|
-
fun axisX(held: Held) -> Float =
|
|
383
|
-
axis(held.isDown(Key.Left) || held.isDown(Key.KeyA), held.isDown(Key.Right) || held.isDown(Key.KeyD))
|
|
384
|
-
|
|
385
|
-
fun axisY(held: Held) -> Float =
|
|
386
|
-
axis(held.isDown(Key.Up) || held.isDown(Key.KeyW), held.isDown(Key.Down) || held.isDown(Key.KeyS))
|
|
387
|
-
|
|
388
|
-
fun axis(negative: Bool, positive: Bool) -> Float =
|
|
389
|
-
if negative && !positive
|
|
390
|
-
-1.0
|
|
391
|
-
else if positive && !negative
|
|
392
|
-
1.0
|
|
393
|
-
else
|
|
394
|
-
0.0
|
|
395
|
-
|
|
396
|
-
# Enter or R going down.
|
|
397
|
-
fun isRestartKey(e: InputEvent) -> Bool = match e
|
|
398
|
-
KeyDown(k) => k == Key.Enter || k == Key.KeyR
|
|
399
|
-
_ => false
|
|
400
|
-
|
|
401
|
-
# Whether the tick's input has one of the restart keys going down, or Escape.
|
|
402
|
-
fun pressedRestart(input: Input) -> Bool = input.events.any(|e| isRestartKey(e))
|
|
403
|
-
|
|
404
|
-
fun pressedEscape(input: Input) -> Bool = input.isKeyPressed(Key.Escape)
|
|
405
|
-
|
|
406
|
-
# --- building the trees ---
|
|
407
|
-
|
|
408
|
-
fun group(id: Int, kids: List<RoseTree<Actor<Msg>>>) -> RoseTree<Actor<Msg>> =
|
|
409
|
-
RoseTree.of(Group(id: id, x: 0.0, y: 0.0), kids)
|
|
410
|
-
|
|
411
|
-
fun label(id: Int, text: Str, x: Float, y: Float, size: Float, c: Color) -> RoseTree<Actor<Msg>> =
|
|
412
|
-
RoseTree.leaf(Label(id: id, x: x, y: y, text: text, size: size, color: c))
|
|
413
|
-
|
|
414
|
-
# Stars `i` and up to `StarCount`, each at its fixed spot.
|
|
415
|
-
fun starNodes(i: Int) -> List<RoseTree<Actor<Msg>>> =
|
|
416
|
-
if i >= StarCount
|
|
417
|
-
Nil
|
|
418
|
-
else
|
|
419
|
-
Cons(head: RoseTree.leaf(Star(id: StarId + i, i: i, clock: 0.0)), tail: starNodes(i + 1))
|
|
420
|
-
|
|
421
|
-
# Life icons `i` and up to `StartLives`, from the right edge going left.
|
|
422
|
-
fun lifeNodes(i: Int, sheet: Texture) -> List<RoseTree<Actor<Msg>>> =
|
|
423
|
-
if i >= StartLives
|
|
424
|
-
Nil
|
|
425
|
-
else
|
|
426
|
-
icon := Icon(id: LifeId + i, x: ArenaW - 40.0 - Float(i) * 36.0, y: 12.0, size: 32.0, col: 0, row: 0, sheet: sheet)
|
|
427
|
-
Cons(head: RoseTree.leaf(icon), tail: lifeNodes(i + 1, sheet))
|
|
428
|
-
|
|
429
|
-
fun shipActor(x: Float, y: Float, sheet: Texture) -> Ship =
|
|
430
|
-
Ship(id: ShipId, x: x, y: y, rotation: 0.0, vx: 0.0, vy: 0.0, hurt: 0.0, hurtAge: 0.0, clock: 0.0, sheet: sheet, visible: true)
|
|
431
|
-
|
|
432
|
-
# The camera fitted to a `sw` by `sh` screen.
|
|
433
|
-
fun fittedCamera(sw: Float, sh: Float) -> Camera = Camera(id: RootId, x: 0.0, y: 0.0, zoom: 1.0).fitted(sw, sh)
|
|
434
|
-
|
|
435
|
-
# A screen's subtree: the screen `screen` over `kids`.
|
|
436
|
-
fun screenTree(screen: Actor<Msg>, kids: List<RoseTree<Actor<Msg>>>) -> SceneTree<Msg> =
|
|
437
|
-
node: RoseTree<Actor<Msg>> := RoseTree.of(screen, kids)
|
|
438
|
-
SceneTree(root: node, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
439
|
-
|
|
440
|
-
fun backdrop() -> RoseTree<Actor<Msg>> =
|
|
441
|
-
RoseTree.leaf(Box(id: BackId, x: 0.0, y: 0.0, w: ArenaW, h: ArenaH, color: Color.rgb(0.07, 0.08, 0.16)))
|
|
442
|
-
|
|
443
|
-
# The play screen's subtree of a fresh run, with the run's first orbs and mines
|
|
444
|
-
# (`State.run` places them).
|
|
445
|
-
fun playTree(s: State) -> SceneTree<Msg> =
|
|
446
|
-
orbs: List<RoseTree<Actor<Msg>>> := s.newOrbs.map(|o| RoseTree.leaf(o))
|
|
447
|
-
mines: List<RoseTree<Actor<Msg>>> := s.newMines.map(|m| RoseTree.leaf(m))
|
|
448
|
-
hud := group(HudId, Cons(
|
|
449
|
-
head: label(ScoreId, "Score {s.score}", 16.0, 12.0, 28.0, Color.White),
|
|
450
|
-
tail: Cons(head: label(BestId, "Best {s.best.max(s.score)}", 16.0, 44.0, 20.0, Color.Yellow), tail: lifeNodes(0, s.sheet))))
|
|
451
|
-
screenTree(PlayScreen(id: PlayScreenId), [
|
|
452
|
-
backdrop(),
|
|
453
|
-
group(StarLayer, starNodes(0)),
|
|
454
|
-
group(MineLayer, mines),
|
|
455
|
-
group(OrbLayer, orbs),
|
|
456
|
-
RoseTree.leaf(shipActor(ArenaW / 2.0, ArenaH / 2.0, s.sheet)),
|
|
457
|
-
hud])
|
|
458
|
-
|
|
459
|
-
# The game-over panel that comes up over the play screen.
|
|
460
|
-
fun panelNode() -> RoseTree<Actor<Msg>> =
|
|
461
|
-
RoseTree.of(Panel(id: PanelId, age: 0.0, alpha: 0.0), [
|
|
462
|
-
RoseTree.leaf(Box(id: DimId, x: 0.0, y: 230.0, w: ArenaW, h: 170.0, color: Color(r: 0.0, g: 0.0, b: 0.0, a: 0.6))),
|
|
463
|
-
RoseTree.leaf(Banner(id: TitleId, x: 400.0, y: 268.0, scaleX: 1.0, scaleY: 1.0, age: 0.0, color: Color.Red)),
|
|
464
|
-
label(PromptId, "Press Enter to play again", 270.0, 300.0, 24.0, Color.White),
|
|
465
|
-
RoseTree.leaf(ui.button(RestartId, 340.0, 342.0, 120.0, 44.0, "Again", Again))])
|
|
466
|
-
|
|
467
|
-
# The title screen's subtree.
|
|
468
|
-
fun titleTree() -> SceneTree<Msg> =
|
|
469
|
-
screenTree(TitleScreen(id: TitleScreenId), [
|
|
470
|
-
backdrop(),
|
|
471
|
-
group(StarLayer, starNodes(0)),
|
|
472
|
-
label(NameId, "Orb Run", 280.0, 200.0, 64.0, Color.rgb(1.0, 0.8, 0.3)),
|
|
473
|
-
label(HelpId, "Steer with the arrows or WASD, collect the orbs, dodge the mines", 90.0, 290.0, 20.0, Color.White),
|
|
474
|
-
RoseTree.leaf(ui.button(PlayId, 340.0, 342.0, 120.0, 44.0, "Play", Start))])
|
|
475
|
-
|
|
476
|
-
# The game's tree: the camera that fits the arena on screen over the three screens. Play
|
|
477
|
-
# and game over start empty: each builds its subtree when the state switches to it.
|
|
478
|
-
fun gameTree() -> SceneTree<Msg> =
|
|
479
|
-
empty: List<RoseTree<Actor<Msg>>> := Nil
|
|
480
|
-
screens: List<RoseTree<Actor<Msg>>> := [
|
|
481
|
-
titleTree().root,
|
|
482
|
-
RoseTree.of(PlayScreen(id: PlayScreenId), empty),
|
|
483
|
-
RoseTree.of(GameOverScreen(id: GameOverScreenId), empty)]
|
|
484
|
-
root: RoseTree<Actor<Msg>> := RoseTree.of(fittedCamera(ArenaW, ArenaH), screens)
|
|
485
|
-
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
486
|
-
|
|
487
|
-
# --- the game ---
|
|
488
|
-
|
|
489
|
-
# What can happen to the state: a run starts from the title or again after game over, the
|
|
490
|
-
# ship at (x, y) touches the orb `id`, the mines grow to the score with the ship at
|
|
491
|
-
# (x, y), a mine hits the ship.
|
|
492
|
-
enum Msg =
|
|
493
|
-
| Start
|
|
494
|
-
| Again
|
|
495
|
-
| Collected(id: Int, x: Float, y: Float)
|
|
496
|
-
| Grow(x: Float, y: Float)
|
|
497
|
-
| Hurt
|
|
498
|
-
|
|
499
|
-
# The run between the bodies: the randomness, the score, the lives, how many mines are out
|
|
500
|
-
# (the next one's id is `MineId + mines`), and where the last message put things: the
|
|
501
|
-
# run's first orbs and mines, the spot of a collected orb, the mines just added. The
|
|
502
|
-
# sprite sheet and the sounds are for the screens and the effects.
|
|
503
|
-
struct State[Reducer<Msg>](
|
|
504
|
-
on: Str,
|
|
505
|
-
seed: Int,
|
|
506
|
-
rng: Random,
|
|
507
|
-
score: Int,
|
|
508
|
-
best: Int,
|
|
509
|
-
lives: Int,
|
|
510
|
-
over: Bool,
|
|
511
|
-
mines: Int,
|
|
512
|
-
newOrbs: List<Orb>,
|
|
513
|
-
newMines: List<Mine>,
|
|
514
|
-
spot: Motion,
|
|
515
|
-
sheet: Texture,
|
|
516
|
-
sounds: Sounds
|
|
517
|
-
) =
|
|
518
|
-
|
|
519
|
-
# The state on the title screen: no run yet. The first run is seeded with `seed`.
|
|
520
|
-
fun create(seed: Int, sheet: Texture, sounds: Sounds) -> State =
|
|
521
|
-
State(
|
|
522
|
-
on: TitleScreen.name(), seed: seed, rng: Random.seeded(seed), score: 0, best: 0, lives: StartLives, over: false, mines: 0,
|
|
523
|
-
newOrbs: Nil, newMines: Nil, spot: Motion(x: 0.0, y: 0.0, vx: 0.0, vy: 0.0), sheet: sheet, sounds: sounds)
|
|
524
|
-
|
|
525
|
-
fun update(self, msg: Msg) -> State = match msg
|
|
526
|
-
Start => self.run(self.seed, self.best)
|
|
527
|
-
Again => if self.over then self.run(self.rng.nextInt().value, self.best.max(self.score)) else self
|
|
528
|
-
Collected(_, x, y) =>
|
|
529
|
-
sp := spawn(self.rng, x, y, 120.0, 40.0)
|
|
530
|
-
State(..self, rng: sp.rng, spot: sp.at, score: self.score + OrbPoints)
|
|
531
|
-
Grow(x, y) => self.grown(x, y, Nil)
|
|
532
|
-
Hurt =>
|
|
533
|
-
lives := self.lives - 1
|
|
534
|
-
done := lives <= 0
|
|
535
|
-
State(..self, lives: lives, over: done, best: if done then self.best.max(self.score) else self.best, on: if done then GameOverScreen.name() else self.on)
|
|
536
|
-
|
|
537
|
-
# A fresh run seeded with `seed`, keeping `best`: its orbs and mines spread over the
|
|
538
|
-
# arena away from the ship in the middle.
|
|
539
|
-
fun run(self, seed: Int, best: Int) -> State =
|
|
540
|
-
fresh := State(..self, on: PlayScreen.name(), rng: Random.seeded(seed), score: 0, best: best, lives: StartLives, over: false, mines: 0, newOrbs: Nil)
|
|
541
|
-
orbs := fresh.orbsFrom(0, Nil)
|
|
542
|
-
orbs.grown(ArenaW / 2.0, ArenaH / 2.0, Nil)
|
|
543
|
-
|
|
544
|
-
# Orbs `i` and up to `OrbCount`, each at a random spot away from the ship.
|
|
545
|
-
fun orbsFrom(self, i: Int, acc: List<Orb>) -> State =
|
|
546
|
-
if i >= OrbCount
|
|
547
|
-
State(..self, newOrbs: acc.reverse())
|
|
548
|
-
else
|
|
549
|
-
sp := spawn(self.rng, ArenaW / 2.0, ArenaH / 2.0, 120.0, 40.0)
|
|
550
|
-
orb := Orb(id: OrbId + i, x: sp.at.x, y: sp.at.y, vx: sp.at.vx, vy: sp.at.vy, phase: Float(i) * 0.1, clock: 0.0, sheet: self.sheet)
|
|
551
|
-
State(..self, rng: sp.rng).orbsFrom(i + 1, Cons(head: orb, tail: acc))
|
|
552
|
-
|
|
553
|
-
# Mines added (on top of the others) until there are as many as the score asks for, away
|
|
554
|
-
# from the ship at (x, y).
|
|
555
|
-
fun grown(self, x: Float, y: Float, acc: List<Mine>) -> State =
|
|
556
|
-
if self.mines >= mineCount(self.score)
|
|
557
|
-
State(..self, newMines: acc.reverse())
|
|
558
|
-
else
|
|
559
|
-
sp := spawn(self.rng, x, y, 220.0, 90.0)
|
|
560
|
-
mine := Mine(id: MineId + self.mines, x: sp.at.x, y: sp.at.y, rotation: 0.0, vx: sp.at.vx, vy: sp.at.vy, spin: 2.0, clock: 0.0, sheet: self.sheet)
|
|
561
|
-
State(..self, rng: sp.rng, mines: self.mines + 1).grown(x, y, Cons(head: mine, tail: acc))
|
|
562
|
-
|
|
563
|
-
# The screen shown: the title, the play or the game over.
|
|
564
|
-
fun screen(self) -> Str = self.on
|
|
565
|
-
|
|
566
|
-
# The sounds, with the state after the tick.
|
|
567
|
-
fun handle(self, io: Io, msg: Msg) = match msg
|
|
568
|
-
Again => self.sounds.startMusic(io)
|
|
569
|
-
Collected(_, _, _) => self.sounds.pickup.play(io, 0.8)
|
|
570
|
-
Hurt =>
|
|
571
|
-
if self.over
|
|
572
|
-
self.sounds.music.stop(io)
|
|
573
|
-
self.sounds.over.play(io, 1.0)
|
|
574
|
-
else
|
|
575
|
-
self.sounds.hit.play(io, 1.0)
|
|
576
|
-
_ => Unit
|
|
577
|
-
|
|
578
|
-
struct Sounds(pickup: Sound, hit: Sound, over: Sound, music: Sound) =
|
|
579
|
-
# Restarts the music loop from the top.
|
|
580
|
-
fun startMusic(self, io: Io) =
|
|
581
|
-
self.music.stop(io)
|
|
582
|
-
self.music.loop(io, musicVolume())
|
|
583
|
-
|
|
584
|
-
fun silent() -> Sounds = Sounds(pickup: Sound.Silent, hit: Sound.Silent, over: Sound.Silent, music: Sound.Silent)
|
|
585
|
-
|
|
586
|
-
fun musicVolume() -> Float =
|
|
587
|
-
0.3
|
|
588
|
-
|
|
589
|
-
# The title: Enter, R or the "Play" button start the first run.
|
|
590
|
-
struct TitleScreen[Screen<State, Msg>](id: Int) =
|
|
591
|
-
fun key(self) -> Int = self.id
|
|
592
|
-
|
|
593
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
594
|
-
|
|
595
|
-
fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
|
|
596
|
-
if pressedRestart(ctx.input)
|
|
597
|
-
ctx.send(Start)
|
|
598
|
-
t
|
|
599
|
-
|
|
600
|
-
fun draw(self, io: Io, shown: SceneTree<Msg>) = drawTree(io, shown)
|
|
601
|
-
|
|
602
|
-
# A run: the bodies, the hud and the rules between them. It fades in over the title.
|
|
603
|
-
struct PlayScreen[Screen<State, Msg>](id: Int) =
|
|
604
|
-
fun key(self) -> Int = self.id
|
|
605
|
-
|
|
606
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
607
|
-
|
|
608
|
-
# Each time the state switches to it, a fresh run.
|
|
609
|
-
fun enter(self, t: SceneTree<Msg>, state: State, tree: SceneTree<Msg>) -> SceneTree<Msg> = playTree(state)
|
|
610
|
-
|
|
611
|
-
fun transition(self, from: Str) -> Transition = if from == TitleScreen.name() then Fade(secs: TitleFade) else Cut
|
|
612
|
-
|
|
613
|
-
# After every actor stepped: the orbs the ship touches, the mines to grow, a mine that
|
|
614
|
-
# hits the ship (unless it is still flashing from the last).
|
|
615
|
-
fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
|
|
616
|
-
b := bodiesOf(t)
|
|
617
|
-
sh := b.ship.unwrap()
|
|
618
|
-
for o := range b.orbs
|
|
619
|
-
if overlaps(sh.x, sh.y, ShipRadius, o.x, o.y, OrbRadius)
|
|
620
|
-
ctx.send(Collected(id: o.id, x: sh.x, y: sh.y))
|
|
621
|
-
ctx.send(Grow(x: sh.x, y: sh.y))
|
|
622
|
-
if sh.hurt <= 0.0 && b.mines.find(|m| overlaps(sh.x, sh.y, ShipRadius, m.x, m.y, MineRadius)).isSome()
|
|
623
|
-
ctx.send(Hurt)
|
|
624
|
-
t
|
|
625
|
-
|
|
626
|
-
fun react(self, t: SceneTree<Msg>, state: State, msg: Msg) -> SceneTree<Msg> = match msg
|
|
627
|
-
Collected(id, _, _) =>
|
|
628
|
-
spot := state.spot
|
|
629
|
-
showScore(t.updateAs<Orb>(id, |o| o.placed(spot)), state)
|
|
630
|
-
Grow(_, _) => state.newMines.fold(t, |tr, m| tr.add(MineLayer, RoseTree.leaf(m)))
|
|
631
|
-
Hurt => t.updateAs<Ship>(ShipId, |sh| sh.struck()).kill(LifeId + state.lives)
|
|
632
|
-
_ => t
|
|
633
|
-
|
|
634
|
-
fun draw(self, io: Io, shown: SceneTree<Msg>) = drawTree(io, shown)
|
|
635
|
-
|
|
636
|
-
# How long the play screen takes to fade in over the title, in seconds.
|
|
637
|
-
TitleFade = 0.5
|
|
638
|
-
|
|
639
|
-
# What the play screen's rules read: the ship, the orbs and the mines.
|
|
640
|
-
struct Bodies(ship: Option<Ship>, orbs: List<Orb>, mines: List<Mine>)
|
|
641
|
-
|
|
642
|
-
# The bodies of the play screen's tree `t`, read in one walk along the screen's children
|
|
643
|
-
# (the ship, and the orb and mine layers), so the stars are never visited.
|
|
644
|
-
fun bodiesOf(t: SceneTree<Msg>) -> Bodies =
|
|
645
|
-
layersFrom(t.root.kids(), Bodies(ship: None, orbs: Nil, mines: Nil))
|
|
646
|
-
|
|
647
|
-
fun layersFrom(c: RoseTree<Actor<Msg>>, b: Bodies) -> Bodies = match c
|
|
648
|
-
RoseEmpty => b
|
|
649
|
-
RoseNode(a, k, n) =>
|
|
650
|
-
id := a.key()
|
|
651
|
-
next := if id == OrbLayer
|
|
652
|
-
Bodies(..b, orbs: scenetree.chainAs<Orb, Msg>(k))
|
|
653
|
-
else if id == MineLayer
|
|
654
|
-
Bodies(..b, mines: scenetree.chainAs<Mine, Msg>(k))
|
|
655
|
-
else
|
|
656
|
-
match a
|
|
657
|
-
Ship as sh => Bodies(..b, ship: Some(sh))
|
|
658
|
-
_ => b
|
|
659
|
-
layersFrom(n, next)
|
|
660
|
-
|
|
661
|
-
# The hud's labels from the score.
|
|
662
|
-
fun showScore(t: SceneTree<Msg>, state: State) -> SceneTree<Msg> =
|
|
663
|
-
score := "Score {state.score}"
|
|
664
|
-
best := "Best {state.best.max(state.score)}"
|
|
665
|
-
t.updateAs<Label<Msg>>(ScoreId, |l| l.relabel(score)).updateAs<Label<Msg>>(BestId, |l| l.relabel(best))
|
|
666
|
-
|
|
667
|
-
# Game over: the run's last picture with the ship gone, the bodies stopped (they still
|
|
668
|
-
# animate) and the panel up. Enter, R or "Again" start another run; Escape goes back to
|
|
669
|
-
# the title.
|
|
670
|
-
struct GameOverScreen[Screen<State, Msg>](id: Int) =
|
|
671
|
-
fun key(self) -> Int = self.id
|
|
672
|
-
|
|
673
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
674
|
-
|
|
675
|
-
# The play screen's actors as they are when the run ends, under this screen.
|
|
676
|
-
fun enter(self, t: SceneTree<Msg>, state: State, tree: SceneTree<Msg>) -> SceneTree<Msg> =
|
|
677
|
-
play := tree.subtree(PlayScreenId).unwrap()
|
|
678
|
-
hidden := play.updateAs<Ship>(ShipId, |sh| sh.hidden())
|
|
679
|
-
over: Actor<Msg> := self
|
|
680
|
-
still := hidden.root.withValue(over).map(stilled)
|
|
681
|
-
hidden.withRoot(still).add(GameOverScreenId, panelNode())
|
|
682
|
-
|
|
683
|
-
fun rules(self, t: SceneTree<Msg>, ctx: Ctx<Msg>, state: State, dt: Float) -> SceneTree<Msg> =
|
|
684
|
-
if pressedRestart(ctx.input)
|
|
685
|
-
ctx.send(Again)
|
|
686
|
-
else if pressedEscape(ctx.input)
|
|
687
|
-
ctx.out.push(Restart)
|
|
688
|
-
t
|
|
689
|
-
|
|
690
|
-
fun draw(self, io: Io, shown: SceneTree<Msg>) = drawTree(io, shown)
|
|
691
|
-
|
|
692
|
-
# Every screen clears to the night, then draws the tree.
|
|
693
|
-
fun drawTree(io: Io, t: SceneTree<Msg>) =
|
|
694
|
-
gfx.clear(io, Color.rgb(0.04, 0.05, 0.1))
|
|
695
|
-
t.draw(io)
|
|
696
|
-
|
|
697
|
-
fun main(io: Io) -> Game<State, Msg> =
|
|
698
|
-
sounds := Sounds(
|
|
699
|
-
pickup: audio.loadSound(io, "pickup.wav"),
|
|
700
|
-
hit: audio.loadSound(io, "hit.wav"),
|
|
701
|
-
over: audio.loadSound(io, "gameover.wav"),
|
|
702
|
-
music: audio.loadSound(io, "music.wav"))
|
|
703
|
-
state := State.create(io.randomSeed(), gfx.loadTexture(io, "sprites.png"), sounds)
|
|
704
|
-
sounds.startMusic(io)
|
|
705
|
-
Game.start(gameTree(), state)
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
# --- tests ---
|
|
709
|
-
|
|
710
|
-
View = Vec2(x: 800.0, y: 600.0)
|
|
711
|
-
|
|
712
|
-
fun newGame(seed: Int) -> Game<State, Msg> =
|
|
713
|
-
Game.start(gameTree(), State.create(seed, Texture(id: -1), Sounds.silent()))
|
|
714
|
-
|
|
715
|
-
fun inputOf(keys: List<Int>, events: List<InputEvent>) -> Input =
|
|
716
|
-
Input(held: Held(mouse: false, keys: keys.toSlice()), events: events.toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
717
|
-
|
|
718
|
-
fun press(k: Int) -> List<InputEvent> = [KeyDown(key: k)]
|
|
719
|
-
|
|
720
|
-
fun click(x: Float, y: Float) -> List<InputEvent> = [PointerDown(x: x, y: y), PointerUp(x: x, y: y)]
|
|
721
|
-
|
|
722
|
-
# One tick of 1/60 s (or `dt`) with `keys` held and `events`, on an 800 by 600 screen.
|
|
723
|
-
fun tickOf(io: Io, g: Game<State, Msg>, keys: List<Int>, events: List<InputEvent>) -> Game<State, Msg> =
|
|
724
|
-
g.step(io, inputOf(keys, events), 1.0 / 60.0, View)
|
|
725
|
-
|
|
726
|
-
fun ticksOf(io: Io, g: Game<State, Msg>, n: Int, keys: List<Int>, dt: Float) -> Game<State, Msg> =
|
|
727
|
-
0.until(n).fold(g, |cur, _| cur.step(io, inputOf(keys, Nil), dt, View))
|
|
728
|
-
|
|
729
|
-
# A game on the play screen: the title, then Enter.
|
|
730
|
-
fun started(io: Io, seed: Int) -> Game<State, Msg> = tickOf(io, newGame(seed), Nil, press(Key.Enter))
|
|
731
|
-
|
|
732
|
-
# The current screen's subtree.
|
|
733
|
-
fun treeOf(g: Game<State, Msg>) -> SceneTree<Msg> = g.screenTree()
|
|
734
|
-
|
|
735
|
-
fun onScreen(g: Game<State, Msg>) -> Str =
|
|
736
|
-
if g.current == TitleScreen.name()
|
|
737
|
-
"title"
|
|
738
|
-
else if g.current == PlayScreen.name()
|
|
739
|
-
"play"
|
|
740
|
-
else if g.current == GameOverScreen.name()
|
|
741
|
-
"over"
|
|
742
|
-
else
|
|
743
|
-
"?"
|
|
744
|
-
|
|
745
|
-
# The game with the current screen's subtree replaced by `t`.
|
|
746
|
-
fun withScreenTree(g: Game<State, Msg>, t: SceneTree<Msg>) -> Game<State, Msg> =
|
|
747
|
-
key := g.currentKey()
|
|
748
|
-
Game(..g, tree: g.tree.withRoot(g.tree.root.replace(|a| a.key() == key, |_| t.root)))
|
|
749
|
-
|
|
750
|
-
fun shipOf(g: Game<State, Msg>) -> Ship = treeOf(g).findAs<Ship>(ShipId).unwrap()
|
|
751
|
-
|
|
752
|
-
fun orbAt(g: Game<State, Msg>, id: Int) -> Orb = treeOf(g).findAs<Orb>(id).unwrap()
|
|
753
|
-
|
|
754
|
-
fun mineAt(g: Game<State, Msg>, id: Int) -> Mine = treeOf(g).findAs<Mine>(id).unwrap()
|
|
755
|
-
|
|
756
|
-
fun labelText(g: Game<State, Msg>, id: Int) -> Str = treeOf(g).findAs<Label<Msg>>(id).unwrap().text
|
|
757
|
-
|
|
758
|
-
fun mineCountOf(g: Game<State, Msg>) -> Int = treeOf(g).root.fold(0, |n, a| match a
|
|
759
|
-
Mine as m1 => n + 1
|
|
760
|
-
_ => n)
|
|
761
|
-
|
|
762
|
-
# The game with every actor of its screen's tree through `f`.
|
|
763
|
-
fun mapped(g: Game<State, Msg>, f: fn(Actor<Msg>) -> Actor<Msg>) -> Game<State, Msg> =
|
|
764
|
-
t := treeOf(g)
|
|
765
|
-
withScreenTree(g, t.withRoot(t.root.map(f)))
|
|
766
|
-
|
|
767
|
-
# The game with the actor `id` through `f`.
|
|
768
|
-
fun moved(g: Game<State, Msg>, id: Int, m: Motion) -> Game<State, Msg> =
|
|
769
|
-
withScreenTree(g, treeOf(g).update(id, |a| placedAt(a, m)))
|
|
770
|
-
|
|
771
|
-
fun away() -> Motion =
|
|
772
|
-
Motion(x: 5000.0, y: 0.0, vx: 0.0, vy: 0.0)
|
|
773
|
-
|
|
774
|
-
fun onShip(g: Game<State, Msg>) -> Motion =
|
|
775
|
-
Motion(x: shipOf(g).x, y: shipOf(g).y, vx: 0.0, vy: 0.0)
|
|
776
|
-
|
|
777
|
-
# A game on the play screen with the orbs and mines moved out of the way.
|
|
778
|
-
fun emptyGame(io: Io) -> Game<State, Msg> = mapped(started(io, 7), |a| placedAt(a, away()))
|
|
779
|
-
|
|
780
|
-
fun withState(g: Game<State, Msg>, s: State) -> Game<State, Msg> =
|
|
781
|
-
store := Store.of(s)
|
|
782
|
-
Game(..g, store: store)
|
|
783
|
-
|
|
784
|
-
# A game over with the score `score`: the one life left lost to a mine.
|
|
785
|
-
fun overWith(io: Io, score: Int) -> Game<State, Msg> =
|
|
786
|
-
e := emptyGame(io)
|
|
787
|
-
g := withState(e, State(..e.state(), lives: 1, score: score))
|
|
788
|
-
tickOf(io, moved(g, MineId, onShip(g)), Nil, Nil)
|
|
789
|
-
|
|
790
|
-
fun lone(sh: Ship) -> SceneTree<Msg> = SceneTree.of(sh)
|
|
791
|
-
|
|
792
|
-
fun shipAt(x: Float, y: Float) -> Ship = shipActor(x, y, Texture(id: -1))
|
|
793
|
-
|
|
794
|
-
# What a game draws, in order.
|
|
795
|
-
fun drawnOf(g: Game<State, Msg>) -> List<Drawn<Msg>> = List.fromSlice(g.shown().flatten())
|
|
796
|
-
|
|
797
|
-
fun near(a: Float, b: Float) -> Bool =
|
|
798
|
-
{a - b}.abs() < 0.01
|
|
799
|
-
|
|
800
|
-
# Tick `i` of a scripted run: Right held over ticks 10..59 and Up over 30..89, with a
|
|
801
|
-
# KeyDown and a KeyUp on the ticks they change.
|
|
802
|
-
fun scriptedInput(i: Int) -> Input =
|
|
803
|
-
events := Slice<InputEvent>()
|
|
804
|
-
if i == 10
|
|
805
|
-
events.push(KeyDown(key: Key.Right))
|
|
806
|
-
if i == 30
|
|
807
|
-
events.push(KeyDown(key: Key.Up))
|
|
808
|
-
if i == 60
|
|
809
|
-
events.push(KeyUp(key: Key.Right))
|
|
810
|
-
if i == 90
|
|
811
|
-
events.push(KeyUp(key: Key.Up))
|
|
812
|
-
keys := Slice<Int>()
|
|
813
|
-
if i >= 10 && i < 60
|
|
814
|
-
keys.push(Key.Right)
|
|
815
|
-
if i >= 30 && i < 90
|
|
816
|
-
keys.push(Key.Up)
|
|
817
|
-
Input(held: input.inHeld(keys), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
818
|
-
|
|
819
|
-
# 120 ticks of 1/60 s from `seed` with the scripted inputs.
|
|
820
|
-
fun scriptedRun(io: Io, seed: Int) -> Game<State, Msg> =
|
|
821
|
-
0.until(120).fold(started(io, seed), |g, i| g.step(io, scriptedInput(i), 1.0 / 60.0, View))
|
|
822
|
-
|
|
823
|
-
fun sameRun(a: Game<State, Msg>, b: Game<State, Msg>) -> Bool =
|
|
824
|
-
sum := |g: Game<State, Msg>| treeOf(g).root.fold(0.0, |t, x| match x
|
|
825
|
-
Orb as o => t + o.x + o.y * 1000.0
|
|
826
|
-
_ => t)
|
|
827
|
-
a.state().rng.seed == b.state().rng.seed && a.state().score == b.state().score && a.state().lives == b.state().lives
|
|
828
|
-
&& shipOf(a).x == shipOf(b).x && shipOf(a).y == shipOf(b).y && sum(a) == sum(b) && a.ticks == b.ticks
|
|
829
|
-
|
|
830
|
-
test "the title starts a run on Enter or on its Play button"
|
|
831
|
-
g := newGame(7)
|
|
832
|
-
assert onScreen(g) == "title"
|
|
833
|
-
assert onScreen(tickOf(io, g, Nil, Nil)) == "title"
|
|
834
|
-
assert onScreen(tickOf(io, g, Nil, press(Key.Enter))) == "play"
|
|
835
|
-
# the Play button is at (340, 342), 120 by 44
|
|
836
|
-
assert onScreen(tickOf(io, g, Nil, click(400.0, 364.0))) == "play"
|
|
837
|
-
assert onScreen(tickOf(io, g, Nil, click(100.0, 100.0))) == "title"
|
|
838
|
-
|
|
839
|
-
test "a run's tree has 58 actors, all drawn; game over adds the panel"
|
|
840
|
-
g := started(io, 7)
|
|
841
|
-
assert treeOf(g).count() == 58
|
|
842
|
-
assert treeOf(g).flatten().length() == 58
|
|
843
|
-
over := overWith(io, 0)
|
|
844
|
-
assert onScreen(over) == "over"
|
|
845
|
-
# the last life icon went, the ship is hidden, the panel's five actors came
|
|
846
|
-
assert treeOf(over).count() == 58 - 1 + 5
|
|
847
|
-
assert treeOf(over).flatten().length() == 58 - 1 - 1 + 5
|
|
848
|
-
|
|
849
|
-
test "steering accelerates and drag slows the ship"
|
|
850
|
-
sh := shipAt(ArenaW / 2.0, ArenaH / 2.0).moved(1.0, 0.0, 0.1)
|
|
851
|
-
assert sh.x > ArenaW / 2.0
|
|
852
|
-
assert sh.vx > 0.0
|
|
853
|
-
t := 0.until(30).fold(sh, |cur, _| cur.moved(0.0, 0.0, 0.1))
|
|
854
|
-
assert t.vx < sh.vx / 4.0
|
|
855
|
-
assert t.x - sh.x < 50.0
|
|
856
|
-
|
|
857
|
-
test "the held keys steer the ship in its step"
|
|
858
|
-
g := ticksOf(io, emptyGame(io), 10, [Key.Left, Key.KeyS], 1.0 / 60.0)
|
|
859
|
-
assert shipOf(g).x < ArenaW / 2.0
|
|
860
|
-
assert shipOf(g).y > ArenaH / 2.0
|
|
861
|
-
assert axisX(Held(mouse: false, keys: [Key.Left, Key.Right].toSlice())) == 0.0
|
|
862
|
-
|
|
863
|
-
test "the ship stops at the arena walls"
|
|
864
|
-
s := 0.until(20).fold(shipAt(20.0, 20.0), |cur, _| cur.moved(-1.0, -1.0, 0.1))
|
|
865
|
-
assert s.x == ShipRadius
|
|
866
|
-
assert s.y == ShipRadius
|
|
867
|
-
assert s.vx == 0.0
|
|
868
|
-
|
|
869
|
-
test "orbs bounce off the walls and mines spin as they drift"
|
|
870
|
-
orb := Orb(id: OrbId, x: 795.0, y: 300.0, vx: 100.0, vy: 0.0, phase: 0.0, clock: 0.0, sheet: Texture(id: -1))
|
|
871
|
-
o := orb.step(Ctx<Msg>(), 0.1)
|
|
872
|
-
assert near(o.x, ArenaW - 10.0)
|
|
873
|
-
mine := Mine(id: MineId, x: 400.0, y: 300.0, rotation: 0.0, vx: 10.0, vy: 0.0, spin: 2.0, clock: 0.0, sheet: Texture(id: -1))
|
|
874
|
-
k := mine.step(Ctx<Msg>(), 0.5)
|
|
875
|
-
assert near(k.rotation, 1.0)
|
|
876
|
-
assert near(k.x, 405.0)
|
|
877
|
-
assert near(mine.rotation, 0.0)
|
|
878
|
-
|
|
879
|
-
test "collecting an orb scores, respawns it elsewhere and updates the hud"
|
|
880
|
-
e := emptyGame(io)
|
|
881
|
-
g := moved(e, OrbId, onShip(e))
|
|
882
|
-
t := tickOf(io, g, Nil, Nil)
|
|
883
|
-
orb := orbAt(t, OrbId)
|
|
884
|
-
assert t.state().score == OrbPoints
|
|
885
|
-
assert math.hypot(orb.x - shipOf(t).x, orb.y - shipOf(t).y) >= 120.0
|
|
886
|
-
assert orb.x < 5000.0
|
|
887
|
-
assert labelText(t, ScoreId) == "Score 10"
|
|
888
|
-
assert labelText(g, ScoreId) == "Score 0"
|
|
889
|
-
|
|
890
|
-
test "a mine costs one life and its icon, and makes the ship flash"
|
|
891
|
-
e := emptyGame(io)
|
|
892
|
-
hit := tickOf(io, moved(e, MineId, onShip(e)), Nil, Nil)
|
|
893
|
-
assert hit.state().lives == StartLives - 1
|
|
894
|
-
assert shipOf(hit).hurt > 0.0
|
|
895
|
-
assert treeOf(hit).find(LifeId + 2).isNone()
|
|
896
|
-
assert treeOf(hit).find(LifeId + 1).isSome()
|
|
897
|
-
safe := moved(hit, MineId, away())
|
|
898
|
-
blinks := 0.until(100).fold(Slice<Bool>(), |acc, i|
|
|
899
|
-
acc.push(shipOf(ticksOf(io, safe, i, Nil, 0.016)).blinking())
|
|
900
|
-
acc
|
|
901
|
-
)
|
|
902
|
-
assert blinks.contains(true) && blinks.contains(false)
|
|
903
|
-
later := ticksOf(io, safe, 100, Nil, 0.016)
|
|
904
|
-
assert shipOf(later).hurt == 0.0
|
|
905
|
-
assert later.state().lives == StartLives - 1
|
|
906
|
-
|
|
907
|
-
test "the ship is briefly safe after a hit"
|
|
908
|
-
e := emptyGame(io)
|
|
909
|
-
hit := tickOf(io, moved(e, MineId, onShip(e)), Nil, Nil)
|
|
910
|
-
assert tickOf(io, hit, Nil, Nil).state().lives == StartLives - 1
|
|
911
|
-
|
|
912
|
-
test "the game ends at zero lives: the ship goes, the panel comes up, the bodies stop"
|
|
913
|
-
t := overWith(io, 40)
|
|
914
|
-
assert t.state().over
|
|
915
|
-
assert t.state().lives == 0
|
|
916
|
-
assert t.state().best == 40
|
|
917
|
-
assert !shipOf(t).shown()
|
|
918
|
-
assert treeOf(t).find(PanelId).unwrap().shown()
|
|
919
|
-
x := shipOf(t).x
|
|
920
|
-
mine := mineAt(t, MineId)
|
|
921
|
-
u := ticksOf(io, t, 10, [Key.Right], 0.1)
|
|
922
|
-
assert shipOf(u).x == x
|
|
923
|
-
after := mineAt(u, MineId)
|
|
924
|
-
assert after.x == mine.x && after.rotation == mine.rotation
|
|
925
|
-
assert after.clock > mine.clock + 0.9
|
|
926
|
-
assert orbAt(u, OrbId).clock > 0.9
|
|
927
|
-
assert onScreen(u) == "over"
|
|
928
|
-
|
|
929
|
-
test "again starts a fresh run and keeps the best score; escape goes back to the title"
|
|
930
|
-
over := overWith(io, 90)
|
|
931
|
-
r := tickOf(io, over, Nil, press(Key.Enter))
|
|
932
|
-
assert onScreen(r) == "play"
|
|
933
|
-
assert !r.state().over
|
|
934
|
-
assert r.state().score == 0
|
|
935
|
-
assert r.state().best == 90
|
|
936
|
-
assert r.state().lives == StartLives
|
|
937
|
-
assert shipOf(r).x == ArenaW / 2.0 && shipOf(r).shown()
|
|
938
|
-
assert treeOf(r).find(PanelId).isNone()
|
|
939
|
-
assert mineCountOf(r) == mineCount(0)
|
|
940
|
-
assert labelText(r, BestId) == "Best 90"
|
|
941
|
-
# a click on "Again" does the same
|
|
942
|
-
c := tickOf(io, over, Nil, click(400.0, 364.0))
|
|
943
|
-
assert onScreen(c) == "play" && c.state().best == 90
|
|
944
|
-
assert onScreen(tickOf(io, over, Nil, click(100.0, 100.0))) == "over"
|
|
945
|
-
# Escape restarts the whole game: the title and the first state
|
|
946
|
-
t := tickOf(io, over, Nil, press(Key.Escape))
|
|
947
|
-
assert onScreen(t) == "title"
|
|
948
|
-
assert t.state().best == 0
|
|
949
|
-
# while playing, Enter and the buttons do nothing
|
|
950
|
-
assert tickOf(io, emptyGame(io), Nil, press(Key.Enter)).state().score == 0
|
|
951
|
-
assert onScreen(tickOf(io, emptyGame(io), Nil, press(Key.Escape))) == "play"
|
|
952
|
-
|
|
953
|
-
test "more mines are added to the tree as the score grows"
|
|
954
|
-
assert mineCount(0) == 3
|
|
955
|
-
assert mineCount(100) == 5
|
|
956
|
-
assert mineCount(10000) == 8
|
|
957
|
-
e := emptyGame(io)
|
|
958
|
-
t := tickOf(io, withState(e, State(..e.state(), score: 100)), Nil, Nil)
|
|
959
|
-
assert mineCountOf(t) == 5
|
|
960
|
-
assert treeOf(t).find(MineId + 4).isSome()
|
|
961
|
-
assert t.state().mines == 5
|
|
962
|
-
|
|
963
|
-
test "the same seed plays out the same way"
|
|
964
|
-
a := ticksOf(io, started(io, 11), 120, [Key.Right, Key.Up], 0.016)
|
|
965
|
-
b := ticksOf(io, started(io, 11), 120, [Key.Right, Key.Up], 0.016)
|
|
966
|
-
assert shipOf(a).x == shipOf(b).x
|
|
967
|
-
assert a.state().score == b.state().score
|
|
968
|
-
assert mineAt(a, MineId).x == mineAt(b, MineId).x
|
|
969
|
-
assert orbAt(started(io, 12), OrbId).x != orbAt(started(io, 11), OrbId).x
|
|
970
|
-
|
|
971
|
-
test "a kept old game still has its old tree"
|
|
972
|
-
g := emptyGame(io)
|
|
973
|
-
x := shipOf(g).x
|
|
974
|
-
t := ticksOf(io, g, 6, [Key.Right], 1.0 / 60.0)
|
|
975
|
-
assert shipOf(t).x > x
|
|
976
|
-
assert shipOf(g).x == x
|
|
977
|
-
|
|
978
|
-
test "the root camera fits the arena on the screen"
|
|
979
|
-
g := emptyGame(io).step(io, inputOf(Nil, Nil), 1.0 / 60.0, Vec2(x: 1600.0, y: 600.0))
|
|
980
|
-
root := g.tree.find(RootId).unwrap().place().local()
|
|
981
|
-
assert near(root.a, 1.0)
|
|
982
|
-
assert near(root.e, 400.0)
|
|
983
|
-
assert near(root.f, 0.0)
|
|
984
|
-
|
|
985
|
-
test "the again button is found through the root's camera"
|
|
986
|
-
o := overWith(io, 0)
|
|
987
|
-
assert o.shown().hitId(400.0, 364.0).unwrapOr(-1) == RestartId
|
|
988
|
-
assert o.shown().hitId(100.0, 100.0).unwrapOr(-1) == BackId
|
|
989
|
-
assert emptyGame(io).shown().hitId(400.0, 364.0).unwrapOr(-1) != RestartId
|
|
990
|
-
wide := o.step(io, inputOf(Nil, Nil), 1.0 / 60.0, Vec2(x: 1600.0, y: 600.0))
|
|
991
|
-
assert wide.shown().hitId(800.0, 364.0).unwrapOr(-1) == RestartId
|
|
992
|
-
assert onScreen(tickOf(io, wide, Nil, click(800.0, 364.0))) == "play"
|
|
993
|
-
|
|
994
|
-
test "a press on the button shows it pressed, and a release elsewhere does not click"
|
|
995
|
-
o := overWith(io, 90)
|
|
996
|
-
down := o.step(io, Input(held: Held(mouse: true, keys: Slice<Int>()), events: [PointerDown(x: 400.0, y: 364.0)].toSlice(), pos: Vec2(x: 400.0, y: 364.0), wheel: 0.0), 1.0 / 60.0, View)
|
|
997
|
-
assert onScreen(down) == "over"
|
|
998
|
-
assert treeOf(down).findAs<Button<Msg>>(RestartId).unwrap().look == 2
|
|
999
|
-
up := tickOf(io, down, Nil, [PointerUp(x: 100.0, y: 100.0)])
|
|
1000
|
-
assert onScreen(up) == "over"
|
|
1001
|
-
assert treeOf(up).findAs<Button<Msg>>(RestartId).unwrap().look == 0
|
|
1002
|
-
|
|
1003
|
-
test "the title pulses and the panel fades in by their own clocks"
|
|
1004
|
-
t := ticksOf(io, overWith(io, 0), 15, Nil, 0.02)
|
|
1005
|
-
assert near(treeOf(t).find(PanelId).unwrap().opacity(), 0.6)
|
|
1006
|
-
assert near(treeOf(t).find(TitleId).unwrap().place().local().a, 1.3)
|
|
1007
|
-
assert near(titlePose(0.8).scaleX, 1.17)
|
|
1008
|
-
assert near(flashPose(0.05).scaleX, 0.4)
|
|
1009
|
-
|
|
1010
|
-
test "same_seed_same_game: one seed and one input list give the same run"
|
|
1011
|
-
a := scriptedRun(io, 42)
|
|
1012
|
-
b := scriptedRun(io, 42)
|
|
1013
|
-
assert sameRun(a, b)
|
|
1014
|
-
assert shipOf(a).x != shipOf(started(io, 42)).x
|
|
1015
|
-
assert !sameRun(a, scriptedRun(io, 43))
|
|
1016
|
-
|
|
1017
|
-
test "the play screen fades in over the title, which is frozen meanwhile"
|
|
1018
|
-
g := started(io, 7)
|
|
1019
|
-
assert onScreen(g) == "play" && g.shift.isSome()
|
|
1020
|
-
# both drawn: the title's name and play's ship
|
|
1021
|
-
assert drawnOf(g).find(|d| d.actor.key() == NameId).isSome()
|
|
1022
|
-
assert drawnOf(g).find(|d| d.actor.key() == ShipId).unwrap().alpha == 0.0
|
|
1023
|
-
title := g.tree.subtree(TitleScreenId).unwrap()
|
|
1024
|
-
mid := ticksOf(io, g, 15, Nil, 1.0 / 60.0)
|
|
1025
|
-
assert near(drawnOf(mid).find(|d| d.actor.key() == ShipId).unwrap().alpha, 0.5)
|
|
1026
|
-
assert mid.tree.subtree(TitleScreenId).unwrap().root.kids() == title.root.kids()
|
|
1027
|
-
done := ticksOf(io, mid, 15, Nil, 1.0 / 60.0)
|
|
1028
|
-
assert done.shift.isNone()
|
|
1029
|
-
assert drawnOf(done).find(|d| d.actor.key() == NameId).isNone()
|
|
1030
|
-
# again after game over comes in at once
|
|
1031
|
-
assert tickOf(io, overWith(io, 90), Nil, press(Key.Enter)).shift.isNone()
|
examples/games/{assets → orbitrunner/assets}/gameover.wav
RENAMED
|
File without changes
|
examples/games/{assets → orbitrunner/assets}/hit.wav
RENAMED
|
File without changes
|
examples/games/{assets → orbitrunner/assets}/music.wav
RENAMED
|
File without changes
|
examples/games/{assets → orbitrunner/assets}/pickup.wav
RENAMED
|
File without changes
|
examples/games/{assets → orbitrunner/assets}/sprites.png
RENAMED
|
File without changes
|
std/game/Clickable.plum
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Bool
|
|
4
|
-
import std/math/Vec2
|
|
5
|
-
|
|
6
|
-
# An actor the pointer can hit, as well as an `Actor<M>`: `struct Button<M>[Actor<M>,
|
|
7
|
-
# Clickable](..)`. `hit` says whether `p`, in the actor's own coordinates, is on it. Only a
|
|
8
|
-
# `Clickable` actor gets pointer events (`SceneTree.input`) and is found by
|
|
9
|
-
# `SceneTree.hit`; the tree's pointer walk skips every other actor with one type-tag test,
|
|
10
|
-
# and computes no transform for one without children. A `hit` on an actor that isn't
|
|
11
|
-
# `Clickable` is a plain method the tree never calls.
|
|
12
|
-
trait Clickable =
|
|
13
|
-
fun hit(self, p: Vec2) -> Bool
|
std/game/Ctx.plum
DELETED
|
@@ -1,188 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Str
|
|
6
|
-
import std/collections/List
|
|
7
|
-
import std/Slice
|
|
8
|
-
import std/math/Vec2
|
|
9
|
-
import std/math/Affine
|
|
10
|
-
import std/game/input
|
|
11
|
-
import std/collections/RoseTree
|
|
12
|
-
import std/game/Actor
|
|
13
|
-
import std/game/SceneTree
|
|
14
|
-
import std/Option
|
|
15
|
-
|
|
16
|
-
# What a step changes besides the actors. `Spawn` and `Kill` are the tree's: they are
|
|
17
|
-
# applied once the step's walk is over (`SceneTree.apply`): a new node under the actor
|
|
18
|
-
# `parent` (by id), on top of its children, or the end of the actor `id` and its subtree.
|
|
19
|
-
# The rest are the game's (std/game/Game), and the tree leaves them in `ctx.out`, in
|
|
20
|
-
# order: `Send` is a message of the game's type `M` for its store, `Restart` starts the
|
|
21
|
-
# game over from its first tree and state, and `Exit` ends it (no tick runs after).
|
|
22
|
-
enum Cmd<M> =
|
|
23
|
-
| Spawn(parent: Int, node: RoseTree<Actor<M>>)
|
|
24
|
-
| Kill(id: Int)
|
|
25
|
-
| Send(msg: M)
|
|
26
|
-
| Restart
|
|
27
|
-
| Exit
|
|
28
|
-
|
|
29
|
-
# Whether it is the game's (`Send`, `Restart`, `Exit`) rather than the tree's.
|
|
30
|
-
fun isGame(self) -> Bool = match self
|
|
31
|
-
Spawn(_, _) => false
|
|
32
|
-
Kill(_) => false
|
|
33
|
-
_ => true
|
|
34
|
-
|
|
35
|
-
fun isSend(self) -> Bool = match self
|
|
36
|
-
Send(_) => true
|
|
37
|
-
_ => false
|
|
38
|
-
|
|
39
|
-
# What the step hands each actor in place of a parent link: the context of the actor's
|
|
40
|
-
# parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so an
|
|
41
|
-
# actor's own world transform is `ctx.worldOf(self.place().local())` and its alpha
|
|
42
|
-
# `ctx.alphaOf(self.opacity())`, computed only when it asks. `input` is the tick's input
|
|
43
|
-
# (held keys, the pointer, the events) and `view` the size of the screen in pixels. `out` takes the commands an actor pushes for after
|
|
44
|
-
# the walk (`ctx.out.push(Spawn(..))`, `ctx.out.push(Kill(..))`, `ctx.send(msg)`,
|
|
45
|
-
# `ctx.out.push(Restart)`).
|
|
46
|
-
#
|
|
47
|
-
# fun step(self, ctx: Ctx<Msg>, dt: Float) -> Gun =
|
|
48
|
-
# ctx.out.push(Spawn(parent: 0, node: RoseTree.leaf(Bullet(id: self.next, x: self.x, y: self.y))))
|
|
49
|
-
# Gun(..self, next: self.next + 1)
|
|
50
|
-
#
|
|
51
|
-
# `scene` is the tree being stepped (`SceneTree.step` sets it; empty for a context made
|
|
52
|
-
# by hand), so an actor can ask which actor the pointer is on (`pointedAt`); `pointed`
|
|
53
|
-
# keeps the answer once found, shared by every context of one step's walk.
|
|
54
|
-
#
|
|
55
|
-
# A context is a value. The walk makes one for each parent with children (`under`), with
|
|
56
|
-
# one multiply, and hands it to every child.
|
|
57
|
-
struct Ctx<M>(up: Affine, alpha: Float, input: Input, view: Vec2, out: Slice<Cmd<M>>, scene: RoseTree<Actor<M>>, pointed: Slice<Int>) =
|
|
58
|
-
|
|
59
|
-
# The context above a tree's root: the identity transform, full opacity, no input, no
|
|
60
|
-
# screen and no commands.
|
|
61
|
-
fun init() -> Ctx<M> = Ctx.of(Input.create(), Vec2(x: 0.0, y: 0.0))
|
|
62
|
-
|
|
63
|
-
# The context above a tree's root for a tick with `input` on a screen of `view` pixels.
|
|
64
|
-
fun of(input: Input, view: Vec2) -> Ctx<M> =
|
|
65
|
-
Ctx(up: Affine.Identity, alpha: 1.0, input: input, view: view, out: Slice<Cmd<M>>(), scene: RoseEmpty, pointed: Slice<Int>())
|
|
66
|
-
|
|
67
|
-
# The context for a step's walk over the tree `root`: the same input, view and commands,
|
|
68
|
-
# with `root` as the scene `pointedAt` looks in.
|
|
69
|
-
fun over(self, root: RoseTree<Actor<M>>) -> Ctx<M> =
|
|
70
|
-
Ctx(..self, scene: root, pointed: Slice<Int>())
|
|
71
|
-
|
|
72
|
-
# The key of the actor a pointer event at the tick's pointer would go to: the topmost
|
|
73
|
-
# shown `Clickable` actor there that says it is hit (as `SceneTree.input` routes one),
|
|
74
|
-
# or None. A widget shows itself hovered only when it is this one, so of two overlapping
|
|
75
|
-
# buttons only the one a click reaches is hovered. Found once per step's walk, the first
|
|
76
|
-
# time an actor asks; None when the context has no scene.
|
|
77
|
-
fun pointedAt(self) -> Option<Int> =
|
|
78
|
-
if self.scene.isEmpty()
|
|
79
|
-
None
|
|
80
|
-
else
|
|
81
|
-
if self.pointed.length() == 0
|
|
82
|
-
self.pointed.push(scenetree.hitChain(self.scene, self.input.pos).map(|a| a.key()).unwrapOr(NoPointedActor))
|
|
83
|
-
k := self.pointed.at(0)
|
|
84
|
-
if k == NoPointedActor then None else Some(k)
|
|
85
|
-
|
|
86
|
-
# The world transform of a child whose own transform is `local`.
|
|
87
|
-
fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
|
|
88
|
-
|
|
89
|
-
# The accumulated alpha of a child whose own is `a`.
|
|
90
|
-
fun alphaOf(self, a: Float) -> Float = self.alpha * a
|
|
91
|
-
|
|
92
|
-
# The context for the children of a child with the transform `local` and opacity `a`:
|
|
93
|
-
# the same commands, the child's world transform above them.
|
|
94
|
-
fun under(self, local: Affine, a: Float) -> Ctx<M> =
|
|
95
|
-
Ctx(..self, up: self.up.mul(local), alpha: self.alpha * a)
|
|
96
|
-
|
|
97
|
-
# Sends `msg` to the game after the step.
|
|
98
|
-
fun send(self, msg: M) = self.out.push(Send(msg: msg))
|
|
99
|
-
|
|
100
|
-
# The messages sent so far, oldest first, taken out of `out` (its other commands stay,
|
|
101
|
-
# in order).
|
|
102
|
-
fun takeSends(self) -> List<M> =
|
|
103
|
-
if self.out.length() == 0
|
|
104
|
-
Nil
|
|
105
|
-
else
|
|
106
|
-
msgs := Slice<M>()
|
|
107
|
-
for c := range self.out
|
|
108
|
-
if Send(m) := c
|
|
109
|
-
msgs.push(m)
|
|
110
|
-
kept := Slice<Cmd<M>>()
|
|
111
|
-
for c := range self.out
|
|
112
|
-
if !c.isSend()
|
|
113
|
-
kept.push(c)
|
|
114
|
-
self.out.clear()
|
|
115
|
-
self.out.add(kept)
|
|
116
|
-
List.fromSlice(msgs)
|
|
117
|
-
|
|
118
|
-
# Keeps in `out` only the game's commands (`game` true) or only the tree's, in order.
|
|
119
|
-
fun keepOnly(self, game: Bool) =
|
|
120
|
-
if !allGame(self.out, game, 0)
|
|
121
|
-
kept := Slice<Cmd<M>>()
|
|
122
|
-
for c := range self.out
|
|
123
|
-
if c.isGame() == game
|
|
124
|
-
kept.push(c)
|
|
125
|
-
self.out.clear()
|
|
126
|
-
self.out.add(kept)
|
|
127
|
-
|
|
128
|
-
# `Ctx.pointed`'s mark for "the pointer is on no actor".
|
|
129
|
-
NoPointedActor = -1000003
|
|
130
|
-
|
|
131
|
-
# Whether each command of `cmds` from index `i` on is the game's (`game`) or each the
|
|
132
|
-
# tree's (not `game`).
|
|
133
|
-
fun allGame<M>(cmds: Slice<Cmd<M>>, game: Bool, i: Int) -> Bool =
|
|
134
|
-
if i >= cmds.length()
|
|
135
|
-
true
|
|
136
|
-
else if cmds.at(i).isGame() != game
|
|
137
|
-
false
|
|
138
|
-
else
|
|
139
|
-
allGame(cmds, game, i + 1)
|
|
140
|
-
|
|
141
|
-
fun cmdName<M>(c: Cmd<M>) -> Str = match c
|
|
142
|
-
Spawn(_, _) => "Spawn"
|
|
143
|
-
Kill(_) => "Kill"
|
|
144
|
-
Send(_) => "Send"
|
|
145
|
-
Restart => "Restart"
|
|
146
|
-
Exit => "Exit"
|
|
147
|
-
|
|
148
|
-
test "under multiplies the child's transform into the parent's"
|
|
149
|
-
c := Ctx<Int>()
|
|
150
|
-
m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
|
|
151
|
-
u := c.under(m, 0.5).under(m, 0.5)
|
|
152
|
-
assert u.up.a == 4.0 && u.up.e == 3.0
|
|
153
|
-
assert u.alpha == 0.25
|
|
154
|
-
assert u.worldOf(m).e == 7.0
|
|
155
|
-
u.out.push(Kill(id: 3))
|
|
156
|
-
assert c.out.length() == 1
|
|
157
|
-
|
|
158
|
-
test "sends are taken out in order and the other commands stay"
|
|
159
|
-
c := Ctx<Str>()
|
|
160
|
-
c.send("a")
|
|
161
|
-
c.out.push(Kill(id: 3))
|
|
162
|
-
c.under(Affine.Identity, 1.0).send("b")
|
|
163
|
-
c.out.push(Kill(id: 4))
|
|
164
|
-
msgs := c.takeSends()
|
|
165
|
-
assert msgs.length() == 2 && msgs.get(0).unwrap() == "a" && msgs.get(1).unwrap() == "b"
|
|
166
|
-
assert c.out.length() == 2
|
|
167
|
-
assert c.takeSends().isEmpty()
|
|
168
|
-
assert c.out.length() == 2
|
|
169
|
-
|
|
170
|
-
test "restart and exit are the game's, and stay with the sends"
|
|
171
|
-
c := Ctx<Str>()
|
|
172
|
-
c.out.push(Kill(id: 1))
|
|
173
|
-
c.out.push(Restart)
|
|
174
|
-
c.send("a")
|
|
175
|
-
c.out.push(Exit)
|
|
176
|
-
c.keepOnly(true)
|
|
177
|
-
assert c.out.length() == 3
|
|
178
|
-
assert c.takeSends().length() == 1
|
|
179
|
-
assert c.out.length() == 2
|
|
180
|
-
assert cmdName(c.out.at(0)) == "Restart" && cmdName(c.out.at(1)) == "Exit"
|
|
181
|
-
|
|
182
|
-
test "a context carries the tick's input down the tree"
|
|
183
|
-
i := Input(held: Held(mouse: true, keys: Slice<Int>()), events: Slice<InputEvent>(), pos: Vec2(x: 3.0, y: 4.0), wheel: 0.0)
|
|
184
|
-
c: Ctx<Int> := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
|
|
185
|
-
assert c.under(Affine.Identity, 1.0).input.pos.x == 3.0
|
|
186
|
-
assert c.under(Affine.Identity, 1.0).view.y == 600.0
|
|
187
|
-
assert c.input.isMouseDown()
|
|
188
|
-
assert !Ctx<Int>().input.isMouseDown()
|
std/game/SceneTree.plum
DELETED
|
@@ -1,1003 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Bool
|
|
6
|
-
import std/Str
|
|
7
|
-
import std/Option
|
|
8
|
-
import std/collections/List
|
|
9
|
-
import std/Slice
|
|
10
|
-
import std/Array
|
|
11
|
-
import std/collections/Map
|
|
12
|
-
import std/collections/Set
|
|
13
|
-
import std/Pair
|
|
14
|
-
import std/math/math
|
|
15
|
-
import std/Io
|
|
16
|
-
import std/math/Vec2
|
|
17
|
-
import std/math/Affine
|
|
18
|
-
import std/game/Color
|
|
19
|
-
import std/game/gfx
|
|
20
|
-
import std/game/input
|
|
21
|
-
import std/collections/RoseTree
|
|
22
|
-
import std/game/Actor
|
|
23
|
-
import std/game/Clickable
|
|
24
|
-
import std/game/Place
|
|
25
|
-
import std/game/Ctx
|
|
26
|
-
|
|
27
|
-
# The game's scene: a persistent tree of actors of any kind that implements `Actor<M>` (see
|
|
28
|
-
# std/game/Actor), `M` being the game's message type. The root is an
|
|
29
|
-
# `RoseTree<Actor<M>>`, a left-child, right-sibling tree of actors, and a scene tree is a
|
|
30
|
-
# value: every change returns a new tree. While something holds the old tree it stays as
|
|
31
|
-
# it was, a snapshot; when nothing does, the compiler reuses its cells for the new one.
|
|
32
|
-
#
|
|
33
|
-
# s: SceneTree<Msg> := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)) # a root group, id 0
|
|
34
|
-
# s2 := s.add(0, RoseTree.leaf(Box(id: 1, x: 10.0, y: 5.0, w: 40.0, h: 20.0, color: Color.Red)))
|
|
35
|
-
# ctx := Ctx<Msg>()
|
|
36
|
-
# s3 := s2.step(ctx, dt) # every actor's next version, then the commands in ctx.out
|
|
37
|
-
# s3.draw(io)
|
|
38
|
-
#
|
|
39
|
-
# The tree uses only what the trait gives: it finds actors by `key()` (`add(parent, n)`,
|
|
40
|
-
# `update(id, f)`, `find(id)`, `kill(id)`, `Spawn(parent, n)`, `Kill(id)`, each by a
|
|
41
|
-
# search down from the root, O(n); `step` applies all of a tick's commands in its own
|
|
42
|
-
# walk), drops a `gone()` actor with its subtree, skips one that is not `shown()` (or is
|
|
43
|
-
# gone) with its subtree when it draws and hit tests, and multiplies the transforms
|
|
44
|
-
# (`place().local()`) and alphas (`opacity()`) down the tree. Each actor's own type gives
|
|
45
|
-
# the behaviour: `step`, `paint`, and `hit` for one that is also `Clickable` (only those
|
|
46
|
-
# get pointer events). The tree never needs an actor's own type; game code that does uses
|
|
47
|
-
# `updateAs<T>` and `findAs<T>`, which act only on an actor of the type `T`.
|
|
48
|
-
#
|
|
49
|
-
# Children are kept in draw order: a parent is drawn before its children, and siblings
|
|
50
|
-
# first to last. Hit testing goes the other way, topmost first: children before their
|
|
51
|
-
# parent, later siblings before earlier ones.
|
|
52
|
-
#
|
|
53
|
-
# The walks `step` and `apply` rebuild every link node they pass: each is one loop along a
|
|
54
|
-
# sibling chain (the compiler builds the chain front to back, tail modulo cons), with
|
|
55
|
-
# recursion only into children. Keeping an unchanged node instead (`@sameRef` on its actor,
|
|
56
|
-
# children and later siblings) needs the siblings' result before the node is built, so the
|
|
57
|
-
# walk recurses along the chain; that costs more than the nodes it saves, even when 99% of
|
|
58
|
-
# the actors stand still (benchmarks/scene_trees, workloads 10 and 11). `input`, which
|
|
59
|
-
# rebuilds only the nodes on the hit actor's path (and relinks the siblings before each),
|
|
60
|
-
# keeps every node off that path, and the hit node itself when the actor's `input`
|
|
61
|
-
# returns it as it was (`Actor`'s default); a value compared by
|
|
62
|
-
# `@sameRef` is never updated in place, so a changed actor is always another
|
|
63
|
-
# object. `withRoot`, `apply` with nothing to do and `input` that hits nothing return the
|
|
64
|
-
# tree itself.
|
|
65
|
-
struct SceneTree<M>(root: RoseTree<Actor<M>>, camX: Float, camY: Float, camScale: Float) =
|
|
66
|
-
|
|
67
|
-
# A tree whose root is the actor `top`.
|
|
68
|
-
fun of(top: Actor<M>) -> SceneTree<M> =
|
|
69
|
-
SceneTree(root: RoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
70
|
-
|
|
71
|
-
# The same camera over another tree; this very tree when `r` is its own root.
|
|
72
|
-
fun withRoot(self, r: RoseTree<Actor<M>>) -> SceneTree<M> = if @sameRef(r, self.root) then self else SceneTree(..self, root: r)
|
|
73
|
-
|
|
74
|
-
# A game's tree (std/game/Game): a root group (id `ScreensRootId`) whose children are the
|
|
75
|
-
# screens, in order.
|
|
76
|
-
fun ofScreens(screens: List<RoseTree<Actor<M>>>) -> SceneTree<M> =
|
|
77
|
-
root: Actor<M> := Group(id: ScreensRootId, x: 0.0, y: 0.0)
|
|
78
|
-
SceneTree(root: RoseTree.of(root, screens), camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
79
|
-
|
|
80
|
-
# The same tree with its root actor replaced by `a` (its children kept).
|
|
81
|
-
fun withTop(self, a: Actor<M>) -> SceneTree<M> = self.withRoot(self.root.withValue(a))
|
|
82
|
-
|
|
83
|
-
# The actor `id` with its subtree, as a tree of its own (the same camera), if there is
|
|
84
|
-
# one: what a screen copies from another (`tree.subtree(PlayScreen)`).
|
|
85
|
-
fun subtree(self, id: Int) -> Option<SceneTree<M>> =
|
|
86
|
-
n := nodeOf(self.root, id)
|
|
87
|
-
if n.isEmpty() then None else Some(self.withRoot(n))
|
|
88
|
-
|
|
89
|
-
fun pan(self, x: Float, y: Float) -> SceneTree<M> = SceneTree(..self, camX: x, camY: y)
|
|
90
|
-
|
|
91
|
-
fun zoom(self, s: Float) -> SceneTree<M> = SceneTree(..self, camScale: s)
|
|
92
|
-
|
|
93
|
-
# The number of actors.
|
|
94
|
-
fun count(self) -> Int = self.root.count()
|
|
95
|
-
|
|
96
|
-
# The actor with this id, if any.
|
|
97
|
-
fun find(self, id: Int) -> Option<Actor<M>> = self.root.find(|a| a.key() == id)
|
|
98
|
-
|
|
99
|
-
# The actor with this id as its own type `T`, if there is one and it is a `T`:
|
|
100
|
-
# `tree.findAs<Ship>(ShipId)`.
|
|
101
|
-
fun findAs<T>(self, id: Int) -> Option<T> = match self.find(id)
|
|
102
|
-
Some(T as t) => Some(t)
|
|
103
|
-
_ => None
|
|
104
|
-
|
|
105
|
-
# Every actor of the type `T`, in tree order (a parent before its children, siblings
|
|
106
|
-
# in order): `tree.allAs<Orb>()`.
|
|
107
|
-
fun allAs<T>(self) -> List<T> =
|
|
108
|
-
self.root.fold(Nil, |acc, a| match a
|
|
109
|
-
T as t => Cons(head: t, tail: acc)
|
|
110
|
-
_ => acc).reverse()
|
|
111
|
-
|
|
112
|
-
# The children of the actor `parent` that are `T`s, in order: one layer, not their
|
|
113
|
-
# subtrees (`tree.kidsAs<Balloon>(BalloonLayer)`). Empty if there is no such actor.
|
|
114
|
-
fun kidsAs<T>(self, parent: Int) -> List<T> = chainAs<T, M>(nodeOf(self.root, parent).kids())
|
|
115
|
-
|
|
116
|
-
# The tree with `n` added as the last child of the actor `parent`; unchanged if there
|
|
117
|
-
# is no such actor.
|
|
118
|
-
fun add(self, parent: Int, n: RoseTree<Actor<M>>) -> SceneTree<M> =
|
|
119
|
-
self.withRoot(self.root.replace(|a| a.key() == parent, |p| p.addChild(n)))
|
|
120
|
-
|
|
121
|
-
# The tree with the actor `id` replaced by `f(actor)`; everything off its path is
|
|
122
|
-
# shared.
|
|
123
|
-
fun update(self, id: Int, f: fn(Actor<M>) -> Actor<M>) -> SceneTree<M> =
|
|
124
|
-
self.withRoot(self.root.update(|a| a.key() == id, f))
|
|
125
|
-
|
|
126
|
-
# The tree with the actor `id` replaced by `f(actor)` if it is a `T`, and unchanged if
|
|
127
|
-
# it is not: `tree.updateAs<Orb>(id, |o| Orb(..o, vx: 0.0))`.
|
|
128
|
-
fun updateAs<T>(self, id: Int, f: fn(T) -> T) -> SceneTree<M> =
|
|
129
|
-
self.withRoot(self.root.update(|a| a.key() == id, |a| match a
|
|
130
|
-
T as t =>
|
|
131
|
-
b: Actor<M> := f(t)
|
|
132
|
-
b
|
|
133
|
-
_ => a))
|
|
134
|
-
|
|
135
|
-
# The tree without the actor `id` and its subtree.
|
|
136
|
-
fun kill(self, id: Int) -> SceneTree<M> = self.withRoot(self.root.filter(|a| a.key() != id))
|
|
137
|
-
|
|
138
|
-
# The next tick: every live actor's `step`, parents before children, siblings in
|
|
139
|
-
# order, each given its parent's context under `ctx` (the context above the root). An
|
|
140
|
-
# actor whose step returns it gone is dropped with its subtree. Every `Spawn` and
|
|
141
|
-
# `Kill` in `ctx.out` takes effect after the step, as `apply` would apply it. Those
|
|
142
|
-
# pushed before the step are applied in its own walk: an actor killed this way is
|
|
143
|
-
# dropped without its step, and a spawned node goes on top of its parent's children
|
|
144
|
-
# unstepped. Those pushed during the step (by the actors) are applied by `apply` once
|
|
145
|
-
# the walk is over, as a second batch. Hidden actors are stepped too. `ctx.out` is left
|
|
146
|
-
# with only the game's commands (`Send`, `Restart`, `Exit`), those pushed before the
|
|
147
|
-
# step first, in order, for the game to take (`ctx.takeSends()`).
|
|
148
|
-
# A tick whose commands are all the game's (most ticks) walks with no batch at all, and
|
|
149
|
-
# one whose actors push no `Spawn` or `Kill` applies nothing after it.
|
|
150
|
-
fun step(self, ctx: Ctx<M>, dt: Float) -> SceneTree<M> =
|
|
151
|
-
c := ctx.over(self.root)
|
|
152
|
-
r := if gameOnly(ctx.out, 0)
|
|
153
|
-
stepPlain(self.root, c, dt)
|
|
154
|
-
else
|
|
155
|
-
w := TreeWalk.ofTree(ctx.out)
|
|
156
|
-
ctx.keepOnly(true)
|
|
157
|
-
stepChain(self.root, c, dt, w, RoseEmpty)
|
|
158
|
-
s := self.withRoot(r)
|
|
159
|
-
if gameOnly(ctx.out, 0)
|
|
160
|
-
s
|
|
161
|
-
else
|
|
162
|
-
s2 := s.apply(ctx.out)
|
|
163
|
-
ctx.keepOnly(true)
|
|
164
|
-
s2
|
|
165
|
-
|
|
166
|
-
# The tree with the commands applied, in one pass over the tree: every `Kill` actor
|
|
167
|
-
# goes with its subtree, and every `Spawn` node goes on top of its parent's children,
|
|
168
|
-
# in the order pushed. A spawn whose parent is not on the tree, or is killed by the
|
|
169
|
-
# same batch, is dropped. The game's commands (`Send`, `Restart`, `Exit`) are skipped.
|
|
170
|
-
fun apply(self, cmds: Slice<Cmd<M>>) -> SceneTree<M> =
|
|
171
|
-
if gameOnly(cmds, 0)
|
|
172
|
-
self
|
|
173
|
-
else
|
|
174
|
-
w := TreeWalk.ofTree(cmds)
|
|
175
|
-
self.withRoot(applyChain(self.root, w, RoseEmpty))
|
|
176
|
-
|
|
177
|
-
# The tree after the pointer event `e` (in tree coordinates; a key event changes
|
|
178
|
-
# nothing): the topmost shown `Clickable` actor under it that says it is hit (as `hit`
|
|
179
|
-
# finds it) gets it through `input`, then each of its parents up to the root, clickable
|
|
180
|
-
# or not. Each gets `e` in its own coordinates (as `hit` gets its point) and its
|
|
181
|
-
# parent's context under `ctx` (as `step` gives it). With no actor under the pointer
|
|
182
|
-
# the tree is returned as it was. The hit actor is found first, with no context built
|
|
183
|
-
# (`hitPath`); then only the nodes on its path are walked again, each child's context
|
|
184
|
-
# made from its parent's.
|
|
185
|
-
fun input(self, ctx: Ctx<M>, e: InputEvent) -> SceneTree<M> = match e.position()
|
|
186
|
-
None => self
|
|
187
|
-
Some(p) => match hitPath(self.root, p, 0)
|
|
188
|
-
Some(path) => match path
|
|
189
|
-
Cons(i, rest) => self.withRoot(routeChain(self.root, ctx, p, e, i, rest))
|
|
190
|
-
Nil => self
|
|
191
|
-
None => self
|
|
192
|
-
|
|
193
|
-
# What `draw` would draw, in order: each shown actor with its tree transform and alpha,
|
|
194
|
-
# a parent before its children, siblings first to last.
|
|
195
|
-
fun flatten(self) -> Slice<Drawn<M>> =
|
|
196
|
-
out := Slice<Drawn<M>>()
|
|
197
|
-
collectChain(self.root, Affine.Identity, 1.0, out)
|
|
198
|
-
out
|
|
199
|
-
|
|
200
|
-
# The topmost shown `Clickable` actor at a tree point that says it is hit there
|
|
201
|
-
# (`hit(p)`, with `p` in the actor's own coordinates).
|
|
202
|
-
fun hit(self, x: Float, y: Float) -> Option<Actor<M>> = hitChain(self.root, Vec2(x: x, y: y))
|
|
203
|
-
|
|
204
|
-
# The id of that actor, if any.
|
|
205
|
-
fun hitId(self, x: Float, y: Float) -> Option<Int> = self.hit(x, y).map(|a| a.key())
|
|
206
|
-
|
|
207
|
-
# Draws the tree through its camera.
|
|
208
|
-
fun draw(self, io: Io) =
|
|
209
|
-
gfx.setCamera(io, self.camX, self.camY, self.camScale)
|
|
210
|
-
self.paint(io)
|
|
211
|
-
gfx.resetCamera(io)
|
|
212
|
-
|
|
213
|
-
# Draws the tree as `draw` does, without setting the camera: for a screen that sets its
|
|
214
|
-
# own, or draws in screen pixels.
|
|
215
|
-
fun paint(self, io: Io) = drawChain(self.root, io, Affine.Identity, 1.0)
|
|
216
|
-
|
|
217
|
-
# The id of the root `SceneTree.ofScreens` makes.
|
|
218
|
-
ScreensRootId = -1
|
|
219
|
-
|
|
220
|
-
# The node of the actor `id` in the chain `t` or below, alone (with its subtree, without
|
|
221
|
-
# its siblings); empty if there is none.
|
|
222
|
-
fun nodeOf<M>(t: RoseTree<Actor<M>>, id: Int) -> RoseTree<Actor<M>> = match t
|
|
223
|
-
RoseEmpty => t
|
|
224
|
-
RoseNode(a, k, n) =>
|
|
225
|
-
if a.key() == id
|
|
226
|
-
t.alone()
|
|
227
|
-
else
|
|
228
|
-
below := nodeOf(k, id)
|
|
229
|
-
if below.isEmpty() then nodeOf(n, id) else below
|
|
230
|
-
|
|
231
|
-
# The actors of the chain `c` (not their subtrees) that are `T`s, in order.
|
|
232
|
-
fun chainAs<T, M>(c: RoseTree<Actor<M>>) -> List<T> =
|
|
233
|
-
chainAsOnto<T, M>(c, Nil).reverse()
|
|
234
|
-
|
|
235
|
-
fun chainAsOnto<T, M>(c: RoseTree<Actor<M>>, acc: List<T>) -> List<T> = match c
|
|
236
|
-
RoseEmpty => acc
|
|
237
|
-
RoseNode(a, _, n) => chainAsOnto<T, M>(n, match a
|
|
238
|
-
T as t => Cons(head: t, tail: acc)
|
|
239
|
-
_ => acc)
|
|
240
|
-
|
|
241
|
-
# One entry of the draw list: a shown actor, its tree transform and its alpha.
|
|
242
|
-
struct Drawn<M>(actor: Actor<M>, m: Affine, alpha: Float)
|
|
243
|
-
|
|
244
|
-
# The largest id range the bitsets cover is [0, 2^22).
|
|
245
|
-
BitsCap = 4194304
|
|
246
|
-
|
|
247
|
-
# The largest id seen in a batch, and whether all of them fit the bitsets.
|
|
248
|
-
struct TreeScan(mut top: Int, mut ok: Bool) =
|
|
249
|
-
fun see(self, id: Int) =
|
|
250
|
-
if id < 0 || id >= BitsCap
|
|
251
|
-
self.ok = false
|
|
252
|
-
else if id > self.top
|
|
253
|
-
self.top = id
|
|
254
|
-
|
|
255
|
-
# A batch of commands as a walk uses them: the ids to drop, and the nodes to add under
|
|
256
|
-
# each parent id, in the order pushed. The walk asks about every actor, so beside the set
|
|
257
|
-
# and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
|
|
258
|
-
# answers are a shift and a mask, and only an actor with spawns does a map lookup. Ids
|
|
259
|
-
# below 0 or from 2^22 up make that batch use the set and the map alone. A batch with no
|
|
260
|
-
# `Kill` and no `Spawn` (most ticks) has neither: it builds nothing.
|
|
261
|
-
struct TreeWalk<M>(
|
|
262
|
-
kills: Option<Set<Int>>, spawns: Option<Map<Int, Slice<RoseTree<Actor<M>>>>>,
|
|
263
|
-
hasKills: Bool, hasSpawns: Bool,
|
|
264
|
-
bitsOk: Bool, killBits: Array<Int>, spawnBits: Array<Int>) =
|
|
265
|
-
|
|
266
|
-
fun of(cmds: Slice<Cmd<M>>) -> TreeWalk<M> =
|
|
267
|
-
if gameOnly(cmds, 0)
|
|
268
|
-
TreeWalk(kills: None, spawns: None, hasKills: false, hasSpawns: false, bitsOk: true, killBits: Array<Int>(), spawnBits: Array<Int>())
|
|
269
|
-
else
|
|
270
|
-
TreeWalk.ofTree(cmds)
|
|
271
|
-
|
|
272
|
-
# `of` for a batch with a `Kill` or a `Spawn`.
|
|
273
|
-
fun ofTree(cmds: Slice<Cmd<M>>) -> TreeWalk<M> =
|
|
274
|
-
noSpawns: Map<Int, Slice<RoseTree<Actor<M>>>> := Map.empty()
|
|
275
|
-
start: Pair<Set<Int>, Map<Int, Slice<RoseTree<Actor<M>>>>> := Pair(first: Set<Int>(), second: noSpawns)
|
|
276
|
-
scan := TreeScan(top: 0, ok: true)
|
|
277
|
-
found := cmds.fold(start, |acc, c|
|
|
278
|
-
match c
|
|
279
|
-
Kill(id) =>
|
|
280
|
-
scan.see(id)
|
|
281
|
-
Pair(first: acc.first.add(id), second: acc.second)
|
|
282
|
-
Spawn(parent, node) =>
|
|
283
|
-
scan.see(parent)
|
|
284
|
-
match acc.second.get(parent)
|
|
285
|
-
Some(xs) =>
|
|
286
|
-
xs.push(node)
|
|
287
|
-
acc
|
|
288
|
-
None =>
|
|
289
|
-
ys := Slice<RoseTree<Actor<M>>>()
|
|
290
|
-
ys.push(node)
|
|
291
|
-
Pair(first: acc.first, second: acc.second.with(parent, ys))
|
|
292
|
-
_ => acc
|
|
293
|
-
)
|
|
294
|
-
kills := found.first
|
|
295
|
-
spawns := found.second
|
|
296
|
-
words := if scan.ok && {kills.length() > 0 || spawns.length() > 0} then scan.top / 64 + 1 else 0
|
|
297
|
-
killBits := Array<Int>().resize(words)
|
|
298
|
-
spawnBits := Array<Int>().resize(words)
|
|
299
|
-
if words > 0
|
|
300
|
-
for c := range cmds
|
|
301
|
-
match c
|
|
302
|
-
Kill(id) => bitSet(killBits, id)
|
|
303
|
-
Spawn(parent, _) => bitSet(spawnBits, parent)
|
|
304
|
-
_ => Unit
|
|
305
|
-
TreeWalk(
|
|
306
|
-
kills: Some(kills), spawns: Some(spawns),
|
|
307
|
-
hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
|
|
308
|
-
bitsOk: scan.ok, killBits: killBits, spawnBits: spawnBits)
|
|
309
|
-
|
|
310
|
-
# Whether the actor `id` is killed by this batch.
|
|
311
|
-
fun killed(self, id: Int) -> Bool =
|
|
312
|
-
if !self.hasKills
|
|
313
|
-
false
|
|
314
|
-
else if self.bitsOk
|
|
315
|
-
bitHas(self.killBits, id)
|
|
316
|
-
else
|
|
317
|
-
match self.kills
|
|
318
|
-
Some(k) => k.contains(id)
|
|
319
|
-
None => false
|
|
320
|
-
|
|
321
|
-
# The nodes to add under the actor `id`, as a chain in the order pushed (empty if none).
|
|
322
|
-
fun spawnsUnder(self, id: Int) -> RoseTree<Actor<M>> =
|
|
323
|
-
if !self.hasSpawns || {self.bitsOk && !bitHas(self.spawnBits, id)}
|
|
324
|
-
RoseEmpty
|
|
325
|
-
else
|
|
326
|
-
match self.spawns
|
|
327
|
-
Some(m) => match m.get(id)
|
|
328
|
-
Some(xs) => chainFrom(xs, 0)
|
|
329
|
-
None => RoseEmpty
|
|
330
|
-
None => RoseEmpty
|
|
331
|
-
|
|
332
|
-
# Whether the commands of `cmds` from index `i` on are all the game's (no `Kill`, no
|
|
333
|
-
# `Spawn`).
|
|
334
|
-
fun gameOnly<M>(cmds: Slice<Cmd<M>>, i: Int) -> Bool =
|
|
335
|
-
if i >= cmds.length()
|
|
336
|
-
true
|
|
337
|
-
else if !cmds.at(i).isGame()
|
|
338
|
-
false
|
|
339
|
-
else
|
|
340
|
-
gameOnly(cmds, i + 1)
|
|
341
|
-
|
|
342
|
-
# The nodes of `ns` from index `i` on (each with its subtree, not its siblings), linked
|
|
343
|
-
# into one chain, in order: `RoseTree.chainOf` for a `Slice`.
|
|
344
|
-
fun chainFrom<T>(ns: Slice<RoseTree<T>>, i: Int) -> RoseTree<T> =
|
|
345
|
-
if i >= ns.length()
|
|
346
|
-
RoseEmpty
|
|
347
|
-
else
|
|
348
|
-
match ns.at(i)
|
|
349
|
-
RoseEmpty => chainFrom(ns, i + 1)
|
|
350
|
-
RoseNode(v, k, _) => RoseNode(value: v, firstChild: k, nextSibling: chainFrom(ns, i + 1))
|
|
351
|
-
|
|
352
|
-
fun bitSet(bits: Array<Int>, id: Int) =
|
|
353
|
-
w := id / 64
|
|
354
|
-
bits.set(w, bits.at(w) | {1 << {id % 64}})
|
|
355
|
-
|
|
356
|
-
fun bitHas(bits: Array<Int>, id: Int) -> Bool =
|
|
357
|
-
w := id / 64
|
|
358
|
-
if id < 0 || w >= bits.length() then false else {{bits.at(w) >> {id % 64}} & 1} == 1
|
|
359
|
-
|
|
360
|
-
# `stepChain` for a tick with no `Kill` and no `Spawn` before the step: no batch to ask.
|
|
361
|
-
fun stepPlain<M>(t: RoseTree<Actor<M>>, ctx: Ctx<M>, dt: Float) -> RoseTree<Actor<M>> = match t
|
|
362
|
-
RoseEmpty => t
|
|
363
|
-
RoseNode(a, k, n) =>
|
|
364
|
-
if a.gone()
|
|
365
|
-
stepPlain(n, ctx, dt)
|
|
366
|
-
else
|
|
367
|
-
walkKids := !k.isEmpty()
|
|
368
|
-
cc := if walkKids then ctx.under(a.place().local(), a.opacity()) else ctx
|
|
369
|
-
na := a.step(ctx, dt)
|
|
370
|
-
if na.gone()
|
|
371
|
-
stepPlain(n, ctx, dt)
|
|
372
|
-
else
|
|
373
|
-
k2 := if walkKids then stepPlain(k, cc, dt) else k
|
|
374
|
-
RoseNode(value: na, firstChild: k2, nextSibling: stepPlain(n, ctx, dt))
|
|
375
|
-
|
|
376
|
-
# The chain `t` one step on, under `ctx` (the context of the chain's parent), without the
|
|
377
|
-
# actors `w` kills, and followed by `extra` (the parent's spawns, unstepped). An actor with
|
|
378
|
-
# children (or spawns) gets one context for them, made from its place before its step.
|
|
379
|
-
# Every kept node is rebuilt: in place when nothing else holds `t`.
|
|
380
|
-
fun stepChain<M>(t: RoseTree<Actor<M>>, ctx: Ctx<M>, dt: Float, w: TreeWalk<M>, extra: RoseTree<Actor<M>>) -> RoseTree<Actor<M>> = match t
|
|
381
|
-
RoseEmpty => extra
|
|
382
|
-
RoseNode(a, k, n) =>
|
|
383
|
-
if a.gone() || {w.hasKills && w.killed(a.key())}
|
|
384
|
-
stepChain(n, ctx, dt, w, extra)
|
|
385
|
-
else
|
|
386
|
-
xs := if w.hasSpawns then w.spawnsUnder(a.key()) else RoseEmpty
|
|
387
|
-
walkKids := !k.isEmpty() || !xs.isEmpty()
|
|
388
|
-
cc := if walkKids then ctx.under(a.place().local(), a.opacity()) else ctx
|
|
389
|
-
na := a.step(ctx, dt)
|
|
390
|
-
if na.gone()
|
|
391
|
-
stepChain(n, ctx, dt, w, extra)
|
|
392
|
-
else
|
|
393
|
-
k2 := if walkKids then stepChain(k, cc, dt, w, xs) else k
|
|
394
|
-
RoseNode(value: na, firstChild: k2, nextSibling: stepChain(n, ctx, dt, w, extra))
|
|
395
|
-
|
|
396
|
-
# The chain `t` without the actors `w` kills and followed by `extra`, with the same done
|
|
397
|
-
# in every subtree: `apply`'s walk.
|
|
398
|
-
fun applyChain<M>(t: RoseTree<Actor<M>>, w: TreeWalk<M>, extra: RoseTree<Actor<M>>) -> RoseTree<Actor<M>> = match t
|
|
399
|
-
RoseEmpty => extra
|
|
400
|
-
RoseNode(a, k, n) =>
|
|
401
|
-
id := a.key()
|
|
402
|
-
if w.killed(id)
|
|
403
|
-
applyChain(n, w, extra)
|
|
404
|
-
else
|
|
405
|
-
xs := w.spawnsUnder(id)
|
|
406
|
-
k2 := if k.isEmpty() && xs.isEmpty() then k else applyChain(k, w, xs)
|
|
407
|
-
RoseNode(value: a, firstChild: k2, nextSibling: applyChain(n, w, extra))
|
|
408
|
-
|
|
409
|
-
# Whether the walks that draw and hit test go into `a`: shown, and not gone.
|
|
410
|
-
fun isShown<M>(a: Actor<M>) -> Bool = a.shown() && !a.gone()
|
|
411
|
-
|
|
412
|
-
fun collectChain<M>(t: RoseTree<Actor<M>>, parent: Affine, alpha: Float, out: Slice<Drawn<M>>) =
|
|
413
|
-
if RoseNode(a, k, n) := t
|
|
414
|
-
if isShown(a)
|
|
415
|
-
m := parent.mul(a.place().local())
|
|
416
|
-
al := alpha * a.opacity()
|
|
417
|
-
out.push(Drawn(actor: a, m: m, alpha: al))
|
|
418
|
-
collectChain(k, m, al, out)
|
|
419
|
-
collectChain(n, parent, alpha, out)
|
|
420
|
-
|
|
421
|
-
fun drawChain<M>(t: RoseTree<Actor<M>>, io: Io, parent: Affine, alpha: Float) =
|
|
422
|
-
if RoseNode(a, k, n) := t
|
|
423
|
-
if isShown(a)
|
|
424
|
-
m := parent.mul(a.place().local())
|
|
425
|
-
al := alpha * a.opacity()
|
|
426
|
-
a.paint(io, m, al)
|
|
427
|
-
drawChain(k, io, m, al)
|
|
428
|
-
drawChain(n, io, parent, alpha)
|
|
429
|
-
|
|
430
|
-
# `p` (a point in the parent's coordinates of an actor at `pl`) in the actor's own
|
|
431
|
-
# coordinates: `pl.local().inverse().apply(p)`, or for an unscaled, unturned place about
|
|
432
|
-
# (0, 0) (most of them) the subtraction that gives.
|
|
433
|
-
fun toLocal(pl: Place, p: Vec2) -> Vec2 =
|
|
434
|
-
if pl.rotation == 0.0 && pl.scaleX == 1.0 && pl.scaleY == 1.0 && pl.originX == 0.0 && pl.originY == 0.0
|
|
435
|
-
Vec2(x: p.x - pl.x, y: p.y - pl.y)
|
|
436
|
-
else
|
|
437
|
-
pl.local().inverse().apply(p)
|
|
438
|
-
|
|
439
|
-
# Where the actor `hitChain` finds under `p` is in the chain `t` (whose first node is the
|
|
440
|
-
# `i`-th of its siblings): its index among its siblings at each depth, from the chain down.
|
|
441
|
-
# Only a `Clickable` actor can be hit: any other is skipped with no transform computed,
|
|
442
|
-
# unless it has children, whose coordinates its place gives.
|
|
443
|
-
fun hitPath<M>(t: RoseTree<Actor<M>>, p: Vec2, i: Int) -> Option<List<Int>> =
|
|
444
|
-
hitPathFrom(t, p, i, None)
|
|
445
|
-
|
|
446
|
-
# `hitPath`'s walk along the chain, one tail call per sibling (recursion only into
|
|
447
|
-
# children), so a chain of any length runs in constant stack. A later sibling is on top of
|
|
448
|
-
# an earlier one, so the last one hit wins: `best` is the path found so far.
|
|
449
|
-
fun hitPathFrom<M>(t: RoseTree<Actor<M>>, p: Vec2, i: Int, best: Option<List<Int>>) -> Option<List<Int>> = match t
|
|
450
|
-
RoseEmpty => best
|
|
451
|
-
RoseNode(a, k, n) =>
|
|
452
|
-
found := hitPathAt(a, k, p, i)
|
|
453
|
-
hitPathFrom(n, p, i + 1, if found.isSome() then found else best)
|
|
454
|
-
|
|
455
|
-
# The path to the topmost hit in the node of `a` (the `i`-th of its siblings, with the
|
|
456
|
-
# children `k`): in its children first, then itself.
|
|
457
|
-
fun hitPathAt<M>(a: Actor<M>, k: RoseTree<Actor<M>>, p: Vec2, i: Int) -> Option<List<Int>> =
|
|
458
|
-
# One tag test per node; a flag computed at spawn would replace it once comptime lands.
|
|
459
|
-
match a
|
|
460
|
-
Clickable as c =>
|
|
461
|
-
if !isShown(a)
|
|
462
|
-
None
|
|
463
|
-
else
|
|
464
|
-
q := toLocal(a.place(), p)
|
|
465
|
-
below := if k.isEmpty() then None else hitPath(k, q, 0)
|
|
466
|
-
match below
|
|
467
|
-
Some(path) => Some(Cons(head: i, tail: path))
|
|
468
|
-
None =>
|
|
469
|
-
if c.hit(q) then Some(Cons(head: i, tail: Nil)) else None
|
|
470
|
-
_ =>
|
|
471
|
-
if k.isEmpty() || !isShown(a)
|
|
472
|
-
None
|
|
473
|
-
else
|
|
474
|
-
match hitPath(k, toLocal(a.place(), p), 0)
|
|
475
|
-
Some(path) => Some(Cons(head: i, tail: path))
|
|
476
|
-
None => None
|
|
477
|
-
|
|
478
|
-
# The chain `t` after the pointer event `e` at `p` (in the chain's parent's coordinates)
|
|
479
|
-
# went to the actor at `i`, then `path` below it (as `hitPath` found it): that actor's
|
|
480
|
-
# `input`, then its parents' on the way back up, each under its parent's context (`ctx`
|
|
481
|
-
# for this chain). A node whose actor and children come back as they were is kept, and so
|
|
482
|
-
# is every node off the path. The walk to the `i`-th node and the relinking of the nodes
|
|
483
|
-
# before it are loops: constant stack along a chain.
|
|
484
|
-
fun routeChain<M>(t: RoseTree<Actor<M>>, ctx: Ctx<M>, p: Vec2, e: InputEvent, i: Int, path: List<Int>) -> RoseTree<Actor<M>> = match chainFromNth(t, i)
|
|
485
|
-
RoseEmpty => t
|
|
486
|
-
RoseNode(a, k, n) =>
|
|
487
|
-
pl := a.place()
|
|
488
|
-
q := toLocal(pl, p)
|
|
489
|
-
k2 := match path
|
|
490
|
-
Cons(j, rest) => routeChain(k, ctx.under(pl.local(), a.opacity()), q, e, j, rest)
|
|
491
|
-
Nil => k
|
|
492
|
-
na := a.input(ctx, InputEvent.pointerAt(e, q))
|
|
493
|
-
if @sameRef(na, a) && @sameRef(k2, k) then t else relinked(t, i, RoseNode(value: na, firstChild: k2, nextSibling: n))
|
|
494
|
-
|
|
495
|
-
# The chain `t` from its `i`-th node on (empty if it is shorter).
|
|
496
|
-
fun chainFromNth<T>(t: RoseTree<T>, i: Int) -> RoseTree<T> = match t
|
|
497
|
-
RoseEmpty => t
|
|
498
|
-
RoseNode(_, _, n) => if i <= 0 then t else chainFromNth(n, i - 1)
|
|
499
|
-
|
|
500
|
-
# The chain `t` with its first `i` nodes copied in front of `node` (which stands for the
|
|
501
|
-
# `i`-th and brings the later ones).
|
|
502
|
-
fun relinked<T>(t: RoseTree<T>, i: Int, node: RoseTree<T>) -> RoseTree<T> = match t
|
|
503
|
-
RoseEmpty => node
|
|
504
|
-
RoseNode(a, k, n) => if i <= 0 then node else RoseNode(value: a, firstChild: k, nextSibling: relinked(n, i - 1, node))
|
|
505
|
-
|
|
506
|
-
# The topmost shown `Clickable` actor under `p` (a point in the chain's parent's
|
|
507
|
-
# coordinates) that says it is hit: later siblings before earlier ones, and in each, its
|
|
508
|
-
# children before itself. Other actors are skipped as `hitPath` skips them.
|
|
509
|
-
fun hitChain<M>(t: RoseTree<Actor<M>>, p: Vec2) -> Option<Actor<M>> =
|
|
510
|
-
hitFrom(t, p, None)
|
|
511
|
-
|
|
512
|
-
# `hitChain`'s walk along the chain, as `hitPathFrom`: the last sibling hit wins.
|
|
513
|
-
fun hitFrom<M>(t: RoseTree<Actor<M>>, p: Vec2, best: Option<Actor<M>>) -> Option<Actor<M>> = match t
|
|
514
|
-
RoseEmpty => best
|
|
515
|
-
RoseNode(a, k, n) =>
|
|
516
|
-
found := hitAt(a, k, p)
|
|
517
|
-
hitFrom(n, p, if found.isSome() then found else best)
|
|
518
|
-
|
|
519
|
-
# The topmost hit in the node of `a` (with the children `k`): in its children first, then
|
|
520
|
-
# itself, as `hitPathAt`.
|
|
521
|
-
fun hitAt<M>(a: Actor<M>, k: RoseTree<Actor<M>>, p: Vec2) -> Option<Actor<M>> =
|
|
522
|
-
match a
|
|
523
|
-
Clickable as c =>
|
|
524
|
-
if isShown(a)
|
|
525
|
-
q := toLocal(a.place(), p)
|
|
526
|
-
match hitChain(k, q)
|
|
527
|
-
Some(found) => Some(found)
|
|
528
|
-
None => if c.hit(q) then Some(a) else None
|
|
529
|
-
else
|
|
530
|
-
None
|
|
531
|
-
_ => if k.isEmpty() || !isShown(a) then None else hitChain(k, toLocal(a.place(), p))
|
|
532
|
-
|
|
533
|
-
# --- tests ---
|
|
534
|
-
|
|
535
|
-
# The kinds for the tests, in a tree of `Actor<Int>` (the messages are Ints): a plain body,
|
|
536
|
-
# and four with behaviour.
|
|
537
|
-
|
|
538
|
-
# A `w` by `w` box (a group when `w` is 0) with its own alpha and flags.
|
|
539
|
-
struct TBody[Actor<Int>, Clickable](id: Int, at: Place, w: Float, alpha: Float, visible: Bool, dead: Bool) =
|
|
540
|
-
fun key(self) -> Int = self.id
|
|
541
|
-
fun place(self) -> Place = self.at
|
|
542
|
-
fun opacity(self) -> Float = self.alpha
|
|
543
|
-
fun shown(self) -> Bool = self.visible
|
|
544
|
-
fun gone(self) -> Bool = self.dead
|
|
545
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) = actor.boxPaint(io, m, alpha, self.w, self.w, Color.Red)
|
|
546
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.w, p)
|
|
547
|
-
|
|
548
|
-
# Moves by vx per second; dies when `ttl` runs out (never if it starts at -1).
|
|
549
|
-
struct TDrifter[Actor<Int>, Clickable](id: Int, at: Place, vx: Float, ttl: Int, visible: Bool, dead: Bool) =
|
|
550
|
-
fun key(self) -> Int = self.id
|
|
551
|
-
fun place(self) -> Place = self.at
|
|
552
|
-
fun shown(self) -> Bool = self.visible
|
|
553
|
-
fun gone(self) -> Bool = self.dead
|
|
554
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
|
|
555
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> TDrifter =
|
|
556
|
-
if self.ttl == 0
|
|
557
|
-
TDrifter(..self, dead: true)
|
|
558
|
-
else
|
|
559
|
-
TDrifter(..self, at: self.at.moveBy(self.vx * dt, 0.0), ttl: if self.ttl > 0 then self.ttl - 1 else self.ttl)
|
|
560
|
-
|
|
561
|
-
# Spawns a drifter under the root (id 0) each step, with ids from `next` on, and sends
|
|
562
|
-
# the id it spawned.
|
|
563
|
-
struct TSpawner[Actor<Int>](id: Int, next: Int) =
|
|
564
|
-
fun key(self) -> Int = self.id
|
|
565
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
566
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> TSpawner =
|
|
567
|
-
ctx.out.push(Spawn(parent: 0, node: tdrifter(self.next, 0.0, 0.0, -1)))
|
|
568
|
-
ctx.send(self.next)
|
|
569
|
-
TSpawner(..self, next: self.next + 1)
|
|
570
|
-
|
|
571
|
-
# Keeps the world transform and alpha its context gave it in its last step.
|
|
572
|
-
struct TProbe[Actor<Int>](id: Int, at: Place, seen: Affine, seenA: Float) =
|
|
573
|
-
fun key(self) -> Int = self.id
|
|
574
|
-
fun place(self) -> Place = self.at
|
|
575
|
-
fun opacity(self) -> Float = 0.5
|
|
576
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> TProbe =
|
|
577
|
-
TProbe(..self, seen: ctx.worldOf(self.at.local()), seenA: ctx.alphaOf(self.opacity()))
|
|
578
|
-
|
|
579
|
-
# A 10 by 10 box at (x, 0) that counts the pointer events it gets.
|
|
580
|
-
struct TClicker[Actor<Int>, Clickable](id: Int, x: Float, clicks: Int) =
|
|
581
|
-
fun key(self) -> Int = self.id
|
|
582
|
-
fun place(self) -> Place = place.at(self.x, 0.0)
|
|
583
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(10.0, 10.0, p)
|
|
584
|
-
fun input(self, ctx: Ctx<Int>, e: InputEvent) -> TClicker = TClicker(..self, clicks: self.clicks + 1)
|
|
585
|
-
|
|
586
|
-
fun tclicker(id: Int, x: Float) -> RoseTree<Actor<Int>> = RoseTree.leaf(TClicker(id: id, x: x, clicks: 0))
|
|
587
|
-
|
|
588
|
-
# Not `Clickable`, though it has a `hit` that says yes everywhere: a plain method the tree
|
|
589
|
-
# never calls. It counts the pointer events it gets (as a parent on a hit actor's path).
|
|
590
|
-
struct TPlain[Actor<Int>](id: Int, at: Place, inputs: Int) =
|
|
591
|
-
fun key(self) -> Int = self.id
|
|
592
|
-
fun place(self) -> Place = self.at
|
|
593
|
-
fun hit(self, p: Vec2) -> Bool = true
|
|
594
|
-
fun input(self, ctx: Ctx<Int>, e: InputEvent) -> TPlain = TPlain(..self, inputs: self.inputs + 1)
|
|
595
|
-
|
|
596
|
-
fun tplain(id: Int, at: Place, kids: List<RoseTree<Actor<Int>>>) -> RoseTree<Actor<Int>> = RoseTree.of(TPlain(id: id, at: at, inputs: 0), kids)
|
|
597
|
-
|
|
598
|
-
# Pushes `Kill(target)` in each step.
|
|
599
|
-
struct TKiller[Actor<Int>](id: Int, target: Int) =
|
|
600
|
-
fun key(self) -> Int = self.id
|
|
601
|
-
fun place(self) -> Place = place.at(0.0, 0.0)
|
|
602
|
-
fun step(self, ctx: Ctx<Int>, dt: Float) -> TKiller =
|
|
603
|
-
ctx.out.push(Kill(id: self.target))
|
|
604
|
-
self
|
|
605
|
-
|
|
606
|
-
fun tbody(id: Int, x: Float, y: Float, w: Float) -> TBody =
|
|
607
|
-
TBody(id: id, at: place.at(x, y), w: w, alpha: 1.0, visible: true, dead: false)
|
|
608
|
-
|
|
609
|
-
fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> RoseTree<Actor<Int>> =
|
|
610
|
-
RoseTree.leaf(TDrifter(id: id, at: place.at(x, 0.0), vx: vx, ttl: ttl, visible: true, dead: false))
|
|
611
|
-
|
|
612
|
-
fun tspawner(id: Int, next: Int) -> RoseTree<Actor<Int>> = RoseTree.leaf(TSpawner(id: id, next: next))
|
|
613
|
-
|
|
614
|
-
fun tkiller(id: Int, target: Int) -> RoseTree<Actor<Int>> = RoseTree.leaf(TKiller(id: id, target: target))
|
|
615
|
-
|
|
616
|
-
fun tprobe(id: Int, x: Float, y: Float, r: Float) -> TProbe =
|
|
617
|
-
at := Place(x: x, y: y, scaleX: 0.5, scaleY: 3.0, rotation: r, originX: 2.0, originY: 1.0)
|
|
618
|
-
TProbe(id: id, at: at, seen: Affine.Identity, seenA: 0.0)
|
|
619
|
-
|
|
620
|
-
fun trect(id: Int, x: Float, y: Float, w: Float) -> RoseTree<Actor<Int>> = RoseTree.leaf(tbody(id, x, y, w))
|
|
621
|
-
|
|
622
|
-
fun tturned(id: Int, x: Float, y: Float, s: Float, r: Float) -> TBody =
|
|
623
|
-
TBody(id: id, at: place.turned(x, y, s, r), w: 0.0, alpha: 1.0, visible: true, dead: false)
|
|
624
|
-
|
|
625
|
-
fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List<RoseTree<Actor<Int>>>) -> RoseTree<Actor<Int>> =
|
|
626
|
-
RoseTree.of(tturned(id, x, y, s, r), kids)
|
|
627
|
-
|
|
628
|
-
fun ttree() -> SceneTree<Int> = SceneTree.of(tbody(0, 0.0, 0.0, 0.0))
|
|
629
|
-
|
|
630
|
-
fun tids(s: SceneTree<Int>) -> Str = s.root.fold("", |acc, a| if acc == "" then "{a.key()}" else "{acc},{a.key()}")
|
|
631
|
-
|
|
632
|
-
fun tx(s: SceneTree<Int>, id: Int) -> Float = s.find(id).unwrap().place().x
|
|
633
|
-
|
|
634
|
-
fun tnear(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.0001
|
|
635
|
-
|
|
636
|
-
fun tsameM(a: Affine, b: Affine) -> Bool =
|
|
637
|
-
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)
|
|
638
|
-
|
|
639
|
-
fun tseen(s: SceneTree<Int>, id: Int) -> Affine = s.findAs<TProbe>(id).unwrap().seen
|
|
640
|
-
|
|
641
|
-
fun tseenA(s: SceneTree<Int>, id: Int) -> Float = s.findAs<TProbe>(id).unwrap().seenA
|
|
642
|
-
|
|
643
|
-
fun tfade(s: SceneTree<Int>, id: Int, a: Float) -> SceneTree<Int> = s.updateAs<TBody>(id, |b| TBody(..b, alpha: a))
|
|
644
|
-
|
|
645
|
-
fun thide(s: SceneTree<Int>, id: Int) -> SceneTree<Int> = s.updateAs<TBody>(id, |b| TBody(..b, visible: false))
|
|
646
|
-
|
|
647
|
-
# Steps a tree that nothing else holds, so an in-place update could take the old cells.
|
|
648
|
-
fun tstepFresh(vx: Float) -> SceneTree<Int> = ttree().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tdrifter(2, 0.0, vx, -1)).step(Ctx<Int>(), 0.5)
|
|
649
|
-
|
|
650
|
-
test "step returns a new tree and leaves a kept one as it was"
|
|
651
|
-
s0 := ttree().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
|
|
652
|
-
ctx := Ctx<Int>()
|
|
653
|
-
s1 := s0.step(ctx, 0.5)
|
|
654
|
-
s2 := s1.step(ctx, 0.5)
|
|
655
|
-
assert tx(s0, 1) == 0.0
|
|
656
|
-
assert tx(s1, 1) == 5.0
|
|
657
|
-
assert tx(s2, 1) == 10.0
|
|
658
|
-
assert tx(s2, 2) == -5.0
|
|
659
|
-
assert tids(s0) == "0,1,2"
|
|
660
|
-
assert tids(s2) == "0,1,2"
|
|
661
|
-
|
|
662
|
-
test "a step that changes nothing keeps every actor"
|
|
663
|
-
s0 := ttree().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)]))
|
|
664
|
-
s1 := s0.step(Ctx<Int>(), 1.0)
|
|
665
|
-
assert tids(s1) == "0,1,2,3"
|
|
666
|
-
assert s1.find(3).unwrap() == s0.find(3).unwrap()
|
|
667
|
-
|
|
668
|
-
test "input or apply that changes nothing returns the very same tree"
|
|
669
|
-
s0 := ttree().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)]))
|
|
670
|
-
assert @sameRef(s0.apply(Slice<Cmd<Int>>()), s0)
|
|
671
|
-
assert @sameRef(s0.input(Ctx<Int>(), PointerDown(x: 1000.0, y: 1000.0)), s0)
|
|
672
|
-
# A hit on a rect whose `input` is the default: the same tree.
|
|
673
|
-
assert @sameRef(s0.input(Ctx<Int>(), PointerDown(x: 1.0, y: 1.0)), s0)
|
|
674
|
-
|
|
675
|
-
test "input keeps the nodes off the hit actor's path"
|
|
676
|
-
s0 := ttree().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 5.0)])).add(0, tclicker(3, 100.0)).add(0, trect(4, 500.0, 0.0, 5.0))
|
|
677
|
-
s1 := s0.input(Ctx<Int>(), PointerDown(x: 101.0, y: 1.0))
|
|
678
|
-
assert s1.findAs<TClicker>(3).unwrap().clicks == 1
|
|
679
|
-
assert s0.findAs<TClicker>(3).unwrap().clicks == 0
|
|
680
|
-
assert @sameRef(nodeOf(s1.root, 4), nodeOf(s0.root, 4))
|
|
681
|
-
assert @sameRef(s1.find(1).unwrap(), s0.find(1).unwrap())
|
|
682
|
-
assert @sameRef(s1.find(2).unwrap(), s0.find(2).unwrap())
|
|
683
|
-
|
|
684
|
-
test "an actor whose step changes it is seen as changed, also where nothing else holds the tree"
|
|
685
|
-
# Under the default, `--no-fbip` and `--no-fusion` alike (the sweep runs all three): were
|
|
686
|
-
# the drifter written in place, `@sameRef` would keep the old node and the old place.
|
|
687
|
-
assert tx(tstepFresh(10.0), 2) == 5.0
|
|
688
|
-
assert tx(tstepFresh(-4.0), 2) == -2.0
|
|
689
|
-
assert tx(tstepFresh(10.0).step(Ctx<Int>(), 0.5), 2) == 10.0
|
|
690
|
-
clicked := ttree().add(0, tclicker(1, 0.0)).input(Ctx<Int>(), PointerDown(x: 1.0, y: 1.0))
|
|
691
|
-
assert clicked.findAs<TClicker>(1).unwrap().clicks == 1
|
|
692
|
-
assert clicked.input(Ctx<Int>(), PointerDown(x: 1.0, y: 1.0)).findAs<TClicker>(1).unwrap().clicks == 2
|
|
693
|
-
|
|
694
|
-
test "an actor whose step returns it gone is dropped with its subtree in the same step"
|
|
695
|
-
s := ttree().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))
|
|
696
|
-
assert tids(s) == "0,1,3,2"
|
|
697
|
-
ctx := Ctx<Int>()
|
|
698
|
-
s1 := s.step(ctx, 1.0)
|
|
699
|
-
assert tids(s1) == "0,1,3,2"
|
|
700
|
-
s2 := s1.step(ctx, 1.0)
|
|
701
|
-
assert tids(s2) == "0,2"
|
|
702
|
-
assert s2.find(3).isNone()
|
|
703
|
-
|
|
704
|
-
test "a gone or hidden actor: gone ones go with their subtree, hidden ones still step"
|
|
705
|
-
s := ttree().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))
|
|
706
|
-
hidden := s.updateAs<TDrifter>(1, |d| TDrifter(..d, visible: false))
|
|
707
|
-
h1 := hidden.step(Ctx<Int>(), 1.0)
|
|
708
|
-
assert tx(h1, 1) == 1.0
|
|
709
|
-
assert h1.flatten().length() == 2
|
|
710
|
-
assert h1.hit(1.0, 1.0).unwrap().key() == 3
|
|
711
|
-
gone := s.updateAs<TDrifter>(1, |d| TDrifter(..d, dead: true))
|
|
712
|
-
# not drawn or hit before the step drops it
|
|
713
|
-
assert gone.flatten().length() == 2
|
|
714
|
-
assert tids(gone.step(Ctx<Int>(), 1.0)) == "0,3"
|
|
715
|
-
|
|
716
|
-
test "spawns pushed to ctx.out are added after the step, on top, and sends stay for the game"
|
|
717
|
-
s := ttree().add(0, tspawner(1, 10))
|
|
718
|
-
ctx := Ctx<Int>()
|
|
719
|
-
ctx.send(99)
|
|
720
|
-
s1 := s.step(ctx, 1.0)
|
|
721
|
-
assert tids(s1) == "0,1,10"
|
|
722
|
-
assert ctx.out.length() == 2
|
|
723
|
-
s2 := s1.step(ctx, 1.0)
|
|
724
|
-
assert tids(s2) == "0,1,10,11"
|
|
725
|
-
sent := ctx.takeSends()
|
|
726
|
-
assert sent.length() == 3
|
|
727
|
-
assert sent.get(0).unwrap() == 99 && sent.get(1).unwrap() == 10 && sent.get(2).unwrap() == 11
|
|
728
|
-
assert ctx.out.length() == 0
|
|
729
|
-
|
|
730
|
-
test "apply kills and spawns in one pass, in order, and skips sends"
|
|
731
|
-
s := ttree().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))
|
|
732
|
-
cmds := Slice<Cmd<Int>>()
|
|
733
|
-
cmds.push(Kill(id: 2))
|
|
734
|
-
cmds.push(Spawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
|
|
735
|
-
cmds.push(Send(msg: 7))
|
|
736
|
-
cmds.push(Spawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
|
|
737
|
-
cmds.push(Spawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
|
|
738
|
-
cmds.push(Spawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
|
|
739
|
-
s2 := s.apply(cmds)
|
|
740
|
-
assert tids(s2) == "0,1,3,5,7,4,6"
|
|
741
|
-
assert tids(s) == "0,1,2,3,4"
|
|
742
|
-
assert s.kill(1).count() == 2
|
|
743
|
-
sends := Slice<Cmd<Int>>()
|
|
744
|
-
sends.push(Send(msg: 1))
|
|
745
|
-
assert tids(s.apply(sends)) == "0,1,2,3,4"
|
|
746
|
-
|
|
747
|
-
test "update by id changes one actor and shares its untouched siblings"
|
|
748
|
-
s := ttree().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)]))
|
|
749
|
-
s1 := s.add(0, tgroup(4, 0.0, 0.0, 1.0, 0.0, [trect(5, 0.0, 0.0, 1.0)]))
|
|
750
|
-
u := s1.updateAs<TBody>(2, |b| TBody(..b, at: b.at.moveTo(9.0, 9.0), w: 3.0))
|
|
751
|
-
assert tx(u, 2) == 9.0
|
|
752
|
-
assert tx(s1, 2) == 0.0
|
|
753
|
-
# 2's later sibling (3) and 1's later sibling (the group 4) are the same nodes
|
|
754
|
-
assert u.root.kids().kids().rest() == s1.root.kids().kids().rest()
|
|
755
|
-
assert u.root.kids().rest() == s1.root.kids().rest()
|
|
756
|
-
k := s1.update(5, |a| TDrifter(id: a.key(), at: a.place(), vx: 2.0, ttl: -1, visible: true, dead: false)).step(Ctx<Int>(), 1.0)
|
|
757
|
-
assert tx(k, 5) == 2.0
|
|
758
|
-
|
|
759
|
-
test "updateAs and findAs act only on an actor of that type"
|
|
760
|
-
s := ttree().add(0, tdrifter(1, 0.0, 1.0, -1)).add(0, trect(2, 3.0, 0.0, 1.0))
|
|
761
|
-
assert s.findAs<TDrifter>(1).unwrap().vx == 1.0
|
|
762
|
-
assert s.findAs<TBody>(1).isNone()
|
|
763
|
-
assert s.findAs<TBody>(2).unwrap().w == 1.0
|
|
764
|
-
assert s.findAs<TBody>(42).isNone()
|
|
765
|
-
same := s.updateAs<TBody>(1, |b| TBody(..b, w: 50.0))
|
|
766
|
-
assert same.find(1).unwrap() == s.find(1).unwrap()
|
|
767
|
-
assert same.find(2).unwrap() == s.find(2).unwrap()
|
|
768
|
-
t := s.updateAs<TDrifter>(1, |d| TDrifter(..d, vx: 5.0)).step(Ctx<Int>(), 1.0)
|
|
769
|
-
assert tx(t, 1) == 5.0
|
|
770
|
-
assert tx(t, 2) == 3.0
|
|
771
|
-
# std's own kinds
|
|
772
|
-
g: SceneTree<Int> := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)).add(0, RoseTree.leaf(Box(id: 1, x: 1.0, y: 0.0, w: 2.0, h: 2.0, color: Color.Red)))
|
|
773
|
-
moved := g.updateAs<Box<Int>>(1, |b| Box(..b, x: b.x + 1.0))
|
|
774
|
-
assert moved.findAs<Box<Int>>(1).unwrap().x == 2.0
|
|
775
|
-
assert moved.findAs<Group<Int>>(0).unwrap().id == 0
|
|
776
|
-
|
|
777
|
-
test "flatten gives each shown actor its tree transform, parents first"
|
|
778
|
-
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)])
|
|
779
|
-
s := ttree().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
|
|
780
|
-
d := s.flatten()
|
|
781
|
-
assert d.length() == 5
|
|
782
|
-
ids := Slice<Int>()
|
|
783
|
-
for e := range d
|
|
784
|
-
ids.push(e.actor.key())
|
|
785
|
-
assert ids.toStr() == "[0,1,2,3,4]"
|
|
786
|
-
# (0, 0) of rect 2 is (10, 0) in the group, turned a quarter and doubled: (100, 20)
|
|
787
|
-
p := d.at(2).m.apply(Vec2(x: 0.0, y: 0.0))
|
|
788
|
-
assert tnear(p.x, 100.0) && tnear(p.y, 20.0)
|
|
789
|
-
assert tnear(d.at(4).m.e, 5.0)
|
|
790
|
-
assert thide(s, 1).flatten().length() == 2
|
|
791
|
-
# alphas multiply down the tree
|
|
792
|
-
faded := tfade(tfade(s, 1, 0.5), 2, 0.5).flatten()
|
|
793
|
-
assert faded.at(2).alpha == 0.25 && faded.at(3).alpha == 0.5 && faded.at(4).alpha == 1.0
|
|
794
|
-
|
|
795
|
-
test "hit finds the topmost actor: later siblings and children first"
|
|
796
|
-
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)])
|
|
797
|
-
s := ttree().add(0, g)
|
|
798
|
-
assert s.hit(90.0, 30.0).unwrap().key() == 3
|
|
799
|
-
assert s.hit(70.0, 10.0).unwrap().key() == 2
|
|
800
|
-
assert s.hit(10.0, 10.0).isNone()
|
|
801
|
-
t := ttree().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))
|
|
802
|
-
assert t.hit(10.0, 10.0).unwrap().key() == 5
|
|
803
|
-
assert t.hit(30.0, 5.0).unwrap().key() == 7
|
|
804
|
-
assert t.hitId(40.0, 10.0).unwrap() == 6
|
|
805
|
-
assert thide(t, 6).hitId(40.0, 10.0).unwrap() == 5
|
|
806
|
-
|
|
807
|
-
test "an actor's world transform is computed when it asks, and matches the eager product"
|
|
808
|
-
gb := tturned(1, 100.0, 30.0, 2.0, 0.7)
|
|
809
|
-
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))
|
|
810
|
-
p := tprobe(3, 7.0, -2.0, 2.5)
|
|
811
|
-
q := tprobe(4, 1.0, 1.0, 0.0)
|
|
812
|
-
s := ttree().add(0, RoseTree.of(gb, [RoseTree.of(hb, [RoseTree.leaf(p), RoseTree.leaf(q)])]))
|
|
813
|
-
s1 := s.step(Ctx<Int>(), 1.0)
|
|
814
|
-
assert tsameM(tseen(s1, 3), gb.at.local().mul(hb.at.local()).mul(p.at.local()))
|
|
815
|
-
assert tnear(tseenA(s1, 3), 0.5)
|
|
816
|
-
# the sibling got its own transform from the same context
|
|
817
|
-
assert tsameM(tseen(s1, 4), gb.at.local().mul(hb.at.local()).mul(q.at.local()))
|
|
818
|
-
|
|
819
|
-
test "siblings with children each give their children their own world transform"
|
|
820
|
-
g1 := tturned(1, 100.0, 30.0, 2.0, 0.7)
|
|
821
|
-
g2 := tturned(2, -40.0, 5.0, 0.5, -1.2)
|
|
822
|
-
p1 := tprobe(3, 7.0, -2.0, 2.5)
|
|
823
|
-
p2 := tprobe(4, 1.0, 9.0, 0.3)
|
|
824
|
-
s := ttree().add(0, RoseTree.of(g1, [RoseTree.leaf(p1)])).add(0, RoseTree.of(g2, [RoseTree.leaf(p2)]))
|
|
825
|
-
s1 := s.step(Ctx<Int>(), 1.0)
|
|
826
|
-
assert tsameM(tseen(s1, 3), g1.at.local().mul(p1.at.local()))
|
|
827
|
-
assert tsameM(tseen(s1, 4), g2.at.local().mul(p2.at.local()))
|
|
828
|
-
|
|
829
|
-
test "a kill pushed before the step drops the actor in the step's own walk, unstepped"
|
|
830
|
-
s := ttree().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)]))
|
|
831
|
-
ctx := Ctx<Int>()
|
|
832
|
-
ctx.out.push(Kill(id: 1))
|
|
833
|
-
s2 := s.step(ctx, 1.0)
|
|
834
|
-
# the spawner was not stepped, so it spawned nothing
|
|
835
|
-
assert tids(s2) == "0,2,3"
|
|
836
|
-
assert ctx.out.length() == 0
|
|
837
|
-
# ids outside the bitsets' range take the set: the same answers
|
|
838
|
-
ctx.out.push(Kill(id: -7))
|
|
839
|
-
ctx.out.push(Kill(id: 3))
|
|
840
|
-
ctx.out.push(Kill(id: 5000000))
|
|
841
|
-
assert tids(s2.step(ctx, 1.0)) == "0,2"
|
|
842
|
-
|
|
843
|
-
test "spawns pushed before the step go on top of their parents, in order, unstepped"
|
|
844
|
-
s := ttree().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)]))
|
|
845
|
-
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)]))
|
|
846
|
-
ctx := Ctx<Int>()
|
|
847
|
-
ctx.out.push(Spawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
|
|
848
|
-
ctx.out.push(Spawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
|
|
849
|
-
ctx.out.push(Spawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
|
|
850
|
-
ctx.out.push(Spawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
|
|
851
|
-
s2 := s1.step(ctx, 1.0)
|
|
852
|
-
assert tids(s2) == "0,1,2,3,5,7,4,6,9,10"
|
|
853
|
-
# the drifter was added after the step: it hasn't moved yet
|
|
854
|
-
assert tx(s2, 5) == 0.0
|
|
855
|
-
assert tx(s2.step(ctx, 1.0), 5) == 10.0
|
|
856
|
-
# many spawns into one parent keep their order
|
|
857
|
-
for i := range 50
|
|
858
|
-
ctx.out.push(Spawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
|
|
859
|
-
s3 := s2.step(ctx, 1.0)
|
|
860
|
-
ids := s3.root.kids().rest().kids().fold(Slice<Int>(), |acc, a|
|
|
861
|
-
acc.push(a.key())
|
|
862
|
-
acc
|
|
863
|
-
)
|
|
864
|
-
assert ids.length() == 51 && ids.at(0) == 6 && ids.at(1) == 100 && ids.at(50) == 149
|
|
865
|
-
|
|
866
|
-
test "a kill and a spawn of the same id before the step: the old actor goes, the new one stays"
|
|
867
|
-
s := ttree().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)]))
|
|
868
|
-
ctx := Ctx<Int>()
|
|
869
|
-
ctx.out.push(Kill(id: 2))
|
|
870
|
-
ctx.out.push(Spawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
|
|
871
|
-
s2 := s.step(ctx, 1.0)
|
|
872
|
-
assert tids(s2) == "0,1,3,2"
|
|
873
|
-
assert tx(s2, 2) == 7.0
|
|
874
|
-
# the old tree is as it was
|
|
875
|
-
assert tids(s) == "0,1,2,3"
|
|
876
|
-
assert tx(s, 2) == 0.0
|
|
877
|
-
# a reused id is killed again by the next batch
|
|
878
|
-
ctx.out.push(Kill(id: 2))
|
|
879
|
-
assert tids(s2.step(ctx, 1.0)) == "0,1,3"
|
|
880
|
-
|
|
881
|
-
test "commands pushed during the step apply after those pushed before it"
|
|
882
|
-
s := ttree().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
|
|
883
|
-
ctx := Ctx<Int>()
|
|
884
|
-
# spawned by the batch before the step, then killed by an actor during it
|
|
885
|
-
ctx.out.push(Spawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
|
|
886
|
-
s2 := s.step(ctx, 1.0)
|
|
887
|
-
assert tids(s2) == "0,1,2"
|
|
888
|
-
assert ctx.out.length() == 0
|
|
889
|
-
|
|
890
|
-
test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids past it"
|
|
891
|
-
big := 4194303
|
|
892
|
-
s := ttree().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
|
|
893
|
-
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)]))
|
|
894
|
-
ctx := Ctx<Int>()
|
|
895
|
-
# in the bitsets' range: the last bit of the last word, and a word boundary
|
|
896
|
-
ctx.out.push(Kill(id: big - 1))
|
|
897
|
-
ctx.out.push(Kill(id: 64))
|
|
898
|
-
ctx.out.push(Spawn(parent: big, node: trect(0 - 3, 0.0, 0.0, 1.0)))
|
|
899
|
-
s2 := s1.step(ctx, 1.0)
|
|
900
|
-
assert tids(s2) == "0,{big},-3,{big + 1},63"
|
|
901
|
-
# one id past the range: the whole batch uses the set and the map
|
|
902
|
-
ctx.out.push(Spawn(parent: big + 1, node: trect(9, 0.0, 0.0, 1.0)))
|
|
903
|
-
ctx.out.push(Kill(id: 0 - 3))
|
|
904
|
-
ctx.out.push(Kill(id: 63))
|
|
905
|
-
s3 := s2.step(ctx, 1.0)
|
|
906
|
-
assert tids(s3) == "0,{big},{big + 1},9"
|
|
907
|
-
# a kill of an id the tree doesn't have, past the bitsets: nothing changes
|
|
908
|
-
ctx.out.push(Kill(id: big + 100))
|
|
909
|
-
assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
|
|
910
|
-
|
|
911
|
-
test "a plain tree of std's Group and Box: add, step, draw list"
|
|
912
|
-
s: SceneTree<Int> := SceneTree.of(Group(id: 0, x: 0.0, y: 0.0)).add(0, RoseTree.leaf(Box(id: 1, x: 10.0, y: 5.0, w: 40.0, h: 20.0, color: Color.Red)))
|
|
913
|
-
s1 := s.step(Ctx<Int>(), 1.0)
|
|
914
|
-
assert s1.count() == 2
|
|
915
|
-
assert s1.flatten().at(1).m.e == 10.0
|
|
916
|
-
assert s1.hit(20.0, 10.0).unwrap().key() == 1
|
|
917
|
-
|
|
918
|
-
test "only a Clickable actor is hit: a plain one with a hit method never is, its clickable child is"
|
|
919
|
-
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), []))
|
|
920
|
-
assert s.hitId(25.0, 5.0).unwrapOr(-1) == 2
|
|
921
|
-
assert s.hitId(5.0, 5.0).isNone() && s.hitId(205.0, 5.0).isNone()
|
|
922
|
-
assert TPlain(id: 9, at: place.at(0.0, 0.0), inputs: 0).hit(Vec2(x: 0.0, y: 0.0))
|
|
923
|
-
# A press on the plain parent alone goes nowhere; one on the child goes to it, then to
|
|
924
|
-
# the parent on its way up.
|
|
925
|
-
assert @sameRef(s.input(Ctx<Int>(), PointerDown(x: 5.0, y: 5.0)), s)
|
|
926
|
-
assert @sameRef(s.input(Ctx<Int>(), PointerDown(x: 205.0, y: 5.0)), s)
|
|
927
|
-
s1 := s.input(Ctx<Int>(), PointerDown(x: 25.0, y: 5.0))
|
|
928
|
-
assert s1.findAs<TClicker>(2).unwrap().clicks == 1
|
|
929
|
-
assert s1.findAs<TPlain>(1).unwrap().inputs == 1
|
|
930
|
-
assert s1.findAs<TPlain>(3).unwrap().inputs == 0
|
|
931
|
-
|
|
932
|
-
test "a clickable actor under a moved, scaled and turned plain parent is hit where it is drawn"
|
|
933
|
-
# The parent at (100, 0), doubled and turned a quarter: (x, y) in it is (100 - 2y, 2x).
|
|
934
|
-
s := ttree().add(0, tplain(1, place.turned(100.0, 0.0, 2.0, Float.HalfPi), [tclicker(2, 10.0)]))
|
|
935
|
-
# (2, 1) in the clicker is (12, 1) in the parent: (98, 24) in the tree.
|
|
936
|
-
assert s.hitId(98.0, 24.0).unwrapOr(-1) == 2
|
|
937
|
-
# (2, -1) in the clicker, just off it: (102, 24).
|
|
938
|
-
assert s.hitId(102.0, 24.0).isNone()
|
|
939
|
-
# Where an unturned parent would put it: nothing.
|
|
940
|
-
assert s.hitId(112.0, 1.0).isNone()
|
|
941
|
-
d := s.flatten()
|
|
942
|
-
q := d.at(2).m.apply(Vec2(x: 2.0, y: 1.0))
|
|
943
|
-
assert tnear(q.x, 98.0) && tnear(q.y, 24.0)
|
|
944
|
-
s1 := s.input(Ctx<Int>(), PointerDown(x: 98.0, y: 24.0))
|
|
945
|
-
assert s1.findAs<TClicker>(2).unwrap().clicks == 1 && s1.findAs<TPlain>(1).unwrap().inputs == 1
|
|
946
|
-
|
|
947
|
-
test "allAs gives every actor of a type in tree order, kidsAs one layer of it"
|
|
948
|
-
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))
|
|
949
|
-
bodies := s.allAs<TBody>()
|
|
950
|
-
assert bodies.map(|b| b.id).toStr() == "[0,10,11,15,13,14]"
|
|
951
|
-
assert s.allAs<TClicker>().map(|c| c.id).toStr() == "[12]"
|
|
952
|
-
assert s.allAs<TKiller>().isEmpty()
|
|
953
|
-
assert s.kidsAs<TBody>(10).map(|b| b.id).toStr() == "[11,13]"
|
|
954
|
-
assert s.kidsAs<TClicker>(10).map(|c| c.id).toStr() == "[12]"
|
|
955
|
-
assert s.kidsAs<TBody>(0).map(|b| b.id).toStr() == "[10,14]"
|
|
956
|
-
assert s.kidsAs<TBody>(99).isEmpty() && s.kidsAs<TBody>(15).isEmpty()
|
|
957
|
-
|
|
958
|
-
test "a kill among 200000 siblings runs in constant stack and keeps the others"
|
|
959
|
-
kids := 0.until(200000).fold(Slice<RoseTree<Actor<Int>>>(), |acc, i|
|
|
960
|
-
acc.push(trect(i + 1, 0.0, 0.0, 1.0))
|
|
961
|
-
acc
|
|
962
|
-
)
|
|
963
|
-
wide := SceneTree.of(tbody(0, 0.0, 0.0, 0.0)).withRoot(RoseTree.of(tbody(0, 0.0, 0.0, 0.0), List.fromSlice(kids)))
|
|
964
|
-
assert wide.count() == 200001
|
|
965
|
-
k := wide.kill(100000)
|
|
966
|
-
assert k.count() == 200000 && k.find(100000).isNone() && k.find(100001).isSome()
|
|
967
|
-
assert wide.kill(-7).count() == 200001
|
|
968
|
-
assert wide.kidsAs<TBody>(0).length() == 200000
|
|
969
|
-
|
|
970
|
-
test "hit, input, step, apply and the draw list among 200000 siblings run in constant stack"
|
|
971
|
-
kids := 0.until(200000).fold(Slice<RoseTree<Actor<Int>>>(), |acc, i|
|
|
972
|
-
acc.push(RoseTree.leaf(TClicker(id: i + 1, x: Float(i) * 20.0, clicks: 0)))
|
|
973
|
-
acc
|
|
974
|
-
)
|
|
975
|
-
wide := SceneTree.of(tbody(0, 0.0, 0.0, 0.0)).withRoot(RoseTree.of(tbody(0, 0.0, 0.0, 0.0), List.fromSlice(kids)))
|
|
976
|
-
# the first, one in the middle and the last (the deepest walk)
|
|
977
|
-
assert wide.hitId(5.0, 5.0).unwrapOr(-1) == 1
|
|
978
|
-
assert wide.hitId(2000005.0, 5.0).unwrapOr(-1) == 100001
|
|
979
|
-
assert wide.hitId(3999985.0, 5.0).unwrapOr(-1) == 200000
|
|
980
|
-
assert wide.hitId(15.0, 5.0).isNone()
|
|
981
|
-
t := wide.input(Ctx<Int>(), PointerDown(x: 3999985.0, y: 5.0))
|
|
982
|
-
assert t.count() == 200001
|
|
983
|
-
assert t.findAs<TClicker>(200000).unwrap().clicks == 1 && t.findAs<TClicker>(199999).unwrap().clicks == 0
|
|
984
|
-
assert wide.findAs<TClicker>(200000).unwrap().clicks == 0
|
|
985
|
-
ctx := Ctx<Int>()
|
|
986
|
-
assert wide.step(ctx, 1.0).count() == 200001
|
|
987
|
-
ctx.out.push(Kill(id: 100000))
|
|
988
|
-
ctx.out.push(Spawn(parent: 0, node: tclicker(300000, 0.0)))
|
|
989
|
-
s := wide.step(ctx, 1.0)
|
|
990
|
-
assert s.count() == 200001 && s.find(100000).isNone() && s.find(300000).isSome()
|
|
991
|
-
assert wide.flatten().length() == 200001
|
|
992
|
-
|
|
993
|
-
test "later siblings are on top: the last of the overlapping ones is hit, and gets the event"
|
|
994
|
-
s := ttree().add(0, tclicker(1, 0.0)).add(0, tclicker(2, 5.0)).add(0, tclicker(3, 8.0)).add(0, tclicker(4, 100.0))
|
|
995
|
-
assert s.hitId(9.0, 5.0).unwrapOr(-1) == 3
|
|
996
|
-
assert s.hitId(6.0, 5.0).unwrapOr(-1) == 2
|
|
997
|
-
assert s.hitId(1.0, 5.0).unwrapOr(-1) == 1
|
|
998
|
-
s1 := s.input(Ctx<Int>(), PointerDown(x: 9.0, y: 5.0))
|
|
999
|
-
assert s1.findAs<TClicker>(3).unwrap().clicks == 1
|
|
1000
|
-
assert s1.findAs<TClicker>(1).unwrap().clicks == 0 && s1.findAs<TClicker>(2).unwrap().clicks == 0
|
|
1001
|
-
# the nodes after the hit one are the same nodes, those before it only relinked
|
|
1002
|
-
assert @sameRef(nodeOf(s1.root, 4), nodeOf(s.root, 4))
|
|
1003
|
-
assert @sameRef(s1.find(1).unwrap(), s.find(1).unwrap())
|
std/game/Store.plum
DELETED
|
@@ -1,116 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Str
|
|
5
|
-
import std/collections/List
|
|
6
|
-
import std/Slice
|
|
7
|
-
import std/Io
|
|
8
|
-
|
|
9
|
-
# A game's state and the messages that change it. The state is a `Reducer<M>`: `update`
|
|
10
|
-
# is the rules (pure, no `Io`: the same messages from the same state give the same state,
|
|
11
|
-
# which is what makes a run replayable), and `handle` is the effects of a message (a sound,
|
|
12
|
-
# a save), run after the tick with the final state.
|
|
13
|
-
#
|
|
14
|
-
# A `Store` holds the state and the messages of the tick so far. `dispatch` reduces a
|
|
15
|
-
# message at once and queues it; `flush(io)` runs `handle` for each queued message, in
|
|
16
|
-
# the order they were dispatched, and empties the queue. Only `Game` drives a store (see
|
|
17
|
-
# docs/plans/2026-11-09-actor-trait.md, "One way to make a game"): a game writes its
|
|
18
|
-
# `Reducer`, never a loop that dispatches.
|
|
19
|
-
#
|
|
20
|
-
# A store is a value: `dispatch` and `flush` return a new store and leave the old one as
|
|
21
|
-
# it was. The queue is a `List` with the newest message first.
|
|
22
|
-
|
|
23
|
-
trait Reducer<M> =
|
|
24
|
-
# The rules: the state after `msg`.
|
|
25
|
-
fun update(self, msg: M) -> Self
|
|
26
|
-
|
|
27
|
-
# The effects of `msg`, run by `Store.flush` after the tick. None by default.
|
|
28
|
-
fun handle(self, io: Io, msg: M) = Unit
|
|
29
|
-
|
|
30
|
-
# The name of the screen to show (std/game/Game): `Game` switches to it after a tick
|
|
31
|
-
# that changed it. "" (the default) is the tree's first screen, so a game of one screen
|
|
32
|
-
# needs nothing; a game of several keeps the name in its state.
|
|
33
|
-
fun screen(self) -> Str = ""
|
|
34
|
-
|
|
35
|
-
struct Store<S: Reducer<M>, M>(state: S, queue: List<M>) =
|
|
36
|
-
# A store holding `state` with nothing queued.
|
|
37
|
-
fun of(state: S) -> Store<S, M> = Store(state: state, queue: Nil)
|
|
38
|
-
|
|
39
|
-
# Reduces `msg` into the state now and queues it for `flush`.
|
|
40
|
-
fun dispatch(self, msg: M) -> Store<S, M> =
|
|
41
|
-
Store(state: self.state.update(msg), queue: Cons(msg, self.queue))
|
|
42
|
-
|
|
43
|
-
# Each message of `msgs`, in order, as `dispatch` does.
|
|
44
|
-
fun dispatchAll(self, msgs: List<M>) -> Store<S, M> = msgs.fold(self, |st, m| st.dispatch(m))
|
|
45
|
-
|
|
46
|
-
# The queued messages, oldest first.
|
|
47
|
-
fun pending(self) -> List<M> = self.queue.reverse()
|
|
48
|
-
|
|
49
|
-
# Runs `handle` on the state for each queued message, oldest first, and empties the queue.
|
|
50
|
-
# A store with nothing queued is returned as it is.
|
|
51
|
-
fun flush(self, io: Io) -> Store<S, M> = match self.queue
|
|
52
|
-
Nil => self
|
|
53
|
-
Cons(_, _) =>
|
|
54
|
-
st := self.state
|
|
55
|
-
self.pending().each(|m| st.handle(io, m))
|
|
56
|
-
Store(state: st, queue: Nil)
|
|
57
|
-
|
|
58
|
-
# The state after each of `msgs` in order, with no effects: what a recorded run of
|
|
59
|
-
# messages leads to.
|
|
60
|
-
fun reduceAll<S: Reducer<M>, M>(s: S, msgs: List<M>) -> S = msgs.fold(s, |a, m| a.update(m))
|
|
61
|
-
|
|
62
|
-
enum StoreTestMsg = Add(n: Int) | Reset | Note(n: Int)
|
|
63
|
-
|
|
64
|
-
struct StoreTally[Reducer<StoreTestMsg>](total: Int, count: Int, log: Slice<Int>) =
|
|
65
|
-
fun update(self, msg: StoreTestMsg) -> StoreTally = match msg
|
|
66
|
-
Add(n) => StoreTally(..self, total: self.total + n, count: self.count + 1)
|
|
67
|
-
Reset => StoreTally(..self, total: 0, count: self.count + 1)
|
|
68
|
-
Note(_) => self
|
|
69
|
-
|
|
70
|
-
# Records what it saw, so a test can check the order and the state it ran with.
|
|
71
|
-
fun handle(self, io: Io, msg: StoreTestMsg) = match msg
|
|
72
|
-
Add(n) => self.log.push(n)
|
|
73
|
-
Reset => self.log.push(-1)
|
|
74
|
-
Note(n) => self.log.push(n * 1000 + self.total)
|
|
75
|
-
|
|
76
|
-
struct StoreQuiet[Reducer<Int>](n: Int) =
|
|
77
|
-
fun update(self, msg: Int) -> StoreQuiet = StoreQuiet(n: self.n + msg)
|
|
78
|
-
|
|
79
|
-
test "dispatch reduces at once and queues"
|
|
80
|
-
s := Store.of(StoreTally(total: 0, count: 0, log: Slice()))
|
|
81
|
-
t := s.dispatch(Add(n: 2)).dispatch(Add(n: 3))
|
|
82
|
-
assert t.state.total == 5
|
|
83
|
-
assert t.state.count == 2
|
|
84
|
-
assert t.pending().length() == 2
|
|
85
|
-
assert t.state.log.length() == 0
|
|
86
|
-
assert s.state.total == 0
|
|
87
|
-
assert s.pending().isEmpty()
|
|
88
|
-
|
|
89
|
-
test "flush handles each queued message in order with the final state, then clears"
|
|
90
|
-
log: Slice<Int> := Slice()
|
|
91
|
-
s := Store.of(StoreTally(total: 0, count: 0, log: log))
|
|
92
|
-
t := s.dispatchAll([Add(n: 2), Reset, Add(n: 7), Note(n: 1)])
|
|
93
|
-
assert t.state.total == 7
|
|
94
|
-
u := t.flush(io)
|
|
95
|
-
assert u.pending().isEmpty()
|
|
96
|
-
assert u.state.total == 7
|
|
97
|
-
assert log.length() == 4
|
|
98
|
-
assert log.at(0) == 2
|
|
99
|
-
assert log.at(1) == -1
|
|
100
|
-
assert log.at(2) == 7
|
|
101
|
-
assert log.at(3) == 1007
|
|
102
|
-
v := u.flush(io)
|
|
103
|
-
assert log.length() == 4
|
|
104
|
-
assert v.state.count == 3
|
|
105
|
-
|
|
106
|
-
test "a reducer without handle has no effects"
|
|
107
|
-
s := Store.of(StoreQuiet(n: 1)).dispatch(2).dispatch(3)
|
|
108
|
-
assert s.state.n == 6
|
|
109
|
-
assert s.flush(io).state.n == 6
|
|
110
|
-
assert s.flush(io).pending().isEmpty()
|
|
111
|
-
|
|
112
|
-
test "reduceAll reduces messages with no store"
|
|
113
|
-
assert reduceAll(StoreQuiet(n: 0), [1, 2, 3]).n == 6
|
|
114
|
-
t := reduceAll(StoreTally(total: 0, count: 0, log: Slice()), [Add(n: 4), Reset, Add(n: 1)])
|
|
115
|
-
assert t.total == 1 && t.count == 3
|
|
116
|
-
assert t.log.length() == 0
|
std/game/ui.plum
DELETED
|
@@ -1,193 +0,0 @@
|
|
|
1
|
-
module std
|
|
2
|
-
|
|
3
|
-
import std/Int
|
|
4
|
-
import std/Float
|
|
5
|
-
import std/Str
|
|
6
|
-
import std/Slice
|
|
7
|
-
import std/collections/List
|
|
8
|
-
import std/Option
|
|
9
|
-
import std/Io
|
|
10
|
-
import std/math/Vec2
|
|
11
|
-
import std/math/Affine
|
|
12
|
-
import std/game/Color
|
|
13
|
-
import std/game/input
|
|
14
|
-
import std/collections/RoseTree
|
|
15
|
-
import std/game/Place
|
|
16
|
-
import std/game/Actor
|
|
17
|
-
import std/game/Clickable
|
|
18
|
-
import std/game/Ctx
|
|
19
|
-
import std/game/SceneTree
|
|
20
|
-
|
|
21
|
-
# Widgets for a scene tree: actors (each implements `Actor<M>`), so any game's `SceneTree<M>` takes
|
|
22
|
-
# them. A `Button<M>` sends its `onClick: M` to the game when it is clicked: pressed (a
|
|
23
|
-
# pointer down on it, which `SceneTree.input` routes to it through `input`) and released
|
|
24
|
-
# on it. It shows the pointer by its own `step`: hovered while the pointer is over it,
|
|
25
|
-
# pressed while it is held down after a press on it. Releasing elsewhere sends nothing;
|
|
26
|
-
# dragging off and back while held, then releasing on it, still clicks.
|
|
27
|
-
|
|
28
|
-
# A button `w` by `h` with its top-left at (x, y) that sends `onClick` when clicked.
|
|
29
|
-
# `look` is how it shows the pointer, 0 idle, 1 hovered, 2 pressed; `armed` is whether a
|
|
30
|
-
# press on it is held. Make one with `ui.button`.
|
|
31
|
-
struct Button<M>[Actor<M>, Clickable](id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M, look: Int, armed: Bool) =
|
|
32
|
-
fun key(self) -> Int = self.id
|
|
33
|
-
|
|
34
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
35
|
-
|
|
36
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
37
|
-
actor.boxPaint(io, m, alpha, self.w, self.h, lookColor(self.look))
|
|
38
|
-
actor.textPaint(io, m, alpha, self.label, 4.0, 4.0, self.h * 0.5, Color.White)
|
|
39
|
-
|
|
40
|
-
fun hit(self, p: Vec2) -> Bool = actor.boxHit(self.w, self.h, p)
|
|
41
|
-
|
|
42
|
-
# A press on it arms it; a release on it while armed sends `onClick`.
|
|
43
|
-
fun input(self, ctx: Ctx<M>, e: InputEvent) -> Button<M> = match e
|
|
44
|
-
PointerDown(_, _) => Button(..self, armed: true, look: 2)
|
|
45
|
-
PointerUp(_, _) =>
|
|
46
|
-
if self.armed
|
|
47
|
-
ctx.send(self.onClick)
|
|
48
|
-
Button(..self, armed: false, look: 1)
|
|
49
|
-
_ => self
|
|
50
|
-
|
|
51
|
-
# Its look from the tick's pointer; a release anywhere disarms it. It is over the
|
|
52
|
-
# pointer when a pointer event there would go to it (`ctx.pointedAt()`), so of
|
|
53
|
-
# overlapping buttons only the top one shows hovered or pressed; stepped outside a
|
|
54
|
-
# tree's step, by its own `hit`.
|
|
55
|
-
fun step(self, ctx: Ctx<M>, dt: Float) -> Button<M> =
|
|
56
|
-
over := if ctx.scene.isEmpty()
|
|
57
|
-
self.hit(ctx.worldOf(self.place().local()).inverse().apply(ctx.input.pos))
|
|
58
|
-
else
|
|
59
|
-
ctx.pointedAt().map(|k| k == self.id).unwrapOr(false)
|
|
60
|
-
armed := self.armed && ctx.input.held.mouse
|
|
61
|
-
look := if armed && over then 2 else if over then 1 else 0
|
|
62
|
-
if armed == self.armed && look == self.look then self else Button(..self, armed: armed, look: look)
|
|
63
|
-
|
|
64
|
-
# A button, idle.
|
|
65
|
-
fun button<M>(id: Int, x: Float, y: Float, w: Float, h: Float, label: Str, onClick: M) -> Button<M> =
|
|
66
|
-
Button(id: id, x: x, y: y, w: w, h: h, label: label, onClick: onClick, look: 0, armed: false)
|
|
67
|
-
|
|
68
|
-
# A line of text in `color` with its top-left at (x, y), `size` high. Its opacity is its
|
|
69
|
-
# colour's alpha.
|
|
70
|
-
struct Label<M>[Actor<M>](id: Int, x: Float, y: Float, text: Str, size: Float, color: Color) =
|
|
71
|
-
fun key(self) -> Int = self.id
|
|
72
|
-
|
|
73
|
-
fun place(self) -> Place = place.at(self.x, self.y)
|
|
74
|
-
|
|
75
|
-
fun opacity(self) -> Float = self.color.a
|
|
76
|
-
|
|
77
|
-
fun paint(self, io: Io, m: Affine, alpha: Float) =
|
|
78
|
-
actor.textPaint(io, m, alpha, self.text, 0.0, 0.0, self.size, self.color.withAlpha(1.0))
|
|
79
|
-
|
|
80
|
-
fun relabel(self, t: Str) -> Label<M> = Label(..self, text: t)
|
|
81
|
-
|
|
82
|
-
fun lookColor(look: Int) -> Color =
|
|
83
|
-
if look == 2
|
|
84
|
-
uiPressedColor()
|
|
85
|
-
else if look == 1
|
|
86
|
-
uiHoverColor()
|
|
87
|
-
else
|
|
88
|
-
uiIdleColor()
|
|
89
|
-
|
|
90
|
-
fun uiIdleColor() -> Color = Color.rgb(0.2, 0.2, 0.3)
|
|
91
|
-
|
|
92
|
-
fun uiHoverColor() -> Color = Color.rgb(0.35, 0.35, 0.5)
|
|
93
|
-
|
|
94
|
-
fun uiPressedColor() -> Color = Color.rgb(0.6, 0.2, 0.2)
|
|
95
|
-
|
|
96
|
-
# --- tests ---
|
|
97
|
-
|
|
98
|
-
fun uiButton(id: Int, msg: Int, label: Str, x: Float, y: Float) -> RoseTree<Actor<Int>> =
|
|
99
|
-
RoseTree.leaf(button(id, x, y, 10.0, 10.0, label, msg))
|
|
100
|
-
|
|
101
|
-
# Two buttons in a group at (100, 0): 3 sends 30, 4 sends 40.
|
|
102
|
-
fun uiTree() -> SceneTree<Int> =
|
|
103
|
-
root: RoseTree<Actor<Int>> := RoseTree.of(Group(id: 0, x: 100.0, y: 0.0), [uiButton(3, 30, "Go", 0.0, 0.0), uiButton(4, 40, "Stop", 20.0, 0.0)])
|
|
104
|
-
SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
105
|
-
|
|
106
|
-
fun uiLook(t: SceneTree<Int>, id: Int) -> Int = t.findAs<Button<Int>>(id).unwrap().look
|
|
107
|
-
|
|
108
|
-
# A tick of the pointer at (x, 5) with the mouse `down` and `events`: the events routed
|
|
109
|
-
# through the tree, then a step, as `Game` does; the messages sent go to `out`.
|
|
110
|
-
fun uiTick(t: SceneTree<Int>, x: Float, down: Bool, events: List<InputEvent>, out: Slice<Int>) -> SceneTree<Int> =
|
|
111
|
-
i := Input(held: Held(mouse: down, keys: Slice<Int>()), events: events.toSlice(), pos: Vec2(x: x, y: 5.0), wheel: 0.0)
|
|
112
|
-
ctx: Ctx<Int> := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
|
|
113
|
-
routed := events.fold(t, |tr, e| tr.input(ctx, e))
|
|
114
|
-
s := routed.step(ctx, 1.0 / 60.0)
|
|
115
|
-
ctx.takeSends().each(|m| out.push(m))
|
|
116
|
-
s
|
|
117
|
-
|
|
118
|
-
test "a press and a release on a button sends its message"
|
|
119
|
-
out := Slice<Int>()
|
|
120
|
-
t := uiTree()
|
|
121
|
-
down := uiTick(t, 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
122
|
-
assert uiLook(down, 3) == 2 && uiLook(down, 4) == 0
|
|
123
|
-
assert out.length() == 0
|
|
124
|
-
up := uiTick(down, 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
125
|
-
assert out.length() == 1 && out.at(0) == 30
|
|
126
|
-
assert uiLook(up, 3) == 1
|
|
127
|
-
assert !up.findAs<Button<Int>>(3).unwrap().armed
|
|
128
|
-
|
|
129
|
-
test "a release elsewhere sends nothing and disarms"
|
|
130
|
-
out := Slice<Int>()
|
|
131
|
-
down := uiTick(uiTree(), 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
132
|
-
off := uiTick(down, 150.0, true, [PointerMove(x: 150.0, y: 5.0)], out)
|
|
133
|
-
assert uiLook(off, 3) == 0
|
|
134
|
-
up := uiTick(off, 150.0, false, [PointerUp(x: 150.0, y: 5.0)], out)
|
|
135
|
-
assert out.length() == 0
|
|
136
|
-
assert !up.findAs<Button<Int>>(3).unwrap().armed
|
|
137
|
-
# a later release on it is not a click
|
|
138
|
-
again := uiTick(uiTick(up, 105.0, false, [PointerMove(x: 105.0, y: 5.0)], out), 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
139
|
-
assert out.length() == 0
|
|
140
|
-
assert uiLook(again, 3) == 1
|
|
141
|
-
|
|
142
|
-
test "dragging off and back while held, then releasing on it, clicks once"
|
|
143
|
-
out := Slice<Int>()
|
|
144
|
-
down := uiTick(uiTree(), 105.0, true, [PointerDown(x: 105.0, y: 5.0)], out)
|
|
145
|
-
off := uiTick(down, 150.0, true, [PointerMove(x: 150.0, y: 5.0)], out)
|
|
146
|
-
back := uiTick(off, 105.0, true, [PointerMove(x: 105.0, y: 5.0)], out)
|
|
147
|
-
assert uiLook(back, 3) == 2
|
|
148
|
-
_ := uiTick(back, 105.0, false, [PointerUp(x: 105.0, y: 5.0)], out)
|
|
149
|
-
assert out.length() == 1 && out.at(0) == 30
|
|
150
|
-
|
|
151
|
-
test "a press and release between two ticks still clicks"
|
|
152
|
-
out := Slice<Int>()
|
|
153
|
-
_ := uiTick(uiTree(), 125.0, false, [PointerDown(x: 125.0, y: 5.0), PointerUp(x: 125.0, y: 5.0)], out)
|
|
154
|
-
assert out.length() == 1 && out.at(0) == 40
|
|
155
|
-
|
|
156
|
-
test "buttons show the pointer and are hit in their box"
|
|
157
|
-
out := Slice<Int>()
|
|
158
|
-
t := uiTree()
|
|
159
|
-
hov := uiTick(t, 101.0, false, [PointerMove(x: 101.0, y: 5.0)], out)
|
|
160
|
-
assert uiLook(t, 3) == 0
|
|
161
|
-
assert uiLook(hov, 3) == 1 && uiLook(hov, 4) == 0
|
|
162
|
-
assert lookColor(2).eq(uiPressedColor()) && lookColor(1).eq(uiHoverColor()) && lookColor(0).eq(uiIdleColor())
|
|
163
|
-
assert t.hitId(105.0, 5.0).unwrapOr(-1) == 3
|
|
164
|
-
assert t.hitId(125.0, 5.0).unwrapOr(-1) == 4
|
|
165
|
-
assert t.hitId(115.0, 5.0).isNone()
|
|
166
|
-
|
|
167
|
-
test "of two overlapping buttons only the top one, which a click reaches, shows the pointer"
|
|
168
|
-
out := Slice<Int>()
|
|
169
|
-
# 4 (x 105 to 115) is on top of 3 (x 100 to 110): they overlap from 105 to 110
|
|
170
|
-
root: RoseTree<Actor<Int>> := RoseTree.of(Group(id: 0, x: 100.0, y: 0.0), [uiButton(3, 30, "Under", 0.0, 0.0), uiButton(4, 40, "Top", 5.0, 0.0)])
|
|
171
|
-
t := SceneTree(root: root, camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
172
|
-
assert t.hitId(107.0, 5.0).unwrapOr(-1) == 4
|
|
173
|
-
hov := uiTick(t, 107.0, false, [PointerMove(x: 107.0, y: 5.0)], out)
|
|
174
|
-
assert uiLook(hov, 4) == 1 && uiLook(hov, 3) == 0
|
|
175
|
-
down := uiTick(hov, 107.0, true, [PointerDown(x: 107.0, y: 5.0)], out)
|
|
176
|
-
assert uiLook(down, 4) == 2 && uiLook(down, 3) == 0
|
|
177
|
-
up := uiTick(down, 107.0, false, [PointerUp(x: 107.0, y: 5.0)], out)
|
|
178
|
-
assert out.length() == 1 && out.at(0) == 40
|
|
179
|
-
# off the top one but still on the one under it, that one shows the pointer
|
|
180
|
-
under := uiTick(up, 102.0, false, [PointerMove(x: 102.0, y: 5.0)], out)
|
|
181
|
-
assert uiLook(under, 3) == 1 && uiLook(under, 4) == 0
|
|
182
|
-
|
|
183
|
-
test "a button stepped outside a tree's step shows the pointer by its own hit"
|
|
184
|
-
b: Button<Int> := button(1, 0.0, 0.0, 10.0, 10.0, "b", 7)
|
|
185
|
-
i := Input(held: Held(mouse: false, keys: Slice<Int>()), events: Slice<InputEvent>(), pos: Vec2(x: 5.0, y: 5.0), wheel: 0.0)
|
|
186
|
-
ctx: Ctx<Int> := Ctx.of(i, Vec2(x: 800.0, y: 600.0))
|
|
187
|
-
assert b.step(ctx, 0.1).look == 1
|
|
188
|
-
|
|
189
|
-
test "a label relabels and its alpha is its opacity"
|
|
190
|
-
l: Label<Int> := Label(id: 1, x: 0.0, y: 0.0, text: "a", size: 10.0, color: Color.White.withAlpha(0.5))
|
|
191
|
-
assert l.relabel("b").text == "b"
|
|
192
|
-
a: Actor<Int> := l
|
|
193
|
-
assert a.opacity() == 0.5
|
tests/traits/subtrait_defaults.plum
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# A subtrait may give a method of its supertrait a default of its own, with the same
|
|
2
|
+
# signature: a type that implements the subtrait and doesn't define the method takes the
|
|
3
|
+
# subtrait's default, whatever order its `[ ]` lists the traits in, and a call through the
|
|
4
|
+
# supertrait reaches it. This is how a generic trait does what its non-generic supertrait
|
|
5
|
+
# can't type: `Driven<A>` turns the keys into its own `A`s behind `Panel`'s `press`.
|
|
6
|
+
import std/Int
|
|
7
|
+
import std/Str
|
|
8
|
+
import std/Option
|
|
9
|
+
import std/collections/List
|
|
10
|
+
|
|
11
|
+
trait Panel =
|
|
12
|
+
fun title(self) -> Str
|
|
13
|
+
|
|
14
|
+
# The supertrait's default: nothing happens.
|
|
15
|
+
fun press(self, key: Int) -> Int = 0
|
|
16
|
+
|
|
17
|
+
# A panel with actions of its own type `A`: `press` maps the key to an `A` and applies it.
|
|
18
|
+
trait Driven<A>[Panel] =
|
|
19
|
+
fun map(self, key: Int) -> Option<A>
|
|
20
|
+
|
|
21
|
+
fun apply(self, a: A) -> Int
|
|
22
|
+
|
|
23
|
+
fun press(self, key: Int) -> Int = match self.map(key)
|
|
24
|
+
Some(a) => self.apply(a)
|
|
25
|
+
None => -1
|
|
26
|
+
|
|
27
|
+
enum Turn = Left | Right
|
|
28
|
+
|
|
29
|
+
enum Pick = First | Second(n: Int)
|
|
30
|
+
|
|
31
|
+
struct Wheel[Driven<Turn>](angle: Int) =
|
|
32
|
+
fun title(self) -> Str = "wheel"
|
|
33
|
+
|
|
34
|
+
fun map(self, key: Int) -> Option<Turn> =
|
|
35
|
+
if key == 1 then Some(Left) else if key == 2 then Some(Right) else None
|
|
36
|
+
|
|
37
|
+
fun apply(self, a: Turn) -> Int = match a
|
|
38
|
+
Left => self.angle - 90
|
|
39
|
+
Right => self.angle + 90
|
|
40
|
+
|
|
41
|
+
# The supertrait first in the list: the subtrait's default still wins.
|
|
42
|
+
struct Menu[Panel, Driven<Pick>](chosen: Int) =
|
|
43
|
+
fun title(self) -> Str = "menu"
|
|
44
|
+
|
|
45
|
+
fun map(self, key: Int) -> Option<Pick> = if key == 0 then Some(First) else Some(Second(n: key))
|
|
46
|
+
|
|
47
|
+
fun apply(self, a: Pick) -> Int = match a
|
|
48
|
+
First => 0
|
|
49
|
+
Second(n) => n * 10
|
|
50
|
+
|
|
51
|
+
# Only the supertrait: its own default.
|
|
52
|
+
struct Sign[Panel](n: Int) =
|
|
53
|
+
fun title(self) -> Str = "sign"
|
|
54
|
+
|
|
55
|
+
# A type that defines the method itself keeps its own.
|
|
56
|
+
struct Knob[Driven<Turn>](turns: Int) =
|
|
57
|
+
fun title(self) -> Str = "knob"
|
|
58
|
+
|
|
59
|
+
fun map(self, key: Int) -> Option<Turn> = Some(Right)
|
|
60
|
+
|
|
61
|
+
fun apply(self, a: Turn) -> Int = self.turns + 1
|
|
62
|
+
|
|
63
|
+
fun press(self, key: Int) -> Int = 1000 + key
|
|
64
|
+
|
|
65
|
+
test "panels of different action types in one list each take the most specific default"
|
|
66
|
+
panels: List<Panel> := [Wheel(angle: 0), Menu(chosen: 0), Sign(n: 0), Knob(turns: 0)]
|
|
67
|
+
out := panels.map(|p| p.press(2))
|
|
68
|
+
assert out.get(0).unwrap() == 90
|
|
69
|
+
assert out.get(1).unwrap() == 20
|
|
70
|
+
assert out.get(2).unwrap() == 0
|
|
71
|
+
assert out.get(3).unwrap() == 1002
|
|
72
|
+
assert Wheel(angle: 0).press(7) == -1
|
|
73
|
+
assert Wheel(angle: 90).press(1) == 0
|
|
74
|
+
|
|
75
|
+
test "a call through the subtrait reaches the same default"
|
|
76
|
+
d: Driven<Pick> := Menu(chosen: 5)
|
|
77
|
+
assert d.press(0) == 0
|
|
78
|
+
assert d.title() == "menu"
|