Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions examples/basic/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ compression-threshold = 64
# Packet compression level 0..=9 (0 is no compression)
compression-level = 3

# world = "/home/vulae/.local/share/PrismLauncher/instances/Fabulously Optimized 1.21.4/.minecraft/saves/pkmc/"
# NOTE: If you are loading an old world (<=1.19), you will want to optimize it first, or it will not load.
# Worlds > Edit World > Optimize World > Confirm (And wait (-.-)...Zzz)
# If it is a massive world you're optimizing, it's very likely you'll want to create a tmpfs directory for that folder.
# As Minecraft is extremely slow at doing this, and probably will be IO-limited (For some stupid reason, IDK)
world = "/home/vulae/.local/share/PrismLauncher/instances/1.21.5 temp/minecraft/saves/pkmc/"
world = "/home/vulae/.local/share/PrismLauncher/instances/Fabulously Optimized 1.21.5/.minecraft/saves/pkmc/"

view-distance = 32
entity-distance = 256.0
Expand Down
18 changes: 8 additions & 10 deletions examples/basic/src/player.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,23 @@
use std::sync::{Arc, Mutex};

use pkmc_defs::{
block::Block,
packet::{self, play::EntityAnimationType},
particle::Particle,
text_component::TextComponent,
};
use pkmc_generated::registry::EntityType;
use pkmc_generated::{block::Block, registry::EntityType};
use pkmc_server::{
entity_manager::{new_entity_id, Entity, EntityBase, EntityViewer},
entity_manager::{Entity, EntityBase, EntityViewer, new_entity_id},
tab_list::{TabListPlayer, TabListViewer},
world::{anvil::AnvilError, World as _, WorldBlock, WorldViewer},
world::{World as _, WorldViewer, anvil::AnvilError},
};
use pkmc_util::{
Color, Position, UUID, Vec3,
connection::{Connection, ConnectionError},
Color, Position, Vec3, UUID,
};
use thiserror::Error;

use crate::server::{ServerState, REGISTRIES};
use crate::server::{REGISTRIES, ServerState};

const KEEPALIVE_PING_TIME: std::time::Duration = std::time::Duration::from_millis(10000);

Expand Down Expand Up @@ -352,7 +351,7 @@ impl Player {
.get_block(*p)
.ok()
.flatten()
.map(|b| !b.as_block().is_air())
.map(|b| !b.is_air())
.unwrap_or(false)
}) {
//self.connection.send(&packet::play::LevelParticles {
Expand All @@ -368,9 +367,8 @@ impl Player {
// particle_count: 64,
// particle: Particle::ExplosionEmitter,
//})?;
Position::iter_offset(Position::iter_sphere(32.0), position).try_for_each(
|p| world.set_block(p, WorldBlock::Block(Block::air())),
)?;
Position::iter_offset(Position::iter_sphere(48.0), position)
.try_for_each(|p| world.set_block(p, Block::Air))?;
}
}
packet::play::PlayPacket::ChatMessage(chat_message) => {
Expand Down
76 changes: 36 additions & 40 deletions pkmc-defs/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
use std::{collections::BTreeMap, sync::LazyLock};

use pkmc_generated::{block::BLOCKS_REPORT, registry::BlockEntityType};
use pkmc_generated::{
block::{Block, BLOCKS_REPORT},
registry::BlockEntityType,
};
use pkmc_util::{nbt::NBT, IdTable};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Hash, Default)]
#[serde(transparent)]
pub struct BlockProperties(BTreeMap<String, String>);
pub struct DynamicBlockProperties(BTreeMap<String, String>);

