diff --git a/crates/horizon-client/examples/command_parse_fixture.rs b/crates/horizon-client/examples/command_parse_fixture.rs index a909e8094..35c70655a 100644 --- a/crates/horizon-client/examples/command_parse_fixture.rs +++ b/crates/horizon-client/examples/command_parse_fixture.rs @@ -64,6 +64,7 @@ fn parser_id(ty: &ArgType) -> String { ArgType::Operation => "minecraft:operation".into(), ArgType::TeamColor => "minecraft:team_color".into(), ArgType::IntRange => "minecraft:int_range".into(), + ArgType::FloatRange => "minecraft:float_range".into(), ArgType::NbtPath => "minecraft:nbt_path".into(), ArgType::NbtTag => "minecraft:nbt_tag".into(), ArgType::Vec2 => "minecraft:vec2".into(), diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index c620d60ee..117e81e38 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -41,6 +41,7 @@ pub struct Registries { pub bossbars: Vec, pub predicates: Vec, pub schedules: Vec, + pub stopwatches: Vec, pub recipes: Vec, pub sounds: Vec, pub damage_types: Vec, @@ -156,6 +157,7 @@ pub enum ArgType { TeamColor, /// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`). IntRange, + FloatRange, /// NbtPathArgument (kept as text). NbtPath, /// NbtTagArgument: any SNBT value (kept as text). @@ -426,6 +428,7 @@ pub enum Arg { Anchor(bool), ScoreHolder(ScoreHolderArg), IntRange(IntRange), + DoubleRange(DoubleRange), } fn is_id_char(c: char) -> bool { @@ -1750,6 +1753,7 @@ impl ArgType { Arg::Str(name.to_owned()) } ArgType::IntRange => Arg::IntRange(range_int(reader)?), + ArgType::FloatRange => Arg::DoubleRange(range_double(reader)?), ArgType::Name(_) => Arg::Str(reader.read_string()?), ArgType::Vec2 | ArgType::ColumnPos => { let block = matches!(self, ArgType::ColumnPos); @@ -1923,6 +1927,7 @@ impl ArgType { "storages" => reg.storages.clone(), "bossbars" => reg.bossbars.clone(), "schedules" => reg.schedules.clone(), + "stopwatches" => reg.stopwatches.clone(), "recipes" => reg.recipes.clone(), "sounds" => reg.sounds.clone(), "damage_types" => reg.damage_types.clone(), diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-client/src/command/tree_execute.rs index f8b3ae484..0a30608aa 100644 --- a/crates/horizon-client/src/command/tree_execute.rs +++ b/crates/horizon-client/src/command/tree_execute.rs @@ -180,6 +180,11 @@ fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) { let p = d.argument(predicate, "predicate", ArgType::Id("predicates")); conditional(d, p, ex); + let stopwatch = d.literal(m, "stopwatch"); + let id = d.argument(stopwatch, "id", ArgType::Id("stopwatches")); + let range = d.argument(id, "range", ArgType::FloatRange); + conditional(d, range, ex); + let function = d.literal(m, "function"); let name = d.argument(function, "name", ArgType::Function); conditional(d, name, ex); diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs index 2494acb72..dc014fce8 100644 --- a/crates/horizon-client/src/command/tree_misc.rs +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -21,6 +21,7 @@ pub fn register(d: &mut Dispatcher, root: usize) { item(d, root); bossbar(d, root); function(d, root); + stopwatch(d, root); // return | fail | run let ret = d.literal(root, "return"); @@ -255,3 +256,32 @@ fn function(d: &mut Dispatcher, root: usize) { d.executes(path, "function"); } } + +/// stopwatch create | query [] | restart | remove +fn stopwatch(d: &mut Dispatcher, root: usize) { + let sw = d.literal(root, "stopwatch"); + d.requires(sw, GAMEMASTERS); + let create = d.literal(sw, "create"); + let id = d.argument(create, "id", ArgType::Id("none")); + d.executes(id, "stopwatch.create"); + let query = d.literal(sw, "query"); + let id = d.argument(query, "id", ArgType::Id("stopwatches")); + d.executes(id, "stopwatch.query"); + let scale = d.argument( + id, + "scale", + ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + ); + d.executes(scale, "stopwatch.query"); + for (name, command) in [ + ("restart", "stopwatch.restart"), + ("remove", "stopwatch.remove"), + ] { + let l = d.literal(sw, name); + let id = d.argument(l, "id", ArgType::Id("stopwatches")); + d.executes(id, command); + } +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index b74a65c04..e8974925c 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -546,6 +546,7 @@ impl Game<'_> { id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx), id if id.starts_with("loot.") => self.cmd_loot(id, ctx), "teammsg" => self.cmd_teammsg(ctx), + id if id.starts_with("stopwatch.") => self.cmd_stopwatch(id, ctx), id if id.starts_with("tick.") => self.cmd_tick(id, ctx), id if id.starts_with("random.") => self.cmd_random(id, ctx), "function" => self.cmd_function(ctx), diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index fc3041a2e..2fda44bfe 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -777,6 +777,9 @@ impl Game<'_> { if c.has("blocks") { return self.condition_blocks(c); } + if c.has("range") && c.has("id") { + return self.condition_stopwatch(c).map(flag); + } if c.has("predicate") { let Some(Arg::Resource(id)) = c.get("predicate").cloned() else { return Ok((false, 0)); @@ -785,6 +788,18 @@ impl Game<'_> { } Ok((false, 0)) } + fn condition_stopwatch(&mut self, c: &Context) -> R { + let Some(Arg::Resource(id)) = c.get("id").cloned() else { + return Ok(false); + }; + let Some(Arg::DoubleRange((lo, hi))) = c.get("range").cloned() else { + return Ok(false); + }; + let Some(t) = self.score.stopwatches.elapsed_seconds(&id) else { + return Err(err("commands.stopwatch.does_not_exist", &[&id])); + }; + Ok(lo.is_none_or(|l| t >= l) && hi.is_none_or(|h| t <= h)) + } fn condition_score(&mut self, c: &Context) -> R { let target = self.score_holder_names(c, "target", false)?; let Some(Arg::Str(to)) = c.get("targetObjective").cloned() else { diff --git a/crates/horizon-client/src/game/commands/misc.rs b/crates/horizon-client/src/game/commands/misc.rs index fbf2261a6..24a02272d 100644 --- a/crates/horizon-client/src/game/commands/misc.rs +++ b/crates/horizon-client/src/game/commands/misc.rs @@ -9,6 +9,59 @@ fn millis(nanos: u64) -> String { } impl Game<'_> { + /// `/stopwatch` (StopwatchCommand). + pub(super) fn cmd_stopwatch(&mut self, id: &str, ctx: &Context) -> R { + let Some(Arg::Resource(name)) = ctx.get("id").cloned() else { + return Ok(0); + }; + let arg = || Text::literal(name.clone()); + let missing = || err("commands.stopwatch.does_not_exist", &[&name]); + let sw = &mut self.score.stopwatches; + match id { + "stopwatch.create" => { + if !sw.create(&name) { + return Err(err("commands.stopwatch.already_exists", &[&name])); + } + self.feedback(Text::translate( + "commands.stopwatch.create.success", + &[arg()], + )); + Ok(1) + } + "stopwatch.query" => { + let scale = match ctx.get("scale") { + Some(Arg::Double(v)) => *v, + _ => 1.0, + }; + let t = sw.elapsed_seconds(&name).ok_or_else(missing)?; + self.feedback(Text::translate( + "commands.stopwatch.query", + &[arg(), Text::literal(format!("{t:?}"))], + )); + Ok((t * scale) as i32) + } + "stopwatch.restart" => { + if !sw.restart(&name) { + return Err(missing()); + } + self.feedback(Text::translate( + "commands.stopwatch.restart.success", + &[arg()], + )); + Ok(1) + } + _ => { + if !sw.remove(&name) { + return Err(missing()); + } + self.feedback(Text::translate( + "commands.stopwatch.remove.success", + &[arg()], + )); + Ok(1) + } + } + } /// `/tick` (TickCommand) over the game clock. pub(super) fn cmd_tick(&mut self, id: &str, ctx: &Context) -> R { let t = |key: &str, args: &[Text]| Text::translate(key, args); diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 6258b2283..cafacc00a 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -32,6 +32,7 @@ pub(super) struct ScoreState { pub board: Scoreboard, /// `/data ... storage`. pub storage: horizon_client::command_storage::CommandStorage, + pub stopwatches: horizon_client::stopwatches::Stopwatches, loaded: bool, recorded: Recorded, } @@ -62,6 +63,7 @@ impl Game<'_> { { self.border = horizon_client::worldborder::WorldBorder::unpack(data); } + self.score.stopwatches = horizon_client::stopwatches::Stopwatches::load(&self.world_root); self.sync_score_registries(); } pub(super) fn save_scoreboard(&mut self) { @@ -69,6 +71,7 @@ impl Game<'_> { return; } self.score.storage.save(&self.world_root); + self.score.stopwatches.save(&self.world_root); if self.border != horizon_client::worldborder::WorldBorder::default() { let _ = save::write_dat( &self.world_root.join("data/minecraft/world_border.dat"), @@ -99,6 +102,7 @@ impl Game<'_> { reg.teams = board.teams.iter().map(|t| t.name.clone()).collect(); reg.tracked = board.tracked(); reg.storages = self.score.storage.keys(); + reg.stopwatches = self.score.stopwatches.ids(); } // ---- score holders --------------------------------------------------- diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 09c1ecbb0..162687cc0 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -75,6 +75,7 @@ pub mod snbt; pub mod sprint; pub mod sprites; pub mod stations; +pub mod stopwatches; pub mod streaming; pub mod structure_blocks; pub mod subtitles; diff --git a/crates/horizon-client/src/stopwatches.rs b/crates/horizon-client/src/stopwatches.rs new file mode 100644 index 000000000..3d15d19a4 --- /dev/null +++ b/crates/horizon-client/src/stopwatches.rs @@ -0,0 +1,119 @@ +//! `Stopwatches`: the named wall-clock timers of `/stopwatch`, saved in +//! `data/minecraft/stopwatches.dat` as the elapsed milliseconds of each. +use crate::save; +use horizon_world::nbt::{Compound, JavaString, Tag}; +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, + sync::OnceLock, + time::Instant, +}; + +/// `Util.getMillis`, measured from the first call. +pub fn current_time() -> i64 { + static START: OnceLock = OnceLock::new(); + START.get_or_init(Instant::now).elapsed().as_millis() as i64 +} + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Stopwatch { + creation_time: i64, + accumulated: i64, +} +impl Stopwatch { + fn elapsed_ms(self, now: i64) -> i64 { + self.accumulated + (now - self.creation_time) + } +} + +#[derive(Clone, Debug, Default)] +pub struct Stopwatches { + watches: BTreeMap, + dirty: bool, +} +fn file(root: &Path) -> PathBuf { + root.join("data/minecraft/stopwatches.dat") +} +impl Stopwatches { + pub fn load(root: &Path) -> Self { + let mut s = Self::default(); + let now = current_time(); + if let Some(Tag::Compound(data)) = + save::read_dat(&file(root)).and_then(|t| t.get("data").cloned()) + && let Some(Tag::Compound(map)) = data.get(&JavaString::from("stopwatches")) + { + for (k, v) in map.iter() { + if let Tag::Long(ms) = v { + s.watches.insert( + k.to_string_lossy(), + Stopwatch { + creation_time: now, + accumulated: *ms, + }, + ); + } + } + } + s + } + pub fn save(&mut self, root: &Path) { + if !self.dirty && self.watches.is_empty() { + return; + } + self.dirty = false; + let now = current_time(); + let map: Compound = self + .watches + .iter() + .map(|(k, w)| (k.as_str().into(), Tag::Long(w.elapsed_ms(now)))) + .collect(); + let _ = save::write_dat( + &file(root), + Tag::compound([ + ("data", Tag::compound([("stopwatches", Tag::Compound(map))])), + ("DataVersion", Tag::Int(horizon_world::DATA_VERSION)), + ]), + ); + } + pub fn ids(&self) -> Vec { + self.watches.keys().cloned().collect() + } + /// `add`: false when the id exists. + pub fn create(&mut self, id: &str) -> bool { + if self.watches.contains_key(id) { + return false; + } + self.watches.insert( + id.to_owned(), + Stopwatch { + creation_time: current_time(), + accumulated: 0, + }, + ); + self.dirty = true; + true + } + /// `update` with a fresh stopwatch. + pub fn restart(&mut self, id: &str) -> bool { + let Some(w) = self.watches.get_mut(id) else { + return false; + }; + *w = Stopwatch { + creation_time: current_time(), + accumulated: 0, + }; + self.dirty = true; + true + } + pub fn remove(&mut self, id: &str) -> bool { + let removed = self.watches.remove(id).is_some(); + self.dirty |= removed; + removed + } + /// `Stopwatch.elapsedSeconds`. + pub fn elapsed_seconds(&self, id: &str) -> Option { + self.watches + .get(id) + .map(|w| w.elapsed_ms(current_time()) as f64 / 1000.0) + } +}