diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b2fd9fa48..227d810d6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -72,6 +72,9 @@ jobs: if: steps.rust.outputs.required != 'false' run: | cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack + # The full content-root tests (#[ignore]d: minutes each on a laptop). The same build as above; they need the + # prepared vanilla data, so without it they pass at once. + cargo +stable test --workspace --lib --features horizon-client/mods,horizon-mods/pack mod_content::tests:: -- --ignored cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack # The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that # changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass diff --git a/AGENTS.md b/AGENTS.md index 489a1466b..3804ebae8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,7 +11,7 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md] - **Keep your runs away from real player data.** Any game or launcher you start gets fresh `mktemp -d` folders in `HORIZON_HOME` (the game's data), `HORIZON_LAUNCHER_HOME`, `XDG_DATA_HOME` and `XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the - launcher, `HORIZON_LAUNCHER_TRASH` and `HORIZON_LAUNCHER_CLIPBOARD` pointing into the scratch home. Never write to + launcher, `HORIZON_LAUNCHER_TRASH`, `HORIZON_LAUNCHER_CLIPBOARD` and `HORIZON_LAUNCHER_DESKTOP` pointing into the scratch home. Never write to `~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`. - **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what. Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a @@ -66,6 +66,7 @@ reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` an python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR python3 tools/pr_ready.py --quick # same without harnesses cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately +cargo test -p horizon-client --features horizon-client/mods --lib mod_content::tests:: -- --ignored # the 5 slow content-root tests, #[ignore]d; pr_ready runs them when mod content, assets, blocks or items change cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job) python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them diff --git a/Cargo.lock b/Cargo.lock index 0e0a39038..e65b25dab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -930,6 +930,13 @@ version = "3.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" +[[package]] +name = "far-view" +version = "1.0.0" +dependencies = [ + "horizon-mod-sdk", +] + [[package]] name = "fdeflate" version = "0.3.7" @@ -1398,6 +1405,7 @@ dependencies = [ "sha1", "sha2", "symphonia", + "unicode-bidi", "ureq", "wgpu", "winit", @@ -3767,6 +3775,12 @@ version = "1.20.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.26" diff --git a/Cargo.toml b/Cargo.toml index 933901dce..8f3153c62 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ members = [ "crates/horizon-mod-sdk/examples/beacons", "mods/official/fps-overlay", "mods/official/keystrokes", + "mods/official/far-view", "mods/official/minimap", "mods/official/zoom", "xtask", diff --git a/crates/horizon-client-core/src/lang.rs b/crates/horizon-client-core/src/lang.rs index 6213cedc8..ad9f1a358 100644 --- a/crates/horizon-client-core/src/lang.rs +++ b/crates/horizon-client-core/src/lang.rs @@ -4,7 +4,10 @@ //! language used by every screen. use std::{ collections::{BTreeMap, HashMap}, - sync::{Arc, RwLock}, + sync::{ + Arc, RwLock, + atomic::{AtomicBool, Ordering}, + }, }; #[derive(Clone, Debug, PartialEq, Eq)] @@ -23,11 +26,16 @@ impl LanguageInfo { #[derive(Default)] pub struct Language { pub code: String, + /// `LanguageInfo.bidirectional`: text without a strong character reads + /// right to left (`ClientLanguage.defaultRightToLeft`). + bidirectional: bool, map: HashMap, } pub const DEFAULT: &str = "en_us"; static CURRENT: RwLock>> = RwLock::new(None); +/// The current language's `bidirectional`, read for every drawn string. +static BIDIRECTIONAL: AtomicBool = AtomicBool::new(false); /// A source of resource files: the prepared root plus packs, highest priority last. pub trait ResourceSource { @@ -134,8 +142,12 @@ impl Language { { apply_deprecated(&mut map, &bytes); } + let bidirectional = available(sources) + .iter() + .any(|info| info.code == code && info.bidirectional); Self { code: code.to_owned(), + bidirectional, map, } } @@ -197,11 +209,16 @@ pub fn available(sources: &[&dyn ResourceSource]) -> Vec { } pub fn set(language: Language) { + BIDIRECTIONAL.store(language.bidirectional, Ordering::Relaxed); *CURRENT.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(language)); } pub fn current() -> Option> { CURRENT.read().unwrap_or_else(|e| e.into_inner()).clone() } +/// `ClientLanguage.defaultRightToLeft` of the current language. +pub fn bidirectional() -> bool { + BIDIRECTIONAL.load(Ordering::Relaxed) +} pub fn code() -> String { current().map_or_else(|| DEFAULT.to_owned(), |l| l.code.clone()) } diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 5611edbc9..150433918 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -62,6 +62,7 @@ gilrs = { version = "0.11", optional = true } horizon-dualsense = { path = "../horizon-dualsense", optional = true } # HTTPS to the Minecraft services (online-mode session join). ureq = { version = "2", default-features = false, features = ["tls"] } +unicode-bidi = "0.3.18" [target.'cfg(unix)'.dependencies] # The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs). diff --git a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs index b1b25e723..067d545a8 100644 --- a/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs +++ b/crates/horizon-client/examples/probe/finalize_spawn_fixture.rs @@ -154,11 +154,11 @@ const MEMORIES: [&str; 7] = [ fn variant(m: &Mob, regs: &SpawnRegistries, v: &mut Vec) { use Species as S; let s = m.species(); - let named = |reg: &finalize::VariantRegistry, i: u8| { - format!( - "minecraft:{}", + let named = |reg: &finalize::VariantRegistry, i: Option| { + let name = i.map_or("classic", |i| { reg.names.get(i as usize).map_or("?", |n| n.as_str()) - ) + }); + format!("minecraft:{name}") }; let var = format!("minecraft:{}", finalize::variant_name(s, m.extra.variant)); match s { diff --git a/crates/horizon-client/examples/probe/recipe_book_fixture.rs b/crates/horizon-client/examples/probe/recipe_book_fixture.rs index ce2afe624..2dda3b109 100644 --- a/crates/horizon-client/examples/probe/recipe_book_fixture.rs +++ b/crates/horizon-client/examples/probe/recipe_book_fixture.rs @@ -5,6 +5,10 @@ //! //! usage: recipe_book_fixture RESOURCES CASES OUTPUT use horizon_client::recipe_book::{BookType, RecipeIndex, Settings}; +use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::recipes::RecipeBookChangeSettings, +}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::BTreeSet, fs, path::Path}; @@ -93,8 +97,23 @@ pub fn main() -> horizon_client::Result<()> { _ => BookType::Smoker, } .index(); - book.open[i] = op["open"].as_bool().unwrap_or(false); - book.filtering[i] = op["filtering"].as_bool().unwrap_or(false); + let packet = RecipeBookChangeSettings { + book_type: i as i32, + open: op["open"].as_bool().unwrap_or(false), + filtering: op["filtering"].as_bool().unwrap_or(false), + }; + let mut wire = Writer::new(); + RecipeBookChangeSettings::write(&packet, &mut wire); + extra = format!( + " packet={}", + wire.data + .iter() + .map(|b| format!("{b:02x}")) + .collect::() + ); + let decoded = RecipeBookChangeSettings::read(&mut Reader::new(&wire.data))?; + book.open[decoded.book_type as usize] = decoded.open; + book.filtering[decoded.book_type as usize] = decoded.filtering; } "save" => { let tag = book.write(); diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index be6628ece..e45362e19 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -719,11 +719,6 @@ impl Audio { self.play(event, at, volume, pitch); self.capture = capture; } - /// `LivingEntity.handleDamageEvent`'s pitch, `(r - r) * 0.2 + 1`, drawn on the - /// client (the entity's own random there, never the server's world random). - pub fn hurt_pitch(&mut self) -> f32 { - (self.random.next_float() - self.random.next_float()) * 0.2 + 1.0 - } /// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound. pub fn play_button_click(&mut self) { self.play_instance( diff --git a/crates/horizon-client/src/benchmark.rs b/crates/horizon-client/src/benchmark.rs index 12e38e78a..bd2e97be0 100644 --- a/crates/horizon-client/src/benchmark.rs +++ b/crates/horizon-client/src/benchmark.rs @@ -450,6 +450,54 @@ mod tests { assert_eq!(view_chunks(32), 2573); assert_eq!(view_chunks(0), 0); } + /// The status a fake control answers with: the player is where it should + /// be, nothing is queued, and the world holds `chunks` resident chunks. + fn status(chunks: u64) -> String { + serde_json::json!({ + "player": {"position": [0.0, 64.0, 0.0]}, + "pending_chunks": 0, + "screen": "playing", + "render_distance": 12, + "chunks": chunks, + "generated_chunks": chunks, + "meshed_sections": 0, + "streaming": {}, + }) + .to_string() + } + + #[test] + fn the_load_waits_for_the_chunks_a_teleport_starts() { + // Right after a teleport the game reports steady counts and nothing + // queued for over a second, before the integrated server has sent the + // first chunk: the quiet rule alone would call that loaded, and the + // scene would be measured over an empty view (#1749). + const LATE: usize = 30; + let (tx, rx) = mpsc::channel::(); + let polls = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let counted = std::sync::Arc::clone(&polls); + let server = thread::spawn(move || { + let mut seen = 0; + while let Ok(request) = rx.recv() { + if request.line == "status" { + let chunks = if seen < LATE { 0 } else { 400 }; + seen += 1; + counted.store(seen, std::sync::atomic::Ordering::SeqCst); + let _ = request.reply.send(status(chunks)); + } else { + let _ = request.reply.send("{}".to_owned()); + } + } + }); + let control = Control(tx); + wait_loaded(&control, |_| true).expect("the scene loads"); + assert!( + polls.load(std::sync::atomic::Ordering::SeqCst) > LATE, + "the load finished before the chunks arrived" + ); + drop(control); + let _ = server.join(); + } #[test] fn yaw_matches_vanilla() { diff --git a/crates/horizon-client/src/bidi.rs b/crates/horizon-client/src/bidi.rs new file mode 100644 index 000000000..c9c6caac7 --- /dev/null +++ b/crates/horizon-client/src/bidi.rs @@ -0,0 +1,302 @@ +//! Right-to-left text (`FormattedBidiReorder.reorder`, behind +//! `Language.getVisualOrder`): the logical text a player types becomes the +//! glyphs a font draws left to right. Arabic letters are shaped into their +//! joined presentation forms (ICU's `ArabicShaping` with `LETTERS_SHAPE`), the +//! text is reordered by the Unicode bidirectional algorithm, and characters in +//! right-to-left runs are mirrored. Left-to-right text comes back unchanged. +use crate::text::{Span, Text}; +use std::borrow::Cow; +use unicode_bidi::{ + BidiClass, Direction, Level, ParagraphBidiInfo, bidi_class, get_base_direction, +}; + +/// How a letter joins its neighbours, as ICU's shaper sees it: `Right` joins +/// the letter before it only, `Dual` both neighbours, `Mark` is skipped over +/// (diacritics) and `None` never joins. +#[derive(Clone, Copy, PartialEq)] +enum Join { + None, + Right, + Dual, + Mark, +} +use Join::{Dual, Mark, Right}; + +/// ICU's joining table (`araLink`): code point ranges and their class, with the +/// lam-alef ligatures at the end. Anything else is `Join::None`. +const JOINS: &[(u32, u32, Join)] = &[ + (0x0622, 0x0625, Right), + (0x0626, 0x0626, Dual), + (0x0627, 0x0627, Right), + (0x0628, 0x0628, Dual), + (0x0629, 0x0629, Right), + (0x062A, 0x062E, Dual), + (0x062F, 0x0632, Right), + (0x0633, 0x063A, Dual), + (0x0640, 0x0647, Dual), + (0x0648, 0x0649, Right), + (0x064A, 0x064A, Dual), + (0x064B, 0x0656, Mark), + (0x0670, 0x0670, Mark), + (0x0671, 0x0673, Right), + (0x0675, 0x0677, Right), + (0x0678, 0x0687, Dual), + (0x0688, 0x0699, Right), + (0x069A, 0x06B9, Dual), + (0x06BA, 0x06BA, Right), + (0x06BB, 0x06BF, Dual), + (0x06C0, 0x06C0, Right), + (0x06C1, 0x06C1, Dual), + (0x06C2, 0x06CB, Right), + (0x06CC, 0x06CC, Dual), + (0x06CD, 0x06CD, Right), + (0x06CE, 0x06D1, Dual), + (0x06D2, 0x06D3, Right), + (0x200D, 0x200D, Dual), + (0x206D, 0x206F, Mark), + (0xFEF5, 0xFEFC, Right), +]; + +/// Letters that have joined forms and the code point of the isolated one; the +/// final, initial and medial forms follow it (a right-joining letter has the +/// isolated and final only). The lam-alef ligatures are their own letters. +/// ICU leaves the extended letters (پ چ ژ ک گ ی and the rest of U+0679 to +/// U+06D3) unchanged, so they are in `JOINS` but not here. +#[rustfmt::skip] +const FORMS: &[(u32, u32)] = &[ + (0x0622, 0xFE81), (0x0623, 0xFE83), (0x0624, 0xFE85), (0x0625, 0xFE87), (0x0626, 0xFE89), + (0x0627, 0xFE8D), (0x0628, 0xFE8F), (0x0629, 0xFE93), (0x062A, 0xFE95), (0x062B, 0xFE99), + (0x062C, 0xFE9D), (0x062D, 0xFEA1), (0x062E, 0xFEA5), (0x062F, 0xFEA9), (0x0630, 0xFEAB), + (0x0631, 0xFEAD), (0x0632, 0xFEAF), (0x0633, 0xFEB1), (0x0634, 0xFEB5), (0x0635, 0xFEB9), + (0x0636, 0xFEBD), (0x0637, 0xFEC1), (0x0638, 0xFEC5), (0x0639, 0xFEC9), (0x063A, 0xFECD), + (0x0641, 0xFED1), (0x0642, 0xFED5), (0x0643, 0xFED9), (0x0644, 0xFEDD), (0x0645, 0xFEE1), + (0x0646, 0xFEE5), (0x0647, 0xFEE9), (0x0648, 0xFEED), (0x0649, 0xFEEF), (0x064A, 0xFEF1), + (0xFEF5, 0xFEF5), (0xFEF7, 0xFEF7), (0xFEF9, 0xFEF9), (0xFEFB, 0xFEFB), +]; + +/// `Bidi_Mirroring_Glyph` (`UCharacter.getMirror`): each pair is two +/// neighbouring characters that mirror each other. +const MIRRORED: &str = "\ + ()<>[]{}«»༺༻༼༽᚛᚜‹›⁅⁆⁽⁾₍₎∈∋∉∌∊∍∕⧵∟⯾∠⦣∡⦛∢⦠∤⫮∼∽≃⋍≅≌≒≓\ + ≔≕≤≥≦≧≨≩≪≫≮≯≰≱≲≳≴≵≶≷≸≹≺≻≼≽≾≿⊀⊁⊂⊃⊄⊅⊆⊇⊈⊉⊊⊋⊏⊐⊑⊒⊘⦸⊢⊣⊦⫞\ + ⊨⫤⊩⫣⊫⫥⊰⊱⊲⊳⊴⊵⊶⊷⊸⟜⋉⋊⋋⋌⋐⋑⋖⋗⋘⋙⋚⋛⋜⋝⋞⋟⋠⋡⋢⋣⋤⋥⋦⋧⋨⋩⋪⋫⋬⋭⋰⋱⋲⋺\ + ⋳⋻⋴⋼⋶⋽⋷⋾⌈⌉⌊⌋〈〉❨❩❪❫❬❭❮❯❰❱❲❳❴❵⟃⟄⟅⟆⟈⟉⟋⟍⟕⟖⟝⟞⟢⟣⟤⟥⟦⟧⟨⟩⟪⟫\ + ⟬⟭⟮⟯⦃⦄⦅⦆⦇⦈⦉⦊⦋⦌⦍⦐⦎⦏⦑⦒⦓⦔⦕⦖⦗⦘⦤⦥⦨⦩⦪⦫⦬⦭⦮⦯⧀⧁⧄⧅⧏⧐⧑⧒⧔⧕⧘⧙⧚⧛\ + ⧨⧩⧸⧹⧼⧽⨫⨬⨭⨮⨴⨵⨼⨽⩤⩥⩹⩺⩻⩼⩽⩾⩿⪀⪁⪂⪃⪄⪅⪆⪇⪈⪉⪊⪋⪌⪍⪎⪏⪐⪑⪒⪓⪔⪕⪖⪗⪘⪙⪚\ + ⪛⪜⪝⪞⪟⪠⪡⪢⪦⪧⪨⪩⪪⪫⪬⪭⪯⪰⪱⪲⪳⪴⪵⪶⪷⪸⪹⪺⪻⪼⪽⪾⪿⫀⫁⫂⫃⫄⫅⫆⫇⫈⫉⫊⫋⫌⫍⫎⫏⫐\ + ⫑⫒⫓⫔⫕⫖⫬⫭⫷⫸⫹⫺⸂⸃⸄⸅⸉⸊⸌⸍⸜⸝⸠⸡⸢⸣⸤⸥⸦⸧⸨⸩⹕⹖⹗⹘⹙⹚⹛⹜〈〉《》「」『』【】\ + 〔〕〖〗〘〙〚〛﹙﹚﹛﹜﹝﹞﹤﹥()<>[]{}⦅⦆「」"; + +fn join(c: char) -> Join { + let c = c as u32; + JOINS + .iter() + .find(|&&(from, to, _)| (from..=to).contains(&c)) + .map_or(Join::None, |&(_, _, join)| join) +} + +/// The letter whose joined form `c` is (ICU shapes the forms again), or `c`. +fn letter_of(c: char) -> char { + let c32 = c as u32; + if !matches!(c32, 0xFE70..=0xFEFC) { + return c; + } + if (0xFE70..0xFE80).contains(&c32) { + // The diacritics' forms pair up from fathatan on. + return char::from_u32(0x064B + (c32 - 0xFE70) / 2).unwrap_or(c); + } + FORMS + .iter() + .find(|&&(letter, iso)| { + let forms = if join(char::from_u32(letter).unwrap_or(c)) == Dual { + 4 + } else { + 2 + }; + (iso..iso + forms).contains(&c32) + }) + .and_then(|&(letter, _)| char::from_u32(letter)) + .unwrap_or(c) +} + +/// `ArabicShaping(LETTERS_SHAPE).shape`: lam followed by an alef (diacritics +/// may sit between) becomes one ligature, then every letter takes the isolated, +/// final, initial or medial form its neighbours call for. Diacritics take the +/// tatweel form between two joined letters. The text can only get shorter. +fn shape(text: &[char]) -> Vec { + let letters: Vec = text.iter().map(|&c| letter_of(c)).collect(); + let mut chars = Vec::with_capacity(letters.len()); + let mut i = 0; + while i < letters.len() { + if letters[i] == '\u{644}' { + let mut at = i + 1; + while letters.get(at).is_some_and(|&c| join(c) == Mark) { + at += 1; + } + let alef = letters.get(at).and_then(|&c| { + ['\u{622}', '\u{623}', '\u{625}', '\u{627}'] + .iter() + .position(|&a| a == c) + }); + if let Some(alef) = alef { + chars.push(char::from_u32(0xFEF5 + 2 * alef as u32).unwrap_or('\u{644}')); + chars.extend_from_slice(&letters[i + 1..at]); + i = at + 1; + continue; + } + } + chars.push(letters[i]); + i += 1; + } + // Whether the nearest letter before joins the next one, and the joins of + // the nearest letter after. + let mut joins_next = false; + let mut out = Vec::with_capacity(chars.len()); + for (i, &c) in chars.iter().enumerate() { + let next_joins = chars[i + 1..] + .iter() + .map(|&n| join(n)) + .find(|&j| j != Mark) + .is_some_and(|j| j != Join::None); + let kind = join(c); + let shaped = match kind { + Join::None => { + joins_next = false; + c + } + Mark => match c as u32 { + m @ 0x064B..=0x0652 => { + let iso = 0xFE70 + 2 * (m - 0x064B); + let tatweel = joins_next && next_joins && !matches!(m, 0x064C | 0x064D); + char::from_u32(iso + u32::from(tatweel)).unwrap_or(c) + } + _ => c, + }, + Right | Dual => { + let to_next = kind == Dual && next_joins; + let form = match (joins_next, to_next) { + (false, false) => 0, + (true, false) => 1, + (false, true) => 2, + (true, true) => 3, + }; + joins_next = kind == Dual; + FORMS + .binary_search_by_key(&(c as u32), |&(letter, _)| letter) + .ok() + .and_then(|at| char::from_u32(FORMS[at].1 + form)) + .unwrap_or(c) + } + }; + out.push(shaped); + } + out +} + +/// `UCharacter.getMirror`. +fn mirror(c: char) -> char { + if bidi_class(c) != BidiClass::ON { + return c; + } + let mut pairs = MIRRORED.chars(); + while let (Some(a), Some(b)) = (pairs.next(), pairs.next()) { + if c == a { + return b; + } + if c == b { + return a; + } + } + c +} + +/// Whether a character can change anything: right-to-left letters and numbers, +/// the explicit direction controls and the diacritics that shaping turns into +/// letters. Without any, left-to-right text keeps its order. +fn directional(c: char) -> bool { + c as u32 >= 0x0590 + && (matches!(c as u32, 0x064B..=0x0652) + || matches!( + bidi_class(c), + BidiClass::R + | BidiClass::AL + | BidiClass::AN + | BidiClass::LRE + | BidiClass::RLE + | BidiClass::LRO + | BidiClass::RLO + | BidiClass::PDF + | BidiClass::LRI + | BidiClass::RLI + | BidiClass::FSI + | BidiClass::PDI + )) +} + +/// Whether `chars` keep their order and shapes: left-to-right text without +/// anything directional, in a language that reads left to right by default. +fn unchanged(mut chars: impl Iterator, default_rtl: bool) -> bool { + !default_rtl && !chars.any(directional) +} + +/// `FormattedBidiReorder.reorder`: `chars` shaped, in visual order, with each +/// character's position in the shaped text. A character's style is the one at +/// its position in the shaped text, as `SubStringSource` takes it (the text +/// shrinks at a lam-alef ligature). +fn reorder(chars: &[char], default_rtl: bool) -> Vec<(char, usize)> { + let shaped = shape(chars); + let plain: String = shaped.iter().collect(); + // DEFAULT_RTL only changes text without a strong character. + let level = + (default_rtl && get_base_direction(plain.as_str()) == Direction::Mixed).then(Level::rtl); + let info = ParagraphBidiInfo::new(&plain, level); + let levels = info.reordered_levels_per_char(0..plain.len()); + ParagraphBidiInfo::reorder_visual(&levels) + .into_iter() + .map(|i| { + let c = if levels[i].is_rtl() { + mirror(shaped[i]) + } else { + shaped[i] + }; + (c, i) + }) + .collect() +} + +/// `Language.getVisualOrder` of a text (its `§` codes already resolved), for +/// the current language's direction. +pub fn visual(text: &Text) -> Cow<'_, Text> { + let default_rtl = crate::lang::bidirectional(); + if unchanged(text.chars().map(|(c, _)| c), default_rtl) { + return Cow::Borrowed(text); + } + let chars: Vec = text.chars().map(|(c, _)| c).collect(); + let styles: Vec<_> = text.chars().map(|(_, style)| style).collect(); + let mut out = Text::default(); + for (c, at) in reorder(&chars, default_rtl) { + match out.spans.last_mut() { + Some(span) if span.style == *styles[at] => span.text.push(c), + _ => out.spans.push(Span { + text: c.to_string(), + style: styles[at].clone(), + }), + } + } + Cow::Owned(out) +} + +/// The same for a plain string. +pub fn visual_str(s: &str) -> Cow<'_, str> { + let default_rtl = crate::lang::bidirectional(); + if unchanged(s.chars(), default_rtl) { + return Cow::Borrowed(s); + } + let chars: Vec = s.chars().collect(); + Cow::Owned( + reorder(&chars, default_rtl) + .into_iter() + .map(|(c, _)| c) + .collect(), + ) +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 28a876d80..a312fe9f7 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -610,7 +610,9 @@ fn sign_text_calls( .iter() .enumerate() .map(|(i, line)| { + // The line that fits, in the order it is drawn (getVisualOrder). let shown = first_line(line, data.max_line_width(), &advance); + let shown = crate::bidi::visual_str(&shown).into_owned(); TextCall { matrix: m, x: -((width(&shown) as i32) / 2) as f32, diff --git a/crates/horizon-client/src/brewing.rs b/crates/horizon-client/src/brewing.rs index f29bfc08b..cdd988a7a 100644 --- a/crates/horizon-client/src/brewing.rs +++ b/crates/horizon-client/src/brewing.rs @@ -7,7 +7,12 @@ use crate::{ items::{ItemStack, Items}, }; use serde_json::Value; -use std::{collections::HashSet, fs, path::Path, sync::Arc}; +use std::{ + collections::{HashMap, HashSet}, + fs, + path::Path, + sync::{Arc, OnceLock}, +}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Category { @@ -94,6 +99,24 @@ pub fn effect(id: &str) -> Option<&'static EffectDef> { let id = id.trim_start_matches("minecraft:"); EFFECTS.iter().find(|e| e.id == id) } +/// Namespaced effect ids for mob effect storage. +pub fn namespaced(id: &'static str) -> &'static str { + static IDS: OnceLock> = OnceLock::new(); + IDS.get_or_init(|| { + EFFECTS + .iter() + .map(|e| { + ( + e.id, + &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()), + ) + }) + .collect() + }) + .get(id) + .copied() + .unwrap_or(id) +} /// A `Potion`: id, name suffix (`item.minecraft.potion.effect.`) and /// effects as (effect, duration ticks, amplifier). #[derive(Clone, Copy, Debug)] diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs index ed25491c5..fddded9e1 100644 --- a/crates/horizon-client/src/chunk_map.rs +++ b/crates/horizon-client/src/chunk_map.rs @@ -76,14 +76,11 @@ impl<'a> IntoIterator for &'a ChunkMap { } } impl crate::light::LightWorld for ChunkMap { - fn state(&self, x: i32, y: i32, z: i32) -> Option { - self.columns.state(x, y, z) + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc> { + self.columns.section(cx, s, cz) } - fn light(&self, x: i32, y: i32, z: i32) -> Option { - self.columns.light(x, y, z) - } - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { - self.columns.set_light(x, y, z, packed); + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: crate::chunk::Light) { + self.columns.set_section_light(cx, s, cz, light); } } @@ -106,7 +103,13 @@ mod tests { for column in map.values_mut() { Arc::make_mut(column).light_loaded = true; } - crate::light::LightWorld::set_light(&mut map, 0, 0, 0, 0); + crate::light::LightWorld::set_section_light( + &mut map, + 0, + 0, + 0, + crate::chunk::Light::Uniform(0), + ); assert_eq!(inserted, map.membership_revision()); map.remove(&(0, 0)); map.insert((1, 0), chunk); diff --git a/crates/horizon-client/src/command_block.rs b/crates/horizon-client/src/command_block.rs index 942e11ab6..47f808932 100644 --- a/crates/horizon-client/src/command_block.rs +++ b/crates/horizon-client/src/command_block.rs @@ -35,6 +35,23 @@ impl Mode { Self::Redstone => "minecraft:command_block", } } + /// `Enum.ordinal`, which `ServerboundSetCommandBlockPacket` writes. + pub fn ordinal(self) -> i32 { + match self { + Self::Sequence => 0, + Self::Auto => 1, + Self::Redstone => 2, + } + } + /// The mode of a packet's ordinal; `handleSetCommandBlock` treats any + /// other value as a plain command block (its `default` branch). + pub fn from_ordinal(ordinal: i32) -> Self { + match ordinal { + 0 => Self::Sequence, + 1 => Self::Auto, + _ => Self::Redstone, + } + } /// `CycleButton`: the next value, wrapping round. pub fn next(self) -> Self { match self { diff --git a/crates/horizon-client/src/container_screen.rs b/crates/horizon-client/src/container_screen.rs index 77c7ad8aa..a7b1794c5 100644 --- a/crates/horizon-client/src/container_screen.rs +++ b/crates/horizon-client/src/container_screen.rs @@ -124,6 +124,18 @@ impl Clicks { self.skip_next_release = true; } + /// The screen that takes the pointer over starts with its own state: + /// `AbstractContainerScreen` holds `isQuickCrafting` and the drag it + /// belongs to on the screen, so a screen that opens (or closes) drops + /// them. A press whose release never arrived -- the pointer left the + /// window -- would otherwise keep the drag running, and `press` answers + /// `None` for every later press, so the quick move and the clicks go + /// dead on every screen after it. + pub fn cancel_drag(&mut self) { + self.quick_crafting = None; + self.skip_next_release = false; + } + /// `mouseClicked` (no double click): the `slotClicked` input it sends on /// `target`, if any. A press holding a stack starts a quick craft drag /// instead. `cloning` is `keyPickItem` with infinite materials. @@ -301,4 +313,35 @@ mod tests { Some(Input::Pickup) ); } + + /// #1737: a press whose release never arrives (the pointer left the + /// window) leaves `isQuickCrafting` set, and `press` answers `None` for + /// every later press, so the Shift quick move and the clicks on the + /// inventory go dead. The drag belongs to the screen that has it + /// (`AbstractContainerScreen` holds `isQuickCrafting`), so the screen + /// that takes the pointer over drops it and the quick move works again. + #[test] + fn a_lost_release_does_not_wedge_the_quick_move() { + let mut clicks = Clicks::default(); + let slot = Target::::Slot(3); + // Pressed with a stack carried: a quick craft drag starts, and its + // release never arrives. + assert_eq!(clicks.press(&slot, Button::Left, false, false, false), None); + assert!(clicks.quick_crafting().is_some()); + // The stuck drag swallows the next press: the Shift quick move stops + // working and the inventory stops answering. + assert_eq!(clicks.press(&slot, Button::Right, true, true, false), None); + // The screen that takes the pointer over starts with its own state. + clicks.cancel_drag(); + assert!(clicks.quick_crafting().is_none()); + // The quick move works again. + assert_eq!( + clicks.press(&slot, Button::Right, true, true, false), + Some(Input::QuickMove) + ); + assert_eq!( + clicks.press(&slot, Button::Left, true, false, false), + Some(Input::Pickup) + ); + } } diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 17dce93ab..16a7a273a 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -179,13 +179,14 @@ impl PlayerEffects { self.list.clear(); } /// The effects of a saved player (`Player.active_effects`: id, - /// duration, amplifier, ambient, visible). + /// duration, amplifier, ambient, particles visible). pub fn from_saved(saved: &[(String, i32, i32, bool, bool)]) -> Self { let mut effects = Self::default(); - for (id, duration, amplifier, ambient, _) in saved { + for (id, duration, amplifier, ambient, particles) in saved { if let Some(def) = brewing::effect(id) { let mut e = EffectInstance::new(def.id, *duration, *amplifier); e.ambient = *ambient; + e.visible = *particles; effects.add(e); } } diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 44f07dc82..14cd946c2 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -582,17 +582,21 @@ impl Experience { 7 + level * 2 } } - /// Returns true when a level was gained. - pub fn give(&mut self, points: i32) -> bool { - let start = self.level; + /// Returns the first multiple of 5 the player reached, where each level + /// gained would play the level-up sound (`Player.giveExperienceLevels`). + pub fn give(&mut self, points: i32) -> Option { + let mut sound_level = None; self.progress += points as f32 / Self::needed(self.level) as f32; self.total = self.total.saturating_add(points).max(0); while self.progress >= 1.0 { self.progress = (self.progress - 1.0) * Self::needed(self.level) as f32; self.level += 1; + if self.level % 5 == 0 { + sound_level.get_or_insert(self.level); + } self.progress /= Self::needed(self.level) as f32; } - self.level > start + sound_level } } /// A painting (`Painting`, a `HangingEntity`): the block it hangs in, the diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 79e11719f..2541a4b35 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -203,7 +203,7 @@ fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, // lit texture, then the lightmap, then the glint and fog. color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a); color *= in.light_color; - if in.overlay == 7u || in.overlay == 8u { + if in.overlay == 7u || in.overlay == 8u || in.overlay == 33u { // Enchantment glint (overlay 7, 8 with the hurt tint): the purple // enchanted_glint sheen drifting diagonally over the item's shape. let px = in.uv * vec2(textureDimensions(atlas)); @@ -219,9 +219,22 @@ fn crumbling_uv(uv: vec2, packed_origin: vec2, sprite_size: vec2, return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a); } +fn celestial_color(in: Out) -> vec4 { + return textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; +} @fragment fn fs_celestial(in: Out) -> @location(0) vec4 { - let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; - return color; + return celestial_color(in); +} + +// The sky's celestial pass (sun, moon, the End sky): fs_celestial's light, +// premultiplied for an additive (one, one) blend, and as alpha how much of it +// the texel adds, which the blend takes off the frame's alpha. HDR output +// (hdr.wgsl) lifts only where that left it low: the sun's and moon's discs, not +// the dark rest of their quads or the dim End sky. +@fragment fn fs_sky_celestial(in: Out) -> @location(0) vec4 { + let color = celestial_color(in); + let added = color.rgb * color.a; + return vec4(added, smoothstep(0.1, 0.3, max(added.r, max(added.g, added.b)))); } // RenderPipelines.WATER_MASK: depth only (the pipeline masks the colour off). diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index c49af48c9..c65f35f5b 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -187,6 +187,31 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { map.remove(&horizon_world::nbt::JavaString::from(key)); } } + // LivingEntity.addAdditionalSaveData: `active_effects` only when there are + // any (MobEffectInstance.CODEC; a mob's effects are never ambient, and one + // given with `hideParticles` shows neither particles nor its icon). + if m.extra.effects.is_empty() { + map.remove(&horizon_world::nbt::JavaString::from("active_effects")); + } else { + let effects = m + .extra + .effects + .iter() + .map(|&(effect, duration, amplifier)| { + let shown = !m.extra.hidden_effects.contains(&effect); + let mut e = vec![ + ("id", string(crate::brewing::namespaced(effect))), + ("amplifier", Tag::Byte(amplifier.clamp(0, 255) as u8 as i8)), + ("duration", Tag::Int(duration)), + ]; + if !shown { + e.push(("show_particles", Tag::Byte(0))); + } + e.push(("show_icon", Tag::Byte(i8::from(shown)))); + Tag::compound(e) + }); + map.insert("active_effects".into(), Tag::List(effects.collect())); + } map.insert( "Invulnerable".into(), Tag::Byte(i8::from(m.invulnerable_flag)), @@ -244,7 +269,51 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { if is_animal(id) { map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); } + let species = m.species(); + if let Some((_, variant)) = + crate::mobs::finalize::species_variant_component(species, m.extra.variant) + { + map.insert("variant".into(), string(&variant)); + } + if species == crate::mobs::Species::Chicken { + map.insert("EggLayTime".into(), Tag::Int(m.extra.egg_time)); + } + let sounds = crate::mobs::finalize::sound_variants(species); + if !sounds.is_empty() { + let sound = m.extra.sound_variant.and_then(|i| sounds.get(i as usize)); + let sound = sound.copied().unwrap_or("classic"); + map.insert( + "sound_variant".into(), + string(&format!("minecraft:{sound}")), + ); + } match id { + // Fox.addAdditionalSaveData; Horizon models only the type. + "minecraft:fox" => { + let kind = if m.extra.variant == 1 { "snow" } else { "red" }; + map.insert("Type".into(), string(kind)); + for (key, value) in [ + ("Trusted", Tag::List(Vec::new())), + ("Sleeping", Tag::Byte(0)), + ("Sitting", Tag::Byte(0)), + ("Crouching", Tag::Byte(0)), + ] { + map.entry(key.into()).or_insert(value); + } + } + "minecraft:rabbit" => { + map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant))); + map.entry("MoreCarrotTicks".into()).or_insert(Tag::Int(0)); + } + "minecraft:goat" => { + map.insert( + "IsScreamingGoat".into(), + Tag::Byte(i8::from(m.extra.screaming)), + ); + let [left, right] = m.extra.lost_horns; + map.insert("HasLeftHorn".into(), Tag::Byte(i8::from(!left))); + map.insert("HasRightHorn".into(), Tag::Byte(i8::from(!right))); + } "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { map.entry(key.into()).or_insert(value); @@ -260,10 +329,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::CAT_VARIANTS[(m.extra.variant as usize).min(10)]; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:wolf" => { if let Some(owner) = m.extra.owner { @@ -273,10 +338,6 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { } map.insert("Sitting".into(), Tag::Byte(i8::from(m.extra.sitting))); map.insert("CollarColor".into(), Tag::Byte(m.extra.color as i8)); - let variant = crate::mobs::tame::WOLF_VARIANTS[(m.extra.variant as usize).min(8)].0; - map.insert("variant".into(), string(&format!("minecraft:{variant}"))); - map.entry("sound_variant".into()) - .or_insert_with(|| string("minecraft:classic")); } "minecraft:piglin" | "minecraft:piglin_brute" | "minecraft:hoglin" => { // Only Piglin.addAdditionalSaveData writes CannotHunt. @@ -311,6 +372,10 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { | "minecraft:trader_llama" => { map.insert("Tame".into(), Tag::Byte(i8::from(m.extra.tame))); map.insert("Temper".into(), Tag::Int(i32::from(m.extra.variant3))); + // AbstractHorse.addAdditionalSaveData; Horizon models neither. + for key in ["EatingHaystack", "Bred"] { + map.entry(key.into()).or_insert(Tag::Byte(0)); + } if let Some(owner) = m.extra.owner { map.insert("Owner".into(), Tag::IntArray(owner.to_vec())); } @@ -426,7 +491,36 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { crate::mobs::villager::write_nbt(m, map); } "minecraft:wandering_trader" => put_offers(map, m), - "minecraft:axolotl" => write_axolotl_memories(m, map), + "minecraft:axolotl" => { + write_axolotl_memories(m, map); + map.insert( + "Variant".into(), + Tag::Int(i32::from(m.extra.variant.min(4))), + ); + } + // Rabbit.addAdditionalSaveData (the legacy id; 99 is the killer bunny). + "minecraft:rabbit" => { + map.insert("RabbitType".into(), Tag::Int(i32::from(m.extra.variant))); + } + "minecraft:parrot" => { + map.insert( + "Variant".into(), + Tag::Int(i32::from(m.extra.variant.min(4))), + ); + } + "minecraft:salmon" => { + let size = SALMON_SIZES[usize::from(m.extra.variant).min(2)]; + map.insert("type".into(), string(size)); + } + // TropicalFish.addAdditionalSaveData: the packed variant. + "minecraft:tropical_fish" => { + let pattern = m.extra.variant.min(11); + let packed = i32::from(pattern >= 6) + | i32::from(pattern % 6) << 8 + | i32::from(m.extra.variant2 & 15) << 16 + | i32::from(m.extra.variant3 & 15) << 24; + map.insert("Variant".into(), Tag::Int(packed)); + } "minecraft:allay" => { // InventoryCarrier: the fetched stack; the liked player memory. let mut inv = Vec::new(); @@ -800,6 +894,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - add_modifier(&mut m, Attr::FollowRange, id, bonus, Op::AddMultipliedBase); } m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32); + // LivingEntity.setHealth clamps to the max health: a horse or llama is made + // with the type's and saved before it drops to the one it rolled. (Only + // the base is read here, so the clamp would cut a leader zombie's bonus.) + if crate::mobs::equine::is_equine(m.species()) { + m.health = m.health.min(m.attrs.max_health); + } m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32; // What it holds (equipment.mainhand / offhand), when saved. if let Some(eq) = tag.get("equipment") { @@ -854,6 +954,25 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.no_gravity = flag(tag, "NoGravity"); m.glowing = flag(tag, "Glowing"); m.ticks_frozen = number(tag.get("TicksFrozen")).unwrap_or(0) as i32; + // LivingEntity.readAdditionalSaveData: the saved `active_effects`, the last + // entry of an effect winning. + if let Some(Tag::List(effects)) = tag.get("active_effects") { + for e in effects { + let Some(def) = text(e.get("id")).and_then(|id| crate::brewing::effect(&id)) else { + continue; + }; + let effect = crate::brewing::namespaced(def.id); + let duration = number(e.get("duration")).unwrap_or(0) as i32; + let amplifier = number(e.get("amplifier")).unwrap_or(0) as i32; + m.extra.effects.retain(|x| x.0 != effect); + m.extra.effects.push((effect, duration, amplifier)); + // Details.CODEC: `show_particles` defaults to true. + m.extra.hidden_effects.retain(|h| *h != effect); + if number(e.get("show_particles")) == Some(0) { + m.extra.hidden_effects.push(effect); + } + } + } m.silent = flag(tag, "Silent"); m.invulnerable_flag = flag(tag, "Invulnerable"); if m.species() == crate::mobs::Species::Bat { @@ -935,20 +1054,45 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.vector[0] = 0.7; } } + if crate::mobs::finalize::species_variant_component(m.species(), 0).is_some() + && let Some(v) = text(tag.get("variant")) + { + m.extra.variant = crate::mobs::finalize::variant_index(m.species(), &v); + } + if m.species() == crate::mobs::Species::Chicken + && let Some(t) = number(tag.get("EggLayTime")) + { + m.extra.egg_time = t as i32; + } + if let Some(v) = text(tag.get("sound_variant")) { + let v = v.trim_start_matches("minecraft:"); + let sounds = crate::mobs::finalize::sound_variants(m.species()); + m.extra.sound_variant = sounds.iter().position(|n| *n == v).map(|i| i as u8); + } + match m.species() { + crate::mobs::Species::Fox => { + m.extra.variant = u8::from(text(tag.get("Type")).as_deref() == Some("snow")); + } + crate::mobs::Species::Rabbit => { + // Rabbit.Variant.byId: an unknown id is brown. + m.extra.variant = match number(tag.get("RabbitType")).unwrap_or(0) { + v @ (0..=5 | 99) => v as u8, + _ => 0, + }; + } + crate::mobs::Species::Goat => { + m.extra.screaming = flag(tag, "IsScreamingGoat"); + let horn = |key| number(tag.get(key)).is_some_and(|v| v == 0); + m.extra.lost_horns = [horn("HasLeftHorn"), horn("HasRightHorn")]; + } + _ => {} + } if m.species() == crate::mobs::Species::Cat { m.extra.owner = crate::save::uuid_from_tag(tag.get("Owner")); m.extra.tame = m.extra.owner.is_some(); m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::CAT_VARIANTS - .iter() - .position(|n| *n == v) - .unwrap_or(0) as u8; - } } if m.species() == crate::mobs::Species::Wolf { let health = m.health; @@ -959,14 +1103,6 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.sitting = flag(tag, "Sitting"); m.extra.color = number(tag.get("CollarColor")).map_or(crate::mobs::tame::RED, |c| (c as u8) & 15); - if let Some(Tag::String(v)) = tag.get("variant") { - let v = v.to_string().unwrap_or_default(); - let v = v.trim_start_matches("minecraft:"); - m.extra.variant = crate::mobs::tame::WOLF_VARIANTS - .iter() - .position(|(n, _)| *n == v) - .unwrap_or(0) as u8; - } } if matches!( m.species(), @@ -985,6 +1121,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - if m.species() == crate::mobs::Species::Axolotl { restore_axolotl_memories(&mut m, tag); } + read_variant(&mut m, tag); m.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i32; m.air = number(tag.get("Air")).unwrap_or(300) as i32; if m.species() == crate::mobs::Species::Allay { @@ -2166,6 +2303,41 @@ fn write_axolotl_memories(m: &Mob, map: &mut Compound) { } } } +/// The variant tags `Axolotl`, `Rabbit`, `Parrot`, `Salmon` and +/// `TropicalFish` read; a missing tag is the default variant (a medium +/// salmon, otherwise index 0). +fn read_variant(m: &mut Mob, tag: &Tag) { + use crate::mobs::Species as S; + let int = |key| number(tag.get(key)).unwrap_or(0) as i32; + match m.species() { + S::Axolotl | S::Parrot => m.extra.variant = int("Variant").clamp(0, 4) as u8, + // Rabbit.Variant.LEGACY_CODEC: an unknown id is brown. + S::Rabbit => { + m.extra.variant = match int("RabbitType") { + v @ (0..=5 | 99) => v as u8, + _ => 0, + } + } + S::Salmon => { + m.extra.variant = text(tag.get("type")) + .and_then(|t| SALMON_SIZES.iter().position(|v| *v == t)) + .unwrap_or(1) as u8; + } + S::TropicalFish => { + let packed = int("Variant"); + let (size, index) = (packed & 0xFF, (packed >> 8) & 0xFF); + // TropicalFish.Pattern.byId: an unknown id is a kob. + m.extra.variant = if size <= 1 && index < 6 { + (size * 6 + index) as u8 + } else { + 0 + }; + m.extra.variant2 = ((packed >> 16) & 15) as u8; + m.extra.variant3 = ((packed >> 24) & 15) as u8; + } + _ => {} + } +} fn restore_axolotl_memories(m: &mut Mob, tag: &Tag) { let memories = tag.get("Brain").and_then(|b| b.get("memories")); let ttl = memories @@ -2567,6 +2739,123 @@ mod sheep_nbt_tests { let back = mob_from_nbt(&tag, &types, 2).unwrap(); assert_eq!((back.extra.color, back.extra.sheared), (14, true)); } + + #[test] + fn farm_animals_keep_their_variant_and_sound_variant() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let mut m = Mob::new( + 1, + types["minecraft:pig"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!( + text(tag.get("variant")).as_deref(), + Some("minecraft:temperate") + ); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:classic") + ); + // Spawned in a warm biome with the mini sounds. + (m.extra.variant, m.extra.sound_variant) = (1, Some(2)); + let tag = mob_to_nbt(&m, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:warm")); + assert_eq!( + text(tag.get("sound_variant")).as_deref(), + Some("minecraft:mini") + ); + let back = mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!((back.extra.variant, back.extra.sound_variant), (1, Some(2))); + let mut hen = Mob::new( + 3, + types["minecraft:chicken"].clone(), + Vec3::new(0.0, 4.0, 0.0), + 0.0, + ); + (hen.extra.variant, hen.extra.egg_time) = (2, 7795); + let tag = mob_to_nbt(&hen, [1, 2, 3, 4], None); + assert_eq!(text(tag.get("variant")).as_deref(), Some("minecraft:cold")); + let back = mob_from_nbt(&tag, &types, 4).unwrap(); + assert_eq!((back.extra.variant, back.extra.egg_time), (2, 7795)); + // The sound variants are indices into the registries finalizeSpawn draws from. + use crate::mobs::{Species, finalize}; + let registries = finalize::SpawnRegistries::load(&root); + for (species, registry) in [ + (Species::Pig, ®istries.pig_sound), + (Species::Cow, ®istries.cow_sound), + (Species::Chicken, ®istries.chicken_sound), + (Species::Cat, ®istries.cat_sound), + (Species::Wolf, ®istries.wolf_sound), + ] { + assert_eq!( + finalize::sound_variants(species), + registry.names, + "{species:?}" + ); + } + } + + #[test] + fn foxes_rabbits_and_goats_keep_their_kind() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("items.json").exists() { + return; + } + let data = crate::mobs::MobTypes::load(&root).unwrap(); + let types: HashMap> = data + .types + .iter() + .map(|(k, v)| (k.clone(), Arc::new(v.clone()))) + .collect(); + let new = |kind: &str| Mob::new(1, types[kind].clone(), Vec3::new(0.0, 4.0, 0.0), 0.0); + let round_trip = |m: &Mob| { + let tag = mob_to_nbt(m, [1, 2, 3, 4], None); + (mob_from_nbt(&tag, &types, 2).unwrap(), tag) + }; + let mut fox = new("minecraft:fox"); + fox.extra.variant = 1; + let (back, tag) = round_trip(&fox); + assert_eq!(text(tag.get("Type")).as_deref(), Some("snow")); + assert_eq!(number(tag.get("Sleeping")), Some(0)); + assert_eq!(back.extra.variant, 1); + let mut rabbit = new("minecraft:rabbit"); + rabbit.extra.variant = 4; + let (back, tag) = round_trip(&rabbit); + assert_eq!(number(tag.get("RabbitType")), Some(4)); + assert_eq!(back.extra.variant, 4); + let mut goat = new("minecraft:goat"); + (goat.extra.screaming, goat.extra.lost_horns) = (true, [false, true]); + let (back, tag) = round_trip(&goat); + assert_eq!(number(tag.get("HasRightHorn")), Some(0)); + assert_eq!( + (back.extra.screaming, back.extra.lost_horns), + (true, [false, true]) + ); + // A goat saved without horn flags has both, as vanilla reads it. + let bare = Tag::compound([ + ("id", string("minecraft:goat")), + ("Pos", doubles(&[0.5, 64.0, 0.5])), + ]); + assert_eq!( + mob_from_nbt(&bare, &types, 3).unwrap().extra.lost_horns, + [false; 2] + ); + } } #[cfg(test)] diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index d0e8c8499..2bb712612 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -889,12 +889,17 @@ impl Font { if s.contains('§') { return self.width_text(&Text::legacy(s)); } - s.chars().map(|c| self.glyph(c).advance).sum::().ceil() + crate::bidi::visual_str(s) + .chars() + .map(|c| self.glyph(c).advance) + .sum::() + .ceil() } /// Font.width of a component: `§` codes in the spans are formatting, - /// not glyphs. + /// not glyphs. Right-to-left text is measured as it is drawn, shaped. pub fn width_text(&self, t: &Text) -> f32 { - t.resolved() + let t = t.resolved(); + crate::bidi::visual(&t) .chars() .map(|(c, s)| self.advance(c, s)) .sum::() diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..bf2434965 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -63,7 +63,6 @@ mod frames; mod friends; mod functions; mod game_mode; -mod game_rules_screen; mod gamemode_switcher; mod ghasts; mod golems; @@ -157,6 +156,7 @@ mod scoreboard; mod screens; mod sculk; mod sculk_fixture; +mod server_links; mod server_mods; mod server_packs; mod server_travel; @@ -508,6 +508,12 @@ enum Screen { Friends, /// CommandBlockEditScreen (game/command_blocks.rs). CommandBlock, + /// ServerLinksDialogScreen: a server's links (game/server_links.rs). + ServerLinks, + /// ConfirmLinkScreen for a server link (game/server_links.rs). + ConfirmLink, + /// DialogScreen.WarningScreen: the note about custom screens. + DialogWarning, /// WinScreen: the end poem and the credits (game/win.rs). Win, /// A `ui` mod's own screen, or its settings page from Options > Mods @@ -1675,6 +1681,7 @@ struct Game<'a> { guest_use: Option, /// Level events of this tick for the guests, and the guest acting now. lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_cushion_breaks: Vec<(horizon_world::registry::BlockStateId, [f64; 3])>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. lan_block_events: Vec<([i32; 3], i32, i32, u32)>, @@ -1698,6 +1705,9 @@ struct Game<'a> { /// The acting guest's cooldowns, as (item, ticks): their packet needs the /// hub's item registry, which the guest's turn does not hold. guest_cooldowns: Vec<(Arc, i32)>, + /// The acting guest's own entity events (`ServerPlayer.connection.send`), + /// sent with their entity id, which the guest's turn does not hold. + guest_entity_events: Vec, /// `broadcastToAdmins` lines a guest's command queued, sent once it /// returns: the line, whether operators get it and whether the console /// logs it. @@ -1732,6 +1742,8 @@ struct Game<'a> { restore_player_state: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, + /// The Server Links screens' state (game/server_links.rs). + links_ui: server_links::LinksUi, camera_type: perspective::CameraType, fangs: fangs::FangState, /// The local player as a model (third person, the inventory). @@ -2037,9 +2049,11 @@ impl Game<'_> { /// item in use (LocalPlayer.modifyInput), the helmet's Respiration /// (decreaseAirSupply), the wings, leather boots on powder snow /// (PowderSnowBlock.canEntityWalkOnPowderSnow), freeze-immune wear - /// (LivingEntity.canFreeze) and the dimension's FAST_LAVA. + /// (LivingEntity.canFreeze), the dimension's FAST_LAVA and the sleeping + /// pose. pub(crate) fn sync_player_body(&mut self) { let glider = self.glider_worn(); + let sleeping = self.sleeping.is_some(); let item_use_speed = self .using .and_then(|(slot, _)| { @@ -2067,6 +2081,7 @@ impl Game<'_> { player.item_use_speed = item_use_speed; player.respiration = respiration; player.glider = glider; + let _ = player.set_sleeping(sleeping); player.leather_boots = leather_boots; player.freeze_immune = freeze_immune; player.fluids.fast_lava = self.dim == Dim::Nether; @@ -2990,6 +3005,16 @@ impl Game<'_> { data, } => self.sculk_charge_event(pos, data), LevelEvent::LevelEvent { id: 3007, pos, .. } => self.shriek_event(pos), + // LevelEventHandler 2019 and 2020: the crack on a face of the + // block being mined, with its hit sound for 2020. + LevelEvent::LevelEvent { + id: id @ (2019 | 2020), + pos, + data, + } => { + let face = horizon_core::geometry::Direction::ALL[data.clamp(0, 5) as usize]; + self.breaking_block_effects([pos.x, pos.y, pos.z], face.normal(), id == 2020); + } LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } @@ -3009,6 +3034,11 @@ impl Game<'_> { pos, data, } => self.dragon_egg_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2016, + pos, + data, + } => self.shulker_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2017, pos, @@ -4202,6 +4232,7 @@ impl Game<'_> { if &*stack.item == "minecraft:spyglass" { // SpyglassItem.USE_DURATION, then finishUsingItem. if ticks + 1 >= 1200 { + self.send_use_item_complete(); self.stop_spyglass(); self.using = None; } else { @@ -4223,6 +4254,7 @@ impl Game<'_> { } if ticks >= duration { self.using = None; + self.send_use_item_complete(); // ItemStack.finishUsingItem's applyAfterUseComponentSideEffects. self.apply_use_cooldown(&stack); self.finish_consuming(&info, consumable, &stack); @@ -4241,6 +4273,17 @@ impl Game<'_> { _ => {} } } + /// `ServerPlayerGameMode.tick` while a player digs: level event 2020 every + /// fourth tick since the START (the hit sound), else 2019 (the crack only), + /// for everyone around, the digger included (`levelEvent(null, ...)`). + fn destroy_progress_event(&mut self, pos: [i32; 3], face: [i32; 3], ticks: u32) { + let id = if ticks.is_multiple_of(4) { 2020 } else { 2019 }; + let direction = horizon_core::geometry::Direction::ALL + .iter() + .position(|d| d.normal() == face) + .unwrap_or(1); + self.level_event_at(id, pos, direction as i32); + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; @@ -4284,6 +4327,11 @@ impl Game<'_> { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); let facts = self.res.facts().get(state); if facts.hardness < 0.0 { + // The server still counts its destroy ticks on an unbreakable block. + let m = self.mining.as_mut().ok_or("mining")?; + m.ticks += 1; + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); return Ok(()); } // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. @@ -4314,26 +4362,15 @@ impl Game<'_> { } else { speed / facts.hardness / if harvest { 30.0 } else { 100.0 } }; - let hit_sound = facts.sounds.clone(); self.swing_arm(); let m = self.mining.as_mut().ok_or("mining")?; m.progress += progress; m.ticks += 1; - let crack = (m.pos, hit.face); - if m.ticks % 4 == 1 { - let c = [ - f64::from(m.pos[0]) + 0.5, - f64::from(m.pos[1]) + 0.5, - f64::from(m.pos[2]) + 0.5, - ]; - self.audio.play( - &hit_sound.hit, - Some(c), - (hit_sound.volume + 1.0) / 8.0, - hit_sound.pitch * 0.5, - ); + // An instant break at START sends no destroy events. + if m.progress < 1.0 || m.ticks > 1 { + let (pos, ticks) = (m.pos, m.ticks); + self.destroy_progress_event(pos, hit.face, ticks); } - self.crack_particle(crack.0, crack.1, state); let m = self.mining.as_mut().ok_or("mining")?; // ServerPlayerGameMode breaks a player's block at once only when it is instant (START's // insta-mine); otherwise it waits for the client's STOP_DESTROY_BLOCK @@ -4653,7 +4690,6 @@ impl Game<'_> { player.dimensions.eye_height }; self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; - let crouching = player.pose == horizon_client::pose::Pose::Crouching; // `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the // glide's wear): both draw from the level random. if let Some((at, velocity)) = self.tick_soul_speed() { @@ -4689,10 +4725,12 @@ impl Game<'_> { MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, feet), MotionEvent::Emission { state, in_water, .. - } if !crouching => { + } => { let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, - // muffled under the swim sound in water. + // muffled under the swim sound in water. Whether it plays is + // Player.getMovementEmission's call (shift on the ground), + // not the pose: a forced crouch still steps. let (volume, pitch) = if in_water { (sounds.volume * 0.05, sounds.pitch * 0.8) } else { @@ -4704,26 +4742,21 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.swim", Some(feet), volume, pitch); } + MotionEvent::Chime { volume, pitch } => { + self.audio.play( + "minecraft:block.amethyst_block.chime", + Some(feet), + volume, + pitch, + ); + } MotionEvent::Drown => { - // LivingEntity.makeDrownParticles: eight bubbles moving - // with the player. - use horizon_client::particles::{ParticleOptions, ParticleType}; - for _ in 0..8 { - let mut triangle = || { - let r = self.particles.random(); - r.next_double() - r.next_double() - }; - let p = [ - feet[0] + triangle(), - feet[1] + triangle(), - feet[2] + triangle(), - ]; - self.particles.add( - &ParticleOptions::simple(ParticleType::Bubble), - p, - player_velocity, - ); + // The guests see the entity event 67 too. + if let Some(host) = &self.lan { + host.hub + .entity_event(host.host_entity, combat::DROWN_EVENT, feet); } + self.drown_particles(feet, player_velocity); } MotionEvent::BubbleColumnParticle { bubble, position } => { // ServerLevel.sendParticles: SPLASH (speed 1) or BUBBLE @@ -4826,6 +4859,7 @@ impl Game<'_> { } } self.powder_snow_fire()?; + self.rain_extinguish_in_frame(); self.tick_totem(); let Some(player) = self.player.as_mut() else { return Ok(()); @@ -5098,6 +5132,9 @@ impl Game<'_> { | Screen::Advancements | Screen::WorldOptions | Screen::Friends + | Screen::ServerLinks + | Screen::ConfirmLink + | Screen::DialogWarning | Screen::CommandBlock ) || self.book.is_some() || self.win_screen_pauses()) @@ -5119,10 +5156,13 @@ impl Game<'_> { if capture && !self.focused { return; } - if capture { - // The inventory's screens are behind us: no drag survives them. - self.reset_inventory_clicks(); - } else { + // The container screen's press state belongs to the screen: a screen + // that takes the pointer over starts with its own state, as + // `AbstractContainerScreen` does, so a press whose release never + // arrived (the pointer left the window) cannot wedge the next + // screen's quick move and clicks. + self.reset_inventory_clicks(); + if !capture { self.stop_mining(); } // The real pointer takes over from an agent's. @@ -5581,6 +5621,9 @@ impl Game<'_> { Screen::Advancements => self.draw_advancements(&mut batch), Screen::WorldOptions => self.draw_world_options(&mut batch), Screen::Friends => self.draw_friends_screen(&mut batch), + Screen::ServerLinks => self.draw_server_links(&mut batch), + Screen::ConfirmLink => self.draw_confirm_link(&mut batch), + Screen::DialogWarning => self.draw_dialog_warning(&mut batch), Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::Inventory => { self.draw_inventory(&mut batch); @@ -5968,12 +6011,14 @@ impl Game<'_> { } } /// `AbstractContainerScreen` keeps `isQuickCrafting` and the drag it - /// belongs to on the screen; Horizon keeps them on the game, so they are - /// dropped when a screen closes. A press whose release never reaches the - /// screen (the pointer left the window, or the screen closed first) would + /// belongs to on the screen. Horizon keeps both on `Game` (`inv_clicks`, + /// `inv_drag`, `last_inv_click`), so they are dropped when the pointer + /// changes hands: a screen that opens or closes starts with its own + /// state, and a press whose release never reached the screen -- the + /// pointer left the window, or the screen closed first -- would /// otherwise leave every later press on every later screen swallowed. pub(super) fn reset_inventory_clicks(&mut self) { - self.inv_clicks = Default::default(); + self.inv_clicks.cancel_drag(); self.inv_drag = None; self.last_inv_click = None; } @@ -8050,11 +8095,6 @@ impl Game<'_> { let sweep = self.sweep_attack_position(scale, crit); let (knockback, knockback_attack) = self.extra_knockback(&target_kind, scale); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } let player = self.player.as_ref(); let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); if knockback_attack { @@ -8164,6 +8204,13 @@ impl Game<'_> { } } self.weapon_hit(index); + // Player.attack: causeFoodExhaustion(0.1F) only when the hit hurt + // (inside `if (wasHurt)`), after damageStatsAndHearts. + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } } else { self.audio .play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0); @@ -8727,6 +8774,10 @@ impl Game<'_> { } self.lan_close(false); self.save_game()?; + if let Some(mut remote) = self.remote.take() { + // Minecraft.disconnect closes the connection, so the host sees a clean leave. + remote.session.disconnect(); + } self.saved_for_exit = true; Ok(()) } @@ -9710,16 +9761,13 @@ impl Game<'_> { /// sound every fifth level (at most every 100 ticks). pub(super) fn give_orb_points(&mut self, gained: u32) { let at = self.eye_position(); - if self.experience.give(gained as i32) - && self.experience.level % 5 == 0 + // Player.giveExperienceLevels runs per level, so the first multiple of 5 + // crossed plays the sound (and starts the cooldown for the rest). + if let Some(level) = self.experience.give(gained as i32) && self.ticks > self.last_level_up + 100 { self.last_level_up = self.ticks; - let volume = if self.experience.level > 30 { - 1.0 - } else { - self.experience.level as f32 / 30.0 - }; + let volume = if level > 30 { 1.0 } else { level as f32 / 30.0 }; self.audio .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); } @@ -9784,7 +9832,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); self.player_projectile_shot(); let pitch = 1.0 / (self.world.random.next_float() * 0.4 + 1.2) + power * 0.5; self.audio @@ -10089,6 +10137,14 @@ impl Game<'_> { }; Some(t < 0.15) } + /// `Level.isRainingAt`: it rains, the sky light is 15, nothing that stops + /// motion is above, and the biome's precipitation there is rain. + fn raining_at(&self, p: BlockPos) -> bool { + self.world.weather.levels(1.0).0 > 0.2 + && self.world.light(p.x, p.y, p.z) >> 4 == 15 + && self.rain_height(p.x, p.z) <= p.y + && self.precipitation(p.x, p.y, p.z) == Some(false) + } /// `getHeight(Heightmap.Types.MOTION_BLOCKING, x, z)`: one above the /// highest block in `blocks_motion_in_heightmap` or holding a fluid. fn rain_height(&self, x: i32, z: i32) -> i32 { @@ -10125,12 +10181,15 @@ impl Game<'_> { } else { ("minecraft:weather.rain", 0.2, 1.0) }; - self.audio.play( - name, - Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), - volume, - pitch, - ); + // The Horizon Weather option off silences the rain too. + if self.settings.horizon.weather { + self.audio.play( + name, + Some([f64::from(x) + 0.5, f64::from(top), f64::from(z) + 0.5]), + volume, + pitch, + ); + } } } } @@ -10673,6 +10732,9 @@ impl Game<'_> { let level = &mut self.level; level.creative = self.creative; level.game_mode = mode; + // PrimaryLevelData.setDifficulty: /difficulty and the options button change it. + level.difficulty = + horizon_client::title::DIFFICULTIES[usize::from(self.ui.difficulty) & 3].into(); level.time = self.world.game_time; level.weather = self.world.weather; level.day_time = self.world.day_time; @@ -10948,7 +11010,11 @@ impl Game<'_> { let debug_crosshair = horizon_client::gizmos::camera_relative(&crosshair.on_top, at, view); // LevelExtractor.extractBlockOutline: model translucency controls draw order. let mut outline_after_terrain = false; - let outline = if self.screen == Screen::Playing && !self.spectator() { + // GameRenderer.shouldRenderBlockOutline: not with the HUD hidden (F1), and only for a + // player who may build. Adventure players only get one with a CAN_BREAK or + // CAN_PLACE_ON item and spectators with a menu block; Horizon reads neither the + // components nor opens menus for spectators, so those never show it. + let outline = if self.screen == Screen::Playing && !self.ui.hide_gui && self.may_build() { self.pick() .map(|h| { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); @@ -11144,6 +11210,7 @@ impl Game<'_> { dark_disc: self.dark_disc(camera), outline, outline_after_terrain, + outline_high_contrast: self.settings.file.bool("highContrastBlockOutline"), debug_lines: &debug_lines, debug_lines_on_top: &debug_lines_on_top, debug_crosshair: &debug_crosshair, @@ -11203,7 +11270,7 @@ impl Game<'_> { }), ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), - night_vision: self.night_vision_intensity(), + night_vision: self.night_vision_intensity(alpha as f32), block_flicker: self.fog.block_light_flicker, boss_darken: self .boss_overlay @@ -11375,6 +11442,10 @@ impl Game<'_> { Screen::GameModeSwitcher => self.close_gamemode_switcher(false), Screen::Dead => {} Screen::Stats | Screen::Friends => self.screen = Screen::Paused, + Screen::ServerLinks => self.screen = Screen::Paused, + // ConfirmScreen.keyPressed: Escape answers no; both return to + // the Server Links screen they came from. + Screen::ConfirmLink | Screen::DialogWarning => self.screen = Screen::ServerLinks, Screen::Advancements => self.close_advancements(), Screen::WorldOptions => self.world_options_escape(), Screen::CommandBlock => self.close_command_block(), @@ -11443,8 +11514,10 @@ impl Game<'_> { // key.swapOffhand: on a server, ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND // (the server swaps the hands and sends both slots back; spectators can't). KeyCode::KeyF if self.screen == Screen::Playing && self.remote.is_some() => { - if !self.spectator() { - self.remote_swap_hands(); + if !self.spectator() + && let Some(r) = self.remote.as_mut() + { + r.pending_keys.push(key); } } KeyCode::KeyF if self.screen == Screen::Playing => { @@ -11541,11 +11614,28 @@ impl Game<'_> { } Ok(()) } - /// LOD Distance as far terrain uses it (`Graphics::lod_distance_on`). + /// LOD Distance and Far Detail Reduced as chosen: the player's LOD + /// Distance when it is on, else a mod's far terrain + /// (`render.set-far-terrain`). + fn far_terrain_choice(&self) -> (u32, bool) { + let g = &self.settings.horizon; + let reduced = g.far_detail == horizon_client::graphics::FarDetail::Reduced; + if g.lod_distance > 0 { + return (g.lod_distance, reduced); + } + match self.mod_far_terrain() { + Some(f) => (f.distance, reduced || f.reduced), + None => (0, reduced), + } + } + /// LOD Distance as far terrain uses it (`graphics::lod_distance_capped`). fn lod_distance(&self) -> u32 { + let (distance, _) = self.far_terrain_choice(); match &self.renderer { - Some(renderer) => self.settings.horizon.lod_distance_on(&renderer.info), - None => self.settings.horizon.lod_distance.min(1024), + Some(renderer) => { + horizon_client::graphics::lod_distance_capped(distance, &renderer.info) + } + None => distance.min(1024), } } /// Only enabled LOD worlds extend the renderer's range, never simulation. @@ -11566,7 +11656,7 @@ impl Game<'_> { } } fn prepare_lod(&mut self) { - let enabled = self.settings.horizon.lod_distance > 0 + let enabled = self.far_terrain_choice().0 > 0 && self.renderer.is_some() && self.player.is_some() && self.title.is_none() @@ -11663,6 +11753,7 @@ impl Game<'_> { { log::warn!("Horizon: failed to save unloaded chunks: {e}"); } + let (far_distance, far_reduced) = self.far_terrain_choice(); if let Some(renderer) = self.renderer.as_mut() { let g = &self.settings.horizon; let budgeted = g.chunk_updates > 0 || g.upload_budget_kib > 0; @@ -11716,12 +11807,10 @@ impl Game<'_> { } renderer.remove_columns(unloaded.iter().map(|c| (c.x, c.z))); if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { - let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info); + let lod_distance = + horizon_client::graphics::lod_distance_capped(far_distance, &renderer.info); lod.set_near_loading(self.streaming.busy()); - lod.set_reduced_detail( - self.settings.horizon.far_detail - == horizon_client::graphics::FarDetail::Reduced, - ); + lod.set_reduced_detail(far_reduced); // The covered columns change only with the complete ones and // the render area: rebuilt then, not every frame. let at = ( @@ -12055,6 +12144,9 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::WorldOptions && d != 0.0 { self.world_options_scroll(d); } + if self.screen == Screen::ServerLinks && d != 0.0 { + self.server_links_scroll(d); + } if self.screen == Screen::Advancements { self.advancements_scroll(scaled(raw_x) as f32, d); } @@ -12108,7 +12200,8 @@ impl ApplicationHandler for Game<'_> { let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { let clicked = t.click(self.cursor.0, self.cursor.1, (b.width, b.height)); t.press_field(atlas, self.cursor, (b.width, b.height), shift); - clicked + let rules = t.press_rules(atlas, self.cursor, (b.width, b.height)); + (clicked.0, clicked.1 || rules) }); self.save_title_options(); if sound { @@ -12246,6 +12339,15 @@ impl ApplicationHandler for Game<'_> { Screen::WorldOptions if pressed && button == MouseButton::Left => { self.world_options_click() } + Screen::ServerLinks if pressed && button == MouseButton::Left => { + self.server_links_click()? + } + Screen::ConfirmLink if pressed && button == MouseButton::Left => { + self.confirm_link_click() + } + Screen::DialogWarning if pressed && button == MouseButton::Left => { + self.dialog_warning_click()? + } Screen::WorldOptions if button == MouseButton::Left => { self.world_options_release() } @@ -12677,6 +12779,16 @@ impl ApplicationHandler for Game<'_> { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 + && self.pending_save.as_ref().is_none_or(|save| !save.quit) + { + // SIGTERM, SIGINT or SIGHUP: the shutdown hook's server halt, as a window close. + if let Err(error) = self.begin_closing_save(true) { + self.error = Some(error); + event_loop.exit(); + return; + } + } if self.pending_save.is_some() { match self.poll_closing_save() { Ok(true) => event_loop.exit(), @@ -13093,6 +13205,7 @@ impl<'a> Game<'a> { forced_hit: None, guest_use: None, lan_events: Vec::new(), + lan_cushion_breaks: Vec::new(), lan_block_events: Vec::new(), lan_entity_events: Vec::new(), lan_critical_hits: Vec::new(), @@ -13101,6 +13214,7 @@ impl<'a> Game<'a> { lan_acting: None, guest_packets: Vec::new(), guest_cooldowns: Vec::new(), + guest_entity_events: Vec::new(), lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, @@ -13127,6 +13241,7 @@ impl<'a> Game<'a> { restore_player_state: true, stats_ui: Default::default(), adv_ui: Default::default(), + links_ui: Default::default(), camera_type: Default::default(), fangs: Default::default(), player_model: None, @@ -13851,6 +13966,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { dark_disc: false, outline: Vec::new(), outline_after_terrain: false, + outline_high_contrast: false, debug_lines: &[], debug_lines_on_top: &[], debug_crosshair: &[], @@ -14163,6 +14279,11 @@ impl Loading { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if horizon_threads::stop_requests() > 0 { + // No world is open yet: nothing to save. + event_loop.exit(); + return; + } if let Err(error) = self.poll_menu_resources() { self.error = Some(error); event_loop.exit(); @@ -14440,6 +14561,9 @@ pub fn run() -> Result<()> { { horizon_client::heartbeat::start(); } + if options.execution_role.is_client() { + horizon_threads::catch_stop_signals(); + } let started = Instant::now(); horizon_client::spans::enable(options.spikes.is_some()); let vanilla_root = options.resources.clone(); diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index fa9dbf3c6..d99f32f24 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -419,6 +419,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", @@ -707,9 +710,12 @@ impl Game<'_> { // the recipe buttons of the page, page arrows, filter and tabs. let book = self.recipe_book_targets(); if !book.is_empty() { + let (open, filtering) = self.recipe_book_flags().unwrap_or_default(); v["recipe_book"] = json!({ "targets": book.iter().map(|t| t.rect).collect::>(), "known": self.recipe_book_known(), + "open": open, + "filtering": filtering, }); } v["slot_ids"] = json!( diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 6f92d7f55..7790a48f3 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -547,7 +547,7 @@ impl Game<'_> { }); } /// `Entity.isInRain`: rain at the block position or at the top of the box. - fn in_rain(&mut self, at: Vec3, top: f64) -> bool { + pub(super) fn in_rain(&mut self, at: Vec3, top: f64) -> bool { let p = BlockPos::new( at.x.floor() as i32, at.y.floor() as i32, diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 06dfab22d..7e80f6f58 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -862,7 +862,7 @@ impl Game<'_> { let a = alpha as f32; let range = super::entity_culling::default_range( glam::DVec3::new(WIDTH, HEIGHT, WIDTH), - self.settings.entity_distance, + self.view_scale(), ); for b in &self.boats { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 2f38dffd9..b09803e49 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -1009,9 +1009,12 @@ impl Game<'_> { } }; let indicator = |batch: &mut HudBatch, page: usize, count: usize| { - let text = tr("book.pageIndicator", "Page %s of %s") - .replacen("%s", &(page + 1).to_string(), 1) - .replacen("%s", &count.max(1).to_string(), 1); + // BookViewScreen.getPageNumberMessage: 26.3's en_us template is + // positional ("Page %1$s of %2$s"). + let text = horizon_protocol::text::format_java( + &tr("book.pageIndicator", "Page %1$s of %2$s"), + &[(page + 1).to_string(), count.max(1).to_string()], + ); let tw = HudBatch::text_width(atlas, &text); batch.text(atlas, &text, left + 148.0 - tw, top + 16.0, BLACK, false); }; diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 03174c009..94f7661b7 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -801,7 +801,11 @@ impl Game<'_> { 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); + // PrimaryLevelData: the difficulty comes back from level.dat's difficulty_settings. + self.ui.difficulty = horizon_client::title::DIFFICULTIES + .iter() + .position(|d| *d == self.level.difficulty) + .map_or(2, |i| i as u8); 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, _)) = @@ -826,9 +830,9 @@ impl Game<'_> { self.build_registries(); self.sync_rules(); } - /// Save the clock and the difficulty beside level.dat (Level.write saves - /// the game rules: a second writer of game_rules.dat could leave it with - /// the rules loaded when the world opened). + /// Save the clock beside level.dat (Level.write saves the game rules: a + /// second writer of game_rules.dat could leave it with the rules loaded + /// when the world opened). pub(super) fn save_world_state(&mut self) { if self.world_root.as_os_str().is_empty() { return; @@ -876,9 +880,6 @@ impl Game<'_> { if let Err(e) = horizon_client::save::write_dat(&path, root) { log::warn!("the world clocks were not written: {e}"); } - if let Err(e) = write_difficulty(&self.world_root, self.ui.difficulty) { - log::warn!("the difficulty was not written: {e}"); - } } /// Death message in chat (CombatTracker.getDeathMessage, as far as the /// cause is known to the client). @@ -988,34 +989,6 @@ pub fn screenshot_name(dir: &std::path::Path) -> String { 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(()) -} /// `IntegratedServer.getProfilePermissions` for the owner: `OWNER` (4) when /// commands are allowed, else `ALL` (0). diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index 2d6b75902..f69f1b695 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -1,7 +1,16 @@ //! The player's `CombatTracker`: the damage taken lately, who dealt it and //! where the player fell from, turned into the vanilla death message. use super::{Game, chat::PLAYER_NAME}; -use horizon_client::{health::HealthEvent, motion::MotionEvent, text::Text}; +use horizon_client::{ + health::HealthEvent, + motion::MotionEvent, + particles::{ParticleOptions, ParticleType}, + text::Text, +}; +use horizon_core::random::RandomSource; + +/// `EntityEvent.DROWN_PARTICLES`: broadcast with the drowning damage. +pub(super) const DROWN_EVENT: i8 = 67; struct Entry { damage_type: String, @@ -45,6 +54,38 @@ pub(super) struct CombatTracker { fall_before: f64, } impl Game<'_> { + /// `LivingEntity.makeDrownParticles`: eight bubbles around the entity, + /// moving with it. + pub(super) fn drown_particles(&mut self, at: [f64; 3], velocity: [f64; 3]) { + let bubble = ParticleOptions::simple(ParticleType::Bubble); + for _ in 0..8 { + let mut triangle = || { + let r = self.particles.random(); + r.next_double() - r.next_double() + }; + let p = [at[0] + triangle(), at[1] + triangle(), at[2] + triangle()]; + self.particles.add(&bubble, p, velocity); + } + } + /// Entity event 67 from a server, for this client's own player or an + /// entity it draws. + pub(super) fn remote_drown(&mut self, id: i32) { + let own = self.remote.as_ref().is_some_and(|r| r.entity_id == id); + let body = if own { + self.player.as_ref().map(|p| { + let (at, v) = (p.position, p.velocity); + ([at.x, at.y, at.z], [v.x, v.y, v.z]) + }) + } else { + self.mobs.iter().find(|m| m.id == id as u32).map(|m| { + let (at, v) = (m.position, m.velocity); + ([at.x, at.y, at.z], [v.x, v.y, v.z]) + }) + }; + if let Some((at, v)) = body { + self.drown_particles(at, v); + } + } /// The display name of a mob: its custom name or its type's name. pub(super) fn mob_display_name(&self, id: u32) -> Option { let m = self.mobs.iter().find(|m| m.id == id)?; @@ -82,8 +123,8 @@ impl Game<'_> { /// `LivingEntity.handleDamageEvent` for the player: the hurt sound of the /// source's `DamageEffects` (`Player.getHurtSound`). pub(super) fn player_hurt_sound(&mut self, sound: &str, at: [f64; 3]) { - let pitch = self.audio.hurt_pitch(); - self.audio.play(sound, Some(at), 1.0, pitch); + // Player.getVoicePitch: always 1.0. + self.audio.play(sound, Some(at), 1.0, 1.0); } /// `CombatTracker.recordDamage` for the motion events of this tick. pub(super) fn record_combat(&mut self, events: &[MotionEvent]) { diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 76fc6d48c..868346452 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -2,7 +2,7 @@ //! tick (`execute`, `executeChain`), `BaseCommandBlock.performCommand` //! through the command system with the block's output, and //! `CommandBlockEditScreen` with what `handleSetCommandBlock` does with it. -use super::{Game, Screen, commands::execute::Source}; +use super::{Game, Screen, commands::execute::Source, lan::LanHost}; use horizon_client::{ command_block::{self, CommandBlock, Mode}, containers::BlockEntity, @@ -12,6 +12,7 @@ use horizon_client::{ world::World, }; use horizon_core::position::BlockPos; +use horizon_protocol::packets::play::{self, Serverbound as S}; use horizon_world::{ chunk::BlockState, level::flags, @@ -35,6 +36,16 @@ pub(super) struct CommandBlockScreen { auto: bool, } +/// What `ServerboundSetCommandBlockPacket` carries. +struct CommandBlockEdit { + pos: Pos, + command: String, + track_output: bool, + mode: Mode, + conditional: bool, + auto: bool, +} + #[derive(Clone, Copy, PartialEq)] enum Button { Output, @@ -186,6 +197,18 @@ impl Game<'_> { pub(super) fn can_use_game_master_blocks(&self) -> bool { self.creative && self.ui.registries.permission >= 2 } + /// `CommandBlock.useWithoutItem` on a server's client, which opens the + /// screen itself (`Player.openCommandBlock`) while the server only + /// answers the click: the block at `pos`, when it is a command block the + /// player may edit. + pub(super) fn open_command_block_if_editable(&mut self, pos: Pos) { + let is_command_block = self + .block_state_at(pos) + .is_some_and(|state| Mode::of_block(&state.name).is_some()); + if is_command_block && self.can_use_game_master_blocks() { + self.open_command_block(pos); + } + } fn command_block(&self, pos: Pos) -> Option<&CommandBlock> { match self.world.block_entities.get(&pos)? { BlockEntity::CommandBlock(c) => Some(c), @@ -572,12 +595,66 @@ impl Game<'_> { s.command.insert_text(&allowed); } } - /// `ServerGamePacketListenerImpl.handleSetCommandBlock`. + /// The edit screen's Done: a server's client sends the packet, the + /// window's own world applies it (`handleSetCommandBlock`). fn set_command_block(&mut self, s: &CommandBlockScreen) { if !self.can_use_game_master_blocks() { self.system_message(Text::translate("advMode.notAllowed", &[])); return; } + let edit = CommandBlockEdit { + pos: s.pos, + command: s.command.value.clone(), + track_output: s.track_output, + mode: s.mode, + conditional: s.conditional, + auto: s.auto, + }; + if self.remote.is_some() { + self.send(S::SetCommandBlock(play::SetCommandBlock { + pos: [edit.pos.0, edit.pos.1, edit.pos.2], + command: edit.command, + mode: edit.mode.ordinal(), + flags: i8::from(edit.track_output) + | (i8::from(edit.conditional) << 1) + | (i8::from(edit.auto) << 2), + })); + } else { + self.apply_command_block(&edit); + } + } + /// `ServerGamePacketListenerImpl.handleSetCommandBlock` for a guest: the + /// block is edited only by a creative player with game master commands. + pub(super) fn lan_set_command_block( + &mut self, + host: &mut LanHost, + conn: u32, + p: play::SetCommandBlock, + ) { + let Some(g) = host.hub.guest(conn) else { + return; + }; + let allowed = g.creative() && g.permission >= 2; + let edit = CommandBlockEdit { + pos: (p.pos[0], p.pos[1], p.pos[2]), + command: p.command, + track_output: p.flags & 1 != 0, + mode: Mode::from_ordinal(p.mode), + conditional: p.flags & 2 != 0, + auto: p.flags & 4 != 0, + }; + self.as_guest(host, conn, |game| { + if allowed { + game.apply_command_block(&edit); + // BaseCommandBlock.onUpdated: the clients get the new command. + game.mark_block_entity_updated(edit.pos); + } else { + game.system_message(Text::translate("advMode.notAllowed", &[])); + } + }); + } + /// What `handleSetCommandBlock` does once the player may edit the block. + fn apply_command_block(&mut self, s: &CommandBlockEdit) { let pos = s.pos; let registry = self.pack.assets.registry; let Some(current) = self.block_state_at(pos) else { @@ -609,7 +686,7 @@ impl Game<'_> { } let _ = self.process_level_events(); } - let command = s.command.value.clone(); + let command = s.command.clone(); let Some(c) = command_block_mut(&mut self.world, pos) else { return; }; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index f308cfec6..d3c40c3eb 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -42,9 +42,10 @@ pub(super) enum Target { Guest(u32), Mob(u32), Item(u32), - Orb(usize), - /// By index in `creatures.projectiles`. - Projectile(usize), + /// An experience orb, by its entity id. + Orb(u32), + /// A projectile, by its entity id. + Projectile(u32), Stand(u32), Frame(u32), Painting(u32), @@ -53,6 +54,10 @@ pub(super) enum Target { /// An entity of a type Horizon does not simulate (markers, displays, /// interactions...): kept as its saved data at a position. Other(u32), + /// An End crystal, by its entity id (`minecraft:end_crystal`). + Crystal(u32), + /// The Ender Dragon, by its entity id (`minecraft:ender_dragon`). + Dragon(u32), } /// An entity of a type Horizon does not simulate: its compound lives in the /// entity memory (`persist.raw`), its position and rotation here. @@ -340,14 +345,16 @@ impl Game<'_> { .iter() .find(|i| i.id == id) .map(|i| [i.position.x, i.position.y, i.position.z]), - Target::Orb(i) => self + Target::Orb(id) => self .orbs - .get(i) + .iter() + .find(|o| o.id == id) .map(|o| [o.position.x, o.position.y, o.position.z]), - Target::Projectile(i) => self + Target::Projectile(id) => self .creatures .projectiles - .get(i) + .iter() + .find(|a| a.id == id) .map(|a| [a.position.x, a.position.y, a.position.z]), Target::Stand(id) => self .armor_stands @@ -385,6 +392,16 @@ impl Game<'_> { .iter() .find(|o| o.id == id) .map(|o| [o.position.x, o.position.y, o.position.z]), + Target::Crystal(id) => self + .crystals + .iter() + .find(|c| c.id == id) + .map(|c| [c.position.x, c.position.y, c.position.z]), + Target::Dragon(id) => self + .dragon + .as_ref() + .filter(|d| d.id == id) + .map(|d| [d.position.x, d.position.y, d.position.z]), } } pub(super) fn target_type(&self, t: Target) -> String { @@ -399,10 +416,11 @@ impl Game<'_> { }), Target::Item(_) => "minecraft:item".into(), Target::Orb(_) => "minecraft:experience_orb".into(), - Target::Projectile(i) => self + Target::Projectile(id) => self .creatures .projectiles - .get(i) + .iter() + .find(|p| p.id == id) .map_or_else(String::new, |p| p.kind.id().into()), Target::Stand(_) => "minecraft:armor_stand".into(), Target::Frame(id) => { @@ -428,6 +446,8 @@ impl Game<'_> { .iter() .find(|o| o.id == id) .map_or_else(String::new, |o| o.kind.clone()), + Target::Crystal(_) => "minecraft:end_crystal".into(), + Target::Dragon(_) => "minecraft:ender_dragon".into(), } } /// The name of the player the game acts for: a guest's own while their @@ -512,50 +532,72 @@ impl Game<'_> { s.pos[2].unwrap_or(p[2]), ] }; - let mut candidates: Vec = Vec::new(); + let mut source_candidates: Vec = Vec::new(); match (s.kind, self.command_source) { // @s: the executing entity (none for a server source). - ('s', Some(source)) => candidates.extend(source.entity), - ('s', None) => candidates.extend(self.source_entity()), + ('s', Some(source)) => source_candidates.extend(source.entity), + ('s', None) => source_candidates.extend(self.source_entity()), // A guest in place is among the players, in join order. _ if self.player.is_some() && self.lan_acting.is_none() => { - candidates.push(Target::Player); + source_candidates.push(Target::Player); } _ => {} } if s.kind != 's' { - use horizon_client::projectiles::ProjectileKind as K; - candidates.extend(self.player_candidates(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( - self.creatures - .projectiles - .iter() - .enumerate() - // The kinds /data can write (entity_nbt). - .filter(|(_, p)| { - p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) - }) - .map(|(i, _)| Target::Projectile(i)), - ); - candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id))); - candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id))); - candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); - candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); - candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); - candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); + source_candidates.extend(self.player_candidates(s)); } + let source_dim = self.dim; + // A selector with a spatial constraint reaches the level the command + // runs in only; an unbounded one reaches every loaded level + // (EntitySelector.findEntities). + let dims = if s.world_limited() { + vec![source_dim] + } else { + self.loaded_dims() + }; + let mut out: Vec<(Target, f64)> = Vec::new(); + for dim in dims { + let back = self.enter_command_level(dim); + let mut candidates = Vec::new(); + if dim == source_dim { + candidates.append(&mut source_candidates); + } + if s.kind != 's' { + candidates.extend(self.level_candidates()); + } + out.extend(self.select_in_level(candidates, s, origin)); + if let Some(back) = back { + self.enter_command_level(back); + } + } + 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() + } + /// The candidates of the level in place that pass the selector + /// (EntitySelector.getPredicate). + fn select_in_level( + &mut self, + candidates: Vec, + s: &Selector, + origin: [f64; 3], + ) -> Vec<(Target, f64)> { let level = self.experience.level; let creative = self.creative; let passing = self.selector_extra_filter(&candidates, s); - let mut out: Vec<(Target, f64)> = candidates + candidates .into_iter() .filter_map(|t| { let p = self.target_position(t)?; @@ -627,23 +669,102 @@ impl Game<'_> { } 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() } + /// The entities of the level in place a selector can find. + fn level_candidates(&self) -> Vec { + use horizon_client::projectiles::ProjectileKind as K; + let mut candidates = Vec::new(); + 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(self.orbs.iter().map(|o| Target::Orb(o.id))); + candidates.extend( + self.creatures + .projectiles + .iter() + // The kinds /data can write (entity_nbt). + .filter(|p| { + p.is_arrow() || matches!(p.kind, K::LargeFireball { .. } | K::SmallFireball) + }) + .map(|p| Target::Projectile(p.id)), + ); + candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id))); + candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id))); + candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id))); + candidates.extend(self.boats.iter().map(|b| Target::Boat(b.id))); + candidates.extend(self.carts.iter().map(|c| Target::Cart(c.id))); + candidates.extend(self.others.iter().map(|o| Target::Other(o.id))); + // The End crystals and the dragon (EndCrystal and EnderDragon + // are entities of their own). + candidates.extend(self.crystals.iter().map(|c| Target::Crystal(c.id))); + if let Some(d) = &self.dragon { + candidates.push(Target::Dragon(d.id)); + } + candidates + } + /// The loaded levels, in the order the server holds them: the + /// overworld, the nether, the end (MinecraftServer.getAllLevels). + fn loaded_dims(&self) -> Vec { + let mut dims = vec![self.dim]; + dims.extend(self.levels.parked_dims()); + dims.sort_by_key(|d| match d { + Dim::Overworld => 0, + Dim::Nether => 1, + Dim::End => 2, + }); + dims + } + /// Whether the level in place holds the entity a target names. + fn level_holds(&self, t: Target) -> bool { + match t { + // A player is in no level of its own. + Target::Player | Target::Guest(_) => true, + Target::Mob(id) => self.mobs.iter().any(|m| m.id == id), + Target::Item(id) => self.dropped.iter().any(|i| i.id == id), + Target::Orb(id) => self.orbs.iter().any(|o| o.id == id), + Target::Projectile(id) => self.creatures.projectiles.iter().any(|p| p.id == id), + Target::Stand(id) => self.armor_stands.iter().any(|a| a.id == id), + Target::Frame(id) => self.item_frames.iter().any(|f| f.id == id), + Target::Painting(id) => self.paintings.iter().any(|p| p.id == id), + Target::Boat(id) => self.boats.iter().any(|b| b.id == id), + Target::Cart(id) => self.carts.iter().any(|c| c.id == id), + Target::Other(id) => self.others.iter().any(|o| o.id == id), + Target::Crystal(id) => self.crystals.iter().any(|c| c.id == id), + Target::Dragon(id) => self.dragon.as_ref().is_some_and(|d| d.id == id), + } + } + /// Run `f` with the level that holds the entity a target names in place + /// (the entity ids are unique across the loaded levels) and put the + /// level back afterwards. `f` does not run when no level holds the + /// entity. + pub(in crate::game) fn in_target_level( + &mut self, + t: Target, + f: impl FnOnce(&mut Self) -> R, + ) -> Option { + if self.level_holds(t) { + return Some(f(self)); + } + for dim in self.levels.parked_dims() { + let back = self.enter_command_level(dim); + if self.level_holds(t) { + let r = f(self); + if let Some(back) = back { + self.enter_command_level(back); + } + return Some(r); + } + if let Some(back) = back { + self.enter_command_level(back); + } + } + None + } fn entity_tag_matches(&self, tag: &str, ty: &str) -> bool { let path = self.options.resources.join(format!( "data/minecraft/tags/entity_type/{}.json", @@ -1103,6 +1224,10 @@ impl Game<'_> { Ok(targets.len() as i32) } fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { + // An entity in another level is teleported in the level that holds it. + let _ = self.in_target_level(t, |g| g.teleport_to_in_level(t, pos, rotation)); + } + fn teleport_to_in_level(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { let v = Vec3::new(pos[0], pos[1], pos[2]); match t { Target::Guest(_) => { @@ -1151,14 +1276,14 @@ impl Game<'_> { i.previous = v; } } - Target::Orb(i) => { - if let Some(o) = self.orbs.get_mut(i) { + Target::Orb(id) => { + if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) { o.position = v; o.previous = v; } } - Target::Projectile(i) => { - if let Some(a) = self.creatures.projectiles.get_mut(i) { + Target::Projectile(id) => { + if let Some(a) = self.creatures.projectiles.iter_mut().find(|a| a.id == id) { a.position = v; a.previous = v; } @@ -1198,6 +1323,17 @@ impl Game<'_> { } } } + Target::Crystal(id) => { + if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) { + c.position = v; + } + } + Target::Dragon(id) => { + if let Some(d) = self.dragon.as_mut().filter(|d| d.id == id) { + d.position = v; + d.previous = v; + } + } // Wall-mounted entities do not move. Target::Frame(_) | Target::Painting(_) => {} } @@ -1557,6 +1693,10 @@ impl Game<'_> { Ok(duration.unwrap_or(-1)) } fn kill_target(&mut self, t: Target) { + // An entity in another level is killed in the level that holds it. + let _ = self.in_target_level(t, |g| g.kill_target_in_level(t)); + } + fn kill_target_in_level(&mut self, t: Target) { match t { Target::Guest(_) => { self.for_player(t, |g| g.kill_target(Target::Player)); @@ -1576,16 +1716,13 @@ impl Game<'_> { } } 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::Orb(id) => { + if let Some(o) = self.orbs.iter_mut().find(|o| o.id == id) { + o.age = u32::MAX / 2; } } - // cmd_kill goes from the highest index down. - Target::Projectile(i) => { - if i < self.creatures.projectiles.len() { - self.creatures.projectiles.remove(i); - } + Target::Projectile(id) => { + self.creatures.projectiles.retain(|p| p.id != id); } Target::Stand(id) => self.armor_stands.retain(|a| a.id != id), Target::Frame(id) => self.item_frames.retain(|f| f.id != id), @@ -1593,7 +1730,11 @@ impl Game<'_> { Target::Boat(id) => self.boats.retain(|b| b.id != id), Target::Cart(id) => self.carts.retain(|c| c.id != id), Target::Other(id) => self.others.retain(|o| o.id != id), + Target::Crystal(id) => self.kill_crystal(id), + Target::Dragon(id) => self.kill_dragon(id), } + // The orbs marked for removal are gone (Entity.kill removes them). + self.orbs.retain(|o| o.age < u32::MAX / 2); } fn cmd_kill(&mut self, ctx: &Context) -> R { let targets = if ctx.get("targets").is_some() { @@ -1601,19 +1742,18 @@ impl Game<'_> { } else { vec![self.implied_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::Projectile(i) => *i, - _ => 0, - }) - }); - for t in ordered { + let mut names: Vec = Vec::new(); + for &t in &targets { + // The name of an entity in another level is read there. + let name = match self.in_target_level(t, |g| g.target_name(t)) { + Some(name) => name, + None => self.target_name(t), + }; + names.push(name); + } + for &t in &targets { self.kill_target(t); } - self.orbs.retain(|o| o.age < u32::MAX / 2); let message = if targets.len() == 1 { Text::translate("commands.kill.success.single", &[names[0].clone()]) } else { @@ -1705,6 +1845,20 @@ impl Game<'_> { self.spawn_bolt(pos, false); name = Text::translate("entity.minecraft.lightning_bolt", &[]); } + "end_crystal" => { + // EndCrystal's constructor takes an id from the entity + // counter, and the crystal is shown with its base. + self.next_entity += 1; + self.crystals.push(super::dragon::Crystal { + id: self.next_entity, + position: Vec3::new(pos[0], pos[1], pos[2]), + show_bottom: true, + time: self.world.random.next_int_bound(100_000).unwrap_or(0), + beam: None, + invulnerable: false, + }); + name = Text::translate("entity.minecraft.end_crystal", &[]); + } k if super::minecarts::CartKind::from_id(&kind).is_some() => { let cart_kind = super::minecarts::CartKind::from_id(&kind) .unwrap_or(super::minecarts::CartKind::Rideable); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index ac16c5e7c..61bf3abe9 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -31,8 +31,13 @@ fn set_key(tag: &mut Tag, key: &str, value: Tag) { impl Game<'_> { // ---- entity data --------------------------------------------------- - /// `NbtPredicate.getEntityTagToCompare`: the entity as saved. + /// `NbtPredicate.getEntityTagToCompare`: the entity as saved. An entity + /// in another level is read in the level that holds it. pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option { + self.in_target_level(t, |g| g.entity_nbt_in_level(t)) + .flatten() + } + fn entity_nbt_in_level(&mut self, t: Target) -> Option { let player_uuid = self.level.player_uuid; Some(match t { Target::Guest(_) => { @@ -113,9 +118,11 @@ impl Game<'_> { let o = self.others.iter().find(|o| o.id == id)?.clone(); self.other_to_nbt(&o, uuid) } - Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()), - Target::Projectile(i) => { - let p = self.creatures.projectiles.get(i)?; + Target::Orb(id) => { + entity_nbt::orb_to_nbt(self.orbs.iter().find(|o| o.id == id)?, random_uuid()) + } + Target::Projectile(id) => { + let p = self.creatures.projectiles.iter().find(|p| p.id == id)?; let owner = if p.owner == Some(horizon_client::mobs::Who::Player) { player_uuid } else { @@ -129,6 +136,16 @@ impl Game<'_> { entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None) .or_else(|| entity_nbt::fireball_to_nbt(p, random_uuid(), owner, None))? } + Target::Crystal(id) => { + let c = self.crystals.iter().find(|c| c.id == id)?; + let (uuid, raw) = self.persist_anon("minecraft:end_crystal", c.position); + c.to_nbt(uuid.unwrap_or_else(random_uuid), raw) + } + Target::Dragon(id) => { + let d = self.dragon.as_ref().filter(|d| d.id == id)?; + let (uuid, raw) = self.persist_anon("minecraft:ender_dragon", d.position); + d.to_nbt(uuid.unwrap_or_else(random_uuid), raw) + } }) } /// `Entity.load` of new data (`EntityDataAccessor.setData`): the entity is @@ -397,6 +414,19 @@ impl Game<'_> { } pub(super) fn cmd_data(&mut self, id: &str, ctx: &Context) -> R { let target = self.data_ref(ctx, 0)?; + // An entity in another level is read and written in the level that + // holds it. + if let DataRef::Entity(t) = &target { + let t = *t; + let target = target.clone(); + return match self.in_target_level(t, |g| g.cmd_data_in(id, ctx, target)) { + Some(r) => r, + None => Err(err("argument.entity.notfound.entity", &[])), + }; + } + self.cmd_data_in(id, ctx, target) + } + fn cmd_data_in(&mut self, id: &str, ctx: &Context, target: DataRef) -> R { match id { "data.merge" => { let Some(Arg::Str(nbt)) = ctx.get("nbt") else { diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 6516bfe6c..3a26f6c0d 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -1,11 +1,10 @@ //! `/effect` (EffectCommands) and `/enchant` (EnchantCommand). use super::{Arg, Context, Game, R, Target, err, texts}; use horizon_client::{ - brewing, + brewing::{self, namespaced}, effects::EffectInstance, text::{self, Style, Text}, }; -use std::{collections::HashMap, sync::OnceLock}; /// `CommandResponseTracker` over targets: elements with a non-zero result. #[derive(Default)] @@ -21,24 +20,6 @@ impl Tracker { } } } -/// Namespaced effect ids for mob effect storage. -fn namespaced(id: &'static str) -> &'static str { - static IDS: OnceLock> = OnceLock::new(); - IDS.get_or_init(|| { - brewing::EFFECTS - .iter() - .map(|e| { - ( - e.id, - &*Box::leak(format!("minecraft:{}", e.id).into_boxed_str()), - ) - }) - .collect() - }) - .get(id) - .copied() - .unwrap_or(id) -} fn effect_name(id: &str) -> Text { Text::translate(&format!("effect.minecraft.{id}"), &[]) } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index eb4d4b157..12aedc59a 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -663,10 +663,11 @@ impl Game<'_> { // TraceableEntity.getOwner: who shot a projectile, who threw an // item, who summoned a vex. Some("origin") => match entity { - Target::Projectile(i) => self + Target::Projectile(id) => self .creatures .projectiles - .get(i) + .iter() + .find(|p| p.id == id) .and_then(|p| match (p.owner?, p.guest) { // A guest's shot: `Who::Player` is them. (horizon_client::mobs::Who::Player, Some(conn)) @@ -907,10 +908,12 @@ impl Game<'_> { .coords(c, "pos") .map(|co| co.block(self.source_position(), self.source_rotation())); let dimension = self.command_source.map_or(self.dim, |s| s.dimension); - return Ok(flag( - dimension == self.dim - && p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))), - )); + // ExecuteCommand.isChunkLoaded: ENTITY_TICKING, which is past lit. + let loaded = |p: [i32; 3]| { + let key = (p[0] >> 4, p[2] >> 4); + self.world.chunks.contains_key(&key) && self.streaming.is_lit(key.0, key.1) + }; + return Ok(flag(dimension == self.dim && p.is_some_and(loaded))); } if c.has("dimension") { let dimension = self.command_source.map_or(self.dim, |s| s.dimension); diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 559d30db4..39587fa00 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -119,6 +119,7 @@ impl Game<'_> { "magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic, "sting" => DamageKind::Sting, "cactus" | "sweet_berry_bush" => DamageKind::Cactus, + "freeze" => DamageKind::Freeze, "in_wall" => DamageKind::InWall, "thorns" => DamageKind::Thorns, _ => DamageKind::Generic, diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs index 93d919911..dc187d207 100644 --- a/crates/horizon-client/src/game/consume.rs +++ b/crates/horizon-client/src/game/consume.rs @@ -19,7 +19,17 @@ use std::convert::Infallible; type ItemConsumable = Consumable; +/// `EntityEvent.USE_ITEM_COMPLETE`: the server finished the player's use. +pub(super) const USE_ITEM_COMPLETE_EVENT: i8 = 9; + impl Game<'_> { + /// `ServerPlayer.completeUsingItem`: the player's own client is told + /// first, and completes the use itself (eating the food there too). + pub(super) fn send_use_item_complete(&mut self) { + if self.lan_acting.is_some() { + self.guest_entity_events.push(USE_ITEM_COMPLETE_EVENT); + } + } /// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`. pub(super) fn emit_consume( &mut self, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9b5cd93e7..0fe5d89ce 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -878,6 +878,9 @@ impl Game<'_> { Screen::Advancements => "advancements", Screen::WorldOptions => "world-options", Screen::Friends => "friends", + Screen::ServerLinks => "server-links", + Screen::ConfirmLink => "confirm-link", + Screen::DialogWarning => "dialog-warning", Screen::CommandBlock => "command-block", Screen::Win => "win", Screen::Mod => "mod", diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 2bc40a7af..0906e5357 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -46,6 +46,9 @@ pub(super) struct Creatures { pub projectiles: Vec, /// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs). pub wind_bursts: Vec, + /// Explosion packets from a guest's turn, waiting for it to end + /// (centre, small, radius, blocks hit; game/lan_particles.rs). + pub lan_explosions: Vec<([f64; 3], bool, f32, usize)>, /// Ticks left of the elder guardian's apparition (MobAppearanceParticle). pub elder_apparition: i32, /// The wandering trader spawner's clock. @@ -679,6 +682,7 @@ impl Game<'_> { self.sync_riders(); self.tick_skeleton_traps(); self.tick_apparition(); + self.guardian_bubbles(); self.villager_reputation_tick(); self.merchant_tick(); self.villager_pickups(); @@ -928,11 +932,29 @@ impl Game<'_> { self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); } } + /// Adds a projectile, giving it an id from the entity counter + /// (`Entity.id`, the same counter as the rest) when it has none. + pub(super) fn add_projectile(&mut self, mut p: horizon_client::projectiles::Projectile) { + if p.id == 0 { + self.next_entity += 1; + p.id = self.next_entity; + } + self.creatures.projectiles.push(p); + } pub(super) fn handle_mob_events(&mut self, events: Vec) -> Result<()> { for e in events { match e { MobEvent::SquidCycle { mob, at } => self.lan_entity_event(mob as i32, 19, at), MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at), + MobEvent::Drown { mob, at } => { + self.lan_entity_event(mob as i32, super::combat::DROWN_EVENT, at); + let v = self + .mobs + .iter() + .find(|m| m.id == mob) + .map_or([0.0; 3], |m| [m.velocity.x, m.velocity.y, m.velocity.z]); + self.drown_particles(at, v); + } MobEvent::Sound(name, at, volume, pitch) | MobEvent::LocalSound(name, at, volume, pitch) => { self.audio @@ -980,6 +1002,21 @@ impl Game<'_> { } } } + MobEvent::Shift { target, delta } => { + let d = Vec3::new(delta[0], delta[1], delta[2]); + match target { + Who::Player => { + if let Some(p) = self.player.as_mut() { + p.position = p.position.add_vector(d); + } + } + Who::Mob(id) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { + m.position = m.position.add_vector(d); + } + } + } + } MobEvent::Wololo { mob } => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { // DyeColor.RED. @@ -1119,7 +1156,7 @@ impl Game<'_> { let v = p.velocity; self.particles.llama_spit_burst(at, [v.x, v.y, v.z]); } - self.creatures.projectiles.push(p); + self.add_projectile(p); self.projectile_event("minecraft:projectile_shoot", owner, at); } MobEvent::Spawn(mut m) => { @@ -1920,6 +1957,7 @@ impl Game<'_> { let mut hits = Vec::new(); let mut deflections: Vec<[f64; 3]> = Vec::new(); let mut arrow_events = Vec::new(); + let mut trails = Vec::new(); { let mut targets: Vec<(Who, Aabb)> = self .mobs @@ -2011,6 +2049,10 @@ impl Game<'_> { if shooter.is_some() { p.owner = Some(Who::Player); } + // AbstractHurtingProjectile.tick ends with createParticleTrail. + if super::remote_projectiles::has_smoke_trail(&p.kind) { + trails.push(p.position); + } if let Some(a) = p.arrow.as_mut() { arrow_events.extend(a.events.drain(..).map(|e| (p.position, e))); } @@ -2053,6 +2095,7 @@ impl Game<'_> { keep }); } + self.smoke_trails(trails); for at in deflections { self.audio .play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0); @@ -2085,6 +2128,7 @@ impl Game<'_> { _ => self.projectile_hit(&p, hit)?, } } + self.flush_lan_explosions(); self.flush_wind_bursts() } /// `projectile_hit` for a projectile the guest `conn` shot, run as them; @@ -2217,11 +2261,9 @@ impl Game<'_> { ArrowEvent::ShootEvent | ArrowEvent::Drop => {} } } - /// `Level.isRainingAt` for arrows: raining, open to the sky (the biome's - /// precipitation is not checked here). + /// `Level.isRainingAt` for arrows. fn arrow_rain(&self) -> impl Fn(BlockPos) -> bool + '_ { - let raining = self.world.weather.levels(1.0).0 > 0.2; - move |p: BlockPos| raining && self.world.light(p.x, p.y, p.z) >> 4 == 15 + move |p: BlockPos| self.raining_at(p) } /// The level as arrows see it. fn arrow_scene<'s>( @@ -2259,7 +2301,7 @@ impl Game<'_> { } } if keep { - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); } } /// `TargetBlock.onProjectileHit`: a target block takes its power from @@ -3309,7 +3351,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(proj); + self.add_projectile(proj); self.player_projectile_shot(); // ItemStack.use's applyAfterUseComponentSideEffects: the pearl's // second is the `use_cooldown` component, as for any thrown item. @@ -3402,11 +3444,65 @@ impl Game<'_> { } } } + /// `Guardian.aiStep` on a client: two bubbles a tick trailing a guardian + /// that swims along, and bubbles up the beam to its target. The server + /// never draws them, so the mob's own random stays untouched. + pub(super) fn guardian_bubbles(&mut self) { + use horizon_client::mobs::guardian; + use horizon_client::particles::{ParticleOptions, ParticleType}; + let mut swimming = Vec::new(); + let mut beams = Vec::new(); + for m in &self.mobs { + if !m.alive() || !matches!(m.species(), Species::Guardian | Species::ElderGuardian) { + continue; + } + let at = [m.position.x, m.position.y, m.position.z]; + if m.extra.flag2 && m.fluids.in_water { + let (width, height, _) = m.dims(); + swimming.push((at, width, height, m.view_vector())); + } + if let Some((_, scale)) = guardian::beam(m, 0.0) + && let Some(t) = self.beam_target(m.ai.target, 1.0) + { + beams.push(([at[0], m.eye_y(), at[2]], [t.x, t.y, t.z], f64::from(scale))); + } + } + let bubble = ParticleOptions::simple(ParticleType::Bubble); + for (at, width, height, view) in swimming { + for _ in 0..2 { + let (x, y, z) = { + let r = self.particles.random(); + (r.next_double(), r.next_double(), r.next_double()) + }; + let p = [ + at[0] + width * (2.0 * x - 1.0) * 0.5 - view[0] * 1.5, + at[1] + height * y - view[1] * 1.5, + at[2] + width * (2.0 * z - 1.0) * 0.5 - view[2] * 1.5, + ]; + self.particles.add(&bubble, p, [0.0; 3]); + } + } + for (eye, target, scale) in beams { + let d = [target[0] - eye[0], target[1] - eye[1], target[2] - eye[2]]; + let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt(); + if length <= 0.0 { + continue; + } + let mut dist = self.particles.random().next_double(); + while dist < length { + let r = self.particles.random(); + dist += 1.8 - scale + r.next_double() * (1.7 - scale); + let f = dist / length; + let p = [eye[0] + d[0] * f, eye[1] + d[1] * f, eye[2] + d[2] * f]; + self.particles.add(&bubble, p, [0.0; 3]); + } + } + } /// Mob models and projectiles for the entity pass. pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); - let scale = f64::from(self.settings.entity_distance); + let scale = self.view_scale(); for mob in &self.mobs { let entity_start = out.len(); // Entity.DATA_SHARED_FLAGS_ID invisible: only the name tag draws. @@ -3415,9 +3511,16 @@ impl Game<'_> { } let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's - // mean edge, scaled by the entity distance option. + // mean edge, scaled by the view scale. RemotePlayer's box counts + // ten times. let (w, h, _) = mob.dims(); - let range = (w + h + w) / 3.0 * 64.0 * scale; + let edge = (w + h + w) / 3.0 + * if &*mob.kind.id == "minecraft:player" { + 10.0 + } else { + 1.0 + }; + let range = edge * 64.0 * scale; if d.length_squared() >= range * range { continue; } @@ -3703,6 +3806,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) K::InWall => "minecraft:in_wall", K::Thorns => "minecraft:thorns", K::SonicBoom => "minecraft:sonic_boom", + K::Freeze => "minecraft:freeze", K::OutOfWorld => "minecraft:out_of_world", } } diff --git a/crates/horizon-client/src/game/crossbow.rs b/crates/horizon-client/src/game/crossbow.rs index bc49c4b90..d66610183 100644 --- a/crates/horizon-client/src/game/crossbow.rs +++ b/crates/horizon-client/src/game/crossbow.rs @@ -222,7 +222,7 @@ impl Game<'_> { a.pierce = pierce; } arrow.shoot(&mut self.world.random, dir.to_array(), power, 1.0); - self.creatures.projectiles.push(arrow); + self.add_projectile(arrow); } self.player_projectile_shot(); let pitch = if index == 0 { diff --git a/crates/horizon-client/src/game/cushions.rs b/crates/horizon-client/src/game/cushions.rs index 0847321d6..989009d82 100644 --- a/crates/horizon-client/src/game/cushions.rs +++ b/crates/horizon-client/src/game/cushions.rs @@ -348,11 +348,15 @@ impl Game<'_> { let Some(state) = self.pack.assets.registry.default_state(&name) else { return; }; - let at = [ - c.position.x.floor() as i32, - c.position.y.floor() as i32, - c.position.z.floor() as i32, - ]; + let p = c.position; + // Entity.getY(2/3) is relative to the cushion's quarter-block height. + let particle_at = [p.x, p.y + 0.25 * (2.0 / 3.0), p.z]; + // Guest actions temporarily take self.lan; flush once the hub is back. + // Queue before resolving a sprite: a dedicated server has no renderer. + if self.audio.capture.is_some() { + self.lan_cushion_breaks.push((state, particle_at)); + } + let at = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; let Some((sprite, tint)) = self.particle_sprite(state, at) else { return; }; @@ -361,14 +365,8 @@ impl Game<'_> { sprite, tint, ); - let p = c.position; - self.particles.send_particles( - &options, - [p.x, p.y + 0.666_666_7, p.z], - [0.25, 0.0625, 0.25], - 0.05, - 10, - ); + self.particles + .send_particles(&options, particle_at, [0.25, 0.0625, 0.25], 0.05, 10); } /// `BlockAttachedEntity.tick`: survive and burn checks after the post-increment reaches 100. @@ -455,8 +453,7 @@ impl Game<'_> { glam::DVec3::new(lo.x, lo.y, lo.z), glam::DVec3::new(hi.x, hi.y, hi.z), ); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 16e7fc6e7..dc79bf8c1 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -13,7 +13,7 @@ use horizon_client::{ save::VERSION_NAME, text::Text, }; -use horizon_core::geometry::Axis; +use horizon_core::geometry::{Axis, Vec3}; use winit::keyboard::KeyCode; /// `ChatFormatting.YELLOW` and `RED`. @@ -766,7 +766,8 @@ impl Game<'_> { } let lerp = |a: f64, b: f64| a + f64::from(alpha) * (b - a); let lerpf = |a: f32, b: f32| a + alpha * (b - a); - for m in &self.mobs { + let guests = self.lan.iter().flat_map(|h| h.models.values()); + for m in self.mobs.iter().chain(guests) { if m.removed || m.invisible || m.has_effect("minecraft:invisibility") { continue; } @@ -796,6 +797,159 @@ impl Game<'_> { // EntityType.ITEM: 0.25 by 0.25, eyes at 0.2125. g.hitbox(pos, (0.25, 0.25), 0.2125, false, (0.0, 0.0)); } + // The other entities (EntityTypes sizes; eyes at 0.85 of the height + // unless the type sets one). `at` is the interpolated position. + let at = |previous: Vec3, now: Vec3| { + [ + lerp(previous.x, now.x), + lerp(previous.y, now.y), + lerp(previous.z, now.z), + ] + }; + for p in &self.paintings { + let (min, max) = p.bounds(); + let centre = std::array::from_fn(|i| (min[i] + max[i]) / 2.0); + g.entity_box(min, max, centre, 0.425, false, step_view(p.step())); + } + for f in self.item_frames.iter().filter(|f| !f.invisible) { + let (min, max) = f.bounds(); + let centre = std::array::from_fn(|i| (min[i] + max[i]) / 2.0); + g.entity_box(min, max, centre, 0.0, false, step_view(f.step())); + } + for c in &self.cushions { + let (min, max) = c.bounds(); + let p = c.position; + g.entity_box(min, max, [p.x, p.y, p.z], 0.2125, false, (0.0, c.yaw)); + } + for a in self.armor_stands.iter().filter(|a| !a.invisible) { + // ArmorStand.getDimensions: a marker has none, a small one is + // half scale with its eyes at 0.9875. + let (size, eye) = match (a.marker, a.small) { + (true, _) => ((0.0, 0.0), 0.0), + (_, true) => ((0.25, 0.9875), 0.9875), + _ => ((0.5, 1.975), 1.7775), + }; + let p = a.position; + g.hitbox([p.x, p.y, p.z], size, eye, true, (0.0, a.yaw)); + } + for b in &self.boats { + let h = super::boats::HEIGHT as f32; + g.hitbox( + at(b.previous, b.position), + (super::boats::WIDTH as f32, h), + h, + false, + (0.0, b.yaw), + ); + } + for c in &self.carts { + let (w, h) = ( + super::minecarts::WIDTH as f32, + super::minecarts::HEIGHT as f32, + ); + g.hitbox( + at(c.previous, c.position), + (w, h), + h * 0.85, + false, + (0.0, c.yaw), + ); + } + for o in &self.orbs { + g.hitbox( + at(o.previous, o.position), + (0.5, 0.5), + 0.425, + false, + (0.0, 0.0), + ); + } + for f in &self.falling { + g.hitbox( + at(f.previous, f.position), + (0.98, 0.98), + 0.833, + false, + (0.0, 0.0), + ); + } + for t in &self.tnts { + g.hitbox( + at(t.previous, t.position), + (0.98, 0.98), + 0.15, + false, + (0.0, 0.0), + ); + } + for c in &self.crystals { + let p = c.position; + g.hitbox([p.x, p.y, p.z], (2.0, 2.0), 1.7, false, (0.0, 0.0)); + } + for p in &self.creatures.projectiles { + use horizon_client::projectiles::ProjectileKind as K; + let (size, eye) = match p.kind { + K::Arrow { .. } | K::Trident => (0.5, 0.13), + K::Snowball | K::Egg | K::EnderPearl | K::LlamaSpit | K::Potion { .. } => { + (0.25, 0.2125) + } + K::SmallFireball | K::ShulkerBullet { .. } | K::WitherSkull { .. } => { + (0.3125, 0.265_625) + } + K::WindCharge | K::BreezeWindCharge => (0.3125, 0.0), + K::LargeFireball { .. } => (1.0, 0.85), + }; + g.hitbox( + at(p.previous, p.position), + (size, size), + eye, + false, + (p.pitch, p.yaw), + ); + } + for t in &self.tridents { + g.hitbox( + at(t.previous, t.position), + (0.5, 0.5), + 0.13, + false, + (t.pitch, t.yaw), + ); + } + for r in &self.rockets { + // Projectile.updateRotation: the look follows the motion. + let v = r.velocity; + let yaw = v.x.atan2(v.z).to_degrees() as f32; + let pitch = v.y.atan2(v.x.hypot(v.z)).to_degrees() as f32; + g.hitbox( + at(r.previous, r.position), + (0.25, 0.25), + 0.2125, + false, + (pitch, yaw), + ); + } + for h in self + .hook + .iter() + .map(|h| (h.previous, h.position)) + .chain(self.remote_hooks.iter().map(|h| (h.previous, h.position))) + { + g.hitbox(at(h.0, h.1), (0.25, 0.25), 0.2125, false, (0.0, 0.0)); + } + for b in &self.bolts { + g.hitbox(b.at, (0.0, 0.0), 0.0, false, (0.0, 0.0)); + } + // The dragon: 16 by 8, a living entity; its parts follow. + if let Some(d) = &self.dragon { + g.hitbox( + at(d.previous, d.position), + (16.0, 8.0), + 6.8, + true, + (0.0, d.yaw), + ); + } // The dragon's parts. for (id, b) in self.special_targets() { if (super::dragon::SPECIAL..super::dragon::SPECIAL + 8).contains(&id) { @@ -828,3 +982,12 @@ impl Game<'_> { g } } + +/// The (x, y) rotations whose view vector is the step of a direction. +fn step_view(step: [i32; 3]) -> (f32, f32) { + let [x, y, z] = step.map(f64::from); + ( + (-y).asin().to_degrees() as f32, + (-x.atan2(z)).to_degrees() as f32, + ) +} diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 49b653ae1..73c6fd4cc 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -24,6 +24,7 @@ use horizon_client::{ use horizon_protocol::text::translatable; use horizon_world::nbt::{JavaString, Tag}; use std::{ + io::Write, path::PathBuf, sync::{Arc, Mutex, OnceLock, mpsc}, time::{Duration, Instant}, @@ -89,7 +90,9 @@ fn log_from(thread: &str, level: &str, message: &str) { } }); // Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log. - println!( + // The launcher can close its stdout pipe while the server keeps running. + let _ = writeln!( + std::io::stdout().lock(), "[{}] [{thread}/{level}]: {message}", chrono::Local::now().format("%H:%M:%S") ); @@ -618,6 +621,22 @@ impl Game<'_> { log_ips: props.log_ips, }), resource_pack: props.resource_pack.clone(), + // DedicatedServer.serverLinks: `bug-report-link` as the only link + // (ServerLinks.KnownLinkType.BUG_REPORT is id 0). + server_links: if props.bug_report_link.is_empty() { + Vec::new() + } else if super::server_links::valid_untrusted_uri(&props.bug_report_link) { + vec![horizon_protocol::packets::configuration::ServerLink { + kind: horizon_protocol::packets::configuration::ServerLinkKind::Known(0), + link: props.bug_report_link.clone(), + }] + } else { + log( + "WARN", + &format!("Failed to parse bug link {}", props.bug_report_link), + ); + Vec::new() + }, }; let config = HubConfig { default_game_mode: game_mode, @@ -1311,3 +1330,110 @@ fn png_size(bytes: &[u8]) -> Option<(u32, u32)> { let h = u32::from_be_bytes(bytes[20..24].try_into().ok()?); Some((w, h)) } + +#[cfg(test)] +mod tests { + use super::{capture_log, log, log_from}; + use std::{ + fs, + io::{self, BufRead, BufReader, Read, Write}, + process::{Command, Stdio}, + time::{SystemTime, UNIX_EPOCH}, + }; + + const LOGIN: &str = "Player[/127.0.0.1:0] logged in with entity id 2 at (0.5, 115.0, 0.5)"; + const WARNING: &str = "Authentication warning"; + const READY: &str = "horizon-console-log-ready\n"; + const CHILD_HOME: &str = "HORIZON_TEST_CONSOLE_LOG_HOME"; + + fn assert_log_lines(text: &str) { + let expected = [ + format!("] [Server thread/INFO]: {LOGIN}"), + format!("] [User Authenticator #1/WARN]: {WARNING}"), + ]; + assert_eq!(text.lines().count(), expected.len()); + for (line, suffix) in text.lines().zip(expected) { + assert!(line.starts_with('[')); + assert!(chrono::NaiveTime::parse_from_str(&line[1..9], "%H:%M:%S").is_ok()); + assert_eq!(&line[9..], suffix); + } + } + + #[test] + fn console_logging_survives_closed_stdout() { + if let Some(home) = std::env::var_os(CHILD_HOME) { + horizon_client::logging::init(std::path::Path::new(&home), "Server thread"); + // Let the parent close the real stdout pipe only after libtest's startup output. + io::stdout().write_all(READY.as_bytes()).unwrap(); + io::stdout().flush().unwrap(); + io::stdin().read_exact(&mut [0]).unwrap(); + std::thread::Builder::new() + .name("Server thread".into()) + .spawn(|| { + let captured = capture_log(|| { + log("INFO", LOGIN); + log_from("User Authenticator #1", "WARN", WARNING); + }); + assert_eq!(captured, [LOGIN, WARNING]); + horizon_client::logging::flush(); + }) + .unwrap() + .join() + .unwrap(); + // Libtest's final status also writes to stdout; only the game logger is under test. + std::process::exit(0); + } + + for closed_stdout in [false, true] { + let unique = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_nanos(); + let home = std::env::temp_dir().join(format!( + "horizon-console-log-test-{}-{unique}", + std::process::id() + )); + fs::create_dir(&home).unwrap(); + let mut child = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "game::dedicated::tests::console_logging_survives_closed_stdout", + "--nocapture", + ]) + .env(CHILD_HOME, &home) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut stdout = BufReader::new(child.stdout.take().unwrap()); + loop { + let mut line = String::new(); + assert!( + stdout.read_line(&mut line).unwrap() > 0, + "child was not ready" + ); + if line.ends_with(READY) { + break; + } + } + if closed_stdout { + drop(stdout); // No reader remains: the next console write gets EPIPE. + } else { + child.stdout = Some(stdout.into_inner()); + } + child.stdin.take().unwrap().write_all(&[1]).unwrap(); + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "closed_stdout={closed_stdout}: {}", + String::from_utf8_lossy(&output.stderr) + ); + if !closed_stdout { + assert_log_lines(std::str::from_utf8(&output.stdout).unwrap()); + } + assert_log_lines(&fs::read_to_string(home.join("logs/latest.log")).unwrap()); + fs::remove_dir_all(home).unwrap(); + } + } +} diff --git a/crates/horizon-client/src/game/deflect.rs b/crates/horizon-client/src/game/deflect.rs index a08de87b3..088374a34 100644 --- a/crates/horizon-client/src/game/deflect.rs +++ b/crates/horizon-client/src/game/deflect.rs @@ -120,6 +120,11 @@ impl Game<'_> { p.guest = guest; // Not into the one who turned it on its way out. p.left_owner = false; + // `AbstractHurtingProjectile.onDeflection` by an attack, and the + // `needsSync` that `AIM_DEFLECT` sets: a server's players see it turn + // at once, not at the fireball's next update ten ticks later. + p.acceleration = 0.1; + p.needs_sync = true; self.reset_attack_strength(); self.swing_arm(); let from = self diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index f902f1c05..a0a9bfd93 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -1034,7 +1034,7 @@ impl Game<'_> { a.pickup = horizon_client::arrows::Pickup::Allowed; } shot.shoot(&mut own, dir, power, uncertainty); - self.creatures.projectiles.push(shot); + self.add_projectile(shot); } } } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 8f3fdb224..a13bcb5b7 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -291,11 +291,11 @@ pub(super) enum FightWho { } /// A player in the End as the dragon sees it. #[derive(Clone, Copy, Debug)] -struct FightPlayer { - who: FightWho, - position: Vec3, - bounds: Aabb, - alive: bool, +pub(super) struct FightPlayer { + pub(super) who: FightWho, + pub(super) position: Vec3, + pub(super) bounds: Aabb, + pub(super) alive: bool, creative: bool, spectator: bool, } @@ -693,7 +693,7 @@ impl Game<'_> { } /// The players in the level the dragon sees (`level.players()`): the /// window's own, then every guest in the level. - fn fight_players(&self) -> Vec { + pub(super) fn fight_players(&self) -> Vec { let mut out = Vec::new(); if let Some(p) = self.player.as_ref() { out.push(FightPlayer { @@ -722,7 +722,7 @@ impl Game<'_> { } /// Run `f` as the fight's player `who` (a guest's turn, its knockback /// sent to its client). - fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { + pub(super) fn as_fight_player(&mut self, who: FightWho, f: impl FnOnce(&mut Self)) { match who { FightWho::Host => f(self), FightWho::Guest(conn) => { @@ -828,8 +828,10 @@ impl Game<'_> { continue; } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + // EndCrystal's constructor takes an id from the entity counter. + self.next_entity += 1; self.crystals.push(Crystal { - id: 0, + id: self.next_entity, position: at, show_bottom: true, time, @@ -1566,6 +1568,7 @@ impl Game<'_> { age: 0, duration: 200, from_dragon: true, + potion: None, }); } } @@ -2078,6 +2081,7 @@ impl Game<'_> { age: 0, duration: 600, from_dragon: false, + potion: None, }); self.audio.play( "minecraft:entity.dragon_fireball.explode", @@ -2110,6 +2114,10 @@ impl Game<'_> { let mut harmed: Vec<(FightWho, f32)> = Vec::new(); let mut clouds = std::mem::take(&mut self.breath_clouds); clouds.retain_mut(|c| { + // Lingering potions' clouds tick with the potions. + if c.potion.is_some() { + return true; + } c.age += 1; if c.age >= c.duration { return false; @@ -2257,8 +2265,22 @@ pub(super) struct Breath { pub(super) at: [f64; 3], pub(super) radius: f32, pub(super) age: i32, - duration: i32, - from_dragon: bool, + pub(super) duration: i32, + pub(super) from_dragon: bool, + /// A lingering potion's cloud (`ThrownLingeringPotion`): what it applies. + pub(super) potion: Option, +} +impl Breath { + /// `AreaEffectCloud.isWaiting`: before its wait time (20 ticks, 10 for a + /// lingering potion's). + pub(super) fn waiting(&self) -> bool { + self.age + < if self.potion.is_some() { + super::potions::LINGERING_WAIT + } else { + 20 + } + } } impl Game<'_> { /// `EnderDragonRenderer` and `EnderDragonModel.setupAnim`. @@ -2835,8 +2857,11 @@ impl Game<'_> { return false; } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); + // EndCrystal's constructor takes an id from the entity counter, so + // the crystal is an entity a command can name (`@e[type=end_crystal]`). + self.next_entity += 1; self.crystals.push(Crystal { - id: 0, + id: self.next_entity, position: Vec3::new(x + 0.5, y, z + 0.5), show_bottom: false, time, @@ -2853,6 +2878,21 @@ impl Game<'_> { self.swing_arm(); true } + /// `EndCrystal.kill` (`/kill`): the crystal is removed, without a blast + /// (`Entity.kill` does not hurt it). + pub(super) fn kill_crystal(&mut self, id: u32) { + if let Some(i) = self.crystals.iter().position(|c| c.id == id) { + self.destroy_crystal(i, None, CrystalDamage::Explosion); + } + } + /// `EnderDragon.kill` (`/kill`): `Entity.kill` removes the entity, it + /// does not hurt it (the dragon flies its death flight when its health + /// runs out). + pub(super) fn kill_dragon(&mut self, id: u32) { + if self.dragon.as_ref().is_some_and(|d| d.id == id) { + self.dragon = None; + } + } /// Any entity touching `room` (`Level.getEntities(null, box)`). fn entity_in(&self, room: Aabb) -> bool { let touches = |lo: Vec3, hi: Vec3| { diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 32d5113b0..bb0f3789d 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -19,7 +19,7 @@ use horizon_core::{ use std::{collections::HashMap, sync::Arc}; /// ServerLevel.END_SPAWN_POINT. -const END_SPAWN: [i32; 3] = [100, 50, 0]; +pub(super) const END_SPAWN: [i32; 3] = [100, 50, 0]; /// EnderDragonFight gateway ring radius and height. const GATEWAY_RADIUS: f64 = 96.0; const GATEWAY_Y: i32 = 75; @@ -253,10 +253,17 @@ impl Game<'_> { out } - /// LightmapRenderStateExtractor: End flashes add to the sky light factor. + /// LightmapRenderStateExtractor: End flashes add to the sky light factor + /// unless Hide Lightning Flashes is on (the sky sprite is not gated), a + /// third of it under a boss bar's world fog. pub(super) fn end_flash_sky(&self, sky: &mut horizon_client::environment::Sky, partial: f64) { - if self.dim == Dim::End { - sky.sky_light_factor += self.end.flash.intensity(partial as f32); + if self.dim == Dim::End && !self.settings.file.bool("hideLightningFlashes") { + let intensity = self.end.flash.intensity(partial as f32); + sky.sky_light_factor += if self.boss_overlay.should_create_world_fog() { + intensity / 3.0 + } else { + intensity + }; } } diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 66fbaa3e4..971639a42 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -60,12 +60,27 @@ impl Game<'_> { } } +impl Game<'_> { + /// Entity.setViewScale (LevelExtractor.extractVisibleEntities): the entity + /// distance option times the render distance's boost — 1 at 8 chunks, 2.5 + /// at 20 or more. The render distance is the client setting, capped by + /// the server's view distance when connected + /// (Options.getEffectiveRenderDistance). + pub(super) fn view_scale(&self) -> f64 { + let distance = match &self.remote { + Some(r) => self.settings.render_distance.min(r.view_distance), + None => self.settings.render_distance, + }; + (f64::from(distance) / 8.0).clamp(1.0, 2.5) * f64::from(self.settings.entity_distance) + } +} + /// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding -/// box's mean edge, scaled by the entity distance option. -pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 { +/// box's mean edge, scaled by the view scale. +pub(super) fn default_range(size: glam::DVec3, view_scale: f64) -> f64 { let edge = (size.x + size.y + size.z) / 3.0; let edge = if edge.is_nan() { 1.0 } else { edge }; - edge * 64.0 * f64::from(view_scale) + edge * 64.0 * view_scale } impl Game<'_> { diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 38fd74ed8..5aa540fcd 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -23,7 +23,7 @@ pub(super) struct Rocket { /// The entity id a server tracks it by (0 until it is tracked). pub id: u32, pub(super) position: Vec3, - previous: Vec3, + pub(super) previous: Vec3, pub(super) velocity: Vec3, life: i32, lifetime: i32, diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 39f9e5ffe..b308b9f1d 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -30,8 +30,8 @@ enum State { pub(super) struct Hook { /// Its entity id, which a server's players track it under. id: u32, - position: Vec3, - previous: Vec3, + pub(super) position: Vec3, + pub(super) previous: Vec3, velocity: Vec3, state: State, life: i32, @@ -770,8 +770,8 @@ impl Game<'_> { pub(super) struct RemoteHook { id: u32, owner: u32, - position: Vec3, - previous: Vec3, + pub(super) position: Vec3, + pub(super) previous: Vec3, } impl Hook { diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index d08c5f283..946d1c017 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -311,8 +311,9 @@ impl Game<'_> { let sprites = &self.gui.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); - // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%. - let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance); + // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at a view scale + // of 1. + let range = 16.0 * 64.0 * self.view_scale(); for f in &self.item_frames { let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); @@ -456,7 +457,7 @@ impl Game<'_> { } for (id, m, light) in maps { let entity_start = out.len(); - self.map_vertices(id, m, light, out); + self.map_vertices(id, true, m, light, out); self.cull_entity_vertices(out, entity_start); } } diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 28ec3fe8a..78bfbc410 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -21,6 +21,7 @@ use horizon_core::geometry::Vec3; use horizon_protocol::{ crypto::offline_uuid, entity_data::{Value, serializer}, + packets::play::{self, Clientbound as C}, }; use std::{ collections::HashMap, @@ -411,6 +412,26 @@ fn mob_meta( } } +/// What a client shakes a mob by: Entity.DATA_TICKS_FROZEN (7), whose full +/// count is `isFullyFrozen`, and Strider.DATA_SUFFOCATING (19, after +/// AgeableMob's two and DATA_BOOST_TIME). +fn mob_freeze_meta( + m: &Mob, + meta: &mut Vec<(u8, i32, Value)>, + defaults: &mut Vec<(u8, i32, Value)>, +) { + if m.ticks_frozen > 0 { + meta.push((7, serializer::INT, Value::Int(m.ticks_frozen))); + } + defaults.push((7, serializer::INT, Value::Int(0))); + if m.kind.id == "minecraft:strider" { + if m.extra.flag { + meta.push((19, serializer::BOOLEAN, Value::Bool(true))); + } + defaults.push((19, serializer::BOOLEAN, Value::Bool(false))); + } +} + /// The equipment a mob shows (ClientboundSetEquipmentPacket slots: main hand, /// off hand, feet, legs, chest, head, body, saddle). fn mob_equipment( @@ -419,13 +440,16 @@ fn mob_equipment( out: &mut Vec<(u8, Option)>, ) { let e = &m.extra; + // A horse's armour, a llama's carpet, a harness: Horizon keeps the body + // slot's item (6) in `head`. + let body = horizon_client::mobs::drops::head_is_body(m.species()); let slots = [ (0u8, &e.main_hand), (1, &e.off_hand), (2, &e.feet), (3, &e.legs), (4, &e.chest), - (5, &e.head), + (if body { 6 } else { 5 }, &e.head), ]; for (slot, item) in slots { if let Some(item) = item { @@ -715,6 +739,7 @@ impl Game<'_> { self.audio.capture = None; self.lan_events.clear(); self.lan_critical_hits.clear(); + self.lan_cushion_breaks.clear(); self.streaming.extra.clear(); if announce { self.system_message(Text::translate( @@ -928,6 +953,7 @@ impl Game<'_> { e.velocity = [m.velocity.x, m.velocity.y, m.velocity.z]; e.needs_sync = m.needs_sync; mob_meta(m, hub, player_entity, &mut e.meta, &mut e.defaults); + mob_freeze_meta(m, &mut e.meta, &mut e.defaults); mob_equipment(m, hub, &mut e.equipment); self.mob_attributes(m, &mut e.attributes); e.leash = leash; @@ -1004,6 +1030,9 @@ impl Game<'_> { for m in &mut self.mobs { m.needs_sync = false; } + for p in &mut self.creatures.projectiles { + p.needs_sync = false; + } // `runBlockEvents`' broadcast precedes the tick's block changes // (`ChunkHolder.broadcastChanges` in `tick_level` below): the // guest re-runs a piston's `triggerEvent` while its level still @@ -1164,7 +1193,8 @@ impl Game<'_> { drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); - // A mace's wind burst from a guest's attack. + // A blast from a guest's attack, and a mace's wind burst. + self.flush_lan_explosions(); let _ = self.flush_wind_bursts(); } @@ -1267,8 +1297,9 @@ impl Game<'_> { horizon_world::level::LevelEvent::LevelEvent { id, pos, data } => { // The acting guest does not predict the egg's teleport // particles, bone meal's growth, or anvil result sounds - // (these levelEvent calls name no excluded player). - let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) { + // (these levelEvent calls name no excluded player), nor + // the digger's own crack and hit sound (2019, 2020). + let except = if matches!(*id, 2015 | 1505 | 1029 | 1030 | 2019 | 2020) { None } else { self.lan_acting @@ -1330,6 +1361,33 @@ impl Game<'_> { /// Send the tick's level events, sounds and mob animations. fn lan_flush_effects(&mut self, host: &mut LanHost) { let critical_hits = std::mem::take(&mut self.lan_critical_hits); + for (state, at) in std::mem::take(&mut self.lan_cushion_breaks) { + if let Some(id) = host + .hub + .registry_id("minecraft:particle_type", "minecraft:block") + { + host.hub.broadcast_near( + at, + 32.0, + &C::LevelParticles(play::LevelParticles { + particle: horizon_protocol::entity_data::Particle { + id, + data: Some(horizon_protocol::entity_data::ParticleData::State( + state.0 as i32, + )), + }, + override_limiter: false, + always_show: false, + pos: at, + dist: [0.25, 0.0625, 0.25], + max_speed: [0.05; 3], + count: 10, + randomization: 0, + }), + None, + ); + } + } for (kind, pos, data, acting) in std::mem::take(&mut self.lan_events) { if kind == 2001 { host.broken @@ -1491,6 +1549,7 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + m.extra.avatar_pose = g.pose(); m.extra.sprinting = g.sprinting; // LivingEntity.DATA_EFFECT_PARTICLES: the swirls of its visible effects. let visible = || g.effects.list.iter().filter(|e| e.visible); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 8c51a3f2a..444c98ff2 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -165,6 +165,8 @@ pub(super) struct GuestSwap { acting: (Option, Option, Option), /// The packets queued for that guest. packets: Vec, + /// The entity events queued for that guest. + entity_events: Vec, /// The host's count of swings started, kept while the guest acts. swings: u32, /// How many projectiles there were: those added since are the guest's. @@ -389,6 +391,7 @@ impl Game<'_> { self.lan_acting_uuid.replace(g.uuid), ); let packets = std::mem::take(&mut self.guest_packets); + let entity_events = std::mem::take(&mut self.guest_entity_events); let swings = self.swings_started; let projectiles = self.creatures.projectiles.len(); let modifiers = std::mem::replace( @@ -449,6 +452,7 @@ impl Game<'_> { death_cause, acting, packets, + entity_events, swings, projectiles, modifiers, @@ -508,6 +512,7 @@ impl Game<'_> { combat, acting, packets, + entity_events, swings, projectiles, modifiers, @@ -529,6 +534,17 @@ impl Game<'_> { for packet in std::mem::replace(&mut self.guest_packets, packets) { host.hub.send_to(conn, &packet); } + // ServerPlayer.connection.send: the guest's own entity events. + let entity_id = host.hub.guests[i].entity_id; + for event in std::mem::replace(&mut self.guest_entity_events, entity_events) { + host.hub.send_to( + conn, + &C::EntityEvent(play::EntityEvent { + id: entity_id, + event, + }), + ); + } // ServerItemCooldowns.onCooldownStarted: the guest's own cooldown. for (group, duration) in std::mem::take(&mut self.guest_cooldowns) { host.hub.send_to( @@ -1200,6 +1216,7 @@ impl Game<'_> { } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), S::SignUpdate(p) => self.lan_sign_update(host, conn, p), + S::SetCommandBlock(p) => self.lan_set_command_block(host, conn, p), S::EditBook(p) => self.lan_edit_book(host, conn, p), S::ContainerSlotStateChanged(p) => { self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); @@ -1524,9 +1541,13 @@ impl Game<'_> { if let Some(victim) = Self::pvp_victim(host, conn, id) { if let Some(Some(strike)) = self.as_guest(host, conn, |g| g.pvp_strike()) && self.pvp_land(host, victim, &strike) - && strike.stops_sprint() { - self.as_guest(host, conn, |g| g.stop_sprint_after_extra_knockback()); + self.as_guest(host, conn, |g| { + g.pvp_exhaustion(); + if strike.stops_sprint() { + g.stop_sprint_after_extra_knockback(); + } + }); } return; } @@ -1916,21 +1937,8 @@ impl Game<'_> { continue; } let play = host.play.entry(conn).or_default(); - // Player.tick's ItemCooldowns.tick, once a tick for each player - // (the shield an axe disabled, a thrown pearl). - play.shield_cooldown = play.shield_cooldown.saturating_sub(1); + // ServerGamePacketListenerImpl.tick's dropSpamThrottler. play.creative_drops = play.creative_drops.saturating_sub(1); - // ServerItemCooldowns.onCooldownEnded: a finished entry is told to - // the guest (a duration of 0 removes it). - for group in play.cooldowns.tick() { - host.hub.send_to( - conn, - &C::Cooldown(play::Cooldown { - group: group.to_string(), - duration: 0, - }), - ); - } let digging = play.digging; let using = play.using.is_some(); let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100; @@ -1967,6 +1975,24 @@ impl Game<'_> { play.digging = None; } } + // Player.tick's ItemCooldowns.tick, once a tick for each player + // (the shield an axe disabled, a thrown pearl), after + // LivingEntity.tick's use: an entry a finished use starts has 20 + // ticks left when the next tick's packets are handled, as the + // guest's own client counts. + let play = host.play.entry(conn).or_default(); + play.shield_cooldown = play.shield_cooldown.saturating_sub(1); + // ServerItemCooldowns.onCooldownEnded: a finished entry is told to + // the guest (a duration of 0 removes it). + for group in play.cooldowns.tick() { + host.hub.send_to( + conn, + &C::Cooldown(play::Cooldown { + group: group.to_string(), + duration: 0, + }), + ); + } // Player.tick: a different main-hand item resets the attack // strength, and detectEquipmentUpdates gives the guest its modifiers. let g = &host.hub.guests[gi]; @@ -2188,7 +2214,7 @@ impl Game<'_> { } let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let at = g.position; - let sneaking = g.sneaking; + let (sneaking, sleeping) = (g.sneaking, g.sleeping); let mut soul = None; let events = self.as_guest(host, conn, |game| { let (rules, motion) = (game.world.health_rules, game.motion); @@ -2257,6 +2283,7 @@ impl Game<'_> { // Entity.applyEffectsFromBlocks along those moves: magma, cactus, // lit campfires and grown sweet berry bushes hurt (#1305). w.player.shift_key_down = sneaking; + let _ = w.player.set_sleeping(sleeping); w.player.freeze_immune = freeze_immune; let _ = w.server_block_damage(start); let _ = w.update_soul_speed_block(); @@ -2273,6 +2300,8 @@ impl Game<'_> { game.cauldron_extinguish(*pos); } } + // Entity.baseTick: rain puts out a burning player. + game.rain_extinguish_player(); // WitherRoseBlock.entityInside along those moves. for event in &events { if matches!(event, MotionEvent::InsideWitherRose) { @@ -2333,6 +2362,15 @@ impl Game<'_> { speed, }) => self.landing_dust(Some(host), state, position, count, speed), MotionEvent::Fall(event) => self.landing_block_updates(&event), + // LivingEntity.baseTick's entity event 67, to every client + // around, the guest's own included; this window draws it too. + MotionEvent::Drown => { + if let Some(g) = host.hub.guest(conn) { + host.hub + .entity_event(g.entity_id, super::combat::DROWN_EVENT, at); + } + self.drown_particles(at, [0.0; 3]); + } // HoneyBlock.maybeDoSlideEffects: the sound reaches the // others (Player.playSound excludes the player, whose client // plays it), the entity event 53 everyone around. @@ -2668,8 +2706,7 @@ impl Game<'_> { /// with Mending and gives the rest as points. Everyone near hears it. fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) { let g = &host.hub.guests[gi]; - // Player's standing and crouching boxes: 1.8 and 1.5 high. - let height = if g.sneaking { 1.5 } else { 1.8 }; + let height = f64::from(g.dimensions().height); let (conn, id, at) = (g.conn, g.entity_id, g.position); let unable = g.spectator() || g.dead || g.health <= 0.0; let play = host.play.entry(conn).or_default(); diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 665710be2..f5e35631d 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -342,6 +342,7 @@ impl Game<'_> { let mut e = state(p.id, kind, at(p.position), p.yaw, false); e.pitch = p.pitch; e.velocity = at(p.velocity); + e.needs_sync = p.needs_sync; // Projectile.getAddEntityPacket: the owner's id. e.data = match p.guest.and_then(|conn| hub.guest(conn)) { Some(g) => g.entity_id, @@ -466,7 +467,7 @@ impl Game<'_> { } out.push(e); } - // The dragon's breath clouds (AreaEffectCloud's DATA_RADIUS, + // The dragon's breath and lingering potion clouds (AreaEffectCloud's DATA_RADIUS, // DATA_WAITING for its 20-tick wait, and DATA_PARTICLE): the // client draws them from these (`tick_remote_clouds`). let breath = self.network_particle( @@ -484,10 +485,14 @@ impl Game<'_> { for b in self.breath_clouds.iter().filter(|b| b.id != 0) { let mut e = state(b.id, "minecraft:area_effect_cloud", b.at, 0.0, false); e.meta.push((8, serializer::FLOAT, Value::Float(b.radius))); - if b.age < 20 { + if b.waiting() { e.meta.push((9, serializer::BOOLEAN, Value::Bool(true))); } - if let Some(p) = &breath { + let particle = match &b.potion { + Some(p) => self.network_particle(&p.particle(), None), + None => breath.clone(), + }; + if let Some(p) = &particle { e.meta .push((10, serializer::PARTICLE, Value::Particle(p.clone()))); } diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 6527f1015..db042be43 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -175,9 +175,9 @@ impl Game<'_> { .iter() .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .map(|g| { - let [x, y, z] = g.position; - let height = if g.sneaking { 1.5 } else { 1.8 }; - ([x - 0.3, y, z - 0.3], [x + 0.3, y + height, z + 0.3]) + let b = g.bounds(); + let (lo, hi) = (b.min_position(), b.max_position()); + ([lo.x, lo.y, lo.z], [hi.x, hi.y, hi.z]) }) .collect() } @@ -319,7 +319,7 @@ impl Game<'_> { uuid: horizon_client::lan::playerdata::uuid_ints(g.uuid), position: g.position, eye: [x, y + g.eye_height(), z], - height: if g.sneaking { 1.5 } else { 1.8 }, + height: g.dimensions().height, creative: g.creative(), spectator: g.spectator(), alive: !g.dead, @@ -336,14 +336,9 @@ impl Game<'_> { } } -/// A guest's bounding box (0.6 wide, 1.8 tall, 1.5 crouching). +/// A guest's bounding box, by its pose (`Avatar.POSES`). pub(super) fn guest_bounds(g: &horizon_client::lan::guest::Guest) -> Aabb { - let [x, y, z] = g.position; - let height = if g.sneaking { 1.5 } else { 1.8 }; - Aabb::new( - Vec3::new(x - 0.3, y, z - 0.3), - Vec3::new(x + 0.3, y + height, z + 0.3), - ) + g.bounds() } #[cfg(test)] diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs index 648cef962..89c409ae4 100644 --- a/crates/horizon-client/src/game/lan_particles.rs +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -322,12 +322,21 @@ impl Game<'_> { /// sound and the push reach them on their own (the level's sounds, the /// motion a hurt player is sent), so the packet carries neither. pub(super) fn lan_explode( - &self, + &mut self, center: [f64; 3], small: bool, radius: f32, block_count: usize, ) { + // In a guest's turn (their hit on an end crystal or a minecart) the + // host holds the players (`as_guest`): the packet waits for the turn + // to end so that it reaches every player, the guest too. + if self.lan_acting.is_some() && self.lan.is_none() { + self.creatures + .lan_explosions + .push((center, small, radius, block_count)); + return; + } let emitter = if small { "minecraft:explosion" } else { @@ -341,6 +350,15 @@ impl Game<'_> { } } + /// The explosions guests' turns put off. + pub(super) fn flush_lan_explosions(&mut self) { + for (center, small, radius, block_count) in + std::mem::take(&mut self.creatures.lan_explosions) + { + self.lan_explode(center, small, radius, block_count); + } + } + /// A wind charge's burst (`AbstractWindCharge.explode`): gust emitters, /// no block particles, and for each player it pushed the push /// (`ServerExplosion.hitPlayers`), which only that client applies, as diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index 65520221a..aa969305f 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -86,9 +86,11 @@ impl Game<'_> { }; if let Some(strike) = self.pvp_strike() && self.pvp_land(&mut host, Victim::Guest(conn), &strike) - && strike.stops_sprint() { - self.stop_sprint_after_extra_knockback(); + self.pvp_exhaustion(); + if strike.stops_sprint() { + self.stop_sprint_after_extra_knockback(); + } } self.lan = Some(host); true @@ -106,8 +108,18 @@ impl Game<'_> { .map(|g| Victim::Guest(g.conn)) } + /// `Player.attack`'s `causeFoodExhaustion(0.1F)`, charged to the attacker + /// (the host, or a guest swapped in) only once the hit hurt the victim. + pub(super) fn pvp_exhaustion(&mut self) { + if let Some(p) = self.player.as_mut() + && !self.creative + { + p.cause_food_exhaustion(0.1); + } + } + /// The attacker's side of `Player.attack` (the host, or a guest swapped - /// in): the damage, the charge reset, the exhaustion and the swing. + /// in): the damage, the charge reset and the swing. pub(super) fn pvp_strike(&mut self) -> Option { let p = self.player.as_ref()?; let from = [p.position.x, p.position.y, p.position.z]; @@ -116,11 +128,6 @@ impl Game<'_> { let (strength, knockback_attack) = self.extra_knockback("minecraft:player", scale); let (xd, zd) = self.extra_knockback_direction(); self.attack_ticks = 0; - if let Some(p) = self.player.as_mut() - && !self.creative - { - p.cause_food_exhaustion(0.1); - } self.swing_arm(); Some(Strike { attacker: self.lan_acting, diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 260cc76c3..055d1ea1f 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -5,14 +5,10 @@ //! forcing the game mode. Its difficulty lock asks first (PopupScreen), and //! Restrictions opens RestrictionsScreen. //! Parity reference: https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/WorldOptionsScreen -use super::{ - Game, Screen, - game_rules_screen::{Exit, RulesScreen}, - integrated::ServerOptions, - lan::LanSettings, -}; +use super::{Game, Screen, integrated::ServerOptions, lan::LanSettings}; use horizon_client::{ font::Font, + game_rules_screen::{Exit, RulesScreen}, hud::{HudBatch, rgba}, text::{Text, named_color}, ui::{self, EditBox}, diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 9fa53eb25..dc815a39f 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -13,6 +13,12 @@ impl Game<'_> { self.particles .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); } + /// Event 2016: `Shulker.teleportSomewhere`'s particles between the + /// shell's old and new cells. + pub(super) fn shulker_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .block_teleportation(pos, data, [8, 8, 8], self.settings.particles); + } /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { self.particles @@ -135,6 +141,30 @@ impl Game<'_> { // Each guest plays it from the global packet. self.audio.play_unshared(sound, at, volume, 1.0); } + /// `ClientLevel.addBreakingBlockEffects`: the block's hit sound (only for + /// `play_sound`) and one crumb on the face being mined; nothing for air. + pub(super) fn breaking_block_effects( + &mut self, + pos: [i32; 3], + face: [i32; 3], + play_sound: bool, + ) { + let state = self.world.block(pos[0], pos[1], pos[2]); + if self.res.facts().is_air(state) { + return; + } + if play_sound { + let sounds = self.res.facts().get(state).sounds.clone(); + // Each guest plays it from the level event itself. + self.audio.play_unshared( + &sounds.hit, + Some(pos.map(|v| f64::from(v) + 0.5)), + (sounds.volume + 1.0) / 8.0, + sounds.pitch * 0.5, + ); + } + self.crack_particle(pos, face, state); + } /// `LevelEventHandler.potionSplashParticles` (2002 with `Effect`, 2007 /// with `InstantEffect`): eight splash potion crumbs, and a hundred /// spell particles in the potion's colour `data`, flung out in a disc. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 5f0286d02..b0c10e34b 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -120,6 +120,10 @@ impl Levels { .iter_mut() .map(|(d, p)| (*d, &mut p.world.chunks)) } + /// The levels that are not in place, by dimension. + pub(super) fn parked_dims(&self) -> Vec { + self.parked.keys().copied().collect() + } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 6da65c592..eb8c3687b 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -324,6 +324,13 @@ const DECORATION_TYPES: [(&str, &str); 24] = [ ("mineshaft", "map/decorations/mineshaft"), ("ocean_ruin_warm", "map/decorations/warm_ocean_ruins"), ]; +/// `MapDecorationType.showOnItemFrame` is false for the player arrows and the two markers. +fn shown_on_frame(sprite: &str) -> bool { + !matches!( + decoration_type(sprite), + Some("player" | "red_marker" | "blue_marker" | "player_off_map" | "player_off_limits") + ) +} /// The sprite of a decoration type that a `minecraft:map_decorations` /// entry or a server's packet names. fn decoration_sprite(id: &str) -> Option<&'static str> { @@ -1114,9 +1121,12 @@ impl Game<'_> { } /// `MapRenderer.render`: the map texture and its decorations under `m` /// (map pixels 0..128, y down), drawn at depth offsets toward the viewer. + /// `show_only_frame` (a map in an item frame) leaves out the decorations that + /// do not show on frames. pub(super) fn map_vertices( &mut self, id: i32, + show_only_frame: bool, m: glam::Mat4, light: u32, out: &mut Vec, @@ -1158,14 +1168,18 @@ impl Game<'_> { .get(&id) .map(|m| m.decorations.clone()) .unwrap_or_default(); - for (i, d) in decorations.iter().enumerate() { + let mut count = 0; + for d in &decorations { + if show_only_frame && !shown_on_frame(d.sprite) { + continue; + } let Some(s) = self.gui.atlas.sprites.get(d.sprite).copied() else { continue; }; let dm = glam::Mat4::from_translation(glam::Vec3::new( f32::from(d.x) / 2.0 + 64.0, f32::from(d.y) / 2.0 + 64.0, - -0.02 - i as f32 * 0.001, + -0.02 - count as f32 * 0.001, )) * glam::Mat4::from_rotation_z( (f32::from(d.rot) * 360.0 / 16.0).to_radians(), ) * glam::Mat4::from_scale(glam::Vec3::splat(4.0)) @@ -1187,6 +1201,7 @@ impl Game<'_> { [p(-1.0, 1.0), p(1.0, 1.0), p(1.0, -1.0), p(-1.0, -1.0)], [[s.u0, s.v0], [s.u1, s.v0], [s.u1, s.v1], [s.u0, s.v1]], ); + count += 1; } } /// `renderTwoHandedMap`: map `id` held in both hands, in view space (the @@ -1255,7 +1270,7 @@ impl Game<'_> { } } if has_data { - self.map_vertices(id, m, light, out); + self.map_vertices(id, false, m, light, out); } } } diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 072059e49..3737e4c20 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -90,6 +90,8 @@ pub(super) struct Minecart { /// Chest minecarts: the loot table rolled into `items` on load, saved /// again while the items are still that roll. pub loot: Option, + /// `Entity.firstTick`: not ticked yet (saved as `HasTicked`). + pub first_tick: bool, } pub(super) const WIDTH: f64 = 0.98; pub(super) const HEIGHT: f64 = 0.7; @@ -186,6 +188,7 @@ impl Minecart { fuse: -1, enabled: true, loot: None, + first_tick: true, } } pub fn bounds(&self) -> Aabb { @@ -536,6 +539,7 @@ impl Game<'_> { } /// `AbstractMinecart.tick` for one cart; returns false once it is gone. fn tick_cart(&mut self, c: &mut Minecart, intent: [f64; 2]) -> bool { + c.first_tick = false; c.previous = c.position; c.previous_yaw = c.yaw; c.hurt_time = (c.hurt_time - 1).max(0); @@ -713,12 +717,7 @@ impl Game<'_> { host.hub.here(g) && g.loaded && !g.dead && !g.spectator() && g.vehicle.is_none() }) { let [x, y, z] = g.position; - let height = if g.sneaking { 1.5 } else { 1.8 }; - let bb = Aabb::new( - Vec3::new(x - 0.3, y, z - 0.3), - Vec3::new(x + 0.3, y + height, z + 0.3), - ); - pushers.push((Vec3::new(x, y, z), bb)); + pushers.push((Vec3::new(x, y, z), g.bounds())); } } for (feet, bb) in pushers { @@ -1067,10 +1066,8 @@ impl Game<'_> { } self.riding = Some(self.carts[i].id); } + // AbstractMinecartContainer.interact: no sneak check. CartKind::Chest | CartKind::Hopper => { - if sneaking { - return false; - } let c = self.carts[i].clone(); let key = (i32::MAX - 15, CART_KEY_Y, c.id as i32); self.world @@ -1340,9 +1337,8 @@ impl Game<'_> { return; }; // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean - // edge, scaled by the entity distance option. - let range = - (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance); + // edge, scaled by the view scale. + let range = (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * self.view_scale(); for c in &self.carts { let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { @@ -1509,6 +1505,10 @@ impl Minecart { map.insert(JavaString::from(k), v); }; put("FlippedRotation", Tag::Byte(i8::from(self.flipped))); + // AbstractMinecart saves firstTick as HasTicked. A cart never burns: + // Entity.move sets -getFireImmuneTicks(), 0 for all but players. + put("HasTicked", Tag::Byte(i8::from(self.first_tick))); + put("Fire", Tag::Short(0)); match self.kind { CartKind::Chest | CartKind::Hopper => { put("Items", horizon_client::save::encode_items(&self.items)); @@ -1558,6 +1558,7 @@ impl Minecart { _ => 0.0, }; c.flipped = int("FlippedRotation").unwrap_or(0) != 0; + c.first_tick = int("HasTicked").unwrap_or(0) != 0; if kind.slots() > 0 { c.items = horizon_client::save::decode_items(tag.get("Items"), kind.slots()); } @@ -1582,4 +1583,30 @@ mod tests { assert_eq!(display_offset(CartKind::CommandBlock), 6.0); assert_eq!(display_offset(CartKind::Rideable), 6.0); } + + #[test] + fn a_cart_saves_as_never_ticked_until_it_ticks() { + use horizon_world::nbt::Tag; + let generated = Tag::compound([ + ("id", Tag::String("minecraft:chest_minecart".into())), + ( + "Pos", + Tag::List( + [0.5f64, 40.5, 0.5] + .map(|v| Tag::Double(v.to_bits())) + .to_vec(), + ), + ), + ("HasTicked", Tag::Byte(1)), + ("Fire", Tag::Short(0)), + ]); + let mut cart = Minecart::from_nbt(&generated, 1, CartKind::Chest).unwrap(); + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(1))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + cart.first_tick = false; + let saved = cart.to_nbt([0; 4], Some(&generated)); + assert_eq!(saved.get("HasTicked"), Some(&Tag::Byte(0))); + assert_eq!(saved.get("Fire"), Some(&Tag::Short(0))); + } } diff --git a/crates/horizon-client/src/game/mod_input.rs b/crates/horizon-client/src/game/mod_input.rs index 3df62c3d4..3769b03c9 100644 --- a/crates/horizon-client/src/game/mod_input.rs +++ b/crates/horizon-client/src/game/mod_input.rs @@ -31,6 +31,9 @@ impl Game<'_> { pub(super) fn mod_minimap(&self) -> Option { None } + pub(super) fn mod_far_terrain(&self) -> Option { + None + } } /// A mod's zoom (`render.set-zoom`), clamped by the runtime. @@ -51,6 +54,13 @@ pub(super) struct ModMinimap { pub(super) round: bool, } +/// A mod's far terrain (`render.set-far-terrain`), clamped by the runtime. +#[derive(Clone, Copy)] +pub(super) struct ModFarTerrain { + pub(super) distance: u32, + pub(super) reduced: bool, +} + #[cfg(feature = "mods")] impl Game<'_> { /// The main hand's stack as `input` shows it; none when it is empty. @@ -190,4 +200,12 @@ impl Game<'_> { round: m.round, }) } + /// The far terrain the first mod drawing one asks for. + pub(super) fn mod_far_terrain(&self) -> Option { + let f = self.mods.mods.far_terrain()?; + Some(ModFarTerrain { + distance: f.distance, + reduced: f.reduced, + }) + } } diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index fa4bbc209..fa0052bc5 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -126,6 +126,19 @@ impl Game<'_> { if !equine::is_equine(species) || !m.alive() || Some(m.id) == self.riding { return false; } + // AbstractHorse.mobInteract: a horse a mob rides (`isVehicle`) has no + // seat, inventory or feeding to give. Camels seat two and check their + // passengers themselves. + let id = m.id; + if !matches!(species, Species::Camel | Species::CamelHusk) + && self + .mobs + .iter() + .any(|p| p.extra.mount == Some(id) && !p.removed && p.alive()) + { + return false; + } + let m = &self.mobs[index]; // AbstractHorse.mobInteract: shift + use opens a tamed adult's inventory. if !m.is_baby() && m.extra.tame diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 9f7561e53..6b5324e3a 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -338,7 +338,9 @@ impl Game<'_> { let (r, u) = (right.as_vec3() * 0.025, up.as_vec3() * 0.025); // Text space: x right, y down (scale 0.025, -0.025). let at = |x: f32, y: f32| o + r * x - u * y; - let chars: Vec<(char, u32)> = text + // Component.getVisualOrderText. + let shown = horizon_client::bidi::visual(text); + let chars: Vec<(char, u32)> = shown .spans .iter() .flat_map(|s| { diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 87ba81c93..c8142284a 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -2,7 +2,9 @@ //! `Entity.setAsInsidePortal` / `handlePortal` with `PortalProcessor`, //! `NetherPortalBlock.getPortalTransitionTime` and `getPortalDestination` //! (`PortalForcer` through `horizon_world::level::portal_travel`), and -//! `LocalPlayer.handlePortalTransitionEffect`. +//! `LocalPlayer.handlePortalTransitionEffect`. Items and mobs also go through +//! End portals here (`EndPortalBlock.entityInside` / `getPortalDestination`); +//! the player's End portals are game/end.rs's. //! //! Only one dimension is loaded at a time. The player's destination is found //! once the other dimension has loaded around it. An item or mob that goes @@ -12,7 +14,7 @@ use super::{Dim, Game, Screen}; use horizon_client::Result; use horizon_client::nether_portal::PortalState; use horizon_core::{ - geometry::{Axis, Vec3}, + geometry::{Aabb, Axis, Vec3}, position::BlockPos, random::RandomSource, }; @@ -40,6 +42,32 @@ pub(super) struct Plan { offset: Vec3, width: f32, height: f32, + /// Through an End portal: `approximate` is the End's spawn point, or the + /// Overworld's shared spawn. + end: bool, +} + +impl Plan { + /// `EndPortalBlock.getPortalDestination` for an entity other than a + /// player in `from`: the End's spawn point, or out of the End the + /// Overworld's shared spawn `world_spawn`. + fn end_portal(from: Dim, world_spawn: BlockPos, width: f32, height: f32) -> Self { + let (dim, approximate) = if from == Dim::End { + (Dim::Overworld, world_spawn) + } else { + let [x, y, z] = super::end::END_SPAWN; + (Dim::End, BlockPos::new(x, y, z)) + }; + Self { + dim, + approximate, + entry_x_axis: true, + offset: Vec3::ZERO, + width, + height, + end: true, + } + } } /// An entity on its way to a dimension that isn't loaded. @@ -81,6 +109,89 @@ fn rotate_y(v: Vec3, degrees: f32) -> Vec3 { fn doubles(values: [f64; 3]) -> Tag { Tag::List(values.iter().map(|v| Tag::Double(v.to_bits())).collect()) } +/// Whether a `width` by `height` box moving from `from` to `to` meets the End +/// portal at `pos`: `Entity.collidedWithShapeMovingFrom` against its +/// entity-inside shape, y 6/16..12/16 of the block. +fn touches_end_portal(from: Vec3, to: Vec3, width: f32, height: f32, pos: BlockPos) -> bool { + let half = f64::from(width) / 2.0; + let start = Aabb::new( + Vec3::new(from.x - half, from.y, from.z - half), + Vec3::new(from.x + half, from.y + f64::from(height), from.z + half), + ); + let (x, y, z) = (f64::from(pos.x), f64::from(pos.y), f64::from(pos.z)); + let shape = Aabb::new( + Vec3::new(x, y + 0.375, z), + Vec3::new(x + 1.0, y + 0.75, z + 1.0), + ); + start.collided_along_vector(to.subtract(from), &[shape]) +} +/// `PositionMoveRotation.calculateAbsolute` for an End portal's transition +/// of an entity facing `[yaw, pitch]`: into the End it faces west and keeps +/// its pitch (`Relative.X_ROT`); out of it both turn by the world spawn's +/// angles (`Relative.ROTATION`). The pitch stays within ±90. +fn end_portal_rotation(into_end: bool, [yaw, pitch]: [f32; 2], spawn: [f32; 2]) -> [f32; 2] { + let (yaw, pitch) = if into_end { + // Direction.WEST.toYRot(). + (90.0, pitch) + } else { + (yaw + spawn[0], pitch + spawn[1]) + }; + [yaw, pitch.clamp(-90.0, 90.0)] +} +/// A waiting entity as `horizon_portal_arrivals.dat` keeps it. +fn arrival_tag(a: &Arrival) -> Tag { + let p = &a.plan; + Tag::compound([ + ("dimension", Tag::String(p.dim.id().into())), + ("x", Tag::Int(p.approximate.x)), + ("y", Tag::Int(p.approximate.y)), + ("z", Tag::Int(p.approximate.z)), + ("x_axis", Tag::Int(i32::from(p.entry_x_axis))), + ("right", Tag::Double(p.offset.x.to_bits())), + ("up", Tag::Double(p.offset.y.to_bits())), + ("forward", Tag::Double(p.offset.z.to_bits())), + ("width", Tag::Float(p.width.to_bits())), + ("height", Tag::Float(p.height.to_bits())), + ("end", Tag::Int(i32::from(p.end))), + ("entity", a.tag.clone()), + ]) +} +/// The waiting entity `arrival_tag` wrote. +fn arrival_from_tag(a: &Tag) -> Option { + let int = |k: &str| match a.get(k) { + Some(Tag::Int(v)) => Some(*v), + _ => None, + }; + let float = |k: &str| match a.get(k) { + Some(Tag::Float(v)) => Some(f32::from_bits(*v)), + _ => None, + }; + let double = |k: &str| match a.get(k) { + Some(Tag::Double(v)) => Some(f64::from_bits(*v)), + _ => None, + }; + let dim = Dim::from_id(&horizon_client::save::text(a.get("dimension"))?); + let (Some(x), Some(y), Some(z), Some(tag)) = (int("x"), int("y"), int("z"), a.get("entity")) + else { + return None; + }; + Some(Arrival { + plan: Plan { + dim, + approximate: BlockPos::new(x, y, z), + entry_x_axis: int("x_axis").unwrap_or(1) != 0, + offset: Vec3::new( + double("right").unwrap_or(0.5), + double("up").unwrap_or(0.0), + double("forward").unwrap_or(0.0), + ), + width: float("width").unwrap_or(0.25), + height: float("height").unwrap_or(0.25), + end: int("end").unwrap_or(0) != 0, + }, + tag: tag.clone(), + }) +} impl Game<'_> { /// The world border's extent. @@ -146,8 +257,54 @@ impl Game<'_> { offset, width, height, + end: false, } } + /// The plan of an item or mob going through the portal block at `entry`: + /// an End portal's fixed destination, else the Nether portal's. + fn entity_plan( + &self, + entry: BlockPos, + at: Vec3, + width: f32, + height: f32, + reset_forward: bool, + ) -> Plan { + if !self.is_end_portal(self.world.block(entry.x, entry.y, entry.z)) { + return self.portal_plan(entry, at, width, height, reset_forward); + } + let spawn = self.level.world_spawn.unwrap_or_else(|| { + self.spawn.map_or([0, 64, 0], |s| { + [s.x.floor() as i32, s.y.floor() as i32, s.z.floor() as i32] + }) + }); + Plan::end_portal( + self.dim, + BlockPos::new(spawn[0], spawn[1], spawn[2]), + width, + height, + ) + } + fn is_end_portal(&self, state: horizon_world::registry::BlockStateId) -> bool { + &*self.res.facts().get(state).name == "minecraft:end_portal" + } + /// Where an item or mob through an End portal lands once `plan`'s level + /// has loaded around it: the bottom centre of the End's spawn point, + /// above the platform built below it (`EndPlatformFeature.createEndPlatform`); + /// out of the End, the top of the shared spawn's column + /// (`Entity.adjustSpawnLocation`). + fn end_portal_exit(&mut self, plan: &Plan) -> Vec3 { + let p = plan.approximate; + let centre = Vec3::new(f64::from(p.x) + 0.5, f64::from(p.y), f64::from(p.z) + 0.5); + if plan.dim == Dim::End { + if let Err(e) = self.end_arrival(centre) { + log::error!("End platform: {e}"); + } + return centre; + } + let y = self.motion_top(p.x, p.z); + Vec3::new(centre.x, f64::from(y), centre.z) + } /// The nether portal blocks of the chunks within `radius` of `center` /// (the points of interest `PortalForcer` searches): loaded chunks as /// they are, the others as saved; chunks never generated have none. @@ -520,9 +677,10 @@ impl Game<'_> { || self.ridden_by_guest(id) || self.mobs.iter().any(|m| m.extra.mount == Some(id)) } - /// `NetherPortalBlock.entityInside` for the items, mobs and empty boats - /// and minecarts that moved this tick: the portal blocks their box swept - /// through. + /// `NetherPortalBlock.entityInside` and `EndPortalBlock.entityInside` + /// for the items, mobs and empty boats and minecarts that moved this + /// tick: the portal blocks their box swept through (an End portal's + /// transition time is 0 too). pub(super) fn find_entity_portals(&mut self) { if self.remote.is_some() { return; @@ -570,7 +728,7 @@ impl Game<'_> { .set_inside(pos, ENTITY_DELAY); } } - /// The first nether portal block an entity box swept through + /// The first nether or End portal block an entity box swept through /// (`Entity.checkInsideBlocks`, whose first portal sets the entry). fn swept_portal( &self, @@ -604,11 +762,9 @@ impl Game<'_> { bounds, 1_000_000, |p, _| { - if self - .res - .behaviours() - .portal_axis(self.world.block(p.x, p.y, p.z)) - .is_some() + let state = self.world.block(p.x, p.y, p.z); + if self.res.behaviours().portal_axis(state).is_some() + || (self.is_end_portal(state) && touches_end_portal(from, to, width, height, p)) { found = Some(p); return false; @@ -618,8 +774,8 @@ impl Game<'_> { ); found } - /// Whether a section `reach` touches has a nether portal state in its - /// palette: without one, no block there is a portal. Palette answers are + /// Whether a section `reach` touches has a nether or End portal state in + /// its palette: without one, no block there is a portal. Palette answers are /// kept per chunk across ticks (`portal_sections`); a box over many /// sections is not checked. fn may_hold_portal( @@ -656,9 +812,8 @@ impl Game<'_> { (z0..=z1).any(|cz| { chunks.get(&(cx, cz)).is_some_and(|chunk| { sections.get((cx, cz), chunk, |v| { - behaviours - .portal_axis(horizon_world::registry::BlockStateId(v)) - .is_some() + let state = horizon_world::registry::BlockStateId(v); + behaviours.portal_axis(state).is_some() || self.is_end_portal(state) }) & y_mask != 0 }) @@ -670,7 +825,7 @@ impl Game<'_> { fn send_through_portal(&mut self, id: u32, entry: BlockPos) { if let Some(i) = self.dropped.iter().position(|e| e.id == id) { let e = &self.dropped[i]; - let plan = self.portal_plan(entry, e.position, 0.25, 0.25, false); + let plan = self.entity_plan(entry, e.position, 0.25, 0.25, false); if !self.may_enter(plan.dim) { return; } @@ -686,7 +841,7 @@ impl Game<'_> { self.portals.dirty = true; } else if let Some(i) = self.mobs.iter().position(|m| m.id == id) { let m = &self.mobs[i]; - let plan = self.portal_plan(entry, m.position, m.width(), m.height(), true); + let plan = self.entity_plan(entry, m.position, m.width(), m.height(), true); if !self.may_enter(plan.dim) { return; } @@ -716,7 +871,7 @@ impl Game<'_> { } else if let Some(i) = self.boats.iter().position(|b| b.id == id) { let b = &self.boats[i]; let (width, height) = (super::boats::WIDTH as f32, super::boats::HEIGHT as f32); - let plan = self.portal_plan(entry, b.position, width, height, false); + let plan = self.entity_plan(entry, b.position, width, height, false); if !self.may_enter(plan.dim) { return; } @@ -741,7 +896,7 @@ impl Game<'_> { super::minecarts::WIDTH as f32, super::minecarts::HEIGHT as f32, ); - let plan = self.portal_plan(entry, c.position, width, height, false); + let plan = self.entity_plan(entry, c.position, width, height, false); if !self.may_enter(plan.dim) { return; } @@ -754,8 +909,8 @@ impl Game<'_> { } } /// Entities waiting for the loaded dimension whose exit area is loaded: - /// their exit portal (found or built), position, turned yaw and motion, - /// and portal cooldown; they join the world with the chunk entities. + /// their exit portal (found or built) or End destination, position, + /// turned yaw and motion, and portal cooldown; they join the world with the chunk entities. pub(super) fn resolve_arrivals(&mut self) { if self.remote.is_some() { return; @@ -772,21 +927,28 @@ impl Game<'_> { } let Arrival { plan, mut tag } = self.portals.arrivals.remove(i); self.portals.dirty = true; - let Some(exit) = self.nether_exit_portal(&plan) else { - continue; - }; - let (at, rotation) = self.arrival(&plan, exit); - let motion = rotate_y(horizon_client::entity_nbt::motion(&tag), -rotation); + let motion = horizon_client::entity_nbt::motion(&tag); let [yaw, pitch] = horizon_client::entity_nbt::rotation(&tag); + let (at, motion, [yaw, pitch]) = if plan.end { + // Relative.DELTA: the motion is kept. + let at = self.end_portal_exit(&plan); + let into_end = plan.dim == Dim::End; + let turn = + end_portal_rotation(into_end, [yaw, pitch], self.level.world_spawn_angle); + (at, motion, turn) + } else { + let Some(exit) = self.nether_exit_portal(&plan) else { + continue; + }; + let (at, rotation) = self.arrival(&plan, exit); + (at, rotate_y(motion, -rotation), [yaw + rotation, pitch]) + }; if let Tag::Compound(c) = &mut tag { c.insert("Pos".into(), doubles([at.x, at.y, at.z])); c.insert("Motion".into(), doubles([motion.x, motion.y, motion.z])); c.insert( "Rotation".into(), - Tag::List(vec![ - Tag::Float((yaw + rotation).to_bits()), - Tag::Float(pitch.to_bits()), - ]), + Tag::List(vec![Tag::Float(yaw.to_bits()), Tag::Float(pitch.to_bits())]), ); // setPortalCooldown before the teleport, copied by restoreFrom. c.insert("PortalCooldown".into(), Tag::Int(ENTITY_DELAY)); @@ -823,75 +985,117 @@ impl Game<'_> { let Some(Tag::List(list)) = root.get("arrivals") else { return; }; - for a in list { - let int = |k: &str| match a.get(k) { - Some(Tag::Int(v)) => Some(*v), - _ => None, - }; - let float = |k: &str| match a.get(k) { - Some(Tag::Float(v)) => Some(f32::from_bits(*v)), - _ => None, - }; - let double = |k: &str| match a.get(k) { - Some(Tag::Double(v)) => Some(f64::from_bits(*v)), - _ => None, - }; - let dim = match horizon_client::save::text(a.get("dimension")).as_deref() { - Some("minecraft:the_nether") => Dim::Nether, - Some(_) => Dim::Overworld, - None => continue, - }; - let (Some(x), Some(y), Some(z), Some(tag)) = - (int("x"), int("y"), int("z"), a.get("entity")) - else { - continue; - }; - self.portals.arrivals.push(Arrival { - plan: Plan { - dim, - approximate: BlockPos::new(x, y, z), - entry_x_axis: int("x_axis").unwrap_or(1) != 0, - offset: Vec3::new( - double("right").unwrap_or(0.5), - double("up").unwrap_or(0.0), - double("forward").unwrap_or(0.0), - ), - width: float("width").unwrap_or(0.25), - height: float("height").unwrap_or(0.25), - }, - tag: tag.clone(), - }); - } + self.portals + .arrivals + .extend(list.iter().filter_map(arrival_from_tag)); } /// Write the waiting entities when they changed. pub(super) fn save_portal_arrivals(&mut self) { if !self.portals.dirty || self.remote.is_some() { return; } - let list = self - .portals - .arrivals - .iter() - .map(|a| { - let p = &a.plan; - Tag::compound([ - ("dimension", Tag::String(p.dim.id().into())), - ("x", Tag::Int(p.approximate.x)), - ("y", Tag::Int(p.approximate.y)), - ("z", Tag::Int(p.approximate.z)), - ("x_axis", Tag::Int(i32::from(p.entry_x_axis))), - ("right", Tag::Double(p.offset.x.to_bits())), - ("up", Tag::Double(p.offset.y.to_bits())), - ("forward", Tag::Double(p.offset.z.to_bits())), - ("width", Tag::Float(p.width.to_bits())), - ("height", Tag::Float(p.height.to_bits())), - ("entity", a.tag.clone()), - ]) - }) - .collect(); + let list = self.portals.arrivals.iter().map(arrival_tag).collect(); let root = Tag::compound([("arrivals", Tag::List(list))]); if horizon_client::save::write_dat(&self.arrivals_path(), root).is_ok() { self.portals.dirty = false; } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn end_portals_lead_to_the_end_spawn_and_back_to_the_world_spawn() { + let spawn = BlockPos::new(-7, 70, 12); + for from in [Dim::Overworld, Dim::Nether] { + let plan = Plan::end_portal(from, spawn, 0.9, 1.4); + assert_eq!(plan.dim, Dim::End); + assert_eq!(plan.approximate, BlockPos::new(100, 50, 0)); + assert!(plan.end); + } + let plan = Plan::end_portal(Dim::End, spawn, 0.25, 0.25); + assert_eq!(plan.dim, Dim::Overworld); + assert_eq!(plan.approximate, spawn); + } + + #[test] + fn the_end_portal_shape_takes_falling_items_and_standing_mobs() { + let portal = BlockPos::new(0, 100, 3); + let at = |y| Vec3::new(0.5, y, 3.5); + // A dropped item falling through the slab, or in it. + assert!(touches_end_portal( + at(100.6), + at(100.56), + 0.25, + 0.25, + portal + )); + // One tick's fall across the whole slab, in it at neither end. + assert!(touches_end_portal(at(101.0), at(99.9), 0.25, 0.25, portal)); + // Resting below the slab (on the floor) or above it. + assert!(!touches_end_portal( + at(100.0), + at(100.0), + 0.25, + 0.25, + portal + )); + assert!(!touches_end_portal( + at(100.8), + at(100.8), + 0.25, + 0.25, + portal + )); + // A cow standing in the portal block. + assert!(touches_end_portal(at(100.0), at(100.0), 0.9, 1.4, portal)); + // Beside it. + let beside = Vec3::new(2.0, 100.0, 3.5); + assert!(!touches_end_portal(beside, beside, 0.9, 1.4, portal)); + } + + #[test] + fn end_portals_turn_entities_like_their_teleport_transition() { + // Into the End: facing west, pitch kept. + assert_eq!( + end_portal_rotation(true, [-30.0, 20.0], [45.0, 10.0]), + [90.0, 20.0] + ); + // Out of it: turned by the world spawn's yaw and pitch, pitch clamped. + assert_eq!( + end_portal_rotation(false, [-30.0, 20.0], [45.0, 10.0]), + [15.0, 30.0] + ); + assert_eq!( + end_portal_rotation(false, [0.0, 80.0], [0.0, 30.0]), + [0.0, 90.0] + ); + } + + #[test] + fn waiting_arrivals_keep_their_end_destination_when_saved() { + let tag = Tag::compound([("id", Tag::String("minecraft:cow".into()))]); + for (from, dim) in [(Dim::Overworld, Dim::End), (Dim::End, Dim::Overworld)] { + let arrival = Arrival { + plan: Plan::end_portal(from, BlockPos::new(3, 64, -5), 0.9, 1.4), + tag: tag.clone(), + }; + let back = arrival_from_tag(&arrival_tag(&arrival)).unwrap(); + assert_eq!(back.plan.dim, dim); + assert_eq!(back.plan.approximate, arrival.plan.approximate); + assert!(back.plan.end); + assert_eq!(back.tag, tag); + } + // Arrivals saved before End portals were Nether portal plans. + let mut old = arrival_tag(&Arrival { + plan: Plan::end_portal(Dim::End, BlockPos::new(0, 64, 0), 0.25, 0.25), + tag, + }); + if let Tag::Compound(c) = &mut old { + c.remove(&"end".into()); + } + assert!(!arrival_from_tag(&old).unwrap().plan.end); + } +} diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 569c63083..89d7738f8 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -34,6 +34,10 @@ pub fn open_folder(dir: &Path) { log::warn!("Horizon: could not open {}: {e}", dir.display()); } } +/// `Util.getPlatform().openUri`: the system browser on the link. +pub fn open_uri(uri: &str) { + open_folder(Path::new(uri)); +} /// The resource root to load from, given the vanilla root, the selection and /// a server's packs, which go on top (`Pack.Position.TOP`, fixed). pub fn startup_root( diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 321e59f7d..1b839f5b0 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -267,8 +267,7 @@ impl Game<'_> { // measured from the box's centre (HangingEntity's position). let (lo, hi) = p.bounds(); let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); - let range = - super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + let range = super::entity_culling::default_range(hi - lo, self.view_scale()); if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { continue; } diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 9e727d35d..8ceea7e12 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -193,12 +193,12 @@ impl Game<'_> { if let Some(a) = p.arrow.as_mut() { a.last_state = in_block.and_then(|t| self.state_from_nbt(&t)); } - self.creatures.projectiles.push(p); + self.add_projectile(p); } } "minecraft:fireball" | "minecraft:small_fireball" => { if let Some(p) = entity_nbt::fireball_from_nbt(&tag, player_uuid) { - self.creatures.projectiles.push(p); + self.add_projectile(p); } } "minecraft:falling_block" => { @@ -290,14 +290,22 @@ impl Game<'_> { "minecraft:ender_dragon" => { let seed = self.world.random.next_long(); if self.dragon.is_none() - && let Some(d) = super::dragon::Dragon::from_nbt(&tag, seed) + && let Some(mut d) = super::dragon::Dragon::from_nbt(&tag, seed) { + // EnderDragon's constructor takes its id and its + // parts' from the entity counter. + d.id = self.next_entity + 1; + self.next_entity += 9; self.dragon = Some(d); } } "minecraft:end_crystal" => { let time = self.world.random.next_int_bound(100_000).unwrap_or(0); - if let Some(c) = super::dragon::Crystal::from_nbt(&tag, time) { + if let Some(mut c) = super::dragon::Crystal::from_nbt(&tag, time) { + // EndCrystal's constructor takes an id from the + // entity counter. + self.next_entity += 1; + c.id = self.next_entity; self.crystals.push(c); } } @@ -533,6 +541,14 @@ impl Game<'_> { self.persist.uuids.remove(&id); self.persist.raw.remove(&id); } + /// The compound an entity without a Horizon entity ID was loaded with + /// (the crystals and the dragon), found again by type and position. + pub(super) fn persist_anon(&self, kind: &str, p: Vec3) -> (Option<[i32; 4]>, Option<&Tag>) { + self.persist + .anon + .get(&anon_key(kind, p)) + .map_or((None, None), |(_, uuid, raw)| (*uuid, Some(raw))) + } /// The compound an entity was loaded with (and commands have edited). pub(super) fn persist_raw(&self, id: u32) -> Option<&Tag> { self.persist.raw.get(&id) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 4dd8cdb05..5efac4927 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -2,7 +2,12 @@ //! `Consumable`), throwing splash/lingering potions (`ThrownSplashPotion`), //! filling glass bottles (`BottleItem`), the per-tick effect application, //! effect attribute modifiers and the HUD effect icons (`Hud.extractEffects`). -use super::{Game, Screen, item_draw::owner_at}; +use super::{ + Game, Screen, + dragon::{Breath, FightPlayer, FightWho}, + item_draw::owner_at, + remote_projectiles::cloud_client_tick, +}; use horizon_assets::item_model::DisplayContext; use horizon_client::{ block_entity_render::vertex_light, @@ -12,9 +17,13 @@ use horizon_client::{ hud_layout, hud_overlays, inventory_effects, items::ItemStack, mesher::Vertex, + particles::{ParticleOptions, ParticleType}, text::Text, }; -use horizon_core::{geometry::Vec3, random::RandomSource}; +use horizon_core::{ + geometry::{Aabb, Vec3}, + random::RandomSource, +}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] @@ -31,6 +40,35 @@ pub(super) struct ThrownPotion { /// for a dispenser's). owner: Option, } +/// `AreaEffectCloud` wait time set by `ThrownLingeringPotion.onHitAsPotion`. +pub(super) const LINGERING_WAIT: i32 = 10; +/// `AreaEffectCloud.DEFAULT_REAPPLICATION_DELAY`. +const REAPPLICATION_DELAY: i32 = 20; +/// An entity a cloud has affected (`AreaEffectCloud.victims`). +#[derive(Clone, Copy, PartialEq)] +enum Victim { + Mob(u32), + Player(FightWho), +} +/// What a lingering potion's `AreaEffectCloud` applies: the potion's effects +/// (at the lingering item's 0.25 duration scale) and who it has affected. +pub(super) struct PotionCloud { + effects: &'static [(&'static str, i32, i32)], + /// The potion's colour (`PotionContents.getColor`). + color: u32, + /// Each victim and the tick it can be affected again. + victims: Vec<(Victim, i32)>, + /// Who its instant damage names (`indirectMagic(cloud, owner)`): the + /// thrower, else the cloud. + source: Text, +} +impl PotionCloud { + /// `AreaEffectCloud.updateParticle`: an entity effect in the potion's colour. + pub(super) fn particle(&self) -> ParticleOptions { + let c = |shift: u32| (self.color >> shift & 255) as f32 / 255.0; + ParticleOptions::colored(ParticleType::EntityEffect, [c(16), c(8), c(0), 1.0]) + } +} /// A mob's effect ids carry the `minecraft:` namespace. fn mob_effect_id(id: &str) -> Option<&'static str> { use std::{collections::HashMap, sync::OnceLock}; @@ -48,6 +86,39 @@ fn mob_effect_id(id: &str) -> Option<&'static str> { .get(id) .copied() } +/// `LivingEntity.canBeAffected` with the mob overrides (`WitherBoss` and +/// `WitherSkeleton` shrug off wither, `Spider` and `AbstractNautilus` poison, +/// `Parched` weakness): the immune-to-infested and immune-to-oozing tags +/// decide first, then the tag of mobs that ignore poison and regeneration. +fn mob_can_be_affected( + tags: &std::collections::HashMap>, + kind: &str, + effect: &str, +) -> bool { + let effect = effect.trim_start_matches("minecraft:"); + let kind = kind.trim_start_matches("minecraft:"); + let overridden = match kind { + "wither" | "wither_skeleton" => effect == "wither", + "spider" | "cave_spider" | "nautilus" | "zombie_nautilus" => effect == "poison", + "parched" => effect == "weakness", + _ => false, + }; + if overridden { + return false; + } + let in_tag = |tag: &str| { + tags.get(tag) + .is_some_and(|t| t.contains(&format!("minecraft:{kind}"))) + }; + if in_tag("minecraft:immune_to_infested") { + effect != "infested" + } else if in_tag("minecraft:immune_to_oozing") { + effect != "oozing" + } else { + !in_tag("minecraft:ignores_poison_and_regen") + || (effect != "regeneration" && effect != "poison") + } +} impl Game<'_> { /// A splash potion, lingering potion or experience bottle in flight (the /// player's throws and dispensers both end up here). @@ -313,6 +384,7 @@ impl Game<'_> { return true; } self.using = None; + self.send_use_item_complete(); self.post_entity_event("minecraft:drink", horizon_client::mobs::Who::Player); if ominous { self.drink_ominous_bottle(slot, stack); @@ -390,6 +462,7 @@ impl Game<'_> { self.tick_mob_effects(); if running { self.tick_thrown_potions(); + self.tick_potion_clouds(); } } /// `LivingEntity.tickEffects` (server side) for `self.player`, the local @@ -547,29 +620,176 @@ impl Game<'_> { let state = self.world .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts().get(state).full_collision - || self.mobs.iter().any(|m| { - m.alive() - && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 - && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 - && p.y >= m.position.y - && p.y <= m.position.y + m.kind.height - }) - { - hit = Some(p); + let mob = self.mobs.iter().find(|m| { + m.alive() + && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 + && (m.position.z - p.z).abs() < m.kind.width / 2.0 + 0.125 + && p.y >= m.position.y + && p.y <= m.position.y + m.kind.height + }); + if self.res.facts().get(state).full_collision || mob.is_some() { + hit = Some((p, mob.map(|m| m.position))); break; } } - if let Some(p) = hit { - landed.push((t.stack.clone(), p, t.owner.clone())); + if let Some((p, mob)) = hit { + landed.push((t.stack.clone(), p, mob, t.owner.clone())); return false; } t.position = next; t.age < 1200 && t.position.y > -128.0 }); self.potions.thrown = thrown; - for (stack, at, owner) in landed { - self.splash(&stack, at, owner); + for (stack, at, mob, owner) in landed { + self.splash(&stack, at, mob, owner); + } + } + /// `AreaEffectCloud.tick` for the lingering potions' clouds: the client + /// tick's particles, then the server tick. + fn tick_potion_clouds(&mut self) { + if self.breath_clouds.iter().all(|c| c.potion.is_none()) { + return; + } + let players: Vec = self + .fight_players() + .into_iter() + .filter(|p| p.alive) + .collect(); + let mut clouds = std::mem::take(&mut self.breath_clouds); + clouds.retain_mut(|c| c.potion.is_none() || self.tick_potion_cloud(c, &players)); + self.breath_clouds.append(&mut clouds); + } + /// `AreaEffectCloud.serverTick` for a lingering potion's cloud: after its + /// wait it shrinks, and every 5 ticks it affects the living entities in + /// its box and radius that were not affected in the last 20 ticks, each + /// taking some of its radius. False once it is gone. + fn tick_potion_cloud(&mut self, c: &mut Breath, players: &[FightPlayer]) -> bool { + c.age += 1; + let Some(potion) = c.potion.as_mut() else { + return true; + }; + if c.age - LINGERING_WAIT >= c.duration { + return false; + } + let waiting = c.age < LINGERING_WAIT; + cloud_client_tick( + &mut self.particles, + c.at, + c.radius, + waiting, + &potion.particle(), + ); + if waiting { + return true; + } + // setRadiusPerTick(-radius / duration). + c.radius += -3.0 / 600.0; + if c.radius < 0.5 { + return false; + } + if c.age % 5 != 0 { + return true; + } + potion.victims.retain(|(_, until)| c.age < *until); + let r = f64::from(c.radius); + let area = Aabb::new( + Vec3::new(c.at[0] - r, c.at[1], c.at[2] - r), + Vec3::new(c.at[0] + r, c.at[1] + 0.5, c.at[2] + r), + ); + let mut inside = Vec::new(); + for p in players.iter().filter(|p| p.bounds.intersects(area)) { + inside.push((Victim::Player(p.who), p.position.x, p.position.z)); + } + let effects = potion.effects; + let tags = &self.res.stations().enchantments.entity_tags; + // Only mobs that at least one of the cloud's effects can affect are + // taken (`allEffects.stream().anyMatch(entity::canBeAffected)`), so + // the others neither become victims nor use up its radius. + for m in self.mobs.iter().filter(|m| { + m.alive() + && m.bounds().intersects(area) + && effects + .iter() + .any(|(id, ..)| mob_can_be_affected(tags, &m.kind.id, id)) + }) { + inside.push((Victim::Mob(m.id), m.position.x, m.position.z)); + } + for (victim, x, z) in inside { + let (dx, dz) = (x - c.at[0], z - c.at[2]); + if potion.victims.iter().any(|(v, _)| *v == victim) + || dx * dx + dz * dz > f64::from(c.radius * c.radius) + { + continue; + } + potion.victims.push((victim, c.age + REAPPLICATION_DELAY)); + self.cloud_affect(victim, effects, c.at, &potion.source); + // setRadiusOnUse(-0.5). + c.radius -= 0.5; + if c.radius < 0.5 { + return false; + } + } + true + } + /// What a cloud puts on one entity: instant effects at half strength + /// (`applyInstantaneousEffect` with 0.5), the others for their duration + /// at the lingering item's 0.25 scale (`PotionContents.forEachEffect`). + fn cloud_affect( + &mut self, + victim: Victim, + effects: &'static [(&'static str, i32, i32)], + at: [f64; 3], + source: &Text, + ) { + let scaled = |duration: i32| ((f64::from(duration) * 0.25) as i32).max(1); + match victim { + Victim::Player(who) => self.as_fight_player(who, |g| { + for (id, duration, amp) in effects { + let Some(e) = brewing::effect(id) else { + continue; + }; + if e.instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, 0.5) { + g.apply_indirect_effect_action(a, source); + } + } else { + g.add_player_effect(EffectInstance::new(e.id, scaled(*duration), *amp)); + } + } + }), + Victim::Mob(mob) => { + let Some(i) = self.mobs.iter().position(|m| m.id == mob) else { + return; + }; + // Undead invert healing and harming. + let tags = &self.res.stations().enchantments.entity_tags; + let inverted = tags + .get("minecraft:inverted_healing_and_harm") + .is_some_and(|t| t.contains(&self.mobs[i].kind.id)); + for (id, duration, amp) in effects { + let m = &mut self.mobs[i]; + match *id { + "instant_damage" | "instant_health" => { + let amount = + |base: i32| (0.5 * f64::from(base << amp) + 0.5) as i32 as f32; + if (*id == "instant_damage") != inverted { + m.hurt(amount(6), Some(at), &mut self.world.random); + } else { + m.health = (m.health + amount(4)).min(m.kind.max_health); + } + } + _ => { + // `LivingEntity.addEffect` refuses what the mob + // cannot be affected by. + if mob_can_be_affected(tags, &m.kind.id, id) + && let Some(name) = mob_effect_id(id) + { + m.add_effect(name, scaled(*duration), *amp); + } + } + } + } + } } } /// `ThrowableProjectile.tick`'s `applyGravity` and `applyInertia`, which @@ -671,12 +891,23 @@ impl Game<'_> { self.submit_item_world(&state, pose, vertex_light(light), out); } } + /// `HealOrHarmMobEffect.applyInstantaneousEffect` with a source (a + /// potion or a cloud): indirectMagic, not plain magic. + fn apply_indirect_effect_action(&mut self, a: EffectAction, source: &Text) { + let a = match a { + EffectAction::Hurt("minecraft:magic", amount) => { + self.note_direct_entity("minecraft:indirect_magic", source.clone()); + EffectAction::Hurt("minecraft:indirect_magic", amount) + } + a => a, + }; + self.apply_effect_action(a); + } /// A splash potion's effects on the player in place, by their distance. fn splash_on_player( &mut self, effects: &'static [(&'static str, i32, i32)], at: Vec3, - scale: f64, source: &Text, ) { if let Some(p) = self.player.as_ref() { @@ -693,22 +924,10 @@ impl Game<'_> { let instant = brewing::effect(id).is_some_and(|e| e.instant); if instant { if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { - // HealOrHarmMobEffect.applyInstantaneousEffect with - // a source: indirectMagic, not plain magic. - let a = match a { - EffectAction::Hurt("minecraft:magic", amount) => { - self.note_direct_entity( - "minecraft:indirect_magic", - source.clone(), - ); - EffectAction::Hurt("minecraft:indirect_magic", amount) - } - a => a, - }; - self.apply_effect_action(a); + self.apply_indirect_effect_action(a, source); } } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(e) = brewing::effect(id) { @@ -719,8 +938,9 @@ impl Game<'_> { } } } - /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). - fn splash(&mut self, stack: &ItemStack, at: Vec3, owner: Option) { + /// `ThrownSplashPotion.onHitAsPotion`, or `ThrownLingeringPotion.onHitAsPotion` + /// for a lingering potion; `mob` is where it hit a mob. + fn splash(&mut self, stack: &ItemStack, at: Vec3, mob: Option, owner: Option) { let block = [at.x, at.y, at.z].map(|v| v.floor() as i32); if &*stack.item == "minecraft:experience_bottle" { // ThrownExperienceBottle.onHit: the water-coloured splash (level @@ -744,23 +964,41 @@ impl Game<'_> { let color = brewing::potion_color(stack.potion()); self.level_event_at(if instant { 2007 } else { 2002 }, block, color as i32); self.level_event_at(if instant { 1054 } else { 1053 }, block, 0); - let scale = if lingering { 0.25 } else { 1.0 }; let Some(def) = potion else { return; }; + if lingering { + // The cloud sits at the mob it hit (its feet), else the impact; + // radius 3, wait 10, 600 ticks, shrinking to nothing, and a + // potion with no effects leaves none. + if !def.effects.is_empty() { + let at = mob.unwrap_or(at); + self.breath_clouds.push(Breath { + id: 0, + at: [at.x, at.y, at.z], + radius: 3.0, + age: 0, + duration: 600, + from_dragon: false, + potion: Some(PotionCloud { + effects: def.effects, + color, + victims: Vec::new(), + source: owner.unwrap_or_else(|| { + Text::translate("entity.minecraft.area_effect_cloud", &[]) + }), + }), + }); + } + return; + } // Every player in range (`ThrownSplashPotion.applySplash` over // `LivingEntity`s, the players among them). - // Instant damage is indirectMagic(potion or cloud, owner), which the - // death message names by the owner, else by the potion or cloud. - let source = owner.unwrap_or_else(|| { - let entity = if lingering { - "entity.minecraft.area_effect_cloud" - } else { - "entity.minecraft.splash_potion" - }; - Text::translate(entity, &[]) - }); - self.for_each_player(|g| g.splash_on_player(def.effects, at, scale, &source)); + // Instant damage is indirectMagic(potion, owner), which the death + // message names by the owner, else by the potion. + let source = + owner.unwrap_or_else(|| Text::translate("entity.minecraft.splash_potion", &[])); + self.for_each_player(|g| g.splash_on_player(def.effects, at, &source)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); @@ -783,7 +1021,7 @@ impl Game<'_> { _ => { // `Potion.applySplash`: timed effects last in // proportion to how close the mob was. - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + let d = (intensity * f64::from(*duration) + 0.5) as i32; if d > 20 && let Some(name) = mob_effect_id(id) { diff --git a/crates/horizon-client/src/game/powder_snow.rs b/crates/horizon-client/src/game/powder_snow.rs index 6a904706f..7d935d07b 100644 --- a/crates/horizon-client/src/game/powder_snow.rs +++ b/crates/horizon-client/src/game/powder_snow.rs @@ -53,7 +53,11 @@ impl Game<'_> { if let Some(player) = self.player.as_mut() { player.fire_ticks = 0; } - // Entity.playEntityOnFireExtinguishedSound + self.extinguish_sound(at); + Ok(()) + } + /// Entity.playEntityOnFireExtinguishedSound + fn extinguish_sound(&mut self, at: [f64; 3]) { let r = self.particles.random(); let pitch = 1.6 + (r.next_float() - r.next_float()) * 0.4; self.audio.play( @@ -62,7 +66,29 @@ impl Game<'_> { 0.7, pitch, ); - Ok(()) + } + /// `Entity.applyEffectsFromBlocks`: a burning player in the rain + /// (`isInRain`) has the fire put out (`clearFire`), with the extinguish + /// sound that everyone near hears. + pub(super) fn rain_extinguish_player(&mut self) { + let Some(player) = self.player.as_ref() else { + return; + }; + let (at, top) = (player.position, player.bounds().max_position().y); + if player.fire_ticks <= 0 || !self.in_rain(at, top) { + return; + } + if let Some(player) = self.player.as_mut() { + player.fire_ticks = 0; + } + self.extinguish_sound([at.x, at.y, at.z]); + } + /// The in-window player's rain extinguish (a server's player has its + /// fire put out by the server). + pub(super) fn rain_extinguish_in_frame(&mut self) { + if self.remote.is_none() { + self.rain_extinguish_player(); + } } /// Whether the block at `pos` is powder snow. pub(super) fn is_powder_snow(&self, pos: [i32; 3]) -> bool { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index da7c79394..c51fbdc0b 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -1036,6 +1036,7 @@ impl Game<'_> { /// read it). fn sync_villager_raids(&mut self, infos: &HashMap>) { let raids = &self.raiding.raids; + let mut ongoing = Vec::new(); for m in &mut self.mobs { if m.species() != Species::Villager { continue; @@ -1061,7 +1062,27 @@ impl Game<'_> { let ext = mobs_villager::ext_mut(m); ext.raid = status; ext.raid_wave = wave; + if !m.no_ai && matches!(status, mobs_villager::PRE_RAID | mobs_villager::RAID) { + ongoing.push(m.id); + } } + // Villager.customServerAiStep: a 1 in 100 chance each tick, in an + // ongoing raid, of entity event 42 (`handleEntityEvent` splashes). + for id in ongoing { + if self.particles.random().next_int_bound(100) == Ok(0) { + self.mob_raid_splash(id); + } + } + } + /// Entity event 42 for villager `id`: the guests get the byte, and this + /// game draws `AbstractVillager.addParticlesAroundSelf(SPLASH)` itself. + fn mob_raid_splash(&mut self, id: u32) { + let Some(m) = self.mobs.iter().find(|m| m.id == id) else { + return; + }; + let at = [m.position.x, m.position.y, m.position.z]; + self.lan_entity_event(id as i32, 42, at); + self.particles_around_mob(id, "splash", horizon_client::particles::Burst::VILLAGER); } /// The raid bar a living player at `at` is in (`Raid.getPlayers`): red, diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 024d45734..9991ce366 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -609,6 +609,7 @@ impl Game<'_> { if inside(cursor, bx, by, 20.0, 18.0) { let open = !self.book_open(book_type); self.level.recipe_book.open[book_type.index()] = open; + self.send_book_settings(book_type); if !open { self.recipe_ui.overlay = None; } @@ -694,6 +695,7 @@ impl Game<'_> { if inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0) { let filtering = !self.book_filtering(book_type); self.level.recipe_book.filtering[book_type.index()] = filtering; + self.send_book_settings(book_type); self.recipe_ui.page = 0; self.audio .play("minecraft:ui.button.click", None, 0.25, 1.0); @@ -714,6 +716,22 @@ impl Game<'_> { } false } + /// `RecipeBookComponent.sendUpdateSettings`: the server owns the saved book. + fn send_book_settings(&self, book_type: BookType) { + self.send( + horizon_protocol::packets::play::Serverbound::RecipeBookChangeSettings( + horizon_protocol::packets::recipes::RecipeBookChangeSettings { + book_type: book_type.index() as i32, + open: self.book_open(book_type), + filtering: self.book_filtering(book_type), + }, + ), + ); + } + pub(super) fn recipe_book_flags(&self) -> Option<(bool, bool)> { + let book = self.active_book()?; + Some((self.book_open(book), self.book_filtering(book))) + } /// How many displays the client's book holds. pub(super) fn recipe_book_known(&self) -> usize { self.recipe_ui.client.displays().len() diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 77e143f9a..e41aca43b 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -117,13 +117,17 @@ pub(super) struct Remote { joined: bool, status: String, pub(super) entity_id: i32, + /// The item the player's use began with (`LivingEntity.useItem`). + pub(super) use_item: Option>, dimension: DimensionType, /// What chunk packets decode with (the dimension's height and sky, the /// biome registry); replaced whenever one of them changes. pub(super) chunk_format: Arc, /// Decodes chunk packets as they arrive, off the frame. decoder: ChunkDecoder, - view_distance: i32, + /// Options.serverRenderDistance: the server's view distance from the + /// login or the last chunk-cache-radius packet. + pub(super) view_distance: i32, sequence: i32, position_sender: horizon_client::player_sync::PositionSender, last_input: u8, @@ -189,6 +193,10 @@ pub(super) struct Remote { destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, + /// Keys whose presses send a packet (swap hands, drop, a mount's + /// inventory): like the click queue, they wait for the tick's + /// `handleKeybinds` phase rather than going out between window events. + pub(super) pending_keys: Vec, stop_mining: bool, placing: Option<([i32; 3], u64)>, death_message: Option, @@ -212,6 +220,9 @@ pub(super) struct Remote { /// `ClientboundTransferPacket`'s target: when the connection ends the /// game connects here, the stored cookies carried over (`TransferState`). transfer: Option, + /// `ClientCommonPacketListenerImpl.serverLinks`: the links "Server + /// Links..." in the pause menu lists (only `http`/`https` URIs kept). + pub(super) server_links: Vec, } /// The time a frame spends on chunk packets before it leaves the rest of @@ -394,6 +405,9 @@ impl Game<'_> { self.carried = None; self.using = None; self.clicks.miss_time = 0; + // A new LocalPlayer has no effects: the server sends what it has + // (ClientboundUpdateMobEffectPacket on placement). + self.potions = Default::default(); self.set_mode_id(0); self.experience = Experience { level: 0, @@ -428,6 +442,7 @@ impl Game<'_> { joined: false, status: "Connecting to the server...".into(), entity_id: 0, + use_item: None, dimension: DimensionType::vanilla("minecraft:overworld"), chunk_format: Arc::new(ChunkFormat::new( &DimensionType::vanilla("minecraft:overworld"), @@ -473,6 +488,7 @@ impl Game<'_> { destroying: None, destroy_delay: 0, input: Default::default(), + pending_keys: Vec::new(), stop_mining: false, placing: None, death_message: None, @@ -486,6 +502,7 @@ impl Game<'_> { chunk_center: (0, 0), backlog: VecDeque::new(), backlog_since: None, + server_links: Vec::new(), transfer: None, }); // The level's TickRateManager follows the server's ticking packets. @@ -862,6 +879,11 @@ impl Game<'_> { } Event::PackPush(p) => self.handle_pack_push(p), Event::PackPop(id) => self.handle_pack_pop(id), + Event::ServerLinks(links) => { + if let Some(r) = self.remote.as_mut() { + r.server_links = super::server_links::trusted(links); + } + } Event::ShowDialog(dialog) => self.show_dialog(&dialog), Event::ClearDialog => self.clear_dialog(), Event::DecodeError(e) => { @@ -1621,7 +1643,11 @@ impl Game<'_> { } C::Login(p) => { self.level.hardcore = p.hardcore; + // handleLogin makes a new MultiPlayerGameMode (carried index 0) and a + // new LocalPlayer (slot 0). + self.selected = 0; if let Some(r) = self.remote.as_mut() { + r.carried = Some(0); r.online_mode = p.online_mode; r.entity_id = p.player_id; r.view_distance = p.chunk_radius; @@ -1639,8 +1665,10 @@ impl Game<'_> { self.send(S::ClientInformation(info)); } C::Respawn(p) => { - // A new player, without effects: the server sends them again. + // A new player, without effects (the server sends them + // again) and with no item in use. self.potions.effects.clear(); + self.using = None; self.enter_remote_dimension(&p.spawn, true); self.screen = Screen::Playing; if let Some(r) = self.remote.as_mut() { @@ -1926,6 +1954,22 @@ impl Game<'_> { } } } + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + for (index, _, value) in &p.values { + match (index, value) { + // Entity.DATA_TICKS_FROZEN: isFullyFrozen shakes it. + (7, Value::Int(ticks)) => m.ticks_frozen = *ticks, + // Strider.DATA_SUFFOCATING (after AgeableMob's two + // and DATA_BOOST_TIME): a cold strider shakes. + (19, Value::Bool(cold)) + if m.species() == horizon_client::mobs::Species::Strider => + { + m.extra.flag = *cold; + } + _ => {} + } + } + } // LivingEntity.DATA_LIVING_ENTITY_FLAGS: for another player // too, remote_mob_data's apply reads index 8 above. let mannequin = self @@ -2024,13 +2068,22 @@ impl Game<'_> { // player holds and wears (EquipmentSlot ordinals). C::SetEquipment(p) => { self.remote_object_equipment(p.id, &p.slots); - let items: Vec<(u8, Option>)> = p + let items: Vec<(u8, Option>, Option)> = p .slots .iter() - .map(|(slot, stack)| (*slot, stack.as_ref().map(|s| self.item_name(s.item)))) + .map(|(slot, stack)| { + ( + *slot, + stack.as_ref().map(|s| self.item_name(s.item)), + self.to_stack(stack), + ) + }) .collect(); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - for (slot, item) in items { + // The body slot (6: horse armour, llama carpet, harness) + // is kept in `head`, as Horizon's own mobs do. + let body = horizon_client::mobs::drops::head_is_body(m.species()); + for (slot, item, stack) in items { let e = &mut m.extra; match slot { 0 => e.main_hand = item, @@ -2038,7 +2091,9 @@ impl Game<'_> { 2 => e.feet = item, 3 => e.legs = item, 4 => e.chest = item, - 5 => e.head = item, + 5 if !body => e.head = item, + 6 if body => e.head = item, + 7 => m.set_saddle(stack), _ => {} } } @@ -2157,6 +2212,9 @@ impl Game<'_> { if p.event == super::totem::TOTEM_EVENT { self.remote_totem(p.id); } + if p.event == super::combat::DROWN_EVENT { + self.remote_drown(p.id); + } // Entity event 53: the honey slide particles of a player // sliding down a honey block (HoneyBlock.showSlideParticles). if p.event == 53 { @@ -2174,6 +2232,11 @@ impl Game<'_> { self.honey_slide_particles(at); } } + if p.event == super::consume::USE_ITEM_COMPLETE_EVENT + && self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) + { + self.remote_complete_using(); + } } C::Animate(p) => self.remote_animate(p.id, p.action), // ClientPacketListener.handleSwingAnimation: the entity swings @@ -2336,10 +2399,11 @@ impl Game<'_> { } self.apply_remote_abilities(); } + // ClientPacketListener.handleSetHeldSlot: a hotbar slot only, and the + // carried index stays, so the next tick answers with SetCarriedItem. C::SetHeldSlot(p) => { - self.selected = p.slot.clamp(0, 8) as usize; - if let Some(r) = self.remote.as_mut() { - r.carried = Some(self.selected); + if (0..9).contains(&p.slot) { + self.selected = p.slot as usize; } } C::ContainerSetContent(p) => { @@ -3171,12 +3235,6 @@ impl Game<'_> { fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; self.track_experience_display(); - // Player.tick's ItemCooldowns.tick: this path replaces `tick_world`'s - // for a server's client (multiplayer and the default single player), - // so the entries advance here or the slot stays shaded until the - // server says the entry ended. `onCooldownEnded` is the plain - // ItemCooldowns' no-op on a client. - self.cooldowns.tick(); // Leaving a slot clears its bundle's selection here and on the server. self.tick_bundle_hover(); // Options.broadcastOptions: a changed render distance or Chat option @@ -3212,6 +3270,14 @@ impl Game<'_> { // Window callbacks only queue clicks, so an interaction cannot leak // between CLIENT_TICK_END and a later pong. self.remote_handle_input(); + // Player.tick's ItemCooldowns.tick, in ClientLevel.tickEntities after + // handleKeybinds: this path replaces `tick_world`'s for a server's + // client (multiplayer and the default single player), so the entries + // advance here or the slot stays shaded until the server says the + // entry ended. `onCooldownEnded` is the plain ItemCooldowns' no-op on + // a client. Ticking it after the keybinds keeps a held use from + // trying again a tick before the server's entry ends. + self.cooldowns.tick(); // ClientLevel.tick: the border's size change. self.border.tick(); self.player_border(); @@ -3333,6 +3399,11 @@ impl Game<'_> { resources: self.motion, } .controlled_simulation_tick(keys)?; + } else { + // LivingEntity.baseTick counts hurtTime down for a dead or riding + // player too (controlled_simulation_tick does it otherwise): left + // at 10, the hurt tilt restarted every frame and shook the camera. + player.health.advance_clock(); } // LocalPlayer.onUpdateAbilities: flight turned on or off (a double // jump, a spectator, landing) is sent to the server. @@ -3343,13 +3414,12 @@ impl Game<'_> { let events = std::mem::take(&mut player.events); self.previous_eye = self.eye; self.eye += (player.dimensions.eye_height - self.eye) * 0.5; - let crouching = player.pose == horizon_client::pose::Pose::Crouching; let feet = [player.position.x, player.position.y, player.position.z]; for event in events { match event { horizon_client::motion::MotionEvent::Emission { state, in_water, .. - } if !crouching => { + } => { let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. let (volume, pitch) = if in_water { @@ -3363,6 +3433,14 @@ impl Game<'_> { self.audio .play("minecraft:entity.player.swim", Some(feet), volume, pitch); } + horizon_client::motion::MotionEvent::Chime { volume, pitch } => { + self.audio.play( + "minecraft:block.amethyst_block.chime", + Some(feet), + volume, + pitch, + ); + } // NetherPortalBlock.entityInside on the client's own level: // the portal overlay and its trigger sound (the server moves // the player). @@ -3537,11 +3615,15 @@ impl Game<'_> { let head_lerps = &mut r.head_lerps; let players = &r.level_players; let mut using = Vec::new(); + let mut wither_heads = Vec::new(); for m in &mut self.mobs { let player = players.contains_key(&(m.id as i32)); if !running && !player { continue; } + if m.species() == horizon_client::mobs::Species::Wither { + wither_heads.extend((0..3).map(|i| horizon_client::mobs::wither::head_pos(m, i))); + } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; @@ -3614,7 +3696,7 @@ impl Game<'_> { m.extra.main_hand.clone() }; if let Some(item) = item { - let eye = if m.extra.crouching { 1.27 } else { 1.62 }; + let eye = m.eye_height(); let at = [m.position.x, m.position.y, m.position.z]; using.push(( item, @@ -3672,10 +3754,24 @@ impl Game<'_> { d.tick(world, facts, collision, false, &self.res.motion().fluids); } head_lerps.retain(|_, (_, steps)| *steps > 0); + // WitherBoss.aiStep runs on a client too: smoke around each head. + let smoke = horizon_client::particles::ParticleOptions::simple( + horizon_client::particles::ParticleType::Smoke, + ); + for h in wither_heads { + let r = self.particles.random(); + let at = [ + h[0] + r.next_gaussian() * 0.3, + h[1] + r.next_gaussian() * 0.3, + h[2] + r.next_gaussian() * 0.3, + ]; + self.particles.add(&smoke, at, [0.0; 3]); + } for (item, ticks, at, eye, pitch, yaw) in using { self.remote_player_eating(&item, ticks, at, eye, pitch, yaw); } if running { + self.guardian_bubbles(); // The dragon: LivingEntity's interpolation, inside its aiStep. let dragon_lerp = self .dragon @@ -3930,6 +4026,9 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.destroying = Some((hit.pos, face, 0.0)); } + // startDestroyBlock plays the first hit and crack itself; the + // server's level events 2019 and 2020 do the rest. + self.breaking_block_effects(hit.pos, hit.face, true); self.mining = Some(Mining { pos: hit.pos, progress: 0.0, @@ -3942,20 +4041,6 @@ impl Game<'_> { }; let done = done + progress; let ticks = self.mining.as_ref().map_or(0, |m| m.ticks) + 1; - if ticks % 4 == 1 { - let c = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - &facts.sounds.hit, - Some(c), - (facts.sounds.volume + 1.0) / 8.0, - facts.sounds.pitch * 0.5, - ); - } - self.crack_particle(pos, hit.face, state); if done >= 1.0 { let seq = self.next_sequence(); self.predict_break(pos, state, seq); @@ -4123,6 +4208,7 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + self.open_command_block_if_editable((hit.pos[0], hit.pos[1], hit.pos[2])); } else if let Some(stack) = held.as_ref() && self.predict_item_on_block(stack, &hit) { @@ -4354,13 +4440,27 @@ impl Game<'_> { let Some(info) = self.res.items().get(&held.item).cloned() else { return false; }; - // MultiPlayerGameMode.useItem runs the use here too (inside - // startPrediction): the `use_cooldown` component starts its entry, and - // the server's ClientboundCooldownPacket confirms it. - self.apply_use_cooldown(&held); - // Food starts being eaten (Consumable.startConsuming), a book and - // quill opens. - self.with_hand(hand, |g| g.start_eating(&info)); + // MultiPlayerGameMode.useItem's prediction: an item cooling down + // passes (its packet still goes). + let group = horizon_client::cooldowns::group(&held, info.use_cooldown.as_ref()); + if self.cooldowns.is_on_cooldown(&group) { + return false; + } + // Food starts being eaten (Consumable.startConsuming). A food that + // can't be eaten (full and not always-edible) fails the use + // (InteractionResult.FAIL): startUseItem tries the other hand, and + // no cooldown or use animation starts. + let eating = self.with_hand(hand, |g| g.start_eating(&info)); + if info.food.is_some() && !eating { + return false; + } + // It runs the use here too: ItemStack.use starts the `use_cooldown` + // of an item with no use time, and the server's + // ClientboundCooldownPacket confirms it; one held in use starts it at + // finishUsingItem (remote_complete_using). + if !info.consumable.as_ref().is_some_and(|c| c.ticks() > 0) { + self.apply_use_cooldown(&held); + } if self.with_hand(hand, |g| g.remote_use_book(&held)) { return true; } @@ -4432,14 +4532,25 @@ impl Game<'_> { self.remote_use_item(Hand::Off); } /// `LivingEntity.updatingUsingItem` on a server client: an item held in - /// use (`held_until_released`), and a - /// consumable's eating animation and its crumbs. The server eats it and - /// sends the stack, the hunger and the sounds. + /// use (`held_until_released`), and a consumable's eating animation and + /// its crumbs until the server's USE_ITEM_COMPLETE. The server sends the + /// stack, its hunger and the sounds. fn remote_tick_using(&mut self) { let Some((slot, ticks)) = self.using else { return; }; let stack = self.stack_in(slot).cloned(); + // The use stops when the hand no longer holds the item it began with + // (ItemStack.isSameItem). + let item = stack.as_ref().map(|s| Arc::clone(&s.item)); + if let Some(r) = self.remote.as_mut() { + if ticks == 0 { + r.use_item = item; + } else if r.use_item != item { + self.using = None; + return; + } + } // Another hotbar slot picked: LivingEntity.updatingUsingItem sees a // different stack in the hand. The off hand keeps its item. let in_hand = slot == self.selected || slot == super::shield::OFFHAND_SLOT; @@ -4464,20 +4575,51 @@ impl Game<'_> { self.using = None; return; } - // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. - let duration = consumable.ticks().max(0) as u32; - let remaining = duration - ticks.min(duration); - if consumable.particles && consumable.should_emit(remaining as i32) { + // Consumable.startConsuming eats one with no use time at once, without + // a use (nor a USE_ITEM_COMPLETE). + if consumable.ticks() <= 0 { + self.using = None; + return; + } + // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. The + // countdown goes on past zero (LivingEntity.updateUsingItem completes + // only on the server) until the server's USE_ITEM_COMPLETE. + let remaining = consumable.ticks() - ticks as i32; + if consumable.particles && consumable.should_emit(remaining) { self.eat_particles(&stack, 5); } - if ticks + 1 >= duration { - self.using = None; - if consumable.particles { - self.eat_particles(&stack, 16); - } - } else { - self.using = Some((slot, ticks + 1)); + self.using = Some((slot, ticks + 1)); + } + /// `Player.handleEntityEvent(9)`: `completeUsingItem` on the client. A consumable's last crumbs, and FoodProperties.onConsume, + /// which runs on the client too (Consumable.onConsume calls its + /// ConsumableListeners on both sides): the client's FoodData eats at once, + /// so a held right click finds `Player.canEat` false instead of starting + /// another bite before the server's ClientboundSetHealth arrives. + fn remote_complete_using(&mut self) { + let Some((slot, _)) = self.using.take() else { + return; + }; + let Some(stack) = self.stack_in(slot).cloned() else { + return; + }; + let Some(info) = self.res.items().get(&stack.item).cloned() else { + return; + }; + if info.consumable.as_ref().is_some_and(|c| c.particles) { + self.eat_particles(&stack, 16); } + if let Some((nutrition, saturation)) = info.food + && let Some(r) = self.remote.as_mut() + { + // FoodData.eat(nutrition, saturation), as finish_consuming does; + // the next ClientboundSetHealth replaces it. + let (_, food, sat) = &mut r.health; + *food = (*food + nutrition as i32).clamp(0, 20); + *sat = (*sat + saturation).clamp(0.0, *food as f32); + self.apply_remote_health(); + } + // ItemStack.finishUsingItem's applyAfterUseComponentSideEffects. + self.apply_use_cooldown(&stack); } /// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick. pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { @@ -4542,6 +4684,31 @@ impl Game<'_> { } let (attack, use_item) = (self.left, self.right); input.tick(&mut RemoteInputWorld(self), attack, use_item); + // handleKeybinds' keybind polls: the queued presses act now, in tick + // order, so no packet goes out between CLIENT_TICK_END and a pong. + let pending = self + .remote + .as_mut() + .map(|r| std::mem::take(&mut r.pending_keys)) + .unwrap_or_default(); + for key in pending { + match key { + KeyCode::KeyF if !self.spectator() => self.remote_swap_hands(), + KeyCode::KeyQ if !self.spectator() => { + let all = self.keys.contains(&KeyCode::ControlLeft); + self.remote_drop(all); + } + KeyCode::KeyE if self.riding_mount_with_menu() => { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 5, + data: 0, + })); + } + _ => {} + } + } if self.clicks.miss_time > 0 { self.clicks.miss_time -= 1; } @@ -4653,22 +4820,8 @@ impl Game<'_> { if self.spectator() { return Ok(true); } - let all = self.keys.contains(&KeyCode::ControlLeft); - // MultiPlayerGameMode.dropItem: predict removal before sending - // the action, then swing only if a nonempty stack was removed. - let dropped = horizon_client::items::take_held_drop( - &mut self.inventory[self.selected], - all, - false, - ); - self.send(S::PlayerAction(play::PlayerAction { - action: if all { 4 } else { 5 }, - pos: [0; 3], - direction: 0, - sequence: 0, - })); - if dropped.is_some() { - self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + if let Some(r) = self.remote.as_mut() { + r.pending_keys.push(key); } Ok(true) } @@ -4676,12 +4829,9 @@ impl Game<'_> { // horse or llama, the server opens its inventory // (ServerboundPlayerCommandPacket OPEN_INVENTORY). KeyCode::KeyE if self.riding_mount_with_menu() => { - let id = self.remote.as_ref().map_or(0, |r| r.entity_id); - self.send(S::PlayerCommand(play::PlayerCommand { - id, - action: 5, - data: 0, - })); + if let Some(r) = self.remote.as_mut() { + r.pending_keys.push(key); + } Ok(true) } KeyCode::KeyE => { @@ -4728,6 +4878,21 @@ impl Game<'_> { })); } } + /// MultiPlayerGameMode.dropItem (key.drop): predict the removal, then send + /// the action; swing only if a nonempty stack was removed. + fn remote_drop(&mut self, all: bool) { + let dropped = + horizon_client::items::take_held_drop(&mut self.inventory[self.selected], all, false); + self.send(S::PlayerAction(play::PlayerAction { + action: if all { 4 } else { 5 }, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + if dropped.is_some() { + self.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + } + } /// Minecraft.handleKeybinds, key.swapOffhand: the server swaps the hands /// (ServerboundPlayerActionPacket SWAP_ITEM_WITH_OFFHAND at BlockPos.ZERO, facing down) and /// sends both slots back; nothing is predicted. diff --git a/crates/horizon-client/src/game/remote_mob_data.rs b/crates/horizon-client/src/game/remote_mob_data.rs index 65bbbfbbe..d6e4372f6 100644 --- a/crates/horizon-client/src/game/remote_mob_data.rs +++ b/crates/horizon-client/src/game/remote_mob_data.rs @@ -17,6 +17,12 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin, local_enti let baby = super::lan::baby_index(&m.kind.id); for (index, _, value) in values { match (*index, value) { + // Entity.DATA_POSE: a player's or mannequin's box follows it. + (6, Value::Id(pose)) + if matches!(&*m.kind.id, "minecraft:player" | "minecraft:mannequin") => + { + m.extra.avatar_pose = horizon_client::pose::Pose::from_id(*pose); + } // Entity.DATA_SHARED_FLAGS_ID's FLAG_ONFIRE: Entity.isOnFire on a // client, which draws the flames. A client doesn't count the // fire down: the flag goes off when the server's fire is out. diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index 55c233ca0..06270e4f0 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -23,6 +23,58 @@ fn default_cloud_particle() -> ParticleOptions { ParticleOptions::colored(ParticleType::EntityEffect, [1.0; 4]) } +/// `AreaEffectCloud.clientTick`: while waiting, now and then two particles +/// near the middle; then about one per square block of the disc, drifting +/// (an entity effect stays still). +pub(super) fn cloud_client_tick( + particles: &mut horizon_client::particles::ParticleEngine, + at: [f64; 3], + radius: f32, + waiting: bool, + particle: &ParticleOptions, +) { + if waiting && particles.random().next_boolean() { + return; + } + let (count, spread) = if waiting { + (2, 0.2) + } else { + ( + (std::f32::consts::PI * radius * radius).ceil() as i32, + radius, + ) + }; + for _ in 0..count { + let r = particles.random(); + let angle = r.next_float() * std::f32::consts::TAU; + let distance = r.next_float().sqrt() * spread; + let at = [ + at[0] + f64::from(angle.cos() * distance), + at[1], + at[2] + f64::from(angle.sin() * distance), + ]; + let (options, velocity) = if particle.ty == ParticleType::EntityEffect { + let default = waiting && r.next_boolean(); + let options = if default { + default_cloud_particle() + } else { + particle.clone() + }; + (options, [0.0; 3]) + } else if waiting { + (particle.clone(), [0.0; 3]) + } else { + let v = [ + (0.5 - r.next_double()) * 0.15, + f64::from(0.01f32), + (0.5 - r.next_double()) * 0.15, + ]; + (particle.clone(), v) + }; + particles.add(&options, at, velocity); + } +} + /// The projectile a type id names, as Horizon models it. fn projectile_kind(kind: &str) -> Option { Some(match kind { @@ -77,8 +129,36 @@ fn remote_arrow_tick(p: &mut Projectile, w: &impl ProjectileWorld) { } p.velocity.y -= 0.05; } +/// A server's client ticks a projectile itself: it flies on between the +/// tracker's updates (10 to 20 ticks apart) with its own gravity and drag, +/// and a block stops it there; only the server decides what it hits. +pub(super) fn remote_projectile_tick(p: &mut Projectile, w: &impl ProjectileWorld) { + if !matches!(p.tick(w).1, Hit::None) { + p.velocity = Vec3::ZERO; + } +} + +/// `AbstractHurtingProjectile.getTrailParticle`: smoke for every one of them +/// but the wind charges (no trail) and the dragon's fireball (its own). +pub(super) fn has_smoke_trail(kind: &ProjectileKind) -> bool { + matches!( + kind, + ProjectileKind::SmallFireball + | ProjectileKind::LargeFireball { .. } + | ProjectileKind::WitherSkull { .. } + ) +} impl Game<'_> { + /// `AbstractHurtingProjectile.createParticleTrail`: one smoke puff half a + /// block above each position. + pub(super) fn smoke_trails(&mut self, at: impl IntoIterator) { + let smoke = ParticleOptions::simple(ParticleType::Smoke); + for p in at { + self.particles.add(&smoke, [p.x, p.y + 0.5, p.z], [0.0; 3]); + } + } + /// `handleAddEntity` for these types; false when `kind` isn't one. pub(super) fn spawn_remote_projectile( &mut self, @@ -171,7 +251,7 @@ impl Game<'_> { p.velocity = velocity; p.yaw = yaw; p.pitch = pitch; - self.creatures.projectiles.push(p); + self.add_projectile(p); } } true @@ -347,15 +427,19 @@ impl Game<'_> { p.age += 1; p.position = p.position.add_vector(p.velocity); } - _ => { - if !matches!(p.tick(&world).1, Hit::None) { - p.velocity = Vec3::ZERO; - } - } + _ => remote_projectile_tick(p, &world), } } } self.creatures.projectiles = projectiles; + let trails: Vec = self + .creatures + .projectiles + .iter() + .filter(|p| has_smoke_trail(&p.kind)) + .map(|p| p.position) + .collect(); + self.smoke_trails(trails); for t in &mut self.tridents { let id = t.id; t.remote_step(|at| step(id, at)); @@ -414,52 +498,10 @@ impl Game<'_> { } } - /// `AreaEffectCloud.clientTick`: while waiting, now and then two - /// particles near the middle; then about one per square block of the - /// disc, drifting (an entity effect stays still). + /// `AreaEffectCloud.clientTick` for each cloud a server tracks. fn tick_remote_clouds(&mut self) { for c in &self.potions.clouds { - let r = self.particles.random(); - if c.waiting && r.next_boolean() { - continue; - } - let (count, spread) = if c.waiting { - (2, 0.2) - } else { - ( - (std::f32::consts::PI * c.radius * c.radius).ceil() as i32, - c.radius, - ) - }; - for _ in 0..count { - let r = self.particles.random(); - let angle = r.next_float() * std::f32::consts::TAU; - let distance = r.next_float().sqrt() * spread; - let at = [ - c.at[0] + f64::from(angle.cos() * distance), - c.at[1], - c.at[2] + f64::from(angle.sin() * distance), - ]; - let (options, velocity) = if c.particle.ty == ParticleType::EntityEffect { - let default = c.waiting && r.next_boolean(); - let options = if default { - default_cloud_particle() - } else { - c.particle.clone() - }; - (options, [0.0; 3]) - } else if c.waiting { - (c.particle.clone(), [0.0; 3]) - } else { - let v = [ - (0.5 - r.next_double()) * 0.15, - f64::from(0.01f32), - (0.5 - r.next_double()) * 0.15, - ]; - (c.particle.clone(), v) - }; - self.particles.add(&options, at, velocity); - } + cloud_client_tick(&mut self.particles, c.at, c.radius, c.waiting, &c.particle); } } @@ -533,3 +575,68 @@ impl Game<'_> { out } } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_client::mobs::Who; + use horizon_core::geometry::Aabb; + + /// A world with nothing in it: the client tick of a projectile only + /// needs the blocks around it. + struct Empty; + impl ProjectileWorld for Empty { + fn clip(&self, _: Vec3, _: Vec3) -> Option<(Vec3, [i32; 3], [i32; 3])> { + None + } + fn in_water(&self, _: Vec3) -> bool { + false + } + fn targets(&self) -> &[(Who, Aabb)] { + &[] + } + } + + /// A thrown item, as a server's client tracks it: the spawn position and + /// the motion the server gave it. + fn thrown(kind: ProjectileKind) -> Projectile { + let mut p = Projectile::new(kind, Vec3::new(0.0, 100.0, 0.0), None); + p.velocity = Vec3::new(1.5, 0.0, 0.0); + p + } + + #[test] + fn a_thrown_item_flies_on_between_the_server_updates() { + // A thrown egg, an ender pearl and a wind charge (#1762): the server + // sends their position every 10 ticks, and the client ticks them + // itself in between, as vanilla's no-op interpolation handler does. + for kind in [ + ProjectileKind::Egg, + ProjectileKind::EnderPearl, + ProjectileKind::WindCharge, + ] { + let mut p = thrown(kind); + remote_projectile_tick(&mut p, &Empty); + assert!(p.position.x > 1.0, "the projectile did not fly on: {p:?}"); + // A second tick moves it further: it keeps flying, not a hop. + let first = p.position.x; + remote_projectile_tick(&mut p, &Empty); + assert!(p.position.x > first, "the projectile stopped: {p:?}"); + } + } + + #[test] + fn a_thrown_item_falls_and_drags_like_a_throwable_projectile() { + // ThrowableProjectile.tick: gravity 0.03, then the air drag 0.99. + let mut p = thrown(ProjectileKind::Egg); + remote_projectile_tick(&mut p, &Empty); + assert!((p.velocity.x - 1.5 * 0.99).abs() < 1e-9, "{p:?}"); + assert!((p.velocity.y - (-0.03 * 0.99)).abs() < 1e-9, "{p:?}"); + // A wind charge keeps its speed: no gravity and no drag + // (AbstractWindCharge: acceleration 0, inertia 1). + let mut p = thrown(ProjectileKind::WindCharge); + remote_projectile_tick(&mut p, &Empty); + assert!((p.velocity.x - 1.5).abs() < 1e-9, "{p:?}"); + assert!((p.velocity.y - 0.0).abs() < 1e-9, "{p:?}"); + } +} diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 3f5862f49..c6c632f02 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -288,10 +288,11 @@ impl Game<'_> { e[2].floor() as i32, ]; animate_tick(self.res.animate(), &mut self.particles, &ctx, block); - if rain > 0.0 { - // ClientLevel.tickWeatherEffects: rain splashes (weather radius 10). + // The Horizon Weather option off means no rain visuals at all. + if rain > 0.0 && self.settings.horizon.weather { + // ClientLevel.tickWeatherEffects: rain splashes within the weather radius. let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); - let radius = 10; + let radius = self.settings.weather_radius; let diameter = 2 * radius + 1; let count = (0.225 * (diameter * diameter) as f32 * rain * rain) as i32; for _ in 0..count { diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 72b3ab000..53323fdbb 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -139,8 +139,10 @@ impl Game<'_> { | Target::Painting(id) | Target::Boat(id) | Target::Cart(id) + | Target::Crystal(id) + | Target::Dragon(id) | Target::Other(id) => Some(uuid_text(self.uuid_for(id))), - // Orbs and projectiles are addressed by index and have no UUID here. + // Orbs and projectiles have no UUID here. Target::Orb(_) | Target::Projectile(_) => None, } } @@ -188,7 +190,11 @@ impl Game<'_> { | Target::Cart(id) | Target::Other(id) => self.persist.raw.get(&id), Target::Player => self.level.player_extra.as_ref(), - Target::Guest(_) | Target::Orb(_) | Target::Projectile(_) => None, + Target::Guest(_) + | Target::Orb(_) + | Target::Projectile(_) + | Target::Crystal(_) + | Target::Dragon(_) => None, }; match raw.and_then(|r| r.get("Tags")) { Some(Tag::List(l)) => l diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index f8885f83a..750895adb 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -19,6 +19,9 @@ impl Screen { | Self::Advancements | Self::WorldOptions | Self::Friends + | Self::ServerLinks + | Self::ConfirmLink + | Self::DialogWarning | Self::Mod => true, Self::Playing | Self::GameModeSwitcher @@ -35,20 +38,35 @@ impl Screen { } /// PauseScreen buttons: (x, y, width, label key, action id, active). +/// `links`: the `minecraft:server_links` dialog's button, which the +/// `pause_screen_additions` tag (empty in vanilla) falls back to when the +/// server sent links — a full-width row that pushes the last two rows down. /// https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/PauseScreen -fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { +fn pause_buttons( + w: f32, + h: f32, + remote: bool, + links: bool, +) -> Vec<(f32, f32, f32, &'static str, u8, bool)> { // GridLayout of two 98px columns (padding 4), aligned at (0.5, 0.25). - let (grid_w, grid_h) = (212.0, 166.0); + let (grid_w, grid_h) = (212.0, 166.0 + if links { 24.0 } else { 0.0 }); let x0 = ((w - grid_w) * 0.5).floor(); let y0 = ((h - grid_h) * 0.25).floor(); - vec![ + let down = if links { 24.0 } else { 0.0 }; + let mut v = vec![ (x0 + 4.0, y0 + 50.0, 204.0, "menu.returnToGame", 0, true), (x0 + 4.0, y0 + 74.0, 98.0, "gui.advancements", 4, true), (x0 + 110.0, y0 + 74.0, 98.0, "gui.stats", 3, true), - (x0 + 4.0, y0 + 122.0, 98.0, "menu.options", 1, true), + ]; + if links { + // CommonDialogData.computeExternalTitle of Dialogs.SERVER_LINKS. + v.push((x0 + 4.0, y0 + 122.0, 204.0, "menu.server_links", 11, true)); + } + v.extend([ + (x0 + 4.0, y0 + 122.0 + down, 98.0, "menu.options", 1, true), ( x0 + 110.0, - y0 + 122.0, + y0 + 122.0 + down, 98.0, "options.worldOptions.button", 9, @@ -56,7 +74,7 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s ), ( x0 + 4.0, - y0 + 146.0, + y0 + 146.0 + down, 204.0, if remote { "menu.disconnect" @@ -66,16 +84,17 @@ fn pause_buttons(w: f32, h: f32, remote: bool) -> Vec<(f32, f32, f32, &'static s 2, true, ), - ] + ]); + v } /// The icon row: report bugs, feedback, friends, player reporting. /// `FRIENDS_ICON` (vanilla's `CommonButtons.friends`) opens Horizon's /// Play with Friends; the others stay inactive. const FRIENDS_ICON: usize = 2; -fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] { +fn pause_icons(w: f32, h: f32, links: bool) -> [(f32, f32, &'static str); 4] { let x0 = ((w - 212.0) * 0.5).floor() + 60.0; - let y = ((h - 166.0) * 0.25).floor() + 98.0; + let y = ((h - 166.0 - if links { 24.0 } else { 0.0 }) * 0.25).floor() + 98.0; [ (x0, y, "gui/sprites/pause_menu/bug"), (x0 + 24.0, y, "gui/sprites/pause_menu/social_interactions"), @@ -120,7 +139,9 @@ impl Game<'_> { u32::MAX, true, ); - for (x, y, bw, key, _, active) in pause_buttons(w, h, self.external_server()) { + let links = !self.server_links().is_empty(); + let mut tooltip = None; + for (x, y, bw, key, id, active) in pause_buttons(w, h, self.external_server(), links) { let hover = active && ui::hovered(self.cursor, x, y, bw, 20.0); ui::button( batch, @@ -133,9 +154,12 @@ impl Game<'_> { active, hover, ); + // PauseScreen's customAdditions button: CUSTOM_OPTIONS_TOOLTIP. + if id == 11 && hover { + tooltip = Some(Text::translate("menu.custom_options.tooltip", &[])); + } } - let mut tooltip = None; - for (i, (x, y, sprite)) in pause_icons(w, h).into_iter().enumerate() { + for (i, (x, y, sprite)) in pause_icons(w, h, links).into_iter().enumerate() { let active = i == FRIENDS_ICON && friends; let hover = ui::hovered(self.cursor, x, y, 20.0, 20.0); // The icon has no label: name it for controller focus and the @@ -168,7 +192,13 @@ impl Game<'_> { } // SpriteIconButton.withTootip: the label as a tooltip. if let Some(tip) = tooltip { - ui::tooltip(batch, atlas, &[tip], self.cursor); + let lines: Vec = atlas + .font + .split_lines(&tip, batch.width) + .into_iter() + .map(|(line, _)| line) + .collect(); + ui::tooltip(batch, atlas, &lines, self.cursor); } } pub(super) fn pause_click(&mut self) -> Result<()> { @@ -180,8 +210,9 @@ impl Game<'_> { let b = HudBatch::new(size); (b.width, b.height) }; - let friends = pause_icons(w, h)[FRIENDS_ICON]; - let hit = pause_buttons(w, h, self.external_server()) + let links = !self.server_links().is_empty(); + let friends = pause_icons(w, h, links)[FRIENDS_ICON]; + let hit = pause_buttons(w, h, self.external_server(), links) .into_iter() .find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0)) .map(|b| b.4) @@ -200,6 +231,11 @@ impl Game<'_> { Some(4) => self.open_advancements(true), Some(9) => self.open_world_options(), Some(10) => self.screen = Screen::Friends, + // DialogConnectionAccess.openDialog(Dialogs.SERVER_LINKS). + Some(11) => { + self.links_ui.scroll = 0.0; + self.screen = Screen::ServerLinks; + } Some(2) => self.close_world()?, _ => {} } @@ -357,7 +393,7 @@ impl Game<'_> { #[cfg(test)] mod tests { - use super::{Screen, pause_buttons}; + use super::{Screen, pause_buttons, pause_icons}; #[test] fn menu_blur_matches_vanilla_screen_backgrounds() { @@ -390,11 +426,32 @@ mod tests { #[test] fn pause_menu_uses_disconnect_for_servers_and_keeps_world_options() { for (remote, label) in [(false, "menu.returnToMenu"), (true, "menu.disconnect")] { - let buttons = pause_buttons(427.0, 240.0, remote); + let buttons = pause_buttons(427.0, 240.0, remote, false); let quit = buttons.iter().find(|b| b.4 == 2).unwrap(); assert_eq!(quit.3, label); assert!(quit.5); assert!(buttons.iter().any(|b| b.4 == 9 && b.5)); } } + + #[test] + fn server_links_adds_a_full_width_row_above_options() { + let with = pause_buttons(427.0, 240.0, true, true); + let without = pause_buttons(427.0, 240.0, true, false); + let links = with.iter().find(|b| b.4 == 11).unwrap(); + assert_eq!(links.2, 204.0); + assert_eq!(links.3, "menu.server_links"); + assert!(links.5); + // The icon row sits above it; Options and Disconnect move down 24. + let icons = pause_icons(427.0, 240.0, true); + let y0_icons = ((240.0f32 - 190.0) * 0.25).floor() + 98.0; + assert_eq!(icons[0].1, y0_icons); + assert!(links.1 > icons[0].1); + for b in &with { + if b.4 == 1 || b.4 == 9 || b.4 == 2 { + let same = without.iter().find(|o| o.4 == b.4).unwrap(); + assert_eq!(b.1, same.1 + 24.0 - 6.0, "{}", b.3); + } + } + } } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 7916c46a1..473509f0a 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -1194,14 +1194,14 @@ impl Game<'_> { /// `LightmapRenderStateExtractor`: the night vision effect's intensity /// (`GameRenderer.nightVisionScale`), or conduit power's water vision. - pub(super) fn night_vision_intensity(&self) -> f32 { + pub(super) fn night_vision_intensity(&self, partial: f32) -> f32 { use horizon_client::fog::FogType; if let Some(e) = self.potions.effects.get("night_vision") { // MobEffectInstance.endsWithin(200); -1 is infinite. return if e.duration < 0 || e.duration > 200 { 1.0 } else { - 0.7 + (e.duration as f32 * std::f32::consts::PI * 0.2).sin() * 0.3 + 0.7 + ((e.duration as f32 - partial) * std::f32::consts::PI * 0.2).sin() * 0.3 }; } if self.potions.effects.get("conduit_power").is_some() diff --git a/crates/horizon-client/src/game/server_links.rs b/crates/horizon-client/src/game/server_links.rs new file mode 100644 index 000000000..85fda71d6 --- /dev/null +++ b/crates/horizon-client/src/game/server_links.rs @@ -0,0 +1,487 @@ +//! `ServerLinksDialogScreen`: the pause menu's "Server Links..." button opens +//! the `minecraft:server_links` dialog (the `pause_screen_additions` tag's +//! fallback when a server sent ClientboundServerLinksPacket): a scrollable +//! list of the server's links, each opened through `ConfirmLinkScreen` +//! (Screen.clickUrlAction), and the `dialog/warning_button`'s +//! DialogScreen.WarningScreen ("Note about custom screens"). +//! https://mcsrc.dev/2/26.3/net/minecraft/client/gui/screens/dialog/ServerLinksDialogScreen +use super::{Game, Screen, packs::open_uri}; +use horizon_client::{Result, clipboard::Clipboard, hud::HudBatch, text::Text, ui}; +use horizon_protocol::packets::configuration::{ServerLink, ServerLinkKind}; + +/// HeaderAndFooterLayout's header and footer heights; the content wants to +/// start 30 pixels under the header (its `CONTENTS_MARGIN_TOP`). +const HEADER: f32 = 33.0; +const FOOTER: f32 = 33.0; +const CONTENT_TOP: f32 = HEADER + 30.0; +/// `server_links.json`: `columns` 1, `button_width` 310, `exit_action`'s 200. +const LINK_WIDTH: f32 = 310.0; +/// packControlsIntoColumns: rowSpacing 2 under the 20-pixel buttons. +const ROW: f32 = 22.0; +/// ScrollableLayout's BOTH reserve (scrollbarSpacing 4 + SCROLLBAR_WIDTH 6). +const SCROLL_RESERVE: f32 = 10.0; +/// DialogScreen's `dialog/warning_button` ImageButton. +const WARNING_BUTTON: f32 = 20.0; + +/// The ServerLinks screen's state: ScrollableLayout's scroll and the link +/// ConfirmLinkScreen is asking about (`Screen::ConfirmLink`). +#[derive(Default)] +pub(super) struct LinksUi { + pub scroll: f32, + pub confirm: Option, +} + +/// `Util.parseAndValidateUntrustedUri`: an absolute `http`/`https` URI +/// (java.net.URI's scheme then the allowlist; whitespace-free). +pub(super) fn valid_untrusted_uri(uri: &str) -> bool { + let Some(colon) = uri.find(':') else { + return false; + }; + let scheme = &uri[..colon]; + let mut chars = scheme.chars(); + if !chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + || !chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + { + return false; + } + if !matches!(scheme.to_ascii_lowercase().as_str(), "http" | "https") { + return false; + } + !uri.chars().any(|c| c.is_control() || c == ' ') +} +/// `ClientCommonPacketListenerImpl.handleServerLinks`: keep only the links +/// that validate, warning about the dropped ones. +pub(super) fn trusted(links: Vec) -> Vec { + links + .into_iter() + .filter(|l| { + let ok = valid_untrusted_uri(&l.link); + if !ok { + log::warn!("Horizon: server sent an invalid link: {}", l.link); + } + ok + }) + .collect() +} +/// `ServerLinks.Entry.displayName`: `known_server_link.` for a known +/// type (ByIdMap.ZERO reads unknown ids as `report_bug`), the component else. +fn link_label(link: &ServerLink) -> Text { + const KNOWN: [&str; 10] = [ + "report_bug", + "community_guidelines", + "support", + "status", + "feedback", + "community", + "website", + "forums", + "news", + "announcements", + ]; + match &link.kind { + ServerLinkKind::Known(id) => Text::translate( + &format!( + "known_server_link.{}", + KNOWN.get(*id as usize).copied().unwrap_or(KNOWN[0]) + ), + &[], + ), + ServerLinkKind::Custom(tag) => { + horizon_client::scoreboard::comp_text(&horizon_client::scoreboard::tag_to_json(tag)) + } + } +} + +/// The scrolled column of link buttons: content height and, for a list that +/// fits, the `HeaderAndFooterLayout` contents frame's top. +fn list_height(n: usize) -> f32 { + n as f32 * ROW - 2.0 +} +fn list_top(h: f32, n: usize) -> f32 { + CONTENT_TOP.min(h - FOOTER - list_height(n).min(h - HEADER - FOOTER)) +} +fn scroll_limit(h: f32, n: usize) -> f32 { + (list_height(n) - (h - HEADER - FOOTER)).max(0.0) +} + +/// `ServerLinksScreen`'s buttons as (x, y) over the scrolled content, and the +/// footer `Back` button's corner. `top` includes the scroll. +fn link_buttons(w: f32, top: f32, n: usize) -> Vec<(f32, f32)> { + let x = ((w - LINK_WIDTH - 2.0 * SCROLL_RESERVE) / 2.0 + SCROLL_RESERVE).floor(); + (0..n).map(|i| (x, top + i as f32 * ROW)).collect() +} +/// The warning button beside the title (DialogScreen's title row: 10 pixels +/// apart), clamped onto the screen (makeSureWarningButtonIsInBounds). +fn warning_button(w: f32, h: f32, title_width: f32) -> (f32, f32) { + let x = ((w - title_width - 30.0) / 2.0).floor() + title_width + 10.0; + let y = ((HEADER - WARNING_BUTTON) / 2.0).floor(); + if x < 0.0 || y < 0.0 || x > w - WARNING_BUTTON || y > h - WARNING_BUTTON { + (0.0f32.max(w - 40.0), 5.0f32.min(h)) + } else { + (x, y) + } +} +fn back_button(w: f32, h: f32) -> (f32, f32) { + ( + ((w - 200.0) / 2.0).floor(), + h - FOOTER + ((FOOTER - 20.0) / 2.0).floor(), + ) +} + +impl Game<'_> { + /// `connection.serverLinks()`: the links the open server sent (empty for + /// a world without a connection or one that sent none). + pub(super) fn server_links(&self) -> &[ServerLink] { + self.remote + .as_ref() + .map_or(&[], |r| r.server_links.as_slice()) + } + /// DialogScreen over the pause menu: `menu.server_links.title`, the + /// scrollable link buttons and `gui.back` in the footer. + pub(super) fn draw_server_links(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let links = self.server_links().to_vec(); + self.links_ui.scroll = self + .links_ui + .scroll + .clamp(0.0, scroll_limit(h, links.len())); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + // The title row: the title, then 10 pixels on the warning button. + let title = Text::translate("menu.server_links.title", &[]); + let tw = atlas.font.width_text(&title); + let tx = ((w - tw - 30.0) / 2.0).floor(); + batch.text_styled(atlas, &title, tx, 12.0, u32::MAX, true); + let (wx, wy) = warning_button(w, h, tw); + let wh = ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON); + horizon_client::widgets::record( + "menu.custom_screen_info.tooltip", + [wx, wy, WARNING_BUTTON, WARNING_BUTTON], + true, + ); + batch.sprite_scaled( + atlas, + if wh { + "gui/sprites/dialog/warning_button_highlighted" + } else { + "gui/sprites/dialog/warning_button" + }, + wx, + wy, + WARNING_BUTTON, + WARNING_BUTTON, + u32::MAX, + ); + let first = batch.vertices.len(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + for (link, (x, y)) in links.iter().zip(link_buttons(w, top, links.len())) { + let hover = inside && ui::hovered(self.cursor, x, y, LINK_WIDTH, 20.0); + ui::button( + batch, + atlas, + x, + y, + LINK_WIDTH, + 20.0, + &link_label(link), + true, + hover, + ); + } + batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); + ui::scrollbar( + batch, + atlas, + (w / 2.0).floor() + 155.0 + 4.0, + HEADER, + h - FOOTER, + list_height(links.len()), + self.links_ui.scroll.trunc(), + ); + let (bx, by) = back_button(w, h); + let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); + ui::button( + batch, + atlas, + bx, + by, + 200.0, + 20.0, + &Text::translate("gui.back", &[]), + true, + hover, + ); + if wh { + ui::tooltip( + batch, + atlas, + &[Text::translate("menu.custom_screen_info.tooltip", &[])], + self.cursor, + ); + } + } + /// A click on `Screen::ServerLinks`: a link, the warning button or Back. + pub(super) fn server_links_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let links = self.server_links().to_vec(); + let top = list_top(h, links.len()) - self.links_ui.scroll.trunc(); + let inside = self.cursor.1 >= HEADER && self.cursor.1 < h - FOOTER; + if inside + && let Some(i) = link_buttons(w, top, links.len()) + .iter() + .position(|(x, y)| ui::hovered(self.cursor, *x, *y, LINK_WIDTH, 20.0)) + { + self.audio.play_button_click(); + self.click_link(&links[i].link); + return Ok(()); + } + let title = Text::translate("menu.server_links.title", &[]); + let tw = self.gui.atlas.font.width_text(&title); + let (wx, wy) = warning_button(w, h, tw); + if ui::hovered(self.cursor, wx, wy, WARNING_BUTTON, WARNING_BUTTON) { + self.audio.play_button_click(); + self.screen = Screen::DialogWarning; + return Ok(()); + } + let (bx, by) = back_button(w, h); + if ui::hovered(self.cursor, bx, by, 200.0, 20.0) { + self.audio.play_button_click(); + self.screen = Screen::Paused; + } + Ok(()) + } + /// `Screen.clickUrlAction`: "Web Links" off ignores the click; "Prompt on + /// Links" asks with ConfirmLinkScreen, else the browser opens directly. + fn click_link(&mut self, url: &str) { + if !self.settings.chat_links { + return; + } + if self.settings.chat_links_prompt { + self.links_ui.confirm = Some(url.to_owned()); + self.screen = Screen::ConfirmLink; + } else { + open_uri(url); + } + } + /// `ScrollableLayout`'s mouse wheel over the links. + pub(super) fn server_links_scroll(&mut self, delta: f32) { + let (_, h) = self.gui_size(); + self.links_ui.scroll = (self.links_ui.scroll - delta * 10.0) + .clamp(0.0, scroll_limit(h, self.server_links().len())); + } + /// `ConfirmLinkScreen` (untrusted): "Are you sure you want to open the + /// following website?", the link, the red warning, and Yes / Copy Link to + /// Clipboard / No. + pub(super) fn draw_confirm_link(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(atlas, (w, h), &url); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let labels = ["gui.yes", "gui.copy_link_to_clipboard", "gui.no"]; + for ((x, y), key) in layout.buttons.iter().zip(labels) { + let hover = ui::hovered(self.cursor, *x, *y, 100.0, 20.0); + ui::button( + batch, + atlas, + *x, + *y, + 100.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// ConfirmLinkScreen's answer: yes opens the browser, the middle button + /// copies the link, no closes; all return to Server Links. + pub(super) fn confirm_link_click(&mut self) { + let (w, h) = self.gui_size(); + let url = self.links_ui.confirm.clone().unwrap_or_default(); + let layout = confirm_link_layout(&self.gui.atlas, (w, h), &url); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 100.0, 20.0) { + continue; + } + self.audio.play_button_click(); + match i { + 0 => open_uri(&url), + 1 => { + self.clipboard.set(&url); + } + _ => {} + } + self.screen = Screen::ServerLinks; + return; + } + } + /// `DialogScreen.WarningScreen`: the custom-screens note, a disconnect + /// button ("Custom screen rejected" is the shown reason) and Back. + pub(super) fn draw_dialog_warning(&mut self, batch: &mut HudBatch) { + let atlas = &self.gui.atlas; + let (w, h) = (batch.width, batch.height); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + let layout = dialog_warning_layout(atlas, (w, h)); + for (line, x, y) in &layout.lines { + batch.text_styled(atlas, line, *x, *y, u32::MAX, true); + } + let quit = if self.external_server() { + "menu.disconnect" + } else { + "menu.returnToMenu" + }; + for ((x, y), key) in layout.buttons.into_iter().zip([quit, "gui.back"]) { + let hover = ui::hovered(self.cursor, x, y, 150.0, 20.0); + ui::button( + batch, + atlas, + x, + y, + 150.0, + 20.0, + &Text::translate(key, &[]), + true, + hover, + ); + } + } + /// WarningScreen's answer: disconnect, or back to Server Links. + pub(super) fn dialog_warning_click(&mut self) -> Result<()> { + let (w, h) = self.gui_size(); + let layout = dialog_warning_layout(&self.gui.atlas, (w, h)); + for (i, (x, y)) in layout.buttons.iter().enumerate() { + if !ui::hovered(self.cursor, *x, *y, 150.0, 20.0) { + continue; + } + self.audio.play_button_click(); + if i == 0 { + // DialogConnectionAccess.disconnect: leave with the custom + // screens' reason. + let reason = self.translate( + "menu.custom_screen_info.disconnect", + "Custom screen rejected", + ); + self.leave_server(Some(reason))?; + } else { + self.screen = Screen::ServerLinks; + } + return Ok(()); + } + Ok(()) + } +} + +/// A confirm screen's laid-out text (title, message, extra warning lines) and +/// button corners; the whole column centred (ConfirmScreen.init). +struct ConfirmLayout { + lines: Vec<(Text, f32, f32)>, + buttons: Vec<(f32, f32)>, +} +/// `ConfirmScreen.init`: title, message wrapped to `width - 50` (15 rows at +/// most), the extra lines, then a button row `spacing` 4 with `paddingTop` 16. +fn confirm_layout( + font: &horizon_client::font::Font, + (w, h): (f32, f32), + title: &Text, + message: &Text, + extra: &[Text], + button_widths: &[f32], +) -> ConfirmLayout { + let message: Vec = font + .split_lines(message, w - 50.0) + .into_iter() + .take(15) + .map(|(line, _)| line) + .collect(); + // LinearLayout vertical spacing 8; the button row's children pad 16 on top. + let extra_h = 17.0 * extra.len() as f32; + let mh = 9.0 * message.len() as f32; + let total = 9.0 + 8.0 + mh + extra_h + 8.0 + 16.0 + 20.0; + let mut y = ((h - total) / 2.0).trunc(); + let mut lines = Vec::new(); + let mut push = |line: &Text, at: f32| { + let lw = font.width_text(line); + lines.push((line.clone(), ((w - lw) / 2.0).trunc(), at)); + }; + push(title, y); + y += 17.0; + for line in &message { + push(line, y); + y += 9.0; + } + for line in extra { + y += 8.0; + push(line, y); + y += 9.0; + } + let row_w: f32 = button_widths.iter().sum::() + 4.0 * (button_widths.len() - 1) as f32; + let by = y + 8.0 + 16.0; + let mut bx = ((w - row_w) / 2.0).trunc(); + let buttons = button_widths + .iter() + .map(|bw| { + let p = (bx, by); + bx += bw + 4.0; + p + }) + .collect(); + ConfirmLayout { lines, buttons } +} +fn confirm_link_layout( + atlas: &horizon_client::hud::HudAtlas, + size: (f32, f32), + url: &str, +) -> ConfirmLayout { + // ConfirmLinkScreen (untrusted): `chat.link.confirm`, the link as the + // message, `chat.link.warning` in its red (0xFFCCCC). + confirm_layout( + &atlas.font, + size, + &Text::translate("chat.link.confirm", &[]), + &Text::literal(url.to_owned()), + &[Text::translate("chat.link.warning", &[]).with_color(0xFFCCCC)], + &[100.0; 3], + ) +} +fn dialog_warning_layout(atlas: &horizon_client::hud::HudAtlas, size: (f32, f32)) -> ConfirmLayout { + confirm_layout( + &atlas.font, + size, + &Text::translate("menu.custom_screen_info.title", &[]), + &Text::translate("menu.custom_screen_info.contents", &[]), + &[], + &[150.0; 2], + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn untrusted_uris_are_http_or_https_with_a_scheme() { + for ok in [ + "https://example.net/x", + "http://example.net", + "HTTPS://EXAMPLE.NET", + ] { + assert!(valid_untrusted_uri(ok), "{ok}"); + } + for bad in [ + "example.net/no-scheme", + "ftp://example.net", + "file:///etc/passwd", + "javascript:alert(1)", + "https://exa mple.net", + "://example.net", + "", + ] { + assert!(!valid_untrusted_uri(bad), "{bad}"); + } + } +} diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index ed5971324..fdeb726ae 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -546,6 +546,11 @@ impl Loading { (batch.width, batch.height), self.menu.modifiers.shift_key(), ); + title.press_rules( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + ); self.menu_action(event_loop, action); } } diff --git a/crates/horizon-client/src/game/text_displays.rs b/crates/horizon-client/src/game/text_displays.rs index 45bd64fa7..587db3382 100644 --- a/crates/horizon-client/src/game/text_displays.rs +++ b/crates/horizon-client/src/game/text_displays.rs @@ -164,11 +164,12 @@ impl Game<'_> { } else { [self.yaw, self.pitch] }; + let scale = self.view_scale(); for display in self.text_displays.values_mut() { display.last_progress = display.progress(partial as f32); let d = display.shown.blend(&display.from, display.last_progress); let position = display.previous.lerp(display.position, partial); - let range = f64::from(d.view_range) * 64.0 * f64::from(self.settings.entity_distance); + let range = f64::from(d.view_range) * 64.0 * scale; if position.distance_squared(camera) >= range * range || d.text.is_empty() { continue; } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 6bd2ae956..177e3bf80 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -252,7 +252,7 @@ impl Game<'_> { } let range = super::entity_culling::default_range( glam::DVec3::splat(PrimedTnt::SIZE), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tnts { // EntityRenderer.shouldRender. diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index d934e85aa..9d6b3f9c5 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -21,7 +21,7 @@ pub(super) struct ThrownTrident { pub id: u32, pub(super) stack: ItemStack, pub(super) position: Vec3, - previous: Vec3, + pub(super) previous: Vec3, pub(super) velocity: Vec3, pub(super) yaw: f32, pub(super) pitch: f32, @@ -112,7 +112,7 @@ impl Game<'_> { } true } - fn in_water_or_rain(&self) -> bool { + fn in_water_or_rain(&mut self) -> bool { let Some(p) = &self.player else { return false }; let (x, y, z) = ( p.position.x.floor() as i32, @@ -121,8 +121,8 @@ impl Game<'_> { ); let water = self.res.facts().get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water; - let sky = self.world.light(x, y + 1, z) >> 4 == 15; - water || (self.world.weather.raining && sky) + let (at, top) = (p.position, p.bounds().max_position().y); + water || self.in_rain(at, top) } /// The living entities a spinning player can touch this tick, for /// `LivingEntity.checkAutoSpinAttack` (none when not spinning). @@ -495,7 +495,7 @@ impl Game<'_> { let range = 10.0 * super::entity_culling::default_range( glam::DVec3::splat(2.0 * HALF), - self.settings.entity_distance, + self.view_scale(), ); for t in &self.tridents { // EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5. diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index fb24102ba..63ac2641d 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -68,7 +68,7 @@ impl Game<'_> { velocity, on_ground, ); - self.creatures.projectiles.push(proj); + self.add_projectile(proj); let pitch = 0.4 / (self.world.random.next_float() * 0.4 + 0.8); self.audio .play("minecraft:entity.wind_charge.throw", Some(eye), 0.5, pitch); diff --git a/crates/horizon-client/src/game/world_loading.rs b/crates/horizon-client/src/game/world_loading.rs index 73f1820f2..454f9f2eb 100644 --- a/crates/horizon-client/src/game/world_loading.rs +++ b/crates/horizon-client/src/game/world_loading.rs @@ -94,6 +94,8 @@ impl WorldRequest { level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); level.allow_commands = Some(o.commands(creative)); horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + // WorldCreationUiState.getGameRules, written with the level. + level.game_rules = o.rules.by_name(); } // Worlds made without the Create New World screen (--world, the // control socket) take its default: commands on for Creative only. diff --git a/crates/horizon-client/src/game/game_rules_screen.rs b/crates/horizon-client/src/game_rules_screen.rs similarity index 91% rename from crates/horizon-client/src/game/game_rules_screen.rs rename to crates/horizon-client/src/game_rules_screen.rs index 0992f7689..7f7c307b6 100644 --- a/crates/horizon-client/src/game/game_rules_screen.rs +++ b/crates/horizon-client/src/game_rules_screen.rs @@ -1,8 +1,9 @@ -//! InWorldGameRulesScreen (AbstractGameRulesScreen), opened from World -//! Options: the rules by category under a search box, a switch or a number -//! box each, and Done sending the changed ones (ServerboundSetGameRulePacket). -//! Leaving with changes asks first (ConfirmScreen). -use horizon_client::{ +//! AbstractGameRulesScreen: the rules by category under a search box, a +//! switch or a number box each. InWorldGameRulesScreen, opened from World +//! Options, sends the changed ones on Done (ServerboundSetGameRulePacket) and +//! asks before leaving with changes (ConfirmScreen); WorldCreationGameRulesScreen, +//! opened from Create New World, hands them back and leaves without asking. +use crate::{ confirm_screen::Confirm, font::Font, gamerules::{self, GameRules, RULES, Rule, Value}, @@ -32,14 +33,14 @@ enum Row { /// What a click or Escape asks of World Options. #[derive(Debug, PartialEq)] -pub(super) enum Exit { +pub enum Exit { /// Done: the rules that changed. Apply(Vec<(&'static str, Value)>), /// Cancel, or discarding the changes. Discard, } -pub(super) struct RulesScreen { +pub struct RulesScreen { search: EditBox, values: GameRules, initial: GameRules, @@ -49,6 +50,8 @@ pub(super) struct RulesScreen { scroll: ui::Scroll, /// ConfirmScreen "Game Rule Changes" in its place. confirm: bool, + /// InWorldGameRulesScreen rather than WorldCreationGameRulesScreen. + in_world: bool, } fn name_key(r: &Rule) -> String { @@ -102,7 +105,15 @@ fn confirm(font: &Font, size: (f32, f32)) -> Confirm { } impl RulesScreen { - pub(super) fn new(rules: &GameRules) -> Self { + /// InWorldGameRulesScreen over the world's rules. + pub fn new(rules: &GameRules) -> Self { + Self::build(rules, true) + } + /// WorldCreationGameRulesScreen over the new world's rules. + pub fn for_creation(rules: &GameRules) -> Self { + Self::build(rules, false) + } + fn build(rules: &GameRules, in_world: bool) -> Self { // setInitialFocus: the search box. let search = EditBox::new(0.0, 0.0, SEARCH_WIDTH, 15.0); let numbers = RULES @@ -123,6 +134,7 @@ impl RulesScreen { numbers, scroll: ui::Scroll::default(), confirm: false, + in_world, } } @@ -197,9 +209,10 @@ impl RulesScreen { }) .collect() } - /// InWorldGameRulesScreen.onClose: pending changes ask first. + /// InWorldGameRulesScreen.onClose: pending changes ask first; + /// WorldCreationGameRulesScreen.onClose discards them. fn close(&mut self) -> Option { - if self.changes().is_empty() { + if !self.in_world || self.changes().is_empty() { Some(Exit::Discard) } else { self.confirm = true; @@ -207,7 +220,7 @@ impl RulesScreen { } } /// Escape: ConfirmScreen answers no; the rules close. - pub(super) fn escape(&mut self) -> Option { + pub fn escape(&mut self) -> Option { if self.confirm { self.confirm = false; None @@ -216,7 +229,7 @@ impl RulesScreen { } } /// The mouse wheel (AbstractSelectionList: half an entry a step). - pub(super) fn wheel(&mut self, delta: f32, h: f32) { + pub fn wheel(&mut self, delta: f32, h: f32) { if !self.confirm { let content = self.content(); self.scroll @@ -224,20 +237,20 @@ impl RulesScreen { } } /// A press on the scrollbar holds it (AbstractSelectionList.updateScrolling). - pub(super) fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool { + pub fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool { let content = self.content(); self.scroll .press(cursor, Self::bar(w), HEADER, h - FOOTER, content) } /// The pointer moved while the scrollbar is held. - pub(super) fn drag(&mut self, y: f32, h: f32) { + pub fn drag(&mut self, y: f32, h: f32) { if self.scroll.held() { let content = self.content(); self.scroll.drag(y, HEADER, h - FOOTER, content); } } /// The button came up: the scrollbar lets go. - pub(super) fn release(&mut self) { + pub fn release(&mut self) { self.scroll.release(); } fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> { @@ -272,7 +285,7 @@ impl RulesScreen { } } /// Run an edit on the focused box, then its responder. - pub(super) fn edit(&mut self, f: impl FnOnce(&mut EditBox)) { + pub fn edit(&mut self, f: impl FnOnce(&mut EditBox)) { let Some((rule, b)) = self.focused() else { return; }; @@ -282,12 +295,12 @@ impl RulesScreen { self.edited(rule); } } - pub(super) fn typing(&self) -> bool { + pub fn typing(&self) -> bool { !self.confirm && (self.search.focused || self.numbers.iter().any(|(_, b)| b.focused)) } /// A left click; Some when the screen closes. - pub(super) fn click( + pub fn click( &mut self, atlas: &HudAtlas, cursor: (f32, f32), @@ -355,12 +368,7 @@ impl RulesScreen { } } /// Whether a click lands on a button (for its sound). - pub(super) fn clicks_button( - &self, - atlas: &HudAtlas, - cursor: (f32, f32), - size: (f32, f32), - ) -> bool { + pub fn clicks_button(&self, atlas: &HudAtlas, cursor: (f32, f32), size: (f32, f32)) -> bool { let (w, h) = size; let on = |(x, y): (f32, f32)| ui::hovered(cursor, x, y, 150.0, 20.0); if self.confirm { @@ -377,9 +385,9 @@ impl RulesScreen { }) } - pub(super) fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { + pub fn draw(&mut self, batch: &mut HudBatch, atlas: &HudAtlas, cursor: (f32, f32)) { let (w, h) = (batch.width, batch.height); - ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); + ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world); if self.confirm { let labels = [ Text::translate("gui.yes", &[]), @@ -393,7 +401,7 @@ impl RulesScreen { self.scroll.clamp(HEADER, h - FOOTER, content); // RuleList: the in-world list background, its entries clipped to it, // then the separators and scrollbar. - ui::list_background(batch, atlas, HEADER, h - FOOTER, true); + ui::list_background(batch, atlas, HEADER, h - FOOTER, self.in_world); let first = batch.vertices.len(); let hovered = self.hovered(rows.len(), cursor, (w, h)); let (left, x) = (row_left(w), control_x(w)); @@ -450,7 +458,7 @@ impl RulesScreen { } } batch.clip_since(first, 0.0, HEADER, w, h - FOOTER); - ui::separators(batch, atlas, HEADER, h - FOOTER, true); + ui::separators(batch, atlas, HEADER, h - FOOTER, self.in_world); ui::scrollbar( batch, atlas, @@ -526,8 +534,8 @@ mod tests { #[test] fn box_colours_are_vanillas() { - assert_eq!(VALID, horizon_client::hud::rgba(224, 224, 224, 255)); - assert_eq!(INVALID, horizon_client::hud::rgba(255, 0, 0, 255)); + assert_eq!(VALID, crate::hud::rgba(224, 224, 224, 255)); + assert_eq!(INVALID, crate::hud::rgba(255, 0, 0, 255)); } #[test] diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 70d882a98..a98637b5a 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -37,7 +37,10 @@ mod crumbling_tests; mod entity_batch; mod weather; use entity_batch::EntityBatch; -pub use entity_batch::{SHADOW_OVERLAY, TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY}; +pub use entity_batch::{ + SHADOW_OVERLAY, TRANSLUCENT_GLINT_ITEM_OVERLAY, TRANSLUCENT_ITEM_OVERLAY, + TRANSLUCENT_PARTICLE_OVERLAY, WATER_MASK_OVERLAY, +}; /// Window.getAppropriateLineWidth, in framebuffer pixels. pub fn outline_width(width: u32) -> f32 { @@ -247,6 +250,8 @@ pub struct Frame<'a> { pub outline: Vec<[f64; 6]>, /// `BlockOutlineRenderState.isTranslucent`: draw after translucent terrain. pub outline_after_terrain: bool, + /// `BlockOutlineRenderState.highContrast`: a thick black outline under a bright one. + pub outline_high_contrast: bool, /// `lines` with a colour and pixel width (`gizmos::camera_relative`): /// the fishing line and debug gizmos, depth tested, then gizmos drawn /// over everything. @@ -377,6 +382,7 @@ pub struct Renderer { sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, + lines_secondary: wgpu::RenderPipeline, /// Gizmo lines (`RenderTypes.linesTranslucentNoDepthWrite`) and the /// always-on-top ones. debug_lines: wgpu::RenderPipeline, @@ -391,6 +397,7 @@ pub struct Renderer { weather: weather::Weather, crumbling_pipeline: wgpu::RenderPipeline, shadow_blob_pipeline: wgpu::RenderPipeline, + translucent_item_pipeline: wgpu::RenderPipeline, /// `RenderPipelines.WATER_MASK`: depth writes only, no colour. water_mask_pipeline: wgpu::RenderPipeline, cloud_pipeline: wgpu::RenderPipeline, @@ -511,10 +518,10 @@ pub struct Renderer { occlusion: occlusion::Occlusion, /// Resolution scale and FXAA (Horizon settings). world_post: world_post::Post, - /// HDR output (Horizon setting): `Some` while the swapchain is scRGB. + /// HDR output (Horizon setting): `Some` while the swapchain is HDR. hdr: Option, - /// Whether the window's surface can present scRGB. - hdr_capable: bool, + /// The HDR output the window's surface can present. + hdr_output: Option, /// The shader pack's post-processing, and the dimension (legacy id) it was loaded for. pack_post: Option<(i32, Option)>, /// The post passes of one of Horizon's own shader packs; never beside `pack_post`'s. @@ -1071,7 +1078,7 @@ impl Renderer { let info = adapter.get_info(); crate::graphics::suggest_reduced_far_detail(crate::graphics::lod_capped(&info)); let size = window.inner_size(); - let (config, present_modes, hdr_capable) = if let Some(surface) = &surface { + let (config, present_modes, hdr_output) = if let Some(surface) = &surface { let mut config = surface .get_default_config(&adapter, size.width.max(1), size.height.max(1)) .ok_or("surface has no supported configuration")?; @@ -1099,7 +1106,7 @@ impl Renderer { )); } surface.configure(&device, &config); - (config, caps.present_modes.clone(), hdr::supported(&caps)) + (config, caps.present_modes.clone(), hdr::output(&caps)) } else { let format = wgpu::TextureFormat::Bgra8Unorm; let config = wgpu::SurfaceConfiguration { @@ -1113,7 +1120,7 @@ impl Renderer { view_formats: vec![format], color_space: wgpu::SurfaceColorSpace::default(), }; - (config, Vec::new(), false) + (config, Vec::new(), None) }; let offscreen = surface .is_none() @@ -1213,12 +1220,6 @@ impl Renderer { attributes: &instance_attributes, }), ]; - let line_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3]; - let line_buffers = [Some(wgpu::VertexBufferLayout { - array_stride: 24, - step_mode: wgpu::VertexStepMode::Instance, - attributes: &line_attributes, - })]; let alpha_blend = wgpu::BlendState::ALPHA_BLENDING; let debug_line_attributes = wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x3,2=>Unorm8x4,3=>Float32]; @@ -1351,13 +1352,25 @@ impl Renderer { "Block outline", "vs_line", "fs_line", - &line_buffers, + &debug_line_buffers, wgpu::PrimitiveTopology::TriangleStrip, None, true, true, Some(alpha_blend), ); + // RenderTypes.secondaryBlockOutline: the black stroke under a high contrast outline. + let lines_secondary = pipeline( + "Block outline secondary", + "vs_line", + "fs_line", + &debug_line_buffers, + wgpu::PrimitiveTopology::TriangleStrip, + None, + false, + true, + Some(alpha_blend), + ); let debug_lines = pipeline( "Debug lines", "vs_debug_line", @@ -1531,7 +1544,7 @@ impl Renderer { }); let outline = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Outline"), - size: 24 * MAX_OUTLINE_EDGES, + size: 32 * 2 * MAX_OUTLINE_EDGES, usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -1818,25 +1831,40 @@ impl Renderer { false, ); // RenderPipelines.ENTITY_SHADOW: translucent, depth test without - // writes. The quads lie on the block tops like vanilla's, but the - // terrain under them snaps to the subpixel grid at other vertices, so - // at a slant their depths differ by up to 1/256 of a pixel's depth - // slope and whole shadows failed the test. The bias covers that and - // the rounding, and stays below the 0.001 a model's feet sit higher - // (1/27 of a pixel's slope at the 16-block shadow range in 720p). + // writes. The quads lie exactly on the block tops like vanilla's, but + // terrain and shadows are separate draw paths, so their fp32 depth + // interpolations disagree by a few dozen ulps of the fragment depth + // and the shadow's rim z-fights with the block top (speckle that + // re-rolls as the camera drifts a subpixel). A constant bias of 128 + // ulps covers that spread at any resolution while staying far below + // the 0.001 a model's feet sit higher, so shadows never bleed onto + // the feet. let shadow_blob_pipeline = entity_pipeline( "Entity shadows", None, false, wgpu::CompareFunction::GreaterEqual, wgpu::DepthBiasState { - constant: 16, + constant: 128, slope_scale: 0.015, clamp: 0.0, }, alpha_blend, false, ); + // RenderPipelines.ITEM_TRANSLUCENT: blended, depth tested. Drawn before + // translucent terrain, it cannot write depth: the water behind a + // glass item would fail the test and vanish (vanilla sorts these in + // its order independent transparency pass instead). + let translucent_item_pipeline = entity_pipeline( + "Translucent items", + None, + false, + wgpu::CompareFunction::GreaterEqual, + Default::default(), + alpha_blend, + false, + ); let cloud_pipeline = entity_pipeline( "Clouds", Some(wgpu::Face::Back), @@ -1953,22 +1981,23 @@ impl Renderer { multisample: Default::default(), fragment: Some(wgpu::FragmentState { module: &entity_shader, - entry_point: Some("fs_celestial"), + entry_point: Some("fs_sky_celestial"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { format: config.format.remove_srgb_suffix(), - // RenderPipelines.CELESTIAL: additive (src alpha, one). The - // alpha goes to 0: HDR output (hdr.wgsl) lets the sun and - // moon shine; nothing else reads the frame's alpha. + // RenderPipelines.CELESTIAL: additive (src alpha, one), with + // the colour premultiplied in fs_sky_celestial. Its alpha is + // how much a texel adds: HDR output (hdr.wgsl) lets the sun's + // and moon's discs shine; nothing else reads the frame's alpha. blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { - src_factor: wgpu::BlendFactor::SrcAlpha, + src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add, }, alpha: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::Zero, - dst_factor: wgpu::BlendFactor::Zero, + dst_factor: wgpu::BlendFactor::OneMinusSrcAlpha, operation: wgpu::BlendOperation::Add, }, }), @@ -2361,6 +2390,7 @@ impl Renderer { sky, dark_disc, lines, + lines_secondary, debug_lines, debug_lines_on_top, debug_line_buffer, @@ -2371,6 +2401,7 @@ impl Renderer { weather, crumbling_pipeline, shadow_blob_pipeline, + translucent_item_pipeline, water_mask_pipeline, cloud_pipeline, cloud_mesh: Default::default(), @@ -2456,7 +2487,7 @@ impl Renderer { occlusion: occlusion::Occlusion::new(crate::chunk::MIN_Y, crate::chunk::HEIGHT / 16), world_post, hdr: None, - hdr_capable, + hdr_output, pack_post: None, native: None, pass_timing: pack_timing::PassTiming::logging(), @@ -2482,6 +2513,18 @@ impl Renderer { present_modes, }) } + /// LevelRenderer.submitBlockOutline: the buffer holds `edges` per stroke, the black + /// secondary stroke first when high contrast is on. + fn draw_outline(&self, pass: &mut wgpu::RenderPass<'_>, edges: u32, high_contrast: bool) { + pass.set_vertex_buffer(0, self.outline.slice(..)); + if high_contrast { + pass.set_pipeline(&self.lines_secondary); + pass.draw(0..4, 0..edges); + } + pass.set_pipeline(&self.lines); + let first = if high_contrast { edges } else { 0 }; + pass.draw(0..4, first..first + edges); + } fn quad_indices(device: &wgpu::Device, quads: u32) -> wgpu::Buffer { let indices: Vec = (0..quads) .flat_map(|q| { @@ -2990,24 +3033,24 @@ impl Renderer { } } /// The swapchain's configuration: `config` (what every pipeline draws in), or - /// scRGB while HDR output is on. + /// HDR10 or scRGB while HDR output is on. fn surface_config(&self) -> wgpu::SurfaceConfiguration { let mut config = self.config.clone(); - if self.hdr.is_some() { - config.format = hdr::FORMAT; - config.view_formats = vec![hdr::FORMAT]; - config.color_space = hdr::COLOR_SPACE; + if let Some(hdr) = &self.hdr { + config.format = hdr.output.format(); + config.view_formats = vec![hdr.output.format()]; + config.color_space = hdr.output.color_space(); config.usage = wgpu::TextureUsages::RENDER_ATTACHMENT; } config } - /// HDR output (Horizon setting): scRGB at `paper_white` nits, the world's + /// HDR output (Horizon setting): HDR10 or scRGB at `paper_white` nits, the world's /// highlights expanded up to `peak` nits. Off where the surface can't present it. pub fn set_hdr(&mut self, on: bool, paper_white: f32, peak: f32) { - let on = on && self.hdr_capable && self.surface.is_some(); - if on != self.hdr.is_some() { - self.hdr = - on.then(|| hdr::Hdr::new(&self.device, self.config.format.remove_srgb_suffix())); + let output = self.hdr_output.filter(|_| on && self.surface.is_some()); + if output.is_some() != self.hdr.is_some() { + let format = self.config.format.remove_srgb_suffix(); + self.hdr = output.map(|output| hdr::Hdr::new(&self.device, format, output)); self.configure_surface(); } if let Some(hdr) = &mut self.hdr @@ -3194,7 +3237,7 @@ impl Renderer { /// The Mipmap Levels option: block textures sample at most `levels` /// reduced copies (0: none). pub fn set_mipmap_levels(&mut self, levels: u32) { - let levels = sprite_mipmap_limit( + let levels = crate::sprites::sprite_mipmap_limit( levels, self.sprite_textures[0].width(), self.sprite_minimum_size, @@ -3954,7 +3997,26 @@ impl Renderer { ); let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize); if outline_edges > 0 { - let lines = outline_vertices(&frame.outline[..outline_edges], camera); + // The same per-line colour and pixel width layout as the gizmo lines. A high + // contrast outline is two strokes: the black one first, the bright one after it. + let edges = outline_vertices(&frame.outline[..outline_edges], camera); + let width = outline_width(self.config.width); + let stroke = |color: u32, width: f32| { + edges.iter().map(move |e| { + let mut line = [0.0; 8]; + line[..6].copy_from_slice(e); + line[6] = f32::from_bits(color); + line[7] = width; + line + }) + }; + let lines: Vec<[f32; 8]> = if frame.outline_high_contrast { + stroke(0xff00_0000, 7.0) + .chain(stroke(0xff57_ffe1, width)) + .collect() + } else { + stroke(0x6600_0000, width).collect() + }; self.uploads .buffer(&mut encoder, &self.outline, 0, bytemuck::cast_slice(&lines)); } @@ -3981,6 +4043,7 @@ impl Renderer { water_mask_quads, shadow_quads, translucent_particle_quads, + translucent_item_quads, ] = self .entity_batch .update(entities, frame.additive, frame.hand, frame.see_through); @@ -3990,7 +4053,8 @@ impl Renderer { + translucent_crumbling_quads + water_mask_quads + shadow_quads - + translucent_particle_quads; + + translucent_particle_quads + + translucent_item_quads; let cloud_quads = if let Some(input) = &frame.clouds { let (rebuilt, uniform) = crate::spans::time("clouds", || self.cloud_mesh.prepare(input)); @@ -4513,6 +4577,17 @@ impl Renderer { pass.draw_indexed(0..entity_quads * 6, 0, 0..1); pass.set_bind_group(0, &self.group, &[]); } + if translucent_item_quads > 0 { + pass.set_pipeline(&self.translucent_item_pipeline); + pass.set_bind_group(0, &self.entity_group, &[]); + pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); + pass.draw_indexed( + 0..translucent_item_quads * 6, + ((world_quads - translucent_item_quads) * 4) as i32, + 0..1, + ); + pass.set_bind_group(0, &self.group, &[]); + } if !pack_draws_weather { self.weather.draw(&mut pass, &self.entity_group); } @@ -4530,7 +4605,11 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed( 0..shadow_quads * 6, - ((world_quads - translucent_particle_quads - shadow_quads) * 4) as i32, + ((world_quads + - translucent_item_quads + - translucent_particle_quads + - shadow_quads) + * 4) as i32, 0..1, ); pass.set_bind_group(0, &self.group, &[]); @@ -4562,9 +4641,7 @@ impl Renderer { pass.set_bind_group(0, &self.group, &[]); } if outline_edges > 0 && !frame.outline_after_terrain { - pass.set_pipeline(&self.lines); - pass.set_vertex_buffer(0, self.outline.slice(..)); - pass.draw(0..4, 0..outline_edges as u32); + self.draw_outline(&mut pass, outline_edges as u32, frame.outline_high_contrast); } if debug_depth > 0 { pass.set_pipeline(&self.debug_lines); @@ -4611,7 +4688,8 @@ impl Renderer { pass.set_vertex_buffer(0, self.entity_buffer.slice(..)); pass.draw_indexed( 0..translucent_particle_quads * 6, - ((world_quads - translucent_particle_quads) * 4) as i32, + ((world_quads - translucent_item_quads - translucent_particle_quads) * 4) + as i32, 0..1, ); pass.set_bind_group(0, &self.group, &[]); @@ -4619,9 +4697,7 @@ impl Renderer { // LevelRenderer.executeClassicTransparency: translucent targets' // outlines follow terrain, so its blending cannot wash them out. if outline_edges > 0 && frame.outline_after_terrain { - pass.set_pipeline(&self.lines); - pass.set_vertex_buffer(0, self.outline.slice(..)); - pass.draw(0..4, 0..outline_edges as u32); + self.draw_outline(&mut pass, outline_edges as u32, frame.outline_high_contrast); } pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); // LevelRenderer: the world border after translucent terrain and weather. @@ -5240,7 +5316,7 @@ mod tests { let mut batch = super::EntityBatch::default(); let counts = batch.update(&entities, &quad(3, 5), &quad(0, 6), &quad(0, 8)); let vertices = &batch.combined; - assert_eq!(counts, [4, 1, 1, 0, 1, 1]); + assert_eq!(counts, [4, 1, 1, 0, 1, 1, 0]); assert_eq!( vertices .as_chunks::<4>() @@ -5476,11 +5552,6 @@ mod tests { } } -pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, available: u32) -> u32 { - // Only the atlas native minimum determines how many resampling-only mips to skip. - let upscale = (size / minimum.max(1)).max(1).ilog2(); - requested.saturating_add(upscale).min(available - 1) -} #[cfg(test)] mod sprite_upload_tests { use super::*; @@ -5541,13 +5612,6 @@ mod sprite_upload_tests { } } #[test] - fn mipmap_option_keeps_real_16px_reductions() { - for levels in 0..=4 { - assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1); - assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels); - } - } - #[test] fn prepared_texture_uploads_preserve_layer_order_and_settings() { let size = 4; let layers = 5; diff --git a/crates/horizon-client/src/gfx/entity_batch.rs b/crates/horizon-client/src/gfx/entity_batch.rs index 8153699fc..08d749b54 100644 --- a/crates/horizon-client/src/gfx/entity_batch.rs +++ b/crates/horizon-client/src/gfx/entity_batch.rs @@ -5,14 +5,20 @@ use super::Vertex; /// ordinary entities, breaking cracks (11), translucent breaking cracks (12), /// the boat water mask (13, `RenderPipelines.WATER_MASK`), entity shadows /// (14, `RenderPipelines.ENTITY_SHADOW`) and translucent-layer particles (15, -/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`). -const MATERIALS: usize = 6; +/// drawn after translucent terrain: `SubmitNodeCollection.submitQuadParticleGroup`) +/// and translucent item quads (32, drawn without depth writes). +const MATERIALS: usize = 7; /// The overlay of depth-only quads that hide water (`RenderTypes.waterMask`). pub const WATER_MASK_OVERLAY: u32 = 13; /// The overlay of entity shadow quads (`RenderTypes.entityShadow`). pub const SHADOW_OVERLAY: u32 = 14; /// The overlay of translucent-layer particles (`SingleQuadParticle.Layer.translucent`). pub const TRANSLUCENT_PARTICLE_OVERLAY: u32 = 15; +/// The overlay of item quads with translucent pixels (`Sheets.translucentItemSheet`, +/// `RenderPipelines.ITEM_TRANSLUCENT`); past the creeper swell range (16 to 31). +pub const TRANSLUCENT_ITEM_OVERLAY: u32 = 32; +/// A translucent item with an enchantment glint. +pub const TRANSLUCENT_GLINT_ITEM_OVERLAY: u32 = 33; #[derive(Default)] pub(super) struct EntityBatch { @@ -45,6 +51,7 @@ impl EntityBatch { WATER_MASK_OVERLAY => 3, SHADOW_OVERLAY => 4, TRANSLUCENT_PARTICLE_OVERLAY => 5, + TRANSLUCENT_ITEM_OVERLAY | TRANSLUCENT_GLINT_ITEM_OVERLAY => 6, _ => 0, }; self.buckets[material][counts[material]] = index; diff --git a/crates/horizon-client/src/gfx/hdr.rs b/crates/horizon-client/src/gfx/hdr.rs index 11deed546..8b9df7af0 100644 --- a/crates/horizon-client/src/gfx/hdr.rs +++ b/crates/horizon-client/src/gfx/hdr.rs @@ -1,17 +1,50 @@ //! HDR output (Horizon setting, off by default): the frame renders exactly as //! without it, into an 8-bit target in vanilla's gamma space, and one pass -//! (`hdr.wgsl`) writes it to an scRGB swapchain at the player's paper white, -//! expanding the world's highlights towards their peak brightness. The world -//! is copied aside before the hand and HUD so only it is expanded. +//! (`hdr.wgsl`) writes it to an HDR10 or scRGB swapchain at the player's paper +//! white, expanding the world's highlights towards their peak brightness. The +//! world is copied aside before the hand and HUD so only it is expanded. -/// The swapchain format and colour space HDR output presents in. -pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float; -pub const COLOR_SPACE: wgpu::SurfaceColorSpace = wgpu::SurfaceColorSpace::ExtendedSrgbLinear; +/// The swapchain HDR output presents to. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Output { + /// HDR10: 10-bit BT.2020 with the PQ curve, the display's own signal. + Pq, + /// scRGB: linear 16-bit float, BT.709 primaries, 1.0 = 80 nits. + ScRgb, +} -/// Whether `caps` can present scRGB. -pub fn supported(caps: &wgpu::SurfaceCapabilities) -> bool { - caps.color_spaces(FORMAT) - .contains(wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR) +impl Output { + pub fn format(self) -> wgpu::TextureFormat { + match self { + Self::Pq => wgpu::TextureFormat::Rgb10a2Unorm, + Self::ScRgb => wgpu::TextureFormat::Rgba16Float, + } + } + pub fn color_space(self) -> wgpu::SurfaceColorSpace { + match self { + Self::Pq => wgpu::SurfaceColorSpace::Bt2100Pq, + Self::ScRgb => wgpu::SurfaceColorSpace::ExtendedSrgbLinear, + } + } + fn space(self) -> wgpu::SurfaceColorSpaces { + match self { + Self::Pq => wgpu::SurfaceColorSpaces::BT2100_PQ, + Self::ScRgb => wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR, + } + } +} + +/// The HDR output `caps` can present: HDR10 where offered, else scRGB. +/// `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only that one. +pub fn output(caps: &wgpu::SurfaceCapabilities) -> Option { + pick(caps, std::env::var("HORIZON_HDR_OUTPUT").ok().as_deref()) +} +fn pick(caps: &wgpu::SurfaceCapabilities, only: Option<&str>) -> Option { + [(Output::Pq, "pq"), (Output::ScRgb, "scrgb")] + .into_iter() + .filter(|(_, name)| only.is_none_or(|o| o == *name)) + .map(|(output, _)| output) + .find(|o| caps.color_spaces(o.format()).contains(o.space())) } struct Targets { @@ -25,6 +58,7 @@ pub struct Hdr { layout: wgpu::BindGroupLayout, pipeline: wgpu::RenderPipeline, params: wgpu::Buffer, + pub output: Output, /// The frame's format: what every other pipeline draws in. format: wgpu::TextureFormat, targets: Option, @@ -36,7 +70,7 @@ pub struct Hdr { } impl Hdr { - pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, output: Output) -> Self { let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("Horizon HDR"), source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()), @@ -90,7 +124,7 @@ impl Hdr { entry_point: Some("fs_hdr"), compilation_options: Default::default(), targets: &[Some(wgpu::ColorTargetState { - format: FORMAT, + format: output.format(), blend: None, write_mask: wgpu::ColorWrites::ALL, })], @@ -100,7 +134,7 @@ impl Hdr { }); let params = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Horizon HDR parameters"), - size: 16, + size: 32, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); @@ -108,6 +142,7 @@ impl Hdr { layout, pipeline, params, + output, format, targets: None, debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"), @@ -198,6 +233,10 @@ impl Hdr { (self.peak / paper).max(1.0), f32::from(u8::from(world)), f32::from(u8::from(self.debug)), + f32::from(u8::from(self.output == Output::Pq)), + 0.0, + 0.0, + 0.0, ]; queue.write_buffer(&self.params, 0, bytemuck::cast_slice(¶ms)); let view = target.create_view(&Default::default()); @@ -220,3 +259,37 @@ impl Hdr { pass.draw(0..3, 0..1); } } + +#[cfg(test)] +mod tests { + use super::{Output, pick}; + use wgpu::{SurfaceColorSpaces as S, TextureFormat as F}; + + fn caps(offered: &[(F, S)]) -> wgpu::SurfaceCapabilities { + wgpu::SurfaceCapabilities { + format_capabilities: offered + .iter() + .map(|&(format, color_spaces)| wgpu::SurfaceFormatCapabilities { + format, + color_spaces, + }) + .collect(), + ..Default::default() + } + } + + #[test] + fn hdr10_first_then_scrgb() { + let both = caps(&[ + (F::Bgra8UnormSrgb, S::SRGB), + (F::Rgb10a2Unorm, S::BT2100_PQ | S::BT2100_HLG), + (F::Rgba16Float, S::EXTENDED_SRGB_LINEAR), + ]); + assert_eq!(pick(&both, None), Some(Output::Pq)); + assert_eq!(pick(&both, Some("scrgb")), Some(Output::ScRgb)); + let scrgb = caps(&[(F::Rgba16Float, S::EXTENDED_SRGB_LINEAR)]); + assert_eq!(pick(&scrgb, None), Some(Output::ScRgb)); + assert_eq!(pick(&scrgb, Some("pq")), None); + assert_eq!(pick(&caps(&[(F::Bgra8UnormSrgb, S::SRGB)]), None), None); + } +} diff --git a/crates/horizon-client/src/gizmos.rs b/crates/horizon-client/src/gizmos.rs index d4125710e..70e2b87f3 100644 --- a/crates/horizon-client/src/gizmos.rs +++ b/crates/horizon-client/src/gizmos.rs @@ -204,6 +204,19 @@ impl Gizmos { position[1] + f64::from(size.1), position[2] + half, ]; + self.entity_box(min, max, position, eye_height, living, view); + } + /// The same for an entity whose box is not centred on its position + /// (a painting or an item frame): `min` and `max` are the box. + pub fn entity_box( + &mut self, + min: [f64; 3], + max: [f64; 3], + position: [f64; 3], + eye_height: f32, + living: bool, + view: (f32, f32), + ) { self.cuboid(min, max, WHITE, STROKE_WIDTH); if living { let eye = min[1] + f64::from(eye_height); diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index 4f6f04bc0..fbf67f9ad 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -216,15 +216,19 @@ pub const INTEGRATED_LOD_DISTANCE: u32 = 128; pub fn lod_capped(info: &wgpu::AdapterInfo) -> bool { info.device_type == wgpu::DeviceType::IntegratedGpu && !info.name.starts_with("Apple") } +/// A LOD distance as far terrain uses it on this adapter. +pub fn lod_distance_capped(distance: u32, info: &wgpu::AdapterInfo) -> u32 { + let distance = distance.min(1024); + if lod_capped(info) { + distance.min(INTEGRATED_LOD_DISTANCE) + } else { + distance + } +} impl Graphics { /// `lod_distance` as far terrain uses it on this adapter. pub fn lod_distance_on(&self, info: &wgpu::AdapterInfo) -> u32 { - let distance = self.lod_distance.min(1024); - if lod_capped(info) { - distance.min(INTEGRATED_LOD_DISTANCE) - } else { - distance - } + lod_distance_capped(self.lod_distance, info) } } #[derive(Clone, Debug, PartialEq)] @@ -255,7 +259,7 @@ pub struct Graphics { pub resolution_scale: u32, /// FXAA over the world. pub fxaa: bool, - /// HDR output (scRGB), where the display path offers it. + /// HDR output (HDR10, or scRGB), where the display path offers it. pub hdr: bool, /// HDR paper white (where SDR white sits), in nits. pub hdr_paper_white: u32, diff --git a/crates/horizon-client/src/hdr.wgsl b/crates/horizon-client/src/hdr.wgsl index bf6c27cca..ec2ae118a 100644 --- a/crates/horizon-client/src/hdr.wgsl +++ b/crates/horizon-client/src/hdr.wgsl @@ -1,6 +1,6 @@ // Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma -// space, decoded to linear light at the paper white and written to the scRGB -// swapchain (1.0 = 80 nits). Bright pixels of light sources that still show the +// space, decoded to linear light at the paper white and written to the swapchain: +// HDR10 (BT.2020, PQ) or scRGB (1.0 = 80 nits). Bright pixels of light sources that still show the // world as it was before the hand and HUD are expanded towards the peak. @group(0) @binding(0) var frame: texture_2d; @group(0) @binding(1) var world: texture_2d; @@ -14,6 +14,8 @@ struct Params { world: f32, // 1 paints expanded pixels magenta (HORIZON_HDR_DEBUG=1). debug: f32, + // 1 for an HDR10 swapchain, 0 for scRGB. + pq: f32, }; @group(0) @binding(2) var params: Params; @@ -30,14 +32,28 @@ const STRENGTH: f32 = 0.7; // Whether `c` still shows the world pixel `w`: the same, or darkened evenly // across its channels, as the vignette and other screen-wide tints darken it. -// The hand, HUD and text replace pixels instead, so they never pass. +// The hand, HUD and text replace pixels instead, so they never pass. The +// channels are held to one factor, the ratio of their sums, so a channel at 0 +// stays 0; a step of 8-bit rounding is allowed on each. fn shows_world(c: vec3, w: vec3) -> bool { if all(c == w) { return true; } - let k = c / max(w, vec3(1.0 / 255.0)); - let mean = (k.r + k.g + k.b) / 3.0; - return mean <= 1.01 && mean > 0.5 && all(abs(k - vec3(mean)) < vec3(0.03)); + let f = (c.r + c.g + c.b) / max(w.r + w.g + w.b, 1.0 / 255.0); + return f <= 1.01 && f > 0.5 && all(abs(c - f * w) <= 0.03 * w + 1.0 / 255.0); +} + +// Linear BT.709 to BT.2020 (ITU-R BT.2087), columns first. +const BT709_TO_BT2020 = mat3x3( + vec3(0.6274, 0.0691, 0.0164), + vec3(0.3293, 0.9195, 0.0880), + vec3(0.0433, 0.0114, 0.8956), +); + +// SMPTE ST 2084: nits (up to 10000) to the PQ signal. +fn pq(nits: vec3) -> vec3 { + let y = pow(clamp(nits / 10000.0, vec3(0.0), vec3(1.0)), vec3(0.1593017578125)); + return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), vec3(78.84375)); } @vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { @@ -54,7 +70,10 @@ fn shows_world(c: vec3, w: vec3) -> bool { // The world's alpha is 0 on light-emitting blocks, the sun and the moon // (terrain.wgsl, the celestial pipeline): only those shine. if params.world > 0.5 && params.peak > 1.0 && w.a < 0.75 && shows_world(c, w.rgb) { - let y = 0.5 * (dot(light, vec3(0.2126, 0.7152, 0.0722)) + max(light.r, max(light.g, light.b))); + // Brightness of the world pixel, before the vignette darkens the frame + // toward its edges: a light source shines the same anywhere on screen. + let wl = pow(max(w.rgb, vec3(0.0)), vec3(2.2)); + let y = 0.5 * (dot(wl, vec3(0.2126, 0.7152, 0.0722)) + max(wl.r, max(wl.g, wl.b))); let lift = smoothstep(LIFT_START, LIFT_FULL, y); if lift > 0.0 { let top = max(light.r, max(light.g, light.b)); @@ -65,5 +84,9 @@ fn shows_world(c: vec3, w: vec3) -> bool { } } } - return vec4(light * params.paper, 1.0); + let scrgb = light * params.paper; + if params.pq > 0.5 { + return vec4(pq(BT709_TO_BT2020 * scrgb * 80.0), 1.0); + } + return vec4(scrgb, 1.0); } diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index 46821df27..4514c2bcf 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -860,6 +860,31 @@ mod tests { assert!(!third.hurt && !third.knockback); } + /// #2141: an arrow that takes the last of the player's health must kill + /// them: `LivingEntity.hurt` leaves the health at zero and `Player.die` + /// follows. + #[test] + fn an_arrow_kills_a_player_at_one_health() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let resources = crate::motion::MotionResources::load(&root, &assets).unwrap(); + let mut player = + crate::motion::PlayerMotion::new(&resources, horizon_core::geometry::Vec3::ZERO) + .unwrap(); + player.set_health(1.0, false).unwrap(); + let (health, rules) = (&resources.health, super::HealthRules::default()); + let id = health.damage.id("minecraft:arrow").unwrap(); + let hurt = player.hurt(health, rules, id, 5.0).unwrap(); + assert!(hurt, "the arrow must hurt"); + assert_eq!(player.health.health(), 0.0, "the health must be spent"); + assert!(player.health.dead_or_dying(), "the player must be dead"); + } + #[test] fn hurt_sounds_follow_damage_effects() { // DamageEffects: HURT, THORNS, DROWNING, BURNING, POKING, FREEZING. diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 2b6acda41..850093780 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -912,6 +912,8 @@ impl HudBatch { // StringDecomposer.iterateFormatted inside Font.drawInternal: // `§` codes inside a span restyle what follows and are not drawn. let text = text.resolved(); + // Language.getVisualOrder: shaped and reordered for right-to-left text. + let text = crate::bidi::visual(&text); let font = &atlas.font; let alpha = (color >> 24) as u8; let mut glyphs = Vec::new(); diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index 253bc6cc5..9873752ca 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -321,7 +321,9 @@ fn read_text(t: &Tag) -> Option { // A component's root `text` may be empty with the visible words in // `extra` (every legacy display name ViaVersion produces looks like // this), so flatten the whole component instead of reading one key. - Tag::Compound(_) => Some(crate::entity_nbt::name_text(t).plain()), + // ComponentSerialization.CODEC also takes a list (its first element + // styling the rest), as servers behind ViaVersion send book pages. + Tag::Compound(_) | Tag::List(_) => Some(crate::entity_nbt::name_text(t).plain()), _ => None, } } @@ -916,6 +918,37 @@ mod tests { ); } + #[test] + fn written_book_pages_may_be_component_lists() { + // A page as Hypixel sends it through ViaVersion: a list, not a compound. + let page = Tag::List(vec![ + Tag::compound([("text", Tag::String("".into()))]), + Tag::compound([("text", Tag::String("Please read ".into()))]), + Tag::compound([("text", Tag::String("the rules".into()))]), + ]); + let book = Tag::compound([ + ( + "title", + Tag::compound([("raw", Tag::String("Rules".into()))]), + ), + ("author", Tag::String("Server".into())), + ( + "pages", + Tag::List(vec![ + page, + Tag::compound([("raw", Tag::String("Two".into()))]), + ]), + ), + ]); + let components = Tag::compound([("minecraft:written_book_content", book)]); + let (_, extra) = decode_components(Some(&components)); + let pages = extra.and_then(|d| d.written.clone()).map(|w| w.pages); + assert_eq!( + pages, + Some(vec!["Please read the rules".to_owned(), "Two".to_owned()]) + ); + } + #[test] fn banner_layers_and_shield_base_round_trip() { let mut stack = ItemStack::new("minecraft:shield", 1); diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 8188eb712..323b1dd70 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -46,6 +46,9 @@ pub struct ItemQuad { pub foil: Foil, /// `MaterialInfo.lightEmission` (block light floor). pub light_emission: u8, + /// The quad's sprite has translucent pixels (`MaterialInfo.itemRenderType` + /// is a translucent sheet): drawn with the translucent entities. + pub translucent: bool, } /// Which glint render type a quad uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -159,7 +162,7 @@ impl ItemRenderState { let m = pose * layer.matrix; match &layer.geometry { LayerGeometry::Quads(baked) => { - submit_quads(baked, layer, self.display, m, sprites, sink); + submit_quads(renderer, baked, layer, self.display, m, sprites, sink); } LayerGeometry::Special { model, argument } => special::submit( renderer, @@ -203,6 +206,7 @@ pub fn argb(color: i32) -> u32 { /// `ItemFeatureRenderer.prepareMainSubmit` for one cuboid layer. fn submit_quads( + renderer: &ItemRenderer, baked: &BakedItemModel, layer: &LayerRender, display: DisplayContext, @@ -216,6 +220,8 @@ fn submit_quads( FoilType::Special => Foil::Special, }; let _ = display; + // Quads of one layer mostly share a sprite: look its translucency up once. + let mut last: Option<(&str, bool)> = None; for q in &baked.quads { let Some(r) = sprites .get(sprite_name(&q.material.sprite)) @@ -239,6 +245,16 @@ fn submit_quads( let pos = q.positions.map(|p| m.transform_point3(Vec3::from(p))); let uv = q.uv.map(|[u, v]| [r.u0 + (r.u1 - r.u0) * u, r.v0 + (r.v1 - r.v0) * v]); + let translucent = match last { + Some((sprite, translucent)) if sprite == q.material.sprite => translucent, + _ => { + let translucent = renderer + .sprites + .translucent(sprite_name(&q.material.sprite)); + last = Some((&q.material.sprite, translucent)); + translucent + } + }; sink.quad(ItemQuad { pos, uv, @@ -246,6 +262,7 @@ fn submit_quads( color: argb(color), foil, light_emission: q.light_emission, + translucent: translucent || q.material.force_translucent, }); } } @@ -260,6 +277,9 @@ struct FileSprites { root: PathBuf, permutations: Vec, cache: Mutex>>, + /// Sprites with a pixel that is neither fully transparent nor opaque + /// (`Transparency.hasTranslucent`), filled in as sprites load. + translucent: Mutex>, } impl SpriteLookup for FileSprites { fn mask(&self, sprite: &str) -> Option { @@ -283,6 +303,13 @@ fn argb_pixels(rgba: &[u8]) -> Vec { .collect() } impl FileSprites { + fn translucent(&self, sprite: &str) -> bool { + let known = |this: &Self| this.translucent.lock().ok()?.get(sprite).copied(); + known(self).unwrap_or_else(|| { + self.mask(sprite); + known(self).unwrap_or(false) + }) + } fn png(&self, sprite: &str, directory: &str) -> PathBuf { crate::atlas_sources::texture_path(&self.root, sprite, directory) } @@ -303,6 +330,10 @@ impl FileSprites { (w, h, pixels) } }; + let translucent = argb.iter().any(|p| matches!(p >> 24, 1..=254)); + if let Ok(mut cache) = self.translucent.lock() { + cache.insert(sprite.to_owned(), translucent); + } let alpha: Vec = argb.iter().map(|p| (p >> 24) as u8).collect(); let animation = fs::read_to_string(png.with_extension("png.mcmeta")) .ok() @@ -452,6 +483,7 @@ impl ItemRenderer { root: root.to_path_buf(), permutations, cache: Mutex::default(), + translucent: Mutex::default(), }, baked: Mutex::default(), extents: Mutex::default(), @@ -694,7 +726,12 @@ impl ItemSink for WorldSink<'_> { } else { self.light }; - let overlay = if q.foil == Foil::None { 0 } else { 7 }; + let overlay = match (q.foil, q.translucent) { + (Foil::None, true) => crate::gfx::TRANSLUCENT_ITEM_OVERLAY, + (Foil::None, false) => 0, + (_, true) => crate::gfx::TRANSLUCENT_GLINT_ITEM_OVERLAY, + (_, false) => 7, + }; for (p, uv) in q.pos.iter().zip(q.uv) { self.out.push(Vertex { normal: [0; 4], diff --git a/crates/horizon-client/src/item_render/gui.rs b/crates/horizon-client/src/item_render/gui.rs index ff25fff1d..e0c901c0e 100644 --- a/crates/horizon-client/src/item_render/gui.rs +++ b/crates/horizon-client/src/item_render/gui.rs @@ -358,6 +358,7 @@ mod tests { color, foil: Foil::None, light_emission: 0, + translucent: false, } } diff --git a/crates/horizon-client/src/item_render/special.rs b/crates/horizon-client/src/item_render/special.rs index d42378db1..dc023f756 100644 --- a/crates/horizon-client/src/item_render/special.rs +++ b/crates/horizon-client/src/item_render/special.rs @@ -119,6 +119,7 @@ fn draw( color, foil, light_emission: 0, + translucent: false, }); } for (child_name, child) in &part.children { diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index f2dcf701d..99b70e065 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -791,6 +791,16 @@ fn login_and_configure( }, }), )?; + // ServerConfigurationPacketListenerImpl.startConfiguration: links, only + // when there are any (MinecraftServer.serverLinks is empty elsewhere). + if !shared.config.server_links.is_empty() { + send( + c, + cfg::Clientbound::ServerLinks(cfg::ServerLinks { + links: shared.config.server_links.clone(), + }), + )?; + } send( c, cfg::Clientbound::UpdateEnabledFeatures(cfg::UpdateEnabledFeatures { diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 7e43cf04e..2deb5905e 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -2,7 +2,12 @@ //! player state (inventory, health, game mode) that the host's gameplay code //! operates on when it acts for them. use super::{Joined, PlayerSender, entity::Tracker}; -use crate::{items::ItemStack, motion::PlayerMotion}; +use crate::{ + items::ItemStack, + motion::PlayerMotion, + pose::{Dimensions, Pose}, +}; +use horizon_core::geometry::{Aabb, Vec3}; use horizon_protocol::{ item::Stack, packets::{configuration::ClientInformation, play}, @@ -407,8 +412,41 @@ impl Guest { } f } + /// `Player.getDesiredPose`: sleeping, gliding, then the body's own pose + /// (swimming, crawling, crouching) once its server tick has run. + pub fn pose(&self) -> Pose { + if self.sleeping { + Pose::Sleeping + } else if self.fall_flying { + Pose::FallFlying + } else if let Some(m) = &self.motion { + m.pose + } else if self.sneaking && !self.flying { + Pose::Crouching + } else { + Pose::Standing + } + } + /// `Avatar.POSES` for the guest's pose, with its scale attribute. + pub fn dimensions(&self) -> Dimensions { + let pose = self.pose(); + match &self.motion { + Some(m) if m.pose == pose => m.dimensions, + _ => pose.dimensions(1.0), + } + } + /// `Entity.getBoundingBox`. + pub fn bounds(&self) -> Aabb { + let [x, y, z] = self.position; + let d = self.dimensions(); + let half = f64::from(d.width) / 2.0; + Aabb::new( + Vec3::new(x - half, y, z - half), + Vec3::new(x + half, y + f64::from(d.height), z + half), + ) + } pub fn eye_height(&self) -> f64 { - if self.sneaking { 1.27 } else { 1.62 } + f64::from(self.dimensions().eye_height) } /// `Player.isWithinBlockInteractionRange(pos, buffer)` for the guest: /// its block interaction range is 4.5, 5 in creative. diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index f9b6e8ce7..7395cc0a4 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -2068,6 +2068,7 @@ impl Hub { | S::PlayerLoaded(_) | S::ChunkBatchReceived(_) | S::ClientInformation(_) + | S::RecipeBookChangeSettings(_) | S::ClientTickEnd(_) | S::KeepAlive(_) => false, S::MovePlayerPos(p) => self.moved_far(i, [p.x, p.y, p.z]), @@ -2134,6 +2135,15 @@ impl Hub { g.max_unacknowledged = 10; } S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, + // ServerGamePacketListenerImpl.handleRecipeBookChangeSettingsPacket. + S::RecipeBookChangeSettings(p) => { + if let Some(book) = crate::recipe_book::BookType::ALL.get(p.book_type as usize) + { + let settings = &mut self.guests[i].recipe_book; + settings.open[book.index()] = p.open; + settings.filtering[book.index()] = p.filtering; + } + } S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = @@ -2269,11 +2279,16 @@ impl Hub { packets = 1; } // shouldCheckPlayerMovement (never the single-player owner). - // The server holds no velocity for a guest (getDeltaMovement), - // so nothing is expected. if !owner && check && (!g.fall_flying || elytra_check) { let limit = if g.fall_flying { 300.0 } else { 100.0 }; - if moved > limit * f64::from(packets) { + // `movedDist - expectedDist` (getDeltaMovement): the velocity + // the server last simulated for the guest is expected + // movement, not a violation — a landing glide keeps its speed. + let expected = g.motion.as_ref().map_or(0.0, |m| { + let v = m.velocity; + v.x * v.x + v.y * v.y + v.z * v.z + }); + if moved - expected > limit * f64::from(packets) { events.push(HostEvent::Warn(format!( "{} moved too quickly! {},{},{}", g.name, @@ -2329,18 +2344,8 @@ impl Hub { } // getBoundingBox: the box of the body's pose (swimming and crawling // are 0.6 tall), so a swimmer under a ceiling isn't sent back. - let (half, height) = if g.fall_flying { - (0.3, 0.6) - } else if let Some(m) = &g.motion { - ( - f64::from(m.dimensions.width) / 2.0, - f64::from(m.dimensions.height), - ) - } else if g.sneaking { - (0.3, 1.5) - } else { - (0.3, 1.8) - }; + let d = g.dimensions(); + let (half, height) = (f64::from(d.width) / 2.0, f64::from(d.height)); let at = |p: [f64; 3]| { Aabb::new( Vec3::new(p[0] - half, p[1], p[2] - half), diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 3e9b93cac..34c465ffa 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -142,6 +142,10 @@ pub struct NetConfig { /// server.properties `resource-pack`: offered to every player during /// configuration (a dedicated server's; MinecraftServer.getServerResourcePack). pub resource_pack: Option, + /// MinecraftServer.serverLinks (a dedicated server's `bug-report-link`): + /// sent in configuration when non-empty + /// (ServerConfigurationPacketListenerImpl.startConfiguration). + pub server_links: Vec, } impl NetConfig { /// MinecraftServer.enforceSecureProfile. @@ -168,6 +172,7 @@ impl NetConfig { online: None, log: None, resource_pack: None, + server_links: Vec::new(), } } } diff --git a/crates/horizon-client/src/landing.rs b/crates/horizon-client/src/landing.rs index 6fb1f7580..629d8c042 100644 --- a/crates/horizon-client/src/landing.rs +++ b/crates/horizon-client/src/landing.rs @@ -324,10 +324,13 @@ impl BlockLandingWorld for MotionWorld<'_, '_, '_> { type DamageSource = LandingDamage; type Sound = SceneSound; fn is_server_level(&self) -> bool { - true + // A remote client's world is a client level: it never tramples, + // the server's block change and teleport do it (FarmlandBlock.fallOn + // and TurtleEggBlock.fallOn check `level instanceof ServerLevel`). + !self.player.client_side } fn is_client_side(&mut self) -> Result { - Ok(false) + Ok(self.player.client_side) } fn random_float(&mut self) -> Result { Ok(self.scene.random.next_float()) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index fa5ef1c4d..4082c0b0c 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -15,6 +15,7 @@ pub mod auto_jump; pub mod banner; pub mod beehive; pub mod benchmark; +pub mod bidi; pub mod biome; pub mod block_entities; pub mod block_entity_anim; @@ -74,6 +75,7 @@ pub mod fog; pub mod font; pub mod friends_screen; pub mod game_mode_switcher; +pub mod game_rules_screen; pub mod gamepad; pub mod gfx; pub mod gizmos; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 6cb4b65b1..c8313c3d7 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -17,7 +17,7 @@ use crate::fast_hash::FxHashMap; use crate::{ blocks::BlockFacts, - chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, index}, + chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, Section, index}, }; use horizon_core::geometry::{Direction, ShapeOp, VoxelShape}; use horizon_world::registry::{BlockRegistry, BlockStateId}; @@ -565,43 +565,130 @@ pub fn update_light_layers>( /// Resident chunks the incremental relighter reads and writes. pub trait LightWorld { - fn state(&self, x: i32, y: i32, z: i32) -> Option; - /// Packed light (sky << 4 | block), None outside loaded chunks. - fn light(&self, x: i32, y: i32, z: i32) -> Option; - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8); + /// Section `s` of chunk (cx, cz), None unless the chunk is loaded and lit. + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc
>; + /// Replace the light of a section `section` returned. + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: Light); } impl LightWorld for HashMap<(i32, i32), Arc, S> { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + fn section(&self, cx: i32, s: usize, cz: i32) -> Option<&Arc
> { + self.get(&(cx, cz)) + .filter(|c| c.lit) + .map(|c| &c.sections[s]) + } + fn set_section_light(&mut self, cx: i32, s: usize, cz: i32, light: Light) { + if let Some(chunk) = self.get_mut(&(cx, cz)) { + Arc::make_mut(&mut Arc::make_mut(chunk).sections[s]).light = light; + } + } +} +/// The sections one relight touches, held for the whole flood fill so each +/// cell access is an array index instead of a chunk lookup. Light a section +/// gets written is copied out on the first write and stored back by `finish`. +struct Region<'w> { + world: &'w mut dyn LightWorld, + slots: Vec, + /// Section key (cx, s, cz) to slot, `NONE` where the chunk isn't lit. + index: FxHashMap, + last: (Pos, u32), +} +struct Slot { + key: Pos, + /// The world's section; its light is the value before this relight. + section: Arc
, + light: Option>, +} +const NONE: u32 = u32::MAX; +impl<'w> Region<'w> { + fn new(world: &'w mut dyn LightWorld) -> Self { + Self { + world, + slots: Vec::new(), + index: FxHashMap::default(), + last: ((i32::MIN, 0, 0), NONE), + } + } + #[inline] + fn slot(&mut self, x: i32, y: i32, z: i32) -> Option { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } - self.get(&(x >> 4, z >> 4)) - .filter(|c| c.lit) - .map(|c| c.get(x & 15, y, z & 15)) - } - fn light(&self, x: i32, y: i32, z: i32) -> Option { - if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { - return None; + let key = (x >> 4, (y - MIN_Y) >> 4, z >> 4); + if self.last.0 != key { + self.last = (key, self.load(key)); } - self.get(&(x >> 4, z >> 4)) - .filter(|c| c.lit) - .map(|c| c.light(x & 15, y, z & 15)) + (self.last.1 != NONE).then_some(self.last.1 as usize) } - fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8) { - let Some(chunk) = self.get_mut(&(x >> 4, z >> 4)) else { + fn load(&mut self, key: Pos) -> u32 { + if let Some(&slot) = self.index.get(&key) { + return slot; + } + let slot = match self.world.section(key.0, key.1 as usize, key.2) { + Some(section) => { + self.slots.push(Slot { + key, + section: section.clone(), + light: None, + }); + (self.slots.len() - 1) as u32 + } + None => NONE, + }; + self.index.insert(key, slot); + slot + } + fn state(&mut self, x: i32, y: i32, z: i32) -> Option { + let slot = self.slot(x, y, z)?; + Some(self.slots[slot].section.get(index(x, y, z))) + } + /// Packed light (sky << 4 | block), None outside loaded, lit chunks. + fn light(&mut self, x: i32, y: i32, z: i32) -> Option { + let slot = self.slot(x, y, z)?; + let slot = &self.slots[slot]; + let i = index(x, y, z); + Some(match &slot.light { + Some(light) => light[i], + None => slot.section.light(i), + }) + } + /// State and packed light of a cell, with a single section lookup. + fn cell(&mut self, x: i32, y: i32, z: i32) -> Option<(u32, u8)> { + let slot = self.slot(x, y, z)?; + let slot = &self.slots[slot]; + let i = index(x, y, z); + let light = match &slot.light { + Some(light) => light[i], + None => slot.section.light(i), + }; + Some((slot.section.get(i), light)) + } + /// Rewrite a cell's packed light; nothing outside loaded, lit chunks. + fn update_light(&mut self, x: i32, y: i32, z: i32, f: impl FnOnce(u8) -> u8) { + let Some(slot) = self.slot(x, y, z) else { return; }; - let s = ((y - MIN_Y) >> 4) as usize; + let slot = &mut self.slots[slot]; + let light = slot.light.get_or_insert_with(|| match &slot.section.light { + Light::Uniform(v) => Box::new([*v; 4096]), + Light::Full(a) => a.clone(), + }); let i = index(x, y, z); - if chunk.sections[s].light(i) == packed { - return; - } - let section = Arc::make_mut(&mut Arc::make_mut(chunk).sections[s]); - if let Light::Uniform(v) = section.light { - section.light = Light::Full(Box::new([v; 4096])); - } - if let Light::Full(a) = &mut section.light { - a[i] = packed; + light[i] = f(light[i]); + } + /// Store back the light of every section whose values changed. + fn finish(self) { + for slot in self.slots { + let Some(light) = slot.light else { + continue; + }; + if (0..4096).all(|i| slot.section.light(i) == light[i]) { + continue; + } + // Drop the clone first so the world's section isn't copied. + drop(slot.section); + let (cx, s, cz) = slot.key; + self.world + .set_section_light(cx, s as usize, cz, Light::Full(light)); } } } @@ -690,25 +777,23 @@ impl LightChanges { } } } -fn level(world: &impl LightWorld, sky: bool, p: Pos) -> Option { +fn level(world: &mut Region, sky: bool, p: Pos) -> Option { world .light(p.0, p.1, p.2) .map(|v| if sky { v >> 4 } else { v & 15 }) } -fn set_level(world: &mut impl LightWorld, sky: bool, p: Pos, value: u8) { - let Some(old) = world.light(p.0, p.1, p.2) else { - return; - }; - let packed = if sky { - (old & 0x0F) | value << 4 - } else { - (old & 0xF0) | value - }; - world.set_light(p.0, p.1, p.2, packed); +fn set_level(world: &mut Region, sky: bool, p: Pos, value: u8) { + world.update_light(p.0, p.1, p.2, |old| { + if sky { + (old & 0x0F) | value << 4 + } else { + (old & 0xF0) | value + } + }); } /// `ChunkSkyLightSources`: the Y of the upper block of the highest occluded /// edge in the column (every block at or above it is a sky source). -pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, z: i32) -> i32 { +fn lowest_sky_source(world: &mut Region, tables: &LightTables, x: i32, z: i32) -> i32 { let mut y = MIN_Y + HEIGHT - 1; let Some(mut top) = world.state(x, y, z) else { return MIN_Y; @@ -739,34 +824,52 @@ pub fn relight( force: bool, changed: &mut LightChanges, ) { - relight_layer(world, tables, false, positions.to_vec(), force, changed); + let mut region = Region::new(world); + relight_region(&mut region, tables, sky_light, positions, force, changed); + region.finish(); +} +fn relight_region( + world: &mut Region, + tables: &LightTables, + sky_light: bool, + positions: &[Pos], + force: bool, + changed: &mut LightChanges, +) { + crate::spans::time("lt_block", || { + relight_layer(world, tables, false, positions.to_vec(), force, changed) + }); if sky_light { let mut seeds = positions.to_vec(); - let mut columns: HashMap<(i32, i32), i32> = HashMap::new(); - for &(x, _, z) in positions { - if columns.contains_key(&(x, z)) { - continue; - } - let source = lowest_sky_source(world, tables, x, z); - columns.insert((x, z), source); - // Cells whose source status changed: non-15 at or above the new - // lowest source, and old 15s (sources) below it. - for y in source..MIN_Y + HEIGHT { - if level(world, true, (x, y, z)).is_some_and(|l| l != 15) { + let mut columns: FxHashMap<(i32, i32), i32> = FxHashMap::default(); + crate::spans::time("lt_columns", || { + for &(x, _, z) in positions { + if columns.contains_key(&(x, z)) { + continue; + } + let source = lowest_sky_source(world, tables, x, z); + columns.insert((x, z), source); + // Cells whose source status changed: non-15 at or above the new + // lowest source, and old 15s (sources) below it. + for y in source..MIN_Y + HEIGHT { + if level(world, true, (x, y, z)).is_some_and(|l| l != 15) { + seeds.push((x, y, z)); + } + } + let mut y = source - 1; + while y >= MIN_Y && level(world, true, (x, y, z)) == Some(15) { seeds.push((x, y, z)); + y -= 1; } } - let mut y = source - 1; - while y >= MIN_Y && level(world, true, (x, y, z)) == Some(15) { - seeds.push((x, y, z)); - y -= 1; - } - } - relight_layer(world, tables, true, seeds, force, changed); + }); + crate::spans::time("lt_sky", || { + relight_layer(world, tables, true, seeds, force, changed) + }); } } fn relight_layer( - world: &mut impl LightWorld, + world: &mut Region, tables: &LightTables, sky: bool, seeds: Vec, @@ -809,42 +912,40 @@ fn relight_layer( } } // Sources inside the cleared area light up again. - let mut sources: HashMap<(i32, i32), i32> = HashMap::new(); - for p in cleared { - let seed = if sky { - let lowest = *sources - .entry((p.0, p.2)) - .or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); - if p.1 >= lowest { 15 } else { 0 } - } else { - world - .state(p.0, p.1, p.2) - .map_or(0, |s| tables.cells[s as usize].emission) - }; - if seed > level(world, sky, p).unwrap_or(15) { - set_level(world, sky, p, seed); - changed.push(p); - increase.push_back(p); + let mut sources: FxHashMap<(i32, i32), i32> = FxHashMap::default(); + crate::spans::time("lt_sources", || { + for p in cleared { + let seed = if sky { + let lowest = *sources + .entry((p.0, p.2)) + .or_insert_with(|| lowest_sky_source(world, tables, p.0, p.2)); + if p.1 >= lowest { 15 } else { 0 } + } else { + world + .state(p.0, p.1, p.2) + .map_or(0, |s| tables.cells[s as usize].emission) + }; + if seed > level(world, sky, p).unwrap_or(15) { + set_level(world, sky, p, seed); + changed.push(p); + increase.push_back(p); + } } - } + }); while let Some(p) = increase.pop_front() { - let Some(l) = level(world, sky, p) else { + let Some((from, packed)) = world.cell(p.0, p.1, p.2) else { continue; }; + let l = if sky { packed >> 4 } else { packed & 15 }; if l <= 1 { continue; } - let Some(from) = world.state(p.0, p.1, p.2) else { - continue; - }; for (d, (ox, oy, oz)) in OFFSETS.iter().enumerate() { let q = (p.0 + ox, p.1 + oy, p.2 + oz); - let Some(to) = world.state(q.0, q.1, q.2) else { - continue; - }; - let Some(ql) = level(world, sky, q) else { + let Some((to, packed)) = world.cell(q.0, q.1, q.2) else { continue; }; + let ql = if sky { packed >> 4 } else { packed & 15 }; let next = l.saturating_sub(tables.cells[to as usize].dampening.max(1)); if next > ql && !tables.blocked(from as usize, to as usize, d) { set_level(world, sky, q, next); @@ -915,10 +1016,10 @@ mod tests { lit.into_iter().collect() } fn sky(world: &HashMap<(i32, i32), Arc>, x: i32, y: i32, z: i32) -> u8 { - world.light(x, y, z).unwrap() >> 4 + world[&(x >> 4, z >> 4)].light(x & 15, y, z & 15) >> 4 } fn block(world: &HashMap<(i32, i32), Arc>, x: i32, y: i32, z: i32) -> u8 { - world.light(x, y, z).unwrap() & 15 + world[&(x >> 4, z >> 4)].light(x & 15, y, z & 15) & 15 } #[test] @@ -954,6 +1055,108 @@ mod tests { assert_eq!(sky(&w, 8, 2, 8), 0, "the full bottom face stops sky light"); } #[test] + fn relight_keeps_unchanged_and_unlit_sections() { + let mut w = world(|_| {}); + Arc::make_mut(w.get_mut(&(1, 0)).unwrap()).lit = false; + let before = w.clone(); + let same = |w: &HashMap<(i32, i32), Arc>, key| { + w[&key] + .sections + .iter() + .zip(&before[&key].sections) + .all(|(a, b)| Arc::ptr_eq(a, b)) + }; + // Cleared and lit back to the same values: nothing is stored. + relight( + &mut w, + &tables(), + true, + &[(8, 5, 8)], + false, + &mut LightChanges::default(), + ); + assert!(w.keys().all(|&key| same(&w, key))); + // Light reaching an unlit chunk isn't written into it. + Arc::make_mut(w.get_mut(&(0, 0)).unwrap()).set(15, 0, 8, TORCH); + relight( + &mut w, + &tables(), + true, + &[(15, 0, 8)], + false, + &mut LightChanges::default(), + ); + assert!(same(&w, (1, 0))); + assert_eq!(block(&w, 14, 0, 8), 13); + } + #[test] + fn random_border_relights_match_full_relight() { + // Edits around every border of chunk (0, 0), at the top and bottom of + // the world, in batches; a held clone of the chunk must not change. + let mut w = world(|_| {}); + let held = w[&(0, 0)].clone(); + let mut rng = 0x9e37_79b9_u32; + let mut next = |n: usize| { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + rng as usize % n + }; + let xz = [-2, -1, 0, 1, 7, 14, 15, 16, 17]; + let ys = [ + MIN_Y, + MIN_Y + 1, + -2, + -1, + 0, + 1, + 15, + 16, + MIN_Y + HEIGHT - 2, + MIN_Y + HEIGHT - 1, + ]; + for _ in 0..60 { + let positions: Vec = (0..1 + next(6)) + .map(|_| (xz[next(xz.len())], ys[next(ys.len())], xz[next(xz.len())])) + .collect(); + for &(x, y, z) in &positions { + let state = [TORCH, SLAB, AIR, STONE][next(4)]; + Arc::make_mut(w.get_mut(&(x >> 4, z >> 4)).unwrap()).set(x & 15, y, z & 15, state); + } + relight( + &mut w, + &tables(), + true, + &positions, + false, + &mut LightChanges::default(), + ); + } + // Every chunk, the outer ring lit as `world` lit it (no neighbours + // past the 3x3). + for (&(cx, cz), chunk) in &w { + let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { + std::array::from_fn(|dx| { + w.get(&(cx + dx as i32 - 1, cz + dz as i32 - 1)) + .map(|c| &**c) + }) + }); + for (si, s) in light_chunk(®ion, &tables(), true).iter().enumerate() { + for i in 0..4096 { + assert_eq!( + s.get(i), + chunk.sections[si].light(i), + "chunk {cx},{cz} section {si} index {i}" + ); + } + } + } + let fresh = world(|_| {}); + for (a, b) in held.sections.iter().zip(&fresh[&(0, 0)].sections) { + assert!((0..4096).all(|i| a.light(i) == b.light(i))); + } + } + #[test] fn incremental_relight_matches_full_relight() { let mut w = world(|c| { c.set(8, 0, 8, TORCH); @@ -1319,4 +1522,37 @@ mod tests { "fixture heap payload {payload} bytes; old worker clones it plus 24 section Arcs; old application clones current payload and 98304 returned light bytes. New worker clones zero section payload; new application clones current payload only when shared." ); } + /// Relight cost for torches placed and removed near chunk borders with + /// slabs flickering around them (fluids next to lava, in the game). + /// `cargo test --profile fast -p horizon-client relight_bench -- --ignored --nocapture` + #[test] + #[ignore] + fn relight_bench() { + let mut w: FxHashMap<_, _> = world(|_| {}).into_iter().collect(); + let t = tables(); + let mut rng = 0x2545_f491_u32; + let mut next = |n: i32| { + rng ^= rng << 13; + rng ^= rng >> 17; + rng ^= rng << 5; + (rng % n as u32) as i32 + }; + let start = std::time::Instant::now(); + let mut changed = LightChanges::default(); + for round in 0..400 { + let state = [TORCH, SLAB, AIR][round % 3]; + let positions: Vec = (0..32) + .map(|_| (next(32) - 8, next(12), next(32) - 8)) + .collect(); + for &(x, y, z) in &positions { + Arc::make_mut(w.get_mut(&(x >> 4, z >> 4)).unwrap()).set(x & 15, y, z & 15, state); + } + relight(&mut w, &t, true, &positions, false, &mut changed); + } + println!( + "relight_bench: {:?}, {} sections", + start.elapsed(), + changed.sections().count() + ); + } } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 3b2b8fd31..da24eb176 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3211,4 +3211,64 @@ pub(crate) mod tests { assert_eq!(menu.slot(0), stack("dirt", 1).as_ref()); }); } + + /// #1737: a Shift+Right-Click quick move in a chest (a double chest's + /// 54 slots) moves the stack and leaves the menu's state clean, so the + /// next quick move still moves its stack and the inventory still + /// answers. + #[test] + fn a_chest_quick_move_keeps_the_next_one_working() { + with_menu(Kind::Chest(6), |env, menu| { + menu.creative = false; + // The hotbar holds two stacks; the chest is empty. + menu.set_slot(env, 81, stack("cobblestone", 64)); + menu.set_slot(env, 82, stack("dirt", 32)); + // Shift+Right-Click on the hotbar: the stack goes into the chest. + menu.click(env, 81, 1, Input::QuickMove).unwrap(); + assert_eq!(menu.slot(81), None); + assert_eq!(menu.slot(0).map(|s| s.count), Some(64)); + // Nothing is left on the cursor and no quick craft is running. + assert_eq!(menu.carried, None); + assert_eq!(menu.quick_status, 0); + // The next quick move still works. + menu.click(env, 82, 1, Input::QuickMove).unwrap(); + assert_eq!(menu.slot(82), None); + assert_eq!(menu.slot(1).map(|s| s.count), Some(32)); + assert_eq!(menu.carried, None); + assert_eq!(menu.quick_status, 0); + }); + } + + /// #1832: a potion taken from the creative inventory and put in the + /// hotbar keeps its `PotionContents` (the brew), as vanilla's + /// `PotionContents.createItemStack` builds it: the item tab's stack is + /// the real one, and the hotbar slot holds it as it is. + #[test] + fn a_creative_potion_keeps_its_contents_in_the_hotbar() { + let snbt = r#"{components:{"minecraft:potion_contents":{potion:"minecraft:swiftness"}},count:1,id:"minecraft:potion"}"#; + let potion = crate::item_data::parse_stack(snbt).unwrap().unwrap(); + assert_eq!(potion.potion(), Some("minecraft:swiftness")); + // The creative screen hands the stack over... + let mut carried = None; + crate::creative::click_display( + &mut carried, + Some(&potion), + |_: &ItemStack| 1, + 0, + Input::Pickup, + ); + assert_eq!( + carried.as_ref().and_then(|s| s.potion()), + Some("minecraft:swiftness") + ); + // ... and the hotbar slot keeps it: it is not the uncraftable + // potion, which is a `minecraft:potion` with no contents at all. + with_menu(Kind::ItemPicker, |env, menu| { + menu.carried = carried; + menu.click(env, 45, 0, Input::Pickup).unwrap(); + let in_hand = menu.slot(45).expect("the hotbar slot"); + assert_eq!(in_hand.potion(), Some("minecraft:swiftness")); + assert_eq!(&*in_hand.item, "minecraft:potion"); + }); + } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 2325c3f5b..50ce01f9f 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -527,6 +527,8 @@ pub enum DamageKind { InWall, Thorns, SonicBoom, + /// `freeze`: a fully frozen mob in powder snow. + Freeze, /// `fell_out_of_world`: below the world's floor. OutOfWorld, } @@ -596,6 +598,7 @@ impl Damage { | DamageKind::InWall | DamageKind::Generic | DamageKind::SonicBoom + | DamageKind::Freeze | DamageKind::OutOfWorld ) } @@ -620,6 +623,7 @@ impl Damage { | DamageKind::Cactus | DamageKind::Generic | DamageKind::InWall + | DamageKind::Freeze | DamageKind::OutOfWorld ) } @@ -646,6 +650,9 @@ pub struct Attrs { pub struct Extra { /// Players: crouching and riding (HumanoidModel's poses). pub crouching: bool, + /// A player's or mannequin's synced pose (`Entity.DATA_POSE`), which + /// sets its box (`Avatar.POSES`). + pub avatar_pose: crate::pose::Pose, /// Players: sprinting (`Entity.DATA_SHARED_FLAGS_ID`), for the dust they raise. pub sprinting: bool, pub passenger: bool, @@ -781,8 +788,9 @@ pub struct Extra { pub drop_chances: Option>, /// `Mob.leftHanded`. pub left_handed: bool, - /// The sound variant: index in the species' `*_sound_variant` registry. - pub sound_variant: u8, + /// The sound variant: index in the species' `*_sound_variant` registry + /// (`finalize::sound_variants`); None is the default, `classic`. + pub sound_variant: Option, /// `Zombie.canBreakDoors`. pub can_break_doors: bool, /// A goat's `IsScreamingGoat` and the horns it lost (left, right). @@ -903,6 +911,12 @@ pub enum MobEvent { mob: u32, at: [f64; 3], }, + /// `LivingEntity.baseTick`'s drowning damage: entity event 67, the + /// clients' `makeDrownParticles`. + Drown { + mob: u32, + at: [f64; 3], + }, Sound(&'static str, [f64; 3], f32, f32), /// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the /// chest's opener count goes up or down (interaction range 3). @@ -983,6 +997,12 @@ pub enum MobEvent { target: Who, velocity: [f64; 3], }, + /// `Entity.move(MoverType.SHULKER, delta)`: shift a target's position + /// (an opening shulker lifts what stands on its shell). + Shift { + target: Who, + delta: [f64; 3], + }, /// `EvokerWololoSpellGoal`: a blue sheep turns red. Wololo { mob: u32, @@ -1348,6 +1368,10 @@ impl Mob { .max((f64::from(ticks) * self.burning_time()).ceil() as i32); self.ticks_frozen = 0; } + /// `Entity.isFullyFrozen`. + pub fn is_fully_frozen(&self) -> bool { + self.ticks_frozen >= crate::motion::PlayerMotion::TICKS_REQUIRED_TO_FREEZE + } /// What other mobs see of this one this tick (`player`: the player's /// UUID, which villagers' reputation is keyed by). @@ -1826,6 +1850,15 @@ impl Mob { { amount *= 0.75; } + // LivingEntity.hurtServer: `#freeze_hurts_extra_types` take five times. + if source.kind == DamageKind::Freeze + && matches!( + self.species(), + Species::Strider | Species::Blaze | Species::MagmaCube + ) + { + amount *= 5.0; + } let (worn, worn_toughness) = self.worn_armor(); if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { // CombatRules.getDamageAfterAbsorb @@ -1999,8 +2032,18 @@ impl Mob { } /// LivingEntity.getVoicePitch. pub fn voice_pitch(&mut self) -> f32 { + // HappyGhast.getVoicePitch: always 1.0, babies and all. + if self.species() == Species::HappyGhast { + return 1.0; + } + // ZombieVillager.getVoicePitch: babies are 2.0, not 1.5. + let baby = if self.species() == Species::ZombieVillager { + 2.0 + } else { + 1.5 + }; let pitch = (self.random.next_float() - self.random.next_float()) * 0.2 - + if self.is_baby() { 1.5 } else { 1.0 }; + + if self.is_baby() { baby } else { 1.0 }; // Bat.getVoicePitch: a little lower. if self.species() == Species::Bat { pitch * 0.95 diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 26b94eeac..9adf93a8f 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -188,6 +188,20 @@ pub fn register(m: &mut Mob) { if m.species() == Species::Turtle { super::turtle::register(m); } + if m.species() == Species::Frog { + // `Frog()`: SmoothSwimmingMoveControl(85, 10, 0.02, 0.1, true). + // The frog's movement speed is 1.0, so the controller's 0.1 + // outside-water speed is what keeps a walking frog at + // vanilla's pace; the plain ground controller walks ten + // times too fast (#2213). + m.ai.mov.kind = super::control::MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + }; + } } Family::Inert => {} Family::Witch => super::witch::register(m), @@ -448,6 +462,16 @@ pub fn tick_swing(m: &mut Mob) { } m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; } +/// `Entity.isInRain`: rain at the block position, or at the top of the box. +pub(super) fn in_rain(m: &Mob, w: &MobWorld) -> bool { + let (x, y, z) = ( + m.position.x.floor() as i32, + m.position.y.floor() as i32, + m.position.z.floor() as i32, + ); + let top = (m.position.y + f64::from(m.height())).floor() as i32; + w.raining_at(x, y, z) || w.raining_at(x, top, z) +} /// `LivingEntity.baseTick` refills a breather's air by 4, then /// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills /// it, anywhere else it runs down from the pre-tick value, and at -20 the @@ -458,15 +482,7 @@ fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) { if m.no_ai { return; } - // Entity.isInRain: rain at the block, or at the top of the box. - let (x, y, z) = ( - m.position.x.floor() as i32, - m.position.y.floor() as i32, - m.position.z.floor() as i32, - ); - let top = (m.position.y + f64::from(m.height())).floor() as i32; - let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z); - if m.fluids.in_water || in_rain { + if m.fluids.in_water || in_rain(m, w) { m.air = super::axolotl::MAX_AIR; } else { m.air = before - 1; @@ -494,8 +510,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { ); m.damage(fire, Damage::of(DamageKind::InFire)); } - // Fire: water extinguishes, lava ignites, burning hurts every second. - if m.fluids.in_water && m.fire_ticks > 0 { + // Fire: water or rain (Entity.isInRain) extinguishes, lava ignites, + // burning hurts every second. + if m.fire_ticks > 0 && (m.fluids.in_water || in_rain(m, w)) { m.fire_ticks = 0; events.push(MobEvent::Sound( "entity.generic.extinguish_fire", @@ -524,14 +541,19 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } m.first_tick = false; if m.alive() { - // LivingEntity.baseTick: suffocation inside full blocks. + // LivingEntity.baseTick: suffocation inside full blocks. Entity.isInWall + // is false under noPhysics, which Vex.tick holds while it ticks. let (ex, ey, ez) = ( m.position.x.floor() as i32, m.eye_y().floor() as i32, m.position.z.floor() as i32, ); let at_eye = w.facts.get(w.world.block(ex, ey, ez)); - if at_eye.full_collision && at_eye.solid_render && m.width() < 1.0 { + if at_eye.full_collision + && at_eye.solid_render + && m.width() < 1.0 + && m.species() != Species::Vex + { m.damage(1.0, Damage::of(DamageKind::InWall)); } // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). @@ -551,17 +573,20 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.air -= 1; if m.air == -20 { m.air = 0; + events.push(MobEvent::Drown { + mob: m.id, + at: [m.position.x, m.position.y, m.position.z], + }); m.damage(2.0, Damage::of(DamageKind::Drown)); } } else if m.air < 300 { m.air = (m.air + 4).min(300); } - if m.kind.flags.water_sensitive - && (m.fluids.in_water || w.raining && w.can_see_sky(ex, ey, ez)) - { + if m.kind.flags.water_sensitive && (m.fluids.in_water || in_rain(m, w)) { m.damage(1.0, Damage::of(DamageKind::Drown)); } + freeze_tick(m, w); } tick_effects(m); if m.species() == Species::Illusioner { @@ -591,6 +616,57 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { // Entity.baseTick ends with Leashable.tickLeash. super::leash::tick(m, w, events); } +/// `LivingEntity.aiStep`'s "freezing" with `InsideBlockEffectType.FREEZE`: +/// powder snow builds `ticks_frozen` up, anywhere else it melts twice as +/// fast, and a fully frozen mob takes one freeze damage every 40 ticks. +fn freeze_tick(m: &mut Mob, w: &MobWorld) { + let in_snow = in_powder_snow(m, w); + if !in_snow && m.ticks_frozen == 0 { + return; + } + let can_freeze = can_freeze(m, w); + if in_snow && can_freeze { + m.ticks_frozen = + (m.ticks_frozen + 1).min(crate::motion::PlayerMotion::TICKS_REQUIRED_TO_FREEZE); + } else { + m.ticks_frozen = (m.ticks_frozen - 2).max(0); + } + if m.age.is_multiple_of(40) && m.is_fully_frozen() && can_freeze { + m.damage(1.0, Damage::of(DamageKind::Freeze)); + } +} +/// Whether the mob's box (shrunk by `1.0E-5`, as in `Entity.checkInsideBlocks`) +/// touches powder snow. +fn in_powder_snow(m: &Mob, w: &MobWorld) -> bool { + let b = m.bounds().deflate(Vec3::new(1e-5, 1e-5, 1e-5)); + let (min, max) = (b.min_position(), b.max_position()); + for x in min.x.floor() as i32..=max.x.floor() as i32 { + for y in min.y.floor() as i32..=max.y.floor() as i32 { + for z in min.z.floor() as i32..=max.z.floor() as i32 { + if &*w.facts.get(w.world.block(x, y, z)).name == "minecraft:powder_snow" { + return true; + } + } + } + } + false +} +/// `LivingEntity.canFreeze`: not a `#freeze_immune_entity_types` mob and no +/// worn piece in `#freeze_immune_wearables`. +fn can_freeze(m: &Mob, w: &MobWorld) -> bool { + if w.data + .entity_has("minecraft:freeze_immune_entity_types", &m.kind.id) + { + return false; + } + let immune = w + .items + .and_then(|i| i.item_tags.get("minecraft:freeze_immune_wearables")); + ![&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] + .into_iter() + .flatten() + .any(|item| immune.is_some_and(|t| t.contains(&**item))) +} /// `Mob.playAmbientSound` on demand: a spawn egg or a mob bucket just placed `m`. pub fn ambient_sound(m: &mut Mob, w: &MobWorld, events: &mut Vec) { play_ambient(m, w, events); @@ -895,7 +971,7 @@ fn sun_burn_tick(m: &mut Mob, w: &MobWorld) -> bool { m.position.z.floor() as i32, ); let br = w.brightness(x, y, z); - let wet = m.fluids.in_water || w.raining && w.can_see_sky(x, y, z); + let wet = m.fluids.in_water || in_rain(m, w); br > 0.5 && m.random.next_float() * 30.0 < (br - 0.4) * 2.0 && !wet && w.can_see_sky(x, y, z) } /// Mob.serverAiStep @@ -1682,8 +1758,20 @@ pub fn step_sound( S::Husk => quiet("entity.husk.step"), S::Drowned => quiet("entity.drowned.step"), S::ZombieVillager => quiet("entity.zombie_villager.step"), - S::CamelHusk => Some(("entity.camel_husk.step", 0.4, 1.0)), - S::Camel => Some(("entity.camel.step", 1.0, 1.0)), + // Camel.playStepSound and CamelHusk.playStepSound: sand and concrete + // powder have their own step. + S::CamelHusk | S::Camel => { + let sand = w.has_tag( + "minecraft:camel_sand_step_sound_blocks", + &w.facts.get(state).name, + ); + Some(match (m.species(), sand) { + (S::Camel, true) => ("entity.camel.step_sand", 1.0, 1.0), + (S::Camel, false) => ("entity.camel.step", 1.0, 1.0), + (_, true) => ("entity.camel_husk.step_sand", 0.4, 1.0), + (_, false) => ("entity.camel_husk.step", 0.4, 1.0), + }) + } S::IronGolem => Some(("entity.iron_golem.step", 1.0, 1.0)), // CopperGolem.playStepSound: its oxidation level's step. S::CopperGolem => Some((super::copper_golem::sound(m, "step"), 1.0, 1.0)), @@ -1762,3 +1850,41 @@ mod despawn_tests { } } } + +#[cfg(test)] +mod frog_tests { + use super::*; + use crate::mobs::MobTypes; + use crate::mobs::control::MoveKind; + use std::sync::Arc; + + /// `Frog()`: `new SmoothSwimmingMoveControl<>(this, 85, 10, 0.02F, 0.1F, true)`. + /// The frog's movement speed is 1.0, so the controller's 0.1 outside-water + /// speed is what keeps a walking frog at vanilla's pace. The plain ground + /// controller walks it ten times too fast, which is the jitter, the + /// teleporting and the flying of #2213. + #[test] + fn a_frog_walks_at_the_vanilla_speed() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("entity-types.json").exists() { + return; + } + let data = MobTypes::load(&root).unwrap(); + let kind = Arc::new(data.types.get("minecraft:frog").unwrap().clone()); + assert_eq!(kind.speed, 1.0, "the frog's movement speed attribute"); + let mut m = Mob::new(1, kind, Vec3::new(0.0, 4.0, 0.0), 0.0); + register(&mut m); + assert_eq!( + m.ai.mov.kind, + MoveKind::SmoothSwimming { + max_turn_x: 85.0, + max_turn_y: 10.0, + in_water: 0.02, + outside: 0.1, + gravity: true, + } + ); + } +} diff --git a/crates/horizon-client/src/mobs/aquatic.rs b/crates/horizon-client/src/mobs/aquatic.rs index f63a42239..59a73c605 100644 --- a/crates/horizon-client/src/mobs/aquatic.rs +++ b/crates/horizon-client/src/mobs/aquatic.rs @@ -259,7 +259,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } S::Dolphin => { // Dolphin.tick: moisture out of water, hop on land. - if m.fluids.in_water || w.raining { + if m.fluids.in_water || super::ai::in_rain(m, w) { m.extra.counter = 2400; } else { m.extra.counter -= 1; diff --git a/crates/horizon-client/src/mobs/body_anim.rs b/crates/horizon-client/src/mobs/body_anim.rs index 0e88fafb2..360e1447f 100644 --- a/crates/horizon-client/src/mobs/body_anim.rs +++ b/crates/horizon-client/src/mobs/body_anim.rs @@ -980,9 +980,10 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool { Species::Parrot => { let flap = m.anim.flap_o + (m.anim.flap - m.anim.flap_o) * s.partial; let speed = m.anim.flap_speed_o + (m.anim.flap_speed - m.anim.flap_speed_o) * s.partial; + // `Parrot.isFlying` is `!onGround`, in water too. let pose = if m.extra.sitting { ParrotPose::Sitting - } else if !m.on_ground && !m.fluids.in_water { + } else if !m.on_ground { ParrotPose::Flying } else { ParrotPose::Standing diff --git a/crates/horizon-client/src/mobs/control.rs b/crates/horizon-client/src/mobs/control.rs index 3df557362..bd17d7b5f 100644 --- a/crates/horizon-client/src/mobs/control.rs +++ b/crates/horizon-client/src/mobs/control.rs @@ -1,12 +1,12 @@ //! Mob controls: `MoveControl` (with the flying and smooth-swimming //! variants), `LookControl`, `JumpControl` and `BodyRotationControl`. -use super::{Mob, MobWorld, living::wrap}; +use super::{Mob, MobWorld, Species, living::wrap}; use horizon_core::geometry::trig; /// `2.5000003E-7F` widened: the squared distance controls treat as arrived. const ARRIVED: f64 = 2.500_000_3e-7_f32 as f64; /// `1.0E-5F` widened. -const EPSILON: f64 = 1.0e-5_f32 as f64; +pub(super) const EPSILON: f64 = 1.0e-5_f32 as f64; #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum Operation { @@ -90,6 +90,9 @@ pub enum LookKind { Fixed, /// `HappyGhast.HappyGhastLookControl`. HappyGhast, + /// `Shulker.ShulkerLookControl`: the yaw turns in the attach face's + /// plane and the head is never clamped to the body. + Shulker, } #[derive(Clone, Debug, Default)] pub struct LookControl { @@ -113,8 +116,16 @@ pub struct BodyRotation { last_stable_head: f32, } impl Mob { + /// `Mob.getMaxHeadXRot`, with `Wolf`'s 20 degrees while sitting. + pub fn max_head_x_rot(&self) -> f32 { + if self.species() == Species::Wolf && self.extra.sitting { + 20.0 + } else { + self.kind.max_head_x_rot + } + } pub fn look_at(&mut self, at: [f64; 3]) { - let (y, x) = (self.kind.head_rot_speed, self.kind.max_head_x_rot); + let (y, x) = (self.kind.head_rot_speed, self.max_head_x_rot()); self.ai.look.set_look_at(at, y, x); } pub fn look_at_speed(&mut self, at: [f64; 3], y_speed: f32, x_max: f32) { @@ -135,6 +146,9 @@ impl Mob { if self.species() == super::Species::Rabbit { return super::rabbit::move_control(self, w); } + if self.species() == super::Species::Turtle { + return super::turtle::move_control(self); + } let attr_speed = self.movement_speed(); match self.ai.mov.kind { MoveKind::Custom => super::ai::custom_move_control(self, w, events), @@ -345,6 +359,20 @@ impl Mob { self.body_yaw += 4.0; } } + LookKind::Shulker => { + // ShulkerLookControl: resetXRotOnTick, getXRotD 0, and the + // yaw worked out in the attach face's plane (getYRotD). + self.head_pitch = 0.0; + if look.cooldown > 0 { + self.ai.look.cooldown -= 1; + if let Some(y) = super::shulker::look_yaw(self, look.wanted) { + self.head_yaw = rotate_towards(self.head_yaw, y, look.y_max_rot_speed); + } + } else { + self.head_yaw = rotate_towards(self.head_yaw, self.body_yaw, 10.0); + } + // clampHeadRotationToBody does nothing for a shulker. + } LookKind::Default | LookKind::Fixed => { if look.kind == LookKind::Default { self.head_pitch = 0.0; diff --git a/crates/horizon-client/src/mobs/enderman.rs b/crates/horizon-client/src/mobs/enderman.rs index 3ccd963a2..17566fb65 100644 --- a/crates/horizon-client/src/mobs/enderman.rs +++ b/crates/horizon-client/src/mobs/enderman.rs @@ -184,15 +184,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { } } } - if (m.fluids.in_water - || w.raining - && w.can_see_sky( - m.position.x.floor() as i32, - m.eye_y().floor() as i32, - m.position.z.floor() as i32, - )) - && m.alive() - { + if (m.fluids.in_water || super::ai::in_rain(m, w)) && m.alive() { // Hurt by water: teleport away. m.extra.counter2 = m.extra.counter2.max(1); } diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index 6e5daff1f..ccf4564ca 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -1508,7 +1508,7 @@ impl Ctx<'_, L, R> { } fn sound(&mut self, m: &mut Mob, registry: fn(&SpawnRegistries) -> &VariantRegistry) { let r = registry(self.data.registries); - m.extra.sound_variant = r.random(self.random) as u8; + m.extra.sound_variant = Some(r.random(self.random) as u8); } /// `finalizeSpawn` of the mob's class. @@ -2014,6 +2014,17 @@ pub fn species_variant_component(s: Species, variant: u8) -> Option<(&'static st }; Some((component, format!("minecraft:{}", variant_name(s, variant)))) } +/// The `*_sound_variant` registry of a species, in registry order. +pub fn sound_variants(s: Species) -> &'static [&'static str] { + match s { + Species::Pig => &["big", "classic", "mini"], + Species::Cow => &["classic", "moody"], + Species::Chicken => &["classic", "picky"], + Species::Cat => &["classic", "royal"], + Species::Wolf => &["angry", "big", "classic", "cute", "grumpy", "puglin", "sad"], + _ => &[], + } +} /// The registry name of the game's variant index. pub fn variant_name(s: Species, index: u8) -> &'static str { let i = index as usize; diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index d0b784166..3d9709ac4 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -1778,7 +1778,7 @@ impl Goal for Tempt { } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { let Some(p) = cx.w.player.clone() else { return }; - let (y, x) = (m.kind.max_head_y_rot + 20.0, m.kind.max_head_x_rot); + let (y, x) = (m.kind.max_head_y_rot + 20.0, m.max_head_x_rot()); m.look_at_speed(p.eye, y, x); if m.distance_sqr(p.position) < self.stop_distance * self.stop_distance { m.nav_stop(); @@ -1887,7 +1887,7 @@ impl Goal for Breed { let Some(p) = self.partner.and_then(|p| cx.w.seen(p)).cloned() else { return; }; - let x = m.kind.max_head_x_rot; + let x = m.max_head_x_rot(); m.look_at_speed([p.position.x, p.eye_y, p.position.z], 10.0, x); m.nav_move_to_entity( cx.w, diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index bd4c5b1f3..296644acc 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -544,14 +544,15 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld) { m.ai.home = Some((here, radius)); } } - // continuousHeal: a point every 30 seconds, every second in rain. + // continuousHeal: a point every 30 seconds, every second in rain or snow + // (Level.precipitationAt). if m.alive() && m.death_time == 0 && m.health < m.attrs.max_health { let (x, y, z) = ( m.position.x.floor() as i32, m.position.y.floor() as i32, m.position.z.floor() as i32, ); - let wet = w.raining && w.can_see_sky(x, y, z); + let wet = w.precipitation_at(x, y, z).is_some(); let interval = if wet { 20 } else { 600 }; if m.age.is_multiple_of(interval) { m.health = (m.health + 1.0).min(m.attrs.max_health); diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index e9cd42798..389457a11 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -235,6 +235,26 @@ impl MobWorld<'_> { }; scene.unobstructed(b).unwrap_or(false) } + /// `LevelReader.containsAnyLiquid`: the blocks from the box's minimum + /// corner to the block holding its maximum corner. + pub fn contains_any_liquid(&self, b: Aabb) -> bool { + let (lo, hi) = (b.min_position(), b.max_position()); + let (x0, y0, z0) = ( + lo.x.floor() as i32, + lo.y.floor() as i32, + lo.z.floor() as i32, + ); + let (x1, y1, z1) = ( + hi.x.floor() as i32, + hi.y.floor() as i32, + hi.z.floor() as i32, + ); + (x0..=x1).any(|x| { + (y0..=y1).any(|y| { + (z0..=z1).any(|z| self.facts.get(self.world.block(x, y, z)).fluid != Fluid::None) + }) + }) + } } impl Mob { /// `Entity.refreshDimensions` after growing from `old_w` by `old_h`: @@ -281,6 +301,15 @@ impl Mob { return (f64::from(0.2_f32), f64::from(0.2_f32), f64::from(0.2_f32)); } let k = &self.kind; + // Avatar.POSES: a player's or mannequin's box follows its pose. + if matches!(&*k.id, "minecraft:player" | "minecraft:mannequin") { + let d = self.extra.avatar_pose.dimensions(1.0); + return ( + f64::from(d.width), + f64::from(d.height), + f64::from(d.eye_height), + ); + } let (mut w, mut h, mut e) = (k.width as f32, k.height as f32, k.eye_height as f32); // Sniffer.DIGGING_DIMENSIONS: 0.4 lower, its eyes at 0.81. if k.species == super::Species::Sniffer && super::sniffer::digging(self) { @@ -529,13 +558,15 @@ impl Mob { } } /// `Entity.nextStep`: the next whole metre walked; a warden's steps come - /// every 0.55, a strider's every 0.6. + /// every 0.55, a strider's every 0.6, a turtle's every 0.15. fn next_step(&self) -> f32 { let walked = self.ai.steps.move_dist; if self.kind.species == super::Species::Warden { walked + 0.55 } else if self.kind.species == super::Species::Strider { walked + 0.6 + } else if self.kind.species == super::Species::Turtle { + walked + 0.15 } else { (walked as i32).wrapping_add(1) as f32 } @@ -813,14 +844,24 @@ impl Mob { self.velocity.y -= gravity / 4.0; } } - // jumpOutOfFluid + // jumpOutOfFluid: Entity.isFree wants the box dry and clear of the + // entities a mob collides with (canBeCollidedWith: living shulkers). let m = self.velocity; + let ahead = self.bounds().move_by(Vec3::new( + m.x, + m.y + f64::from(0.6_f32) - self.position.y + old_y, + m.z, + )); + let wide = ahead.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); if self.horizontal_collision - && w.no_collision(self.bounds().move_by(Vec3::new( - m.x, - m.y + f64::from(0.6_f32) - self.position.y + old_y, - m.z, - ))) + && w.no_collision(ahead) + && !w.contains_any_liquid(ahead) + && !w.others_near(wide).any(|s| { + s.id != self.id + && s.alive + && s.species == super::Species::Shulker + && s.bounds.intersects(wide) + }) { self.velocity.y = f64::from(0.3_f32); } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 077fd38a6..46eb14cc1 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -177,8 +177,71 @@ pub fn body(m: &Mob) -> (String, String) { "frog#main".into(), format!("entity/frog/frog_{}", climate(m)), ), - S::Rabbit => ( - baby_or(m, "rabbit#main", "rabbit_baby#main"), + // RabbitRenderer.getTextureLocation: the Toast name tag, else the + // variant (the killer bunny's id is 99). + S::Rabbit => { + let name = if m.custom_name.as_deref() == Some("Toast") { + "toast" + } else { + match m.extra.variant { + 1 => "white", + 2 => "black", + 3 => "white_splotched", + 4 => "gold", + 5 => "salt", + 99 => "caerbannog", + _ => "brown", + } + }; + ( + baby_or(m, "rabbit#main", "rabbit_baby#main"), + b(&format!("entity/rabbit/rabbit_{name}")), + ) + } + // ParrotRenderer.getVariantTexture. + S::Parrot => { + let name = ["red_blue", "blue", "green", "yellow_blue", "grey"] + [usize::from(m.extra.variant).min(4)]; + (m.kind.model_key(), format!("entity/parrot/parrot_{name}")) + } + // AxolotlRenderer.getTextureLocation. + S::Axolotl => { + let name = + ["lucy", "wild", "gold", "cyan", "blue"][usize::from(m.extra.variant).min(4)]; + ( + baby_or(m, "axolotl#main", "axolotl_baby#main"), + b(&format!("entity/axolotl/axolotl_{name}")), + ) + } + // SalmonRenderer.submit: the model of the salmon's size. + S::Salmon => { + let model = match m.extra.variant { + 0 => "salmon_small#main", + 2 => "salmon_large#main", + _ => "salmon#main", + }; + (model.into(), "entity/fish/salmon".into()) + } + // The baby models and textures of AgeableMobRenderer's other + // subclasses. + S::Goat => ( + baby_or(m, "goat#main", "goat_baby#main"), + b(&m.kind.texture), + ), + S::PolarBear => ( + baby_or(m, "polar_bear#main", "polar_bear_baby#main"), + b(&m.kind.texture), + ), + S::Ocelot => ( + baby_or(m, "ocelot#main", "ocelot_baby#main"), + b(&m.kind.texture), + ), + S::Turtle => ( + baby_or(m, "turtle#main", "turtle_baby#main"), + b(&m.kind.texture), + ), + S::Armadillo => ( + baby_or(m, "armadillo#main", "armadillo_baby#main"), b(&m.kind.texture), ), S::Pig => { @@ -241,7 +304,7 @@ pub fn body(m: &Mob) -> (String, String) { ), S::ZombieVillager => ( baby_or(m, "zombie_villager#main", "zombie_villager_baby#main"), - "entity/zombie_villager/zombie_villager".into(), + b("entity/zombie_villager/zombie_villager"), ), S::Villager => ( baby_or(m, "villager#main", "villager_baby#main"), @@ -765,7 +828,14 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 let rotation = match sleep { // setupRotations for Pose.SLEEPING, with the head moved toward the pillow. Some((angle, step)) => { - let head = (m.eye_y() - m.position.y) as f32 - 0.1; + // The eye height of the standing pose (LivingEntityRenderer + // extracts `getEyeHeight(Pose.STANDING)` for a bed). + let eye = if avatar(m) { + m.kind.eye_height as f32 + } else { + (m.eye_y() - m.position.y) as f32 + }; + let head = eye - 0.1; glam::Mat4::from_translation(glam::Vec3::new(-step[0] * head, 0.0, -step[1] * head)) * glam::Mat4::from_rotation_y(angle.to_radians()) * glam::Mat4::from_rotation_z(90.0_f32.to_radians()) @@ -833,10 +903,15 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 base *= species_scale(m, alpha); base * glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.501, 0.0)) } -/// `LivingEntityRenderer.isShaking`: converting zombies, piglins and -/// hoglins, and a zombie villager being cured. +/// `LivingEntityRenderer.isShaking`: a fully frozen mob (the skeleton's own +/// `isShaking` is its stray conversion only), converting zombies, piglins +/// and hoglins, a zombie villager being cured and a cold strider. fn shaking(m: &Mob) -> bool { + if m.is_fully_frozen() && m.species() != Species::Skeleton { + return true; + } match m.species() { + Species::Strider => super::strider::suffocating(m), Species::ZombieVillager => super::zombie_villager::is_converting(m), Species::Zombie | Species::Husk => m.extra.counter2 > 0, Species::Piglin | Species::PiglinBrute | Species::Hoglin => { @@ -1235,6 +1310,15 @@ fn hand_base( 0.0 }; let mut t = part_matrix(model, base, poses, arm, offset)?; + if m.species() == Species::Vex { + // `VexModel.translateToHand`: the held item is drawn at 0.55 scale. + t *= glam::Mat4::from_scale(glam::Vec3::splat(0.55)); + t *= glam::Mat4::from_translation(glam::Vec3::new( + if left { -0.046_875 } else { 0.046_875 }, + -0.156_25, + 0.078_125, + )); + } let (ox, oy, oz) = if m.is_baby() { (0.0, 1.0, -4.5) } else { @@ -1421,4 +1505,40 @@ mod tests { assert!(vertices.iter().all(|v| v.uv[0] >= 0.5)); } } + /// `VexModel.translateToHand`: the held item is drawn at 0.55 scale and + /// moved by the vex's own offset, so the vex's sword is the tiny one + /// vanilla shows. It was drawn at the full size, like a zombie's. + #[test] + fn the_vex_holds_its_item_at_the_small_scale() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("entity-models.json").exists() { + return; + } + let types = super::super::MobTypes::load(&root).unwrap(); + let kind = std::sync::Arc::new(types.types["minecraft:vex"].clone()); + let mob = Mob::new(1, kind, horizon_core::geometry::Vec3::ZERO, 0.0); + let data = MobData { + states: Vec::new(), + placements: Default::default(), + heightmaps: Default::default(), + animations: Default::default(), + biome_tags: Default::default(), + entity_tags: Default::default(), + villager_hats: Default::default(), + pois: Default::default(), + }; + for left in [false, true] { + let t = held_item_transform(&mob, 0.5, glam::DVec3::ZERO, &data, left).unwrap(); + // The model's own part scale is 1, so the item's scale is the + // renderer's: `poseStack.scale(0.55F, 0.55F, 0.55F)`. + for axis in [t.x_axis, t.y_axis, t.z_axis] { + let scale = axis.truncate().length(); + assert!( + (scale - 0.55).abs() < 1.0e-5, + "the vex's item is drawn at 0.55 scale, got {scale}" + ); + } + } + } } diff --git a/crates/horizon-client/src/mobs/shulker.rs b/crates/horizon-client/src/mobs/shulker.rs index 6f0edc2d7..32f952e15 100644 --- a/crates/horizon-client/src/mobs/shulker.rs +++ b/crates/horizon-client/src/mobs/shulker.rs @@ -5,6 +5,7 @@ use super::{ Damage, DamageKind, Mob, MobEvent, MobWorld, Species, Who, anim::{Poses, State}, + control::LookKind, goals::{ Cx, Goal, HurtByTarget, LOOK, LookAtPlayer, MOVE, NearestTarget, RandomLookAround, goal_clone, reduced, @@ -37,7 +38,13 @@ pub fn register(m: &mut Mob) { g.add(4, ShulkerAttack { attack_time: 0 }); g.add(7, Peek { time: 0 }); g.add(8, RandomLookAround::default()); - m.ai.targets.add(1, HurtByTarget::new().alert()); + // `ShulkerLookControl`: the head turns in the attach face's plane. + m.ai.look.kind = LookKind::Shulker; + // `HurtByTargetGoal(this, Shulker.class).setAlertOthers()`: damage from + // another shulker draws no retaliation (`toIgnoreDamage`), but a hurt + // shulker alerts every targetless shulker around. + m.ai.targets + .add(1, HurtByTarget::new().alert().ignoring(&[Species::Shulker])); // ShulkerNearestAttackGoal: the search box is only 4 deep along the // attach axis. m.ai.targets.add( @@ -57,6 +64,10 @@ pub fn register(m: &mut Mob) { fn face_step(face: u8) -> [i32; 3] { STEPS[face.min(5) as usize] } +/// `Direction.getOpposite` for a 3D data value. +fn opposite(face: u8) -> u8 { + face.min(5) ^ 1 +} fn block_pos(m: &Mob) -> [i32; 3] { [ m.position.x.floor() as i32, @@ -64,19 +75,83 @@ fn block_pos(m: &Mob) -> [i32; 3] { m.position.z.floor() as i32, ] } -/// `Shulker.canStayAt`: an empty spot against a sturdy face. -fn can_stay_at(w: &MobWorld, p: [i32; 3], face: u8) -> bool { - if !w.facts.is_air(w.world.block(p[0], p[1], p[2])) { +/// `Shulker.getProgressDeltaAabb` at scale 1: the shell's box from `pos` +/// (the bottom centre), grown `from`..`to` along `direction`. +fn progress_aabb(direction: u8, from: f64, to: f64, pos: Vec3) -> Aabb { + let s = face_step(direction).map(f64::from); + let (max, min) = (from.max(to), from.min(to)); + Aabb::new(Vec3::new(-0.5, 0.0, -0.5), Vec3::new(0.5, 1.0, 0.5)) + .expand_towards(Vec3::new(s[0] * max, s[1] * max, s[2] * max)) + .contract(Vec3::new( + -s[0] * (1.0 + min), + -s[1] * (1.0 + min), + -s[2] * (1.0 + min), + )) + .move_by(pos) +} +/// `Level.noCollision(shulker, aabb)`: no block collision under the empty +/// context, and none of the entities a shulker collides with overlaps +/// (`canBeCollidedWith`: living shulkers and adult happy ghasts; players +/// and other mobs never block it). +fn no_collision(m: &Mob, w: &MobWorld, bounds: Aabb) -> bool { + let mut scene = crate::collisions::SceneCollisions { + world: w.world, + binding: w.collision, + subject: None, + }; + if !crate::collisions::no_collision_empty(&mut scene, bounds) { return false; } + let grown = bounds.inflate(Vec3::new(1.0e-7, 1.0e-7, 1.0e-7)); + !w.others_near(grown).any(|s| { + s.id != m.id + && s.alive + && (s.species == Species::Shulker || (s.species == Species::HappyGhast && !s.baby)) + && s.bounds.intersects(grown) + }) +} +/// `Shulker.canStayAt`: an empty spot against a sturdy face, with room +/// for the fully opened shell (`canStayAt`). +fn can_stay_at(m: &Mob, w: &MobWorld, p: [i32; 3], face: u8) -> bool { + // isPositionBlocked: anything but air blocks, except a moving piston + // being driven through the shulker's own cell. + if !w.facts.is_air(w.world.block(p[0], p[1], p[2])) + && (p != block_pos(m) || w.block_name(p[0], p[1], p[2]) != "minecraft:moving_piston") + { + return false; + } + // loadedAndEntityCanStandOnFace: the supporting block's face toward + // the shell is sturdy. let s = face_step(face); - let n = w.world.block(p[0] + s[0], p[1] + s[1], p[2] + s[2]); - w.facts.get(n).full_collision + let support = w.world.block(p[0] + s[0], p[1] + s[1], p[2] + s[2]); + let open = opposite(face); + if w.facts.get(support).sturdy_full & (1 << open) == 0 { + return false; + } + // The fully opened shell's box, shrunk by the skin vanilla uses. + let opened = progress_aabb( + open, + -1.0, + 1.0, + Vec3::new( + f64::from(p[0]) + 0.5, + f64::from(p[1]), + f64::from(p[2]) + 0.5, + ), + ) + .deflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6)); + no_collision(m, w, opened) } /// `findAttachableSurface`: the first face (down, up, north, south, west, /// east) to cling to. -fn attachable(w: &MobWorld, p: [i32; 3]) -> Option { - (0..6).find(|&f| can_stay_at(w, p, f)) +fn attachable(m: &Mob, w: &MobWorld, p: [i32; 3]) -> Option { + (0..6).find(|&f| can_stay_at(m, w, p, f)) +} +/// `BlockUtil.packDifferenceInPosition` within 8 blocks of `pos`. +fn pack_diff(pos: [i32; 3], to: [i32; 3]) -> i32 { + ((to[0] - pos[0] + 8) & 0xFF) << 16 + | ((to[1] - pos[1] + 8) & 0xFF) << 8 + | (to[2] - pos[2] + 8) & 0xFF } /// `Shulker.teleportSomewhere`: up to five tries within 8 blocks. fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { @@ -87,12 +162,31 @@ fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { for _ in 0..5 { let r = |m: &mut Mob| m.random.next_int_bound(17).unwrap_or(8) - 8; let t = [old[0] + r(m), old[1] + r(m), old[2] + r(m)]; - if t[1] <= crate::chunk::MIN_Y || !w.facts.is_air(w.world.block(t[0], t[1], t[2])) { + let unit = Aabb::new( + Vec3::new(f64::from(t[0]), f64::from(t[1]), f64::from(t[2])), + Vec3::new( + f64::from(t[0]) + 1.0, + f64::from(t[1]) + 1.0, + f64::from(t[2]) + 1.0, + ), + ); + if t[1] <= crate::chunk::MIN_Y + || !w.facts.is_air(w.world.block(t[0], t[1], t[2])) + || !no_collision(m, w, unit.deflate(Vec3::new(1.0e-6, 1.0e-6, 1.0e-6))) + { continue; } - let Some(face) = attachable(w, t) else { + let Some(face) = attachable(m, w, t) else { continue; }; + // `#minecraft:shulker_does_not_teleport_to` (bedrock) is never clung to. + let s = face_step(face); + if w.has_tag( + "minecraft:shulker_does_not_teleport_to", + w.block_name(t[0] + s[0], t[1] + s[1], t[2] + s[2]), + ) { + continue; + } m.extra.variant3 = face; events.push(MobEvent::Sound( "entity.shulker.teleport", @@ -106,6 +200,14 @@ fn teleport(m: &mut Mob, w: &MobWorld, events: &mut Vec) -> bool { f64::from(t[2]) + 0.5, ); m.previous = m.position; + // Level.levelEvent(2016, oldPos, packedDiff): the teleport's + // particles at both ends, seen by the players around. + events.push(MobEvent::LevelEvent { + id: 2016, + pos: old, + data: pack_diff(old, t), + }); + m.needs_sync = true; m.extra.counter = 0; m.ai.target = None; return true; @@ -127,31 +229,102 @@ fn set_peek(m: &mut Mob, amount: i32, events: &mut Vec) { )); m.extra.counter = amount; } -/// `Shulker.tick` additions: keep a face (or teleport), ease the peek, -/// stay still and square on its block. +/// `Shulker.updatePeekAmount`/`updatePeekAmountO`: the eased peek. +fn ease_peek(m: &mut Mob) -> (f32, f32) { + let old = m.anim.v[PEEK]; + let target = m.extra.counter as f32 * 0.01; + let new = if old > target { + (old - 0.05).clamp(target, 1.0) + } else { + (old + 0.05).clamp(0.0, target) + }; + m.anim.v[PEEK] = new; + (old, new) +} +/// `Shulker.tick` additions: keep a face (or teleport), ease the peek +/// (pushing whatever it opens into), stay still and square on its block. pub fn tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.velocity = Vec3::ZERO; m.body_yaw = 0.0; m.yaw = 0.0; m.head_pitch = 0.0; let p = block_pos(m); - if !can_stay_at(w, p, m.extra.variant3) { - match attachable(w, p) { + if !can_stay_at(m, w, p, m.extra.variant3) { + match attachable(m, w, p) { Some(f) => m.extra.variant3 = f, None => { teleport(m, w, events); } } } - let a = &mut m.anim; - let target = m.extra.counter as f32 * 0.01; - let cur = a.v[PEEK]; - if cur > target { - a.v[PEEK] = (cur - 0.05).clamp(target, 1.0); - } else if cur < target { - a.v[PEEK] = (cur + 0.05).clamp(0.0, target); + let (old, new) = ease_peek(m); + if new != old { + on_peek_change(m, w, old, new, events); } } +/// `Shulker.getPhysicalPeek`: the lid's lift for a peek amount. +fn physical_peek(amount: f32) -> f64 { + f64::from(0.5 - ((0.5 + amount) * PI).msin() * 0.5) +} +/// `Shulker.onPeekAmountChange`: an opening shell pushes out of its way +/// every entity that can be collided with (except other shulkers). +fn on_peek_change(m: &Mob, w: &MobWorld, old: f32, new: f32, events: &mut Vec) { + let dir = opposite(m.extra.variant3); + let s = face_step(dir).map(f64::from); + let (old_p, new_p) = (physical_peek(old), physical_peek(new)); + let push = new_p - old_p; + if push <= 0.0 { + return; + } + let delta = [push * s[0], push * s[1], push * s[2]]; + let area = progress_aabb(dir, old_p, new_p, m.position); + if let Some(p) = &w.player + && p.alive + && !p.spectator + && p.bounds.intersects(area) + { + events.push(MobEvent::Shift { + target: Who::Player, + delta, + }); + } + for seen in w.others_near(area) { + if seen.id == m.id + || !seen.alive + || seen.species == Species::Shulker + || !seen.bounds.intersects(area) + { + continue; + } + events.push(MobEvent::Shift { + target: Who::Mob(seen.id), + delta, + }); + } +} +/// `ShulkerLookControl.getYRotD`: the look yaw in the open direction's +/// plane (`None`: the target is on the head's own axis). +pub fn look_yaw(m: &Mob, at: [f64; 3]) -> Option { + let open = opposite(m.extra.variant3); + // `attachFace.getRotation().transform(FORWARD)`: the model's forward + // rotated as the renderer does (`rotations` uses the same quats). + let forward = face_quat(m.extra.variant3) * glam::Vec3::Z; + let s = face_step(open).map(|v| v as f32); + let right = glam::Vec3::from_array(s).cross(forward); + let out = glam::Vec3::new( + (at[0] - m.position.x) as f32, + (at[1] - m.eye_y()) as f32, + (at[2] - m.position.z) as f32, + ); + let (delta_right, delta_forward) = (right.dot(out), forward.dot(out)); + if delta_right.abs() <= 1.0e-5 && delta_forward.abs() <= 1.0e-5 { + return None; + } + Some(horizon_core::geometry::trig::atan2_degrees( + f64::from(-delta_right), + f64::from(delta_forward), + )) +} /// `Shulker.hurtServer` before the damage: arrows bounce off a closed shell. pub fn accepts(m: &Mob, source: &Damage) -> bool { !(m.extra.counter == 0 && source.kind == DamageKind::Arrow) @@ -319,7 +492,7 @@ impl Goal for Peek { fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { m.ai.target.is_none() && m.random.next_int_bound(reduced(40)).unwrap_or(1) == 0 - && can_stay_at(cx.w, block_pos(m), m.extra.variant3) + && can_stay_at(m, cx.w, block_pos(m), m.extra.variant3) } fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool { m.ai.target.is_none() && self.time > 0 @@ -362,24 +535,27 @@ pub fn texture(m: &Mob) -> String { None => "entity/shulker/shulker".into(), } } +/// `attachFace.getOpposite().getRotation()` by attach face: the open +/// direction's rotation (`Direction.getRotation` of `face ^ 1`). +fn face_quat(face: u8) -> glam::Quat { + match face.min(5) { + // Attached below: upright. + 0 => glam::Quat::IDENTITY, + 1 => glam::Quat::from_rotation_x(PI), + 2 => glam::Quat::from_rotation_x(PI / 2.0), + 3 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI), + 4 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, -PI / 2.0), + _ => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI / 2.0), + } +} /// `ShulkerRenderer.setupRotations`: turned onto its attach face around the /// block's centre (after a half turn of the body). pub fn rotations(m: &Mob) -> glam::Mat4 { - { - let q = match m.extra.variant3 { - // Attached below: upright. - 0 => glam::Quat::IDENTITY, - 1 => glam::Quat::from_rotation_x(PI), - 2 => glam::Quat::from_rotation_x(PI / 2.0), - 3 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI), - 4 => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, -PI / 2.0), - _ => glam::Quat::from_euler(glam::EulerRot::XYZ, PI / 2.0, 0.0, PI / 2.0), - }; - glam::Mat4::from_rotation_y(PI) - * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.5, 0.0)) - * glam::Mat4::from_quat(q) - * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0)) - } + let q = face_quat(m.extra.variant3); + glam::Mat4::from_rotation_y(PI) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.5, 0.0)) + * glam::Mat4::from_quat(q) + * glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0)) } /// `ShulkerModel.setupAnim`: the lid rises and twists with the peek, the /// head turns. diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index f48a21fe9..92d1f21cd 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1500,7 +1500,7 @@ impl Def { ), // Nautilus.handleAirSupply: it dries out on land. needs_water: aquatic || s == S::Nautilus, - water_sensitive: matches!(s, S::Enderman | S::Blaze | S::SnowGolem), + water_sensitive: matches!(s, S::Enderman | S::Blaze | S::SnowGolem | S::Strider), animal: !matches!(s, S::Bat | S::SulfurCube | S::Mannequin) && !self.hostile_class() && !aquatic @@ -1629,6 +1629,7 @@ impl Def { match self.species { Species::Dolphin | Species::Axolotl => 1.0, Species::Slime | Species::MagmaCube | Species::SulfurCube => 0.0, + Species::Guardian | Species::ElderGuardian | Species::Shulker => 180.0, _ => 40.0, } } @@ -1640,6 +1641,9 @@ impl Def { Species::Sniffer => 50.0, Species::Goat => 15.0, Species::Armadillo => 32.0, + Species::Ravager => 45.0, + Species::Camel | Species::CamelHusk => 30.0, + Species::Shulker => 180.0, _ => 75.0, } } diff --git a/crates/horizon-client/src/mobs/sulfur_cube.rs b/crates/horizon-client/src/mobs/sulfur_cube.rs index 00b846b86..e97134505 100644 --- a/crates/horizon-client/src/mobs/sulfur_cube.rs +++ b/crates/horizon-client/src/mobs/sulfur_cube.rs @@ -297,6 +297,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool { | DamageKind::Fall | DamageKind::Sting | DamageKind::Cactus + | DamageKind::Freeze ); if immune { if let Some(from) = source.from { diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 1e725df80..0b2075c96 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -360,7 +360,7 @@ impl Goal for FollowOwner { }; let far = m.distance_sqr(at) >= 144.0; if !far { - let max = max_head_x_rot(m); + let max = m.max_head_x_rot(); m.look_at_speed([at.x, eye, at.z], 10.0, max); } self.recalc -= 1; @@ -507,7 +507,7 @@ impl Goal for Beg { } fn tick(&mut self, m: &mut Mob, cx: &mut Cx) { if let Some(p) = &cx.w.player { - let max = max_head_x_rot(m); + let max = m.max_head_x_rot(); m.look_at_speed([p.position.x, p.eye[1], p.position.z], 10.0, max); } self.ticks -= 1; @@ -529,12 +529,7 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { let v = &mut m.anim.v; v[INTEREST] += (goal - v[INTEREST]) * 0.4; // isWet (extra.flag2), isShaking (counter2 > 0). - let rain = w.raining - && w.can_see_sky( - m.position.x.floor() as i32, - (m.position.y + f64::from(m.height())).floor() as i32, - m.position.z.floor() as i32, - ); + let rain = super::ai::in_rain(m, w); let shaking = m.extra.counter2 > 0; if m.fluids.in_water || rain { m.extra.flag2 = true; @@ -683,14 +678,6 @@ pub fn texture(m: &Mob) -> String { let baby = if m.is_baby() { "_baby" } else { "" }; format!("entity/wolf/{file}{state}{baby}") } -/// `Wolf.getMaxHeadXRot`: 20 degrees while sitting. -fn max_head_x_rot(m: &Mob) -> f32 { - if m.extra.sitting { - 20.0 - } else { - m.kind.max_head_x_rot - } -} /// Cat variants (`CatVariants`): registry name, texture file. pub const CAT_VARIANTS: [&str; 11] = [ diff --git a/crates/horizon-client/src/mobs/turtle.rs b/crates/horizon-client/src/mobs/turtle.rs index 98dd5b558..e56973384 100644 --- a/crates/horizon-client/src/mobs/turtle.rs +++ b/crates/horizon-client/src/mobs/turtle.rs @@ -1,12 +1,17 @@ //! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her //! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand //! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`, -//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. +//! `extra.counter` `layEggCounter` and `extra.home` `homePos`. Its own +//! `TurtleMoveControl` sets the speed it walks and swims at. Not ported yet: +//! `Turtle.travelInWater` (swimming still uses the generic fluid travel), +//! `TurtlePathNavigation` and the rest of the turtle goal set, so movement in +//! water still differs from vanilla. use super::{ Mob, MobEvent, MobWorld, + control::{EPSILON, Operation, rotlerp}, goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::trig, random::RandomSource}; pub fn register(m: &mut Mob) { let g = &mut m.ai.goals; @@ -49,6 +54,45 @@ fn block_of(m: &Mob) -> [i32; 3] { fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool { w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2])) } +/// `Turtle.TurtleMoveControl.updateSpeed`: slow in water away from home +/// (slower still as a baby), and halved every tick on land, never under 0.06. +fn update_speed(m: &mut Mob) { + if m.fluids.in_water { + m.velocity.y += 0.005; + if !close_to_home(m, 16.0) { + m.set_speed((m.ai.speed / 2.0).max(0.08)); + } + if m.is_baby() { + m.set_speed((m.ai.speed / 3.0).max(0.06)); + } + } else if m.on_ground { + m.set_speed((m.ai.speed / 2.0).max(0.06)); + } +} +/// `Turtle.TurtleMoveControl.tick`: ease the speed an eighth of the way to +/// the wanted one each tick (after `updateSpeed` cut it), face the wanted +/// point and lift towards it; no jumping, and the operation is never reset. +pub fn move_control(m: &mut Mob) { + update_speed(m); + if m.ai.mov.operation != Operation::MoveTo || m.ai.nav.is_done() { + m.set_speed(0.0); + return; + } + let [wx, wy, wz] = m.ai.mov.wanted; + let (xd, yd, zd) = (wx - m.position.x, wy - m.position.y, wz - m.position.z); + let dist = (xd * xd + yd * yd + zd * zd).sqrt(); + if dist < EPSILON { + m.set_speed(0.0); + return; + } + let y_rot = trig::atan2_degrees(zd, xd) - 90.0; + m.yaw = rotlerp(m.yaw, y_rot, 90.0); + m.body_yaw = m.yaw; + let wanted = (m.ai.mov.speed_modifier * m.movement_speed()) as f32; + // Mth.lerp(0.125F, getSpeed(), wanted). + m.set_speed(m.ai.speed + 0.125 * (wanted - m.ai.speed)); + m.velocity.y += f64::from(m.ai.speed) * (yd / dist) * 0.1; +} /// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick. pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 { @@ -207,3 +251,149 @@ impl Goal for GoHome { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::mobs::{ + Species, + path::{Path, PathNode, PathType}, + }; + use horizon_core::geometry::Vec3; + use std::sync::Arc; + + /// A turtle (movement speed 0.25) strolling (`speedModifier` 1.0) to a + /// point ten blocks ahead along a path it has not finished. + fn strolling_turtle() -> Mob { + let mut kind = crate::mobs::sensor_scan_tests::kind(); + let k = Arc::make_mut(&mut kind); + k.id = "minecraft:turtle".into(); + k.species = Species::Turtle; + k.speed = 0.25; + k.step_height = 1.0; + let mut m = Mob::new(1, kind, Vec3::ZERO, 0.0); + m.on_ground = true; + let node = PathNode { + x: 0, + y: 0, + z: 10, + kind: PathType::Walkable, + }; + m.ai.nav.path = Some(Path { + nodes: vec![node], + next: 0, + target: [0, 0, 10], + dist_to_target: 0.0, + reached: true, + }); + m.ai.mov.set_wanted(0.0, 0.0, 10.0, 1.0); + m + } + fn speeds(m: &mut Mob, ticks: usize) -> Vec { + (0..ticks) + .map(|_| { + move_control(m); + assert_eq!(m.ai.zza, m.ai.speed, "setSpeed sets the forward input"); + m.ai.speed + }) + .collect() + } + + #[test] + fn walks_on_land_at_a_third_of_its_movement_speed() { + // TurtleMoveControl.tick on the ground: updateSpeed makes it + // max(speed / 2, 0.06) = 0.06, then Mth.lerp(0.125F, 0.06, 0.25), + // every tick. The default MoveControl walked it at the full 0.25, so + // the walk animation (and TurtleModel's 8 * walkSpeed leg swing) ran + // about nine times too fast (#1776). + let mut m = strolling_turtle(); + let land = 0.06_f32 + 0.125 * (0.25 - 0.06_f32); + assert_eq!(speeds(&mut m, 40), vec![land; 40]); + // Facing the wanted point, the body with it; it never jumps. + assert_eq!(m.body_yaw, m.yaw); + assert!(crate::mobs::living::wrap(m.yaw).abs() < 1.0e-3); + assert!(!m.ai.jump); + assert_eq!(m.ai.mov.operation, Operation::MoveTo); + assert_eq!(m.velocity.y, 0.0); + } + + #[test] + fn water_speed_is_cut_away_from_home_and_for_babies() { + // updateSpeed in water near home: no cut, the lerp climbs towards + // 0.25, and it lifts the turtle 0.005 a tick. (Only the control's + // speed: Turtle.travelInWater is not ported.) + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + let s = speeds(&mut m, 60); + assert_eq!(s[0], 0.125 * 0.25); + assert!(s.windows(2).all(|w| w[1] > w[0]) && s[59] > 0.24 && s[59] < 0.25); + assert!((m.velocity.y - 60.0 * 0.005).abs() < 1.0e-9); + // More than 16 blocks from home: max(speed / 2, 0.08) first. + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + m.extra.home = Some([0, 0, 40]); + let far = 0.08_f32 + 0.125 * (0.25 - 0.08_f32); + assert_eq!(speeds(&mut m, 20), vec![far; 20]); + // A baby: max(speed / 3, 0.06). + let mut m = strolling_turtle(); + m.on_ground = false; + m.fluids.in_water = true; + m.extra.age = -24000; + let young = 0.06_f32 + 0.125 * (0.25 - 0.06_f32); + assert_eq!(speeds(&mut m, 20), vec![young; 20]); + } + + #[test] + fn stops_when_the_path_is_done_or_the_point_reached() { + let mut m = strolling_turtle(); + m.ai.nav.stop(); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(0.0, 0.0, 0.0, 1.0); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + // updateSpeed runs before the early return: a stopped turtle in + // water is still lifted 0.005, path done or not moving at all. + let mut m = strolling_turtle(); + m.fluids.in_water = true; + m.ai.nav.stop(); + assert_eq!(speeds(&mut m, 1), vec![0.0]); + assert_eq!(m.velocity.y, 0.005); + let mut m = strolling_turtle(); + m.fluids.in_water = true; + m.ai.mov.operation = Operation::Wait; + assert_eq!(speeds(&mut m, 1), vec![0.0]); + assert_eq!(m.velocity.y, 0.005); + } + + #[test] + fn lifts_towards_a_point_above_by_the_slope_of_the_way_there() { + // setDeltaMovement(... + getSpeed() * (dy / dist) * 0.1): two up, + // three across and ten ahead. + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(3.0, 2.0, 10.0, 1.0); + let speed = speeds(&mut m, 1)[0]; + let dist = (3.0_f64 * 3.0 + 2.0 * 2.0 + 10.0 * 10.0).sqrt(); + assert_eq!(m.velocity.y, f64::from(speed) * (2.0 / dist) * 0.1); + assert!(m.velocity.y > 0.0); + } + + #[test] + fn turns_at_most_ninety_degrees_a_tick_and_wraps_into_a_turn() { + // rotlerp(yRot, target, 90): from 150 towards about -16.7 it turns + // the full 90 to 60, then reaches the target, kept in [0, 360] as + // about 343.3; the body follows the yaw each tick. + let mut m = strolling_turtle(); + m.ai.mov.set_wanted(3.0, 0.0, 10.0, 1.0); + m.yaw = 150.0; + m.body_yaw = 150.0; + let target = trig::atan2_degrees(10.0, 3.0) - 90.0; + assert!((-17.0..-16.0).contains(&target)); + move_control(&mut m); + assert_eq!((m.yaw, m.body_yaw), (60.0, 60.0)); + move_control(&mut m); + assert_eq!(m.yaw, 60.0 + (target - 60.0) + 360.0); + assert_eq!(m.body_yaw, m.yaw); + } +} diff --git a/crates/horizon-client/src/mobs/villager.rs b/crates/horizon-client/src/mobs/villager.rs index aad0ec911..20280b190 100644 --- a/crates/horizon-client/src/mobs/villager.rs +++ b/crates/horizon-client/src/mobs/villager.rs @@ -905,6 +905,53 @@ mod tests { assert!(t.unset); assert_eq!(m.extra.variant2, 2); } + /// The reported sequence: a villager works at a bench, the bench is + /// destroyed (its job site is gone, so `ResetProfession` makes it + /// unemployed) and it takes another bench's job. The new profession's + /// trades are offered again. + /// + /// `Villager.setVillagerData` drops the offers (`offers = null`) when the + /// profession changes, so `AbstractVillager.getOffers` rolls the new + /// profession's trade set the next time the offers are asked for. A + /// villager that keeps its old offers marked as made never trades again: + /// it shakes its head instead of opening the trading menu. + #[test] + fn a_villager_that_loses_its_job_site_offers_its_new_profession_trades() { + let mut m = villager(); + // The composter's job: the villager is a farmer. + set_profession(&mut m, 5); + assert_eq!(m.extra.variant2, 5); + // Its trades were made, so the offers are there. + let trade = m.extra.trade.get_or_insert_default(); + trade.unset = false; + trade.offers = vec![crate::merchant::MerchantOffer { + base_cost_a: crate::merchant::ItemCost { + stack: ItemStack::new("minecraft:wheat", 20), + }, + cost_b: None, + result: ItemStack::new("minecraft:emerald", 1), + uses: 0, + max_uses: 16, + reward_exp: true, + special_price_diff: 0, + demand: 0, + price_multiplier: 0.0, + xp: 1, + }]; + // The work bench is destroyed: the job site is gone, so the villager + // is unemployed and its offers are dropped (`offers = null`). + set_profession(&mut m, NONE); + let t = m.extra.trade.as_ref().unwrap(); + assert!(t.offers.is_empty()); + assert!(t.unset); + // It takes the smithing table's job. The new profession's trades are + // rolled by the next `getOffers` (ensure_offers). + set_profession(&mut m, 13); + let t = m.extra.trade.as_ref().unwrap(); + assert!(t.offers.is_empty()); + assert!(t.unset); + assert_eq!(m.extra.variant2, 13); + } fn stack(item: &str, count: u32) -> ItemStack { ItemStack::new(item, count) diff --git a/crates/horizon-client/src/mobs/wither.rs b/crates/horizon-client/src/mobs/wither.rs index 6702686c5..6c3316ac7 100644 --- a/crates/horizon-client/src/mobs/wither.rs +++ b/crates/horizon-client/src/mobs/wither.rs @@ -96,7 +96,7 @@ pub fn make_invulnerable(m: &mut Mob) { pub fn powered(m: &Mob) -> bool { m.health <= m.attrs.max_health / 2.0 } -fn head_pos(m: &Mob, i: usize) -> [f64; 3] { +pub fn head_pos(m: &Mob, i: usize) -> [f64; 3] { if i == 0 { return [m.position.x, m.position.y + 3.0, m.position.z]; } diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index bce324228..dc201a3f3 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -206,18 +206,24 @@ impl MobWorld<'_> { } self.world.light(x, y, z) >> 4 == 15 } - /// Level.isRainingAt: raining, open to the sky, nothing motion blocking - /// above, and the biome's precipitation at the position is rain, not snow + /// Level.precipitationAt: raining, open to the sky, nothing motion + /// blocking above, then the biome's precipitation at the position: + /// `Some(true)` rain, `Some(false)` snow, `None` nothing. + pub fn precipitation_at(&self, x: i32, y: i32, z: i32) -> Option { + if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { + return None; + } + let chunk = self.world.chunks.get(&(x >> 4, z >> 4))?; + let biome = self.biomes.get(chunk.biome(x, y, z)); + if !biome.precipitation { + return None; + } + Some(biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15) + } + /// Level.isRainingAt: the precipitation at the position is rain, not snow /// or none. pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool { - if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y { - return false; - } - let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { - return false; - }; - let biome = self.biomes.get(chunk.biome(x, y, z)); - biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15 + self.precipitation_at(x, y, z) == Some(true) } /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// at the raw (sky darkened) light level. diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 3d38fae4d..aeeab3016 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -114,6 +114,7 @@ fn ruby_mod(dir: &Path) -> ContentMod { /// new blocks behave like their templates with the overrides, and vanilla's /// states are where they were. #[test] +#[ignore = "full content root: CI and pr_ready run it"] fn content_root_loads_with_every_table() { let Some(base) = prepared() else { return; @@ -352,6 +353,7 @@ fn no_content_keeps_the_base_root() { use horizon_world::registry::BlockStateId; #[test] +#[ignore = "full content root: CI and pr_ready run it"] fn shared_behaviour_document_matches_independent_loaders() { let Some(root) = prepared() else { return }; let assets = Assets::load(&root).expect("assets"); @@ -414,6 +416,7 @@ fn shared_behaviour_document_matches_independent_loaders() { #[cfg(unix)] #[test] +#[ignore = "full content root: CI and pr_ready run it"] fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() { let Some(base) = prepared() else { return }; let scratch = std::env::temp_dir().join(format!("horizon-json-reloads-{}", std::process::id())); @@ -535,6 +538,7 @@ fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() { /// A built root is kept for later starts, and built again when a mod's /// files change. #[test] +#[ignore = "full content root: CI and pr_ready run it"] fn content_root_is_reused_until_a_mod_changes() { let Some(base) = prepared() else { return; @@ -571,6 +575,7 @@ fn content_root_is_reused_until_a_mod_changes() { /// set, pool and templates join the bundles, and its biome tag keeps only /// what the loader knows. #[test] +#[ignore = "full content root: CI and pr_ready run it"] fn content_root_carries_a_structure_mod() { let Some(base) = prepared() else { return; diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index be8dc5837..a0a06a83a 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -55,6 +55,8 @@ pub struct MotionResources { /// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for. pub soul_speed_blocks: BTreeSet, pub fall_reset: BTreeSet, + /// `BlockTags.CRYSTAL_SOUND_BLOCKS`: blocks that chime under footsteps. + pub crystal_sound: BTreeSet, pub landing: BlockLandingRegistry, pub health: crate::health::HealthResources, pub fluids: FluidResources, @@ -115,6 +117,7 @@ impl MotionResources { glide_through: tag("minecraft:can_glide_through")?, soul_speed_blocks: tag("minecraft:soul_speed_blocks")?, fall_reset: tag("minecraft:fall_damage_resetting")?, + crystal_sound: tag("minecraft:crystal_sound_blocks")?, }) } } @@ -165,6 +168,11 @@ pub enum MotionEvent { state: BlockStateId, in_water: bool, }, + /// `Entity.playAmethystStepSound`: `block.amethyst_block.chime`. + Chime { + volume: f32, + pitch: f32, + }, /// `Entity.waterSwimSound`: `entity.player.swim`. Swim { volume: f32, @@ -280,6 +288,8 @@ pub struct PlayerMotion { pub pitch: f32, /// Gliding (shared flag 7) and LivingEntity.fallFlyTicks. pub fall_flying: bool, + /// Asleep in a bed (`LivingEntity.isSleeping`): the sleeping pose. + pub sleeping: bool, pub fall_fly_ticks: i32, /// The server saw the glide end last tick (`updateFallFlying`'s `canGlide` /// failed): the cleared flag reaches the client at its next tick. @@ -309,6 +319,10 @@ pub struct PlayerMotion { /// `Entity.moveDist`, `flyDist` and `nextStep`: footsteps come once per /// metre walked, not once per move. pub steps: MovementDistances, + /// `Entity.crystalSoundIntensity` and `lastCrystalSoundPlayTick`: the + /// amethyst chime grows with steps taken close together. + pub crystal_sound_intensity: f32, + pub last_crystal_sound_play_tick: i32, pub needs_sync: bool, pub sync_position: bool, /// Moved by an ender pearl (`ServerPlayer.teleport`): a server sends the @@ -476,6 +490,7 @@ impl PlayerMotion { glider: false, pitch: 0.0, fall_flying: false, + sleeping: false, fall_fly_ticks: 0, glide_ending: false, glider_wear: 0, @@ -501,6 +516,8 @@ impl PlayerMotion { next_step: 1.0, ..MovementDistances::default() }, + crystal_sound_intensity: 0.0, + last_crystal_sound_play_tick: 0, needs_sync: false, sync_position: false, teleported: false, @@ -2164,6 +2181,30 @@ impl MovementEmissionWorld for MotionWorld<'_, '_, '_> { state, in_water, }); + // Entity.walkingStepSound: the amethyst chime after the step. + let name = &self + .assets + .registry + .state(state) + .ok_or("missing scene state")? + .name; + let tick = self.player.health.tick_count; + if self.resources.crystal_sound.contains(name) + && tick >= self.player.last_crystal_sound_play_tick + 20 + { + // Entity.playAmethystStepSound (the level random stands in for + // the entity's). + let elapsed = f64::from(tick - self.player.last_crystal_sound_play_tick); + let decayed = self.player.crystal_sound_intensity * 0.997_f64.powf(elapsed) as f32; + let intensity = 1.0_f32.min(decayed + 0.07); + self.player.crystal_sound_intensity = intensity; + let pitch = 0.5 + intensity * self.scene.random.next_float() * 1.2; + let volume = 0.1 + intensity * 1.2; + self.player + .events + .push(MotionEvent::Chime { volume, pitch }); + self.player.last_crystal_sound_play_tick = tick; + } Ok(()) } fn step_event(&mut self, _: BlockStateId) -> Result<()> { @@ -4043,4 +4084,190 @@ mod tests { "{walked} steps over {metres} step-metres" ); } + /// Vanilla sprint is a state, not a held key: `LocalPlayer.aiStep` starts + /// it with the sprint key and stops it only on a vanilla stop condition. + /// Releasing the key while swimming keeps the sprint and its swim speed. + #[test] + fn a_sprint_survives_the_sprint_key_coming_up_while_swimming() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + // The same swim with the sprint key held, and with the key released + // once the sprint has started: the speed must not change. + let mut swims = Vec::new(); + for release in [false, true] { + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + for x in 19..=21 { + for y in 4..=8 { + for z in 19..=31 { + scene.set(x, y, z, water).unwrap(); + } + } + } + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + let mut speed = Vec::new(); + for tick in 0..12 { + // The key comes up on the fourth tick, after the sprint has + // started and the player swims. + let keys = if release && tick >= 4 { + forward + } else { + sprinting + }; + w.controlled_simulation_tick(keys).unwrap(); + speed.push(w.player.velocity.z); + } + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in water" + ); + assert!(w.player.swimming, "a sprinting player in water swims"); + swims.push(speed); + } + assert_eq!( + swims[0], swims[1], + "the swim speed must not drop when the sprint key comes up" + ); + } + + /// Vanilla: `LivingEntity.jumpFromGround` adds its 0.2 forward impulse + /// while the sprint state holds, so a jump taken after the sprint key + /// comes up is still a sprint jump. + #[test] + fn a_sprint_jump_keeps_its_impulse_when_the_sprint_key_comes_up() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + for _ in 0..20 { + w.controlled_simulation_tick(sprinting).unwrap(); + } + assert!(w.player.ground.on_ground, "the player settles on the floor"); + assert!(w.player.sprinting, "the sprint key starts the sprint"); + let running = w.player.velocity.z; + // The sprint key comes up and the player jumps. + w.controlled_simulation_tick(crate::sprint::Keys { + jump: true, + ..forward + }) + .unwrap(); + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in the air" + ); + assert!( + w.player.velocity.z > running + 0.05, + "the sprint jump keeps its forward impulse: {:?} vs {running}", + w.player.velocity + ); + } + + /// Vanilla `Player.getFlyingSpeed`: a flying player moves at the ability + /// speed, doubled while the sprint state holds. The sprint key starts the + /// state; releasing it does not change the speed. + #[test] + fn the_flight_speed_follows_the_sprint_state_not_the_sprint_key() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client") + .join(horizon_core::VANILLA_VERSION); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); + let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 10.0, 20.5)).unwrap(); + let mut w = MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + }; + w.player.may_fly = true; + w.player.flying = true; + let forward = crate::sprint::Keys { + forward: true, + ..Default::default() + }; + let sprinting = crate::sprint::Keys { + sprint: true, + ..forward + }; + assert_eq!( + w.flying_speed().unwrap(), + 0.05, + "a flying player without a sprint moves at the ability speed" + ); + // The sprint key starts the sprint, and the state doubles the speed. + w.controlled_simulation_tick(sprinting).unwrap(); + assert!(w.player.sprinting, "the sprint key starts the sprint"); + assert_eq!( + w.flying_speed().unwrap(), + 0.1, + "a sprinting player flies at twice the ability speed" + ); + // Releasing the sprint key keeps the state, so the speed stays. + w.controlled_simulation_tick(forward).unwrap(); + assert!( + w.player.sprinting, + "the sprint state survives the sprint key in the air" + ); + assert_eq!( + w.flying_speed().unwrap(), + 0.1, + "the flight speed follows the sprint state, not the sprint key" + ); + } } diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 34daaf85c..93364ed91 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -68,6 +68,9 @@ pub enum Event { host: String, port: i32, }, + /// `ClientboundServerLinksPacket`: the links the pause menu's "Server + /// Links..." lists (ClientCommonPacketListenerImpl.handleServerLinks). + ServerLinks(Vec), /// The connection ended. `from_server`: the server gave the reason (or /// the connection was refused for good), rather than the connection /// failing (auto-reconnect retries only failures and shutdowns). @@ -565,6 +568,9 @@ fn receive_play( play::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + play::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } // ClientCommonPacketListenerImpl.handleTransfer: the connection // ends and the game connects to the other address. play::Clientbound::Transfer(p) => { @@ -644,6 +650,9 @@ fn configure( cfg::Clientbound::StoreCookie(p) => { cookies.lock().unwrap().insert(p.key, p.payload); } + cfg::Clientbound::ServerLinks(p) => { + let _ = send.send(Event::ServerLinks(p.links)); + } cfg::Clientbound::Transfer(p) => { let _ = send.send(Event::Transfer { host: p.host, diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index a40d11258..85882009f 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -56,6 +56,7 @@ pub enum Opt { ChatVisibility, ChatColors, ChatLinks, + ChatLinksPrompt, ChatOpacity, TextBackgroundOpacity, ChatScale, @@ -243,6 +244,7 @@ impl Opt { Opt::ChatVisibility => "options.chat.visibility", Opt::ChatColors => "options.chat.color", Opt::ChatLinks => "options.chat.links", + Opt::ChatLinksPrompt => "options.chat.links.prompt", Opt::ChatOpacity => "options.chat.opacity", Opt::TextBackgroundOpacity => "options.accessibility.text_background_opacity", Opt::ChatScale => "options.chat.scale", @@ -581,6 +583,7 @@ impl Opt { ][usize::from(s.chat_visibility.min(2))]), Opt::ChatColors => on_off(s.chat_colors), Opt::ChatLinks => on_off(s.chat_links), + Opt::ChatLinksPrompt => on_off(s.chat_links_prompt), Opt::AutoSuggestions => on_off(s.auto_suggestions), Opt::ReducedDebugInfo => on_off(s.reduced_debug_info), Opt::HighContrast => on_off(s.high_contrast), @@ -692,6 +695,7 @@ impl Opt { | Opt::CutoutLeaves | Opt::ImprovedTransparency | Opt::MenuBlur + | Opt::ChunkBuilder ) } /// Advance a cycle button (CycleButton.cycleValue). @@ -755,6 +759,7 @@ impl Opt { Opt::ChatVisibility => s.chat_visibility = next(s.chat_visibility, 3), Opt::ChatColors => s.chat_colors = !s.chat_colors, Opt::ChatLinks => s.chat_links = !s.chat_links, + Opt::ChatLinksPrompt => s.chat_links_prompt = !s.chat_links_prompt, Opt::AutoSuggestions => s.auto_suggestions = !s.auto_suggestions, Opt::ReducedDebugInfo => s.reduced_debug_info = !s.reduced_debug_info, Opt::HighContrast => s.high_contrast = !s.high_contrast, @@ -1507,6 +1512,7 @@ impl OptionsUi { Opt::ChatVisibility, Opt::ChatColors, Opt::ChatLinks, + Opt::ChatLinksPrompt, Opt::ChatOpacity, Opt::TextBackgroundOpacity, Opt::ChatScale, diff --git a/crates/horizon-client/src/pose.rs b/crates/horizon-client/src/pose.rs index e34b1f1fc..2a01579f3 100644 --- a/crates/horizon-client/src/pose.rs +++ b/crates/horizon-client/src/pose.rs @@ -15,8 +15,21 @@ pub enum Pose { Swimming, FallFlying, SpinAttack, + Sleeping, } impl Pose { + /// `Pose` by its network id (`Pose.id`); the poses a player never takes + /// are standing. + pub fn from_id(id: i32) -> Self { + match id { + 1 => Self::FallFlying, + 2 => Self::Sleeping, + 3 => Self::Swimming, + 4 => Self::SpinAttack, + 5 => Self::Crouching, + _ => Self::Standing, + } + } pub fn name(self) -> &'static str { match self { Self::Standing => "STANDING", @@ -24,18 +37,24 @@ impl Pose { Self::Swimming => "SWIMMING", Self::FallFlying => "FALL_FLYING", Self::SpinAttack => "SPIN_ATTACK", + Self::Sleeping => "SLEEPING", } } + /// `Avatar.POSES` (and `LivingEntity.SLEEPING_DIMENSIONS`): the box of a + /// player or mannequin in this pose; sleeping ignores the scale. pub fn dimensions(self, scale: f32) -> Dimensions { - let (height, eye_height) = match self { - Self::Standing => (1.8, 1.62), - Self::Crouching => (1.5, 1.27), - Self::Swimming | Self::FallFlying | Self::SpinAttack => (0.6, 0.4), + let (width, height, eye_height) = match self { + Self::Standing => (0.6 * scale, 1.8 * scale, 1.62 * scale), + Self::Crouching => (0.6 * scale, 1.5 * scale, 1.27 * scale), + Self::Swimming | Self::FallFlying | Self::SpinAttack => { + (0.6 * scale, 0.6 * scale, 0.4 * scale) + } + Self::Sleeping => (0.2, 0.2, 0.2), }; Dimensions { - width: 0.6 * scale, - height: height * scale, - eye_height: eye_height * scale, + width, + height, + eye_height, } } } @@ -73,6 +92,19 @@ impl PlayerMotion { } Ok(()) } + /// `LivingEntity.startSleeping` and `stopSleeping` set the pose at once + /// (the 0.2 box in the bed, standing again after). + pub fn set_sleeping(&mut self, sleeping: bool) -> Result<()> { + if self.sleeping != sleeping { + self.sleeping = sleeping; + self.set_pose(if sleeping { + Pose::Sleeping + } else { + Pose::Standing + })?; + } + Ok(()) + } pub fn moving_slowly(&self) -> bool { self.local_crouching || (self.pose == Pose::Swimming && !self.fluids.was_touching_water) } @@ -100,8 +132,10 @@ impl MotionWorld<'_, '_, '_> { if !self.can_fit_pose(Pose::Swimming)? { return Ok(()); } - // Player.getDesiredPose: swimming, gliding, Riptide's spin. - let desired = if self.player.swimming { + // Player.getDesiredPose: sleeping, swimming, gliding, Riptide's spin. + let desired = if self.player.sleeping { + Pose::Sleeping + } else if self.player.swimming { Pose::Swimming } else if self.player.fall_flying { Pose::FallFlying diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index aae9b296b..b3e9938c9 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -109,6 +109,9 @@ pub struct Projectile { pub arrow: Option>, /// `AbstractHurtingProjectile.accelerationPower`. pub acceleration: f64, + /// `Entity.needsSync`: a server tells its clients about the change this + /// tick instead of at the next update interval. + pub needs_sync: bool, } /// What a projectile struck this tick. #[derive(Clone, Copy, Debug, PartialEq)] @@ -173,6 +176,7 @@ impl Projectile { left_owner: false, bonus: Default::default(), acceleration: 0.1, + needs_sync: false, arrow: kind_is_arrow.then(|| { // Entity.random: seeded unpredictably, the position stands in. Box::new(crate::arrows::ArrowState::new( diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dc08d90b0..b6f4c1322 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -2742,7 +2742,7 @@ pub struct Level { pub xp_seed: i32, /// ServerPlayer.seenCredits: the end poem has been shown. pub seen_credits: bool, - /// Player.active_effects: (id, duration, amplifier, ambient, show_icon). + /// Player.active_effects: (id, duration, amplifier, ambient, show_particles). pub active_effects: Vec<(String, i32, i32, bool, bool)>, /// Player.EnderItems: the ender chest inventory (27 slots). pub ender_items: Vec>, @@ -3022,7 +3022,7 @@ impl Level { get("duration").unwrap_or(0) as i32, get("amplifier").unwrap_or(0) as i32, get("ambient").unwrap_or(0) != 0, - get("show_icon").is_none_or(|v| v != 0), + get("show_particles").is_none_or(|v| v != 0), )) }) .collect(), @@ -3124,14 +3124,14 @@ impl Level { Tag::List( self.active_effects .iter() - .map(|(id, duration, amplifier, ambient, icon)| { + .map(|(id, duration, amplifier, ambient, particles)| { Tag::compound([ ("id", string(id)), ("duration", Tag::Int(*duration)), ("amplifier", Tag::Byte(*amplifier as i8)), ("ambient", Tag::Byte(i8::from(*ambient))), - ("show_particles", Tag::Byte(1)), - ("show_icon", Tag::Byte(i8::from(*icon))), + ("show_particles", Tag::Byte(i8::from(*particles))), + ("show_icon", Tag::Byte(i8::from(*particles))), ]) }) .collect(), @@ -3820,6 +3820,9 @@ impl ChunkGenerator for Persistent { fn is_decorated(&self, proto: &crate::streaming::Proto) -> bool { self.inner.is_decorated(proto) } + fn light_view(&self, proto: &crate::streaming::Proto) -> Option { + self.inner.light_view(proto) + } fn save_protos(&self, protos: &[&crate::streaming::Proto]) { self.save .tables diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 2308794d3..09d7ae3ff 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -145,6 +145,7 @@ pub struct Settings { pub chat_visibility: u8, pub chat_colors: bool, pub chat_links: bool, + pub chat_links_prompt: bool, pub chat_opacity: f32, pub text_background_opacity: f32, pub chat_scale: f32, @@ -230,6 +231,7 @@ impl Default for Settings { chat_visibility: 0, chat_colors: true, chat_links: true, + chat_links_prompt: true, chat_opacity: 1.0, text_background_opacity: 0.5, chat_scale: 1.0, @@ -423,6 +425,7 @@ impl Settings { chat_visibility: f.int("chatVisibility") as u8, chat_colors: f.bool("chatColors"), chat_links: f.bool("chatLinks"), + chat_links_prompt: f.bool("chatLinksPrompt"), chat_opacity: f.double("chatOpacity") as f32, text_background_opacity: f.double("textBackgroundOpacity") as f32, chat_scale: f.double("chatScale") as f32, @@ -506,6 +509,7 @@ impl Settings { put_i(&mut f, "chatVisibility", i32::from(self.chat_visibility)); put_b(&mut f, "chatColors", self.chat_colors); put_b(&mut f, "chatLinks", self.chat_links); + put_b(&mut f, "chatLinksPrompt", self.chat_links_prompt); put_f(&mut f, "chatOpacity", self.chat_opacity); put_f( &mut f, diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index ce69be8ce..33c4bb933 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -52,8 +52,9 @@ pub fn thread_cpu() -> Option { Some(Duration::new(t.tv_sec as u64, t.tv_nsec as u32)) } #[cfg(not(unix))] - None + horizon_threads::thread_cpu() } + /// The frame's spans, summed by name, slowest first; clears them. pub fn take() -> Vec { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); @@ -135,7 +136,7 @@ mod tests { /// The thread's CPU clock moves with work done on it, not with time /// spent asleep. - #[cfg(unix)] + #[cfg(any(unix, all(windows, target_arch = "x86_64")))] #[test] fn thread_cpu_counts_work_not_sleep() { let start = super::thread_cpu().unwrap(); diff --git a/crates/horizon-client/src/sprites.rs b/crates/horizon-client/src/sprites.rs index 6d754894a..b720c5bfd 100644 --- a/crates/horizon-client/src/sprites.rs +++ b/crates/horizon-client/src/sprites.rs @@ -342,10 +342,25 @@ pub(crate) fn test_frames(layer: u32, frames: Vec>, metadata: &str) -> S } } +/// How many reduced copies a sprite atlas keeps: the Mipmap Levels option plus the +/// resampling-only levels an upscaled pack needs, within what the atlas holds. +pub(crate) fn sprite_mipmap_limit(requested: u32, size: u32, minimum: u32, available: u32) -> u32 { + // Only the atlas native minimum determines how many resampling-only mips to skip. + let upscale = (size / minimum.max(1)).max(1).ilog2(); + requested.saturating_add(upscale).min(available - 1) +} + #[cfg(test)] mod tests { use super::*; #[test] + fn mipmap_option_keeps_real_16px_reductions() { + for levels in 0..=4 { + assert_eq!(sprite_mipmap_limit(levels, 32, 16, 6), levels + 1); + assert_eq!(sprite_mipmap_limit(levels, 16, 16, 5), levels); + } + } + #[test] fn identical_still_textures_share_a_layer() { let root = std::env::temp_dir().join(format!("horizon-sprite-share-{}", std::process::id())); @@ -398,7 +413,7 @@ mod tests { assert_eq!((sprites.size, sprites.minimum_size), (32, 32)); for level in 0..=4 { assert_eq!( - crate::gfx::sprite_mipmap_limit(level, sprites.size, sprites.minimum_size, 6), + sprite_mipmap_limit(level, sprites.size, sprites.minimum_size, 6), level ); } @@ -408,7 +423,7 @@ mod tests { sprites.finish(); assert_eq!((sprites.size, sprites.minimum_size), (32, 16)); assert_eq!( - crate::gfx::sprite_mipmap_limit(0, sprites.size, sprites.minimum_size, 6), + sprite_mipmap_limit(0, sprites.size, sprites.minimum_size, 6), 1 ); } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index c0a96f504..619a0202c 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -70,6 +70,11 @@ pub trait ChunkGenerator: Send + Sync + 'static { false } /// What to save of a proto chunk dropped before it became final. + /// A decorated proto chunk's blocks as a column, to light a finished + /// neighbour against (vanilla lights with neighbours at FEATURES). + fn light_view(&self, _proto: &Proto) -> Option { + None + } fn saved_proto(&self, _proto: &Proto) -> Option { None } @@ -212,6 +217,7 @@ struct Shared { } pub struct Streaming { shared: Arc, + light_view: Arc Option + Send + Sync>, results: mpsc::Receiver, threads: Vec>, order: u64, @@ -539,8 +545,13 @@ impl Streaming { .expect("spawn worker") }) .collect(); + let light_view = { + let generator = generator.clone(); + Arc::new(move |p: &Proto| generator.light_view(p)) + }; Self { shared, + light_view, results, threads, order: 0, @@ -779,6 +790,26 @@ impl Streaming { fn distance(&self, x: i32, z: i32) -> i64 { self.ranges().priority(x, z, self.loading) } + /// The 3x3 a light job reads: the finished columns, and for a neighbour + /// that will not finish (past the area), its decorated proto chunk, as + /// vanilla lights its last FULL ring against neighbours at FEATURES. + fn light_region(&self, world: &World, x: i32, z: i32) -> Option> { + let mut region: Region = Default::default(); + for dz in 0..3 { + for dx in 0..3 { + let n = (x + dx as i32 - 1, z + dz as i32 - 1); + region[dz][dx] = Some(match world.chunks.get(&n) { + Some(chunk) => chunk.clone(), + None if !self.in_range(n.0, n.1, 1) && self.decorated.contains(&n) => { + let proto = self.protos.get(&n)?.as_ref()?; + Arc::new((self.light_view)(proto)?) + } + None => return None, + }); + } + } + Some(Box::new(region)) + } fn region(world: &World, x: i32, z: i32) -> Option> { let mut region: Region = Default::default(); for dz in 0..3 { @@ -900,6 +931,11 @@ impl Streaming { } else { apply_relighting(chunk, sections, &mut changed); } + // Saved unlit (at the edge of what was loaded), or its light + // changed: saved again. + if (first && !chunk.light_loaded) || !changed.is_empty() { + world.modified.insert((x, z)); + } chunk.lit = true; if first { for dz in -1..=1 { @@ -1136,7 +1172,7 @@ impl Streaming { world.dirty_light.remove(&(x, z)); continue; } - let Some(region) = Self::region(world, x, z) else { + let Some(region) = self.light_region(world, x, z) else { continue; }; world.dirty_light.remove(&(x, z)); @@ -1468,7 +1504,7 @@ impl Streaming { counts[1] += 1; } else { counts[2] += 1; - if Self::region(world, key.0, key.1).is_some() { + if self.light_region(world, key.0, key.1).is_some() { world.dirty_light.insert(key); } } diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index c0cf44bb5..3aea6fc1a 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -258,7 +258,7 @@ fn sky_along_ray(d: vec3) -> vec3 { } // rendertype_lines.vsh: screen-space stroke and camera-space depth separation. -fn outline_clip(vertex: u32, start: vec3, end: vec3) -> vec4 { +fn outline_clip(vertex: u32, start: vec3, end: vec3, width: f32) -> vec4 { let position = select(start, end, vertex >= 2u); let normal = normalize(end - start); let view_shrink = 1.0 - 1.0 / 256.0; @@ -268,7 +268,7 @@ fn outline_clip(vertex: u32, start: vec3, end: vec3) -> vec4 { let ndc2 = line_end.xyz / line_end.w; let screen = globals.outline_params.xy; let direction = normalize((ndc2.xy - ndc1.xy) * screen); - var offset = vec2(-direction.y, direction.x) * globals.outline_params.z / screen; + var offset = vec2(-direction.y, direction.x) * width / screen; if offset.x < 0.0 { offset = -offset; } if vertex % 2u != 0u { offset = -offset; } return vec4((ndc1 + vec3(offset, 0.0)) * line_start.w, line_start.w); @@ -277,18 +277,22 @@ struct LineOut { @builtin(position) clip: vec4, @location(0) spherical: f32, @location(1) cylindrical: f32, + @location(2) color: vec4, } @vertex fn vs_line(@builtin(vertex_index) vertex: u32, - @location(0) start: vec3, @location(1) end: vec3) -> LineOut { + @location(0) start: vec3, @location(1) end: vec3, + @location(2) argb: vec4, @location(3) width: f32) -> LineOut { let position = select(start, end, vertex >= 2u); var out: LineOut; - out.clip = outline_clip(vertex, start, end); + out.clip = outline_clip(vertex, start, end, width); out.spherical = length(position); out.cylindrical = max(length(position.xz), abs(position.y)); + // ARGB in a little-endian u32 reads as B, G, R, A. + out.color = argb.zyxw; return out; } @fragment fn fs_line(in: LineOut) -> @location(0) vec4 { - return apply_fog(vec4(0.0, 0.0, 0.0, 0.4), in.spherical, in.cylindrical); + return apply_fog(in.color, in.spherical, in.cylindrical); } // Gizmo lines (rendertype_lines with a per-vertex colour and LineWidth in // pixels; no layering transform). diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 87bd05fd0..9984cdcdf 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1,6 +1,7 @@ //! Title, world selection and world creation screens (TitleScreen, //! SelectWorldScreen, CreateWorldScreen layouts), drawn as HUD quads. use crate::{ + game_rules_screen::{Exit, RulesScreen}, hud::{HudAtlas, HudBatch, rgba}, lang, save::Level, @@ -144,6 +145,8 @@ pub struct Title { splash: Option, /// The saves listed for Home, re-read every couple of seconds. recent: std::cell::RefCell)>>, + /// WorldCreationGameRulesScreen, over Create New World while it is open. + rules: RefCell>, } pub(crate) struct Button { x: f32, @@ -252,6 +255,7 @@ impl Title { (today.month(), today.day()), ), recent: std::cell::RefCell::new(None), + rules: RefCell::new(None), } } /// Vanilla bypasses the selector when there are no saves. @@ -360,6 +364,9 @@ impl Title { } /// The pointer moved with the button held (`mouseDragged`). pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { + if let Some(rules) = self.rules.get_mut() { + return rules.drag(cursor.1, size.1.ceil()); + } if let Mode::Multiplayer(screen) = &mut self.mode { return screen.drag(cursor.1, size); } @@ -372,6 +379,9 @@ impl Title { } /// The button was released (`onRelease`). pub fn release(&mut self) { + if let Some(rules) = self.rules.get_mut() { + rules.release(); + } if let Mode::Multiplayer(screen) = &mut self.mode { screen.release(); } @@ -379,6 +389,9 @@ impl Title { } /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Some(rules) = self.rules.get_mut() { + return rules.wheel(delta, size.1.ceil()); + } if let Mode::Multiplayer(screen) = &mut self.mode { screen.wheel(delta, cursor, size); return; @@ -566,6 +579,10 @@ impl Title { folder } fn buttons(&self, w: f32, h: f32) -> Vec