diff --git a/Cargo.lock b/Cargo.lock index 8eadbf02a..81416440e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -686,6 +686,7 @@ dependencies = [ "horizon-assets", "horizon-core", "horizon-world", + "miniz_oxide 0.8.9", "png", "pollster", "serde_json", diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 4da5f8513..a373b30fa 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -20,3 +20,4 @@ png = "0.18" serde_json = { version = "1.0.151", features = ["raw_value"] } cpal = "0.16" symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } +miniz_oxide = "0.8" diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs new file mode 100644 index 000000000..3500f6fd6 --- /dev/null +++ b/crates/horizon-client/src/command/args.rs @@ -0,0 +1,1160 @@ +//! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with +//! the vanilla error messages and completion suggestions. +use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; +use std::collections::BTreeMap; + +/// Registry contents and source state used to validate and complete arguments. +#[derive(Clone, Debug, Default)] +pub struct Registries { + /// Permission level of the command source. + pub permission: u8, + pub items: Vec, + pub item_tags: Vec, + /// Block id -> (property, allowed values). + pub blocks: BTreeMap)>>, + pub block_tags: Vec, + /// Entity types that `summon` can create. + pub summonable: Vec, + /// Every entity type (selector `type=`). + pub entity_types: Vec, + pub effects: Vec, + pub enchantments: Vec, + pub structures: Vec, + pub biomes: Vec, + pub dimensions: Vec, + pub clocks: Vec, + pub timelines: Vec, + pub time_markers: Vec, + /// Game rule name -> integer-valued. + pub game_rules: Vec<(String, bool)>, + pub players: Vec, + /// The block the source is looking at (relevant coordinates). + pub target_block: Option<[i32; 3]>, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Resource { + EntityType, + Effect, + Enchantment, + Structure, + Biome, + Clock, + Timeline, +} +impl Resource { + pub fn registry(self) -> &'static str { + match self { + Resource::EntityType => "minecraft:entity_type", + Resource::Effect => "minecraft:mob_effect", + Resource::Enchantment => "minecraft:enchantment", + Resource::Structure => "minecraft:worldgen/structure", + Resource::Biome => "minecraft:worldgen/biome", + Resource::Clock => "minecraft:world_clock", + Resource::Timeline => "minecraft:timeline", + } + } + fn values(self, reg: &Registries) -> &[String] { + match self { + Resource::EntityType => ®.summonable, + Resource::Effect => ®.effects, + Resource::Enchantment => ®.enchantments, + Resource::Structure => ®.structures, + Resource::Biome => ®.biomes, + Resource::Clock => ®.clocks, + Resource::Timeline => ®.timelines, + } + } +} + +#[derive(Clone, Debug)] +pub enum ArgType { + Bool, + Integer { min: i32, max: i32 }, + Float { min: f32, max: f32 }, + Double { min: f64, max: f64 }, + Word, + Str, + Greedy, + Entity { single: bool, players: bool }, + BlockPos, + Vec3 { center: bool }, + Rotation, + Angle, + Item, + ItemPredicate, + BlockState, + BlockPredicate, + Resource(Resource), + /// A plain identifier; suggestions come from the named list. + Id(&'static str), + Time { min: i32 }, + GameMode, + Message, + Dimension, + Anchor, + /// CompoundTagArgument (kept as SNBT text). + Nbt, +} +pub fn integer(min: i32) -> ArgType { + ArgType::Integer { min, max: i32::MAX } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Coord { + pub relative: bool, + pub value: f64, +} +impl Coord { + pub fn get(self, base: f64) -> f64 { + if self.relative { base + self.value } else { self.value } + } +} +#[derive(Clone, Debug, PartialEq)] +pub enum Coordinates { + World([Coord; 3]), + Local([f64; 3]), +} +impl Coordinates { + /// WorldCoordinates/LocalCoordinates.getPosition from the source position + /// (feet) and rotation (yaw, pitch in degrees). + pub fn position(&self, pos: [f64; 3], rot: [f32; 2]) -> [f64; 3] { + match self { + Coordinates::World(c) => [c[0].get(pos[0]), c[1].get(pos[1]), c[2].get(pos[2])], + Coordinates::Local([left, up, forwards]) => { + let d = std::f32::consts::PI / 180.0; + let (yaw, pitch) = (rot[0], rot[1]); + let cos_y = ((yaw + 90.0) * d).cos(); + let sin_y = ((yaw + 90.0) * d).sin(); + let cos_p = (-pitch * d).cos(); + let sin_p = (-pitch * d).sin(); + let cos_p2 = ((-pitch + 90.0) * d).cos(); + let sin_p2 = ((-pitch + 90.0) * d).sin(); + let f = [f64::from(cos_y * cos_p), f64::from(sin_p), f64::from(sin_y * cos_p)]; + let u = [f64::from(cos_y * cos_p2), f64::from(sin_p2), f64::from(sin_y * cos_p2)]; + // left = -(forward x up) + let l = [-(f[1] * u[2] - f[2] * u[1]), -(f[2] * u[0] - f[0] * u[2]), -(f[0] * u[1] - f[1] * u[0])]; + [ + pos[0] + f[0] * forwards + u[0] * up + l[0] * left, + pos[1] + f[1] * forwards + u[1] * up + l[1] * left, + pos[2] + f[2] * forwards + u[2] * up + l[2] * left, + ] + } + } + } + pub fn block(&self, pos: [f64; 3], rot: [f32; 2]) -> [i32; 3] { + let p = self.position(pos, rot); + [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + } + /// RotationArgument: (yaw, pitch) from the source rotation. + pub fn rotation(&self, rot: [f32; 2]) -> [f32; 2] { + match self { + Coordinates::World(c) => [c[0].get(f64::from(rot[0])) as f32, c[1].get(f64::from(rot[1])) as f32], + Coordinates::Local(_) => rot, + } + } +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Sort { + #[default] + Arbitrary, + Nearest, + Furthest, + Random, +} +pub type DoubleRange = (Option, Option); +pub type IntRange = (Option, Option); +/// A parsed entity selector (EntitySelector) or player name. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Selector { + pub player_name: Option, + /// 'p', 'a', 'r', 's', 'e', 'n'. + pub kind: char, + pub limit: usize, + pub sort: Sort, + pub include_entities: bool, + pub types: Vec<(String, bool)>, + pub names: Vec<(String, bool)>, + pub tags: Vec<(String, bool)>, + pub gamemodes: Vec<(String, bool)>, + pub distance: Option, + pub level: Option, + pub x_rotation: Option, + pub y_rotation: Option, + pub pos: [Option; 3], + pub delta: [Option; 3], +} +impl Selector { + pub fn is_self(&self) -> bool { + self.kind == 's' + } + pub fn single(&self) -> bool { + self.limit <= 1 + } +} +#[derive(Clone, Debug, PartialEq)] +pub struct BlockInput { + pub id: String, + pub properties: Vec<(String, String)>, + /// `#tag` for block predicates. + pub tag: bool, + pub nbt: Option, +} +#[derive(Clone, Debug, PartialEq)] +pub struct ItemInput { + pub id: String, + pub tag: bool, + pub any: bool, + pub components: Option, +} +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GameMode { + Survival, + Creative, + Adventure, + Spectator, +} +impl GameMode { + pub const ALL: [GameMode; 4] = [GameMode::Survival, GameMode::Creative, GameMode::Adventure, GameMode::Spectator]; + pub fn name(self) -> &'static str { + match self { + GameMode::Survival => "survival", + GameMode::Creative => "creative", + GameMode::Adventure => "adventure", + GameMode::Spectator => "spectator", + } + } + pub fn from_name(s: &str) -> Option { + Self::ALL.into_iter().find(|m| m.name() == s) + } +} +#[derive(Clone, Debug, PartialEq)] +pub enum Arg { + Bool(bool), + Int(i32), + Float(f32), + Double(f64), + Str(String), + Entity(Selector), + Coords(Coordinates), + Angle(Coord), + Item(ItemInput), + Block(BlockInput), + Resource(String), + GameMode(GameMode), + /// `eyes` (true) or `feet`. + Anchor(bool), +} + +fn is_id_char(c: char) -> bool { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '-' | '.' | ':' | '/') +} +/// Identifier.read: the longest run of identifier characters, normalised to +/// the `minecraft` namespace. +pub fn read_id(reader: &mut Reader) -> CmdResult { + let start = reader.cursor; + while reader.can_read() && is_id_char(reader.peek()) { + reader.skip(); + } + let raw = &reader.string[start..reader.cursor]; + let valid = !raw.is_empty() && raw.matches(':').count() <= 1 && !raw.ends_with(':') && !raw.split(':').next().unwrap_or("").contains('/'); + if !valid { + reader.cursor = start; + return Err(CommandError::tr_at("argument.id.invalid", &[], reader)); + } + Ok(normalize(raw)) +} +pub fn normalize(id: &str) -> String { + match id.split_once(':') { + Some(("", path)) => format!("minecraft:{path}"), + Some(_) => id.to_owned(), + None => format!("minecraft:{id}"), + } +} +/// SharedSuggestionProvider.matchesSubStr: `input` is a prefix of +/// `candidate` or of a part after an underscore. +pub fn matches_sub_str(input: &str, candidate: &str) -> bool { + let mut index = 0; + loop { + if candidate[index..].starts_with(input) { + return true; + } + match candidate[index..].find('_') { + Some(i) => index += i + 1, + None => return false, + } + } +} +/// SharedSuggestionProvider.suggestResource. +pub fn suggest_resources<'a>(builder: &mut SuggestionsBuilder, ids: impl IntoIterator, prefix: &str) { + let remaining = builder.remaining_lower(); + let remaining = remaining.strip_prefix(prefix).unwrap_or(&remaining).to_owned(); + for id in ids { + let matched = if remaining.contains(':') { + matches_sub_str(&remaining, id) + } else { + let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); + matches_sub_str(&remaining, ns) || (ns == "minecraft" && matches_sub_str(&remaining, path)) + }; + if matched { + builder.suggest(format!("{prefix}{id}")); + } + } +} +fn range_double(reader: &mut Reader) -> CmdResult { + let (a, b) = read_range(reader)?; + let parse = |s: &str, reader: &Reader| s.parse::().map_err(|_| CommandError::tr_at("parsing.double.invalid", &[&s], reader)); + let lo = a.map(|s| parse(&s, reader)).transpose()?; + let hi = b.map(|s| parse(&s, reader)).transpose()?; + if let (Some(l), Some(h)) = (lo, hi) + && l > h + { + return Err(CommandError::tr_at("argument.range.swapped", &[], reader)); + } + Ok((lo, hi)) +} +fn range_int(reader: &mut Reader) -> CmdResult { + let (a, b) = read_range(reader)?; + let parse = |s: &str, reader: &Reader| { + if s.contains('.') { + return Err(CommandError::tr_at("argument.range.ints", &[], reader)); + } + s.parse::().map_err(|_| CommandError::tr_at("parsing.int.invalid", &[&s], reader)) + }; + let lo = a.map(|s| parse(&s, reader)).transpose()?; + let hi = b.map(|s| parse(&s, reader)).transpose()?; + if let (Some(l), Some(h)) = (lo, hi) + && l > h + { + return Err(CommandError::tr_at("argument.range.swapped", &[], reader)); + } + Ok((lo, hi)) +} +/// MinMaxBounds: `a`, `a..`, `..b` or `a..b`. +fn read_range(reader: &mut Reader) -> CmdResult<(Option, Option)> { + if !reader.can_read() { + return Err(CommandError::tr_at("argument.range.empty", &[], reader)); + } + let number = |reader: &mut Reader| { + let start = reader.cursor; + while reader.can_read() && (reader.peek().is_ascii_digit() || reader.peek() == '-' || (reader.peek() == '.' && reader.peek_at(1) != '.')) { + reader.skip(); + } + let s = &reader.string[start..reader.cursor]; + (!s.is_empty()).then(|| s.to_owned()) + }; + let lo = number(reader); + let hi = if reader.remaining().starts_with("..") { + reader.skip(); + reader.skip(); + number(reader) + } else { + lo.clone() + }; + if lo.is_none() && hi.is_none() { + return Err(CommandError::tr_at("argument.range.empty", &[], reader)); + } + Ok((lo, hi)) +} +fn parse_coord_int(reader: &mut Reader) -> CmdResult { + if reader.can_read() && reader.peek() == '^' { + return Err(CommandError::tr_at("argument.pos.mixed", &[], reader)); + } + if !reader.can_read() { + return Err(CommandError::tr_at("argument.pos.missing.int", &[], reader)); + } + let relative = reader.peek() == '~'; + if relative { + reader.skip(); + } + let value = if reader.can_read() && reader.peek() != ' ' { + if relative { reader.read_double()? } else { f64::from(reader.read_int()?) } + } else { + 0.0 + }; + Ok(Coord { relative, value }) +} +fn parse_coord_double(reader: &mut Reader, center: bool) -> CmdResult { + if reader.can_read() && reader.peek() == '^' { + return Err(CommandError::tr_at("argument.pos.mixed", &[], reader)); + } + if !reader.can_read() { + return Err(CommandError::tr_at("argument.pos.missing.double", &[], reader)); + } + let relative = reader.peek() == '~'; + if relative { + reader.skip(); + } + let start = reader.cursor; + let mut value = if reader.can_read() && reader.peek() != ' ' { reader.read_double()? } else { 0.0 }; + let number = &reader.string[start..reader.cursor]; + if relative && number.is_empty() { + return Ok(Coord { relative, value: 0.0 }); + } + if !number.contains('.') && !relative && center { + value += 0.5; + } + Ok(Coord { relative, value }) +} +fn parse_local(reader: &mut Reader) -> CmdResult { + let start = reader.cursor; + let mut v = [0.0; 3]; + for (i, slot) in v.iter_mut().enumerate() { + if i > 0 { + if !reader.can_read() || reader.peek() != ' ' { + reader.cursor = start; + return Err(CommandError::tr_at("argument.pos3d.incomplete", &[], reader)); + } + reader.skip(); + } + if !reader.can_read() || reader.peek() != '^' { + reader.cursor = start; + return Err(CommandError::tr_at("argument.pos.mixed", &[], reader)); + } + reader.skip(); + *slot = if reader.can_read() && reader.peek() != ' ' { reader.read_double()? } else { 0.0 }; + } + Ok(Coordinates::Local(v)) +} +fn parse_world(reader: &mut Reader, block: bool, center: bool) -> CmdResult { + let start = reader.cursor; + let mut c = [Coord { relative: false, value: 0.0 }; 3]; + for (i, slot) in c.iter_mut().enumerate() { + if i > 0 { + if !reader.can_read() || reader.peek() != ' ' { + reader.cursor = start; + return Err(CommandError::tr_at("argument.pos3d.incomplete", &[], reader)); + } + reader.skip(); + } + *slot = if block { parse_coord_int(reader)? } else { parse_coord_double(reader, center && i != 1)? }; + } + Ok(Coordinates::World(c)) +} +fn suggest_coordinates(builder: &mut SuggestionsBuilder, reg: &Registries) { + let remaining = builder.remaining().to_owned(); + let coords: Vec<[String; 3]> = if remaining.starts_with('^') { + vec![["^".into(), "^".into(), "^".into()]] + } else if let Some(t) = reg.target_block { + vec![[t[0].to_string(), t[1].to_string(), t[2].to_string()]] + } else { + vec![["~".into(), "~".into(), "~".into()]] + }; + if remaining.is_empty() { + for c in &coords { + builder.suggest(c[0].clone()); + builder.suggest(format!("{} {}", c[0], c[1])); + builder.suggest(format!("{} {} {}", c[0], c[1], c[2])); + } + } else { + let parts: Vec<&str> = remaining.split(' ').collect(); + for c in &coords { + match parts.len() { + 1 => { + builder.suggest(format!("{} {}", parts[0], c[1])); + builder.suggest(format!("{} {} {}", parts[0], c[1], c[2])); + } + 2 => builder.suggest(format!("{} {} {}", parts[0], parts[1], c[2])), + _ => {} + } + } + } +} + +const SELECTORS: [(&str, &str); 6] = [ + ("@a", "argument.entity.selector.allPlayers"), + ("@e", "argument.entity.selector.allEntities"), + ("@n", "argument.entity.selector.nearestEntity"), + ("@p", "argument.entity.selector.nearestPlayer"), + ("@r", "argument.entity.selector.randomPlayer"), + ("@s", "argument.entity.selector.self"), +]; +const OPTIONS: [&str; 16] = [ + "name", "distance", "level", "x", "y", "z", "dx", "dy", "dz", "x_rotation", "y_rotation", "limit", "sort", "gamemode", "tag", "type", +]; +fn parse_selector(reader: &mut Reader, reg: &Registries) -> CmdResult { + let start = reader.cursor; + if !(reader.can_read() && reader.peek() == '@') { + // EntitySelectorParser.parseNameOrUUID. + let name = reader.read_string()?; + if name.is_empty() || name.chars().count() > 16 { + reader.cursor = start; + return Err(CommandError::tr_at("argument.entity.invalid", &[], reader)); + } + return Ok(Selector { player_name: Some(name), kind: '\0', limit: 1, include_entities: false, ..Selector::default() }); + } + reader.skip(); + if !reader.can_read() { + return Err(CommandError::tr_at("argument.entity.selector.missing", &[], reader)); + } + let kind = reader.read(); + let mut s = Selector { kind, ..Selector::default() }; + match kind { + 'p' => { + s.limit = 1; + s.sort = Sort::Nearest; + s.types.push(("minecraft:player".into(), false)); + } + 'a' => { + s.limit = usize::MAX; + s.types.push(("minecraft:player".into(), false)); + } + 'r' => { + s.limit = 1; + s.sort = Sort::Random; + s.types.push(("minecraft:player".into(), false)); + } + 's' => { + s.limit = 1; + s.include_entities = true; + } + 'e' => { + s.limit = usize::MAX; + s.include_entities = true; + } + 'n' => { + s.limit = 1; + s.sort = Sort::Nearest; + s.include_entities = true; + } + other => { + reader.cursor = start; + return Err(CommandError::tr_at("argument.entity.selector.unknown", &[&format!("@{other}")], reader)); + } + } + if reader.can_read() && reader.peek() == '[' { + reader.skip(); + reader.skip_whitespace(); + while reader.can_read() && reader.peek() != ']' { + reader.skip_whitespace(); + let option_start = reader.cursor; + let option = reader.read_string()?; + if !OPTIONS.contains(&option.as_str()) { + reader.cursor = option_start; + return Err(CommandError::tr_at("argument.entity.options.unknown", &[&option], reader)); + } + reader.skip_whitespace(); + if !reader.can_read() || reader.peek() != '=' { + reader.cursor = option_start; + return Err(CommandError::tr_at("argument.entity.options.valueless", &[&option], reader)); + } + reader.skip(); + reader.skip_whitespace(); + let negated = |reader: &mut Reader| { + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == '!' { + reader.skip(); + reader.skip_whitespace(); + true + } else { + false + } + }; + match option.as_str() { + "name" => { + let neg = negated(reader); + let v = reader.read_string()?; + s.names.push((v, neg)); + } + "distance" => { + let r = range_double(reader)?; + if r.0.is_some_and(|v| v < 0.0) || r.1.is_some_and(|v| v < 0.0) { + reader.cursor = option_start; + return Err(CommandError::tr_at("argument.entity.options.distance.negative", &[], reader)); + } + s.distance = Some(r); + if s.kind != 's' { + s.sort = if s.sort == Sort::Arbitrary { Sort::Arbitrary } else { s.sort }; + } + } + "level" => { + let r = range_int(reader)?; + if r.0.is_some_and(|v| v < 0) || r.1.is_some_and(|v| v < 0) { + reader.cursor = option_start; + return Err(CommandError::tr_at("argument.entity.options.level.negative", &[], reader)); + } + s.level = Some(r); + s.include_entities = false; + } + "x" | "y" | "z" => { + let i = usize::from(option.as_bytes()[0] - b'x'); + s.pos[i] = Some(reader.read_double()?); + } + "dx" | "dy" | "dz" => { + let i = usize::from(option.as_bytes()[1] - b'x'); + s.delta[i] = Some(reader.read_double()?); + } + "x_rotation" => s.x_rotation = Some(range_double(reader)?), + "y_rotation" => s.y_rotation = Some(range_double(reader)?), + "limit" => { + let at = reader.cursor; + let n = reader.read_int()?; + if n < 1 { + reader.cursor = at; + return Err(CommandError::tr_at("argument.entity.options.limit.toosmall", &[], reader)); + } + s.limit = n as usize; + } + "sort" => { + let at = reader.cursor; + let v = reader.read_unquoted_string(); + s.sort = match v { + "nearest" => Sort::Nearest, + "furthest" => Sort::Furthest, + "random" => Sort::Random, + "arbitrary" => Sort::Arbitrary, + _ => { + reader.cursor = at; + return Err(CommandError::tr_at("argument.entity.options.sort.irreversible", &[&v], reader)); + } + }; + } + "gamemode" => { + let neg = negated(reader); + let at = reader.cursor; + let v = reader.read_unquoted_string().to_owned(); + if GameMode::from_name(&v).is_none() { + reader.cursor = at; + return Err(CommandError::tr_at("argument.entity.options.mode.invalid", &[&v], reader)); + } + s.gamemodes.push((v, neg)); + s.include_entities = false; + } + "tag" => { + let neg = negated(reader); + let v = reader.read_unquoted_string().to_owned(); + s.tags.push((v, neg)); + } + "type" => { + let neg = negated(reader); + let at = reader.cursor; + let tag = reader.can_read() && reader.peek() == '#'; + if tag { + reader.skip(); + } + let id = read_id(reader)?; + if !tag && !reg.entity_types.is_empty() && !reg.entity_types.contains(&id) { + reader.cursor = at; + return Err(CommandError::tr_at("argument.entity.options.type.invalid", &[&id], reader)); + } + let id = if tag { format!("#{id}") } else { id }; + if s.kind == 'p' || s.kind == 'a' || s.kind == 'r' { + s.types.clear(); + } + if id == "minecraft:player" && !neg { + s.include_entities = false; + } + s.types.push((id, neg)); + } + _ => {} + } + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + continue; + } + if !reader.can_read() || reader.peek() != ']' { + return Err(CommandError::tr_at("argument.entity.options.unterminated", &[], reader)); + } + } + if !reader.can_read() { + return Err(CommandError::tr_at("argument.entity.options.unterminated", &[], reader)); + } + reader.skip(); + } + Ok(s) +} +fn suggest_selector(builder: &mut SuggestionsBuilder, reg: &Registries) { + let remaining = builder.remaining().to_owned(); + // Inside the option list: complete option names and values. + if let Some(open) = remaining.find('[') { + let inside = &remaining[open + 1..]; + let part_start = inside.rfind(',').map_or(0, |i| i + 1); + let part = &inside[part_start..]; + let base = builder.start + open + 1 + part_start; + if let Some((name, value)) = part.split_once('=') { + let value_start = base + name.len() + 1; + let mut b = builder.offset(value_start); + let value = value.trim_start_matches('!'); + let neg = part[name.len() + 1..].starts_with('!'); + let mut b2 = builder.offset(value_start + usize::from(neg)); + let name = name.trim(); + let complete = match name { + "type" => { + let v = value.trim_start_matches('#'); + !v.is_empty() && (reg.entity_types.contains(&normalize(v)) || value.starts_with('#')) + } + "sort" => ["nearest", "furthest", "random", "arbitrary"].contains(&value), + "gamemode" => GameMode::from_name(value).is_some(), + _ => !value.is_empty(), + }; + if complete { + let mut end = builder.offset(builder.input.len()); + end.suggest(","); + end.suggest("]"); + builder.out.extend(end.out); + return; + } + match name { + "type" => { + let types: Vec = reg.entity_types.clone(); + suggest_resources(&mut b2, &types, ""); + if !neg && value.is_empty() { + for t in &types { + b.suggest(format!("!{t}")); + } + } + } + "sort" => b2.suggest_matching(["nearest", "furthest", "random", "arbitrary"]), + "gamemode" => b2.suggest_matching(GameMode::ALL.map(GameMode::name)), + _ => {} + } + builder.out.extend(b.out); + builder.out.extend(b2.out); + } else { + let mut b = builder.offset(base); + let lower = part.trim_start().to_lowercase(); + for o in OPTIONS { + if o.starts_with(&lower) { + b.suggest_tooltip(format!("{o}="), crate::lang::get(&format!("argument.entity.options.{o}.description"))); + } + } + if part.is_empty() { + b.suggest("]"); + } + builder.out.extend(b.out); + } + return; + } + if remaining.len() == 2 && remaining.starts_with('@') { + let mut b = builder.offset(builder.input.len()); + b.suggest("["); + builder.out.extend(b.out); + return; + } + let lower = builder.remaining_lower(); + for (s, tip) in SELECTORS { + if s.starts_with(&lower) { + builder.suggest_tooltip(s, crate::lang::get(tip)); + } + } + let players = reg.players.clone(); + builder.suggest_matching(players.iter().map(String::as_str)); +} +fn parse_block(reader: &mut Reader, reg: &Registries, tags: bool) -> CmdResult { + let start = reader.cursor; + let tag = tags && reader.can_read() && reader.peek() == '#'; + if !tags && reader.can_read() && reader.peek() == '#' { + return Err(CommandError::tr_at("argument.block.tag.disallowed", &[], reader)); + } + if tag { + reader.skip(); + } + let id = read_id(reader)?; + let known = if tag { reg.block_tags.contains(&id) || reg.block_tags.is_empty() } else { reg.blocks.contains_key(&id) || reg.blocks.is_empty() }; + if !known { + reader.cursor = start; + let key = if tag { "arguments.block.tag.unknown" } else { "argument.block.id.invalid" }; + return Err(CommandError::tr_at(key, &[&id], reader)); + } + let mut properties = Vec::new(); + if reader.can_read() && reader.peek() == '[' { + reader.skip(); + reader.skip_whitespace(); + let allowed = reg.blocks.get(&id); + while reader.can_read() && reader.peek() != ']' { + reader.skip_whitespace(); + let at = reader.cursor; + let name = reader.read_string()?; + let property = allowed.and_then(|p| p.iter().find(|(n, _)| *n == name)); + if !tag && allowed.is_some() && property.is_none() { + reader.cursor = at; + return Err(CommandError::tr_at("argument.block.property.unknown", &[&id, &name], reader)); + } + if properties.iter().any(|(n, _): &(String, String)| *n == name) { + reader.cursor = at; + return Err(CommandError::tr_at("argument.block.property.duplicate", &[&name, &id], reader)); + } + reader.skip_whitespace(); + if !reader.can_read() || reader.peek() != '=' { + return Err(CommandError::tr_at("argument.block.property.novalue", &[&name, &id], reader)); + } + reader.skip(); + reader.skip_whitespace(); + let vat = reader.cursor; + let value = reader.read_string()?; + if let Some((_, values)) = property + && !values.contains(&value) + { + reader.cursor = vat; + return Err(CommandError::tr_at("argument.block.property.invalid", &[&id, &value, &name], reader)); + } + properties.push((name, value)); + reader.skip_whitespace(); + if reader.can_read() && reader.peek() == ',' { + reader.skip(); + continue; + } + if !reader.can_read() || reader.peek() != ']' { + return Err(CommandError::tr_at("argument.block.property.unclosed", &[], reader)); + } + } + if !reader.can_read() { + return Err(CommandError::tr_at("argument.block.property.unclosed", &[], reader)); + } + reader.skip(); + } + let nbt = if reader.can_read() && reader.peek() == '{' { Some(read_braced(reader, '{', '}')?) } else { None }; + Ok(BlockInput { id, properties, tag, nbt }) +} +/// Skip a balanced bracketed section (SNBT or component list) and return it. +fn read_braced(reader: &mut Reader, open: char, close: char) -> CmdResult { + let start = reader.cursor; + let mut depth = 0; + let mut quote: Option = None; + while reader.can_read() { + let c = reader.read(); + match quote { + Some(q) if c == '\\' => { + let _ = q; + reader.skip(); + } + Some(q) if c == q => quote = None, + Some(_) => {} + None if c == '"' || c == '\'' => quote = Some(c), + None if c == open || c == '[' || c == '{' => depth += 1, + None if c == close || c == ']' || c == '}' => { + depth -= 1; + if depth == 0 { + return Ok(reader.string[start..reader.cursor].to_owned()); + } + } + None => {} + } + } + Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)) +} +fn suggest_block(builder: &mut SuggestionsBuilder, reg: &Registries, tags: bool) { + let remaining = builder.remaining().to_owned(); + if let Some(open) = remaining.find('[') { + let id = normalize(&remaining[..open]); + let Some(props) = reg.blocks.get(&id) else { return }; + let inside = &remaining[open + 1..]; + if inside.contains(']') { + return; + } + let part_start = inside.rfind(',').map_or(0, |i| i + 1); + let part = &inside[part_start..]; + let base = builder.start + open + 1 + part_start; + let used: Vec<&str> = inside.split(',').filter_map(|p| p.split_once('=').map(|(n, _)| n.trim())).collect(); + match part.split_once('=') { + Some((name, value)) => { + let mut b = builder.offset(base + name.len() + 1); + if let Some((_, values)) = props.iter().find(|(n, _)| n == name.trim()) { + if values.iter().any(|v| v == value) { + let mut end = builder.offset(builder.input.len()); + if used.len() < props.len() { + end.suggest(","); + } + end.suggest("]"); + builder.out.extend(end.out); + } else { + b.suggest_matching(values.iter().map(String::as_str)); + } + } + builder.out.extend(b.out); + } + None => { + let mut b = builder.offset(base); + for (n, _) in props { + if !used.contains(&n.as_str()) && n.starts_with(part.trim()) { + b.suggest(format!("{n}=")); + } + } + if part.is_empty() { + b.suggest("]"); + } + builder.out.extend(b.out); + } + } + return; + } + let id = normalize(&remaining); + if !remaining.is_empty() && reg.blocks.get(&id).is_some_and(|p| !p.is_empty()) { + let mut end = builder.offset(builder.input.len()); + end.suggest("["); + builder.out.extend(end.out); + } + let ids: Vec = reg.blocks.keys().cloned().collect(); + suggest_resources(builder, &ids, ""); + if tags { + suggest_resources(builder, ®.block_tags, "#"); + } +} +fn parse_item(reader: &mut Reader, reg: &Registries, predicate: bool) -> CmdResult { + let start = reader.cursor; + if predicate && reader.can_read() && reader.peek() == '*' { + reader.skip(); + return Ok(ItemInput { id: "*".into(), tag: false, any: true, components: None }); + } + let tag = reader.can_read() && reader.peek() == '#'; + if tag && !predicate { + return Err(CommandError::tr_at("argument.item.tag.disallowed", &[], reader)); + } + if tag { + reader.skip(); + } + let id = read_id(reader)?; + let known = if tag { reg.item_tags.is_empty() || reg.item_tags.contains(&id) } else { reg.items.is_empty() || reg.items.contains(&id) }; + if !known { + reader.cursor = start; + let key = if tag { "arguments.item.tag.unknown" } else { "argument.item.id.invalid" }; + return Err(CommandError::tr_at(key, &[&id], reader)); + } + let components = if reader.can_read() && reader.peek() == '[' { Some(read_braced(reader, '[', ']')?) } else { None }; + Ok(ItemInput { id, tag, any: false, components }) +} +/// TimeArgument units. +fn time_unit(unit: &str) -> Option { + match unit { + "" | "t" => Some(1), + "s" => Some(20), + "d" => Some(24000), + _ => None, + } +} + +impl ArgType { + pub fn parse(&self, reader: &mut Reader, reg: &Registries) -> CmdResult { + let start = reader.cursor; + Ok(match self { + ArgType::Bool => Arg::Bool(reader.read_boolean()?), + ArgType::Integer { min, max } => { + let v = reader.read_int()?; + if v < *min { + reader.cursor = start; + return Err(CommandError::tr_at("argument.integer.low", &[min, &v], reader)); + } + if v > *max { + reader.cursor = start; + return Err(CommandError::tr_at("argument.integer.big", &[max, &v], reader)); + } + Arg::Int(v) + } + ArgType::Float { min, max } => { + let v = reader.read_float()?; + if v < *min { + reader.cursor = start; + return Err(CommandError::tr_at("argument.float.low", &[min, &v], reader)); + } + if v > *max { + reader.cursor = start; + return Err(CommandError::tr_at("argument.float.big", &[max, &v], reader)); + } + Arg::Float(v) + } + ArgType::Double { min, max } => { + let v = reader.read_double()?; + if v < *min { + reader.cursor = start; + return Err(CommandError::tr_at("argument.double.low", &[min, &v], reader)); + } + if v > *max { + reader.cursor = start; + return Err(CommandError::tr_at("argument.double.big", &[max, &v], reader)); + } + Arg::Double(v) + } + ArgType::Word => Arg::Str(reader.read_unquoted_string().to_owned()), + ArgType::Str => Arg::Str(reader.read_string()?), + ArgType::Greedy | ArgType::Message => { + let s = reader.remaining().to_owned(); + reader.cursor = reader.string.len(); + Arg::Str(s) + } + ArgType::Entity { single, players } => { + let s = parse_selector(reader, reg)?; + if s.limit > 1 && *single { + reader.cursor = start; + let key = if *players { "argument.player.toomany" } else { "argument.entity.toomany" }; + return Err(CommandError::tr_at(key, &[], reader)); + } + if s.include_entities && *players && !s.is_self() { + reader.cursor = start; + return Err(CommandError::tr_at("argument.player.entities", &[], reader)); + } + Arg::Entity(s) + } + ArgType::BlockPos => { + if reader.can_read() && reader.peek() == '^' { + Arg::Coords(parse_local(reader)?) + } else { + Arg::Coords(parse_world(reader, true, false)?) + } + } + ArgType::Vec3 { center } => { + if reader.can_read() && reader.peek() == '^' { + Arg::Coords(parse_local(reader)?) + } else { + Arg::Coords(parse_world(reader, false, *center)?) + } + } + ArgType::Rotation => { + if !reader.can_read() { + return Err(CommandError::tr_at("argument.rotation.incomplete", &[], reader)); + } + let yaw = parse_coord_double(reader, false)?; + if !reader.can_read() || reader.peek() != ' ' { + reader.cursor = start; + return Err(CommandError::tr_at("argument.rotation.incomplete", &[], reader)); + } + reader.skip(); + let pitch = parse_coord_double(reader, false)?; + Arg::Coords(Coordinates::World([yaw, pitch, Coord { relative: true, value: 0.0 }])) + } + ArgType::Angle => { + if !reader.can_read() { + return Err(CommandError::tr_at("argument.angle.incomplete", &[], reader)); + } + let relative = reader.peek() == '~'; + if relative { + reader.skip(); + } + let value = if reader.can_read() && reader.peek() != ' ' { f64::from(reader.read_float()?) } else { 0.0 }; + if value.is_nan() || value.is_infinite() { + return Err(CommandError::tr_at("argument.angle.invalid", &[], reader)); + } + Arg::Angle(Coord { relative, value }) + } + ArgType::Item => Arg::Item(parse_item(reader, reg, false)?), + ArgType::ItemPredicate => Arg::Item(parse_item(reader, reg, true)?), + ArgType::BlockState => Arg::Block(parse_block(reader, reg, false)?), + ArgType::BlockPredicate => Arg::Block(parse_block(reader, reg, true)?), + ArgType::Resource(kind) => { + let id = read_id(reader)?; + let values = kind.values(reg); + if !values.is_empty() && !values.contains(&id) { + reader.cursor = start; + return Err(CommandError::new(crate::text::Text::tr("argument.resource.not_found", &[&id, &kind.registry()]))); + } + Arg::Resource(id) + } + ArgType::Id(_) => Arg::Resource(read_id(reader)?), + ArgType::Dimension => { + let id = read_id(reader)?; + if !reg.dimensions.is_empty() && !reg.dimensions.contains(&id) { + return Err(CommandError::tr("argument.dimension.invalid", &[&id])); + } + Arg::Resource(id) + } + ArgType::Time { min } => { + let v = reader.read_float()?; + let unit = reader.read_unquoted_string(); + let Some(m) = time_unit(unit) else { + return Err(CommandError::tr("argument.time.invalid_unit", &[])); + }; + let ticks = (v * m as f32).round() as i32; + if ticks < *min { + return Err(CommandError::tr("argument.time.tick_count_too_low", &[min, &ticks])); + } + Arg::Int(ticks) + } + ArgType::GameMode => { + let name = reader.read_unquoted_string(); + match GameMode::from_name(name) { + Some(m) => Arg::GameMode(m), + None => { + reader.cursor = start; + return Err(CommandError::tr_at("argument.gamemode.invalid", &[&name], reader)); + } + } + } + ArgType::Nbt => { + if !reader.can_read() || reader.peek() != '{' { + return Err(CommandError::tr_at("argument.nbt.expected.compound", &[], reader)); + } + Arg::Str(read_braced(reader, '{', '}')?) + } + ArgType::Anchor => { + let name = reader.read_unquoted_string(); + match name { + "eyes" => Arg::Anchor(true), + "feet" => Arg::Anchor(false), + _ => { + reader.cursor = start; + return Err(CommandError::tr_at("argument.anchor.invalid", &[&name], reader)); + } + } + } + }) + } + pub fn suggest(&self, builder: &mut SuggestionsBuilder, reg: &Registries, context: &Context, _name: &str) { + let _ = context; + match self { + ArgType::Bool => builder.suggest_matching(["true", "false"]), + ArgType::Entity { .. } => suggest_selector(builder, reg), + ArgType::BlockPos => suggest_coordinates(builder, reg), + ArgType::Vec3 { .. } => suggest_coordinates(builder, reg), + ArgType::Rotation => { + if builder.remaining().is_empty() { + builder.suggest("~"); + builder.suggest("~ ~"); + } + } + ArgType::Angle => { + if builder.remaining().is_empty() { + builder.suggest("~"); + } + } + ArgType::Item | ArgType::ItemPredicate => { + let items = reg.items.clone(); + suggest_resources(builder, &items, ""); + if matches!(self, ArgType::ItemPredicate) { + suggest_resources(builder, ®.item_tags, "#"); + } + } + ArgType::BlockState => suggest_block(builder, reg, false), + ArgType::BlockPredicate => suggest_block(builder, reg, true), + ArgType::Resource(kind) => { + let values = kind.values(reg).to_vec(); + suggest_resources(builder, &values, ""); + } + ArgType::Id(list) => { + let values = match *list { + "time_markers" => reg.time_markers.clone(), + _ => Vec::new(), + }; + suggest_resources(builder, &values, ""); + } + ArgType::Dimension => { + let dims = reg.dimensions.clone(); + suggest_resources(builder, &dims, ""); + } + ArgType::Time { .. } => { + let mut r = Reader::new(builder.remaining()); + if r.read_float().is_ok() { + let mut b = builder.offset(builder.start + r.cursor); + b.suggest_matching(["d", "s", "t"]); + builder.out.extend(b.out); + } + } + ArgType::GameMode => builder.suggest_matching(GameMode::ALL.map(GameMode::name)), + ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), + ArgType::Message => { + // MessageArgument suggests selectors and names for the last word. + let rem = builder.remaining(); + let word_start = rem.rfind(' ').map_or(0, |i| i + 1); + let mut b = builder.offset(builder.start + word_start); + if b.remaining().starts_with('@') || !b.remaining().is_empty() { + let players = reg.players.clone(); + b.suggest_matching(players.iter().map(String::as_str)); + if b.remaining().starts_with('@') { + b.suggest_matching(SELECTORS.map(|s| s.0)); + } + } + builder.out.extend(b.out); + } + _ => {} + } + } +} diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs new file mode 100644 index 000000000..f186f02cf --- /dev/null +++ b/crates/horizon-client/src/command/mod.rs @@ -0,0 +1,639 @@ +//! A port of Brigadier (the command library vanilla uses): a string reader, +//! literal/argument node trees with redirects, parsing that tries every +//! relevant child and keeps the best result, completion suggestions, smart +//! usage text and the vanilla error messages. Argument types live in +//! [`args`]; the vanilla command tree in [`vanilla`]. +pub mod args; +pub mod vanilla; + +use crate::text::Text; +pub use args::{Arg, ArgType, Registries}; + +/// A command error (CommandSyntaxException): the message and, for parse +/// errors, the input and cursor it occurred at. +#[derive(Clone, Debug, PartialEq)] +pub struct CommandError { + pub message: Text, + pub input: Option, + pub cursor: usize, + /// BuiltInExceptions.literalIncorrect (summarised specially by the chat UI). + pub literal_incorrect: bool, +} +impl CommandError { + pub fn new(message: Text) -> Self { + Self { message, input: None, cursor: 0, literal_incorrect: false } + } + pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self { + Self::new(Text::tr(key, args)) + } + pub fn at(message: Text, reader: &Reader) -> Self { + Self { message, input: Some(reader.string.to_owned()), cursor: reader.cursor, literal_incorrect: false } + } + pub fn tr_at(key: &str, args: &[&dyn std::fmt::Display], reader: &Reader) -> Self { + Self::at(Text::tr(key, args), reader) + } + /// CommandSyntaxException.getContext: up to ten characters before the + /// cursor followed by "<--[HERE]". + pub fn context(&self) -> Option { + let input = self.input.as_ref()?; + let cursor = self.cursor.min(input.len()); + let start = input.floor_char_boundary(cursor.saturating_sub(10)); + let mut out = String::new(); + if cursor > 10 { + out.push_str("..."); + } + out.push_str(&input[start..cursor]); + out.push_str("<--[HERE]"); + Some(out) + } + /// The message as shown by command suggestions ("... at position N: ..."). + pub fn with_context(&self) -> Text { + match self.context() { + Some(context) => Text::translate("command.context.parse_error", &[self.message.clone(), Text::literal(self.cursor.to_string()), Text::literal(context)]), + None => self.message.clone(), + } + } +} +pub type CmdResult = Result; + +/// Brigadier StringReader over a command line (byte cursor on char boundaries). +#[derive(Clone, Debug)] +pub struct Reader<'a> { + pub string: &'a str, + pub cursor: usize, +} +impl<'a> Reader<'a> { + pub fn new(string: &'a str) -> Self { + Self { string, cursor: 0 } + } + pub fn can_read(&self) -> bool { + self.cursor < self.string.len() + } + pub fn can_read_n(&self, n: usize) -> bool { + self.string[self.cursor..].chars().take(n).count() == n + } + pub fn peek(&self) -> char { + self.string[self.cursor..].chars().next().unwrap_or('\0') + } + pub fn peek_at(&self, offset: usize) -> char { + self.string[self.cursor..].chars().nth(offset).unwrap_or('\0') + } + pub fn skip(&mut self) { + self.cursor += self.peek().len_utf8(); + } + pub fn read(&mut self) -> char { + let c = self.peek(); + self.skip(); + c + } + pub fn remaining(&self) -> &'a str { + &self.string[self.cursor..] + } + pub fn skip_whitespace(&mut self) { + while self.can_read() && self.peek().is_whitespace() { + self.skip(); + } + } + pub fn is_allowed_number(c: char) -> bool { + c.is_ascii_digit() || c == '.' || c == '-' + } + pub fn is_allowed_in_unquoted(c: char) -> bool { + c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '+') + } + fn read_number_text(&mut self) -> &'a str { + let start = self.cursor; + while self.can_read() && Self::is_allowed_number(self.peek()) { + self.skip(); + } + &self.string[start..self.cursor] + } + fn number(&mut self, kind: &str) -> CmdResult { + let start = self.cursor; + let text = self.read_number_text(); + if text.is_empty() { + return Err(CommandError::tr_at(&format!("parsing.{kind}.expected"), &[], self)); + } + // Java's parsers reject a trailing '.'-less exponent etc. the same way. + match text.parse::() { + Ok(v) if !(kind == "int" || kind == "long") || !text.contains('.') => Ok(v), + _ => { + self.cursor = start; + Err(CommandError::tr_at(&format!("parsing.{kind}.invalid"), &[&text], self)) + } + } + } + pub fn read_int(&mut self) -> CmdResult { + self.number("int") + } + pub fn read_long(&mut self) -> CmdResult { + self.number("long") + } + pub fn read_double(&mut self) -> CmdResult { + self.number("double") + } + pub fn read_float(&mut self) -> CmdResult { + self.number("float") + } + pub fn read_unquoted_string(&mut self) -> &'a str { + let start = self.cursor; + while self.can_read() && Self::is_allowed_in_unquoted(self.peek()) { + self.skip(); + } + &self.string[start..self.cursor] + } + pub fn read_string_until(&mut self, terminator: char) -> CmdResult { + let mut out = String::new(); + let mut escaped = false; + while self.can_read() { + let c = self.read(); + if escaped { + if c == terminator || c == '\\' { + out.push(c); + escaped = false; + } else { + self.cursor -= c.len_utf8(); + return Err(CommandError::tr_at("parsing.quote.escape", &[&c], self)); + } + } else if c == '\\' { + escaped = true; + } else if c == terminator { + return Ok(out); + } else { + out.push(c); + } + } + Err(CommandError::tr_at("parsing.quote.expected.end", &[], self)) + } + pub fn read_quoted_string(&mut self) -> CmdResult { + if !self.can_read() { + return Ok(String::new()); + } + let next = self.peek(); + if next != '"' && next != '\'' { + return Err(CommandError::tr_at("parsing.quote.expected.start", &[], self)); + } + self.skip(); + self.read_string_until(next) + } + pub fn read_string(&mut self) -> CmdResult { + if !self.can_read() { + return Ok(String::new()); + } + let next = self.peek(); + if next == '"' || next == '\'' { + self.skip(); + return self.read_string_until(next); + } + Ok(self.read_unquoted_string().to_owned()) + } + pub fn read_boolean(&mut self) -> CmdResult { + let start = self.cursor; + let value = self.read_string()?; + if value.is_empty() { + return Err(CommandError::tr_at("parsing.bool.expected", &[], self)); + } + match value.as_str() { + "true" => Ok(true), + "false" => Ok(false), + _ => { + self.cursor = start; + Err(CommandError::tr_at("parsing.bool.invalid", &[&value], self)) + } + } + } + pub fn expect(&mut self, c: char) -> CmdResult<()> { + if !self.can_read() || self.peek() != c { + return Err(CommandError::tr_at("parsing.expected", &[&c], self)); + } + self.skip(); + Ok(()) + } +} + +pub type Range = (usize, usize); +#[derive(Clone, Debug)] +pub enum NodeKind { + Root, + Literal(String), + Argument { name: String, ty: ArgType }, +} +#[derive(Clone, Debug)] +pub struct Node { + pub kind: NodeKind, + pub children: Vec, + /// The command id run when parsing ends here. + pub command: Option<&'static str>, + pub redirect: Option, + /// Required permission level (0 everyone, 2 game masters, 4 owners). + pub permission: u8, +} +impl Node { + pub fn name(&self) -> &str { + match &self.kind { + NodeKind::Root => "", + NodeKind::Literal(l) => l, + NodeKind::Argument { name, .. } => name, + } + } + /// CommandNode.getUsageText. + pub fn usage_text(&self) -> String { + match &self.kind { + NodeKind::Root => String::new(), + NodeKind::Literal(l) => l.clone(), + NodeKind::Argument { name, .. } => format!("<{name}>"), + } + } +} +#[derive(Clone, Debug)] +pub struct ParsedArg { + pub name: String, + pub value: Arg, + pub range: Range, +} +/// CommandContextBuilder: the nodes and arguments parsed so far. +#[derive(Clone, Debug)] +pub struct Context { + pub root: usize, + pub nodes: Vec<(usize, Range)>, + pub args: Vec, + pub command: Option<&'static str>, + pub range: Range, + pub child: Option>, + /// Literal words parsed so far (mode keywords such as `masked`). + pub literals: Vec, +} +impl Context { + fn new(root: usize, start: usize) -> Self { + Self { root, nodes: Vec::new(), args: Vec::new(), command: None, range: (start, start), child: None, literals: Vec::new() } + } + /// Whether the literal `word` was parsed (in this context). + pub fn has(&self, word: &str) -> bool { + self.literals.iter().any(|l| l == word) + } + fn with_node(&mut self, node: usize, range: Range) { + self.nodes.push((node, range)); + self.range = (self.range.0.min(range.0), self.range.1.max(range.1)); + } + pub fn last_child(&self) -> &Context { + let mut c = self; + while let Some(child) = &c.child { + c = child; + } + c + } + pub fn get(&self, name: &str) -> Option<&Arg> { + self.args.iter().rev().find(|a| a.name == name).map(|a| &a.value) + } + /// CommandContextBuilder.findSuggestionContext: the node whose children + /// complete the text at `cursor`, and where that text starts. + pub fn suggestion_context(&self, cursor: usize) -> (usize, usize, &Context) { + if self.range.1 < cursor { + if let Some(child) = &self.child { + return child.suggestion_context(cursor); + } + if let Some((node, range)) = self.nodes.last() { + return (*node, range.1 + 1, self); + } + return (self.root, self.range.0, self); + } + let mut prev = self.root; + for (node, range) in &self.nodes { + if range.0 <= cursor && cursor <= range.1 { + return (prev, range.0, self); + } + prev = *node; + } + (prev, self.range.0, self) + } +} +#[derive(Clone, Debug)] +pub struct ParseResults { + pub context: Context, + pub input: String, + pub cursor: usize, + pub errors: Vec<(usize, CommandError)>, +} +impl ParseResults { + pub fn can_read(&self) -> bool { + self.cursor < self.input.len() + } + /// Commands.getParseException. + pub fn error(&self) -> Option { + if !self.can_read() { + return None; + } + if self.errors.len() == 1 { + return Some(self.errors[0].1.clone()); + } + let reader = Reader { string: &self.input, cursor: self.cursor }; + Some(if self.context.range.0 == self.context.range.1 { + CommandError::tr_at("command.unknown.command", &[], &reader) + } else { + CommandError::tr_at("command.unknown.argument", &[], &reader) + }) + } + /// The executable context and command id, or the vanilla error. + pub fn executable(&self) -> CmdResult<(&Context, &'static str)> { + if let Some(e) = self.error() { + return Err(e); + } + let last = self.context.last_child(); + match last.command { + Some(id) => Ok((last, id)), + None => Err(CommandError::tr_at("command.unknown.command", &[], &Reader { string: &self.input, cursor: self.cursor })), + } + } +} +/// A completion: replace `range` of the input with `text`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Suggestion { + pub range: Range, + pub text: String, + pub tooltip: Option, +} +impl Suggestion { + /// Suggestion.apply. + pub fn apply(&self, input: &str) -> String { + let (s, e) = (self.range.0.min(input.len()), self.range.1.min(input.len())); + format!("{}{}{}", &input[..s], self.text, &input[e..]) + } +} +/// SuggestionsBuilder: suggestions for the text from `start` to the cursor. +pub struct SuggestionsBuilder<'a> { + pub input: &'a str, + pub start: usize, + pub out: Vec, +} +impl<'a> SuggestionsBuilder<'a> { + pub fn new(input: &'a str, start: usize) -> Self { + Self { input, start: start.min(input.len()), out: Vec::new() } + } + pub fn remaining(&self) -> &'a str { + &self.input[self.start..] + } + pub fn remaining_lower(&self) -> String { + self.remaining().to_lowercase() + } + pub fn suggest(&mut self, text: impl Into) { + let text = text.into(); + if text != self.remaining() { + self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: None }); + } + } + pub fn suggest_tooltip(&mut self, text: impl Into, tooltip: impl Into) { + let text = text.into(); + if text != self.remaining() { + self.out.push(Suggestion { range: (self.start, self.input.len()), text, tooltip: Some(tooltip.into()) }); + } + } + pub fn offset(&self, start: usize) -> SuggestionsBuilder<'a> { + SuggestionsBuilder::new(self.input, start) + } + /// SharedSuggestionProvider.suggest: candidates starting with the remaining text. + pub fn suggest_matching<'b>(&mut self, candidates: impl IntoIterator) { + let lower = self.remaining_lower(); + for c in candidates { + if c.to_lowercase().starts_with(&lower) { + self.suggest(c); + } + } + } +} +/// Suggestions.create: merged, expanded to a common range and sorted case-insensitively. +pub fn merge_suggestions(input: &str, list: Vec) -> (Range, Vec) { + if list.is_empty() { + return ((0, 0), Vec::new()); + } + let start = list.iter().map(|s| s.range.0).min().unwrap_or(0); + let end = list.iter().map(|s| s.range.1).max().unwrap_or(0); + let mut out: Vec = Vec::new(); + for s in list { + // Suggestion.expand: pad the text with the input around it. + let text = format!("{}{}{}", &input[start..s.range.0], s.text, &input[s.range.1..end]); + let expanded = Suggestion { range: (start, end), text, tooltip: s.tooltip }; + if !out.iter().any(|o| o.text == expanded.text) { + out.push(expanded); + } + } + out.sort_by(|a, b| a.text.to_lowercase().cmp(&b.text.to_lowercase())); + ((start, end), out) +} + +/// The command tree (CommandDispatcher). Node 0 is the root. +#[derive(Clone, Debug)] +pub struct Dispatcher { + pub nodes: Vec, +} +impl Default for Dispatcher { + fn default() -> Self { + Self::new() + } +} +impl Dispatcher { + pub fn new() -> Self { + Self { nodes: vec![Node { kind: NodeKind::Root, children: Vec::new(), command: None, redirect: None, permission: 0 }] } + } + fn add(&mut self, parent: usize, kind: NodeKind) -> usize { + let name = match &kind { + NodeKind::Literal(l) => l.clone(), + NodeKind::Argument { name, .. } => name.clone(), + NodeKind::Root => String::new(), + }; + // CommandNode.addChild merges same-named children. + if let Some(&existing) = self.nodes[parent].children.iter().find(|&&c| self.nodes[c].name() == name) { + return existing; + } + let permission = self.nodes[parent].permission; + self.nodes.push(Node { kind, children: Vec::new(), command: None, redirect: None, permission }); + let id = self.nodes.len() - 1; + self.nodes[parent].children.push(id); + id + } + pub fn literal(&mut self, parent: usize, name: &str) -> usize { + self.add(parent, NodeKind::Literal(name.to_owned())) + } + pub fn argument(&mut self, parent: usize, name: &str, ty: ArgType) -> usize { + self.add(parent, NodeKind::Argument { name: name.to_owned(), ty }) + } + pub fn executes(&mut self, node: usize, command: &'static str) -> usize { + self.nodes[node].command = Some(command); + node + } + pub fn redirect(&mut self, node: usize, target: usize) -> usize { + self.nodes[node].redirect = Some(target); + node + } + pub fn requires(&mut self, node: usize, level: u8) -> usize { + self.nodes[node].permission = level; + node + } + /// A root literal by name. + pub fn find(&self, name: &str) -> Option { + self.nodes[0].children.iter().copied().find(|&c| self.nodes[c].name() == name) + } + fn relevant(&self, node: usize, reader: &Reader) -> Vec { + let children = &self.nodes[node].children; + let literals: Vec = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Literal(_))).collect(); + let arguments: Vec = children.iter().copied().filter(|&c| matches!(self.nodes[c].kind, NodeKind::Argument { .. })).collect(); + if literals.is_empty() { + return arguments; + } + let rest = reader.remaining(); + let word = rest.split(' ').next().unwrap_or(""); + match literals.iter().find(|&&l| self.nodes[l].name() == word) { + Some(&l) => vec![l], + None => arguments, + } + } + fn parse_node(&self, node: usize, reader: &mut Reader, context: &mut Context, reg: &Registries) -> CmdResult<()> { + let start = reader.cursor; + match &self.nodes[node].kind { + NodeKind::Root => Ok(()), + NodeKind::Literal(literal) => { + if reader.remaining().starts_with(literal.as_str()) { + let end = start + literal.len(); + reader.cursor = end; + if !reader.can_read() || reader.peek() == ' ' { + context.with_node(node, (start, end)); + context.literals.push(literal.clone()); + return Ok(()); + } + reader.cursor = start; + } + let mut e = CommandError::tr_at("argument.literal.incorrect", &[literal], reader); + e.literal_incorrect = true; + Err(e) + } + NodeKind::Argument { name, ty } => { + let value = ty.parse(reader, reg)?; + let range = (start, reader.cursor); + context.args.push(ParsedArg { name: name.clone(), value, range }); + context.with_node(node, range); + Ok(()) + } + } + } + fn parse_nodes(&self, node: usize, input: &str, cursor: usize, so_far: &Context, reg: &Registries, level: u8) -> ParseResults { + let mut errors = Vec::new(); + let mut potentials: Vec = Vec::new(); + let original = Reader { string: input, cursor }; + for child in self.relevant(node, &original) { + if self.nodes[child].permission > level { + continue; + } + let mut context = so_far.clone(); + let mut reader = original.clone(); + let parsed = self.parse_node(child, &mut reader, &mut context, reg).and_then(|()| { + if reader.can_read() && reader.peek() != ' ' { + Err(CommandError::tr_at("command.expected.separator", &[], &reader)) + } else { + Ok(()) + } + }); + if let Err(e) = parsed { + errors.push((child, e)); + continue; + } + context.command = self.nodes[child].command; + let redirect = self.nodes[child].redirect; + if reader.can_read_n(if redirect.is_none() { 2 } else { 1 }) { + reader.skip(); + if let Some(target) = redirect { + let child_context = Context::new(target, reader.cursor); + let parse = self.parse_nodes(target, input, reader.cursor, &child_context, reg, level); + context.child = Some(Box::new(parse.context)); + return ParseResults { context, input: input.to_owned(), cursor: parse.cursor, errors: parse.errors }; + } + potentials.push(self.parse_nodes(child, input, reader.cursor, &context, reg, level)); + } else { + potentials.push(ParseResults { context, input: input.to_owned(), cursor: reader.cursor, errors: Vec::new() }); + } + } + if !potentials.is_empty() { + // Prefer fully read input, then results without errors (stable sort). + potentials.sort_by_key(|p| (p.can_read(), !p.errors.is_empty())); + return potentials.swap_remove(0); + } + ParseResults { context: so_far.clone(), input: input.to_owned(), cursor, errors } + } + /// CommandDispatcher.parse from the start of `input` (no leading slash). + pub fn parse(&self, input: &str, reg: &Registries) -> ParseResults { + self.parse_at(input, 0, reg) + } + /// Parse starting at byte `start` (after a leading '/'). + pub fn parse_at(&self, input: &str, start: usize, reg: &Registries) -> ParseResults { + let context = Context::new(0, start); + self.parse_nodes(0, input, start, &context, reg, reg.permission) + } + /// CommandDispatcher.getCompletionSuggestions at `cursor`. + pub fn suggestions(&self, parse: &ParseResults, cursor: usize, reg: &Registries) -> (Range, Vec) { + let (parent, start, context) = parse.context.suggestion_context(cursor); + let start = start.min(cursor); + let truncated = &parse.input[..cursor.min(parse.input.len())]; + let mut all = Vec::new(); + for &child in &self.nodes[parent].children { + if self.nodes[child].permission > reg.permission { + continue; + } + let mut builder = SuggestionsBuilder::new(truncated, start); + match &self.nodes[child].kind { + NodeKind::Literal(l) => { + if l.to_lowercase().starts_with(&builder.remaining_lower()) { + builder.suggest(l.clone()); + } + } + NodeKind::Argument { ty, name } => ty.suggest(&mut builder, reg, context, name), + NodeKind::Root => {} + } + all.extend(builder.out); + } + merge_suggestions(truncated, all) + } + fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option { + let n = &self.nodes[node]; + if n.permission > level { + return None; + } + let this = if optional { format!("[{}]", n.usage_text()) } else { n.usage_text() }; + let child_optional = n.command.is_some(); + let (open, close) = if child_optional { ("[", "]") } else { ("(", ")") }; + if !deep { + if let Some(r) = n.redirect { + let target = if r == 0 { "...".to_owned() } else { format!("-> {}", self.nodes[r].usage_text()) }; + return Some(format!("{this} {target}")); + } + let children: Vec = n.children.iter().copied().filter(|&c| self.nodes[c].permission <= level).collect(); + if children.len() == 1 { + if let Some(usage) = self.smart_usage_of(children[0], child_optional, child_optional, level) { + return Some(format!("{this} {usage}")); + } + } else if children.len() > 1 { + let mut child_usage: Vec = Vec::new(); + for &c in &children { + if let Some(u) = self.smart_usage_of(c, child_optional, true, level) + && !child_usage.contains(&u) + { + child_usage.push(u); + } + } + if child_usage.len() == 1 { + let usage = &child_usage[0]; + return Some(format!("{this} {}", if child_optional { format!("[{usage}]") } else { usage.clone() })); + } + if child_usage.len() > 1 { + let alternatives: Vec = children.iter().map(|&c| self.nodes[c].usage_text()).collect(); + return Some(format!("{this} {open}{}{close}", alternatives.join("|"))); + } + } + } + Some(this) + } + /// CommandDispatcher.getSmartUsage: one line per child of `node`. + pub fn smart_usage(&self, node: usize, level: u8) -> Vec<(usize, String)> { + let optional = self.nodes[node].command.is_some(); + self.nodes[node].children.iter().filter_map(|&c| self.smart_usage_of(c, optional, false, level).map(|u| (c, u))).collect() + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/horizon-client/src/command/tests.rs b/crates/horizon-client/src/command/tests.rs new file mode 100644 index 000000000..f2645a4b2 --- /dev/null +++ b/crates/horizon-client/src/command/tests.rs @@ -0,0 +1,139 @@ +use super::{args::*, vanilla, *}; + +fn reg() -> Registries { + let mut r = Registries { permission: 4, ..Registries::default() }; + r.items = vec!["minecraft:diamond".into(), "minecraft:diamond_sword".into(), "minecraft:stone".into()]; + r.blocks.insert("minecraft:stone".into(), vec![]); + r.blocks.insert( + "minecraft:oak_stairs".into(), + vec![("facing".into(), vec!["north".into(), "south".into()]), ("half".into(), vec!["top".into(), "bottom".into()])], + ); + r.summonable = vec!["minecraft:pig".into(), "minecraft:zombie".into()]; + r.entity_types = vec!["minecraft:pig".into(), "minecraft:player".into(), "minecraft:zombie".into()]; + r.players = vec!["Player".into()]; + r.dimensions = vec!["minecraft:overworld".into()]; + r.time_markers = vec!["minecraft:day".into(), "minecraft:noon".into()]; + r +} +fn run(input: &str) -> CmdResult<(String, Vec)> { + let reg = reg(); + let parse = vanilla::dispatcher().parse(input, ®); + let (ctx, id) = parse.executable()?; + Ok((id.to_owned(), ctx.args.iter().map(|a| a.name.clone()).collect())) +} +fn suggestions(input: &str) -> Vec { + let reg = reg(); + let d = vanilla::dispatcher(); + let parse = d.parse(input, ®); + d.suggestions(&parse, input.len(), ®).1.into_iter().map(|s| s.text).collect() +} + +#[test] +fn reader_matches_brigadier() { + let mut r = Reader::new("12 -3.5 abc \"q\\\"x\" true"); + assert_eq!(r.read_int().unwrap(), 12); + r.skip(); + assert_eq!(r.read_double().unwrap(), -3.5); + r.skip(); + assert_eq!(r.read_unquoted_string(), "abc"); + r.skip(); + assert_eq!(r.read_string().unwrap(), "q\"x"); + r.skip(); + assert!(r.read_boolean().unwrap()); + let e = Reader::new("1.5").read_int().unwrap_err(); + assert_eq!(e.message.plain(), "parsing.int.invalid"); + assert_eq!(e.context().unwrap(), "<--[HERE]"); +} +#[test] +fn parses_vanilla_commands() { + assert_eq!(run("gamemode creative").unwrap().0, "gamemode"); + assert_eq!(run("gamemode creative @s").unwrap().1, ["gamemode", "target"]); + assert_eq!(run("give @s minecraft:diamond 64").unwrap().1, ["targets", "item", "count"]); + assert_eq!(run("tp 1 2 3").unwrap().0, "teleport.location"); + assert_eq!(run("tp Player").unwrap().0, "teleport.destination"); + assert_eq!(run("tp @s ~ ~10 ~").unwrap().0, "teleport.targets.location"); + assert_eq!(run("teleport @e[type=pig,limit=2] ^ ^ ^5 90 0").unwrap().0, "teleport.targets.location"); + assert_eq!(run("time set 1000").unwrap().0, "time.set"); + assert_eq!(run("time set 1d").unwrap().0, "time.set"); + assert_eq!(run("time set day").unwrap().0, "time.set.marker"); + assert_eq!(run("time query gametime").unwrap().0, "time.query.gametime"); + assert_eq!(run("weather rain 10s").unwrap().0, "weather"); + assert_eq!(run("xp add @s 5 levels").unwrap().0, "experience"); + assert_eq!(run("gamerule keep_inventory true").unwrap().0, "gamerule"); + assert_eq!(run("gamerule minecraft:random_tick_speed 10").unwrap().0, "gamerule"); + assert_eq!(run("fill ~ ~ ~ ~1 ~1 ~1 stone hollow").unwrap().0, "fill"); + assert_eq!(run("fill 0 0 0 1 1 1 minecraft:oak_stairs[facing=north] replace stone").unwrap().0, "fill"); + assert_eq!(run("clone 0 0 0 1 1 1 5 5 5 masked move").unwrap().0, "clone"); + assert_eq!(run("setblock ~ ~1 ~ oak_stairs[half=top] keep").unwrap().0, "setblock"); + assert_eq!(run("summon zombie ~ ~ ~ {NoAI:1b}").unwrap().0, "summon"); + assert_eq!(run("difficulty hard").unwrap().0, "difficulty"); + assert_eq!(run("say hello @p").unwrap().0, "say"); + let reg = reg(); + let parse = vanilla::dispatcher().parse("clone 0 0 0 1 1 1 5 5 5 strict filtered stone force", ®); + let (ctx, _) = parse.executable().unwrap(); + assert!(ctx.has("strict") && ctx.has("filtered") && ctx.has("force") && !ctx.has("move")); +} +#[test] +fn vanilla_error_messages() { + let e = run("foo").unwrap_err(); + assert_eq!(e.message.plain(), "command.unknown.command"); + assert_eq!(e.cursor, 0); + let e = run("gamemode").unwrap_err(); + assert_eq!(e.message.plain(), "command.unknown.command"); + let e = run("gamemode creatve").unwrap_err(); + assert_eq!(e.message.plain(), "argument.gamemode.invalid"); + assert_eq!(e.cursor, 9); + let e = run("give @s minecraft:dirt").unwrap_err(); + assert_eq!(e.message.plain(), "argument.item.id.invalid"); + let e = run("give @s diamond 0").unwrap_err(); + assert_eq!(e.message.plain(), "argument.integer.low"); + let e = run("gamemode creative @e").unwrap_err(); + assert_eq!(e.message.plain(), "argument.player.entities"); + let e = run("setblock 1 2").unwrap_err(); + assert_eq!(e.message.plain(), "argument.pos3d.incomplete"); + let e = run("setblock 1 2 3 oak_stairs[facing=up]").unwrap_err(); + assert_eq!(e.message.plain(), "argument.block.property.invalid"); +} +#[test] +fn suggestions_like_vanilla() { + let root = suggestions(""); + assert!(root.contains(&"gamemode".to_owned()) && root.contains(&"tp".to_owned())); + assert_eq!(suggestions("game"), ["gamemode", "gamerule"]); + assert_eq!(suggestions("gamemode "), ["adventure", "creative", "spectator", "survival"]); + assert_eq!(suggestions("gamemode c"), ["creative"]); + assert_eq!(suggestions("give @s dia"), ["minecraft:diamond", "minecraft:diamond_sword"]); + // Underscore-separated parts match too (SharedSuggestionProvider.matchesSubStr). + assert_eq!(suggestions("give @s sword"), ["minecraft:diamond_sword"]); + assert_eq!(suggestions("kill @"), ["@a", "@e", "@n", "@p", "@r", "@s"]); + assert_eq!(suggestions("kill @e"), ["["]); + assert_eq!(suggestions("kill @e[ty"), ["type="]); + assert!(suggestions("kill @e[type=").contains(&"minecraft:zombie".to_owned())); + assert_eq!(suggestions("kill @e[type=pig"), [",", "]"]); + assert_eq!(suggestions("setblock 0 0 0 oak_stairs[fa"), ["facing="]); + assert_eq!(suggestions("setblock 0 0 0 oak_stairs[facing=n"), ["north"]); + assert_eq!(suggestions("tp "), ["@a", "@e", "@n", "@p", "@r", "@s", "Player", "~", "~ ~", "~ ~ ~"]); + assert_eq!(suggestions("time set 5"), ["d", "s", "t"]); + assert!(suggestions("time set ").contains(&"minecraft:day".to_owned())); +} +#[test] +fn smart_usage_matches_brigadier() { + let d = vanilla::dispatcher(); + let usage = |name: &str| d.smart_usage(0, 4).into_iter().find(|(n, _)| d.nodes[*n].name() == name).unwrap().1; + assert_eq!(usage("gamemode"), "gamemode []"); + assert_eq!(usage("give"), "give []"); + assert_eq!(usage("kill"), "kill []"); + assert_eq!(usage("weather"), "weather (clear|rain|thunder)"); + assert_eq!(usage("tp"), "tp -> teleport"); + assert_eq!(usage("difficulty"), "difficulty [peaceful|easy|normal|hard]"); +} +#[test] +fn local_coordinates_follow_view() { + // Facing south (yaw 0) moves +Z. + let p = Coordinates::Local([0.0, 0.0, 2.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]); + assert!((p[2] - 2.0).abs() < 1e-6 && p[0].abs() < 1e-6); + // ^1 (left) while facing south is +X. + let p = Coordinates::Local([1.0, 0.0, 0.0]).position([0.0, 64.0, 0.0], [0.0, 0.0]); + assert!((p[0] - 1.0).abs() < 1e-6, "{p:?}"); + let w = Coordinates::World([Coord { relative: true, value: 1.0 }, Coord { relative: false, value: 5.0 }, Coord { relative: true, value: 0.0 }]); + assert_eq!(w.position([10.0, 64.0, 3.0], [0.0, 0.0]), [11.0, 5.0, 3.0]); +} diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs new file mode 100644 index 000000000..1f0d31e79 --- /dev/null +++ b/crates/horizon-client/src/command/vanilla.rs @@ -0,0 +1,340 @@ +//! The vanilla command tree (Commands.java registrations) for the commands +//! Horizon implements. Leaves carry command ids that the game executes; +//! mode keywords are read back from the parsed literals. +use super::{ + Dispatcher, + args::{ArgType, GameMode, Resource, integer}, +}; +use crate::gamerules::{RULES, Value}; + +/// Permission levels (Commands.LEVEL_*). +pub const ALL: u8 = 0; +pub const GAMEMASTERS: u8 = 2; + +const PLAYERS: ArgType = ArgType::Entity { single: false, players: true }; +const PLAYER: ArgType = ArgType::Entity { single: true, players: true }; +const ENTITIES: ArgType = ArgType::Entity { single: false, players: false }; +const ENTITY: ArgType = ArgType::Entity { single: true, players: false }; + +pub const DIFFICULTIES: [&str; 4] = ["peaceful", "easy", "normal", "hard"]; + +pub fn build() -> Dispatcher { + let mut d = Dispatcher::new(); + let root = 0; + + // help [] + let help = d.literal(root, "help"); + d.executes(help, "help"); + let c = d.argument(help, "command", ArgType::Greedy); + d.executes(c, "help"); + + // gamemode [] + let gm = d.literal(root, "gamemode"); + d.requires(gm, GAMEMASTERS); + let mode = d.argument(gm, "gamemode", ArgType::GameMode); + d.executes(mode, "gamemode"); + let t = d.argument(mode, "target", PLAYERS); + d.executes(t, "gamemode"); + + let dgm = d.literal(root, "defaultgamemode"); + d.requires(dgm, GAMEMASTERS); + let mode = d.argument(dgm, "gamemode", ArgType::GameMode); + d.executes(mode, "defaultgamemode"); + + // give [] + let give = d.literal(root, "give"); + d.requires(give, GAMEMASTERS); + let targets = d.argument(give, "targets", PLAYERS); + let item = d.argument(targets, "item", ArgType::Item); + d.executes(item, "give"); + let count = d.argument(item, "count", integer(1)); + d.executes(count, "give"); + + // teleport / tp + let tp = d.literal(root, "teleport"); + d.requires(tp, GAMEMASTERS); + let loc = d.argument(tp, "location", ArgType::Vec3 { center: true }); + d.executes(loc, "teleport.location"); + let dest = d.argument(tp, "destination", ENTITY); + d.executes(dest, "teleport.destination"); + let targets = d.argument(tp, "targets", ENTITIES); + let loc = d.argument(targets, "location", ArgType::Vec3 { center: true }); + d.executes(loc, "teleport.targets.location"); + let rot = d.argument(loc, "rotation", ArgType::Rotation); + d.executes(rot, "teleport.targets.location"); + let facing = d.literal(loc, "facing"); + let fe = d.literal(facing, "entity"); + let fent = d.argument(fe, "facingEntity", ENTITY); + d.executes(fent, "teleport.targets.location"); + let anchor = d.argument(fent, "facingAnchor", ArgType::Anchor); + d.executes(anchor, "teleport.targets.location"); + let floc = d.argument(facing, "facingLocation", ArgType::Vec3 { center: true }); + d.executes(floc, "teleport.targets.location"); + let dest = d.argument(targets, "destination", ENTITY); + d.executes(dest, "teleport.targets.destination"); + let alias = d.literal(root, "tp"); + d.requires(alias, GAMEMASTERS); + d.redirect(alias, tp); + + // time: clock nodes for the dimension's default clock, plus `of `. + let time = d.literal(root, "time"); + d.requires(time, GAMEMASTERS); + clock_nodes(&mut d, time); + let query = d.literal(time, "query"); + let gt = d.literal(query, "gametime"); + d.executes(gt, "time.query.gametime"); + let of = d.literal(time, "of"); + let clock = d.argument(of, "clock", ArgType::Resource(Resource::Clock)); + clock_nodes(&mut d, clock); + + // weather (clear|rain|thunder) [] + let weather = d.literal(root, "weather"); + d.requires(weather, GAMEMASTERS); + for kind in ["clear", "rain", "thunder"] { + let k = d.literal(weather, kind); + d.executes(k, "weather"); + let dur = d.argument(k, "duration", ArgType::Time { min: 1 }); + d.executes(dur, "weather"); + } + + // kill [] + let kill = d.literal(root, "kill"); + d.requires(kill, GAMEMASTERS); + d.executes(kill, "kill"); + let t = d.argument(kill, "targets", ENTITIES); + d.executes(t, "kill"); + + // summon [] [] + let summon = d.literal(root, "summon"); + d.requires(summon, GAMEMASTERS); + let e = d.argument(summon, "entity", ArgType::Resource(Resource::EntityType)); + d.executes(e, "summon"); + let pos = d.argument(e, "pos", ArgType::Vec3 { center: true }); + d.executes(pos, "summon"); + let nbt = d.argument(pos, "nbt", ArgType::Nbt); + d.executes(nbt, "summon"); + + // setblock [destroy|keep|replace|strict] + let sb = d.literal(root, "setblock"); + d.requires(sb, GAMEMASTERS); + let pos = d.argument(sb, "pos", ArgType::BlockPos); + let block = d.argument(pos, "block", ArgType::BlockState); + d.executes(block, "setblock"); + for m in ["destroy", "keep", "replace", "strict"] { + let l = d.literal(block, m); + d.executes(l, "setblock"); + } + + // fill [modes] + let fill = d.literal(root, "fill"); + d.requires(fill, GAMEMASTERS); + let from = d.argument(fill, "from", ArgType::BlockPos); + let to = d.argument(from, "to", ArgType::BlockPos); + let block = d.argument(to, "block", ArgType::BlockState); + fill_modes(&mut d, block); + let replace = d.literal(block, "replace"); + d.executes(replace, "fill"); + let filter = d.argument(replace, "filter", ArgType::BlockPredicate); + fill_modes(&mut d, filter); + let keep = d.literal(block, "keep"); + d.executes(keep, "fill"); + + // clone [from ] [to ] [strict] [mask] [mode] + let clone = d.literal(root, "clone"); + d.requires(clone, GAMEMASTERS); + clone_begin(&mut d, clone); + let from = d.literal(clone, "from"); + let dim = d.argument(from, "sourceDimension", ArgType::Dimension); + clone_begin(&mut d, dim); + + // experience / xp + let xp = d.literal(root, "experience"); + d.requires(xp, GAMEMASTERS); + for (op, min) in [("add", i32::MIN), ("set", 0)] { + let o = d.literal(xp, op); + let t = d.argument(o, "target", PLAYERS); + let amount = d.argument(t, "amount", integer(min)); + d.executes(amount, "experience"); + for unit in ["points", "levels"] { + let u = d.literal(amount, unit); + d.executes(u, "experience"); + } + } + let q = d.literal(xp, "query"); + let t = d.argument(q, "target", PLAYER); + for unit in ["points", "levels"] { + let u = d.literal(t, unit); + d.executes(u, "experience"); + } + let alias = d.literal(root, "xp"); + d.requires(alias, GAMEMASTERS); + d.redirect(alias, xp); + + // gamerule [] (short and namespaced names) + let gr = d.literal(root, "gamerule"); + d.requires(gr, GAMEMASTERS); + for rule in RULES { + for name in [rule.name.to_owned(), format!("minecraft:{}", rule.name)] { + let r = d.literal(gr, &name); + d.executes(r, "gamerule"); + let ty = match rule.default { + Value::Bool(_) => ArgType::Bool, + Value::Int(_) => ArgType::Integer { min: rule.min, max: rule.max }, + }; + let v = d.argument(r, "value", ty); + d.executes(v, "gamerule"); + } + } + + // difficulty [] + let diff = d.literal(root, "difficulty"); + d.executes(diff, "difficulty"); + for name in DIFFICULTIES { + let l = d.literal(diff, name); + d.requires(l, GAMEMASTERS); + d.executes(l, "difficulty"); + } + + let seed = d.literal(root, "seed"); + d.executes(seed, "seed"); + + // spawnpoint [] [] [] + let sp = d.literal(root, "spawnpoint"); + d.requires(sp, GAMEMASTERS); + d.executes(sp, "spawnpoint"); + let t = d.argument(sp, "targets", PLAYERS); + d.executes(t, "spawnpoint"); + let pos = d.argument(t, "pos", ArgType::BlockPos); + d.executes(pos, "spawnpoint"); + let rot = d.argument(pos, "rotation", ArgType::Rotation); + d.executes(rot, "spawnpoint"); + + // setworldspawn [] [] + let ws = d.literal(root, "setworldspawn"); + d.requires(ws, GAMEMASTERS); + d.executes(ws, "setworldspawn"); + let pos = d.argument(ws, "pos", ArgType::BlockPos); + d.executes(pos, "setworldspawn"); + let rot = d.argument(pos, "rotation", ArgType::Rotation); + d.executes(rot, "setworldspawn"); + + // clear [] [] [] + let clear = d.literal(root, "clear"); + d.requires(clear, GAMEMASTERS); + d.executes(clear, "clear"); + let t = d.argument(clear, "targets", PLAYERS); + d.executes(t, "clear"); + let item = d.argument(t, "item", ArgType::ItemPredicate); + d.executes(item, "clear"); + let max = d.argument(item, "maxCount", integer(0)); + d.executes(max, "clear"); + + // locate (structure|biome) <...> + let locate = d.literal(root, "locate"); + d.requires(locate, GAMEMASTERS); + let s = d.literal(locate, "structure"); + let a = d.argument(s, "structure", ArgType::Resource(Resource::Structure)); + d.executes(a, "locate.structure"); + let b = d.literal(locate, "biome"); + let a = d.argument(b, "biome", ArgType::Resource(Resource::Biome)); + d.executes(a, "locate.biome"); + + // say / me / msg / list + let say = d.literal(root, "say"); + d.requires(say, GAMEMASTERS); + let m = d.argument(say, "message", ArgType::Message); + d.executes(m, "say"); + let me = d.literal(root, "me"); + let m = d.argument(me, "action", ArgType::Message); + d.executes(m, "me"); + let msg = d.literal(root, "msg"); + let t = d.argument(msg, "targets", PLAYERS); + let m = d.argument(t, "message", ArgType::Message); + d.executes(m, "msg"); + for alias in ["tell", "w"] { + let a = d.literal(root, alias); + d.redirect(a, msg); + } + let list = d.literal(root, "list"); + d.executes(list, "list"); + let uuids = d.literal(list, "uuids"); + d.executes(uuids, "list"); + + d +} + +/// TimeCommand.addClockNodes. +fn clock_nodes(d: &mut Dispatcher, node: usize) { + let set = d.literal(node, "set"); + let t = d.argument(set, "time", ArgType::Time { min: 0 }); + d.executes(t, "time.set"); + let marker = d.argument(set, "timemarker", ArgType::Id("time_markers")); + d.executes(marker, "time.set.marker"); + let add = d.literal(node, "add"); + let t = d.argument(add, "time", ArgType::Time { min: i32::MIN }); + d.executes(t, "time.add"); + let pause = d.literal(node, "pause"); + d.executes(pause, "time.pause"); + let resume = d.literal(node, "resume"); + d.executes(resume, "time.resume"); + let rate = d.literal(node, "rate"); + let r = d.argument(rate, "rate", ArgType::Float { min: 1.0e-5, max: 1000.0 }); + d.executes(r, "time.rate"); + let query = d.literal(node, "query"); + let time = d.literal(query, "time"); + d.executes(time, "time.query.time"); + let tl = d.argument(query, "timeline", ArgType::Resource(Resource::Timeline)); + d.executes(tl, "time.query.timeline"); + let rep = d.literal(tl, "repetition"); + d.executes(rep, "time.query.repetition"); +} +/// FillCommand.wrapWithMode. +fn fill_modes(d: &mut Dispatcher, node: usize) { + d.executes(node, "fill"); + for m in ["outline", "hollow", "destroy", "strict"] { + let l = d.literal(node, m); + d.executes(l, "fill"); + } +} +fn clone_begin(d: &mut Dispatcher, node: usize) { + let begin = d.argument(node, "begin", ArgType::BlockPos); + let end = d.argument(begin, "end", ArgType::BlockPos); + clone_destination(d, end); + let to = d.literal(end, "to"); + let dim = d.argument(to, "targetDimension", ArgType::Dimension); + clone_destination(d, dim); +} +fn clone_destination(d: &mut Dispatcher, node: usize) { + let dest = d.argument(node, "destination", ArgType::BlockPos); + clone_mask(d, dest); + let strict = d.literal(dest, "strict"); + clone_mask(d, strict); +} +fn clone_mask(d: &mut Dispatcher, node: usize) { + d.executes(node, "clone"); + for m in ["replace", "masked"] { + let l = d.literal(node, m); + clone_mode(d, l); + } + let filtered = d.literal(node, "filtered"); + let filter = d.argument(filtered, "filter", ArgType::BlockPredicate); + clone_mode(d, filter); +} +fn clone_mode(d: &mut Dispatcher, node: usize) { + d.executes(node, "clone"); + for m in ["force", "move", "normal"] { + let l = d.literal(node, m); + d.executes(l, "clone"); + } +} +/// Game mode names for selector `gamemode=` and the argument. +pub fn game_modes() -> [&'static str; 4] { + GameMode::ALL.map(GameMode::name) +} +/// The shared vanilla tree. +pub fn dispatcher() -> &'static Dispatcher { + static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); + TREE.get_or_init(build) +} +#[allow(unused)] +const _: (u8, u8) = (ALL, GAMEMASTERS); diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs new file mode 100644 index 000000000..adb693e56 --- /dev/null +++ b/crates/horizon-client/src/font.rs @@ -0,0 +1,455 @@ +//! The default font (FontSet over `font/default.json`): space and bitmap +//! providers from the shared atlas, the unihex (GNU Unifont) fallback whose +//! glyphs are rasterized on demand into a reserved atlas region, vanilla +//! glyph metrics (ascent, oversampling, advances, bold/shadow offsets), +//! styled drawing and StringSplitter-style line wrapping. +use crate::{ + hud::Rect, + text::{Style, Text}, + zip::Zip, +}; +use std::{ + cell::RefCell, + collections::HashMap, + path::{Path, PathBuf}, +}; + +/// A glyph ready to draw: atlas UVs and its box relative to the pen +/// position (GlyphBitmap left/top/right/bottom), in GUI pixels. +#[derive(Clone, Copy, Debug)] +pub struct Glyph { + pub rect: Option, + pub left: f32, + pub top: f32, + pub right: f32, + pub bottom: f32, + pub advance: f32, + /// Shadow and bold offset (1 for bitmap glyphs, 0.5 for unihex). + pub offset: f32, +} +/// Pixels to copy into the shared atlas before the next HUD draw. +#[derive(Clone, Debug)] +pub struct Patch { + pub x: u32, + pub y: u32, + pub width: u32, + pub height: u32, + pub rgba: Vec, +} +#[derive(Clone, Copy)] +struct HexGlyph { + /// Rows left-aligned in 32 bits. + rows: [u32; 16], + left: u32, + right: u32, +} +#[derive(Default)] +struct HexProvider { + glyphs: HashMap, +} +struct Cache { + glyphs: HashMap, + cursor: (u32, u32), + pending: Vec, + hex: Option>, +} +pub struct Font { + bitmap: HashMap, + space: HashMap, + missing: Glyph, + white: Rect, + root: PathBuf, + /// Atlas size and the reserved dynamic region (y, height). + atlas: (u32, u32), + region: (u32, u32), + cache: RefCell, + /// "Force Unicode Font": skip the bitmap providers (font/uniform.json). + pub uniform: bool, + /// "Japanese Glyph Variants": enable providers filtered on `jp`. + pub japanese: bool, +} +fn parse_hex_digit(b: u8) -> Option { + (b as char).to_digit(16) +} +/// UnihexProvider.readFromStream over one `.hex` file. +fn parse_hex(text: &[u8], out: &mut HashMap) { + for line in text.split(|b| *b == b'\n') { + let line = line.strip_suffix(b"\r").unwrap_or(line); + let Some(colon) = line.iter().position(|b| *b == b':') else { continue }; + let (code, data) = (&line[..colon], &line[colon + 1..]); + if !(4..=6).contains(&code.len()) { + continue; + } + let Some(codepoint) = code.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) else { continue }; + let digits_per_row = match data.len() { + 32 => 2, + 64 => 4, + 96 => 6, + 128 => 8, + _ => continue, + }; + let bit_width = digits_per_row as u32 * 4; + let mut rows = [0u32; 16]; + let mut mask = 0u32; + let mut ok = true; + for (r, row) in rows.iter_mut().enumerate() { + let chunk = &data[r * digits_per_row..(r + 1) * digits_per_row]; + match chunk.iter().try_fold(0u32, |a, b| parse_hex_digit(*b).map(|d| a << 4 | d)) { + Some(v) => { + *row = v << (32 - bit_width); + mask |= *row; + } + None => ok = false, + } + } + if !ok { + continue; + } + // LineData.calculateWidth. + let (left, right) = if mask == 0 { (0, bit_width) } else { (mask.leading_zeros(), 31 - mask.trailing_zeros()) }; + out.insert(codepoint, HexGlyph { rows, left, right }); + } +} +fn read_json(root: &Path, path: &str) -> Option { + serde_json::from_slice(&std::fs::read(root.join(path)).ok()?).ok() +} +fn resource_path(id: &str, folder: &str, ext: &str) -> String { + let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); + format!("assets/{ns}/{folder}/{}{ext}", path.trim_end_matches(ext)) +} +/// Providers of a font definition with references expanded, in order, with +/// their `filter` objects. +fn providers(root: &Path, id: &str, depth: u32, out: &mut Vec) { + if depth > 8 { + return; + } + let Some(def) = read_json(root, &resource_path(id, "font", ".json")) else { return }; + for p in def["providers"].as_array().into_iter().flatten() { + if p["type"] == "reference" { + let mut nested = Vec::new(); + providers(root, p["id"].as_str().unwrap_or(""), depth + 1, &mut nested); + for mut n in nested { + // A reference's filter applies to everything it includes. + if let Some(f) = p["filter"].as_object() { + let merged = n["filter"].as_object().cloned().unwrap_or_default().into_iter().chain(f.clone()).collect(); + n["filter"] = serde_json::Value::Object(merged); + } + out.push(n); + } + } else { + out.push(p.clone()); + } + } +} +impl Font { + /// Build from the atlas holding the bitmap font sheets. `pixels` is the + /// RGBA atlas (for glyph widths) and `region` the reserved rows. + pub fn load(root: &Path, sprites: &HashMap, pixels: &[u8], atlas: (u32, u32), region: (u32, u32), white: Rect) -> Self { + let mut bitmap = HashMap::new(); + let mut space = HashMap::new(); + let mut all = Vec::new(); + providers(root, "minecraft:default", 0, &mut all); + for provider in &all { + match provider["type"].as_str() { + Some("space") => { + for (k, v) in provider["advances"].as_object().into_iter().flatten() { + if let (Some(c), Some(a)) = (k.chars().next(), v.as_f64()) { + space.entry(c).or_insert(a as f32); + } + } + } + Some("bitmap") => { + // Only non-uniform bitmap sheets exist in the default font. + let file = provider["file"].as_str().unwrap_or(""); + let name = file.trim_start_matches("minecraft:").trim_end_matches(".png"); + let name = format!("{}", name); + let Some(rect) = sprites.get(&name).copied() else { continue }; + let rows: Vec> = provider["chars"] + .as_array() + .into_iter() + .flatten() + .filter_map(|r| r.as_str().map(|s| s.chars().collect())) + .collect(); + if rows.is_empty() || rows[0].is_empty() { + continue; + } + let cell_w = rect.w / rows[0].len() as u32; + let cell_h = rect.h / rows.len() as u32; + let height = provider["height"].as_f64().unwrap_or(8.0) as f32; + let ascent = provider["ascent"].as_f64().unwrap_or(7.0) as f32; + let scale = height / cell_h as f32; + let (ax, ay) = ((rect.u0 * atlas.0 as f32).round() as u32, (rect.v0 * atlas.1 as f32).round() as u32); + for (r, row) in rows.iter().enumerate() { + for (c, ch) in row.iter().enumerate() { + if *ch == '\0' || bitmap.contains_key(ch) { + continue; + } + let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); + // BitmapProvider.getActualGlyphWidth. + let mut used = 0; + for x in (0..cell_w).rev() { + if (0..cell_h).any(|y| pixels.get((((cy + y) * atlas.0 + cx + x) * 4 + 3) as usize).is_some_and(|a| *a != 0)) { + used = x + 1; + break; + } + } + let top = 7.0 - ascent; + bitmap.insert( + *ch, + Glyph { + rect: Some(Rect { + u0: cx as f32 / atlas.0 as f32, + v0: cy as f32 / atlas.1 as f32, + u1: (cx + cell_w) as f32 / atlas.0 as f32, + v1: (cy + cell_h) as f32 / atlas.1 as f32, + w: cell_w, + h: cell_h, + }), + left: 0.0, + top, + right: cell_w as f32 * scale, + bottom: top + cell_h as f32 * scale, + advance: (0.5 + used as f32 * scale).floor() + 1.0, + offset: 1.0, + }, + ); + } + } + } + _ => {} + } + } + let missing = Glyph { rect: None, left: 0.0, top: 0.0, right: 5.0, bottom: 8.0, advance: 6.0, offset: 1.0 }; + Self { + bitmap, + space, + missing, + white, + root: root.to_owned(), + atlas, + region, + cache: RefCell::new(Cache { glyphs: HashMap::new(), cursor: (0, 0), pending: Vec::new(), hex: None }), + uniform: false, + japanese: false, + } + } + fn load_hex(&self) -> Vec { + let mut all = Vec::new(); + providers(&self.root, "minecraft:default", 0, &mut all); + let mut out = Vec::new(); + for p in all.iter().filter(|p| p["type"] == "unihex") { + if let Some(filter) = p["filter"].as_object() { + let pass = filter.iter().all(|(k, v)| match k.as_str() { + "jp" => v.as_bool() == Some(self.japanese), + "uniform" => v.as_bool() == Some(self.uniform), + _ => true, + }); + if !pass { + continue; + } + } + let Some(file) = p["hex_file"].as_str() else { continue }; + let path = self.root.join(resource_path(file, "", "").replace("//", "/")); + let Ok(zip) = Zip::open(&path) else { continue }; + let mut provider = HexProvider::default(); + let names: Vec = zip.names().filter(|n| n.ends_with(".hex")).map(str::to_owned).collect(); + for name in names { + if let Ok(bytes) = zip.read(&name) { + parse_hex(&bytes, &mut provider.glyphs); + } + } + for o in p["size_overrides"].as_array().into_iter().flatten() { + let from = o["from"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from); + let to = o["to"].as_str().and_then(|s| s.chars().next()).map_or(0, u32::from); + let (left, right) = (o["left"].as_u64().unwrap_or(0) as u32, o["right"].as_u64().unwrap_or(15) as u32); + for c in from..=to { + if let Some(g) = provider.glyphs.get_mut(&c) { + g.left = left; + g.right = right; + } + } + } + out.push(provider); + } + out + } + /// Forget rasterized fallback glyphs (after changing font options). + pub fn reset_cache(&self) { + let mut cache = self.cache.borrow_mut(); + cache.glyphs.clear(); + cache.cursor = (0, 0); + cache.hex = None; + } + /// The glyph for a character (FontSet.getGlyph). + pub fn glyph(&self, c: char) -> Glyph { + if let Some(a) = self.space.get(&c) { + return Glyph { rect: None, left: 0.0, top: 0.0, right: 0.0, bottom: 0.0, advance: *a, offset: 1.0 }; + } + if !self.uniform + && let Some(g) = self.bitmap.get(&c) + { + return *g; + } + if let Some(g) = self.cache.borrow().glyphs.get(&c) { + return *g; + } + let mut cache = self.cache.borrow_mut(); + if cache.hex.is_none() { + cache.hex = Some(self.load_hex()); + } + let hex = cache.hex.as_ref().and_then(|providers| providers.iter().find_map(|p| p.glyphs.get(&u32::from(c)).copied())); + let glyph = match hex { + Some(h) => self.rasterize(&mut cache, h).unwrap_or(self.missing), + None => self.missing, + }; + cache.glyphs.insert(c, glyph); + glyph + } + fn rasterize(&self, cache: &mut Cache, h: HexGlyph) -> Option { + let width = h.right.saturating_sub(h.left) + 1; + let (mut x, mut y) = cache.cursor; + if x + width + 1 > self.atlas.0 { + x = 0; + y += 17; + } + if y + 16 > self.region.1 { + return None; + } + let mut rgba = Vec::with_capacity((width * 16 * 4) as usize); + for row in h.rows { + for bit in h.left..=h.right { + let set = bit < 32 && (row >> (31 - bit)) & 1 != 0; + rgba.extend(if set { [255; 4] } else { [0; 4] }); + } + } + let (ax, ay) = (x, self.region.0 + y); + cache.pending.push(Patch { x: ax, y: ay, width, height: 16, rgba }); + cache.cursor = (x + width + 1, y); + Some(Glyph { + rect: Some(Rect { + u0: ax as f32 / self.atlas.0 as f32, + v0: ay as f32 / self.atlas.1 as f32, + u1: (ax + width) as f32 / self.atlas.0 as f32, + v1: (ay + 16) as f32 / self.atlas.1 as f32, + w: width, + h: 16, + }), + left: 0.0, + top: 0.0, + right: width as f32 / 2.0, + bottom: 8.0, + advance: (width / 2 + 1) as f32, + offset: 0.5, + }) + } + /// Atlas pixels rasterized since the last call. + pub fn take_patches(&self) -> Vec { + std::mem::take(&mut self.cache.borrow_mut().pending) + } + pub fn advance(&self, c: char, style: &Style) -> f32 { + let g = self.glyph(c); + g.advance + if style.is_bold() { g.offset } else { 0.0 } + } + /// Font.width of plain text (legacy codes are formatting, not glyphs). + pub fn width(&self, s: &str) -> f32 { + if s.contains('§') { + return self.width_text(&Text::legacy(s)); + } + s.chars().map(|c| self.glyph(c).advance).sum::().ceil() + } + pub fn width_text(&self, t: &Text) -> f32 { + t.chars().map(|(c, s)| self.advance(c, s)).sum::().ceil() + } + /// StringSplitter.splitLines: wrap at the last space that fits (or + /// mid-word when none does); `\n` always breaks. Styles are kept. + pub fn split(&self, t: &Text, max_width: f32) -> Vec { + let chars: Vec<(char, Style)> = t.chars().map(|(c, s)| (c, s.clone())).collect(); + let mut lines = Vec::new(); + let mut start = 0; + while start < chars.len() { + let mut width = 0.0; + let mut end = chars.len(); + let mut next = chars.len(); + let mut last_space = None; + for (i, (c, style)) in chars.iter().enumerate().skip(start) { + if *c == '\n' { + end = i; + next = i + 1; + break; + } + if *c == ' ' { + last_space = Some(i); + } + width += self.advance(*c, style); + if width > max_width { + match last_space { + Some(s) if s > start => { + end = s; + next = s + 1; + } + _ => { + end = i.max(start + 1); + next = end; + } + } + break; + } + } + lines.push(t.slice(start, end)); + start = next; + if start == chars.len() && chars.last().is_some_and(|c| c.0 == '\n') { + lines.push(Text::empty()); + } + } + if lines.is_empty() { + lines.push(Text::empty()); + } + lines + } + /// Characters of `s` that fit in `width` (Font.plainSubstrByWidth). + pub fn fit(&self, s: &str, width: f32) -> usize { + let mut w = 0.0; + for (i, c) in s.chars().enumerate() { + w += self.glyph(c).advance; + if w > width { + return i; + } + } + s.chars().count() + } + /// Characters of `s` that fit in `width`, measured from the end. + pub fn fit_reverse(&self, s: &str, width: f32) -> usize { + let mut w = 0.0; + for (i, c) in s.chars().rev().enumerate() { + w += self.glyph(c).advance; + if w > width { + return i; + } + } + s.chars().count() + } + pub fn white(&self) -> Rect { + self.white + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unihex_rows_and_widths() { + let mut out = HashMap::new(); + // 'A' from unifont (8 wide) and a 16-wide glyph with an empty left column. + let wide = format!("4E00:{}7FFE{}\n", "0000".repeat(4), "0000".repeat(11)); + parse_hex(b"0041:0000000018242442427E424242420000\n", &mut out); + parse_hex(wide.as_bytes(), &mut out); + let a = out[&0x41]; + assert_eq!((a.left, a.right), (1, 6)); + assert_eq!(a.rows[4], 0x18 << 24); + let yi = out[&0x4E00]; + assert_eq!((yi.left, yi.right), (1, 14)); + // Unparseable lines are skipped. + parse_hex(b"zz:00\n", &mut out); + assert_eq!(out.len(), 2); + } +} diff --git a/crates/horizon-client/src/gamerules.rs b/crates/horizon-client/src/gamerules.rs new file mode 100644 index 000000000..08862b1f9 --- /dev/null +++ b/crates/horizon-client/src/gamerules.rs @@ -0,0 +1,207 @@ +//! Game rules (26.3 `GameRules`): the registered rules with their category, +//! type, default and bounds, a value map, and persistence in the world's +//! `data/minecraft/game_rules.dat` saved-data file. +use horizon_world::{ + DATA_VERSION, + compression::Compression, + nbt::{self, Limits, NamedTag, Tag}, +}; +use std::{collections::BTreeMap, fs, path::Path}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Value { + Bool(bool), + Int(i32), +} +impl std::fmt::Display for Value { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Value::Bool(b) => write!(f, "{b}"), + Value::Int(i) => write!(f, "{i}"), + } + } +} +pub struct Rule { + pub name: &'static str, + pub category: &'static str, + pub default: Value, + pub min: i32, + pub max: i32, +} +const fn b(name: &'static str, category: &'static str, default: bool) -> Rule { + Rule { name, category, default: Value::Bool(default), min: 0, max: 0 } +} +const fn i(name: &'static str, category: &'static str, default: i32, min: i32, max: i32) -> Rule { + Rule { name, category, default: Value::Int(default), min, max } +} +/// Every rule available without experimental features, in registration order. +pub const RULES: &[Rule] = &[ + b("advance_time", "updates", true), + b("advance_weather", "updates", true), + b("allow_entering_nether_using_portals", "misc", true), + b("block_drops", "drops", true), + b("block_explosion_drop_decay", "drops", true), + b("command_blocks_work", "misc", true), + b("command_block_output", "chat", true), + b("drowning_damage", "player", true), + b("elytra_movement_check", "player", true), + b("ender_pearls_vanish_on_death", "player", true), + b("entity_drops", "drops", true), + b("fall_damage", "player", true), + b("fire_damage", "player", true), + i("fire_spread_radius_around_player", "updates", 128, -1, i32::MAX), + b("forgive_dead_players", "mobs", true), + b("freeze_damage", "player", true), + b("global_sound_events", "misc", true), + b("immediate_respawn", "player", false), + b("keep_inventory", "player", false), + b("lava_source_conversion", "updates", false), + b("limited_crafting", "player", false), + b("locator_bar", "player", true), + b("log_admin_commands", "chat", true), + i("max_block_modifications", "misc", 32768, 1, i32::MAX), + i("max_command_forks", "misc", 65536, 0, i32::MAX), + i("max_command_sequence_length", "misc", 65536, 0, i32::MAX), + i("max_entity_cramming", "mobs", 24, 0, i32::MAX), + i("max_snow_accumulation_height", "updates", 1, 0, 8), + b("mob_drops", "drops", true), + b("mob_explosion_drop_decay", "drops", true), + b("mob_griefing", "mobs", true), + b("natural_health_regeneration", "player", true), + b("player_movement_check", "player", true), + i("players_nether_portal_creative_delay", "player", 0, 0, i32::MAX), + i("players_nether_portal_default_delay", "player", 80, 0, i32::MAX), + i("players_sleeping_percentage", "player", 100, 0, i32::MAX), + b("projectiles_can_break_blocks", "drops", true), + b("pvp", "player", true), + b("raids", "mobs", true), + i("random_tick_speed", "updates", 3, 0, i32::MAX), + b("reduced_debug_info", "misc", false), + i("respawn_radius", "player", 10, 0, i32::MAX), + b("send_command_feedback", "chat", true), + b("show_advancement_messages", "chat", true), + b("show_death_messages", "chat", true), + b("spawner_blocks_work", "misc", true), + b("spawn_mobs", "spawning", true), + b("spawn_monsters", "spawning", true), + b("spawn_patrols", "spawning", true), + b("spawn_phantoms", "spawning", true), + b("spawn_wandering_traders", "spawning", true), + b("spawn_wardens", "spawning", true), + b("spectators_generate_chunks", "player", true), + b("spread_vines", "updates", true), + b("tnt_explodes", "misc", true), + b("tnt_explosion_drop_decay", "drops", false), + b("universal_anger", "mobs", false), + b("water_source_conversion", "updates", true), +]; +pub fn rule(name: &str) -> Option<&'static Rule> { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + RULES.iter().find(|r| r.name == name) +} + +/// Current values (defaults unless set). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct GameRules { + values: BTreeMap<&'static str, Value>, +} +impl GameRules { + pub fn get(&self, name: &str) -> Option { + let r = rule(name)?; + Some(self.values.get(r.name).copied().unwrap_or(r.default)) + } + pub fn bool(&self, name: &str) -> bool { + matches!(self.get(name), Some(Value::Bool(true))) + } + pub fn int(&self, name: &str) -> i32 { + match self.get(name) { + Some(Value::Int(v)) => v, + _ => 0, + } + } + /// Set a rule; false if the name or value type is wrong. + pub fn set(&mut self, name: &str, value: Value) -> bool { + let Some(r) = rule(name) else { return false }; + let ok = match (r.default, value) { + (Value::Bool(_), Value::Bool(_)) => true, + (Value::Int(_), Value::Int(v)) => (r.min..=r.max).contains(&v), + _ => false, + }; + if ok && value == r.default { + self.values.remove(r.name); + } else if ok { + self.values.insert(r.name, value); + } + ok + } + /// GameRuleMap codec: `{data: {"minecraft:": value...}, DataVersion}`. + pub fn to_nbt(&self) -> NamedTag { + let data: Vec<(horizon_world::nbt::JavaString, Tag)> = RULES + .iter() + .map(|r| { + let v = self.values.get(r.name).copied().unwrap_or(r.default); + let tag = match v { + Value::Bool(b) => Tag::Byte(i8::from(b)), + Value::Int(i) => Tag::Int(i), + }; + (horizon_world::nbt::JavaString::from(format!("minecraft:{}", r.name).as_str()), tag) + }) + .collect(); + NamedTag { name: "".into(), tag: Tag::compound([("data", Tag::compound(data)), ("DataVersion", Tag::Int(DATA_VERSION))]) } + } + pub fn from_nbt(root: &Tag) -> Self { + let mut rules = Self::default(); + let Some(data) = root.get("data") else { return rules }; + for r in RULES { + let key = format!("minecraft:{}", r.name); + let value = data.get(&key).or_else(|| data.get(r.name)); + match (r.default, value) { + (Value::Bool(_), Some(Tag::Byte(v))) => { + rules.set(r.name, Value::Bool(*v != 0)); + } + (Value::Int(_), Some(Tag::Int(v))) => { + rules.set(r.name, Value::Int(*v)); + } + _ => {} + } + } + rules + } + pub fn load(world: &Path) -> Self { + let Ok(bytes) = fs::read(world.join("data/minecraft/game_rules.dat")) else { return Self::default() }; + let Ok(raw) = Compression::Gzip.decode(&bytes, 16 << 20) else { return Self::default() }; + match nbt::read_named(&raw, Limits::default()) { + Ok((root, _)) => Self::from_nbt(&root.tag), + Err(_) => Self::default(), + } + } + pub fn save(&self, world: &Path) -> crate::Result<()> { + let dir = world.join("data/minecraft"); + fs::create_dir_all(&dir)?; + let bytes = nbt::write_named(&self.to_nbt(), Limits::default()).map_err(|e| e.to_string())?; + fs::write(dir.join("game_rules.dat"), Compression::Gzip.encode(&bytes)?)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn defaults_bounds_and_round_trip() { + let mut rules = GameRules::default(); + assert!(rules.bool("advance_time")); + assert_eq!(rules.int("random_tick_speed"), 3); + assert!(!rules.set("random_tick_speed", Value::Bool(true))); + assert!(!rules.set("max_snow_accumulation_height", Value::Int(9))); + assert!(rules.set("keep_inventory", Value::Bool(true))); + assert!(rules.set("minecraft:random_tick_speed", Value::Int(10))); + let back = GameRules::from_nbt(&rules.to_nbt().tag); + assert_eq!(back, rules); + assert!(back.bool("keep_inventory")); + let dir = std::env::temp_dir().join(format!("horizon-gamerules-{}", std::process::id())); + rules.save(&dir).unwrap(); + assert_eq!(GameRules::load(&dir), rules); + let _ = fs::remove_dir_all(dir); + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index d40da0e31..fdb1ea8d2 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -488,7 +488,8 @@ impl Renderer { atlas_pixels, ); let atlas_view = atlas.create_view(&Default::default()); - let hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?; + let mut hud = HudRenderer::new(&device, config.format.remove_srgb_suffix(), &atlas_view)?; + hud.atlas_texture = Some(atlas.clone()); let entity_shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon entities"), source: wgpu::ShaderSource::Wgsl(include_str!("entity.wgsl").into()), diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index fa6a0f20e..66a2f739e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -18,19 +18,17 @@ pub struct Rect { pub w: u32, pub h: u32, } -#[derive(Clone, Copy)] -struct Glyph { - rect: Rect, - advance: f32, -} pub struct HudAtlas { pub pixels: Vec, pub width: u32, pub height: u32, pub sprites: HashMap, - glyphs: HashMap, + /// The default font (bitmap sheets in this atlas, unifont rasterized on demand). + pub font: crate::font::Font, white: Rect, } +/// Atlas rows reserved for glyphs rasterized at run time. +pub const GLYPH_ROWS: u32 = 512; pub fn decode(path: &Path) -> Result<(u32, u32, Vec)> { let mut decoder = png::Decoder::new(std::io::BufReader::new(fs::File::open(path)?)); decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); @@ -129,7 +127,8 @@ impl HudAtlas { x += w + 1; row = row.max(*h); } - let height = (y + row + 1).next_power_of_two(); + let glyph_region = y + row + 1; + let height = (glyph_region + GLYPH_ROWS).next_power_of_two(); let mut pixels = vec![0u8; (width * height * 4) as usize]; let mut sprites = HashMap::new(); for ((name, w, h, data), (px, py)) in images.iter().zip(placements) { @@ -151,91 +150,15 @@ impl HudAtlas { ); } let white = sprites["horizon/white"]; - let mut atlas = Self { + let font = crate::font::Font::load(root, &sprites, &pixels, (width, height), (glyph_region, height - glyph_region), white); + Ok(Self { pixels, width, height, sprites, - glyphs: HashMap::new(), + font, white, - }; - atlas.load_font(root)?; - Ok(atlas) - } - fn load_font(&mut self, root: &Path) -> Result<()> { - let text = fs::read_to_string(root.join("assets/minecraft/font/include/default.json"))?; - let value: serde_json::Value = serde_json::from_str(&text)?; - for provider in value["providers"].as_array().into_iter().flatten() { - if provider["type"] != "bitmap" { - continue; - } - let file = provider["file"].as_str().unwrap_or(""); - let name = file - .trim_start_matches("minecraft:") - .trim_end_matches(".png") - .to_owned(); - let Some(rect) = self.sprites.get(&name).copied() else { - continue; - }; - let rows: Vec> = provider["chars"] - .as_array() - .into_iter() - .flatten() - .filter_map(|r| r.as_str().map(|s| s.chars().collect())) - .collect(); - if rows.is_empty() { - continue; - } - let columns = rows[0].len() as u32; - let cell_w = rect.w / columns; - let cell_h = rect.h / rows.len() as u32; - let height = provider["height"].as_f64().unwrap_or(8.0) as f32; - let scale = height / cell_h as f32; - let (ax, ay) = ( - (rect.u0 * self.width as f32) as u32, - (rect.v0 * self.height as f32) as u32, - ); - for (r, row) in rows.iter().enumerate() { - for (c, ch) in row.iter().enumerate() { - if *ch == '\0' || self.glyphs.contains_key(ch) { - continue; - } - let (cx, cy) = (ax + c as u32 * cell_w, ay + r as u32 * cell_h); - // Glyph width: rightmost column containing an opaque pixel. - let mut used = 0; - for x in (0..cell_w).rev() { - if (0..cell_h).any(|y| { - self.pixels[(((cy + y) * self.width + cx + x) * 4 + 3) as usize] != 0 - }) { - used = x + 1; - break; - } - } - self.glyphs.insert( - *ch, - Glyph { - rect: Rect { - u0: cx as f32 / self.width as f32, - v0: cy as f32 / self.height as f32, - u1: (cx + cell_w) as f32 / self.width as f32, - v1: (cy + cell_h) as f32 / self.height as f32, - w: cell_w, - h: cell_h, - }, - advance: (used as f32 * scale + 0.5).floor() + 1.0, - }, - ); - } - } - } - self.glyphs.insert( - ' ', - Glyph { - rect: self.white, - advance: 4.0, - }, - ); - Ok(()) + }) } } #[repr(C)] @@ -253,6 +176,8 @@ pub struct HudBatch { pub scale: f32, pub width: f32, pub height: f32, + /// Glyph pixels to upload into the atlas before drawing. + pub patches: Vec, } pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 { u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r) @@ -271,6 +196,7 @@ impl HudBatch { scale: scale as f32, width: (window[0] as f32 / scale as f32).ceil(), height: (window[1] as f32 / scale as f32).ceil(), + patches: Vec::new(), } } pub fn quad(&mut self, p: [[f32; 2]; 4], uv: [[f32; 2]; 4], color: u32) { @@ -317,26 +243,77 @@ impl HudBatch { self.rect_uv(x, y, w, h, r, color); } pub fn text_width(atlas: &HudAtlas, text: &str) -> f32 { - text.chars() - .map(|c| atlas.glyphs.get(&c).map_or(6.0, |g| g.advance)) - .sum() + atlas.font.width(text) } + /// Draw plain text (legacy `§` codes are honoured); returns the advance. pub fn text(&mut self, atlas: &HudAtlas, text: &str, x: f32, y: f32, color: u32, shadow: bool) -> f32 { - if shadow { - let c = color.to_le_bytes(); - let dark = rgba(c[0] / 4, c[1] / 4, c[2] / 4, c[3]); - self.text(atlas, text, x + 1.0, y + 1.0, dark, false); - } + let t = if text.contains('§') { crate::text::Text::legacy(text) } else { crate::text::Text::literal(text) }; + self.text_styled(atlas, &t, x, y, color, shadow) + } + /// Font.drawInternal: styled glyphs, shadows first, with bold, italic, + /// underline and strikethrough. `color` is the default colour and alpha. + pub fn text_styled(&mut self, atlas: &HudAtlas, text: &crate::text::Text, x: f32, y: f32, color: u32, shadow: bool) -> f32 { + let font = &atlas.font; + let alpha = (color >> 24) as u8; + let mut glyphs = Vec::new(); let mut cursor = x; - for ch in text.chars() { - let Some(g) = atlas.glyphs.get(&ch).copied() else { - cursor += 6.0; - continue; - }; - if ch != ' ' { - self.rect_uv(cursor, y, 8.0, 8.0, g.rect, color); + for (i, (ch, style)) in text.chars().enumerate() { + let g = font.glyph(ch); + let c = style.color.map_or(color, |rgb| rgba((rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8, alpha)); + let bold = style.is_bold(); + let advance = g.advance + if bold { g.offset } else { 0.0 }; + glyphs.push((cursor, g, c, bold, style.is_italic(), style.underlined == Some(true), style.strikethrough == Some(true), i == 0, advance)); + cursor += advance; + } + self.patches.extend(font.take_patches()); + let white = font.white(); + let passes: &[bool] = if shadow { &[true, false] } else { &[false] }; + for &is_shadow in passes { + for &(gx, g, c, bold, italic, underline, strike, first, advance) in &glyphs { + let (dx, col) = if is_shadow { + let b = c.to_le_bytes(); + (g.offset, rgba((f32::from(b[0]) * 0.25) as u8, (f32::from(b[1]) * 0.25) as u8, (f32::from(b[2]) * 0.25) as u8, b[3])) + } else { + (0.0, c) + }; + let (px, py) = (gx + dx, y + dx); + let shear = |v: f32| if italic { 1.0 - 0.25 * v } else { 0.0 }; + let thick = if bold { 0.1 } else { 0.0 }; + let draw = |batch: &mut Self, ox: f32| match g.rect { + Some(r) => { + let (x0, x1, y0, y1) = (px + ox + g.left, px + ox + g.right, py + g.top, py + g.bottom); + batch.quad( + [ + [x0 + shear(g.top) - thick, y0 - thick], + [x1 + shear(g.top) + thick, y0 - thick], + [x1 + shear(g.bottom) + thick, y1 + thick], + [x0 + shear(g.bottom) - thick, y1 + thick], + ], + [[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]], + col, + ); + } + None if g.right > 0.0 => { + // SpecialGlyphs.MISSING: a 5x8 outline. + let (bx, by) = (px + ox, py); + for (fx, fy, fw, fh) in [(0.0, 0.0, 5.0, 1.0), (0.0, 7.0, 5.0, 1.0), (0.0, 1.0, 1.0, 6.0), (4.0, 1.0, 1.0, 6.0)] { + batch.rect_uv(bx + fx, by + fy, fw, fh, white, col); + } + } + None => {} + }; + draw(self, 0.0); + if bold { + draw(self, g.offset); + } + let x0 = if first { px - 1.0 } else { px }; + if strike { + self.rect_uv(x0, py + 3.5, px + advance - x0, 1.0, white, col); + } + if underline { + self.rect_uv(x0, py + 8.0, px + advance - x0, 1.0, white, col); + } } - cursor += g.advance; } cursor - x } @@ -347,6 +324,8 @@ struct HudUniform { size: [f32; 4], } pub struct HudRenderer { + /// The shared atlas texture, for run-time glyph uploads. + pub atlas_texture: Option, pipeline: wgpu::RenderPipeline, group: wgpu::BindGroup, uniform: wgpu::Buffer, @@ -465,6 +444,7 @@ impl HudRenderer { mapped_at_creation: false, }); Ok(Self { + atlas_texture: None, pipeline, group, uniform, @@ -481,6 +461,16 @@ impl HudRenderer { batch: &HudBatch, size: [u32; 2], ) { + if let Some(texture) = &self.atlas_texture { + for p in &batch.patches { + queue.write_texture( + wgpu::TexelCopyTextureInfo { texture, mip_level: 0, origin: wgpu::Origin3d { x: p.x, y: p.y, z: 0 }, aspect: wgpu::TextureAspect::All }, + &p.rgba, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(p.width * 4), rows_per_image: None }, + wgpu::Extent3d { width: p.width, height: p.height, depth_or_array_layers: 1 }, + ); + } + } if batch.vertices.is_empty() { return; } diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs new file mode 100644 index 000000000..1174906ec --- /dev/null +++ b/crates/horizon-client/src/lang.rs @@ -0,0 +1,159 @@ +//! Languages (ClientLanguage / LanguageManager): `lang/.json` from the +//! resource root and enabled packs layered over `en_us`, the language list +//! from `pack.mcmeta` `language` sections, and a process-wide current +//! language used by every screen. +use std::{ + collections::{BTreeMap, HashMap}, + path::Path, + sync::{Arc, RwLock}, +}; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LanguageInfo { + pub code: String, + pub name: String, + pub region: String, + pub bidirectional: bool, +} +impl LanguageInfo { + /// LanguageInfo.toComponent: "Name (Region)". + pub fn label(&self) -> String { + format!("{} ({})", self.name, self.region) + } +} +#[derive(Default)] +pub struct Language { + pub code: String, + map: HashMap, +} +pub const DEFAULT: &str = "en_us"; + +static CURRENT: RwLock>> = RwLock::new(None); + +/// A source of resource files: the prepared root plus packs, highest priority last. +pub trait ResourceSource { + fn read(&self, path: &str) -> Option>; +} +impl ResourceSource for Path { + fn read(&self, path: &str) -> Option> { + std::fs::read(self.join(path)).ok() + } +} + +impl Language { + pub fn from_map(code: &str, map: HashMap) -> Self { + Self { code: code.to_owned(), map } + } + /// ClientLanguage.loadFrom: en_us first, then the selected language, each + /// from every source in priority order (later sources override). + pub fn load(sources: &[&dyn ResourceSource], code: &str) -> Self { + let mut map = HashMap::new(); + let mut codes = vec![DEFAULT]; + if code != DEFAULT { + codes.push(code); + } + for c in codes { + for source in sources { + let Some(bytes) = source.read(&format!("assets/minecraft/lang/{c}.json")) else { continue }; + if let Ok(entries) = serde_json::from_slice::>(&bytes) { + map.extend(entries); + } + } + } + Self { code: code.to_owned(), map } + } + pub fn get(&self, key: &str) -> Option<&str> { + self.map.get(key).map(String::as_str) + } + pub fn len(&self) -> usize { + self.map.len() + } + pub fn is_empty(&self) -> bool { + self.map.is_empty() + } +} + +/// Languages declared by `pack.mcmeta` files (the vanilla asset root first). +pub fn available(sources: &[&dyn ResourceSource]) -> Vec { + let mut found: BTreeMap = BTreeMap::new(); + found.insert( + DEFAULT.into(), + LanguageInfo { code: DEFAULT.into(), name: "English".into(), region: "US".into(), bidirectional: false }, + ); + for source in sources { + for path in ["assets/pack.mcmeta", "pack.mcmeta"] { + let Some(bytes) = source.read(path) else { continue }; + let Ok(value) = serde_json::from_slice::(&bytes) else { continue }; + for (code, info) in value["language"].as_object().into_iter().flatten() { + // Only languages whose file exists somewhere are selectable. + let file = format!("assets/minecraft/lang/{code}.json"); + if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) { + continue; + } + found.insert( + code.clone(), + LanguageInfo { + code: code.clone(), + name: info["name"].as_str().unwrap_or(code).to_owned(), + region: info["region"].as_str().unwrap_or("").to_owned(), + bidirectional: info["bidirectional"].as_bool().unwrap_or(false), + }, + ); + } + } + } + found.into_values().collect() +} + +pub fn set(language: Language) { + *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language)); +} +pub fn current() -> Option> { + CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone() +} +pub fn code() -> String { + current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone()) +} +/// Language.getOrDefault: the translation, or the key itself. +pub fn get(key: &str) -> String { + current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| key.to_owned()) +} +/// The translation, or `fallback` when the key is missing. +pub fn get_or(key: &str, fallback: &str) -> String { + current().and_then(|l| l.get(key).map(str::to_owned)).unwrap_or_else(|| fallback.to_owned()) +} +pub fn has(key: &str) -> bool { + current().is_some_and(|l| l.get(key).is_some()) +} +/// I18n.get with plain string arguments. +pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> String { + crate::text::Text::tr(key, args).plain() +} + +#[cfg(test)] +mod tests { + use super::*; + struct Mem(HashMap>); + impl ResourceSource for Mem { + fn read(&self, path: &str) -> Option> { + self.0.get(path).cloned() + } + } + #[test] + fn layers_selected_language_over_english() { + let base = Mem(HashMap::from([ + ("assets/minecraft/lang/en_us.json".into(), br#"{"a":"Apple","b":"Banana"}"#.to_vec()), + ("assets/minecraft/lang/fr_fr.json".into(), br#"{"a":"Pomme"}"#.to_vec()), + ("assets/pack.mcmeta".into(), r#"{"language":{"fr_fr":{"name":"Français","region":"France"},"de_de":{"name":"Deutsch","region":"Deutschland"}}}"#.as_bytes().to_vec()), + ])); + let pack = Mem(HashMap::from([("assets/minecraft/lang/fr_fr.json".into(), br#"{"b":"Banane"}"#.to_vec())])); + let sources: [&dyn ResourceSource; 2] = [&base, &pack]; + let fr = Language::load(&sources, "fr_fr"); + assert_eq!(fr.get("a"), Some("Pomme")); + assert_eq!(fr.get("b"), Some("Banane")); + let langs = available(&sources); + // de_de has no file, so only English and French are offered. + assert_eq!(langs.iter().map(|l| l.code.as_str()).collect::>(), ["en_us", "fr_fr"]); + assert_eq!(langs[1].label(), "Français (France)"); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 00265cade..93326510b 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -8,6 +8,7 @@ pub mod biome; pub mod blocks; pub mod chunk; pub mod clock; +pub mod command; pub mod containers; pub mod control; pub mod crafting; @@ -15,12 +16,15 @@ pub mod creative; pub mod collisions; pub mod entities; pub mod environment; +pub mod font; +pub mod gamerules; pub mod gfx; pub mod health; pub mod hud; pub mod hunger; pub mod input; pub mod items; +pub mod lang; pub mod landing; pub mod light; pub mod mesher; @@ -35,7 +39,9 @@ pub mod sprint; pub mod sprites; pub mod streaming; pub mod testgen; +pub mod text; pub mod title; pub mod vanillagen; pub mod world; +pub mod zip; pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs new file mode 100644 index 000000000..037153fca --- /dev/null +++ b/crates/horizon-client/src/text.rs @@ -0,0 +1,320 @@ +//! Styled text (a flattened `Component`): spans with ChatFormatting colours +//! and decorations, translatable messages formatted like +//! `TranslatableContents` (`%s`, `%1$s`, `%%`), and legacy `§` codes. +use crate::lang; + +/// ChatFormatting colours by legacy code index 0..=15. +pub const COLORS: [(char, &str, u32); 16] = [ + ('0', "black", 0x000000), + ('1', "dark_blue", 0x0000AA), + ('2', "dark_green", 0x00AA00), + ('3', "dark_aqua", 0x00AAAA), + ('4', "dark_red", 0xAA0000), + ('5', "dark_purple", 0xAA00AA), + ('6', "gold", 0xFFAA00), + ('7', "gray", 0xAAAAAA), + ('8', "dark_gray", 0x555555), + ('9', "blue", 0x5555FF), + ('a', "green", 0x55FF55), + ('b', "aqua", 0x55FFFF), + ('c', "red", 0xFF5555), + ('d', "light_purple", 0xFF55FF), + ('e', "yellow", 0xFFFF55), + ('f', "white", 0xFFFFFF), +]; +pub const BLACK: u32 = 0x000000; +pub const GRAY: u32 = 0xAAAAAA; +pub const DARK_GRAY: u32 = 0x555555; +pub const GREEN: u32 = 0x55FF55; +pub const AQUA: u32 = 0x55FFFF; +pub const RED: u32 = 0xFF5555; +pub const YELLOW: u32 = 0xFFFF55; +pub const GOLD: u32 = 0xFFAA00; +pub const WHITE: u32 = 0xFFFFFF; +pub const LIGHT_PURPLE: u32 = 0xFF55FF; + +pub fn named_color(name: &str) -> Option { + COLORS.iter().find(|c| c.1 == name).map(|c| c.2) +} + +/// Text style; `None` fields inherit from the enclosing style. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Style { + pub color: Option, + pub bold: Option, + pub italic: Option, + pub underlined: Option, + pub strikethrough: Option, + pub obfuscated: Option, + /// ClickEvent.SuggestCommand: clicking puts this into the chat box. + pub suggest: Option, + /// Hover text. + pub hover: Option>, +} +impl Style { + pub fn color(c: u32) -> Self { + Self { color: Some(c), ..Self::default() } + } + /// Fill unset fields from `base` (Style.applyTo). + pub fn inherit(&mut self, base: &Style) { + self.color = self.color.or(base.color); + self.bold = self.bold.or(base.bold); + self.italic = self.italic.or(base.italic); + self.underlined = self.underlined.or(base.underlined); + self.strikethrough = self.strikethrough.or(base.strikethrough); + self.obfuscated = self.obfuscated.or(base.obfuscated); + if self.suggest.is_none() { + self.suggest.clone_from(&base.suggest); + } + if self.hover.is_none() { + self.hover.clone_from(&base.hover); + } + } + pub fn is_bold(&self) -> bool { + self.bold == Some(true) + } + pub fn is_italic(&self) -> bool { + self.italic == Some(true) + } +} +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Span { + pub text: String, + pub style: Style, +} +/// A run of styled spans. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Text { + pub spans: Vec, +} +impl From<&str> for Text { + fn from(s: &str) -> Self { + Text::literal(s) + } +} +impl From for Text { + fn from(s: String) -> Self { + Text::literal(s) + } +} +impl Text { + pub fn empty() -> Self { + Self::default() + } + pub fn literal(s: impl Into) -> Self { + let text = s.into(); + if text.is_empty() { + return Self::default(); + } + Self { spans: vec![Span { text, style: Style::default() }] } + } + pub fn styled(s: impl Into, style: Style) -> Self { + let mut t = Self::literal(s); + for span in &mut t.spans { + span.style = style.clone(); + } + t + } + pub fn colored(s: impl Into, color: u32) -> Self { + Self::styled(s, Style::color(color)) + } + /// Component.translatable(key, args) in the current language. + pub fn translate(key: &str, args: &[Text]) -> Self { + format_translation(&lang::get(key), args) + } + /// A translatable message whose arguments are plain strings. + pub fn tr(key: &str, args: &[&dyn std::fmt::Display]) -> Self { + let args: Vec = args.iter().map(|a| Text::literal(a.to_string())).collect(); + Self::translate(key, &args) + } + pub fn append(mut self, other: impl Into) -> Self { + self.spans.extend(other.into().spans); + self + } + pub fn push(&mut self, other: impl Into) { + self.spans.extend(other.into().spans); + } + /// Apply `style` underneath every span (MutableComponent.withStyle on a parent). + pub fn with_style(mut self, style: &Style) -> Self { + for span in &mut self.spans { + span.style.inherit(style); + } + self + } + pub fn with_color(self, color: u32) -> Self { + self.with_style(&Style::color(color)) + } + pub fn italic(self) -> Self { + self.with_style(&Style { italic: Some(true), ..Style::default() }) + } + pub fn underlined(self) -> Self { + self.with_style(&Style { underlined: Some(true), ..Style::default() }) + } + pub fn bold(self) -> Self { + self.with_style(&Style { bold: Some(true), ..Style::default() }) + } + /// Component.getString: the plain characters. + pub fn plain(&self) -> String { + self.spans.iter().map(|s| s.text.as_str()).collect() + } + pub fn is_empty(&self) -> bool { + self.spans.iter().all(|s| s.text.is_empty()) + } + /// Parse legacy formatting codes (`§a`, `§l`, `§r`...) as the font does. + pub fn legacy(s: &str) -> Self { + let mut out = Text::default(); + let mut style = Style::default(); + let mut current = String::new(); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '§' { + current.push(c); + continue; + } + let Some(code) = chars.next() else { break }; + if !current.is_empty() { + out.spans.push(Span { text: std::mem::take(&mut current), style: style.clone() }); + } + let code = code.to_ascii_lowercase(); + if let Some(c) = COLORS.iter().find(|c| c.0 == code) { + // Colour codes reset decorations (Style.applyLegacyFormat). + style = Style::color(c.2); + } else { + match code { + 'k' => style.obfuscated = Some(true), + 'l' => style.bold = Some(true), + 'm' => style.strikethrough = Some(true), + 'n' => style.underlined = Some(true), + 'o' => style.italic = Some(true), + 'r' => style = Style::default(), + _ => {} + } + } + } + if !current.is_empty() { + out.spans.push(Span { text: current, style }); + } + out + } + /// Characters with their effective styles. + pub fn chars(&self) -> impl Iterator { + self.spans.iter().flat_map(|s| s.text.chars().map(move |c| (c, &s.style))) + } + /// Sub-range of characters [from, to) keeping styles. + pub fn slice(&self, from: usize, to: usize) -> Text { + let mut out = Text::default(); + let mut index = 0; + for span in &self.spans { + let mut part = String::new(); + for c in span.text.chars() { + if index >= from && index < to { + part.push(c); + } + index += 1; + } + if !part.is_empty() { + out.spans.push(Span { text: part, style: span.style.clone() }); + } + } + out + } + pub fn char_count(&self) -> usize { + self.spans.iter().map(|s| s.text.chars().count()).sum() + } +} + +/// TranslatableContents.decomposeTemplate: `%s` takes the next argument, +/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are +/// shown verbatim. +pub fn format_translation(template: &str, args: &[Text]) -> Text { + let mut out = Text::default(); + let mut literal = String::new(); + let mut next = 0usize; + let chars: Vec = template.chars().collect(); + let mut i = 0; + while i < chars.len() { + if chars[i] != '%' { + literal.push(chars[i]); + i += 1; + continue; + } + // %(?:(\d+)\$)?([A-Za-z%]|$) + let mut j = i + 1; + let mut number = None; + let digits_start = j; + while j < chars.len() && chars[j].is_ascii_digit() { + j += 1; + } + if j > digits_start && j < chars.len() && chars[j] == '$' { + number = chars[digits_start..j].iter().collect::().parse::().ok(); + j += 1; + } else { + j = digits_start; + } + let conversion = chars.get(j).copied(); + match conversion { + Some('%') if number.is_none() => { + literal.push('%'); + i = j + 1; + } + // Not a format specifier at all: the percent sign is literal. + Some(c) if !c.is_ascii_alphabetic() && c != '%' => { + literal.push('%'); + i += 1; + } + Some('s') => { + let index = match number { + Some(n) => n.wrapping_sub(1), + None => { + next += 1; + next - 1 + } + }; + let Some(arg) = args.get(index) else { + return Text::literal(template); + }; + if !literal.is_empty() { + out.spans.push(Span { text: std::mem::take(&mut literal), style: Style::default() }); + } + out.spans.extend(arg.spans.iter().cloned()); + i = j + 1; + } + _ => return Text::literal(template), + } + } + if !literal.is_empty() { + out.spans.push(Span { text: literal, style: Style::default() }); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn formats_like_translatable_contents() { + let a = [Text::literal("Steve"), Text::colored("Zombie", RED)]; + assert_eq!(format_translation("%s was slain by %s", &a).plain(), "Steve was slain by Zombie"); + assert_eq!(format_translation("%2$s then %1$s", &a).plain(), "Zombie then Steve"); + assert_eq!(format_translation("100%% sure %s", &a).plain(), "100% sure Steve"); + // Missing arguments or unknown conversions show the template. + assert_eq!(format_translation("%s %s %s", &a).plain(), "%s %s %s"); + assert_eq!(format_translation("%d", &a).plain(), "%d"); + assert_eq!(format_translation("50% off %s", &a).plain(), "50% off Steve"); + assert_eq!(format_translation("end %", &a).plain(), "end %"); + let t = format_translation("%s was slain by %s", &a); + assert_eq!(t.spans.last().unwrap().style.color, Some(RED)); + } + #[test] + fn legacy_codes_and_inheritance() { + let t = Text::legacy("§aGreen §lbold§r plain"); + assert_eq!(t.plain(), "Green bold plain"); + assert_eq!(t.spans[0].style.color, Some(GREEN)); + assert!(t.spans[1].style.is_bold()); + assert_eq!(t.spans[2].style, Style::default()); + let t = Text::literal("x").append(Text::colored("y", GOLD)).with_color(RED); + assert_eq!(t.spans[0].style.color, Some(RED)); + assert_eq!(t.spans[1].style.color, Some(GOLD)); + assert_eq!(t.slice(1, 2).plain(), "y"); + } +} diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs new file mode 100644 index 000000000..4a413a2fd --- /dev/null +++ b/crates/horizon-client/src/zip.rs @@ -0,0 +1,139 @@ +//! Minimal read-only ZIP archive support (stored and deflated entries), used +//! for resource packs and the unifont glyph archive. +use std::{collections::BTreeMap, fs, io, path::Path}; + +/// One archive held in memory with its central directory indexed by name. +pub struct Zip { + data: Vec, + entries: BTreeMap, +} +#[derive(Clone, Copy)] +struct Entry { + method: u16, + compressed: usize, + size: usize, + header: usize, +} +fn invalid(message: &str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} +fn u16_at(d: &[u8], at: usize) -> io::Result { + d.get(at..at + 2).map(|b| u16::from_le_bytes([b[0], b[1]])).ok_or_else(|| invalid("truncated zip")) +} +fn u32_at(d: &[u8], at: usize) -> io::Result { + d.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])).ok_or_else(|| invalid("truncated zip")) +} +impl Zip { + pub fn open(path: &Path) -> io::Result { + Self::from_bytes(fs::read(path)?) + } + pub fn from_bytes(data: Vec) -> io::Result { + // End of central directory: the last "PK\x05\x06" within 64 KiB of the end. + let min = data.len().saturating_sub(22 + 65_535); + let eocd = (min..=data.len().saturating_sub(22)) + .rev() + .find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06]) + .ok_or_else(|| invalid("not a zip archive"))?; + let count = usize::from(u16_at(&data, eocd + 10)?); + let mut at = u32_at(&data, eocd + 16)? as usize; + let mut entries = BTreeMap::new(); + for _ in 0..count { + if u32_at(&data, at)? != 0x0201_4b50 { + return Err(invalid("bad central directory entry")); + } + let method = u16_at(&data, at + 10)?; + let compressed = u32_at(&data, at + 20)? as usize; + let size = u32_at(&data, at + 24)? as usize; + let name_len = usize::from(u16_at(&data, at + 28)?); + let extra_len = usize::from(u16_at(&data, at + 30)?); + let comment_len = usize::from(u16_at(&data, at + 32)?); + let header = u32_at(&data, at + 42)? as usize; + let name = data.get(at + 46..at + 46 + name_len).ok_or_else(|| invalid("truncated zip name"))?; + let name = String::from_utf8_lossy(name).replace('\\', "/"); + if !name.ends_with('/') { + entries.insert(name, Entry { method, compressed, size, header }); + } + at += 46 + name_len + extra_len + comment_len; + } + Ok(Self { data, entries }) + } + pub fn names(&self) -> impl Iterator { + self.entries.keys().map(String::as_str) + } + pub fn contains(&self, name: &str) -> bool { + self.entries.contains_key(name) + } + pub fn read(&self, name: &str) -> io::Result> { + let e = *self.entries.get(name).ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?; + if u32_at(&self.data, e.header)? != 0x0403_4b50 { + return Err(invalid("bad local file header")); + } + let start = e.header + 30 + usize::from(u16_at(&self.data, e.header + 26)?) + usize::from(u16_at(&self.data, e.header + 28)?); + let raw = self.data.get(start..start + e.compressed).ok_or_else(|| invalid("truncated zip entry"))?; + match e.method { + 0 => Ok(raw.to_vec()), + 8 => { + let out = miniz_oxide::inflate::decompress_to_vec_with_limit(raw, e.size.max(1) * 2 + 1024) + .map_err(|_| invalid("corrupt deflate stream"))?; + Ok(out) + } + _ => Err(invalid("unsupported zip compression")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + /// A hand-built archive with one stored and one deflated entry. + fn archive() -> Vec { + let files: [(&str, &[u8], bool); 2] = [("pack.mcmeta", b"{\"pack\":{}}", false), ("a/b.txt", b"hello hello hello hello", true)]; + let mut out = Vec::new(); + let mut central = Vec::new(); + for (name, body, deflate) in files { + let data = if deflate { miniz_oxide::deflate::compress_to_vec(body, 6) } else { body.to_vec() }; + let offset = out.len() as u32; + let local = |v: &mut Vec, sig: u32| { + v.extend(sig.to_le_bytes()); + }; + local(&mut out, 0x0403_4b50); + out.extend([20, 0, 0, 0]); + out.extend((if deflate { 8u16 } else { 0 }).to_le_bytes()); + out.extend([0; 8]); + out.extend((data.len() as u32).to_le_bytes()); + out.extend((body.len() as u32).to_le_bytes()); + out.extend((name.len() as u16).to_le_bytes()); + out.extend(0u16.to_le_bytes()); + out.extend(name.as_bytes()); + out.extend(&data); + local(&mut central, 0x0201_4b50); + central.extend([20, 0, 20, 0, 0, 0]); + central.extend((if deflate { 8u16 } else { 0 }).to_le_bytes()); + central.extend([0; 8]); + central.extend((data.len() as u32).to_le_bytes()); + central.extend((body.len() as u32).to_le_bytes()); + central.extend((name.len() as u16).to_le_bytes()); + central.extend([0; 12]); + central.extend(offset.to_le_bytes()); + central.extend(name.as_bytes()); + } + let start = out.len() as u32; + out.extend(¢ral); + out.extend(0x0605_4b50u32.to_le_bytes()); + out.extend([0; 4]); + out.extend(2u16.to_le_bytes()); + out.extend(2u16.to_le_bytes()); + out.extend((central.len() as u32).to_le_bytes()); + out.extend(start.to_le_bytes()); + out.extend([0; 2]); + out + } + #[test] + fn reads_stored_and_deflated_entries() { + let zip = Zip::from_bytes(archive()).unwrap(); + assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]); + assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}"); + assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello"); + assert!(zip.read("missing").is_err()); + } +} diff --git a/tools/fetch_client_assets.py b/tools/fetch_client_assets.py new file mode 100644 index 000000000..02373cd91 --- /dev/null +++ b/tools/fetch_client_assets.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python3 +"""Fetch the pinned version's indexed client assets that are not in the game +jar: language files and the language list (pack.mcmeta), the unifont glyph +archives and their font definitions, and the built-in Programmer Art and High +Contrast resource packs. Every object's SHA-1 is verified. Files go to the +private client resource directory (or --target) and are never committed.""" +import argparse +import concurrent.futures +import hashlib +import json +from pathlib import Path +import urllib.request + +ROOT = Path(__file__).resolve().parent.parent +LOCAL = ROOT / '.local' + + +def fetch(url): + with urllib.request.urlopen(url, timeout=120) as response: + return response.read() + + +def wanted(name): + return (name == 'pack.mcmeta' + or name.startswith('minecraft/lang/') + or name.startswith('minecraft/font/') + or name.startswith('minecraft/resourcepacks/')) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--target', type=Path, default=LOCAL / 'horizon-client/26.3', + help='prepared resource directory (default: .local/horizon-client/26.3)') + args = parser.parse_args() + manifest = json.loads((LOCAL / 'minecraft/26.3/manifest.json').read_text()) + index_info = manifest['assetIndex'] + target = args.target + index_path = target / 'asset-index.json' + if not index_path.exists() or hashlib.sha1(index_path.read_bytes()).hexdigest() != index_info['sha1']: + data = fetch(index_info['url']) + if hashlib.sha1(data).hexdigest() != index_info['sha1']: + raise ValueError('asset index checksum mismatch') + target.mkdir(parents=True, exist_ok=True) + index_path.write_bytes(data) + objects = json.loads(index_path.read_text())['objects'] + selected = {name: info for name, info in objects.items() if wanted(name)} + + def download(item): + name, info = item + path = target / 'assets' / name + if path.exists() and hashlib.sha1(path.read_bytes()).hexdigest() == info['hash']: + return 0 + h = info['hash'] + data = fetch(f'https://resources.download.minecraft.net/{h[:2]}/{h}') + if hashlib.sha1(data).hexdigest() != h: + raise ValueError(f'checksum mismatch for {name}') + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(data) + return len(data) + + total = 0 + with concurrent.futures.ThreadPoolExecutor(16) as pool: + for size in pool.map(download, selected.items()): + total += size + print(f'Client assets ready: {len(selected)} files, {total / 1e6:.1f} MB downloaded') + + +if __name__ == '__main__': + main()