use super::*;
pub(super) struct Layout {
pub(super) sections: usize,
pub(super) biome_bits: u32,
pub(super) biome_count: usize,
pub(super) keep_biomes: bool,
}
type Decoded = Result<(Arc<[Section]>, Option<Vec<BiomeSection>>), (usize, &'static str)>;
pub(super) fn decode_sections(b: &mut Builder, data: &Bytes, l: &Layout) -> Decoded {
let mut r = Reader::new(data);
let mut biomes = l.keep_biomes.then(|| Vec::with_capacity(l.sections));
let mut err = None;
let sections: Arc<[Section]> = (0..l.sections)
.map(|j| {
if err.is_some() {
return Section::Uniform(0);
}
let step = read_section(b, &mut r).and_then(|s| {
match &mut biomes {
Some(v) => v.push(read_biomes(&mut r, l.biome_bits, l.biome_count)?),
None => skip_biomes(&mut r, l.biome_bits, l.biome_count)?,
}
Ok(s)
});
match step {
Ok(s) => s,
Err(reason) => {
err = Some((j, reason));
Section::Uniform(0)
}
}
})
.collect();
match err {
Some(e) => Err(e),
None => Ok((sections, biomes)),
}
}
pub(super) fn decode_sections_shared(
b: &mut Builder,
cache: &SharedChunks,
data: &Bytes,
l: &Layout,
) -> Decoded {
let mut r = Reader::new(data);
let mut biomes = l.keep_biomes.then(|| Vec::with_capacity(l.sections));
let mut wire: Vec<(Ident, usize)> = Vec::with_capacity(l.sections);
for _ in 0..l.sections {
let at = r.position();
let ident = match shareable_len(&r) {
Some(len) => {
let key = cache.key(super::PROTOCOL, &r.rest_slice()[..len]);
r.skip(len).ok().map(|()| Ident::Keyed(key))
}
None => match read_section(b, &mut r) {
Ok(Section::Uniform(u)) => Some(Ident::Uniform(u)),
_ => None,
},
};
let biome = match &mut biomes {
Some(v) => read_biomes(&mut r, l.biome_bits, l.biome_count).map(|b| v.push(b)),
None => skip_biomes(&mut r, l.biome_bits, l.biome_count),
};
let (Some(ident), Ok(())) = (ident, biome) else {
let (sections, biomes) = decode_sections(b, data, l)?;
return Ok((cache.intern_column(sections), biomes));
};
wire.push((ident, at));
}
if let Some(sections) = cache.find_column(wire.iter().map(|w| w.0)) {
return Ok((sections, biomes));
}
let mut err = None;
let sections: Arc<[Section]> = wire
.iter()
.enumerate()
.map(|(j, &(ident, at))| {
let key = match ident {
Ident::Uniform(u) => return Section::Uniform(u),
Ident::Keyed(key) => key,
};
if err.is_some() {
return Section::Uniform(0);
}
if let Some(s) = cache.get(key) {
return s;
}
let mut r = Reader::new(data);
let s = r
.skip(at)
.map_err(|_| "truncated")
.and_then(|()| read_section(b, &mut r));
match s {
Ok(s) => cache.insert(key, s),
Err(reason) => {
err = Some((j, reason));
Section::Uniform(0)
}
}
})
.collect();
match err {
Some(e) => Err(e),
None => Ok((cache.intern_column(sections), biomes)),
}
}
#[inline(always)]
pub(super) fn read(sections: &[Section], x: i32, ry: i32, z: i32) -> BlockState {
match sections.get((ry as u32 >> 4) as usize) {
Some(s) => state(s.get_at(x, ry, z)),
None => void_air(),
}
}
fn read_section(b: &mut Builder, r: &mut Reader<'_>) -> Result<Section, &'static str> {
const EOF: &str = "truncated";
r.read_i16().map_err(|_| EOF)?;
r.read_i16().map_err(|_| EOF)?;
let bits = r.read_i8().map_err(|_| EOF)?;
match bits {
0 => {
let id = r.read_varint().map_err(|_| EOF)?;
let id = u16::try_from(id)
.ok()
.filter(|&v| usize::from(v) < STATE_COUNT)
.ok_or("palette id is not a block state")?;
Ok(Section::Uniform(id))
}
1..=8 => {
let storage = if bits <= 4 { 4u32 } else { bits as u32 };
let n = r.read_varint().map_err(|_| EOF)?;
let n = usize::try_from(n).map_err(|_| "negative palette length")?;
if bits <= 4 && n > 16 {
return Err("linear palette longer than 16");
}
if n > r.remaining() {
return Err(EOF);
}
let mut pal = [0u16; 256];
for i in 0..n {
let id = r.read_varint().map_err(|_| EOF)?;
let id = u16::try_from(id)
.ok()
.filter(|&v| usize::from(v) < STATE_COUNT)
.ok_or("palette id is not a block state")?;
if let Some(p) = pal.get_mut(i) {
*p = id;
}
}
let longs = 4096usize.div_ceil((64 / storage) as usize);
let data = r.take(longs * 8).map_err(|_| EOF)?;
b.build(&WireBlocks {
storage_bits: storage,
palette: Some(&pal[..n.min(256)]),
data,
})
}
_ => {
let longs = 4096usize.div_ceil((64 / GLOBAL_BITS) as usize);
let data = r.take(longs * 8).map_err(|_| EOF)?;
b.build(&WireBlocks {
storage_bits: GLOBAL_BITS,
palette: None,
data,
})
}
}
}
fn shareable_len(r: &Reader<'_>) -> Option<usize> {
let mut p = r.clone();
let start = p.position();
p.skip(4).ok()?;
let bits = p.read_i8().ok()?;
let longs = match bits {
0 => return None,
1..=8 => {
let n = usize::try_from(p.read_varint().ok()?).ok()?;
if (bits <= 4 && n > 16) || n > p.remaining() {
return None;
}
for _ in 0..n {
p.read_varint().ok()?;
}
let storage = if bits <= 4 { 4 } else { bits as usize };
4096usize.div_ceil(64 / storage)
}
_ => 4096usize.div_ceil((64 / GLOBAL_BITS) as usize),
};
p.skip(longs * 8).ok()?;
Some(p.position() - start)
}
pub(super) fn read_biomes(
r: &mut Reader<'_>,
global_bits: u32,
count: usize,
) -> Result<BiomeSection, &'static str> {
let mut cells = [0u16; 64];
Ok(match read_biome_cells(r, global_bits, count, &mut cells)? {
Some(single) => BiomeSection::Single(single),
None => BiomeSection::Cells(Box::new(cells)),
})
}
fn skip_biomes(r: &mut Reader<'_>, global_bits: u32, count: usize) -> Result<(), &'static str> {
read_biome_cells(r, global_bits, count, &mut [0u16; 64]).map(|_| ())
}
fn read_biome_cells(
r: &mut Reader<'_>,
global_bits: u32,
count: usize,
cells: &mut [u16; 64],
) -> Result<Option<u16>, &'static str> {
const EOF: &str = "truncated";
let check = |id: i32| -> Result<u16, &'static str> {
u16::try_from(id)
.ok()
.filter(|&v| count == 0 || usize::from(v) < count)
.ok_or("palette id is not a biome")
};
let bits = r.read_i8().map_err(|_| EOF)?;
let (storage, palette) = match bits {
0 => {
let id = check(r.read_varint().map_err(|_| EOF)?)?;
return Ok(Some(id));
}
1..=3 => {
let n = r.read_varint().map_err(|_| EOF)?;
let n = usize::try_from(n).map_err(|_| "negative palette length")?;
if n > 1 << bits {
return Err("biome palette too long");
}
let mut pal = [0u16; 8];
for p in pal.iter_mut().take(n) {
*p = check(r.read_varint().map_err(|_| EOF)?)?;
}
(bits as u32, Some((pal, n)))
}
_ => (global_bits.max(1), None),
};
let per = (64 / storage) as usize;
let longs = 64usize.div_ceil(per);
let data = r.take(longs * 8).map_err(|_| EOF)?;
let mask = (1u64 << storage) - 1;
let mut i = 0;
for w in data.as_chunks::<8>().0 {
let mut x = u64::from_be_bytes(*w);
for _ in 0..per {
if i == 64 {
break;
}
let v = (x & mask) as usize;
cells[i] = match &palette {
Some((pal, n)) => {
if v >= *n {
return Err("biome index past the palette");
}
pal[v]
}
None => check(v as i32)?,
};
x >>= storage;
i += 1;
}
}
if cells.iter().all(|&c| c == cells[0]) {
return Ok(Some(cells[0]));
}
Ok(None)
}