2209950220
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
246 lines
9.3 KiB
Rust
246 lines
9.3 KiB
Rust
//! Binds `horizon_world`'s vanilla overworld generator (noise terrain,
|
|
//! aquifers, surface rules, carvers and placed features) to chunk streaming.
|
|
use crate::{
|
|
biome::Biomes,
|
|
chunk::{BIOME_STRATEGY, Chunk, HEIGHT, MIN_Y, SECTIONS, Section},
|
|
streaming::{ChunkGenerator, Proto},
|
|
};
|
|
use horizon_core::{paletted::PalettedContainer, position::ChunkPos};
|
|
use horizon_world::{
|
|
registry::BlockRegistry,
|
|
worldgen::generator::{GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk},
|
|
};
|
|
use std::{path::Path, sync::Arc};
|
|
|
|
pub struct VanillaTerrain {
|
|
generator: OverworldGenerator,
|
|
/// Generator biome index -> client biome table index.
|
|
biome_map: Vec<u16>,
|
|
/// Loot tables for generated containers.
|
|
loot: Option<Arc<horizon_world::loot::LootData>>,
|
|
/// A worker for structure queries from the game thread.
|
|
query: std::sync::Mutex<Option<GeneratorWorker>>,
|
|
}
|
|
/// A proto chunk, or the position of one whose generation failed.
|
|
enum VanillaProto {
|
|
Ready(Box<ProtoChunk>),
|
|
Failed(i32, i32),
|
|
}
|
|
impl VanillaTerrain {
|
|
pub fn new(
|
|
dir: &Path,
|
|
registry: &'static BlockRegistry,
|
|
biomes: &Biomes,
|
|
seed: i64,
|
|
) -> crate::Result<Self> {
|
|
Self::for_dimension(dir, registry, biomes, seed, "minecraft:overworld")
|
|
}
|
|
pub fn for_dimension(
|
|
dir: &Path,
|
|
registry: &'static BlockRegistry,
|
|
biomes: &Biomes,
|
|
seed: i64,
|
|
dimension: &str,
|
|
) -> crate::Result<Self> {
|
|
let data: Arc<GeneratorData> = shared_data(dir, registry)?;
|
|
let biome_map = data
|
|
.biome_names()
|
|
.iter()
|
|
.map(|name| biomes.id(name))
|
|
.collect();
|
|
let generator =
|
|
OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?;
|
|
let unsupported = generator.unsupported_features();
|
|
if !unsupported.is_empty() {
|
|
eprintln!(
|
|
"Horizon: {} placed features cannot run and will be skipped",
|
|
unsupported.len()
|
|
);
|
|
if !dir.join("blocks/block-properties.nbt").exists() {
|
|
eprintln!(
|
|
"Horizon: the worldgen bundle lacks the block behavior exports (worldgen/blocks/*.nbt); \
|
|
run python3 tools/prepare_native_client.py to add them"
|
|
);
|
|
}
|
|
}
|
|
let loot = dir.parent().and_then(crate::structure_blocks::loot_data);
|
|
Ok(Self {
|
|
generator,
|
|
biome_map,
|
|
loot,
|
|
query: std::sync::Mutex::new(None),
|
|
})
|
|
}
|
|
/// The structure starts owned by a chunk (cached by the generator).
|
|
pub fn starts_at(
|
|
&self,
|
|
x: i32,
|
|
z: i32,
|
|
) -> Vec<Arc<horizon_world::worldgen::structure::start::StructureStart>> {
|
|
let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner());
|
|
let worker = worker.get_or_insert_with(|| self.generator.worker());
|
|
worker.structure_starts(ChunkPos::new(x, z))
|
|
}
|
|
/// `/locate structure`: the nearest start of one of `names` within
|
|
/// `radius` placement sectors of block `from`.
|
|
pub fn locate(
|
|
&self,
|
|
names: &[String],
|
|
from: [i32; 3],
|
|
radius: i32,
|
|
) -> Option<(String, [i32; 3])> {
|
|
self.generator.worker().locate(names, from, radius)
|
|
}
|
|
/// Concentric ring positions of a structure set (strongholds), once known.
|
|
pub fn ring_positions(&self, set: &str) -> Option<Vec<ChunkPos>> {
|
|
self.generator.ring_positions(set)
|
|
}
|
|
}
|
|
/// The worldgen bundle at `dir`, loaded once and shared by every generator
|
|
/// and by live feature placement (sapling growth, bone meal).
|
|
pub fn shared_data(
|
|
dir: &Path,
|
|
registry: &'static BlockRegistry,
|
|
) -> crate::Result<Arc<GeneratorData>> {
|
|
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
|
|
std::sync::Mutex::new(Vec::new());
|
|
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
|
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
|
|
return Ok(data.clone());
|
|
}
|
|
let data = GeneratorData::load(dir, registry)?;
|
|
cache.push((dir.to_owned(), data.clone()));
|
|
Ok(data)
|
|
}
|
|
impl ChunkGenerator for VanillaTerrain {
|
|
type Worker = GeneratorWorker;
|
|
fn worker(&self) -> GeneratorWorker {
|
|
self.generator.worker()
|
|
}
|
|
fn proto(&self, worker: &mut GeneratorWorker, x: i32, z: i32) -> Proto {
|
|
match worker.generate_proto(ChunkPos::new(x, z)) {
|
|
Ok(chunk) => Box::new(VanillaProto::Ready(Box::new(chunk))),
|
|
Err(e) => {
|
|
eprintln!("Horizon: generating chunk {x} {z} failed: {e}");
|
|
Box::new(VanillaProto::Failed(x, z))
|
|
}
|
|
}
|
|
}
|
|
fn decorates(&self) -> bool {
|
|
true
|
|
}
|
|
fn decorate(&self, worker: &mut GeneratorWorker, region: &mut [Proto; 9]) {
|
|
let taken: Vec<Box<VanillaProto>> = region
|
|
.iter_mut()
|
|
.map(|p| {
|
|
std::mem::replace(p, Box::new(()))
|
|
.downcast::<VanillaProto>()
|
|
.expect("vanilla proto")
|
|
})
|
|
.collect();
|
|
let all_ready = taken.iter().all(|p| matches!(**p, VanillaProto::Ready(_)));
|
|
if all_ready {
|
|
let chunks: Vec<ProtoChunk> = taken
|
|
.into_iter()
|
|
.map(|p| match *p {
|
|
VanillaProto::Ready(c) => *c,
|
|
VanillaProto::Failed(..) => unreachable!(),
|
|
})
|
|
.collect();
|
|
let mut array: [ProtoChunk; 9] = match chunks.try_into() {
|
|
Ok(a) => a,
|
|
Err(_) => unreachable!(),
|
|
};
|
|
if let Err(e) = worker.decorate(&mut array) {
|
|
eprintln!("Horizon: decorating chunk failed: {e}");
|
|
}
|
|
for (slot, chunk) in region.iter_mut().zip(array) {
|
|
*slot = Box::new(VanillaProto::Ready(Box::new(chunk)));
|
|
}
|
|
} else {
|
|
for (slot, p) in region.iter_mut().zip(taken) {
|
|
*slot = p;
|
|
}
|
|
}
|
|
}
|
|
fn finish(&self, proto: Proto) -> Chunk {
|
|
let proto = proto.downcast::<VanillaProto>().expect("vanilla proto");
|
|
let mut chunk = match *proto {
|
|
VanillaProto::Ready(c) => c,
|
|
VanillaProto::Failed(x, z) => return Chunk::empty(x, z),
|
|
};
|
|
let pos = chunk.position();
|
|
let mut out = Chunk::empty(pos.x, pos.z);
|
|
let (bx, bz) = (pos.x * 16, pos.z * 16);
|
|
// Only the generated range (the Nether is 0..256) is copied.
|
|
let (lo, hi) = (
|
|
chunk.terrain.min_y().max(MIN_Y),
|
|
(chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT),
|
|
);
|
|
let mut values = Box::new([0u16; 4096]);
|
|
for si in 0..SECTIONS as i32 {
|
|
let base = MIN_Y + si * 16;
|
|
if base + 16 <= lo || base >= hi {
|
|
continue;
|
|
}
|
|
values.fill(0);
|
|
let mut any = false;
|
|
for y in base.max(lo)..(base + 16).min(hi) {
|
|
for z in 0..16 {
|
|
for x in 0..16 {
|
|
let id = chunk.block(bx + x, y, bz + z).0 as u16;
|
|
values[((y & 15) << 8 | z << 4 | x) as usize] = id;
|
|
any |= id != 0;
|
|
}
|
|
}
|
|
}
|
|
if any {
|
|
Arc::make_mut(&mut out.sections[si as usize]).blocks =
|
|
Section::from_blocks(&values);
|
|
}
|
|
}
|
|
let base_section = chunk.terrain.min_y() >> 4;
|
|
for (i, marks) in chunk.terrain.postprocessing().iter().enumerate() {
|
|
let sy = (base_section + i as i32) * 16;
|
|
for &packed in marks {
|
|
let p = i32::from(packed);
|
|
let y = sy + ((p >> 4) & 15);
|
|
if (lo..hi).contains(&y) {
|
|
out.postprocess
|
|
.push([bx + (p & 15), y, bz + ((p >> 8) & 15)]);
|
|
}
|
|
}
|
|
}
|
|
for si in 0..SECTIONS as i32 {
|
|
let mut cells = [0u32; 64];
|
|
for (j, cell) in cells.iter_mut().enumerate() {
|
|
let (qx, qz, qy) = (j as i32 & 3, (j as i32 >> 2) & 3, si * 4 + (j as i32 >> 4));
|
|
let y = (MIN_Y + qy * 4).clamp(lo, hi - 1);
|
|
let id = chunk.biome_id_at(bx + qx * 4, y, bz + qz * 4);
|
|
*cell = u32::from(self.biome_map.get(id.0 as usize).copied().unwrap_or(0));
|
|
}
|
|
Arc::make_mut(&mut out.sections[si as usize]).biomes =
|
|
PalettedContainer::from_values(BIOME_STRATEGY, &cells);
|
|
}
|
|
out.block_entities = crate::structure_blocks::block_entities(&chunk, self.loot.as_deref());
|
|
out.structure_refs = chunk
|
|
.structures()
|
|
.into_iter()
|
|
.map(|(id, start, _, _)| (Arc::from(id), (start.x, start.z)))
|
|
.collect();
|
|
let entities = std::mem::take(&mut chunk.entities);
|
|
out.entities = entities
|
|
.into_iter()
|
|
.map(|nbt| {
|
|
crate::structure_blocks::unpack_entity_loot(&chunk, nbt, self.loot.as_deref())
|
|
})
|
|
.map(horizon_world::nbt::Tag::Compound)
|
|
.collect();
|
|
for s in &mut out.sections {
|
|
Arc::make_mut(s).compact();
|
|
}
|
|
out.fresh = true;
|
|
out
|
|
}
|
|
}
|