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 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-14 17:43:24 +02:00
parent 45663c9e39
commit 80645bf0de
8 changed files with 423 additions and 27 deletions
+48 -27
View File
@@ -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;
@@ -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<Vec<String>> {
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<ItemStack>) {
+11
View File
@@ -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)
+17
View File
@@ -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.
+27
View File
@@ -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<ItemStack> {
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,
@@ -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<L: LevelAccess + ?Sized>(
&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)
}
}