use bytestring::ByteString;
use crate::crafting::RecipeBook;
use crate::rules::{Version, VersionNotEnabled};
use crate::sim::{Layout, Loc, Model, OUTSIDE, Screen, Sim};
use crate::stack::Stack;
fn is_grid(lay: Layout, l: Loc) -> bool {
match (lay.screen, l) {
(Screen::Player, Loc::Craft(_)) => true,
(Screen::Container(WindowKind::Crafting), Loc::Container(k)) => (1..=9).contains(&k),
_ => false,
}
}
use crate::window::{SlotKind, WindowKind};
const V18: u8 = 0;
const V112: u8 = 1;
const V1165: u8 = 2;
const V261: u8 = 3;
const V262: u8 = 4;
const V263: u8 = 5;
trait Incoming {
fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool;
}
impl Incoming for Option<Stack> {
#[inline(always)]
fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
let s = normalize_as::<V>(self);
let s = if clamp { clamp_as::<V>(s) } else { s };
if same_slot(slot, &s) {
false
} else {
*slot = s;
true
}
}
}
#[cfg(any(feature = "v1_8", feature = "v1_12"))]
impl Incoming for &ghast_protocol::types::slot::legacy::Slot {
#[inline(always)]
fn settle<const V: u8>(self, slot: &mut Option<Stack>, clamp: bool) -> bool {
if legacy_same::<V>(slot, self, clamp) {
return false;
}
crate::stack::from_legacy_slot(self.clone()).settle::<V>(slot, clamp);
true
}
}
#[cfg(any(feature = "v1_8", feature = "v1_12"))]
#[inline(always)]
fn legacy_same<const V: u8>(
stored: &Option<Stack>,
w: &ghast_protocol::types::slot::legacy::Slot,
clamp: bool,
) -> bool {
let Some(ws) = &w.0 else {
return stored.is_none();
};
let id = i32::from(ws.id);
let mut count = i32::from(ws.count);
if V != V18 && (count <= 0 || id == 0) {
return stored.is_none();
}
if V == V261 || V == V262 || V == V263 || V == V1165 {
return false;
}
if clamp && count > 64 {
count = 64;
}
let Some(st) = stored else {
return false;
};
st.id == id
&& st.count == count
&& st.damage == ws.damage
&& match (&st.data, &ws.nbt) {
(crate::stack::ItemData::None, None) => true,
(crate::stack::ItemData::Nbt(a), Some(b)) => a == b,
_ => false,
}
}
#[inline(always)]
fn normalize_as<const V: u8>(s: Option<Stack>) -> Option<Stack> {
if V == V18 {
return s;
}
let mut s = s.filter(|s| s.count > 0 && s.id != 0);
if V != V112
&& let Some(st) = &mut s
{
st.damage = 0;
}
s
}
#[inline(always)]
fn clamp_as<const V: u8>(mut s: Option<Stack>) -> Option<Stack> {
if V == V261 {
crate::sim::clamp_v(Version::V26_1, &mut s);
} else if V == V262 {
crate::sim::clamp_v(Version::V26_2, &mut s);
} else if V == V263 {
crate::sim::clamp_v(Version::V26_3, &mut s);
} else {
crate::sim::clamp(&mut s);
}
s
}
#[inline(always)]
fn same_slot(a: &Option<Stack>, b: &Option<Stack>) -> bool {
match (a, b) {
(None, None) => true,
(Some(a), Some(b)) => {
a.id == b.id && a.count == b.count && a.damage == b.damage && a.data == b.data
}
_ => false,
}
}
#[cfg(modern)]
const MOUNT_MENU: i32 = 1000;
pub const DEFAULT_CLICK_SETTLE_TICKS: u32 = 4;
pub const DEFAULT_CLICK_TIMEOUT_TICKS: u32 = 40;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Click {
Pickup {
slot: i16,
right: bool,
},
QuickMove {
slot: i16,
right: bool,
},
Swap {
slot: i16,
hotbar: u8,
},
Drop {
slot: i16,
all: bool,
},
PickupAll {
slot: i16,
},
Clone {
slot: i16,
},
QuickCraft {
slot: i16,
stage: DragStage,
kind: DragKind,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragStage {
Start,
Slot,
End,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DragKind {
Split,
One,
Clone,
}
impl Click {
#[must_use]
pub fn wire(self) -> (i16, u8, u8) {
match self {
Click::Pickup { slot, right } => (slot, u8::from(right), 0),
Click::QuickMove { slot, right } => (slot, u8::from(right), 1),
Click::Swap { slot, hotbar } => (slot, hotbar, 2),
Click::Drop { slot, all } => (slot, u8::from(all), 4),
Click::PickupAll { slot } => (slot, 0, 6),
Click::Clone { slot } => (slot, 2, 3),
Click::QuickCraft { slot, stage, kind } => {
let header = match stage {
DragStage::Start => 0,
DragStage::Slot => 1,
DragStage::End => 2,
};
let ty = match kind {
DragKind::Split => 0,
DragKind::One => 1,
DragKind::Clone => 2,
};
(slot, header | ty << 2, 5)
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickError {
Pending,
Resyncing,
NoScreen,
WindowOpen,
SameTick,
InvalidSlot,
InvalidButton,
Unpredictable,
}
impl std::fmt::Display for ClickError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
ClickError::Pending => "a click is waiting for its confirm",
ClickError::Resyncing => "waiting for the window resync after a rejected click",
ClickError::NoScreen => "no inventory screen is open",
ClickError::WindowOpen => "a container window is open",
ClickError::SameTick => "not allowed in the same tick",
ClickError::InvalidSlot => "invalid slot",
ClickError::InvalidButton => "invalid button",
ClickError::Unpredictable => "click outcome cannot be predicted",
})
}
}
impl std::error::Error for ClickError {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ClickPacket {
pub window_id: u8,
pub slot: i16,
pub button: u8,
pub mode: u8,
pub action: i16,
pub item: Option<Stack>,
pub swings: u8,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Outgoing {
Click(ClickPacket),
Confirm {
window_id: i8,
action: i16,
},
CloseWindow(u8),
OpenInventory,
ContainerClick(ContainerClick),
Creative(Vec<CreativePacket>),
RenameItem(String),
ButtonClick {
window_id: i32,
button: i32,
},
SelectTrade(i32),
Swing,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CreativePacket {
Swing,
SetSlot {
slot: i16,
item: Option<Stack>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ContainerClick {
pub window_id: i32,
pub state_id: i32,
pub slot: i16,
pub button: u8,
pub mode: u8,
pub changed: Vec<(i16, Option<Stack>)>,
pub carried: Option<Stack>,
pub predicted: bool,
pub action: i16,
pub swings: u8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ClickOutcome {
Accepted,
Rejected,
TimedOut,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct ClickResult {
pub window_id: i32,
pub action: i16,
pub outcome: ClickOutcome,
}
impl ClickResult {
#[must_use]
pub fn new(window_id: i32, action: i16, outcome: ClickOutcome) -> ClickResult {
ClickResult {
window_id,
action,
outcome,
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Events {
pub player_changed: bool,
pub window_changed: bool,
pub cursor_changed: bool,
pub opened: Option<i32>,
pub closed: bool,
pub clicks: Vec<ClickResult>,
pub player_synced: bool,
pub window_synced: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Window {
id: i32,
kind: WindowKind,
title: ByteString,
action: i16,
properties: Vec<(i16, i16)>,
menu: i32,
}
impl Window {
#[must_use]
pub fn id(&self) -> i32 {
self.id
}
#[must_use]
pub fn kind(&self) -> WindowKind {
self.kind
}
#[must_use]
pub fn title(&self) -> &ByteString {
&self.title
}
#[must_use]
pub fn property(&self, id: i16) -> Option<i16> {
self.properties.iter().find(|p| p.0 == id).map(|p| p.1)
}
#[must_use]
pub fn menu_modern(&self) -> Option<i32> {
(self.menu >= 0).then_some(self.menu)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum ScreenState {
None,
Inventory,
Window(Window),
}
#[derive(Debug, Clone, Copy)]
struct PendingClick {
window_id: i32,
action: i16,
age: u32,
}
#[derive(Debug, Clone, Copy, Default)]
struct TickFlags {
clicked: bool,
opened: bool,
closed: bool,
}
#[derive(Debug, Clone)]
pub struct Inventory {
version: Version,
m: Model,
screen: ScreenState,
player_action: i16,
pending: Option<PendingClick>,
resync: Option<(i32, u32)>,
flags: TickFlags,
timeout: u32,
settle: u32,
events: Events,
hotbar_writes: [u16; 10],
book: RecipeBook,
tags16: Option<std::sync::Arc<crate::tags16::ItemTags16>>,
state_player: i32,
state_window: i32,
#[cfg(modern)]
reg26: crate::item26::HashRegistries,
#[cfg(modern)]
w26: crate::sim26::World26,
#[cfg(modern)]
s26: [crate::sim26::Screen26; 2],
#[cfg(modern)]
creative_last: Vec<Option<Stack>>,
#[cfg(modern)]
creative_screen: bool,
#[cfg(modern)]
creative_echo: Vec<CreativePacket>,
#[cfg(modern)]
drop_throttle: i32,
#[cfg(modern)]
recipes_raw: Option<bytes::Bytes>,
#[cfg(modern)]
d26: crate::data26::Data26,
creative16: Option<Box<creative_legacy::CreativeLegacy>>,
}
mod aliases;
mod click;
mod creative_legacy;
mod hands;
mod inbound;
#[cfg(modern)]
mod modern;
mod read;
mod screens;
pub use creative_legacy::CreativeTab;
#[inline]
fn hand_writes_index(l: Loc) -> Option<usize> {
match l {
Loc::Player(k @ 0..9) => Some(k),
Loc::Player(40) => Some(9),
_ => None,
}
}
impl Inventory {
pub fn new(version: Version) -> Result<Inventory, VersionNotEnabled> {
if version.is_enabled() {
Ok(Inventory::empty(version))
} else {
Err(VersionNotEnabled(version))
}
}
fn empty(version: Version) -> Inventory {
Inventory {
version,
m: Model::default(),
screen: ScreenState::None,
player_action: 0,
pending: None,
resync: None,
flags: TickFlags::default(),
timeout: DEFAULT_CLICK_TIMEOUT_TICKS,
settle: DEFAULT_CLICK_SETTLE_TICKS,
events: Events::default(),
hotbar_writes: [0; 10],
book: RecipeBook::default(),
tags16: None,
state_player: 0,
state_window: 0,
#[cfg(modern)]
reg26: crate::item26::HashRegistries::default(),
#[cfg(modern)]
w26: crate::sim26::World26::default(),
#[cfg(modern)]
s26: Default::default(),
#[cfg(modern)]
creative_last: Vec::new(),
#[cfg(modern)]
creative_screen: false,
#[cfg(modern)]
creative_echo: Vec::new(),
#[cfg(modern)]
drop_throttle: 0,
#[cfg(modern)]
recipes_raw: None,
#[cfg(modern)]
d26: Default::default(),
creative16: None,
}
}
pub fn set_click_timeout(&mut self, ticks: u32) {
self.timeout = ticks.max(1);
}
pub fn set_click_settle_ticks(&mut self, ticks: u32) {
self.settle = ticks.max(1);
}
#[must_use]
pub fn version(&self) -> Version {
self.version
}
#[must_use]
pub fn enchantment_level(&self, stack: &crate::Stack, name: &str) -> i32 {
let want = name.strip_prefix("minecraft:").unwrap_or(name);
#[cfg(modern)]
let registry: &[String] = self.reg26.enchantments();
#[cfg(not(modern))]
let registry: &[String] = &[];
stack
.enchantments(self.version)
.iter()
.find(|e| e.id.plain_name(registry) == Some(want))
.map_or(0, |e| e.level)
}
#[cfg(modern)]
#[inline]
pub(crate) fn mv(&self) -> crate::tables::Mv {
crate::tables::Mv::of(self.version).unwrap_or(crate::tables::Mv::ANY)
}
pub fn reset(&mut self) {
#[cfg(modern)]
let reg26 = std::mem::take(&mut self.reg26);
#[cfg(modern)]
let w26 = std::mem::take(&mut self.w26);
#[cfg(modern)]
let recipes_raw = self.recipes_raw.take();
#[cfg(modern)]
let d26 = std::mem::take(&mut self.d26);
*self = Inventory {
timeout: self.timeout,
settle: self.settle,
book: std::mem::take(&mut self.book),
hotbar_writes: self.hotbar_writes,
tags16: self.tags16.take(),
#[cfg(modern)]
reg26,
#[cfg(modern)]
w26,
#[cfg(modern)]
recipes_raw,
#[cfg(modern)]
d26,
creative16: self
.creative16
.take()
.map(creative_legacy::CreativeLegacy::respawned),
..Inventory::empty(self.version)
};
self.events.player_changed = true;
}
pub fn tick(&mut self) {
self.flags = TickFlags::default();
#[cfg(modern)]
if self.drop_throttle > 0 {
self.drop_throttle -= 1;
}
if let Some(p) = &mut self.pending {
p.age += 1;
if self.version.is_modern() && p.age >= self.settle {
self.events.clicks.push(ClickResult {
window_id: p.window_id,
action: p.action,
outcome: ClickOutcome::Accepted,
});
self.pending = None;
} else if p.age >= self.timeout {
self.events.clicks.push(ClickResult {
window_id: p.window_id,
action: p.action,
outcome: ClickOutcome::TimedOut,
});
self.pending = None;
}
}
if let Some((_, age)) = &mut self.resync {
*age += 1;
if *age >= self.timeout {
self.resync = None;
}
}
}
pub fn drain_events(&mut self) -> Events {
std::mem::take(&mut self.events)
}
}