slurmscope 2.0.0.dev1__tar.gz → 2.1.0.dev1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. slurmscope-2.1.0.dev1/.gitignore +2 -0
  2. slurmscope-2.1.0.dev1/CHANGELOG.md +20 -0
  3. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/Cargo.lock +1 -1
  4. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/Cargo.toml +1 -1
  5. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/PKG-INFO +4 -4
  6. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/PYPI.md +3 -3
  7. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/README.md +4 -4
  8. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/pyproject.toml +1 -1
  9. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/app.rs +26 -2
  10. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/main.rs +5 -1
  11. slurmscope-2.1.0.dev1/src/surfer.rs +818 -0
  12. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/LICENSE +0 -0
  13. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/build.rs +0 -0
  14. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/coord.rs +0 -0
  15. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/data.rs +0 -0
  16. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/hooks.rs +0 -0
  17. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/probe.rs +0 -0
  18. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/pyuni.rs +0 -0
  19. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/render.rs +0 -0
  20. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/share.rs +0 -0
  21. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/slurm.rs +0 -0
  22. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/storage.rs +0 -0
  23. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/style.rs +0 -0
  24. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/src/util.rs +0 -0
  25. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/bench.sh +0 -0
  26. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/difftest.sh +0 -0
  27. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/gen_pyuni.py +0 -0
  28. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/parity_app.py +0 -0
  29. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/parity_funcs.py +0 -0
  30. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/run_all.sh +0 -0
  31. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/test_harness_regressions.py +0 -0
  32. {slurmscope-2.0.0.dev1 → slurmscope-2.1.0.dev1}/tests/test_process_parity.py +0 -0
@@ -0,0 +1,2 @@
1
+ target/
2
+ patches/
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 2.1.0.dev1 — 2026-11-04 (pre-release)
4
+
5
+ ### Added
6
+ - **Easter egg: endless runner while you wait.** Press **`S`** (capital S) in any view — Overview, Jobs, Nodes,
7
+ Memory, the QoS browser, and inside job/node/log/help screens — to open a side panel with a looping ASCII
8
+ endless runner on train tracks. Press **`S`** again to close it. The view keeps working beside it (cursor,
9
+ sorting, clicks, filters).
10
+ - The runner dodges parked and oncoming trains, jumps low barriers, rolls under high ones, runs up ramps onto
11
+ train roofs and collects coins. The course is generated once from a fixed seed and a dynamic-programming
12
+ planner guarantees a collision-free path; the animation loops seamlessly every 24 s.
13
+ - Needs a terminal at least 100 columns wide (the panel takes ~40% of the width). It redraws at 15 fps only
14
+ while it is open; otherwise the refresh behaviour is unchanged.
15
+ - Deliberately not listed in the footer or in the help screen. While a search (`/`) is being typed, `S` is text.
16
+ - Same feature as slurmscope 1.5.0 (Python, the stable version); the course differs because the two versions use different
17
+ random generators.
18
+
19
+ No changes to data collection, the shared collector protocol (still compatible with the Python version) or
20
+ command-line options.
@@ -484,7 +484,7 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
484
484
 
485
485
  [[package]]
486
486
  name = "slurmscope"
