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); + } +}