diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 9d93e6175..059aaf58b 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -57,6 +57,8 @@ enum Animate { drag: bool, }, Fire, + /// An active sculk sensor. + SculkSensor, } fn step(facing: &str) -> [i32; 3] { match facing { @@ -128,6 +130,11 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option) -> Animate { drag: prop("drag").as_deref() == Some("true"), }, "fire" | "soul_fire" => Animate::Fire, + "sculk_sensor" | "calibrated_sculk_sensor" + if prop("sculk_sensor_phase").as_deref() == Some("active") => + { + Animate::SculkSensor + } _ if name.ends_with("candle_cake") && lit => Animate::CandleCake, _ if (name == "candle" || name.ends_with("_candle")) && lit => { Animate::Candles(prop("candles").and_then(|c| c.parse().ok()).unwrap_or(1)) @@ -905,6 +912,35 @@ fn block_animate_tick( } } } + Animate::SculkSensor => { + // SculkSensorBlock.animateTick. + let r = engine.random(); + let direction = r.next_int_bound(6).unwrap_or(0); + // Direction.values(): down, up, north, south, west, east. + if direction >= 2 { + let step = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]][direction as usize - 2]; + let x = fx + + 0.5 + + if step[0] == 0 { + 0.5 - r.next_double() + } else { + f64::from(step[0]) * 0.6 + }; + let z = fz + + 0.5 + + if step[2] == 0 { + 0.5 - r.next_double() + } else { + f64::from(step[2]) * 0.6 + }; + let ya = f64::from(r.next_float() * 0.04); + engine.add( + &crate::particles::ParticleOptions::sculk_to_redstone(), + [x, fy + 0.25, z], + [0.0, ya, 0.0], + ); + } + } Animate::RespawnAnchor => { let r = engine.random(); if next_int(r, 100) == 0 { diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 929c5c0e2..bc6aaff78 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -26,6 +26,9 @@ struct Voice { step: f64, left: f32, right: f32, + /// The sound event and `SoundSource` index (what `/stopsound` matches). + event: Arc, + source: usize, } #[derive(Default)] struct Mixer { @@ -49,8 +52,25 @@ struct MusicTrack { /// Set by the decoder thread once the voice is in the mixer (or failed). ready: Arc, } +/// A sound the player could have heard (`SoundEventListener.onPlaySound`): +/// what the subtitle overlay needs. +#[derive(Clone, Debug, PartialEq)] +pub struct Heard { + /// The `subtitle` translation key of the sound event. + pub subtitle: String, + /// Where it played (None = relative to the listener, e.g. UI sounds). + pub at: Option<[f64; 3]>, + /// `SoundEngine.getRange`: infinite for relative and non-attenuated sounds. + pub range: f32, + pub looping: bool, +} pub struct Audio { _stream: Option, + /// `subtitle` keys of `sounds.json` events. + subtitles: HashMap, + /// Record `Heard` sounds (the subtitle overlay is listening). + pub record_heard: bool, + heard: Vec, mixer: Arc>, rate: u32, root: PathBuf, @@ -62,6 +82,8 @@ pub struct Audio { pub master: f32, music: Option, next_tracked: u64, + /// A `SoundSource` index the next sound plays on (`/playsound`). + source_override: Option, } fn decode(path: &Path) -> Option<(Vec, u32)> { use symphonia::core::{ @@ -108,6 +130,7 @@ fn decode(path: &Path) -> Option<(Vec, u32)> { impl Audio { pub fn new(root: &Path) -> Self { let mut events = HashMap::new(); + let mut subtitles = HashMap::new(); if let Ok(text) = fs::read(root.join("assets/minecraft/sounds.json")) && let Ok(Value::Object(map)) = serde_json::from_slice::(&text) { @@ -135,6 +158,9 @@ impl Audio { }, }) .collect::>(); + if let Some(key) = def["subtitle"].as_str() { + subtitles.insert(format!("minecraft:{name}"), key.to_owned()); + } events.insert(format!("minecraft:{name}"), variants); } } @@ -151,6 +177,9 @@ impl Audio { }; Self { _stream: stream, + subtitles, + record_heard: false, + heard: Vec::new(), mixer, rate, root: root.to_owned(), @@ -162,6 +191,7 @@ impl Audio { master: 1.0, music: None, next_tracked: 0, + source_override: None, } } fn open(mixer: Arc>) -> Result<(cpal::Stream, u32)> { @@ -279,12 +309,27 @@ impl Audio { } /// Play a sound event at a world position (None = non-positional UI sound). pub fn play(&mut self, event: &str, at: Option<[f64; 3]>, volume: f32, pitch: f32) { - if self._stream.is_none() { - return; - } let Some(variant) = self.resolve(event, 0) else { return; }; + if self.record_heard + && let Some(key) = self.subtitles.get(event) + { + let range = if at.is_some() { + variant.attenuation * volume.max(1.0) + } else { + f32::INFINITY + }; + self.heard.push(Heard { + subtitle: key.clone(), + at, + range, + looping: false, + }); + } + if self._stream.is_none() { + return; + } let file = variant.name.trim_start_matches("minecraft:").to_owned(); let entry = self.cache.entry(file.clone()).or_insert_with(|| { decode( @@ -297,9 +342,12 @@ impl Audio { let Some((samples, rate)) = entry.clone() else { return; }; + let source = self + .source_override + .unwrap_or_else(|| crate::settings::sound_source(event)); let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master - * crate::settings::event_volume(event); + * crate::settings::source_volume(source); let pitch = (pitch * variant.pitch).clamp(0.5, 2.0); let (mut left, mut right) = (volume, volume); if let Some(p) = at { @@ -333,6 +381,8 @@ impl Audio { step, left, right, + event: event.into(), + source, }); } } @@ -356,6 +406,7 @@ impl Audio { let step_scale = f64::from(variant.pitch.clamp(0.5, 2.0)) / f64::from(self.rate); let ready = Arc::new(std::sync::atomic::AtomicBool::new(false)); let (mixer, done) = (self.mixer.clone(), ready.clone()); + let music_event = event.to_owned(); std::thread::spawn(move || { if let Some((samples, rate)) = decode(&path) && let Ok(mut m) = mixer.lock() @@ -367,6 +418,8 @@ impl Audio { step: f64::from(rate) * step_scale, left: volume, right: volume, + event: music_event.as_str().into(), + source: 1, }); } done.store(true, std::sync::atomic::Ordering::Release); @@ -407,6 +460,50 @@ impl Audio { pub fn music_event(&self) -> Option<&str> { self.music.as_ref().map(|t| t.event.as_str()) } + /// Every sound event id (for command completion). + pub fn event_names(&self) -> Vec { + let mut v: Vec = self.events.keys().cloned().collect(); + v.sort(); + v + } + /// Play a sound on a given `SoundSource` index (`/playsound`). + pub fn play_on( + &mut self, + source: usize, + event: &str, + at: Option<[f64; 3]>, + volume: f32, + pitch: f32, + ) { + self.source_override = Some(source); + self.play(event, at, volume, pitch); + self.source_override = None; + } + /// `ClientboundStopSoundPacket`: stop the playing sounds of an event + /// and/or a source. + pub fn stop_sounds(&mut self, event: Option<&str>, source: Option) { + let matches = |v: &Voice| { + event.is_none_or(|e| &*v.event == e) && source.is_none_or(|s| v.source == s) + }; + if let Ok(mut m) = self.mixer.lock() { + m.voices.retain(|v| !matches(v)); + m.tracked.retain(|t| !matches(&t.voice)); + if m.music.as_ref().is_some_and(matches) { + m.music = None; + } + } + if self + .music + .as_ref() + .is_some_and(|t| event.is_none_or(|e| t.event == e) && source.is_none_or(|s| s == 1)) + { + self.music = None; + } + } + /// The sounds played since the last call, for the subtitle overlay. + pub fn take_heard(&mut self) -> Vec { + std::mem::take(&mut self.heard) + } /// `SoundManager.updateCategoryVolume(MUSIC, gain)`. pub fn set_music_gain(&mut self, gain: f32) { if let Ok(mut m) = self.mixer.lock() { @@ -416,8 +513,18 @@ impl Audio { /// Play a relative (non-positional) tickable sound instance the caller /// keeps a handle to: ambient loops (`looping`) and sub-sounds. pub fn play_tracked(&mut self, event: &str, volume: f32, looping: bool) -> Option { - self._stream.as_ref()?; let variant = self.resolve(event, 0)?; + if self.record_heard + && let Some(key) = self.subtitles.get(event) + { + self.heard.push(Heard { + subtitle: key.clone(), + at: None, + range: f32::INFINITY, + looping, + }); + } + self._stream.as_ref()?; let file = variant.name.trim_start_matches("minecraft:").to_owned(); let root = &self.root; let (samples, rate) = self @@ -443,6 +550,8 @@ impl Audio { step, left: gain, right: gain, + event: event.into(), + source: crate::settings::sound_source(event), }, looping, volume: volume.clamp(0.0, 1.0), diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs new file mode 100644 index 000000000..d2bc33fba --- /dev/null +++ b/crates/horizon-client/src/banner.rs @@ -0,0 +1,313 @@ +//! Banner patterns: the `banner_pattern` registry and its tags, the +//! `banner_patterns` layers carried by banner items, shields and placed +//! banners, and the loom rules of `LoomMenu` (selectable patterns, the +//! six-layer limit and the result stack). +use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use horizon_world::nbt::Tag; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path, sync::Arc}; + +/// `BannerPatternLayers.Layer`: a pattern id and the dye name it is painted in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct BannerLayer { + pub pattern: Arc, + pub color: Arc, +} +impl BannerLayer { + pub fn new(pattern: &str, color: &str) -> Self { + Self { + pattern: Arc::from(pattern), + color: Arc::from(color), + } + } +} + +/// Layers a loom may stack on a banner (`LoomMenu`'s `hasMaxPatterns`). +pub const MAX_LAYERS: usize = 6; + +/// One `banner_pattern` registry entry. +#[derive(Clone, Debug)] +pub struct Pattern { + pub id: Arc, + /// `asset_id` path, the texture under `entity/banner` and `entity/shield`. + pub asset: String, + pub translation_key: String, +} + +/// The pattern registry, its tags and the item components the loom reads. +#[derive(Default)] +pub struct Banners { + patterns: Vec, + /// `#minecraft:no_item_required`, in tag order. + no_item_required: Vec>, + /// Item -> `dye` component. + dyes: HashMap, Arc>, + /// Item -> `provides_banner_patterns`, in tag order. + provided: HashMap, Vec>>, +} + +fn read_tag(root: &Path, name: &str, depth: u32) -> Vec> { + if depth > 8 { + return Vec::new(); + } + let path = root.join(format!( + "data/minecraft/tags/banner_pattern/{}.json", + name.trim_start_matches("minecraft:") + )); + let Some(v) = fs::read(path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + return Vec::new(); + }; + let mut out = Vec::new(); + for value in v["values"].as_array().into_iter().flatten() { + let Some(s) = value.as_str().or_else(|| value["id"].as_str()) else { + continue; + }; + match s.strip_prefix('#') { + Some(tag) => out.extend(read_tag(root, tag, depth + 1)), + None => out.push(Arc::from(s)), + } + } + out +} + +impl Banners { + pub fn load(root: &Path) -> Self { + let mut banners = Self::default(); + let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/banner_pattern")) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + for path in files { + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Some(v) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + let asset = v["asset_id"] + .as_str() + .unwrap_or(stem) + .trim_start_matches("minecraft:") + .to_owned(); + banners.patterns.push(Pattern { + id: Arc::from(format!("minecraft:{stem}").as_str()), + asset, + translation_key: v["translation_key"].as_str().unwrap_or_default().to_owned(), + }); + } + banners.no_item_required = read_tag(root, "no_item_required", 0); + if let Some(raw) = fs::read(root.join("items.json")).ok().and_then(|b| { + serde_json::from_slice::>(&b).ok() + }) { + for (item, c) in raw { + let id: Arc = Arc::from(item.as_str()); + if let Some(dye) = c["minecraft:dye"].as_str() { + banners.dyes.insert(id.clone(), Arc::from(dye)); + } + match &c["minecraft:provides_banner_patterns"] { + Value::String(tag) if tag.starts_with('#') => { + banners.provided.insert(id, read_tag(root, &tag[1..], 0)); + } + Value::String(single) => { + banners + .provided + .insert(id, vec![Arc::from(single.as_str())]); + } + _ => {} + } + } + } + banners + } + pub fn pattern(&self, id: &str) -> Option<&Pattern> { + self.patterns.iter().find(|p| &*p.id == id) + } + /// `Sheets.getBannerSprite` texture name of a pattern. + pub fn banner_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/banner/{}", p.asset), + None => format!("entity/banner/{}", id.trim_start_matches("minecraft:")), + } + } + /// `Sheets.getShieldSprite` texture name of a pattern. + pub fn shield_texture(&self, id: &str) -> String { + match self.pattern(id) { + Some(p) => format!("entity/shield/{}", p.asset), + None => format!("entity/shield/{}", id.trim_start_matches("minecraft:")), + } + } + /// `BannerPatternLayers.Layer.description` translation key. + pub fn layer_key(&self, layer: &BannerLayer) -> String { + let base = self.pattern(&layer.pattern).map_or_else( + || { + format!( + "block.minecraft.banner.{}", + layer.pattern.trim_start_matches("minecraft:") + ) + }, + |p| p.translation_key.clone(), + ); + format!("{base}.{}", layer.color) + } + /// `LoomMenu.isDyeItem`: the dye colour of a loom dye. + pub fn loom_dye(&self, items: &Items, stack: &ItemStack) -> Option> { + let tagged = items + .item_tags + .get("minecraft:loom_dyes") + .is_some_and(|t| t.contains(&*stack.item)); + tagged + .then(|| self.dyes.get(&stack.item).cloned()) + .flatten() + } + /// `LoomMenu.isPatternItem`. + pub fn is_pattern_item(&self, items: &Items, stack: &ItemStack) -> bool { + items + .item_tags + .get("minecraft:loom_patterns") + .is_some_and(|t| t.contains(&*stack.item)) + && self.provided.contains_key(&stack.item) + } + /// `LoomMenu.getSelectablePatterns`. + pub fn selectable(&self, pattern_item: Option<&ItemStack>) -> Vec> { + match pattern_item { + None => self.no_item_required.clone(), + Some(stack) => self.provided.get(&stack.item).cloned().unwrap_or_default(), + } + } +} + +/// `BannerItem`: a banner's dye colour from its item id. +pub fn banner_color(item: &str) -> Option<&'static str> { + let name = item.strip_prefix("minecraft:")?.strip_suffix("_banner")?; + DYES.iter().map(|d| d.0).find(|d| *d == name) +} +/// `DyeColor.getTextureDiffuseColor` (RGB) by dye name. +pub fn dye_rgb(name: &str) -> u32 { + DYES.iter().find(|d| d.0 == name).map_or(0xFFFFFF, |d| d.1) +} +/// The layers of a banner or shield stack. +pub fn layers(stack: &ItemStack) -> &[BannerLayer] { + stack.data().map_or(&[], |d| &d.banner_patterns) +} +/// `LoomMenu.setupResultSlot`: one banner with the pattern added in the dye colour. +pub fn loom_result(banner: &ItemStack, dye: &str, pattern: &str) -> ItemStack { + let mut result = ItemStack { + count: 1, + ..banner.clone() + }; + result + .data_mut() + .banner_patterns + .push(BannerLayer::new(pattern, dye)); + result +} +/// Whether the banner already carries the loom's limit. +pub fn has_max_layers(banner: &ItemStack) -> bool { + layers(banner).len() >= MAX_LAYERS +} + +/// The `banner_patterns` NBT list of layers. +pub fn layers_to_nbt(layers: &[BannerLayer]) -> Tag { + Tag::List( + layers + .iter() + .map(|l| { + Tag::compound([ + ("pattern", Tag::String((&*l.pattern).into())), + ("color", Tag::String((&*l.color).into())), + ]) + }) + .collect(), + ) +} +pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { + let Some(Tag::List(list)) = tag else { + return Vec::new(); + }; + list.iter() + .filter_map(|e| { + let text = |k: &str| match e.get(k) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + }; + let pattern = text("pattern")?; + let color = text("color")?; + Some(BannerLayer::new( + &if pattern.contains(':') { + pattern + } else { + format!("minecraft:{pattern}") + }, + &color, + )) + }) + .collect() +} +/// Keeps `item_data` linked: the `StackData` fields the banner code reads. +pub fn set_layers(stack: &mut ItemStack, layers: Vec) { + let data: &mut item_data::StackData = stack.data_mut(); + data.banner_patterns = layers; + stack.tidy(); +} + +#[cfg(test)] +mod tests { + use super::*; + + fn banners() -> Banners { + let mut b = Banners { + no_item_required: vec![Arc::from("minecraft:stripe_top")], + ..Default::default() + }; + b.provided.insert( + Arc::from("minecraft:flower_banner_pattern"), + vec![Arc::from("minecraft:flower")], + ); + b + } + #[test] + fn selectable_follow_the_pattern_item() { + let b = banners(); + assert_eq!(b.selectable(None).len(), 1); + let item = ItemStack::new("minecraft:flower_banner_pattern", 1); + assert_eq!(&*b.selectable(Some(&item))[0], "minecraft:flower"); + } + #[test] + fn banner_colour_comes_from_the_item() { + assert_eq!( + banner_color("minecraft:light_gray_banner"), + Some("light_gray") + ); + assert_eq!(banner_color("minecraft:white_banner"), Some("white")); + assert_eq!(banner_color("minecraft:white_wool"), None); + } + #[test] + fn loom_adds_a_layer_up_to_the_limit() { + let mut banner = ItemStack::new("minecraft:white_banner", 3); + for i in 0..MAX_LAYERS { + assert!(!has_max_layers(&banner)); + banner = loom_result(&banner, "red", "minecraft:cross"); + assert_eq!(banner.count, 1); + assert_eq!(layers(&banner).len(), i + 1); + } + assert!(has_max_layers(&banner)); + } + #[test] + fn layers_round_trip_through_nbt() { + let l = vec![ + BannerLayer::new("minecraft:flower", "red"), + BannerLayer::new("minecraft:border", "black"), + ]; + assert_eq!(layers_from_nbt(Some(&layers_to_nbt(&l))), l); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 5869f6de0..8114542b0 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -700,6 +700,8 @@ pub struct Scene<'a> { pub lid: &'a dyn Fn([i32; 3]) -> f32, /// Sign block-entity data at a position. pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>, + /// Banner layers at a position: pattern texture and RGB tint, bottom first. + pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>, /// Font glyph cell and advance. pub glyph: &'a dyn Fn(char) -> Option<(Rect, f32)>, } @@ -773,6 +775,13 @@ impl BlockEntityRenderer { random: LegacyRandom::new(0x5EED_B00C), } } + /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). + pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { + Some(( + self.models.get("standing_banner")?, + self.models.get("standing_banner_flag")?, + )) + } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } @@ -993,10 +1002,16 @@ impl BlockEntityRenderer { draw_part(main, "root", m, &none, paint, out); draw_part(flag, "root", m, &wave, paint, out); } - // BannerRenderer.submitPatterns: the base pattern layer in the dye colour. + // BannerRenderer.submitPatterns: the base pattern layer in the dye colour, + // then up to 16 pattern layers in order. if let Some(paint) = paint("entity/banner/base", *color, packed) { draw_part(flag, "root", m, &wave, paint, out); } + for (texture, tint) in (scene.banner)(pos).iter().take(16) { + if let Some(paint) = paint(texture, *tint, packed) { + draw_part(flag, "root", m, &wave, paint, out); + } + } } Kind::Skull { kind, diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs new file mode 100644 index 000000000..9df17431c --- /dev/null +++ b/crates/horizon-client/src/bossbar.rs @@ -0,0 +1,182 @@ +//! Custom boss bars (`CustomBossEvents`): the `/bossbar` store, its saved +//! form (`data/minecraft/custom_boss_events.dat`) and how a bar is shown. +use crate::{ + scoreboard::{Comp, bracketed, comp_text, json_to_tag, literal, tag_to_json}, + text::{self, Style, Text}, +}; +use horizon_world::nbt::{Compound, Tag}; + +pub const COLORS: [&str; 7] = ["pink", "blue", "red", "green", "yellow", "purple", "white"]; +pub const STYLES: [&str; 5] = [ + "progress", + "notched_6", + "notched_10", + "notched_12", + "notched_20", +]; +/// `BossBarColor.getFormatting`. +pub fn color_rgb(color: &str) -> u32 { + let name = match color { + "pink" => "red", + "red" => "dark_red", + "purple" => "dark_purple", + other => other, + }; + text::named_color(name).unwrap_or(text::WHITE) +} + +#[derive(Clone, Debug, PartialEq)] +pub struct BossBar { + pub id: String, + pub name: Comp, + pub color: String, + pub style: String, + pub value: i32, + pub max: i32, + pub visible: bool, + /// Whether the (single) local player is in the bar's player set. + pub player: bool, +} +impl BossBar { + pub fn new(id: &str, name: Comp) -> Self { + Self { + id: id.to_owned(), + name, + color: "white".into(), + style: "progress".into(), + value: 0, + max: 100, + visible: false, + player: false, + } + } + /// `CustomBossEvent.getDisplayName`. + pub fn display_name(&self) -> Text { + let style = Style { + color: Some(color_rgb(&self.color)), + hover: Some(Box::new(Text::literal(self.id.clone()))), + ..Style::default() + }; + bracketed(comp_text(&self.name).with_style(&style)) + } + /// The filled fraction of the bar (`BossEvent.getProgress`). + pub fn progress(&self) -> f32 { + (self.value as f32 / self.max.max(1) as f32).clamp(0.0, 1.0) + } +} + +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BossBars { + pub bars: Vec, +} +impl BossBars { + pub fn get(&self, id: &str) -> Option<&BossBar> { + self.bars.iter().find(|b| b.id == id) + } + pub fn get_mut(&mut self, id: &str) -> Option<&mut BossBar> { + self.bars.iter_mut().find(|b| b.id == id) + } + pub fn add(&mut self, id: &str, name: Comp) -> bool { + if self.get(id).is_some() { + return false; + } + self.bars.push(BossBar::new(id, name)); + true + } + pub fn remove(&mut self, id: &str) { + self.bars.retain(|b| b.id != id); + } + pub fn ids(&self) -> Vec { + self.bars.iter().map(|b| b.id.clone()).collect() + } + /// The saved compound; the player's UUID stands for "the local player". + pub fn pack(&self, player: Option<[i32; 4]>) -> Tag { + let mut c = Compound::new(); + for b in &self.bars { + let mut e = vec![ + ("Name", json_to_tag(&b.name)), + ("Visible", Tag::Byte(i8::from(b.visible))), + ("Value", Tag::Int(b.value)), + ("Max", Tag::Int(b.max)), + ("Color", Tag::String(b.color.as_str().into())), + ("Overlay", Tag::String(b.style.as_str().into())), + ("DarkenScreen", Tag::Byte(0)), + ("PlayBossMusic", Tag::Byte(0)), + ("CreateWorldFog", Tag::Byte(0)), + ]; + let players = match (b.player, player) { + (true, Some(u)) => vec![Tag::IntArray(u.to_vec())], + _ => Vec::new(), + }; + e.push(("Players", Tag::List(players))); + c.insert(b.id.as_str().into(), Tag::compound(e)); + } + Tag::Compound(c) + } + pub fn unpack(data: &Tag, player: Option<[i32; 4]>) -> Self { + let mut bars = Vec::new(); + if let Tag::Compound(c) = data { + for (id, e) in c { + let get = |k: &str| e.get(k); + let text = |k: &str, d: &str| match get(k) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => d.to_owned(), + }; + let num = |k: &str, d: i32| match get(k) { + Some(Tag::Int(v)) => *v, + Some(Tag::Short(v)) => i32::from(*v), + Some(Tag::Byte(v)) => i32::from(*v), + _ => d, + }; + let in_players = match (get("Players"), player) { + (Some(Tag::List(l)), Some(u)) => l + .iter() + .any(|t| matches!(t, Tag::IntArray(a) if a.as_slice() == u)), + _ => false, + }; + bars.push(BossBar { + id: id.to_string_lossy(), + name: get("Name").map_or_else(|| literal(""), tag_to_json), + color: text("Color", "white"), + style: text("Overlay", "progress"), + value: num("Value", 0), + max: num("Max", 100), + visible: num("Visible", 0) != 0, + player: in_players, + }); + } + } + Self { bars } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bars_round_trip_and_show() { + let mut b = BossBars::default(); + assert!(b.add("test:x", literal("Hello"))); + assert!(!b.add("test:x", literal("Again"))); + let bar = b.get_mut("test:x").unwrap(); + bar.color = "pink".into(); + bar.style = "notched_10".into(); + bar.value = 25; + bar.max = 50; + bar.visible = true; + bar.player = true; + let uuid = Some([1, 2, 3, 4]); + let back = BossBars::unpack(&b.pack(uuid), uuid); + assert_eq!(back, b); + // Another player's UUID does not include the local player. + assert!(!BossBars::unpack(&b.pack(uuid), Some([9, 9, 9, 9])).bars[0].player); + let bar = b.get("test:x").unwrap(); + assert_eq!(bar.progress(), 0.5); + assert_eq!(bar.display_name().plain(), "chat.square_brackets"); + assert_eq!(color_rgb("pink"), text::RED); + assert_eq!(color_rgb("purple"), 0xAA00AA); + b.remove("test:x"); + assert!(b.bars.is_empty()); + } +} diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index e1332b159..d5e65655c 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -94,6 +94,8 @@ pub struct Chunk { /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. pub heights: Arc<[i16; 256]>, pub lit: bool, + /// Light read from a save with `isLightOn`: no light job is needed. + pub light_loaded: bool, /// Newly generated (not loaded from a save): eligible for generation-time spawns. pub fresh: bool, /// Block entities read from a save, moved into the world on arrival. @@ -120,6 +122,7 @@ impl Chunk { biomes: Arc::new(vec![0; 16 * (HEIGHT as usize / 4)]), heights: Arc::new([MIN_Y as i16; 256]), lit: false, + light_loaded: false, fresh: false, block_entities: Vec::new(), structure_refs: Vec::new(), diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 874fec656..835d0e009 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -1,24 +1,136 @@ //! Fixed-rate development simulation driver. Rendering consumes elapsed time; //! a per-frame work cap retains its backlog instead of dropping simulation time. +//! The rate, freezing, stepping and sprinting are what `/tick` controls +//! (`ServerTickRateManager`). use std::time::Duration; pub const TICK: Duration = Duration::from_millis(50); -#[derive(Default)] +/// Ticks one sprint frame may run. +const SPRINT_PER_FRAME: u32 = 40; +const SAMPLES: usize = 100; + pub struct FixedStep { pending: Duration, + /// Ticks per second (`tickrate`). + rate: f32, + frozen: bool, + /// Ticks the frozen world still runs (`/tick step`). + step: u32, + /// Ticks left in a sprint. + sprint: u32, + /// How long recent ticks took (nanoseconds), newest last. + samples: Vec, +} +impl Default for FixedStep { + fn default() -> Self { + Self { + pending: Duration::ZERO, + rate: 20.0, + frozen: false, + step: 0, + sprint: 0, + samples: Vec::new(), + } + } } impl FixedStep { + /// The length of one tick at the current rate. + pub fn tick_duration(&self) -> Duration { + Duration::from_secs_f64(1.0 / f64::from(self.rate.max(0.01))) + } pub fn advance(&mut self, elapsed: Duration) -> u32 { + if self.sprint > 0 { + let n = self.sprint.min(SPRINT_PER_FRAME); + self.sprint -= n; + self.pending = Duration::ZERO; + return n; + } self.pending += elapsed; - let steps = (self.pending.as_nanos() / TICK.as_nanos()).min(10) as u32; - self.pending -= TICK * steps; + let tick = self.tick_duration(); + let steps = (self.pending.as_nanos() / tick.as_nanos().max(1)).min(10) as u32; + self.pending -= tick * steps; steps } pub fn reset(&mut self) { self.pending = Duration::ZERO; } pub fn fraction(&self) -> f64 { - (self.pending.as_secs_f64() / TICK.as_secs_f64()).min(1.0) + (self.pending.as_secs_f64() / self.tick_duration().as_secs_f64()).min(1.0) + } + /// Whether the world ticks this time (`ServerTickRateManager.runsNormally` + /// or a pending step); called once per tick. + pub fn world_runs(&mut self) -> bool { + if !self.frozen { + return true; + } + if self.step > 0 { + self.step -= 1; + return true; + } + false + } + pub fn rate(&self) -> f32 { + self.rate + } + pub fn set_rate(&mut self, rate: f32) { + self.rate = rate.clamp(1.0, 10000.0); + } + pub fn frozen(&self) -> bool { + self.frozen + } + pub fn set_frozen(&mut self, frozen: bool) { + self.frozen = frozen; + if !frozen { + self.step = 0; + } + } + pub fn sprinting(&self) -> bool { + self.sprint > 0 + } + /// `requestGameToSprint`: true when a sprint was already running. + pub fn start_sprint(&mut self, ticks: u32) -> bool { + let was = self.sprint > 0; + self.sprint = ticks; + was + } + pub fn stop_sprint(&mut self) -> bool { + let was = self.sprint > 0; + self.sprint = 0; + was + } + pub fn stepping(&self) -> bool { + self.step > 0 + } + /// `stepGameIfPaused`: only works while frozen. + pub fn start_step(&mut self, ticks: u32) -> bool { + if !self.frozen { + return false; + } + self.step = ticks; + true + } + pub fn stop_step(&mut self) -> bool { + let was = self.step > 0; + self.step = 0; + was + } + pub fn record(&mut self, took: Duration) { + if self.samples.len() == SAMPLES { + self.samples.remove(0); + } + self.samples.push(took.as_nanos() as u64); + } + pub fn average_nanos(&self) -> u64 { + if self.samples.is_empty() { + return 0; + } + self.samples.iter().sum::() / self.samples.len() as u64 + } + /// The sorted tick times (p50, p95, p99 inputs) and their count. + pub fn sorted_samples(&self) -> Vec { + let mut v = self.samples.clone(); + v.sort_unstable(); + v } } @@ -60,4 +172,35 @@ mod tests { assert_eq!(clock.advance(Duration::from_millis(26)), 0); assert_eq!(clock.advance(Duration::from_millis(24)), 1); } + #[test] + fn rate_changes_the_tick_length() { + let mut clock = FixedStep::default(); + clock.set_rate(40.0); + assert_eq!(clock.advance(Duration::from_millis(100)), 4); + clock.set_rate(5.0); + assert_eq!(clock.advance(Duration::from_millis(400)), 2); + clock.set_rate(1.0e9); + assert_eq!(clock.rate(), 10000.0); + } + #[test] + fn freeze_step_and_sprint() { + let mut clock = FixedStep::default(); + assert!(clock.world_runs()); + assert!(!clock.start_step(3), "stepping needs a frozen game"); + clock.set_frozen(true); + assert!(!clock.world_runs()); + assert!(clock.start_step(2)); + assert!(clock.world_runs() && clock.world_runs() && !clock.world_runs()); + assert!(clock.start_step(5) && clock.stop_step() && !clock.stop_step()); + clock.set_frozen(false); + assert!(!clock.start_sprint(100)); + assert!(clock.sprinting()); + assert_eq!(clock.advance(Duration::ZERO), SPRINT_PER_FRAME); + assert!(clock.stop_sprint() && !clock.sprinting()); + for ns in [3, 1, 2] { + clock.record(Duration::from_nanos(ns)); + } + assert_eq!(clock.average_nanos(), 2); + assert_eq!(clock.sorted_samples(), vec![1, 2, 3]); + } } diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index bfe79244d..c92c44a33 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -29,6 +29,28 @@ pub struct Registries { /// Game rule name -> integer-valued. pub game_rules: Vec<(String, bool)>, pub players: Vec, + /// Scoreboard objective names, team names and tracked score holders. + pub objectives: Vec, + pub teams: Vec, + pub tracked: Vec, + /// Loaded datapack functions (`ns:path`) and function tags (`ns:path`). + pub functions: Vec, + /// `/data ... storage` ids. + pub storages: Vec, + /// Boss bar ids and datapack predicate ids. + pub bossbars: Vec, + pub predicates: Vec, + pub schedules: Vec, + pub recipes: Vec, + pub sounds: Vec, + pub damage_types: Vec, + pub attributes: Vec, + pub loot_tables: Vec, + pub templates: Vec, + pub random_sequences: Vec, + pub datapacks_enabled: Vec, + pub datapacks_disabled: Vec, + pub function_tags: Vec, /// The block the source is looking at (relevant coordinates). pub target_block: Option<[i32; 3]>, } @@ -116,7 +138,93 @@ pub enum ArgType { Component, /// CompoundTagArgument (kept as SNBT text). Nbt, + /// ScoreHolderArgument. + ScoreHolder { + multiple: bool, + }, + /// ObjectiveArgument (checked when the command runs). + Objective, + /// TeamArgument (checked when the command runs). + Team, + /// ObjectiveCriteriaArgument. + Criteria, + /// ScoreboardSlotArgument. + ScoreboardSlot, + /// OperationArgument. + Operation, + /// TeamColorArgument. + TeamColor, + /// RangeArgument.Ints (`1`, `1..`, `..5`, `1..5`). + IntRange, + /// NbtPathArgument (kept as text). + NbtPath, + /// NbtTagArgument: any SNBT value (kept as text). + NbtTag, + /// Vec2Argument: `x z` with `~` relative parts. + Vec2, + /// ColumnPosArgument: block `x z`. + ColumnPos, + /// ParticleArgument: a particle id and its options (kept as text). + Particle, + /// One of a fixed set of words. + Enum(&'static [&'static str]), + /// A (possibly quoted) name suggested from a registry list. + Name(&'static str), + /// FunctionArgument: `ns:path`, or `#ns:path` for a function tag. + Function, + /// SlotsArgument: a slot name or a wildcard group (`container.*`). + Slots, + /// SlotArgument: one slot (`container.5`, `weapon.mainhand`). + Slot, } + +/// Every slot name a command can address (`SlotRanges`), without wildcards. +pub fn slot_names() -> Vec { + let mut v: Vec = Vec::new(); + let mut range = |prefix: &str, n: usize| { + for i in 0..n { + v.push(format!("{prefix}.{i}")); + } + }; + range("container", 54); + range("hotbar", 9); + range("inventory", 27); + range("enderchest", 27); + range("villager", 8); + range("horse", 15); + range("player.crafting", 4); + for name in [ + "weapon", + "weapon.mainhand", + "weapon.offhand", + "armor.head", + "armor.chest", + "armor.legs", + "armor.feet", + "armor.body", + "saddle", + "horse.saddle", + "horse.chest", + "player.cursor", + "contents", + ] { + v.push(name.to_owned()); + } + v +} +/// The wildcard groups of `slot_names` (`container.*`, `armor.*`, ...). +pub const SLOT_GROUPS: [&str; 10] = [ + "container.*", + "hotbar.*", + "inventory.*", + "enderchest.*", + "villager.*", + "horse.*", + "player.crafting.*", + "armor.*", + "weapon.*", + "player.*", +]; pub fn integer(min: i32) -> ArgType { ArgType::Integer { min, max: i32::MAX } } @@ -227,6 +335,29 @@ pub struct Selector { pub y_rotation: Option, pub pos: [Option; 3], pub delta: [Option; 3], + /// `scores={objective=range,...}`. + pub scores: Vec<(String, IntRange)>, + /// `team=` (an empty name matches entities without a team). + pub teams: Vec<(String, bool)>, + /// `nbt=` compounds (SNBT text). + pub nbt: Vec<(String, bool)>, + /// `advancements={id=true|{criterion=true}}`. + pub advancements: Vec<(String, AdvCondition)>, + /// `predicate=` ids. + pub predicates: Vec<(String, bool)>, +} +/// An `advancements=` entry: all done or not, or per-criterion states. +#[derive(Clone, Debug, PartialEq)] +pub enum AdvCondition { + Done(bool), + Criteria(Vec<(String, bool)>), +} +/// A `ScoreHolderArgument` value. +#[derive(Clone, Debug, PartialEq)] +pub enum ScoreHolderArg { + Wildcard, + Name(String), + Selector(Selector), } impl Selector { pub fn is_self(&self) -> bool { @@ -293,6 +424,8 @@ pub enum Arg { GameMode(GameMode), /// `eyes` (true) or `feet`. Anchor(bool), + ScoreHolder(ScoreHolderArg), + IntRange(IntRange), } fn is_id_char(c: char) -> bool { @@ -563,6 +696,7 @@ fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries) { } } +pub const OPERATIONS: [&str; 9] = ["=", "+=", "-=", "*=", "/=", "%=", "<", ">", "><"]; const SELECTORS: [(&str, &str); 6] = [ ("@a", "argument.entity.selector.allPlayers"), ("@e", "argument.entity.selector.allEntities"), @@ -571,7 +705,7 @@ const SELECTORS: [(&str, &str); 6] = [ ("@r", "argument.entity.selector.randomPlayer"), ("@s", "argument.entity.selector.self"), ]; -const OPTIONS: [&str; 16] = [ +const OPTIONS: [&str; 21] = [ "name", "distance", "level", @@ -588,7 +722,22 @@ const OPTIONS: [&str; 16] = [ "gamemode", "tag", "type", + "scores", + "team", + "nbt", + "advancements", + "predicate", ]; +/// StringReader.expect. +fn expect_symbol(reader: &mut Reader, c: char) -> CmdResult<()> { + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == c { + reader.skip(); + Ok(()) + } else { + Err(CommandError::tr_at("parsing.expected", &[&c], reader)) + } +} fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult { let start = reader.cursor; if !(reader.can_read() && reader.peek() == '@') { @@ -791,6 +940,81 @@ fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult let v = reader.read_unquoted_string().to_owned(); s.tags.push((v, neg)); } + "team" => { + let neg = negated(reader); + let v = reader.read_unquoted_string().to_owned(); + s.teams.push((v, neg)); + } + "nbt" => { + let neg = negated(reader); + if !reader.can_read() || reader.peek() != '{' { + return Err(CommandError::tr_at( + "argument.nbt.expected.compound", + &[], + reader, + )); + } + s.nbt.push((read_braced(reader, '{', '}')?, neg)); + } + "predicate" => { + let neg = negated(reader); + s.predicates.push((read_id(reader)?, neg)); + } + "scores" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let name = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + let range = range_int(reader)?; + s.scores.push((name, range)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + } + "advancements" => { + expect_symbol(reader, '{')?; + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let id = read_id(reader)?; + expect_symbol(reader, '=')?; + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == '{' { + reader.skip(); + reader.skip_whitespace(); + let mut criteria = Vec::new(); + while reader.can_read() && reader.peek() != '}' { + reader.skip_whitespace(); + let c = reader.read_unquoted_string().to_owned(); + expect_symbol(reader, '=')?; + criteria.push((c, reader.read_boolean()?)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.advancements.push((id, AdvCondition::Criteria(criteria))); + } else { + s.advancements + .push((id, AdvCondition::Done(reader.read_boolean()?))); + } + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + } + reader.skip_whitespace(); + } + expect_symbol(reader, '}')?; + s.include_entities = false; + } "type" => { let neg = negated(reader); let at = reader.cursor; @@ -1410,7 +1634,11 @@ impl ArgType { reader, )); } - Arg::Str(read_braced(reader, '{', '}')?) + let text = read_braced(reader, '{', '}')?; + if let Err(e) = horizon_world::nbt::parse_snbt(&text) { + return Err(CommandError::at(crate::text::Text::literal(e), reader)); + } + Arg::Str(text) } ArgType::Component => { let (value, used) = @@ -1436,6 +1664,205 @@ impl ArgType { } Arg::Str(axes) } + ArgType::ScoreHolder { multiple } => { + if reader.can_read() && reader.peek() == '@' { + let sel = parse_selector(reader, reg)?; + if !*multiple && sel.limit > 1 { + reader.cursor = start; + return Err(CommandError::tr_at("argument.entity.toomany", &[], reader)); + } + Arg::ScoreHolder(ScoreHolderArg::Selector(sel)) + } else { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let text = &reader.string[start..reader.cursor]; + if text == "*" { + Arg::ScoreHolder(ScoreHolderArg::Wildcard) + } else { + Arg::ScoreHolder(ScoreHolderArg::Name(text.to_owned())) + } + } + } + ArgType::Objective | ArgType::Team => { + Arg::Str(reader.read_unquoted_string().to_owned()) + } + ArgType::Criteria => { + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let id = &reader.string[start..reader.cursor]; + if !crate::scoreboard::criteria_exists(id, reg) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.criteria.invalid", + &[&id], + reader, + )); + } + Arg::Str(id.to_owned()) + } + ArgType::ScoreboardSlot => { + let name = reader.read_unquoted_string(); + if !crate::scoreboard::display_slot_valid(name) { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.scoreboardDisplaySlot.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::Operation => { + if !reader.can_read() { + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + } + let op = &reader.string[start..reader.cursor]; + if !OPERATIONS.contains(&op) { + reader.cursor = start; + return Err(CommandError::tr_at( + "arguments.operation.invalid", + &[], + reader, + )); + } + Arg::Str(op.to_owned()) + } + ArgType::TeamColor => { + let name = reader.read_unquoted_string(); + if crate::scoreboard::team_color_rgb(name).is_none() { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.color.invalid", + &[&name], + reader, + )); + } + Arg::Str(name.to_owned()) + } + ArgType::IntRange => Arg::IntRange(range_int(reader)?), + ArgType::Name(_) => Arg::Str(reader.read_string()?), + ArgType::Vec2 | ArgType::ColumnPos => { + let block = matches!(self, ArgType::ColumnPos); + let one = |reader: &mut Reader| { + if block { + parse_coord_int(reader) + } else { + parse_coord_double(reader, false) + } + }; + let x = one(reader)?; + if !reader.can_read() || reader.peek() != ' ' { + reader.cursor = start; + return Err(CommandError::tr_at( + "argument.pos2d.incomplete", + &[], + reader, + )); + } + reader.skip(); + let z = one(reader)?; + Arg::Coords(Coordinates::World([ + x, + Coord { + relative: true, + value: 0.0, + }, + z, + ])) + } + ArgType::Particle => { + let id = read_id(reader)?; + let name = id.trim_start_matches("minecraft:").to_owned(); + if crate::particles::ParticleType::from_name(&id).is_none() { + reader.cursor = start; + return Err(CommandError::tr_at("particle.notFound", &[&id], reader)); + } + let floats = |reader: &mut Reader, n: usize| -> CmdResult<()> { + for _ in 0..n { + reader.expect(' ')?; + reader.read_float()?; + } + Ok(()) + }; + match name.as_str() { + "dust" => floats(reader, 4)?, + "dust_color_transition" => floats(reader, 7)?, + "entity_effect" | "tinted_leaves" | "flash" => floats(reader, 4)?, + "sculk_charge" => floats(reader, 1)?, + "shriek" => { + reader.expect(' ')?; + reader.read_int()?; + } + "block" | "block_marker" | "falling_dust" | "dust_pillar" | "block_crumble" => { + reader.expect(' ')?; + parse_block(reader, reg, false)?; + } + "item" => { + reader.expect(' ')?; + parse_item(reader, reg, false)?; + } + _ => {} + } + Arg::Str(reader.string[start..reader.cursor].to_owned()) + } + ArgType::Enum(words) => { + let word = reader.read_unquoted_string(); + if !words.contains(&word) { + reader.cursor = start; + return Err(CommandError::tr_at("command.unknown.argument", &[], reader)); + } + Arg::Str(word.to_owned()) + } + ArgType::Function => { + let tag = reader.can_read() && reader.peek() == '#'; + if tag { + reader.skip(); + } + let id = read_id(reader)?; + Arg::Resource(if tag { format!("#{id}") } else { id }) + } + ArgType::Slots | ArgType::Slot => { + let mut end = reader.cursor; + while reader.can_read() && reader.peek() != ' ' { + reader.skip(); + end = reader.cursor; + } + let word = &reader.string[start..end]; + let known = slot_names().iter().any(|n| n == word) + || (matches!(self, ArgType::Slots) && SLOT_GROUPS.contains(&word)); + if !known { + reader.cursor = start; + return Err(CommandError::tr_at("slot.unknown", &[&word], reader)); + } + Arg::Str(word.to_owned()) + } + ArgType::NbtPath => { + let (path, used) = crate::nbt_path::NbtPath::parse_prefix(reader.remaining()) + .map_err(|e| { + reader.cursor += e.cursor.min(reader.remaining().len()); + let args: Vec<&dyn std::fmt::Display> = + e.args.iter().map(|a| a as &dyn std::fmt::Display).collect(); + CommandError::tr_at(e.key, &args, reader) + })?; + reader.cursor += used; + Arg::Str(path.as_str().to_owned()) + } + ArgType::NbtTag => { + let (_, used) = horizon_world::nbt::parse_snbt(reader.remaining()) + .map_err(|e| CommandError::at(crate::text::Text::literal(e), reader))?; + let text = reader.remaining()[..used].to_owned(); + reader.cursor += used; + Arg::Str(text) + } ArgType::Anchor => { let name = reader.read_unquoted_string(); match name { @@ -1492,6 +1919,17 @@ impl ArgType { } ArgType::Id(list) => { let values = match *list { + "storages" => reg.storages.clone(), + "bossbars" => reg.bossbars.clone(), + "schedules" => reg.schedules.clone(), + "recipes" => reg.recipes.clone(), + "sounds" => reg.sounds.clone(), + "damage_types" => reg.damage_types.clone(), + "attributes" => reg.attributes.clone(), + "loot_tables" => reg.loot_tables.clone(), + "templates" => reg.templates.clone(), + "random_sequences" => reg.random_sequences.clone(), + "predicates" => reg.predicates.clone(), "time_markers" => reg.time_markers.clone(), "advancements" => reg.advancements.clone(), _ => Vec::new(), @@ -1511,6 +1949,79 @@ impl ArgType { } } ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)), + ArgType::ScoreHolder { .. } => { + suggest_selector(builder, reg); + let names: Vec = reg + .players + .iter() + .chain(reg.tracked.iter()) + .cloned() + .collect(); + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::Objective => { + builder.suggest_matching(reg.objectives.iter().map(String::as_str)) + } + ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), + ArgType::Criteria => { + let mut ids: Vec = crate::scoreboard::CUSTOM_CRITERIA + .iter() + .map(|s| (*s).to_owned()) + .collect(); + for c in crate::scoreboard::team_colors() { + ids.push(format!("teamkill.{c}")); + ids.push(format!("killedByTeam.{c}")); + } + let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); + ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); + for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { + ids.extend(reg.items.iter().map(|i| stat(ty, i))); + } + for ty in ["killed", "killed_by"] { + ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); + } + ids.extend( + crate::scoreboard::CUSTOM_STATS + .iter() + .map(|c| stat("custom", &format!("minecraft:{c}"))), + ); + builder.suggest_matching(ids.iter().map(String::as_str)); + } + ArgType::ScoreboardSlot => { + let slots = crate::scoreboard::display_slots(); + builder.suggest_matching(slots.iter().map(String::as_str)); + } + ArgType::Operation => builder.suggest_matching(OPERATIONS), + ArgType::Enum(words) => builder.suggest_matching(words.iter().copied()), + ArgType::Particle => { + let names: Vec = crate::particles::ParticleType::ALL + .iter() + .map(|t| format!("minecraft:{}", t.name())) + .collect(); + suggest_resources(builder, &names, ""); + } + ArgType::Vec2 | ArgType::ColumnPos => builder.suggest_matching(["~", "~ ~"]), + ArgType::Name(list) => { + let names = match *list { + "datapacks_enabled" => reg.datapacks_enabled.clone(), + _ => reg.datapacks_disabled.clone(), + }; + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::Function => { + let functions = reg.functions.clone(); + suggest_resources(builder, &functions, ""); + let tags = reg.function_tags.clone(); + suggest_resources(builder, &tags, "#"); + } + ArgType::Slots | ArgType::Slot => { + let mut names = slot_names(); + if matches!(self, ArgType::Slots) { + names.extend(SLOT_GROUPS.iter().map(|s| (*s).to_owned())); + } + builder.suggest_matching(names.iter().map(String::as_str)); + } + ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Swizzle | ArgType::Component => {} ArgType::Message => { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 7e8090d6b..d5b40ab71 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -4,6 +4,11 @@ //! usage text and the vanilla error messages. Argument types live in //! [`args`]; the vanilla command tree in [`vanilla`]. pub mod args; +pub mod tree_data; +pub mod tree_execute; +pub mod tree_misc; +pub mod tree_scoreboard; +pub mod tree_world; pub mod vanilla; use crate::text::Text; diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs index 7d1a4cda1..c7fe6b1fa 100644 --- a/crates/horizon-client/src/command/tests.rs +++ b/crates/horizon-client/src/command/tests.rs @@ -215,3 +215,262 @@ fn local_coordinates_follow_view() { ]); assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]); } + +#[test] +fn data_and_tag_commands_parse() { + let (id, args) = run("data get entity @s Pos 2.5").unwrap(); + assert_eq!(id, "data.get"); + assert_eq!(args, ["target", "path", "scale"]); + assert_eq!(run("data get block ~ ~ ~ Items[0]").unwrap().0, "data.get"); + assert_eq!(run("data get storage my:store").unwrap().0, "data.get"); + assert_eq!(run("data merge storage a:b {x:1}").unwrap().0, "data.merge"); + assert_eq!( + run("data remove entity @s foo.bar[1]").unwrap().0, + "data.remove" + ); + let (id, args) = run("data modify storage a:b x.y insert 2 from entity @s Pos[0]").unwrap(); + assert_eq!(id, "data.modify"); + assert_eq!( + args, + ["target", "targetPath", "index", "source", "sourcePath"] + ); + assert_eq!( + run("data modify block 1 2 3 Text1 set string storage a:b x 1 3") + .unwrap() + .0, + "data.modify" + ); + assert_eq!( + run("data modify storage a:b l append value [1,2]") + .unwrap() + .0, + "data.modify" + ); + assert!(run("data modify storage a:b l explode value 1").is_err()); + assert!(run("data get storage a:b {broken").is_err()); + assert!(run("data merge storage a:b 5").is_err()); + assert_eq!(run("tag @e[tag=!x] add foo").unwrap().0, "tag.add"); + assert_eq!(run("tag @s list").unwrap().0, "tag.list"); + // Selector options added for scoreboards and NBT. + assert!(run("kill @e[scores={a=1..},team=red,nbt={x:1b},tag=t]").is_ok()); + assert!(run("kill @e[scores={a=1..]").is_err()); +} + +#[test] +fn smoke_commands_parse() { + for line in [ + "tag @s list", + "random value 1..6", + "team list", + "data get storage a:b", + "scoreboard objectives list", + "function test:a", + "execute store result score #r t run function test:a", + "schedule function test:a 20t", + "datapack list", + "bossbar list", + "item replace entity @s hotbar.0 with minecraft:stone 3", + ] { + assert!(run(line).is_ok(), "{line}: {:?}", run(line).err()); + } +} + +#[test] +fn execute_tree_covers_vanilla_forms() { + for line in [ + "execute as @a at @s run say hi", + "execute store result score @s x run data get entity @s Health", + "execute store success bossbar minecraft:b value run say hi", + "execute store result storage a:b out int 1.5 run time query gametime", + "execute store result entity @s Air short 1 run say hi", + "execute if score @s a = @s b run say hi", + "execute unless score @s a matches ..5 run say hi", + "execute if block ~ ~ ~ minecraft:stone", + "execute if blocks 0 0 0 1 1 1 5 5 5 masked run say hi", + "execute if biome ~ ~ ~ minecraft:plains", + "execute if loaded ~ ~ ~", + "execute if dimension minecraft:overworld", + "execute if data entity @s Inventory[0]", + "execute unless data storage a:b x run say hi", + "execute if predicate a:b", + "execute if function a:b run say hi", + "execute if items entity @s hotbar.* minecraft:stone", + "execute if slots block 0 0 0 container.*", + "execute positioned over world_surface run say hi", + "execute summon minecraft:pig run say hi", + "execute on vehicle run say hi", + "execute on passengers as @s run say hi", + "execute rotated as @s facing entity @s eyes align xyz anchored feet in minecraft:overworld run say hi", + ] { + assert!(run(line).is_ok(), "{line}: {:?}", run(line).err()); + } + assert!(run("execute positioned over nothing run say hi").is_err()); + assert!(run("execute on nobody run say hi").is_err()); + assert!(run("execute store result score @s").is_err()); +} + +#[test] +fn function_and_misc_trees() { + assert_eq!(run("function a:b").unwrap().0, "function"); + assert_eq!(run("function #a:tag {x:1}").unwrap().0, "function"); + assert_eq!( + run("function a:b with storage c:d path.x").unwrap().0, + "function" + ); + assert_eq!(run("return 5").unwrap().0, "return.value"); + assert_eq!(run("return fail").unwrap().0, "return.fail"); + assert_eq!(run("return run say hi").unwrap().0, "say"); + assert_eq!( + run("schedule function a:b 5s append").unwrap().0, + "schedule.function" + ); + assert_eq!(run("schedule clear a:b").unwrap().0, "schedule.clear"); + assert_eq!(run("random roll 1..20").unwrap().0, "random.roll"); + assert_eq!( + run("random reset * 5 true false").unwrap().0, + "random.reset" + ); + assert_eq!(run("teammsg hi there").unwrap().0, "teammsg"); + assert_eq!(run("tm hi").unwrap().0, "teammsg"); + assert_eq!( + run("bossbar set a:b color pink").unwrap().0, + "bossbar.set.color" + ); + assert_eq!( + run("bossbar set a:b players @a").unwrap().0, + "bossbar.set.players" + ); + assert_eq!(run("bossbar get a:b max").unwrap().0, "bossbar.get"); + assert_eq!( + run("item fill block 1 2 3 container.* with minecraft:stone 5") + .unwrap() + .0, + "item" + ); + assert_eq!( + run("item replace entity @s armor.head from block 0 0 0 container.3") + .unwrap() + .0, + "item" + ); + assert_eq!(run("tick rate 40").unwrap().0, "tick.rate"); + assert_eq!(run("tick step 1s").unwrap().0, "tick.step"); + assert_eq!(run("reload").unwrap().0, "reload"); + assert_eq!( + run("datapack enable \"file/x\" after \"file/y\"") + .unwrap() + .0, + "datapack.enable" + ); + assert!(run("bossbar set a:b value -1").is_err()); + assert!(run("item replace entity @s nowhere.0 with minecraft:stone").is_err()); +} + +#[test] +fn world_command_trees() { + for (line, id) in [ + ("recipe give @s *", "recipe.give"), + ("recipe take @a minecraft:stick", "recipe.take"), + ("damage @e[limit=1] 5", "damage"), + ( + "damage @s 3.5 minecraft:magic by @e[limit=1] from @s", + "damage", + ), + ("damage @s 3 minecraft:fall at ~ ~ ~", "damage"), + ("rotate @s 90 0", "rotate"), + ("rotate @s facing entity @e[limit=1] eyes", "rotate"), + ("rotate @s facing 0 64 0", "rotate"), + ("swing", "swing"), + ("swing @e offhand whack 10", "swing"), + ("playsound minecraft:entity.cow.ambient", "playsound"), + ( + "playsound minecraft:block.stone.break block @s ~ ~ ~ 1 1 0.5", + "playsound", + ), + ("stopsound @s", "stopsound"), + ("stopsound @s * minecraft:ambient.cave", "stopsound"), + ("stopsound @s music minecraft:music.game", "stopsound"), + ("particle minecraft:smoke", "particle"), + ( + "particle minecraft:dust 1 0 0 2 ~ ~ ~ 0.1 0.1 0.1 0 10 force @a", + "particle", + ), + ("particle minecraft:block minecraft:stone ~ ~ ~", "particle"), + ("attribute @s minecraft:max_health get 2", "attribute.get"), + ( + "attribute @s minecraft:max_health base set 40", + "attribute.base.set", + ), + ( + "attribute @s minecraft:scale modifier add a:b 1.5 add_multiplied_base", + "attribute.modifier.add", + ), + ( + "attribute @s minecraft:scale modifier remove a:b", + "attribute.modifier.remove", + ), + ( + "attribute @s minecraft:scale modifier value get a:b 2", + "attribute.modifier.get", + ), + ("ride @s mount @e[limit=1]", "ride.mount"), + ("ride @s dismount", "ride.dismount"), + ("spreadplayers 0 0 5 20 false @a", "spreadplayers"), + ("spreadplayers ~ ~ 5 20 under 100 true @e", "spreadplayers"), + ("forceload add 0 0 100 100", "forceload.add"), + ("forceload remove all", "forceload.remove.all"), + ("forceload query", "forceload.query"), + ("forceload query ~ ~", "forceload.query"), + ( + "fillbiome 0 0 0 10 10 10 minecraft:plains replace minecraft:desert", + "fillbiome", + ), + ("worldborder set 100 5s", "worldborder.set"), + ("worldborder add -10", "worldborder.add"), + ("worldborder center 5 5", "worldborder.center"), + ("worldborder damage amount 1", "worldborder.damage.amount"), + ("worldborder warning time 10s", "worldborder.warning.time"), + ("worldborder get", "worldborder.get"), + ( + "loot give @s loot minecraft:chests/simple_dungeon", + "loot.loot", + ), + ("loot spawn ~ ~ ~ kill @e[limit=1]", "loot.kill"), + ("loot insert 0 0 0 mine 1 2 3 mainhand", "loot.mine"), + ( + "loot replace entity @s hotbar.0 3 fish minecraft:gameplay/fishing 0 0 0", + "loot.fish", + ), + ( + "loot replace block 1 2 3 container.5 loot minecraft:chests/x", + "loot.loot", + ), + ] { + assert_eq!( + run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0, + id, + "{line}" + ); + } + assert!(run("playsound minecraft:x invalid_source").is_err()); + assert!(run("particle minecraft:not_a_particle").is_err()); + assert!(run("damage @s -1").is_err()); + assert!(run("spreadplayers 0 0 5 0 false @a").is_err()); + assert!(run("worldborder warning distance -1").is_err()); +} + +#[test] +fn place_template_tree() { + for line in [ + "place template minecraft:igloo/top", + "place template minecraft:igloo/top ~ ~ ~", + "place template minecraft:igloo/top 1 2 3 clockwise_90 left_right 0.5 12 strict", + ] { + assert_eq!( + run(line).unwrap_or_else(|e| panic!("{line}: {e:?}")).0, + "place" + ); + } + assert!(run("place template minecraft:x ~ ~ ~ sideways").is_err()); + assert!(run("place template minecraft:x ~ ~ ~ none none 2").is_err()); +} diff --git a/crates/horizon-client/src/command/tree_data.rs b/crates/horizon-client/src/command/tree_data.rs new file mode 100644 index 000000000..bbf7ff468 --- /dev/null +++ b/crates/horizon-client/src/command/tree_data.rs @@ -0,0 +1,124 @@ +//! The `/data` and `/tag` command trees (DataCommands, TagCommand). +use super::{ + Dispatcher, + args::ArgType, + vanilla::{ENTITIES, GAMEMASTERS}, +}; + +const ENTITY: ArgType = ArgType::Entity { + single: true, + players: false, +}; + +/// `ArgProvider.wrap` for each of entity, block and storage: calls `then` +/// with the node holding the provider's argument. +fn providers( + d: &mut Dispatcher, + parent: usize, + role: &str, + mut then: impl FnMut(&mut Dispatcher, usize), +) { + let e = d.literal(parent, "entity"); + let a = d.argument(e, role, ENTITY); + then(d, a); + let b = d.literal(parent, "block"); + let a = d.argument(b, &format!("{role}Pos"), ArgType::BlockPos); + then(d, a); + let s = d.literal(parent, "storage"); + let a = d.argument(s, role, ArgType::Id("storages")); + then(d, a); +} + +pub fn register(d: &mut Dispatcher, root: usize) { + let data = d.literal(root, "data"); + d.requires(data, GAMEMASTERS); + + let merge = d.literal(data, "merge"); + providers(d, merge, "target", |d, a| { + let nbt = d.argument(a, "nbt", ArgType::Nbt); + d.executes(nbt, "data.merge"); + }); + let get = d.literal(data, "get"); + providers(d, get, "target", |d, a| { + d.executes(a, "data.get"); + let path = d.argument(a, "path", ArgType::NbtPath); + d.executes(path, "data.get"); + let scale = d.argument( + path, + "scale", + ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + ); + d.executes(scale, "data.get"); + }); + let remove = d.literal(data, "remove"); + providers(d, remove, "target", |d, a| { + let path = d.argument(a, "path", ArgType::NbtPath); + d.executes(path, "data.remove"); + }); + let modify = d.literal(data, "modify"); + providers(d, modify, "target", |d, a| { + let target_path = d.argument(a, "targetPath", ArgType::NbtPath); + // insert | prepend | append | set | merge, then the source. + let mut ops = Vec::new(); + let insert = d.literal(target_path, "insert"); + let index = d.argument( + insert, + "index", + ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }, + ); + ops.push(index); + for op in ["prepend", "append", "set", "merge"] { + ops.push(d.literal(target_path, op)); + } + for op in ops { + let from = d.literal(op, "from"); + providers(d, from, "source", |d, s| { + d.executes(s, "data.modify"); + let sp = d.argument(s, "sourcePath", ArgType::NbtPath); + d.executes(sp, "data.modify"); + }); + let string = d.literal(op, "string"); + providers(d, string, "source", |d, s| { + d.executes(s, "data.modify"); + let sp = d.argument(s, "sourcePath", ArgType::NbtPath); + d.executes(sp, "data.modify"); + let int = || ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }; + let start = d.argument(sp, "start", int()); + d.executes(start, "data.modify"); + let end = d.argument(start, "end", int()); + d.executes(end, "data.modify"); + }); + let value = d.literal(op, "value"); + let v = d.argument(value, "value", ArgType::NbtTag); + d.executes(v, "data.modify"); + } + }); + + // tag add|remove | list + let tag = d.literal(root, "tag"); + d.requires(tag, GAMEMASTERS); + let targets = d.argument(tag, "targets", ENTITIES); + for word in ["add", "remove"] { + let w = d.literal(targets, word); + let name = d.argument(w, "name", ArgType::Word); + d.executes( + name, + if word == "add" { + "tag.add" + } else { + "tag.remove" + }, + ); + } + let list = d.literal(targets, "list"); + d.executes(list, "tag.list"); +} diff --git a/crates/horizon-client/src/command/tree_execute.rs b/crates/horizon-client/src/command/tree_execute.rs new file mode 100644 index 000000000..f8b3ae484 --- /dev/null +++ b/crates/horizon-client/src/command/tree_execute.rs @@ -0,0 +1,232 @@ +//! The `/execute` tree (ExecuteCommand): modifiers redirect back to +//! `execute`, `run` to the root; conditions both execute (as a test) and +//! continue the chain; `store` redirects with a result callback. +use super::{ + Dispatcher, + args::{ArgType, Resource}, + vanilla::{ENTITIES, GAMEMASTERS}, +}; + +pub const HEIGHTMAPS: &[&str] = &[ + "world_surface", + "motion_blocking", + "motion_blocking_no_leaves", + "ocean_floor", +]; +pub const RELATIONS: [&str; 8] = [ + "owner", + "leasher", + "target", + "attacker", + "vehicle", + "controller", + "origin", + "passengers", +]; + +/// A conditional's end: it runs as a test and continues the chain. +fn conditional(d: &mut Dispatcher, node: usize, ex: usize) { + d.executes(node, "execute"); + d.redirect(node, ex); +} + +pub fn register(d: &mut Dispatcher, root: usize) { + let ex = d.literal(root, "execute"); + d.requires(ex, GAMEMASTERS); + let run = d.literal(ex, "run"); + d.redirect(run, root); + for name in ["as", "at"] { + let l = d.literal(ex, name); + let t = d.argument(l, "targets", ENTITIES); + d.redirect(t, ex); + } + let positioned = d.literal(ex, "positioned"); + let pos = d.argument(positioned, "pos", ArgType::Vec3 { center: true }); + d.redirect(pos, ex); + let as_ = d.literal(positioned, "as"); + let t = d.argument(as_, "targets", ENTITIES); + d.redirect(t, ex); + let over = d.literal(positioned, "over"); + let hm = d.argument(over, "heightmap", ArgType::Enum(HEIGHTMAPS)); + d.redirect(hm, ex); + let rotated = d.literal(ex, "rotated"); + let rot = d.argument(rotated, "rot", ArgType::Rotation); + d.redirect(rot, ex); + let as_ = d.literal(rotated, "as"); + let t = d.argument(as_, "targets", ENTITIES); + d.redirect(t, ex); + let facing = d.literal(ex, "facing"); + let pos = d.argument(facing, "pos", ArgType::Vec3 { center: true }); + d.redirect(pos, ex); + let entity = d.literal(facing, "entity"); + let t = d.argument(entity, "targets", ENTITIES); + let anchor = d.argument(t, "anchor", ArgType::Anchor); + d.redirect(anchor, ex); + let align = d.literal(ex, "align"); + let axes = d.argument(align, "axes", ArgType::Swizzle); + d.redirect(axes, ex); + let anchored = d.literal(ex, "anchored"); + let anchor = d.argument(anchored, "anchor", ArgType::Anchor); + d.redirect(anchor, ex); + let in_ = d.literal(ex, "in"); + let dim = d.argument(in_, "dimension", ArgType::Dimension); + d.redirect(dim, ex); + let summon = d.literal(ex, "summon"); + let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType)); + d.redirect(e, ex); + let on = d.literal(ex, "on"); + for r in RELATIONS { + let l = d.literal(on, r); + d.redirect(l, ex); + } + store(d, ex); + for mode in ["if", "unless"] { + let m = d.literal(ex, mode); + conditionals(d, m, ex); + } +} + +fn store(d: &mut Dispatcher, ex: usize) { + let store = d.literal(ex, "store"); + for kind in ["result", "success"] { + let k = d.literal(store, kind); + let score = d.literal(k, "score"); + let targets = d.argument(score, "targets", ArgType::ScoreHolder { multiple: true }); + let objective = d.argument(targets, "objective", ArgType::Objective); + d.redirect(objective, ex); + let bossbar = d.literal(k, "bossbar"); + let id = d.argument(bossbar, "id", ArgType::Id("bossbars")); + for what in ["value", "max"] { + let w = d.literal(id, what); + d.redirect(w, ex); + } + for provider in ["entity", "block", "storage"] { + let p = d.literal(k, provider); + let a = match provider { + "entity" => d.argument( + p, + "target", + ArgType::Entity { + single: true, + players: false, + }, + ), + "block" => d.argument(p, "targetPos", ArgType::BlockPos), + _ => d.argument(p, "target", ArgType::Id("storages")), + }; + let path = d.argument(a, "path", ArgType::NbtPath); + for ty in ["int", "float", "short", "long", "double", "byte"] { + let t = d.literal(path, ty); + let scale = d.argument( + t, + "scale", + ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + ); + d.redirect(scale, ex); + } + } + } +} + +fn conditionals(d: &mut Dispatcher, m: usize, ex: usize) { + let block = d.literal(m, "block"); + let pos = d.argument(block, "pos", ArgType::BlockPos); + let predicate = d.argument(pos, "block", ArgType::BlockPredicate); + conditional(d, predicate, ex); + + let biome = d.literal(m, "biome"); + let pos = d.argument(biome, "pos", ArgType::BlockPos); + let b = d.argument(pos, "biome", ArgType::Resource(Resource::Biome)); + conditional(d, b, ex); + + let loaded = d.literal(m, "loaded"); + let pos = d.argument(loaded, "pos", ArgType::BlockPos); + conditional(d, pos, ex); + + let dimension = d.literal(m, "dimension"); + let dim = d.argument(dimension, "dimension", ArgType::Dimension); + conditional(d, dim, ex); + + let score = d.literal(m, "score"); + let target = d.argument(score, "target", ArgType::ScoreHolder { multiple: false }); + let objective = d.argument(target, "targetObjective", ArgType::Objective); + for op in ["=", "<", "<=", ">", ">="] { + let o = d.literal(objective, op); + let source = d.argument(o, "source", ArgType::ScoreHolder { multiple: false }); + let so = d.argument(source, "sourceObjective", ArgType::Objective); + conditional(d, so, ex); + } + let matches = d.literal(objective, "matches"); + let range = d.argument(matches, "range", ArgType::IntRange); + conditional(d, range, ex); + + let blocks = d.literal(m, "blocks"); + let start = d.argument(blocks, "start", ArgType::BlockPos); + let end = d.argument(start, "end", ArgType::BlockPos); + let dest = d.argument(end, "destination", ArgType::BlockPos); + for mode in ["all", "masked"] { + let l = d.literal(dest, mode); + conditional(d, l, ex); + } + + let entity = d.literal(m, "entity"); + let targets = d.argument(entity, "entities", ENTITIES); + conditional(d, targets, ex); + + let predicate = d.literal(m, "predicate"); + let p = d.argument(predicate, "predicate", ArgType::Id("predicates")); + conditional(d, p, ex); + + let function = d.literal(m, "function"); + let name = d.argument(function, "name", ArgType::Function); + conditional(d, name, ex); + + let data = d.literal(m, "data"); + for provider in ["entity", "block", "storage"] { + let p = d.literal(data, provider); + let a = match provider { + "entity" => d.argument( + p, + "source", + ArgType::Entity { + single: true, + players: false, + }, + ), + "block" => d.argument(p, "sourcePos", ArgType::BlockPos), + _ => d.argument(p, "source", ArgType::Id("storages")), + }; + let path = d.argument(a, "path", ArgType::NbtPath); + conditional(d, path, ex); + } + + // items / slots (entity|block) [] + for kind in ["items", "slots"] { + let k = d.literal(m, kind); + for provider in ["entity", "block"] { + let p = d.literal(k, provider); + let a = if provider == "entity" { + d.argument( + p, + "source", + ArgType::Entity { + single: false, + players: false, + }, + ) + } else { + d.argument(p, "sourcePos", ArgType::BlockPos) + }; + let slots = d.argument(a, "slots", ArgType::Slots); + if kind == "items" { + let item = d.argument(slots, "item_predicate", ArgType::ItemPredicate); + conditional(d, item, ex); + } else { + conditional(d, slots, ex); + } + } + } +} diff --git a/crates/horizon-client/src/command/tree_misc.rs b/crates/horizon-client/src/command/tree_misc.rs new file mode 100644 index 000000000..2494acb72 --- /dev/null +++ b/crates/horizon-client/src/command/tree_misc.rs @@ -0,0 +1,257 @@ +//! Smaller command trees: `/bossbar`, `/function`, `/return`, `/schedule`, +//! `/random`, `/tick`, `/teammsg`, `/reload` and `/datapack`. +use super::{ + Dispatcher, + args::ArgType, + vanilla::{ENTITIES, GAMEMASTERS, PLAYERS}, +}; + +fn int() -> ArgType { + ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + } +} +fn int_min(min: i32) -> ArgType { + ArgType::Integer { min, max: i32::MAX } +} +pub const ADMINS: u8 = 3; + +pub fn register(d: &mut Dispatcher, root: usize) { + item(d, root); + bossbar(d, root); + function(d, root); + + // return | fail | run + let ret = d.literal(root, "return"); + d.requires(ret, GAMEMASTERS); + let v = d.argument(ret, "value", int()); + d.executes(v, "return.value"); + let fail = d.literal(ret, "fail"); + d.executes(fail, "return.fail"); + let run = d.literal(ret, "run"); + d.redirect(run, root); + + // schedule function