From 18dc7e7d8a36c49c15e52737cbcd4b4541411b1a Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:38:12 -0400 Subject: [PATCH 01/23] Handle fullscreen shortcut before screen input --- crates/horizon-client/src/game.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index a54a3b38c..cf66729d2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9015,6 +9015,20 @@ impl ApplicationHandler for Game<'_> { if let WindowEvent::ModifiersChanged(m) = &event { self.modifiers = m.state(); } + // Fullscreen is a window shortcut, before screens consume keyboard input. + if let WindowEvent::KeyboardInput { event, .. } = &event + && event.state == ElementState::Pressed + && let PhysicalKey::Code(key) = event.physical_key + && horizon_client::keybinds::key_name(key) + == Some(self.settings.keys.get("key.fullscreen")) + && !(self.screen == Screen::Options && self.options_waiting_for_key()) + { + self.last_input = Instant::now(); + if !event.repeat { + self.toggle_fullscreen(); + } + return; + } // KeyboardHandler.keyPress: the debug keys come before the game's. if let WindowEvent::KeyboardInput { event: key_event, .. From e86b05333e0c5f88e1ce4a85e32d83dbad477f8a Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:40:17 -0400 Subject: [PATCH 02/23] Keep cloud alpha independent of face shading --- crates/horizon-client/src/clouds.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/clouds.rs b/crates/horizon-client/src/clouds.rs index 6e9f19ca2..70f29c132 100644 --- a/crates/horizon-client/src/clouds.rs +++ b/crates/horizon-client/src/clouds.rs @@ -120,8 +120,9 @@ impl Input<'_> { bottom: bottom + 4.0 >= 0.0, }; let colors = [1.0, 0.7, 0.8, 0.9].map(|shade| { - self.color - .map(|v| ((v * shade).clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0) + let [r, g, b, a] = self.color; + [r * shade, g * shade, b * shade, a] + .map(|v| (v.clamp(0.0, 1.0) * 255.0) as u8 as f32 / 255.0) }); ( key, @@ -249,8 +250,11 @@ mod tests { assert_eq!(uniform.offset[1], (192.33 - input.camera.y) as f32); assert_eq!( uniform.colors[1], - [0.8, 0.7, 0.6, 0.5].map(|v| ((v * 0.7f32) * 255.0) as u8 as f32 / 255.0) + [0.8 * 0.7, 0.7 * 0.7, 0.6 * 0.7, 0.5].map(|v| (v * 255.0) as u8 as f32 / 255.0) ); + for color in uniform.colors { + assert_eq!(color[3], 127.0 / 255.0); + } } for (x, y, z, range, fast) in [ (13.0, 101.0, 1.0, 2, false), From 65f9819686fe5b59ca6220b18cc63a71ab5f4739 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 11:43:31 -0400 Subject: [PATCH 03/23] Limit Classic graphics submenus to additional settings --- crates/horizon-client/src/graphics_ui.rs | 75 ++++++++++++++++++++---- 1 file changed, 64 insertions(+), 11 deletions(-) diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index c03041152..745cd5d80 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -265,6 +265,24 @@ pub fn rows(level: Level) -> Vec { const UPLOAD_STEPS: [u32; 8] = [0, 256, 512, 1024, 2048, 4096, 8192, 16384]; +/// Classic's submenus supplement the vanilla options on their parent screens. +fn extra_rows(level: Level) -> Vec { + let mut rows = rows(level); + rows.retain(|row| !matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_)))); + // Drop headings whose settings were all on the parent screens. + let mut has_setting = false; + rows.reverse(); + rows.retain(|row| match row { + Row::Setting(_) => { + has_setting = true; + true + } + Row::Header(_) => std::mem::take(&mut has_setting), + }); + rows.reverse(); + rows +} + fn on_off(on: bool) -> &'static str { if on { "On" } else { "Off" } } @@ -539,7 +557,7 @@ impl GraphicsUi { (STYLE.band, h - STYLE.band) } fn content_height(level: Level) -> f32 { - rows(level).iter().fold(4.0, |height, row| { + extra_rows(level).iter().fold(4.0, |height, row| { height + match row { Row::Header(_) => STYLE.header_height, @@ -561,7 +579,7 @@ impl GraphicsUi { let mut y = top + 4.0 - self.scroll; let mut widgets = Vec::new(); let mut headers = Vec::new(); - for row in rows(level) { + for row in extra_rows(level) { match row { Row::Header(name) => { headers.push((y, name)); @@ -625,7 +643,7 @@ impl GraphicsUi { STYLE.header(batch, atlas, &Text::literal(name), x, y); } } - let descriptions: Vec<(Cost, &'static str)> = rows(level) + let descriptions: Vec<(Cost, &'static str)> = extra_rows(level) .into_iter() .filter_map(|r| match r { Row::Setting(s) => Some((s.cost, s.text)), @@ -766,18 +784,34 @@ mod tests { let mut s = Settings::default(); let mut ui = GraphicsUi::default(); let size = (480.0, 320.0); - let (widgets, _, _) = ui.layout(Level::Simple, size.0, size.1); + let (widgets, _, _) = ui.layout(Level::Advanced, size.0, size.1); let button = widgets .iter() .find(|w| matches!(w.target, Target::Button(_))) .unwrap(); let point = (button.x + 1.0, button.y + 1.0); assert!( - ui.click(Level::Simple, &mut s, point, size, [854, 480], false, true) - .is_empty() + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + true + ) + .is_empty() ); assert_eq!( - ui.click(Level::Simple, &mut s, point, size, [854, 480], false, false)[0], + ui.click( + Level::Advanced, + &mut s, + point, + size, + [854, 480], + false, + false + )[0], Action::ButtonClick ); assert!(!ui.release()); @@ -787,7 +821,7 @@ mod tests { .unwrap(); assert_eq!( ui.click( - Level::Simple, + Level::Advanced, &mut s, (slider.x + 1.0, slider.y + 1.0), size, @@ -799,7 +833,7 @@ mod tests { ); assert_eq!( ui.click( - Level::Simple, + Level::Advanced, &mut s, (-100.0, -100.0), size, @@ -817,7 +851,7 @@ mod tests { fn scrolling_stops_at_both_limits_before_layout() { for level in [Level::Simple, Level::Advanced] { let mut ui = GraphicsUi::default(); - let h = 120.0; + let h = 2.0 * STYLE.band + 10.0; let (top, bottom) = GraphicsUi::bounds(h); let max = GraphicsUi::content_height(level) - (bottom - top); assert!(max > 4.5); @@ -841,7 +875,7 @@ mod tests { fn resizing_clamps_before_positioning_graphics_rows() { for level in [Level::Simple, Level::Advanced] { let mut ui = GraphicsUi::default(); - ui.scroll(level, 120.0, -1000.0); + ui.scroll(level, 2.0 * STYLE.band + 10.0, -1000.0); assert!(ui.scroll > 0.0); let (widgets, headers, _) = ui.layout(level, 480.0, 4000.0); assert_eq!(ui.scroll, 0.0); @@ -858,6 +892,25 @@ mod tests { } } + #[test] + fn classic_submenus_only_add_horizon_settings_without_empty_groups() { + for level in [Level::Simple, Level::Advanced] { + let rows = extra_rows(level); + assert!(rows.iter().any(|row| matches!(row, Row::Setting(_)))); + for (i, row) in rows.iter().enumerate() { + match row { + Row::Setting(s) => assert!(matches!(s.item, Item::Horizon(_))), + Row::Header(_) => assert!(matches!(rows.get(i + 1), Some(Row::Setting(_)))), + } + } + assert!( + super::rows(level).iter().any( + |row| matches!(row, Row::Setting(s) if matches!(s.item, Item::Vanilla(_))) + ) + ); + } + } + #[test] fn every_advanced_setting_has_a_description() { for level in [Level::Simple, Level::Advanced] { From b9d6d1c7d91b7654f63fa1d58903b666af747c6c Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 15:24:11 +0200 Subject: [PATCH 04/23] Stronghold ring searches run on every worker that needs them The 128 stronghold ring positions each need a biome search over a 57x57 quart area. The first worker to ask computed all of them inside a OnceLock while every other worker blocked on it: about 2 s on an M4 Pro with 12 of 13 workers idle, after every world load and every return to the Overworld. Vanilla's generateRingPositions runs each search as its own task on the background executor. Now the ring chunks and search randoms are planned serially (cheap), and every thread that needs the rings takes searches until none are left, then waits for the rest. Positions are unchanged: each search only uses its own forked random. Co-Authored-By: Claude Opus 5.5 --- .../src/worldgen/generator_structures.rs | 153 ++++++++++++++++-- .../src/worldgen/structure/start.rs | 48 +++--- .../src/worldgen/structure/stronghold.rs | 61 +++++-- 3 files changed, 211 insertions(+), 51 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 8a5f15d65..76b4d39c9 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -5,7 +5,10 @@ use super::{ generator::{GeneratorData, GeneratorError}, structure::{ StructureResources, - start::{Rings, StructureRegistry, StructureStart, beardifier, create_starts}, + start::{ + Rings, StartContext, StructureRegistry, StructureStart, beardifier, create_starts, + }, + stronghold::RingSearch, }, }; use horizon_core::{density::Beardifier, position::ChunkPos}; @@ -13,7 +16,10 @@ use serde_json::Value; use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, - sync::{Arc, Mutex, OnceLock}, + sync::{ + Arc, Condvar, Mutex, OnceLock, + atomic::{AtomicUsize, Ordering}, + }, }; pub(super) type Starts = Arc>>; @@ -27,6 +33,78 @@ pub(super) struct StructureState { starts: Mutex>, /// Concentric ring positions, computed on first use. rings: OnceLock, + /// Their biome searches while they are computed. + ring_work: OnceLock, +} + +/// generateRingPositions' biome searches, shared out. Vanilla runs each as +/// its own task on its worker pool; here every thread that needs the rings +/// before they exist takes searches until none are left, then waits for the +/// ones others took. Done by the first thread alone, the 128 stronghold +/// searches kept every other worker blocked for seconds after each world load. +struct RingWork { + /// The concentric-ring sets, some with no positions. + sets: Vec, + /// Set index and search, sets in `possible_sets` order. + searches: Vec<(usize, RingSearch)>, + next: AtomicUsize, + found: Vec>, + left: Mutex, + finished: Condvar, +} +impl RingWork { + fn new(sets: Vec<(usize, Vec)>) -> Self { + let indices = sets.iter().map(|(set, _)| *set).collect(); + let searches: Vec<(usize, RingSearch)> = sets + .into_iter() + .flat_map(|(set, searches)| searches.into_iter().map(move |s| (set, s))) + .collect(); + Self { + sets: indices, + next: AtomicUsize::new(0), + found: (0..searches.len()).map(|_| OnceLock::new()).collect(), + left: Mutex::new(searches.len()), + finished: Condvar::new(), + searches, + } + } + /// Run searches until none are left to take, then wait for the rest. + fn help<'a>( + &self, + preferred: impl Fn(usize) -> &'a BTreeSet, + biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + ) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some((set, search)) = self.searches.get(i) else { + break; + }; + let _ = self.found[i].set(search.find(preferred(*set), biome)); + let mut left = self.left.lock().unwrap(); + *left -= 1; + if *left == 0 { + self.finished.notify_all(); + } + } + let mut left = self.left.lock().unwrap(); + while *left > 0 { + left = self.finished.wait(left).unwrap(); + } + } + /// The positions by set name, once every search is done. + fn rings(&self, name: impl Fn(usize) -> String) -> Rings { + let mut rings: Rings = self + .sets + .iter() + .map(|&set| (name(set), Vec::new())) + .collect(); + for ((set, _), found) in self.searches.iter().zip(&self.found) { + if let Some(positions) = rings.get_mut(&name(*set)) { + positions.push(*found.get().expect("every search finished")); + } + } + rings + } } const START_CACHE_LIMIT: usize = 65536; @@ -89,6 +167,7 @@ impl StructureState { by_step, starts: Mutex::new(HashMap::new()), rings: OnceLock::new(), + ring_work: OnceLock::new(), })) } /// Concentric ring positions of a structure set, once the first start @@ -96,6 +175,25 @@ impl StructureState { pub(super) fn cached_rings(&self, set: &str) -> Option> { self.rings.get().and_then(|rings| rings.get(set).cloned()) } + /// The concentric ring positions, computing them with the threads that + /// need them first (see `RingWork`). + fn rings(&self, context: &mut impl StartContext) -> &Rings { + if let Some(rings) = self.rings.get() { + return rings; + } + let work = self.ring_work.get_or_init(|| { + RingWork::new( + self.registry + .ring_searches(&self.possible_sets, context.seed()), + ) + }); + let registry = &self.registry; + work.help(|set| registry.ring_biomes(set), &mut |q| { + context.noise_biome(q) + }); + self.rings + .get_or_init(|| work.rings(|set| registry.sets[set].name.clone())) + } /// Drop the cached starts, so that later chunks build fresh pieces (the /// pieces keep per-start placement state such as a shipwreck's height). pub(super) fn forget_starts(&self) { @@ -110,11 +208,7 @@ impl StructureState { if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) { return found.clone(); } - let rings = self.rings.get_or_init(|| { - let seed = context.seed(); - self.registry - .ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q)) - }); + let rings = self.rings(context); let starts: Starts = Arc::new( create_starts( &self.registry, @@ -148,13 +242,7 @@ impl StructureState { radius: i32, ) -> Option<(String, [i32; 3])> { let seed = context.seed(); - let rings = self - .rings - .get_or_init(|| { - self.registry - .ring_positions(&self.possible_sets, seed, &mut |q| context.noise_biome(q)) - }) - .clone(); + let rings = self.rings(context).clone(); let wanted = |s: usize| names.iter().any(|n| *n == self.registry.structures[s].name); let dist = |p: [i32; 3]| { let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2])); @@ -288,3 +376,40 @@ impl StructureState { beardifier(&self.registry, references, chunk) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::worldgen::structure::stronghold::{ring_positions, ring_searches}; + + /// Searches shared between threads give the positions of one thread + /// running them in order, set by set. + #[test] + fn ring_work_shared_between_threads_matches_serial_search() { + let preferred: BTreeSet = (0..20).map(|b| BiomeId(b * 3)).collect(); + let biome = |q: [i32; 3]| { + BiomeId((q[0].wrapping_mul(31) ^ q[2].wrapping_mul(17)).rem_euclid(64) as u32) + }; + let none = BTreeSet::new(); + for seed in [0, 1234, -77, i64::MAX] { + let work = RingWork::new(vec![ + (0, ring_searches(seed, 32, 3, 128)), + (1, ring_searches(seed ^ 5, 10, 4, 0)), + (2, ring_searches(seed + 1, 20, 5, 40)), + ]); + let sets = [&preferred, &none, &preferred]; + std::thread::scope(|scope| { + for _ in 0..4 { + scope.spawn(|| work.help(|set| sets[set], &mut { biome })); + } + }); + let rings = work.rings(|set| format!("set{set}")); + let serial = |s: i64, distance, spread, count, preferred| { + ring_positions(s, distance, spread, count, preferred, &mut { biome }) + }; + assert_eq!(rings["set0"], serial(seed, 32, 3, 128, &preferred)); + assert_eq!(rings["set1"], Vec::new()); + assert_eq!(rings["set2"], serial(seed + 1, 20, 5, 40, &preferred)); + } + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 1526e08ed..1b443eba5 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -299,31 +299,37 @@ impl StructureRegistry { pools: Pools::new(pools), }) } - /// ChunkGeneratorStructureState ring positions of the concentric-ring - /// sets among `possible_sets`. - pub fn ring_positions( + /// ChunkGeneratorStructureState.generatePositions: the ring positions of + /// each concentric-ring set among `possible_sets` before their biome + /// searches (set index, searches in order). + pub fn ring_searches( &self, possible_sets: &[usize], seed: i64, - biome: &mut dyn FnMut([i32; 3]) -> BiomeId, - ) -> Rings { - let mut rings = Rings::new(); - for &i in possible_sets { - let set = &self.sets[i]; - if let Placement::ConcentricRings { - distance, - spread, - count, - preferred, - } = &set.placement - { - let positions = super::stronghold::ring_positions( - seed, *distance, *spread, *count, preferred, biome, - ); - rings.insert(set.name.clone(), positions); - } + ) -> Vec<(usize, Vec)> { + possible_sets + .iter() + .filter_map(|&i| match &self.sets[i].placement { + Placement::ConcentricRings { + distance, + spread, + count, + .. + } => Some(( + i, + super::stronghold::ring_searches(seed, *distance, *spread, *count), + )), + _ => None, + }) + .collect() + } + /// The preferred biomes of a concentric-ring set (empty for others). + pub fn ring_biomes(&self, set: usize) -> &BTreeSet { + static NONE: BTreeSet = BTreeSet::new(); + match &self.sets[set].placement { + Placement::ConcentricRings { preferred, .. } => preferred, + _ => &NONE, } - rings } /// RandomSpreadStructurePlacement.getPotentialStructureChunk et al. /// RandomSpreadStructurePlacement.getPotentialStructureChunk for the diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index eb31e0627..270b412af 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -22,20 +22,30 @@ pub fn ring_positions( preferred: &BTreeSet, biome: &mut dyn FnMut([i32; 3]) -> BiomeId, ) -> Vec { - let mut random = LegacyRandom::new(seed); - let mut angle = random.next_double() * PI * 2.0; - let (mut in_circle, mut circle, mut spread) = (0, 0, spread); - let mut out = Vec::with_capacity(count.max(0) as usize); - for i in 0..count { - let dist = f64::from(4 * distance + distance * circle * 6) - + (random.next_double() - 0.5) * (f64::from(distance) * 2.5); - let round = |v: f64| (v + 0.5).floor() as i64 as i32; - let (x, z) = ( - round(horizon_core::jmath::cos(angle) * dist), - round(horizon_core::jmath::sin(angle) * dist), - ); - let mut search = random.fork(); - let (cx, cz) = ((x * 16 + 8) >> 2, (z * 16 + 8) >> 2); + ring_searches(seed, distance, spread, count) + .iter() + .map(|search| search.find(preferred, biome)) + .collect() +} + +/// One ring position before its biome search: the chunk on the ring and the +/// random its search uses. Vanilla runs each search as its own task. +#[derive(Clone, Debug)] +pub struct RingSearch { + x: i32, + z: i32, + random: LegacyRandom, +} +impl RingSearch { + /// BiomeSource.findBiomeHorizontal around the ring chunk's centre: a + /// random preferred biome within 112 blocks, else the ring chunk itself. + pub fn find( + &self, + preferred: &BTreeSet, + biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + ) -> ChunkPos { + let mut search = self.random.clone(); + let (cx, cz) = ((self.x * 16 + 8) >> 2, (self.z * 16 + 8) >> 2); let mut found = 0; let mut result = None; for dz in -28..=28 { @@ -48,9 +58,28 @@ pub fn ring_positions( } } } - out.push(match result { + match result { Some((bx, bz)) => ChunkPos::new(bx >> 4, bz >> 4), - None => ChunkPos::new(x, z), + None => ChunkPos::new(self.x, self.z), + } + } +} + +/// The ring chunks and search randoms of generateRingPositions, in order: +/// the serial part, cheap; the searches can then run anywhere. +pub fn ring_searches(seed: i64, distance: i32, spread: i32, count: i32) -> Vec { + let mut random = LegacyRandom::new(seed); + let mut angle = random.next_double() * PI * 2.0; + let (mut in_circle, mut circle, mut spread) = (0, 0, spread); + let mut out = Vec::with_capacity(count.max(0) as usize); + for i in 0..count { + let dist = f64::from(4 * distance + distance * circle * 6) + + (random.next_double() - 0.5) * (f64::from(distance) * 2.5); + let round = |v: f64| (v + 0.5).floor() as i64 as i32; + out.push(RingSearch { + x: round(horizon_core::jmath::cos(angle) * dist), + z: round(horizon_core::jmath::sin(angle) * dist), + random: random.fork(), }); angle += PI * 2.0 / f64::from(spread); in_circle += 1; From 5bc981e577d1b088cc5c5c13b7003e09ebff24d0 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:07:39 -0400 Subject: [PATCH 05/23] Match world-list search hints and detail placement --- crates/horizon-client/src/title.rs | 12 +++++----- crates/horizon-client/src/title/tests.rs | 28 ++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 31a51939b..2a9f0fdf9 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -839,13 +839,15 @@ impl Title { self.search_focused, self.started, ); - if self.search.is_empty() { - batch.text( + if self.search.is_empty() && !self.search_focused { + batch.text_styled( atlas, - &lang::get_or("gui.selectWorld.search", "Search..."), + &Text::literal(lang::get_or("gui.selectWorld.search", "Search...")) + .italic() + .with_color(crate::text::GRAY), (w / 2.0).floor() - 96.0, 27.0, - rgba(128, 128, 128, 255), + u32::MAX, true, ); } @@ -921,7 +923,7 @@ impl Title { atlas, &details, x + 35.0, - y + 22.0, + y + 21.0, rgba(128, 128, 128, 255), true, ); diff --git a/crates/horizon-client/src/title/tests.rs b/crates/horizon-client/src/title/tests.rs index c994885d8..4f759f960 100644 --- a/crates/horizon-client/src/title/tests.rs +++ b/crates/horizon-client/src/title/tests.rs @@ -625,6 +625,34 @@ fn delete_removes_links_without_following_them() { assert!(outside.join("keep.txt").is_file()); } +#[test] +fn world_search_hint_is_gray_and_only_shown_empty_and_unfocused() { + let mut f = Fixture::new(); + f.world("World", "World"); + f.select(); + let atlas = crate::hud::HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let draw = |title: &Title| { + let mut batch = HudBatch::new([480, 262]); + title.draw(&atlas, &mut batch, (0.0, 0.0), true); + batch + }; + let has_hint = |batch: &HudBatch| { + batch + .vertices + .iter() + .any(|v| v.color == rgba(170, 170, 170, 255) && (21.0..41.0).contains(&v.pos[1])) + }; + assert!(has_hint(&draw(&f.title))); + + f.title.click(240.0, 31.0, (480.0, 262.0)); + assert!(f.title.search_focused); + assert!(!has_hint(&draw(&f.title))); + f.title.type_text("World"); + f.title.click(240.0, 60.0, (480.0, 262.0)); + assert!(!f.title.search_focused); + assert!(!has_hint(&draw(&f.title))); +} + #[test] fn scrolled_world_list_draws_inside_the_list_and_drags_its_scroller() { let mut f = Fixture::new(); From c47dc83eab96ade6a625c76e1482a8f2f97751bf Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:16:05 -0400 Subject: [PATCH 06/23] Honor villager texture hat metadata in type layers --- crates/horizon-client/src/game/packs.rs | 2 + crates/horizon-client/src/mobs.rs | 1 + crates/horizon-client/src/mobs/data.rs | 4 + crates/horizon-client/src/mobs/render.rs | 8 ++ .../horizon-client/src/mobs/villager_hats.rs | 128 ++++++++++++++++++ 5 files changed, 143 insertions(+) create mode 100644 crates/horizon-client/src/mobs/villager_hats.rs diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 599399b96..2e977ddc9 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -147,6 +147,8 @@ impl Game<'_> { self.res.clouds = super::load_clouds(root); self.res.forcefield = super::load_forcefield(root); self.res.names = super::Names::load(root); + self.res.mob_data.villager_hats = + horizon_client::mobs::villager_hats::VillagerHats::load(root); horizon_client::ui::load_metadata(root); lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); self.audio.reload(root); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a98cbb897..d531c8c4b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -70,6 +70,7 @@ pub mod undead; pub mod vex; pub mod villager; pub mod villager_brain; +pub mod villager_hats; pub mod warden; pub mod warden_brain; pub mod witch; diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 48fc4234f..ad948ac1f 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -46,6 +46,7 @@ pub struct MobData { /// Each entity type's `SpawnPlacements.getHeightmapType`. pub heightmaps: HashMap, pub animations: HashMap, + pub villager_hats: super::villager_hats::VillagerHats, /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. pub biome_tags: HashMap>, /// Entity type tags (`data/*/tags/entity_type`). @@ -68,6 +69,7 @@ impl MobData { }; data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(); data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); + data.villager_hats = super::villager_hats::VillagerHats::load(root); data } /// Only the keyframe animation definitions of `mob-data.json`. @@ -128,6 +130,7 @@ impl MobData { placements, heightmaps, animations, + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), } @@ -182,6 +185,7 @@ impl MobData { placements: HashMap::new(), heightmaps: HashMap::new(), animations: HashMap::new(), + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a3b29f63b..46505ec9d 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1061,6 +1061,14 @@ fn render_visible( }; let mut poses = Poses::new(&part); anim::setup(m, &s, &mut poses, &data.animations); + if matches!(m.species(), Species::Villager | Species::ZombieVillager) + && let Some((folder, variant)) = layer.texture.split_once("/type/") + { + let variant = variant.strip_prefix("baby/").unwrap_or(variant); + let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; + data.villager_hats + .apply(folder, variant, profession, &mut poses); + } let light = if layer.full_bright { 240 | 240 << 8 } else { diff --git a/crates/horizon-client/src/mobs/villager_hats.rs b/crates/horizon-client/src/mobs/villager_hats.rs new file mode 100644 index 000000000..b81fa35ef --- /dev/null +++ b/crates/horizon-client/src/mobs/villager_hats.rs @@ -0,0 +1,128 @@ +//! VillagerProfessionLayer's cached texture metadata and type-layer head visibility. +use super::{ + anim::Poses, + render::{PROFESSIONS, VILLAGER_TYPES}, +}; +use std::{collections::HashMap, fs, path::Path}; + +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] +enum Hat { + #[default] + None, + Partial, + Full, +} + +#[derive(Default)] +pub struct VillagerHats(HashMap); + +impl VillagerHats { + pub fn load(root: &Path) -> Self { + let mut hats = HashMap::new(); + for folder in ["villager", "zombie_villager"] { + for (group, names) in [ + ("type", VILLAGER_TYPES.as_slice()), + ("profession", PROFESSIONS.as_slice()), + ] { + for name in names { + let texture = format!("entity/{folder}/{group}/{name}"); + let path = root.join(format!("assets/minecraft/textures/{texture}.png.mcmeta")); + let metadata = fs::read(path) + .ok() + .and_then(|bytes| serde_json::from_slice::(&bytes).ok()); + let hat = match metadata + .as_ref() + .and_then(|v| v["villager"]["hat"].as_str()) + { + Some("partial") => Hat::Partial, + Some("full") => Hat::Full, + _ => Hat::None, + }; + hats.insert(texture, hat); + } + } + } + Self(hats) + } + + pub fn apply(&self, folder: &str, variant: &str, profession: &str, poses: &mut Poses) { + let hat = |group, name| { + self.0 + .get(&format!("{folder}/{group}/{name}")) + .copied() + .unwrap_or_default() + }; + let visible = match hat("profession", profession) { + Hat::None => true, + Hat::Partial => hat("type", variant) != Hat::Full, + Hat::Full => false, + }; + // VillagerModel.createNoHatModel clears the head and every child. + poses.visible("head", visible); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[ignore = "requires prepared 26.3 models and textures in HORIZON_TEST_RESOURCES"] + fn metadata_head_visibility_matches_exported_no_hat_models() { + use crate::mobs::{load_model, render::draw}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let mut hats = VillagerHats::load(Path::new(&root)); + assert_eq!(hats.0["entity/villager/profession/farmer"], Hat::Full); + assert_eq!(hats.0["entity/villager/type/plains"], Hat::None); + for (name, folder) in [ + ("villager", "entity/villager"), + ("villager_baby", "entity/villager"), + ("zombie_villager", "entity/zombie_villager"), + ("zombie_villager_baby", "entity/zombie_villager"), + ] { + let model = load_model(Path::new(&root), &format!("minecraft:{name}#main")).unwrap(); + let no_hat = + load_model(Path::new(&root), &format!("minecraft:{name}_no_hat#main")).unwrap(); + for (type_hat, profession_hat, hidden) in [ + (Hat::None, Hat::Full, true), + (Hat::Full, Hat::Partial, true), + (Hat::Partial, Hat::Partial, false), + (Hat::Full, Hat::None, false), + ] { + hats.0.insert(format!("{folder}/type/plains"), type_hat); + hats.0 + .insert(format!("{folder}/profession/farmer"), profession_hat); + let mut poses = Poses::new(&model); + hats.apply(folder, "plains", "farmer", &mut poses); + let mut actual = Vec::new(); + draw( + &model, + glam::Mat4::IDENTITY, + &poses, + [0.0, 0.0, 1.0, 1.0], + u32::MAX, + 0, + 0, + &mut actual, + ); + let expected_model = if hidden { &no_hat } else { &model }; + let mut expected = Vec::new(); + draw( + expected_model, + glam::Mat4::IDENTITY, + &Poses::new(expected_model), + [0.0, 0.0, 1.0, 1.0], + u32::MAX, + 0, + 0, + &mut expected, + ); + assert_eq!( + bytemuck::cast_slice::<_, u8>(&actual), + bytemuck::cast_slice::<_, u8>(&expected), + "{name}: {type_hat:?}/{profession_hat:?}" + ); + } + } + } +} From 4c3b2b789f687a3613cdff015f659c39798f04f6 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:20:41 -0400 Subject: [PATCH 07/23] Draw translated hover tooltips for Classic options --- crates/horizon-client/src/options_ui.rs | 112 ++++++++++++++++++++++++ 1 file changed, 112 insertions(+) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index d6a5fa476..38be29576 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -223,6 +223,25 @@ impl Opt { _ => Kind::Cycle, } } + /// OptionInstance's static or value-dependent tooltip translation. + fn tooltip_key(self, s: &Settings) -> String { + let key = match self { + Opt::InactivityFps => { + if s.inactivity_fps_limit == "minimized" { + "options.inactivityFpsLimit.minimized" + } else { + "options.inactivityFpsLimit.afk" + } + } + Opt::ChunkBuilder => [ + "options.prioritizeChunkUpdates.none", + "options.prioritizeChunkUpdates.byPlayer", + "options.prioritizeChunkUpdates.nearby", + ][usize::from(s.prioritize_chunk_updates.min(2))], + _ => self.caption(), + }; + format!("{key}.tooltip") + } /// A slider's position (0..1), or `None` for a cycle button. pub fn slider_position(self, s: &Settings) -> Option { match self.kind(s) { @@ -1611,6 +1630,27 @@ impl OptionsUi { let start = batch.vertices.len(); let hover = ui::hovered(cursor, wd.x, wd.y, wd.w, wd.h) && (!wd.list || cursor.1 >= top && cursor.1 < bottom); + if hover { + let key = match &wd.kind { + WKind::Button { + act: Act::Cycle(opt), + .. + } + | WKind::Slider { opt, .. } => Some(opt.tooltip_key(s)), + WKind::Button { + act: Act::Push(Page::Language), + .. + } => Some("options.language.tooltip".into()), + WKind::Button { + act: Act::Push(Page::Accessibility), + .. + } => Some("options.accessibility.tooltip".into()), + _ => None, + }; + if let Some(key) = key.filter(|key| lang::has(key)) { + tooltip = Some(atlas.font.split(&tr(&key), 170.0)); + } + } match &wd.kind { WKind::Button { label, active, act } => { ui::button(batch, atlas, wd.x, wd.y, wd.w, wd.h, label, *active, hover); @@ -2161,6 +2201,78 @@ mod tests { HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap() } + #[test] + fn option_tooltip_keys_follow_value_dependent_descriptions() { + let mut s = Settings::default(); + assert_eq!( + Opt::InactivityFps.tooltip_key(&s), + "options.inactivityFpsLimit.afk.tooltip" + ); + s.inactivity_fps_limit = "minimized".into(); + assert_eq!( + Opt::InactivityFps.tooltip_key(&s), + "options.inactivityFpsLimit.minimized.tooltip" + ); + for (value, name) in ["none", "byPlayer", "nearby"].iter().enumerate() { + s.prioritize_chunk_updates = value as u8; + assert_eq!( + Opt::ChunkBuilder.tooltip_key(&s), + format!("options.prioritizeChunkUpdates.{name}.tooltip") + ); + } + assert_eq!( + Opt::MenuBlur.tooltip_key(&s), + "options.accessibility.menu_background_blurriness.tooltip" + ); + } + + #[test] + #[ignore = "requires prepared language data in HORIZON_TEST_RESOURCES; run alone"] + fn classic_hover_draws_the_selected_options_wrapped_tooltip() { + let root = std::path::PathBuf::from( + std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), + ); + lang::set(lang::Language::load(&[&root], "en_us")); + let atlas = atlas(); + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Video); + for mode in ["afk", "minimized"] { + s.inactivity_fps_limit = mode.into(); + let (widgets, _, _, _) = ui.layout(&s, 480.0, 480.0); + let option = widgets + .iter() + .find(|w| { + matches!( + w.kind, + WKind::Button { + act: Act::Cycle(Opt::InactivityFps), + .. + } + ) + }) + .unwrap(); + let cursor = (option.x + 1.0, option.y + 1.0); + let mut actual = HudBatch::new([480, 480]); + ui.draw(&s, &mut actual, &atlas, cursor); + let key = format!("options.inactivityFpsLimit.{mode}.tooltip"); + assert!(lang::has(&key)); + let mut expected = HudBatch::new([480, 480]); + ui::tooltip( + &mut expected, + &atlas, + &atlas.font.split(&tr(&key), 170.0), + cursor, + ); + assert!(!expected.vertices.is_empty()); + let tail = &actual.vertices[actual.vertices.len() - expected.vertices.len()..]; + assert_eq!( + bytemuck::cast_slice::<_, u8>(tail), + bytemuck::cast_slice::<_, u8>(&expected.vertices) + ); + } + } + #[test] fn classic_video_gui_scale_cycles_on_press_without_dragging() { let atlas = atlas(); From c7073db8b5b54fd8f03d40dd7e03c8bc1e23d07f Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 12:47:49 -0400 Subject: [PATCH 08/23] Apply falling anvil impact damage and wear --- crates/horizon-client/src/entity_nbt.rs | 45 +++- crates/horizon-client/src/falling_block.rs | 192 ++++++++++++++++++ crates/horizon-client/src/game.rs | 55 +++-- crates/horizon-client/src/game/creatures.rs | 1 + .../horizon-client/src/game/falling_damage.rs | 123 +++++++++++ crates/horizon-client/src/game/persist.rs | 21 +- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mobs.rs | 7 + 8 files changed, 394 insertions(+), 51 deletions(-) create mode 100644 crates/horizon-client/src/falling_block.rs create mode 100644 crates/horizon-client/src/game/falling_damage.rs diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index 4e1220d91..adeb1da25 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -1046,12 +1046,15 @@ pub fn arrow_from_nbt( } /// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities. +#[allow(clippy::too_many_arguments)] pub fn falling_block_to_nbt( state: Tag, position: Vec3, motion: Vec3, time: i32, drop_item: bool, + damage: crate::falling_block::Damage, + fall_distance: f64, uuid: [i32; 4], ) -> Tag { let base = Base { @@ -1061,29 +1064,27 @@ pub fn falling_block_to_nbt( motion, rotation: [0.0, 0.0], on_ground: false, - fall_distance: 0.0, + fall_distance, }; let mut tag = base.tag(None); for (key, value) in [ ("BlockState", state), ("Time", Tag::Int(time)), ("DropItem", Tag::Byte(i8::from(drop_item))), - ("HurtEntities", Tag::Byte(0)), - ("CancelDrop", Tag::Byte(0)), - ("FallHurtAmount", Tag::Float(0)), - ("FallHurtMax", Tag::Int(40)), ] { put(&mut tag, key, value); } + damage.save(&mut tag); tag } -/// (block state tag, position, motion, time) -pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32)> { +/// (block state tag, position, motion, time, fall distance) +pub fn falling_block_from_nbt(tag: &Tag) -> Option<(Tag, Vec3, Vec3, i32, f64)> { Some(( tag.get("BlockState")?.clone(), position(tag)?, motion(tag), number(tag.get("Time")).unwrap_or(0) as i32, + float(tag.get("fall_distance")).unwrap_or(0.0), )) } @@ -1493,6 +1494,36 @@ mod tests { use super::*; use crate::items::ItemStack; + #[test] + fn falling_block_round_trip_keeps_impact_distance_and_settings() { + let state = Tag::compound([("Name", string("minecraft:damaged_anvil"))]); + let position = Vec3::new(3.5, 100.0, -7.5); + let velocity = Vec3::new(0.0, -1.25, 0.0); + let damage = crate::falling_block::Damage { + cancel_drop: true, + ..crate::falling_block::Damage::anvil() + }; + let tag = falling_block_to_nbt( + state.clone(), + position, + velocity, + 30, + false, + damage, + 19.75, + [1, 2, 3, 4], + ); + let (loaded_state, pos, motion, age, distance) = falling_block_from_nbt(&tag).unwrap(); + assert_eq!(loaded_state, state); + assert_eq!( + (pos, motion, age, distance), + (position, velocity, 30, 19.75) + ); + assert_eq!(falling_block_flags(&tag), (false, false)); + assert_eq!(crate::falling_block::Damage::from_nbt(&tag, true), damage); + assert_eq!(uuid(&tag), Some([1, 2, 3, 4])); + } + #[test] fn item_entities_round_trip() { let e = ItemEntity { diff --git a/crates/horizon-client/src/falling_block.rs b/crates/horizon-client/src/falling_block.rs new file mode 100644 index 000000000..86c6ebd6f --- /dev/null +++ b/crates/horizon-client/src/falling_block.rs @@ -0,0 +1,192 @@ +//! FallingBlockEntity's impact damage, anvil wear and saved impact settings. +use crate::{ + mobs::{Damage as MobDamage, DamageKind, Mob}, + save::{float, number, put}, +}; +use horizon_core::geometry::{Aabb, Vec3}; +use horizon_world::{chunk::BlockState, nbt::Tag}; + +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Damage { + pub hurt_entities: bool, + pub cancel_drop: bool, + pub per_distance: f32, + pub max: i32, +} +impl Default for Damage { + fn default() -> Self { + Self { + hurt_entities: false, + cancel_drop: false, + per_distance: 0.0, + max: 40, + } + } +} +impl Damage { + pub fn anvil() -> Self { + Self { + hurt_entities: true, + per_distance: 2.0, + ..Self::default() + } + } + pub fn from_nbt(tag: &Tag, anvil: bool) -> Self { + Self { + hurt_entities: number(tag.get("HurtEntities")).map_or(anvil, |v| v != 0), + cancel_drop: number(tag.get("CancelDrop")).is_some_and(|v| v != 0), + per_distance: float(tag.get("FallHurtAmount")).unwrap_or(0.0) as f32, + max: number(tag.get("FallHurtMax")).unwrap_or(40) as i32, + } + } + pub fn save(self, tag: &mut Tag) { + for (key, value) in [ + ("HurtEntities", Tag::Byte(i8::from(self.hurt_entities))), + ("CancelDrop", Tag::Byte(i8::from(self.cancel_drop))), + ("FallHurtAmount", Tag::Float(self.per_distance.to_bits())), + ("FallHurtMax", Tag::Int(self.max)), + ] { + put(tag, key, value); + } + } + pub fn impact(self, fall_distance: f64) -> Option { + if !self.hurt_entities { + return None; + } + let steps = (fall_distance - 1.0).ceil() as i32; + if steps < 0 { + return None; + } + let amount = ((steps as f32 * self.per_distance).floor() as i32).min(self.max) as f32; + Some(Impact { + amount, + wear_chance: if amount > 0.0 { + 0.05 + steps as f32 * 0.05 + } else { + 0.0 + }, + }) + } +} + +#[derive(Clone, Copy, Debug)] +pub struct Impact { + pub amount: f32, + pub wear_chance: f32, +} + +/// AnvilBlock.damage: advance wear without changing facing; false means broken. +pub fn wear_anvil(state: &mut BlockState) -> bool { + state.name = match state.name.as_str() { + "minecraft:anvil" => "minecraft:chipped_anvil", + "minecraft:chipped_anvil" => "minecraft:damaged_anvil", + _ => return false, + } + .into(); + true +} + +pub fn bounds(position: Vec3) -> Aabb { + let size = f64::from(0.98_f32); + Aabb::new( + Vec3::new(position.x - size / 2.0, position.y, position.z - size / 2.0), + Vec3::new( + position.x + size / 2.0, + position.y + size, + position.z + size / 2.0, + ), + ) +} +pub fn hurt_mobs(mobs: &mut [Mob], position: Vec3, amount: f32) { + if amount <= 0.0 { + return; + } + let bounds = bounds(position); + let source = MobDamage { + kind: DamageKind::FallingBlock, + attacker: None, + from: Some([position.x, position.y, position.z]), + }; + for mob in mobs + .iter_mut() + .filter(|m| m.alive() && bounds.intersects(m.bounds())) + { + mob.damage(amount, source); + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn impact_uses_ceil_distance_capped_damage_and_positive_damage_wear() { + let damage = Damage::anvil(); + assert!(Damage::default().impact(50.0).is_none()); + assert!(damage.impact(0.0).is_none()); + let short = damage.impact(1.0).unwrap(); + assert_eq!((short.amount, short.wear_chance), (0.0, 0.0)); + assert_eq!(damage.impact(1.01).unwrap().amount, 2.0); + assert_eq!(damage.impact(5.0).unwrap().amount, 8.0); + assert_eq!(damage.impact(100.0).unwrap().amount, 40.0); + assert!(damage.impact(21.0).unwrap().wear_chance > 1.0); + } + #[test] + fn damage_settings_round_trip_and_keep_vanilla_load_defaults() { + let empty = Tag::Compound(Default::default()); + assert_eq!(Damage::from_nbt(&empty, false), Damage::default()); + let loaded_anvil = Damage::from_nbt(&empty, true); + assert!(loaded_anvil.hurt_entities); + assert_eq!(loaded_anvil.per_distance, 0.0); + let damage = Damage { + hurt_entities: true, + cancel_drop: true, + per_distance: 3.5, + max: 17, + }; + let mut tag = empty; + damage.save(&mut tag); + assert_eq!(Damage::from_nbt(&tag, false), damage); + } + #[test] + fn anvil_wears_twice_then_breaks_preserving_facing() { + for facing in ["north", "south", "east", "west"] { + let mut state = BlockState { + name: "minecraft:anvil".into(), + properties: [("facing".into(), facing.into())].into(), + }; + for name in ["minecraft:chipped_anvil", "minecraft:damaged_anvil"] { + assert!(wear_anvil(&mut state)); + assert_eq!(state.name, name); + assert_eq!(state.properties["facing"], facing); + } + assert!(!wear_anvil(&mut state)); + } + } + #[test] + #[ignore = "requires prepared entity models/data in HORIZON_TEST_RESOURCES"] + fn impact_hurts_only_living_intersecting_noninvulnerable_mobs() { + use crate::mobs::{Mob, MobTypes}; + use std::{path::Path, sync::Arc}; + let root = std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"); + let types = MobTypes::load(Path::new(&root)).unwrap(); + let cow = Arc::new(types.types["minecraft:cow"].clone()); + let mut mobs = vec![ + Mob::new(1, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(2, cow.clone(), Vec3::new(3.0, 0.0, 0.0), 0.0), + Mob::new(3, cow.clone(), Vec3::ZERO, 0.0), + Mob::new(4, cow, Vec3::ZERO, 0.0), + ]; + mobs[2].invulnerable_flag = true; + mobs[3].extra.head = Some("minecraft:carved_pumpkin".into()); + let initial = mobs.iter().map(|m| m.health).collect::>(); + hurt_mobs( + &mut mobs, + Vec3::ZERO, + Damage::anvil().impact(5.0).unwrap().amount, + ); + assert_eq!(mobs[0].health, initial[0] - 8.0); + assert_eq!(mobs[1].health, initial[1]); + assert_eq!(mobs[2].health, initial[2]); + assert_eq!(mobs[3].health, initial[3] - 6.0); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7072abeb5..4c039204b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -41,6 +41,7 @@ mod entity_culling; mod events; mod explosion; mod extras; +mod falling_damage; mod fangs; mod fireworks; mod fishing; @@ -642,6 +643,7 @@ struct FallingBlock { drop_item: bool, /// `Entity.fallDistance` (powder snow holds a block that fell far at 0.9). fall_distance: f64, + damage: horizon_client::falling_block::Damage, /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } @@ -1900,6 +1902,7 @@ impl Game<'_> { 1009 => Some(("minecraft:block.fire.extinguish", 0.5)), 1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)), 1030 => Some(("minecraft:block.anvil.use", 1.0)), + 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), _ => None, @@ -1952,6 +1955,11 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, + damage: if self.res.facts.get(state).name.ends_with("anvil") { + horizon_client::falling_block::Damage::anvil() + } else { + Default::default() + }, saved: None, }); } @@ -2207,14 +2215,19 @@ impl Game<'_> { return false; } if solid { - landed.push(( - f.state, - [ - next.x.floor() as i32, - next.y.floor() as i32 + i32::from(!sunk), - next.z.floor() as i32, - ], - )); + let pos = [ + next.x.floor() as i32, + next.y.floor() as i32 + i32::from(!sunk), + next.z.floor() as i32, + ]; + let landing_y = if sunk { + next.y.floor() + f64::from(0.9_f32) + } else { + f64::from(pos[1]) + }; + f.fall_distance += (f.position.y - landing_y).max(0.0); + f.position = Vec3::new(next.x, landing_y, next.z); + landed.push((f.clone(), pos)); return false; } if next.y < f.position.y { @@ -2248,30 +2261,8 @@ impl Game<'_> { self.spawn_item(stack, [at.x, at.y, at.z], v, 10); } } - for (state, pos) in landed { - let landing = self.with_level(|b, level, ticks| { - b.falling_block_landed( - level, - ticks, - BlockPos::new(pos[0], pos[1], pos[2]), - state, - false, - ) - }); - if matches!(landing, Landing::Broken) { - let item = self.res.facts.get(state).item.clone(); - if &*item != "minecraft:air" { - self.pop_resource( - pos, - ItemStack { - item, - count: 1, - damage: 0, - extra: None, - }, - ); - } - } + for (block, pos) in landed { + self.finish_falling_block(block, pos); } self.process_level_events() } diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index e454264d8..262ff11c2 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -2980,6 +2980,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static K::Explosion if player => "minecraft:player_explosion", K::Explosion => "minecraft:explosion", K::Fall => "minecraft:fall", + K::FallingBlock => "minecraft:falling_block", K::OnFire => "minecraft:on_fire", K::InFire => "minecraft:in_fire", K::Lava => "minecraft:lava", diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs new file mode 100644 index 000000000..313ddbaac --- /dev/null +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -0,0 +1,123 @@ +//! Landing impacts for falling blocks, before their placement/drop decision. +use super::{FallingBlock, Game, Landing}; +use horizon_client::{falling_block, items::ItemStack}; +use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource}; +use horizon_world::level::LevelEvent; + +impl Game<'_> { + pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { + let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + if let Some(impact) = block.damage.impact(block.fall_distance) { + if impact.amount > 0.0 { + falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); + let kind = if anvil { + "minecraft:falling_anvil" + } else { + "minecraft:falling_block" + }; + self.falling_hurt_player(block.position, impact.amount, kind); + if let Some(mut host) = self.lan.take() { + let bounds = falling_block::bounds(block.position); + let conns = host + .hub + .guests + .iter() + .filter(|g| { + g.placed + && g.loaded + && !g.dead + && !g.creative() + && !g.spectator() + && bounds.intersects(super::lan_mobs::guest_bounds(g)) + }) + .map(|g| g.conn) + .collect::>(); + for conn in conns { + self.guest_hit_by(&mut host, conn, |g| { + g.falling_hurt_player(block.position, impact.amount, kind) + }); + } + self.lan = Some(host); + } + } + if anvil + && impact.wear_chance > 0.0 + && self.world.random.next_float() < impact.wear_chance + && let Some(mut state) = self.res.assets.registry.state(block.state).cloned() + { + if falling_block::wear_anvil(&mut state) { + block.state = self + .res + .assets + .registry + .resolve(&state) + .unwrap_or(block.state); + } else { + block.damage.cancel_drop = true; + } + } + } + if block.damage.cancel_drop { + if anvil { + self.level_events.push(LevelEvent::LevelEvent { + id: 1029, + pos: BlockPos::new(pos[0], pos[1], pos[2]), + data: 0, + }); + } + return; + } + let landing = self.with_level(|b, level, ticks| { + b.falling_block_landed( + level, + ticks, + BlockPos::new(pos[0], pos[1], pos[2]), + block.state, + false, + ) + }); + if matches!(landing, Landing::Broken) + && block.drop_item + && self.ui.rules.bool("entity_drops") + { + let item = self.res.facts.get(block.state).item.clone(); + if &*item != "minecraft:air" { + self.pop_resource( + pos, + ItemStack { + item, + count: 1, + damage: 0, + extra: None, + }, + ); + } + } + } + fn falling_hurt_player(&mut self, position: Vec3, amount: f32, kind: &str) { + if self.creative || self.spectator() { + return; + } + if self.player.as_ref().is_none_or(|p| { + p.health.dead_or_dying() || !falling_block::bounds(position).intersects(p.bounds()) + }) { + return; + } + let amount = if self.armor[0].is_some() { + amount * 0.75 + } else { + amount + }; + let hurt = if let Some(p) = self.player.as_mut() + && let Some(id) = self.motion.health.damage.id(kind) + { + p.hurt(&self.motion.health, self.world.health_rules, id, amount) + .unwrap_or(false) + } else { + false + }; + if hurt { + self.hurt_armor(amount); + } + } +} diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 054f2c2fc..29549bb02 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -49,16 +49,7 @@ fn with_raw(modelled: Tag, raw: Option<&Tag>) -> Tag { // Defaults Horizon invents for fields it does not simulate give way to the save. let invented = matches!( k.to_string_lossy().as_str(), - "Fire" - | "Air" - | "Invulnerable" - | "PortalCooldown" - | "HasBeenShot" - // FallingBlockEntity fields Horizon does not simulate. - | "HurtEntities" - | "CancelDrop" - | "FallHurtAmount" - | "FallHurtMax" + "Fire" | "Air" | "Invulnerable" | "PortalCooldown" | "HasBeenShot" ); if !(invented && out.contains_key(k)) { out.insert(k.clone(), v.clone()); @@ -199,7 +190,7 @@ impl Game<'_> { } } "minecraft:falling_block" => { - if let Some((state, position, velocity, age)) = + if let Some((state, position, velocity, age, fall_distance)) = entity_nbt::falling_block_from_nbt(&tag) && let Some(state) = self.state_from_nbt(&state) { @@ -214,7 +205,11 @@ impl Game<'_> { age, no_gravity, drop_item, - fall_distance: 0.0, + fall_distance, + damage: horizon_client::falling_block::Damage::from_nbt( + &tag, + self.res.facts.get(state).name.ends_with("anvil"), + ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); } @@ -620,6 +615,8 @@ impl Game<'_> { f.velocity, f.age, f.drop_item, + f.damage, + f.fall_distance, uuid, ); out.entry(chunk_of(f.position)) diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..092a782e4 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -59,6 +59,7 @@ pub mod entity_nbt; pub mod environment; pub mod extras; pub mod extras_hud; +pub mod falling_block; pub mod fast_hash; pub mod fastutil_order; pub mod fire_render; diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index a98cbb897..8697f66f0 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -507,6 +507,7 @@ pub enum DamageKind { Fireball, Explosion, Fall, + FallingBlock, OnFire, InFire, Lava, @@ -1610,6 +1611,12 @@ impl Mob { return false; } let mut amount = amount; + if source.kind == DamageKind::FallingBlock + && !species::body_slot(self.species()) + && self.extra.head.is_some() + { + amount *= 0.75; + } let (worn, worn_toughness) = self.worn_armor(); if !source.bypasses_armor() && self.kind.armor + worn > 0.0 { // CombatRules.getDamageAfterAbsorb From 746c888cd3b85bfe27dbc15b292f0c62054300f6 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:20:46 +0200 Subject: [PATCH 09/23] horizon-mods: content mods (API 0.2), blocks and items declared from vanilla templates A .hmod may carry assets/ and data/ beside mod.wasm, or instead of it. The manifest needs api = "0.2" and the new registries capability ("add blocks and items to your worlds"). Content mods have no WIT interface: code still links API 0.1. horizon_mods::content::Content reads a mod's content and checks it: - plain resource paths only; - 65,536 files, 16 MiB each, 512 MiB in all; - files in the mod's own namespace, plus additions to vanilla tags; - blocks and items declared in data//horizon/{block,item}/*.json, each copying a vanilla template with typed overrides (hardness, resistance, light, tool, friction, map colour, sounds; stack size, rarity), unknown keys refused. Mods::load refuses an enabled mod whose content fails these checks, with the reason on its row. A content-only mod is on with no engine and no hooks. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-mods/Cargo.toml | 1 + crates/horizon-mods/src/content.rs | 557 +++++++++++++++++++++++++++ crates/horizon-mods/src/lib.rs | 2 + crates/horizon-mods/src/manifest.rs | 110 ++++-- crates/horizon-mods/src/runtime.rs | 22 +- crates/horizon-mods/tests/sandbox.rs | 34 +- docs/mods.md | 22 ++ 8 files changed, 711 insertions(+), 38 deletions(-) create mode 100644 crates/horizon-mods/src/content.rs diff --git a/Cargo.lock b/Cargo.lock index 68d0b250d..90b288a8e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1483,6 +1483,7 @@ dependencies = [ "horizon-mods", "log", "serde", + "serde_json", "toml", "wasmtime", "wit-component 0.239.0", diff --git a/crates/horizon-mods/Cargo.toml b/crates/horizon-mods/Cargo.toml index ee325261d..8db24ac35 100644 --- a/crates/horizon-mods/Cargo.toml +++ b/crates/horizon-mods/Cargo.toml @@ -8,6 +8,7 @@ description = "Horizon's mod runtime: sandboxed WebAssembly components (docs/mod [dependencies] serde = { version = "1", features = ["derive"] } +serde_json = "1" toml = "1.1.6" zip = { version = "2", default-features = false, features = ["deflate"] } log = "0.4" diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs new file mode 100644 index 000000000..411fa7277 --- /dev/null +++ b/crates/horizon-mods/src/content.rs @@ -0,0 +1,557 @@ +//! A content mod's `assets/` and `data/` (API 0.2, docs/modpacks.md): the +//! files it adds to the game's resource tree, and the blocks and items it +//! declares in `data//horizon/block/` and `data//horizon/item/`. +//! +//! Content is data, not code: nothing here runs in the sandbox. What a mod +//! may add is fenced instead. Its own namespace, plus additions to vanilla +//! tags. Paths are plain, files and totals are capped, and vanilla ids +//! cannot be redefined. +use crate::manifest::{Capability, MANIFEST, Manifest}; +use serde::Deserialize; +use std::{ + collections::BTreeSet, + io::Read, + path::{Path, PathBuf}, +}; + +/// Content files per mod, bytes per file and bytes per mod. +pub const MAX_FILES: usize = 65_536; +pub const MAX_FILE: u64 = 16 << 20; +pub const MAX_TOTAL: u64 = 512 << 20; + +/// Checks a content path: `assets/` or `data/`, then `/`-separated parts of +/// `[a-z0-9_.-]`, none of them `.` or `..` (vanilla's resource-location +/// characters, so the path means the same on every OS). +pub fn check_path(name: &str) -> Result<(), String> { + let bad = || format!("{name:?} is not a plain assets/ or data/ path"); + let mut parts = name.split('/'); + if !matches!(parts.next(), Some("assets" | "data")) { + return Err(bad()); + } + let mut count = 0; + for part in parts { + count += 1; + let chars_ok = part + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b)); + if part.is_empty() || part == "." || part == ".." || !chars_ok { + return Err(bad()); + } + } + // assets// at least. + if count < 2 { + return Err(bad()); + } + Ok(()) +} + +/// A vanilla identifier, `minecraft:path`. +fn vanilla_id(id: &str) -> bool { + id.strip_prefix("minecraft:").is_some_and(|path| { + !path.is_empty() + && path + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_./-".contains(&b)) + }) +} + +/// What a declared block changes from its template; unset keeps the +/// template's value. +#[derive(Clone, Debug, Default, Deserialize, PartialEq)] +#[serde(deny_unknown_fields)] +pub struct BlockProperties { + /// Destroy time in seconds of hand mining (-1: unbreakable). + pub hardness: Option, + pub explosion_resistance: Option, + /// Light emitted, 0 to 15. + pub light: Option, + pub requires_tool: Option, + pub friction: Option, + /// A `MapColor` id, 0 to 61. + pub map_color: Option, + /// A vanilla block whose sounds this block uses. + pub sounds: Option, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct BlockFile { + template: String, + #[serde(default)] + properties: BlockProperties, + #[serde(default = "yes")] + item: bool, +} +fn yes() -> bool { + true +} + +/// A block the mod adds: a vanilla template's behaviour, states and shapes +/// under a new id, with `properties` applied. +#[derive(Clone, Debug, PartialEq)] +pub struct Block { + /// `:`. + pub id: String, + /// The vanilla block it copies, `minecraft:`. + pub template: String, + pub properties: BlockProperties, + /// Also add a block item with the same id. + pub item: bool, +} + +#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub enum Rarity { + Common, + Uncommon, + Rare, + Epic, +} + +#[derive(Debug, Deserialize)] +#[serde(deny_unknown_fields)] +struct ItemFile { + template: String, + max_stack_size: Option, + rarity: Option, +} + +/// An item the mod adds: a vanilla template item's components under a new +/// id, with these changed. +#[derive(Clone, Debug, PartialEq)] +pub struct Item { + pub id: String, + /// The vanilla item it copies, `minecraft:`. + pub template: String, + pub max_stack_size: Option, + pub rarity: Option, +} + +#[derive(Debug)] +enum Source { + Dir(PathBuf), + Zip(PathBuf), +} + +/// A mod's content: its files and declarations. +#[derive(Debug)] +pub struct Content { + source: Source, + /// Every content file (`assets/...`, `data/...`), sorted. + pub files: Vec, + pub blocks: Vec, + pub items: Vec, +} + +impl Content { + /// The content of the mod at `path` (a `.hmod` or a mod folder). + pub fn read(path: &Path, manifest: &Manifest) -> Result { + let (source, sized) = if path.is_dir() { + let mut out = Vec::new(); + for top in ["assets", "data"] { + walk(path, &path.join(top), &mut out)?; + } + (Source::Dir(path.to_owned()), out) + } else { + let mut zip = open_zip(path)?; + let mut out = Vec::new(); + for i in 0..zip.len() { + let entry = zip.by_index_raw(i).map_err(|e| e.to_string())?; + let name = entry.name(); + if (name.starts_with("assets/") || name.starts_with("data/")) && !entry.is_dir() { + out.push((name.to_owned(), entry.size())); + } + } + (Source::Zip(path.to_owned()), out) + }; + let mut files = Vec::with_capacity(sized.len()); + let mut total = 0u64; + for (name, size) in sized { + check_path(&name)?; + if size > MAX_FILE { + return Err(format!("{name} is over {} MiB", MAX_FILE >> 20)); + } + total += size; + files.push(name); + } + if files.len() > MAX_FILES { + return Err(format!("more than {MAX_FILES} content files")); + } + if total > MAX_TOTAL { + return Err(format!("content is over {} MiB", MAX_TOTAL >> 20)); + } + files.sort(); + files.dedup(); + let mut content = Content { + source, + files, + blocks: Vec::new(), + items: Vec::new(), + }; + content.check(manifest)?; + Ok(content) + } + + /// No files: a mod with code only. + pub fn is_empty(&self) -> bool { + self.files.is_empty() + } + + /// One content file's bytes. + pub fn file(&self, name: &str) -> Result, String> { + check_path(name)?; + let mut out = Vec::new(); + match &self.source { + Source::Dir(root) => { + let file = + std::fs::File::open(root.join(name)).map_err(|e| format!("{name}: {e}"))?; + file.take(MAX_FILE + 1) + .read_to_end(&mut out) + .map_err(|e| format!("{name}: {e}"))?; + } + Source::Zip(path) => { + let mut zip = open_zip(path)?; + let entry = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; + entry + .take(MAX_FILE + 1) + .read_to_end(&mut out) + .map_err(|e| format!("{name}: {e}"))?; + } + } + if out.len() as u64 > MAX_FILE { + return Err(format!("{name} is over {} MiB", MAX_FILE >> 20)); + } + Ok(out) + } + + /// Where content may go, and the declarations. + fn check(&mut self, manifest: &Manifest) -> Result<(), String> { + let id = manifest.id.as_str(); + if !self.files.is_empty() && !manifest.capabilities.contains(&Capability::Registries) { + return Err(format!( + "has assets/ or data/ but not capability registries in {MANIFEST}" + )); + } + let mut blocks = Vec::new(); + let mut items = Vec::new(); + for name in &self.files { + let mut parts = name.splitn(3, '/'); + let (top, namespace, rest) = ( + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + parts.next().unwrap_or(""), + ); + let own = namespace == id; + // Vanilla's own files stay vanilla's; a mod may only add to its tags. + let allowed = + own || (top == "data" && namespace == "minecraft" && rest.starts_with("tags/")); + if !allowed { + return Err(format!( + "{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla tags" + )); + } + let Some(decl) = (own && top == "data") + .then(|| rest.strip_prefix("horizon/")) + .flatten() + else { + continue; + }; + let parse = |kind: &str| -> Option { + let path = decl + .strip_prefix(kind)? + .strip_prefix('/')? + .strip_suffix(".json")?; + Some(format!("{id}:{path}")) + }; + if let Some(block) = parse("block") { + blocks.push((block, name.clone())); + } else if let Some(item) = parse("item") { + items.push((item, name.clone())); + } else { + return Err(format!( + "{name}: data/{id}/horizon/ holds block/*.json and item/*.json only" + )); + } + } + let mut ids = BTreeSet::new(); + for (block, name) in blocks { + let file: BlockFile = + serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?; + check_block(&file).map_err(|e| format!("{name}: {e}"))?; + if file.item { + ids.insert(block.clone()); + } + self.blocks.push(Block { + id: block, + template: file.template, + properties: file.properties, + item: file.item, + }); + } + for (item, name) in items { + let file: ItemFile = + serde_json::from_slice(&self.file(&name)?).map_err(|e| format!("{name}: {e}"))?; + if !vanilla_id(&file.template) { + return Err(format!( + "{name}: template {:?} is not a vanilla item (minecraft:...)", + file.template + )); + } + if file.max_stack_size.is_some_and(|n| !(1..=99).contains(&n)) { + return Err(format!("{name}: max_stack_size is 1 to 99")); + } + if !ids.insert(item.clone()) { + return Err(format!("{name}: {item} is also a block's item")); + } + self.items.push(Item { + id: item, + template: file.template, + max_stack_size: file.max_stack_size, + rarity: file.rarity, + }); + } + Ok(()) + } +} + +fn check_block(file: &BlockFile) -> Result<(), String> { + if !vanilla_id(&file.template) { + return Err(format!( + "template {:?} is not a vanilla block (minecraft:...)", + file.template + )); + } + let p = &file.properties; + let finite = |v: Option| v.is_none_or(f32::is_finite); + if !finite(p.hardness) || !finite(p.explosion_resistance) || !finite(p.friction) { + return Err("hardness, explosion_resistance and friction are numbers".into()); + } + if p.hardness.is_some_and(|h| h < 0.0 && h != -1.0) { + return Err("hardness is 0 or more, or -1 (unbreakable)".into()); + } + if p.explosion_resistance.is_some_and(|r| r < 0.0) { + return Err("explosion_resistance is 0 or more".into()); + } + if p.friction.is_some_and(|f| !(0.0..=2.0).contains(&f)) { + return Err("friction is 0 to 2".into()); + } + if p.light.is_some_and(|l| l > 15) { + return Err("light is 0 to 15".into()); + } + if p.map_color.is_some_and(|c| c > 61) { + return Err("map_color is a MapColor id, 0 to 61".into()); + } + if p.sounds.as_deref().is_some_and(|s| !vanilla_id(s)) { + return Err("sounds names a vanilla block (minecraft:...)".into()); + } + Ok(()) +} + +fn open_zip(path: &Path) -> Result, String> { + let file = std::fs::File::open(path).map_err(|e| e.to_string())?; + zip::ZipArchive::new(file).map_err(|e| e.to_string()) +} + +/// Files under `dir`, relative to `root` with `/` separators. Symbolic links +/// are not followed: a mod folder holds its own files. +fn walk(root: &Path, dir: &Path, out: &mut Vec<(String, u64)>) -> Result<(), String> { + let Ok(read) = std::fs::read_dir(dir) else { + return Ok(()); + }; + for entry in read.flatten() { + let path = entry.path(); + let meta = std::fs::symlink_metadata(&path).map_err(|e| e.to_string())?; + if meta.is_dir() { + walk(root, &path, out)?; + } else if meta.is_file() { + let rel = path.strip_prefix(root).map_err(|e| e.to_string())?; + let parts: Option> = rel.iter().map(|p| p.to_str()).collect(); + let name = parts.ok_or_else(|| format!("{} is not UTF-8", rel.display()))?; + out.push((name.join("/"), meta.len())); + } + if out.len() > MAX_FILES { + return Err(format!("more than {MAX_FILES} content files")); + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest::Package; + + const MANIFEST_TEXT: &str = r#" +id = "ruby" +name = "Ruby" +version = "0.1.0" +api = "0.2" +side = "both" +capabilities = ["registries"] +"#; + const BLOCK: &[u8] = br#"{"template": "minecraft:iron_block", + "properties": {"hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block"}}"#; + const ITEM: &[u8] = br#"{"template": "minecraft:diamond", "rarity": "uncommon"}"#; + + fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("horizon-content-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + fn hmod(name: &str, manifest: &str, files: &[(&str, &[u8])]) -> Result { + let dir = scratch(name); + let path = dir.join("m.hmod"); + std::fs::write(&path, Package::write_files(manifest, None, files)?).unwrap(); + let package = Package::read(&path); + let content = package.and_then(|p| Content::read(&path, &p.manifest)); + std::fs::remove_dir_all(&dir).unwrap(); + content + } + + #[test] + fn content_only_mod_round_trips() { + let files: &[(&str, &[u8])] = &[ + ("data/ruby/horizon/block/ruby_block.json", BLOCK), + ("data/ruby/horizon/item/ruby.json", ITEM), + ("data/ruby/recipe/ruby_block.json", b"{}"), + ("data/minecraft/tags/block/mineable/pickaxe.json", b"{}"), + ("assets/ruby/textures/block/ruby_block.png", b"png"), + ]; + let content = hmod("ok", MANIFEST_TEXT, files).unwrap(); + assert_eq!(content.files.len(), 5); + assert_eq!( + content.blocks, + [Block { + id: "ruby:ruby_block".into(), + template: "minecraft:iron_block".into(), + properties: BlockProperties { + hardness: Some(4.0), + light: Some(3), + sounds: Some("minecraft:amethyst_block".into()), + ..BlockProperties::default() + }, + item: true, + }] + ); + assert_eq!(content.items[0].id, "ruby:ruby"); + assert_eq!(content.items[0].rarity, Some(Rarity::Uncommon)); + } + + #[test] + fn folder_mod_reads_the_same() { + let dir = scratch("folder"); + std::fs::write(dir.join(MANIFEST), MANIFEST_TEXT).unwrap(); + let block = dir.join("data/ruby/horizon/block"); + std::fs::create_dir_all(&block).unwrap(); + std::fs::write(block.join("ruby_block.json"), BLOCK).unwrap(); + let package = Package::read(&dir).unwrap(); + assert!(package.wasm.is_none()); + let content = Content::read(&dir, &package.manifest).unwrap(); + assert_eq!(content.files, ["data/ruby/horizon/block/ruby_block.json"]); + assert_eq!(content.file(&content.files[0]).unwrap(), BLOCK); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn refuses_content_outside_its_fence() { + let refused = |name: &str, files: &[(&str, &[u8])]| { + let e = hmod(name, MANIFEST_TEXT, files).unwrap_err(); + assert!(!e.is_empty()); + e + }; + let e = refused("other-ns", &[("data/other/horizon/block/a.json", BLOCK)]); + assert!(e.contains("own namespace"), "{e}"); + refused( + "vanilla-asset", + &[("assets/minecraft/textures/block/stone.png", b"x")], + ); + refused( + "vanilla-recipe", + &[("data/minecraft/recipe/stone.json", b"{}")], + ); + let e = refused( + "modded-template", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "ruby:other"}"#, + )], + ); + assert!(e.contains("not a vanilla block"), "{e}"); + refused( + "light", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "minecraft:stone", "properties": {"light": 16}}"#, + )], + ); + refused( + "unknown-key", + &[( + "data/ruby/horizon/block/a.json", + br#"{"template": "minecraft:stone", "glow": true}"#, + )], + ); + let e = refused( + "clash", + &[ + ("data/ruby/horizon/block/a.json", BLOCK), + ("data/ruby/horizon/item/a.json", ITEM), + ], + ); + assert!(e.contains("also a block's item"), "{e}"); + refused("other-kind", &[("data/ruby/horizon/entity/a.json", b"{}")]); + refused( + "stack", + &[( + "data/ruby/horizon/item/a.json", + br#"{"template": "minecraft:stick", "max_stack_size": 100}"#, + )], + ); + } + + #[test] + fn content_needs_the_registries_capability() { + let code_only = MANIFEST_TEXT + .replace("api = \"0.2\"", "api = \"0.1\"") + .replace("capabilities = [\"registries\"]", "capabilities = []"); + // No code and no registries: nothing to load. + let e = hmod("empty", &code_only, &[]).unwrap_err(); + assert!(e.contains("mod.wasm: missing"), "{e}"); + // Registries on API 0.1. + let old = MANIFEST_TEXT.replace("api = \"0.2\"", "api = \"0.1\""); + assert!(Manifest::parse(&old).unwrap_err().contains("needs api")); + // Content without the capability, in a mod with code. + let dir = scratch("no-cap"); + let path = dir.join("m.hmod"); + let files: &[(&str, &[u8])] = &[("assets/ruby/lang/en_us.json", b"{}")]; + std::fs::write( + &path, + Package::write_files(&code_only, Some(b"\0asm"), files).unwrap(), + ) + .unwrap(); + let package = Package::read(&path).unwrap(); + let e = Content::read(&path, &package.manifest).err().unwrap(); + assert!(e.contains("not capability registries"), "{e}"); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn paths_are_plain() { + assert!(check_path("assets/ruby/textures/block/ruby_block.png").is_ok()); + assert!(check_path("data/ruby/loot_table/blocks/a.json").is_ok()); + for bad in [ + "assets/ruby", + "assets/../x/y", + "assets/ruby//a", + "assets/Ruby/a", + "assets/ruby/a b", + "/assets/ruby/a", + "other/ruby/a", + "assets\\ruby\\a", + ] { + assert!(check_path(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/horizon-mods/src/lib.rs b/crates/horizon-mods/src/lib.rs index f2bb3833c..ec9ebe67d 100644 --- a/crates/horizon-mods/src/lib.rs +++ b/crates/horizon-mods/src/lib.rs @@ -5,10 +5,12 @@ //! //! Nothing here runs unless a mod is installed and turned on: an empty //! [`Mods`] makes no engine and every hook returns at once. +pub mod content; pub mod manifest; #[cfg(feature = "runtime")] mod runtime; +pub use content::Content; pub use manifest::{Capability, Manifest, Package, Side}; #[cfg(feature = "runtime")] pub use runtime::*; diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 984ef7e6b..47eeba8fe 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -9,6 +9,10 @@ pub const WASM: &str = "mod.wasm"; /// The API (WIT package `horizon:mods`) versions this build runs: a mod /// built for any 0.1.x SDK. pub const API: &str = "0.1"; +/// The manifest `api` lines this build loads. 0.2 is 0.1 plus content: +/// `assets/` and `data/` in the `.hmod`, with blocks and items declared in +/// `data//horizon/` (docs/modpacks.md). Code still links API 0.1. +pub const APIS: [&str; 2] = [API, "0.2"]; /// The biggest `mod.wasm` a mod may ship. const MAX_WASM: u64 = 32 << 20; @@ -23,7 +27,7 @@ pub struct Manifest { pub description: String, #[serde(default)] pub authors: Vec, - /// The API version the mod was built for: `0.1`. + /// The API line the mod was built for: `0.1`, or `0.2` for content. pub api: String, #[serde(default)] pub side: Side, @@ -51,15 +55,24 @@ pub enum Capability { GameRead, Chat, Hud, + /// New blocks and items from the mod's `data/` (API 0.2): no WIT + /// interface, the game reads them before the world loads. + Registries, } impl Capability { - pub const ALL: [Capability; 3] = [Capability::GameRead, Capability::Chat, Capability::Hud]; + pub const ALL: [Capability; 4] = [ + Capability::GameRead, + Capability::Chat, + Capability::Hud, + Capability::Registries, + ]; /// The WIT interface it grants, in `horizon:mods`. pub fn interface(self) -> &'static str { match self { Capability::GameRead => "game", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Registries => "registries", } } /// What the player reads before turning the mod on: "May ". @@ -68,6 +81,7 @@ impl Capability { Capability::GameRead => "see your position, health and the time", Capability::Chat => "show you chat messages", Capability::Hud => "draw text on your screen", + Capability::Registries => "add blocks and items to your worlds", } } /// The capability a component import needs, `Ok(None)` for one every @@ -84,6 +98,7 @@ impl Capability { } Capability::ALL .into_iter() + .filter(|c| *c != Capability::Registries) .find(|c| c.interface() == interface) .map(Some) .ok_or_else(unknown) @@ -95,6 +110,7 @@ impl fmt::Display for Capability { Capability::GameRead => "game-read", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Registries => "registries", }; f.write_str(name) } @@ -113,8 +129,17 @@ impl Manifest { m.id )); } - if m.api != API { - return Err(format!("built for API {}; this Horizon runs {API}", m.api)); + if !APIS.contains(&m.api.as_str()) { + return Err(format!( + "built for API {}; this Horizon runs {}", + m.api, + APIS.join(" and ") + )); + } + if m.capabilities.contains(&Capability::Registries) && m.api == API { + return Err(format!( + "{MANIFEST}: capability registries needs api = \"0.2\"" + )); } Ok(m) } @@ -137,54 +162,79 @@ impl Manifest { /// A mod as found on disk: its manifest and component bytes. pub struct Package { pub manifest: Manifest, - pub wasm: Vec, + /// None for a content-only mod (capability `registries`, no code). + pub wasm: Option>, } impl Package { - /// A `.hmod` (a zip holding `horizon-mod.toml` and `mod.wasm`) or a - /// folder holding the same two files. + /// A `.hmod` (a zip holding `horizon-mod.toml`, `mod.wasm` and, for + /// content, `assets/` and `data/`) or a folder holding the same. pub fn read(path: &Path) -> Result { let (toml, wasm) = if path.is_dir() { let toml = std::fs::read_to_string(path.join(MANIFEST)); - let wasm = std::fs::read(path.join(WASM)); - ( - toml.map_err(|e| format!("{MANIFEST}: {e}"))?, - wasm.map_err(|e| format!("{WASM}: {e}"))?, - ) + let wasm = path.join(WASM); + let wasm = match wasm.exists() { + true => Some(std::fs::read(wasm).map_err(|e| format!("{WASM}: {e}"))?), + false => None, + }; + (toml.map_err(|e| format!("{MANIFEST}: {e}"))?, wasm) } else { let file = std::fs::File::open(path).map_err(|e| e.to_string())?; let mut zip = zip::ZipArchive::new(file).map_err(|e| e.to_string())?; - let mut entry = |name: &str| -> Result, String> { - let f = zip.by_name(name).map_err(|e| format!("{name}: {e}"))?; + let mut entry = |name: &str| -> Result>, String> { + let f = match zip.by_name(name) { + Ok(f) => f, + Err(zip::result::ZipError::FileNotFound) => return Ok(None), + Err(e) => return Err(format!("{name}: {e}")), + }; let mut out = Vec::new(); f.take(MAX_WASM + 1) .read_to_end(&mut out) .map_err(|e| e.to_string())?; - Ok(out) + Ok(Some(out)) }; - let toml = String::from_utf8(entry(MANIFEST)?) - .map_err(|_| format!("{MANIFEST}: not UTF-8"))?; + let toml = entry(MANIFEST)?.ok_or_else(|| format!("{MANIFEST}: missing"))?; + let toml = String::from_utf8(toml).map_err(|_| format!("{MANIFEST}: not UTF-8"))?; (toml, entry(WASM)?) }; - if wasm.len() as u64 > MAX_WASM { + if wasm.as_ref().is_some_and(|w| w.len() as u64 > MAX_WASM) { return Err(format!("{WASM} is over {} MiB", MAX_WASM >> 20)); } - Ok(Package { - manifest: Manifest::parse(&toml)?, - wasm, - }) + let manifest = Manifest::parse(&toml)?; + if wasm.is_none() && !manifest.capabilities.contains(&Capability::Registries) { + return Err(format!( + "{WASM}: missing (only a content mod, with capability registries, may have no code)" + )); + } + Ok(Package { manifest, wasm }) } /// The `.hmod` bytes for `manifest_text` and a component. pub fn write(manifest_text: &str, wasm: &[u8]) -> Result, String> { + Self::write_files(manifest_text, Some(wasm), &[]) + } + /// The `.hmod` bytes for `manifest_text`, a component if the mod has + /// code, and content `files` (`assets/...`, `data/...`) by path. + pub fn write_files( + manifest_text: &str, + wasm: Option<&[u8]>, + files: &[(&str, &[u8])], + ) -> Result, String> { use std::io::Write; Manifest::parse(manifest_text)?; let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); let options = zip::write::SimpleFileOptions::default(); let err = |e: zip::result::ZipError| e.to_string(); - zip.start_file(MANIFEST, options).map_err(err)?; - zip.write_all(manifest_text.as_bytes()) - .map_err(|e| e.to_string())?; - zip.start_file(WASM, options).map_err(err)?; - zip.write_all(wasm).map_err(|e| e.to_string())?; + let mut put = |name: &str, bytes: &[u8]| -> Result<(), String> { + zip.start_file(name, options).map_err(err)?; + zip.write_all(bytes).map_err(|e| e.to_string()) + }; + put(MANIFEST, manifest_text.as_bytes())?; + if let Some(wasm) = wasm { + put(WASM, wasm)?; + } + for (name, bytes) in files { + crate::content::check_path(name)?; + put(name, bytes)?; + } Ok(zip.finish().map_err(err)?.into_inner()) } } @@ -256,8 +306,8 @@ capabilities = ["game-read", "hud"] fn refuses_bad_ids_and_apis() { let bad_id = EXAMPLE.replace("coords_hud", "Coords HUD"); assert!(Manifest::parse(&bad_id).unwrap_err().contains("is not")); - let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.2\""); - assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.2")); + let bad_api = EXAMPLE.replace("api = \"0.1\"", "api = \"0.3\""); + assert!(Manifest::parse(&bad_api).unwrap_err().contains("API 0.3")); let unknown = format!("{EXAMPLE}network = true\n"); assert!(Manifest::parse(&unknown).is_err()); } @@ -270,7 +320,7 @@ capabilities = ["game-read", "hud"] std::fs::write(&path, Package::write(EXAMPLE, b"\0asm").unwrap()).unwrap(); let p = Package::read(&path).unwrap(); assert_eq!(p.manifest.id, "coords_hud"); - assert_eq!(p.wasm, b"\0asm"); + assert_eq!(p.wasm.as_deref(), Some(&b"\0asm"[..])); std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index 7e3741287..f8a6e5865 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -153,9 +153,12 @@ impl Mods { let on = enabled(&package.manifest.id); entry.manifest = Some(package.manifest.clone()); if on { - entry.status = match mods.start(&package, &reserved) { + // Content is read before the world loads; a mod whose + // content is refused stays off, with the reason. + let content = crate::Content::read(path, &package.manifest); + entry.status = match content.and_then(|_| mods.start(&package, &reserved)) { Ok(run) => { - entry.run = Some(run); + entry.run = run; Status::Running } Err(e) => Status::Failed(e), @@ -184,12 +187,17 @@ impl Mods { Ok(self.engine.as_ref().expect("made above")) } + /// Starts a mod's code; `Ok(None)` for a content-only mod, which has + /// nothing to run (the game reads its content before the world loads). fn start( &mut self, package: &Package, reserved: &dyn Fn(&str) -> bool, - ) -> Result { + ) -> Result, String> { let m = &package.manifest; + let Some(wasm) = &package.wasm else { + return Ok(None); + }; if m.side == Side::Server { return Err("server mods do not run yet".into()); } @@ -202,7 +210,7 @@ impl Mods { let snapshot = self.snapshot.clone(); let (engine, linker) = self.engine()?; let component = - Component::new(engine, &package.wasm).map_err(|e| format!("not a component: {e}"))?; + Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; let ty = component.component_type(); let imports: Vec = ty .imports(engine) @@ -237,11 +245,11 @@ impl Mods { free }); self.out.append(&mut store.data_mut().out); - Ok(Running { + Ok(Some(Running { store, exports, hooks, - }) + })) } /// True when at least one mod runs: the game skips its mod work otherwise. @@ -403,7 +411,7 @@ impl Mods { match started { Ok(run) => { log::info!("Horizon: mod {id} reloaded"); - entry.run = Some(run); + entry.run = run; entry.status = Status::Running; } Err(e) => { diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 6a0389d55..6aa45e5cc 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -131,7 +131,8 @@ fn undeclared_capabilities_are_refused() { std::fs::create_dir_all(&dir).unwrap(); let wasm = Package::read(&mods_dir().join("horizon_mods_test_guest.hmod")) .unwrap() - .wasm; + .wasm + .expect("the guest has code"); let manifest = GUEST_MANIFEST.replace("[\"chat\"]", "[]"); std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); @@ -241,3 +242,34 @@ fn hook_overhead() { started.elapsed().as_secs_f64() * 1000.0 ); } + +#[test] +fn content_only_mods_load_without_an_engine() { + let manifest = r#" +id = "ruby" +name = "Ruby" +version = "0.1.0" +api = "0.2" +side = "both" +capabilities = ["registries"] +"#; + let block: &[u8] = br#"{"template": "minecraft:iron_block"}"#; + let dir = mods_dir().join("content"); + std::fs::create_dir_all(&dir).unwrap(); + let ok = dir.join("ruby.hmod"); + let files: &[(&str, &[u8])] = &[("data/ruby/horizon/block/ruby_block.json", block)]; + std::fs::write(&ok, Package::write_files(manifest, None, files).unwrap()).unwrap(); + let bad = dir.join("bad.hmod"); + let files: &[(&str, &[u8])] = &[("data/minecraft/recipe/stone.json", b"{}")]; + let bad_manifest = manifest.replace("\"ruby\"", "\"bad\""); + std::fs::write( + &bad, + Package::write_files(&bad_manifest, None, files).unwrap(), + ) + .unwrap(); + let mods = Mods::load(&[ok, bad], |_| true, |_| false); + assert_eq!(mods.entries()[0].status, Status::Running); + assert!(matches!(&mods.entries()[1].status, Status::Failed(e) if e.contains("own namespace"))); + // Content has no hooks: the game's per-tick mod work stays skipped. + assert!(!mods.is_running()); +} diff --git a/docs/mods.md b/docs/mods.md index 6b9f88096..6203c4066 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -262,6 +262,28 @@ capabilities = ["game-read", "hud", "chat"] Unknown keys are refused, so a typo is an error, not a silently ignored permission. +### Content mods (API 0.2) + +A mod with `api = "0.2"` and capability `registries` may carry `assets/` and +`data/` in the `.hmod`, and needs no `mod.wasm` if it has no code. It adds +blocks and items by declaring them in `data//horizon/block/*.json` and +`data//horizon/item/*.json`, each copying a vanilla template +([modpacks.md](modpacks.md#registries-02-data-driven-blocks-and-items)): + +```json +{ "template": "minecraft:iron_block", + "properties": { "hardness": 4.0, "light": 3, "sounds": "minecraft:amethyst_block" }, + "item": true } +``` + +The fence: files go in the mod's own namespace (`assets//`, +`data//`), plus additions to vanilla tags (`data/minecraft/tags/`). +Templates and `sounds` name vanilla blocks; unknown keys are refused. Paths +use vanilla's resource characters, at most 65,536 files, 16 MiB each and +512 MiB in all. A mod whose content is refused stays off, with the reason on +its row. The game reading this content into its block and item tables comes +next (docs/modpacks.md). + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and From 002cfcd8593dfc293b3ed9e07523bcfd0e0f3870 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:33:11 +0200 Subject: [PATCH 10/23] Content mods in the resource root: template rows appended to every block table horizon_client::mod_content builds the resource root for content mods as an overlay over the base root (vanilla, or the resource-pack overlay): - the base is linked; - the block and item tables are rewritten, each mod block getting its template's rows appended. That covers 13 JSON tables (facts, gameplay, behaviours, models, render, landing, items, command registries, mob data, worldgen flags, structure, survival) and 6 NBT ones (occlusion, collision, support, movement, worldgen block properties). Names, translation keys and in-table state ids move over, and the declared overrides apply; - each mod's own assets/ and data/ are copied in; - tag additions are merged into the tag files and both block-tag bundles. Vanilla state ids never move: mod states come after them, mods and blocks in id order. Rewritten JSON keeps its key order. With no content mod the root is the base itself. The game doesn't call this yet. Tested over the real prepared resources: every loader reads the overlay (Assets, BlockFacts, Items, collision, visibility, light, motion, worldgen GeneratorData). The mod blocks carry their templates' facts with the overrides applied, and vanilla's rows and ids are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/mod_content.rs | 818 ++++++++++++++++++ .../horizon-client/src/mod_content_tests.rs | 213 +++++ 3 files changed, 1032 insertions(+) create mode 100644 crates/horizon-client/src/mod_content.rs create mode 100644 crates/horizon-client/src/mod_content_tests.rs diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..d6b4dd345 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -107,6 +107,7 @@ pub mod mesher; pub mod minimap; pub mod mipmap; pub mod mobs; +pub mod mod_content; pub mod mod_list; mod model_library; pub mod models; diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs new file mode 100644 index 000000000..106d73010 --- /dev/null +++ b/crates/horizon-client/src/mod_content.rs @@ -0,0 +1,818 @@ +//! Content mods in the resource root (docs/modpacks.md, registries 0.2). +//! +//! Every loader reads one resource root, and most of its block and item +//! tables are exports from vanilla indexed by block-state id or keyed by +//! name. A content mod's block copies a vanilla *template*. So the mods' +//! root is an overlay, like the resource-pack one: +//! - the base root linked, with the per-state and per-name tables +//! rewritten: each mod block gets its template's rows appended (states +//! after vanilla's, mods and blocks in id order) with names, translation +//! keys and in-table state ids moved over, and the declared overrides +//! applied; +//! - each mod's own `assets/` and `data/` files; +//! - additions to tags merged into the tag files and bundles. +//! +//! The loaders need no mod code, vanilla state ids never move, and with no +//! content mod the root is the base root itself. +use crate::{Result, blocks::MAP_COLORS}; +use horizon_mods::content::{Block, Content, Rarity}; +use horizon_world::nbt::{self, JavaString, Limits, Tag}; +use serde::{Deserialize, Serialize, de}; +use std::{ + collections::BTreeMap, + fmt, fs, + ops::Range, + path::{Path, PathBuf}, +}; + +/// A content mod to put in the root: its id and content. +pub struct ContentMod { + pub id: String, + pub content: Content, +} + +/// JSON with its object keys in file order, so a rewritten table differs +/// from the original only by what was added. +#[derive(Clone, Debug, PartialEq)] +enum J { + Null, + Bool(bool), + Num(serde_json::Number), + Str(String), + Arr(Vec), + Obj(Vec<(String, J)>), +} +impl<'de> Deserialize<'de> for J { + fn deserialize>(d: D) -> std::result::Result { + struct V; + impl<'de> de::Visitor<'de> for V { + type Value = J; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("JSON") + } + fn visit_unit(self) -> std::result::Result { + Ok(J::Null) + } + fn visit_bool(self, v: bool) -> std::result::Result { + Ok(J::Bool(v)) + } + fn visit_i64(self, v: i64) -> std::result::Result { + Ok(J::Num(v.into())) + } + fn visit_u64(self, v: u64) -> std::result::Result { + Ok(J::Num(v.into())) + } + fn visit_f64(self, v: f64) -> std::result::Result { + serde_json::Number::from_f64(v) + .map(J::Num) + .ok_or_else(|| E::custom("not a JSON number")) + } + fn visit_str(self, v: &str) -> std::result::Result { + Ok(J::Str(v.to_owned())) + } + fn visit_string(self, v: String) -> std::result::Result { + Ok(J::Str(v)) + } + fn visit_seq>( + self, + mut a: A, + ) -> std::result::Result { + let mut out = Vec::new(); + while let Some(v) = a.next_element()? { + out.push(v); + } + Ok(J::Arr(out)) + } + fn visit_map>( + self, + mut a: A, + ) -> std::result::Result { + let mut out = Vec::new(); + while let Some(kv) = a.next_entry()? { + out.push(kv); + } + Ok(J::Obj(out)) + } + } + d.deserialize_any(V) + } +} +impl Serialize for J { + fn serialize(&self, s: S) -> std::result::Result { + use serde::ser::{SerializeMap, SerializeSeq}; + match self { + J::Null => s.serialize_unit(), + J::Bool(b) => s.serialize_bool(*b), + J::Num(n) => n.serialize(s), + J::Str(t) => s.serialize_str(t), + J::Arr(a) => { + let mut seq = s.serialize_seq(Some(a.len()))?; + for v in a { + seq.serialize_element(v)?; + } + seq.end() + } + J::Obj(o) => { + let mut map = s.serialize_map(Some(o.len()))?; + for (k, v) in o { + map.serialize_entry(k, v)?; + } + map.end() + } + } + } +} +impl J { + fn get(&self, key: &str) -> Option<&J> { + match self { + J::Obj(o) => o.iter().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + fn get_mut(&mut self, key: &str) -> Option<&mut J> { + match self { + J::Obj(o) => o.iter_mut().find(|(k, _)| k == key).map(|(_, v)| v), + _ => None, + } + } + /// Sets `key`, in place if present, else at the end. + fn set(&mut self, key: &str, value: J) { + if let Some(v) = self.get_mut(key) { + *v = value; + } else if let J::Obj(o) = self { + o.push((key.to_owned(), value)); + } + } + /// The value at a `/`-separated path ("" is the document). + fn at(&mut self, path: &str) -> Option<&mut J> { + path.split('/') + .filter(|p| !p.is_empty()) + .try_fold(self, |j, key| j.get_mut(key)) + } + fn f64(v: f64) -> J { + serde_json::Number::from_f64(v).map_or(J::Null, J::Num) + } + fn as_u32(&self) -> Option { + match self { + J::Num(n) => n.as_u64().and_then(|v| u32::try_from(v).ok()), + _ => None, + } + } + /// Renames strings and, with `ids`, moves state ids, everywhere inside. + fn rename(&mut self, r: &Rename, ids: bool) { + match self { + J::Str(s) => { + if let Some(new) = r.string(s) { + *s = new; + } + } + J::Num(n) if ids => { + if let Some(new) = n + .as_u64() + .and_then(|v| u32::try_from(v).ok()) + .and_then(|id| r.id(id)) + { + *n = new.into(); + } + } + J::Arr(a) => a.iter_mut().for_each(|v| v.rename(r, ids)), + J::Obj(o) => o.iter_mut().for_each(|(_, v)| v.rename(r, ids)), + _ => {} + } + } +} + +/// One id moving to another: `minecraft:iron_block` → `ruby:ruby_block`, +/// with its state range for blocks. +#[derive(Clone)] +struct Rename { + from: String, + to: String, + states: Range, + first: u32, +} +impl Rename { + fn new(from: &str, to: &str) -> Self { + Rename { + from: from.to_owned(), + to: to.to_owned(), + states: 0..0, + first: 0, + } + } + /// The id itself, `Block{id}`, and `block..` / `item..` keys. + fn string(&self, s: &str) -> Option { + if s == self.from { + return Some(self.to.clone()); + } + if s.strip_prefix("Block{").and_then(|x| x.strip_suffix('}')) == Some(&self.from) { + return Some(format!("Block{{{}}}", self.to)); + } + let key = |id: &str| id.replacen(':', ".", 1).replace('/', "."); + for kind in ["block", "item"] { + if s.strip_prefix(kind).and_then(|x| x.strip_prefix('.')) == Some(&key(&self.from)) { + return Some(format!("{kind}.{}", key(&self.to))); + } + } + None + } + fn id(&self, id: u32) -> Option { + self.states + .contains(&id) + .then(|| self.first + (id - self.states.start)) + } +} + +/// A block being added: its declaration and where its states go. +struct NewBlock<'a> { + decl: &'a Block, + rename: Rename, + /// The template's item, if it has one. + item: Option, +} +/// An item being added (declared, or a block's). +struct NewItem { + rename: Rename, + max_stack_size: Option, + rarity: Option, +} + +struct Plan<'a> { + blocks: Vec>, + items: Vec, + /// Vanilla's state count (the tables' length before). + states: usize, + /// Each vanilla block's default state. + defaults: BTreeMap, + /// The gameplay rows' sound objects, by block, for `sounds` overrides. + sounds: BTreeMap, +} + +fn read_json(path: &Path) -> Result { + Ok(serde_json::from_slice(&fs::read(path)?).map_err(|e| format!("{}: {e}", path.display()))?) +} + +impl<'a> Plan<'a> { + fn new(base: &Path, mods: &'a [ContentMod]) -> Result { + let mut facts = read_json(&base.join("facts.json"))?; + let names: Vec = match facts.at("states") { + Some(J::Arr(states)) => states + .iter() + .map(|s| match s { + J::Arr(row) => match row.first() { + Some(J::Str(name)) => Ok(name.clone()), + _ => Err("facts.json: a state without a name"), + }, + _ => Err("facts.json: a state that is not a row"), + }) + .collect::>()?, + _ => return Err("facts.json: no states".into()), + }; + let defaults: BTreeMap = match facts.at("defaults") { + Some(J::Obj(o)) => o + .iter() + .filter_map(|(k, v)| Some((k.clone(), v.as_u32()?))) + .collect(), + _ => return Err("facts.json: no defaults".into()), + }; + let range = |name: &str| -> Option> { + let start = names.iter().position(|n| n == name)?; + let len = names[start..].iter().take_while(|n| *n == name).count(); + // A block's states are one run in registry order. + (names[start + len..].iter().all(|n| n != name)) + .then_some(start as u32..(start + len) as u32) + }; + let mut blocks = Vec::new(); + let mut next = names.len() as u32; + let mut sorted: Vec<&ContentMod> = mods.iter().collect(); + sorted.sort_by(|a, b| a.id.cmp(&b.id)); + let mut wanted_sounds = Vec::new(); + for m in &sorted { + let mut declared: Vec<&Block> = m.content.blocks.iter().collect(); + declared.sort_by(|a, b| a.id.cmp(&b.id)); + for decl in declared { + if defaults.contains_key(&decl.id) { + return Err(format!("{}: {} is already a block", m.id, decl.id).into()); + } + let states = range(&decl.template).ok_or_else(|| { + format!("{}: template {} is not a block", decl.id, decl.template) + })?; + let mut rename = Rename::new(&decl.template, &decl.id); + rename.first = next; + next += states.len() as u32; + rename.states = states; + if let Some(s) = &decl.properties.sounds { + if !defaults.contains_key(s) { + return Err(format!("{}: sounds {s} is not a block", decl.id).into()); + } + wanted_sounds.push(s.clone()); + } + blocks.push(NewBlock { + decl, + rename, + item: None, + }); + } + } + // Block items copy the template block's item. + let gameplay = read_json(&base.join("gameplay-facts.json"))?; + let rows = match gameplay.get("states") { + Some(J::Arr(rows)) if rows.len() == names.len() => rows, + _ => return Err("gameplay-facts.json does not match facts.json".into()), + }; + let mut sounds = BTreeMap::new(); + for s in wanted_sounds { + let row = &rows[defaults[&s] as usize]; + sounds.insert(s, row.get("sound").cloned().unwrap_or(J::Null)); + } + let mut items = Vec::new(); + for b in &mut blocks { + let row = &rows[b.rename.states.start as usize]; + b.item = match row.get("item") { + Some(J::Str(i)) if i != "minecraft:air" => Some(i.clone()), + _ => None, + }; + if b.decl.item { + let item = b.item.as_deref().ok_or_else(|| { + format!("{}: template {} has no item", b.decl.id, b.decl.template) + })?; + items.push(NewItem { + rename: Rename::new(item, &b.decl.id), + max_stack_size: None, + rarity: None, + }); + } + } + for m in &sorted { + for i in &m.content.items { + items.push(NewItem { + rename: Rename::new(&i.template, &i.id), + max_stack_size: i.max_stack_size, + rarity: i.rarity, + }); + } + } + Ok(Plan { + blocks, + items, + states: names.len(), + defaults, + sounds, + }) + } + + /// What moves in a new block's copies of its template's rows: the + /// block, and the template's item when it has another name. A block + /// without an item gets `minecraft:air` where rows name one. + fn renames(&self, b: &NewBlock) -> Vec { + let mut out = vec![b.rename.clone()]; + if let Some(item) = b.item.as_deref().filter(|i| *i != b.decl.template) + && b.decl.item + { + out.push(Rename::new(item, &b.decl.id)); + } + out + } + + /// Appends each new block's copies of the template's states to `list`; + /// `gameplay` rows get their index and the declared overrides. + fn states(&self, list: &mut Vec, ids: bool, gameplay: bool) -> Result<()> { + if list.len() != self.states { + return Err(format!("{} states, not {}", list.len(), self.states).into()); + } + for b in &self.blocks { + let renames = self.renames(b); + for (i, id) in b.rename.states.clone().enumerate() { + let mut row = list[id as usize].clone(); + for r in &renames { + row.rename(r, ids); + } + if gameplay { + row.set("id", J::Num((b.rename.first + i as u32).into())); + if !b.decl.item { + row.set("item", J::Str("minecraft:air".into())); + } + self.override_gameplay(b, &mut row); + } + list.push(row); + } + } + Ok(()) + } + + /// The declared properties, on a gameplay row. + fn override_gameplay(&self, b: &NewBlock, row: &mut J) { + let p = &b.decl.properties; + if let Some(v) = p.hardness { + row.set("hardness", J::f64(v as f64)); + } + if let Some(v) = p.explosion_resistance { + row.set("explosion_resistance", J::f64(v as f64)); + } + if let Some(v) = p.light { + row.set("emission", J::Num(v.into())); + } + if let Some(v) = p.requires_tool { + row.set("requires_tool", J::Bool(v)); + } + if let Some(v) = p.friction { + row.set("friction", J::f64(v as f64)); + } + if let Some(v) = p.map_color { + let col = if v == 0 { 0 } else { MAP_COLORS[v as usize] }; + row.set("map_color", J::Num(col.into())); + } + if let Some(s) = &p.sounds { + row.set("sound", self.sounds[s].clone()); + } + } + + /// Adds each new block's copy of the template's entry to a map by name. + fn names(&self, map: &mut J, ids: bool) { + for b in &self.blocks { + if let Some(v) = map.get(&b.decl.template) { + let mut v = v.clone(); + for r in &self.renames(b) { + v.rename(r, ids); + } + map.set(&b.decl.id, v); + } + } + } + + /// Adds each new item's copy of its template's entry to a map by name; + /// `components` applies the overrides (items.json). + fn items(&self, map: &mut J, components: bool) { + for i in &self.items { + let Some(v) = map.get(&i.rename.from) else { + continue; + }; + let mut v = v.clone(); + v.rename(&i.rename, false); + if components { + if let Some(n) = i.max_stack_size { + v.set("minecraft:max_stack_size", J::Num(n.into())); + } + if let Some(r) = i.rarity { + let r = match r { + Rarity::Common => "common", + Rarity::Uncommon => "uncommon", + Rarity::Rare => "rare", + Rarity::Epic => "epic", + }; + v.set("minecraft:rarity", J::Str(r.into())); + } + } + map.set(&i.rename.to, v); + } + } + + /// One JSON table, rewritten. + fn json(&self, name: &str, doc: &mut J) -> Result<()> { + let states = |doc: &mut J, path: &str, ids: bool, gameplay: bool| -> Result<()> { + match doc.at(path) { + Some(J::Arr(a)) => self.states(a, ids, gameplay), + _ => Err(format!("no list at /{path}").into()), + } + }; + match name { + "facts.json" => { + states(doc, "states", false, false)?; + let defaults = doc.at("defaults").ok_or("no defaults")?; + for b in &self.blocks { + let default = self.defaults[&b.decl.template]; + let id = b.rename.id(default).ok_or("a default outside its block")?; + defaults.set(&b.decl.id, J::Num(id.into())); + } + } + "gameplay-facts.json" => states(doc, "states", false, true)?, + "block-behaviours.json" => { + states(doc, "states", false, false)?; + let Some(J::Arr(blocks)) = doc.at("blocks") else { + return Err("no blocks".into()); + }; + for b in &self.blocks { + let template = blocks.iter().find( + |x| matches!(x.get("name"), Some(J::Str(n)) if *n == b.decl.template), + ); + if let Some(mut v) = template.cloned() { + for r in &self.renames(b) { + v.rename(r, false); + } + if !b.decl.item { + v.set("item", J::Str("minecraft:air".into())); + } + blocks.push(v); + } + } + self.items(doc.at("items").ok_or("no items")?, false); + for odds in ["fire/burnOdds", "fire/igniteOdds"] { + if let Some(map) = doc.at(odds) { + self.names(map, false); + } + } + } + "model-states.json" + | "landing-definitions.json" + | "worldgen/blocks/survival-rules.json" => self.names(doc, false), + "render-definitions.json" => self.names(doc, true), + "worldgen/blocks/survival-extra-definitions.json" => { + if let Some(map) = doc.at("ignition_odds") { + self.names(map, false); + } + } + "items.json" => self.items(doc, true), + "command-registries.json" => { + self.names(doc.at("blocks").ok_or("no blocks")?, false); + let Some(J::Arr(items)) = doc.at("items") else { + return Err("no items".into()); + }; + items.extend(self.items.iter().map(|i| J::Str(i.rename.to.clone()))); + } + "mob-data.json" => states(doc, "states", false, false)?, + "worldgen/block_flags.json" => states(doc, "", false, false)?, + "worldgen/blocks/structure-blocks.json" => { + for key in ["rotate", "mirror", "full_block"] { + states(doc, key, true, false)?; + } + let added: usize = self.blocks.iter().map(|b| b.rename.states.len()).sum(); + doc.set("states", J::Num(((self.states + added) as u64).into())); + } + _ => return Err("no rule for this table".into()), + } + Ok(()) + } + + /// One NBT table: `states` lists, `cached_shapes` arrays and `blocks` + /// compounds, wherever they are. + fn nbt(&self, tag: &mut Tag) { + let Tag::Compound(c) = tag else { + return; + }; + for (key, value) in c.iter_mut() { + match (key.to_string_lossy().as_str(), value) { + ("states", Tag::List(list)) if list.len() == self.states => { + for b in &self.blocks { + for id in b.rename.states.clone() { + let mut state = list[id as usize].clone(); + if let Some(slot) = state.get_mut("id") { + *slot = Tag::String(b.decl.id.as_str().into()); + } + list.push(state); + } + } + } + ("cached_shapes", Tag::IntArray(a)) if a.len() == self.states => { + for b in &self.blocks { + let r = &b.rename.states; + let copy = a[r.start as usize..r.end as usize].to_vec(); + a.extend(copy); + } + } + ("blocks", Tag::Compound(map)) => { + for b in &self.blocks { + let Some(mut v) = map + .get(&JavaString::from(b.decl.template.as_str())) + .cloned() + else { + continue; + }; + if let (Some(f), Some(slot)) = + (b.decl.properties.friction, v.get_mut("friction")) + { + *slot = Tag::Float(f.to_bits()); + } + map.insert(b.decl.id.as_str().into(), v); + } + } + (_, inner @ Tag::Compound(_)) => self.nbt(inner), + _ => {} + } + } + } +} + +/// The JSON and NBT tables rewritten for new blocks and items. +const JSON_TABLES: [&str; 13] = [ + "facts.json", + "gameplay-facts.json", + "block-behaviours.json", + "model-states.json", + "render-definitions.json", + "landing-definitions.json", + "items.json", + "command-registries.json", + "mob-data.json", + "worldgen/block_flags.json", + "worldgen/blocks/structure-blocks.json", + "worldgen/blocks/survival-rules.json", + "worldgen/blocks/survival-extra-definitions.json", +]; +const NBT_TABLES: [&str; 6] = [ + "occlusion.nbt", + "cached-collision.nbt", + "movement-properties.nbt", + "worldgen/blocks/block-properties.nbt", + "worldgen/blocks/cached-support.nbt", + "worldgen/blocks/cached-collision.nbt", +]; +/// Bundles of block tag files (tag id → the tag file's text). +const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; + +/// The overlay being written: `out` mirrors `base` through links, and a +/// directory becomes real only when something inside it is written. +struct Overlay<'a> { + base: &'a Path, + out: &'a Path, +} +impl Overlay<'_> { + fn new<'a>(base: &'a Path, out: &'a Path) -> Result> { + if fs::symlink_metadata(out).is_ok() { + fs::remove_dir_all(out)?; + } + fs::create_dir_all(out)?; + let overlay = Overlay { base, out }; + overlay.link_children(Path::new(""))?; + Ok(overlay) + } + fn link_children(&self, rel: &Path) -> Result<()> { + let Ok(read) = fs::read_dir(self.base.join(rel)) else { + return Ok(()); + }; + for entry in read.flatten() { + let rel = rel.join(entry.file_name()); + link(&self.base.join(&rel), &self.out.join(&rel))?; + } + Ok(()) + } + /// Makes `rel`'s directories real, each holding links to the base's. + fn dir(&self, rel: &Path) -> Result<()> { + let mut at = PathBuf::new(); + for part in rel.iter() { + at.push(part); + let path = self.out.join(&at); + let meta = fs::symlink_metadata(&path); + if meta + .as_ref() + .is_ok_and(|m| m.is_dir() && !m.file_type().is_symlink()) + { + continue; + } + if meta.is_ok() { + fs::remove_file(&path)?; + } + fs::create_dir(&path)?; + self.link_children(&at)?; + } + Ok(()) + } + fn write(&self, rel: &str, bytes: &[u8]) -> Result<()> { + let rel = Path::new(rel); + if let Some(parent) = rel.parent() { + self.dir(parent)?; + } + let path = self.out.join(rel); + if fs::symlink_metadata(&path).is_ok() { + fs::remove_file(&path)?; + } + fs::write(path, bytes)?; + Ok(()) + } +} +#[cfg(unix)] +fn link(target: &Path, at: &Path) -> std::io::Result<()> { + std::os::unix::fs::symlink(target, at) +} +#[cfg(not(unix))] +fn link(target: &Path, at: &Path) -> std::io::Result<()> { + if target.is_dir() { + fs::create_dir_all(at)?; + for entry in fs::read_dir(target)?.flatten() { + link(&entry.path(), &at.join(entry.file_name()))?; + } + Ok(()) + } else { + fs::copy(target, at).map(|_| ()) + } +} + +/// A tag file's JSON text with `more` appended to its values (no repeats). +fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result { + let mut doc = match text { + Some(t) => serde_json::from_str(t).map_err(|e| format!("{what}: {e}"))?, + None => J::Obj(vec![("values".into(), J::Arr(Vec::new()))]), + }; + let Some(J::Arr(values)) = doc.get_mut("values") else { + return Err(format!("{what}: no values").into()); + }; + for v in more { + if !values.contains(v) { + values.push(v.clone()); + } + } + Ok(serde_json::to_string_pretty(&doc)?) +} + +/// Builds the content root for `mods` over `base` in `out`. +pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { + let plan = Plan::new(base, mods)?; + let overlay = Overlay::new(base, out)?; + for name in JSON_TABLES { + let path = base.join(name); + if !path.exists() { + continue; + } + let mut doc = read_json(&path)?; + plan.json(name, &mut doc) + .map_err(|e| format!("{name}: {e}"))?; + overlay.write(name, &serde_json::to_vec(&doc)?)?; + } + for name in NBT_TABLES { + let path = base.join(name); + if !path.exists() { + continue; + } + let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::default()) + .map_err(|e| format!("{name}: {e}"))?; + plan.nbt(&mut named.tag); + let bytes = + nbt::write_named(&named, Limits::default()).map_err(|e| format!("{name}: {e}"))?; + overlay.write(name, &bytes)?; + } + // Mod files, and every tag addition gathered per tag file. + let mut tags: BTreeMap> = BTreeMap::new(); + for m in mods { + let declarations = format!("data/{}/horizon/", m.id); + for file in &m.content.files { + let bytes = m.content.file(file)?; + let is_tag = file.starts_with("data/") && file.contains("/tags/"); + if is_tag && file.ends_with(".json") { + let doc: J = serde_json::from_slice(&bytes).map_err(|e| format!("{file}: {e}"))?; + if doc.get("replace") == Some(&J::Bool(true)) { + let e = format!( + "{}: {file}: a mod adds to tags, it cannot replace them", + m.id + ); + return Err(e.into()); + } + let Some(J::Arr(values)) = doc.get("values") else { + return Err(format!("{}: {file}: no values", m.id).into()); + }; + tags.entry(file.clone()) + .or_default() + .extend(values.iter().cloned()); + } else if !file.starts_with(&declarations) { + overlay.write(file, &bytes)?; + } + } + } + let mut bundles: Vec<(&str, J)> = Vec::new(); + for name in TAG_BUNDLES { + if base.join(name).exists() { + bundles.push((name, read_json(&base.join(name))?)); + } + } + for (file, values) in &tags { + let vanilla = fs::read_to_string(base.join(file)).ok(); + overlay.write( + file, + merge_tag(vanilla.as_deref(), values, file)?.as_bytes(), + )?; + // data//tags/block/.json is the block tag :. + let Some((ns, path)) = file + .strip_prefix("data/") + .and_then(|r| r.split_once("/tags/block/")) + .and_then(|(ns, p)| Some((ns, p.strip_suffix(".json")?))) + else { + continue; + }; + let id = format!("{ns}:{path}"); + for (name, doc) in &mut bundles { + let text = match doc.get(&id) { + Some(J::Str(t)) => Some(t.clone()), + _ => None, + }; + let merged = merge_tag(text.as_deref(), values, name)?; + doc.set(&id, J::Str(merged)); + } + } + for (name, doc) in &bundles { + overlay.write(name, &serde_json::to_vec(doc)?)?; + } + Ok(()) +} + +/// The root to load: `base` itself with no content, else the mods' overlay +/// over it, built in `cache/mod-content`. +pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result { + if mods.iter().all(|m| m.content.is_empty()) { + return Ok(base.to_owned()); + } + let out = cache.join("mod-content"); + build(base, mods, &out)?; + Ok(out) +} + +#[cfg(test)] +#[path = "mod_content_tests.rs"] +mod tests; diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs new file mode 100644 index 000000000..b5f235916 --- /dev/null +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -0,0 +1,213 @@ +use super::*; +use crate::{assets::Assets, blocks::BlockFacts, items::Items}; + +#[test] +fn renames_ids_keys_and_states() { + let mut r = Rename::new("minecraft:iron_block", "ruby:ruby_block"); + r.states = 10..12; + r.first = 100; + assert_eq!( + r.string("minecraft:iron_block").as_deref(), + Some("ruby:ruby_block") + ); + assert_eq!( + r.string("Block{minecraft:iron_block}").as_deref(), + Some("Block{ruby:ruby_block}") + ); + assert_eq!( + r.string("block.minecraft.iron_block").as_deref(), + Some("block.ruby.ruby_block") + ); + assert_eq!(r.string("minecraft:iron_blocks"), None); + assert_eq!(r.string("block.minecraft.iron_bars"), None); + assert_eq!( + (r.id(9), r.id(10), r.id(11), r.id(12)), + (None, Some(100), Some(101), None) + ); +} + +#[test] +fn json_keeps_key_order_and_numbers() { + let text = r#"{"z":1,"a":[0.6,5.0,-1,{"m":null,"b":true}],"k":"v"}"#; + let doc: J = serde_json::from_str(text).unwrap(); + assert_eq!(serde_json::to_string(&doc).unwrap(), text); +} + +#[test] +fn tags_merge_without_repeats() { + let vanilla = r#"{"values": ["minecraft:stone"]}"#; + let more = [ + J::Str("ruby:ruby_block".into()), + J::Str("minecraft:stone".into()), + ]; + let merged: serde_json::Value = + serde_json::from_str(&merge_tag(Some(vanilla), &more, "t").unwrap()).unwrap(); + assert_eq!( + merged["values"], + serde_json::json!(["minecraft:stone", "ruby:ruby_block"]) + ); +} + +fn prepared() -> Option { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + root.join("gameplay-facts.json").exists().then_some(root) +} + +/// A content mod folder: a full block, a door and an item-less glass from +/// templates, an item, a vanilla tag addition and a language file. +fn ruby_mod(dir: &Path) -> ContentMod { + let files: [(&str, &str); 7] = [ + ( + "horizon-mod.toml", + "id = \"ruby\"\nname = \"Ruby\"\nversion = \"0.1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + ), + ( + "data/ruby/horizon/block/ruby_block.json", + r#"{"template": "minecraft:iron_block", "properties": {"hardness": 4.0, "light": 3, + "sounds": "minecraft:amethyst_block", "map_color": 28, "friction": 0.8}}"#, + ), + ( + "data/ruby/horizon/block/ruby_door.json", + r#"{"template": "minecraft:oak_door"}"#, + ), + ( + "data/ruby/horizon/block/ruby_glass.json", + r#"{"template": "minecraft:glass", "item": false}"#, + ), + ( + "data/ruby/horizon/item/ruby.json", + r#"{"template": "minecraft:diamond", "max_stack_size": 16, "rarity": "rare"}"#, + ), + ( + "data/minecraft/tags/block/mineable/pickaxe.json", + r#"{"values": ["ruby:ruby_block"]}"#, + ), + ( + "assets/ruby/lang/en_us.json", + r#"{"block.ruby.ruby_block": "Block of Ruby"}"#, + ), + ]; + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + let package = horizon_mods::Package::read(dir).unwrap(); + ContentMod { + id: "ruby".into(), + content: Content::read(dir, &package.manifest).unwrap(), + } +} + +/// The overlay over the real prepared resources: every loader reads it, the +/// new blocks behave like their templates with the overrides, and vanilla's +/// states are where they were. +#[test] +fn content_root_loads_with_every_table() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let m = ruby_mod(&scratch.join("ruby")); + let root = resource_root(&base, std::slice::from_ref(&m), &scratch.join("cache")).unwrap(); + assert_ne!(root, base); + + let vanilla = Assets::load(&base).unwrap(); + let assets = Assets::load(&root).unwrap(); + let (old, new) = (vanilla.registry, assets.registry); + let n = old.len() as u32; + let iron = old.default_state("minecraft:iron_block").unwrap(); + let door = old.default_state("minecraft:oak_door").unwrap(); + let door_first = (0..n) + .map(BlockStateId) + .find(|&s| old.state(s).unwrap().name == "minecraft:oak_door") + .unwrap(); + // Vanilla keeps its ids; blocks come after, sorted: ruby_block, ruby_door, ruby_glass. + assert_eq!(new.len(), old.len() + 1 + 64 + 1); + assert_eq!(new.default_state("minecraft:iron_block"), Some(iron)); + let ruby = new.default_state("ruby:ruby_block").unwrap(); + assert_eq!(ruby, BlockStateId(n)); + let ruby_door = new.default_state("ruby:ruby_door").unwrap(); + assert_eq!(ruby_door, BlockStateId(n + 1 + (door.0 - door_first.0))); + assert_eq!( + new.default_state("ruby:ruby_glass"), + Some(BlockStateId(n + 65)) + ); + + let old_facts = BlockFacts::load(&base, old).unwrap(); + let facts = BlockFacts::load(&root, new).unwrap(); + let (a, b) = (old_facts.get(iron), facts.get(ruby)); + assert_eq!((b.hardness, b.emission, b.friction), (4.0, 3, 0.8)); + assert_eq!(b.explosion_resistance, a.explosion_resistance); + assert_eq!(b.outline, a.outline); + assert_eq!(b.classes, a.classes); + assert_eq!(&*b.item, "ruby:ruby_block"); + assert_eq!(b.map_color, 28); + let amethyst = old_facts.get(old.default_state("minecraft:amethyst_block").unwrap()); + assert_eq!(b.sounds.break_sound, amethyst.sounds.break_sound); + for i in 0..64 { + let (v, m) = ( + old_facts.get(BlockStateId(door_first.0 + i)), + facts.get(BlockStateId(n + 1 + i)), + ); + assert_eq!( + (v.outline.clone(), v.hardness, v.classes.clone()), + (m.outline.clone(), m.hardness, m.classes.clone()) + ); + assert_eq!(&*m.name, "ruby:ruby_door"); + } + let glass = facts.get(BlockStateId(n + 65)); + assert_eq!(&*glass.item, "minecraft:air"); + // Vanilla's own rows are untouched. + assert_eq!(facts.get(iron).hardness, a.hardness); + assert_eq!(&*facts.get(iron).name, "minecraft:iron_block"); + + let items = Items::load(&root, new, &facts).unwrap(); + let ruby_block = &items.items["ruby:ruby_block"]; + assert_eq!(ruby_block.block, Some(ruby)); + let gem = &items.items["ruby:ruby"]; + assert_eq!(gem.max_stack, 16); + assert!(!items.items.contains_key("ruby:ruby_glass")); + assert!(items.block_tags["minecraft:mineable/pickaxe"].contains("ruby:ruby_block")); + + crate::collisions::load(&root, new).unwrap(); + crate::models::load_visibility(&root, new).unwrap(); + crate::light::LightTables::load(&root, new, &facts).unwrap(); + crate::motion::MotionResources::load(&root, &assets).unwrap(); + horizon_world::worldgen::generator::GeneratorData::load(&root.join("worldgen"), new).unwrap(); + assert!(root.join("assets/ruby/lang/en_us.json").is_file()); + + // The base root was only read. + assert!( + fs::symlink_metadata(base.join("facts.json")) + .unwrap() + .is_file() + ); + fs::remove_dir_all(&scratch).unwrap(); +} + +#[test] +fn refuses_unknown_templates_and_vanilla_ids() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-refuse-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let mut m = ruby_mod(&scratch.join("ruby")); + m.content.blocks[0].template = "minecraft:not_a_block".into(); + let e = build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap_err(); + assert!(e.to_string().contains("is not a block"), "{e}"); + fs::remove_dir_all(&scratch).unwrap(); +} + +#[test] +fn no_content_keeps_the_base_root() { + let base = Path::new("/nonexistent/base"); + assert_eq!( + resource_root(base, &[], Path::new("/nonexistent/cache")).unwrap(), + base + ); +} + +use horizon_world::registry::BlockStateId; From ac7b7f98c0292ead567c90b4553bdbd911128329 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:13:17 +0200 Subject: [PATCH 11/23] Content mods in the game: loot, recipes, models, names and icons from mod namespaces The game builds the content root from the enabled content mods at startup. Loaders that only read the minecraft namespace now also read the content mods' namespaces (from the root's marker file): block loot tables, recipes, blockstates, language files, and the HUD atlas's item sprites. /give and the command registries know the new items and blocks. A block without a blockstate of its own takes its template's, so every state has a model. Adds examples/ruby-content, a folder content mod: a ruby block and a ruby item with recipes, loot, tags, models, textures and names. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/crafting.rs | 39 +++++++++---- crates/horizon-client/src/creative.rs | 21 ++++--- crates/horizon-client/src/game.rs | 5 ++ crates/horizon-client/src/game/mods.rs | 54 ++++++++++++++++++ crates/horizon-client/src/hud.rs | 6 +- crates/horizon-client/src/items.rs | 38 ++++++++---- crates/horizon-client/src/mod_content.rs | 41 ++++++++++++- .../horizon-client/src/mod_content_tests.rs | 5 ++ crates/horizon-client/src/models.rs | 2 +- crates/horizon-client/src/models/catalog.rs | 6 +- .../assets/ruby/blockstates/ruby_block.json | 7 +++ .../ruby-content/assets/ruby/items/ruby.json | 6 ++ .../assets/ruby/items/ruby_block.json | 6 ++ .../ruby-content/assets/ruby/lang/en_us.json | 4 ++ .../assets/ruby/models/block/ruby_block.json | 6 ++ .../assets/ruby/models/item/ruby.json | 6 ++ .../assets/ruby/textures/block/ruby_block.png | Bin 0 -> 149 bytes .../assets/ruby/textures/item/ruby.png | Bin 0 -> 149 bytes .../tags/block/mineable/pickaxe.json | 5 ++ .../minecraft/tags/block/needs_iron_tool.json | 5 ++ .../data/ruby/horizon/block/ruby_block.json | 9 +++ .../data/ruby/horizon/item/ruby.json | 4 ++ .../ruby/loot_table/blocks/ruby_block.json | 18 ++++++ .../data/ruby/recipe/ruby_block.json | 15 +++++ .../ruby/recipe/ruby_from_ruby_block.json | 10 ++++ .../examples/ruby-content/horizon-mod.toml | 11 ++++ 26 files changed, 294 insertions(+), 35 deletions(-) create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json create mode 100644 crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index e4a70811a..457ddf497 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -14,7 +14,7 @@ use serde_json::Value; use std::{ collections::{HashMap, HashSet}, fs, - path::Path, + path::{Path, PathBuf}, sync::Arc, }; @@ -1182,18 +1182,33 @@ impl Recipes { let mut crafting = Vec::new(); let mut cooking = Vec::new(); let mut meta = HashMap::new(); - let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))? - .flatten() - .map(|e| e.path()) - .filter(|p| p.extension().is_some_and(|e| e == "json")) + let json_files = |dir: &Path| -> Result> { + let mut files: Vec<_> = fs::read_dir(dir)? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + Ok(files) + }; + // Vanilla's recipes by bare name, then content mods' as `:`. + let mut files: Vec<(String, PathBuf)> = json_files(&root.join("data/minecraft/recipe"))? + .into_iter() + .map(|p| (String::new(), p)) .collect(); - files.sort(); - for path in files { - let name = path - .file_stem() - .and_then(|s| s.to_str()) - .unwrap_or("") - .to_owned(); + for namespace in crate::mod_content::namespaces(root) { + let dir = root.join(format!("data/{namespace}/recipe")); + if dir.is_dir() { + files.extend( + json_files(&dir)? + .into_iter() + .map(|p| (format!("{namespace}:"), p)), + ); + } + } + for (prefix, path) in files { + let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); + let name = format!("{prefix}{stem}"); let v: Value = serde_json::from_slice(&fs::read(&path)?)?; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 942bf13b9..80445d541 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -49,17 +49,24 @@ pub struct Names { } impl Names { pub fn load(root: &Path) -> Self { - let map = fs::read(root.join("assets/minecraft/lang/en_us.json")) - .ok() - .and_then(|b| serde_json::from_slice::>(&b).ok()) - .unwrap_or_default(); + let read = |namespace: &str| { + fs::read(root.join(format!("assets/{namespace}/lang/en_us.json"))) + .ok() + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default() + }; + let mut map = read("minecraft"); + // Content mods' names (docs/modpacks.md); none in a vanilla root. + for namespace in crate::mod_content::namespaces(root) { + map.extend(read(&namespace)); + } Self { map } } pub fn item(&self, id: &str) -> String { - let path = id.trim_start_matches("minecraft:"); + let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id)); self.map - .get(&format!("item.minecraft.{path}")) - .or_else(|| self.map.get(&format!("block.minecraft.{path}"))) + .get(&format!("item.{namespace}.{path}")) + .or_else(|| self.map.get(&format!("block.{namespace}.{path}"))) .cloned() .unwrap_or_else(|| path.replace('_', " ")) } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7072abeb5..fb83c291f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -9746,6 +9746,11 @@ pub fn run() -> Result<()> { let vanilla_root = options.resources.clone(); let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs); + options.resources = mods::content_root( + &options.resources, + &early_settings.mods.enabled, + &options.dev_mods, + ); let assets = match Assets::load(&options.resources) { Ok(assets) => assets, // Minecraft.rollbackResourcePacks: the packs break loading, start diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 56cb1d0d8..939cb671d 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -47,6 +47,60 @@ fn vanilla_command(name: &str) -> bool { .any(|&c| d.nodes[c].name() == name) } +/// `root` with the content mods that are on layered over it +/// (docs/modpacks.md): their blocks, items, data and assets. Read once at +/// start, before the resources load; a mod whose content is refused is left +/// out here and its row on the Mods page says why. +pub(super) fn content_root( + root: &std::path::Path, + enabled: &std::collections::BTreeSet, + dev: &[std::path::PathBuf], +) -> std::path::PathBuf { + use horizon_client::mod_content::{self, ContentMod}; + use horizon_mods::{Capability, Content, Package}; + let here = std::env::current_dir().unwrap_or_default(); + let mut paths = horizon_mods::find(&here.join(mod_list::DIR)); + paths.retain(|p| !dev.contains(p)); + paths.extend(dev.iter().cloned()); + let mut mods: Vec = Vec::new(); + for path in &paths { + let Ok(package) = Package::read(path) else { + continue; + }; + let m = &package.manifest; + let on = enabled.contains(&m.id) || dev.contains(path); + if !on + || !m.capabilities.contains(&Capability::Registries) + || mods.iter().any(|c| c.id == m.id) + { + continue; + } + match Content::read(path, m) { + Ok(content) => mods.push(ContentMod { + id: m.id.clone(), + content, + }), + Err(e) => log::warn!("Horizon: mod {} content not loaded: {e}", m.id), + } + } + match mod_content::resource_root(root, &mods, &here.join(".horizon-cache")) { + Ok(out) => { + if out != root { + log::info!( + "Horizon: content from {} mod(s) in {}", + mods.len(), + out.display() + ); + } + out + } + Err(e) => { + log::warn!("Horizon: content mods not loaded: {e}"); + root.to_owned() + } + } +} + impl Game<'_> { /// Reads `horizon-mods/` and the dev mods, and starts the ones turned on. pub(super) fn start_mods(&mut self) { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index e73803ee7..cf4861458 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -102,8 +102,10 @@ fn atlas_sprites(root: &Path, packed: &[PackedImage]) -> Vec { let image = match &origin { SpriteOrigin::File(texture) => { let path = texture.strip_prefix("minecraft:").unwrap_or(texture); - // Packed under its own name already: only a renamed file is new. - if path == name { + // A vanilla file is packed under its own name already: + // only a renamed one is new. Other namespaces' files + // (content mods) are never in the walked directories. + if texture.starts_with("minecraft:") && path == name { continue; } load(texture, "textures").map(|(w, h, p)| { diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index bf49efec7..0aca99cef 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -512,11 +512,16 @@ impl Items { let mut loot = HashMap::new(); // Every loot table, keyed by its id (blocks/stone, entities/sheep/white, // gameplay/chicken_lay, shearing/sheep/red...). - fn walk_loot(dir: &Path, base: &Path, loot: &mut HashMap) -> Result<()> { + fn walk_loot( + dir: &Path, + base: &Path, + namespace: &str, + loot: &mut HashMap, + ) -> Result<()> { for entry in fs::read_dir(dir)?.flatten() { let p = entry.path(); if p.is_dir() { - walk_loot(&p, base, loot)?; + walk_loot(&p, base, namespace, loot)?; } else if p.extension().is_some_and(|e| e == "json") { let id = p .strip_prefix(base)? @@ -524,7 +529,7 @@ impl Items { .to_string_lossy() .replace('\\', "/"); loot.insert( - format!("minecraft:{id}"), + format!("{namespace}:{id}"), serde_json::from_slice(&fs::read(&p)?)?, ); } @@ -532,7 +537,14 @@ impl Items { Ok(()) } let loot_root = root.join("data/minecraft/loot_table"); - walk_loot(&loot_root, &loot_root, &mut loot)?; + walk_loot(&loot_root, &loot_root, "minecraft", &mut loot)?; + // Content mods' tables (docs/modpacks.md): `:blocks/...`. + for namespace in crate::mod_content::namespaces(root) { + let dir = root.join(format!("data/{namespace}/loot_table")); + if dir.is_dir() { + walk_loot(&dir, &dir, &namespace, &mut loot)?; + } + } let registry_order = registry_order(root, &order); Ok(Self { items, @@ -644,12 +656,15 @@ impl Items { state: BlockStateId, ) -> Option { let block = registry.state(state)?; - let name = block.name.trim_start_matches("minecraft:"); + let (namespace, name) = block + .name + .split_once(':') + .unwrap_or(("minecraft", &block.name)); let standing = name.replacen("_wall_", "_", 1); let standing = standing.strip_prefix("wall_").unwrap_or(&standing); let standing = standing.replacen("wall_", "", 1); - self.loot_sequence(&format!("minecraft:blocks/{name}")) - .or_else(|| self.loot_sequence(&format!("minecraft:blocks/{standing}"))) + self.loot_sequence(&format!("{namespace}:blocks/{name}")) + .or_else(|| self.loot_sequence(&format!("{namespace}:blocks/{standing}"))) } /// Evaluate the block's loot table for a player break without explosions. pub fn block_drops( @@ -737,7 +752,10 @@ impl Items { let Some(block) = registry.state(state) else { return vec![]; }; - let name = block.name.trim_start_matches("minecraft:"); + let (namespace, name) = block + .name + .split_once(':') + .unwrap_or(("minecraft", &block.name)); // `Blocks.wallVariant`: wall signs, banners, heads, fans and torches // reuse the standing block's loot table. let standing = name.replacen("_wall_", "_", 1); @@ -745,8 +763,8 @@ impl Items { let standing = standing.replacen("wall_", "", 1); let table = self .loot - .get(&format!("minecraft:blocks/{name}")) - .or_else(|| self.loot.get(&format!("minecraft:blocks/{standing}"))); + .get(&format!("{namespace}:blocks/{name}")) + .or_else(|| self.loot.get(&format!("{namespace}:blocks/{standing}"))); let Some(table) = table else { return vec![]; }; diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index 106d73010..3a8c2920e 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -524,10 +524,19 @@ impl<'a> Plan<'a> { "items.json" => self.items(doc, true), "command-registries.json" => { self.names(doc.at("blocks").ok_or("no blocks")?, false); + let new_items = || self.items.iter().map(|i| J::Str(i.rename.to.clone())); + let new_blocks = || self.blocks.iter().map(|b| J::Str(b.decl.id.clone())); let Some(J::Arr(items)) = doc.at("items") else { return Err("no items".into()); }; - items.extend(self.items.iter().map(|i| J::Str(i.rename.to.clone()))); + items.extend(new_items()); + // The registries commands check ids against. + if let Some(J::Arr(ids)) = doc.at("by_registry/minecraft:item/ids") { + ids.extend(new_items()); + } + if let Some(J::Arr(ids)) = doc.at("by_registry/minecraft:block/ids") { + ids.extend(new_blocks()); + } } "mob-data.json" => states(doc, "states", false, false)?, "worldgen/block_flags.json" => states(doc, "", false, false)?, @@ -616,6 +625,19 @@ const NBT_TABLES: [&str; 6] = [ "worldgen/blocks/cached-support.nbt", "worldgen/blocks/cached-collision.nbt", ]; +/// In a root built here: the content mods' ids, the namespaces loaders +/// read besides `minecraft`. +const MARKER: &str = "horizon-mod-content.json"; + +/// The content mods' namespaces in a root built by [`build`]; none in any +/// other root, so vanilla's loaders read exactly what they did. +pub fn namespaces(root: &Path) -> Vec { + fs::read(root.join(MARKER)) + .ok() + .and_then(|b| serde_json::from_slice(&b).ok()) + .unwrap_or_default() +} + /// Bundles of block tag files (tag id → the tag file's text). const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; @@ -799,6 +821,23 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { for (name, doc) in &bundles { overlay.write(name, &serde_json::to_vec(doc)?)?; } + // A block without its own blockstate looks like its template, so every + // state still has a model. + for m in mods { + for block in &m.content.blocks { + let (ns, path) = block.id.split_once(':').unwrap_or((&m.id, &block.id)); + let own = format!("assets/{ns}/blockstates/{path}.json"); + if m.content.files.contains(&own) { + continue; + } + let template = block.template.trim_start_matches("minecraft:"); + let vanilla = base.join(format!("assets/minecraft/blockstates/{template}.json")); + overlay.write(&own, &fs::read(&vanilla)?)?; + } + } + let mut ids: Vec<&str> = mods.iter().map(|m| m.id.as_str()).collect(); + ids.sort(); + overlay.write(MARKER, &serde_json::to_vec(&ids)?)?; Ok(()) } diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index b5f235916..6dd92ecfd 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -177,6 +177,11 @@ fn content_root_loads_with_every_table() { crate::motion::MotionResources::load(&root, &assets).unwrap(); horizon_world::worldgen::generator::GeneratorData::load(&root.join("worldgen"), new).unwrap(); assert!(root.join("assets/ruby/lang/en_us.json").is_file()); + // Blocks without a blockstate of their own take their template's. + assert_eq!( + fs::read(root.join("assets/ruby/blockstates/ruby_door.json")).unwrap(), + fs::read(base.join("assets/minecraft/blockstates/oak_door.json")).unwrap() + ); // The base root was only read. assert!( diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 85d90b087..ba5bffefb 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -73,7 +73,7 @@ pub(crate) fn prepare_with_models( let blocks: Vec<&str> = facts .keys() .filter(|name| registry.default_state(name).is_some()) - .filter_map(|name| name.strip_prefix("minecraft:")) + .map(|name| name.strip_prefix("minecraft:").unwrap_or(name)) .collect(); let catalog = StateModels::from_facts_with_models(root, registry, &blocks, sprites, &facts, models)?; diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index 59a885821..cccf08900 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -94,7 +94,9 @@ impl StateModels { } } for block in blocks.iter().copied().collect::>() { - let name = format!("minecraft:{block}"); + // Vanilla blocks come bare; content mods' blocks with their namespace. + let (namespace, path) = block.split_once(':').unwrap_or(("minecraft", block)); + let name = format!("{namespace}:{path}"); let facts = facts.get(&name).ok_or("missing block model state schema")?; let schema: PropertySchema = facts["schema"] .as_object() @@ -133,7 +135,7 @@ impl StateModels { .collect::>()?; let possible: Vec = serde_json::from_value(facts["states"].clone())?; let resource = fs::read_to_string( - root.join(format!("assets/minecraft/blockstates/{block}.json")), + root.join(format!("assets/{namespace}/blockstates/{path}.json")), )?; let definition = BlockStateDefinition::from_json(&resource)?; let bound = definition.bind(&schema, &possible)?; diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json new file mode 100644 index 000000000..53d9292f2 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/blockstates/ruby_block.json @@ -0,0 +1,7 @@ +{ + "variants": { + "": { + "model": "ruby:block/ruby_block" + } + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json new file mode 100644 index 000000000..683211550 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "ruby:item/ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json new file mode 100644 index 000000000..7cd81eb4d --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/items/ruby_block.json @@ -0,0 +1,6 @@ +{ + "model": { + "type": "minecraft:model", + "model": "ruby:block/ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json new file mode 100644 index 000000000..0b1723511 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/lang/en_us.json @@ -0,0 +1,4 @@ +{ + "block.ruby.ruby_block": "Block of Ruby", + "item.ruby.ruby": "Ruby" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json new file mode 100644 index 000000000..e29b03d89 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/block/ruby_block.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:block/cube_all", + "textures": { + "all": "ruby:block/ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json new file mode 100644 index 000000000..8589c680f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/models/item/ruby.json @@ -0,0 +1,6 @@ +{ + "parent": "minecraft:item/generated", + "textures": { + "layer0": "ruby:item/ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png new file mode 100644 index 0000000000000000000000000000000000000000..c6e4eeaf2b6023df2dfe5faed484a150fd8300d3 GIT binary patch literal 149 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`F`h1tAr-fhPY4J6@#joq5cHoK z^MCy$lVb-I3MG!I@tZR&lbD^BVz+{G}T@x>>JM28dS yUwqQo=+HC2@EFs^I<=b(7fT$@mpE{;F`S?B!{FkAd0T+?FnGH9xvX7RVqreg;b3MG!I@tZR&lbD^BVz+{G}T@x>>JM28dS xUwqQo=+HC2@EFs^I<=b(7fT$@mpE{;F?{~4u+)1)t0T}J22WQ%mvv4FO#t8qHlP3i literal 0 HcmV?d00001 diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json new file mode 100644 index 000000000..d39b250dc --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/mineable/pickaxe.json @@ -0,0 +1,5 @@ +{ + "values": [ + "ruby:ruby_block" + ] +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json new file mode 100644 index 000000000..d39b250dc --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/minecraft/tags/block/needs_iron_tool.json @@ -0,0 +1,5 @@ +{ + "values": [ + "ruby:ruby_block" + ] +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json new file mode 100644 index 000000000..a07c26d08 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/block/ruby_block.json @@ -0,0 +1,9 @@ +{ + "template": "minecraft:iron_block", + "properties": { + "hardness": 4.0, + "light": 3, + "sounds": "minecraft:amethyst_block", + "map_color": 28 + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json new file mode 100644 index 000000000..4c89fe38f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/horizon/item/ruby.json @@ -0,0 +1,4 @@ +{ + "template": "minecraft:diamond", + "rarity": "uncommon" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json new file mode 100644 index 000000000..e58b73946 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/loot_table/blocks/ruby_block.json @@ -0,0 +1,18 @@ +{ + "type": "minecraft:block", + "pools": [ + { + "condition": { + "type": "minecraft:survives_explosion" + }, + "entries": [ + { + "type": "minecraft:item", + "name": "ruby:ruby_block" + } + ], + "rolls": 1 + } + ], + "random_sequence": "ruby:blocks/ruby_block" +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json new file mode 100644 index 000000000..da374d024 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_block.json @@ -0,0 +1,15 @@ +{ + "type": "minecraft:crafting_shaped", + "category": "building", + "key": { + "#": "ruby:ruby" + }, + "pattern": [ + "###", + "###", + "###" + ], + "result": { + "id": "ruby:ruby_block" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json new file mode 100644 index 000000000..dc416fa2f --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/data/ruby/recipe/ruby_from_ruby_block.json @@ -0,0 +1,10 @@ +{ + "type": "minecraft:crafting_shapeless", + "ingredients": [ + "ruby:ruby_block" + ], + "result": { + "count": 9, + "id": "ruby:ruby" + } +} diff --git a/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml b/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml new file mode 100644 index 000000000..39355bb57 --- /dev/null +++ b/crates/horizon-mod-sdk/examples/ruby-content/horizon-mod.toml @@ -0,0 +1,11 @@ +# A content-only Horizon mod (API 0.2, docs/modpacks.md): no code, a block +# and an item declared from vanilla templates, with their recipes, loot, +# tags, models, textures and names. Try it: horizon-client --dev-mod +id = "ruby" +name = "Ruby" +version = "0.1.0" +description = "A ruby gem and a block of ruby" +authors = ["Horizon"] +api = "0.2" +side = "both" +capabilities = ["registries"] From 85858610bfbbd91141fec78b960334d178d0f656 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:24:49 +0200 Subject: [PATCH 12/23] horizon-port-pack: import a modpack and classify its mods A CLI for the first steps of docs/modpacks.md's pipeline: - import: a Modrinth .mrpack, a CurseForge zip or a Prism / MultiMC instance (or a folder of jars) to pack.json: Minecraft and loader versions, each file with its hash and sides, and the overrides. - inventory: Modrinth metadata by SHA-1 (cached in modrinth.json, so reruns work offline), and the jars when the user's instance has them (neoforge.mods.toml / mods.toml / fabric.mod.json and a file census, without decompiling). Each mod gets a class and API tier from the reviewed ATM10 table, then rules on categories, sides and the census, and a dependency layer. Writes inventory.json and inventory.csv. Only metadata is downloaded; jars are never fetched. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 12 + Cargo.toml | 2 +- crates/horizon-port-pack/Cargo.toml | 18 ++ crates/horizon-port-pack/src/classify.rs | 233 +++++++++++++++ crates/horizon-port-pack/src/import.rs | 335 ++++++++++++++++++++++ crates/horizon-port-pack/src/inventory.rs | 225 +++++++++++++++ crates/horizon-port-pack/src/jar.rs | 245 ++++++++++++++++ crates/horizon-port-pack/src/main.rs | 104 +++++++ crates/horizon-port-pack/src/modrinth.rs | 113 ++++++++ docs/modpacks.md | 14 + 10 files changed, 1300 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-port-pack/Cargo.toml create mode 100644 crates/horizon-port-pack/src/classify.rs create mode 100644 crates/horizon-port-pack/src/import.rs create mode 100644 crates/horizon-port-pack/src/inventory.rs create mode 100644 crates/horizon-port-pack/src/jar.rs create mode 100644 crates/horizon-port-pack/src/main.rs create mode 100644 crates/horizon-port-pack/src/modrinth.rs diff --git a/Cargo.lock b/Cargo.lock index 90b288a8e..9c3ad04ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1498,6 +1498,18 @@ dependencies = [ "horizon-mod-sdk", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "sha1", + "toml", + "ureq", + "zip", +] + [[package]] name = "horizon-prepare" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 49ef5785f..1b4cb92d4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/crates/horizon-port-pack/Cargo.toml b/crates/horizon-port-pack/Cargo.toml new file mode 100644 index 000000000..1b33b6c01 --- /dev/null +++ b/crates/horizon-port-pack/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "horizon-port-pack" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.86" +description = "Port a Java modpack to Horizon: import, inventory, classification and data carry-over (docs/modpacks.md)" + +[dependencies] +serde = { version = "1", features = ["derive"] } +serde_json = "1" +sha1 = "0.10" +toml = "1.1.6" +ureq = { version = "2", default-features = false, features = ["tls"] } +zip = { version = "2", default-features = false, features = ["deflate"] } + +[lints] +workspace = true diff --git a/crates/horizon-port-pack/src/classify.rs b/crates/horizon-port-pack/src/classify.rs new file mode 100644 index 000000000..7ebb65644 --- /dev/null +++ b/crates/horizon-port-pack/src/classify.rs @@ -0,0 +1,233 @@ +//! Step 2 and 3: classify each mod (class and API tier, `docs/modpacks.md`) +//! and order them by required dependencies. +use std::collections::{BTreeMap, HashMap}; + +/// The reviewed table: ATM10's 495 rows (`docs/modpacks/atm10-mods.csv`). +/// It wins over the heuristics. +const KNOWN_CSV: &str = include_str!("../../../docs/modpacks/atm10-mods.csv"); + +pub struct Known { + by_key: HashMap, +} + +/// Lowercase letters and digits only: `Get It Together, Drops!` -> +/// `getittogetherdrops`. +pub fn normalise(s: &str) -> String { + s.chars() + .filter(char::is_ascii_alphanumeric) + .map(|c| c.to_ascii_lowercase()) + .collect() +} + +/// One CSV line, with `"quoted, fields"`. +fn csv_fields(line: &str) -> Vec { + let (mut out, mut field, mut quoted) = (Vec::new(), String::new(), false); + let mut chars = line.chars().peekable(); + while let Some(c) = chars.next() { + match c { + '"' if quoted && chars.peek() == Some(&'"') => { + field.push('"'); + chars.next(); + } + '"' => quoted = !quoted, + ',' if !quoted => out.push(std::mem::take(&mut field)), + c => field.push(c), + } + } + out.push(field); + out +} + +impl Known { + pub fn atm10() -> Self { + let mut by_key = HashMap::new(); + for line in KNOWN_CSV.lines().skip(1) { + let f = csv_fields(line); + if f.len() < 6 || f[5] == "guess" { + continue; + } + let value = (f[3].clone(), f[4].clone()); + by_key.insert(normalise(&f[0]), value.clone()); + by_key.entry(normalise(&f[1])).or_insert(value); + } + Known { by_key } + } + + /// By mod id, Modrinth slug or name, in that order. + pub fn get(&self, keys: &[&str]) -> Option<&(String, String)> { + keys.iter() + .filter(|k| !k.is_empty()) + .find_map(|k| self.by_key.get(&normalise(k))) + } +} + +/// What the rules look at. +#[derive(Default)] +pub struct Facts<'a> { + /// `mods`, `resourcepacks`, `shaderpacks`, `datapacks`. + pub kind: &'a str, + pub client: &'a str, + pub server: &'a str, + /// Modrinth categories. + pub categories: &'a [String], + /// From the jar: classes, and whether it has blocks, items or data. + pub classes: Option, + pub has_content: bool, +} + +/// Class, tier and confidence (`known` is set by the caller). +pub fn rules(f: &Facts) -> (&'static str, &'static str, &'static str) { + let has = |c: &str| f.categories.iter().any(|x| x == c); + match f.kind { + "resourcepacks" => return ("other", "data", "kind"), + "shaderpacks" => return ("other", "none", "kind"), + "datapacks" => return ("content", "data", "kind"), + _ => {} + } + if has("library") { + return ("library", "none", "categories"); + } + if has("optimization") { + return ("performance", "none", "categories"); + } + if f.client != "unsupported" && f.server == "unsupported" { + return ("client-ui", "client", "sides"); + } + if f.client == "unsupported" && f.server != "unsupported" && !f.server.is_empty() { + return ("server-only", "logic", "sides"); + } + if f.classes == Some(0) && f.has_content { + return ("content", "data", "jar"); + } + let content = [ + "adventure", + "decoration", + "equipment", + "food", + "game-mechanics", + "magic", + "mobs", + "storage", + "technology", + "transportation", + "worldgen", + ]; + if f.categories.iter().any(|c| content.contains(&c.as_str())) { + let tier = if has("mobs") || has("magic") || has("adventure") { + "deep" + } else if has("technology") || has("storage") || has("transportation") { + "machines" + } else if f.categories.iter().all(|c| { + ["worldgen", "decoration", "food"].contains(&c.as_str()) + || !content.contains(&c.as_str()) + }) { + "data" + } else { + "logic" + }; + return ("content", tier, "categories"); + } + if has("utility") || has("management") || has("social") { + return ("other", "logic", "guess"); + } + ("unknown", "none", "unknown") +} + +/// Layer of each mod: 0 needs nothing in the pack, n needs layer n-1. +/// Mods in a cycle get one layer past the rest; dependencies outside the +/// pack are left out (the caller lists them). +pub fn layers(depends: &BTreeMap>) -> BTreeMap { + let mut out: BTreeMap = BTreeMap::new(); + loop { + let mut progressed = false; + for (id, deps) in depends { + if out.contains_key(id) { + continue; + } + let inside = deps.iter().filter(|d| depends.contains_key(*d) && *d != id); + let mut layer = 0; + let mut ready = true; + for d in inside { + match out.get(d) { + Some(l) => layer = layer.max(l + 1), + None => ready = false, + } + } + if ready { + out.insert(id.clone(), layer); + progressed = true; + } + } + if !progressed { + break; + } + } + let past = out.values().max().map_or(0, |m| m + 1); + for id in depends.keys() { + out.entry(id.clone()).or_insert(past); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn known_table_matches_ids_and_names() { + let k = Known::atm10(); + assert_eq!(k.get(&["create"]).map(|v| v.0.as_str()), Some("content")); + assert_eq!( + k.get(&["", "Get It Together, Drops!"]) + .map(|v| v.0.as_str()), + Some("performance") + ); + assert_eq!(k.get(&["sodium"]).map(|v| v.1.as_str()), Some("none")); + assert!(k.get(&["not-a-mod"]).is_none()); + } + + #[test] + fn rules_follow_sides_then_categories() { + let cats = |c: &[&str]| c.iter().map(|s| s.to_string()).collect::>(); + let f = |client, server, c: &[String]| { + rules(&Facts { + kind: "mods", + client, + server, + categories: c, + ..Facts::default() + }) + }; + assert_eq!(f("required", "unsupported", &[]).0, "client-ui"); + assert_eq!(f("unsupported", "required", &[]).0, "server-only"); + assert_eq!(f("required", "required", &cats(&["library"])).0, "library"); + assert_eq!( + f("required", "unsupported", &cats(&["optimization"])).0, + "performance" + ); + assert_eq!( + f("required", "required", &cats(&["technology", "utility"])), + ("content", "machines", "categories") + ); + assert_eq!( + f("required", "required", &cats(&["worldgen", "neoforge"])), + ("content", "data", "categories") + ); + assert_eq!(f("", "", &[]).0, "unknown"); + } + + #[test] + fn layers_put_dependencies_first() { + let d = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::>(); + let deps = BTreeMap::from([ + ("lib".to_string(), d(&[])), + ("create".to_string(), d(&["lib", "outside"])), + ("addon".to_string(), d(&["create", "lib"])), + ("a".to_string(), d(&["b"])), + ("b".to_string(), d(&["a"])), + ]); + let l = layers(&deps); + assert_eq!((l["lib"], l["create"], l["addon"]), (0, 1, 2)); + assert_eq!((l["a"], l["b"]), (3, 3)); + } +} diff --git a/crates/horizon-port-pack/src/import.rs b/crates/horizon-port-pack/src/import.rs new file mode 100644 index 000000000..b0f5d04c2 --- /dev/null +++ b/crates/horizon-port-pack/src/import.rs @@ -0,0 +1,335 @@ +//! Step 1, import: a Modrinth `.mrpack`, a CurseForge zip, or an instance +//! folder (Prism / MultiMC, or a plain `mods/` folder) to `pack.json`. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::Read, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Pack { + pub name: String, + /// `mrpack`, `curseforge` or `instance`. + pub format: String, + pub minecraft: String, + /// `neoforge`, `forge`, `fabric` or `quilt`. + pub loader: String, + pub loader_version: String, + pub files: Vec, + /// Override files by top folder (`config`, `kubejs`, ...). + pub overrides: BTreeMap, +} + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct PackFile { + /// Path in the instance (`mods/create-1.21.1-6.0.4.jar`). + pub path: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sha1: Option, + /// `required`, `optional` or `unsupported`; empty when not stated. + pub client: String, + pub server: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub downloads: Vec, + /// CurseForge project and file ids. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub curseforge: Option<(u64, u64)>, + /// The jar on disk (instances only). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jar: Option, +} + +impl PackFile { + /// `mods`, `resourcepacks`, `shaderpacks`, `datapacks`... + pub fn kind(&self) -> &str { + self.path.split('/').next().unwrap_or("") + } + pub fn file_name(&self) -> &str { + self.path.rsplit('/').next().unwrap_or(&self.path) + } +} + +const LOADERS: [(&str, &str); 4] = [ + ("neoforge", "neoforge"), + ("forge", "forge"), + ("fabric-loader", "fabric"), + ("quilt-loader", "quilt"), +]; + +pub fn import(path: &Path) -> Result { + if path.is_dir() { + return instance(path); + } + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", path.display()))?; + if let Some(index) = read_json(&mut zip, "modrinth.index.json")? { + return Ok(mrpack(&index, &names(&zip))); + } + if let Some(manifest) = read_json(&mut zip, "manifest.json")? { + return Ok(curseforge(&manifest, &names(&zip))); + } + Err(format!( + "{}: neither modrinth.index.json nor manifest.json", + path.display() + )) +} + +fn names(zip: &zip::ZipArchive) -> Vec { + zip.file_names().map(str::to_owned).collect() +} + +fn read_json(zip: &mut zip::ZipArchive, name: &str) -> Result, String> { + let Ok(mut entry) = zip.by_name(name) else { + return Ok(None); + }; + let mut text = String::new(); + entry + .read_to_string(&mut text) + .map_err(|e| format!("{name}: {e}"))?; + serde_json::from_str(&text) + .map(Some) + .map_err(|e| format!("{name}: {e}")) +} + +fn str_of(v: &Value, key: &str) -> String { + v.get(key).and_then(Value::as_str).unwrap_or("").to_owned() +} + +/// Override files by top folder, below any of `roots`. +fn overrides(names: &[String], roots: &[&str]) -> BTreeMap { + let mut out = BTreeMap::new(); + for name in names.iter().filter(|n| !n.ends_with('/')) { + for root in roots { + if let Some(rest) = name.strip_prefix(root).and_then(|r| r.strip_prefix('/')) { + let top = rest.split('/').next().unwrap_or(rest); + *out.entry(top.to_owned()).or_default() += 1; + } + } + } + out +} + +pub fn mrpack(index: &Value, names: &[String]) -> Pack { + let deps = &index["dependencies"]; + let (loader, loader_version) = LOADERS + .iter() + .find_map(|(key, name)| Some((name.to_string(), deps.get(*key)?.as_str()?.to_owned()))) + .unwrap_or_default(); + let files = index["files"] + .as_array() + .into_iter() + .flatten() + .map(|f| PackFile { + path: str_of(f, "path"), + sha1: f["hashes"]["sha1"].as_str().map(str::to_owned), + client: str_of(&f["env"], "client"), + server: str_of(&f["env"], "server"), + downloads: f["downloads"] + .as_array() + .into_iter() + .flatten() + .filter_map(|d| d.as_str().map(str::to_owned)) + .collect(), + ..PackFile::default() + }) + .collect(); + Pack { + name: str_of(index, "name"), + format: "mrpack".into(), + minecraft: str_of(deps, "minecraft"), + loader, + loader_version, + files, + overrides: overrides( + names, + &["overrides", "client-overrides", "server-overrides"], + ), + } +} + +pub fn curseforge(manifest: &Value, names: &[String]) -> Pack { + let primary = manifest["minecraft"]["modLoaders"] + .as_array() + .into_iter() + .flatten() + .find(|l| l["primary"].as_bool().unwrap_or(true)) + .map(|l| str_of(l, "id")) + .unwrap_or_default(); + let (loader, loader_version) = primary.split_once('-').unwrap_or((&primary, "")); + let files = manifest["files"] + .as_array() + .into_iter() + .flatten() + .map(|f| { + let (p, id) = (f["projectID"].as_u64(), f["fileID"].as_u64()); + PackFile { + path: format!("mods/curseforge-{}-{}", p.unwrap_or(0), id.unwrap_or(0)), + // CurseForge states no side; its API needs a key, so names + // come from the user's installed instance (import that). + curseforge: p.zip(id), + ..PackFile::default() + } + }) + .collect(); + let root = manifest["overrides"].as_str().unwrap_or("overrides"); + Pack { + name: str_of(manifest, "name"), + format: "curseforge".into(), + minecraft: str_of(&manifest["minecraft"], "version"), + loader: loader.to_owned(), + loader_version: loader_version.to_owned(), + files, + overrides: overrides(names, &[root]), + } +} + +/// A Prism / MultiMC instance (`mmc-pack.json`), a game folder, or a +/// folder of jars: the jars on disk, hashed. +fn instance(dir: &Path) -> Result { + let mut pack = Pack { + name: dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(), + format: "instance".into(), + ..Pack::default() + }; + if let Ok(text) = fs::read_to_string(dir.join("mmc-pack.json")) { + let mmc: Value = serde_json::from_str(&text).map_err(|e| format!("mmc-pack.json: {e}"))?; + for c in mmc["components"].as_array().into_iter().flatten() { + let version = str_of(c, "version"); + match c["uid"].as_str().unwrap_or("") { + "net.minecraft" => pack.minecraft = version, + "net.neoforged" => { + (pack.loader, pack.loader_version) = ("neoforge".into(), version) + } + "net.minecraftforge" => { + (pack.loader, pack.loader_version) = ("forge".into(), version) + } + "net.fabricmc.fabric-loader" => { + (pack.loader, pack.loader_version) = ("fabric".into(), version) + } + "org.quiltmc.quilt-loader" => { + (pack.loader, pack.loader_version) = ("quilt".into(), version) + } + _ => {} + } + } + } + let game = [".minecraft", "minecraft", "."] + .iter() + .map(|g| dir.join(g)) + .find(|g| g.join("mods").is_dir()) + .or_else(|| dir.read_dir().is_ok().then(|| dir.to_path_buf())) + .ok_or_else(|| format!("{}: no mods folder", dir.display()))?; + let mods = if game.join("mods").is_dir() { + game.join("mods") + } else { + game.clone() + }; + let mut jars: Vec = fs::read_dir(&mods) + .map_err(|e| format!("{}: {e}", mods.display()))? + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|x| x == "jar")) + .collect(); + jars.sort(); + for jar in jars { + let bytes = fs::read(&jar).map_err(|e| format!("{}: {e}", jar.display()))?; + pack.files.push(PackFile { + path: format!( + "mods/{}", + jar.file_name().unwrap_or_default().to_string_lossy() + ), + sha1: Some(sha1_hex(&bytes)), + jar: Some(jar), + ..PackFile::default() + }); + } + for top in ["config", "kubejs", "defaultconfigs", "datapacks"] { + let n = count_files(&game.join(top)); + if n > 0 { + pack.overrides.insert(top.into(), n); + } + } + Ok(pack) +} + +fn count_files(dir: &Path) -> usize { + let Ok(entries) = fs::read_dir(dir) else { + return 0; + }; + entries + .flatten() + .map(|e| { + let p = e.path(); + if p.is_dir() { count_files(&p) } else { 1 } + }) + .sum() +} + +pub fn sha1_hex(bytes: &[u8]) -> String { + use sha1::Digest; + sha1::Sha1::digest(bytes) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn reads_an_mrpack_index() { + let index = json!({"name": "Small", "dependencies": {"minecraft": "1.21.1", "neoforge": "21.1.233"}, + "files": [{"path": "mods/create.jar", "hashes": {"sha1": "ab"}, "env": {"client": "required", "server": "required"}, + "downloads": ["https://cdn.modrinth.com/create.jar"]}, + {"path": "resourcepacks/look.zip", "hashes": {"sha1": "cd"}}]}); + let names = [ + "overrides/config/a.toml", + "overrides/config/b/c.toml", + "client-overrides/kubejs/x.js", + "overrides/", + ] + .map(String::from); + let p = mrpack(&index, &names); + assert_eq!( + ( + p.minecraft.as_str(), + p.loader.as_str(), + p.loader_version.as_str() + ), + ("1.21.1", "neoforge", "21.1.233") + ); + assert_eq!(p.files.len(), 2); + assert_eq!( + (p.files[0].kind(), p.files[0].file_name()), + ("mods", "create.jar") + ); + assert_eq!(p.files[0].sha1.as_deref(), Some("ab")); + assert_eq!(p.files[1].kind(), "resourcepacks"); + assert_eq!( + p.overrides, + BTreeMap::from([("config".into(), 2), ("kubejs".into(), 1)]) + ); + } + + #[test] + fn reads_a_curseforge_manifest() { + let manifest = json!({"name": "CF", "overrides": "overrides", + "minecraft": {"version": "1.21.1", "modLoaders": [{"id": "neoforge-21.1.259", "primary": true}]}, + "files": [{"projectID": 238222, "fileID": 5101366, "required": true}]}); + let p = curseforge(&manifest, &["overrides/kubejs/server_scripts/a.js".into()]); + assert_eq!( + (p.loader.as_str(), p.loader_version.as_str()), + ("neoforge", "21.1.259") + ); + assert_eq!(p.files[0].curseforge, Some((238222, 5101366))); + assert_eq!(p.overrides["kubejs"], 1); + } +} diff --git a/crates/horizon-port-pack/src/inventory.rs b/crates/horizon-port-pack/src/inventory.rs new file mode 100644 index 000000000..49661f1ae --- /dev/null +++ b/crates/horizon-port-pack/src/inventory.rs @@ -0,0 +1,225 @@ +//! Step 2, inventory: one record per pack file, from the jar (when the +//! user's instance has it) and Modrinth's metadata, classified and ordered. +use crate::{ + classify::{self, Facts, Known}, + import::Pack, + jar::{self, JarInfo}, + modrinth::Cache, +}; +use serde::{Deserialize, Serialize}; +use std::{ + collections::{BTreeMap, HashMap}, + path::{Path, PathBuf}, +}; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Record { + /// The mod id from the jar, else the Modrinth slug, else the file name. + pub key: String, + pub name: String, + pub version: String, + pub path: String, + pub class: String, + pub tier: String, + /// `known` (reviewed table), `sides`, `categories`, `jar`, `kind`, + /// `guess` or `unknown`. + pub confidence: String, + /// `modrinth`, `curseforge` or `file`. + pub source: String, + pub license: String, + pub client: String, + pub server: String, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub categories: Vec, + /// Required dependencies inside the pack, by key. + pub depends: Vec, + /// Required dependencies the pack does not have. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub missing: Vec, + pub layer: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub jar: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub info: Option, +} + +/// The jar of a pack file: the instance's own, or one the user put in +/// `/jars/`. +fn jar_of(pack_jar: Option<&PathBuf>, file_name: &str, work: &Path) -> Option { + pack_jar + .cloned() + .or_else(|| Some(work.join("jars").join(file_name))) + .filter(|p| p.is_file()) +} + +pub fn build(pack: &Pack, cache: &Cache, work: &Path) -> Vec { + let known = Known::atm10(); + let mut records = Vec::new(); + // Modrinth project id -> record key, for dependencies. + let mut by_project: HashMap = HashMap::new(); + let mut project_deps: Vec> = Vec::new(); + for f in &pack.files { + let jar = jar_of(f.jar.as_ref(), f.file_name(), work); + let info = jar.as_deref().and_then(|j| jar::read(j).ok()); + let sha1 = f.sha1.as_deref().unwrap_or(""); + let project = cache.project_of(sha1); + let p = |k: &str| project.and_then(|p| p[k].as_str()).unwrap_or("").to_owned(); + let categories: Vec = project + .into_iter() + .flat_map(|p| { + ["categories", "additional_categories"] + .iter() + .flat_map(|k| p[*k].as_array().cloned().unwrap_or_default()) + }) + .filter_map(|c| c.as_str().map(str::to_owned)) + .collect(); + let stem = f.file_name().trim_end_matches(".jar").to_owned(); + let key = info + .as_ref() + .map(|i| i.mod_id.clone()) + .filter(|k| !k.is_empty()) + .or_else(|| Some(p("slug")).filter(|s| !s.is_empty())) + .unwrap_or(stem); + let (client, server) = match project { + Some(_) if f.client.is_empty() => (p("client_side"), p("server_side")), + _ => (f.client.clone(), f.server.clone()), + }; + let census = info.as_ref().map(|i| &i.census); + let facts = Facts { + kind: f.kind(), + client: &client, + server: &server, + categories: &categories, + classes: census.map(|c| c.classes), + has_content: census.is_some_and(|c| c.blockstates + c.item_models + c.recipes > 0), + }; + let name = info + .as_ref() + .map(|i| i.name.clone()) + .filter(|n| !n.is_empty()) + .unwrap_or_else(|| p("title")); + let (class, tier, confidence) = + match known.get(&[key.as_str(), p("slug").as_str(), name.as_str()]) { + Some((c, t)) => (c.clone(), t.clone(), "known".to_owned()), + None => { + let (c, t, conf) = classify::rules(&facts); + (c.into(), t.into(), conf.into()) + } + }; + let license = info + .as_ref() + .map(|i| i.license.clone()) + .filter(|l| !l.is_empty()) + .or_else(|| project.and_then(|p| p["license"]["id"].as_str().map(str::to_owned))) + .unwrap_or_else(|| "unknown".into()); + if let Some(id) = project.and_then(|p| p["id"].as_str()) { + by_project.insert(id.to_owned(), key.clone()); + } + project_deps.push(cache.required(sha1)); + records.push(Record { + name, + version: info.as_ref().map(|i| i.version.clone()).unwrap_or_else(|| { + cache + .versions + .get(sha1) + .and_then(|v| v["version_number"].as_str()) + .unwrap_or("") + .to_owned() + }), + path: f.path.clone(), + class, + tier, + confidence, + source: if project.is_some() { + "modrinth".into() + } else if f.curseforge.is_some() { + "curseforge".into() + } else { + "file".into() + }, + license, + client, + server, + categories, + depends: info.as_ref().map(|i| i.depends.clone()).unwrap_or_default(), + jar, + info, + key, + ..Record::default() + }); + } + // Dependencies: the jar's mod ids, else Modrinth's required projects. + let keys: std::collections::HashSet = records.iter().map(|r| r.key.clone()).collect(); + for (r, deps) in records.iter_mut().zip(project_deps) { + if r.depends.is_empty() { + r.depends = deps + .iter() + .map(|p| { + by_project + .get(p) + .cloned() + .unwrap_or_else(|| format!("modrinth:{p}")) + }) + .collect(); + } + let (inside, missing): (Vec, Vec) = + r.depends.drain(..).partition(|d| keys.contains(d)); + r.depends = inside; + r.missing = missing; + } + let graph: BTreeMap> = records + .iter() + .map(|r| (r.key.clone(), r.depends.clone())) + .collect(); + let layers = classify::layers(&graph); + for r in &mut records { + r.layer = layers.get(&r.key).copied().unwrap_or(0); + } + records.sort_by(|a, b| (a.layer, &a.key).cmp(&(b.layer, &b.key))); + records +} + +/// Counts by a field, largest first. +pub fn counts<'a>( + records: &'a [Record], + field: impl Fn(&'a Record) -> &'a str, +) -> Vec<(&'a str, usize)> { + let mut m: BTreeMap<&str, usize> = BTreeMap::new(); + for r in records { + *m.entry(field(r)).or_default() += 1; + } + let mut v: Vec<_> = m.into_iter().collect(); + v.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); + v +} + +/// `inventory.csv`: the columns of `docs/modpacks/atm10-mods.csv`, plus the layer. +pub fn csv(records: &[Record]) -> String { + let field = |s: &str| { + if s.contains([',', '"', '\n']) { + format!("\"{}\"", s.replace('"', "\"\"")) + } else { + s.to_owned() + } + }; + let mut out = String::from( + "mod_id,name,version,class,tier,confidence,source,license,client,server,layer\n", + ); + for r in records { + let row = [ + &r.key, + &r.name, + &r.version, + &r.class, + &r.tier, + &r.confidence, + &r.source, + &r.license, + &r.client, + &r.server, + ]; + let cells: Vec = row.iter().map(|s| field(s)).collect(); + out.push_str(&format!("{},{}\n", cells.join(","), r.layer)); + } + out +} diff --git a/crates/horizon-port-pack/src/jar.rs b/crates/horizon-port-pack/src/jar.rs new file mode 100644 index 000000000..67028755e --- /dev/null +++ b/crates/horizon-port-pack/src/jar.rs @@ -0,0 +1,245 @@ +//! What a mod jar holds, read without decompiling: its metadata +//! (`neoforge.mods.toml`, `mods.toml`, `fabric.mod.json`) and a census of +//! its data, assets and classes. +use serde::{Deserialize, Serialize}; +use std::{fs, io::Read, path::Path}; + +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +pub struct JarInfo { + pub mod_id: String, + pub name: String, + pub version: String, + pub license: String, + /// Required dependencies by mod id (loaders and `minecraft` left out). + pub depends: Vec, + pub census: Census, +} + +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +pub struct Census { + pub blockstates: usize, + pub item_models: usize, + pub recipes: usize, + pub loot_tables: usize, + pub tags: usize, + pub worldgen: usize, + pub structures: usize, + pub languages: usize, + pub textures: usize, + pub sounds: usize, + pub classes: usize, + pub mixin_configs: usize, +} + +const NOT_MODS: [&str; 5] = ["minecraft", "neoforge", "forge", "fabricloader", "java"]; + +pub fn read(path: &Path) -> Result { + let file = fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", path.display()))?; + let text = |zip: &mut zip::ZipArchive, name: &str| -> Option { + let mut s = String::new(); + zip.by_name(name).ok()?.read_to_string(&mut s).ok()?; + Some(s) + }; + let mut info = if let Some(t) = text(&mut zip, "META-INF/neoforge.mods.toml") + .or_else(|| text(&mut zip, "META-INF/mods.toml")) + { + mods_toml(&t)? + } else if let Some(t) = text(&mut zip, "fabric.mod.json") { + fabric(&t)? + } else { + JarInfo::default() + }; + let names: Vec = zip.file_names().map(str::to_owned).collect(); + info.census = census(&names); + if info.mod_id.is_empty() { + info.mod_id = path + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + } + Ok(info) +} + +/// `[[mods]]` (the first one is the jar's mod), the top-level `license`, and +/// `[[dependencies.]]` with `type = "required"` (or the older +/// `mandatory = true`). +pub fn mods_toml(text: &str) -> Result { + let doc: toml::Table = toml::from_str(text).map_err(|e| format!("mods.toml: {e}"))?; + let first = doc + .get("mods") + .and_then(|m| m.as_array()) + .and_then(|m| m.first()) + .and_then(|m| m.as_table()); + let get = |t: Option<&toml::Table>, k: &str| { + t.and_then(|t| t.get(k)) + .and_then(|v| v.as_str()) + .unwrap_or("") + .to_owned() + }; + let mod_id = get(first, "modId"); + let mut depends = Vec::new(); + if let Some(deps) = doc + .get("dependencies") + .and_then(|d| d.get(&mod_id)) + .and_then(|d| d.as_array()) + { + for d in deps.iter().filter_map(|d| d.as_table()) { + let required = d.get("type").and_then(|t| t.as_str()).map_or_else( + || d.get("mandatory").and_then(|m| m.as_bool()) == Some(true), + |t| t.eq_ignore_ascii_case("required"), + ); + let id = get(Some(d), "modId"); + if required && !NOT_MODS.contains(&id.as_str()) && !id.is_empty() { + depends.push(id); + } + } + } + Ok(JarInfo { + name: get(first, "displayName"), + version: get(first, "version"), + license: get(Some(&doc), "license"), + mod_id, + depends, + census: Census::default(), + }) +} + +pub fn fabric(text: &str) -> Result { + let v: serde_json::Value = + serde_json::from_str(text).map_err(|e| format!("fabric.mod.json: {e}"))?; + let s = |k: &str| v[k].as_str().unwrap_or("").to_owned(); + let license = match &v["license"] { + serde_json::Value::Array(l) => l + .iter() + .filter_map(|x| x.as_str()) + .collect::>() + .join(" OR "), + l => l.as_str().unwrap_or("").to_owned(), + }; + let depends = v["depends"] + .as_object() + .into_iter() + .flatten() + .map(|(id, _)| id.clone()) + .filter(|id| !NOT_MODS.contains(&id.as_str()) && !id.starts_with("fabric")) + .collect(); + Ok(JarInfo { + mod_id: s("id"), + name: s("name"), + version: s("version"), + license, + depends, + census: Census::default(), + }) +} + +pub fn census(names: &[String]) -> Census { + let mut c = Census::default(); + for n in names { + let parts: Vec<&str> = n.split('/').collect(); + if n.ends_with(".class") { + c.classes += 1; + } else if n.ends_with(".mixins.json") || (parts.len() == 1 && n.contains("mixins")) { + c.mixin_configs += 1; + } + // assets///... and data///... + let (Some(root), Some(kind)) = (parts.first(), parts.get(2)) else { + continue; + }; + let json = n.ends_with(".json"); + match (*root, *kind) { + ("assets", "blockstates") if json => c.blockstates += 1, + ("assets", "models") if json && parts.get(3) == Some(&"item") => c.item_models += 1, + ("assets", "lang") => c.languages += 1, + ("assets", "textures") if n.ends_with(".png") => c.textures += 1, + ("assets", "sounds.json") => c.sounds += 1, + ("data", "recipe" | "recipes") if json => c.recipes += 1, + ("data", "loot_table" | "loot_tables") if json => c.loot_tables += 1, + ("data", "tags") if json => c.tags += 1, + ("data", "worldgen") if json => c.worldgen += 1, + ("data", "structure" | "structures") if n.ends_with(".nbt") => c.structures += 1, + _ => {} + } + } + c +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_neoforge_metadata() { + let info = mods_toml( + r#"modLoader = "javafml" +license = "MIT" +[[mods]] +modId = "ruby" +version = "1.2.0" +displayName = "Ruby" +[[dependencies.ruby]] +modId = "neoforge" +type = "required" +[[dependencies.ruby]] +modId = "geckolib" +type = "required" +[[dependencies.ruby]] +modId = "jei" +type = "optional" +[[dependencies.ruby]] +modId = "curios" +mandatory = true +"#, + ) + .unwrap(); + assert_eq!( + ( + info.mod_id.as_str(), + info.version.as_str(), + info.license.as_str() + ), + ("ruby", "1.2.0", "MIT") + ); + assert_eq!(info.depends, ["geckolib", "curios"]); + } + + #[test] + fn reads_fabric_metadata() { + let info = fabric( + r#"{"id": "gem", "version": "3", "name": "Gem", "license": ["MIT", "Apache-2.0"], + "depends": {"fabricloader": "*", "fabric-api": "*", "minecraft": "1.21.1", "cloth-config": "*"}}"#, + ) + .unwrap(); + assert_eq!(info.license, "MIT OR Apache-2.0"); + assert_eq!(info.depends, ["cloth-config"]); + } + + #[test] + fn counts_files_by_kind() { + let names = [ + "assets/ruby/blockstates/ruby_block.json", + "assets/ruby/models/item/ruby.json", + "assets/ruby/models/block/ruby_block.json", + "assets/ruby/textures/item/ruby.png", + "assets/ruby/lang/en_us.json", + "data/ruby/recipe/ruby.json", + "data/ruby/loot_table/blocks/ruby_block.json", + "data/minecraft/tags/block/mineable/pickaxe.json", + "data/ruby/structure/hut.nbt", + "com/example/Ruby.class", + "ruby.mixins.json", + ] + .map(String::from); + let c = census(&names); + assert_eq!( + (c.blockstates, c.item_models, c.textures, c.languages), + (1, 1, 1, 1) + ); + assert_eq!( + (c.recipes, c.loot_tables, c.tags, c.structures), + (1, 1, 1, 1) + ); + assert_eq!((c.classes, c.mixin_configs), (1, 1)); + } +} diff --git a/crates/horizon-port-pack/src/main.rs b/crates/horizon-port-pack/src/main.rs new file mode 100644 index 000000000..200e42334 --- /dev/null +++ b/crates/horizon-port-pack/src/main.rs @@ -0,0 +1,104 @@ +//! `horizon-port-pack`: port a Java modpack to Horizon (`docs/modpacks.md`). +//! +//! - `import `: a `.mrpack`, CurseForge zip or instance folder +//! to `/pack.json`. +//! - `inventory [--offline]`: Modrinth metadata (cached in +//! `/modrinth.json`), the jars in the instance or `/jars/`, +//! classes, tiers and dependency layers in `/inventory.json` and +//! `inventory.csv`. +//! +//! The work folder belongs to the user: jars stay there and are never +//! uploaded or committed. +mod classify; +mod import; +mod inventory; +mod jar; +mod modrinth; + +use std::{fs, path::Path, process::ExitCode}; + +const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline]"; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let path = |i: usize| args.get(i).map(Path::new).ok_or(USAGE.to_owned()); + let result = match args.first().map(String::as_str) { + Some("import") => path(1) + .and_then(|p| Ok((p, path(2)?))) + .and_then(|(p, w)| import(p, w)), + Some("inventory") => { + path(1).and_then(|w| inventory(w, args.iter().any(|a| a == "--offline"))) + } + _ => Err(USAGE.to_owned()), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("error: {e}"); + ExitCode::FAILURE + } + } +} + +fn write_json(path: &Path, value: &impl serde::Serialize) -> Result<(), String> { + let text = serde_json::to_string_pretty(value).map_err(|e| e.to_string())?; + fs::write(path, text).map_err(|e| format!("{}: {e}", path.display())) +} + +fn read_json(path: &Path) -> Result { + let text = fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?; + serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display())) +} + +fn import(pack: &Path, work: &Path) -> Result<(), String> { + let pack = import::import(pack)?; + fs::create_dir_all(work).map_err(|e| format!("{}: {e}", work.display()))?; + write_json(&work.join("pack.json"), &pack)?; + let mut kinds = std::collections::BTreeMap::<&str, usize>::new(); + for f in &pack.files { + *kinds.entry(f.kind()).or_default() += 1; + } + println!( + "{} ({}): Minecraft {}, {} {}; files {kinds:?}; overrides {:?}", + pack.name, pack.format, pack.minecraft, pack.loader, pack.loader_version, pack.overrides + ); + Ok(()) +} + +fn inventory(work: &Path, offline: bool) -> Result<(), String> { + let pack: import::Pack = read_json(&work.join("pack.json"))?; + let cache_path = work.join("modrinth.json"); + let mut cache = modrinth::Cache::load(&cache_path); + if !offline { + let hashes: Vec = pack.files.iter().filter_map(|f| f.sha1.clone()).collect(); + cache.fetch(&hashes)?; + write_json(&cache_path, &cache)?; + } + let records = inventory::build(&pack, &cache, work); + write_json(&work.join("inventory.json"), &records)?; + fs::write(work.join("inventory.csv"), inventory::csv(&records)) + .map_err(|e| format!("inventory.csv: {e}"))?; + let jars = records.iter().filter(|r| r.jar.is_some()).count(); + println!("{} files, {jars} jars read", records.len()); + for (title, field) in [ + ( + "class", + (|r: &inventory::Record| r.class.as_str()) as fn(&inventory::Record) -> &str, + ), + ("tier", |r| r.tier.as_str()), + ("confidence", |r| r.confidence.as_str()), + ("source", |r| r.source.as_str()), + ] { + println!("{title}: {:?}", inventory::counts(&records, field)); + } + let layers = records.iter().map(|r| r.layer).max().map_or(0, |m| m + 1); + let per_layer: Vec = (0..layers) + .map(|l| records.iter().filter(|r| r.layer == l).count()) + .collect(); + println!("layers: {per_layer:?}"); + let missing: usize = records.iter().map(|r| r.missing.len()).sum(); + if missing > 0 { + println!("{missing} required dependencies are not in the pack (see inventory.json)"); + } + Ok(()) +} diff --git a/crates/horizon-port-pack/src/modrinth.rs b/crates/horizon-port-pack/src/modrinth.rs new file mode 100644 index 000000000..8c34a2004 --- /dev/null +++ b/crates/horizon-port-pack/src/modrinth.rs @@ -0,0 +1,113 @@ +//! Modrinth metadata for the pack's files: the version of each file by +//! SHA-1, and its project (categories, licence, sides). Only metadata: no +//! jar is downloaded. Answers are cached in `/modrinth.json`, so a +//! rerun works offline. +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::{collections::BTreeMap, path::Path}; + +const API: &str = "https://api.modrinth.com/v2"; +const AGENT: &str = "ludovic111/horizon horizon-port-pack/0.1 (docs/modpacks.md)"; + +#[derive(Debug, Default, Serialize, Deserialize)] +pub struct Cache { + /// Version objects by file SHA-1. + pub versions: BTreeMap, + /// Project objects by project id. + pub projects: BTreeMap, +} + +impl Cache { + pub fn load(path: &Path) -> Self { + std::fs::read_to_string(path) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default() + } + + /// Ask Modrinth about the hashes and projects not cached yet. + pub fn fetch(&mut self, hashes: &[String]) -> Result<(), String> { + let missing: Vec<&String> = hashes + .iter() + .filter(|h| !self.versions.contains_key(*h)) + .collect(); + for chunk in missing.chunks(500) { + let body = serde_json::json!({"hashes": chunk, "algorithm": "sha1"}); + let found = post(&format!("{API}/version_files"), &body)?; + for (hash, version) in found.as_object().into_iter().flatten() { + self.versions.insert(hash.clone(), version.clone()); + } + } + let mut ids: Vec = self + .versions + .values() + .filter_map(|v| v["project_id"].as_str().map(str::to_owned)) + .filter(|id| !self.projects.contains_key(id)) + .collect(); + ids.sort(); + ids.dedup(); + for chunk in ids.chunks(100) { + let list = serde_json::to_string(chunk).unwrap_or_default(); + let found = get(&format!("{API}/projects?ids={}", encode(&list)))?; + for project in found.as_array().into_iter().flatten() { + if let Some(id) = project["id"].as_str() { + self.projects.insert(id.to_owned(), project.clone()); + } + } + } + Ok(()) + } + + pub fn project_of(&self, sha1: &str) -> Option<&Value> { + let id = self.versions.get(sha1)?["project_id"].as_str()?; + self.projects.get(id) + } + + /// Required dependencies of a file's version, as project ids. + pub fn required(&self, sha1: &str) -> Vec { + let Some(v) = self.versions.get(sha1) else { + return Vec::new(); + }; + v["dependencies"] + .as_array() + .into_iter() + .flatten() + .filter(|d| d["dependency_type"] == "required") + .filter_map(|d| d["project_id"].as_str().map(str::to_owned)) + .collect() + } +} + +fn post(url: &str, body: &Value) -> Result { + let response = ureq::post(url) + .set("User-Agent", AGENT) + .set("Content-Type", "application/json") + .send_string(&body.to_string()) + .map_err(|e| format!("{url}: {e}"))?; + read(url, response) +} + +fn get(url: &str) -> Result { + let response = ureq::get(url) + .set("User-Agent", AGENT) + .call() + .map_err(|e| format!("{url}: {e}"))?; + read(url, response) +} + +fn read(url: &str, response: ureq::Response) -> Result { + let text = response.into_string().map_err(|e| format!("{url}: {e}"))?; + serde_json::from_str(&text).map_err(|e| format!("{url}: {e}")) +} + +/// Percent-encoding for a query value. +fn encode(s: &str) -> String { + s.bytes() + .map(|b| match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { + (b as char).to_string() + } + _ => format!("%{b:02X}"), + }) + .collect() +} diff --git a/docs/modpacks.md b/docs/modpacks.md index 54dc43bdc..753299fda 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -262,6 +262,20 @@ inspected: └── coverage.json, coverage.md ``` +**Status.** `import` and `inventory` run today, `carry` follows (see below): + +``` +cargo run -p horizon-port-pack -- import ~/Downloads/pack.mrpack ~/.horizon/ports/pack +cargo run -p horizon-port-pack -- inventory ~/.horizon/ports/pack # --offline reuses modrinth.json +``` + +`inventory` reads metadata only: Modrinth answers by file hash, and the jars only if the user's +instance has them (an imported instance folder, or jars put in `/jars/`). Without jars, +classes come from the reviewed table, Modrinth categories and sides; with jars, from their +`mods.toml` / `fabric.mod.json` and file census too. On Create+ 6.0.0 alpha f (155 files, metadata +only): content 54, library 33, client-ui 26, performance 25, other 14, unknown 2, server-only 1; +40 rows matched the reviewed ATM10 table; three dependency layers (93 / 57 / 5). + ### 1. Import | Format | Read | Jars come from | From 673ac847243b44b515b7effdfe93bc730bfd97c4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:25:28 +0200 Subject: [PATCH 13/23] horizon-port-pack carry: a jar's data and assets as a content mod carry [...] turns each content mod with a jar into a folder content mod (API 0.2) in /mods//carry/, for local use: - assets//, data// and data/minecraft/tags/ are copied; other namespaces and vanilla data go to outside/ for review; no class file is copied. - Vanilla-type recipes get 26.3 ingredients ("id", "#tag", lists); custom types and NeoForge conditions are kept and listed. - Item models get the items/ client definitions 1.21.4 introduced. - Each block is declared from a vanilla template guessed from its blockstate properties; unknown property sets are listed. Items without a block are declared from minecraft:stick. The test builds a small NeoForge jar, carries it over, and reads the result with horizon-mods' own Content reader. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/horizon-port-pack/Cargo.toml | 3 + crates/horizon-port-pack/src/carry.rs | 440 ++++++++++++++++++++++++++ crates/horizon-port-pack/src/main.rs | 54 +++- docs/modpacks.md | 12 +- 5 files changed, 506 insertions(+), 4 deletions(-) create mode 100644 crates/horizon-port-pack/src/carry.rs diff --git a/Cargo.lock b/Cargo.lock index 9c3ad04ab..6ebc69964 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1502,6 +1502,7 @@ dependencies = [ name = "horizon-port-pack" version = "0.1.0" dependencies = [ + "horizon-mods", "serde", "serde_json", "sha1", diff --git a/crates/horizon-port-pack/Cargo.toml b/crates/horizon-port-pack/Cargo.toml index 1b33b6c01..3b903ad03 100644 --- a/crates/horizon-port-pack/Cargo.toml +++ b/crates/horizon-port-pack/Cargo.toml @@ -14,5 +14,8 @@ toml = "1.1.6" ureq = { version = "2", default-features = false, features = ["tls"] } zip = { version = "2", default-features = false, features = ["deflate"] } +[dev-dependencies] +horizon-mods = { path = "../horizon-mods", default-features = false } + [lints] workspace = true diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs new file mode 100644 index 000000000..42c457f02 --- /dev/null +++ b/crates/horizon-port-pack/src/carry.rs @@ -0,0 +1,440 @@ +//! Step 4, carry-over: a jar's `assets/` and `data/` into a folder content +//! mod (API 0.2) for local use. Files are copied, never code; recipes are +//! upgraded from 1.21.1 to 26.3, item models get their `items/` client +//! definitions, and each blockstate gets a vanilla template guessed from its +//! properties until the oracle's facts replace the guess. +use crate::jar::JarInfo; +use serde::Serialize; +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + io::Read, + path::Path, +}; + +#[derive(Debug, Default, Serialize)] +pub struct Report { + pub copied: usize, + /// Files outside what a content mod may hold (other namespaces, vanilla + /// data other than tags), kept in `outside/` for review. + pub outside: Vec, + pub recipes_upgraded: usize, + /// Recipes left as they were: custom types, NeoForge conditions. + pub recipes_kept: Vec, + pub item_definitions_added: usize, + /// Declared blocks and their guessed templates. + pub blocks: BTreeMap, + /// Blockstates whose properties match no template. + pub blocks_unknown: Vec, + pub items: usize, +} + +/// Vanilla blocks by their sorted property names. +const TEMPLATES: &[(&str, &str)] = &[ + ("", "minecraft:stone"), + ("axis", "minecraft:oak_log"), + ("type,waterlogged", "minecraft:oak_slab"), + ("facing,half,shape,waterlogged", "minecraft:oak_stairs"), + ("facing,half,hinge,open,powered", "minecraft:oak_door"), + ( + "facing,half,open,powered,waterlogged", + "minecraft:oak_trapdoor", + ), + ("east,north,south,waterlogged,west", "minecraft:oak_fence"), + ( + "east,north,south,up,waterlogged,west", + "minecraft:cobblestone_wall", + ), + ("facing,in_wall,open,powered", "minecraft:oak_fence_gate"), + ("face,facing,powered", "minecraft:oak_button"), + ("powered", "minecraft:oak_pressure_plate"), + ("facing", "minecraft:carved_pumpkin"), + ("facing,lit", "minecraft:furnace"), + ("lit", "minecraft:redstone_lamp"), + ("waterlogged", "minecraft:chain"), + ("age", "minecraft:wheat"), + ("distance,persistent,waterlogged", "minecraft:oak_leaves"), + ("stage", "minecraft:oak_sapling"), +]; + +pub fn template(properties: &BTreeSet) -> Option<&'static str> { + let key = properties.iter().cloned().collect::>().join(","); + TEMPLATES.iter().find(|(k, _)| *k == key).map(|(_, t)| *t) +} + +/// The property names a blockstate file uses. +pub fn properties(blockstate: &Value) -> BTreeSet { + let mut out = BTreeSet::new(); + let mut add = |pairs: &str| { + for pair in pairs.split(',').filter(|p| !p.is_empty()) { + out.insert(pair.split('=').next().unwrap_or(pair).to_owned()); + } + }; + for key in blockstate["variants"] + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k) + { + add(key); + } + for part in blockstate["multipart"].as_array().into_iter().flatten() { + let when = &part["when"]; + let mut conditions: Vec<&Value> = vec![when]; + for or in ["OR", "AND"] { + conditions.extend(when[or].as_array().into_iter().flatten()); + } + for c in conditions { + for (k, _) in c.as_object().into_iter().flatten() { + if k != "OR" && k != "AND" { + out.insert(k.clone()); + } + } + } + } + out +} + +/// A 1.21.1 ingredient (`{"item": id}`, `{"tag": t}` or a list of those) as +/// 26.3's (`"id"`, `"#t"`, `["id", ...]`); `None` for what has no 26.3 form +/// (custom ingredient types, tags inside lists). +pub fn ingredient(v: &Value) -> Option { + match v { + Value::String(_) => Some(v.clone()), + Value::Object(o) if o.len() == 1 => { + if let Some(Value::String(id)) = o.get("item") { + Some(json!(id)) + } else if let Some(Value::String(tag)) = o.get("tag") { + Some(json!(format!("#{tag}"))) + } else { + None + } + } + Value::Array(list) => { + let ids: Option> = list + .iter() + .map(|x| { + x.get("item") + .filter(|_| x.as_object().is_some_and(|o| o.len() == 1)) + .cloned() + }) + .collect(); + match ids? { + ids if ids.len() == 1 => ids.into_iter().next(), + ids => Some(Value::Array(ids)), + } + } + _ => None, + } +} + +/// A vanilla recipe upgraded in place; `false` (unchanged) when it is not +/// a vanilla type or one of its ingredients has no 26.3 form. +pub fn upgrade_recipe(recipe: &mut Value) -> bool { + let kind = recipe["type"].as_str().unwrap_or(""); + if !kind.starts_with("minecraft:") || recipe.get("neoforge:conditions").is_some() { + return false; + } + let mut out = recipe.clone(); + if let Some(key) = out.get_mut("key").and_then(Value::as_object_mut) { + for v in key.values_mut() { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + if let Some(list) = out.get_mut("ingredients").and_then(Value::as_array_mut) { + for v in list.iter_mut() { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + for field in ["ingredient", "base", "addition", "template"] { + if let Some(v) = out.get_mut(field) { + let Some(new) = ingredient(v) else { + return false; + }; + *v = new; + } + } + *recipe = out; + true +} + +/// Where a jar entry goes: `Some(true)` inside the content mod, `Some(false)` +/// to `outside/`, `None` not carried (code, metadata). +fn place(name: &str, id: &str) -> Option { + let mut parts = name.splitn(3, '/'); + let (root, ns, rest) = (parts.next()?, parts.next()?, parts.next()?); + if !(root == "assets" || root == "data") || rest.is_empty() || name.ends_with('/') { + return None; + } + Some(ns == id || (root == "data" && ns == "minecraft" && rest.starts_with("tags/"))) +} + +pub fn carry(jar: &Path, info: &JarInfo, out: &Path) -> Result { + let id = &info.mod_id; + if id.is_empty() + || id.len() > 64 + || !id + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') + { + return Err(format!( + "mod id {id:?} is not [a-z0-9_]{{1,64}}: rename it before carrying over" + )); + } + let file = fs::File::open(jar).map_err(|e| format!("{}: {e}", jar.display()))?; + let mut zip = zip::ZipArchive::new(file).map_err(|e| format!("{}: {e}", jar.display()))?; + let (inside, outside) = (out.join("carry"), out.join("outside")); + let _ = fs::remove_dir_all(&inside); + let _ = fs::remove_dir_all(&outside); + let mut report = Report::default(); + let mut blockstates: BTreeMap = BTreeMap::new(); + let mut item_models = BTreeSet::new(); + for i in 0..zip.len() { + let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; + let name = entry.name().to_owned(); + let Some(keep) = place(&name, id) else { + continue; + }; + if name.split('/').any(|p| p == ".." || p.is_empty()) { + continue; + } + let mut bytes = Vec::new(); + entry + .read_to_end(&mut bytes) + .map_err(|e| format!("{name}: {e}"))?; + let dest = if keep { + report.copied += 1; + inside.join(&name) + } else { + report.outside.push(name.clone()); + outside.join(&name) + }; + if keep { + let rel = name.split_once(&format!("/{id}/")).map_or("", |(_, r)| r); + if let Some(file) = rel + .strip_prefix("recipe/") + .filter(|_| name.starts_with("data/")) + { + if let Ok(mut recipe) = serde_json::from_slice::(&bytes) { + if upgrade_recipe(&mut recipe) { + report.recipes_upgraded += 1; + bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); + } else { + report.recipes_kept.push(file.to_owned()); + } + } + } else if let Some(b) = rel + .strip_prefix("blockstates/") + .and_then(|b| b.strip_suffix(".json")) + { + if let Ok(v) = serde_json::from_slice(&bytes) { + blockstates.insert(b.to_owned(), v); + } + } else if let Some(m) = rel + .strip_prefix("models/item/") + .and_then(|m| m.strip_suffix(".json")) + { + item_models.insert(m.to_owned()); + } + } + write(&dest, &bytes)?; + } + // 1.21.4 moved item models behind `items/.json` definitions. + for m in &item_models { + let def = inside.join(format!("assets/{id}/items/{m}.json")); + if !def.exists() { + let model = + json!({"model": {"type": "minecraft:model", "model": format!("{id}:item/{m}")}}); + write(&def, &serde_json::to_vec_pretty(&model).unwrap_or_default())?; + report.item_definitions_added += 1; + } + } + let decl = inside.join(format!("data/{id}/horizon")); + for (b, state) in &blockstates { + match template(&properties(state)) { + Some(t) => { + write( + &decl.join(format!("block/{b}.json")), + json!({"template": t}).to_string().as_bytes(), + )?; + report.blocks.insert(b.clone(), t.to_owned()); + } + None => report.blocks_unknown.push(b.clone()), + } + } + for m in item_models.iter().filter(|m| !blockstates.contains_key(*m)) { + let item = json!({"template": "minecraft:stick"}); + write( + &decl.join(format!("item/{m}.json")), + item.to_string().as_bytes(), + )?; + report.items += 1; + } + let q = |s: &str| toml::Value::String(s.to_owned()).to_string(); + let name = if info.name.is_empty() { id } else { &info.name }; + let manifest = format!( + "# Carried over from {jar} by horizon-port-pack, for local use only.\n# Licence: {license}\nid = {}\nname = {}\nversion = {}\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + q(id), + q(name), + q(&info.version), + jar = jar.file_name().unwrap_or_default().to_string_lossy(), + license = if info.license.is_empty() { + "not stated" + } else { + &info.license + }, + ); + write(&inside.join("horizon-mod.toml"), manifest.as_bytes())?; + write( + &out.join("carry-report.json"), + &serde_json::to_vec_pretty(&report).unwrap_or_default(), + )?; + Ok(report) +} + +fn write(path: &Path, bytes: &[u8]) -> Result<(), String> { + if let Some(dir) = path.parent() { + fs::create_dir_all(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + } + fs::write(path, bytes).map_err(|e| format!("{}: {e}", path.display())) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Write; + + #[test] + fn upgrades_ingredients() { + let mut r = json!({"type": "minecraft:crafting_shaped", "pattern": ["##"], + "key": {"#": {"item": "gem:gem"}, "s": {"tag": "c:rods/wooden"}}, + "result": {"id": "gem:gem_block", "count": 1}}); + assert!(upgrade_recipe(&mut r)); + assert_eq!(r["key"], json!({"#": "gem:gem", "s": "#c:rods/wooden"})); + let mut custom = json!({"type": "gem:infuse", "ingredient": {"item": "gem:gem"}}); + assert!(!upgrade_recipe(&mut custom)); + let mut tag_list = json!({"type": "minecraft:smelting", + "ingredient": [{"tag": "c:ores"}, {"item": "gem:gem"}]}); + assert!(!upgrade_recipe(&mut tag_list)); + } + + #[test] + fn templates_from_blockstate_properties() { + let door = + json!({"variants": {"facing=east,half=lower,hinge=left,open=false,powered=false": {}}}); + assert_eq!(template(&properties(&door)), Some("minecraft:oak_door")); + let fence = json!({"multipart": [{"apply": {}}, {"when": {"north": "true"}, "apply": {}}, + {"when": {"east": "true"}}, {"when": {"south": "true"}}, {"when": {"west": "true"}}, + {"when": {"OR": [{"waterlogged": "true"}]}}]}); + assert_eq!(template(&properties(&fence)), Some("minecraft:oak_fence")); + assert_eq!( + template(&properties(&json!({"variants": {"": {}}}))), + Some("minecraft:stone") + ); + let odd = json!({"variants": {"charge=1,mode=fast": {}}}); + assert_eq!(template(&properties(&odd)), None); + } + + /// A small NeoForge jar carried over is a content mod Horizon loads. + #[test] + fn carried_jar_is_a_content_mod() { + let dir = std::env::temp_dir().join(format!("horizon-port-pack-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let jar = dir.join("gem-1.0.jar"); + let mut zip = zip::ZipWriter::new(fs::File::create(&jar).unwrap()); + let files: &[(&str, &str)] = &[ + ( + "META-INF/neoforge.mods.toml", + "license = \"MIT\"\n[[mods]]\nmodId = \"gem\"\nversion = \"1.0\"\ndisplayName = \"Gem\"\n", + ), + ("com/example/gem/Gem.class", "not real bytecode"), + ( + "assets/gem/blockstates/gem_block.json", + r#"{"variants": {"": {"model": "gem:block/gem_block"}}}"#, + ), + ( + "assets/gem/blockstates/gem_door.json", + r#"{"variants": {"facing=east,half=lower,hinge=left,open=false,powered=false": {"model": "gem:block/gem_door"}}}"#, + ), + ( + "assets/gem/blockstates/gem_core.json", + r#"{"variants": {"charge=1": {"model": "gem:block/gem_core"}}}"#, + ), + ( + "assets/gem/models/item/gem.json", + r#"{"parent": "minecraft:item/generated", "textures": {"layer0": "gem:item/gem"}}"#, + ), + ( + "assets/gem/models/item/gem_block.json", + r#"{"parent": "gem:block/gem_block"}"#, + ), + ("assets/gem/textures/item/gem.png", "png"), + ("assets/gem/lang/en_us.json", r#"{"item.gem.gem": "Gem"}"#), + ( + "data/gem/recipe/gem_block.json", + r####"{"type": "minecraft:crafting_shaped", "pattern": ["###", "###", "###"], + "key": {"#": {"item": "gem:gem"}}, "result": {"id": "gem:gem_block", "count": 1}}"####, + ), + ( + "data/gem/recipe/infuse.json", + r#"{"type": "gem:infuse", "ingredient": {"item": "gem:gem"}}"#, + ), + ( + "data/gem/loot_table/blocks/gem_block.json", + r#"{"type": "minecraft:block", "pools": []}"#, + ), + ( + "data/minecraft/tags/block/mineable/pickaxe.json", + r#"{"values": ["gem:gem_block"]}"#, + ), + ("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#), + ]; + for (name, text) in files { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(text.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + + let info = crate::jar::read(&jar).unwrap(); + assert_eq!( + (info.mod_id.as_str(), info.license.as_str()), + ("gem", "MIT") + ); + assert_eq!(info.census.classes, 1); + let out = dir.join("work/mods/gem"); + let report = carry(&jar, &info, &out).unwrap(); + assert_eq!(report.copied, 11); + assert_eq!(report.outside, ["data/c/tags/item/gems.json"]); + assert_eq!((report.recipes_upgraded, report.recipes_kept.len()), (1, 1)); + assert_eq!(report.item_definitions_added, 2); + assert_eq!(report.blocks["gem_door"], "minecraft:oak_door"); + assert_eq!(report.blocks["gem_block"], "minecraft:stone"); + assert_eq!(report.blocks_unknown, ["gem_core"]); + assert_eq!(report.items, 1); + let carried = out.join("carry"); + assert!(!carried.join("com").exists()); + let recipe: Value = serde_json::from_slice( + &fs::read(carried.join("data/gem/recipe/gem_block.json")).unwrap(), + ) + .unwrap(); + assert_eq!(recipe["key"]["#"], "gem:gem"); + + // Horizon's own reader accepts it: blocks and items declared, files fenced. + let package = horizon_mods::Package::read(&carried).unwrap(); + let content = horizon_mods::Content::read(&carried, &package.manifest).unwrap(); + let blocks: Vec<&str> = content.blocks.iter().map(|b| b.id.as_str()).collect(); + assert_eq!(blocks, ["gem:gem_block", "gem:gem_door"]); + assert_eq!(content.items.len(), 1); + assert_eq!(content.items[0].id, "gem:gem"); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-port-pack/src/main.rs b/crates/horizon-port-pack/src/main.rs index 200e42334..4df3ef3ca 100644 --- a/crates/horizon-port-pack/src/main.rs +++ b/crates/horizon-port-pack/src/main.rs @@ -6,9 +6,12 @@ //! `/modrinth.json`), the jars in the instance or `/jars/`, //! classes, tiers and dependency layers in `/inventory.json` and //! `inventory.csv`. +//! - `carry [...]`: the content mods' data and assets into +//! `/mods//carry/`, a folder mod for local use. //! -//! The work folder belongs to the user: jars stay there and are never -//! uploaded or committed. +//! The work folder belongs to the user: jars and carried-over files stay +//! there and are never uploaded or committed. +mod carry; mod classify; mod import; mod inventory; @@ -17,7 +20,7 @@ mod modrinth; use std::{fs, path::Path, process::ExitCode}; -const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline]"; +const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | carry [...]"; fn main() -> ExitCode { let args: Vec = std::env::args().skip(1).collect(); @@ -29,6 +32,7 @@ fn main() -> ExitCode { Some("inventory") => { path(1).and_then(|w| inventory(w, args.iter().any(|a| a == "--offline"))) } + Some("carry") => path(1).and_then(|w| carry(w, &args[2..])), _ => Err(USAGE.to_owned()), }; match result { @@ -102,3 +106,47 @@ fn inventory(work: &Path, offline: bool) -> Result<(), String> { } Ok(()) } + +fn carry(work: &Path, only: &[String]) -> Result<(), String> { + let records: Vec = read_json(&work.join("inventory.json"))?; + let mut done = 0; + for r in &records { + let chosen = if only.is_empty() { + r.class == "content" + } else { + only.contains(&r.key) + }; + let (Some(jar), Some(info)) = (&r.jar, &r.info) else { + if chosen && !only.is_empty() { + eprintln!("{}: no jar (put it in {}/jars/)", r.key, work.display()); + } + continue; + }; + if !chosen { + continue; + } + match carry::carry(jar, info, &work.join("mods").join(&r.key)) { + Ok(report) => { + done += 1; + println!( + "{}: {} files, {} recipes upgraded ({} kept), {} item definitions added, {} blocks ({} without a template), {} items, {} outside", + r.key, + report.copied, + report.recipes_upgraded, + report.recipes_kept.len(), + report.item_definitions_added, + report.blocks.len(), + report.blocks_unknown.len(), + report.items, + report.outside.len() + ); + } + Err(e) => eprintln!("{}: {e}", r.key), + } + } + println!( + "{done} mods carried over into {}", + work.join("mods").display() + ); + Ok(()) +} diff --git a/docs/modpacks.md b/docs/modpacks.md index 753299fda..7951ad4d4 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -262,11 +262,12 @@ inspected: └── coverage.json, coverage.md ``` -**Status.** `import` and `inventory` run today, `carry` follows (see below): +**Status.** `import`, `inventory` and `carry` run today: ``` cargo run -p horizon-port-pack -- import ~/Downloads/pack.mrpack ~/.horizon/ports/pack cargo run -p horizon-port-pack -- inventory ~/.horizon/ports/pack # --offline reuses modrinth.json +cargo run -p horizon-port-pack -- carry ~/.horizon/ports/pack # content mods with a jar, or name them ``` `inventory` reads metadata only: Modrinth answers by file hash, and the jars only if the user's @@ -276,6 +277,15 @@ classes come from the reviewed table, Modrinth categories and sides; with jars, only): content 54, library 33, client-ui 26, performance 25, other 14, unknown 2, server-only 1; 40 rows matched the reviewed ATM10 table; three dependency layers (93 / 57 / 5). +`carry` copies a jar's `assets//`, `data//` and `data/minecraft/tags/` into +`mods//carry/`, a folder content mod (API 0.2) the game loads with `--dev-mod`, and keeps +what a content mod may not hold (other namespaces such as `c` tags, vanilla data) in `outside/`. +No class file is copied. It upgrades vanilla-type recipes from 1.21.1 ingredients to 26.3's, +adds the `items/` definitions 1.21.4 introduced, and declares each block from a vanilla template +guessed from its blockstate properties (stone for none, a door for `facing, half, hinge, open, +powered`, ...); blocks with an unknown property set, custom recipe types and NeoForge +conditions are listed in `carry-report.json` for the oracle step. + ### 1. Import | Format | Read | Jars come from | From be6a9d2cb57c63bf8dbcc3a08238582f6d5e31f5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:32:45 +0200 Subject: [PATCH 14/23] Stronghold ring test: wrap the seed + 1 for i64::MAX The threaded test added seed + 1 for seed = i64::MAX, which overflows in debug builds (CI's verify). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/src/worldgen/generator_structures.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 76b4d39c9..4ccf2ebb8 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -395,7 +395,7 @@ mod tests { let work = RingWork::new(vec![ (0, ring_searches(seed, 32, 3, 128)), (1, ring_searches(seed ^ 5, 10, 4, 0)), - (2, ring_searches(seed + 1, 20, 5, 40)), + (2, ring_searches(seed.wrapping_add(1), 20, 5, 40)), ]); let sets = [&preferred, &none, &preferred]; std::thread::scope(|scope| { @@ -409,7 +409,7 @@ mod tests { }; assert_eq!(rings["set0"], serial(seed, 32, 3, 128, &preferred)); assert_eq!(rings["set1"], Vec::new()); - assert_eq!(rings["set2"], serial(seed + 1, 20, 5, 40, &preferred)); + assert_eq!(rings["set2"], serial(seed.wrapping_add(1), 20, 5, 40, &preferred)); } } } From bfb6a0458d45f0e02f21e68d2c988cc804cae37e Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 14:33:44 -0400 Subject: [PATCH 15/23] Restrict crafter result rendering to crafter menus --- crates/horizon-client/src/game.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7072abeb5..57beb9f77 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4109,7 +4109,9 @@ impl Game<'_> { fn slot_view(&mut self, i: usize) -> Option { match i { 200 => self.craft_result(), - 309 => self.crafter_result(), + 309 if matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) => { + self.crafter_result() + } _ => self.slot_mut(i).clone(), } } From 24bb3f97aa21d9107fd5b6243337847fd7b0f134 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:35:59 +0200 Subject: [PATCH 16/23] Stronghold ring test: rustfmt Co-Authored-By: Claude Opus 5.5 --- crates/horizon-world/src/worldgen/generator_structures.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 4ccf2ebb8..4f804712f 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -409,7 +409,10 @@ mod tests { }; assert_eq!(rings["set0"], serial(seed, 32, 3, 128, &preferred)); assert_eq!(rings["set1"], Vec::new()); - assert_eq!(rings["set2"], serial(seed.wrapping_add(1), 20, 5, 40, &preferred)); + assert_eq!( + rings["set2"], + serial(seed.wrapping_add(1), 20, 5, 40, &preferred) + ); } } } From 05d1b92d56f6bf357fde51f2c9934d7239fd6c4f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 20:06:13 +0200 Subject: [PATCH 17/23] Renderer: skip wgpu's indirect-draw validation in release builds wgpu validates every indirect draw with a compute pass and a per-draw batcher before the render pass, for untrusted WebGPU content. The section draws are the only indirect draws and are in bounds by construction; the validation cost about 0.1 ms of the render thread per frame at render distance 32 on Metal. Debug builds keep it, and WGPU_VALIDATION_INDIRECT_CALL=1 turns it back on. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 073643809..d2c001ead 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -395,6 +395,24 @@ fn mip_chain( debug_assert_eq!(out.len(), chain_bytes * layers as usize); (out, levels) } +/// The wgpu instance options, without wgpu's validation of indirect draws +/// in release builds. That validation (meant for untrusted WebGPU content) +/// copies every indirect draw through a compute pass before the render pass +/// and costs about a tenth of `render`'s CPU time on Metal. The only indirect +/// draws are the section draws `render` writes from resident sections, in +/// bounds by construction: index counts within `indices`, vertices within +/// the section's arena range, first instances below the origins written that +/// frame. Debug builds keep validating them; `WGPU_VALIDATION_INDIRECT_CALL=1` +/// turns it back on. +fn instance_descriptor() -> wgpu::InstanceDescriptor { + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle(); + if !cfg!(debug_assertions) { + descriptor + .flags + .remove(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL); + } + descriptor.with_env() +} /// What to tell a player whose system offers no usable graphics adapter. /// Vulkan is loaded at run time (the game links no graphics library), so a /// missing driver shows here rather than as a missing-DLL dialog. @@ -438,8 +456,7 @@ impl Renderer { forcefield: (&[u8], u32), panorama_faces: &panorama::Faces, ) -> Result { - let instance = - wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let instance = wgpu::Instance::new(instance_descriptor()); // Offscreen rendering needs no surface, so it can use a GPU the // window's display cannot present from (a headless compositor). let surface = if offscreen { @@ -3102,6 +3119,16 @@ mod tests { assert_eq!(super::outline_width(3840), 5.0); } #[test] + fn indirect_draws_are_validated_only_in_debug_builds() { + if std::env::var_os("WGPU_VALIDATION_INDIRECT_CALL").is_none() { + let flags = super::instance_descriptor().flags; + assert_eq!( + flags.contains(wgpu::InstanceFlags::VALIDATION_INDIRECT_CALL), + cfg!(debug_assertions) + ); + } + } + #[test] fn far_faces_a_hair_apart_keep_their_depth_order() { let m = super::world_projection(70.0, 16.0 / 9.0, 768.0); let depth = |distance: f32| { From c57c409f40cb7a7b1e6939e0c61476a5134d9411 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 16:25:53 +0200 Subject: [PATCH 18/23] Split Resources into shared read-only data and per-game pack state Resources now holds only what is loaded once and never changes (blocks, items, recipes, biomes, mobs, collision, motion) and is Send + Sync behind an Arc, so an integrated server thread can share it with the client. What a resource pack reload replaces moves to PackResources (assets, meshing context, item renderer, names, panorama, clouds, forcefield), built by one loader used at startup and on reload. The client-only mutable state (the HUD atlas with its font cache and skin slots, fog state, screen effects) becomes the game's own fields. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/fog.rs | 16 - crates/horizon-client/src/game.rs | 349 ++++++++++-------- .../horizon-client/src/game/advancements.rs | 10 +- .../src/game/advancements_screen.rs | 18 +- crates/horizon-client/src/game/agent.rs | 2 +- .../horizon-client/src/game/armor_stands.rs | 10 +- crates/horizon-client/src/game/backdrop.rs | 8 +- crates/horizon-client/src/game/beacon.rs | 16 +- crates/horizon-client/src/game/beehives.rs | 4 +- .../src/game/block_entity_anims.rs | 2 +- crates/horizon-client/src/game/block_items.rs | 2 +- crates/horizon-client/src/game/blockctl.rs | 6 +- crates/horizon-client/src/game/boats.rs | 1 - crates/horizon-client/src/game/books.rs | 8 +- crates/horizon-client/src/game/cartography.rs | 6 +- crates/horizon-client/src/game/chat.rs | 30 +- .../horizon-client/src/game/command_blocks.rs | 14 +- crates/horizon-client/src/game/commands.rs | 16 +- .../src/game/commands/compute.rs | 2 +- .../horizon-client/src/game/commands/data.rs | 2 +- .../src/game/commands/effects.rs | 4 +- .../src/game/commands/execute.rs | 2 +- .../horizon-client/src/game/commands/place.rs | 4 +- .../src/game/commands/terrain_cmds.rs | 4 +- crates/horizon-client/src/game/composter.rs | 2 +- crates/horizon-client/src/game/control.rs | 2 +- .../horizon-client/src/game/copper_golems.rs | 2 +- crates/horizon-client/src/game/creaking.rs | 8 +- crates/horizon-client/src/game/creatures.rs | 12 +- crates/horizon-client/src/game/debug_keys.rs | 2 +- .../src/game/dispense_fixture.rs | 2 +- crates/horizon-client/src/game/dispenser.rs | 18 +- crates/horizon-client/src/game/dragon.rs | 24 +- crates/horizon-client/src/game/end.rs | 14 +- crates/horizon-client/src/game/explosion.rs | 2 +- crates/horizon-client/src/game/extras.rs | 8 +- crates/horizon-client/src/game/fangs.rs | 1 - crates/horizon-client/src/game/fishing.rs | 1 - crates/horizon-client/src/game/fov.rs | 2 +- crates/horizon-client/src/game/frames.rs | 2 +- .../src/game/gamemode_switcher.rs | 6 +- crates/horizon-client/src/game/ghasts.rs | 2 +- crates/horizon-client/src/game/golems.rs | 2 +- crates/horizon-client/src/game/growth.rs | 2 +- crates/horizon-client/src/game/hand.rs | 2 +- .../horizon-client/src/game/initial_spawn.rs | 4 +- crates/horizon-client/src/game/item_draw.rs | 22 +- crates/horizon-client/src/game/jukebox.rs | 2 +- crates/horizon-client/src/game/lan.rs | 4 +- crates/horizon-client/src/game/lan_actions.rs | 2 +- crates/horizon-client/src/game/lan_screen.rs | 15 +- crates/horizon-client/src/game/leads.rs | 2 +- crates/horizon-client/src/game/lightning.rs | 6 +- crates/horizon-client/src/game/loom.rs | 6 +- crates/horizon-client/src/game/machines.rs | 6 +- .../src/game/machines/crafter.rs | 4 +- crates/horizon-client/src/game/maps.rs | 7 +- crates/horizon-client/src/game/minecarts.rs | 15 +- crates/horizon-client/src/game/mob_blocks.rs | 6 +- crates/horizon-client/src/game/mods.rs | 4 +- crates/horizon-client/src/game/mount_menu.rs | 4 +- crates/horizon-client/src/game/mounts.rs | 2 +- crates/horizon-client/src/game/music.rs | 2 +- crates/horizon-client/src/game/names.rs | 6 +- .../horizon-client/src/game/nether_portal.rs | 4 +- .../src/game/ominous_item_spawner.rs | 2 +- crates/horizon-client/src/game/options.rs | 18 +- crates/horizon-client/src/game/packs.rs | 48 +-- crates/horizon-client/src/game/pad_menu.rs | 10 +- crates/horizon-client/src/game/paintings.rs | 2 +- crates/horizon-client/src/game/persist.rs | 4 +- crates/horizon-client/src/game/perspective.rs | 18 +- crates/horizon-client/src/game/potions.rs | 8 +- crates/horizon-client/src/game/raids.rs | 2 +- crates/horizon-client/src/game/recipe_book.rs | 10 +- crates/horizon-client/src/game/remote.rs | 19 +- .../horizon-client/src/game/render_control.rs | 2 +- crates/horizon-client/src/game/render_tick.rs | 66 ++-- .../horizon-client/src/game/respawn_anchor.rs | 12 +- crates/horizon-client/src/game/scoreboard.rs | 8 +- crates/horizon-client/src/game/screens.rs | 8 +- crates/horizon-client/src/game/sculk.rs | 6 +- .../horizon-client/src/game/sculk_fixture.rs | 4 +- crates/horizon-client/src/game/sign_edit.rs | 6 +- crates/horizon-client/src/game/spawner.rs | 2 +- crates/horizon-client/src/game/stations.rs | 38 +- .../horizon-client/src/game/stats_screen.rs | 10 +- crates/horizon-client/src/game/storage.rs | 4 +- .../horizon-client/src/game/subtitle_hud.rs | 2 +- crates/horizon-client/src/game/titles.rs | 10 +- crates/horizon-client/src/game/tnt.rs | 10 +- crates/horizon-client/src/game/trading.rs | 10 +- .../horizon-client/src/game/trial_spawner.rs | 6 +- .../horizon-client/src/game/trial_visuals.rs | 2 +- crates/horizon-client/src/game/trident.rs | 1 - crates/horizon-client/src/game/tweaks.rs | 4 +- crates/horizon-client/src/game/vault.rs | 8 +- crates/horizon-client/src/game/wind.rs | 3 +- crates/horizon-client/src/mobs/data.rs | 5 +- crates/horizon-client/src/mobs/render.rs | 2 + 100 files changed, 563 insertions(+), 582 deletions(-) diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 801b1e303..83f1a8bf5 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -119,22 +119,6 @@ impl FogState { } } -/// The fog tables and evolving state kept by the game. -pub struct FogRenderer { - pub tables: FogTables, - pub state: FogState, -} -impl FogRenderer { - pub fn load(root: &Path, biomes: &Biomes) -> Self { - Self { - tables: FogTables::load(root, biomes), - state: FogState::default(), - } - } - pub fn setup(&self, input: &FogInputs) -> FogData { - setup_fog(&self.tables, &self.state, input) - } -} /// `FluidState.getHeightForCamera`. fn camera_fluid_height(world: &World, facts: &BlockFacts, b: [i32; 3]) -> Option<(Fluid, f64)> { let s = facts.get(world.block(b[0], b[1], b[2])); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 57beb9f77..c7fc7f1c7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -645,43 +645,91 @@ struct FallingBlock { /// The UUID and compound it was loaded with, kept while it moves. saved: Option>, } +/// The data loaded once at startup and never changed: blocks, items, +/// recipes, biomes, mobs, collision and motion. Read-only and `Send + Sync`, +/// so the client and an integrated server thread can share one copy. pub struct Resources { - assets: Arc, facts: BlockFacts, items: Items, recipes: Recipes, transformers: horizon_client::block_transform::Transformers, biomes: Arc, environment: Environment, - atlas: HudAtlas, - panorama: horizon_client::gfx::panorama::Faces, - layer_names: HashMap, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer, animate: horizon_client::animate_tick::AnimateTables, - fog: horizon_client::fog::FogRenderer, + fog: horizon_client::fog::FogTables, music: horizon_client::music::MusicTables, ambient: horizon_client::ambience::AmbientTables, - screen_fx: horizon_client::screen_effects::ScreenEffects, nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, - names: Names, - /// clouds.png: (width, height, filled cells). - clouds: (u32, u32, Vec), - /// misc/forcefield.png: (width, height, RGBA) for the world border wall. - forcefield: (u32, u32, Vec), - context: Arc, + collision: BlockCollisionRegistry<'static>, + motion: MotionResources, threads: usize, player_arm: Option, player_type: Option>, - /// Item definitions, baked item models and special renderers. - item_renderer: Arc, /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } +/// What a resource pack reload replaces (`Minecraft.reloadResourcePacks`): +/// block models and sprites with their meshing tables, item models, +/// translations and the textures read on the CPU. Each game holds its own; +/// cloning shares the loaded data. +#[derive(Clone)] +pub struct PackResources { + assets: Arc, + context: Arc, + layer_names: Arc>, + panorama: Arc, + /// Item definitions, baked item models and special renderers. + item_renderer: Arc, + names: Arc, + /// clouds.png: (width, height, filled cells). + clouds: Arc<(u32, u32, Vec)>, + /// misc/forcefield.png: (width, height, RGBA) for the world border wall. + forcefield: Arc<(u32, u32, Vec)>, +} +impl PackResources { + /// Everything a pack overlay at `root` provides, over `assets` loaded from it. + fn load( + root: &std::path::Path, + assets: Arc, + facts: &BlockFacts, + biomes: Arc, + light: Arc, + ) -> Result { + let visibility = models::load_visibility(root, assets.registry)?; + let tables = Arc::new(MeshTables::new(&assets, facts, visibility)?); + let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( + root, + assets.model_library.clone(), + )?; + Ok(Self { + layer_names: Arc::new( + assets + .sprite_layers + .iter() + .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) + .collect(), + ), + context: Arc::new(WorkerContext { + assets: assets.clone(), + tables, + biomes, + light, + }), + assets, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + item_renderer: Arc::new(item_renderer), + names: Arc::new(Names::load(root)), + clouds: Arc::new(load_clouds(root)), + forcefield: Arc::new(load_forcefield(root)), + }) + } +} /// A quick craft drag as the screen draws it: each dragged slot's count and /// whether the slot caps it (None: hidden), and what stays in hand. struct DragView { @@ -705,9 +753,17 @@ fn select_creative_tab( } struct Game<'a> { - res: &'a mut Resources, + /// Shared with an integrated server; `collision` and `motion` borrow from it. + res: Arc, collision: &'a BlockCollisionRegistry<'a>, motion: &'a MotionResources, + /// This game's resource packs (`reload_packs` replaces them). + pack: PackResources, + /// The GUI, font, particle, map and skin atlas. + atlas: HudAtlas, + /// `FogRenderer`'s evolving state. + fog: horizon_client::fog::FogState, + screen_fx: horizon_client::screen_effects::ScreenEffects, world: World, streaming: Streaming, options: Options, @@ -1170,7 +1226,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1368,7 +1424,7 @@ impl Game<'_> { } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self - .res + .pack .assets .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) @@ -1378,7 +1434,7 @@ impl Game<'_> { .flat_map(|(_, m)| m.faces.iter()) .find(|f| f.quad.facing == horizon_assets::model::Direction::Up) .or_else(|| models.iter().flat_map(|(_, m)| m.faces.iter()).next())?; - let name = self.res.layer_names.get(&face.layer)?.clone(); + let name = self.pack.layer_names.get(&face.layer)?.clone(); let tint = if face.quad.tint_index >= 0 { let n = &self.res.facts.get(state).name; if n.contains("leaves") || n.contains("vine") { @@ -1394,7 +1450,7 @@ impl Game<'_> { fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> { let f = self.res.facts.get(state); let offset = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, pos[0], pos[2]) @@ -1467,7 +1523,7 @@ impl Game<'_> { state: BlockStateId, held: Option<&ItemStack>, ) -> Vec { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let dynamic = self.pending.dynamic(pos); match self.res.items.block_loot_sequence(registry, state) { Some(sequence) => { @@ -1548,7 +1604,7 @@ impl Game<'_> { let environment = item.environment_tick( &self.world, &self.res.facts, - self.res.assets.registry, + self.pack.assets.registry, &self.res.items, ); // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. @@ -1684,7 +1740,7 @@ impl Game<'_> { behaviours: &self.res.behaviours, items: &self.res.items, loot: horizon_client::structure_blocks::loot_data(&self.options.resources), - registry: self.res.assets.registry, + registry: self.pack.assets.registry, rules, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, @@ -3179,7 +3235,7 @@ impl Game<'_> { entities: &ghast_collisions, player, scene: &mut self.world, - assets: &self.res.assets, + assets: &self.pack.assets, collision_binding: self.collision, resources: self.motion, } @@ -3626,7 +3682,7 @@ impl Game<'_> { let (stack, capped) = match drag.and_then(|d| d.slots.get(&slot)) { Some(None) => return, Some(Some((count, capped))) => { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); let carried = self .carried .clone() @@ -3721,10 +3777,10 @@ impl Game<'_> { 0, 0, &decorations, - &self.res.atlas.font, + &self.atlas.font, )); draws.push(hud_layout::GuiDraw::Pop); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); @@ -3732,7 +3788,7 @@ impl Game<'_> { // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); self.frame_graph - .draw(self.settings.horizon.overlay, &mut batch, &self.res.atlas); + .draw(self.settings.horizon.overlay, &mut batch, &self.atlas); self.draw_pad_cursor(&mut batch); batch } @@ -3753,12 +3809,12 @@ impl Game<'_> { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); let mut ui = - horizon_client::ui_theme::Ui::new(&self.res.atlas, &mut batch, self.cursor); + horizon_client::ui_theme::Ui::new(&self.atlas, &mut batch, self.cursor); title.draw_horizon(&mut ui, fade); ui.finish(); } else { title.draw( - &self.res.atlas, + &self.atlas, &mut batch, self.cursor, self.settings.file.bool("hideSplashTexts"), @@ -3766,7 +3822,7 @@ impl Game<'_> { } return batch; } - let atlas_ptr: *const HudAtlas = &self.res.atlas; + let atlas_ptr: *const HudAtlas = &self.atlas; let _ = atlas_ptr; if self.remote_overlay(&mut batch) { return batch; @@ -3795,7 +3851,7 @@ impl Game<'_> { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) }); let draws = hud_layout::crosshair(wi, hi, attack, full); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -3807,7 +3863,7 @@ impl Game<'_> { attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { @@ -3829,7 +3885,7 @@ impl Game<'_> { // Hud.extractSleepOverlay, under the sidebar, titles and chat. if let Some((_, ticks)) = self.sleeping { let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); - hud_layout::paint(&mut batch, &self.res.atlas, &draws); + hud_layout::paint(&mut batch, &self.atlas, &draws); } if !self.ui.hide_gui { self.draw_titles(&mut batch); @@ -3845,7 +3901,7 @@ impl Game<'_> { && !spectator && let Some(p) = &mut self.player { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let width = |s: &str| HudBatch::text_width(atlas, s) as i32; let draws = hud_layout::experience( wi, @@ -3906,7 +3962,7 @@ impl Game<'_> { self.draw_selected_name(&mut batch, !self.creative); } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !self.ui.hide_gui && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -3921,9 +3977,9 @@ impl Game<'_> { // PauseScreen(false): only its title, at the top. Screen::Paused => { let title = self.translate("menu.paused", "Game Paused"); - let tw = HudBatch::text_width(&self.res.atlas, &title); + let tw = HudBatch::text_width(&self.atlas, &title); batch.text( - &self.res.atlas, + &self.atlas, &title, ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), 10.0, @@ -4141,7 +4197,7 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if i == 504 && self.offhand.is_none() { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/container/slot/shield", ox + sx, oy + sy, @@ -4150,7 +4206,7 @@ impl Game<'_> { if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -4166,7 +4222,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -4297,7 +4353,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -4408,8 +4464,8 @@ impl Game<'_> { let search = &self.creative_screen.search; self.text_selection.select(("creative.search", 0), search); } - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); let shown = items.get(first * 9 + slot - Creative::DISPLAY); let catalog = &self.res.items; let max = |s: &ItemStack| catalog.get(&s.item).map_or(64, |i| i.max_stack); @@ -5323,7 +5379,7 @@ impl Game<'_> { m.height(), camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5345,7 +5401,7 @@ impl Game<'_> { p.dimensions.height, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, @@ -5368,7 +5424,7 @@ impl Game<'_> { 0.25, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5387,7 +5443,7 @@ impl Game<'_> { 1.975 * scale, camera, fire_yaw, - &self.res.atlas.sprites, + &self.atlas.sprites, self.world.light( stand.position.x.floor() as i32, stand.position.y.floor() as i32, @@ -5412,7 +5468,7 @@ impl Game<'_> { self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() { + if let Some(sprite) = self.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -5467,7 +5523,7 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.res.atlas.sprites, + sprites: &self.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { @@ -5475,7 +5531,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.res.atlas.glyph_cell(c), + glyph: &|c| self.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). @@ -5520,7 +5576,6 @@ impl Game<'_> { } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self - .res .atlas .sprites .get("entity/experience/experience_orb") @@ -5632,7 +5687,7 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.res.atlas; + let atlas = &self.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -5652,13 +5707,13 @@ impl Game<'_> { if self.res.facts.get(state).render_shape == horizon_client::blocks::RenderShape::Model && let Ok(models) = self - .res + .pack .assets .model_catalog .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) { let offset = self - .res + .pack .context .tables .offset(state, m.pos[0], m.pos[2]) @@ -5931,11 +5986,11 @@ impl Game<'_> { } for ((x, y, z), lit) in lit_changes { let state = self.world.block(x, y, z); - if let Some(mut s) = self.res.assets.registry.state(state).cloned() + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() && s.properties.contains_key("lit") { s.properties.insert("lit".into(), lit.to_string()); - if let Ok(id) = self.res.assets.registry.resolve(&s) { + if let Ok(id) = self.pack.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; } } @@ -5976,7 +6031,7 @@ impl Game<'_> { /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) @@ -6278,14 +6333,14 @@ impl Game<'_> { world_root, dim.id(), ))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let flat = (dim == Dim::Overworld) .then(|| horizon_client::save::world_gen_settings(world_root)) .flatten() .and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - res.assets.registry, + pack.assets.registry, &res.biomes, ) }); @@ -6294,26 +6349,26 @@ impl Game<'_> { Arc::new(Persistent { inner: Arc::new(inner), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else if self.options.test_terrain && dim == Dim::Overworld { - let inner = Arc::new(TestTerrain::new(res.assets.registry, &res.biomes)?); + let inner = Arc::new(TestTerrain::new(pack.assets.registry, &res.biomes)?); Streaming::new( Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) } else { - let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), res.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { + let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); @@ -6321,10 +6376,10 @@ impl Game<'_> { Arc::new(Persistent { inner, save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads, ) }; @@ -6349,7 +6404,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save(&chunks, self.pack.assets.registry, &self.res.biomes)?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -6474,7 +6529,7 @@ impl Game<'_> { for x_axis in [true, false] { if let Some((origin, width, height)) = self.portal_shape(at, x_axis) { let d = if x_axis { [1, 0, 0] } else { [0, 0, 1] }; - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let Some(default) = registry.default_state("minecraft:nether_portal") else { return Ok(false); }; @@ -6747,7 +6802,7 @@ impl Game<'_> { } } } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let id = self.world.block(pos[0], pos[1], pos[2]); let Some(state) = registry .state(id) @@ -6839,7 +6894,7 @@ impl Game<'_> { [-1, 0, 0] => "west", _ => "east", }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let (state, sound, loot, damage, particle) = { let around = Column { world: &self.world, @@ -6893,7 +6948,7 @@ impl Game<'_> { Ok(true) } fn set_state_named(&mut self, pos: [i32; 3], name: &str, keep: &[&str]) -> Result { - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let old = self.world.block(pos[0], pos[1], pos[2]); let Some(default) = registry.default_state(name) else { return Ok(false); @@ -7073,7 +7128,7 @@ impl Game<'_> { return Ok(UseResult::Success { swing: true }); } if item == "honeycomb" { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let old = registry.state(clicked).cloned(); if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) @@ -7098,7 +7153,7 @@ impl Game<'_> { } let name = self.res.facts.get(clicked).name.clone(); if self.can_light(clicked, &name) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut state = registry .state(clicked) .cloned() @@ -7447,13 +7502,7 @@ impl Game<'_> { let Some(arm) = self.res.player_arm.clone() else { continue; }; - let Some(r) = self - .res - .atlas - .sprites - .get("entity/player/wide/steve") - .copied() - else { + let Some(r) = self.atlas.sprites.get("entity/player/wide/steve").copied() else { continue; }; // renderPlayerArm (right arm) @@ -7523,7 +7572,7 @@ impl Game<'_> { "minecraft:trident" if using => ItemPose::Trident { ticks_used }, _ if using => { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(&stack)); @@ -7580,7 +7629,7 @@ impl Game<'_> { /// The renderer for the window, with the current block sprites, shared /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - let assets = &self.res.assets; + let assets = &self.pack.assets; let mut renderer = pollster::block_on(Renderer::new( window, self.options.offscreen, @@ -7590,16 +7639,11 @@ impl Game<'_> { assets.texture_layers, &assets.sprite_mips, &assets.animations, - ( - &self.res.atlas.pixels, - self.res.atlas.width, - self.res.atlas.height, - ), - (&self.res.forcefield.2, self.res.forcefield.0), - &self.res.panorama, + (&self.atlas.pixels, self.atlas.width, self.atlas.height), + (&self.pack.forcefield.2, self.pack.forcefield.0), + &self.pack.panorama, ))?; renderer.hud.fire_animations = self - .res .atlas .fire_animations .iter() @@ -7720,7 +7764,7 @@ impl Game<'_> { if intensity <= 0.0 { return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (Some(rain_tex), Some(snow_tex)) = ( atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied(), @@ -7808,7 +7852,7 @@ impl Game<'_> { let night = (12542..23460).contains(&time) || self.world.weather.thundering; let state = self.world.block(pos[0], pos[1], pos[2]); let props = self - .res + .pack .assets .registry .state(state) @@ -7909,7 +7953,7 @@ impl Game<'_> { } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, text); let (x, y) = (x + 12.0, y - 12.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 16.0, rgba(16, 0, 16, 240)); @@ -7931,7 +7975,7 @@ impl Game<'_> { ) }; batch.fill( - &self.res.atlas, + &self.atlas, 0.0, 0.0, batch.width, @@ -7942,7 +7986,7 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { if i != selected { let (tx, ty) = Creative::tab_position(t); - batch.sprite(&self.res.atlas, &tab_sprite(t, false), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(t, false), ox + tx, oy + ty); } } let background = if tab.search { @@ -7952,13 +7996,13 @@ impl Game<'_> { } else { "gui/container/creative_inventory/tab_items" }; - if let Some(mut r) = self.res.atlas.sprites.get(background).copied() { + if let Some(mut r) = self.atlas.sprites.get(background).copied() { r.u1 = r.u0 + (r.u1 - r.u0) * Creative::WIDTH / r.w as f32; r.v1 = r.v0 + (r.v1 - r.v0) * Creative::HEIGHT / r.h as f32; batch.rect_uv(ox, oy, Creative::WIDTH, Creative::HEIGHT, r, u32::MAX); } let (tx, ty) = Creative::tab_position(&tab); - batch.sprite(&self.res.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); + batch.sprite(&self.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); let stack = ItemStack { @@ -7974,7 +8018,7 @@ impl Game<'_> { oy + ty + if t.top { 9.0 } else { 7.0 }, ); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; if !tab.inventory { batch.text( atlas, @@ -8016,7 +8060,7 @@ impl Game<'_> { if Self::creative_trash_hovered(batch, self.cursor) { let (x, y) = Creative::TRASH_POSITION; batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8027,7 +8071,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (x, y) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + x, oy + y, 16.0, @@ -8036,8 +8080,8 @@ impl Game<'_> { ); } } else { - let items = self.creative_screen.items(&self.res.names); - let first = self.creative_screen.first_row(&self.res.names); + let items = self.creative_screen.items(&self.pack.names); + let first = self.creative_screen.first_row(&self.pack.names); for r in 0..5 { for c in 0..9 { let Some(stack) = items.get((first + r) * 9 + c) else { @@ -8050,7 +8094,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - batch.fill(&self.res.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(stack.item.to_string()); } } @@ -8069,14 +8113,14 @@ impl Game<'_> { hovered = Some(stack.item.to_string()); } } - let scrollable = self.creative_screen.rows(&self.res.names) > 5; + let scrollable = self.creative_screen.rows(&self.pack.names) > 5; let scroller = if scrollable { "gui/sprites/container/creative_inventory/scroller" } else { "gui/sprites/container/creative_inventory/scroller_disabled" }; batch.sprite( - &self.res.atlas, + &self.atlas, scroller, ox + Creative::SCROLL_X, oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), @@ -8102,7 +8146,7 @@ impl Game<'_> { } else if self.carried.is_none() && let Some(item) = hovered { - let name = self.res.names.item(&item); + let name = self.pack.names.item(&item); self.tooltip(batch, &name, self.cursor.0, self.cursor.1); } self.draw_inventory_effects(batch, (ox, oy), Creative::WIDTH as i32); @@ -8158,7 +8202,7 @@ impl Game<'_> { if !right && self .creative_screen - .press_scrollbar(cx - ox, cy - oy, &self.res.names) + .press_scrollbar(cx - ox, cy - oy, &self.pack.names) { return; } @@ -8277,7 +8321,7 @@ impl Game<'_> { let keys: Vec<_> = self.world.modified.drain().collect(); let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); self.save - .save_later(&chunks, self.res.assets.registry, &self.res.biomes)?; + .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; if wait { self.save.flush(); } @@ -8385,7 +8429,7 @@ impl Game<'_> { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); let f = self.res.facts.get(state); let o = if f.outline_offset { - self.res + self.pack .context .tables .offset(state, h.pos[0], h.pos[2]) @@ -8540,10 +8584,10 @@ impl Game<'_> { clouds: ((!title || live) && self.dim == Dim::Overworld && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) - .then(|| self.res.atlas.sprites.get("horizon/white")) + .then(|| self.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { - texture: &self.res.clouds, + texture: &self.pack.clouds, uv: [(white.u0 + white.u1) / 2.0, (white.v0 + white.v1) / 2.0], camera, time: self.world.game_time, @@ -8570,15 +8614,14 @@ impl Game<'_> { .mining .as_ref() .and_then(|m| { - self.res.atlas.sprites.get(&format!( + self.atlas.sprites.get(&format!( "block/destroy_stage_{}", ((m.progress * 10.0) as u32).min(9) )) }) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { - self.res - .atlas + self.atlas .sprites .get(n) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) @@ -8586,7 +8629,7 @@ impl Game<'_> { ticks: self.ticks, darkness: self.darkness_lighting(alpha as f32), night_vision: self.night_vision_intensity(), - block_flicker: self.res.fog.state.block_light_flicker, + block_flicker: self.fog.block_light_flicker, post: if live { Some(horizon_client::post::PostGrade::FROST) } else if self.horizon_pause() { @@ -8638,7 +8681,7 @@ impl Game<'_> { reason: horizon_client::level_loading::Reason, ) { use horizon_client::level_loading::{self, Reason, STATUS_RADIUS}; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); match reason { // The panorama and its blur are drawn by the renderer. @@ -8910,7 +8953,7 @@ impl Game<'_> { if !modified.is_empty() && let Err(e) = horizon_client::spans::time("save_chunks", || { self.save - .save_later(&modified, self.res.assets.registry, &self.res.biomes) + .save_later(&modified, self.pack.assets.registry, &self.res.biomes) }) { log::warn!("Horizon: failed to save unloaded chunks: {e}"); @@ -9114,7 +9157,7 @@ impl ApplicationHandler for Game<'_> { && !horizon_client::ui_theme::horizon() { title.drag(self.cursor, (b.width, b.height)); - title.drag_field(&self.res.atlas, self.cursor.0); + title.drag_field(&self.atlas, self.cursor.0); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -9169,7 +9212,7 @@ impl ApplicationHandler for Game<'_> { self.options_scroll(d); } if self.screen == Screen::Creative && d != 0.0 { - self.creative_screen.wheel(f64::from(d), &self.res.names); + self.creative_screen.wheel(f64::from(d), &self.pack.names); } if self.screen == Screen::Inventory && d != 0.0 @@ -9218,7 +9261,7 @@ impl ApplicationHandler for Game<'_> { .map(|r| [r.config.width, r.config.height]) .unwrap_or([1, 1]); let mut b = HudBatch::new(size); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let shift = self.has_shift_down(); let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { @@ -9778,24 +9821,16 @@ pub fn run() -> Result<()> { let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); - let visibility = models::load_visibility(&root, assets.registry)?; - log::info!("load visibility: {:.2}s", started.elapsed().as_secs_f32()); - let tables = Arc::new(MeshTables::new(&assets, &facts, visibility)?); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - log::info!("load tables: {:.2}s", started.elapsed().as_secs_f32()); + let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; + log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32()); let atlas = HudAtlas::build(&root)?; - let panorama = horizon_client::gfx::panorama::Faces::load(&root); horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], &early_settings.language, )); log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); - let layer_names = assets - .sprite_layers - .iter() - .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) - .collect(); let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; let motion = MotionResources::load(&root, ®istry_owner)?; @@ -9803,12 +9838,6 @@ pub fn run() -> Result<()> { "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); - let context = Arc::new(WorkerContext { - assets: assets.clone(), - tables, - biomes: biomes.clone(), - light, - }); let threads = early_settings.horizon.worker_threads(); log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", @@ -9821,7 +9850,7 @@ pub fn run() -> Result<()> { // Until a world is opened the streamer is idle. let mut streaming = Streaming::new( Arc::new(TestTerrain::new(assets.registry, &biomes)?), - context.clone(), + pack.context.clone(), 1, ); streaming.paused = true; @@ -9841,26 +9870,17 @@ pub fn run() -> Result<()> { let stations = horizon_client::stations::StationData::load(&root, &items); let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; - let fog = horizon_client::fog::FogRenderer::load(&root, &biomes); - let item_renderer = Arc::new( - horizon_client::item_render::ItemRenderer::load_with_library( - &root, - assets.model_library.clone(), - )?, - ); - let mut resources = Resources { + let fog = horizon_client::fog::FogTables::load(&root, &biomes); + let resources = Arc::new(Resources { stations, - assets, facts, items, recipes, transformers, biomes, environment, - atlas, - panorama, - item_renderer, - layer_names, + collision, + motion, providers: Providers::load(&root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( &root, @@ -9870,25 +9890,20 @@ pub fn run() -> Result<()> { fog, music: horizon_client::music::MusicTables::load(&root), ambient: horizon_client::ambience::AmbientTables::load(&root), - screen_fx: Default::default(), nether_environment: Environment::load_dimension(&root, "the_nether", false)?, end_environment: Environment::load_dimension(&root, "the_end", false)?, behaviours: Behaviours::load(registry_owner.registry, &root)?, - names: Names::load(&root), - clouds: load_clouds(&root), - forcefield: load_forcefield(&root), mob_types: MobTypes::load(&root)? .types .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), mob_data, - context, threads, player_type: perspective::player_type(&root), player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - }; + }); // These batches share the exported document instead of reparsing it per layer. let (armor_stand_assets, boat_models, cart_models) = { let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); @@ -9914,11 +9929,15 @@ pub fn run() -> Result<()> { settings.render_distance = d; } let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &resources.atlas.sprites); + let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); let mut game = Game { - res: &mut resources, - collision: &collision, - motion: &motion, + res: resources.clone(), + collision: &resources.collision, + motion: &resources.motion, + pack, + atlas, + fog: Default::default(), + screen_fx: Default::default(), world, streaming, options, @@ -10325,6 +10344,14 @@ mod tests { use horizon_client::container_screen::{Button, Clicks, Release, Target}; use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys}; + /// An integrated server thread shares the loaded resources with the client. + #[test] + fn shared_resources_can_cross_threads() { + fn shared() {} + shared::(); + shared::(); + } + #[test] fn selecting_creative_tabs_does_not_drop_the_carried_stack_on_release() { let mut creative = Creative::from_json(&serde_json::json!({ diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 3a5711e41..980b5769e 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -109,7 +109,7 @@ impl adv::World for View<'_, '_> { let name = self.0.res.facts.get(state).name.to_string(); let props = self .0 - .res + .pack .assets .registry .state(state) @@ -613,7 +613,7 @@ impl Game<'_> { } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { - let Some(definition) = self.res.assets.registry.state(state).cloned() else { + let Some(definition) = self.pack.assets.registry.state(state).cloned() else { return; }; let me = self.player_entity(); @@ -746,11 +746,11 @@ impl Game<'_> { if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); @@ -759,7 +759,7 @@ impl Game<'_> { self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 3340ca78a..5e1c0343b 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -257,7 +257,7 @@ impl Game<'_> { } /// `AdvancementWidget`'s title lines, description lines and width. fn adv_widget_text(&self, i: usize) -> (Vec, Vec, f32) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; let a = &self.adv.tree.list[i]; let Some(d) = &a.display else { return (Vec::new(), Vec::new(), 0.0); @@ -320,7 +320,7 @@ impl Game<'_> { let (sx, sy) = self.adv_ui.scroll.unwrap_or_default(); let (sx, sy) = (sx.floor() as i32, sy.floor() as i32); self.adv_tick_hover(&view, sx, sy, left, top); - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("gui.advancements", &[]); let tw = atlas.font.width_text(&title); @@ -432,7 +432,7 @@ impl Game<'_> { } let (x, y) = pos(i); let (x, y) = ((ox + x) as f32, (oy + y) as f32); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_scaled( atlas, frame_sprite(d.frame, done), @@ -449,7 +449,7 @@ impl Game<'_> { } } // The window, tabs and title. - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/advancements/window", @@ -463,7 +463,7 @@ impl Game<'_> { let (x, y) = tab_pos(ty, i); let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab); batch.sprite_scaled( - &self.res.atlas, + &self.atlas, &sprite, left + x, top + y, @@ -482,7 +482,7 @@ impl Game<'_> { } } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else( || Text::translate("gui.advancements", &[]), |d| text_of(&d.title), @@ -497,7 +497,7 @@ impl Game<'_> { } } // Done. - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( @@ -520,7 +520,7 @@ impl Game<'_> { let (cx, cy) = self.cursor; if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 { if let Some(d) = &tree.list[t].display { - ui::tooltip(batch, &self.res.atlas, &[text_of(&d.title)], self.cursor); + ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor); } break; } @@ -604,7 +604,7 @@ impl Game<'_> { ], ) }); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32; let top_side = title_bottom + desc_h >= INSIDE_H; let amount = if a.criteria.is_empty() || total == 0 { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 0493a5d7d..cd39606b3 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -301,7 +301,7 @@ pub(super) enum Handled { impl Game<'_> { pub(super) fn state_string(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index c8be758ab..03a60faca 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -124,7 +124,7 @@ impl Game<'_> { continue; }; let (Some(r), Some(part)) = ( - self.res.atlas.sprites.get(texture.as_str()), + self.atlas.sprites.get(texture.as_str()), assets.player.get(layer), ) else { continue; @@ -379,7 +379,7 @@ impl Game<'_> { let mut dead = Vec::new(); for (i, a) in self.armor_stands.iter_mut().enumerate() { a.tick(&mut scene); - if !a.environment_tick(&self.world, &self.res.facts, self.res.assets.registry) { + if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) { dead.push(i); } } @@ -403,7 +403,7 @@ impl Game<'_> { out: &mut Vec, ) { let assets = &self.armor_stand_assets; - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let Some(wood) = uv_of("entity/armorstand/armorstand") else { return; @@ -668,12 +668,12 @@ impl Game<'_> { self.dim == super::Dim::Nether, )), }; - self.res.item_renderer.submit_special( + self.pack.item_renderer.submit_special( &special, &serde_json::Value::Null, false, pose, - &self.res.atlas.sprites, + &self.atlas.sprites, &self.item_host(), &mut sink, ); diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 15ca99ba9..149cddefa 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -150,11 +150,11 @@ impl Game<'_> { .join("backdrop"); std::fs::create_dir_all(&root)?; let save = Arc::new(SaveDir::new(root.join(format!("{seed}")))); - let res = &*self.res; + let (res, pack) = (&*self.res, &self.pack); let inner = Arc::new( VanillaTerrain::new( &self.options.resources.join("worldgen"), - res.assets.registry, + pack.assets.registry, &res.biomes, seed, ) @@ -164,10 +164,10 @@ impl Game<'_> { Arc::new(Persistent { inner: inner.clone(), save: save.clone(), - registry: res.assets.clone(), + registry: pack.assets.clone(), biomes: res.biomes.clone(), }), - res.context.clone(), + pack.context.clone(), res.threads.min(6), ); streaming.radius = self.settings.render_distance.clamp(4, 10); diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 1526cad6f..15a7de79d 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -385,7 +385,7 @@ impl Game<'_> { let levels = self.beacon_levels(); let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon); let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -406,7 +406,7 @@ impl Game<'_> { ("block.minecraft.beacon.secondary", "Secondary Power", 169.0), ] { let text = self.translate(key, fallback); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = HudBatch::text_width(atlas, &text); batch.text( atlas, @@ -421,7 +421,7 @@ impl Game<'_> { let x = [20.0, 41.0, 63.0, 86.0, 108.0][i]; self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut tooltip = None; let button = |batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| { @@ -503,7 +503,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -524,13 +524,7 @@ impl Game<'_> { } /// `BeaconRenderer`: each section's rotating solid beam and its glow. pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(s) = self - .res - .atlas - .sprites - .get("entity/beacon/beacon_beam") - .copied() - else { + let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else { return; }; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index eb74becc7..0520e4367 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -63,7 +63,7 @@ impl HiveHost for GameHive<'_, '_> { impl Game<'_> { fn hive_with_honey(&self, state: BlockStateId, level: i32) -> Option { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut s = registry.state(state)?.clone(); s.properties .insert("honey_level".to_owned(), level.to_string()); @@ -82,7 +82,7 @@ impl Game<'_> { { return None; } - let props = &self.res.assets.registry.state(state)?.properties; + let props = &self.pack.assets.registry.state(state)?.properties; let honey = props.get("honey_level").and_then(|v| v.parse().ok()); let facing = beehive::facing_step(props.get("facing").map(String::as_str)); Some((honey, facing)) diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index c83b493ed..d377aeb45 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -280,7 +280,7 @@ impl Game<'_> { Ticker::Conduit => { let world = &self.world; let facts = &self.res.facts; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let is_water = |p: [i32; 3]| { facts.get(world.block(p[0], p[1], p[2])).fluid == horizon_client::blocks::Fluid::Water diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index e9a426404..b8012cce1 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -46,7 +46,7 @@ impl Game<'_> { // BeehiveBlock.getCloneItemStack: the honey level as the item's block state. if include_data && let Some(level) = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 369e46316..993e0789e 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -33,7 +33,7 @@ fn parse_state(text: &str) -> Result { impl Game<'_> { fn state_text(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { @@ -69,7 +69,7 @@ impl Game<'_> { "setblock" => { let pos = [int(1)?, int(2)?, int(3)?]; let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?; @@ -81,7 +81,7 @@ impl Game<'_> { "fill" => { let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]); let state = self - .res + .pack .assets .registry .resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?; diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 40211161d..a5a609cac 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -712,7 +712,6 @@ impl Game<'_> { }; let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self - .res .atlas .sprites .get(&format!("entity/{folder}/{}", b.wood)) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 3904ab465..5603e8369 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -45,7 +45,7 @@ pub(super) enum BookScreen { } impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.res.atlas.font.split(&Text::literal(page), 114.0) + self.atlas.font.split(&Text::literal(page), 114.0) } /// `WritableBookItem.use` / `WrittenBookItem.use`. pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { @@ -242,7 +242,7 @@ impl Game<'_> { /// the page (`MultilineTextField.insertText`: line breaks kept, cut to /// the 1024 characters left, rejected when it overflows the 14 lines). fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.res.atlas.font; + let font = &self.atlas.font; match self.book.as_mut() { Some(BookScreen::Edit { signing: true, @@ -363,7 +363,7 @@ impl Game<'_> { } fn set_lectern_property(&mut self, key: (i32, i32, i32), name: &str, value: bool) { let state = self.world.block(key.0, key.1, key.2); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; @@ -549,7 +549,7 @@ impl Game<'_> { } pub(super) fn draw_book(&self, batch: &mut HudBatch) { let Some(book) = &self.book else { return }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let (mx, my) = self.cursor; let hover = diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index a59a31669..86d5d5395 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -89,17 +89,17 @@ impl Game<'_> { if is_locked { locked = true; if scaling || locking { - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } if scaling && scale >= 4 { locked = true; - batch.sprite(&self.res.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); } } let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| { batch.sprite( - &game.res.atlas, + &game.atlas, &format!("gui/sprites/container/cartography_table/{name}"), ox + x, oy + y, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 16c5295c9..8f6bed0ca 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -226,7 +226,7 @@ impl Game<'_> { .map(|k| horizon_client::command::args::normalize(k)) .collect(); reg.block_tags.sort(); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let mut blocks: BTreeMap>> = BTreeMap::new(); for id in 0..registry.len() { let Some(state) = registry.state(horizon_world::registry::BlockStateId(id as u32)) @@ -389,7 +389,7 @@ impl Game<'_> { .as_ref() .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -428,7 +428,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( - &self.res.atlas, + &self.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, @@ -441,7 +441,7 @@ impl Game<'_> { /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { if let Some(shortcut) = self.edit_shortcut(event) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -487,7 +487,7 @@ impl Game<'_> { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -513,7 +513,7 @@ impl Game<'_> { } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -536,7 +536,7 @@ impl Game<'_> { let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); if let Some(line) = heard { self.mods_chat(&line); } @@ -564,7 +564,7 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -577,7 +577,7 @@ impl Game<'_> { return; } match self.ui.chat.click_at( - &self.res.atlas.font, + &self.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, @@ -603,15 +603,13 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui - .chat - .draw(batch, &self.res.atlas, self.ticks, focused); + self.ui.chat.draw(batch, &self.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.res.atlas.font); + let m = Measure(&self.atlas.font); let c = Commands { dispatcher: self.mods.dispatcher(), registries: &self.ui.registries, @@ -629,7 +627,7 @@ impl Game<'_> { .chat_opened .map_or(0, |t| t.elapsed().as_millis() as u64); let draws = screen.draw(&m, mouse, blink, background); - horizon_client::screen_draw::paint(batch, &self.res.atlas, &draws); + horizon_client::screen_draw::paint(batch, &self.atlas, &draws); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when @@ -821,11 +819,11 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, message, None, self.ticks, focused); + .add(&self.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.res.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 97419c986..5a5fa11c8 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -193,7 +193,7 @@ impl Game<'_> { } } fn block_state_at(&self, pos: Pos) -> Option<&'static BlockState> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; state_of(registry, self.world.block(pos.0, pos.1, pos.2)) } fn schedule_command_block(&mut self, pos: Pos) { @@ -202,7 +202,7 @@ impl Game<'_> { } /// `CommandBlockEntity.scheduleTick`. fn schedule_command_block_tick(&mut self, pos: Pos) { - mark_condition_met(&mut self.world, self.res.assets.registry, pos); + mark_condition_met(&mut self.world, self.pack.assets.registry, pos); self.schedule_command_block(pos); } fn update_output_signal(&mut self, pos: Pos) { @@ -225,7 +225,7 @@ impl Game<'_> { } let at = BlockPos::new(pos.0, pos.1, pos.2); let signal = self.with_level(|b, level, ticks| b.has_neighbor_signal(level, ticks, at)); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; if let Some((was, auto)) = set_powered(&mut self.world, registry, pos, signal) && signal && !was @@ -249,7 +249,7 @@ impl Game<'_> { return; }; if mode == Mode::Auto { - mark_condition_met(&mut self.world, self.res.assets.registry, key); + mark_condition_met(&mut self.world, self.pack.assets.registry, key); } match command_block::tick_action(mode, was_met, conditional(state)) { Some(true) => self.command_block_execute(key, state), @@ -283,7 +283,7 @@ impl Game<'_> { /// `CommandBlock.executeChain`: the chain command blocks in front, each /// facing on to the next, up to `max_command_sequence_length`. fn execute_chain(&mut self, start: Pos, mut step: [i32; 3]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let limit = self.ui.rules.int("max_command_sequence_length"); let mut remaining = limit; let mut pos = start; @@ -458,7 +458,7 @@ impl Game<'_> { self.close_command_block(); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let mid = (w / 2.0).floor(); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); @@ -578,7 +578,7 @@ impl Game<'_> { return; } let pos = s.pos; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(current) = self.block_state_at(pos) else { return; }; diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 29befe606..6c4817f63 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -340,7 +340,7 @@ impl Game<'_> { .find(|i| i.id == id) .map(|i| i.stack.item.to_string()) .unwrap_or_default(); - Text::literal(self.res.names.item(&item)) + Text::literal(self.pack.names.item(&item)) } Target::Mob(id) if self @@ -783,7 +783,7 @@ impl Game<'_> { _ => text::WHITE, }; Text::literal("[") - .append(Text::literal(self.res.names.item(item))) + .append(Text::literal(self.pack.names.item(item))) .append("]") .with_color(color) } @@ -816,7 +816,7 @@ impl Game<'_> { &[], ) } else { - Text::literal(self.res.names.item(item)) + Text::literal(self.pack.names.item(item)) }; let wrapped = Text::translate("chat.square_brackets", &[hover]); if empty { @@ -1456,7 +1456,7 @@ impl Game<'_> { name: b.id.clone(), properties: b.properties.iter().cloned().collect(), }; - self.res + self.pack .assets .registry .resolve(&state) @@ -1464,7 +1464,7 @@ impl Game<'_> { } /// BlockPredicateArgument test. fn block_matches(&self, b: &BlockInput, state: BlockStateId) -> bool { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name_ok = if b.tag { @@ -1739,7 +1739,7 @@ impl Game<'_> { let strict = ctx.has("strict"); // CloneCommands.clone sets every destination to a barrier first, so // each copied state but a barrier counts as placed. - let barrier = self.res.assets.registry.default_state("minecraft:barrier"); + let barrier = self.pack.assets.registry.default_state("minecraft:barrier"); let mut count = 0; for (_, to, s, entity) in copies { self.place_state(to, s, strict)?; @@ -2266,7 +2266,7 @@ impl Game<'_> { } /// `PoiTypes`: the point of interest type of a block state. fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; let name = s.name.strip_prefix("minecraft:")?; Some(match name { "blast_furnace" => "minecraft:armorer", @@ -2542,7 +2542,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs index 8ffcfac03..24552011d 100644 --- a/crates/horizon-client/src/game/commands/compute.rs +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -494,7 +494,7 @@ impl Game<'_> { return false; }; let state = self.world.block(p[0], p[1], p[2]); - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return false; }; let name = s.name.to_string(); diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index a10fff3bd..1d2321a1a 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -180,7 +180,7 @@ impl Game<'_> { } pub(in crate::game) fn data_block_name(&self, p: [i32; 3]) -> String { let state = self.world.block(p[0], p[1], p[2]); - self.res + self.pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index ffa44d745..3e04f7179 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -227,7 +227,7 @@ impl Game<'_> { return Err(err( "commands.enchant.failed.incompatible", &[&stack.custom_name().map_or_else( - || self.res.names.item(&stack.item).to_string(), + || self.pack.names.item(&stack.item).to_string(), str::to_owned, )], )); @@ -247,7 +247,7 @@ impl Game<'_> { ), Some(item) => err( "commands.enchant.failed.incompatible", - &[&self.res.names.item(&item)], + &[&self.pack.names.item(&item)], ), }); } diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index a9cfb19b8..1fa67c8b6 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -652,7 +652,7 @@ impl Game<'_> { let facts = self.res.facts.get(state); let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None; let leaves = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 502cb53f4..3e447a7fb 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -25,7 +25,7 @@ impl Game<'_> { .join("worldgen/blocks/structure-blocks.json"), ) .ok()?; - StateTransforms::from_json(&json, self.res.assets.registry.len()).ok() + StateTransforms::from_json(&json, self.pack.assets.registry.len()).ok() }) .as_ref() } @@ -64,7 +64,7 @@ impl Game<'_> { }; return Some(Arc::new(StructureTemplate::from_nbt( &named.tag, - self.res.assets.registry, + self.pack.assets.registry, transforms, ))); } diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 048a7c71c..cee7a1d72 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -551,14 +551,14 @@ impl Game<'_> { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), random, ) } None => self.res.items.block_drops( - self.res.assets.registry, + self.pack.assets.registry, state, tool.as_ref(), &mut self.world.random, diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 942e02eda..3e4cb7169 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -13,7 +13,7 @@ impl Game<'_> { /// The composter's `level` at `pos`, None when it isn't a composter. pub(super) fn composter_level(&self, pos: [i32; 3]) -> Option { let state = self.world.block(pos[0], pos[1], pos[2]); - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; if &*s.name != "minecraft:composter" { return None; } diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 08d21e6cd..e1169b2c8 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -427,7 +427,7 @@ impl Game<'_> { match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), - Screen::Options => self.ui.options.type_text(&self.res.atlas, text), + Screen::Options => self.ui.options.type_text(&self.atlas, text), // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index 7cb6f946a..a12fbd416 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -168,7 +168,7 @@ impl Game<'_> { ] .into(), }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(id) = registry.id(&state) else { return; }; diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index c87c98f7a..1caa419ff 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -84,7 +84,7 @@ impl HeartHost for Host<'_> { impl Game<'_> { fn heart_state_name(&self, state: BlockStateId) -> String { - self.res + self.pack .assets .registry .state(state) @@ -177,7 +177,7 @@ impl Game<'_> { } /// `Creaking.tearDown`: the crumble particles. pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let crumble = |this: &mut Self, name: &str, props: &[(&str, &str)], count: i32| { let Some(mut state) = registry .default_state(name) @@ -229,7 +229,7 @@ impl Game<'_> { }); let state = self.world.block(key.0, key.1, key.2); let natural = self - .res + .pack .assets .registry .state(state) @@ -297,7 +297,7 @@ impl Game<'_> { /// entity (`newBlockEntity`) the first time their chunk is seen. fn scan_for_hearts(&mut self) { let Some(heart) = self - .res + .pack .assets .registry .default_state("minecraft:creaking_heart") diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 351b622cb..460b73708 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -378,7 +378,7 @@ impl Game<'_> { let (rain, thunder) = self.world.weather.levels(1.0); MobWorld { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, movement: &self.motion.blocks, collision: self.collision, @@ -995,7 +995,7 @@ impl Game<'_> { 0.8, ); } - if let Some(state) = self.res.assets.registry.default_state(name) { + if let Some(state) = self.pack.assets.registry.default_state(name) { self.world.set(pos[0], pos[1], pos[2], state)?; } } @@ -1004,7 +1004,7 @@ impl Game<'_> { self.destroy_particles(pos, old); if drop { let drops = self.res.items.block_drops_in( - self.res.assets.registry, + self.pack.assets.registry, old, None, &mut self.world.random, @@ -1752,7 +1752,7 @@ impl Game<'_> { ) -> horizon_client::arrows::ArrowScene<'s, 's> { horizon_client::arrows::ArrowScene { world: &self.world, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, facts: &self.res.facts, collision: self.collision, fluids: &self.motion.fluids, @@ -2008,7 +2008,7 @@ impl Game<'_> { .facts .is_air(self.world.block(fire[0], fire[1], fire[2])) && let Some(state) = - self.res.assets.registry.default_state("minecraft:fire") + self.pack.assets.registry.default_state("minecraft:fire") { self.world.set(fire[0], fire[1], fire[2], state)?; } @@ -2767,7 +2767,7 @@ impl Game<'_> { } /// 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.res.atlas; + let atlas = &self.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); for mob in &self.mobs { diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 95e3ca52c..3aac02ae7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -423,7 +423,7 @@ impl Game<'_> { )); } let (left, right) = d.columns(&self.debug_chart_lines()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); let charts = self.debug_charts.draw( &atlas.font, diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index 0d8043ecc..ee8170bc5 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -224,7 +224,7 @@ impl Game<'_> { for p in crafter_positions { let state = self.world.block(p.0, p.1, p.2); let triggered = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index c6cf3ff56..cb28aa1cc 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -308,7 +308,7 @@ pub(super) fn mob_set_slot(m: &mut Mob, slot: Slot, stack: ItemStack) { impl Game<'_> { fn prop(&self, state: BlockStateId, key: &str) -> Option { - self.res + self.pack .assets .registry .state(state)? @@ -318,11 +318,11 @@ impl Game<'_> { } /// The same block with other properties (`withProperty`). fn with_props(&self, state: BlockStateId, props: &[(&str, &str)]) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); + let mut s = self.pack.assets.registry.state(state)?.clone(); for (k, v) in props { s.properties.insert((*k).to_owned(), (*v).to_owned()); } - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() } fn block_at(&self, p: Pos) -> BlockStateId { self.world.block(p.0, p.1, p.2) @@ -1407,7 +1407,7 @@ impl Game<'_> { } }; let skull = self - .res + .pack .assets .registry .default_state("minecraft:wither_skeleton_skull") @@ -1470,7 +1470,7 @@ impl Game<'_> { && self.can_spawn_golem([target.0, target.1, target.2]) { if let Some(pumpkin) = self - .res + .pack .assets .registry .default_state("minecraft:carved_pumpkin") @@ -2046,10 +2046,10 @@ impl Game<'_> { return None; } let twin = format!("minecraft:waxed_{n}"); - let mut s = self.res.assets.registry.state(state)?.clone(); - self.res.assets.registry.default_state(&twin)?; + let mut s = self.pack.assets.registry.state(state)?.clone(); + self.pack.assets.registry.default_state(&twin)?; s.name = twin; - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() }); let Some(waxed) = waxed.filter(|_| name.contains("copper") || name.contains("lightning_rod")) @@ -2108,7 +2108,7 @@ impl Game<'_> { 1.0, ); self.post_block_game_event("minecraft:fluid_place", [pos.0, pos.1, pos.2], None, None); - if let Some(mud) = self.res.assets.registry.default_state("minecraft:mud") { + if let Some(mud) = self.pack.assets.registry.default_state("minecraft:mud") { self.level_set([target.0, target.1, target.2], mud)?; } let bottle = ItemStack::new("minecraft:glass_bottle", 1); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index 5d1eef394..ff91df583 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -582,7 +582,7 @@ impl Game<'_> { } /// `EndCrystal.tick`: the time and the fire below it in the End. fn tick_crystals(&mut self) { - let fire = self.res.assets.registry.default_state("minecraft:fire"); + let fire = self.pack.assets.registry.default_state("minecraft:fire"); for i in 0..self.crystals.len() { self.crystals[i].time += 1; let p = self.crystals[i].position; @@ -1702,7 +1702,7 @@ impl Game<'_> { } if !self.fight.previously_killed && let Some(egg) = self - .res + .pack .assets .registry .default_state("minecraft:dragon_egg") @@ -1866,9 +1866,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, &bars, - &self.res.atlas.font, + &self.atlas.font, ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, /// with `setCreateWorldFog`). @@ -1906,13 +1906,7 @@ impl Game<'_> { return; }; let a = alpha as f32; - let sprite = |n: &str| { - self.res - .atlas - .sprites - .get(n) - .map(|r| [r.u0, r.v0, r.u1, r.v1]) - }; + let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]); let (Some(skin), Some(eyes)) = ( sprite("entity/enderdragon/dragon"), sprite("entity/enderdragon/dragon_eyes"), @@ -2078,7 +2072,7 @@ impl Game<'_> { } /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let uv = [white.u0, white.v0]; let over = if t > 0.8 { ((t - 0.8) / 0.2).min(1.0) @@ -2134,7 +2128,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/end_crystal/end_crystal_beam") @@ -2196,7 +2189,6 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self - .res .atlas .sprites .get("entity/enderdragon/dragon_fireball") @@ -2610,7 +2602,7 @@ impl Game<'_> { /// and grown again with a guarded crystal. fn rebuild_spike(&mut self, spike: &horizon_world::worldgen::end_spike::EndSpike) { let (cx, cz, h) = (spike.center_x, spike.center_z, spike.height); - let air = self.res.assets.registry.default_state("minecraft:air"); + let air = self.pack.assets.registry.default_state("minecraft:air"); let Some(air) = air else { return; }; @@ -2685,7 +2677,7 @@ impl Game<'_> { } /// Iron bars connected north, south, west and east. fn set_bars(&mut self, pos: [i32; 3], sides: [bool; 4]) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut state) = registry .default_state("minecraft:iron_bars") .and_then(|d| registry.state(d).cloned()) diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index 4bebc8d9b..d02904872 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -142,7 +142,7 @@ impl Game<'_> { /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. pub(super) fn end_sky_geometry(&self) -> Vec { let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.res.atlas.sprites.get("environment/end_sky").copied() else { + let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else { return out; }; use std::f32::consts::FRAC_PI_2; @@ -184,7 +184,6 @@ impl Game<'_> { let intensity = self.end.flash.intensity(self.clock.fraction() as f32); if intensity > 1e-5 && let Some(r) = self - .res .atlas .sprites .get("environment/celestial/end_flash") @@ -237,7 +236,7 @@ impl Game<'_> { if &*stack.item != "minecraft:ender_eye" { return Ok(false); } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let target = self.pick().and_then(|hit| { let state = registry.state(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]))?; (state.name == "minecraft:end_portal_frame").then(|| (hit, state.clone())) @@ -303,7 +302,7 @@ impl Game<'_> { /// ring (corners free) of filled frames, all facing the centre or all /// facing away from it. Returns the centre of the 3×3 opening. fn portal_ring_center(&self, frame: [i32; 3]) -> Option<[i32; 3]> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; // (offset from the centre, facing when the frames face the centre) let mut ring = Vec::with_capacity(12); for i in -1..=1 { @@ -630,7 +629,7 @@ impl Game<'_> { &[], )?; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; for (facing, d) in [ ("north", [0, -1]), ("south", [0, 1]), @@ -898,8 +897,7 @@ impl Game<'_> { fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let (Some(model), Some(r)) = ( self.crystal_model.as_ref(), - self.res - .atlas + self.atlas .sprites .get("entity/end_crystal/end_crystal") .copied(), @@ -1052,7 +1050,7 @@ impl Game<'_> { /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self.res.atlas.sprites.get("item/ender_eye").copied() else { + let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else { return; }; let alpha = self.clock.fraction(); diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index b871e8df9..4ed2772c7 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -511,7 +511,7 @@ impl Game<'_> { // random sequence. let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); let drops = self.res.items.block_drops_exploded( - self.res.assets.registry, + self.pack.assets.registry, state, None, &dynamic, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 1495800ec..c6ac6d25e 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -193,10 +193,10 @@ impl Game<'_> { if !self.extras.minimap.compose(view) { return; } - let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else { return; }; - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -242,7 +242,7 @@ impl Game<'_> { let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); - let atlas = &self.res.atlas; + let atlas = &self.atlas; if let Some(view) = self.minimap_view() && visible(map_corner) && !self.extras.minimap.image.is_empty() @@ -286,7 +286,7 @@ impl Game<'_> { use_: self.extras.mouse[1], cps, }; - extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k); + extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k); } if mod_panels { self.draw_mod_panels(batch, &mut corners); diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index 2f09bc538..dd2b9bde6 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -108,7 +108,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/illager/evoker_fangs") diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index eb7a54f99..8a63f2cfe 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -565,7 +565,6 @@ impl Game<'_> { return; }; let Some(r) = self - .res .atlas .sprites .get("entity/fishing/fishing_hook") diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 778c0f0a2..7825d6514 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -171,6 +171,6 @@ impl Game<'_> { } let draws = hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 26e195d4e..3ffa0e67e 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -301,7 +301,7 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); for f in &self.item_frames { diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs index e7826ba22..5f73080f4 100644 --- a/crates/horizon-client/src/game/gamemode_switcher.rs +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -39,7 +39,7 @@ impl Game<'_> { }; switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); let selected = switcher.selected; - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/container/gamemode_switcher", @@ -62,14 +62,14 @@ impl Game<'_> { for (index, mode) in MODES.into_iter().enumerate() { let (x, y) = slot_origin(w, h, index); batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/slot", x as f32, y as f32, ); if mode == selected { batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/gamemode_switcher/selection", x as f32, y as f32, diff --git a/crates/horizon-client/src/game/ghasts.rs b/crates/horizon-client/src/game/ghasts.rs index 9bdd9460d..8ce0a4231 100644 --- a/crates/horizon-client/src/game/ghasts.rs +++ b/crates/horizon-client/src/game/ghasts.rs @@ -110,7 +110,7 @@ impl Game<'_> { f64::from(pos[2]) + 0.5, ]; let facing = self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 990ce4271..2bfeda70d 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -146,7 +146,7 @@ impl Game<'_> { let below = [head[0], head[1] - 1, head[2]]; let copper = self.world.block(below[0], below[1], below[2]); let pumpkin = self.world.block(head[0], head[1], head[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let facing = registry .state(pumpkin) .and_then(|s| s.properties.get("facing").cloned()) diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index 7e5ad08ce..18591b0fe 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -15,7 +15,7 @@ impl Game<'_> { } let dir = self.options.resources.join("worldgen"); let started = std::time::Instant::now(); - let features = vanillagen::shared_data(&dir, self.res.assets.registry) + let features = vanillagen::shared_data(&dir, self.pack.assets.registry) .map_err(|e| e.to_string()) .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); match features { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index ddbdcb058..76d626716 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -257,7 +257,7 @@ impl Game<'_> { .or_else(|| self.held()); if let Some(stack) = active { let components = self - .res + .pack .item_renderer .models .components(&horizon_client::item_render::stack_view(stack)); diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 1f5d294a7..5fcd90517 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -72,7 +72,7 @@ impl Game<'_> { fn spawn_columns(&self) -> Columns<'_, '_> { Columns { world: &self.world, - properties: &self.res.assets.properties, + properties: &self.pack.assets.properties, binding: self.collision, } } @@ -82,7 +82,7 @@ impl Game<'_> { horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| { horizon_client::flatgen::FlatTerrain::from_settings( &s, - self.res.assets.registry, + self.pack.assets.registry, &self.res.biomes, ) }) diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index 87599042e..aae200b50 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -31,7 +31,7 @@ impl ItemEnv for Env<'_, '_> { } fn grass_color(&self, temperature: f64, downfall: f64) -> i32 { self.game - .res + .pack .item_renderer .grass_color(temperature, downfall) } @@ -43,7 +43,7 @@ impl ItemEnv for Env<'_, '_> { else { return 0.0; }; - let prototypes = &self.game.res.item_renderer.models.prototypes; + let prototypes = &self.game.pack.item_renderer.models.prototypes; let mut total = 0.0f64; for item in items { let id = item["id"].as_str().unwrap_or(""); @@ -216,7 +216,7 @@ impl Game<'_> { && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) { let view = item_render::stack_view(stack); - let duration = use_duration(&self.res.item_renderer.models.components(&view)); + let duration = use_duration(&self.pack.item_renderer.models.components(&view)); owner.using_this_item = true; owner.use_duration = duration; owner.use_item_remaining_ticks = duration - ticks as i32; @@ -239,7 +239,7 @@ impl Game<'_> { seed: i32, ) -> ItemRenderState { let level = self.item_level(); - self.res.item_renderer.resolve( + self.pack.item_renderer.resolve( &item_render::stack_view(stack), display, owner, @@ -254,8 +254,8 @@ impl Game<'_> { let state = self.resolve_item(stack, DisplayContext::Gui, Some(&owner), 0); item_render::gui::draw( &state, - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), batch, x, @@ -278,8 +278,8 @@ impl Game<'_> { lights: Some(diffuse_lights(self.dim == Dim::Nether)), }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -299,8 +299,8 @@ impl Game<'_> { lights: None, }; state.submit( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -360,7 +360,7 @@ impl Game<'_> { (q.y + 0.1).floor() as i32, q.z.floor() as i32, ); - let seed = i64::from(self.res.item_renderer.item_id(&item.stack.item)) + let seed = i64::from(self.pack.item_renderer.item_id(&item.stack.item)) + i64::from(item.stack.damage); for copy in item_render::cluster_poses( &state, diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 3bde15818..235ad7c24 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -21,7 +21,7 @@ impl Game<'_> { } fn set_has_record(&mut self, pos: [i32; 3], has: bool) { let state = self.world.block(pos[0], pos[1], pos[2]); - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let Some(mut s) = registry.state(state).cloned() else { return; }; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index e34d71bc7..024f671b2 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -440,7 +440,7 @@ impl Game<'_> { encoder.tables = Some( self.save .tables - .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.res.assets))) + .get_or_init(|| Arc::new(horizon_client::save::SaveTables::new(&self.pack.assets))) .clone(), ); let lan = Lan::start_with(sync.clone(), net)?; @@ -886,7 +886,7 @@ impl Game<'_> { let Some(host) = &self.lan else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { let entity_start = out.len(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 41ba2f84d..6bf76f160 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -859,7 +859,7 @@ impl Game<'_> { entities: &[], player, scene: &mut game.world, - assets: &game.res.assets, + assets: &game.pack.assets, collision_binding: game.collision, resources: game.motion, }; diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 0081b1745..2402a5286 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -502,7 +502,7 @@ impl Game<'_> { View::Restrictions => self.draw_restrictions(batch), View::GameRules => { if let Some(rules) = o.rules.as_mut() { - rules.draw(batch, &self.res.atlas, self.cursor); + rules.draw(batch, &self.atlas, self.cursor); } } } @@ -510,7 +510,7 @@ impl Game<'_> { } fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); // Screen.extractTransparentBackground. batch.fill_gradient( @@ -552,7 +552,7 @@ impl Game<'_> { } fn draw_restrictions(&self, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("restrictions_screen.title", &[]); @@ -583,7 +583,7 @@ impl Game<'_> { } fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); o.scroll = o.scroll.clamp(0.0, WorldOptions::max_scroll(h)); // extractMenuBackground: the in-world background, the list @@ -701,7 +701,7 @@ impl Game<'_> { match o.view { View::Options => {} View::GameRules => { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let exit = o.rules.as_mut().and_then(|rules| { if rules.clicks_button(atlas, self.cursor, (w, h)) { self.audio.play_button_click(); @@ -715,7 +715,7 @@ impl Game<'_> { return; } View::LockQuestion => { - let p = Popup::lock_question(&self.res.atlas.font, o.difficulty, (w, h)); + let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h)); let hit = p .buttons .iter() @@ -733,8 +733,7 @@ impl Game<'_> { return; } View::Restrictions => { - let r = - Restrictions::new(&self.res.atlas.font, self.settings.chat_visibility, (w, h)); + let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h)); let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1; let action = r.action.is_some_and(|(ax, ay)| { in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0) diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index c9e3627e3..3b8fc29c4 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -283,7 +283,7 @@ impl Game<'_> { } /// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots. pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let white = atlas.font.white(); let uv = [ [white.u0, white.v1], diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 25a8325a8..834925c57 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -174,7 +174,7 @@ impl Game<'_> { if below.sturdy_full >> 1 & 1 == 0 { continue; } - if let Some(fire) = self.res.assets.registry.default_state(name) { + if let Some(fire) = self.pack.assets.registry.default_state(name) { let _ = self.level_set(p, fire); } } @@ -239,7 +239,7 @@ impl Game<'_> { if !self.res.facts.get(state).name.ends_with("lightning_rod") { return; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; if let Some(mut s) = registry.state(state).cloned() { s.properties.insert("powered".into(), "true".into()); if let Some(powered) = registry.id(&s) { @@ -348,7 +348,7 @@ impl Game<'_> { /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8 /// segments of 16 blocks, from the bolt's seed. pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let uv = [white.u0, white.v0]; // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index c0827b9a6..541e4e6a9 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -198,8 +198,8 @@ impl Game<'_> { .map(|l| (banners.banner_texture(&l.pattern), l.color.to_string())) .collect(); horizon_client::item_render::gui::draw_banner_result( - &self.res.item_renderer, - &self.res.atlas.sprites, + &self.pack.item_renderer, + &self.atlas.sprites, batch, x, y, @@ -217,7 +217,7 @@ impl Game<'_> { draws: &[ScreenDraw], background: bool, ) -> Option> { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let mut tooltip = None; let mut sheet: Option = None; for d in draws { diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 1afc5638a..0d334d248 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -363,7 +363,7 @@ impl Game<'_> { world: &self.world, behaviours: &self.res.behaviours, items: &self.res.items, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, brewing: Some(&self.res.stations.brewing), bone_meal: bone_meal(), } @@ -500,7 +500,7 @@ impl Game<'_> { /// Every hopper's `pushItemsTick`, in a stable position order. pub(super) fn tick_hoppers(&mut self) -> Result<()> { let hopper = self - .res + .pack .assets .registry .default_state("minecraft:hopper") @@ -833,7 +833,7 @@ impl Game<'_> { let Some(screen) = self.machine_screen() else { return false; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let key_is_cart = self .container .is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y); diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index bd103bdfc..11ca70d5d 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -33,7 +33,7 @@ fn recipe_matches(condition: &Value, id: &str) -> bool { impl Game<'_> { /// `Level.setBlock` of one boolean property of the block at `pos`. fn set_bool_prop(&mut self, pos: Pos, key: &str, value: bool, flags: i32) { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let old = self.world.block(pos.0, pos.1, pos.2); let Some(mut state) = registry.state(old).cloned() else { return; @@ -254,7 +254,7 @@ impl Game<'_> { // The background goes first, then the labels, then the slot decorations. let (background, rest) = draws.split_at(2.min(draws.len())); self.paint_screen(batch, ox, oy, background, true); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index e2d4617fc..2d7639260 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -789,7 +789,6 @@ impl Game<'_> { } let slot = self.maps.slots.last()?.1; let rect = self - .res .atlas .sprites .get(&format!("horizon/map{slot}")) @@ -798,7 +797,7 @@ impl Game<'_> { if m.texture_dirty { m.texture_dirty = false; let rgba: Vec = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect(); - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -856,7 +855,7 @@ impl Game<'_> { .map(|m| m.decorations.clone()) .unwrap_or_default(); for (i, d) in decorations.iter().enumerate() { - let Some(s) = self.res.atlas.sprites.get(d.sprite).copied() else { + let Some(s) = self.atlas.sprites.get(d.sprite).copied() else { continue; }; let dm = glam::Mat4::from_translation(glam::Vec3::new( @@ -932,7 +931,7 @@ impl Game<'_> { } else { "map/map_background" }; - if let Some(r) = self.res.atlas.sprites.get(background).copied() { + if let Some(r) = self.atlas.sprites.get(background).copied() { for (c, uv) in [ ([-7.0, 135.0, 0.0], [r.u0, r.v1]), ([135.0, 135.0, 0.0], [r.u1, r.v1]), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index fe9008cd7..de42c4907 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -221,7 +221,7 @@ impl Game<'_> { ) { return None; } - let s = self.res.assets.registry.state(state)?; + let s = self.pack.assets.registry.state(state)?; let shape = Shape::parse(s.properties.get("shape").map_or("", String::as_str)); let powered = s.properties.get("powered").is_some_and(|v| v == "true"); Some(Rail { @@ -1148,16 +1148,16 @@ impl Game<'_> { light: u32, out: &mut Vec, ) { - let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else { + let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else { return; }; for (_, model) in &models { for face in &model.faces { let Some(s) = self - .res + .pack .layer_names .get(&face.layer) - .and_then(|n| self.res.atlas.sprites.get(n)) + .and_then(|n| self.atlas.sprites.get(n)) else { continue; }; @@ -1185,7 +1185,7 @@ impl Game<'_> { } } fn display_state(&self, c: &Minecart) -> Option { - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let with = |name: &str, props: &[(&str, &str)]| { let mut s = registry.state(registry.default_state(name)?)?.clone(); for (k, v) in props { @@ -1218,7 +1218,6 @@ impl Game<'_> { continue; }; let Some(uv) = self - .res .atlas .sprites .get("entity/minecart/minecart") @@ -1325,12 +1324,12 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.res.atlas.sprites, + sprites: &self.atlas.sprites, nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), - glyph: &|c| self.res.atlas.glyph_cell(c), + glyph: &|c| self.atlas.glyph_cell(c), }; self.res .block_entity_render diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 3506e6c84..c2246cf5b 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -78,7 +78,7 @@ impl Game<'_> { let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else { return; }; - let Some(r) = self.res.atlas.sprites.get("entity/guardian_elder").copied() else { + let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else { return; }; let age = (APPARITION_TICKS - left) as f32 + alpha as f32; @@ -147,7 +147,7 @@ impl Game<'_> { return; }; let m = banner_matrix(head); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); // BannerRenderer: the flag sways with a per-banner phase. let phase = @@ -187,7 +187,7 @@ impl Game<'_> { ) { for (corners, shade, side) in FACES { let name = cube.sprites[usize::from(side)]; - let Some(r) = self.res.atlas.sprites.get(name).copied() else { + let Some(r) = self.atlas.sprites.get(name).copied() else { continue; }; let tint = if side == 0 { cube.tint } else { 0xFF_FFFF }; diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 56cb1d0d8..e98f13bd8 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -230,7 +230,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.res.atlas, line, None, self.ticks, focused); + .add(&self.atlas, line, None, self.ticks, focused); } } /// The mods' HUD panels, stacked with the extras in their corners. @@ -251,7 +251,7 @@ impl Game<'_> { .iter() .map(|l| (l.text.as_str(), l.color)) .collect(); - extras_hud::draw_lines(batch, &self.res.atlas, corners, corner, &lines); + extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines); } } } diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 8f70f6754..55e9dde11 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -283,7 +283,7 @@ impl Game<'_> { let Some(open) = self.mount_menu.open.as_ref() else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.sprite_region( atlas, "gui/container/horse", @@ -376,7 +376,7 @@ impl Game<'_> { m.hurt_time = 0; m.death_time = 0; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 7e8923f23..869364176 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -457,7 +457,7 @@ impl Game<'_> { return (0, false); }; let m = &self.mobs[i]; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 43607ab44..381af21cf 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -122,7 +122,7 @@ impl Game<'_> { f64::from(p.dimensions.width / 2.0), f64::from(p.dimensions.height), ); - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let facts = &self.res.facts; let bubble_column = horizon_client::ambience::bubble_column_in( [ diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 1d03da48f..368c5c0f2 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -218,7 +218,7 @@ impl Game<'_> { let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - let white = self.res.atlas.font.white(); + let white = self.atlas.font.white(); let away = forward.as_vec3() * 0.002; for (text, lift) in lines { let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3(); @@ -240,7 +240,7 @@ impl Game<'_> { .collect(); let width: f32 = chars .iter() - .map(|(c, _)| self.res.atlas.glyph(*c).map_or(6.0, |g| g.1)) + .map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1)) .sum(); let x0 = -(width / 2.0).trunc(); let y0 = if text.plain() == "deadmau5" { @@ -278,7 +278,7 @@ impl Game<'_> { } let mut x = x0; for (ch, color) in chars { - let Some((g, advance)) = self.res.atlas.glyph(ch) else { + let Some((g, advance)) = self.atlas.glyph(ch) else { x += 6.0; continue; }; diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index 829f1e6ab..01a657b0b 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -161,7 +161,7 @@ impl Game<'_> { Some(c) => &**c, None => match self .save - .load(x, z, self.res.assets.registry, &self.res.biomes) + .load(x, z, self.pack.assets.registry, &self.res.biomes) { Some(c) => { saved = c; @@ -390,7 +390,7 @@ impl Game<'_> { self.capture(true); } } - if self.res.screen_fx.portal == 0.0 { + if self.screen_fx.portal == 0.0 { let pitch = self.world.random.next_float() * 0.4 + 0.8; self.audio .play("minecraft:block.portal.trigger", None, 0.25, pitch); diff --git a/crates/horizon-client/src/game/ominous_item_spawner.rs b/crates/horizon-client/src/game/ominous_item_spawner.rs index 10c4f372f..1470a3124 100644 --- a/crates/horizon-client/src/game/ominous_item_spawner.rs +++ b/crates/horizon-client/src/game/ominous_item_spawner.rs @@ -160,7 +160,7 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::splat(scale)) * glam::Mat4::from_rotation_y(spin.to_radians()); let seed = - i64::from(self.res.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage); + i64::from(self.pack.item_renderer.item_id(&s.item.item)) + i64::from(s.item.damage); for copy in item_render::cluster_poses( &state, pose, diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index b83920e64..25eb6eb96 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -100,7 +100,7 @@ impl Game<'_> { } pub(super) fn draw_options(&mut self, batch: &mut HudBatch) { let mut ui = std::mem::take(&mut self.ui.options); - ui.draw(&self.settings, batch, &self.res.atlas, self.cursor); + ui.draw(&self.settings, batch, &self.atlas, self.cursor); self.ui.options = ui; } pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { @@ -122,7 +122,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.res.atlas, + &self.atlas, self.cursor.0, self.cursor.1, size, @@ -141,7 +141,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.res.atlas, + &self.atlas, self.cursor.0, self.cursor.1, size, @@ -154,7 +154,7 @@ impl Game<'_> { } pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> { let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.key(&mut self.settings, &self.res.atlas, key, text); + let events = ui.key(&mut self.settings, &self.atlas, key, text); self.ui.options = ui; self.handle_option_events(events) } @@ -165,7 +165,7 @@ impl Game<'_> { ) -> bool { self.ui .options - .shortcut(&self.res.atlas, shortcut, &mut self.clipboard) + .shortcut(&self.atlas, shortcut, &mut self.clipboard) } pub(super) fn options_scroll(&mut self, amount: f32) { let size = self.gui_size(); @@ -226,7 +226,7 @@ impl Game<'_> { pub(super) fn load_language(&mut self, code: &str) { let root = self.options.resources.clone(); lang::set(lang::Language::load(&[&root], code)); - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { @@ -256,14 +256,14 @@ impl Game<'_> { }; self.ui.chat.options = chat; if rescale { - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } - let font = &mut self.res.atlas.font; + let font = &mut self.atlas.font; if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs { font.uniform = s.force_unicode; font.japanese = s.japanese_glyphs; font.reset_cache(); - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); } // A new renderer (resource reload, first window) takes the loaded pack. let stale = self diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 2e977ddc9..4a80bee48 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -110,44 +110,30 @@ impl Game<'_> { } } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let assets = std::sync::Arc::new(self.res.assets.reload(root)?); + let assets = std::sync::Arc::new(self.pack.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; - let panorama = horizon_client::gfx::panorama::Faces::load(root); atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; - let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( + let pack = super::PackResources::load( root, - assets.model_library.clone(), - )?; - let visibility = horizon_client::models::load_visibility(root, assets.registry)?; - let tables = std::sync::Arc::new(horizon_client::mesher::MeshTables::new( - &assets, + assets, &self.res.facts, - visibility, - )?); + self.pack.context.biomes.clone(), + self.pack.context.light.clone(), + )?; // Everything loaded: switch over. self.random_tick_sections.clear(); self.options.resources = root.to_path_buf(); - let context = std::sync::Arc::new(horizon_client::streaming::WorkerContext { - assets: assets.clone(), - tables, - biomes: self.res.context.biomes.clone(), - light: self.res.context.light.clone(), - }); - self.res.layer_names = assets - .sprite_layers - .iter() - .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) - .collect(); - self.res.assets = assets; - self.res.context = context.clone(); - self.res.atlas = atlas; - self.res.panorama = panorama; - self.res.item_renderer = std::sync::Arc::new(item_renderer); - self.res.clouds = super::load_clouds(root); - self.res.forcefield = super::load_forcefield(root); - self.res.names = super::Names::load(root); - self.res.mob_data.villager_hats = + let context = pack.context.clone(); + self.pack = pack; + self.atlas = atlas; + // Villager hats come from the pack's texture metadata (shared data, swapped in place). + *self + .res + .mob_data + .villager_hats + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = horizon_client::mobs::villager_hats::VillagerHats::load(root); horizon_client::ui::load_metadata(root); lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); @@ -161,7 +147,7 @@ impl Game<'_> { self.renderer = Some(self.new_renderer(window)?); self.apply_ui_settings(); } - self.ui.chat.rescale(&self.res.atlas); + self.ui.chat.rescale(&self.atlas); Ok(()) } } diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index e80aa2b32..8f34d2b3a 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -942,7 +942,7 @@ impl Game<'_> { } else if self.screen == Screen::Options { let result = match text { Some(t) => { - self.ui.options.type_text(&self.res.atlas, t); + self.ui.options.type_text(&self.atlas, t); Ok(()) } None => self.options_key(key.expect("a key"), None), @@ -987,7 +987,7 @@ impl Game<'_> { .is_some_and(|f| f.center().1 > batch.height / 2.0) || self.screen == Screen::Chat || self.remote_chat_open(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); return; @@ -1002,7 +1002,7 @@ impl Game<'_> { return; } // An arrow, outlined, pointing up-left at (x, y). - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (x, y) = (x.floor(), y.floor()); const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1]; for (i, &w) in ROWS.iter().enumerate() { @@ -1047,7 +1047,7 @@ impl Game<'_> { }; if horizon { use horizon_client::ui_theme::{self as theme, Ui, color}; - let mut ui = Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = Ui::new(&self.atlas, batch, self.cursor); let k = ui.batch.scale / ui.density; let (x, y, w, h) = (x * k, y * k, w * k, h * k); let radius = match focus.kind { @@ -1070,7 +1070,7 @@ impl Game<'_> { return; } if matches!(focus.kind, Kind::Row | Kind::Field) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let white = rgba(255, 255, 255, 255); batch.fill(atlas, x, y, w, 1.0, white); batch.fill(atlas, x, y + h - 1.0, w, 1.0, white); diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 06bb7f6d0..2e5542ccc 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -249,7 +249,7 @@ impl Game<'_> { /// PaintingRenderer: the variant on the front, the back texture behind and /// on the edges. pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.res.atlas.sprites; + let sprites = &self.atlas.sprites; let Some(back) = sprites.get("painting/back").copied() else { return; }; diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 054f2c2fc..12ba759b4 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -506,7 +506,7 @@ impl Game<'_> { } /// `BlockState.CODEC`: a block name or `{id, properties}` (or legacy `{Name, Properties}`). fn state_from_nbt(&self, tag: &Tag) -> Option { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let state = match tag.get("Name") { Some(Tag::String(name)) => BlockState { name: name.to_string_lossy(), @@ -528,7 +528,7 @@ impl Game<'_> { .or_else(|| registry.default_state(&state.name)) } pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; match registry.state(state) { Some(s) if registry.default_state(&s.name) == Some(state) => { Tag::String(s.name.as_str().into()) diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index ff500a08f..a66ca487d 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -203,7 +203,12 @@ impl Game<'_> { let p = self.player.as_ref()?; let sleeping = self.sleeping.map(|(head, _)| { let state = self.world.block(head[0], head[1], head[2]); - let props = self.res.assets.registry.state(state).map(|s| &s.properties); + let props = self + .pack + .assets + .registry + .state(state) + .map(|s| &s.properties); // BedBlock.getBedOrientation as Direction.toYRot. props.and_then(|props| match props.get("facing").map(String::as_str) { Some("south") => Some(0.0), @@ -405,7 +410,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); horizon_client::mobs::render::render_with( m, @@ -459,7 +464,7 @@ impl Game<'_> { m.position.y += 0.125 * f64::from(u8::from(m.extra.crouching)); m.previous = m.position; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -530,10 +535,9 @@ impl Game<'_> { let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else { return; }; - let (Some(model), Some(rect)) = ( - assets.player.get("elytra"), - self.res.atlas.sprites.get(texture), - ) else { + let (Some(model), Some(rect)) = + (assets.player.get("elytra"), self.atlas.sprites.get(texture)) + else { return; }; let base = horizon_client::mobs::render::base_transform(m, partial, camera) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 826480bd6..fbc8556e7 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -576,7 +576,7 @@ impl Game<'_> { .map(hud_overlays::EffectIcon::from) .collect(); let draws = hud_overlays::effects(batch.width as i32, false, &icons); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// `EffectsInInventory`: panels to the right of survival/creative inventory. pub(super) fn draw_inventory_effects( @@ -591,12 +591,12 @@ impl Game<'_> { image_width, &self.potions.effects.list, self.clock.rate(), - &|key| self.res.names.get(key).map(str::to_owned), - &|text| self.res.atlas.font.width(text).ceil() as i32, + &|key| self.pack.names.get(key).map(str::to_owned), + &|text| self.atlas.font.width(text).ceil() as i32, ); if let Some(lines) = inventory_effects::paint( batch, - &self.res.atlas, + &self.atlas, &panels, [self.cursor.0 as i32, self.cursor.1 as i32], ) { diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 9e73d790c..63f45c1c5 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -976,7 +976,7 @@ impl Game<'_> { } let bed = *known.entry(state.0).or_insert_with(|| { self.res.facts.get(state).name.ends_with("_bed") - && self.res.assets.registry.state(state).is_some_and(|s| { + && self.pack.assets.registry.state(state).is_some_and(|s| { s.properties.get("part").map(String::as_str) == Some("head") }) }); diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index edede6f0f..67fc46b68 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -467,7 +467,7 @@ impl Game<'_> { horizon_client::item_tooltip::lines( stack, self.res.items.get(&stack.item), - &|k| self.res.names.get(k).map(str::to_owned), + &|k| self.pack.names.get(k).map(str::to_owned), ) }) { @@ -629,7 +629,7 @@ impl Game<'_> { search.focused = true; search.reset_blink(); if !magnifier { - let idx = search.index_at(&self.res.atlas, cursor.0); + let idx = search.index_at(&self.atlas, cursor.0); search.set_cursor(idx, false); } return true; @@ -871,7 +871,7 @@ impl Game<'_> { let (bx, by) = self.book_button_pos(book_type, ox, batch); let hover = inside(cursor, bx, by, 20.0, 18.0); batch.sprite( - &self.res.atlas, + &self.atlas, &sprite(if hover { "button_highlighted" } else { @@ -919,7 +919,7 @@ impl Game<'_> { fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) { let (xo, yo) = self.book_origin(batch); let cursor = self.cursor; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let search = match self.recipe_ui.search.as_mut() { Some(edit) => { // The box's place, for clicks and typing. @@ -1042,7 +1042,7 @@ impl Game<'_> { let mut tooltip: Option> = None; for d in calls { let start = batch.vertices.len(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; match &d.call { Call::Blit { x, y, w, h, u, v, .. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a7b1c4410..7bc41d703 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -169,7 +169,7 @@ impl Game<'_> { let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), - self.res.context.clone(), + self.pack.context.clone(), self.res.threads, ); streaming.remote = true; @@ -278,7 +278,7 @@ impl Game<'_> { self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); - self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); + self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -465,7 +465,7 @@ impl Game<'_> { if !same { let mut streaming = Streaming::new( Arc::new(NoTerrain), - self.res.context.clone(), + self.pack.context.clone(), self.res.threads, ); streaming.remote = true; @@ -1545,11 +1545,10 @@ impl Game<'_> { self.skin_slots.len() } else { let (old, slot) = self.skin_slots.remove(0); - self.res.atlas.sprites.remove(&old); + self.atlas.sprites.remove(&old); slot }; let Some(rect) = self - .res .atlas .sprites .get(&format!("horizon/skin{slot}")) @@ -1557,7 +1556,7 @@ impl Game<'_> { else { return; }; - let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32); + let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -1565,7 +1564,7 @@ impl Game<'_> { height: 64, rgba, }); - self.res.atlas.sprites.insert(location.clone(), rect); + self.atlas.sprites.insert(location.clone(), rect); self.skin_slots.push((location, slot)); } /// Whether a downloaded skin is in the atlas, marking it recently shown. @@ -1807,7 +1806,7 @@ impl Game<'_> { entities: &ghast_collisions, player, scene: &mut self.world, - assets: &self.res.assets, + assets: &self.pack.assets, collision_binding: self.collision, resources: self.motion, } @@ -2742,7 +2741,7 @@ impl Game<'_> { if self.player.is_some() { return false; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); let shown = horizon_client::net::shown_address(&r.session.address); @@ -2767,7 +2766,7 @@ impl Game<'_> { /// Chat (ChatComponent), the chat input line and the action bar. pub(super) fn remote_hud(&self, batch: &mut HudBatch) { let Some(r) = &self.remote else { return }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); let open = r.chat_input.is_some(); let now = Instant::now(); diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index d34b1d7ab..10add4668 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -25,7 +25,7 @@ impl Game<'_> { } else { format!("minecraft:{name}") }; - let registry = &self.res.assets.registry; + let registry = &self.pack.assets.registry; let default = registry .default_state(&name) .ok_or_else(|| format!("unknown block {name}"))?; diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index bc08df07c..4ee10e6d2 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -73,29 +73,33 @@ impl Game<'_> { } else { (0.0, 0.0) }; - self.res.fog.setup(&FogInputs { - fog_type, - sky, - water_fog_color: [ - (water >> 16 & 255) as f32 / 255.0, - (water >> 8 & 255) as f32 / 255.0, - (water & 255) as f32 / 255.0, - ], - biome, - render_distance_chunks: self.streaming.radius, - cloud_range_chunks: self.settings.cloud_range, - camera_y: camera.y, - // level.getMinY(): the Nether and the End start at y 0. - min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, - flat: false, - forward: forward.map(|c| c as f32), - rain, - thunder, - skybox: self.dim == Dim::Overworld, - blindness: None, - darkness: self.darkness_fog(), - boss_world_fog: self.dragon_bar_shown(), - }) + horizon_client::fog::setup_fog( + &self.res.fog, + &self.fog, + &FogInputs { + fog_type, + sky, + water_fog_color: [ + (water >> 16 & 255) as f32 / 255.0, + (water >> 8 & 255) as f32 / 255.0, + (water & 255) as f32 / 255.0, + ], + biome, + render_distance_chunks: self.streaming.radius, + cloud_range_chunks: self.settings.cloud_range, + camera_y: camera.y, + // level.getMinY(): the Nether and the End start at y 0. + min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 }, + flat: false, + forward: forward.map(|c| c as f32), + rain, + thunder, + skybox: self.dim == Dim::Overworld, + blindness: None, + darkness: self.darkness_fog(), + boss_world_fog: self.dragon_bar_shown(), + }, + ) } /// What a shader pack's `Frame` uniform reads of the game this frame. pub(super) fn shader_inputs( @@ -181,7 +185,7 @@ impl Game<'_> { (in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); // Hud.extractCameraOverlays; the spyglass scope (and its easing) is // drawn on the HUD by draw_spyglass. - let fx = &self.res.screen_fx; + let fx = &self.screen_fx; let overlays = hud_overlays::CameraOverlays { vignette: self.settings.vignette.then_some(( fx.vignette_brightness, @@ -206,8 +210,8 @@ impl Game<'_> { let mut scope = self.scope_scale; let gui_overlays = hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); - self.res.screen_fx.build(&ScreenInputs { - sprites: &self.res.atlas.sprites, + self.screen_fx.build(&ScreenInputs { + sprites: &self.atlas.sprites, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, @@ -231,16 +235,16 @@ impl Game<'_> { lightmap_brightness(if self.dim == Dim::Nether { 0.1 } else { 0.0 }, raw) } pub(super) fn tick_particles(&mut self) { - self.res.fog.state.tick_flicker(); + self.fog.tick_flicker(); let eye = self.eye_position(); if let Some(e) = eye { let brightness = self.eye_brightness(e); let inside_portal = self.client_portal_effect(); - self.res.screen_fx.tick(brightness, inside_portal); + self.screen_fx.tick(brightness, inside_portal); // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. let in_water = fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water; - self.res.fog.state.tick(in_water); + self.fog.tick(in_water); let b = [ e[0].floor() as i32, e[1].floor() as i32, @@ -258,7 +262,7 @@ impl Game<'_> { .map_or(0, |c| c.biome(b[0], b[1], b[2])); let rains = self.res.biomes.get(biome).precipitation; update_rain_fog( - &mut self.res.fog.state, + &mut self.fog, rain, self.world.light(b[0], b[1], b[2]) >> 4, rains, @@ -287,7 +291,7 @@ impl Game<'_> { facts, collision: self.collision, biomes, - registry: self.res.assets.registry, + registry: self.pack.assets.registry, raining_at: &raining_at, }; if let Some(e) = eye { diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 834d1ad44..5a31dfd5c 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -66,7 +66,7 @@ impl Game<'_> { &*self.res.facts.get(state).name == "minecraft:respawn_anchor" } fn anchor_charges(&self, state: BlockStateId) -> i32 { - self.res + self.pack .assets .registry .state(state) @@ -75,9 +75,9 @@ impl Game<'_> { .unwrap_or(0) } fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option { - let mut s = self.res.assets.registry.state(state)?.clone(); + let mut s = self.pack.assets.registry.state(state)?.clone(); s.properties.insert("charges".into(), charges.to_string()); - self.res.assets.registry.resolve(&s).ok() + self.pack.assets.registry.resolve(&s).ok() } /// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute /// (only the Nether's dimension type sets it). @@ -243,7 +243,7 @@ impl Game<'_> { } // removeBlock(head), then the foot behind it if it is still this bed. let facing = self - .res + .pack .assets .registry .state(state) @@ -300,7 +300,7 @@ impl Game<'_> { let name = &self.res.facts.get(state).name; let open_trapdoor = name.ends_with("_trapdoor") && self - .res + .pack .assets .registry .state(state) @@ -337,7 +337,7 @@ impl Game<'_> { let name = &*self.res.facts.get(state).name; let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") && self - .res + .pack .assets .registry .state(state) diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 7bcb6ceed..16297e930 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -573,11 +573,11 @@ impl Game<'_> { batch.height as i32, board, objective, - &self.res.atlas.font, + &self.atlas.font, self.settings.text_background(0.3), self.settings.text_background(0.4), ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } @@ -639,8 +639,8 @@ impl Game<'_> { ), upside_down: &up, }; - let draws = self.tab_list.layout(&inputs, &self.res.atlas.font); - horizon_client::hud_layout::paint(batch, &self.res.atlas, &draws); + let draws = self.tab_list.layout(&inputs, &self.atlas.font); + horizon_client::hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 94891cd25..ac4d16274 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -78,12 +78,12 @@ impl Game<'_> { let (world, quit) = self.pause_labels(); self.tick_friends(); let friends = self.friends_view(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.res.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); horizon_client::front::pause::draw(&mut ui, &world, quit, opened, &friends); ui.finish(); return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("menu.game", &[]); @@ -135,7 +135,7 @@ impl Game<'_> { let mut b = HudBatch::new(size); let (world, quit) = self.pause_labels(); horizon_client::front::pause::click( - &self.res.atlas, + &self.atlas, &mut b, self.cursor.0, self.cursor.1, @@ -175,7 +175,7 @@ impl Game<'_> { } /// DeathScreen: gradient, the title at double size, the cause and score. pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); // fillGradient(0x60500000 -> 0xA0803030). let rows = h.ceil() as i32; diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index fb23cc498..6701181e7 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -262,7 +262,7 @@ impl Game<'_> { if self.sculk.tables.built { return; } - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let n = registry.len(); let tag = |name: &str| { self.res @@ -640,7 +640,7 @@ impl Game<'_> { self.state_property(state, "shrieking") == Some("true") } fn state_property(&self, state: BlockStateId, key: &str) -> Option<&str> { - self.res + self.pack .assets .registry .state(state) @@ -1156,7 +1156,7 @@ impl Game<'_> { let in_water = horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; - return self.res.fog.state.water_vision(in_water); + return self.fog.water_vision(in_water); } 0.0 } diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 0c12804ec..2ebdbcb2b 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -177,7 +177,7 @@ impl Game<'_> { Some((n, rest)) => (n, rest.trim_end_matches(']')), None => (text, ""), }; - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let base = registry .default_state(name) .ok_or_else(|| format!("unknown block {name}"))?; @@ -197,7 +197,7 @@ impl Game<'_> { /// `BlockStateParser.serialize`. fn fixture_state_text(&self, state: BlockStateId) -> String { - let Some(s) = self.res.assets.registry.state(state) else { + let Some(s) = self.pack.assets.registry.state(state) else { return "?".into(); }; if s.properties.is_empty() { diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index ab298007f..c0a780063 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -88,7 +88,7 @@ impl Game<'_> { return; }; let line = edit.line; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let width = |s: &str| HudBatch::text_width(atlas, s); let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return; @@ -130,7 +130,7 @@ impl Game<'_> { } else { &mut sign.back }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; self.text_selection.apply( sign_line_id(front, line), &mut text.lines[line], @@ -163,7 +163,7 @@ impl Game<'_> { let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return; }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); let title = if sign.hanging { diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index 3fcd30e8c..ba7bd66a1 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -399,7 +399,7 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for (key, (_, mob)) in &self.spawners.displays { let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index d8a5d1416..f16fa14af 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -398,7 +398,7 @@ impl Game<'_> { fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { Some(input) - if input.custom_name().is_none() && s.name == self.res.names.item(&input.item) => + if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) => { String::new() } @@ -429,7 +429,7 @@ impl Game<'_> { let name = self.anvil_item_name(&s); let hover = s.inputs[0] .as_ref() - .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .map(|i| stations::hover_name(&|id| self.pack.names.item(id), i)) .unwrap_or_default(); s.anvil = stations::anvil_result( &data.enchantments, @@ -1157,7 +1157,7 @@ impl Game<'_> { s.anvil_last = s.inputs[0].clone(); s.name = s.inputs[0] .as_ref() - .map(|i| stations::hover_name(&|id| self.res.names.item(id), i)) + .map(|i| stations::hover_name(&|id| self.pack.names.item(id), i)) .unwrap_or_default(); } self.station_changed(); @@ -1249,7 +1249,7 @@ impl Game<'_> { } /// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels. fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else { batch.text(atlas, text, x, y, color, false); return; @@ -1325,7 +1325,7 @@ impl Game<'_> { let local = (self.cursor.0 - ox, self.cursor.1 - oy); let mut tooltip: Option> = None; { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -1342,7 +1342,7 @@ impl Game<'_> { }; let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); - let atlas = &self.res.atlas; + let atlas = &self.atlas; Self::part( batch, atlas, @@ -1417,7 +1417,7 @@ impl Game<'_> { if self.slot_mut(i).is_none() { let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -1427,7 +1427,7 @@ impl Game<'_> { } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { let title = self.translate(kind.title_key(), ""); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; Self::part( batch, atlas, @@ -1446,7 +1446,7 @@ impl Game<'_> { if kind == Kind::Loom { tooltip = self.draw_loom(batch, ox, oy, local); } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); match kind { @@ -1552,7 +1552,7 @@ impl Game<'_> { ); -8323296 }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let cw = HudBatch::text_width(atlas, &cost_text); batch.text( atlas, @@ -1679,7 +1679,7 @@ impl Game<'_> { ) }; if let Some(line) = line { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let tw = HudBatch::text_width(atlas, &line); let tx = 176.0 - 8.0 - tw - 2.0; batch.fill( @@ -1788,7 +1788,7 @@ impl Game<'_> { "recipe" }; batch.sprite_scaled( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, @@ -1816,7 +1816,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, @@ -1889,16 +1889,16 @@ impl Game<'_> { { let key = brewing::potion_name_key(&stack.item, stack.potion()); e.translate(&key) - .map_or_else(|| self.res.names.item(&stack.item), str::to_owned) + .map_or_else(|| self.pack.names.item(&stack.item), str::to_owned) } else { - self.res.names.item(&stack.item) + self.pack.names.item(&stack.item) }; let mut lines = vec![(name, color)]; let translate = |k: &str| e.translate(k).map(str::to_owned); // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() - .map_or_else(|| self.res.names.item(&s.item), str::to_owned) + .map_or_else(|| self.pack.names.item(&s.item), str::to_owned) }; for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) { lines.push((line, u32::MAX)); @@ -2045,7 +2045,7 @@ impl Game<'_> { if lines.is_empty() { return; } - let atlas = &self.res.atlas; + let atlas = &self.atlas; let w = lines .iter() .map(|(t, _)| HudBatch::text_width(atlas, t)) @@ -2149,14 +2149,14 @@ impl Game<'_> { } if let Some(bottles) = out.bottles { let state = self.world.block(x, y, z); - if let Some(mut s) = self.res.assets.registry.state(state).cloned() + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() && AsRef::::as_ref(&s.name) == "minecraft:brewing_stand" { for (i, has) in bottles.iter().enumerate() { s.properties .insert(format!("has_bottle_{i}"), has.to_string()); } - if let Ok(id) = self.res.assets.registry.resolve(&s) { + if let Ok(id) = self.pack.assets.registry.resolve(&s) { self.world.set(x, y, z, id)?; } } diff --git a/crates/horizon-client/src/game/stats_screen.rs b/crates/horizon-client/src/game/stats_screen.rs index e7d618428..f023f30b7 100644 --- a/crates/horizon-client/src/game/stats_screen.rs +++ b/crates/horizon-client/src/game/stats_screen.rs @@ -216,7 +216,7 @@ impl Game<'_> { } pub(super) fn draw_stats(&mut self, batch: &mut HudBatch) { let (w, h) = (batch.width, batch.height); - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let (top, bottom) = (TAB_H, h - FOOTER); ui::separators(batch, atlas, top, bottom, true); @@ -327,13 +327,13 @@ impl Game<'_> { } let stack = ItemStack::new(item, 1); batch.sprite( - &self.res.atlas, + &self.atlas, "gui/sprites/container/slot", left + 1.0, y + 1.0, ); self.draw_item(batch, &stack, left + 2.0, y + 2.0); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let color = if (i + 1) % 2 == 0 { u32::MAX } else { @@ -394,7 +394,7 @@ impl Game<'_> { } } } - let atlas = &self.res.atlas; + let atlas = &self.atlas; ui::scrollbar( batch, atlas, @@ -407,7 +407,7 @@ impl Game<'_> { self.draw_stats_footer(batch, w, h); } fn draw_stats_footer(&self, batch: &mut HudBatch, w: f32, h: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index d3db63b72..44b62e276 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -76,7 +76,7 @@ impl Game<'_> { /// The other half of the open double chest and whether the open one is /// the right half (`ChestBlock.getConnectedDirection`). pub(super) fn chest_partner(&self, key: (i32, i32, i32)) -> Option<((i32, i32, i32), bool)> { - let registry = self.res.assets.registry; + let registry = self.pack.assets.registry; let state = registry.state(self.world.block(key.0, key.1, key.2))?; if !matches!( state.name.as_str(), @@ -211,7 +211,7 @@ impl Game<'_> { oy: f32, ) { use horizon_client::hud::rgba; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let grey = rgba(64, 64, 64, 255); if self .container_block() diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs index 94b0d3c86..cf89a4b15 100644 --- a/crates/horizon-client/src/game/subtitle_hud.rs +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -47,7 +47,7 @@ impl Game<'_> { width: batch.width as i32, height: batch.height as i32, }; - let atlas = &self.res.atlas; + let atlas = &self.atlas; let draws = self .subtitles .overlay diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 89e50c0d0..30abfc34d 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -15,10 +15,10 @@ impl Game<'_> { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); - let font = &self.res.atlas.font; + let font = &self.atlas.font; let mut draws = self.titles.overlay_message(w, h, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option { @@ -37,7 +37,7 @@ impl Game<'_> { Some(HeldName { item: stack.item.to_string(), hover_name: Text::literal( - custom.map_or_else(|| self.res.names.item(&stack.item), str::to_owned), + custom.map_or_else(|| self.pack.names.item(&stack.item), str::to_owned), ), rarity_color: match rarity.as_str() { "uncommon" => text::YELLOW, @@ -61,9 +61,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, can_hurt, - &self.res.atlas.font, + &self.atlas.font, self.settings.text_background(0.0), ); - hud_layout::paint(batch, &self.res.atlas, &draws); + hud_layout::paint(batch, &self.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 2a1404ace..78f107599 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -158,7 +158,7 @@ impl Game<'_> { t.tick( &self.world, self.collision, - &self.res.assets, + &self.pack.assets, &self.res.facts, )?; if t.fuse <= 0 { @@ -210,12 +210,12 @@ impl Game<'_> { if self.tnts.is_empty() { return; } - let Some(state) = self.res.assets.registry.default_state("minecraft:tnt") else { + let Some(state) = self.pack.assets.registry.default_state("minecraft:tnt") else { return; }; // Face sprites from the block model: up, down, north, south, west, east. let Ok(models) = self - .res + .pack .assets .model_catalog .collect(state, BlockPos::new(0, 0, 0)) @@ -235,10 +235,10 @@ impl Game<'_> { }; if sprites[index].is_none() { sprites[index] = self - .res + .pack .layer_names .get(&face.layer) - .and_then(|name| self.res.atlas.sprites.get(name).copied()); + .and_then(|name| self.atlas.sprites.get(name).copied()); } } for t in &self.tnts { diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index 9950a86f2..ce389ac84 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -548,7 +548,7 @@ impl Game<'_> { ); let offers = m.session.offers.clone(); let costs: Vec = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -687,7 +687,7 @@ impl Game<'_> { } else { "gui/sprites/widget/button" }; - batch.sprite_scaled(&self.res.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); + batch.sprite_scaled(&self.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; let base = offer.base_cost_a.stack.clone(); let cost_a = costs[index].clone(); @@ -705,7 +705,7 @@ impl Game<'_> { x, y, ); - let atlas = &self.res.atlas; + let atlas = &self.atlas; let t = base.count.to_string(); batch.text( atlas, @@ -740,7 +740,7 @@ impl Game<'_> { "trade_arrow" }; batch.sprite( - &self.res.atlas, + &self.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0, @@ -770,7 +770,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.res.atlas, + &self.atlas, ox + sx, oy + sy, 16.0, diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs index 5f5289a5b..4107e0859 100644 --- a/crates/horizon-client/src/game/trial_spawner.rs +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -138,7 +138,7 @@ impl Game<'_> { /// The trial spawner block at `key`: its state and ominous flag. pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> { let block = self - .res + .pack .assets .registry .state(self.world.block(key.0, key.1, key.2))?; @@ -292,7 +292,7 @@ impl Game<'_> { ominous: bool, ) -> Result<()> { let current = self.world.block(key.0, key.1, key.2); - let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + let Some(mut block) = self.pack.assets.registry.state(current).cloned() else { return Ok(()); }; block @@ -301,7 +301,7 @@ impl Game<'_> { block .properties .insert("ominous".into(), ominous.to_string()); - let id = self.res.assets.registry.resolve(&block)?; + let id = self.pack.assets.registry.resolve(&block)?; self.level_set([key.0, key.1, key.2], id) } /// `transformBadOmenIntoTrialOmen`: Bad Omen becomes Trial Omen, 15 diff --git a/crates/horizon-client/src/game/trial_visuals.rs b/crates/horizon-client/src/game/trial_visuals.rs index 062c61521..d32957fe1 100644 --- a/crates/horizon-client/src/game/trial_visuals.rs +++ b/crates/horizon-client/src/game/trial_visuals.rs @@ -293,7 +293,7 @@ impl Game<'_> { p.position.z, ]; let facing = self - .res + .pack .assets .registry .state(self.world.block(pos[0], pos[1], pos[2])) diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 179ade374..8c372fa46 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -343,7 +343,6 @@ impl Game<'_> { return; }; let Some(uv) = self - .res .atlas .sprites .get("entity/trident/trident") diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index af81de5ad..dc87a13bf 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -331,7 +331,7 @@ impl Game<'_> { /// The sort buttons: a bordered square with three bars, lighter under /// the cursor. pub(super) fn draw_sort_buttons(&self, batch: &mut HudBatch, ox: f32, oy: f32) { - let atlas = &self.res.atlas; + let atlas = &self.atlas; for ((x, y), _) in self.sort_buttons() { let (x, y) = (ox + x, oy + y); let (cx, cy) = self.cursor; @@ -401,7 +401,7 @@ impl Game<'_> { } let views: Vec> = slots.iter().map(|&s| self.slot_view(s)).collect(); let clicks = { - let names = |id: &str| self.res.names.item(id); + let names = |id: &str| self.pack.names.item(id); let rank = |s: &ItemStack| { let order = self.creative_screen.order_of(s).unwrap_or(usize::MAX); (order, hover_name(&names, s)) diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index dca31ddab..31d7d3ea3 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -51,7 +51,7 @@ impl Game<'_> { /// The vault at `key` with its block's state and ominous flag. pub(super) fn take_vault(&mut self, key: Pos) -> Option<(Box, VaultState, bool)> { let state = self.world.block(key.0, key.1, key.2); - let block = self.res.assets.registry.state(state)?; + let block = self.pack.assets.registry.state(state)?; if block.name != "minecraft:vault" { return None; } @@ -200,13 +200,13 @@ impl Game<'_> { /// `setBlockAndUpdate` with the new `vault_state`. fn set_vault_state(&mut self, key: Pos, state: VaultState) -> Result<()> { let current = self.world.block(key.0, key.1, key.2); - let Some(mut block) = self.res.assets.registry.state(current).cloned() else { + let Some(mut block) = self.pack.assets.registry.state(current).cloned() else { return Ok(()); }; block .properties .insert("vault_state".into(), state.name().into()); - let id = self.res.assets.registry.resolve(&block)?; + let id = self.pack.assets.registry.resolve(&block)?; self.level_set([key.0, key.1, key.2], id) } /// `VaultRenderer`: the display item of every vault near the camera that @@ -233,7 +233,7 @@ impl Game<'_> { ) * glam::Mat4::from_rotation_y(vault.display_spin(alpha as f32).to_radians()); let light = self.world.light(key.0, key.1, key.2); let seed = - i64::from(self.res.item_renderer.item_id(&stack.item)) + i64::from(stack.damage); + i64::from(self.pack.item_renderer.item_id(&stack.item)) + i64::from(stack.damage); for copy in item_render::cluster_poses( &state, pose, diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 9dae29564..07759944f 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -404,7 +404,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let name = self.res.facts.get(state).name.clone(); let prop = |game: &Self, key: &str| { - game.res + game.pack .assets .registry .state(state) @@ -478,7 +478,6 @@ impl Game<'_> { }); let Some(model) = model else { return }; let Some(r) = self - .res .atlas .sprites .get("entity/projectiles/wind_charge") diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index bc7ae5f49..539a85c66 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -46,7 +46,8 @@ pub struct MobData { /// Each entity type's `SpawnPlacements.getHeightmapType`. pub heightmaps: HashMap, pub animations: HashMap, - pub villager_hats: super::villager_hats::VillagerHats, + /// Replaced when the resource packs change (the rest of `MobData` never is). + pub villager_hats: std::sync::RwLock, /// Biome tags (spawns_warm_variant_farm_animals, is_ocean...) by tag id. pub biome_tags: HashMap>, /// Entity type tags (`data/*/tags/entity_type`). @@ -72,7 +73,7 @@ impl MobData { }; data.biome_tags = crate::items::load_tags(root, "worldgen/biome").unwrap_or_default(); data.entity_tags = crate::items::load_tags(root, "entity_type").unwrap_or_default(); - data.villager_hats = super::villager_hats::VillagerHats::load(root); + data.villager_hats = std::sync::RwLock::new(super::villager_hats::VillagerHats::load(root)); data } /// Only the keyframe animation definitions of `mob-data.json`. diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index 46505ec9d..4c312e5fd 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1067,6 +1067,8 @@ fn render_visible( let variant = variant.strip_prefix("baby/").unwrap_or(variant); let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; data.villager_hats + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) .apply(folder, variant, profession, &mut poses); } let light = if layer.full_bright { From c2f4ecc188d8fa49909550c4ab61eef85e75be7e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:04:10 +0200 Subject: [PATCH 19/23] Build the game in Game::new instead of inside run() run() loads the shared resources and the pack, then hands them to a constructor that builds a game with no world open. The same constructor will build an integrated server's game on its own thread. The struct literal moves unchanged; Options derives Clone so a server can start from the client's. No behaviour change. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 621 +++++++++++++++--------------- 1 file changed, 319 insertions(+), 302 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c7fc7f1c7..34af3318d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -203,6 +203,7 @@ use winit::{ window::{CursorGrabMode, Window, WindowId}, }; +#[derive(Clone)] struct Options { resources: PathBuf, distance: i32, @@ -9779,6 +9780,323 @@ fn load_forcefield(root: &std::path::Path) -> (u32, u32, Vec) { .filter(|(w, h, _)| w == h && w.is_power_of_two()) .unwrap_or((1, 1, vec![0; 4])) } +impl<'a> Game<'a> { + /// A game with no world open, over the loaded resources: the window's, + /// or an integrated server's on its own thread. + fn new( + res: &'a Arc, + pack: PackResources, + atlas: HudAtlas, + options: Options, + settings: Settings, + audio: Audio, + ) -> Result { + let root = options.resources.clone(); + let registry = pack.assets.registry; + // Until a world is opened the streamer is idle. + let mut streaming = Streaming::new( + Arc::new(TestTerrain::new(registry, &res.biomes)?), + pack.context.clone(), + 1, + ); + streaming.paused = true; + let level = Level::default(); + let save = Arc::new(SaveDir::new( + std::env::current_dir()? + .join("saves") + .join(".horizon-title"), + )); + // These batches share the exported document instead of reparsing it per layer. + let (armor_stand_assets, boat_models, cart_models) = { + let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); + ( + armor_stands::ArmorStandAssets::load(&root, document.as_ref()), + boats::BoatModels::load(document.as_ref()), + minecarts::CartModels::load(document.as_ref()), + ) + }; + let world = World::new(res.facts.air, 0); + let creative = options.creative; + let inventory = vec![None; 36]; + let now = Instant::now(); + let look = options.look; + let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); + Ok(Game { + res: res.clone(), + collision: &res.collision, + motion: &res.motion, + pack, + atlas, + fog: Default::default(), + screen_fx: Default::default(), + world, + streaming, + options, + player: None, + spawn: None, + clock: FixedStep::default(), + previous_position: Vec3::ZERO, + eye: 1.62, + previous_eye: 1.62, + yaw: look.map_or(level.rotation[0], |l| l.0), + pitch: look.map_or(level.rotation[1], |l| l.1), + inventory, + selected: 0, + carried: None, + craft_grid: vec![None; 9], + craft_size: 2, + inv_drag: None, + tweaks: Default::default(), + inv_clicks: Default::default(), + last_inv_click: None, + last_quick_moved: None, + container: None, + station: None, + potions: Default::default(), + scratch_slot: None, + mining: None, + destroy_delay: 0, + use_delay: 0, + creative, + mode: if creative { + horizon_client::command::args::GameMode::Creative + } else { + horizon_client::command::args::GameMode::Survival + }, + keys: HashSet::new(), + physical_keys: HashSet::new(), + left: false, + right: false, + cursor: (0.0, 0.0), + captured: false, + focused: true, + modifiers: winit::keyboard::ModifiersState::empty(), + fullscreen: horizon_client::window::FullscreenState::new(false), + shader_packs: Default::default(), + mouse: MouseLook::default(), + agent_pointer: false, + smooth_camera: false, + toggles: Default::default(), + was_playing: false, + pause: false, + debug: false, + screen: Screen::Playing, + window: None, + renderer: None, + entity_vertices: Vec::new(), + see_through_vertices: Vec::new(), + health_hud: hud_layout::HealthHud::default(), + started: now, + previous: now, + last_input: now, + pad: Default::default(), + frames: 0, + world_frames: 0, + fps: 0.0, + fps_frames: 0, + fps_at: now, + ticks: 0, + error: None, + message: None, + save, + level, + session_lock: None, + audio, + music: Default::default(), + ambience: Default::default(), + sound_paused: false, + cart_sounds: HashSet::new(), + riding_cart_sounds: None, + dropped: Vec::new(), + next_entity: 0, + particles, + pickups: Default::default(), + sign_edit: None, + book: None, + lectern_pulses: Vec::new(), + loading_progress: 0.0, + spawn_origin: None, + spawn_spiral: Default::default(), + player_spawn: None, + mobs: Vec::new(), + creatures: Default::default(), + sculk: Default::default(), + raiding: Default::default(), + attack_ticks: 100, + last_hurt_by_player: HashSet::new(), + died: HashSet::new(), + be_anims: { + let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); + anims.classify(registry); + anims + }, + using: None, + view: Default::default(), + limiter: horizon_client::window::FramerateLimiter::new(0), + frame_clock: Default::default(), + scope_scale: 0.5, + frame_ticks: 0.0, + title: None, + armor: [None, None, None, None], + offhand: None, + hand: Hand::Main, + shield_cooldown: 0, + command_source: None, + titles: Default::default(), + tool_highlight: Default::default(), + applied_modifiers: Vec::new(), + experience: Experience::default(), + orbs: Vec::new(), + xp_delay: 0, + last_level_up: 0, + swing: Default::default(), + swings_started: 0, + heights: Default::default(), + sway: Default::default(), + visible_hands: [(0, None), (0, None)], + clicks: Default::default(), + attack_clicks: 0, + hand_strength: Default::default(), + settings, + options_from_title: false, + backdrop: Default::default(), + pause_since: None, + dragging: false, + avatar: Default::default(), + flash: 0, + sleeping: None, + dim: Dim::Overworld, + world_root: PathBuf::new(), + travelling: None, + portals: Default::default(), + end_travel: false, + respawn_config: None, + respawn_travel: None, + end_portal_travel: false, + end: Default::default(), + block_ticks: Ticks::new(0), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + painting_variants: paintings::PaintingVariants::load(&root), + item_frames: Vec::new(), + frame_model: frames::bake_frame(&root, "item_frame"), + glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), + map_frame_model: frames::bake_frame(&root, "item_frame_map"), + glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), + armor_stands: Vec::new(), + others: Vec::new(), + armor_stand_assets, + boats: Vec::new(), + boat_models, + crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + maps: maps::Maps::default(), + fight: dragon::Fight::default(), + dragon: None, + crystals: Vec::new(), + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), + map_patches: Vec::new(), + skin_downloads: horizon_client::skins::Downloader::new( + std::env::current_dir() + .unwrap_or_default() + .join("assets/skins"), + ), + skin_slots: Vec::new(), + cart_models, + riding: None, + ender_items: vec![None; 27], + ender_open: None, + pending: Default::default(), + spill: Default::default(), + recipe_ui: Default::default(), + mount_menu: Default::default(), + hook: None, + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + creaking: Default::default(), + spawners: Default::default(), + trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), + arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), + tnts: Vec::new(), + hoppers: HashMap::new(), + creative_screen: Creative::load(&root)?, + control: None, + frame_stats: Default::default(), + perf: Default::default(), + pending_screenshot: None, + pending_bench: None, + flight: None, + ui_wait: Default::default(), + events: Default::default(), + agent: agent::Agent::default(), + view_frustum: None, + entity_culler: None, + pending_uploads: Vec::new(), + frame_graph: Default::default(), + extras: Default::default(), + mods: Default::default(), + sky_darken_memo: Default::default(), + persist: Default::default(), + remote: None, + lan: None, + world_options: None, + options_to_world_options: false, + command_block_screen: None, + friends: None, + debug_keys: Default::default(), + debug_charts: Default::default(), + show_hitboxes: false, + show_chunk_borders: false, + pause_menu: true, + previous_mode: None, + gamemode_switcher: None, + clipboard: Default::default(), + text_selection: Default::default(), + saved_for_exit: false, + forced_hit: None, + lan_item_only: false, + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + lid_openers: HashMap::new(), + lan_acting: None, + lan_acting_name: None, + lan_acting_uuid: None, + chat_capture: None, + cmds: Default::default(), + ui: Default::default(), + combat: Default::default(), + mount: Default::default(), + stats: Default::default(), + score: Default::default(), + fns: Default::default(), + bosses: Default::default(), + exec: Default::default(), + rand_sequences: Default::default(), + border: Default::default(), + border_renderer: Default::default(), + border_state: Default::default(), + tab_list: Default::default(), + subtitles: Default::default(), + adv: Default::default(), + restore_player_environment: true, + stats_ui: Default::default(), + adv_ui: Default::default(), + camera_type: Default::default(), + fangs: Default::default(), + player_model: None, + }) + } +} + pub fn run() -> Result<()> { let Some(mut options) = Options::read()? else { return Ok(()); @@ -9847,26 +10165,11 @@ pub fn run() -> Result<()> { biomes.list.len(), threads ); - // Until a world is opened the streamer is idle. - let mut streaming = Streaming::new( - Arc::new(TestTerrain::new(assets.registry, &biomes)?), - pack.context.clone(), - 1, - ); - streaming.paused = true; - let level = Level::default(); - let save = Arc::new(SaveDir::new( - std::env::current_dir()? - .join("saves") - .join(".horizon-title"), - )); let audio = if options.dedicated.is_some() { Audio::silent(&root) } else { Audio::new(&root) }; - let world = World::new(facts.air, 0); - let creative = options.creative; let stations = horizon_client::stations::StationData::load(&root, &items); let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; @@ -9904,18 +10207,6 @@ pub fn run() -> Result<()> { player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), }); - // These batches share the exported document instead of reparsing it per layer. - let (armor_stand_assets, boat_models, cart_models) = { - let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); - ( - armor_stands::ArmorStandAssets::load(&root, document.as_ref()), - boats::BoatModels::load(document.as_ref()), - minecarts::CartModels::load(document.as_ref()), - ) - }; - let inventory = vec![None; 36]; - let now = Instant::now(); - let game_root = options.resources.clone(); let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); // Scripted and frame-limited runs (the parity harnesses) see vanilla's @@ -9928,281 +10219,7 @@ pub fn run() -> Result<()> { if let Some(d) = options.distance_override { settings.render_distance = d; } - let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); - let mut game = Game { - res: resources.clone(), - collision: &resources.collision, - motion: &resources.motion, - pack, - atlas, - fog: Default::default(), - screen_fx: Default::default(), - world, - streaming, - options, - player: None, - spawn: None, - clock: FixedStep::default(), - previous_position: Vec3::ZERO, - eye: 1.62, - previous_eye: 1.62, - yaw: look.map_or(level.rotation[0], |l| l.0), - pitch: look.map_or(level.rotation[1], |l| l.1), - inventory, - selected: 0, - carried: None, - craft_grid: vec![None; 9], - craft_size: 2, - inv_drag: None, - tweaks: Default::default(), - inv_clicks: Default::default(), - last_inv_click: None, - last_quick_moved: None, - container: None, - station: None, - potions: Default::default(), - scratch_slot: None, - mining: None, - destroy_delay: 0, - use_delay: 0, - creative, - mode: if creative { - horizon_client::command::args::GameMode::Creative - } else { - horizon_client::command::args::GameMode::Survival - }, - keys: HashSet::new(), - physical_keys: HashSet::new(), - left: false, - right: false, - cursor: (0.0, 0.0), - captured: false, - focused: true, - modifiers: winit::keyboard::ModifiersState::empty(), - fullscreen: horizon_client::window::FullscreenState::new(false), - shader_packs: Default::default(), - mouse: MouseLook::default(), - agent_pointer: false, - smooth_camera: false, - toggles: Default::default(), - was_playing: false, - pause: false, - debug: false, - screen: Screen::Playing, - window: None, - renderer: None, - entity_vertices: Vec::new(), - see_through_vertices: Vec::new(), - health_hud: hud_layout::HealthHud::default(), - started: now, - previous: now, - last_input: now, - pad: Default::default(), - frames: 0, - world_frames: 0, - fps: 0.0, - fps_frames: 0, - fps_at: now, - ticks: 0, - error: None, - message: None, - save, - level, - session_lock: None, - audio, - music: Default::default(), - ambience: Default::default(), - sound_paused: false, - cart_sounds: HashSet::new(), - riding_cart_sounds: None, - dropped: Vec::new(), - next_entity: 0, - particles, - pickups: Default::default(), - sign_edit: None, - book: None, - lectern_pulses: Vec::new(), - loading_progress: 0.0, - spawn_origin: None, - spawn_spiral: Default::default(), - player_spawn: None, - mobs: Vec::new(), - creatures: Default::default(), - sculk: Default::default(), - raiding: Default::default(), - attack_ticks: 100, - last_hurt_by_player: HashSet::new(), - died: HashSet::new(), - be_anims: { - let mut anims = horizon_client::block_entity_anim::BlockEntityAnims::default(); - anims.classify(registry_owner.registry); - anims - }, - using: None, - view: Default::default(), - limiter: horizon_client::window::FramerateLimiter::new(0), - frame_clock: Default::default(), - scope_scale: 0.5, - frame_ticks: 0.0, - title: None, - armor: [None, None, None, None], - offhand: None, - hand: Hand::Main, - shield_cooldown: 0, - command_source: None, - titles: Default::default(), - tool_highlight: Default::default(), - applied_modifiers: Vec::new(), - experience: Experience::default(), - orbs: Vec::new(), - xp_delay: 0, - last_level_up: 0, - swing: Default::default(), - swings_started: 0, - heights: Default::default(), - sway: Default::default(), - visible_hands: [(0, None), (0, None)], - clicks: Default::default(), - attack_clicks: 0, - hand_strength: Default::default(), - settings, - options_from_title: false, - backdrop: Default::default(), - pause_since: None, - dragging: false, - avatar: Default::default(), - flash: 0, - sleeping: None, - dim: Dim::Overworld, - world_root: PathBuf::new(), - travelling: None, - portals: Default::default(), - end_travel: false, - respawn_config: None, - respawn_travel: None, - end_portal_travel: false, - end: Default::default(), - block_ticks: Ticks::new(0), - tick_chunks: Default::default(), - random_tick_sections: Default::default(), - level_events: Vec::new(), - falling: Vec::new(), - paintings: Vec::new(), - painting_variants: paintings::PaintingVariants::load(&root), - item_frames: Vec::new(), - frame_model: frames::bake_frame(&root, "item_frame"), - glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), - map_frame_model: frames::bake_frame(&root, "item_frame_map"), - glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), - armor_stands: Vec::new(), - others: Vec::new(), - armor_stand_assets, - boats: Vec::new(), - boat_models, - crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), - carts: Vec::new(), - jukebox_sounds: HashMap::new(), - bolts: Vec::new(), - maps: maps::Maps::default(), - fight: dragon::Fight::default(), - dragon: None, - crystals: Vec::new(), - dragon_fireballs: Vec::new(), - breath_clouds: Vec::new(), - dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), - map_patches: Vec::new(), - skin_downloads: horizon_client::skins::Downloader::new( - std::env::current_dir() - .unwrap_or_default() - .join("assets/skins"), - ), - skin_slots: Vec::new(), - cart_models, - riding: None, - ender_items: vec![None; 27], - ender_open: None, - pending: Default::default(), - spill: Default::default(), - recipe_ui: Default::default(), - mount_menu: Default::default(), - hook: None, - tridents: Vec::new(), - rockets: Vec::new(), - ominous_spawners: Vec::new(), - creaking: Default::default(), - spawners: Default::default(), - trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), - arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), - tnts: Vec::new(), - hoppers: HashMap::new(), - creative_screen: Creative::load(&game_root)?, - control: None, - frame_stats: Default::default(), - perf: Default::default(), - pending_screenshot: None, - pending_bench: None, - flight: None, - ui_wait: Default::default(), - events: Default::default(), - agent: agent::Agent::default(), - view_frustum: None, - entity_culler: None, - pending_uploads: Vec::new(), - frame_graph: Default::default(), - extras: Default::default(), - mods: Default::default(), - sky_darken_memo: Default::default(), - persist: Default::default(), - remote: None, - lan: None, - world_options: None, - options_to_world_options: false, - command_block_screen: None, - friends: None, - debug_keys: Default::default(), - debug_charts: Default::default(), - show_hitboxes: false, - show_chunk_borders: false, - pause_menu: true, - previous_mode: None, - gamemode_switcher: None, - clipboard: Default::default(), - text_selection: Default::default(), - saved_for_exit: false, - forced_hit: None, - lan_item_only: false, - lan_events: Vec::new(), - lan_block_events: Vec::new(), - lan_entity_events: Vec::new(), - lid_openers: HashMap::new(), - lan_acting: None, - lan_acting_name: None, - lan_acting_uuid: None, - chat_capture: None, - cmds: Default::default(), - ui: Default::default(), - combat: Default::default(), - mount: Default::default(), - stats: Default::default(), - score: Default::default(), - fns: Default::default(), - bosses: Default::default(), - exec: Default::default(), - rand_sequences: Default::default(), - border: Default::default(), - border_renderer: Default::default(), - border_state: Default::default(), - tab_list: Default::default(), - subtitles: Default::default(), - adv: Default::default(), - restore_player_environment: true, - stats_ui: Default::default(), - adv_ui: Default::default(), - camera_type: Default::default(), - fangs: Default::default(), - player_model: None, - }; + let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?; game.ui.vanilla_root = vanilla_root; if game.options.benchmark.is_some() { // The same conditions on every machine: no VSync, no frame cap, no From 56dc4352d2d935b8b199ea40baa8256bb41a6301 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:18:03 +0200 Subject: [PATCH 20/23] Run single player on an integrated server thread (opt-in) With --server-thread or HORIZON_SERVER_THREAD=1, opening a single-player world starts a game of its own on a "Server thread" over the shared resources, as vanilla's IntegratedServer does, and the window joins it as a player over a local connection. The world tick then never runs inside a frame. - The server listens on 127.0.0.1 only, lets in the window's profile alone, without compression, and makes it an operator when the world allows commands. - The window's player is the world's own player: it loads from and saves to players/data/.dat, so the world opens the same way in either mode. - A pause screen pauses the server (IntegratedServer.tickServer), and leaving the world or quitting waits for the server to save. - The integrated server does not mesh sections it never draws. - Worlds whose player is outside the Overworld open the usual way for now. - The bench summary reports the 0.1% low. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/control.rs | 20 +- crates/horizon-client/src/game.rs | 30 +- crates/horizon-client/src/game/dedicated.rs | 4 +- crates/horizon-client/src/game/integrated.rs | 288 +++++++++++++++++++ crates/horizon-client/src/game/lan.rs | 52 +++- crates/horizon-client/src/game/remote.rs | 13 + crates/horizon-client/src/lan/playerdata.rs | 55 ++-- crates/horizon-client/src/streaming.rs | 8 + 8 files changed, 434 insertions(+), 36 deletions(-) create mode 100644 crates/horizon-client/src/game/integrated.rs diff --git a/crates/horizon-client/src/control.rs b/crates/horizon-client/src/control.rs index 3019d8dfa..9749cc9bd 100644 --- a/crates/horizon-client/src/control.rs +++ b/crates/horizon-client/src/control.rs @@ -467,13 +467,16 @@ impl FrameStats { } let total: f64 = sorted.iter().map(|&m| f64::from(m)).sum(); let percentile = |p: f64| sorted[((n as f64 * p).ceil() as usize).clamp(1, n) - 1]; - // Average frame time of the slowest 1% of frames, as frames per second. - let slowest = n.div_ceil(100); - let slow: f64 = sorted[n - slowest..] - .iter() - .map(|&m| f64::from(m)) - .sum::() - / slowest as f64; + // Average frame time of the slowest 1% (0.1%) of frames, as frames per second. + let low = |per: usize| { + let slowest = n.div_ceil(per); + let slow: f64 = sorted[n - slowest..] + .iter() + .map(|&m| f64::from(m)) + .sum::() + / slowest as f64; + 1000.0 / slow + }; // Where the slowest 1% of frames by CPU time go. let slow_phases = { let mut cpu = self.cpu.clone(); @@ -487,7 +490,8 @@ impl FrameStats { "frames": n, "seconds": total / 1000.0, "avg_fps": n as f64 * 1000.0 / total, - "low_1pct_fps": 1000.0 / slow, + "low_1pct_fps": low(100), + "low_01pct_fps": low(1000), "p50_ms": percentile(0.5), "p95_ms": percentile(0.95), "p99_ms": percentile(0.99), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 34af3318d..6b9cfb700 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -56,6 +56,7 @@ mod golems; mod growth; mod hand; mod initial_spawn; +mod integrated; mod item_draw; mod item_particles; mod jukebox; @@ -243,6 +244,11 @@ struct Options { benchmark: Option, /// `--dev-mod PATH` (repeatable): mods always on and reloaded when rebuilt. dev_mods: Vec, + /// `--server-thread` or `HORIZON_SERVER_THREAD=1`: single player runs on + /// an integrated server thread (game/integrated.rs). + server_thread: bool, + /// Set on the integrated server's own options: it draws nothing, so it skips meshing. + integrated: bool, } impl Options { /// The name to join servers with: the one given, else the offline name kept @@ -294,6 +300,8 @@ impl Options { dedicated: None, benchmark: None, dev_mods: Vec::new(), + server_thread: std::env::var("HORIZON_SERVER_THREAD").is_ok_and(|v| v == "1"), + integrated: false, }; let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok(); let mut args = std::env::args().skip(1); @@ -314,6 +322,7 @@ impl Options { "--no-pause" => o.no_pause = true, "--offscreen" => o.offscreen = true, "--control" => o.control = Some(horizon_client::control::default_path()), + "--server-thread" => o.server_thread = true, _ => { let value = args .next() @@ -1074,6 +1083,8 @@ struct Game<'a> { remote: Option, /// This world is open to the network (game/lan.rs). lan: Option, + /// Single player's server thread, which `remote` is connected to. + integrated: Option, /// The open world is shared behind an invite code (game/friends.rs). friends: Option, world_options: Option, @@ -3632,7 +3643,7 @@ impl Game<'_> { } /// `Minecraft.pause`: a single-player game with a pausing screen open. fn pauses_game(&self) -> bool { - self.remote.is_none() + (self.remote.is_none() || self.integrated.is_some()) && self.lan.is_none() && self.title.is_none() && (matches!( @@ -6129,8 +6140,11 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { - self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); + if integrated::wanted(&self.options, &save_root) { + return self.open_integrated(folder, name, seed, creative, create); + } + self.perf.world_opening(); horizon_client::save::upgrade_older_world(&save_root)?; horizon_client::save::migrate_legacy(&save_root)?; self.session_lock = None; @@ -6392,6 +6406,8 @@ impl Game<'_> { streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; + // The integrated server draws nothing (the dedicated server keeps its behaviour). + streaming.mesh = !self.options.integrated; Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -6587,6 +6603,11 @@ impl Game<'_> { return Ok(()); } self.saved_for_exit = true; + if let Some(server) = self.integrated.take() { + // The server thread saves the world. + server.stop(); + return Ok(()); + } self.close_container(); if self.remote.is_none() { self.stats.custom("leave_game", 1); @@ -8340,6 +8361,7 @@ impl Game<'_> { self.save_schedule(); self.save_warden_tracker(); self.sync_level(); + self.store_owner(); self.level.write(&self.world_root)?; self.save_world_state(); self.message = Some(("Saved the game".into(), Instant::now())); @@ -9652,6 +9674,9 @@ impl ApplicationHandler for Game<'_> { } self.limit_frame(); self.pause = self.pauses_game(); + if let Some(server) = &self.integrated { + server.set_paused(self.pause); + } self.clock.end_frame(self.pause); let finished = self .renderer @@ -10047,6 +10072,7 @@ impl<'a> Game<'a> { persist: Default::default(), remote: None, lan: None, + integrated: None, world_options: None, options_to_world_options: false, command_block_screen: None, diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index cd7744d87..e0b283f69 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -525,7 +525,7 @@ impl Game<'_> { /// Load the spawn area and find the world spawn as single player does, /// without keeping a player there. - fn settle_spawn(&mut self) -> Result<()> { + pub(super) fn settle_spawn(&mut self) -> Result<()> { let deadline = Instant::now() + Duration::from_secs(600); while self.player.is_none() { self.update_world(); @@ -541,7 +541,7 @@ impl Game<'_> { /// The chunks to keep loaded: the players' (lan_update_streaming), or /// the spawn chunk while nobody is online. - fn update_dedicated_streaming(&mut self) { + pub(super) fn update_dedicated_streaming(&mut self) { let center = self .lan .as_ref() diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs new file mode 100644 index 000000000..1b20b077d --- /dev/null +++ b/crates/horizon-client/src/game/integrated.rs @@ -0,0 +1,288 @@ +//! The integrated server (`IntegratedServer`): single player's world runs on +//! its own "Server thread", as vanilla's does, and the window joins it as a +//! player over a local connection, so a world tick never holds up a frame. +//! +//! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the +//! player joins as a network player, and the server side of a network player +//! does not do everything single player does yet. Worlds whose player is +//! outside the Overworld open the usual way, since network players stay in +//! the Overworld so far. +use super::{ + Dim, Game, Options, PackResources, Resources, + lan::{LanSettings, Owner}, +}; +use horizon_client::{ + Result, + audio::Audio, + hud::HudAtlas, + lan::{MAX_PLAYERS, NetConfig, hub::HubConfig}, + save::Level, + settings::Settings, + title::WorldOptions, +}; +use horizon_protocol::{crypto::offline_uuid, text::translatable}; +use std::{ + net::{IpAddr, Ipv4Addr}, + path::Path, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc::{Sender, channel}, + }, + thread::JoinHandle, + time::{Duration, Instant}, +}; + +/// What the window tells its server thread. +#[derive(Default)] +struct Flags { + /// `Minecraft.pause`: a single-player pause screen is open. + paused: AtomicBool, + stop: AtomicBool, +} + +/// The window's handle on its server thread. +pub(super) struct Integrated { + flags: Arc, + thread: Option>, +} +impl Integrated { + /// `IntegratedServer.tickServer` skips the world while the game is paused. + pub fn set_paused(&self, paused: bool) { + self.flags.paused.store(paused, Ordering::Relaxed); + } + /// `IntegratedServer.halt(true)`: returns once the world is saved and let go. + pub fn stop(mut self) { + self.halt(); + } + fn halt(&mut self) { + self.flags.stop.store(true, Ordering::Relaxed); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} +impl Drop for Integrated { + fn drop(&mut self) { + self.halt(); + } +} + +/// The world to open and the player who owns it. +struct Launch { + folder: String, + name: Option, + seed: Option, + creative: bool, + create: Option, + /// The window's profile: the only one let in, and the world's player. + owner: u128, +} + +/// Whether this world opens on a server thread: asked for, and its player +/// (if any yet) in the Overworld. +pub(super) fn wanted(options: &Options, world: &Path) -> bool { + options.server_thread + && options.dedicated.is_none() + && Level::read(world).is_none_or(|l| Dim::from_id(&l.dimension) == Dim::Overworld) +} + +impl Game<'_> { + /// `Minecraft.doWorldLoad`: start the server thread on the world, wait + /// until it listens, then join it. + pub(super) fn open_integrated( + &mut self, + folder: &str, + name: Option<&str>, + seed: Option, + creative: bool, + create: Option<&WorldOptions>, + ) -> Result<()> { + let auth = horizon_client::auth::current(); + let player = auth + .as_ref() + .map_or_else(|| self.options.player_name(), |a| a.name.clone()); + let launch = Launch { + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned(), + // An offline-mode server names its players by their offline profile. + owner: offline_uuid(&player), + }; + let mut options = self.options.clone(); + // A server without a console: no local player, no window, no control socket. + options.dedicated = Some(Vec::new()); + options.server_thread = false; + options.integrated = true; + options.control = None; + options.benchmark = None; + options.frames = None; + options.world_frames = None; + options.report = None; + options.server = None; + options.world = None; + options.dev_mods.clear(); + let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); + let flags = Arc::new(Flags::default()); + let (ready_tx, ready) = channel(); + let server_flags = flags.clone(); + let thread = std::thread::Builder::new() + .name("Server thread".into()) + .spawn(move || { + let result = serve( + &res, + pack, + options, + settings, + launch, + &server_flags, + &ready_tx, + ); + if let Err(e) = result { + log::error!("Horizon: integrated server: {e}"); + let _ = ready_tx.send(Err(e.to_string())); + } + })?; + let handle = Integrated { + flags, + thread: Some(thread), + }; + let port = match ready.recv() { + Ok(Ok(port)) => port, + Ok(Err(e)) => return Err(e.into()), + Err(_) => return Err("the integrated server stopped".into()), + }; + self.connect_server(&format!("127.0.0.1:{port}"), &player)?; + self.integrated = Some(handle); + Ok(()) + } + + /// The server thread's loop (`MinecraftServer.runServer`): 20 ticks a + /// second, the world held while the window is paused. + fn run_integrated( + &mut self, + launch: Launch, + flags: &Flags, + ready: &Sender>, + ) -> Result<()> { + self.open_world( + &launch.folder, + launch.name.as_deref(), + launch.seed, + launch.creative, + launch.create.as_ref(), + )?; + let saved = Box::new(self.level.clone()); + let view_distance = self.settings.render_distance.clamp(2, 32); + let config = HubConfig { + default_game_mode: self.level.mode(), + guest_commands: true, + force_game_mode: false, + hardcore: self.level.hardcore, + view_distance, + simulation_distance: self.settings.simulation_distance.clamp(2, 32), + dimension: self.dim.id().to_owned(), + seed: self.level.seed, + max_players: MAX_PLAYERS, + // No player of its own: the hub runs without a host. + dedicated: true, + }; + let owner = launch.owner; + let net = NetConfig { + bind: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)), + // A local connection is not compressed (`Connection.isMemoryConnection`). + compression_threshold: -1, + enable_status: false, + announce: false, + gate: Some(Arc::new(move |_, uuid, _| { + (uuid != owner).then(|| translatable("multiplayer.disconnect.not_whitelisted", &[])) + })), + ..NetConfig::lan(0, self.level.name.clone(), MAX_PLAYERS) + }; + let settings = LanSettings { + port: 0, + guest_commands: true, + force_game_mode: false, + }; + self.lan_host(settings, net, config, None)?; + let commands = self.allow_commands(); + let port = { + let host = self + .lan + .as_mut() + .ok_or("the integrated server did not start")?; + // The owner is an operator when the world allows commands + // (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`). + host.hub.ops.insert(owner, if commands { 4 } else { 0 }); + host.owner = Some(Owner { + uuid: owner, + saved: Some(saved), + }); + host.settings.port + }; + let _ = ready.send(Ok(port)); + self.settle_spawn()?; + let mut next = Instant::now(); + while !flags.stop.load(Ordering::Relaxed) { + self.update_dedicated_streaming(); + self.update_world(); + if flags.paused.load(Ordering::Relaxed) { + // Only the connections run. + self.tick_lan(); + } else { + self.tick()?; + } + let rate = self.clock.rate().max(1.0); + next += Duration::from_secs_f64(1.0 / f64::from(rate)); + let now = Instant::now(); + if next > now { + std::thread::sleep(next - now); + } else if now - next > Duration::from_secs(2) { + next = now; + } + } + self.stop_integrated() + } + + /// `MinecraftServer.stopServer`: the players are saved and sent away, + /// then the world is saved. + fn stop_integrated(&mut self) -> Result<()> { + if let Some(mut host) = self.lan.take() { + for g in &host.hub.guests { + self.save_guest(&host, g); + } + let conns: Vec = host.hub.guests.iter().map(|g| g.conn).collect(); + for conn in conns { + host.hub.kick( + conn, + translatable("multiplayer.disconnect.server_shutdown", &[]), + ); + } + self.lan = Some(host); + } + std::thread::sleep(Duration::from_millis(100)); + self.save_game()?; + self.lan_close(false); + self.save.flush(); + self.session_lock = None; + Ok(()) + } +} + +/// The server thread: a game of its own over the shared resources. +fn serve( + res: &Arc, + pack: PackResources, + options: Options, + settings: Settings, + launch: Launch, + flags: &Flags, + ready: &Sender>, +) -> Result<()> { + let atlas = HudAtlas::build(&options.resources)?; + let audio = Audio::silent(&options.resources); + let mut server = Game::new(res, pack, atlas, options, settings, audio)?; + server.run_integrated(launch, flags, ready) +} diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 024f671b2..c416c202f 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -55,6 +55,17 @@ pub(super) struct LanHost { mob_state: HashMap, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, + /// An integrated server's owner (game/integrated.rs). + pub owner: Option, +} + +/// The player who owns an integrated server's world: a guest whose state is +/// the world's own player (`players/data/.dat`), as in +/// single player. +pub(super) struct Owner { + pub uuid: u128, + /// The world's player as loaded, until the owner joins. + pub saved: Option>, } /// A stable UUID for an entity that has none. @@ -465,6 +476,7 @@ impl Game<'_> { broken: Vec::new(), mob_state: HashMap::new(), mob_players: HashMap::new(), + owner: None, }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -477,7 +489,7 @@ impl Game<'_> { return; }; for g in &host.hub.guests { - playerdata::save(g, &self.world_root); + self.save_guest(&host, g); } host.hub.disconnect_all(); // Give the writer threads a moment to flush the disconnect packets. @@ -494,6 +506,30 @@ impl Game<'_> { } } + /// Save a guest when they leave or the world closes: an integrated + /// server's owner with the world (`save_game`), anyone else in their file. + pub(super) fn save_guest(&mut self, host: &LanHost, guest: &horizon_client::lan::guest::Guest) { + if host.owner.as_ref().is_some_and(|o| o.uuid == guest.uuid) { + if guest.placed { + playerdata::store(guest, &mut self.level); + } + } else { + playerdata::save(guest, &self.world_root); + } + } + /// The integrated server's owner into the world's player, for `Level::write`. + pub(super) fn store_owner(&mut self) { + let Some(host) = &self.lan else { + return; + }; + let Some(uuid) = host.owner.as_ref().map(|o| o.uuid) else { + return; + }; + if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == uuid && g.placed) { + playerdata::store(g, &mut self.level); + } + } + /// The world's default game mode (`defaultgamemode`). pub(super) fn set_default_game_mode(&mut self, mode: i32) { self.level.game_mode = mode; @@ -664,7 +700,7 @@ impl Game<'_> { self.container_openers_changed(pos, false); } self.lan_crafting_left(&mut host, &mut guest); - playerdata::save(&guest, &self.world_root); + self.save_guest(&host, &guest); host.models.remove(&guest.conn); if self.options.dedicated.is_some() && guest.placed { super::dedicated::log( @@ -707,10 +743,20 @@ impl Game<'_> { let default_mode = host.hub.config.default_game_mode; let force = host.hub.config.force_game_mode; let root = self.world_root.clone(); + let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; }; - let known = playerdata::load(g, &root); + let saved = owner + .filter(|o| o.uuid == g.uuid) + .and_then(|o| o.saved.take()); + let known = match saved { + Some(level) => { + playerdata::apply(g, &level); + level.position.is_some() + } + None => playerdata::load(g, &root), + }; if !known || force { g.game_mode = default_mode; } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 7bc41d703..0d6df8663 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -274,6 +274,14 @@ impl Game<'_> { if let Some(mut r) = self.remote.take() { r.session.disconnect(); } + // Single player's server thread saves the world before the title shows. + let single_player = match self.integrated.take() { + Some(server) => { + server.stop(); + true + } + None => false, + }; horizon_client::crash::clear_detail("Server"); self.debug_charts.reset(); self.tab_list.reset(); @@ -296,6 +304,11 @@ impl Game<'_> { } let saves = std::env::current_dir()?.join("saves"); let mut title = horizon_client::title::Title::new(saves.clone(), &self.options.resources); + if single_player && reason.is_none() { + self.title = Some(title); + self.capture(false); + return Ok(()); + } title.mode = horizon_client::title::Mode::Multiplayer(match reason { Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason, diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index c0ccc41b0..3554463ea 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -45,6 +45,13 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { ..Level::default() }; level.read_player(&tag); + level.player_extra = Some(tag); + apply(guest, &level); + true +} + +/// Give a guest the player state read into `level`. +pub fn apply(guest: &mut Guest, level: &Level) { if let Some(p) = level.position { guest.position = p; guest.previous_position = p; @@ -61,7 +68,7 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { guest.xp_total = level.xp_total; guest.game_mode = level.mode(); guest.selected = (level.selected_slot.max(0) as usize).min(8); - guest.saved = Some(tag); + guest.saved = level.player_extra.clone(); if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -85,30 +92,41 @@ pub fn load(guest: &mut Guest, world: &Path) -> bool { _ => {} } } - true } /// Save a guest (PlayerDataStorage.save). pub fn save(guest: &Guest, world: &Path) { let mut level = Level { player_uuid: Some(uuid_ints(guest.uuid)), - position: Some(guest.position), - rotation: [guest.yaw, guest.pitch], - health: guest.health, - food: guest.food, - saturation: guest.saturation, - xp_level: guest.xp_level, - xp_progress: guest.xp_progress, - xp_total: guest.xp_total, - game_mode: guest.game_mode, - creative: guest.game_mode == 1, - selected_slot: guest.selected as i32, - on_ground: guest.on_ground, dimension: "minecraft:overworld".into(), - player_extra: guest.saved.clone(), - ender_items: guest.ender_items.clone(), ..Level::default() }; + store(guest, &mut level); + let file = path(world, guest.uuid); + if let Some(dir) = file.parent() { + let _ = std::fs::create_dir_all(dir); + } + let _ = write_dat(&file, level.player_tag()); +} + +/// Put a guest's state in `level`'s player fields. +pub fn store(guest: &Guest, level: &mut Level) { + level.position = Some(guest.position); + level.rotation = [guest.yaw, guest.pitch]; + level.health = guest.health; + level.food = guest.food; + level.saturation = guest.saturation; + level.xp_level = guest.xp_level; + level.xp_progress = guest.xp_progress; + level.xp_total = guest.xp_total; + level.game_mode = guest.game_mode; + level.creative = guest.game_mode == 1; + level.selected_slot = guest.selected as i32; + level.on_ground = guest.on_ground; + level.player_extra = guest.saved.clone(); + level.ender_items = guest.ender_items.clone(); + level.inventory.clear(); + level.inventory_components.clear(); let mut put = |slot: u8, stack: &Option| { if let Some(s) = stack { level @@ -127,9 +145,4 @@ pub fn save(guest: &Guest, world: &Path) { put(101, &guest.armor[2]); put(100, &guest.armor[3]); put(150, &guest.offhand); - let file = path(world, guest.uuid); - if let Some(dir) = file.parent() { - let _ = std::fs::create_dir_all(dir); - } - let _ = write_dat(&file, level.player_tag()); } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index e341caa3d..df1001640 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -200,6 +200,8 @@ pub struct Streaming { /// More areas to keep loaded (centre chunk, radius), e.g. around guests /// of a world open to the network. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, + /// Mesh the sections for drawing (false on a server thread). + pub mesh: bool, } /// Snapshot only after a scan found no missing candidates. Public range fields /// and `World::chunks` can change without going through Streaming, so compare @@ -466,6 +468,7 @@ impl Streaming { meshed_total: 0, remote: false, extra: Vec::new(), + mesh: true, } } /// Resource packs reloaded (`LevelRenderer.allChanged`): mesh with the new @@ -959,6 +962,11 @@ impl Streaming { Job::Light(x, z, region, self.sequence, self.sky_light), ); } + // A server draws nothing: its sections are never meshed. + if !self.mesh { + world.dirty_sections.clear(); + return (uploads, removed); + } // Meshing once the column and its neighbours are lit, and the column // is within the render distance. Sections set aside past it come back // when the player moves: a column that loads with its light gets no From db45b6f87a4bf1e03ec3cc415faefaabde9480e5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 17:33:06 +0200 Subject: [PATCH 21/23] Integrated server: join through memory instead of a socket The window now joins its server thread through an in-memory pipe, as vanilla's integrated server player does (LocalChannel), rather than a TCP socket on 127.0.0.1. The server opens no port until it is opened to the LAN. - horizon-protocol: Connection runs over TCP or one end of a Pipe (a blocking byte pipe with read timeouts and shutdown; dropping an end closes it). - Lan: NetConfig.listen false starts no listener; connect_local serves the other end of a pipe on its own thread, through the same handshake, login and configuration as a socket. - Session::connect_local joins through a pipe. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/dedicated.rs | 1 + crates/horizon-client/src/game/integrated.rs | 27 +-- crates/horizon-client/src/game/remote.rs | 32 ++- crates/horizon-client/src/lan/conn.rs | 20 +- crates/horizon-client/src/lan/mod.rs | 54 ++++- crates/horizon-client/src/net.rs | 48 ++++- crates/horizon-protocol/src/connection.rs | 208 ++++++++++++++++++- 7 files changed, 344 insertions(+), 46 deletions(-) diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index e0b283f69..01728b351 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -418,6 +418,7 @@ impl Game<'_> { enforces_secure_chat: false, accepts_transfers: props.accepts_transfers, announce: false, + listen: true, bypasses_limit: Some(Arc::new(move |uuid| { bypass_lists .lock() diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 1b20b077d..6edbb6e40 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -1,6 +1,6 @@ //! The integrated server (`IntegratedServer`): single player's world runs on //! its own "Server thread", as vanilla's does, and the window joins it as a -//! player over a local connection, so a world tick never holds up a frame. +//! player through memory, so a world tick never holds up a frame. //! //! Opt-in for now (`--server-thread` or `HORIZON_SERVER_THREAD=1`): the //! player joins as a network player, and the server side of a network player @@ -20,9 +20,9 @@ use horizon_client::{ settings::Settings, title::WorldOptions, }; +use horizon_protocol::connection::Pipe; use horizon_protocol::{crypto::offline_uuid, text::translatable}; use std::{ - net::{IpAddr, Ipv4Addr}, path::Path, sync::{ Arc, @@ -89,7 +89,7 @@ pub(super) fn wanted(options: &Options, world: &Path) -> bool { impl Game<'_> { /// `Minecraft.doWorldLoad`: start the server thread on the world, wait - /// until it listens, then join it. + /// until it can be joined, then join it through memory. pub(super) fn open_integrated( &mut self, folder: &str, @@ -149,12 +149,12 @@ impl Game<'_> { flags, thread: Some(thread), }; - let port = match ready.recv() { - Ok(Ok(port)) => port, + let pipe = match ready.recv() { + Ok(Ok(pipe)) => pipe, Ok(Err(e)) => return Err(e.into()), Err(_) => return Err("the integrated server stopped".into()), }; - self.connect_server(&format!("127.0.0.1:{port}"), &player)?; + self.connect_local(pipe, &player)?; self.integrated = Some(handle); Ok(()) } @@ -165,7 +165,7 @@ impl Game<'_> { &mut self, launch: Launch, flags: &Flags, - ready: &Sender>, + ready: &Sender>, ) -> Result<()> { self.open_world( &launch.folder, @@ -191,8 +191,9 @@ impl Game<'_> { }; let owner = launch.owner; let net = NetConfig { - bind: Some(IpAddr::V4(Ipv4Addr::LOCALHOST)), - // A local connection is not compressed (`Connection.isMemoryConnection`). + // No network until it is opened to the LAN. + listen: false, + // A memory connection is not compressed (`Connection.isMemoryConnection`). compression_threshold: -1, enable_status: false, announce: false, @@ -208,7 +209,7 @@ impl Game<'_> { }; self.lan_host(settings, net, config, None)?; let commands = self.allow_commands(); - let port = { + let pipe = { let host = self .lan .as_mut() @@ -220,9 +221,9 @@ impl Game<'_> { uuid: owner, saved: Some(saved), }); - host.settings.port + host.hub.lan.connect_local()? }; - let _ = ready.send(Ok(port)); + let _ = ready.send(Ok(pipe)); self.settle_spawn()?; let mut next = Instant::now(); while !flags.stop.load(Ordering::Relaxed) { @@ -279,7 +280,7 @@ fn serve( settings: Settings, launch: Launch, flags: &Flags, - ready: &Sender>, + ready: &Sender>, ) -> Result<()> { let atlas = HudAtlas::build(&options.resources)?; let audio = Audio::silent(&options.resources); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 0d6df8663..e31e270b8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -153,6 +153,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + self.join_server(address, name, None) + } + /// Join single player's integrated server through memory. + pub(super) fn connect_local( + &mut self, + pipe: horizon_protocol::connection::Pipe, + name: &str, + ) -> Result<()> { + self.join_server("local", name, Some(pipe)) + } + fn join_server( + &mut self, + address: &str, + name: &str, + local: Option, + ) -> Result<()> { self.perf.world_opening(); let root = self.options.resources.clone(); let builtin = Builtin::find(&root) @@ -160,12 +176,22 @@ impl Game<'_> { .ok_or("registries.json not found next to the resources; run the data generator reports (horizon-prepare)")?; let lang = Arc::new(horizon_client::net::load_language(&root)); let view = self.settings.render_distance.clamp(2, 32) as i8; - horizon_client::crash::set_detail("Server", horizon_client::net::shown_address(address)); + if local.is_none() { + horizon_client::crash::set_detail( + "Server", + horizon_client::net::shown_address(address), + ); + } // A signed-in account always plays under its own name. let auth = horizon_client::auth::current(); let name = auth.as_ref().map_or(name, |a| a.name.as_str()); - let session = Session::connect(address, name, auth.clone(), view, lang.clone()); - self.extras_connecting(address, name); + let session = match local { + Some(pipe) => Session::connect_local(pipe, name, view, lang.clone()), + None => { + self.extras_connecting(address, name); + Session::connect(address, name, auth.clone(), view, lang.clone()) + } + }; let player_type = super::perspective::player_type(&root); let mut streaming = Streaming::new( Arc::new(NoTerrain), diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index f67c647fd..0688db0c6 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -217,7 +217,25 @@ pub fn serve( { return serve_legacy(stream, &shared); } - let mut c = Connection::from_stream(stream).map_err(e)?; + serve_connection(Connection::from_stream(stream).map_err(e)?, address, shared) +} + +/// `ServerConnectionListener.startMemoryChannel`: an integrated server's +/// own player, over one end of an in-memory pipe. +pub fn serve_local( + pipe: horizon_protocol::connection::Pipe, + shared: Arc, +) -> Result<(), String> { + let address = std::net::SocketAddr::from(([127, 0, 0, 1], 0)); + serve_connection(Connection::local(pipe), address, shared) +} + +fn serve_connection( + mut c: Connection, + address: std::net::SocketAddr, + shared: Arc, +) -> Result<(), String> { + let e = |e: horizon_protocol::Error| e.to_string(); c.reader .set_read_timeout(Some(Duration::from_secs(30))) .map_err(e)?; diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 20a35cf8e..f4211c6ea 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -101,6 +101,9 @@ pub struct NetConfig { pub accepts_transfers: bool, /// LanServerPinger: announce the world on the local network. pub announce: bool, + /// Accept connections from the network. Without it only local ones + /// (`Lan::connect_local`): an integrated server not open to the LAN. + pub listen: bool, /// Ops bypass a full server (ServerOpList.canBypassPlayerLimit). pub bypasses_limit: Option bool + Send + Sync>>, pub gate: Option, @@ -120,6 +123,7 @@ impl NetConfig { enforces_secure_chat: false, accepts_transfers: false, announce: true, + listen: true, bypasses_limit: None, gate: None, } @@ -321,13 +325,21 @@ impl Lan { } /// ServerConnectionListener.startTcpServerListener with a configuration. pub fn start_with(sync: Arc, config: NetConfig) -> io::Result { - let bind = config - .bind - .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); - let listener = TcpListener::bind((bind, config.port))?; - listener.set_nonblocking(true)?; - let port = listener.local_addr()?.port(); - let _pinger = if config.announce { + let listener = if config.listen { + let bind = config + .bind + .unwrap_or(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED)); + let listener = TcpListener::bind((bind, config.port))?; + listener.set_nonblocking(true)?; + Some(listener) + } else { + None + }; + let port = match &listener { + Some(l) => l.local_addr()?.port(), + None => 0, + }; + let _pinger = if config.announce && listener.is_some() { discovery::Pinger::start(config.motd.clone(), port).ok() } else { None @@ -346,17 +358,37 @@ impl Lan { config, }); let accept_shared = shared.clone(); - let listener = std::thread::Builder::new() - .name("horizon-lan-accept".into()) - .spawn(move || accept_loop(listener, accept_shared))?; + let listener = listener + .map(|listener| { + std::thread::Builder::new() + .name("horizon-lan-accept".into()) + .spawn(move || accept_loop(listener, accept_shared)) + }) + .transpose()?; Ok(Self { shared, events, port, - listener: Some(listener), + listener, _pinger, }) } + /// `Connection.connectToLocalServer`: a connection through memory, its + /// server end served on its own thread like an accepted socket. + pub fn connect_local(&self) -> io::Result { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let shared = self.shared.clone(); + std::thread::Builder::new() + .name("horizon-local-conn".into()) + .spawn(move || { + if let Err(e) = conn::serve_local(server, shared) + && std::env::var_os("HORIZON_NET_DEBUG").is_some() + { + log::warn!("[lan] local: {e}"); + } + })?; + Ok(client) + } /// Everything the connection threads reported since the last call. pub fn poll(&self) -> Vec { self.events.try_iter().collect() diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index 047698e14..d260498a0 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -67,6 +67,25 @@ impl Session { auth: Option>, view_distance: i8, lang: Arc, + ) -> Self { + Self::start(address, name, auth, view_distance, lang, None) + } + /// Join an integrated server through memory (`Connection.connectToLocalServer`). + pub fn connect_local( + pipe: horizon_protocol::connection::Pipe, + name: &str, + view_distance: i8, + lang: Arc, + ) -> Self { + Self::start("local", name, None, view_distance, lang, Some(pipe)) + } + fn start( + address: &str, + name: &str, + auth: Option>, + view_distance: i8, + lang: Arc, + local: Option, ) -> Self { let (send, events) = channel(); let writer = Arc::new(Mutex::new(None)); @@ -77,6 +96,7 @@ impl Session { .name("horizon-net".into()) .spawn(move || { let result = run( + local, &address_owned, &name_owned, auth.as_deref(), @@ -222,6 +242,7 @@ fn tr(lang: &Language, key: &str) -> String { /// The whole connection. Ok: why it ended for good (the server's reason, or /// a refusal no retry fixes); Err: the connection failed. fn run( + local: Option, address: &str, name: &str, auth: Option<&AuthSession>, @@ -231,18 +252,23 @@ fn run( shared_writer: &Mutex>, shared_counters: &Mutex>>, ) -> Result { - let (host, port) = match address.strip_prefix(FRIEND) { - Some(code) => join_friend(code, send)?, - None => { - let Some(target) = parse_address(address) else { - return Ok(format!("Invalid server address: {address}")); - }; - status(send, "Connecting to the server..."); - target - } + let (host, port, mut c) = if let Some(pipe) = local { + (address.to_owned(), 0, Connection::local(pipe)) + } else { + let (host, port) = match address.strip_prefix(FRIEND) { + Some(code) => join_friend(code, send)?, + None => { + let Some(target) = parse_address(address) else { + return Ok(format!("Invalid server address: {address}")); + }; + status(send, "Connecting to the server..."); + target + } + }; + let c = + Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; + (host, port, c) }; - let mut c = - Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?; *shared_counters.lock().unwrap() = Some(c.reader.counters.clone()); let e = |e: horizon_protocol::Error| e.to_string(); c.send( diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index cac0ab60f..3c6087f2e 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -1,17 +1,163 @@ -//! A blocking TCP connection with vanilla's pipeline: optional AES/CFB8 +//! A blocking connection with vanilla's pipeline: optional AES/CFB8 //! encryption, VarInt21 framing and threshold compression. After login it -//! splits into a reader (for a receive thread) and a shareable writer. +//! splits into a reader (for a receive thread) and a shareable writer. It runs +//! over TCP, or over an in-memory pipe between two threads of one process +//! (vanilla's `LocalChannel`, which an integrated server's player uses). use crate::{Error, Result, buf::Reader, crypto::Cfb8, frame}; use std::{ io::{Read, Write}, net::{Shutdown, TcpStream, ToSocketAddrs}, sync::{ - Arc, + Arc, Condvar, Mutex, atomic::{AtomicI64, Ordering}, }, - time::Duration, + time::{Duration, Instant}, }; +/// One direction of a [`Pipe`]: the bytes written and not read yet, and +/// whether either end closed it. +#[derive(Default)] +struct Channel { + state: Mutex<(std::collections::VecDeque, bool)>, + ready: Condvar, +} +impl Channel { + fn close(&self) { + self.state.lock().unwrap().1 = true; + self.ready.notify_all(); + } +} +/// The channels of one end; dropping the end's last clone closes them, as +/// a socket closes with its process. +struct End { + incoming: Arc, + outgoing: Arc, +} +impl Drop for End { + fn drop(&mut self) { + self.incoming.close(); + self.outgoing.close(); + } +} +/// One end of an in-memory byte pipe: what one end writes the other reads. +pub struct Pipe { + end: Arc, + /// The read timeout (`set_read_timeout`). + timeout: Mutex>, +} +impl Pipe { + /// Two connected ends. + pub fn pair() -> (Self, Self) { + let (a, b) = (Arc::new(Channel::default()), Arc::new(Channel::default())); + let end = |incoming, outgoing| Self { + end: Arc::new(End { incoming, outgoing }), + timeout: Mutex::new(None), + }; + (end(a.clone(), b.clone()), end(b, a)) + } + fn try_clone(&self) -> Self { + Self { + end: self.end.clone(), + timeout: Mutex::new(*self.timeout.lock().unwrap()), + } + } + /// Close both directions: reads at either end then see the end of the stream. + pub fn shutdown(&self) { + self.end.incoming.close(); + self.end.outgoing.close(); + } +} +impl Read for Pipe { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + let deadline = self.timeout.lock().unwrap().map(|t| Instant::now() + t); + let mut state = self.end.incoming.state.lock().unwrap(); + while state.0.is_empty() && !state.1 { + state = match deadline { + None => self.end.incoming.ready.wait(state).unwrap(), + Some(deadline) => { + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err(std::io::ErrorKind::TimedOut.into()); + } + self.end.incoming.ready.wait_timeout(state, left).unwrap().0 + } + }; + } + let n = out.len().min(state.0.len()); + for (o, b) in out.iter_mut().zip(state.0.drain(..n)) { + *o = b; + } + Ok(n) + } +} +impl Write for Pipe { + fn write(&mut self, data: &[u8]) -> std::io::Result { + let mut state = self.end.outgoing.state.lock().unwrap(); + if state.1 { + return Err(std::io::ErrorKind::BrokenPipe.into()); + } + state.0.extend(data); + self.end.outgoing.ready.notify_all(); + Ok(data.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// What a connection runs over. +enum Stream { + Tcp(TcpStream), + Memory(Pipe), +} +impl Stream { + fn try_clone(&self) -> std::io::Result { + Ok(match self { + Self::Tcp(s) => Self::Tcp(s.try_clone()?), + Self::Memory(p) => Self::Memory(p.try_clone()), + }) + } + fn set_read_timeout(&self, timeout: Option) -> std::io::Result<()> { + match self { + Self::Tcp(s) => s.set_read_timeout(timeout), + Self::Memory(p) => { + *p.timeout.lock().unwrap() = timeout; + Ok(()) + } + } + } + fn shutdown(&self) { + match self { + Self::Tcp(s) => { + let _ = s.shutdown(Shutdown::Both); + } + Self::Memory(p) => p.shutdown(), + } + } +} +impl Read for Stream { + fn read(&mut self, out: &mut [u8]) -> std::io::Result { + match self { + Self::Tcp(s) => s.read(out), + Self::Memory(p) => p.read(out), + } + } +} +impl Write for Stream { + fn write(&mut self, data: &[u8]) -> std::io::Result { + match self { + Self::Tcp(s) => s.write(data), + Self::Memory(p) => p.write(data), + } + } + fn flush(&mut self) -> std::io::Result<()> { + match self { + Self::Tcp(s) => s.flush(), + Self::Memory(p) => p.flush(), + } + } +} + /// Packets received/sent and bytes in/out, for the debug screen. #[derive(Debug, Default)] pub struct Counters { @@ -22,14 +168,14 @@ pub struct Counters { } pub struct ConnReader { - stream: TcpStream, + stream: Stream, buffer: Vec, decrypt: Option, pub threshold: Option, pub counters: Arc, } pub struct ConnWriter { - stream: TcpStream, + stream: Stream, encrypt: Option, pub threshold: Option, counters: Arc, @@ -56,6 +202,13 @@ impl Connection { } pub fn from_stream(stream: TcpStream) -> Result { stream.set_nodelay(true)?; + Self::over(Stream::Tcp(stream)) + } + /// A connection over one end of an in-memory [`Pipe`]. + pub fn local(pipe: Pipe) -> Self { + Self::over(Stream::Memory(pipe)).expect("a pipe end clones") + } + fn over(stream: Stream) -> Result { let counters = Arc::new(Counters::default()); let write = stream.try_clone()?; Ok(Self { @@ -144,7 +297,7 @@ impl ConnWriter { Ok(()) } pub fn shutdown(&self) { - let _ = self.stream.shutdown(Shutdown::Both); + self.stream.shutdown(); } } @@ -184,6 +337,47 @@ mod tests { server.join().unwrap(); } + #[test] + fn local_pipe_carries_packets_and_closes() { + let (a, b) = Pipe::pair(); + let server = std::thread::spawn(move || { + let mut c = Connection::local(b); + c.set_compression(64); + let (id, payload) = c.recv().unwrap(); + assert_eq!((id, payload.len()), (5, 1000)); + c.send(&[9, 1, 2]).unwrap(); + let (_, writer) = c.split(); + writer.shutdown(); + }); + let mut c = Connection::local(a); + c.set_compression(64); + let mut big = vec![5]; + big.extend(std::iter::repeat_n(3u8, 1000)); + c.send(&big).unwrap(); + assert_eq!(c.recv().unwrap(), (9, vec![1, 2])); + server.join().unwrap(); + assert!(c.recv().is_err()); + } + + #[test] + fn dropping_a_pipe_end_closes_it() { + let (a, b) = Pipe::pair(); + let mut c = Connection::local(a); + drop(b); + assert!(c.recv().is_err()); + assert!(c.send(&[1]).is_err()); + } + + #[test] + fn local_pipe_read_times_out() { + let (a, _b) = Pipe::pair(); + let mut c = Connection::local(a); + c.reader + .set_read_timeout(Some(Duration::from_millis(20))) + .unwrap(); + assert!(c.recv().is_err()); + } + /// Encrypted bytes that arrive in the same read as the last plain packet /// are decrypted once encryption is enabled. #[test] From 9c03535011dedea6cb7f87f6d64fa957c94a8678 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:22:56 +0200 Subject: [PATCH 22/23] docs/server.md: hosting a Horizon server, the design What the dedicated server does today (measured against vanilla 26.3), the horizon-server supervisor and its packaging, server.toml, the CLI and TUI, the web panel, backups and updates, the control API and MCP, the bot benchmark plan against vanilla and Paper, the working version for 2026-10-23, and the PRs that build it (#551 to #556). Co-Authored-By: Claude Opus 5.5 --- docs/README.md | 1 + docs/server.md | 522 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 523 insertions(+) create mode 100644 docs/server.md diff --git a/docs/README.md b/docs/README.md index af78b7f01..7cf322042 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,6 +6,7 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. +- [Hosting a server](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. - [Agent control](agent-control.md): what AI agents can drive in the launcher and the game, and the design of the control socket, `horizon-ctl` and MCP. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 000000000..6e165f534 --- /dev/null +++ b/docs/server.md @@ -0,0 +1,522 @@ +# Hosting a Horizon server: design + +Horizon's dedicated server should be the easiest and lightest Minecraft 26.3 server to host. It should be one +small native program with no Java and no Python, one command to install it, one config file, and a CLI, a web +panel and a control API to manage it. At the same view and simulation distance and with the same players, it +should beat vanilla, Paper and Fabric + Lithium on TPS/MSPT, RAM, CPU, chunk generation and start time. +Gameplay stays vanilla: there are no Paper-style rule changes unless the owner turns one on. + +This page covers what the server does today (measured), the design of `horizon-server`, and what ships for the +first working version (2026-10-23). It replaces the Java/Fabric starter (`docs/server-quickstart.txt`, +`tools/server.py`), which goes once the benchmark below exists. + +## 1. Today + +### How it runs + +The dedicated server is the game itself, run headless: +`horizon-client --resources --dedicated [--nogui] [--port N] [--world NAME] [--universe DIR] +[--initSettings]`, started in the server folder (`crates/horizon-client/src/game/dedicated.rs`). + +- **Startup.** It follows vanilla's `Main.main` and `DedicatedServer.initServer`. It reads `server.properties` + and writes it straight back with vanilla's defaults filled in (`horizon_client::server`, byte-exact with + vanilla's `Properties.store`), and refuses to start until `eula.txt` says `eula=true`. It then loads the + operator, whitelist and ban lists in vanilla's order and format, and opens `/` with + the same `Game` as single player, minus the local player. +- **Network.** Players join through the play-state hub that Open to LAN uses (`crates/horizon-client/src/lan`). + Status ping, legacy ping, compression, login gate (bans, whitelist, IP bans), operator permission levels, + the player limit with `bypassesPlayerLimit`, MOTD and `server-icon.png` all follow `server.properties`. +- **Main loop.** It ticks at 20 TPS on one thread, with chunk generation and lighting on the worker pool. + Chunks stay loaded around every player (`lan_update_streaming`), or around the spawn while nobody is + online. It supports `pause-when-empty-seconds`, `player-idle-timeout` and the autosave. +- **Console (stdin).** `stop`, `save-all`, `save-on`/`save-off`, `list [uuids]`, `op`/`deop`, + `whitelist on|off|list|reload|add|remove`, `ban`, `ban-ip`, `pardon`, `pardon-ip`, `banlist`, `kick` and + `say` behave as in `DedicatedServer`. Every other command goes to the game's own dispatcher as the server + (permission level 4). The log follows vanilla's Log4j pattern, in `logs/latest.log` and on stdout. + +### Measured (2026-10-16, Mac mini M4 Pro, main at bd8dff20, release build) + +The server ran in a scratch folder with `online-mode=false`, `level-seed=12345` and view and simulation +distance 10. The vanilla server was the pinned 26.3 `server.jar` on Java 25 with `-Xmx4G`. + +| | Horizon (`horizon-client --dedicated`) | Vanilla 26.3 | +|---|---|---| +| Start, new world (wall clock, to `Done`) | 11.4 s (`Done (9.762s)`) | 12.5 s (`Done (2.066s)`, includes the bundler's first unpack) | +| Start, existing world (wall clock) | **5.8 s** (resources load in 1.6 s) | 10.7 s (`Done (0.446s)`: the JVM and DataFixerUpper take the rest) | +| RAM, idle with nobody online (RSS) | 1.40–1.51 GB | **0.93–0.97 GB** | +| CPU, idle with nobody online | 1.2 % of one core | **0.6 %** | +| `stop` to exit | 0.6 s | 0.6 s | +| What has to be installed | one 46.8 MB binary + 589 MB of prepared resources | Java 25 + the 62 MB jar | +| Crates linked | 384 (wgpu, winit, cpal, gilrs, arboard, naga…) | n/a | + +On Linux the binary loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup, even on a server. +wgpu, winit and the Wayland/X11 libraries are loaded only when a window opens. That makes a minimal +container image need ALSA and udev for a program that never plays a sound or reads a controller. + +The two clear losses are RAM and idle CPU. The dedicated server loads everything the client needs to draw +(the HUD atlas, item renderer, block-entity models, panorama, fog and music tables, entity models), and it +builds the meshing tables at startup. None of these are used without a window. Loading them is startup work, +not tick cost, so it is in scope here (see section 9). + +### Joining it + +- **Horizon client:** works. A headless Horizon client (`--server 127.0.0.1:PORT`, the harness mode) logged + in, received its 49 chunks at render distance 2, chatted, saw `/list`, and left. The server's log matched + vanilla's lines (`logged in with entity id`, `joined the game`, `[Not Secure] …`, `lost connection: + Disconnected`, `left the game`). +- **Vanilla 26.3 client:** checked by `tools/test_dedicated_server_parity.py`. VanillaProtocolClient, a + headless client built from vanilla's own codecs, pings and joins Horizon's server and vanilla's from the + same world copy. It compares every login, configuration and play packet up to the first chunk batch, the + chunk bytes, chat, `/list`, failing commands, the console lines and the files left behind. Result on main: + see "Harnesses on main" below. The real vanilla GUI client (`tools/vanilla_client.py`) could not be run + here: the tool only knows Linux natives, and the Mac mini's session was locked, which stalls the client's + rendering. It runs on the desktop under vscreen. + +### What fails or is missing + +| Area | Status | +|---|---| +| `online-mode=true` | **Not supported.** The server logs a warning and runs offline: no session `hasJoined` check, no encryption, no secure chat. (The client side of online mode works and is tested by `test_online_mode_parity.py` against vanilla's server.) A public server must not run like this. This is the top engine item. | +| Nether and End | **Players can't change dimension.** The engine keeps one dimension loaded (`Game::enter_dimension` moves only the local single-player player), and the hub serves one `dimension` to everyone. | +| Refused logins | Nothing is logged. Vanilla logs `Disconnecting : ` (`ServerLoginPacketListenerImpl.disconnect`) and ` lost connection: …`. | +| Gameplay for remote players | The LAN guest leftovers apply: an item used on a block is used twice, the recipe book doesn't work, status effects don't apply to guests, arrows don't record their owner, team friendly fire is ignored (#484). Block desync and short freezes are reported on a same-machine server (#500). | +| Defaults that surprise owners | `white-list=true` is vanilla 26.3's default, so a fresh server refuses everyone until they are added. That matches vanilla, so the first-run flow (section 3) asks about the whitelist up front. | +| Management | Only stdin. There is no service, no backups, no status beyond `list`, no restart after a crash, and a server can't be managed while it runs in the background. | +| Packaging | The server is the full game client. Resources come from `horizon-prepare`, which needs a JDK and the official launcher's client install, both awkward on a headless VPS. | +| Tick times | The dedicated loop never recorded its tick times in the game clock (only the windowed loop did), so `/tick query` on a dedicated server reported 0 ms. Fixed in PR 2b, which the benchmark needs (section 9). | +| Scale | Not measured with more than one player. The tick is single-threaded, and each remote player costs the hub one tracking and chunk-sending pass. | + +### Harnesses on main + +On the tip of the code PRs (2a to 3, rebased on b4ad6538), `tools/parity.py dedicated_server online_mode +server_files server_player_combat server_player_damage` passed all five. That includes the vanilla protocol +client joining Horizon's server and vanilla's from the same world. The full `--changed origin/main` set +(309 harnesses, since the PRs touch the client crate) had passed 60 of 60 when it was stopped for disk +space; CI runs it on every pull request. + +## 2. Architecture: a supervisor and an engine + +``` + owner ──► horizon-server (CLI, TUI) browser ──► web panel AI ──► MCP (stdio) + │ │ │ + └────────── control API: HTTP + JSON on 127.0.0.1, token ────────┘ + │ + horizon-server run (the supervisor: no GPU, no game code) + server.toml ──► server.properties ──► │ ◄── stdout: the vanilla log + backups, updates, crash restart │ ──► stdin: console commands + │ ◄─► engine endpoint: status, TPS/MSPT, players + ▼ + the engine: horizon-client --dedicated (the game, headless) +``` + +`horizon-server` is a new crate and binary (`crates/horizon-server`). It is the only program an owner runs. +It depends only on the light crates (`horizon-core`, `horizon-protocol`, `horizon-world`, `horizon-bench`) +plus `serde`, `toml`, `toml_edit` and `zip`, which are already in the lockfile. It doesn't link wgpu, winit, +audio or controller crates. It runs the engine as a child process. + +The supervisor/engine split stays even after the engine becomes headless, for these reasons: + +- **Crash restart and diagnostics.** The supervisor outlives an engine crash. It keeps the crash report, + restarts the engine with backoff, and the panel stays up to say what happened. +- **Safe updates.** An update swaps the engine binary and restarts. If the new engine fails its start check, + the supervisor rolls back to the previous one. +- **Parity stays cheap.** The engine keeps reading vanilla's own files (`server.properties`, the four JSON + lists, `eula.txt`) exactly as `test_dedicated_server_parity.py` checks them today. The clean config is a + layer on top and never changes what the engine sees. +- **No conflicts.** The supervisor touches none of the game code that the tick and integrated-server work + (perf-server-1, perf-ticks-2) are changing. + +**The engine today** is `horizon-client --dedicated`. It needs one small, additive change: a status endpoint. +With `--control-socket /.horizon/engine.json` (the existing control protocol: TCP on 127.0.0.1 plus a token, on +every OS), the dedicated loop answers `server-status` with TPS, MSPT (average, P50/P95/P99 from the tick +clock `/tick query` uses), players (name, UUID, address, ping), loaded chunks and uptime. It answers +`console ` with the command's output. + +**The headless engine** comes after perf-ticks-2's work lands: Resources split into shared and per-game, the +game built in `Game::new`, the integrated server on its own thread. On that base: + +1. The dedicated path skips everything only a window uses: the HUD atlas, item renderer, block-entity and + entity models, panorama, fog, music, and mesh tables (perf-ticks-2 already stops server-side meshing). + This is the RAM and start-time item. +2. The game moves into a library crate, with the window, audio and controller parts behind a `client` + feature. A `horizon-engine` binary built without that feature links no wgpu, winit, cpal or gilrs, and + needs neither ALSA nor udev. The supervisor finds it beside itself and falls back to `horizon-client`. + +## 3. Packaging + +**Binaries.** The release archives already hold `horizon-client`, `horizon-ctl` and `horizon-prepare`. +`horizon-server` joins them (PR 3: `xtask package` and `release.yml` build it and check it starts). Once +`horizon-engine` exists (section 2), a separate small archive per platform +(`horizon-server--.tar.gz` or `.zip`) holds just the server's binaries. + +**Game files: the owner's own copy, as with `prepare`.** Nothing of Mojang's is redistributed and nothing is +downloaded on the owner's behalf. `horizon-server` looks for prepared resources in this order: + +1. `[engine] resources` in `server.toml`; +2. `resources/` in the server folder; +3. `.local/horizon-client/26.3` beside the engine or up to four folders above it: a release folder, the + installer's `game-files` (below), or a checkout. + +If none is found, `init` says where it looked. Today the owner runs `horizon-prepare --prepare --server-jar +PATH` from the release folder (it needs a JDK and the client files, as for playing), or copies a folder +prepared on their own computer to the server (`scp -r`). Planned wrappers: + +- **On this machine:** `horizon-server prepare --server-jar PATH` runs `horizon-prepare` on the owner's own + server jar plus their launcher install. +- **Prepared elsewhere:** `horizon-server import-resources DIR` copies a folder prepared on the owner's own + computer, for example by the launcher, to a headless machine. + +A server-only `prepare` (from `server.jar` alone, without the client jar or a JDK) is the follow-up that +removes the last Java step. It needs a list of which prepared files the server really reads, and that list +comes out of the headless-engine work. + +**One-command install** (`packaging/server/`): + +- Linux and macOS: + `curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh` + The script picks the release archive for the OS and architecture (Linux x86_64, macOS arm64), downloads + it from GitHub Releases, and checks it against the SHA-256 GitHub publishes for each asset. It never asks + for sudo. Options: `--version vX.Y.Z`, `--dir` (default `~/.local/share/horizon`), `--bin` (default + `~/.local/bin`). +- Windows: + `irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex` + The script does the same into `%LOCALAPPDATA%\Horizon` (`-Version`, `-Dir`), with junctions instead of + links (no admin rights), and adds `bin` to the user's PATH. +- **Layout.** Each release goes to `/releases/` and `/current` points at the one in use, so an + update or a rollback is one link. `/horizon-server` and `/horizon-prepare` are two-line launchers + that run `current`. The prepared game files live in `/game-files/horizon-client` and each release's + `.local/horizon-client` links there, so updates keep them. The script then prints the next steps + (`horizon-prepare`, `horizon-server init`). + +**Docker** (`packaging/server/Dockerfile`, built the same way as the relay's image): a multi-stage build that +ends on `debian:bookworm-slim` as user `horizon`. It adds `libasound2` and `libudev1` until the headless engine +lands. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only +mount on `/opt/horizon/.local/horizon-client/26.3`, exposes port `25565/tcp`, and keeps the control API (and +later the panel) on 127.0.0.1 inside the container: `docker exec horizon-server status|cmd|backup`. +On the first start, `HORIZON_EULA=true` and `HORIZON_WORLD`, `HORIZON_SEED`, `HORIZON_PORT`, +`HORIZON_WHITELIST`, `HORIZON_PLAYERS` and `HORIZON_OP` answer `init`'s questions; without the EULA answer +the container exits and says why. `docker stop` sends SIGTERM, which saves and stops cleanly (give it +`--stop-timeout 180`). The image is published only with Ludovic's OK (it's hosted infrastructure). + +**Services.** + +- `horizon-server service install` writes and enables a systemd unit (`--user`, or a system unit with + `--system`) on Linux, a launchd agent (`~/Library/LaunchAgents/dev.horizon.server..plist`) on + macOS, or a Scheduled Task at logon on Windows (a real Windows service needs a wrapper and comes later). +- Each runs `horizon-server run --dir ` through the installer's launcher, so an update applies at the + next restart. The supervisor restarts the engine itself, and the service manager restarts the supervisor. + `service uninstall` stops and removes it and leaves the server folder alone. +- `service print` shows the unit or agent it would write, for owners who'd rather install it by hand. + +**First run (`horizon-server init`, interactive on a terminal):** + +1. **EULA.** It shows the link to https://aka.ms/MinecraftEULA and asks "Do you agree? [y/N]". Only a yes + writes `eula=true`. +2. **World.** It asks for the world name (`world`) and an optional seed. An existing world folder, or a + vanilla server folder, is detected and kept: its `server.properties` is imported (section 4). +3. **Port.** 25565 by default, checked free right away. +4. **Players.** It asks whether to use a whitelist (yes by default, as vanilla) and who to add first, then + offers to make the first player an operator. +5. **Game files.** It finds or explains the prepared resources (see above). +6. It writes `server.toml`, shows the panel address and the commands to start it in the background + (`horizon-server start`) or as a service. + +Every question has a flag (`--eula`, `--world`, `--seed`, `--port`, `--whitelist`/`--no-whitelist`, +`--player NAME`, `--op NAME`, `--yes`) and an environment variable for Docker (`HORIZON_EULA`, …; flags win). + +## 4. One config file: `server.toml` + +The owner edits only `server.toml`. The supervisor writes `server.properties` from it before every engine +start, so the engine stays exactly vanilla. The file is short: typed sections for what owners change, and +a `[properties]` table that passes any other vanilla key through unchanged. + +```toml +# Horizon server settings (docs/server.md). The server writes them into server.properties before +# every start: edit this file, not that one. + +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # not supported by Horizon yet: the server runs offline and says so +whitelist = true # only whitelisted players and operators can join +enforce_whitelist = false # kick online players taken off the whitelist +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" # the world folder +seed = "" # empty: a random seed on the first start +game_mode = "survival" # survival, creative, adventure or spectator +difficulty = "easy" # peaceful, easy, normal or hard +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it, for example: +# spawn-protection = 16 +[properties] + +[engine] +path = "" # the game program; empty: the one installed beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true + +[backups] +every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off +keep = 12 # automatic backups kept (backups made by hand are never deleted) +``` + +This is the file `init` writes today (PR 4 adds `[panel] bind = "127.0.0.1:8130"` and `allow_public = +false`, section 6). The defaults are vanilla 26.3's (a test checks each one). Unknown keys are errors, as are +a typed key set again under `[properties]` and values vanilla would refuse. Planned: `backups.before_update` +(section 7). + +- **Import.** `horizon-server init` in a folder with a `server.properties`, or `horizon-server import + server.properties`, reads it with vanilla's own parser (`ServerProperties`). Keys with typed fields go into + their sections; any other key that differs from vanilla's default goes into `[properties]`. Keys left at + their defaults are dropped, so the TOML stays short. The original file is kept as + `server.properties.imported`. +- **Changes made in game.** The engine writes `server.properties` itself, for example after `/whitelist on`. + After it stops, the supervisor compares the file with what it wrote and copies any changed keys back into + `server.toml`, so an in-game change survives the next start. Edits go through `toml_edit`, so the owner's + comments and order are kept. +- **Reload (planned).** The four lists already reload through the engine (`whitelist reload`). `reload` will + send what can change live and say which settings need a restart. A real hot reload (view distance, MOTD) needs engine + support and comes later. +- `server.properties`, `ops.json`, `whitelist.json`, `banned-*.json` and `world/` keep vanilla's names and + formats. A vanilla server folder works as is, and so does going back to vanilla. + +## 5. CLI and TUI + +``` +horizon-server init first run (section 3) +horizon-server run supervisor + engine in the foreground; the console on stdin +horizon-server start | stop | restart in the background (detached `run`); each waits for the game +horizon-server status [--json] up?, uptime, TPS, MSPT, players, RAM, CPU, crashes +horizon-server cmd one console command, with its output +horizon-server logs [-f] [-n N] +horizon-server op|deop +horizon-server whitelist on|off|list|add|remove [player] +horizon-server backup [NAME] backups restore [--yes] +horizon-server import +horizon-server service install|uninstall|print [--system] +horizon-server panel the panel's address and a one-time login link + +Planned: +horizon-server console attach: the live log, and send commands (Ctrl-D detaches) +horizon-server ban|pardon [reason] ban-ip|pardon-ip
(`cmd ban …` works now) +horizon-server update [--check] [--version vX.Y.Z] rollback +horizon-server import-resources prepare --server-jar PATH +horizon-server mcp MCP server on stdio (section 8) +``` + +- Every command takes `--dir` (the server folder; default: the current folder). +- While the server runs, management commands go through the control API, so the engine applies them as + vanilla's console would and its lists stay right. While it's stopped, they edit the vanilla files directly + with the same code the engine uses (`horizon_server_files::user_lists`). +- **The TUI** is `horizon-server console`: the log, a one-line header (TPS, MSPT, players, RAM) that updates + every second, and a command line. It uses plain ANSI with no TUI framework, and falls back to plain lines + when stdout isn't a terminal. + +## 6. Web panel + +**Scope (MVP, PR 4):** status (phase, uptime, version, crashes), live TPS, MSPT, RAM and CPU graphs (the last +10 minutes, sampled once a second), players (list with ping, op, kick), the console (live log plus a command +line), and backups (list, back up now, restore with confirmation), with restart and stop. The panel lives in +the supervisor, so it is up exactly when the server is: starting a stopped server stays a command (or the +service manager's job). Whitelist and bans go through the console for now. + +**Later:** bans and IP bans, worlds, updates with rollback, `server.properties` import, logs and crash +reports, and modpacks (with the modpack work). + +**Tech:** one HTML page with plain JS and CSS (`crates/horizon-server/panel/`), embedded in the binary with +`include_str!`. No build step, no framework, no CDN. It uses Horizon's design system tokens (`horizon-theme`'s +colours, light and dark) and draws charts on a canvas. It polls the control API's routes once a second +(`status`, `metrics?since=`, `logs?since=`), served by the same small HTTP code on `std::net`, with no async +runtime or new dependency. Server-sent events can replace the polling later if a tab ever costs too much. + +**Auth: local or tailnet only, never an open admin port.** + +- **Bind.** The panel listens on `127.0.0.1:8130` by default. `panel.bind` can name a tailnet address + (100.64.0.0/10 or Tailscale's fd7a:115c:a1e0::/48) or another loopback address. Any other address, such as + 0.0.0.0 or a public IP, is refused unless `panel.allow_public = true` is set, and even then the panel logs + a warning at every start. +- **Who may act.** The API token in `.horizon/api.json` (file mode 0600) is what the CLI and MCP use. Browsers + get a one-time login link from `horizon-server panel`: a code good for 10 minutes, swapped for an + `HttpOnly; SameSite=Strict` session cookie. Anyone who can read the server folder can manage the server, + and no one else can. Sessions end when the supervisor stops. +- **Protection.** The `Host` header must name the panel itself: its address, `localhost` on loopback, or a + tailnet name (a MagicDNS short name or `*.ts.net`). That stops DNS rebinding. Changes are POST only and need + the `X-Horizon: 1` header, which stops CSRF. After 10 failed logins in a minute, logins are refused for a + while. The page is served with a strict Content-Security-Policy (nothing from elsewhere) and can't be + framed. +- **Remote access** goes over Tailscale/SSH (`ssh -L 8130:127.0.0.1:8130 host`), with no TLS or passwords to + manage. HTTPS comes for free with `tailscale serve`, and the doc shows how to set it up. + +## 7. Backups, updates and crash restart + +- **Backups.** The supervisor runs `save-off`, then `save-all flush`, then zips the world plus the vanilla + files and `server.toml` into `backups/-.zip`, then runs `save-on`. Players stay online. Zip + works for everyone, Windows included. It runs on the `every` schedule and on demand (later also before an + update). It keeps the last `keep` automatic backups and never deletes one made by hand. A backup is written + to a temporary name and renamed when complete, so a crash never leaves a half-written backup that looks + finished. A stopped server is backed up straight from its files. +- **Restore.** `restore NAME` takes a file name, a unique prefix, or the name given to `backup` (the newest + with it). The server stops. The current world is moved to `backups/replaced-