valence_protocol/
chunk_pos.rs

1use valence_math::DVec3;
2
3use crate::block_pos::BlockPos;
4use crate::chunk_section_pos::ChunkSectionPos;
5use crate::{BiomePos, Decode, Encode};
6
7/// The X and Z position of a chunk.
8#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Hash, Debug, Encode, Decode)]
9pub struct ChunkPos {
10    /// The X position of the chunk.
11    pub x: i32,
12    /// The Z position of the chunk.
13    pub z: i32,
14}
15
16impl ChunkPos {
17    /// Constructs a new chunk position.
18    pub const fn new(x: i32, z: i32) -> Self {
19        Self { x, z }
20    }
21
22    pub const fn distance_squared(self, other: Self) -> u64 {
23        let diff_x = other.x as i64 - self.x as i64;
24        let diff_z = other.z as i64 - self.z as i64;
25
26        (diff_x * diff_x + diff_z * diff_z) as u64
27    }
28}
29
30impl From<BlockPos> for ChunkPos {
31    fn from(pos: BlockPos) -> Self {
32        Self {
33            x: pos.x.div_euclid(16),
34            z: pos.z.div_euclid(16),
35        }
36    }
37}
38
39impl From<ChunkSectionPos> for ChunkPos {
40    fn from(pos: ChunkSectionPos) -> Self {
41        Self { x: pos.x, z: pos.z }
42    }
43}
44
45impl From<BiomePos> for ChunkPos {
46    fn from(pos: BiomePos) -> Self {
47        Self {
48            x: pos.x.div_euclid(4),
49            z: pos.z.div_euclid(4),
50        }
51    }
52}
53
54impl From<DVec3> for ChunkPos {
55    fn from(pos: DVec3) -> Self {
56        Self {
57            x: (pos.x / 16.0).floor() as i32,
58            z: (pos.z / 16.0).floor() as i32,
59        }
60    }
61}
62
63impl From<(i32, i32)> for ChunkPos {
64    fn from((x, z): (i32, i32)) -> Self {
65        Self { x, z }
66    }
67}
68
69impl From<ChunkPos> for (i32, i32) {
70    fn from(pos: ChunkPos) -> Self {
71        (pos.x, pos.z)
72    }
73}
74
75impl From<[i32; 2]> for ChunkPos {
76    fn from([x, z]: [i32; 2]) -> Self {
77        Self { x, z }
78    }
79}
80
81impl From<ChunkPos> for [i32; 2] {
82    fn from(pos: ChunkPos) -> Self {
83        [pos.x, pos.z]
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[test]
92    fn chunk_pos_round_trip_conv() {
93        let p = ChunkPos::new(rand::random(), rand::random());
94
95        assert_eq!(ChunkPos::from(<(i32, i32)>::from(p)), p);
96        assert_eq!(ChunkPos::from(<[i32; 2]>::from(p)), p);
97    }
98}