Add stopwatch command and execute if stopwatch

Adds the stopwatches store saved in data/minecraft/stopwatches.dat, the /stopwatch create, query, restart and remove commands, and the execute if stopwatch condition, with the parse tree and parse fixture updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-10 06:20:08 +02:00
parent 5a5bdf6a9b
commit abb21704dd
10 changed files with 234 additions and 0 deletions
@@ -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(),
@@ -41,6 +41,7 @@ pub struct Registries {
pub bossbars: Vec<String>,
pub predicates: Vec<String>,
pub schedules: Vec<String>,
pub stopwatches: Vec<String>,
pub recipes: Vec<String>,
pub sounds: Vec<String>,
pub damage_types: Vec<String>,
@@ -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(),
@@ -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);
@@ -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 <value> | fail | run <command>
let ret = d.literal(root, "return");
@@ -255,3 +256,32 @@ fn function(d: &mut Dispatcher, root: usize) {
d.executes(path, "function");
}
}
/// stopwatch create <id> | query <id> [<scale>] | restart <id> | remove <id>
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);
}
}
@@ -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),
@@ -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<bool> {
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<bool> {
let target = self.score_holder_names(c, "target", false)?;
let Some(Arg::Str(to)) = c.get("targetObjective").cloned() else {
@@ -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<i32> {
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<i32> {
let t = |key: &str, args: &[Text]| Text::translate(key, args);
@@ -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 ---------------------------------------------------
+1
View File
@@ -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;
+119
View File
@@ -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<Instant> = 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<String, Stopwatch>,
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<String> {
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<f64> {
self.watches
.get(id)
.map(|w| w.elapsed_ms(current_time()) as f64 / 1000.0)
}
}