cuqueclicker_lib/sim.rs
1//! Platform-agnostic simulation core.
2//!
3//! Owns the [`Action`] / [`BuyQty`] types (the input router produces them;
4//! [`apply_action`] is the only thing that interprets them) and the per-tick
5//! `state.tick()` + ambient spawn helpers.
6//!
7//! What lives **outside** this module:
8//! - the threaded sim loop on native (`app.rs::sim_loop`), which wraps
9//! [`sim_tick`] + [`apply_action`] with `mpsc::recv_timeout`, save
10//! scheduling via the [`Persistence`](crate::platform::Persistence) impl,
11//! and the demo-recorder driver.
12//! - the requestAnimationFrame-driven loop on web (added when the wasm
13//! port lands), which calls the same [`sim_tick`] + [`apply_action`]
14//! single-threaded.
15//!
16//! The split is: this module is cross-platform; threading + I/O scheduling
17//! around it isn't. See tracking issue #13 for rationale.
18
19use rand::RngExt;
20use ratatui::layout::Rect;
21
22use crate::game::powerup::{self, Powerup, PowerupKind};
23use crate::game::state::{GameState, TICK_DT};
24use crate::game::tree::coord::TreeCoord;
25
26/// Buy quantity for a fingerer purchase action. Modifier-key meaning is
27/// translated to this in the input router; sim only consumes the resolved
28/// value so the modifier mapping can change without touching tick logic.
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum BuyQty {
31 One,
32 Ten,
33 Max,
34}
35
36/// Commands the input router produces and the sim consumes. The sim is
37/// the sole authority on [`GameState`] mutation — input handling translates
38/// raw events (key/mouse/wheel) into these and feeds them through.
39#[derive(Clone, Debug)]
40pub enum Action {
41 Click {
42 col: u16,
43 row: u16,
44 },
45 ClickCenter,
46 /// Catch the on-screen powerup with the given `spawn_id`. The id is
47 /// minted at spawn time on `GameState::next_spawn_id`; click hit-test
48 /// and the `g` hotkey both reference instances by id, never by Vec
49 /// index, so `swap_remove` on catch is safe even with multiple
50 /// in-flight events between frames.
51 CatchPowerup(u64),
52 BuyFingerer {
53 idx: usize,
54 qty: BuyQty,
55 },
56 /// Buy the tree node at the given lot. No-op if the lot doesn't have a
57 /// node, is already owned, isn't reachable, or the player can't afford it.
58 TreeBuy(TreeCoord),
59 /// Refund the tree node at the given lot. No-op if not owned, would
60 /// orphan another owned node, or the node doesn't exist.
61 TreeRefund(TreeCoord),
62 /// Move the tree cursor to `lot` (no purchase). Persists into
63 /// `state.tree.cursor` so reopening the modal lands here.
64 TreeFocus(TreeCoord),
65 PrestigeReset,
66 /// Latest render-computed biscuit geometry, so the sim can place
67 /// powerups and auto-particles inside the current layout. Powerup
68 /// rects live on the input/render side (only the click handler reads
69 /// them). `powerups_paused` is set while a full-screen modal (the
70 /// upgrade tree) is open — auto-FPS keeps accruing but the powerup
71 /// engine freezes (no new spawns, existing on-screen powerups stop
72 /// counting down their lifetime).
73 UpdateGeometry {
74 biscuit: Rect,
75 powerups_paused: bool,
76 },
77 /// Dev-only cheats (F-keys). Gated at the input router by `debug`;
78 /// the sim trusts whatever arrives.
79 DevAddCuques(f64),
80 /// Force-spawn a powerup of the given kind. Pushes a fresh entry onto
81 /// `state.powerups` — pressing the same F-key twice now produces two
82 /// of the same kind on screen.
83 DevForcePowerup(PowerupKind),
84 /// J10: a click that didn't hit anything actionable. Sim spawns a
85 /// short-lived "·" misclick particle at the screen point so dead-zone
86 /// clicks visibly register.
87 Misclick {
88 col: u16,
89 row: u16,
90 },
91}
92
93/// Geometry the sim needs to interpret screen-space events. Updated on
94/// every render via [`Action::UpdateGeometry`].
95#[derive(Clone, Copy, Default)]
96pub struct SimGeometry {
97 pub biscuit: Rect,
98 /// True while a full-screen modal (the upgrade tree) is open. Pauses
99 /// the powerup spawn / tick engine; the rest of the tick keeps
100 /// running so auto-FPS continues to accrue underneath.
101 pub powerups_paused: bool,
102}
103
104/// Apply one [`Action`] to the canonical [`GameState`]. Pure data: no I/O,
105/// no time, no threading. Called from both the native sim thread (on
106/// `mpsc::recv_timeout` returning Ok) and the web rAF loop.
107pub fn apply_action(state: &mut GameState, action: Action, geom: &mut SimGeometry) {
108 match action {
109 Action::Click { col, row } => {
110 let r = geom.biscuit;
111 if r.width > 0
112 && col >= r.x
113 && col < r.x + r.width
114 && row >= r.y
115 && row < r.y + r.height
116 {
117 state.click((col, row), r);
118 }
119 }
120 Action::ClickCenter => {
121 let r = geom.biscuit;
122 if r.width > 0 && r.height > 0 {
123 state.click((r.x + r.width / 2, r.y + r.height / 2), r);
124 }
125 // Mark this tick as "saw a spacebar press." `tick()` reads the
126 // flag, advances the held-streak counter, and clears it. A
127 // single tap → 1 tick of streak → resets immediately. A held
128 // key (terminal repeat) → streak climbs over time.
129 state.space_pressed_this_tick = true;
130 }
131 Action::CatchPowerup(id) => {
132 state.catch_powerup(id);
133 }
134 Action::BuyFingerer { idx, qty } => match qty {
135 BuyQty::One => {
136 state.buy(idx);
137 }
138 BuyQty::Ten => {
139 state.buy_n(idx, 10);
140 }
141 BuyQty::Max => {
142 state.buy_max(idx);
143 }
144 },
145 Action::TreeBuy(lot) => {
146 state.buy_tree_node(lot);
147 }
148 Action::TreeRefund(lot) => {
149 let _ = state.refund_tree_node(lot);
150 }
151 Action::TreeFocus(lot) => {
152 state.tree.cursor = lot;
153 }
154 Action::PrestigeReset => {
155 state.prestige_reset();
156 }
157 Action::UpdateGeometry {
158 biscuit,
159 powerups_paused,
160 } => {
161 *geom = SimGeometry {
162 biscuit,
163 powerups_paused,
164 };
165 }
166 Action::DevAddCuques(n) => {
167 state.dev_add_cuques(n);
168 }
169 Action::DevForcePowerup(kind) => {
170 force_spawn_powerup(state, geom, kind);
171 }
172 Action::Misclick { col, row } => {
173 state.spawn_misclick(col, row);
174 }
175 }
176}
177
178/// Run the platform-agnostic body of one sim tick: state updates + ambient
179/// spawn helpers. Save scheduling and demo-driver autopilot are the
180/// **caller's** concern (they live in `app.rs::sim_loop` on native).
181///
182/// When `geom.powerups_paused` is set (a full-screen modal is open), the
183/// powerup engine is skipped entirely — no spawns, no lifetime ticks, no
184/// cooldown advancement. The base tick still runs so auto-FPS, modifiers,
185/// achievements, and HUD count-ups keep flowing.
186pub fn sim_tick(state: &mut GameState, geom: &SimGeometry) {
187 state.tick();
188 if !geom.powerups_paused {
189 state.tick_powerups();
190 maybe_spawn_powerups(state, geom);
191 }
192 maybe_spawn_auto_particle(state, geom);
193 maybe_idle_clench(state);
194}
195
196fn maybe_idle_clench(state: &mut GameState) {
197 if state.clench_ticks > 0 {
198 return;
199 }
200 // ~1 per 45s average at 20Hz
201 if rand::rng().random::<f64>() < 1.0 / 900.0 {
202 state.trigger_clench();
203 }
204}
205
206fn maybe_spawn_auto_particle(state: &mut GameState, geom: &SimGeometry) {
207 let fps = state.fps();
208 if fps <= 0.0 || geom.biscuit.width < 4 || geom.biscuit.height < 4 {
209 return;
210 }
211 let target_rate = fps.sqrt().clamp(0.5, 8.0);
212 let prob = target_rate * TICK_DT;
213 let mut rng = rand::rng();
214 if rng.random::<f64>() >= prob {
215 return;
216 }
217 // Random anchor within the biscuit, with a small inset so the "+N" text
218 // doesn't clip into the border.
219 let frac_x = rng.random_range(0.05_f32..=0.95);
220 let frac_y = rng.random_range(0.10_f32..=0.95);
221 state.spawn_auto_particle(frac_x, frac_y);
222}
223
224/// Insets pull the spawn lottery away from the biscuit edges so the 5×3
225/// marker has room to render without clipping into the border. Match the
226/// pre-refactor inset values exactly — they were tuned against the same
227/// marker geometry.
228const SPAWN_INSET_X: f32 = 0.08;
229const SPAWN_INSET_Y: f32 = 0.10;
230/// Minimum cell-space distance between two on-screen powerup centers,
231/// measured in biscuit-cell units (NOT fractional units). The 5×3 marker
232/// is 5 cells wide and 3 tall, so a 4-cell minimum keeps two markers
233/// from sharing any of their interior cells while still allowing tight
234/// neighbors that read as distinct.
235const POWERUP_MIN_CELL_DIST: f32 = 4.0;
236/// Approximate biscuit cell aspect ratio (width / height of a terminal
237/// cell). Most monospace fonts render cells ~2× taller than wide; the
238/// FULL biscuit's bounding box is ~60×30 (cell ratio 2:1), MEDIUM is
239/// 40×18 (~2.2:1), TINY is 16×8 (2:1). Using 2.0 here keeps the
240/// dispersion check working in cell space, so the same fractional gap
241/// in `frac_y` covers more visual cells than in `frac_x` — without this
242/// correction, two markers separated only vertically would read as
243/// overlapping while passing the dispersion filter.
244const BISCUIT_CELL_ASPECT: f32 = 2.0;
245/// Best-effort retry budget for dispersion. Eight tries is plenty when the
246/// Vec is short (the expected ~0.2 concurrent per kind average); on a
247/// pile-up the fall-through to plain-random keeps the spawn happening
248/// rather than skipping it.
249const POWERUP_DISPERSION_TRIES: u32 = 8;
250
251/// Pick a fractional position inside the biscuit, dispersed away from any
252/// existing powerup in `existing`. Best-effort: up to
253/// `POWERUP_DISPERSION_TRIES` retries, then accept a plain-random position
254/// (acceptable to the issue spec — exact overlap is rare in practice).
255///
256/// `biscuit_cells` is `(width, height)` of the live biscuit rect. The
257/// dispersion check works in CELL SPACE — `dx_cells² + dy_cells² ≥
258/// POWERUP_MIN_CELL_DIST²` — because the biscuit is roughly 2:1 in cell
259/// aspect (terminal cells are ~2× tall as wide), and a pure-fractional
260/// distance would over-allow vertical overlap.
261fn pick_dispersed_frac(existing: &[Powerup], biscuit_cells: (u16, u16)) -> (f32, f32) {
262 let (bw, bh) = biscuit_cells;
263 let bw = bw.max(1) as f32;
264 let bh = bh.max(1) as f32;
265 let min_sq = POWERUP_MIN_CELL_DIST * POWERUP_MIN_CELL_DIST;
266 let mut rng = rand::rng();
267 for _ in 0..POWERUP_DISPERSION_TRIES {
268 let fx = rng.random_range(SPAWN_INSET_X..=(1.0 - SPAWN_INSET_X));
269 let fy = rng.random_range(SPAWN_INSET_Y..=(1.0 - SPAWN_INSET_Y));
270 let too_close = existing.iter().any(|p| {
271 // Convert fractional deltas to cell-space deltas. Y is
272 // multiplied by BISCUIT_CELL_ASPECT to compensate for the
273 // tall terminal cell — one row visually equals ~2 cols.
274 let dx_cells = (p.frac_x - fx) * bw;
275 let dy_cells = (p.frac_y - fy) * bh * BISCUIT_CELL_ASPECT;
276 dx_cells * dx_cells + dy_cells * dy_cells < min_sq
277 });
278 if !too_close {
279 return (fx, fy);
280 }
281 }
282 let fx = rng.random_range(SPAWN_INSET_X..=(1.0 - SPAWN_INSET_X));
283 let fy = rng.random_range(SPAWN_INSET_Y..=(1.0 - SPAWN_INSET_Y));
284 (fx, fy)
285}
286
287fn maybe_spawn_powerups(state: &mut GameState, geom: &SimGeometry) {
288 if geom.biscuit.width < 8 || geom.biscuit.height < 5 {
289 return;
290 }
291 let cells = (geom.biscuit.width, geom.biscuit.height);
292 // Each kind runs on its own clock. Cooldown is reset to a fresh
293 // exponential sample on every spawn (regardless of how many of the
294 // same kind are already on screen — the parallelism is the whole
295 // point of this refactor). `tick_powerups` already decremented the
296 // cooldown this tick, so a `> 0` test here is correct.
297 for kind in PowerupKind::ALL {
298 let i = kind as usize;
299 if state.powerup_cooldowns[i] > 0 {
300 continue;
301 }
302 spawn_powerup(state, kind, cells);
303 // Tree contribution: SpawnRateMul is a true spawn-rate
304 // multiplier — >1.0 means more frequent spawns, so the
305 // cooldown scales by its inverse.
306 let mul = state
307 .tree_aggregate
308 .powerup_spawn_mul
309 .get(i)
310 .copied()
311 .unwrap_or(1.0);
312 let base = powerup::next_cooldown(kind) as f64;
313 let cooldown = if mul > 0.0 { base / mul } else { base };
314 state.powerup_cooldowns[i] = cooldown.max(1.0) as u32;
315 }
316}
317
318/// Push a fresh powerup of `kind` onto `state.powerups`. Position is
319/// picked with the dispersion helper so back-to-back spawns don't land in
320/// the exact same cell. Cooldown management is the caller's responsibility
321/// (`maybe_spawn_powerups` resets the kind's clock; the dev cheats don't —
322/// pressing F8 twice in quick succession really does push two Lucky's, AND
323/// the natural Lucky cooldown keeps ticking down independently, so a dev
324/// spawn followed shortly by a natural spawn is expected and intentional).
325fn spawn_powerup(state: &mut GameState, kind: PowerupKind, biscuit_cells: (u16, u16)) {
326 // Defensive: every spawn site uses the kind's full lifetime. If a
327 // future caller passes a Powerup with `life_ticks: 0` directly,
328 // `tick_powerups` would still drop it on the next tick — but the
329 // marker would briefly render at near-zero life, hitting the
330 // alarm-mode shimmer immediately. Catch that misuse here.
331 let life_ticks = kind.lifetime_ticks();
332 debug_assert!(life_ticks > 0, "PowerupKind::lifetime_ticks must be > 0");
333 let (frac_x, frac_y) = pick_dispersed_frac(&state.powerups, biscuit_cells);
334 let spawn_id = state.mint_spawn_id();
335 state.powerups.push(Powerup {
336 kind,
337 spawn_id,
338 frac_x,
339 frac_y,
340 life_ticks,
341 });
342}
343
344/// Dev cheat: force-spawn a powerup of `kind`. Unlike `maybe_spawn_powerups`
345/// this does NOT reset the cooldown, so it doesn't disturb the natural
346/// rhythm — and it does NOT gate on slot occupancy (that's the whole
347/// point: pressing F8 twice produces two Lucky's). The biscuit-size
348/// guard mirrors the natural-spawn path so a tiny terminal can't drop a
349/// marker into a 0-width rect.
350fn force_spawn_powerup(state: &mut GameState, geom: &SimGeometry, kind: PowerupKind) {
351 if geom.biscuit.width < 8 || geom.biscuit.height < 5 {
352 return;
353 }
354 spawn_powerup(state, kind, (geom.biscuit.width, geom.biscuit.height));
355}
356
357#[cfg(test)]
358mod tests {
359 use super::*;
360 use crate::game::state::GameState;
361 use ratatui::layout::Rect;
362
363 fn geom_with_biscuit() -> SimGeometry {
364 SimGeometry {
365 biscuit: Rect::new(0, 0, 40, 20),
366 powerups_paused: false,
367 }
368 }
369
370 #[test]
371 fn force_spawn_pushes_to_vec_uncapped() {
372 // Pressing the same F-key twice in a row produces two on-screen
373 // powerups of that kind — no per-kind cap, no slot-occupancy
374 // displacement. This is the headline feature of the refactor.
375 let mut state = GameState::default();
376 let geom = geom_with_biscuit();
377 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
378 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
379 let lucky_count = state
380 .powerups
381 .iter()
382 .filter(|p| p.kind == PowerupKind::Lucky)
383 .count();
384 assert_eq!(lucky_count, 2);
385 // Distinct spawn ids — id reuse would defeat the per-instance
386 // hit-test.
387 let ids: Vec<u64> = state.powerups.iter().map(|p| p.spawn_id).collect();
388 assert_ne!(ids[0], ids[1]);
389 }
390
391 #[test]
392 fn force_spawn_mixes_kinds_freely() {
393 // All four kinds can coexist; no slot ever forces a one-per-kind cap.
394 let mut state = GameState::default();
395 let geom = geom_with_biscuit();
396 for kind in PowerupKind::ALL {
397 force_spawn_powerup(&mut state, &geom, kind);
398 }
399 assert_eq!(state.powerups.len(), 4);
400 for kind in PowerupKind::ALL {
401 assert!(state.powerups.iter().any(|p| p.kind == kind));
402 }
403 }
404
405 #[test]
406 fn spawn_dispersion_avoids_exact_overlap() {
407 // Two consecutive force-spawns on a fresh state must produce two
408 // distinct positions. Dispersion is best-effort; we assert the
409 // weaker but tractable property "distance between them is at
410 // least the dispersion threshold" most of the time. With only one
411 // existing entry the retry loop almost always finds a clean spot.
412 let mut state = GameState::default();
413 let geom = geom_with_biscuit();
414 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
415 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
416 let a = &state.powerups[0];
417 let b = &state.powerups[1];
418 let dx = a.frac_x - b.frac_x;
419 let dy = a.frac_y - b.frac_y;
420 let dist = (dx * dx + dy * dy).sqrt();
421 // Allow a generous floor: dispersion fall-through can produce a
422 // single near-overlap, but not zero.
423 assert!(dist > 0.0, "two spawns landed at the exact same point");
424 }
425
426 #[test]
427 fn spawn_dispersion_keeps_cell_distance_in_typical_layout() {
428 // Statistical: across 1000 fresh-state pair spawns on a normal
429 // 60×30 biscuit, the cell-space distance between the two
430 // markers should clear `POWERUP_MIN_CELL_DIST` the vast
431 // majority of the time (only the fall-through path violates,
432 // and that fires once per ~8 retries × dense neighborhood,
433 // which is rare for a single existing point on a 50-cell-wide
434 // free area). Asserting a 90%+ pass rate is generous.
435 let mut clear = 0;
436 let trials = 1000;
437 let geom = SimGeometry {
438 biscuit: Rect::new(0, 0, 60, 30),
439 powerups_paused: false,
440 };
441 for _ in 0..trials {
442 let mut state = GameState::default();
443 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
444 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
445 let a = &state.powerups[0];
446 let b = &state.powerups[1];
447 let dx_cells = (a.frac_x - b.frac_x) * geom.biscuit.width as f32;
448 let dy_cells = (a.frac_y - b.frac_y) * geom.biscuit.height as f32 * BISCUIT_CELL_ASPECT;
449 let cell_dist = (dx_cells * dx_cells + dy_cells * dy_cells).sqrt();
450 if cell_dist >= POWERUP_MIN_CELL_DIST {
451 clear += 1;
452 }
453 }
454 let ratio = clear as f32 / trials as f32;
455 assert!(
456 ratio > 0.90,
457 "expected ≥90% of pair spawns to clear cell distance; got {clear}/{trials} = {ratio}"
458 );
459 }
460
461 #[test]
462 fn spawn_dispersion_handles_tiny_biscuit_without_panic() {
463 // Edge case: at TINY zoom (16×8) the biscuit is barely large
464 // enough for the marker. The dispersion helper must not divide
465 // by zero or panic, even when the size guard in
466 // `maybe_spawn_powerups` would normally reject.
467 let mut state = GameState::default();
468 // Just above the size guard so force_spawn_powerup goes through.
469 let geom = SimGeometry {
470 biscuit: Rect::new(0, 0, 16, 8),
471 powerups_paused: false,
472 };
473 force_spawn_powerup(&mut state, &geom, PowerupKind::Lucky);
474 force_spawn_powerup(&mut state, &geom, PowerupKind::Frenzy);
475 assert_eq!(state.powerups.len(), 2);
476 }
477}