From d073783f55545af31d227b1a7ca3728cb58115f7 Mon Sep 17 00:00:00 2001 From: chexit Date: Sat, 21 Nov 2026 12:13:01 +0300 Subject: [PATCH] Mod-path CPU spans and a monotonic mod clock (#147 step 3.1) Host-side per-tick CPU spans of tick_mods (ground answers, world rays/ sections, snapshot, the WASM tick wall time, model prep, output), gated by HORIZON_MOD_CPU_PROFILE=1 like the fuel profile and bounded like FrameStats. Each record carries the game tick and the frame index it ran in, so the bench can join the spans with the frame/CPU/GPU trace; stats reports per-span percentiles and stats raw the per-tick records, cleared by stats reset/bench. game.monotonic-nanos (API level 32): a monotonic clock a mod reads to time its own phases, never simulation time. Additive to the game interface, so older mods still link; api_level and the generated reference updated. Co-Authored-By: Kimi Code --- crates/horizon-client/src/game/control.rs | 13 ++ crates/horizon-client/src/game/mods.rs | 142 ++++++++++++++++++++++ crates/horizon-mod-sdk/wit/horizon.wit | 4 + crates/horizon-mods/src/api_level.rs | 6 +- crates/horizon-mods/src/runtime.rs | 6 + docs/api/mods-reference.md | 1 + 6 files changed, 170 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index cec28c6ae..e7a1567ec 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -704,6 +704,15 @@ impl Game<'_> { let mut summary = self.frame_stats.summary(); // AirDef fork (#126): what the mod-model path did since the reset. summary["mod_models"] = self.mod_model_profile(); + // AirDef fork (#147 step 3.1): the mod tick path's host-side CPU + // spans (`HORIZON_MOD_CPU_PROFILE=1`); raw adds the per-tick records. + #[cfg(feature = "mods")] + if let Some(p) = self.mod_cpu_profile() { + summary["mod_cpu"] = p.summary(); + if words.contains(&"raw") { + summary["mod_cpu_ticks"] = p.raw(); + } + } // AirDef fork (#147): every recorded frame time, for the bench // driver's own percentiles and worst-frame counts. if words.contains(&"raw") { @@ -751,6 +760,8 @@ impl Game<'_> { if words.get(1) == Some(&"reset") { self.frame_stats.reset(); self.reset_mod_model_profile(); + #[cfg(feature = "mods")] + self.reset_mod_cpu_profile(); } Ok(Some(summary)) } @@ -772,6 +783,8 @@ impl Game<'_> { } self.frame_stats.reset(); self.reset_mod_model_profile(); + #[cfg(feature = "mods")] + self.reset_mod_cpu_profile(); self.pending_bench = Some(( Instant::now() + Duration::from_secs_f64(seconds), reply.clone(), diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 5fcf5a5c2..bb8521240 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -44,6 +44,103 @@ fn mod_fuel_profile_enabled() -> bool { *ON.get_or_init(|| std::env::var("HORIZON_MOD_FUEL_PROFILE").map_or(false, |v| v == "1")) } +/// Host-side CPU spans of the mod tick path for the bench driver (#147 step +/// 3.1): `HORIZON_MOD_CPU_PROFILE=1`. Off unless asked for, like the fuel +/// profile; the spans themselves cost a few clock reads a tick either way. +#[cfg(feature = "mods")] +fn mod_cpu_profile_enabled() -> bool { + static ON: std::sync::OnceLock = std::sync::OnceLock::new(); + *ON.get_or_init(|| std::env::var("HORIZON_MOD_CPU_PROFILE").map_or(false, |v| v == "1")) +} + +/// One game tick's mod-path CPU spans (#147 step 3.1), in milliseconds. `frame` +/// is the index the tick's frame takes in `FrameStats`' raw arrays, so the bench +/// can join these with the frame/CPU/GPU times; `tick` is the game tick number. +#[cfg(feature = "mods")] +pub(super) struct ModCpuTick { + pub tick: u64, + pub frame: u64, + pub ground_ms: f32, + pub world_ms: f32, + pub snapshot_ms: f32, + pub wasm_ms: f32, + pub models_ms: f32, + pub output_ms: f32, + pub total_ms: f32, +} + +/// The mod-path spans since the last reset, one record per game tick. Bounded +/// like `FrameStats`; cleared by `stats reset` and `bench`. +#[cfg(feature = "mods")] +#[derive(Default)] +pub(super) struct ModCpuProfile { + ticks: Vec, +} + +#[cfg(feature = "mods")] +impl ModCpuProfile { + /// About 54 minutes of ticks at 20 Hz; past it the oldest records are kept. + const LIMIT: usize = 1 << 16; + fn push(&mut self, t: ModCpuTick) { + if self.ticks.len() < Self::LIMIT { + self.ticks.push(t); + } + } + fn reset(&mut self) { + self.ticks.clear(); + } + /// Every recorded tick, in order, for `stats raw`. + pub(super) fn raw(&self) -> serde_json::Value { + self.ticks + .iter() + .map(|t| { + serde_json::json!({ + "tick": t.tick, + "frame": t.frame, + "ground_ms": t.ground_ms, + "world_ms": t.world_ms, + "snapshot_ms": t.snapshot_ms, + "wasm_ms": t.wasm_ms, + "models_ms": t.models_ms, + "output_ms": t.output_ms, + "total_ms": t.total_ms, + }) + }) + .collect::>() + .into() + } + /// Per-span percentiles over the recorded ticks, for `stats`. + pub(super) fn summary(&self) -> serde_json::Value { + let span = |get: fn(&ModCpuTick) -> f32| { + let mut v: Vec = self.ticks.iter().map(get).collect(); + v.sort_by(f32::total_cmp); + let n = v.len(); + if n == 0 { + return serde_json::Value::Null; + } + let pct = |p: f64| v[((n as f64 * p).ceil() as usize).clamp(1, n) - 1]; + let total: f64 = v.iter().map(|&m| f64::from(m)).sum(); + serde_json::json!({ + "avg_ms": total / n as f64, + "p50_ms": pct(0.5), + "p95_ms": pct(0.95), + "p99_ms": pct(0.99), + "max_ms": v[n - 1], + }) + }; + serde_json::json!({ + "ticks": self.ticks.len(), + "ground": span(|t| t.ground_ms), + "world": span(|t| t.world_ms), + "snapshot": span(|t| t.snapshot_ms), + "wasm": span(|t| t.wasm_ms), + "models": span(|t| t.models_ms), + "output": span(|t| t.output_ms), + "total": span(|t| t.total_ms), + }) + } +} + /// Chunks mods may have loaded at once, and how long one is held after its last request (20 s). #[cfg(feature = "mods")] const CHUNK_TICKETS: usize = 64; @@ -141,6 +238,10 @@ pub(super) struct ModsState { /// Playing at the last frame, for `mod_input_frame`. #[cfg(feature = "mods")] pub(super) playing: bool, + /// The mod tick path's CPU spans (#147 step 3.1), `HORIZON_MOD_CPU_PROFILE=1`; + /// none until profiling is asked for. + #[cfg(feature = "mods")] + pub(super) cpu_profile: Option, } /// The mappings `input.mapping` answers for, with the default key their @@ -746,8 +847,17 @@ impl Game<'_> { if mod_fuel_profile_enabled() && self.mods.mods.fuel_profile().is_none() { self.mods.mods.enable_fuel_profile(); } + // AirDef fork (#147 step 3.1): the host-side CPU spans of this path, + // per tick and attributed to the frame; off unless asked for. + if mod_cpu_profile_enabled() && self.mods.cpu_profile.is_none() { + self.mods.cpu_profile = Some(ModCpuProfile::default()); + } + let cpu_profile = self.mods.cpu_profile.is_some(); + let frame = self.frame_stats.frame_millis().len() as u64; + let t0 = Instant::now(); self.tick_mod_use(); self.take_mod_chunk_requests(); + let t1 = Instant::now(); for (i, columns) in self.mods.mods.take_ground_queries() { let ground: Vec<(i32, i32, i32)> = columns .into_iter() @@ -755,7 +865,9 @@ impl Game<'_> { .collect(); self.mods.mods.answer_ground(i, ground); } + let t2 = Instant::now(); self.answer_mod_world(); + let t3 = Instant::now(); let snapshot = self.mod_snapshot(); self.mods.mods.set_snapshot(snapshot); let registry = self.pack.assets.registry; @@ -773,11 +885,41 @@ impl Game<'_> { .set_source_generation(self.audio.mod_sources.epoch); self.mods.mods.set_acoustics(self.audio.acoustics.is_some()); self.mods.mods.set_acoustics_output_ready(self.audio.acoustics_output_ready()); + let t4 = Instant::now(); self.mods.mods.tick(self.ticks); + let t5 = Instant::now(); self.refresh_mod_trees(); self.update_mod_models(); + let t6 = Instant::now(); self.show_mod_output(); + let t7 = Instant::now(); self.sync_mod_sources(); + if cpu_profile { + let ms = |a: Instant, b: Instant| (b - a).as_secs_f32() * 1000.0; + self.mods.cpu_profile.as_mut().unwrap().push(ModCpuTick { + tick: self.ticks, + frame, + ground_ms: ms(t1, t2), + world_ms: ms(t2, t3), + snapshot_ms: ms(t3, t4), + wasm_ms: ms(t4, t5), + models_ms: ms(t5, t6), + output_ms: ms(t6, t7), + total_ms: ms(t0, Instant::now()), + }); + } + } + /// Clears the mod-path CPU spans (`stats reset`, `bench`); keeps profiling on. + #[cfg(feature = "mods")] + pub(super) fn reset_mod_cpu_profile(&mut self) { + if let Some(p) = &mut self.mods.cpu_profile { + p.reset(); + } + } + /// The mod-path CPU spans for the `stats` control command (#147 step 3.1). + #[cfg(feature = "mods")] + pub(super) fn mod_cpu_profile(&self) -> Option<&ModCpuProfile> { + self.mods.cpu_profile.as_ref() } /// `render.load-chunks` (API level 22): the chunks mods asked for become tickets held for /// `CHUNK_TICKET_TICKS`; `update_world` keeps them loaded as extra areas of the streaming, diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 8428f89a3..ada987fc7 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -73,6 +73,10 @@ interface game { /// distant terrain when LOD Distance is on), as of this tick. None when /// nothing is hit, and on the title screen. raycast: func(distance: f32) -> option; + /// Nanoseconds on a monotonic clock (AirDef fork, API level 32): for + /// timing a mod's own work, never simulation time. It only ever rises + /// while the game runs; a mod must not feed it into combat decisions. + monotonic-nanos: func() -> u64; } /// Capability `chat`: messages only the local player sees. diff --git a/crates/horizon-mods/src/api_level.rs b/crates/horizon-mods/src/api_level.rs index 91f5b12e9..95827b9e5 100644 --- a/crates/horizon-mods/src/api_level.rs +++ b/crates/horizon-mods/src/api_level.rs @@ -7,13 +7,13 @@ //! version's level so the launcher can tell before it installs. /// The newest level this Horizon serves. -pub const LEVEL: u32 = 31; +pub const LEVEL: u32 = 32; /// Every function the game offers mods, as `interface.function`, with its /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// function takes the next level and raises [`LEVEL`] (the `api_reference` /// test fails until it is listed here). -pub const FUNCTIONS: [(&str, u32); 98] = [ +pub const FUNCTIONS: [(&str, u32); 99] = [ ("log.write", 0), ("game.get-player", 0), ("game.get-clock", 0), @@ -128,6 +128,8 @@ pub const FUNCTIONS: [(&str, u32); 98] = [ ("render.camera-status", 30), // AirDef fork: a world point on the screen, through the last drawn frame's camera. ("render.project", 31), + // AirDef fork: a monotonic clock for a mod to time its own work (#147 step 3.1). + ("game.monotonic-nanos", 32), ]; /// What the game's program carries so the launcher can read its level diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index da298e0d1..225d45622 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -2263,6 +2263,12 @@ impl game::Host for State { // NaN compares false: no hit. (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) } + fn monotonic_nanos(&mut self) -> u64 { + // AirDef fork (#147 step 3.1): a clock for a mod to time its own work. + // One process-wide epoch; only ever rises, never simulation time. + static EPOCH: std::sync::OnceLock = std::sync::OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos() as u64 + } } impl browser::Host for State { fn set_items(&mut self, items: Vec) { diff --git a/docs/api/mods-reference.md b/docs/api/mods-reference.md index 31b8aa889..a73822830 100644 --- a/docs/api/mods-reference.md +++ b/docs/api/mods-reference.md @@ -128,6 +128,7 @@ A block along the player's view. | `world-id` | `func() -> option` | Which world is open (AirDef fork): `world:` for a saved world, `server:
` on a server; none on the title screen. Mods keep their state apart by it. | | `world-seed` | `func() -> option` | The open saved world's seed (AirDef fork, API level 25): with the folder name it tells a new world from an old one that had the same name. None on the title screen and on a server. | | `raycast` | `func(distance: f32) -> option` | The first block along the player's view (fluids pass), up to `distance` blocks (at most 1024; past the loaded chunks, across the distant terrain when LOD Distance is on), as of this tick. None when nothing is hit, and on the title screen. | +| `monotonic-nanos` | `func() -> u64` | Nanoseconds on a monotonic clock (AirDef fork, API level 32): for timing a mod's own work, never simulation time. It only ever rises while the game runs; a mod must not feed it into combat decisions. | ## `chat`