impl BlockProperties {
impl DynamicBlockProperties {
pub fn new() -> Self {
Self(BTreeMap::new())
}
Expand Down Expand Up @@ -38,9 +41,9 @@ impl BlockProperties {
}
}

impl<K: ToString, V: ToString, I: IntoIterator<Item = (K, V)>> From<I> for BlockProperties {
impl<K: ToString, V: ToString, I: IntoIterator<Item = (K, V)>> From<I> for DynamicBlockProperties {
fn from(value: I) -> Self {
BlockProperties(
DynamicBlockProperties(
value
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
Expand All @@ -50,15 +53,15 @@ impl<K: ToString, V: ToString, I: IntoIterator<Item = (K, V)>> From<I> for Block
}

#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct Block {
pub struct DynamicBlock {
#[serde(alias = "Name")]
pub name: String,
#[serde(alias = "Properties", default)]
pub properties: BlockProperties,
pub properties: DynamicBlockProperties,
}

impl Block {
pub fn new_p<N: ToString, P: Into<BlockProperties>>(name: N, properties: P) -> Self {
impl DynamicBlock {
pub fn new_p<N: ToString, P: Into<DynamicBlockProperties>>(name: N, properties: P) -> Self {
Self {
name: name.to_string(),
properties: properties.into(),
Expand All @@ -73,78 +76,71 @@ impl Block {
Self::new(&self.name)
}

pub fn air() -> Self {
Self::new("minecraft:air")
}

pub fn is_air(&self) -> bool {
//matches!(
// self.name.as_ref(),
// "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air"
//)
self.id()
.map(pkmc_generated::block::is_air)
.unwrap_or(false)
}

pub fn id(&self) -> Option<i32> {
BLOCKS_TO_IDS.get(self).copied()
}

pub fn id_with_default_fallback(&self) -> Option<i32> {
self.id().or_else(|| self.without_properties().id())
pub fn to_block(&self) -> Option<Block> {
BLOCKS_TO_IDS
.get(self)
.or_else(|| BLOCKS_TO_IDS.get(&self.without_properties()))
.copied()
.and_then(Block::from_id)
}
}

impl Default for Block {
impl Default for DynamicBlock {
fn default() -> Self {
Self::air()
Self::new("minecraft:air")
}
}

#[derive(Debug, Clone, PartialEq)]
pub struct BlockEntity {
pub block: Block,
pub block: DynamicBlock,
pub r#type: BlockEntityType,
pub data: NBT,
}

impl BlockEntity {
pub fn new(block: Block, r#type: BlockEntityType, data: NBT) -> Self {
pub fn new(block: DynamicBlock, r#type: BlockEntityType, data: NBT) -> Self {
Self {
block,
r#type,
data,
}
}

pub fn into_block(self) -> Block {
pub fn into_block(self) -> DynamicBlock {
self.block
}
}

pub static BLOCKS_TO_IDS: LazyLock<IdTable<Block>> = LazyLock::new(|| {
pub static BLOCKS_TO_IDS: LazyLock<IdTable<DynamicBlock>> = LazyLock::new(|| {
let mut blocks_to_ids = IdTable::new();
BLOCKS_REPORT.0.iter().for_each(|(name, block)| {
block.states.iter().for_each(|state| {
if state.default {
blocks_to_ids.insert(Block::new(name), state.id);
blocks_to_ids.insert(DynamicBlock::new(name), state.id);
}
blocks_to_ids.insert(Block::new_p(name, state.properties.iter()), state.id);
blocks_to_ids.insert(DynamicBlock::new_p(name, state.properties.iter()), state.id);
});
});
blocks_to_ids
});

#[cfg(test)]
mod test {
use crate::block::{Block, BLOCKS_TO_IDS};
use crate::block::{DynamicBlock, BLOCKS_TO_IDS};

#[test]
fn test_blocks_to_ids() {
assert_eq!(BLOCKS_TO_IDS.get(&Block::air()).copied(), Some(0));
assert_eq!(
BLOCKS_TO_IDS.get(&Block::new("minecraft:stone")).copied(),
BLOCKS_TO_IDS
.get(&DynamicBlock::new("minecraft:air"))
.copied(),
Some(0)
);
assert_eq!(
BLOCKS_TO_IDS
.get(&DynamicBlock::new("minecraft:stone"))
.copied(),
Some(1)
);
}
Expand Down
59 changes: 30 additions & 29 deletions pkmc-defs/src/packet/play.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ use std::{
io::{Read, Write},
};

use pkmc_generated::{
block::Block,
registry::{BlockEntityType, EntityType},
};
use pkmc_util::{
connection::{
paletted_container::to_paletted_data_singular, ClientboundPacket, ConnectionError,
Expand Down Expand Up @@ -395,7 +399,7 @@ pub struct BlockEntity {
/// u4
pub z: u8,
pub y: i16,
pub r#type: i32,
pub r#type: BlockEntityType,
pub data: NBT,
}

Expand All @@ -412,7 +416,7 @@ pub enum LevelChunkHeightmapType {
}

impl LevelChunkHeightmapType {
fn to_id(&self) -> i32 {
fn to_id(self) -> i32 {
match self {
LevelChunkHeightmapType::WorldSurfaceWorldgen => 0,
LevelChunkHeightmapType::WorldSurface => 1,
Expand Down Expand Up @@ -475,7 +479,7 @@ impl LevelChunkData {
debug_assert!(block_entity.z <= 15);
writer.write_all(&((block_entity.x << 4) | block_entity.z).to_be_bytes())?;
writer.write_all(&block_entity.y.to_be_bytes())?;
writer.encode(block_entity.r#type)?;
writer.encode(block_entity.r#type.to_id())?;
writer.encode(&block_entity.data)?;
}
//println!("{:#?}", self.block_entities);
Expand Down Expand Up @@ -564,19 +568,21 @@ impl LevelChunkWithLight {
let mut writer = Vec::new();

for i in 0..num_sections {
let block_id = if i == 0 { 1 } else { 0 };
// Num non-air blocks
writer.write_all(
&if pkmc_generated::block::is_air(block_id) {
0i16
} else {
4096i16
let block = match i {
0 => {
if (chunk_x + chunk_z) % 2 == 0 {
Block::PinkConcrete
} else {
Block::LightBlueConcrete
}
}
.to_be_bytes(),
)?;
_ => Block::Air,
};
// Num non-air blocks
writer.write_all(&(!block.is_air() as i16 * 4096).to_be_bytes())?;

// Blocks
writer.write_all(&to_paletted_data_singular(block_id)?)?;
writer.write_all(&to_paletted_data_singular(block.into_id())?)?;
// Biome
writer.write_all(&to_paletted_data_singular(0)?)?;
}
Expand Down Expand Up @@ -885,7 +891,7 @@ impl ClientboundPacket for UpdateSectionBlocks {
pub struct AddEntity {
pub id: i32,
pub uuid: UUID,
pub r#type: i32,
pub r#type: EntityType,
pub position: Vec3<f64>,
pub pitch: u8,
pub yaw: u8,
Expand All @@ -902,7 +908,7 @@ impl ClientboundPacket for AddEntity {
fn packet_write(&self, mut writer: impl Write) -> Result<(), ConnectionError> {
writer.encode(self.id)?;
writer.encode(&self.uuid)?;
writer.encode(self.r#type)?;
writer.encode(self.r#type.to_id())?;
writer.write_all(&self.position.x.to_be_bytes())?;
writer.write_all(&self.position.y.to_be_bytes())?;
writer.write_all(&self.position.z.to_be_bytes())?;
Expand Down Expand Up @@ -935,8 +941,8 @@ pub enum EntityMetadata {
// TODO: Implement enum
Direction(i32),
OptionalUUID(Option<UUID>),
BlockState(i32),
OptionalBlockState(Option<i32>),
BlockState(Block),
OptionalBlockState(Option<Block>),
NBT(NBT),
Particle(i32),
Particles(Vec<i32>),
Expand Down Expand Up @@ -1020,16 +1026,11 @@ impl EntityMetadata {
}
EntityMetadata::BlockState(block_state) => {
writer.encode(14)?;
writer.encode(*block_state)?;
writer.encode(block_state.into_id())?;
}
EntityMetadata::OptionalBlockState(block_state) => {
writer.encode(15)?;
if let Some(block_state) = block_state {
assert_ne!(*block_state, 0);
writer.encode(*block_state)?;
} else {
writer.encode(0)?;
}
writer.encode(block_state.unwrap_or(Block::Air).into_id())?;
}
EntityMetadata::NBT(nbt) => {
writer.encode(16)?;
Expand Down Expand Up @@ -1623,10 +1624,10 @@ impl ClientboundPacket for LevelParticles {
writer.encode(self.particle.r#type().to_id())?;
match &self.particle {
Particle::Block(block) => {
writer.encode(block.id_with_default_fallback().unwrap())?;
writer.encode(block.into_id())?;
}
Particle::BlockMarker(block) => {
writer.encode(block.id_with_default_fallback().unwrap())?;
writer.encode(block.into_id())?;
}
Particle::Dust { color, scale } => {
writer.write_all(&color.to_argb8888(0).to_be_bytes())?;
Expand All @@ -1641,7 +1642,7 @@ impl ClientboundPacket for LevelParticles {
writer.write_all(&color.to_argb8888(*alpha).to_be_bytes())?;
}
Particle::FallingDust(block) => {
writer.encode(block.id_with_default_fallback().unwrap())?;
writer.encode(block.into_id())?;
}
Particle::SculkCharge { roll } => {
writer.write_all(&roll.to_be_bytes())?;
Expand Down Expand Up @@ -1676,10 +1677,10 @@ impl ClientboundPacket for LevelParticles {
writer.encode(*delay)?;
}
Particle::DustPillar(block) => {
writer.encode(block.id_with_default_fallback().unwrap())?;
writer.encode(block.into_id())?;
}
Particle::BlockCrumble(block) => {
writer.encode(block.id_with_default_fallback().unwrap())?;
writer.encode(block.into_id())?;
}
_ => {}
}
Expand Down
4 changes: 1 addition & 3 deletions pkmc-defs/src/particle.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
use pkmc_generated::registry::ParticleType;
use pkmc_generated::{block::Block, registry::ParticleType};
use pkmc_util::{Color, Position, Vec3};

use crate::block::Block;

#[derive(Debug)]
pub enum Particle {
AngryVillager,
Expand Down
Loading