From ff28fd839036a7c3f88203a428bd6c23a92963f9 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:13:40 +0100 Subject: [PATCH 1/2] Read a chiseled bookshelf's last slot and a shelf's back mask with a comparator --- crates/horizon-client/src/game.rs | 7 +++- crates/horizon-client/src/game/machines.rs | 39 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7699e83d7..087b15dc7 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -700,7 +700,7 @@ impl LevelAccess for GameLevel<'_> { &self, pos: BlockPos, state: BlockStateId, - _direction: Direction, + direction: Direction, ) -> i32 { if let Some(signal) = command_blocks::analog_signal(self.world, (pos.x, pos.y, pos.z)) { return signal; @@ -725,6 +725,11 @@ impl LevelAccess for GameLevel<'_> { if let Some(signal) = books::lectern_signal(self.world, pos) { return signal; } + if let Some(signal) = + machines::shelf_signal(self.world, self.registry, state, pos, direction) + { + return signal; + } machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos) } fn block_entity_signal( diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index bb936744b..f398f4511 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -399,6 +399,45 @@ pub(super) fn container_signal( .map_or(0, |v| c.signal(&v)) } +/// `ChiseledBookShelfBlock.getAnalogOutputSignal` and +/// `ShelfBlock.getAnalogOutputSignal`, from the block entity Horizon keeps as +/// it was loaded; `None` for any other block. `direction` points from the +/// block to the comparator. +pub(super) fn shelf_signal( + world: &World, + registry: &'static horizon_world::registry::BlockRegistry, + state: BlockStateId, + pos: BlockPos, + direction: Direction, +) -> Option { + let info = registry.state(state)?; + let chiseled = info.name == "minecraft:chiseled_bookshelf"; + if !chiseled && !info.name.ends_with("_shelf") { + return None; + } + let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); + if chiseled { + // The last slot touched, plus one (`lastInteractedSlot` starts at -1). + let last = tag + .as_ref() + .and_then(|t| horizon_client::save::number(t.get("last_interacted_slot"))); + return Some(last.map_or(0, |slot| slot as i32 + 1)); + } + // Only read from the back: a bit for each of the three slots in use. + let facing = info.properties.get("facing").and_then(|f| dir_from_name(f)); + if facing.map(Direction::opposite) != Some(direction) { + return Some(0); + } + let items = horizon_client::save::decode_items(tag.as_ref().and_then(|t| t.get("Items")), 3); + Some( + items + .iter() + .enumerate() + .map(|(slot, item)| i32::from(item.is_some()) << slot) + .sum(), + ) +} + impl Game<'_> { fn containers(&self) -> Containers<'_> { Containers { From 2f6d259615028dd45859893d29936db1aa7ec4f5 Mon Sep 17 00:00:00 2001 From: Kacpherek Date: Tue, 27 Oct 2026 06:38:17 +0100 Subject: [PATCH 2/2] Put books into a chiseled bookshelf and take them out Horizon only kept a chiseled bookshelf's saved data, so using it did nothing. It is now a block entity with six slots and lastInteractedSlot: - ChiseledBookShelfBlock.useItemOn / useWithoutItem: the slot comes from the hit position on the front face (getHitSlot, 3x2). A #bookshelf_books item goes into an empty slot (one book, the insert sounds, the used statistic), a book comes out to the inventory or the ground, with the pickup sounds. The slot_N_occupied states follow (ChiseledBookShelfBlockEntity.updateState) and reach a server's clients with the block update; the client's prediction ends the click the same way. - Hoppers and droppers use its container: books only, one to a slot, and the occupied state and last slot follow what they moved. - The comparator reads lastInteractedSlot from the block entity. --- crates/horizon-client/src/containers.rs | 23 +++ crates/horizon-client/src/game.rs | 13 +- .../src/game/chiseled_bookshelf.rs | 178 ++++++++++++++++++ crates/horizon-client/src/game/machines.rs | 26 ++- crates/horizon-client/src/save.rs | 12 ++ crates/horizon-world/src/level/data.rs | 6 + crates/horizon-world/src/level/interact.rs | 59 ++++++ crates/horizon-world/src/level/mod.rs | 2 +- 8 files changed, 310 insertions(+), 9 deletions(-) create mode 100644 crates/horizon-client/src/game/chiseled_bookshelf.rs diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 8ca9af0ad..765c6b343 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -101,6 +101,22 @@ pub enum BlockEntity { /// `DaylightDetectorBlockEntity`: no data, only the ticker /// (`DaylightDetectorBlock.tickEntity`). DaylightDetector, + /// `ChiseledBookShelfBlockEntity`: a `Container` of six one-book slots. + ChiseledBookshelf(Box), +} +/// `ChiseledBookShelfBlockEntity`: six slots and `lastInteractedSlot`. +#[derive(Clone, Debug, PartialEq)] +pub struct ChiseledBookshelf { + pub items: [Option; 6], + pub last_slot: i32, +} +impl Default for ChiseledBookshelf { + fn default() -> Self { + Self { + items: Default::default(), + last_slot: -1, + } + } } /// `CampfireBlockEntity`: four cooking slots, each with its /// `cookingProgress` and `cookingTime` (the recipe's). @@ -381,6 +397,9 @@ impl BlockEntity { if name == "minecraft:campfire" || name == "minecraft:soul_campfire" { return Some(Self::Campfire(Box::default())); } + if name == "minecraft:chiseled_bookshelf" { + return Some(Self::ChiseledBookshelf(Box::default())); + } let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, @@ -420,6 +439,7 @@ impl BlockEntity { Self::Skull(_) => "minecraft:skull", Self::DaylightDetector => "minecraft:daylight_detector", Self::Campfire(_) => "minecraft:campfire", + Self::ChiseledBookshelf(_) => "minecraft:chiseled_bookshelf", } } pub fn contents(&self) -> Vec { @@ -443,6 +463,7 @@ impl BlockEntity { Self::Banner(_) => Vec::new(), Self::Crafter(c) => c.items.iter().flatten().cloned().collect(), Self::Campfire(c) => c.items.iter().flatten().cloned().collect(), + Self::ChiseledBookshelf(b) => b.items.iter().flatten().cloned().collect(), } } pub fn slots(&self) -> &[Option] { @@ -459,6 +480,7 @@ impl BlockEntity { | Self::Skull(_) | Self::DaylightDetector => &[], Self::Crafter(c) => &c.items, + Self::ChiseledBookshelf(b) => &b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) @@ -483,6 +505,7 @@ impl BlockEntity { | Self::Skull(_) | Self::DaylightDetector => &mut [], Self::Crafter(c) => &mut c.items, + Self::ChiseledBookshelf(b) => &mut b.items, Self::CreakingHeart(_) | Self::Spawner(_) | Self::TrialSpawner(_) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 087b15dc7..0435b6043 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -23,6 +23,7 @@ mod campfire; mod campfire_douse; mod cartography; mod chat; +mod chiseled_bookshelf; mod client_ambient; mod clipboard; mod combat; @@ -3822,6 +3823,12 @@ impl Game<'_> { self.swing_arm(); return Ok(true); } + if let Some(swings) = self.use_chiseled_bookshelf(hit, held.as_ref()) { + if swings { + self.swing_arm(); + } + return Ok(true); + } if self.use_composter(hit.pos, held.as_ref()) { self.swing_arm(); return Ok(true); @@ -5657,7 +5664,8 @@ impl Game<'_> { | BlockEntity::CommandBlock(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None => { v.extend((0..self.craft_size * self.craft_size).map(|i| 100 + i)); @@ -5929,7 +5937,8 @@ impl Game<'_> { | BlockEntity::CommandBlock(_) | BlockEntity::Skull(_) | BlockEntity::DaylightDetector - | BlockEntity::Campfire(_), + | BlockEntity::Campfire(_) + | BlockEntity::ChiseledBookshelf(_), ) => {} None if self.mount_active() => self.draw_mount_background(batch, ox, oy), None => { diff --git a/crates/horizon-client/src/game/chiseled_bookshelf.rs b/crates/horizon-client/src/game/chiseled_bookshelf.rs new file mode 100644 index 000000000..5d383b4ea --- /dev/null +++ b/crates/horizon-client/src/game/chiseled_bookshelf.rs @@ -0,0 +1,178 @@ +//! Chiseled bookshelves: `ChiseledBookShelfBlock.useItemOn` / `useWithoutItem` +//! (a book into the slot under the crosshair, or out of it) and +//! `ChiseledBookShelfBlockEntity.updateState`, which also follows the books a +//! hopper or dropper moved (`machines::container_changed`). The slots' books +//! show through the block state's `slot_N_occupied`, which reaches a server's +//! clients with the block update. +use super::{Game, Hit, machines::dir_from_name}; +use horizon_client::{containers::BlockEntity, items::ItemStack, mobs::Who}; +use horizon_core::{ + geometry::{Direction, Vec3}, + position::BlockPos, +}; +use horizon_world::level::{flags, hit_slot}; + +const BLOCK: &str = "minecraft:chiseled_bookshelf"; + +impl Game<'_> { + /// `useItemOn` with `held` in the acting hand, then `useWithoutItem` on + /// the main hand's turn: None when the block passes the click, else + /// whether the use succeeded and the arm swings (a click on an empty slot + /// without a book only consumes it). + pub(super) fn use_chiseled_bookshelf( + &mut self, + hit: &Hit, + held: Option<&ItemStack>, + ) -> Option { + let pos = hit.pos; + let state = self.world.block(pos[0], pos[1], pos[2]); + let info = self + .pack + .assets + .registry + .state(state) + .filter(|s| s.name == BLOCK)?; + let facing = info + .properties + .get("facing") + .and_then(|f| dir_from_name(f))?; + let face = Direction::ALL + .into_iter() + .find(|d| d.normal() == hit.face)?; + let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]); + let slot = hit_slot( + facing, + face, + BlockPos::new(pos[0], pos[1], pos[2]), + at, + 2, + 3, + )?; + let occupied = info + .properties + .get(&format!("slot_{slot}_occupied")) + .map(String::as_str) + == Some("true"); + let book = held.filter(|s| { + self.res + .items() + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*s.item)) + }); + let centre = pos.map(|v| f64::from(v) + 0.5); + if let Some(book) = book + && !occupied + { + // addBook: one book goes in (a creative player keeps theirs). + let book = book.clone(); + self.stats.add("used", &book.item, 1); + let sound = if &*book.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.insert.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.insert" + }; + self.bookshelf_items(pos)?[slot] = Some(ItemStack { + count: 1, + ..book.clone() + }); + self.consume_held(); + self.chiseled_bookshelf_update_state(pos, slot); + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.trigger_block("minecraft:item_used_on_block", pos, &book); + return Some(true); + } + // TRY_WITH_EMPTY_HAND: only the main hand goes on to useWithoutItem. + if self.hand != horizon_client::first_person::Hand::Main { + return None; + } + if !occupied { + return Some(false); + } + // removeBook: the book goes to the inventory, or is dropped. + let retrieved = self.bookshelf_items(pos)?[slot].take()?; + self.chiseled_bookshelf_update_state(pos, slot); + let sound = if &*retrieved.item == "minecraft:enchanted_book" { + "minecraft:block.chiseled_bookshelf.pickup.enchanted" + } else { + "minecraft:block.chiseled_bookshelf.pickup" + }; + self.audio.play(sound, Some(centre), 1.0, 1.0); + self.give_or_drop(retrieved); + self.post_block_game_event("minecraft:block_change", pos, Some(Who::Player), None); + Some(true) + } + + /// The bookshelf's six slots (made if the block has no block entity yet). + fn bookshelf_items(&mut self, pos: [i32; 3]) -> Option<&mut [Option; 6]> { + let entity = self + .world + .block_entities + .get_or_insert_with((pos[0], pos[1], pos[2]), || { + BlockEntity::ChiseledBookshelf(Box::default()) + }); + match entity { + BlockEntity::ChiseledBookshelf(b) => Some(&mut b.items), + _ => None, + } + } + + /// `ChiseledBookShelfBlockEntity.updateState`: `slot` becomes the last + /// one touched, the block state takes the slots' occupancy + /// (`setBlockAndUpdate`) and `BLOCK_CHANGE` goes out. + fn chiseled_bookshelf_update_state(&mut self, pos: [i32; 3], slot: usize) { + let key = (pos[0], pos[1], pos[2]); + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get_mut(&key) + else { + return; + }; + b.last_slot = slot as i32; + let occupied: Vec = b.items.iter().map(Option::is_some).collect(); + let registry = self.pack.assets.registry; + let Some(mut state) = registry + .state(self.world.block(pos[0], pos[1], pos[2])) + .cloned() + else { + return; + }; + for (i, occupied) in occupied.into_iter().enumerate() { + state + .properties + .insert(format!("slot_{i}_occupied"), occupied.to_string()); + } + let Some(new) = registry.id(&state) else { + return; + }; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, new, flags::UPDATE_ALL)); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.post_block_game_event("minecraft:block_change", pos, None, Some(new)); + } + + /// The books a hopper or dropper put in or took out: the slot whose + /// occupancy no longer matches the block state is the one `setItem` or + /// `removeItem` updated. + pub(super) fn chiseled_bookshelf_synced(&mut self, pos: (i32, i32, i32)) { + let Some(BlockEntity::ChiseledBookshelf(b)) = self.world.block_entities.get(&pos) else { + return; + }; + let Some(info) = self + .pack + .assets + .registry + .state(self.world.block(pos.0, pos.1, pos.2)) + else { + return; + }; + let moved = (0..6).rev().find(|i| { + let shown = info + .properties + .get(&format!("slot_{i}_occupied")) + .map(String::as_str); + b.items[*i].is_some() != (shown == Some("true")) + }); + if let Some(slot) = moved { + self.chiseled_bookshelf_update_state([pos.0, pos.1, pos.2], slot); + } + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index f398f4511..fe1b64f65 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -41,6 +41,8 @@ enum Kind { Crafter, /// `BrewingStandBlockEntity` (a `WorldlyContainer`). Brewing, + /// `ChiseledBookShelfBlockEntity`: books only, one to a slot. + Bookshelf, /// `ComposterBlock.getContainer` at this level (a `WorldlyContainerHolder` /// without a block entity): input below 7, empty at 7, bone meal at 8. Composter(i32), @@ -82,7 +84,7 @@ impl View { } } -fn dir_from_name(name: &str) -> Option { +pub(super) fn dir_from_name(name: &str) -> Option { Some(match name { "down" => Direction::Down, "up" => Direction::Up, @@ -169,6 +171,7 @@ impl Containers<'_> { (BlockEntity::Furnace(_), _) => Kind::Furnace, (BlockEntity::Crafter(_), _) => Kind::Crafter, (BlockEntity::Brewing(_), _) => Kind::Brewing, + (BlockEntity::ChiseledBookshelf(_), _) => Kind::Bookshelf, (_, "minecraft:hopper") => Kind::Hopper, _ => Kind::Generic, }; @@ -250,6 +253,16 @@ impl Containers<'_> { _ => false, }; } + if view.kind == Kind::Bookshelf { + // ListBackedContainer.canPlaceItem: `acceptsItemType` (the books) + // and a free slot, as `getMaxStackSize` is 1. + return self + .items + .item_tags + .get("minecraft:bookshelf_books") + .is_some_and(|m| m.contains(&*stack.item)) + && self.get(view, slot).is_none(); + } if view.kind == Kind::Brewing { // BrewingStandBlockEntity.canPlaceItem return match slot { @@ -415,14 +428,14 @@ pub(super) fn shelf_signal( if !chiseled && !info.name.ends_with("_shelf") { return None; } - let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); if chiseled { // The last slot touched, plus one (`lastInteractedSlot` starts at -1). - let last = tag - .as_ref() - .and_then(|t| horizon_client::save::number(t.get("last_interacted_slot"))); - return Some(last.map_or(0, |slot| slot as i32 + 1)); + return Some(match world.block_entities.get(&(pos.x, pos.y, pos.z)) { + Some(BlockEntity::ChiseledBookshelf(b)) => b.last_slot + 1, + _ => 0, + }); } + let tag = super::spill::saved_entity(world, [pos.x, pos.y, pos.z]); // Only read from the back: a bit for each of the three slots in use. let facing = info.properties.get("facing").and_then(|f| dir_from_name(f)); if facing.map(Direction::opposite) != Some(direction) { @@ -472,6 +485,7 @@ impl Game<'_> { if pos.1 == super::minecarts::CART_KEY_Y { return; } + self.chiseled_bookshelf_synced(pos); // A double chest's other half changes with it. let halves: Vec = std::iter::once(pos) .chain(self.chest_other_half(pos)) diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index dc08d90b0..df2aebc87 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -599,6 +599,11 @@ pub fn encode_block_entity( } } BlockEntity::Sculk(s) => entries.extend(s.to_nbt()), + // ChiseledBookShelfBlockEntity.saveAdditional. + BlockEntity::ChiseledBookshelf(b) => { + entries.push(("Items", encode_items(&b.items))); + entries.push(("last_interacted_slot", Tag::Int(b.last_slot))); + } // CampfireBlockEntity.saveAdditional. BlockEntity::Campfire(c) => { entries.push(("Items", encode_items(&c.items))); @@ -814,6 +819,13 @@ pub fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::contain } BlockEntity::Sign(sign) => sign.decode(tag), BlockEntity::Sculk(s) => s.load(tag), + // ChiseledBookShelfBlockEntity.loadAdditional. + BlockEntity::ChiseledBookshelf(b) => { + for (slot, item) in decode_items(tag.get("Items"), 6).into_iter().enumerate() { + b.items[slot] = item; + } + b.last_slot = int("last_interacted_slot").unwrap_or(-1); + } // CampfireBlockEntity.loadAdditional: missing time arrays stay zeros. BlockEntity::Campfire(c) => { for (slot, item) in decode_items(tag.get("Items"), 4).into_iter().enumerate() { diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 4635e8b05..cda834217 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -571,6 +571,12 @@ props! { orientation = "orientation", crafting = "crafting", side_chain = "side_chain", + slot_0_occupied = "slot_0_occupied", + slot_1_occupied = "slot_1_occupied", + slot_2_occupied = "slot_2_occupied", + slot_3_occupied = "slot_3_occupied", + slot_4_occupied = "slot_4_occupied", + slot_5_occupied = "slot_5_occupied", copper_golem_pose = "copper_golem_pose", sculk_sensor_phase = "sculk_sensor_phase", shrieking = "shrieking", diff --git a/crates/horizon-world/src/level/interact.rs b/crates/horizon-world/src/level/interact.rs index 831dea544..ccf4c69a2 100644 --- a/crates/horizon-world/src/level/interact.rs +++ b/crates/horizon-world/src/level/interact.rs @@ -24,6 +24,44 @@ impl InteractionResult { } } +/// `SelectableSlotContainer.getHitSlot`: the slot of a block with `rows` by +/// `columns` slots on its front face (the way it `facing`) that the click at +/// `hit` on `face` of the block at `pos` lands in, if it is the front face. +pub fn hit_slot( + facing: Direction, + face: Direction, + pos: BlockPos, + hit: Vec3, + rows: i32, + columns: i32, +) -> Option { + if facing != face { + return None; + } + // The location relative to the block in front of the face, which only + // moves the axis the face points along: the others are the block's own. + let (dx, dy, dz) = ( + hit.x - f64::from(pos.x), + hit.y - f64::from(pos.y), + hit.z - f64::from(pos.z), + ); + let (x, y) = match face { + Direction::North => ((1.0 - dx) as f32, dy as f32), + Direction::South => (dx as f32, dy as f32), + Direction::West => (dz as f32, dy as f32), + Direction::East => ((1.0 - dz) as f32, dy as f32), + Direction::Down | Direction::Up => return None, + }; + // getSection + let section = |relative: f32, sections: i32| { + let size = 16.0f32 / sections as f32; + ((relative * 16.0f32 / size).floor() as i32).clamp(0, sections - 1) + }; + let row = section(1.0 - y, rows); + let column = section(x, columns); + Some((column + row * columns) as usize) +} + /// The interacting player, as far as block behaviour needs it. #[derive(Clone, Copy, Debug)] pub struct PlayerContext { @@ -326,6 +364,27 @@ impl Sim<'_, L> { Consume } } + Class::ChiseledBookShelf => { + // useItemOn and useWithoutItem agree on what a click takes: no + // slot under it passes, an empty slot consumes it, a book in + // it comes out (the block entity is the game's). + let Some(slot) = hit_slot(b.facing(state), face, pos, hit, 2, 3) else { + return Pass; + }; + let occupied = [ + p.slot_0_occupied, + p.slot_1_occupied, + p.slot_2_occupied, + p.slot_3_occupied, + p.slot_4_occupied, + p.slot_5_occupied, + ]; + if table.bool(state, occupied[slot]) { + Success + } else { + Consume + } + } Class::Bell => { let click_y = hit.y - f64::from(pos.y); let proper = axis_of(face) != Axis::Y && click_y <= 0.8124 && { diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index 0a8e160cd..39c6bb6f7 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -137,7 +137,7 @@ mod tests; pub use buckets::BucketContent; pub use data::{BlockData, ItemBinding, ItemKind, Named, Props, PushReaction, StateFacts, Tags}; pub use falling::Landing; -pub use interact::{InteractionResult, PlayerContext, PlayerEffect}; +pub use interact::{InteractionResult, PlayerContext, PlayerEffect, hit_slot}; pub use pistons::{BlockEventData, MovingPiston}; pub use place::{PlaceContext, PlaceOutcome}; pub use states::{BlockId, PropKey, StateTable};