From b41e0facfe0e2cc644f208ca723218c4ac791011 Mon Sep 17 00:00:00 2001 From: shtefan4079 <78881564+shtefan4079@users.noreply.github.com> Date: Thu, 26 Nov 2026 22:05:35 +0100 Subject: [PATCH] feat(item-use): add mcrs_minecraft_vanilla_item_use plugin (Refs #117) --- Cargo.lock | 23 ++ Cargo.toml | 1 + .../Cargo.toml | 31 ++ .../src/ingest.rs | 93 +++++ .../src/lib.rs | 9 + .../src/plugin.rs | 70 ++++ .../src/systems.rs | 380 ++++++++++++++++++ docs/crates.md | 1 + 8 files changed, 608 insertions(+) create mode 100644 crates/mcrs_minecraft_vanilla_item_use/Cargo.toml create mode 100644 crates/mcrs_minecraft_vanilla_item_use/src/ingest.rs create mode 100644 crates/mcrs_minecraft_vanilla_item_use/src/lib.rs create mode 100644 crates/mcrs_minecraft_vanilla_item_use/src/plugin.rs create mode 100644 crates/mcrs_minecraft_vanilla_item_use/src/systems.rs diff --git a/Cargo.lock b/Cargo.lock index a09179888..7b9cbd91a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7653,6 +7653,29 @@ dependencies = [ "tracing", ] +[[package]] +name = "mcrs_minecraft_vanilla_item_use" +version = "0.5.8" +dependencies = [ + "bevy_app", + "bevy_ecs", + "mcrs_minecraft_damage", + "mcrs_minecraft_engine", + "mcrs_minecraft_engine_damage", + "mcrs_minecraft_engine_item", + "mcrs_minecraft_engine_world", + "mcrs_minecraft_game_mode", + "mcrs_minecraft_inventory_player", + "mcrs_minecraft_item_stack", + "mcrs_minecraft_item_use", + "mcrs_minecraft_network", + "mcrs_minecraft_player_holders", + "mcrs_minecraft_protocol", + "mcrs_minecraft_protocol_game", + "mcrs_minecraft_vanilla_inventory", + "smallvec", +] + [[package]] name = "mcrs_minecraft_vanilla_light" version = "0.5.8" diff --git a/Cargo.toml b/Cargo.toml index 22cd93c9b..88b21852d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -229,6 +229,7 @@ mcrs_minecraft_vanilla_player_attack = { path = "crates/mcrs_minecraft_vanilla_p mcrs_minecraft_vanilla_respawn = { path = "crates/mcrs_minecraft_vanilla_respawn" } mcrs_minecraft_vanilla_death = { path = "crates/mcrs_minecraft_vanilla_death" } mcrs_minecraft_vanilla_hunger = { path = "crates/mcrs_minecraft_vanilla_hunger" } +mcrs_minecraft_vanilla_item_use = { path = "crates/mcrs_minecraft_vanilla_item_use" } mcrs_minecraft_vanilla_weather = { path = "crates/mcrs_minecraft_vanilla_weather" } mcrs_minecraft_player_holders = { path = "crates/mcrs_minecraft_player_holders" } mcrs_minecraft_inventory_server = { path = "crates/mcrs_minecraft_inventory_server" } diff --git a/crates/mcrs_minecraft_vanilla_item_use/Cargo.toml b/crates/mcrs_minecraft_vanilla_item_use/Cargo.toml new file mode 100644 index 000000000..46459832c --- /dev/null +++ b/crates/mcrs_minecraft_vanilla_item_use/Cargo.toml @@ -0,0 +1,31 @@ +[package] +name = "mcrs_minecraft_vanilla_item_use" +description = "Vanilla continuous item use, consumable completion, release, and slot-change cancellation in dimension worlds" +version.workspace = true +edition.workspace = true +license.workspace = true + +[lib] +doctest = false + +[lints] +workspace = true + +[dependencies] +bevy_app.workspace = true +bevy_ecs.workspace = true +mcrs_minecraft_damage = { workspace = true, features = ["bevy"] } +mcrs_minecraft_engine.workspace = true +mcrs_minecraft_engine_damage.workspace = true +mcrs_minecraft_engine_item.workspace = true +mcrs_minecraft_engine_world.workspace = true +mcrs_minecraft_game_mode = { workspace = true, features = ["bevy"] } +mcrs_minecraft_inventory_player.workspace = true +mcrs_minecraft_item_stack = { workspace = true, features = ["bevy"] } +mcrs_minecraft_item_use = { workspace = true, features = ["bevy"] } +mcrs_minecraft_network.workspace = true +mcrs_minecraft_player_holders.workspace = true +mcrs_minecraft_protocol.workspace = true +mcrs_minecraft_protocol_game.workspace = true +mcrs_minecraft_vanilla_inventory.workspace = true +smallvec.workspace = true diff --git a/crates/mcrs_minecraft_vanilla_item_use/src/ingest.rs b/crates/mcrs_minecraft_vanilla_item_use/src/ingest.rs new file mode 100644 index 000000000..c96781a31 --- /dev/null +++ b/crates/mcrs_minecraft_vanilla_item_use/src/ingest.rs @@ -0,0 +1,93 @@ +use std::mem::{align_of, size_of}; + +use bevy_ecs::entity::Entity; +use bevy_ecs::message::{Message, MessageWriter}; +use bevy_ecs::observer::On; +use mcrs_minecraft_inventory_player::HOTBAR; +use mcrs_minecraft_network::event::Received; +use mcrs_minecraft_protocol::VarInt; +use mcrs_minecraft_protocol_game::Hand; +use mcrs_minecraft_protocol_game::player::PlayerAction; +use mcrs_minecraft_protocol_game::serverbound::{ + ServerboundPlayerAction, ServerboundSetCarriedItem, ServerboundUseItem, +}; + +#[derive(Message, Clone, Copy, Debug, PartialEq, Eq)] +pub struct StartUseItem { + pub player: Entity, + pub hand: Hand, + pub sequence: VarInt, +} + +#[derive(Message, Clone, Copy, Debug, PartialEq, Eq)] +pub struct ReleaseUseItem { + pub player: Entity, +} + +#[derive(Message, Clone, Copy, Debug, PartialEq, Eq)] +pub struct CarriedSlotChanged { + pub player: Entity, + pub slot: u8, +} + +const _: () = { + assert!(size_of::() == 16, "StartUseItem is 16 bytes"); + assert!(align_of::() == 8, "StartUseItem aligns to 8"); + assert!( + size_of::() == size_of::(), + "ReleaseUseItem matches Entity size" + ); + assert!( + align_of::() == align_of::(), + "ReleaseUseItem matches Entity align" + ); + assert!( + size_of::() == 16, + "CarriedSlotChanged is 16 bytes" + ); + assert!( + align_of::() == 8, + "CarriedSlotChanged aligns to 8" + ); +}; + +pub(crate) fn on_use_item( + received: On>, + mut writer: MessageWriter, +) { + if let Some(packet) = received.packet() { + writer.write(StartUseItem { + player: received.entity, + hand: packet.hand, + sequence: packet.sequence, + }); + } +} + +pub(crate) fn on_player_action( + received: On>, + mut writer: MessageWriter, +) { + if let Some(packet) = received.packet() + && packet.action == PlayerAction::ReleaseUseItem + { + writer.write(ReleaseUseItem { + player: received.entity, + }); + } +} + +pub(crate) fn on_set_carried_item( + received: On>, + mut writer: MessageWriter, +) { + if let Some(packet) = received.packet() + && HOTBAR.contains(&packet.slot) + && let Ok(slot) = u8::try_from(packet.slot) + { + writer.write(CarriedSlotChanged { + player: received.entity, + slot, + }); + } +} diff --git a/crates/mcrs_minecraft_vanilla_item_use/src/lib.rs b/crates/mcrs_minecraft_vanilla_item_use/src/lib.rs new file mode 100644 index 000000000..1a3bf6f9b --- /dev/null +++ b/crates/mcrs_minecraft_vanilla_item_use/src/lib.rs @@ -0,0 +1,9 @@ +mod ingest; +mod plugin; +mod systems; + +pub use ingest::CarriedSlotChanged; +pub use ingest::ReleaseUseItem; +pub use ingest::StartUseItem; +pub use plugin::ItemUseSet; +pub use plugin::VanillaItemUsePlugin; diff --git a/crates/mcrs_minecraft_vanilla_item_use/src/plugin.rs b/crates/mcrs_minecraft_vanilla_item_use/src/plugin.rs new file mode 100644 index 000000000..05a5b9298 --- /dev/null +++ b/crates/mcrs_minecraft_vanilla_item_use/src/plugin.rs @@ -0,0 +1,70 @@ +use bevy_app::{App, FixedUpdate, Plugin}; +use bevy_ecs::schedule::common_conditions::{any_with_component, on_message}; +use bevy_ecs::schedule::{IntoScheduleConfigs, SystemCondition, SystemSet}; +use mcrs_minecraft_engine::block_simulation::BlockSimulationSet; +use mcrs_minecraft_engine::bus::OutboundPlayerPacket; +use mcrs_minecraft_engine::{BlockBreakSet, ItemUsePredictionSet, UsingItem}; +use mcrs_minecraft_engine_damage::DamageSet; +use mcrs_minecraft_engine_world::tick::TickSet; +use mcrs_minecraft_vanilla_inventory::InventorySet; + +use crate::ingest::{on_player_action, on_set_carried_item, on_use_item}; +use crate::systems::{FinishUseItem, finish_use_items, handle_use_item_inputs, tick_using_items}; +use crate::{CarriedSlotChanged, ReleaseUseItem, StartUseItem}; + +#[derive(SystemSet, Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum ItemUseSet { + Input, + Simulate, + Finish, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct VanillaItemUsePlugin; + +impl Plugin for VanillaItemUsePlugin { + fn build(&self, app: &mut App) { + app.add_message::() + .add_message::() + .add_message::() + .add_message::() + .add_message::() + .add_observer(on_use_item) + .add_observer(on_player_action) + .add_observer(on_set_carried_item) + .configure_sets( + FixedUpdate, + ( + ItemUseSet::Input + .in_set(TickSet::ClientInput) + .after(InventorySet::Input) + .after(BlockBreakSet), + ItemUseSet::Simulate + .in_set(TickSet::Simulate) + .before(ItemUsePredictionSet), + ItemUseSet::Finish + .in_set(TickSet::WorldWrite) + .after(BlockSimulationSet) + .before(DamageSet::Collect), + ), + ) + .add_systems( + FixedUpdate, + ( + handle_use_item_inputs + .run_if( + on_message:: + .or_else(on_message::) + .or_else(on_message::), + ) + .in_set(ItemUseSet::Input), + tick_using_items + .run_if(any_with_component::) + .in_set(ItemUseSet::Simulate), + finish_use_items + .run_if(on_message::) + .in_set(ItemUseSet::Finish), + ), + ); + } +} diff --git a/crates/mcrs_minecraft_vanilla_item_use/src/systems.rs b/crates/mcrs_minecraft_vanilla_item_use/src/systems.rs new file mode 100644 index 000000000..36b2150fb --- /dev/null +++ b/crates/mcrs_minecraft_vanilla_item_use/src/systems.rs @@ -0,0 +1,380 @@ +use std::mem::{align_of, size_of}; + +use bevy_ecs::change_detection::{DetectChangesMut, Mut}; +use bevy_ecs::component::Component; +use bevy_ecs::entity::Entity; +use bevy_ecs::message::{Message, MessageReader, MessageWriter}; +use bevy_ecs::query::{Has, With}; +use bevy_ecs::system::{Commands, Populated, Query, SystemParam}; +use mcrs_minecraft_damage::Vitals; +use mcrs_minecraft_engine::bus::{OutboundPlayerPacket, PacketPayload, to}; +use mcrs_minecraft_engine::loaded_client::UnloadedClient; +use mcrs_minecraft_engine::network_id::player_network_id; +use mcrs_minecraft_engine::player_sprinting::PlayerSprinting; +use mcrs_minecraft_engine::player_state::PlayerFileState; +use mcrs_minecraft_engine::{LivingFlags, UsingItem}; +use mcrs_minecraft_engine_item::{Selected, Slots, StackCommandsExt, Stacks}; +use mcrs_minecraft_engine_world::session::Owner; +use mcrs_minecraft_game_mode::{GameMode, PlayerGameMode}; +use mcrs_minecraft_inventory_player::{HOTBAR, OFF_HAND}; +use mcrs_minecraft_item_stack::{BlocksAttacks, Consumable, Food, Kind, UseEffects}; +use mcrs_minecraft_item_use::{ + SprintPolicy, UseHand, UseKind, UseOutcome, UseSpec, cancel_on_slot_change, release_use, + start_use, tick_use, +}; +use mcrs_minecraft_player_holders::PlayerHolders; +use mcrs_minecraft_protocol_game::Hand; +use mcrs_minecraft_protocol_game::clientbound::ClientboundEntityEvent; +use smallvec::SmallVec; + +use crate::{CarriedSlotChanged, ReleaseUseItem, StartUseItem}; + +const MAX_FOOD_LEVEL: i32 = 20; + +#[derive(Component, Clone, Copy, Debug, PartialEq, Eq)] +#[component(storage = "SparseSet")] +pub(crate) struct UsingTarget { + stack: Entity, + kind: Kind, +} + +#[derive(Message, Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct FinishUseItem { + player: Entity, + stack: Entity, + hand: UseHand, + hotbar_slot: u8, + kind: Kind, +} + +const _: () = { + assert!( + size_of::() == 16 && align_of::() == 8, + "UsingTarget stores Entity and Kind within 16 bytes" + ); + assert!( + size_of::() == 24 && align_of::() == 8, + "FinishUseItem stores player, stack, hand, slot, and kind within 24 bytes" + ); +}; + +type InputPlayerRow<'a> = ( + Option<&'a UsingItem>, + &'a mut LivingFlags, + Option<&'a mut PlayerSprinting>, + &'a Slots, + &'a Selected, + Option<&'a PlayerGameMode>, + Option<&'a Vitals>, + Has, + &'a PlayerFileState, +); + +type TickPlayerRow<'a> = ( + Entity, + &'a mut UsingItem, + &'a UsingTarget, + &'a mut LivingFlags, + Option<&'a mut PlayerSprinting>, + &'a Slots, + &'a Selected, + Option<&'a PlayerGameMode>, + Option<&'a Vitals>, + Has, +); + +type FinishPlayerRow<'a> = ( + &'a Owner, + &'a Slots, + &'a Selected, + Option<&'a Vitals>, + Option<&'a PlayerGameMode>, + Has, +); + +#[derive(SystemParam)] +pub(crate) struct UseInputMessages<'w, 's> { + starts: MessageReader<'w, 's, StartUseItem>, + releases: MessageReader<'w, 's, ReleaseUseItem>, + slot_changes: MessageReader<'w, 's, CarriedSlotChanged>, +} + +#[derive(SystemParam)] +pub(crate) struct FinishContext<'w, 's> { + players: Query<'w, 's, FinishPlayerRow<'static>, With>, + stacks: Stacks<'w, 's>, + packets: MessageWriter<'w, OutboundPlayerPacket>, + commands: Commands<'w, 's>, +} + +pub(crate) fn handle_use_item_inputs( + mut inputs: UseInputMessages<'_, '_>, + mut players: Query, With>, + mut stacks: Stacks<'_, '_>, + mut finishes: MessageWriter, + mut commands: Commands, +) { + let released: SmallVec<[Entity; 4]> = inputs + .releases + .read() + .map(|message| message.player) + .collect(); + let changed_slots: SmallVec<[(Entity, u8); 4]> = inputs + .slot_changes + .read() + .map(|message| (message.player, message.slot)) + .collect(); + + let mut stopped: SmallVec<[Entity; 4]> = SmallVec::new(); + for &player in &released { + if !stopped.contains(&player) + && let Ok((Some(active), flags, ..)) = players.get_mut(player) + && release_use(Some(active.0)).is_some() + { + stopped.push(player); + clear_active_use(player, flags, commands.reborrow()); + } + } + for &(player, slot) in &changed_slots { + if !stopped.contains(&player) + && let Ok((Some(active), flags, ..)) = players.get_mut(player) + && cancel_on_slot_change(active.0, slot).is_none() + { + stopped.push(player); + clear_active_use(player, flags, commands.reborrow()); + } + } + + let mut started: SmallVec<[Entity; 4]> = SmallVec::new(); + for &start in inputs.starts.read() { + if started.contains(&start.player) { + continue; + } + let Ok(( + active, + mut flags, + sprinting, + slots, + selected, + game_mode, + vitals, + unloaded, + file_state, + )) = players.get_mut(start.player) + else { + continue; + }; + let active_state = if stopped.contains(&start.player) { + None + } else { + active.map(|component| component.0) + }; + if active_state.is_some() || !can_act(unloaded, vitals, game_mode) { + continue; + } + let Some((use_hand, hotbar_slot, slot_index)) = hand_slot(start.hand, selected.0) else { + continue; + }; + let Some(stack) = slots.get(usize::from(slot_index)) else { + continue; + }; + let Some(kind) = stacks.kind(stack) else { + continue; + }; + let Some(spec) = classify_use_spec(&mut stacks, stack, is_creative(game_mode), file_state) + else { + continue; + }; + started.push(start.player); + let Some(state) = start_use(None, use_hand, hotbar_slot, spec) else { + continue; + }; + let cancelled_same_tick = released.contains(&start.player) + || changed_slots.iter().any(|&(player, slot)| { + player == start.player && cancel_on_slot_change(state, slot).is_none() + }); + if cancelled_same_tick { + continue; + } + if spec.kind == UseKind::Consumable && spec.use_duration_ticks == 0 { + finishes.write(FinishUseItem { + player: start.player, + stack, + hand: use_hand, + hotbar_slot, + kind, + }); + continue; + } + clear_sprint_if_disallowed(spec.sprint_policy, sprinting); + flags.set_if_neq(flags.with_active_hand(Some(use_hand))); + commands + .entity(start.player) + .insert((UsingItem(state), UsingTarget { stack, kind })); + } +} + +pub(crate) fn tick_using_items( + mut players: Populated, With>, + stacks: Stacks<'_, '_>, + mut finishes: MessageWriter, + mut commands: Commands, +) { + for ( + player, + mut using, + target, + flags, + sprinting, + slots, + selected, + game_mode, + vitals, + unloaded, + ) in &mut players + { + let slot_index = active_slot_index(using.0.hand, using.0.slot); + let valid = can_act(unloaded, vitals, game_mode) + && cancel_on_slot_change(using.0, selected.0).is_some() + && slots.get(usize::from(slot_index)) == Some(target.stack) + && stacks.kind(target.stack) == Some(target.kind); + if !valid { + clear_active_use(player, flags, commands.reborrow()); + continue; + } + let next_state = match tick_use(using.0) { + UseOutcome::Continuing { state, .. } => Some(state), + UseOutcome::Completed { .. } => None, + }; + if let Some(state) = next_state { + clear_sprint_if_disallowed(state.sprint_policy, sprinting); + using.set_if_neq(UsingItem(state)); + } else { + clear_active_use(player, flags, commands.reborrow()); + finishes.write(FinishUseItem { + player, + stack: target.stack, + hand: using.0.hand, + hotbar_slot: using.0.slot, + kind: target.kind, + }); + } + } +} + +pub(crate) fn finish_use_items( + mut finishes: MessageReader, + mut context: FinishContext<'_, '_>, +) { + for &finish in finishes.read() { + complete_use(finish, &mut context); + } +} + +fn complete_use(finish: FinishUseItem, context: &mut FinishContext<'_, '_>) { + if context.stacks.kind(finish.stack) != Some(finish.kind) { + return; + } + let Ok((owner, slots, selected, vitals, game_mode, unloaded)) = + context.players.get_mut(finish.player) + else { + return; + }; + let slot_index = active_slot_index(finish.hand, finish.hotbar_slot); + let still_held = can_act(unloaded, vitals, game_mode) + && match finish.hand { + UseHand::Main => selected.0 == finish.hotbar_slot, + UseHand::Off => true, + } + && slots.get(usize::from(slot_index)) == Some(finish.stack); + if !still_held { + return; + } + + context.packets.write(to( + owner.0, + PacketPayload::EntityEvent(ClientboundEntityEvent { + entity_id: player_network_id(owner.0), + entity_status: ClientboundEntityEvent::USE_ITEM_FINISH, + }), + )); + if !is_creative(game_mode) { + context.commands.entity(finish.stack).consume(1); + } +} + +fn classify_use_spec( + stacks: &mut Stacks<'_, '_>, + stack: Entity, + creative: bool, + file_state: &PlayerFileState, +) -> Option { + let use_effects = stacks.get::(stack).copied().unwrap_or_default(); + let sprint_policy = if use_effects.can_sprint { + SprintPolicy::Allow + } else { + SprintPolicy::Forbid + }; + if let Some(consumable) = stacks.get::(stack) { + let consume_seconds = consumable.consume_seconds; + let food = stacks.get::(stack); + if !creative + && food.is_some_and(|food| !food.can_always_eat) + && file_state.food_level >= MAX_FOOD_LEVEL + { + return None; + } + return Some(UseSpec::consumable( + consume_seconds, + use_effects.speed_multiplier, + sprint_policy, + )); + } + stacks + .get::(stack) + .is_some() + .then(|| UseSpec::continuous(use_effects.speed_multiplier, sprint_policy)) +} + +fn can_act(unloaded: bool, vitals: Option<&Vitals>, game_mode: Option<&PlayerGameMode>) -> bool { + !unloaded + && vitals.is_none_or(|health| health.is_alive() && health.health > 0.0) + && game_mode.is_none_or(|mode| mode.0 != GameMode::Spectator) +} + +fn is_creative(game_mode: Option<&PlayerGameMode>) -> bool { + game_mode.is_some_and(|mode| mode.0 == GameMode::Creative) +} + +fn clear_sprint_if_disallowed( + sprint_policy: SprintPolicy, + sprinting: Option>, +) { + if sprint_policy == SprintPolicy::Forbid + && let Some(mut sprint) = sprinting + { + sprint.set_if_neq(PlayerSprinting(false)); + } +} + +fn hand_slot(hand: Hand, selected: u8) -> Option<(UseHand, u8, u16)> { + match hand { + Hand::Main if HOTBAR.contains(&u16::from(selected)) => { + Some((UseHand::Main, selected, u16::from(selected))) + } + Hand::Main => None, + Hand::Off => Some((UseHand::Off, 0, OFF_HAND)), + } +} + +fn active_slot_index(hand: UseHand, hotbar_slot: u8) -> u16 { + match hand { + UseHand::Main => u16::from(hotbar_slot), + UseHand::Off => OFF_HAND, + } +} + +fn clear_active_use(player: Entity, mut flags: Mut, mut commands: Commands) { + flags.set_if_neq(flags.with_active_hand(None)); + commands.entity(player).remove::<(UsingItem, UsingTarget)>(); +} diff --git a/docs/crates.md b/docs/crates.md index cff33eff5..be9457bc6 100644 --- a/docs/crates.md +++ b/docs/crates.md @@ -204,6 +204,7 @@ Use the crate that owns the item. Do not write a second copy. - `mcrs_minecraft_vanilla_hunger`: Server hunger plugin wiring exhaustion sources, natural and peaceful regeneration, starvation damage requests, and spectator chunk gating - `mcrs_minecraft_vanilla_inventory`: The gameplay of the player inventory: the hand actions, the close, the drops and the player file - `mcrs_minecraft_vanilla_item_entity`: The vanilla item entity: a dropped stack that moves with the motion pass, ages, merges and is picked up +- `mcrs_minecraft_vanilla_item_use`: Vanilla continuous item use, consumable completion, release, and slot-change cancellation in dimension worlds - `mcrs_minecraft_vanilla_light`: Vanilla light wired into the dimension worlds: the block light table, the light engine driver of each dimension and the light updates sent to the players - `mcrs_minecraft_vanilla_player_attack`: The melee attack of a player on an entity: the attack strength, the damage amount, the hit request from the attack packet and the knockback of the hit - `mcrs_minecraft_vanilla_respawn`: Vanilla respawn of a dead player on its request, at the respawn position of the vanilla rules