Mining: the block-removal harness mines blocks as a survival player

test_block_removal_parity gains a "mine" removal: VanillaDispenserOracle
calls the real ServerPlayerGameMode.destroyBlock for a survival player holding
a pickaxe, axe, shovel, sword, shears, a mace or nothing, and Horizon's
dispense fixture calls break_block, the path every player's mining takes (the
single player game, the server thread and LAN guests). It compares the drops,
the spilled contents, experience, sounds, events, statistics and the held
stack. On main it shows every mined container losing its contents (#844, fixed
by #855) and three gaps of Horizon's own, fixed here:

- ItemStack.mineBlock: an item with a tool component counts as used, and wears
  its damage_per_block (2 for swords, the mace and the trident), also the mace
  and trident, whose tool component has no rules. Shears wear on every block
  but fire (ShearsItem.mineBlock).
- DecoratedPotBlock.playerWillDestroy: a pot mined with an item in
  breaks_decorated_pots, unless an enchantment prevents it, cracks first and
  shatters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-18 14:40:56 +02:00
parent 6d238a89c5
commit 62cacfa607
5 changed files with 221 additions and 28 deletions
+71 -18
View File
@@ -2505,6 +2505,75 @@ impl Game<'_> {
}
Ok(())
}
/// `DecoratedPotBlock.playerWillDestroy`: a pot mined with an item in
/// `breaks_decorated_pots`, unless an enchantment prevents shattering, is
/// cracked first (flags 260), so it shatters into its sherds.
fn crack_mined_pot(&mut self, pos: [i32; 3], state: BlockStateId) -> BlockStateId {
let registry = &self.pack.assets.registry;
let Some(mut pot) = registry
.state(state)
.filter(|s| s.name == "minecraft:decorated_pot")
.cloned()
else {
return state;
};
let Some(held) = self.held() else {
return state;
};
let breaks = self
.res
.items
.item_tags
.get("minecraft:breaks_decorated_pots")
.is_some_and(|t| t.contains(&*held.item));
let enchantments = &self.res.stations.enchantments;
let kept = held
.enchantments()
.iter()
.any(|(e, _)| enchantments.in_tag("minecraft:prevents_decorated_pot_shattering", e));
if !breaks || kept {
return state;
}
pot.properties.insert("cracked".into(), "true".into());
let Ok(cracked) = registry.resolve(&pot) else {
return state;
};
let at = BlockPos::new(pos[0], pos[1], pos[2]);
self.with_level(|b, level, ticks| b.set_block(level, ticks, at, cracked, 260));
cracked
}
/// `ItemStack.mineBlock` for the held stack once a survival player has
/// mined the block `name`: an item with a `tool` component counts as used
/// and loses its `damage_per_block` on a block that doesn't break
/// instantly (`ShearsItem`: on any block but fire).
fn mine_block_with_held(&mut self, name: &str, hardness: f32) {
let Some(stack) = self.inventory[self.selected].clone() else {
return;
};
let Some((per_block, max)) = self
.res
.items
.get(&stack.item)
.and_then(|i| Some((i.tool_damage_per_block?, i.max_damage)))
else {
return;
};
let wears = if &*stack.item == "minecraft:shears" {
!self.res.items.block_in_tag("minecraft:fire", name)
} else {
hardness != 0.0
};
if wears && per_block > 0 && max > 0 {
let loss = self.durability_loss(&stack, per_block);
if let Some(held) = self.inventory[self.selected].as_mut() {
held.damage += loss;
if held.damage >= max {
self.inventory[self.selected] = None;
}
}
}
self.stats.add("used", &stack.item, 1);
}
fn break_block(&mut self, pos: [i32; 3]) -> Result<()> {
self.with_player_actor(|game| game.break_block_as_player(pos))
}
@@ -2513,6 +2582,7 @@ impl Game<'_> {
// ServerPlayerGameMode.destroyBlock.
let state = self.world.block(pos[0], pos[1], pos[2]);
let facts = self.res.facts.get(state).clone();
let state = self.crack_mined_pot(pos, state);
// Block.playerWillDestroy: mining their gold angers all nearby piglins.
if self.guarded_by_piglins(&facts.name) {
self.anger_piglins(false);
@@ -2544,24 +2614,7 @@ impl Game<'_> {
});
if removed && !creative {
let held = self.held().cloned();
// ItemStack.mineBlock: tools lose durability on blocks with nonzero hardness.
if facts.hardness > 0.0
&& let Some(stack) = self.inventory[self.selected].clone()
&& let Some(max) = self
.res
.items
.get(&stack.item)
.filter(|i| i.max_damage > 0 && !i.tool.is_empty())
.map(|i| i.max_damage)
{
let loss = self.durability_loss(&stack, 1);
if let Some(stack) = self.inventory[self.selected].as_mut() {
stack.damage += loss;
if stack.damage >= max {
self.inventory[self.selected] = None;
}
}
}
self.mine_block_with_held(&facts.name, facts.hardness);
let harvest = !facts.requires_tool
|| self.res.items.correct_for_drops(held.as_ref(), &facts.name);
if harvest {
@@ -284,7 +284,7 @@ impl Game<'_> {
let state = self.world.block(origin.x, origin.y, origin.z);
let mut used = Vec::new();
if let Some(op) = case.get("remove") {
self.fixture_remove(origin, op)?;
used = 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") {
@@ -788,8 +788,9 @@ impl Game<'_> {
other => *other = Tag::List(vec![item]),
}
}
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block.
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> {
/// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block, or
/// a player mining it (`fixture_mine`).
fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<Vec<String>> {
match op["op"].as_str().unwrap_or("") {
"set" => {
let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32);
@@ -803,9 +804,61 @@ impl Game<'_> {
"remove" => {
self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false));
}
"mine" => return self.fixture_mine(origin, op),
other => return Err(format!("unknown removal {other}").into()),
}
self.process_level_events()
self.process_level_events()?;
Ok(Vec::new())
}
/// A survival player three blocks south of `pos` mines it holding the
/// case's item (`break_block`, which every player's mining goes through):
/// the statistics and the held stack, as `VanillaDispenserOracle.mine`
/// prints them.
fn fixture_mine(&mut self, pos: BlockPos, op: &Value) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.mode = GameMode::Survival;
self.creative = false;
self.player = Some(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,
),
)?);
self.yaw = 0.0;
self.pitch = 90.0;
self.keys.clear();
self.inventory[self.selected] = stack.clone();
self.offhand = None;
let state = self.world.block(pos.x, pos.y, pos.z);
let block = self.res.facts.get(state).name.clone();
let item = stack.as_ref().map(|s| s.item.clone());
let before = |game: &Self| {
let used = item.as_ref().map_or(0, |i| game.stats.get("used", i));
(used, game.stats.get("mined", &block))
};
let (used, mined) = before(self);
self.break_block([pos.x, pos.y, pos.z])?;
let (used_after, mined_after) = before(self);
let mut out = Vec::new();
if let Some(item) = &item
&& used_after != used
{
out.push(format!("stat {item} minecraft:used {}", used_after - used));
}
if mined_after != mined {
out.push(format!(
"stat {block} minecraft:mined {}",
mined_after - mined
));
}
out.push(format!(
"mine held {}",
canon_stack(self.inventory[self.selected].as_ref())
));
Ok(out)
}
/// `EntityType.create` and `snapTo` for one target: no spawn finalization.
+10
View File
@@ -67,6 +67,9 @@ pub struct ItemInfo {
pub block: Option<BlockStateId>,
pub tool: Vec<ToolRule>,
pub tool_default_speed: f32,
/// The `tool` component's `damage_per_block`, when the item has the
/// component (a mace or trident has one without rules).
pub tool_damage_per_block: Option<u32>,
pub food: Option<(u32, f32)>,
pub can_always_eat: bool,
pub consumable: bool,
@@ -528,6 +531,9 @@ impl Items {
tool_default_speed: c["minecraft:tool"]["default_mining_speed"]
.as_f64()
.unwrap_or(1.0) as f32,
tool_damage_per_block: c
.get("minecraft:tool")
.map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32),
food,
can_always_eat,
consumable: c.get("minecraft:consumable").is_some(),
@@ -694,6 +700,10 @@ impl Items {
songs: HashMap::new(),
}
}
/// Whether `block` is in the block tag `tag` (`minecraft:fire`, no `#`).
pub fn block_in_tag(&self, tag: &str, block: &str) -> bool {
self.block_tags.get(tag).is_some_and(|s| s.contains(block))
}
fn block_matches(&self, spec: &str, block: &str) -> bool {
match spec.strip_prefix('#') {
Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)),
@@ -170,14 +170,82 @@ public final class VanillaDispenserOracle {
throw new IllegalStateException("no slots in " + be);
}
/** The removal a "remove" case runs on the block at its origin. */
static void remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) {
/** The removal a "remove" case runs on the block at its origin; a player's mining prints its statistics and held stack. */
static List<String> remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) throws Exception {
switch (op.get("op").getAsString()) {
case "set" -> w.setBlock(origin, Block.stateById(op.get("state").getAsInt()), op.get("flags").getAsInt());
case "destroy" -> w.destroyBlock(origin, op.get("drop").getAsBoolean());
case "remove" -> w.removeBlock(origin, false);
case "mine" -> {
return mine(w, origin, op);
}
default -> throw new IllegalStateException(op.toString());
}
return new ArrayList<>();
}
/**
* A survival player three blocks south of `pos` mines it holding the case's
* item: the real `ServerPlayerGameMode.destroyBlock` (playerWillDestroy,
* removeBlock with the block entity's side effects, mineBlock, playerDestroy's
* statistic, exhaustion and drops). The statistics and the held stack follow.
*/
static List<String> mine(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception {
Miner player = (Miner) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Miner.class);
player.world = w;
player.hand = stack(op.get("item").getAsString());
player.offhand = ItemStack.EMPTY;
player.stats = new ArrayList<>();
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", new net.minecraft.world.entity.player.Abilities());
VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", new net.minecraft.world.food.FoodData());
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);
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));
// PiglinAi.angerNearbyPiglins looks around the player's box (gold, chests, barrels...).
player.setBoundingBox(EntityTypes.PLAYER.getDimensions().makeBoundingBox(at));
var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player);
VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer",
net.minecraft.world.level.GameType.SURVIVAL);
gameMode.destroyBlock(pos);
List<String> out = new ArrayList<>(player.stats);
out.add("mine held " + ParityData.canon(player.hand));
return out;
}
/** The player of a "mine" case: a survival `Clicker` whose selected inventory slot is its main hand. */
static final class Miner extends net.minecraft.server.level.ServerPlayer {
VanillaBlockUpdateOracle.World world;
ItemStack hand, offhand;
List<String> stats;
Miner() {
super(null, null, null, null);
}
@Override public ServerLevel level() { return world; }
@Override public boolean hasInfiniteMaterials() { return false; }
@Override public boolean isCreative() { return false; }
@Override public boolean isSpectator() { return false; }
@Override public EntityType<?> getType() { return EntityTypes.PLAYER; }
@Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); }
@Override public ItemStack getItemBySlot(EquipmentSlot slot) {
return slot == EquipmentSlot.MAINHAND ? hand : slot == EquipmentSlot.OFFHAND ? offhand : ItemStack.EMPTY;
}
@Override public void setItemSlot(EquipmentSlot slot, ItemStack stack) {
if (slot == EquipmentSlot.MAINHAND) hand = stack; else if (slot == EquipmentSlot.OFFHAND) offhand = stack;
}
@Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) {
return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : offhand;
}
// Player.hasCorrectToolForDrops asks the inventory's selected slot: the main hand.
@Override public boolean hasCorrectToolForDrops(BlockState state) {
return !state.requiresCorrectToolForDrops() || hand.isCorrectToolForDrops(state);
}
@Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) {
stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count);
}
@Override public net.minecraft.server.players.NameAndId nameAndId() { return new net.minecraft.server.players.NameAndId(new UUID(0L, 0L), "Player"); }
}
static boolean hasList(Object be) {
@@ -324,7 +392,7 @@ public final class VanillaDispenserOracle {
BlockState state = w.getBlockState(origin);
List<String> used = new ArrayList<>();
if (f.has("remove")) {
remove(w, origin, f.getAsJsonObject("remove"));
used = remove(w, origin, f.getAsJsonObject("remove"));
} else if (f.has("use")) {
used = use(w, origin, f.getAsJsonObject("use"));
} else if (f.has("use_item")) {
+12 -3
View File
@@ -5,8 +5,9 @@ A container, jukebox, lectern, campfire, decorated pot, chiseled bookshelf,
shelf, shulker box or another block entity holder at the origin holds random
contents; the case then replaces it with `Level.setBlock` (another block, the
same block in another state, with or without UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS),
destroys it with `Level.destroyBlock` (with or without drops) or removes it with
`Level.removeBlock`. Vanilla runs over the headless level of the dispenser oracle
destroys it with `Level.destroyBlock` (with or without drops), removes it with
`Level.removeBlock`, or a survival player mines it (`ServerPlayerGameMode.destroyBlock`,
holding a tool or nothing, #844). Vanilla runs over the headless level of the dispenser oracle
(`VanillaDispenserOracle`, "remove" cases), which replays `LevelChunk.setBlockState`'s
`BlockEntity.preRemoveSideEffects`; Horizon runs its game glue in a headless game
(`HORIZON_DISPENSE_FIXTURE`). Both print the block changes, the contents left,
@@ -63,6 +64,10 @@ LISTED = {'chest', 'trapped_chest', 'barrel', 'hopper', 'dispenser', 'dropper',
REPLACEMENTS = ['air', 'stone', 'glass', 'water', 'oak_planks', 'barrel', 'chest', 'hopper', 'blue_shulker_box', 'dirt', 'tnt',
'copper_chest', 'oxidized_copper_chest', 'lectern', 'jukebox']
FLAGS = [3, 3, 3, 2, 18, 2 | 256, 816, 3 | 64, 1]
# What a mining player holds: the right tool, a tool too weak or of another kind (swords and maces
# wear 2 a block, shears any block but fire), or nothing.
TOOLS = [plain('diamond_pickaxe'), plain('wooden_pickaxe'), plain('stone_axe'), plain('iron_shovel'), plain('iron_sword'),
plain('shears'), plain('mace'), '-']
def contents(rng, name, slots, pool):
@@ -135,8 +140,12 @@ def cases(facts, count, seed, only):
op = {'op': 'destroy', 'drop': True}
elif roll < 0.85:
op = {'op': 'destroy', 'drop': False}
else:
elif roll < 0.92:
op = {'op': 'remove'}
else:
# ServerPlayerGameMode.destroyBlock: a survival player mines it (#844). The tool comes
# from the roll, not another draw, so the cases after this one stay the same.
op = {'op': 'mine', 'item': TOOLS[int(roll * 1000) % len(TOOLS)]}
case = {**h.environment(rng), 'mode': 'remove', 'pos': [0, 0, 0], 'cells': cells, 'items': items, 'remove': op}
case.pop('raining', None)
case.pop('thundering', None)