diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8966854c2..17075add1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -64,9 +64,13 @@ jobs: cargo +stable clippy --workspace --all-targets -- -D warnings # The server build (released as horizon-engine): the game without sound or controllers. cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings + # Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already + # type-checks and the parity job builds and runs (they were most of this step's build and link time). - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' - run: cargo +stable test --workspace + run: | + cargo +stable test --workspace --lib --bins --tests + cargo +stable test --workspace --doc parity: if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository uses: ./.github/workflows/parity.yml diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index f3dfea6b1..139528612 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -121,6 +121,7 @@ fn main() -> Result<(), Box> { tick_frozen: false, tick_steps: (0, 0), collision: None, + border: &horizon_client::worldborder::WorldBorder::default(), }; for event in hub.tick(&mut ctx) { match event { diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index ec20eee74..2dae2204c 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -78,6 +78,7 @@ fn main() -> Result<()> { let mut selected = collisions::EntityCollisions { blocks: scene, entities: &entities, + border: None, }; let movement = world_movement::resolve_world_movement( &mut selected, diff --git a/crates/horizon-client/src/banner.rs b/crates/horizon-client/src/banner.rs index 861294722..aa470a552 100644 --- a/crates/horizon-client/src/banner.rs +++ b/crates/horizon-client/src/banner.rs @@ -2,7 +2,7 @@ //! `banner_patterns` layers carried by banner items, shields and placed //! banners, and the loom rules of `LoomMenu` (selectable patterns, the //! six-layer limit and the result stack). -use crate::{block_entity_render::DYES, item_data, items::ItemStack, items::Items}; +use crate::{block_entity_render::DYES, items::ItemStack, items::Items}; use horizon_world::nbt::Tag; use serde_json::Value; use std::{collections::HashMap, fs, path::Path, sync::Arc}; @@ -261,12 +261,6 @@ pub fn layers_from_nbt(tag: Option<&Tag>) -> Vec { }) .collect() } -/// Keeps `item_data` linked: the `StackData` fields the banner code reads. -pub fn set_layers(stack: &mut ItemStack, layers: Vec) { - let data: &mut item_data::StackData = stack.data_mut(); - data.banner_patterns = layers; - stack.tidy(); -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs index 93abb3711..03fff85ca 100644 --- a/crates/horizon-client/src/block_entities.rs +++ b/crates/horizon-client/src/block_entities.rs @@ -144,9 +144,6 @@ impl BlockEntities { pub fn set_states(&mut self, states: Vec) { self.states = states; } - pub fn take_states(&mut self) -> Vec { - std::mem::take(&mut self.states) - } pub fn ticking(&self, state: u32) -> Ticking { self.states.get(state as usize).copied().unwrap_or_default() } diff --git a/crates/horizon-client/src/block_entity_anim.rs b/crates/horizon-client/src/block_entity_anim.rs index 2a35c9835..d91748e73 100644 --- a/crates/horizon-client/src/block_entity_anim.rs +++ b/crates/horizon-client/src/block_entity_anim.rs @@ -382,10 +382,6 @@ impl Shulker { } out } - /// `getProgress(a)`: `Mth.lerp(a, progressOld, progress)`. - pub fn get_progress(&self, a: f32) -> f32 { - self.progress_old + a * (self.progress - self.progress_old) - } /// `ShulkerBoxBlock.canOpen`: a closed box only opens when its lid has room /// (`level.noCollision` of the half-block lid box, deflated by 1e-6). pub fn lid_box(pos: [i32; 3], facing: u8) -> [f64; 6] { @@ -668,14 +664,6 @@ impl Skull { self.animating = false; } } - /// `getAnimation(a)`. - pub fn get_animation(&self, a: f32) -> f32 { - if self.animating { - self.tick_count as f32 + a - } else { - self.tick_count as f32 - } - } } /// `DecoratedPotBlockEntity.WobbleStyle`. diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 21376d698..af4168307 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -875,13 +875,6 @@ impl BlockEntityRenderer { visibility: None, } } - /// The standing banner's pole-and-bar and flag models (`BannerRenderer.submitSpecial`). - pub fn banner_models(&self) -> Option<(&ModelPart, &ModelPart)> { - Some(( - self.models.get("standing_banner")?, - self.models.get("standing_banner_flag")?, - )) - } fn kind(&self, state: u32) -> &Kind { self.kinds.get(state as usize).unwrap_or(&Kind::None) } diff --git a/crates/horizon-client/src/bossbar.rs b/crates/horizon-client/src/bossbar.rs index a976258f9..eab31a5e5 100644 --- a/crates/horizon-client/src/bossbar.rs +++ b/crates/horizon-client/src/bossbar.rs @@ -46,7 +46,7 @@ impl BossBar { style: "progress".into(), value: 0, max: 100, - visible: false, + visible: true, player: false, } } diff --git a/crates/horizon-client/src/clock.rs b/crates/horizon-client/src/clock.rs index 5239db143..27cc714bf 100644 --- a/crates/horizon-client/src/clock.rs +++ b/crates/horizon-client/src/clock.rs @@ -169,10 +169,6 @@ impl TickRateManager { self.frozen_ticks_to_run -= 1; } } - /// `isEntityFrozen` for an entity that is not (and does not carry) a player. - pub fn is_entity_frozen(&self, is_player_or_carries_player: bool) -> bool { - !self.runs_normally() && !is_player_or_carries_player - } } /// What `/tick sprint` reports when it ends. diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index 67f5d6027..cfca854dc 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -3,7 +3,7 @@ //! Entity-dependent rules use the defaults for players and the supported mobs. use crate::{Result, world::World}; use horizon_core::{ - geometry::{Aabb, Vec3, VoxelShape}, + geometry::{Aabb, Vec3, VoxelShape, border::BorderGeometry}, position::{BlockPos, ChunkPos}, }; use horizon_world::{ @@ -64,6 +64,9 @@ pub struct SceneCollisions<'w, 'r> { pub struct EntityCollisions<'a, W> { pub blocks: W, pub entities: &'a [Aabb], + /// The world border and the moving entity's x and z + /// (`CollisionGetter.borderCollision`); None: the blocks' answer. + pub border: Option<(&'a BorderGeometry, [f64; 2])>, } impl BlockCollisionWorld for EntityCollisions<'_, W> { type Error = W::Error; @@ -114,12 +117,20 @@ impl> EntityMovementWorld for EntityCo } Ok(shapes) } + /// `WorldBorder.isInsideCloseToBorder`: an entity inside the border and + /// near it collides with its walls. fn movement_border( &mut self, entity: EntityIdentity, bounds: Aabb, ) -> io::Result> { - self.blocks.movement_border(entity, bounds) + let Some((border, [x, z])) = self.border else { + return self.blocks.movement_border(entity, bounds); + }; + if !border.is_inside_close_to_border(x, z, bounds) { + return Ok(None); + } + border.collision_shape().map(Some).map_err(io::Error::other) } } impl SceneCollisions<'_, '_> { diff --git a/crates/horizon-client/src/command/args.rs b/crates/horizon-client/src/command/args.rs index 68d41e14f..ccced67a7 100644 --- a/crates/horizon-client/src/command/args.rs +++ b/crates/horizon-client/src/command/args.rs @@ -812,14 +812,6 @@ pub fn java_parse_int(s: &str) -> Option { } s.parse().ok() } -/// Long.parseLong. -pub fn java_parse_long(s: &str) -> Option { - let digits = s.strip_prefix(['-', '+']).unwrap_or(s); - if digits.is_empty() || !digits.chars().all(|c| c.is_ascii_digit()) { - return None; - } - s.parse().ok() -} /// Double.parseDouble over the characters StringReader reads as a number. pub fn java_parse_double(s: &str) -> Option { let t = s.trim_matches(|c: char| c <= ' '); diff --git a/crates/horizon-client/src/command/component.rs b/crates/horizon-client/src/command/component.rs index 9bc0668d5..15a8fa6a0 100644 --- a/crates/horizon-client/src/command/component.rs +++ b/crates/horizon-client/src/command/component.rs @@ -1,7 +1,7 @@ //! ComponentSerialization.CODEC and Style.Serializer.MAP_CODEC decoding of //! SNBT text components, with the data-fixer-upper error messages //! (ComponentArgument, StyleArgument and component-valued item data). -use super::codec::{get, no_key, not_list, not_map, snbt}; +use super::codec::{get, no_key, not_list, not_map}; use horizon_world::nbt::{Compound, Tag}; /// A DataResult error: its message and whether it carries a partial result. @@ -362,7 +362,3 @@ pub fn decode_style(t: &Tag) -> Result<(), String> { _ => Err(not_map(t)), } } -#[allow(unused)] -fn _keep(t: &Tag) -> String { - snbt(t) -} diff --git a/crates/horizon-client/src/command/item.rs b/crates/horizon-client/src/command/item.rs index 7c8abe84a..f2abc91ef 100644 --- a/crates/horizon-client/src/command/item.rs +++ b/crates/horizon-client/src/command/item.rs @@ -632,10 +632,6 @@ pub fn parse_predicate(reader: &mut Reader, reg: &Registries) -> CmdResult String { - snbt(t) -} #[cfg(test)] mod tests { diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index e9aeaae51..a61c8c08d 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -183,9 +183,6 @@ impl<'a> Reader<'a> { pub fn read_int(&mut self) -> CmdResult { self.number("int") } - pub fn read_long(&mut self) -> CmdResult { - self.number("long") - } pub fn read_double(&mut self) -> CmdResult { self.number("double") } @@ -222,21 +219,6 @@ impl<'a> Reader<'a> { } Err(CommandError::tr_at("parsing.quote.expected.end", &[], self)) } - pub fn read_quoted_string(&mut self) -> CmdResult { - if !self.can_read() { - return Ok(String::new()); - } - let next = self.peek(); - if next != '"' && next != '\'' { - return Err(CommandError::tr_at( - "parsing.quote.expected.start", - &[], - self, - )); - } - self.skip(); - self.read_string_until(next) - } pub fn read_string(&mut self) -> CmdResult { if !self.can_read() { return Ok(String::new()); @@ -539,18 +521,6 @@ impl<'a> SuggestionsBuilder<'a> { } } } - /// The same with a tooltip per candidate. - pub fn suggest_matching_tooltip<'b>( - &mut self, - candidates: impl IntoIterator, - ) { - let lower = self.remaining_lower(); - for (c, tip) in candidates { - if args::matches_sub_str(&lower, &c.to_lowercase()) { - self.suggest_tooltip(c, tip); - } - } - } } /// String.compareToIgnoreCase. pub fn compare_ignore_case(a: &str, b: &str) -> std::cmp::Ordering { diff --git a/crates/horizon-client/src/command/snbt.rs b/crates/horizon-client/src/command/snbt.rs index 05fe6d9bc..7472c7ae3 100644 --- a/crates/horizon-client/src/command/snbt.rs +++ b/crates/horizon-client/src/command/snbt.rs @@ -1,8 +1,6 @@ //! SnbtGrammar and TagParser: vanilla's packrat SNBT grammar, with its //! error messages and completion suggestions, producing NBT tags. -use super::packrat::{ - Grammar, Reason, Rule, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq, -}; +use super::packrat::{Grammar, Reason, State, Sugg, Term, Value, alt, ch, chs, look, opt, seq}; use super::{CmdResult, CommandError, Reader, SuggestionsBuilder}; use horizon_world::nbt::{Compound, JavaString, Tag}; use std::rc::Rc; @@ -981,5 +979,3 @@ pub fn rule_in( } } } -#[allow(unused)] -fn _rule_kind(_: Rule) {} diff --git a/crates/horizon-client/src/command/vanilla.rs b/crates/horizon-client/src/command/vanilla.rs index fd23b82cd..cdd4848d7 100644 --- a/crates/horizon-client/src/command/vanilla.rs +++ b/crates/horizon-client/src/command/vanilla.rs @@ -3,7 +3,7 @@ //! mode keywords are read back from the parsed literals. use super::{ Dispatcher, - args::{ArgType, GameMode, Resource, integer}, + args::{ArgType, Resource, integer}, }; use crate::gamerules::{RULES, Value}; @@ -509,10 +509,6 @@ fn clone_mode(d: &mut Dispatcher, node: usize) { d.executes(l, "clone"); } } -/// Game mode names for selector `gamemode=` and the argument. -pub fn game_modes() -> [&'static str; 4] { - GameMode::ALL.map(GameMode::name) -} /// The shared vanilla tree. /// Reorder node children as vanilla registers them (Brigadier keeps /// children in registration order; smart usage lists them that way). @@ -559,5 +555,3 @@ pub fn release_dispatcher() -> &'static Dispatcher { static TREE: std::sync::OnceLock = std::sync::OnceLock::new(); TREE.get_or_init(|| build_with(false)) } -#[allow(unused)] -const _: (u8, u8) = (ALL, GAMEMASTERS); diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 854332815..6ecdf0d93 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -252,24 +252,6 @@ impl BlockEntity { }; Some(Self::Chest(vec![None; size])) } - /// The vanilla block entity type id of a container block. - pub fn id_for_block(name: &str) -> Option<&'static str> { - Some(match name { - "minecraft:chest" => "minecraft:chest", - n if n.ends_with("copper_chest") => "minecraft:chest", - "minecraft:trapped_chest" => "minecraft:trapped_chest", - "minecraft:barrel" => "minecraft:barrel", - "minecraft:hopper" => "minecraft:hopper", - "minecraft:dispenser" => "minecraft:dispenser", - "minecraft:dropper" => "minecraft:dropper", - "minecraft:furnace" => "minecraft:furnace", - "minecraft:blast_furnace" => "minecraft:blast_furnace", - "minecraft:smoker" => "minecraft:smoker", - n if n.ends_with("shulker_box") => "minecraft:shulker_box", - "minecraft:crafter" => "minecraft:crafter", - _ => return None, - }) - } pub fn id(&self) -> &'static str { match self { Self::Chest(items) => match items.len() { diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs index 35fd40bd4..3d9cc5556 100644 --- a/crates/horizon-client/src/debug_chart.rs +++ b/crates/horizon-client/src/debug_chart.rs @@ -17,8 +17,6 @@ use std::{ pub const CAPACITY: usize = 240; /// `AbstractDebugChart.CHART_HEIGHT`. pub const CHART_HEIGHT: i32 = 60; -/// `TpsDebugDimensions`: a tick sample's values. -pub const FULL_TICK: usize = 0; pub const TICK_SERVER_METHOD: usize = 1; pub const SCHEDULED_TASKS: usize = 2; pub const IDLE: usize = 3; @@ -252,10 +250,6 @@ impl Chart { pub fn width(max_width: i32) -> i32 { (CAPACITY as i32 + 2).min(max_width) } - /// `getFullHeight`: the box and the min/avg/max line above it. - pub fn full_height() -> i32 { - CHART_HEIGHT + 9 - } /// `AbstractDebugChart.extractRenderState`. pub fn draw( self, diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index ca2ea6f5c..2fc9ef2fb 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -359,10 +359,6 @@ impl Enchantments { } out } - /// Whether a stack draws the enchantment glint. - pub fn has_glint(&self, stack: &ItemStack) -> bool { - stack.has_any_enchantments() || self.props(&stack.item).is_some_and(|p| p.glint) - } // ---- Enchanting table (EnchantmentHelper) ---- @@ -514,19 +510,6 @@ impl Enchantments { .is_some_and(|e| e.effects.get(component).is_some()) }) } - /// The highest level among enchantments on `stack` that have `component`. - pub fn component_level(&self, stack: &ItemStack, component: &str) -> u32 { - stack - .enchantments() - .iter() - .filter(|(id, _)| { - self.get(id) - .is_some_and(|e| e.effects.get(component).is_some()) - }) - .map(|(_, l)| *l) - .max() - .unwrap_or(0) - } /// `minecraft:attributes` contributions of `stack`: (attribute, id, amount, operation). pub fn attributes(&self, stack: &ItemStack) -> Vec<(String, String, f64, String)> { let mut out = Vec::new(); diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index dbddb274b..49ea776ba 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -89,6 +89,47 @@ impl Base<'_> { } /// `LivingEntity` + `Mob` (+ `AgeableMob`, creeper and skeleton specifics). +/// The mobs whose class extends vanilla's `Animal` (and so save `InLove`): +/// not allays, villagers, golems, dolphins or fish. +fn is_animal(id: &str) -> bool { + matches!( + id.strip_prefix("minecraft:").unwrap_or(id), + "pig" + | "cow" + | "mooshroom" + | "sheep" + | "chicken" + | "rabbit" + | "horse" + | "donkey" + | "mule" + | "zombie_horse" + | "skeleton_horse" + | "llama" + | "trader_llama" + | "goat" + | "panda" + | "polar_bear" + | "fox" + | "wolf" + | "cat" + | "ocelot" + | "parrot" + | "bee" + | "turtle" + | "armadillo" + | "frog" + | "axolotl" + | "hoglin" + | "strider" + | "camel" + | "camel_husk" + | "sniffer" + | "happy_ghast" + | "nautilus" + | "zombie_nautilus" + ) +} pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: &m.kind.id, @@ -175,12 +216,15 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { for (key, value) in [ ("Age", Tag::Int(0)), ("ForcedAge", Tag::Int(0)), - ("InLove", Tag::Int(0)), ("AgeLocked", Tag::Byte(0)), ] { map.entry(key.into()).or_insert(value); } } + // Animal.addAdditionalSaveData: the love ticks left, whatever the save had. + if is_animal(id) { + map.insert("InLove".into(), Tag::Int(m.extra.in_love.max(0))); + } match id { "minecraft:creeper" => { for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] { @@ -621,6 +665,9 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.extra.forced_age = number(tag.get("ForcedAge")).unwrap_or(0) as i32; m.extra.age_locked = flag(tag, "AgeLocked"); } + if is_animal(&m.kind.id) { + m.extra.in_love = number(tag.get("InLove")).unwrap_or(0) as i32; + } m.name_visible = flag(tag, "CustomNameVisible"); m.no_ai = flag(tag, "NoAI"); m.no_gravity = flag(tag, "NoGravity"); diff --git a/crates/horizon-client/src/first_person.rs b/crates/horizon-client/src/first_person.rs index 463d51437..02132d942 100644 --- a/crates/horizon-client/src/first_person.rs +++ b/crates/horizon-client/src/first_person.rs @@ -289,15 +289,6 @@ impl Default for HandHeights { } } } -/// What `FirstPersonHandsAndItems.tick` decides about a hand's visible item. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct HandChange { - /// The visible item is not the hand's item after the instant replacement - /// (`mainHandItem != nextMainHand`): the hand lowers. - pub changed: bool, - /// The visible item becomes the hand's item this tick. - pub replace: bool, -} impl HandHeights { /// `FirstPersonHandsAndItems.tick`'s heights. `changed` says per hand /// whether the visible item differs from the held one once diff --git a/crates/horizon-client/src/font.rs b/crates/horizon-client/src/font.rs index c5e5760f3..a25568df5 100644 --- a/crates/horizon-client/src/font.rs +++ b/crates/horizon-client/src/font.rs @@ -271,7 +271,10 @@ fn load_bitmap( .flatten(); // The sheet: its size, and its pixels when they are not in the atlas. let (sw, sh, sheet) = match in_atlas { - Some(rect) => (rect.w, rect.h, None), + Some(rect) => { + let (w, h) = rect.texels(atlas); + (w, h, None) + } None => match crate::hud::decode(&root.join(resource_path(file, "textures", ""))) { Ok((w, h, rgba)) => (w, h, Some(Arc::new((w, rgba)))), Err(_) => { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2eb9d1fb2..f0d0f93e7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -73,6 +73,7 @@ mod lan_crafting; mod lan_entities; mod lan_mobs; mod lan_mount_menu; +mod lan_particles; mod lan_pvp; mod lan_screen; mod lan_stations; @@ -1021,9 +1022,11 @@ pub struct UiResources { pub panorama: Arc, } impl UiResources { - pub fn load(root: &std::path::Path) -> Result { + /// From a resource root layering packs over `defaults`, the game's own + /// resources (`root` itself when no pack is on). + pub fn load(root: &std::path::Path, defaults: &std::path::Path) -> Result { Ok(Self { - atlas: HudAtlas::build(root)?, + atlas: HudAtlas::build_over(root, defaults)?, panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), }) } @@ -2575,6 +2578,17 @@ impl Game<'_> { LevelEvent::LevelEvent { id: 2004, pos, .. } => { self.spawner_burst([pos.x, pos.y, pos.z]) } + // LevelEventHandler 1505: the growth particles, then the sound. + LevelEvent::LevelEvent { + id: 1505, + pos, + data, + } => { + self.growth_particles(pos, data); + let at = [pos.x, pos.y, pos.z].map(|v| f64::from(v) + 0.5); + self.audio + .play("minecraft:item.bone_meal.use", Some(at), 1.0, 1.0); + } LevelEvent::LevelEvent { id: 2015, pos, @@ -2618,7 +2632,6 @@ impl Game<'_> { 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)), 1042 => Some(("minecraft:block.grindstone.use", 1.0)), 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), // LevelEvent.SOUND_PAGE_TURN (a lectern's page). @@ -8100,13 +8113,15 @@ impl Game<'_> { } Ok(true) } - /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. - fn use_block_transformer( - &mut self, + /// What `BlockTransformer.transformBlock` would do with a held axe, hoe + /// or shovel on the block at `pos`, without doing it: the new state, its + /// sound, loot table, the durability it costs and its particle. + pub(super) fn block_transform( + &self, stack: &ItemStack, pos: [i32; 3], face: [i32; 3], - ) -> Result { + ) -> Option<(BlockStateId, String, Option, u32, String)> { use horizon_client::block_transform::Around; struct Column<'w> { world: &'w World, @@ -8126,14 +8141,11 @@ impl Game<'_> { }) } } - let Some(id) = self + let id = self .res .items() .get(&stack.item) - .and_then(|i| i.block_transformer.clone()) - else { - return Ok(false); - }; + .and_then(|i| i.block_transformer.clone())?; // playerHasBlockingItemUseIntent: a shield in the off hand is raised // instead, unless sneaking. let shield = self @@ -8142,7 +8154,7 @@ impl Game<'_> { .and_then(|s| self.res.items().get(&s.item)) .is_some_and(|i| i.blocks_attacks.is_some()); if shield && !self.keys.contains(&KeyCode::ShiftLeft) { - return Ok(false); + return None; } let face_name = match face { [0, -1, 0] => "down", @@ -8153,38 +8165,47 @@ impl Game<'_> { _ => "east", }; let registry = self.pack.assets.registry; - let (state, sound, loot, damage, particle) = { - let around = Column { - world: &self.world, - registry, - pos, - }; - let Some((_, t, state)) = - self.res - .transformers() - .apply(self.res.items(), registry, &id, face_name, &around) - else { - return Ok(false); - }; - ( - state, - t.sound.clone(), - t.loot.clone(), - t.damage, - t.particle.clone(), - ) + let around = Column { + world: &self.world, + registry, + pos, }; - let Ok(new) = registry.resolve(&state) else { - return Ok(false); - }; - self.level_set(pos, new)?; - // BlockTransformer.TransformParticle.send. - match particle.as_str() { + let (_, t, state) = + self.res + .transformers() + .apply(self.res.items(), registry, &id, face_name, &around)?; + let new = registry.resolve(&state).ok()?; + Some(( + new, + t.sound.clone(), + t.loot.clone(), + t.damage, + t.particle.clone(), + )) + } + /// `BlockTransformer.TransformParticle.send`: its level event. + pub(super) fn transform_particle(&mut self, particle: &str, pos: [i32; 3]) { + match particle { "scrape" => self.level_event_at(3005, pos, 0), "wax_on" => self.level_event_at(3003, pos, 0), "wax_off" => self.level_event_at(3004, pos, 0), _ => {} } + } + /// `BlockTransformer.transformBlock` for a held axe, hoe or shovel. + fn use_block_transformer( + &mut self, + stack: &ItemStack, + pos: [i32; 3], + face: [i32; 3], + ) -> Result { + let Some((new, sound, loot, damage, particle)) = self.block_transform(stack, pos, face) + else { + return Ok(false); + }; + self.level_set(pos, new)?; + // BlockTransformer.TransformParticle.send. + self.transform_particle(&particle, pos); if loot.as_deref() == Some("minecraft:till/rooted_dirt") { self.pop_resource( [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]], @@ -9570,6 +9591,7 @@ impl Game<'_> { ); map.insert("Air".into(), horizon_world::nbt::Tag::Short(p.air as i16)); } + level.fall_distance = p.fall_distance; level.food = p.health.food.food; level.saturation = p.health.food.saturation; @@ -12119,7 +12141,20 @@ fn load_resources( // loads; the synchronous launch instead carries it in `Loaded`. let mut loaded_gui = None; let mut ui_ready = false; - if let Ok(ui) = UiResources::load(&root) { + let mut pack_error = None; + let ui = match UiResources::load(&root, vanilla_root) { + Ok(ui) => Some(ui), + // Minecraft.rollbackResourcePacks: the packs' textures don't fit, start + // with the game's own resources. + Err(e) if root != vanilla_root => { + log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); + pack_error = Some(e.to_string()); + root = vanilla_root.to_path_buf(); + None + } + Err(_) => None, + }; + if let Some(ui) = ui { if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( @@ -12133,7 +12168,6 @@ fn load_resources( ui_ready = true; } progress.set(0); - let mut pack_error = None; let (assets, render) = match Assets::load(&root).and_then(|assets| { let render = assets.reload(&root)?; Ok((assets, render)) @@ -12160,7 +12194,7 @@ fn load_resources( let render = Arc::new(render); // The menu bundle must come from the same root as the world bundle. if !ui_ready || root != requested_root { - let ui = UiResources::load(&root)?; + let ui = UiResources::load(&root, vanilla_root)?; if menu { horizon_client::telemetry::mark_ui_ready(); log::info!( @@ -12571,6 +12605,10 @@ fn start_game<'a>( game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { + // Minecraft.clearResourcePacksOnError: the selection is cleared and + // saved, so the next launch starts without the packs. + game.settings.resource_packs.clear(); + game.settings.save(&Game::options_path()); game.open_options_at(true, horizon_client::options_ui::Page::Packs); game.ui.options.resource_error = Some(error); } diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index 20aeeb7fd..0247896f5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -5,7 +5,7 @@ use horizon_client::{ chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR}, command::Registries, gamerules::GameRules, - hud::{HudBatch, rgba}, + hud::HudBatch, screen_draw::Measure, text::{ClickEvent, Style, Text}, }; @@ -883,10 +883,6 @@ impl Game<'_> { .chat .add(&self.gui.atlas, message, None, self.ticks, focused); } - #[allow(dead_code)] - fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); - } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time /// approximated as UTC). diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index 46df0ce7d..df52f2251 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -248,8 +248,32 @@ impl Game<'_> { /// Every tick: the size change, the wall the player cannot pass and /// damage outside the border. + /// `BorderChangeListener.DelegateBorderChangeListener`'s packets: what + /// changed on the border since the guests were last told of it. + pub(in crate::game) fn lan_sync_border(&mut self, host: &mut crate::game::lan::LanHost) { + let now = horizon_client::lan::border::Sent::of(&self.border); + if let Some(sent) = host.border_sent.replace(now) { + for packet in sent.changes(&self.border) { + host.hub.broadcast(&packet); + } + } + } pub(in crate::game) fn tick_worldborder(&mut self) { self.border.tick(); + self.player_border(); + self.border_damage(); + } + /// The player's movement collides with the border as it is now + /// (`CollisionGetter.borderCollision`): from inside, its walls stop it. + pub(in crate::game) fn player_border(&mut self) { + if let Some(p) = self.player.as_mut() { + p.border = Some(self.border.geometry().clone()); + } + } + /// `LivingEntity.baseTick`: a player outside the border, further than + /// its safe zone, is hurt by the blocks beyond it. The game's player, or + /// a guest's in their turn (`as_guest`). + pub(in crate::game) fn border_damage(&mut self) { let Some((px, pz, half)) = self.player.as_ref().map(|p| { ( p.position.x, @@ -269,20 +293,6 @@ impl Game<'_> { let amount = (-dist * self.border.damage_per_block).floor().max(1.0) as f32; self.hurt_player_by("minecraft:outside_border", amount); } - // From inside the border the wall stops movement. - if self.border.distance(px, pz) >= 0.0 { - let [x, z] = self.border.clamp(px, pz, half); - if let Some(p) = self.player.as_mut() { - if x != px { - p.velocity.x = 0.0; - } - if z != pz { - p.velocity.z = 0.0; - } - p.position.x = x; - p.position.z = z; - } - } } pub(super) fn cmd_worldborder(&mut self, id: &str, ctx: &Context) -> R { let float2 = |v: f64| format!("{v:.2}"); diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 7e02626d2..1f7504d8a 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -8,6 +8,7 @@ use horizon_client::{ text::Text, }; use horizon_core::random::RandomSource; +use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_world::attribute_map::ValueKind; use horizon_world::nbt::Tag; @@ -409,6 +410,8 @@ impl Game<'_> { ], _ => [1.0, 0.0, 0.0], }; + // The block state of a block particle, for its packet. + let mut block_state = None; let options = match ty { ParticleType::Dust => ParticleOptions::dust( rgb, @@ -470,6 +473,7 @@ impl Game<'_> { match block { Ok(Arg::Block(b)) => { let state = self.block_state(&b)?; + block_state = Some(state); let at = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()) @@ -487,10 +491,9 @@ impl Game<'_> { let pos = self .position_arg(ctx, "pos") .unwrap_or_else(|| self.source_position()); - let delta = self.position_arg(ctx, "delta").map_or([0.0; 3], |d| { - let s = self.source_position(); - [d[0] - s[0], d[1] - s[1], d[2] - s[2]] - }); + // Vec3Argument.getVec3: the spread as given (relative parts from the + // source), not a position to measure from the source. + let delta = self.position_arg(ctx, "delta").unwrap_or([0.0; 3]); let speed = match ctx.get("speed") { Some(Arg::Float(v)) => *v, _ => 0.0, @@ -501,27 +504,74 @@ impl Game<'_> { }; // ParticleCommand.sendParticles: the viewers it reached, each within // 32 blocks (512 with `force`) of the particle's block centre. + // Without viewers, every player (PlayerList.getPlayers). let viewers = if ctx.get("viewers").is_some() { self.entities(ctx, "viewers", true)? } else { - vec![Target::Player] + let acting = self.lan_acting; + let guests = self.lan.iter().flat_map(|h| h.hub.guests.iter()); + self.player + .as_ref() + .map(|_| Target::Player) + .into_iter() + .chain( + guests + .filter(|g| g.placed && Some(g.conn) != acting) + .map(|g| Target::Guest(g.conn)), + ) + .collect() }; - let limit = if ctx.has("force") { 512.0 } else { 32.0 }; - let reached = viewers - .iter() - .filter(|&&t| { + let force = ctx.has("force"); + let limit = if force { 512.0 } else { 32.0 }; + let reached: Vec = viewers + .into_iter() + .filter(|&t| { self.target_position(t).is_some_and(|p| { let c = p.map(|v| v.floor() + 0.5); (c[0] - pos[0]).powi(2) + (c[1] - pos[1]).powi(2) + (c[2] - pos[2]).powi(2) < limit * limit }) }) - .count() as i32; - if reached == 0 { + .collect(); + if reached.is_empty() { return Err(err("commands.particle.failed", &[])); } - // `ServerLevel.sendParticles`: no count means one particle with the delta as velocity. - if count <= 0 { + // ServerLevel.sendParticles: each viewer a server serves is sent the + // particles (the player in place too when it is a guest); the + // window's own player draws them. + let packet = self + .network_particle(&options, block_state) + .map(|particle| { + C::LevelParticles(play::LevelParticles { + particle, + override_limiter: force, + always_show: false, + pos, + dist: delta.map(|d| d as f32), + max_speed: [speed; 3], + count: count.max(0), + randomization: 0, + }) + }); + let mut local = false; + for &t in &reached { + match (t, &packet) { + (Target::Player, Some(p)) if self.lan_acting.is_some() => { + self.guest_packets.push(p.clone()); + } + (Target::Player, _) => local = true, + (Target::Guest(conn), Some(p)) => { + if let Some(host) = self.lan.as_ref() { + host.hub.send_to(conn, p); + } + } + _ => {} + } + } + let reached = reached.len() as i32; + if !local { + } else if count <= 0 { + // No count: one particle with the delta as velocity. self.particles.create(&options, pos, delta); } else { for _ in 0..count { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 9132c7723..f7e4c6b36 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -834,6 +834,12 @@ impl Game<'_> { "velocity": [p.velocity.x, p.velocity.y, p.velocity.z], "on_ground": p.ground.on_ground, "health": p.health.health(), + // The maximum the HUD's hearts last read (its cached value). + "max_health": p + .attributes + .lookup(p.attributes.key("minecraft:max_health").as_ref()) + .and_then(|h| p.attributes.instance(&h).ok()) + .map(|i| i.cached_value()), "food": p.health.food.food, }) }); @@ -971,6 +977,12 @@ impl Game<'_> { "flashes": self.lightning_seen[1], "flash": self.flash}); // Primed TNT, falling blocks, projectiles, tridents and end crystals. status["projectiles"] = json!(self.projectiles_status()); + // The particles made so far, by type. + status["particles"] = json!(self.particles.made()); + // The world border this side knows of. + status["border"] = json!({ "center": self.border.center(), "size": self.border.size() }); + // The scoreboard sidebar the HUD shows. + status["sidebar"] = self.sidebar_status(); status } } diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index d62c8ccc2..599158e3e 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -97,8 +97,58 @@ impl EndState { } } +impl EndState { + /// The eyes' entity ids, for a server to number them. + pub(super) fn eye_ids(&mut self) -> impl Iterator { + self.eyes.iter_mut().map(|e| &mut e.id) + } + /// The numbered eyes as a server's clients track them: (id, position, motion). + pub(super) fn eyes_tracked(&self) -> impl Iterator { + self.eyes + .iter() + .filter(|e| e.id != 0) + .map(|e| (e.id, e.position.to_array(), e.velocity.to_array())) + } + /// `handleAddEntity` for an eye of ender on a server's client: it flies + /// where the server says. + pub(super) fn add_remote_eye(&mut self, id: u32, at: [f64; 3], velocity: [f64; 3]) { + self.eyes.retain(|e| e.id != id); + let at = glam::DVec3::from_array(at); + self.eyes.push(EyeOfEnder { + id, + position: at, + previous: at, + velocity: glam::DVec3::from_array(velocity), + target: at, + life: 0, + survive: false, + }); + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_eyes(&mut self, mut step: impl FnMut(u32, [f64; 3]) -> [f64; 3]) { + for e in &mut self.eyes { + e.previous = e.position; + e.life += 1; + e.position = glam::DVec3::from_array(step(e.id, e.position.to_array())); + } + } + pub(super) fn remove_remote_eye(&mut self, id: u32) { + self.eyes.retain(|e| e.id != id); + } + pub(super) fn clear_remote_eyes(&mut self) { + self.eyes.clear(); + } + /// Where each eye is, for `status`. + pub(super) fn eye_positions(&self) -> impl Iterator { + self.eyes.iter().map(|e| (e.id, e.position.to_array())) + } +} + /// The EyeOfEnder entity. struct EyeOfEnder { + /// Its entity id once a server's clients track it (0 until then). + id: u32, position: glam::DVec3, previous: glam::DVec3, velocity: glam::DVec3, @@ -1023,6 +1073,7 @@ impl Game<'_> { }; let survive = self.world.random.next_int_bound(5).unwrap_or(0) > 0; self.end.eyes.push(EyeOfEnder { + id: 0, position: start, previous: start, velocity: glam::DVec3::ZERO, diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 0923b4110..6ecba3a54 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -580,6 +580,7 @@ impl Game<'_> { self.particles.explosion(center, radius, block_count, &|b| { facts.is_air(world.block(b[0], b[1], b[2])) }); + self.lan_explode(center, radius, block_count); Ok(()) } /// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse). diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 8467b6d3a..e7d2cb95e 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -66,6 +66,8 @@ pub(super) struct LanHost { /// whose respawn replaces their waypoint. pub waypoints: std::collections::HashMap, pub waypoint_dead: std::collections::HashSet, + /// The world border as the guests were last told of it (lan/border.rs). + pub border_sent: Option, /// Guests' commands waiting for the hub to be back in `self.lan`, where /// a command can reach every player (game/lan_actions.rs). pub commands: Vec, @@ -561,6 +563,7 @@ impl Game<'_> { owner: None, waypoints: Default::default(), waypoint_dead: Default::default(), + border_sent: None, commands: Vec::new(), states: Default::default(), }); @@ -891,6 +894,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.movement_checks = ( self.ui.rules.bool("player_movement_check"), @@ -997,6 +1001,8 @@ impl Game<'_> { self.lan_update_streaming(&host); self.lan_update_models(&mut host); self.lan_update_waypoints(&mut host, state.as_ref()); + self.lan_sync_scoreboard(&mut host); + self.lan_sync_border(&mut host); drop(holding); lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); @@ -1073,6 +1079,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.place_new_player(conn, &mut ctx); if elsewhere && let Err(e) = self.enter_level(Some(host), back) { @@ -1087,8 +1094,14 @@ impl Game<'_> { } for e in events { if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e { - // The acting guest does not predict the egg's teleport particles. - let except = if *id == 2015 { None } else { self.lan_acting }; + // The acting guest does not predict the egg's teleport + // particles, nor bone meal's growth (BoneMealItem.useOn's + // levelEvent names no player). + let except = if matches!(*id, 2015 | 1505) { + None + } else { + self.lan_acting + }; self.lan_events .push((*id, [pos.x, pos.y, pos.z], *data, except)); } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 0527e30a0..58307ad81 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -220,6 +220,12 @@ impl Game<'_> { host.hub.guests[i].position[2], ); host.hub.guests[i].motion = PlayerMotion::new(self.motion, p).ok().map(Box::new); + // The first body after joining burns, breathes and falls on as saved. + if let Some(saved) = host.hub.guests[i].loaded_body.take() + && let Some(m) = host.hub.guests[i].motion.as_mut() + { + saved.apply(m); + } // The saved golden hearts go on the first body of a player who // has been here before. let saved = host.hub.guests[i].saved_absorption.take(); @@ -1575,6 +1581,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, }; host.hub.respawn(i, spawn, &ctx); if let Some(config) = elsewhere { @@ -1912,7 +1919,8 @@ impl Game<'_> { for d in travelled { game.movement_stats(Vec3::new(d[0], d[1], d[2])); } - // LivingEntity.baseTick ends with tickEffects. + // LivingEntity.baseTick: outside the world border, then tickEffects. + game.border_damage(); game.tick_mob_effects(); let Some(player) = game.player.as_mut() else { return Vec::new(); diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index f3098408c..db0c3e8b2 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -277,6 +277,8 @@ impl Game<'_> { self.rockets.iter_mut().for_each(|r| give(&mut r.id)); self.crystals.iter_mut().for_each(|c| give(&mut c.id)); self.bolts.iter_mut().for_each(|b| give(&mut b.id)); + self.potions.thrown_ids().for_each(&mut give); + self.end.eye_ids().for_each(&mut give); } /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and @@ -359,6 +361,26 @@ impl Game<'_> { } out.push(e); } + // Thrown potions and bottles: ThrowableItemProjectile.DATA_ITEM_STACK + // (the potion's colour), which a plain bottle's type already has. + for (id, kind, stack, position, velocity) in self.potions.thrown_tracked() { + let mut e = state(id, kind, at(position), 0.0, false); + e.velocity = at(velocity); + if stack.extra.is_some() || stack.count != 1 { + e.meta.push(( + 8, + serializer::ITEM_STACK, + Value::Item(hub.stack(&Some(stack.clone()))), + )); + } + out.push(e); + } + // EyeOfEnder: its item is the plain eye (DATA_ITEM_STACK's default). + for (id, position, velocity) in self.end.eyes_tracked() { + let mut e = state(id, "minecraft:eye_of_ender", position, 0.0, false); + e.velocity = velocity; + out.push(e); + } for t in self.tridents.iter().filter(|t| t.id != 0) { let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); e.pitch = t.pitch; diff --git a/crates/horizon-client/src/game/lan_particles.rs b/crates/horizon-client/src/game/lan_particles.rs new file mode 100644 index 000000000..2cacfabdb --- /dev/null +++ b/crates/horizon-client/src/game/lan_particles.rs @@ -0,0 +1,228 @@ +//! Particles a server sends its players and its clients draw: +//! `ClientboundLevelParticlesPacket` (`ServerLevel.sendParticles`, which +//! `/particle` uses) and `ClientboundExplodePacket` (`ServerLevel.explode`). +use super::Game; +use horizon_client::particles::{ParticleOptions, ParticleType}; +use horizon_core::random::RandomSource; +use horizon_protocol::{ + entity_data::{Particle, ParticleData}, + packets::play::{self, Clientbound as C}, +}; +use horizon_world::registry::BlockStateId; + +/// An ARGB colour as the options' RGBA. +fn rgba(argb: i32) -> [f32; 4] { + let c = |shift: i32| ((argb >> shift) & 255) as f32 / 255.0; + [c(16), c(8), c(0), c(24)] +} +/// The options' RGB as an RGB colour (`ARGB.colorFromFloat` without alpha). +fn rgb_int(c: [f32; 3]) -> i32 { + let b = |v: f32| ((v.clamp(0.0, 1.0) * 255.0).round() as i32) & 255; + (b(c[0]) << 16) | (b(c[1]) << 8) | b(c[2]) +} +fn rgb(c: [f32; 4]) -> [f32; 3] { + [c[0], c[1], c[2]] +} + +impl Game<'_> { + /// `ParticleTypes.STREAM_CODEC`'s value for `options`: the type's + /// network id and the data it carries (`state` for the block particles). + /// None while not serving, or for a particle whose data isn't sent from + /// here (items, vibrations, trails). + pub(super) fn network_particle( + &self, + options: &ParticleOptions, + state: Option, + ) -> Option { + let name = format!("minecraft:{}", options.ty.name()); + let id = self + .lan + .as_ref()? + .hub + .registry_id("minecraft:particle_type", &name)?; + use ParticleType as T; + let c = options.color; + let data = match options.ty { + T::Block | T::BlockMarker | T::FallingDust | T::DustPillar | T::BlockCrumble => { + Some(ParticleData::State(state?.0 as i32)) + } + T::Dust => Some(ParticleData::ColorScale(rgb_int(rgb(c)), options.scale)), + T::DustColorTransition => Some(ParticleData::ColorScale2( + rgb_int(rgb(c)), + rgb_int(options.to_color), + options.scale, + )), + T::Effect | T::InstantEffect => { + Some(ParticleData::ColorPower(rgb_int(rgb(c)), options.scale)) + } + T::EntityEffect | T::TintedLeaves => Some(ParticleData::Color( + (((c[3].clamp(0.0, 1.0) * 255.0).round() as i32) << 24) | rgb_int(rgb(c)), + )), + T::DragonBreath | T::SculkCharge => Some(ParticleData::Scalar(options.scale)), + T::Shriek => Some(ParticleData::Delay(options.scale as i32)), + T::Item | T::Trail | T::Vibration => return None, + _ => None, + }; + Some(Particle { id, data }) + } + + /// The options a server's particle stands for (None for a type or data + /// this client doesn't draw). + fn received_particle(&mut self, p: &Particle, at: [f64; 3]) -> Option { + let name = self + .remote + .as_ref()? + .builtin + .get("minecraft:particle_type")? + .name(p.id)? + .to_owned(); + let ty = ParticleType::from_name(&name)?; + Some(match &p.data { + None => ParticleOptions::simple(ty), + Some(ParticleData::State(s)) => { + let pos = at.map(|v| v.floor() as i32); + let (sprite, tint) = self + .particle_sprite(BlockStateId(*s as u32), pos) + .unwrap_or_else(|| ("block/stone".into(), 0xFFFFFF)); + ParticleOptions::block(ty, sprite, tint) + } + Some(ParticleData::ColorScale(c, scale)) => { + ParticleOptions::dust(rgb(rgba(*c)), *scale) + } + Some(ParticleData::ColorScale2(from, to, scale)) => { + ParticleOptions::dust_transition(rgb(rgba(*from)), rgb(rgba(*to)), *scale) + } + Some(ParticleData::ColorPower(c, power)) => ParticleOptions { + scale: *power, + ..ParticleOptions::colored(ty, [rgba(*c)[0], rgba(*c)[1], rgba(*c)[2], 1.0]) + }, + Some(ParticleData::Color(c)) => ParticleOptions::colored(ty, rgba(*c)), + Some(ParticleData::Scalar(v)) if ty == ParticleType::SculkCharge => { + ParticleOptions::sculk_charge(*v) + } + Some(ParticleData::Scalar(v)) => ParticleOptions { + scale: *v, + ..ParticleOptions::simple(ty) + }, + Some(ParticleData::Delay(d)) => ParticleOptions::shriek(*d), + Some(ParticleData::Trail(target, color, duration)) => { + ParticleOptions::trail(*target, *color as u32 & 0xFF_FFFF, *duration) + } + Some(_) => return None, + }) + } + + /// `ClientPacketListener.handleParticleEvent`: no count is one particle + /// moving by speed times spread; otherwise each is spread and sped up by + /// gaussians on each axis. + pub(super) fn remote_level_particles(&mut self, p: &play::LevelParticles) { + let Some(options) = self.received_particle(&p.particle, p.pos) else { + return; + }; + let (d, s) = (p.dist.map(f64::from), p.max_speed.map(f64::from)); + // ClientLevel.addParticle: the camera's 32 blocks unless the packet + // (`force`) or the type overrides the limiter. + let add = |particles: &mut horizon_client::particles::ParticleEngine, at, v| { + if p.override_limiter { + particles.create(&options, at, v); + } else { + particles.add(&options, at, v); + } + }; + if p.count == 0 { + add( + &mut self.particles, + p.pos, + [s[0] * d[0], s[1] * d[1], s[2] * d[2]], + ); + return; + } + for _ in 0..p.count { + let r = self.particles.random(); + let at = [ + p.pos[0] + r.next_gaussian() * d[0], + p.pos[1] + r.next_gaussian() * d[1], + p.pos[2] + r.next_gaussian() * d[2], + ]; + let v = [ + r.next_gaussian() * s[0], + r.next_gaussian() * s[1], + r.next_gaussian() * s[2], + ]; + add(&mut self.particles, at, v); + } + } + + /// `ClientPacketListener.handleExplosion`: the blast's particles (and its + /// sound, when the packet carries it). + pub(super) fn remote_explode(&mut self, p: &play::Explode) { + if p.play_sound { + let pitch = (1.0 + + (self.particles.random().next_float() - self.particles.random().next_float()) + * 0.2) + * 0.7; + self.audio.play( + "minecraft:entity.generic.explode", + Some(p.center), + 4.0, + pitch, + ); + } + let (world, facts) = (&self.world, self.res.facts()); + self.particles + .explosion(p.center, p.radius, p.block_count.max(0) as usize, &|b| { + facts.is_air(world.block(b[0], b[1], b[2])) + }); + } + + /// `ServerLevel.explode`'s packet to each player within 64 blocks. The + /// sound and the push reach them on their own (the level's sounds, the + /// players' motion), so the packet carries neither. + pub(super) fn lan_explode(&self, center: [f64; 3], radius: f32, block_count: usize) { + let Some(host) = self.lan.as_ref() else { + return; + }; + let particle = |name: &str| { + Some(Particle { + id: host.hub.registry_id("minecraft:particle_type", name)?, + data: None, + }) + }; + let emitter = if radius < 2.0 { + "minecraft:explosion" + } else { + "minecraft:explosion_emitter" + }; + let (Some(at_center), Some(poof), Some(smoke)) = ( + particle(emitter), + particle("minecraft:poof"), + particle("minecraft:smoke"), + ) else { + return; + }; + // Level.DEFAULT_EXPLOSION_BLOCK_PARTICLES. + let info = |particle, scaling| play::ExplosionParticle { + particle, + scaling, + speed: 1.0, + weight: 1, + }; + let packet = C::Explode(play::Explode { + center, + radius, + block_count: block_count as i32, + knockback: None, + particle: at_center, + sound: match host + .hub + .registry_id("minecraft:sound_event", "minecraft:entity.generic.explode") + { + Some(id) => (id, None), + None => (-1, Some(("minecraft:entity.generic.explode".into(), None))), + }, + block_particles: vec![info(poof, 0.5), info(smoke, 1.0)], + play_sound: false, + }); + host.hub.broadcast_near(center, 64.0, &packet, None); + } +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 786399dac..83aafecc2 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -129,23 +129,6 @@ impl Game<'_> { } /// The screen title: the custom name, else the profession (the client /// adds the level itself). - #[allow(dead_code)] - fn merchant_title(&self, state: &MerchantState) -> String { - if let Some(name) = &state.name { - return name.clone(); - } - let e = &self.res.stations().enchantments; - let profession = state.session.profession.trim_start_matches("minecraft:"); - if state.session.villager { - e.translate(&format!("entity.minecraft.villager.{profession}")) - .unwrap_or(profession) - .to_owned() - } else { - e.translate("entity.minecraft.wandering_trader") - .unwrap_or("Wandering Trader") - .to_owned() - } - } /// `ServerPlayer.sendMerchantOffers`, when the offers changed. fn lan_send_offers( &mut self, diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 47d06254d..d239c69d0 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,10 +1,10 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: dragon egg teleportation (2015), a consumable's teleport -//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and -//! scraping (3005). +//! on a block: bone meal's growth (1505), dragon egg teleportation (2015), a +//! consumable's teleport (2017), electric sparks (3002), waxing (3003), wax +//! off (3004) and scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; -use horizon_core::position::BlockPos; +use horizon_core::{position::BlockPos, random::RandomSource}; use horizon_world::level::LevelEvent; impl Game<'_> { @@ -42,6 +42,65 @@ impl Game<'_> { self.particles.add(&options, p, v); } } + /// `BoneMealItem.addGrowthParticles` (event 1505, `count` the data): + /// happy villager sparks over a spreading block's neighbourhood (grass, + /// nylium, netherrack, moss) or water, or inside a growing block. + pub(super) fn growth_particles(&mut self, pos: BlockPos, count: i32) { + let p = [pos.x, pos.y, pos.z]; + let state = self.world.block(p[0], p[1], p[2]); + let facts = self.res.facts(); + // ParticleUtils.spawnParticles(level, pos, count, xzSpread, ySpread, + // allowFloatingParticles, particle). + let (at, count, xz, height, floating) = match self.res.behaviours().bone_meal_spreads(state) + { + Some(spreads) => { + // BonemealableBlock.getParticlePos: below for rooted dirt + // (its hanging roots) and mangrove leaves (their propagule). + let at = match &*facts.get(state).name { + "minecraft:rooted_dirt" | "minecraft:mangrove_leaves" => [p[0], p[1] - 1, p[2]], + _ => p, + }; + if spreads { + (at, count * 3, 3.0, 1.0, false) + } else { + // ParticleUtils.spawnParticleInBlock: up to the + // block's shape (a full block when air). + let inside = self.world.block(at[0], at[1], at[2]); + let height = if facts.is_air(inside) { + 1.0 + } else { + facts + .get(inside) + .outline + .iter() + .map(|b| b[4]) + .fold(0.0, f64::max) + }; + (at, count, 0.5, height, true) + } + } + None if &*facts.get(state).name == "minecraft:water" => (p, count * 3, 3.0, 1.0, false), + None => return, + }; + let options = ParticleOptions::simple(ParticleType::HappyVillager); + for _ in 0..count.max(0) { + let r = self.particles.level_random(); + let v = [0.0; 3].map(|_: f64| r.next_gaussian() * 0.02); + let start = 0.5 - xz; + let x = f64::from(at[0]) + start + r.next_double() * xz * 2.0; + let y = f64::from(at[1]) + r.next_double() * height; + let z = f64::from(at[2]) + start + r.next_double() * xz * 2.0; + let below = [x.floor() as i32, y.floor() as i32 - 1, z.floor() as i32]; + if floating + || !self + .res + .facts() + .is_air(self.world.block(below[0], below[1], below[2])) + { + self.particles.add(&options, [x, y, z], v); + } + } + } /// Queue and play level event `id` at `pos` (`Level.levelEvent`). pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) { self.level_events.push(LevelEvent::LevelEvent { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 94e61d948..ae2de00e6 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -133,7 +133,7 @@ impl Game<'_> { } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { let render = std::sync::Arc::new(self.pack.assets.reload(root)?); - let mut atlas = HudAtlas::build(root)?; + let mut atlas = HudAtlas::build_over(root, &self.vanilla_root())?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; let gui = super::UiResources { diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 7b466b3bb..b17316e08 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -18,6 +18,8 @@ use horizon_core::{geometry::Vec3, random::RandomSource}; /// A thrown splash or lingering potion in flight. #[derive(Clone, Debug)] pub(super) struct ThrownPotion { + /// Its entity id once a server's clients track it (0 until then). + id: u32, stack: ItemStack, /// The position before the last tick, for drawing between ticks. previous: Vec3, @@ -47,6 +49,7 @@ impl Game<'_> { /// player's throws and dispensers both end up here). pub(super) fn launch_thrown(&mut self, stack: ItemStack, position: Vec3, velocity: Vec3) { self.potions.thrown.push(ThrownPotion { + id: 0, stack, previous: position, position, @@ -90,19 +93,78 @@ impl PotionState { pub(super) fn thrown_entities(&self) -> Vec<(&'static str, Vec3, Vec3)> { self.thrown .iter() - .map(|t| { - let kind = match &*t.stack.item { - "minecraft:lingering_potion" => "minecraft:lingering_potion", - "minecraft:experience_bottle" => "minecraft:experience_bottle", - _ => "minecraft:splash_potion", - }; - (kind, t.position, t.velocity) - }) + .map(|t| (thrown_kind(&t.stack), t.position, t.velocity)) .collect() } pub(super) fn clear_thrown(&mut self) { self.thrown.clear(); } + /// Their entity ids, for a server to number them. + pub(super) fn thrown_ids(&mut self) -> impl Iterator { + self.thrown.iter_mut().map(|t| &mut t.id) + } + /// The numbered ones as a server's clients track them: (id, entity + /// type, item, position, motion). + pub(super) fn thrown_tracked( + &self, + ) -> impl Iterator { + self.thrown.iter().filter(|t| t.id != 0).map(|t| { + ( + t.id, + thrown_kind(&t.stack), + &t.stack, + t.position, + t.velocity, + ) + }) + } + /// `handleAddEntity` for a thrown potion or bottle on a server's client: + /// drawn where the server says (its item comes in its entity data). + pub(super) fn add_remote_thrown(&mut self, id: u32, kind: &str, at: Vec3, velocity: Vec3) { + self.thrown.retain(|t| t.id != id); + let item = match kind { + "minecraft:lingering_potion" | "minecraft:experience_bottle" => kind, + _ => "minecraft:splash_potion", + }; + self.thrown.push(ThrownPotion { + id, + stack: ItemStack::new(item, 1), + previous: at, + position: at, + velocity, + age: 0, + }); + } + /// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it shows. + pub(super) fn remote_thrown_item(&mut self, id: u32, stack: ItemStack) { + if let Some(t) = self.thrown.iter_mut().find(|t| t.id == id) { + t.stack = stack; + } + } + /// One tick of a server's client: `step` moves each toward where the + /// server put it. + pub(super) fn step_remote_thrown(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.thrown { + t.previous = t.position; + t.age += 1; + t.position = step(t.id, t.position); + } + } + pub(super) fn remove_remote_thrown(&mut self, id: u32) { + self.thrown.retain(|t| t.id != id); + } + pub(super) fn has_thrown(&self, id: u32) -> bool { + self.thrown.iter().any(|t| t.id == id) + } +} + +/// The entity type of a thrown potion or bottle. +fn thrown_kind(stack: &ItemStack) -> &'static str { + match &*stack.item { + "minecraft:lingering_potion" => "minecraft:lingering_potion", + "minecraft:experience_bottle" => "minecraft:experience_bottle", + _ => "minecraft:splash_potion", + } } impl Game<'_> { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index dfde08d7f..118db7710 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -101,7 +101,7 @@ fn place_interpolated(m: &mut Mob, at: PosRot) { pub(super) struct Remote { pub session: Session, pub brand: String, - builtin: Arc, + pub(super) builtin: Arc, lang: Arc, pub(super) registries: Arc, joined: bool, @@ -164,6 +164,8 @@ pub(super) struct Remote { level_players: HashMap, /// The local player's profile UUID (always in the level). profile: u128, + /// The local player's profile name: its score holder and team member. + pub(super) profile_name: String, destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, input: horizon_client::interaction_input::InteractionInput, @@ -411,6 +413,7 @@ impl Game<'_> { online_mode: false, level_players: HashMap::new(), profile: 0, + profile_name: String::new(), destroying: None, destroy_delay: 0, input: Default::default(), @@ -795,6 +798,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.joined = true; r.profile = uuid; + r.profile_name = name.clone(); r.status = format!("Joined as {name}; loading terrain..."); } } @@ -1725,29 +1729,12 @@ impl Game<'_> { self.block_entity_event(p.pos, i32::from(p.b0), i32::from(p.b1)); } } - C::LevelEvent(p) if p.kind == 2015 => { - self.dragon_egg_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2017 => { - self.consume_teleport_particles(p.pos, p.data); - } - C::LevelEvent(p) if p.kind == 2001 => { - // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. - let state = BlockStateId(p.data.max(0) as u32); - let s = self.res.facts().get(state).sounds.clone(); - let at = [ - f64::from(p.pos[0]) + 0.5, - f64::from(p.pos[1]) + 0.5, - f64::from(p.pos[2]) + 0.5, - ]; - self.audio.play( - &s.break_sound, - Some(at), - (s.volume + 1.0) / 2.0, - s.pitch * 0.8, - ); - self.destroy_particles(p.pos, state); - } + // ClientLevel.levelEvent: LevelEventHandler, as this client's own + // level plays them (particles and sounds: a spawner's burst, bone + // meal, waxing, a block broken by someone else). + C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data), + C::LevelParticles(p) => self.remote_level_particles(&p), + C::Explode(p) => self.remote_explode(&p), C::Sound(p) => { let name = match &p.sound.1 { Some((location, _)) => Some(location.clone()), @@ -2147,6 +2134,15 @@ impl Game<'_> { m.swing(); } } + // The player's own instances: its maximum health (the hearts the + // HUD draws and the health it may hold), reach, speed and so on. + // Then the received health again, which the old maximum clamped. + C::UpdateAttributes(p) if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) => { + if let Some(pl) = self.player.as_mut() { + horizon_client::lan::attributes::apply(&mut pl.attributes, &p.values); + } + self.apply_remote_health(); + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -3049,6 +3045,7 @@ impl Game<'_> { self.remote_handle_input(); // ClientLevel.tick: the border's size change. self.border.tick(); + self.player_border(); self.tick_remote_entities(running); // ClientLevel.tickBlockEntities: chest lids, shulker boxes, bells. self.tick_block_entity_anims(); @@ -3821,6 +3818,8 @@ impl Game<'_> { } if reacts { self.predict_use(&changes, seq); + } else if let Some(stack) = held.as_ref() { + self.predict_item_on_block(stack, &hit); } if held_block { if reacts @@ -3839,6 +3838,38 @@ impl Game<'_> { false } + /// `Item.useOn` on this client's level for the items whose effects are + /// the clicker's own (`Level.levelEvent(player, ...)` and + /// `playSound(player, ...)`: the server sends them to the others only): + /// honeycomb waxing copper, and an axe, hoe or shovel transforming a + /// block (stripping, scraping, removing wax, tilling, making a path). + fn predict_item_on_block(&mut self, stack: &ItemStack, hit: &super::Hit) { + let at = [ + f64::from(hit.pos[0]) + 0.5, + f64::from(hit.pos[1]) + 0.5, + f64::from(hit.pos[2]) + 0.5, + ]; + if &*stack.item == "minecraft:honeycomb" { + // HoneycombItem.useOn. + let registry = self.pack.assets.registry; + let clicked = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + let waxes = registry + .state(clicked) + .and_then(|old| self.res.transformers().waxed(registry, old)) + .is_some(); + if waxes { + self.level_event_at(3003, hit.pos, 0); + self.audio + .play("minecraft:item.honeycomb.wax_on", Some(at), 1.0, 1.0); + } + } else if let Some((_, sound, _, _, particle)) = + self.block_transform(stack, hit.pos, hit.face) + { + self.transform_particle(&particle, hit.pos); + self.audio.play(&sound, Some(at), 1.0, 1.0); + } + } + /// MultiPlayerGameMode.useItemOn inside startPrediction: the blocks the /// use changed on this client's level at once, each kept as predicted /// under the use's sequence until the server acknowledges it (a use the diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs index c008611f6..82d0a11e2 100644 --- a/crates/horizon-client/src/game/remote_projectiles.rs +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -79,6 +79,15 @@ impl Game<'_> { self.rockets .push(super::fireworks::Rocket::remote(id, at, velocity)); } + "minecraft:splash_potion" + | "minecraft:lingering_potion" + | "minecraft:experience_bottle" => { + self.potions.add_remote_thrown(id, kind, at, velocity); + } + "minecraft:eye_of_ender" => { + self.end + .add_remote_eye(id, position, [velocity.x, velocity.y, velocity.z]) + } "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { id, position: at, @@ -105,6 +114,17 @@ impl Game<'_> { /// `handleSetEntityData` for these types: what changes how they look. pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { let id = id as u32; + if self.potions.has_thrown(id) { + // ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is. + for (index, _, value) in values { + if let (8, Value::Item(stack)) = (index, value) + && let Some(stack) = self.to_stack(stack) + { + self.potions.remote_thrown_item(id, stack); + } + } + return; + } for (index, _, value) in values { if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { // PrimedTnt.DATA_FUSE_ID. @@ -184,6 +204,11 @@ impl Game<'_> { c.time += 1; c.position = step(c.id, c.position); } + self.potions.step_remote_thrown(&mut step); + self.end.step_remote_eyes(|id, at| { + let at = step(id, Vec3::new(at[0], at[1], at[2])); + [at.x, at.y, at.z] + }); } pub(super) fn remove_remote_projectile(&mut self, id: u32) { @@ -193,6 +218,8 @@ impl Game<'_> { self.tridents.retain(|t| t.id != id); self.rockets.retain(|r| r.id != id); self.crystals.retain(|c| c.id != id); + self.potions.remove_remote_thrown(id); + self.end.remove_remote_eye(id); } /// Every one a server sent (a new connection, level or dimension). @@ -203,6 +230,8 @@ impl Game<'_> { self.tridents.clear(); self.rockets.clear(); self.crystals.clear(); + self.potions.clear_thrown(); + self.end.clear_remote_eyes(); } /// Their kind and place, for `status`. @@ -225,6 +254,12 @@ impl Game<'_> { for p in &self.creatures.projectiles { out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); } + for (kind, p, _) in self.potions.thrown_entities() { + out.push(json!({"kind": kind, "position": at(p)})); + } + for (id, p) in self.end.eye_positions() { + out.push(json!({"id": id, "kind": "minecraft:eye_of_ender", "position": p})); + } out } } diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 4d60c2df7..4905fb80f 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -324,6 +324,22 @@ impl Game<'_> { } } } + /// `ServerScoreboard`'s packets: each placed player's client is sent + /// what changed on the board since it was last sent it (all of it on + /// joining), lan/scoreboard.rs. + pub(super) fn lan_sync_scoreboard(&mut self, host: &mut super::lan::LanHost) { + if host.hub.guests.iter().all(|g| !g.placed) { + return; + } + self.load_scoreboard(); + let view = horizon_client::lan::scoreboard::View::of(&self.score.board); + for g in host.hub.guests.iter_mut().filter(|g| g.placed) { + if g.scoreboard != view { + g.send_all(&g.scoreboard.changes(&view)); + g.scoreboard = view.clone(); + } + } + } /// `ServerPlayer.doTick` score updates and the statistic criteria. pub(super) fn tick_scoreboard(&mut self) { self.load_scoreboard(); @@ -563,19 +579,42 @@ impl Game<'_> { // ---- the sidebar ----------------------------------------------------------- - /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. - pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + /// The objective in the player's team's sidebar slot, else the sidebar's. + fn sidebar_objective(&self) -> Option<&sb::Objective> { let board = &self.score.board; if board.display.is_empty() { - return; + return None; } + // A server's client is in its team by its profile name. + let name = self + .remote + .as_ref() + .map_or(PLAYER_NAME, |r| r.profile_name.as_str()); let team_slot = board - .players_team(PLAYER_NAME) + .players_team(name) .and_then(|t| t.color.as_ref()) .map(|c| format!("sidebar.team.{c}")) .and_then(|slot| board.display_objective(&slot)); - let Some(objective) = team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) - else { + team_slot.or_else(|| board.display_objective(sb::SLOT_SIDEBAR)) + } + /// The sidebar the HUD shows: its objective and its lines, for `status`. + pub(super) fn sidebar_status(&self) -> serde_json::Value { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { + return serde_json::Value::Null; + }; + let scores: serde_json::Map = board + .scores + .iter() + .filter_map(|(holder, s)| Some((holder.clone(), s.get(&objective.name)?.value.into()))) + .collect(); + serde_json::json!({ "objective": objective.name, "title": objective.display_text().plain(), "scores": scores }) + } + + /// `Hud.extractScoreboardSidebar` / `displayScoreboardSidebar`. + pub(super) fn draw_scoreboard(&self, batch: &mut HudBatch) { + let board = &self.score.board; + let Some(objective) = self.sidebar_objective() else { return; }; let draws = hud_overlays::sidebar( diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 1e94ec995..02b94c0f6 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -455,6 +455,7 @@ impl Game<'_> { tick_frozen: self.clock.frozen(), tick_steps: self.clock.step_state(), collision: Some(self.collision), + border: &self.border, } } } diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 82a9603e2..fc217bf5c 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1491,6 +1491,13 @@ impl Renderer { mapped_at_creation: false, }); let (atlas_pixels, atlas_width, atlas_height) = hud_atlas; + let limit = device.limits().max_texture_dimension_2d; + if atlas_width.max(atlas_height) > limit { + return Err(format!( + "the shared atlas is {atlas_width}x{atlas_height}; this GPU allows {limit}x{limit}" + ) + .into()); + } let atlas = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { @@ -2456,10 +2463,6 @@ impl Renderer { view_formats: &config.view_formats, }) } - /// Rendering to a texture instead of the window (`--offscreen`). - pub fn is_offscreen(&self) -> bool { - self.surface.is_none() - } /// Release the window surface before another renderer uses the same window. pub fn release_surface(&mut self) { self.surface = None; diff --git a/crates/horizon-client/src/gfx/lod.rs b/crates/horizon-client/src/gfx/lod.rs index 734110b5c..3ebec378b 100644 --- a/crates/horizon-client/src/gfx/lod.rs +++ b/crates/horizon-client/src/gfx/lod.rs @@ -119,10 +119,6 @@ impl Tile { } impl Renderer { - pub fn resident_lods(&self) -> usize { - self.lods.len() - } - pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) { self.remove_lod(key); if let Some(bounds) = Bounds::mesh(mesh) diff --git a/crates/horizon-client/src/gossip.rs b/crates/horizon-client/src/gossip.rs index 9a964a3e6..9ea4a668d 100644 --- a/crates/horizon-client/src/gossip.rs +++ b/crates/horizon-client/src/gossip.rs @@ -7,7 +7,6 @@ use std::collections::BTreeMap; /// `ReputationEventType` amounts. pub const REPUTATION_CHANGE_PER_EVENT: i32 = 25; -pub const REPUTATION_CHANGE_PER_EVERLASTING_MEMORY: i32 = 20; pub const REPUTATION_CHANGE_PER_TRADE: i32 = 2; /// `GossipContainer.DISCARD_THRESHOLD`: values below this are forgotten. const DISCARD_THRESHOLD: i32 = 2; diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index fe797af3e..6617ef009 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -486,14 +486,6 @@ impl Item { _ => return None, }) } - /// Caption and value text, split from the label ("Caption: Value"). - pub fn caption_value(self, s: &Settings) -> (String, String) { - let label = self.label(s).plain(); - match label.split_once(": ") { - Some((c, v)) => (c.to_owned(), v.to_owned()), - None => (label, String::new()), - } - } pub fn slider(self, s: &Settings) -> Option { match self { Item::Vanilla(o) => o.slider_position(s), diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index 82e606947..cc922752e 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -9,6 +9,11 @@ use std::{ }; use wgpu::util::DeviceExt; +/// A sprite's atlas region, and its size in GUI pixels: the size of the +/// default resources' texture of that name, whatever the resolution of the +/// pack that replaced it (vanilla's GUI code draws in those units: `blit` +/// divides by the texture size it is given, sprites by their `gui.scaling` +/// size). Textures the default resources lack keep their own size. #[derive(Clone, Copy, Debug)] pub struct Rect { pub u0: f32, @@ -18,6 +23,15 @@ pub struct Rect { pub w: u32, pub h: u32, } +impl Rect { + /// The region's size in texels of an atlas this large. + pub fn texels(&self, (width, height): (u32, u32)) -> (u32, u32) { + ( + ((self.u1 - self.u0) * width as f32).round() as u32, + ((self.v1 - self.v0) * height as f32).round() as u32, + ) + } +} /// `TextureMetadataSection`'s `blur` and `clamp`: how vanilla samples a /// standalone texture (`ReloadableTexture.setSampler`: linear rather than /// nearest filtering, clamp-to-edge rather than repeat addressing). @@ -54,6 +68,9 @@ pub struct HudAtlas { } /// Atlas rows reserved for glyphs rasterized at run time. pub const GLYPH_ROWS: u32 = 512; +/// The largest atlas side: the 2D texture limit of the GPUs Horizon runs on +/// (Apple silicon, RADV and Intel allow 16384; NVIDIA 32768). +pub const MAX_ATLAS_SIZE: u32 = 16384; /// 128x128 atlas slots for map textures. A lobby paints its signs as walls of /// framed maps, so the pool holds a wall; too few slots re-upload every map /// every frame. 26.3's `MapTextureManager` keeps a texture per map instead. @@ -89,6 +106,15 @@ pub fn decode_bytes(data: &[u8]) -> Result<(u32, u32, Vec)> { } Ok((info.width, info.height, rgba)) } +/// A PNG's width and height, from its header alone. +fn png_size(path: &Path) -> Option<(u32, u32)> { + use std::io::Read; + let mut header = [0u8; 24]; + fs::File::open(path).ok()?.read_exact(&mut header).ok()?; + let field = |at: usize| u32::from_be_bytes(header[at..at + 4].try_into().unwrap_or_default()); + (header[..8] == *b"\x89PNG\r\n\x1a\n" && header[12..16] == *b"IHDR") + .then(|| (field(16), field(20))) +} fn walk(dir: &Path, out: &mut Vec) { let Ok(entries) = fs::read_dir(dir) else { return; @@ -201,8 +227,14 @@ impl HudAtlas { (g.rect, g.advance) } pub fn build(root: &Path) -> Result { + Self::build_over(root, root) + } + /// The atlas of a resource root that layers packs over `defaults` (the + /// game's own resources), whose textures give the sprites' GUI sizes. + pub fn build_over(root: &Path, defaults: &Path) -> Result { Self::pack( root, + defaults, &[ "gui", "item", @@ -265,14 +297,53 @@ impl HudAtlas { /// holding its textures. The pixels are dropped once the glyph widths are /// read, since nothing uploads them. pub fn fonts(root: &Path) -> Result { - let mut atlas = Self::pack(root, &["font"], false)?; + let mut atlas = Self::pack(root, root, &["font"], false)?; atlas.pixels = Vec::new(); Ok(atlas) } + /// Shelf placements of `images` (tallest first) in the narrowest atlas + /// width from 4096 up that keeps the atlas, glyph rows included, within + /// `max` texels a side; and the first row free for glyphs. High-resolution + /// packs fill a 4096-wide atlas past what GPUs allow (Faithful 64x needs + /// 32768 rows); vanilla's stitcher fails the reload when its atlases don't + /// fit, and the packs are then turned off (`Minecraft.clearResourcePacksOnError`). + fn layout(images: &[PackedImage], max: u32) -> Result<(u32, Vec<(u32, u32)>, u32)> { + let mut width = 4096.min(max); + loop { + let mut placements = Vec::with_capacity(images.len()); + let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); + for (_, w, h, _) in images { + if x + w + 1 > width { + x = 0; + y += row + 1; + row = 0; + } + placements.push((x, y)); + x += w + 1; + row = row.max(*h); + } + let glyph_region = y + row + 1; + let wide_enough = images.iter().all(|i| i.1 < width); + if wide_enough && glyph_region + GLYPH_ROWS <= max { + return Ok((width, placements, glyph_region)); + } + if width >= max { + let texels: u64 = images.iter().map(|i| u64::from(i.1) * u64::from(i.2)).sum(); + return Err(format!( + "the textures ({} images, {texels} texels) do not fit a {max}x{max} atlas", + images.len() + ) + .into()); + } + width = (width * 2).min(max); + } + } /// Pack the textures under these folders of `textures/`, and for the /// `full` atlas the generated sprites and the run-time slots too. - fn pack(root: &Path, folders: &[&str], full: bool) -> Result { + fn pack(root: &Path, defaults: &Path, folders: &[&str], full: bool) -> Result { let textures = root.join("assets/minecraft/textures"); + let default_textures = + (defaults != root).then(|| defaults.join("assets/minecraft/textures")); let mut files = Vec::new(); for folder in folders { walk(&textures.join(folder), &mut files); @@ -281,7 +352,8 @@ impl HudAtlas { let s = p.to_string_lossy(); !s.contains("title/background") && !s.contains("realms") && !s.contains("presets") }); - let decode_one = |path: &PathBuf| -> Option<(PackedImage, Option)> { + type Decoded = (PackedImage, Option, Option<(u32, u32)>); + let decode_one = |path: &PathBuf| -> Option { let name = path .strip_prefix(&textures) .ok()? @@ -289,18 +361,29 @@ impl HudAtlas { .to_string_lossy() .replace('\\', "/"); let (w, mut h, pixels) = decode(path).ok()?; - let is_frame_strip = (name.starts_with("block/") || name.starts_with("item/")) && h > w; - let pixels = if is_frame_strip { + // Animated strips keep their first frame. + let frames = name.starts_with("block/") || name.starts_with("item/"); + let pixels = if frames && h > w { h = w; pixels[..(w * w * 4) as usize].to_vec() } else { pixels }; + // The default texture's size, when a pack's differs from it. + let gui_size = default_textures + .as_ref() + .and_then(|d| png_size(&d.join(format!("{name}.png")))) + .map(|(dw, dh)| (dw, if frames { dh.min(dw) } else { dh })) + .filter(|&size| size != (w, h)); let flags = fs::read_to_string(path.with_extension("png.mcmeta")) .ok() .and_then(|json| TextureFlags::from_mcmeta(&json)); - (w <= 1024 && (h <= 512 || name.starts_with("font/"))) - .then_some(((name, w, h, pixels), flags)) + let (gw, gh) = gui_size.unwrap_or((w, h)); + (gw <= 1024 && (gh <= 512 || name.starts_with("font/"))).then_some(( + (name, w, h, pixels), + flags, + gui_size, + )) }; let threads = std::thread::available_parallelism().map_or(2, |n| n.get()); let chunk = files.len().div_ceil(threads).max(1); @@ -317,11 +400,15 @@ impl HudAtlas { .collect() }); let mut flags = HashMap::new(); + let mut gui_sizes = HashMap::new(); let mut images: Vec = Vec::with_capacity(decoded.len()); - for (image, image_flags) in decoded { + for (image, image_flags, gui_size) in decoded { if let Some(f) = image_flags { flags.insert(image.0.clone(), f); } + if let Some(size) = gui_size { + gui_sizes.insert(image.0.clone(), size); + } images.push(image); } if full { @@ -351,21 +438,10 @@ impl HudAtlas { } } images.sort_by(|a, b| b.2.cmp(&a.2).then(b.1.cmp(&a.1))); - let width = 4096u32; - let mut placements = Vec::with_capacity(images.len()); - let (mut x, mut y, mut row) = (0u32, 0u32, 0u32); - for (_, w, h, _) in &images { - if x + w + 1 > width { - x = 0; - y += row + 1; - row = 0; - } - placements.push((x, y)); - x += w + 1; - row = row.max(*h); - } - let glyph_region = y + row + 1; - let height = (glyph_region + GLYPH_ROWS).next_power_of_two(); + let (width, placements, glyph_region) = Self::layout(&images, MAX_ATLAS_SIZE)?; + // A multiple of 1024 rather than a power of two: the default resources + // need 4096x5120 (8192 rows before), Faithful 32x 4096x12288 (16384). + let height = (glyph_region + GLYPH_ROWS).next_multiple_of(1024); let mut pixels = vec![0u8; (width * height * 4) as usize]; let mut sprites = HashMap::new(); for ((name, w, h, data), (px, py)) in images.iter().zip(placements) { @@ -376,6 +452,7 @@ impl HudAtlas { } let b = u32::from(bordered.contains(name)); let (px, py, w, h) = (px + b, py + b, w - 2 * b, h - 2 * b); + let (gw, gh) = gui_sizes.get(name).copied().unwrap_or((w, h)); sprites.insert( name.clone(), Rect { @@ -383,8 +460,8 @@ impl HudAtlas { v0: py as f32 / height as f32, u1: (px + w) as f32 / width as f32, v1: (py + h) as f32 / height as f32, - w, - h, + w: gw, + h: gh, }, ); } @@ -404,14 +481,15 @@ impl HudAtlas { .find(|a| a.layer == layer) .cloned() { - let image = animation.resized_pixels(animation.frame(0), rect.w, rect.h); + let (tw, th) = rect.texels((width, height)); + let image = animation.resized_pixels(animation.frame(0), tw, th); let x = (rect.u0 * width as f32).round() as usize; let y = (rect.v0 * height as f32).round() as usize; - for row in 0..rect.h as usize { + let row_bytes = tw as usize * 4; + for row in 0..th as usize { let dst = ((y + row) * width as usize + x) * 4; - let src = row * rect.w as usize * 4; - pixels[dst..dst + rect.w as usize * 4] - .copy_from_slice(&image[src..src + rect.w as usize * 4]); + let src = row * row_bytes; + pixels[dst..dst + row_bytes].copy_from_slice(&image[src..src + row_bytes]); } fire_animations.push((rect, animation)); } @@ -783,24 +861,6 @@ impl HudBatch { }; self.text_styled(atlas, &t, x, y, color, shadow) } - /// `text_styled` under a pose: GUI positions scaled by `scale`, then - /// moved to `origin` (Matrix3x2fStack translate + scale). - pub fn text_posed( - &mut self, - atlas: &HudAtlas, - text: &crate::text::Text, - at: [f32; 2], - color: u32, - scale: f32, - origin: [f32; 2], - ) -> f32 { - let start = self.vertices.len(); - let advance = self.text_styled(atlas, text, at[0], at[1], color, true); - for v in &mut self.vertices[start..] { - v.pos = [origin[0] + v.pos[0] * scale, origin[1] + v.pos[1] * scale]; - } - advance - } /// Font.drawInternal: styled glyphs, shadows first, with bold, italic, /// underline and strikethrough. `color` is the default colour and alpha. pub fn text_styled( @@ -1162,7 +1222,8 @@ impl HudRenderer { if frame == *previous { continue; } - let pixels = animation.resized_pixels(frame, rect.w, rect.h); + let (w, h) = rect.texels((texture.width(), texture.height())); + let pixels = animation.resized_pixels(frame, w, h); uploads.texture( encoder, wgpu::TexelCopyTextureInfo { @@ -1175,8 +1236,8 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, - rect.w, - rect.h, + w, + h, &pixels, ); *previous = frame; @@ -1340,6 +1401,87 @@ impl HudRenderer { mod tests { use super::*; + /// `count` images of `w x h`; layout reads only their sizes. + fn sized(count: usize, w: u32, h: u32) -> Vec { + (0..count) + .map(|i| (format!("i{i}"), w, h, Vec::new())) + .collect() + } + fn assert_inside(images: &[PackedImage], width: u32, placements: &[(u32, u32)], free: u32) { + for ((_, w, h, _), (x, y)) in images.iter().zip(placements) { + assert!( + x + w <= width && y + h < free, + "{x},{y} {w}x{h} outside {width}x{free}" + ); + } + } + fn write_png(root: &Path, name: &str, w: u32, h: u32) { + let path = root.join(format!("assets/minecraft/textures/{name}.png")); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), w, h); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let pixels = vec![255; (w * h * 4) as usize]; + encoder + .write_header() + .unwrap() + .write_image_data(&pixels) + .unwrap(); + } + #[test] + fn a_pack_texture_keeps_the_default_textures_gui_size() { + let temp = std::env::temp_dir().join(format!("horizon-gui-size-{}", std::process::id())); + let (defaults, pack) = (temp.join("defaults"), temp.join("pack")); + write_png(&defaults, "gui/container/inventory", 256, 256); + write_png(&defaults, "gui/sprites/widget/button", 200, 20); + write_png(&defaults, "block/stone", 16, 16); + write_png(&defaults, "item/compass", 16, 512); + // Faithful 64x's inventory (past the 512 rows a texture may have), + // 32x's button and stone, an animated strip, and a texture of its own. + write_png(&pack, "gui/container/inventory", 1024, 1024); + write_png(&pack, "gui/sprites/widget/button", 400, 40); + write_png(&pack, "block/stone", 32, 32); + write_png(&pack, "item/compass", 32, 1024); + write_png(&pack, "gui/sprites/pack_only", 30, 10); + let atlas = HudAtlas::build_over(&pack, &defaults).unwrap(); + let _ = fs::remove_dir_all(&temp); + let size = (atlas.width, atlas.height); + for (name, gui, texels) in [ + ("gui/container/inventory", (256, 256), (1024, 1024)), + ("gui/sprites/widget/button", (200, 20), (400, 40)), + ("block/stone", (16, 16), (32, 32)), + ("item/compass", (16, 16), (32, 32)), + ("gui/sprites/pack_only", (30, 10), (30, 10)), + ] { + let r = atlas.sprites[name]; + assert_eq!(((r.w, r.h), r.texels(size)), (gui, texels), "{name}"); + } + } + #[test] + fn the_default_textures_keep_a_4096_wide_atlas() { + let images = sized(400, 64, 64); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 4096); + assert_inside(&images, width, &placements, free); + } + #[test] + fn a_high_resolution_pack_widens_the_atlas_to_fit_the_gpu() { + // 34 rows of three 1024x512 GUI textures: 17442 rows at 4096 wide, + // past the 16384 GPUs allow (Faithful 64x needed 32768). + let images = sized(100, 1024, 512); + let (width, placements, free) = HudAtlas::layout(&images, MAX_ATLAS_SIZE).unwrap(); + assert_eq!(width, 8192); + assert!(free + GLYPH_ROWS <= MAX_ATLAS_SIZE); + assert_inside(&images, width, &placements, free); + } + #[test] + fn textures_that_cannot_fit_are_an_error_not_a_gpu_panic() { + let error = HudAtlas::layout(&sized(300, 1024, 1024), MAX_ATLAS_SIZE).unwrap_err(); + assert!(error.to_string().contains("do not fit a 16384x16384 atlas")); + // One image wider than the largest atlas. + assert!(HudAtlas::layout(&sized(1, 2048, 16), 2048).is_err()); + } + #[test] fn a_wrapped_border_repeats_the_opposite_edges() { // 2x2 texels a b / c d, one byte each in red. diff --git a/crates/horizon-client/src/item_render.rs b/crates/horizon-client/src/item_render.rs index 45531bedd..c2f5c8400 100644 --- a/crates/horizon-client/src/item_render.rs +++ b/crates/horizon-client/src/item_render.rs @@ -124,17 +124,6 @@ impl ItemRenderState { pub fn is_empty(&self) -> bool { self.layers.is_empty() } - /// `pickParticleMaterial`: a random layer's particle sprite. - pub fn pick_particle( - &self, - random: &mut impl horizon_core::random::RandomSource, - ) -> Option { - if self.layers.is_empty() { - return None; - } - let i = random.next_int_bound(self.layers.len() as i32).unwrap_or(0) as usize; - self.layers.get(i).map(|l| l.particle.clone()) - } /// `usesBlockLight` of the first layer (GUI lighting choice). pub fn uses_block_light(&self) -> bool { self.layers.first().is_some_and(|l| l.uses_block_light) diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index ee4d29d61..d8873e25c 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -236,6 +236,24 @@ mod tests { assert_eq!(vendor_name(0, "Apple M4 Pro"), "Apple"); } + /// wgpu is given the WGSL text: it must parse again. + fn reparse_error(pack: &JavaPasses) -> Option { + let passes = pack + .folders + .iter() + .flat_map(|f| f.passes.iter().chain(&f.final_pass)); + passes + .flat_map(|p| [(p, &p.vertex, "vsh"), (p, &p.fragment, "fsh")]) + .find_map(|(p, t, ext)| { + let e = naga::front::wgsl::parse_str(&t.wgsl).err()?; + Some(format!( + "{}.{ext}: {}", + p.pass.program, + e.emit_to_string(&t.wgsl) + )) + }) + } + /// The packs in `HORIZON_TEST_SHADERPACKS` (folders or zips) load as the /// game loads them, with their default options: the compatibility table /// of docs/shader-packs.md. Skipped when the variable isn't set. @@ -255,6 +273,10 @@ mod tests { for path in entries { let name = path.file_name().unwrap().to_string_lossy().into_owned(); match load(&path, &BTreeMap::new(), "Apple", "Apple M4 Pro") { + Ok(pack) if let Some(e) = reparse_error(&pack) => { + println!("{name}: {e}"); + failures.push(name); + } Ok(pack) => { let folders: Vec = pack .folders diff --git a/crates/horizon-client/src/keybinds.rs b/crates/horizon-client/src/keybinds.rs index 5f8c0876b..a59aa627c 100644 --- a/crates/horizon-client/src/keybinds.rs +++ b/crates/horizon-client/src/keybinds.rs @@ -295,15 +295,6 @@ impl KeyBinds { self.keys.insert(n, key.to_owned()); } } - /// Load `key_` from options.txt; false for unknown mappings. - pub fn set_saved(&mut self, name: &str, key: &str) -> bool { - if MAPPINGS.iter().any(|m| m.0 == name) { - self.set(name, key); - true - } else { - false - } - } pub fn saved(&self) -> Vec<(&'static str, String)> { MAPPINGS .iter() diff --git a/crates/horizon-client/src/keymapping.rs b/crates/horizon-client/src/keymapping.rs index e598fbf71..e438c27ce 100644 --- a/crates/horizon-client/src/keymapping.rs +++ b/crates/horizon-client/src/keymapping.rs @@ -104,8 +104,6 @@ pub const SNEAK: usize = 0; pub const SPRINT: usize = 1; /// Attack (mouse). pub const ATTACK: usize = 2; -/// Use (mouse). -pub const USE: usize = 3; /// The `ToggleKeyMapping`s `Options` builds: sneak and sprint (keyboard, /// restored after a screen), attack (mouse, restored) and use (mouse, not diff --git a/crates/horizon-client/src/lan/attributes.rs b/crates/horizon-client/src/lan/attributes.rs index bc208b6f9..eef565409 100644 --- a/crates/horizon-client/src/lan/attributes.rs +++ b/crates/horizon-client/src/lan/attributes.rs @@ -5,7 +5,7 @@ //! changed since (`getAttributesToSync`), to the trackers and the player itself. use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; use horizon_world::attributes::{ - Instance, Operation, + Instance, Modifier, Operation, entity::{AttributeId, EntityAttributes}, live::LiveAttributes, }; @@ -70,6 +70,48 @@ pub fn take_dirty i32>(map: &mut LiveAttributes) -> Vec i32>(map: &mut LiveAttributes, values: &[AttributeSnapshot]) { + for s in values { + let Some(key) = map + .keys() + .iter() + .find(|k| k.attribute().registry_id() == s.attribute) + .cloned() + else { + continue; + }; + let Ok(Some(handle)) = map.get_instance(Some(key)) else { + continue; + }; + let modifiers: Vec<_> = s + .modifiers + .iter() + .filter_map(|m| Modifier::new(&m.id, m.amount, operation(m.operation)).ok()) + .collect(); + let _ = map.edit(&handle, |instance, observer| { + instance.set_base_value(s.base, observer)?; + instance.remove_all(observer)?; + for m in modifiers { + instance.add_transient(m, observer)?; + } + Ok(()) + }); + } +} + +/// `AttributeModifier.Operation.BY_ID`. +fn operation(id: i32) -> Operation { + match id { + 1 => Operation::AddMultipliedBase, + 2 => Operation::AddMultipliedTotal, + _ => Operation::AddValue, + } +} + /// The client-syncable instances of a generic attribute map. pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator + '_ { let catalog = map.catalog(); diff --git a/crates/horizon-client/src/lan/border.rs b/crates/horizon-client/src/lan/border.rs new file mode 100644 index 000000000..b4e3ffc63 --- /dev/null +++ b/crates/horizon-client/src/lan/border.rs @@ -0,0 +1,130 @@ +//! The world border a server's players see: all of it when they enter a +//! level (`PlayerList.sendLevelInfo`), then each change as +//! `BorderChangeListener` broadcasts it: a new centre, a new size, a size +//! change in progress, a new warning time or distance. +use crate::worldborder::WorldBorder; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// `ClientboundInitializeBorderPacket`. +pub fn initialize(b: &WorldBorder) -> play::InitializeBorder { + let [center_x, center_z] = b.center(); + play::InitializeBorder { + center_x, + center_z, + old_size: b.size(), + new_size: b.target_size(), + lerp_time: b.remaining_ticks(), + absolute_max_size: b.absolute_max_size(), + warning_blocks: b.warning_distance, + warning_time: b.warning_time, + } +} + +/// The border as the players were last told of it. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Sent { + center: [f64; 2], + size: f64, + target: f64, + remaining: i64, + warning_distance: i32, + warning_time: i32, +} + +impl Sent { + pub fn of(b: &WorldBorder) -> Self { + Self { + center: b.center(), + size: b.size(), + target: b.target_size(), + remaining: b.remaining_ticks(), + warning_distance: b.warning_distance, + warning_time: b.warning_time, + } + } + + /// The packets that tell the players what changed since `self`, other + /// than a size change going on (which each client runs itself). + pub fn changes(&self, b: &WorldBorder) -> Vec { + let now = Self::of(b); + let mut out = Vec::new(); + if now.center != self.center { + out.push(C::SetBorderCenter(play::SetBorderCenter { + x: now.center[0], + z: now.center[1], + })); + } + // A change going on counts down a tick at a time (or not at all + // while the game is frozen), towards the same size. + let going_on = self.remaining > 0 + && now.target == self.target + && (now.remaining == self.remaining || now.remaining == self.remaining - 1); + if now.remaining > 0 { + if !going_on { + out.push(C::SetBorderLerpSize(play::SetBorderLerpSize { + old_size: now.size, + new_size: now.target, + lerp_time: now.remaining, + })); + } + } else if now.size != self.size && !(self.remaining > 0 && now.size == self.target) { + out.push(C::SetBorderSize(play::SetBorderSize { size: now.size })); + } + if now.warning_time != self.warning_time { + out.push(C::SetBorderWarningDelay(play::SetBorderWarningDelay { + delay: now.warning_time, + })); + } + if now.warning_distance != self.warning_distance { + out.push(C::SetBorderWarningDistance( + play::SetBorderWarningDistance { + blocks: now.warning_distance, + }, + )); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn kinds(packets: &[C]) -> Vec<&'static str> { + packets + .iter() + .map(|p| match p { + C::SetBorderCenter(_) => "center", + C::SetBorderSize(_) => "size", + C::SetBorderLerpSize(_) => "lerp", + C::SetBorderWarningDelay(_) => "delay", + C::SetBorderWarningDistance(_) => "distance", + _ => "other", + }) + .collect() + } + + #[test] + fn each_change_is_sent_once() { + let mut b = WorldBorder::default(); + let mut sent = Sent::of(&b); + assert!(sent.changes(&b).is_empty()); + b.set_center([4.0, -2.0]); + b.set_size(10.0); + b.warning_time = 30; + assert_eq!(kinds(&sent.changes(&b)), ["center", "size", "delay"]); + sent = Sent::of(&b); + // A change over 3 ticks: sent once, then each client runs it. + b.lerp_to(20.0, 3); + assert_eq!(kinds(&sent.changes(&b)), ["lerp"]); + for _ in 0..4 { + sent = Sent::of(&b); + b.tick(); + assert!(sent.changes(&b).is_empty(), "{:?}", sent.changes(&b)); + } + assert_eq!(b.size(), 20.0); + b.warning_distance = 1; + assert_eq!(kinds(&Sent::of(&b).changes(&b)), [] as [&str; 0]); + assert_eq!(kinds(&sent.changes(&b)), ["distance"]); + } +} diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 4236280cd..84e768879 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -15,9 +15,33 @@ use std::{ /// GameType ids. pub const SURVIVAL: i32 = 0; pub const CREATIVE: i32 = 1; -pub const ADVENTURE: i32 = 2; pub const SPECTATOR: i32 = 3; +/// The body state a player's file keeps that lives on `PlayerMotion`. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct SavedBody { + pub fire_ticks: i32, + pub air: i32, + pub fall_distance: f64, +} + +impl SavedBody { + /// The body state of `motion`, to save. + pub fn of(motion: &PlayerMotion) -> Self { + Self { + fire_ticks: motion.fire_ticks, + air: motion.air, + fall_distance: motion.fall_distance, + } + } + /// Put it on a new body. + pub fn apply(self, motion: &mut PlayerMotion) { + motion.fire_ticks = self.fire_ticks; + motion.air = self.air; + motion.fall_distance = self.fall_distance; + } +} + /// An effect as last sent in ClientboundUpdateMobEffectPacket. #[derive(Clone, Debug, PartialEq)] pub struct SentEffect { @@ -133,6 +157,9 @@ pub struct Guest { pub tracker: Tracker, // Player state the gameplay code reads and writes. pub motion: Option>, + /// What the player's file says of the body (`Entity.load`: the fire + /// and air ticks and the fall distance), for the first body it gets. + pub loaded_body: Option, /// The hurt and attack logs of the body it had before it respawned, /// until the new body takes them over (the control socket's `hurtlog` /// reads across a death). @@ -215,6 +242,8 @@ pub struct Guest { pub advancements_loaded: bool, pub advancements_visible: Vec, pub advancements_changed: std::collections::BTreeSet, + /// The server's scoreboard as this player's client has it (lan/scoreboard.rs). + pub scoreboard: super::scoreboard::View, /// Recipes unlocked since the client was last told /// (`ServerRecipeBook.addRecipes` sends them). pub recipes_unlocked: Vec, @@ -282,6 +311,7 @@ impl Guest { batch_quota: 0.0, tracker: Tracker::default(), motion: None, + loaded_body: None, logs_kept: None, inventory: vec![None; 36], armor: [None, None, None, None], @@ -326,6 +356,7 @@ impl Guest { advancements_loaded: false, advancements_visible: Vec::new(), advancements_changed: Default::default(), + scoreboard: Default::default(), recipes_unlocked: Vec::new(), } } diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index c8f2e980d..640d6616c 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -111,6 +111,8 @@ pub struct TickCtx<'a> { /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly /// check (none: moves are not checked against blocks). pub collision: Option<&'a BlockCollisionRegistry<'a>>, + /// The level's world border (PlayerList.sendLevelInfo sends it). + pub border: &'a crate::worldborder::WorldBorder, } /// What the gameplay code has to do for a guest. @@ -172,13 +174,6 @@ pub struct Hub { fn string(s: &str) -> Tag { Tag::String(JavaString::from(s)) } -pub fn yellow_translation(key: &str, args: &[&str]) -> Tag { - let mut t = translatable(key, args); - if let Tag::Compound(map) = &mut t { - map.insert(JavaString::from("color"), string("yellow")); - } - t -} /// Player.getDisplayName for a player in no team: the name, suggesting /// `/tell NAME `, showing the player on hover and inserting the name. @@ -898,17 +893,7 @@ impl Hub { fn send_level_info(&mut self, i: usize, ctx: &TickCtx) { let spawn = ctx.spawn; let g = &self.guests[i]; - g.send(&C::InitializeBorder(play::InitializeBorder { - center_x: 0.0, - center_z: 0.0, - old_size: 59_999_968.0, - new_size: 59_999_968.0, - lerp_time: 0, - absolute_max_size: 29_999_984, - warning_blocks: 5, - // WorldBorder.DEFAULT_WARNING_TIME, in ticks. - warning_time: 300, - })); + g.send(&C::InitializeBorder(super::border::initialize(ctx.border))); g.send(&self.time_packet(ctx.world, ctx.clock_rate)); g.send(&self.default_spawn(spawn)); let w = &ctx.world.weather; @@ -1360,21 +1345,6 @@ impl Hub { (!batch.is_empty()).then_some(batch) } - /// Resend a chunk to everyone who has it (a block entity changed, relight). - pub fn resend_chunk(&mut self, world: &World, x: i32, z: i32) { - let Some(chunk) = world.chunks.get(&(x, z)) else { - return; - }; - let body = self.encoder.body_in(chunk, world); - for g in self - .guests - .iter() - .filter(|g| g.sent_chunks.contains(&(x, z))) - { - g.sender.send(body.clone()); - } - } - /// `ChunkHolder.broadcastChanges`' light part: the light sections that /// changed in a column go to the players for whom it is on the border of /// what they track (`ChunkMap.isChunkOnTrackedBorder`); the others light diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index c2f35bc8e..e2f0a719f 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -6,6 +6,7 @@ //! world that is not open to the network pays nothing. mod advancements; pub mod attributes; +pub mod border; pub mod chunks; mod command_order; pub mod command_suggestions; @@ -20,6 +21,7 @@ pub mod hub; pub mod menu; pub mod playerdata; mod recipes; +pub mod scoreboard; pub mod tracking; pub mod waypoints; @@ -272,9 +274,6 @@ impl Shared { pub fn max_players(&self) -> usize { self.max_players.load(Ordering::Relaxed) } - pub fn set_max_players(&self, n: usize) { - self.max_players.store(n, Ordering::Relaxed); - } pub fn release(&self, uuid: u128) { self.online.lock().unwrap().retain(|(u, _)| *u != uuid); } @@ -513,9 +512,6 @@ impl Lan { pub fn reserve(&self, uuid: u128) { self.shared.reserved.lock().unwrap().insert(uuid); } - pub fn set_motd(&self, motd: &str) { - *self.shared.motd.lock().unwrap() = motd.to_owned(); - } pub fn stop(&mut self) { self.shared.stop.store(true, Ordering::Relaxed); self.stop_listening(); diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 475979d81..62102ade1 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -1,6 +1,6 @@ //! Guests' saved state: `players/data/.dat` in the vanilla player //! compound, through the same code that saves the host. -use super::guest::Guest; +use super::guest::{Guest, SavedBody}; use crate::{ items::ItemStack, save::{Level, read_dat, write_dat}, @@ -80,6 +80,17 @@ pub fn apply(guest: &mut Guest, level: &Level) { .map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.respawn_elsewhere = level.respawn_elsewhere.clone(); guest.saved = level.player_extra.clone(); + let extra = level.player_extra.as_ref(); + let short = |key: &str, default: i64| { + extra + .and_then(|t| crate::save::number(t.get(key))) + .unwrap_or(default) as i32 + }; + guest.loaded_body = Some(SavedBody { + fire_ticks: short("Fire", -20), + air: short("Air", 300), + fall_distance: level.fall_distance, + }); guest.recipe_book = level.recipe_book.clone(); guest.dimension = match level.dimension.as_str() { d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(), @@ -151,6 +162,24 @@ pub fn store(guest: &Guest, level: &mut Level) { level.respawn_elsewhere = guest.respawn_elsewhere.clone(); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); + // The live body's fire, air and fall distance (Entity.saveWithoutId), + // or what the file had while the player has no body yet. + let body = guest + .motion + .as_deref() + .map(SavedBody::of) + .or(guest.loaded_body); + if let Some(body) = body { + level.fall_distance = body.fall_distance; + let extra = level + .player_extra + .get_or_insert_with(|| horizon_world::nbt::Tag::Compound(Default::default())); + if let horizon_world::nbt::Tag::Compound(map) = extra { + let short = |v: i32| horizon_world::nbt::Tag::Short(v.clamp(-32768, 32767) as i16); + map.insert("Fire".into(), short(body.fire_ticks)); + map.insert("Air".into(), short(body.air)); + } + } level.recipe_book = guest.recipe_book.clone(); level.ender_items = guest.ender_items.clone(); level.inventory.clear(); @@ -174,3 +203,52 @@ pub fn store(guest: &Guest, level: &mut Level) { put(100, &guest.armor[3]); put(150, &guest.offhand); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::lan::{Joined, PlayerSender}; + use horizon_protocol::packets::configuration::ClientInformation; + use std::sync::{Arc, atomic::AtomicI32, mpsc}; + + fn guest() -> Guest { + let (tx, _rx) = mpsc::channel(); + Guest::new( + Joined { + conn: 2, + uuid: 2, + name: "Alex".into(), + properties: Vec::new(), + info: ClientInformation::new(8), + brand: "test".into(), + sender: PlayerSender::new(tx, Arc::default()), + latency: Arc::new(AtomicI32::new(0)), + address: "127.0.0.1:25565".parse().unwrap(), + }, + 2, + [0.0, 64.0, 0.0], + 8, + ) + } + + #[test] + fn a_saved_burn_and_fall_come_back() { + // A player saved burning in mid-fall (#1323, #1327): Entity.saveWithoutId's + // Fire, Air and fall_distance, read back for the next body. + let mut g = guest(); + g.loaded_body = Some(SavedBody { + fire_ticks: 96, + air: 250, + fall_distance: 9.5, + }); + let mut level = Level::default(); + store(&g, &mut level); + let tag = level.player_tag(); + let mut read = Level::default(); + read.read_player(&tag); + read.player_extra = Some(tag); + let mut back = guest(); + apply(&mut back, &read); + assert_eq!(back.loaded_body, g.loaded_body); + } +} diff --git a/crates/horizon-client/src/lan/scoreboard.rs b/crates/horizon-client/src/lan/scoreboard.rs new file mode 100644 index 000000000..cba0f914c --- /dev/null +++ b/crates/horizon-client/src/lan/scoreboard.rs @@ -0,0 +1,308 @@ +//! `ServerScoreboard`: what a player's client knows of the server's +//! scoreboard. Every team goes to every player; an objective goes once it +//! sits in a display slot (`startTrackingObjective`: its objective, its +//! slots, then its scores) and leaves when it sits in none +//! (`stopTrackingObjective`). A joining player gets it all +//! (`PlayerList.updateEntireScoreboard`). +//! +//! A server's commands change the board in place; each tick a player is +//! sent the packets that turn what it was last sent into what it should +//! have now, which are the ones `ServerScoreboard`'s callbacks send. +use crate::scoreboard::{NumberFormat, RenderType, Scoreboard, component_tag, display_slots}; +use crate::text::COLORS; +use horizon_protocol::packets::play::{ + self, Clientbound as C, ResetScore, SetDisplayObjective, SetObjective, SetPlayerTeam, SetScore, + TeamParameters, +}; +use horizon_world::nbt::Tag; +use std::collections::{BTreeMap, BTreeSet}; + +type Format = Option; + +/// The scoreboard as one player's client has it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct View { + /// The tracked objectives: display name, render type (1 hearts), format. + objectives: BTreeMap, + /// `DisplaySlot` id to objective. + display: BTreeMap, + /// The tracked objectives' scores, by holder and objective. + scores: BTreeMap<(String, String), (i32, Option, Format)>, + /// Every team: its parameters and players, in the team's order. + teams: BTreeMap)>, +} + +fn format(f: Option<&NumberFormat>) -> Format { + f.map(|f| match f { + NumberFormat::Blank => play::NumberFormat::Blank, + NumberFormat::Styled(s) => play::NumberFormat::Styled(crate::scoreboard::json_to_tag(s)), + NumberFormat::Fixed(c) => play::NumberFormat::Fixed(component_tag(c)), + }) +} + +impl View { + /// What the board's state gives a client. + pub fn of(board: &Scoreboard) -> Self { + let slots = display_slots(); + let display: BTreeMap = board + .display + .iter() + .filter_map(|(slot, o)| Some((slots.iter().position(|s| s == slot)? as i32, o.clone()))) + .collect(); + let tracked: BTreeSet<&String> = display.values().collect(); + let objectives = board + .objectives + .iter() + .filter(|o| tracked.contains(&o.name)) + .map(|o| { + let render = i32::from(o.render_type == RenderType::Hearts); + ( + o.name.clone(), + ( + component_tag(&o.display_name), + render, + format(o.number_format.as_ref()), + ), + ) + }) + .collect(); + let scores = board + .scores + .iter() + .flat_map(|(holder, scores)| { + scores + .iter() + .filter(|(o, _)| tracked.contains(o)) + .map(move |(o, s)| { + ( + (holder.clone(), o.clone()), + ( + s.value, + s.display.as_ref().map(component_tag), + format(s.number_format.as_ref()), + ), + ) + }) + }) + .collect(); + let teams = board + .teams + .iter() + .map(|t| { + let params = TeamParameters { + display_name: component_tag(&t.display_name), + prefix: component_tag(&t.prefix), + suffix: component_tag(&t.suffix), + name_tag_visibility: t.nametag_visibility as i32, + collision_rule: t.collision_rule as i32, + color: t + .color + .as_deref() + .and_then(|c| COLORS.iter().position(|(_, n, _)| *n == c)) + .map(|i| i as i32), + options: i8::from(t.allow_friendly_fire) + | (i8::from(t.see_friendly_invisibles) << 1), + }; + ( + t.name.clone(), + (params, t.players.iter().cloned().collect()), + ) + }) + .collect(); + Self { + objectives, + display, + scores, + teams, + } + } + + /// The packets that take a client from `self` to `next`. + pub fn changes(&self, next: &View) -> Vec { + let mut out = Vec::new(); + let team = |name: &str, method, parameters, players| { + C::SetPlayerTeam(SetPlayerTeam { + name: name.to_owned(), + method, + parameters, + players, + }) + }; + for name in self.teams.keys().filter(|n| !next.teams.contains_key(*n)) { + out.push(team(name, 1, None, Vec::new())); + } + for (name, (params, players)) in &next.teams { + let Some((was, had)) = self.teams.get(name) else { + out.push(team(name, 0, Some(params.clone()), players.clone())); + continue; + }; + if was != params { + out.push(team(name, 2, Some(params.clone()), Vec::new())); + } + let joined: Vec<_> = players + .iter() + .filter(|p| !had.contains(p)) + .cloned() + .collect(); + if !joined.is_empty() { + out.push(team(name, 3, None, joined)); + } + let left: Vec<_> = had + .iter() + .filter(|p| !players.contains(p)) + .cloned() + .collect(); + if !left.is_empty() { + out.push(team(name, 4, None, left)); + } + } + for (name, display) in &next.objectives { + let method = match self.objectives.get(name) { + None => 0, + Some(was) if was != display => 2, + Some(_) => continue, + }; + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method, + display: Some(display.clone()), + })); + } + let slots: BTreeSet = self + .display + .keys() + .chain(next.display.keys()) + .copied() + .collect(); + for slot in slots { + let objective = next.display.get(&slot); + if self.display.get(&slot) != objective { + out.push(C::SetDisplayObjective(SetDisplayObjective { + slot, + objective: objective.cloned().unwrap_or_default(), + })); + } + } + for ((holder, objective), (value, display, number_format)) in &next.scores { + let key = (holder.clone(), objective.clone()); + if self.scores.get(&key) != Some(&(*value, display.clone(), number_format.clone())) { + out.push(C::SetScore(SetScore { + owner: holder.clone(), + objective: objective.clone(), + score: *value, + display: display.clone(), + number_format: number_format.clone(), + })); + } + } + for (holder, objective) in self.scores.keys() { + let key = (holder.clone(), objective.clone()); + if !next.scores.contains_key(&key) && next.objectives.contains_key(objective) { + out.push(C::ResetScore(ResetScore { + owner: holder.clone(), + objective: Some(objective.clone()), + })); + } + } + for name in self + .objectives + .keys() + .filter(|n| !next.objectives.contains_key(*n)) + { + out.push(C::SetObjective(SetObjective { + name: name.clone(), + method: 1, + display: None, + })); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn methods(packets: &[C]) -> Vec { + packets + .iter() + .map(|p| match p { + C::SetObjective(o) => format!("objective {} {}", o.name, o.method), + C::SetDisplayObjective(d) => format!("display {} {}", d.slot, d.objective), + C::SetScore(s) => format!("score {} {} {}", s.owner, s.objective, s.score), + C::ResetScore(r) => format!("reset {} {:?}", r.owner, r.objective), + C::SetPlayerTeam(t) => format!("team {} {} {:?}", t.name, t.method, t.players), + _ => "other".into(), + }) + .collect() + } + + #[test] + fn a_shown_objective_goes_with_its_scores_and_leaves_when_hidden() { + let mut board = Scoreboard::default(); + board.add_objective( + "audit", + "dummy", + json!("Audit"), + RenderType::Integer, + false, + None, + ); + board.score_mut("Alpha", "audit").value = 7; + let empty = View::default(); + // Not displayed: not tracked, nothing sent. + let hidden = View::of(&board); + assert!(empty.changes(&hidden).is_empty()); + board.set_display_objective("sidebar", Some("audit")); + let shown = View::of(&board); + assert_eq!( + methods(&hidden.changes(&shown)), + [ + "objective audit 0", + "display 1 audit", + "score Alpha audit 7" + ] + ); + board.score_mut("Alpha", "audit").value = 12; + board.score_mut("Beta", "audit").value = 3; + board.reset_one("Beta", "audit"); + let changed = View::of(&board); + assert_eq!(methods(&shown.changes(&changed)), ["score Alpha audit 12"]); + board.reset_one("Alpha", "audit"); + let reset = View::of(&board); + assert_eq!( + methods(&changed.changes(&reset)), + ["reset Alpha Some(\"audit\")"] + ); + board.set_display_objective("sidebar", None); + assert_eq!( + methods(&reset.changes(&View::of(&board))), + ["display 1 ", "objective audit 1"] + ); + } + + #[test] + fn teams_go_to_everyone_with_their_players() { + let mut board = Scoreboard::default(); + board.add_team("red"); + board.add_to_team("Alpha", "red"); + let first = View::of(&board); + assert_eq!( + methods(&View::default().changes(&first)), + ["team red 0 [\"Alpha\"]"] + ); + board.add_to_team("Beta", "red"); + board.remove_from_team("Alpha"); + let second = View::of(&board); + assert_eq!( + methods(&first.changes(&second)), + ["team red 3 [\"Beta\"]", "team red 4 [\"Alpha\"]"] + ); + board.remove_team("red"); + assert_eq!( + methods(&second.changes(&View::of(&board))), + ["team red 1 []"] + ); + } +} diff --git a/crates/horizon-client/src/lang.rs b/crates/horizon-client/src/lang.rs index 9f04ef27a..15f47285a 100644 --- a/crates/horizon-client/src/lang.rs +++ b/crates/horizon-client/src/lang.rs @@ -77,12 +77,6 @@ pub fn apply_deprecated(map: &mut HashMap, json: &[u8]) { } impl Language { - pub fn from_map(code: &str, map: HashMap) -> Self { - Self { - code: code.to_owned(), - map, - } - } /// ClientLanguage.loadFrom: en_us first, then the selected language, each /// from every namespace and every source in priority order (later sources /// override). diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index d7ea7d7fd..6cb4b65b1 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -203,7 +203,7 @@ impl LightTables { Ok(tables) } /// Assembled tables (tests and benchmarks): derives the packed light cache. - #[allow(dead_code)] + #[cfg(test)] fn from_parts(cells: Vec, occludes: Vec, faces: usize) -> Self { let mut tables = Self { cells, diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 1410bf858..aa0d8fb2a 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -239,10 +239,6 @@ pub enum ArmPose { /// Raising a trident to throw it (or to launch with Riptide). ThrowTrident, } -/// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. -pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { - humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); -} /// HumanoidModel.setupAnim with empty hands (endermen). pub fn humanoid_pub(p: &mut Poses, s: &State, _m: &Mob) { humanoid(p, s, &Hum::new(ArmPose::Empty, ArmPose::Empty)); diff --git a/crates/horizon-client/src/mobs/creaking_heart.rs b/crates/horizon-client/src/mobs/creaking_heart.rs index e3c0e4cb7..1172b229c 100644 --- a/crates/horizon-client/src/mobs/creaking_heart.rs +++ b/crates/horizon-client/src/mobs/creaking_heart.rs @@ -152,10 +152,6 @@ pub fn protector(heart: &mut CreakingHeart, host: &impl HeartHost) -> Option bool { - protector(heart, host) == Some(id) -} fn distance_to_creaking(heart: &mut CreakingHeart, pos: [i32; 3], host: &impl HeartHost) -> f64 { protector(heart, host) .and_then(|id| host.mob(id)) diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index c12f9e7ee..7f73e32c4 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -76,9 +76,6 @@ pub struct GoalSelector { locked: [Option; 4], pub disabled: u8, } -fn flag_index(f: u8) -> usize { - f.trailing_zeros() as usize -} impl GoalSelector { pub fn add(&mut self, priority: i32, goal: impl Goal + 'static) { self.goals.push(Wrapped { @@ -174,10 +171,6 @@ impl GoalSelector { } self.locked = [None; 4]; } - #[allow(dead_code)] - fn locked_by(&self, flag: u8) -> Option { - self.locked[flag_index(flag)] - } } // --- random positions (DefaultRandomPos / LandRandomPos / RandomPos) ------- @@ -565,36 +558,6 @@ impl Mob { m.land_up_out_of_solid(w, p) }) } - /// LandRandomPos.getPosTowards - pub fn land_random_pos_towards( - &mut self, - w: &MobWorld, - h: i32, - v: i32, - to: [f64; 3], - ) -> Option<[f64; 3]> { - let (xd, zd) = (to[0] - self.position.x, to[2] - self.position.z); - self.pick_best(w, |m| { - let d = m.random_direction_within( - 0.0, - f64::from(h), - v, - 0, - xd, - zd, - std::f64::consts::FRAC_PI_2, - )?; - let p = m.toward(f64::from(h), d); - if p[1] < crate::chunk::MIN_Y - || p[1] >= 320 - || m.restricted(f64::from(h), p) - || !m.stable_destination(w, p) - { - return None; - } - m.land_up_out_of_solid(w, p) - }) - } pub fn target_info(&self, w: &MobWorld) -> Option { self.ai.target.and_then(|t| w.target_info(t)) } diff --git a/crates/horizon-client/src/mobs/happy_ghast.rs b/crates/horizon-client/src/mobs/happy_ghast.rs index c0ee860dd..6fc07e898 100644 --- a/crates/horizon-client/src/mobs/happy_ghast.rs +++ b/crates/horizon-client/src/mobs/happy_ghast.rs @@ -17,7 +17,6 @@ use horizon_core::{ // Happy ghast state: `head` the harness, `scratch[0]` 1 once set up as a // baby and 2 as an adult, `ai.home` the restriction, `counter` // the end tick of the follow-an-adult range pick. -pub const BABY_SCALE: f64 = 0.2375; /// `Attributes.FLYING_SPEED` and the speed `travel` uses (`* 5 / 3`). pub const FLYING_SPEED: f64 = 0.05; pub const AIR_SPEED: f32 = 0.05 * 5.0 / 3.0; diff --git a/crates/horizon-client/src/mobs/monster_brain.rs b/crates/horizon-client/src/mobs/monster_brain.rs index eeb2c42f2..1099e0bc3 100644 --- a/crates/horizon-client/src/mobs/monster_brain.rs +++ b/crates/horizon-client/src/mobs/monster_brain.rs @@ -250,10 +250,6 @@ pub fn nearest_players(m: &Mob) -> Vec { .and_then(|b| b.mem.nearest_players.value()) .unwrap_or_default() } -/// The damage the brain remembers (`HURT_BY`). -pub fn hurt_by_present(m: &Mob) -> bool { - brain(m).is_some_and(|b| b.mem.hurt_by.present()) -} /// `HURT_BY`'s damage source entity, if a living one. fn hurt_by_entity(m: &Mob, w: &MobWorld) -> Option { let t = brain(m)?.mem.hurt_by.value()?; diff --git a/crates/horizon-client/src/mobs/nautilus.rs b/crates/horizon-client/src/mobs/nautilus.rs index efeb5cc40..2fcf7eb46 100644 --- a/crates/horizon-client/src/mobs/nautilus.rs +++ b/crates/horizon-client/src/mobs/nautilus.rs @@ -76,14 +76,6 @@ pub fn finalize(m: &mut Mob, warm_ocean: bool) { m.extra.variant = u8::from(warm_ocean); } } -/// `checkNautilusSpawnRules`: 5 to 25 blocks below sea level, water below -/// and above. -pub fn spawn_rules_ok(w: &MobWorld, x: i32, y: i32, z: i32) -> bool { - let sea = 63; - (sea - 25..=sea - 5).contains(&y) - && w.fluid(x, y - 1, z) == Fluid::Water - && w.block_name(x, y + 1, z) == "minecraft:water" -} /// `getControllingPassenger`: a player on a saddled nautilus. pub fn controlled(m: &Mob) -> bool { m.rider.is_some() && m.extra.saddled diff --git a/crates/horizon-client/src/mobs/nav.rs b/crates/horizon-client/src/mobs/nav.rs index 24dafa48d..793303c6d 100644 --- a/crates/horizon-client/src/mobs/nav.rs +++ b/crates/horizon-client/src/mobs/nav.rs @@ -582,26 +582,4 @@ impl Mob { NavKind::Amphibious => !w.facts.is_air(w.world.block(p[0], p[1] - 1, p[2])), } } - pub fn should_recompute_path(&self, p: [i32; 3]) -> bool { - if self.ai.nav.delayed_recompute { - return false; - } - let Some(path) = &self.ai.nav.path else { - return false; - }; - if path.is_done() || path.nodes.is_empty() { - return false; - } - let Some(end) = path.end() else { return false }; - let mid = [ - (f64::from(end.x) + self.position.x) / 2.0, - (f64::from(end.y) + self.position.y) / 2.0, - (f64::from(end.z) + self.position.z) / 2.0, - ]; - let d = (f64::from(p[0]) + 0.5 - mid[0]).powi(2) - + (f64::from(p[1]) + 0.5 - mid[1]).powi(2) - + (f64::from(p[2]) + 0.5 - mid[2]).powi(2); - let r = (path.nodes.len() - path.next) as f64; - d < r * r - } } diff --git a/crates/horizon-client/src/mobs/rabbit.rs b/crates/horizon-client/src/mobs/rabbit.rs index 05ab0e390..a2ab6e95c 100644 --- a/crates/horizon-client/src/mobs/rabbit.rs +++ b/crates/horizon-client/src/mobs/rabbit.rs @@ -310,6 +310,18 @@ mod tests { } } + #[test] + fn love_ticks_survive_a_save() { + // Animal.addAdditionalSaveData / readAdditionalSaveData: "InLove" (#1396). + let mut m = rabbit(); + m.extra.in_love = 570; + let tag = crate::entity_nbt::mob_to_nbt(&m, [0, 0, 0, 1], None); + assert_eq!(tag.get("InLove"), Some(&horizon_world::nbt::Tag::Int(570))); + let types = HashMap::from([(m.kind.id.clone(), m.kind.clone())]); + let back = crate::entity_nbt::mob_from_nbt(&tag, &types, 2).unwrap(); + assert_eq!(back.extra.in_love, 570); + } + #[test] fn landing_waits_then_real_hop_clock_moves_the_model() { let mut m = rabbit(); diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index 046583a1f..4e51722f1 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -769,19 +769,6 @@ pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Opt None } -/// `NaturalSpawner.getRandomSpawnMobAt`. -pub fn random_spawn_mob_at( - list: &[SpawnEntry], - category: &str, - reduced_water_ambient: bool, - random: &mut impl RandomSource, -) -> Option { - if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 { - return None; - } - weighted_pick(list, random) -} - /// `SpawnerData.count().sample(random)`: a constant draws nothing. pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 { if entry.constant { diff --git a/crates/horizon-client/src/mobs/spawning.rs b/crates/horizon-client/src/mobs/spawning.rs index 0bfd5d223..93e3fe119 100644 --- a/crates/horizon-client/src/mobs/spawning.rs +++ b/crates/horizon-client/src/mobs/spawning.rs @@ -30,25 +30,6 @@ pub struct BiomeFacts { pub fn placement_ok(species: Species, w: &MobWorld, x: i32, y: i32, z: i32) -> bool { super::spawn_rules::is_spawn_position_ok(species, w, x, y, z) } -/// `SpawnPlacements.checkSpawnRules` for a natural spawn. -pub fn spawn_rules_ok( - species: Species, - w: &MobWorld, - random: &mut impl RandomSource, - x: i32, - y: i32, - z: i32, -) -> bool { - super::spawn_rules::check_spawn_rules( - species, - w, - super::spawn_rules::Reason::Natural, - random, - x, - y, - z, - ) -} /// Mob.finalizeSpawn for natural, chunk-generation and summoned mobs. /// `DifficultyInstance`: the local difficulty at a position. #[derive(Clone, Copy, Debug)] diff --git a/crates/horizon-client/src/mobs/villager_brain.rs b/crates/horizon-client/src/mobs/villager_brain.rs index e02cfa176..194bd75ff 100644 --- a/crates/horizon-client/src/mobs/villager_brain.rs +++ b/crates/horizon-client/src/mobs/villager_brain.rs @@ -10,7 +10,7 @@ //! other `GateBehavior`s shuffle with a random of their own, seeded with //! `Brain::shuffle_seed` when the brain is built. use super::{ - Mob, MobEvent, MobWorld, Seen, Species, Who, + Mob, MobEvent, MobWorld, Species, Who, path::{Path, PathNode}, }; use horizon_core::{ @@ -4156,10 +4156,6 @@ pub fn woken(m: &mut Mob, now: i64) { pub fn potential_job_site(m: &Mob) -> Option<[i32; 3]> { mem_ref(m).and_then(|mm| mm.potential_job_site.value()) } -/// Whether a seen mob is a villager wanting to breed (`AgeableMob::canBreed`). -pub fn seen_can_breed(s: &Seen) -> bool { - s.species == Species::Villager && s.in_love -} /// The memories other villagers read: the interaction target, the path's /// nodes (while it is not done), whether a golem was seen lately and the /// last sleep. diff --git a/crates/horizon-client/src/mobs/world.rs b/crates/horizon-client/src/mobs/world.rs index 79bbaa30c..7836a49ef 100644 --- a/crates/horizon-client/src/mobs/world.rs +++ b/crates/horizon-client/src/mobs/world.rs @@ -1,7 +1,7 @@ //! What mobs read from the level: block solidity, ray clipping for line of //! sight (`ClipContext.Block.COLLIDER`), sky visibility, light-dependent //! values and the positions of other entities. -use super::{MobWorld, Seen, Species, Who, data}; +use super::{MobWorld, Seen, Who, data}; use crate::{ blocks::{BlockFacts, Fluid}, collisions::SceneCollisions, @@ -269,12 +269,6 @@ impl MobWorld<'_> { }); v.into_iter() } - pub fn count_species(&self, species: Species) -> usize { - self.others - .iter() - .filter(|s| s.species == species && s.alive) - .count() - } } /// Level.clip with VISUAL shapes and no fluids: the block the segment first diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 339cb86b8..9edbb4f2a 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -307,6 +307,9 @@ pub struct PlayerMotion { pub hurt_log: Vec, /// The last melee attacks made on mobs, newest last. pub attack_log: Vec, + /// The level's world border, whose walls stop the player's movement + /// from inside (the game keeps it current; None: no border). + pub border: Option, } fn attribute_error(error: impl std::fmt::Debug) -> io::Error { io::Error::other(format!("movement attribute: {error:?}")) @@ -337,6 +340,7 @@ impl PlayerMotion { self.air = extra .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; + self.fall_distance = level.fall_distance; self.set_health(level.health, false)?; // LivingEntity.readAdditionalSaveData: internalSetAbsorptionAmount. self.internal_set_absorption(level.absorption)?; @@ -460,6 +464,7 @@ impl PlayerMotion { powder_snow_entered: Vec::new(), hurt_log: Vec::new(), attack_log: Vec::new(), + border: None, }) } /// `Entity.getTicksRequiredToFreeze`. @@ -677,9 +682,11 @@ impl MotionWorld<'_, '_, '_> { fn movement_collisions( &self, ) -> crate::collisions::EntityCollisions<'_, SceneCollisions<'_, '_>> { + let at = [self.player.position.x, self.player.position.z]; crate::collisions::EntityCollisions { blocks: self.collisions(), entities: self.entities, + border: self.player.border.as_ref().map(|b| (b, at)), } } /// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes. diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 7bd4fd782..5daaaacad 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -804,11 +804,6 @@ impl SelectionModel { false } } - /// Whether activating the entry asks first (`handlePackSelection`'s - /// ConfirmScreen for an incompatible pack). - pub fn needs_confirmation(&self, selected: bool, i: usize) -> bool { - self.can_select(selected, i) && !self.unselected[i].compatible - } /// `moveUp` / `moveDown` when allowed. pub fn move_by(&mut self, selected: bool, i: usize, up: bool) -> bool { let ok = if up { diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 55a7a5120..a5df97258 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1158,6 +1158,8 @@ pub struct ParticleEngine { starters: Vec, /// Local sounds requested by particles (dripstone drips): (event, position, volume, pitch). pub sounds: Vec<(&'static str, [f64; 3], f32, f32)>, + /// How many of each type were made, for `horizon-ctl status`. + made: std::collections::BTreeMap<&'static str, u64>, /// The item particles' sprites (`BreakingItemParticle`'s slime ball, snowball /// and cobweb models, resolved for the ground), one per model layer. pub item_sprites: HashMap>, @@ -1183,6 +1185,7 @@ impl ParticleEngine { starters: Vec::new(), camera: [0.0; 3], sounds: Vec::new(), + made: Default::default(), item_sprites: HashMap::new(), }; let dir = root.join("assets/minecraft/particles"); @@ -1449,9 +1452,14 @@ impl ParticleEngine { pub fn create(&mut self, options: &ParticleOptions, p: [f64; 3], v: [f64; 3]) { let seed = self.seeds.next_long(); if let Some(particle) = self.make(options, p, v, seed) { + *self.made.entry(options.ty.name()).or_default() += 1; self.pending.push(particle); } } + /// How many particles of each type were made so far. + pub fn made(&self) -> &std::collections::BTreeMap<&'static str, u64> { + &self.made + } /// Parity probes: seed the provider (`ParticleEngine.random`), level and /// `SpellParticle.RANDOM` generators. pub fn seed_randoms(&mut self, provider: i64, level: i64, spell: i64) { diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 27051bbc6..fa247a695 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -384,21 +384,6 @@ impl Book { order, } } - /// Which book a recipe id belongs to. - pub fn book_of(&self, id: &str) -> Option { - let e = self.entries.iter().find(|e| e.id == id)?; - Some(match e.category { - Category::CraftingBuilding - | Category::CraftingRedstone - | Category::CraftingEquipment - | Category::CraftingMisc => BookType::Crafting, - Category::FurnaceFood | Category::FurnaceBlocks | Category::FurnaceMisc => { - BookType::Furnace - } - Category::BlastBlocks | Category::BlastMisc => BookType::BlastFurnace, - Category::SmokerFood => BookType::Smoker, - }) - } /// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients /// (`craftingRequirements`) can all be found in `stock`. pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dd86c8f9c..7819a9b0b 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -750,12 +750,6 @@ fn heightmaps(chunk: &Chunk, tables: &SaveTables) -> Tag { ) })) } -/// The heightmaps a ClientboundLevelChunkPacketData carries (the types with -/// sendToClient: WORLD_SURFACE, MOTION_BLOCKING, MOTION_BLOCKING_NO_LEAVES), -/// as (network id, packed longs) in Heightmap.Types order. -pub fn client_heightmaps(chunk: &Chunk, tables: &SaveTables) -> Vec<(i32, Vec)> { - client_heightmaps_in(&chunk.sections, tables, MIN_Y, SECTIONS as i32 * 16) -} /// The client heightmaps of a column's sections, in a level from `min_y`, /// `height` blocks high. pub fn client_heightmaps_in( diff --git a/crates/horizon-client/src/sculk.rs b/crates/horizon-client/src/sculk.rs index 58ac921ff..3affbda77 100644 --- a/crates/horizon-client/src/sculk.rs +++ b/crates/horizon-client/src/sculk.rs @@ -78,7 +78,6 @@ pub const RESONANCE: [&str; 15] = [ ]; pub const SHRIEK: &str = "minecraft:shriek"; pub const TENDRILS_CLICKING: &str = "minecraft:sculk_sensor_tendrils_clicking"; -pub const NO_VIBRATION_FREQUENCY: i32 = 0; /// `VibrationSystem.getGameEventFrequency`. pub fn frequency(event: &str) -> i32 { @@ -567,10 +566,6 @@ pub struct WardenSpawnTracker { } impl WardenSpawnTracker { pub const MAX_WARNING_LEVEL: i32 = 4; - /// Blocks around a shrieker within which players are warned. - pub const PLAYER_SEARCH_RADIUS: f64 = 16.0; - /// `AABB.ofSize(centre, 48, 48, 48)` for an existing warden. - pub const WARNING_CHECK_DIAMETER: f64 = 48.0; const DECREASE_EVERY: i32 = 12000; const INCREASE_COOLDOWN: i32 = 200; pub fn tick(&mut self) { diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 1fadacf57..97acc91c9 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -81,10 +81,6 @@ pub fn sound_source(event: &str) -> usize { index("master") } } -/// Volume multiplier of an event's source (master applied separately). -pub fn event_volume(event: &str) -> f32 { - source_volume(sound_source(event)) -} /// Volume multiplier of a sound source by index. pub fn source_volume(i: usize) -> f32 { if i == 0 { diff --git a/crates/horizon-client/src/tab_list.rs b/crates/horizon-client/src/tab_list.rs index 2c03f999f..0374e3fc2 100644 --- a/crates/horizon-client/src/tab_list.rs +++ b/crates/horizon-client/src/tab_list.rs @@ -317,9 +317,6 @@ impl TabList { self.visible = visible; } } - pub fn is_visible(&self) -> bool { - self.visible - } /// `reset`. pub fn reset(&mut self) { self.header = None; diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index 9f39155d1..11abb3328 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -455,9 +455,6 @@ impl Text { } out } - pub fn char_count(&self) -> usize { - self.spans.iter().map(|s| s.text.chars().count()).sum() - } } /// The style fields of a component's JSON. diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index b4958c600..f77ac93eb 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -1630,26 +1630,6 @@ fn caret_field<'a>( _ => None, } } -/// `yyyy/MM/dd HH:mm` (UTC) for a modification time in Unix seconds. -pub fn date_label(secs: u64) -> String { - date_string(secs) -} -fn date_string(secs: u64) -> String { - // Civil date from Unix time (days-from-civil inverse), UTC. - let days = (secs / 86400) as i64; - let (h, m) = ((secs % 86400) / 3600, (secs % 3600) / 60); - let z = days + 719_468; - let era = z.div_euclid(146_097); - let doe = z - era * 146_097; - let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; - let y = yoe + era * 400; - let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); - let mp = (5 * doy + 2) / 153; - let d = doy - (153 * mp + 2) / 5 + 1; - let mo = if mp < 10 { mp + 3 } else { mp - 9 }; - let y = if mo <= 2 { y + 1 } else { y }; - format!("{y}-{mo:02}-{d:02} {h:02}:{m:02}") -} #[cfg(test)] mod classic_tests { diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index b1ffab866..1c6e93067 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -7,9 +7,40 @@ use crate::{ }; use std::{collections::HashMap, path::Path, sync::RwLock, time::Instant}; -/// Nine-slice borders (left, top, right, bottom) from `.png.mcmeta` files. -static NINE_SLICE: RwLock>> = RwLock::new(None); +/// `GuiSpriteScaling.NineSlice`: the sprite's size in GUI pixels, whatever +/// its texture's resolution, its borders (left, top, right, bottom) in the +/// same units, and whether the edges and centre stretch rather than tile. +#[derive(Clone, Copy, Debug, PartialEq)] +struct NineSlice { + width: u32, + height: u32, + border: [u32; 4], + stretch_inner: bool, +} +/// Nine-slice scaling from `.png.mcmeta` files. +static NINE_SLICE: RwLock>> = RwLock::new(None); +/// A `gui.scaling` section of type `nine_slice`. +fn parse_nine_slice(v: &serde_json::Value) -> Option { + let s = &v["gui"]["scaling"]; + if s["type"] != "nine_slice" { + return None; + } + let size = |k: &str| s[k].as_u64().map(|n| n as u32); + let border = &s["border"]; + let border = if let Some(n) = border.as_u64() { + [n as u32; 4] + } else { + let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; + [g("left"), g("top"), g("right"), g("bottom")] + }; + Some(NineSlice { + width: size("width")?, + height: size("height")?, + border, + stretch_inner: s["stretch_inner"].as_bool().unwrap_or(false), + }) +} /// Read `gui.scaling` metadata for every GUI sprite under `root`. pub fn load_metadata(root: &Path) { let mut map = HashMap::new(); @@ -32,47 +63,48 @@ pub fn load_metadata(root: &Path) { let Ok(text) = std::fs::read_to_string(&p) else { continue; }; - let Ok(v) = serde_json::from_str::(&text) else { + let Some(nine_slice) = serde_json::from_str(&text) + .ok() + .as_ref() + .and_then(parse_nine_slice) + else { continue; }; - let s = &v["gui"]["scaling"]; - if s["type"] != "nine_slice" { - continue; - } - let border = &s["border"]; - let b = if let Some(n) = border.as_u64() { - [n as u32; 4] - } else { - let g = |k: &str| border[k].as_u64().unwrap_or(0) as u32; - [g("left"), g("top"), g("right"), g("bottom")] - }; let key = Path::new(stripped) .strip_prefix(&base) .map(|r| r.to_string_lossy().replace('\\', "/")) .unwrap_or_default(); - map.insert(key, b); + map.insert(key, nine_slice); } } *NINE_SLICE.write().unwrap_or_else(|e| e.into_inner()) = Some(map); } -fn border(sprite: &str) -> [u32; 4] { +/// The sprite's nine-slice metadata; without any (no resources loaded), its +/// GUI size and the widgets' usual borders. +fn scaling(sprite: &str, r: &Rect) -> NineSlice { NINE_SLICE .read() .unwrap_or_else(|e| e.into_inner()) .as_ref() .and_then(|m| m.get(sprite).copied()) - .unwrap_or(match sprite { - "gui/sprites/widget/button" - | "gui/sprites/widget/button_highlighted" - | "gui/sprites/widget/button_disabled" => [3; 4], - "gui/sprites/widget/slider_handle" | "gui/sprites/widget/slider_handle_highlighted" => { - [2, 2, 2, 3] - } - _ => [1; 4], + .unwrap_or(NineSlice { + width: r.w, + height: r.h, + border: match sprite { + "gui/sprites/widget/button" + | "gui/sprites/widget/button_highlighted" + | "gui/sprites/widget/button_disabled" => [3; 4], + "gui/sprites/widget/slider_handle" + | "gui/sprites/widget/slider_handle_highlighted" => [2, 2, 2, 3], + _ => [1; 4], + }, + stretch_inner: false, }) } -fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { - let (du, dv) = ((r.u1 - r.u0) / r.w as f32, (r.v1 - r.v0) / r.h as f32); +/// The region `[x, y, w, h]` of a sprite `size` GUI pixels large, in its +/// own units (`TextureAtlasSprite.getU(x / width)`). +fn sub(r: Rect, size: [f32; 2], [x, y, w, h]: [f32; 4]) -> Rect { + let (du, dv) = ((r.u1 - r.u0) / size[0], (r.v1 - r.v0) / size[1]); Rect { u0: r.u0 + x * du, v0: r.v0 + y * dv, @@ -82,8 +114,9 @@ fn sub(r: Rect, x: f32, y: f32, w: f32, h: f32) -> Rect { h: h as u32, } } -/// Tile `src` (a sub-rectangle of a sprite, in its pixels) over a target area. -fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) { +/// `blitTiledSprite`: `src` (a region of a sprite `size` large, in its +/// units) repeated over `dst` from its top left, the last row and column cut. +fn tile(batch: &mut HudBatch, r: Rect, size: [f32; 2], src: [f32; 4], dst: [f32; 4], color: u32) { let [sx, sy, sw, sh] = src; let [dx, dy, dw, dh] = dst; if sw <= 0.0 || sh <= 0.0 || dw <= 0.0 || dh <= 0.0 { @@ -95,13 +128,16 @@ fn tile(batch: &mut HudBatch, r: Rect, src: [f32; 4], dst: [f32; 4], color: u32) let mut x = 0.0; while x < dw { let w = sw.min(dw - x); - batch.rect_uv(dx + x, dy + y, w, h, sub(r, sx, sy, w, h), color); + batch.rect_uv(dx + x, dy + y, w, h, sub(r, size, [sx, sy, w, h]), color); x += sw; } y += sh; } } -/// GuiGraphics.blitSprite with nine-slice scaling (inner parts tiled). +/// `GuiGraphicsExtractor.blitNineSlicedSprite`: the corners at their size, +/// the edges and centre tiled (or stretched with `stretch_inner`), all in +/// the sprite's `gui.scaling` units, so a high-resolution pack's sprite draws +/// as the default one does. pub fn nine_slice( batch: &mut HudBatch, atlas: &HudAtlas, @@ -112,47 +148,73 @@ pub fn nine_slice( h: f32, color: u32, ) { - let Some(r) = atlas.sprites.get(sprite).copied() else { - return; + if let Some(r) = atlas.sprites.get(sprite) { + draw_nine_slice(batch, *r, scaling(sprite, r), [x, y, w, h], color); + } +} +fn draw_nine_slice( + batch: &mut HudBatch, + r: Rect, + n: NineSlice, + [x, y, w, h]: [f32; 4], + color: u32, +) { + let size = [n.width as f32, n.height as f32]; + let [sw, sh] = size; + let [l, t, rr, b] = n.border.map(|v| v as f32); + let (half_w, half_h) = ((w / 2.0).floor(), (h / 2.0).floor()); + let (l, rr, t, b) = (l.min(half_w), rr.min(half_w), t.min(half_h), b.min(half_h)); + // blitSprite(sprite, width, height, textureX, textureY, x, y, w, h). + let part = |batch: &mut HudBatch, tx: f32, ty: f32, dst: [f32; 4]| { + if dst[2] != 0.0 && dst[3] != 0.0 { + batch.rect_uv( + dst[0], + dst[1], + dst[2], + dst[3], + sub(r, size, [tx, ty, dst[2], dst[3]]), + color, + ); + } }; - let [l, t, rr, b] = border(sprite).map(|v| v as f32); - let (sw, sh) = (r.w as f32, r.h as f32); - let l = l.min(w / 2.0); - let rr = rr.min(w / 2.0); - let t = t.min(h / 2.0); - let b = b.min(h / 2.0); - let (cw, ch) = (w - l - rr, h - t - b); - let (scw, sch) = (sw - l - rr, sh - t - b); - // Corners. - batch.rect_uv(x, y, l, t, sub(r, 0.0, 0.0, l, t), color); - batch.rect_uv(x + w - rr, y, rr, t, sub(r, sw - rr, 0.0, rr, t), color); - batch.rect_uv(x, y + h - b, l, b, sub(r, 0.0, sh - b, l, b), color); - batch.rect_uv( - x + w - rr, - y + h - b, - rr, - b, - sub(r, sw - rr, sh - b, rr, b), - color, - ); - // Edges and centre. - tile(batch, r, [l, 0.0, scw, t], [x + l, y, cw, t], color); - tile( - batch, - r, - [l, sh - b, scw, b], - [x + l, y + h - b, cw, b], - color, - ); - tile(batch, r, [0.0, t, l, sch], [x, y + t, l, ch], color); - tile( - batch, - r, - [sw - rr, t, rr, sch], - [x + w - rr, y + t, rr, ch], - color, - ); - tile(batch, r, [l, t, scw, sch], [x + l, y + t, cw, ch], color); + // blitNineSliceInnerSegment. + let inner = |batch: &mut HudBatch, dst: [f32; 4], src: [f32; 4]| { + if dst[2] <= 0.0 || dst[3] <= 0.0 { + return; + } + if n.stretch_inner { + batch.rect_uv(dst[0], dst[1], dst[2], dst[3], sub(r, size, src), color); + } else { + tile(batch, r, size, src, dst, color); + } + }; + if w == sw && h == sh { + part(batch, 0.0, 0.0, [x, y, w, h]); + return; + } + if h == sh { + part(batch, 0.0, 0.0, [x, y, l, h]); + inner(batch, [x + l, y, w - rr - l, h], [l, 0.0, sw - rr - l, sh]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, h]); + return; + } + if w == sw { + part(batch, 0.0, 0.0, [x, y, w, t]); + inner(batch, [x, y + t, w, h - b - t], [0.0, t, sw, sh - b - t]); + part(batch, 0.0, sh - b, [x, y + h - b, w, b]); + return; + } + let (cw, ch) = (w - rr - l, h - b - t); + let (scw, sch) = (sw - rr - l, sh - b - t); + part(batch, 0.0, 0.0, [x, y, l, t]); + inner(batch, [x + l, y, cw, t], [l, 0.0, scw, t]); + part(batch, sw - rr, 0.0, [x + w - rr, y, rr, t]); + part(batch, 0.0, sh - b, [x, y + h - b, l, b]); + inner(batch, [x + l, y + h - b, cw, b], [l, sh - b, scw, b]); + part(batch, sw - rr, sh - b, [x + w - rr, y + h - b, rr, b]); + inner(batch, [x, y + t, l, ch], [0.0, t, l, sch]); + inner(batch, [x + l, y + t, cw, ch], [l, t, scw, sch]); + inner(batch, [x + w - rr, y + t, rr, ch], [sw - rr, t, rr, sch]); } /// Repeat a whole texture with each copy drawn `size` GUI pixels square. pub fn tiled( @@ -169,7 +231,6 @@ pub fn tiled( let Some(r) = atlas.sprites.get(sprite).copied() else { return; }; - let scale = r.w as f32 / size; let mut yy = 0.0; while yy < h { let th = size.min(h - yy); @@ -181,7 +242,7 @@ pub fn tiled( y + yy, tw, th, - sub(r, 0.0, 0.0, tw * scale, th * scale), + sub(r, [size, size], [0.0, 0.0, tw, th]), color, ); xx += size; @@ -793,10 +854,6 @@ impl EditBox { text_color: rgba(224, 224, 224, 255), } } - /// When the field gained focus, for the cursor's blink. - pub fn focused_since(&mut self, at: Instant) { - self.focused_at = at; - } pub fn inner_width(&self) -> f32 { if self.bordered { self.width - 8.0 @@ -1128,6 +1185,130 @@ impl EditBox { #[cfg(test)] mod tests { use super::*; + + /// The quads' destination rectangles and their UVs. + fn quads(batch: &HudBatch) -> Vec<([f32; 4], [f32; 4])> { + batch + .vertices + .chunks(6) + .map(|q| { + let (a, c) = (q[0], q[2]); + ( + [a.pos[0], a.pos[1], c.pos[0], c.pos[1]], + [a.uv[0], a.uv[1], c.uv[0], c.uv[1]], + ) + }) + .collect() + } + /// Destination and UV rectangles equal to within f32 rounding. + fn assert_quad(actual: ([f32; 4], [f32; 4]), expected: ([f32; 4], [f32; 4])) { + let close = |a: [f32; 4], b: [f32; 4]| a.iter().zip(b).all(|(a, b)| (a - b).abs() < 1e-5); + assert!( + close(actual.0, expected.0) && close(actual.1, expected.1), + "{actual:?} != {expected:?}" + ); + } + /// A sprite filling the atlas, `w x h` texels as a 32x pack draws it. + fn sprite(w: u32, h: u32) -> Rect { + Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w, + h, + } + } + fn faithful(json: &str) -> NineSlice { + parse_nine_slice(&serde_json::from_str(json).unwrap()).unwrap() + } + #[test] + fn a_high_resolution_button_slices_in_its_gui_units() { + // Faithful 32x's widget/button: 400x40 texels, gui.scaling 200x20. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":200,"height":20, + "border":{"left":20,"top":4,"right":20,"bottom":4}}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(400, 40), + n, + [10.0, 5.0, 150.0, 20.0], + u32::MAX, + ); + let q = quads(&batch); + // Full height: left border, the centre tiled, right border + // (blitNineSlicedSprite's height == nineSlice.height case). + assert_quad(q[0], ([10.0, 5.0, 30.0, 25.0], [0.0, 0.0, 0.1, 1.0])); + assert_quad(q[1], ([30.0, 5.0, 140.0, 25.0], [0.1, 0.0, 0.65, 1.0])); + assert_quad(q[2], ([140.0, 5.0, 160.0, 25.0], [0.9, 0.0, 1.0, 1.0])); + assert_eq!(q.len(), 3); + } + #[test] + fn nine_slice_corners_and_a_stretched_centre() { + // Faithful 32x's tooltip/frame: 200x200 texels, 100x100, border 12, stretched. + let n = faithful( + r#"{"gui":{"scaling":{"type":"nine_slice","width":100,"height":100,"border":12,"stretch_inner":true}}}"#, + ); + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(200, 200), + n, + [0.0, 0.0, 300.0, 40.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 9); + // Top left corner: 12 GUI pixels, 12/100 of the sprite. + assert_quad(q[0], ([0.0, 0.0, 12.0, 12.0], [0.0, 0.0, 0.12, 0.12])); + // The centre is one stretched quad (blitNineSliceInnerSegment, stretch_inner). + assert_quad(q[7], ([12.0, 12.0, 288.0, 28.0], [0.12, 0.12, 0.88, 0.88])); + // Bottom right corner. + assert_quad(q[5], ([288.0, 28.0, 300.0, 40.0], [0.88, 0.88, 1.0, 1.0])); + } + #[test] + fn a_sprite_drawn_at_its_own_size_is_one_quad() { + let n = NineSlice { + width: 50, + height: 50, + border: [10; 4], + stretch_inner: false, + }; + let mut batch = HudBatch::new([640, 480]); + draw_nine_slice( + &mut batch, + sprite(100, 100), + n, + [4.0, 4.0, 50.0, 50.0], + u32::MAX, + ); + let q = quads(&batch); + assert_eq!(q.len(), 1); + assert_quad(q[0], ([4.0, 4.0, 54.0, 54.0], [0.0, 0.0, 1.0, 1.0])); + } + #[test] + fn borders_shrink_to_half_the_drawn_size() { + let n = NineSlice { + width: 20, + height: 20, + border: [8; 4], + stretch_inner: true, + }; + let mut batch = HudBatch::new([640, 480]); + // 9 wide: borders of floor(9 / 2) = 4, as vanilla's integer division. + draw_nine_slice( + &mut batch, + sprite(20, 20), + n, + [0.0, 0.0, 9.0, 30.0], + u32::MAX, + ); + let q = quads(&batch); + assert_quad(q[0], ([0.0, 0.0, 4.0, 8.0], [0.0, 0.0, 0.2, 0.4])); + assert_quad(q[2], ([5.0, 0.0, 9.0, 8.0], [0.8, 0.0, 1.0, 0.4])); + } #[test] fn append_fields_highlight_the_whole_value_and_blink_their_cursor() { use crate::hud::Blend; diff --git a/crates/horizon-client/src/worldborder.rs b/crates/horizon-client/src/worldborder.rs index 3ed4ea152..fa2380d74 100644 --- a/crates/horizon-client/src/worldborder.rs +++ b/crates/horizon-client/src/worldborder.rs @@ -7,7 +7,6 @@ pub use horizon_core::geometry::border::BorderStatus; /// `WorldBorder.MAX_SIZE` (the float 5.999997E7 as a double). pub const MAX_SIZE: f64 = 59_999_968.0; -pub const MAX_CENTER: f64 = 2.999_998_4e7; /// `BorderStatus.getColor`: the wall colour. pub fn status_color(status: BorderStatus) -> u32 { @@ -81,6 +80,10 @@ impl PartialEq for WorldBorder { } } impl WorldBorder { + /// Its extent, for collisions. + pub fn geometry(&self) -> &BorderGeometry { + &self.geometry + } pub fn center(&self) -> [f64; 2] { self.geometry.center() } diff --git a/crates/horizon-client/src/zip.rs b/crates/horizon-client/src/zip.rs index a0551c829..22cab132d 100644 --- a/crates/horizon-client/src/zip.rs +++ b/crates/horizon-client/src/zip.rs @@ -1,75 +1,35 @@ -//! Minimal read-only ZIP archive support (stored and deflated entries), used -//! for resource packs and the unifont glyph archive. -use std::{collections::BTreeMap, fs, io, path::Path}; +//! Read-only ZIP archives held in memory (resource packs, data packs and the +//! unifont glyph archive), on the `zip` crate. Like Java's `ZipFile` (what +//! vanilla's `FilePackResources` reads with), entries aren't CRC-checked. +use std::{ + collections::BTreeMap, + fs, + io::{self, Cursor, Read}, + path::Path, + sync::Arc, +}; +use zip::{CompressionMethod, ZipArchive}; -/// One archive held in memory with its central directory indexed by name. +/// One archive with its entries indexed by name (`\` read as `/`, folders +/// left out). pub struct Zip { - data: Vec, - entries: BTreeMap, + archive: ZipArchive>>, + entries: BTreeMap, } -#[derive(Clone, Copy)] -struct Entry { - method: u16, - compressed: usize, - size: usize, - header: usize, -} -fn invalid(message: &str) -> io::Error { - io::Error::new(io::ErrorKind::InvalidData, message) -} -fn u16_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 2) - .map(|b| u16::from_le_bytes([b[0], b[1]])) - .ok_or_else(|| invalid("truncated zip")) -} -fn u32_at(d: &[u8], at: usize) -> io::Result { - d.get(at..at + 4) - .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]])) - .ok_or_else(|| invalid("truncated zip")) +fn invalid(e: impl std::fmt::Display) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, e.to_string()) } impl Zip { pub fn open(path: &Path) -> io::Result { Self::from_bytes(fs::read(path)?) } pub fn from_bytes(data: Vec) -> io::Result { - // End of central directory: the last "PK\x05\x06" within 64 KiB of the end. - let min = data.len().saturating_sub(22 + 65_535); - let eocd = (min..=data.len().saturating_sub(22)) - .rev() - .find(|&i| data[i..i + 4] == [0x50, 0x4b, 0x05, 0x06]) - .ok_or_else(|| invalid("not a zip archive"))?; - let count = usize::from(u16_at(&data, eocd + 10)?); - let mut at = u32_at(&data, eocd + 16)? as usize; - let mut entries = BTreeMap::new(); - for _ in 0..count { - if u32_at(&data, at)? != 0x0201_4b50 { - return Err(invalid("bad central directory entry")); - } - let method = u16_at(&data, at + 10)?; - let compressed = u32_at(&data, at + 20)? as usize; - let size = u32_at(&data, at + 24)? as usize; - let name_len = usize::from(u16_at(&data, at + 28)?); - let extra_len = usize::from(u16_at(&data, at + 30)?); - let comment_len = usize::from(u16_at(&data, at + 32)?); - let header = u32_at(&data, at + 42)? as usize; - let name = data - .get(at + 46..at + 46 + name_len) - .ok_or_else(|| invalid("truncated zip name"))?; - let name = String::from_utf8_lossy(name).replace('\\', "/"); - if !name.ends_with('/') { - entries.insert( - name, - Entry { - method, - compressed, - size, - header, - }, - ); - } - at += 46 + name_len + extra_len + comment_len; - } - Ok(Self { data, entries }) + let archive = ZipArchive::new(Cursor::new(Arc::from(data))).map_err(invalid)?; + let entries = (0..archive.len()) + .filter_map(|i| Some((archive.name_for_index(i)?.replace('\\', "/"), i))) + .filter(|(name, _)| !name.ends_with('/')) + .collect(); + Ok(Self { archive, entries }) } pub fn names(&self) -> impl Iterator { self.entries.keys().map(String::as_str) @@ -78,30 +38,21 @@ impl Zip { self.entries.contains_key(name) } pub fn read(&self, name: &str) -> io::Result> { - let e = *self + let &index = self .entries .get(name) .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, name.to_owned()))?; - if u32_at(&self.data, e.header)? != 0x0403_4b50 { - return Err(invalid("bad local file header")); - } - let start = e.header - + 30 - + usize::from(u16_at(&self.data, e.header + 26)?) - + usize::from(u16_at(&self.data, e.header + 28)?); - let raw = self - .data - .get(start..start + e.compressed) - .ok_or_else(|| invalid("truncated zip entry"))?; - match e.method { - 0 => Ok(raw.to_vec()), - 8 => { - let out = miniz_oxide::inflate::decompress_to_vec_with_limit( - raw, - e.size.max(1) * 2 + 1024, - ) - .map_err(|_| invalid("corrupt deflate stream"))?; - Ok(out) + // A clone shares the bytes and the central directory: reading needs `&mut`. + let mut archive = self.archive.clone(); + let mut entry = archive.by_index_raw(index).map_err(invalid)?; + let (method, size) = (entry.compression(), entry.size() as usize); + let mut raw = Vec::with_capacity(entry.compressed_size() as usize); + entry.read_to_end(&mut raw)?; + match method { + CompressionMethod::Stored => Ok(raw), + CompressionMethod::Deflated => { + miniz_oxide::inflate::decompress_to_vec_with_limit(&raw, size.max(1) * 2 + 1024) + .map_err(|_| invalid("corrupt deflate stream")) } _ => Err(invalid("unsupported zip compression")), } @@ -163,10 +114,97 @@ mod tests { } #[test] fn reads_stored_and_deflated_entries() { + // Its CRCs are zero: Java's ZipFile doesn't check them either. let zip = Zip::from_bytes(archive()).unwrap(); assert_eq!(zip.names().collect::>(), ["a/b.txt", "pack.mcmeta"]); assert_eq!(zip.read("pack.mcmeta").unwrap(), b"{\"pack\":{}}"); assert_eq!(zip.read("a/b.txt").unwrap(), b"hello hello hello hello"); assert!(zip.read("missing").is_err()); } + + /// A pack as zip tools write it: folder entries, a nested pack root, + /// stored and deflated files, and a Windows-style name. + fn written() -> Vec { + use std::io::Write; + use zip::write::SimpleFileOptions; + let mut w = zip::ZipWriter::new(Cursor::new(Vec::new())); + let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); + let deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + w.add_directory("Pack-main/", stored).unwrap(); + w.add_directory("Pack-main/assets/minecraft/", stored) + .unwrap(); + w.start_file("Pack-main/pack.mcmeta", stored).unwrap(); + w.write_all(b"{\"pack\":{\"pack_format\":64}}").unwrap(); + w.start_file("Pack-main/assets/minecraft/lang/en_us.json", deflated) + .unwrap(); + w.write_all("{\"a\":\"b\"}".repeat(100).as_bytes()).unwrap(); + w.start_file( + "Pack-main\\assets\\minecraft\\texts\\splashes.txt", + deflated, + ) + .unwrap(); + w.write_all(b"Also try Horizon!").unwrap(); + w.finish().unwrap().into_inner() + } + + #[test] + fn reads_nested_folders_and_skips_folder_entries() { + let zip = Zip::from_bytes(written()).unwrap(); + assert_eq!( + zip.names().collect::>(), + [ + "Pack-main/assets/minecraft/lang/en_us.json", + "Pack-main/assets/minecraft/texts/splashes.txt", + "Pack-main/pack.mcmeta", + ] + ); + assert!(zip.contains("Pack-main/pack.mcmeta")); + assert!(!zip.contains("Pack-main/")); + assert_eq!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(), + "{\"a\":\"b\"}".repeat(100).as_bytes() + ); + assert_eq!( + zip.read("Pack-main/assets/minecraft/texts/splashes.txt") + .unwrap(), + b"Also try Horizon!" + ); + } + + #[test] + fn a_bad_entry_fails_alone() { + let mut bytes = written(); + // The deflated lang file's stream becomes a reserved block type. + let (start, len) = { + let mut archive = ZipArchive::new(Cursor::new(bytes.as_slice())).unwrap(); + let index = archive + .index_for_name("Pack-main/assets/minecraft/lang/en_us.json") + .unwrap(); + let entry = archive.by_index_raw(index).unwrap(); + ( + entry.data_start() as usize, + entry.compressed_size() as usize, + ) + }; + bytes[start..start + len].fill(0xff); + let zip = Zip::from_bytes(bytes).unwrap(); + assert!( + zip.read("Pack-main/assets/minecraft/lang/en_us.json") + .is_err() + ); + assert_eq!( + zip.read("Pack-main/pack.mcmeta").unwrap(), + b"{\"pack\":{\"pack_format\":64}}" + ); + } + + #[test] + fn refuses_what_is_not_a_zip() { + assert!(Zip::from_bytes(b"PK not really".to_vec()).is_err()); + assert!(Zip::from_bytes(Vec::new()).is_err()); + let mut cut = written(); + cut.truncate(cut.len() / 2); + assert!(Zip::from_bytes(cut).is_err()); + } } diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index fdafcbb68..6dd1b8258 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -200,6 +200,7 @@ impl Server { tick_frozen: false, tick_steps: (0, 0), collision: None, + border: &horizon_client::worldborder::WorldBorder::default(), }; let events = self.hub.tick(&mut ctx); for event in events { diff --git a/crates/horizon-core/src/density/beardifier.rs b/crates/horizon-core/src/density/beardifier.rs index 5dec64189..b041be160 100644 --- a/crates/horizon-core/src/density/beardifier.rs +++ b/crates/horizon-core/src/density/beardifier.rs @@ -168,9 +168,6 @@ impl Beardifier { self.kernel_junctions = junctions; self } - pub fn affected_bounds(&self) -> Option { - self.affected - } fn sample_unchecked(&self, [x, y, z]: [i32; 3]) -> f32 { let mut value = 0.; // The kernel is a process-wide constant; resolving it once keeps the diff --git a/crates/horizon-core/src/geometry/shape/join.rs b/crates/horizon-core/src/geometry/shape/join.rs index 57c981e65..261c33802 100644 --- a/crates/horizon-core/src/geometry/shape/join.rs +++ b/crates/horizon-core/src/geometry/shape/join.rs @@ -13,8 +13,6 @@ impl ShapeOp { pub const XOR: Self = Self(6); pub const ONLY_FIRST: Self = Self(4); pub const ONLY_SECOND: Self = Self(2); - pub const FIRST: Self = Self(12); - pub const SECOND: Self = Self(10); pub const fn from_truth_table(bits: u8) -> Self { Self(bits & 15) } diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index d9ade23f2..802eac225 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -466,34 +466,6 @@ impl PalettedContainer { } } } - /// Block ids as 16-bit values (callers whose registry fits in 16 bits). - pub fn unpack_u16(&self, out: &mut [u16; 4096]) { - debug_assert_eq!(self.strategy.entries(), 4096); - match &self.palette { - Palette::Single(value) => out.fill(*value as u16), - Palette::List(list) => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - let id = ((word >> (slot * bits)) & m) as usize; - *cell = list[id] as u16; - } - } - } - Palette::Global => { - let bits = usize::from(self.bits); - let per = 64 / bits; - let m = mask(self.bits); - for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { - for (slot, cell) in chunk.iter_mut().enumerate() { - *cell = ((word >> (slot * bits)) & m) as u16; - } - } - } - } - } /// A container holding `values` in the smallest configuration for their /// distinct count, with palette ids in first-occurrence order, like a /// container unpacked from disk. diff --git a/crates/horizon-core/src/ticks/generation.rs b/crates/horizon-core/src/ticks/generation.rs index 4e1fdce6f..f81d9353e 100644 --- a/crates/horizon-core/src/ticks/generation.rs +++ b/crates/horizon-core/src/ticks/generation.rs @@ -91,9 +91,6 @@ impl WorldGenTickAccess { pub fn containers_mut(&mut self) -> &mut C { &mut self.containers } - pub fn into_containers(self) -> C { - self.containers - } pub fn schedule(&mut self, tick: ScheduledTick) -> Result { Ok(self.containers.container_at(tick.pos)?.schedule(tick)) } diff --git a/crates/horizon-core/src/ticks/mod.rs b/crates/horizon-core/src/ticks/mod.rs index f3cc83999..693aab130 100644 --- a/crates/horizon-core/src/ticks/mod.rs +++ b/crates/horizon-core/src/ticks/mod.rs @@ -636,7 +636,4 @@ impl LevelTicks { pub fn copy_area(&mut self, area: TickArea, offset: BlockPos) { self.schedule_copy(self.area_ticks(area), offset); } - pub fn copy_area_from(&mut self, source: &Self, area: TickArea, offset: BlockPos) { - self.schedule_copy(source.area_ticks(area), offset); - } } diff --git a/crates/horizon-friends/src/guest.rs b/crates/horizon-friends/src/guest.rs index 4f64bb1cc..492f4d482 100644 --- a/crates/horizon-friends/src/guest.rs +++ b/crates/horizon-friends/src/guest.rs @@ -296,14 +296,4 @@ impl Tunnel { })?; Ok((port, thread)) } - /// The protected stream itself (tests, or a client that reads it - /// directly). - pub fn into_stream( - self, - ) -> ( - crypto::SecureReader, - crypto::SecureWriter, - ) { - self.secure - } } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 23ba00699..be3c4eb07 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -7,7 +7,7 @@ use crate::{ Vec3d, Writer, }, chunk::{ChunkData, LightData}, - entity_data::{EntityData, Value}, + entity_data::{EntityData, Particle, Value}, item::{Hashed, HashedSlot, Slot, Stack}, packet, packet_enum, packets::{ @@ -883,6 +883,116 @@ impl Codec for SetObjective { } } } +/// ClientboundLevelParticlesPacket: a particle, whether it ignores the +/// client's particle setting (`overrideLimiter`) and its distance limit +/// (`alwaysShow`), where, the spread and the speed on each axis, how many +/// (0: one, moving by speed times spread) and the randomization type +/// (0 default: gaussian spread and speed). +#[derive(Clone, Debug, PartialEq)] +pub struct LevelParticles { + pub particle: Particle, + pub override_limiter: bool, + pub always_show: bool, + pub pos: [f64; 3], + pub dist: [f32; 3], + pub max_speed: [f32; 3], + pub count: i32, + pub randomization: i32, +} +impl Codec for LevelParticles { + fn read(r: &mut Reader) -> Result { + Ok(Self { + particle: Particle::read(r)?, + override_limiter: r.bool()?, + always_show: r.bool()?, + pos: Vec3d::read(r)?, + dist: [r.f32()?, r.f32()?, r.f32()?], + max_speed: [r.f32()?, r.f32()?, r.f32()?], + count: r.varint()?, + randomization: r.varint()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + v.particle.write(w); + w.bool(v.override_limiter); + w.bool(v.always_show); + Vec3d::write(&v.pos, w); + for f in v.dist.iter().chain(&v.max_speed) { + w.f32(*f); + } + w.varint(v.count); + w.varint(v.randomization); + } +} +/// `ExplosionParticleInfo` in a `WeightedList`: a particle the blast +/// scatters, its scaling and speed, then its weight. +#[derive(Clone, Debug, PartialEq)] +pub struct ExplosionParticle { + pub particle: Particle, + pub scaling: f32, + pub speed: f32, + pub weight: i32, +} +/// ClientboundExplodePacket: the centre, radius and blocks destroyed, the +/// push the receiving player takes, the particle at the centre, the sound, +/// the particles the blast scatters, and whether the sound plays. +#[derive(Clone, Debug, PartialEq)] +pub struct Explode { + pub center: [f64; 3], + pub radius: f32, + pub block_count: i32, + pub knockback: Option<[f64; 3]>, + pub particle: Particle, + pub sound: (i32, Option<(String, Option)>), + pub block_particles: Vec, + pub play_sound: bool, +} +impl Codec for Explode { + fn read(r: &mut Reader) -> Result { + let center = Vec3d::read(r)?; + let radius = r.f32()?; + let block_count = r.i32()?; + let knockback = >::read(r)?; + let particle = Particle::read(r)?; + let sound = SoundHolder::read(r)?; + let n = r.varint()?; + let mut block_particles = Vec::new(); + for _ in 0..n { + block_particles.push(ExplosionParticle { + particle: Particle::read(r)?, + scaling: r.f32()?, + speed: r.f32()?, + weight: r.varint()?, + }); + } + Ok(Self { + center, + radius, + block_count, + knockback, + particle, + sound, + block_particles, + play_sound: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + Vec3d::write(&v.center, w); + w.f32(v.radius); + w.i32(v.block_count); + >::write(&v.knockback, w); + v.particle.write(w); + SoundHolder::write(&v.sound, w); + w.varint(v.block_particles.len() as i32); + for b in &v.block_particles { + b.particle.write(w); + w.f32(b.scaling); + w.f32(b.speed); + w.varint(b.weight); + } + w.bool(v.play_sound); + } +} /// `ClientboundSetPlayerTeamPacket.Parameters`. #[derive(Clone, Debug, PartialEq)] pub struct TeamParameters { @@ -1566,6 +1676,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TickingStep(TickingStep) = TICKING_STEP, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, + LevelParticles(LevelParticles) = LEVEL_PARTICLES, + Explode(Explode) = EXPLODE, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, TrackedWaypoint(TrackedWaypoint) = WAYPOINT, @@ -2270,6 +2382,34 @@ mod tests { passengers: vec![3, 300], }), Clientbound::SetEntityLink(SetEntityLink { source: 2, dest: 0 }), + Clientbound::LevelParticles(LevelParticles { + particle: Particle { + id: 21, + data: Some(crate::entity_data::ParticleData::ColorScale(0xFF0000, 1.5)), + }, + override_limiter: true, + always_show: false, + pos: [0.5, 101.0, 3.0], + dist: [0.2, 0.0, 0.2], + max_speed: [0.0; 3], + count: 60, + randomization: 0, + }), + Clientbound::Explode(Explode { + center: [1.0, 2.0, 3.0], + radius: 4.0, + block_count: 12, + knockback: Some([0.5, 0.1, 0.0]), + particle: Particle { id: 29, data: None }, + sound: (-1, Some(("minecraft:entity.generic.explode".into(), None))), + block_particles: vec![ExplosionParticle { + particle: Particle { id: 69, data: None }, + scaling: 0.5, + speed: 1.0, + weight: 1, + }], + play_sound: true, + }), Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, diff --git a/crates/horizon-server-files/src/user_cache.rs b/crates/horizon-server-files/src/user_cache.rs index c8ccd6cf0..38e779488 100644 --- a/crates/horizon-server-files/src/user_cache.rs +++ b/crates/horizon-server-files/src/user_cache.rs @@ -190,14 +190,6 @@ impl UserCache { result } - /// `get(UUID)`: a cached player by id (expired or not). - pub fn get_by_id(&mut self, id: u128) -> Option { - let index = *self.by_uuid.get(&id)?; - self.operations += 1; - self.infos[index].last_access = self.operations; - Some(self.infos[index].user.clone()) - } - /// The file's text: the 1000 most recently used entries, most recent /// first, as Gson writes them (compact, HTML-safe). pub fn to_json(&self) -> String { diff --git a/crates/horizon-server-files/src/user_lists.rs b/crates/horizon-server-files/src/user_lists.rs index 77de64e31..5bef4f38f 100644 --- a/crates/horizon-server-files/src/user_lists.rs +++ b/crates/horizon-server-files/src/user_lists.rs @@ -416,11 +416,6 @@ pub type WhiteList = UserList; pub type BanList = UserList>; pub type IpBanList = UserList>; -/// IpBanList.getIpFromAddress. -pub fn ip_of(address: &std::net::SocketAddr) -> String { - address.ip().to_string() -} - #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index 0e989341a..885351b97 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -199,8 +199,11 @@ pub fn preprocess( let (start, end) = (token.location.start, token.location.end); let at = line_of(start); if at > line { + // Lines the preprocessor left empty stay empty lines, so a value + // continued with `\` before an `#else` (Photon's + // `moon_phase_brightness`) ends there, as in Iris. if line > 0 { - out.push('\n'); + out.extend(std::iter::repeat_n('\n', at - line)); } line = at; } else if last_end != Some(start) { @@ -799,7 +802,26 @@ b = 1 }; let values = OptionValues::default(); let out = preprocess(text, &env, &set, &values).unwrap(); - assert_eq!(out, "a = 0.75\nb = 1\n"); + let lines: Vec<&str> = out.lines().filter(|l| !l.is_empty()).collect(); + assert_eq!(lines, ["a = 0.75", "b = 1"]); + // Photon ends an `#if`'d value with `) \` before `#else`: the value + // stops at the empty line the directive leaves. + let text = "\ +#if FOG == 0 +a = if( \\ + moonPhase == 0, 1.0, \\ + 2.0 \\ +) \\ +#else +a = 1.0 +#endif + +b = 2 +"; + let out = preprocess(text, &env, &set, &values).unwrap(); + let parsed = Properties::parse(&out); + assert_eq!(parsed.get("a"), Some("if( moonPhase == 0, 1.0, 2.0 ) ")); + assert_eq!(parsed.get("b"), Some("2")); assert_eq!( jcpp_condition("#elif FOG == 0.75 && X > 2.5", &set, &values), "#elif 0 == 0 && X > 2" diff --git a/crates/horizon-shaderpack/src/translate.rs b/crates/horizon-shaderpack/src/translate.rs index 27fafe34b..2e5d46db3 100644 --- a/crates/horizon-shaderpack/src/translate.rs +++ b/crates/horizon-shaderpack/src/translate.rs @@ -17,8 +17,9 @@ //! (`vaPosition`, `modelViewMatrix`, ...) are declared; //! - legacy texture calls are renamed, `shadow2D` returns a `vec4` again and a //! swizzled shadow lookup is widened first (naga has no scalar swizzle); -//! - vertex and compute `texture(s, uv)` calls without an explicit LOD become -//! `textureLod(s, uv, 0.0)` so naga doesn't reject implicit derivatives; +//! - outside fragment programs, `texture`, `textureProj` and their `Offset` +//! forms become their `Lod` forms at level 0 (no derivatives there; naga +//! refuses the implicit ones), a bias dropped; //! - global initialisers run at the start of `main` (drivers accept //! non-constant ones), unsized global arrays are sized from them; //! - `isnan`, `isinf` and `modf` are helper functions (WGSL has none); @@ -380,9 +381,10 @@ pub fn translate( stage: naga_stage, defines: Default::default(), }; - let module = naga::front::glsl::Frontend::default() + let mut module = naga::front::glsl::Frontend::default() .parse(&options, &glsl) .map_err(|e| first_lines(&e.emit_to_string(&glsl)))?; + unpad_private_arrays(&mut module); let info = naga::valid::Validator::new( naga::valid::ValidationFlags::all(), naga::valid::Capabilities::all(), @@ -508,6 +510,79 @@ fn negative_constant(e: &ast::Expr) -> bool { } } +/// naga's GLSL front end lays every struct out as std140, so an array field +/// of a struct that never reaches a buffer (Photon's ACES spline parameters, +/// `float[6]`) gets a stride of 16, and constructing it from a `float[6](..)` +/// (stride 4) fails validation. Give such fields their natural stride. +fn unpad_private_arrays(module: &mut naga::Module) { + use naga::TypeInner as T; + let mut shared = HashSet::new(); + let mut stack: Vec<_> = module + .global_variables + .iter() + .filter(|(_, v)| { + matches!( + v.space, + naga::AddressSpace::Uniform + | naga::AddressSpace::Storage { .. } + | naga::AddressSpace::Immediate + ) + }) + .map(|(_, v)| v.ty) + .collect(); + while let Some(ty) = stack.pop() { + if !shared.insert(ty) { + continue; + } + match &module.types[ty].inner { + T::Struct { members, .. } => stack.extend(members.iter().map(|m| m.ty)), + T::Array { base, .. } | T::BindingArray { base, .. } => stack.push(*base), + _ => {} + } + } + let mut layouter = naga::proc::Layouter::default(); + if layouter.update(module.to_ctx()).is_err() { + return; + } + let structs: Vec<_> = module + .types + .iter() + .filter(|(h, t)| !shared.contains(h) && matches!(t.inner, T::Struct { .. })) + .map(|(h, _)| h) + .collect(); + for ty in structs { + let mut new = module.types[ty].clone(); + let T::Struct { members, .. } = &mut new.inner else { + continue; + }; + let mut changed = false; + for m in members.iter_mut() { + let T::Array { base, size, stride } = module.types[m.ty].inner else { + continue; + }; + let natural = layouter[base].to_stride(); + if stride != natural { + let span = module.types.get_span(m.ty); + m.ty = module.types.insert( + naga::Type { + name: None, + inner: T::Array { + base, + size, + stride: natural, + }, + }, + span, + ); + changed = true; + } + } + if changed { + module.types.replace(ty, new); + } + } +} + fn first_lines(s: &str) -> String { s.lines().take(8).collect::>().join("\n") } @@ -554,6 +629,8 @@ struct Legaliser<'a> { /// their helpers go in. modulo: bool, nan: bool, + /// `textureGather` was used: [`GATHER`] is added. + gather: bool, mat2_ctor: bool, /// Constants turned into globals ([`needs_runtime`]). runtime_constants: HashSet, @@ -571,6 +648,94 @@ fn call(name: &str, args: Vec) -> ast::Expr { .into_node() } +/// `textureGather(sampler2D, uv, comp)`: component `comp` of the four texels +/// bilinear filtering at `uv` would blend, in GL's order, read with +/// `texelFetch` (edges clamped). +const GATHER: &str = "\ +vec4 iris_gather(texture2D t, sampler s, vec2 uv, int c) { + ivec2 hi = textureSize(sampler2D(t, s), 0) - 1; + ivec2 i = ivec2(floor(uv * vec2(hi + 1) - 0.5)); + vec4 a = texelFetch(sampler2D(t, s), clamp(i + ivec2(0, 1), ivec2(0), hi), 0); + vec4 b = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 1), ivec2(0), hi), 0); + vec4 d = texelFetch(sampler2D(t, s), clamp(i + ivec2(1, 0), ivec2(0), hi), 0); + vec4 e = texelFetch(sampler2D(t, s), clamp(i, ivec2(0), hi), 0); + return vec4(a[c], b[c], d[c], e[c]); +} +"; + +/// GL converts a `bool` given to a numeric constructor (`vec3(r < radius)`, +/// Photon's sun disc); naga refuses. A comparison or logical expression +/// passed to one becomes `(cond ? 1.0 : 0.0)` (or `1`/`1u`). +fn bool_to_number(e: &mut ast::Expr) { + use ast::BinaryOpData as B; + let ast::ExprData::FunCall(f, args) = &mut e.content else { + return; + }; + let Some(name) = callee(f) else { return }; + let base = name.trim_start_matches('d'); + let (one, zero) = if base.starts_with("ivec") || name == "int" { + (ast::ExprData::IntConst(1), ast::ExprData::IntConst(0)) + } else if base.starts_with("uvec") || name == "uint" { + (ast::ExprData::UIntConst(1), ast::ExprData::UIntConst(0)) + } else if base.starts_with("vec") || base.starts_with("mat") || name == "float" { + ( + ast::ExprData::FloatConst(1.0), + ast::ExprData::FloatConst(0.0), + ) + } else { + return; + }; + for a in args.iter_mut() { + let boolean = match &a.content { + ast::ExprData::Binary(op, ..) => matches!( + op.content, + B::Or | B::Xor | B::And | B::Equal | B::NonEqual | B::Lt | B::Gt | B::Lte | B::Gte + ), + ast::ExprData::Unary(op, _) => op.content == ast::UnaryOpData::Not, + _ => false, + }; + if boolean { + let cond = std::mem::replace(a, var("_")); + *a = ast::ExprData::Ternary( + Box::new(cond), + Box::new(one.clone().into_node()), + Box::new(zero.clone().into_node()), + ) + .into_node(); + } + } +} + +/// Outside fragment shaders there are no derivatives, so GL samples level 0 +/// where `texture` and its kin would pick one; naga refuses them there (the +/// vertex programs of Chocapic13', MakeUp and Bliss). Turn them into their +/// `Lod` forms at level 0 (a bias is dropped), also inside `vec4(..)` as +/// legacy shadow lookups are wrapped. +fn explicit_lod(e: &mut ast::Expr) { + let ast::ExprData::FunCall(f, args) = &mut e.content else { + return; + }; + let Some(name) = callee(f) else { return }; + if name == "vec4" && args.len() == 1 { + return explicit_lod(&mut args[0]); + } + // (implicit, explicit, where the level goes, how many arguments without a bias) + let (lod, at, plain) = match name.as_str() { + "texture" => ("textureLod", 2, 2), + "textureProj" => ("textureProjLod", 2, 2), + "textureOffset" => ("textureLodOffset", 2, 3), + "textureProjOffset" => ("textureProjLodOffset", 2, 3), + _ => return, + }; + if args.len() < plain { + return; + } + args.truncate(plain); + let zero = ast::ExprData::FloatConst(0.0).into_node(); + args.insert(at, zero); + *f = ast::FunIdentifierData::Expr(Box::new(var(lod))).into_node(); +} + /// The name a call is made by: a function, or a constructor's type. fn callee(f: &ast::FunIdentifier) -> Option { match &f.content { @@ -784,6 +949,7 @@ impl<'a> Legaliser<'a> { constant: false, modulo: false, nan: false, + gather: false, mat2_ctor: false, runtime_constants: HashSet::new(), } @@ -1253,7 +1419,23 @@ impl<'a> Legaliser<'a> { } let mut locals = Vec::new(); let mut params = Vec::with_capacity(p.parameters.len()); - for param in std::mem::take(&mut p.parameters) { + for mut param in std::mem::take(&mut p.parameters) { + // `const in float x` (Bliss): naga's front end takes no `const` + // on parameters, and it changes nothing for the caller. + match &mut param.content { + ast::FunctionParameterDeclarationData::Named(q, _) + | ast::FunctionParameterDeclarationData::Unnamed(q, _) => { + if let Some(list) = q { + list.qualifiers.retain(|q| { + !matches!(&q.content, ast::TypeQualifierSpecData::Storage(s) + if s.content == ast::StorageQualifierData::Const) + }); + if list.qualifiers.is_empty() { + *q = None; + } + } + } + } let (ty, name) = match ¶m.content { ast::FunctionParameterDeclarationData::Named(_, d) => { (type_text(&d.ty), Some(d.ident.ident.as_str().to_owned())) @@ -1713,32 +1895,60 @@ impl<'a> Legaliser<'a> { self.nan = true; return; } - let mut target_name = name.as_str(); + if name == "textureGather" + && (2..=3).contains(&args.len()) + && let ast::ExprData::FunCall(g, inner) = &args[0].content + && inner.len() == 2 + && callee(g).as_deref() == Some("sampler2D") + { + // naga's GLSL front end has no `textureGather`. + let mut call_args = inner.clone(); + call_args.push(args[1].clone()); + call_args.push( + args.get(2) + .cloned() + .unwrap_or_else(|| ast::ExprData::IntConst(0).into_node()), + ); + *e = call("iris_gather", call_args); + self.gather = true; + return; + } + if name == "modf" + && args.len() == 2 + && !matches!(args[1].content, ast::ExprData::Variable(_)) + { + // `modf(x, v.y)` (Photon): WGSL can't point at a vector + // component, so no `out` parameter: `+(v.y = trunc(x), x - trunc(x))` + // (the unary `+` has the comma printed in brackets, also in an + // initialiser). + let (x, whole) = (args[0].clone(), args[1].clone()); + let assign = ast::ExprData::Assignment( + Box::new(whole), + ast::AssignmentOpData::Equal.into_node(), + Box::new(call("trunc", vec![x.clone()])), + ) + .into_node(); + let fraction = ast::ExprData::Binary( + ast::BinaryOpData::Sub.into_node(), + Box::new(x.clone()), + Box::new(call("trunc", vec![x])), + ) + .into_node(); + let comma = ast::ExprData::Comma(Box::new(assign), Box::new(fraction)).into_node(); + *e = ast::ExprData::Unary(ast::UnaryOpData::Add.into_node(), Box::new(comma)) + .into_node(); + return; + } if let Some((_, new)) = LEGACY_CALLS.iter().find(|(old, _)| *old == name) { *f = ast::FunIdentifierData::Expr(Box::new(var(new))).into_node(); - target_name = new; } else if let Some((_, new)) = SHADOW_CALLS.iter().find(|(old, _)| *old == name) { let args = std::mem::take(args); *e = call("vec4", vec![call(new, args)]); - return; } - // In vertex and compute shaders, `texture(sampler, coord)` uses implicit - // derivatives that WGSL/naga forbid outside fragment shaders (Bliss): - // rewrite 2-argument non-shadow `texture(s, uv)` to `textureLod(s, uv, 0.0)`. - if self.stage != Stage::Fragment && target_name == "texture" && args.len() == 2 { - let is_shadow = match &args[0].content { - ast::ExprData::FunCall(g, _) => { - callee(g).and_then(|c| opaque(&c)).is_some_and(|o| o.3) - } - _ => false, - }; - if !is_shadow { - if let ast::ExprData::FunCall(f, args) = &mut e.content { - *f = ast::FunIdentifierData::Expr(Box::new(var("textureLod"))).into_node(); - args.push(ast::ExprData::FloatConst(0.0).into_node()); - } - } + if self.stage != Stage::Fragment { + explicit_lod(e); } + bool_to_number(e); } /// The legalised source: header, the rewritten program, then a `main` @@ -1775,6 +1985,9 @@ impl<'a> Legaliser<'a> { if self.modulo { out.push_str(&modulo_helpers()); } + if self.gather { + out.push_str(GATHER); + } if self.nan { out.push_str("float iris_sqrt(float x) { return sqrt(x); }\n"); } diff --git a/crates/horizon-shaderpack/tests/translate.rs b/crates/horizon-shaderpack/tests/translate.rs index 9198f8b92..4c932d199 100644 --- a/crates/horizon-shaderpack/tests/translate.rs +++ b/crates/horizon-shaderpack/tests/translate.rs @@ -368,6 +368,78 @@ void main() { reparse(&fs.wgsl).unwrap(); } +/// What Photon, Chocapic13', MakeUp Ultra Fast and Bliss write and GL takes: +/// lookups without a level in a vertex shader, a struct passed between +/// stages, `textureGather`, a `bool` given to `vec3(..)`, `const in` +/// parameters and an array field in a struct built by its constructor. +#[test] +fn legalises_what_photon_and_chocapic_write() { + let mut link = Link::default(); + let header = "uniform sampler2D colortex0; +uniform sampler2DShadow shadowtex0; +struct Clouds { float coverage; vec2 wind; mat3 turn; int layers; }; +"; + let vs = run( + Stage::Vertex, + &format!( + "{header}flat varying Clouds clouds; +void main() {{ + clouds.coverage = texture2D(colortex0, vec2(0.5)).r + shadow2D(shadowtex0, vec3(0.5)).r; + clouds.wind = textureOffset(colortex0, vec2(0.5), ivec2(1, 0), 2.0).rg; + clouds.turn = mat3(1.0); + clouds.layers = 2; + gl_Position = ftransform(); +}} +" + ), + &mut link, + ) + .unwrap(); + for wanted in [ + "textureLod(sampler2D(colortex0_t", + "vec2(0.5), 0.)", + "textureLodOffset(sampler2D(colortex0_t", + "clouds_iriscoverage = clouds.coverage;", + "clouds_iristurn_iris1 = clouds.turn[1];", + ] { + assert!(vs.glsl.contains(wanted), "{wanted}\n{}", vs.glsl); + } + reparse(&vs.wgsl).unwrap(); + let fs = run( + Stage::Fragment, + &format!( + "{header}flat varying Clouds clouds; +struct Spline {{ float slope; float[3] coeffs; }}; +float edge(const in float x, const float r) {{ return float(x < r); }} +void main() {{ + const Spline spline = Spline(0.0, float[3](1.0, 2.0, 3.0)); + vec4 four = textureGather(colortex0, vec2(0.5), 1); + vec3 disc = vec3(clouds.coverage < 0.5); + vec2 cell = vec2(0.0); + float part = modf(clouds.coverage * 4.0, cell.y); + gl_FragColor = vec4(disc * edge(four.x, spline.coeffs[1]), clouds.wind.x + float(clouds.layers) + part + cell.y); +}} +" + ), + &mut link, + ) + .unwrap(); + for wanted in [ + "iris_gather(colortex0_t", + "clouds.coverage = clouds_iriscoverage;", + "float edge(in float x, float r)", + "cell.y = trunc(", + ] { + assert!(fs.glsl.contains(wanted), "{wanted}\n{}", fs.glsl); + } + reparse(&fs.wgsl).unwrap(); + // The vertex program's outputs are the fragment program's inputs. + assert_eq!( + io(&vs, true).get("clouds_iriswind"), + io(&fs, false).get("clouds_iriswind") + ); +} + /// A fragment output narrower than its four-channel target (Steadfast's /// `final` writes `out vec3 color`) is written through a `vec4` with alpha 1: /// GL fills the missing channels, wgpu refuses the pipeline. diff --git a/crates/horizon-world/src/block_entities.rs b/crates/horizon-world/src/block_entities.rs index 22a2bc959..1ee8a90e0 100644 --- a/crates/horizon-world/src/block_entities.rs +++ b/crates/horizon-world/src/block_entities.rs @@ -62,9 +62,6 @@ impl ProtoBlockEntities { pub fn active(&self, position: BlockPos) -> Option<&E> { self.active.get(&position) } - pub fn active_mut(&mut self, position: BlockPos) -> Option<&mut E> { - self.active.get_mut(&position) - } pub fn pending(&self, position: BlockPos) -> Option<&Tag> { self.pending.get(&position) } diff --git a/crates/horizon-world/src/block_render.rs b/crates/horizon-world/src/block_render.rs index 1ed9c51af..aa10d361c 100644 --- a/crates/horizon-world/src/block_render.rs +++ b/crates/horizon-world/src/block_render.rs @@ -157,12 +157,6 @@ impl FaceVisibility { } } } - /// Whether the state's occlusion face toward `direction` is the full square. - pub fn full_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_some_and(|s| s.faces[direction as usize] == 1) - } /// The state's occlusion face toward `direction` (`getFaceOcclusionShape`) and /// its shared ID: 0 is the empty singleton, 1 the full-block singleton. pub fn occlusion_face( @@ -173,12 +167,6 @@ impl FaceVisibility { let id = self.states.get(state.0 as usize)?.faces[direction as usize]; Some((id, &self.faces[id as usize])) } - /// Whether the state's occlusion face toward `direction` is empty. - pub fn empty_face(&self, state: BlockStateId, direction: Direction) -> bool { - self.states - .get(state.0 as usize) - .is_none_or(|s| s.faces[direction as usize] == 0) - } pub fn skip_rendering( &self, state: BlockStateId, diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs index 295999d18..d3ac386cd 100644 --- a/crates/horizon-world/src/block_support.rs +++ b/crates/horizon-world/src/block_support.rs @@ -186,25 +186,6 @@ impl<'r> BlockSupportRegistry<'r> { pub fn registry(&self) -> &'r BlockRegistry { self.cached.registry() } - pub fn support_shape( - &self, - world: &mut W, - state: BlockStateId, - position: [i32; 3], - ) -> Result> { - if let Some(shape) = self - .cached - .cached_shape(state) - .map_err(SupportQueryError::Data)? - { - return Ok(shape.clone()); - } - self.dynamic - .get(&state) - .ok_or(SupportQueryError::Unsupported(state))? - .shape(world, position) - .map_err(SupportQueryError::Dynamic) - } pub fn is_face_sturdy( &self, world: &mut W, diff --git a/crates/horizon-world/src/block_survival.rs b/crates/horizon-world/src/block_survival.rs index bb21f46df..ae53451ba 100644 --- a/crates/horizon-world/src/block_survival.rs +++ b/crates/horizon-world/src/block_survival.rs @@ -524,14 +524,6 @@ impl<'r> BlockSurvivalRegistry<'r> { bubble_down: tag_states("minecraft:enables_bubble_column_drag_down")?, }) } - pub fn supported_states(&self) -> usize { - self.rules.iter().filter(|r| r.is_some()).count() - } - pub fn supports_state(&self, state: BlockStateId) -> bool { - self.rules - .get(state.0 as usize) - .is_some_and(Option::is_some) - } fn read( &self, world: &mut W, diff --git a/crates/horizon-world/src/component_durability.rs b/crates/horizon-world/src/component_durability.rs index 15237133b..5bf576c08 100644 --- a/crates/horizon-world/src/component_durability.rs +++ b/crates/horizon-world/src/component_durability.rs @@ -3,7 +3,6 @@ use crate::{ component_patch::{ComponentMap, MissingPrototype, Patch, Prototype}, item_durability::DurabilityStorage, - item_use_catalog::UseComponents, }; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Key { @@ -52,13 +51,6 @@ impl DurabilityPrototype { } Self(Prototype::new(entries)) } - pub fn from_defaults(defaults: &UseComponents) -> Self { - Self::new([ - Change::MaxDamage(defaults.max_damage), - Change::Damage(defaults.damage), - Change::Unbreakable(defaults.unbreakable), - ]) - } } #[derive(Clone, Debug)] pub struct DurabilityPatch(Patch); diff --git a/crates/horizon-world/src/datafix/dynamic.rs b/crates/horizon-world/src/datafix/dynamic.rs index 44336729c..69cca1453 100644 --- a/crates/horizon-world/src/datafix/dynamic.rs +++ b/crates/horizon-world/src/datafix/dynamic.rs @@ -157,12 +157,6 @@ pub fn map(tag: &Tag) -> Option<&Compound> { _ => None, } } -pub fn map_mut(tag: &mut Tag) -> Option<&mut Compound> { - match tag { - Tag::Compound(c) => Some(c), - _ => None, - } -} /// `Dynamic.set`: only maps change. pub fn set(tag: &mut Tag, field: &str, value: Tag) { if let Tag::End = tag { @@ -193,12 +187,6 @@ pub fn update(tag: &mut Tag, field: &str, f: impl FnOnce(Tag) -> Tag) { set(tag, field, f(v)); } } -/// `Dynamic.update` in place. -pub fn update_mut(tag: &mut Tag, field: &str, f: impl FnOnce(&mut Tag)) { - if let Some(v) = tag.get_mut(field) { - f(v); - } -} /// `Dynamic.renameAndFixField`: the fixed value under the new name, removed when /// the fix gives nothing. pub fn rename_and_fix(tag: &mut Tag, from: &str, to: &str, f: impl FnOnce(Tag) -> Option) { @@ -223,15 +211,6 @@ pub fn is_empty_map(tag: &Tag) -> bool { pub fn or_empty_map(tag: Option<&Tag>) -> Tag { tag.cloned().unwrap_or_else(empty_map) } -/// Apply `f` to every element of a list field (`Dynamic.createList(asStream().map(f))`). -pub fn map_list(tag: &mut Tag, field: &str, mut f: impl FnMut(Tag) -> Tag) { - if let Some(v) = tag.get(field) - && is_list(Some(v)) - { - let list = stream(Some(v)).into_iter().map(&mut f).collect(); - set(tag, field, Tag::List(list)); - } -} /// `NamespacedSchema.ensureNamespaced`. pub fn namespaced(id: &str) -> String { match crate::datafix::identifier(id) { diff --git a/crates/horizon-world/src/entity_move.rs b/crates/horizon-world/src/entity_move.rs index b3b189df0..25d7aef14 100644 --- a/crates/horizon-world/src/entity_move.rs +++ b/crates/horizon-world/src/entity_move.rs @@ -44,9 +44,6 @@ impl MovementHistory { } self.records.push_back(record); } - pub fn remove_latest(&mut self) { - self.records.pop_back(); - } pub fn clear(&mut self) { self.records.clear(); } diff --git a/crates/horizon-world/src/entity_obstruction.rs b/crates/horizon-world/src/entity_obstruction.rs index 89f7f586b..aac2306b6 100644 --- a/crates/horizon-world/src/entity_obstruction.rs +++ b/crates/horizon-world/src/entity_obstruction.rs @@ -73,17 +73,3 @@ pub fn is_unobstructed( } Ok(true) } - -/// Entity obstruction for the unit cube used by the vanilla block predicate. -/// Translate the voxel shape in floating point: integer MAX + 1 must not wrap. -pub fn is_block_unobstructed( - world: &mut W, - position: [i32; 3], -) -> Result> { - let shape = VoxelShape::block().moved(horizon_core::geometry::Vec3::new( - f64::from(position[0]), - f64::from(position[1]), - f64::from(position[2]), - )); - is_unobstructed(world, None, &shape) -} diff --git a/crates/horizon-world/src/fluid.rs b/crates/horizon-world/src/fluid.rs index 4a89764a8..ab03d6a52 100644 --- a/crates/horizon-world/src/fluid.rs +++ b/crates/horizon-world/src/fluid.rs @@ -272,13 +272,6 @@ impl FluidStateTable { pub fn get(&self, state: BlockStateId) -> Option { self.0.get(state.0 as usize).copied() } - pub fn matching_states(&self, mask: u8) -> impl Iterator + '_ { - self.0 - .iter() - .enumerate() - .filter(move |(_, state)| state.kind.mask() & mask != 0) - .map(|(i, _)| BlockStateId(i as u32)) - } } /// Bound identities for converting fluid states into their legacy liquid blocks. diff --git a/crates/horizon-world/src/level/classes.rs b/crates/horizon-world/src/level/classes.rs index 9540a5a47..2d0193de5 100644 --- a/crates/horizon-world/src/level/classes.rs +++ b/crates/horizon-world/src/level/classes.rs @@ -15,9 +15,6 @@ macro_rules! classes { pub fn from_java(name: &str) -> Option { match name { $($java => Some(Class::$name),)* _ => None } } - pub const fn java_name(self) -> &'static str { - match self { $(Class::$name => $java,)* } - } } }; } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index e343e06a7..696777386 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -148,7 +148,6 @@ pub mod flags { pub const UPDATE_NEIGHBORS: i32 = 1; pub const UPDATE_CLIENTS: i32 = 2; pub const UPDATE_INVISIBLE: i32 = 4; - pub const UPDATE_IMMEDIATE: i32 = 8; pub const UPDATE_KNOWN_SHAPE: i32 = 16; pub const UPDATE_SUPPRESS_DROPS: i32 = 32; pub const UPDATE_MOVE_BY_PISTON: i32 = 64; diff --git a/crates/horizon-world/src/level/states.rs b/crates/horizon-world/src/level/states.rs index c7fe012dc..8d2544953 100644 --- a/crates/horizon-world/src/level/states.rs +++ b/crates/horizon-world/src/level/states.rs @@ -348,10 +348,4 @@ impl StateTable { } result } - pub fn property_names(&self, block: BlockId) -> impl Iterator { - self.info(block) - .slots - .iter() - .map(|slot| self.key_names[slot.key.0 as usize].as_str()) - } } diff --git a/crates/horizon-world/src/level/ticks.rs b/crates/horizon-world/src/level/ticks.rs index fbad6c28d..c8d715623 100644 --- a/crates/horizon-world/src/level/ticks.rs +++ b/crates/horizon-world/src/level/ticks.rs @@ -149,9 +149,6 @@ impl Ticks { self.blocks .has_scheduled(pos, TickTypeId(u32::from(block.0))) } - pub fn has_fluid_tick(&self, pos: BlockPos, fluid: FluidKind) -> bool { - self.fluids.has_scheduled(pos, TickTypeId(fluid as u32)) - } pub fn will_block_tick_this_tick(&mut self, pos: BlockPos, block: BlockId) -> bool { self.blocks .will_tick_this_tick(pos, TickTypeId(u32::from(block.0))) diff --git a/crates/horizon-world/src/registry_fluid.rs b/crates/horizon-world/src/registry_fluid.rs index eb0f4ffe0..a122a8978 100644 --- a/crates/horizon-world/src/registry_fluid.rs +++ b/crates/horizon-world/src/registry_fluid.rs @@ -62,9 +62,6 @@ impl<'r> FluidRegistry<'r> { pub fn blocks_flow(&self, id: BlockStateId) -> io::Result { Ok(self.state(id)?.blocks_flow) } - pub fn is_ice(&self, id: BlockStateId) -> io::Result { - Ok(self.state(id)?.ice) - } } /// Both queries return state IDs from the same registry. Separate entry points /// preserve native world dispatch when reading a block versus its fluid cell. diff --git a/crates/horizon-world/src/retrogen.rs b/crates/horizon-world/src/retrogen.rs index fc9f450bf..2f048f48e 100644 --- a/crates/horizon-world/src/retrogen.rs +++ b/crates/horizon-world/src/retrogen.rs @@ -33,9 +33,6 @@ impl BelowZeroRetrogen { .get(index / 64) .is_some_and(|word| word & (1_u64 << (index % 64)) != 0) } - pub fn missing_bedrock_words(&self) -> &[u64] { - &self.missing_bedrock - } pub fn from_nbt(tag: &Tag) -> io::Result { if !matches!(tag, Tag::Compound(_)) { return Err(invalid("retrogen is not a compound")); diff --git a/crates/horizon-world/src/worldgen/aquifer.rs b/crates/horizon-world/src/worldgen/aquifer.rs index 2b4f6e7c3..44500313b 100644 --- a/crates/horizon-world/src/worldgen/aquifer.rs +++ b/crates/horizon-world/src/worldgen/aquifer.rs @@ -50,11 +50,6 @@ impl GlobalFluidPicker { disabled: false, } } - /// Matches the vanilla developer flag. Regular gameplay keeps this false. - pub const fn with_disabled(mut self, disabled: bool) -> Self { - self.disabled = disabled; - self - } } impl FluidPicker for GlobalFluidPicker { fn compute(&self, [_, y, _]: [i32; 3]) -> FluidStatus { diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index b4e8c07b0..e1d80e8bc 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -212,9 +212,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn tick_clock(&self) -> (i64, i64) { (self.game_time, self.next_tick_order) } - pub fn set_game_time(&mut self, game_time: i64) { - self.game_time = game_time; - } /// Raw tick identities are default block-state IDs for block ticks and /// `FluidKind` discriminants for fluid ticks, in separate namespaces. pub fn schedule_tick( @@ -224,15 +221,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { ) -> Result { WorldGenTickAccess::new(RegionTickContainers { region: self, kind }).schedule(tick) } - pub fn has_scheduled_tick( - &mut self, - kind: TickKind, - position: BlockPos, - tick_type: TickTypeId, - ) -> Result { - WorldGenTickAccess::new(RegionTickContainers { region: self, kind }) - .has_scheduled(position, tick_type) - } fn request_tick( &mut self, kind: TickKind, @@ -251,11 +239,6 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { self.schedule_tick(kind, tick)?; Ok(()) } - /// Override world sea level without changing generator placement anchors. - pub fn with_world_sea_level(mut self, sea_level: i32) -> Self { - self.sea_level = sea_level; - self - } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { self.chunks diff --git a/crates/horizon-world/src/worldgen/material_condition/codec.rs b/crates/horizon-world/src/worldgen/material_condition/codec.rs index ec646697e..aa159bd1e 100644 --- a/crates/horizon-world/src/worldgen/material_condition/codec.rs +++ b/crates/horizon-world/src/worldgen/material_condition/codec.rs @@ -65,12 +65,6 @@ impl MaterialConditionRegistry { pub fn from_json(definitions: &BTreeMap) -> Result { Self::load(definitions, None) } - pub fn from_json_with_biomes( - definitions: &BTreeMap, - biomes: &BTreeSet, - ) -> Result { - Self::from_json_with_biome_tags(definitions, biomes, &BTreeMap::new()) - } /// Bind resolved biome tags, such as `TagDefinitions::build().tags`. /// Names and memberships remain immutable for the lifetime of this registry. pub fn from_json_with_biome_tags( diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 098decdf1..da39cd246 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -344,12 +344,6 @@ impl BlockStateProvider { _ => Err(DecodeError::Field("exclusive state or provider")), } } - pub fn from_typed_json( - json: &str, - bindings: &StateProviderBindings<'_>, - ) -> Result { - Self::decode_typed(json, bindings, 0, &mut 65536, None) - } fn decode_typed( json: &str, bindings: &StateProviderBindings<'_>, diff --git a/crates/horizon-world/src/worldgen/terrain.rs b/crates/horizon-world/src/worldgen/terrain.rs index 8ea3b01be..5ecc48045 100644 --- a/crates/horizon-world/src/worldgen/terrain.rs +++ b/crates/horizon-world/src/worldgen/terrain.rs @@ -432,18 +432,6 @@ impl<'r, B: TerrainBlockStates> TerrainChunk<'r, B> { )?; Ok(()) } - pub fn set_heightmap_raw( - &mut self, - kind: HeightmapType, - words: &[u64], - ) -> Result<(), TerrainError> { - self.ensure_heightmap(kind); - self.heightmaps[kind as usize] - .as_mut() - .unwrap() - .set_raw_data(&self.blocks, words)?; - Ok(()) - } /// Before replaying a saved chunk's `PostProcessing` lists. pub fn clear_postprocessing(&mut self) { self.postprocessing.iter_mut().for_each(Vec::clear); diff --git a/docs/agent-control.md b/docs/agent-control.md index 5383cc03c..9d5db2597 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -71,7 +71,6 @@ passes on without checking it). | Dedicated server here: start, console, log, stop | Servers | yes | yes | yes | yes | `server`; MCP `server`, `server_command`, `server_log`, `server_stop` | | Hosted servers: list, create, set up, run a command, forget | Servers | yes | no | yes | yes | `servers ...`; `servers_forget` needs `confirm` | | Accounts: list, sign in, sign out, select, offline | Settings | yes | part | yes | yes | names and UUIDs only; sign-in is a device code; `account_offline` was missing | -| Update channel (Alpha, Stable) | Settings | yes | yes | yes | yes | | | Game folder, server folder, install new versions, opening animation | Settings | no | no | yes | yes | `settings [KEY VALUE]` | | Extra game arguments | Settings | yes | no | yes | yes | `game-args` | | Applications menu entry (Linux) | Settings | yes | no | yes | yes | `desktop-entry` | @@ -148,7 +147,7 @@ The switch is in three places: Settings > AI in the launcher, Horizon Settings i | Companion (#1068) | uses the same switch (see horizon-parity companion-notes.md) | Every other launcher command stays usable: versions, install, remove, prepare, play, server, -notes, links, account, update-channel, settings, game-args, logs, update, desktop-entry, data, +notes, links, account, settings, game-args, logs, update, desktop-entry, data, modpack, mods, servers, no-ai and benchmark. None of them drives the game for an agent. The launcher itself, packagers, the docs and players' scripts need them, and `no-ai` has to stay to turn the switch off. diff --git a/docs/launcher-commands.md b/docs/launcher-commands.md index 579659e68..9e09cd00b 100644 --- a/docs/launcher-commands.md +++ b/docs/launcher-commands.md @@ -130,16 +130,6 @@ Play offline, without an account. MCP: `account_offline`. -## `horizon-launcher update-channel` - -Show or set which Horizon releases install by themselves: stable (a tested build about once a day) or alpha (every release as soon as it is built; can break). - - horizon-launcher update-channel [CHANNEL] - -- `CHANNEL` (stable, alpha): Omit to show the current channel - -MCP: `update_channel`. - ## `horizon-launcher settings` Show the launcher's settings, or set one (the Settings page): selected-version TAG, minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions on|off, opening-animation on|off. diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 3cd6a7191..d30122544 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -451,10 +451,10 @@ The MakeUp, Chocapic13' and Photon rows are from 2026-10-23, on Metal and on Vul | Steadfast | 0.8.0 | drawn: 3 passes | | | MakeUp Ultra Fast | 9.6 | drawn: 6 passes, its fog, light shafts and grade over Horizon's world | | | Chocapic13' | V9 High | drawn: 16 passes; its default TAA upscaling shrinks the world in its `gbuffers_*` vertex programs, which don't run, so the picture is magnified 1/0.7: turn TAA Upscaling off in its settings | | -| Bliss | 2.1.2 | fails | `world0/deferred.vsh`: an operation naga forbids in a vertex shader | +| Photon | v1.4 | loads: 27 passes; draws black: it lights the scene from the G-buffer its `gbuffers_*` write | | +| Bliss | 2.1.2 | fails | `world0/composite1.fsh`: a vector component passed to an `inout` parameter (WGSL can't point at one) | | Bloop | 1.8.0-Alpha-3 | fails | `world0/prepare1.fsh`: `mat2(vec4)` and other constructors naga's GLSL front end refuses | | Noble | v1.9.9 | fails (Apple and NVIDIA) | `world0/deferred4.vsh`: a `vec3[9][9]` varying (nested arrays between stages) | -| Photon | v1.4 | fails | `world0/deferred1.fsh`: `textureGather` | | Rethinking Voxels | r0.1-beta9 | fails | `world0/prepare.fsh`: `1 << 31` overflows naga's constant folding; it also needs images | What the translator does for these packs, as Iris (JCPP and its GLSL transformer) does: @@ -472,6 +472,15 @@ What the translator does for these packs, as Iris (JCPP and its GLSL transformer (`mix`, `?:`, `smoothstep`) becomes a global set at the start of `main`, `sqrt` of a negative constant is evaluated at run time, and a fragment output narrower than four channels (`out vec3`, Steadfast's `final`) is written through a `vec4` with alpha 1 as OpenGL fills it. +- **What GL takes and naga doesn't** (Photon, Chocapic13', MakeUp Ultra Fast, Bliss): `texture2D` and its kin without a + level outside fragment shaders sample level 0 (`textureLod`); a struct passed between stages travels as one varying + per field (matrices by column, arrays by element); `textureGather` reads the four texels with `texelFetch`; a + `bool` given to `vec3(..)` and other numeric constructors becomes `cond ? 1.0 : 0.0`; `const in` parameters lose + the `const`; an array field of a struct that never reaches a buffer gets its natural stride (naga lays every struct + out as std140, so `Spline(.., float[6](..))` didn't match); `modf` into a vector component assigns it instead of + passing a pointer. +- **Every translated program parses again as WGSL** in `real_packs_load`: wgpu is given the text, and naga's WGSL + writer can emit what its WGSL parser refuses (`&v.y`). ### Order to implement diff --git a/launcher/README.md b/launcher/README.md index e12ed2439..16ef197c7 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -78,16 +78,13 @@ page `servers.json` (the list), `servers//` (the servers created there) an `server-runtime/` (the programs and game files they run). - **Settings**: install new Horizon versions automatically (on unless you turn it off; the - selected version only moves to the new one if you were on the newest), which ones (Updates, - below), the opening animation, the game's extra command-line arguments, and the launcher's own - version and update state. -- **Updates**: **Stable** (the default) installs a tested build about once a day, the betas that - `promote.yml` makes stable; **Alpha** installs every release as soon as it is built, several - times a day, and can break (docs/release-flow.md, "Channels"). While it is open, the launcher - looks for new releases every 4 hours on Stable and every 30 minutes on Alpha. Kept as `update_channel` in - `settings.json`; a `beta_builds: true` from launchers before 0.2 reads as Alpha (so does a `nightly` from the channel's first name). - `horizon-launcher update-channel [stable|alpha]` shows or sets it. The **Versions** page - shows each release's channel. The launcher's own updates don't depend on it. + selected version only moves to the new one if you were on the newest), the opening animation, + the game's extra command-line arguments, and the launcher's own version and update state. +- **Updates**: there is one channel. Every release is published as the release, GitHub's latest, + once its smoke test passed (docs/release-flow.md), and the launcher installs it. The game + pre-releases of the old Alpha channel (v0.2.1 on) stay on the Versions page to install + by hand, but are never installed as an update. The `update_channel` and `beta_builds` keys + older launchers wrote in `settings.json` are ignored and dropped on the next save. - **Game arguments**: extra arguments added to the game's command line (for example `--server-thread`), one line where quotes group a word with spaces. They are appended after the launcher's own arguments, kept as `game_args` in `settings.json`, and apply the next time the @@ -102,7 +99,7 @@ their content overflows. Drag the thumb or click the track to navigate without a ## Updates -The launcher looks for a newer Horizon release when it starts and every four hours while it +The launcher looks for a newer Horizon release when it starts and every 30 minutes while it is open, and shows a small "available, Install" line on Play. It also updates itself from GitHub releases tagged `launcher@X.Y.Z` (Horizon's own are `vX.Y.Z`; @@ -111,8 +108,14 @@ every 0.2 tag counts as newer than all of those (docs/versioning.md). It downloa own binary, and offers "Restart" in the footer. Development builds and `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` never replace themselves. +On Linux a release build that starts writes its applications-menu entry only when there is +none, or when the program the entry starts (its `TryExec`, else its `Exec`) no longer exists. +An entry pointing at another launcher that works is left alone, so a test or development build +never takes it over. Turning the Settings switch on, or `horizon-launcher desktop-entry`, +points the entry at this launcher whatever is there. + Linux packagers can set `HORIZON_LAUNCHER_DESKTOP_EXEC` to a wrapper's absolute path. -Menu entries created by Settings or `desktop-entry` then start that wrapper, which can +Menu entries the launcher writes then start that wrapper, which can set `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` to keep launcher updates with the package manager. Launcher releases are automatic (docs/release-flow.md in the repository): when main changes the @@ -134,7 +137,6 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher server [--dir ] [--version ] [--accept-eula] horizon-launcher notes [] patch notes as plain text horizon-launcher links the Discord, sponsor and website links - horizon-launcher update-channel [stable|alpha] show or set which releases install by themselves horizon-launcher game-args [] show or set the extra arguments the game starts with horizon-launcher update [--check] Horizon and the launcher horizon-launcher logs [--lines N] [--crash] the end of the game's log, or its newest crash report @@ -168,7 +170,7 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher data benchmark upload a benchmark report, printed first `--json` prints JSON where there is something to report (`versions`, `install`, `notes`, -`next`, `links`, `update-channel`, `game-args`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, +`next`, `links`, `game-args`, `update --check`, `logs`, `account`, `benchmark`, `data`, `modpack`). Errors go to stderr with exit code 1. `server` runs in the terminal, so lines you type reach its console. `HORIZON_LAUNCHER_HOME` replaces the data folder (for scripts and tests). diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index f88171c4e..87034c43f 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -37,8 +37,9 @@ pub struct Release { pub body: String, pub date: String, pub asset: Option<(String, u64)>, - /// A beta: a game release not promoted to stable yet (a GitHub pre-release, docs/release-flow.md). - pub beta: bool, + /// A GitHub pre-release: the Alpha builds from before every release went out as the release + /// (v0.2.1 on, docs/release-flow.md). Listed and installed by hand, never as an update. + pub prerelease: bool, } #[cfg(all(target_os = "linux", target_arch = "x86_64"))] @@ -264,7 +265,7 @@ fn parse_releases( .take(10) .collect(), asset: found, - beta: r["prerelease"].as_bool().unwrap_or(false), + prerelease: r["prerelease"].as_bool().unwrap_or(false), }); } out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); @@ -348,75 +349,14 @@ pub fn latest(releases: &[Release]) -> Option<&Release> { releases.iter().find(|r| r.asset.is_some()) } -/// The releases a launcher installs by itself: stable ones, and betas too on the Alpha channel. -pub fn channel(releases: &[Release], channel: UpdateChannel) -> Vec { - releases - .iter() - .filter(|r| channel.takes(r)) - .cloned() - .collect() +/// The releases a launcher installs by itself: every one that is published as a release, so +/// GitHub's latest when it comes out. The pre-releases of the old Alpha channel are left out. +pub fn installable_updates(releases: &[Release]) -> Vec { + releases.iter().filter(|r| !r.prerelease).cloned().collect() } -/// Which game releases install by themselves (Settings, "Updates"; docs/release-flow.md, "Channels"). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum UpdateChannel { - /// A tested build about once a day: the betas promote.yml makes stable. - #[default] - Stable, - /// Every release as soon as it is built, pre-releases included. It was called "nightly" - /// while the channels were new: that name is still read. - #[serde(alias = "nightly")] - Alpha, -} - -impl UpdateChannel { - pub fn name(self) -> &'static str { - match self { - UpdateChannel::Stable => "stable", - UpdateChannel::Alpha => "alpha", - } - } - - /// Its name in Settings and on the Versions page. - pub fn label(self) -> &'static str { - match self { - UpdateChannel::Stable => "Stable", - UpdateChannel::Alpha => "Alpha", - } - } - - pub fn parse(name: &str) -> Option { - match name { - "stable" => Some(UpdateChannel::Stable), - "alpha" | "nightly" => Some(UpdateChannel::Alpha), - _ => None, - } - } - - /// Whether this channel installs `release`: betas only reach Alpha. - pub fn takes(self, release: &Release) -> bool { - self == UpdateChannel::Alpha || !release.beta - } - - /// How often a launcher left open looks for new releases: Alpha's come many times a day, - /// Stable's once. - pub fn check_every(self) -> std::time::Duration { - std::time::Duration::from_secs(match self { - UpdateChannel::Stable => 4 * 3600, - UpdateChannel::Alpha => 30 * 60, - }) - } - - /// The channel a release is on when it is listed: betas are Alpha's only. - pub fn of(release: &Release) -> Self { - if release.beta { - UpdateChannel::Alpha - } else { - UpdateChannel::Stable - } - } -} +/// How often a launcher left open looks for new releases: they come out several times a day. +pub const CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(30 * 60); /// The community, sponsor and website links, from `launcher/links.json` on main, so they can change /// without a launcher release. An empty address hides its button. @@ -1745,17 +1685,10 @@ fn launcher_update_from(releases: &[Release], own: &str) -> Option { pub fn releases_and_updates( on_releases: impl FnOnce(Result, String>), ) -> Result { - releases_and_updates_with( - Settings::load().update_channel, - release_list, - installed, - launcher_releases_in, - on_releases, - ) + releases_and_updates_with(release_list, installed, launcher_releases_in, on_releases) } fn releases_and_updates_with( - update_channel: UpdateChannel, load: impl FnOnce() -> Result, installed: impl FnOnce() -> Vec, launchers: impl FnOnce(&serde_json::Value) -> Vec, @@ -1769,7 +1702,7 @@ fn releases_and_updates_with( } }; let releases = parse_releases(&list, ASSET, is_game_tag); - let horizon = horizon_update(&channel(&releases, update_channel), &installed()); + let horizon = horizon_update(&installable_updates(&releases), &installed()); on_releases(Ok(releases)); Ok(Updates { horizon, @@ -1791,15 +1724,14 @@ pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) } } -/// Installs `tag` (or with "latest" the newest release of the player's channel), then updates the selection as +/// Installs `tag` (or with "latest" the newest release, pre-releases left out), then updates the selection as /// `select_after_update` says when `as_update`, or always selects it otherwise. pub fn install_tag(tag: &str, as_update: bool, progress: impl Fn(f32)) -> Result { let releases = releases()?; let release = if tag == "latest" { - let update_channel = Settings::load().update_channel; releases .iter() - .find(|r| r.asset.is_some() && update_channel.takes(r)) + .find(|r| r.asset.is_some() && !r.prerelease) .ok_or("No release has a build for this platform yet.")? } else { releases @@ -2262,10 +2194,6 @@ pub struct Settings { /// default. Appended after the launcher's own arguments, so they can add to or override them. #[serde(default, skip_serializing_if = "String::is_empty")] pub game_args: String, - /// Which releases install by themselves: Stable by default. Launchers before 0.2 had a "Beta - /// builds" switch instead; [`Settings::parse`] reads its `beta_builds: true` as Alpha. - #[serde(default)] - pub update_channel: UpdateChannel, /// Dark, Light, or the system's: the launcher's look. Dark by default. #[serde(default)] pub appearance: Appearance, @@ -2284,20 +2212,7 @@ impl Settings { return Self::default(); }; if let Some(fields) = value.as_object_mut() { - // The switch from before 0.2: on meant every release at once, the Alpha channel. - if fields.remove("beta_builds") == Some(serde_json::Value::Bool(true)) { - fields - .entry("update_channel") - .or_insert_with(|| UpdateChannel::Alpha.name().into()); - } - // A channel this launcher doesn't know is Stable, not a reason to lose every setting. - if fields - .get("update_channel") - .is_some_and(|c| c.as_str().and_then(UpdateChannel::parse).is_none()) - { - fields.remove("update_channel"); - } - // The same for an appearance from a newer launcher. + // An appearance from a newer launcher is Dark, not a reason to lose every setting. if fields .get("appearance") .is_some_and(|a| serde_json::from_value::(a.clone()).is_err()) @@ -2517,41 +2432,35 @@ mod tests { assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); } - /// Betas (GitHub pre-releases) install by themselves only on the Alpha channel; Stable waits - /// for promote.yml's daily promotion (docs/release-flow.md, "Channels"). + /// Every release is published as the release, and launchers update to it. The pre-releases + /// of the old Alpha channel (v0.2.1 on) are only installed by hand: a launcher that + /// had one installed waits for the next release instead of going back. #[test] - fn updates_follow_the_stable_channel_unless_alpha_is_picked() { + fn updates_follow_every_release_and_leave_the_old_alpha_ones_out() { let asset = ASSET.unwrap_or("horizon-linux-x86_64.tar.gz"); let list = serde_json::json!([ - {"tag_name": "v2026.10.19.02", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "b", "size": 1}]}, - {"tag_name": "v2026.10.19.01", "assets": [{"name": asset, "browser_download_url": "s", "size": 1}]}, + {"tag_name": "v0.2.13", "assets": [{"name": asset, "browser_download_url": "n", "size": 1}]}, + {"tag_name": "v0.2.12", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "a", "size": 1}]}, + {"tag_name": "v0.2.0", "assets": [{"name": asset, "browser_download_url": "s", "size": 1}]}, ]); let releases = parse_releases(&list, Some(asset), is_game_tag); assert_eq!( - releases.iter().map(|r| r.beta).collect::>(), - [true, false] + releases.iter().map(|r| r.prerelease).collect::>(), + [false, true, false] ); - let offered = |alpha: bool, installed: &[&str]| { + let offered = |releases: &[Release], installed: &[&str]| { let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); - let on = if alpha { - UpdateChannel::Alpha - } else { - UpdateChannel::Stable - }; - horizon_update(&channel(&releases, on), &installed).map(|r| r.tag) + horizon_update(&installable_updates(releases), &installed).map(|r| r.tag) }; - assert_eq!(offered(false, &[]), Some("v2026.10.19.01".into())); - assert_eq!( - offered(true, &["v2026.10.19.01"]), - Some("v2026.10.19.02".into()) - ); - assert_eq!(offered(false, &["v2026.10.19.01"]), None); - // A beta installed earlier is never "updated" to an older stable build. - assert_eq!(offered(false, &["v2026.10.19.02"]), None); - assert_eq!( - releases.iter().map(UpdateChannel::of).collect::>(), - [UpdateChannel::Alpha, UpdateChannel::Stable] - ); + assert_eq!(offered(&releases, &[]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.0"]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.12"]), Some("v0.2.13".into())); + assert_eq!(offered(&releases, &["v0.2.13"]), None); + // Before the first release of the single channel: the old Alpha one stays where it is. + let before = &releases[1..]; + assert_eq!(offered(before, &["v0.2.0"]), None); + assert_eq!(offered(before, &["v0.2.12", "v0.2.0"]), None); + assert_eq!(CHECK_EVERY.as_secs(), 30 * 60); } #[test] @@ -2573,48 +2482,20 @@ mod tests { } #[test] - fn the_update_channel_is_stored_by_name_and_the_old_beta_switch_reads_as_alpha() { - let read = |text: &str| Settings::parse(text).update_channel; - assert_eq!(read(""), UpdateChannel::Stable); - assert_eq!(read("{}"), UpdateChannel::Stable); - assert_eq!( - read(r#"{"update_channel": "stable"}"#), - UpdateChannel::Stable - ); - assert_eq!(read(r#"{"update_channel": "alpha"}"#), UpdateChannel::Alpha); - // The channel's first name, from launchers built while it was called Nightly. - assert_eq!( - read(r#"{"update_channel": "nightly"}"#), - UpdateChannel::Alpha - ); - assert_eq!(UpdateChannel::parse("nightly"), Some(UpdateChannel::Alpha)); - // Launchers before 0.2: "Beta builds" on is Alpha, off is Stable. - assert_eq!(read(r#"{"beta_builds": true}"#), UpdateChannel::Alpha); - assert_eq!(read(r#"{"beta_builds": false}"#), UpdateChannel::Stable); - // Once a channel is picked, it wins over a switch left behind. - let both = r#"{"beta_builds": true, "update_channel": "stable"}"#; - assert_eq!(read(both), UpdateChannel::Stable); - // An unknown channel is Stable, and the rest of the settings survive it. - let odd = - Settings::parse(r#"{"update_channel": "beta", "game_args": "--x", "beta_builds": 1}"#); - assert_eq!(odd.update_channel, UpdateChannel::Stable); - assert_eq!(odd.game_args, "--x"); - // Saved as a name, without the old switch. - let mut settings = Settings::parse(r#"{"selected": "v0.2.0", "beta_builds": true}"#); - let saved = serde_json::to_value(&settings).unwrap(); - assert_eq!(saved["update_channel"], "alpha"); - assert!(saved.get("beta_builds").is_none()); - assert_eq!(saved["selected"], "v0.2.0"); - settings.update_channel = UpdateChannel::Stable; - let text = serde_json::to_string(&settings).unwrap(); - assert_eq!(read(&text), UpdateChannel::Stable); - for c in [UpdateChannel::Stable, UpdateChannel::Alpha] { - assert_eq!(UpdateChannel::parse(c.name()), Some(c)); + fn the_old_update_channel_settings_are_dropped_and_the_rest_kept() { + for old in [ + r#"{"update_channel": "alpha", "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"update_channel": "stable", "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"beta_builds": true, "game_args": "--x", "selected": "v0.2.0"}"#, + r#"{"beta_builds": false, "update_channel": "nightly", "game_args": "--x", "selected": "v0.2.0"}"#, + ] { + let settings = Settings::parse(old); + assert_eq!(settings.game_args, "--x", "{old}"); + assert_eq!(settings.selected.as_deref(), Some("v0.2.0"), "{old}"); + let saved = serde_json::to_value(&settings).unwrap(); + assert!(saved.get("update_channel").is_none(), "{old}"); + assert!(saved.get("beta_builds").is_none(), "{old}"); } - // An open launcher looks again every 4 hours on Stable, every 30 minutes on Alpha. - let minutes = |c: UpdateChannel| c.check_every().as_secs() / 60; - assert_eq!(minutes(UpdateChannel::Stable), 240); - assert_eq!(minutes(UpdateChannel::Alpha), 30); } #[test] @@ -2635,7 +2516,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; assert!(launcher_update(&[r(own_tag())]).is_none()); assert_eq!(launcher_version(&own_tag()), Some(VERSION)); @@ -2675,7 +2556,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; let mut list = vec![ r("launcher-v0.16.0"), @@ -2744,10 +2625,14 @@ mod tests { ]); let releases = parse_releases(&list, Some(asset), is_game_tag); let installed = ["v2026.10.19.15".to_string(), "v2026.10.12".to_string()]; - let offered = |on| horizon_update(&channel(&releases, on), &installed).map(|r| r.tag); - // A beta 0.2.0 reaches launchers on Alpha; Stable ones wait for its promotion. - assert_eq!(offered(UpdateChannel::Alpha), Some("v0.2.0".into())); - assert_eq!(offered(UpdateChannel::Stable), None); + // A pre-release 0.2.0 is not an update; once published as the release, it is one. + let offered = |releases: &[Release]| { + horizon_update(&installable_updates(releases), &installed).map(|r| r.tag) + }; + assert_eq!(offered(&releases), None); + let mut released = releases.clone(); + released[0].prerelease = false; + assert_eq!(offered(&released), Some("v0.2.0".into())); let mut sorted = vec![ "v2026.10.19.15".to_string(), "v0.2.1".into(), @@ -2837,7 +2722,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), - beta: false, + prerelease: false, }; let releases = [r("v2026.10.13"), r("v2026.10.12")]; assert_eq!( diff --git a/launcher/src/backend/release_loading_tests.rs b/launcher/src/backend/release_loading_tests.rs index 4aaa616a2..d7f839bde 100644 --- a/launcher/src/backend/release_loading_tests.rs +++ b/launcher/src/backend/release_loading_tests.rs @@ -45,7 +45,6 @@ fn baseline(load: impl Fn() -> Result) -> (Vec Result) -> (Vec, Updates) { let mut releases = None; let updates = releases_and_updates_with( - UpdateChannel::Stable, load, installed_fixture, |list| parse_releases(list, LAUNCHER_ASSET, is_launcher_tag), @@ -82,7 +81,6 @@ fn errors_reach_releases_and_updates_without_fallback() { ] { let mut published = None; let result = releases_and_updates_with( - UpdateChannel::Stable, || Err(error.into()), || panic!("no installed scan after failure"), |_| panic!("no fallback after failure"), @@ -97,7 +95,6 @@ fn errors_reach_releases_and_updates_without_fallback() { fn publish_games_before_older_launcher_fallback() { let events = RefCell::new(Vec::new()); let result = releases_and_updates_with( - UpdateChannel::Stable, || Ok(serde_json::json!([{"tag_name": "v2026.10.14", "assets": []}])), Vec::new, |list| { @@ -132,7 +129,6 @@ fn failed_launcher_fallback_keeps_game_result_and_checks_stay_fresh() { for day in [14, 15] { let mut published = None; let updates = releases_and_updates_with( - UpdateChannel::Stable, || { requests.fetch_add(1, Ordering::Relaxed); Ok(serde_json::json!([{"tag_name": format!("v2026.10.{day}")}])) diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index 732aa872b..9d8e51d93 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -287,13 +287,6 @@ enum Cmd { #[command(subcommand)] action: Option, }, - /// Show or set which Horizon releases install by themselves: stable (a tested build about once - /// a day) or alpha (every release as soon as it is built; can break) - UpdateChannel { - /// Omit to show the current channel - #[arg(value_parser = ["stable", "alpha"])] - channel: Option, - }, /// Show the launcher's settings, or set one (the Settings page): selected-version TAG, /// minecraft-dir PATH, server-dir PATH ("default" resets a folder), install-new-versions /// on|off, opening-animation on|off @@ -435,7 +428,6 @@ fn settings_json(s: &backend::Settings) -> serde_json::Value { "server_dir": backend::server_dir(None), "install_new_versions": s.install_new_versions.unwrap_or(true), "opening_animation": !s.skip_opening, - "update_channel": s.update_channel.name(), "game_args": s.game_args, "desktop_entry": s.desktop_entry.unwrap_or(true), "no_ai": backend::no_ai(), @@ -504,7 +496,7 @@ fn attached(mut cmd: Command) -> Result<(), String> { fn release_json(r: &Release) -> serde_json::Value { serde_json::json!({ - "tag": r.tag, "name": r.name, "date": r.date, "channel": backend::UpdateChannel::of(r).name(), + "tag": r.tag, "name": r.name, "date": r.date, "prerelease": r.prerelease, "available_here": r.asset.is_some(), "installed": backend::installed().contains(&r.tag), }) } @@ -555,8 +547,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { (false, true) => "", (false, false) => "no build for this platform", }; - let channel = backend::UpdateChannel::of(r).name(); - println!("{:<15} {} {:<7} {}", r.tag, r.date, channel, state); + println!("{:<15} {} {}", r.tag, r.date, state); } } Cmd::Install { tag } => { @@ -733,19 +724,6 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } } - Cmd::UpdateChannel { channel } => { - let mut settings = backend::Settings::load(); - if let Some(channel) = channel.as_deref().and_then(backend::UpdateChannel::parse) { - settings.update_channel = channel; - settings.save(); - } - let channel = settings.update_channel.name(); - if as_json { - json(serde_json::json!({ "update_channel": channel })); - } else { - println!("Update channel: {channel}"); - } - } Cmd::GameArgs { args } => { let mut settings = backend::Settings::load(); if let Some(line) = args { diff --git a/launcher/src/cli_tools.rs b/launcher/src/cli_tools.rs index 307f17dba..7653311ac 100644 --- a/launcher/src/cli_tools.rs +++ b/launcher/src/cli_tools.rs @@ -366,7 +366,6 @@ mod tests { "prepare", "notes", "update", - "update_channel", "game_args", "settings", "logs", diff --git a/launcher/src/desktop.rs b/launcher/src/desktop.rs index 1c9fe931e..281850cb6 100644 --- a/launcher/src/desktop.rs +++ b/launcher/src/desktop.rs @@ -2,8 +2,12 @@ //! `applications/horizon-launcher.desktop` (pointing at wherever the binary is now) and Horizon's //! icon into the `hicolor` theme, under `$XDG_DATA_HOME` (`~/.local/share` by default), so no root //! is needed; `horizon.desktop` (hidden from menus) gives the game's window its icon on Wayland. -//! A release build does this when it starts, and again whenever the binary has moved; the -//! Settings switch and `horizon-launcher desktop-entry --remove` take it all away again. +//! A release build writes it when it starts only if there is no entry yet or the one there starts +//! a program that is gone ([`repair`]), so a development or test build never takes over a working +//! entry. Turning the Settings switch on (or `horizon-launcher desktop-entry`) points it at this +//! binary whatever is there ([`install`]); the switch off and `desktop-entry --remove` take it all +//! away again. +use std::ffi::OsStr; use std::fs; use std::io; use std::path::{Path, PathBuf}; @@ -153,15 +157,85 @@ pub fn remove_in(data: &Path) -> io::Result<()> { Ok(()) } -/// Registers the launcher, using a distributor's wrapper when one is configured. -/// Both GUI registration (including the settings switch) and the CLI use this path. +/// The program an entry starts: its `TryExec`, else the first word of its `Exec` (unquoted as +/// [`quote`] writes it). None when the entry names neither. +fn entry_target(entry: &str) -> Option { + let mut in_main = false; + let (mut exec, mut try_exec) = (None, None); + for line in entry.lines().map(str::trim) { + if line.starts_with('[') { + in_main = line == "[Desktop Entry]"; + } else if let Some((key, value)) = line.split_once('=').filter(|_| in_main) { + match key.trim() { + "TryExec" if try_exec.is_none() => try_exec = Some(value.trim()), + "Exec" if exec.is_none() => exec = Some(value.trim()), + _ => {} + } + } + } + if let Some(program) = try_exec.filter(|p| !p.is_empty()) { + return Some(program.to_string()); + } + let exec = exec?; + let program = match exec.strip_prefix('"') { + Some(rest) => { + let (mut out, mut chars) = (String::new(), rest.chars()); + while let Some(c) = chars.next() { + match c { + '"' => break, + '\\' => out.extend(chars.next()), + c => out.push(c), + } + } + out + } + None => exec.split_whitespace().next()?.to_string(), + }; + (!program.is_empty()).then_some(program) +} + +/// Whether an entry's program is there: a path that exists, or a bare name found on `path` +/// (`$PATH`), as menus look `TryExec` up. +fn target_exists(program: &str, path: Option<&OsStr>) -> bool { + if program.contains('/') { + return Path::new(program).exists(); + } + path.is_some_and(|dirs| std::env::split_paths(dirs).any(|dir| dir.join(program).is_file())) +} + +/// Whether the launcher may write its entry by itself: there is none under `data`, or the one +/// there starts a program that no longer exists. An entry pointing at another launcher that +/// still works is left alone. +pub fn needs_repair_in(data: &Path, path: Option<&OsStr>) -> bool { + match fs::read_to_string(data.join("applications").join(LAUNCHER_ENTRY)) { + Ok(entry) => !entry_target(&entry).is_some_and(|p| target_exists(&p, path)), + Err(e) => e.kind() == io::ErrorKind::NotFound, + } +} + +/// What the entry starts: a distributor's wrapper (`HORIZON_LAUNCHER_DESKTOP_EXEC`) when one is +/// configured, else the binary at `exe`. +fn target(exe: &Path) -> PathBuf { + std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") + .filter(|path| !path.is_empty()) + .map_or_else(|| exe.to_path_buf(), PathBuf::from) +} + +/// Registers the launcher whatever entry is there: for the player turning it on (the Settings +/// switch, `horizon-launcher desktop-entry`). pub fn install(exe: &Path) -> Result { let data = data_home().ok_or("No home folder to put the menu entry in.")?; - let wrapper = std::env::var_os("HORIZON_LAUNCHER_DESKTOP_EXEC") - .filter(|path| !path.is_empty()) - .map(PathBuf::from); - install_in(&data, wrapper.as_deref().unwrap_or(exe)) - .map_err(|e| format!("{}: {e}", data.display())) + install_in(&data, &target(exe)).map_err(|e| format!("{}: {e}", data.display())) +} + +/// At start: registers the launcher only when [`needs_repair_in`] says so. Returns whether it +/// wrote anything. +pub fn repair(exe: &Path) -> Result { + let data = data_home().ok_or("No home folder to put the menu entry in.")?; + if !needs_repair_in(&data, std::env::var_os("PATH").as_deref()) { + return Ok(false); + } + install_in(&data, &target(exe)).map_err(|e| format!("{}: {e}", data.display())) } pub fn remove() -> Result<(), String> { @@ -206,4 +280,59 @@ mod tests { remove_in(&data).unwrap(); let _ = fs::remove_dir_all(&data); } + + #[test] + fn the_target_is_try_exec_else_the_first_word_of_exec() { + let ours = launcher_entry(Path::new("/opt/a b/horizon \"x\"/horizon-launcher")); + assert_eq!( + entry_target(&ours).as_deref(), + Some("/opt/a b/horizon \"x\"/horizon-launcher") + ); + let without_try = ours.replace("TryExec=", "X-Old="); + assert_eq!( + entry_target(&without_try).as_deref(), + Some("/opt/a b/horizon \"x\"/horizon-launcher") + ); + let wrapper = "[Desktop Entry]\nExec=flatpak run dev.horizon.Launcher %U\n"; + assert_eq!(entry_target(wrapper).as_deref(), Some("flatpak")); + // Only the main group counts: an action's Exec is not the launcher. + let action = "[Desktop Action play]\nExec=/a\n[Desktop Entry]\nExec=/b --x\n"; + assert_eq!(entry_target(action).as_deref(), Some("/b")); + assert_eq!(entry_target("[Desktop Entry]\nName=Horizon\n"), None); + assert_eq!(entry_target("[Desktop Entry]\nExec=\nTryExec=\n"), None); + } + + /// A build that starts never takes over an entry that works (a test or development build + /// started on a player's machine, 2026-10-23); it writes one only when there is none or the + /// program it starts is gone. + #[test] + fn a_start_writes_the_entry_only_when_none_works() { + let root = + std::env::temp_dir().join(format!("horizon-desktop-repair-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let (data, bin) = (root.join("data"), root.join("bin")); + fs::create_dir_all(&bin).unwrap(); + let installed = bin.join("horizon-launcher"); + fs::write(&installed, b"").unwrap(); + let entry = data.join("applications").join(LAUNCHER_ENTRY); + let path = Some(bin.as_os_str()); + + // No entry: write one. + assert!(needs_repair_in(&data, path)); + install_in(&data, &installed).unwrap(); + // Ours works: a build elsewhere leaves it alone. + assert!(!needs_repair_in(&data, path)); + // So does one another launcher wrote, found on PATH or by its path. + fs::write(&entry, "[Desktop Entry]\nExec=horizon-launcher %U\n").unwrap(); + assert!(!needs_repair_in(&data, path)); + assert!(needs_repair_in(&data, None)); + // The program is gone (a deleted target/ folder, a moved binary): write it again. + install_in(&data, &installed).unwrap(); + fs::remove_file(&installed).unwrap(); + assert!(needs_repair_in(&data, path)); + // An entry that starts nothing is broken too. + fs::write(&entry, "[Desktop Entry]\nName=Horizon\n").unwrap(); + assert!(needs_repair_in(&data, path)); + let _ = fs::remove_dir_all(&root); + } } diff --git a/launcher/src/main.rs b/launcher/src/main.rs index 128bf1bcf..18e8295b1 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -238,15 +238,16 @@ impl Launcher { if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); } - // Release builds on Linux keep their entry in the applications menu up to date (a moved - // binary changes it); `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. + // Release builds on Linux put their entry back in the applications menu when there is + // none or it starts a program that is gone (a moved or deleted binary), never over one + // that works; `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. if cfg!(target_os = "linux") && settings.desktop_entry() && (!cfg!(debug_assertions) || std::env::var_os("HORIZON_LAUNCHER_DESKTOP_ENTRY").is_some()) { std::thread::spawn(|| { - let _ = horizon_launcher::desktop::install(backend::exe_path()); + let _ = horizon_launcher::desktop::repair(backend::exe_path()); }); } let installed = backend::installed(); @@ -658,8 +659,10 @@ impl Launcher { changed = true; } } - let every = self.settings.update_channel.check_every(); - if self.checked.is_some_and(|at| at.elapsed() > every) { + if self + .checked + .is_some_and(|at| at.elapsed() > backend::CHECK_EVERY) + { self.check_updates(); } if changed { @@ -1698,14 +1701,10 @@ impl Launcher { )); } foot = foot.child( - caps(format!( - "Launcher {} · {}", - backend::VERSION, - self.settings.update_channel.label() - )) - .px(px(8.)) - .pt(px(6.)) - .text_color(t.muted), + caps(format!("Launcher {}", backend::VERSION)) + .px(px(8.)) + .pt(px(6.)) + .text_color(t.muted), ); div() .id("sidebar") @@ -2339,25 +2338,6 @@ impl Launcher { cx.notify(); }), ); - use backend::UpdateChannel::{Alpha, Stable}; - let this = cx.entity().downgrade(); - let update_channel = segments( - "update-channel", - &[(Stable, Stable.label()), (Alpha, Alpha.label())], - self.settings.update_channel, - &t, - move |picked, _, cx| { - let _ = this.update(cx, |this, cx| { - if this.settings.update_channel != picked { - this.settings.update_channel = picked; - this.settings.save(); - // What counts as new changed: check again (and install it if that is on). - this.check_updates(); - } - cx.notify(); - }); - }, - ); let opening = switch("opening", !self.settings.skip_opening, &t).on_click(cx.listener( |this, _: &ClickEvent, _, cx| { this.settings.skip_opening = !this.settings.skip_opening; @@ -2487,22 +2467,6 @@ impl Launcher { Some(toggle.into_any_element()), &t, )) - .child(index_row( - n + 2, - "Updates", - Some( - div() - .flex() - .flex_col() - .child("Stable: a tested build about once a day.") - .child( - "Alpha: every change as soon as it is built, several times a day; can break.", - ) - .into_any_element(), - ), - Some(update_channel.into_any_element()), - &t, - )) .child(group("Launcher", "monitor")) .child(index_row( n + 3, @@ -2955,8 +2919,7 @@ impl Launcher { let tag = release.tag.clone(); let installed = self.installed.contains(&tag); let selected = self.selected() == Some(&tag); - let channel = backend::UpdateChannel::of(&release).label(); - let mut meta = vec![channel.to_string(), release.date.clone()]; + let mut meta = vec![release.date.clone()]; if let Some((_, size)) = release.asset { meta.push(megabytes(size)); } diff --git a/tests/test_parity_runner.py b/tests/test_parity_runner.py index ffec8d3d5..a9b7ff595 100644 --- a/tests/test_parity_runner.py +++ b/tests/test_parity_runner.py @@ -16,10 +16,38 @@ class ParityRunnerTests(unittest.TestCase): def test_artifacts_follow_profile_and_stop_at_program_arguments(self): self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "--example", "a", "--bin", "b"]), - [["example", "a", "release"], ["bin", "b", "release"]]) + [["example", "a", "release", [], True], ["bin", "b", "release", [], True]]) self.assertEqual(parity.artifacts_of(["cargo", "run", "--profile", "fast", "--example", "c", "--", "--example", "x"]), - [["example", "c", "fast"]]) - self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev"]]) + [["example", "c", "fast", [], True]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--example", "d"]), [["example", "d", "dev", [], True]]) + + def test_artifacts_keep_the_package_and_feature_selection(self): + self.assertEqual(parity.artifacts_of(["cargo", "build", "--locked", "--profile=fast", "-j", "4", "--package", + "horizon-client", "--bins", "-F", "x"]), + [["bins", "", "fast", ["-p", "horizon-client", "--features", "x"], False]]) + self.assertEqual(parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin=horizon-world"]), + [["bin", "horizon-world", "release", ["-p", "horizon-world"], False]]) + + def test_prebuild_repeats_each_harness_selection(self): + artifacts = [ + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "a"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "b"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "build", "--release", "--bin", "horizon-world"]), + *parity.artifacts_of(["cargo", "run", "--profile", "fast", "-p", "horizon-client", "--example", "c"]), + *parity.artifacts_of(["cargo", "build", "--release", "-p", "horizon-world", "--example", "renamed"]), + ["example", "old", "release"], # recorded before selections were kept: its own crate's -p + ["example", "unknown", "release"], # no longer in the workspace: left to its harness + ] + packages = {("example", "a"): "horizon-world", ("example", "b"): "horizon-world", ("example", "c"): "horizon-client", + ("bin", "horizon-world"): "horizon-world", ("example", "old"): "horizon-world"} + self.assertEqual(parity.prebuild_commands(artifacts, packages), [ + ["cargo", "build", "--locked", "--profile", "fast", "-p", "horizon-client", "--example", "c"], + ["cargo", "build", "--locked", "--profile", "release", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--bin", "horizon-world"], + ["cargo", "build", "--locked", "--profile", "release", "-p", "horizon-world", "--example", "a", "--example", "b", + "--example", "old"], + ]) def test_java_sources_include_classes_pulled_from_the_sourcepath(self): with tempfile.TemporaryDirectory() as temp: diff --git a/tools/datafix_scene_12.py b/tools/datafix_scene_12.py index 3d4a6366f..a73b16c28 100644 --- a/tools/datafix_scene_12.py +++ b/tools/datafix_scene_12.py @@ -23,6 +23,8 @@ import threading import time from pathlib import Path +import lab + BX, BZ, SIZE = 144, 144, 96 # south-west corner and size of the platforms (inside the spawn chunks) LAYERS = list(range(100, 245, 16)) # platform y levels: one chunk section each, the last one reaches y = 255 UUID_HI = 0x6000 @@ -1743,7 +1745,7 @@ LAST = {} def populate(server, Bot, port, protocol, name, problems): """Build the whole 1.12.2 scene, save it for good and return the (still joined) bot.""" harness = sys.modules[Bot.__module__] - Player = make_player(Bot, harness.varint, harness.parse_varint, harness.mcstring) + Player = make_player(Bot, lab.varint, lab.parse_varint, harness.mcstring) set_protocol(protocol) say = lambda cmds, **kw: batch(server, cmds, problems, **kw) if ERA < 12: @@ -1874,7 +1876,7 @@ def build_flat(h, force=False): return [] work = h.LOCAL / 'gen' / (version + '-flat') shutil.rmtree(work, ignore_errors=True) - port = h.free_port() + port = lab.free_port() class FlatServer(h.Server): def __init__(self, directory): # as Server.__init__, with a flat world @@ -1900,7 +1902,7 @@ def build_flat(h, force=False): # A flat world's spawn is found far away; make it (64, 64), and let a bot visit the scene's area so that its chunks # are loaded (they stay loaded, being within the spawn radius). batch(server, ['setworldspawn 64 4 64'], problems) - Player = make_player(h.Bot, h.varint, h.parse_varint, h.mcstring) + Player = make_player(h.Bot, lab.varint, lab.parse_varint, h.mcstring) visitor = Player(port, protocol, h.BOT) time.sleep(2) for x, z in ((24, 24), (24, 72), (24, 104), (72, 24), (72, 72), (72, 104), (104, 24), (104, 72), (104, 104), (72, 123), (-8, 63), (32, 103)): diff --git a/tools/datafix_worlds.py b/tools/datafix_worlds.py index de32e4c09..8411afbc2 100644 --- a/tools/datafix_worlds.py +++ b/tools/datafix_worlds.py @@ -23,7 +23,6 @@ import sys import threading import time import urllib.request -import uuid import zipfile import zlib from pathlib import Path @@ -31,6 +30,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import datafix_scene as scene # noqa: E402 import datafix_scene_12 as scene12 # noqa: E402 +import lab # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -159,12 +159,6 @@ def install_runtime(pin, home): target.symlink_to(to) -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Server: def __init__(self, directory, jar, port, packs=(), java='java', props_override=None): directory.mkdir(parents=True, exist_ok=True) @@ -230,38 +224,9 @@ def failed(lines): # ------------------------------------------------------------------ minimal bot -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def mcstring(s): data = s.encode() - return varint(len(data)) + data - - -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) + return lab.varint(len(data)) + data class Bot: @@ -273,21 +238,21 @@ class Bot: self.buffer = b'' self.protocol = protocol self.stop = threading.Event() - self.send(0, varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + varint(2)) + self.send(0, lab.varint(protocol) + mcstring('127.0.0.1') + struct.pack('>H', port) + lab.varint(2)) if protocol <= 758: # 1.18.2: the name only self.send(0, mcstring(name)) elif protocol == 759: # 1.19: no signature data self.send(0, mcstring(name) + b'\x00') elif protocol == 760: # 1.19.2: no signature data, optional UUID - self.send(0, mcstring(name) + b'\x00' + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x00' + b'\x01' + lab.offline_uuid(name).bytes) elif protocol <= 763: # 1.19.3 - 1.20.1: optional UUID - self.send(0, mcstring(name) + b'\x01' + offline_uuid(name).bytes) + self.send(0, mcstring(name) + b'\x01' + lab.offline_uuid(name).bytes) else: - self.send(0, mcstring(name) + offline_uuid(name).bytes) + self.send(0, mcstring(name) + lab.offline_uuid(name).bytes) while True: pid, data = self.receive() if pid == 3: - self.threshold = parse_varint(data, 0)[1] + self.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -312,15 +277,15 @@ class Bot: elif pid == disconnect: raise RuntimeError(f'disconnected during configuration: {data!r}') elif not old and self.known_packs(data): - self.send(7, varint(0)) # claim no packs: the server sends full registries + self.send(7, lab.varint(0)) # claim no packs: the server sends full registries @staticmethod def known_packs(data): try: - pos, count = parse_varint(data, 0) + pos, count = lab.parse_varint(data, 0) if count < 1: return False - pos, n = parse_varint(data, pos) + pos, n = lab.parse_varint(data, pos) return data[pos:pos + n] == b'minecraft' except IndexError: return False @@ -359,18 +324,18 @@ class Bot: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: - body = varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(len(body)) + zlib.compress(body) if len(body) >= self.threshold else lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] @@ -428,7 +393,7 @@ def build(name, force=False): era = scene.era(data_version) work = LOCAL / 'gen' / name shutil.rmtree(work, ignore_errors=True) - port = free_port() + port = lab.free_port() server = Server(work, jar, port, scene.experiments(data_version), java(version), props) problems = [] diff --git a/tools/lab.py b/tools/lab.py index 87713276d..a62a38f59 100644 --- a/tools/lab.py +++ b/tools/lab.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 """Pinned Java Edition import/decompilation. Game files come from the user's own copy (their official launcher install and the server jar they downloaded); all -generated files stay in .local/.""" +generated files stay in .local/. Also the small helpers the harnesses share +(free ports, offline UUIDs, VarInts, float bits).""" import argparse from collections import Counter @@ -12,11 +13,13 @@ import platform from pathlib import Path, PurePosixPath import re import shutil +import socket import struct import subprocess import sys import tempfile import urllib.request +import uuid import zipfile ROOT = Path(__file__).resolve().parents[1] @@ -61,6 +64,66 @@ def digest(path, algorithm): return hashlib.file_digest(stream, algorithm).hexdigest() +def free_port(): + """A free local TCP port, for a server a harness starts.""" + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +def offline_uuid(name): + """UUIDUtil.createOfflinePlayerUUID: the UUID an offline-mode server gives a player name.""" + digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return uuid.UUID(bytes=bytes(digest)) + + +def varint(value): + """FriendlyByteBuf.writeVarInt: the int's 32 bits, 7 at a time.""" + out = b"" + value &= 0xFFFFFFFF + while True: + b = value & 0x7F + value >>= 7 + out += bytes([b | (0x80 if value else 0)]) + if not value: + return out + + +def parse_varint(data, pos): + """The VarInt at data[pos]: (the position after it, its unsigned value).""" + value = shift = 0 + while True: + b = data[pos] + pos += 1 + value |= (b & 0x7F) << shift + shift += 7 + if not b & 0x80: + return pos, value + + +def fbits(value): + """A float's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">f", value).hex() + + +def dbits(value): + """A double's IEEE 754 bits in hex, as the Java oracles print them.""" + return struct.pack(">d", value).hex() + + +def settled(lines): + """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: + what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more + than once on the way there; the packet by packet order is test_locator_bar_parity's.""" + def waypoint(line): + parts = line.split(" ") + return parts[3] if len(parts) > 3 and parts[2] in ("track", "untrack", "update") else None + last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} + return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] + + def download(url, destination, checksum, algorithm="sha1"): """Never promote an unverified or partial download into the artifact cache.""" destination.parent.mkdir(parents=True, exist_ok=True) diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index b3dae9ef4..a00d3afea 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -107,6 +107,11 @@ address. The script then checks, from both sides, what a guest's game used to ge guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- thrown: a splash potion and an eye of ender the host and the guest each throw fly on both + sides (#1363, #1391); +- sparks: level events' particles on both sides: the host's and the guest's bone meal on wheat + (growth sparks), honeycomb on copper and an axe taking the wax off, and a spawner's + burst when it spawns (#1395, #1401, #1402); - fireball: a fire charge a dispenser shoots onto stone lights a fire both sides see, and the fire goes out on its own within a minute (it ticks: FireBlock.tick on a floor that doesn't burn) @@ -208,7 +213,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'looks', 'leads', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'thrown', 'sparks', 'hud', 'sidebar', 'border', 'particles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth', 'flight', 'ladder', 'boats', 'minecarts', 'frames', 'lightning', 'riding', 'mounts', 'worldspawn', 'beds', 'shield', 'deathmining', 'contacts', 'absorption', 'breath', 'lava', 'levels', 'drops', 'underwater'] class Game: @@ -2612,6 +2617,291 @@ def check_projectiles(host, guest, out): return f'{len(theirs)} identical, fuses (host, guest) {fuses}' +def check_thrown(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + player('command', command='gamemode survival') + for item, kind in (('splash_potion', 'minecraft:splash_potion'), ('ender_eye', 'minecraft:eye_of_ender')): + player('command', command=f'item replace entity @s weapon.mainhand with minecraft:{item}') + player.wait(10) + # Up at 45 degrees, into open sky. + player.raw('look-at', f'{x + 0.5:.2f}', f'{y + 11.6:.2f}', f'{z + 10.5:.2f}') + player.raw('use-item') + seen = {'own': 0, 'other': 0} + for _ in range(10): + player.wait(2) + for side, game in (('own', player), ('other', other)): + if any(p['kind'] == kind for p in game('status')['projectiles']): + seen[side] += 1 + if all(seen.values()): + break + player.shot(out, f'thrown-{label}-{item}') + other.shot(out, f'thrown-{label}-{item}-seen') + player.wait(100) # it lands or drops + result[f'{label} {item}'] = seen + for name, seen in result.items(): + assert all(seen.values()), f'{name}: seen in flight (samples) {result}' + return result + + +def made(game, kind): + """How many `kind` particles `game` has made so far.""" + return game('status').get('particles', {}).get(kind, 0) + + +def sparked(player, other, kinds, act, ticks=20): + """The `kinds` particles each side makes while `act` runs and for up to `ticks` after.""" + before = {(side, k): made(g, k) for side, g in (('own', player), ('other', other)) for k in kinds} + act() + seen = {} + for _ in range(ticks // 2): + player.wait(2) + seen = {f'{side} {k}': made(g, k) - before[(side, k)] + for side, g in (('own', player), ('other', other)) for k in kinds} + if all(seen.values()): + break + return seen + + +def check_sparks(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + at = (x, y, z + 2) + player('command', command='gamemode survival') + try: + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:farmland') + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:wheat') + player('command', command='item replace entity @s weapon.mainhand with minecraft:bone_meal 8') + player.wait(10) + + def click(height): + player.raw('look-at', f'{at[0] + 0.5:.2f}', f'{at[1] + height:.2f}', f'{at[2] + 0.5:.2f}') + player.raw('mouse', 'right', 'click') + result[f'{label} bone meal'] = sparked(player, other, ['happy_villager'], lambda: click(0.1)) + player('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:copper_block') + player('command', command='item replace entity @s weapon.mainhand with minecraft:honeycomb') + player.wait(10) + result[f'{label} wax'] = sparked(player, other, ['wax_on'], lambda: click(0.5)) + player('command', command='item replace entity @s weapon.mainhand with minecraft:iron_axe') + player.wait(10) + result[f'{label} wax off'] = sparked(player, other, ['wax_off'], lambda: click(0.5)) + block = player.raw('block', *at).get('block', '') + result[f'{label} copper'] = block + finally: + player('command', command=f'fill {at[0]} {at[1] - 1} {at[2]} {at[0]} {at[1]} {at[2]} minecraft:air') + player('command', command=f'setblock {at[0]} {at[1] - 1} {at[2]} minecraft:stone') + player('command', command='clear @s') + # A spawner beside the host, at night: its burst when the zombie comes. + x, y, z = spots['host'] + host('command', command='time set midnight') + try: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:spawner{{Delay:20s,SpawnCount:1s,' + 'SpawnData:{entity:{id:"minecraft:zombie",NoAI:1b}}}') + result['spawner'] = sparked(host, guest, ['flame', 'smoke'], lambda: None, ticks=200) + finally: + host('command', command=f'setblock {x} {y} {z + 3} minecraft:air') + host('command', command=f'kill @e[type=minecraft:zombie,x={x},y={y},z={z},distance=..12]') + host('command', command='time set day') + wrong = {k: v for k, v in result.items() if isinstance(v, dict) and not all(n > 0 for n in v.values())} + assert not wrong, f'no particles: {wrong}\n{result}' + return result + + +def hearts(game): + """The player's maximum and current health as its own client holds them.""" + p = game('status')['player'] + return p.get('max_health'), round(p['health'], 1) + + +def check_hud(host, guest, out): + result = {} + for label, player in (('host', host), ('guest', guest)): + player('command', command='gamemode survival') + try: + for maximum in (40, 10): + player('command', command=f'attribute @s minecraft:max_health base set {maximum}') + player.wait(10) + player('command', command='effect give @s minecraft:instant_health 1 10') + seen = None + for _ in range(15): + player.wait(2) + seen = hearts(player) + if seen == (maximum, maximum): + break + result[f'{label} {maximum}'] = seen + player.shot(out, f'hearts-{label}-{maximum}') + finally: + player('command', command='attribute @s minecraft:max_health base reset') + player('command', command='effect give @s minecraft:instant_health 1 10') + # BossBarCommands' new bar starts visible (ServerBossEvent's constructor). + host('command', command='bossbar add lan_e2e:bar "LAN bar"') + try: + host('command', command='bossbar get lan_e2e:bar visible') + host.wait(5) + result['bar'] = [line for line in host.raw('messages', 5)['chat'] if 'lan_e2e:bar' in line or 'LAN bar' in line] + finally: + host('command', command='bossbar remove lan_e2e:bar') + wrong = {k: v for k, v in result.items() if k != 'bar' and v != (int(k.split()[1]),) * 2} + assert not wrong, f'hearts: {wrong}\n{result}' + assert any('currently visible' in line for line in result['bar']), f'bar: {result["bar"]}' + return result + + +def sidebars(host, guest, want, ticks=40): + """Each side's sidebar (objective and scores) once both show `want` (host, guest), or after `ticks`.""" + seen = None + for _ in range(ticks // 2): + host.wait(2) + seen = tuple(g('status').get('sidebar') for g in (host, guest)) + got = tuple(s and (s['objective'], s['scores']) for s in seen) + if got == want: + break + return seen + + +def check_sidebar(host, guest, out): + result = {} + run = lambda *cmds: [host('command', command=c) for c in cmds] + try: + run('scoreboard objectives add audit dummy {"text":"Audit board","color":"aqua"}', + 'scoreboard players set Alpha audit 7', 'scoreboard players set Beta audit 3', + 'scoreboard objectives setdisplay sidebar audit') + both = ('audit', {'Alpha': 7, 'Beta': 3}) + result['shown'] = sidebars(host, guest, (both, both)) + host.shot(out, 'sidebar') + guest.shot(out, 'sidebar') + run('scoreboard players set Alpha audit 12', 'scoreboard players reset Beta audit') + both = ('audit', {'Alpha': 12}) + result['changed'] = sidebars(host, guest, (both, both)) + # The guest's team's sidebar replaces the sidebar for the guest only. + run('team add red', 'team modify red color red', f'team join red {GUEST_NAME}', + 'scoreboard objectives add reds dummy', f'scoreboard players set {GUEST_NAME} reds 5', + 'scoreboard objectives setdisplay sidebar.team.red reds') + result['team'] = sidebars(host, guest, (both, ('reds', {GUEST_NAME: 5}))) + run('scoreboard objectives remove reds', 'scoreboard objectives setdisplay sidebar') + result['cleared'] = sidebars(host, guest, (None, None)) + finally: + run('scoreboard objectives remove audit', 'scoreboard objectives remove reds', 'team remove red') + want = {'shown': (('audit', {'Alpha': 7, 'Beta': 3}),) * 2, 'changed': (('audit', {'Alpha': 12}),) * 2, + 'team': (('audit', {'Alpha': 12}), ('reds', {GUEST_NAME: 5})), 'cleared': (None, None)} + got = {k: tuple(s and (s['objective'], s['scores']) for s in v) for k, v in result.items()} + wrong = {k: v for k, v in got.items() if v != want[k]} + assert not wrong, f'sidebars: {wrong}\n{result}' + return result + + +def check_border(host, guest, out): + spots = apart(host, guest) + result = {} + try: + for label, player, other in (('host', host, guest), ('guest', guest, host)): + x, y, z = spots[label] + # A whole-block centre: the wall's collision box is the border's, rounded out to blocks. + cx, cz = float(x), float(z) + # The other player keeps out of harm outside the border meanwhile. + other('command', command='gamemode creative') + host('command', command=f'fill {x - 3} {y - 1} {z} {x + 4} {y - 1} {z + 10} minecraft:stone') + host('command', command=f'fill {x - 3} {y} {z} {x + 4} {y + 3} {z + 10} minecraft:air') + # A border 10 wide around the player, its wall 5 blocks ahead: both sides know it. + host('command', command=f'worldborder center {cx} {cz}') + host('command', command='worldborder set 10') + seen = None + for _ in range(10): + player.wait(2) + seen = [g('status').get('border') for g in (player, other)] + if all(b and b['size'] == 10 and b['center'] == [cx, cz] for b in seen): + break + result[f'{label} border'] = seen + # Sprint-jumping into the wall: it stops the player at the border. + player('command', command=f'tp @s {cx} {y} {cz} 0 0') + player.wait(10) + player.raw('look-at', f'{cx:.2f}', f'{y + 1.6:.2f}', f'{cz + 20:.2f}') + for k in ('w', 'ctrl', 'space'): + player.raw('key', k, 'down') + player.wait(40) + for k in ('space', 'ctrl', 'w'): + player.raw('key', k, 'up') + player.wait(10) + result[f'{label} reached'] = round(pos_of(player)[2] - cz, 2) + player.shot(out, f'border-{label}') + # Two blocks outside, with no safe zone: the border hurts. + host('command', command='worldborder damage buffer 0') + host('command', command='worldborder damage amount 1') + player('command', command='effect give @s minecraft:instant_health 1 5') + player.wait(20) + player('command', command=f'tp @s {cx} {y} {cz + 7}') + player.wait(5) + before = player('status')['player']['health'] + player.wait(40) + result[f'{label} hurt'] = [before, player('status')['player']['health']] + player('command', command=f'tp @s {cx} {y} {cz}') + player('command', command='effect give @s minecraft:instant_health 1 5') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + other('command', command='gamemode survival') + finally: + guest('command', command='gamemode survival') + host('command', command='gamemode survival') + host('command', command='worldborder damage amount 0.2') + host('command', command='worldborder damage buffer 5') + host('command', command='worldborder center 0 0') + host('command', command='worldborder set 59999968') + wrong = {} + for label in ('host', 'guest'): + x, y, z = spots[label] + known = result[f'{label} border'] + if not all(b and b['size'] == 10 and b['center'] == [x, z] for b in known): + wrong[f'{label} border'] = known + if not 4.0 < result[f'{label} reached'] <= 4.71: + wrong[f'{label} reached'] = result[f'{label} reached'] + before, after = result[f'{label} hurt'] + if not after < before: + wrong[f'{label} hurt'] = result[f'{label} hurt'] + assert not wrong, f'border: {wrong}\n{result}' + return result + + +def check_particles(host, guest, out): + spots = apart(host, guest) + result = {} + for label, player, other in (('host', host, guest), ('guest', guest, host)): + # For the player alone (`@s`), then for every player near. + before = {side: made(g, 'flame') for side, g in (('own', player), ('other', other))} + player('command', command='particle minecraft:flame ~ ~1 ~3 .2 .2 .2 0 60 force @s') + player.wait(10) + result[f'{label} @s'] = {side: made(g, 'flame') - before[side] for side, g in (('own', player), ('other', other))} + player.shot(out, f'flame-{label}') + # No spread: one point, wherever the player stands. + player('command', command='particle minecraft:flame ~ ~1 ~3 0 0 0 0 200 force @s') + player.wait(3) + player.shot(out, f'zero-spread-{label}') + result[f'{label} all'] = sparked(player, other, ['dust'], lambda: player( + 'command', command='particle minecraft:dust{color:[1,0,0],scale:2} ~ ~1 ~3 0 0 0 0 10')) + # A TNT's blast between the players: its burst on both sides. + x, y, z = spots['host'] + host('command', command='gamemode creative') + guest('command', command='gamemode creative') + try: + result['blast'] = sparked(host, guest, ['explosion_emitter'], lambda: host( + 'command', command=f'summon minecraft:tnt {x + 6.5} {y} {z + 4.5} {{fuse:10s}}'), ticks=40) + host.shot(out, 'blast') + finally: + host('command', command='gamemode survival') + guest('command', command='gamemode survival') + host('command', command=f'fill {x - 3} {y - 1} {z - 3} {x + 16} {y - 1} {z + 8} minecraft:stone') + # Without the server thread a guest's command reaches no host player (as `@a` doesn't). + if not SERVER_THREAD: + result['guest all'].pop('other dust') + wrong = {k: v for k, v in result.items() if not k.endswith('@s') and not all(n > 0 for n in v.values())} + wrong.update({k: v for k, v in result.items() if k.endswith('@s') and not (v['own'] >= 30 and v['other'] == 0)}) + assert not wrong, f'particles: {wrong}\n{result}' + return result + + def check_blast(host, guest, out): guest('command', command='gamemode survival') guest('command', command='clear @s') @@ -3945,7 +4235,13 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'lava': check_lava, 'levels': check_levels, 'drops': check_drops, 'underwater': check_underwater, 'looks': check_looks, - 'leads': check_leads} + 'leads': check_leads, + 'thrown': check_thrown, + 'sparks': check_sparks, + 'hud': check_hud, + 'sidebar': check_sidebar, + 'border': check_border, + 'particles': check_particles} def run(ctl, out, resources, checks): diff --git a/tools/parity.py b/tools/parity.py index 6ba4c0d90..4113cc791 100644 --- a/tools/parity.py +++ b/tools/parity.py @@ -27,9 +27,10 @@ Harness probes build into .local/parity-target with release optimisations but without LTO and with 16 codegen units (`PROFILE` below), which builds in seconds instead of minutes. Rust does not let those settings change results: there is no fast-math, and overflow checks stay as in release. Probes built in -the dev profile are optimised too, keeping their overflow checks. Probes the -recorded harnesses need are built in one Cargo run before the harnesses start, -so parallel harnesses don't queue on Cargo's lock. +the dev profile are optimised too, keeping their overflow checks. The probes the +selected harnesses built last time are built before they start, so parallel +harnesses don't queue on Cargo's lock, with each harness's own package and +feature flags so that its Cargo run then finds them fresh. """ import argparse @@ -210,18 +211,42 @@ def artifact_path(kind, name, profile): return TARGET / directory / ("examples" if kind == "example" else "") / name +SELECTION_FLAGS = {"-p", "--package", "-F", "--features"} # followed by a value +SELECTION_SWITCHES = {"--workspace", "--all", "--all-features", "--no-default-features"} + + def artifacts_of(arguments): - """The [kind, name, profile] targets a cargo build/run command line names.""" + """The [kind, name, profile, selection, examples] targets a cargo build/run command line names. + + kind is example, bin, or examples/bins (every one, name ""). selection is the command's package and feature + flags, and examples whether the command builds any example (which turns on dev-dependencies): together they + decide how Cargo unifies features, so the probe prebuild must repeat them exactly. A `--workspace` build of + the same example gives its dependencies other features, and the harness's own `-p` build then compiles + everything again.""" arguments = arguments[:arguments.index("--")] if "--" in arguments else arguments profile = "release" if "--release" in arguments else "dev" - if "--profile" in arguments: - profile = arguments[arguments.index("--profile") + 1] + selection = [] found = [] - for flag, kind in (("--example", "example"), ("--bin", "bin")): - for index, argument in enumerate(arguments[:-1]): - if argument == flag: - found.append([kind, arguments[index + 1], profile]) - return found + index = 1 + while index < len(arguments): + argument = arguments[index] + flag, _, value = argument.partition("=") + if flag in SELECTION_FLAGS | {"--profile", "--example", "--bin"} and not value and index + 1 < len(arguments): + value = arguments[index + 1] + index += 1 + if flag == "--profile": + profile = value + elif flag in SELECTION_FLAGS: + selection += ["-p" if flag == "--package" else "--features" if flag == "-F" else flag, value] + elif flag in SELECTION_SWITCHES: + selection.append("--workspace" if flag == "--all" else flag) + elif flag in ("--example", "--bin"): + found.append([flag[2:], value]) + elif flag in ("--examples", "--bins"): + found.append([flag[2:], ""]) + index += 1 + examples = any(kind in ("example", "examples") for kind, _ in found) + return [[kind, name, profile, selection, examples] for kind, name in found] RUST_PATH = re.compile(r"(?d', v).hex() + import lab def settings(): @@ -54,11 +50,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def sounds(self, value): - mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], dbits(value['mood'][3])) - self.add('sounds', value['loop'] or '-', mood, *[f'{s},{dbits(c)}' for s, c in value['additions']]) + mood = '-' if value['mood'] is None else '{},{},{},{}'.format(value['mood'][0], value['mood'][1], value['mood'][2], lab.dbits(value['mood'][3])) + self.add('sounds', value['loop'] or '-', mood, *[f'{s},{lab.dbits(c)}' for s, c in value['additions']]) def player(self, at=(0.5, 64.0, 0.5), eye=1.62, water=0, spectator=0, removed=0, mode=0, height=1.8, columns=()): - self.add('player', *map(dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), + self.add('player', *map(lab.dbits, at), h.bits(eye), water, spectator, removed, mode, h.bits(height), *[f'{x},{y},{z},{d}' for x, y, z, d in columns]) def tick(self, n=1): diff --git a/tools/test_auto_jump_parity.py b/tools/test_auto_jump_parity.py index da0c16b7b..3e9da7d5a 100644 --- a/tools/test_auto_jump_parity.py +++ b/tools/test_auto_jump_parity.py @@ -8,11 +8,9 @@ overhangs approached from every angle with varied speeds, input vectors, sizes, jump boost and the canAutoJump preconditions.""" import json import math -import os from pathlib import Path import platform import random -import struct import subprocess try: @@ -23,14 +21,6 @@ except ImportError: import test_native_client as client -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - BLOCKS = [ ('stone', {}), ('stone', {}), ('stone', {}), ('stone_slab', {'type': 'bottom'}), ('stone_slab', {'type': 'top'}), ('stone_slab', {'type': 'double'}), @@ -64,12 +54,12 @@ DIMS = [(0.6, 1.8), (0.6, 1.8), (0.6, 1.5), (0.6, 0.6), (0.3, 0.9), (1.2, 3.6), def player(rng, x, y, z, yaw): w, h = rng.choice(DIMS) - return dict(pos=[dbits(x), dbits(y), dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, - yr=fbits(yaw), xr=fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), - speed=fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), - move=[fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), + return dict(pos=[lab.dbits(x), lab.dbits(y), lab.dbits(z)], ground=rng.random() < 0.9, shift=rng.random() < 0.08, + yr=lab.fbits(yaw), xr=lab.fbits(rng.choice([0.0, 30.0, -45.0, 90.0, rng.uniform(-90, 90)])), + speed=lab.fbits(rng.choice([0.1, 0.13000001, 0.03, 0.0, 0.2, rng.uniform(0, 0.3)])), + move=[lab.fbits(v) for v in rng.choice([(0.0, 1.0), (0.0, 1.0), (1.0, 0.0), (-1.0, 0.0), (0.70710677, 0.70710677), (0.0, -1.0), (0.0, 0.0), (0.3, 0.3)])], - width=fbits(w), height=fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), + width=lab.fbits(w), height=lab.fbits(h), boost=rng.choice([None] * 6 + [0, 1, 4, 255]), enabled=rng.random() < 0.93, time=rng.choice([0] * 12 + [1, -3, 2])) @@ -86,18 +76,18 @@ def cases(rng): x = ox + 0.5 - dx * 1.1 z = oz + 0.5 - dz * 1.1 p = player(rng, x, float(oy), z, yaw) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8), xr=fbits(0.0)) - yield dict(blocks=blocks, player=p, xa=fbits(dx * step), za=fbits(dz * step)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8), xr=lab.fbits(0.0)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(dx * step), za=lab.fbits(dz * step)) # Ceilings above the player and above the step. for ceiling in range(2, 6): for step_height in (0, 1): blocks = [[ox, oy + step_height, oz, 'minecraft:stone', {}], [ox - 1, oy + ceiling, oz, 'minecraft:stone', {}], [ox, oy + ceiling + step_height, oz, 'minecraft:stone_slab', {'type': 'top'}]] p = player(rng, ox - 0.5, float(oy), oz + 0.5, -90.0) - p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[fbits(0.0), fbits(1.0)], - width=fbits(0.6), height=fbits(1.8)) - yield dict(blocks=blocks, player=p, xa=fbits(0.2), za=fbits(0.0)) + p.update(ground=True, shift=False, enabled=True, time=0, boost=None, move=[lab.fbits(0.0), lab.fbits(1.0)], + width=lab.fbits(0.6), height=lab.fbits(1.8)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(0.2), za=lab.fbits(0.0)) for _ in range(9000): blocks = placed(rng, rng.choice([1, 2, 4, 8, 16, 30])) x = ox + rng.uniform(-2, 3) @@ -108,7 +98,7 @@ def cases(rng): move = rng.choice([0.0, 0.0, 0.01, 0.1, 0.215, 0.3, rng.uniform(0, 0.4)]) angle = rng.uniform(0, 6.283) - yield dict(blocks=blocks, player=p, xa=fbits(math.cos(angle) * move), za=fbits(math.sin(angle) * move)) + yield dict(blocks=blocks, player=p, xa=lab.fbits(math.cos(angle) * move), za=lab.fbits(math.sin(angle) * move)) def main(): diff --git a/tools/test_camera_parity.py b/tools/test_camera_parity.py index 3cd0e403d..bde9ea897 100644 --- a/tools/test_camera_parity.py +++ b/tools/test_camera_parity.py @@ -20,14 +20,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -39,8 +31,8 @@ TICKS = [0, 1, 5, 10, 19, 20, 21, 72000, -5, 3] def fov_fields(rng): use = rng.choice([None, None, ['bow', rng.choice(TICKS)], ['spyglass', rng.choice(TICKS)], ['other', rng.choice(TICKS)]]) - return dict(flying=rng.random() < 0.3, ws=fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), - speed=dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) + return dict(flying=rng.random() < 0.3, ws=lab.fbits(rng.choice(WALK + [rng.uniform(-0.3, 0.3)])), + speed=lab.dbits(rng.choice(SPEED + [rng.uniform(0, 2)])), use=use) def fov_cases(rng): @@ -50,9 +42,9 @@ def fov_cases(rng): for use in [None, ['bow', 0], ['bow', 7], ['bow', 20], ['bow', 40], ['spyglass', 2], ['other', 5]]: for fp in (False, True): for scale in (0.0, 0.5, 1.0): - yield dict(t='fov', flying=flying, ws=fbits(ws), speed=dbits(speed), use=use, fp=fp, scale=fbits(scale)) + yield dict(t='fov', flying=flying, ws=lab.fbits(ws), speed=lab.dbits(speed), use=use, fp=fp, scale=lab.fbits(scale)) for _ in range(3000): - yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=fbits(rng.choice([0.0, 1.0, rng.random()]))) + yield dict(t='fov', **fov_fields(rng), fp=rng.random() < 0.6, scale=lab.fbits(rng.choice([0.0, 1.0, rng.random()]))) FULL = [[0, 0, 0, 1, 1, 1]] @@ -65,7 +57,7 @@ def world(rng, center): cx, cy, cz = center for _ in range(rng.choice([0, 3, 10, 40, 120])): p = (cx + rng.randint(-6, 6), cy + rng.randint(-3, 5), cz + rng.randint(-6, 6)) - cells[f'{p[0]} {p[1]} {p[2]}'] = [[dbits(v) for v in box] for box in rng.choice(SHAPES)] + cells[f'{p[0]} {p[1]} {p[2]}'] = [[lab.dbits(v) for v in box] for box in rng.choice(SHAPES)] return cells @@ -81,22 +73,22 @@ def entity_state(rng, center): prev = [p - rng.choice([0, 0, 0.1, 0.3, 1.0, rng.uniform(-1, 1)]) for p in pos] kind = 'player' if rng.random() < 0.85 else 'marker' xr, yr = angle(rng), angle(rng) - s = dict(kind=kind, pos=[dbits(v) for v in pos], prev=[dbits(v) for v in prev], xr=fbits(xr), yr=fbits(yr), - xro=fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=fbits(rng.choice([yr, yr + 10, angle(rng)])), - eye=fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) + s = dict(kind=kind, pos=[lab.dbits(v) for v in pos], prev=[lab.dbits(v) for v in prev], xr=lab.fbits(xr), yr=lab.fbits(yr), + xro=lab.fbits(rng.choice([xr, xr - 5, angle(rng)])), yro=lab.fbits(rng.choice([yr, yr + 10, angle(rng)])), + eye=lab.fbits(rng.choice([1.62, 1.27, 0.4, 0.2, 0.81, 3.24, rng.uniform(0, 4)]))) s.update(fov_fields(rng)) - s.update(scale_attr=dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), - dist=dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), + s.update(scale_attr=lab.dbits(rng.choice([1.0, 1.0, 0.5, 2.0, 0.0625, 16.0, rng.uniform(0.0625, 3)])), + dist=lab.dbits(rng.choice([4.0, 4.0, 0.0, 1.0, 10.0, 32.0, rng.uniform(0, 32)])), sleeping=rng.choice([None] * 6 + [[None], [0], [1], [2], [3]]), dead=rng.choice([None] * 6 + [0, 1, 5, 19, 20, 25]), - mount=rng.choice([None] * 4 + [[dbits(rng.choice([1.0, 2.0, 0.5])), dbits(rng.choice([4.0, 8.0, 1.0]))]])) + mount=rng.choice([None] * 4 + [[lab.dbits(rng.choice([1.0, 2.0, 0.5])), lab.dbits(rng.choice([4.0, 8.0, 1.0]))]])) return s def window(rng): """Window size and Camera.depthFar for the world and hand projections.""" w, h = rng.choice([(1600, 1000), (854, 480), (1920, 1080), (800, 1200), (1, 1), (rng.randint(1, 4000), rng.randint(1, 3000))]) - return [fbits(w), fbits(h), fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] + return [lab.fbits(w), lab.fbits(h), lab.fbits(rng.choice([768.0, 128.0, 2048.0, 4096.0, rng.uniform(32, 4096)]))] def camera_cases(rng): @@ -113,11 +105,11 @@ def camera_cases(rng): ops.append(['tick']) elif kind == 'frame': pt = rng.choice([0.0, 1.0, 0.5, 0.25, 0.999, rng.random()]) - ops.append(['frame', fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) + ops.append(['frame', lab.fbits(pt), rng.choice([0, 0, 0, 1, 2, 3]), rng.random() < 0.05] + window(rng)) else: ops.append(['type', rng.randrange(3)]) yield dict(t='camera', fov=rng.choice([70, 30, 110, 90, rng.randint(30, 110)]), - effect=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), + effect=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), type=rng.choice([0, 1, 1, 2]), cells=world(rng, center), ops=ops) # The hand's projection at FOV 30, 70 and 110 while walking, sprinting, under # speed, drawing a bow, dying and in fluids: GameRenderer.render3dHud uses @@ -127,13 +119,13 @@ def camera_cases(rng): for use in (None, ['bow', 10]): for dead in (None, 5): for fluid in (0, 1, 2): - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(0.0), yr=fbits(0.0), xro=fbits(0.0), yro=fbits(0.0), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(speed), use=use, scale_attr=dbits(1.0), dist=dbits(4.0), + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(0.0), yr=lab.fbits(0.0), xro=lab.fbits(0.0), yro=lab.fbits(0.0), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(speed), use=use, scale_attr=lab.dbits(1.0), dist=lab.dbits(4.0), sleeping=None, dead=dead, mount=None) - ops = [['entity', s]] + [['tick']] * 8 + [['frame', fbits(pt), fluid, False, fbits(1600.0), fbits(1000.0), fbits(768.0)] + ops = [['entity', s]] + [['tick']] * 8 + [['frame', lab.fbits(pt), fluid, False, lab.fbits(1600.0), lab.fbits(1000.0), lab.fbits(768.0)] for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=fov, effect=dbits(1.0), type=0, cells={}, ops=ops) + yield dict(t='camera', fov=fov, effect=lab.dbits(1.0), type=0, cells={}, ops=ops) # A walled-in third-person camera stepping through every distance bound. for dist in [0.0, 0.5, 1.0, 2.0, 4.0, 8.0, 32.0]: for wall in range(0, 6): @@ -141,28 +133,28 @@ def camera_cases(rng): cells = {} for dx in range(-6, 7): for dy in range(62, 68): - cells[f'{dx} {dy} {-wall - 1}'] = [[dbits(v) for v in box] for box in FULL] - cells[f'{dx} {dy} {wall + 1}'] = [[dbits(v) for v in box] for box in FULL] - s = dict(kind='player', pos=[dbits(0.5), dbits(64.0), dbits(0.5)], prev=[dbits(0.5), dbits(64.0), dbits(0.5)], - xr=fbits(15.0), yr=fbits(yaw), xro=fbits(15.0), yro=fbits(yaw), eye=fbits(1.62), flying=False, - ws=fbits(0.1), speed=dbits(f32(0.1)), use=None, scale_attr=dbits(1.0), dist=dbits(dist), + cells[f'{dx} {dy} {-wall - 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + cells[f'{dx} {dy} {wall + 1}'] = [[lab.dbits(v) for v in box] for box in FULL] + s = dict(kind='player', pos=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], prev=[lab.dbits(0.5), lab.dbits(64.0), lab.dbits(0.5)], + xr=lab.fbits(15.0), yr=lab.fbits(yaw), xro=lab.fbits(15.0), yro=lab.fbits(yaw), eye=lab.fbits(1.62), flying=False, + ws=lab.fbits(0.1), speed=lab.dbits(f32(0.1)), use=None, scale_attr=lab.dbits(1.0), dist=lab.dbits(dist), sleeping=None, dead=None, mount=None) - ops = [['entity', s]] + [['tick']] * 6 + [['frame', fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] - yield dict(t='camera', fov=70, effect=dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) + ops = [['entity', s]] + [['tick']] * 6 + [['frame', lab.fbits(pt), 0, False] + window(rng) for pt in (0.0, 0.5, 1.0)] + yield dict(t='camera', fov=70, effect=lab.dbits(1.0), type=1 + (wall % 2), cells=cells, ops=ops) def bob_cases(rng): for n in range(6000): living = None if rng.random() < 0.8: - living = dict(hurt=fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), - duration=rng.choice([10, 10, 0, 5, 20]), dir=fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), - death=rng.choice([None, None, None, fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) + living = dict(hurt=lab.fbits(rng.choice([-1.0, -0.5, 0.0, 10.0, 9.5, 5.25, 1.0, rng.uniform(-2, 11)])), + duration=rng.choice([10, 10, 0, 5, 20]), dir=lab.fbits(rng.choice([0.0, 90.0, -45.0, 180.0, rng.uniform(-360, 360)])), + death=rng.choice([None, None, None, lab.fbits(rng.choice([0.0, 0.5, 19.5, 20.0, 25.0, rng.uniform(0, 30)]))])) player = None if rng.random() < 0.8: - player = [fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), - fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] - yield dict(t='bob', living=living, player=player, tilt=dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), + player = [lab.fbits(rng.choice([0.0, -0.3, -1.7, -100.25, rng.uniform(-1000, 0)])), + lab.fbits(rng.choice([0.0, 0.1, 0.05, 0.0999, rng.uniform(0, 0.1)]))] + yield dict(t='bob', living=living, player=player, tilt=lab.dbits(rng.choice([1.0, 0.0, 0.5, rng.random()])), view=rng.random() < 0.8) @@ -174,12 +166,12 @@ def avatar_cases(rng): if kind == 'tick': ops.append(['tick']) elif kind == 'move': - ops.append(['move', fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) + ops.append(['move', lab.fbits(rng.choice([0.0, 0.2158, -0.1, rng.uniform(-1, 1)])), lab.fbits(rng.choice([0.0, 0.2806, rng.uniform(-1, 1)]))]) elif kind == 'bob': v = [rng.choice([0.0, 0.05, -0.2, rng.uniform(-0.5, 0.5)]), rng.uniform(-1, 1), rng.choice([0.0, 0.08, rng.uniform(-0.5, 0.5)])] - ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [dbits(x) for x in v]]) + ops.append(['bob', rng.random() < 0.7, rng.random() < 0.1, rng.random() < 0.1, [lab.dbits(x) for x in v]]) elif kind == 'frame': - ops.append(['frame', fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) + ops.append(['frame', lab.fbits(rng.choice([0.0, 1.0, 0.5, rng.random()]))]) else: ops.append(['reset']) yield dict(t='avatar', ops=ops) diff --git a/tools/test_datafix_parity.py b/tools/test_datafix_parity.py index a2d11009c..4c189983f 100644 --- a/tools/test_datafix_parity.py +++ b/tools/test_datafix_parity.py @@ -33,6 +33,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import anvil_dump # noqa: E402 +import parity_shard # noqa: E402 ROOT = Path(__file__).resolve().parent.parent LOCAL = ROOT / '.local' / 'datafix' @@ -63,7 +64,7 @@ def java_classpath(): import test_model_baking_parity as baking lock, jars, _ = base.verify_artifacts() libraries = baking.client_libraries() - build = LOCAL / 'build' / os.environ.get('PARITY_SHARD', 'all').replace('/', '-') # shards compile apart + build = LOCAL / 'build' / parity_shard.label() # shards compile apart build.mkdir(parents=True, exist_ok=True) classes, dependencies, _ = harness.compile_oracle(build, 'VanillaDataFixOracle', jars, libraries, lock['minecraft']['java_major']) @@ -78,15 +79,6 @@ def build_rust(): return Path(meta['target_directory']) / 'release' / 'examples' / 'datafix_world' -def shard(items): - """This run's share of items when tools/parity.py runs the harness in parts (PARITY_SHARD=i/n).""" - spec = os.environ.get('PARITY_SHARD') - if not spec: - return items - index, count = map(int, spec.split('/')) - return items[index - 1::count] - - def run_vanilla(classpath, world, out, target=None): # The oracle replaces OUT itself: left in place, an unchanged run's outputs can be reused. log = out.parent / (out.name + '.log') @@ -226,7 +218,7 @@ def main(): band = args.band if band and not args.versions: # worlds in the layout of before 1.16, saved before the target worlds = [w for w in worlds if json.loads((world_path(w) / 'datafix-source.json').read_text())['data_version'] < band] - versions = shard(args.versions or worlds) + versions = parity_shard.shard(args.versions or worlds) classpath = java_classpath() binary = None if args.vanilla_only else Path(args.binary) if args.binary else build_rust() total = 0 diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 22677bf07..07d61f3d5 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -68,10 +68,12 @@ import zlib try: from . import lab, oracle_harness as oh, test_rust_parity as base + from .lab import free_port # the other server harnesses import it from here except ImportError: import lab import oracle_harness as oh import test_rust_parity as base + from lab import free_port NAME = 'dedicated-server-parity' SEED = 12345 @@ -89,12 +91,6 @@ PROPERTIES = { } -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def icon_png(): """A 64x64 RGBA PNG (server-icon.png).""" rows = b''.join(b'\0' + b''.join(bytes((x * 4, y * 4, (x ^ y) * 4, 255)) for x in range(64)) for y in range(64)) diff --git a/tools/test_first_person_parity.py b/tools/test_first_person_parity.py index 476d2cc52..fcb1206ec 100644 --- a/tools/test_first_person_parity.py +++ b/tools/test_first_person_parity.py @@ -18,14 +18,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def f32(v): return struct.unpack('>f', struct.pack('>f', v))[0] @@ -52,15 +44,15 @@ def step(hit=('miss',), ac=0, uc=0, ad=False, ud=False, busy=False, using=False, """rot: the player's (xRot, yRot) from this step on (LocalPlayer.applyInput's hand sway).""" return dict(hit=list(hit), ac=ac, uc=uc, ad=ad, ud=ud, busy=busy, using=using, uses=uses or dict(entity='pass', block='pass', item='pass'), shrink=shrink, set=set, - rot=None if rot is None else [fbits(rot[0]), fbits(rot[1])]) + rot=None if rot is None else [lab.fbits(rot[0]), lab.fbits(rot[1])]) def case(steps, creative=False, main=None, off=None, blocks=None, haste=None, fatigue=None): return dict(creative=creative, main=main, off=off, haste=haste, fatigue=fatigue, blocks=[[*p, b] for p, b in (blocks or {}).items()], steps=steps, - rust=dict(blocks={k: [fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, - tools={k: [fbits(v[0]), v[1]] for k, v in TOOLS.items()}, - attack_speed={k: dbits(v) for k, v in SPEEDS.items()})) + rust=dict(blocks={k: [lab.fbits(v[0]), v[1]] for k, v in BLOCKS.items()}, + tools={k: [lab.fbits(v[0]), v[1]] for k, v in TOOLS.items()}, + attack_speed={k: lab.dbits(v) for k, v in SPEEDS.items()})) def block_hit(pos, face=1): diff --git a/tools/test_friends.py b/tools/test_friends.py index 3daeb28e7..8fa1a4fee 100644 --- a/tools/test_friends.py +++ b/tools/test_friends.py @@ -72,12 +72,6 @@ def wait_for(endpoint, line, predicate, timeout=60, what=None): raise AssertionError(f'timed out waiting for {what or line}: {last}') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def health(relay_url): with urllib.request.urlopen(f'http://{relay_url}/health', timeout=5) as r: return json.loads(r.read()) @@ -204,7 +198,7 @@ def leave(host, guest, name): def start_relay(args, work): """A relay on a free local port, as anyone would run their own.""" - port = free_port() + port = lab.free_port() url = f'127.0.0.1:{port}' log = (work / 'relay.log').open('w+') process = subprocess.Popen([str(args.relay.resolve())], env=dict(os.environ, PORT=str(port)), diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index 101b3f238..f5f5e94a3 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -6,9 +6,7 @@ and absolute motion, sensitivity curve, cinematic smoothing, inversion, scroll accumulation and discrete scrolling), Entity.turn and ToggleKeyMapping, all driven with identical synthetic input and time sequences.""" import json -import math import random -import struct try: from . import lab, oracle_harness as harness @@ -16,14 +14,6 @@ except ImportError: import lab, oracle_harness as harness -def fbits(v): - return struct.pack('>f', v).hex() - - -def dbits(v): - return struct.pack('>d', v).hex() - - def timer_cases(rng): for n in range(700): tps = rng.choice([20.0, 20.0, 10.0, 60.0, 1.0, 144.0]) @@ -38,12 +28,12 @@ def timer_cases(rng): now -= rng.randrange(0, 30) if kind == 'adv': mspt = rng.choice([None, None, None, 50.0, 25.0, 100.0, 500.0, 1000.0, 0.5, 5.0, 0.1]) - ops.append(['adv', now, None if mspt is None else fbits(mspt)]) + ops.append(['adv', now, None if mspt is None else lab.fbits(mspt)]) elif kind == 'real': ops.append(['real', now]) else: ops.append([kind, rng.random() < 0.5]) - yield dict(t='timer', tps=fbits(tps), start=start, ops=ops) + yield dict(t='timer', tps=lab.fbits(tps), start=start, ops=ops) def rate_cases(rng): @@ -55,7 +45,7 @@ def rate_cases(rng): kind = rng.choice(['rate', 'freeze', 'step', 'stopstep', 'sprint', 'check', 'check', 'check', 'end', 'stopsprint', 'tick', 'tick', 'tick']) if kind == 'rate': - ops.append(['rate', fbits(rng.choice(rates))]) + ops.append(['rate', lab.fbits(rng.choice(rates))]) elif kind == 'freeze': ops.append(['freeze', rng.random() < 0.5]) elif kind == 'step': @@ -78,7 +68,7 @@ def scale_cases(rng): for uni in (False, True): sw, sh = rng.choice([(w, h), (max(w // 2, 1), max(h // 2, 1)), (w + 1, h + 3)]) yield dict(t='scale', w=w, h=h, max=maxs, uni=uni, sw=sw, sh=sh, - x=dbits(rng.uniform(0, w)), y=dbits(rng.uniform(0, h))) + x=lab.dbits(rng.uniform(0, w)), y=lab.dbits(rng.uniform(0, h))) def limit_cases(rng): @@ -103,13 +93,13 @@ def mouse_cases(rng): if kind == 'move': x, y = rng.uniform(0, 1920), rng.uniform(0, 1080) big = rng.choice([1, 1, 1, 50, 5000]) - ops.append(['move', dbits(x), dbits(y), dbits(rng.uniform(-30, 30) * big), dbits(rng.uniform(-30, 30) * big)]) + ops.append(['move', lab.dbits(x), lab.dbits(y), lab.dbits(rng.uniform(-30, 30) * big), lab.dbits(rng.uniform(-30, 30) * big)]) elif kind == 'frame': time += rng.choice([0.0, 0.001, 0.0069, 0.016, 0.0167, 0.05, 0.5, 2.0]) - ops.append(['frame', dbits(time)]) + ops.append(['frame', lab.dbits(time)]) else: ops.append(['ignore']) - yield dict(t='mouse', sens=dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, + yield dict(t='mouse', sens=lab.dbits(sens), smooth=rng.random() < 0.4, scoping=rng.random() < 0.3, ix=rng.random() < 0.3, iy=rng.random() < 0.3, grabbed=rng.random() < 0.85, active=rng.random() < 0.9, ops=ops) @@ -119,14 +109,14 @@ def scroll_cases(rng): for _ in range(rng.randrange(1, 40)): x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)]) y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)]) - ops.append([dbits(x), dbits(y)]) - case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), + ops.append([lab.dbits(x), lab.dbits(y)]) + case = dict(t='scroll', discrete=rng.random() < 0.4, sens=lab.dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), slot=rng.randrange(9), ops=ops) yield case yield dict(case, spectator=True) # Bounds, recovery from each bound, fractional accumulation, and horizontal-only input. - yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True, - ops=[[dbits(x), dbits(y)] for x, y in + yield dict(t='scroll', discrete=False, sens=lab.dbits(1.0), slot=4, spectator=True, + ops=[[lab.dbits(x), lab.dbits(y)] for x, y in [(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7), (0, -.4), (0, -.7), (5, 0), (-5, 0)]]) diff --git a/tools/test_save_roundtrip_parity.py b/tools/test_save_roundtrip_parity.py index 72bea8845..bd8b07a29 100644 --- a/tools/test_save_roundtrip_parity.py +++ b/tools/test_save_roundtrip_parity.py @@ -109,15 +109,9 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user # ---------------------------------------------------------------- vanilla server -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - class Vanilla: def __init__(self, directory, port=None, world='world', extra=None): - port = port or free_port() + port = port or lab.free_port() directory.mkdir(parents=True, exist_ok=True) (directory / 'eula.txt').write_text('eula=true\n') props = { diff --git a/tools/test_secure_chat_parity.py b/tools/test_secure_chat_parity.py index ed408efa3..c6c76a892 100644 --- a/tools/test_secure_chat_parity.py +++ b/tools/test_secure_chat_parity.py @@ -41,12 +41,12 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer try: from . import lab, oracle_harness as oh, test_rust_parity as base - from .test_dedicated_server_parity import Server, free_port + from .test_dedicated_server_parity import Server except ImportError: import lab import oracle_harness as oh import test_rust_parity as base - from test_dedicated_server_parity import Server, free_port + from test_dedicated_server_parity import Server NAME = 'secure-chat-parity' SCENARIOS = { @@ -153,20 +153,10 @@ def dashed(u): return f'{u[:8]}-{u[8:12]}-{u[12:16]}-{u[16:20]}-{u[20:]}' -def varint(n): - out = b'' - while True: - b = n & 0x7F - n >>= 7 - out += bytes([b | (0x80 if n else 0)]) - if not n: - return out - - def status(port): """The status response's JSON (ServerStatus).""" def packet(body): - return varint(len(body)) + body + return lab.varint(len(body)) + body def read_varint(s): value = 0 @@ -177,7 +167,7 @@ def status(port): return value with socket.create_connection(('127.0.0.1', port), timeout=10) as s: host = b'127.0.0.1' - s.sendall(packet(b'\x00' + varint(777) + varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) + s.sendall(packet(b'\x00' + lab.varint(777) + lab.varint(len(host)) + host + port.to_bytes(2, 'big') + b'\x01')) s.sendall(packet(b'\x00')) length = read_varint(s) data = b'' @@ -212,7 +202,7 @@ def chat_lines(lines): def run_side(label, scenario, command, directory, client): - port = free_port() + port = lab.free_port() shutil.rmtree(directory, ignore_errors=True) directory.mkdir(parents=True) props = dict(PROPERTIES, **SCENARIOS[scenario], **{'server-port': str(port)}) diff --git a/tools/test_server_dimension_players_parity.py b/tools/test_server_dimension_players_parity.py index 8453d14af..b1efc4378 100644 --- a/tools/test_server_dimension_players_parity.py +++ b/tools/test_server_dimension_players_parity.py @@ -96,17 +96,6 @@ def run_side(label, server_command, client_command, build, world): SHOWN = ('add', 'remove', 'respawn', 'track', 'untrack', 'update') -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def shown(lines): """Each player's adds, removes, respawns and waypoints (as the step leaves them), step by step; sorted within a step (the packets of one step may leave in another order within the tick).""" @@ -115,7 +104,7 @@ def shown(lines): parts = line.split(' ', 2) if len(parts) == 3 and parts[2].split(' ')[0] in SHOWN: steps.setdefault((parts[0], parts[1]), []).append(line) - return [l for key in steps for l in sorted(settled(steps[key]))] + return [l for key in steps for l in sorted(lab.settled(steps[key]))] def main(): diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py index 71416223b..cad8782cc 100644 --- a/tools/test_server_player_targets_parity.py +++ b/tools/test_server_player_targets_parity.py @@ -15,7 +15,6 @@ in sorted order (the packets of one step may leave in another order within the t waypoints as each step leaves them (one manager per level: a player in another level is untracked). What a death does besides its messages is left to its own harness. """ -import hashlib import os from pathlib import Path import platform @@ -23,7 +22,6 @@ import shutil import subprocess import sys import time -import uuid as uuidlib try: from . import lab, test_rust_parity as base @@ -39,20 +37,12 @@ NAME = 'server-player-targets-parity' NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld' -def offline_uuid(name): - """UUIDUtil.createOfflinePlayerUUID.""" - digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return str(uuidlib.UUID(bytes=bytes(digest))) - - # (label, what the console does, what the players do). SCRIPT = [ ('console-give', ['give Bob minecraft:diamond 3'], []), ('console-give-all', ['give @a minecraft:apple'], []), ('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']), - ('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []), + ('console-give-uuid', [f'give {lab.offline_uuid("Bob")} minecraft:iron_ingot'], []), ('console-give-nearest', ['give @p minecraft:emerald'], []), ('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']), ('console-gamemode', ['gamemode survival Bob'], []), @@ -83,17 +73,6 @@ DEATH_STEP = 'step=console-kill' STEP_SECONDS = 2.5 -def settled(lines): - """One player's lines of one step, in order, with the waypoint packets reduced to the last for each waypoint: - what the locator bar shows once the step is over. Arriving in a level, vanilla sends the same waypoint more - than once on the way there; the packet by packet order is test_locator_bar_parity's.""" - def waypoint(line): - parts = line.split(' ') - return parts[3] if len(parts) > 3 and parts[2] in ('track', 'untrack', 'update') else None - last = {waypoint(l): i for i, l in enumerate(lines) if waypoint(l)} - return [l for i, l in enumerate(lines) if not waypoint(l) or last[waypoint(l)] == i] - - def run_side(label, server_command, client_command, build, world): directory = build / label port = server_dir(directory, world) @@ -151,7 +130,7 @@ def run_side(label, server_command, client_command, build, world): steps.setdefault((who, step), []).append(line) order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) - return [l for k in keys for l in sorted(settled(steps[k]))], errors + return [l for k in keys for l in sorted(lab.settled(steps[k]))], errors def main(): diff --git a/tools/test_sound_engine_parity.py b/tools/test_sound_engine_parity.py index 36095542c..8eb02a7fe 100644 --- a/tools/test_sound_engine_parity.py +++ b/tools/test_sound_engine_parity.py @@ -18,14 +18,10 @@ import math import random try: - from . import audio_harness as h + from . import audio_harness as h, lab except ImportError: import audio_harness as h - - -def dbits(v): - import struct - return struct.pack('>d', v).hex() + import lab class Script: @@ -37,11 +33,11 @@ class Script: self.lines.append(' '.join(map(str, parts))) def play(self, name, event, source=4, volume=1.0, pitch=1.0, at=(0.0, 0.0, 0.0), looping=0, delay=0, linear=True, relative=0, seed=0, kind='simple'): - self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(dbits, at), looping, delay, + self.add('play', name, kind, event, source, h.bits(volume), h.bits(pitch), *map(lab.dbits, at), looping, delay, 'linear' if linear else 'none', relative, seed) def cart(self, name, at, delta, removed=0): - self.add('cart', name, *map(dbits, at), *map(dbits, delta), removed) + self.add('cart', name, *map(lab.dbits, at), *map(lab.dbits, delta), removed) def tick(self, n=1, paused=0): for _ in range(n): diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py index 9b495c3dc..4247a0ee7 100644 --- a/tools/test_world_spawn_parity.py +++ b/tools/test_world_spawn_parity.py @@ -29,6 +29,10 @@ Seeds: the player report's seed (1891623539983467248: Horizon spawned at -48 -48, vanilla at 152 145), the chunk generation harness's seeds and --random seeds from a fixed generator. +tools/parity.py runs it in PARITY_SHARDS parts, each creating the worlds of +every PARITY_SHARDS-th seed: each seed is a vanilla and a Horizon server start, +~15 s, and 60 seeds in one run were the longest harness (~25 min). + usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only] """ import argparse @@ -43,16 +47,18 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path try: - from . import anvil_dump, lab, oracle_harness as oh, test_rust_parity as base + from . import anvil_dump, lab, oracle_harness as oh, parity_shard, test_rust_parity as base from .test_dedicated_server_parity import Server, free_port except ImportError: import anvil_dump import lab import oracle_harness as oh + import parity_shard import test_rust_parity as base from test_dedicated_server_parity import Server, free_port NAME = 'world-spawn-parity' +PARITY_SHARDS = 4 REPORT = 1891623539983467248 SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0] RESOURCES = lab.RESOURCES @@ -107,7 +113,7 @@ def main(): parser.add_argument('--seed', type=int, action='append', help='only these seeds (repeatable)') args = parser.parse_args() lock, jars, libraries = base.verify_artifacts() - build = lab.LOCAL / NAME + build = lab.LOCAL / NAME / parity_shard.label() # shards run at once build.mkdir(parents=True, exist_ok=True) dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) classes = build / 'classes' @@ -116,7 +122,7 @@ def main(): '-d', classes, lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java'], build, 'compile-java') oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-world', '--example', 'spawn_origin'], build, 'compile-probe') - all_seeds = args.seed or seeds(args.random) + all_seeds = parity_shard.shard(args.seed or seeds(args.random)) started = time.time() vanilla, rust = origins(build, classes, dependencies, all_seeds) diff --git a/tools/upgrade_world.py b/tools/upgrade_world.py index 9db5e4517..5f42988f1 100755 --- a/tools/upgrade_world.py +++ b/tools/upgrade_world.py @@ -9,7 +9,6 @@ level.dat, player and data/*.dat files) is applied exactly. The original is kept upgrade_world.py SOURCE_WORLD DEST_WORLD """ import shutil -import socket import subprocess import sys import tempfile @@ -24,12 +23,6 @@ ROOT = Path(__file__).resolve().parent.parent SERVER = lab.GAME / 'jars' / 'server.jar' -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): if len(sys.argv) != 3: sys.exit(__doc__) @@ -42,7 +35,7 @@ def main(): scratch = Path(scratch) (scratch / 'eula.txt').write_text('eula=true\n') (scratch / 'server.properties').write_text( - f'level-name=world\nonline-mode=false\nserver-port={free_port()}\n') + f'level-name=world\nonline-mode=false\nserver-port={lab.free_port()}\n') shutil.copytree(source, scratch / 'world') # The server upgrades at startup, then keeps running as a normal server: stop it # once it reports "Done". diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 64eb82691..2cdfeec21 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -14,12 +14,10 @@ that skips the first-run screens, keeps the game running unfocused and renders few chunks, so a harness can drive it with vscreen keys. """ import argparse -import hashlib import json import os import subprocess import sys -import uuid import zipfile from pathlib import Path @@ -56,13 +54,6 @@ if sys.platform == "darwin": OPTIONS["enableVsync"] = "false" -def offline_uuid(name): - digest = bytearray(hashlib.md5(("OfflinePlayer:" + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - def host_library(path): name = Path(path).name if "natives-" in name: @@ -127,7 +118,7 @@ def command(args): f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", f"-Dio.netty.native.workdir={natives}", "-cp", os.pathsep.join(map(str, jars)), "net.minecraft.client.main.Main", - "--username", args.name, "--uuid", offline_uuid(args.name).hex, + "--username", args.name, "--uuid", lab.offline_uuid(args.name).hex, "--accessToken", "0", "--offlineDeveloperMode", "--version", lab.VERSION, "--gameDir", str(args.game_dir), "--assetsDir", str(assets), "--assetIndex", json.loads((GAME / "manifest.json").read_text())["assetIndex"]["id"], diff --git a/tools/vanilla_login.py b/tools/vanilla_login.py index fa2664c9d..ecc9715b4 100644 --- a/tools/vanilla_login.py +++ b/tools/vanilla_login.py @@ -11,12 +11,10 @@ its log reports the position it read, and console commands such as `data get entity NAME` can inspect the loaded player meanwhile. """ import argparse -import hashlib import socket import struct import sys import time -import uuid import zlib try: @@ -25,27 +23,9 @@ except ImportError: import lab -def offline_uuid(name): - digest = bytearray(hashlib.md5(('OfflinePlayer:' + name).encode()).digest()) - digest[6] = (digest[6] & 0x0F) | 0x30 - digest[8] = (digest[8] & 0x3F) | 0x80 - return uuid.UUID(bytes=bytes(digest)) - - -def varint(v): - out = b'' - v &= 0xFFFFFFFF - while True: - b = v & 0x7F - v >>= 7 - out += bytes([b | (0x80 if v else 0)]) - if not v: - return out - - def string(s): data = s.encode() - return varint(len(data)) + data + return lab.varint(len(data)) + data class Connection: @@ -73,44 +53,33 @@ class Connection: return value def send(self, packet_id, payload=b''): - body = varint(packet_id) + payload + body = lab.varint(packet_id) + payload if self.threshold >= 0: if len(body) >= self.threshold: - body = varint(len(body)) + zlib.compress(body) + body = lab.varint(len(body)) + zlib.compress(body) else: - body = varint(0) + body - self.sock.sendall(varint(len(body)) + body) + body = lab.varint(0) + body + self.sock.sendall(lab.varint(len(body)) + body) def receive(self): length = self.read_varint() body = self.read_exact(length) if self.threshold >= 0: - pos, size = parse_varint(body, 0) + pos, size = lab.parse_varint(body, 0) body = zlib.decompress(body[pos:]) if size else body[pos:] - pos, packet_id = parse_varint(body, 0) + pos, packet_id = lab.parse_varint(body, 0) return packet_id, body[pos:] -def parse_varint(data, pos): - value = shift = 0 - while True: - b = data[pos] - pos += 1 - value |= (b & 0x7F) << shift - shift += 7 - if not b & 0x80: - return pos, value - - def join(host, port, name, seconds): c = Connection(host, port) - c.send(0, varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + varint(2)) - c.send(0, string(name) + offline_uuid(name).bytes) + c.send(0, lab.varint(lab.version_info()['protocol_version']) + string(host) + struct.pack('>H', port) + lab.varint(2)) + c.send(0, string(name) + lab.offline_uuid(name).bytes) # Login: compression, then login finished. while True: pid, data = c.receive() if pid == 3: - c.threshold = parse_varint(data, 0)[1] + c.threshold = lab.parse_varint(data, 0)[1] elif pid == 2: break elif pid == 0: @@ -119,7 +88,7 @@ def join(host, port, name, seconds): while True: pid, data = c.receive() if pid == 15: # select known packs: claim none, receive full registries - c.send(7, varint(0)) + c.send(7, lab.varint(0)) elif pid == 4: # keep alive c.send(4, data) elif pid == 5: # ping @@ -153,7 +122,7 @@ def main(): p.add_argument('--uuid', action='store_true') args = p.parse_args() if args.uuid: - print(offline_uuid(args.name)) + print(lab.offline_uuid(args.name)) return 0 join(args.host, args.port, args.name, args.seconds) return 0 diff --git a/tools/vanilla_world_check.py b/tools/vanilla_world_check.py index 1bbc64004..317b7e998 100644 --- a/tools/vanilla_world_check.py +++ b/tools/vanilla_world_check.py @@ -17,12 +17,16 @@ load failures. import argparse import os import re -import socket import subprocess import sys import threading import time +try: + from . import lab +except ImportError: + import lab + SUSPICIOUS = re.compile( r'(ERROR|login failed|Exception|Couldn\'t load|Failed to|Skipping|Invalid|Unknown|corrupt|' r'Recreating|upgrad|DataFix|out of bounds|missing|Mismatch)', re.IGNORECASE) @@ -31,12 +35,6 @@ BENIGN = re.compile(r'(Unpacking |OFFLINE/INSECURE|online-mode|authenticate user r'Failed to load properties|Failed to load eula)') -def free_port(): - with socket.socket() as s: - s.bind(('127.0.0.1', 0)) - return s.getsockname()[1] - - def main(): p = argparse.ArgumentParser() p.add_argument('--jar', required=True) @@ -48,7 +46,7 @@ def main(): p.add_argument('--wait-after', type=float, default=1.0) p.add_argument('--timeout', type=float, default=240) args = p.parse_args() - port = args.port or free_port() + port = args.port or lab.free_port() os.makedirs(args.dir, exist_ok=True) with open(os.path.join(args.dir, 'eula.txt'), 'w') as f: f.write('eula=true\n') diff --git a/website/docs/agents.md b/website/docs/agents.md index 32ba58362..02042be4d 100644 --- a/website/docs/agents.md +++ b/website/docs/agents.md @@ -9,7 +9,7 @@ Everything you can do with the mouse and keyboard, through commands instead of c - **In the launcher:** - install, remove and prepare versions; - start the game, alone or with a world, or a server; - - your settings, the update channel and the extra game arguments; + - your settings and the extra game arguments; - the mod browser (mods, resource packs, shader packs, modpacks), imported modpacks and hosted servers; - your accounts (names only), logs and crash reports, patch notes, the data collection settings and the benchmark. - **In the game:**