1
2
Fork 0
mirror of https://github.com/mat-1/azalea.git synced 2025-08-02 14:26:04 +00:00

remove most uses of into_variant

This commit is contained in:
mat 2024-11-27 03:24:00 +00:00
parent 35441c33fa
commit 170ffb07d0
23 changed files with 257 additions and 256 deletions

View file

@ -83,15 +83,14 @@ pub fn handle_attack_event(
swing_arm_event.send(SwingArmEvent {
entity: event.entity,
});
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundInteract {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundInteract {
entity_id: *event.target,
action: s_interact::ActionType::Attack,
using_secondary_action: **sneaking,
}
.into_variant(),
});
},
));
// we can't attack if we're in spectator mode but it still sends the attack
// packet

View file

@ -6,12 +6,15 @@ use std::{
};
use azalea_chat::FormattedText;
use azalea_protocol::packets::game::{
c_disguised_chat::ClientboundDisguisedChat,
c_player_chat::ClientboundPlayerChat,
c_system_chat::ClientboundSystemChat,
s_chat::{LastSeenMessagesUpdate, ServerboundChat},
s_chat_command::ServerboundChatCommand,
use azalea_protocol::packets::{
game::{
c_disguised_chat::ClientboundDisguisedChat,
c_player_chat::ClientboundPlayerChat,
c_system_chat::ClientboundSystemChat,
s_chat::{LastSeenMessagesUpdate, ServerboundChat},
s_chat_command::ServerboundChatCommand,
},
Packet,
};
use bevy_app::{App, Plugin, Update};
use bevy_ecs::{
@ -281,10 +284,7 @@ pub fn handle_send_chat_kind_event(
}
};
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet,
});
send_packet_events.send(SendPacketEvent::new(event.entity, packet));
}
}

View file

@ -159,13 +159,12 @@ pub fn handle_chunk_batch_finished_event(
if let Ok(mut chunk_batch_info) = query.get_mut(event.entity) {
chunk_batch_info.batch_finished(event.batch_size);
let desired_chunks_per_tick = chunk_batch_info.desired_chunks_per_tick();
send_packets.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundChunkBatchReceived {
send_packets.send(SendPacketEvent::new(
event.entity,
ServerboundChunkBatchReceived {
desired_chunks_per_tick,
}
.into_variant(),
});
},
));
}
}
}

View file

