From 497cb8e0e36cc7be7f8308730f245600756e2fed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:14:23 +0200 Subject: [PATCH 1/5] Add production noise-chunk generator, worldgen resource bundle and bench GeneratorData loads a worldgen bundle (written by prepare_native_client.py to the client resource dir) once; OverworldGenerator binds a seed and shares compiled samplers across threads; GeneratorWorker generates vanilla BIOMES..TERRAIN proto chunks (noise fill with aquifers, material surface, carvers) that match the material-stage parity dumps. Decoration is stubbed. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 370 +++++ crates/horizon-world/src/worldgen.rs | 2 + .../horizon-world/src/worldgen/generator.rs | 1185 +++++++++++++++++ .../src/worldgen/generator_decoration.rs | 27 + tools/prepare_native_client.py | 43 +- 5 files changed, 1626 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-world/examples/chunkgen_bench.rs create mode 100644 crates/horizon-world/src/worldgen/generator.rs create mode 100644 crates/horizon-world/src/worldgen/generator_decoration.rs diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs new file mode 100644 index 000000000..484237780 --- /dev/null +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -0,0 +1,370 @@ +//! Chunk generation throughput and sanity map. +//! +//! chunkgen_bench [--seed S] [--size N] [--threads T] +//! [--center CX CZ] [--verify ] [--no-decorate] +use horizon_core::position::ChunkPos; +use horizon_world::{ + DATA_VERSION, + heightmap::HeightmapType, + nbt::Tag, + registry::BlockRegistry, + worldgen::generator::{ + DecorateStats, GeneratorData, GeneratorWorker, OverworldGenerator, ProtoChunk, StageTimings, + }, +}; +use serde_json::Value; +use std::{ + collections::BTreeMap, + fs, + io::{BufRead, BufReader}, + path::{Path, PathBuf}, + sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Instant, +}; + +type Error = Box; + +fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Array(a) => Tag::List(a.iter().map(tag).collect()), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => panic!("invalid registry metadata"), + } +} +fn registry(resources: &Path) -> Result<&'static BlockRegistry, Error> { + let facts: Value = serde_json::from_str(&fs::read_to_string(resources.join("facts.json"))?)?; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List( + facts["states"] + .as_array() + .unwrap() + .iter() + .map(|v| tag(&v[4])) + .collect(), + ), + ), + ("defaults", tag(&facts["defaults"])), + ]))?; + Ok(Box::leak(Box::new(registry))) +} + +/// The material-stage fixture's chunk dump format. +fn dump(chunk: &ProtoChunk) -> Vec { + let terrain = &chunk.terrain; + let mut out = Vec::new(); + for section in 0..terrain.height() as usize / 16 { + out.push(format!("section {section}")); + let data = terrain.section(section).unwrap(); + for y in 0..16 { + for z in 0..16 { + let mut line = String::from("blocks"); + for x in 0..16 { + line += &format!(" {}", data.get((y << 8) | (z << 4) | x).unwrap().0); + } + out.push(line); + } + } + } + for kind in [HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg] { + out.push(format!("heightmap {}", kind.name())); + for word in terrain.heightmap(kind).unwrap().raw_data() { + out.push(format!("{word:x}")); + } + } + for (section, offsets) in terrain.postprocessing().iter().enumerate() { + out.push(format!("post {section} {}", offsets.len())); + out.extend(offsets.iter().map(u16::to_string)); + } + out +} + +/// Compare generated chunks with vanilla's post-carver dumps in server.txt. +fn verify(data: &std::sync::Arc, parity: &Path) -> Result<(), Error> { + let cases = [ + (-1i64, -2, 3), + (0x0123_4567_89ab_cdef, 1_875_000, -1_875_000), + ]; + let mut expected = Vec::new(); + for (seed, x, z) in cases { + let generator = OverworldGenerator::new(data.clone(), seed)?; + let lines = dump(&generator.worker().generate_proto(ChunkPos::new(x, z))?); + if let Ok(path) = std::env::var("HORIZON_VERIFY_DUMP") { + fs::write(format!("{path}{seed}.txt"), lines.join("\n") + "\n")?; + } + expected.push((seed, lines)); + } + let mut matched = vec![false; expected.len()]; + let mut lines = BufReader::new(fs::File::open(parity.join("server.txt"))?).lines(); + let mut candidates = 0; + while let Some(line) = lines.next() { + if line? != "generatedcarving ok" { + continue; + } + candidates += 1; + // Each candidate dump is followed by other output; compare per case. + let mut active = (0..expected.len()).collect::>(); + let length = expected.iter().map(|(_, e)| e.len()).max().unwrap_or(0); + for i in 0..length { + let Some(line) = lines.next() else { break }; + let line = line?; + active.retain(|&c| { + let expected = &expected[c].1; + if i == expected.len() { + matched[c] = true; + } + i < expected.len() && expected[i] == line + }); + if active.is_empty() { + break; + } + } + for c in active { + matched[c] = true; + } + } + for ((seed, _), ok) in expected.iter().zip(&matched) { + println!( + "verify seed {seed}: {}", + if *ok { "MATCH" } else { "MISMATCH" } + ); + } + println!("({candidates} vanilla generated-terrain dumps scanned)"); + if matched.iter().all(|m| *m) { + Ok(()) + } else { + Err("generated chunks differ from vanilla".into()) + } +} + +fn glyph(name: &str) -> char { + let name = name.strip_prefix("minecraft:").unwrap_or(name); + match name { + "water" => '~', + "lava" => '!', + "grass_block" => '"', + "sand" | "suspicious_sand" => '.', + "red_sand" => ',', + "sandstone" | "red_sandstone" => '=', + "stone" | "deepslate" | "andesite" | "diorite" | "granite" | "tuff" => '#', + "gravel" => ':', + "dirt" | "coarse_dirt" | "rooted_dirt" => 'd', + "podzol" => 'p', + "mycelium" => 'm', + "mud" => 'u', + "snow" | "snow_block" | "powder_snow" => 's', + "ice" | "packed_ice" | "blue_ice" => 'i', + "clay" => 'c', + "calcite" => 'C', + _ if name.ends_with("terracotta") => 't', + _ if name.ends_with("leaves") => '*', + _ if name.ends_with("log") || name.ends_with("wood") => '|', + _ if name.contains("grass") || name.contains("fern") || name.contains("flower") => '\'', + _ => '?', + } +} + +fn main() -> Result<(), Error> { + let mut args = std::env::args().skip(1); + let resources = PathBuf::from(args.next().expect("client resource directory")); + let (mut seed, mut size, mut threads, mut center) = (0i64, 16i32, 2usize, (0, 0)); + let mut parity = None; + let mut decorate = true; + while let Some(arg) = args.next() { + let mut next = || args.next().expect("argument value"); + match arg.as_str() { + "--seed" => seed = next().parse()?, + "--size" => size = next().parse()?, + "--threads" => threads = next().parse()?, + "--center" => center = (next().parse()?, next().parse()?), + "--verify" => parity = Some(PathBuf::from(next())), + "--no-decorate" => decorate = false, + _ => return Err(format!("unknown argument {arg}").into()), + } + } + let start = Instant::now(); + let registry = registry(&resources)?; + let data = GeneratorData::load(&resources.join("worldgen"), registry)?; + println!("loaded resources in {:.2?}", start.elapsed()); + if let Some(parity) = parity { + verify(&data, &parity)?; + } + let start = Instant::now(); + let generator = OverworldGenerator::new(data.clone(), seed)?; + println!("seeded generator in {:.2?}", start.elapsed()); + let (x0, z0) = (center.0 - size / 2, center.1 - size / 2); + let count = (size * size) as usize; + let next = AtomicUsize::new(0); + let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); + let timings = Mutex::new(Vec::new()); + let start = Instant::now(); + std::thread::scope(|scope| -> Result<(), Error> { + let handles = (0..threads) + .map(|_| { + scope.spawn(|| -> Result<(), Error> { + let mut worker = generator.worker(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + if i >= count { + timings.lock().unwrap().push(worker.stage_timings()); + return Ok(()); + } + let pos = ChunkPos::new(x0 + (i as i32 % size), z0 + (i as i32 / size)); + *slots[i].lock().unwrap() = Some(worker.generate_proto(pos)?); + } + }) + }) + .collect::>(); + handles.into_iter().try_for_each(|h| h.join().unwrap()) + })?; + let elapsed = start.elapsed(); + println!( + "generated {count} proto chunks with {threads} threads in {elapsed:.2?}: {:.1} chunks/s ({:.1} ms/chunk/thread)", + count as f64 / elapsed.as_secs_f64(), + elapsed.as_secs_f64() * 1000. * threads as f64 / count as f64 + ); + let timings = timings.into_inner().unwrap(); + let per_chunk = |f: fn(&StageTimings) -> std::time::Duration| { + timings + .iter() + .map(f) + .sum::() + .as_secs_f64() + * 1000. + / count as f64 + }; + println!( + " per chunk: biomes {:.2} ms, noise {:.2} ms, surface {:.2} ms, carvers {:.2} ms", + per_chunk(|t| t.biomes), + per_chunk(|t| t.noise), + per_chunk(|t| t.surface), + per_chunk(|t| t.carvers) + ); + let mut chunks: Vec> = slots + .into_iter() + .map(|slot| slot.into_inner().unwrap()) + .collect(); + if decorate && size >= 3 { + let totals = Mutex::new(DecorateStats::default()); + let start = Instant::now(); + let mut decorated = 0; + // Disjoint 3×3 regions per phase can be decorated concurrently. + for phase in 0..9 { + let mut regions = Vec::new(); + for z in 1..size - 1 { + for x in 1..size - 1 { + if (x % 3) * 3 + z % 3 != phase { + continue; + } + let mut region = Vec::with_capacity(9); + for dz in -1..=1 { + for dx in -1..=1 { + region + .push(chunks[((z + dz) * size + x + dx) as usize].take().unwrap()); + } + } + regions.push(((x, z), region)); + } + } + decorated += regions.len(); + let queue = Mutex::new(regions); + let done = Mutex::new(Vec::new()); + std::thread::scope(|scope| -> Result<(), Error> { + let handles = (0..threads) + .map(|_| { + scope.spawn(|| -> Result<(), Error> { + let mut worker: GeneratorWorker = generator.worker(); + loop { + let Some((at, region)) = queue.lock().unwrap().pop() else { + return Ok(()); + }; + let mut region: [ProtoChunk; 9] = + region.try_into().map_err(|_| "region size")?; + let stats = worker.decorate(&mut region)?; + let mut totals = totals.lock().unwrap(); + totals.placed += stats.placed; + totals.unsupported += stats.unsupported; + totals.failed += stats.failed; + totals.skipped.extend(stats.skipped); + drop(totals); + done.lock().unwrap().push((at, region)); + } + }) + }) + .collect::>(); + handles.into_iter().try_for_each(|h| h.join().unwrap()) + })?; + for ((x, z), region) in done.into_inner().unwrap() { + for (i, chunk) in region.into_iter().enumerate() { + let (dx, dz) = (i as i32 % 3 - 1, i as i32 / 3 - 1); + chunks[((z + dz) * size + x + dx) as usize] = Some(chunk); + } + } + } + let elapsed = start.elapsed(); + let totals = totals.into_inner().unwrap(); + println!( + "decorated {decorated} chunks in {elapsed:.2?}: {:.1} chunks/s; feature roots placed {}, unsupported {}, failed {}", + decorated as f64 / elapsed.as_secs_f64(), + totals.placed, + totals.unsupported, + totals.failed + ); + if !totals.skipped.is_empty() { + println!( + "skipped roots: {}", + totals.skipped.into_iter().collect::>().join(" ") + ); + } + } + let mut legend = BTreeMap::>::new(); + let step = (size * 16 / 96).max(1); + for bz in (0..size * 16).step_by(step as usize) { + let mut row = String::new(); + for bx in (0..size * 16).step_by(step as usize) { + let chunk = chunks[((bz / 16) * size + bx / 16) as usize] + .as_ref() + .unwrap(); + let (x, z) = ( + chunk.position().x * 16 + bx % 16, + chunk.position().z * 16 + bz % 16, + ); + let y = chunk.surface_height(x, z) - 1; + let name = chunk.block_name(x, y, z).to_owned(); + let c = glyph(&name); + *legend.entry(c).or_default().entry(name).or_default() += 1; + row.push(c); + } + println!("{row}"); + } + for (c, names) in legend { + let mut names = names.into_iter().collect::>(); + names.sort_by_key(|(_, n)| std::cmp::Reverse(*n)); + let names = names + .into_iter() + .take(4) + .map(|(n, _)| n) + .collect::>(); + println!(" {c} {}", names.join(" ")); + } + let middle = chunks[(size / 2 * size + size / 2) as usize] + .as_ref() + .unwrap(); + let p = middle.position(); + println!( + "biome at center ({}, 64, {}): {}", + p.x * 16, + p.z * 16, + middle.biome_at(p.x * 16, 64, p.z * 16) + ); + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index ed126b40e..a9828cc18 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -33,6 +33,8 @@ pub mod feature_graph; pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; +pub mod generator; +mod generator_decoration; pub mod height_provider; pub mod material_condition; pub mod material_extensions; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs new file mode 100644 index 000000000..876f1dbb9 --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -0,0 +1,1185 @@ +//! Production noise-chunk generation for one dimension of a world preset. +//! +//! `GeneratorData` holds seed-independent resources parsed once from a bundle +//! directory (see `GeneratorData::load`). `OverworldGenerator` binds a world seed +//! and is shared across threads; each thread owns a `GeneratorWorker`. +//! `generate_proto` runs vanilla's BIOMES and TERRAIN statuses (noise fill with +//! aquifers, material surface, carvers) and primes the post-terrain heightmaps. +//! `decorate` runs the FEATURES status for the center of a 3×3 neighborhood with +//! whatever feature algorithms are implemented; structures are not generated. +use super::{ + DecodeError, + anchor::WorldGenerationContext, + aquifer::{ + AquiferConfig, AquiferField, AquiferSamplers, DisabledAquifer, GlobalFluidPicker, + NoiseBasedAquifer, RegistryAquiferBlockStates, + }, + biome::BiomeId, + biome_chunk::{BiomeChunk, BiomeRegion}, + biome_source::{BiomeSourceCatalog, ResolvedBiomeSource}, + biome_temperature::{BiomeTemperature, BiomeTemperatureSettings}, + carver::{CarverCatalog, WorldCarver, generate_carving_mask}, + carving::{CarvingBlocks, apply_carving_mask}, + climate::{ClimateSampler, quantize}, + decode_noise, + density::DensityRegistry, + material_condition::{ + MaterialConditionRegistry, MaterialRule, MaterialRuleError, MaterialRuleLibrary, + MaterialSurfaceQueries, + }, + material_extensions::{ExtensionBlocks, ExtensionNoises, MaterialExtensions}, + material_stage::{SurfaceInputs, TopMaterialInputs, build_surface}, + material_surface::{ClayBandBlocks, MaterialSurface}, + router::{NoiseRouter, RouterField, RouterSamplers}, + tags::TagDefinitions, + terrain::{PreLightChunkStage, TerrainAquifer, TerrainBlockStates, TerrainChunk, fill_noise}, +}; +use crate::{ + heightmap::{HeightmapState, HeightmapType}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::{ + biome::{BiomeZoom, obfuscate_seed}, + density::{DensitySampler, SamplerContext}, + noise::{DensityVolume, Noise}, + position::{BlockPos, ChunkPos}, + random::{LegacyRandom, PositionalRandom, RandomSource, XoroshiroRandom}, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + fs, io, + path::Path, + sync::{Arc, Mutex}, +}; + +#[derive(Debug)] +pub enum GeneratorError { + Io(io::Error), + Decode(DecodeError), + /// A resource is missing or inconsistent with the block registry. + Resource(String), + /// A generation stage failed; the chunk is incomplete. + Stage(&'static str, String), +} +impl std::fmt::Display for GeneratorError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(e) => e.fmt(f), + Self::Decode(e) => e.fmt(f), + Self::Resource(e) => write!(f, "invalid generator resources: {e}"), + Self::Stage(stage, e) => write!(f, "{stage} failed: {e}"), + } + } +} +impl std::error::Error for GeneratorError {} +impl From for GeneratorError { + fn from(e: io::Error) -> Self { + Self::Io(e) + } +} +impl From for GeneratorError { + fn from(e: DecodeError) -> Self { + Self::Decode(e) + } +} +impl From for GeneratorError { + fn from(e: serde_json::Error) -> Self { + Self::Decode(e.into()) + } +} +fn stage(name: &'static str) -> impl FnOnce(E) -> GeneratorError { + move |e| GeneratorError::Stage(name, e.to_string()) +} +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} + +/// Heightmap-relevant block behavior, one entry per registry state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct GenBlockState { + pub air: bool, + pub air_block: bool, + pub fluid: bool, + pub motion: bool, + pub no_leaves: bool, +} +impl HeightmapState for GenBlockState { + fn is_air(self) -> bool { + self.air + } + fn is_air_block(self) -> bool { + self.air_block + } + fn has_fluid(self) -> bool { + self.fluid + } + fn blocks_motion_in_heightmap(self) -> bool { + self.motion + } + fn blocks_motion_in_heightmap_no_leaves(self) -> bool { + self.no_leaves + } +} +/// Shared, cheaply cloned state table bound into every generated chunk. +#[derive(Clone, Debug)] +pub struct GenBlockStates(Arc<[GenBlockState]>); +impl GenBlockStates { + pub fn get(&self, id: BlockStateId) -> GenBlockState { + self.0.get(id.0 as usize).copied().unwrap_or_default() + } +} +impl TerrainBlockStates for GenBlockStates { + type State = GenBlockState; + fn heightmap_state(&self, id: BlockStateId) -> GenBlockState { + self.get(id) + } +} + +/// Feature resources for the FEATURES status, keyed by resource identifier. +pub(super) struct FeatureResources { + pub(super) features: BTreeMap, + pub(super) placed: BTreeMap, + pub(super) feature_tags: BTreeMap, + pub(super) fluid_tags: BTreeMap>, +} + +/// Seed-independent generation resources, loaded once and shared by every +/// generator. Biome identities are indices into the sorted biome registry. +pub struct GeneratorData { + registry: &'static BlockRegistry, + states: GenBlockStates, + integers: BTreeSet<(String, String)>, + noises: BTreeMap, + densities: BTreeMap, + rules: BTreeMap, + settings: BTreeMap, + presets: BTreeMap, + world_presets: BTreeMap, + conditions: MaterialConditionRegistry, + source_catalog: BiomeSourceCatalog, + biome_names: Vec>, + biome_ids: BTreeMap, + biome_json: Vec, + temperatures: Vec, + biome_carvers: Vec>>, + carving_blocks: CarvingBlocks, + pub(super) block_tags: BTreeMap>, + pub(super) biome_tags: BTreeMap>, + pub(super) feature_resources: Option, +} +type Bundle = BTreeMap; +fn read_bundle(dir: &Path, name: &str) -> Result { + let path = dir.join(format!("{name}.json")); + let text = + fs::read_to_string(&path).map_err(|e| resource(format!("{}: {e}", path.display())))?; + Ok(serde_json::from_str(&text)?) +} +fn read_optional_bundle(dir: &Path, name: &str) -> Result, GeneratorError> { + if dir.join(format!("{name}.json")).exists() { + read_bundle(dir, name).map(Some) + } else { + Ok(None) + } +} +fn build_tags( + raw: &Bundle, + known: impl Fn(&str) -> bool, +) -> Result>, GeneratorError> { + let mut definitions = TagDefinitions::default(); + for (name, json) in raw { + definitions.apply_json(name, "vanilla", json)?; + } + let built = definitions + .build(|id, _| known(id).then(|| id.to_owned())) + .map_err(|e| resource(format!("tags: {e:?}")))?; + if !built.missing.is_empty() { + return Err(resource(format!( + "unresolved tag entries in {:?}", + built.missing.keys().collect::>() + ))); + } + Ok(built.tags) +} +/// Convert a data-generator `biome_parameters` report into the quantized +/// preset table format, using vanilla's float `quantizeCoord`. +fn quantize_parameter_report(json: &str) -> Result { + let report: Value = serde_json::from_str(json)?; + let float = |v: &Value| -> Result { + let text = v.to_string(); + text.parse::() + .map(quantize) + .map_err(|_| resource("biome parameter value")) + }; + let mut entries = Vec::new(); + for entry in report["biomes"] + .as_array() + .ok_or_else(|| resource("biome parameter report"))? + { + let parameters = &entry["parameters"]; + let mut coordinates = Vec::new(); + for key in [ + "temperature", + "humidity", + "continentalness", + "erosion", + "depth", + "weirdness", + ] { + let value = ¶meters[key]; + coordinates.push(match value.as_array() { + Some(range) if range.len() == 2 => { + serde_json::json!([float(&range[0])?, float(&range[1])?]) + } + None if value.is_number() => { + let v = float(value)?; + serde_json::json!([v, v]) + } + _ => return Err(resource("biome parameter interval")), + }); + } + entries.push(serde_json::json!({ + "coordinates": coordinates, + "offset": float(¶meters["offset"])?, + "biome": entry["biome"], + })); + } + Ok(Value::Array(entries).to_string()) +} +impl GeneratorData { + /// Load a worldgen bundle directory. Required files are JSON objects mapping + /// resource identifiers to the resource's JSON text: `noises`, `densities`, + /// `rules` (material rules), `conditions` (material conditions), `settings` + /// (noise settings), `carvers`, `biomes`, `biome_tags`, `block_tags`, + /// `world_presets`; `block_flags.json` is an array of `[is_air, has_fluid]` + /// per registry state. Multi-noise tables come from `presets.json` + /// (quantized) or `biome_parameters/.json` data-generator reports. + /// Optional decoration inputs: `features`, `placed_features`, + /// `feature_tags`, `fluid_tags`. Integer block properties are derived from + /// the registry: properties whose every value is a decimal integer. + pub fn load(dir: &Path, registry: &'static BlockRegistry) -> Result, GeneratorError> { + let flags: Vec<(bool, bool)> = + serde_json::from_str(&fs::read_to_string(dir.join("block_flags.json"))?)?; + if flags.len() != registry.len() { + return Err(resource("block_flags.json does not match the registry")); + } + let block_tags = build_tags(&read_bundle(dir, "block_tags")?, |id| { + registry.default_state(id).is_some() + })?; + let tag_set = |name: &str| -> Result, GeneratorError> { + Ok(block_tags + .get(name) + .ok_or_else(|| resource(format!("missing block tag {name}")))? + .iter() + .map(String::as_str) + .collect()) + }; + let motion = tag_set("minecraft:blocks_motion_in_heightmap")?; + let no_leaves = tag_set("minecraft:blocks_motion_in_heightmap_no_leaves")?; + let mut values = BTreeMap::<(String, String), bool>::new(); + let states = (0..registry.len()) + .map(|i| { + let state = registry.state(BlockStateId(i as u32)).unwrap(); + for (key, value) in &state.properties { + let integer = !value.is_empty() + && value + .trim_start_matches('-') + .bytes() + .all(|b| b.is_ascii_digit()); + *values + .entry((state.name.clone(), key.clone())) + .or_insert(true) &= integer; + } + GenBlockState { + air: flags[i].0, + air_block: state.name == "minecraft:air", + fluid: flags[i].1, + motion: motion.contains(state.name.as_str()), + no_leaves: no_leaves.contains(state.name.as_str()), + } + }) + .collect::>(); + let integers = values + .into_iter() + .filter_map(|(key, integer)| integer.then_some(key)) + .collect(); + let biomes = read_bundle(dir, "biomes")?; + let biome_tags = build_tags(&read_bundle(dir, "biome_tags")?, |id| { + biomes.contains_key(id) + })?; + let biome_set = biomes.keys().cloned().collect::>(); + let conditions = MaterialConditionRegistry::from_json_with_biome_tags( + &read_bundle(dir, "conditions")?, + &biome_set, + &biome_tags, + )?; + let mut presets = read_optional_bundle(dir, "presets")?.unwrap_or_default(); + let reports = dir.join("biome_parameters"); + if reports.is_dir() { + for entry in fs::read_dir(&reports)? { + let path = entry?.path(); + let Some(stem) = path + .file_stem() + .and_then(|s| s.to_str()) + .filter(|_| path.extension().is_some_and(|e| e == "json")) + else { + continue; + }; + presets + .entry(format!("minecraft:{stem}")) + .or_insert(quantize_parameter_report(&fs::read_to_string(&path)?)?); + } + } + let source_catalog = + BiomeSourceCatalog::new(&biome_set, &biome_tags, &presets.keys().cloned().collect())?; + let carvers = CarverCatalog::from_json(&read_bundle(dir, "carvers")?)?; + let mut biome_names = Vec::new(); + let mut biome_ids = BTreeMap::new(); + let mut biome_json = Vec::new(); + let mut temperatures = Vec::new(); + let mut biome_carvers = Vec::new(); + for (name, json) in &biomes { + biome_ids.insert(name.clone(), BiomeId(biome_names.len() as u32)); + biome_names.push(Arc::::from(name.as_str())); + temperatures.push(BiomeTemperatureSettings::from_json(json)?); + let value: Value = serde_json::from_str(json)?; + biome_carvers.push(carvers.decode_set(&value["carvers"].to_string())?); + biome_json.push(json.clone()); + } + let carving_blocks = CarvingBlocks::from_registry( + registry, + &tag_set("minecraft:uncarvable")? + .into_iter() + .map(str::to_owned) + .collect(), + ) + .map_err(|e| resource(format!("carving blocks: {e}")))?; + let feature_resources = match ( + read_optional_bundle(dir, "features")?, + read_optional_bundle(dir, "placed_features")?, + ) { + (Some(features), Some(placed)) => { + let fluid_tags = match read_optional_bundle(dir, "fluid_tags")? { + Some(raw) => build_tags(&raw, |id| { + matches!( + id, + "minecraft:water" + | "minecraft:flowing_water" + | "minecraft:lava" + | "minecraft:flowing_lava" + | "minecraft:empty" + ) + })?, + None => BTreeMap::new(), + }; + Some(FeatureResources { + features, + placed, + feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), + fluid_tags, + }) + } + _ => None, + }; + Ok(Arc::new(Self { + registry, + states: GenBlockStates(states.into()), + integers, + noises: read_bundle(dir, "noises")?, + densities: read_bundle(dir, "densities")?, + rules: read_bundle(dir, "rules")?, + settings: read_bundle(dir, "settings")?, + world_presets: read_bundle(dir, "world_presets")?, + presets, + conditions, + source_catalog, + biome_names, + biome_ids, + biome_json, + temperatures, + biome_carvers, + carving_blocks, + block_tags, + biome_tags, + feature_resources, + })) + } + pub fn registry(&self) -> &'static BlockRegistry { + self.registry + } + pub fn block_states(&self) -> &GenBlockStates { + &self.states + } + /// Biome identifiers in registry (identifier-sorted) order. + pub fn biome_names(&self) -> &[Arc] { + &self.biome_names + } + pub fn biome_name(&self, id: BiomeId) -> &str { + &self.biome_names[id.0 as usize] + } + pub fn biome_id(&self, name: &str) -> Option { + self.biome_ids.get(name).copied() + } + /// The biome's resource JSON (climate, effects such as water/sky/foliage + /// colors, attributes, carvers and features). + pub fn biome_json(&self, id: BiomeId) -> &str { + &self.biome_json[id.0 as usize] + } + pub(super) fn integers(&self) -> &BTreeSet<(String, String)> { + &self.integers + } +} + +/// A generated chunk with its quart biomes. Blocks and heightmaps live in +/// `terrain`; after `generate_proto` it is at the TERRAIN status with the +/// WORLD_SURFACE(_WG), OCEAN_FLOOR(_WG) and MOTION_BLOCKING(_NO_LEAVES) +/// heightmaps primed. Fluid positions scheduled for postprocessing are kept in +/// `terrain.postprocessing()`. +pub struct ProtoChunk { + pub terrain: TerrainChunk<'static, GenBlockStates>, + biomes: BiomeChunk, + data: Arc, + decorated: bool, +} +impl ProtoChunk { + pub fn position(&self) -> ChunkPos { + self.terrain.position() + } + pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { + self.terrain.block(x, y, z) + } + pub fn block_name(&self, x: i32, y: i32, z: i32) -> &str { + &self + .data + .registry + .state(self.block(x, y, z)) + .expect("registered state") + .name + } + /// Stored quart biome (4×4×4 cell) containing this block, without the + /// client's biome zoom. X/Z wrap to this chunk; Y clamps to its range. + pub fn biome_id_at(&self, x: i32, y: i32, z: i32) -> BiomeId { + *self.biomes.noise_biome([x >> 2, y >> 2, z >> 2]) + } + pub fn biome_at(&self, x: i32, y: i32, z: i32) -> &str { + self.data.biome_name(self.biome_id_at(x, y, z)) + } + pub fn biomes(&self) -> &BiomeChunk { + &self.biomes + } + pub fn data(&self) -> &Arc { + &self.data + } + pub fn is_decorated(&self) -> bool { + self.decorated + } + /// Highest non-air block + 1 in the column (WORLD_SURFACE). + pub fn surface_height(&self, x: i32, z: i32) -> i32 { + self.terrain + .heightmap(HeightmapType::WorldSurface) + .and_then(|map| map.first_available(x & 15, z & 15).ok()) + .unwrap_or(self.terrain.min_y()) + } +} + +/// Per-noise-settings values resolved from the dimension's generator JSON. +struct Settings { + min_y: i32, + height: i32, + sea_level: i32, + default_block: BlockStateId, + default_fluid: BlockStateId, + legacy: bool, +} + +/// The seed-bound pipeline for one random-source kind. +struct Pipeline { + data: Arc, + seed: i64, + settings: Settings, + root: R::Positional, + router: RouterSamplers, + climate: ClimateSampler, + aquifer: Option<[Arc; 6]>, + rule: MaterialRule, + preliminary: Arc, + source: ResolvedBiomeSource, + surface: MaterialSurface, + noises: BTreeMap>, + extensions: MaterialExtensions, + picker: GlobalFluidPicker, + zoom: BiomeZoom, + biome_cache: Mutex>>>, + carver_cache: Mutex>, + pub(super) decoration: Option, +} +const CACHE_LIMIT: usize = 16384; + +fn state(registry: &BlockRegistry, raw: &Value) -> Result { + let name = raw + .get("Name") + .and_then(Value::as_str) + .or_else(|| raw.as_str()) + .ok_or_else(|| resource("block state"))?; + let properties = raw.get("Properties").and_then(Value::as_object); + match properties { + Some(properties) if !properties.is_empty() => { + let descriptor = crate::chunk::BlockState { + name: super::tags::identifier(name)?, + properties: properties + .iter() + .map(|(k, v)| (k.clone(), v.as_str().unwrap_or_default().to_owned())) + .collect(), + }; + registry + .resolve(&descriptor) + .map_err(|e| resource(format!("block state {name}: {e}"))) + } + _ => registry + .default_state(&super::tags::identifier(name)?) + .ok_or_else(|| resource(format!("unknown block {name}"))), + } +} + +impl Pipeline +where + R::Positional: Clone + Send + Sync, +{ + fn new( + data: Arc, + seed: i64, + mut random: R, + generator: &Value, + settings_json: &Value, + ) -> Result { + let registry = data.registry; + let noise = &settings_json["noise"]; + let settings = Settings { + min_y: noise["min_y"] + .as_i64() + .ok_or_else(|| resource("noise min_y"))? as i32, + height: noise["height"] + .as_i64() + .ok_or_else(|| resource("noise height"))? as i32, + sea_level: settings_json["sea_level"] + .as_i64() + .ok_or_else(|| resource("sea_level"))? as i32, + default_block: state(registry, &settings_json["default_block"])?, + default_fluid: state(registry, &settings_json["default_fluid"])?, + legacy: settings_json["legacy_random_source"] + .as_bool() + .unwrap_or(false), + }; + let root = random.fork_positional(); + let codec = crate::registry::BlockStateJsonCodec::new(registry, data.integers.clone()) + .map_err(|e| resource(e.to_string()))?; + let mut densities = DensityRegistry::from_json(&data.noises, &data.densities)?; + let router = + NoiseRouter::from_json(&settings_json["noise_router"].to_string(), &mut densities)?; + let aquifers = settings_json + .get("aquifers") + .filter(|v| !v.is_null()) + .map(|v| AquiferConfig::from_json(&v.to_string(), &mut densities)) + .transpose()?; + let mut library = MaterialRuleLibrary::from_json( + &data.rules, + &data.conditions, + &codec, + densities, + seed, + settings.legacy, + )?; + let router = library.compile_router(router)?; + let aquifer = aquifers + .map(|config| library.compile_aquifer(config)) + .transpose()? + .map(|samplers| AquiferField::ALL.map(|field| samplers.get(field).clone())); + let rule_name = settings_json["material_rule"] + .as_str() + .ok_or_else(|| resource("material_rule"))?; + let rule = library.rule(rule_name)?; + let preliminary = router.get(RouterField::ChunkSurfaceLevel).clone(); + let source = data + .source_catalog + .decode(&generator["biome_source"].to_string())? + .resolve(&data.presets) + .map_err(|e| resource(format!("biome source: {e}")))?; + let climate = router.climate_sampler(); + let mut noises = BTreeMap::new(); + for (name, json) in &data.noises { + let noise: Arc = Arc::new( + decode_noise(json)? + .create(&mut root.from_hash_of(name)) + .map_err(DecodeError::from)?, + ); + noises.insert(name.clone(), noise); + } + let noise = |name: &str| -> Result, GeneratorError> { + noises + .get(name) + .cloned() + .ok_or_else(|| resource(format!("missing noise {name}"))) + }; + let surface = MaterialSurface::new( + root.clone(), + ClayBandBlocks::from_registry(registry).ok_or_else(|| resource("clay bands"))?, + noise("minecraft:clay_bands_offset")?, + noise("minecraft:surface")?, + noise("minecraft:surface_secondary")?, + ); + let default = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| resource(format!("missing block {name}"))) + }; + let extensions = MaterialExtensions::new( + root.clone(), + ExtensionBlocks { + default: settings.default_block, + water: default("minecraft:water")?, + packed_ice: default("minecraft:packed_ice")?, + snow: default("minecraft:snow_block")?, + }, + ExtensionNoises { + badlands_surface: noise("minecraft:badlands_surface")?, + badlands_pillar: noise("minecraft:badlands_pillar")?, + badlands_roof: noise("minecraft:badlands_pillar_roof")?, + iceberg_surface: noise("minecraft:iceberg_surface")?, + iceberg_pillar: noise("minecraft:iceberg_pillar")?, + iceberg_roof: noise("minecraft:iceberg_pillar_roof")?, + }, + settings.sea_level, + ); + let picker = GlobalFluidPicker::new( + settings.sea_level, + settings.default_fluid, + default("minecraft:lava")?, + default("minecraft:air")?, + ); + let mut pipeline = Self { + zoom: BiomeZoom::new(obfuscate_seed(seed)), + data, + seed, + settings, + root, + router, + climate, + aquifer, + rule, + preliminary, + source, + surface, + noises, + extensions, + picker, + biome_cache: Mutex::new(HashMap::new()), + carver_cache: Mutex::new(HashMap::new()), + decoration: None, + }; + pipeline.decoration = + super::generator_decoration::Decoration::new(&pipeline.data, &pipeline.source)?; + Ok(pipeline) + } + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new( + self.settings.min_y, + self.settings.height, + self.settings.sea_level, + ) + } + fn biome_chunk( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result>, GeneratorError> { + if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { + return Ok(chunk.clone()); + } + let (min, height) = (self.settings.min_y, self.settings.height); + let mut chunk = BiomeChunk::new(pos, min, height, BiomeId(0)).map_err(stage("biomes"))?; + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let context = &mut worker.biome_context; + let volume = resolver + .prepare_volume( + context, + [ + pos.x.wrapping_shl(4) >> 2, + min >> 2, + pos.z.wrapping_shl(4) >> 2, + ], + [4, height >> 2, 4], + ) + .map_err(stage("biomes"))?; + let ids = &self.data.biome_ids; + chunk + .fill(min, min + height - 1, |quart| { + resolver + .sample_prepared(context, volume.as_ref(), quart) + .map_err(|e| e.to_string()) + .and_then(|name| ids.get(name).copied().ok_or_else(|| name.to_owned())) + }) + .map_err(stage("biomes"))?; + let chunk = Arc::new(chunk); + let mut cache = self.biome_cache.lock().unwrap(); + if cache.len() >= CACHE_LIMIT { + cache.clear(); + } + cache.insert((pos.x, pos.z), chunk.clone()); + Ok(chunk) + } + fn carver_biome(&self, worker: &mut WorkerState, origin: ChunkPos) -> Result { + if let Some(id) = self.carver_cache.lock().unwrap().get(&(origin.x, origin.z)) { + return Ok(*id); + } + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let quart = [ + origin.x.wrapping_shl(4) >> 2, + 0, + origin.z.wrapping_shl(4) >> 2, + ]; + let name = resolver + .sample(&mut worker.carver_context, quart) + .map_err(|e| e.to_string())?; + let id = self.data.biome_id(name).ok_or_else(|| name.to_owned())?; + let mut cache = self.carver_cache.lock().unwrap(); + if cache.len() >= CACHE_LIMIT * 4 { + cache.clear(); + } + cache.insert((origin.x, origin.z), id); + Ok(id) + } + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result { + let data = &self.data; + let (min, height, sea) = ( + self.settings.min_y, + self.settings.height, + self.settings.sea_level, + ); + let mut clock = std::time::Instant::now(); + let mut neighbors = Vec::with_capacity(9); + let mut possible = BTreeSet::new(); + for dz in -1..=1 { + for dx in -1..=1 { + let chunk = self.biome_chunk( + worker, + ChunkPos::new(pos.x.wrapping_add(dx), pos.z.wrapping_add(dz)), + )?; + for section in 0..(height / 16) as usize { + possible.extend(chunk.section(section).unwrap().iter().copied()); + } + neighbors.push((*chunk).clone()); + } + } + let center = neighbors[4].clone(); + let biomes = + BiomeRegion::new(neighbors, obfuscate_seed(self.seed)).map_err(stage("biomes"))?; + let possible = possible + .into_iter() + .map(|id| data.biome_name(id).to_owned()) + .collect(); + worker.timings.biomes += lap(&mut clock); + let mut chunk = TerrainChunk::new(pos, min, height, data.registry, data.states.clone()) + .map_err(stage("noise"))?; + chunk.set_generation_stage(PreLightChunkStage::Biomes); + let mut context = SamplerContext::cached(); + let volume = DensityVolume::new( + [16, height, 16], + [pos.x.wrapping_shl(4), min, pos.z.wrapping_shl(4)], + [1; 3], + ) + .map_err(stage("noise"))?; + worker.timings.noise += lap(&mut clock); + let mut aquifer: Box = match &self.aquifer { + Some(samplers) => Box::new( + NoiseBasedAquifer::new( + AquiferSamplers::new(samplers.clone()), + self.picker, + self.root + .from_hash_of("minecraft:aquifer") + .fork_positional(), + RegistryAquiferBlockStates::new(data.registry).map_err(stage("aquifer"))?, + volume, + &mut context, + ) + .map_err(stage("aquifer"))?, + ), + None => Box::new(DisabledAquifer::new( + self.picker, + data.registry.default_state("minecraft:air").unwrap(), + )), + }; + worker.timings.noise += lap(&mut clock); + fill_noise( + &mut chunk, + volume, + self.router.get(RouterField::FinalDensity).as_ref(), + &mut context, + aquifer.as_mut(), + self.settings.default_block, + ) + .map_err(stage("noise"))?; + let generation = self.generation(); + worker.timings.noise += lap(&mut clock); + build_surface( + &mut chunk, + self.rule.clone(), + SurfaceInputs:: { + generation, + noise_volume: volume, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Region(&biomes), + possible: Some(possible), + }, + preliminary_surface: self.preliminary.clone(), + density_context: &mut context, + write_min_y: min, + write_max_y: min + height - 1, + }, + &self.extensions, + ) + .map_err(stage("surface"))?; + worker.timings.surface += lap(&mut clock); + let carvers = &data.biome_carvers; + let mask = generate_carving_mask(self.seed, pos, generation, false, |origin| { + self.carver_biome(worker, origin) + .map(|id| carvers[id.0 as usize].as_slice()) + }) + .map_err(stage("carvers"))?; + worker.timings.carvers += lap(&mut clock); + if !mask.is_empty() { + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let mut biome_context = SamplerContext::default(); + apply_carving_mask( + &mut chunk, + &mask, + self.rule.clone(), + TopMaterialInputs:: { + generation, + root: self.root.clone(), + surface: SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Resolver(&mut resolver, &mut biome_context), + possible: None, + }, + preliminary_surface: self.preliminary.clone(), + density_context: &mut context, + }, + aquifer.as_mut(), + &data.carving_blocks, + |_| true, + ) + .map_err(stage("carvers"))?; + } + worker.timings.carvers += lap(&mut clock); + chunk + .prime_heightmaps(&[ + HeightmapType::MotionBlocking, + HeightmapType::MotionBlockingNoLeaves, + HeightmapType::OceanFloor, + HeightmapType::WorldSurface, + ]) + .map_err(stage("heightmaps"))?; + chunk.set_generation_stage(PreLightChunkStage::Terrain); + let _ = sea; + Ok(ProtoChunk { + terrain: chunk, + biomes: center, + data: data.clone(), + decorated: false, + }) + } +} + +enum Biomes<'a, 'b> { + Region(&'a BiomeRegion), + Resolver( + &'a mut super::biome_source::BiomeSourceResolver<'b>, + &'a mut SamplerContext, + ), +} +/// Material-rule world queries for one chunk: shared seed-bound noises, the +/// worker's temperature caches and either stored or raw-resolver biomes. +struct SurfaceQueries<'a, 'b, R: RandomSource> { + pipeline: &'a Pipeline, + temperatures: &'a mut [BiomeTemperature], + biome: Biomes<'a, 'b>, + possible: Option>, +} +impl SurfaceQueries<'_, '_, R> { + fn temperature(&mut self, name: &str) -> Result<&mut BiomeTemperature, MaterialRuleError> { + let id = self + .pipeline + .data + .biome_id(name) + .ok_or(MaterialRuleError::MissingBiome)?; + Ok(&mut self.temperatures[id.0 as usize]) + } +} +impl MaterialSurfaceQueries for SurfaceQueries<'_, '_, R> { + fn surface_depth(&mut self, x: i32, z: i32) -> i32 { + self.pipeline.surface.surface_depth(x, z) + } + fn surface_secondary(&mut self, x: i32, z: i32) -> f64 { + self.pipeline.surface.surface_secondary(x, z) + } + fn band(&mut self, p: BlockPos) -> Result { + self.pipeline + .surface + .band([p.x, p.y, p.z]) + .ok_or(MaterialRuleError::InvalidBandIndex) + } + fn bind_noise(&mut self, name: &str) -> Result, DecodeError> { + self.pipeline + .noises + .get(&super::tags::identifier(name)?) + .cloned() + .ok_or(DecodeError::Field("unknown material noise")) + } + fn possible_biomes(&self) -> Option> { + self.possible.clone() + } + fn biome(&mut self, p: BlockPos) -> Result>, MaterialRuleError> { + let data = &self.pipeline.data; + let id = match &mut self.biome { + Biomes::Region(region) => *region + .biome(p) + .map_err(|_| MaterialRuleError::MissingBiome)?, + Biomes::Resolver(resolver, context) => { + let name = resolver + .sample(context, self.pipeline.zoom.quart_at_block(p)) + .map_err(|_| MaterialRuleError::BiomeQueryFailed)?; + data.biome_id(name).ok_or(MaterialRuleError::MissingBiome)? + } + }; + Ok(Some(data.biome_names[id.0 as usize].clone())) + } + fn cold_enough_to_snow( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self.temperature(name)?.cold_enough_to_snow(p, sea)) + } + fn melts_frozen_ocean( + &mut self, + name: &str, + p: BlockPos, + sea: i32, + ) -> Result { + Ok(self + .temperature(name)? + .should_melt_frozen_ocean_iceberg_slightly(p, sea)) + } +} + +fn lap(clock: &mut std::time::Instant) -> std::time::Duration { + let now = std::time::Instant::now(); + let elapsed = now - *clock; + *clock = now; + elapsed +} +/// Cumulative wall time spent by one worker in each proto-chunk stage. +#[derive(Clone, Copy, Debug, Default)] +pub struct StageTimings { + pub chunks: u64, + pub biomes: std::time::Duration, + /// Noise fill including aquifer setup. + pub noise: std::time::Duration, + pub surface: std::time::Duration, + /// Carving mask generation/application and final heightmap priming. + pub carvers: std::time::Duration, +} +/// Worker-owned mutable caches. Biome temperature caches mirror vanilla's +/// thread-local caches and never change results. +pub(super) struct WorkerState { + pub(super) temperatures: Vec, + biome_context: SamplerContext, + carver_context: SamplerContext, + timings: StageTimings, +} + +trait SeededPipeline: Send + Sync { + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result; + fn decorate( + &self, + worker: &mut WorkerState, + region: &mut [ProtoChunk; 9], + ) -> Result; + fn data(&self) -> &Arc; + fn sea_level(&self) -> i32; +} +impl SeededPipeline for Pipeline +where + R::Positional: Clone + Send + Sync, +{ + fn generate( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + ) -> Result { + Pipeline::generate(self, worker, pos) + } + fn decorate( + &self, + worker: &mut WorkerState, + region: &mut [ProtoChunk; 9], + ) -> Result { + match &self.decoration { + Some(decoration) => { + decoration.decorate(&self.data, self.seed, self.generation(), worker, region) + } + None => Err(resource("decoration resources were not loaded")), + } + } + fn data(&self) -> &Arc { + &self.data + } + fn sea_level(&self) -> i32 { + self.settings.sea_level + } +} + +/// Counters from one FEATURES pass. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct DecorateStats { + /// Placed-feature roots executed (including those that placed nothing). + pub placed: usize, + /// Roots skipped because their algorithm or bindings are not implemented. + pub unsupported: usize, + /// Roots that started but failed on an unavailable world query or error. + /// Their partial writes are kept, as each root reseeds its own random. + pub failed: usize, + /// Identifiers of skipped or failed roots, for diagnostics. + pub skipped: BTreeSet, +} + +/// A seed-bound generator for one dimension, shareable across worker threads. +#[derive(Clone)] +pub struct OverworldGenerator { + pipeline: Arc, +} +impl OverworldGenerator { + /// The `minecraft:overworld` dimension of the `minecraft:normal` world preset. + pub fn new(data: Arc, seed: i64) -> Result { + Self::for_dimension(data, seed, "minecraft:normal", "minecraft:overworld") + } + /// Any noise-generator dimension of a bundled world preset. + pub fn for_dimension( + data: Arc, + seed: i64, + preset: &str, + dimension: &str, + ) -> Result { + let preset_json: Value = serde_json::from_str( + data.world_presets + .get(preset) + .ok_or_else(|| resource(format!("missing world preset {preset}")))?, + )?; + let generator = preset_json["dimensions"][dimension]["generator"].clone(); + if generator["type"].as_str() != Some("minecraft:noise") { + return Err(resource(format!("{dimension} is not a noise generator"))); + } + let settings_json: Value = match &generator["settings"] { + Value::String(name) => serde_json::from_str( + data.settings + .get(name) + .ok_or_else(|| resource(format!("missing noise settings {name}")))?, + )?, + inline => inline.clone(), + }; + let pipeline: Arc = if settings_json["legacy_random_source"] + .as_bool() + .unwrap_or(false) + { + Arc::new(Pipeline::new( + data, + seed, + LegacyRandom::new(seed), + &generator, + &settings_json, + )?) + } else { + Arc::new(Pipeline::new( + data, + seed, + XoroshiroRandom::new(seed), + &generator, + &settings_json, + )?) + }; + Ok(Self { pipeline }) + } + pub fn data(&self) -> &Arc { + self.pipeline.data() + } + pub fn sea_level(&self) -> i32 { + self.pipeline.sea_level() + } + /// Create per-thread state. Workers are cheap; keep one per thread. + pub fn worker(&self) -> GeneratorWorker { + let data = self.pipeline.data(); + GeneratorWorker { + pipeline: self.pipeline.clone(), + state: WorkerState { + temperatures: data + .temperatures + .iter() + .map(|s| BiomeTemperature::new(*s)) + .collect(), + biome_context: SamplerContext::cached(), + carver_context: SamplerContext::default(), + timings: StageTimings::default(), + }, + } + } +} + +/// Per-thread generation state. +pub struct GeneratorWorker { + pipeline: Arc, + state: WorkerState, +} +impl GeneratorWorker { + /// Biomes, noise fill and aquifers, material surface and carvers: the + /// vanilla statuses up to TERRAIN. Independent of neighbor chunks' state. + pub fn generate_proto(&mut self, pos: ChunkPos) -> Result { + let result = self.pipeline.generate(&mut self.state, pos); + self.state.timings.chunks += 1; + result + } + pub fn stage_timings(&self) -> StageTimings { + self.state.timings + } + /// FEATURES status for `region[4]`. The region is a 3×3 neighborhood in + /// row-major order: index `(dz + 1) * 3 + (dx + 1)` around the center. + /// Writes may reach the neighbors, as in vanilla. Unsupported features are + /// skipped and counted. On error, chunks keep partial writes. + pub fn decorate( + &mut self, + region: &mut [ProtoChunk; 9], + ) -> Result { + self.pipeline.decorate(&mut self.state, region) + } +} diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs new file mode 100644 index 000000000..eaf78f14e --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -0,0 +1,27 @@ +//! FEATURES status over a 3×3 neighborhood of generated chunks. +use super::{ + anchor::WorldGenerationContext, + biome_source::ResolvedBiomeSource, + generator::{DecorateStats, GeneratorData, GeneratorError, ProtoChunk, WorkerState}, +}; +use std::sync::Arc; + +pub(super) struct Decoration; +impl Decoration { + pub(super) fn new( + _data: &Arc, + _source: &ResolvedBiomeSource, + ) -> Result, GeneratorError> { + Ok(None) + } + pub(super) fn decorate( + &self, + _data: &Arc, + _seed: i64, + _generation: WorldGenerationContext, + _worker: &mut WorkerState, + _region: &mut [ProtoChunk; 9], + ) -> Result { + Ok(DecorateStats::default()) + } +} diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index bfbac9c45..6d96390e8 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -15,6 +15,46 @@ except ImportError: import test_model_baking_parity as baking +WORLDGEN_BUNDLES = { + 'noises': 'worldgen/noise', 'densities': 'worldgen/density_function', 'rules': 'worldgen/material_rule', + 'conditions': 'worldgen/material_condition', 'settings': 'worldgen/noise_settings', 'carvers': 'worldgen/carver', + 'biomes': 'worldgen/biome', 'world_presets': 'worldgen/world_preset', 'features': 'worldgen/feature', + 'placed_features': 'worldgen/placed_feature', 'state_providers': 'worldgen/block_state_provider', + 'biome_tags': 'tags/worldgen/biome', 'feature_tags': 'tags/worldgen/feature', 'block_tags': 'tags/block', + 'fluid_tags': 'tags/fluid'} + + +def prepare_worldgen(root, jars, local): + """Write the chunk generator's resource bundle to root/worldgen (see GeneratorData::load).""" + out = root / 'worldgen' + out.mkdir(exist_ok=True) + with zipfile.ZipFile(jars['server']) as server, zipfile.ZipFile(jars['client']) as client: + for name, path in WORLDGEN_BUNDLES.items(): + prefix = f'data/minecraft/{path}/' + def extract(archive): + return {'minecraft:'+n[len(prefix):-5]: archive.read(n).decode('utf-8') + for n in sorted(archive.namelist()) if n.startswith(prefix) and n.endswith('.json')} + resources = extract(server) + if not resources or resources != extract(client): + raise ValueError('Reference worldgen resources disagree: '+path) + (out/(name+'.json')).write_text(json.dumps(resources, separators=(',', ':')), encoding='utf-8') + facts = json.loads((root/'facts.json').read_text()) + (out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':'))) + reports = out/'biome_parameters' + reports.mkdir(exist_ok=True) + for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']: + if (source/'overworld.json').exists(): + for report in sorted(source.glob('*.json')): + (reports/report.name).write_bytes(report.read_bytes()) + break + else: + # Fall back to the Java-exported quantized tables from the material-stage parity run. + presets = local/'rust-material-stage-parity/presets.json' + if not presets.exists(): + raise FileNotFoundError('No multi-noise biome parameter tables; run the data generator reports') + (out/'presets.json').write_bytes(presets.read_bytes()) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--prepare', action='store_true', help='Fetch pinned reference artifacts first') @@ -160,8 +200,9 @@ def main(): check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) (root/'render-definitions.json').write_bytes((export/'definitions.json').read_bytes()) (root/'occlusion.nbt').write_bytes((export/'occlusion.nbt').read_bytes()) + prepare_worldgen(root, jars, lab.LOCAL) count = 0 - prefixes = ('assets/minecraft/blockstates/', 'assets/minecraft/models/block/', + prefixes =('assets/minecraft/blockstates/', 'assets/minecraft/models/block/', 'assets/minecraft/textures/block/') with zipfile.ZipFile(jars['client']) as archive: version = json.loads(archive.read('version.json')) From 939eabe62715e657607416310d29c15569d721e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:04:38 +0200 Subject: [PATCH 2/5] Speed up section palette writes and noise-fill heightmap updates Section palettes hash state IDs with a multiplicative hasher instead of SipHash, and fill_noise skips heightmap updates at or below first-available - 2, which are no-ops. Material-stage parity output is byte-identical to vanilla. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/chunk.rs | 30 +++++++++++++++-- crates/horizon-world/src/worldgen/terrain.rs | 35 ++++++++++++-------- 2 files changed, 48 insertions(+), 17 deletions(-) diff --git a/crates/horizon-world/src/chunk.rs b/crates/horizon-world/src/chunk.rs index f049334f6..f4341c92f 100644 --- a/crates/horizon-world/src/chunk.rs +++ b/crates/horizon-world/src/chunk.rs @@ -357,9 +357,33 @@ impl ChunkData { /// Resident section: 4,096 blocks stored as numeric palette entries. Uniform /// sections have no word array; property strings live in the shared registry. +/// Multiplicative hash for dense state IDs; section palettes are hashed on +/// every block write, where SipHash dominated generation profiles. +#[derive(Default)] +struct StateIdHasher(u64); +impl std::hash::Hasher for StateIdHasher { + fn finish(&self) -> u64 { + self.0 + } + fn write(&mut self, bytes: &[u8]) { + for &b in bytes { + self.0 = (self.0.rotate_left(8) ^ u64::from(b)).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } + } + fn write_u32(&mut self, value: u32) { + self.0 = (self.0 ^ u64::from(value)).wrapping_mul(0x9e37_79b9_7f4a_7c15); + } +} +type LocalIds = + std::collections::HashMap>; +fn local_ids(state: BlockStateId) -> LocalIds { + let mut ids = LocalIds::default(); + ids.insert(state, 0); + ids +} pub struct BlockSection<'r> { palette: Vec, - local_ids: std::collections::HashMap, + local_ids: LocalIds, counts: Vec, free: Vec, storage: Option, @@ -376,7 +400,7 @@ impl<'r> BlockSection<'r> { } Ok(Self { palette: vec![state], - local_ids: [(state, 0)].into(), + local_ids: local_ids(state), counts: vec![4096], free: Vec::new(), storage: None, @@ -474,7 +498,7 @@ impl<'r> BlockSection<'r> { } if self.counts[id as usize] == 4096 { self.palette = vec![state]; - self.local_ids = [(state, 0)].into(); + self.local_ids = local_ids(state); self.counts = vec![4096]; self.free.clear(); self.storage = None; diff --git a/crates/horizon-world/src/worldgen/terrain.rs b/crates/horizon-world/src/worldgen/terrain.rs index b5c1eac4c..a9b7ed349 100644 --- a/crates/horizon-world/src/worldgen/terrain.rs +++ b/crates/horizon-world/src/worldgen/terrain.rs @@ -482,10 +482,20 @@ pub fn fill_noise( chunk.ensure_heightmap(HeightmapType::WorldSurfaceWg); let mut density = vec![0.; volume.size()]; final_density.sample_volume(context, &mut density, volume)?; + const MAPS: [HeightmapType; 2] = [HeightmapType::OceanFloorWg, HeightmapType::WorldSurfaceWg]; for z in 0..sz { let world_z = bz.wrapping_add(z as i32); for x in 0..sx { let world_x = bx.wrapping_add(x as i32); + // Heightmap updates at or below first-available - 2 are no-ops; the + // bound only changes through an update, so skip those calls. + let mut settled = MAPS.map(|kind| { + chunk.heightmaps[kind as usize] + .as_ref() + .expect("ensured heightmap") + .first_available(x as i32, z as i32) + .map(|first| first.wrapping_sub(2)) + }); for y in (0..sy).rev() { let world_y = by.wrapping_add(y as i32); let value = density[volume.index([x, y, z]).expect("valid density coordinates")]; @@ -496,20 +506,17 @@ pub fn fill_noise( continue; } chunk.set_block_raw(x as i32, world_y, z as i32, state)?; - chunk.update_heightmap( - HeightmapType::OceanFloorWg, - x as i32, - world_y, - z as i32, - state, - )?; - chunk.update_heightmap( - HeightmapType::WorldSurfaceWg, - x as i32, - world_y, - z as i32, - state, - )?; + for (kind, settled) in MAPS.into_iter().zip(&mut settled) { + if matches!(settled, Ok(bound) if world_y <= *bound) { + continue; + } + chunk.update_heightmap(kind, x as i32, world_y, z as i32, state)?; + *settled = chunk.heightmaps[kind as usize] + .as_ref() + .expect("ensured heightmap") + .first_available(x as i32, z as i32) + .map(|first| first.wrapping_sub(2)); + } if aquifer.should_schedule_fluid_update() && chunk.blocks.properties.heightmap_state(state).has_fluid() { From 8178ccede22c0bf94c1472414ff331174f0b91ed Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:04:38 +0200 Subject: [PATCH 3/5] Decorate generated chunks with implemented placed features Resolve each possible biome's placed features in vanilla encounter order into a FeatureDecorationPlan and run FEATURES over a 3x3 neighborhood through a WorldGenRegion-style adapter (write radius, zoomed biomes, biome filters, freeze/snow weather). Roots whose algorithm or bindings are missing are skipped and reported. Add worker stage timings, CPU-time reporting in the bench, and a parameter-report quantization test. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../horizon-world/examples/chunkgen_bench.rs | 24 + .../src/worldgen/feature_region.rs | 4 + .../horizon-world/src/worldgen/generator.rs | 38 ++ .../src/worldgen/generator_decoration.rs | 467 +++++++++++++++++- 4 files changed, 521 insertions(+), 12 deletions(-) diff --git a/crates/horizon-world/examples/chunkgen_bench.rs b/crates/horizon-world/examples/chunkgen_bench.rs index 484237780..7fb326643 100644 --- a/crates/horizon-world/examples/chunkgen_bench.rs +++ b/crates/horizon-world/examples/chunkgen_bench.rs @@ -146,6 +146,20 @@ fn verify(data: &std::sync::Arc, parity: &Path) -> Result<(), Err } } +/// Process CPU seconds (Linux), robust against other load on shared machines. +fn cpu_seconds() -> f64 { + fs::read_to_string("/proc/self/stat") + .ok() + .and_then(|stat| { + let fields = stat + .rsplit_once(')')? + .1 + .split_whitespace() + .collect::>(); + Some((fields[11].parse::().ok()? + fields[12].parse::().ok()?) / 100.) + }) + .unwrap_or(0.) +} fn glyph(name: &str) -> char { let name = name.strip_prefix("minecraft:").unwrap_or(name); match name { @@ -206,6 +220,7 @@ fn main() -> Result<(), Error> { let next = AtomicUsize::new(0); let slots: Vec>> = (0..count).map(|_| Mutex::new(None)).collect(); let timings = Mutex::new(Vec::new()); + let cpu = cpu_seconds(); let start = Instant::now(); std::thread::scope(|scope| -> Result<(), Error> { let handles = (0..threads) @@ -232,6 +247,10 @@ fn main() -> Result<(), Error> { count as f64 / elapsed.as_secs_f64(), elapsed.as_secs_f64() * 1000. * threads as f64 / count as f64 ); + println!( + " cpu time {:.1} ms/chunk", + (cpu_seconds() - cpu) * 1000. / count as f64 + ); let timings = timings.into_inner().unwrap(); let per_chunk = |f: fn(&StageTimings) -> std::time::Duration| { timings @@ -319,6 +338,11 @@ fn main() -> Result<(), Error> { totals.unsupported, totals.failed ); + if std::env::var_os("HORIZON_FEATURE_ERRORS").is_some() { + for (name, error) in generator.unsupported_features() { + println!("unsupported {name}: {error}"); + } + } if !totals.skipped.is_empty() { println!( "skipped roots: {}", diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 8939d24f9..73d9f05c5 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -177,6 +177,10 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { self.sea_level = sea_level; self } + /// Release the resident chunks, ordered by X then Z; match them by position. + pub fn into_chunks(self) -> Vec> { + self.chunks.into_values().collect() + } pub fn chunks(&self) -> impl Iterator> { self.chunks.values() } diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 876f1dbb9..3a4647278 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -473,6 +473,9 @@ impl ProtoChunk { pub fn is_decorated(&self) -> bool { self.decorated } + pub(super) fn set_decorated(&mut self) { + self.decorated = true; + } /// Highest non-air block + 1 in the column (WORLD_SURFACE). pub fn surface_height(&self, x: i32, z: i32) -> i32 { self.terrain @@ -1029,6 +1032,7 @@ trait SeededPipeline: Send + Sync { ) -> Result; fn data(&self) -> &Arc; fn sea_level(&self) -> i32; + fn unsupported_features(&self) -> Vec<(String, String)>; } impl SeededPipeline for Pipeline where @@ -1059,6 +1063,12 @@ where fn sea_level(&self) -> i32 { self.settings.sea_level } + fn unsupported_features(&self) -> Vec<(String, String)> { + self.decoration + .as_ref() + .map(super::generator_decoration::Decoration::unsupported) + .unwrap_or_default() + } } /// Counters from one FEATURES pass. @@ -1137,6 +1147,11 @@ impl OverworldGenerator { pub fn sea_level(&self) -> i32 { self.pipeline.sea_level() } + /// Placed features of this dimension's biomes that decoration skips because + /// their algorithm or bindings are not implemented, with the decode error. + pub fn unsupported_features(&self) -> Vec<(String, String)> { + self.pipeline.unsupported_features() + } /// Create per-thread state. Workers are cheap; keep one per thread. pub fn worker(&self) -> GeneratorWorker { let data = self.pipeline.data(); @@ -1183,3 +1198,26 @@ impl GeneratorWorker { self.pipeline.decorate(&mut self.state, region) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parameter_reports_quantize_like_vanilla() { + let report = r#"{"biomes":[{"biome":"minecraft:plains","parameters":{ + "temperature":[-0.45,-0.15],"humidity":[-1.0,-0.35],"continentalness":[-0.11,0.03], + "erosion":[0.45,0.55],"depth":0.0,"weirdness":[-0.2633,-0.05],"offset":0.0}}]}"#; + let table: Value = + serde_json::from_str(&quantize_parameter_report(report).unwrap()).unwrap(); + assert_eq!( + table, + serde_json::json!([{"coordinates":[[-4500,-1500],[-10000,-3500],[-1100,300], + [4500,5500],[0,0],[-2633,-500]],"offset":0,"biome":"minecraft:plains"}]) + ); + assert!( + quantize_parameter_report(r#"{"biomes":[{"parameters":{"temperature":"x"}}]}"#) + .is_err() + ); + } +} diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index eaf78f14e..e298de8cc 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -1,27 +1,470 @@ //! FEATURES status over a 3×3 neighborhood of generated chunks. +//! +//! Placed features are resolved by name from the bundled feature registries. +//! Roots whose algorithm or bindings are not implemented are left out of +//! execution (but keep their place in vanilla's per-step feature ordering, so +//! decoration seeds of the remaining features are unchanged). use super::{ anchor::WorldGenerationContext, + biome::BiomeId, + biome_chunk::BiomeRegion, + biome_predicate::BiomePredicateBindings, biome_source::ResolvedBiomeSource, - generator::{DecorateStats, GeneratorData, GeneratorError, ProtoChunk, WorkerState}, + biome_temperature::BiomeTemperature, + biome_weather::BiomeWeatherBindings, + block_feature::FeatureBlockBindings, + decoration::{DecorationWorld, FeatureDecorationPlan}, + feature::{FeatureBlocks, FeatureWorld}, + feature_catalog::FeatureCatalog, + feature_graph::PlacedFeatureDefinition, + feature_region::{RegionError, TerrainRegion}, + feature_sort::FeatureIdentity, + generator::{ + DecorateStats, GenBlockStates, GeneratorData, GeneratorError, ProtoChunk, WorkerState, + }, + placement::{LayerBlock, PlacementContext, PlacementQueryError}, + tags::TagDefinitions, + terrain::PreLightChunkStage, + write_zone::GenerationWriteZone, +}; +use crate::{ + fluid::{FluidKind, FluidState}, + heightmap::{HeightmapState, HeightmapType}, + registry::BlockStateId, +}; +use horizon_core::{ + biome::obfuscate_seed, + position::{BlockPos, ChunkPos}, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, }; -use std::sync::Arc; -pub(super) struct Decoration; +pub(super) struct Decoration { + plan: FeatureDecorationPlan, + names: Vec, + /// Executable roots by identity, or why the root cannot be executed. + features: Vec>, + /// Placed features of each biome's generation settings, by BiomeId. + biome_features: Vec>, + bindings: FeatureBlockBindings<'static>, + weather: Option, + blocks: FeatureBlocks, +} +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} +/// Biomes in vanilla's possible-biome encounter order for this source. +fn possible_biomes(source: &ResolvedBiomeSource) -> Vec { + let mut seen = BTreeSet::new(); + let ordered: Vec = match source { + ResolvedBiomeSource::MultiNoise(source) => source + .parameters() + .entries() + .iter() + .map(|(_, name)| name.clone()) + .collect(), + ResolvedBiomeSource::End(source) => [ + &source.center, + &source.highlands, + &source.midlands, + &source.islands, + &source.barrens, + ] + .into_iter() + .cloned() + .collect(), + other => other + .possible_biomes() + .into_iter() + .map(str::to_owned) + .collect(), + }; + ordered + .into_iter() + .filter(|name| seen.insert(name.clone())) + .collect() +} impl Decoration { pub(super) fn new( - _data: &Arc, - _source: &ResolvedBiomeSource, + data: &Arc, + source: &ResolvedBiomeSource, ) -> Result, GeneratorError> { - Ok(None) + let Some(resources) = &data.feature_resources else { + return Ok(None); + }; + let registry = data.registry(); + let mut feature_tags = TagDefinitions::default(); + for (name, json) in &resources.feature_tags { + feature_tags.apply_json(name, "vanilla", json)?; + } + let catalog = + FeatureCatalog::from_resources(&resources.features, &resources.placed, &feature_tags)?; + let biomes = Arc::new(BiomePredicateBindings::new( + &data + .biome_names() + .iter() + .enumerate() + .map(|(i, name)| (name.to_string(), BiomeId(i as u32))) + .collect(), + &data.biome_tags, + )?); + let bindings = + FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? + .with_fluid_tags(&resources.fluid_tags)? + .with_biomes(biomes); + let tags = feature_tags + .build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned())) + .map_err(|e| resource(format!("feature tags: {e:?}")))? + .tags; + let mut ids = BTreeMap::::new(); + let mut names = Vec::new(); + let mut features = Vec::new(); + let mut identity = |name: &str| -> FeatureIdentity { + *ids.entry(name.to_owned()).or_insert_with(|| { + let id = FeatureIdentity(names.len() as u32); + names.push(name.to_owned()); + features.push( + catalog + .placed_feature_with_blocks(&Value::from(name).to_string(), &bindings) + .map_err(|e| e.to_string()), + ); + id + }) + }; + let mut biome_features = vec![BTreeSet::new(); data.biome_names().len()]; + let mut plan = Vec::new(); + for name in possible_biomes(source) { + let id = data + .biome_id(&name) + .ok_or_else(|| resource(format!("unknown biome {name}")))?; + let json: Value = serde_json::from_str(data.biome_json(id))?; + let mut steps = Vec::new(); + for step in json["features"].as_array().into_iter().flatten() { + let mut list = Vec::new(); + let entries = match step { + Value::String(tag) if tag.starts_with('#') => tags + .get(&super::tags::identifier(&tag[1..])?) + .cloned() + .ok_or_else(|| resource(format!("unknown feature tag {tag}")))?, + Value::String(name) => vec![name.clone()], + Value::Array(values) => values + .iter() + .map(|v| { + v.as_str() + .map(str::to_owned) + .ok_or_else(|| resource("inline placed feature in biome")) + }) + .collect::>()?, + _ => return Err(resource("biome feature step")), + }; + for entry in entries { + let feature = identity(&super::tags::identifier(&entry)?); + list.push(feature); + biome_features[id.0 as usize].insert(feature); + } + steps.push(list); + } + plan.push((id, steps)); + } + let plan = FeatureDecorationPlan::new(plan).map_err(|e| resource(e.to_string()))?; + let weather = BiomeWeatherBindings::new(&bindings).ok(); + Ok(Some(Self { + plan, + names, + features, + biome_features, + weather, + blocks: FeatureBlocks::from_registry(registry)?, + bindings, + })) + } + /// Placed-feature roots that cannot run, with their decode errors. + pub(super) fn unsupported(&self) -> Vec<(String, String)> { + self.names + .iter() + .zip(&self.features) + .filter_map(|(name, feature)| feature.as_ref().err().map(|e| (name.clone(), e.clone()))) + .collect() } pub(super) fn decorate( &self, - _data: &Arc, - _seed: i64, - _generation: WorldGenerationContext, - _worker: &mut WorkerState, - _region: &mut [ProtoChunk; 9], + data: &Arc, + seed: i64, + generation: WorldGenerationContext, + worker: &mut WorkerState, + region: &mut [ProtoChunk; 9], ) -> Result { - Ok(DecorateStats::default()) + let center = region[4].position(); + for (i, chunk) in region.iter().enumerate() { + let expected = ChunkPos::new( + center.x.wrapping_add(i as i32 % 3 - 1), + center.z.wrapping_add(i as i32 / 3 - 1), + ); + if chunk.position() != expected { + return Err(resource("decoration region is not a 3×3 neighborhood")); + } + if (chunk.terrain.generation_stage() as u8) < PreLightChunkStage::Terrain as u8 { + return Err(resource("decoration requires terrain-stage chunks")); + } + } + if region[4].is_decorated() { + return Ok(DecorateStats::default()); + } + let mut chunks = Vec::with_capacity(9); + let mut biomes = Vec::with_capacity(9); + let (min_y, height) = (region[4].terrain.min_y(), region[4].terrain.height()); + for chunk in region.iter_mut() { + let empty = super::terrain::TerrainChunk::new( + chunk.position(), + min_y, + height, + data.registry(), + data.block_states().clone(), + ) + .map_err(|e| resource(e.to_string()))?; + chunks.push(std::mem::replace(&mut chunk.terrain, empty)); + biomes.push(chunk.biomes().clone()); + } + let terrain = TerrainRegion::new(chunks, generation) + .and_then(|region| region.with_block_bindings(&self.bindings)); + let terrain = match terrain { + Ok(terrain) => terrain, + Err(e) => return Err(resource(e.to_string())), + }; + let mut world = World { + region: terrain, + biomes: BiomeRegion::new(biomes, obfuscate_seed(seed)) + .map_err(|e| resource(e.to_string()))?, + zone: GenerationWriteZone::new(center, 1), + decoration: self, + temperatures: &mut worker.temperatures, + }; + let mut stats = DecorateStats::default(); + let blocks = self.blocks; + let result = self.plan.decorate_features( + &mut world, + center, + seed, + |world, placer, random, id, origin| { + let Ok(feature) = &self.features[id.0 as usize] else { + stats.unsupported += 1; + stats.skipped.insert(self.names[id.0 as usize].clone()); + return Ok(false); + }; + stats.placed += 1; + let placed = placer.place_with_biome_check( + &feature.placement, + world, + random, + origin, + id, + |world, random, p| feature.feature.place(world, random, p, blocks), + ); + if placed.is_err() { + stats.failed += 1; + stats.skipped.insert(self.names[id.0 as usize].clone()); + } + Ok(placed.unwrap_or(false)) + }, + ); + for terrain in world.region.into_chunks() { + let p = terrain.position(); + let index = (p.z.wrapping_sub(center.z) + 1) * 3 + p.x.wrapping_sub(center.x) + 1; + region[index as usize].terrain = terrain; + } + result.map_err(|e| GeneratorError::Stage("features", e.to_string()))?; + region[4] + .terrain + .set_generation_stage(PreLightChunkStage::Features); + region[4].set_decorated(); + Ok(stats) + } +} + +/// WorldGenRegion-style view: reads anywhere in the 3×3 region, writes within +/// the FEATURES step's write radius, biome lookups through the biome zoom. +struct World<'a> { + region: TerrainRegion<'static, GenBlockStates>, + biomes: BiomeRegion, + zone: GenerationWriteZone, + decoration: &'a Decoration, + temperatures: &'a mut [BiomeTemperature], +} +impl DecorationWorld for World<'_> { + type Error = RegionError; + fn min_section_y(&mut self) -> Result { + Ok(self + .region + .min_y() + .map_err(|_| RegionError::InvalidChunks)? + >> 4) + } + fn chunk_biomes(&mut self, chunk: ChunkPos) -> Result, RegionError> { + self.biomes + .present_in_chunk(chunk) + .map_err(RegionError::Biome) + } + fn set_currently_generating(&mut self, _: Option) -> Result<(), RegionError> { + Ok(()) + } +} +impl FeatureWorld for World<'_> { + type Error = RegionError; + fn block(&mut self, position: [i32; 3]) -> Result { + self.region.block(position) + } + fn set_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + _flags: i32, + ) -> Result { + if !self + .zone + .contains_block(BlockPos::new(position[0], position[1], position[2])) + { + return Ok(false); + } + self.region.set_block_worldgen(position, state)?; + Ok(true) + } +} +fn query(e: impl std::fmt::Display) -> PlacementQueryError { + PlacementQueryError::Failed(e.to_string()) +} +impl PlacementContext for World<'_> { + fn destroy_block_without_entity( + &mut self, + position: [i32; 3], + _drop_resources: bool, + ) -> Result { + let chunk = self.region.chunk(position[0] >> 4, position[2] >> 4)?; + let state = chunk.block(position[0], position[1], position[2]); + if chunk.block_properties(state).is_air() { + return Ok(false); + } + let air = self + .decoration + .bindings + .registry() + .default_state("minecraft:air") + .ok_or(PlacementQueryError::Unavailable)?; + self.set_block(position, air, 3).map_err(query) + } + fn biome_should_freeze( + &mut self, + biome: BiomeId, + position: [i32; 3], + require_edge: bool, + ) -> Result { + let weather = self + .decoration + .weather + .clone() + .ok_or(PlacementQueryError::Unavailable)?; + let settings = self.temperatures[biome.0 as usize].settings(); + let mut temperature = std::mem::replace( + &mut self.temperatures[biome.0 as usize], + BiomeTemperature::new(settings), + ); + let result = weather.should_freeze(self, &mut temperature, position, require_edge); + self.temperatures[biome.0 as usize] = temperature; + result + } + fn biome_should_snow( + &mut self, + biome: BiomeId, + position: [i32; 3], + ) -> Result { + let weather = self + .decoration + .weather + .clone() + .ok_or(PlacementQueryError::Unavailable)?; + let settings = self.temperatures[biome.0 as usize].settings(); + let mut temperature = std::mem::replace( + &mut self.temperatures[biome.0 as usize], + BiomeTemperature::new(settings), + ); + let result = weather.should_snow(self, &mut temperature, position); + self.temperatures[biome.0 as usize] = temperature; + result + } + /// Lighting has not run during FEATURES; block light reads zero. + fn block_brightness(&mut self, _: [i32; 3]) -> Result { + Ok(0) + } + fn fluid_state(&mut self, position: [i32; 3]) -> Result { + self.region.fluid_state(position) + } + fn sea_level(&mut self) -> Result { + self.region.sea_level() + } + fn schedule_fluid_tick( + &mut self, + position: [i32; 3], + fluid: FluidKind, + delay: i32, + ) -> Result<(), PlacementQueryError> { + self.region.schedule_fluid_tick(position, fluid, delay) + } + fn mark_postprocessing(&mut self, position: [i32; 3]) -> Result<(), PlacementQueryError> { + self.region.mark_postprocessing(position) + } + fn water_at(&mut self, position: [i32; 3]) -> Result { + self.region.water_at(position) + } + fn schedule_block_tick( + &mut self, + position: [i32; 3], + block: BlockStateId, + delay: i32, + ) -> Result<(), PlacementQueryError> { + self.region.schedule_block_tick(position, block, delay) + } + fn biome_identity(&mut self, position: [i32; 3]) -> Result { + self.region + .biome_at( + &self.biomes, + BlockPos::new(position[0], position[1], position[2]), + ) + .copied() + .map_err(Into::into) + } + fn biome_allows_feature( + &mut self, + position: [i32; 3], + feature: FeatureIdentity, + ) -> Result { + let biome = self.biome_identity(position)?; + Ok(self.decoration.biome_features[biome.0 as usize].contains(&feature)) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.region.block_state(position) + } + fn block_matches_tag( + &mut self, + position: [i32; 3], + tag: &str, + ) -> Result { + self.region.block_matches_tag(position, tag) + } + fn max_y(&mut self) -> Result { + self.region.max_y() + } + fn layer_block(&mut self, position: [i32; 3]) -> Result { + self.region.layer_block(position) + } + fn generation(&self) -> WorldGenerationContext { + self.region.generation() + } + fn min_y(&mut self) -> Result { + self.region.min_y() + } + fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { + self.region.height(kind, x, z) } } From 42f89606048fba0fbbe407908862f87f5aa0da76 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:23:48 +0200 Subject: [PATCH 4/5] WIP: checkpoint interrupted agent work Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 1 + .../horizon-world/src/worldgen/generator.rs | 37 +++- .../src/worldgen/generator_blocks.rs | 161 ++++++++++++++++++ .../src/worldgen/generator_decoration.rs | 150 +++++++++++++++- tools/prepare_native_client.py | 15 ++ 5 files changed, 359 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/generator_blocks.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index a9828cc18..f9cf00a62 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -34,6 +34,7 @@ pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; pub mod generator; +mod generator_blocks; mod generator_decoration; pub mod height_provider; pub mod material_condition; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 3a4647278..e3fe337aa 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -142,6 +142,9 @@ pub(super) struct FeatureResources { pub(super) placed: BTreeMap, pub(super) feature_tags: BTreeMap, pub(super) fluid_tags: BTreeMap>, + pub(super) state_providers: BTreeMap, + /// Block properties, support, collision and survival for placement checks. + pub(super) blocks: Option, } /// Seed-independent generation resources, loaded once and shared by every @@ -255,7 +258,8 @@ impl GeneratorData { /// per registry state. Multi-noise tables come from `presets.json` /// (quantized) or `biome_parameters/.json` data-generator reports. /// Optional decoration inputs: `features`, `placed_features`, - /// `feature_tags`, `fluid_tags`. Integer block properties are derived from + /// `feature_tags`, `fluid_tags`, `state_providers` and the Java-exported + /// block behavior files in `blocks/` (see `generator_blocks`). Integer block properties are derived from /// the registry: properties whose every value is a decimal integer. pub fn load(dir: &Path, registry: &'static BlockRegistry) -> Result, GeneratorError> { let flags: Vec<(bool, bool)> = @@ -376,7 +380,15 @@ impl GeneratorData { features, placed, feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), + blocks: super::generator_blocks::BlockBehavior::load( + &dir.join("blocks"), + registry, + &block_tags, + &fluid_tags, + )?, fluid_tags, + state_providers: read_optional_bundle(dir, "state_providers")? + .unwrap_or_default(), }) } _ => None, @@ -512,11 +524,12 @@ struct Pipeline { extensions: MaterialExtensions, picker: GlobalFluidPicker, zoom: BiomeZoom, - biome_cache: Mutex>>>, + biome_cache: BiomeCache, carver_cache: Mutex>, pub(super) decoration: Option, } const CACHE_LIMIT: usize = 16384; +type BiomeCache = Mutex>>>; fn state(registry: &BlockRegistry, raw: &Value) -> Result { let name = raw @@ -1052,7 +1065,25 @@ where ) -> Result { match &self.decoration { Some(decoration) => { - decoration.decorate(&self.data, self.seed, self.generation(), worker, region) + let center = region[4].position(); + // WorldGenRegion's level random, positioned at the center chunk. + let mut random = self + .root + .from_hash_of("minecraft:worldgen_region_random") + .fork_positional() + .at(BlockPos::new( + center.x.wrapping_shl(4), + 0, + center.z.wrapping_shl(4), + )); + decoration.decorate( + &self.data, + self.seed, + self.generation(), + worker, + region, + || random.next_boolean(), + ) } None => Err(resource("decoration resources were not loaded")), } diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs new file mode 100644 index 000000000..262a8cb2d --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -0,0 +1,161 @@ +//! Optional block-behavior registries used by feature placement: physical +//! properties, face support, collision and survival rules. Loaded from the +//! bundle's `blocks/` directory (Java-exported, see prepare_native_client.py). +use super::generator::GeneratorError; +use crate::{ + block_collision::BlockCollisionRegistry, + block_properties::BlockPropertiesRegistry, + block_support::BlockSupportRegistry, + block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule}, + collision::CachedCollisionRegistry, + nbt::{self, Limits, Tag}, + registry::BlockRegistry, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, + sync::Arc, +}; + +pub(super) struct BlockBehavior { + pub(super) properties: BlockPropertiesRegistry<'static>, + pub(super) support: Arc>, + pub(super) collision: Arc>, + pub(super) survival: BlockSurvivalRegistry<'static>, + pub(super) double_plants: BTreeSet, + pub(super) mossy_carpets: BTreeSet, +} +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} +fn rule(name: &str) -> Option { + use SurvivalRule::*; + if let Some(tag) = name.strip_prefix("TagBelow:") { + return Some(TagBelow(tag.to_owned())); + } + Some(match name { + "CactusFlower" => CactusFlower, + "Seagrass" => Seagrass, + "BubbleColumn" => BubbleColumn, + "RedstoneWire" => RedstoneWire, + "DoublePlant" => DoublePlant, + "Door" => Door, + "BigDripleaf" => BigDripleaf, + "BigDripleafStem" => BigDripleafStem, + "Farmland" => Farmland, + "Cocoa" => Cocoa, + "Crop" => Crop, + "GrowingPlant" => GrowingPlant, + "MangrovePropagule" => MangrovePropagule, + "Speleothem" => Speleothem, + "Scaffolding" => Scaffolding, + "PistonHead" => PistonHead, + "ChorusPlant" => ChorusPlant, + "ChorusFlower" => ChorusFlower, + "PitcherCrop" => PitcherCrop, + "Multiface" => Multiface, + "Vine" => Vine, + "HangingMoss" => HangingMoss, + "SnowLayer" => SnowLayer, + "SeaPickle" => SeaPickle, + "Fire" => Fire, + "Cactus" => Cactus, + "Path" => Path, + "Mushroom" => Mushroom, + "Bell" => Bell, + "SugarCane" => SugarCane, + "LilyPad" => LilyPad, + "Frogspawn" => Frogspawn, + "SporeBlossom" => SporeBlossom, + "SmallDripleaf" => SmallDripleaf, + "TallSeagrass" => TallSeagrass, + "Always" => Always, + "SolidBelow" => SolidBelow, + "SolidBehind" => SolidBehind, + "NonAirBelow" => NonAirBelow, + "MossCarpet" => MossCarpet, + "CenterBelow" => CenterBelow, + "Lantern" => Lantern, + "FullAbove" => FullAbove, + "FullBehind" => FullBehind, + "RigidOrCenterBelow" => RigidOrCenterBelow, + "RigidBelow" => RigidBelow, + "FullBelow" => FullBelow, + "CenterAbove" => CenterAbove, + "FaceAttached" => FaceAttached, + "SupportsBamboo" => SupportsBamboo, + _ => return None, + }) +} +impl BlockBehavior { + /// Files: `block-properties.nbt`, `cached-collision.nbt`, + /// `cached-support.nbt`, `survival-rules.json`, + /// `survival-extra-definitions.json` and `placement-definitions.json`. + pub(super) fn load( + dir: &Path, + registry: &'static BlockRegistry, + tags: &BTreeMap>, + fluid_tags: &BTreeMap>, + ) -> Result, GeneratorError> { + if !dir.join("block-properties.nbt").exists() { + return Ok(None); + } + let read = |name: &str| -> Result { + let limits = Limits { + max_bytes: 1 << 28, + ..Limits::default() + }; + Ok(nbt::read_named(&fs::read(dir.join(name))?, limits) + .map_err(|e| resource(format!("{name}: {e:?}")))? + .0 + .tag) + }; + let json = |name: &str| -> Result { + Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) + }; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; + let properties = BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; + let support = Arc::new(BlockSupportRegistry::from_nbt( + &read("cached-support.nbt")?, + registry, + )?); + let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); + let rules = json("survival-rules.json")? + .as_object() + .ok_or_else(|| resource("survival rules"))? + .iter() + .map(|(name, value)| { + let text = value.as_str().unwrap_or_default(); + rule(text) + .map(|rule| (name.clone(), rule)) + .ok_or_else(|| resource(format!("unknown survival rule {text}"))) + }) + .collect::>()?; + let extra = json("survival-extra-definitions.json")?; + let definitions = SurvivalDefinitions { + rules, + ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?, + fence_gates: serde_json::from_value(extra["fence_gates"].clone())?, + }; + let survival = BlockSurvivalRegistry::new( + registry, + &properties, + support.clone(), + collision.clone(), + &definitions, + tags, + fluid_tags, + )?; + let placement = json("placement-definitions.json")?; + Ok(Some(Self { + double_plants: serde_json::from_value(placement["double_plants"].clone())?, + mossy_carpets: serde_json::from_value(placement["mossy_carpets"].clone())?, + properties, + support, + collision, + survival, + })) + } +} diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index e298de8cc..09cfe1b07 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -27,13 +27,23 @@ use super::{ terrain::PreLightChunkStage, write_zone::GenerationWriteZone, }; +use super::{ + generator_blocks::BlockBehavior, + state_provider::{StateProviderBindings, StateProviderCatalog}, +}; use crate::{ + block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, + block_placement::BlockPlacementBindings, + block_support::SupportType, + block_survival::SurvivalWorld, + dynamic_support::DynamicSupportWorld, fluid::{FluidKind, FluidState}, heightmap::{HeightmapState, HeightmapType}, registry::BlockStateId, }; use horizon_core::{ biome::obfuscate_seed, + geometry::{Direction, VoxelShape}, position::{BlockPos, ChunkPos}, }; use serde_json::Value; @@ -111,10 +121,31 @@ impl Decoration { .collect(), &data.biome_tags, )?); - let bindings = + let mut bindings = FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? .with_fluid_tags(&resources.fluid_tags)? - .with_biomes(biomes); + .with_biomes(biomes.clone()); + if let Some(blocks) = &resources.blocks { + bindings = bindings + .with_block_properties(&blocks.properties)? + .with_state_providers( + StateProviderBindings::new( + registry, + data.integers().clone(), + &data.block_tags, + )? + .with_block_properties(&blocks.properties)? + .with_fluid_tags(&resources.fluid_tags)? + .with_biomes(biomes), + StateProviderCatalog::from_resources(&resources.state_providers)?, + BlockPlacementBindings::new( + registry, + &blocks.properties, + &blocks.double_plants, + &blocks.mossy_carpets, + )?, + )?; + } let tags = feature_tags .build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned())) .map_err(|e| resource(format!("feature tags: {e:?}")))? @@ -196,6 +227,7 @@ impl Decoration { generation: WorldGenerationContext, worker: &mut WorkerState, region: &mut [ProtoChunk; 9], + next_boolean: impl FnMut() -> bool, ) -> Result { let center = region[4].position(); for (i, chunk) in region.iter().enumerate() { @@ -234,7 +266,13 @@ impl Decoration { Ok(terrain) => terrain, Err(e) => return Err(resource(e.to_string())), }; + let mut next_boolean = next_boolean; let mut world = World { + next_boolean: &mut next_boolean, + blocks: data + .feature_resources + .as_ref() + .and_then(|r| r.blocks.as_ref()), region: terrain, biomes: BiomeRegion::new(biomes, obfuscate_seed(seed)) .map_err(|e| resource(e.to_string()))?, @@ -287,6 +325,8 @@ impl Decoration { /// WorldGenRegion-style view: reads anywhere in the 3×3 region, writes within /// the FEATURES step's write radius, biome lookups through the biome zoom. struct World<'a> { + next_boolean: &'a mut dyn FnMut() -> bool, + blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, zone: GenerationWriteZone, @@ -335,7 +375,113 @@ impl FeatureWorld for World<'_> { fn query(e: impl std::fmt::Display) -> PlacementQueryError { PlacementQueryError::Failed(e.to_string()) } +impl<'a> World<'a> { + fn blocks(&self) -> Result<&'a BlockBehavior, PlacementQueryError> { + self.blocks.ok_or(PlacementQueryError::Unavailable) + } +} +/// Proto chunks hold no block entities, so dynamic shapes resolve to absent. +impl DynamicSupportWorld for World<'_> { + type Error = PlacementQueryError; + fn shulker_is_closed(&mut self, _: [i32; 3]) -> Result, PlacementQueryError> { + Ok(None) + } + fn moving_piston_shape( + &mut self, + _: [i32; 3], + ) -> Result, PlacementQueryError> { + Ok(None) + } +} +impl DynamicCollisionWorld for World<'_> { + fn shulker_collision_state( + &mut self, + _: [i32; 3], + ) -> Result, PlacementQueryError> { + Ok(None) + } +} +impl SurvivalWorld for World<'_> { + fn fluid_state(&mut self, position: [i32; 3]) -> Result { + self.region.fluid_state(position) + } + /// Unlit generation chunks report no sky or block light. + fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> Result { + Ok(0) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.region.block_state(position) + } +} impl PlacementContext for World<'_> { + fn state_collision_empty( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + let collision = self.blocks()?.collision.clone(); + collision + .collision_shape(self, state, position) + .map(|shape| shape.is_empty()) + .map_err(query) + } + /// Block entities are not stored in proto chunks; loot tables are no-ops. + fn set_block_entity_loot_table( + &mut self, + _: [i32; 3], + _: &str, + _: &mut impl horizon_core::random::RandomSource, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn attachment_at( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let blocks = self.blocks()?; + blocks + .survival + .can_attach_to(self, position, direction) + .map_err(query) + } + fn next_world_boolean(&mut self) -> Result { + Ok((self.next_boolean)()) + } + fn block_survives( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + let blocks = self.blocks()?; + blocks + .survival + .can_survive(self, state, position) + .map_err(query) + } + fn face_sturdy( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let state = self.region.block_state(position)?; + self.state_face_sturdy(state, position, direction) + } + fn state_face_sturdy( + &mut self, + state: BlockStateId, + position: [i32; 3], + direction: Direction, + ) -> Result { + let support = self.blocks()?.support.clone(); + support + .is_face_sturdy(self, state, position, direction, SupportType::Full) + .map_err(query) + } + /// Generation regions contain no entities. + fn unobstructed_block(&mut self, _: [i32; 3]) -> Result { + Ok(true) + } fn destroy_block_without_entity( &mut self, position: [i32; 3], diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 6d96390e8..f5dd4372c 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -42,12 +42,27 @@ def prepare_worldgen(root, jars, local): (out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':'))) reports = out/'biome_parameters' reports.mkdir(exist_ok=True) + presets = reports for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']: if (source/'overworld.json').exists(): for report in sorted(source.glob('*.json')): (reports/report.name).write_bytes(report.read_bytes()) break else: + presets = None + # Block behavior used by feature placement checks (survival, support, collision). + # These come from the Java exporters of the simple-block parity run. + behavior = local/'rust-simple-block-parity' + blocks = out/'blocks' + names = ['block-properties.nbt', 'cached-collision.nbt', 'cached-support.nbt', 'survival-rules.json', + 'survival-extra-definitions.json', 'placement-definitions.json'] + if all((behavior/name).exists() for name in names): + blocks.mkdir(exist_ok=True) + for name in names: + (blocks/name).write_bytes((behavior/name).read_bytes()) + else: + print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration') + if presets is None: # Fall back to the Java-exported quantized tables from the material-stage parity run. presets = local/'rust-material-stage-parity/presets.json' if not presets.exists(): From b6e6ac06ca567c2bdc0cd5dcfee430c05fa65a36 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:30:45 +0200 Subject: [PATCH 5/5] WIP: checkpoint remaining interrupted agent changes Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen/generator_blocks.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index 262a8cb2d..390fb338c 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -115,8 +115,10 @@ impl BlockBehavior { let json = |name: &str| -> Result { Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) }; - let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; - let properties = BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; + let collisions = + CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; + let properties = + BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; let support = Arc::new(BlockSupportRegistry::from_nbt( &read("cached-support.nbt")?, registry,