diff --git a/Cargo.lock b/Cargo.lock index 68d0b250d..6ebc69964 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", @@ -1497,6 +1498,19 @@ dependencies = [ "horizon-mod-sdk", ] +[[package]] +name = "horizon-port-pack" +version = "0.1.0" +dependencies = [ + "horizon-mods", + "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-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), 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/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/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/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 21f59af94..fec643d30 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; @@ -56,6 +57,7 @@ mod golems; mod growth; mod hand; mod initial_spawn; +mod integrated; mod item_draw; mod item_particles; mod jukebox; @@ -203,6 +205,7 @@ use winit::{ window::{CursorGrabMode, Window, WindowId}, }; +#[derive(Clone)] struct Options { resources: PathBuf, distance: i32, @@ -242,6 +245,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 @@ -293,6 +301,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); @@ -313,6 +323,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() @@ -642,46 +653,95 @@ 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>, } +/// 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 +765,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, @@ -1017,6 +1085,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, @@ -1170,7 +1240,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 +1438,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)) @@ -1382,7 +1452,7 @@ impl Game<'_> { let layer = face .map(|face| face.layer) .or_else(|| models.iter().find_map(|(_, model)| model.particle))?; - let name = self.res.layer_names.get(&layer)?.clone(); + let name = self.pack.layer_names.get(&layer)?.clone(); let tint = if face.is_some_and(|face| face.quad.tint_index >= 0) { let n = &self.res.facts.get(state).name; if n.contains("leaves") || n.contains("vine") { @@ -1398,7 +1468,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]) @@ -1471,7 +1541,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) => { @@ -1552,7 +1622,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. @@ -1688,7 +1758,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, @@ -1904,6 +1974,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, @@ -1956,6 +2027,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, }); } @@ -2211,14 +2287,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 { @@ -2252,30 +2333,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() } @@ -3183,7 +3242,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, } @@ -3579,7 +3638,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!( @@ -3630,7 +3689,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() @@ -3725,10 +3784,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); @@ -3736,7 +3795,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 } @@ -3757,12 +3816,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"), @@ -3770,7 +3829,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; @@ -3799,7 +3858,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 { @@ -3811,7 +3870,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 { @@ -3833,7 +3892,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); @@ -3849,7 +3908,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, @@ -3910,7 +3969,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) @@ -3925,9 +3984,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, @@ -4113,7 +4172,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(), } } @@ -4143,7 +4204,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, @@ -4152,7 +4213,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, @@ -4168,7 +4229,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.res.atlas; + let atlas = &self.atlas; batch.fill( atlas, 0.0, @@ -4299,7 +4360,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, @@ -4410,8 +4471,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); @@ -5325,7 +5386,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, @@ -5347,7 +5408,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, @@ -5370,7 +5431,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, @@ -5389,7 +5450,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, @@ -5414,7 +5475,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; @@ -5469,7 +5530,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])) { @@ -5477,7 +5538,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). @@ -5521,7 +5582,7 @@ impl Game<'_> { } if let Some(mining) = &self.mining && mining.progress > 0.0 - && self.res.atlas.sprites.contains_key(&format!( + && self.atlas.sprites.contains_key(&format!( "block/destroy_stage_{}", ((mining.progress * 10.0) as u32).min(9) )) @@ -5536,7 +5597,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") @@ -5648,7 +5708,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 @@ -5668,13 +5728,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]) @@ -5947,11 +6007,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)?; } } @@ -5992,7 +6052,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()) @@ -6089,8 +6149,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; @@ -6294,14 +6357,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, ) }); @@ -6310,26 +6373,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())); @@ -6337,10 +6400,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, ) }; @@ -6352,6 +6415,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 @@ -6365,7 +6430,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) { @@ -6490,7 +6555,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); }; @@ -6547,6 +6612,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); @@ -6763,7 +6833,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) @@ -6855,7 +6925,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, @@ -6909,7 +6979,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); @@ -7089,7 +7159,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) @@ -7114,7 +7184,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() @@ -7463,13 +7533,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) @@ -7539,7 +7603,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)); @@ -7596,7 +7660,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, @@ -7606,16 +7670,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() @@ -7736,7 +7795,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(), @@ -7824,7 +7883,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) @@ -7925,7 +7984,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)); @@ -7947,7 +8006,7 @@ impl Game<'_> { ) }; batch.fill( - &self.res.atlas, + &self.atlas, 0.0, 0.0, batch.width, @@ -7958,7 +8017,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 { @@ -7968,13 +8027,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 { @@ -7990,7 +8049,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, @@ -8032,7 +8091,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, @@ -8043,7 +8102,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, @@ -8052,8 +8111,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 { @@ -8066,7 +8125,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.clone()); } } @@ -8085,14 +8144,14 @@ impl Game<'_> { hovered = Some(stack); } } - 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(), @@ -8174,7 +8233,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; } @@ -8293,7 +8352,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(); } @@ -8311,6 +8370,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())); @@ -8401,7 +8461,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]) @@ -8556,10 +8616,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, @@ -8586,15 +8646,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]) @@ -8602,7 +8661,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() { @@ -8654,7 +8713,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. @@ -8926,7 +8985,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}"); @@ -9043,6 +9102,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, .. @@ -9130,7 +9203,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; @@ -9185,7 +9258,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 @@ -9234,7 +9307,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() { @@ -9624,6 +9697,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 @@ -9752,6 +9828,324 @@ 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, + integrated: 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(()); @@ -9764,6 +10158,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 @@ -9794,24 +10193,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)?; @@ -9819,12 +10210,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", @@ -9834,49 +10219,25 @@ 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)?), - 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)?; - 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, @@ -9886,37 +10247,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(); - ( - 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 @@ -9929,277 +10273,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, &resources.atlas.sprites); - let mut game = Game { - res: &mut resources, - collision: &collision, - motion: &motion, - 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 @@ -10341,6 +10415,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..076c2fbef 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 { @@ -2985,6 +2985,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/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/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index cd7744d87..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() @@ -525,7 +526,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 +542,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/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/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/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/integrated.rs b/crates/horizon-client/src/game/integrated.rs new file mode 100644 index 000000000..6edbb6e40 --- /dev/null +++ b/crates/horizon-client/src/game/integrated.rs @@ -0,0 +1,289 @@ +//! 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 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 +//! 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::connection::Pipe; +use horizon_protocol::{crypto::offline_uuid, text::translatable}; +use std::{ + 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 can be joined, then join it through memory. + 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 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_local(pipe, &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 { + // 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, + 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 pipe = { + 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.hub.lan.connect_local()? + }; + let _ = ready.send(Ok(pipe)); + 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/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..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. @@ -440,7 +451,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)?; @@ -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; } @@ -886,7 +932,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..5a1131c3b 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) { @@ -230,7 +284,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 +305,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 599399b96..4a80bee48 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -110,43 +110,31 @@ 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); + 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())); self.audio.reload(root); @@ -159,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..96d879f13 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()))), }); } @@ -506,7 +501,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 +523,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()) @@ -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/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..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,16 +176,26 @@ 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), - self.res.context.clone(), + self.pack.context.clone(), self.res.threads, ); streaming.remote = true; @@ -274,11 +300,19 @@ 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(); 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; @@ -296,6 +330,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, @@ -465,7 +504,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 +1584,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 +1595,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 +1603,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 +1845,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 +2780,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 +2805,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 5e8952901..c9e9a5317 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, @@ -1881,16 +1881,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)); @@ -2037,7 +2037,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)) @@ -2141,14 +2141,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 f0de6ad9e..459aab503 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -16,10 +16,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 { @@ -30,7 +30,7 @@ impl Game<'_> { Some(HeldName { item: stack.item.to_string(), hover_name: Text::literal(item_tooltip::name_line(stack, &|key| { - self.res.names.get(key).map(str::to_owned) + self.pack.names.get(key).map(str::to_owned) })), rarity_color: match rarity { "uncommon" => text::YELLOW, @@ -54,9 +54,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/gfx.rs b/crates/horizon-client/src/gfx.rs index 073643809..4401ea22d 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -62,6 +62,7 @@ mod java_stages; mod occlusion; mod pack_stages; pub mod panorama; +mod resident; mod timing; pub(crate) mod upload; mod world_post; @@ -98,8 +99,6 @@ struct SectionGpu { /// The solid quads by facing: back-facing groups are skipped. faces: crate::mesher::FaceGroups, } -/// A visible section this frame: key, squared distance, camera-relative origin. -type Visible = (SectionKey, f64, [f32; 3]); /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; pub struct Frame<'a> { @@ -310,7 +309,7 @@ pub struct Renderer { instance_capacity: u64, outline: wgpu::Buffer, depth: wgpu::TextureView, - sections: HashMap, + sections: resident::Resident, arena: arena::Arena, /// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws. indirect: wgpu::Buffer, @@ -318,7 +317,7 @@ pub struct Renderer { /// Indirect draws may set `first_instance` (the section origin). pub multi_draw: bool, /// Per-frame scratch, kept to avoid allocating every frame. - visible: Vec, + visible: Vec, origins: Vec<[f32; 4]>, /// `DrawIndexedIndirectArgs` words: index count, instance count, first /// index, base vertex, first instance. @@ -395,6 +394,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 +455,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 { @@ -1576,7 +1592,7 @@ impl Renderer { instance_capacity, outline, depth, - sections: HashMap::new(), + sections: resident::Resident::default(), arena, indirect, indirect_capacity: 1024, @@ -1723,7 +1739,7 @@ impl Renderer { self.sections.len() } pub fn has_section(&self, key: SectionKey) -> bool { - self.sections.contains_key(&key) + self.sections.contains(key) } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); @@ -1792,7 +1808,7 @@ impl Renderer { } } fn release_section(&mut self, key: SectionKey) { - if let Some(s) = self.sections.remove(&key) { + if let Some(s) = self.sections.remove(key) { self.arena .release(s.page, s.start, u64::from(s.solid + s.translucent) * 4); } @@ -2199,34 +2215,13 @@ impl Renderer { let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); visible.clear(); - visible.extend( - self.sections - .keys() - .filter(|&&k| !culling || reachable.contains(k)) - .filter_map(|&(sx, sy, sz)| { - let origin = DVec3::new( - f64::from(sx * 16), - f64::from(crate::chunk::MIN_Y + sy * 16), - f64::from(sz * 16), - ) - camera; - let center = origin + DVec3::splat(8.0); - let horizontal = (center.x * center.x + center.z * center.z).sqrt(); - if horizontal > f64::from(frame.distance) + 24.0 { - return None; - } - let min = origin.as_vec3(); - let max = min + Vec3::splat(16.0); - if !view.intersects(min, max) { - return None; - } - Some(( - (sx, sy, sz), - center.length_squared(), - origin.as_vec3().to_array(), - )) - }), + self.sections.visible( + camera, + frame.distance, + &view, + |k| !culling || reachable.contains(k), + &mut visible, ); - visible.sort_unstable_by(|a, b| a.1.total_cmp(&b.1)); self.drawn_sections = visible.len(); if visible.len() as u64 > self.instance_capacity { self.instance_capacity = (visible.len() as u64).next_power_of_two(); @@ -2238,8 +2233,11 @@ impl Renderer { }); } self.origins.clear(); - self.origins - .extend(visible.iter().map(|(_, _, o)| [o[0], o[1], o[2], 0.0])); + self.origins.extend( + visible + .iter() + .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]), + ); if !self.origins.is_empty() { self.uploads.buffer( &mut encoder, @@ -2259,18 +2257,18 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); - for (i, (key, _, origin)) in visible.iter().enumerate() { - let s = &self.sections[key]; + for (i, v) in visible.iter().enumerate() { + let s = self.sections.get(v.slot); // Only the solid groups that can face the eye. - s.faces.ranges(eye - Vec3::from(*origin), |first, quads| { + s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { let first = s.start + u64::from(first) * 4; self.draws.push([quads * 6, 1, 0, first as u32, i as u32]); self.draw_pages.push(s.page); }); } let solid_draws = self.draws.len() as u32; - for (i, (key, _, _)) in visible.iter().enumerate().rev() { - let s = &self.sections[key]; + for (i, v) in visible.iter().enumerate().rev() { + let s = self.sections.get(v.slot); if s.translucent > 0 { let first = s.start + u64::from(s.solid) * 4; self.draws @@ -3102,6 +3100,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| { diff --git a/crates/horizon-client/src/gfx/resident.rs b/crates/horizon-client/src/gfx/resident.rs new file mode 100644 index 000000000..58e187090 --- /dev/null +++ b/crates/horizon-client/src/gfx/resident.rs @@ -0,0 +1,381 @@ +//! Resident sections, stored densely and grouped by chunk column for the +//! per-frame culling walk: a column whose box misses the frustum or lies past +//! the render distance rejects all of its sections with one test, and the +//! sections that remain are reached by index rather than by hashing keys. +use super::{Frustum, SectionKey}; +use crate::fast_hash::FxHashMap; +use glam::{DVec3, Vec3}; + +/// One chunk column's resident sections. +struct Column { + x: i32, + z: i32, + /// Section y (from the world's bottom) and slot, in no particular order. + sections: Vec<(i32, u32)>, + /// The lowest and highest section y of `sections`. + low: i32, + high: i32, +} + +impl Column { + fn bounds(&mut self) { + self.low = self.sections.iter().map(|s| s.0).min().unwrap_or(0); + self.high = self.sections.iter().map(|s| s.0).max().unwrap_or(0); + } +} + +/// Values of type `T` per section key, in a dense list with stable keys and +/// slots that move only when a section is removed. +pub struct Resident { + items: Vec<(SectionKey, T)>, + slots: FxHashMap, + columns: Vec, + column_index: FxHashMap<(i32, i32), u32>, +} + +impl Default for Resident { + fn default() -> Self { + Self { + items: Vec::new(), + slots: FxHashMap::default(), + columns: Vec::new(), + column_index: FxHashMap::default(), + } + } +} + +impl Resident { + pub fn len(&self) -> usize { + self.items.len() + } + pub fn contains(&self, key: SectionKey) -> bool { + self.slots.contains_key(&key) + } + pub fn values(&self) -> impl Iterator { + self.items.iter().map(|(_, v)| v) + } + /// The section in `slot` (`Visible::slot`). + pub fn get(&self, slot: u32) -> &T { + &self.items[slot as usize].1 + } + pub fn clear(&mut self) { + self.items.clear(); + self.slots.clear(); + self.columns.clear(); + self.column_index.clear(); + } + /// Adds or replaces `key`'s value. + pub fn insert(&mut self, key: SectionKey, value: T) { + if let Some(&slot) = self.slots.get(&key) { + self.items[slot as usize].1 = value; + return; + } + let slot = self.items.len() as u32; + self.items.push((key, value)); + self.slots.insert(key, slot); + let column = match self.column_index.get(&(key.0, key.2)) { + Some(&c) => &mut self.columns[c as usize], + None => { + self.column_index + .insert((key.0, key.2), self.columns.len() as u32); + self.columns.push(Column { + x: key.0, + z: key.2, + sections: Vec::new(), + low: key.1, + high: key.1, + }); + self.columns.last_mut().expect("just pushed") + } + }; + column.sections.push((key.1, slot)); + column.low = column.low.min(key.1); + column.high = column.high.max(key.1); + } + pub fn remove(&mut self, key: SectionKey) -> Option { + let slot = self.slots.remove(&key)?; + let c = self.column_index[&(key.0, key.2)] as usize; + let column = &mut self.columns[c]; + let at = column + .sections + .iter() + .position(|s| s.1 == slot) + .expect("section in its column"); + column.sections.swap_remove(at); + if column.sections.is_empty() { + self.column_index.remove(&(key.0, key.2)); + self.columns.swap_remove(c); + if let Some(moved) = self.columns.get(c) { + self.column_index.insert((moved.x, moved.z), c as u32); + } + } else { + column.bounds(); + } + let (_, value) = self.items.swap_remove(slot as usize); + // The last item now sits in `slot`: point its key and column at it. + if let Some(&(moved, _)) = self.items.get(slot as usize) { + let last = self.items.len() as u32; + self.slots.insert(moved, slot); + let column = &mut self.columns[self.column_index[&(moved.0, moved.2)] as usize]; + let entry = column + .sections + .iter_mut() + .find(|s| s.1 == last) + .expect("moved section in its column"); + entry.1 = slot; + } + Some(value) + } +} + +/// A section in view. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Visible { + /// Its centre's squared distance from the camera, as bits: non-negative + /// floats order like their bits, so sorting compares integers. + pub distance: u64, + pub key: SectionKey, + pub slot: u32, + /// Its camera-relative origin. + pub origin: [f32; 3], +} + +/// The camera-relative origin of the section at `key`. +fn origin(key: SectionKey, camera: DVec3) -> DVec3 { + DVec3::new( + f64::from(key.0 * 16), + f64::from(crate::chunk::MIN_Y + key.1 * 16), + f64::from(key.2 * 16), + ) - camera +} + +/// Whether the section at `key` is drawn: within `distance` blocks of the +/// camera horizontally (plus a section and a half), and partly inside the +/// frustum. `None` when it is not, else its squared centre distance and origin. +fn in_view( + key: SectionKey, + camera: DVec3, + distance: f32, + frustum: &Frustum, +) -> Option<(f64, Vec3)> { + let origin = origin(key, camera); + let center = origin + DVec3::splat(8.0); + let horizontal = (center.x * center.x + center.z * center.z).sqrt(); + if horizontal > f64::from(distance) + 24.0 { + return None; + } + let min = origin.as_vec3(); + if !frustum.intersects(min, min + Vec3::splat(16.0)) { + return None; + } + Some((center.length_squared(), min)) +} + +impl Resident { + /// Appends the sections `in_view` and `reachable` to `out`, nearest + /// first (ties by key, so the order never depends on storage). + /// + /// Columns are tested first, with the same distance test (it depends + /// only on x and z) and a box spanning their sections: every section box + /// lies inside it and the frustum test rounds monotonically, so a column + /// the frustum rejects holds no section it would accept. + pub fn visible( + &self, + camera: DVec3, + distance: f32, + frustum: &Frustum, + reachable: impl Fn(SectionKey) -> bool, + out: &mut Vec, + ) { + for column in &self.columns { + let low = origin((column.x, column.low, column.z), camera); + let center = low + DVec3::splat(8.0); + if (center.x * center.x + center.z * center.z).sqrt() > f64::from(distance) + 24.0 { + continue; + } + let min = low.as_vec3(); + let top = origin((column.x, column.high, column.z), camera).as_vec3(); + if !frustum.intersects(min, top + Vec3::splat(16.0)) { + continue; + } + for &(y, slot) in &column.sections { + let key = (column.x, y, column.z); + if !reachable(key) { + continue; + } + if let Some((d, o)) = in_view(key, camera, distance, frustum) { + out.push(Visible { + distance: d.to_bits(), + key, + slot, + origin: o.to_array(), + }); + } + } + } + out.sort_unstable_by_key(|v| (v.distance, v.key)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::HashMap; + + #[test] + fn column_walk_finds_exactly_the_sections_in_view() { + let mut r = Resident::default(); + for x in -12i32..=12 { + for z in -12..=12 { + for y in 0..24 { + // Leave holes so columns have uneven bounds. + if (x * 7 + y * 3 + z * 5).rem_euclid(4) != 0 { + r.insert((x, y, z), ()); + } + } + } + } + let reachable = |k: SectionKey| (k.0 + k.1 + k.2).rem_euclid(9) != 0; + let cameras = [ + (DVec3::new(0.5, 70.0, 0.5), 0.0, 0.0), + (DVec3::new(-37.25, 130.5, 21.75), 135.0, 35.0), + (DVec3::new(100.0, -60.0, -3.0), 270.0, -80.0), + (DVec3::new(8.0, 64.0, 8.0), 45.0, 89.0), + ]; + for (camera, yaw, pitch) in cameras { + for distance in [32.0, 96.0, 160.0] { + let projection = super::super::world_projection(70.0, 16.0 / 9.0, 512.0); + let view = crate::camera::view_matrix(yaw, pitch); + let frustum = Frustum { + planes: super::super::frustum(projection * view), + }; + let mut fast = Vec::new(); + r.visible(camera, distance, &frustum, reachable, &mut fast); + let mut slow: Vec<(SectionKey, f64, [f32; 3])> = r + .items + .iter() + .filter(|(k, _)| reachable(*k)) + .filter_map(|(k, _)| { + in_view(*k, camera, distance, &frustum).map(|(d, o)| (*k, d, o.to_array())) + }) + .collect(); + slow.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); + let fast: Vec<_> = fast + .iter() + .map(|v| { + assert_eq!(r.items[v.slot as usize].0, v.key); + (v.key, f64::from_bits(v.distance), v.origin) + }) + .collect(); + assert!(!slow.is_empty()); + assert_eq!(fast, slow, "{camera} {yaw} {pitch} {distance}"); + } + } + } + + /// Every key reaches its value through its slot and column, and every + /// column's bounds and sections match the keys. + fn check(r: &Resident, model: &HashMap) { + assert_eq!(r.len(), model.len()); + let mut seen = 0; + for column in &r.columns { + assert!(!column.sections.is_empty()); + let ys: Vec = column.sections.iter().map(|s| s.0).collect(); + assert_eq!(column.low, *ys.iter().min().unwrap()); + assert_eq!(column.high, *ys.iter().max().unwrap()); + for &(y, slot) in &column.sections { + let (key, value) = &r.items[slot as usize]; + assert_eq!(*key, (column.x, y, column.z)); + assert_eq!(model[key], *value); + seen += 1; + } + } + assert_eq!(seen, model.len()); + for key in model.keys() { + assert!(r.contains(*key)); + } + } + + #[test] + fn slots_and_columns_follow_inserts_and_removals() { + let mut r = Resident::default(); + let mut model = HashMap::new(); + // A deterministic mix of inserts, replacements and removals. + let mut seed = 0x2545_f491_u32; + for step in 0..4000u32 { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + let key = ( + (seed % 5) as i32 - 2, + ((seed >> 4) % 6) as i32 - 1, + ((seed >> 8) % 5) as i32 - 2, + ); + if (seed >> 12).is_multiple_of(3) { + assert_eq!(r.remove(key), model.remove(&key)); + } else { + r.insert(key, step); + model.insert(key, step); + } + check(&r, &model); + } + r.clear(); + assert_eq!(r.len(), 0); + assert!(r.columns.is_empty()); + } + + /// The old walk (every key of a hash map, sorted by distance, then two + /// lookups per visible section) against `visible` on a render distance + /// 32 world. Run with `cargo test --profile fast -p horizon-client --lib + /// -- --ignored column_walk_speed --nocapture`. + #[test] + #[ignore = "timing, not a check"] + fn column_walk_speed() { + use std::time::{Duration, Instant}; + let mut r = Resident::default(); + let mut map = HashMap::new(); + for x in -33i32..=33 { + for z in -33i32..=33 { + for y in 0..24 { + if (x * 7 + y * 3 + z * 5).rem_euclid(4) != 0 { + r.insert((x, y, z), [x, y, z]); + map.insert((x, y, z), [x, y, z]); + } + } + } + } + let camera = DVec3::new(8.5, 100.0, 8.5); + let projection = super::super::world_projection(70.0, 16.0 / 9.0, 1024.0); + let frustum = Frustum { + planes: super::super::frustum(projection * crate::camera::view_matrix(30.0, 35.0)), + }; + let (mut old, mut new) = (Duration::MAX, Duration::MAX); + let (mut list, mut keys) = (Vec::new(), Vec::new()); + let mut sum = 0i64; + for _ in 0..200 { + let t = Instant::now(); + keys.clear(); + keys.extend(map.keys().filter_map(|&k| { + in_view(k, camera, 512.0, &frustum).map(|(d, o)| (k, d, o.to_array())) + })); + keys.sort_unstable_by(|a, b| a.1.total_cmp(&b.1)); + for (k, _, _) in &keys { + sum += i64::from(map[k][1] + map[k][0]); + } + old = old.min(t.elapsed()); + let t = Instant::now(); + list.clear(); + r.visible(camera, 512.0, &frustum, |_| true, &mut list); + for v in &list { + sum += i64::from(r.get(v.slot)[1] + r.get(v.slot)[0]); + } + new = new.min(t.elapsed()); + } + assert_eq!(keys.len(), list.len()); + println!( + "{} resident, {} visible: old walk {old:?}, column walk {new:?} (checksum {sum})", + r.len(), + list.len() + ); + } +} 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] { diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 176d223e5..77ba0e342 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/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/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/lib.rs b/crates/horizon-client/src/lib.rs index b56891996..6148dc4aa 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; @@ -107,6 +108,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/mesher/facing.rs b/crates/horizon-client/src/mesher/facing.rs index 2440bf926..2a7f0ba61 100644 --- a/crates/horizon-client/src/mesher/facing.rs +++ b/crates/horizon-client/src/mesher/facing.rs @@ -80,26 +80,22 @@ impl FaceGroups { } } +/// The axis and sign of each axis group (`UNALIGNED`'s entry is unused). +const AXES: [(usize, bool); GROUPS] = { + let mut axes = [(0, false); GROUPS]; + let mut axis = 0; + while axis < 3 { + axes[NEGATIVE[axis]] = (axis, false); + axes[GROUPS - 1 - NEGATIVE[axis]] = (axis, true); + axis += 1; + } + axes +}; + /// The axis and sign of axis group `g`. fn axis(g: usize) -> (usize, bool) { - if g < UNALIGNED { - ( - NEGATIVE - .iter() - .position(|&n| n == g) - .expect("negative group"), - false, - ) - } else { - let n = GROUPS - 1 - g; - ( - NEGATIVE - .iter() - .position(|&m| m == n) - .expect("positive group"), - true, - ) - } + debug_assert_ne!(g, UNALIGNED); + AXES[g] } /// The group of one quad, and its plane: an axis group only when all four diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 06e88af3c..8b51593bc 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -71,6 +71,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; @@ -508,6 +509,7 @@ pub enum DamageKind { Fireball, Explosion, Fall, + FallingBlock, OnFire, InFire, Lava, @@ -1613,6 +1615,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 diff --git a/crates/horizon-client/src/mobs/data.rs b/crates/horizon-client/src/mobs/data.rs index 47c40b093..539a85c66 100644 --- a/crates/horizon-client/src/mobs/data.rs +++ b/crates/horizon-client/src/mobs/data.rs @@ -46,6 +46,8 @@ pub struct MobData { /// Each entity type's `SpawnPlacements.getHeightmapType`. pub heightmaps: HashMap, pub animations: HashMap, + /// 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`). @@ -71,6 +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 = std::sync::RwLock::new(super::villager_hats::VillagerHats::load(root)); data } /// Only the keyframe animation definitions of `mob-data.json`. @@ -131,6 +134,7 @@ impl MobData { placements, heightmaps, animations, + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), pois: Default::default(), @@ -186,6 +190,7 @@ impl MobData { placements: HashMap::new(), heightmaps: HashMap::new(), animations: HashMap::new(), + villager_hats: Default::default(), biome_tags: HashMap::new(), entity_tags: HashMap::new(), pois: Default::default(), diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index a3b29f63b..4c312e5fd 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -1061,6 +1061,16 @@ 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 + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .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:?}" + ); + } + } + } +} diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs new file mode 100644 index 000000000..3a8c2920e --- /dev/null +++ b/crates/horizon-client/src/mod_content.rs @@ -0,0 +1,857 @@ +//! 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 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(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)?, + "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", +]; +/// 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"]; + +/// 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)?)?; + } + // 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(()) +} + +/// 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..6dd92ecfd --- /dev/null +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -0,0 +1,218 @@ +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()); + // 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!( + 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; 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 abb9e6c50..ecedd0f95 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -96,7 +96,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() @@ -135,7 +137,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-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-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(); 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 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(); 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 000000000..c6e4eeaf2 Binary files /dev/null and b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/block/ruby_block.png differ diff --git a/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png new file mode 100644 index 000000000..bfe0c217b Binary files /dev/null and b/crates/horizon-mod-sdk/examples/ruby-content/assets/ruby/textures/item/ruby.png differ 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"] 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/crates/horizon-port-pack/Cargo.toml b/crates/horizon-port-pack/Cargo.toml new file mode 100644 index 000000000..3b903ad03 --- /dev/null +++ b/crates/horizon-port-pack/Cargo.toml @@ -0,0 +1,21 @@ +[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"] } + +[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/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..4df3ef3ca --- /dev/null +++ b/crates/horizon-port-pack/src/main.rs @@ -0,0 +1,152 @@ +//! `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`. +//! - `carry [...]`: the content mods' data and assets into +//! `/mods//carry/`, a folder mod for local use. +//! +//! 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; +mod jar; +mod modrinth; + +use std::{fs, path::Path, process::ExitCode}; + +const USAGE: &str = "usage: horizon-port-pack import | inventory [--offline] | carry [...]"; + +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"))) + } + Some("carry") => path(1).and_then(|w| carry(w, &args[2..])), + _ => 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(()) +} + +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/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/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] diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 8a5f15d65..4f804712f 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,43 @@ 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.wrapping_add(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.wrapping_add(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; 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/modpacks.md b/docs/modpacks.md index 54dc43bdc..7951ad4d4 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -262,6 +262,30 @@ inspected: └── coverage.json, coverage.md ``` +**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 +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). + +`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 | 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 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-