@ -30,7 +30,7 @@ use azalea_protocol::{
s_hello::ServerboundHello, s_key::ServerboundKey,
s_login_acknowledged::ServerboundLoginAcknowledged, ClientboundLoginPacket,
},
ClientIntention, ConnectionProtocol, PROTOCOL_VERSION,
ClientIntention, ConnectionProtocol, Packet, PROTOCOL_VERSION,
},
resolver, ServerAddress,
};
@ -349,15 +349,12 @@ impl Client {
JoinError,
> {
// handshake
conn.write(
ServerboundClientIntention {
protocol_version: PROTOCOL_VERSION,
hostname: address.host.clone(),
port: address.port,
intention: ClientIntention::Login,
}
.into_variant(),
)
conn.write(ServerboundClientIntention {
protocol_version: PROTOCOL_VERSION,
hostname: address.host.clone(),
port: address.port,
intention: ClientIntention::Login,
})
.await?;
let mut conn = conn.login();
@ -370,15 +367,12 @@ impl Client {
));
// login
conn.write(
ServerboundHello {
name: account.username.clone(),
// TODO: pretty sure this should generate an offline-mode uuid instead of just
// Uuid::default()
profile_id: account.uuid.unwrap_or_default(),
}
.into_variant(),
)
conn.write(ServerboundHello {
name: account.username.clone(),
// TODO: pretty sure this should generate an offline-mode uuid instead of just
// Uuid::default()
profile_id: account.uuid.unwrap_or_default(),
})
.await?;
let (conn, profile) = loop {
@ -438,13 +432,10 @@ impl Client {
}
}
conn.write(
ServerboundKey {
key_bytes: e.encrypted_public_key,
encrypted_challenge: e.encrypted_challenge,
}
.into_variant(),
)
conn.write(ServerboundKey {
key_bytes: e.encrypted_public_key,
encrypted_challenge: e.encrypted_challenge,
})
.await?;
conn.set_encryption_key(e.secret_key);
@ -458,8 +449,7 @@ impl Client {
"Got profile {:?}. handshake is finished and we're now switching to the configuration state",
p.game_profile
);
conn.write(ServerboundLoginAcknowledged {}.into_variant())
.await?;
conn.write(ServerboundLoginAcknowledged {}).await?;
break (conn.configuration(), p.game_profile);
}
ClientboundLoginPacket::LoginDisconnect(p) => {
@ -489,8 +479,9 @@ impl Client {
/// Write a packet directly to the server.
pub fn write_packet(
&self,
packet: ServerboundGamePacket,
packet: impl Packet<ServerboundGamePacket>,
) -> Result<(), crate::raw_connection::WritePacketError> {
let packet = packet.into_variant();
self.raw_connection_mut(&mut self.ecs.lock())
.write_packet(packet)
}
@ -601,7 +592,7 @@ impl Client {
"Sending client information (already logged in): {:?}",
client_information
);
self.write_packet(azalea_protocol::packets::game::s_client_information::ServerboundClientInformation { information: client_information.clone() }.into_variant())?;
self.write_packet(azalea_protocol::packets::game::s_client_information::ServerboundClientInformation { information: client_information.clone() })?;
}
Ok(())

View file

@ -31,21 +31,19 @@ fn handle_in_configuration_state(
let mut brand_data = Vec::new();
// they don't have to know :)
"vanilla".azalea_write(&mut brand_data).unwrap();
send_packet_events.send(SendConfigurationEvent {
send_packet_events.send(SendConfigurationEvent::new(
entity,
packet: ServerboundCustomPayload {
ServerboundCustomPayload {
identifier: ResourceLocation::new("brand"),
data: brand_data.into(),
}
.into_variant(),
});
},
));
send_packet_events.send(SendConfigurationEvent {
send_packet_events.send(SendConfigurationEvent::new(
entity,
packet: ServerboundClientInformation {
ServerboundClientInformation {
information: client_information.clone(),
}
.into_variant(),
});
},
));
}
}

View file

@ -148,15 +148,14 @@ pub fn handle_block_interact_event(
}
};
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundUseItemOn {
ServerboundUseItemOn {
hand: InteractionHand::MainHand,
block_hit,
sequence: sequence_number.0,
}
.into_variant(),
});
},
));
}
}
@ -302,13 +301,12 @@ pub fn handle_swing_arm_event(
mut send_packet_events: EventWriter<SendPacketEvent>,
) {
for event in events.read() {
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundSwing {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundSwing {
hand: InteractionHand::MainHand,
}
.into_variant(),
});
},
));
}
}

View file

@ -627,13 +627,12 @@ fn handle_container_close_event(
continue;
}
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundContainerClose {
ServerboundContainerClose {
container_id: inventory.id,
}
.into_variant(),
});
},
));
client_side_events.send(ClientSideCloseContainerEvent {
entity: event.entity,
});
@ -695,9 +694,9 @@ pub fn handle_container_click_event(
}
}
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundContainerClick {
ServerboundContainerClick {
container_id: event.window_id,
state_id: inventory.state_id,
slot_num: event.operation.slot_num().map(|n| n as i16).unwrap_or(-999),
@ -705,9 +704,8 @@ pub fn handle_container_click_event(
click_type: event.operation.click_type(),
changed_slots,
carried_item: inventory.carried.clone(),
}
.into_variant(),
});
},
));
}
}
@ -763,12 +761,11 @@ fn handle_set_selected_hotbar_slot_event(
}
inventory.selected_hotbar_slot = event.slot;
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundSetCarriedItem {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundSetCarriedItem {
slot: event.slot as u16,
}
.into_variant(),
});
},
));
}
}

View file

