Skip to content

Commit

Permalink
Add more informations about blocks
Browse files Browse the repository at this point in the history
Also fixed light for transparent blocks
  • Loading branch information
Snowiiii committed Nov 1, 2024
1 parent 21dd9c1 commit 460e9d3
Show file tree
Hide file tree
Showing 11 changed files with 99,601 additions and 27,394 deletions.
126,868 changes: 99,550 additions & 27,318 deletions assets/blocks.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion extractor/gradle.properties
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
# Done to increase the memory available to gradle.
org.gradle.jvmargs=-Xmx1G
org.gradle.parallel=true
# Fabric Properties
# check these on https://modmuss50.me/fabric.html
minecraft_version=1.21.3
yarn_mappings=1.21.3+build.2
loader_version=0.16.7
loader_version=0.16.9
kotlin_loader_version=1.12.3+kotlin.2.0.21
# Mod Properties
mod_version=1.0-SNAPSHOT
Expand Down
12 changes: 6 additions & 6 deletions extractor/src/main/kotlin/de/snowii/extractor/Extractor.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,11 @@ import java.nio.file.Paths


class Extractor : ModInitializer {
val MOD_ID: String = "pumpkin_extractor"
val LOGGER: Logger = LoggerFactory.getLogger(MOD_ID)
private val modID: String = "pumpkin_extractor"
private val logger: Logger = LoggerFactory.getLogger(modID)

override fun onInitialize() {
LOGGER.info("Starting Pumpkin Extractor")
logger.info("Starting Pumpkin Extractor")
val extractors = arrayOf(
Sounds(),
Recipes(),
Expand All @@ -36,7 +36,7 @@ class Extractor : ModInitializer {
try {
outputDirectory = Files.createDirectories(Paths.get("pumpkin_extractor_output"))
} catch (e: IOException) {
LOGGER.info("Failed to create output directory.", e)
logger.info("Failed to create output directory.", e)
return
}

Expand All @@ -49,9 +49,9 @@ class Extractor : ModInitializer {
val fileWriter = FileWriter(out.toFile(), StandardCharsets.UTF_8)
gson.toJson(ext.extract(server.registryManager), fileWriter)
fileWriter.close()
LOGGER.info("Wrote " + out.toAbsolutePath())
logger.info("Wrote " + out.toAbsolutePath())
} catch (e: java.lang.Exception) {
LOGGER.error(("Extractor for \"" + ext.fileName()) + "\" failed.", e)
logger.error(("Extractor for \"" + ext.fileName()) + "\" failed.", e)
}
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,13 @@ class Blocks : Extractor.Extractor {
val id = stateIdCounter
stateIdCounter++
stateJson.addProperty("id", id)
stateJson.addProperty("air", state.isAir)
stateJson.addProperty("luminance", state.luminance)
stateJson.addProperty("opaque", state.isOpaque)
stateJson.addProperty("burnable", state.isBurnable)
if (state.isOpaque) {
stateJson.addProperty("opacity", state.opacity)
}
stateJson.addProperty("sided_transparency", state.hasSidedTransparency())
stateJson.addProperty("replaceable", state.isReplaceable)

if (block.defaultState == state) {
Expand Down
14 changes: 7 additions & 7 deletions pumpkin-protocol/src/client/play/c_chunk_data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ impl<'a> ClientPacket for CChunkData<'a> {

let mut data_buf = ByteBuffer::empty();
self.0.blocks.iter_subchunks().for_each(|chunk| {
let block_count = chunk.iter().filter(|block| !block.is_air()).count() as i16;
let block_count = chunk.len() as i16;
// Block count
data_buf.put_i16(block_count);
//// Block states
Expand Down Expand Up @@ -56,7 +56,7 @@ impl<'a> ClientPacket for CChunkData<'a> {

palette.iter().for_each(|id| {
// Palette
data_buf.put_var_int(&VarInt(id.get_id_mojang_repr()));
data_buf.put_var_int(&VarInt(**id as i32));
});
// Data array length
let data_array_len = chunk.len().div_ceil(64 / block_size as usize);
Expand Down Expand Up @@ -87,7 +87,7 @@ impl<'a> ClientPacket for CChunkData<'a> {
let mut out_long: i64 = 0;
let mut shift = 0;
for block in block_clump {
out_long |= (block.get_id() as i64) << shift;
out_long |= (*block as i64) << shift;
shift += DIRECT_PALETTE_BITS;
}
data_buf.put_i64(out_long);
Expand Down Expand Up @@ -124,10 +124,10 @@ impl<'a> ClientPacket for CChunkData<'a> {
buf.put_var_int(&VarInt(self.0.blocks.subchunks_len() as i32));
self.0.blocks.iter_subchunks().for_each(|chunk| {
let mut chunk_light = [0u8; 2048];
for (i, block) in chunk.iter().enumerate() {
if !block.is_air() {
continue;
}
for (i, _) in chunk.iter().enumerate() {
// if !block .is_air() {
// continue;
// }
let index = i / 2;
let mask = if i % 2 == 1 { 0xF0 } else { 0x0F };
chunk_light[index] |= mask;
Expand Down
30 changes: 3 additions & 27 deletions pumpkin-world/src/block/block_registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ use std::sync::LazyLock;

use serde::Deserialize;

use super::BlockState;

pub static BLOCKS: LazyLock<TopLevel> = LazyLock::new(|| {
serde_json::from_str(include_str!("../../../assets/blocks.json"))
.expect("Could not parse blocks.json registry.")
Expand Down Expand Up @@ -55,8 +53,10 @@ struct Property {
#[derive(Deserialize, Clone, Debug)]
struct State {
id: u16,
air: bool,
luminance: u8,
opaque: bool,
burnable: bool,
opacity: Option<u32>,
replaceable: bool,
collision_shapes: Vec<u16>,
block_entity_type: Option<u32>,
Expand All @@ -71,27 +71,3 @@ struct Shape {
max_y: f64,
max_z: f64,
}

#[derive(Default, Copy, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
#[serde(transparent)]
pub struct BlockId(pub u16);

impl BlockId {
pub fn is_air(&self) -> bool {
self.0 == 0 || self.0 == 12959 || self.0 == 12958
}

pub fn get_id_mojang_repr(&self) -> i32 {
self.0 as i32
}

pub fn get_id(&self) -> u16 {
self.0
}
}

impl From<BlockState> for BlockId {
fn from(value: BlockState) -> Self {
Self(value.get_id())
}
}
1 change: 0 additions & 1 deletion pumpkin-world/src/block/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ pub mod block_state;

use pumpkin_core::math::vector3::Vector3;

pub use block_registry::BlockId;
pub use block_state::BlockState;

#[derive(FromPrimitive)]
Expand Down
28 changes: 12 additions & 16 deletions pumpkin-world/src/chunk/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::{
block::{BlockId, BlockState},
block::BlockState,
coordinates::{ChunkRelativeBlockCoordinates, Height},
level::SaveFile,
WORLD_HEIGHT,
Expand Down Expand Up @@ -63,7 +63,7 @@ pub struct ChunkBlocks {

// The packet relies on this ordering -> leave it like this for performance
/// Ordering: yzx (y being the most significant)
blocks: Box<[BlockId; CHUNK_VOLUME]>,
blocks: Box<[u16; CHUNK_VOLUME]>,

/// See `https://minecraft.fandom.com/wiki/Heightmap` for more info
pub heightmap: ChunkHeightmaps,
Expand Down Expand Up @@ -152,7 +152,7 @@ impl Default for ChunkHeightmaps {
impl Default for ChunkBlocks {
fn default() -> Self {
Self {
blocks: Box::new([BlockId::default(); CHUNK_VOLUME]),
blocks: Box::new([0; CHUNK_VOLUME]),
heightmap: ChunkHeightmaps::default(),
}
}
Expand All @@ -173,24 +173,20 @@ impl ChunkBlocks {

pub fn empty_with_heightmap(heightmap: ChunkHeightmaps) -> Self {
Self {
blocks: Box::new([BlockId::default(); CHUNK_VOLUME]),
blocks: Box::new([0; CHUNK_VOLUME]),
heightmap,
}
}

/// Gets the given block in the chunk
pub fn get_block(&self, position: ChunkRelativeBlockCoordinates) -> BlockId {
pub fn get_block(&self, position: ChunkRelativeBlockCoordinates) -> u16 {
self.blocks[Self::convert_index(position)]
}

/// Sets the given block in the chunk, returning the old block
pub fn set_block(
&mut self,
position: ChunkRelativeBlockCoordinates,
block: BlockId,
) -> BlockId {
pub fn set_block(&mut self, position: ChunkRelativeBlockCoordinates, block_id: u16) -> u16 {
// TODO @LUK_ESC? update the heightmap
self.set_block_no_heightmap_update(position, block)
self.set_block_no_heightmap_update(position, block_id)
}

/// Sets the given block in the chunk, returning the old block
Expand All @@ -201,12 +197,12 @@ impl ChunkBlocks {
pub fn set_block_no_heightmap_update(
&mut self,
position: ChunkRelativeBlockCoordinates,
block: BlockId,
) -> BlockId {
block: u16,
) -> u16 {
std::mem::replace(&mut self.blocks[Self::convert_index(position)], block)
}

pub fn iter_subchunks(&self) -> impl Iterator<Item = &[BlockId; SUBCHUNK_VOLUME]> {
pub fn iter_subchunks(&self) -> impl Iterator<Item = &[u16; SUBCHUNK_VOLUME]> {
self.blocks
.chunks(SUBCHUNK_VOLUME)
.map(|subchunk| subchunk.try_into().unwrap())
Expand All @@ -226,7 +222,7 @@ impl ChunkBlocks {
}

impl Index<ChunkRelativeBlockCoordinates> for ChunkBlocks {
type Output = BlockId;
type Output = u16;

fn index(&self, index: ChunkRelativeBlockCoordinates) -> &Self::Output {
&self.blocks[Self::convert_index(index)]
Expand Down Expand Up @@ -299,7 +295,7 @@ impl ChunkData {
y: Height::from_absolute((block_index / CHUNK_AREA) as u16),
x: (block_index % 16).into(),
},
BlockId(block.get_id()),
block.get_id(),
);

block_index += 1;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,22 +57,22 @@ impl PerlinTerrainGenerator for PlainsTerrainGenerator {
if y == -64 {
blocks.set_block(
coordinates,
BlockState::new("minecraft:bedrock").unwrap().into(),
BlockState::new("minecraft:bedrock").unwrap().state_id,
);
} else if y >= -63 && y <= begin_stone_height {
blocks.set_block(
coordinates,
BlockState::new("minecraft:stone").unwrap().into(),
BlockState::new("minecraft:stone").unwrap().state_id,
);
} else if y >= begin_stone_height && y < begin_dirt_height {
blocks.set_block(
coordinates,
BlockState::new("minecraft:dirt").unwrap().into(),
BlockState::new("minecraft:dirt").unwrap().state_id,
);
} else if y == chunk_height - 2 {
blocks.set_block(
coordinates,
BlockState::new("minecraft:grass_block").unwrap().into(),
BlockState::new("minecraft:grass_block").unwrap().state_id,
);
} else if y == chunk_height - 1 {
// TODO: generate flowers and grass
Expand All @@ -84,39 +84,39 @@ impl PerlinTerrainGenerator for PlainsTerrainGenerator {
0 => {
blocks.set_block(
coordinates,
BlockState::new("minecraft:dandelion").unwrap().into(),
BlockState::new("minecraft:dandelion").unwrap().state_id,
);
}
1 => {
blocks.set_block(
coordinates,
BlockState::new("minecraft:oxeye_daisy").unwrap().into(),
BlockState::new("minecraft:oxeye_daisy").unwrap().state_id,
);
}
2 => {
blocks.set_block(
coordinates,
BlockState::new("minecraft:cornflower").unwrap().into(),
BlockState::new("minecraft:cornflower").unwrap().state_id,
);
}
3 => {
blocks.set_block(
coordinates,
BlockState::new("minecraft:poppy").unwrap().into(),
BlockState::new("minecraft:poppy").unwrap().state_id,
);
}
_ => {
blocks.set_block(
coordinates,
BlockState::new("minecraft:azure_bluet").unwrap().into(),
BlockState::new("minecraft:azure_bluet").unwrap().state_id,
);
}
}
} else {
// TODO: Tall grass, Tall grass data called `half`, There is `upper` and `lower`
blocks.set_block(
coordinates,
BlockState::new("minecraft:short_grass").unwrap().into(),
BlockState::new("minecraft:short_grass").unwrap().state_id,
);
}
}
Expand Down
3 changes: 1 addition & 2 deletions pumpkin/src/client/player_packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,6 @@ use pumpkin_protocol::{
server::play::{SCloseContainer, SKeepAlive, SSetPlayerGround, SUseItem},
VarInt,
};
use pumpkin_world::block::BlockId;
use pumpkin_world::block::{block_registry::get_block_by_item, BlockFace};

use super::{
Expand Down Expand Up @@ -624,7 +623,7 @@ impl Player {
world
.set_block(
WorldPosition(location.0 + face.to_offset()),
BlockId(block.default_state_id),
block.default_state_id,
)
.await;
}
Expand Down
9 changes: 4 additions & 5 deletions pumpkin/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use pumpkin_protocol::{
},
ClientPacket, VarInt,
};
use pumpkin_world::block::BlockId;
use pumpkin_world::chunk::ChunkData;
use pumpkin_world::coordinates::ChunkRelativeBlockCoordinates;
use pumpkin_world::level::Level;
Expand Down Expand Up @@ -575,7 +574,7 @@ impl World {
self.broadcast_packet_all(&CRemoveEntities::new(&[entity.entity_id.into()]))
.await;
}
pub async fn set_block(&self, position: WorldPosition, block_id: BlockId) {
pub async fn set_block(&self, position: WorldPosition, block_id: u16) {
let (chunk_coordinate, relative_coordinates) = position.chunk_and_chunk_relative_position();

// Since we divide by 16 remnant can never exceed u8
Expand All @@ -584,7 +583,7 @@ impl World {
let chunk = self.receive_chunk(chunk_coordinate).await;
chunk.write().await.blocks.set_block(relative, block_id);

self.broadcast_packet_all(&CBlockUpdate::new(&position, i32::from(block_id.0).into()))
self.broadcast_packet_all(&CBlockUpdate::new(&position, i32::from(block_id).into()))
.await;
}

Expand All @@ -604,13 +603,13 @@ impl World {
}

pub async fn break_block(&self, position: WorldPosition) {
self.set_block(position, BlockId(0)).await;
self.set_block(position, 0).await;

self.broadcast_packet_all(&CWorldEvent::new(2001, &position, 11, false))
.await;
}

pub async fn get_block(&self, position: WorldPosition) -> BlockId {
pub async fn get_block(&self, position: WorldPosition) -> u16 {
let (chunk, relative) = position.chunk_and_chunk_relative_position();
let relative = ChunkRelativeBlockCoordinates::from(relative);
let chunk = self.receive_chunk(chunk).await;
Expand Down

0 comments on commit 460e9d3

Please sign in to comment.