Skip to content

Commit

Permalink
Add .set_block on ChunkData
Browse files Browse the repository at this point in the history
  • Loading branch information
lukas0008 committed Aug 21, 2024
1 parent b370391 commit 0d05e5e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
5 changes: 1 addition & 4 deletions pumpkin-protocol/src/bytebuf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,7 @@ impl ByteBuffer {
/// some, then it also calls the `write` closure.
pub fn put_option<T>(&mut self, val: &Option<T>, write: impl FnOnce(&mut Self, &T)) {
self.put_bool(val.is_some());
match val {
Some(v) => write(self, v),
None => {}
}
if let Some(v) = val { write(self, v) }
}

pub fn get_list<T>(&mut self, val: impl Fn(&mut Self) -> T) -> Vec<T> {
Expand Down
19 changes: 18 additions & 1 deletion pumpkin-world/src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;

use fastnbt::LongArray;

use crate::{level::WorldError, WORLD_HEIGHT};
use crate::{level::WorldError, vector3::Vector3, WORLD_HEIGHT, WORLD_Y_START_AT};

pub struct ChunkData {
pub blocks: Box<[i32; 16 * 16 * WORLD_HEIGHT]>,
Expand Down Expand Up @@ -110,4 +110,21 @@ impl ChunkData {
heightmaps: chunk_data.heightmaps,
})
}
/// Sets the given block in the chunk, returning the old block
pub fn set_block(&mut self, at: Vector3<i32>, block_id: i32) -> Result<i32, WorldError> {
let x = at.x - self.position.0 * 16;
let z = at.z - self.position.1 * 16;
let y = at.y - WORLD_Y_START_AT;
if !(0..16).contains(&x)
|| !(0..16).contains(&z)
|| !(0..(WORLD_HEIGHT as i32)).contains(&y)
{
return Err(WorldError::BlockOutsideChunk);
}

Ok(std::mem::replace(
&mut self.blocks[(y * 16 * 16 + z * 16 + x) as usize],
block_id,
))
}
}
2 changes: 2 additions & 0 deletions pumpkin-world/src/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ pub enum WorldError {
ErrorDeserializingChunk(String),
#[error("The requested block state id does not exist")]
BlockStateIdNotFound,
#[error("The block is not inside of the chunk")]
BlockOutsideChunk,
}

#[derive(Error, Debug)]
Expand Down

0 comments on commit 0d05e5e

Please sign in to comment.