@ -251,17 +251,16 @@ fn handle_start_mining_block_with_direction_event(
{
if mining.is_some() {
// send a packet to stop mining since we just changed target
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundPlayerAction {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundPlayerAction {
action: s_player_action::Action::AbortDestroyBlock,
pos: current_mining_pos
.expect("IsMining is true so MineBlockPos must be present"),
direction: event.direction,
sequence: 0,
}
.into_variant(),
});
},
));
}
let target_block_state = instance
@ -324,16 +323,15 @@ fn handle_start_mining_block_with_direction_event(
});
}
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundPlayerAction {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundPlayerAction {
action: s_player_action::Action::StartDestroyBlock,
pos: event.position,
direction: event.direction,
sequence: **sequence_number,
}
.into_variant(),
});
},
));
}
}
}
@ -494,16 +492,15 @@ pub fn handle_stop_mining_block_event(
let mine_block_pos =
mine_block_pos.expect("IsMining is true so MineBlockPos must be present");
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundPlayerAction {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundPlayerAction {
action: s_player_action::Action::AbortDestroyBlock,
pos: mine_block_pos,
direction: Direction::Down,
sequence: 0,
}
.into_variant(),
});
},
));
commands.entity(event.entity).remove::<Mining>();
**mine_progress = 0.;
mine_block_progress_events.send(MineBlockProgressEvent {
@ -568,16 +565,15 @@ pub fn continue_mining_block(
position: mining.pos,
});
*sequence_number += 1;
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundPlayerAction {
ServerboundPlayerAction {
action: s_player_action::Action::StartDestroyBlock,
pos: mining.pos,
direction: mining.dir,
sequence: **sequence_number,
}
.into_variant(),
});
},
));
swing_arm_events.send(SwingArmEvent { entity });
} else if is_same_mining_target(
mining.pos,
@ -614,16 +610,15 @@ pub fn continue_mining_block(
entity,
position: mining.pos,
});
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundPlayerAction {
ServerboundPlayerAction {
action: s_player_action::Action::StopDestroyBlock,
pos: mining.pos,
direction: mining.dir,
sequence: **sequence_number,
}
.into_variant(),
});
},
));
**mine_progress = 0.;
**mine_ticks = 0.;
**mine_delay = 0;

View file

@ -5,12 +5,15 @@ use azalea_core::tick::GameTick;
use azalea_entity::{metadata::Sprinting, Attributes, Jumping};
use azalea_entity::{InLoadedChunk, LastSentPosition, LookDirection, Physics, Position};
use azalea_physics::{ai_step, PhysicsSet};
use azalea_protocol::packets::game::s_player_command::ServerboundPlayerCommand;
use azalea_protocol::packets::game::{
s_move_player_pos::ServerboundMovePlayerPos,
s_move_player_pos_rot::ServerboundMovePlayerPosRot,
s_move_player_rot::ServerboundMovePlayerRot,
s_move_player_status_only::ServerboundMovePlayerStatusOnly,
use azalea_protocol::packets::game::ServerboundPlayerCommand;
use azalea_protocol::packets::{
game::{
s_move_player_pos::ServerboundMovePlayerPos,
s_move_player_pos_rot::ServerboundMovePlayerPosRot,
s_move_player_rot::ServerboundMovePlayerRot,
s_move_player_status_only::ServerboundMovePlayerStatusOnly,
},
Packet,
};
use azalea_world::{MinecraftEntityId, MoveEntityError};
use bevy_app::{App, Plugin, Update};
@ -244,7 +247,10 @@ pub fn send_position(
};
if let Some(packet) = packet {
send_packet_events.send(SendPacketEvent { entity, packet });
send_packet_events.send(SendPacketEvent {
sent_by: entity,
packet,
});
}
}
}
@ -261,15 +267,14 @@ fn send_sprinting_if_needed(
} else {
azalea_protocol::packets::game::s_player_command::Action::StopSprinting
};
send_packet_events.send(SendPacketEvent {
send_packet_events.send(SendPacketEvent::new(
entity,
packet: ServerboundPlayerCommand {
ServerboundPlayerCommand {
id: **minecraft_entity_id,
action: sprinting_action,
data: 0,
}
.into_variant(),
});
},
));
physics_state.was_sprinting = **sprinting;
}
}

