use std::collections::HashMap;
use super::proto::{configuration, handshaking, login, play};
use bytes::{Bytes, BytesMut};
use ghast_protocol::chat::nbt_to_plain_text;
use ghast_protocol::nbt::AnonNbt;
use ghast_protocol::types::{ByteString, LpVec3};
use ghast_protocol::{DecodeError, EncodeError, FrameEncoder, McWrite, PacketFilter, RawPacket};
use super::{Marker, inv};
use crate::common::{
Abilities, AttributeUpdate, ChatMessage, ChatPosition, ConfigInbound, ConfigOutbound,
EntityAction, GameMode, Health, Inbound, JoinGame, KnownPack, LoginInbound, MovePacket,
Outbound, Pose, Teleport, Vec3,
};
use crate::interest::Interests;
use crate::version::{ClientVersion, GameVersion, teleport_target, truncate_utf16};
use play::clientbound as cb;
use play::serverbound as sb;
const LAST_SEEN: usize = 20;
const ACK_AFTER: i32 = 64;
#[derive(Debug, Default)]
pub struct Wire {
sequence: i32,
last_look: (f32, f32),
tick_look: Option<(f32, f32)>,
dimension: String,
seen: LastSeen,
next_chat_index: i32,
chat_types: Vec<String>,
cookies: HashMap<ByteString, Bytes>,
salt: u64,
hash_registries: inv::HashRegistries,
inv_config: Vec<(bool, Bytes)>,
commands_raw: Option<Bytes>,
commands: Option<crate::version::commands::CommandTree>,
chat: Option<ChatSession>,
entity_id: i32,
op_level: u8,
online_mode: Option<bool>,
dialogs: Option<std::sync::Arc<crate::dialog::DialogRegistry>>,
}
struct ChatSession {
keys: std::sync::Arc<ghast_auth::chat::ProfileKeys>,
chain: ghast_auth::chat::SignedMessageChain,
}
impl std::fmt::Debug for ChatSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChatSession")
.field("session", &self.chain.session_id())
.finish_non_exhaustive()
}
}
fn random_uuid() -> uuid::Uuid {
let mut b = [0u8; 16];
ghast_auth::crypto::random_bytes(&mut b);
b[6] = (b[6] & 0x0f) | 0x40;
b[8] = (b[8] & 0x3f) | 0x80;
uuid::Uuid::from_bytes(b)
}
#[derive(Debug, Default)]
struct LastSeen {
entries: [Option<Bytes>; LAST_SEEN],
tail: usize,
offset: i32,
last: Option<Bytes>,
ack_due: bool,
}
impl LastSeen {
fn add(&mut self, sig: Bytes, shown: bool) {
if self.last.as_ref() == Some(&sig) {
return;
}
let sig = Bytes::copy_from_slice(&sig);
self.last = Some(sig.clone());
self.entries[self.tail] = shown.then_some(sig);
self.tail = (self.tail + 1) % LAST_SEEN;
self.offset += 1;
if self.offset > ACK_AFTER {
self.ack_due = true;
}
}
#[cfg(test)]
fn update(&mut self) -> (i32, [u8; 3], u8) {
self.update_with(|_| {})
}
fn update_with(&mut self, mut seen: impl FnMut(&Bytes)) -> (i32, [u8; 3], u8) {
let offset = std::mem::take(&mut self.offset);
self.ack_due = false;
let mut bits = [0u8; 3];
let mut checksum: i32 = 1;
for i in 0..LAST_SEEN {
if let Some(sig) = &self.entries[(self.tail + i) % LAST_SEEN] {
bits[i / 8] |= 1 << (i % 8);
checksum = checksum.wrapping_mul(31).wrapping_add(java_array_hash(sig));
seen(sig);
}
}
let b = checksum as u8;
(offset, bits, if b == 0 { 1 } else { b })
}
}
fn java_array_hash(b: &[u8]) -> i32 {
b.iter().fold(1i32, |h, &x| {
h.wrapping_mul(31).wrapping_add(i32::from(x as i8))
})
}
impl Wire {
#[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(crate) fn set_last_look(&mut self, yaw: f32, pitch: f32) {
self.last_look = (yaw, pitch);
}
fn next_sequence(&mut self) -> i32 {
self.sequence = self.sequence.wrapping_add(1);
self.sequence
}
fn next_salt(&mut self) -> i64 {
if self.salt == 0 {
let t = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_nanos() as u64);
self.salt = t ^ (std::ptr::from_ref(self) as u64).rotate_left(32) | 1;
}
let mut x = self.salt;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
self.salt = x;
x.wrapping_mul(0x2545_F491_4F6C_DD1D) as i64
}
fn sign(&mut self, content: &str, timestamp: i64, salt: i64, seen: &[Bytes]) -> Option<Bytes> {
let s = self.chat.as_mut()?;
match s.chain.sign(
&s.keys,
content,
timestamp,
salt,
seen.iter().map(|b| &b[..]),
) {
Ok(sig) => sig.map(Bytes::from),
Err(e) => {
log::warn!("chat signing failed: {e}");
None
}
}
}
fn write_chat(&mut self, enc: &mut FrameEncoder, text: &str) -> Result<(), EncodeError> {
let salt = self.next_salt();
self.write_chat_at(enc, text, now_millis(), salt)
}
fn write_chat_at(
&mut self,
enc: &mut FrameEncoder,
text: &str,
timestamp: i64,
salt: i64,
) -> Result<(), EncodeError> {
let message = truncate_utf16(text, Marker::CHAT_LIMIT);
let mut seen = Vec::new();
let signing = self.chat.is_some();
let (offset, bits, checksum) = self.seen.update_with(|s| {
if signing {
seen.push(s.clone());
}
});
let signature = self.sign(message, timestamp, salt, &seen);
enc.write_packet(&sb::ChatMessage {
message: ByteString::from(message),
timestamp,
salt,
signature,
offset,
acknowledged: Bytes::copy_from_slice(&bits),
checksum,
})
}
fn write_command(&mut self, enc: &mut FrameEncoder, command: &str) -> Result<(), EncodeError> {
let salt = self.next_salt();
self.write_command_at(enc, command, now_millis(), salt)
}
fn write_command_at(
&mut self,
enc: &mut FrameEncoder,
command: &str,
timestamp: i64,
salt: i64,
) -> Result<(), EncodeError> {
self.parse_commands();
let signable = self
.commands
.as_ref()
.map(|t| t.signable_arguments(command, self.op_level >= 2))
.unwrap_or_default();
if signable.is_empty() {
return enc.write_packet(&sb::ChatCommand {
command: ByteString::from(command),
});
}
let mut seen = Vec::new();
let signing = self.chat.is_some();
let (offset, bits, checksum) = self.seen.update_with(|s| {
if signing {
seen.push(s.clone());
}
});
let mut argument_signatures = Vec::new();
for (name, value) in signable {
if let Some(signature) = self.sign(value, timestamp, salt, &seen) {
argument_signatures.push(sb::ChatCommandSignedArgumentSignatures {
argument_name: ByteString::from(&*name),
signature,
});
}
}
enc.write_packet(&sb::ChatCommandSigned {
command: ByteString::from(command),
timestamp,
salt,
argument_signatures,
message_count: offset,
acknowledged: Bytes::copy_from_slice(&bits),
checksum,
})
}
fn parse_commands(&mut self) {
if self.commands.is_none()
&& let Some(raw) = self.commands_raw.as_deref().and_then(inflate)
{
match raw.decode_as::<cb::DeclareCommands>() {
Ok(p) => self.commands = command_tree(&p),
Err(e) => log::warn!("bad declare_commands packet: {e}"),
}
if self.commands.is_some() {
self.commands_raw = None;
}
}
}
fn check_command(&mut self, command: &str) -> crate::dialog::CommandCheck {
self.parse_commands();
self.commands
.as_ref()
.map_or(crate::dialog::CommandCheck::ParseErrors, |t| {
t.check(command, self.op_level)
})
}
fn new_level(&mut self, dimension: &str) {
self.sequence = 0;
dimension.clone_into(&mut self.dimension);
}
}
fn now_millis() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
fn plain(nbt: &AnonNbt) -> String {
nbt_to_plain_text(nbt)
}
fn reason_json(nbt: &AnonNbt) -> ByteString {
let text = plain(nbt);
let mut s = String::with_capacity(text.len() + 12);
s.push_str("{\"text\":\"");
for c in text.chars() {
match c {
'"' => s.push_str("\\\""),
'\\' => s.push_str("\\\\"),
'\n' => s.push_str("\\n"),
c if (c as u32) < 0x20 => s.push_str(&format!("\\u{:04x}", c as u32)),
c => s.push(c),
}
}
s.push_str("\"}");
ByteString::from(s)
}
fn chat_pattern(chat_type: &str) -> &'static str {
match chat_type.strip_prefix("minecraft:").unwrap_or(chat_type) {
"say_command" => "[%1] %2",
"emote_command" => "* %1 %2",
"msg_command_incoming" => "%1 whispers to you: %2",
"msg_command_outgoing" => "You whisper to %3: %2",
"team_msg_command_incoming" => "%3 <%1> %2",
"team_msg_command_outgoing" => "%3 -> <%1> %2",
_ => "<%1> %2",
}
}
fn render_chat(pattern: &str, sender: &str, content: &str, target: &str) -> String {
let mut out = String::with_capacity(pattern.len() + sender.len() + content.len());
let mut it = pattern.chars().peekable();
while let Some(c) = it.next() {
if c == '%' {
match it.peek() {
Some('1') => out.push_str(sender),
Some('2') => out.push_str(content),
Some('3') => out.push_str(target),
_ => {
out.push(c);
continue;
}
}
it.next();
} else {
out.push(c);
}
}
out
}
const MOVEMENT_ATTRIBUTES: &[&str] = &[
"block_break_speed",
"block_interaction_range",
"entity_interaction_range",
"gravity",
"jump_strength",
"mining_efficiency",
"movement_efficiency",
"movement_speed",
"attack_speed",
"safe_fall_distance",
"scale",
"sneaking_speed",
"step_height",
"submerged_mining_speed",
"water_movement_efficiency",
"bounciness",
"friction_modifier",
"air_drag_modifier",
];
#[cfg(test)]
pub(super) fn attribute_name_of(
k: cb::EntityUpdateAttributesPropertiesKey,
) -> Option<&'static str> {
attribute_name(k.name())
}
fn attribute_name(label: Option<&'static str>) -> Option<&'static str> {
let label = label?;
let name = label.rsplit_once('.').map_or(label, |(_, n)| n);
MOVEMENT_ATTRIBUTES.iter().copied().find(|&n| n == name)
}
impl ClientVersion for Marker {
const GAME: GameVersion = super::GAME;
const CHAT_LIMIT: usize = super::GAME.caps().chat_limit;
type Wire = Wire;
fn write_handshake(enc: &mut FrameEncoder, host: &str, port: u16) -> Result<(), EncodeError> {
enc.write_packet(&handshaking::serverbound::SetProtocol {
protocol_version: <Marker as ghast_protocol::Version>::PROTOCOL,
server_host: ByteString::from(host),
server_port: port,
next_state: 2,
})
}
fn write_login_start(
enc: &mut FrameEncoder,
username: &str,
uuid: uuid::Uuid,
) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::LoginStart {
username: ByteString::from(username),
player_uuid: uuid,
})
}
fn write_encryption_response(
enc: &mut FrameEncoder,
shared_secret: &[u8],
verify_token: &[u8],
) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::EncryptionBegin {
shared_secret: Bytes::copy_from_slice(shared_secret),
verify_token: Bytes::copy_from_slice(verify_token),
})
}
fn write_plugin_response(enc: &mut FrameEncoder, message_id: i32) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::LoginPluginResponse {
message_id,
data: None,
})
}
fn decode_login(raw: &RawPacket) -> Result<Option<LoginInbound>, DecodeError> {
use login::clientbound as lc;
Ok(Some(match raw.id {
lc::id::DISCONNECT => {
LoginInbound::Disconnect(raw.decode_as::<lc::Disconnect>()?.reason)
}
lc::id::ENCRYPTION_BEGIN => {
let p: lc::EncryptionBegin = raw.decode_as()?;
if p.should_authenticate {
LoginInbound::EncryptionRequest {
server_id: p.server_id,
public_key: p.public_key,
verify_token: p.verify_token,
}
} else {
LoginInbound::EncryptionRequestUnauthenticated {
server_id: p.server_id,
public_key: p.public_key,
verify_token: p.verify_token,
}
}
}
lc::id::SUCCESS => {
let p: lc::Success = raw.decode_as()?;
LoginInbound::Success {
uuid: Some(p.uuid),
username: p.username,
}
}
lc::id::COMPRESS => LoginInbound::Compress(raw.decode_as::<lc::Compress>()?.threshold),
lc::id::LOGIN_PLUGIN_REQUEST => {
let p: lc::LoginPluginRequest = raw.decode_as()?;
LoginInbound::PluginRequest {
message_id: p.message_id,
channel: p.channel,
}
}
lc::id::COOKIE_REQUEST => {
LoginInbound::CookieRequest(raw.decode_as::<lc::CookieRequest>()?.cookie)
}
_ => return Ok(None),
}))
}
fn prepare_play(out: &[Outbound], wire: &mut Wire) {
wire.tick_look = out.iter().find_map(|o| match *o {
Outbound::Move(MovePacket::Look { yaw, pitch, .. })
| Outbound::Move(MovePacket::PositionLook { yaw, pitch, .. }) => Some((yaw, pitch)),
_ => None,
});
}
fn write_transfer_handshake(
enc: &mut FrameEncoder,
host: &str,
port: u16,
) -> Result<(), EncodeError> {
enc.write_packet(&handshaking::serverbound::SetProtocol {
protocol_version: <Marker as ghast_protocol::Version>::PROTOCOL,
server_host: ByteString::from(host),
server_port: port,
next_state: 3,
})
}
fn take_cookies(wire: &mut Wire) -> Vec<(ByteString, Bytes)> {
std::mem::take(&mut wire.cookies).into_iter().collect()
}
fn put_cookies(wire: &mut Wire, cookies: Vec<(ByteString, Bytes)>) {
wire.cookies.extend(cookies);
}
fn write_login_cookie_response_from(
enc: &mut FrameEncoder,
key: &str,
wire: &mut Wire,
) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::CookieResponse {
key: ByteString::from(key),
value: wire.cookies.get(key).cloned(),
})
}
fn write_login_cookie_response(enc: &mut FrameEncoder, key: &str) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::CookieResponse {
key: ByteString::from(key),
value: None,
})
}
fn write_login_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
enc.write_packet(&login::serverbound::LoginAcknowledged {})
}
fn decode_configuration(
raw: &RawPacket,
wire: &mut Wire,
) -> Result<Option<ConfigInbound>, DecodeError> {
use configuration::clientbound as cc;
Ok(Some(match raw.id {
cc::id::KEEP_ALIVE => {
ConfigInbound::KeepAlive(raw.decode_as::<cc::KeepAlive>()?.keep_alive_id)
}
cc::id::PING => ConfigInbound::Ping(raw.decode_as::<cc::Ping>()?.id),
cc::id::FINISH_CONFIGURATION => ConfigInbound::Finish,
cc::id::DISCONNECT => {
ConfigInbound::Disconnect(plain(&raw.decode_as::<cc::Disconnect>()?.reason))
}
cc::id::SELECT_KNOWN_PACKS => {
let p: cc::SelectKnownPacks = raw.decode_as()?;
ConfigInbound::SelectKnownPacks(
p.packs
.into_iter()
.map(|k| KnownPack {
namespace: k.namespace,
id: k.id,
version: k.version,
})
.collect(),
)
}
cc::id::REGISTRY_DATA => ConfigInbound::RegistryData(raw.clone()),
cc::id::ADD_RESOURCE_PACK => {
let p: cc::AddResourcePack = raw.decode_as()?;
ConfigInbound::ResourcePackPush {
id: p.uuid,
required: p.forced,
}
}
cc::id::COOKIE_REQUEST => {
ConfigInbound::CookieRequest(raw.decode_as::<cc::CookieRequest>()?.cookie)
}
cc::id::STORE_COOKIE => {
let p: cc::StoreCookie = raw.decode_as()?;
wire.cookies.insert(p.key, p.value);
return Ok(None);
}
cc::id::CODE_OF_CONDUCT => ConfigInbound::CodeOfConduct(
raw.decode_as::<cc::CodeOfConduct>()?.contents.to_string(),
),
cc::id::TAGS => {
wire.inv_config
.push((true, Bytes::copy_from_slice(&raw.body)));
return Ok(None);
}
cc::id::TRANSFER => {
let p: cc::Transfer = raw.decode_as()?;
ConfigInbound::Transfer(format!("{}:{}", p.host, p.port))
}
cc::id::SHOW_DIALOG => ConfigInbound::ShowDialog(Box::new(crate::dialog::decode(
&raw.decode_as::<cc::ShowDialog>()?.dialog,
wire.dialogs.as_ref(),
))),
cc::id::CLEAR_DIALOG => ConfigInbound::ClearDialog,
id => {
use ghast_protocol::PacketSet;
log::debug!(
"configuration packet {} (0x{id:02x}, {} B) not handled",
cc::ClientboundConfigurationPacket::name_of(id).unwrap_or("?"),
raw.body.len()
);
return Ok(None);
}
}))
}
fn write_configuration(
enc: &mut FrameEncoder,
out: &ConfigOutbound,
wire: &mut Wire,
) -> Result<(), EncodeError> {
use configuration::serverbound as cs;
match out {
ConfigOutbound::KeepAlive(id) => {
enc.write_packet(&cs::KeepAlive { keep_alive_id: *id })
}
ConfigOutbound::Pong(id) => enc.write_packet(&cs::Pong { id: *id }),
ConfigOutbound::Finish => enc.write_packet(&cs::FinishConfiguration {}),
ConfigOutbound::SelectKnownPacks(packs) => enc.write_packet(&cs::SelectKnownPacks {
packs: packs
.iter()
.map(|k| cs::SelectKnownPacksPacks {
namespace: k.namespace.clone(),
id: k.id.clone(),
version: k.version.clone(),
})
.collect(),
}),
ConfigOutbound::ResourcePackStatus { id, result } => {
enc.write_packet(&cs::ResourcePackReceive {
uuid: *id,
result: *result,
})
}
ConfigOutbound::CookieResponse { key } => enc.write_packet(&cs::CookieResponse {
key: key.clone(),
value: wire.cookies.get(key).cloned(),
}),
ConfigOutbound::AcceptCodeOfConduct => enc.write_packet(&cs::AcceptCodeOfConduct {}),
ConfigOutbound::Brand(brand) => {
let mut data = BytesMut::with_capacity(brand.len() + 1);
data.put_string(brand)?;
enc.write_packet(&cs::CustomPayload {
channel: ByteString::from_static("minecraft:brand"),
data: data.freeze(),
})
}
ConfigOutbound::Settings(s) => enc.write_packet(&cs::Settings {
locale: ByteString::from(s.locale.to_ascii_lowercase()),
view_distance: s.view_distance,
chat_flags: i32::from(s.chat_mode),
chat_colors: s.chat_colors,
skin_parts: s.skin_parts,
main_hand: s.main_hand,
enable_text_filtering: false,
enable_server_listing: true,
particle_status: cs::SettingsParticleStatus::ALL,
}),
ConfigOutbound::CustomClickAction { id, payload } => {
enc.write_packet(&cs::CustomClickAction {
id: ByteString::from(id.as_str()),
nbt: payload.clone(),
})
}
}
}
fn feed_inventory_config(inv: &mut ghast_inventory::Inventory, wire: &mut Wire) {
wire.hash_registries = inv.registries_modern().clone();
for (tags, body) in wire.inv_config.drain(..) {
if tags {
super::inv_on_update_tags(inv, body);
} else {
super::inv_on_registry_data(inv, body);
}
}
}
fn mount_screen_entity(raw: &RawPacket) -> Option<i32> {
if raw.id != cb::id::OPEN_HORSE_WINDOW {
return None;
}
raw.decode_as::<cb::OpenHorseWindow>()
.ok()
.map(|p| p.entity_id)
}
fn open_mount_screen(
inv: &mut ghast_inventory::Inventory,
raw: &RawPacket,
mount: Option<(i32, bool, bool)>,
) -> Result<(), DecodeError> {
let p: cb::OpenHorseWindow = raw.decode_as()?;
match mount {
Some((ty, saddle, body)) => {
super::inv_on_mount_screen(inv, p.window_id, p.nb_slots, ty, saddle, body);
Ok(())
}
None => super::inv_apply_raw(inv, raw),
}
}
fn note_registry(raw: &RawPacket, wire: &mut Wire) {
let Ok(p) = raw.decode_as::<configuration::clientbound::RegistryData>() else {
return;
};
if &*p.id == "minecraft:enchantment" {
wire.inv_config
.push((false, Bytes::copy_from_slice(&raw.body)));
}
if &*p.id == "minecraft:chat_type" {
wire.chat_types = p.entries.iter().map(|e| e.key.to_string()).collect();
}
if &*p.id == "minecraft:dialog" {
wire.dialogs = Some(std::sync::Arc::new(crate::dialog::DialogRegistry::new(
p.entries
.iter()
.map(|e| (e.key.to_string(), e.value.clone())),
)));
}
wire.hash_registries
.add(&p.id, p.entries.iter().map(|e| &*e.key));
}
fn write_configuration_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
enc.write_packet(&sb::ConfigurationAcknowledged {})
}
fn write_configuration_start_replies(
enc: &mut FrameEncoder,
wire: &mut Wire,
) -> Result<(), EncodeError> {
wire.seen.ack_due = false;
let count = std::mem::take(&mut wire.seen.offset);
if count > 0 {
enc.write_packet(&sb::MessageAcknowledgement { count })?;
}
Ok(())
}
fn check_command(wire: &mut Wire, command: &str) -> crate::dialog::CommandCheck {
wire.check_command(command)
}
fn prediction_sequence(wire: &Wire) -> Option<i32> {
Some(wire.sequence)
}
fn write_wire_replies(enc: &mut FrameEncoder, wire: &mut Wire) -> Result<(), EncodeError> {
if wire.seen.ack_due {
wire.seen.ack_due = false;
let count = std::mem::take(&mut wire.seen.offset);
if count > 0 {
enc.write_packet(&sb::MessageAcknowledgement { count })?;
}
}
Ok(())
}
fn play_filter(interests: Interests) -> PacketFilter {
let mut f = PacketFilter::none()
.with(cb::id::KEEP_ALIVE)
.with(cb::id::PING)
.with(cb::id::LOGIN)
.with(cb::id::UPDATE_HEALTH)
.with(cb::id::UPDATE_TIME)
.with(cb::id::RESPAWN)
.with(cb::id::POSITION)
.with(cb::id::PLAYER_ROTATION)
.with(cb::id::HELD_ITEM_SLOT)
.with(cb::id::GAME_STATE_CHANGE)
.with(cb::id::OPEN_WINDOW)
.with(cb::id::OPEN_HORSE_WINDOW)
.with(cb::id::CLOSE_WINDOW)
.with(cb::id::WINDOW_ITEMS)
.with(cb::id::SET_SLOT)
.with(cb::id::SET_CURSOR_ITEM)
.with(cb::id::SET_PLAYER_INVENTORY)
.with(cb::id::CRAFT_PROGRESS_BAR)
.with(cb::id::ABILITIES)
.with(cb::id::KICK_DISCONNECT)
.with(cb::id::DEATH_COMBAT_EVENT)
.with(cb::id::SPAWN_POSITION)
.with(cb::id::DAMAGE_EVENT)
.with(cb::id::ENTITY_STATUS)
.with(cb::id::SET_COOLDOWN)
.with(cb::id::ENTITY_UPDATE_ATTRIBUTES)
.with(cb::id::ENTITY_EFFECT)
.with(cb::id::REMOVE_ENTITY_EFFECT)
.with(cb::id::ENTITY_VELOCITY)
.with(cb::id::EXPLOSION)
.with(cb::id::START_CONFIGURATION)
.with(cb::id::ADD_RESOURCE_PACK)
.with(cb::id::COOKIE_REQUEST)
.with(cb::id::STORE_COOKIE)
.with(cb::id::PLAYER_CHAT)
.with(cb::id::DECLARE_COMMANDS)
.with(cb::id::TRANSFER);
for &id in super::world::PACKET_IDS {
f.insert(id);
}
for &id in super::inventory_packet_ids() {
f.insert(id);
}
if interests.contains(Interests::TEAMS) {
f.insert(cb::id::TEAMS);
}
if interests.contains(Interests::CHAT) {
f.insert(cb::id::SYSTEM_CHAT);
f.insert(cb::id::PROFILELESS_CHAT);
}
if interests.contains(Interests::DIALOGS) {
f.insert(cb::id::SHOW_DIALOG);
f.insert(cb::id::CLEAR_DIALOG);
}
f.insert(cb::id::TAB_COMPLETE);
f.insert(cb::id::OPEN_SIGN_ENTITY);
if interests.contains(Interests::HUD) {
f.insert(cb::id::BOSS_BAR);
f.insert(cb::id::SET_TITLE_TEXT);
f.insert(cb::id::SET_TITLE_SUBTITLE);
f.insert(cb::id::SET_TITLE_TIME);
f.insert(cb::id::CLEAR_TITLES);
f.insert(cb::id::ACTION_BAR);
f.insert(cb::id::PLAYERLIST_HEADER);
f.insert(cb::id::SYSTEM_CHAT);
}
f
}
fn decode_play(raw: &RawPacket, wire: &mut Wire) -> Result<Option<Inbound>, DecodeError> {
Ok(Some(match raw.id {
cb::id::KEEP_ALIVE => {
Inbound::KeepAlive(raw.decode_as::<cb::KeepAlive>()?.keep_alive_id)
}
cb::id::PING => Inbound::Ping(raw.decode_as::<cb::Ping>()?.id),
cb::id::LOGIN => {
let p: cb::Login = raw.decode_as()?;
let w = &p.world_state;
wire.new_level(&w.name);
wire.next_chat_index = 0;
wire.seen = LastSeen::default();
wire.chat = None;
wire.entity_id = p.entity_id;
wire.op_level = 0;
wire.online_mode = super::login_online_mode(&p);
Inbound::JoinGame(JoinGame {
entity_id: p.entity_id,
game_mode: GameMode::from_wire(w.gamemode.0 as u8),
dimension: w.name.to_string(),
hardcore: p.is_hardcore,
dimension_nbt: None,
respawn_screen: p.enable_respawn_screen,
})
}
cb::id::RESPAWN => {
let p: cb::Respawn = raw.decode_as()?;
let w = &p.world_state;
if *w.name != *wire.dimension {
wire.new_level(&w.name);
}
Inbound::Respawn {
dimension: w.name.to_string(),
game_mode: GameMode::from_wire(w.gamemode.0 as u8),
keep: p.copy_metadata,
}
}
cb::id::SYSTEM_CHAT => {
let p: cb::SystemChat = raw.decode_as()?;
Inbound::Chat(ChatMessage::from_text(
plain(&p.content),
if p.is_action_bar {
ChatPosition::ActionBar
} else {
ChatPosition::System
},
None,
))
}
cb::id::PLAYER_CHAT => {
let p: cb::PlayerChat = raw.decode_as()?;
if p.global_index != wire.next_chat_index {
log::warn!(
"player chat index {} (expected {}): vanilla disconnects here",
p.global_index,
wire.next_chat_index
);
}
wire.next_chat_index = p.global_index.wrapping_add(1);
if let Some(sig) = p.signature.clone() {
wire.seen.add(sig, true);
}
let content = p
.unsigned_chat_content
.as_ref()
.map_or_else(|| p.plain_message.to_string(), plain);
let kind = match &p.r#type {
ghast_protocol::types::Holder::Id(i) => usize::try_from(*i)
.ok()
.and_then(|i| wire.chat_types.get(i))
.map_or("minecraft:chat", String::as_str),
ghast_protocol::types::Holder::Inline(_) => "minecraft:chat",
};
let target = p
.network_target_name
.as_ref()
.map(plain)
.unwrap_or_default();
let text = render_chat(
chat_pattern(kind),
&plain(&p.network_name),
&content,
&target,
);
Inbound::Chat(ChatMessage::from_text(
text,
ChatPosition::Chat,
Some(p.sender_uuid),
))
}
cb::id::PROFILELESS_CHAT => {
let p: cb::ProfilelessChat = raw.decode_as()?;
let kind = p
.r#type
.id()
.and_then(|i| usize::try_from(i).ok())
.and_then(|i| wire.chat_types.get(i))
.map_or("minecraft:chat", String::as_str);
let target = p.target.as_ref().map(plain).unwrap_or_default();
Inbound::Chat(ChatMessage::from_text(
render_chat(
chat_pattern(kind),
&plain(&p.name),
&plain(&p.message),
&target,
),
ChatPosition::Chat,
None,
))
}
cb::id::UPDATE_HEALTH => {
let p: cb::UpdateHealth = raw.decode_as()?;
Inbound::Health(Health {
health: p.health,
food: p.food,
saturation: p.food_saturation,
..Health::default()
})
}
cb::id::POSITION => {
let p: cb::Position = raw.decode_as()?;
Inbound::Teleport(Teleport {
x: p.x,
y: p.y,
z: p.z,
yaw: p.yaw,
pitch: p.pitch,
flags: (p.flags.0 & 0x1f) as i8,
teleport_id: Some(p.teleport_id),
relative: p.flags.0,
delta: Vec3::new(p.dx, p.dy, p.dz),
})
}
cb::id::PLAYER_ROTATION => {
let p: cb::PlayerRotation = raw.decode_as()?;
Inbound::Rotate {
yaw: p.yaw,
pitch: p.pitch,
relative_yaw: p.relative_yaw,
relative_pitch: p.relative_pitch,
}
}
cb::id::UPDATE_TIME => {
Inbound::Time(crate::common::TimeUpdate::decode_modern(&raw.body)?)
}
cb::id::HELD_ITEM_SLOT => {
Inbound::HeldSlot(raw.decode_as::<cb::HeldItemSlot>()?.slot as i8)
}
cb::id::GAME_STATE_CHANGE => {
let p: cb::GameStateChange = raw.decode_as()?;
Inbound::GameState {
reason: p.reason.0,
value: p.game_mode,
}
}
cb::id::OPEN_WINDOW => {
Inbound::OpenWindow(raw.decode_as::<cb::OpenWindow>()?.window_id)
}
cb::id::CLOSE_WINDOW => {
Inbound::CloseWindow(raw.decode_as::<cb::CloseWindow>()?.window_id)
}
cb::id::ABILITIES => {
let p: cb::Abilities = raw.decode_as()?;
Inbound::Abilities(Abilities {
flags: p.flags,
flying_speed: p.flying_speed,
walking_speed: p.walking_speed,
})
}
cb::id::KICK_DISCONNECT => {
Inbound::Disconnect(reason_json(&raw.decode_as::<cb::KickDisconnect>()?.reason))
}
cb::id::ENTITY_VELOCITY => {
let p: cb::EntityVelocity = raw.decode_as()?;
let [x, y, z] = p.velocity.to_vec3();
Inbound::Velocity {
entity_id: p.entity_id,
motion: Vec3::new(x, y, z),
}
}
cb::id::EXPLOSION => {
let p: cb::Explosion = raw.decode_as()?;
let Some(k) = p.player_knockback else {
return Ok(None);
};
Inbound::ExplosionPush(Vec3::new(k.x, k.y, k.z))
}
cb::id::ENTITY_UPDATE_ATTRIBUTES => {
let p: cb::EntityUpdateAttributes = raw.decode_as()?;
let attributes: Vec<AttributeUpdate> = p
.properties
.iter()
.filter_map(|a| {
Some(AttributeUpdate {
name: attribute_name(a.key.name())?,
base: a.value,
modifiers: a
.modifiers
.iter()
.map(|m| (m.uuid.clone(), m.amount, m.operation))
.collect(),
})
})
.collect();
if attributes.is_empty() {
return Ok(None);
}
Inbound::Attributes {
entity_id: p.entity_id,
attributes,
}
}
cb::id::ENTITY_EFFECT => {
let p: cb::EntityEffect = raw.decode_as()?;
Inbound::EffectApplied(crate::common::StatusEffect {
entity_id: p.entity_id,
id: i8::try_from(p.effect_id + 1).unwrap_or(i8::MAX),
amplifier: p.amplifier.clamp(0, 127) as i8,
duration: p.duration,
flags: p.flags,
})
}
cb::id::REMOVE_ENTITY_EFFECT => {
let p: cb::RemoveEntityEffect = raw.decode_as()?;
Inbound::EffectRemoved {
entity_id: p.entity_id,
id: i8::try_from(p.effect_id + 1).unwrap_or(i8::MAX),
}
}
cb::id::ENTITY_STATUS => {
let p: cb::EntityStatus = raw.decode_as()?;
if p.entity_id == wire.entity_id && (24..=28).contains(&p.entity_status) {
wire.op_level = (p.entity_status - 24) as u8;
}
Inbound::EntityStatus {
entity_id: p.entity_id,
status: p.entity_status,
}
}
cb::id::SET_COOLDOWN => {
let p: cb::SetCooldown = raw.decode_as()?;
Inbound::ItemCooldown {
key: crate::cooldown::CooldownKey::Group(crate::cooldown::identifier(
&p.cooldown_group,
)),
ticks: p.cooldown_ticks,
}
}
cb::id::DEATH_COMBAT_EVENT => {
let p: cb::DeathCombatEvent = raw.decode_as()?;
Inbound::Death(crate::common::Death {
entity_id: p.player_id,
killer_id: None,
message: ChatMessage::from_text(plain(&p.message), ChatPosition::System, None),
})
}
cb::id::SPAWN_POSITION => {
let p: cb::SpawnPosition = raw.decode_as()?;
Inbound::SpawnPoint(crate::common::SpawnPoint {
pos: p.global_pos.location,
yaw: p.yaw,
pitch: p.pitch,
dimension: Some(p.global_pos.dimension_name.to_string()),
})
}
cb::id::DAMAGE_EVENT => {
let p: cb::DamageEvent = raw.decode_as()?;
let opt = |v: i32| (v > 0).then(|| v - 1);
Inbound::Damage(crate::common::Hurt::from_damage(
p.entity_id,
p.source_type_id,
opt(p.source_cause_id),
opt(p.source_direct_id),
))
}
cb::id::CHUNK_BATCH_START => Inbound::ChunkBatchStart,
cb::id::CHUNK_BATCH_FINISHED => {
Inbound::ChunkBatchFinished(raw.decode_as::<cb::ChunkBatchFinished>()?.batch_size)
}
cb::id::START_CONFIGURATION => Inbound::StartConfiguration,
cb::id::ADD_RESOURCE_PACK => {
let p: cb::AddResourcePack = raw.decode_as()?;
Inbound::ResourcePackPush {
id: p.uuid,
required: p.forced,
}
}
cb::id::COOKIE_REQUEST => {
Inbound::CookieRequest(raw.decode_as::<cb::CookieRequest>()?.cookie)
}
cb::id::STORE_COOKIE => {
let p: cb::StoreCookie = raw.decode_as()?;
wire.cookies.insert(p.key, p.value);
return Ok(None);
}
cb::id::TRANSFER => {
let p: cb::Transfer = raw.decode_as()?;
Inbound::Transfer {
host: p.host.to_string(),
port: u16::try_from(p.port).unwrap_or(25565),
}
}
cb::id::SHOW_DIALOG => {
use ghast_protocol::types::Holder;
let reg = wire.dialogs.as_ref();
Inbound::ShowDialog(std::sync::Arc::new(
match raw.decode_as::<cb::ShowDialog>()?.dialog {
Holder::Inline(n) => crate::dialog::decode(&n, reg),
Holder::Id(id) => crate::dialog::decode_reference(id, reg),
},
))
}
cb::id::CLEAR_DIALOG => Inbound::ClearDialog,
cb::id::DECLARE_COMMANDS => {
wire.commands_raw = Some(ghast_protocol::intern::bytes(&deflate(raw)));
wire.commands = None;
return Ok(None);
}
cb::id::BOSS_BAR => {
use crate::hud::{BossBar, BossBarColor, BossBarOp, BossBarStyle, Text};
let p: cb::BossBar = raw.decode_as()?;
let id = p.entity_uuid;
let style = || {
Some((
BossBarColor::from_wire(p.color?)?,
BossBarStyle::from_wire(p.dividers?)?,
))
};
let text = || Text::from_text(p.title.as_ref().map(plain).unwrap_or_default());
let f = p.flags.unwrap_or(0);
Inbound::BossBar(match p.action {
0 => {
let Some((color, style)) = style() else {
return Ok(None);
};
let mut bar =
BossBar::new(id, text(), p.health.unwrap_or(0.0), color, style);
bar.darken_screen = f & 1 != 0;
bar.play_music = f & 2 != 0;
bar.create_fog = f & 4 != 0;
BossBarOp::Add(bar)
}
1 => BossBarOp::Remove(id),
2 => BossBarOp::Progress(id, p.health.unwrap_or(0.0)),
3 => BossBarOp::Title(id, text()),
4 => {
let Some((color, style)) = style() else {
return Ok(None);
};
BossBarOp::Style { id, color, style }
}
5 => BossBarOp::Flags {
id,
darken_screen: f & 1 != 0,
play_music: f & 2 != 0,
create_fog: Some(f & 4 != 0),
},
_ => return Ok(None),
})
}
cb::id::SET_TITLE_TEXT => Inbound::Title(crate::hud::TitleOp::Title(
crate::hud::Text::from_text(plain(&raw.decode_as::<cb::SetTitleText>()?.text)),
)),
cb::id::SET_TITLE_SUBTITLE => Inbound::Title(crate::hud::TitleOp::Subtitle(
crate::hud::Text::from_text(plain(&raw.decode_as::<cb::SetTitleSubtitle>()?.text)),
)),
cb::id::SET_TITLE_TIME => {
let p: cb::SetTitleTime = raw.decode_as()?;
Inbound::Title(crate::hud::TitleOp::Times(crate::hud::TitleTimes::new(
p.fade_in, p.stay, p.fade_out,
)))
}
cb::id::CLEAR_TITLES => Inbound::Title(if raw.decode_as::<cb::ClearTitles>()?.reset {
crate::hud::TitleOp::Reset
} else {
crate::hud::TitleOp::Clear
}),
cb::id::ACTION_BAR => Inbound::ActionBar(crate::hud::Text::from_text(plain(
&raw.decode_as::<cb::ActionBar>()?.text,
))),
cb::id::PLAYERLIST_HEADER => {
let p: cb::PlayerlistHeader = raw.decode_as()?;
let part = |n: &AnonNbt| {
Some(crate::hud::Text::from_text(plain(n))).filter(|t| !t.is_empty())
};
Inbound::TabList {
header: part(&p.header),
footer: part(&p.footer),
}
}
cb::id::OPEN_SIGN_ENTITY => Inbound::OpenSign(super::decode_open_sign(raw)?),
cb::id::TAB_COMPLETE => {
let p: cb::TabComplete = raw.decode_as()?;
Inbound::TabComplete(crate::hud::TabCompleteResponse::new(
Some(p.transaction_id),
Some((p.start, p.length)),
p.matches
.iter()
.map(|m| {
crate::hud::Suggestion::new(
m.r#match.to_string(),
m.tooltip
.as_ref()
.map(|t| crate::hud::Text::from_text(plain(t))),
)
})
.collect(),
))
}
cb::id::TEAMS => Inbound::Teams(crate::teams::TeamsPacket::new(
raw.body.clone(),
super::TEAMS_LAYOUT,
)),
_ => return Ok(None),
}))
}
#[inline]
fn online_mode(wire: &Wire, encrypted: bool) -> bool {
wire.online_mode.unwrap_or(encrypted)
}
fn begin_chat_session(
wire: &mut Wire,
keys: &std::sync::Arc<ghast_auth::chat::ProfileKeys>,
profile_id: uuid::Uuid,
) -> bool {
if wire
.chat
.as_ref()
.is_some_and(|s| std::sync::Arc::ptr_eq(&s.keys, keys))
{
return false;
}
wire.chat = Some(ChatSession {
keys: keys.clone(),
chain: ghast_auth::chat::SignedMessageChain::new(profile_id, random_uuid()),
});
true
}
const INVENTORY: ghast_inventory::Version = super::INVENTORY;
fn inventory_packet(
inv: &mut ghast_inventory::Inventory,
raw: &RawPacket,
) -> Result<Option<ghast_inventory::Outgoing>, DecodeError> {
if (raw.id == cb::id::LOGIN
|| raw.id == cb::id::RESPAWN
|| super::inventory_packet_ids().contains(&raw.id))
&& raw.id != cb::id::OPEN_HORSE_WINDOW
{
super::inv_apply_raw(inv, raw)?;
let echo = super::inv_take_creative_echo(inv);
if !echo.is_empty() {
return Ok(Some(ghast_inventory::Outgoing::Creative(echo)));
}
}
Ok(None)
}
fn configure_inventory(inv: &mut ghast_inventory::Inventory, wire: &Wire) {
super::inv_set_registries(inv, wire.hash_registries.clone());
}
fn write_play(
enc: &mut FrameEncoder,
out: &Outbound,
wire: &mut Wire,
) -> Result<(), EncodeError> {
let flags = |on_ground: bool, horizontal_collision: bool| {
let mut f = sb::MovementFlags(0);
if on_ground {
f = f.with(sb::MovementFlags::ON_GROUND);
}
if horizontal_collision {
f = f.with(sb::MovementFlags::HAS_HORIZONTAL_COLLISION);
}
f
};
match out {
Outbound::KeepAlive(id) => enc.write_packet(&sb::KeepAlive { keep_alive_id: *id }),
Outbound::TeleportConfirm(teleport_id) => {
super::write_teleport_confirm(enc, *teleport_id, None)
}
Outbound::TeleportConfirmPose {
id,
pos,
yaw,
pitch,
} => super::write_teleport_confirm(enc, *id, Some((*pos, *yaw, *pitch))),
Outbound::Move(m) => match *m {
MovePacket::Flying {
on_ground,
horizontal_collision,
} => enc.write_packet(&sb::Flying {
flags: flags(on_ground, horizontal_collision),
}),
MovePacket::Position {
pos,
on_ground,
horizontal_collision,
} => enc.write_packet(&sb::Position {
x: pos.x,
y: pos.y,
z: pos.z,
flags: flags(on_ground, horizontal_collision),
}),
MovePacket::Look {
yaw,
pitch,
on_ground,
horizontal_collision,
} => {
wire.last_look = (yaw, pitch);
enc.write_packet(&sb::Look {
yaw,
pitch,
flags: flags(on_ground, horizontal_collision),
})
}
MovePacket::PositionLook {
pos,
yaw,
pitch,
on_ground,
horizontal_collision,
} => {
wire.last_look = (yaw, pitch);
enc.write_packet(&sb::PositionLook {
x: pos.x,
y: pos.y,
z: pos.z,
yaw,
pitch,
flags: flags(on_ground, horizontal_collision),
})
}
},
Outbound::VehicleMove {
pos,
yaw,
pitch,
on_ground,
} => enc.write_packet(&sb::VehicleMove {
x: pos.x,
y: pos.y,
z: pos.z,
yaw: *yaw,
pitch: *pitch,
on_ground: *on_ground,
}),
Outbound::SteerBoat { left, right } => enc.write_packet(&sb::SteerBoat {
left_paddle: *left,
right_paddle: *right,
}),
Outbound::SteerVehicle { .. } => Ok(()),
Outbound::LookAnswer { yaw, pitch } => {
wire.last_look = (*yaw, *pitch);
enc.write_packet(&sb::Look {
yaw: *yaw,
pitch: *pitch,
flags: flags(false, false),
})
}
Outbound::EntityAction { entity_id, action } => {
let action_id = match action {
EntityAction::StartSprinting => sb::EntityActionActionId::START_SPRINTING,
EntityAction::StopSprinting => sb::EntityActionActionId::STOP_SPRINTING,
EntityAction::StartFallFlying => sb::EntityActionActionId::START_FALL_FLYING,
EntityAction::StopRidingJump => sb::EntityActionActionId::STOP_RIDING_JUMP,
EntityAction::LeaveBed => sb::EntityActionActionId::STOP_SLEEPING,
_ => return Ok(()),
};
enc.write_packet(&sb::EntityAction {
entity_id: *entity_id,
action_id,
jump_boost: 0,
})
}
Outbound::RidingJump {
entity_id,
strength,
} => enc.write_packet(&sb::EntityAction {
entity_id: *entity_id,
action_id: sb::EntityActionActionId::START_RIDING_JUMP,
jump_boost: *strength,
}),
Outbound::PlayerInput(c) => {
let mut i = sb::PlayerInputInputs(0);
for (on, bit) in [
(c.forward, sb::PlayerInputInputs::FORWARD),
(c.back, sb::PlayerInputInputs::BACKWARD),
(c.left, sb::PlayerInputInputs::LEFT),
(c.right, sb::PlayerInputInputs::RIGHT),
(c.jump, sb::PlayerInputInputs::JUMP),
(c.sneak, sb::PlayerInputInputs::SHIFT),
(c.sprint, sb::PlayerInputInputs::SPRINT),
] {
if on {
i = sb::PlayerInputInputs(i.0 | bit.0);
}
}
enc.write_packet(&sb::PlayerInput { inputs: i })
}
Outbound::TickEnd => enc.write_packet(&sb::TickEnd {}),
Outbound::PlayerLoaded => enc.write_packet(&sb::PlayerLoaded {}),
Outbound::ChunkBatchReceived(chunks_per_tick) => {
enc.write_packet(&sb::ChunkBatchReceived {
chunks_per_tick: *chunks_per_tick,
})
}
Outbound::Pong(id) => enc.write_packet(&sb::Pong { id: *id }),
Outbound::Raw(p) => enc.write_raw(p),
Outbound::CustomClickAction { id, payload } => {
enc.write_packet(&sb::CustomClickAction {
id: ByteString::from(id.as_str()),
nbt: payload.clone(),
})
}
Outbound::DialogCommand(command) => enc.write_packet(&sb::ChatCommand {
command: ByteString::from(command.as_str()),
}),
Outbound::Chat(text) => match text.strip_prefix('/') {
Some(command) => wire.write_command(enc, command),
None => wire.write_chat(enc, text),
},
Outbound::ChatSessionUpdate => match &wire.chat {
Some(s) => enc.write_packet(&sb::ChatSessionUpdate {
session_uuid: s.chain.session_id(),
expire_time: s.keys.expires_at_millis(),
public_key: Bytes::copy_from_slice(s.keys.public_key_der()),
signature: Bytes::copy_from_slice(s.keys.key_signature()),
}),
None => Ok(()),
},
Outbound::TabComplete { id, text, .. } => enc.write_packet(&sb::TabComplete {
transaction_id: *id,
text: ByteString::from(text.as_str()),
}),
Outbound::EditBook(b) => enc.write_packet(&sb::EditBook {
hand: b.slot,
pages: b
.pages
.iter()
.map(|p| ByteString::from(p.as_str()))
.collect(),
title: b.title.as_deref().map(ByteString::from),
}),
Outbound::UpdateSign { pos, front, lines } => {
super::write_update_sign(enc, *pos, *front, lines)
}
Outbound::Respawn => enc.write_packet(&sb::ClientCommand {
action_id: sb::ClientCommandActionId::PERFORM_RESPAWN,
}),
Outbound::Abilities { flags, .. } => enc.write_packet(&sb::Abilities { flags: *flags }),
Outbound::HeldSlot(slot) => enc.write_packet(&sb::HeldItemSlot { slot_id: *slot }),
Outbound::Swing => super::write_swing(enc, false),
Outbound::SwingOffHand => super::write_swing(enc, true),
Outbound::Punch => super::write_punch(enc),
Outbound::Dig { status, pos, face } => {
use crate::common::DigStatus;
let sequence = match status {
DigStatus::Start | DigStatus::Finish => wire.next_sequence(),
_ => 0,
};
enc.write_packet(&sb::BlockDig {
status: super::dig_status_id(*status),
location: *pos,
face: face.id(),
sequence,
})
}
Outbound::Place {
pos,
face,
cursor,
off_hand,
..
}
| Outbound::PlaceInside {
pos,
face,
cursor,
off_hand,
..
} => {
let sequence = wire.next_sequence();
enc.write_packet(&sb::BlockPlace {
hand: sb::BlockPlaceHand(i32::from(*off_hand)),
location: *pos,
direction: i32::from(face.id()),
cursor_x: cursor.x as f32,
cursor_y: cursor.y as f32,
cursor_z: cursor.z as f32,
inside_block: matches!(out, Outbound::PlaceInside { .. }),
world_border_hit: false,
sequence,
})
}
Outbound::UseItem { off_hand, .. } => {
let sequence = wire.next_sequence();
let (yaw, pitch) = wire.tick_look.unwrap_or(wire.last_look);
enc.write_packet(&sb::UseItem {
hand: sb::UseItemHand(i32::from(*off_hand)),
sequence,
rotation: super::proto::types::Vec2f { x: yaw, y: pitch },
})
}
Outbound::UseEntity {
target,
action,
off_hand,
sneaking,
} => match action {
crate::common::EntityUse::Attack => {
enc.write_packet(&sb::Attack { entity_id: *target })
}
crate::common::EntityUse::InteractAt(v) => enc.write_packet(&sb::UseEntity {
target: *target,
hand: sb::UseEntityHand(i32::from(*off_hand)),
location: LpVec3::from_vec3([v.x, v.y, v.z]),
sneaking: *sneaking,
}),
_ => Ok(()),
},
Outbound::Settings(s) => enc.write_packet(&sb::Settings {
locale: ByteString::from(s.locale.to_ascii_lowercase()),
view_distance: s.view_distance,
chat_flags: i32::from(s.chat_mode),
chat_colors: s.chat_colors,
skin_parts: s.skin_parts,
main_hand: s.main_hand,
enable_text_filtering: false,
enable_server_listing: true,
particle_status: sb::SettingsParticleStatus::ALL,
}),
Outbound::Brand(brand) => {
let mut data = BytesMut::with_capacity(brand.len() + 1);
data.put_string(brand)?;
enc.write_packet(&sb::CustomPayload {
channel: ByteString::from_static("minecraft:brand"),
data: data.freeze(),
})
}
Outbound::ResourcePackStatus { id, result } => {
enc.write_packet(&sb::ResourcePackReceive {
uuid: *id,
result: *result,
})
}
Outbound::CookieResponse { key, value } => enc.write_packet(&sb::CookieResponse {
key: key.clone(),
value: value.clone().or_else(|| wire.cookies.get(key).cloned()),
}),
Outbound::Inventory(o) => match super::inv_packet(o, &wire.hash_registries) {
Some(sb::ServerboundPlayPacket::WindowClick(p)) => {
if let ghast_inventory::Outgoing::ContainerClick(c) = o {
for _ in 0..c.swings {
super::write_swing(enc, false)?;
}
}
enc.write_packet(&p)
}
Some(sb::ServerboundPlayPacket::CloseWindow(p)) => enc.write_packet(&p),
Some(sb::ServerboundPlayPacket::NameItem(p)) => enc.write_packet(&p),
Some(sb::ServerboundPlayPacket::EnchantItem(p)) => enc.write_packet(&p),
Some(sb::ServerboundPlayPacket::SelectTrade(p)) => enc.write_packet(&p),
None => match o {
ghast_inventory::Outgoing::Creative(list) => {
for c in list {
match super::inv_creative_packet(c) {
Some(sb::ServerboundPlayPacket::SetCreativeSlot(p)) => {
enc.write_packet(&p)?;
}
Some(_) => super::write_swing(enc, false)?,
None => {}
}
}
Ok(())
}
_ => Ok(()),
},
_ => Ok(()),
},
Outbound::Transaction { .. } => Ok(()),
}
}
fn apply_teleport(pose: &mut Pose, t: &Teleport) {
let (yaw, pitch) = teleport_target(pose, t);
pose.yaw = yaw;
pose.pitch = pitch.clamp(-90.0, 90.0);
}
}
impl crate::version::HasSim for Marker {
type Sim = super::Sim;
fn new_sim(opts: &crate::sim::SimOptions) -> Self::Sim {
super::Sim::with(opts)
}
}
#[cfg(test)]
#[path = "modern_chat_golden.rs"]
mod chat_golden;
fn command_tree(p: &cb::DeclareCommands) -> Option<crate::version::commands::CommandTree> {
use super::proto::types::CommandNodeExtraNodeData;
use crate::version::commands::{CommandTree, Node, Reader};
let n = p.nodes.len();
let index = |i: i32| u32::try_from(i).ok().filter(|&i| (i as usize) < n);
let mut nodes = Vec::with_capacity(n);
for node in &p.nodes {
let (name, reader): (Box<str>, Reader) = match &node.extra_node_data {
CommandNodeExtraNodeData::Case1(l) => ((&*l.name).into(), Reader::Balanced),
CommandNodeExtraNodeData::Case2(a) => ((&*a.name).into(), reader_for(a)),
_ => ("".into(), Reader::Balanced),
};
nodes.push(Node {
kind: node.flags.command_node_type,
name,
reader,
children: node.children.iter().filter_map(|&c| index(c)).collect(),
redirect: node.redirect_node.and_then(index),
executable: node.flags.has_command != 0,
restricted: node.flags.allows_restricted != 0,
});
}
Some(CommandTree::new(nodes, index(p.root_index)?))
}
fn reader_for(
a: &super::proto::types::CommandNodeExtraNodeDataCase2,
) -> crate::version::commands::Reader {
use super::proto::types::CommandNodeExtraNodeDataCase2Parser as P;
use super::proto::types::CommandNodeExtraNodeDataCase2Properties as Props;
use crate::version::commands::Reader;
match a.parser {
P::BRIGADIER_BOOL => Reader::StringToken,
P::BRIGADIER_FLOAT | P::BRIGADIER_DOUBLE | P::BRIGADIER_INTEGER | P::BRIGADIER_LONG => {
Reader::Number
}
P::BRIGADIER_STRING => match &a.properties {
Props::BrigadierString(s) if s.0 == 0 => Reader::Word,
Props::BrigadierString(s) if s.0 == 2 => Reader::Greedy,
_ => Reader::StringToken,
},
P::MINECRAFT_ENTITY => match &a.properties {
Props::Entity(f) => Reader::Entity {
single: f.only_allow_entities == 1,
players: f.only_allow_players == 1,
},
_ => Reader::Entity {
single: false,
players: false,
},
},
P::MINECRAFT_GAME_PROFILE => Reader::GameProfile,
P::MINECRAFT_SCORE_HOLDER => Reader::ScoreHolder,
P::MINECRAFT_MESSAGE => Reader::Message,
P::MINECRAFT_VEC3 | P::MINECRAFT_BLOCK_POS => Reader::Coords(3),
P::MINECRAFT_VEC2 | P::MINECRAFT_COLUMN_POS | P::MINECRAFT_ROTATION => Reader::Coords(2),
P::MINECRAFT_ANGLE => Reader::Coords(1),
P::MINECRAFT_TIME => Reader::Time,
_ => Reader::Balanced,
}
}
fn deflate(raw: &RawPacket) -> Box<[u8]> {
let mut enc = FrameEncoder::new();
enc.set_compression(0);
match enc.write_raw(raw) {
Ok(()) => enc.pending().into(),
Err(_) => Box::default(),
}
}
fn inflate(z: &[u8]) -> Option<RawPacket> {
let mut dec = ghast_protocol::FrameDecoder::new();
dec.set_compression(0);
dec.push(z);
dec.next_packet().ok().flatten()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn last_seen_checksum_and_bits() {
let mut t = LastSeen::default();
assert_eq!(t.update(), (0, [0; 3], 1));
t.add(Bytes::from_static(&[1, 2, 3]), true);
t.add(Bytes::from_static(&[1, 2, 3]), true); t.add(Bytes::from_static(&[200]), true);
let (offset, bits, checksum) = t.update();
assert_eq!(offset, 2);
assert_eq!(bits, [0, 0, 0b1100]);
let h1 = java_array_hash(&[1, 2, 3]);
let h2 = java_array_hash(&[200]);
let c = 31i32.wrapping_add(h1).wrapping_mul(31).wrapping_add(h2);
assert_eq!(checksum, if c as u8 == 0 { 1 } else { c as u8 });
assert_eq!(h1, 30817);
}
#[test]
fn creative_screen_packets_and_echo() {
use ghast_inventory::{Click, Inventory, Outgoing, Stack};
let mut inv = Inventory::new(super::super::INVENTORY).unwrap();
super::super::inv_set_creative(&mut inv, true);
let stone = inv::item_id("stone").unwrap();
let mut w0 = vec![None; 46];
w0[36] = Some(Stack::new(stone, 64, 0));
super::super::inv_on_window_items(&mut inv, 0, 1, w0, None);
inv.tick();
let open = inv.open_inventory().unwrap();
assert!(matches!(open, Some(Outgoing::Creative(_))));
inv.tick();
let o = inv
.click(Click::Drop {
slot: 36,
all: false,
})
.unwrap();
let mut enc = FrameEncoder::new();
let mut wire = Wire::default();
Marker::write_play(&mut enc, &Outbound::Inventory(o), &mut wire).unwrap();
let ids = frame_ids(&mut enc);
let slots = match super::super::SWING_PACKET_ID {
Some(swing) => {
assert_eq!(ids[0], swing);
&ids[1..]
}
None => &ids[..],
};
assert!(
slots.iter().all(|&i| i == sb::id::SET_CREATIVE_SLOT),
"{ids:?}"
);
assert!(!slots.is_empty());
let mut body = vec![0x00, 0x02, 0x00, 37, 0x05];
let mut id = stone as u32;
loop {
let b = (id & 0x7f) as u8;
id >>= 7;
if id == 0 {
body.push(b);
break;
}
body.push(b | 0x80);
}
body.extend_from_slice(&[0, 0]);
let raw = RawPacket::new(cb::id::SET_SLOT, Bytes::from(body));
let echo = Marker::inventory_packet(&mut inv, &raw).unwrap();
let Some(Outgoing::Creative(list)) = echo else {
panic!("no echo: {echo:?}");
};
let slots: Vec<(i16, i32)> = list
.iter()
.map(|c| match c {
ghast_inventory::CreativePacket::SetSlot { slot, item } => {
(*slot, item.as_ref().map_or(0, |s| s.count()))
}
other => panic!("{other:?}"),
})
.collect();
assert_eq!(slots, vec![(36, 63), (37, 5)]);
let n = list.len();
Marker::write_play(
&mut enc,
&Outbound::Inventory(Outgoing::Creative(list)),
&mut wire,
)
.unwrap();
assert_eq!(frame_ids(&mut enc), vec![sb::id::SET_CREATIVE_SLOT; n]);
}
fn frame_ids(enc: &mut FrameEncoder) -> Vec<i32> {
let out = enc.out_mut().split().freeze();
let mut v = Vec::new();
let mut r = &out[..];
while !r.is_empty() {
let (len, rest) = (usize::from(r[0]), &r[1..]);
assert!(r[0] < 0x80, "long frame");
v.push(i32::from(rest[0]));
r = &rest[len..];
}
v
}
fn menu_of(kind: ghast_inventory::WindowKind) -> i32 {
(0..64)
.find(|&m| inv::window_kind(m) == Some(kind))
.unwrap()
}
#[test]
fn anvil_rename_and_trade_packets() {
use ghast_inventory::{Inventory, Stack, WindowKind};
let mut wire = Wire::default();
let mut enc = FrameEncoder::new();
let mut inv = Inventory::new(super::super::INVENTORY).unwrap();
super::super::inv_on_open_screen(
&mut inv,
3,
menu_of(WindowKind::Anvil),
ByteString::from_static("Anvil"),
);
let sword = inv::item_id("iron_sword").unwrap();
inv.on_set_slot(3, 0, Some(Stack::new(sword, 1, 0)));
inv.tick();
let o = super::super::inv_anvil_rename(&mut inv, "Blade")
.unwrap()
.expect("a rename");
Marker::write_play(&mut enc, &Outbound::Inventory(o), &mut wire).unwrap();
assert_eq!(frame_ids(&mut enc), vec![sb::id::NAME_ITEM]);
assert!(
super::super::inv_anvil_rename(&mut inv, "Blade")
.unwrap()
.is_none()
);
let mut inv = Inventory::new(super::super::INVENTORY).unwrap();
super::super::inv_on_open_screen(
&mut inv,
4,
menu_of(WindowKind::Merchant),
ByteString::from_static("Villager"),
);
inv.tick();
let o = super::super::inv_select_trade(&mut inv, 1).unwrap();
Marker::write_play(&mut enc, &Outbound::Inventory(o), &mut wire).unwrap();
assert_eq!(frame_ids(&mut enc), vec![sb::id::SELECT_TRADE]);
}
#[test]
fn mount_screen_reads_the_entity() {
use super::super::proto::types::{
EntityMetadataEntry, EntityMetadataEntryType as T, EntityMetadataEntryValue as V,
};
use crate::sim::Sim;
use ghast_inventory::{Inventory, WindowKind};
fn body<P: ghast_protocol::Packet + ghast_protocol::Encode>(p: &P) -> Bytes {
let mut enc = FrameEncoder::new();
enc.write_packet(p).unwrap();
let out = enc.out_mut().split().freeze();
Bytes::copy_from_slice(&out[2..])
}
let mut sim = super::super::Sim::test_overworld();
let ty = |name: &str| i32::from(super::super::data::entity_by_name(name).unwrap().id);
let spawn = |id: i32, ty: i32| {
RawPacket::new(
cb::id::SPAWN_ENTITY,
body(&cb::SpawnEntity {
entity_id: id,
object_uuid: uuid::Uuid::from_u64_pair(1, id as u64),
r#type: ty,
x: 0.5,
y: 4.0,
z: 0.5,
velocity: LpVec3::ZERO,
pitch: 0,
yaw: 0,
head_pitch: 0,
object_data: 0,
}),
)
};
let meta = |id: i32, key: u8, ty: T, value: V| {
RawPacket::new(
cb::id::ENTITY_METADATA,
body(&cb::EntityMetadata {
entity_id: id,
metadata: vec![EntityMetadataEntry {
key,
r#type: ty,
value,
}],
}),
)
};
let (horse, llama, nautilus) = (ty("horse"), ty("llama"), ty("nautilus"));
sim.world_packet(&spawn(50, horse)).unwrap();
assert_eq!(sim.mount_info(50), Some((horse, false, true)));
sim.world_packet(&meta(50, 18, T::BYTE, V::Byte(2)))
.unwrap(); assert_eq!(sim.mount_info(50), Some((horse, true, true)));
sim.world_packet(&meta(50, 16, T::BOOLEAN, V::Boolean(true)))
.unwrap(); assert_eq!(sim.mount_info(50), Some((horse, false, true)));
sim.world_packet(&spawn(51, llama)).unwrap();
assert_eq!(sim.mount_info(51), Some((llama, true, true)));
sim.world_packet(&spawn(52, nautilus)).unwrap(); assert_eq!(sim.mount_info(52), Some((nautilus, false, false)));
let destroy = RawPacket::new(
cb::id::ENTITY_DESTROY,
body(&cb::EntityDestroy {
entity_ids: vec![51],
}),
);
sim.world_packet(&destroy).unwrap();
assert_eq!(sim.mount_info(51), None);
let open = RawPacket::new(
cb::id::OPEN_HORSE_WINDOW,
body(&cb::OpenHorseWindow {
window_id: 5,
nb_slots: 3,
entity_id: 50,
}),
);
assert_eq!(Marker::mount_screen_entity(&open), Some(50));
let mut inv = Inventory::new(super::super::INVENTORY).unwrap();
Marker::open_mount_screen(&mut inv, &open, sim.mount_info(50)).unwrap();
let w = inv.window().expect("mount screen");
assert_eq!(w.id(), 5);
assert!(
matches!(w.kind(), WindowKind::Horse { .. }),
"{:?}",
w.kind()
);
}
#[test]
fn filter_passes_the_inventory_packets() {
let f = Marker::play_filter(Interests::NONE);
for &id in super::super::inventory_packet_ids() {
assert!(f.contains(id), "0x{id:02x}");
}
}
#[test]
fn dropping_click_swings_first() {
use ghast_inventory::{Click, Inventory, Stack};
let mut inv = Inventory::new(super::super::INVENTORY).unwrap();
let dirt = inv::item_id("dirt").unwrap();
inv.on_set_slot(0, 36, Some(Stack::new(dirt, 5, 0)));
let _ = inv.open_inventory().unwrap();
for _ in 0..3 {
inv.tick();
}
let o = inv
.click(Click::Drop {
slot: 36,
all: false,
})
.unwrap();
let swings = match &o {
ghast_inventory::Outgoing::ContainerClick(c) => c.swings,
other => panic!("{other:?}"),
};
assert_eq!(
usize::from(swings),
usize::from(super::super::SWING_PACKET_ID.is_some())
);
let mut enc = FrameEncoder::new();
let mut wire = Wire::default();
Marker::write_play(&mut enc, &Outbound::Inventory(o), &mut wire).unwrap();
let out = enc.out_mut().split().freeze();
match super::super::SWING_PACKET_ID {
Some(swing) => {
assert_eq!(&out[..3], &[2, swing as u8, 0]);
assert_eq!(out[4], sb::id::WINDOW_CLICK as u8);
}
None => assert_eq!(out[1], sb::id::WINDOW_CLICK as u8),
}
}
#[test]
fn transfer_handshake_has_the_transfer_intent() {
let mut enc = FrameEncoder::new();
Marker::write_transfer_handshake(&mut enc, "example.org", 25566).unwrap();
let out = enc.out_mut().split().freeze();
let host = b"example.org";
let mut want = vec![0x00];
let mut v = BytesMut::new();
v.put_varint(<Marker as ghast_protocol::Version>::PROTOCOL);
want.extend_from_slice(&v);
want.push(host.len() as u8);
want.extend_from_slice(host);
want.extend_from_slice(&25566u16.to_be_bytes());
want.push(3);
assert_eq!(out[0] as usize, want.len());
assert_eq!(&out[1..], &want[..]);
}
#[test]
fn chat_rendering() {
assert_eq!(
render_chat(chat_pattern("minecraft:chat"), "Steve", "hi", ""),
"<Steve> hi"
);
assert_eq!(
render_chat(chat_pattern("minecraft:say_command"), "Server", "%2 x", ""),
"[Server] %2 x"
);
}
}