plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
73e7dd0
— Peter John
2026-11-13T22:40:48+05:30
game framework ports from master (T5): an actor steps what it holds as far as a value can (`Views.stepIn` steps an `Actor` without looking inside it or making its view, and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is: making a view again is only possible for a kind std knows, so master's `View.holdsActors()` is std's two containers here and its kit check `unsteppedIn` has nothing to find, as nothing is stepped behind the screen's back; game.md says why); frames on demand in the hosts: the frame entry point ends with `Game.hostFrame`, which tells the host an idle frame (`Game.frameIdle`, master's extern) and otherwise counts the frame the host is about to draw (`frameDrawn`), so a live `OnDemand` screen goes idle; the browser skips an idle frame's draw, keeps the canvas and asks for no frame until a key, press, move, wheel, resize or blur (a replay keeps its frames), the native host has `PlumGame::idle()` and `plum-game` skips the draw; development runs: `plum run --dev` (the page gets `plumTimeTravel` before the bridge, `ReplayMode.Dev` = 3, refused by `plum build`, `--replay` and a non-game), the game keeps its history from the first frame and takes master's time travel keys (`[`, `]`, `\`, Ctrl/Cmd+Z, Ctrl/Cmd+Y or Shift+Z; std/game/History's `TravelKeys` and `TravelCmd`, as values: `frame(now) -> TravelFrame`), kept from the game's poll (`Input.poll(io, skip)`), done by `Game.devFrame`/`travelCommand`, with `devLine` drawn along the bottom; a rewind keeps `dev` and `paused`; no `remakeGame`: `timeTravel` remakes the game from the screens it was made with; the bridge's Cmd keyup fix, short taps kept for a frame and undo/redo chords kept from the browser, from master; `PlumGame::dev()`; the window's size on each tick's input: `Input.screen` (a field default, 0 by 0) and `Input.sized(w, h)`, set by the poll from `Gfx`, kept through the ticker's frame, a decoded replay's ticks on its header's window (`Replay.onScreen`), and `Game.update` is `step` with `input.screen` (0 by 0 leaves the window); `Clock` is `Ticker` (`Ticker.Tick`, `Ticker()` with field defaults in place of `Clock.create()`), moved to std/game/Game.plum beside `GameRun(game, ticker)`, the host's state, now std's with `start`, `frame` and `draw`, so the compiler's game entry (core/game_entry.rs) is three one-line functions calling it (its own `gameTicks`/`gameTick` gone; the in-place test names `GameRun.ticks` and `GameRun.shown`); a `Label`'s width from Arial's advance widths (`Label.Advances`, four digits a character from space to `~`, a digit's width past ASCII, none for control and continuation bytes) in place of 0.6 of the size a letter, and the bridge lays text out by the same table (`ADVANCES`, a host test checks they match) and draws its atlas in Arial, Helvetica or Liberation Sans first; master still estimates, and a host call measuring text would make a tick that hits a label read the host; `plum compile <folder>` compiles the folder's file with `main`, as `run` and `build` do; tests: std (tests/std/game/Game.plum: the window from the input, the ticker keeping it, a development run's history and commands, a frame counted as drawn; History: the travel keys' commands and what they keep from the game; Input: `sized`, a replay's window; View: stepping inside groups and overlays, not inside an actor or a kind of your own; Label: real widths), host tests (an `OnDemand` screen's idle frames, waking on a key and a resize with the new window on the input, an `Always` screen never idle, a development run's keys, line, pause, step, undo and resume, none of it outside `--dev`, the bridge's table), CLI tests (`compile <folder>`, `--dev` refused with `--replay` and for a program), the page test for `plumTimeTravel`, web-test `an_idle_page_sleeps_and_a_dev_run_travels` on two_screens (the page's `__plumDrawLog` probe, from master); docs: game.md (stepping, the label width, the ticker, the window on the input, the development keys, frames on demand in the hosts, the "Beside master" rows and "Not ported"), tools.md (`--dev`, `compile` of a folder), backlog (the five items done), the web-test README
- benchmarks/screen_views/orbit.plum +1 -1
- benchmarks/screen_views/scale.plum +2 -2
- compiler/cli/src/game.rs +31 -4
- compiler/cli/src/main.rs +15 -7
- compiler/cli/tests/cli/game_in_place_test.rs +3 -4
- compiler/cli/tests/cli/replay_test.rs +7 -1
- compiler/cli/tests/cli/run_folder_test.rs +19 -0
- compiler/core/src/game_entry.rs +33 -27
- compiler/game/src/host.rs +26 -3
- compiler/game/src/main.rs +5 -1
- compiler/game/tests/host_test.rs +135 -0
- compiler/game/web-test/README.md +1 -1
- compiler/game/web-test/src/lib.rs +124 -8
- compiler/game/web-test/tests/web_check.rs +14 -0
- compiler/game/web/plum_bridge.js +117 -17
- docs/backlog.md +1 -5
- docs/game.md +29 -18
- docs/tools.md +3 -2
- std/game/Game.plum +201 -11
- std/game/Gfx.plum +1 -1
- std/game/History.plum +69 -0
- std/game/Input.plum +23 -116
- std/game/Label.plum +27 -4
- std/game/Replay.plum +15 -3
- std/game/TestRig.plum +13 -13
- std/game/View.plum +10 -2
- tests/benchmarks/screen_views/orbit.plum +2 -2
- tests/examples/games/balloonpop/screens/PlaygroundScreen.plum +3 -3
- tests/examples/games/orbitrunner/screens/PlayingScreen.plum +6 -6
- tests/port/game/determinism.plum +9 -9
- tests/port/game/replay.plum +6 -6
- tests/std/game/Game.plum +71 -0
- tests/std/game/History.plum +37 -0
- tests/std/game/Input.plum +15 -0
- tests/std/game/Label.plum +24 -7
- tests/std/game/View.plum +42 -0
benchmarks/screen_views/orbit.plum
CHANGED
|
@@ -54,7 +54,7 @@ primitive OrbitBench[App] =
|
|
|
54
54
|
Timing.hash(head.append(orbs.reverse()).append(mines.reverse()))
|
|
55
55
|
|
|
56
56
|
fun tickOnce(io: Io, g: Game, inp: Input, paint: Bool) -> Game =
|
|
57
|
-
next := g.update(io, inp,
|
|
57
|
+
next := g.update(io, inp, Ticker.Tick)
|
|
58
58
|
if paint
|
|
59
59
|
next.draw(io)
|
|
60
60
|
next
|
benchmarks/screen_views/scale.plum
CHANGED
|
@@ -73,7 +73,7 @@ primitive ScaleBench[App] =
|
|
|
73
73
|
_ => ScaleBench.crowdOf(g).frameSum()
|
|
74
74
|
|
|
75
75
|
fun tickOnce(io: Io, g: Game, paint: Bool) -> Game =
|
|
76
|
-
next := g.update(io, Input.create(),
|
|
76
|
+
next := g.update(io, Input.create(), Ticker.Tick)
|
|
77
77
|
if paint
|
|
78
78
|
next.draw(io)
|
|
79
79
|
next
|
|
@@ -81,7 +81,7 @@ primitive ScaleBench[App] =
|
|
|
81
81
|
# `ticks` ticks of `s` on an 800 by 600 screen, with no host (a test's).
|
|
82
82
|
fun run(io: Io, s: CrowdScreen, ticks: Int) -> CrowdScreen =
|
|
83
83
|
only: Screen := s
|
|
84
|
-
crowdOf(Range.until(0, ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input.create(),
|
|
84
|
+
crowdOf(Range.until(0, ticks).fold(Game(screens: [only]), |g, t| g.step(io, Input.create(), Ticker.Tick, Vec2(x: 800.0, y: 600.0))))
|
|
85
85
|
|
|
86
86
|
fun main(io: Io) =
|
|
87
87
|
args := io.args()
|
compiler/cli/src/game.rs
CHANGED
|
@@ -89,12 +89,16 @@ struct Site {
|
|
|
89
89
|
assets: PathBuf,
|
|
90
90
|
/// Served by `plum run` with the watcher: the page gets the dev script and its events.
|
|
91
91
|
dev: bool,
|
|
92
|
+
/// Served by `plum run --dev`: the page runs the game with time travel and its keys
|
|
93
|
+
/// (std/game/History's `TravelKeys`), switched on before the bridge starts. Never in a
|
|
94
|
+
/// `plum build`.
|
|
95
|
+
travel: bool,
|
|
92
96
|
}
|
|
93
97
|
|
|
94
98
|
impl Site {
|
|
95
99
|
fn new(wasm: Vec<u8>, assets: PathBuf) -> Result<Site> {
|
|
96
100
|
let preload = listFiles(&assets)?.iter().map(|f| format!("{f}\n")).collect();
|
|
97
|
-
Ok(Site { wasm, preload, assets, dev: false })
|
|
101
|
+
Ok(Site { wasm, preload, assets, dev: false, travel: false })
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/// The body and content type of the file at the URL path `rel`.
|
|
@@ -102,11 +106,14 @@ impl Site {
|
|
|
102
106
|
let rel = if rel.is_empty() { "index.html" } else { rel };
|
|
103
107
|
match rel {
|
|
104
108
|
"index.html" => {
|
|
105
|
-
let html = if self.dev {
|
|
109
|
+
let mut html = if self.dev {
|
|
106
110
|
INDEX_HTML.replace("</body>", " <script src=\"plum_dev.js\"></script>\n</body>")
|
|
107
111
|
} else {
|
|
108
112
|
INDEX_HTML.to_string()
|
|
109
113
|
};
|
|
114
|
+
if self.travel {
|
|
115
|
+
html = html.replace("<script src=\"plum_bridge.js\">", "<script>globalThis.plumTimeTravel = true;</script>\n <script src=\"plum_bridge.js\">");
|
|
116
|
+
}
|
|
110
117
|
return Some((html.into_bytes(), mime("index.html")));
|
|
111
118
|
}
|
|
112
119
|
"plum_dev.js" if self.dev => return Some((DEV_JS.as_bytes().to_vec(), mime("plum_dev.js"))),
|
|
@@ -517,8 +524,8 @@ pub(crate) fn gameAssets(file: &Path, assets: Option<PathBuf>) -> Result<PathBuf
|
|
|
517
524
|
|
|
518
525
|
/// `plum build` of a game: writes the static site to `-o` (default `dist` in the current folder).
|
|
519
526
|
pub fn buildGame(file: &Path, wasm: Vec<u8>, options: crate::GameOptions) -> Result<()> {
|
|
520
|
-
if options.port.is_some() || options.noOpen || options.noWatch {
|
|
527
|
+
if options.port.is_some() || options.noOpen || options.noWatch || options.dev {
|
|
521
|
-
bail!("--port, --no-open
|
|
528
|
+
bail!("--port, --no-open, --no-watch and --dev are for `plum run`");
|
|
522
529
|
}
|
|
523
530
|
let site = Site::new(wasm, gameAssets(file, options.assets)?)?;
|
|
524
531
|
let dist = options.output.unwrap_or_else(|| PathBuf::from("dist"));
|
|
@@ -533,6 +540,10 @@ pub fn serveGame(file: &Path, lib: &Path, wasm: Vec<u8>, options: crate::GameOpt
|
|
|
533
540
|
let mut site = Site::new(wasm, gameAssets(file, options.assets)?)?;
|
|
534
541
|
let watching = !options.noWatch;
|
|
535
542
|
site.dev = watching;
|
|
543
|
+
site.travel = options.dev;
|
|
544
|
+
if options.dev {
|
|
545
|
+
println!("time travel: [ and ] step a tick, \\ pauses and resumes, Ctrl or Cmd+Z undoes, Ctrl or Cmd+Y (or Shift+Z) redoes");
|
|
546
|
+
}
|
|
536
547
|
let assets = site.assets.clone();
|
|
537
548
|
// The baseline is taken before the URL is printed, so an edit right after it is seen.
|
|
538
549
|
let baseline = (sourceStamps(file, lib), assetStamps(&assets));
|
|
@@ -586,6 +597,22 @@ mod serverTests {
|
|
|
586
597
|
out
|
|
587
598
|
}
|
|
588
599
|
|
|
600
|
+
#[test]
|
|
601
|
+
fn onlyADevRunSwitchesTimeTravelOnInThePage() {
|
|
602
|
+
let dir = std::env::temp_dir().join(format!("plum_travel_site_{}", std::process::id()));
|
|
603
|
+
fs::create_dir_all(&dir).unwrap();
|
|
604
|
+
let server = serverWith(dir.clone());
|
|
605
|
+
let page = request(&server, "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n");
|
|
606
|
+
assert!(page.contains("plum_bridge.js") && !page.contains("plumTimeTravel"), "{page}");
|
|
607
|
+
let mut site = Site::new(Vec::new(), dir.clone()).unwrap();
|
|
608
|
+
let _ = fs::remove_dir_all(&dir);
|
|
609
|
+
site.travel = true;
|
|
610
|
+
let (html, _) = site.get("").unwrap();
|
|
611
|
+
let html = String::from_utf8(html).unwrap();
|
|
612
|
+
let (on, bridge) = (html.find("plumTimeTravel = true").unwrap(), html.find("src=\"plum_bridge.js\"").unwrap());
|
|
613
|
+
assert!(on < bridge, "{html}");
|
|
614
|
+
}
|
|
615
|
+
|
|
589
616
|
#[test]
|
|
590
617
|
fn onlyLoopbackHostsAreAllowed() {
|
|
591
618
|
assert!(hostAllowed("127.0.0.1:8080"));
|
compiler/cli/src/main.rs
CHANGED
|
@@ -40,7 +40,7 @@ enum Command {
|
|
|
40
40
|
},
|
|
41
41
|
/// Compile a Plum source file to WASM
|
|
42
42
|
Compile {
|
|
43
|
-
/// Source file to compile
|
|
43
|
+
/// Source file to compile, or a folder holding one file with a `main` (its `.wasm` is written beside that file)
|
|
44
44
|
file: std::path::PathBuf,
|
|
45
45
|
/// Output path (default: input with .wasm extension)
|
|
46
46
|
#[arg(short, long)]
|
|
@@ -97,6 +97,10 @@ enum Command {
|
|
|
97
97
|
/// Games: replay this recorded run headless (no browser) and print the draw calls of its last frame
|
|
98
98
|
#[arg(long)]
|
|
99
99
|
replay: Option<std::path::PathBuf>,
|
|
100
|
+
/// Games: a development run with time travel: `[` and `]` step a tick back and forward, `\` pauses
|
|
101
|
+
/// and resumes, Ctrl or Cmd with Z undoes and with Y (or Shift and Z) redoes
|
|
102
|
+
#[arg(long)]
|
|
103
|
+
dev: bool,
|
|
100
104
|
/// Root directory `import <path>` is resolved against (`import std/x` -> `<lib-path>/std/x.plum`;
|
|
101
105
|
/// default: `.` when it holds `std`, else the repository plum was built from)
|
|
102
106
|
#[arg(long)]
|
|
@@ -205,15 +209,15 @@ fn run() -> Result<()> {
|
|
|
205
209
|
match cli.command {
|
|
206
210
|
Command::Format { file, check, stdin } => cmdFormat(file, check, stdin),
|
|
207
211
|
Command::Compile { file, output, lib_path, explain_fusion, no_fusion, no_fbip } => {
|
|
208
|
-
cmdCompile(file, output, libPathOrDefault(lib_path), fusionFlags(explain_fusion, no_fusion, no_fbip))
|
|
212
|
+
cmdCompile(program::entryFile(&file)?, output, libPathOrDefault(lib_path), fusionFlags(explain_fusion, no_fusion, no_fbip))
|
|
209
213
|
}
|
|
210
214
|
Command::Check { paths, lib_path } => cmdCheck(paths, libPathOrDefault(lib_path)),
|
|
211
|
-
Command::Run { file, lib_path, explain_fusion, no_fusion, no_fbip, assets, port, no_open, no_watch, replay, args } => {
|
|
215
|
+
Command::Run { file, lib_path, explain_fusion, no_fusion, no_fbip, assets, port, no_open, no_watch, replay, dev, args } => {
|
|
212
216
|
plum_host::setProgramArgs(args);
|
|
213
|
-
cmdRun(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay })
|
|
217
|
+
cmdRun(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port, noOpen: no_open, noWatch: no_watch, output: None, replay, dev })
|
|
214
218
|
}
|
|
215
219
|
Command::Build { file, output, lib_path, assets, explain_fusion, no_fusion, no_fbip } => {
|
|
216
|
-
cmdBuild(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None })
|
|
220
|
+
cmdBuild(program::entryFile(&file)?, lib_path, fusionFlags(explain_fusion, no_fusion, no_fbip), GameOptions { assets, port: None, noOpen: false, noWatch: false, output, replay: None, dev: false })
|
|
217
221
|
}
|
|
218
222
|
Command::Test { paths, lib_path, explain_fusion, no_fusion, no_fbip, timeout, filter, watch } => {
|
|
219
223
|
let options = TestOptions { fusion: fusionFlags(explain_fusion, no_fusion, no_fbip), timeout: testTimeout(timeout)?, filter };
|
|
@@ -276,6 +280,8 @@ pub struct GameOptions {
|
|
|
276
280
|
pub output: Option<std::path::PathBuf>,
|
|
277
281
|
/// `plum run --replay`.
|
|
278
282
|
pub replay: Option<std::path::PathBuf>,
|
|
283
|
+
/// `plum run --dev`: time travel and its keys in the page (std/game/History's `TravelKeys`).
|
|
284
|
+
pub dev: bool,
|
|
279
285
|
}
|
|
280
286
|
|
|
281
287
|
impl GameOptions {
|
|
@@ -291,6 +297,8 @@ impl GameOptions {
|
|
|
291
297
|
Some("--no-watch")
|
|
292
298
|
} else if self.replay.is_some() {
|
|
293
299
|
Some("--replay")
|
|
300
|
+
} else if self.dev {
|
|
301
|
+
Some("--dev")
|
|
294
302
|
} else {
|
|
295
303
|
None
|
|
296
304
|
}
|
|
@@ -391,8 +399,8 @@ fn cmdRun(
|
|
|
391
399
|
let program = program::compileProgram(&file, &lib, fusion)?;
|
|
392
400
|
if program.isGame {
|
|
393
401
|
if let Some(replay) = &gameOptions.replay {
|
|
394
|
-
if gameOptions.port.is_some() || gameOptions.noOpen || gameOptions.noWatch {
|
|
402
|
+
if gameOptions.port.is_some() || gameOptions.noOpen || gameOptions.noWatch || gameOptions.dev {
|
|
395
|
-
anyhow::bail!("--replay runs the game headless: --port, --no-open
|
|
403
|
+
anyhow::bail!("--replay runs the game headless: --port, --no-open, --no-watch and --dev don't apply");
|
|
396
404
|
}
|
|
397
405
|
return replay::replayGame(&file, &program.wasm, gameOptions.assets, replay);
|
|
398
406
|
}
|
compiler/cli/tests/cli/game_in_place_test.rs
CHANGED
|
@@ -40,12 +40,11 @@ fn assertKept(game: &str, want: &[(&str, usize)]) {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
const TICK: &[(&str, usize)] = &[
|
|
43
|
-
("gameTick", 1),
|
|
44
|
-
("
|
|
43
|
+
("GameRun.ticks", 1),
|
|
44
|
+
("GameRun.shown", 1),
|
|
45
45
|
("Game.step", 1),
|
|
46
46
|
("Game.run", 1),
|
|
47
47
|
("Game.obey", 2),
|
|
48
|
-
("Clock.playing", 1),
|
|
49
48
|
("Viewport.update", 2),
|
|
50
49
|
];
|
|
51
50
|
|
|
@@ -58,7 +57,7 @@ fn orbitRunnerKeepsItsInPlaceSpreads() {
|
|
|
58
57
|
("PlayingScreen.newOrb", 1),
|
|
59
58
|
("PlayingScreen.newMine$unique", 1),
|
|
60
59
|
("Mine.step", 1),
|
|
61
|
-
("Mine.put
|
|
60
|
+
("Mine.put", 1),
|
|
62
61
|
("Orb.put$unique", 1),
|
|
63
62
|
]);
|
|
64
63
|
assertKept("examples/games/orbitrunner/OrbitRunner.plum", &want);
|
compiler/cli/tests/cli/replay_test.rs
CHANGED
|
@@ -90,9 +90,15 @@ fn replayFlagRefusesABadFileAndBrowserFlags() {
|
|
|
90
90
|
assert!(!ok && stderr.contains("not a plum replay"), "{stderr}");
|
|
91
91
|
let (ok, _, stderr) = runReplay("examples/games/orbitrunner/OrbitRunner.plum", &file, &["--no-open"]);
|
|
92
92
|
assert!(!ok && stderr.contains("--replay runs the game headless"), "{stderr}");
|
|
93
|
+
let (ok, _, stderr) = runReplay("examples/games/orbitrunner/OrbitRunner.plum", &file, &["--dev"]);
|
|
94
|
+
assert!(!ok && stderr.contains("--replay runs the game headless") && stderr.contains("--dev"), "{stderr}");
|
|
93
95
|
let prog = dir.join("app.plum");
|
|
94
96
|
std::fs::write(&prog, "import std/Str\nimport std/Io\nimport std/App\nprimitive Main[App] =\n fun main(io: Io) =\n io.printLn(\"hi\")\n").unwrap();
|
|
95
97
|
let (ok, _, stderr) = runReplay(prog.to_str().unwrap(), &file, &[]);
|
|
96
|
-
let _ = std::fs::remove_dir_all(&dir);
|
|
97
98
|
assert!(!ok && stderr.contains("--replay is only for games"), "{stderr}");
|
|
99
|
+
// `--dev` is a game's too.
|
|
100
|
+
let out = Command::new(plumBin()).current_dir(root()).args(["run", prog.to_str().unwrap(), "--dev"]).output().unwrap();
|
|
101
|
+
let _ = std::fs::remove_dir_all(&dir);
|
|
102
|
+
let stderr = String::from_utf8_lossy(&out.stderr);
|
|
103
|
+
assert!(!out.status.success() && stderr.contains("--dev is only for games"), "{stderr}");
|
|
98
104
|
}
|
compiler/cli/tests/cli/run_folder_test.rs
CHANGED
|
@@ -50,3 +50,22 @@ fn runGameFolderIsItsMainFile() {
|
|
|
50
50
|
assert!(!byFile.1.is_empty());
|
|
51
51
|
assert_eq!(byFolder.1, byFile.1);
|
|
52
52
|
}
|
|
53
|
+
|
|
54
|
+
/// `plum compile <folder>` compiles the folder's one file with a `main`, writing its `.wasm`
|
|
55
|
+
/// beside that file (or to `-o`); none is the same error as `plum run`'s.
|
|
56
|
+
#[test]
|
|
57
|
+
fn compileFolderCompilesItsOneMain() {
|
|
58
|
+
let dir = Scratch::new("compile_folder_one");
|
|
59
|
+
std::fs::write(dir.join("App.plum"), APP).unwrap();
|
|
60
|
+
std::fs::write(dir.join("Helper.plum"), "primitive Main =\n fun helper() -> Int = 1\n").unwrap();
|
|
61
|
+
let (ok, _, stderr) = run(&["compile", dir.path().to_str().unwrap()]);
|
|
62
|
+
assert!(ok, "{stderr}");
|
|
63
|
+
assert!(dir.join("App.wasm").is_file(), "{stderr}");
|
|
64
|
+
let out = dir.join("out.wasm");
|
|
65
|
+
let (ok, _, stderr) = run(&["compile", dir.path().to_str().unwrap(), "-o", out.to_str().unwrap()]);
|
|
66
|
+
assert!(ok && out.is_file(), "{stderr}");
|
|
67
|
+
let none = Scratch::new("compile_folder_none");
|
|
68
|
+
std::fs::write(none.join("Helper.plum"), "primitive Main =\n fun helper() -> Int = 1\n").unwrap();
|
|
69
|
+
let (ok, _, stderr) = run(&["compile", none.path().to_str().unwrap()]);
|
|
70
|
+
assert!(!ok && stderr.contains("has no .plum file with a `primitive <Name>[App]`"), "{stderr}");
|
|
71
|
+
}
|
compiler/core/src/game_entry.rs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
//! A game is a `main` returning `Game` (std/game/Game), made by `Game(screens: [..])`: there is
|
|
2
2
|
//! no other kind of game. This lowering (run before checking) renames the game's `main`
|
|
3
|
-
//! to `gameUserMain` and appends the state the host holds,
|
|
3
|
+
//! to `gameUserMain` and appends a `main` that builds the state the host holds, std/game/Game's
|
|
4
|
-
//! `
|
|
4
|
+
//! `GameRun(game, ticker)` (`GameRun.start`), and the two frame entry points the host calls:
|
|
5
|
-
//!
|
|
5
|
+
//! `gameUpdate(io, r, dt)` is `GameRun.frame` (the input polled once, a development run's time
|
|
6
|
+
//! travel keys, the fixed 1/60 s ticks the frame covers, at most 8, each one `Game.update`, and
|
|
6
|
-
//!
|
|
7
|
+
//! the host told when the frame is idle) and `gameDraw(io, r)` is `GameRun.draw`. The wasm
|
|
7
|
-
//!
|
|
8
|
+
//! module exports them as `update(state, dt) -> state` and `draw(state)`.
|
|
8
9
|
//! A `main` returning anything else is a command line program, except a type with its own
|
|
9
10
|
//! `update` and `draw` (the old game shape), which is an error that names `Game(screens: ..)`.
|
|
10
11
|
use crate::ast::*;
|
|
@@ -15,12 +16,8 @@ pub const GAME_UPDATE: &str = "gameUpdate";
|
|
|
15
16
|
pub const GAME_DRAW: &str = "gameDraw";
|
|
16
17
|
/// The game's own `main`, renamed: the lowered `main` wraps its result in a `GameRun`.
|
|
17
18
|
pub const GAME_USER_MAIN: &str = "gameUserMain";
|
|
18
|
-
/// The state the host holds between frames: the game and its
|
|
19
|
+
/// The state the host holds between frames, std/game/Game's: the game and its ticker.
|
|
19
20
|
pub const GAME_RUN: &str = "GameRun";
|
|
20
|
-
/// Runs the ticks of one frame, calling the game's `update` once each.
|
|
21
|
-
pub const GAME_TICKS: &str = "gameTicks";
|
|
22
|
-
/// One tick: the game's `update` with the clock's input, and the clock moved on.
|
|
23
|
-
pub const GAME_TICK: &str = "gameTick";
|
|
24
21
|
|
|
25
22
|
/// The name of std/game/Game's game type.
|
|
26
23
|
pub const GAME_TYPE: &str = "Game";
|
|
@@ -29,12 +26,24 @@ fn hasMethod(source: &Source, ty: &str, name: &str) -> bool {
|
|
|
29
26
|
source.items.iter().any(|i| matches!(i, Item::Fn(f) if f.name == name && f.has_self && f.type_param.as_deref() == Some(ty)))
|
|
30
27
|
}
|
|
31
28
|
|
|
29
|
+
fn hasStatic(source: &Source, ty: &str, name: &str) -> bool {
|
|
30
|
+
source.items.iter().any(|i| matches!(i, Item::Fn(f) if f.name == name && !f.has_self && f.type_param.as_deref() == Some(ty)))
|
|
31
|
+
}
|
|
32
|
+
|
|
32
33
|
/// Whether `source` has std/game/Game's `Game`: a struct `Game` with no type parameters, with
|
|
33
|
-
/// `update` and `draw` methods, in a program that has std/game/Screen's `Screen` trait
|
|
34
|
+
/// `update` and `draw` methods, in a program that has std/game/Screen's `Screen` trait and
|
|
35
|
+
/// std/game/Game's `GameRun` with its `frame` and `draw`.
|
|
34
36
|
fn hasStdGame(source: &Source) -> bool {
|
|
35
|
-
let isStruct = source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name ==
|
|
37
|
+
let isStruct = |name: &str| source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.name == name && e.generics.is_empty() && e.isStruct()));
|
|
36
38
|
let hasScreen = source.items.iter().any(|i| matches!(i, Item::Trait(t) if t.name == "Screen"));
|
|
39
|
+
isStruct(GAME_TYPE)
|
|
40
|
+
&& isStruct(GAME_RUN)
|
|
41
|
+
&& hasScreen
|
|
37
|
-
|
|
42
|
+
&& hasMethod(source, GAME_TYPE, "update")
|
|
43
|
+
&& hasMethod(source, GAME_TYPE, "draw")
|
|
44
|
+
&& hasStatic(source, GAME_RUN, "start")
|
|
45
|
+
&& hasMethod(source, GAME_RUN, "frame")
|
|
46
|
+
&& hasMethod(source, GAME_RUN, "draw")
|
|
38
47
|
}
|
|
39
48
|
|
|
40
49
|
/// The game type `main` returns (`Game`, as written): `Ok(None)` for a program that is not a
|
|
@@ -75,11 +84,12 @@ pub fn isLoweredGame(source: &Source) -> bool {
|
|
|
75
84
|
has(GAME_UPDATE) && has(GAME_DRAW)
|
|
76
85
|
}
|
|
77
86
|
|
|
78
|
-
/// If `main` returns a game type, renames `main`, appends the host's state and
|
|
87
|
+
/// If `main` returns a game type, renames `main`, appends a `main` making the host's state and
|
|
79
|
-
/// points, and numbers the new nodes. Returns whether `source` is a game.
|
|
88
|
+
/// the frame entry points, and numbers the new nodes. Returns whether `source` is a game.
|
|
80
89
|
pub fn lowerGame(source: &mut Source) -> Result<bool, Diagnostic> {
|
|
81
|
-
|
|
90
|
+
if gameType(source)?.is_none() {
|
|
82
|
-
|
|
91
|
+
return Ok(false);
|
|
92
|
+
}
|
|
83
93
|
let mut file = String::new();
|
|
84
94
|
let mut mainTakesIo = false;
|
|
85
95
|
for item in &mut source.items {
|
|
@@ -93,13 +103,9 @@ pub fn lowerGame(source: &mut Source) -> Result<bool, Diagnostic> {
|
|
|
93
103
|
}
|
|
94
104
|
let mainArgs = if mainTakesIo { "io" } else { "" };
|
|
95
105
|
let text = format!(
|
|
96
|
-
"struct {GAME_RUN}(game: {ty}, clock: Clock)\n\n\
|
|
97
|
-
|
|
106
|
+
"fun main(io: Io) -> {GAME_RUN} = {GAME_RUN}.start({GAME_USER_MAIN}({mainArgs}))\n\n\
|
|
98
|
-
fun {GAME_UPDATE}(io: Io, r: {GAME_RUN}, dt: Float) -> {GAME_RUN} =
|
|
107
|
+
fun {GAME_UPDATE}(io: Io, r: {GAME_RUN}, dt: Float) -> {GAME_RUN} = r.frame(io, dt)\n\n\
|
|
99
|
-
fun {GAME_TICKS}(io: Io, r: {GAME_RUN}) -> {GAME_RUN} =\n \
|
|
100
|
-
if r.clock.due() then {GAME_TICKS}(io, {GAME_TICK}(io, r)) else {GAME_RUN}(..r, clock: r.clock.settled())\n\n\
|
|
101
|
-
fun {GAME_TICK}(io: Io, r: {GAME_RUN}) -> {GAME_RUN} = {GAME_RUN}(..r, game: r.game.update(io, r.clock.input(), Clock.Tick), clock: r.clock.ticked())\n\n\
|
|
102
|
-
fun {GAME_DRAW}(io: Io, r: {GAME_RUN}) = r.
|
|
108
|
+
fun {GAME_DRAW}(io: Io, r: {GAME_RUN}) = r.draw(io)\n"
|
|
103
109
|
);
|
|
104
110
|
source.items.extend(parseItems(&text, &file));
|
|
105
111
|
// The host holds the state as one reference between frames: a flat struct would travel as
|
|
@@ -132,7 +138,7 @@ mod tests {
|
|
|
132
138
|
/// A stand-in for std/game/Game's `Game` and a `main` returning `ret`.
|
|
133
139
|
fn game(ret: &str) -> Source {
|
|
134
140
|
parse(&format!(
|
|
135
|
-
"trait Screen =\n fun name(self) -> Str\n\nstruct Game(n: Int) =\n fun update(self, io: Io, dt: Float) -> Game = self\n\n fun draw(self, io: Io) = Unit\n\nprimitive Main[App] =\n fun main(io: Io) -> {ret} =\n crash \"unused\"\n"
|
|
141
|
+
"trait Screen =\n fun name(self) -> Str\n\nstruct Game(n: Int) =\n fun update(self, io: Io, dt: Float) -> Game = self\n\n fun draw(self, io: Io) = Unit\n\nstruct GameRun(game: Game) =\n fun start(g: Game) -> GameRun = GameRun(game: g)\n\n fun frame(self, io: Io, dt: Float) -> GameRun = self\n\n fun draw(self, io: Io) = Unit\n\nprimitive Main[App] =\n fun main(io: Io) -> {ret} =\n crash \"unused\"\n"
|
|
136
142
|
))
|
|
137
143
|
}
|
|
138
144
|
|
|
@@ -172,11 +178,11 @@ mod tests {
|
|
|
172
178
|
}
|
|
173
179
|
|
|
174
180
|
#[test]
|
|
175
|
-
fn
|
|
181
|
+
fn loweringWrapsTheGameInStdsGameRun() {
|
|
176
182
|
let mut src = game("Game");
|
|
177
183
|
assert!(lowerGame(&mut src).expect("lowers"));
|
|
178
184
|
let fns: Vec<&str> = src.items.iter().filter_map(|i| if let Item::Fn(f) = i { Some(f.name.as_str()) } else { None }).collect();
|
|
179
|
-
for name in [GAME_USER_MAIN, "main", GAME_UPDATE,
|
|
185
|
+
for name in [GAME_USER_MAIN, "main", GAME_UPDATE, GAME_DRAW] {
|
|
180
186
|
assert_eq!(fns.iter().filter(|n| **n == name).count(), 1, "{name} in {fns:?}");
|
|
181
187
|
}
|
|
182
188
|
let run = src.items.iter().find_map(|i| if let Item::Enum(e) = i { (e.name == GAME_RUN).then_some(e) } else { None });
|
compiler/game/src/host.rs
CHANGED
|
@@ -9,9 +9,14 @@ pub use wasmtime::Result;
|
|
|
9
9
|
struct HostState<B> {
|
|
10
10
|
backend: B,
|
|
11
11
|
replay: Replay,
|
|
12
|
+
/// The game called `frameIdle` during the last `update`: an `OnDemand` screen has nothing
|
|
13
|
+
/// new to draw (std/game/Game's `hostFrame`, docs/game.md "Frames on demand").
|
|
14
|
+
idle: bool,
|
|
12
15
|
}
|
|
13
16
|
|
|
14
|
-
/// Record and replay (std/game/Replay).
|
|
17
|
+
/// Record and replay (std/game/Replay). A development run (`DEV`, `plum run --dev`) records
|
|
18
|
+
/// and replays nothing: the game keeps its own history and reads the time travel keys.
|
|
19
|
+
/// Recording, the host keeps the first two values
|
|
15
20
|
/// `rawRandomHalf` returns (the halves of `io.randomSeed()`), the screen size, and the tick
|
|
16
21
|
/// lines the game hands it. Replaying, `rawRandomHalf` returns the recorded halves first, the
|
|
17
22
|
/// screen size is the recorded one, and the game reads the replay's text. In both, every
|
|
@@ -19,7 +24,7 @@ struct HostState<B> {
|
|
|
19
24
|
/// seeds replays too.
|
|
20
25
|
#[derive(Default)]
|
|
21
26
|
struct Replay {
|
|
22
|
-
/// 0 off, 1 recording, 2 replaying: `ReplayMode` in std/game/Replay.
|
|
27
|
+
/// 0 off, 1 recording, 2 replaying, 3 a development run: `ReplayMode` in std/game/Replay.
|
|
23
28
|
mode: i32,
|
|
24
29
|
/// Recording: the halves returned so far. Replaying: the recorded halves.
|
|
25
30
|
halves: Vec<i32>,
|
|
@@ -33,6 +38,7 @@ struct Replay {
|
|
|
33
38
|
|
|
34
39
|
const RECORDING: i32 = 1;
|
|
35
40
|
const REPLAYING: i32 = 2;
|
|
41
|
+
const DEV: i32 = 3;
|
|
36
42
|
|
|
37
43
|
/// The seed halves and screen size from a replay's first line,
|
|
38
44
|
/// `plum-replay 1 <hi> <lo> <width> <height>`.
|
|
@@ -164,6 +170,7 @@ fn dispatch<B: Backend>(name: &str, caller: &mut Caller<'_, HostState<B>>, p: &[
|
|
|
164
170
|
r[0] = Val::I32(v);
|
|
165
171
|
}
|
|
166
172
|
"replayMode" => r[0] = Val::I32(caller.data().replay.mode),
|
|
173
|
+
"frameIdle" => caller.data_mut().idle = true,
|
|
167
174
|
"replayText" => {
|
|
168
175
|
let text = caller.data().replay.text.clone();
|
|
169
176
|
r[0] = new_str(caller, text.as_bytes())?;
|
|
@@ -275,7 +282,7 @@ impl<B: Backend> PlumGame<B> {
|
|
|
275
282
|
return Err(wasmtime::Error::msg(format!("module has no `{name}` export{old}")));
|
|
276
283
|
}
|
|
277
284
|
}
|
|
278
|
-
let mut store = Store::new(&engine, HostState { backend, replay: Replay::default() });
|
|
285
|
+
let mut store = Store::new(&engine, HostState { backend, replay: Replay::default(), idle: false });
|
|
279
286
|
let mut linker: Linker<HostState<B>> = Linker::new(&engine);
|
|
280
287
|
for imp in module.imports() {
|
|
281
288
|
let Some(ty) = imp.ty().func().cloned() else { continue };
|
|
@@ -311,6 +318,13 @@ impl<B: Backend> PlumGame<B> {
|
|
|
311
318
|
self.store.data_mut().replay = Replay { mode: RECORDING, screen, ..Replay::default() };
|
|
312
319
|
}
|
|
313
320
|
|
|
321
|
+
/// A development run from `main` on (`plum run --dev`): call before `init`. The game keeps
|
|
322
|
+
/// its history from the first frame and takes the time travel keys (std/game/History's
|
|
323
|
+
/// `TravelKeys`).
|
|
324
|
+
pub fn dev(&mut self) {
|
|
325
|
+
self.store.data_mut().replay = Replay { mode: DEV, ..Replay::default() };
|
|
326
|
+
}
|
|
327
|
+
|
|
314
328
|
/// The text of the run recorded since `record`: the seed and screen line, then one line per
|
|
315
329
|
/// tick so far.
|
|
316
330
|
pub fn recording(&self) -> String {
|
|
@@ -362,7 +376,16 @@ impl<B: Backend> PlumGame<B> {
|
|
|
362
376
|
Ok(())
|
|
363
377
|
}
|
|
364
378
|
|
|
379
|
+
/// Whether the last `update` said its frame has nothing new to draw: the screen shown is
|
|
380
|
+
/// `OnDemand` and slept through the frame's ticks (std/game/Game's `idle`). A host may
|
|
381
|
+
/// then skip `draw` and keep showing the last frame; calling `draw` anyway draws the same
|
|
382
|
+
/// frame.
|
|
383
|
+
pub fn idle(&self) -> bool {
|
|
384
|
+
self.store.data().idle
|
|
385
|
+
}
|
|
386
|
+
|
|
365
387
|
pub fn update(&mut self, dt: f32) -> Result<()> {
|
|
388
|
+
self.store.data_mut().idle = false;
|
|
366
389
|
self.call_with_state("update", &[fv(dt)], true)
|
|
367
390
|
}
|
|
368
391
|
|
compiler/game/src/main.rs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
//! `plum-game <module.wasm> [--assets DIR] [--frames N]`: runs a compiled Plum
|
|
2
2
|
//! game headless (main, then N update+draw frames at 60 fps, default 1) and
|
|
3
|
-
//! prints the host calls recorded during the last draw.
|
|
3
|
+
//! prints the host calls recorded during the last draw. A frame the game says is idle
|
|
4
|
+
//! (an `OnDemand` screen with nothing new to draw) is not drawn, as a browser skips it. The asset root defaults
|
|
4
5
|
//! to `assets` beside the wasm.
|
|
5
6
|
|
|
6
7
|
use plum_game::{host::PlumGame, recorder::Recorder};
|
|
@@ -31,6 +32,9 @@ fn run() -> Result<(), String> {
|
|
|
31
32
|
game.init().map_err(|e| format!("main: {e:#}"))?;
|
|
32
33
|
for _ in 0..frames {
|
|
33
34
|
game.update(1.0 / 60.0).map_err(|e| format!("update: {e:#}"))?;
|
|
35
|
+
if game.idle() {
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
34
38
|
game.backend_mut().calls.clear();
|
|
35
39
|
game.draw().map_err(|e| format!("draw: {e:#}"))?;
|
|
36
40
|
}
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -790,3 +790,138 @@ fn aTurnedBoxAndLabelAreDrawnTurnedAndTheHudOnePixelAUnit() {
|
|
|
790
790
|
let texts: Vec<&String> = calls.iter().filter(|c| c.starts_with("drawText")).collect();
|
|
791
791
|
assert_eq!(texts, ["drawTextEx(\"hi\",100,100,10,1.5707964,1,1,1,1)", "drawText(\"hud\",5,5,10,1,1,1,1)"], "{calls:?}");
|
|
792
792
|
}
|
|
793
|
+
|
|
794
|
+
/// A game of one screen that counts its ticks and its presses of Space, and draws both with
|
|
795
|
+
/// the window's width; `frames` is `OnDemand` or `Always` (std/game/Screen, "Frames on demand").
|
|
796
|
+
fn countingGame(name: &str, frames: &str) -> Vec<u8> {
|
|
797
|
+
let dir = std::env::temp_dir().join(format!("plum_game_counting_{name}_{}", std::process::id()));
|
|
798
|
+
std::fs::create_dir_all(&dir).unwrap();
|
|
799
|
+
let path = dir.join("m.plum");
|
|
800
|
+
std::fs::write(
|
|
801
|
+
&path,
|
|
802
|
+
format!(
|
|
803
|
+
"import 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/Color\nimport std/game/Input\nimport std/game/Control\nimport std/game/Screen\nimport std/game/ScreenSlice\nimport std/game/Game\nimport std/game/View\nimport std/game/Label\nimport std/App\nenum Count = Bump | Tock\nstruct Counting[ScreenSlice<Count>](ticks: Int, bumps: Int) =\n fun name(self) -> Str = \"main\"\n fun frames(self) -> Frames = {frames}\n fun hud(self, window: Vec2) -> List<View> = [Label(text: \"ticks {{self.ticks}} bumps {{self.bumps}} w {{window.x}}\", size: 8.0)]\n fun onKey(self, e: InputEvent) -> Option<Count> = match e\n KeyDown(k) => if k == Key.Space then Some(Bump) else None\n _ => None\n fun tick(self, dt: Float) -> Option<Count> = Some(Tock)\n fun reduce(self, a: Count) -> Counting = match a\n Bump => Counting(..self, bumps: self.bumps + 1)\n Tock => Counting(..self, ticks: self.ticks + 1)\n\nprimitive Main[App] =\n fun main(io: Io) -> Game =\n only: Screen := Counting(ticks: 0, bumps: 0)\n Game(screens: [only])\n"
|
|
804
|
+
),
|
|
805
|
+
)
|
|
806
|
+
.unwrap();
|
|
807
|
+
let wasm = compile(&path);
|
|
808
|
+
let _ = std::fs::remove_dir_all(&dir);
|
|
809
|
+
wasm
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/// The texts the last draw drew, in order.
|
|
813
|
+
fn texts(g: &PlumGame<Recorder>) -> Vec<String> {
|
|
814
|
+
g.backend().calls.iter().filter(|c| c.starts_with("drawText(")).map(|c| c.split('"').nth(1).unwrap_or("").to_string()).collect()
|
|
815
|
+
}
|
|
816
|
+
|
|
817
|
+
/// An `OnDemand` screen: the frame after one that drew it with nothing to do is idle
|
|
818
|
+
/// (`frameIdle`), runs no tick of the screen and needs no draw; a key wakes it for one frame.
|
|
819
|
+
#[test]
|
|
820
|
+
fn anOnDemandScreenTellsTheHostItsIdleFramesAndWakesOnInput() {
|
|
821
|
+
let mut g = PlumGame::load(&countingGame("demand", "OnDemand"), Recorder::new()).unwrap();
|
|
822
|
+
g.init().unwrap();
|
|
823
|
+
g.update(1.0 / 60.0).unwrap();
|
|
824
|
+
assert!(!g.idle());
|
|
825
|
+
g.draw().unwrap();
|
|
826
|
+
assert_eq!(texts(&g), ["ticks 1 bumps 0 w 800.0"]);
|
|
827
|
+
for _ in 0..30 {
|
|
828
|
+
g.update(1.0 / 60.0).unwrap();
|
|
829
|
+
assert!(g.idle());
|
|
830
|
+
}
|
|
831
|
+
g.backend_mut().keys_down.insert(32);
|
|
832
|
+
g.update(1.0 / 60.0).unwrap();
|
|
833
|
+
assert!(!g.idle());
|
|
834
|
+
g.backend_mut().calls.clear();
|
|
835
|
+
g.draw().unwrap();
|
|
836
|
+
assert_eq!(texts(&g), ["ticks 2 bumps 1 w 800.0"]);
|
|
837
|
+
// Space held, which the screen doesn't map: asleep again from the next frame.
|
|
838
|
+
g.update(1.0 / 60.0).unwrap();
|
|
839
|
+
assert!(g.idle());
|
|
840
|
+
// A resize wakes it, and the screen sees the new window on the tick's input.
|
|
841
|
+
g.backend_mut().screen = (640.0, 480.0);
|
|
842
|
+
g.update(1.0 / 60.0).unwrap();
|
|
843
|
+
assert!(!g.idle());
|
|
844
|
+
g.backend_mut().calls.clear();
|
|
845
|
+
g.draw().unwrap();
|
|
846
|
+
assert_eq!(texts(&g), ["ticks 3 bumps 1 w 640.0"]);
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
#[test]
|
|
850
|
+
fn anAlwaysScreenIsNeverIdle() {
|
|
851
|
+
let mut g = PlumGame::load(&countingGame("always", "Always"), Recorder::new()).unwrap();
|
|
852
|
+
g.init().unwrap();
|
|
853
|
+
for _ in 0..3 {
|
|
854
|
+
g.update(1.0 / 60.0).unwrap();
|
|
855
|
+
assert!(!g.idle());
|
|
856
|
+
g.draw().unwrap();
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/// One frame with exactly `keys` held.
|
|
861
|
+
fn frameWith(g: &mut PlumGame<Recorder>, keys: &[i32]) {
|
|
862
|
+
g.backend_mut().keys_down = keys.iter().copied().collect();
|
|
863
|
+
g.update(1.0 / 60.0).unwrap();
|
|
864
|
+
g.backend_mut().calls.clear();
|
|
865
|
+
g.draw().unwrap();
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/// A development run (`plum run --dev`): the game keeps its history from the first frame,
|
|
869
|
+
/// `\` pauses, `[` steps back a tick, Ctrl+Z undoes the last press of Space, and the line
|
|
870
|
+
/// along the bottom says where it is; none of those keys reaches the game.
|
|
871
|
+
#[test]
|
|
872
|
+
fn aDevelopmentRunTravelsWithTheTimeTravelKeys() {
|
|
873
|
+
const SPACE: i32 = 32;
|
|
874
|
+
const Z: i32 = 90;
|
|
875
|
+
const BRACKET_LEFT: i32 = 91;
|
|
876
|
+
const BACKSLASH: i32 = 92;
|
|
877
|
+
const CTRL: i32 = 341;
|
|
878
|
+
let mut g = PlumGame::load(&countingGame("dev", "Always"), Recorder::new()).unwrap();
|
|
879
|
+
g.dev();
|
|
880
|
+
g.init().unwrap();
|
|
881
|
+
for _ in 0..3 {
|
|
882
|
+
frameWith(&mut g, &[]);
|
|
883
|
+
}
|
|
884
|
+
frameWith(&mut g, &[SPACE]);
|
|
885
|
+
frameWith(&mut g, &[]);
|
|
886
|
+
assert_eq!(texts(&g), ["ticks 5 bumps 1 w 800.0", "tick 5 of 5"]);
|
|
887
|
+
frameWith(&mut g, &[BACKSLASH]);
|
|
888
|
+
assert_eq!(texts(&g), ["ticks 5 bumps 1 w 800.0", "tick 5 of 5 (paused)"]);
|
|
889
|
+
frameWith(&mut g, &[]);
|
|
890
|
+
frameWith(&mut g, &[BRACKET_LEFT]);
|
|
891
|
+
assert_eq!(texts(&g), ["ticks 4 bumps 1 w 800.0", "tick 4 of 5 (paused)"]);
|
|
892
|
+
frameWith(&mut g, &[CTRL]);
|
|
893
|
+
frameWith(&mut g, &[CTRL, Z]);
|
|
894
|
+
assert_eq!(texts(&g), ["ticks 3 bumps 0 w 800.0", "tick 3 of 5 (paused)"]);
|
|
895
|
+
// Resumed, the game goes on from tick 3, the resuming frame's tick first; what was
|
|
896
|
+
// undone can't be redone.
|
|
897
|
+
frameWith(&mut g, &[BACKSLASH]);
|
|
898
|
+
frameWith(&mut g, &[]);
|
|
899
|
+
assert_eq!(texts(&g), ["ticks 5 bumps 0 w 800.0", "tick 5 of 5"]);
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/// Outside a development run nothing is drawn but the game, and the keys are the game's.
|
|
903
|
+
#[test]
|
|
904
|
+
fn onlyADevelopmentRunHasTheTimeTravelKeys() {
|
|
905
|
+
let mut g = PlumGame::load(&countingGame("nodev", "Always"), Recorder::new()).unwrap();
|
|
906
|
+
g.init().unwrap();
|
|
907
|
+
frameWith(&mut g, &[]);
|
|
908
|
+
frameWith(&mut g, &[92]);
|
|
909
|
+
frameWith(&mut g, &[]);
|
|
910
|
+
assert_eq!(texts(&g), ["ticks 3 bumps 0 w 800.0"]);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/// The browser lays text out by std/game/Label's advance widths, so a label's bounds are as
|
|
914
|
+
/// wide as what the browser draws: the bridge's `ADVANCES` is `Label.Advances`.
|
|
915
|
+
#[test]
|
|
916
|
+
fn theBridgeLaysTextOutByLabelsAdvances() {
|
|
917
|
+
let quoted = |text: &str, key: &str| -> String {
|
|
918
|
+
let at = text.find(key).unwrap_or_else(|| panic!("no {key}"));
|
|
919
|
+
text[at + key.len()..].split('"').nth(1).expect("a quoted table").to_string()
|
|
920
|
+
};
|
|
921
|
+
let label = std::fs::read_to_string(root().join("std/game/Label.plum")).unwrap();
|
|
922
|
+
let bridge = std::fs::read_to_string(root().join("compiler/game/web/plum_bridge.js")).unwrap();
|
|
923
|
+
let table = quoted(&label, "const Advances =");
|
|
924
|
+
assert_eq!(table.len(), 95 * 4);
|
|
925
|
+
assert!(table.bytes().all(|b| b.is_ascii_digit()));
|
|
926
|
+
assert_eq!(quoted(&bridge, "const ADVANCES ="), table);
|
|
927
|
+
}
|
compiler/game/web-test/README.md
CHANGED
|
@@ -25,4 +25,4 @@ Options: `--browser chromium|webkit` (default chromium; WebKit is Playwright's S
|
|
|
25
25
|
Exit code is non-zero with a message on failure.
|
|
26
26
|
|
|
27
27
|
`cargo test --manifest-path compiler/game/web-test/Cargo.toml` runs the same check on
|
|
28
|
-
`examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs, Orbit Runner with `--stall-adapter`, and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there); each skips with a note if its browser is not installed. The checks take turns, one browser at a time: several software-WebGPU browsers at once starve each other of frames.
|
|
28
|
+
`examples/games/orbitrunner/OrbitRunner.plum`, `examples/games/balloonpop/BalloonPop.plum` and `fixtures/stress_state_view.plum`, plus WebKit runs, Orbit Runner with `--stall-adapter`, and a record-and-replay run (Orbit Runner recorded at `?record` with keys and clicks, then replayed at `?replay=` in two pages, one pressing other keys: both must end on the same frame and stay there), and `examples/games/two_screens.plum`'s `OnDemand` title (the page counts its frames through `__plumDrawLog`: once idle it runs no frame for a second, a key wakes it for a drawn frame and it sleeps again; then, as `plum run --dev` serves it, its history line is drawn and `\` pauses it and `[` steps it back a tick); each skips with a note if its browser is not installed. The checks take turns, one browser at a time: several software-WebGPU browsers at once starve each other of frames.
|
compiler/game/web-test/src/lib.rs
CHANGED
|
@@ -796,6 +796,14 @@ pub async fn record_and_replay(file: &Path) -> Result<String, String> {
|
|
|
796
796
|
}
|
|
797
797
|
|
|
798
798
|
async fn record_and_replay_at(port: u16, dir: &Path) -> Result<String, String> {
|
|
799
|
+
let browser = launch_chromium().await?;
|
|
800
|
+
let out = record_then_replay(&browser.1, port, dir).await;
|
|
801
|
+
let _ = browser.1.close().await;
|
|
802
|
+
out
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
/// Headless Chromium with software WebGPU, and the Playwright that drives it.
|
|
806
|
+
async fn launch_chromium() -> Result<(Playwright, playwright_rs::protocol::Browser), String> {
|
|
799
807
|
let pw = Playwright::launch().await.map_err(pe("launch playwright"))?;
|
|
800
808
|
let args: Vec<String> = [
|
|
801
809
|
"--ignore-gpu-blocklist",
|
|
@@ -808,16 +816,124 @@ async fn record_and_replay_at(port: u16, dir: &Path) -> Result<String, String> {
|
|
|
808
816
|
.map(String::from)
|
|
809
817
|
.to_vec();
|
|
810
818
|
let browser = pw.chromium().launch_with_options(LaunchOptions::new().headless(true).args(args)).await.map_err(pe("launch chromium"))?;
|
|
819
|
+
Ok((pw, browser))
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/// Frames on demand and a development run in the browser, on `file`, a game whose first
|
|
823
|
+
/// screen is `OnDemand` and maps no letter key (examples/games/two_screens.plum). A plain
|
|
824
|
+
/// page: once the screen is drawn and idle the page runs no frame (`frameIdle`, the bridge
|
|
825
|
+
/// asks for none until input), a key wakes it for a frame that is drawn, and it sleeps
|
|
826
|
+
/// again. A page served as `plum run --dev` serves it (`plumTimeTravel`): the frame shows
|
|
827
|
+
/// where the game is in its history, `\` pauses it and `[` steps it back a tick, each
|
|
828
|
+
/// drawn at once though the screen was idle.
|
|
829
|
+
pub async fn on_demand_and_travel(file: &Path) -> Result<String, String> {
|
|
830
|
+
let tmp = std::env::temp_dir().join(format!("plum-web-demand-{}", std::process::id()));
|
|
831
|
+
let _ = std::fs::remove_dir_all(&tmp);
|
|
832
|
+
std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?;
|
|
833
|
+
build_web(file, &tmp, None, false, false)?;
|
|
834
|
+
let stop = Arc::new(AtomicBool::new(false));
|
|
835
|
+
let port = serve(tmp.clone(), stop.clone());
|
|
836
|
+
let res = match launch_chromium().await {
|
|
837
|
+
Ok((_pw, browser)) => {
|
|
811
|
-
|
|
838
|
+
let out = on_demand_then_travel(&browser, port).await;
|
|
812
|
-
|
|
839
|
+
let _ = browser.close().await;
|
|
813
|
-
|
|
840
|
+
out
|
|
841
|
+
}
|
|
842
|
+
Err(e) => Err(e),
|
|
843
|
+
};
|
|
844
|
+
stop.store(true, Ordering::Relaxed);
|
|
845
|
+
let _ = TcpStream::connect(("127.0.0.1", port));
|
|
846
|
+
let _ = std::fs::remove_dir_all(&tmp);
|
|
847
|
+
res
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
/// The page's frames run and frames drawn so far, and the texts of the last frame drawn.
|
|
851
|
+
async fn probed(page: &playwright_rs::protocol::Page) -> Result<(u64, u64, Vec<String>), String> {
|
|
852
|
+
let v: (f64, f64, Vec<String>) = page
|
|
853
|
+
.evaluate("() => { const p = window.__plumDrawLog; return [p.frames, p.draws, p.last ? p.last.texts.map((t) => t.s) : []]; }", None::<&()>)
|
|
854
|
+
.await
|
|
855
|
+
.map_err(pe("draw log"))?;
|
|
856
|
+
Ok((v.0 as u64, v.1 as u64, v.2))
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async fn tap(page: &playwright_rs::protocol::Page, key: &str) -> Result<(), String> {
|
|
860
|
+
page.keyboard().down(key).await.map_err(pe("key down"))?;
|
|
861
|
+
tokio::time::sleep(Duration::from_millis(80)).await;
|
|
862
|
+
page.keyboard().up(key).await.map_err(pe("key up"))?;
|
|
863
|
+
tokio::time::sleep(Duration::from_millis(600)).await;
|
|
864
|
+
Ok(())
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
async fn on_demand_then_travel(browser: &playwright_rs::protocol::Browser, port: u16) -> Result<String, String> {
|
|
868
|
+
const PROBE: &str = "window.__plumDrawLog = {};";
|
|
869
|
+
let mut failures = Vec::new();
|
|
870
|
+
let (page, errors, logs) = open_page(browser, port, "", &[PROBE]).await?;
|
|
871
|
+
let (f1, d1, _) = probed(&page).await?;
|
|
872
|
+
tokio::time::sleep(Duration::from_secs(1)).await;
|
|
873
|
+
let (f2, d2, texts) = probed(&page).await?;
|
|
874
|
+
if d1 == 0 || texts.is_empty() {
|
|
875
|
+
failures.push(format!("the page drew nothing (frames {f1}, draws {d1})"));
|
|
876
|
+
}
|
|
877
|
+
if f2 != f1 || d2 != d1 {
|
|
878
|
+
failures.push(format!("the idle page kept running frames: {f1} -> {f2} run, {d1} -> {d2} drawn in 1 s"));
|
|
879
|
+
}
|
|
880
|
+
tap(&page, "KeyA").await?;
|
|
881
|
+
let (f3, d3, _) = probed(&page).await?;
|
|
882
|
+
if d3 <= d2 || f3 <= f2 {
|
|
883
|
+
failures.push(format!("a key did not wake the idle page: {f2} -> {f3} run, {d2} -> {d3} drawn"));
|
|
884
|
+
}
|
|
885
|
+
tokio::time::sleep(Duration::from_millis(700)).await;
|
|
886
|
+
let (f4, d4, _) = probed(&page).await?;
|
|
887
|
+
if f4 != f3 || d4 != d3 {
|
|
888
|
+
failures.push(format!("the page did not go back to sleep after the key: {f3} -> {f4} run, {d3} -> {d4} drawn"));
|
|
889
|
+
}
|
|
890
|
+
let errs = real_errors(&errors.lock().unwrap(), &logs.lock().unwrap());
|
|
891
|
+
if !errs.is_empty() {
|
|
892
|
+
failures.push(format!("plain page: {errs:?}"));
|
|
893
|
+
}
|
|
894
|
+
page.close().await.map_err(pe("close page"))?;
|
|
895
|
+
|
|
896
|
+
let (dev, errors, logs) = open_page(browser, port, "", &[PROBE, "globalThis.plumTimeTravel = true;"]).await?;
|
|
897
|
+
let line = |texts: &[String]| texts.iter().find(|t| t.starts_with("tick ")).cloned().unwrap_or_default();
|
|
898
|
+
let (_, _, texts) = probed(&dev).await?;
|
|
899
|
+
let first = line(&texts);
|
|
900
|
+
let ticks: Option<(u64, u64)> = first.strip_prefix("tick ").and_then(|r| r.split_once(" of ")).and_then(|(a, b)| Some((a.parse().ok()?, b.trim().parse().ok()?)));
|
|
901
|
+
match ticks {
|
|
902
|
+
Some((now, of)) if now == of && now > 0 => {
|
|
903
|
+
tap(&dev, "Backslash").await?;
|
|
904
|
+
let paused = line(&probed(&dev).await?.2);
|
|
905
|
+
if !paused.starts_with("tick ") || !paused.ends_with(" (paused)") {
|
|
906
|
+
failures.push(format!("`\\` did not pause the development run: {paused:?}"));
|
|
907
|
+
}
|
|
908
|
+
let at: u64 = paused.strip_prefix("tick ").and_then(|r| r.split(' ').next()).and_then(|n| n.parse().ok()).unwrap_or(0);
|
|
909
|
+
tap(&dev, "BracketLeft").await?;
|
|
910
|
+
let back = line(&probed(&dev).await?.2);
|
|
911
|
+
if back != format!("tick {} of {at} (paused)", at - 1) {
|
|
912
|
+
failures.push(format!("`[` did not step back a tick from {paused:?}: {back:?}"));
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
_ => failures.push(format!("the development run shows no history line: {texts:?}")),
|
|
916
|
+
}
|
|
917
|
+
let errs = real_errors(&errors.lock().unwrap(), &logs.lock().unwrap());
|
|
918
|
+
if !errs.is_empty() {
|
|
919
|
+
failures.push(format!("development page: {errs:?}"));
|
|
920
|
+
}
|
|
921
|
+
if failures.is_empty() {
|
|
922
|
+
Ok(format!("idle page slept at {d2} frames drawn and woke on a key; development run showed {first:?} and paused and stepped back"))
|
|
923
|
+
} else {
|
|
924
|
+
Err(failures.join("\n"))
|
|
925
|
+
}
|
|
814
926
|
}
|
|
815
927
|
|
|
816
928
|
type Lines = Arc<Mutex<Vec<String>>>;
|
|
817
929
|
|
|
818
|
-
/// A page at `query` that collects its errors and its console lines
|
|
930
|
+
/// A page at `query` that collects its errors and its console lines, `init` run before it
|
|
931
|
+
/// loads.
|
|
819
|
-
async fn open_page(browser: &playwright_rs::protocol::Browser, port: u16, query: &str) -> Result<(playwright_rs::protocol::Page, Lines, Lines), String> {
|
|
932
|
+
async fn open_page(browser: &playwright_rs::protocol::Browser, port: u16, query: &str, init: &[&str]) -> Result<(playwright_rs::protocol::Page, Lines, Lines), String> {
|
|
820
933
|
let page = browser.new_page().await.map_err(pe("new page"))?;
|
|
934
|
+
for script in init {
|
|
935
|
+
page.add_init_script(script).await.map_err(pe("init script"))?;
|
|
936
|
+
}
|
|
821
937
|
let errors: Lines = Arc::default();
|
|
822
938
|
let logs: Lines = Arc::default();
|
|
823
939
|
{
|
|
@@ -862,7 +978,7 @@ async fn play_some(page: &playwright_rs::protocol::Page, key: &str, secs: f64, x
|
|
|
862
978
|
}
|
|
863
979
|
|
|
864
980
|
async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u16, dir: &Path) -> Result<String, String> {
|
|
865
|
-
let (rec, rec_errors, rec_logs) = open_page(browser, port, "?record").await?;
|
|
981
|
+
let (rec, rec_errors, rec_logs) = open_page(browser, port, "?record", &[]).await?;
|
|
866
982
|
play_some(&rec, "ArrowRight", 1.0, 300.0, 200.0).await?;
|
|
867
983
|
play_some(&rec, "ArrowDown", 0.7, 500.0, 300.0).await?;
|
|
868
984
|
play_some(&rec, "Space", 0.3, 200.0, 400.0).await?;
|
|
@@ -885,8 +1001,8 @@ async fn record_then_replay(browser: &playwright_rs::protocol::Browser, port: u1
|
|
|
885
1001
|
rec.close().await.map_err(pe("close recording page"))?;
|
|
886
1002
|
|
|
887
1003
|
let wait = Duration::from_secs_f64(ticks as f64 / 60.0 * 2.0 + 3.0);
|
|
888
|
-
let (quiet, quiet_errors, quiet_logs) = open_page(browser, port, "?replay=replay.txt").await?;
|
|
1004
|
+
let (quiet, quiet_errors, quiet_logs) = open_page(browser, port, "?replay=replay.txt", &[]).await?;
|
|
889
|
-
let (noisy, noisy_errors, noisy_logs) = open_page(browser, port, "?replay=replay.txt").await?;
|
|
1005
|
+
let (noisy, noisy_errors, noisy_logs) = open_page(browser, port, "?replay=replay.txt", &[]).await?;
|
|
890
1006
|
play_some(&noisy, "ArrowLeft", 0.5, 100.0, 100.0).await?;
|
|
891
1007
|
play_some(&noisy, "Enter", 0.3, 400.0, 250.0).await?;
|
|
892
1008
|
tokio::time::sleep(wait).await;
|
compiler/game/web-test/tests/web_check.rs
CHANGED
|
@@ -197,3 +197,17 @@ fn a_recorded_run_replays_in_the_browser() {
|
|
|
197
197
|
let report = rt.block_on(plum_web_test::record_and_replay(&repo_root().join("examples/games/orbitrunner/OrbitRunner.plum"))).unwrap_or_else(|e| panic!("{e}"));
|
|
198
198
|
println!("{report}");
|
|
199
199
|
}
|
|
200
|
+
|
|
201
|
+
/// Frames on demand in the browser (the page sleeps while the `OnDemand` screen is idle and
|
|
202
|
+
/// wakes on a key) and `plum run --dev`'s time travel keys (pause and step back).
|
|
203
|
+
#[test]
|
|
204
|
+
fn an_idle_page_sleeps_and_a_dev_run_travels() {
|
|
205
|
+
if !chromium_installed() {
|
|
206
|
+
eprintln!("SKIP: Playwright Chromium not installed (see compiler/game/web-test/README.md)");
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
let _one = one_browser();
|
|
210
|
+
let rt = tokio::runtime::Runtime::new().unwrap();
|
|
211
|
+
let report = rt.block_on(plum_web_test::on_demand_and_travel(&repo_root().join("examples/games/two_screens.plum"))).unwrap_or_else(|e| panic!("{e}"));
|
|
212
|
+
println!("{report}");
|
|
213
|
+
}
|
compiler/game/web/plum_bridge.js
CHANGED
|
@@ -94,21 +94,51 @@
|
|
|
94
94
|
let wheelPending = 0;
|
|
95
95
|
let wheel = 0;
|
|
96
96
|
const mouse = { x: 0, y: 0 };
|
|
97
|
+
// macOS sends no keyup for a key let go while Cmd is down, so such a key is let go here
|
|
98
|
+
// once a frame has seen it down: `cmdTaps` went down since the last frame, `cmdShown`
|
|
99
|
+
// were down for the frame that ran last. Cmd held and Z tapped twice is two presses.
|
|
100
|
+
let cmdTaps = new Set();
|
|
101
|
+
let cmdShown = new Set();
|
|
102
|
+
const MODIFIERS = [340, 341, 342, 343, 344, 345, 346, 347];
|
|
103
|
+
// A key let go before any frame saw it down (a tap shorter than a frame, or one while
|
|
104
|
+
// frames stall) would never reach the game, which reads the keys held once a frame
|
|
105
|
+
// (std/game/Input's `poll`): it is kept down for the next frame and let go at the
|
|
106
|
+
// frame after. `tapsUp` went up since the last frame, `tapsShown` were kept down for
|
|
107
|
+
// the frame that ran last.
|
|
108
|
+
let tapsUp = new Set();
|
|
109
|
+
let tapsShown = new Set();
|
|
97
110
|
|
|
98
111
|
window.addEventListener("keydown", (e) => {
|
|
99
112
|
const k = glfwKey(e.code);
|
|
100
113
|
if (k < 0) return;
|
|
101
114
|
if (k === 32 || k === 258 || k === 259 || (k >= 262 && k <= 265)) e.preventDefault();
|
|
115
|
+
// Time travel's undo and redo chords are the game's, not the browser's.
|
|
116
|
+
if (globalThis.plumTimeTravel && (e.ctrlKey || e.metaKey) && (k === 90 || k === 89)) e.preventDefault();
|
|
117
|
+
if (e.metaKey && !MODIFIERS.includes(k)) {
|
|
118
|
+
// A held key's repeats are not presses: holding Cmd+Z is one press, as Ctrl+Z is.
|
|
119
|
+
if (e.repeat) return;
|
|
120
|
+
cmdTaps.add(k);
|
|
121
|
+
}
|
|
102
122
|
if (!e.repeat) keysPending.add(k);
|
|
103
123
|
keysDown.add(k);
|
|
124
|
+
tapsUp.delete(k);
|
|
125
|
+
tapsShown.delete(k);
|
|
104
126
|
});
|
|
105
127
|
window.addEventListener("keyup", (e) => {
|
|
106
128
|
const k = glfwKey(e.code);
|
|
129
|
+
if (k >= 0) {
|
|
130
|
+
if (keysPending.has(k)) tapsUp.add(k);
|
|
107
|
-
|
|
131
|
+
else keysDown.delete(k);
|
|
132
|
+
}
|
|
133
|
+
// macOS sends no keyup for a key let go while Cmd is down: once Cmd goes up, nothing
|
|
134
|
+
// else is taken to be held (Cmd+Z would otherwise leave Z down for good).
|
|
135
|
+
if (k === 343 || k === 347) keysDown.clear();
|
|
108
136
|
});
|
|
109
137
|
window.addEventListener("blur", () => {
|
|
110
138
|
keysDown.clear();
|
|
111
139
|
mouseDown.clear();
|
|
140
|
+
tapsUp.clear();
|
|
141
|
+
tapsShown.clear();
|
|
112
142
|
});
|
|
113
143
|
const track = (e) => {
|
|
114
144
|
const r = canvas.getBoundingClientRect();
|
|
@@ -141,6 +171,12 @@
|
|
|
141
171
|
mouse,
|
|
142
172
|
// Fixes what isKeyPressed / isMousePressed / mouseWheel report for the frame about to run.
|
|
143
173
|
beginFrame() {
|
|
174
|
+
for (const k of cmdShown) if (!cmdTaps.has(k)) keysDown.delete(k);
|
|
175
|
+
[cmdShown, cmdTaps] = [cmdTaps, cmdShown];
|
|
176
|
+
cmdTaps.clear();
|
|
177
|
+
for (const k of tapsShown) keysDown.delete(k);
|
|
178
|
+
[tapsShown, tapsUp] = [tapsUp, tapsShown];
|
|
179
|
+
tapsUp.clear();
|
|
144
180
|
[keysPressed, keysPending] = [keysPending, keysPressed];
|
|
145
181
|
keysPending.clear();
|
|
146
182
|
[mousePressed, mousePending] = [mousePending, mousePressed];
|
|
@@ -256,6 +292,13 @@
|
|
|
256
292
|
// distance field around them, into an ATLAS_W x ATLAS_H rgba texture (the
|
|
257
293
|
// distance is the alpha channel, 0.5 on the outline).
|
|
258
294
|
const GLYPH_BASE = 48;
|
|
295
|
+
// The advance widths, in thousandths of the size, of the characters from the space (32)
|
|
296
|
+
// to `~` (126), four digits each: std/game/Label's `Advances` (Arial's), which its bounds
|
|
297
|
+
// and its alignment go by. Text is laid out by them, not by the page font's own
|
|
298
|
+
// advances, so what is drawn is as wide as the label's bounds on every platform. A
|
|
299
|
+
// character past `~` is as wide as a digit; a control character takes no width.
|
|
300
|
+
const ADVANCES = "02780278035505560556088906670191033303330389058402780333027802780556055605560556055605560556055605560556027802780584058405840556101506670667072207220667061107780722027805000667055608330722077806670778072206670611072206670944066706670611027802780278046905560333055605560500055605560278055605560222022205000222083305560556055605560333050002780556050007220500050005000334026003340584";
|
|
301
|
+
const advanceOf = (cp) => (cp >= 32 && cp <= 126 ? Number(ADVANCES.substr((cp - 32) * 4, 4)) : cp >= 128 ? 556 : 0);
|
|
259
302
|
const GLYPH_SPREAD = 6;
|
|
260
303
|
const GLYPH_PAD = GLYPH_SPREAD;
|
|
261
304
|
const ATLAS_W = 2048;
|
|
@@ -536,9 +579,9 @@
|
|
|
536
579
|
const ty = (px, py) => y + (px - x) * si + (py - y) * co;
|
|
537
580
|
let pen = x;
|
|
538
581
|
for (const ch of str) {
|
|
539
|
-
const
|
|
582
|
+
const cp = ch.codePointAt(0);
|
|
540
|
-
|
|
583
|
+
const gl = env.glyph(cp);
|
|
541
|
-
if (gl.w > 0) {
|
|
584
|
+
if (gl && gl.w > 0) {
|
|
542
585
|
const x0 = pen - GLYPH_PAD * k;
|
|
543
586
|
const y0 = y - GLYPH_PAD * k;
|
|
544
587
|
const x1 = x0 + gl.w * k;
|
|
@@ -549,7 +592,7 @@
|
|
|
549
592
|
quad(env.atlas, tx(x0, y0), ty(x0, y0), tx(x1, y0), ty(x1, y0), tx(x1, y1), ty(x1, y1), tx(x0, y1), ty(x0, y1), gl.u0, gl.v0, gl.u1, gl.v1, c);
|
|
550
593
|
}
|
|
551
594
|
}
|
|
552
|
-
pen +=
|
|
595
|
+
pen += (advanceOf(cp) * size) / 1000;
|
|
553
596
|
}
|
|
554
597
|
},
|
|
555
598
|
setCamera,
|
|
@@ -974,8 +1017,9 @@ fn shade(i: VOut) -> vec4f {
|
|
|
974
1017
|
}
|
|
975
1018
|
}
|
|
976
1019
|
|
|
977
|
-
// The glyph atlas: ASCII and Latin-1 are drawn at start-up
|
|
1020
|
+
// The glyph atlas: ASCII and Latin-1 are drawn at start-up in Arial (or Helvetica or
|
|
1021
|
+
// Liberation Sans, which have its advances, `ADVANCES`; else the page's sans-serif),
|
|
978
|
-
//
|
|
1022
|
+
// other characters when first used. The pixels are kept so a
|
|
979
1023
|
// restored GPU device can upload them again. A glyph that no longer fits in the
|
|
980
1024
|
// atlas draws as `?`.
|
|
981
1025
|
function makeGlyphAtlas(getBackend, atlas) {
|
|
@@ -987,7 +1031,7 @@ fn shade(i: VOut) -> vec4f {
|
|
|
987
1031
|
const glyphs = new Map();
|
|
988
1032
|
const scratch = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(8, 8) : document.createElement("canvas");
|
|
989
1033
|
const c2d = scratch.getContext("2d", { willReadFrequently: true });
|
|
990
|
-
const font = GLYPH_BASE +
|
|
1034
|
+
const font = GLYPH_BASE + 'px Arial, Helvetica, "Liberation Sans", sans-serif';
|
|
991
1035
|
let px = 0;
|
|
992
1036
|
let py = 0;
|
|
993
1037
|
let rowH = 0;
|
|
@@ -1096,12 +1140,14 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1096
1140
|
}
|
|
1097
1141
|
|
|
1098
1142
|
// What the page's query asks for: `{ mode: 0 }`, `{ mode: 1 }` for `?record`, or
|
|
1099
|
-
// `{ mode: 2, url }` for `?replay=<url>` (a replay wins over a recording)
|
|
1143
|
+
// `{ mode: 2, url }` for `?replay=<url>` (a replay wins over a recording); with neither,
|
|
1144
|
+
// `{ mode: 3 }` on a page `plum run --dev` serves (`travel`, its `plumTimeTravel`).
|
|
1100
|
-
function replayRequest(search) {
|
|
1145
|
+
function replayRequest(search, travel) {
|
|
1101
1146
|
const params = new URLSearchParams(search);
|
|
1102
1147
|
const url = params.get("replay");
|
|
1103
1148
|
if (url) return { mode: 2, url };
|
|
1104
1149
|
if (params.has("record")) return { mode: 1 };
|
|
1150
|
+
if (travel) return { mode: 3 };
|
|
1105
1151
|
return { mode: 0 };
|
|
1106
1152
|
}
|
|
1107
1153
|
|
|
@@ -1113,7 +1159,7 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1113
1159
|
}
|
|
1114
1160
|
|
|
1115
1161
|
async function makeReplay(view) {
|
|
1116
|
-
const req = replayRequest(location.search);
|
|
1162
|
+
const req = replayRequest(location.search, !!globalThis.plumTimeTravel);
|
|
1117
1163
|
if (req.mode === 2) {
|
|
1118
1164
|
const res = await fetch(req.url);
|
|
1119
1165
|
if (!res.ok) throw new Error("replay " + req.url + ": HTTP " + res.status);
|
|
@@ -1137,6 +1183,12 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1137
1183
|
append() {},
|
|
1138
1184
|
};
|
|
1139
1185
|
}
|
|
1186
|
+
if (req.mode === 3) {
|
|
1187
|
+
// `plum run --dev` (ReplayMode.Dev): the game keeps its own history for time travel
|
|
1188
|
+
// and reads the time travel keys; nothing is recorded.
|
|
1189
|
+
console.log("plum: time travel ([ ] step, \\ pause, Ctrl/Cmd+Z undo, Ctrl/Cmd+Y or Shift+Z redo)");
|
|
1190
|
+
return { mode: 3, text: "", screen: (_, live) => live, randomHalf: (fresh) => fresh(), append() {} };
|
|
1191
|
+
}
|
|
1140
1192
|
if (req.mode !== 1) return { mode: 0, text: "", screen: (_, live) => live, randomHalf: (fresh) => fresh(), append() {} };
|
|
1141
1193
|
const halves = [];
|
|
1142
1194
|
let served = 0;
|
|
@@ -1311,6 +1363,10 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1311
1363
|
const ctx = { plum: null };
|
|
1312
1364
|
const fileStrs = new Map(); // path -> Plum Str, built once per path
|
|
1313
1365
|
let dt = 1 / 60;
|
|
1366
|
+
// Set by `frameIdle` during `update` (std/game/Game's `hostFrame`): the screen shown is
|
|
1367
|
+
// `OnDemand` and has nothing new to draw, so the frame is not drawn and, unless a replay
|
|
1368
|
+
// is playing, no frame is asked for until input arrives.
|
|
1369
|
+
let idle = false;
|
|
1314
1370
|
|
|
1315
1371
|
const host = {
|
|
1316
1372
|
screenWidth: () => replay.screen(0, view.w),
|
|
@@ -1375,6 +1431,9 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1375
1431
|
isMousePressed: input.isMousePressed,
|
|
1376
1432
|
mouseWheel: input.mouseWheel,
|
|
1377
1433
|
rawRandomHalf: () => replay.randomHalf(() => (Math.random() * 4294967296) | 0),
|
|
1434
|
+
frameIdle: () => {
|
|
1435
|
+
idle = true;
|
|
1436
|
+
},
|
|
1378
1437
|
replayMode: () => replay.mode,
|
|
1379
1438
|
replayText: () => bytesToStr(ctx.plum, new TextEncoder().encode(replay.text)),
|
|
1380
1439
|
replayAppend: (s) => replay.append(strToJs(ctx.plum, s)),
|
|
@@ -1388,6 +1447,20 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1388
1447
|
},
|
|
1389
1448
|
};
|
|
1390
1449
|
|
|
1450
|
+
// plum-web-test sets __plumDrawLog to an object before the page loads: the page then
|
|
1451
|
+
// counts the frames it runs (`frames`) and draws (`draws`), and `last` holds the last
|
|
1452
|
+
// frame drawn's texts in CSS pixels. Not set otherwise.
|
|
1453
|
+
const probe = globalThis.__plumDrawLog || null;
|
|
1454
|
+
let probeFrame = null;
|
|
1455
|
+
if (probe) {
|
|
1456
|
+
Object.assign(probe, { frames: 0, draws: 0, last: null });
|
|
1457
|
+
const { drawText } = host;
|
|
1458
|
+
host.drawText = (s, x, y, size, ...rest) => {
|
|
1459
|
+
if (probeFrame) probeFrame.texts.push({ s: strToJs(ctx.plum, s), at: [(x - b.cam.x) * b.cam.s, (y - b.cam.y) * b.cam.s], size: size * b.cam.s });
|
|
1460
|
+
return drawText(s, x, y, size, ...rest);
|
|
1461
|
+
};
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1391
1464
|
const instance = await instantiatePlum(host);
|
|
1392
1465
|
ctx.plum = instance.exports;
|
|
1393
1466
|
const ex = ctx.plum;
|
|
@@ -1405,22 +1478,49 @@ fn shade(i: VOut) -> vec4f {
|
|
|
1405
1478
|
const m = globalThis.__plumMeasure; // set by plum-web-test --measure; null otherwise
|
|
1406
1479
|
const t0 = m ? performance.now() : 0;
|
|
1407
1480
|
// `update` is handed the wall time since the last frame and runs the game's fixed
|
|
1408
|
-
// 1/60 s ticks it covers (`
|
|
1481
|
+
// 1/60 s ticks it covers (`Ticker` in std/game/Game). While plum-web-test measures,
|
|
1409
1482
|
// each frame is handed one tick, so update_ms is one tick's work at any frame rate.
|
|
1483
|
+
idle = false;
|
|
1410
1484
|
state = ex.update(state, m ? 1 / 60 : dt);
|
|
1485
|
+
if (probe) probe.frames++;
|
|
1486
|
+
if (!idle) {
|
|
1411
|
-
|
|
1487
|
+
const t1 = m ? performance.now() : 0;
|
|
1488
|
+
if (probe) probeFrame = { texts: [] };
|
|
1412
|
-
|
|
1489
|
+
ex.draw(state);
|
|
1413
|
-
|
|
1490
|
+
const t2 = m ? performance.now() : 0;
|
|
1414
|
-
|
|
1491
|
+
const draws = backend.submit(b);
|
|
1415
|
-
|
|
1492
|
+
if (m) { m.n++; m.u += t1 - t0; m.d += t2 - t1; m.r += performance.now() - t2; m.dr += draws; }
|
|
1493
|
+
if (probe) {
|
|
1494
|
+
probe.last = probeFrame;
|
|
1495
|
+
probeFrame = null;
|
|
1496
|
+
probe.draws++;
|
|
1497
|
+
}
|
|
1498
|
+
}
|
|
1416
1499
|
} catch (e) {
|
|
1417
1500
|
console.error("frame failed:", e);
|
|
1418
1501
|
// The game stops here; say so on the page, not only in the console.
|
|
1419
1502
|
document.body.append(Object.assign(document.createElement("pre"), { textContent: "plum game stopped: " + String(e), style: "position:fixed;top:0;left:0;color:#f55;margin:8px" }));
|
|
1420
1503
|
return;
|
|
1421
1504
|
}
|
|
1505
|
+
if (idle && replay.mode !== 2 && !globalThis.__plumMeasure) {
|
|
1506
|
+
sleepUntilInput();
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1422
1509
|
requestAnimationFrame(frame);
|
|
1423
1510
|
}
|
|
1511
|
+
// An idle frame asks for no next one: the canvas keeps the last frame drawn, and the
|
|
1512
|
+
// first input (or a resize) asks for a frame again, one tick after the last.
|
|
1513
|
+
const WAKERS = ["keydown", "keyup", "pointerdown", "pointerup", "pointermove", "wheel", "resize", "blur"];
|
|
1514
|
+
function sleepUntilInput() {
|
|
1515
|
+
const wake = () => {
|
|
1516
|
+
for (const ev of WAKERS) window.removeEventListener(ev, wake);
|
|
1517
|
+
requestAnimationFrame((now) => {
|
|
1518
|
+
last = now - 1000 / 60;
|
|
1519
|
+
frame(now);
|
|
1520
|
+
});
|
|
1521
|
+
};
|
|
1522
|
+
for (const ev of WAKERS) window.addEventListener(ev, wake);
|
|
1523
|
+
}
|
|
1424
1524
|
requestAnimationFrame((now) => {
|
|
1425
1525
|
last = now - 1000 / 60;
|
|
1426
1526
|
frame(now);
|
docs/backlog.md
CHANGED
|
@@ -4,17 +4,13 @@ Open work on `simpler-language`, rewritten 2026-11-11. Only what is still open i
|
|
|
4
4
|
|
|
5
5
|
## Screen views (branch `sl/view`, 2026-11-12)
|
|
6
6
|
|
|
7
|
-
The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, `Control` for effects, undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks is master's (925878360). On 2026-11-13 it was brought up to master at e91c40ce (stages 24 and 25 and the review after 24): `View` and `Actor[View]`, actors stepped by the game through the screen's `stepped(dt)`, `Screen.hud`, `steps` and `camera`, one walk over `view`, turned boxes and text, the other mouse buttons and keys, the per-screen backgrounds and dropped pointer events of a transition (the "Beside master" table has what still differs). Open:
|
|
7
|
+
The retained scene tree was replaced by master's screen view in functional form: a `Game(screens: ..)` of `Screen`s, a `ScreenSlice<A>` per screen with rules (master's `Slice<A>`), a `view` each frame that the game draws and hit-tests itself, `Control` for effects, undo and time travel by re-simulation, and the headless kit (`docs/game.md`, "Beside master", has the table of differences). `SceneTree`, `Ctx`, `Clickable`, `Store` and `ui` are gone, with the examples that used them (`orb_run`, `kids/balloon_pop`, now `examples/games/orbitrunner` and `balloonpop`), `benchmarks/scene_trees` and two web-test stress fixtures (their results stay in `docs/benchmarks` and `compiler/game/web-test/BENCHMARK.md`). Orbit Runner's state checksum over four seeds of 3,600 ticks is master's (925878360). On 2026-11-13 it was brought up to master at e91c40ce (stages 24 and 25 and the review after 24): `View` and `Actor[View]`, actors stepped by the game through the screen's `stepped(dt)`, `Screen.hud`, `steps` and `camera`, one walk over `view`, turned boxes and text, the other mouse buttons and keys, the per-screen backgrounds and dropped pointer events of a transition (the "Beside master" table has what still differs). On 2026-11-13 (branch `sl/game-ports`) master's later framework work followed: the stepping of what a `Group` or an `Overlay` holds, frames on demand in the hosts (`frameIdle`), `plum run --dev` and its time travel keys, the window's size on the tick's input, the `Ticker`, a `Label`'s width from Arial's advance widths (in std and the browser's layout; master still estimates it) and `plum compile <folder>`. Open:
|
|
8
8
|
|
|
9
9
|
- **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
|
|
10
10
|
- **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
|
|
11
|
-
- **Frames on demand in the hosts**: `Game.idle()` works, but no host is told (master's `frameIdle` extern, and the browser skipping the draw and waiting for input).
|
|
12
|
-
- **Development keys** (`plum run --dev`, master's `remakeGame` host call): a game offers undo only through its own effects.
|
|
13
11
|
- **Master's other games** (`clockwork`, `menu`) are not ported.
|
|
14
12
|
- **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
|
|
15
13
|
- **Stepping without the screen naming its actors**: the game cannot step an actor found in a view, as the screen holding it is a value; each screen maps its own fields in `stepped`. A lens per field, or a view walk that rebuilds the screen, would let std do it; not designed.
|
|
16
|
-
- **Real font metrics** for a `Label`'s width, which its bounds and `align` go by (0.6 of the size a letter), as on master.
|
|
17
|
-
- **The window's size on the tick's input** (master's `input.screen`) and master's `Ticker` name for `Clock`: not ported.
|
|
18
14
|
|
|
19
15
|
## Decided, not built
|
|
20
16
|
|
docs/game.md
CHANGED
|
@@ -10,7 +10,7 @@ Write a game in Plum and run it in the browser on Plum's own WebGPU renderer. It
|
|
|
10
10
|
plum run examples/games/orbitrunner/OrbitRunner.plum
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
This builds the game, starts a local server and opens your browser. `plum run examples/games/orbitrunner` does the same: given a folder, `plum run` and `plum
|
|
13
|
+
This builds the game, starts a local server and opens your browser. `plum run examples/games/orbitrunner` does the same: given a folder, `plum run`, `plum build` and `plum compile` take the one `.plum` file in it with the program's `[App]` primitive, which holds its `main` (none, or more than one, is an error that says so). Steer with the arrow keys or WASD, collect the orbs and dodge the mines; when the game is over, Enter or R plays again. Press a key first, because browsers only start sound after you interact with the page. `examples/games/balloonpop/BalloonPop.plum` is the other example game: press the balloons, and Z or Backspace takes the last press back.
|
|
14
14
|
|
|
15
15
|
## A game's files
|
|
16
16
|
|
|
@@ -158,7 +158,7 @@ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture)
|
|
|
158
158
|
Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
|
|
159
159
|
```
|
|
160
160
|
|
|
161
|
-
**Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen says where its actors are, in one line that maps its fields (`Views.stepAll` steps each actor of a list, `Views.stepIn` each `Actor` of a `List<View>`, the others as they are):
|
|
161
|
+
**Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen says where its actors are, in one line that maps its fields (`Views.stepAll` steps each actor of a list, `Views.stepIn` each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are):
|
|
162
162
|
|
|
163
163
|
```plum
|
|
164
164
|
fun steps(self) -> Bool = !self.over
|
|
@@ -167,7 +167,7 @@ fun stepped(self, dt: Float) -> PlayingScreen =
|
|
|
167
167
|
PlayingScreen(..self, mines: Views.stepAll(self.mines, dt), orbs: Views.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: Views.stepAll(self.rings, dt))
|
|
168
168
|
```
|
|
169
169
|
|
|
170
|
-
That is the only line a game writes for stepping, one per screen that holds actors; the default returns the screen as it is. A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick. An actor the screen leaves out of `stepped` is not stepped, whether it is in the view or not, and one stepped there moves whether it is visible or not. So the tick action only runs the rules on what has moved:
|
|
170
|
+
That is the only line a game writes for stepping, one per screen that holds actors; the default returns the screen as it is. A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick. An actor steps what it holds itself, in its own `step` (`Views.stepIn` doesn't look inside an actor, nor make its view); a `Group` or an `Overlay` is made again with its actors stepped; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. An actor the screen leaves out of `stepped` is not stepped, whether it is in the view or not, and one stepped there moves whether it is visible or not. So the tick action only runs the rules on what has moved:
|
|
171
171
|
|
|
172
172
|
```plum
|
|
173
173
|
fun advance(self, dt: Float) -> PlayingScreen =
|
|
@@ -195,7 +195,7 @@ The ready-made kinds are made with their fields named, and their fields have def
|
|
|
195
195
|
| `Box` | `x, y, w, h, color, touch` (x, y its top-left) | `x: 0.0, y: 0.0, touch: Disabled` |
|
|
196
196
|
| `Circle` | `x, y, r, color, touch` (x, y its centre: its bounds are -r to r) | `x: 0.0, y: 0.0, touch: Disabled` |
|
|
197
197
|
| `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` |
|
|
198
|
-
| `Label` | `x, y, text, size, color, align, touch`; `align` puts the text's start (`Left`), middle (`Centre`) or end (`Right`) on `x`, by
|
|
198
|
+
| `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` |
|
|
199
199
|
| `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` |
|
|
200
200
|
|
|
201
201
|
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`.
|
|
@@ -208,13 +208,13 @@ Nothing is kept between frames, and there is no tree: the game keeps the screens
|
|
|
208
208
|
|
|
209
209
|
## Fixed timestep and determinism
|
|
210
210
|
|
|
211
|
-
The host adds up the time between frames and runs one tick (`Game.update`) for each whole tick, always with the same `dt` of 1/60 s. A slow frame runs several ticks (a 50 ms frame runs 3) and a fast one, on a 120 Hz screen say, may run none. A frame runs at most eight ticks: after a longer stall the rest is dropped, so the game slows down for a moment instead of falling ever further behind. The
|
|
211
|
+
The host adds up the time between frames and runs one tick (`Game.update`) for each whole tick, always with the same `dt` of 1/60 s. A slow frame runs several ticks (a 50 ms frame runs 3) and a fast one, on a 120 Hz screen say, may run none. A frame runs at most eight ticks: after a longer stall the rest is dropped, so the game slows down for a moment instead of falling ever further behind. The driver that does this is `Ticker` (`Ticker.Tick`, `Ticker.MaxTicks`) in [`std/game/Game.plum`](../std/game/Game.plum), held beside the game in `GameRun`, the state the host keeps between frames.
|
|
212
212
|
|
|
213
|
-
The tick's `Input` is read from the host once per frame, before the ticks. 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 mapping (`onKey`, `held`, ..); don't read input any other way.
|
|
213
|
+
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 mapping (`onKey`, `held`, ..); don't read input any other way.
|
|
214
214
|
|
|
215
215
|
Keep randomness in the screen: a `Random` ([`std/math/Random.plum`](../std/math/Random.plum)) seeded once in `main` from `io.randomSeed()`, threaded through each draw (`r := self.rng.nextFloat()`, then keep `r.rng` in the next screen). Then the same seed and the same inputs give the same game, tick for tick. Orbit Runner's state after 3,600 ticks of each of four seeds under a scripted input has the same checksum as master's imperative Orbit Runner (`benchmarks/screen_views/orbit.plum`).
|
|
216
216
|
|
|
217
|
-
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
|
|
217
|
+
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.
|
|
218
218
|
|
|
219
219
|
## Record and replay
|
|
220
220
|
|
|
@@ -225,7 +225,7 @@ A run of a game is its seed and one `Input` per tick, so a recording is that and
|
|
|
225
225
|
- **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.
|
|
226
226
|
- **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.
|
|
227
227
|
|
|
228
|
-
While recording, the host remembers what `io.randomSeed()` returned in `main`, and the game's `
|
|
228
|
+
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.
|
|
229
229
|
|
|
230
230
|
The text is one line for the seed and screen size, then one line per tick (the held keys, the mouse button, the pointer, the wheel and the tick's events). Floats are written exactly. The details are at the top of `std/game/Replay.plum`.
|
|
231
231
|
|
|
@@ -266,7 +266,16 @@ A move that can't be made (no history, a full one, a tick out of reach) leaves t
|
|
|
266
266
|
|
|
267
267
|
**What it costs.** A rewind back costs the ticks it plays: `rewindTo(k)` plays `k` ticks from the start, with no drawing and no effects. 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.
|
|
268
268
|
|
|
269
|
-
**
|
|
269
|
+
**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:
|
|
270
|
+
|
|
271
|
+
| Key | What it does |
|
|
272
|
+
|---|---|
|
|
273
|
+
| `\` | pauses, or resumes from where the game is (dropping what could be redone) |
|
|
274
|
+
| `[`, `]` | pauses and steps a tick back, or forward along what was stepped back over |
|
|
275
|
+
| Ctrl or Cmd with `Z` | undo: back to just before the last user action |
|
|
276
|
+
| Ctrl or Cmd with `Y`, or with Shift and `Z` | redo |
|
|
277
|
+
|
|
278
|
+
A line along the bottom of the window says where the game is (`tick 412 of 980 (paused)`). The keys are read once a frame, before the game's input, and never reach the game: `[`, `]`, `\`, Ctrl and Cmd are kept from it while they are down, and a `Z`, `Y` or Shift that goes down with Ctrl or Cmd is kept from it until it is let go (std/game/History's `TravelKeys`; the `Ticker` reads them and `Game.devFrame` does their commands). A Shift held before the Ctrl or Cmd is the game's. Outside `--dev` they are the game's keys like any other. The page's undo and redo chords don't reach the browser either, and on macOS, which sends no key up for a key let go while Cmd is down, the page lets such a key go once a frame has seen it, so Cmd held and Z tapped twice undoes twice. The host's `ReplayMode` is `Dev` (3); `--dev` is not for `plum build` or `--replay`. Unlike master, the host is not asked to make the game again for a rewind (master's `remakeGame`): the game keeps the screens it was made with.
|
|
270
279
|
|
|
271
280
|
## What a game can use
|
|
272
281
|
|
|
@@ -323,7 +332,7 @@ fun frames(self) -> Frames = OnDemand
|
|
|
323
332
|
|
|
324
333
|
It then ticks as an `Always` screen until it goes quiet again. A tick it sleeps through is still a tick of the run: a recording keeps its input, and whether the screen sleeps is worked out from that input and the screen's state alone, so a replay sleeps through the same ticks. `Game.delivered` and `Game.skipped` count the ticks delivered and slept through. `Game.idle()` is true when the shown screen is `OnDemand`, no transition runs and no tick has run since the last frame drawn (`frameDrawn()`, which a test calls).
|
|
325
334
|
|
|
326
|
-
**The host.**
|
|
335
|
+
**The host.** At the end of each frame's ticks the frame entry point (`GameRun.frame`) tells the host when the frame is idle (`Game.hostFrame`, the `frameIdle` host call); any other frame the host draws right after, so it counts as drawn. The browser then skips the draw, keeps the last frame on the canvas and asks for no next frame until input comes (a key, a press, a pointer move, the wheel, a resize or the page losing focus), one tick after the last; a replay keeps its frames coming. The native host's `PlumGame::idle()` says the same, and `plum-game` skips an idle frame's draw. A paused development run is idle the same way once its frame is drawn.
|
|
327
336
|
|
|
328
337
|
## The slice
|
|
329
338
|
|
|
@@ -417,7 +426,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
417
426
|
| | |
|
|
418
427
|
|---|---|
|
|
419
428
|
| 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)` |
|
|
420
|
-
| Time | `tick()` (the game's own tick: mapping, the step, reducer, transition, effects and what they ask), `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 `
|
|
429
|
+
| Time | `tick()` (the game's own tick: mapping, the step, reducer, transition, effects and what they ask), `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 |
|
|
421
430
|
| An action | `dispatch(a)`: reduced into the screen as its reducer would dispatch it, then what ends a tick: its effects with what they ask, an undo, a redo or a rewind done at once |
|
|
422
431
|
| 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()`) |
|
|
423
432
|
| What came out of the last `tick` or `ticks` | `effects<A>()` (the actions of type `A` whose effects ran, in order), `wentTo()` (an `Option`), `exited()`; `showing()` names the screen shown |
|
|
@@ -436,7 +445,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
436
445
|
u := t.press(Key.Space).tick()
|
|
437
446
|
assert u.screen.over
|
|
438
447
|
v := u.press(Key.Enter).tick()
|
|
439
|
-
assert playingscreen.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({
|
|
448
|
+
assert playingscreen.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({Ticker.Tick})"
|
|
440
449
|
assert !v.screen.over
|
|
441
450
|
```
|
|
442
451
|
|
|
@@ -449,7 +458,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
449
458
|
| Master | Here | Why |
|
|
450
459
|
|---|---|---|
|
|
451
460
|
| `trait Actor[View]` with `step(&self, dt)` | `step(self, dt) -> Self` | a value is not changed in place: `step` returns the actor's next version |
|
|
452
|
-
| the game walks the view and the hud and steps
|
|
461
|
+
| the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the game calls the screen's `stepped(dt) -> Self` (default: the screen as it is), which maps the fields that hold actors (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
|
|
453
462
|
| `trait Slice<A>[Screen]` | `trait ScreenSlice<A>[Screen]` | `Slice` is std's growable array here, and a trait can't share a type's name |
|
|
454
463
|
| `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` | `fun reduce(self, a: A) -> Self`, `fun dispatch(self, a: A) -> Self` | the reducer returns the next screen |
|
|
455
464
|
| `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
|
|
@@ -457,8 +466,10 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
457
466
|
| `Effects`, one queue of `Queued<A>` holding each action with its slice, set in one slot around a delivery | one slot too (`Effects.startDispatch`), holding the delivery's queue of its own action type; after the tick each action is held with the slice as the tick left it (`Queued<A>`), and `Effects.sent<A>(list)` reads them | an effect must see the slice the tick left, which is a new value, not the one the action was reduced into |
|
|
458
467
|
| `Viewport` updated in place (`v.update(w, h)`), `lookAt(x, y, zoom = 1.0)` | `Viewport.of(..).update(w, h) -> Viewport`, the same `lookAt` and `moved` | a value |
|
|
459
468
|
| the frame sets the host's camera (`setCamera`) for a camera with one scale, and puts a `Stretch` camera into the transform | every camera goes into the transform the view is drawn through, in window pixels, and culling maps its area through it | this branch's draw has always gone through the transform; the host sees no `setCamera`/`resetCamera` in a frame, so the recorder's calls differ (`compiler/game/tests/host_test.rs` checks the pixels) |
|
|
460
|
-
| the window's size on each tick's input (`input.screen`, `Input.sized`) |
|
|
461
|
-
| the fixed-timestep driver is `Ticker` (`Ticker.Tick`, `game.ticker.ticks`) | `
|
|
469
|
+
| the window's size on each tick's input (`input.screen`, `Input.sized`) | the same; `Game.step(io, input, dt, pixels)` takes it from a test, and an input of 0 by 0 leaves the window as it was | |
|
|
470
|
+
| the fixed-timestep driver is `Ticker` (`Ticker.Tick`, `game.ticker.ticks`), a field of the game | `Ticker` (`Ticker.Tick`), a value held beside the game in `GameRun` (`run.ticker.ticks`), `game.ticks`, the rig's `t.frame(..)` | the game is a value that the frame's ticks return, so the ticker that runs them is held beside it |
|
|
471
|
+
| `timeTravel(make)`, and `plum run --dev`'s rewind asks the host to run `main` again (`remakeGame`, with the run's seed, its textures and no sound) | `timeTravel(cap)`; the same development keys, line and host mode, with no `remakeGame` | the game keeps the screens it was made with, so a rewind needs no host call |
|
|
472
|
+
| a `Label`'s width an estimate, 0.6 of its size a letter (master's backlog: real font metrics) | Arial's advance widths, in std (`Label.Advances`) and in the browser's layout (`ADVANCES`) | a host call that measured text would make a tick that hits a label read the host, and differ between hosts and in a replay; a table in std is the same everywhere, and the browser lays text out by it |
|
|
462
473
|
| actor and view fields with defaults (`Box(w:, h:)`, `Held(buttons: [])`) | the same: struct fields with defaults (`Label(x:, y:, text:)`, `Held(keys: k)`, `Held()`) | master's `Box` and `Group` default their size too; here every kind defaults its place (`x: 0.0, y: 0.0`) and names its size |
|
|
463
474
|
| `Tween` advanced in place | `tween.advance(dt) -> Tween` | a value |
|
|
464
475
|
| `Game` mutated by `update(&self, ..)` | `update(self, io, input, dt) -> Game`, `step(self, io, input, dt, pixels) -> Game` | the game is a value |
|
|
@@ -466,13 +477,13 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
|
|
|
466
477
|
| `timeTravel(make: fn(Io) -> Game, cap)` | `timeTravel(cap) -> Game` | the game keeps the screens it was made with |
|
|
467
478
|
| `rewindTo`, `undo`, `redo`, .. `-> Bool` | `-> Game`, with `game.moved` | the move returns the moved game |
|
|
468
479
|
| the kit's `t.press(k)` (in place) | `u := t.press(k)` | a rig is a value |
|
|
469
|
-
| a view literal's `if`, `for`, `..` elements | `
|
|
480
|
+
| a view literal's `if`, `for`, `..` elements | `if` and `..` items and children blocks (`Overlay(..) {` + an item a line + `}`); no `for` item: `..xs.map(..)` | a `for` item would be a second way to write a `map` |
|
|
470
481
|
| std's test helper types private (`_ViewProbe`, `_KitScreen`, ..) | public names (`ViewProbe`, `Stepper`, ..) | a type's name here is the module's: a game's own `Stepper` beside std's compiles, so there is no clash to avoid (checked with a probe) |
|
|
471
482
|
| `std/game` without `Anim` | `std/game/Anim` kept (pure animations of time) | a web-test fixture uses it; no example game does |
|
|
472
483
|
|
|
473
|
-
The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `steps`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`; no `restart`), pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, `Input.axis`, `isMouseDown(b)`, `isMousePressed(b)`, `isMouseReleased(b)`, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, and Orbit Runner's state checksum (925878360).
|
|
484
|
+
The same on both: `View` (`place`, `view`, `visible`, `paintSelf`, the shared empty default), the walks (`Views.paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), `Screen` (`name`, `view`, `hud(window)`, `steps`, `camera(base)`, `size`, `viewport`, `culls`, `busy`, `background`, `transition`, `frames`; no `enter`, `leave`, `resize`, `draw` or `fresh`), `Control` (`goTo`, `exit`, `undo`, `redo`, `rewindTo`; no `restart`), pointer events dropped during a transition, each screen on its own background in one, the ready-made views (Circle by its centre, `Label(align:)`, `Overlay` with a required size hit inside its box, `Sprite.frameAt`), `Gfx.drawRectEx` and `drawTextEx` in std, the browser, the native host and the recorder, the input (`ButtonDown`, `ButtonUp`, `Held.buttons`, the extra `Key`s, `Input.axis`, `isMouseDown(b)`, `isMousePressed(b)`, `isMouseReleased(b)`, the replay's button mask and `B`/`b` events), `Math.near`, `Game.pixels`, `frameDrawn()`, `drawList()`, `camera(i)`, `toWorld`, `toScreen`, `visible(i)`, `travelAsked`, frames on demand in the hosts (`frameIdle`, the browser waiting for input, `PlumGame::idle`), `plum run --dev` (its keys, its line, the page's Cmd key fixes), `plum compile <folder>`, and Orbit Runner's state checksum (925878360).
|
|
474
485
|
|
|
475
|
-
Not ported: master's
|
|
486
|
+
Not ported: master's `clockwork` and `menu` games; see the [backlog](backlog.md). This branch keeps `examples/games/clicks.plum` and `two_screens.plum`, which master doesn't have.
|
|
476
487
|
|
|
477
488
|
## Publishing
|
|
478
489
|
|
docs/tools.md
CHANGED
|
@@ -6,11 +6,11 @@
|
|
|
6
6
|
|
|
7
7
|
| Command | What it does |
|
|
8
8
|
|---|---|
|
|
9
|
-
| `plum run file.plum` | Compile and run. A program whose `main` returns a [game](game.md), a type with `update` and `draw`, opens in the browser. Given a folder (`plum run examples/games/orbitrunner`), it runs the one `.plum` file in the folder with the program's `primitive <Name>[App]` (its `main`); `plum build`
|
|
9
|
+
| `plum run file.plum` | Compile and run. A program whose `main` returns a [game](game.md), a type with `update` and `draw`, opens in the browser. Given a folder (`plum run examples/games/orbitrunner`), it runs the one `.plum` file in the folder with the program's `primitive <Name>[App]` (its `main`); `plum build` and `plum compile` do the same |
|
|
10
10
|
| `plum run file.plum -- a b` | Run with arguments: the words after `--` are the program's `io.args()` (here `a` and `b`). A `plum build` executable gets its own arguments the same way; `plum test` and a game in the browser get none |
|
|
11
11
|
| `plum test tests/ file.plum` | Run the tests (the funs of each `primitive XTest[UnitTest]`) in files and folders |
|
|
12
12
|
| `plum check file.plum dir/` | Type-check files and folders without compiling or running them |
|
|
13
|
-
| `plum compile file.plum` | Write `file.wasm` (`-o` names the file) |
|
|
13
|
+
| `plum compile file.plum` | Write `file.wasm` (`-o` names the file). Given a folder, the `.wasm` of its file with `main` is written beside that file |
|
|
14
14
|
| `plum build file.plum` | Make a native executable, or for a game, a static site |
|
|
15
15
|
| `plum format file.plum` | Format the file in place (`--check` only checks, `--stdin` reads standard input) |
|
|
16
16
|
| `plum editor helix` | Set up Helix |
|
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
| `--no-open` | Don't open the browser |
|
|
26
26
|
| `--no-watch` | Don't rebuild and reload when files change |
|
|
27
27
|
| `--replay FILE` | Replay a recorded run headless, with no browser, and print the draw calls of its last frame (see [Record and replay](game.md#record-and-replay)) |
|
|
28
|
+
| `--dev` | A development run: the game keeps its history, and `[`, `]`, `\`, Ctrl or Cmd with `Z`, and with `Y` step, pause, undo and redo it (see [the development keys](game.md#undo-and-time-travel)) |
|
|
28
29
|
|
|
29
30
|
**Options for `plum build`:**
|
|
30
31
|
|
std/game/Game.plum
CHANGED
|
@@ -5,6 +5,7 @@ import std/Float
|
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/Str
|
|
7
7
|
import std/Option
|
|
8
|
+
import std/Result
|
|
8
9
|
import std/Pair
|
|
9
10
|
import std/Slice
|
|
10
11
|
import std/collections/List
|
|
@@ -22,6 +23,7 @@ import std/game/Viewport
|
|
|
22
23
|
import std/game/Control
|
|
23
24
|
import std/game/Screen
|
|
24
25
|
import std/game/History
|
|
26
|
+
import std/game/Replay
|
|
25
27
|
|
|
26
28
|
# A game: its screens. `main(io: Io)` returning a `Game` runs as a game; anything else is
|
|
27
29
|
# a command line program. A game writes its actors and its screens, and makes one. A
|
|
@@ -39,16 +41,17 @@ import std/game/History
|
|
|
39
41
|
# A game is a value: each tick returns the next game, and the screens in it are the ones
|
|
40
42
|
# the tick left. A screen left and shown again is as it was left.
|
|
41
43
|
#
|
|
42
|
-
# The window's size in pixels (`pixels`) comes
|
|
44
|
+
# The window's size in pixels (`pixels`) comes with each tick's input (`Input.screen`,
|
|
45
|
+
# which the `Ticker` reads from the host once a frame, and a replay from its header) for
|
|
43
|
-
# the test (`step`). Each screen is seen through a camera worked out from its `size()`,
|
|
46
|
+
# `update`, or from the test (`step`). Each screen is seen through a camera worked out from its `size()`,
|
|
44
47
|
# its `viewport()`, the window's size and its `camera(base)` (`camera(i)`,
|
|
45
48
|
# `Game.cameraOf`): the game maps a press through it to the world's
|
|
46
49
|
# coordinates, draws the screen's `view` through it and, for a screen that `culls()`,
|
|
47
50
|
# skips what it doesn't show.
|
|
48
51
|
#
|
|
49
|
-
# The compiler adds the frame entry points the host calls
|
|
52
|
+
# The compiler adds the frame entry points the host calls (`GameRun`, below): they run
|
|
50
|
-
# fixed 1/60 s tick of the frame (
|
|
53
|
+
# `update` once per fixed 1/60 s tick of the frame (the `Ticker`, which also records and
|
|
51
|
-
# the ticks' input, std/game/Replay) and `draw` once a frame.
|
|
54
|
+
# replays the ticks' input, std/game/Replay) and `draw` once a frame.
|
|
52
55
|
#
|
|
53
56
|
# One tick (`update`, or `step` with the window's size given, as a test runs it): the
|
|
54
57
|
# current screen gets the tick (`deliver`, with a `Delivery`: the tick's input, its
|
|
@@ -68,7 +71,9 @@ import std/game/History
|
|
|
68
71
|
#
|
|
69
72
|
# A screen whose `frames()` is `OnDemand` sleeps through the ticks in which nothing needs
|
|
70
73
|
# doing (docs/game.md, "Frames on demand"): `update` delivers it nothing, and once the
|
|
71
|
-
# last frame drawn shows the screen as it is (`frameDrawn`), `idle()` is true.
|
|
74
|
+
# last frame drawn shows the screen as it is (`frameDrawn`), `idle()` is true. The host's
|
|
75
|
+
# frame then tells the host so (`hostFrame`, the `frameIdle` host call): it skips the
|
|
76
|
+
# draw, keeps the last frame shown and, in a browser, waits for input. `delivered`,
|
|
72
77
|
# `skipped` and `draws` count the ticks delivered, the ticks slept through and the frames
|
|
73
78
|
# drawn, for tests; `ran` and `asked` are the effects that ran in the last tick and what
|
|
74
79
|
# they asked of the game (std/game/TestRig reads them).
|
|
@@ -82,7 +87,9 @@ import std/game/History
|
|
|
82
87
|
# through the same tick as ever (`run`), with no effects run: what they asked of the game
|
|
83
88
|
# (a `goTo`) is recorded and done again, an `exit` is not. `pause()` holds
|
|
84
89
|
# the game still until `resume()`, which drops what could be redone. `rewound` is how many
|
|
85
|
-
# ticks the last move played.
|
|
90
|
+
# ticks the last move played. A development run (`plum run --dev`) does this from the
|
|
91
|
+
# first frame and moves with the time travel keys (`devFrame`, std/game/History's
|
|
92
|
+
# `TravelKeys`), showing where it is along the bottom of the window (`devLine`).
|
|
86
93
|
struct Game(screens: List<Screen>) =
|
|
87
94
|
fun init(self) =
|
|
88
95
|
self.initial: List<Screen> = self.screens
|
|
@@ -113,6 +120,7 @@ struct Game(screens: List<Screen>) =
|
|
|
113
120
|
self.paused: Bool = false
|
|
114
121
|
self.rewound: Int = 0
|
|
115
122
|
self.moved: Bool = false
|
|
123
|
+
self.dev: Bool = false
|
|
116
124
|
if self.screens.isEmpty()
|
|
117
125
|
crash "game: a game needs a screen"
|
|
118
126
|
if Some(dup) := Game.duplicateName(self.screens, Nil)
|
|
@@ -145,9 +153,10 @@ struct Game(screens: List<Screen>) =
|
|
|
145
153
|
c := self.camera(i)
|
|
146
154
|
if c.w > 0.0 && c.h > 0.0 then c.visible() else Aabb(min: Vec2(x: 0.0 - Float.Max, y: 0.0 - Float.Max), max: Vec2(x: Float.Max, y: Float.Max))
|
|
147
155
|
|
|
148
|
-
# One tick of `dt` seconds with `input`
|
|
156
|
+
# One tick of `dt` seconds with `input`, in the window it gives (`input.screen`; one of
|
|
157
|
+
# 0 by 0 leaves the window as it was): what the host runs.
|
|
149
158
|
fun update(self, io: Io, input: Input, dt: Float) -> Game =
|
|
150
|
-
self.step(io, input, dt,
|
|
159
|
+
self.step(io, input, dt, input.screen)
|
|
151
160
|
|
|
152
161
|
# One tick of `dt` seconds with `input` in a window of `pixels` (see the top of this
|
|
153
162
|
# file); a test runs ticks with it. With a history, the tick is added to it, and then
|
|
@@ -297,6 +306,20 @@ struct Game(screens: List<Screen>) =
|
|
|
297
306
|
fun idle(self) -> Bool =
|
|
298
307
|
if self.paused then !self.dirty else Game.onDemand(self.screen()) && !self.dirty && self.shift.isNone()
|
|
299
308
|
|
|
309
|
+
# Tells the host, during `update`, that the frame has nothing new to draw (`idle`): it
|
|
310
|
+
# may skip `draw`, keep showing the last frame, and wait for input before the next.
|
|
311
|
+
extern fun frameIdle(io: Io)
|
|
312
|
+
|
|
313
|
+
# The end of the host's frame, after its ticks: an idle game tells the host
|
|
314
|
+
# (`frameIdle`); any other is drawn by the host right after, so it counts as drawn
|
|
315
|
+
# (`frameDrawn`), which is what lets it go idle at a later frame with no tick to run.
|
|
316
|
+
fun hostFrame(self, io: Io) -> Game =
|
|
317
|
+
if self.idle()
|
|
318
|
+
Game.frameIdle(io)
|
|
319
|
+
self
|
|
320
|
+
else
|
|
321
|
+
self.frameDrawn()
|
|
322
|
+
|
|
300
323
|
# --- undo and time travel (std/game/History) ---
|
|
301
324
|
|
|
302
325
|
# Keeps the game's history from now on, which must be its start (no tick has run). The
|
|
@@ -377,11 +400,40 @@ struct Game(screens: List<Screen>) =
|
|
|
377
400
|
# Goes on from where the game is; what could be redone is dropped.
|
|
378
401
|
fun resume(self) -> Game = Game(..self, paused: false, history: self.history.map(|h| h.cut()))
|
|
379
402
|
|
|
403
|
+
# A frame of a development run (`t.mode` is `ReplayMode.Dev`): the history kept from the
|
|
404
|
+
# first frame (`timeTravel`, unless the game keeps one already), then the commands of
|
|
405
|
+
# the time travel keys the ticker read (`t.travel`) done in order. Any other run's game
|
|
406
|
+
# is as it is.
|
|
407
|
+
fun devFrame(self, io: Io, t: Ticker) -> Game =
|
|
408
|
+
if t.mode != ReplayMode.Dev
|
|
409
|
+
self
|
|
410
|
+
else
|
|
411
|
+
kept := if self.history.isNone() && self.delivered + self.skipped == 0 then self.timeTravel(History.Cap) else self
|
|
412
|
+
t.travel.fold(Game(..kept, dev: true), |g, c| g.travelCommand(io, c))
|
|
413
|
+
|
|
414
|
+
# The game after a time travel key's command (std/game/History's `TravelCmd`): `\`
|
|
415
|
+
# pauses or resumes, `[` and `]` pause and step a tick back or forward, the undo and
|
|
416
|
+
# redo chords undo and redo. It is drawn again.
|
|
417
|
+
fun travelCommand(self, io: Io, c: TravelCmd) -> Game =
|
|
418
|
+
moved := match c
|
|
419
|
+
TravelPause => if self.paused then self.resume() else self.pause()
|
|
420
|
+
TravelBack => self.pause().stepBack(io)
|
|
421
|
+
TravelForward => self.pause().stepForward(io)
|
|
422
|
+
TravelUndo => self.undo(io)
|
|
423
|
+
TravelRedo => self.redo(io)
|
|
424
|
+
Game(..moved, dirty: true)
|
|
425
|
+
|
|
426
|
+
# A development run's line: where the game is in its history.
|
|
427
|
+
fun devLine(self) -> Str =
|
|
428
|
+
line := "tick {self.tickNow()} of {self.ticksRecorded()}"
|
|
429
|
+
if self.paused then "{line} (paused)" else line
|
|
430
|
+
|
|
380
|
-
# The game made again from its start, with the history `h`, and its ticks played into it
|
|
431
|
+
# The game made again from its start, with the history `h`, and its ticks played into it;
|
|
432
|
+
# held still or a development run's as it was.
|
|
381
433
|
fun remake(self, io: Io, h: History) -> Game =
|
|
382
434
|
fresh := Game(screens: self.initial)
|
|
383
435
|
sized := if h.pixels.x > 0.0 && h.pixels.y > 0.0 then fresh.resized(h.pixels) else fresh
|
|
384
|
-
Game(..sized, history: Some(h), paused: self.paused).playOn(io, h.played())
|
|
436
|
+
Game(..sized, history: Some(h), paused: self.paused, dev: self.dev).playOn(io, h.played())
|
|
385
437
|
|
|
386
438
|
# `recs` played again from the state the game is in, with no effects run.
|
|
387
439
|
fun playOn(self, io: Io, recs: List<HistoryTick>) -> Game =
|
|
@@ -442,3 +494,141 @@ struct Game(screens: List<Screen>) =
|
|
|
442
494
|
fun lastPointer(input: Input, pointer: Vec2) -> Vec2 =
|
|
443
495
|
evs := input.events
|
|
444
496
|
Range.until(0, evs.length()).fold(pointer, |p, i| evs.at(i).position().unwrapOr(p))
|
|
497
|
+
|
|
498
|
+
# A game's ticker: its clock and input between frames: the input not yet given to a tick
|
|
499
|
+
# (`pending`), the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in
|
|
500
|
+
# all (`ticks`). The host's frame (`GameRun.frame`) calls `frame` once, then
|
|
501
|
+
# `update(io, ticker.input(), Ticker.Tick)` and `ticked` while `due`, then `settled`. So
|
|
502
|
+
# `update` always gets the same `dt`, a slow frame runs several ticks and a fast one may
|
|
503
|
+
# run none. A frame's events go to its first tick (or the next frame's, if it ran none),
|
|
504
|
+
# so a press counts once; later ticks see what is held, with no events. Each tick's input
|
|
505
|
+
# carries the window's size (`Input.screen`), read once a frame.
|
|
506
|
+
#
|
|
507
|
+
# Record and replay (std/game/Replay): `frame` asks the host each frame. Recording, it
|
|
508
|
+
# hands the host the inputs of the ticks the frame runs. Replaying (`mode`), the ticks
|
|
509
|
+
# take their input from `played`, from `cursor` on, on the recorded window, the host's
|
|
510
|
+
# input is never read, and no tick runs once the replay is over.
|
|
511
|
+
#
|
|
512
|
+
# A development run (`plum run --dev`, `ReplayMode.Dev`): `frame` reads the time travel
|
|
513
|
+
# keys first (`keys`, std/game/History's `TravelKeys`), keeps them from the game's input
|
|
514
|
+
# and leaves their commands in `travel` for the game (`Game.devFrame`).
|
|
515
|
+
struct Ticker(
|
|
516
|
+
pending: Input = Input.create(), acc: Float = 0.0, n: Int = 0, ticks: Int = 0, mode: Int = ReplayMode.Off, played: Slice<Input> = Slice<Input>(), cursor: Int = 0,
|
|
517
|
+
keys: TravelKeys = TravelKeys(), travel: List<TravelCmd> = Nil) =
|
|
518
|
+
# The tick length in seconds (1/60), the most ticks one frame runs (a longer stall drops
|
|
519
|
+
# the rest, so the game slows down instead of falling further behind), and how much
|
|
520
|
+
# short of a whole tick still counts as one (frame times jitter around 1/60).
|
|
521
|
+
const Tick = 0.016666666666666666
|
|
522
|
+
const MaxTicks = 8
|
|
523
|
+
const Slack = 0.002
|
|
524
|
+
|
|
525
|
+
# A ticker that replays `r` from its first tick: each frame's time paces the ticks
|
|
526
|
+
# (`paced`), and their input is `r`'s.
|
|
527
|
+
fun playing(r: Replay) -> Ticker = Ticker(mode: ReplayMode.Replaying, played: r.ticks)
|
|
528
|
+
|
|
529
|
+
# Polls the host once for a frame `dt` seconds long. While the host records, the
|
|
530
|
+
# frame's ticks go to it; while it replays, the host's input isn't read; in a
|
|
531
|
+
# development run the time travel keys are read first and kept from the game.
|
|
532
|
+
fun frame(self, io: Io, dt: Float) -> Ticker =
|
|
533
|
+
mode := Replay.replayMode(io)
|
|
534
|
+
if mode == ReplayMode.Replaying
|
|
535
|
+
self.loaded(io).paced(dt)
|
|
536
|
+
else if mode == ReplayMode.Dev
|
|
537
|
+
f := self.keys.frame(TravelKeys.downIn(io))
|
|
538
|
+
Ticker(..self.accept(self.pending.poll(io, f.keys.taken), dt), mode: ReplayMode.Dev, keys: f.keys, travel: f.cmds)
|
|
539
|
+
else
|
|
540
|
+
c := self.accept(self.pending.poll(io), dt)
|
|
541
|
+
if mode == ReplayMode.Recording
|
|
542
|
+
Replay.replayAppend(io, Replay.ticksText(c.dueInputs()))
|
|
543
|
+
c
|
|
544
|
+
|
|
545
|
+
# The ticker replaying the host's replay: this one once it is loaded. A replay with no
|
|
546
|
+
# window size plays on the host's.
|
|
547
|
+
fun loaded(self, io: Io) -> Ticker =
|
|
548
|
+
if self.mode == ReplayMode.Replaying
|
|
549
|
+
self
|
|
550
|
+
else
|
|
551
|
+
match Replay.decode(Replay.replayText(io))
|
|
552
|
+
Ok(r) => Ticker.playing(if r.width > 0 && r.height > 0 then r else r.onScreen(Int(Gfx.screenWidth(io)), Int(Gfx.screenHeight(io))))
|
|
553
|
+
Err(why) => Ticker.unreadable(why)
|
|
554
|
+
|
|
555
|
+
# Stops the game: the host's replay is not one (`crash` is a statement, not a match arm).
|
|
556
|
+
fun unreadable(why: Str) -> Ticker =
|
|
557
|
+
crash "the replay can't be read: {why}"
|
|
558
|
+
|
|
559
|
+
# Adds a frame's time while replaying: the frame's own input isn't used.
|
|
560
|
+
fun paced(self, dt: Float) -> Ticker =
|
|
561
|
+
Ticker(..self, acc: self.acc + dt.max(0.0), n: 0)
|
|
562
|
+
|
|
563
|
+
# Adds a frame's input and time. No host calls: what `frame` does after polling.
|
|
564
|
+
fun accept(self, frame: Input, dt: Float) -> Ticker =
|
|
565
|
+
events := Slice<InputEvent>()
|
|
566
|
+
for i := range self.pending.events.length()
|
|
567
|
+
events.push(self.pending.events.at(i))
|
|
568
|
+
for i := range frame.events.length()
|
|
569
|
+
events.push(frame.events.at(i))
|
|
570
|
+
pending := Input(..frame, events: events, wheel: self.pending.wheel + frame.wheel)
|
|
571
|
+
Ticker(..self, pending: pending, acc: self.acc + dt.max(0.0), n: 0, travel: Nil)
|
|
572
|
+
|
|
573
|
+
fun replaying(self) -> Bool =
|
|
574
|
+
self.mode == ReplayMode.Replaying
|
|
575
|
+
|
|
576
|
+
# Is another tick due this frame?
|
|
577
|
+
fun due(self) -> Bool =
|
|
578
|
+
self.acc >= Ticker.Tick - Ticker.Slack && self.n < Ticker.MaxTicks && {!self.replaying() || self.cursor < self.played.length()}
|
|
579
|
+
|
|
580
|
+
# The input of the next tick.
|
|
581
|
+
fun input(self) -> Input =
|
|
582
|
+
if self.replaying() then self.played.at(self.cursor) else self.pending
|
|
583
|
+
|
|
584
|
+
# After a tick: its time is spent and its events are used up.
|
|
585
|
+
fun ticked(self) -> Ticker =
|
|
586
|
+
p := self.pending
|
|
587
|
+
pending := if self.replaying() then p else Input(..p, events: Slice<InputEvent>(), wheel: 0.0)
|
|
588
|
+
Ticker(..self, pending: pending, acc: self.acc - Ticker.Tick, n: self.n + 1, ticks: self.ticks + 1, cursor: if self.replaying() then self.cursor + 1 else self.cursor)
|
|
589
|
+
|
|
590
|
+
# After the frame's last tick: a stall's leftover time is dropped.
|
|
591
|
+
fun settled(self) -> Ticker =
|
|
592
|
+
if self.acc >= Ticker.Tick then Ticker(..self, acc: 0.0) else self
|
|
593
|
+
|
|
594
|
+
# The inputs of the ticks still due this frame, in order: what a recording hands the host.
|
|
595
|
+
fun dueInputs(self) -> Slice<Input> =
|
|
596
|
+
self.collectDue(Slice<Input>())
|
|
597
|
+
|
|
598
|
+
fun collectDue(self, out: Slice<Input>) -> Slice<Input> =
|
|
599
|
+
if self.due()
|
|
600
|
+
out.push(self.input())
|
|
601
|
+
self.ticked().collectDue(out)
|
|
602
|
+
else
|
|
603
|
+
out
|
|
604
|
+
|
|
605
|
+
# What the host holds between frames: the game and its ticker. The compiler makes a
|
|
606
|
+
# game's `main` return one, and its frame entry points (`update(state, dt)` and
|
|
607
|
+
# `draw(state)` in the wasm module) are `frame` and `draw`.
|
|
608
|
+
struct GameRun(game: Game, ticker: Ticker = Ticker()) =
|
|
609
|
+
# The host's state at the start: `game` and a new ticker. The compiler's `main` of a
|
|
610
|
+
# game returns it.
|
|
611
|
+
fun start(game: Game) -> GameRun = GameRun(game: game)
|
|
612
|
+
|
|
613
|
+
# One host frame `dt` seconds long: the input read once (`Ticker.frame`), a development
|
|
614
|
+
# run's time travel keys done (`Game.devFrame`), the ticks the frame covers, each one
|
|
615
|
+
# `Game.update`, and then the host told whether there is a frame to draw
|
|
616
|
+
# (`Game.hostFrame`).
|
|
617
|
+
fun frame(self, io: Io, dt: Float) -> GameRun =
|
|
618
|
+
t := self.ticker.frame(io, dt)
|
|
619
|
+
GameRun(game: self.game.devFrame(io, t), ticker: t).ticks(io).shown(io)
|
|
620
|
+
|
|
621
|
+
fun ticks(self, io: Io) -> GameRun =
|
|
622
|
+
if self.ticker.due() && !self.game.exited
|
|
623
|
+
GameRun(game: self.game.update(io, self.ticker.input(), Ticker.Tick), ticker: self.ticker.ticked()).ticks(io)
|
|
624
|
+
else
|
|
625
|
+
GameRun(..self, ticker: self.ticker.settled())
|
|
626
|
+
|
|
627
|
+
fun shown(self, io: Io) -> GameRun = GameRun(..self, game: self.game.hostFrame(io))
|
|
628
|
+
|
|
629
|
+
# Draws the frame (`Game.draw`); in a development run, with where the game is in its
|
|
630
|
+
# history along the bottom (`Game.devLine`).
|
|
631
|
+
fun draw(self, io: Io) =
|
|
632
|
+
self.game.draw(io)
|
|
633
|
+
if self.game.dev
|
|
634
|
+
Gfx.drawText(io, self.game.devLine(), 8.0, self.game.pixels.y - 24.0, 16.0, Color.Yellow)
|
std/game/Gfx.plum
CHANGED
|
@@ -11,7 +11,7 @@ import std/Io
|
|
|
11
11
|
# `Gfx` that take the `Io` capability first: `Gfx.clear(io, Color.Black)`,
|
|
12
12
|
# `Texture.load(io, "sprites.png")`. A game is any type that `main(io: Io)` returns and
|
|
13
13
|
# that has `update(self, io: Io, input: Input, dt: Float) -> Self` and `draw(self, io: Io)`;
|
|
14
|
-
# `update` runs once per fixed 1/60 s tick (see `
|
|
14
|
+
# `update` runs once per fixed 1/60 s tick (see `Ticker` in std/game/Game), `draw` once
|
|
15
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
16
|
# holds the `Blend` constants and the `Texture` handle. A path that escapes the asset root
|
|
17
17
|
# fails like a missing file. Coordinates are world units once `Gfx.setCamera` is set.
|
std/game/History.plum
CHANGED
|
@@ -4,6 +4,7 @@ import std/Int
|
|
|
4
4
|
import std/Float
|
|
5
5
|
import std/Bool
|
|
6
6
|
import std/collections/List
|
|
7
|
+
import std/Io
|
|
7
8
|
import std/math/Vec2
|
|
8
9
|
import std/game/Input
|
|
9
10
|
import std/game/Control
|
|
@@ -123,3 +124,71 @@ struct History(cap: Int, pixels: Vec2, ticks: List<HistoryTick>, count: Int, fut
|
|
|
123
124
|
|
|
124
125
|
# A history moved forward, and the ticks to play.
|
|
125
126
|
struct Forwarded(history: History, taken: List<HistoryTick>)
|
|
127
|
+
|
|
128
|
+
# The time travel keys of a development run (`plum run --dev`, std/game/Game's `Ticker`
|
|
129
|
+
# and `devFrame`), std/game/Input's `Key`s: `[` steps back a tick and `]` forward (each
|
|
130
|
+
# pausing the game first), `\` pauses and resumes, Ctrl or Cmd with `Z` undoes, and with
|
|
131
|
+
# `Y`, or `Shift` and `Z`, redoes. Outside a development run they are the game's.
|
|
132
|
+
enum TravelCmd =
|
|
133
|
+
| TravelPause
|
|
134
|
+
| TravelBack
|
|
135
|
+
| TravelForward
|
|
136
|
+
| TravelUndo
|
|
137
|
+
| TravelRedo
|
|
138
|
+
|
|
139
|
+
# What the time travel keys did since the last frame. They never reach the game: `[`,
|
|
140
|
+
# `]`, `\`, Ctrl and Cmd are kept from it while they are down, and a `Z`, `Y` or `Shift`
|
|
141
|
+
# that goes down while Ctrl or Cmd is down is kept from it until it is let go (`taken`,
|
|
142
|
+
# which the game's poll skips). A `Shift` held before the Ctrl or Cmd is the game's.
|
|
143
|
+
# `down` is what was down at the last frame.
|
|
144
|
+
struct TravelKeys(down: List<Int> = Nil, taken: List<Int> = Nil) =
|
|
145
|
+
# The keys it reads from the host.
|
|
146
|
+
fun codes() -> List<Int> = [
|
|
147
|
+
Key.KeyY
|
|
148
|
+
Key.KeyZ
|
|
149
|
+
Key.BracketLeft
|
|
150
|
+
Key.Backslash
|
|
151
|
+
Key.BracketRight
|
|
152
|
+
Key.LeftShift
|
|
153
|
+
Key.LeftControl
|
|
154
|
+
Key.LeftSuper
|
|
155
|
+
Key.RightShift
|
|
156
|
+
Key.RightControl
|
|
157
|
+
Key.RightSuper
|
|
158
|
+
]
|
|
159
|
+
|
|
160
|
+
# The keys always kept from the game while they are down.
|
|
161
|
+
fun always() -> List<Int> = [Key.BracketLeft, Key.Backslash, Key.BracketRight, Key.LeftControl, Key.RightControl, Key.LeftSuper, Key.RightSuper]
|
|
162
|
+
|
|
163
|
+
# The keys of `codes()` the host holds down now.
|
|
164
|
+
fun downIn(io: Io) -> List<Int> = TravelKeys.codes().filter(|k| InputEvent.isKeyDown(io, k))
|
|
165
|
+
|
|
166
|
+
# One frame, with the keys of `codes()` that are down now (`now`): the commands given,
|
|
167
|
+
# in order, and the keys as they are after it (its `taken` is what the game's poll skips
|
|
168
|
+
# this frame).
|
|
169
|
+
fun frame(self, now: List<Int>) -> TravelFrame =
|
|
170
|
+
modifier := TravelKeys.anyOf(now, [Key.LeftControl, Key.RightControl, Key.LeftSuper, Key.RightSuper])
|
|
171
|
+
shift := TravelKeys.anyOf(now, [Key.LeftShift, Key.RightShift])
|
|
172
|
+
stillTaken := self.taken.filter(|k| TravelKeys.anyOf(now, [k]))
|
|
173
|
+
always := TravelKeys.always().fold(stillTaken, |acc, k| TravelKeys.adding(acc, k, TravelKeys.anyOf(now, [k])))
|
|
174
|
+
taken := [Key.KeyZ, Key.KeyY, Key.LeftShift, Key.RightShift].fold(always, |acc, k| TravelKeys.adding(acc, k, modifier && self.went(now, k)))
|
|
175
|
+
cmds := [
|
|
176
|
+
if self.went(now, Key.Backslash) then TravelPause
|
|
177
|
+
if self.went(now, Key.BracketLeft) then TravelBack
|
|
178
|
+
if self.went(now, Key.BracketRight) then TravelForward
|
|
179
|
+
if modifier && self.went(now, Key.KeyZ) then {if shift then TravelRedo else TravelUndo}
|
|
180
|
+
if modifier && self.went(now, Key.KeyY) then TravelRedo
|
|
181
|
+
]
|
|
182
|
+
TravelFrame(keys: TravelKeys(down: now, taken: taken), cmds: cmds)
|
|
183
|
+
|
|
184
|
+
# Whether `k` is down now and was not at the last frame.
|
|
185
|
+
fun went(self, now: List<Int>, k: Int) -> Bool = TravelKeys.anyOf(now, [k]) && !TravelKeys.anyOf(self.down, [k])
|
|
186
|
+
|
|
187
|
+
# Whether any of `ks` is in `xs`.
|
|
188
|
+
fun anyOf(xs: List<Int>, ks: List<Int>) -> Bool = xs.any(|x| ks.any(|k| k == x))
|
|
189
|
+
|
|
190
|
+
# `xs` with `k` at the end when `add` and it is not there yet.
|
|
191
|
+
fun adding(xs: List<Int>, k: Int, add: Bool) -> List<Int> = if add && !TravelKeys.anyOf(xs, [k]) then xs.append([k]) else xs
|
|
192
|
+
|
|
193
|
+
# A frame of the time travel keys: the keys after it and the commands they gave.
|
|
194
|
+
struct TravelFrame(keys: TravelKeys, cmds: List<TravelCmd>)
|
std/game/Input.plum
CHANGED
|
@@ -8,8 +8,7 @@ import std/Io
|
|
|
8
8
|
import std/Option
|
|
9
9
|
import std/collections/List
|
|
10
10
|
import std/Str
|
|
11
|
-
import std/Result
|
|
12
|
-
import std/game/
|
|
11
|
+
import std/game/Gfx
|
|
13
12
|
|
|
14
13
|
# Player input. `InputEvent.poll` is the only code that reads
|
|
15
14
|
# input from the host: a game that feeds every polled `InputEvent` into its state reads
|
|
@@ -106,11 +105,12 @@ enum InputEvent =
|
|
|
106
105
|
extern fun mouseWheel(io: Io) -> Float
|
|
107
106
|
|
|
108
107
|
# This frame's inputs: the host's mouse buttons and keys compared with `prev`, what was
|
|
109
|
-
# held after the last poll
|
|
108
|
+
# held after the last poll; the keys in `skip` read as up (a development run's time
|
|
109
|
+
# travel keys, std/game/History's `TravelKeys`). One pointer input (down, up or move)
|
|
110
|
-
# ButtonDown or ButtonUp for the right and the middle button if it
|
|
110
|
+
# comes first, then a ButtonDown or ButtonUp for the right and the middle button if it
|
|
111
|
-
# KeyDown or KeyUp for each key that changed, in key-code order. A click
|
|
111
|
+
# changed, then a KeyDown or KeyUp for each key that changed, in key-code order. A click
|
|
112
|
-
# ended between two polls gives a down and an up.
|
|
112
|
+
# that began and ended between two polls gives a down and an up.
|
|
113
|
-
fun poll(io: Io, prev: Held) -> Polled =
|
|
113
|
+
fun poll(io: Io, prev: Held, skip: List<Int> = Nil) -> Polled =
|
|
114
114
|
out := Slice<InputEvent>()
|
|
115
115
|
m := mousePos(io)
|
|
116
116
|
down := isMouseDown(io, Mouse.Left)
|
|
@@ -131,7 +131,7 @@ enum InputEvent =
|
|
|
131
131
|
codes := InputEvent.keyCodes()
|
|
132
132
|
for i := range codes.length()
|
|
133
133
|
k := codes.at(i)
|
|
134
|
-
now := isKeyDown(io, k)
|
|
134
|
+
now := isKeyDown(io, k) && !skip.any(|s| s == k)
|
|
135
135
|
was := prev.isDown(k)
|
|
136
136
|
if now
|
|
137
137
|
keys.push(k)
|
|
@@ -243,18 +243,24 @@ struct Held(mouse: Bool = false, keys: Slice<Int> = Slice<Int>(), buttons: Slice
|
|
|
243
243
|
struct Polled(inputs: Slice<InputEvent>, held: Held)
|
|
244
244
|
|
|
245
245
|
# The player's input for one tick, a value: a slice's `held(input)` receives it. The
|
|
246
|
-
# game's `
|
|
246
|
+
# game's `Ticker` (std/game/Game) reads the host once per frame, so `events`, `isKeyDown`
|
|
247
|
-
# reads agree for the whole tick however often they are called, and
|
|
247
|
+
# and the pointer reads agree for the whole tick however often they are called, and
|
|
248
|
-
# reads input from the host. `pos` is where the pointer is, in screen
|
|
248
|
+
# nothing in a tick reads input from the host. `pos` is where the pointer is, in screen
|
|
249
|
-
# how far the wheel turned this frame.
|
|
249
|
+
# pixels, and `wheel` how far the wheel turned this frame. `screen` is the window's size
|
|
250
|
+
# in pixels (0 by 0 unless given, or `sized`): the host's when the `Ticker` reads it, the
|
|
251
|
+
# recorded one in a replay; the game takes its window from it (`Game.update`).
|
|
250
|
-
struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float) =
|
|
252
|
+
struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float, screen: Vec2 = Vec2(x: 0.0, y: 0.0)) =
|
|
251
253
|
fun create() -> Input =
|
|
252
254
|
Input(held: Held(), events: Slice<InputEvent>(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
253
255
|
|
|
256
|
+
# This input in a window `w` by `h` pixels.
|
|
257
|
+
fun sized(self, w: Float, h: Float) -> Input = Input(..self, screen: Vec2(x: w, y: h))
|
|
258
|
+
|
|
254
|
-
# The input of this frame: the host polled once and compared with what was held before
|
|
259
|
+
# The input of this frame: the host polled once and compared with what was held before,
|
|
260
|
+
# the keys in `skip` read as up, in the host's window.
|
|
255
|
-
fun poll(self, io: Io) -> Input =
|
|
261
|
+
fun poll(self, io: Io, skip: List<Int> = Nil) -> Input =
|
|
256
|
-
p := InputEvent.poll(io, self.held)
|
|
262
|
+
p := InputEvent.poll(io, self.held, skip)
|
|
257
|
-
Input(held: p.held, events: p.inputs, pos: InputEvent.mousePos(io), wheel: InputEvent.mouseWheel(io))
|
|
263
|
+
Input(held: p.held, events: p.inputs, pos: InputEvent.mousePos(io), wheel: InputEvent.mouseWheel(io), screen: Vec2(x: Gfx.screenWidth(io), y: Gfx.screenHeight(io)))
|
|
258
264
|
|
|
259
265
|
# Held at the start of this frame (a `Key` code).
|
|
260
266
|
fun isKeyDown(self, key: Int) -> Bool =
|
|
@@ -286,102 +292,3 @@ struct Input(held: Held, events: Slice<InputEvent>, pos: Vec2, wheel: Float) =
|
|
|
286
292
|
PointerUp(_, _) => b == Mouse.Left
|
|
287
293
|
ButtonUp(n, _, _) => n == b
|
|
288
294
|
_ => false)
|
|
289
|
-
|
|
290
|
-
# A game's clock and input between frames: the input not yet given to a tick (`pending`),
|
|
291
|
-
# the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in all
|
|
292
|
-
# (`ticks`). The entry point the compiler adds to a game calls `frame` once per host
|
|
293
|
-
# frame, then `update(io, clock.input(), Clock.Tick)` and `ticked` while `due`, then
|
|
294
|
-
# `settled`. So `update` always gets the same `dt`, a slow frame runs several ticks and a
|
|
295
|
-
# fast one may run none. A frame's events go to its first tick (or the next frame's, if it
|
|
296
|
-
# ran none), so a press counts once; later ticks see what is held, with no events.
|
|
297
|
-
#
|
|
298
|
-
# Record and replay (std/game/Replay): `frame` asks the host each frame. Recording, it
|
|
299
|
-
# hands the host the inputs of the ticks the frame runs. Replaying (`mode`), the ticks
|
|
300
|
-
# take their input from `played`, from `cursor` on, the host's input is never read, and
|
|
301
|
-
# no tick runs once the replay is over.
|
|
302
|
-
struct Clock(pending: Input, acc: Float, n: Int, ticks: Int, mode: Int, played: Slice<Input>, cursor: Int) =
|
|
303
|
-
# The tick length in seconds (1/60), the most ticks one frame runs (a longer stall drops
|
|
304
|
-
# the rest, so the game slows down instead of falling further behind), and how much
|
|
305
|
-
# short of a whole tick still counts as one (frame times jitter around 1/60).
|
|
306
|
-
const Tick = 0.016666666666666666
|
|
307
|
-
const MaxTicks = 8
|
|
308
|
-
const Slack = 0.002
|
|
309
|
-
|
|
310
|
-
fun create() -> Clock =
|
|
311
|
-
Clock(pending: Input.create(), acc: 0.0, n: 0, ticks: 0, mode: ReplayMode.Off, played: Slice<Input>(), cursor: 0)
|
|
312
|
-
|
|
313
|
-
# A clock that replays `r` from its first tick: each frame's time paces the ticks
|
|
314
|
-
# (`paced`), and their input is `r`'s.
|
|
315
|
-
fun playing(r: Replay) -> Clock =
|
|
316
|
-
Clock(..Clock.create(), mode: ReplayMode.Replaying, played: r.ticks)
|
|
317
|
-
|
|
318
|
-
# Polls the host once for a frame `dt` seconds long. While the host records, the
|
|
319
|
-
# frame's ticks go to it; while it replays, the host's input isn't read.
|
|
320
|
-
fun frame(self, io: Io, dt: Float) -> Clock =
|
|
321
|
-
mode := Replay.replayMode(io)
|
|
322
|
-
if mode == ReplayMode.Replaying
|
|
323
|
-
self.loaded(io).paced(dt)
|
|
324
|
-
else
|
|
325
|
-
c := self.accept(self.pending.poll(io), dt)
|
|
326
|
-
if mode == ReplayMode.Recording
|
|
327
|
-
Replay.replayAppend(io, Replay.ticksText(c.dueInputs()))
|
|
328
|
-
c
|
|
329
|
-
|
|
330
|
-
# The clock replaying the host's replay: this one once it is loaded.
|
|
331
|
-
fun loaded(self, io: Io) -> Clock =
|
|
332
|
-
if self.mode == ReplayMode.Replaying
|
|
333
|
-
self
|
|
334
|
-
else
|
|
335
|
-
match Replay.decode(Replay.replayText(io))
|
|
336
|
-
Ok(r) => Clock.playing(r)
|
|
337
|
-
Err(why) => Clock.unreadable(why)
|
|
338
|
-
|
|
339
|
-
# Stops the game: the host's replay is not one (`crash` is a statement, not a match arm).
|
|
340
|
-
fun unreadable(why: Str) -> Clock =
|
|
341
|
-
crash "the replay can't be read: {why}"
|
|
342
|
-
|
|
343
|
-
# Adds a frame's time while replaying: the frame's own input isn't used.
|
|
344
|
-
fun paced(self, dt: Float) -> Clock =
|
|
345
|
-
Clock(..self, acc: self.acc + dt.max(0.0), n: 0)
|
|
346
|
-
|
|
347
|
-
# Adds a frame's input and time. No host calls: what `frame` does after polling.
|
|
348
|
-
fun accept(self, frame: Input, dt: Float) -> Clock =
|
|
349
|
-
events := Slice<InputEvent>()
|
|
350
|
-
for i := range self.pending.events.length()
|
|
351
|
-
events.push(self.pending.events.at(i))
|
|
352
|
-
for i := range frame.events.length()
|
|
353
|
-
events.push(frame.events.at(i))
|
|
354
|
-
pending := Input(held: frame.held, events: events, pos: frame.pos, wheel: self.pending.wheel + frame.wheel)
|
|
355
|
-
Clock(..self, pending: pending, acc: self.acc + dt.max(0.0), n: 0)
|
|
356
|
-
|
|
357
|
-
fun replaying(self) -> Bool =
|
|
358
|
-
self.mode == ReplayMode.Replaying
|
|
359
|
-
|
|
360
|
-
# Is another tick due this frame?
|
|
361
|
-
fun due(self) -> Bool =
|
|
362
|
-
self.acc >= Clock.Tick - Clock.Slack && self.n < Clock.MaxTicks && {!self.replaying() || self.cursor < self.played.length()}
|
|
363
|
-
|
|
364
|
-
# The input of the next tick.
|
|
365
|
-
fun input(self) -> Input =
|
|
366
|
-
if self.replaying() then self.played.at(self.cursor) else self.pending
|
|
367
|
-
|
|
368
|
-
# After a tick: its time is spent and its events are used up.
|
|
369
|
-
fun ticked(self) -> Clock =
|
|
370
|
-
p := self.pending
|
|
371
|
-
pending := if self.replaying() then p else Input(held: p.held, events: Slice<InputEvent>(), pos: p.pos, wheel: 0.0)
|
|
372
|
-
Clock(..self, pending: pending, acc: self.acc - Clock.Tick, n: self.n + 1, ticks: self.ticks + 1, cursor: if self.replaying() then self.cursor + 1 else self.cursor)
|
|
373
|
-
|
|
374
|
-
# After the frame's last tick: a stall's leftover time is dropped.
|
|
375
|
-
fun settled(self) -> Clock =
|
|
376
|
-
if self.acc >= Clock.Tick then Clock(..self, acc: 0.0) else self
|
|
377
|
-
|
|
378
|
-
# The inputs of the ticks still due this frame, in order: what a recording hands the host.
|
|
379
|
-
fun dueInputs(self) -> Slice<Input> =
|
|
380
|
-
self.collectDue(Slice<Input>())
|
|
381
|
-
|
|
382
|
-
fun collectDue(self, out: Slice<Input>) -> Slice<Input> =
|
|
383
|
-
if self.due()
|
|
384
|
-
out.push(self.input())
|
|
385
|
-
self.ticked().collectDue(out)
|
|
386
|
-
else
|
|
387
|
-
out
|
std/game/Label.plum
CHANGED
|
@@ -31,8 +31,8 @@ enum Align =
|
|
|
31
31
|
Right => w
|
|
32
32
|
|
|
33
33
|
# Text whose top is at its place's y, which starts at (x, y), placed on its x by `align`,
|
|
34
|
-
# `size` high, in `color` (painted at its alpha). Its width is
|
|
34
|
+
# `size` high, in `color` (painted at its alpha). Its width is its text's at `size` in the
|
|
35
|
-
#
|
|
35
|
+
# font the hosts draw with (`Label.textWidth`), which its bounds and its alignment go by. It turns with its
|
|
36
36
|
# place. It is decoration unless `touch: Enabled` (std/game/Touch). In a view it is made
|
|
37
37
|
# again each frame, so its text is read from the state as it is made
|
|
38
38
|
# (`Label(x: 16.0, y: 12.0, text: "Score {self.score}", size: 28.0)`). Unless given, it is
|
|
@@ -49,8 +49,31 @@ struct Label[View, Sized, Touch](x: Float = 0.0, y: Float = 0.0, text: Str, size
|
|
|
49
49
|
|
|
50
50
|
fun paintSelf(self, io: Io, m: Affine, alpha: Float) = Label.draw(io, m, alpha * self.color.a, self.text, self.size, self.color, self.align)
|
|
51
51
|
|
|
52
|
-
#
|
|
53
|
-
|
|
52
|
+
# The advance widths, in thousandths of the size, of the characters from the space (32)
|
|
53
|
+
# to `~` (126), four digits each: Arial's, which are Helvetica's and Liberation Sans's,
|
|
54
|
+
# the `sans-serif` a browser draws text with on macOS, Windows and most Linux. The browser
|
|
55
|
+
# places each glyph by them too (compiler/game/web/plum_bridge.js, `ADVANCES`), so the
|
|
56
|
+
# text drawn is as wide as its bounds. They are std's, not asked of the host, so a tick
|
|
57
|
+
# that hits a label is the same on every host and in a replay.
|
|
58
|
+
const Advances = "02780278035505560556088906670191033303330389058402780333027802780556055605560556055605560556055605560556027802780584058405840556101506670667072207220667061107780722027805000667055608330722077806670778072206670611072206670944066706670611027802780278046905560333055605560500055605560278055605560222022205000222083305560556055605560333050002780556050007220500050005000334026003340584"
|
|
59
|
+
|
|
60
|
+
# How wide `s` is at `size`: the sum of its characters' advances (`Advances`). A
|
|
61
|
+
# character past `~` is as wide as a digit; a control character takes no width.
|
|
62
|
+
fun textWidth(s: Str, size: Float) -> Float =
|
|
63
|
+
size * Float(Range.until(0, s.length()).fold(0, |acc, i| acc + Label.advance(s.byteAt(i)))) / 1000.0
|
|
64
|
+
|
|
65
|
+
# The advance, in thousandths of the size, of the character whose UTF-8 encoding has the
|
|
66
|
+
# byte `b`: its own for a printable ASCII byte, a digit's for the first byte of any other
|
|
67
|
+
# character, none for the bytes after it or a control character.
|
|
68
|
+
fun advance(b: Int) -> Int =
|
|
69
|
+
if b >= 32 && b <= 126
|
|
70
|
+
t := Label.Advances
|
|
71
|
+
i := {b - 32} * 4
|
|
72
|
+
{t.byteAt(i) - 48} * 1000 + {t.byteAt(i + 1) - 48} * 100 + {t.byteAt(i + 2) - 48} * 10 + {t.byteAt(i + 3) - 48}
|
|
73
|
+
else if b >= 192
|
|
74
|
+
556
|
|
75
|
+
else
|
|
76
|
+
0
|
|
54
77
|
|
|
55
78
|
# Draws text with its top on the transform `m`'s origin, placed on it by `align`, turned
|
|
56
79
|
# and scaled as `m` turns and scales it. Paints with `alpha` in place of the colour's
|
std/game/Replay.plum
CHANGED
|
@@ -17,7 +17,7 @@ import std/game/Input
|
|
|
17
17
|
# `Input`, so the same seed and inputs play the same game again, tick for tick.
|
|
18
18
|
#
|
|
19
19
|
# The game hosts do both (docs/game.md, "Record and replay"). While recording, the host
|
|
20
|
-
# remembers what `io.randomSeed()` returned and the game's `
|
|
20
|
+
# remembers what `io.randomSeed()` returned and the game's `Ticker` (std/game/Game) hands
|
|
21
21
|
# it each frame's ticks as lines of text. While replaying, `io.randomSeed()` returns the
|
|
22
22
|
# recorded seed and the ticks take their input from the replay, never from the host. A
|
|
23
23
|
# game's `main` doesn't change for either.
|
|
@@ -27,7 +27,8 @@ import std/game/Input
|
|
|
27
27
|
# plum-replay 1 <seed, high 32 bits> <seed, low 32 bits> <screen width> <screen height>
|
|
28
28
|
# <held keys, comma separated, or -> <mouse buttons held> <pointer x> <pointer y> <wheel> <events>
|
|
29
29
|
#
|
|
30
|
+
# with one tick line per tick; every tick's `Input.screen` is the header's size (a tick
|
|
30
|
-
#
|
|
31
|
+
# line holds none). The mouse buttons held are a sum: 1 for the left, 2 for the
|
|
31
32
|
# right, 4 for the middle (a replay from before the other buttons has only 0 and 1). An
|
|
32
33
|
# event is `K<key>` (KeyDown), `k<key>` (KeyUp), `D<x>,<y>` (PointerDown), `U<x>,<y>`
|
|
33
34
|
# (PointerUp), `M<x>,<y>` (PointerMove), `B<button>,<x>,<y>` (ButtonDown) or
|
|
@@ -40,6 +41,9 @@ primitive ReplayMode =
|
|
|
40
41
|
const Off = 0
|
|
41
42
|
const Recording = 1
|
|
42
43
|
const Replaying = 2
|
|
44
|
+
# A development run (`plum run --dev`): nothing is recorded or replayed; the game keeps
|
|
45
|
+
# its history and takes the time travel keys (std/game/Game's `Ticker` and `devFrame`).
|
|
46
|
+
const Dev = 3
|
|
43
47
|
|
|
44
48
|
# A recorded run: the seed `io.randomSeed()` gave `main`, the screen size at the start,
|
|
45
49
|
# and the input of every tick in order.
|
|
@@ -84,7 +88,15 @@ struct Replay(seed: Int, width: Int, height: Int, ticks: Slice<Input>) =
|
|
|
84
88
|
width := Replay.headNumber(head, 4)?
|
|
85
89
|
height := Replay.headNumber(head, 5)?
|
|
86
90
|
ticks := Replay.decodeTicks(lines, 1, Slice<Input>())?
|
|
87
|
-
Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks))
|
|
91
|
+
Ok(Replay(seed: {hi << 32} | {lo & 0xFFFFFFFF}, width: width, height: height, ticks: ticks).onScreen(width, height))
|
|
92
|
+
|
|
93
|
+
# The replay on a window `w` by `h` pixels, each tick's input in it (`Input.screen`): a
|
|
94
|
+
# decoded replay is on the window of its header.
|
|
95
|
+
fun onScreen(self, w: Int, h: Int) -> Replay =
|
|
96
|
+
sized := Slice<Input>()
|
|
97
|
+
for i := range self.ticks.length()
|
|
98
|
+
sized.push(self.ticks.at(i).sized(Float(w), Float(h)))
|
|
99
|
+
Replay(..self, width: w, height: h, ticks: sized)
|
|
88
100
|
|
|
89
101
|
# The whole number at `head.at(i)`, a field of the first line.
|
|
90
102
|
fun headNumber(head: Slice<Str>, i: Int) -> Result<Int, Str> =
|
std/game/TestRig.plum
CHANGED
|
@@ -64,7 +64,7 @@ import std/game/Game
|
|
|
64
64
|
# its reducer, the transition, the effects and what they ask of the game), with the input
|
|
65
65
|
# waiting and what is held; `ticks(n)` runs `n`, the input waiting going to the first.
|
|
66
66
|
# `tick(dt)` runs one of `dt` seconds instead. `frame(input, frameDt)` is the host's
|
|
67
|
-
# frame, the `
|
|
67
|
+
# frame, the `Ticker` turning wall time into ticks, for scripted runs.
|
|
68
68
|
#
|
|
69
69
|
# Reading, all from the shown screen's view and then its `hud`: `find<T>()` lists the
|
|
70
70
|
# items of type `T` they draw, in the order drawn; `first<T>()` is the first (none stops the test with "headless: first: no
|
|
@@ -85,10 +85,10 @@ import std/game/Game
|
|
|
85
85
|
# `moved()` says whether the last move could.
|
|
86
86
|
# A game run headless (see the top of this file): the window's size, what is held, the input
|
|
87
87
|
# waiting for the next tick, the pointer, what the last ticks gave (the effects that ran,
|
|
88
|
-
# what they asked of the game), and the
|
|
88
|
+
# what they asked of the game), and the ticker and recording of `frame` and `record`.
|
|
89
89
|
struct TestRig<S>(
|
|
90
90
|
io: Io, game: Game, screen: S, pixels: Vec2, held: Held, events: List<InputEvent>, pos: Vec2,
|
|
91
|
-
ran: List<Effect>, asks: List<Ask>,
|
|
91
|
+
ran: List<Effect>, asks: List<Ask>, ticker: Ticker, recording: Bool, log: Replay) =
|
|
92
92
|
const DefaultW = 800.0
|
|
93
93
|
|
|
94
94
|
const DefaultH = 600.0
|
|
@@ -113,7 +113,7 @@ struct TestRig<S>(
|
|
|
113
113
|
pixels := Vec2(x: TestRig.DefaultW, y: TestRig.DefaultH)
|
|
114
114
|
TestRig(
|
|
115
115
|
io: io, game: game.resized(pixels), screen: screen, pixels: pixels, held: Held(), events: Nil, pos: Vec2(x: 0.0, y: 0.0),
|
|
116
|
-
ran: Nil, asks: Nil,
|
|
116
|
+
ran: Nil, asks: Nil, ticker: Ticker(), recording: false, log: Replay.create(0))
|
|
117
117
|
|
|
118
118
|
# Stops a test that clicks an actor in neither the view nor the hud.
|
|
119
119
|
fun notInView() -> Vec2 =
|
|
@@ -161,23 +161,23 @@ struct TestRig<S>(
|
|
|
161
161
|
Some(h) => h.apply(p)
|
|
162
162
|
None => TestRig.notInView()
|
|
163
163
|
|
|
164
|
-
fun tick(self, dt: Float =
|
|
164
|
+
fun tick(self, dt: Float = Ticker.Tick) -> TestRig<S> = self.forget().step(dt)
|
|
165
165
|
|
|
166
|
-
fun ticks(self, n: Int) -> TestRig<S> = Range.until(0, n).fold(self.forget(), |r, i| r.step(
|
|
166
|
+
fun ticks(self, n: Int) -> TestRig<S> = Range.until(0, n).fold(self.forget(), |r, i| r.step(Ticker.Tick))
|
|
167
167
|
|
|
168
168
|
# One host frame `frameDt` seconds long with `input`, as the host runs it: the ticks it
|
|
169
169
|
# covers. The input waiting and what is held are not used.
|
|
170
170
|
fun frame(self, input: Input, frameDt: Float) -> TestRig<S> =
|
|
171
|
-
|
|
171
|
+
ticked := TestRig(..self.forget(), ticker: self.ticker.accept(input, frameDt))
|
|
172
|
-
|
|
172
|
+
ticked.frameTicks()
|
|
173
173
|
|
|
174
174
|
fun frameTicks(self) -> TestRig<S> =
|
|
175
|
-
if self.
|
|
175
|
+
if self.ticker.due() && !self.game.exited
|
|
176
|
-
self.ran1(self.
|
|
176
|
+
self.ran1(self.ticker.input(), Ticker.Tick).tickerTicked().frameTicks()
|
|
177
177
|
else
|
|
178
|
-
TestRig(..self,
|
|
178
|
+
TestRig(..self, ticker: self.ticker.settled())
|
|
179
179
|
|
|
180
|
-
fun
|
|
180
|
+
fun tickerTicked(self) -> TestRig<S> = TestRig(..self, ticker: self.ticker.ticked())
|
|
181
181
|
|
|
182
182
|
# Dispatches `a` to the shown screen as its reducer would dispatch it (reduced at once,
|
|
183
183
|
# with what its reducer dispatches), then runs what ends a tick: the effects with what
|
|
@@ -312,4 +312,4 @@ struct TestRig<S>(
|
|
|
312
312
|
|
|
313
313
|
# Every tick of `r` played now (a game made from `r.seed`).
|
|
314
314
|
fun replay(self, r: Replay) -> TestRig<S> =
|
|
315
|
-
Range.until(0, r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i),
|
|
315
|
+
Range.until(0, r.length()).fold(self.forget(), |t, i| t.ran1(r.at(i), Ticker.Tick))
|
std/game/View.plum
CHANGED
|
@@ -20,6 +20,7 @@ import std/game/Box
|
|
|
20
20
|
import std/game/Group
|
|
21
21
|
import std/game/Label
|
|
22
22
|
import std/game/Circle
|
|
23
|
+
import std/game/Overlay
|
|
23
24
|
|
|
24
25
|
# One thing a screen draws (std/game/Screen's `view`). Each kind of view is its own
|
|
25
26
|
# struct, with only its own fields, that implements `View`. A `View` is stateless: it says
|
|
@@ -82,7 +83,8 @@ import std/game/Circle
|
|
|
82
83
|
# `worldOf`)
|
|
83
84
|
#
|
|
84
85
|
# and the steps a screen's `stepped` uses: `stepAll` (each actor of a list of one kind)
|
|
85
|
-
# and `stepIn` (each `Actor` of a list of views,
|
|
86
|
+
# and `stepIn` (each `Actor` of a list of views, what a `Group` or an `Overlay` holds,
|
|
87
|
+
# and the others as they are).
|
|
86
88
|
trait View =
|
|
87
89
|
fun place(self) -> Place
|
|
88
90
|
|
|
@@ -108,11 +110,17 @@ primitive Views =
|
|
|
108
110
|
# actors it holds.
|
|
109
111
|
fun stepAll<T: Actor>(xs: List<T>, dt: Float) -> List<T> = xs.map(|x| x.step(dt))
|
|
110
112
|
|
|
111
|
-
# Each `Actor` of `items` stepped by `dt`, in order
|
|
113
|
+
# Each `Actor` of `items` stepped by `dt`, in order: an actor steps what it holds itself
|
|
114
|
+
# (its own `step`), so its view is neither made nor looked inside. A `Group` or an
|
|
115
|
+
# `Overlay` is made again with its children stepped the same way; any other view is as it
|
|
116
|
+
# is, with what it holds (a kind of your own that holds actors is an `Actor` that steps
|
|
117
|
+
# them, or its screen's `stepped` steps them).
|
|
112
118
|
fun stepIn(items: List<View>, dt: Float) -> List<View> = items.map(|x| Views.stepOne(x, dt))
|
|
113
119
|
|
|
114
120
|
fun stepOne(x: View, dt: Float) -> View = match x
|
|
115
121
|
Actor as a => a.step(dt)
|
|
122
|
+
Group as g => Group(..g, children: Views.stepIn(g.children, dt))
|
|
123
|
+
Overlay as o => Overlay(..o, children: Views.stepIn(o.children, dt))
|
|
116
124
|
_ => x
|
|
117
125
|
|
|
118
126
|
# Draws the visible `items`, `m` and `alpha` being those of what holds them (the screen's
|
tests/benchmarks/screen_views/orbit.plum
CHANGED
|
@@ -19,7 +19,7 @@ import std/Test
|
|
|
19
19
|
primitive OrbitTest[UnitTest] =
|
|
20
20
|
# the driver's run is the game's: the same seed reaches the same state
|
|
21
21
|
fun theDriversRunIsTheGamesTheSame() =
|
|
22
|
-
a := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t),
|
|
22
|
+
a := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Ticker.Tick, Vec2(x: 800.0, y: 600.0)))
|
|
23
|
-
b := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t),
|
|
23
|
+
b := Range.until(0, 600).fold(OrbitBench.gameOf(7), |g, t| g.step(io, Timing.script(7, t), Ticker.Tick, Vec2(x: 800.0, y: 600.0)))
|
|
24
24
|
assert OrbitBench.state(OrbitBench.playingOf(a)) == OrbitBench.state(OrbitBench.playingOf(b))
|
|
25
25
|
assert OrbitBench.state(OrbitBench.playingOf(a)) != OrbitBench.state(OrbitBench.make(7))
|
tests/examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -156,7 +156,7 @@ primitive PlaygroundScreenTest[UnitTest] =
|
|
|
156
156
|
assert v.screen.pops == 2
|
|
157
157
|
assert PlaygroundScreenHelpers.bursting(v.screen) == bursts
|
|
158
158
|
assert v.game.tickNow() == at + 1
|
|
159
|
-
w := v.frame(Input(held: Held(), events: [KeyDown(key: Key.Backspace)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0),
|
|
159
|
+
w := v.frame(Input(held: Held(), events: [KeyDown(key: Key.Backspace)].toSlice(), pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0), Ticker.Tick)
|
|
160
160
|
assert w.screen.pops == 1
|
|
161
161
|
assert w.game.tickNow() == at - 1
|
|
162
162
|
x := w.press(Key.Backspace).tick()
|
|
@@ -215,7 +215,7 @@ primitive PlaygroundScreenHelpers =
|
|
|
215
215
|
p.x == q.x && p.y == q.y && p.hue == q.hue && p.poppedAt == q.poppedAt)
|
|
216
216
|
|
|
217
217
|
fun framesFrom(t: TestRig<PlaygroundScreen>, from: Int, n: Int) -> TestRig<PlaygroundScreen> =
|
|
218
|
-
Range.until(0, n).fold(t, |r, f| r.frame(runInput(from + f),
|
|
218
|
+
Range.until(0, n).fold(t, |r, f| r.frame(runInput(from + f), Ticker.Tick))
|
|
219
219
|
|
|
220
220
|
fun untilPops(t: TestRig<PlaygroundScreen>, f: Int, pops: Int) -> TestRig<PlaygroundScreen> =
|
|
221
|
-
if t.screen.pops >= pops || f >= 900 then t else untilPops(t.frame(runInput(f),
|
|
221
|
+
if t.screen.pops >= pops || f >= 900 then t else untilPops(t.frame(runInput(f), Ticker.Tick), f + 1, pops)
|
tests/examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -249,7 +249,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
249
249
|
assert PlayingScreenHelpers.names(PlayingScreenHelpers.ruledLast(u)) == ""
|
|
250
250
|
assert u.screen.over
|
|
251
251
|
v := u.press(Key.Enter).tick()
|
|
252
|
-
assert PlayingScreenHelpers.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({
|
|
252
|
+
assert PlayingScreenHelpers.names(v.effects<PlayAction>()) == "PlayAgain Steer(0.0, 0.0) StartOver Tick({Ticker.Tick})"
|
|
253
253
|
assert !v.screen.over
|
|
254
254
|
assert v.screen.score == 0
|
|
255
255
|
assert v.screen.best == 30
|
|
@@ -325,7 +325,7 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
325
325
|
|
|
326
326
|
# a recorded run through game over and a restart replays to the same state
|
|
327
327
|
fun aRecordedRunThroughGameOverAndA() =
|
|
328
|
-
run := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1).record(42), overs: 0, restarts: 0), 0, 900,
|
|
328
|
+
run := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1).record(42), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
329
329
|
a := run.rig
|
|
330
330
|
assert run.overs > 0
|
|
331
331
|
assert run.restarts > 0
|
|
@@ -336,16 +336,16 @@ primitive PlayingScreenTest[UnitTest] =
|
|
|
336
336
|
|
|
337
337
|
# a run through game over and a restart, rewound to its middle and played on again, reaches the same end
|
|
338
338
|
fun aRunThroughGameOverAndARestart() =
|
|
339
|
-
a := PlayingScreenHelpers.counted(Run(rig: TestRig.mountWith(io, PlayingScreen.at(Random.seeded(42), Assets.none(), 0, 1)), overs: 0, restarts: 0), 0, 900,
|
|
339
|
+
a := PlayingScreenHelpers.counted(Run(rig: TestRig.mountWith(io, PlayingScreen.at(Random.seeded(42), Assets.none(), 0, 1)), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
340
|
-
b := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1), overs: 0, restarts: 0), 0, 900,
|
|
340
|
+
b := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1), overs: 0, restarts: 0), 0, 900, Ticker.Tick)
|
|
341
341
|
assert a.restarts > 0
|
|
342
342
|
assert PlayingScreenHelpers.sameRun(a.rig.screen, b.rig.screen)
|
|
343
|
-
mid := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1), overs: 0, restarts: 0), 0, 450,
|
|
343
|
+
mid := PlayingScreenHelpers.counted(Run(rig: PlayingScreenHelpers.mounted(io, 42, 0, 1), overs: 0, restarts: 0), 0, 450, Ticker.Tick)
|
|
344
344
|
back := a.rig.rewindTo(450)
|
|
345
345
|
assert back.moved()
|
|
346
346
|
assert back.game.rewound == 450
|
|
347
347
|
assert PlayingScreenHelpers.sameRun(back.screen, mid.rig.screen)
|
|
348
|
-
again := PlayingScreenHelpers.counted(Run(rig: back, overs: 0, restarts: 0), 450, 900,
|
|
348
|
+
again := PlayingScreenHelpers.counted(Run(rig: back, overs: 0, restarts: 0), 450, 900, Ticker.Tick)
|
|
349
349
|
assert PlayingScreenHelpers.sameRun(again.rig.screen, b.rig.screen)
|
|
350
350
|
assert again.rig.screen.over == b.rig.screen.over
|
|
351
351
|
|
tests/port/game/determinism.plum
CHANGED
|
@@ -14,7 +14,7 @@ import std/game/ScreenSlice
|
|
|
14
14
|
import std/game/Game
|
|
15
15
|
import std/Test
|
|
16
16
|
|
|
17
|
-
# Deterministic games: the game's `
|
|
17
|
+
# Deterministic games: the game's `Ticker` (std/game/Game) runs fixed 1/60 s ticks, at
|
|
18
18
|
# most 8 a frame, and hands each tick its input as a value; randomness is a `Random`
|
|
19
19
|
# held by the screen. So one seed and one list of inputs give the same game.
|
|
20
20
|
|
|
@@ -63,10 +63,10 @@ primitive Determinism =
|
|
|
63
63
|
ticks(io, Run(game: r.game, clock: r.clock.accept(frame, dt)))
|
|
64
64
|
|
|
65
65
|
fun ticks(io: Io, r: Run) -> Run =
|
|
66
|
-
if r.clock.due() then ticks(io, Run(game: r.game.step(io, r.clock.input(),
|
|
66
|
+
if r.clock.due() then ticks(io, Run(game: r.game.step(io, r.clock.input(), Ticker.Tick, Determinism.View), clock: r.clock.ticked())) else Run(game: r.game, clock: r.clock.settled())
|
|
67
67
|
|
|
68
68
|
fun start(seed: Int) -> Run =
|
|
69
|
-
Run(game: probeGame(seed), clock:
|
|
69
|
+
Run(game: probeGame(seed), clock: Ticker())
|
|
70
70
|
|
|
71
71
|
fun still() -> Input =
|
|
72
72
|
Input.create()
|
|
@@ -104,7 +104,7 @@ primitive Determinism =
|
|
|
104
104
|
# The screen the tests run on.
|
|
105
105
|
|
|
106
106
|
# The game and its clock, as the entry point the compiler adds to a game holds them.
|
|
107
|
-
struct Run(game: Game, clock:
|
|
107
|
+
struct Run(game: Game, clock: Ticker) =
|
|
108
108
|
fun probe(self) -> Probe = match self.game.screen()
|
|
109
109
|
Probe as p => p
|
|
110
110
|
_ => Probe.seeded(-1)
|
|
@@ -121,8 +121,8 @@ primitive DeterminismTest[UnitTest] =
|
|
|
121
121
|
# a stall's leftover time is dropped, not run later
|
|
122
122
|
fun aStallsLeftoverTimeIsDroppedNotRun() =
|
|
123
123
|
r := Determinism.runFrame(io, Determinism.start(1), Determinism.still(), 10.0)
|
|
124
|
-
assert r.probe().ticks ==
|
|
124
|
+
assert r.probe().ticks == Ticker.MaxTicks
|
|
125
|
-
assert Determinism.runFrame(io, r, Determinism.still(), 1.0 / 60.0).probe().ticks ==
|
|
125
|
+
assert Determinism.runFrame(io, r, Determinism.still(), 1.0 / 60.0).probe().ticks == Ticker.MaxTicks + 1
|
|
126
126
|
|
|
127
127
|
# dt is the same constant tick whatever the frame rate
|
|
128
128
|
fun dtIsTheSameConstantTickWhateverThe() =
|
|
@@ -130,8 +130,8 @@ primitive DeterminismTest[UnitTest] =
|
|
|
130
130
|
for k := range rates.length()
|
|
131
131
|
rate := rates.at(k)
|
|
132
132
|
r := Range.until(0, rate).fold(Determinism.start(1), |acc, _| Determinism.runFrame(io, acc, Determinism.still(), 1.0 / Float(rate)))
|
|
133
|
-
assert r.probe().minDt ==
|
|
133
|
+
assert r.probe().minDt == Ticker.Tick
|
|
134
|
-
assert r.probe().maxDt ==
|
|
134
|
+
assert r.probe().maxDt == Ticker.Tick
|
|
135
135
|
assert r.probe().ticks >= 59 && r.probe().ticks <= 60
|
|
136
136
|
assert r.clock.ticks == r.probe().ticks
|
|
137
137
|
|
|
@@ -150,7 +150,7 @@ primitive DeterminismTest[UnitTest] =
|
|
|
150
150
|
for i := range 120
|
|
151
151
|
inputs.push(Determinism.scripted(i / 3))
|
|
152
152
|
play := |seed: Int| Range.until(0, 120).fold(Determinism.probeGame(seed), |g, i| g.step(io, inputs.at(i), 1.0 / 60.0, Determinism.View))
|
|
153
|
-
play2 := |seed: Int| Run(game: play(seed), clock:
|
|
153
|
+
play2 := |seed: Int| Run(game: play(seed), clock: Ticker()).probe()
|
|
154
154
|
a := play2(5)
|
|
155
155
|
b := play2(5)
|
|
156
156
|
assert a.same(b)
|
tests/port/game/replay.plum
CHANGED
|
@@ -18,7 +18,7 @@ import std/game/Game
|
|
|
18
18
|
import std/Test
|
|
19
19
|
|
|
20
20
|
# Record and replay (std/game/Replay): a run is its seed and one `Input` per tick, as text
|
|
21
|
-
# with exact floats. A game's `
|
|
21
|
+
# with exact floats. A game's `Ticker` records the ticks of each frame and replays them.
|
|
22
22
|
|
|
23
23
|
# What a tick saw (from `held`) and the tick itself.
|
|
24
24
|
enum Saw =
|
|
@@ -60,7 +60,7 @@ struct Probe[ScreenSlice<Saw>](rng: Random, ticks: Int, presses: Int, held: Int,
|
|
|
60
60
|
# The screen the tests run on.
|
|
61
61
|
|
|
62
62
|
# The game, its clock and the ticks recorded so far, as a recording host holds them.
|
|
63
|
-
struct Run(game: Game, clock:
|
|
63
|
+
struct Run(game: Game, clock: Ticker, log: Slice<Input>) =
|
|
64
64
|
fun probe(self) -> Probe = match self.game.screen()
|
|
65
65
|
Probe as p => p
|
|
66
66
|
_ => Probe.seeded(-1)
|
|
@@ -121,7 +121,7 @@ primitive ReplayTest[UnitTest] =
|
|
|
121
121
|
|
|
122
122
|
# a frame's due ticks are the ones it runs
|
|
123
123
|
fun aFramesDueTicksAreTheOnesIt() =
|
|
124
|
-
c :=
|
|
124
|
+
c := Ticker().accept(scripted(3), 0.05)
|
|
125
125
|
due := c.dueInputs()
|
|
126
126
|
assert due.length() == 3
|
|
127
127
|
assert due.at(0).events.length() == 1
|
|
@@ -230,7 +230,7 @@ primitive ReplayTest[UnitTest] =
|
|
|
230
230
|
Game(screens: [only])
|
|
231
231
|
|
|
232
232
|
fun ticks(io: Io, r: Run) -> Run =
|
|
233
|
-
if r.clock.due() then ticks(io, Run(..r, game: r.game.step(io, r.clock.input(),
|
|
233
|
+
if r.clock.due() then ticks(io, Run(..r, game: r.game.step(io, r.clock.input(), Ticker.Tick, Probe.View), clock: r.clock.ticked())) else Run(..r, clock: r.clock.settled())
|
|
234
234
|
|
|
235
235
|
# One recorded frame: what the generated `gameUpdate` does while the host records, with
|
|
236
236
|
# `frame` as the polled input and the frame's ticks handed to the log.
|
|
@@ -269,9 +269,9 @@ primitive ReplayTest[UnitTest] =
|
|
|
269
269
|
0.0166 + Float(i % 3) * 0.004 - 0.004
|
|
270
270
|
|
|
271
271
|
fun recorded(io: Io, seed: Int, frames: Int) -> Run =
|
|
272
|
-
start := Run(game: probeGame(seed), clock:
|
|
272
|
+
start := Run(game: probeGame(seed), clock: Ticker(), log: Slice<Input>())
|
|
273
273
|
Range.until(0, frames).fold(start, |r, i| recordFrame(io, r, scripted(i), jitter(i)))
|
|
274
274
|
|
|
275
275
|
fun replayed(io: Io, r: Replay, frames: Int) -> Run =
|
|
276
|
-
start := Run(game: probeGame(r.seed), clock:
|
|
276
|
+
start := Run(game: probeGame(r.seed), clock: Ticker.playing(r), log: Slice<Input>())
|
|
277
277
|
Range.until(0, frames).fold(start, |run, i| replayFrame(io, run, jitter(i + 1)))
|
tests/std/game/Game.plum
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Bool
|
|
4
|
+
import std/Str
|
|
5
|
+
import std/Option
|
|
6
|
+
import std/Slice
|
|
7
|
+
import std/Io
|
|
8
|
+
import std/collections/List
|
|
9
|
+
import std/math/Vec2
|
|
10
|
+
import std/game/Input
|
|
11
|
+
import std/game/View
|
|
12
|
+
import std/game/Screen
|
|
13
|
+
import std/game/History
|
|
14
|
+
import std/game/Replay
|
|
15
|
+
import std/game/Game
|
|
16
|
+
import std/App
|
|
17
|
+
import std/Test
|
|
18
|
+
|
|
19
|
+
primitive GameTest[UnitTest] =
|
|
20
|
+
# a tick takes the window from its input, and an input with no window leaves it as it was
|
|
21
|
+
fun aTickTakesTheWindowFromItsInput() =
|
|
22
|
+
g := GameHelpers.game().update(io, Input.create().sized(640.0, 480.0), Ticker.Tick)
|
|
23
|
+
assert g.pixels == Vec2(x: 640.0, y: 480.0)
|
|
24
|
+
assert g.update(io, Input.create(), Ticker.Tick).pixels == Vec2(x: 640.0, y: 480.0)
|
|
25
|
+
assert g.update(io, Input.create().sized(320.0, 200.0), Ticker.Tick).pixels == Vec2(x: 320.0, y: 200.0)
|
|
26
|
+
|
|
27
|
+
# the ticker hands each tick of a frame the window the frame was polled in
|
|
28
|
+
fun theTickerHandsEachTickTheWindow() =
|
|
29
|
+
t := Ticker().accept(Input.create().sized(300.0, 200.0), 0.05)
|
|
30
|
+
assert t.input().screen == Vec2(x: 300.0, y: 200.0)
|
|
31
|
+
assert t.ticked().ticked().input().screen == Vec2(x: 300.0, y: 200.0)
|
|
32
|
+
assert t.dueInputs().length() == 3
|
|
33
|
+
assert Ticker.Tick == 1.0 / 60.0 && Ticker.MaxTicks == 8
|
|
34
|
+
|
|
35
|
+
# a development run keeps the history from its first frame and does the time travel keys' commands
|
|
36
|
+
fun aDevelopmentRunKeepsTheHistoryAndTravels() =
|
|
37
|
+
plain := GameHelpers.game().devFrame(io, Ticker())
|
|
38
|
+
assert !plain.dev && plain.history.isNone()
|
|
39
|
+
started := GameHelpers.game().devFrame(io, Ticker(mode: ReplayMode.Dev))
|
|
40
|
+
assert started.dev && started.history.isSome() && !started.paused
|
|
41
|
+
played := Range.until(0, 3).fold(started, |g, i| g.step(io, Input.create(), Ticker.Tick, Vec2(x: 800.0, y: 600.0)))
|
|
42
|
+
assert played.devLine() == "tick 3 of 3"
|
|
43
|
+
back := played.devFrame(io, Ticker(mode: ReplayMode.Dev, travel: [TravelBack]))
|
|
44
|
+
assert back.paused && back.dev && back.tickNow() == 2
|
|
45
|
+
assert back.devLine() == "tick 2 of 3 (paused)"
|
|
46
|
+
forward := back.travelCommand(io, TravelForward)
|
|
47
|
+
assert forward.tickNow() == 3 && forward.paused
|
|
48
|
+
resumed := forward.travelCommand(io, TravelPause)
|
|
49
|
+
assert !resumed.paused && resumed.devLine() == "tick 3 of 3"
|
|
50
|
+
paused := resumed.travelCommand(io, TravelPause)
|
|
51
|
+
assert paused.paused && paused.devLine() == "tick 3 of 3 (paused)"
|
|
52
|
+
|
|
53
|
+
# a frame the host is about to draw counts as drawn, which lets an OnDemand screen go idle
|
|
54
|
+
fun aFrameTheHostDrawsCountsAsDrawn() =
|
|
55
|
+
g := GameHelpers.game().step(io, Input.create(), Ticker.Tick, Vec2(x: 800.0, y: 600.0))
|
|
56
|
+
assert !g.idle()
|
|
57
|
+
shown := g.hostFrame(io)
|
|
58
|
+
assert shown.draws == 1 && shown.idle()
|
|
59
|
+
|
|
60
|
+
primitive GameHelpers =
|
|
61
|
+
fun game() -> Game =
|
|
62
|
+
only: Screen := Quiet(n: 0)
|
|
63
|
+
Game(screens: [only])
|
|
64
|
+
|
|
65
|
+
# A screen that sleeps through the ticks with nothing to do.
|
|
66
|
+
struct Quiet[Screen](n: Int) =
|
|
67
|
+
fun name(self) -> Str = "quiet"
|
|
68
|
+
|
|
69
|
+
fun view(self) -> List<View> = Nil
|
|
70
|
+
|
|
71
|
+
fun frames(self) -> Frames = OnDemand
|
tests/std/game/History.plum
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import std/Int
|
|
2
2
|
import std/Float
|
|
3
3
|
import std/Bool
|
|
4
|
+
import std/Str
|
|
4
5
|
import std/collections/List
|
|
5
6
|
import std/math/Vec2
|
|
6
7
|
import std/game/Input
|
|
@@ -30,6 +31,42 @@ primitive HistoryTest[UnitTest] =
|
|
|
30
31
|
h := Range.until(0, 4).fold(History.start(3, Vec2(x: 1.0, y: 1.0)), |acc, i| acc.push(HistoryHelpers.tick(false)))
|
|
31
32
|
assert h.full && h.now() == 4
|
|
32
33
|
|
|
34
|
+
# the time travel keys give their commands as they go down and keep themselves and their chords from the game
|
|
35
|
+
fun theTimeTravelKeysGiveTheirCommands() =
|
|
36
|
+
pause := TravelKeys().frame([Key.Backslash])
|
|
37
|
+
assert HistoryHelpers.names(pause.cmds) == "pause" && pause.keys.taken == [Key.Backslash]
|
|
38
|
+
held := pause.keys.frame([Key.Backslash])
|
|
39
|
+
assert held.cmds.isEmpty() && held.keys.taken == [Key.Backslash]
|
|
40
|
+
steps := held.keys.frame([Key.BracketLeft, Key.BracketRight])
|
|
41
|
+
assert HistoryHelpers.names(steps.cmds) == "back forward" && steps.keys.taken == [Key.BracketLeft, Key.BracketRight]
|
|
42
|
+
ctrl := TravelKeys().frame([Key.LeftControl])
|
|
43
|
+
undo := ctrl.keys.frame([Key.LeftControl, Key.KeyZ])
|
|
44
|
+
assert HistoryHelpers.names(undo.cmds) == "undo" && undo.keys.taken == [Key.LeftControl, Key.KeyZ]
|
|
45
|
+
# Z let go after Ctrl stays the developer's until it is let go
|
|
46
|
+
zOnly := undo.keys.frame([Key.KeyZ])
|
|
47
|
+
assert zOnly.cmds.isEmpty() && zOnly.keys.taken == [Key.KeyZ]
|
|
48
|
+
assert zOnly.keys.frame(Nil).keys.taken.isEmpty()
|
|
49
|
+
redo := TravelKeys().frame([Key.LeftSuper]).keys.frame([Key.LeftSuper, Key.LeftShift, Key.KeyZ])
|
|
50
|
+
assert HistoryHelpers.names(redo.cmds) == "redo" && redo.keys.taken == [Key.LeftSuper, Key.KeyZ, Key.LeftShift]
|
|
51
|
+
assert HistoryHelpers.names(ctrl.keys.frame([Key.LeftControl, Key.KeyY]).cmds) == "redo"
|
|
52
|
+
|
|
53
|
+
# a Shift held before Ctrl, and a Z or Y with no Ctrl or Cmd, are the game's
|
|
54
|
+
fun keysWithoutTheChordAreTheGames() =
|
|
55
|
+
shifted := TravelKeys().frame([Key.LeftShift]).keys.frame([Key.LeftShift, Key.LeftControl])
|
|
56
|
+
redo := shifted.keys.frame([Key.LeftShift, Key.LeftControl, Key.KeyZ])
|
|
57
|
+
assert HistoryHelpers.names(redo.cmds) == "redo" && redo.keys.taken == [Key.LeftControl, Key.KeyZ]
|
|
58
|
+
plain := TravelKeys().frame([Key.KeyZ, Key.KeyY, Key.LeftShift])
|
|
59
|
+
assert plain.cmds.isEmpty() && plain.keys.taken.isEmpty()
|
|
60
|
+
|
|
33
61
|
primitive HistoryHelpers =
|
|
62
|
+
fun names(cmds: List<TravelCmd>) -> Str = cmds.fold("", |acc, c| if acc == "" then HistoryHelpers.name(c) else "{acc} {HistoryHelpers.name(c)}")
|
|
63
|
+
|
|
64
|
+
fun name(c: TravelCmd) -> Str = match c
|
|
65
|
+
TravelPause => "pause"
|
|
66
|
+
TravelBack => "back"
|
|
67
|
+
TravelForward => "forward"
|
|
68
|
+
TravelUndo => "undo"
|
|
69
|
+
TravelRedo => "redo"
|
|
70
|
+
|
|
34
71
|
fun tick(user: Bool) -> HistoryTick =
|
|
35
72
|
HistoryTick(input: Input.create(), pixels: Vec2(x: 800.0, y: 600.0), dt: 0.1, user: user, asks: Nil)
|
tests/std/game/Input.plum
CHANGED
|
@@ -34,6 +34,21 @@ primitive InputTest[UnitTest] =
|
|
|
34
34
|
assert !up.isButtonDown(Mouse.Right) && up.isButtonDown(Mouse.Middle)
|
|
35
35
|
assert ButtonDown(button: Mouse.Right, x: 3.0, y: 4.0).position().unwrap().x == 3.0
|
|
36
36
|
|
|
37
|
+
# an input is in no window until it is sized, and sizing keeps the rest of it
|
|
38
|
+
fun anInputIsInNoWindowUntilSized() =
|
|
39
|
+
i := Input(held: Held(keys: [Key.KeyA].toSlice()), events: [KeyDown(key: Key.KeyA)].toSlice(), pos: Vec2(x: 3.0, y: 4.0), wheel: 1.0)
|
|
40
|
+
assert i.screen == Vec2(x: 0.0, y: 0.0)
|
|
41
|
+
s := i.sized(800.0, 600.0)
|
|
42
|
+
assert s.screen == Vec2(x: 800.0, y: 600.0) && s.isKeyDown(Key.KeyA) && s.isKeyPressed(Key.KeyA) && s.pos.x == 3.0 && s.wheel == 1.0
|
|
43
|
+
|
|
44
|
+
# a replay's ticks are in the window of its header
|
|
45
|
+
fun aReplaysTicksAreInItsWindow() =
|
|
46
|
+
r := Replay.decode("plum-replay 1 0 7 640 480\n- 0 0 0 0\n65 1 2 3 0 K65\n").unwrap()
|
|
47
|
+
assert r.width == 640 && r.ticks.length() == 2
|
|
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: 320.0, y: 200.0)
|
|
50
|
+
assert r.onScreen(320, 200).ticks.at(1).isKeyDown(Key.KeyA)
|
|
51
|
+
|
|
37
52
|
# key_down_twice_keeps_one_entry
|
|
38
53
|
fun keyDownTwiceKeepsOneEntry() =
|
|
39
54
|
h := Held().after(KeyDown(key: Key.KeyA)).after(KeyDown(key: Key.KeyA))
|
tests/std/game/Label.plum
CHANGED
|
@@ -18,20 +18,37 @@ import std/game/Label
|
|
|
18
18
|
import std/Test
|
|
19
19
|
|
|
20
20
|
primitive LabelTest[UnitTest] =
|
|
21
|
-
# a label is as tall as its size and hit over its text
|
|
21
|
+
# a label is as tall as its size and hit over its text, as wide as its letters are in the font
|
|
22
22
|
fun aLabelIsAsTallAsItsSize() =
|
|
23
23
|
l := Label(text: "ab", size: 10.0)
|
|
24
24
|
assert l.x == 0.0 && l.y == 0.0
|
|
25
|
+
assert Math.near(Label.textWidth("ab", 10.0), 11.12, 0.000001)
|
|
25
26
|
assert l.hit(Vec2(x: 11.0, y: 9.0))
|
|
26
|
-
assert !l.hit(Vec2(x:
|
|
27
|
+
assert !l.hit(Vec2(x: 11.5, y: 9.0))
|
|
27
|
-
assert Label(text: "abc", size: 10.0).hit(Vec2(x:
|
|
28
|
+
assert Label(text: "abc", size: 10.0).hit(Vec2(x: 16.0, y: 9.0))
|
|
29
|
+
|
|
30
|
+
# letters are as wide as the font draws them: a W wider than an i, digits alike, nothing for a control character
|
|
31
|
+
fun lettersAreAsWideAsTheFontDrawsThem() =
|
|
32
|
+
assert Label.advance(87) == 944 && Label.advance(105) == 222 && Label.advance(32) == 278
|
|
33
|
+
assert Label.advance(48) == 556 && Label.advance(57) == 556 && Label.advance(126) == 584
|
|
34
|
+
assert Label.textWidth("WWW", 20.0) > Label.textWidth("iiiiii", 20.0)
|
|
35
|
+
assert Label.textWidth("0123456789", 10.0) == Label.textWidth("9876543210", 10.0)
|
|
36
|
+
assert Label.textWidth("", 30.0) == 0.0
|
|
37
|
+
assert Label.textWidth("a\tb", 10.0) == Label.textWidth("ab", 10.0)
|
|
38
|
+
|
|
39
|
+
# a character past ASCII is one digit wide however many bytes it takes
|
|
40
|
+
fun aCharacterPastAsciiIsOneDigitWide() =
|
|
41
|
+
assert Math.near(Label.textWidth("é", 10.0), 5.56, 0.000001)
|
|
42
|
+
assert Math.near(Label.textWidth("a€b", 10.0), 16.68, 0.000001)
|
|
28
43
|
|
|
29
44
|
# a label is placed on its x by its alignment
|
|
30
45
|
fun aLabelIsPlacedOnItsXBy() =
|
|
46
|
+
w := Label.textWidth("abcd", 10.0)
|
|
47
|
+
assert Math.near(w, 21.68, 0.000001)
|
|
31
48
|
c := Label(x: 100.0, text: "abcd", size: 10.0, align: Centre)
|
|
32
|
-
assert c.bounds() == Aabb.of(-
|
|
49
|
+
assert c.bounds() == Aabb.of(0.0 - w / 2.0, 0.0, w, 10.0)
|
|
33
|
-
assert c.hit(Vec2(x: -
|
|
50
|
+
assert c.hit(Vec2(x: -10.0, y: 5.0))
|
|
34
|
-
assert !c.hit(Vec2(x:
|
|
51
|
+
assert !c.hit(Vec2(x: 11.0, y: 5.0))
|
|
35
52
|
r := Label(text: "abcd", size: 10.0, align: Right)
|
|
36
|
-
assert r.bounds() == Aabb.of(
|
|
53
|
+
assert r.bounds() == Aabb.of(0.0 - w, 0.0, w, 10.0)
|
|
37
54
|
assert Label(text: "abcd", size: 10.0).lead() == 0.0
|
tests/std/game/View.plum
CHANGED
|
@@ -18,6 +18,7 @@ import std/game/Box
|
|
|
18
18
|
import std/game/Group
|
|
19
19
|
import std/game/Label
|
|
20
20
|
import std/game/Circle
|
|
21
|
+
import std/game/Overlay
|
|
21
22
|
import std/game/View
|
|
22
23
|
import std/Test
|
|
23
24
|
|
|
@@ -65,6 +66,34 @@ primitive ViewTest[UnitTest] =
|
|
|
65
66
|
_ => -1.0)
|
|
66
67
|
assert times.at(0) == 0.75 && times.at(1) == -1.0 && times.at(2) == 2.75
|
|
67
68
|
|
|
69
|
+
# stepping a view's items steps the actors in a group or an overlay, not what an actor or a kind of your own holds
|
|
70
|
+
fun steppingLooksInsideGroupsAndOverlays() =
|
|
71
|
+
held := Holder(time: 0.0, kids: [Stepper(time: 0.0)])
|
|
72
|
+
items := [
|
|
73
|
+
Group(x: 5.0) {
|
|
74
|
+
Stepper(time: 1.0)
|
|
75
|
+
Overlay(w: 10.0, h: 10.0) { Stepper(time: 2.0) }
|
|
76
|
+
}
|
|
77
|
+
held
|
|
78
|
+
TurnedGroup(x: 0.0, y: 0.0) { Stepper(time: 3.0) }
|
|
79
|
+
]
|
|
80
|
+
stepped := Views.stepIn(items, 0.5)
|
|
81
|
+
group := match stepped.at(0)
|
|
82
|
+
Group as g => g
|
|
83
|
+
_ => Group(children: [])
|
|
84
|
+
assert group.x == 5.0
|
|
85
|
+
assert ViewHelpers.timeOf(group.children.at(0)) == 1.5
|
|
86
|
+
inner := match group.children.at(1)
|
|
87
|
+
Overlay as o => o.children
|
|
88
|
+
_ => Nil
|
|
89
|
+
assert ViewHelpers.timeOf(inner.at(0)) == 2.5
|
|
90
|
+
holder := match stepped.at(1)
|
|
91
|
+
Holder as h => h
|
|
92
|
+
_ => held
|
|
93
|
+
assert holder.time == 0.5 && holder.kids.at(0).time == 0.25
|
|
94
|
+
own := stepped.at(2).view()
|
|
95
|
+
assert ViewHelpers.timeOf(own.at(0)) == 3.0
|
|
96
|
+
|
|
68
97
|
# a press is on the top-most item that takes it, through groups and their turns, never under a Disabled one
|
|
69
98
|
fun aPressIsOnTheTopMostItem() =
|
|
70
99
|
top := Box(x: 10.0, y: 10.0, w: 20.0, h: 20.0, color: Color.White, touch: Enabled)
|
|
@@ -138,10 +167,23 @@ struct Stepper[Actor](time: Float) =
|
|
|
138
167
|
fun step(self, dt: Float) -> Stepper = Stepper(time: self.time + dt)
|
|
139
168
|
|
|
140
169
|
# A group turned a quarter.
|
|
170
|
+
# An actor holding actors, stepped by its own `step` (at half its own pace), never by std.
|
|
171
|
+
struct Holder[Actor](time: Float, kids: List<Stepper>) =
|
|
172
|
+
fun place(self) -> Place = Place.at(0.0, 0.0)
|
|
173
|
+
|
|
174
|
+
fun view(self) -> List<View> = self.kids
|
|
175
|
+
|
|
176
|
+
fun step(self, dt: Float) -> Holder = Holder(time: self.time + dt, kids: Views.stepAll(self.kids, dt / 2.0))
|
|
177
|
+
|
|
141
178
|
struct TurnedGroup[View](x: Float, y: Float, children: List<View>) =
|
|
142
179
|
fun place(self) -> Place = Place.at(self.x, self.y).rotateTo(Float.HalfPi)
|
|
143
180
|
|
|
144
181
|
fun view(self) -> List<View> = self.children
|
|
145
182
|
|
|
146
183
|
primitive ViewHelpers =
|
|
184
|
+
# A `Stepper`'s time, -1 for any other view.
|
|
185
|
+
fun timeOf(v: View) -> Float = match v
|
|
186
|
+
Stepper as s => s.time
|
|
187
|
+
_ => -1.0
|
|
188
|
+
|
|
147
189
|
fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
|