use std::sync::{Arc, Mutex}; use crate::block::entities::hanging_sign::HangingSignBlockEntity; use crate::block::entities::sign::{SignBlockEntity, SignEntityRef, Text}; use crate::command::CommandSender; use crate::command::context::command_source::CommandSource; use pumpkin_data::Block; use pumpkin_data::BlockDirection; use pumpkin_data::BlockId; use pumpkin_data::BlockStateId; use pumpkin_data::HorizontalFacingExt; use pumpkin_data::block_properties::EnumVariants; use pumpkin_data::tag::Taggable; use pumpkin_inventory::screen_handler::InventoryPlayer; use pumpkin_macros::pumpkin_block_from_tag; use pumpkin_util::math::position::BlockPos; use pumpkin_util::math::vector2::Vector2; use pumpkin_util::math::vector3::Vector3; use pumpkin_util::text::TextComponent; use pumpkin_util::text::click::ClickEvent; use uuid::Uuid; use crate::block::BlockBehaviour; use crate::block::CanPlaceAtArgs; use crate::block::GetStateForNeighborUpdateArgs; use crate::block::NormalUseArgs; use crate::block::OnPlaceArgs; use crate::block::OnStateReplacedArgs; use crate::block::PlacedArgs; use crate::block::PlayerPlacedArgs; use crate::block::UseWithItemArgs; use crate::block::registry::BlockActionResult; use crate::entity::EntityBase; use crate::entity::player::Player; use crate::item::items::dye::DyeItem; use crate::item::items::glowing_ink_sac::GlowingInkSacItem; use crate::item::items::honeycomb::HoneyCombItem; use crate::item::items::ink_sac::InkSacItem; use crate::world::World; use pumpkin_protocol::java::client::play::COpenSignEditor; #[pumpkin_block_from_tag("minecraft:all_signs")] pub struct SignBlock; /// Helper struct to hold support detection results struct SupportInfo { above_is_valid: bool, side_direction: Option, } /// Helper struct for sign placement configuration struct SignPlacement { block_id: BlockId, facing: Option, rotation: Option, attached: bool, } impl SignBlock { /// Checks if a block can provide support for a sign. fn is_valid_support(world: &World, pos: &BlockPos, direction: BlockDirection) -> bool { let (block, state) = world.get_block_and_state(pos); let is_permissive = block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_LEAVES) || block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_SIGNS); match direction { BlockDirection::Up => state.is_side_solid(BlockDirection::Down) || is_permissive, BlockDirection::Down => state.is_center_solid(BlockDirection::Up) || is_permissive, _ => state.is_side_solid(direction.opposite()) || is_permissive, } } /// Detects available support points around a position. fn detect_support(world: &World, position: &BlockPos) -> SupportInfo { let (block_above, state_above) = world.get_block_and_state(&position.up()); let above_is_valid = state_above.is_side_solid(BlockDirection::Down) || block_above.has_tag(&pumpkin_data::tag::Block::MINECRAFT_SIGNS) || block_above.has_tag(&pumpkin_data::tag::Block::MINECRAFT_LEAVES); let mut side_direction = None; for direction in BlockDirection::horizontal() { let pos = position.offset(direction.to_offset()); if Self::is_valid_support(world, &pos, direction.opposite().to_block_direction()) { side_direction = Some(direction); break; } } SupportInfo { above_is_valid, side_direction: side_direction.map(|d| d.to_block_direction()), } } /// Determines the appropriate facing direction for a wall-hanging sign. fn calculate_wall_hanging_facing(wall_dir: BlockDirection, player_yaw: f32) -> &'static str { match wall_dir { BlockDirection::North | BlockDirection::South => { // Wall runs North-South, sign faces East or West if (player_yaw + 360.0) % 360.0 < 180.0 { "east" } else { "west" } } BlockDirection::East | BlockDirection::West => { // Wall runs East-West, sign faces North or South if (-270.0..=270.0).contains(&player_yaw) { "south" } else { "north" } } _ => wall_dir.opposite().to_cardinal_direction().to_value(), } } /// Calculates rotation for wall-hanging signs. fn calculate_wall_hanging_rotation( wall_dir: BlockDirection, player_rot: u8, is_sneaking: bool, ) -> u8 { if is_sneaking { return player_rot; } match wall_dir { BlockDirection::North | BlockDirection::South => { // Snap to North-South axis (0 or 8) if (4..12).contains(&player_rot) { 8 } else { 0 } } BlockDirection::East | BlockDirection::West => { // Snap to East-West axis (4 or 12) if (2..10).contains(&player_rot) { 4 } else { 12 } } _ => player_rot, } } /// Determines the block variant and placement properties for a sign. fn determine_placement(args: &OnPlaceArgs, support: &SupportInfo) -> Option { let is_hanging = args.block.name.contains("hanging"); let is_sneaking = args.player.get_entity().is_sneaking(); // Select block variant let block_id = if is_hanging { Self::select_hanging_variant(args, support)? } else { Self::select_standing_variant(args, support) }; let actual_block = Block::from_id(block_id); let is_wall_hanging = is_hanging && actual_block.name.contains("wall_hanging"); // Calculate orientation let (facing, rotation, attached) = if is_wall_hanging { Self::calculate_wall_hanging_orientation(args, support, is_sneaking) } else if is_hanging { Self::calculate_ceiling_orientation(args, is_sneaking) } else if actual_block.name.contains("wall") { Self::calculate_wall_orientation(args) } else { Self::calculate_standing_orientation(args) }; Some(SignPlacement { block_id, facing, rotation, attached, }) } /// Selects the appropriate hanging sign variant. fn select_hanging_variant(args: &OnPlaceArgs, support: &SupportInfo) -> Option { if args.direction == BlockDirection::Down && support.above_is_valid { Some(args.block.id) // Ceiling hanging } else if (args.direction.is_horizontal() || args.direction == BlockDirection::Up) && support.side_direction.is_some() { Some(get_sign_variant(args.block, true)) // Wall-hanging with post } else if support.above_is_valid { Some(args.block.id) } else { None // No valid placement } } /// Selects the appropriate standing sign variant. fn select_standing_variant(args: &OnPlaceArgs, support: &SupportInfo) -> BlockId { if args.direction.is_horizontal() && support.side_direction.is_some() { get_sign_variant(args.block, false) // Wall sign } else { args.block.id // Standing sign } } /// Calculates orientation for wall-hanging signs. fn calculate_wall_hanging_orientation( args: &OnPlaceArgs, support: &SupportInfo, is_sneaking: bool, ) -> (Option, Option, bool) { let wall_dir = if args.direction.is_horizontal() { args.direction } else { support.side_direction.unwrap_or(args.direction) }; let player_yaw = args.player.get_entity().yaw.load(); let facing = Self::calculate_wall_hanging_facing(wall_dir, player_yaw); let player_rot = args.player.get_entity().get_flipped_rotation_16(); let rotation = Self::calculate_wall_hanging_rotation(wall_dir, player_rot, is_sneaking); let is_angled = rotation % 4 != 0; let attached = is_angled || is_sneaking; (Some(facing.to_string()), Some(rotation), attached) } /// Calculates orientation for ceiling-hanging signs. fn calculate_ceiling_orientation( args: &OnPlaceArgs, is_sneaking: bool, ) -> (Option, Option, bool) { let rotation = if is_sneaking { args.player.get_entity().get_flipped_rotation_16() } else { // Snap to nearest cardinal let index = args.player.get_entity().get_flipped_rotation_16(); ((index + 2) / 4 * 4) % 16 }; let is_angled = rotation % 4 != 0; let attached = is_angled || is_sneaking; (None, Some(rotation), attached) } /// Calculates orientation for wall signs. fn calculate_wall_orientation(args: &OnPlaceArgs) -> (Option, Option, bool) { let facing = args.direction.opposite().to_cardinal_direction().to_value(); (Some(facing.to_string()), None, false) } /// Calculates orientation for standing signs. fn calculate_standing_orientation(args: &OnPlaceArgs) -> (Option, Option, bool) { let rotation = args.player.get_entity().get_flipped_rotation_16(); (None, Some(rotation), false) } /// Applies placement properties to a block. fn apply_placement_properties(block: &Block, placement: &SignPlacement) -> BlockStateId { let mut props = block .properties(block.default_state.id) .map(|p| p.to_props()) .unwrap_or_default(); if let Some(facing) = &placement.facing && let Some(prop) = props.iter_mut().find(|(k, _)| *k == "facing") { prop.1 = facing; } if let Some(rotation) = placement.rotation && let Some(prop) = props.iter_mut().find(|(k, _)| *k == "rotation") { prop.1 = match rotation { 1 => "1", 2 => "2", 3 => "3", 4 => "4", 5 => "5", 6 => "6", 7 => "7", 8 => "8", 9 => "9", 10 => "10", 11 => "11", 12 => "12", 13 => "13", 14 => "14", 15 => "15", _ => "0", }; } if let Some(prop) = props.iter_mut().find(|(k, _)| *k == "attached") { prop.1 = if placement.attached { "true" } else { "false" }; } block.from_properties(&props).to_state_id(block) } } impl BlockBehaviour for SignBlock { fn on_place(&self, args: OnPlaceArgs<'_>) -> BlockStateId { let support = Self::detect_support(args.world, args.position); let Some(placement) = Self::determine_placement(&args, &support) else { return BlockStateId::AIR; // Invalid placement }; let actual_block = Block::from_id(placement.block_id); Self::apply_placement_properties(actual_block, &placement) } fn placed(&self, args: PlacedArgs<'_>) { if args.block.name.contains("hanging") { args.world .add_block_entity(Arc::new(HangingSignBlockEntity::empty(*args.position))); } else { args.world .add_block_entity(Arc::new(SignBlockEntity::empty(*args.position))); } } fn player_placed(&self, args: PlayerPlacedArgs<'_>) { if let Some(block_entity) = args.world.get_block_entity(args.position) && let Some(sign) = SignEntityRef::from_block_entity(&*block_entity) { open_text_edit( args.player, sign.currently_editing_player(), args.position, true, ); return; } args.player .try_send_client_packet(&COpenSignEditor::new(*args.position, true)); } fn can_place_at(&self, args: CanPlaceAtArgs<'_>) -> bool { let is_hanging = args.block.name.contains("hanging"); let clicked_face = args .use_item_on .and_then(|u| pumpkin_data::BlockDirection::try_from(u.face.0).ok()) .unwrap_or(pumpkin_data::BlockDirection::Up); // Detection for floor-to-wall attachment (broken rn) if is_hanging && clicked_face == BlockDirection::Up { for d in pumpkin_data::BlockDirection::horizontal() { let wall_pos = args.position.offset(d.to_offset()); let (block, state) = args.block_accessor.get_block_and_state(&wall_pos); if state.is_side_solid(d.opposite().to_block_direction()) || block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_LEAVES) || block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_SIGNS) { return true; } } } // Standard support validation with permissive tags let support_pos = match clicked_face { BlockDirection::Up => args.position.down(), BlockDirection::Down => args.position.up(), _ => args.position.offset(clicked_face.opposite().to_offset()), }; let (block, state) = args.block_accessor.get_block_and_state(&support_pos); let is_permissive = block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_LEAVES) || block.has_tag(&pumpkin_data::tag::Block::MINECRAFT_SIGNS); match clicked_face { BlockDirection::Up => { !is_hanging && (state.is_center_solid(BlockDirection::Up) || is_permissive) } BlockDirection::Down => { is_hanging && (state.is_side_solid(BlockDirection::Down) || is_permissive) } _ => state.is_side_solid(clicked_face.opposite()) || is_permissive, } } fn on_state_replaced(&self, args: OnStateReplacedArgs<'_>) { args.world.remove_block_entity(args.position); } fn get_state_for_neighbor_update( &self, args: GetStateForNeighborUpdateArgs<'_>, ) -> BlockStateId { let is_hanging = args.block.name.contains("hanging"); let is_wall_sign = args.block.name.contains("wall"); // Determine the expected support direction let support_dir = if is_wall_sign { // Look up the 'facing' property to find the support behind the wall sign get_wall_support_direction(args.block, args.state_id) } else if is_hanging { // Ceiling-hanging signs always look Up Some(BlockDirection::Up) } else { // Standing signs always look Down Some(BlockDirection::Down) }; if let Some(dir) = support_dir { let support_pos = args.position.offset(dir.to_offset()); let support_state = args.world.get_block_state(&support_pos); let is_leaf = args .world .get_block(&support_pos) .has_tag(&pumpkin_data::tag::Block::MINECRAFT_LEAVES); let is_sign = args .world .get_block(&support_pos) .has_tag(&pumpkin_data::tag::Block::MINECRAFT_ALL_SIGNS); let is_valid = match dir { BlockDirection::Up => { support_state.is_center_solid(BlockDirection::Down) || is_leaf || is_sign } BlockDirection::Down => { support_state.is_center_solid(BlockDirection::Up) || is_leaf || is_sign } _ => support_state.is_side_solid(dir.opposite()) || is_leaf || is_sign, }; if !is_valid { return BlockStateId::AIR; } } args.state_id } /// Handles normal use (right-click) on the sign block. fn normal_use(&self, args: NormalUseArgs<'_>) -> BlockActionResult { let Some(block_entity) = args.world.get_block_entity(args.position) else { return BlockActionResult::Pass; }; let Some(sign_entity) = SignEntityRef::from_block_entity(&*block_entity) else { return BlockActionResult::Pass; }; let is_front_text = is_facing_front_text(args.world, args.position, args.block, args.player); let text = sign_entity.get_text(is_front_text); let executed_click_command = execute_click_commands_if_present(args.world, args.player, args.position, text); if sign_entity.is_waxed() { let is_hanging = args.block.name.contains("hanging"); let sound = if is_hanging { pumpkin_data::sound::Sound::BlockHangingSignWaxedInteractFail } else { pumpkin_data::sound::Sound::BlockSignWaxedInteractFail }; args.world.play_block_sound( sound, pumpkin_data::sound::SoundCategory::Blocks, *args.position, ); BlockActionResult::SuccessServer } else if executed_click_command { BlockActionResult::SuccessServer } else if !other_player_is_editing_sign( args.player, sign_entity.currently_editing_player(), args.world, args.position, ) && args.player.may_build() && has_editable_text(text) { open_text_edit( args.player, sign_entity.currently_editing_player(), args.position, is_front_text, ); BlockActionResult::SuccessServer } else { BlockActionResult::Pass } } /// Handles use with an item on the sign block. fn use_with_item(&self, args: UseWithItemArgs<'_>) -> BlockActionResult { let Some(block_entity) = args.world.get_block_entity(args.position) else { return BlockActionResult::Pass; }; let Some(sign_entity) = SignEntityRef::from_block_entity(&*block_entity) else { return BlockActionResult::Pass; }; let Some(pumpkin_item) = args .server .item_registry .get_pumpkin_item(args.item_stack.item.id) else { return BlockActionResult::PassToDefaultBlockAction; }; let is_applicator = pumpkin_item.as_any().is::() || pumpkin_item.as_any().is::() || pumpkin_item.as_any().is::() || pumpkin_item.as_any().is::(); let has_applicator_to_use = is_applicator && args.player.may_build(); if has_applicator_to_use && !sign_entity.is_waxed() && !other_player_is_editing_sign( args.player, sign_entity.currently_editing_player(), args.world, args.position, ) { let is_front_text = is_facing_front_text(args.world, args.position, args.block, args.player); let text = sign_entity.get_text(is_front_text); let result = if let Some(honeycomb_item) = pumpkin_item.as_any().downcast_ref::() { honeycomb_item.apply_to_sign(&args, &block_entity, &sign_entity) } else if let Some(g_ink_sac_item) = pumpkin_item.as_any().downcast_ref::() { g_ink_sac_item.apply_to_sign(&args, &block_entity, text) } else if let Some(ink_sac_item) = pumpkin_item.as_any().downcast_ref::() { ink_sac_item.apply_to_sign(&args, &block_entity, text) } else if let Some(dye) = pumpkin_item.as_any().downcast_ref::() { let color_name = args .item_stack .item .registry_key .strip_suffix("_dye") .unwrap_or(args.item_stack.item.registry_key); dye.apply_to_sign(&args, &block_entity, text, color_name) } else { BlockActionResult::PassToDefaultBlockAction }; if result == BlockActionResult::Success { execute_click_commands_if_present(args.world, args.player, args.position, text); if pumpkin_item.as_any().is::() { args.player.trigger_advancement( crate::entity::player::advancement::trigger::AdvancementTrigger::GlowedSign, ); } if !args.player.has_infinite_materials() { args.item_stack.decrement(1); } return BlockActionResult::Success; } } BlockActionResult::PassToDefaultBlockAction } } /// Opens the sign text edit interface for the player and registers them as allowed editor. fn open_text_edit( player: &Player, currently_editing_player: &Arc>>, position: &BlockPos, is_front_text: bool, ) { *currently_editing_player .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(player.gameprofile.id); player.try_send_client_packet(&COpenSignEditor::new(*position, is_front_text)); } /// Checks if another player is actively editing the sign within reach. fn other_player_is_editing_sign( player: &Player, currently_editing_player: &Arc>>, world: &World, position: &BlockPos, ) -> bool { let currently_editing = currently_editing_player .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if let Some(editing_player_id) = *currently_editing && editing_player_id != player.gameprofile.id && let Some(editing_player) = world.get_player_by_uuid(editing_player_id) && editing_player.can_interact_with_block_at(position, 4.0) { return true; } false } /// Checks whether all messages on the given sign text face are plain text or empty. fn has_editable_text(text: &Text) -> bool { let messages = text .messages .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); messages.iter().all(|msg| is_plain_or_empty_text(msg)) } fn is_plain_or_empty_text(text: &str) -> bool { if text.is_empty() { return true; } if !text.starts_with('{') { return true; } match serde_json::from_str::(text) { Ok(component) => { component.0.style.click_event.is_none() && component.0.style.hover_event.is_none() && component.0.extra.is_empty() && matches!( *component.0.content, pumpkin_util::text::TextContent::Text { .. } ) } Err(_) => true, } } /// Executes any `run_command` click events defined in the sign's text messages. fn execute_click_commands_if_present( world: &Arc, player: &Arc, position: &BlockPos, text: &Text, ) -> bool { let Some(server) = world.server.upgrade() else { return false; }; let messages = text .messages .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); let mut has_run_command = false; for msg in messages.iter() { if msg.is_empty() || !msg.starts_with('{') { continue; } if let Ok(component) = serde_json::from_str::(msg) && let Some(ClickEvent::RunCommand { command }) = &component.0.style.click_event { let source = CommandSource::new( CommandSender::Dummy, world.clone(), Some(player.clone()), position.to_centered_f64(), Vector2::new(0.0, 0.0), player.gameprofile.name.clone(), player.get_display_name(), server.clone(), ); let command_str = command.strip_prefix('/').unwrap_or(command); let dispatcher = server.command_dispatcher.load(); dispatcher.handle_command(&source, command_str); has_run_command = true; } } has_run_command } /// Returns the direction of the block supporting the wall sign. fn get_wall_support_direction(block: &Block, state_id: BlockStateId) -> Option { block.properties(state_id).and_then(|props| { let prop_map = props.to_props(); prop_map .into_iter() .find(|(k, _)| k == &"facing") .map(|(_, v)| match v { "north" => BlockDirection::South, "south" => BlockDirection::North, "east" => BlockDirection::West, _ => BlockDirection::East, // "west" and default case }) }) } /// Helper to convert a regular sign to its wall variant. /// Returns the block ID of the wall variant, or the base block's ID if not found. fn get_sign_variant(base: &Block, is_hanging: bool) -> BlockId { let base_name = base.name; let wood_type = base_name .strip_suffix("_hanging_sign") .or_else(|| base_name.strip_suffix("_sign")) .unwrap_or("oak"); let target_name = if is_hanging { // This is the variant that provides the "horizontal wooden post" format!("{wood_type}_wall_hanging_sign") } else { format!("{wood_type}_wall_sign") }; pumpkin_data::Block::from_name(&target_name).map_or(base.id, |b| b.id) } fn is_facing_front_text( world: &World, location: &BlockPos, block: &Block, player: &Player, ) -> bool { let state_id = world.get_block_state_id(location); // Read properties dynamically: some sign types use a `rotation` property (0..15), // others (wall signs) use a `facing` property (north/south/west/east), // hanging signs may have `rotation` + `attached`. let mut rotation: f32 = 0.0; if let Some(props) = block.properties(state_id) { let prop_map = props.to_props(); if let Some((_, val)) = prop_map.iter().find(|(k, _)| k == &"rotation") { let r = val.parse().unwrap_or(0); rotation = get_yaw_from_rotation_16(r); } else if let Some((_, val)) = prop_map.iter().find(|(k, _)| k == &"facing") { rotation = match &val[..] { "north" => 180.0, "west" => 90.0, "east" => -90.0, _ => 0.0, }; } } let bounding_box = Vector3::new(0.5, 0.5, 0.5); let d = player.eye_position().x - (f64::from(location.0.x) + bounding_box.x); let d1 = player.eye_position().z - (f64::from(location.0.z) + bounding_box.z); let f = (d1.atan2(d).to_degrees() as f32) - 90.0; let diff = (f - rotation + 180.0).rem_euclid(360.0) - 180.0; diff.abs() <= 90.0 } fn get_yaw_from_rotation_16(rotation: u8) -> f32 { f32::from(rotation) * 22.5 }