View file

@ -4,8 +4,10 @@ use azalea_entity::indexing::EntityIdIndex;
use azalea_protocol::packets::config::s_finish_configuration::ServerboundFinishConfiguration;
use azalea_protocol::packets::config::s_keep_alive::ServerboundKeepAlive;
use azalea_protocol::packets::config::s_select_known_packs::ServerboundSelectKnownPacks;
use azalea_protocol::packets::config::{self, ClientboundConfigPacket, ServerboundConfigPacket};
use azalea_protocol::packets::ConnectionProtocol;
use azalea_protocol::packets::config::{
self, ClientboundConfigPacket, ServerboundConfigPacket, ServerboundResourcePack,
};
use azalea_protocol::packets::{ConnectionProtocol, Packet};
use azalea_protocol::read::deserialize_packet;
use bevy_ecs::prelude::*;
use bevy_ecs::system::SystemState;
@ -107,7 +109,7 @@ pub fn process_packet_events(ecs: &mut World) {
let mut raw_connection = query.get_mut(player_entity).unwrap();
raw_connection
.write_packet(ServerboundFinishConfiguration {}.into_variant())
.write_packet(ServerboundFinishConfiguration {})
.expect(
"we should be in the right state and encoding this packet shouldn't fail",
);
@ -150,7 +152,7 @@ pub fn process_packet_events(ecs: &mut World) {
id: p.id,
});
raw_connection
.write_packet(ServerboundKeepAlive { id: p.id }.into_variant())
.write_packet(ServerboundKeepAlive { id: p.id })
.unwrap();
}
ClientboundConfigPacket::Ping(p) => {
@ -161,7 +163,7 @@ pub fn process_packet_events(ecs: &mut World) {
let raw_connection = query.get_mut(player_entity).unwrap();
raw_connection
.write_packet(config::s_pong::ServerboundPong { id: p.id }.into_variant())
.write_packet(config::s_pong::ServerboundPong { id: p.id })
.unwrap();
}
ClientboundConfigPacket::ResourcePackPush(p) => {
@ -173,13 +175,10 @@ pub fn process_packet_events(ecs: &mut World) {
// always accept resource pack
raw_connection
.write_packet(
config::s_resource_pack::ServerboundResourcePack {
id: p.id,
action: config::s_resource_pack::Action::Accepted,
}
.into_variant(),
)
.write_packet(ServerboundResourcePack {
id: p.id,
action: config::s_resource_pack::Action::Accepted,
})
.unwrap();
}
ClientboundConfigPacket::ResourcePackPop(_) => {
@ -212,12 +211,9 @@ pub fn process_packet_events(ecs: &mut World) {
// resource pack management isn't implemented
raw_connection
.write_packet(
ServerboundSelectKnownPacks {
known_packs: vec![],
}
.into_variant(),
)
.write_packet(ServerboundSelectKnownPacks {
known_packs: vec![],
})
.unwrap();
}
}
@ -228,16 +224,22 @@ pub fn process_packet_events(ecs: &mut World) {
/// `configuration` state.
#[derive(Event)]
pub struct SendConfigurationEvent {
pub entity: Entity,
pub sent_by: Entity,
pub packet: ServerboundConfigPacket,
}
impl SendConfigurationEvent {
pub fn new(sent_by: Entity, packet: impl Packet<ServerboundConfigPacket>) -> Self {
let packet = packet.into_variant();
Self { sent_by, packet }
}
}
pub fn handle_send_packet_event(
mut send_packet_events: EventReader<SendConfigurationEvent>,
mut query: Query<&mut RawConnection>,
) {
for event in send_packet_events.read() {
if let Ok(raw_connection) = query.get_mut(event.entity) {
if let Ok(raw_connection) = query.get_mut(event.sent_by) {
// debug!("Sending packet: {:?}", event.packet);
if let Err(e) = raw_connection.write_packet(event.packet.clone()) {
error!("Failed to send packet: {e}");

View file

@ -17,12 +17,15 @@ use azalea_entity::{
Physics, PlayerBundle, Position, RelativeEntityUpdate,
};
use azalea_protocol::{
packets::game::{
c_player_combat_kill::ClientboundPlayerCombatKill,
s_accept_teleportation::ServerboundAcceptTeleportation,
s_configuration_acknowledged::ServerboundConfigurationAcknowledged,
s_keep_alive::ServerboundKeepAlive, s_move_player_pos_rot::ServerboundMovePlayerPosRot,
s_pong::ServerboundPong, ClientboundGamePacket, ServerboundGamePacket,
packets::{
game::{
c_player_combat_kill::ClientboundPlayerCombatKill,
s_accept_teleportation::ServerboundAcceptTeleportation,
s_configuration_acknowledged::ServerboundConfigurationAcknowledged,
s_keep_alive::ServerboundKeepAlive, s_move_player_pos_rot::ServerboundMovePlayerPosRot,
s_pong::ServerboundPong, ClientboundGamePacket, ServerboundGamePacket,
},
Packet,
},
read::deserialize_packet,
};
@ -338,10 +341,9 @@ pub fn process_packet_events(ecs: &mut World) {
"Sending client information because login: {:?}",
client_information
);
send_packet_events.send(SendPacketEvent {
entity: player_entity,
packet: azalea_protocol::packets::game::s_client_information::ServerboundClientInformation { information: client_information.clone() }.into_variant(),
});
send_packet_events.send(SendPacketEvent::new(player_entity,
azalea_protocol::packets::game::s_client_information::ServerboundClientInformation { information: client_information.clone() },
));
system_state.apply(ecs);
}
@ -491,13 +493,13 @@ pub fn process_packet_events(ecs: &mut World) {
**position = new_pos;
}
send_packet_events.send(SendPacketEvent {
entity: player_entity,
packet: ServerboundAcceptTeleportation { id: p.id }.into_variant(),
});
send_packet_events.send(SendPacketEvent {
entity: player_entity,
packet: ServerboundMovePlayerPosRot {
send_packet_events.send(SendPacketEvent::new(
player_entity,
ServerboundAcceptTeleportation { id: p.id },
));
send_packet_events.send(SendPacketEvent::new(
player_entity,
ServerboundMovePlayerPosRot {
x: new_pos.x,
y: new_pos.y,
z: new_pos.z,
@ -505,9 +507,8 @@ pub fn process_packet_events(ecs: &mut World) {
x_rot,
// this is always false
on_ground: false,
}
.into_variant(),
});
},
));
}
ClientboundGamePacket::PlayerInfoUpdate(p) => {
debug!("Got player info packet {p:?}");
@ -981,10 +982,10 @@ pub fn process_packet_events(ecs: &mut World) {
entity: player_entity,
id: p.id,
});
send_packet_events.send(SendPacketEvent {
entity: player_entity,
packet: ServerboundKeepAlive { id: p.id }.into_variant(),
});
send_packet_events.send(SendPacketEvent::new(
player_entity,
ServerboundKeepAlive { id: p.id },
));
}
ClientboundGamePacket::RemoveEntities(p) => {
debug!("Got remove entities packet {:?}", p);
@ -1277,10 +1278,10 @@ pub fn process_packet_events(ecs: &mut World) {
SystemState::new(ecs);
let mut send_packet_events = system_state.get_mut(ecs);
send_packet_events.send(SendPacketEvent {
entity: player_entity,
packet: ServerboundPong { id: p.id }.into_variant(),
});
send_packet_events.send(SendPacketEvent::new(
player_entity,
ServerboundPong { id: p.id },
));
}
ClientboundGamePacket::PlaceGhostRecipe(_) => {}
ClientboundGamePacket::PlayerCombatEnd(_) => {}
@ -1421,10 +1422,10 @@ pub fn process_packet_events(ecs: &mut World) {
SystemState::new(ecs);
let (mut commands, mut packet_events) = system_state.get_mut(ecs);
packet_events.send(SendPacketEvent {
entity: player_entity,
packet: ServerboundConfigurationAcknowledged {}.into_variant(),
});
packet_events.send(SendPacketEvent::new(
player_entity,
ServerboundConfigurationAcknowledged {},
));
commands
.entity(player_entity)
@ -1488,16 +1489,22 @@ pub fn process_packet_events(ecs: &mut World) {
/// An event for sending a packet to the server while we're in the `game` state.
#[derive(Event)]
pub struct SendPacketEvent {
pub entity: Entity,
pub sent_by: Entity,
pub packet: ServerboundGamePacket,
}
impl SendPacketEvent {
pub fn new(sent_by: Entity, packet: impl Packet<ServerboundGamePacket>) -> Self {
let packet = packet.into_variant();
Self { sent_by, packet }
}
}
pub fn handle_send_packet_event(
mut send_packet_events: EventReader<SendPacketEvent>,
mut query: Query<&mut RawConnection>,
) {
for event in send_packet_events.read() {
if let Ok(raw_connection) = query.get_mut(event.entity) {
if let Ok(raw_connection) = query.get_mut(event.sent_by) {
// debug!("Sending packet: {:?}", event.packet);
if let Err(e) = raw_connection.write_packet(event.packet.clone()) {
error!("Failed to send packet: {e}");

View file

@ -3,9 +3,12 @@
use std::{collections::HashSet, sync::Arc};
use azalea_protocol::packets::login::{
s_custom_query_answer::ServerboundCustomQueryAnswer, ClientboundLoginPacket,
ServerboundLoginPacket,
use azalea_protocol::packets::{
login::{
s_custom_query_answer::ServerboundCustomQueryAnswer, ClientboundLoginPacket,
ServerboundLoginPacket,
},
Packet,
};
use bevy_ecs::{prelude::*, system::SystemState};
use derive_more::{Deref, DerefMut};
@ -33,6 +36,12 @@ pub struct SendLoginPacketEvent {
pub entity: Entity,
pub packet: ServerboundLoginPacket,
}
impl SendLoginPacketEvent {
pub fn new(entity: Entity, packet: impl Packet<ServerboundLoginPacket>) -> Self {
let packet = packet.into_variant();
Self { entity, packet }
}
}
#[derive(Component)]
pub struct LoginSendPacketQueue {
@ -86,14 +95,13 @@ pub fn process_packet_events(ecs: &mut World) {
}
}
send_packet_events.send(SendLoginPacketEvent {
entity: player_entity,
packet: ServerboundCustomQueryAnswer {
send_packet_events.send(SendLoginPacketEvent::new(
player_entity,
ServerboundCustomQueryAnswer {
transaction_id: p.transaction_id,
data: None,
}
.into_variant(),
});
},
));
}
_ => {}
}

View file

@ -74,21 +74,17 @@ pub async fn ping_server_with_connection(
mut conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket>,
) -> Result<ClientboundStatusResponse, PingError> {
// send the client intention packet and switch to the status state
conn.write(
ServerboundClientIntention {
protocol_version: PROTOCOL_VERSION,
hostname: address.host.clone(),
port: address.port,
intention: ClientIntention::Status,
}
.into_variant(),
)
conn.write(ServerboundClientIntention {
protocol_version: PROTOCOL_VERSION,
hostname: address.host.clone(),
port: address.port,
intention: ClientIntention::Status,
})
.await?;
let mut conn = conn.status();
// send the empty status request packet
conn.write(ServerboundStatusRequest {}.into_variant())
.await?;
conn.write(ServerboundStatusRequest {}).await?;
let packet = conn.read().await?;

View file

@ -3,7 +3,7 @@ use std::sync::Arc;
use azalea_protocol::{
connect::{RawReadConnection, RawWriteConnection},
packets::{ConnectionProtocol, ProtocolPacket},
packets::{ConnectionProtocol, Packet, ProtocolPacket},
read::ReadPacketError,
write::serialize_packet,
};
@ -106,8 +106,9 @@ impl RawConnection {
/// encoding it failed somehow (like it's too big or something).
pub fn write_packet<P: ProtocolPacket + Debug>(
&self,
packet: P,
packet: impl Packet<P>,
) -> Result<(), WritePacketError> {
let packet = packet.into_variant();
let raw_packet = serialize_packet(&packet)?;
self.write_raw_packet(raw_packet)?;

View file

@ -24,12 +24,11 @@ pub fn perform_respawn(
mut send_packets: EventWriter<SendPacketEvent>,
) {
for event in events.read() {
send_packets.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundClientCommand {
send_packets.send(SendPacketEvent::new(
event.entity,
ServerboundClientCommand {
action: s_client_command::Action::PerformRespawn,
}
.into_variant(),
});
},
));
}
}

View file

@ -1,6 +1,6 @@
use std::io::{Cursor, Write};
use azalea_buf::{BufReadError, AzaleaRead, AzaleaReadVar, AzaleaWrite};
use azalea_buf::{AzaleaRead, AzaleaReadVar, AzaleaWrite, BufReadError};
use tracing::debug;
/// A Minecraft gamemode, like survival or creative.

View file

@ -648,8 +648,7 @@ mod tests {
azalea_block::blocks::StoneSlab {
kind: azalea_block::properties::Type::Top,
waterlogged: false,
}
.into(),
},
);
assert!(
block_state.is_some(),
@ -705,8 +704,7 @@ mod tests {
west: azalea_block::properties::WallWest::Low,
up: false,
waterlogged: false,
}
.into(),
},
);
assert!(
block_state.is_some(),
@ -767,8 +765,7 @@ mod tests {
west: azalea_block::properties::WallWest::Low,
up: false,
waterlogged: false,
}
.into(),
},
);
assert!(
block_state.is_some(),

View file

@ -28,11 +28,13 @@ fn as_packet_derive(input: TokenStream, state: proc_macro2::TokenStream) -> Toke
buf: &mut std::io::Cursor<&[u8]>,
) -> Result<#state, azalea_buf::BufReadError> {
use azalea_buf::AzaleaRead;
Ok(Self::azalea_read(buf)?.into_variant())
Ok(crate::packets::Packet::into_variant(Self::azalea_read(buf)?))
}
/// Convert this packet into an variant for the enum of the state and direction.
pub fn into_variant(self) -> #state {
}
impl crate::packets::Packet<#state> for #ident {
fn into_variant(self) -> #state {
#state::#variant_name(self)
}
}
@ -352,6 +354,13 @@ pub fn declare_state_packets(input: TokenStream) -> TokenStream {
})
}
}
impl crate::packets::Packet<#s_state_name> for #s_state_name {
/// No-op, exists so you can pass a packet enum when a Packet<> is expected.
fn into_variant(self) -> #s_state_name {
self
}
}
});
contents.extend(quote! {

View file

@ -108,12 +108,12 @@ async fn handle_connection(stream: TcpStream) -> anyhow::Result<()> {
version: PROXY_VERSION.clone(),
enforces_secure_chat: PROXY_SECURE_CHAT,
}
.into_variant(),
.into(),
)
.await?;
}
ServerboundStatusPacket::PingRequest(p) => {
conn.write(ClientboundPongResponse { time: p.time }.into_variant())
conn.write(ClientboundPongResponse { time: p.time }.into())
.await?;
break;
}
@ -189,10 +189,10 @@ async fn transfer(
// received earlier to the proxy target
let mut outbound_conn: Connection<ClientboundHandshakePacket, ServerboundHandshakePacket> =
Connection::wrap(outbound);
outbound_conn.write(intent.into_variant()).await?;
outbound_conn.write(intent.into()).await?;
let mut outbound_conn = outbound_conn.login();
outbound_conn.write(hello.into_variant()).await?;
outbound_conn.write(hello.into()).await?;
let mut outbound = outbound_conn.unwrap()?;

View file

@ -84,7 +84,7 @@ pub struct WriteConnection<W: ProtocolPacket> {
/// port: resolved_address.port(),
/// intention: ClientIntention::Login,
/// }
/// .into_variant(),
/// .into(),
/// )
/// .await?;
///
@ -96,7 +96,7 @@ pub struct WriteConnection<W: ProtocolPacket> {
/// name: "bot".to_string(),
/// profile_id: uuid::Uuid::nil(),
/// }
/// .into_variant(),
/// .into(),
/// )
/// .await?;
///
@ -111,7 +111,7 @@ pub struct WriteConnection<W: ProtocolPacket> {
/// key_bytes: e.encrypted_public_key,
/// encrypted_challenge: e.encrypted_challenge,
/// }
/// .into_variant(),
/// .into(),
/// )
/// .await?;
/// conn.set_encryption_key(e.secret_key);
@ -241,7 +241,8 @@ where
}
/// Write a packet to the other side of the connection.
pub async fn write(&mut self, packet: W) -> std::io::Result<()> {
pub async fn write(&mut self, packet: impl crate::packets::Packet<W>) -> std::io::Result<()> {
let packet = packet.into_variant();
self.writer.write(packet).await
}
@ -414,7 +415,7 @@ impl Connection<ClientboundLoginPacket, ServerboundLoginPacket> {
/// ServerboundKeyPacket {
/// key_bytes: e.encrypted_public_key,
/// encrypted_challenge: e.encrypted_challenge,
/// }.into_variant()
/// }.into()
/// ).await?;
/// conn.set_encryption_key(e.secret_key);
/// }

View file

@ -122,7 +122,7 @@ mod tests {
name: "test".to_string(),
profile_id: Uuid::nil(),
}
.into_variant();
.into();
let mut stream = Vec::new();
write_packet(&packet, &mut stream, None, &mut None)
.await
@ -146,7 +146,7 @@ mod tests {
name: "test".to_string(),
profile_id: Uuid::nil(),
}
.into_variant();
.into();
let mut stream = Vec::new();
write_packet(&packet, &mut stream, None, &mut None)
.await
@ -170,16 +170,13 @@ mod tests {
async fn test_read_long_compressed_chat() {
let compression_threshold = 256;
let buf = serialize_packet(
&ServerboundChat {
message: "a".repeat(256),
timestamp: 0,
salt: 0,
signature: None,
last_seen_messages: LastSeenMessagesUpdate::default(),
}
.into_variant(),
)
let buf = serialize_packet(&ServerboundChat {
message: "a".repeat(256),
timestamp: 0,
salt: 0,
signature: None,
last_seen_messages: LastSeenMessagesUpdate::default(),
})
.unwrap();
let buf = compression_encoder(&buf, compression_threshold).unwrap();

View file

@ -7,7 +7,7 @@ pub mod status;
use std::io::{Cursor, Write};
use azalea_buf::{AzaleaWrite, AzaleaWriteVar, BufReadError, AzaleaReadVar};
use azalea_buf::{AzaleaReadVar, AzaleaWrite, AzaleaWriteVar, BufReadError};
use crate::read::ReadPacketError;
@ -39,7 +39,7 @@ impl ConnectionProtocol {
}
}
/// An enum of packets for a certain protocol
/// An enum of packets for a certain protocol.
pub trait ProtocolPacket
where
Self: Sized,
@ -52,6 +52,10 @@ where
fn write(&self, buf: &mut impl Write) -> Result<(), std::io::Error>;
}
pub trait Packet<Protocol> {
fn into_variant(self) -> Protocol;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ClientIntention {
Status = 1,

View file

@ -30,21 +30,19 @@ fn accept_resource_pack(
mut send_packet_events: EventWriter<SendPacketEvent>,
) {
for event in events.read() {
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundResourcePack {
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundResourcePack {
id: event.id,
action: s_resource_pack::Action::Accepted,
}
.into_variant(),
});
send_packet_events.send(SendPacketEvent {
entity: event.entity,
packet: ServerboundResourcePack {
},
));
send_packet_events.send(SendPacketEvent::new(
event.entity,
ServerboundResourcePack {
id: event.id,
action: s_resource_pack::Action::SuccessfullyLoaded,
}
.into_variant(),
});
},
));
}
}