ghast_protocol/types/
chunk.rs1use bytes::Bytes;
26
27use crate::codec::{DecodeResult, Reader};
28use crate::error::DecodeError;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
32pub enum ContainerKind {
33 Blocks,
35 Biomes,
37}
38
39impl ContainerKind {
40 pub const fn entries(self) -> usize {
42 match self {
43 ContainerKind::Blocks => 4096,
44 ContainerKind::Biomes => 64,
45 }
46 }
47
48 const fn max_indirect(self) -> u8 {
50 match self {
51 ContainerKind::Blocks => 8,
52 ContainerKind::Biomes => 3,
53 }
54 }
55
56 const fn storage_bits(self, bits: u8) -> u8 {
58 match self {
59 ContainerKind::Blocks if bits >= 1 && bits <= 4 => 4,
60 _ => bits,
61 }
62 }
63}
64
65#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum Palette {
68 Single(i32),
70 Indirect(Vec<i32>),
72 Direct,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct PalettedContainer {
79 pub kind: ContainerKind,
81 pub bits: u8,
83 pub palette: Palette,
85 pub data: Bytes,
87}
88
89impl PalettedContainer {
90 pub fn read(r: &mut Reader<'_>, kind: ContainerKind) -> DecodeResult<Self> {
92 let bits = r.read_u8()?;
93 let palette = if bits == 0 {
94 Palette::Single(r.read_varint()?)
95 } else if bits <= kind.max_indirect() {
96 let n = r.read_varint()?;
97 let n = r.check_count(i64::from(n), 1)?;
98 let mut ids = Vec::with_capacity(n.min(256));
99 for _ in 0..n {
100 ids.push(r.read_varint()?);
101 }
102 Palette::Indirect(ids)
103 } else {
104 Palette::Direct
105 };
106 let longs = Self::long_count(kind, bits).ok_or(DecodeError::Invalid("palette bits"))?;
107 let data = r.read_bytes(longs * 8)?;
108 Ok(PalettedContainer {
109 kind,
110 bits,
111 palette,
112 data,
113 })
114 }
115
116 pub fn long_count(kind: ContainerKind, bits: u8) -> Option<usize> {
118 if bits == 0 {
119 return Some(0);
120 }
121 let b = kind.storage_bits(bits);
122 if b > 32 {
123 return None;
124 }
125 let per_long = 64 / usize::from(b);
126 Some(kind.entries().div_ceil(per_long))
127 }
128
129 pub fn get(&self, index: usize) -> Option<i32> {
132 if index >= self.kind.entries() {
133 return None;
134 }
135 let raw = match &self.palette {
136 Palette::Single(id) => return Some(*id),
137 _ => {
138 let b = usize::from(self.kind.storage_bits(self.bits));
139 let per_long = 64 / b;
140 let (li, slot) = (index / per_long, index % per_long);
141 let at = li * 8;
142 let long = u64::from_be_bytes(self.data.get(at..at + 8)?.try_into().ok()?);
143 ((long >> (slot * b)) & ((1u64 << b) - 1)) as usize
144 }
145 };
146 match &self.palette {
147 Palette::Indirect(ids) => ids.get(raw).copied(),
148 _ => i32::try_from(raw).ok(),
149 }
150 }
151}
152
153#[derive(Debug, Clone, PartialEq, Eq)]
155pub struct ChunkSection {
156 pub block_count: i16,
158 pub fluid_count: i16,
160 pub blocks: PalettedContainer,
162 pub biomes: PalettedContainer,
164}
165
166impl ChunkSection {
167 pub fn read(r: &mut Reader<'_>) -> DecodeResult<Self> {
169 Ok(ChunkSection {
170 block_count: r.read_i16()?,
171 fluid_count: r.read_i16()?,
172 blocks: PalettedContainer::read(r, ContainerKind::Blocks)?,
173 biomes: PalettedContainer::read(r, ContainerKind::Biomes)?,
174 })
175 }
176}
177
178#[derive(Debug, Clone)]
180pub struct Sections<'a> {
181 r: Reader<'a>,
182 failed: bool,
183}
184
185impl<'a> Sections<'a> {
186 pub fn new(data: &'a Bytes) -> Self {
188 Sections {
189 r: Reader::new(data),
190 failed: false,
191 }
192 }
193}
194
195impl Iterator for Sections<'_> {
196 type Item = DecodeResult<ChunkSection>;
197
198 fn next(&mut self) -> Option<Self::Item> {
199 if self.failed || self.r.remaining() == 0 {
200 return None;
201 }
202 let s = ChunkSection::read(&mut self.r);
203 self.failed = s.is_err();
204 Some(s)
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211 use crate::codec::McWrite;
212 use bytes::{BufMut, BytesMut};
213
214 #[test]
215 fn single_and_indirect() {
216 let mut w = BytesMut::new();
217 w.put_i16(4096);
219 w.put_i16(0);
220 w.put_u8(0);
221 w.put_varint(1);
222 w.put_u8(0);
223 w.put_varint(0);
224 w.put_i16(1);
226 w.put_i16(0);
227 w.put_u8(4);
228 w.put_varint(2);
229 w.put_varint(0);
230 w.put_varint(9);
231 for i in 0..256 {
232 w.put_u64(if i == 0 { 1 } else { 0 });
233 }
234 w.put_u8(0);
235 w.put_varint(3);
236 let data = w.freeze();
237 let s: Vec<ChunkSection> = Sections::new(&data).map(Result::unwrap).collect();
238 assert_eq!(s.len(), 2);
239 assert_eq!(s[0].blocks.get(123), Some(1));
240 assert_eq!(s[1].blocks.get(0), Some(9));
241 assert_eq!(s[1].blocks.get(1), Some(0));
242 assert_eq!(s[1].biomes.get(5), Some(3));
243 assert_eq!(s[1].blocks.get(4096), None);
244 assert_eq!(
245 PalettedContainer::long_count(ContainerKind::Blocks, 15),
246 Some(1024)
247 );
248 assert_eq!(
249 PalettedContainer::long_count(ContainerKind::Biomes, 7),
250 Some(8)
251 );
252 }
253}