From 205191b1942c73550de0f81571e02645b3c6f6a4 Mon Sep 17 00:00:00 2001 From: Kris <37947442+OfficialKris@users.noreply.github.com> Date: Sat, 28 Dec 2024 11:46:25 -0500 Subject: [PATCH 1/7] Added default op level (#426) --- pumpkin-config/src/commands.rs | 4 ++++ pumpkin/src/entity/player.rs | 7 ++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/pumpkin-config/src/commands.rs b/pumpkin-config/src/commands.rs index 23aa27116..bf686b0fa 100644 --- a/pumpkin-config/src/commands.rs +++ b/pumpkin-config/src/commands.rs @@ -1,3 +1,4 @@ +use pumpkin_core::PermissionLvl; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize)] @@ -7,6 +8,8 @@ pub struct CommandsConfig { pub use_console: bool, /// Should be commands from players be logged in console? pub log_console: bool, // TODO: commands... + /// The op permission level of everyone that is not in the ops file + pub default_op_level: PermissionLvl, } impl Default for CommandsConfig { @@ -14,6 +17,7 @@ impl Default for CommandsConfig { Self { use_console: true, log_console: true, + default_op_level: PermissionLvl::Zero, } } } diff --git a/pumpkin/src/entity/player.rs b/pumpkin/src/entity/player.rs index eae83b3ed..c197f58f9 100644 --- a/pumpkin/src/entity/player.rs +++ b/pumpkin/src/entity/player.rs @@ -197,9 +197,10 @@ impl Player { .ops .iter() .find(|op| op.uuid == gameprofile_clone.id) - .map_or(AtomicCell::new(PermissionLvl::Zero), |op| { - AtomicCell::new(op.level) - }), + .map_or( + AtomicCell::new(ADVANCED_CONFIG.commands.default_op_level), + |op| AtomicCell::new(op.level), + ), } } From ad2fd3c9a52a18986e6c9d6ee5399f21da1d39b7 Mon Sep 17 00:00:00 2001 From: Kris <37947442+OfficialKris@users.noreply.github.com> Date: Sat, 28 Dec 2024 12:02:32 -0500 Subject: [PATCH 2/7] Added chest opening and closing animation (#421) * Added basic chest opening and closing * Added number tracking * Added play chest action function --- pumpkin-inventory/src/open_container.rs | 4 ++ .../src/client/play/c_block_event.rs | 31 ++++++++ pumpkin-protocol/src/client/play/mod.rs | 2 + pumpkin/src/block/blocks/chest.rs | 71 +++++++++++++++---- pumpkin/src/block/blocks/crafting_table.rs | 4 +- pumpkin/src/block/pumpkin_block.rs | 2 +- 6 files changed, 99 insertions(+), 15 deletions(-) create mode 100644 pumpkin-protocol/src/client/play/c_block_event.rs diff --git a/pumpkin-inventory/src/open_container.rs b/pumpkin-inventory/src/open_container.rs index 3025ed92f..c563ee47f 100644 --- a/pumpkin-inventory/src/open_container.rs +++ b/pumpkin-inventory/src/open_container.rs @@ -76,6 +76,10 @@ impl OpenContainer { self.players.clone() } + pub fn get_number_of_players(&self) -> usize { + self.players.len() + } + pub fn get_location(&self) -> Option { self.location } diff --git a/pumpkin-protocol/src/client/play/c_block_event.rs b/pumpkin-protocol/src/client/play/c_block_event.rs new file mode 100644 index 000000000..c1b2e6e09 --- /dev/null +++ b/pumpkin-protocol/src/client/play/c_block_event.rs @@ -0,0 +1,31 @@ +use pumpkin_core::math::position::WorldPosition; + +use pumpkin_macros::client_packet; +use serde::Serialize; + +use crate::VarInt; + +#[derive(Serialize)] +#[client_packet("play:block_event")] +pub struct CBlockAction<'a> { + location: &'a WorldPosition, + action_id: u8, + action_parameter: u8, + block_type: VarInt, +} + +impl<'a> CBlockAction<'a> { + pub fn new( + location: &'a WorldPosition, + action_id: u8, + action_parameter: u8, + block_type: VarInt, + ) -> Self { + Self { + location, + action_id, + action_parameter, + block_type, + } + } +} diff --git a/pumpkin-protocol/src/client/play/mod.rs b/pumpkin-protocol/src/client/play/mod.rs index 79f7e3ea3..68a7cc576 100644 --- a/pumpkin-protocol/src/client/play/mod.rs +++ b/pumpkin-protocol/src/client/play/mod.rs @@ -2,6 +2,7 @@ mod bossevent_action; mod c_acknowledge_block; mod c_actionbar; mod c_block_destroy_stage; +mod c_block_event; mod c_block_update; mod c_boss_event; mod c_center_chunk; @@ -72,6 +73,7 @@ pub use bossevent_action::*; pub use c_acknowledge_block::*; pub use c_actionbar::*; pub use c_block_destroy_stage::*; +pub use c_block_event::*; pub use c_block_update::*; pub use c_boss_event::*; pub use c_center_chunk::*; diff --git a/pumpkin/src/block/blocks/chest.rs b/pumpkin/src/block/blocks/chest.rs index 313d9a5bf..5a83570ee 100644 --- a/pumpkin/src/block/blocks/chest.rs +++ b/pumpkin/src/block/blocks/chest.rs @@ -2,7 +2,11 @@ use async_trait::async_trait; use pumpkin_core::math::position::WorldPosition; use pumpkin_inventory::{Chest, OpenContainer, WindowType}; use pumpkin_macros::{pumpkin_block, sound}; -use pumpkin_world::{block::block_registry::Block, item::item_registry::Item}; +use pumpkin_protocol::{client::play::CBlockAction, codec::var_int::VarInt}; +use pumpkin_world::{ + block::block_registry::{get_block, Block}, + item::item_registry::Item, +}; use crate::{ block::{block_manager::BlockActionResult, pumpkin_block::PumpkinBlock}, @@ -10,6 +14,12 @@ use crate::{ server::Server, }; +#[derive(PartialEq)] +pub enum ChestState { + IsOpened, + IsClosed, +} + #[pumpkin_block("minecraft:chest")] pub struct ChestBlock; @@ -24,10 +34,6 @@ impl PumpkinBlock for ChestBlock { ) { self.open_chest_block(block, player, _location, server) .await; - player - .world() - .play_block_sound(sound!("block.chest.open"), _location) - .await; } async fn on_use_with_item<'a>( @@ -57,15 +63,14 @@ impl PumpkinBlock for ChestBlock { &self, _block: &Block, player: &Player, - _location: WorldPosition, - _server: &Server, - _container: &OpenContainer, + location: WorldPosition, + server: &Server, + container: &mut OpenContainer, ) { - player - .world() - .play_block_sound(sound!("block.chest.close"), _location) + container.remove_player(player.entity_id()); + + self.play_chest_action(container, player, location, server, ChestState::IsClosed) .await; - // TODO: send entity updates close } } @@ -86,6 +91,46 @@ impl ChestBlock { WindowType::Generic9x3, ) .await; - // TODO: send entity updates open + + if let Some(container_id) = server.get_container_id(location, block.clone()).await { + let open_containers = server.open_containers.read().await; + if let Some(container) = open_containers.get(&u64::from(container_id)) { + self.play_chest_action(container, player, location, server, ChestState::IsOpened) + .await; + } + } + } + + pub async fn play_chest_action( + &self, + container: &OpenContainer, + player: &Player, + location: WorldPosition, + server: &Server, + state: ChestState, + ) { + let num_players = container.get_number_of_players() as u8; + if state == ChestState::IsClosed && num_players == 0 { + player + .world() + .play_block_sound(sound!("block.chest.close"), location) + .await; + } else if state == ChestState::IsOpened && num_players == 1 { + player + .world() + .play_block_sound(sound!("block.chest.open"), location) + .await; + } + + if let Some(e) = get_block("minecraft:chest").cloned() { + server + .broadcast_packet_all(&CBlockAction::new( + &location, + 1, + num_players, + VarInt(e.id.into()), + )) + .await; + } } } diff --git a/pumpkin/src/block/blocks/crafting_table.rs b/pumpkin/src/block/blocks/crafting_table.rs index 01ad41795..c879f0601 100644 --- a/pumpkin/src/block/blocks/crafting_table.rs +++ b/pumpkin/src/block/blocks/crafting_table.rs @@ -53,7 +53,7 @@ impl PumpkinBlock for CraftingTableBlock { player: &Player, _location: WorldPosition, _server: &Server, - container: &OpenContainer, + container: &mut OpenContainer, ) { let entity_id = player.entity_id(); for player_id in container.all_player_ids() { @@ -62,6 +62,8 @@ impl PumpkinBlock for CraftingTableBlock { } } + container.remove_player(entity_id); + // TODO: items should be re-added to player inventory or dropped dependending on if they are in movement. // TODO: unique containers should be implemented as a separate stack internally (optimizes large player servers for example) // TODO: ephemeral containers (crafting tables) might need to be separate data structure than stored (ender chest) diff --git a/pumpkin/src/block/pumpkin_block.rs b/pumpkin/src/block/pumpkin_block.rs index c0a65c316..90de57189 100644 --- a/pumpkin/src/block/pumpkin_block.rs +++ b/pumpkin/src/block/pumpkin_block.rs @@ -60,7 +60,7 @@ pub trait PumpkinBlock: Send + Sync { _player: &Player, _location: WorldPosition, _server: &Server, - _container: &OpenContainer, + _container: &mut OpenContainer, ) { } } From c5c7e897cbb0d8b1b7cb9b673fc35e6166de8e33 Mon Sep 17 00:00:00 2001 From: Alexander Medvedev Date: Sun, 29 Dec 2024 12:40:22 +0100 Subject: [PATCH 3/7] Update website and repo links --- CONTRIBUTING.md | 2 +- Dockerfile | 2 +- README.md | 6 +++--- pumpkin-config/src/server_links.rs | 2 +- pumpkin/src/command/commands/cmd_pumpkin.rs | 12 +++++------- pumpkin/src/main.rs | 2 +- pumpkin/src/net/authentication.rs | 2 +- 7 files changed, 13 insertions(+), 15 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3599738cb..690cbb930 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -27,7 +27,7 @@ There are several ways you can contribute to Pumpkin: ### Docs -The Documentation of Pumpkin can be found at +The Documentation of Pumpkin can be found at **Tip: [typos](https://github.com/crate-ci/typos) is a great Project to detect and automatically fix typos diff --git a/Dockerfile b/Dockerfile index 7fc544257..05edc4d03 100644 --- a/Dockerfile +++ b/Dockerfile @@ -19,7 +19,7 @@ RUN strip pumpkin.release FROM alpine:3.21 # Identifying information for registries like ghcr.io -LABEL org.opencontainers.image.source=https://github.com/Snowiiii/Pumpkin +LABEL org.opencontainers.image.source=https://github.com/Pumpkin-MC/Pumpkin RUN apk add --no-cache libgcc diff --git a/README.md b/README.md index e62595150..5245514c6 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ -[Pumpkin](https://snowiiii.github.io/Pumpkin-Website/) is a Minecraft server built entirely in Rust, offering a fast, efficient, +[Pumpkin](https://pumpkinmc.org/) is a Minecraft server built entirely in Rust, offering a fast, efficient, and customizable experience. It prioritizes performance and player enjoyment while adhering to the core mechanics of the game. ![image](https://github.com/user-attachments/assets/7e2e865e-b150-4675-a2d5-b52f9900378e) @@ -88,7 +88,7 @@ Check out our [Github Project](https://github.com/users/Snowiiii/projects/12/vie ## How to run -See our [Quick Start](https://snowiiii.github.io/Pumpkin-Website/about/quick-start.html) Guide to get Pumpkin running +See our [Quick Start](https://pumpkinmc.org/about/quick-start.html) Guide to get Pumpkin running ## Contributions @@ -96,7 +96,7 @@ Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) ## Docs -The Documentation of Pumpkin can be found at https://snowiiii.github.io/Pumpkin-Website/ +The Documentation of Pumpkin can be found at https://pumpkinmc.org/ ## Communication diff --git a/pumpkin-config/src/server_links.rs b/pumpkin-config/src/server_links.rs index a9cf9627a..cb8a9b3a4 100644 --- a/pumpkin-config/src/server_links.rs +++ b/pumpkin-config/src/server_links.rs @@ -21,7 +21,7 @@ impl Default for ServerLinksConfig { fn default() -> Self { Self { enabled: true, - bug_report: "https://github.com/Snowiiii/Pumpkin/issues".to_string(), + bug_report: "https://github.com/Pumpkin-MC/Pumpkin/issues".to_string(), support: "".to_string(), status: "".to_string(), feedback: "".to_string(), diff --git a/pumpkin/src/command/commands/cmd_pumpkin.rs b/pumpkin/src/command/commands/cmd_pumpkin.rs index a76a1be99..ea8079663 100644 --- a/pumpkin/src/command/commands/cmd_pumpkin.rs +++ b/pumpkin/src/command/commands/cmd_pumpkin.rs @@ -61,11 +61,11 @@ impl CommandExecutor for PumpkinExecutor { .color_named(NamedColor::Gold), ) .add_child(TextComponent::text(" ")) - // https://snowiiii.github.io/Pumpkin/ + // https://pumpkinmc.org/ .add_child( TextComponent::text("Github Repository") .click_event(ClickEvent::OpenUrl(Cow::from( - "https://github.com/Snowiiii/Pumpkin", + "https://github.com/Pumpkin-MC/Pumpkin", ))) .hover_event(HoverEvent::ShowText(Cow::from( "Click to open repository.", @@ -77,11 +77,9 @@ impl CommandExecutor for PumpkinExecutor { // Added docs. and a space for spacing .add_child(TextComponent::text(" ")) .add_child( - TextComponent::text("Docs") - .click_event(ClickEvent::OpenUrl(Cow::from( - "https://snowiiii.github.io/Pumpkin/", - ))) - .hover_event(HoverEvent::ShowText(Cow::from("Click to open docs."))) + TextComponent::text("Website") + .click_event(ClickEvent::OpenUrl(Cow::from("https://pumpkinmc.org/"))) + .hover_event(HoverEvent::ShowText(Cow::from("Click to open website."))) .color_named(NamedColor::Blue) .bold() .underlined(), diff --git a/pumpkin/src/main.rs b/pumpkin/src/main.rs index d0dbe4019..3dec495f8 100644 --- a/pumpkin/src/main.rs +++ b/pumpkin/src/main.rs @@ -142,7 +142,7 @@ async fn main() { ); log::warn!("Pumpkin is currently under heavy development!"); - log::info!("Report Issues on https://github.com/Snowiiii/Pumpkin/issues"); + log::info!("Report Issues on https://github.com/Pumpkin-MC/Pumpkin/issues"); log::info!("Join our Discord for community support https://discord.com/invite/wT8XjrjKkf"); tokio::spawn(async { diff --git a/pumpkin/src/net/authentication.rs b/pumpkin/src/net/authentication.rs index 4136a74a6..0069228e5 100644 --- a/pumpkin/src/net/authentication.rs +++ b/pumpkin/src/net/authentication.rs @@ -43,7 +43,7 @@ const MOJANG_PREVENT_PROXY_AUTHENTICATION_URL: &str = "https://sessionserver.moj /// 2. Mojang's servers verify the client's credentials and add the player to the their Servers /// 3. Now our server will send a Request to the Session servers and check if the Player has joined the Session Server . /// -/// See +/// See pub async fn authenticate( username: &str, server_hash: &str, From 2d136b1c246453bfea0a2cd209b11e6592b12407 Mon Sep 17 00:00:00 2001 From: smuu <18609909+smuu@users.noreply.github.com> Date: Sun, 29 Dec 2024 16:43:25 +0100 Subject: [PATCH 4/7] fix: command permission message (#428) * fix: command permission handling Signed-off-by: Smuu <18609909+Smuu@users.noreply.github.com> * fix: formatting Signed-off-by: Smuu <18609909+Smuu@users.noreply.github.com> --------- Signed-off-by: Smuu <18609909+Smuu@users.noreply.github.com> --- pumpkin/src/command/client_cmd_suggestions.rs | 8 +++ pumpkin/src/command/commands/cmd_fill.rs | 26 +++---- pumpkin/src/command/commands/cmd_gamemode.rs | 13 ++-- pumpkin/src/command/commands/cmd_give.rs | 13 ++-- pumpkin/src/command/commands/cmd_op.rs | 9 +-- pumpkin/src/command/commands/cmd_say.rs | 9 +-- pumpkin/src/command/commands/cmd_seed.rs | 8 +-- pumpkin/src/command/commands/cmd_setblock.rs | 20 +++--- pumpkin/src/command/commands/cmd_stop.rs | 6 +- pumpkin/src/command/commands/cmd_teleport.rs | 71 +++++++++---------- pumpkin/src/command/commands/cmd_time.rs | 32 ++++----- pumpkin/src/command/commands/cmd_transfer.rs | 25 +++---- pumpkin/src/command/dispatcher.rs | 34 +++++++-- pumpkin/src/command/mod.rs | 38 +++++----- pumpkin/src/command/tree_builder.rs | 5 +- 15 files changed, 155 insertions(+), 162 deletions(-) diff --git a/pumpkin/src/command/client_cmd_suggestions.rs b/pumpkin/src/command/client_cmd_suggestions.rs index 707dfcf50..39da02ea5 100644 --- a/pumpkin/src/command/client_cmd_suggestions.rs +++ b/pumpkin/src/command/client_cmd_suggestions.rs @@ -20,6 +20,14 @@ pub async fn send_c_commands_packet(player: &Arc, dispatcher: &RwLock CommandTree { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two) && sender.world().is_some()) - .with_child( - argument(ARG_FROM, BlockPosArgumentConsumer).with_child( - argument(ARG_TO, BlockPosArgumentConsumer).with_child( - argument(ARG_BLOCK, BlockArgumentConsumer) - .with_child(literal("destroy").execute(SetblockExecutor(Mode::Destroy))) - .with_child(literal("hollow").execute(SetblockExecutor(Mode::Hollow))) - .with_child(literal("keep").execute(SetblockExecutor(Mode::Keep))) - .with_child(literal("outline").execute(SetblockExecutor(Mode::Outline))) - .with_child(literal("replace").execute(SetblockExecutor(Mode::Replace))) - .execute(SetblockExecutor(Mode::Replace)), - ), - ), + argument(ARG_FROM, BlockPosArgumentConsumer).with_child( + argument(ARG_TO, BlockPosArgumentConsumer).with_child( + argument(ARG_BLOCK, BlockArgumentConsumer) + .with_child(literal("destroy").execute(SetblockExecutor(Mode::Destroy))) + .with_child(literal("hollow").execute(SetblockExecutor(Mode::Hollow))) + .with_child(literal("keep").execute(SetblockExecutor(Mode::Keep))) + .with_child(literal("outline").execute(SetblockExecutor(Mode::Outline))) + .with_child(literal("replace").execute(SetblockExecutor(Mode::Replace))) + .execute(SetblockExecutor(Mode::Replace)), ), + ), ) } diff --git a/pumpkin/src/command/commands/cmd_gamemode.rs b/pumpkin/src/command/commands/cmd_gamemode.rs index 1b586130c..14f169115 100644 --- a/pumpkin/src/command/commands/cmd_gamemode.rs +++ b/pumpkin/src/command/commands/cmd_gamemode.rs @@ -4,7 +4,6 @@ use crate::command::args::arg_gamemode::GamemodeArgumentConsumer; use crate::command::args::GetCloned; use crate::TextComponent; -use pumpkin_core::permission::PermissionLvl; use crate::command::args::arg_players::PlayersArgumentConsumer; @@ -109,12 +108,10 @@ impl CommandExecutor for GamemodeTargetPlayer { #[allow(clippy::redundant_closure_for_method_calls)] pub fn init_command_tree() -> CommandTree { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two)).with_child( - argument(ARG_GAMEMODE, GamemodeArgumentConsumer) - .with_child(require(|sender| sender.is_player()).execute(GamemodeTargetSelf)) - .with_child( - argument(ARG_TARGET, PlayersArgumentConsumer).execute(GamemodeTargetPlayer), - ), - ), + argument(ARG_GAMEMODE, GamemodeArgumentConsumer) + .with_child(require(|sender| sender.is_player()).execute(GamemodeTargetSelf)) + .with_child( + argument(ARG_TARGET, PlayersArgumentConsumer).execute(GamemodeTargetPlayer), + ), ) } diff --git a/pumpkin/src/command/commands/cmd_give.rs b/pumpkin/src/command/commands/cmd_give.rs index d3f91bafa..6b9b3f07c 100644 --- a/pumpkin/src/command/commands/cmd_give.rs +++ b/pumpkin/src/command/commands/cmd_give.rs @@ -7,9 +7,8 @@ use crate::command::args::arg_item::ItemArgumentConsumer; use crate::command::args::arg_players::PlayersArgumentConsumer; use crate::command::args::{ConsumedArgs, FindArg, FindArgDefaultName}; use crate::command::tree::CommandTree; -use crate::command::tree_builder::{argument, argument_default_name, require}; +use crate::command::tree_builder::{argument, argument_default_name}; use crate::command::{CommandError, CommandExecutor, CommandSender}; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 1] = ["give"]; @@ -76,12 +75,10 @@ impl CommandExecutor for GiveExecutor { pub fn init_command_tree() -> CommandTree { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two)).with_child( - argument_default_name(PlayersArgumentConsumer).with_child( - argument(ARG_ITEM, ItemArgumentConsumer) - .execute(GiveExecutor) - .with_child(argument_default_name(item_count_consumer()).execute(GiveExecutor)), - ), + argument_default_name(PlayersArgumentConsumer).with_child( + argument(ARG_ITEM, ItemArgumentConsumer) + .execute(GiveExecutor) + .with_child(argument_default_name(item_count_consumer()).execute(GiveExecutor)), ), ) } diff --git a/pumpkin/src/command/commands/cmd_op.rs b/pumpkin/src/command/commands/cmd_op.rs index 614ffcc7d..41206fcb5 100644 --- a/pumpkin/src/command/commands/cmd_op.rs +++ b/pumpkin/src/command/commands/cmd_op.rs @@ -2,14 +2,13 @@ use crate::{ command::{ args::{arg_players::PlayersArgumentConsumer, Arg, ConsumedArgs}, tree::CommandTree, - tree_builder::{argument, require}, + tree_builder::argument, CommandError, CommandExecutor, CommandSender, }, data::{op_data::OPERATOR_CONFIG, SaveJSONConfiguration}, }; use async_trait::async_trait; use pumpkin_config::{op::Op, BASIC_CONFIG}; -use pumpkin_core::permission::PermissionLvl; use pumpkin_core::text::TextComponent; use CommandError::InvalidConsumption; @@ -73,8 +72,6 @@ impl CommandExecutor for OpExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Three)) - .with_child(argument(ARG_TARGET, PlayersArgumentConsumer).execute(OpExecutor)), - ) + CommandTree::new(NAMES, DESCRIPTION) + .with_child(argument(ARG_TARGET, PlayersArgumentConsumer).execute(OpExecutor)) } diff --git a/pumpkin/src/command/commands/cmd_say.rs b/pumpkin/src/command/commands/cmd_say.rs index ffeb9c884..9ee8874de 100644 --- a/pumpkin/src/command/commands/cmd_say.rs +++ b/pumpkin/src/command/commands/cmd_say.rs @@ -5,10 +5,9 @@ use pumpkin_protocol::client::play::CSystemChatMessage; use crate::command::{ args::{arg_message::MsgArgConsumer, Arg, ConsumedArgs}, tree::CommandTree, - tree_builder::{argument, require}, + tree_builder::argument, CommandError, CommandExecutor, CommandSender, }; -use pumpkin_core::permission::PermissionLvl; use CommandError::InvalidConsumption; const NAMES: [&str; 1] = ["say"]; @@ -42,8 +41,6 @@ impl CommandExecutor for SayExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two)) - .with_child(argument(ARG_MESSAGE, MsgArgConsumer).execute(SayExecutor)), - ) + CommandTree::new(NAMES, DESCRIPTION) + .with_child(argument(ARG_MESSAGE, MsgArgConsumer).execute(SayExecutor)) } diff --git a/pumpkin/src/command/commands/cmd_seed.rs b/pumpkin/src/command/commands/cmd_seed.rs index 50fe6ecd8..a3094193d 100644 --- a/pumpkin/src/command/commands/cmd_seed.rs +++ b/pumpkin/src/command/commands/cmd_seed.rs @@ -1,9 +1,7 @@ -use crate::command::tree_builder::require; use crate::command::{ args::ConsumedArgs, tree::CommandTree, CommandError, CommandExecutor, CommandSender, }; use async_trait::async_trait; -use pumpkin_core::permission::PermissionLvl; use pumpkin_core::text::click::ClickEvent; use pumpkin_core::text::hover::HoverEvent; use pumpkin_core::text::{color::NamedColor, TextComponent}; @@ -55,9 +53,5 @@ impl CommandExecutor for PumpkinExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION) - .with_child(require(|sender| { - sender.has_permission_lvl(PermissionLvl::Two) - })) - .execute(PumpkinExecutor) + CommandTree::new(NAMES, DESCRIPTION).execute(PumpkinExecutor) } diff --git a/pumpkin/src/command/commands/cmd_setblock.rs b/pumpkin/src/command/commands/cmd_setblock.rs index 82e813924..ee8310d08 100644 --- a/pumpkin/src/command/commands/cmd_setblock.rs +++ b/pumpkin/src/command/commands/cmd_setblock.rs @@ -6,9 +6,8 @@ use crate::command::args::arg_block::BlockArgumentConsumer; use crate::command::args::arg_position_block::BlockPosArgumentConsumer; use crate::command::args::{ConsumedArgs, FindArg}; use crate::command::tree::CommandTree; -use crate::command::tree_builder::{argument, literal, require}; +use crate::command::tree_builder::{argument, literal}; use crate::command::{CommandError, CommandExecutor, CommandSender}; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 1] = ["setblock"]; @@ -81,15 +80,12 @@ impl CommandExecutor for SetblockExecutor { pub fn init_command_tree() -> CommandTree { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two) && sender.world().is_some()) - .with_child( - argument(ARG_BLOCK_POS, BlockPosArgumentConsumer).with_child( - argument(ARG_BLOCK, BlockArgumentConsumer) - .with_child(literal("replace").execute(SetblockExecutor(Mode::Replace))) - .with_child(literal("destroy").execute(SetblockExecutor(Mode::Destroy))) - .with_child(literal("keep").execute(SetblockExecutor(Mode::Keep))) - .execute(SetblockExecutor(Mode::Replace)), - ), - ), + argument(ARG_BLOCK_POS, BlockPosArgumentConsumer).with_child( + argument(ARG_BLOCK, BlockArgumentConsumer) + .with_child(literal("replace").execute(SetblockExecutor(Mode::Replace))) + .with_child(literal("destroy").execute(SetblockExecutor(Mode::Destroy))) + .with_child(literal("keep").execute(SetblockExecutor(Mode::Keep))) + .execute(SetblockExecutor(Mode::Replace)), + ), ) } diff --git a/pumpkin/src/command/commands/cmd_stop.rs b/pumpkin/src/command/commands/cmd_stop.rs index 6368988c1..c1f3f4f33 100644 --- a/pumpkin/src/command/commands/cmd_stop.rs +++ b/pumpkin/src/command/commands/cmd_stop.rs @@ -4,9 +4,7 @@ use pumpkin_core::text::TextComponent; use crate::command::args::ConsumedArgs; use crate::command::tree::CommandTree; -use crate::command::tree_builder::require; use crate::command::{CommandError, CommandExecutor, CommandSender}; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 1] = ["stop"]; @@ -38,7 +36,5 @@ impl CommandExecutor for StopExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Four)).execute(StopExecutor), - ) + CommandTree::new(NAMES, DESCRIPTION).execute(StopExecutor) } diff --git a/pumpkin/src/command/commands/cmd_teleport.rs b/pumpkin/src/command/commands/cmd_teleport.rs index 59ccc9606..d5f535f14 100644 --- a/pumpkin/src/command/commands/cmd_teleport.rs +++ b/pumpkin/src/command/commands/cmd_teleport.rs @@ -9,10 +9,9 @@ use crate::command::args::arg_rotation::RotationArgumentConsumer; use crate::command::args::ConsumedArgs; use crate::command::args::FindArg; use crate::command::tree::CommandTree; -use crate::command::tree_builder::{argument, literal, require}; +use crate::command::tree_builder::{argument, literal}; use crate::command::CommandError; use crate::command::{CommandExecutor, CommandSender}; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 2] = ["teleport", "tp"]; const DESCRIPTION: &str = "Teleports entities, including players."; // todo @@ -238,41 +237,37 @@ impl CommandExecutor for TpSelfToPosExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two)) - .with_child( - argument(ARG_LOCATION, Position3DArgumentConsumer).execute(TpSelfToPosExecutor), - ) - .with_child( - argument(ARG_DESTINATION, EntityArgumentConsumer).execute(TpSelfToEntityExecutor), - ) - .with_child( - argument(ARG_TARGETS, EntitiesArgumentConsumer) - .with_child( - argument(ARG_LOCATION, Position3DArgumentConsumer) - .execute(TpEntitiesToPosExecutor) - .with_child( - argument(ARG_ROTATION, RotationArgumentConsumer) - .execute(TpEntitiesToPosWithRotationExecutor), - ) - .with_child( - literal("facing") - .with_child( - literal("entity").with_child( - argument(ARG_FACING_ENTITY, EntityArgumentConsumer) - .execute(TpEntitiesToPosFacingEntityExecutor), - ), - ) - .with_child( - argument(ARG_FACING_LOCATION, Position3DArgumentConsumer) - .execute(TpEntitiesToPosFacingPosExecutor), + CommandTree::new(NAMES, DESCRIPTION) + .with_child(argument(ARG_LOCATION, Position3DArgumentConsumer).execute(TpSelfToPosExecutor)) + .with_child( + argument(ARG_DESTINATION, EntityArgumentConsumer).execute(TpSelfToEntityExecutor), + ) + .with_child( + argument(ARG_TARGETS, EntitiesArgumentConsumer) + .with_child( + argument(ARG_LOCATION, Position3DArgumentConsumer) + .execute(TpEntitiesToPosExecutor) + .with_child( + argument(ARG_ROTATION, RotationArgumentConsumer) + .execute(TpEntitiesToPosWithRotationExecutor), + ) + .with_child( + literal("facing") + .with_child( + literal("entity").with_child( + argument(ARG_FACING_ENTITY, EntityArgumentConsumer) + .execute(TpEntitiesToPosFacingEntityExecutor), ), - ), - ) - .with_child( - argument(ARG_DESTINATION, EntityArgumentConsumer) - .execute(TpEntitiesToEntityExecutor), - ), - ), - ) + ) + .with_child( + argument(ARG_FACING_LOCATION, Position3DArgumentConsumer) + .execute(TpEntitiesToPosFacingPosExecutor), + ), + ), + ) + .with_child( + argument(ARG_DESTINATION, EntityArgumentConsumer) + .execute(TpEntitiesToEntityExecutor), + ), + ) } diff --git a/pumpkin/src/command/commands/cmd_time.rs b/pumpkin/src/command/commands/cmd_time.rs index 9cc45ec67..c28f712af 100644 --- a/pumpkin/src/command/commands/cmd_time.rs +++ b/pumpkin/src/command/commands/cmd_time.rs @@ -6,10 +6,8 @@ use crate::command::args::arg_bounded_num::BoundedNumArgumentConsumer; use crate::command::args::FindArgDefaultName; use crate::command::tree_builder::{argument_default_name, literal}; use crate::command::{ - tree::CommandTree, tree_builder::require, CommandError, CommandExecutor, CommandSender, - ConsumedArgs, + tree::CommandTree, CommandError, CommandExecutor, CommandSender, ConsumedArgs, }; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 1] = ["time"]; @@ -125,19 +123,21 @@ impl CommandExecutor for TimeChangeExecutor { } pub fn init_command_tree() -> CommandTree { - CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Two)) - .with_child(literal("add").with_child( + CommandTree::new(NAMES, DESCRIPTION) + .with_child( + literal("add").with_child( argument_default_name(arg_number()).execute(TimeChangeExecutor(Mode::Add)), - )) - .with_child( - literal("query") - .with_child(literal("daytime").execute(TimeQueryExecutor(QueryMode::DayTime))) - .with_child(literal("gametime").execute(TimeQueryExecutor(QueryMode::GameTime))) - .with_child(literal("day").execute(TimeQueryExecutor(QueryMode::Day))), - ) - .with_child(literal("set").with_child( + ), + ) + .with_child( + literal("query") + .with_child(literal("daytime").execute(TimeQueryExecutor(QueryMode::DayTime))) + .with_child(literal("gametime").execute(TimeQueryExecutor(QueryMode::GameTime))) + .with_child(literal("day").execute(TimeQueryExecutor(QueryMode::Day))), + ) + .with_child( + literal("set").with_child( argument_default_name(arg_number()).execute(TimeChangeExecutor(Mode::Set)), - )), - ) + ), + ) } diff --git a/pumpkin/src/command/commands/cmd_transfer.rs b/pumpkin/src/command/commands/cmd_transfer.rs index 8aa412511..504739206 100644 --- a/pumpkin/src/command/commands/cmd_transfer.rs +++ b/pumpkin/src/command/commands/cmd_transfer.rs @@ -13,7 +13,6 @@ use crate::command::tree_builder::{argument, argument_default_name, require}; use crate::command::{ args::ConsumedArgs, tree::CommandTree, CommandError, CommandExecutor, CommandSender, }; -use pumpkin_core::permission::PermissionLvl; const NAMES: [&str; 1] = ["transfer"]; @@ -121,19 +120,15 @@ impl CommandExecutor for TransferTargetPlayer { #[allow(clippy::redundant_closure_for_method_calls)] pub fn init_command_tree() -> CommandTree { CommandTree::new(NAMES, DESCRIPTION).with_child( - require(|sender| sender.has_permission_lvl(PermissionLvl::Three)).with_child( - argument(ARG_HOSTNAME, SimpleArgConsumer) - .with_child(require(|sender| sender.is_player()).execute(TransferTargetSelf)) - .with_child( - argument_default_name(port_consumer()) - .with_child( - require(|sender| sender.is_player()).execute(TransferTargetSelf), - ) - .with_child( - argument(ARG_PLAYERS, PlayersArgumentConsumer) - .execute(TransferTargetPlayer), - ), - ), - ), + argument(ARG_HOSTNAME, SimpleArgConsumer) + .with_child(require(|sender| sender.is_player()).execute(TransferTargetSelf)) + .with_child( + argument_default_name(port_consumer()) + .with_child(require(|sender| sender.is_player()).execute(TransferTargetSelf)) + .with_child( + argument(ARG_PLAYERS, PlayersArgumentConsumer) + .execute(TransferTargetPlayer), + ), + ), ) } diff --git a/pumpkin/src/command/dispatcher.rs b/pumpkin/src/command/dispatcher.rs index 4d1bb943c..b59b0680c 100644 --- a/pumpkin/src/command/dispatcher.rs +++ b/pumpkin/src/command/dispatcher.rs @@ -1,10 +1,11 @@ +use pumpkin_core::permission::PermissionLvl; use pumpkin_core::text::TextComponent; use pumpkin_protocol::client::play::CommandSuggestion; use super::args::ConsumedArgs; use crate::command::dispatcher::CommandError::{ - GeneralCommandIssue, InvalidConsumption, InvalidRequirement, OtherPumpkin, + GeneralCommandIssue, InvalidConsumption, InvalidRequirement, OtherPumpkin, PermissionDenied, }; use crate::command::tree::{Command, CommandTree, NodeType, RawArgs}; use crate::command::CommandSender; @@ -23,6 +24,8 @@ pub(crate) enum CommandError { /// Return this if a condition that a [`Node::Require`] should ensure is met is not met. InvalidRequirement, + PermissionDenied, + OtherPumpkin(Box), GeneralCommandIssue(String), @@ -39,6 +42,10 @@ impl CommandError { log::error!("Error while parsing command \"{cmd}\": a requirement that was expected was not met."); Ok("Internal Error (See logs for details)".into()) } + PermissionDenied => { + log::warn!("Permission denied for command \"{cmd}\""); + Ok("I'm sorry, but you do not have permission to perform this command. Please contact the server administrator if you believe this is an error.".into()) + } GeneralCommandIssue(s) => Ok(s), OtherPumpkin(e) => Err(e), } @@ -48,6 +55,7 @@ impl CommandError { #[derive(Default)] pub struct CommandDispatcher { pub(crate) commands: HashMap, + pub(crate) permissions: HashMap, } /// Stores registered [`CommandTree`]s and dispatches commands to them. @@ -113,6 +121,10 @@ impl CommandDispatcher { log::error!("Error while parsing command \"{cmd}\": a requirement that was expected was not met."); return Vec::new(); } + Err(PermissionDenied) => { + log::warn!("Permission denied for command \"{cmd}\""); + return Vec::new(); + } Err(GeneralCommandIssue(issue)) => { log::error!("Error while parsing command \"{cmd}\": {issue}"); return Vec::new(); @@ -147,6 +159,14 @@ impl CommandDispatcher { .ok_or(GeneralCommandIssue("Empty Command".to_string()))?; let raw_args: Vec<&str> = parts.rev().collect(); + let Some(permission) = self.permissions.get(key) else { + return Err(GeneralCommandIssue("Command not found".to_string())); + }; + + if !src.has_permission_lvl(*permission) { + return Err(PermissionDenied); + } + let tree = self.get_tree(key)?; // try paths until fitting path is found @@ -180,6 +200,10 @@ impl CommandDispatcher { } } + pub(crate) fn get_permission_lvl(&self, key: &str) -> Option { + self.permissions.get(key).copied() + } + async fn try_is_fitting_path<'a>( src: &mut CommandSender<'a>, server: &'a Server, @@ -270,7 +294,7 @@ impl CommandDispatcher { } /// Register a command with the dispatcher. - pub(crate) fn register(&mut self, tree: CommandTree) { + pub(crate) fn register(&mut self, tree: CommandTree, permission: PermissionLvl) { let mut names = tree.names.iter(); let primary_name = names.next().expect("at least one name must be provided"); @@ -280,6 +304,8 @@ impl CommandDispatcher { .insert(name.to_string(), Command::Alias(primary_name.to_string())); } + self.permissions + .insert(primary_name.to_string(), permission); self.commands .insert(primary_name.to_string(), Command::Tree(tree)); } @@ -288,11 +314,11 @@ impl CommandDispatcher { #[cfg(test)] mod test { use crate::command::{default_dispatcher, tree::CommandTree}; - + use pumpkin_core::permission::PermissionLvl; #[test] fn test_dynamic_command() { let mut dispatcher = default_dispatcher(); let tree = CommandTree::new(["test"], "test_desc"); - dispatcher.register(tree); + dispatcher.register(tree, PermissionLvl::Zero); } } diff --git a/pumpkin/src/command/mod.rs b/pumpkin/src/command/mod.rs index c05017ed5..4e922579c 100644 --- a/pumpkin/src/command/mod.rs +++ b/pumpkin/src/command/mod.rs @@ -112,25 +112,25 @@ impl<'a> CommandSender<'a> { pub fn default_dispatcher() -> CommandDispatcher { let mut dispatcher = CommandDispatcher::default(); - dispatcher.register(cmd_pumpkin::init_command_tree()); - dispatcher.register(cmd_bossbar::init_command_tree()); - dispatcher.register(cmd_say::init_command_tree()); - dispatcher.register(cmd_gamemode::init_command_tree()); - dispatcher.register(cmd_stop::init_command_tree()); - dispatcher.register(cmd_help::init_command_tree()); - dispatcher.register(cmd_kill::init_command_tree()); - dispatcher.register(cmd_kick::init_command_tree()); - dispatcher.register(cmd_worldborder::init_command_tree()); - dispatcher.register(cmd_teleport::init_command_tree()); - dispatcher.register(cmd_time::init_command_tree()); - dispatcher.register(cmd_give::init_command_tree()); - dispatcher.register(cmd_list::init_command_tree()); - dispatcher.register(cmd_clear::init_command_tree()); - dispatcher.register(cmd_setblock::init_command_tree()); - dispatcher.register(cmd_seed::init_command_tree()); - dispatcher.register(cmd_transfer::init_command_tree()); - dispatcher.register(cmd_fill::init_command_tree()); - dispatcher.register(cmd_op::init_command_tree()); + dispatcher.register(cmd_pumpkin::init_command_tree(), PermissionLvl::Zero); + dispatcher.register(cmd_bossbar::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_say::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_gamemode::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_stop::init_command_tree(), PermissionLvl::Four); + dispatcher.register(cmd_help::init_command_tree(), PermissionLvl::Zero); + dispatcher.register(cmd_kill::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_kick::init_command_tree(), PermissionLvl::Three); + dispatcher.register(cmd_worldborder::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_teleport::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_time::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_give::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_list::init_command_tree(), PermissionLvl::Zero); + dispatcher.register(cmd_clear::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_setblock::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_seed::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_transfer::init_command_tree(), PermissionLvl::Zero); + dispatcher.register(cmd_fill::init_command_tree(), PermissionLvl::Two); + dispatcher.register(cmd_op::init_command_tree(), PermissionLvl::Three); dispatcher } diff --git a/pumpkin/src/command/tree_builder.rs b/pumpkin/src/command/tree_builder.rs index 92f65d9e6..f9d5bff99 100644 --- a/pumpkin/src/command/tree_builder.rs +++ b/pumpkin/src/command/tree_builder.rs @@ -1,12 +1,11 @@ use std::sync::Arc; +use super::args::DefaultNameArgConsumer; +use super::CommandExecutor; use crate::command::args::ArgumentConsumer; use crate::command::tree::{CommandTree, Node, NodeType}; use crate::command::CommandSender; -use super::args::DefaultNameArgConsumer; -use super::CommandExecutor; - impl CommandTree { /// Add a child [Node] to the root of this [`CommandTree`]. pub fn with_child(mut self, child: impl NodeBuilder) -> Self { From f4de9e41c8600257909c7502240b83687d696d4d Mon Sep 17 00:00:00 2001 From: DataModel <183248792+DataM0del@users.noreply.github.com> Date: Sun, 29 Dec 2024 11:19:14 -0500 Subject: [PATCH 5/7] kick for self-attacking (#430) * fix(combat): kick for self-attacking * chore(combat): fix the duplication of the word client * chore(pumpkin/src/net/packet/play.rs#Player/handle_interact): remove useless parens * fix(combat): compare entity IDs, not actual objects * chore(pumpkin/src/net/packet/play): `cargo fmt` --- pumpkin/src/net/packet/play.rs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/pumpkin/src/net/packet/play.rs b/pumpkin/src/net/packet/play.rs index baf904659..d47a72355 100644 --- a/pumpkin/src/net/packet/play.rs +++ b/pumpkin/src/net/packet/play.rs @@ -556,10 +556,16 @@ impl Player { return; }; if victim.living_entity.health.load() <= 0.0 { - // you can trigger this from a non-modded / innocent client client, + // you can trigger this from a non-modded / innocent client, // so we shouldn't kick the player return; } + if victim.entity_id() == self.entity_id() { + // this, however, can't be triggered from a non-modded client. + self.kick(TextComponent::text("You can't attack yourself")) + .await; + return; + } self.attack(&victim).await; } ActionType::Interact | ActionType::InteractAt => { From b40c27444586cade80b560653ac443d0d76c5115 Mon Sep 17 00:00:00 2001 From: Alexander Medvedev Date: Sun, 29 Dec 2024 18:15:39 +0100 Subject: [PATCH 6/7] extractor moved to: https://github.com/Pumpkin-MC/Extractor --- extractor/build.gradle.kts | 103 ------- extractor/gradle.properties | 14 - .../gradle/wrapper/gradle-wrapper.properties | 7 - extractor/gradlew | 251 ------------------ extractor/gradlew.bat | 94 ------- extractor/settings.gradle.kts | 8 - .../kotlin/de/snowii/extractor/Extractor.kt | 70 ----- .../de/snowii/extractor/extractors/Blocks.kt | 116 -------- .../snowii/extractor/extractors/Entities.kt | 42 --- .../de/snowii/extractor/extractors/Items.kt | 41 --- .../de/snowii/extractor/extractors/Packets.kt | 105 -------- .../snowii/extractor/extractors/Particles.kt | 25 -- .../de/snowii/extractor/extractors/Recipes.kt | 30 --- .../de/snowii/extractor/extractors/Screens.kt | 24 -- .../de/snowii/extractor/extractors/Sounds.kt | 25 -- .../extractor/extractors/SyncedRegistries.kt | 50 ---- .../de/snowii/extractor/extractors/Tags.kt | 40 --- .../de/snowii/extractor/extractors/Tests.kt | 137 ---------- extractor/src/main/resources/fabric.mod.json | 22 -- 19 files changed, 1204 deletions(-) delete mode 100644 extractor/build.gradle.kts delete mode 100644 extractor/gradle.properties delete mode 100644 extractor/gradle/wrapper/gradle-wrapper.properties delete mode 100755 extractor/gradlew delete mode 100644 extractor/gradlew.bat delete mode 100644 extractor/settings.gradle.kts delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/Extractor.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Blocks.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Entities.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Items.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Packets.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Particles.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Recipes.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Screens.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Sounds.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/SyncedRegistries.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Tags.kt delete mode 100644 extractor/src/main/kotlin/de/snowii/extractor/extractors/Tests.kt delete mode 100644 extractor/src/main/resources/fabric.mod.json diff --git a/extractor/build.gradle.kts b/extractor/build.gradle.kts deleted file mode 100644 index 944a30d35..000000000 --- a/extractor/build.gradle.kts +++ /dev/null @@ -1,103 +0,0 @@ -import org.jetbrains.kotlin.gradle.dsl.JvmTarget -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile - -plugins { - kotlin("jvm") version "2.1.0" - id("fabric-loom") version "1.9-SNAPSHOT" - id("maven-publish") -} - -version = project.property("mod_version") as String -group = project.property("maven_group") as String - -base { - archivesName.set(project.property("archives_base_name") as String) -} - -val targetJavaVersion = 21 -java { - toolchain.languageVersion = JavaLanguageVersion.of(targetJavaVersion) - // Loom will automatically attach sourcesJar to a RemapSourcesJar task and to the "build" task - // if it is present. - // If you remove this line, sources will not be generated. - withSourcesJar() -} - -loom { - splitEnvironmentSourceSets() - - mods { - register("extractor") { - sourceSet("main") - } - } -} - -repositories { - // Add repositories to retrieve artifacts from in here. - // You should only use this when depending on other mods because - // Loom adds the essential maven repositories to download Minecraft and libraries from automatically. - // See https://docs.gradle.org/current/userguide/declaring_repositories.html - // for more information about repositories. -} - -dependencies { - // To change the versions see the gradle.properties file - minecraft("com.mojang:minecraft:${project.property("minecraft_version")}") - mappings("net.fabricmc:yarn:${project.property("yarn_mappings")}:v2") - modImplementation("net.fabricmc:fabric-loader:${project.property("loader_version")}") - modImplementation("net.fabricmc:fabric-language-kotlin:${project.property("kotlin_loader_version")}") - - modImplementation("net.fabricmc.fabric-api:fabric-api:${project.property("fabric_version")}") - - // To allow for reflection - implementation(kotlin("reflect")) -} - -tasks.processResources { - inputs.property("version", project.version) - inputs.property("minecraft_version", project.property("minecraft_version")) - inputs.property("loader_version", project.property("loader_version")) - filteringCharset = "UTF-8" - - filesMatching("fabric.mod.json") { - expand( - "version" to project.version, - "minecraft_version" to project.property("minecraft_version"), - "loader_version" to project.property("loader_version"), - "kotlin_loader_version" to project.property("kotlin_loader_version") - ) - } -} - -tasks.withType().configureEach { - // ensure that the encoding is set to UTF-8, no matter what the system default is - // this fixes some edge cases with special characters not displaying correctly - // see http://yodaconditions.net/blog/fix-for-java-file-encoding-problems-with-gradle.html - // If Javadoc is generated, this must be specified in that task too. - options.encoding = "UTF-8" - options.release.set(targetJavaVersion) -} - -tasks.withType().configureEach { - compilerOptions.jvmTarget.set(JvmTarget.fromTarget(targetJavaVersion.toString())) -} - - -// configure the maven publication -publishing { - publications { - create("mavenJava") { - artifactId = project.property("archives_base_name") as String - from(components["java"]) - } - } - - // See https://docs.gradle.org/current/userguide/publishing_maven.html for information on how to set up publishing. - repositories { - // Add repositories to publish to here. - // Notice: This block does NOT have the same function as the block in the top level. - // The repositories here will be used for publishing your artifact, not for - // retrieving dependencies. - } -} diff --git a/extractor/gradle.properties b/extractor/gradle.properties deleted file mode 100644 index 880c97721..000000000 --- a/extractor/gradle.properties +++ /dev/null @@ -1,14 +0,0 @@ -# Done to increase the memory available to gradle. -org.gradle.jvmargs=-Xmx1G -org.gradle.parallel=true -# Fabric Properties -# check these on https://modmuss50.me/fabric.html -minecraft_version=1.21.4 -yarn_mappings=1.21.4+build.2 -loader_version=0.16.9 -kotlin_loader_version=1.13.0+kotlin.2.1.0 -# Mod Properties -mod_version=1.0-SNAPSHOT -maven_group=de.snowii -archives_base_name=extractor -fabric_version=0.113.0+1.21.4 diff --git a/extractor/gradle/wrapper/gradle-wrapper.properties b/extractor/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index cea7a793a..000000000 --- a/extractor/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/extractor/gradlew b/extractor/gradlew deleted file mode 100755 index 057afac53..000000000 --- a/extractor/gradlew +++ /dev/null @@ -1,251 +0,0 @@ -#!/bin/sh - -# -# Copyright © 2015-2021 the original authors. -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# https://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# SPDX-License-Identifier: Apache-2.0 -# - -############################################################################## -# -# Gradle start up script for POSIX generated by Gradle. -# -# Important for running: -# -# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is -# noncompliant, but you have some other compliant shell such as ksh or -# bash, then to run this script, type that shell name before the whole -# command line, like: -# -# ksh Gradle -# -# Busybox and similar reduced shells will NOT work, because this script -# requires all of these POSIX shell features: -# * functions; -# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», -# «${var#prefix}», «${var%suffix}», and «$( cmd )»; -# * compound commands having a testable exit status, especially «case»; -# * various built-in commands including «command», «set», and «ulimit». -# -# Important for patching: -# -# (2) This script targets any POSIX shell, so it avoids extensions provided -# by Bash, Ksh, etc; in particular arrays are avoided. -# -# The "traditional" practice of packing multiple parameters into a -# space-separated string is a well documented source of bugs and security -# problems, so this is (mostly) avoided, by progressively accumulating -# options in "$@", and eventually passing that to Java. -# -# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, -# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; -# see the in-line comments for details. -# -# There are tweaks for specific operating systems such as AIX, CygWin, -# Darwin, MinGW, and NonStop. -# -# (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt -# within the Gradle project. -# -# You can find Gradle at https://github.com/gradle/gradle/. -# -############################################################################## - -# Attempt to set APP_HOME - -# Resolve links: $0 may be a link -app_path=$0 - -# Need this for daisy-chained symlinks. -while - APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path - [ -h "$app_path" ] -do - ls=$( ls -ld "$app_path" ) - link=${ls#*' -> '} - case $link in #( - /*) app_path=$link ;; #( - *) app_path=$APP_HOME$link ;; - esac -done - -# This is normally unused -# shellcheck disable=SC2034 -APP_BASE_NAME=${0##*/} -# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) -APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit - -# Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD=maximum - -warn () { - echo "$*" -} >&2 - -die () { - echo - echo "$*" - echo - exit 1 -} >&2 - -# OS specific support (must be 'true' or 'false'). -cygwin=false -msys=false -darwin=false -nonstop=false -case "$( uname )" in #( - CYGWIN* ) cygwin=true ;; #( - Darwin* ) darwin=true ;; #( - MSYS* | MINGW* ) msys=true ;; #( - NONSTOP* ) nonstop=true ;; -esac - -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar - - -# Determine the Java command to use to start the JVM. -if [ -n "$JAVA_HOME" ] ; then - if [ -x "$JAVA_HOME/jre/sh/java" ] ; then - # IBM's JDK on AIX uses strange locations for the executables - JAVACMD=$JAVA_HOME/jre/sh/java - else - JAVACMD=$JAVA_HOME/bin/java - fi - if [ ! -x "$JAVACMD" ] ; then - die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -else - JAVACMD=java - if ! command -v java >/dev/null 2>&1 - then - die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. - -Please set the JAVA_HOME variable in your environment to match the -location of your Java installation." - fi -fi - -# Increase the maximum file descriptors if we can. -if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then - case $MAX_FD in #( - max*) - # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - MAX_FD=$( ulimit -H -n ) || - warn "Could not query maximum file descriptor limit" - esac - case $MAX_FD in #( - '' | soft) :;; #( - *) - # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. - # shellcheck disable=SC2039,SC3045 - ulimit -n "$MAX_FD" || - warn "Could not set maximum file descriptor limit to $MAX_FD" - esac -fi - -# Collect all arguments for the java command, stacking in reverse order: -# * args from the command line -# * the main class name -# * -classpath -# * -D...appname settings -# * --module-path (only if needed) -# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. - -# For Cygwin or MSYS, switch paths to Windows format before running java -if "$cygwin" || "$msys" ; then - APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) - - JAVACMD=$( cygpath --unix "$JAVACMD" ) - - # Now convert the arguments - kludge to limit ourselves to /bin/sh - for arg do - if - case $arg in #( - -*) false ;; # don't mess with options #( - /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath - [ -e "$t" ] ;; #( - *) false ;; - esac - then - arg=$( cygpath --path --ignore --mixed "$arg" ) - fi - # Roll the args list around exactly as many times as the number of - # args, so each arg winds up back in the position where it started, but - # possibly modified. - # - # NB: a `for` loop captures its iteration list before it begins, so - # changing the positional parameters here affects neither the number of - # iterations, nor the values presented in `arg`. - shift # remove old arg - set -- "$@" "$arg" # push replacement arg - done -fi - - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' - -# Collect all arguments for the java command: -# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, -# and any embedded shellness will be escaped. -# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be -# treated as '${Hostname}' itself on the command line. - -set -- \ - "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ - "$@" - -# Stop when "xargs" is not available. -if ! command -v xargs >/dev/null 2>&1 -then - die "xargs is not available" -fi - -# Use "xargs" to parse quoted args. -# -# With -n1 it outputs one arg per line, with the quotes and backslashes removed. -# -# In Bash we could simply go: -# -# readarray ARGS < <( xargs -n1 <<<"$var" ) && -# set -- "${ARGS[@]}" "$@" -# -# but POSIX shell has neither arrays nor command substitution, so instead we -# post-process each arg (as a line of input to sed) to backslash-escape any -# character that might be a shell metacharacter, then use eval to reverse -# that process (while maintaining the separation between arguments), and wrap -# the whole thing up as a single "set" statement. -# -# This will of course break if any of these variables contains a newline or -# an unmatched quote. -# - -eval "set -- $( - printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | - xargs -n1 | - sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | - tr '\n' ' ' - )" '"$@"' - -exec "$JAVACMD" "$@" diff --git a/extractor/gradlew.bat b/extractor/gradlew.bat deleted file mode 100644 index 6a90cee9b..000000000 --- a/extractor/gradlew.bat +++ /dev/null @@ -1,94 +0,0 @@ -@rem -@rem Copyright 2015 the original author or authors. -@rem -@rem Licensed under the Apache License, Version 2.0 (the "License"); -@rem you may not use this file except in compliance with the License. -@rem You may obtain a copy of the License at -@rem -@rem https://www.apache.org/licenses/LICENSE-2.0 -@rem -@rem Unless required by applicable law or agreed to in writing, software -@rem distributed under the License is distributed on an "AS IS" BASIS, -@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -@rem See the License for the specific language governing permissions and -@rem limitations under the License. -@rem -@rem SPDX-License-Identifier: Apache-2.0 -@rem - -@if "%DEBUG%"=="" @echo off -@rem ########################################################################## -@rem -@rem Gradle startup script for Windows -@rem -@rem ########################################################################## - -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal - -set DIRNAME=%~dp0 -if "%DIRNAME%"=="" set DIRNAME=. -@rem This is normally unused -set APP_BASE_NAME=%~n0 -set APP_HOME=%DIRNAME% - -@rem Resolve any "." and ".." in APP_HOME to make it shorter. -for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi - -@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" - -@rem Find java.exe -if defined JAVA_HOME goto findJavaFromJavaHome - -set JAVA_EXE=java.exe -%JAVA_EXE% -version >NUL 2>&1 -if %ERRORLEVEL% equ 0 goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:findJavaFromJavaHome -set JAVA_HOME=%JAVA_HOME:"=% -set JAVA_EXE=%JAVA_HOME%/bin/java.exe - -if exist "%JAVA_EXE%" goto execute - -echo. 1>&2 -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 -echo. 1>&2 -echo Please set the JAVA_HOME variable in your environment to match the 1>&2 -echo location of your Java installation. 1>&2 - -goto fail - -:execute -@rem Setup the command line - -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if %ERRORLEVEL% equ 0 goto mainEnd - -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -set EXIT_CODE=%ERRORLEVEL% -if %EXIT_CODE% equ 0 set EXIT_CODE=1 -if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% -exit /b %EXIT_CODE% - -:mainEnd -if "%OS%"=="Windows_NT" endlocal - -:omega diff --git a/extractor/settings.gradle.kts b/extractor/settings.gradle.kts deleted file mode 100644 index 05eb23d12..000000000 --- a/extractor/settings.gradle.kts +++ /dev/null @@ -1,8 +0,0 @@ -pluginManagement { - repositories { - maven("https://maven.fabricmc.net/") { - name = "Fabric" - } - gradlePluginPortal() - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/Extractor.kt b/extractor/src/main/kotlin/de/snowii/extractor/Extractor.kt deleted file mode 100644 index 2f47fe63c..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/Extractor.kt +++ /dev/null @@ -1,70 +0,0 @@ -package de.snowii.extractor - -import com.google.gson.GsonBuilder -import com.google.gson.JsonElement -import de.snowii.extractor.extractors.* -import net.fabricmc.api.ModInitializer -import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents -import net.minecraft.server.MinecraftServer -import org.slf4j.Logger -import org.slf4j.LoggerFactory -import java.io.FileWriter -import java.io.IOException -import java.nio.charset.StandardCharsets -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.Paths - - -class Extractor : ModInitializer { - private val modID: String = "pumpkin_extractor" - private val logger: Logger = LoggerFactory.getLogger(modID) - - override fun onInitialize() { - logger.info("Starting Pumpkin Extractor") - val extractors = arrayOf( - Sounds(), - Recipes(), - Particles(), - SyncedRegistries(), - Packets(), - Screens(), - Tags(), - Entities(), - Items(), - Blocks(), - Tests(), - ) - - val outputDirectory: Path - try { - outputDirectory = Files.createDirectories(Paths.get("pumpkin_extractor_output")) - } catch (e: IOException) { - logger.info("Failed to create output directory.", e) - return - } - - val gson = GsonBuilder().disableHtmlEscaping().create() - - ServerLifecycleEvents.SERVER_STARTED.register(ServerLifecycleEvents.ServerStarted { server: MinecraftServer -> - for (ext in extractors) { - try { - val out = outputDirectory.resolve(ext.fileName()) - val fileWriter = FileWriter(out.toFile(), StandardCharsets.UTF_8) - gson.toJson(ext.extract(server), fileWriter) - fileWriter.close() - logger.info("Wrote " + out.toAbsolutePath()) - } catch (e: java.lang.Exception) { - logger.error(("Extractor for \"" + ext.fileName()) + "\" failed.", e) - } - } - }) - } - - interface Extractor { - fun fileName(): String - - @Throws(Exception::class) - fun extract(server: MinecraftServer): JsonElement - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Blocks.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Blocks.kt deleted file mode 100644 index b4d3a82d2..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Blocks.kt +++ /dev/null @@ -1,116 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import de.snowii.extractor.Extractor -import net.minecraft.block.Block -import net.minecraft.registry.Registries -import net.minecraft.server.MinecraftServer -import net.minecraft.util.math.BlockPos -import net.minecraft.util.math.Box -import net.minecraft.world.EmptyBlockView -import java.util.* - -class Blocks : Extractor.Extractor { - override fun fileName(): String { - return "blocks.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val topLevelJson = JsonObject() - - val blocksJson = JsonArray() - - val shapes: LinkedHashMap = LinkedHashMap() - - for (block in Registries.BLOCK) { - val blockJson = JsonObject() - blockJson.addProperty("id", Registries.BLOCK.getRawId(block)) - blockJson.addProperty("name", Registries.BLOCK.getId(block).path) - blockJson.addProperty("translation_key", block.translationKey) - blockJson.addProperty("hardness", block.hardness) - blockJson.addProperty("item_id", Registries.ITEM.getRawId(block.asItem())) - - val propsJson = JsonArray() - for (prop in block.stateManager.properties) { - val propJson = JsonObject() - - propJson.addProperty("name", prop.name) - - val valuesJson = JsonArray() - for (value in prop.values) { - valuesJson.add(value.toString().lowercase()) - } - propJson.add("values", valuesJson) - - propsJson.add(propJson) - } - blockJson.add("properties", propsJson) - - val statesJson = JsonArray() - for (state in block.stateManager.states) { - val stateJson = JsonObject() - stateJson.addProperty("id", Block.getRawIdFromState(state)) - stateJson.addProperty("air", state.isAir) - stateJson.addProperty("luminance", state.luminance) - stateJson.addProperty("burnable", state.isBurnable) - if (state.isOpaque) { - stateJson.addProperty("opacity", state.opacity) - } - stateJson.addProperty("sided_transparency", state.hasSidedTransparency()) - stateJson.addProperty("replaceable", state.isReplaceable) - - if (block.defaultState == state) { - blockJson.addProperty("default_state_id", Block.getRawIdFromState(state)) - } - - val collisionShapeIdxsJson = JsonArray() - for (box in state.getCollisionShape(EmptyBlockView.INSTANCE, BlockPos.ORIGIN).boundingBoxes) { - val idx = shapes.putIfAbsent(box, shapes.size) - collisionShapeIdxsJson.add(Objects.requireNonNullElseGet(idx) { shapes.size - 1 }) - } - - stateJson.add("collision_shapes", collisionShapeIdxsJson) - - for (blockEntity in Registries.BLOCK_ENTITY_TYPE) { - if (blockEntity.supports(state)) { - stateJson.addProperty("block_entity_type", Registries.BLOCK_ENTITY_TYPE.getRawId(blockEntity)) - } - } - - statesJson.add(stateJson) - } - blockJson.add("states", statesJson) - - blocksJson.add(blockJson) - } - - val blockEntitiesJson = JsonArray() - for (blockEntity in Registries.BLOCK_ENTITY_TYPE) { - blockEntitiesJson.add(Registries.BLOCK_ENTITY_TYPE.getId(blockEntity)!!.path) - } - - val shapesJson = JsonArray() - for (shape in shapes.keys) { - val shapeJson = JsonObject() - val min = JsonArray() - min.add(shape.minX) - min.add(shape.minY) - min.add(shape.minZ) - val max = JsonArray() - max.add(shape.maxX) - max.add(shape.maxY) - max.add(shape.maxZ) - shapeJson.add("min", min) - shapeJson.add("max", max) - shapesJson.add(shapeJson) - } - - topLevelJson.add("block_entity_types", blockEntitiesJson) - topLevelJson.add("shapes", shapesJson) - topLevelJson.add("blocks", blocksJson) - - return topLevelJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Entities.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Entities.kt deleted file mode 100644 index 475047118..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Entities.kt +++ /dev/null @@ -1,42 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import de.snowii.extractor.Extractor -import net.minecraft.entity.LivingEntity -import net.minecraft.entity.SpawnReason -import net.minecraft.registry.Registries -import net.minecraft.server.MinecraftServer - -class Entities : Extractor.Extractor { - override fun fileName(): String { - return "entities.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val entitiesJson = JsonObject() - for (entityType in Registries.ENTITY_TYPE) { - val entity = entityType.create(server.overworld!!, SpawnReason.NATURAL) ?: continue - val entityJson = JsonObject() - entityJson.addProperty("id", Registries.ENTITY_TYPE.getRawId(entityType)) - if (entity is LivingEntity) { - entityJson.addProperty("max_health", entity.maxHealth) - - } - entityJson.addProperty("attackable", entity.isAttackable) - entityJson.addProperty("summonable", entityType.isSummonable) - entityJson.addProperty("fire_immune", entityType.isFireImmune) - val dimension = JsonArray() - dimension.add(entityType.dimensions.width) - dimension.add(entityType.dimensions.height) - entityJson.add("dimension", dimension) - - entitiesJson.add( - Registries.ENTITY_TYPE.getId(entityType).path, entityJson - ) - } - - return entitiesJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Items.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Items.kt deleted file mode 100644 index ec76836f5..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Items.kt +++ /dev/null @@ -1,41 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import com.mojang.serialization.JsonOps -import de.snowii.extractor.Extractor -import net.minecraft.component.ComponentMap -import net.minecraft.item.Item -import net.minecraft.registry.Registries -import net.minecraft.registry.RegistryKeys -import net.minecraft.registry.RegistryOps -import net.minecraft.server.MinecraftServer - - -class Items : Extractor.Extractor { - override fun fileName(): String { - return "items.json" - } - - - override fun extract(server: MinecraftServer): JsonElement { - val itemsJson = JsonObject() - - for (item in server.registryManager.getOrThrow(RegistryKeys.ITEM).streamEntries().toList()) { - val itemJson = JsonObject() - val realItem: Item = item.value() - - itemJson.addProperty("id", Registries.ITEM.getRawId(realItem)) - itemJson.add( - "components", - ComponentMap.CODEC.encodeStart( - RegistryOps.of(JsonOps.INSTANCE, server.registryManager), - realItem.components - ).getOrThrow() - ) - - itemsJson.add(Registries.ITEM.getId(realItem).path, itemJson) - } - return itemsJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Packets.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Packets.kt deleted file mode 100644 index 548c87a3e..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Packets.kt +++ /dev/null @@ -1,105 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import de.snowii.extractor.Extractor -import io.netty.buffer.ByteBuf -import net.minecraft.network.NetworkPhase -import net.minecraft.network.NetworkState -import net.minecraft.network.PacketByteBuf -import net.minecraft.network.listener.ClientPacketListener -import net.minecraft.network.listener.ServerCrashSafePacketListener -import net.minecraft.network.packet.PacketType -import net.minecraft.network.state.* -import net.minecraft.server.MinecraftServer - - -class Packets : Extractor.Extractor { - override fun fileName(): String { - return "packets.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val packetsJson = JsonObject() - - val clientBound = arrayOf( - QueryStates.S2C_FACTORY, - LoginStates.S2C_FACTORY, - ConfigurationStates.S2C_FACTORY, - PlayStateFactories.S2C - ) - - val serverBound = arrayOf( - HandshakeStates.C2S_FACTORY, - QueryStates.C2S_FACTORY, - LoginStates.C2S_FACTORY, - ConfigurationStates.C2S_FACTORY, - PlayStateFactories.C2S - ) - val serverBoundJson = serializeServerBound(serverBound) - val clientBoundJson = serializeClientBound(clientBound) - - packetsJson.add("serverbound", serverBoundJson) - packetsJson.add("clientbound", clientBoundJson) - - return packetsJson - } - - - private fun serializeServerBound( - packets: Array> - ): JsonObject { - val handshakeArray = JsonArray() - val statusArray = JsonArray() - val loginArray = JsonArray() - val configArray = JsonArray() - val playArray = JsonArray() - - for (factory in packets) { - factory.forEachPacketType { type: PacketType<*>, _: Int -> - when (factory.phase()!!) { - NetworkPhase.HANDSHAKING -> handshakeArray.add(type.id().path) - NetworkPhase.PLAY -> playArray.add(type.id().path) - NetworkPhase.STATUS -> statusArray.add(type.id().path) - NetworkPhase.LOGIN -> loginArray.add(type.id().path) - NetworkPhase.CONFIGURATION -> configArray.add(type.id().path) - } - } - } - val finalJson = JsonObject() - finalJson.add("handshake", handshakeArray) - finalJson.add("status", statusArray) - finalJson.add("login", loginArray) - finalJson.add("config", configArray) - finalJson.add("play", playArray) - return finalJson - } - - private fun serializeClientBound( - packets: Array> - ): JsonObject { - val statusArray = JsonArray() - val loginArray = JsonArray() - val configArray = JsonArray() - val playArray = JsonArray() - - for (factory in packets) { - factory.forEachPacketType { type: PacketType<*>, _: Int -> - when (factory.phase()!!) { - NetworkPhase.HANDSHAKING -> error("Client bound Packet should have no handshake") - NetworkPhase.PLAY -> playArray.add(type.id().path) - NetworkPhase.STATUS -> statusArray.add(type.id().path) - NetworkPhase.LOGIN -> loginArray.add(type.id().path) - NetworkPhase.CONFIGURATION -> configArray.add(type.id().path) - } - } - } - val finalJson = JsonObject() - finalJson.add("status", statusArray) - finalJson.add("login", loginArray) - finalJson.add("config", configArray) - finalJson.add("play", playArray) - return finalJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Particles.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Particles.kt deleted file mode 100644 index 26d08d528..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Particles.kt +++ /dev/null @@ -1,25 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import de.snowii.extractor.Extractor -import net.minecraft.registry.Registries -import net.minecraft.server.MinecraftServer - - -class Particles : Extractor.Extractor { - override fun fileName(): String { - return "particles.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val particlesJson = JsonArray() - for (particle in Registries.PARTICLE_TYPE) { - particlesJson.add( - Registries.PARTICLE_TYPE.getId(particle)!!.path, - ) - } - - return particlesJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Recipes.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Recipes.kt deleted file mode 100644 index 6e1657df1..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Recipes.kt +++ /dev/null @@ -1,30 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.mojang.serialization.JsonOps -import de.snowii.extractor.Extractor -import net.minecraft.recipe.Recipe -import net.minecraft.registry.RegistryOps -import net.minecraft.server.MinecraftServer - -class Recipes : Extractor.Extractor { - override fun fileName(): String { - return "recipes.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val recipesJson = JsonArray() - - for (recipeRaw in server.recipeManager.values()) { - val recipe = recipeRaw.value - recipesJson.add( - Recipe.CODEC.encodeStart( - RegistryOps.of(JsonOps.INSTANCE, server.registryManager), - recipe - ).getOrThrow() - ) - } - return recipesJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Screens.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Screens.kt deleted file mode 100644 index d52b90745..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Screens.kt +++ /dev/null @@ -1,24 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import de.snowii.extractor.Extractor -import net.minecraft.registry.Registries -import net.minecraft.server.MinecraftServer - -class Screens : Extractor.Extractor { - override fun fileName(): String { - return "screens.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val screensJson = JsonArray() - for (screen in Registries.SCREEN_HANDLER) { - screensJson.add( - Registries.SCREEN_HANDLER.getId(screen)!!.path, - ) - } - - return screensJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Sounds.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Sounds.kt deleted file mode 100644 index 3efdc42c4..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Sounds.kt +++ /dev/null @@ -1,25 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import de.snowii.extractor.Extractor -import net.minecraft.registry.Registries -import net.minecraft.server.MinecraftServer - - -class Sounds : Extractor.Extractor { - override fun fileName(): String { - return "sounds.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val soundJson = JsonArray() - for (sound in Registries.SOUND_EVENT) { - soundJson.add( - Registries.SOUND_EVENT.getId(sound)!!.path, - ) - } - - return soundJson - } -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/SyncedRegistries.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/SyncedRegistries.kt deleted file mode 100644 index 207adadbb..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/SyncedRegistries.kt +++ /dev/null @@ -1,50 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import com.mojang.serialization.Codec -import com.mojang.serialization.JsonOps -import de.snowii.extractor.Extractor -import net.minecraft.registry.* -import net.minecraft.server.MinecraftServer -import java.util.stream.Stream - - -class SyncedRegistries : Extractor.Extractor { - override fun fileName(): String { - return "synced_registries.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val registries: Stream> = RegistryLoader.SYNCED_REGISTRIES.stream() - val json = JsonObject() - registries.forEach { entry -> - json.add( - entry.key().value.path, - mapJson(entry, server.registryManager, server.combinedDynamicRegistries) - ) - } - return json - } - - private fun mapJson( - registryEntry: RegistryLoader.Entry, - registryManager: DynamicRegistryManager.Immutable, - combinedRegistries: CombinedDynamicRegistries - ): JsonObject { - val codec: Codec = registryEntry.elementCodec() - val registry: Registry = registryManager.getOrThrow(registryEntry.key()) - val json = JsonObject() - registry.streamEntries().forEach { entry -> - json.add( - entry.key.orElseThrow().value.path, - codec.encodeStart( - combinedRegistries.combinedRegistryManager.getOps(JsonOps.INSTANCE), - entry.value() - ).getOrThrow() - ) - } - return json - } - -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tags.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tags.kt deleted file mode 100644 index 85a9ece13..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tags.kt +++ /dev/null @@ -1,40 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import com.google.gson.JsonObject -import de.snowii.extractor.Extractor -import net.minecraft.registry.tag.TagPacketSerializer -import net.minecraft.server.MinecraftServer - - -class Tags : Extractor.Extractor { - override fun fileName(): String { - return "tags.json" - } - - override fun extract(server: MinecraftServer): JsonElement { - val tagsJson = JsonArray() - - val tags = TagPacketSerializer.serializeTags(server.combinedDynamicRegistries) - - for (tag in tags.entries) { - val tagGroupTagsJson = JsonObject() - tagGroupTagsJson.addProperty("name", tag.key.value.path) - val tagValues = - tag.value.toRegistryTags(server.combinedDynamicRegistries.combinedRegistryManager.getOrThrow(tag.key)) - for (value in tagValues.tags) { - val tagGroupTagsJsonArray = JsonArray() - for (tagVal in value.value) { - tagGroupTagsJsonArray.add(tagVal.key.orElseThrow().value.path) - } - tagGroupTagsJson.add(value.key.id.path, tagGroupTagsJsonArray) - } - tagsJson.add(tagGroupTagsJson) - } - - return tagsJson - } - - -} diff --git a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tests.kt b/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tests.kt deleted file mode 100644 index e75a1797d..000000000 --- a/extractor/src/main/kotlin/de/snowii/extractor/extractors/Tests.kt +++ /dev/null @@ -1,137 +0,0 @@ -package de.snowii.extractor.extractors - -import com.google.gson.JsonArray -import com.google.gson.JsonElement -import de.snowii.extractor.Extractor -import net.minecraft.block.Block -import net.minecraft.block.BlockState -import net.minecraft.block.Blocks -import net.minecraft.registry.BuiltinRegistries -import net.minecraft.registry.RegistryKeys -import net.minecraft.server.MinecraftServer -import net.minecraft.util.math.ChunkPos -import net.minecraft.world.gen.chunk.* -import net.minecraft.world.gen.densityfunction.DensityFunction.EachApplier -import net.minecraft.world.gen.densityfunction.DensityFunction.NoisePos -import net.minecraft.world.gen.densityfunction.DensityFunctionTypes -import net.minecraft.world.gen.noise.NoiseConfig -import kotlin.reflect.KFunction -import kotlin.reflect.full.declaredFunctions - -class Tests : Extractor.Extractor { - override fun fileName(): String = "chunk.json" - - private fun createFluidLevelSampler(settings: ChunkGeneratorSettings): AquiferSampler.FluidLevelSampler { - val fluidLevel = AquiferSampler.FluidLevel(-54, Blocks.LAVA.defaultState) - val i = settings.seaLevel() - val fluidLevel2 = AquiferSampler.FluidLevel(i, settings.defaultFluid()) - return AquiferSampler.FluidLevelSampler { _, y, _ -> if (y < Math.min(-54, i)) fluidLevel else fluidLevel2 } - } - - private fun get_index(config: GenerationShapeConfig, x: Int, y: Int, z: Int): Int { - if (x < 0 || y < 0 || z < 0) { - System.err.println("Bad local pos") - System.exit(1) - } - return config.height() * 16 * x + 16 * y + z - } - - // This is basically just what NoiseChunkGenerator is doing - private fun populate_noise( - start_x: Int, - start_z: Int, - sampler: ChunkNoiseSampler, - config: GenerationShapeConfig, - settings: ChunkGeneratorSettings - ): IntArray? { - val result = IntArray(16 * 16 * config.height()) - - for (method: KFunction<*> in sampler::class.declaredFunctions) { - if (method.name.equals("sampleBlockState")) { - sampler.sampleStartDensity() - val k = config.horizontalCellBlockCount() - val l = config.verticalCellBlockCount() - - val m = 16 / k - val n = 16 / k - - val cellHeight = config.height() / l - val minimumCellY = config.minimumY() / l - - for (o in 0.. - topLevelJson.add(state) - } - - return topLevelJson - } -} diff --git a/extractor/src/main/resources/fabric.mod.json b/extractor/src/main/resources/fabric.mod.json deleted file mode 100644 index 695e56e8a..000000000 --- a/extractor/src/main/resources/fabric.mod.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "schemaVersion": 1, - "id": "extractor", - "version": "${version}", - "name": "pumpkin-extractor", - "description": "", - "authors": [], - "contact": {}, - "license": "MIT", - "environment": "*", - "entrypoints": { - "main": [ - "de.snowii.extractor.Extractor" - ] - }, - "depends": { - "fabricloader": ">=${loader_version}", - "fabric-language-kotlin": ">=${kotlin_loader_version}", - "fabric": "*", - "minecraft": "${minecraft_version}" - } -} From 02cec5873b908566affcd8fb80d461d47fe3bace Mon Sep 17 00:00:00 2001 From: Adel C <48925842+Bafran@users.noreply.github.com> Date: Sun, 29 Dec 2024 10:04:57 -0800 Subject: [PATCH 7/7] Add Pick block (Middle Mouse Click) (#418) * Pick Item Changes * Changed some logging * Pick Item working for hotbar slots * Basic functionality, changes needed to adhere to expected minecraft behaviour * Clean up code * Added todo for pick from entity * Added item swapping * Swapping and cleanup * Fix for rebase * Remove unused function * Bugfix * remove todo --------- Co-authored-by: Alexander Medvedev --- pumpkin-inventory/src/player.rs | 29 +++++ pumpkin-protocol/src/server/play/mod.rs | 2 + .../src/server/play/s_pick_item.rs | 17 +++ pumpkin/src/entity/player.rs | 12 +- pumpkin/src/net/packet/play.rs | 105 +++++++++++++++++- 5 files changed, 159 insertions(+), 6 deletions(-) create mode 100644 pumpkin-protocol/src/server/play/s_pick_item.rs diff --git a/pumpkin-inventory/src/player.rs b/pumpkin-inventory/src/player.rs index 3a230385c..f406ba5a6 100644 --- a/pumpkin-inventory/src/player.rs +++ b/pumpkin-inventory/src/player.rs @@ -116,6 +116,35 @@ impl PlayerInventory { &mut self.items[self.selected + 36 - 9] } + pub fn get_slot_with_item(&self, item_id: u16) -> Option { + for slot in 9..=44 { + match &self.items[slot - 9] { + Some(item) if item.item_id == item_id => return Some(slot), + _ => continue, + } + } + + None + } + + pub fn get_pick_item_hotbar_slot(&self) -> usize { + if self.items[self.selected + 36 - 9].is_none() { + return self.selected; + } + + for slot in 0..9 { + if self.items[slot + 36 - 9].is_none() { + return slot; + } + } + + self.selected + } + + pub fn get_empty_slot(&self) -> Option { + (9..=44).find(|&slot| self.items[slot - 9].is_none()) + } + pub fn slots(&self) -> Vec> { let mut slots = vec![self.crafting_output.as_ref()]; slots.extend(self.crafting.iter().map(|c| c.as_ref())); diff --git a/pumpkin-protocol/src/server/play/mod.rs b/pumpkin-protocol/src/server/play/mod.rs index 3fa607d6c..3995f3326 100644 --- a/pumpkin-protocol/src/server/play/mod.rs +++ b/pumpkin-protocol/src/server/play/mod.rs @@ -10,6 +10,7 @@ mod s_confirm_teleport; mod s_cookie_response; mod s_interact; mod s_keep_alive; +mod s_pick_item; mod s_ping_request; mod s_player_abilities; mod s_player_action; @@ -37,6 +38,7 @@ pub use s_confirm_teleport::*; pub use s_cookie_response::*; pub use s_interact::*; pub use s_keep_alive::*; +pub use s_pick_item::*; pub use s_ping_request::*; pub use s_player_abilities::*; pub use s_player_action::*; diff --git a/pumpkin-protocol/src/server/play/s_pick_item.rs b/pumpkin-protocol/src/server/play/s_pick_item.rs new file mode 100644 index 000000000..8ff25b1d3 --- /dev/null +++ b/pumpkin-protocol/src/server/play/s_pick_item.rs @@ -0,0 +1,17 @@ +use pumpkin_core::math::position::WorldPosition; +use pumpkin_macros::server_packet; +use serde::Deserialize; + +#[derive(Deserialize)] +#[server_packet("play:pick_item_from_block")] +pub struct SPickItemFromBlock { + pub pos: WorldPosition, + pub include_data: bool, +} + +#[derive(Deserialize)] +#[server_packet("play:pick_item_from_entity")] +pub struct SPickItemFromEntity { + pub id: i32, + pub include_data: bool, +} diff --git a/pumpkin/src/entity/player.rs b/pumpkin/src/entity/player.rs index c197f58f9..5d58a7d71 100644 --- a/pumpkin/src/entity/player.rs +++ b/pumpkin/src/entity/player.rs @@ -37,9 +37,10 @@ use pumpkin_protocol::{ }, server::play::{ SChatCommand, SChatMessage, SClientCommand, SClientInformationPlay, SClientTickEnd, - SCommandSuggestion, SConfirmTeleport, SInteract, SPlayerAbilities, SPlayerAction, - SPlayerCommand, SPlayerInput, SPlayerPosition, SPlayerPositionRotation, SPlayerRotation, - SSetCreativeSlot, SSetHeldItem, SSetPlayerGround, SSwingArm, SUseItem, SUseItemOn, + SCommandSuggestion, SConfirmTeleport, SInteract, SPickItemFromBlock, SPlayerAbilities, + SPlayerAction, SPlayerCommand, SPlayerInput, SPlayerPosition, SPlayerPositionRotation, + SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSetPlayerGround, SSwingArm, SUseItem, + SUseItemOn, }, RawPacket, ServerPacket, SoundCategory, }; @@ -675,6 +676,7 @@ impl Player { } } + #[allow(clippy::too_many_lines)] pub async fn handle_play_packet( self: &Arc, server: &Arc, @@ -726,6 +728,10 @@ impl Player { SSetPlayerGround::PACKET_ID => { self.handle_player_ground(&SSetPlayerGround::read(bytebuf)?); } + SPickItemFromBlock::PACKET_ID => { + self.handle_pick_item_from_block(SPickItemFromBlock::read(bytebuf)?) + .await; + } SPlayerAbilities::PACKET_ID => { self.handle_player_abilities(SPlayerAbilities::read(bytebuf)?) .await; diff --git a/pumpkin/src/net/packet/play.rs b/pumpkin/src/net/packet/play.rs index d47a72355..e1be49685 100644 --- a/pumpkin/src/net/packet/play.rs +++ b/pumpkin/src/net/packet/play.rs @@ -18,7 +18,10 @@ use pumpkin_core::{ text::TextComponent, GameMode, }; +use pumpkin_inventory::player::PlayerInventory; use pumpkin_inventory::InventoryError; +use pumpkin_protocol::client::play::{CSetContainerSlot, CSetHeldItem}; +use pumpkin_protocol::codec::slot::Slot; use pumpkin_protocol::codec::var_int::VarInt; use pumpkin_protocol::server::play::SCookieResponse as SPCookieResponse; use pumpkin_protocol::{ @@ -32,13 +35,14 @@ use pumpkin_protocol::{ }, server::play::{ Action, ActionType, SChatCommand, SChatMessage, SClientCommand, SClientInformationPlay, - SConfirmTeleport, SInteract, SPlayPingRequest, SPlayerAbilities, SPlayerAction, - SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, SPlayerRotation, - SSetCreativeSlot, SSetHeldItem, SSwingArm, SUseItemOn, Status, + SConfirmTeleport, SInteract, SPickItemFromBlock, SPickItemFromEntity, SPlayPingRequest, + SPlayerAbilities, SPlayerAction, SPlayerCommand, SPlayerPosition, SPlayerPositionRotation, + SPlayerRotation, SSetCreativeSlot, SSetHeldItem, SSwingArm, SUseItemOn, Status, }, }; use pumpkin_world::block::{block_registry::get_block_by_item, BlockFace}; use pumpkin_world::item::item_registry::get_item_by_id; +use pumpkin_world::item::ItemStack; use thiserror::Error; fn modulus(a: f32, b: f32) -> f32 { @@ -310,6 +314,101 @@ impl Player { .store(ground.on_ground, std::sync::atomic::Ordering::Relaxed); } + async fn update_single_slot( + &self, + inventory: &mut tokio::sync::MutexGuard<'_, PlayerInventory>, + slot: usize, + slot_data: Slot, + ) { + inventory.state_id += 1; + let dest_packet = CSetContainerSlot::new(0, inventory.state_id as i32, slot, &slot_data); + self.client.send_packet(&dest_packet).await; + + if inventory + .set_slot(slot, slot_data.to_item(), false) + .is_err() + { + log::error!("Pick item set slot error!"); + } + } + + pub async fn handle_pick_item_from_block(&self, pick_item: SPickItemFromBlock) { + if !self.can_interact_with_block_at(&pick_item.pos, 1.0) { + return; + } + + let Ok(block) = self.world().get_block(pick_item.pos).await else { + return; + }; + + if block.item_id == 0 { + // Invalid block id (blocks such as tall seagrass) + return; + } + + let mut inventory = self.inventory().lock().await; + + let source_slot = inventory.get_slot_with_item(block.item_id); + let mut dest_slot = inventory.get_pick_item_hotbar_slot(); + + let dest_slot_data = match inventory.get_slot(dest_slot + 36) { + Ok(Some(stack)) => Slot::from(&*stack), + _ => Slot::from(None), + }; + + // Early return if no source slot and not in creative mode + if source_slot.is_none() && self.gamemode.load() != GameMode::Creative { + return; + } + + match source_slot { + Some(slot_index) if (36..=44).contains(&slot_index) => { + // Case where item is in hotbar + dest_slot = slot_index - 36; + } + Some(slot_index) => { + // Case where item is in inventory + + // Update destination slot + let source_slot_data = match inventory.get_slot(slot_index) { + Ok(Some(stack)) => Slot::from(&*stack), + _ => return, + }; + self.update_single_slot(&mut inventory, dest_slot + 36, source_slot_data) + .await; + + // Update source slot + self.update_single_slot(&mut inventory, slot_index, dest_slot_data) + .await; + } + None if self.gamemode.load() == GameMode::Creative => { + // Case where item is not present, if in creative mode create the item + let item_stack = ItemStack::new(1, block.item_id); + let slot_data = Slot::from(&item_stack); + self.update_single_slot(&mut inventory, dest_slot + 36, slot_data) + .await; + + // Check if there is any empty slot in the player inventory + if let Some(slot_index) = inventory.get_empty_slot() { + inventory.state_id += 1; + self.update_single_slot(&mut inventory, slot_index, dest_slot_data) + .await; + } + } + _ => return, + } + + // Update held item + inventory.set_selected(dest_slot); + self.client + .send_packet(&CSetHeldItem::new(dest_slot as i8)) + .await; + } + + pub fn handle_pick_item_from_entity(&self, _pick_item: SPickItemFromEntity) { + // TODO: Implement and merge any redundant code with pick_item_from_block + } + pub async fn handle_player_command(&self, command: SPlayerCommand) { if command.entity_id != self.entity_id().into() { return;