From 67f51123e8d1e566b48dfacbe79c267cb1ca4264 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:16:20 +0200 Subject: [PATCH 1/4] Add vanilla font metrics with unifont fallback, languages, styled text and a Brigadier command core Font: bitmap glyph ascent/oversampling, unihex glyphs rasterized on demand into a reserved atlas region, bold/italic/underline/strikethrough and StringSplitter wrapping. Languages layer lang/.json over en_us. The command module ports Brigadier parsing, suggestions and smart usage with the vanilla argument types and the 26.3 command tree; game rules use the 26.3 registry names and saved-data file. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-client/Cargo.toml | 1 + crates/horizon-client/src/command/args.rs | 1160 ++++++++++++++++++ crates/horizon-client/src/command/mod.rs | 639 ++++++++++ crates/horizon-client/src/command/tests.rs | 139 +++ crates/horizon-client/src/command/vanilla.rs | 340 +++++ crates/horizon-client/src/font.rs | 455 +++++++ crates/horizon-client/src/gamerules.rs | 207 ++++ crates/horizon-client/src/gfx.rs | 3 +- crates/horizon-client/src/hud.rs | 196 ++- crates/horizon-client/src/lang.rs | 159 +++ crates/horizon-client/src/lib.rs | 6 + crates/horizon-client/src/text.rs | 320 +++++ crates/horizon-client/src/zip.rs | 139 +++ tools/fetch_client_assets.py | 69 ++ 15 files changed, 3730 insertions(+), 104 deletions(-) create mode 100644 crates/horizon-client/src/command/args.rs create mode 100644 crates/horizon-client/src/command/mod.rs create mode 100644 crates/horizon-client/src/command/tests.rs create mode 100644 crates/horizon-client/src/command/vanilla.rs create mode 100644 crates/horizon-client/src/font.rs create mode 100644 crates/horizon-client/src/gamerules.rs create mode 100644 crates/horizon-client/src/lang.rs create mode 100644 crates/horizon-client/src/text.rs create mode 100644 crates/horizon-client/src/zip.rs create mode 100644 tools/fetch_client_assets.py 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() From c9eeed0300074865a41d74026c44f5f6bd777eea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:29:51 +0200 Subject: [PATCH 2/4] Add chat, the vanilla command set and game rules to the game ChatComponent/ChatScreen port: wrapped 100-line history with the 200-tick fade, scrolling, system message indicator, input history, argument colouring, usage hints, parse errors and tab completion. Commands: help, gamemode, defaultgamemode, give, teleport/tp, time (26.3 clocks and markers), weather, kill, summon, setblock, fill, clone, experience/xp, gamerule, difficulty, seed, spawnpoint, setworldspawn, clear, locate biome, say, me, msg, list. Game rules gate the clock, weather, random ticks, keep_inventory, death messages and command feedback, and are saved to data/minecraft/game_rules.dat. F1 hides the HUD, F2 saves screenshots. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/chat.rs | 590 ++++++++++ crates/horizon-client/src/game.rs | 54 +- crates/horizon-client/src/game/chat.rs | 494 ++++++++ crates/horizon-client/src/game/commands.rs | 1231 ++++++++++++++++++++ crates/horizon-client/src/game/control.rs | 35 + crates/horizon-client/src/lang.rs | 3 +- crates/horizon-client/src/lib.rs | 2 + crates/horizon-client/src/ui.rs | 502 ++++++++ 8 files changed, 2905 insertions(+), 6 deletions(-) create mode 100644 crates/horizon-client/src/chat.rs create mode 100644 crates/horizon-client/src/game/chat.rs create mode 100644 crates/horizon-client/src/game/commands.rs create mode 100644 crates/horizon-client/src/ui.rs diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs new file mode 100644 index 000000000..33459b29f --- /dev/null +++ b/crates/horizon-client/src/chat.rs @@ -0,0 +1,590 @@ +//! Chat: the message list (ChatComponent: wrapping, 100-line history, +//! 200-tick fade, scrolling, system message indicator) and the chat screen +//! (ChatScreen + EditBox + CommandSuggestions: history navigation, argument +//! colouring, usage hints, parse errors and tab completion). +use crate::{ + command::{Dispatcher, ParseResults, Registries, Suggestion}, + hud::{HudAtlas, HudBatch, rgba}, + text::{self, Style, Text}, + ui::{EditBox, char_len}, +}; + +/// GuiMessageTag.systemSinglePlayer's indicator colour. +pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0; + +#[derive(Clone, Copy, Debug)] +pub struct ChatOptions { + pub opacity: f32, + pub background_opacity: f32, + pub scale: f32, + pub width: f32, + pub height_focused: f32, + pub height_unfocused: f32, + pub line_spacing: f32, +} +impl Default for ChatOptions { + fn default() -> Self { + Self { opacity: 1.0, background_opacity: 0.5, scale: 1.0, width: 1.0, height_focused: 1.0, height_unfocused: 70.0 / 160.0, line_spacing: 0.0 } + } +} +impl ChatOptions { + /// ChatComponent.getWidth/getHeight. + pub fn width_px(&self) -> f32 { + (self.width * 280.0 + 40.0).floor() + } + pub fn height_px(&self, focused: bool) -> f32 { + ((if focused { self.height_focused } else { self.height_unfocused }) * 160.0 + 20.0).floor() + } + pub fn line_height(&self) -> f32 { + (9.0 * (self.line_spacing + 1.0)).floor() + } +} +#[derive(Clone, Debug)] +struct Message { + added: u64, + content: Text, + indicator: Option, +} +#[derive(Clone, Debug)] +struct Line { + added: u64, + content: Text, + indicator: Option, +} +#[derive(Default)] +pub struct Chat { + messages: Vec, + /// Wrapped lines, newest first. + lines: Vec, + /// Sent messages and commands (ChatComponent.recentChat). + pub recent: Vec, + scroll: usize, + new_since_scroll: bool, + pub options: ChatOptions, + /// Messages printed to stdout as `[CHAT]` (vanilla logs them). + pub log: bool, +} +impl Chat { + pub fn lines_per_page(&self, focused: bool) -> usize { + (self.options.height_px(focused) / self.options.line_height().max(1.0)) as usize + } + fn max_width(&self) -> f32 { + (self.options.width_px() / self.options.scale.max(0.01)).floor() + } + /// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. + pub fn add(&mut self, atlas: &HudAtlas, content: Text, indicator: Option, ticks: u64, focused: bool) { + if self.log { + println!("[CHAT] {}", content.plain()); + } + let message = Message { added: ticks, content, indicator }; + self.add_lines(atlas, &message, focused); + self.messages.insert(0, message); + self.messages.truncate(100); + } + fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) { + let width = self.max_width(); + for line in atlas.font.split(&message.content, width) { + if focused && self.scroll > 0 { + self.new_since_scroll = true; + self.scroll_by(1, focused); + } + self.lines.insert(0, Line { added: message.added, content: line, indicator: message.indicator }); + } + self.lines.truncate(100); + } + /// Re-wrap after a width or scale change (ChatComponent.rescaleChat). + pub fn rescale(&mut self, atlas: &HudAtlas) { + self.scroll = 0; + self.new_since_scroll = false; + self.lines.clear(); + let messages: Vec = self.messages.iter().rev().cloned().collect(); + for m in &messages { + self.add_lines(atlas, m, false); + } + } + pub fn clear(&mut self) { + self.messages.clear(); + self.lines.clear(); + self.scroll = 0; + } + pub fn add_recent(&mut self, message: &str) { + if self.recent.last().map(String::as_str) != Some(message) { + if self.recent.len() >= 100 { + self.recent.remove(0); + } + self.recent.push(message.to_owned()); + } + } + pub fn reset_scroll(&mut self) { + self.scroll = 0; + self.new_since_scroll = false; + } + pub fn scroll_by(&mut self, dir: i32, focused: bool) { + let max = self.lines.len().saturating_sub(self.lines_per_page(focused)) as i32; + let pos = (self.scroll as i32 + dir).min(max); + if pos <= 0 { + self.scroll = 0; + self.new_since_scroll = false; + } else { + self.scroll = pos as usize; + } + } + /// ChatComponent.extractRenderState. + pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas, ticks: u64, focused: bool) { + if self.lines.is_empty() { + return; + } + let o = &self.options; + let scale = o.scale; + if scale <= 0.0 { + return; + } + let max_width = (o.width_px() / scale).ceil(); + let chat_bottom = ((batch.height - 40.0) / scale).floor(); + let text_opacity = o.opacity * 0.9 + 0.1; + let entry_height = o.line_height(); + let bottom_to_text = (8.0 * (o.line_spacing + 1.0) - 4.0 * o.line_spacing).round(); + let per_page = self.lines_per_page(focused); + let alpha_of = |line: &Line| -> f32 { + if focused { + return 1.0; + } + let t = ((1.0 - (ticks.saturating_sub(line.added)) as f64 / 200.0) * 10.0).clamp(0.0, 1.0); + (t * t) as f32 + }; + let visible = self.lines.len().saturating_sub(self.scroll).min(per_page); + let mut count = 0; + // Pass 1: backgrounds; pass 2: text (same order as vanilla). + let s = |v: f32| v * scale; + for i in (0..visible).rev() { + let line = &self.lines[i + self.scroll]; + let alpha = alpha_of(line); + if alpha <= 1.0e-5 { + continue; + } + count += 1; + let bottom = chat_bottom - i as f32 * entry_height; + let top = bottom - entry_height; + batch.fill(atlas, 0.0, s(top), s(max_width + 8.0), s(entry_height), rgba(0, 0, 0, (alpha * o.background_opacity * 255.0) as u8)); + } + for i in (0..visible).rev() { + let line = &self.lines[i + self.scroll]; + let alpha = alpha_of(line); + if alpha <= 1.0e-5 { + continue; + } + let bottom = chat_bottom - i as f32 * entry_height; + let top = bottom - entry_height; + let text_top = bottom - bottom_to_text; + let a = (alpha * text_opacity * 255.0) as u8; + if let Some(c) = line.indicator { + batch.fill(atlas, 0.0, s(top), s(2.0), s(entry_height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, a)); + } + if a > 3 { + batch.text_styled(atlas, &line.content, s(4.0), s(text_top), rgba(255, 255, 255, a), true); + } + } + // Scroll bar while focused and scrolled content exists. + if focused && count > 0 { + let total = self.lines.len() as f32; + let chat_height = count as f32 * entry_height; + let virtual_height = total * entry_height; + if virtual_height != chat_height { + let y = self.scroll as f32 * chat_height / total - chat_bottom; + let height = chat_height * chat_height / virtual_height; + let alpha = if y > 0.0 { 170 } else { 96 }; + let c = if self.new_since_scroll { 0xCC3333 } else { 0x3333AA }; + let x = max_width + 4.0 + 4.0; + batch.fill(atlas, s(x), s(-y - height), s(2.0), s(height), rgba((c >> 16) as u8, (c >> 8) as u8, c as u8, alpha)); + batch.fill(atlas, s(x + 1.0), s(-y - height), s(1.0), s(height), rgba(0xCC, 0xCC, 0xCC, alpha)); + } + } + } + /// Plain text of the newest messages (for tests and the control socket). + pub fn recent_lines(&self, n: usize) -> Vec { + self.messages.iter().take(n).map(|m| m.content.plain()).collect() + } +} + +/// CommandSuggestions.SuggestionsList. +#[derive(Clone, Debug)] +struct SuggestionList { + x: f32, + width: f32, + list: Vec, + offset: usize, + current: usize, + original: String, + tab_cycles: bool, + last_mouse: (f32, f32), +} + +/// The open chat screen. +pub struct ChatScreen { + pub input: EditBox, + history_pos: usize, + history_buffer: String, + parse: Option, + usage: Vec, + usage_x: f32, + suggestions: Option, + pending: Vec, + pending_start: usize, + keep_suggestions: bool, + allow_suggestions: bool, + pub auto_suggestions: bool, + dirty: bool, +} +const FILL: u32 = 0xD000_0000; +fn fill_color() -> u32 { + rgba(0, 0, 0, (FILL >> 24) as u8) +} +impl ChatScreen { + pub fn new(initial: &str, history_len: usize, width: f32, height: f32) -> Self { + let mut input = EditBox::new(4.0, height - 12.0, width - 4.0, 12.0); + input.bordered = false; + input.max_length = 256; + input.set_value(initial); + Self { + input, + history_pos: history_len, + history_buffer: String::new(), + parse: None, + usage: Vec::new(), + usage_x: 0.0, + suggestions: None, + pending: Vec::new(), + pending_start: 0, + keep_suggestions: false, + allow_suggestions: false, + auto_suggestions: true, + dirty: true, + } + } + /// Keep the input box at the bottom when the window resizes. + pub fn resize(&mut self, width: f32, height: f32) { + self.input.x = 4.0; + self.input.y = height - 12.0; + self.input.width = width - 4.0; + } + pub fn value(&self) -> &str { + &self.input.value + } + /// ChatScreen.onEdited. + pub fn edited(&mut self) { + self.allow_suggestions = true; + self.dirty = true; + } + /// CommandSuggestions.updateCommandInfo (run lazily before drawing/keys). + pub fn update(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries) { + if !self.dirty { + return; + } + self.dirty = false; + let command = self.input.value.clone(); + if self.parse.as_ref().is_some_and(|p| p.input != command) { + self.parse = None; + } + if !self.keep_suggestions { + self.input.suggestion = None; + self.suggestions = None; + } + self.usage.clear(); + self.pending.clear(); + let cursor_chars = self.input.cursor; + let cursor = command.char_indices().nth(cursor_chars).map_or(command.len(), |(i, _)| i); + if !command.starts_with('/') { + return; + } + if self.parse.is_none() { + self.parse = Some(d.parse_at(&command, 1, reg)); + } + let Some(parse) = &self.parse else { return }; + if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { + let (range, list) = d.suggestions(parse, cursor, reg); + self.pending = list; + self.pending_start = range.0; + // CommandSuggestions.updateUsageInfo. + let mut trailing = false; + if cursor == command.len() { + if self.pending.is_empty() && !parse.errors.is_empty() { + let mut literals = 0; + for (_, e) in &parse.errors { + if e.literal_incorrect { + literals += 1; + } else { + self.usage.push(e.with_context().with_color(text::RED)); + } + } + if literals > 0 { + let reader = crate::command::Reader { string: &parse.input, cursor: parse.cursor }; + self.usage.push(crate::command::CommandError::tr_at("command.unknown.argument", &[], &reader).with_context().with_color(text::RED)); + } + } else if parse.can_read() { + trailing = true; + } + } + let (node, start, _) = parse.context.suggestion_context(cursor); + if self.usage.is_empty() { + let mut lines: Vec = d + .smart_usage(node, reg.permission) + .into_iter() + .filter(|(n, _)| !matches!(d.nodes[*n].kind, crate::command::NodeKind::Literal(_))) + .map(|(_, u)| Text::colored(u, text::GRAY)) + .collect(); + if lines.is_empty() + && trailing + && let Some(e) = parse.error() + { + lines.push(e.with_context().with_color(text::RED)); + } + self.usage = lines; + } + let usage_width = self.usage.iter().map(|u| atlas.font.width_text(u)).fold(0.0, f32::max); + let start_chars = char_len(&command[..start.min(command.len())]); + self.usage_x = if self.usage.is_empty() { + 0.0 + } else { + self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - usage_width).max(0.0)) + }; + self.suggestions = None; + if self.allow_suggestions && self.auto_suggestions { + self.show_suggestions(atlas); + } + } + } + /// CommandSuggestions.showSuggestions. + fn show_suggestions(&mut self, atlas: &HudAtlas) { + if self.pending.is_empty() { + return; + } + let value = self.input.value.clone(); + let width = self.pending.iter().map(|s| atlas.font.width(&s.text)).fold(0.0, f32::max); + let start_chars = char_len(&value[..self.pending_start.min(value.len())]); + let x = self.input.screen_x(atlas, start_chars).clamp(0.0, (self.input.screen_x(atlas, 0) + self.input.inner_width() - width).max(0.0)); + // Sort: suggestions starting with the last word first. + let cursor = value.char_indices().nth(self.input.cursor).map_or(value.len(), |(i, _)| i); + let partial = &value[..cursor]; + let last_word = partial.rfind(char::is_whitespace).map_or(0, |i| i + 1); + let word = partial[last_word..].to_lowercase(); + let (mut first, partial_matches): (Vec, Vec) = + self.pending.iter().cloned().partition(|s| s.text.starts_with(&word) || s.text.starts_with(&format!("minecraft:{word}"))); + first.extend(partial_matches); + let mut list = SuggestionList { x: x - 1.0, width: width + 1.0, list: first, offset: 0, current: 0, original: value, tab_cycles: false, last_mouse: (-1.0, -1.0) }; + self.select(&mut list, 0); + self.suggestions = Some(list); + } + fn select(&mut self, list: &mut SuggestionList, index: isize) { + let n = list.list.len() as isize; + list.current = index.rem_euclid(n.max(1)) as usize; + let applied = list.list[list.current].apply(&list.original); + self.input.suggestion = applied.strip_prefix(self.input.value.as_str()).filter(|s| !s.is_empty()).map(str::to_owned); + } + fn cycle(&mut self, list: &mut SuggestionList, dir: isize) { + self.select(list, list.current as isize + dir); + let limit = 10; + let max_offset = list.list.len().saturating_sub(limit); + if list.current < list.offset { + list.offset = list.current.min(max_offset); + } else if list.current > list.offset + limit - 1 { + list.offset = (list.current + 1).saturating_sub(limit).min(max_offset); + } + } + fn use_suggestion(&mut self, list: &mut SuggestionList) { + let s = list.list[list.current].clone(); + self.keep_suggestions = true; + let applied = s.apply(&list.original); + self.input.set_value(&applied); + let end = char_len(&list.original[..s.range.0.min(list.original.len())]) + char_len(&s.text); + self.input.set_cursor(end, false); + self.dirty = true; + self.select(list, list.current as isize); + self.keep_suggestions = false; + list.tab_cycles = true; + } + /// Suggestion-list keys (CommandSuggestions.keyPressed). Returns true if handled. + pub fn suggestion_key(&mut self, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, key: winit::keyboard::KeyCode, shift: bool) -> bool { + use winit::keyboard::KeyCode as K; + self.update(atlas, d, reg); + if let Some(mut list) = self.suggestions.take() { + let handled = match key { + K::ArrowUp => { + self.cycle(&mut list, -1); + list.tab_cycles = false; + true + } + K::ArrowDown => { + self.cycle(&mut list, 1); + list.tab_cycles = false; + true + } + K::Tab => { + if list.tab_cycles { + self.cycle(&mut list, if shift { -1 } else { 1 }); + } + self.use_suggestion(&mut list); + // Keep the list across the re-parse triggered by the edit. + let keep = list.clone(); + self.keep_suggestions = true; + self.update(atlas, d, reg); + self.keep_suggestions = false; + self.suggestions = Some(keep); + return true; + } + K::Escape => { + self.input.suggestion = None; + return true; + } + _ => false, + }; + self.suggestions = Some(list); + return handled; + } + if key == K::Tab { + self.show_suggestions(atlas); + return true; + } + false + } + /// ChatScreen.moveInHistory. + pub fn move_in_history(&mut self, recent: &[String], dir: isize) { + let max = recent.len(); + let new = (self.history_pos as isize + dir).clamp(0, max as isize) as usize; + if new == self.history_pos { + return; + } + if new == max { + self.history_pos = max; + let b = self.history_buffer.clone(); + self.input.set_value(&b); + } else { + if self.history_pos == max { + self.history_buffer = self.input.value.clone(); + } + self.input.set_value(&recent[new]); + self.suggestions = None; + self.allow_suggestions = false; + self.history_pos = new; + } + self.dirty = true; + } + /// Mouse wheel over the suggestion list. + pub fn scroll_suggestions(&mut self, cursor: (f32, f32), height: f32, amount: f32) -> bool { + let Some(list) = &mut self.suggestions else { return false }; + let n = list.list.len().min(10); + let top = height - 12.0 - 3.0 - n as f32 * 12.0; + if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) { + let max = list.list.len().saturating_sub(10) as isize; + list.offset = (list.offset as isize - amount.signum() as isize).clamp(0, max) as usize; + return true; + } + false + } + /// Click on a suggestion row. + pub fn click(&mut self, cursor: (f32, f32), height: f32) -> bool { + let Some(mut list) = self.suggestions.take() else { return false }; + let n = list.list.len().min(10); + let top = height - 12.0 - 3.0 - n as f32 * 12.0; + if crate::ui::hovered(cursor, list.x, top, list.width, n as f32 * 12.0) { + let row = ((cursor.1 - top) / 12.0) as usize + list.offset; + if row < list.list.len() { + self.select(&mut list, row as isize); + self.use_suggestion(&mut list); + } + self.suggestions = Some(list); + return true; + } + self.suggestions = Some(list); + false + } + /// CommandSuggestions.formatText: argument colours over the input. + fn formatted(&self) -> Option { + let parse = self.parse.as_ref()?; + let value = &self.input.value; + let styles = [text::AQUA, text::YELLOW, text::GREEN, text::LIGHT_PURPLE, text::GOLD]; + let mut colors = vec![text::GRAY; value.len()]; + let ctx = parse.context.last_child(); + for (i, arg) in ctx.args.iter().enumerate() { + let c = styles[i % styles.len()]; + for b in arg.range.0.min(value.len())..arg.range.1.min(value.len()) { + colors[b] = c; + } + } + if parse.can_read() { + for c in colors.iter_mut().skip(parse.cursor) { + *c = text::RED; + } + } + let mut out = Text::empty(); + for (i, ch) in value.char_indices() { + out.push(Text::styled(ch.to_string(), Style::color(colors[i]))); + } + Some(out) + } + /// ChatScreen.extractRenderState minus the chat lines. + pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, d: &Dispatcher, reg: &Registries, cursor: (f32, f32), background_opacity: f32) { + self.update(atlas, d, reg); + let (w, h) = (batch.width, batch.height); + batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, (background_opacity * 255.0) as u8)); + let formatted = self.formatted(); + self.input.draw(batch, atlas, formatted.as_ref()); + let fill = fill_color(); + if let Some(mut list) = self.suggestions.take() { + let limit = list.list.len().min(10); + let top = h - 12.0 - 3.0 - limit as f32 * 12.0; + let has_prev = list.offset > 0; + let has_next = list.list.len() > list.offset + limit; + let moved = list.last_mouse != cursor; + list.last_mouse = cursor; + if has_prev || has_next { + batch.fill(atlas, list.x, top - 1.0, list.width, 1.0, fill); + batch.fill(atlas, list.x, top + limit as f32 * 12.0, list.width, 1.0, fill); + for x in (0..list.width as i32).step_by(2) { + if has_prev { + batch.fill(atlas, list.x + x as f32, top - 1.0, 1.0, 1.0, u32::MAX); + } + if has_next { + batch.fill(atlas, list.x + x as f32, top + limit as f32 * 12.0, 1.0, 1.0, u32::MAX); + } + } + } + let mut hovered_row = None; + for i in 0..limit { + let y = top + 12.0 * i as f32; + batch.fill(atlas, list.x, y, list.width, 12.0, fill); + if cursor.0 > list.x && cursor.0 < list.x + list.width && cursor.1 > y && cursor.1 < y + 12.0 { + hovered_row = Some(i + list.offset); + } + } + if moved && let Some(r) = hovered_row { + self.select(&mut list, r as isize); + } + for i in 0..limit { + let s = &list.list[i + list.offset]; + let color = if i + list.offset == list.current { rgba(255, 255, 0, 255) } else { rgba(0xAA, 0xAA, 0xAA, 255) }; + batch.text(atlas, &s.text, list.x + 1.0, top + 2.0 + 12.0 * i as f32, color, true); + } + if hovered_row.is_some() + && let Some(tip) = &list.list[list.current].tooltip + { + crate::ui::tooltip(batch, atlas, &[Text::literal(tip.clone())], cursor); + } + self.suggestions = Some(list); + } else { + for (i, line) in self.usage.iter().enumerate() { + let y = h - 27.0 - 12.0 * i as f32; + let width = atlas.font.width_text(line); + batch.fill(atlas, self.usage_x - 1.0, y, width + 2.0, 12.0, fill); + batch.text_styled(atlas, line, self.usage_x, y + 2.0, u32::MAX, true); + } + } + } + /// ChatScreen.normalizeChatMessage. + pub fn normalized(&self) -> String { + let collapsed = self.input.value.split_whitespace().collect::>().join(" "); + collapsed.chars().take(256).collect() + } + pub fn suggestions_visible(&self) -> bool { + self.suggestions.is_some() + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6f6b063aa..28ce636f9 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1,5 +1,7 @@ //! The playable game loop: streaming world, player simulation at 20 ticks/s, //! block interaction, inventory and HUD. +mod chat; +mod commands; mod control; use horizon_client::{ Result, @@ -166,6 +168,7 @@ enum Screen { Playing, Paused, Options, + Chat, Creative, Inventory, Dead, @@ -196,8 +199,12 @@ struct GameLevel<'w> { raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, + rules: horizon_world::level::GameRules, } impl LevelAccess for GameLevel<'_> { + fn game_rules(&self) -> horizon_world::level::GameRules { + self.rules + } fn block_state(&self, pos: BlockPos) -> BlockStateId { self.world.block(pos.x, pos.y, pos.z) } @@ -387,6 +394,7 @@ struct Game<'a> { /// Control replies waiting for a rendered frame or a benchmark deadline. pending_screenshot: Option>, pending_bench: Option<(Instant, std::sync::mpsc::Sender)>, + ui: chat::UiState, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Dim { @@ -677,6 +685,7 @@ impl Game<'_> { ([p.position.x - w, p.position.y, p.position.z - w], [p.position.x + w, p.position.y + f64::from(p.dimensions.height), p.position.z + w]) }); let dimension = if self.dim == Dim::Nether { LevelDimension::Nether } else { LevelDimension::Overworld }; + let rules = self.level_rules(); let mut level = GameLevel { world: &mut self.world, facts: &self.res.facts, @@ -686,6 +695,7 @@ impl Game<'_> { raining: rain > 0.2, thundering: thunder > 0.9, player_box, + rules, }; f(&self.res.behaviours, &mut level, &mut self.block_ticks) } @@ -1286,12 +1296,14 @@ impl Game<'_> { fn tick(&mut self) -> Result<()> { self.ticks += 1; self.world.game_time += 1; - self.world.weather.tick(&mut self.world.random); + if self.ui.rules.bool("advance_weather") { + self.world.weather.tick(&mut self.world.random); + } self.tick_weather_effects(); if self.ticks % 6000 == 0 { self.save_game()?; } - self.world.day_time += 1; + self.advance_clock(); if self.use_delay > 0 { self.use_delay -= 1; } @@ -1357,7 +1369,8 @@ impl Game<'_> { if player.health.dead_or_dying() && self.screen != Screen::Dead { // Inventory.dropAll: every stack thrown in a random direction. let at = [player.position.x, player.position.y + 1.32, player.position.z]; - if !self.creative { + self.death_message(); + if !self.creative && !self.ui.rules.bool("keep_inventory") { let stacks: Vec = self.inventory.iter_mut().filter_map(Option::take).collect(); for stack in stacks { let r = &mut self.world.random; @@ -1676,6 +1689,8 @@ impl Game<'_> { let tw = HudBatch::text_width(atlas, text); batch.text(atlas, text, (w - tw) / 2.0, h - 59.0, u32::MAX, true); } + self.draw_chat(&mut batch); + let atlas = &self.res.atlas; if let Some((_, ticks)) = self.sleeping { // Gui sleep overlay fading in over 100 ticks. let a = ((ticks as f32 / 100.0).min(1.0) * 204.0) as u8; @@ -1713,6 +1728,7 @@ impl Game<'_> { Screen::Creative => { self.draw_creative(&mut batch); } + Screen::Chat => self.draw_chat_screen(&mut batch), Screen::Playing | Screen::Options => {} } batch @@ -2946,6 +2962,7 @@ impl Game<'_> { if !save_root.join("level.dat").exists() { self.level.write(&save_root)?; } + self.load_world_state(); Ok(()) } /// Streaming and region storage for one dimension of a world. @@ -4110,6 +4127,7 @@ impl Game<'_> { } level.dimension = self.dim.id().to_owned(); level.write(&self.world_root)?; + self.save_world_state(); self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) } @@ -4232,7 +4250,12 @@ impl Game<'_> { self.capture(true); } Screen::Dead => {} + Screen::Chat => self.close_chat(), }, + KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), + KeyCode::Slash if self.screen == Screen::Playing => self.open_chat("/"), + KeyCode::F1 => self.toggle_hide_gui(), + KeyCode::F2 => self.take_screenshot(), KeyCode::KeyE if self.screen == Screen::Creative && self.creative_screen.tab().search => {} KeyCode::KeyE => match self.screen { Screen::Playing => { @@ -4418,6 +4441,9 @@ impl ApplicationHandler for Game<'_> { MouseScrollDelta::LineDelta(_, y) => y, MouseScrollDelta::PixelDelta(p) => p.y as f32, }; + if self.screen == Screen::Chat && d != 0.0 { + self.chat_scroll(d); + } if self.screen == Screen::Creative && d != 0.0 { let rows = self.creative_screen.rows(&self.res.names).saturating_sub(5).max(1) as f32; self.creative_screen.scroll = (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); @@ -4470,6 +4496,7 @@ impl ApplicationHandler for Game<'_> { Screen::Inventory if pressed => { self.click_inventory(button == MouseButton::Right); } + Screen::Chat if pressed && button == MouseButton::Left => self.chat_click(), Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); } @@ -4500,6 +4527,16 @@ impl ApplicationHandler for Game<'_> { _ => {} } } + WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Chat && self.title.is_none() => { + if let PhysicalKey::Code(key) = event.physical_key { + if event.state == ElementState::Pressed { + self.keys.insert(key); + self.chat_key(&event); + } else { + self.keys.remove(&key); + } + } + } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Creative && self.creative_screen.tab().search && event.state == ElementState::Pressed && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => @@ -4564,7 +4601,13 @@ impl ApplicationHandler for Game<'_> { } } let rendered = self.render()?; - if let Some(result) = self.renderer.as_mut().and_then(|r| r.screenshot_result.take()) + let finished = self.renderer.as_mut().and_then(|r| r.screenshot_result.take()); + if let Some(result) = &finished + && self.ui.screenshot_message.is_some() + { + self.finish_screenshot(result); + } + if let Some(result) = finished && let Some(reply) = self.pending_screenshot.take() { let _ = reply.send(match result { @@ -4643,6 +4686,8 @@ pub fn run() -> Result<()> { let light = Arc::new(LightTables::new(&facts)); eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; + horizon_client::ui::load_metadata(&root); + horizon_client::lang::set(horizon_client::lang::Language::load(&[&root], horizon_client::lang::DEFAULT)); eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); let layer_names = assets .sprite_layers @@ -4803,6 +4848,7 @@ pub fn run() -> Result<()> { frame_stats: Default::default(), pending_screenshot: None, pending_bench: None, + ui: Default::default(), }; if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs new file mode 100644 index 000000000..5b7d5db69 --- /dev/null +++ b/crates/horizon-client/src/game/chat.rs @@ -0,0 +1,494 @@ +//! Chat, the command registries and the per-world state behind commands +//! (game rules, the world clock, difficulty), bound to the game. +use super::{Dim, Game, Screen}; +use horizon_client::{ + chat::{Chat, ChatScreen, SYSTEM_INDICATOR}, + command::{Registries, vanilla}, + gamerules::GameRules, + hud::{HudBatch, rgba}, + text::Text, +}; +use std::collections::BTreeMap; +use winit::{event::KeyEvent, keyboard::{KeyCode, PhysicalKey}}; + +/// The local player's name (offline single player). +pub const PLAYER_NAME: &str = "Player"; + +/// ServerClockManager.ServerClockInstance for the overworld clock (its +/// total ticks are the world's day time). +#[derive(Clone, Copy, Debug)] +pub struct WorldClock { + pub partial: f32, + pub rate: f32, + pub paused: bool, +} +impl Default for WorldClock { + fn default() -> Self { + Self { partial: 0.0, rate: 1.0, paused: false } + } +} +/// A clock time marker from the timelines (ClockTimeMarker). +#[derive(Clone, Copy, Debug)] +pub struct TimeMarker { + pub ticks: i64, + pub period: Option, + pub show: bool, +} +impl TimeMarker { + pub fn occurs_at(&self, total: i64) -> bool { + match self.period { + Some(p) => self.ticks == total.rem_euclid(p), + None => self.ticks == total, + } + } + pub fn resolve(&self, total: i64) -> i64 { + match self.period { + Some(p) => { + let d = self.ticks - total.rem_euclid(p); + total + if d > 0 { d } else { p + d } + } + None => self.ticks, + } + } +} +/// UI and command state that lives beside the game. +#[derive(Default)] +pub struct UiState { + pub chat: Chat, + pub chat_screen: Option, + pub registries: Registries, + pub rules: GameRules, + pub clock: WorldClock, + /// Time markers and timelines of the overworld clock. + pub markers: BTreeMap, + pub timelines: BTreeMap>, + /// 0 peaceful .. 3 hard. + pub difficulty: u8, + /// F1: hide the HUD. + pub hide_gui: bool, + /// Death message key set by the cause of death (e.g. /kill). + pub death_cause: Option, + /// File name of an F2 screenshot waiting for its frame. + pub screenshot_message: Option, +} + +impl Game<'_> { + /// Registry contents for argument parsing (built when a world opens). + pub(super) fn build_registries(&mut self) { + let reg = &mut self.ui.registries; + reg.permission = 4; + let mut items: Vec = self.res.items.order.iter().map(|s| s.to_string()).collect(); + items.sort(); + reg.items = items; + reg.item_tags = self.res.items.item_tags.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); + reg.item_tags.sort(); + reg.block_tags = self.res.items.block_tags.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); + reg.block_tags.sort(); + let registry = self.res.assets.registry; + let mut blocks: BTreeMap>> = BTreeMap::new(); + for id in 0..registry.len() { + let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) else { continue }; + let props = blocks.entry(state.name.clone()).or_default(); + for (k, v) in &state.properties { + let values = props.entry(k.clone()).or_default(); + if !values.contains(v) { + values.push(v.clone()); + } + } + } + reg.blocks = blocks.into_iter().map(|(k, v)| (k, v.into_iter().collect())).collect(); + let mut summonable: Vec = self.res.mob_types.keys().map(|k| horizon_client::command::args::normalize(k)).collect(); + summonable.extend(["minecraft:item", "minecraft:experience_orb", "minecraft:falling_block", "minecraft:arrow"].map(String::from)); + summonable.sort(); + summonable.dedup(); + reg.summonable = summonable; + let root = self.options.resources.clone(); + let mut types: Vec = serde_json::from_slice::(&std::fs::read(root.join("entity-types.json")).unwrap_or_default()) + .ok() + .and_then(|v| v.as_object().map(|o| o.keys().map(|k| horizon_client::command::args::normalize(k)).collect())) + .unwrap_or_default(); + if types.is_empty() { + types = reg.summonable.clone(); + types.push("minecraft:player".into()); + } + types.sort(); + reg.entity_types = types; + let list = |dir: &str| -> Vec { + let mut out: Vec = std::fs::read_dir(root.join(dir)) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| e.file_name().to_str()?.strip_suffix(".json").map(|n| format!("minecraft:{n}"))) + .collect(); + out.sort(); + out + }; + reg.enchantments = list("data/minecraft/enchantment"); + reg.structures = list("data/minecraft/worldgen/structure"); + reg.biomes = list("data/minecraft/worldgen/biome"); + reg.clocks = list("data/minecraft/world_clock"); + reg.dimensions = vec!["minecraft:overworld".into(), "minecraft:the_nether".into()]; + reg.players = vec![PLAYER_NAME.into()]; + // Timelines of the overworld clock and their time markers. + self.ui.markers.clear(); + self.ui.timelines.clear(); + for name in list("data/minecraft/timeline") { + let path = root.join(format!("data/minecraft/timeline/{}.json", name.trim_start_matches("minecraft:"))); + let Ok(v) = serde_json::from_slice::(&std::fs::read(path).unwrap_or_default()) else { continue }; + if v["clock"].as_str() != Some("minecraft:overworld") { + continue; + } + let period = v["period_ticks"].as_i64(); + self.ui.timelines.insert(name.clone(), period); + for (marker, def) in v["time_markers"].as_object().into_iter().flatten() { + let (ticks, show) = match def { + serde_json::Value::Number(n) => (n.as_i64().unwrap_or(0), false), + other => (other["ticks"].as_i64().unwrap_or(0), other["show_in_commands"].as_bool().unwrap_or(false)), + }; + self.ui.markers.insert(marker.clone(), TimeMarker { ticks, period, show }); + } + } + let reg = &mut self.ui.registries; + reg.timelines = self.ui.timelines.keys().cloned().collect(); + reg.time_markers = self.ui.markers.iter().filter(|(_, m)| m.show).map(|(k, _)| k.clone()).collect(); + } + /// The block the player is looking at, for coordinate suggestions. + fn refresh_dynamic_registries(&mut self) { + self.ui.registries.target_block = self.pick().map(|h| h.pos); + } + pub(super) fn open_chat(&mut self, initial: &str) { + if self.player.is_none() { + return; + } + self.refresh_dynamic_registries(); + let size = self.renderer.as_ref().map_or([1280, 720], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + let mut screen = ChatScreen::new(initial, self.ui.chat.recent.len(), b.width, b.height); + screen.auto_suggestions = true; + self.ui.chat_screen = Some(screen); + self.screen = Screen::Chat; + self.keys.clear(); + self.left = false; + self.right = false; + self.capture(false); + } + pub(super) fn close_chat(&mut self) { + self.ui.chat_screen = None; + self.ui.chat.reset_scroll(); + if self.screen == Screen::Chat { + self.screen = Screen::Playing; + self.capture(true); + } + } + /// A chat message from the game (ChatComponent.addServerSystemMessage). + pub(super) fn system_message(&mut self, text: Text) { + let focused = self.screen == Screen::Chat; + self.ui.chat.add(&self.res.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, focused); + } + /// Keys while the chat screen is open. + pub(super) fn chat_key(&mut self, event: &KeyEvent) { + let PhysicalKey::Code(key) = event.physical_key else { return }; + self.chat_key_code(key, event.text.as_deref()); + } + /// A key (and the text it typed) while the chat screen is open. + pub(super) fn chat_key_code(&mut self, key: KeyCode, typed_text: Option<&str>) { + let ctrl = self.keys.contains(&KeyCode::ControlLeft) || self.keys.contains(&KeyCode::ControlRight); + let shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); + let Some(mut screen) = self.ui.chat_screen.take() else { return }; + let atlas = &self.res.atlas; + let d = vanilla::dispatcher(); + if screen.suggestion_key(atlas, d, &self.ui.registries, key, shift) { + self.ui.chat_screen = Some(screen); + return; + } + let mut close = false; + let mut submit = None; + match key { + KeyCode::Escape => close = true, + KeyCode::Enter | KeyCode::NumpadEnter => { + submit = Some(screen.normalized()); + close = true; + } + KeyCode::ArrowUp => screen.move_in_history(&self.ui.chat.recent, -1), + KeyCode::ArrowDown => screen.move_in_history(&self.ui.chat.recent, 1), + KeyCode::PageUp => { + let n = self.ui.chat.lines_per_page(true) as i32 - 1; + self.ui.chat.scroll_by(n, true); + } + KeyCode::PageDown => { + let n = self.ui.chat.lines_per_page(true) as i32 - 1; + self.ui.chat.scroll_by(-n, true); + } + _ => { + if screen.input.key(key, ctrl, shift) { + screen.edited(); + } else if let Some(text) = typed_text + && !ctrl + { + let typed: String = text.chars().filter(|c| !c.is_control()).collect(); + if !typed.is_empty() { + screen.input.insert_text(&typed); + screen.edited(); + } + } + } + } + if close { + self.close_chat(); + } else { + self.ui.chat_screen = Some(screen); + } + if let Some(message) = submit + && !message.is_empty() + { + self.handle_chat_input(&message); + } + } + /// Text typed into the chat box (control socket `chat`). + pub(super) fn chat_type(&mut self, text: &str) { + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.input.insert_text(text); + screen.edited(); + } + } + /// ChatScreen.handleChatInput: history, then a command or a chat line. + pub(super) fn handle_chat_input(&mut self, message: &str) { + self.ui.chat.add_recent(message); + if let Some(command) = message.strip_prefix('/') { + self.run_command(command); + } else { + let line = Text::translate("chat.type.text", &[Text::literal(PLAYER_NAME), Text::literal(message)]); + let focused = self.screen == Screen::Chat; + self.ui.chat.add(&self.res.atlas, line, None, self.ticks, focused); + } + } + pub(super) fn chat_scroll(&mut self, amount: f32) { + let cursor = self.cursor; + let height = self.renderer.as_ref().map_or(720.0, |r| HudBatch::new([r.config.width, r.config.height]).height); + if let Some(screen) = self.ui.chat_screen.as_mut() + && screen.scroll_suggestions(cursor, height, amount) + { + return; + } + let shift = self.keys.contains(&KeyCode::ShiftLeft); + let amount = amount.clamp(-1.0, 1.0) * if shift { 1.0 } else { 7.0 }; + self.ui.chat.scroll_by(amount as i32, true); + } + pub(super) fn chat_click(&mut self) { + let cursor = self.cursor; + let height = self.renderer.as_ref().map_or(720.0, |r| HudBatch::new([r.config.width, r.config.height]).height); + if let Some(screen) = self.ui.chat_screen.as_mut() + && !screen.click(cursor, height) + && screen.input.y <= cursor.1 + { + let i = screen.input.index_at(&self.res.atlas, cursor.0); + screen.input.set_cursor(i, false); + } + } + /// Chat lines over the HUD (focused while the chat screen is open). + pub(super) fn draw_chat(&mut self, batch: &mut HudBatch) { + let focused = self.screen == Screen::Chat; + if self.ui.hide_gui && !focused { + return; + } + self.ui.chat.draw(batch, &self.res.atlas, self.ticks, focused); + } + pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { + let Some(mut screen) = self.ui.chat_screen.take() else { return }; + screen.resize(batch.width, batch.height); + let bg = self.ui.chat.options.background_opacity; + screen.draw(batch, &self.res.atlas, vanilla::dispatcher(), &self.ui.registries, self.cursor, bg); + self.ui.chat_screen = Some(screen); + } + /// Advance the overworld clock (ServerClockManager.tick) when + /// `advance_time` allows it. + pub(super) fn advance_clock(&mut self) { + if !self.ui.rules.bool("advance_time") || self.ui.clock.paused || self.dim == Dim::Nether && false { + return; + } + let c = &mut self.ui.clock; + c.partial += c.rate; + let whole = c.partial.floor(); + c.partial -= whole; + self.world.day_time += whole as i64; + } + /// The engine-side rule values (block behaviour and health). + pub(super) fn level_rules(&self) -> horizon_world::level::GameRules { + let r = &self.ui.rules; + horizon_world::level::GameRules { + water_source_conversion: r.bool("water_source_conversion"), + lava_source_conversion: r.bool("lava_source_conversion"), + random_tick_speed: r.int("random_tick_speed"), + block_drops: r.bool("block_drops"), + mob_griefing: r.bool("mob_griefing"), + max_snow_accumulation_height: r.int("max_snow_accumulation_height"), + } + } + /// Apply rules mirrored in other state (natural regeneration, difficulty). + pub(super) fn sync_rules(&mut self) { + self.world.health_rules.natural_regeneration = self.ui.rules.bool("natural_health_regeneration"); + use horizon_world::food::Difficulty; + self.world.health_rules.difficulty = match self.ui.difficulty { + 0 => Difficulty::Peaceful, + 1 => Difficulty::Easy, + 3 => Difficulty::Hard, + _ => Difficulty::Normal, + }; + } + /// Load per-world command state when a world opens. + pub(super) fn load_world_state(&mut self) { + self.ui.rules = GameRules::load(&self.world_root); + self.ui.clock = WorldClock::default(); + self.ui.difficulty = read_difficulty(&self.world_root).unwrap_or(2); + if let Ok(bytes) = std::fs::read(self.world_root.join("data/minecraft/world_clocks.dat")) + && let Ok(raw) = horizon_world::compression::Compression::Gzip.decode(&bytes, 1 << 20) + && let Ok((root, _)) = horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()) + && let Some(c) = root.tag.get("data").and_then(|d| d.get("minecraft:overworld")) + { + use horizon_world::nbt::Tag; + if let Some(Tag::Float(r)) = c.get("rate") { + self.ui.clock.rate = f32::from_bits(*r); + } + if let Some(Tag::Float(p)) = c.get("partial_tick") { + self.ui.clock.partial = f32::from_bits(*p); + } + if let Some(Tag::Byte(p)) = c.get("paused") { + self.ui.clock.paused = *p != 0; + } + } + self.ui.chat.clear(); + self.build_registries(); + self.sync_rules(); + } + /// Save game rules, the clock and the difficulty beside level.dat. + pub(super) fn save_world_state(&mut self) { + if self.world_root.as_os_str().is_empty() { + return; + } + if let Err(e) = self.ui.rules.save(&self.world_root) { + eprintln!("Horizon: failed to save game rules: {e}"); + } + use horizon_world::nbt::{Limits, NamedTag, Tag}; + let c = self.ui.clock; + let clock = Tag::compound([ + ("total_ticks", Tag::Long(self.world.day_time)), + ("partial_tick", Tag::Float(c.partial.to_bits())), + ("rate", Tag::Float(c.rate.to_bits())), + ("paused", Tag::Byte(i8::from(c.paused))), + ]); + let root = NamedTag { + name: "".into(), + tag: Tag::compound([("data", Tag::compound([("minecraft:overworld", clock)])), ("DataVersion", Tag::Int(horizon_world::DATA_VERSION))]), + }; + if let Ok(bytes) = horizon_world::nbt::write_named(&root, Limits::default()) + && let Ok(gz) = horizon_world::compression::Compression::Gzip.encode(&bytes) + { + let dir = self.world_root.join("data/minecraft"); + let _ = std::fs::create_dir_all(&dir); + let _ = std::fs::write(dir.join("world_clocks.dat"), gz); + } + let _ = write_difficulty(&self.world_root, self.ui.difficulty); + } + /// Death message in chat (CombatTracker.getDeathMessage, as far as the + /// cause is known to the client). + pub(super) fn death_message(&mut self) { + let cause = self.ui.death_cause.take(); + if !self.ui.rules.bool("show_death_messages") { + return; + } + let Some(p) = self.player.as_ref() else { return }; + let key = cause.unwrap_or_else(|| { + let feet = [p.position.x.floor() as i32, p.position.y.floor() as i32, p.position.z.floor() as i32]; + let fluid = self.res.facts.get(self.world.block(feet[0], feet[1], feet[2])).fluid; + if p.position.y < f64::from(horizon_client::chunk::MIN_Y - 64) { + "death.attack.outOfWorld".into() + } else if fluid == horizon_client::blocks::Fluid::Lava { + "death.attack.lava".into() + } else if p.fall_distance > 3.0 || p.ground.on_ground && p.velocity.y < -0.5 { + "death.attack.fall".into() + } else { + "death.attack.generic".into() + } + }); + self.system_message(Text::translate(&key, &[Text::literal(PLAYER_NAME)])); + } + /// F1 hides the HUD (and hand); the screenshot key still works. + pub(super) fn toggle_hide_gui(&mut self) { + self.ui.hide_gui = !self.ui.hide_gui; + } + /// F2: ScreenShot.grab into `screenshots/` with vanilla's file name. + pub(super) fn take_screenshot(&mut self) { + let dir = std::env::current_dir().unwrap_or_default().join("screenshots"); + if std::fs::create_dir_all(&dir).is_err() { + return; + } + let name = screenshot_name(&dir); + let Some(renderer) = self.renderer.as_mut() else { return }; + renderer.screenshot = Some(dir.join(&name)); + self.ui.screenshot_message = Some(name); + } + /// After a frame: report a finished F2 screenshot in chat. + pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) { + let Some(name) = self.ui.screenshot_message.take() else { return }; + let message = match result { + Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]), + Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]), + }; + let focused = self.screen == Screen::Chat; + self.ui.chat.add(&self.res.atlas, message, None, self.ticks, focused); + } + #[allow(dead_code)] + fn chat_debug_fill(&self, batch: &mut HudBatch) { + batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + } +} +/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time +/// approximated as UTC). +pub fn screenshot_name(dir: &std::path::Path) -> String { + let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs()); + let days = (secs / 86400) as i64; + let (h, m, s) = ((secs % 86400) / 3600, (secs % 3600) / 60, secs % 60); + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z - era * 146_097; + let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let mo = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = yoe + era * 400 + i64::from(mo <= 2); + let base = format!("{y}-{mo:02}-{d:02}_{h:02}.{m:02}.{s:02}"); + let mut n = 1; + loop { + let name = if n == 1 { format!("{base}.png") } else { format!("{base}_{n}.png") }; + if !dir.join(&name).exists() { + return name; + } + n += 1; + } +} +fn read_difficulty(world: &std::path::Path) -> Option { + let bytes = std::fs::read(world.join("level.dat")).ok()?; + let raw = horizon_world::compression::Compression::Gzip.decode(&bytes, 64 << 20).ok()?; + let (root, _) = horizon_world::nbt::read_named(&raw, horizon_world::nbt::Limits::default()).ok()?; + match root.tag.get("Data")?.get("Difficulty")? { + horizon_world::nbt::Tag::Byte(b) => Some((*b).clamp(0, 3) as u8), + _ => None, + } +} +/// Patch `Data.Difficulty` in level.dat (Level::write stores the default). +fn write_difficulty(world: &std::path::Path, difficulty: u8) -> horizon_client::Result<()> { + use horizon_world::{compression::Compression, nbt}; + let path = world.join("level.dat"); + let bytes = std::fs::read(&path)?; + let raw = Compression::Gzip.decode(&bytes, 64 << 20)?; + let (mut root, _) = nbt::read_named(&raw, nbt::Limits::default()).map_err(|e| e.to_string())?; + if let Some(data) = root.tag.get_mut("Data") + && let Some(d) = data.get_mut("Difficulty") + { + *d = nbt::Tag::Byte(difficulty as i8); + } + let out = nbt::write_named(&root, nbt::Limits::default()).map_err(|e| e.to_string())?; + std::fs::write(&path, Compression::Gzip.encode(&out)?)?; + Ok(()) +} diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs new file mode 100644 index 000000000..574de770c --- /dev/null +++ b/crates/horizon-client/src/game/commands.rs @@ -0,0 +1,1231 @@ +//! Command execution (the `execute` side of each vanilla command class): +//! entity selectors resolved against the game, vanilla feedback and errors. +use super::{Dim, Game, Screen, chat::PLAYER_NAME}; +use horizon_client::{ + command::{ + Arg, CommandError, Context, Reader, + args::{BlockInput, Coordinates, GameMode, ItemInput, Selector, Sort}, + vanilla::{self, DIFFICULTIES}, + }, + gamerules::{self, Value}, + items::ItemStack, + text::{self, Style, Text}, +}; +use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_world::registry::BlockStateId; + +type R = Result; + +/// An entity a selector found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Target { + Player, + Mob(u32), + Item(u32), + Orb(usize), + Arrow(usize), +} +fn err(key: &str, args: &[&dyn std::fmt::Display]) -> CommandError { + CommandError::tr(key, args) +} +fn texts(args: &[Text]) -> Vec { + args.to_vec() +} +/// Java's String.valueOf(float/double) for the values commands print. +fn java_float(v: f64) -> String { + if v == v.trunc() && v.abs() < 1.0e7 { format!("{v:.1}") } else { format!("{v}") } +} +/// String.format(Locale.ROOT, "%f"). +fn format_double(v: f64) -> String { + format!("{v:.6}") +} + +impl Game<'_> { + /// Commands.performCommand for a line without its slash. + pub(super) fn run_command(&mut self, command: &str) { + let d = vanilla::dispatcher(); + let parse = d.parse(command, &self.ui.registries); + let result = match parse.executable() { + Err(e) => { + self.syntax_failure(&e, command); + return; + } + Ok((ctx, id)) => { + let ctx = ctx.clone(); + self.execute_command(id, &ctx) + } + }; + if let Err(e) = result { + if e.input.is_some() { + self.syntax_failure(&e, command); + } else { + self.command_failure(e.message); + } + } + } + fn syntax_failure(&mut self, e: &CommandError, command: &str) { + self.command_failure(e.message.clone()); + let Some(input) = &e.input else { return }; + let cursor = e.cursor.min(input.len()); + let suggest = Style { suggest: Some(format!("/{command}")), ..Style::default() }; + let mut context = Text::empty(); + if cursor > 10 { + context.push("..."); + } + let start = input.floor_char_boundary(cursor.saturating_sub(10)); + context.push(&input[start..cursor]); + if cursor < input.len() { + context.push(Text::literal(&input[cursor..]).with_color(text::RED).underlined()); + } + context.push(Text::translate("command.context.here", &[]).with_color(text::RED).italic()); + self.command_failure(context.with_color(text::GRAY).with_style(&suggest)); + } + /// CommandSourceStack.sendFailure: red text. + fn command_failure(&mut self, message: Text) { + self.system_message(message.with_color(text::RED)); + } + /// sendSuccess honouring `send_command_feedback`. + fn feedback(&mut self, message: Text) { + if self.ui.rules.bool("send_command_feedback") { + self.system_message(message); + } + } + fn source_position(&self) -> [f64; 3] { + match &self.player { + Some(p) => [p.position.x, p.position.y, p.position.z], + None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]), + } + } + fn source_rotation(&self) -> [f32; 2] { + [self.yaw, self.pitch] + } + fn coords(&self, ctx: &Context, name: &str) -> Option { + match ctx.get(name) { + Some(Arg::Coords(c)) => Some(c.clone()), + _ => None, + } + } + fn position_arg(&self, ctx: &Context, name: &str) -> Option<[f64; 3]> { + self.coords(ctx, name).map(|c| c.position(self.source_position(), self.source_rotation())) + } + /// BlockPosArgument.getLoadedBlockPos. + fn block_pos_arg(&self, ctx: &Context, name: &str) -> R<[i32; 3]> { + let c = self.coords(ctx, name).ok_or_else(|| err("argument.pos.missing.int", &[]))?; + let p = c.block(self.source_position(), self.source_rotation()); + if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { + return Err(err("argument.pos.unloaded", &[])); + } + if p[1] < horizon_client::chunk::MIN_Y || p[1] >= horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT { + return Err(err("argument.pos.outofworld", &[])); + } + Ok(p) + } + fn int(ctx: &Context, name: &str) -> Option { + match ctx.get(name) { + Some(Arg::Int(v)) => Some(*v), + _ => None, + } + } + // ---- entities ------------------------------------------------------- + + fn target_position(&self, t: Target) -> Option<[f64; 3]> { + match t { + Target::Player => self.player.as_ref().map(|p| [p.position.x, p.position.y, p.position.z]), + Target::Mob(id) => self.mobs.iter().find(|m| m.id == id).map(|m| [m.position.x, m.position.y, m.position.z]), + Target::Item(id) => self.dropped.iter().find(|i| i.id == id).map(|i| [i.position.x, i.position.y, i.position.z]), + Target::Orb(i) => self.orbs.get(i).map(|o| [o.position.x, o.position.y, o.position.z]), + Target::Arrow(i) => self.arrows.get(i).map(|a| [a.position.x, a.position.y, a.position.z]), + } + } + fn target_type(&self, t: Target) -> String { + match t { + Target::Player => "minecraft:player".into(), + Target::Mob(id) => self.mobs.iter().find(|m| m.id == id).map_or_else(String::new, |m| horizon_client::command::args::normalize(&m.kind.id)), + Target::Item(_) => "minecraft:item".into(), + Target::Orb(_) => "minecraft:experience_orb".into(), + Target::Arrow(_) => "minecraft:arrow".into(), + } + } + /// Entity.getDisplayName. + pub(super) fn target_name(&self, t: Target) -> Text { + match t { + Target::Player => Text::literal(PLAYER_NAME), + Target::Item(id) => { + let item = self.dropped.iter().find(|i| i.id == id).map(|i| i.stack.item.to_string()).unwrap_or_default(); + Text::literal(self.res.names.item(&item)) + } + other => { + let ty = self.target_type(other); + Text::translate(&format!("entity.{}", ty.replace(':', ".")), &[]) + } + } + } + /// EntitySelector.findEntities. + fn select(&mut self, s: &Selector) -> Vec { + if let Some(name) = &s.player_name { + return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() { vec![Target::Player] } else { Vec::new() }; + } + let origin = { + let p = self.source_position(); + [s.pos[0].unwrap_or(p[0]), s.pos[1].unwrap_or(p[1]), s.pos[2].unwrap_or(p[2])] + }; + let mut candidates: Vec = Vec::new(); + if self.player.is_some() { + candidates.push(Target::Player); + } + if s.kind != 's' { + candidates.extend(self.mobs.iter().filter(|m| m.death_time == 0).map(|m| Target::Mob(m.id))); + candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id))); + candidates.extend((0..self.orbs.len()).map(Target::Orb)); + candidates.extend((0..self.arrows.len()).map(Target::Arrow)); + } + let level = self.experience.level; + let creative = self.creative; + let mut out: Vec<(Target, f64)> = candidates + .into_iter() + .filter_map(|t| { + let p = self.target_position(t)?; + let ty = self.target_type(t); + // type=: every positive must match, no negative may match. + for (want, neg) in &s.types { + let matches = if let Some(tag) = want.strip_prefix('#') { self.entity_tag_matches(tag, &ty) } else { *want == ty }; + if matches == *neg { + return None; + } + } + if !s.include_entities && t != Target::Player && s.types.iter().all(|(w, n)| *n || w != &ty) && s.kind != 'e' && s.kind != 'n' { + return None; + } + for (name, neg) in &s.names { + let n = self.target_name(t).plain(); + if (n == *name) == *neg { + return None; + } + } + for (_, neg) in &s.tags { + if !*neg { + return None; + } + } + if let Some((lo, hi)) = s.level { + if t != Target::Player || lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h) { + return None; + } + } + for (mode, neg) in &s.gamemodes { + let current = if creative { "creative" } else { "survival" }; + if t != Target::Player || (current == mode) == *neg { + return None; + } + } + let d2 = (p[0] - origin[0]).powi(2) + (p[1] - origin[1]).powi(2) + (p[2] - origin[2]).powi(2); + if let Some((lo, hi)) = s.distance + && (lo.is_some_and(|l| d2 < l * l) || hi.is_some_and(|h| d2 > h * h)) + { + return None; + } + if s.delta.iter().any(Option::is_some) { + let d = s.delta.map(|v| v.unwrap_or(0.0)); + for i in 0..3 { + let (a, b) = (origin[i].min(origin[i] + d[i]), origin[i].max(origin[i] + d[i]) + 1.0); + if p[i] < a || p[i] >= b { + return None; + } + } + } + Some((t, d2)) + }) + .collect(); + match s.sort { + Sort::Nearest => out.sort_by(|a, b| a.1.total_cmp(&b.1)), + Sort::Furthest => out.sort_by(|a, b| b.1.total_cmp(&a.1)), + Sort::Random => { + for i in (1..out.len()).rev() { + let j = self.world.random.next_int_bound(i as i32 + 1).unwrap_or(0) as usize; + out.swap(i, j); + } + } + Sort::Arbitrary => {} + } + out.into_iter().take(s.limit.max(1)).map(|(t, _)| t).collect() + } + fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool { + let path = self.options.resources.join(format!("data/minecraft/tags/entity_type/{}.json", tag.trim_start_matches("minecraft:"))); + serde_json::from_slice::(&std::fs::read(path).unwrap_or_default()) + .ok() + .is_some_and(|v| v["values"].as_array().is_some_and(|a| a.iter().any(|e| e.as_str() == Some(ty)))) + } + /// EntityArgument.getEntities / getPlayers / getEntity / getPlayer. + fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R> { + let Some(Arg::Entity(s)) = ctx.get(name).cloned() else { return Ok(vec![Target::Player]) }; + let found: Vec = self.select(&s).into_iter().filter(|t| !players || *t == Target::Player).collect(); + if found.is_empty() { + return Err(err(if players { "argument.entity.notfound.player" } else { "argument.entity.notfound.entity" }, &[])); + } + Ok(found) + } + // ---- dispatch ------------------------------------------------------- + + fn execute_command(&mut self, id: &str, ctx: &Context) -> R { + match id { + "help" => self.cmd_help(ctx), + "gamemode" => self.cmd_gamemode(ctx), + "defaultgamemode" => { + let Some(Arg::GameMode(m)) = ctx.get("gamemode") else { return Ok(0) }; + self.feedback(Text::translate("commands.defaultgamemode.success", &[Text::translate(&format!("gameMode.{}", m.name()), &[])])); + Ok(0) + } + "give" => self.cmd_give(ctx), + "teleport.location" | "teleport.destination" | "teleport.targets.location" | "teleport.targets.destination" => self.cmd_teleport(id, ctx), + id if id.starts_with("time.") => self.cmd_time(id, ctx), + "weather" => self.cmd_weather(ctx), + "kill" => self.cmd_kill(ctx), + "summon" => self.cmd_summon(ctx), + "setblock" => self.cmd_setblock(ctx), + "fill" => self.cmd_fill(ctx), + "clone" => self.cmd_clone(ctx), + "experience" => self.cmd_experience(ctx), + "gamerule" => self.cmd_gamerule(ctx), + "difficulty" => self.cmd_difficulty(ctx), + "seed" => { + let seed = self.level.seed.to_string(); + let green = Style { color: Some(text::GREEN), suggest: None, ..Style::default() }; + let value = Text::literal("[").append(Text::styled(seed.clone(), green)).append("]"); + self.system_message(Text::translate("commands.seed.success", &[value])); + Ok(self.level.seed as i32) + } + "spawnpoint" => self.cmd_spawnpoint(ctx), + "setworldspawn" => self.cmd_setworldspawn(ctx), + "clear" => self.cmd_clear(ctx), + "locate.structure" | "locate.biome" => self.cmd_locate(id, ctx), + "say" | "me" | "msg" => self.cmd_say(id, ctx), + "list" => { + let names = if ctx.has("uuids") { + Text::translate("commands.list.nameAndId", &[Text::literal(PLAYER_NAME), Text::literal("00000000-0000-0000-0000-000000000000")]) + } else { + Text::literal(PLAYER_NAME) + }; + self.system_message(Text::translate("commands.list.players", &[Text::literal("1"), Text::literal("8"), names])); + Ok(1) + } + _ => Err(err("command.failed", &[])), + } + } + fn cmd_help(&mut self, ctx: &Context) -> R { + let d = vanilla::dispatcher(); + let level = self.ui.registries.permission; + match ctx.get("command") { + None => { + let usage = d.smart_usage(0, level); + let n = usage.len() as i32; + for (_, line) in usage { + self.system_message(Text::literal(format!("/{line}"))); + } + Ok(n) + } + Some(Arg::Str(command)) => { + let parse = d.parse(command, &self.ui.registries); + if parse.context.nodes.is_empty() { + return Err(err("commands.help.failed", &[])); + } + let last = parse.context.nodes.last().map(|n| n.0).unwrap_or(0); + let usage = d.smart_usage(last, level); + let prefix = &command[..parse.context.range.1.min(command.len())]; + for (_, line) in &usage { + self.system_message(Text::literal(format!("/{prefix} {line}"))); + } + if usage.is_empty() { + self.system_message(Text::literal(format!("/{prefix}"))); + } + Ok(usage.len().max(1) as i32) + } + _ => Ok(0), + } + } + fn set_game_mode(&mut self, mode: GameMode) -> bool { + let creative = mode == GameMode::Creative; + if self.creative == creative && matches!(mode, GameMode::Survival | GameMode::Creative) { + return false; + } + self.creative = creative; + if self.screen == Screen::Inventory && creative { + self.screen = Screen::Playing; + } + true + } + fn cmd_gamemode(&mut self, ctx: &Context) -> R { + let Some(Arg::GameMode(mode)) = ctx.get("gamemode").cloned() else { return Ok(0) }; + let targets = if ctx.get("target").is_some() { self.entities(ctx, "target", true)? } else { vec![Target::Player] }; + let mut count = 0; + for t in targets { + if t != Target::Player || !self.set_game_mode(mode) { + continue; + } + count += 1; + let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); + if ctx.get("target").is_none() { + self.feedback(Text::translate("commands.gamemode.success.self", &[mode_name])); + } else { + self.system_message(Text::translate("gameMode.changed", &[mode_name.clone()])); + self.feedback(Text::translate("commands.gamemode.success.other", &[Text::literal(PLAYER_NAME), mode_name])); + } + } + Ok(count) + } + /// ItemStack.getDisplayName: "[Name]" in the rarity colour. + pub(super) fn item_display_name(&self, item: &str) -> Text { + let rarity = self.item_rarity(item); + let color = match rarity.as_str() { + "uncommon" => text::YELLOW, + "rare" => text::AQUA, + "epic" => text::LIGHT_PURPLE, + _ => text::WHITE, + }; + Text::literal("[").append(Text::literal(self.res.names.item(item))).append("]").with_color(color) + } + fn item_rarity(&self, item: &str) -> String { + static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); + let map = RARITY.get_or_init(|| { + let v: serde_json::Value = serde_json::from_slice(&std::fs::read(self.options.resources.join("items.json")).unwrap_or_default()).unwrap_or_default(); + v.as_object() + .map(|o| o.iter().filter_map(|(k, c)| c["minecraft:rarity"].as_str().map(|r| (k.clone(), r.to_owned()))).collect()) + .unwrap_or_default() + }); + map.get(item).cloned().unwrap_or_else(|| "common".into()) + } + fn cmd_give(&mut self, ctx: &Context) -> R { + let Some(Arg::Item(ItemInput { id, .. })) = ctx.get("item").cloned() else { return Ok(0) }; + let count = Self::int(ctx, "count").unwrap_or(1); + let targets = self.entities(ctx, "targets", true)?; + let max_stack = self.res.items.get(&id).map_or(64, |i| i.max_stack) as i32; + if count > max_stack * 100 { + return Err(CommandError::new(Text::translate("commands.give.failed.toomanyitems", &[Text::literal((max_stack * 100).to_string()), self.item_display_name(&id)]))); + } + for _ in &targets { + let mut remaining = count; + while remaining > 0 { + let size = remaining.min(max_stack); + remaining -= size; + let left = self.give(ItemStack { item: id.as_str().into(), count: size as u32, damage: 0 }); + if let Some(rest) = left { + // Inventory full: drop the rest at the player's feet without pickup delay. + let p = self.source_position(); + self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); + } else { + let r = &mut self.world.random; + let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; + let p = self.source_position(); + self.audio.play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + } + } + } + let name = self.item_display_name(&id); + let message = if targets.len() == 1 { + Text::translate("commands.give.success.single", &[Text::literal(count.to_string()), name, Text::literal(PLAYER_NAME)]) + } else { + Text::translate("commands.give.success.multiple", &texts(&[Text::literal(count.to_string()), name, Text::literal(targets.len().to_string())])) + }; + self.feedback(message); + Ok(targets.len() as i32) + } + fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { + let v = Vec3::new(pos[0], pos[1], pos[2]); + match t { + Target::Player => { + if let Some(p) = self.player.as_mut() { + p.position = v; + p.velocity = Vec3::new(0.0, 0.0, 0.0); + p.fall_distance = 0.0; + p.ground.on_ground = false; + } + self.previous_position = v; + if let Some([yaw, pitch]) = rotation { + self.yaw = yaw; + self.pitch = pitch.clamp(-90.0, 90.0); + } + } + Target::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.position = v; + m.previous = v; + if let Some([yaw, _]) = rotation { + m.yaw = yaw; + m.body_yaw = yaw; + } + } + } + Target::Item(id) => { + if let Some(i) = self.dropped.iter_mut().find(|i| i.id == id) { + i.position = v; + i.previous = v; + } + } + Target::Orb(i) => { + if let Some(o) = self.orbs.get_mut(i) { + o.position = v; + o.previous = v; + } + } + Target::Arrow(i) => { + if let Some(a) = self.arrows.get_mut(i) { + a.position = v; + a.previous = v; + } + } + } + } + fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R { + let targets = if id.starts_with("teleport.targets") { self.entities(ctx, "targets", false)? } else { vec![Target::Player] }; + if id.ends_with("destination") { + let dest = self.entities(ctx, "destination", false)?[0]; + let pos = self.target_position(dest).unwrap_or(self.source_position()); + for &t in &targets { + self.teleport_to(t, pos, None); + } + let message = if targets.len() == 1 { + Text::translate("commands.teleport.success.entity.single", &[self.target_name(targets[0]), self.target_name(dest)]) + } else { + Text::translate("commands.teleport.success.entity.multiple", &[Text::literal(targets.len().to_string()), self.target_name(dest)]) + }; + self.feedback(message); + return Ok(targets.len() as i32); + } + let pos = self.position_arg(ctx, "location").unwrap_or(self.source_position()); + if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) || !(-20_000_000.0..20_000_000.0).contains(&pos[1]) { + return Err(err("commands.teleport.invalidPosition", &[])); + } + let mut rotation = match ctx.get("rotation") { + Some(Arg::Coords(c)) => Some(c.rotation(self.source_rotation())), + _ => None, + }; + // facing: look from the new position at a location or entity. + let facing = self.position_arg(ctx, "facingLocation").or_else(|| { + let Some(Arg::Entity(_)) = ctx.get("facingEntity") else { return None }; + None + }); + let facing = match (facing, ctx.get("facingEntity")) { + (Some(f), _) => Some(f), + (None, Some(_)) => { + let e = self.entities(ctx, "facingEntity", false)?[0]; + let eyes = matches!(ctx.get("facingAnchor"), Some(Arg::Anchor(true))); + self.target_position(e).map(|p| [p[0], p[1] + if eyes { 1.62 } else { 0.0 }, p[2]]) + } + _ => None, + }; + if let Some(f) = facing { + let eye = pos[1] + 1.62; + let (dx, dy, dz) = (f[0] - pos[0], f[1] - eye, f[2] - pos[2]); + let horizontal = (dx * dx + dz * dz).sqrt(); + rotation = Some([((dz.atan2(dx).to_degrees()) - 90.0) as f32, (-(dy.atan2(horizontal).to_degrees())) as f32]); + } + for &t in &targets { + self.teleport_to(t, pos, rotation); + } + let [x, y, z] = pos.map(|v| Text::literal(format_double(v))); + let message = if targets.len() == 1 { + Text::translate("commands.teleport.success.location.single", &[self.target_name(targets[0]), x, y, z]) + } else { + Text::translate("commands.teleport.success.location.multiple", &[Text::literal(targets.len().to_string()), x, y, z]) + }; + self.feedback(message); + Ok(targets.len() as i32) + } + fn cmd_time(&mut self, id: &str, ctx: &Context) -> R { + if id == "time.query.gametime" { + let t = self.world.game_time; + self.system_message(Text::tr("commands.time.query.gametime", &[&t])); + return Ok((t % i64::from(i32::MAX)) as i32); + } + // `time of ` names the clock; otherwise the dimension's default clock. + let clock = match ctx.get("clock") { + Some(Arg::Resource(c)) => c.clone(), + _ => { + if self.dim == Dim::Nether { + return Err(err("commands.time.no_default_clock", &[&"minecraft:the_nether"])); + } + "minecraft:overworld".to_owned() + } + }; + if clock != "minecraft:overworld" { + // Only the overworld clock runs in Horizon (no End yet). + return Err(err("commands.time.no_default_clock", &[&clock])); + } + let total = self.world.day_time; + match id { + "time.set" => { + let t = i64::from(Self::int(ctx, "time").unwrap_or(0)); + if total == t { + return Err(err("commands.time.set.already_at_time", &[&clock, &t])); + } + self.world.day_time = t; + self.ui.clock.partial = 0.0; + self.feedback(Text::tr("commands.time.set.absolute", &[&clock, &t])); + Ok(t as i32) + } + "time.set.marker" => { + let Some(Arg::Resource(marker)) = ctx.get("timemarker").cloned() else { return Ok(0) }; + let Some(m) = self.ui.markers.get(&marker).copied() else { + return Err(err("commands.time.no_time_marker_found", &[&marker, &clock])); + }; + if m.occurs_at(total) { + return Err(err("commands.time.set.already_at_time_marker", &[&clock, &marker])); + } + self.world.day_time = m.resolve(total); + self.ui.clock.partial = 0.0; + self.feedback(Text::tr("commands.time.set.time_marker", &[&clock, &marker])); + Ok((self.world.day_time % i64::from(i32::MAX)) as i32) + } + "time.add" => { + let t = i64::from(Self::int(ctx, "time").unwrap_or(0)); + self.world.day_time = (total + t).max(0); + let now = self.world.day_time; + self.feedback(Text::tr("commands.time.set.absolute", &[&clock, &now])); + Ok((now % i64::from(i32::MAX)) as i32) + } + "time.pause" | "time.resume" => { + let pause = id == "time.pause"; + if self.ui.clock.paused == pause { + return Err(err(if pause { "commands.time.pause.already_paused" } else { "commands.time.pause.already_running" }, &[&clock])); + } + self.ui.clock.paused = pause; + self.feedback(Text::tr(if pause { "commands.time.pause" } else { "commands.time.resume" }, &[&clock])); + Ok(1) + } + "time.rate" => { + let rate = match ctx.get("rate") { + Some(Arg::Float(r)) => *r, + _ => 1.0, + }; + if self.ui.clock.rate == rate { + return Err(err("commands.time.rate.already_same", &[&clock, &java_float(f64::from(rate))])); + } + self.ui.clock.rate = rate; + self.feedback(Text::tr("commands.time.rate", &[&clock, &java_float(f64::from(rate))])); + Ok(1) + } + "time.query.time" => { + self.system_message(Text::tr("commands.time.query.absolute", &[&clock, &total])); + Ok((total % i64::from(i32::MAX)) as i32) + } + "time.query.timeline" | "time.query.repetition" => { + let Some(Arg::Resource(timeline)) = ctx.get("timeline").cloned() else { return Ok(0) }; + let Some(period) = self.ui.timelines.get(&timeline).copied() else { + return Err(err("commands.time.wrong_timeline_for_clock", &[&clock, &timeline])); + }; + if id == "time.query.timeline" { + let ticks = period.map_or(total, |p| total.rem_euclid(p)); + self.system_message(Text::tr("commands.time.query.timeline", &[&timeline, &ticks])); + Ok(ticks as i32) + } else { + let reps = period.map_or(0, |p| total / p); + self.system_message(Text::tr("commands.time.query.timeline.repetitions", &[&timeline, &reps])); + Ok(reps as i32) + } + } + _ => Ok(0), + } + } + fn cmd_weather(&mut self, ctx: &Context) -> R { + let duration = Self::int(ctx, "duration"); + let sample = |min: i32, max: i32, r: &mut horizon_core::random::LegacyRandom| min + r.next_int_bound(max - min + 1).unwrap_or(0); + let w = &mut self.world.weather; + let r = &mut self.world.random; + let (key, clear, time, raining, thundering) = if ctx.has("clear") { + ("commands.weather.set.clear", duration.unwrap_or_else(|| sample(12_000, 180_000, r)), 0, false, false) + } else if ctx.has("rain") { + ("commands.weather.set.rain", 0, duration.unwrap_or_else(|| sample(12_000, 24_000, r)), true, false) + } else { + ("commands.weather.set.thunder", 0, duration.unwrap_or_else(|| sample(3_600, 15_600, r)), true, true) + }; + // ServerLevel.setWeatherParameters. + w.clear_time = clear; + w.rain_time = time; + w.thunder_time = time; + w.raining = raining; + w.thundering = thundering; + self.feedback(Text::translate(key, &[])); + Ok(duration.unwrap_or(0)) + } + fn kill_target(&mut self, t: Target) { + match t { + Target::Player => { + if let Some(p) = self.player.as_mut() { + let _ = p.set_health(0.0, false); + } + self.ui.death_cause = Some("death.attack.genericKill".into()); + } + Target::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.health = 0.0; + if m.death_time == 0 { + m.death_time = 1; + } + } + } + Target::Item(id) => self.dropped.retain(|i| i.id != id), + Target::Orb(i) => { + if i < self.orbs.len() { + self.orbs[i].age = u32::MAX / 2; + } + } + Target::Arrow(i) => { + if i < self.arrows.len() { + self.arrows[i].age = u32::MAX / 2; + } + } + } + } + fn cmd_kill(&mut self, ctx: &Context) -> R { + let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", false)? } else { vec![Target::Player] }; + let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect(); + // Remove indexed entities from the back so earlier indices stay valid. + let mut ordered = targets.clone(); + ordered.sort_by_key(|t| std::cmp::Reverse(match t { + Target::Orb(i) | Target::Arrow(i) => *i, + _ => 0, + })); + for t in ordered { + self.kill_target(t); + } + self.orbs.retain(|o| o.age < u32::MAX / 2); + self.arrows.retain(|a| a.age < u32::MAX / 2); + let message = if targets.len() == 1 { + Text::translate("commands.kill.success.single", &[names[0].clone()]) + } else { + Text::tr("commands.kill.success.multiple", &[&targets.len()]) + }; + self.feedback(message); + Ok(targets.len() as i32) + } + fn cmd_summon(&mut self, ctx: &Context) -> R { + let Some(Arg::Resource(kind)) = ctx.get("entity").cloned() else { return Ok(0) }; + let pos = self.position_arg(ctx, "pos").unwrap_or(self.source_position()); + let block_y = pos[1].floor() as i32; + if !(-30_000_000.0..30_000_000.0).contains(&pos[0]) || !(-20_000_000..20_000_000).contains(&block_y) || !(-30_000_000.0..30_000_000.0).contains(&pos[2]) { + return Err(err("commands.summon.invalidPosition", &[])); + } + let short = kind.trim_start_matches("minecraft:").to_owned(); + let name; + if let Some(t) = self.res.mob_types.get(&short).cloned() { + if self.ui.difficulty == 0 && t.category == "monster" { + return Err(err("commands.summon.failed.peaceful", &[])); + } + self.add_mob(&short, pos[0], pos[1], pos[2], true); + name = Text::translate(&format!("entity.minecraft.{short}"), &[]); + } else { + match short.as_str() { + "item" => { + // An item entity needs an item; vanilla spawns an empty one that despawns. + return Err(err("commands.summon.failed", &[])); + } + "experience_orb" => { + self.orbs.push(horizon_client::entities::ExperienceOrb { + position: Vec3::new(pos[0], pos[1], pos[2]), + previous: Vec3::new(pos[0], pos[1], pos[2]), + velocity: Vec3::new(0.0, 0.0, 0.0), + value: 0, + age: 0, + on_ground: false, + }); + name = Text::translate("entity.minecraft.experience_orb", &[]); + } + _ => return Err(err("commands.summon.failed", &[])), + } + } + self.feedback(Text::translate("commands.summon.success", &[name])); + Ok(1) + } + /// BlockStateArgument -> registry state. + fn block_state(&self, b: &BlockInput) -> R { + let state = horizon_world::chunk::BlockState { name: b.id.clone(), properties: b.properties.iter().cloned().collect() }; + self.res.assets.registry.resolve(&state).map_err(|_| err("argument.block.id.invalid", &[&b.id])) + } + /// BlockPredicateArgument test. + fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool { + let Some(s) = self.res.assets.registry.state(state) else { return false }; + let name_ok = if b.tag { + let tag = b.id.trim_start_matches("minecraft:"); + self.res.items.block_tags.get(tag).or_else(|| self.res.items.block_tags.get(&b.id)).is_some_and(|set| set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:"))) + } else { + s.name == b.id + }; + name_ok && b.properties.iter().all(|(k, v)| s.properties.get(k) == Some(v)) + } + /// Place a state like BlockInput.place: false when nothing changed. + fn place_state(&mut self, pos: [i32; 3], state: BlockStateId, strict: bool) -> R { + if self.world.block(pos[0], pos[1], pos[2]) == state { + return Ok(false); + } + if strict { + self.with_level(|b, level, ticks| { + b.set_block(level, ticks, horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]), state, horizon_world::level::flags::UPDATE_CLIENTS | horizon_world::level::flags::UPDATE_SKIP_ALL_SIDEEFFECTS); + }); + self.process_level_events().map_err(|e| CommandError::new(Text::literal(e.to_string())))?; + } else { + self.level_set(pos, state).map_err(|e| CommandError::new(Text::literal(e.to_string())))?; + } + Ok(true) + } + fn cmd_setblock(&mut self, ctx: &Context) -> R { + let pos = self.block_pos_arg(ctx, "pos")?; + let Some(Arg::Block(b)) = ctx.get("block").cloned() else { return Ok(0) }; + let state = self.block_state(&b)?; + let current = self.world.block(pos[0], pos[1], pos[2]); + if ctx.has("keep") && current != self.world.air { + return Err(err("commands.setblock.failed", &[])); + } + if ctx.has("destroy") && current != self.world.air { + let creative = self.creative; + self.creative = false; + let _ = self.break_block(pos); + self.creative = creative; + } + if !self.place_state(pos, state, ctx.has("strict"))? { + return Err(err("commands.setblock.failed", &[])); + } + self.feedback(Text::tr("commands.setblock.success", &[&pos[0], &pos[1], &pos[2]])); + Ok(1) + } + fn cmd_fill(&mut self, ctx: &Context) -> R { + let a = self.block_pos_arg(ctx, "from")?; + let b = self.block_pos_arg(ctx, "to")?; + let Some(Arg::Block(block)) = ctx.get("block").cloned() else { return Ok(0) }; + let filter = match ctx.get("filter") { + Some(Arg::Block(f)) => Some(f.clone()), + _ => None, + }; + let min = [a[0].min(b[0]), a[1].min(b[1]), a[2].min(b[2])]; + let max = [a[0].max(b[0]), a[1].max(b[1]), a[2].max(b[2])]; + let area = (0..3).map(|i| i64::from(max[i] - min[i] + 1)).product::(); + let limit = self.ui.rules.int("max_block_modifications"); + if area > i64::from(limit) { + return Err(err("commands.fill.toobig", &[&limit, &area])); + } + let state = self.block_state(&block)?; + let air = self.world.air; + let (hollow, outline, destroy, strict, keep) = (ctx.has("hollow"), ctx.has("outline"), ctx.has("destroy"), ctx.has("strict"), ctx.has("keep")); + let mut count = 0; + for y in min[1]..=max[1] { + for z in min[2]..=max[2] { + for x in min[0]..=max[0] { + let current = self.world.block(x, y, z); + if keep && current != air { + continue; + } + if let Some(f) = &filter + && !self.block_matches(f, current) + { + continue; + } + let edge = x == min[0] || x == max[0] || y == min[1] || y == max[1] || z == min[2] || z == max[2]; + let mut affected = false; + if destroy && current != air { + let creative = self.creative; + self.creative = false; + let _ = self.break_block([x, y, z]); + self.creative = creative; + affected = true; + } + let target = if (outline || hollow) && !edge { + if outline { + if affected { + count += 1; + } + continue; + } + air + } else { + state + }; + if self.place_state([x, y, z], target, strict)? || affected { + count += 1; + } + } + } + } + if count == 0 { + return Err(err("commands.fill.failed", &[])); + } + self.feedback(Text::tr("commands.fill.success", &[&count])); + Ok(count) + } + fn cmd_clone(&mut self, ctx: &Context) -> R { + let a = self.block_pos_arg(ctx, "begin")?; + let b = self.block_pos_arg(ctx, "end")?; + let dest = self.block_pos_arg(ctx, "destination")?; + let min = [a[0].min(b[0]), a[1].min(b[1]), a[2].min(b[2])]; + let max = [a[0].max(b[0]), a[1].max(b[1]), a[2].max(b[2])]; + let size = [max[0] - min[0], max[1] - min[1], max[2] - min[2]]; + let dmax = [dest[0] + size[0], dest[1] + size[1], dest[2] + size[2]]; + let overlap = (0..3).all(|i| dest[i] <= max[i] && dmax[i] >= min[i]); + let moving = ctx.has("move"); + if !ctx.has("force") && overlap { + return Err(err("commands.clone.overlap", &[])); + } + let area = (0..3).map(|i| i64::from(size[i] + 1)).product::(); + let limit = self.ui.rules.int("max_block_modifications"); + if area > i64::from(limit) { + return Err(err("commands.clone.toobig", &[&limit, &area])); + } + for p in [dest, dmax] { + if !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { + return Err(err("argument.pos.unloaded", &[])); + } + } + let filter = match ctx.get("filter") { + Some(Arg::Block(f)) => Some(f.clone()), + _ => None, + }; + let air = self.world.air; + let masked = ctx.has("masked"); + let mut copies = Vec::new(); + for y in min[1]..=max[1] { + for z in min[2]..=max[2] { + for x in min[0]..=max[0] { + let s = self.world.block(x, y, z); + if masked && s == air { + continue; + } + if let Some(f) = &filter + && !self.block_matches(f, s) + { + continue; + } + copies.push(([x, y, z], [dest[0] + x - min[0], dest[1] + y - min[1], dest[2] + z - min[2]], s)); + } + } + } + if moving { + for (from, _, _) in &copies { + self.place_state(*from, air, true)?; + } + } + let strict = ctx.has("strict"); + let mut count = 0; + for (_, to, s) in copies { + if self.place_state(to, s, strict)? { + count += 1; + } + } + if count == 0 { + return Err(err("commands.clone.failed", &[])); + } + self.feedback(Text::tr("commands.clone.success", &[&count])); + Ok(count) + } + /// Player.giveExperiencePoints including negative amounts. + fn give_points(&mut self, amount: i32) { + let e = &mut self.experience; + e.progress += amount as f32 / horizon_client::entities::Experience::needed(e.level) as f32; + e.total = e.total.saturating_add(amount).clamp(0, i32::MAX); + while e.progress < 0.0 { + let f = e.progress * horizon_client::entities::Experience::needed(e.level) as f32; + if e.level > 0 { + e.level -= 1; + e.progress = 1.0 + f / horizon_client::entities::Experience::needed(e.level) as f32; + } else { + e.level = 0; + e.progress = 0.0; + } + } + while e.progress >= 1.0 { + e.progress = (e.progress - 1.0) * horizon_client::entities::Experience::needed(e.level) as f32; + e.level += 1; + e.progress /= horizon_client::entities::Experience::needed(e.level) as f32; + } + } + fn cmd_experience(&mut self, ctx: &Context) -> R { + let levels = ctx.has("levels"); + let unit = if levels { "levels" } else { "points" }; + if ctx.has("query") { + let _ = self.entities(ctx, "target", true)?; + let e = &self.experience; + let value = if levels { e.level } else { (e.progress * horizon_client::entities::Experience::needed(e.level) as f32) as i32 }; + self.system_message(Text::translate(&format!("commands.experience.query.{unit}"), &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())])); + return Ok(value); + } + let targets = self.entities(ctx, "target", true)?; + let amount = Self::int(ctx, "amount").unwrap_or(0); + let op = if ctx.has("add") { "add" } else { "set" }; + if op == "add" { + if levels { + self.experience.level = (self.experience.level + amount).max(0); + if self.experience.level == 0 && amount < 0 { + self.experience.progress = 0.0; + } + } else { + self.give_points(amount); + } + } else if levels { + self.experience.level = amount; + } else { + let needed = horizon_client::entities::Experience::needed(self.experience.level); + if amount > needed - 1 { + return Err(err("commands.experience.set.points.invalid", &[])); + } + self.experience.progress = amount as f32 / needed as f32; + } + let key = format!("commands.experience.{op}.{unit}.success.{}", if targets.len() == 1 { "single" } else { "multiple" }); + self.feedback(Text::translate(&key, &[Text::literal(amount.to_string()), Text::literal(PLAYER_NAME)])); + Ok(targets.len() as i32) + } + fn cmd_gamerule(&mut self, ctx: &Context) -> R { + let Some(name) = ctx.literals.get(1).cloned() else { return Ok(0) }; + let Some(rule) = gamerules::rule(&name) else { return Ok(0) }; + let current = self.ui.rules.get(rule.name).unwrap_or(rule.default); + let value = match ctx.get("value") { + Some(Arg::Bool(b)) => Value::Bool(*b), + Some(Arg::Int(i)) => Value::Int(*i), + _ => { + self.system_message(Text::tr("commands.gamerule.query", &[&rule.name, ¤t])); + return Ok(match current { + Value::Bool(b) => i32::from(b), + Value::Int(i) => i, + }); + } + }; + if current == value { + return Err(err("commands.gamerule.not_set", &[&rule.name, &value])); + } + self.ui.rules.set(rule.name, value); + self.sync_rules(); + self.feedback(Text::tr("commands.gamerule.set", &[&rule.name, &value])); + Ok(match value { + Value::Bool(b) => i32::from(b), + Value::Int(i) => i, + }) + } + fn cmd_difficulty(&mut self, ctx: &Context) -> R { + let name = |d: u8| Text::translate(&format!("options.difficulty.{}", DIFFICULTIES[d as usize]), &[]); + let Some(i) = DIFFICULTIES.iter().position(|d| ctx.has(d)) else { + let current = self.ui.difficulty; + self.system_message(Text::translate("commands.difficulty.query", &[name(current)])); + return Ok(i32::from(current)); + }; + let i = i as u8; + if self.ui.difficulty == i { + return Err(CommandError::new(Text::translate("commands.difficulty.failure", &[Text::literal(DIFFICULTIES[i as usize])]))); + } + self.ui.difficulty = i; + self.sync_rules(); + if i == 0 { + // Peaceful removes hostile mobs. + self.mobs.retain(|m| !m.hostile()); + } + self.feedback(Text::translate("commands.difficulty.success", &[name(i)])); + Ok(0) + } + fn cmd_spawnpoint(&mut self, ctx: &Context) -> R { + let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? } else { vec![Target::Player] }; + let pos = if ctx.get("pos").is_some() { + self.block_pos_arg(ctx, "pos")? + } else { + let p = self.source_position(); + [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + }; + let rot = match ctx.get("rotation") { + Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), + _ => [0.0, 0.0], + }; + let yaw = ((rot[0] + 180.0).rem_euclid(360.0)) - 180.0; + let pitch = rot[1].clamp(-90.0, 90.0); + self.spawn = Some(Vec3::new(f64::from(pos[0]) + 0.5, f64::from(pos[1]), f64::from(pos[2]) + 0.5)); + let dim = Text::literal(self.dim.id()); + let p = pos.map(|v| Text::literal(v.to_string())); + let mut args = vec![p[0].clone(), p[1].clone(), p[2].clone(), Text::literal(java_float(f64::from(yaw))), Text::literal(java_float(f64::from(pitch))), dim]; + let key = if targets.len() == 1 { + args.push(Text::literal(PLAYER_NAME)); + "commands.spawnpoint.success.single" + } else { + args.push(Text::literal(targets.len().to_string())); + "commands.spawnpoint.success.multiple" + }; + self.feedback(Text::translate(key, &args)); + Ok(targets.len() as i32) + } + fn cmd_setworldspawn(&mut self, ctx: &Context) -> R { + let pos = if ctx.get("pos").is_some() { + self.block_pos_arg(ctx, "pos")? + } else { + let p = self.source_position(); + [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32] + }; + if self.dim != Dim::Overworld { + return Err(err("commands.setworldspawn.failure.not_overworld", &[])); + } + let rot = match ctx.get("rotation") { + Some(Arg::Coords(c)) => c.rotation(self.source_rotation()), + _ => [0.0, 0.0], + }; + self.level.spawn = Some([f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]); + let args = [ + Text::literal(pos[0].to_string()), + Text::literal(pos[1].to_string()), + Text::literal(pos[2].to_string()), + Text::literal(java_float(f64::from(rot[0]))), + Text::literal(java_float(f64::from(rot[1]))), + Text::literal(self.dim.id()), + ]; + self.feedback(Text::translate("commands.setworldspawn.success", &args)); + Ok(1) + } + fn item_matches(&self, predicate: &ItemInput, item: &str) -> bool { + if predicate.any { + return true; + } + if predicate.tag { + let tag = predicate.id.trim_start_matches("minecraft:"); + return self.res.items.item_tags.get(tag).or_else(|| self.res.items.item_tags.get(&predicate.id)).is_some_and(|s| s.contains(item) || s.contains(item.trim_start_matches("minecraft:"))); + } + predicate.id == item + } + fn cmd_clear(&mut self, ctx: &Context) -> R { + let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", true)? } else { vec![Target::Player] }; + let predicate = match ctx.get("item") { + Some(Arg::Item(i)) => i.clone(), + _ => ItemInput { id: "*".into(), tag: false, any: true, components: None }, + }; + let max = Self::int(ctx, "maxCount").unwrap_or(-1); + let counting = max == 0; + // Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried. + let mut removed = 0i32; + let mut budget = if max < 0 { i32::MAX } else { max }; + let mut slots: Vec<&mut Option> = Vec::new(); + slots.extend(self.inventory.iter_mut()); + slots.extend(self.armor.iter_mut()); + slots.extend(self.craft_grid.iter_mut()); + slots.push(&mut self.carried); + for slot in slots { + let Some(stack) = slot.as_mut() else { continue }; + if !(predicate.any || predicate.tag || predicate.id == *stack.item) && !predicate.tag { + continue; + } + if predicate.tag { + continue; + } + let take = if counting { stack.count as i32 } else { (stack.count as i32).min(budget) }; + removed += take; + if !counting { + budget -= take; + stack.count -= take as u32; + if stack.count == 0 { + *slot = None; + } + if budget == 0 { + break; + } + } + } + if predicate.tag { + // Tag predicates: match against item tags. + let pred = predicate.clone(); + let mut budget = if max < 0 { i32::MAX } else { max }; + let items: Vec<(usize, String, u32)> = self.inventory.iter().enumerate().filter_map(|(i, s)| s.as_ref().map(|s| (i, s.item.to_string(), s.count))).collect(); + for (i, item, count) in items { + if !self.item_matches(&pred, &item) { + continue; + } + let take = if counting { count as i32 } else { (count as i32).min(budget) }; + removed += take; + if !counting && let Some(s) = self.inventory[i].as_mut() { + budget -= take; + s.count -= take as u32; + if s.count == 0 { + self.inventory[i] = None; + } + } + } + } + if removed == 0 { + return Err(if targets.len() == 1 { + CommandError::new(Text::translate("clear.failed.single", &[Text::literal(PLAYER_NAME)])) + } else { + err("clear.failed.multiple", &[&targets.len()]) + }); + } + let kind = if counting { "test" } else { "success" }; + self.feedback(Text::translate(&format!("commands.clear.{kind}.single"), &[Text::literal(removed.to_string()), Text::literal(PLAYER_NAME)])); + Ok(removed) + } + fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R { + let origin = self.source_position(); + if id == "locate.biome" { + let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0) }; + // Search loaded chunks around the player (BiomeSource.findClosestBiome3d + // samples a 6400-block radius; Horizon searches what is generated). + let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32); + let mut best: Option<([i32; 3], f64)> = None; + for (&(cx, cz), chunk) in &self.world.chunks { + for (dx, dz) in [(0, 0), (8, 8)] { + let (x, z) = (cx * 16 + dx, cz * 16 + dz); + let y = origin[1].floor() as i32; + let b = self.res.biomes.get(chunk.biome(x, y, z)); + if b.name == biome { + let d = f64::from((x - px).pow(2) + (z - pz).pow(2)); + if best.is_none_or(|(_, bd)| d < bd) { + best = Some(([x, y, z], d)); + } + } + } + } + let Some((p, d2)) = best else { + return Err(CommandError::new(Text::tr("commands.locate.biome.not_found", &[&biome]))); + }; + let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); + let link = Text::literal("[").append(coords).append("]").with_style(&Style { color: Some(text::GREEN), suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), ..Style::default() }); + let distance = d2.sqrt().floor() as i32; + self.system_message(Text::translate("commands.locate.biome.success", &[Text::literal(biome), link, Text::literal(distance.to_string())])); + return Ok(distance); + } + let Some(Arg::Resource(s)) = ctx.get("structure").cloned() else { return Ok(0) }; + Err(CommandError::new(Text::tr("commands.locate.structure.not_found", &[&s]))) + } + fn cmd_say(&mut self, id: &str, ctx: &Context) -> R { + let raw = match ctx.get(if id == "me" { "action" } else { "message" }) { + Some(Arg::Str(s)) => s.clone(), + _ => String::new(), + }; + let message = self.expand_selectors(&raw); + let line = match id { + "say" => Text::translate("chat.type.announcement", &[Text::literal(PLAYER_NAME), message]), + "me" => Text::translate("chat.type.emote", &[Text::literal(PLAYER_NAME), message]), + _ => { + let _ = self.entities(ctx, "targets", true)?; + // Whispering to yourself: the incoming and outgoing lines. + let out = Text::translate("commands.message.display.outgoing", &[Text::literal(PLAYER_NAME), message.clone()]).with_color(text::GRAY).italic(); + self.system_message(out); + Text::translate("commands.message.display.incoming", &[Text::literal(PLAYER_NAME), message]).with_color(text::GRAY).italic() + } + }; + let focused = self.screen == Screen::Chat; + self.ui.chat.add(&self.res.atlas, line, None, self.ticks, focused); + Ok(1) + } + /// MessageArgument: `@p`-style selectors in a message become names. + fn expand_selectors(&mut self, raw: &str) -> Text { + let mut out = Text::empty(); + let mut rest = raw; + while let Some(at) = rest.find('@') { + out.push(&rest[..at]); + let mut reader = Reader::new(&rest[at..]); + match (horizon_client::command::ArgType::Entity { single: false, players: false }).parse(&mut reader, &self.ui.registries) { + Ok(Arg::Entity(s)) if reader.cursor > 1 => { + let found = self.select(&s); + for (i, t) in found.iter().enumerate() { + if i > 0 { + out.push(", "); + } + out.push(self.target_name(*t)); + } + rest = &rest[at + reader.cursor..]; + } + _ => { + out.push("@"); + rest = &rest[at + 1..]; + } + } + } + out.push(rest); + out + } +} diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index f6b2bdcc6..e6e1441bd 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -23,6 +23,9 @@ const HELP: &[&str] = &[ "time TICKS set the time of day", "resume leave the pause menu", "screenshot PATH write the next frame as PNG", + "chat TEXT send a chat line or /command as if typed", + "type TEXT type into the open chat box (key enter tap sends)", + "chat-log [N] the newest N chat messages (default 10)", "stats [reset] frame-time summary since the last reset", "bench SECONDS reset stats, wait, then reply with the summary", "open WORLD [SEED] [creative] open or create a world from the title screen", @@ -211,6 +214,25 @@ impl Game<'_> { self.pending_screenshot = Some(reply.clone()); Ok(None) } + "chat" => { + self.require_world()?; + let text = line.trim_start().strip_prefix("chat").unwrap_or("").trim(); + self.handle_chat_input(text); + Ok(Some(json!({ "ok": true, "chat": self.ui.chat.recent_lines(5) }))) + } + "type" => { + self.require_world()?; + let text = line.trim_start().strip_prefix("type").unwrap_or("").strip_prefix(' ').unwrap_or(""); + if self.screen != Screen::Chat { + return Err("type needs the chat screen (key t tap)".into()); + } + self.chat_type(text); + ok() + } + "chat-log" => { + let n = words.get(1).map_or(Ok(10), |n| n.parse())?; + Ok(Some(json!({ "chat": self.ui.chat.recent_lines(n) }))) + } "stats" => { let summary = self.frame_stats.summary(); if words.get(1) == Some(&"reset") { @@ -264,6 +286,10 @@ impl Game<'_> { } fn control_key_down(&mut self, key: KeyCode) -> Result<()> { + if self.screen == Screen::Chat { + self.chat_key_code(key, None); + return Ok(()); + } if self.keys.insert(key) { self.key_pressed(key)?; } @@ -281,6 +307,7 @@ impl Game<'_> { Screen::Inventory => "inventory", Screen::Creative => "creative", Screen::Dead => "dead", + Screen::Chat => "chat", } } @@ -390,7 +417,15 @@ fn key_code(name: &str) -> Option { "esc" | "escape" => KeyCode::Escape, "tab" => KeyCode::Tab, "enter" | "return" => KeyCode::Enter, + "f1" => KeyCode::F1, + "f2" => KeyCode::F2, "f3" => KeyCode::F3, + "f5" => KeyCode::F5, + "f11" => KeyCode::F11, + "slash" | "/" => KeyCode::Slash, + "backspace" => KeyCode::Backspace, + "pageup" => KeyCode::PageUp, + "pagedown" => KeyCode::PageDown, "left" => KeyCode::ArrowLeft, "right" => KeyCode::ArrowRight, "up" => KeyCode::ArrowUp, diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs index 1174906ec..a8a86b523 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client/src/lang.rs @@ -4,7 +4,6 @@ //! language used by every screen. use std::{ collections::{BTreeMap, HashMap}, - path::Path, sync::{Arc, RwLock}, }; @@ -34,7 +33,7 @@ static CURRENT: RwLock>> = RwLock::new(None); pub trait ResourceSource { fn read(&self, path: &str) -> Option>; } -impl ResourceSource for Path { +impl ResourceSource for std::path::PathBuf { fn read(&self, path: &str) -> Option> { std::fs::read(self.join(path)).ok() } diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 93326510b..387d15e16 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -7,6 +7,7 @@ pub mod audio; pub mod biome; pub mod blocks; pub mod chunk; +pub mod chat; pub mod clock; pub mod command; pub mod containers; @@ -41,6 +42,7 @@ pub mod streaming; pub mod testgen; pub mod text; pub mod title; +pub mod ui; pub mod vanillagen; pub mod world; pub mod zip; diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs new file mode 100644 index 000000000..d253f2c5e --- /dev/null +++ b/crates/horizon-client/src/ui.rs @@ -0,0 +1,502 @@ +//! Shared GUI widgets drawn as HUD quads: nine-slice sprites (gui.scaling +//! metadata), buttons, sliders, tiled menu backgrounds, separators and the +//! EditBox text field with vanilla cursor, selection and scrolling. +use crate::{ + hud::{HudAtlas, HudBatch, Rect, rgba}, + text::Text, +}; +use std::{ + collections::HashMap, + path::Path, + sync::RwLock, + time::Instant, +}; + +/// Nine-slice borders (left, top, right, bottom) from `.png.mcmeta` files. +static NINE_SLICE: RwLock>> = RwLock::new(None); + +/// Read `gui.scaling` metadata for every GUI sprite under `root`. +pub fn load_metadata(root: &Path) { + let mut map = HashMap::new(); + let base = root.join("assets/minecraft/textures"); + let mut stack = vec![base.join("gui/sprites")]; + while let Some(dir) = stack.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { continue }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + continue; + } + let name = p.to_string_lossy().into_owned(); + let Some(stripped) = name.strip_suffix(".png.mcmeta") else { continue }; + let Ok(text) = std::fs::read_to_string(&p) else { continue }; + let Ok(v) = serde_json::from_str::(&text) else { continue }; + let s = &v["gui"]["scaling"]; + if s["type"] != "nine_slice" { + continue; + } + let border = &s["border"]; + let b = if let Some(n) = border.as_u64() { + [n as u32; 4] + } else { + let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; + [g("left"), g("top"), g("right"), g("bottom")] + }; + let key = Path::new(stripped).strip_prefix(&base).map(|r| r.to_string_lossy().replace('\\', "/")).unwrap_or_default(); + map.insert(key, b); + } + } + *NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map); +} +fn border(sprite: &str) -> [u32; 4] { + NINE_SLICE.read().unwrap_or_else(|e| e.into_inner()).as_ref().and_then(|m| m.get(sprite).copied()).unwrap_or(match sprite { + "gui/sprites/widget/button" | "gui/sprites/widget/button_highlighted" | "gui/sprites/widget/button_disabled" => [3; 4], + "gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3], + _ => [1; 4], + }) +} +fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); + Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, u1: r.u0 + (x + w) * du, v1: r.v0 + (y + h) * dv, w: w as u32, h: h as u32 } +} +/// Tile `src` (a sub-rectangle of a sprite, in its pixels) over a target area. +fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) { + let [sx, sy, sw, sh] = src; + let [dx, dy, dw, dh] = dst; + if sw <= 0.0 || sh <= 0.0 || dw <= 0.0 || dh <= 0.0 { + return; + } + let mut y = 0.0; + while y < dh { + let h = sh.min(dh - y); + let mut x = 0.0; + while x < dw { + let w = sw.min(dw - x); + batch.rect_uv(dx + x, dy + y, w, h, sub(r, sx, sy, w, h), color); + x += sw; + } + y += sh; + } +} +/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled). +pub fn nine_slice(batch: &mut HudBatch, atlas: &HudAtlas, sprite: &str, x: f32, y: f32, w: f32, h: f32, color: u32) { + let Some(r) = atlas.sprites.get(sprite).copied() else { return }; + let [l, t, rr, b] = border(sprite).map(|v| v as f32); + let (sw, sh) = (r.w as f32, r.h as f32); + let l = l.min(w / 2.0); + let rr = rr.min(w / 2.0); + let t = t.min(h / 2.0); + let b = b.min(h / 2.0); + let (cw, ch) = (w - l - rr, h - t - b); + let (scw, sch) = (sw - l - rr, sh - t - b); + // Corners. + batch.rect_uv(x, y, l, t, sub(r, 0.0, 0.0, l, t), color); + batch.rect_uv(x + w - rr, y, rr, t, sub(r, sw - rr, 0.0, rr, t), color); + batch.rect_uv(x, y + h - b, l, b, sub(r, 0.0, sh - b, l, b), color); + batch.rect_uv(x + w - rr, y + h - b, rr, b, sub(r, sw - rr, sh - b, rr, b), color); + // Edges and centre. + tile(batch, r, [l, 0.0, scw, t], [x + l, y, cw, t], color); + tile(batch, r, [l, sh - b, scw, b], [x + l, y + h - b, cw, b], color); + tile(batch, r, [0.0, t, l, sch], [x, y + t, l, ch], color); + tile(batch, r, [sw - rr, t, rr, sch], [x + w - rr, y + t, rr, ch], color); + tile(batch, r, [l, t, scw, sch], [x + l, y + t, cw, ch], color); +} +/// Repeat a whole texture with each copy drawn `size` GUI pixels square. +pub fn tiled(batch: &mut HudBatch, atlas: &HudAtlas, sprite: &str, x: f32, y: f32, w: f32, h: f32, size: f32, color: u32) { + let Some(r) = atlas.sprites.get(sprite).copied() else { return }; + let scale = r.w as f32 / size; + let mut yy = 0.0; + while yy < h { + let th = size.min(h - yy); + let mut xx = 0.0; + while xx < w { + let tw = size.min(w - xx); + batch.rect_uv(x + xx, y + yy, tw, th, sub(r, 0.0, 0.0, tw * scale, th * scale), color); + xx += size; + } + yy += size; + } +} +pub fn hovered(cursor: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { + cursor.0 >= x && cursor.0 < x + w && cursor.1 >= y && cursor.1 < y + h +} +/// Centered text with a shadow, scrolled when wider than `w` (AbstractWidget.renderScrollingString). +pub fn centered_text(batch: &mut HudBatch, atlas: &HudAtlas, text: &Text, x: f32, y: f32, w: f32, color: u32) { + let width = atlas.font.width_text(text); + if width <= w { + batch.text_styled(atlas, text, x + ((w - width) / 2.0).floor(), y, color, true); + } else { + // Clip by characters (vanilla scrolls; we show the part that fits). + let mut shown = Text::empty(); + let mut used = 0.0; + for (i, (c, s)) in text.chars().enumerate() { + used += atlas.font.advance(c, s); + if used > w - 2.0 { + break; + } + shown.push(text.slice(i, i + 1)); + } + batch.text_styled(atlas, &shown, x + 1.0, y, color, true); + } +} +/// Button (AbstractButton): nine-slice sprite plus the centred label. +pub fn button(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, label: &Text, active: bool, hover: bool) { + let sprite = if !active { + "gui/sprites/widget/button_disabled" + } else if hover { + "gui/sprites/widget/button_highlighted" + } else { + "gui/sprites/widget/button" + }; + nine_slice(batch, atlas, sprite, x, y, w, h, u32::MAX); + let color = if active { rgba(255, 255, 255, 255) } else { rgba(160, 160, 160, 255) }; + centered_text(batch, atlas, label, x + 2.0, y + ((h - 8.0) / 2.0).floor(), w - 4.0, color); +} +/// AbstractSliderButton: track, 8px handle at `value` (0..1) and the label. +pub fn slider(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, label: &Text, value: f32, hover: bool, active: bool) { + let track = if hover && active { "gui/sprites/widget/slider_highlighted" } else { "gui/sprites/widget/slider" }; + nine_slice(batch, atlas, track, x, y, w, 20.0, u32::MAX); + let handle = if hover && active { "gui/sprites/widget/slider_handle_highlighted" } else { "gui/sprites/widget/slider_handle" }; + nine_slice(batch, atlas, handle, x + (value.clamp(0.0, 1.0) * (w - 8.0)).floor(), y, 8.0, 20.0, u32::MAX); + let color = if active { u32::MAX } else { rgba(160, 160, 160, 255) }; + centered_text(batch, atlas, label, x + 2.0, y + 6.0, w - 4.0, color); +} +/// Slider value for a click at `cx` (AbstractSliderButton.setValueFromMouse). +pub fn slider_value(x: f32, w: f32, cx: f32) -> f32 { + ((cx - (x + 4.0)) / (w - 8.0)).clamp(0.0, 1.0) +} +/// Screen.renderMenuBackground: in a world the translucent dark texture, +/// otherwise the dirt-like menu texture, tiled at 32 pixels. +pub fn menu_background(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, y: f32, w: f32, h: f32, in_world: bool) { + let sprite = if in_world { "gui/inworld_menu_background" } else { "gui/menu_background" }; + if atlas.sprites.contains_key(sprite) { + tiled(batch, atlas, sprite, x, y, w, h, 32.0, u32::MAX); + } else { + batch.fill(atlas, x, y, w, h, rgba(0, 0, 0, 160)); + } +} +/// Header and footer separators of list screens. +pub fn separators(batch: &mut HudBatch, atlas: &HudAtlas, header_bottom: f32, footer_top: f32, in_world: bool) { + let (header, footer) = if in_world { + ("gui/inworld_header_separator", "gui/inworld_footer_separator") + } else { + ("gui/header_separator", "gui/footer_separator") + }; + let w = batch.width; + tiled(batch, atlas, header, 0.0, header_bottom - 2.0, w, 2.0, 32.0, u32::MAX); + tiled(batch, atlas, footer, 0.0, footer_top, w, 2.0, 32.0, u32::MAX); +} +/// List background between the separators. +pub fn list_background(batch: &mut HudBatch, atlas: &HudAtlas, top: f32, bottom: f32, in_world: bool) { + let sprite = if in_world { "gui/inworld_menu_list_background" } else { "gui/menu_list_background" }; + tiled(batch, atlas, sprite, 0.0, top, batch.width, bottom - top, 32.0, u32::MAX); +} +/// Vertical scroll bar (AbstractScrollArea): background and scroller sprites. +pub fn scrollbar(batch: &mut HudBatch, atlas: &HudAtlas, x: f32, top: f32, bottom: f32, content: f32, scroll: f32) { + let height = bottom - top; + if content <= height { + return; + } + let bar = (height * height / content).clamp(32.0, height - 8.0).floor(); + let max = content - height; + let y = top + ((scroll / max) * (height - bar)).floor(); + nine_slice(batch, atlas, "gui/sprites/widget/scroller_background", x, top, 6.0, height, u32::MAX); + nine_slice(batch, atlas, "gui/sprites/widget/scroller", x, y, 6.0, bar, u32::MAX); +} + +/// Screen tooltip (DefaultTooltipPositioner + TooltipRenderUtil): the +/// background and frame sprites around the lines, beside the cursor. +pub fn tooltip(batch: &mut HudBatch, atlas: &HudAtlas, lines: &[Text], cursor: (f32, f32)) { + if lines.is_empty() { + return; + } + let w = lines.iter().map(|l| atlas.font.width_text(l)).fold(0.0, f32::max); + let h = if lines.len() == 1 { 8.0 } else { 10.0 * lines.len() as f32 }; + let mut x = cursor.0 + 12.0; + let mut y = cursor.1 - 12.0; + if x + w > batch.width { + x = (cursor.0 - 24.0 - w).max(4.0); + } + if y + h + 3.0 > batch.height { + y = batch.height - h - 3.0; + } + y = y.max(4.0); + nine_slice(batch, atlas, "gui/sprites/tooltip/background", x - 12.0, y - 12.0, w + 24.0, h + 24.0, u32::MAX); + nine_slice(batch, atlas, "gui/sprites/tooltip/frame", x - 12.0, y - 12.0, w + 24.0, h + 24.0, u32::MAX); + let mut ly = y; + for (i, line) in lines.iter().enumerate() { + batch.text_styled(atlas, line, x, ly, u32::MAX, true); + ly += if i == 0 { 12.0 } else { 10.0 }; + } +} + +/// The EditBox text field. +#[derive(Clone, Debug)] +pub struct EditBox { + pub value: String, + /// Cursor and selection anchor, in characters. + pub cursor: usize, + pub highlight: usize, + display: usize, + pub max_length: usize, + pub bordered: bool, + pub x: f32, + pub y: f32, + pub width: f32, + pub height: f32, + pub focused: bool, + focused_at: Instant, + /// Grey completion shown after the text (EditBox.setSuggestion). + pub suggestion: Option, + pub text_color: u32, +} +fn byte_index(s: &str, chars: usize) -> usize { + s.char_indices().nth(chars).map_or(s.len(), |(i, _)| i) +} +pub fn char_len(s: &str) -> usize { + s.chars().count() +} +impl EditBox { + pub fn new(x: f32, y: f32, width: f32, height: f32) -> Self { + Self { + value: String::new(), + cursor: 0, + highlight: 0, + display: 0, + max_length: 32, + bordered: true, + x, + y, + width, + height, + focused: true, + focused_at: Instant::now(), + suggestion: None, + text_color: rgba(224, 224, 224, 255), + } + } + pub fn inner_width(&self) -> f32 { + if self.bordered { self.width - 8.0 } else { self.width } + } + pub fn text_x(&self) -> f32 { + if self.bordered { self.x + 4.0 } else { self.x } + } + pub fn text_y(&self) -> f32 { + if self.bordered { self.y + ((self.height - 8.0) / 2.0).floor() } else { self.y } + } + pub fn reset_blink(&mut self) { + self.focused_at = Instant::now(); + } + pub fn set_value(&mut self, value: &str) { + self.value = value.chars().take(self.max_length).collect(); + self.move_cursor_to_end(false); + } + fn selected(&self) -> (usize, usize) { + (self.cursor.min(self.highlight), self.cursor.max(self.highlight)) + } + pub fn selected_text(&self) -> String { + let (a, b) = self.selected(); + self.value.chars().skip(a).take(b - a).collect() + } + /// EditBox.insertText: replace the selection, respecting the maximum length. + pub fn insert_text(&mut self, text: &str) { + let (a, b) = self.selected(); + let filtered: String = text.chars().filter(|c| !c.is_control() && *c != '§').collect(); + let room = self.max_length.saturating_sub(char_len(&self.value) - (b - a)); + let insert: String = filtered.chars().take(room).collect(); + let (ba, bb) = (byte_index(&self.value, a), byte_index(&self.value, b)); + self.value.replace_range(ba..bb, &insert); + let pos = a + char_len(&insert); + self.set_cursor(pos, false); + } + /// Delete `n` characters (negative: backwards) or the selection. + pub fn delete_chars(&mut self, n: isize) { + if self.cursor != self.highlight { + self.insert_text(""); + return; + } + let target = (self.cursor as isize + n).clamp(0, char_len(&self.value) as isize) as usize; + let (a, b) = (self.cursor.min(target), self.cursor.max(target)); + let (ba, bb) = (byte_index(&self.value, a), byte_index(&self.value, b)); + self.value.replace_range(ba..bb, ""); + self.set_cursor(a, false); + } + /// EditBox.getWordPosition. + pub fn word_position(&self, dir: isize) -> usize { + let chars: Vec = self.value.chars().collect(); + let mut pos = self.cursor; + if dir < 0 { + while pos > 0 && chars[pos - 1] == ' ' { + pos -= 1; + } + while pos > 0 && chars[pos - 1] != ' ' { + pos -= 1; + } + } else { + let len = chars.len(); + while pos < len && chars[pos] != ' ' { + pos += 1; + } + while pos < len && chars[pos] == ' ' { + pos += 1; + } + } + pos + } + pub fn set_cursor(&mut self, pos: usize, select: bool) { + self.cursor = pos.min(char_len(&self.value)); + if !select { + self.highlight = self.cursor; + } + self.scroll_to(self.cursor); + self.reset_blink(); + } + pub fn move_cursor_to_end(&mut self, select: bool) { + self.set_cursor(char_len(&self.value), select); + } + fn scroll_to(&mut self, pos: usize) { + // EditBox.scrollTo without font access is completed in `layout`. + self.display = self.display.min(char_len(&self.value)); + if pos < self.display { + self.display = pos; + } + } + fn layout(&mut self, atlas: &HudAtlas) { + let len = char_len(&self.value); + self.display = self.display.min(len); + let (value, inner) = (self.value.clone(), self.inner_width()); + let visible = |d: usize| -> usize { + let rest: String = value.chars().skip(d).collect(); + atlas.font.fit(&rest, inner) + }; + while self.cursor > self.display + visible(self.display) && self.display < len { + self.display += 1; + } + if self.cursor < self.display { + self.display = self.cursor; + } + } + /// Keyboard editing shared by every text field. Returns true if handled. + pub fn key(&mut self, key: winit::keyboard::KeyCode, ctrl: bool, shift: bool) -> bool { + use winit::keyboard::KeyCode as K; + match key { + K::Backspace => { + let n = if ctrl { self.word_position(-1) as isize - self.cursor as isize } else { -1 }; + self.delete_chars(n); + } + K::Delete => { + let n = if ctrl { self.word_position(1) as isize - self.cursor as isize } else { 1 }; + self.delete_chars(n); + } + K::ArrowLeft => { + let p = if ctrl { self.word_position(-1) } else { self.cursor.saturating_sub(1) }; + self.set_cursor(p, shift); + } + K::ArrowRight => { + let p = if ctrl { self.word_position(1) } else { self.cursor + 1 }; + self.set_cursor(p, shift); + } + K::Home => self.set_cursor(0, shift), + K::End => self.move_cursor_to_end(shift), + K::KeyA if ctrl => { + self.move_cursor_to_end(false); + self.highlight = 0; + } + _ => return false, + } + true + } + /// Draw the field; `format` styles the visible text (command colouring). + pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, format: Option<&Text>) { + self.layout(atlas); + if self.bordered { + let sprite = if self.focused { "gui/sprites/widget/text_field_highlighted" } else { "gui/sprites/widget/text_field" }; + nine_slice(batch, atlas, sprite, self.x, self.y, self.width, self.height, u32::MAX); + } + let color = self.text_color; + let rest: String = self.value.chars().skip(self.display).collect(); + let shown_len = atlas.font.fit(&rest, self.inner_width()); + let displayed: String = rest.chars().take(shown_len).collect(); + let rel_cursor = self.cursor as isize - self.display as isize; + let on_screen = rel_cursor >= 0 && rel_cursor as usize <= shown_len; + let show_cursor = self.focused && (self.focused_at.elapsed().as_millis() / 300) % 2 == 0 && on_screen; + let styled = |from: usize, to: usize| -> Text { + match format { + Some(t) => t.slice(self.display + from, self.display + to), + None => Text::literal(displayed.chars().skip(from).take(to - from).collect::()), + } + }; + let (tx, ty) = (self.text_x(), self.text_y()); + let mut draw_x = tx; + if !displayed.is_empty() { + let half = if on_screen { rel_cursor as usize } else { shown_len }; + let t = styled(0, half); + batch.text_styled(atlas, &t, draw_x, ty, color, true); + draw_x += atlas.font.width_text(&t) + 1.0; + } + let insert = self.cursor < char_len(&self.value) || char_len(&self.value) >= self.max_length; + let mut cursor_x = draw_x; + if !on_screen { + cursor_x = if rel_cursor > 0 { tx + self.width } else { tx }; + } else if insert { + cursor_x -= 1.0; + draw_x -= 1.0; + } + if !displayed.is_empty() && on_screen && (rel_cursor as usize) < shown_len { + batch.text_styled(atlas, &styled(rel_cursor as usize, shown_len), draw_x, ty, color, true); + } + if !insert && let Some(s) = &self.suggestion { + batch.text(atlas, s, cursor_x - 1.0, ty, rgba(128, 128, 128, 255), true); + } + let rel_highlight = (self.highlight as isize - self.display as isize).clamp(0, shown_len as isize) as usize; + if rel_highlight as isize != rel_cursor { + let hx = tx + atlas.font.width(&displayed.chars().take(rel_highlight).collect::()); + let (a, b) = (cursor_x.min(hx - 1.0), cursor_x.max(hx - 1.0)); + batch.fill(atlas, a, ty - 1.0, b - a, 11.0, rgba(0, 0, 255, 128)); + } + if show_cursor { + if insert { + batch.fill(atlas, cursor_x, ty - 1.0, 1.0, 11.0, color); + } else { + batch.text(atlas, "_", cursor_x, ty, color, true); + } + } + } + /// Character index under GUI x (mouse click). + pub fn index_at(&self, atlas: &HudAtlas, x: f32) -> usize { + let rest: String = self.value.chars().skip(self.display).collect(); + self.display + atlas.font.fit(&rest, (x - self.text_x()).max(0.0)) + } + /// GUI x of a character index (EditBox.getScreenX). + pub fn screen_x(&self, atlas: &HudAtlas, index: usize) -> f32 { + if index > char_len(&self.value) { + return self.x; + } + let shown: String = self.value.chars().skip(self.display).take(index.saturating_sub(self.display)).collect(); + self.text_x() + atlas.font.width(&shown) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn edit_box_editing() { + let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0); + e.max_length = 10; + e.insert_text("hello world"); + assert_eq!(e.value, "hello worl"); + e.set_cursor(5, false); + assert_eq!(e.word_position(-1), 0); + assert_eq!(e.word_position(1), 6); + e.delete_chars(-2); + assert_eq!(e.value, "hel worl"); + e.set_cursor(0, false); + e.set_cursor(3, true); + assert_eq!(e.selected_text(), "hel"); + e.insert_text("é§x"); + assert_eq!(e.value, "éx worl"); + assert_eq!(e.cursor, 2); + } +} From f573c7708280ea1842310d76bf8288365f5d88a9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 15:51:44 +0200 Subject: [PATCH 3/4] Add vanilla options screens, key binds, languages and resource packs Options, Video Settings, Music & Sounds, Controls, Key Binds, Mouse, Chat, Accessibility, Language (with search) and Resource Packs screens in the HeaderAndFooter/OptionsList layouts. options.txt uses vanilla keys and encodings (unknown lines kept), including key_:key.keyboard.x binds that the input path honours, per-source volumes, brightness, VSync, max framerate, fullscreen (F11), chat and font options. Languages reload live; resource packs (folders, zips, Programmer Art, High Contrast) are layered over the vanilla resources through an overlay root. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/audio.rs | 2 +- crates/horizon-client/src/game.rs | 87 +- crates/horizon-client/src/game/chat.rs | 4 + crates/horizon-client/src/game/control.rs | 55 +- crates/horizon-client/src/game/options.rs | 160 +++ crates/horizon-client/src/game/packs.rs | 97 ++ crates/horizon-client/src/gfx.rs | 23 +- crates/horizon-client/src/hud.rs | 2 +- crates/horizon-client/src/keybinds.rs | 344 +++++++ crates/horizon-client/src/lib.rs | 3 + crates/horizon-client/src/options_ui.rs | 1123 +++++++++++++++++++++ crates/horizon-client/src/packs.rs | 284 ++++++ crates/horizon-client/src/settings.rs | 470 +++++++-- 13 files changed, 2527 insertions(+), 127 deletions(-) create mode 100644 crates/horizon-client/src/game/options.rs create mode 100644 crates/horizon-client/src/game/packs.rs create mode 100644 crates/horizon-client/src/keybinds.rs create mode 100644 crates/horizon-client/src/options_ui.rs create mode 100644 crates/horizon-client/src/packs.rs diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index e332e863b..b790ffc05 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -212,7 +212,7 @@ impl Audio { decode(&self.root.join(format!("assets/minecraft/sounds/{file}.ogg"))).map(|(s, r)| (Arc::new(s), r)) }); let Some((samples, rate)) = entry.clone() else { return }; - let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master; + let volume = (volume * variant.volume).clamp(0.0, 1.0) * self.master * crate::settings::event_volume(event); let pitch = (pitch * variant.pitch).clamp(0.5, 2.0); let (mut left, mut right) = (volume, volume); if let Some(p) = at { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 28ce636f9..17a307a80 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3,6 +3,8 @@ mod chat; mod commands; mod control; +mod options; +mod packs; use horizon_client::{ Result, assets::Assets, @@ -1570,7 +1572,7 @@ impl Game<'_> { let mut batch = HudBatch::new(size); let (w, h) = (batch.width, batch.height); if self.screen == Screen::Options { - self.settings.draw(&self.res.atlas, &mut batch, self.cursor); + self.draw_options(&mut batch); return batch; } if let Some(title) = &self.title { @@ -3756,6 +3758,7 @@ impl Game<'_> { self.streaming.radius = self.settings.render_distance; self.audio.master = self.settings.master_volume; horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, std::sync::atomic::Ordering::Relaxed); + self.apply_ui_settings(); } /// Whether precipitation at a column is snow (Biome.coldEnoughToSnow: /// base temperature lowered above y 80) or none (no precipitation). @@ -4231,10 +4234,7 @@ impl Game<'_> { fn key_pressed(&mut self, key: KeyCode) -> Result<()> { match key { KeyCode::Escape => match self.screen { - Screen::Options => { - self.settings.save(&std::env::current_dir()?.join("options.txt")); - self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; - } + Screen::Options => self.options_key(KeyCode::Escape, None)?, Screen::Playing => { self.screen = Screen::Paused; self.capture(false); @@ -4255,6 +4255,7 @@ impl Game<'_> { KeyCode::KeyT if self.screen == Screen::Playing => self.open_chat(""), KeyCode::Slash if self.screen == Screen::Playing => self.open_chat("/"), KeyCode::F1 => self.toggle_hide_gui(), + KeyCode::F11 => self.toggle_fullscreen(), KeyCode::F2 => self.take_screenshot(), KeyCode::KeyE if self.screen == Screen::Creative && self.creative_screen.tab().search => {} KeyCode::KeyE => match self.screen { @@ -4431,8 +4432,8 @@ impl ApplicationHandler for Game<'_> { let b = HudBatch::new([r.config.width, r.config.height]); self.cursor = (position.x as f32 / b.scale, position.y as f32 / b.scale); if self.dragging && self.screen == Screen::Options { - self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), true); - self.apply_settings(); + let _ = b; + self.options_drag()?; } } } @@ -4444,6 +4445,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Chat && d != 0.0 { self.chat_scroll(d); } + if self.screen == Screen::Options && d != 0.0 { + self.options_scroll(d); + } if self.screen == Screen::Creative && d != 0.0 { let rows = self.creative_screen.rows(&self.res.names).saturating_sub(5).max(1) as f32; self.creative_screen.scroll = (self.creative_screen.scroll - d.signum() / rows).clamp(0.0, 1.0); @@ -4452,17 +4456,11 @@ impl ApplicationHandler for Game<'_> { self.selected = (self.selected as i32 - d.signum() as i32).rem_euclid(9) as usize; } } - WindowEvent::MouseInput { state, button: MouseButton::Left, .. } if self.screen == Screen::Options => { - self.dragging = state == ElementState::Pressed; - if self.dragging { - let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); - let b = HudBatch::new(size); - if self.settings.click(self.cursor.0, self.cursor.1, (b.width, b.height), false) { - self.settings.save(&std::env::current_dir()?.join("options.txt")); - self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; - self.dragging = false; - } - self.apply_settings(); + WindowEvent::MouseInput { state, button, .. } if self.screen == Screen::Options => { + if self.options_waiting_for_key() && state == ElementState::Pressed { + self.options_bind_mouse(button)?; + } else if matches!(button, MouseButton::Left | MouseButton::Right) { + self.options_mouse(state == ElementState::Pressed, button == MouseButton::Right)?; } } WindowEvent::MouseInput { state, button: MouseButton::Left, .. } @@ -4473,10 +4471,7 @@ impl ApplicationHandler for Game<'_> { let action = self.title.as_mut().map_or(Action::None, |t| t.click(self.cursor.0, self.cursor.1, (b.width, b.height))); match action { Action::Quit => event_loop.exit(), - Action::Options => { - self.screen = Screen::Options; - self.options_from_title = true; - } + Action::Options => self.open_options(true), Action::Play { folder } => self.open_world(&folder, None, None, false)?, Action::Create { folder, name, seed, creative } => self.open_world(&folder, Some(&name), seed, creative)?, Action::None => {} @@ -4491,7 +4486,17 @@ impl ApplicationHandler for Game<'_> { self.capture(true); return Ok(()); } - self.play_mouse(button, pressed)?; + match self.settings.keys.translate_mouse(button) { + Some(Err(b)) => self.play_mouse(b, pressed)?, + Some(Ok(k)) if pressed => { + self.keys.insert(k); + self.key_pressed(k)?; + } + Some(Ok(k)) => { + self.keys.remove(&k); + } + None => {} + } } Screen::Inventory if pressed => { self.click_inventory(button == MouseButton::Right); @@ -4510,8 +4515,7 @@ impl ApplicationHandler for Game<'_> { self.screen = Screen::Playing; self.capture(true); } else if i == 1 { - self.screen = Screen::Options; - self.options_from_title = false; + self.open_options(false); } else { self.close_world()?; } @@ -4553,6 +4557,13 @@ impl ApplicationHandler for Game<'_> { } self.creative_screen.scroll = 0.0; } + WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::Options => { + if event.state == ElementState::Pressed + && let PhysicalKey::Code(key) = event.physical_key + { + self.options_key(key, event.text.as_deref())?; + } + } WindowEvent::KeyboardInput { event, .. } if self.title.is_some() => { if event.state == ElementState::Pressed && let Some(title) = self.title.as_mut() @@ -4571,6 +4582,17 @@ impl ApplicationHandler for Game<'_> { } WindowEvent::KeyboardInput { event, .. } => { let PhysicalKey::Code(key) = event.physical_key else { return Ok(()) }; + // Key binds: act as the default key of the bound mapping. + let key = match self.settings.keys.translate(key) { + Some(Ok(k)) => k, + Some(Err(button)) => { + if self.screen == Screen::Playing && !event.repeat { + self.play_mouse(button, event.state == ElementState::Pressed)?; + } + return Ok(()); + } + None => return Ok(()), + }; if event.state != ElementState::Pressed { self.keys.remove(&key); return Ok(()); @@ -4658,6 +4680,10 @@ impl ApplicationHandler for Game<'_> { event_loop.exit(); return; } + if let Some(due) = self.next_frame_due() { + event_loop.set_control_flow(ControlFlow::WaitUntil(due)); + return; + } if let Some(w) = &self.window { w.request_redraw(); } @@ -4665,8 +4691,11 @@ impl ApplicationHandler for Game<'_> { } } pub fn run() -> Result<()> { - let Some(options) = Options::read()? else { return Ok(()) }; + let Some(mut options) = Options::read()? else { return Ok(()) }; let started = Instant::now(); + let vanilla_root = options.resources.clone(); + let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); + options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); let root = options.resources.clone(); let assets = Arc::new(Assets::load(&root).map_err(|e| { format!("{e}\nPrepare resources with: python3 tools/prepare_native_client.py --prepare") @@ -4687,7 +4716,7 @@ pub fn run() -> Result<()> { eprintln!("load tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; horizon_client::ui::load_metadata(&root); - horizon_client::lang::set(horizon_client::lang::Language::load(&[&root], horizon_client::lang::DEFAULT)); + horizon_client::lang::set(horizon_client::lang::Language::load(&[&root], &early_settings.language)); eprintln!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); let layer_names = assets .sprite_layers @@ -4850,6 +4879,10 @@ pub fn run() -> Result<()> { pending_bench: None, ui: Default::default(), }; + game.ui.vanilla_root = vanilla_root; + game.res.atlas.font.uniform = game.settings.force_unicode; + game.res.atlas.font.japanese = game.settings.japanese_glyphs; + game.ui.chat.options = game.settings.chat_options(); if let Some(path) = &game.options.control { let server = horizon_client::control::Server::start(path) .map_err(|e| format!("control socket {}: {e}", path.display()))?; diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 5b7d5db69..28dde48b0 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -70,6 +70,10 @@ pub struct UiState { pub death_cause: Option, /// File name of an F2 screenshot waiting for its frame. pub screenshot_message: Option, + /// The options screens. + pub options: horizon_client::options_ui::OptionsUi, + /// The prepared resources before resource packs are layered on. + pub vanilla_root: std::path::PathBuf, } impl Game<'_> { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index e6e1441bd..b620cef1d 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -26,6 +26,7 @@ const HELP: &[&str] = &[ "chat TEXT send a chat line or /command as if typed", "type TEXT type into the open chat box (key enter tap sends)", "chat-log [N] the newest N chat messages (default 10)", + "options [PAGE] open the options (video sound controls keybinds mouse chat accessibility language font packs)", "stats [reset] frame-time summary since the last reset", "bench SECONDS reset stats, wait, then reply with the summary", "open WORLD [SEED] [creative] open or create a world from the title screen", @@ -73,6 +74,27 @@ impl Game<'_> { "key" => { let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?; self.require_world()?; + // Physical key presses follow the key binds like the keyboard does. + let key = if matches!(self.screen, Screen::Chat | Screen::Options) { + key + } else { + match self.settings.keys.translate(key) { + Some(Ok(k)) => k, + Some(Err(button)) => { + let action = arg(2)?; + if self.screen == Screen::Playing { + if action != "up" { + self.play_mouse(button, true)?; + } + if action != "down" { + self.play_mouse(button, false)?; + } + } + return ok(); + } + None => return ok(), + } + }; match arg(2)? { "down" => self.control_key_down(key)?, "up" => { @@ -223,10 +245,34 @@ impl Game<'_> { "type" => { self.require_world()?; let text = line.trim_start().strip_prefix("type").unwrap_or("").strip_prefix(' ').unwrap_or(""); - if self.screen != Screen::Chat { - return Err("type needs the chat screen (key t tap)".into()); + match self.screen { + Screen::Chat => self.chat_type(text), + Screen::Options => self.ui.options.type_text(text), + _ => return Err("type needs the chat screen (key t tap) or the language search".into()), } - self.chat_type(text); + ok() + } + "options" => { + use horizon_client::options_ui::Page; + let page = match words.get(1).copied().unwrap_or("main") { + "main" => Page::Main, + "video" => Page::Video, + "sound" => Page::Sound, + "controls" => Page::Controls, + "keybinds" => Page::KeyBinds, + "mouse" => Page::Mouse, + "chat" => Page::Chat, + "accessibility" => Page::Accessibility, + "language" => Page::Language, + "font" => Page::Font, + "packs" => Page::Packs, + other => return Err(format!("unknown options page {other}").into()), + }; + if self.screen == Screen::Playing && self.title.is_none() { + self.capture(false); + } + self.open_options(self.title.is_some()); + self.ui.options.show(page); ok() } "chat-log" => { @@ -290,6 +336,9 @@ impl Game<'_> { self.chat_key_code(key, None); return Ok(()); } + if self.screen == Screen::Options { + return self.options_key(key, None); + } if self.keys.insert(key) { self.key_pressed(key)?; } diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs new file mode 100644 index 000000000..e1c886bb0 --- /dev/null +++ b/crates/horizon-client/src/game/options.rs @@ -0,0 +1,160 @@ +//! The options screens bound to the game: drawing, input, applying settings +//! (video, sound, chat, font, language) and the F11 fullscreen toggle. +use super::{Game, Screen}; +use horizon_client::{ + Result, + hud::HudBatch, + lang, + options_ui::{Event, Page}, +}; +use winit::{event::MouseButton, keyboard::KeyCode, window::Fullscreen}; + +impl Game<'_> { + fn options_path() -> std::path::PathBuf { + std::env::current_dir().unwrap_or_default().join("options.txt") + } + fn gui_size(&self) -> (f32, f32) { + let size = self.renderer.as_ref().map_or([1280, 720], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + (b.width, b.height) + } + /// Open the options screens (OptionsScreen) from the title or pause menu. + pub(super) fn open_options(&mut self, from_title: bool) { + self.screen = Screen::Options; + self.options_from_title = from_title; + let ui = &mut self.ui.options; + ui.open(!from_title && self.title.is_none()); + let root = self.options.resources.clone(); + ui.languages = lang::available(&[&root]); + self.refresh_pack_lists(); + } + pub(super) fn draw_options(&mut self, batch: &mut HudBatch) { + let mut ui = std::mem::take(&mut self.ui.options); + ui.draw(&self.settings, batch, &self.res.atlas, self.cursor); + self.ui.options = ui; + } + pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { + if !pressed { + self.ui.options.release(); + self.dragging = false; + return Ok(()); + } + self.dragging = true; + let size = self.gui_size(); + let mut ui = std::mem::take(&mut self.ui.options); + let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, false, right); + self.ui.options = ui; + self.handle_option_events(events) + } + pub(super) fn options_drag(&mut self) -> Result<()> { + let size = self.gui_size(); + let mut ui = std::mem::take(&mut self.ui.options); + let events = ui.click(&mut self.settings, &self.res.atlas, self.cursor.0, self.cursor.1, size, true, false); + self.ui.options = ui; + self.handle_option_events(events) + } + pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> { + let mut ui = std::mem::take(&mut self.ui.options); + let events = ui.key(&mut self.settings, key, text); + self.ui.options = ui; + self.handle_option_events(events) + } + pub(super) fn options_scroll(&mut self, amount: f32) { + self.ui.options.scroll(amount); + } + /// Mouse buttons pressed while a key is being bound. + pub(super) fn options_waiting_for_key(&self) -> bool { + self.ui.options.selected_key.is_some() && self.ui.options.page() == Page::KeyBinds + } + pub(super) fn options_bind_mouse(&mut self, button: MouseButton) -> Result<()> { + if let Some(name) = self.ui.options.selected_key.take() { + self.settings.keys.set(name, &horizon_client::keybinds::mouse_name(button)); + self.handle_option_events(vec![Event::Changed])?; + } + Ok(()) + } + fn handle_option_events(&mut self, events: Vec) -> Result<()> { + for e in events { + match e { + Event::Changed => { + self.settings.save(&Self::options_path()); + self.apply_settings(); + } + Event::Close => { + self.settings.save(&Self::options_path()); + self.screen = if self.options_from_title { Screen::Playing } else { Screen::Paused }; + self.dragging = false; + } + Event::Language(code) => { + self.load_language(&code); + } + Event::Packs(_) => { + self.settings.save(&Self::options_path()); + self.reload_packs(); + } + Event::OpenPackFolder => { + let dir = std::env::current_dir().unwrap_or_default().join("resourcepacks"); + let _ = std::fs::create_dir_all(&dir); + let _ = std::process::Command::new("xdg-open").arg(&dir).spawn(); + } + } + } + Ok(()) + } + /// LanguageManager.setSelected + reload: translations, then re-wrap chat. + pub(super) fn load_language(&mut self, code: &str) { + let root = self.options.resources.clone(); + lang::set(lang::Language::load(&[&root], code)); + self.ui.chat.rescale(&self.res.atlas); + } + /// Settings that Horizon applies beyond render distance, volume and GUI scale. + pub(super) fn apply_ui_settings(&mut self) { + let s = &self.settings; + if let Some(r) = self.renderer.as_mut() { + r.gamma = s.gamma; + r.set_vsync(s.vsync); + } + if let Some(w) = &self.window { + let want = s.fullscreen; + if want != w.fullscreen().is_some() { + w.set_fullscreen(want.then_some(Fullscreen::Borderless(None))); + } + } + let mut volumes = s.volumes; + volumes[0] = 1.0; + horizon_client::settings::set_source_volumes(volumes); + let chat = s.chat_options(); + let rescale = { + let o = &self.ui.chat.options; + o.width != chat.width || o.scale != chat.scale || o.line_spacing != chat.line_spacing + }; + self.ui.chat.options = chat; + if rescale { + self.ui.chat.rescale(&self.res.atlas); + } + let font = &mut self.res.atlas.font; + if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs { + font.uniform = s.force_unicode; + font.japanese = s.japanese_glyphs; + font.reset_cache(); + self.ui.chat.rescale(&self.res.atlas); + } + } + /// F11 (key.fullscreen): Window.toggleFullScreen, remembered in options.txt. + pub(super) fn toggle_fullscreen(&mut self) { + self.settings.fullscreen = !self.settings.fullscreen; + self.settings.save(&Self::options_path()); + self.apply_ui_settings(); + } + /// Frame limiter for the Max Framerate option: when the next frame is due. + pub(super) fn next_frame_due(&self) -> Option { + let fps = self.settings.max_fps; + if fps >= 260 || self.options.frames.is_some() { + return None; + } + // Menus without a world run at 60 fps like vanilla's title screen. + let fps = if self.title.is_some() { fps.min(60) } else { fps }; + let due = self.previous + std::time::Duration::from_secs_f64(1.0 / f64::from(fps)); + (due > std::time::Instant::now()).then_some(due) + } +} diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs new file mode 100644 index 000000000..787dfbb5b --- /dev/null +++ b/crates/horizon-client/src/game/packs.rs @@ -0,0 +1,97 @@ +//! Resource pack selection bound to the game: the pack screen lists and +//! reloading after a change (atlas, fonts, GUI metadata, languages and item +//! icons live; block textures and models from the next start). +use super::Game; +use horizon_client::{ + hud::HudAtlas, + lang, + options_ui::PackEntry, + packs::{self, Pack}, + text::Text, +}; +use std::path::{Path, PathBuf}; + +/// Where overlay roots are built (beside options.txt). +pub fn cache_dir() -> PathBuf { + std::env::current_dir().unwrap_or_default().join(".horizon-cache/resourcepacks") +} +pub fn packs_dir() -> PathBuf { + std::env::current_dir().unwrap_or_default().join("resourcepacks") +} +/// The resource root to load from, given the vanilla root and the selection. +pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf { + let all = packs::discover(vanilla, &packs_dir()); + let enabled = packs::enabled(&all, selected); + packs::resource_root(vanilla, &enabled, &cache_dir()) +} +fn entry(p: &Pack) -> PackEntry { + PackEntry { id: p.id.clone(), title: p.title.clone(), description: p.description.clone(), compatible: p.compatible, required: false } +} +fn vanilla_entry() -> PackEntry { + PackEntry { + id: "vanilla".into(), + title: Text::translate("resourcePack.vanilla.name", &[]), + description: Text::translate("resourcePack.vanilla.description", &[]), + compatible: true, + required: true, + } +} +impl Game<'_> { + fn vanilla_root(&self) -> PathBuf { + if self.ui.vanilla_root.as_os_str().is_empty() { self.options.resources.clone() } else { self.ui.vanilla_root.clone() } + } + /// PackSelectionModel: available (unselected) and selected (top first). + pub(super) fn refresh_pack_lists(&mut self) { + let all = packs::discover(&self.vanilla_root(), &packs_dir()); + let selected_ids = &self.settings.resource_packs; + let mut selected: Vec = selected_ids + .iter() + .rev() + .filter_map(|id| if id == "vanilla" { Some(vanilla_entry()) } else { all.iter().find(|p| &p.id == id).map(entry) }) + .collect(); + if !selected.iter().any(|p| p.id == "vanilla") { + selected.push(vanilla_entry()); + } + let available = all.iter().filter(|p| !selected_ids.contains(&p.id)).map(entry).collect(); + self.ui.options.available = available; + self.ui.options.selected = selected; + } + /// Rebuild the overlay and reload what can change while running. + pub(super) fn reload_packs(&mut self) { + let vanilla = self.vanilla_root(); + if self.ui.vanilla_root.as_os_str().is_empty() { + self.ui.vanilla_root = vanilla.clone(); + } + let root = startup_root(&vanilla, &self.settings.resource_packs); + self.options.resources = root.clone(); + horizon_client::ui::load_metadata(&root); + match HudAtlas::build(&root) { + Ok(mut atlas) => { + atlas.font.uniform = self.settings.force_unicode; + atlas.font.japanese = self.settings.japanese_glyphs; + let same_size = atlas.width == self.res.atlas.width && atlas.height == self.res.atlas.height; + if same_size { + if let Some(texture) = self.renderer.as_ref().and_then(|r| r.hud.atlas_texture.clone()) + && let Some(r) = self.renderer.as_ref() + { + r.queue.write_texture( + wgpu::TexelCopyTextureInfo { texture: &texture, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All }, + &atlas.pixels, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(atlas.width * 4), rows_per_image: None }, + wgpu::Extent3d { width: atlas.width, height: atlas.height, depth_or_array_layers: 1 }, + ); + } + self.res.atlas = atlas; + self.res.icons.clear(); + self.res.displays.clear(); + } else { + eprintln!("Horizon: resource pack atlas size changed; restart to apply GUI textures"); + } + } + Err(e) => eprintln!("Horizon: resource pack reload failed: {e}"), + } + let code = lang::code(); + lang::set(lang::Language::load(&[&root], &code)); + self.ui.chat.rescale(&self.res.atlas); + } +} diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index fdb1ea8d2..675e38078 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -108,6 +108,9 @@ pub struct Renderer { pub screenshot: Option, /// Outcome of the last screenshot: frame size, or the error. pub screenshot_result: Option>, + /// Brightness option (lightmap gamma), 0..1. + pub gamma: f32, + present_modes: Vec, } fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec, u32) { let levels = size.trailing_zeros() + 1; @@ -204,6 +207,7 @@ impl Renderer { if caps.usages.contains(wgpu::TextureUsages::COPY_SRC) { config.usage |= wgpu::TextureUsages::COPY_SRC; } + let present_modes = caps.present_modes.clone(); config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) { wgpu::PresentMode::Mailbox } else { @@ -699,6 +703,8 @@ impl Renderer { started: Instant::now(), screenshot: None, screenshot_result: None, + gamma: 0.5, + present_modes, }) } fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { @@ -732,6 +738,21 @@ impl Renderer { }) .create_view(&Default::default()) } + /// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available. + pub fn set_vsync(&mut self, vsync: bool) { + let has = |m| self.present_modes.contains(&m); + let mode = match (vsync, has(wgpu::PresentMode::Mailbox), has(wgpu::PresentMode::Immediate)) { + (true, true, _) => wgpu::PresentMode::Mailbox, + (true, false, _) => wgpu::PresentMode::Fifo, + (false, _, true) => wgpu::PresentMode::Immediate, + (false, true, false) => wgpu::PresentMode::Mailbox, + _ => wgpu::PresentMode::Fifo, + }; + if self.config.present_mode != mode { + self.config.present_mode = mode; + self.surface.configure(&self.device, &self.config); + } + } pub fn resize(&mut self, width: u32, height: u32) { self.suspended = width == 0 || height == 0; if self.suspended { @@ -953,7 +974,7 @@ impl Renderer { } }; self.animate(frame.ticks); - self.update_lightmap(&frame.sky, 0.0, 0.5); + self.update_lightmap(&frame.sky, 0.0, self.gamma); let view_proj = self.view_projection(frame); let aspect = self.config.width as f32 / self.config.height.max(1) as f32; let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians()); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 66a2f739e..638f9d6d3 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -101,7 +101,7 @@ impl HudAtlas { } return Some((name, 256, 256, small)); } - (w <= 1024 && h <= 512).then_some((name, w, h, pixels)) + (w <= 1024 && (h <= 512 || name.starts_with("font/"))).then_some((name, w, h, pixels)) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs new file mode 100644 index 000000000..0d608e2ef --- /dev/null +++ b/crates/horizon-client/src/keybinds.rs @@ -0,0 +1,344 @@ +//! Key mappings (Options.keyMappings): vanilla names, categories and +//! defaults, `key_:key.keyboard.x` persistence, display names, and the +//! translation of rebound physical keys back to the default keys the game +//! logic listens for. +use crate::text::Text; +use std::collections::BTreeMap; +use winit::{event::MouseButton, keyboard::KeyCode}; + +/// (name, default key, category) in Options.keyMappings order. +pub const MAPPINGS: &[(&str, &str, &str)] = &[ + ("key.attack", "key.mouse.left", "gameplay"), + ("key.use", "key.mouse.right", "gameplay"), + ("key.forward", "key.keyboard.w", "movement"), + ("key.left", "key.keyboard.a", "movement"), + ("key.back", "key.keyboard.s", "movement"), + ("key.right", "key.keyboard.d", "movement"), + ("key.jump", "key.keyboard.space", "movement"), + ("key.sneak", "key.keyboard.left.shift", "movement"), + ("key.sprint", "key.keyboard.left.control", "movement"), + ("key.drop", "key.keyboard.q", "inventory"), + ("key.inventory", "key.keyboard.e", "inventory"), + ("key.chat", "key.keyboard.t", "multiplayer"), + ("key.playerlist", "key.keyboard.tab", "multiplayer"), + ("key.pickItem", "key.mouse.middle", "gameplay"), + ("key.command", "key.keyboard.slash", "multiplayer"), + ("key.friends", "key.keyboard.o", "multiplayer"), + ("key.socialInteractions", "key.keyboard.p", "multiplayer"), + ("key.toggleGui", "key.keyboard.f1", "misc"), + ("key.toggleSpectatorShaderEffects", "key.keyboard.f4", "misc"), + ("key.screenshot", "key.keyboard.f2", "misc"), + ("key.togglePerspective", "key.keyboard.f5", "misc"), + ("key.smoothCamera", "key.keyboard.unknown", "misc"), + ("key.fullscreen", "key.keyboard.f11", "misc"), + ("key.spectatorOutlines", "key.keyboard.unknown", "spectator"), + ("key.spectatorHotbar", "key.mouse.middle", "spectator"), + ("key.swapOffhand", "key.keyboard.f", "inventory"), + ("key.saveToolbarActivator", "key.keyboard.c", "creative"), + ("key.loadToolbarActivator", "key.keyboard.x", "creative"), + ("key.advancements", "key.keyboard.l", "misc"), + ("key.quickActions", "key.keyboard.g", "misc"), + ("key.debug.overlay", "key.keyboard.f3", "debug"), + ("key.hotbar.1", "key.keyboard.1", "inventory"), + ("key.hotbar.2", "key.keyboard.2", "inventory"), + ("key.hotbar.3", "key.keyboard.3", "inventory"), + ("key.hotbar.4", "key.keyboard.4", "inventory"), + ("key.hotbar.5", "key.keyboard.5", "inventory"), + ("key.hotbar.6", "key.keyboard.6", "inventory"), + ("key.hotbar.7", "key.keyboard.7", "inventory"), + ("key.hotbar.8", "key.keyboard.8", "inventory"), + ("key.hotbar.9", "key.keyboard.9", "inventory"), +]; +/// KeyMapping.Category sort order. +pub const CATEGORIES: [&str; 8] = ["movement", "misc", "multiplayer", "gameplay", "inventory", "creative", "spectator", "debug"]; + +/// InputConstants key names <-> winit physical keys. +const KEYS: &[(&str, KeyCode)] = &[ + ("key.keyboard.a", KeyCode::KeyA), + ("key.keyboard.b", KeyCode::KeyB), + ("key.keyboard.c", KeyCode::KeyC), + ("key.keyboard.d", KeyCode::KeyD), + ("key.keyboard.e", KeyCode::KeyE), + ("key.keyboard.f", KeyCode::KeyF), + ("key.keyboard.g", KeyCode::KeyG), + ("key.keyboard.h", KeyCode::KeyH), + ("key.keyboard.i", KeyCode::KeyI), + ("key.keyboard.j", KeyCode::KeyJ), + ("key.keyboard.k", KeyCode::KeyK), + ("key.keyboard.l", KeyCode::KeyL), + ("key.keyboard.m", KeyCode::KeyM), + ("key.keyboard.n", KeyCode::KeyN), + ("key.keyboard.o", KeyCode::KeyO), + ("key.keyboard.p", KeyCode::KeyP), + ("key.keyboard.q", KeyCode::KeyQ), + ("key.keyboard.r", KeyCode::KeyR), + ("key.keyboard.s", KeyCode::KeyS), + ("key.keyboard.t", KeyCode::KeyT), + ("key.keyboard.u", KeyCode::KeyU), + ("key.keyboard.v", KeyCode::KeyV), + ("key.keyboard.w", KeyCode::KeyW), + ("key.keyboard.x", KeyCode::KeyX), + ("key.keyboard.y", KeyCode::KeyY), + ("key.keyboard.z", KeyCode::KeyZ), + ("key.keyboard.1", KeyCode::Digit1), + ("key.keyboard.2", KeyCode::Digit2), + ("key.keyboard.3", KeyCode::Digit3), + ("key.keyboard.4", KeyCode::Digit4), + ("key.keyboard.5", KeyCode::Digit5), + ("key.keyboard.6", KeyCode::Digit6), + ("key.keyboard.7", KeyCode::Digit7), + ("key.keyboard.8", KeyCode::Digit8), + ("key.keyboard.9", KeyCode::Digit9), + ("key.keyboard.0", KeyCode::Digit0), + ("key.keyboard.enter", KeyCode::Enter), + ("key.keyboard.escape", KeyCode::Escape), + ("key.keyboard.backspace", KeyCode::Backspace), + ("key.keyboard.tab", KeyCode::Tab), + ("key.keyboard.space", KeyCode::Space), + ("key.keyboard.minus", KeyCode::Minus), + ("key.keyboard.equal", KeyCode::Equal), + ("key.keyboard.left.bracket", KeyCode::BracketLeft), + ("key.keyboard.right.bracket", KeyCode::BracketRight), + ("key.keyboard.backslash", KeyCode::Backslash), + ("key.keyboard.semicolon", KeyCode::Semicolon), + ("key.keyboard.apostrophe", KeyCode::Quote), + ("key.keyboard.grave.accent", KeyCode::Backquote), + ("key.keyboard.comma", KeyCode::Comma), + ("key.keyboard.period", KeyCode::Period), + ("key.keyboard.slash", KeyCode::Slash), + ("key.keyboard.caps.lock", KeyCode::CapsLock), + ("key.keyboard.f1", KeyCode::F1), + ("key.keyboard.f2", KeyCode::F2), + ("key.keyboard.f3", KeyCode::F3), + ("key.keyboard.f4", KeyCode::F4), + ("key.keyboard.f5", KeyCode::F5), + ("key.keyboard.f6", KeyCode::F6), + ("key.keyboard.f7", KeyCode::F7), + ("key.keyboard.f8", KeyCode::F8), + ("key.keyboard.f9", KeyCode::F9), + ("key.keyboard.f10", KeyCode::F10), + ("key.keyboard.f11", KeyCode::F11), + ("key.keyboard.f12", KeyCode::F12), + ("key.keyboard.print.screen", KeyCode::PrintScreen), + ("key.keyboard.scroll.lock", KeyCode::ScrollLock), + ("key.keyboard.pause", KeyCode::Pause), + ("key.keyboard.insert", KeyCode::Insert), + ("key.keyboard.home", KeyCode::Home), + ("key.keyboard.page.up", KeyCode::PageUp), + ("key.keyboard.delete", KeyCode::Delete), + ("key.keyboard.end", KeyCode::End), + ("key.keyboard.page.down", KeyCode::PageDown), + ("key.keyboard.right", KeyCode::ArrowRight), + ("key.keyboard.left", KeyCode::ArrowLeft), + ("key.keyboard.down", KeyCode::ArrowDown), + ("key.keyboard.up", KeyCode::ArrowUp), + ("key.keyboard.num.lock", KeyCode::NumLock), + ("key.keyboard.keypad.divide", KeyCode::NumpadDivide), + ("key.keyboard.keypad.multiply", KeyCode::NumpadMultiply), + ("key.keyboard.keypad.subtract", KeyCode::NumpadSubtract), + ("key.keyboard.keypad.add", KeyCode::NumpadAdd), + ("key.keyboard.keypad.enter", KeyCode::NumpadEnter), + ("key.keyboard.keypad.1", KeyCode::Numpad1), + ("key.keyboard.keypad.2", KeyCode::Numpad2), + ("key.keyboard.keypad.3", KeyCode::Numpad3), + ("key.keyboard.keypad.4", KeyCode::Numpad4), + ("key.keyboard.keypad.5", KeyCode::Numpad5), + ("key.keyboard.keypad.6", KeyCode::Numpad6), + ("key.keyboard.keypad.7", KeyCode::Numpad7), + ("key.keyboard.keypad.8", KeyCode::Numpad8), + ("key.keyboard.keypad.9", KeyCode::Numpad9), + ("key.keyboard.keypad.0", KeyCode::Numpad0), + ("key.keyboard.keypad.period", KeyCode::NumpadDecimal), + ("key.keyboard.keypad.equal", KeyCode::NumpadEqual), + ("key.keyboard.menu", KeyCode::ContextMenu), + ("key.keyboard.left.control", KeyCode::ControlLeft), + ("key.keyboard.left.shift", KeyCode::ShiftLeft), + ("key.keyboard.left.alt", KeyCode::AltLeft), + ("key.keyboard.left.win", KeyCode::SuperLeft), + ("key.keyboard.right.control", KeyCode::ControlRight), + ("key.keyboard.right.shift", KeyCode::ShiftRight), + ("key.keyboard.right.alt", KeyCode::AltRight), + ("key.keyboard.right.win", KeyCode::SuperRight), +]; +pub fn key_code(name: &str) -> Option { + KEYS.iter().find(|(n, _)| *n == name).map(|(_, k)| *k) +} +pub fn key_name(code: KeyCode) -> Option<&'static str> { + KEYS.iter().find(|(_, k)| *k == code).map(|(n, _)| *n) +} +pub fn mouse_name(button: MouseButton) -> String { + match button { + MouseButton::Left => "key.mouse.left".into(), + MouseButton::Right => "key.mouse.right".into(), + MouseButton::Middle => "key.mouse.middle".into(), + MouseButton::Back => "key.mouse.4".into(), + MouseButton::Forward => "key.mouse.5".into(), + MouseButton::Other(n) => format!("key.mouse.{}", n + 1), + } +} +pub fn mouse_button(name: &str) -> Option { + Some(match name { + "key.mouse.left" => MouseButton::Left, + "key.mouse.right" => MouseButton::Right, + "key.mouse.middle" => MouseButton::Middle, + "key.mouse.4" => MouseButton::Back, + "key.mouse.5" => MouseButton::Forward, + _ => return None, + }) +} +/// InputConstants.Key.getDisplayName: one-character keys as the upper-case +/// character, others by translation. +pub fn display_name(key: &str) -> Text { + if let Some(rest) = key.strip_prefix("key.keyboard.") + && rest.chars().count() == 1 + { + let c = rest.to_uppercase(); + return Text::literal(c); + } + let symbol = match key { + "key.keyboard.minus" => Some("-"), + "key.keyboard.equal" => Some("="), + "key.keyboard.left.bracket" => Some("["), + "key.keyboard.right.bracket" => Some("]"), + "key.keyboard.backslash" => Some("\\"), + "key.keyboard.semicolon" => Some(";"), + "key.keyboard.apostrophe" => Some("'"), + "key.keyboard.grave.accent" => Some("`"), + "key.keyboard.comma" => Some(","), + "key.keyboard.period" => Some("."), + "key.keyboard.slash" => Some("/"), + _ => None, + }; + if let Some(s) = symbol { + return Text::literal(s); + } + if let Some(n) = key.strip_prefix("key.mouse.") + && n.parse::().is_ok() + && !crate::lang::has(key) + { + return Text::translate("key.mouse", &[Text::literal(n)]); + } + Text::translate(key, &[]) +} + +/// Current bindings by mapping name. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct KeyBinds { + keys: BTreeMap<&'static str, String>, +} +impl Default for KeyBinds { + fn default() -> Self { + Self { keys: MAPPINGS.iter().map(|(n, d, _)| (*n, (*d).to_owned())).collect() } + } +} +impl KeyBinds { + pub fn get(&self, name: &str) -> &str { + self.keys.get(name).map_or("key.keyboard.unknown", String::as_str) + } + pub fn default_of(name: &str) -> &'static str { + MAPPINGS.iter().find(|m| m.0 == name).map_or("key.keyboard.unknown", |m| m.1) + } + pub fn is_default(&self, name: &str) -> bool { + self.get(name) == Self::default_of(name) + } + pub fn set(&mut self, name: &str, key: &str) { + if let Some((n, _, _)) = MAPPINGS.iter().find(|m| m.0 == name) { + self.keys.insert(n, key.to_owned()); + } + } + /// Load `key_` from options.txt; false for unknown mappings. + pub fn set_saved(&mut self, name: &str, key: &str) -> bool { + if MAPPINGS.iter().any(|m| m.0 == name) { + self.set(name, key); + true + } else { + false + } + } + pub fn saved(&self) -> Vec<(&'static str, String)> { + MAPPINGS.iter().map(|(n, _, _)| (*n, self.get(n).to_owned())).collect() + } + pub fn reset_all(&mut self) { + *self = Self::default(); + } + /// Mappings sharing `name`'s key (KeyMapping.same), for conflict marks. + pub fn conflicts(&self, name: &str) -> Vec<&'static str> { + let key = self.get(name); + if key == "key.keyboard.unknown" { + return Vec::new(); + } + MAPPINGS + .iter() + .filter(|(n, _, _)| *n != name && self.get(n) == key && (!self.is_default(n) || !self.is_default(name))) + .map(|(n, _, _)| *n) + .collect() + } + /// The mapping a physical input triggers (first in list order). + pub fn mapping_for(&self, key: &str) -> Option<&'static str> { + MAPPINGS.iter().map(|m| m.0).find(|n| self.get(n) == key) + } + /// Translate a physical key into the default key of the mapping it is + /// bound to, so game code written against vanilla defaults follows the + /// player's bindings. `None` means the key now does nothing; mouse + /// mappings bound to keys come back as `Err(button)`. + pub fn translate(&self, key: KeyCode) -> Option> { + let Some(name) = key_name(key) else { return Some(Ok(key)) }; + if let Some(mapping) = self.mapping_for(name) { + let default = Self::default_of(mapping); + if let Some(code) = key_code(default) { + return Some(Ok(code)); + } + return mouse_button(default).map(Err); + } + // An unbound key whose default meaning was moved elsewhere is inert. + if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) { + return None; + } + Some(Ok(key)) + } + /// Translate a mouse button the same way (keys bound to mouse buttons). + pub fn translate_mouse(&self, button: MouseButton) -> Option> { + let name = mouse_name(button); + if let Some(mapping) = self.mapping_for(&name) { + let default = Self::default_of(mapping); + if let Some(b) = mouse_button(default) { + return Some(Err(b)); + } + return key_code(default).map(Ok); + } + if MAPPINGS.iter().any(|(n, d, _)| *d == name && !self.is_default(n)) { + return None; + } + Some(Err(button)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rebinding_translates_to_defaults() { + let mut k = KeyBinds::default(); + assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyW))); + // Forward on the up arrow, inventory on W. + k.set("key.forward", "key.keyboard.up"); + k.set("key.inventory", "key.keyboard.w"); + assert_eq!(k.translate(KeyCode::ArrowUp), Some(Ok(KeyCode::KeyW))); + assert_eq!(k.translate(KeyCode::KeyW), Some(Ok(KeyCode::KeyE))); + // E's default meaning moved and nothing else uses it. + assert_eq!(k.translate(KeyCode::KeyE), None); + // Attack on a key. + k.set("key.attack", "key.keyboard.r"); + assert_eq!(k.translate(KeyCode::KeyR), Some(Err(MouseButton::Left))); + assert_eq!(k.translate_mouse(MouseButton::Left), None); + assert_eq!(k.translate(KeyCode::Escape), Some(Ok(KeyCode::Escape))); + assert!(k.conflicts("key.forward").is_empty()); + k.set("key.jump", "key.keyboard.up"); + assert_eq!(k.conflicts("key.forward"), ["key.jump"]); + } + #[test] + fn display_names() { + assert_eq!(display_name("key.keyboard.w").plain(), "W"); + assert_eq!(display_name("key.keyboard.slash").plain(), "/"); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 387d15e16..48d9bf648 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -25,6 +25,7 @@ pub mod hud; pub mod hunger; pub mod input; pub mod items; +pub mod keybinds; pub mod lang; pub mod landing; pub mod light; @@ -32,6 +33,8 @@ pub mod mesher; pub mod mobs; pub mod models; pub mod motion; +pub mod options_ui; +pub mod packs; pub mod particles; pub mod pose; pub mod save; diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs new file mode 100644 index 000000000..eee11d3a1 --- /dev/null +++ b/crates/horizon-client/src/options_ui.rs @@ -0,0 +1,1123 @@ +//! The options screens: OptionsScreen, Video Settings, Music & Sounds, +//! Controls, Key Binds, Mouse Settings, Chat Settings, Accessibility, +//! Language and Resource Packs, laid out like vanilla's HeaderAndFooter / +//! OptionsList screens and drawn with the shared widgets. +use crate::{ + hud::{HudAtlas, HudBatch, rgba}, + keybinds::{self, CATEGORIES, KeyBinds, MAPPINGS}, + lang::{self, LanguageInfo}, + settings::{SOUND_SOURCES, Settings}, + text::{self, Style, Text}, + ui, +}; + +/// One option instance. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Opt { + Fov, + RenderDistance, + SimulationDistance, + Sensitivity, + WheelSensitivity, + InvertY, + DiscreteScroll, + Volume(usize), + GuiScale, + ViewBobbing, + Gamma, + MaxFps, + Vsync, + Fullscreen, + SmoothLighting, + Clouds, + CloudRange, + Particles, + EntityDistance, + EntityShadows, + BiomeBlend, + Preset, + Mipmaps, + WeatherRadius, + ChunkFade, + Vignette, + Autosave, + CutoutLeaves, + ImprovedTransparency, + AttackIndicator, + InactivityFps, + ChunkBuilder, + MenuBlur, + ToggleCrouch, + ToggleSprint, + AutoJump, + ChatVisibility, + ChatColors, + ChatLinks, + ChatOpacity, + TextBackgroundOpacity, + ChatScale, + ChatWidth, + ChatHeightFocused, + ChatHeightUnfocused, + ChatLineSpacing, + AutoSuggestions, + ReducedDebugInfo, + HighContrast, + ForceUnicode, + JapaneseGlyphs, +} +fn tr(key: &str) -> Text { + Text::translate(key, &[]) +} +fn generic(caption: &str, value: Text) -> Text { + Text::translate("options.generic_value", &[tr(caption), value]) +} +fn percent(caption: &str, value: f32) -> Text { + Text::translate("options.percent_value", &[tr(caption), Text::literal(((f64::from(value) * 100.0) as i32).to_string())]) +} +fn on_off(v: bool) -> Text { + tr(if v { "options.on" } else { "options.off" }) +} +fn chat_px(caption: &str, px: f32) -> Text { + Text::translate("options.pixel_value", &[tr(caption), Text::literal((px as i32).to_string())]) +} +enum Kind { + /// Slider position 0..1. + Slider(f32), + Cycle, +} +impl Opt { + fn caption(self) -> &'static str { + match self { + Opt::Fov => "options.fov", + Opt::RenderDistance => "options.renderDistance", + Opt::SimulationDistance => "options.simulationDistance", + Opt::Sensitivity => "options.sensitivity", + Opt::WheelSensitivity => "options.mouseWheelSensitivity", + Opt::InvertY => "options.invertMouseY", + Opt::DiscreteScroll => "options.discrete_mouse_scroll", + Opt::Volume(_) => "soundCategory.master", + Opt::GuiScale => "options.guiScale", + Opt::ViewBobbing => "options.viewBobbing", + Opt::Gamma => "options.gamma", + Opt::MaxFps => "options.framerateLimit", + Opt::Vsync => "options.vsync", + Opt::Fullscreen => "options.fullscreen", + Opt::SmoothLighting => "options.ao", + Opt::Clouds => "options.renderClouds", + Opt::CloudRange => "options.renderCloudsDistance", + Opt::Particles => "options.particles", + Opt::EntityDistance => "options.entityDistanceScaling", + Opt::EntityShadows => "options.entityShadows", + Opt::BiomeBlend => "options.biomeBlendRadius", + Opt::Preset => "options.graphics.preset", + Opt::Mipmaps => "options.mipmapLevels", + Opt::WeatherRadius => "options.weatherRadius", + Opt::ChunkFade => "options.chunkFade", + Opt::Vignette => "options.vignette", + Opt::Autosave => "options.autosaveIndicator", + Opt::CutoutLeaves => "options.cutoutLeaves", + Opt::ImprovedTransparency => "options.improvedTransparency", + Opt::AttackIndicator => "options.attackIndicator", + Opt::InactivityFps => "options.inactivityFpsLimit", + Opt::ChunkBuilder => "options.prioritizeChunkUpdates", + Opt::MenuBlur => "options.accessibility.menu_background_blurriness", + Opt::ToggleCrouch => "key.sneak", + Opt::ToggleSprint => "key.sprint", + Opt::AutoJump => "options.autoJump", + Opt::ChatVisibility => "options.chat.visibility", + Opt::ChatColors => "options.chat.color", + Opt::ChatLinks => "options.chat.links", + Opt::ChatOpacity => "options.chat.opacity", + Opt::TextBackgroundOpacity => "options.accessibility.text_background_opacity", + Opt::ChatScale => "options.chat.scale", + Opt::ChatWidth => "options.chat.width", + Opt::ChatHeightFocused => "options.chat.height.focused", + Opt::ChatHeightUnfocused => "options.chat.height.unfocused", + Opt::ChatLineSpacing => "options.chat.line_spacing", + Opt::AutoSuggestions => "options.autoSuggestCommands", + Opt::ReducedDebugInfo => "options.reducedDebugInfo", + Opt::HighContrast => "options.accessibility.high_contrast", + Opt::ForceUnicode => "options.forceUnicodeFont", + Opt::JapaneseGlyphs => "options.japaneseGlyphVariants", + } + } + fn kind(self, s: &Settings) -> Kind { + let unit = |v: f32, lo: f32, hi: f32| Kind::Slider(((v - lo) / (hi - lo)).clamp(0.0, 1.0)); + match self { + Opt::Fov => unit(s.fov, 30.0, 110.0), + Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 32.0), + Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0), + Opt::Sensitivity => Kind::Slider(s.sensitivity), + Opt::WheelSensitivity => unit(s.mouse_wheel_sensitivity, 0.01, 10.0), + Opt::Volume(i) => Kind::Slider(if i == 0 { s.master_volume } else { s.volumes[i] }), + Opt::GuiScale => unit(s.gui_scale as f32, 0.0, 6.0), + Opt::Gamma => Kind::Slider(s.gamma), + Opt::MaxFps => unit(s.max_fps as f32, 10.0, 260.0), + Opt::CloudRange => unit(s.cloud_range as f32, 2.0, 128.0), + Opt::EntityDistance => unit(s.entity_distance, 0.5, 5.0), + Opt::BiomeBlend => unit(s.biome_blend as f32, 0.0, 7.0), + Opt::Preset => unit(preset_index(&s.graphics_preset) as f32, 0.0, 3.0), + Opt::Mipmaps => unit(s.mipmap_levels as f32, 0.0, 4.0), + Opt::WeatherRadius => unit(s.weather_radius as f32, 3.0, 10.0), + Opt::ChunkFade => unit(s.chunk_fade, 0.0, 2.0), + Opt::MenuBlur => unit(s.menu_blur as f32, 0.0, 10.0), + Opt::ChatOpacity => Kind::Slider(s.chat_opacity), + Opt::TextBackgroundOpacity => Kind::Slider(s.text_background_opacity), + Opt::ChatScale => Kind::Slider(s.chat_scale), + Opt::ChatWidth => Kind::Slider(s.chat_width), + Opt::ChatHeightFocused => Kind::Slider(s.chat_height_focused), + Opt::ChatHeightUnfocused => Kind::Slider(s.chat_height_unfocused), + Opt::ChatLineSpacing => Kind::Slider(s.chat_line_spacing), + _ => Kind::Cycle, + } + } + /// The widget message (OptionInstance.toString / CycleButton full name). + pub fn label(self, s: &Settings) -> Text { + let c = self.caption(); + match self { + Opt::Fov => match s.fov as i32 { + 70 => generic(c, tr("options.fov.min")), + 110 => generic(c, tr("options.fov.max")), + v => generic(c, Text::literal(v.to_string())), + }, + Opt::RenderDistance => generic(c, Text::tr("options.chunks", &[&s.render_distance])), + Opt::SimulationDistance => generic(c, Text::tr("options.chunks", &[&s.simulation_distance])), + Opt::Sensitivity => { + if s.sensitivity == 0.0 { + generic(c, tr("options.sensitivity.min")) + } else if s.sensitivity == 1.0 { + generic(c, tr("options.sensitivity.max")) + } else { + percent(c, 2.0 * s.sensitivity) + } + } + Opt::WheelSensitivity => generic(c, Text::literal(format!("{:.2}", s.mouse_wheel_sensitivity))), + Opt::Volume(i) => { + let v = if i == 0 { s.master_volume } else { s.volumes[i] }; + let caption = format!("soundCategory.{}", SOUND_SOURCES[i]); + if v == 0.0 { generic(&caption, tr("options.off")) } else { percent(&caption, v) } + } + Opt::GuiScale => { + if s.gui_scale == 0 { + tr("options.guiScale.auto") + } else { + Text::literal(s.gui_scale.to_string()) + } + } + Opt::Gamma => match (f64::from(s.gamma) * 100.0) as i32 { + 0 => generic(c, tr("options.gamma.min")), + 50 => generic(c, tr("options.gamma.default")), + 100 => generic(c, tr("options.gamma.max")), + v => generic(c, Text::literal(v.to_string())), + }, + Opt::MaxFps => { + if s.max_fps >= 260 { + generic(c, tr("options.framerateLimit.max")) + } else { + generic(c, Text::tr("options.framerate", &[&s.max_fps])) + } + } + Opt::CloudRange => generic(c, Text::tr("options.chunks", &[&s.cloud_range])), + Opt::EntityDistance => percent(c, s.entity_distance), + Opt::BiomeBlend => generic(c, tr(&format!("options.biomeBlendRadius.{}", s.biome_blend * 2 + 1))), + Opt::Preset => generic(c, tr(&format!("options.graphics.{}", s.graphics_preset))), + Opt::Mipmaps => { + if s.mipmap_levels == 0 { + generic(c, tr("options.off")) + } else { + generic(c, Text::literal(s.mipmap_levels.to_string())) + } + } + Opt::WeatherRadius => generic(c, Text::tr("options.blocks", &[&s.weather_radius])), + Opt::ChunkFade => { + if s.chunk_fade <= 0.0 { + tr("options.chunkFade.none") + } else { + Text::tr("options.chunkFade.seconds", &[&format!("{:.2}", s.chunk_fade)]) + } + } + Opt::MenuBlur => { + if s.menu_blur == 0 { + generic(c, tr("options.off")) + } else { + generic(c, Text::literal(s.menu_blur.to_string())) + } + } + Opt::ChatOpacity => percent(c, s.chat_opacity * 0.9 + 0.1), + Opt::TextBackgroundOpacity => percent(c, s.text_background_opacity), + Opt::ChatScale => { + if s.chat_scale == 0.0 { + generic(c, tr("options.off")) + } else { + percent(c, s.chat_scale) + } + } + Opt::ChatWidth => chat_px(c, (s.chat_width * 280.0 + 40.0).floor()), + Opt::ChatHeightFocused => chat_px(c, (s.chat_height_focused * 160.0 + 20.0).floor()), + Opt::ChatHeightUnfocused => chat_px(c, (s.chat_height_unfocused * 160.0 + 20.0).floor()), + Opt::ChatLineSpacing => percent(c, s.chat_line_spacing), + _ => generic(c, self.value_text(s)), + } + } + fn value_text(self, s: &Settings) -> Text { + match self { + Opt::InvertY => on_off(s.invert_y), + Opt::DiscreteScroll => on_off(s.discrete_scroll), + Opt::ViewBobbing => on_off(s.view_bobbing), + Opt::Vsync => on_off(s.vsync), + Opt::Fullscreen => on_off(s.fullscreen), + Opt::SmoothLighting => on_off(s.smooth_lighting), + Opt::Clouds => tr(match s.clouds.as_str() { + "false" => "options.off", + "fast" => "options.clouds.fast", + _ => "options.clouds.fancy", + }), + Opt::Particles => tr(["options.particles.all", "options.particles.decreased", "options.particles.minimal"][usize::from(s.particles.min(2))]), + Opt::EntityShadows => on_off(s.entity_shadows), + Opt::Vignette => on_off(s.vignette), + Opt::Autosave => on_off(s.autosave_indicator), + Opt::CutoutLeaves => on_off(s.cutout_leaves), + Opt::ImprovedTransparency => on_off(s.improved_transparency), + Opt::AttackIndicator => tr(["options.off", "options.attack.crosshair", "options.attack.hotbar"][usize::from(s.attack_indicator.min(2))]), + Opt::InactivityFps => tr(if s.inactivity_fps_limit == "minimized" { "options.inactivityFpsLimit.minimized" } else { "options.inactivityFpsLimit.afk" }), + Opt::ChunkBuilder => tr(["options.prioritizeChunkUpdates.none", "options.prioritizeChunkUpdates.byPlayer", "options.prioritizeChunkUpdates.nearby"][usize::from(s.prioritize_chunk_updates.min(2))]), + Opt::ToggleCrouch => tr(if s.toggle_crouch { "options.key.toggle" } else { "options.key.hold" }), + Opt::ToggleSprint => tr(if s.toggle_sprint { "options.key.toggle" } else { "options.key.hold" }), + Opt::AutoJump => on_off(s.auto_jump), + Opt::ChatVisibility => tr(["options.chat.visibility.full", "options.chat.visibility.system", "options.chat.visibility.hidden"][usize::from(s.chat_visibility.min(2))]), + Opt::ChatColors => on_off(s.chat_colors), + Opt::ChatLinks => on_off(s.chat_links), + Opt::AutoSuggestions => on_off(s.auto_suggestions), + Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), + Opt::HighContrast => on_off(s.high_contrast), + Opt::ForceUnicode => on_off(s.force_unicode), + Opt::JapaneseGlyphs => on_off(s.japanese_glyphs), + _ => Text::empty(), + } + } + /// Set a slider from its 0..1 position (OptionInstance value sets). + pub fn set_slider(self, s: &mut Settings, v: f32) { + let step = |lo: f32, hi: f32| (lo + v * (hi - lo)).round(); + match self { + Opt::Fov => s.fov = step(30.0, 110.0), + Opt::RenderDistance => s.render_distance = step(2.0, 32.0) as i32, + Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32, + Opt::Sensitivity => s.sensitivity = v, + Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99, + Opt::Volume(0) => s.master_volume = v, + Opt::Volume(i) => s.volumes[i] = v, + Opt::GuiScale => s.gui_scale = step(0.0, 6.0) as u32, + Opt::Gamma => s.gamma = v, + Opt::MaxFps => s.max_fps = (step(1.0, 26.0) as u32) * 10, + Opt::CloudRange => s.cloud_range = step(2.0, 128.0) as i32, + Opt::EntityDistance => s.entity_distance = step(2.0, 20.0) / 4.0, + Opt::BiomeBlend => s.biome_blend = step(0.0, 7.0) as i32, + Opt::Preset => s.graphics_preset = PRESETS[step(0.0, 3.0) as usize].into(), + Opt::Mipmaps => s.mipmap_levels = step(0.0, 4.0) as i32, + Opt::WeatherRadius => s.weather_radius = step(3.0, 10.0) as i32, + Opt::ChunkFade => s.chunk_fade = step(0.0, 40.0) / 20.0, + Opt::MenuBlur => s.menu_blur = step(0.0, 10.0) as i32, + Opt::ChatOpacity => s.chat_opacity = v, + Opt::TextBackgroundOpacity => s.text_background_opacity = v, + Opt::ChatScale => s.chat_scale = v, + Opt::ChatWidth => s.chat_width = v, + Opt::ChatHeightFocused => s.chat_height_focused = v, + Opt::ChatHeightUnfocused => s.chat_height_unfocused = v, + Opt::ChatLineSpacing => s.chat_line_spacing = v, + _ => {} + } + if self.affects_preset() { + s.graphics_preset = "custom".into(); + } + } + fn affects_preset(self) -> bool { + matches!( + self, + Opt::RenderDistance + | Opt::SimulationDistance + | Opt::SmoothLighting + | Opt::Clouds + | Opt::CloudRange + | Opt::Particles + | Opt::EntityDistance + | Opt::EntityShadows + | Opt::BiomeBlend + | Opt::Mipmaps + | Opt::WeatherRadius + | Opt::CutoutLeaves + | Opt::ImprovedTransparency + | Opt::MenuBlur + ) + } + /// Advance a cycle button (CycleButton.cycleValue). + pub fn cycle(self, s: &mut Settings, back: bool) { + let next = |n: u8, count: u8| if back { (n + count - 1) % count } else { (n + 1) % count }; + match self { + Opt::InvertY => s.invert_y = !s.invert_y, + Opt::DiscreteScroll => s.discrete_scroll = !s.discrete_scroll, + Opt::ViewBobbing => s.view_bobbing = !s.view_bobbing, + Opt::Vsync => s.vsync = !s.vsync, + Opt::Fullscreen => s.fullscreen = !s.fullscreen, + Opt::SmoothLighting => s.smooth_lighting = !s.smooth_lighting, + Opt::Clouds => { + let order = ["false", "fast", "true"]; + let i = order.iter().position(|c| *c == s.clouds).unwrap_or(2) as u8; + s.clouds = order[usize::from(next(i, 3))].into(); + } + Opt::Particles => s.particles = next(s.particles, 3), + Opt::EntityShadows => s.entity_shadows = !s.entity_shadows, + Opt::Vignette => s.vignette = !s.vignette, + Opt::Autosave => s.autosave_indicator = !s.autosave_indicator, + Opt::CutoutLeaves => s.cutout_leaves = !s.cutout_leaves, + Opt::ImprovedTransparency => s.improved_transparency = !s.improved_transparency, + Opt::AttackIndicator => s.attack_indicator = next(s.attack_indicator, 3), + Opt::InactivityFps => s.inactivity_fps_limit = if s.inactivity_fps_limit == "afk" { "minimized".into() } else { "afk".into() }, + Opt::ChunkBuilder => s.prioritize_chunk_updates = next(s.prioritize_chunk_updates, 3), + Opt::ToggleCrouch => s.toggle_crouch = !s.toggle_crouch, + Opt::ToggleSprint => s.toggle_sprint = !s.toggle_sprint, + Opt::AutoJump => s.auto_jump = !s.auto_jump, + Opt::ChatVisibility => s.chat_visibility = next(s.chat_visibility, 3), + Opt::ChatColors => s.chat_colors = !s.chat_colors, + Opt::ChatLinks => s.chat_links = !s.chat_links, + Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions, + Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, + Opt::HighContrast => s.high_contrast = !s.high_contrast, + Opt::ForceUnicode => s.force_unicode = !s.force_unicode, + Opt::JapaneseGlyphs => s.japanese_glyphs = !s.japanese_glyphs, + _ => {} + } + if self.affects_preset() { + s.graphics_preset = "custom".into(); + } + } +} +const PRESETS: [&str; 4] = ["fast", "fancy", "fabulous", "custom"]; +fn preset_index(p: &str) -> usize { + PRESETS.iter().position(|x| *x == p).unwrap_or(1) +} +/// GraphicsPreset.apply: quality options for Fast/Fancy/Fabulous. +pub fn apply_preset(s: &mut Settings) { + match s.graphics_preset.as_str() { + "fast" => { + s.clouds = "fast".into(); + s.particles = 1; + s.entity_shadows = false; + s.biome_blend = 1; + s.cutout_leaves = false; + s.improved_transparency = false; + s.mipmap_levels = 2; + s.weather_radius = 5; + s.cloud_range = 64; + s.entity_distance = 0.75; + } + "fancy" | "fabulous" => { + s.clouds = "true".into(); + s.particles = 0; + s.entity_shadows = true; + s.biome_blend = 2; + s.cutout_leaves = true; + s.improved_transparency = s.graphics_preset == "fabulous"; + s.mipmap_levels = 4; + s.weather_radius = 10; + s.cloud_range = 128; + s.entity_distance = 1.0; + } + _ => {} + } +} + +/// A resource pack entry for the pack screen. +#[derive(Clone, Debug, PartialEq)] +pub struct PackEntry { + pub id: String, + pub title: Text, + pub description: Text, + pub compatible: bool, + /// Built-in packs that cannot be removed (vanilla). + pub required: bool, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Page { + Main, + Video, + Sound, + Controls, + KeyBinds, + Mouse, + Chat, + Accessibility, + Language, + Font, + Packs, +} +#[derive(Clone, Debug, PartialEq)] +enum Act { + None, + Push(Page), + Done, + Cycle(Opt), + Key(&'static str), + ResetKey(&'static str), + ResetKeys, + OpenPackFolder, +} +enum WKind { + Button { label: Text, active: bool, act: Act }, + Slider { label: Text, value: f32, opt: Opt }, + Text { text: Text, color: u32, centered: bool }, + LanguageRow { label: Text, selected: bool, code: String }, + PackRow { pack: PackEntry, selected: bool, index: usize, count: usize }, +} +struct Widget { + x: f32, + y: f32, + w: f32, + h: f32, + kind: WKind, + /// Scrolls with the list (clipped to the list area). + list: bool, +} +/// What the game must do after an interaction. +#[derive(Clone, Debug, PartialEq)] +pub enum Event { + /// Close the options screens (back to the pause menu or title). + Close, + /// Settings changed: apply them. + Changed, + /// The language changed (reload translations). + Language(String), + /// The pack selection changed (reload resources). + Packs(Vec), + OpenPackFolder, +} +pub struct OptionsUi { + pub stack: Vec, + scroll: f32, + dragging: Option, + /// Key Binds: the mapping waiting for a key. + pub selected_key: Option<&'static str>, + pub languages: Vec, + language_choice: Option, + language_search: ui::EditBox, + /// Packs: (available, selected top-first). + pub available: Vec, + pub selected: Vec, + packs_changed: bool, + pub in_world: bool, + /// Scroll the selected language into the middle on the next layout. + center_language: bool, +} +impl Default for OptionsUi { + fn default() -> Self { + let mut search = ui::EditBox::new(0.0, 0.0, 200.0, 15.0); + search.max_length = 32; + Self { + stack: vec![Page::Main], + scroll: 0.0, + dragging: None, + selected_key: None, + languages: Vec::new(), + language_choice: None, + language_search: search, + available: Vec::new(), + selected: Vec::new(), + packs_changed: false, + in_world: false, + center_language: false, + } + } +} +fn button(x: f32, y: f32, w: f32, label: Text, act: Act) -> Widget { + Widget { x, y, w, h: 20.0, kind: WKind::Button { label, active: true, act }, list: false } +} +fn inactive(mut w: Widget) -> Widget { + if let WKind::Button { active, .. } = &mut w.kind { + *active = false; + } + w +} +fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget { + match opt.kind(s) { + Kind::Slider(v) => Widget { x, y, w, h: 20.0, kind: WKind::Slider { label: opt.label(s), value: v, opt }, list: false }, + Kind::Cycle => button(x, y, w, opt.label(s), Act::Cycle(opt)), + } +} +/// Rows of an OptionsList: (big?, options) or a header. +enum Row { + Big(Opt), + Pair(Opt, Option), + Header(&'static str), + Buttons(Widget, Option), +} +fn pairs(opts: &[Opt]) -> Vec { + opts.chunks(2).map(|c| Row::Pair(c[0], c.get(1).copied())).collect() +} +impl OptionsUi { + pub fn page(&self) -> Page { + *self.stack.last().unwrap_or(&Page::Main) + } + /// Jump straight to a page (control socket / tests). + pub fn show(&mut self, page: Page) { + if page != Page::Main { + self.push(page); + } + } + pub fn open(&mut self, in_world: bool) { + self.stack = vec![Page::Main]; + self.scroll = 0.0; + self.in_world = in_world; + self.selected_key = None; + } + fn push(&mut self, page: Page) { + self.stack.push(page); + self.scroll = 0.0; + if page == Page::Language { + self.language_choice = None; + self.language_search.set_value(""); + self.center_language = true; + } + if page == Page::Packs { + self.packs_changed = false; + } + } + fn title(page: Page) -> &'static str { + match page { + Page::Main => "options.title", + Page::Video => "options.videoTitle", + Page::Sound => "options.sounds.title", + Page::Controls => "controls.title", + Page::KeyBinds => "controls.keybinds.title", + Page::Mouse => "options.mouse_settings.title", + Page::Chat => "options.chat.title", + Page::Accessibility => "options.accessibility.title", + Page::Language => "options.language.title", + Page::Font => "options.font.title", + Page::Packs => "resourcePack.title", + } + } + fn list_rows(&self, s: &Settings) -> Vec { + match self.page() { + Page::Video => { + let mut rows = vec![Row::Header("options.video.display.header")]; + rows.extend(pairs(&[Opt::MaxFps, Opt::Vsync, Opt::InactivityFps, Opt::GuiScale, Opt::Fullscreen, Opt::Gamma])); + rows.push(Row::Header("options.video.quality.header")); + rows.push(Row::Big(Opt::Preset)); + rows.extend(pairs(&[ + Opt::BiomeBlend, + Opt::RenderDistance, + Opt::ChunkBuilder, + Opt::SimulationDistance, + Opt::SmoothLighting, + Opt::Clouds, + Opt::Particles, + Opt::Mipmaps, + Opt::EntityShadows, + Opt::EntityDistance, + Opt::MenuBlur, + Opt::CloudRange, + Opt::CutoutLeaves, + Opt::ImprovedTransparency, + Opt::WeatherRadius, + ])); + rows.push(Row::Header("options.video.preferences.header")); + rows.extend(pairs(&[Opt::Autosave, Opt::Vignette, Opt::AttackIndicator, Opt::ChunkFade])); + rows + } + Page::Sound => { + let mut rows = vec![Row::Big(Opt::Volume(0))]; + let others: Vec = (1..SOUND_SOURCES.len()).map(Opt::Volume).collect(); + rows.extend(pairs(&others)); + rows + } + Page::Controls => { + let mut rows = vec![Row::Buttons( + button(0.0, 0.0, 150.0, tr("options.mouse_settings"), Act::Push(Page::Mouse)), + Some(button(0.0, 0.0, 150.0, tr("controls.keybinds"), Act::Push(Page::KeyBinds))), + )]; + rows.extend(pairs(&[Opt::ToggleCrouch, Opt::ToggleSprint, Opt::AutoJump])); + rows + } + Page::Mouse => pairs(&[Opt::Sensitivity, Opt::WheelSensitivity, Opt::DiscreteScroll, Opt::InvertY]), + Page::Chat => pairs(&[ + Opt::ChatVisibility, + Opt::ChatColors, + Opt::ChatLinks, + Opt::ChatOpacity, + Opt::TextBackgroundOpacity, + Opt::ChatScale, + Opt::ChatLineSpacing, + Opt::ChatWidth, + Opt::ChatHeightFocused, + Opt::ChatHeightUnfocused, + Opt::AutoSuggestions, + Opt::ReducedDebugInfo, + ]), + Page::Accessibility => pairs(&[ + Opt::HighContrast, + Opt::MenuBlur, + Opt::TextBackgroundOpacity, + Opt::ChatOpacity, + Opt::ChatLineSpacing, + Opt::ViewBobbing, + Opt::ToggleCrouch, + Opt::ToggleSprint, + Opt::AutoJump, + ]), + Page::Font => pairs(&[Opt::ForceUnicode, Opt::JapaneseGlyphs]), + _ => { + let _ = s; + Vec::new() + } + } + } + /// Build every widget of the current page. + fn layout(&mut self, s: &Settings, atlas: &HudAtlas, w: f32, h: f32) -> (Vec, f32, f32, f32) { + let mut out = Vec::new(); + let page = self.page(); + let cx = (w / 2.0).floor(); + let done = |y: f32| button(cx - 100.0, y, 200.0, tr("gui.done"), Act::Done); + // (list top, list bottom, content height) + let (mut top, mut bottom, mut content) = (33.0, h - 33.0, 0.0); + match page { + Page::Main => { + out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr("options.title"), color: u32::MAX, centered: true } , list: false }); + out.push(option_widget(s, Opt::Fov, cx - 154.0, 29.0, 150.0)); + out.push(inactive(button(cx + 4.0, 29.0, 150.0, tr("options.online"), Act::None))); + let entries = [ + ("options.skinCustomisation", None), + ("options.sounds", Some(Page::Sound)), + ("options.video", Some(Page::Video)), + ("options.controls", Some(Page::Controls)), + ("options.language", Some(Page::Language)), + ("options.chat", Some(Page::Chat)), + ("options.resourcepack", Some(Page::Packs)), + ("options.accessibility", Some(Page::Accessibility)), + ("options.telemetry", None), + ("options.credits_and_attribution", None), + ]; + let gy = (61.0 + 30.0f32).min(h - 33.0 - 120.0); + for (i, (key, page)) in entries.iter().enumerate() { + let x = cx - 158.0 + 4.0 + (i % 2) as f32 * 158.0; + let y = gy + (i / 2) as f32 * 24.0; + let b = button(x, y, 150.0, tr(key), page.map_or(Act::None, Act::Push)); + out.push(if page.is_some() { b } else { inactive(b) }); + } + out.push(done(h - 27.0)); + top = 0.0; + bottom = 0.0; + } + Page::KeyBinds => { + out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); + let mut mappings: Vec<(&str, &str)> = MAPPINGS.iter().map(|(n, _, c)| (*n, *c)).collect(); + mappings.sort_by(|a, b| { + let ca = CATEGORIES.iter().position(|c| *c == a.1).unwrap_or(99); + let cb = CATEGORIES.iter().position(|c| *c == b.1).unwrap_or(99); + ca.cmp(&cb).then_with(|| lang::get(a.0).cmp(&lang::get(b.0))) + }); + let row_left = cx - 170.0; + let scrollbar_x = row_left + 340.0 + 6.0 + 2.0; + let list_start = out.len(); + let mut y = top + 2.0 - self.scroll; + let mut last_category = ""; + for (name, category) in mappings { + if category != last_category { + last_category = category; + let label = Text::translate(&format!("key.categories.{category}"), &[]).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); + out.push(Widget { x: 0.0, y: y + 7.0, w, h: 9.0, kind: WKind::Text { text: label, color: u32::MAX, centered: true } , list: false }); + y += 20.0; + } + out.push(Widget { x: row_left + 2.0, y: y + 6.0, w: 200.0, h: 9.0, kind: WKind::Text { text: tr(name), color: u32::MAX, centered: false } , list: false }); + let key = s.keys.get(name).to_owned(); + let mut message = keybinds::display_name(&key); + let conflicts = s.keys.conflicts(name); + if !conflicts.is_empty() { + message = Text::literal("[ ").append(message.with_color(text::WHITE)).append(" ]").with_color(text::YELLOW); + } + if self.selected_key == Some(name) { + message = Text::literal("> ").append(message.with_style(&Style { color: Some(text::WHITE), underlined: Some(true), ..Style::default() })).append(" <").with_color(text::YELLOW); + } + let reset_x = scrollbar_x - 50.0 - 10.0; + let change_x = reset_x - 5.0 - 75.0; + let name_static = MAPPINGS.iter().find(|m| m.0 == name).map_or("", |m| m.0); + out.push(button(change_x, y, 75.0, message, Act::Key(name_static))); + if !conflicts.is_empty() { + out.push(Widget { x: change_x - 6.0, y: y + 1.0, w: 3.0, h: 18.0, kind: WKind::Text { text: Text::empty(), color: rgba(255, 255, 0, 255), centered: false } , list: false }); + } + let reset = button(reset_x, y, 50.0, tr("controls.reset"), Act::ResetKey(name_static)); + out.push(if s.keys.is_default(name) { inactive(reset) } else { reset }); + y += 20.0; + } + content = y + self.scroll - top + 2.0; + out[list_start..].iter_mut().for_each(|w| w.list = true); + out.push(button(cx - 154.0, h - 27.0, 150.0, tr("controls.resetAll"), Act::ResetKeys)); + out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); + } + Page::Language => { + top = 36.0; + bottom = h - 53.0; + out.push(Widget { x: 0.0, y: 4.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); + self.language_search.x = cx - 100.0; + self.language_search.y = 17.0; + let query = self.language_search.value.to_lowercase(); + let current = self.language_choice.clone().unwrap_or_else(|| s.language.clone()); + if std::mem::take(&mut self.center_language) + && let Some(i) = self.languages.iter().position(|l| l.code == current) + { + // AbstractSelectionList.centerScrollOn. + self.scroll = (i as f32 * 18.0 + 9.0 - (bottom - top) / 2.0).max(0.0); + } + let list_start = out.len(); + let mut y = top + 2.0 - self.scroll; + for l in &self.languages { + if !query.is_empty() && !l.label().to_lowercase().contains(&query) && !l.code.contains(&query) { + continue; + } + out.push(Widget { x: cx - 110.0, y, w: 220.0, h: 18.0, kind: WKind::LanguageRow { label: Text::literal(l.label()), selected: l.code == current, code: l.code.clone() } , list: false }); + y += 18.0; + } + content = y + self.scroll - top + 2.0; + out[list_start..].iter_mut().for_each(|w| w.list = true); + out.push(Widget { x: 0.0, y: h - 45.0, w, h: 9.0, kind: WKind::Text { text: tr("options.languageAccuracyWarning"), color: rgba(0xBA, 0xBA, 0xBA, 255), centered: true } , list: false }); + out.push(button(cx - 154.0, h - 28.0, 150.0, tr("options.font"), Act::Push(Page::Font))); + out.push(button(cx + 4.0, h - 28.0, 150.0, tr("gui.done"), Act::Done)); + } + Page::Packs => { + top = 47.0; + bottom = h - 33.0; + out.push(Widget { x: 0.0, y: 8.0, w, h: 9.0, kind: WKind::Text { text: tr("resourcePack.title"), color: u32::MAX, centered: true } , list: false }); + out.push(Widget { x: 0.0, y: 20.0, w, h: 9.0, kind: WKind::Text { text: tr("pack.dropInfo").with_color(text::GRAY), color: u32::MAX, centered: true } , list: false }); + let lists = [(false, cx - 4.0 - 200.0), (true, cx + 4.0)]; + let list_start = out.len(); + for (selected, lx) in lists { + let entries = if selected { &self.selected } else { &self.available }; + let header = tr(if selected { "pack.selected.title" } else { "pack.available.title" }).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); + out.push(Widget { x: lx, y: top + 4.0, w: 200.0, h: 9.0, kind: WKind::Text { text: header, color: u32::MAX, centered: true } , list: false }); + let mut y = top + 17.0 - self.scroll; + for (i, p) in entries.iter().enumerate() { + out.push(Widget { x: lx, y, w: 200.0, h: 36.0, kind: WKind::PackRow { pack: p.clone(), selected, index: i, count: entries.len() } , list: false }); + y += 36.0; + } + content = f32::max(content, y + self.scroll - top + 4.0); + } + out[list_start..].iter_mut().for_each(|w| w.list = true); + out.push(button(cx - 154.0, h - 27.0, 150.0, tr("pack.openFolder"), Act::OpenPackFolder)); + out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); + } + _ => { + out.push(Widget { x: 0.0, y: 12.0, w, h: 9.0, kind: WKind::Text { text: tr(Self::title(page)), color: u32::MAX, centered: true } , list: false }); + let list_start = out.len(); + let mut y = top + 2.0 - self.scroll; + for row in self.list_rows(s) { + match row { + Row::Header(key) => { + let padding = if y + self.scroll <= top + 2.0 { 0.0 } else { 18.0 }; + let label = tr(key).with_style(&Style { bold: Some(true), underlined: Some(true), ..Style::default() }); + out.push(Widget { x: 0.0, y: y + 2.0 + padding + 4.0, w, h: 9.0, kind: WKind::Text { text: label, color: u32::MAX, centered: true } , list: false }); + y += padding + 18.0; + } + Row::Big(opt) => { + out.push(option_widget(s, opt, cx - 155.0, y + 2.0, 310.0)); + y += 25.0; + } + Row::Pair(a, b) => { + out.push(option_widget(s, a, cx - 155.0, y + 2.0, 150.0)); + if let Some(b) = b { + out.push(option_widget(s, b, cx + 5.0, y + 2.0, 150.0)); + } + y += 25.0; + } + Row::Buttons(mut a, b) => { + a.x = cx - 155.0; + a.y = y + 2.0; + out.push(a); + if let Some(mut b) = b { + b.x = cx + 5.0; + b.y = y + 2.0; + out.push(b); + } + y += 25.0; + } + } + } + content = y + self.scroll - top + 2.0; + out[list_start..].iter_mut().for_each(|w| w.list = true); + out.push(done(h - 27.0)); + } + } + let _ = atlas; + (out, top, bottom, content) + } + fn clamp_scroll(&mut self, top: f32, bottom: f32, content: f32) { + let max = (content - (bottom - top)).max(0.0); + self.scroll = self.scroll.clamp(0.0, max); + } + pub fn draw(&mut self, s: &Settings, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { + let (w, h) = (batch.width, batch.height); + let (widgets, top, bottom, content) = self.layout(s, atlas, w, h); + self.clamp_scroll(top, bottom, content); + let in_world = self.in_world; + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, in_world); + let list = bottom > top; + if list { + ui::list_background(batch, atlas, top, bottom, in_world); + } + let visible = |wd: &Widget| !wd.list || (wd.y >= top && wd.y + wd.h <= bottom); + let mut tooltip = None; + for wd in &widgets { + if !visible(wd) { + continue; + } + let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, wd.h) && (!wd.list || cursor.1 >= top && cursor.1 < bottom); + match &wd.kind { + WKind::Button { label, active, act } => { + ui::button(batch, atlas, wd.x, wd.y, wd.w, wd.h, label, *active, hover); + if hover && let Act::Key(name) = act { + let conflicts = s.keys.conflicts(name); + if !conflicts.is_empty() { + let names = conflicts.iter().map(|c| lang::get(c)).collect::>().join(", "); + let full = Text::translate("controls.keybinds.duplicateKeybinds", &[Text::literal(names)]); + tooltip = Some(full.plain().split('\n').map(|l| Text::literal(l.to_owned())).collect::>()); + } + } + } + WKind::Slider { label, value, opt } => { + let dragging = self.dragging == Some(*opt); + ui::slider(batch, atlas, wd.x, wd.y, wd.w, label, *value, hover || dragging, true); + } + WKind::Text { text, color, centered } => { + if text.is_empty() { + batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, *color); + } else if *centered { + let tw = atlas.font.width_text(text); + batch.text_styled(atlas, text, wd.x + ((wd.w - tw) / 2.0).floor(), wd.y, *color, true); + } else { + batch.text_styled(atlas, text, wd.x, wd.y, *color, true); + } + } + WKind::LanguageRow { label, selected, .. } => { + if *selected { + batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, u32::MAX); + batch.fill(atlas, wd.x + 1.0, wd.y + 1.0, wd.w - 2.0, wd.h - 2.0, rgba(0, 0, 0, 255)); + } + let tw = atlas.font.width_text(label); + batch.text_styled(atlas, label, wd.x + ((wd.w - tw) / 2.0).floor(), wd.y + 2.0 + 7.0 - 4.0, u32::MAX, true); + } + WKind::PackRow { pack, selected, index, count } => { + if hover { + batch.fill(atlas, wd.x, wd.y, wd.w, wd.h, rgba(255, 255, 255, 255)); + batch.fill(atlas, wd.x + 1.0, wd.y + 1.0, wd.w - 2.0, wd.h - 2.0, rgba(0, 0, 0, 255)); + } + batch.sprite_scaled(atlas, "misc/unknown_pack", wd.x + 2.0, wd.y + 2.0, 32.0, 32.0, u32::MAX); + let title_color = if pack.compatible { u32::MAX } else { rgba(255, 85, 85, 255) }; + batch.text_styled(atlas, &pack.title, wd.x + 36.0, wd.y + 3.0, title_color, true); + for (i, line) in atlas.font.split(&pack.description, 157.0).iter().take(2).enumerate() { + batch.text_styled(atlas, line, wd.x + 36.0, wd.y + 14.0 + i as f32 * 9.0, rgba(128, 128, 128, 255), true); + } + if hover && cursor.0 < wd.x + 34.0 { + // TransferableSelectionList arrows over the icon. + batch.fill(atlas, wd.x + 2.0, wd.y + 2.0, 32.0, 32.0, rgba(160, 160, 160, 136)); + let sprite_dir = if *selected { "unselect" } else { "select" }; + let left = cursor.0 < wd.x + 18.0; + let name = format!("gui/sprites/transferable_list/{sprite_dir}{}", if left || !*selected { "_highlighted" } else { "" }); + batch.sprite(atlas, &name, wd.x + 2.0, wd.y + 2.0); + if *selected { + if *index > 0 { + batch.sprite(atlas, "gui/sprites/transferable_list/move_up", wd.x + 2.0, wd.y + 2.0); + } + if index + 1 < *count { + batch.sprite(atlas, "gui/sprites/transferable_list/move_down", wd.x + 2.0, wd.y + 2.0); + } + } + } + } + } + } + if list { + ui::separators(batch, atlas, top, bottom, in_world); + let sx = match self.page() { + Page::KeyBinds => (w / 2.0).floor() + 170.0 + 8.0, + Page::Language => (w / 2.0).floor() + 110.0 + 8.0, + _ => (w / 2.0).floor() + 155.0 + 8.0, + }; + ui::scrollbar(batch, atlas, sx, top, bottom, content, self.scroll); + } + if self.page() == Page::Language { + let mut search = self.language_search.clone(); + search.draw(batch, atlas, None); + if search.value.is_empty() { + batch.text_styled(atlas, &tr("gui.language.search").with_color(text::GRAY).italic(), search.text_x(), search.text_y(), u32::MAX, true); + } + self.language_search = search; + } + if let Some(lines) = tooltip { + ui::tooltip(batch, atlas, &lines, cursor); + } + } + /// Mouse press/drag. Returns events for the game. + pub fn click(&mut self, s: &mut Settings, atlas: &HudAtlas, x: f32, y: f32, size: (f32, f32), drag: bool, right: bool) -> Vec { + let (widgets, top, bottom, _) = self.layout(s, atlas, size.0, size.1); + let mut events = Vec::new(); + if drag { + if let Some(opt) = self.dragging + && let Some(wd) = widgets.iter().find(|wd| matches!(&wd.kind, WKind::Slider { opt: o, .. } if *o == opt)) + { + opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); + events.push(Event::Changed); + } + return events; + } + // Key Binds: a mouse button pressed while waiting binds it. + if let Some(name) = self.selected_key.take() { + let button = if right { "key.mouse.right" } else { "key.mouse.left" }; + s.keys.set(name, button); + events.push(Event::Changed); + return events; + } + for wd in widgets { + if !ui::hovered((x, y), wd.x, wd.y, wd.w, wd.h) { + continue; + } + if wd.list && (y < top || y >= bottom || wd.y < top || wd.y + wd.h > bottom) { + continue; + } + match wd.kind { + WKind::Button { active: true, act, .. } => match act { + Act::Push(p) => self.push(p), + Act::Done => events.extend(self.back(s)), + Act::Cycle(opt) => { + opt.cycle(s, right); + if opt == Opt::Preset { + apply_preset(s); + } + events.push(Event::Changed); + } + Act::Key(name) => self.selected_key = Some(name), + Act::ResetKey(name) => { + s.keys.set(name, KeyBinds::default_of(name)); + events.push(Event::Changed); + } + Act::ResetKeys => { + s.keys.reset_all(); + events.push(Event::Changed); + } + Act::OpenPackFolder => events.push(Event::OpenPackFolder), + Act::None => {} + }, + WKind::Slider { opt, .. } => { + self.dragging = Some(opt); + opt.set_slider(s, ui::slider_value(wd.x, wd.w, x)); + if opt == Opt::Preset { + apply_preset(s); + } + events.push(Event::Changed); + } + WKind::LanguageRow { code, .. } => { + if self.language_choice.as_deref() == Some(code.as_str()) { + events.extend(self.back(s)); + } else { + self.language_choice = Some(code); + } + } + WKind::PackRow { pack, selected, index, .. } => { + if pack.required { + continue; + } + let on_icon = x < wd.x + 34.0; + if selected && on_icon && x >= wd.x + 18.0 { + // Right half of the icon: move up (top) or down (bottom). + let up = y < wd.y + 18.0; + let target = if up { index.checked_sub(1) } else { Some(index + 1) }; + if let Some(t) = target.filter(|t| *t < self.selected.len() && !self.selected[*t].required) { + self.selected.swap(index, t); + self.packs_changed = true; + } + } else if selected { + let p = self.selected.remove(index); + self.available.insert(0, p); + self.packs_changed = true; + } else { + let p = self.available.remove(index); + self.selected.insert(0, p); + self.packs_changed = true; + } + } + _ => {} + } + break; + } + events + } + pub fn release(&mut self) { + self.dragging = None; + } + pub fn scroll(&mut self, amount: f32) { + self.scroll -= amount * 18.0; + } + /// Escape or Done: leave the current page, applying page results. + pub fn back(&mut self, s: &mut Settings) -> Vec { + let mut events = Vec::new(); + let page = self.stack.pop().unwrap_or(Page::Main); + self.scroll = 0.0; + self.dragging = None; + self.selected_key = None; + match page { + Page::Language => { + if let Some(code) = self.language_choice.take() + && code != s.language + { + s.language = code.clone(); + events.push(Event::Language(code)); + } + } + Page::Packs if self.packs_changed => { + let mut ids: Vec = self.selected.iter().rev().map(|p| p.id.clone()).collect(); + if !ids.contains(&"vanilla".to_owned()) { + ids.insert(0, "vanilla".into()); + } + s.resource_packs = ids.clone(); + events.push(Event::Packs(ids)); + } + _ => {} + } + events.push(Event::Changed); + if self.stack.is_empty() { + events.push(Event::Close); + } + events + } + /// Typed text (the language search box). + pub fn type_text(&mut self, text: &str) { + if self.page() == Page::Language { + self.language_search.insert_text(text); + self.scroll = 0.0; + } + } + /// Keys while the options are open. Returns events; `handled` false lets + /// Escape fall through. + pub fn key(&mut self, s: &mut Settings, key: winit::keyboard::KeyCode, text: Option<&str>) -> Vec { + use winit::keyboard::KeyCode as K; + if let Some(name) = self.selected_key.take() { + // KeyBindsScreen.keyPressed: Escape unbinds. + let value = if key == K::Escape { "key.keyboard.unknown".to_owned() } else { keybinds::key_name(key).unwrap_or("key.keyboard.unknown").to_owned() }; + s.keys.set(name, &value); + return vec![Event::Changed]; + } + if key == K::Escape { + return self.back(s); + } + if self.page() == Page::Language { + if !self.language_search.key(key, false, false) + && let Some(t) = text + { + let typed: String = t.chars().filter(|c| !c.is_control()).collect(); + if !typed.is_empty() { + self.language_search.insert_text(&typed); + } + } + self.scroll = 0.0; + } + Vec::new() + } +} diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs new file mode 100644 index 000000000..61a1e16f3 --- /dev/null +++ b/crates/horizon-client/src/packs.rs @@ -0,0 +1,284 @@ +//! Resource packs (PackRepository / FolderRepositorySource): discovery of +//! folder and zip packs in `resourcepacks/` plus the built-in Programmer Art +//! and High Contrast packs, `pack.mcmeta` metadata and format compatibility, +//! and an overlay resource root that layers the enabled packs over the +//! vanilla resources (later packs win), so every loader sees one tree. +use crate::{text::Text, zip::Zip}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, io, + path::{Path, PathBuf}, +}; + +/// SharedConstants resource pack format of 26.3 (major, minor). +pub const RESOURCE_FORMAT: (i64, i64) = (97, 1); + +#[derive(Clone, Debug)] +pub enum Source { + Dir(PathBuf), + Zip(PathBuf), +} +#[derive(Clone, Debug)] +pub struct Pack { + /// `file/` for user packs, the bare name for built-in ones. + pub id: String, + pub source: Source, + pub title: Text, + pub description: Text, + pub compatible: bool, +} +/// A minimal text component from JSON (strings, `text`, `translate`, arrays). +pub fn component(v: &serde_json::Value) -> Text { + match v { + serde_json::Value::String(s) => Text::legacy(s), + serde_json::Value::Array(a) => { + let mut t = Text::empty(); + for e in a { + t.push(component(e)); + } + t + } + serde_json::Value::Object(o) => { + let mut t = if let Some(s) = o.get("text").and_then(|s| s.as_str()) { + Text::legacy(s) + } else if let Some(k) = o.get("translate").and_then(|s| s.as_str()) { + let args: Vec = o.get("with").and_then(|w| w.as_array()).map(|a| a.iter().map(component).collect()).unwrap_or_default(); + Text::translate(k, &args) + } else { + Text::empty() + }; + if let Some(extra) = o.get("extra") { + t.push(component(extra)); + } + if let Some(c) = o.get("color").and_then(|c| c.as_str()) { + let rgb = crate::text::named_color(c).or_else(|| c.strip_prefix('#').and_then(|h| u32::from_str_radix(h, 16).ok())); + if let Some(rgb) = rgb { + t = t.with_color(rgb); + } + } + t + } + serde_json::Value::Number(n) => Text::literal(n.to_string()), + serde_json::Value::Bool(b) => Text::literal(b.to_string()), + serde_json::Value::Null => Text::empty(), + } +} +fn format_of(v: &serde_json::Value) -> Option<(i64, i64)> { + match v { + serde_json::Value::Number(n) => Some((n.as_i64()?, 0)), + serde_json::Value::Array(a) => Some((a.first()?.as_i64()?, a.get(1).and_then(|m| m.as_i64()).unwrap_or(0))), + _ => None, + } +} +/// PackCompatibility: inside [min_format, max_format] (or the legacy +/// `pack_format`/`supported_formats`). +pub fn compatible(meta: &serde_json::Value) -> bool { + let pack = &meta["pack"]; + let current = RESOURCE_FORMAT; + if let (Some(min), Some(max)) = (format_of(&pack["min_format"]), format_of(&pack["max_format"])) { + return min <= current && current <= (max.0, max.1.max(if max.1 == 0 { i64::MAX } else { max.1 })); + } + if let Some(range) = pack["supported_formats"].as_array() + && let (Some(lo), Some(hi)) = (range.first().and_then(|v| v.as_i64()), range.get(1).and_then(|v| v.as_i64())) + { + return lo <= current.0 && current.0 <= hi; + } + format_of(&pack["pack_format"]).is_some_and(|f| f.0 == current.0) +} +fn read_meta(source: &Source) -> Option { + let bytes = match source { + Source::Dir(d) => fs::read(d.join("pack.mcmeta")).ok()?, + Source::Zip(z) => Zip::open(z).ok()?.read("pack.mcmeta").ok()?, + }; + serde_json::from_slice(&bytes).ok() +} +fn pack(id: String, title: Text, source: Source) -> Option { + let meta = read_meta(&source)?; + Some(Pack { id, title, description: component(&meta["pack"]["description"]), compatible: compatible(&meta), source }) +} +/// Built-in and `resourcepacks/` packs (vanilla itself excluded), sorted like +/// the pack screen (built-ins first, then by name). +pub fn discover(resources: &Path, packs_dir: &Path) -> Vec { + let mut out = Vec::new(); + for (id, key) in [("programmer_art", "resourcePack.programmer_art.name"), ("high_contrast", "resourcePack.high_contrast.name")] { + let z = resources.join(format!("assets/minecraft/resourcepacks/{id}.zip")); + if z.exists() + && let Some(p) = pack(id.into(), Text::translate(key, &[]), Source::Zip(z)) + { + out.push(p); + } + } + let mut user: Vec = fs::read_dir(packs_dir) + .into_iter() + .flatten() + .flatten() + .filter_map(|e| { + let path = e.path(); + let name = e.file_name().to_string_lossy().into_owned(); + let source = if path.is_dir() { + Source::Dir(path) + } else if name.ends_with(".zip") { + Source::Zip(path) + } else { + return None; + }; + pack(format!("file/{name}"), Text::literal(name), source) + }) + .collect(); + user.sort_by(|a, b| a.id.cmp(&b.id)); + out.extend(user); + out +} +/// Files a pack provides under `assets/`. +fn pack_files(source: &Source) -> io::Result>> { + let mut out = BTreeMap::new(); + match source { + Source::Dir(d) => { + let mut stack = vec![d.join("assets")]; + while let Some(dir) = stack.pop() { + let Ok(entries) = fs::read_dir(&dir) else { continue }; + for e in entries.flatten() { + let p = e.path(); + if p.is_dir() { + stack.push(p); + } else if let Ok(rel) = p.strip_prefix(d) { + out.insert(rel.to_string_lossy().replace('\\', "/"), Some(p.clone())); + } + } + } + } + Source::Zip(z) => { + for name in Zip::open(z)?.names() { + if name.starts_with("assets/") { + out.insert(name.to_owned(), None); + } + } + } + } + Ok(out) +} +#[cfg(unix)] +fn link(target: &Path, at: &Path) -> io::Result<()> { + std::os::unix::fs::symlink(target, at) +} +#[cfg(not(unix))] +fn link(target: &Path, at: &Path) -> io::Result<()> { + if target.is_dir() { Ok(()) } else { fs::copy(target, at).map(|_| ()) } +} +/// Build `out` as `vanilla` with the packs' files layered on top (packs in +/// load order, last wins). Untouched directories are symlinks into vanilla. +pub fn build_overlay(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()> { + if out.exists() { + fs::remove_dir_all(out)?; + } + fs::create_dir_all(out)?; + // Final owner of every overridden file. + let mut files: BTreeMap)> = BTreeMap::new(); + for (i, p) in packs.iter().enumerate() { + for (name, path) in pack_files(&p.source)? { + files.insert(name, (i, path)); + } + } + let touched_dirs: BTreeSet = files + .keys() + .flat_map(|f| { + let parts: Vec<&str> = f.split('/').collect(); + (1..parts.len()).map(move |n| parts[..n].join("/")) + }) + .collect(); + let zips: Vec> = packs.iter().map(|p| if let Source::Zip(z) = &p.source { Zip::open(z).ok() } else { None }).collect(); + fn mirror(rel: &str, vanilla: &Path, out: &Path, touched: &BTreeSet, files: &BTreeMap)>, zips: &[Option]) -> io::Result<()> { + let src = if rel.is_empty() { vanilla.to_path_buf() } else { vanilla.join(rel) }; + let dst = if rel.is_empty() { out.to_path_buf() } else { out.join(rel) }; + fs::create_dir_all(&dst)?; + let mut names: BTreeSet = BTreeSet::new(); + if let Ok(entries) = fs::read_dir(&src) { + names.extend(entries.flatten().map(|e| e.file_name().to_string_lossy().into_owned())); + } + let prefix = if rel.is_empty() { String::new() } else { format!("{rel}/") }; + for f in files.keys().filter_map(|f| f.strip_prefix(&prefix)) { + names.insert(f.split('/').next().unwrap_or("").to_owned()); + } + for name in names { + let child = format!("{prefix}{name}"); + if let Some((owner, path)) = files.get(&child) { + let target = out.join(&child); + match path { + Some(p) => link(p, &target)?, + None => { + if let Some(Some(z)) = zips.get(*owner) { + fs::write(&target, z.read(&child)?)?; + } + } + } + } else if touched.contains(&child) { + mirror(&child, vanilla, out, touched, files, zips)?; + } else { + link(&vanilla.join(&child), &out.join(&child))?; + } + } + Ok(()) + } + mirror("", vanilla, out, &touched_dirs, &files, &zips) +} +/// The packs to apply for an options.txt `resourcePacks` list (bottom first). +pub fn enabled(all: &[Pack], ids: &[String]) -> Vec { + ids.iter().filter(|id| *id != "vanilla").filter_map(|id| all.iter().find(|p| &p.id == id).cloned()).collect() +} +/// Resource root for a pack selection: vanilla itself when no pack is on. +pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf { + if packs.is_empty() { + return vanilla.to_path_buf(); + } + let key: String = packs.iter().map(|p| p.id.as_str()).collect::>().join("|"); + let hash = key.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)); + let out = cache.join(format!("{hash:016x}")); + match build_overlay(vanilla, packs, &out) { + Ok(()) => out, + Err(e) => { + eprintln!("Horizon: resource packs not applied: {e}"); + vanilla.to_path_buf() + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn compatibility_ranges() { + let v = |s: &str| serde_json::from_str::(s).unwrap(); + assert!(compatible(&v(r#"{"pack":{"min_format":97,"max_format":98}}"#))); + assert!(compatible(&v(r#"{"pack":{"min_format":[97,0],"max_format":[97,1]}}"#))); + assert!(!compatible(&v(r#"{"pack":{"min_format":[97,2],"max_format":99}}"#))); + assert!(compatible(&v(r#"{"pack":{"pack_format":97}}"#))); + assert!(!compatible(&v(r#"{"pack":{"pack_format":34}}"#))); + assert_eq!(component(&v(r#"["a",{"text":"b","color":"red"}]"#)).plain(), "ab"); + } + #[test] + fn overlay_layers_packs_over_vanilla() { + let base = std::env::temp_dir().join(format!("horizon-packs-{}", std::process::id())); + let _ = fs::remove_dir_all(&base); + let vanilla = base.join("vanilla"); + fs::create_dir_all(vanilla.join("assets/minecraft/textures/block")).unwrap(); + fs::create_dir_all(vanilla.join("assets/minecraft/lang")).unwrap(); + fs::write(vanilla.join("assets/minecraft/textures/block/stone.png"), b"vanilla").unwrap(); + fs::write(vanilla.join("assets/minecraft/textures/block/dirt.png"), b"vanilla dirt").unwrap(); + fs::write(vanilla.join("assets/minecraft/lang/en_us.json"), b"{}").unwrap(); + fs::write(vanilla.join("facts.json"), b"[]").unwrap(); + let pack_dir = base.join("packs/Mine"); + fs::create_dir_all(pack_dir.join("assets/minecraft/textures/block")).unwrap(); + fs::write(pack_dir.join("pack.mcmeta"), br#"{"pack":{"description":"mine","pack_format":97}}"#).unwrap(); + fs::write(pack_dir.join("assets/minecraft/textures/block/stone.png"), b"pack").unwrap(); + let packs = discover(&vanilla, &base.join("packs")); + assert_eq!(packs.len(), 1); + assert_eq!(packs[0].id, "file/Mine"); + let out = base.join("overlay"); + build_overlay(&vanilla, &packs, &out).unwrap(); + assert_eq!(fs::read(out.join("assets/minecraft/textures/block/stone.png")).unwrap(), b"pack"); + assert_eq!(fs::read(out.join("assets/minecraft/textures/block/dirt.png")).unwrap(), b"vanilla dirt"); + assert_eq!(fs::read(out.join("assets/minecraft/lang/en_us.json")).unwrap(), b"{}"); + assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]"); + let _ = fs::remove_dir_all(base); + } +} diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 55a729382..abb70419f 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -1,128 +1,410 @@ -//! Player settings persisted in `options.txt` with vanilla's keys, and the -//! options screen (sliders and toggles in OptionsScreen's two-column layout). -use crate::hud::{HudAtlas, HudBatch, rgba}; -use std::{fs, path::Path}; +//! Player settings persisted in `options.txt` with vanilla's keys and value +//! encodings (Options.processOptions); lines Horizon does not know are kept. +//! The option screens live in `options_ui`. +use crate::keybinds::KeyBinds; +use std::{collections::BTreeMap, fs, path::Path}; + +/// SoundSource names in vanilla order. +pub const SOUND_SOURCES: [&str; 11] = ["master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient", "voice", "ui"]; + +/// Per-source volumes for the mixer (soundCategory_* except master). +static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); +pub fn set_source_volumes(volumes: [f32; 11]) { + *SOURCE_VOLUMES.write().unwrap_or_else(|e| e.into_inner()) = volumes; +} +/// The SoundSource an event plays on. Vanilla callers pick the source; this +/// follows their conventions by event family. +pub fn sound_source(event: &str) -> usize { + let e = event.trim_start_matches("minecraft:"); + let index = |name: &str| SOUND_SOURCES.iter().position(|n| *n == name).unwrap_or(0); + const HOSTILE: [&str; 24] = [ + "zombie", "skeleton", "creeper", "spider", "cave_spider", "enderman", "witch", "slime", "magma_cube", "blaze", "ghast", "drowned", "husk", "stray", + "phantom", "pillager", "vindicator", "evoker", "ravager", "guardian", "elder_guardian", "silverfish", "zombified_piglin", "wither_skeleton", + ]; + if e.starts_with("music_disc.") { + index("record") + } else if e.starts_with("music.") { + index("music") + } else if e.starts_with("weather.") || e.starts_with("entity.lightning_bolt") { + index("weather") + } else if e.starts_with("block.") { + index("block") + } else if e.starts_with("ambient.") { + index("ambient") + } else if e.starts_with("ui.") { + index("ui") + } else if e.starts_with("entity.player.") || e.starts_with("item.") || e.starts_with("entity.item.") || e.starts_with("entity.experience_orb") || e.starts_with("entity.arrow") { + index("player") + } else if let Some(rest) = e.strip_prefix("entity.") { + let mob = rest.split('.').next().unwrap_or(""); + if HOSTILE.contains(&mob) { index("hostile") } else { index("neutral") } + } else { + index("master") + } +} +/// Volume multiplier of an event's source (master applied separately). +pub fn event_volume(event: &str) -> f32 { + let i = sound_source(event); + if i == 0 { 1.0 } else { SOURCE_VOLUMES.read().unwrap_or_else(|e| e.into_inner())[i] } +} #[derive(Clone, Debug)] pub struct Settings { - /// Degrees, 30..=110 (vanilla stores the slider value). + /// Degrees, 30..=110 (options.txt stores (fov - 70) / 40). pub fov: f32, /// Chunks, 2..=32. pub render_distance: i32, + /// Chunks, 5..=32. + pub simulation_distance: i32, /// 0..1, vanilla default 0.5. pub sensitivity: f32, - /// 0..1. + /// 0..1 (soundCategory_master). pub master_volume: f32, + /// Volumes of every other sound source, indexed like SOUND_SOURCES. + pub volumes: [f32; 11], /// 0 = auto. pub gui_scale: u32, pub view_bobbing: bool, + /// Brightness 0..1 (gamma). + pub gamma: f32, + /// 10..=260 (260 = unlimited). + pub max_fps: u32, + pub vsync: bool, + pub fullscreen: bool, + /// Smooth lighting (ao). + pub smooth_lighting: bool, + /// "false", "fast" or "true" (renderClouds). + pub clouds: String, + pub cloud_range: i32, + /// 0 all, 1 decreased, 2 minimal. + pub particles: u8, + pub entity_distance: f32, + pub entity_shadows: bool, + pub biome_blend: i32, + /// "fast", "fancy", "fabulous" or "custom". + pub graphics_preset: String, + pub mipmap_levels: i32, + pub weather_radius: i32, + pub chunk_fade: f32, + pub vignette: bool, + pub autosave_indicator: bool, + pub cutout_leaves: bool, + pub improved_transparency: bool, + /// 0 off, 1 crosshair, 2 hotbar. + pub attack_indicator: u8, + pub inactivity_fps_limit: String, + pub prioritize_chunk_updates: u8, + pub menu_blur: i32, + pub invert_y: bool, + pub mouse_wheel_sensitivity: f32, + pub discrete_scroll: bool, + pub toggle_crouch: bool, + pub toggle_sprint: bool, + pub auto_jump: bool, + pub language: String, + pub force_unicode: bool, + pub japanese_glyphs: bool, + pub chat_visibility: u8, + pub chat_colors: bool, + pub chat_links: bool, + pub chat_opacity: f32, + pub text_background_opacity: f32, + pub chat_scale: f32, + pub chat_width: f32, + pub chat_height_focused: f32, + pub chat_height_unfocused: f32, + pub chat_line_spacing: f32, + pub auto_suggestions: bool, + pub reduced_debug_info: bool, + pub high_contrast: bool, + pub main_hand_left: bool, + /// Enabled resource packs, bottom first (resourcePacks). + pub resource_packs: Vec, + pub keys: KeyBinds, + /// Lines Horizon does not interpret, kept verbatim. + pub extra: BTreeMap, } impl Default for Settings { fn default() -> Self { - Self { fov: 70.0, render_distance: 12, sensitivity: 0.5, master_volume: 1.0, gui_scale: 0, view_bobbing: true } + Self { + fov: 70.0, + render_distance: 12, + simulation_distance: 12, + sensitivity: 0.5, + master_volume: 1.0, + volumes: [1.0; 11], + gui_scale: 0, + view_bobbing: true, + gamma: 0.5, + // Vanilla defaults to 120; Horizon runs unlimited unless capped. + max_fps: 260, + vsync: true, + fullscreen: false, + smooth_lighting: true, + clouds: "true".into(), + cloud_range: 128, + particles: 0, + entity_distance: 1.0, + entity_shadows: true, + biome_blend: 2, + graphics_preset: "fancy".into(), + mipmap_levels: 4, + weather_radius: 10, + chunk_fade: 0.75, + vignette: true, + autosave_indicator: true, + cutout_leaves: true, + improved_transparency: false, + attack_indicator: 1, + inactivity_fps_limit: "afk".into(), + prioritize_chunk_updates: 0, + menu_blur: 5, + invert_y: false, + mouse_wheel_sensitivity: 1.0, + discrete_scroll: false, + toggle_crouch: false, + toggle_sprint: false, + auto_jump: false, + language: "en_us".into(), + force_unicode: false, + japanese_glyphs: false, + chat_visibility: 0, + chat_colors: true, + chat_links: true, + chat_opacity: 1.0, + text_background_opacity: 0.5, + chat_scale: 1.0, + chat_width: 1.0, + chat_height_focused: 1.0, + chat_height_unfocused: 70.0 / 160.0, + chat_line_spacing: 0.0, + auto_suggestions: true, + reduced_debug_info: false, + high_contrast: false, + main_hand_left: false, + resource_packs: vec!["vanilla".into()], + keys: KeyBinds::default(), + extra: BTreeMap::new(), + } } } +fn unquote(v: &str) -> &str { + v.strip_prefix('"').and_then(|v| v.strip_suffix('"')).unwrap_or(v) +} +fn parse_list(v: &str) -> Vec { + serde_json::from_str::>(v).unwrap_or_default() +} impl Settings { pub fn load(path: &Path) -> Self { + let Ok(text) = fs::read_to_string(path) else { return Self::default() }; + Self::parse(&text) + } + pub fn parse(text: &str) -> Self { let mut s = Self::default(); - let Ok(text) = fs::read_to_string(path) else { return s }; for line in text.lines() { let Some((k, v)) = line.split_once(':') else { continue }; + let f = |d: f32| v.parse::().unwrap_or(d); + let b = |d: bool| match v { + "true" => true, + "false" => false, + _ => d, + }; + let i = |d: i32| v.parse::().unwrap_or(d); match k { - // Options.fov is stored as (fov - 70) / 40. - "fov" => s.fov = v.parse::().map_or(70.0, |f| (70.0 + f * 40.0).clamp(30.0, 110.0)), - "renderDistance" => s.render_distance = v.parse().unwrap_or(12).clamp(2, 32), - "mouseSensitivity" => s.sensitivity = v.parse().unwrap_or(0.5f32).clamp(0.0, 1.0), - "soundCategory_master" => s.master_volume = v.parse().unwrap_or(1.0f32).clamp(0.0, 1.0), + "version" => {} + "fov" => s.fov = v.parse::().map_or(70.0, |f| (f * 40.0 + 70.0).round().clamp(30.0, 110.0)), + "renderDistance" => s.render_distance = i(12).clamp(2, 32), + "simulationDistance" => s.simulation_distance = i(12).clamp(5, 32), + "mouseSensitivity" => s.sensitivity = f(0.5).clamp(0.0, 1.0), "guiScale" => s.gui_scale = v.parse().unwrap_or(0), - "bobView" => s.view_bobbing = v == "true", - _ => {} + "bobView" => s.view_bobbing = b(true), + "gamma" => s.gamma = f(0.5).clamp(0.0, 1.0), + "maxFps" => s.max_fps = v.parse::().unwrap_or(260).clamp(10, 260), + "enableVsync" => s.vsync = b(true), + "fullscreen" => s.fullscreen = b(false), + "ao" => s.smooth_lighting = b(true), + "renderClouds" => s.clouds = unquote(v).to_owned(), + "cloudRange" => s.cloud_range = i(128).clamp(2, 128), + "particles" => s.particles = v.parse::().unwrap_or(0).min(2), + "entityDistanceScaling" => s.entity_distance = f(1.0).clamp(0.5, 5.0), + "entityShadows" => s.entity_shadows = b(true), + "biomeBlendRadius" => s.biome_blend = i(2).clamp(0, 7), + "graphicsPreset" => s.graphics_preset = unquote(v).to_owned(), + "mipmapLevels" => s.mipmap_levels = i(4).clamp(0, 4), + "weatherRadius" => s.weather_radius = i(10).clamp(3, 10), + "chunkSectionFadeInTime" => s.chunk_fade = f(0.75).clamp(0.0, 2.0), + "vignette" => s.vignette = b(true), + "showAutosaveIndicator" => s.autosave_indicator = b(true), + "cutoutLeaves" => s.cutout_leaves = b(true), + "improvedTransparency" => s.improved_transparency = b(false), + "attackIndicator" => s.attack_indicator = v.parse::().unwrap_or(1).min(2), + "inactivityFpsLimit" => s.inactivity_fps_limit = unquote(v).to_owned(), + "prioritizeChunkUpdates" => s.prioritize_chunk_updates = v.parse::().unwrap_or(0).min(2), + "menuBackgroundBlurriness" => s.menu_blur = i(5).clamp(0, 10), + "invertYMouse" => s.invert_y = b(false), + "mouseWheelSensitivity" => s.mouse_wheel_sensitivity = f(1.0).clamp(0.01, 10.0), + "discrete_mouse_scroll" => s.discrete_scroll = b(false), + "toggleCrouch" => s.toggle_crouch = b(false), + "toggleSprint" => s.toggle_sprint = b(false), + "autoJump" => s.auto_jump = b(false), + "lang" => s.language = v.to_owned(), + "forceUnicodeFont" => s.force_unicode = b(false), + "japaneseGlyphVariants" => s.japanese_glyphs = b(false), + "chatVisibility" => s.chat_visibility = v.parse::().unwrap_or(0).min(2), + "chatColors" => s.chat_colors = b(true), + "chatLinks" => s.chat_links = b(true), + "chatOpacity" => s.chat_opacity = f(1.0).clamp(0.0, 1.0), + "textBackgroundOpacity" => s.text_background_opacity = f(0.5).clamp(0.0, 1.0), + "chatScale" => s.chat_scale = f(1.0).clamp(0.0, 1.0), + "chatWidth" => s.chat_width = f(1.0).clamp(0.0, 1.0), + "chatHeightFocused" => s.chat_height_focused = f(1.0).clamp(0.0, 1.0), + "chatHeightUnfocused" => s.chat_height_unfocused = f(0.4375).clamp(0.0, 1.0), + "chatLineSpacing" => s.chat_line_spacing = f(0.0).clamp(0.0, 1.0), + "autoSuggestions" => s.auto_suggestions = b(true), + "reducedDebugInfo" => s.reduced_debug_info = b(false), + "highContrast" => s.high_contrast = b(false), + "mainHand" => s.main_hand_left = unquote(v) == "left", + "resourcePacks" => s.resource_packs = parse_list(v), + _ if k.starts_with("key_") => { + if !s.keys.set_saved(&k[4..], v) { + s.extra.insert(k.to_owned(), v.to_owned()); + } + } + _ if k.starts_with("soundCategory_") => { + let name = &k["soundCategory_".len()..]; + match SOUND_SOURCES.iter().position(|n| *n == name) { + Some(0) => s.master_volume = f(1.0).clamp(0.0, 1.0), + Some(i) => s.volumes[i] = f(1.0).clamp(0.0, 1.0), + None => { + s.extra.insert(k.to_owned(), v.to_owned()); + } + } + } + _ => { + s.extra.insert(k.to_owned(), v.to_owned()); + } } } s } + /// The `options.txt` text (Options.save: `version` first, then key:value). + pub fn serialize(&self) -> String { + let mut lines: Vec<(String, String)> = vec![ + ("ao".into(), self.smooth_lighting.to_string()), + ("biomeBlendRadius".into(), self.biome_blend.to_string()), + ("chunkSectionFadeInTime".into(), self.chunk_fade.to_string()), + ("cutoutLeaves".into(), self.cutout_leaves.to_string()), + ("enableVsync".into(), self.vsync.to_string()), + ("entityDistanceScaling".into(), self.entity_distance.to_string()), + ("entityShadows".into(), self.entity_shadows.to_string()), + ("forceUnicodeFont".into(), self.force_unicode.to_string()), + ("japaneseGlyphVariants".into(), self.japanese_glyphs.to_string()), + ("fov".into(), ((self.fov - 70.0) / 40.0).to_string()), + ("graphicsPreset".into(), format!("\"{}\"", self.graphics_preset)), + ("prioritizeChunkUpdates".into(), self.prioritize_chunk_updates.to_string()), + ("fullscreen".into(), self.fullscreen.to_string()), + ("gamma".into(), self.gamma.to_string()), + ("guiScale".into(), self.gui_scale.to_string()), + ("maxFps".into(), self.max_fps.to_string()), + ("improvedTransparency".into(), self.improved_transparency.to_string()), + ("inactivityFpsLimit".into(), format!("\"{}\"", self.inactivity_fps_limit)), + ("mipmapLevels".into(), self.mipmap_levels.to_string()), + ("particles".into(), self.particles.to_string()), + ("reducedDebugInfo".into(), self.reduced_debug_info.to_string()), + ("renderClouds".into(), format!("\"{}\"", self.clouds)), + ("cloudRange".into(), self.cloud_range.to_string()), + ("renderDistance".into(), self.render_distance.to_string()), + ("simulationDistance".into(), self.simulation_distance.to_string()), + ("vignette".into(), self.vignette.to_string()), + ("weatherRadius".into(), self.weather_radius.to_string()), + ("autoJump".into(), self.auto_jump.to_string()), + ("autoSuggestions".into(), self.auto_suggestions.to_string()), + ("chatColors".into(), self.chat_colors.to_string()), + ("chatLinks".into(), self.chat_links.to_string()), + ("discrete_mouse_scroll".into(), self.discrete_scroll.to_string()), + ("invertYMouse".into(), self.invert_y.to_string()), + ("bobView".into(), self.view_bobbing.to_string()), + ("toggleCrouch".into(), self.toggle_crouch.to_string()), + ("toggleSprint".into(), self.toggle_sprint.to_string()), + ("mouseSensitivity".into(), self.sensitivity.to_string()), + ("highContrast".into(), self.high_contrast.to_string()), + ("resourcePacks".into(), serde_json::to_string(&self.resource_packs).unwrap_or_else(|_| "[]".into())), + ("lang".into(), self.language.clone()), + ("chatVisibility".into(), self.chat_visibility.to_string()), + ("chatOpacity".into(), self.chat_opacity.to_string()), + ("chatLineSpacing".into(), self.chat_line_spacing.to_string()), + ("textBackgroundOpacity".into(), self.text_background_opacity.to_string()), + ("chatHeightFocused".into(), self.chat_height_focused.to_string()), + ("chatHeightUnfocused".into(), self.chat_height_unfocused.to_string()), + ("chatScale".into(), self.chat_scale.to_string()), + ("chatWidth".into(), self.chat_width.to_string()), + ("mainHand".into(), if self.main_hand_left { "\"left\"".into() } else { "\"right\"".into() }), + ("attackIndicator".into(), self.attack_indicator.to_string()), + ("mouseWheelSensitivity".into(), self.mouse_wheel_sensitivity.to_string()), + ("showAutosaveIndicator".into(), self.autosave_indicator.to_string()), + ("menuBackgroundBlurriness".into(), self.menu_blur.to_string()), + ]; + for (name, key) in self.keys.saved() { + lines.push((format!("key_{name}"), key)); + } + for (i, source) in SOUND_SOURCES.iter().enumerate() { + let v = if i == 0 { self.master_volume } else { self.volumes[i] }; + lines.push((format!("soundCategory_{source}"), v.to_string())); + } + let known: std::collections::BTreeSet = lines.iter().map(|(k, _)| k.clone()).collect(); + for (k, v) in &self.extra { + if !known.contains(k) { + lines.push((k.clone(), v.clone())); + } + } + let mut out = format!("version:{}\n", horizon_world::DATA_VERSION); + for (k, v) in lines { + out.push_str(&format!("{k}:{v}\n")); + } + out + } pub fn save(&self, path: &Path) { - let text = format!( - "version:4793\nfov:{}\nrenderDistance:{}\nmouseSensitivity:{}\nsoundCategory_master:{}\nguiScale:{}\nbobView:{}\n", - (self.fov - 70.0) / 40.0, - self.render_distance, - self.sensitivity, - self.master_volume, - self.gui_scale, - self.view_bobbing - ); - let _ = fs::write(path, text); + let _ = fs::write(path, self.serialize()); } - fn rows(&self) -> Vec<(String, Option)> { - vec![ - (format!("FOV: {}", if self.fov.round() == 70.0 { "Normal".into() } else if self.fov >= 110.0 { "Quake Pro".into() } else { format!("{:.0}", self.fov) }), Some((self.fov - 30.0) / 80.0)), - (format!("Render Distance: {} chunks", self.render_distance), Some((self.render_distance - 2) as f32 / 30.0)), - (format!("Sensitivity: {}", if self.sensitivity == 0.0 { "*yawn*".into() } else if self.sensitivity >= 1.0 { "HYPERSPEED!!!".into() } else { format!("{:.0}%", self.sensitivity * 200.0) }), Some(self.sensitivity)), - (format!("Master Volume: {}", if self.master_volume == 0.0 { "OFF".into() } else { format!("{:.0}%", self.master_volume * 100.0) }), Some(self.master_volume)), - (format!("GUI Scale: {}", if self.gui_scale == 0 { "Auto".into() } else { self.gui_scale.to_string() }), None), - (format!("View Bobbing: {}", if self.view_bobbing { "ON" } else { "OFF" }), None), - ] + /// Volume of a sound source (master excluded). + pub fn volume(&self, source: &str) -> f32 { + SOUND_SOURCES.iter().position(|n| *n == source).map_or(1.0, |i| if i == 0 { self.master_volume } else { self.volumes[i] }) } - fn layout(w: f32, i: usize) -> (f32, f32) { - (w / 2.0 - 155.0 + (i % 2) as f32 * 160.0, 48.0 + (i / 2) as f32 * 24.0) - } - pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, cursor: (f32, f32)) { - let (w, h) = (batch.width, batch.height); - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 150)); - let title = "Options"; - let tw = HudBatch::text_width(atlas, title); - batch.text(atlas, title, (w - tw) / 2.0, 15.0, u32::MAX, true); - let mut rows = self.rows(); - rows.push(("Done".into(), None)); - for (i, (label, slider)) in rows.iter().enumerate() { - let (x, y) = if i == rows.len() - 1 { (w / 2.0 - 100.0, h / 6.0 + 168.0) } else { Self::layout(w, i) }; - let width = if i == rows.len() - 1 { 200.0 } else { 150.0 }; - let hover = cursor.0 >= x && cursor.0 < x + width && cursor.1 >= y && cursor.1 < y + 20.0; - let sprite = match (slider, hover) { - (Some(_), _) => "gui/sprites/widget/slider", - (None, true) => "gui/sprites/widget/button_highlighted", - (None, false) => "gui/sprites/widget/button", - }; - if let Some(r) = atlas.sprites.get(sprite).copied() { - let half = width / 2.0; - let mut left = r; - left.u1 = r.u0 + (r.u1 - r.u0) * (half / r.w as f32); - batch.rect_uv(x, y, half, 20.0, left, u32::MAX); - let mut right = r; - right.u0 = r.u1 - (r.u1 - r.u0) * (half / r.w as f32); - batch.rect_uv(x + half, y, half, 20.0, right, u32::MAX); - } - if let Some(v) = slider { - let handle = if hover { "gui/sprites/widget/slider_handle_highlighted" } else { "gui/sprites/widget/slider_handle" }; - batch.sprite_scaled(atlas, handle, x + v.clamp(0.0, 1.0) * (width - 8.0), y, 8.0, 20.0, u32::MAX); - } - let tw = HudBatch::text_width(atlas, label); - batch.text(atlas, label, x + (width - tw) / 2.0, y + 6.0, u32::MAX, true); + pub fn chat_options(&self) -> crate::chat::ChatOptions { + crate::chat::ChatOptions { + opacity: self.chat_opacity, + background_opacity: self.text_background_opacity, + scale: self.chat_scale, + width: self.chat_width, + height_focused: self.chat_height_focused, + height_unfocused: self.chat_height_unfocused, + line_spacing: self.chat_line_spacing, } } - /// Handle a click or drag; returns true when Done was pressed. - pub fn click(&mut self, x: f32, y: f32, size: (f32, f32), drag: bool) -> bool { - let (w, h) = size; - let rows = self.rows().len(); - if !drag && x >= w / 2.0 - 100.0 && x < w / 2.0 + 100.0 && y >= h / 6.0 + 168.0 && y < h / 6.0 + 188.0 { - return true; - } - for i in 0..rows { - let (bx, by) = Self::layout(w, i); - if !(x >= bx && x < bx + 150.0 && y >= by && y < by + 20.0) { - continue; - } - let v = ((x - bx - 4.0) / 142.0).clamp(0.0, 1.0); - match i { - 0 => self.fov = (30.0 + v * 80.0).round(), - 1 => self.render_distance = 2 + (v * 30.0).round() as i32, - 2 => self.sensitivity = (v * 100.0).round() / 100.0, - 3 => self.master_volume = (v * 100.0).round() / 100.0, - 4 if !drag => self.gui_scale = (self.gui_scale + 1) % 5, - 5 if !drag => self.view_bobbing = !self.view_bobbing, - _ => {} - } - } - false - } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn round_trips_vanilla_options_txt() { + let text = "version:4000\nfov:0.5\nrenderDistance:16\nmaxFps:260\nrenderClouds:\"fast\"\nkey_key.jump:key.keyboard.j\nsoundCategory_music:0.25\nresourcePacks:[\"vanilla\",\"file/x.zip\"]\nlang:fr_fr\nsomeFutureOption:42\n"; + let s = Settings::parse(text); + assert_eq!(s.fov, 90.0); + assert_eq!(s.render_distance, 16); + assert_eq!(s.max_fps, 260); + assert_eq!(s.clouds, "fast"); + assert_eq!(s.keys.get("key.jump"), "key.keyboard.j"); + assert_eq!(s.volume("music"), 0.25); + assert_eq!(s.resource_packs, ["vanilla", "file/x.zip"]); + assert_eq!(s.language, "fr_fr"); + let out = s.serialize(); + assert!(out.starts_with("version:")); + assert!(out.contains("\nkey_key.jump:key.keyboard.j\n")); + assert!(out.contains("\nsomeFutureOption:42\n")); + assert!(out.contains("\nrenderClouds:\"fast\"\n")); + let again = Settings::parse(&out); + assert_eq!(again.fov, 90.0); + assert_eq!(again.keys.get("key.jump"), "key.keyboard.j"); + } } From c7d3ea9786fe1753a103d79fc05f8889d68013ad Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:40:00 +0200 Subject: [PATCH 4/4] WIP snapshot: unfinished ui parity work (paused mid-task, may not build) Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 53 +--------- crates/horizon-client/src/game/chat.rs | 9 +- crates/horizon-client/src/game/screens.rs | 121 ++++++++++++++++++++++ crates/horizon-client/src/ui.rs | 8 ++ 4 files changed, 142 insertions(+), 49 deletions(-) create mode 100644 crates/horizon-client/src/game/screens.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 17a307a80..59bd58ec5 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5,6 +5,7 @@ mod commands; mod control; mod options; mod packs; +mod screens; use horizon_client::{ Result, assets::Assets, @@ -1699,31 +1700,8 @@ impl Game<'_> { batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 32, a)); } match self.screen { - Screen::Paused => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); - let title = "Game Menu"; - let tw = HudBatch::text_width(atlas, title); - batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); - for (i, label) in ["Back to Game", "Options...", "Save and Quit to Title"].iter().enumerate() { - let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); - let hover = self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0; - let sprite = if hover { "gui/sprites/widget/button_highlighted" } else { "gui/sprites/widget/button" }; - batch.sprite_scaled(atlas, sprite, bx, by, 200.0, 20.0, u32::MAX); - let tw = HudBatch::text_width(atlas, label); - batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); - } - } - Screen::Dead => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(80, 0, 0, 120)); - let title = "You Died!"; - let tw = HudBatch::text_width(atlas, title); - batch.text(atlas, title, (w - tw) / 2.0, 60.0, u32::MAX, true); - let (bx, by) = (w / 2.0 - 100.0, h / 4.0 + 72.0); - batch.sprite_scaled(atlas, "gui/sprites/widget/button", bx, by, 200.0, 20.0, u32::MAX); - let label = "Respawn"; - let tw = HudBatch::text_width(atlas, label); - batch.text(atlas, label, bx + (200.0 - tw) / 2.0, by + 6.0, u32::MAX, true); - } + Screen::Paused => self.draw_pause_menu(&mut batch), + Screen::Dead => self.draw_death_screen(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); } @@ -4505,29 +4483,8 @@ impl ApplicationHandler for Game<'_> { Screen::Creative if pressed => { self.click_creative(button == MouseButton::Right); } - Screen::Paused if pressed => { - let size = self.renderer.as_ref().map(|r| [r.config.width, r.config.height]).unwrap_or([1, 1]); - let b = HudBatch::new(size); - for i in 0..3 { - let (bx, by) = (b.width / 2.0 - 100.0, b.height / 4.0 + 24.0 + i as f32 * 24.0 + 16.0); - if self.cursor.0 >= bx && self.cursor.0 < bx + 200.0 && self.cursor.1 >= by && self.cursor.1 < by + 20.0 { - if i == 0 { - self.screen = Screen::Playing; - self.capture(true); - } else if i == 1 { - self.open_options(false); - } else { - self.close_world()?; - } - } - } - } - Screen::Dead if pressed => { - self.player = None; - self.screen = Screen::Playing; - self.spawn_player()?; - self.capture(true); - } + Screen::Paused if pressed => self.pause_click()?, + Screen::Dead if pressed => self.death_click()?, _ => {} } } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 28dde48b0..8424d957d 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -74,6 +74,9 @@ pub struct UiState { pub options: horizon_client::options_ui::OptionsUi, /// The prepared resources before resource packs are layered on. pub vanilla_root: std::path::PathBuf, + /// Death screen cause and when the player died (buttons wait 20 ticks). + pub death_text: Option, + pub died_at: Option, } impl Game<'_> { @@ -397,6 +400,8 @@ impl Game<'_> { /// cause is known to the client). pub(super) fn death_message(&mut self) { let cause = self.ui.death_cause.take(); + self.ui.died_at = Some(std::time::Instant::now()); + self.ui.death_text = None; if !self.ui.rules.bool("show_death_messages") { return; } @@ -414,7 +419,9 @@ impl Game<'_> { "death.attack.generic".into() } }); - self.system_message(Text::translate(&key, &[Text::literal(PLAYER_NAME)])); + let message = Text::translate(&key, &[Text::literal(PLAYER_NAME)]); + self.ui.death_text = Some(message.clone()); + self.system_message(message); } /// F1 hides the HUD (and hand); the screenshot key still works. pub(super) fn toggle_hide_gui(&mut self) { diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs new file mode 100644 index 000000000..94aaf1597 --- /dev/null +++ b/crates/horizon-client/src/game/screens.rs @@ -0,0 +1,121 @@ +//! The pause menu (PauseScreen) and death screen (DeathScreen) layouts. +use super::{Game, Screen}; +use horizon_client::{ + Result, + hud::{HudBatch, rgba}, + text::{self, Text}, + ui, +}; + +/// PauseScreen buttons: (x, y, width, label key, action id, active). +fn pause_buttons(w: f32, h: f32) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { + // GridLayout of two 98px columns (padding 4), aligned at (0.5, 0.25). + let (grid_w, grid_h) = (212.0, 166.0); + let x0 = ((w - grid_w) * 0.5).floor(); + let y0 = ((h - grid_h) * 0.25).floor(); + vec![ + (x0 + 4.0, y0 + 50.0, 204.0, "menu.returnToGame", 0, true), + (x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 9, false), + (x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 9, false), + (x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true), + (x0 + 110.0, y0 + 122.0, 98.0, "options.worldOptions.button", 9, false), + (x0 + 4.0, y0 + 146.0, 204.0, "menu.returnToMenu", 2, true), + ] +} +/// The icon row: report bugs, feedback, friends, player reporting. +fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { + let x0 = ((w - 212.0) * 0.5).floor() + 60.0; + let y = ((h - 166.0) * 0.25).floor() + 98.0; + [ + (x0, y, "gui/sprites/pause_menu/bug"), + (x0 + 24.0, y, "gui/sprites/pause_menu/social_interactions"), + (x0 + 48.0, y, "gui/sprites/icon/friends"), + (x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"), + ] +} +fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] { + [(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0), (w / 2.0 - 100.0, h / 4.0 + 96.0, "deathScreen.titleScreen", 1)] +} +impl Game<'_> { + pub(super) fn draw_pause_menu(&mut self, batch: &mut HudBatch) { + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let title = Text::translate("menu.game", &[]); + let tw = atlas.font.width_text(&title); + batch.text_styled(atlas, &title, ((w - tw) / 2.0).floor(), 40.0, u32::MAX, true); + for (x, y, bw, key, _, active) in pause_buttons(w, h) { + let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); + ui::button(batch, atlas, x, y, bw, 20.0, &Text::translate(key, &[]), active, hover); + } + for (x, y, sprite) in pause_icons(w, h) { + ui::button(batch, atlas, x, y, 20.0, 20.0, &Text::empty(), false, false); + batch.sprite_scaled(atlas, sprite, x + 2.0, y + 2.0, 15.0, 15.0, rgba(160, 160, 160, 255)); + } + } + pub(super) fn pause_click(&mut self) -> Result<()> { + let (w, h) = { + let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + (b.width, b.height) + }; + let hit = pause_buttons(w, h).into_iter().find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)).map(|b| b.4); + match hit { + Some(0) => { + self.screen = Screen::Playing; + self.capture(true); + } + Some(1) => self.open_options(false), + Some(2) => self.close_world()?, + _ => {} + } + Ok(()) + } + /// DeathScreen: gradient, the title at double size, the cause and score. + pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) { + let atlas = &self.res.atlas; + let (w, h) = (batch.width, batch.height); + // fillGradient(0x60500000 -> 0xA0803030). + let rows = h.ceil() as i32; + for y in 0..rows { + let t = y as f32 / h.max(1.0); + let lerp = |a: f32, b: f32| (a + (b - a) * t) as u8; + batch.fill(atlas, 0.0, y as f32, w, 1.0, rgba(lerp(80.0, 128.0), lerp(0.0, 48.0), lerp(0.0, 48.0), lerp(96.0, 160.0))); + } + let title = Text::translate("deathScreen.title", &[]); + let tw = atlas.font.width_text(&title); + ui::text_scaled(batch, atlas, &title, (w / 2.0 - tw).floor(), 60.0, 2.0, u32::MAX); + if let Some(cause) = &self.ui.death_text { + let cw = atlas.font.width_text(cause); + batch.text_styled(atlas, cause, ((w - cw) / 2.0).floor(), 85.0, u32::MAX, true); + } + let score = Text::translate("deathScreen.score.value", &[Text::colored(self.experience.total.to_string(), text::YELLOW)]); + let sw = atlas.font.width_text(&score); + batch.text_styled(atlas, &score, ((w - sw) / 2.0).floor(), 100.0, u32::MAX, true); + let active = self.ui.died_at.is_none_or(|t| t.elapsed().as_millis() >= 1000); + for (x, y, key, _) in death_buttons(w, h) { + let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0); + ui::button(batch, atlas, x, y, 200.0, 20.0, &Text::translate(key, &[]), active, hover); + } + } + pub(super) fn death_click(&mut self) -> Result<()> { + if self.ui.died_at.is_some_and(|t| t.elapsed().as_millis() < 1000) { + return Ok(()); + } + let size = self.renderer.as_ref().map_or([1, 1], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + let hit = death_buttons(b.width, b.height).into_iter().find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0)).map(|d| d.3); + match hit { + Some(0) => { + self.player = None; + self.screen = Screen::Playing; + self.ui.death_text = None; + self.spawn_player()?; + self.capture(true); + } + Some(1) => self.close_world()?, + _ => {} + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index d253f2c5e..2071b8cd4 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -118,6 +118,14 @@ pub fn tiled(batch: &mut HudBatch, atlas: &HudAtlas, sprite: &str, x: f32, y: f3 yy += size; } } +/// Text drawn at `scale` times its size (a scaled pose). +pub fn text_scaled(batch: &mut HudBatch, atlas: &HudAtlas, text: &Text, x: f32, y: f32, scale: f32, color: u32) { + let start = batch.vertices.len(); + batch.text_styled(atlas, text, 0.0, 0.0, color, true); + for v in &mut batch.vertices[start..] { + v.pos = [x + v.pos[0] * scale, y + v.pos[1] * scale]; + } +} pub fn hovered(cursor: (f32, f32), x: f32, y: f32, w: f32, h: f32) -> bool { cursor.0 >= x && cursor.0 < x + w && cursor.1 >= y && cursor.1 < y + h }