From 80645bf0de2fdd28a80a158e35c06436dba49653 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:43:24 +0200 Subject: [PATCH 1/5] Sweet berries, carrots and potatoes are planted instead of eaten A right click with food that is also a block item tried to eat it before placing it: in creative always, in survival whenever the player was hungry. BlockItem.useOn places first and only eats a consumable that could not be placed (counting the use, as ItemStack.useOn does). Picking a sweet berry bush or cave vines dropped nothing: the harvest loot (Block.dropFromBlockInteractLootTable) is now rolled and popped. Bone meal on a bush that can still grow grows it (SweetBerryBushBlock.useItemOn passes it on) instead of picking it, and counts the use with its item_interact_finish vibration. Every block placement played its sound twice; BlockItem.place's level event is now the only one. tools/test_use_item_on_parity.py drives vanilla's real ServerPlayerGameMode.useItemOn (and Minecraft.startUseItem's useItem fallback) against use_item_as_player in a headless game. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 75 ++++++---- .../src/game/dispense_fixture.rs | 71 +++++++++ crates/horizon-client/src/game/growth.rs | 11 ++ crates/horizon-client/src/game/spill.rs | 17 +++ crates/horizon-client/src/items.rs | 27 ++++ crates/horizon-world/src/level/interact.rs | 24 ++++ .../parity/VanillaDispenserOracle.java | 89 ++++++++++++ tools/test_use_item_on_parity.py | 136 ++++++++++++++++++ 8 files changed, 423 insertions(+), 27 deletions(-) create mode 100644 tools/test_use_item_on_parity.py diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 483646a90..e2ae1223b 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -519,6 +519,13 @@ impl LevelAccess for GameLevel<'_> { effect: PlayerEffect::DropItem(item), .. } => self.pop_above(pos, item), + // Picking a sweet berry bush or cave vines: the harvest loot, + // popped before the pick sound draws its pitch. + LevelEvent::Player { + pos, + state, + effect: PlayerEffect::InteractLoot(table), + } => self.drop_interact_loot(pos, state, table), event => self.events.push(event), } } @@ -2109,14 +2116,16 @@ impl Game<'_> { game_master: false, }; let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let item = held.as_ref().map(|s| s.item.to_string()); let result = self.with_level(|b, level, ticks| { - b.use_without_item( + b.use_item_on( level, ticks, BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]), face, at, player, + item.as_deref(), ) }); self.process_level_events()?; @@ -2158,14 +2167,10 @@ impl Game<'_> { } return Ok(()); } - if info.food.is_some() - && let Some(p) = self.player.as_ref() - && (p.health.food.food < 20 || self.creative) - { - // Consumable.startConsuming: held right click for consume_seconds. - if self.using.is_none() { - self.using = Some((self.selected, 0)); - } + // Food that is also a block item (berries, carrots, potatoes) aimed at + // a block tries to place first: BlockItem.useOn eats only when the + // placement fails. + if !(info.block.is_some() && self.pick().is_some()) && self.start_eating(&info) { return Ok(()); } if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? { @@ -2198,6 +2203,8 @@ impl Game<'_> { return Ok(()); } if !self.may_build() { + // ItemStack.useOn passes in adventure mode; useItem eats. + self.start_eating(&info); return Ok(()); } let face = match hit.face { @@ -2223,6 +2230,11 @@ impl Game<'_> { let outcome = self.with_level(|b, level, ticks| b.place_block(level, ticks, &ctx)); let PlaceOutcome::Placed { pos, state } = outcome else { self.process_level_events()?; + // BlockItem.useOn: a consumable that could not be placed is used, + // which ItemStack.useOn counts as a use of the item. + if self.start_eating(&info) { + self.stats.add("used", &stack.item, 1); + } return Ok(()); }; let target = [pos.x, pos.y, pos.z]; @@ -2239,25 +2251,18 @@ impl Game<'_> { } } self.swing_arm(); - let sounds = self.res.facts.get(state).sounds.clone(); - let center = [ - f64::from(target[0]) + 0.5, - f64::from(target[1]) + 0.5, - f64::from(target[2]) + 0.5, - ]; - // SolidBucketItem.getPlaceSound: the bucket's own empty sound. + // BlockItem.place's sound is among the level events; + // SolidBucketItem.getPlaceSound replaces it with the bucket's own. let solid_bucket = &*stack.item == "minecraft:powder_snow_bucket"; - let place_sound = if solid_bucket { - "minecraft:item.bucket.empty_powder_snow" - } else { - &sounds.place - }; - self.audio.play( - place_sound, - Some(center), - (sounds.volume + 1.0) / 2.0, - sounds.pitch * 0.8, - ); + if solid_bucket { + for event in &mut self.level_events { + if let LevelEvent::Sound { pos: at, sound, .. } = event + && *at == pos + { + *sound = "minecraft:item.bucket.empty_powder_snow".into(); + } + } + } self.process_level_events()?; // BlockItem.place: the used statistic and the placed_block trigger. self.stats.add("used", &stack.item, 1); @@ -2271,6 +2276,22 @@ impl Game<'_> { } Ok(()) } + /// `Consumable.startConsuming` for held food the player can eat + /// (`Player.canEat`): the right click is held for `consume_seconds`. + fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool { + if info.food.is_none() + || !self + .player + .as_ref() + .is_some_and(|p| p.health.food.food < 20 || self.creative) + { + return false; + } + if self.using.is_none() { + self.using = Some((self.selected, 0)); + } + true + } fn consume_held(&mut self) { if self.creative { return; diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index c92f88505..e3fd0e896 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -10,11 +10,13 @@ use super::{ use horizon_client::{ Result, chunk::Chunk, + command::args::GameMode, containers::BlockEntity, gamerules::Value as RuleValue, item_data::{canon_stack, parse_stack}, items::ItemStack, mobs::{Mob, Species}, + motion::PlayerMotion, projectiles::ProjectileKind, world::World, }; @@ -25,6 +27,7 @@ use horizon_core::{ use horizon_world::{level::Ticks, registry::BlockStateId}; use serde_json::Value; use std::{cell::RefCell, collections::HashMap, fmt::Write as _, io::Write as _, sync::Arc}; +use winit::keyboard::KeyCode; thread_local! { /// Level and game events recorded while a fixture case runs. @@ -267,6 +270,8 @@ impl Game<'_> { self.fixture_remove(origin, op)?; } else if let Some(op) = case.get("use") { used = self.fixture_use(origin, op)?; + } else if let Some(op) = case.get("use_item") { + used = self.fixture_use_item(origin, op)?; } else if case.get("hopper").is_some() { // HopperBlockEntity.pushItemsTick, once. self.hopper_try_move_items((origin.x, origin.y, origin.z)); @@ -402,6 +407,72 @@ impl Game<'_> { Ok(out) } + /// A player three blocks south of `pos` right-clicks its top face holding + /// the case's item (`use_item_as_player` on that hit): the statistics, + /// the held stack and the item it started using, as + /// `VanillaDispenserOracle.useItem` prints them. + fn fixture_use_item(&mut self, pos: BlockPos, op: &Value) -> Result> { + let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?; + self.mode = if op["creative"].as_bool().unwrap_or(false) { + GameMode::Creative + } else { + GameMode::Survival + }; + self.creative = self.mode == GameMode::Creative; + let mut player = PlayerMotion::new( + self.motion, + horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 3.5, + ), + )?; + player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32; + self.player = Some(player); + self.yaw = 0.0; + self.pitch = 90.0; + self.keys.clear(); + if op["sneaking"].as_bool().unwrap_or(false) { + self.keys.insert(KeyCode::ShiftLeft); + } + self.using = None; + self.inventory[self.selected] = stack.clone(); + let used_before = stack + .as_ref() + .map_or(0, |s| self.stats.get("used", &s.item)); + self.forced_hit = Some(super::Hit { + pos: [pos.x, pos.y, pos.z], + face: [0, 1, 0], + point: [ + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 0.5, + ], + }); + let used = self.use_item_as_player(); + self.forced_hit = None; + used?; + self.process_level_events()?; + let mut out = Vec::new(); + if let Some(s) = &stack { + let used = self.stats.get("used", &s.item) - used_before; + if used != 0 { + out.push(format!("stat {} minecraft:used {used}", s.item)); + } + } + let using = self + .using + .and_then(|(slot, _)| self.stack_in(slot)) + .map_or("-".to_owned(), |s| s.item.to_string()); + out.push(format!( + "held {} using {using}", + canon_stack(self.inventory[self.selected].as_ref()) + )); + self.player = None; + self.using = None; + Ok(out) + } + /// A stack in a block entity's slot: a container's, a jukebox's record, a /// lectern's book, or the items of a block entity Horizon keeps as saved. fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index a53d0ac69..7e5ad08ce 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -47,9 +47,20 @@ impl Game<'_> { }; let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face)); + // ItemStack.causeUseVibration at the player, after the meal is used + // up (shrunk even in creative): an emptied stack has no use effects. + if used + && stack.count > 1 + && let Some(p) = self.player.as_ref().map(|p| p.position) + { + let ctx = self.player_context(None); + self.post_game_event("minecraft:item_interact_finish", [p.x, p.y, p.z], ctx); + } self.process_level_events()?; if used { self.swing_arm(); + // ItemStack.useOn: an item interaction counts as a use. + self.stats.add("used", &stack.item, 1); self.consume_held(); } Ok(used) diff --git a/crates/horizon-client/src/game/spill.rs b/crates/horizon-client/src/game/spill.rs index 3e910ca1f..9e4ccdf76 100644 --- a/crates/horizon-client/src/game/spill.rs +++ b/crates/horizon-client/src/game/spill.rs @@ -221,6 +221,23 @@ impl GameLevel<'_> { delay: 10, }); } + /// `Block.dropFromBlockInteractLootTable` with `Block.popResource` of + /// every stack. + pub(super) fn drop_interact_loot(&mut self, pos: BlockPos, state: BlockStateId, table: &str) { + let drops = self.items.interact_loot( + table, + self.registry, + state, + &mut self.world.random, + self.rand_sequences, + self.seed, + ); + for stack in drops { + if &*stack.item != "minecraft:air" && stack.count > 0 { + self.pop_resource([pos.x, pos.y, pos.z], stack); + } + } + } /// `Block.dropResources(state, level, pos, blockEntity)`: the block's loot /// (from its random sequence, else the level random), with what its block /// entity copies into it, popped at once. diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 8a71b77ab..9892243fc 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -754,6 +754,33 @@ impl Items { .as_str() .map(str::to_owned) } + /// `Block.dropFromBlockInteractLootTable`: the `block_interact` table `id` + /// for a right click on `state` (its `match_block` conditions see the + /// state), from the table's random sequence when it has one. + pub fn interact_loot( + &self, + id: &str, + registry: &BlockRegistry, + state: BlockStateId, + random: &mut impl RandomSource, + sequences: &mut crate::random_sequences::RandomSequences, + seed: i64, + ) -> Vec { + let (Some(table), Some(block)) = (self.loot.get(id), registry.state(state)) else { + return vec![]; + }; + let ctx = LootContext { + items: self, + block: &block.name, + properties: &block.properties, + held: None, + killed_by_player: false, + }; + match table.get("random_sequence").and_then(Value::as_str) { + Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)), + None => ctx.evaluate(table, random), + } + } /// `loot_table` drawing from any random (a random sequence). pub fn loot_table_from( &self, diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 0d761c7c6..791daf7c2 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -527,4 +527,28 @@ impl Behaviours { self.sim(level, ticks) .use_without_item(pos, face, hit, player) } + /// `BlockState.useItemOn` with `item` in the main hand, then, when the + /// block asks to try with an empty hand (the default), `useWithoutItem`. + /// `SweetBerryBushBlock.useItemOn` passes bone meal on a bush that can + /// still grow on to the item. + #[allow(clippy::too_many_arguments)] + pub fn use_item_on( + &self, + level: &mut L, + ticks: &mut Ticks, + pos: BlockPos, + face: Direction, + hit: Vec3, + player: PlayerContext, + item: Option<&str>, + ) -> InteractionResult { + let state = level.block_state(pos); + if item == Some("minecraft:bone_meal") + && self.data(state).chain.contains(&Class::SweetBerryBush) + && self.table.int(state, self.props.age) < 3 + { + return InteractionResult::Pass; + } + self.use_without_item(level, ticks, pos, face, hit, player) + } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 89dda66f6..721d260f4 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -295,6 +295,8 @@ public final class VanillaDispenserOracle { remove(w, origin, f.getAsJsonObject("remove")); } else if (f.has("use")) { used = use(w, origin, f.getAsJsonObject("use")); + } else if (f.has("use_item")) { + used = useItem(w, origin, f.getAsJsonObject("use_item")); } else if (f.has("hopper")) { // HopperBlockEntity.pushItemsTick, once. var hopper = (net.minecraft.world.level.block.entity.HopperBlockEntity) w.getBlockEntity(origin); @@ -410,6 +412,93 @@ public final class VanillaDispenserOracle { return out; } + /** + * The player of a "use_item" case: a `User` that also has abilities, food, + * item cooldowns and a place (away from the clicked block), and records + * starting to use its item instead of syncing it. + */ + static final class Clicker extends net.minecraft.server.level.ServerPlayer { + VanillaBlockUpdateOracle.World world; + boolean creative, sneaking; + ItemStack hand; + List stats; + String using; + Clicker() { + super(null, null, null, null); + } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return creative; } + @Override public boolean isCreative() { return creative; } + @Override public boolean isSpectator() { return false; } + @Override public boolean isSecondaryUseActive() { return sneaking; } + @Override public boolean isShiftKeyDown() { return sneaking; } + @Override public boolean isDescending() { return sneaking; } + @Override public EntityType getType() { return EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { return slot == EquipmentSlot.MAINHAND ? hand : ItemStack.EMPTY; } + @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : ItemStack.EMPTY; + } + @Override public void setItemInHand(net.minecraft.world.InteractionHand h, ItemStack stack) { + if (h == net.minecraft.world.InteractionHand.MAIN_HAND) hand = stack; + } + @Override public void startUsingItem(net.minecraft.world.InteractionHand h) { + using = BuiltInRegistries.ITEM.getKey(getItemInHand(h).getItem()).toString(); + } + @Override public boolean isUsingItem() { return using != null; } + @Override public void awardStat(net.minecraft.stats.Stat stat, int count) { + stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); + } + } + + /** + * A right click on the top of the block at `pos` (`ServerPlayerGameMode.useItemOn` + * of the real game mode, survival or creative): the block's `useItemOn` and + * `useWithoutItem`, then the item's `useOn` (`BlockItem.place`, falling back + * to eating a consumable), and `useItem` when that passes, as + * `Minecraft.startUseItem` goes on to. The statistics, the held stack and + * the item the player started using follow. + */ + static List useItem(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject use) throws Exception { + Clicker player = (Clicker) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Clicker.class); + player.world = w; + player.creative = use.get("creative").getAsBoolean(); + player.sneaking = use.get("sneaking").getAsBoolean(); + player.hand = stack(use.get("item").getAsString()); + player.stats = new ArrayList<>(); + var abilities = new net.minecraft.world.entity.player.Abilities(); + abilities.invulnerable = abilities.instabuild = abilities.mayfly = player.creative; + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", abilities); + var food = new net.minecraft.world.food.FoodData(); + food.setFoodLevel(use.get("food").getAsInt()); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", food); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "cooldowns", new net.minecraft.world.item.ItemCooldowns()); + var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); + VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); + // Standing three blocks south of the clicked block, looking down at it. + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); + VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); + VanillaBlockUpdateOracle.set(Entity.class, player, "xRot", 90f); + var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer", + player.creative ? net.minecraft.world.level.GameType.CREATIVE : net.minecraft.world.level.GameType.SURVIVAL); + var hit = new net.minecraft.world.phys.BlockHitResult(net.minecraft.world.phys.Vec3.atCenterOf(pos).add(0, 0.5, 0), + net.minecraft.core.Direction.UP, pos, false); + var hand = net.minecraft.world.InteractionHand.MAIN_HAND; + var result = gameMode.useItemOn(player, w, player.getItemInHand(hand), hand, hit); + // Minecraft.startUseItem: a click on a block that neither succeeded nor + // failed goes on to use the item in the same hand. + if (!(result instanceof net.minecraft.world.InteractionResult.Success) + && !(result instanceof net.minecraft.world.InteractionResult.Fail) && !player.hand.isEmpty()) { + gameMode.useItem(player, w, player.getItemInHand(hand), hand); + } + List out = new ArrayList<>(player.stats); + out.add("held " + ParityData.canon(player.hand) + " using " + (player.using == null ? "-" : player.using)); + return out; + } + /** The level's block entity positions by x, y, z. */ static List sortedEntities(VanillaBlockUpdateOracle.World w) { List out = new ArrayList<>(w.blockEntities == null ? List.of() : w.blockEntities.keySet()); diff --git a/tools/test_use_item_on_parity.py b/tools/test_use_item_on_parity.py new file mode 100644 index 000000000..57080c880 --- /dev/null +++ b/tools/test_use_item_on_parity.py @@ -0,0 +1,136 @@ +#!/usr/bin/env python3 +"""Compare a player's right click on a block with vanilla's, for items that are +both food and blocks (sweet and glow berries, carrots, potatoes) and for sweet +berry bushes. + +Every case has a block at the origin, something above it, and a player three +blocks south, survival or creative, hungry or full, sneaking or not, who +right-clicks the top face of the origin holding an item. Vanilla runs the real +`ServerPlayerGameMode.useItemOn` over the headless level of the dispenser +harness (`VanillaDispenserOracle.useItem`): the block's `useItemOn` and +`useWithoutItem` (picking a bush's berries, `SweetBerryBushBlock.useItemOn` +passing bone meal on), then `ItemStack.useOn` (`BlockItem.place` with its +`mayPlaceOn` rules, `BoneMealItem.useOn`, and eating a consumable that could +not be placed). Horizon runs `use_item_as_player` on that hit in a headless +game (`HORIZON_DISPENSE_FIXTURE`). Both print block changes, dropped items, +level events, sounds, game events, the used statistic, the held stack, the +item the player started using, and the level random afterwards. +""" +import json +import os +import random +try: + from . import block_update_harness as h, lab, test_dispenser_parity as d, test_rust_parity as base +except ImportError: + import block_update_harness as h + import lab + import test_dispenser_parity as d + import test_rust_parity as base + +# Blocks the item is used on: the supports of the planted blocks and others. +GROUNDS = ['grass_block', 'dirt', 'coarse_dirt', 'podzol', 'rooted_dirt', 'moss_block', 'pale_moss_block', 'mud', + 'muddy_mangrove_roots', 'farmland', 'stone', 'sand', 'gravel', 'clay', 'snow_block', 'oak_planks'] +ITEMS = ['sweet_berries', 'sweet_berries', 'sweet_berries', 'glow_berries', 'carrot', 'potato', 'bone_meal', + 'wheat_seeds', 'beetroot_seeds', 'apple'] +# What is in the way above the clicked block. +ABOVE = ['air'] * 8 + ['short_grass', 'snow', 'stone', 'water', 'dead_bush', 'fern'] + + +def cases(facts, count, seed): + rng = random.Random(seed) + states = d.States(facts) + for n in range(count): + case = {**h.environment(rng), 'pos': [0, 0, 0]} + case.pop('raining', None) + case.pop('thundering', None) + cells = [] + item = rng.choice(ITEMS) + if rng.random() < 0.3: + # A sweet berry bush on grass: pick it, bone meal it, or plant against it. + age = rng.randrange(4) + cells.append([0, 0, 0, states.get('sweet_berry_bush', age=str(age))]) + cells.append([0, -1, 0, states.get(rng.choice(['grass_block', 'dirt', 'podzol', 'farmland']))]) + item = rng.choice(['bone_meal', 'bone_meal', 'sweet_berries', 'apple', '-', 'stick']) + else: + ground = rng.choice(GROUNDS) + cells.append([0, 0, 0, states.any(rng, ground) if ground == 'farmland' else states.get(ground)]) + above = rng.choice(ABOVE) + if above != 'air': + cells.append([0, 1, 0, states.get(above)]) + if item == 'glow_berries' and rng.random() < 0.5: + # A ceiling two blocks up for the cave vines to hang from. + cells.append([0, 2, 0, states.get(rng.choice(['stone', 'dirt', 'oak_leaves']))]) + if item == 'bone_meal' and ground in ('grass_block', 'moss_block', 'pale_moss_block'): + # Bone meal on spreading blocks is the bone meal harness's. + item = 'sweet_berries' + held = '-' if item == '-' else d.plain(item, rng.choice([1, 1, 2, 16, 64])) + case['use_item'] = {'item': held, 'creative': rng.random() < 0.2, 'sneaking': rng.random() < 0.2, + 'food': rng.choice([20, 20, 19, 10, 0])} + case['cells'] = cells + case['items'] = [] + case['mode'] = 'dispense' + yield case + + +def kind(case, facts): + first = facts.states[case['cells'][0][3]][0].split(':')[1] + item = case['use_item']['item'] + item = item.split('"')[1].split(':')[1] if item != '-' else 'empty hand' + return f'{item} on {first}' + + +def main(): + parser = h.argument_parser(__doc__) + args = parser.parse_args() + if args.count == 40000: + args.count = 4000 + lock, jars, libraries = base.verify_artifacts() + facts = h.load_facts() + resources = lab.LOCAL / 'horizon-client' / lock['minecraft']['version'] + work = lab.LOCAL / 'use-item-on-parity' + work.mkdir(parents=True, exist_ok=True) + all_cases = list(cases(facts, args.count, args.seed)) + (work / 'cases.jsonl').write_text(''.join(json.dumps(case) + '\n' for case in all_cases)) + classes = work / 'classes' + classes.mkdir(exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + java_root = lab.ROOT / 'mods/horizon/src/test/java' + d.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-sourcepath', str(java_root), '-nowarn', + '-cp', dependencies, '-d', str(classes), str(java_root / 'dev/horizonlab/parity/VanillaDispenserOracle.java')]) + d.run(['java', '-Xmx3G', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaDispenserOracle', + str(resources), str(work / 'cases.jsonl'), str(work / 'native.txt')]) + d.run(['cargo', 'build', '-q', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + env={**os.environ, 'CARGO_BUILD_JOBS': os.environ.get('CARGO_BUILD_JOBS', '3')}) + d.run([str(lab.cargo_target() / 'release/horizon-client'), '--resources', str(resources)], cwd=work, + env={**os.environ, 'HORIZON_DISPENSE_FIXTURE': f'{work / "cases.jsonl"},{work / "rust.txt"}', 'HORIZON_NO_AUDIO': '1'}) + ignore = tuple(prefix + ' ' for prefix in args.ignore.split(',') if prefix) + ('D ',) + native = h.split_cases((work / 'native.txt').read_text(), ignore) + rust = h.split_cases((work / 'rust.txt').read_text(), ignore) + assert len(native) == len(rust) == len(all_cases), (len(native), len(rust), len(all_cases)) + groups, errors = {}, {} + planted = eaten = 0 + for case, a, b in zip(all_cases, native, rust): + if a and a[0].startswith('error'): + errors.setdefault(a[0], []).append(case) + continue + planted += any(line.startswith('set 0,1,0') for line in a) + eaten += any(line.startswith('held') and not line.endswith('using -') for line in a) + if not d.same(a, b): + groups.setdefault(kind(case, facts), []).append((case, a, b)) + for name, entries in sorted(errors.items(), key=lambda e: -len(e[1])): + print(f'oracle error x{len(entries)}: {name}') + for name, entries in sorted(groups.items(), key=lambda e: -len(e[1])): + print(f'{name}: {len(entries)} differing') + for case, a, b in entries[:args.show]: + print(' case ' + d.describe(case, facts) + ' use=' + json.dumps(case['use_item'])) + print(' native ' + ' | '.join(sorted(a))) + print(' rust ' + ' | '.join(sorted(b))) + total = sum(len(v) for v in groups.values()) + skipped = sum(len(v) for v in errors.values()) + print(f'{len(all_cases) - total - skipped}/{len(all_cases) - skipped} cases match ({skipped} oracle errors); ' + f'vanilla planted in {planted} and started eating in {eaten}') + h.finish(total + skipped) + + +if __name__ == '__main__': + main() From 7ace13cc821b621951e6747745fe05b437e7852d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:15:36 +0200 Subject: [PATCH 2/5] Find a new world's spawn as vanilla does Horizon searched its own spiral of 48-block steps from 0 0 for a dry, non-leaf top block, so seed 1891623539983467248 spawned at -48 -48 where vanilla puts the world spawn at 144 71 144 (the player then lands within the respawn radius, 152 145 in the report). Vanilla (MinecraftServer.setInitialSpawn): NoiseBasedChunkGenerator. getOrigin runs NoiseSpawnFinder over the noise settings' spawn_target points (SpawnTargetPoint.sampleFitness, a 2048/512 then 512/32 radial search biased towards 0 0); an 11 by 11 chunk spiral around that chunk takes the first column PlayerSpawnFinder.getSpawnPosInChunk accepts (getLevelRespawnPos: MOTION_BLOCKING, WORLD_SURFACE and OCEAN_FLOOR heights, no liquid, a full-topped collision shape); without one, the origin chunk's centre at the spawn height. The first player is then placed by PlayerSpawnFinder.findSpawn: the respawn-radius square in a random coprime order, a free player box with liquids colliding, else the spawn with fixupSpawnHeight; adventure mode uses the spawn as is. horizon-world gains worldgen::spawn_finder and OverworldGenerator::origin; the client's world_spawn module and game/initial_spawn.rs follow setInitialSpawn and PlayerSpawnFinder, for single player and the dedicated server alike. Flat worlds use FlatLevelSource's origin and spawn height. tools/test_world_spawn_parity.py compares, for the report's seed, the chunk harness's seeds and 50 random ones, the origins (VanillaWorldSpawnOracle against the spawn_origin example) and the level.dat spawn of worlds created by the vanilla dedicated server and by Horizon's. Vanilla is not deterministic on chunk corners where trees of neighbouring chunks overlap (decoration order follows its worker threads), so a mismatching seed reruns vanilla up to three times. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/collisions.rs | 16 +- crates/horizon-client/src/flatgen.rs | 4 + crates/horizon-client/src/game.rs | 106 +++---- .../horizon-client/src/game/initial_spawn.rs | 217 ++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/vanillagen.rs | 4 + crates/horizon-client/src/world_spawn.rs | 269 ++++++++++++++++++ crates/horizon-world/examples/spawn_origin.rs | 54 ++++ crates/horizon-world/src/worldgen.rs | 1 + .../horizon-world/src/worldgen/generator.rs | 53 +++- .../src/worldgen/spawn_finder.rs | 128 +++++++++ .../parity/VanillaWorldSpawnOracle.java | 61 ++++ tools/test_world_spawn_parity.py | 169 +++++++++++ 13 files changed, 1022 insertions(+), 61 deletions(-) create mode 100644 crates/horizon-client/src/game/initial_spawn.rs create mode 100644 crates/horizon-client/src/world_spawn.rs create mode 100644 crates/horizon-world/examples/spawn_origin.rs create mode 100644 crates/horizon-world/src/worldgen/spawn_finder.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java create mode 100644 tools/test_world_spawn_parity.py diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index d65851636..1f84a1e29 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -96,6 +96,20 @@ impl SceneCollisions<'_, '_> { /// `noCollision(null, box)`: block collisions under the empty collision /// context, as entity-less queries such as spawn checks use. pub fn no_collision_empty(world: &mut W, bounds: Aabb) -> bool +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + no_collision_in(world, bounds, false) +} +/// `noCollision(null, box, true)`: the same with liquids colliding as +/// blocks (`CollisionContext.emptyWithFluidCollisions`). +pub fn no_collision_or_liquid(world: &mut W, bounds: Aabb) -> bool +where + W: BlockCollisionWorld + EntityMovementWorld, +{ + no_collision_in(world, bounds, true) +} +fn no_collision_in(world: &mut W, bounds: Aabb, fluids: bool) -> bool where W: BlockCollisionWorld + EntityMovementWorld, { @@ -103,7 +117,7 @@ where world, CollisionCheckRequest { entity: EntityIdentity(0), - context: CollisionContext::empty(false), + context: CollisionContext::empty(fluids), bounds, candidate_budget: 1_000_000, }, diff --git a/crates/horizon-client/src/flatgen.rs b/crates/horizon-client/src/flatgen.rs index 72245a4d3..d7764c30e 100644 --- a/crates/horizon-client/src/flatgen.rs +++ b/crates/horizon-client/src/flatgen.rs @@ -39,6 +39,10 @@ impl FlatTerrain { biome: biomes.id(&biome), }) } + /// FlatLevelSource.getSpawnHeight: the top of the layers. + pub fn spawn_height(&self) -> i32 { + crate::chunk::MIN_Y + self.layers.len().min(crate::chunk::HEIGHT as usize) as i32 + } } impl ChunkGenerator for FlatTerrain { type Worker = (); diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 483646a90..c8d0dbb4f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -45,6 +45,7 @@ mod ghasts; mod golems; mod growth; mod hand; +mod initial_spawn; mod item_draw; mod item_particles; mod jukebox; @@ -678,7 +679,13 @@ struct Game<'a> { book: Option, /// Lecterns whose page-turn pulse is running (ticks left). lectern_pulses: Vec<((i32, i32, i32), i32)>, + /// Steps of the world spawn's chunk spiral taken so far. spawn_search: u32, + /// The world spawn search's origin chunk and fallback height, once known. + spawn_origin: Option<((i32, i32), i32)>, + spawn_spiral: horizon_client::world_spawn::ChunkSpiral, + /// A new player's spawn search, while its candidates' chunks load. + player_spawn: Option, mobs: Vec, arrows: Vec, creatures: creatures::Creatures, @@ -2481,31 +2488,6 @@ impl Game<'_> { } Ok(()) } - /// The i-th world spawn search point: a square spiral in 48-block steps. - fn spawn_candidate(i: u32) -> (i32, i32) { - if i == 0 { - return (0, 0); - } - let mut k = 1u32; - let mut ring = 1i32; - loop { - let points = 8 * ring as u32; - if i < k + points { - let j = (i - k) as i32; - let side = j / (2 * ring); - let t = j % (2 * ring) - ring; - let (x, z) = match side { - 0 => (t, -ring), - 1 => (ring, t), - 2 => (-t, ring), - _ => (-ring, -t), - }; - return (x * 48, z * 48); - } - k += points; - ring += 1; - } - } /// A column whose surface is a full solid, non-fluid, non-leaf block open to the sky. fn land_column(&self, x: i32, z: i32) -> Option { if self.dim == Dim::Nether { @@ -2564,48 +2546,48 @@ impl Game<'_> { .spawn .map(|s| Vec3::new(s[0] + 0.5, s[1], s[2] + 0.5)); } - let anchor = match saved.or(self.spawn) { - Some(p) => (p.x.floor() as i32, p.z.floor() as i32), - None => Self::spawn_candidate(self.spawn_search), - }; - let (cx, cz) = (anchor.0 >> 4, anchor.1 >> 4); - self.streaming.center = (cx, cz); - if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { - return Ok(()); - } let feet = if let Some(p) = saved { + let (cx, cz) = ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4); + self.streaming.center = (cx, cz); + if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return Ok(()); + } self.level.position = None; p - } else if let Some(s) = self.spawn { + } else if self.spawn.is_none() || self.player_spawn.is_some() { + // A new world: its spawn, then the first player around it. + if self.spawn.is_none() { + let Some([x, y, z]) = self.find_world_spawn()? else { + return Ok(()); + }; + self.spawn = Some(Vec3::new( + f64::from(x) + 0.5, + f64::from(y), + f64::from(z) + 0.5, + )); + self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]); + } + let s = self + .level + .spawn + .unwrap_or_default() + .map(|v| v.floor() as i32); + let Some(feet) = self.find_player_spawn(s)? else { + return Ok(()); + }; + feet + } else { + let s = self.spawn.unwrap_or_default(); + let (cx, cz) = ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4); + self.streaming.center = (cx, cz); + if !(-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + return Ok(()); + } // WorldSpawn: the stored column, lifted onto its current surface. let y = self .land_column(s.x.floor() as i32, s.z.floor() as i32) .map_or(s.y, f64::from); Vec3::new(s.x, y.max(s.y), s.z) - } else { - let mut best: Option<(i64, i32, i32, i32)> = None; - for z in (cz - 1) * 16..(cz + 2) * 16 { - for x in (cx - 1) * 16..(cx + 2) * 16 { - if let Some(y) = self.land_column(x, z) { - let d = i64::from(x - anchor.0).pow(2) + i64::from(z - anchor.1).pow(2); - if best.is_none_or(|b| d < b.0) { - best = Some((d, x, y, z)); - } - } - } - } - match best { - Some((_, x, y, z)) => { - let spawn = Vec3::new(f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5); - self.spawn = Some(spawn); - self.level.spawn = Some([f64::from(x), f64::from(y), f64::from(z)]); - spawn - } - None => { - self.spawn_search += 1; - return Ok(()); - } - } }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; @@ -5538,6 +5520,9 @@ impl Game<'_> { self.player = None; self.spawn = None; self.spawn_search = 0; + self.spawn_origin = None; + self.spawn_spiral = Default::default(); + self.player_spawn = None; self.mobs.clear(); self.creatures.reset_trader(); self.arrows.clear(); @@ -8948,6 +8933,9 @@ pub fn run() -> Result<()> { book: None, lectern_pulses: Vec::new(), spawn_search: 0, + spawn_origin: None, + spawn_spiral: Default::default(), + player_spawn: None, mobs: Vec::new(), arrows: Vec::new(), creatures: Default::default(), diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs new file mode 100644 index 000000000..d35484390 --- /dev/null +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -0,0 +1,217 @@ +//! A new world's spawn and its first player's position: MinecraftServer. +//! setInitialSpawn walks a chunk spiral around NoiseBasedChunkGenerator. +//! getOrigin, then PlayerSpawnFinder.findSpawn picks a free column around +//! the world spawn within the respawn radius. +use super::{Game, dispenser::entity_random}; +use horizon_client::{ + Result, + assets::Properties, + chunk::{HEIGHT, MIN_Y}, + collisions::{SceneCollisions, no_collision_or_liquid}, + world::World, + world_spawn::{ + PlayerSpawnFinder, SpawnCandidate, SpawnLevel, level_respawn_pos, spawn_pos_in_chunk, + }, +}; +use horizon_core::{ + geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}, + position::BlockPos, + random::RandomSource, +}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, collision_context::CollisionContext, + heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates, +}; + +/// The loaded world as the spawn searches query it. +struct Columns<'a, 'r> { + world: &'a World, + properties: &'a Properties, + binding: &'a BlockCollisionRegistry<'r>, +} +impl SpawnLevel for Columns<'_, '_> { + fn min_y(&self) -> i32 { + MIN_Y + } + fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32 { + (MIN_Y..MIN_Y + HEIGHT) + .rev() + .find(|&y| kind.is_opaque(self.properties.heightmap_state(self.world.block(x, y, z)))) + .map_or(MIN_Y, |y| y + 1) + } + fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool { + use horizon_world::heightmap::HeightmapState; + self.properties + .heightmap_state(self.world.block(x, y, z)) + .has_fluid() + } + fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool { + let mut scene = SceneCollisions { + world: self.world, + binding: self.binding, + subject: None, + }; + let state = self.world.block(x, y, z); + let Ok(shape) = self.binding.collision_shape_with_context( + &mut scene, + state, + BlockPos::new(x, y, z), + &CollisionContext::empty(false), + ) else { + return false; + }; + shape.face_shape(Direction::Up).is_ok_and(|face| { + VoxelShape::block() + .join_is_not_empty(&face, ShapeOp::XOR) + .is_ok_and(|differs| !differs) + }) + } +} + +impl Game<'_> { + fn spawn_columns(&self) -> Columns<'_, '_> { + Columns { + world: &self.world, + properties: &self.res.assets.properties, + binding: self.collision, + } + } + /// ChunkGenerator.getOrigin and getSpawnHeight of the overworld. + fn spawn_origin(&self) -> Result<((i32, i32), i32)> { + if let Some(flat) = + horizon_client::save::world_gen_settings(&self.world_root).and_then(|s| { + horizon_client::flatgen::FlatTerrain::from_settings( + &s, + self.res.assets.registry, + &self.res.biomes, + ) + }) + { + return Ok(((0, 0), flat.spawn_height())); + } + if self.options.test_terrain { + return Ok(((0, 0), 64)); + } + let origin = match self.end.locator() { + Some(terrain) => terrain.origin()?, + None => horizon_core::position::ChunkPos::new(0, 0), + }; + Ok(((origin.x, origin.z), 64)) + } + /// MinecraftServer.setInitialSpawn: the first chunk of the spiral with a + /// valid respawn column gives the world spawn, else the origin chunk's + /// centre at the spawn height. None while a chunk to test is loading. + pub(super) fn find_world_spawn(&mut self) -> Result> { + let ((ox, oz), height) = match self.spawn_origin { + Some(origin) => origin, + None => *self.spawn_origin.insert(self.spawn_origin()?), + }; + while let Some((dx, dz)) = self.spawn_spiral.current() { + self.spawn_search = self.spawn_spiral.steps() as u32; + if self.spawn_spiral.tested() { + let (cx, cz) = (ox + dx, oz + dz); + if !self.streaming.is_lit(cx, cz) { + self.streaming.center = (cx, cz); + return Ok(None); + } + if let Some(pos) = spawn_pos_in_chunk(&self.spawn_columns(), cx, cz) { + return Ok(Some(pos)); + } + } + self.spawn_spiral.advance(); + } + Ok(Some([ox * 16 + 8, height, oz * 16 + 8])) + } + /// PlayerSpawnFinder.findSpawn around the world spawn: the feet of a + /// player who has no position yet. None while a candidate's chunk loads. + pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result> { + let mut finder = match self.player_spawn { + Some(finder) => finder, + None if self.level.game_mode == 2 => { + // Adventure mode: the suggestion itself. + let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0); + finder.next_candidate(); + finder + } + None => { + let mut radius = self.ui.rules.int("respawn_radius").max(0); + let to_border = self + .border + .distance(f64::from(suggestion[0]), f64::from(suggestion[2])) + .floor() as i32; + if to_border < radius { + radius = to_border; + } + if to_border <= 1 { + radius = 1; + } + PlayerSpawnFinder::new(suggestion, radius, |n| { + entity_random().next_int_bound(n).unwrap_or(0) + }) + } + }; + let found = loop { + let Some(candidate) = finder.next_candidate() else { + break Some(self.fixup_spawn_height(suggestion)); + }; + let (x, z) = match candidate { + SpawnCandidate::Column(x, z) => (x, z), + SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]), + }; + if !self.streaming.is_lit(x >> 4, z >> 4) { + self.streaming.center = (x >> 4, z >> 4); + finder.retry(); + break None; + } + match candidate { + SpawnCandidate::Column(x, z) => { + if let Some(pos) = level_respawn_pos(&self.spawn_columns(), x, z) + && self.player_fits(pos) + { + break Some(bottom_center(pos)); + } + } + SpawnCandidate::Suggestion => break Some(self.fixup_spawn_height(suggestion)), + } + }; + self.player_spawn = found.is_none().then_some(finder); + Ok(found) + } + /// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the + /// block's bottom centre touches no block or liquid. + fn player_fits(&self, pos: [i32; 3]) -> bool { + let feet = bottom_center(pos); + let bounds = Aabb::new( + Vec3::new(feet.x - 0.3, feet.y, feet.z - 0.3), + Vec3::new(feet.x + 0.3, feet.y + 1.8, feet.z + 0.3), + ); + let mut scene = SceneCollisions { + world: &self.world, + binding: self.collision, + subject: None, + }; + no_collision_or_liquid(&mut scene, bounds) + } + /// PlayerSpawnFinder.fixupSpawnHeight: up out of anything solid, then + /// down onto the ground. + fn fixup_spawn_height(&self, pos: [i32; 3]) -> Vec3 { + let [x, mut y, z] = pos; + while !self.player_fits([x, y, z]) && y < MIN_Y + HEIGHT - 1 { + y += 1; + } + y -= 1; + while self.player_fits([x, y, z]) && y > MIN_Y { + y -= 1; + } + bottom_center([x, y + 1, z]) + } +} + +/// Vec3.atBottomCenterOf. +fn bottom_center(pos: [i32; 3]) -> Vec3 { + Vec3::new( + f64::from(pos[0]) + 0.5, + f64::from(pos[1]), + f64::from(pos[2]) + 0.5, + ) +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 8ae91ae29..70c4ed119 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -140,6 +140,7 @@ pub mod weather; pub mod widgets; pub mod window; pub mod world; +pub mod world_spawn; pub mod worldborder; pub mod zip; pub type Result = std::result::Result>; diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index ac242c588..04716b99d 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -126,6 +126,10 @@ impl VanillaTerrain { let worker = worker.get_or_insert_with(|| self.generator.worker()); worker.jigsaw_pieces(query) } + /// NoiseBasedChunkGenerator.getOrigin: where the world spawn search starts. + pub fn origin(&self) -> crate::Result { + Ok(self.generator.origin()?) + } /// Concentric ring positions of a structure set (strongholds), once known. pub fn ring_positions(&self, set: &str) -> Option> { self.generator.ring_positions(set) diff --git a/crates/horizon-client/src/world_spawn.rs b/crates/horizon-client/src/world_spawn.rs new file mode 100644 index 000000000..ee6e05101 --- /dev/null +++ b/crates/horizon-client/src/world_spawn.rs @@ -0,0 +1,269 @@ +//! Where a new world's spawn is and where a player first appears around it: +//! MinecraftServer.setInitialSpawn's chunk spiral and PlayerSpawnFinder. +use horizon_world::heightmap::HeightmapType; + +/// The block queries the spawn searches make on full (decorated, lit) chunks. +pub trait SpawnLevel { + fn min_y(&self) -> i32; + /// `chunk.getHeight(kind, x, z)`: one above the column's highest block + /// matching the heightmap, or the minimum height. + fn height(&self, kind: HeightmapType, x: i32, z: i32) -> i32; + /// `!getBlockState(pos).getFluidState().isEmpty()`. + fn has_fluid(&self, x: i32, y: i32, z: i32) -> bool; + /// `Block.isFaceFull(state.getCollisionShape(level, pos), Direction.UP)`. + fn top_face_full(&self, x: i32, y: i32, z: i32) -> bool; +} + +/// PlayerSpawnFinder.getLevelRespawnPos in a dimension without a ceiling: +/// the block above the column's top full-topped collision, unless water, +/// lava or only non-colliding blocks are on top. +pub fn level_respawn_pos(level: &impl SpawnLevel, x: i32, z: i32) -> Option<[i32; 3]> { + let top = level.height(HeightmapType::MotionBlocking, x, z); + if top < level.min_y() { + return None; + } + let surface = level.height(HeightmapType::WorldSurface, x, z); + if surface <= top && surface > level.height(HeightmapType::OceanFloor, x, z) { + return None; + } + for y in (level.min_y()..=top + 1).rev() { + if level.has_fluid(x, y, z) { + break; + } + if level.top_face_full(x, y, z) { + return Some([x, y + 1, z]); + } + } + None +} + +/// PlayerSpawnFinder.getSpawnPosInChunk: the first valid column, x-major. +pub fn spawn_pos_in_chunk(level: &impl SpawnLevel, cx: i32, cz: i32) -> Option<[i32; 3]> { + for x in cx * 16..cx * 16 + 16 { + for z in cz * 16..cz * 16 + 16 { + if let Some(pos) = level_respawn_pos(level, x, z) { + return Some(pos); + } + } + } + None +} + +/// setInitialSpawn's walk: Mth.square(11) steps of a square spiral around +/// the origin chunk, testing the steps within 5 chunks of it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ChunkSpiral { + step: i32, + x: i32, + z: i32, + dx: i32, + dz: i32, +} +impl Default for ChunkSpiral { + fn default() -> Self { + Self::new() + } +} +impl ChunkSpiral { + pub const fn new() -> Self { + Self { + step: 0, + x: 0, + z: 0, + dx: 0, + dz: -1, + } + } + /// Steps taken so far. + pub fn steps(&self) -> i32 { + self.step + } + /// The chunk offset to test now, or None once the walk is over. + pub fn current(&self) -> Option<(i32, i32)> { + (self.step < 11 * 11).then_some((self.x, self.z)) + } + /// Whether `current` lies within the tested 11 by 11 chunks. + pub fn tested(&self) -> bool { + (-5..=5).contains(&self.x) && (-5..=5).contains(&self.z) + } + pub fn advance(&mut self) { + if self.x == self.z + || (self.x < 0 && self.x == -self.z) + || (self.x > 0 && self.x == 1 - self.z) + { + (self.dx, self.dz) = (-self.dz, self.dx); + } + self.x += self.dx; + self.z += self.dz; + self.step += 1; + } +} + +/// What PlayerSpawnFinder tries next. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SpawnCandidate { + /// A column to test with `level_respawn_pos` and a free player box. + Column(i32, i32), + /// Every column failed: the suggestion itself, height fixed up. + Suggestion, +} + +/// PlayerSpawnFinder: the columns of the square of `radius` around the +/// suggestion in a random coprime-stride order, then the suggestion. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct PlayerSpawnFinder { + pub suggestion: [i32; 3], + radius: i32, + count: i32, + coprime: i32, + offset: i32, + next: i32, +} +impl PlayerSpawnFinder { + /// `radius` is the respawn radius already clamped to the world border + /// (findSpawn); `random(n)` draws the start offset in `0..n`. + pub fn new(suggestion: [i32; 3], radius: i32, random: impl FnOnce(i32) -> i32) -> Self { + let side = i64::from(radius) * 2 + 1; + let count = (side * side).min(1024) as i32; + Self { + suggestion, + radius, + count, + coprime: if count <= 16 { count - 1 } else { 17 }, + offset: random(count), + next: 0, + } + } + /// The next candidate, None once the suggestion was handed out. + pub fn next_candidate(&mut self) -> Option { + let index = self.next; + if index > self.count { + return None; + } + self.next += 1; + if index == self.count { + return Some(SpawnCandidate::Suggestion); + } + let value = (self.offset + self.coprime * index) % self.count; + let side = self.radius * 2 + 1; + Some(SpawnCandidate::Column( + self.suggestion[0] + value % side - self.radius, + self.suggestion[2] + value / side - self.radius, + )) + } + /// Hand the last candidate out again (its chunk was not loaded yet). + pub fn retry(&mut self) { + self.next -= 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn spiral_walks_out_from_the_origin_like_set_initial_spawn() { + let mut spiral = ChunkSpiral::default(); + let mut seen = Vec::new(); + while let Some(at) = spiral.current() { + if spiral.tested() { + seen.push(at); + } + spiral.advance(); + } + assert_eq!( + &seen[..9], + &[ + (0, 0), + (1, 0), + (1, 1), + (0, 1), + (-1, 1), + (-1, 0), + (-1, -1), + (0, -1), + (1, -1) + ] + ); + seen.sort_unstable(); + seen.dedup(); + assert_eq!(seen.len(), 121); + } + + #[test] + fn finder_visits_every_column_once_then_the_suggestion() { + let mut finder = PlayerSpawnFinder::new([100, 70, -40], 10, |n| n / 3); + let mut columns = Vec::new(); + while let Some(c) = finder.next_candidate() { + columns.push(c); + } + assert_eq!(columns.len(), 442); + assert_eq!(columns.last(), Some(&SpawnCandidate::Suggestion)); + columns.sort_by_key(|c| format!("{c:?}")); + columns.dedup(); + assert_eq!(columns.len(), 442); + let mut zero = PlayerSpawnFinder::new([5, 64, 5], 0, |_| 0); + assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Column(5, 5))); + assert_eq!(zero.next_candidate(), Some(SpawnCandidate::Suggestion)); + assert_eq!(zero.next_candidate(), None); + } + + struct Flat { + top: i32, + water: bool, + } + impl SpawnLevel for Flat { + fn min_y(&self) -> i32 { + -64 + } + fn height(&self, kind: HeightmapType, _: i32, _: i32) -> i32 { + match kind { + HeightmapType::OceanFloor if self.water => self.top - 3, + _ => self.top + 1, + } + } + fn has_fluid(&self, _: i32, y: i32, _: i32) -> bool { + self.water && y <= self.top && y > self.top - 3 + } + fn top_face_full(&self, _: i32, y: i32, _: i32) -> bool { + y <= self.top + } + } + + #[test] + fn respawn_column_stands_on_land_not_water() { + assert_eq!( + level_respawn_pos( + &Flat { + top: 70, + water: false + }, + 3, + 4 + ), + Some([3, 71, 4]) + ); + assert_eq!( + level_respawn_pos( + &Flat { + top: 62, + water: true + }, + 3, + 4 + ), + None + ); + assert_eq!( + spawn_pos_in_chunk( + &Flat { + top: 70, + water: false + }, + -2, + 1 + ), + Some([-32, 71, 16]) + ); + } +} diff --git a/crates/horizon-world/examples/spawn_origin.rs b/crates/horizon-world/examples/spawn_origin.rs new file mode 100644 index 000000000..727b25a91 --- /dev/null +++ b/crates/horizon-world/examples/spawn_origin.rs @@ -0,0 +1,54 @@ +//! NoiseSpawnFinder for tools/test_world_spawn_parity.py: for each seed, the +//! column the overworld's spawn search starts from and its chunk +//! (NoiseBasedChunkGenerator.getOrigin), as `seed x z chunk_x chunk_z` lines. +//! +//! usage: spawn_origin ... +use horizon_world::{ + DATA_VERSION, + nbt::Tag, + registry::BlockRegistry, + worldgen::generator::{GeneratorData, OverworldGenerator}, +}; +use serde_json::Value; +use std::{fs, path::Path}; + +type Error = Box; + +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { + let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; + let states = facts["states"].as_array().ok_or("facts states")?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(states.iter().map(|v| tag(&v[4])).collect()), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + Ok(Box::leak(Box::new(registry))) +} + +fn main() -> Result<(), Error> { + let mut args = std::env::args().skip(1); + let resources = std::path::PathBuf::from(args.next().ok_or("client resource directory")?); + let data = GeneratorData::load(&resources.join("worldgen"), registry(&resources)?)?; + for seed in args { + let seed: i64 = seed.parse()?; + let generator = OverworldGenerator::new(data.clone(), seed)?; + let [x, z] = generator.spawn_position()?; + let origin = generator.origin()?; + println!("{seed} {x} {z} {} {}", origin.x, origin.z); + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index a3f8487c4..63de74d24 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -61,6 +61,7 @@ pub mod sculk; pub mod settings; pub mod simple_block; pub mod snow_freeze; +pub mod spawn_finder; pub mod speleothem; pub mod spike; pub mod spring; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 8885b7f50..7adcb33b5 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -20,7 +20,7 @@ use super::{ biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, carver::{CarverCatalog, WorldCarver, generate_carving_mask}, carving::{CarvingBlocks, apply_carving_mask}, - climate::{ClimateSampler, quantize}, + climate::{ClimateSampler, decode_parameter, quantize}, decode_noise, density::DensityRegistry, material_condition::{ @@ -31,6 +31,7 @@ use super::{ material_stage::{SurfaceInputs, TopMaterialInputs, build_surface}, material_surface::{ClayBandBlocks, MaterialSurface}, router::{NoiseRouter, RouterField, RouterSamplers}, + spawn_finder::{SpawnTargetPoint, find_spawn_position}, tags::TagDefinitions, terrain::{PreLightChunkStage, TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise}, }; @@ -608,6 +609,9 @@ struct Pipeline { carver_cache: Mutex>, pub(super) decoration: Option, pub(super) structures: Option, + /// The noise settings' `spawn_target` points. + spawn_target: Vec, + spawn_position: std::sync::OnceLock<[i32; 2]>, } const CACHE_LIMIT: usize = 16384; type BiomeCache = Mutex>>>; @@ -706,6 +710,27 @@ where .ok_or_else(|| resource("material_rule"))?; let rule = library.rule(rule_name)?; let preliminary = router.get(RouterField::ChunkSurfaceLevel).clone(); + let spawn_target = match settings_json.get("spawn_target") { + Some(Value::Array(points)) => points + .iter() + .map(|point| { + let Value::Object(fields) = point else { + return Err(resource("spawn_target point")); + }; + let parameters = fields + .iter() + .map(|(name, interval)| { + Ok(( + library.named_density(name)?, + decode_parameter(&interval.to_string())?, + )) + }) + .collect::>()?; + Ok(SpawnTargetPoint { parameters }) + }) + .collect::>()?, + _ => Vec::new(), + }; let source = data .source_catalog .decode(&generator["biome_source"].to_string())? @@ -783,6 +808,8 @@ where carver_cache: Mutex::new(HashMap::new()), decoration: None, structures: None, + spawn_target, + spawn_position: std::sync::OnceLock::new(), }; pipeline.decoration = super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?; @@ -1363,6 +1390,7 @@ trait SeededPipeline: Send + Sync { fn unsupported_features(&self) -> Vec<(String, String)>; fn forget_structure_starts(&self); fn ring_positions(&self, set: &str) -> Option>; + fn spawn_position(&self) -> Result<[i32; 2], GeneratorError>; fn locate( &self, worker: &mut WorkerState, @@ -1462,6 +1490,19 @@ where fn ring_positions(&self, set: &str) -> Option> { self.structures.as_ref()?.cached_rings(set) } + fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> { + if let Some(position) = self.spawn_position.get() { + return Ok(*position); + } + // ChunkGenerator.getOrigin is 0 0 without a spawn target. + let position = if self.spawn_target.is_empty() { + [0, 0] + } else { + find_spawn_position(&self.spawn_target, &mut SamplerContext::cached()) + .map_err(|e| GeneratorError::Stage("spawn search", e.to_string()))? + }; + Ok(*self.spawn_position.get_or_init(|| position)) + } fn locate( &self, worker: &mut WorkerState, @@ -1745,6 +1786,16 @@ impl OverworldGenerator { pub fn ring_positions(&self, set: &str) -> Option> { self.pipeline.ring_positions(set) } + /// NoiseBasedChunkGenerator.getOrigin: the chunk a new world's spawn + /// search starts from (NoiseSpawnFinder over the `spawn_target` points). + pub fn origin(&self) -> Result { + let [x, z] = self.spawn_position()?; + Ok(ChunkPos::new(x >> 4, z >> 4)) + } + /// NoiseSpawnFinder.findSpawnPosition: the column `origin` is the chunk of. + pub fn spawn_position(&self) -> Result<[i32; 2], GeneratorError> { + self.pipeline.spawn_position() + } /// Create per-thread state. Workers are cheap; keep one per thread. pub fn worker(&self) -> GeneratorWorker { let data = self.pipeline.data(); diff --git a/crates/horizon-world/src/worldgen/spawn_finder.rs b/crates/horizon-world/src/worldgen/spawn_finder.rs new file mode 100644 index 000000000..12d0cf530 --- /dev/null +++ b/crates/horizon-world/src/worldgen/spawn_finder.rs @@ -0,0 +1,128 @@ +//! NoiseSpawnFinder: where a new world's spawn search starts. +//! +//! NoiseBasedChunkGenerator.getOrigin samples the noise settings' +//! `spawn_target` points (SpawnTargetPoint) around the world origin and keeps +//! the block whose climate fits them best, biased towards 0 0. The world spawn +//! search (MinecraftServer.setInitialSpawn) then spirals out from its chunk. +use super::climate::{Parameter, quantize}; +use horizon_core::density::{DensitySampler, SampleError, SamplerContext}; +use horizon_core::jmath; +use std::sync::Arc; + +const MAX_RADIUS: f32 = 2048.0; + +/// One `spawn_target` entry: climate intervals over named density functions. +#[derive(Clone, Debug)] +pub struct SpawnTargetPoint { + pub parameters: Vec<(Arc, Parameter)>, +} +impl SpawnTargetPoint { + /// SpawnTargetPoint.sampleFitness: the summed squared distances of the + /// quantized samples to their intervals. + pub fn sample_fitness( + &self, + context: &mut SamplerContext, + position: [i32; 3], + ) -> Result { + let mut fitness = 0i64; + for (function, parameter) in &self.parameters { + let distance = parameter.distance(quantize(function.sample_value(context, position)?)); + fitness = fitness.wrapping_add(distance.wrapping_mul(distance)); + } + Ok(fitness) + } +} + +#[derive(Clone, Copy, Debug)] +struct Candidate { + x: i32, + z: i32, + fitness: i64, +} + +/// NoiseSpawnFinder.findSpawnPosition: the best block column (x, z) of a +/// coarse then a fine radial search around the best of the two. +pub fn find_spawn_position( + targets: &[SpawnTargetPoint], + context: &mut SamplerContext, +) -> Result<[i32; 2], SampleError> { + let mut best = fitness(targets, context, 0, 0)?; + radial_search(targets, context, &mut best, MAX_RADIUS, 512.0)?; + radial_search(targets, context, &mut best, 512.0, 32.0)?; + Ok([best.x, best.z]) +} + +/// NoiseSpawnFinder.radialSearch: rings `increment` apart around the best +/// position so far, sampled every `increment` blocks along each ring. +fn radial_search( + targets: &[SpawnTargetPoint], + context: &mut SamplerContext, + best: &mut Candidate, + max_radius: f32, + increment: f32, +) -> Result<(), SampleError> { + let mut angle = 0f32; + let mut radius = increment; + let (origin_x, origin_z) = (best.x, best.z); + while radius <= max_radius { + let x = origin_x.wrapping_add((jmath::sin(f64::from(angle)) * f64::from(radius)) as i32); + let z = origin_z.wrapping_add((jmath::cos(f64::from(angle)) * f64::from(radius)) as i32); + let candidate = fitness(targets, context, x, z)?; + if candidate.fitness < best.fitness { + *best = candidate; + } + angle += increment / radius; + if f64::from(angle) > std::f64::consts::PI * 2.0 { + angle = 0.0; + radius += increment; + } + } + Ok(()) +} + +/// NoiseSpawnFinder.getSpawnPositionAndFitness: the best target's fitness at +/// the column's quart corner, scaled so the squared distance to 0 0 only +/// breaks ties between equally fitting columns. +fn fitness( + targets: &[SpawnTargetPoint], + context: &mut SamplerContext, + x: i32, + z: i32, +) -> Result { + let quart = [(x >> 2) << 2, 0, (z >> 2) << 2]; + let mut best = i64::MAX; + for target in targets { + best = best.min(target.sample_fitness(context, quart)?); + } + let bias = i64::from(x) * i64::from(x) + i64::from(z) * i64::from(z); + Ok(Candidate { + x, + z, + fitness: best.wrapping_mul(2048 * 2048).wrapping_add(bias), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Debug)] + struct Gradient; + impl DensitySampler for Gradient { + fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result { + Ok(p[0] as f32 / 1000.0) + } + } + + #[test] + fn the_closest_fitting_column_wins() { + // x / 1000 must reach 0.1: every column from x = 100 on fits equally, + // so the distance bias picks the fitting column nearest to 0 0. + let targets = [SpawnTargetPoint { + parameters: vec![(Arc::new(Gradient), Parameter::new(1000, 10_000))], + }]; + let [x, z] = find_spawn_position(&targets, &mut SamplerContext::default()).unwrap(); + assert!(x >= 100, "{x} {z}"); + assert!(x * x + z * z < 160 * 160, "{x} {z}"); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java new file mode 100644 index 000000000..65199b489 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaWorldSpawnOracle.java @@ -0,0 +1,61 @@ +package dev.horizonlab.parity; + +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.RegistryDataLoader; +import net.minecraft.server.Bootstrap; +import net.minecraft.server.RegistryLayer; +import net.minecraft.server.packs.PackType; +import net.minecraft.server.packs.repository.ServerPacksSource; +import net.minecraft.server.packs.resources.MultiPackResourceManager; +import net.minecraft.tags.TagLoader; +import net.minecraft.world.level.ChunkPos; +import net.minecraft.world.level.biome.MultiNoiseBiomeSource; +import net.minecraft.world.level.biome.MultiNoiseBiomeSourceParameterLists; +import net.minecraft.world.level.levelgen.NoiseBasedChunkGenerator; +import net.minecraft.world.level.levelgen.NoiseGeneratorSettings; +import net.minecraft.world.level.levelgen.NoiseSpawnFinder; +import net.minecraft.world.level.levelgen.RandomState; +import net.minecraft.world.level.levelgen.densityfunction.SamplerContext; + +/** + * The overworld's spawn origin for tools/test_world_spawn_parity.py: for each + * seed, NoiseSpawnFinder.findSpawnPosition over the noise settings' spawn + * target and NoiseBasedChunkGenerator.getOrigin, as `seed x z chunk_x chunk_z`. + * + * usage: VanillaWorldSpawnOracle ... + */ +public final class VanillaWorldSpawnOracle { + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion(); + Bootstrap.bootStrap(); + var repo = ServerPacksSource.createVanillaTrustedRepository(); + repo.reload(); + repo.setSelected(List.of("vanilla")); + var resources = new MultiPackResourceManager(PackType.SERVER_DATA, repo.openAllSelected()); + var layers = RegistryLayer.createRegistryAccess(); + var staticTags = TagLoader.loadTagsForExistingRegistries(resources, layers.getLayer(RegistryLayer.STATIC)); + var context = TagLoader.buildUpdatedLookups(layers.getAccessForLoading(RegistryLayer.WORLD), staticTags); + var world = RegistryDataLoader.load(resources, context, RegistryDataLoader.WORLD_REGISTRIES, Runnable::run).join(); + var settings = world.lookupOrThrow(Registries.NOISE_SETTINGS).getOrThrow(NoiseGeneratorSettings.OVERWORLD); + var presets = world.lookupOrThrow(Registries.MULTI_NOISE_BIOME_SOURCE_PARAMETER_LIST); + var biomeSource = MultiNoiseBiomeSource.createFromPreset(presets.getOrThrow(MultiNoiseBiomeSourceParameterLists.OVERWORLD)); + var generator = new NoiseBasedChunkGenerator(biomeSource, settings); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0]), StandardCharsets.UTF_8))) { + for (int i = 1; i < args.length; i++) { + long seed = Long.parseLong(args[i]); + var randomState = RandomState.create(world.lookupOrThrow(Registries.NOISE), seed, settings.value()); + BlockPos spawn = NoiseSpawnFinder.findSpawnPosition( + settings.value().spawnTarget(), randomState.samplersWithContext(SamplerContext.builder().enableCaches().build())); + ChunkPos origin = generator.getOrigin(randomState); + out.println(seed + " " + spawn.getX() + " " + spawn.getZ() + " " + origin.x() + " " + origin.z()); + } + } + } +} diff --git a/tools/test_world_spawn_parity.py b/tools/test_world_spawn_parity.py new file mode 100644 index 000000000..4aae12000 --- /dev/null +++ b/tools/test_world_spawn_parity.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +"""Compare a new world's spawn with vanilla's, seed by seed. + +A new overworld's spawn comes from two steps (MinecraftServer.setInitialSpawn): + +1. the origin: NoiseBasedChunkGenerator.getOrigin runs NoiseSpawnFinder over + the noise settings' `spawn_target` points (a coarse then a fine radial + search of the climate fields) and takes the chunk of the best column; +2. the spawn: an 11 by 11 chunk spiral around that chunk, the first chunk + with a column PlayerSpawnFinder.getSpawnPosInChunk accepts (a full-topped + block under open sky, no liquid on top) gives the world spawn. + +Origins: VanillaWorldSpawnOracle calls NoiseSpawnFinder.findSpawnPosition and +getOrigin for every seed; the spawn_origin example asks Horizon's generator. +World spawns: the pinned vanilla dedicated server creates each world and +stops; Horizon's (`horizon-client --dedicated --nogui`) creates its own from +the same server.properties and stops; the `spawn` position of both +level.dat files is compared. + +Vanilla is not deterministic everywhere: trees of neighbouring chunks +overlap on chunk corners, and which one is placed last depends on the order +the server's worker threads decorate the chunks. A spawn column on such a +corner can then stand on different leaves from one vanilla run to the next. +When the spawns differ, vanilla creates the world up to RETRIES more times; +Horizon's spawn passes if one of vanilla's runs gives it too, and the seed is +reported as varying in vanilla. + +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. + +usage: test_world_spawn_parity.py [--random N] [--jobs N] [--origins-only] +""" +import argparse +import json +import os +import random +import shutil +import subprocess +import sys +import time +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 .test_dedicated_server_parity import Server, free_port +except ImportError: + import anvil_dump + import lab + import oracle_harness as oh + import test_rust_parity as base + from test_dedicated_server_parity import Server, free_port + +NAME = 'world-spawn-parity' +REPORT = 1891623539983467248 +RETRIES = 3 +SEEDS = [REPORT, 12345, -7046029254386353131, 987654321987, 4242, -1, 0x5DEECE66D, 20260607, 777, 0] +RESOURCES = lab.LOCAL / 'horizon-client/26.3' + + +def seeds(count): + rng = random.Random(20261014) + return SEEDS + [rng.randrange(-2**63, 2**63) for _ in range(count)] + + +def target_dir(): + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + return Path(metadata['target_directory']) / 'release' + + +def origins(build, classes, dependencies, all_seeds): + vanilla_out = build / 'origins-vanilla.txt' + oh.run_logged(['java', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.VanillaWorldSpawnOracle', + vanilla_out, *all_seeds], build, 'origins-vanilla') + rust = subprocess.run([target_dir() / 'examples/spawn_origin', RESOURCES, *map(str, all_seeds)], + capture_output=True, text=True, check=True, cwd=lab.ROOT).stdout + vanilla = vanilla_out.read_text() + parse = lambda text: {int(l.split()[0]): tuple(map(int, l.split()[1:])) for l in text.splitlines() if l} + return parse(vanilla), parse(rust) + + +def world_spawn(command, directory, seed, log_name): + """Creates a world with `seed` in `directory`, stops, returns its level.dat spawn position.""" + if directory.exists(): + shutil.rmtree(directory) + directory.mkdir(parents=True) + props = {'online-mode': 'false', 'level-seed': str(seed), 'server-port': str(free_port()), + 'view-distance': '4', 'simulation-distance': '4', 'pause-when-empty-seconds': '-1'} + (directory / 'server.properties').write_text(''.join(f'{k}={v}\n' for k, v in props.items()), encoding='iso-8859-1') + (directory / 'eula.txt').write_text('eula=true\n') + server = Server(command, directory, log_name) + try: + server.wait_for(r'Done \(', timeout=900) + finally: + server.stop() + data = anvil_dump.read_dat(directory / 'world/level.dat')['Data'] + return tuple(data['spawn']['pos'][1]) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--random', type=int, default=50, help='random seeds besides the fixed ones') + parser.add_argument('--jobs', type=int, default=max(1, min(4, int(os.environ.get('FLEET_LOAD_JOBS', '4')) // 4)), + help='worlds created at once (each side)') + parser.add_argument('--origins-only', action='store_true', help='compare the spawn search origins only') + 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.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + oh.run_logged(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies, + '-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) + started = time.time() + + vanilla, rust = origins(build, classes, dependencies, all_seeds) + origin_diffs = [s for s in all_seeds if vanilla.get(s) != rust.get(s)] + for s in origin_diffs: + print(f'origin {s}: vanilla column {vanilla.get(s)} / horizon {rust.get(s)}') + print(f'Origins: {len(all_seeds) - len(origin_diffs)}/{len(all_seeds)} seeds match ' + f'(column x z, chunk x z) in {time.time() - started:.0f}s', flush=True) + if args.origins_only: + sys.exit(1 if origin_diffs else 0) + + oh.run_logged(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], build, + 'compile-rust', timeout=3600) + binary = target_dir() / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', RESOURCES, '--dedicated', '--nogui'] + os.environ['HORIZON_NO_AUDIO'] = '1' + + def one(seed): + t0 = time.time() + a = world_spawn(vanilla_server, build / f'vanilla-{seed}', seed, f'vanilla-{seed}') + b = world_spawn(horizon_server, build / f'horizon-{seed}', seed, f'horizon-{seed}') + runs = [a] + while b not in runs and len(runs) <= RETRIES: + runs.append(world_spawn(vanilla_server, build / f'vanilla-{seed}-{len(runs)}', seed, f'vanilla-{seed}-{len(runs)}')) + return seed, runs, b, time.time() - t0 + + spawn_diffs, varying = [], [] + with ThreadPoolExecutor(args.jobs) as pool: + for seed, runs, b, took in pool.map(one, all_seeds): + ok = b in runs + if not ok: + spawn_diffs.append(seed) + elif len(set(runs)) > 1: + varying.append(seed) + seen = ', '.join(' '.join(map(str, r)) for r in dict.fromkeys(runs)) + print(f'{"ok " if ok else "DIFF"} {seed}: vanilla {seen} / horizon {b[0]} {b[1]} {b[2]} ' + f'(origin chunk {vanilla[seed][2]} {vanilla[seed][3]}; {took:.0f}s)', flush=True) + if ok: + for path in build.glob(f'*-{seed}*'): + shutil.rmtree(path, ignore_errors=True) + print(f'World spawns: {len(all_seeds) - len(spawn_diffs)}/{len(all_seeds)} seeds match in {time.time() - started:.0f}s' + + (f'; vanilla itself gave several spawns for {len(varying)}: {varying}' if varying else '')) + if origin_diffs or spawn_diffs: + sys.exit(1) + + +if __name__ == '__main__': + main() From a3d32978407cead17b8749cbc739fdc7e6be885a Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:15:45 +0200 Subject: [PATCH 3/5] Apply the entity hurt/white overlay in vanilla's order entity.fsh mixes the OverlayTexture texel into the textured, cardinal-lit colour and only then multiplies by the lightmap. Horizon applied the lightmap first and mixed a 0.3 red into the vertex colour, so the red was multiplied by the texture and never darkened: hurt mobs glowed red at night and in caves. The vertex stage now passes the lightmap colour and the overlay texel (0xB2FF0000 hurt red, white alpha 63 for OverlayTexture.u(1.0)) to the fragment stage, which mixes the overlay, then the lightmap, then glint and fog. Layers vanilla submits with OverlayTexture.NO_OVERLAY no longer take the hurt tint: armour (EquipmentLayerRenderer, glint stays), held items (ItemInHandLayer) and the enderman's block (CarriedBlockLayer). The TNT minecart flash uses the white overlay on the cart's light (TntMinecartRenderer.submitWhiteSolidBlock) instead of plain full-bright white. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/entity.wgsl | 36 +++++++++++++------- crates/horizon-client/src/game/minecarts.rs | 4 +-- crates/horizon-client/src/game/mob_blocks.rs | 15 ++------ crates/horizon-client/src/mobs/render.rs | 14 ++++---- 4 files changed, 35 insertions(+), 34 deletions(-) diff --git a/crates/horizon-client/src/entity.wgsl b/crates/horizon-client/src/entity.wgsl index 70481acb5..18cb01230 100644 --- a/crates/horizon-client/src/entity.wgsl +++ b/crates/horizon-client/src/entity.wgsl @@ -31,13 +31,16 @@ struct Out { @location(1) color: vec4, @location(2) spherical: f32, @location(3) cylindrical: f32, - @location(5) flash: f32, + // entity.vsh's overlayColor: the OverlayTexture texel (see overlay_texel). + @location(5) overlay_color: vec4, @location(4) @interpolate(flat) overlay: u32, // Overlay 6: the sprite's v origin and height, for v repeated inside it. @location(6) @interpolate(flat) wrap: vec2, // Overlays 9 and 10: projection_from_position(gl_Position), the End portal's texProj0. @location(7) proj: vec4, @location(8) back_color: vec4, + // entity.vsh's lightMapColor, multiplied in after the overlay. + @location(9) light_color: vec4, } // Shipped light.glsl; normals are already transformed and RGBA8_SNORM packed. fn entity_light(normal: vec3, nether: bool) -> f32 { @@ -45,6 +48,14 @@ fn entity_light(normal: vec3, nether: bool) -> f32 { let l1 = normalize(vec3(-0.2, select(1.0, -1.0, nether), 0.7)); return min(1.0, (max(0.0, dot(l0, normal)) + max(0.0, dot(l1, normal))) * 0.6 + 0.4); } +// The OverlayTexture texel entity.vsh fetches: rows 0-7 hold the hurt red +// 0xB2FF0000; row 10 is white with alpha (1 - u / 15 * 0.75) * 255, u = 15 +// for the primed TNT flash (OverlayTexture.u(1.0)), so 63. Alpha 1 changes nothing. +fn overlay_texel(overlay: u32) -> vec4 { + if overlay == 1u || overlay == 8u { return vec4(1.0, 0.0, 0.0, 178.0 / 255.0); } + if overlay == 5u { return vec4(1.0, 1.0, 1.0, 63.0 / 255.0); } + return vec4(1.0); +} @vertex fn vs_entity(@location(0) position: vec3, @location(1) uv: vec2, @location(2) overlay: u32, @location(3) color: vec4, @location(4) light: vec4, @location(5) normal: vec4) -> Out { var out: Out; @@ -54,24 +65,22 @@ fn entity_light(normal: vec3, nether: bool) -> f32 { let l = vec2(f32(light.y), f32(light.x)); let lm = textureSampleLevel(lightmap, lightmap_sampler, clamp(l / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); - // Celestial bodies, clouds, beacon beams and breaking cracks are unlit. - var c = select(color * lm, color, overlay == 2u || overlay == 4u || overlay == 6u || overlay == 11u || overlay == 12u); + // Celestial bodies, clouds, beacon beams, End portals and breaking cracks are unlit. + let unlit = overlay == 2u || overlay == 4u || overlay == 6u || overlay == 9u || overlay == 10u + || overlay == 11u || overlay == 12u; + out.light_color = select(lm, vec4(1.0), unlit); // Overlay 6 (beacon beams): the light bytes carry the sprite's v range. out.wrap = vec2(f32(light.x | (light.y << 8u)), f32(light.z | (light.w << 8u))) / 65535.0; + // minecraft_mix_light: the vertex colour times the cardinal light only. + var c = color; var back = c; if normal.w != 0.0 { c = vec4(c.rgb * entity_light(normal.xyz, globals.time.y != 0.0), c.a); back = select(c, vec4(back.rgb * entity_light(-normal.xyz, globals.time.y != 0.0), back.a), normal.w < 0.0); } - // Hurt overlay (OverlayTexture red tint). - if overlay == 1u || overlay == 8u { - c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); - back = vec4(mix(back.rgb, vec3(1.0, 0.0, 0.0), 0.3), back.a); - } out.color = c; out.back_color = back; - // Overlay 5: OverlayTexture white flash (primed TNT), applied after texturing. - out.flash = select(0.0, 0.75, overlay == 5u); + out.overlay_color = overlay_texel(overlay); // Sky geometry (clouds, celestial bodies) is exempt from render-distance fog. out.spherical = select(length(position), 0.0, overlay >= 2u && overlay <= 4u); out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u && overlay <= 4u); @@ -140,7 +149,10 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { return vec4(color.rgb, color.a * (1.0 - linear_fog(in.spherical, 0.0, globals.fog_ends.y))); } if color.a < 0.1 { discard; } - color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a); + // entity.fsh calculateFinalColor: the overlay (hurt red, TNT white) over the + // lit texture, then the lightmap, then the glint and fog. + color = vec4(mix(in.overlay_color.rgb, color.rgb, in.overlay_color.a), color.a); + color *= in.light_color; if in.overlay == 7u || in.overlay == 8u { // Enchantment glint (overlay 7, 8 with the hurt tint): the purple // enchanted_glint sheen drifting diagonally over the item's shape. @@ -158,6 +170,6 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 { } @fragment fn fs_celestial(in: Out) -> @location(0) vec4 { - let color = textureSample(atlas, atlas_sampler, in.uv) * in.color; + let color = textureSample(atlas, atlas_sampler, in.uv) * in.color * in.light_color; return color; } diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 62d90648b..c14931e14 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -1240,9 +1240,9 @@ impl Game<'_> { let start = out.len(); self.block_model_vertices(state, m, packed, out); if flash { + // submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light. for v in &mut out[start..] { - v.color = 0xFFFF_FFFF; - v.light = 240 | 240 << 8; + v.layer = 5; } } } diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 52ea5df43..1e5942ef1 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -216,14 +216,13 @@ impl Game<'_> { light: u32, out: &mut Vec, ) { - let overlay = u32::from(mob.hurt_time > 0); self.captain_banner_geometry(mob, camera, alpha, light, out); self.held_item_geometry(mob, camera, alpha, light, true, out); if mob.species() == Species::Enderman && let Some(state) = mob.extra.carried && let Some((sprite, tint)) = self.particle_sprite(state) { - // CarriedBlockLayer. + // CarriedBlockLayer: OverlayTexture.NO_OVERLAY, never the hurt tint. let base = render::base_transform(mob, alpha as f32, camera); let t = base * glam::Mat4::from_translation(glam::Vec3::new(0.0, 0.6875, -0.75)) @@ -240,7 +239,7 @@ impl Game<'_> { tint, }, light, - overlay, + 0, out, ); } @@ -257,7 +256,7 @@ impl Game<'_> { lit: bool, out: &mut Vec, ) { - let overlay = u32::from(mob.hurt_time > 0); + // ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint. for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { let Some(item) = item else { continue }; let Some(t) = @@ -297,19 +296,11 @@ impl Game<'_> { // `updateForLiving`: seeded by the entity id plus the context ordinal. let seed = mob.id as i32 + if left { 1 } else { 2 }; let state = self.resolve_item(&stack, context, Some(&owner), seed); - let start = out.len(); if lit { self.submit_item_world(&state, t, light, out); } else { self.submit_item_unlit(&state, t, light, out); } - if overlay != 0 { - for v in &mut out[start..] { - if v.layer == 0 { - v.layer = overlay; - } - } - } } } } diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index ef45ffb46..266a1f4dd 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -977,10 +977,12 @@ fn render_visible( } else { light }; - let overlay = if armor_slot(&layer.model).is_some_and(|s| super::gear::enchanted(m, s)) { - glint_overlay(overlay) - } else { - overlay + // EquipmentLayerRenderer draws armour with OverlayTexture.NO_OVERLAY: never + // the hurt tint, the glint (7) when enchanted. + let overlay = match armor_slot(&layer.model) { + Some(slot) if super::gear::enchanted(m, slot) => 7, + Some(_) => 0, + None => overlay, }; let start = out.len(); draw(&part, base, &poses, uv, layer.color, light, overlay, out); @@ -1001,10 +1003,6 @@ fn armor_slot(model: &str) -> Option { _ => return None, }) } -/// The entity shader's glint overlay (7), keeping the hurt tint (8). -fn glint_overlay(overlay: u32) -> u32 { - if overlay == 1 { 8 } else { 7 } -} /// Render with a fixed texture rect (the earlier API). pub fn render_single( m: &Mob, From 3f61995c8b7b75beb875b292aadbc5c72c2a8406 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 14 Oct 2026 17:15:45 +0200 Subject: [PATCH 4/5] test(entity_model): compare per-vertex normals with vanilla The entity model parity harness now draws each posed model on both sides under LivingEntityRenderer's root transform (body yaw, scale(-1, -1, 1), the renderer's own scale) and compares every vertex's normal as the signed bytes written to the vertex buffer: vanilla's ModelPart.render / Cube.compile / PoseStack.Pose.transformNormal into a capturing VertexConsumer, packed with BufferBuilder's own normalIntValue, against Horizon's mobs::render::draw RGBA8_SNORM normals. A part-scale override covers negative and non-uniform part scales (trusted sign flips and untrusted 1/scale normalisation). A one-step difference is accepted only where vanilla's float sits at a truncation step; a posed position checksum per drawn part is compared too. Co-Authored-By: Claude Opus 5.5 --- .../examples/entity_anim_fixture.rs | 89 ++++++++++++- .../parity/VanillaEntityAnimOracle.java | 117 +++++++++++++++++- tools/test_entity_model_parity.py | 111 ++++++++++++++++- 3 files changed, 308 insertions(+), 9 deletions(-) diff --git a/crates/horizon-client/examples/entity_anim_fixture.rs b/crates/horizon-client/examples/entity_anim_fixture.rs index 6bec66a68..663bc288a 100644 --- a/crates/horizon-client/examples/entity_anim_fixture.rs +++ b/crates/horizon-client/examples/entity_anim_fixture.rs @@ -1,14 +1,17 @@ //! Replays the render states of the vanilla entity-animation oracle through -//! Horizon's `mobs::anim::setup` and writes every part's pose. +//! Horizon's `mobs::anim::setup` and writes every part's pose, then draws the +//! posed model with `mobs::render::draw` under the case's living-entity root +//! transform and writes each drawn part's packed vertex normals. //! //! cargo run --profile fast -p horizon-client --example entity_anim_fixture -- \ //! RESOURCES VANILLA.jsonl OUT.jsonl +use horizon_client::mesher::Vertex; use horizon_client::mobs::{ Mob, MobData, MobTypes, Part, Species, allay, anim::{self, Poses, State}, aquatic, body_anim as b_anim, equine, guardian, keyframes::AnimationState, - shulker, sniffer, species, tame, + render, shulker, sniffer, species, tame, }; use horizon_core::geometry::Vec3; use serde_json::{Value, json}; @@ -44,6 +47,61 @@ fn walk(part: &Part, path: &str, poses: &Poses, out: &mut BTreeMap