487
- version = "2.0.0-dev.1"
487
+ version = "2.1.0-dev.1"
488
488
  dependencies = [
489
489
  "chrono",
490
490
  "clap",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "slurmscope"
3
- version = "2.0.0-dev.1"
3
+ version = "2.1.0-dev.1"
4
4
  edition = "2021"
5
5
  rust-version = "1.80"
6
6
  description = "Live terminal dashboard for Slurm clusters (Rust port, protocol-compatible with the Python version)"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: slurmscope
3
- Version: 2.0.0.dev1
3
+ Version: 2.1.0.dev1
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Environment :: Console
6
6
  Classifier: Intended Audience :: Science/Research
@@ -25,7 +25,7 @@ Project-URL: Source, https://github.com/FabioBozzoli/slurmscope/tree/slurmscope-
25
25
  This is a **development pre-release** of `slurmscope`, the live terminal dashboard for Slurm
26
26
  clusters, reimplemented in Rust. The stable, recommended version remains the Python one:
27
27
 
28
- pip install slurmscope # stable Python version (1.4.x)
28
+ pip install slurmscope # stable Python version (1.5.x)
29
29
 
30
30
  pip never installs this pre-release unless you ask for it explicitly.
31
31
 
@@ -34,11 +34,11 @@ pip never installs this pre-release unless you ask for it explicitly.
34
34
  Side by side with the stable version (recommended while it is in development), with `pipx`:
35
35
 
36
36
  pipx install slurmscope # Python, command `slurmscope`
37
- pipx install --suffix=-rs "slurmscope==2.0.0.dev1" # Rust, command `slurmscope-rs`
37
+ pipx install --suffix=-rs "slurmscope==2.1.0.dev1" # Rust, command `slurmscope-rs`
38
38
 
39
39
  Or in a dedicated environment:
40
40
 
41
- pip install "slurmscope==2.0.0.dev1"
41
+ pip install "slurmscope==2.1.0.dev1"
42
42
 
43
43
  Wheels are provided for Linux x86_64 (glibc ≥ 2.17). On other platforms pip builds from the
44
44
  source distribution, which needs a Rust toolchain (`cargo`).
@@ -3,7 +3,7 @@
3
3
  This is a **development pre-release** of `slurmscope`, the live terminal dashboard for Slurm
4
4
  clusters, reimplemented in Rust. The stable, recommended version remains the Python one:
5
5
 
6
- pip install slurmscope # stable Python version (1.4.x)
6
+ pip install slurmscope # stable Python version (1.5.x)
7
7
 
8
8
  pip never installs this pre-release unless you ask for it explicitly.
9
9
 
@@ -12,11 +12,11 @@ pip never installs this pre-release unless you ask for it explicitly.
12
12
  Side by side with the stable version (recommended while it is in development), with `pipx`:
13
13
 
14
14
  pipx install slurmscope # Python, command `slurmscope`
15
- pipx install --suffix=-rs "slurmscope==2.0.0.dev1" # Rust, command `slurmscope-rs`
15
+ pipx install --suffix=-rs "slurmscope==2.1.0.dev1" # Rust, command `slurmscope-rs`
16
16
 
17
17
  Or in a dedicated environment:
18
18
 
19
- pip install "slurmscope==2.0.0.dev1"
19
+ pip install "slurmscope==2.1.0.dev1"
20
20
 
21
21
  Wheels are provided for Linux x86_64 (glibc ≥ 2.17). On other platforms pip builds from the
22
22
  source distribution, which needs a Rust toolchain (`cargo`).
@@ -21,11 +21,11 @@ A fully static binary can be built with `rustup target add x86_64-unknown-linux-
21
21
  ## Packaging (PyPI pre-release)
22
22
 
23
23
  Published under the same PyPI name as the Python version, as a **pre-release**, so that
24
- `pip install slurmscope` keeps installing the stable Python 1.4.x and the Rust build is only
25
- installed on request (`pip install "slurmscope==2.0.0.dev1"`, or `pipx install --suffix=-rs …` to
24
+ `pip install slurmscope` keeps installing the stable Python 1.5.x and the Rust build is only
25
+ installed on request (`pip install "slurmscope==2.1.0.dev1"`, or `pipx install --suffix=-rs …` to
26
26
  keep both). `pyproject.toml` uses maturin with `bindings = "bin"`: the wheel ships the
27
27
  `slurmscope` executable and no Python module. The version comes from `Cargo.toml`
28
- (`2.0.0-dev.1`, semver), which maturin publishes as `2.0.0.dev1` (PEP 440); `build.rs` exposes the
28
+ (`2.1.0-dev.1`, semver), which maturin publishes as `2.1.0.dev1` (PEP 440); `build.rs` exposes the
29
29
  same PEP 440 form to the program (`--version`, help). `PYPI.md` is the project description shown
30
30
  on PyPI for this release.
31
31
 
@@ -33,7 +33,7 @@ on PyPI for this release.
33
33
  maturin build --release --zig --compatibility manylinux2014 --out dist # Linux x86_64, glibc >= 2.17
34
34
  maturin sdist --out dist # source: needs cargo to install
35
35
  twine check dist/*
36
- twine upload dist/slurmscope-2.0.0.dev1* # API token of the project
36
+ twine upload dist/slurmscope-2.1.0.dev1* # API token of the project
37
37
 
38
38
  Checks made on the artifacts before publishing: wheel contents (binary, metadata, license, SBOM
39
39
  only), highest glibc symbol version required (2.17), absence of the test-only probe, `twine check`,
@@ -33,4 +33,4 @@ Issues = "https://github.com/FabioBozzoli/slurmscope/issues"
33
33
  bindings = "bin"
34
34
  # Release builds only; the test-only `probe` feature is never enabled here.
35
35
  profile = "release"
36
- include = [{ path = "LICENSE", format = "sdist" }]
36
+ include = [{ path = "LICENSE", format = "sdist" }, { path = "CHANGELOG.md", format = "sdist" }]
@@ -23,6 +23,8 @@ const DESC_DEFAULT: [&str; 17] = ["elapsed", "limit", "gpus", "cpus", "prio", "g
23
23
  "run", "pend", "users", "gpu", "cpu", "priority", "vram"];
24
24
  const JOB_STATES: [Option<&str>; 3] = [None, Some("RUNNING"), Some("PENDING")];
25
25
  const NODE_STATES: [Option<&str>; 6] = [None, Some("idle"), Some("mixed"), Some("allocated"), Some("drain"), Some("down")];
26
+ /// Easter egg (S): side panel with the runner, only on terminals at least this wide.
27
+ const SURF_MIN_WIDTH: usize = 100;
26
28
  const DOC_ROOT: &str = "https://ailb-web.ing.unimore.it/coldfront/documentation/";
27
29
  const SITE_DOCS: [(&str, &str); 6] = [("Environment and Customization", "LrU3q"), ("Scheduler and Job Submission", "UKN8n"),
28
30
  ("Node Features and Constraints", "flOS4"), ("Budget and Accounting", "GSOa2"), ("Job Priority", "cHTQV"),
@@ -493,6 +495,8 @@ pub struct App {
493
495
  log_inflight: Option<u64>,
494
496
  pub log_dropped: u64,
495
497
  pub wake: Option<Arc<dyn Fn() + Send + Sync>>,
498
+ surf_t0: Option<f64>, // S: runner side panel open since this time (undocumented on purpose)
499
+ last_width: usize,
496
500
  }
497
501
 
498
502
  impl App {
@@ -520,6 +524,7 @@ impl App {
520
524
  storage: None, usage: None, partition_defs: IndexMap::new(), report_budget: None, reports_priority: HashMap::new(),
521
525
  extra_errors: HashMap::new(), extra_at: HashMap::new(), extra_pending: HashSet::new(),
522
526
  usage_live: Arc::new(Mutex::new(HashMap::new())), tx, rx, log_gen: 0, log_inflight: None, log_dropped: 0, wake: None,
527
+ surf_t0: None, last_width: 0,
523
528
  }
524
529
  }
525
530
 
@@ -894,6 +899,10 @@ impl App {
894
899
  }
895
900
  _ => {}
896
901
  }
902
+ if ev == Ev::Char('S') {
903
+ self.surf_t0 = if self.surf_t0.is_some() { None } else { Some(self.now()) };
904
+ return true;
905
+ }
897
906
  if self.modal.is_some() {
898
907
  return self.handle_modal(ev);
899
908
  }
@@ -1440,6 +1449,9 @@ impl App {
1440
1449
  }
1441
1450
  let body_rows = rows - 2;
1442
1451
  self.body_rows = body_rows;
1452
+ self.last_width = width;
1453
+ let full = width;
1454
+ let width = if self.animating() { full - (full * 2 / 5).clamp(36, 64) - 1 } else { full };
1443
1455
  let mut body = if self.modal.is_some() {
1444
1456
  self.modal_view(width, body_rows)
1445
1457
  } else if self.view == "overview" {
@@ -1460,12 +1472,24 @@ impl App {
1460
1472
  };
1461
1473
  body.truncate(body_rows);
1462
1474
  body.resize(body_rows, String::new());
1463
- let mut out = vec![self.tabbar(width)];
1475
+ if width < full {
1476
+ let left: Vec<String> = body.iter().map(|l| pad(&clip(l, width), width, false)).collect();
1477
+ let side = full - width - 1;
1478
+ let t = self.now() - self.surf_t0.unwrap_or(0.0);
1479
+ let right = panel("keep running", &crate::surfer::frame(side - 4, body_rows - 2, t), side, &c("S close", "dim", false), 0, "warn");
1480
+ body = side_by_side(&left, &right, 1);
1481
+ }
1482
+ let mut out = vec![self.tabbar(full)];
1464
1483
  out.extend(body);
1465
- out.push(self.footer(width));
1484
+ out.push(self.footer(full));
1466
1485
  out.iter().map(|l| terminal_safe(l)).collect()
1467
1486
  }
1468
1487
 
1488
+ /// The runner panel is open and the terminal is large enough to show it.
1489
+ pub fn animating(&self) -> bool {
1490
+ self.surf_t0.is_some() && self.last_width >= SURF_MIN_WIDTH && self.body_rows >= 12
1491
+ }
1492
+
1469
1493
  fn document_view(&mut self, lines: Vec<String>, rows: usize, memory: bool) -> Vec<String> {
1470
1494
  self.document_height = lines.len();
1471
1495
  let max = lines.len().saturating_sub(rows) as i64;
@@ -15,6 +15,7 @@ mod share;
15
15
  mod slurm;
16
16
  mod storage;
17
17
  mod style;
18
+ mod surfer;
18
19
  mod util;
19
20
 
20
21
  use app::{parse_input, App, Options, INTERVALS};
@@ -402,7 +403,10 @@ fn interactive(args: &Args, app: &mut App) {
402
403
  let frame = app.frame(cols, lines);
403
404
  let _ = write!(out, "\x1b[H{}\x1b[K\x1b[J", frame.join("\x1b[K\n"));
404
405
  let _ = out.flush();
405
- let timeout = if app.ctx.paused { 1.0 } else { (next_poll - util::monotonic()).max(0.0) };
406
+ let mut timeout = if app.ctx.paused { 1.0 } else { (next_poll - util::monotonic()).max(0.0) };
407
+ if app.animating() {
408
+ timeout = timeout.min(1.0 / surfer::FPS);
409
+ }
406
410
  let mut pfds = [libc::pollfd { fd, events: libc::POLLIN, revents: 0 }, libc::pollfd { fd: pipe[0], events: libc::POLLIN, revents: 0 }];
407
411
  let rc = unsafe { libc::poll(pfds.as_mut_ptr(), 2, (timeout * 1000.0).ceil() as i32) };
408
412
  if rc <= 0 {
@@ -0,0 +1,818 @@
1
+ //! Looping ASCII endless-runner on train tracks (easter egg: S toggles it as a side panel).
2
+ //!
3
+ //! Pure function of time: `frame(width, height, t)` returns `height` lines of exactly `width`
4
+ //! visible columns (SGR colours only). The course is generated once from a fixed seed and loops
5
+ //! every `LOOP` world units, so the animation is deterministic and repeats seamlessly. The runner's
6
+ //! lane changes come from a dynamic programme over the course (always collision-free, fewest
7
+ //! changes, coins and train roofs preferred); it jumps low barriers, rolls under high ones and
8
+ //! runs up ramps onto parked trains.
9
+
10
+ use crate::style::{color_on, unicode_on};
11
+ use std::sync::OnceLock;
12
+
13
+ pub const FPS: f64 = 15.0;
14
+ const SPEED: f64 = 11.0; // runner speed, world units per second
15
+ const LOOP: f64 = 264.0; // world units per loop (24 s)
16
+ const RUNNER_R: f64 = 1.35; // runner distance in front of the camera
17
+ const NEAR: f64 = 1.0;
18
+ const FAR: f64 = 48.0;
19
+ const MOVE_LEN: f64 = 2.4; // world units a lane change takes
20
+ const JUMP_LEN: f64 = 5.5;
21
+ const ROLL_LEN: f64 = 4.5;
22
+ const RAMP_LEN: f64 = 3.5; // ramp in front of a climbable train
23
+ const DROP_LEN: f64 = 3.0; // jump down from a roof
24
+ const STEP: f64 = 0.2; // planning resolution
25
+ const CHANGE_COST: f64 = 0.5; // planner: one lane change costs ~1 coin
26
+ const TRAIN_H: f64 = 0.55; // heights in lane widths
27
+ const JUMP_H: f64 = 0.4;
28
+ const LANES: [i32; 3] = [-1, 0, 1];
29
+ const TRAIN_COLOURS: [u8; 5] = [167, 75, 179, 71, 141];
30
+ const SEED: u64 = 20261104;
31
+
32
+ /// SplitMix64: small, deterministic, good enough for level generation.
33
+ struct Rng(u64);
34
+
35
+ impl Rng {
36
+ fn next_u64(&mut self) -> u64 {
37
+ self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
38
+ let mut z = self.0;
39
+ z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
40
+ z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
41
+ z ^ (z >> 31)
42
+ }
43
+ fn random(&mut self) -> f64 {
44
+ (self.next_u64() >> 11) as f64 / (1u64 << 53) as f64
45
+ }
46
+ fn uniform(&mut self, a: f64, b: f64) -> f64 {
47
+ a + (b - a) * self.random()
48
+ }
49
+ fn randint(&mut self, a: i64, b: i64) -> i64 {
50
+ a + (self.next_u64() % (b - a + 1) as u64) as i64
51
+ }
52
+ fn below(&mut self, n: usize) -> usize {
53
+ (self.next_u64() % n as u64) as usize
54
+ }
55
+ fn shuffle<T>(&mut self, v: &mut [T]) {
56
+ for i in (1..v.len()).rev() {
57
+ let j = self.below(i + 1);
58
+ v.swap(i, j);
59
+ }
60
+ }
61
+ fn weighted(&mut self, weights: &[f64]) -> usize {
62
+ let total: f64 = weights.iter().sum();
63
+ let mut x = self.random() * total;
64
+ for (i, w) in weights.iter().enumerate() {
65
+ if x < *w {
66
+ return i;
67
+ }
68
+ x -= w;
69
+ }
70
+ weights.len() - 1
71
+ }
72
+ }
73
+
74
+ #[derive(Clone, Copy)]
75
+ struct Train {
76
+ zm: f64, // the runner meets the front at runner z = zm
77
+ len: f64,
78
+ lane: i32,
79
+ col: u8,
80
+ k: f64, // train speed / runner speed (0: parked, > 0: oncoming)
81
+ ramp: bool,
82
+ }
83
+
84
+ impl Train {
85
+ /// Runner-z interval during which the runner is level with the train.
86
+ fn span(&self) -> (f64, f64) {
87
+ (self.zm, self.zm + self.len / (1.0 + self.k))
88
+ }
89
+ }
90
+
91
+ pub struct Course {
92
+ trains: Vec<Train>,
93
+ low: Vec<(f64, i32)>,
94
+ high: Vec<(f64, i32)>,
95
+ coins: Vec<(f64, i32, f64)>,
96
+ moves: Vec<(f64, i32)>,
97
+ jumps: Vec<f64>,
98
+ rolls: Vec<f64>,
99
+ roofs: Vec<(f64, f64, i32)>,
100
+ collected: Vec<bool>,
101
+ }
102
+
103
+ fn li(lane: i32) -> usize {
104
+ (lane + 1) as usize
105
+ }
106
+
107
+ impl Course {
108
+ pub fn new(seed: u64) -> Course {
109
+ for attempt in 0..500 {
110
+ let mut c = Course { trains: vec![], low: vec![], high: vec![], coins: vec![], moves: vec![], jumps: vec![],
111
+ rolls: vec![], roofs: vec![], collected: vec![] };
112
+ c.generate(&mut Rng(seed + attempt));
113
+ // keep only lively courses: every kind of move appears at least once per loop
114
+ if c.plan(&mut Rng(seed + 1000 + attempt)) && !c.jumps.is_empty() && !c.rolls.is_empty() && !c.roofs.is_empty()
115
+ && c.moves.len() >= 6
116
+ {
117
+ return c;
118
+ }
119
+ }
120
+ panic!("no feasible runner course");
121
+ }
122
+
123
+ fn generate(&mut self, rng: &mut Rng) {
124
+ let mut busy = [-99.0f64; 3]; // runner z until which a lane holds a train
125
+ let mut barrier_at = [-99.0f64; 3];
126
+ let (mut z, mut last_barrier) = (14.0f64, -99.0f64);
127
+ while z < LOOP - 40.0 {
128
+ const KINDS: [&str; 9] = ["parked", "parked2", "oncoming", "ramp", "low", "high", "mixed", "wall", "coins"];
129
+ let kind = KINDS[rng.weighted(&[2.0, 2.0, 4.0, 3.0, 3.0, 3.0, 3.0, 2.0, 1.0])];
130
+ let mut lanes: Vec<i32> = LANES.iter().copied().filter(|l| z - 2.0 > busy[li(*l)]).collect();
131
+ rng.shuffle(&mut lanes);
132
+ let barrier_ok = z - last_barrier > JUMP_LEN + 1.5;
133
+ match kind {
134
+ "parked" | "parked2" | "oncoming" if lanes.len() >= 2 => {
135
+ let n = if kind == "parked2" && lanes.len() == 3 { 2 } else { 1 };
136
+ for &lane in &lanes[..n] {
137
+ let k = if kind == "oncoming" { rng.uniform(0.5, 0.9) } else { 0.0 };
138
+ let (at, len) = (z + rng.uniform(0.0, 2.5), rng.uniform(7.0, 16.0));
139
+ self.train(rng, &mut busy, &barrier_at, at, len, lane, k, false);
140
+ }
141
+ if rng.random() < 0.6 {
142
+ let count = rng.randint(4, 7) as usize;
143
+ self.coin_row(lanes[n], z + 1.0, count, 0.0);
144
+ }
145
+ z += rng.uniform(3.0, 5.5);
146
+ }
147
+ "ramp" if lanes.len() >= 2 => {
148
+ let len = rng.uniform(12.0, 20.0);
149
+ if self.train(rng, &mut busy, &barrier_at, z + RAMP_LEN, len, lanes[0], 0.0, true) {
150
+ self.coin_row(lanes[0], z + RAMP_LEN + 2.0, (len / 1.6) as usize, TRAIN_H);
151
+ if rng.random() < 0.5 && lanes.len() == 3 {
152
+ let (at, l2, k) = (z + rng.uniform(2.0, 8.0), rng.uniform(8.0, 12.0), rng.uniform(0.5, 0.9));
153
+ self.train(rng, &mut busy, &barrier_at, at, l2, lanes[1], k, false);
154
+ }
155
+ }
156
+ z += RAMP_LEN + len * rng.uniform(0.35, 0.7);
157
+ }
158
+ "low" | "high" | "mixed" | "wall"
159
+ if barrier_ok && lanes.len() >= if kind == "mixed" || kind == "wall" { 3 } else { 1 } =>
160
+ {
161
+ let used: Vec<i32> = match kind {
162
+ "low" | "high" => {
163
+ if kind == "low" {
164
+ self.low.push((z, lanes[0]));
165
+ if rng.random() < 0.6 {
166
+ self.coin_arc(lanes[0], z);
167
+ }
168
+ } else {
169
+ self.high.push((z, lanes[0]));
170
+ }
171
+ vec![lanes[0]]
172
+ }
173
+ "mixed" => {
174
+ self.low.push((z, lanes[0]));
175
+ self.high.push((z, lanes[1]));
176
+ vec![lanes[0], lanes[1]]
177
+ }
178
+ _ => {
179
+ self.low.extend(LANES.iter().map(|l| (z, *l)));
180
+ self.coin_arc(lanes[0], z);
181
+ LANES.to_vec()
182
+ }
183
+ };
184
+ for l in used {
185
+ barrier_at[li(l)] = z;
186
+ }
187
+ if kind == "mixed" {
188
+ let len = rng.uniform(8.0, 13.0);
189
+ self.train(rng, &mut busy, &barrier_at, z + 2.5, len, lanes[2], 0.0, false);
190
+ }
191
+ last_barrier = z;
192
+ z += rng.uniform(2.5, 4.5);
193
+ }
194
+ "coins" if !lanes.is_empty() => {
195
+ let count = rng.randint(5, 9) as usize;
196
+ self.coin_row(lanes[0], z, count, 0.0);
197
+ z += rng.uniform(3.0, 5.0);
198
+ }
199
+ _ => z += 1.5,
200
+ }
201
+ }
202
+ }
203
+
204
+ #[allow(clippy::too_many_arguments)]
205
+ fn train(&mut self, rng: &mut Rng, busy: &mut [f64; 3], barrier_at: &[f64; 3], at: f64, len: f64, lane: i32, k: f64, ramp: bool) -> bool {
206
+ if at - if ramp { RAMP_LEN } else { 0.0 } - 2.0 < barrier_at[li(lane)] {
207
+ return false;
208
+ }
209
+ let tr = Train { zm: at, len, lane, col: TRAIN_COLOURS[rng.below(TRAIN_COLOURS.len())], k, ramp };
210
+ self.trains.push(tr);
211
+ busy[li(lane)] = tr.span().1 + if ramp { DROP_LEN } else { 0.0 };
212
+ true
213
+ }
214
+
215
+ fn coin_row(&mut self, lane: i32, z: f64, n: usize, height: f64) {
216
+ self.coins.extend((0..n).map(|i| (z + 1.2 * i as f64, lane, height)));
217
+ }
218
+
219
+ fn coin_arc(&mut self, lane: i32, z: f64) {
220
+ for i in 0..5 {
221
+ let p = (i as f64 - 2.0 + 2.75) / 5.5;
222
+ self.coins.push((z + (i as f64 - 2.0) * 1.1, lane, JUMP_H * 4.0 * p * (1.0 - p)));
223
+ }
224
+ }
225
+
226
+ fn plan(&mut self, style: &mut Rng) -> bool {
227
+ let mut n = (LOOP / STEP) as usize;
228
+ let kk = (MOVE_LEN / STEP).ceil() as usize;
229
+ let size = n + kk + 1;
230
+ let mut blocked = vec![[false; 3]; size]; // cannot be in this lane
231
+ let mut fixed = vec![[false; 3]; size]; // cannot change into / out of it
232
+ let mut gain = vec![[0.0f64; 3]; size];
233
+ let cells = |a: f64, b: f64| -> std::ops::Range<usize> {
234
+ let lo = ((a / STEP).trunc() as i64).max(0) as usize;
235
+ let hi = (((b / STEP).trunc() as i64 + 1).max(0) as usize).min(size);
236
+ lo..hi.max(lo)
237
+ };
238
+ for tr in &self.trains {
239
+ let (a, b) = tr.span();
240
+ if tr.ramp {
241
+ for i in cells(a - RAMP_LEN - 1.2, b + DROP_LEN + 0.3) {
242
+ fixed[i][li(tr.lane)] = true;
243
+ }
244
+ for i in cells(a - RAMP_LEN, b) {
245
+ gain[i][li(tr.lane)] += 0.05; // riding on trains is fun
246
+ }
247
+ } else {
248
+ for i in cells(a - 1.2, b + 0.6) {
249
+ blocked[i][li(tr.lane)] = true;
250
+ }
251
+ }
252
+ }
253
+ for &(z, lane) in self.low.iter().chain(self.high.iter()) {
254
+ let i = (z / STEP) as usize;
255
+ if blocked[i][li(lane)] || fixed[i][li(lane)] {
256
+ return false; // a barrier inside / beside a train would clash
257
+ }
258
+ }
259
+ if (0..size).any(|i| (0..3).any(|l| blocked[i][l] && fixed[i][l])) {
260
+ return false;
261
+ }
262
+ for &(z, lane, _) in &self.coins {
263
+ gain[((z / STEP) as usize).min(n)][li(lane)] += 0.45;
264
+ }
265
+ let mut z0 = 0usize;
266
+ while (z0 as f64) < LOOP {
267
+ // a preferred lane per stretch: the runner weaves
268
+ let lane = LANES[style.below(3)];
269
+ for i in cells(z0 as f64, z0 as f64 + 7.8) {
270
+ gain[i][li(lane)] += 0.06;
271
+ }
272
+ z0 += 8;
273
+ }
274
+ n -= kk; // back in the middle lane (change finished) by the end of the loop
275
+ let inf = f64::INFINITY;
276
+ let mut cost = vec![[inf; 3]; size];
277
+ let mut choice = vec![[1i32 << 8; 3]; n + 1];
278
+ for row in cost.iter_mut().skip(n) {
279
+ row[li(0)] = 0.0;
280
+ }
281
+ for i in (0..n).rev() {
282
+ for lane in LANES {
283
+ let l = li(lane);
284
+ if blocked[i][l] {
285
+ continue;
286
+ }
287
+ let (mut best, mut how) = (cost[i + 1][l] - gain[i][l], lane);
288
+ for l2 in [lane - 1, lane + 1] {
289
+ if !(-1..=1).contains(&l2) {
290
+ continue;
291
+ }
292
+ let k2 = li(l2);
293
+ if (i..=i + kk).any(|j| blocked[j][l] || blocked[j][k2] || fixed[j][l] || fixed[j][k2]) {
294
+ continue;
295
+ }
296
+ let alt = cost[i + kk][k2] + CHANGE_COST - gain[i][l] - 0.5 * gain[(i + kk).min(n)][k2];
297
+ if alt < best {
298
+ best = alt;
299
+ how = l2;
300
+ }
301
+ }
302
+ cost[i][l] = best;
303
+ choice[i][l] = how;
304
+ }
305
+ }
306
+ if cost[0][li(0)] == inf {
307
+ return false;
308
+ }
309
+ let (mut i, mut lane) = (0usize, 0i32);
310
+ while i < n {
311
+ let next = choice[i][li(lane)];
312
+ if next != lane {
313
+ self.moves.push((i as f64 * STEP, next));
314
+ lane = next;
315
+ i += kk;
316
+ } else {
317
+ i += 1;
318
+ }
319
+ }
320
+ let roofs: Vec<(f64, f64, i32)> =
321
+ self.trains.iter().filter(|t| t.ramp && (self.lane_at(t.zm) - t.lane as f64).abs() < 0.01).map(|t| (t.zm, t.span().1, t.lane)).collect();
322
+ self.roofs = roofs;
323
+ // also while changing lanes right at the barrier
324
+ let meets = |s: &Course, z: f64, lane: i32| (-6..=6).any(|dz| (s.lane_at(z + dz as f64 / 10.0) - lane as f64).abs() < 0.8);
325
+ let mut jumps: Vec<f64> = self.low.iter().filter(|(z, l)| meets(self, *z, *l)).map(|(z, _)| z - JUMP_LEN / 2.0).collect();
326
+ let mut rolls: Vec<f64> = self.high.iter().filter(|(z, l)| meets(self, *z, *l)).map(|(z, _)| z - ROLL_LEN / 2.0).collect();
327
+ jumps.sort_by(|a, b| a.partial_cmp(b).unwrap());
328
+ jumps.dedup();
329
+ rolls.sort_by(|a, b| a.partial_cmp(b).unwrap());
330
+ self.jumps = jumps;
331
+ self.rolls = rolls;
332
+ self.collected = self.coins.iter().map(|(z, l, _)| (self.lane_at(*z) - *l as f64).abs() < 0.45).collect();
333
+ true
334
+ }
335
+
336
+ /// Runner lane (fractional during a change) at runner position z in [0, LOOP).
337
+ fn lane_at(&self, z: f64) -> f64 {
338
+ let (mut prev, mut lane, mut start) = (0i32, 0i32, -1e9f64);
339
+ for &(mz, target) in &self.moves {
340
+ if mz > z {
341
+ break;
342
+ }
343
+ prev = lane;
344
+ lane = target;
345
+ start = mz;
346
+ }
347
+ let k = ((z - start) / MOVE_LEN).clamp(0.0, 1.0);
348
+ prev as f64 + (lane - prev) as f64 * k * k * (3.0 - 2.0 * k)
349
+ }
350
+
351
+ /// Runner feet height (lane widths): ramps, roofs, drops and jumps.
352
+ fn height_at(&self, z: f64) -> f64 {
353
+ for &(z0, z1, _) in &self.roofs {
354
+ if z0 - RAMP_LEN <= z && z < z0 {
355
+ return TRAIN_H * (z - z0 + RAMP_LEN) / RAMP_LEN;
356
+ }
357
+ if z0 <= z && z < z1 {
358
+ return TRAIN_H;
359
+ }
360
+ if z1 <= z && z < z1 + DROP_LEN {
361
+ let p = (z - z1) / DROP_LEN;
362
+ return TRAIN_H * (1.0 - p * p) + 0.25 * JUMP_H * (std::f64::consts::PI * p).sin();
363
+ }
364
+ }
365
+ for &jz in &self.jumps {
366
+ if jz <= z && z < jz + JUMP_LEN {
367
+ let p = (z - jz) / JUMP_LEN;
368
+ return JUMP_H * 4.0 * p * (1.0 - p);
369
+ }
370
+ }
371
+ 0.0
372
+ }
373
+
374
+ /// Jumping or dropping (not running on a ramp or a roof).
375
+ fn airborne_at(&self, z: f64) -> bool {
376
+ self.jumps.iter().any(|&jz| jz <= z && z < jz + JUMP_LEN) || self.roofs.iter().any(|&(_, z1, _)| z1 <= z && z < z1 + DROP_LEN)
377
+ }
378
+
379
+ fn rolling_at(&self, z: f64) -> bool {
380
+ self.rolls.iter().any(|&rz| rz <= z && z < rz + ROLL_LEN)
381
+ }
382
+ }
383
+
384
+ fn course() -> &'static Course {
385
+ static COURSE: OnceLock<Course> = OnceLock::new();
386
+ COURSE.get_or_init(|| Course::new(SEED))
387
+ }
388
+
389
+ const SPRITE_COLORS: [u8; 5] = [213, 117, 117, 75, 75];
390
+
391
+ fn sprite(name: &str) -> &'static [&'static str] {
392
+ match name {
393
+ "a" => &[" o ", "/|\\", "/ >"],
394
+ "b" => &[" o ", "\\|/", "< \\"],
395
+ "jump" => &["\\o/", " | ", "/ \\"],
396
+ "roll" => &[" ", " _ ", "(o)"],
397
+ "A" => &[" O ", " /|\\ ", "/ | \\", " /\\ ", " / |"],
398
+ "B" => &[" O ", " /|\\ ", "\\ | /", " /\\ ", " | \\"],
399
+ "JUMP" => &["\\ O /", " \\|/ ", " | ", " / \\ ", "/ \\"],
400
+ _ => &[" ", " ", " __ ", " /O \\", " \\__/"], // ROLL
401
+ }
402
+ }
403
+
404
+ fn ascii(ch: char) -> char {
405
+ match ch {
406
+ '█' => '#',
407
+ '▀' => '"',
408
+ '▄' | '▁' | '▂' => '_',
409
+ '═' => '=',
410
+ '◎' | '●' => 'o',
411
+ '▒' => ':',
412
+ '·' | '▪' => '.',
413
+ '◐' => 'C',
414
+ '╥' => 'n',
415
+ '│' => '|',
416
+ '▓' => '%',
417
+ other => other,
418
+ }
419
+ }
420
+
421
+ struct Canvas {
422
+ w: usize,
423
+ h: usize,
424
+ cells: Vec<(char, Option<u8>, Option<u8>)>,
425
+ }
426
+
427
+ impl Canvas {
428
+ fn put(&mut self, x: f64, y: f64, ch: char, fg: Option<u8>, bg: Option<u8>) {
429
+ let (x, y) = (x.round(), y.round());
430
+ if x < 0.0 || y < 0.0 || x >= self.w as f64 || y >= self.h as f64 {
431
+ return;
432
+ }
433
+ let cell = &mut self.cells[y as usize * self.w + x as usize];
434
+ cell.0 = ch;
435
+ if fg.is_some() {
436
+ cell.1 = fg;
437
+ }
438
+ if bg.is_some() {
439
+ cell.2 = bg;
440
+ }
441
+ }
442
+
443
+ fn rect(&mut self, x0: f64, x1: f64, y0: f64, y1: f64, ch: char, fg: Option<u8>, bg: Option<u8>) {
444
+ let (ya, yb) = ((y0.round() as i64).max(0), (y1.round() as i64 + 1).min(self.h as i64));
445
+ let (xa, xb) = ((x0.round() as i64).max(0), (x1.round() as i64 + 1).min(self.w as i64));
446
+ for y in ya..yb {
447
+ for x in xa..xb {
448
+ self.put(x as f64, y as f64, ch, fg, bg);
449
+ }
450
+ }
451
+ }
452
+
453
+ fn lines(&self) -> Vec<String> {
454
+ let (color, uni) = (color_on(), unicode_on());
455
+ (0..self.h)
456
+ .map(|y| {
457
+ let mut out = String::new();
458
+ let mut run = String::new();
459
+ let mut key: Option<(Option<u8>, Option<u8>)> = None;
460
+ for x in 0..self.w {
461
+ let (ch, fg, bg) = self.cells[y * self.w + x];
462
+ let ch = if uni { ch } else { ascii(ch) };
463
+ if key != Some((fg, bg)) && !run.is_empty() {
464
+ out.push_str(&sgr(key.unwrap(), &run, color));
465
+ run.clear();
466
+ }
467
+ key = Some((fg, bg));
468
+ run.push(ch);
469
+ }
470
+ if let Some(k) = key {
471
+ out.push_str(&sgr(k, &run, color));
472
+ }
473
+ out
474
+ })
475
+ .collect()
476
+ }
477
+ }
478
+
479
+ fn sgr((fg, bg): (Option<u8>, Option<u8>), text: &str, color: bool) -> String {
480
+ if !color || (fg.is_none() && bg.is_none()) {
481
+ return text.to_string();
482
+ }
483
+ let mut codes = vec![];
484
+ if let Some(f) = fg {
485
+ codes.push(format!("38;5;{}", f));
486
+ }
487
+ if let Some(b) = bg {
488
+ codes.push(format!("48;5;{}", b));
489
+ }
490
+ format!("\x1b[{}m{}\x1b[0m", codes.join(";"), text)
491
+ }
492
+
493
+ fn shade(col: u8) -> u8 {
494
+ match col {
495
+ 167 => 131,
496
+ 75 => 67,
497
+ 179 => 136,
498
+ 71 => 65,
499
+ 141 => 97,
500
+ _ => 240,
501
+ }
502
+ }
503
+
504
+ fn roof(col: u8) -> u8 {
505
+ match col {
506
+ 167 => 174,
507
+ 75 => 111,
508
+ 179 => 187,
509
+ 71 => 108,
510
+ 141 => 183,
511
+ _ => 250,
512
+ }
513
+ }
514
+
515
+ /// Distances from the camera of an object's copies in this loop and the next.
516
+ fn instances(z: f64, k: f64, cam: f64) -> [f64; 2] {
517
+ [0.0, 1.0].map(|n| {
518
+ let zm = z + n * LOOP;
519
+ zm - (cam + RUNNER_R - zm) * k - cam
520
+ })
521
+ }
522
+
523
+ enum Obj {
524
+ Train { r0: f64, rf: f64, lane: i32, col: u8, k: f64, ramp: bool },
525
+ Low(i32),
526
+ High(i32),
527
+ Coin(i32, f64),
528
+ Runner,
529
+ }
530
+
531
+ /// One animation frame at time `t` (seconds), `height` lines of exactly `width` visible columns.
532
+ pub fn frame(width: usize, height: usize, t: f64) -> Vec<String> {
533
+ let course = course();
534
+ let (w, h) = (width.max(20), height.max(10));
535
+ let mut cv = Canvas { w, h, cells: vec![(' ', None, None); w * h] };
536
+ let dist = t * SPEED;
537
+ let (loops, cam) = ((dist / LOOP).floor(), dist.rem_euclid(LOOP));
538
+ let zr = cam + RUNNER_R;
539
+ let zrl = zr.rem_euclid(LOOP);
540
+ let (lane_r, elev) = (course.lane_at(zrl), course.height_at(zrl));
541
+ let (airborne, rolling) = (course.airborne_at(zrl), course.rolling_at(zrl));
542
+ let hy = (h / 3).max(3); // horizon row
543
+ let span = (h - hy) as f64;
544
+ let cx = (w as f64 - 1.0) / 2.0;
545
+ let lw = w as f64 * 0.30; // lane width in columns at the bottom row
546
+ let cam_u = 0.35 * lane_r; // the camera follows the runner sideways
547
+ let sx = |u: f64, d: f64| cx + (u - cam_u) * d * lw;
548
+ let row_of = |r: f64| hy as f64 + (1.0 / r) * span - 1.0;
549
+
550
+ // sky: drifting clouds, skyline with twinkling windows
551
+ for (i, (cy, speed, size)) in [(1usize, 1.6, 4usize), (2, 2.3, 6), (1, 1.1, 3)].into_iter().enumerate() {
552
+ if cy + 1 < hy {
553
+ let x0 = ((i * 23 + 7) as f64 - t * speed).rem_euclid((w + 12) as f64) - 6.0;
554
+ let cloud: Vec<char> = std::iter::once('▂').chain(std::iter::repeat('▄').take(size)).chain(std::iter::once('▂')).collect();
555
+ for (j, ch) in cloud.into_iter().enumerate() {
556
+ cv.put(x0 + j as f64, cy as f64, ch, Some(250), None);
557
+ }
558
+ }
559
+ }
560
+ let mut rng = Rng(7);
561
+ let tick = (t * 2.0) as i64;
562
+ let mut x = 0usize;
563
+ while x < w {
564
+ let bw = rng.randint(3, 7) as usize;
565
+ let bh = rng.randint(1, (hy as i64 - 2).max(1)) as usize;
566
+ for xx in x..(x + bw).min(w) {
567
+ for yy in hy - bh.min(hy)..hy {
568
+ let seed = rng.random();
569
+ let lit = seed < 0.2 && xx != x && xx != x + bw - 1 && (tick + (seed * 97.0) as i64) % 9 != 0;
570
+ if lit {
571
+ cv.put(xx as f64, yy as f64, '▪', Some(222), Some(237));
572
+ } else {
573
+ cv.put(xx as f64, yy as f64, '█', Some(237), None);
574
+ }
575
+ }
576
+ }
577
+ x += bw + rng.randint(0, 2) as usize;
578
+ }
579
+ cv.put(w as f64 - 6.0, 1.0, '◐', Some(229), None);
580
+
581
+ // ground: row y has depth r = 1/d
582
+ for y in hy..h {
583
+ let d = (y - hy + 1) as f64 / span;
584
+ let r = 1.0 / d;
585
+ let zw = cam + r;
586
+ let tie = r < 14.0 && (zw / 1.6).rem_euclid(1.0) < 0.35;
587
+ let post = (zw / 5.0).rem_euclid(1.0) < 0.18;
588
+ for x in 0..w {
589
+ let u = (x as f64 - cx) / (d * lw) + cam_u;
590
+ let au = u.abs();
591
+ let (xf, yf) = (x as f64, y as f64);
592
+ if au > 1.75 {
593
+ cv.put(xf, yf, '▒', Some(if post { 244 } else { 239 }), Some(235));
594
+ } else if au > 1.5 {
595
+ cv.put(xf, yf, '·', Some(242), Some(236));
596
+ } else if (u - u.round()).abs() > 0.3 {
597
+ cv.put(xf, yf, if (x + y) % 3 == 0 { '·' } else { ' ' }, Some(240), Some(236));
598
+ } else if tie {
599
+ cv.put(xf, yf, '═', Some(137), Some(237));
600
+ } else {
601
+ cv.put(xf, yf, ' ', None, Some(237));
602
+ }
603
+ }
604
+ for lane in LANES {
605
+ for side in [-0.3, 0.3] {
606
+ let u = lane as f64 + side;
607
+ let ch = if u - cam_u < -0.05 { '/' } else if u - cam_u > 0.05 { '\\' } else { '|' };
608
+ cv.put(sx(u, d), y as f64, ch, Some(if r < 8.0 { 252 } else { 246 }), Some(237));
609
+ }
610
+ }
611
+ }
612
+
613
+ // objects, painted far to near; the runner is one of them
614
+ let mut items: Vec<(f64, Obj)> = vec![];
615
+ for tr in &course.trains {
616
+ for r0 in instances(tr.zm, tr.k, cam) {
617
+ let (r1, rs) = (r0 + tr.len, r0 - if tr.ramp { RAMP_LEN } else { 0.0 });
618
+ if r1 >= NEAR && rs <= FAR {
619
+ items.push((r1.min(FAR), Obj::Train { r0, rf: r1.min(FAR), lane: tr.lane, col: tr.col, k: tr.k, ramp: tr.ramp }));
620
+ }
621
+ }
622
+ }
623
+ for (high, list) in [(false, &course.low), (true, &course.high)] {
624
+ for &(z, lane) in list {
625
+ for r in instances(z, 0.0, cam) {
626
+ if (NEAR..=FAR).contains(&r) {
627
+ items.push((r, if high { Obj::High(lane) } else { Obj::Low(lane) }));
628
+ }
629
+ }
630
+ }
631
+ }
632
+ let mut collected_now = 0usize;
633
+ for (&(z, lane, height), &got) in course.coins.iter().zip(course.collected.iter()) {
634
+ if got && z <= zr {
635
+ collected_now += 1;
636
+ }
637
+ for r in instances(z, 0.0, cam) {
638
+ if got && r <= RUNNER_R + 0.15 {
639
+ continue;
640
+ }
641
+ if (NEAR..=FAR).contains(&r) {
642
+ items.push((r - 0.01, Obj::Coin(lane, height)));
643
+ }
644
+ }
645
+ }
646
+ items.push((RUNNER_R, Obj::Runner));
647
+ items.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
648
+
649
+ for (r, obj) in items {
650
+ let d = 1.0 / r;
651
+ match obj {
652
+ Obj::Train { r0, rf, lane, col, k, ramp } => {
653
+ let rn = r0.max(NEAR);
654
+ if rf > rn {
655
+ let steps = (((rf - rn) / 0.35) as usize).max(1);
656
+ for s in 0..=steps {
657
+ let rr = rf - (rf - rn) * s as f64 / steps as f64;
658
+ let dd = 1.0 / rr;
659
+ let (xc, hw, yb) = (sx(lane as f64, dd), 0.42 * dd * lw, row_of(rr));
660
+ let ht = (TRAIN_H * dd * lw).max(1.0);
661
+ let front = r0 >= NEAR && s == steps;
662
+ cv.rect(xc - hw, xc + hw, yb - ht + 1.0, yb, '█', Some(if front { col } else { shade(col) }), None);
663
+ cv.rect(xc - hw, xc + hw, yb - ht + 1.0, yb - ht + 1.0, '█', Some(roof(col)), None);
664
+ if front && hw >= 2.0 {
665
+ let wy = yb - ht + 1.0 + ((ht * 0.25) as i64).max(1) as f64;
666
+ cv.rect(xc - hw * 0.6, xc + hw * 0.6, wy, wy + ((ht * 0.2) as i64).max(0) as f64, ' ', None, Some(24));
667
+ // oncoming: blinking headlights; parked: red tail lights
668
+ let lamp = if k > 0.0 { if (t * 6.0) as i64 % 2 == 1 { 231 } else { 229 } } else { 196 };
669
+ cv.put(xc - hw * 0.6, yb - 1.0, '●', Some(lamp), Some(col));
670
+ cv.put(xc + hw * 0.6, yb - 1.0, '●', Some(lamp), Some(col));
671
+ }
672
+ }
673
+ }
674
+ if ramp {
675
+ // wedge in front of the train; the part behind the runner would hide it
676
+ let rs = r0 - RAMP_LEN;
677
+ let (a, b) = (rs.max(NEAR).max(RUNNER_R + 0.2), r0.min(FAR));
678
+ if b > a {
679
+ let steps = (((b - a) / 0.25) as usize).max(1);
680
+ for s in 0..=steps {
681
+ let rr = b - (b - a) * s as f64 / steps as f64;
682
+ let dd = 1.0 / rr;
683
+ let (xc, hw) = (sx(lane as f64, dd), 0.36 * dd * lw);
684
+ let ht = TRAIN_H * (rr - rs) / RAMP_LEN * dd * lw;
685
+ if ht >= 0.5 {
686
+ let yb = row_of(rr);
687
+ cv.rect(xc - hw, xc + hw, yb - ht + 1.0, yb, '▓', Some(244), Some(240));
688
+ cv.rect(xc - hw, xc + hw, yb - ht + 1.0, yb - ht + 1.0, '▀', Some(250), Some(240));
689
+ }
690
+ }
691
+ }
692
+ }
693
+ }
694
+ Obj::Low(lane) => {
695
+ let (xc, hw, yb) = (sx(lane as f64, d), 0.4 * d * lw, row_of(r));
696
+ let ht = (0.22 * d * lw).round().max(1.0);
697
+ for x in (xc - hw).round() as i64..=(xc + hw).round() as i64 {
698
+ cv.put(x as f64, yb - ht + 1.0, '▄', Some(if x.div_euclid(2) % 2 != 0 { 203 } else { 255 }), None);
699
+ }
700
+ if ht > 1.0 {
701
+ cv.put(xc - hw, yb, '╥', Some(250), None);
702
+ cv.put(xc + hw, yb, '╥', Some(250), None);
703
+ }
704
+ }
705
+ Obj::High(lane) => {
706
+ let (xc, hw, yb) = (sx(lane as f64, d), 0.42 * d * lw, row_of(r));
707
+ let ht = (0.5 * d * lw).round().max(2.0);
708
+ for y in (yb - ht + 1.0).round() as i64..=yb.round() as i64 {
709
+ cv.put(xc - hw, y as f64, '│', Some(250), None);
710
+ cv.put(xc + hw, y as f64, '│', Some(250), None);
711
+ }
712
+ for x in (xc - hw).round() as i64..=(xc + hw).round() as i64 {
713
+ cv.put(x as f64, yb - ht + 1.0, '▀', Some(if x.div_euclid(2) % 2 != 0 { 220 } else { 238 }), None);
714
+ }
715
+ }
716
+ Obj::Coin(lane, height) => {
717
+ let lift = (height + 0.12) * d * lw;
718
+ let spin = if (t * 4.0 + r) as i64 % 3 != 0 { '◎' } else { '●' };
719
+ cv.put(sx(lane as f64, d), row_of(r) - lift, if r < 7.0 { spin } else { '·' }, Some(220), None);
720
+ }
721
+ Obj::Runner => {
722
+ let (xc, yb) = (sx(lane_r, d), row_of(r));
723
+ let jump_px = (JUMP_H * d * lw).max(2.0) / (JUMP_H * d * lw); // keep small jumps visible
724
+ let scale = if elev < JUMP_H + 1e-9 && airborne { jump_px } else { 1.0 };
725
+ let lift = (elev * d * lw * scale).round();
726
+ let big = d * lw >= 11.0 && h >= 22;
727
+ let step = (t * 8.0) as i64 % 2 == 1;
728
+ let name = match (rolling, airborne, big) {
729
+ (true, _, true) => "ROLL",
730
+ (true, _, false) => "roll",
731
+ (false, true, true) => "JUMP",
732
+ (false, true, false) => "jump",
733
+ (false, false, true) => if step { "A" } else { "B" },
734
+ (false, false, false) => if step { "a" } else { "b" },
735
+ };
736
+ let spr = sprite(name);
737
+ let half = (spr[0].chars().count() / 2) as f64;
738
+ if airborne && lift != 0.0 {
739
+ cv.rect(xc - half, xc + half, yb, yb, '▁', Some(233), None); // shadow on the ground
740
+ }
741
+ let n = spr.len();
742
+ for (i, line) in spr.iter().enumerate() {
743
+ for (j, ch) in line.chars().enumerate() {
744
+ if ch != ' ' {
745
+ let col = if rolling || i == 0 { 213 } else { SPRITE_COLORS[(i * 5 / n).min(4)] };
746
+ cv.put(xc - half + j as f64, yb - lift - n as f64 + 1.0 + i as f64, ch, Some(col), None);
747
+ }
748
+ }
749
+ }
750
+ if airborne {
751
+ cv.rect(xc - half, xc + half, yb - lift + 1.0, yb - lift + 1.0, '▀', Some(208), None); // board
752
+ }
753
+ }
754
+ }
755
+ }
756
+
757
+ // HUD
758
+ let coins = loops as usize * course.collected.iter().filter(|g| **g).count() + collected_now;
759
+ let hud = format!(" {:06} ◎ {} ", (dist * 10.0) as i64, coins);
760
+ for (i, ch) in hud.chars().enumerate() {
761
+ cv.put(i as f64, 0.0, ch, Some(231), Some(236));
762
+ }
763
+ cv.lines()
764
+ }
765
+
766
+ #[cfg(test)]
767
+ mod tests {
768
+ use super::*;
769
+ use crate::style::vlen;
770
+
771
+ #[test]
772
+ fn course_is_collision_free_and_seamless() {
773
+ let c = course();
774
+ let mut z = 0.0;
775
+ while z < LOOP {
776
+ let (l, h) = (c.lane_at(z), c.height_at(z));
777
+ for tr in &c.trains {
778
+ let (a, b) = tr.span();
779
+ let level = (l - tr.lane as f64).abs() < 0.75;
780
+ if a <= z && z <= b && level {
781
+ assert!(tr.ramp && (h - TRAIN_H).abs() < 1e-9, "hits a train at z={:.2}", z);
782
+ }
783
+ if tr.ramp && a - RAMP_LEN <= z && z < b {
784
+ let off = (l - tr.lane as f64).abs();
785
+ assert!(!(0.01 < off && off < 0.75), "brushes a ramp train at z={:.2}", z);
786
+ }
787
+ }
788
+ for &(zb, lane) in &c.low {
789
+ if (z - zb).abs() < 0.3 && (l - lane as f64).abs() < 0.75 {
790
+ assert!(h >= 0.6 * JUMP_H, "hits a low barrier at z={:.2}", z);
791
+ }
792
+ }
793
+ for &(zb, lane) in &c.high {
794
+ if (z - zb).abs() < 0.3 && (l - lane as f64).abs() < 0.75 {
795
+ assert!(c.rolling_at(z), "hits a high barrier at z={:.2}", z);
796
+ }
797
+ }
798
+ z += 0.02;
799
+ }
800
+ assert!(c.lane_at(LOOP - 1e-6).abs() < 1e-9 && c.height_at(LOOP - 1e-6) == 0.0, "loop seam");
801
+ eprintln!("trains {} (oncoming {}, ramps {}) low {} high {} coins {}/{} | moves {} jumps {} rolls {} roofs {}",
802
+ c.trains.len(), c.trains.iter().filter(|t| t.k > 0.0).count(), c.trains.iter().filter(|t| t.ramp).count(),
803
+ c.low.len(), c.high.len(), c.collected.iter().filter(|g| **g).count(), c.coins.len(),
804
+ c.moves.len(), c.jumps.len(), c.rolls.len(), c.roofs.len());
805
+ assert!(c.trains.len() >= 10 && !c.roofs.is_empty() && !c.jumps.is_empty() && c.moves.len() >= 4, "course too static");
806
+ }
807
+
808
+ #[test]
809
+ fn frames_have_exact_width() {
810
+ for (w, h) in [(40, 20), (56, 36), (64, 44)] {
811
+ for i in 0..60 {
812
+ let f = frame(w, h, i as f64 * 0.41);
813
+ assert_eq!(f.len(), h);
814
+ assert!(f.iter().all(|l| vlen(l) == w));
815
+ }
816
+ }
817
+ }
818
+ }
File without changes