diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index f26871605..a58b25457 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -61,6 +61,7 @@ pub mod speleothem; pub mod spike; pub mod spring; pub mod state_provider; +pub mod structure; pub mod tags; pub mod terrain; pub mod tree; diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index ee61e3f35..a901a583d 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -30,10 +30,19 @@ pub struct FeatureBlockBindings<'r> { pub(crate) tags: BTreeMap>>, pub(crate) air: [BlockStateId; 3], tree_blocks: std::sync::OnceLock>, + pub(crate) structures: Option>, } impl<'r> FeatureBlockBindings<'r> { /// Shared tree/vegetation classifications, built on first use. Requires /// state-provider and block-property bindings. + /// Bind structure templates and processor lists for template features. + pub fn with_structures( + mut self, + structures: Arc, + ) -> Self { + self.structures = Some(structures); + self + } pub(crate) fn tree_blocks(&self) -> Result, DecodeError> { if let Some(blocks) = self.tree_blocks.get() { return Ok(blocks.clone()); @@ -154,6 +163,7 @@ impl<'r> FeatureBlockBindings<'r> { .collect(), tags: bound_tags, tree_blocks: std::sync::OnceLock::new(), + structures: None, air: [ get("minecraft:air")?, get("minecraft:cave_air")?, diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 68408a30e..014ea3f42 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -86,6 +86,8 @@ pub enum FeatureDefinition { SteppedColumnCluster(Box), FallenTree(Box), NoOp, + Template(Box), + Fossil(Box), WeightedChoice(OptionalWeightedList), Sequence(Vec), Overlay(Vec), @@ -312,6 +314,16 @@ impl FeatureDefinition { )?)?; match kind.as_str() { "minecraft:no_op" => Ok(Self::NoOp), + "minecraft:template" => super::structure::features::TemplateFeature::decode( + json, + blocks.ok_or(DecodeError::Field("template bindings"))?, + ) + .map(|f| Self::Template(Box::new(f))), + "minecraft:fossil" => super::structure::features::FossilFeature::decode( + json, + blocks.ok_or(DecodeError::Field("fossil bindings"))?, + ) + .map(|f| Self::Fossil(Box::new(f))), "minecraft:freeze_top_layer" => super::snow_freeze::SnowAndFreezeFeature::new( blocks.ok_or(DecodeError::Field("snow and freeze bindings"))?, ) @@ -843,6 +855,12 @@ impl FeatureDefinition { .place(world, random, origin, run.blocks) .map_err(FeatureExecutionError::Basic), Self::NoOp => Ok(true), + Self::Template(feature) => feature + .place(world, random, origin) + .map_err(FeatureExecutionError::Query), + Self::Fossil(feature) => feature + .place(world, random, origin) + .map_err(FeatureExecutionError::Query), Self::SnowAndFreeze(feature) => feature .place(world, origin) .map_err(FeatureExecutionError::SnowAndFreeze), diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index e3fe337aa..2458cb705 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -170,6 +170,8 @@ pub struct GeneratorData { pub(super) block_tags: BTreeMap>, pub(super) biome_tags: BTreeMap>, pub(super) feature_resources: Option, + /// Templates, processor lists and per-state template transforms. + pub(super) structures: Option>, } type Bundle = BTreeMap; fn read_bundle(dir: &Path, name: &str) -> Result { @@ -393,7 +395,18 @@ impl GeneratorData { } _ => None, }; + let structures = match fs::read_to_string(dir.join("blocks/structure-blocks.json")) { + Ok(json) => Some(Arc::new(super::structure::StructureResources::new( + registry, + super::structure::StateTransforms::from_json(&json, registry.len())?, + &dir.join("structure"), + read_optional_bundle(dir, "processor_lists")?.unwrap_or_default(), + &block_tags, + ))), + Err(_) => None, + }; Ok(Arc::new(Self { + structures, registry, states: GenBlockStates(states.into()), integers, @@ -452,6 +465,9 @@ pub struct ProtoChunk { biomes: BiomeChunk, data: Arc, decorated: bool, + /// Block-entity data placed by structures and template features, in + /// placement order (positions are absolute block coordinates). + pub block_entities: Vec<([i32; 3], crate::nbt::Compound)>, } impl ProtoChunk { pub fn position(&self) -> ChunkPos { @@ -919,6 +935,7 @@ where biomes: center, data: data.clone(), decorated: false, + block_entities: Vec::new(), }) } } diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index fc3a65f97..047bd7053 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -125,6 +125,9 @@ impl Decoration { FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? .with_fluid_tags(&resources.fluid_tags)? .with_biomes(biomes.clone()); + if let Some(structures) = &data.structures { + bindings = bindings.with_structures(structures.clone()); + } if let Some(blocks) = &resources.blocks { bindings = bindings .with_block_properties(&blocks.properties)? @@ -268,7 +271,12 @@ impl Decoration { Err(e) => return Err(resource(e.to_string())), }; let mut next_boolean = next_boolean; + let mut block_entities = Vec::new(); + for chunk in region.iter_mut() { + block_entities.append(&mut chunk.block_entities); + } let mut world = World { + block_entities, next_boolean: &mut next_boolean, blocks: data .feature_resources @@ -309,6 +317,14 @@ impl Decoration { Ok(placed.unwrap_or(false)) }, ); + for (pos, nbt) in std::mem::take(&mut world.block_entities) { + let index = ((pos[2] >> 4).wrapping_sub(center.z) + 1) * 3 + + (pos[0] >> 4).wrapping_sub(center.x) + + 1; + if let Some(chunk) = usize::try_from(index).ok().and_then(|i| region.get_mut(i)) { + chunk.block_entities.push((pos, nbt)); + } + } 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; @@ -326,6 +342,7 @@ 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> { + block_entities: Vec<([i32; 3], crate::nbt::Compound)>, next_boolean: &'a mut dyn FnMut() -> bool, blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, @@ -370,6 +387,7 @@ impl FeatureWorld for World<'_> { return Ok(false); } self.region.set_block_worldgen(position, state)?; + self.block_entities.retain(|(p, _)| *p != position); Ok(true) } } @@ -497,6 +515,15 @@ impl PlacementContext for World<'_> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } + fn set_block_entity( + &mut self, + position: [i32; 3], + nbt: crate::nbt::Compound, + ) -> Result<(), PlacementQueryError> { + self.block_entities.retain(|(p, _)| *p != position); + self.block_entities.push((position, nbt)); + Ok(()) + } fn world_seed(&mut self) -> Result { self.region.world_seed() } diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index d00bec6c4..f64dadf94 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -285,6 +285,15 @@ pub trait PlacementContext { fn layer_block(&mut self, _position: [i32; 3]) -> Result { Err(PlacementQueryError::Unavailable) } + /// Store block-entity data loaded at a just-placed block (structure + /// templates). Worlds without block-entity storage drop it. + fn set_block_entity( + &mut self, + _position: [i32; 3], + _nbt: crate::nbt::Compound, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } fn generation(&self) -> WorldGenerationContext; /// Recreate the generation bounds for a block-predicate invocation. World /// adapters may perform fallible level/generator queries here; ordinary diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs new file mode 100644 index 000000000..ee12ef5ff --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -0,0 +1,340 @@ +//! Structure templates, processors and placement shared by template features +//! and structure pieces. +pub mod features; +pub mod processor; +pub mod template; + +use crate::{ + nbt::{self, Limits}, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::Direction; +use processor::ProcessorList; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + io::Read, + path::{Path, PathBuf}, + sync::{Arc, RwLock}, +}; +pub use template::{BlockInfo, JigsawInfo, StructureTemplate}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Rotation { + None, + Clockwise90, + Clockwise180, + Counterclockwise90, +} +impl Rotation { + pub const ALL: [Self; 4] = [ + Self::None, + Self::Clockwise90, + Self::Clockwise180, + Self::Counterclockwise90, + ]; + pub fn from_name(name: &str) -> Option { + Some(match name { + "none" => Self::None, + "clockwise_90" => Self::Clockwise90, + "180" => Self::Clockwise180, + "counterclockwise_90" => Self::Counterclockwise90, + _ => return None, + }) + } + /// Rotation.getRandom: one bounded draw over the four values. + pub fn random(random: &mut impl horizon_core::random::RandomSource) -> Self { + Self::ALL[random.next_int_bound(4).unwrap_or(0) as usize] + } + pub fn rotate_direction(self, direction: Direction) -> Direction { + if matches!(direction, Direction::Up | Direction::Down) { + return direction; + } + let order = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + ]; + let index = order.iter().position(|d| *d == direction).unwrap(); + order[(index + self as usize) % 4] + } + pub fn get_rotated(self, other: Self) -> Self { + Self::ALL[(self as usize + other as usize) % 4] + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Mirror { + None, + LeftRight, + FrontBack, +} + +/// Inclusive integer box (vanilla BoundingBox). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct BoundingBox { + pub min: [i32; 3], + pub max: [i32; 3], +} +impl BoundingBox { + pub fn new(min: [i32; 3], max: [i32; 3]) -> Self { + Self { min, max } + } + pub fn from_corners(a: [i32; 3], b: [i32; 3]) -> Self { + Self { + min: std::array::from_fn(|i| a[i].min(b[i])), + max: std::array::from_fn(|i| a[i].max(b[i])), + } + } + pub fn moved(self, d: [i32; 3]) -> Self { + Self { + min: std::array::from_fn(|i| self.min[i] + d[i]), + max: std::array::from_fn(|i| self.max[i] + d[i]), + } + } + pub fn is_inside(&self, p: [i32; 3]) -> bool { + (0..3).all(|i| p[i] >= self.min[i] && p[i] <= self.max[i]) + } + pub fn intersects(&self, other: &Self) -> bool { + (0..3).all(|i| self.max[i] >= other.min[i] && self.min[i] <= other.max[i]) + } + pub fn encapsulate(&mut self, other: &Self) { + for i in 0..3 { + self.min[i] = self.min[i].min(other.min[i]); + self.max[i] = self.max[i].max(other.max[i]); + } + } + pub fn inflated(self, xz: i32, y: i32) -> Self { + Self { + min: [self.min[0] - xz, self.min[1] - y, self.min[2] - xz], + max: [self.max[0] + xz, self.max[1] + y, self.max[2] + xz], + } + } + pub fn span(&self) -> [i32; 3] { + std::array::from_fn(|i| self.max[i] - self.min[i] + 1) + } + pub fn center(&self) -> [i32; 3] { + std::array::from_fn(|i| self.min[i] + (self.max[i] - self.min[i] + 1) / 2) + } + pub fn corners(&self) -> [[i32; 3]; 8] { + let (a, b) = (self.min, self.max); + [ + [a[0], a[1], a[2]], + [a[0], a[1], b[2]], + [a[0], b[1], a[2]], + [a[0], b[1], b[2]], + [b[0], a[1], a[2]], + [b[0], a[1], b[2]], + [b[0], b[1], a[2]], + [b[0], b[1], b[2]], + ] + } +} + +/// Per-state BlockState.rotate/mirror results and template ordering flags, +/// exported from vanilla (`blocks/structure-blocks.json`). +#[derive(Debug, Default)] +pub struct StateTransforms { + rotate: Vec<[u32; 3]>, + mirror: Vec<[u32; 2]>, + full: Vec, + loot: BTreeSet, +} +impl StateTransforms { + pub fn from_json(json: &str, states: usize) -> Result { + let value: serde_json::Value = serde_json::from_str(json)?; + let arr = |key: &'static str| { + value[key] + .as_array() + .cloned() + .ok_or(super::DecodeError::Field(key)) + }; + let ids = |v: &serde_json::Value| -> Vec { + v.as_array() + .map(|a| { + a.iter() + .filter_map(|x| x.as_u64()) + .map(|x| x as u32) + .collect() + }) + .unwrap_or_default() + }; + let rotate = arr("rotate")? + .iter() + .map(|v| { + let v = ids(v); + [v[0], v[1], v[2]] + }) + .collect::>(); + let mirror = arr("mirror")? + .iter() + .map(|v| { + let v = ids(v); + [v[0], v[1]] + }) + .collect::>(); + let full = arr("full_block")? + .iter() + .map(|v| v.as_bool().unwrap_or(false)) + .collect::>(); + if rotate.len() != states || mirror.len() != states || full.len() != states { + return Err(super::DecodeError::Field("structure block table size")); + } + let loot = ids(&value["loot_containers"]) + .into_iter() + .map(BlockStateId) + .collect(); + Ok(Self { + rotate, + mirror, + full, + loot, + }) + } + pub fn rotate(&self, state: BlockStateId, rotation: Rotation) -> BlockStateId { + match rotation { + Rotation::None => state, + r => self + .rotate + .get(state.0 as usize) + .map_or(state, |t| BlockStateId(t[r as usize - 1])), + } + } + pub fn mirror(&self, state: BlockStateId, mirror: Mirror) -> BlockStateId { + match mirror { + Mirror::None => state, + m => self + .mirror + .get(state.0 as usize) + .map_or(state, |t| BlockStateId(t[m as usize - 1])), + } + } + pub fn full_block(&self, state: BlockStateId) -> bool { + self.full.get(state.0 as usize).copied().unwrap_or(false) + } + pub fn loot_container(&self, state: BlockStateId) -> bool { + self.loot.contains(&state) + } +} + +/// Lazily loaded templates (`structure//.nbt`, gzip NBT) and +/// processor lists, shared by all generators of one resource bundle. +pub struct StructureResources { + pub registry: &'static BlockRegistry, + pub transforms: StateTransforms, + dir: PathBuf, + templates: RwLock>>>, + pub processor_lists: BTreeMap, + jigsaw_states: BTreeMap, + pub(crate) waterlogged: HashMap, + sources: BTreeSet, + /// Block names in each block tag, for processors matching tags by block. + pub block_tags: BTreeMap>, +} +impl std::fmt::Debug for StructureResources { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("StructureResources") + } +} +impl StructureResources { + pub fn new( + registry: &'static BlockRegistry, + transforms: StateTransforms, + dir: &Path, + processor_lists: BTreeMap, + block_tags: &BTreeMap>, + ) -> Self { + let mut sources = BTreeSet::new(); + let fluids = crate::fluid::FluidStateTable::new(registry).ok(); + let mut jigsaw_states = BTreeMap::new(); + let mut waterlogged = HashMap::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + let state = registry.state(id).unwrap(); + if state.name == "minecraft:jigsaw" { + let orientation = state + .properties + .get("orientation") + .cloned() + .unwrap_or_default(); + let front = orientation.split('_').next().unwrap_or(""); + jigsaw_states.insert(id, !matches!(front, "up" | "down")); + } + if fluids + .as_ref() + .and_then(|table| table.get(id)) + .is_some_and(|fluid| fluid.is_source()) + { + sources.insert(id); + } + if state.properties.get("waterlogged").map(String::as_str) == Some("false") { + let mut wet = state.clone(); + wet.properties.insert("waterlogged".into(), "true".into()); + if let Some(wet) = registry.id(&wet) { + waterlogged.insert(id, wet); + } + } + } + Self { + registry, + transforms, + dir: dir.to_owned(), + templates: RwLock::new(HashMap::new()), + processor_lists, + jigsaw_states, + waterlogged, + sources, + block_tags: block_tags + .iter() + .map(|(k, v)| (k.clone(), v.iter().cloned().collect())) + .collect(), + } + } + /// StructureTemplateManager.getOrCreate; missing templates are None. + pub fn template(&self, id: &str) -> Option> { + let id = if id.contains(':') { + id.to_owned() + } else { + format!("minecraft:{id}") + }; + if let Some(found) = self.templates.read().unwrap().get(&id) { + return found.clone(); + } + let (namespace, path) = id.split_once(':').unwrap(); + let file = self.dir.join(namespace).join(format!("{path}.nbt")); + let loaded = std::fs::read(&file).ok().and_then(|bytes| { + let mut raw = Vec::new(); + flate2::read::GzDecoder::new(bytes.as_slice()) + .read_to_end(&mut raw) + .ok()?; + let limits = Limits { + max_bytes: 1 << 28, + ..Limits::default() + }; + let tag = nbt::read_named(&raw, limits).ok()?.0.tag; + Some(Arc::new(StructureTemplate::from_nbt( + &tag, + self.registry, + &self.transforms, + ))) + }); + self.templates.write().unwrap().insert(id, loaded.clone()); + loaded + } + /// Whether the state's fluid is a source (water/lava level 0, waterlogged). + pub fn source_fluid(&self, state: BlockStateId) -> bool { + self.sources.contains(&state) + } + pub fn jigsaw_horizontal(&self, state: BlockStateId) -> Option { + self.jigsaw_states.get(&state).copied() + } + pub fn processor_list( + &self, + json: &str, + bindings: &super::block_feature::FeatureBlockBindings<'_>, + ) -> Result { + ProcessorList::decode(json, self, bindings) + } + pub fn is_jigsaw(&self, state: BlockStateId) -> bool { + self.jigsaw_states.contains_key(&state) + } +} diff --git a/crates/horizon-world/src/worldgen/structure/features.rs b/crates/horizon-world/src/worldgen/structure/features.rs new file mode 100644 index 000000000..63e9a494a --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/features.rs @@ -0,0 +1,231 @@ +//! The `template` and `fossil` configured features. +use super::{ + BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate, + processor::{PlaceSettings, ProcessorList, place_in_world}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + weighted::WeightedList, + }, +}; +use horizon_core::random::RandomSource; +use serde_json::{Value, value::RawValue}; +use std::sync::Arc; + +fn resources(bindings: &FeatureBlockBindings<'_>) -> Result, DecodeError> { + bindings + .structures + .clone() + .ok_or(DecodeError::Field("structure template bindings")) +} +fn template( + resources: &StructureResources, + id: &str, +) -> Result, DecodeError> { + resources + .template(id) + .ok_or_else(|| DecodeError::Registry(format!("missing structure template {id}"))) +} + +#[derive(Clone, Debug)] +pub struct TemplateFeature { + templates: WeightedList<(Arc, Vec)>, + processors: ProcessorList, + resources: Arc, +} +impl TemplateFeature { + pub fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let resources = resources(bindings)?; + let value: Value = serde_json::from_str(json)?; + let raw: Box = serde_json::from_str(&value["templates"].to_string())?; + let templates = WeightedList::decode(&raw, |entry| { + let entry: Value = serde_json::from_str(entry.get())?; + let id = entry["id"] + .as_str() + .ok_or(DecodeError::Field("template id"))?; + let rotations = match entry.get("rotations").and_then(Value::as_array) { + Some(list) => list + .iter() + .map(|r| { + r.as_str() + .and_then(Rotation::from_name) + .ok_or(DecodeError::Field("rotation")) + }) + .collect::, _>>()?, + None => Rotation::ALL.to_vec(), + }; + Ok((template(&resources, id)?, rotations)) + })?; + let processors = match value.get("processors") { + Some(p) => ProcessorList::decode(&p.to_string(), &resources, bindings)?, + None => ProcessorList::default(), + }; + Ok(Self { + templates, + processors, + resources, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result { + let invalid = |_| PlacementQueryError::Failed("template weights".into()); + let (template, rotations) = self.templates.sample(random).map_err(invalid)?; + let rotation = rotations[random + .next_int_bound(rotations.len() as i32) + .map_err(invalid)? as usize]; + // rotation.rotate(axis.getNegative()) * (size along axis / 2), for X then Z. + let mut pos = origin; + for (axis, negative) in [ + (0, horizon_core::geometry::Direction::West), + (2, horizon_core::geometry::Direction::North), + ] { + let step = rotation.rotate_direction(negative).normal(); + let length = template.size[axis] / 2; + for i in 0..3 { + pos[i] += step[i] * length; + } + } + let mut settings = PlaceSettings::new(rotation).add(&self.processors); + settings.random = Some(random); + place_in_world( + world, + &self.resources, + template, + pos, + pos, + &mut settings, + None, + 3, + ) + } +} + +#[derive(Clone, Debug)] +pub struct FossilFeature { + fossils: Vec<(Arc, Arc)>, + fossil_processors: ProcessorList, + overlay_processors: ProcessorList, + max_empty_corners: i32, + resources: Arc, +} +impl FossilFeature { + pub fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let resources = resources(bindings)?; + let value: Value = serde_json::from_str(json)?; + let list = |key: &'static str| -> Result>, DecodeError> { + value[key] + .as_array() + .ok_or(DecodeError::Field(key))? + .iter() + .map(|id| template(&resources, id.as_str().unwrap_or_default())) + .collect() + }; + let (base, overlay) = (list("fossil_structures")?, list("overlay_structures")?); + if base.is_empty() || base.len() != overlay.len() { + return Err(DecodeError::Field("fossil structure lists")); + } + Ok(Self { + fossils: base.into_iter().zip(overlay).collect(), + fossil_processors: ProcessorList::decode( + &value["fossil_processors"].to_string(), + &resources, + bindings, + )?, + overlay_processors: ProcessorList::decode( + &value["overlay_processors"].to_string(), + &resources, + bindings, + )?, + max_empty_corners: value["max_empty_corners_allowed"].as_i64().unwrap_or(0) as i32, + resources, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result { + let invalid = |_| PlacementQueryError::Failed("fossil bounds".into()); + let rotation = Rotation::random(random); + let index = random + .next_int_bound(self.fossils.len() as i32) + .map_err(invalid)? as usize; + let (base, overlay) = &self.fossils[index]; + let (cx, cz) = (origin[0] >> 4, origin[2] >> 4); + let bounds = BoundingBox::new( + [cx * 16 - 16, world.min_y()?, cz * 16 - 16], + [cx * 16 + 15 + 16, world.max_y()?, cz * 16 + 15 + 16], + ); + let size = base.size(rotation); + let low = [origin[0] - size[0] / 2, 0, origin[2] - size[2] / 2]; + let mut lowest = origin[1]; + for x in 0..size[0] { + for z in 0..size[2] { + lowest = lowest.min(world.height( + HeightmapType::OceanFloorWg, + low[0] + x, + low[2] + z, + )?); + } + } + let y = + (lowest - 15 - random.next_int_bound(10).map_err(invalid)?).max(world.min_y()? + 10); + let target = StructureTemplate::zero_position_with_transform( + [low[0], y, low[2]], + Mirror::None, + rotation, + base.size[0], + base.size[2], + ); + let mut empty = 0; + for corner in base + .bounding_box(target, rotation, [0; 3], Mirror::None) + .corners() + { + let state = world.block_state(corner)?; + let name = &self.resources.registry.state(state).unwrap().name; + if matches!( + name.as_str(), + "minecraft:air" + | "minecraft:cave_air" + | "minecraft:void_air" + | "minecraft:lava" + | "minecraft:water" + ) { + empty += 1; + } + } + if empty > self.max_empty_corners { + return Ok(false); + } + for (template, processors) in [ + (base, &self.fossil_processors), + (overlay, &self.overlay_processors), + ] { + let mut settings = PlaceSettings::new(rotation).add(processors); + settings.bounding_box = Some(bounds); + settings.random = Some(&mut *random); + place_in_world( + world, + &self.resources, + template, + target, + target, + &mut settings, + None, + 260, + )?; + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs new file mode 100644 index 000000000..4e50654d6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -0,0 +1,788 @@ +//! Structure processors (`worldgen/processor_list`) and template placement. +use super::{BlockInfo, BoundingBox, Mirror, Rotation, StructureResources, StructureTemplate}; +use crate::{ + fluid::FluidKind, + heightmap::HeightmapType, + nbt::{Compound, JavaString, Tag}, + registry::BlockStateId, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::{PlacementContext, PlacementQueryError}, + rule_test::RuleTest, + value_provider::IntProvider, + }, +}; +use horizon_core::{ + position::BlockPos, + random::{LegacyRandom, PositionalRandom, RandomSource, position_seed}, +}; +use serde_json::Value; +use std::{collections::BTreeSet, sync::Arc}; + +/// The draws processors make from StructurePlaceSettings' random. +pub trait ProcessorRandom { + fn float(&mut self) -> f32; + fn int(&mut self, bound: i32) -> i32; + fn long(&mut self) -> i64; +} +impl ProcessorRandom for R { + fn float(&mut self) -> f32 { + self.next_float() + } + fn int(&mut self, bound: i32) -> i32 { + self.next_int_bound(bound).unwrap_or(0) + } + fn long(&mut self) -> i64 { + self.next_long() + } +} + +#[derive(Clone, Debug)] +enum PosRule { + Always, + Linear { + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + axis: Option, + }, +} +#[derive(Clone, Debug)] +enum Modifier { + Passthrough, + Clear, + AppendLoot(String), + AppendStatic(Compound), +} +#[derive(Clone, Debug)] +pub struct Rule { + input: RuleTest, + location: RuleTest, + position: PosRule, + output: BlockStateId, + modifier: Modifier, +} +#[derive(Clone, Debug)] +pub enum Processor { + Nop, + BlockIgnore(BTreeSet), + BlockRot { + rottable: Option>>, + integrity: f32, + }, + Gravity { + heightmap: HeightmapType, + offset: i32, + }, + Rule(Vec), + Protected(Arc>), + Capped { + delegate: Box, + limit: IntProvider, + }, + JigsawReplacement, + BlockAge(f32), + LavaSubmerged, +} +#[derive(Clone, Debug, Default)] +pub struct ProcessorList(pub Vec); + +fn holder_set( + value: &Value, + bindings: &FeatureBlockBindings<'_>, +) -> Result>, DecodeError> { + let names: Vec<&str> = match value { + Value::String(s) => vec![s.as_str()], + Value::Array(a) => a.iter().filter_map(Value::as_str).collect(), + _ => return Err(DecodeError::Field("block holder set")), + }; + let mut out = BTreeSet::new(); + for name in names { + if let Some(tag) = name.strip_prefix('#') { + let tag = super::super::tags::identifier(tag)?; + out.extend( + bindings + .tags + .get(&tag) + .map(|s| s.iter().copied()) + .into_iter() + .flatten(), + ); + } else { + let name = super::super::tags::identifier(name)?; + out.extend( + bindings + .blocks + .get(&name) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))? + .iter() + .copied(), + ); + } + } + Ok(Arc::new(out)) +} +fn json_to_nbt(value: &Value) -> Tag { + match value { + Value::Bool(b) => Tag::Byte(i8::from(*b)), + Value::Number(n) => match n.as_i64() { + Some(i) if i32::try_from(i).is_ok() => Tag::Int(i as i32), + Some(i) => Tag::Long(i), + None => Tag::Double(n.as_f64().unwrap_or(0.).to_bits()), + }, + Value::String(s) => Tag::String(s.as_str().into()), + Value::Array(a) => Tag::List(a.iter().map(json_to_nbt).collect()), + Value::Object(o) => Tag::Compound( + o.iter() + .map(|(k, v)| (JavaString::from(k.as_str()), json_to_nbt(v))) + .collect(), + ), + Value::Null => Tag::End, + } +} +fn float(value: &Value, key: &'static str) -> Result { + value[key] + .as_f64() + .map(|v| v as f32) + .ok_or(DecodeError::Field(key)) +} +impl Processor { + fn decode( + value: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let kind = value["processor_type"] + .as_str() + .ok_or(DecodeError::Field("processor_type"))?; + let state = |v: &Value| -> Result { + bindings + .codec + .decode(&v.to_string(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }; + Ok(match super::super::tags::identifier(kind)?.as_str() { + "minecraft:nop" => Self::Nop, + "minecraft:block_ignore" => Self::BlockIgnore( + value["blocks"] + .as_array() + .ok_or(DecodeError::Field("block_ignore blocks"))? + .iter() + .map(|b| state(b).map(|id| resources.registry.state(id).unwrap().name.clone())) + .collect::>()?, + ), + "minecraft:block_rot" => Self::BlockRot { + rottable: match value.get("rottable_blocks") { + Some(v) => Some(holder_set(v, bindings)?), + None => None, + }, + integrity: float(value, "integrity")?, + }, + "minecraft:gravity" => Self::Gravity { + heightmap: match value.get("heightmap").and_then(Value::as_str) { + Some(name) => HeightmapType::ALL + .into_iter() + .find(|k| k.name() == name) + .ok_or(DecodeError::Field("gravity heightmap"))?, + None => HeightmapType::WorldSurfaceWg, + }, + offset: value.get("offset").and_then(Value::as_i64).unwrap_or(0) as i32, + }, + "minecraft:protected_blocks" => Self::Protected(holder_set(&value["value"], bindings)?), + "minecraft:jigsaw_replacement" => Self::JigsawReplacement, + "minecraft:block_age" => Self::BlockAge(float(value, "mossiness")?), + "minecraft:lava_submerged_block" => Self::LavaSubmerged, + "minecraft:capped" => Self::Capped { + delegate: Box::new(Self::decode(&value["delegate"], resources, bindings)?), + limit: IntProvider::from_json(&value["limit"].to_string())?, + }, + "minecraft:rule" => Self::Rule( + value["rules"] + .as_array() + .ok_or(DecodeError::Field("rules"))? + .iter() + .map(|rule| { + let test = |key| RuleTest::from_json(&rule[key].to_string(), bindings); + let position = match rule.get("position_predicate") { + Some(p) => match p["predicate_type"] + .as_str() + .unwrap_or("minecraft:always_true") + { + "minecraft:always_true" => PosRule::Always, + kind @ ("minecraft:linear_pos" + | "minecraft:axis_aligned_linear_pos") => PosRule::Linear { + min_chance: p + .get("min_chance") + .and_then(Value::as_f64) + .unwrap_or(0.) + as f32, + max_chance: p + .get("max_chance") + .and_then(Value::as_f64) + .unwrap_or(0.) + as f32, + min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) + as i32, + max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) + as i32, + axis: (kind == "minecraft:axis_aligned_linear_pos").then( + || match p.get("axis").and_then(Value::as_str) { + Some("x") => 0, + Some("z") => 2, + _ => 1, + }, + ), + }, + _ => return Err(DecodeError::Field("position predicate")), + }, + None => PosRule::Always, + }; + let modifier = match rule.get("block_entity_modifier") { + None => Modifier::Passthrough, + Some(m) => match m["type"].as_str().unwrap_or("") { + "minecraft:passthrough" => Modifier::Passthrough, + "minecraft:clear" => Modifier::Clear, + "minecraft:append_loot" => Modifier::AppendLoot( + m["loot_table"].as_str().unwrap_or_default().to_owned(), + ), + "minecraft:append_static" => match json_to_nbt(&m["data"]) { + Tag::Compound(c) => Modifier::AppendStatic(c), + _ => Modifier::AppendStatic(Compound::new()), + }, + _ => return Err(DecodeError::Field("block entity modifier")), + }, + }; + Ok(Rule { + input: test("input_predicate")?, + location: test("location_predicate")?, + position, + output: state(&rule["output_state"])?, + modifier, + }) + }) + .collect::>()?, + ), + _ => return Err(DecodeError::Field("structure processor type")), + }) + } + fn evaluates_entire_piece(&self) -> bool { + matches!(self, Self::Capped { .. }) + } +} +impl ProcessorList { + /// A processor list holder: a registry name, `{"processors": [...]}` or a list. + pub fn decode( + json: &str, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let value: Value = serde_json::from_str(json)?; + let value = match &value { + Value::String(name) => { + let name = super::super::tags::identifier(name)?; + let raw = resources.processor_lists.get(&name).ok_or_else(|| { + DecodeError::Registry(format!("unknown processor list {name}")) + })?; + serde_json::from_str(raw)? + } + other => other.clone(), + }; + let list = match &value { + Value::Array(a) => a.clone(), + Value::Object(_) => value["processors"].as_array().cloned().unwrap_or_default(), + _ => return Err(DecodeError::Field("processor list")), + }; + Ok(Self( + list.iter() + .map(|p| Processor::decode(p, resources, bindings)) + .collect::>()?, + )) + } +} + +/// StructurePlaceSettings without entity options. +pub struct PlaceSettings<'a> { + pub mirror: Mirror, + pub rotation: Rotation, + pub pivot: [i32; 3], + pub bounding_box: Option, + pub processors: Vec<&'a Processor>, + pub waterlogging: bool, + pub random: Option<&'a mut dyn ProcessorRandom>, +} +impl<'a> PlaceSettings<'a> { + pub fn new(rotation: Rotation) -> Self { + Self { + mirror: Mirror::None, + rotation, + pivot: [0; 3], + bounding_box: None, + processors: Vec::new(), + waterlogging: true, + random: None, + } + } + pub fn add(mut self, list: &'a ProcessorList) -> Self { + self.processors.extend(list.0.iter()); + self + } + /// settings.getRandom(pos): the shared random, else a position-seeded one. + fn with_random( + &mut self, + pos: [i32; 3], + f: impl FnOnce(&mut dyn ProcessorRandom) -> T, + ) -> T { + match self.random.as_deref_mut() { + Some(random) => f(random), + None => f(&mut LegacyRandom::new(position_seed(BlockPos::new( + pos[0], pos[1], pos[2], + )))), + } + } +} + +type ProcessResult = Result, PlacementQueryError>; +#[allow(clippy::too_many_arguments)] +fn process_block( + processor: &Processor, + world: &mut W, + resources: &StructureResources, + reference: [i32; 3], + relative: [i32; 3], + info: BlockInfo, + settings: &mut PlaceSettings<'_>, +) -> ProcessResult { + let registry = resources.registry; + let name = |id: BlockStateId| registry.state(id).map(|s| s.name.as_str()).unwrap_or(""); + Ok(match processor { + Processor::Nop => Some(info), + Processor::BlockIgnore(blocks) => (!blocks.contains(name(info.state))).then_some(info), + Processor::BlockRot { + rottable, + integrity, + } => { + let candidate = rottable + .as_ref() + .is_none_or(|set| set.contains(&info.state)); + let keep = settings.with_random(info.pos, |r| !candidate || r.float() <= *integrity); + keep.then_some(info) + } + Processor::Gravity { heightmap, offset } => { + let height = world.height(*heightmap, info.pos[0], info.pos[2])? + offset; + Some(BlockInfo { + pos: [info.pos[0], height + relative[1], info.pos[2]], + ..info + }) + } + Processor::Protected(set) => (!set.contains(&world.block_state(info.pos)?)).then_some(info), + Processor::JigsawReplacement => { + if !resources.is_jigsaw(info.state) { + return Ok(Some(info)); + } + let Some(nbt) = &info.nbt else { + return Ok(Some(info)); + }; + let text = match nbt.get(&JavaString::from("final_state")) { + Some(Tag::String(s)) => s.to_string_lossy(), + _ => "minecraft:air".to_owned(), + }; + let Some(state) = super::template::parse_state_string(registry, &text) else { + return Ok(None); + }; + (name(state) != "minecraft:structure_void").then_some(BlockInfo { + pos: info.pos, + state, + nbt: None, + }) + } + Processor::LavaSubmerged => { + let lava = name(world.block_state(info.pos)?) == "minecraft:lava"; + if lava && !resources.transforms.full_block(info.state) { + Some(BlockInfo { + state: registry.default_state("minecraft:lava").unwrap(), + ..info + }) + } else { + Some(info) + } + } + Processor::BlockAge(mossiness) => block_age(*mossiness, info, settings, resources), + Processor::Rule(rules) => { + let mut random = LegacyRandom::new(position_seed(BlockPos::new( + info.pos[0], + info.pos[1], + info.pos[2], + ))); + for rule in rules { + if !rule.input.test(info.state, info.pos, &mut random) { + continue; + } + let located = world.block_state(info.pos)?; + if !rule.location.test(located, info.pos, &mut random) { + continue; + } + let position_ok = match &rule.position { + PosRule::Always => true, + PosRule::Linear { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = match axis { + None => (0..3) + .map(|i| (info.pos[i] - reference[i]).abs()) + .sum::(), + Some(a) => { + let d: [f32; 3] = std::array::from_fn(|i| { + if i == *a { + ((info.pos[i] - reference[i]) as f32).abs() + } else { + 0. + } + }); + (d[0] + d[1] + d[2]) as i32 + } + }; + let roll = random.next_float(); + let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; + let chance = if t < 0. { + *min_chance + } else if t > 1. { + *max_chance + } else { + min_chance + t * (max_chance - min_chance) + }; + roll <= chance + } + }; + if !position_ok { + continue; + } + let nbt = match &rule.modifier { + Modifier::Passthrough => info.nbt.clone(), + Modifier::Clear => Some(Compound::new()), + Modifier::AppendLoot(table) => { + let mut nbt = info.nbt.clone().unwrap_or_default(); + nbt.insert("LootTable".into(), Tag::String(table.as_str().into())); + nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); + Some(nbt) + } + Modifier::AppendStatic(data) => { + let mut nbt = info.nbt.clone().unwrap_or_default(); + nbt.extend(data.clone()); + Some(nbt) + } + }; + return Ok(Some(BlockInfo { + pos: info.pos, + state: rule.output, + nbt, + })); + } + Some(info) + } + Processor::Capped { .. } => Some(info), + }) +} +fn block_age( + mossiness: f32, + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + resources: &StructureResources, +) -> Option { + let registry = resources.registry; + let state = registry.state(info.state)?.clone(); + let default = |n: &str| registry.default_state(n).unwrap(); + let with_props = |n: &str| { + let mut target = registry.state(default(n)).unwrap().clone(); + for (k, v) in &state.properties { + if target.properties.contains_key(k) { + target.properties.insert(k.clone(), v.clone()); + } + } + registry.id(&target).unwrap_or(default(n)) + }; + let random_stairs = |r: &mut dyn ProcessorRandom, n: &str| { + let facing = ["north", "east", "south", "west"][r.int(4) as usize]; + let half = ["top", "bottom"][r.int(2) as usize]; + let mut target = registry.state(default(n)).unwrap().clone(); + target.properties.insert("facing".into(), facing.into()); + target.properties.insert("half".into(), half.into()); + registry.id(&target).unwrap() + }; + let name = state.name.as_str(); + let is_tag = |tag: &str| { + // Tags are matched by block name through the template resources' bindings. + resources + .block_tags + .get(tag) + .is_some_and(|set| set.contains(name)) + }; + let new_state = settings.with_random(info.pos, |r| -> Option { + let pick = |r: &mut dyn ProcessorRandom, non: &[BlockStateId], mossy: &[BlockStateId]| { + if r.float() < mossiness { + mossy[r.int(mossy.len() as i32) as usize] + } else { + non[r.int(non.len() as i32) as usize] + } + }; + if matches!( + name, + "minecraft:stone_bricks" | "minecraft:stone" | "minecraft:chiseled_stone_bricks" + ) { + if r.float() >= 0.5 { + return None; + } + let non = [ + default("minecraft:cracked_stone_bricks"), + random_stairs(r, "minecraft:stone_brick_stairs"), + ]; + let mossy = [ + default("minecraft:mossy_stone_bricks"), + random_stairs(r, "minecraft:mossy_stone_brick_stairs"), + ]; + Some(pick(r, &non, &mossy)) + } else if is_tag("minecraft:stairs") { + if r.float() >= 0.5 { + return None; + } + let non = [ + default("minecraft:stone_slab"), + default("minecraft:stone_brick_slab"), + ]; + let mossy = [ + with_props("minecraft:mossy_stone_brick_stairs"), + default("minecraft:mossy_stone_brick_slab"), + ]; + Some(pick(r, &non, &mossy)) + } else if is_tag("minecraft:slabs") { + (r.float() < mossiness).then(|| with_props("minecraft:mossy_stone_brick_slab")) + } else if is_tag("minecraft:walls") { + (r.float() < mossiness).then(|| with_props("minecraft:mossy_stone_brick_wall")) + } else if name == "minecraft:obsidian" { + (r.float() < 0.15).then(|| default("minecraft:crying_obsidian")) + } else { + None + } + }); + Some(match new_state { + Some(state) => BlockInfo { state, ..info }, + None => info, + }) +} + +/// StructureTemplate.processBlockInfos. +fn process_infos( + world: &mut W, + resources: &StructureResources, + template: &StructureTemplate, + palette: usize, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, +) -> Result, PlacementQueryError> { + let whole = settings + .processors + .iter() + .any(|p| p.evaluates_entire_piece()); + let mut original = Vec::new(); + let mut processed = Vec::new(); + for info in template.palettes()[palette].blocks() { + let relative = StructureTemplate::transform( + info.pos, + settings.mirror, + settings.rotation, + settings.pivot, + ); + let pos = std::array::from_fn(|i| relative[i] + position[i]); + if !whole && settings.bounding_box.is_some_and(|b| !b.is_inside(pos)) { + continue; + } + let mut current = Some(BlockInfo { + pos, + state: info.state, + nbt: info.nbt.clone(), + }); + let processors = settings.processors.clone(); + for processor in processors { + let Some(value) = current.take() else { break }; + current = process_block( + processor, world, resources, reference, info.pos, value, settings, + )?; + } + if let Some(value) = current { + processed.push(value); + original.push(info.clone()); + } + } + let processors = settings.processors.clone(); + for processor in processors { + let Processor::Capped { delegate, limit } = processor else { + continue; + }; + if limit.bounds()[1] == 0 || processed.is_empty() || original.len() != processed.len() { + continue; + } + let seed = world.world_seed()?; + let mut random = LegacyRandom::new(seed).fork_positional().at(BlockPos::new( + position[0], + position[1], + position[2], + )); + let max = limit + .sample(&mut random) + .unwrap_or(0) + .min(processed.len() as i32); + if max < 1 { + continue; + } + let mut indices: Vec = (0..processed.len()).collect(); + for i in (2..=indices.len()).rev() { + let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; + indices.swap(i - 1, swap); + } + let mut replaced = 0; + for index in indices { + if replaced >= max { + break; + } + let before = processed[index].clone(); + let altered = process_block( + delegate, + world, + resources, + reference, + original[index].pos, + before.clone(), + settings, + )?; + if let Some(altered) = altered { + if altered != before { + replaced += 1; + processed[index] = altered; + } + } + } + } + Ok(processed) +} + +/// StructureTemplate.placeInWorld without entities or neighbor shape updates. +/// Returns false for empty templates. +#[allow(clippy::too_many_arguments)] +pub fn place_in_world( + world: &mut W, + resources: &StructureResources, + template: &StructureTemplate, + position: [i32; 3], + reference: [i32; 3], + settings: &mut PlaceSettings<'_>, + mut loot_random: Option<&mut dyn ProcessorRandom>, + flags: i32, +) -> Result { + if template.palettes().is_empty() { + return Ok(false); + } + let palette = match settings.random.as_deref_mut() { + Some(r) => r.int(template.palettes().len() as i32) as usize, + None => LegacyRandom::new(position_seed(BlockPos::new( + position[0], + position[1], + position[2], + ))) + .next_int_bound(template.palettes().len() as i32) + .unwrap_or(0) as usize, + }; + if template.palettes()[palette].blocks().is_empty() || template.size.iter().any(|s| *s < 1) { + return Ok(false); + } + let infos = process_infos( + world, resources, template, palette, position, reference, settings, + )?; + let barrier = resources + .registry + .default_state("minecraft:barrier") + .unwrap(); + let mut to_fill = Vec::new(); + let mut locked = Vec::new(); + let world_err = |_| PlacementQueryError::Failed("template write".into()); + for info in infos { + if settings + .bounding_box + .is_some_and(|b| !b.is_inside(info.pos)) + { + continue; + } + let previous = if settings.waterlogging { + Some(world.fluid_state(info.pos)?) + } else { + None + }; + let state = resources.transforms.rotate( + resources.transforms.mirror(info.state, settings.mirror), + settings.rotation, + ); + if info.nbt.is_some() { + world.set_block(info.pos, barrier, 820).map_err(world_err)?; + } + if !world.set_block(info.pos, state, flags).map_err(world_err)? { + continue; + } + if let Some(mut nbt) = info.nbt { + if resources.transforms.loot_container(state) { + let seed = match loot_random.as_deref_mut() { + Some(random) => random.long(), + None => settings.random.as_deref_mut().map_or(0, |r| r.long()), + }; + nbt.insert("LootTableSeed".into(), Tag::Long(seed)); + } + world.set_block_entity(info.pos, nbt)?; + } + if let Some(previous) = previous { + if resources.source_fluid(state) { + locked.push(info.pos); + } else if let Some(wet) = resources.waterlogged.get(&state) { + if previous.kind() == FluidKind::Water { + world.set_block(info.pos, *wet, 3).map_err(world_err)?; + world.schedule_fluid_tick(info.pos, previous.kind(), 5).ok(); + } else if !previous.is_source() { + to_fill.push(info.pos); + } + } + } + } + let mut filled = true; + while filled && !to_fill.is_empty() { + filled = false; + let mut remaining = Vec::new(); + for pos in std::mem::take(&mut to_fill) { + let mut fluid = world.fluid_state(pos)?; + for d in [[0, 1, 0], [0, 0, -1], [1, 0, 0], [0, 0, 1], [-1, 0, 0]] { + if fluid.is_source() { + break; + } + let n = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]]; + let neighbor = world.fluid_state(n)?; + if neighbor.is_source() && !locked.contains(&n) { + fluid = neighbor; + } + } + let state = world.block_state(pos)?; + match resources.waterlogged.get(&state) { + Some(wet) if fluid.is_source() && fluid.kind() == FluidKind::Water => { + world.set_block(pos, *wet, 3).map_err(world_err)?; + world.schedule_fluid_tick(pos, fluid.kind(), 5).ok(); + filled = true; + } + _ => remaining.push(pos), + } + } + to_fill = remaining; + } + Ok(true) +} diff --git a/crates/horizon-world/src/worldgen/structure/template.rs b/crates/horizon-world/src/worldgen/structure/template.rs new file mode 100644 index 000000000..8726d2b20 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/template.rs @@ -0,0 +1,302 @@ +//! StructureTemplate: NBT loading, palettes, transforms and bounding boxes. +use super::{BoundingBox, Mirror, Rotation, StateTransforms}; +use crate::{ + chunk::BlockState, + nbt::{Compound, Tag}, + registry::{BlockRegistry, BlockStateId}, +}; +use std::sync::OnceLock; + +#[derive(Clone, Debug, PartialEq)] +pub struct BlockInfo { + pub pos: [i32; 3], + pub state: BlockStateId, + pub nbt: Option, +} +#[derive(Clone, Debug)] +pub struct JigsawInfo { + pub info: BlockInfo, + pub rollable: bool, + pub name: String, + pub pool: String, + pub target: String, + pub placement_priority: i32, + pub selection_priority: i32, +} +#[derive(Debug)] +pub struct Palette { + blocks: Vec, + jigsaws: OnceLock>, +} +impl Palette { + pub fn blocks(&self) -> &[BlockInfo] { + &self.blocks + } +} +#[derive(Debug)] +pub struct StructureTemplate { + pub size: [i32; 3], + palettes: Vec, +} + +fn int_list(tag: Option<&Tag>) -> [i32; 3] { + let mut out = [0; 3]; + if let Some(Tag::List(values)) = tag { + for (slot, value) in out.iter_mut().zip(values) { + if let Tag::Int(v) = value { + *slot = *v; + } + } + } + out +} +fn string(tag: Option<&Tag>) -> Option { + match tag { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } +} +fn get<'a>(compound: &'a Compound, key: &str) -> Option<&'a Tag> { + compound.get(&crate::nbt::JavaString::from(key)) +} +/// NbtUtils.readBlockState: unknown blocks read as air; missing or invalid +/// properties keep the block's defaults. +pub(super) fn read_state(registry: &BlockRegistry, tag: &Tag) -> BlockStateId { + let air = registry.default_state("minecraft:air").expect("air"); + let Tag::Compound(compound) = tag else { + return air; + }; + let Some(name) = string(get(compound, "Name")) else { + return air; + }; + let Some(default) = registry.default_state(&name) else { + return air; + }; + let mut state = registry.state(default).unwrap().clone(); + if let Some(Tag::Compound(properties)) = get(compound, "Properties") { + for (key, value) in properties { + let (Tag::String(value), key) = (value, key.to_string_lossy()) else { + continue; + }; + let value = value.to_string_lossy(); + if let Some(slot) = state.properties.get_mut(&key) { + let previous = std::mem::replace(slot, value); + if registry.id(&state).is_none() { + *state.properties.get_mut(&key).unwrap() = previous; + } + } + } + } + registry.id(&state).unwrap_or(default) +} +/// Parse `name[key=value,...]` (BlockStateParser without NBT); None if invalid. +pub(super) fn parse_state_string(registry: &BlockRegistry, text: &str) -> Option { + let text = text.split('{').next().unwrap_or(text).trim(); + let (name, properties) = match text.split_once('[') { + Some((name, rest)) => (name, rest.strip_suffix(']')?), + None => (text, ""), + }; + let name = if name.contains(':') { + name.to_owned() + } else { + format!("minecraft:{name}") + }; + let mut descriptor = BlockState { + name, + properties: Default::default(), + }; + for pair in properties.split(',').filter(|p| !p.trim().is_empty()) { + let (k, v) = pair.split_once('=')?; + descriptor + .properties + .insert(k.trim().to_owned(), v.trim().to_owned()); + } + registry.resolve(&descriptor).ok() +} + +impl StructureTemplate { + /// StructureTemplate.load. Blocks are ordered as vanilla orders them: + /// full collision blocks, then other blocks, then block entities, each + /// sorted by Y, X, Z. + pub fn from_nbt(tag: &Tag, registry: &BlockRegistry, transforms: &StateTransforms) -> Self { + let empty = Compound::new(); + let root = match tag { + Tag::Compound(c) => c, + _ => &empty, + }; + let size = int_list(get(root, "size")); + let blocks = match get(root, "blocks") { + Some(Tag::List(list)) => list.as_slice(), + _ => &[], + }; + let mut palettes = Vec::new(); + let mut load = |palette: &[Tag]| { + let states: Vec = + palette.iter().map(|t| read_state(registry, t)).collect(); + let air = registry.default_state("minecraft:air").unwrap(); + let mut lists: [Vec; 3] = Default::default(); + for block in blocks { + let Tag::Compound(block) = block else { + continue; + }; + let index = match get(block, "state") { + Some(Tag::Int(i)) => *i, + _ => 0, + }; + let state = usize::try_from(index) + .ok() + .and_then(|i| states.get(i)) + .copied() + .unwrap_or(air); + let nbt = match get(block, "nbt") { + Some(Tag::Compound(c)) => Some(c.clone()), + _ => None, + }; + let class = if nbt.is_some() { + 2 + } else if transforms.full_block(state) { + 0 + } else { + 1 + }; + lists[class].push(BlockInfo { + pos: int_list(get(block, "pos")), + state, + nbt, + }); + } + let mut result = Vec::with_capacity(blocks.len()); + for mut list in lists { + list.sort_by_key(|b| (b.pos[1], b.pos[0], b.pos[2])); + result.extend(list); + } + palettes.push(Palette { + blocks: result, + jigsaws: OnceLock::new(), + }); + }; + match get(root, "palettes") { + Some(Tag::List(lists)) => { + for list in lists { + match list { + Tag::List(p) => load(p), + _ => load(&[]), + } + } + } + _ => match get(root, "palette") { + Some(Tag::List(p)) => load(p), + _ => load(&[]), + }, + } + Self { size, palettes } + } + pub fn palettes(&self) -> &[Palette] { + &self.palettes + } + pub fn size(&self, rotation: Rotation) -> [i32; 3] { + match rotation { + Rotation::Clockwise90 | Rotation::Counterclockwise90 => { + [self.size[2], self.size[1], self.size[0]] + } + _ => self.size, + } + } + pub fn transform( + pos: [i32; 3], + mirror: Mirror, + rotation: Rotation, + pivot: [i32; 3], + ) -> [i32; 3] { + let [mut x, y, mut z] = pos; + match mirror { + Mirror::LeftRight => z = z.wrapping_neg(), + Mirror::FrontBack => x = x.wrapping_neg(), + Mirror::None => {} + } + let (px, pz) = (pivot[0], pivot[2]); + match rotation { + Rotation::Counterclockwise90 => [px - pz + z, y, px + pz - x], + Rotation::Clockwise90 => [px + pz - z, y, pz - px + x], + Rotation::Clockwise180 => [px + px - x, y, pz + pz - z], + Rotation::None => [x, y, z], + } + } + pub fn zero_position_with_transform( + zero: [i32; 3], + mirror: Mirror, + rotation: Rotation, + size_x: i32, + size_z: i32, + ) -> [i32; 3] { + let (sx, sz) = (size_x - 1, size_z - 1); + let mx = if mirror == Mirror::FrontBack { sx } else { 0 }; + let mz = if mirror == Mirror::LeftRight { sz } else { 0 }; + let d = match rotation { + Rotation::Counterclockwise90 => [mz, 0, sx - mx], + Rotation::Clockwise90 => [sz - mz, 0, mx], + Rotation::Clockwise180 => [sx - mx, 0, sz - mz], + Rotation::None => [mx, 0, mz], + }; + [zero[0] + d[0], zero[1], zero[2] + d[2]] + } + pub fn bounding_box( + &self, + position: [i32; 3], + rotation: Rotation, + pivot: [i32; 3], + mirror: Mirror, + ) -> BoundingBox { + let delta = [self.size[0] - 1, self.size[1] - 1, self.size[2] - 1]; + let a = Self::transform([0; 3], mirror, rotation, pivot); + let b = Self::transform(delta, mirror, rotation, pivot); + BoundingBox::from_corners(a, b).moved(position) + } + /// The palette selected by StructurePlaceSettings.getRandomPalette. + pub fn palette_index(&self, random: &mut impl horizon_core::random::RandomSource) -> usize { + random + .next_int_bound(self.palettes.len().max(1) as i32) + .unwrap_or(0) as usize + } + /// Jigsaw blocks of a palette, parsed from their block-entity data. + pub fn jigsaws( + &self, + palette: usize, + jigsaw_states: &dyn Fn(BlockStateId) -> Option, + ) -> &[JigsawInfo] { + let Some(palette) = self.palettes.get(palette) else { + return &[]; + }; + palette.jigsaws.get_or_init(|| { + palette + .blocks + .iter() + .filter_map(|info| { + let horizontal = jigsaw_states(info.state)?; + let nbt = info.nbt.clone().unwrap_or_default(); + let joint = string(get(&nbt, "joint")); + let text = |key: &str, default: &str| { + string(get(&nbt, key)).unwrap_or_else(|| default.to_owned()) + }; + let int = |key: &str| match get(&nbt, key) { + Some(Tag::Int(v)) => *v, + _ => 0, + }; + Some(JigsawInfo { + rollable: match joint.as_deref() { + Some("rollable") => true, + Some("aligned") => false, + _ => !horizontal, + }, + name: text("name", "minecraft:empty"), + pool: text("pool", "minecraft:empty"), + target: text("target", "minecraft:empty"), + placement_priority: int("placement_priority"), + selection_priority: int("selection_priority"), + info: info.clone(), + }) + }) + .collect() + }) + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java new file mode 100644 index 000000000..0e37d5cda --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java @@ -0,0 +1,40 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import net.minecraft.SharedConstants; +import net.minecraft.core.BlockPos; +import net.minecraft.server.Bootstrap; +import net.minecraft.world.RandomizableContainer; +import net.minecraft.world.level.EmptyBlockGetter; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.state.BlockState; + +/** + * Original exporter of per-state structure-template behavior: BlockState.rotate + * and BlockState.mirror results, StructureTemplate's full-block ordering class + * and whether the state's block entity is a RandomizableContainer. + */ +public final class VanillaStructureBlockExporter { + public static void main(String[] args) throws Exception { + SharedConstants.tryDetectVersion();Bootstrap.bootStrap(); + var rotate=new JsonArray();var mirror=new JsonArray();var full=new JsonArray();var loot=new JsonArray(); + Rotation[] rotations={Rotation.CLOCKWISE_90,Rotation.CLOCKWISE_180,Rotation.COUNTERCLOCKWISE_90}; + Mirror[] mirrors={Mirror.LEFT_RIGHT,Mirror.FRONT_BACK}; + for(BlockState state:Block.BLOCK_STATE_REGISTRY) { + var r=new JsonArray();for(var rotation:rotations)r.add(Block.getId(state.rotate(rotation)));rotate.add(r); + var m=new JsonArray();for(var value:mirrors)m.add(Block.getId(state.mirror(value)));mirror.add(m); + full.add(!state.getBlock().hasDynamicShape()&&state.isCollisionShapeFullBlock(EmptyBlockGetter.INSTANCE,BlockPos.ZERO)); + boolean container=false; + if(state.getBlock() instanceof EntityBlock entityBlock) { + try{container=entityBlock.newBlockEntity(BlockPos.ZERO,state) instanceof RandomizableContainer;}catch(Throwable ignored){} + } + if(container)loot.add(Block.getId(state)); + } + var result=new JsonObject(); + result.addProperty("states",Block.BLOCK_STATE_REGISTRY.size()); + result.add("rotate",rotate);result.add("mirror",mirror);result.add("full_block",full);result.add("loot_containers",loot); + Files.writeString(Path.of(args[0]),new Gson().toJson(result),StandardCharsets.UTF_8); + } +} diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 0e2f881f0..280d53e24 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -21,13 +21,44 @@ WORLDGEN_BUNDLES = { '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'} + 'fluid_tags': 'tags/fluid', 'processor_lists': 'worldgen/processor_list', + 'template_pools': 'worldgen/template_pool', 'structures': 'worldgen/structure', + 'structure_sets': 'worldgen/structure_set'} -def prepare_worldgen(root, jars, local): +def export_structure_blocks(target, jars, libraries): + """Run the vanilla exporter of per-state rotate/mirror results and template flags.""" + lock = json.loads((lab.ROOT/'research-lock.json').read_text()) + source = lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaStructureBlockExporter.java' + export = lab.LOCAL/'horizon-client-structures' + classes = export/'classes' + classes.mkdir(parents=True, exist_ok=True) + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + with (export/'export.log').open('w') as log: + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-cp', dependencies, + '-d', str(classes), str(source)], check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + subprocess.run(['java', '-Xmx1G', '-cp', str(classes)+os.pathsep+dependencies, + 'dev.horizonlab.parity.VanillaStructureBlockExporter', str(target)], + check=True, stdout=log, stderr=subprocess.STDOUT, timeout=3600) + + +def prepare_worldgen(root, jars, local, libraries=None): """Write the chunk generator's resource bundle to root/worldgen (see GeneratorData::load).""" out = root / 'worldgen' out.mkdir(exist_ok=True) + # Structure templates: gzip NBT files under structure//.nbt. + with zipfile.ZipFile(jars['server']) as server: + prefix = 'data/minecraft/structure/' + for name in server.namelist(): + if name.startswith(prefix) and name.endswith('.nbt'): + relative = Path(name[len(prefix):]) + if relative.is_absolute() or '..' in relative.parts: + raise ValueError('Invalid structure path') + target = out/'structure'/'minecraft'/relative + data = server.read(name) + if not target.exists() or target.read_bytes() != data: + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) 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}/' @@ -60,6 +91,9 @@ def prepare_worldgen(root, jars, local): blocks.mkdir(exist_ok=True) for name in names: (blocks/name).write_bytes((behavior/name).read_bytes()) + if libraries is not None: + blocks.mkdir(exist_ok=True) + export_structure_blocks(blocks/'structure-blocks.json', jars, libraries) else: print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration') if presets is None: @@ -215,7 +249,7 @@ 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) + prepare_worldgen(root, jars, lab.LOCAL, libraries) count = 0 # The playable client needs every client asset (textures, models, fonts, GUI) # and every data-pack resource (worldgen, recipes, loot tables, tags).