valence/src/client.rs

1154 lines
42 KiB
Rust
Raw Normal View History

2022-06-25 09:11:15 +10:00
/// Contains the [`Event`] enum and related data types.
mod event;
2022-07-03 04:22:28 +10:00
use std::collections::{HashSet, VecDeque};
2022-04-29 17:48:41 +10:00
use std::iter::FusedIterator;
2022-06-30 14:33:42 +10:00
use std::time::Duration;
2022-04-15 07:55:45 +10:00
2022-06-25 09:11:15 +10:00
pub use event::*;
2022-04-15 07:55:45 +10:00
use flume::{Receiver, Sender, TrySendError};
2022-04-29 17:48:41 +10:00
use rayon::iter::ParallelIterator;
use uuid::Uuid;
use vek::Vec3;
2022-04-15 07:55:45 +10:00
2022-06-10 13:26:21 +10:00
use crate::biome::{Biome, BiomeGrassColorModifier, BiomePrecipitation};
use crate::dimension::{Dimension, DimensionEffects};
2022-06-30 06:00:41 +10:00
use crate::entity::types::Player;
2022-05-17 19:58:43 +10:00
use crate::entity::{velocity_to_packet_units, EntityType};
use crate::player_textures::SignedPlayerTextures;
use crate::protocol::packets::play::c2s::{C2sPlayPacket, DiggingStatus, InteractType};
2022-07-04 16:17:51 +10:00
pub use crate::protocol::packets::play::s2c::EntityEventStatus as EntityEvent;
use crate::protocol::packets::play::s2c::{
2022-07-01 07:18:29 +10:00
Biome as BiomeRegistryBiome, BiomeAdditionsSound, BiomeEffects, BiomeMoodSound, BiomeMusic,
2022-07-02 12:18:59 +10:00
BiomeParticle, BiomeParticleOptions, BiomeProperty, BiomeRegistry, BlockChangeAck, ChatType,
ChatTypeChat, ChatTypeNarration, ChatTypeRegistry, ChatTypeRegistryEntry, DimensionType,
2022-07-04 16:17:51 +10:00
DimensionTypeRegistry, DimensionTypeRegistryEntry, Disconnect,
EntityEvent as EntityEventPacket, ForgetLevelChunk, GameEvent, GameEventReason, KeepAlive,
Login, MoveEntityPosition, MoveEntityPositionAndRotation, MoveEntityRotation, PlayerPosition,
PlayerPositionFlags, RegistryCodec, RemoveEntities, Respawn, RotateHead, S2cPlayPacket,
SetChunkCacheCenter, SetChunkCacheRadius, SetEntityMetadata, SetEntityMotion, SpawnPosition,
SystemChat, TeleportEntity,
2022-04-15 07:55:45 +10:00
};
use crate::protocol::{BoundedInt, ByteAngle, Nbt, RawBytes, VarInt};
2022-06-10 13:26:21 +10:00
use crate::server::C2sPacketChannels;
2022-04-29 17:48:41 +10:00
use crate::slotmap::{Key, SlotMap};
2022-04-15 07:55:45 +10:00
use crate::util::{chunks_in_view_distance, is_chunk_in_view_distance};
2022-05-17 19:58:43 +10:00
use crate::{
ident, BlockPos, ChunkPos, DimensionId, Entities, EntityId, NewClientData, SharedServer, Text,
Ticks, WorldId, Worlds, LIBRARY_NAMESPACE,
2022-05-17 19:58:43 +10:00
};
2022-04-15 07:55:45 +10:00
pub struct Clients {
2022-04-29 17:48:41 +10:00
sm: SlotMap<Client>,
}
2022-04-15 07:55:45 +10:00
impl Clients {
2022-04-29 17:48:41 +10:00
pub(crate) fn new() -> Self {
Self { sm: SlotMap::new() }
2022-04-15 07:55:45 +10:00
}
pub(crate) fn insert(&mut self, client: Client) -> (ClientId, &mut Client) {
let (id, client) = self.sm.insert(client);
(ClientId(id), client)
2022-04-15 07:55:45 +10:00
}
pub fn delete(&mut self, client: ClientId) -> bool {
self.sm.remove(client.0).is_some()
2022-04-29 17:48:41 +10:00
}
pub fn retain(&mut self, mut f: impl FnMut(ClientId, &mut Client) -> bool) {
self.sm.retain(|k, v| f(ClientId(k), v))
2022-04-29 17:48:41 +10:00
}
pub fn count(&self) -> usize {
self.sm.len()
2022-04-29 17:48:41 +10:00
}
pub fn get(&self, client: ClientId) -> Option<&Client> {
self.sm.get(client.0)
2022-04-29 17:48:41 +10:00
}
pub fn get_mut(&mut self, client: ClientId) -> Option<&mut Client> {
self.sm.get_mut(client.0)
2022-04-29 17:48:41 +10:00
}
pub fn iter(&self) -> impl FusedIterator<Item = (ClientId, &Client)> + Clone + '_ {
self.sm.iter().map(|(k, v)| (ClientId(k), v))
2022-04-29 17:48:41 +10:00
}
pub fn iter_mut(&mut self) -> impl FusedIterator<Item = (ClientId, &mut Client)> + '_ {
self.sm.iter_mut().map(|(k, v)| (ClientId(k), v))
}
pub fn par_iter(&self) -> impl ParallelIterator<Item = (ClientId, &Client)> + Clone + '_ {
self.sm.par_iter().map(|(k, v)| (ClientId(k), v))
2022-04-15 07:55:45 +10:00
}
pub fn par_iter_mut(&mut self) -> impl ParallelIterator<Item = (ClientId, &mut Client)> + '_ {
self.sm.par_iter_mut().map(|(k, v)| (ClientId(k), v))
}
}
2022-07-04 11:02:00 +10:00
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Debug)]
2022-04-29 17:48:41 +10:00
pub struct ClientId(Key);
2022-07-04 11:02:00 +10:00
impl ClientId {
pub const NULL: Self = Self(Key::NULL);
}
2022-04-15 07:55:45 +10:00
/// Represents a client connected to the server after logging in.
pub struct Client {
/// Setting this to `None` disconnects the client.
2022-06-10 13:26:21 +10:00
send: Option<Sender<S2cPlayPacket>>,
recv: Receiver<C2sPlayPacket>,
2022-04-15 07:55:45 +10:00
/// The tick this client was created.
created_tick: Ticks,
uuid: Uuid,
username: String,
textures: Option<SignedPlayerTextures>,
2022-07-04 11:45:11 +10:00
world: WorldId,
spawn: bool,
2022-04-15 07:55:45 +10:00
on_ground: bool,
new_position: Vec3<f64>,
old_position: Vec3<f64>,
2022-04-15 07:55:45 +10:00
/// Measured in degrees
yaw: f32,
/// Measured in degrees
pitch: f32,
/// If any of position, yaw, or pitch were modified by the
/// user this tick.
teleported_this_tick: bool,
/// Counts up as teleports are made.
teleport_id_counter: u32,
/// The number of pending client teleports that have yet to receive a
/// confirmation. Inbound client position packets are ignored while this
/// is nonzero.
pending_teleports: u32,
spawn_position: BlockPos,
spawn_position_yaw: f32,
/// If spawn_position or spawn_position_yaw were modified this tick.
modified_spawn_position: bool,
death_location: Option<(DimensionId, BlockPos)>,
2022-07-04 16:17:51 +10:00
events: VecDeque<ClientEvent>,
2022-04-15 07:55:45 +10:00
/// The ID of the last keepalive sent.
last_keepalive_id: i64,
/// If the last sent keepalive got a response.
got_keepalive: bool,
new_max_view_distance: u8,
2022-04-29 17:48:41 +10:00
old_max_view_distance: u8,
2022-04-15 07:55:45 +10:00
/// Entities that were visible to this client at the end of the last tick.
/// This is used to determine what entity create/destroy packets should be
/// sent.
loaded_entities: HashSet<EntityId>,
loaded_chunks: HashSet<ChunkPos>,
2022-04-15 07:55:45 +10:00
new_game_mode: GameMode,
2022-04-29 17:48:41 +10:00
old_game_mode: GameMode,
2022-04-15 07:55:45 +10:00
settings: Option<Settings>,
2022-06-25 09:11:15 +10:00
dug_blocks: Vec<i32>,
2022-07-02 12:18:59 +10:00
msgs_to_send: Vec<Text>,
entity_events: Vec<EntityEvent>,
2022-06-30 06:00:41 +10:00
/// The metadata for the client's own player entity.
player_meta: Player,
2022-04-15 07:55:45 +10:00
}
impl Client {
pub(crate) fn new(
2022-06-10 13:26:21 +10:00
packet_channels: C2sPacketChannels,
server: &SharedServer,
ncd: NewClientData,
2022-04-15 07:55:45 +10:00
) -> Self {
let (send, recv) = packet_channels;
Self {
send: Some(send),
recv,
created_tick: server.current_tick(),
uuid: ncd.uuid,
username: ncd.username,
textures: ncd.textures,
2022-07-04 11:45:11 +10:00
world: WorldId::default(),
spawn: false,
2022-04-15 07:55:45 +10:00
on_ground: false,
new_position: Vec3::default(),
old_position: Vec3::default(),
2022-04-15 07:55:45 +10:00
yaw: 0.0,
pitch: 0.0,
teleported_this_tick: false,
teleport_id_counter: 0,
pending_teleports: 0,
spawn_position: BlockPos::default(),
spawn_position_yaw: 0.0,
modified_spawn_position: true,
death_location: None,
2022-07-03 04:22:28 +10:00
events: VecDeque::new(),
2022-04-15 07:55:45 +10:00
last_keepalive_id: 0,
got_keepalive: true,
new_max_view_distance: 16,
2022-04-29 17:48:41 +10:00
old_max_view_distance: 0,
2022-04-15 07:55:45 +10:00
loaded_entities: HashSet::new(),
loaded_chunks: HashSet::new(),
2022-04-15 07:55:45 +10:00
new_game_mode: GameMode::Survival,
2022-04-29 17:48:41 +10:00
old_game_mode: GameMode::Survival,
2022-04-15 07:55:45 +10:00
settings: None,
2022-06-25 09:11:15 +10:00
dug_blocks: Vec::new(),
2022-06-30 14:33:42 +10:00
msgs_to_send: Vec::new(),
2022-07-04 16:17:51 +10:00
entity_events: Vec::new(),
2022-06-30 06:00:41 +10:00
player_meta: Player::new(),
2022-04-15 07:55:45 +10:00
}
}
pub fn created_tick(&self) -> Ticks {
self.created_tick
}
pub fn uuid(&self) -> Uuid {
self.uuid
}
2022-04-15 07:55:45 +10:00
pub fn username(&self) -> &str {
&self.username
}
pub fn textures(&self) -> Option<&SignedPlayerTextures> {
self.textures.as_ref()
}
2022-07-04 11:02:00 +10:00
pub fn world(&self) -> WorldId {
2022-07-04 11:45:11 +10:00
self.world
}
2022-07-04 11:45:11 +10:00
pub fn spawn(&mut self, world: WorldId) {
self.world = world;
self.spawn = true;
}
2022-07-02 12:18:59 +10:00
/// Sends a system message to the player.
pub fn send_message(&mut self, msg: impl Into<Text>) {
self.msgs_to_send.push(msg.into());
2022-06-30 14:33:42 +10:00
}
pub fn position(&self) -> Vec3<f64> {
2022-04-15 07:55:45 +10:00
self.new_position
}
pub fn teleport(&mut self, pos: impl Into<Vec3<f64>>, yaw: f32, pitch: f32) {
self.new_position = pos.into();
self.yaw = yaw;
self.pitch = pitch;
if !self.teleported_this_tick {
self.teleported_this_tick = true;
self.pending_teleports = match self.pending_teleports.checked_add(1) {
Some(n) => n,
None => {
2022-07-03 06:41:45 +10:00
log::warn!("too many pending teleports for {}", self.username());
self.disconnect_no_reason();
return;
}
};
self.teleport_id_counter = self.teleport_id_counter.wrapping_add(1);
}
}
2022-04-15 07:55:45 +10:00
pub fn yaw(&self) -> f32 {
self.yaw
}
pub fn pitch(&self) -> f32 {
self.pitch
}
/// Gets the spawn position. The client will see regular compasses point at
/// the returned position.
pub fn spawn_position(&self) -> BlockPos {
self.spawn_position
}
/// Sets the spawn position. The client will see regular compasses point at
/// the provided position.
pub fn set_spawn_position(&mut self, pos: impl Into<BlockPos>, yaw_degrees: f32) {
let pos = pos.into();
if pos != self.spawn_position || yaw_degrees != self.spawn_position_yaw {
self.spawn_position = pos;
self.spawn_position_yaw = yaw_degrees;
self.modified_spawn_position = true;
}
}
/// Gets the last death location. The client will see recovery compasses
/// point at the returned position. If the client's current dimension
/// differs from the returned dimension or the location is `None` then the
/// compass will spin randomly.
pub fn death_location(&self) -> Option<(DimensionId, BlockPos)> {
self.death_location
}
/// Sets the last death location. The client will see recovery compasses
/// point at the provided position. If the client's current dimension
/// differs from the provided dimension or the location is `None` then the
/// compass will spin randomly.
///
/// Changes to the last death location take effect when the client
/// (re)spawns.
pub fn set_death_location(&mut self, location: Option<(DimensionId, BlockPos)>) {
self.death_location = location;
}
pub fn game_mode(&self) -> GameMode {
self.new_game_mode
}
pub fn set_game_mode(&mut self, new_game_mode: GameMode) {
self.new_game_mode = new_game_mode;
}
pub fn on_ground(&self) -> bool {
self.on_ground
}
pub fn is_disconnected(&self) -> bool {
self.send.is_none()
}
2022-07-04 16:17:51 +10:00
pub fn pop_event(&mut self) -> Option<ClientEvent> {
2022-07-03 04:22:28 +10:00
self.events.pop_front()
}
pub fn push_entity_event(&mut self, event: EntityEvent) {
self.entity_events.push(event);
2022-07-04 16:17:51 +10:00
}
2022-06-20 01:40:37 +10:00
/// The current view distance of this client measured in chunks.
pub fn view_distance(&self) -> u8 {
self.settings
.as_ref()
.map_or(2, |s| s.view_distance)
.min(self.max_view_distance())
}
pub fn max_view_distance(&self) -> u8 {
self.new_max_view_distance
}
/// The new view distance is clamped to `2..=32`.
pub fn set_max_view_distance(&mut self, dist: u8) {
self.new_max_view_distance = dist.clamp(2, 32);
}
pub fn settings(&self) -> Option<&Settings> {
self.settings.as_ref()
2022-04-15 07:55:45 +10:00
}
pub fn disconnect(&mut self, reason: impl Into<Text>) {
if self.send.is_some() {
2022-04-15 07:55:45 +10:00
let txt = reason.into();
log::info!("disconnecting client '{}': \"{txt}\"", self.username);
2022-04-15 07:55:45 +10:00
self.send_packet(Disconnect { reason: txt });
self.send = None;
2022-04-15 07:55:45 +10:00
}
}
pub fn disconnect_no_reason(&mut self) {
if self.send.is_some() {
log::info!("disconnecting client '{}'", self.username);
self.send = None;
2022-04-15 07:55:45 +10:00
}
}
2022-06-30 06:00:41 +10:00
pub fn meta(&self) -> &Player {
&self.player_meta
}
pub fn meta_mut(&mut self) -> &mut Player {
&mut self.player_meta
}
/// Attempts to enqueue a play packet to be sent to this client. The client
/// is disconnected if the clientbound packet buffer is full.
pub(crate) fn send_packet(&mut self, packet: impl Into<S2cPlayPacket>) {
send_packet(&mut self.send, packet);
2022-04-29 17:48:41 +10:00
}
2022-06-25 09:11:15 +10:00
pub(crate) fn handle_serverbound_packets(&mut self, entities: &Entities) {
self.events.clear();
2022-06-25 09:11:15 +10:00
for _ in 0..self.recv.len() {
self.handle_serverbound_packet(entities, self.recv.try_recv().unwrap());
}
}
fn handle_serverbound_packet(&mut self, entities: &Entities, pkt: C2sPlayPacket) {
fn handle_movement_packet(
client: &mut Client,
_vehicle: bool,
new_position: Vec3<f64>,
new_yaw: f32,
new_pitch: f32,
new_on_ground: bool,
) {
if client.pending_teleports == 0 {
// TODO: validate movement using swept AABB collision with the blocks.
// TODO: validate that the client is actually inside/outside the vehicle?
2022-07-04 16:17:51 +10:00
let event = ClientEvent::Movement {
2022-06-25 09:11:15 +10:00
position: client.new_position,
yaw: client.yaw,
pitch: client.pitch,
on_ground: client.on_ground,
};
client.new_position = new_position;
client.yaw = new_yaw;
client.pitch = new_pitch;
client.on_ground = new_on_ground;
2022-07-03 04:22:28 +10:00
client.events.push_back(event);
2022-06-25 09:11:15 +10:00
}
}
match pkt {
2022-07-01 07:18:29 +10:00
C2sPlayPacket::AcceptTeleportation(p) => {
if self.pending_teleports == 0 {
2022-07-03 06:41:45 +10:00
log::warn!("unexpected teleport confirmation from {}", self.username());
self.disconnect_no_reason();
2022-06-25 09:11:15 +10:00
return;
}
let got = p.teleport_id.0 as u32;
let expected = self
2022-06-25 09:11:15 +10:00
.teleport_id_counter
.wrapping_sub(self.pending_teleports);
2022-06-25 09:11:15 +10:00
if got == expected {
self.pending_teleports -= 1;
2022-06-25 09:11:15 +10:00
} else {
2022-07-03 06:41:45 +10:00
log::warn!(
"unexpected teleport ID from {} (expected {expected}, got {got})",
self.username()
);
self.disconnect_no_reason();
return;
2022-06-25 09:11:15 +10:00
}
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::BlockEntityTagQuery(_) => {}
C2sPlayPacket::ChangeDifficulty(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::ChatCommand(_) => {}
2022-07-04 16:17:51 +10:00
C2sPlayPacket::Chat(p) => self.events.push_back(ClientEvent::ChatMessage {
2022-06-30 14:33:42 +10:00
message: p.message.0,
timestamp: Duration::from_millis(p.timestamp),
}),
2022-06-25 09:11:15 +10:00
C2sPlayPacket::ChatPreview(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::ClientCommand(_) => {}
C2sPlayPacket::ClientInformation(p) => {
let old = self.settings.replace(Settings {
2022-06-25 09:11:15 +10:00
locale: p.locale.0,
view_distance: p.view_distance.0,
chat_mode: p.chat_mode,
chat_colors: p.chat_colors,
main_hand: p.main_hand,
displayed_skin_parts: p.displayed_skin_parts,
allow_server_listings: p.allow_server_listings,
});
2022-07-04 16:17:51 +10:00
self.events.push_back(ClientEvent::SettingsChanged(old));
2022-06-25 09:11:15 +10:00
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::CommandSuggestion(_) => {}
C2sPlayPacket::ContainerButtonClick(_) => {}
C2sPlayPacket::ContainerClose(_) => {}
C2sPlayPacket::CustomPayload(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::EditBook(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::EntityTagQuery(_) => {}
C2sPlayPacket::Interact(p) => {
2022-06-25 09:11:15 +10:00
if let Some(id) = entities.get_with_network_id(p.entity_id.0) {
// TODO: verify that the client has line of sight to the targeted entity and
// that the distance is <=4 blocks.
2022-07-04 16:17:51 +10:00
self.events.push_back(ClientEvent::InteractWithEntity {
2022-06-25 09:11:15 +10:00
id,
sneaking: p.sneaking,
typ: match p.typ {
InteractType::Interact(hand) => InteractWithEntity::Interact(hand),
InteractType::Attack => InteractWithEntity::Attack,
InteractType::InteractAt((target, hand)) => {
InteractWithEntity::InteractAt { target, hand }
}
},
});
}
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::JigsawGenerate(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::KeepAlive(p) => {
let last_keepalive_id = self.last_keepalive_id;
if self.got_keepalive {
log::warn!("unexpected keepalive from player {}", self.username());
self.disconnect_no_reason();
2022-06-25 09:11:15 +10:00
} else if p.id != last_keepalive_id {
log::warn!(
"keepalive ids for player {} don't match (expected {}, got {})",
self.username(),
last_keepalive_id,
p.id
);
self.disconnect_no_reason();
2022-06-25 09:11:15 +10:00
} else {
self.got_keepalive = true;
2022-06-25 09:11:15 +10:00
}
}
C2sPlayPacket::LockDifficulty(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::MovePlayerPosition(p) => {
handle_movement_packet(self, false, p.position, self.yaw, self.pitch, p.on_ground)
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::MovePlayerPositionAndRotation(p) => {
handle_movement_packet(self, false, p.position, p.yaw, p.pitch, p.on_ground)
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::MovePlayerRotation(p) => {
handle_movement_packet(self, false, self.new_position, p.yaw, p.pitch, p.on_ground)
2022-06-25 09:11:15 +10:00
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::MovePlayerStatusOnly(p) => handle_movement_packet(
self,
2022-06-25 09:11:15 +10:00
false,
self.new_position,
self.yaw,
self.pitch,
2022-06-25 09:11:15 +10:00
p.on_ground,
),
2022-07-01 07:18:29 +10:00
C2sPlayPacket::MoveVehicle(p) => {
handle_movement_packet(self, true, p.position, p.yaw, p.pitch, self.on_ground);
2022-06-25 09:11:15 +10:00
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::PaddleBoat(p) => {
2022-07-04 16:17:51 +10:00
self.events.push_back(ClientEvent::SteerBoat {
2022-06-25 09:11:15 +10:00
left_paddle_turning: p.left_paddle_turning,
right_paddle_turning: p.right_paddle_turning,
});
}
C2sPlayPacket::PickItem(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::PlaceRecipe(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::PlayerAbilities(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::PlayerAction(p) => {
2022-06-25 09:11:15 +10:00
// TODO: verify dug block is within the correct distance from the client.
// TODO: verify that the broken block is allowed to be broken?
if p.sequence.0 != 0 {
self.dug_blocks.push(p.sequence.0);
2022-06-25 09:11:15 +10:00
}
2022-07-03 04:22:28 +10:00
self.events.push_back(match p.status {
2022-07-04 16:17:51 +10:00
DiggingStatus::StartedDigging => ClientEvent::Digging(Digging {
2022-06-25 09:11:15 +10:00
status: event::DiggingStatus::Start,
position: p.location,
face: p.face,
}),
2022-07-04 16:17:51 +10:00
DiggingStatus::CancelledDigging => ClientEvent::Digging(Digging {
2022-06-25 09:11:15 +10:00
status: event::DiggingStatus::Cancel,
position: p.location,
face: p.face,
}),
2022-07-04 16:17:51 +10:00
DiggingStatus::FinishedDigging => ClientEvent::Digging(Digging {
2022-06-25 09:11:15 +10:00
status: event::DiggingStatus::Finish,
position: p.location,
face: p.face,
}),
DiggingStatus::DropItemStack => return,
DiggingStatus::DropItem => return,
DiggingStatus::ShootArrowOrFinishEating => return,
DiggingStatus::SwapItemInHand => return,
});
}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::PlayerCommand(_) => {}
C2sPlayPacket::PlayerInput(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::Pong(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::RecipeBookChangeSettings(_) => {}
C2sPlayPacket::RecipeBookSeenRecipe(_) => {}
C2sPlayPacket::RenameItem(_) => {}
C2sPlayPacket::ResourcePack(_) => {}
C2sPlayPacket::SeenAdvancements(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::SelectTrade(_) => {}
2022-07-01 07:18:29 +10:00
C2sPlayPacket::SetBeacon(_) => {}
C2sPlayPacket::SetCarriedItem(_) => {}
C2sPlayPacket::SetCommandBlock(_) => {}
C2sPlayPacket::SetCommandBlockMinecart(_) => {}
C2sPlayPacket::SetCreativeModeSlot(_) => {}
C2sPlayPacket::SetJigsawBlock(_) => {}
C2sPlayPacket::SetStructureBlock(_) => {}
C2sPlayPacket::SignUpdate(_) => {}
2022-07-04 16:17:51 +10:00
C2sPlayPacket::Swing(p) => self.events.push_back(ClientEvent::ArmSwing(p.hand)),
2022-07-01 07:18:29 +10:00
C2sPlayPacket::TeleportToEntity(_) => {}
C2sPlayPacket::UseItemOn(_) => {}
2022-06-25 09:11:15 +10:00
C2sPlayPacket::UseItem(_) => {}
}
}
pub(crate) fn update(&mut self, shared: &SharedServer, entities: &Entities, worlds: &Worlds) {
2022-04-29 17:48:41 +10:00
// Mark the client as disconnected when appropriate.
if self.recv.is_disconnected() || self.send.as_ref().map_or(true, |s| s.is_disconnected()) {
self.send = None;
2022-04-29 17:48:41 +10:00
return;
2022-04-15 07:55:45 +10:00
}
2022-07-04 11:45:11 +10:00
let world = match worlds.get(self.world) {
Some(world) => world,
None => {
log::warn!(
"client {} is in an invalid world and must be disconnected",
self.username()
);
self.disconnect_no_reason();
return;
}
};
let current_tick = shared.current_tick();
2022-04-15 07:55:45 +10:00
2022-04-29 17:48:41 +10:00
// Send the join game packet and other initial packets. We defer this until now
// so that the user can set the client's location, game mode, etc.
2022-05-17 19:58:43 +10:00
if self.created_tick == current_tick {
world
.meta
.player_list()
.initial_packets(|pkt| self.send_packet(pkt));
2022-07-04 11:45:11 +10:00
let mut dimension_names: Vec<_> = shared
.dimensions()
.map(|(id, _)| ident!("{LIBRARY_NAMESPACE}:dimension_{}", id.0))
.collect();
dimension_names.push(ident!("{LIBRARY_NAMESPACE}:dummy_dimension"));
2022-07-01 07:18:29 +10:00
self.send_packet(Login {
entity_id: 0, // EntityId 0 is reserved for clients.
is_hardcore: false, // TODO
2022-04-15 07:55:45 +10:00
gamemode: self.new_game_mode,
previous_gamemode: self.old_game_mode,
2022-07-04 11:45:11 +10:00
dimension_names,
registry_codec: Nbt(make_dimension_codec(shared)),
dimension_type_name: ident!(
"{LIBRARY_NAMESPACE}:dimension_type_{}",
world.meta.dimension().0
),
dimension_name: ident!(
"{LIBRARY_NAMESPACE}:dimension_{}",
world.meta.dimension().0
),
2022-04-15 07:55:45 +10:00
hashed_seed: 0,
max_players: VarInt(0),
view_distance: BoundedInt(VarInt(self.new_max_view_distance as i32)),
simulation_distance: VarInt(16),
reduced_debug_info: false,
enable_respawn_screen: false,
2022-06-22 05:26:28 +10:00
is_debug: false,
is_flat: world.meta.is_flat(),
last_death_location: self
.death_location
.map(|(id, pos)| (ident!("{LIBRARY_NAMESPACE}:dimension_{}", id.0), pos)),
2022-04-15 07:55:45 +10:00
});
self.teleport(self.position(), self.yaw(), self.pitch());
2022-06-28 10:52:23 +10:00
} else {
2022-07-04 11:45:11 +10:00
if self.spawn {
self.loaded_entities.clear();
self.loaded_chunks.clear();
2022-07-04 10:32:05 +10:00
// TODO: clear player list.
2022-07-04 11:45:11 +10:00
// Client bug workaround: send the client to a dummy dimension first.
self.send_packet(Respawn {
dimension_type_name: ident!("{LIBRARY_NAMESPACE}:dimension_type_0"),
dimension_name: ident!("{LIBRARY_NAMESPACE}:dummy_dimension"),
hashed_seed: 0,
game_mode: self.game_mode(),
previous_game_mode: self.game_mode(),
is_debug: false,
is_flat: false,
copy_metadata: true,
last_death_location: None,
});
2022-07-04 10:32:05 +10:00
self.send_packet(Respawn {
dimension_type_name: ident!(
"{LIBRARY_NAMESPACE}:dimension_type_{}",
world.meta.dimension().0
),
dimension_name: ident!(
"{LIBRARY_NAMESPACE}:dimension_{}",
world.meta.dimension().0
),
hashed_seed: 0,
game_mode: self.game_mode(),
previous_game_mode: self.game_mode(),
is_debug: false,
is_flat: world.meta.is_flat(),
copy_metadata: true,
last_death_location: self
.death_location
.map(|(id, pos)| (ident!("{LIBRARY_NAMESPACE}:dimension_{}", id.0), pos)),
});
self.teleport(self.position(), self.yaw(), self.pitch());
}
if self.old_game_mode != self.new_game_mode {
self.old_game_mode = self.new_game_mode;
2022-07-01 07:18:29 +10:00
self.send_packet(GameEvent {
reason: GameEventReason::ChangeGameMode,
value: self.new_game_mode as i32 as f32,
2022-06-28 10:52:23 +10:00
});
}
world
.meta
.player_list()
.diff_packets(|pkt| self.send_packet(pkt));
2022-04-15 07:55:45 +10:00
}
2022-04-29 17:48:41 +10:00
// Update the players spawn position (compass position)
if self.modified_spawn_position {
self.modified_spawn_position = false;
2022-04-15 07:55:45 +10:00
self.send_packet(SpawnPosition {
location: self.spawn_position,
angle: self.spawn_position_yaw,
})
}
// Update view distance fog on the client if necessary.
if self.old_max_view_distance != self.new_max_view_distance {
self.old_max_view_distance = self.new_max_view_distance;
if self.created_tick != current_tick {
2022-07-01 07:18:29 +10:00
self.send_packet(SetChunkCacheRadius {
view_distance: BoundedInt(VarInt(self.new_max_view_distance as i32)),
2022-04-15 07:55:45 +10:00
})
}
}
// Check if it's time to send another keepalive.
if current_tick % (shared.tick_rate() * 8) == 0 {
if self.got_keepalive {
2022-04-15 07:55:45 +10:00
let id = rand::random();
2022-06-25 09:11:15 +10:00
self.send_packet(KeepAlive { id });
self.last_keepalive_id = id;
self.got_keepalive = false;
2022-04-15 07:55:45 +10:00
} else {
log::warn!(
"player {} timed out (no keepalive response)",
self.username()
);
self.disconnect_no_reason();
2022-04-15 07:55:45 +10:00
}
}
2022-06-20 01:40:37 +10:00
let view_dist = self.view_distance();
2022-04-15 07:55:45 +10:00
2022-06-25 09:11:15 +10:00
let center = ChunkPos::at(self.new_position.x, self.new_position.z);
2022-04-15 07:55:45 +10:00
// Send the update view position packet if the client changes the chunk section
// they're in.
{
let old_section = self.old_position.map(|n| (n / 16.0).floor() as i32);
let new_section = self.new_position.map(|n| (n / 16.0).floor() as i32);
2022-04-15 07:55:45 +10:00
if old_section != new_section {
2022-07-01 07:18:29 +10:00
self.send_packet(SetChunkCacheCenter {
2022-04-15 07:55:45 +10:00
chunk_x: VarInt(new_section.x),
chunk_z: VarInt(new_section.z),
})
}
}
let dimension = shared.dimension(world.meta.dimension());
2022-06-23 01:06:54 +10:00
// Update existing chunks and unload those outside the view distance. Chunks
// that have been overwritten also need to be unloaded.
self.loaded_chunks.retain(|&pos| {
// The cache stops chunk data packets from needing to be sent when a player
// moves to an adjacent chunk and back to the original.
let cache = 2;
if let Some(chunk) = world.chunks.get(pos) {
if is_chunk_in_view_distance(center, pos, view_dist + cache)
2022-05-17 19:58:43 +10:00
&& chunk.created_tick() != current_tick
{
2022-06-23 01:06:54 +10:00
chunk.block_change_packets(pos, dimension.min_y, |pkt| {
send_packet(&mut self.send, pkt)
2022-06-23 01:06:54 +10:00
});
return true;
2022-04-15 07:55:45 +10:00
}
}
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
ForgetLevelChunk {
chunk_x: pos.x,
chunk_z: pos.z,
},
);
false
2022-04-15 07:55:45 +10:00
});
// Load new chunks within the view distance
for pos in chunks_in_view_distance(center, view_dist) {
if let Some(chunk) = world.chunks.get(pos) {
if self.loaded_chunks.insert(pos) {
self.send_packet(chunk.chunk_data_packet(pos));
2022-06-23 01:06:54 +10:00
chunk.block_change_packets(pos, dimension.min_y, |pkt| self.send_packet(pkt));
2022-04-15 07:55:45 +10:00
}
}
}
2022-06-25 09:11:15 +10:00
// Acknowledge broken blocks.
for seq in self.dug_blocks.drain(..) {
2022-06-25 09:11:15 +10:00
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
BlockChangeAck {
2022-06-25 09:11:15 +10:00
sequence: VarInt(seq),
},
)
}
2022-04-15 07:55:45 +10:00
// This is done after the chunks are loaded so that the "downloading terrain"
// screen is closed at the appropriate time.
if self.teleported_this_tick {
self.teleported_this_tick = false;
2022-07-01 07:18:29 +10:00
self.send_packet(PlayerPosition {
position: self.new_position,
yaw: self.yaw,
pitch: self.pitch,
2022-07-01 07:18:29 +10:00
flags: PlayerPositionFlags::new(false, false, false, false, false),
teleport_id: VarInt((self.teleport_id_counter - 1) as i32),
dismount_vehicle: false,
});
}
2022-07-02 12:18:59 +10:00
for msg in self.msgs_to_send.drain(..) {
send_packet(
&mut self.send,
SystemChat {
chat: msg,
typ: VarInt(0),
},
);
2022-06-30 14:33:42 +10:00
}
let mut entities_to_unload = Vec::new();
// Update all entities that are visible and unload entities that are no
// longer visible.
self.loaded_entities.retain(|&id| {
if let Some(entity) = entities.get(id) {
2022-05-17 19:58:43 +10:00
debug_assert!(entity.typ() != EntityType::Marker);
if self.new_position.distance(entity.position()) <= view_dist as f64 * 16.0 {
2022-05-17 04:53:21 +10:00
if let Some(meta) = entity.updated_metadata_packet(id) {
send_packet(&mut self.send, meta);
2022-05-17 04:53:21 +10:00
}
2022-05-17 19:58:43 +10:00
let position_delta = entity.position() - entity.old_position();
let needs_teleport = position_delta.map(f64::abs).reduce_partial_max() >= 8.0;
let flags = entity.flags();
if entity.position() != entity.old_position()
&& !needs_teleport
&& flags.yaw_or_pitch_modified()
{
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
MoveEntityPositionAndRotation {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
delta: (position_delta * 4096.0).as_(),
yaw: ByteAngle::from_degrees(entity.yaw()),
pitch: ByteAngle::from_degrees(entity.pitch()),
on_ground: entity.on_ground(),
},
);
} else {
if entity.position() != entity.old_position() && !needs_teleport {
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
MoveEntityPosition {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
delta: (position_delta * 4096.0).as_(),
on_ground: entity.on_ground(),
},
);
}
if flags.yaw_or_pitch_modified() {
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
MoveEntityRotation {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
yaw: ByteAngle::from_degrees(entity.yaw()),
pitch: ByteAngle::from_degrees(entity.pitch()),
on_ground: entity.on_ground(),
},
);
}
}
if needs_teleport {
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
TeleportEntity {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
position: entity.position(),
yaw: ByteAngle::from_degrees(entity.yaw()),
pitch: ByteAngle::from_degrees(entity.pitch()),
on_ground: entity.on_ground(),
},
);
}
if flags.velocity_modified() {
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
SetEntityMotion {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
velocity: velocity_to_packet_units(entity.velocity()),
},
);
}
if flags.head_yaw_modified() {
send_packet(
&mut self.send,
2022-07-01 07:18:29 +10:00
RotateHead {
2022-05-17 19:58:43 +10:00
entity_id: VarInt(id.to_network_id()),
head_yaw: ByteAngle::from_degrees(entity.head_yaw()),
},
)
}
for &e in entity.events() {
send_packet(
&mut self.send,
EntityEventPacket {
entity_id: id.to_network_id(),
entity_status: e,
},
);
}
return true;
}
}
entities_to_unload.push(VarInt(id.to_network_id()));
false
});
if !entities_to_unload.is_empty() {
2022-07-01 07:18:29 +10:00
self.send_packet(RemoveEntities {
entities: entities_to_unload,
2022-04-15 07:55:45 +10:00
});
}
2022-06-30 06:00:41 +10:00
// Update the client's own player metadata.
2022-06-30 14:33:42 +10:00
let mut data = Vec::new();
self.player_meta.updated_metadata(&mut data);
2022-06-30 06:00:41 +10:00
2022-06-30 14:33:42 +10:00
if !data.is_empty() {
data.push(0xff);
2022-06-30 06:00:41 +10:00
2022-07-01 07:18:29 +10:00
self.send_packet(SetEntityMetadata {
2022-06-30 14:33:42 +10:00
entity_id: VarInt(0),
metadata: RawBytes(data),
});
2022-06-30 06:00:41 +10:00
}
2022-06-30 14:33:42 +10:00
self.player_meta.clear_modifications();
2022-06-30 06:00:41 +10:00
// Spawn new entities within the view distance.
let pos = self.position();
world.spatial_index.query::<_, _, ()>(
2022-06-20 01:40:37 +10:00
|bb| bb.projected_point(pos).distance(pos) <= view_dist as f64 * 16.0,
|id, _| {
let entity = entities.get(id).unwrap();
if entity.typ() != EntityType::Marker && self.loaded_entities.insert(id) {
self.send_packet(
entity
.spawn_packet(id)
.expect("should not be a marker entity"),
);
2022-06-20 01:40:37 +10:00
if let Some(meta) = entity.initial_metadata_packet(id) {
self.send_packet(meta);
}
for &e in entity.events() {
send_packet(
&mut self.send,
EntityEventPacket {
entity_id: id.to_network_id(),
entity_status: e,
},
);
}
}
None
},
);
// Send entity events for the client's own player entity.
for event in self.entity_events.drain(..) {
send_packet(
&mut self.send,
EntityEventPacket {
entity_id: 0,
entity_status: event,
},
);
2022-07-04 16:17:51 +10:00
}
self.old_position = self.new_position;
2022-07-04 11:45:11 +10:00
self.spawn = false;
2022-04-15 07:55:45 +10:00
}
}
2022-06-10 13:26:21 +10:00
fn send_packet(send_opt: &mut Option<Sender<S2cPlayPacket>>, pkt: impl Into<S2cPlayPacket>) {
2022-04-15 07:55:45 +10:00
if let Some(send) = send_opt {
match send.try_send(pkt.into()) {
Err(TrySendError::Full(_)) => {
log::warn!("max outbound packet capacity reached for client");
*send_opt = None;
}
Err(TrySendError::Disconnected(_)) => {
*send_opt = None;
}
Ok(_) => {}
}
}
}
fn make_dimension_codec(shared: &SharedServer) -> RegistryCodec {
2022-04-15 07:55:45 +10:00
let mut dims = Vec::new();
for (id, dim) in shared.dimensions() {
2022-04-15 07:55:45 +10:00
let id = id.0 as i32;
dims.push(DimensionTypeRegistryEntry {
name: ident!("{LIBRARY_NAMESPACE}:dimension_type_{id}"),
id,
element: to_dimension_registry_item(dim),
})
}
let mut biomes = Vec::new();
for (id, biome) in shared.biomes() {
2022-04-15 07:55:45 +10:00
biomes.push(to_biome_registry_item(biome, id.0 as i32));
}
// The client needs a biome named "minecraft:plains" in the registry to
// connect. This is probably a bug.
//
// If the issue is resolved, just delete this block.
if !biomes.iter().any(|b| b.name == ident!("plains")) {
let biome = Biome::default();
assert_eq!(biome.name, ident!("plains"));
2022-07-03 06:41:45 +10:00
biomes.push(to_biome_registry_item(&biome, biomes.len() as i32));
2022-04-15 07:55:45 +10:00
}
2022-07-03 06:41:45 +10:00
RegistryCodec {
2022-04-15 07:55:45 +10:00
dimension_type_registry: DimensionTypeRegistry {
typ: ident!("dimension_type"),
value: dims,
},
biome_registry: BiomeRegistry {
typ: ident!("worldgen/biome"),
value: biomes,
},
chat_type_registry: ChatTypeRegistry {
typ: ident!("chat_type"),
2022-07-02 12:18:59 +10:00
value: vec![ChatTypeRegistryEntry {
name: ident!("system"),
id: 0,
element: ChatType {
chat: ChatTypeChat {},
narration: ChatTypeNarration {
priority: "system".to_string(),
},
},
}],
},
2022-04-15 07:55:45 +10:00
}
}
fn to_dimension_registry_item(dim: &Dimension) -> DimensionType {
DimensionType {
piglin_safe: true,
has_raids: true,
monster_spawn_light_level: 0,
monster_spawn_block_light_limit: 0,
2022-04-15 07:55:45 +10:00
natural: dim.natural,
ambient_light: dim.ambient_light,
fixed_time: dim.fixed_time.map(|t| t as i64),
infiniburn: "#minecraft:infiniburn_overworld".into(),
respawn_anchor_works: true,
has_skylight: true,
bed_works: true,
effects: match dim.effects {
DimensionEffects::Overworld => ident!("overworld"),
DimensionEffects::TheNether => ident!("the_nether"),
DimensionEffects::TheEnd => ident!("the_end"),
},
min_y: dim.min_y,
height: dim.height,
logical_height: dim.height,
coordinate_scale: 1.0,
ultrawarm: false,
has_ceiling: false,
}
}
fn to_biome_registry_item(biome: &Biome, id: i32) -> BiomeRegistryBiome {
BiomeRegistryBiome {
name: biome.name.clone(),
id,
element: BiomeProperty {
precipitation: match biome.precipitation {
BiomePrecipitation::Rain => "rain",
BiomePrecipitation::Snow => "snow",
BiomePrecipitation::None => "none",
}
.into(),
depth: 0.125,
temperature: 0.8,
scale: 0.05,
downfall: 0.4,
category: "none".into(),
temperature_modifier: None,
effects: BiomeEffects {
sky_color: biome.sky_color as i32,
water_fog_color: biome.water_fog_color as i32,
fog_color: biome.fog_color as i32,
water_color: biome.water_color as i32,
foliage_color: biome.foliage_color.map(|x| x as i32),
2022-07-03 06:41:45 +10:00
grass_color: biome.grass_color.map(|x| x as i32),
2022-04-15 07:55:45 +10:00
grass_color_modifier: match biome.grass_color_modifier {
BiomeGrassColorModifier::Swamp => Some("swamp".into()),
BiomeGrassColorModifier::DarkForest => Some("dark_forest".into()),
BiomeGrassColorModifier::None => None,
},
music: biome.music.as_ref().map(|bm| BiomeMusic {
replace_current_music: bm.replace_current_music,
sound: bm.sound.clone(),
max_delay: bm.max_delay,
min_delay: bm.min_delay,
}),
ambient_sound: biome.ambient_sound.clone(),
additions_sound: biome.additions_sound.as_ref().map(|a| BiomeAdditionsSound {
sound: a.sound.clone(),
tick_chance: a.tick_chance,
}),
mood_sound: biome.mood_sound.as_ref().map(|m| BiomeMoodSound {
sound: m.sound.clone(),
tick_delay: m.tick_delay,
offset: m.offset,
block_search_extent: m.block_search_extent,
}),
},
particle: biome.particle.as_ref().map(|p| BiomeParticle {
probability: p.probability,
options: BiomeParticleOptions { typ: p.typ.clone() },
}),
},
}
}