plum

#treesitter#compiler#wasm

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

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


af2eb22 — Peter John 2026-11-16T17:33:03+05:30
std/game review fixes (T7 items 1-21): undo keeps its redo through held keys (`Game.liveHeld` re-bases what the first tick after a move compares with); moves put the music back (`Game.loops`/`startLoops`, kept by `Loop`/`Stop` live and replayed, `resound` stops and starts the host's loops after a move; `main` starts music with `game.looping(io, sound, volume)`); a flat (zero-scaled) item is never hit (`Place.toLocal` -> Option, through `invert`); window resizes are recorded (`S<w>,<h>` token on a tick line when the window differs from the last written, `Ticker.written`, `Replay.written`; `onScreen` fills only unsized ticks); a nested `Blend` restores the enclosing mode (`Views.paintIn`/`paintCulledIn` thread it); `Bounce` points velocity back inside (`Body.bounced`); `Body.wrap` gives lo for an empty span and never hi; `then` chains stop at `Delivery.ThenDepth` (1000) naming the actions' type; `TestRig.dispatch` goes through `Game.dispatched`, a history entry of its own (`HistoryTick.apply`, `Dispatch`) that moves replay; the rig's ticks carry its window and a framed/replayed input's window resizes it; snapshots every `Game.SnapEvery` (600) ticks (`Game.snaps`, `Snap`; at most cap/600, dropped past a move back, retaken while playing on; a rewind from one equals a rewind from the start); Clockwork's minimap is an `Overlay` (presses no longer reach walkers under it); Balloon phase is its own draw (floatAt(3)); std `Dice(seed).roll(tick, kind, id)` with kinds mixed apart from ids, used by both games (Orbit Runner `DealRoll`/`CatchRoll`/`MineRoll`, Balloon Pop `LaunchRoll`/`RiseRoll`), `Dice.scatter` for the stars and confetti; `OnDemand` + `OnHeld` sleeps while nothing is held (`Held.any`); `OnButtonDown`/`OnButtonUp` subscriptions; `Button` is an `Actor` stepping its children; `Group`/`Blend` `Enabled` documented as `ChildrenOnly`; `Line(x, y)` and its width scaled across the segment (`Line.across`); `Cmd.travels` used by `obey`, Gfx header rewritten, `Test.expectObject` removed; lit `Spinner` bounds hold its halo, `Sprite.frameAt` safe for 0 frames and negative clocks, `Viewport.lookAt` stops on a zoom not above 0; `Aabb.shrink` replaces `Arena.inside`; Balloon Pop clouds wrap by `Body.wrap`. `Looping`'s helpers are walks, not `filter`s: a `filter` there costs Orbit Runner's `PlayingScreen.update` 4 of its 5 in-place spreads. Orbit Runner checksum 166413027 to 612522477 (new dice keys); Clockwork 294124446 kept. Tests: tests/std/game (Game, Replay new, ScreenSlice, View, Body, Line, Sprite, Place, Input), tests/std/math (Dice new, Aabb), games' tests, host_test (nested blend), game_entry_test (then cycle, zero zoom); docs/game.md
Files changed (50) hide show
  1. compiler/cli/tests/cli/game_entry_test.rs +17 -0
  2. compiler/game/tests/host_test.rs +1 -1
  3. docs/game.md +23 -22
  4. examples/games/balloonpop/BalloonPop.plum +1 -2
  5. examples/games/balloonpop/actors/Balloon.plum +1 -1
  6. examples/games/balloonpop/screens/PlaygroundScreen.plum +15 -14
  7. examples/games/clockwork/actors/Spinner.plum +5 -2
  8. examples/games/clockwork/screens/OrreryScreen.plum +8 -4
  9. examples/games/orbitrunner/OrbitRunner.plum +3 -5
  10. examples/games/orbitrunner/actors/Ship.plum +2 -1
  11. examples/games/orbitrunner/actors/Star.plum +5 -1
  12. examples/games/orbitrunner/screens/PlayingScreen.plum +11 -9
  13. std/Test.plum +1 -7
  14. std/game/Blend.plum +5 -4
  15. std/game/Body.plum +18 -9
  16. std/game/Button.plum +5 -2
  17. std/game/Game.plum +179 -37
  18. std/game/Gfx.plum +11 -6
  19. std/game/Group.plum +3 -1
  20. std/game/History.plum +18 -8
  21. std/game/Input.plum +13 -0
  22. std/game/Line.plum +28 -9
  23. std/game/Place.plum +4 -2
  24. std/game/Replay.plum +62 -27
  25. std/game/Screen.plum +1 -1
  26. std/game/ScreenSlice.plum +32 -15
  27. std/game/Sprite.plum +9 -2
  28. std/game/TestRig.plum +26 -18
  29. std/game/Touch.plum +2 -1
  30. std/game/View.plum +38 -26
  31. std/game/Viewport.plum +5 -1
  32. std/math/Aabb.plum +5 -0
  33. std/math/Dice.plum +33 -0
  34. tests/examples/games/balloonpop/actors/Balloon.plum +8 -0
  35. tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +2 -2
  36. tests/examples/games/clockwork/actors/Spinner.plum +9 -0
  37. tests/examples/games/clockwork/screens/OrreryScreen.plum +14 -1
  38. tests/examples/games/orbitrunner/actors/Orb.plum +1 -1
  39. tests/examples/games/orbitrunner/screens/PlayingScreen.plum +9 -0
  40. tests/std/game/Body.plum +19 -0
  41. tests/std/game/Game.plum +111 -0
  42. tests/std/game/Input.plum +6 -3
  43. tests/std/game/Line.plum +12 -0
  44. tests/std/game/Place.plum +2 -1
  45. tests/std/game/Replay.plum +58 -0
  46. tests/std/game/ScreenSlice.plum +37 -0
  47. tests/std/game/Sprite.plum +9 -0
  48. tests/std/game/View.plum +27 -0
  49. tests/std/math/Aabb.plum +6 -0
  50. tests/std/math/Dice.plum +37 -0
compiler/cli/tests/cli/game_entry_test.rs CHANGED
@@ -149,3 +149,20 @@ fn aGameChecksItsScreensNames() {
149
149
  let (ok, err) = runSource("goes", &screensGame(&["a", "b"], "b"));
150
150
  assert!(ok, "{err}");
151
151
  }
152
+
153
+ /// Actions whose `then` ask for each other stop the program at the `then` depth limit, naming
154
+ /// the actions' type, where they would overflow the stack; a camera zoomed to 0 stops it too.
155
+ #[test]
156
+ fn aThenCycleAndAZeroZoomStopTheProgram() {
157
+ let cycle = "module app\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/collections/List\nimport std/math/Vec2\nimport std/game/Input\nimport std/App\n\
158
+ import std/game/Cmd\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\n\n\
159
+ struct Loops[ScreenSlice<Int>](n: Int) =\n fun name(self) -> Str = \"loops\"\n fun subscriptions(self) -> List<Sub<Int>> = [OnFrame(|dt| 1)]\n \
160
+ fun update(self, a: Int) -> Next<Loops, Int> = Next(state: Loops(n: self.n + 1), then: [a])\n\nprimitive Main[App] =\n \
161
+ fun main(io: Io) =\n s: Screen := Loops(n: 0)\n g := Game(screens: [s]).step(io, Input(), 0.1, Vec2(x: 800.0, y: 600.0))\n io.printLn(\"ran {g.ticks}\")\n";
162
+ let (ok, err) = runSource("then_cycle", cycle);
163
+ assert!(!ok && err.contains("game: the actions' `then` goes 1000 deep at an action of Int"), "{err}");
164
+ let zoom = "module app\nimport std/Float\nimport std/Str\nimport std/Io\nimport std/game/Viewport\nimport std/App\n\nprimitive Main[App] =\n \
165
+ fun main(io: Io) =\n v := Viewport.of(Fit, 800.0, 600.0).lookAt(10.0, 10.0, 0.0)\n io.printLn(\"{v.sx}\")\n";
166
+ let (ok, err) = runSource("zero_zoom", zoom);
167
+ assert!(!ok && err.contains("viewport: lookAt needs a zoom above 0, not 0.0"), "{err}");
168
+ }
compiler/game/tests/host_test.rs CHANGED
@@ -941,7 +941,7 @@ fn aBlendWrapsItsChildrenAndALineIsDrawnThroughItsPlace() {
941
941
  "drawCircle(100,50,10,1,0,0,0.5)",
942
942
  "blendMode(2)",
943
943
  "drawCircle(105,50,4,0,0,1,1)",
944
- "blendMode(0)",
944
+ "blendMode(1)",
945
945
  "blendMode(0)",
946
946
  "drawLine(10,20,40,60,2,0,1,0,1)",
947
947
  "drawRect(1,2,3,4,1,0,0,1)",
docs/game.md CHANGED
@@ -213,20 +213,20 @@ The ready-made kinds are made with their fields named, and their fields have def
213
213
 
214
214
  | Kind | Fields | Defaults |
215
215
  |---|---|---|
216
- | `Group` | `x, y, touch, children`: a parent that paints nothing; its children (its block) are its `view` | `x: 0.0, y: 0.0, touch: ChildrenOnly` |
216
+ | `Group` | `x, y, touch, children`: a parent that paints nothing; its children (its block) are its `view`. It has no bounds, so it is never hit itself: `touch: Enabled` is the same as `ChildrenOnly`, and a panel that takes the presses on it is an `Overlay` (Clockwork's minimap is one) | `x: 0.0, y: 0.0, touch: ChildrenOnly` |
217
217
  | `Box` | `x, y, w, h, color, touch` (x, y its top-left) | `x: 0.0, y: 0.0, touch: Disabled` |
218
218
  | `Circle` | `x, y, r, color, touch` (x, y its centre: its bounds are -r to r) | `x: 0.0, y: 0.0, touch: Disabled` |
219
- | `Line` | `from, to, width, color, touch`: the segment from `from` to `to` in its holder's coordinates, `width` wide as its holder scales it; its bounds are the box around the segment widened by half the width, and it is hit within half its width of the segment (`Line.near(a, b, width, p)`, which a balloon's `hit` uses for its string) | `width: 1.0, color: Color.White, touch: Disabled` |
220
- | `Sprite` | `x, y, tex, w, h, srcX, srcY, srcW, srcH, frame, tint, touch`; `frame` picks the cell along a strip of `srcW`-wide cells from (`srcX`, `srcY`), and `Sprite.frameAt(clock, fps, count)` is the frame of a looping strip at a clock | `x: 0.0, y: 0.0, frame: 0, tint: Color.White, touch: Disabled` |
219
+ | `Line` | `x, y, from, to, width, color, touch`: the segment from `from` to `to` in its coordinates, which start at (`x`, `y`), `width` wide as its transform stretches across the segment (`Line.across`: an even scale scales it by that scale); its bounds are the box around the segment widened by half the width, and it is hit within half its width of the segment (`Line.near(a, b, width, p)`, which a balloon's `hit` uses for its string) | `x: 0.0, y: 0.0, width: 1.0, color: Color.White, touch: Disabled` |
220
+ | `Sprite` | `x, y, tex, w, h, srcX, srcY, srcW, srcH, frame, tint, touch`; `frame` picks the cell along a strip of `srcW`-wide cells from (`srcX`, `srcY`), and `Sprite.frameAt(clock, fps, count)` is the frame of a looping strip at a clock (in `[0, count)`: before 0 s it plays backwards from the last frame, and a strip of no frames shows 0) | `x: 0.0, y: 0.0, frame: 0, tint: Color.White, touch: Disabled` |
221
221
  | `Label` | `x, y, text, size, color, align, touch`; `align` puts the text's start (`Left`), middle (`Centre`) or end (`Right`) on `x`, by its width in the font the hosts draw with (`Label.textWidth`: Arial's advance widths, which the browser lays the text out by, so the bounds are what is drawn) | `x: 0.0, y: 0.0, size: 20.0, color: Color.White, align: Left, touch: Disabled` |
222
- | `Blend` | `x, y, mode, touch, children`: a parent that draws its children (its block) in the host's blend mode `mode`, one of its constants `Blend.Normal`, `Add` (brightens), `Multiply` (darkens) and `Screen` (lightens), and then returns the host to `Normal` (a `Blend` under another returns to `Normal`, not to the outer mode); never hit itself, no bounds | `x: 0.0, y: 0.0, touch: ChildrenOnly` |
222
+ | `Blend` | `x, y, mode, touch, children`: a parent that draws its children (its block) in the host's blend mode `mode`, one of its constants `Blend.Normal`, `Add` (brightens), `Multiply` (darkens) and `Screen` (lightens), and then puts back the mode it was drawn in (`Normal`, or the mode of the `Blend` it is under); never hit itself, no bounds | `x: 0.0, y: 0.0, touch: ChildrenOnly` |
223
223
  | `Overlay` | `x, y, w, h, color, touch, children`: a panel that dims what is under it and takes every press inside it, left out of the view while it should not show; its children are its block | `x: 0.0, y: 0.0, color: Overlay.Shade` (black at 0.6 alpha), `touch: Enabled` |
224
224
 
225
225
  Every kind is at the origin of what it is in unless given an `x` and a `y`: an actor's own view draws at the actor's place (`Sprite(tex: self.tex, ..)`). A kind of your own that takes children has a `children: List<View>` field, last so that a block fills it, and returns it from `view`.
226
226
 
227
227
  ### How std draws a view
228
228
 
229
- The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down (after a `Blend`'s view, the blend mode goes back to `Normal`). A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
229
+ The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down (after a `Blend`'s view, the blend mode goes back to the one it was drawn in). An item scaled flat (0 on an axis) is drawn as the host draws it, and never hit, nor what is under it. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
230
230
 
231
231
  Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll`, `stepSome` and `stepIn` for a derived stepping.
232
232
 
@@ -236,7 +236,7 @@ The host adds up the time between frames and runs one tick (`Game.update`) for e
236
236
 
237
237
  The tick's `Input` is read from the host once per frame, before the ticks, with the window's size (`input.screen`, which the game takes its window from: `Game.update` is `step` with `input.screen`). A frame's key and pointer events go to its first tick, or to the next frame's if it ran none, so a press counts once. Later ticks of the frame see what is held, with no events. A slice gets it through its subscriptions (`OnKeyDown`, `OnHeld`, ..) and its presses; don't read input any other way.
238
238
 
239
- Keep randomness in the screen as a seed, taken once in `main` from `io.randomSeed()`, and a tick count, and draw by counter ([`std/math/Random.plum`](../std/math/Random.plum)): `Random.at(seed, tick, salt)` is the key of one moment of one thing (the salt says which: Orbit Runner's orb ids, then a number for each mine), and `dice.floatAt(i)` its `i`th draw, a pure function of the key and `i` (SplitMix64). Nothing is threaded: no generator is handed on from draw to draw or kept in the next screen, so a draw can sit in a `map` (`Range.until(0, n).map(|i| Orb.spawn(i, Random.at(seed, ticks, i), ship, tex))`) and two draws in one tick never wait on each other. Then the same seed and the same inputs give the same game, tick for tick. (`Random.seeded(n)` and `nextFloat`, which return the value and the next generator, are still there for code that would rather thread one.) Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has one checksum, run after run (`benchmarks/screen_views/orbit.plum`; it was master's imperative Orbit Runner's until the rules returned their follow-ups as actions).
239
+ Keep randomness in the screen as its dice, a `Dice` made once from the seed `main` takes from `io.randomSeed()` ([`std/math/Dice.plum`](../std/math/Dice.plum)), and a tick count, and draw by counter: `dice.roll(tick, kind, id)` is the key of one moment of one thing, `kind` a constant of the game for each purpose (Orbit Runner's `DealRoll`, `CatchRoll` and `MineRoll`; Balloon Pop's `LaunchRoll` and `RiseRoll`) and `id` which one of that kind, and `key.floatAt(i)` its `i`th draw, a pure function of the key and `i` (SplitMix64, [`std/math/Random.plum`](../std/math/Random.plum)'s `Random.at`). Kinds are mixed in apart from ids, so two purposes never draw the same numbers, even in one tick (a restart's deal and a catch, which shared keys when the games added salts by hand). Nothing is threaded: no generator is handed on from draw to draw or kept in the next screen, so a draw can sit in a `map` (`Range.until(0, n).map(|i| Orb.spawn(i, dice.roll(ticks, PlayingScreen.DealRoll, i), ship, tex))`) and two draws in one tick never wait on each other. `Dice.scatter(i, w, h)` is the `i`th point of a fixed scatter with no seed, where the games' stars and confetti stand. Then the same seed and the same inputs give the same game, tick for tick. (`Random.seeded(n)` and `nextFloat`, which return the value and the next generator, are still there for code that would rather thread one.) Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has one checksum, run after run (`benchmarks/screen_views/orbit.plum`; it was master's imperative Orbit Runner's until the rules returned their follow-ups as actions).
240
240
 
241
241
  The maths is the same everywhere too. std's maths (`Math.sin`, `Math.sqrt`, ...) is Plum code built from IEEE 754 double operations, which wasm defines exactly, so every browser and the native host get the same bits; a test in [`tests/port/game/replay.plum`](../tests/port/game/replay.plum) pins some of them. The one host value a tick gets is the window's size, on its input, and a replay records it.
242
242
 
@@ -249,46 +249,46 @@ A run of a game is its seed and one `Input` per tick, so a recording is that and
249
249
  - **Going back**, a game that keeps its history can rewind to any tick, undo and redo ([Undo and time travel](#undo-and-time-travel)), by the same idea: the game made again and the recorded ticks played into it.
250
250
  - **In a test**, the kit records with `t.record(seed)`, runs frames with `t.frame(input, frameDt)` and gives the recording with `t.recorded()`; a rig of a game made from `r.seed` and given `t.replay(r)` reaches the same state. `r.encode()` and `Replay.decode(text)` turn a replay into its text and back. Each example game replays a run this way; Orbit Runner's [`screens/PlayingScreen.plum`](../examples/games/orbitrunner/screens/PlayingScreen.plum) replays a 600-tick run and a run through a game over and a restart, and compares the score and every position.
251
251
 
252
- While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `Ticker` hands it the inputs of each frame's ticks. While replaying, `io.randomSeed()` returns the recorded seed and the screen size is the recorded one: each replayed tick's `Input.screen` is the header's. Only the first `io.randomSeed()` call is recorded; while recording or replaying, any later call returns a seed derived from that one, the same in the browser and natively, so it replays too. The screen size is the one at the start of the recording: resizing the window while recording isn't recorded.
252
+ While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `Ticker` hands it the inputs of each frame's ticks. While replaying, `io.randomSeed()` returns the recorded seed and the window is the recorded one: each replayed tick's `Input.screen` is the header's, or the last size a tick line gave. Only the first `io.randomSeed()` call is recorded; while recording or replaying, any later call returns a seed derived from that one, the same in the browser and natively, so it replays too. A resize while recording is recorded: the tick it reaches says its new size (the `Ticker` writes a tick's size when it differs from the last one written), so the replay resizes at the same tick. In a test, a tick's input carries the rig's window, `t.resize(w, h)` changes it, and a replayed or framed input with a window of its own resizes the rig.
253
253
 
254
- The text is one line for the seed and screen size (`plum-replay <seed high> <seed low> <width> <height>`), then one line per tick: what is held after the tick (the keys, the mouse buttons and the pointer) and the tick's events, a turn of the wheel among them (`W<dy>`). What is held is a fold of the events (`Held.after`), and each line keeps it all the same, so a replay doesn't depend on the fold. Floats are written exactly. There is one form, with no version number: a file in an older form is not read. The details are at the top of `std/game/Replay.plum`.
254
+ The text is one line for the seed and screen size (`plum-replay <seed high> <seed low> <width> <height>`), then one line per tick: what is held after the tick (the keys, the mouse buttons and the pointer), the window when it changed (`S<w>,<h>`), and the tick's events, a turn of the wheel among them (`W<dy>`). What is held is a fold of the events (`Held.after`), and each line keeps it all the same, so a replay doesn't depend on the fold. Floats are written exactly. There is one form, with no version number: a file in an older form is not read. The details are at the top of `std/game/Replay.plum`.
255
255
 
256
256
  ## Undo and time travel
257
257
 
258
- A game can go back to any tick it has played, and forward again along what it undid: a player's undo in a puzzle, or stepping through a bug tick by tick. Going back is **re-simulation**: the game is made again from the screens it was made with and the recorded ticks are played into it. A game is a value, so old games could be kept as they are; but keeping one at every tick keeps every state of a long run, and re-simulation keeps only the input, as master does.
258
+ A game can go back to any tick it has played, and forward again along what it undid: a player's undo in a puzzle, or stepping through a bug tick by tick. Going back is **re-simulation**: the game starts again from its latest snapshot before where it goes, or from the screens it was made with, and the recorded ticks after it are played into it. A game is a value, so a snapshot is just the game as it was; keeping one at every tick would keep every state of a long run, so the history keeps the input of every tick and a snapshot every `Game.SnapEvery` (600) ticks.
259
259
 
260
260
  ```plum
261
261
  primitive BalloonPop[App] =
262
262
  fun main(io: Io) -> Game =
263
263
  assets := Assets.load(io)
264
- assets.music.loop(io, 0.2)
265
264
  sky: Screen := PlaygroundScreen.seeded(io.randomSeed(), assets)
266
- Game(screens: [sky]).timeTravel(History.Cap)
265
+ Game(screens: [sky]).looping(io, assets.music, 0.2).timeTravel(History.Cap)
267
266
  ```
268
267
 
269
268
  `g.timeTravel(cap)` switches it on, before the first tick. It needs no function to make the game again (master's `timeTravel(make)` does): the game keeps the screens it was made with (`initial`). From then on the game keeps its **history** (`std/game/History`), one entry per tick. Then, each returning the game moved:
270
269
 
271
270
  | `Game` | What it does |
272
271
  |---|---|
273
- | `rewindTo(io, tick)` | the state the game was in after `tick` ticks. Going back makes the game again from `initial`, then plays the first `tick` recorded ticks into it; going forward plays the ticks undone on from where it is |
272
+ | `rewindTo(io, tick)` | the state the game was in after `tick` ticks. Going back starts from the latest snapshot at or before `tick` (or `initial`), then plays the recorded ticks after it up to `tick`; going forward plays the ticks undone on from where it is |
274
273
  | `undo(io)`, `redo(io)` | back to just before the last user action (below); forward to just before the next user action undone, or to the end |
275
274
  | `canUndo()`, `canRedo()` | whether there is one |
276
275
  | `stepBack(io)`, `stepForward(io)` | one tick back or forward, for scrubbing |
277
276
  | `tickNow()`, `ticksRecorded()` | the tick the game is at, and how far the history reaches |
278
277
  | `pause()`, `resume()`, `paused` | hold the game still: no tick runs and nothing is recorded, while the moves above still work; `resume()` goes on from where the game is and drops what could be redone |
279
278
  | `travels()`, `rewound`, `moved` | whether a history is kept and not full; how many ticks the last move played; whether the last move could be made |
279
+ | `looping(io, sound, volume)` | in `main`, starts a sound looping as a `Loop` command would, so moves know it plays (`loops`) |
280
280
 
281
281
  A move that can't be made (no history, a full one, a tick out of reach) leaves the game as it was with `moved` false. After a move the game plays on from there: the ticks undone stay as the future, for `redo`, until a user action cuts them.
282
282
 
283
- **What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length and whether it was a user action. Not actions: the recorded input is mapped again into fresh actions against the state made again, so an action needs no text form of its own.
283
+ **What is recorded.** Each tick's `Input`, the window's size (`pixels`), the tick's length and whether it was a user action, and every `Game.SnapEvery` ticks a snapshot of the game (`snaps`; at most `cap / SnapEvery` of them, dropped past where a move back goes, and taken again as the ticks are played on). Not actions: the recorded input is mapped again into fresh actions against the state made again, so an action needs no text form of its own. A test's `dispatch(a)`, an action outside any tick, is the one exception: it is an entry of its own, holding the delivery to do again (`Game.dispatched`). A rewind from a snapshot reaches the same game as one from the start (`tests/std/game/Game.plum` checks both against a run played straight there).
284
284
 
285
- **What a rewind does with commands.** A tick played again gives the commands it gave the first time, as it is the same tick on the same state; of those the game does only the `GoTo`s again, at the same point. No sound plays, and no `Exit`, undo, redo or rewind is done again.
285
+ **What a rewind does with commands.** A tick played again gives the commands it gave the first time, as it is the same tick on the same state; of those the game does only the `GoTo`s again, at the same point, and keeps what each `Loop` and `Stop` does to the sounds looping (`loops`). No sound plays, and no `Exit`, undo, redo or rewind is done again. Once moved, the host's loops are put right (`resound`): a sound stopped since the tick gone to starts looping again, one started since stops. A sound `main` starts should be started with `game.looping(io, sound, volume)` for this, as both example games' music is.
286
286
 
287
- **A user action** is a tick in which the shown slice screen's subscriptions or a press gave an action for one of the tick's events (`OnKeyDown`, `OnPointerDown`, .., `onPress`), or `OnHeld` gave an action while what is held (the keys and the mouse buttons) differs from that screen's tick before. The frame action is not one, nor an unchanged `OnHeld`, nor an action an update's `then` gives. A tick whose commands asked for an undo, a redo or a rewind is not one either. `undo` lands just before the last user action; again, just before the one before.
287
+ **A user action** is a tick in which the shown slice screen's subscriptions or a press gave an action for one of the tick's events (`OnKeyDown`, `OnPointerDown`, .., `onPress`), or `OnHeld` gave an action while what is held (the keys and the mouse buttons) differs from that screen's tick before. The frame action is not one, nor an unchanged `OnHeld`, nor an action an update's `then` gives. A tick whose commands asked for an undo, a redo or a rewind is not one either. The first tick after a move compares what is held with what was held at the last tick played live, not at the tick gone back to, so a key held through an undo (or one let go to press it) is no new action and the undone ticks can still be redone. `undo` lands just before the last user action; again, just before the one before.
288
288
 
289
289
  **Offering undo in a game.** A slice's `update` asks with a command: `Undo`, `Redo`, `RewindTo(tick: k)` (`std/game/Cmd`), done once the tick is recorded. Balloon Pop subscribes Z and Backspace to `TakeBack` (`OnKeyDown(key: Key.KeyZ, act: TakeBack)`), whose update is `Next(state: self, cmds: [Undo])`: the last press is taken back, and the balloon it popped is whole again.
290
290
 
291
- **What it costs.** A rewind back costs the ticks it plays: `rewindTo(k)` plays `k` ticks from the start, with no drawing and no sound. A move forward plays only the ticks ahead. The history is a list of ticks; `timeTravel(cap)` bounds it (`History.Cap` is 30 minutes of ticks). Once full, the history lets its ticks go and every move is refused from then on; the game plays on.
291
+ **What it costs.** A rewind back costs the ticks it plays: at most `SnapEvery` (600, 10 s) from the snapshot before it, with no drawing and no sound. A move forward plays only the ticks ahead. The history is a list of ticks and its snapshots; `timeTravel(cap)` bounds it (`History.Cap` is 30 minutes of ticks, and 180 snapshots). Once full, the history lets its ticks and snapshots go and every move is refused from then on; the game plays on.
292
292
 
293
293
  **The development keys.** `plum run --dev` serves the game for development: the game keeps its history from the first frame, whether or not it calls `timeTravel`, and the keyboard moves through it:
294
294
 
@@ -313,7 +313,7 @@ Three files of `std/game` talk to the host. Each host call takes `io` first.
313
313
  | Shapes | `drawRect(io, x, y, w, h, c)`, `drawRectEx(io, x, y, w, h, rotation, c)` (turned clockwise about its centre), `drawCircle(io, x, y, r, c)`, `drawLine(io, x1, y1, x2, y2, thickness, c)` |
314
314
  | Text | `drawText(io, s, x, y, size, c)`, `drawTextEx(io, s, x, y, size, rotation, c)` (turned clockwise about its top-left) |
315
315
  | Images | `Texture.load(io, name)` gives a `Texture` with `draw(io, x, y)`, `width(io)`, `height(io)`, `setSmooth(io, smooth)`; `drawTextureEx(io, t.id, sx, sy, sw, sh, x, y, w, h, rotation, flipX, tint)` |
316
- | Camera | `setCamera(io, x, y, scale)`, `resetCamera(io)` |
316
+ | Camera | `setCamera(io, x, y, scale)`, `resetCamera(io)`: the host's own camera, for a program that draws with `Gfx` alone; the engine never sets it (it draws through each screen's transform), as it never reads `frameTime` (its clock is its ticks) |
317
317
  | Draw into an image | `Texture.create(io, w, h)`, `t.renderTarget(io)`, `renderToScreen(io)` |
318
318
  | Blending | `blendMode(io, m)` with `Blend.Normal`, `Blend.Add`, `Blend.Multiply`, `Blend.Screen` (`std/game/Blend`'s constants; in a view, a `Blend` sets and restores it) |
319
319
  | Files | `loadFile(io, name)`, the file's text; `fileExists(io, name)` |
@@ -353,7 +353,7 @@ fun frames(self) -> Frames = OnDemand
353
353
 
354
354
  `Always`, the default, ticks the screen every tick. An `OnDemand` screen sleeps through every tick in which nothing needs doing: the game delivers it no tick (no action, no command). Something needs doing, and the screen ticks, when any of these holds:
355
355
 
356
- - the tick's input has an event: a key, a press, a pointer that moved (a move to where it already was doesn't count), or the screen subscribes to `OnHeld` (what is held gives it an action);
356
+ - the tick's input has an event: a key, a press, a pointer that moved (a move to where it already was doesn't count), or the screen subscribes to `OnHeld` and something is held (a key, a mouse button or a touch: what is held gives it an action);
357
357
  - the tick before left the screen `busy()`, gave a command, or a transition is in progress;
358
358
  - the screen was just entered, or the screen's size changed.
359
359
 
@@ -386,11 +386,12 @@ fun subscriptions(self) -> List<Sub<PlayAction>> = [
386
386
  |---|---|
387
387
  | `OnFrame(act)` | `act(dt)` each tick, last: the frame, which steps the actors and runs the rules |
388
388
  | `OnKeyDown(key, act)`, `OnKeyUp(key, act)` | `act` when that key goes down, or up |
389
- | `OnHeld(act)` | `act(h)` each tick, with what is held after the tick's events (`Held`): the steering keys. It also wakes an `OnDemand` screen |
389
+ | `OnHeld(act)` | `act(h)` each tick, with what is held after the tick's events (`Held`): the steering keys. It also wakes an `OnDemand` screen while something is held |
390
390
  | `OnWheel(act)` | `act(dy, at)` for a turn of the wheel, `at` where the pointer is, in the world |
391
391
  | `OnPointerDown(act)`, `OnPointerUp(act)`, `OnPointerMove(act)` | `act(at)` for a pointer event, `at` its point in the world; a pointer down that a press target took is not one |
392
+ | `OnButtonDown(act)`, `OnButtonUp(act)` | `act(button, at)` for the right or the middle mouse button (`Mouse.Right`, `Mouse.Middle`) going down or up, `at` where, in the world |
392
393
 
393
- The list is a list literal made again each tick, so an item is there only while the state says so (an `if` item). std reads it once a tick, from the screen as the tick found it: on the tick a run ends, its `OnHeld` still steers, and on the tick Enter starts it over, nothing steers until the next.
394
+ The list is a list literal made again each tick, so an item is there only while the state says so (an `if` item). A chain of `then`s more than 1000 actions deep (`Delivery.ThenDepth`: actions that ask for each other) stops the program, naming the actions' type. std reads it once a tick, from the screen as the tick found it: on the tick a run ends, its `OnHeld` still steers, and on the tick Enter starts it over, nothing steers until the next.
394
395
 
395
396
  **Each tick**, std delivers to the shown screen, in this order:
396
397
 
@@ -415,7 +416,7 @@ Orbit Runner steers with `h.axis`: `Steer(ax: {h.axis(Key.Left, Key.Right) + h.a
415
416
 
416
417
  ## Clicks
417
418
 
418
- A press is hit-tested by std against what the shown screen's `hud` draws, then its view: the press is on the top-most visible item under it that is `Sized` with `touch` `Enabled` and whose `hit(p)` says the point (in its own coordinates) is on it: what is drawn later before what is drawn earlier, what is under an item (its `view`: the children of a `Group` or an `Overlay`) before the item, through every turn and scale on the way. A `Disabled` item takes everything under it out of the walk. The view is made again for the press, from the screen as the tick has left it so far. [`tests/port/game/routing.plum`](../tests/port/game/routing.plum) checks the walk against a brute-force reference on 300 random nested views.
419
+ A press is hit-tested by std against what the shown screen's `hud` draws, then its view: the press is on the top-most visible item under it that is `Sized` with `touch` `Enabled` and whose `hit(p)` says the point (in its own coordinates) is on it: what is drawn later before what is drawn earlier, what is under an item (its `view`: the children of a `Group` or an `Overlay`) before the item, through every turn and scale on the way. A `Disabled` item takes everything under it out of the walk, and so does one scaled flat (0 on an axis), which no point maps back into. The view is made again for the press, from the screen as the tick has left it so far. [`tests/port/game/routing.plum`](../tests/port/game/routing.plum) checks the walk against a brute-force reference on 300 random nested views.
419
420
 
420
421
  The item hit becomes the slice's action through `onPress(target, at)`, which by default is what the item says a press on it means: an item that is a `Presses<A>` (`std/game/Button`) gives its `pressed()`, and any other gives None. A `Button(x, y, w, h, on: action) { .. }` is one ready-made: a box that takes presses, drawn by its children. An actor of your own says it the same way; Balloon Pop's balloons, each `Sized` with its exact shape and `Enabled` while whole, are `Presses<PopAction>`:
421
422
 
@@ -475,7 +476,7 @@ primitive PlayingScreenTest[UnitTest] =
475
476
  |---|---|
476
477
  | Input, for the next tick | `press(key)` (down and up within the tick: one key down for the mapping, not held after), `hold(key)`, `release(key)`, `click(actor)` (a press and release at the actor's centre, its bounds' if it is `Sized`, in screen pixels through the camera, or one unit a pixel for an item of the hud, so it goes through the real hit test: a panel in front gets it), `clickAt(x, y)`, `pointerMove(x, y)`, `send(e)`, `next(held, events)` |
477
478
  | Time | `tick()` (the game's own tick: the subscriptions and presses, the frame action, transition and commands), `ticks(n)` (`n` ticks, the input going to the first), `tick(dt)` for a tick of another length, `frame(input, frameDt)` for the host's frame with the `Ticker` turning wall time into ticks |
478
- | An action | `dispatch(a)`: stepped into the rig's screen through its `update`, as a delivery steps it (with its `then`), then what ends a tick: its commands, an undo, a redo or a rewind done at once |
479
+ | An action | `dispatch(a)`: stepped into the rig's screen through its `update`, as a delivery steps it (with its `then`), then what ends a tick: its commands, an undo, a redo or a rewind done at once; a game with a history keeps it there, so a rewind past it does it again |
479
480
  | Reading, the view's then the hud's | `find<T>()` (the items of type `T` the view and the hud draw, in the order drawn, an item before what is under it), `first<T>()` (none stops the test: "headless: first: no actor of the type asked for is in the view"), `count<T>()`, `text(label)`, `shown(actor)` (the view or the hud draws it), `hit(x, y)` (what a press at that screen pixel lands on, the hud first), `worldOf(actor)` (its transform), `toWorld(x, y)` (a screen pixel in the world, through the camera), `drawn()` (what the frame draws, `Game.drawList()`) |
480
481
  | What came out of the last `tick` or `ticks` | `actions<A>()` (the actions of type `A` stepped, in order), `cmds` (the commands, in order), `wentTo()` (the last `GoTo`'s name, an `Option`), `exited()`; `showing()` names the screen shown |
481
482
  | A whole run | `record(seed)`, `recorded()`, `replay(r)`, and `game` (its counters) |
examples/games/balloonpop/BalloonPop.plum CHANGED
@@ -38,6 +38,5 @@ struct Assets(pop: Sound, party: Sound, music: Sound) =
38
38
  primitive BalloonPop[App] =
39
39
  fun main(io: Io) -> Game =
40
40
  assets := Assets.load(io)
41
- assets.music.loop(io, 0.2)
42
41
  sky: Screen := PlaygroundScreen.seeded(io.randomSeed(), assets)
43
- Game(screens: [sky]).timeTravel(History.Cap)
42
+ Game(screens: [sky]).looping(io, assets.music, 0.2).timeTravel(History.Cap)
examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -34,7 +34,7 @@ struct Balloon[Actor, Sized, Touch, Presses<PopAction>, Steps](
34
34
  speed := Balloon.MinSpeed + dice.floatAt(1) * {Balloon.MaxSpeed - Balloon.MinSpeed}
35
35
  Balloon(
36
36
  id: id, body: Body(pos: Vec2(x: 60.0 + dice.floatAt(0) * {Arena.W - 120.0}, y: Arena.H + Balloon.Radius + depth), vel: Vec2(x: 0.0, y: 0.0 - speed)),
37
- hue: dice.intBelowAt(2, Hue.All.length()), phase: dice.floatAt(0) * Float.Tau, clock: clock)
37
+ hue: dice.intBelowAt(2, Hue.All.length()), phase: dice.floatAt(3) * Float.Tau, clock: clock)
38
38
 
39
39
  fun place(self) -> Place = Place.at(self.drawnX(), self.body.pos.y)
40
40
 
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -8,9 +8,11 @@ import std/Io
8
8
  import std/Slice
9
9
  import std/collections/List
10
10
  import std/math/Random
11
+ import std/math/Dice
11
12
  import std/math/Vec2
12
13
  import std/math/Math
13
14
  import std/game/Color
15
+ import std/game/Body
14
16
  import std/game/Input
15
17
  import std/game/View
16
18
  import std/game/Box
@@ -32,15 +34,18 @@ enum PopAction[Show] =
32
34
  | Tick(dt: Float)
33
35
 
34
36
  struct PlaygroundScreen[ScreenSlice<PopAction>](
35
- seed: Int, ticks: Int, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
37
+ dice: Dice, ticks: Int, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
36
38
  const Count = 6
37
39
  const PartyEvery = 10
38
40
  const PartyTime = 2.5
39
41
  const Confetti = 30
42
+ const LaunchRoll = 0
43
+ const RiseRoll = 1
40
44
 
41
45
  fun seeded(seed: Int, assets: Assets) -> PlaygroundScreen =
46
+ dice := Dice(seed: seed)
42
- balloons := Range.until(0, PlaygroundScreen.Count).map(|i| Balloon.spawn(Balloon.FirstId + i, Random.at(seed, 0, Balloon.FirstId + i), Float(i) * 110.0 - Arena.H * 0.6, 0.0))
47
+ balloons := Range.until(0, PlaygroundScreen.Count).map(|i| Balloon.spawn(Balloon.FirstId + i, dice.roll(0, PlaygroundScreen.LaunchRoll, i), Float(i) * 110.0 - Arena.H * 0.6, 0.0))
43
- PlaygroundScreen(seed: seed, ticks: 0, assets: assets, pops: 0, partyAt: -100.0, clock: 0.0, balloons: balloons)
48
+ PlaygroundScreen(dice: dice, ticks: 0, assets: assets, pops: 0, partyAt: -100.0, clock: 0.0, balloons: balloons)
44
49
 
45
50
  fun name(self) -> Str = "sky"
46
51
 
@@ -52,8 +57,8 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
52
57
  Box(w: Arena.W, h: Arena.H, color: Color.rgb(0.55, 0.8, 1.0))
53
58
  Box(w: Arena.W, h: 200.0, color: Color.rgb(0.45, 0.72, 0.98))
54
59
  Circle(x: 690.0, y: 90.0, r: 46.0, color: Color.rgb(1.0, 0.9, 0.35))
55
- cloud(wrapX(120.0 + self.clock * 12.0), 130.0)
60
+ cloud(Body.wrap(20.0 + self.clock * 12.0, -100.0, Arena.W + 100.0), 130.0)
56
- cloud(wrapX(520.0 + self.clock * 8.0), 220.0)
61
+ cloud(Body.wrap(420.0 + self.clock * 8.0, -100.0, Arena.W + 100.0), 220.0)
57
62
  Box(y: Arena.H - 50.0, w: Arena.W, h: 50.0, color: Color.rgb(0.4, 0.78, 0.35))
58
63
  ..self.balloons
59
64
  if self.partying() then ..self.party()
@@ -87,8 +92,8 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
87
92
  moved := self.stepped(dt)
88
93
  clock := moved.clock + dt
89
94
  ticks := moved.ticks + 1
90
- seed := moved.seed
95
+ dice := moved.dice
91
- balloons := moved.balloons.map(|b| if b.done() then Balloon.spawn(b.id, Random.at(seed, ticks, b.id), 0.0, clock) else b)
96
+ balloons := moved.balloons.map(|b| if b.done() then Balloon.spawn(b.id, dice.roll(ticks, PlaygroundScreen.RiseRoll, b.id), 0.0, clock) else b)
92
97
  Next(state: PlaygroundScreen(..moved, ticks: ticks, clock: clock, balloons: balloons))
93
98
 
94
99
  fun popped(self, at: Float) -> PlaygroundScreen =
@@ -119,14 +124,10 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
119
124
  if lap < 0.4 then 1.4 * {1.0 - 0.15 * lap / 0.4} else 1.4 * 0.85 * {1.0 + {1.0 / 0.85 - 1.0} * {lap - 0.4} / 0.4}
120
125
 
121
126
  fun confetto(i: Int, age: Float) -> Box =
122
- x := Float({i * 7919} % 800)
127
+ p := Dice.scatter(i, 800, 200)
123
- y := Float({i * 104729} % 200) - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
128
+ y := p.y - 200.0 + age * {180.0 + Float(i % 5) * 40.0}
124
129
  wob := 10.0 * Math.sin(age * 4.0 + Float(i))
125
- Box(x: x + wob, y: y, w: 12.0, h: 12.0, color: Hue.of(i).color)
130
+ Box(x: p.x + wob, y: y, w: 12.0, h: 12.0, color: Hue.of(i).color)
126
-
127
- fun wrapX(x: Float) -> Float =
128
- span := Arena.W + 200.0
129
- x - span * Float(Int(x / span)) - 100.0
130
131
 
131
132
  fun cloud(x: Float, y: Float) -> Group =
132
133
  white := Color.White.withAlpha(0.9)
examples/games/clockwork/actors/Spinner.plum CHANGED
@@ -41,11 +41,14 @@ struct Spinner[Actor, Sized, Touch, Presses<SkyAction>, Steps](
41
41
 
42
42
  fun step(self, dt: Float) -> Spinner = Spinner(..self, clock: self.clock + dt)
43
43
 
44
- fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.size, self.size)
44
+ fun bounds(self) -> Aabb =
45
+ c := self.size / 2.0
46
+ r := if self.lit then self.halo() else c
47
+ Aabb.of(c - r, c - r, 2.0 * r, 2.0 * r)
45
48
 
46
49
  fun hit(self, p: Vec2) -> Bool =
47
50
  c := self.size / 2.0
48
- self.bounds().containsPoint(p) || {self.lit && Math.hypot(p.x - c, p.y - c) <= self.halo()}
51
+ Aabb.of(0.0, 0.0, self.size, self.size).containsPoint(p) || {self.lit && Math.hypot(p.x - c, p.y - c) <= self.halo()}
49
52
 
50
53
  fun touch(self) -> Touchable = Enabled
51
54
 
examples/games/clockwork/screens/OrreryScreen.plum CHANGED
@@ -9,13 +9,14 @@ import std/Slice
9
9
  import std/collections/List
10
10
  import std/math/Vec2
11
11
  import std/math/Affine
12
+ import std/math/Dice
12
13
  import std/game/Color
13
14
  import std/game/Input
14
15
  import std/game/Body
15
16
  import std/game/View
16
17
  import std/game/Box
17
18
  import std/game/Circle
18
- import std/game/Group
19
+ import std/game/Overlay
19
20
  import std/game/Label
20
21
  import std/game/Viewport
21
22
  import std/game/Screen
@@ -57,7 +58,7 @@ struct OrreryScreen[ScreenSlice<SkyAction>](
57
58
 
58
59
  fun view(self) -> List<View> = [
59
60
  Box(w: Arena.W, h: Arena.H, color: Color.rgb(0.04, 0.05, 0.1))
60
- ..Range.until(0, 40).map(|i| Circle(x: Float({i * 7919} % 800), y: Float({i * 104729} % 600), r: 1.0 + Float(i % 3) * 0.5, color: Color(r: 0.7, g: 0.8, b: 1.0, a: 0.4)))
61
+ ..Range.until(0, 40).map(|i| OrreryScreen.star(i))
61
62
  ..self.orbits.map(|o| Circle(x: Arena.CentreX, y: Arena.CentreY, r: o.reach, color: Color.White.withAlpha(0.04)))
62
63
  ..self.orbits
63
64
  self.sun
@@ -70,8 +71,7 @@ struct OrreryScreen[ScreenSlice<SkyAction>](
70
71
  w := Sheet.MapW
71
72
  h := Sheet.MapH
72
73
  [
73
- Group(x: window.x - w - 8.0, y: window.y - h - 8.0) {
74
- Box(w: w, h: h, color: Color(r: 0.05, g: 0.1, b: 0.2, a: 0.85))
74
+ Overlay(x: window.x - w - 8.0, y: window.y - h - 8.0, w: w, h: h, color: Color(r: 0.05, g: 0.1, b: 0.2, a: 0.85)) {
75
75
  Box(w: w, h: 1.0, color: Color.White)
76
76
  Box(y: h - 1.0, w: w, h: 1.0, color: Color.White)
77
77
  Box(w: 1.0, h: h, color: Color.White)
@@ -97,6 +97,10 @@ struct OrreryScreen[ScreenSlice<SkyAction>](
97
97
  moved := self.stepped(dt)
98
98
  Next(state: OrreryScreen(..moved, walkers: OrreryScreen.crowd(moved.walkers, moved.front)))
99
99
 
100
+ fun star(i: Int) -> Circle =
101
+ p := Dice.scatter(i, 800, 600)
102
+ Circle(x: p.x, y: p.y, r: 1.0 + Float(i % 3) * 0.5, color: Color(r: 0.7, g: 0.8, b: 1.0, a: 0.4))
103
+
100
104
  fun spots(self) -> List<Spot> = self.orbits.fold(Nil, |all, o| all.append(o.spots(Affine.Identity)))
101
105
 
102
106
  fun title(self) -> Str = match self.spots().find(|s| s.spinner.lit)
examples/games/orbitrunner/OrbitRunner.plum CHANGED
@@ -21,13 +21,12 @@ import screens/PlayingScreen
21
21
  primitive Arena =
22
22
  const W = 800.0
23
23
  const H = 600.0
24
-
25
- fun inside(r: Float) -> Aabb = Aabb(min: Vec2(x: r, y: r), max: Vec2(x: Arena.W - r, y: Arena.H - r))
24
+ const Bounds = Aabb(min: Vec2(x: 0.0, y: 0.0), max: Vec2(x: 800.0, y: 600.0))
26
25
 
27
26
  fun drift(dice: Random, near: Vec2, gap: Float, speed: Float, r: Float) -> Body =
28
27
  heading := dice.floatAt(0) * Float.Tau
29
28
  pace := speed * {0.4 + 0.6 * dice.floatAt(1)}
30
- Body(pos: Arena.spot(dice, near, gap, 0), vel: Vec2(x: Math.cos(heading), y: Math.sin(heading)) * pace, edge: Bounce(box: Arena.inside(r)))
29
+ Body(pos: Arena.spot(dice, near, gap, 0), vel: Vec2(x: Math.cos(heading), y: Math.sin(heading)) * pace, edge: Bounce(box: Arena.Bounds.shrink(r)))
31
30
 
32
31
  fun spot(dice: Random, near: Vec2, gap: Float, n: Int) -> Vec2 =
33
32
  margin := 54.0
@@ -52,6 +51,5 @@ struct Assets(sheet: Texture, pickup: Sound, hit: Sound, over: Sound, music: Sou
52
51
  primitive OrbitRunner[App] =
53
52
  fun main(io: Io) -> Game =
54
53
  assets := Assets.load(io)
55
- assets.music.loop(io, Assets.MusicVolume)
56
54
  play: Screen := PlayingScreen.start(io.randomSeed(), assets)
57
- Game(screens: [play])
55
+ Game(screens: [play]).looping(io, assets.music, Assets.MusicVolume)
examples/games/orbitrunner/actors/Ship.plum CHANGED
@@ -6,6 +6,7 @@ import std/Bool
6
6
  import std/collections/List
7
7
  import std/Option
8
8
  import std/math/Vec2
9
+ import std/math/Aabb
9
10
  import std/game/Body
10
11
  import std/game/Color
11
12
  import std/game/Place
@@ -22,7 +23,7 @@ struct Ship[Actor, Round, Steps](tex: Texture, body: Body, hurtUntil: Float = 0.
22
23
  const HurtTime = 1.5
23
24
 
24
25
  fun create(tex: Texture) -> Ship =
25
- Ship(tex: tex, body: Body(pos: Vec2(x: Arena.W / 2.0, y: Arena.H / 2.0), drag: Ship.Drag, edge: Halt(box: Arena.inside(Ship.Radius)), faceAbove: Some(20.0)))
26
+ Ship(tex: tex, body: Body(pos: Vec2(x: Arena.W / 2.0, y: Arena.H / 2.0), drag: Ship.Drag, edge: Halt(box: Arena.Bounds.shrink(Ship.Radius)), faceAbove: Some(20.0)))
26
27
 
27
28
  fun place(self) -> Place = self.body.place(Sheet.Pivot)
28
29
 
examples/games/orbitrunner/actors/Star.plum CHANGED
@@ -4,6 +4,8 @@ import std/Int
4
4
  import std/Float
5
5
  import std/collections/List
6
6
  import std/math/Math
7
+ import std/math/Vec2
8
+ import std/math/Dice
7
9
  import std/game/Color
8
10
  import std/game/Place
9
11
  import std/game/View
@@ -14,7 +16,9 @@ struct Star[View](index: Int, clock: Float) =
14
16
 
15
17
  fun r(self) -> Float = 1.0 + Float(self.index % 3) * 0.5
16
18
 
19
+ fun place(self) -> Place =
17
- fun place(self) -> Place = Place.at(Float({self.index * 7919} % 800), Float({self.index * 104729} % 600))
20
+ p := Dice.scatter(self.index, 800, 600)
21
+ Place.at(p.x, p.y)
18
22
 
19
23
  fun view(self) -> List<View> = [Circle(r: self.r(), color: Color(r: 0.7, g: 0.8, b: 1.0, a: self.twinkle()))]
20
24
 
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -9,6 +9,7 @@ import std/Slice
9
9
  import std/collections/List
10
10
  import std/math/Vec2
11
11
  import std/math/Random
12
+ import std/math/Dice
12
13
  import std/math/Math
13
14
  import std/game/Color
14
15
  import std/game/Input
@@ -37,14 +38,17 @@ enum PlayAction[Show] =
37
38
  | StartOver
38
39
 
39
40
  struct PlayingScreen[ScreenSlice<PlayAction>](
40
- seed: Int, ticks: Int, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
41
+ dice: Dice, ticks: Int, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
41
42
  @stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
42
43
  const OrbCount = 3
43
44
  const StartLives = 3
45
+ const DealRoll = 0
46
+ const CatchRoll = 1
47
+ const MineRoll = 2
44
48
 
45
49
  fun start(seed: Int, assets: Assets) -> PlayingScreen =
46
50
  PlayingScreen(
47
- seed: seed, ticks: 0, assets: assets, score: 0, best: 0, lives: PlayingScreen.StartLives, over: false, clock: 0.0,
51
+ dice: Dice(seed: seed), ticks: 0, assets: assets, score: 0, best: 0, lives: PlayingScreen.StartLives, over: false, clock: 0.0,
48
52
  ship: Ship.create(assets.sheet), orbs: Nil, mines: Nil, rings: Nil).deal()
49
53
 
50
54
  fun at(seed: Int, assets: Assets, score: Int, lives: Int) -> PlayingScreen =
@@ -92,9 +96,9 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
92
96
  Next(state: moved, then: if moved.over then Nil else moved.rules())
93
97
  Caught(orb) =>
94
98
  sounds := self.assets
95
- dice := self.dice(orb)
99
+ roll := self.dice.roll(self.ticks, PlayingScreen.CatchRoll, orb)
96
100
  ship := self.ship
97
- orbs := self.orbs.map(|o| if o.id == orb then Orb.spawn(orb, dice, ship, o.tex) else o)
101
+ orbs := self.orbs.map(|o| if o.id == orb then Orb.spawn(orb, roll, ship, o.tex) else o)
98
102
  Next(state: PlayingScreen(..self, score: self.score + Orb.Points, orbs: orbs).grown(), cmds: [Play(sound: sounds.pickup, volume: 0.8)])
99
103
  Hit =>
100
104
  sounds := self.assets
@@ -119,19 +123,17 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
119
123
  if !self.ship.hurt() && self.mines.any(|m| self.ship.touches(m)) then Hit
120
124
  ]
121
125
 
122
- fun dice(self, salt: Int) -> Random = Random.at(self.seed, self.ticks, salt)
123
-
124
126
  fun deal(self) -> PlayingScreen =
125
127
  ship := Ship.create(self.assets.sheet)
126
128
  tex := self.assets.sheet
127
- seed := self.seed
129
+ dice := self.dice
128
130
  ticks := self.ticks
129
- orbs := Range.until(0, PlayingScreen.OrbCount).map(|i| Orb.spawn(i, Random.at(seed, ticks, i), ship, tex))
131
+ orbs := Range.until(0, PlayingScreen.OrbCount).map(|i| Orb.spawn(i, dice.roll(ticks, PlayingScreen.DealRoll, i), ship, tex))
130
132
  PlayingScreen(..self, clock: 0.0, ship: ship, orbs: orbs, mines: Nil, rings: Nil).grown()
131
133
 
132
134
  fun grown(self) -> PlayingScreen =
133
135
  if self.mines.length() < Mine.countFor(self.score)
134
- mine := Mine.spawn(self.dice(PlayingScreen.OrbCount + self.mines.length()), self.ship, self.assets.sheet)
136
+ mine := Mine.spawn(self.dice.roll(self.ticks, PlayingScreen.MineRoll, self.mines.length()), self.ship, self.assets.sheet)
135
137
  PlayingScreen(..self, mines: self.mines.append([mine])).grown()
136
138
  else
137
139
  self
std/Test.plum CHANGED
@@ -31,7 +31,7 @@ import std/Result
31
31
  # `unwrapOr` (`r.unwrapOr(0)`, `r!`); `expectFailureNamed` also checks which error it is
32
32
  # (the error enum provides `fun name(self) -> Str`).
33
33
  #
34
- # CAVEAT on `expectEq`/`expectNotEq`/`expectObject`/`expectArray`: `==`/`!=`
34
+ # CAVEAT on `expectEq`/`expectNotEq`/`expectArray`: `==`/`!=`
35
35
  # call the type's `eq(self, other)` method when it has one (Int/Str/Bool/Float,
36
36
  # `Slice`, `List`, `Map`, `Uuid`, `Time`, ...). A struct or enum without an
37
37
  # `eq` compares by reference identity, so `expectEq` on two
@@ -55,12 +55,6 @@ primitive Test =
55
55
  fun expectNotEq<T>(a: T, b: T) -> Bool =
56
56
  a != b
57
57
 
58
- # See the CAVEAT at the top of the file — this is `expectEq` under a name that
59
- # reads better at a class/struct call site; it does NOT do structural
60
- # (field-by-field) comparison.
61
- fun expectObject<T>(a: T, b: T) -> Bool =
62
- a == b
63
-
64
58
  # Elementwise `Slice<T>` comparison — see the CAVEAT at the top of the file for
65
59
  # what the elements' `==` means when `T` is a struct/enum.
66
60
  fun expectArray<T>(a: Slice<T>, b: Slice<T>) -> Bool =
std/game/Blend.plum CHANGED
@@ -11,7 +11,7 @@ import std/game/View
11
11
  import std/game/Touch
12
12
 
13
13
  # A view that draws its children, placed in its coordinates from (x, y), in the blend
14
- # mode `mode` and then returns the host to `Blend.Normal`; they are its block (its last
14
+ # mode `mode` and then returns the host to the mode it was in; they are its block (its last
15
15
  # field, `children`), as a `Group`'s are:
16
16
  #
17
17
  # Blend(mode: Blend.Add) {
@@ -21,9 +21,10 @@ import std/game/Touch
21
21
  #
22
22
  # The modes are its constants: `Normal` (alpha blending), `Add` (brightens), `Multiply`
23
23
  # (darkens, white leaves the target unchanged) and `Screen` (lightens), the values
24
- # `Gfx.blendMode` takes. A `Blend` under another `Blend` returns to `Normal` when it is
24
+ # `Gfx.blendMode` takes. When its children are drawn it puts back the mode it was drawn
25
+ # in: a `Blend` under another `Blend` returns to the outer one's mode (std/game/View's
25
- # done, not to the outer one's mode. Like a `Group` it is never hit itself (`touch` is
26
+ # `paint`). Like a `Group` it is never hit itself (`touch` is `ChildrenOnly` unless given;
26
- # `ChildrenOnly` unless given) and has no bounds.
27
+ # `Enabled` is the same, as it has no bounds) and has no bounds.
27
28
  struct Blend[View, Touch](x: Float = 0.0, y: Float = 0.0, mode: Int, touch: Touchable = ChildrenOnly, children: List<View>) =
28
29
  const Normal = 0
29
30
  const Add = 1
std/game/Body.plum CHANGED
@@ -10,7 +10,7 @@ import std/game/Place
10
10
 
11
11
  # What a body does at the sides of a box its position stays in: nothing (`Free`), stop
12
12
  # there (`Halt`: that axis's velocity goes), bounce back (`Bounce`: that axis's velocity
13
- # turns), or come in at the other side (`Wrap`).
13
+ # points back inside), or come in at the other side (`Wrap`).
14
14
  enum Walls =
15
15
  | Free
16
16
  | Halt(box: Aabb)
@@ -45,12 +45,9 @@ struct Body(
45
45
  hx := x.max(box.min.x).min(box.max.x)
46
46
  hy := y.max(box.min.y).min(box.max.y)
47
47
  Landing(x: hx, y: hy, vx: if hx != x then 0.0 else vx, vy: if hy != y then 0.0 else vy)
48
- Bounce(box) =>
48
+ Bounce(box) => Landing(
49
- outX := x < box.min.x || x > box.max.x
50
- outY := y < box.min.y || y > box.max.y
51
- Landing(
52
- x: if outX then x.max(box.min.x).min(box.max.x) else x, y: if outY then y.max(box.min.y).min(box.max.y) else y,
49
+ x: x.max(box.min.x).min(box.max.x), y: y.max(box.min.y).min(box.max.y),
53
- vx: if outX then 0.0 - vx else vx, vy: if outY then 0.0 - vy else vy)
50
+ vx: Body.bounced(x, vx, box.min.x, box.max.x), vy: Body.bounced(y, vy, box.min.y, box.max.y))
54
51
  Wrap(box) => Landing(x: Body.wrap(x, box.min.x, box.max.x), y: Body.wrap(y, box.min.y, box.max.y), vx: vx, vy: vy)
55
52
  fast := match self.faceAbove
56
53
  Some(s) => at.vx * at.vx + at.vy * at.vy > s * s
@@ -64,10 +61,22 @@ struct Body(
64
61
  fun place(self, origin: Vec2) -> Place =
65
62
  Place(..Place.pivoted(self.pos.x - origin.x, self.pos.y - origin.y, origin.x, origin.y), rotation: self.angle)
66
63
 
64
+ # The velocity `v` along an axis after a bounce at `p`: away from the side `p` is past
65
+ # (`lo` or `hi`), as it is inside.
66
+ fun bounced(p: Float, v: Float, lo: Float, hi: Float) -> Float =
67
+ if p < lo then v.abs() else if p > hi then 0.0 - v.abs() else v
68
+
67
- # `v` brought into `[lo, hi)` by whole spans.
69
+ # `v` brought into `[lo, hi)` by whole spans; `lo` when the span is empty (or not a
70
+ # number), or when rounding would leave it at `hi`.
68
71
  fun wrap(v: Float, lo: Float, hi: Float) -> Float =
69
72
  span := hi - lo
73
+ if v >= lo && v < hi
74
+ v
75
+ else if !{span > 0.0}
76
+ lo
77
+ else
78
+ w := v - span * {{v - lo} / span}.floor()
70
- if v >= lo && v < hi then v else v - span * {{v - lo} / span}.floor()
79
+ if w >= lo && w < hi then w else lo
71
80
 
72
81
  # Where a body's step leaves it: at (x, y), moving at (vx, vy).
73
82
  struct Landing(x: Float, y: Float, vx: Float, vy: Float)
std/game/Button.plum CHANGED
@@ -28,10 +28,13 @@ trait Presses<A> =
28
28
  # }
29
29
  #
30
30
  # It is hit inside its box, edges included, unless a child under the press takes it
31
- # (a child is decoration unless it takes presses itself).
31
+ # (a child is decoration unless it takes presses itself). It is an `Actor` whose step
32
+ # steps the actors among its children (`Views.stepIn`), as a `Group`'s are stepped.
32
- struct Button<A>[View, Sized, Touch, Presses<A>](x: Float = 0.0, y: Float = 0.0, w: Float, h: Float, on: A, children: List<View> = Nil) =
33
+ struct Button<A>[Actor, Sized, Touch, Presses<A>](x: Float = 0.0, y: Float = 0.0, w: Float, h: Float, on: A, children: List<View> = Nil) =
33
34
  fun place(self) -> Place = Place.at(self.x, self.y)
34
35
 
36
+ fun step(self, dt: Float) -> Button<A> = Button(..self, children: Views.stepIn(self.children, dt))
37
+
35
38
  fun view(self) -> List<View> = self.children
36
39
 
37
40
  fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, self.w, self.h)
std/game/Game.plum CHANGED
@@ -20,6 +20,7 @@ import std/game/View
20
20
  import std/game/ScreenSlice
21
21
  import std/game/Viewport
22
22
  import std/game/Cmd
23
+ import std/game/Audio
23
24
  import std/game/Screen
24
25
  import std/game/History
25
26
  import std/game/Replay
@@ -84,14 +85,27 @@ import std/game/Replay
84
85
  # forward again along what it undid: `rewindTo(io, tick)`, `undo(io)`, `redo(io)`,
85
86
  # `stepBack(io)`, `stepForward(io)`, with `canUndo()`, `canRedo()`, `tickNow()` and
86
87
  # `ticksRecorded()`; each move returns the game moved, `moved` saying whether it could.
87
- # Going back makes the game again from `initial` and plays the recorded ticks into it,
88
+ # Going back makes the game again from the latest snapshot at or before the tick it goes
89
+ # to (`snaps`, one every `snapEvery` ticks of the history, `Game.SnapEvery` (600) unless
90
+ # set; at most `cap / snapEvery` of them), or from `initial` when there is none, and plays
91
+ # the recorded ticks after it into it, through the same tick as ever (`run`), which gives
92
+ # the same commands: a game is a value, so the snapshot is the game as it was, and going
88
- # through the same tick as ever (`run`), which gives the same commands: of those only a
93
+ # back by one gives the game a rewind from the start gives. Of those commands only a
94
+ # `GoTo`, and what a `Loop` or a `Stop` does to the sounds looping (`loops`), are done
89
- # `GoTo` is done again, so no sound plays and no `Exit` or rewind is done twice. `pause()` holds
95
+ # again, so no sound plays and no `Exit` or rewind is done twice; once moved, the host's
96
+ # loops are set to the game's (`resound`: a sound stopped since starts again, one started
97
+ # since stops). A dispatched action (std/game/TestRig's `dispatch`) is in the history as
98
+ # an entry of its own (`dispatched`), done again as it was. The first tick after a move
99
+ # compares what is held with what was held at the last tick played live (`liveHeld`), not
100
+ # at the tick it went back to, so keys held through an undo are no new user action. `pause()` holds
90
101
  # the game still until `resume()`, which drops what could be redone. `rewound` is how many
91
102
  # ticks the last move played. A development run (`plum run --dev`) does this from the
92
103
  # first frame and moves with the time travel keys (`devFrame`, std/game/History's
93
104
  # `TravelKeys`), showing where it is along the bottom of the window (`devLine`).
94
105
  struct Game(screens: List<Screen>) =
106
+ # Ticks between two snapshots of the history (10 s).
107
+ const SnapEvery = 600
108
+
95
109
  fun init(self) =
96
110
  self.initial: List<Screen> = self.screens
97
111
  self.current: Int = 0
@@ -122,6 +136,13 @@ struct Game(screens: List<Screen>) =
122
136
  self.rewound: Int = 0
123
137
  self.moved: Bool = false
124
138
  self.dev: Bool = false
139
+ # What was held at the last tick played live, the sounds looping now and at the start
140
+ # (`looping`), the snapshots of the history (the newest first) and how many ticks apart.
141
+ self.liveHeld: Held = Held()
142
+ self.loops: List<Looping> = Nil
143
+ self.startLoops: List<Looping> = Nil
144
+ self.snaps: List<Snap> = Nil
145
+ self.snapEvery: Int = Game.SnapEvery
125
146
  if self.screens.isEmpty()
126
147
  crash "game: a game needs a screen"
127
148
  if Some(dup) := Game.duplicateName(self.screens, Nil)
@@ -167,10 +188,43 @@ struct Game(screens: List<Screen>) =
167
188
  self
168
189
  else
169
190
  ran := self.run(io, input, dt, pixels, false)
170
- noted := match ran.history
191
+ user := ran.acted && ran.travel.isEmpty()
171
- Some(h) => Game(..ran, history: Some(h.push(HistoryTick(input: input, pixels: pixels, dt: dt, user: ran.acted && ran.travel.isEmpty()))))
192
+ Game(..ran, liveHeld: input.held).noted(HistoryTick(input: input, pixels: pixels, dt: dt, user: user)).travelAsked(io)
193
+
194
+ # `f`, an action stepped into the shown screen outside a tick (std/game/TestRig's
195
+ # `dispatch`), done as a tick's are: the screen it gives kept, its commands done, then
196
+ # the undo, redo or rewind they asked for. With a history it is an entry of its own, a
197
+ # user action unless it asked for a move, which a move through the history does again.
198
+ fun dispatched(self, io: Io, f: fn(Screen) -> Delivered) -> Game =
199
+ ran := self.applied(io, f, false)
200
+ ran.noted(HistoryTick(input: Input(), pixels: ran.pixels, dt: 0.0, user: ran.travel.isEmpty(), apply: Some(Dispatch(deliver: f)))).travelAsked(io)
201
+
202
+ # The game with the delivery `f` gives of the shown screen: its screen, its commands done
203
+ # (only its `GoTo`s and loops when `replayed`), woken for its next tick.
204
+ fun applied(self, io: Io, f: fn(Screen) -> Delivered, replayed: Bool) -> Game =
205
+ d := f(self.screen())
206
+ g := Game(..self, screens: Game.setAt(self.screens, self.current, d.screen), wake: true, dirty: true, sent: d.sent, cmds: d.cmds, acted: true)
207
+ if replayed then g.redone(d.cmds) else g.obeyAll(io, d.cmds)
208
+
209
+ # With `r` added to its history, and the snapshot taken that is due after it; a full
210
+ # history keeps none. As it is with no history.
211
+ fun noted(self, r: HistoryTick) -> Game = match self.history
212
+ Some(h) =>
213
+ pushed := h.push(r)
214
+ if pushed.full then Game(..self, history: Some(pushed), snaps: Nil) else Game(..self, history: Some(pushed)).snapped(pushed.count)
172
- None => ran
215
+ None => self
216
+
217
+ # With a snapshot of itself as the history's tick `at`, when snapshots are taken
218
+ # (`snapEvery` above 0), `at` is one of theirs and there is none of it yet.
219
+ fun snapped(self, at: Int) -> Game =
220
+ if self.snapEvery > 0 && at > 0 && at % self.snapEvery == 0 && !self.snaps.any(|s| s.tick == at)
221
+ Game(..self, snaps: Cons(Snap(tick: at, game: self.bare()), self.snaps))
222
+ else
223
+ self
224
+
225
+ # The game as a snapshot keeps it: no history, nothing asked or given by its last tick,
173
- noted.travelAsked(io)
226
+ # not exited (a rewind never does an `Exit` again).
227
+ fun bare(self) -> Game = Game(..self, history: None, snaps: Nil, travel: Nil, sent: Nil, cmds: Nil, exited: false, rewound: 0, moved: false)
174
228
 
175
229
  # The game after the undos, redos and rewinds the tick's commands asked for, in order
176
230
  # (`obey` keeps them for the end of the tick), which it then forgets: what ends a tick,
@@ -214,23 +268,41 @@ struct Game(screens: List<Screen>) =
214
268
  Cons(c, rest) => self.obey(io, c).obeyAll(io, rest)
215
269
 
216
270
  # Does a command of the tick (std/game/Cmd); an undo, a redo or a rewind waits for the
217
- # end of the tick (`step`).
271
+ # end of the tick (`step`). A `Loop` or a `Stop` is kept in `loops` too.
218
- fun obey(self, io: Io, c: Cmd) -> Game = match c
272
+ fun obey(self, io: Io, c: Cmd) -> Game =
219
- GoTo(name) => self.goTo(name)
273
+ if c.travels()
220
- Exit => Game(..self, exited: true)
221
- Undo => Game(..self, travel: self.travel.append([c]))
274
+ Game(..self, travel: self.travel.append([c]))
222
- Redo => Game(..self, travel: self.travel.append([c]))
223
- RewindTo(_) => Game(..self, travel: self.travel.append([c]))
224
- _ =>
275
+ else
225
276
  c.sound(io)
277
+ match c
278
+ GoTo(name) => self.goTo(name)
279
+ Exit => Game(..self, exited: true)
280
+ Loop(_, _) => Game(..self, loops: Looping.after(self.loops, c))
281
+ Stop(_) => Game(..self, loops: Looping.after(self.loops, c))
226
- self
282
+ _ => self
227
283
 
228
284
  # The commands of a tick played again by a rewind: its `GoTo`s are done again, in order,
229
- # and nothing else (no sound, no exit, no move through the history).
285
+ # and its `Loop`s and `Stop`s kept in `loops`, and nothing else (no sound, no exit, no
286
+ # move through the history).
230
287
  fun redone(self, cmds: List<Cmd>) -> Game = cmds.fold(self, |g, c| match c
231
288
  GoTo(name) => g.goTo(name)
289
+ Loop(_, _) => Game(..g, loops: Looping.after(g.loops, c))
290
+ Stop(_) => Game(..g, loops: Looping.after(g.loops, c))
232
291
  _ => g)
233
292
 
293
+ # The game with `s` looping at `volume` from its start, as a `Loop` command starts it, so
294
+ # that a move through its history knows it loops (`loops`): what `main` calls in place of
295
+ # `s.loop(io, volume)`.
296
+ fun looping(self, io: Io, s: Sound, volume: Float) -> Game =
297
+ s.loop(io, volume)
298
+ Game(..self, loops: Looping.after(self.loops, Loop(sound: s, volume: volume)), startLoops: Looping.after(self.startLoops, Loop(sound: s, volume: volume)))
299
+
300
+ # The game after a move, the host's loops changed from those of `before` to its own
301
+ # (`Looping.changes`).
302
+ fun resound(self, io: Io, before: List<Looping>) -> Game =
303
+ Looping.changes(before, self.loops).each(|c| c.sound(io))
304
+ self
305
+
234
306
  # Shows the screen named `name` from the next tick on, as it was left, coming in by its
235
307
  # `transition`. The screen shown already stays as it is.
236
308
  fun goTo(self, name: Str) -> Game =
@@ -358,12 +430,12 @@ struct Game(screens: List<Screen>) =
358
430
  else if tick == now
359
431
  Game(..self, rewound: 0, moved: true)
360
432
  else if tick < now
361
- self.remake(io, h.backTo(tick))
433
+ self.remake(io, h.backTo(tick), tick).resound(io, self.loops)
362
434
  else if h.fork != now || tick > now + h.future.length()
363
435
  Game(..self, moved: false)
364
436
  else
365
437
  f := h.forward(tick - now)
366
- Game(..self, history: Some(f.history)).playOn(io, f.taken)
438
+ Game(..self, history: Some(f.history)).playOn(io, f.taken, now).resound(io, self.loops)
367
439
 
368
440
  # Back to just before the last user action (std/game/History).
369
441
  fun undo(self, io: Io) -> Game = match self.history
@@ -378,7 +450,8 @@ struct Game(screens: List<Screen>) =
378
450
  Game(..self, moved: false)
379
451
  else
380
452
  f := h.forward(h.nextUser())
381
- if h.fork == h.now() then Game(..self, history: Some(f.history)).playOn(io, f.taken) else self.remake(io, f.history)
453
+ moved := if h.fork == h.now() then Game(..self, history: Some(f.history)).playOn(io, f.taken, h.now()) else self.remake(io, f.history, h.fork)
454
+ moved.resound(io, self.loops)
382
455
  None => Game(..self, moved: false)
383
456
 
384
457
  fun stepBack(self, io: Io) -> Game = if self.tickNow() > 0 then self.rewindTo(io, self.tickNow() - 1) else Game(..self, moved: false)
@@ -420,17 +493,35 @@ struct Game(screens: List<Screen>) =
420
493
  line := "tick {self.tickNow()} of {self.ticksRecorded()}"
421
494
  if self.paused then "{line} (paused)" else line
422
495
 
423
- # The game made again from its start, with the history `h`, and its ticks played into it;
496
+ # The game made again, with the history `h`, from its latest snapshot of a tick at or
497
+ # before `valid` (the timeline is unchanged up to there) and `h`'s, or else from its start,
424
- # held still or a development run's as it was.
498
+ # and the ticks of `h` after it played into it; held still or a development run's as it
499
+ # was.
425
- fun remake(self, io: Io, h: History) -> Game =
500
+ fun remake(self, io: Io, h: History, valid: Int) -> Game =
501
+ snaps := Snap.upTo(self.snaps, valid.min(h.count))
502
+ match snaps
503
+ Cons(s, _) =>
504
+ Game(..s.game, history: Some(h), snaps: snaps, paused: self.paused, dev: self.dev, liveHeld: self.liveHeld)
505
+ .playOn(io, History.dropN(h.played(), s.tick), s.tick)
506
+ Nil =>
426
- fresh := Game(screens: self.initial)
507
+ fresh := Game(screens: self.initial)
427
- sized := if h.pixels.x > 0.0 && h.pixels.y > 0.0 then fresh.resized(h.pixels) else fresh
508
+ sized := if h.pixels.x > 0.0 && h.pixels.y > 0.0 then fresh.resized(h.pixels) else fresh
509
+ Game(
428
- Game(..sized, history: Some(h), paused: self.paused, dev: self.dev).playOn(io, h.played())
510
+ ..sized, history: Some(h), paused: self.paused, dev: self.dev, liveHeld: self.liveHeld, loops: self.startLoops,
429
-
511
+ startLoops: self.startLoops, snapEvery: self.snapEvery).playOn(io, h.played(), 0)
512
+
430
- # `recs` played again from the state the game is in, doing only their `GoTo`s.
513
+ # `recs` played again from the state the game is in, the first of them the history's tick
514
+ # `from` + 1, doing only their `GoTo`s and loops, and taking the snapshots due on the way;
515
+ # then the screen shown takes what was held at the last tick played live as what was held
516
+ # at its tick before.
431
- fun playOn(self, io: Io, recs: List<HistoryTick>) -> Game =
517
+ fun playOn(self, io: Io, recs: List<HistoryTick>, from: Int) -> Game =
518
+ played := recs.fold(Played(game: self, at: from), |p, r| Played(game: p.game.playedAgain(io, r).snapped(p.at + 1), at: p.at + 1)).game
519
+ Game(..played, helds: Game.setAt(played.helds, played.current, self.liveHeld), rewound: recs.length(), sent: Nil, cmds: Nil, dirty: true, moved: true)
520
+
521
+ # The entry `r` of the history played again: its tick, or the action it dispatched.
522
+ fun playedAgain(self, io: Io, r: HistoryTick) -> Game = match r.apply
523
+ Some(d) => self.applied(io, d.deliver, true)
432
- played := recs.fold(self, |g, r| g.run(io, r.input, r.dt, r.pixels, true))
524
+ None => self.run(io, r.input, r.dt, r.pixels, true)
433
- Game(..played, rewound: recs.length(), sent: Nil, cmds: Nil, dirty: true, moved: true)
434
525
 
435
526
  # The camera the screen `s` is seen through in a window of `pixels` (0 by 0 while the
436
527
  # game doesn't know it): its world (`size()`) put on the window by its `viewport()`, or,
@@ -483,6 +574,53 @@ struct Game(screens: List<Screen>) =
483
574
  fun lastPointer(input: Input, pointer: Vec2) -> Vec2 =
484
575
  input.events.fold(pointer, |p, e| e.position().unwrapOr(p))
485
576
 
577
+ # A snapshot of a game (`Game.snaps`): the game after `tick` ticks of its history.
578
+ struct Snap(tick: Int, game: Game) =
579
+ # The snapshots of `snaps` (the newest first) of a tick at or before `tick`.
580
+ fun upTo(snaps: List<Snap>, tick: Int) -> List<Snap> = match snaps
581
+ Nil => Nil
582
+ Cons(s, rest) => if s.tick <= tick then snaps else Snap.upTo(rest, tick)
583
+
584
+ # A replay of a game's history so far: the game, and the tick of the history it is at.
585
+ struct Played(game: Game, at: Int)
586
+
587
+ # A sound looping at a volume (`Game.loops`).
588
+ struct Looping(sound: Sound, volume: Float) =
589
+ # `loops` after the command `c`: a `Loop` of a sound keeps it (once, at its volume), a
590
+ # `Stop` drops it; any other leaves them.
591
+ fun after(loops: List<Looping>, c: Cmd) -> List<Looping> = match c
592
+ Loop(s, v) => Looping.without(loops, s.id).append([Looping(sound: s, volume: v)])
593
+ Stop(s) => Looping.without(loops, s.id)
594
+ _ => loops
595
+
596
+ # `loops` but the sound `id`'s. These are walks of their own, not `filter`s: a `filter`
597
+ # of a `Looping` list here costs Orbit Runner's `PlayingScreen.update` four of its five
598
+ # in-place spreads (compiler/cli/tests/cli/game_in_place_test.rs).
599
+ fun without(loops: List<Looping>, id: Int) -> List<Looping> = match loops
600
+ Nil => Nil
601
+ Cons(l, rest) => if l.sound.id == id then Looping.without(rest, id) else Cons(l, Looping.without(rest, id))
602
+
603
+ # The commands that take the host from `before` looping to `after`: a `Stop` for each
604
+ # sound that no longer loops, then a `Stop` and a `Loop` for each that loops anew or at
605
+ # another volume.
606
+ fun changes(before: List<Looping>, after: List<Looping>) -> List<Cmd> = Looping.stopsOf(before, after).append(Looping.startsOf(after, before))
607
+
608
+ # A `Stop` for each of `before` that `after` doesn't loop.
609
+ fun stopsOf(before: List<Looping>, after: List<Looping>) -> List<Cmd> = match before
610
+ Nil => Nil
611
+ Cons(b, rest) => if Looping.holds(after, b, false) then Looping.stopsOf(rest, after) else Cons(Stop(sound: b.sound), Looping.stopsOf(rest, after))
612
+
613
+ # A `Stop` and a `Loop` for each of `after` that `before` doesn't loop at its volume.
614
+ fun startsOf(after: List<Looping>, before: List<Looping>) -> List<Cmd> = match after
615
+ Nil => Nil
616
+ Cons(a, rest) =>
617
+ if Looping.holds(before, a, true) then Looping.startsOf(rest, before) else Cons(Stop(sound: a.sound), Cons(Loop(sound: a.sound, volume: a.volume), Looping.startsOf(rest, before)))
618
+
619
+ # Whether `loops` loops `l`'s sound (at its volume when `sameVolume`).
620
+ fun holds(loops: List<Looping>, l: Looping, sameVolume: Bool) -> Bool = match loops
621
+ Nil => false
622
+ Cons(x, rest) => {x.sound.id == l.sound.id && {!sameVolume || x.volume == l.volume}} || Looping.holds(rest, l, sameVolume)
623
+
486
624
  # A game's ticker: its clock and input between frames: the input not yet given to a tick
487
625
  # (`pending`), the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in
488
626
  # all (`ticks`). The host's frame (`GameRun.frame`) calls `frame` once, then
@@ -493,7 +631,8 @@ struct Game(screens: List<Screen>) =
493
631
  # carries the window's size (`Input.screen`), read once a frame.
494
632
  #
495
633
  # Record and replay (std/game/Replay): `frame` asks the host each frame. Recording, it
496
- # hands the host the inputs of the ticks the frame runs. Replaying (`mode`), the ticks
634
+ # hands the host the inputs of the ticks the frame runs, each tick's window size written
635
+ # when it differs from the last one written (`written`). Replaying (`mode`), the ticks
497
636
  # take their input from `played` (those not yet replayed, the head dropped each tick), on
498
637
  # the recorded window, the host's input is never read, and no tick runs once the replay
499
638
  # is over.
@@ -503,7 +642,7 @@ struct Game(screens: List<Screen>) =
503
642
  # and leaves their commands in `travel` for the game (`Game.devFrame`).
504
643
  struct Ticker(
505
644
  pending: Input = Input(), acc: Float = 0.0, n: Int = 0, ticks: Int = 0, mode: Int = ReplayMode.Off, played: List<Input> = Nil,
506
- keys: TravelKeys = TravelKeys(), travel: List<TravelCmd> = Nil) =
645
+ keys: TravelKeys = TravelKeys(), travel: List<TravelCmd> = Nil, written: Vec2 = Vec2(x: 0.0, y: 0.0)) =
507
646
  # The tick length in seconds (1/60), the most ticks one frame runs (a longer stall drops
508
647
  # the rest, so the game slows down instead of falling further behind), and how much
509
648
  # short of a whole tick still counts as one (frame times jitter around 1/60).
@@ -528,11 +667,14 @@ struct Ticker(
528
667
  else
529
668
  c := self.accept(self.pending.poll(io), dt)
530
669
  if mode == ReplayMode.Recording
670
+ w := Replay.written(c.dueInputs(), c.written)
531
- Replay.replayAppend(io, Replay.ticksText(c.dueInputs()))
671
+ Replay.replayAppend(io, w.text())
672
+ Ticker(..c, written: w.size)
673
+ else
532
- c
674
+ c
533
675
 
534
- # The ticker replaying the host's replay: this one once it is loaded. A replay with no
676
+ # The ticker replaying the host's replay: this one once it is loaded. The ticks of a
535
- # window size plays on the host's.
677
+ # replay with no window size, up to its first size, play on the host's.
536
678
  fun loaded(self, io: Io) -> Ticker =
537
679
  if self.mode == ReplayMode.Replaying
538
680
  self
std/game/Gfx.plum CHANGED
@@ -9,12 +9,17 @@ import std/Io
9
9
 
10
10
  # Drawing, textures and files: the game host's graphics API (`plum run`), as statics of
11
11
  # `Gfx` that take the `Io` capability first: `Gfx.clear(io, Color.Black)`,
12
- # `Texture.load(io, "sprites.png")`. A game is any type that `main(io: Io)` returns and
12
+ # `Texture.load(io, "sprites.png")`. A game (std/game/Game) draws its screens' views
13
+ # (std/game/View), which call these through the transform each item is drawn with, in the
13
- # that has `update(self, io: Io, input: Input, dt: Float) -> Self` and `draw(self, io: Io)`;
14
+ # window's pixels; a kind of view of your own calls them in its `paintSelf`. Input is
14
- # `update` runs once per fixed 1/60 s tick (see `Ticker` in std/game/Game), `draw` once
15
+ # std/game/Input, sound std/game/Audio. This file also holds the `Texture` handle; the
15
- # per frame, and the state `update` returns is the next tick's `self`. Input is `std/game/Input`, sound is `std/game/Audio`. This file also
16
- # holds the `Texture` handle; the blend modes are `Blend`'s constants (std/game/Blend). A path that escapes the asset root
16
+ # blend modes are `Blend`'s constants (std/game/Blend). A path that escapes the asset
17
+ # root fails like a missing file.
18
+ #
19
+ # The engine never sets the host's camera, and its clock is its ticks (std/game/Game's
17
- # fails like a missing file. Coordinates are world units once `Gfx.setCamera` is set.
20
+ # `Ticker`): `setCamera` and `resetCamera` (world units on the host's own camera until
21
+ # reset) and `frameTime` (the host's last frame, in seconds) are the host's, for a program
22
+ # that draws with `Gfx` alone (the hosts' test fixtures do).
18
23
  #
19
24
  # Texture handles are -1 on failure. File and texture paths are relative to the asset
20
25
  # root. `Int` in an extern signature is narrowed to i32 at the host boundary.
std/game/Group.plum CHANGED
@@ -18,7 +18,9 @@ import std/game/Touch
18
18
  #
19
19
  # Its `touch` (std/game/Touch) is `ChildrenOnly` unless given: its children may be hit, it
20
20
  # is not; `touch: Disabled` takes everything under it out of hit testing (a layer of
21
- # decoration the pointer should pass through).
21
+ # decoration the pointer should pass through). `Enabled` is the same as `ChildrenOnly`: a
22
+ # group has no bounds to be hit in. A panel that takes the presses on it, so that none
23
+ # reaches what is under it, is an `Overlay` (std/game/Overlay), which has a size.
22
24
  struct Group[View, Touch](x: Float = 0.0, y: Float = 0.0, touch: Touchable = ChildrenOnly, children: List<View>) =
23
25
  fun place(self) -> Place = Place.at(self.x, self.y)
24
26
 
std/game/History.plum CHANGED
@@ -3,21 +3,27 @@ module std
3
3
  import std/Int
4
4
  import std/Float
5
5
  import std/Bool
6
+ import std/Option
6
7
  import std/collections/List
7
8
  import std/Io
8
9
  import std/math/Vec2
9
10
  import std/game/Input
11
+ import std/game/Screen
10
12
 
11
13
  # A game's own history, for undo and time travel (docs/game.md, "Undo and time travel").
12
14
  #
13
15
  # A game is a value, so an old game could be kept as it is; but a game of a long run kept
14
- # at every tick would keep every state. What is kept instead is what entered the game: the
16
+ # at every tick would keep every state. What is kept instead is what entered the game,
15
- # game goes back by being made again from the screens it was made with (`Game.initial`)
16
- # and having the recorded ticks played into it. So a history is one `HistoryTick` per
17
- # tick: its `Input`, the screen's size, its length and whether it was a user action. A
18
- # tick played again gives the same commands (std/game/Cmd), of which the game does only
17
+ # and a snapshot of the game every so many ticks (std/game/Game's `snaps`): the game goes
18
+ # back by starting again from the latest snapshot before where it goes (or the screens it
19
+ # was made with, `Game.initial`) and having the recorded ticks after it played into it. So
20
+ # a history is one `HistoryTick` per tick: its `Input`, the screen's size, its length and
21
+ # whether it was a user action. A tick played again gives the same commands
22
+ # (std/game/Cmd), of which the game does only the `GoTo`s again (and keeps what the loops
19
- # the `GoTo`s again. It records input, not actions: an action may hold an actor of the
23
+ # do). It records input, not actions: an action may hold an actor of the view, which the
24
+ # input mapped again makes anew. An action dispatched outside a tick (std/game/TestRig's
25
+ # `dispatch`) is the one entry that is not a tick: it holds the delivery to do again
20
- # view, which the input mapped again makes anew.
26
+ # (`apply`), its input empty and its length 0.
21
27
  #
22
28
  # The timeline is `ticks` (the newest first, `count` of them), the ticks played to reach
23
29
  # the state now. Going back moves the ticks after the point gone to into `future`, which
@@ -33,7 +39,11 @@ import std/game/Input
33
39
  #
34
40
  # `cap` bounds it: once the timeline would hold `cap` ticks the history is full, lets its
35
41
  # ticks go, and every rewind, undo and step is refused from then on (the game plays on).
36
- struct HistoryTick(input: Input, pixels: Vec2, dt: Float, user: Bool)
42
+ struct HistoryTick(input: Input, pixels: Vec2, dt: Float, user: Bool, apply: Option<Dispatch> = None)
43
+
44
+ # An action dispatched outside a tick, kept in a history: the delivery it gives of the
45
+ # screen shown.
46
+ struct Dispatch(deliver: fn(Screen) -> Delivered)
37
47
 
38
48
  struct History(cap: Int, pixels: Vec2, ticks: List<HistoryTick>, count: Int, future: List<HistoryTick>, fork: Int, full: Bool, over: Int) =
39
49
  # 30 minutes of ticks.
std/game/Input.plum CHANGED
@@ -200,6 +200,16 @@ enum InputEvent =
200
200
  PointerMove(_, _) => true
201
201
  _ => false
202
202
 
203
+ # The mouse button of a `ButtonDown`, -1 for any other event.
204
+ fun buttonDown(self) -> Int = match self
205
+ ButtonDown(b, _, _) => b
206
+ _ => -1
207
+
208
+ # The mouse button of a `ButtonUp`, -1 for any other event.
209
+ fun buttonUp(self) -> Int = match self
210
+ ButtonUp(b, _, _) => b
211
+ _ => -1
212
+
203
213
  fun isPointer(self) -> Bool =
204
214
  self.position().isSome()
205
215
 
@@ -221,6 +231,9 @@ struct Held(mouse: Bool = false, keys: List<Int> = Nil, buttons: List<Int> = Nil
221
231
  # Whether the key `key` (a `Key` code) is down.
222
232
  fun isKeyDown(self, key: Int) -> Bool = self.keys.any(|k| k == key)
223
233
 
234
+ # Whether anything is held: a mouse button, a touch or a key.
235
+ fun any(self) -> Bool = self.mouse || !self.keys.isEmpty() || !self.buttons.isEmpty()
236
+
224
237
  # -1, 0 or 1: the key `high` held against the key `low`, 0 when both or neither are.
225
238
  # `held.axis(Key.Left, Key.Right)` is the horizontal steering of a ship.
226
239
  fun axis(self, low: Int, high: Int) -> Float =
std/game/Line.plum CHANGED
@@ -15,13 +15,14 @@ import std/game/View
15
15
  import std/game/Sized
16
16
  import std/game/Touch
17
17
 
18
- # A straight line from `from` to `to`, in its holder's coordinates, `width` wide (scaled
18
+ # A straight line from `from` to `to`, in its coordinates, which start at (x, y) (the
19
- # as its place is) in `color` (painted at its alpha). Its bounds are the box around the
19
+ # origin unless given), `width` wide in `color` (painted at its alpha). The width is
20
- # segment, widened by half its width. It is decoration unless `touch: Enabled`
20
+ # scaled as its transform stretches across the line (a turn and an even scale scale it
21
- # (std/game/Touch), and then hit within half its width of the segment (at least half a
21
+ # by that scale). Its bounds are the box around the segment, widened by half its width.
22
+ # It is decoration unless `touch: Enabled` (std/game/Touch), and then hit within half its
22
- # unit), not its whole box.
23
+ # width of the segment (at least half a unit), not its whole box.
23
- struct Line[View, Sized, Touch](from: Vec2, to: Vec2, width: Float = 1.0, color: Color = Color.White, touch: Touchable = Disabled) =
24
+ struct Line[View, Sized, Touch](x: Float = 0.0, y: Float = 0.0, from: Vec2, to: Vec2, width: Float = 1.0, color: Color = Color.White, touch: Touchable = Disabled) =
24
- fun place(self) -> Place = Place.at(0.0, 0.0)
25
+ fun place(self) -> Place = Place.at(self.x, self.y)
25
26
 
26
27
  fun bounds(self) -> Aabb =
27
28
  h := self.width / 2.0
@@ -46,8 +47,26 @@ struct Line[View, Sized, Touch](from: Vec2, to: Vec2, width: Float = 1.0, color:
46
47
  Math.hypot(p.x - {a.x + dx * tc}, p.y - {a.y + dy * tc}) <= width.max(1.0) / 2.0
47
48
 
48
49
  # Draws the line from `a` to `b` seen through the transform `m`, `width` wide as `m`
49
- # scales it. Paints with `alpha` in place of the colour's alpha, as `Box.draw` does.
50
+ # stretches it across the line (`across`). Paints with `alpha` in place of the colour's
51
+ # alpha, as `Box.draw` does.
50
52
  fun draw(io: Io, m: Affine, alpha: Float, a: Vec2, b: Vec2, width: Float, color: Color) =
51
53
  p := m.apply(a)
52
54
  q := m.apply(b)
53
- Gfx.drawLine(io, p.x, p.y, q.x, q.y, width * m.scaleX(), color.withAlpha(alpha))
55
+ Gfx.drawLine(io, p.x, p.y, q.x, q.y, width * Line.across(m, a, b), color.withAlpha(alpha))
56
+
57
+ # How much `m` stretches a length across the segment from `a` to `b`: its scale when it
58
+ # only turns and scales evenly (`m.scaleX()`), else its stretch of the segment's normal,
59
+ # or, for a segment of no length, the square root of its area scale.
60
+ fun across(m: Affine, a: Vec2, b: Vec2) -> Float =
61
+ if m.a == m.d && m.b == 0.0 - m.c
62
+ m.scaleX()
63
+ else
64
+ dx := b.x - a.x
65
+ dy := b.y - a.y
66
+ len := Math.hypot(dx, dy)
67
+ if len == 0.0
68
+ Math.sqrt({m.a * m.d - m.b * m.c}.abs())
69
+ else
70
+ nx := 0.0 - dy / len
71
+ ny := dx / len
72
+ Math.hypot(m.a * nx + m.c * ny, m.b * nx + m.d * ny)
std/game/Place.plum CHANGED
@@ -1,6 +1,7 @@
1
1
  module std
2
2
 
3
3
  import std/Float
4
+ import std/Option
4
5
  import std/math/Math
5
6
  import std/math/Vec2
6
7
  import std/math/Affine
@@ -76,5 +77,6 @@ struct Place(
76
77
  # whatever its rotation and scale (`Place.pivoted(x, y, ox, oy)`'s is (x + ox, y + oy)).
77
78
  fun pivot(self) -> Vec2 = Vec2(x: self.x + self.originX, y: self.y + self.originY)
78
79
 
79
- # A point of the parent's coordinates in its own.
80
+ # A point of the parent's coordinates in its own, or None when the place is flat (a
81
+ # scale of 0 on an axis): nothing of the parent maps back into it.
80
- fun toLocal(self, p: Vec2) -> Vec2 = self.local().inverse().apply(p)
82
+ fun toLocal(self, p: Vec2) -> Option<Vec2> = self.local().invert().map(|m| m.apply(p))
std/game/Replay.plum CHANGED
@@ -25,19 +25,23 @@ import std/game/Input
25
25
  # The text form, one line each:
26
26
  #
27
27
  # plum-replay <seed, high 32 bits> <seed, low 32 bits> <screen width> <screen height>
28
- # <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> <events>
28
+ # <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> [S<w>,<h>] <events>
29
29
  #
30
30
  # with one tick line per tick, its events and what is held after them (`Input.held`:
31
- # a fold of the events, kept on each line so that a replay does not depend on the fold);
31
+ # a fold of the events, kept on each line so that a replay does not depend on the fold).
32
- # every tick's `Input.screen` is the header's size (a tick line holds none). The mouse
32
+ # A tick's `Input.screen` is the header's size until a tick line says another with an
33
+ # `S<w>,<h>` token after the pointer (the window resized): that size is the tick's and the
34
+ # next ones' until another `S`. A recording writes the token on a tick whose window
35
+ # differs from the last one written (`written`). The mouse
33
36
  # buttons held are a sum: 1 for the left, 2 for the right, 4 for the middle. An event is
34
37
  # `K<key>` (KeyDown), `k<key>` (KeyUp), `D<x>,<y>` (PointerDown), `U<x>,<y>` (PointerUp),
35
38
  # `M<x>,<y>` (PointerMove), `B<button>,<x>,<y>` (ButtonDown), `b<button>,<x>,<y>`
36
39
  # (ButtonUp) or `W<dy>` (Wheel). Floats are written exactly, as `m` or `m:e` for the
37
40
  # integer m times 2^e, or as `-0`, `inf`, `-inf` or `nan` (`toStr` rounds to six digits).
38
- # The screen size is the host's at the start of the recording, and the replaying host
41
+ # The header's size is the host's at the start of the recording, and the replaying host
39
- # reports it to the game; 0 means not recorded. There is one form and no version: a
42
+ # reports it to the game; 0 means not recorded (the ticks before the first `S` then play
43
+ # on the replaying host's window). There is one form and no version: a file written in an
40
- # file written in an older form is not read.
44
+ # older form is not read.
41
45
 
42
46
  primitive ReplayMode =
43
47
  const Off = 0
@@ -66,11 +70,16 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: List<Input> = Nil) =
66
70
 
67
71
  # The text form (see the top of this file).
68
72
  fun encode(self) -> Str =
69
- "{Replay.header(self.seed, self.width, self.height)}{Replay.ticksText(self.ticks)}"
73
+ "{Replay.header(self.seed, self.width, self.height)}{Replay.written(self.ticks, Vec2(x: Float(self.width), y: Float(self.height))).text()}"
70
74
 
71
- # The tick lines alone, what a recording game hands the host.
75
+ # The tick lines of `ticks`, what a recording game hands the host, the window size
76
+ # written last being `size`: each tick's size is written when it differs from the last.
72
- fun ticksText(ticks: List<Input>) -> Str =
77
+ fun written(ticks: List<Input>, size: Vec2) -> Written =
78
+ none: List<Str> := Nil
79
+ ticks.fold(Written(lines: none, size: size), |w, t| Written(lines: Cons(Replay.line(t, w.size), w.lines), size: Replay.sizeAfter(t, w.size)))
80
+
73
- ticks.map(|t| Replay.line(t)).join("")
81
+ # The window after the tick `t`, the one before being `size`: its own when it has one.
82
+ fun sizeAfter(t: Input, size: Vec2) -> Vec2 = if t.screen.x > 0.0 && t.screen.y > 0.0 then t.screen else size
74
83
 
75
84
  # Reads the text form back, or says what is wrong with it.
76
85
  fun decode(text: Str) -> Result<Replay, Str> =
@@ -83,43 +92,50 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: List<Input> = Nil) =
83
92
  lo := Replay.headNumber(head, 2)?
84
93
  width := Replay.headNumber(head, 3)?
85
94
  height := Replay.headNumber(head, 4)?
86
- ticks := Replay.decodeTicks(lines, 1, Nil)?
95
+ ticks := Replay.decodeTicks(lines, 1, Nil, Vec2(x: Float(width), y: Float(height)))?
87
- Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks).onScreen(width, height))
96
+ Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks))
88
97
 
89
- # The replay on a window `w` by `h` pixels, each tick's input in it (`Input.screen`): a
98
+ # The replay with the ticks that have no window (`Input.screen` 0 by 0: those before
90
- # decoded replay is on the window of its header.
99
+ # the first size of a replay whose header has none) on a window `w` by `h` pixels.
91
100
  fun onScreen(self, w: Int, h: Int) -> Replay =
92
- Replay(..self, width: w, height: h, ticks: self.ticks.map(|t| t.sized(Float(w), Float(h))))
101
+ Replay(..self, width: w, height: h, ticks: self.ticks.map(|t| if t.screen.x > 0.0 && t.screen.y > 0.0 then t else t.sized(Float(w), Float(h))))
93
102
 
94
103
  # The whole number at `head.at(i)`, a field of the first line.
95
104
  fun headNumber(head: Slice<Str>, i: Int) -> Result<Int, Str> =
96
105
  Int.parse(head.at(i)).mapErr(|e| "line 1: `{head.at(i)}` is not a whole number")
97
106
 
98
- # The tick lines from `lines.at(i)` on, after `out` (the lines before, the last first).
107
+ # The tick lines from `lines.at(i)` on, after `out` (the lines before, the last first),
108
+ # the window of the line before being `size`.
99
- fun decodeTicks(lines: Slice<Str>, i: Int, out: List<Input>) -> Result<List<Input>, Str> =
109
+ fun decodeTicks(lines: Slice<Str>, i: Int, out: List<Input>, size: Vec2) -> Result<List<Input>, Str> =
100
110
  if i >= lines.length()
101
111
  Ok(out.reverse())
102
112
  else
103
113
  l := lines.at(i).trim()
104
114
  if l.length() == 0
105
- Replay.decodeTicks(lines, i + 1, out)
115
+ Replay.decodeTicks(lines, i + 1, out, size)
106
116
  else
107
117
  match Replay.parseLine(l)
118
+ Some(input) =>
119
+ now := Replay.sizeAfter(input, size)
108
- Some(input) => Replay.decodeTicks(lines, i + 1, Cons(input, out))
120
+ Replay.decodeTicks(lines, i + 1, Cons(Input(..input, screen: now), out), now)
109
121
  None => Err("line {i + 1}: `{l}` is not a tick")
110
122
 
111
123
  fun header(seed: Int, width: Int, height: Int) -> Str =
112
124
  "plum-replay {seed >> 32} {seed & 0xFFFFFFFF} {width} {height}\n"
113
125
 
114
- # One tick's line, ending in a newline.
126
+ # One tick's line, ending in a newline, the window written last being `size`: its own
127
+ # window (`S<w>,<h>`) when it has one that differs.
115
- fun line(input: Input) -> Str =
128
+ fun line(input: Input, size: Vec2 = Vec2(x: 0.0, y: 0.0)) -> Str =
116
129
  h := input.held
117
130
  keys := if h.keys.isEmpty() then "-" else h.keys.map(|k| "{k}").join(",")
118
131
  mask := h.buttons.fold(if h.mouse then 1 else 0, |m, x| m | {1 << x})
132
+ s := input.screen
133
+ window := if s.x > 0.0 && s.y > 0.0 && s != size then " S{Replay.floatCode(s.x)},{Replay.floatCode(s.y)}" else ""
119
134
  events := input.events.fold("", |acc, e| "{acc} {Replay.eventCode(e)}")
120
- "{keys} {mask} {Replay.floatCode(h.pointer.x)} {Replay.floatCode(h.pointer.y)}{events}\n"
135
+ "{keys} {mask} {Replay.floatCode(h.pointer.x)} {Replay.floatCode(h.pointer.y)}{window}{events}\n"
121
136
 
122
- # One tick's line read back (no newline), or None.
137
+ # One tick's line read back (no newline), or None; its `screen` is its `S` token's, 0 by
138
+ # 0 for none.
123
139
  fun parseLine(l: Str) -> Option<Input> =
124
140
  t := l.split(" ", 0)
125
141
  mask := if t.length() < 4 then -1 else Int.parse(t.at(1)).ok().unwrapOr(-1)
@@ -130,9 +146,22 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: List<Input> = Nil) =
130
146
  held := keys?
131
147
  x := Replay.parseFloatCode(t.at(2))?
132
148
  y := Replay.parseFloatCode(t.at(3))?
149
+ sized := t.length() > 4 && t.at(4).length() > 1 && t.at(4).byteAt(0) == 83
150
+ window := if sized then Replay.parseSize(t.at(4)) else Some(Vec2(x: 0.0, y: 0.0))
151
+ screen := window?
133
- events := Replay.parseEvents(t, 4)?
152
+ events := Replay.parseEvents(t, if sized then 5 else 4)?
134
153
  buttons := [if {mask & 2} != 0 then Mouse.Right, if {mask & 4} != 0 then Mouse.Middle]
135
- Some(Input(events: events, held: Held(mouse: {mask & 1} != 0, keys: held, buttons: buttons, pointer: Vec2(x: x, y: y))))
154
+ Some(Input(events: events, held: Held(mouse: {mask & 1} != 0, keys: held, buttons: buttons, pointer: Vec2(x: x, y: y)), screen: screen))
155
+
156
+ # A window token `S<w>,<h>` read back, or None (sides must be above 0).
157
+ fun parseSize(tok: Str) -> Option<Vec2> =
158
+ wh := tok.sub(1, tok.length()).split(",", 0)
159
+ if wh.length() != 2
160
+ None
161
+ else
162
+ w := Replay.parseFloatCode(wh.at(0))?
163
+ h := Replay.parseFloatCode(wh.at(1))?
164
+ if w > 0.0 && h > 0.0 then Some(Vec2(x: w, y: h)) else None
136
165
 
137
166
  fun parseKeys(ks: Slice<Str>, i: Int) -> Option<List<Int>> =
138
167
  if i >= ks.length()
@@ -234,9 +263,15 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: List<Input> = Nil) =
234
263
  else
235
264
  None
236
265
 
237
- # The same input, bit for bit (a NaN equals a NaN): what a replay must give back.
266
+ # The same events and held, bit for bit (a NaN equals a NaN), the window aside: what a
267
+ # replay must give back.
238
268
  fun sameInput(a: Input, b: Input) -> Bool =
239
- Replay.line(a) == Replay.line(b)
269
+ Replay.line(a, a.screen) == Replay.line(b, b.screen)
270
+
271
+ # Tick lines written (`Replay.written`): the lines, the last first, and the window size
272
+ # written last.
273
+ struct Written(lines: List<Str>, size: Vec2) =
274
+ fun text(self) -> Str = self.lines.reverse().join("")
240
275
 
241
276
  # A Float written as the integer `m` times 2^`e`.
242
277
  struct Scaled(m: Float, e: Int) =
std/game/Screen.plum CHANGED
@@ -85,7 +85,7 @@ import std/game/ScreenSlice
85
85
  # (its frame among them).
86
86
  # wants std's too: whether what is held after the tick's input gives an
87
87
  # `OnDemand` screen something to do. A plain screen's is never; a slice's
88
- # is whether it subscribes to `OnHeld`.
88
+ # is whether something is held and it subscribes to `OnHeld`.
89
89
  #
90
90
  # The game keeps a screen as it is when it goes to another, so coming back shows it as it
91
91
  # was left.
std/game/ScreenSlice.plum CHANGED
@@ -60,6 +60,8 @@ import std/game/Screen
60
60
  # own), None for any other
61
61
  # a pointer event `OnPointerDown(at)`, `OnPointerUp(at)`, `OnPointerMove(at)`, with
62
62
  # the event's point in the world (through the screen's camera)
63
+ # a right or `OnButtonDown(button, at)`, `OnButtonUp(button, at)`: the
64
+ # middle button button (`Mouse.Right`, `Mouse.Middle`) and where it went
63
65
  # a wheel turn `OnWheel(dy, at)`, at where the pointer is after the tick's events
64
66
  # While a transition runs, the pointer events and the wheel are dropped: only keys
65
67
  # come.
@@ -69,7 +71,9 @@ import std/game/Screen
69
71
  #
70
72
  # Several subscriptions may answer one event (each in the order listed). Each action is
71
73
  # stepped as it is made, and then each action of its `then`, in order, each with its own
72
- # `then` first: so the next action sees what they did. The delivery is a fold
74
+ # `then` first: so the next action sees what they did. A `then` chain more than
75
+ # `Delivery.ThenDepth` (1000) actions deep stops the program, naming the actions' type:
76
+ # actions that ask for each other never end. The delivery is a fold
73
77
  # (`Delivery.deliverTo`): the screen after the tick, the actions stepped, in order, and
74
78
  # their commands, which the game does after the tick (and the transition's step).
75
79
  trait ScreenSlice<A>[Screen] =
@@ -81,9 +85,9 @@ trait ScreenSlice<A>[Screen] =
81
85
  Presses<A> as p => Some(p.pressed())
82
86
  _ => None
83
87
 
84
- # std's: whether what is held gives an `OnDemand` screen something to do: it subscribes
88
+ # std's: whether what is held gives an `OnDemand` screen something to do: something is
85
- # to `OnHeld`.
89
+ # held (`Held.any`) and it subscribes to `OnHeld`.
86
- fun wants(self, h: Held) -> Bool = self.subscriptions().any(|s| s.isHeld())
90
+ fun wants(self, h: Held) -> Bool = h.any() && self.subscriptions().any(|s| s.isHeld())
87
91
 
88
92
  # std's: one tick of the screen, delivered as actions (see the top of this file).
89
93
  fun deliver(self, d: Delivery) -> Delivered = Delivery.deliverTo<A, Self>(self, d)
@@ -98,6 +102,8 @@ trait ScreenSlice<A>[Screen] =
98
102
  # OnPointerDown(act) `act(at)` for a pointer down that no press target took
99
103
  # OnPointerUp(act) `act(at)` for a pointer up
100
104
  # OnPointerMove(act) `act(at)` for a pointer move (a drag, with `OnHeld`'s `h.mouse`)
105
+ # OnButtonDown(act) `act(button, at)` for the right or middle mouse button going down
106
+ # OnButtonUp(act) `act(button, at)` for the right or middle mouse button going up
101
107
  #
102
108
  # A list of them is made again each tick, so one can be there only while the state says
103
109
  # so: `if !self.over then OnHeld(|h| Steer(..))`.
@@ -110,6 +116,8 @@ enum Sub<A> =
110
116
  | OnPointerDown(act: fn(Vec2) -> A)
111
117
  | OnPointerUp(act: fn(Vec2) -> A)
112
118
  | OnPointerMove(act: fn(Vec2) -> A)
119
+ | OnButtonDown(act: fn(Int, Vec2) -> A)
120
+ | OnButtonUp(act: fn(Int, Vec2) -> A)
113
121
 
114
122
  fun isHeld(self) -> Bool = match self
115
123
  OnHeld(_) => true
@@ -126,6 +134,8 @@ enum Sub<A> =
126
134
  OnPointerDown(down) => if e.isPointerDown() then Some(down(at)) else None
127
135
  OnPointerUp(up) => if e.isPointerUp() then Some(up(at)) else None
128
136
  OnPointerMove(move) => if e.isPointerMove() then Some(move(at)) else None
137
+ OnButtonDown(pressed) => if e.buttonDown() >= 0 then Some(pressed(e.buttonDown(), at)) else None
138
+ OnButtonUp(lifted) => if e.buttonUp() >= 0 then Some(lifted(e.buttonUp(), at)) else None
129
139
  _ => None
130
140
 
131
141
  # Its action for what is held, or None.
@@ -202,10 +212,10 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
202
212
  fun heldInto<A, S: ScreenSlice<A>>(self, s: S, subs: List<Sub<A>>, trail: Trail<A>) -> Delivered =
203
213
  h := self.input.held
204
214
  held := Subs.picked<A>(subs, |sub| sub.onHeld(h))
205
- afterHeld := if held.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(!self.before.same(h)), held)
215
+ afterHeld := if held.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(!self.before.same(h)), held, 0)
206
216
  dt := self.dt
207
217
  match afterHeld
208
- Folded(cur, heldTrail) => Delivery.done<A, S>(Delivery.actAll<A, S>(cur, heldTrail, Subs.picked<A>(subs, |sub| sub.onFrame(dt))))
218
+ Folded(cur, heldTrail) => Delivery.done<A, S>(Delivery.actAll<A, S>(cur, heldTrail, Subs.picked<A>(subs, |sub| sub.onFrame(dt)), 0))
209
219
 
210
220
  # The slice `s` after the tick's events `es`.
211
221
  fun eventsInto<A, S: ScreenSlice<A>>(self, s: S, subs: List<Sub<A>>, trail: Trail<A>, es: List<InputEvent>) -> Folded<S, A> = match es
@@ -241,29 +251,36 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
241
251
  p := self.input.held.pointer
242
252
  at := self.camera.toWorld(p.x, p.y)
243
253
  Subs.picked<A>(subs, |sub| sub.onEvent(e, at))
244
- if acts.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(true), acts)
254
+ if acts.isEmpty() then Folded(state: s, trail: trail) else Delivery.actAll<A, S>(s, trail.user(true), acts, 0)
245
255
 
246
256
  # `a` stepped into the slice `s`, with its `then`, as a delivery steps an action: what
247
257
  # std/game/TestRig's `dispatch` runs.
248
258
  fun dispatchTo<A, S: ScreenSlice<A>>(s: S, a: A) -> Delivered =
249
259
  none: Trail<A> := Trail()
250
- Delivery.done<A, S>(Delivery.actIn<A, S>(@copy(s), none, a))
260
+ Delivery.done<A, S>(Delivery.actIn<A, S>(@copy(s), none, a, 0))
251
261
 
262
+ # How deep a chain of `then`s may go before the program stops (see the top of this file).
263
+ const ThenDepth = 1000
264
+
252
- # The slice `s` with `a` stepped into it, and then each action of its `then`.
265
+ # The slice `s` with `a` stepped into it, and then each action of its `then`; `depth` is
266
+ # how many `then`s led to `a`.
253
- fun actIn<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, a: A) -> Folded<S, A> =
267
+ fun actIn<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, a: A, depth: Int) -> Folded<S, A> =
268
+ if depth >= Delivery.ThenDepth
269
+ crash "game: the actions' `then` goes {Delivery.ThenDepth} deep at an action of {@typeName(A)}: do the actions ask for each other?"
254
270
  n := s.update(a)
255
271
  match n
256
272
  Next(next, then, cmds) =>
257
273
  after := Trail(..trail, actions: Cons(a, trail.actions), cmds: cmds.fold(trail.cmds, |acc, c| Cons(c, acc)))
258
- Delivery.actAll<A, S>(next, after, then)
274
+ Delivery.actAll<A, S>(next, after, then, depth + 1)
259
275
 
260
- # The slice `s` with each of `xs` stepped in, in order.
276
+ # The slice `s` with each of `xs` stepped in, in order, each `depth` `then`s deep.
261
- fun actAll<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, xs: List<A>) -> Folded<S, A> = match xs
277
+ fun actAll<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, xs: List<A>, depth: Int) -> Folded<S, A> = match xs
262
278
  Nil => Folded(state: s, trail: trail)
263
279
  Cons(a, rest) =>
264
- f := Delivery.actIn<A, S>(s, trail, a)
280
+ f := Delivery.actIn<A, S>(s, trail, a, depth)
265
281
  match f
266
- Folded(next, after) => Delivery.actAll<A, S>(next, after, rest)
282
+ Folded(next, after) => Delivery.actAll<A, S>(next, after, rest, depth)
283
+
267
284
 
268
285
  # The tick delivered: the slice, its actions and commands in order.
269
286
  fun done<A, S: ScreenSlice<A>>(f: Folded<S, A>) -> Delivered = match f
std/game/Sprite.plum CHANGED
@@ -31,8 +31,15 @@ struct Sprite[View, Sized, Touch](x: Float = 0.0, y: Float = 0.0, tex: Texture,
31
31
  fun place(self) -> Place = Place.at(self.x, self.y)
32
32
 
33
33
  # The frame of a strip of `count` frames played at `fps` frames a second, `clock`
34
- # seconds in, looping: `Sprite(.., frame: Sprite.frameAt(self.clock, 8.0, 4))`.
34
+ # seconds in, looping: `Sprite(.., frame: Sprite.frameAt(self.clock, 8.0, 4))`. Before
35
+ # 0 s it plays backwards from the last frame (always in `[0, count)`); a strip of no
36
+ # frames, or a clock or rate that is not a number, shows frame 0.
35
- fun frameAt(clock: Float, fps: Float, count: Int) -> Int = Int(clock * fps) % count
37
+ fun frameAt(clock: Float, fps: Float, count: Int) -> Int =
38
+ t := {clock * fps}.floor()
39
+ if count <= 0 || t.isNaN() || t.isInfinite()
40
+ 0
41
+ else
42
+ {Int(t) % count + count} % count
36
43
 
37
44
  # Where the frame shown starts in the texture.
38
45
  fun frameX(self) -> Float = self.srcX + Float(self.frame) * self.srcW
std/game/TestRig.plum CHANGED
@@ -57,14 +57,18 @@ import std/game/Game
57
57
  # next(held, evs) the next tick's input is exactly that
58
58
  #
59
59
  # `dispatch(a)` steps an action into the shown screen (the rig's screen) through its
60
- # `update`, as a delivery would (with its `then`), then does what ends a tick: its commands, an undo, a redo or a rewind included.
60
+ # `update`, as a delivery would (with its `then`), then does what ends a tick: its
61
+ # commands, an undo, a redo or a rewind included. A game that keeps a history keeps the
62
+ # dispatch in it (`Game.dispatched`), so a move back through it does it again.
61
63
  #
62
64
  # Time: `tick()` runs one tick of the game's own path (`Game.step`: the screen's
63
65
  # subscriptions and presses, its frame action, the transition and the commands they
64
66
  # gave), with the input
65
67
  # waiting and what is held; `ticks(n)` runs `n`, the input waiting going to the first.
66
68
  # `tick(dt)` runs one of `dt` seconds instead. `frame(input, frameDt)` is the host's
67
- # frame, the `Ticker` turning wall time into ticks, for scripted runs.
69
+ # frame, the `Ticker` turning wall time into ticks, for scripted runs. A tick's input
70
+ # carries the rig's window (`Input.screen`); one given with a window of its own (a
71
+ # frame's, a replay's tick) resizes the rig's to it, as the host's would.
68
72
  #
69
73
  # Reading, all from the shown screen's view and then its `hud`: `find<T>()` lists the
70
74
  # items of type `T` they draw, in the order drawn; `first<T>()` is the first (none stops the test with "headless: first: no
@@ -182,33 +186,37 @@ struct TestRig<S>(
182
186
 
183
187
  # Steps `a` into the shown screen, which must be the rig's screen, as a delivery steps
184
188
  # an action (with its `then`: std/game/ScreenSlice's `Delivery.dispatchTo`), then does
185
- # what ends a tick: its commands, an undo, a redo or a rewind included. What it gave is
189
+ # what ends a tick: its commands, an undo, a redo or a rewind included
190
+ # (`Game.dispatched`, which keeps it in a history). What it gave is read as a tick's. An
186
- # read as a tick's. An `OnDemand` screen is woken for the next tick.
191
+ # `OnDemand` screen is woken for the next tick.
187
192
  fun dispatch<A>(self, a: A) -> TestRig<S> =
188
- g := self.game
193
+ TestRig(..self.forget()).kept(self.game.dispatched(self.io, |s| TestRig.delivered<A, S>(s, a)))
194
+
189
- match g.screen()
195
+ # `a` stepped into `s`, which must be an `S`.
190
- S as sl =>
196
+ fun delivered<A, T>(s: Screen, a: A) -> Delivered = match s
191
- d := Delivery.dispatchTo<A, S>(sl, a)
197
+ T as sl => Delivery.dispatchTo<A, T>(sl, a)
192
- withScreen := Game(..g, screens: Game.setAt(g.screens, g.current, d.screen), wake: true, dirty: true, sent: d.sent, cmds: d.cmds)
193
- TestRig(..self.forget(), game: withScreen).kept(withScreen.obeyAll(self.io, d.cmds).travelAsked(self.io))
194
- _ =>
198
+ _ => TestRig.notTheRigs()
199
+
200
+ fun notTheRigs() -> Delivered =
195
- crash "headless: dispatch: the screen shown is not the rig's screen"
201
+ crash "headless: dispatch: the screen shown is not the rig's screen"
196
202
 
197
203
  # Forgets what the last ticks gave.
198
204
  fun forget(self) -> TestRig<S> = TestRig(..self, sent: Nil, cmds: Nil)
199
205
 
200
- # One tick with the input waiting, keeping what it gave.
206
+ # One tick with the input waiting, in the rig's window, keeping what it gave.
201
207
  fun step(self, dt: Float) -> TestRig<S> =
202
- input := Input(events: self.events, held: self.held)
208
+ input := Input(events: self.events, held: self.held, screen: self.pixels)
203
209
  TestRig(..self, events: Nil).ran1(input, dt)
204
210
 
211
+ # One tick of the game with `input`, in its window when it has one (the rig's from then
205
- # One tick of the game with `input`, recorded while recording.
212
+ # on) or else the rig's, recorded while recording.
206
213
  fun ran1(self, input: Input, dt: Float) -> TestRig<S> =
207
214
  if self.game.exited || self.game.paused
208
215
  self
209
216
  else
217
+ pixels := if input.screen.x > 0.0 && input.screen.y > 0.0 then input.screen else self.pixels
210
- logged := if self.recording then Replay(..self.log, ticks: Cons(input, self.log.ticks)) else self.log
218
+ logged := if self.recording then Replay(..self.log, ticks: Cons(Input(..input, screen: pixels), self.log.ticks)) else self.log
211
- TestRig(..self, log: logged).kept(self.game.step(self.io, input, dt, self.pixels))
219
+ TestRig(..self, log: logged, pixels: pixels).kept(self.game.step(self.io, input, dt, pixels))
212
220
 
213
221
  # The rig with `g`, keeping what its last tick gave.
214
222
  fun kept(self, g: Game) -> TestRig<S> =
@@ -304,6 +312,6 @@ struct TestRig<S>(
304
312
 
305
313
  fun recorded(self) -> Replay = Replay(..self.log, ticks: self.log.ticks.reverse())
306
314
 
307
- # Every tick of `r` played now (a game made from `r.seed`).
315
+ # Every tick of `r` played now (a game made from `r.seed`), each in its window.
308
316
  fun replay(self, r: Replay) -> TestRig<S> =
309
317
  r.ticks.fold(self.forget(), |t, input| t.ran1(input, Ticker.Tick))
std/game/Touch.plum CHANGED
@@ -5,7 +5,8 @@ import std/Bool
5
5
  # Whether an actor takes presses (std/game/View's `hitIn`): `Enabled`, it is hit where
6
6
  # it is (when it is `Sized`) and so is what is under it; `Disabled`, neither it nor
7
7
  # anything under it is; `ChildrenOnly`, what is under it is and it is not. An actor that
8
- # doesn't say is `ChildrenOnly`.
8
+ # doesn't say is `ChildrenOnly`, and so is one that says `Enabled` but is not `Sized` (a
9
+ # `Group`, a `Blend`): it has no bounds to be hit in.
9
10
  enum Touchable =
10
11
  | Enabled
11
12
  | Disabled
std/game/View.plum CHANGED
@@ -137,9 +137,10 @@ primitive Views =
137
137
  None => None
138
138
 
139
139
  # Each `Actor` of `items` stepped by `dt`, in order: an actor steps what it holds itself
140
- # (its own `step`), so its view is neither made nor looked inside. A `Group` or an
140
+ # (its own `step`), so its view is neither made nor looked inside (a `Button` is one,
141
+ # whose step steps its children this way). A `Group`, a `Blend` or an `Overlay` is made
141
- # `Overlay` is made again with its children stepped the same way; any other view is as it
142
+ # again with its children stepped the same way; any other view is as it is, with what it
142
- # is, with what it holds (a kind of your own that holds actors is an `Actor` that steps
143
+ # holds (a kind of your own that holds actors is an `Actor` that steps
143
144
  # them, or its screen's `stepped` steps them).
144
145
  fun stepIn(items: List<View>, dt: Float) -> List<View> = items.map(|x| Views.stepOne(x, dt))
145
146
 
@@ -152,37 +153,45 @@ primitive Views =
152
153
 
153
154
  # Draws the visible `items`, `m` and `alpha` being those of what holds them (the screen's
154
155
  # camera, or the view whose view they are): each through its own place under `m`, at
155
- # `alpha` times its place's alpha, its `paintSelf` and then its view (and, after a
156
+ # `alpha` times its place's alpha, its `paintSelf` and then its view. A `Blend` sets the
157
+ # host's blend mode for its view and puts back the mode it was drawn in after it (the
156
- # `Blend`'s view, the host's blend mode back to `Blend.Normal`).
158
+ # enclosing `Blend`'s, or `Blend.Normal`).
157
- fun paint(io: Io, items: List<View>, m: Affine, alpha: Float) = items.each(|k| Views.paintItem(io, k, m, alpha))
159
+ fun paint(io: Io, items: List<View>, m: Affine, alpha: Float) = Views.paintIn(io, items, m, alpha, Blend.Normal)
158
160
 
161
+ fun paintIn(io: Io, items: List<View>, m: Affine, alpha: Float, mode: Int) = items.each(|k| Views.paintItem(io, k, m, alpha, mode))
162
+
159
- fun paintItem(io: Io, a: View, m: Affine, alpha: Float) =
163
+ fun paintItem(io: Io, a: View, m: Affine, alpha: Float, mode: Int) =
160
164
  if a.visible()
161
165
  at := a.place()
162
166
  mk := at.under(m)
163
167
  ak := alpha * at.alpha
168
+ blend := Views.blendOf(a)
164
169
  a.paintSelf(io, mk, ak)
165
- Views.paint(io, a.view(), mk, ak)
170
+ Views.paintIn(io, a.view(), mk, ak, if blend < 0 then mode else blend)
171
+ if blend >= 0
166
- Views.paintDone(io, a)
172
+ Gfx.blendMode(io, mode)
167
173
 
168
- # What the walk does after `a`'s view is drawn: a `Blend` returns the host to
174
+ # The blend mode `a` draws its view in: a `Blend`'s, -1 for any other view.
169
- # `Blend.Normal`.
170
- fun paintDone(io: Io, a: View) = match a
175
+ fun blendOf(a: View) -> Int = match a
171
- Blend as b => Gfx.blendMode(io, Blend.Normal)
176
+ Blend as b => b.mode
172
- _ => Unit
177
+ _ => -1
173
178
 
174
179
  # `paint`, skipping each `Sized` item whose bounds, through its transform, miss
175
180
  # `area` (in the coordinates `m` maps to), with what is under it.
181
+ fun paintCulled(io: Io, items: List<View>, m: Affine, alpha: Float, area: Aabb) = Views.paintCulledIn(io, items, m, alpha, area, Blend.Normal)
182
+
176
- fun paintCulled(io: Io, items: List<View>, m: Affine, alpha: Float, area: Aabb) =
183
+ fun paintCulledIn(io: Io, items: List<View>, m: Affine, alpha: Float, area: Aabb, mode: Int) =
177
184
  items.each(|a|
178
185
  if a.visible()
179
186
  at := a.place()
180
187
  mk := at.under(m)
181
188
  if !Views.missesArea(a, mk, area)
182
189
  ak := alpha * at.alpha
190
+ blend := Views.blendOf(a)
183
191
  a.paintSelf(io, mk, ak)
184
- Views.paintCulled(io, a.view(), mk, ak, area)
192
+ Views.paintCulledIn(io, a.view(), mk, ak, area, if blend < 0 then mode else blend)
193
+ if blend >= 0
185
- Views.paintDone(io, a)
194
+ Gfx.blendMode(io, mode)
186
195
  )
187
196
 
188
197
  # Pushes onto `out` what `items` draw, in the order drawn: each visible item with its
@@ -203,7 +212,8 @@ primitive Views =
203
212
  # on: the top-most visible item that takes presses (`Sized`, and `Enabled`,
204
213
  # std/game/Touch) and whose `hit` says the point is on it, what is drawn later before what
205
214
  # is drawn earlier, what is under an item before the item. A `Disabled` or invisible item
206
- # is passed over with what is under it. None for none.
215
+ # is passed over with what is under it, and so is one whose place is flat (scaled to 0 on
216
+ # an axis, `Place.toLocal`). None for none.
207
217
  fun hitIn(items: List<View>, p: Vec2) -> Option<View> = Views.hitAmong(items.reverse(), p)
208
218
 
209
219
  fun hitAmong(rev: List<View>, p: Vec2) -> Option<View> = match rev
@@ -217,14 +227,16 @@ primitive Views =
217
227
  if t.disabled() || !a.visible()
218
228
  None
219
229
  else
220
- q := a.place().toLocal(p)
230
+ match a.place().toLocal(p)
231
+ None => None
232
+ Some(q) =>
221
- under := Views.hitIn(a.view(), q)
233
+ under := Views.hitIn(a.view(), q)
222
- if under.isSome()
234
+ if under.isSome()
223
- under
235
+ under
224
- else if t.enabled() && Views.sizedHit(a, q)
236
+ else if t.enabled() && Views.sizedHit(a, q)
225
- Some(a)
237
+ Some(a)
226
- else
238
+ else
227
- None
239
+ None
228
240
 
229
241
  # How `a` takes presses: its own `touch`, or `ChildrenOnly` if it doesn't say.
230
242
  fun touchOf(a: View) -> Touchable = match a
std/game/Viewport.plum CHANGED
@@ -2,6 +2,7 @@ module std
2
2
 
3
3
  import std/Bool
4
4
  import std/Float
5
+ import std/Str
5
6
  import std/math/Vec2
6
7
  import std/math/Affine
7
8
  import std/math/Aabb
@@ -51,8 +52,11 @@ struct Viewport(scaling: Scaling, w: Float, h: Float, screenW: Float, screenH: F
51
52
 
52
53
  # This camera on the same window, moved so that the world point (x, y) is at the
53
54
  # window's centre and `zoom` times as close: what a screen's `camera` returns to follow
54
- # something or zoom (std/game/Screen).
55
+ # something or zoom (std/game/Screen). A zoom that is not above 0 (or not a number)
56
+ # stops the program, as no camera shows the world through it.
55
57
  fun lookAt(self, x: Float, y: Float, zoom: Float = 1.0) -> Viewport =
58
+ if !{zoom > 0.0} || zoom.isInfinite()
59
+ crash "viewport: lookAt needs a zoom above 0, not {zoom}"
56
60
  sx := self.sx * zoom
57
61
  sy := self.sy * zoom
58
62
  Viewport(..self, sx: sx, sy: sy, x: x - self.screenW / sx / 2.0, y: y - self.screenH / sy / 2.0, moved: true)
std/math/Aabb.plum CHANGED
@@ -25,6 +25,11 @@ struct Aabb(min: Vec2, max: Vec2) =
25
25
  fun contains(self, o: Aabb) -> Bool =
26
26
  self.min.x <= o.min.x && o.max.x <= self.max.x && self.min.y <= o.min.y && o.max.y <= self.max.y
27
27
 
28
+ # The box `by` in from each side (out for a negative `by`): the room a circle of radius
29
+ # `by` has to move in, its centre kept inside.
30
+ fun shrink(self, by: Float) -> Aabb =
31
+ Aabb(min: Vec2(x: self.min.x + by, y: self.min.y + by), max: Vec2(x: self.max.x - by, y: self.max.y - by))
32
+
28
33
  # The smallest box holding both.
29
34
  fun union(self, o: Aabb) -> Aabb =
30
35
  Aabb(min: Vec2(x: self.min.x.min(o.min.x), y: self.min.y.min(o.min.y)), max: Vec2(x: self.max.x.max(o.max.x), y: self.max.y.max(o.max.y)))
std/math/Dice.plum ADDED
@@ -0,0 +1,33 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/math/Vec2
6
+ import std/math/Random
7
+
8
+ # A game's dice: its seed, taken once in `main` from `io.randomSeed()` and kept in a
9
+ # screen, and the draws keyed from it by counter (std/math/Random's `Random.at`), so
10
+ # nothing is threaded from draw to draw. A key is a moment, a kind and an id:
11
+ #
12
+ # d := self.dice.roll(self.ticks, Deal.Orb, i)
13
+ # x := d.floatAt(0)
14
+ #
15
+ # `tick` is when (the screen's tick count), `kind` what the draw is for, one constant of
16
+ # the game for each purpose (an orb dealt, an orb caught, a mine added), and `id` which
17
+ # one of that kind (0, 1, ..: any Int). The kind and the id are mixed in one after the
18
+ # other, not added, so keys of two kinds never meet whatever their ids: two purposes in one
19
+ # tick, or a restart's deal and a catch at the same tick, never draw the same numbers,
20
+ # and the same tick, kind and id always do. A key's draws are `floatAt(i)`, `intAt(i)` and
21
+ # `intBelowAt(i, n)` (std/math/Random), independent for each `i`.
22
+ #
23
+ # `Dice.scatter(i, w, h)` is the `i`th point of a fixed scatter over a `w` by `h` area,
24
+ # with no seed: where the stars of a backdrop or the confetti of a party stand, the same
25
+ # every run.
26
+ struct Dice(seed: Int) =
27
+ # The key of the draws for `kind` and `id` at `tick`.
28
+ fun roll(self, tick: Int, kind: Int, id: Int) -> Random =
29
+ Random(seed: Random.mix(Random.at(self.seed, tick, kind).seed + id))
30
+
31
+ # The `i`th point of the scatter over `w` by `h` (whole numbers, in `[0, w)` and
32
+ # `[0, h)`): the primes 7919 and 104729 times `i`, each modulo its side.
33
+ fun scatter(i: Int, w: Int, h: Int) -> Vec2 = Vec2(x: Float({i * 7919} % w), y: Float({i * 104729} % h))
tests/examples/games/balloonpop/actors/Balloon.plum CHANGED
@@ -45,3 +45,11 @@ primitive BalloonTest[UnitTest] =
45
45
  assert p.place().x == x
46
46
  assert !p.done()
47
47
  assert p.step(0.2).done()
48
+
49
+ # a balloon's sway is its own draw, not where it starts across
50
+ fun aBalloonsSwayIsNotWhereItStarts() =
51
+ d := Random.at(5, 0, 1)
52
+ b := Balloon.spawn(1, d, 0.0, 0.0)
53
+ assert b.body.pos.x == 60.0 + d.floatAt(0) * {Arena.W - 120.0}
54
+ assert b.phase == d.floatAt(3) * Float.Tau
55
+ assert Range.until(0, 20).all(|i| Balloon.spawn(1, Random.at(i, 0, 1), 0.0, 0.0).phase != Random.at(i, 0, 1).floatAt(0) * Float.Tau)
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -66,7 +66,7 @@ primitive PlaygroundScreenTest[UnitTest] =
66
66
 
67
67
  fun aPoppedBalloonComesBackAtTheBottom() =
68
68
  t := PlaygroundScreenHelpers.centred(PlaygroundScreenHelpers.field(io, 3)).clickAt(400.0, 300.0).tick(0.0)
69
- assert PlaygroundScreenHelpers.lines(t) == "Blue!, 1"
69
+ assert PlaygroundScreenHelpers.lines(t) == "Purple!, 1"
70
70
  u := t.tick(Balloon.PopTime + 0.1)
71
71
  assert !u.screen.balloons.at(0).popped()
72
72
  assert u.screen.balloons.at(0).body.pos.y > Arena.H
@@ -77,7 +77,7 @@ primitive PlaygroundScreenTest[UnitTest] =
77
77
  u := PlaygroundScreenHelpers.centred(t).clickAt(400.0, 300.0).tick(0.0)
78
78
  assert u.screen.pops == 10
79
79
  assert u.screen.partying()
80
- assert PlaygroundScreenHelpers.lines(u) == "Blue!, Hooray!, 10 balloons!, 10"
80
+ assert PlaygroundScreenHelpers.lines(u) == "Purple!, Hooray!, 10 balloons!, 10"
81
81
  assert !u.tick(PlaygroundScreen.PartyTime + 0.1).screen.partying()
82
82
 
83
83
  # each pop plays the pop sound and the tenth the fanfare too, in the tick of the press
tests/examples/games/clockwork/actors/Spinner.plum CHANGED
@@ -4,6 +4,7 @@ import std/Bool
4
4
  import std/Str
5
5
  import std/collections/List
6
6
  import std/math/Vec2
7
+ import std/math/Aabb
7
8
  import std/math/Math
8
9
  import std/game/Body
9
10
  import std/game/View
@@ -26,6 +27,14 @@ primitive SpinnerTest[UnitTest] =
26
27
  assert !lit.light(5).lit
27
28
  assert s.pressed().toStr() == "Pick(4)"
28
29
 
30
+ # its bounds hold its halo while lit, so a lit body is culled only once its halo is off the view
31
+ fun itsBoundsHoldItsHaloWhileLit() =
32
+ s := Spinner(id: 4, name: "s", size: 40.0, body: Body(pos: Vec2.Zero), tex: Texture.none())
33
+ assert s.bounds() == Aabb.of(0.0, 0.0, 40.0, 40.0)
34
+ lit := s.light(4)
35
+ assert lit.bounds() == Aabb.of(20.0 - lit.halo(), 20.0 - lit.halo(), 2.0 * lit.halo(), 2.0 * lit.halo())
36
+ assert !lit.hit(Vec2(x: 20.0 - lit.halo() + 1.0, y: 20.0 - lit.halo() + 1.0))
37
+
29
38
  # it plays its strip as its clock runs, and turns about its centre
30
39
  fun itPlaysItsStripAndTurnsAboutItsCentre() =
31
40
  s := Spinner(id: 0, name: "s", size: 40.0, body: Body(pos: Vec2(x: 100.0, y: 50.0), turn: 1.0), tex: Texture.none(), fps: 6.0, frames: 4).step(0.5)
tests/examples/games/clockwork/screens/OrreryScreen.plum CHANGED
@@ -170,7 +170,20 @@ primitive OrreryScreenTest[UnitTest] =
170
170
  map := s.hud(Vec2(x: 1600.0, y: 600.0)).at(0)
171
171
  assert map.place().x == 1600.0 - Sheet.MapW - 8.0
172
172
  assert map.place().y == 600.0 - Sheet.MapH - 8.0
173
- assert map.view().length() == 6 + 8
173
+ assert map.view().length() == 5 + 8
174
+
175
+ # a press on the minimap is the minimap's: the walker under it in the sky is not brought to the front
176
+ fun aPressOnTheMinimapReachesNoWalker() =
177
+ t := OrreryScreenHelpers.sky(io)
178
+ corner := Vec2(x: 800.0 - Sheet.MapW - 8.0, y: 600.0 - Sheet.MapH - 8.0)
179
+ under := t.screen.walkers.map(|w| t.game.toScreen(t.worldOf(w).unwrap().apply(Vec2(x: 12.0, y: 12.0))))
180
+ .filter(|p| p.x > corner.x + 2.0 && p.x < corner.x + Sheet.MapW - 2.0 && p.y > corner.y + 2.0 && p.y < corner.y + Sheet.MapH - 2.0)
181
+ assert !under.isEmpty()
182
+ p := under.at(0)
183
+ assert OrreryScreenHelpers.hitId(t, p) == -100
184
+ v := t.clickAt(p.x, p.y).tick(0.0)
185
+ assert OrreryScreenHelpers.names(v) == "Pick(-1) Tick(0.0)"
186
+ assert v.screen.front == -1
174
187
 
175
188
  # a recorded run replays to the same sky, whose checksum is pinned
176
189
  fun aRecordedRunReplaysToTheSameSky() =
tests/examples/games/orbitrunner/actors/Orb.plum CHANGED
@@ -21,7 +21,7 @@ import std/Test
21
21
 
22
22
  primitive OrbTest[UnitTest] =
23
23
  fun anOrbDriftsAndBouncesOffTheWalls() =
24
- orb := Orb(id: 0, body: Body(pos: Vec2(x: 785.0, y: 300.0), vel: Vec2(x: 100.0, y: 0.0), edge: Bounce(box: Arena.inside(Orb.Radius))), tex: Texture.none()).step(0.1)
24
+ orb := Orb(id: 0, body: Body(pos: Vec2(x: 785.0, y: 300.0), vel: Vec2(x: 100.0, y: 0.0), edge: Bounce(box: Arena.Bounds.shrink(Orb.Radius))), tex: Texture.none()).step(0.1)
25
25
  assert orb.body.vel.x == -100.0
26
26
  assert orb.body.pos.x == Arena.W - Orb.Radius
27
27
  assert orb.clock == 0.1
tests/examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -48,6 +48,15 @@ primitive PlayingScreenTest[UnitTest] =
48
48
  assert t.count<Overlay>() == 0
49
49
  assert t.count<Ring>() == 0
50
50
 
51
+ # a deal and a catch at the same tick roll different dice: the orb caught lands elsewhere than the dealt one
52
+ fun aDealAndACatchAtOneTickRollApart() =
53
+ s := PlayingScreen.at(7, Assets.none(), 0, PlayingScreen.StartLives)
54
+ dealt := s.deal().orbs.at(0).body.pos
55
+ caught := s.update(Caught(orb: 0)).state.orbs.at(0).body.pos
56
+ assert dealt != caught
57
+ assert s.deal().orbs.at(0).body.pos == dealt
58
+ assert s.dice.roll(s.ticks, PlayingScreen.DealRoll, 0).seed != s.dice.roll(s.ticks, PlayingScreen.CatchRoll, 0).seed
59
+
51
60
  # a tick is Steer with the keys held, then Tick, whose rules are followed by what happened
52
61
  fun aTickIsSteerWithTheKeysHeld() =
53
62
  t := PlayingScreenHelpers.orbOnShip(PlayingScreenHelpers.emptied(io, 0, PlayingScreen.StartLives)).hold(Key.Right).hold(Key.KeyW).tick(0.016)
tests/std/game/Body.plum CHANGED
@@ -64,6 +64,16 @@ primitive BodyTest[UnitTest] =
64
64
  assert top.pos == Vec2(x: 50.0, y: 10.0)
65
65
  assert top.vel == Vec2(x: 0.0, y: 10.0)
66
66
 
67
+ # bouncing, a body outside the box that already moves back in keeps moving in
68
+ fun aBodyOutsideMovingInKeepsMovingIn() =
69
+ box := Aabb.of(10.0, 10.0, 80.0, 80.0)
70
+ b := Body(pos: Vec2(x: 120.0, y: 0.0), vel: Vec2(x: -5.0, y: 5.0), edge: Bounce(box: box)).step(1.0)
71
+ assert b.pos == Vec2(x: 90.0, y: 10.0)
72
+ assert b.vel == Vec2(x: -5.0, y: 5.0)
73
+ out := Body(pos: Vec2(x: 120.0, y: 0.0), vel: Vec2(x: 5.0, y: -5.0), edge: Bounce(box: box)).step(1.0)
74
+ assert out.vel == Vec2(x: -5.0, y: 5.0)
75
+ assert Body.bounced(5.0, 3.0, 10.0, 90.0) == 3.0 && Body.bounced(95.0, 3.0, 10.0, 90.0) == -3.0 && Body.bounced(50.0, 3.0, 10.0, 90.0) == 3.0
76
+
67
77
  # wrapping, it comes in at the other side with its velocity
68
78
  fun wrappingItComesInAtTheOtherSide() =
69
79
  box := Aabb.of(0.0, 0.0, 100.0, 50.0)
@@ -74,6 +84,15 @@ primitive BodyTest[UnitTest] =
74
84
  assert far.pos == Vec2(x: 60.0, y: 10.0)
75
85
  assert Body.wrap(100.0, 0.0, 100.0) == 0.0
76
86
 
87
+ # wrapping into an empty span gives its low side, and rounding never leaves it at the high side
88
+ fun wrappingNeverGivesNaNOrTheHighSide() =
89
+ assert Body.wrap(5.0, 3.0, 3.0) == 3.0
90
+ assert Body.wrap(5.0, 3.0, 1.0) == 3.0
91
+ assert Body.wrap(0.0 - 0.00000000000000001, 0.0, 1.0) == 0.0
92
+ assert Body.wrap(-1.5, 0.0, 1.0) == 0.5
93
+ stuck := Body(pos: Vec2(x: 5.0, y: 5.0), vel: Vec2(x: 3.0, y: 0.0), edge: Wrap(box: Aabb.of(0.0, 0.0, 0.0, 10.0))).step(1.0)
94
+ assert stuck.pos == Vec2(x: 0.0, y: 5.0)
95
+
77
96
  # facing its motion, it turns to its heading (0 up, clockwise) above the speed, and keeps it below
78
97
  fun facingItTurnsToItsHeading() =
79
98
  face := |v: Vec2| Body(pos: Vec2.Zero, vel: v, faceAbove: Some(5.0)).step(0.0).angle
tests/std/game/Game.plum CHANGED
@@ -9,7 +9,11 @@ import std/collections/List
9
9
  import std/math/Vec2
10
10
  import std/game/Input
11
11
  import std/game/View
12
+ import std/game/Audio
13
+ import std/game/Cmd
12
14
  import std/game/Screen
15
+ import std/game/ScreenSlice
16
+ import std/game/TestRig
13
17
  import std/game/History
14
18
  import std/game/Replay
15
19
  import std/game/Game
@@ -57,11 +61,118 @@ primitive GameTest[UnitTest] =
57
61
  shown := g.hostFrame(io)
58
62
  assert shown.draws == 1 && shown.idle()
59
63
 
64
+ # keys held through an undo are no new user action on the next tick, so what was undone can still be redone
65
+ fun keysHeldThroughAnUndoLeaveTheRedo() =
66
+ t := TestRig.mountWith(io, Counted.start()).hold(Key.Right).ticks(3).release(Key.Right).ticks(3).press(Key.KeyZ).tick()
67
+ assert t.moved() && t.game.tickNow() == 3
68
+ assert t.screen.steer == 1
69
+ u := t.tick()
70
+ assert u.game.canRedo()
71
+ v := u.redo()
72
+ assert v.moved() && v.game.tickNow() == 7 && v.screen.steer == 0
73
+
74
+ # a move through the history puts back the sounds looping where it goes, and the host's loops follow
75
+ fun aMovePutsBackTheLoops() =
76
+ t := TestRig.mountWith(io, Counted.start()).ticks(2).press(Key.KeyN).tick().ticks(2).press(Key.KeyM).tick()
77
+ assert t.game.loops.isEmpty()
78
+ u := t.rewindTo(4)
79
+ assert u.game.loops.length() == 1 && u.game.loops.at(0).volume == 0.5
80
+ assert Cmd.names(Looping.changes(t.game.loops, u.game.loops)) == "stop(-1) loop(-1, 0.5)"
81
+ assert Cmd.names(Looping.changes(u.game.loops, t.game.loops)) == "stop(-1)"
82
+ assert u.rewindTo(1).game.loops.isEmpty()
83
+ assert u.stepForward().stepForward().game.loops.isEmpty()
84
+ started := Game(screens: [GameHelpers.counted()]).looping(io, Sound.Silent, 0.3).timeTravel(History.Cap)
85
+ s := TestRig.playWith(io, started).press(Key.KeyM).tick().ticks(2)
86
+ assert s.game.loops.isEmpty()
87
+ assert s.rewindTo(0).game.loops.length() == 1 && s.rewindTo(0).game.loops.at(0).volume == 0.3
88
+ assert Cmd.names(Looping.changes(Nil, [Looping(sound: Sound.Silent, volume: 0.3)])) == "stop(-1) loop(-1, 0.3)"
89
+
90
+ # a dispatched action is kept in the history, and a move back through it does it again
91
+ fun aDispatchIsKeptInTheHistory() =
92
+ t := TestRig.mountWith(io, Counted.start()).ticks(3).dispatch(Bump).ticks(3)
93
+ assert t.screen.keys == 1 && t.screen.ticks == 6 && t.game.tickNow() == 7
94
+ back := t.rewindTo(5)
95
+ assert back.screen.keys == 1 && back.screen.ticks == 4
96
+ assert t.rewindTo(3).screen.keys == 0
97
+ assert t.undo().game.tickNow() == 3
98
+ assert t.undo().redo().screen.keys == 1
99
+
100
+ # a rewind from a snapshot reaches the game a rewind from the start does, and one played straight there
101
+ fun aRewindFromASnapshotIsARewindFromTheStart() =
102
+ a := GameHelpers.played(GameHelpers.snapping(io, 600), 0, 1500)
103
+ b := GameHelpers.played(GameHelpers.snapping(io, 0), 0, 1500)
104
+ assert a.game.snaps.map(|s| s.tick) == [1200, 600]
105
+ assert b.game.snaps.isEmpty()
106
+ ra := a.rewindTo(1300)
107
+ rb := b.rewindTo(1300)
108
+ assert ra.game.rewound == 100 && rb.game.rewound == 1300
109
+ assert GameHelpers.same(ra.game, rb.game)
110
+ assert GameHelpers.same(ra.game, GameHelpers.played(GameHelpers.snapping(io, 600), 0, 1300).game)
111
+ mid := a.rewindTo(500)
112
+ assert mid.game.rewound == 500 && mid.game.snaps.isEmpty()
113
+ on := GameHelpers.played(mid, 500, 1500)
114
+ assert on.game.snaps.map(|s| s.tick) == [1200, 600]
115
+ assert GameHelpers.same(on.game, a.game)
116
+ assert GameHelpers.same(on.rewindTo(700).game, b.rewindTo(700).game)
117
+ assert on.rewindTo(700).game.rewound == 100
118
+ full := GameHelpers.played(TestRig(..GameHelpers.snapping(io, 600), game: Game(..GameHelpers.snapping(io, 600).game, history: Some(History.start(1000, Vec2(x: 800.0, y: 600.0))))), 0, 1100)
119
+ assert full.game.snaps.isEmpty() && !full.game.travels()
120
+
60
121
  primitive GameHelpers =
122
+ fun counted() -> Screen = Counted.start()
123
+
124
+ fun snapping(io: Io, every: Int) -> TestRig<Counted> =
125
+ t := TestRig.mountWith(io, Counted.start())
126
+ TestRig(..t, game: Game(..t.game, snapEvery: every))
127
+
128
+ # Ticks `from` to `to` of a scripted run: Space every 37 ticks, Right held through some
129
+ # stretches, N and M now and then.
130
+ fun played(t: TestRig<Counted>, from: Int, to: Int) -> TestRig<Counted> =
131
+ Range.until(from, to).fold(t, |r, i|
132
+ held := if i % 200 < 70 then r.hold(Key.Right) else r.release(Key.Right)
133
+ keyed := if i % 37 == 5 then held.press(Key.Space) else if i % 450 == 9 then held.press(Key.KeyN) else if i % 450 == 300 then held.press(Key.KeyM) else held
134
+ keyed.tick())
135
+
136
+ fun same(a: Game, b: Game) -> Bool =
137
+ s := GameHelpers.countedOf(a)
138
+ o := GameHelpers.countedOf(b)
139
+ s.ticks == o.ticks && s.keys == o.keys && s.steer == o.steer && s.sum == o.sum
140
+ && a.ticks == b.ticks && a.current == b.current && a.pixels == b.pixels && a.pointer == b.pointer && a.wake == b.wake
141
+ && a.helds.at(0).same(b.helds.at(0)) && a.loops.length() == b.loops.length() && a.tickNow() == b.tickNow()
142
+
143
+ fun countedOf(g: Game) -> Counted = match g.screen()
144
+ Counted as c => c
145
+ _ => Counted.start()
146
+
61
147
  fun game() -> Game =
62
148
  only: Screen := Quiet(n: 0)
63
149
  Game(screens: [only])
64
150
 
151
+ enum Act = Tick(dt: Float) | Bump | Steer(n: Int) | Back | Music(on: Bool)
152
+
153
+ # A screen that counts its ticks, its bumps (Space, or a dispatch) and steers with the
154
+ # arrows, folding them into a sum; Z undoes, N starts its music and M stops it.
155
+ struct Counted[ScreenSlice<Act>](ticks: Int, keys: Int, steer: Int, sum: Int) =
156
+ fun start() -> Counted = Counted(ticks: 0, keys: 0, steer: 0, sum: 0)
157
+
158
+ fun name(self) -> Str = "counted"
159
+
160
+ fun subscriptions(self) -> List<Sub<Act>> = [
161
+ OnFrame(|dt| Tick(dt: dt))
162
+ OnHeld(|h| Steer(n: Int(h.axis(Key.Left, Key.Right))))
163
+ OnKeyDown(key: Key.Space, act: Bump)
164
+ OnKeyDown(key: Key.KeyZ, act: Back)
165
+ OnKeyDown(key: Key.KeyN, act: Music(on: true))
166
+ OnKeyDown(key: Key.KeyM, act: Music(on: false))
167
+ ]
168
+
169
+ fun update(self, a: Act) -> Next<Counted, Act> = match a
170
+ Tick(dt) => Next(state: Counted(..self, ticks: self.ticks + 1, sum: {self.sum * 31 + self.steer + 7 * self.keys} % 1000003))
171
+ Bump => Next(state: Counted(..self, keys: self.keys + 1))
172
+ Steer(n) => Next(state: Counted(..self, steer: n))
173
+ Back => Next(state: self, cmds: [Undo])
174
+ Music(on) => Next(state: self, cmds: [if on then Loop(sound: Sound.Silent, volume: 0.5) else Stop(sound: Sound.Silent)])
175
+
65
176
  # A screen that sleeps through the ticks with nothing to do.
66
177
  struct Quiet[Screen](n: Int) =
67
178
  fun name(self) -> Str = "quiet"
tests/std/game/Input.plum CHANGED
@@ -41,13 +41,16 @@ primitive InputTest[UnitTest] =
41
41
  assert s.screen == Vec2(x: 800.0, y: 600.0) && s.held.isKeyDown(Key.KeyA) && s.events.length() == 2 && s.held.pointer.x == 3.0
42
42
  assert Input().events.isEmpty() && Input().held.same(Held())
43
43
 
44
- # a replay's ticks are in the window of its header
44
+ # a replay's ticks are in the window of its header, and a replay with none is put on one
45
45
  fun aReplaysTicksAreInItsWindow() =
46
46
  r := Replay.decode("plum-replay 0 7 640 480\n- 0 0 0\n65 1 2 3 K65\n").unwrap()
47
47
  assert r.width == 640 && r.ticks.length() == 2
48
48
  assert r.ticks.all(|t| t.screen == Vec2(x: 640.0, y: 480.0))
49
+ assert r.onScreen(320, 200).ticks.at(1).screen == Vec2(x: 640.0, y: 480.0)
50
+ u := Replay.decode("plum-replay 0 7 0 0\n- 0 0 0\n65 1 2 3 K65\n").unwrap()
51
+ assert u.ticks.all(|t| t.screen == Vec2(x: 0.0, y: 0.0))
49
- assert r.onScreen(320, 200).ticks.at(1).screen == Vec2(x: 320.0, y: 200.0)
52
+ assert u.onScreen(320, 200).ticks.at(1).screen == Vec2(x: 320.0, y: 200.0)
50
- assert r.onScreen(320, 200).ticks.at(1).held.isKeyDown(Key.KeyA)
53
+ assert u.onScreen(320, 200).ticks.at(1).held.isKeyDown(Key.KeyA)
51
54
 
52
55
  # key_down_twice_keeps_one_entry
53
56
  fun keyDownTwiceKeepsOneEntry() =
tests/std/game/Line.plum CHANGED
@@ -40,3 +40,15 @@ primitive LineTest[UnitTest] =
40
40
  l := Line(from: Vec2(x: 0.0, y: 0.0), to: Vec2(x: 10.0, y: 10.0))
41
41
  assert Views.hitIn([l], p).isNone()
42
42
  assert Views.hitIn([Line(..l, touch: Enabled)], p).isSome()
43
+
44
+ # a line starts at its x and y, and its width scales as its transform stretches across it
45
+ fun aLineIsPlacedAndScaledAcrossIt() =
46
+ l := Line(x: 3.0, y: 4.0, from: Vec2(x: 0.0, y: 0.0), to: Vec2(x: 10.0, y: 0.0))
47
+ found := Slice<Drawn>()
48
+ Views.drawnIn([l], Affine.Identity, 1.0, found, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
49
+ assert found.at(0).m.e == 3.0 && found.at(0).m.f == 4.0
50
+ wide := Affine(a: 2.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0)
51
+ assert Line.across(wide, Vec2(x: 0.0, y: 0.0), Vec2(x: 10.0, y: 0.0)) == 1.0
52
+ assert Line.across(wide, Vec2(x: 0.0, y: 0.0), Vec2(x: 0.0, y: 10.0)) == 2.0
53
+ assert Line.across(Affine(a: 3.0, b: 0.0, c: 0.0, d: 3.0, e: 1.0, f: 1.0), Vec2(x: 0.0, y: 0.0), Vec2(x: 5.0, y: 7.0)) == 3.0
54
+ assert Line.across(Affine(a: 4.0, b: 0.0, c: 0.0, d: 1.0, e: 0.0, f: 0.0), Vec2(x: 1.0, y: 1.0), Vec2(x: 1.0, y: 1.0)) == 2.0
tests/std/game/Place.plum CHANGED
@@ -46,7 +46,8 @@ primitive PlaceTest[UnitTest] =
46
46
  # a place maps a point into its own coordinates and back
47
47
  fun aPlaceMapsAPointIntoItsOwn() =
48
48
  p := Place.pivoted(10.0, 20.0, 5.0, 5.0).rotateTo(1.0).fade(0.5)
49
- q := p.toLocal(p.local().apply(Vec2(x: 3.0, y: 4.0)))
49
+ q := p.toLocal(p.local().apply(Vec2(x: 3.0, y: 4.0))).unwrap()
50
50
  assert {q.x - 3.0}.abs() < 0.000001 && {q.y - 4.0}.abs() < 0.000001
51
+ assert Place.at(1.0, 2.0).scaleTo(0.0, 1.0).toLocal(Vec2(x: 1.0, y: 2.0)).isNone()
51
52
  assert p.alpha == 0.5
52
53
  assert Place.at(1.0, 2.0).under(Affine.Identity).e == 1.0
tests/std/game/Replay.plum ADDED
@@ -0,0 +1,58 @@
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/math/Vec2
10
+ import std/game/Input
11
+ import std/game/Replay
12
+ import std/game/Screen
13
+ import std/game/ScreenSlice
14
+ import std/game/Game
15
+ import std/game/TestRig
16
+ import std/Test
17
+
18
+ # A 800 by 600 world fitted to the window that keeps the world x of each press.
19
+ struct Clicks[ScreenSlice<Float>](xs: List<Float>) =
20
+ fun name(self) -> Str = "clicks"
21
+
22
+ fun size(self) -> Vec2 = Vec2(x: 800.0, y: 600.0)
23
+
24
+ fun subscriptions(self) -> List<Sub<Float>> = [OnPointerDown(|at| at.x)]
25
+
26
+ fun update(self, x: Float) -> Next<Clicks, Float> = Next(state: Clicks(xs: self.xs.append([x])))
27
+
28
+ primitive ReplayTest[UnitTest] =
29
+ # a tick line says the window when it differs from the last one written, and reading it back gives each tick its window
30
+ fun aTickSaysTheWindowWhenItChanges() =
31
+ big := Input().sized(1600.0, 600.0)
32
+ r := Replay(seed: 3, width: 800, height: 600, ticks: [Input().sized(800.0, 600.0), big, big, Input().sized(800.0, 600.0), Input()])
33
+ text := r.encode()
34
+ assert text == "plum-replay 0 3 800 600\n- 0 0 0\n- 0 0 0 S1600,600\n- 0 0 0\n- 0 0 0 S800,600\n- 0 0 0\n"
35
+ back := Replay.decode(text).unwrap()
36
+ assert back.ticks.map(|t| t.screen.x) == [800.0, 1600.0, 1600.0, 800.0, 800.0]
37
+ assert back.encode() == text
38
+ w := Replay.written([big, big, Input().sized(320.5, 200.0)], Vec2(x: 0.0, y: 0.0))
39
+ assert w.text() == "- 0 0 0 S1600,600\n- 0 0 0\n- 0 0 0 S641:-1,200\n"
40
+ assert w.size == Vec2(x: 320.5, y: 200.0)
41
+ assert Replay.decode("plum-replay 0 3 0 0\n- 0 0 0 S0,600\n").isErr()
42
+ assert Replay.decode("plum-replay 0 3 0 0\n- 0 0 0 S12 K32\n").isErr()
43
+
44
+ # a run resized while it is recorded replays to the same game, its window following the recording
45
+ fun aResizedRunReplaysToTheSameGame() =
46
+ a := TestRig.mount(io, Clicks(xs: Nil)).record(9).clickAt(800.0, 300.0).tick().resize(1600.0, 600.0).clickAt(800.0, 300.0).tick().tick()
47
+ assert a.screen.xs == [800.0, 400.0]
48
+ back := Replay.decode(a.recorded().encode()).unwrap()
49
+ assert back.ticks.map(|t| t.screen.x) == [800.0, 1600.0, 1600.0]
50
+ b := TestRig.mount(io, Clicks(xs: Nil)).replay(back)
51
+ assert b.screen.xs == a.screen.xs
52
+ assert b.pixels == Vec2(x: 1600.0, y: 600.0) && b.game.pixels == Vec2(x: 1600.0, y: 600.0)
53
+
54
+ # a frame's input in a window of its own resizes the rig, as the host's frame would
55
+ fun aFramesWindowResizesTheRig() =
56
+ t := TestRig.mount(io, Clicks(xs: Nil)).frame(Input(events: [PointerDown(x: 800.0, y: 300.0)]).sized(1600.0, 600.0), Ticker.Tick)
57
+ assert t.pixels == Vec2(x: 1600.0, y: 600.0)
58
+ assert t.screen.xs == [400.0]
tests/std/game/ScreenSlice.plum CHANGED
@@ -78,6 +78,23 @@ struct SleepyScreen[ScreenSlice<Int>](steering: Bool, seen: Int) =
78
78
 
79
79
  fun update(self, n: Int) -> Next<SleepyScreen, Int> = Next(state: SleepyScreen(..self, seen: self.seen + 1))
80
80
 
81
+ # A screen that logs the other mouse buttons.
82
+ struct ButtonScreen[ScreenSlice<Str>](log: List<Str>) =
83
+ fun name(self) -> Str = "buttons"
84
+
85
+ fun subscriptions(self) -> List<Sub<Str>> = [
86
+ OnButtonDown(|b, at| "down {b} at {at.x}")
87
+ OnButtonUp(|b, at| "up {b} at {at.x}")
88
+ ]
89
+
90
+ fun update(self, s: Str) -> Next<ButtonScreen, Str> = Next(state: ButtonScreen(log: self.log.append([s])))
91
+
92
+ # A screen whose action `n` asks for `n - 1` after it, down to 0.
93
+ struct ChainScreen[ScreenSlice<Int>](n: Int) =
94
+ fun name(self) -> Str = "chain"
95
+
96
+ fun update(self, k: Int) -> Next<ChainScreen, Int> = Next(state: ChainScreen(n: self.n + 1), then: if k > 0 then [k - 1] else Nil)
97
+
81
98
  primitive ScreenSliceTest[UnitTest] =
82
99
  # a wheel turn reaches `OnWheel` where the pointer is, and `OnHeld` sees what is held
83
100
  # after the tick's events, the pointer with it
@@ -120,3 +137,23 @@ primitive ScreenSliceTest[UnitTest] =
120
137
  assert t.screen.seen == 3
121
138
  u := TestRig.mount(io, SleepyScreen(steering: false, seen: 0)).tick().hold(Key.Left).tick().ticks(3)
122
139
  assert u.screen.seen == 0 && u.game.skipped >= 3
140
+
141
+ # an `OnDemand` screen subscribed to `OnHeld` sleeps while nothing is held, and wakes once something is
142
+ fun onHeldSleepsWhileNothingIsHeld() =
143
+ t := TestRig.mount(io, SleepyScreen(steering: true, seen: 0)).tick().ticks(5)
144
+ assert t.game.skipped >= 5
145
+ seen := t.screen.seen
146
+ u := t.hold(Key.Left).tick().ticks(3)
147
+ assert u.screen.seen == seen + 4
148
+ assert !Held().any() && Held(keys: [Key.Left]).any() && Held(mouse: true).any() && Held(buttons: [Mouse.Right]).any()
149
+
150
+ # the right and middle buttons reach `OnButtonDown` and `OnButtonUp` with the button and where it went in the world
151
+ fun theOtherButtonsReachTheirSubscriptions() =
152
+ t := TestRig.mount(io, ButtonScreen(log: Nil)).send(ButtonDown(button: Mouse.Right, x: 10.0, y: 20.0)).send(ButtonUp(button: Mouse.Right, x: 11.0, y: 20.0)).send(ButtonDown(button: Mouse.Middle, x: 3.0, y: 4.0)).tick()
153
+ assert t.screen.log.join(", ") == "down 1 at 10.0, up 1 at 11.0, down 2 at 3.0"
154
+ assert KeyDown(key: Key.Space).buttonDown() == -1 && ButtonUp(button: 2, x: 0.0, y: 0.0).buttonUp() == 2
155
+
156
+ # an action whose `then` asks for itself is stepped no deeper than the limit
157
+ fun theThenLimitIsDeep() =
158
+ t := TestRig.mount(io, ChainScreen(n: 0)).dispatch(Delivery.ThenDepth - 1)
159
+ assert t.screen.n == Delivery.ThenDepth
tests/std/game/Sprite.plum CHANGED
@@ -30,3 +30,12 @@ primitive SpriteTest[UnitTest] =
30
30
  assert Sprite.frameAt(0.13, 8.0, 4) == 1
31
31
  assert Sprite.frameAt(0.5, 8.0, 4) == 0
32
32
  assert Sprite.frameAt(9.0, 0.0, 1) == 0
33
+
34
+ # a strip of no frames shows frame 0, and before 0 s the strip plays backwards from its last frame
35
+ fun aStripOfNoFramesAndANegativeClock() =
36
+ assert Sprite.frameAt(1.0, 8.0, 0) == 0
37
+ assert Sprite.frameAt(1.0, 8.0, -3) == 0
38
+ assert Sprite.frameAt(-0.01, 8.0, 4) == 3
39
+ assert Sprite.frameAt(-0.13, 8.0, 4) == 2
40
+ assert Sprite.frameAt(-0.5, 8.0, 4) == 0
41
+ assert Sprite.frameAt(0.0 / 0.0, 8.0, 4) == 0
tests/std/game/View.plum CHANGED
@@ -19,6 +19,7 @@ import std/game/Group
19
19
  import std/game/Label
20
20
  import std/game/Circle
21
21
  import std/game/Overlay
22
+ import std/game/Button
22
23
  import std/game/View
23
24
  import std/game/Screen
24
25
  import std/Test
@@ -112,6 +113,27 @@ primitive ViewTest[UnitTest] =
112
113
  assert Math.near(c.x, 200.0, 0.001) && Math.near(c.y, 150.0, 0.001)
113
114
  assert Views.worldIn(items, Box(w: 1.0, h: 1.0, color: Color.White), Affine.Identity).isNone()
114
115
 
116
+ # an item scaled flat takes no press, nor does what is under it
117
+ fun aFlatItemTakesNoPress() =
118
+ box := Box(w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
119
+ assert @sameRef(Views.hitIn([Squashed(sx: 1.0) { box }], Vec2(x: 5.0, y: 5.0)).unwrap(), box)
120
+ assert Views.hitIn([Squashed(sx: 0.0) { box }], Vec2(x: 5.0, y: 5.0)).isNone()
121
+ assert Views.hitIn([Squashed(sx: 0.0) { box }], Vec2(x: 0.0, y: 0.0)).isNone()
122
+
123
+ # a group that says it takes presses is still never hit itself: it has no bounds
124
+ fun anEnabledGroupIsNeverHitItself() =
125
+ box := Box(w: 10.0, h: 10.0, color: Color.White, touch: Enabled)
126
+ assert Views.hitIn([Group(touch: Enabled) { }], Vec2(x: 0.0, y: 0.0)).isNone()
127
+ assert @sameRef(Views.hitIn([Group(touch: Enabled) { box }], Vec2(x: 5.0, y: 5.0)).unwrap(), box)
128
+
129
+ # stepping a button steps the actors among its children
130
+ fun steppingAButtonStepsItsChildren() =
131
+ stepped := Views.stepIn([Button(w: 10.0, h: 10.0, on: 1) { Stepper(time: 1.0) }], 0.5)
132
+ kids := match stepped.at(0)
133
+ Button<Int> as b => b.children
134
+ _ => Nil
135
+ assert kids.length() == 1 && ViewHelpers.timeOf(kids.at(0)) == 1.5
136
+
115
137
  # the draw list holds every item and what is under it, and culling leaves out what misses the area
116
138
  fun theDrawListHoldsEveryItemAndWhat() =
117
139
  items := [Box(w: 10.0, h: 10.0, color: Color.White), Group(x: 5000.0) { Circle(r: 2.0, color: Color.White), Label(text: "far", size: 24.0) }, Box(x: 5000.0, w: 10.0, h: 10.0, color: Color.White)]
@@ -216,6 +238,11 @@ struct Holder[Actor](time: Float, kids: List<Stepper>) =
216
238
 
217
239
  fun step(self, dt: Float) -> Holder = Holder(time: self.time + dt, kids: Views.stepAll(self.kids, dt / 2.0))
218
240
 
241
+ struct Squashed[View](sx: Float, children: List<View>) =
242
+ fun place(self) -> Place = Place.at(0.0, 0.0).scaleTo(self.sx, 1.0)
243
+
244
+ fun view(self) -> List<View> = self.children
245
+
219
246
  struct TurnedGroup[View](x: Float, y: Float, children: List<View>) =
220
247
  fun place(self) -> Place = Place.at(self.x, self.y).rotateTo(Float.HalfPi)
221
248
 
tests/std/math/Aabb.plum CHANGED
@@ -45,3 +45,9 @@ primitive AabbTest[UnitTest] =
45
45
  assert a.contains(a)
46
46
  assert a.overlaps(Aabb.of(2.0, 2.0, 1.0, 1.0))
47
47
  assert a.distSq(Vec2(x: 2.0, y: 2.0)) == 0.0
48
+
49
+ # shrinking moves each side in, and a negative amount moves them out
50
+ fun shrinkingMovesEachSideIn() =
51
+ a := Aabb.of(0.0, 0.0, 800.0, 600.0)
52
+ assert a.shrink(10.0) == Aabb(min: Vec2(x: 10.0, y: 10.0), max: Vec2(x: 790.0, y: 590.0))
53
+ assert a.shrink(-5.0) == Aabb.of(-5.0, -5.0, 810.0, 610.0)
tests/std/math/Dice.plum ADDED
@@ -0,0 +1,37 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Bool
4
+ import std/collections/List
5
+ import std/math/Vec2
6
+ import std/math/Random
7
+ import std/math/Dice
8
+ import std/Test
9
+
10
+ primitive DiceTest[UnitTest] =
11
+ # the same tick, kind and id always give the same key, and a change to any of them another
12
+ fun aKeyIsItsTickKindAndId() =
13
+ d := Dice(seed: 9)
14
+ assert d.roll(4, 1, 2).intAt(0) == Dice(seed: 9).roll(4, 1, 2).intAt(0)
15
+ assert d.roll(4, 1, 2).intAt(0) != Dice(seed: 10).roll(4, 1, 2).intAt(0)
16
+ assert d.roll(4, 1, 2).intAt(0) != d.roll(5, 1, 2).intAt(0)
17
+ assert d.roll(4, 1, 2).intAt(0) != d.roll(4, 2, 2).intAt(0)
18
+ assert d.roll(4, 1, 2).intAt(0) != d.roll(4, 1, 3).intAt(0)
19
+
20
+ # kinds never meet: a kind and an id that add up alike still draw apart, over many of them
21
+ fun kindsNeverMeet() =
22
+ d := Dice(seed: 3)
23
+ assert d.roll(0, 0, 1).seed != d.roll(0, 1, 0).seed
24
+ keys := Range.until(0, 8).fold(Nil, |acc, k| acc.append(Range.until(0, 8).map(|i| d.roll(7, k, i).seed)))
25
+ assert Range.until(0, keys.length()).all(|i| Range.until(0, keys.length()).all(|j| i == j || keys.at(i) != keys.at(j)))
26
+
27
+ # a key's floats are uniform
28
+ fun aKeysFloatsAreUniform() =
29
+ d := Dice(seed: 77)
30
+ total := Range.until(0, 4000).fold(0.0, |s, t| s + d.roll(t, 2, 5).floatAt(0))
31
+ assert total > 1900.0 && total < 2100.0
32
+
33
+ # the scatter stands each point at the primes times its index, modulo the sides
34
+ fun theScatterIsFixed() =
35
+ assert Dice.scatter(0, 800, 600) == Vec2(x: 0.0, y: 0.0)
36
+ assert Dice.scatter(1, 800, 600) == Vec2(x: 719.0, y: 329.0)
37
+ assert Dice.scatter(3, 800, 200) == Vec2(x: Float({3 * 7919} % 800), y: Float({3 * 104729} % 200))