From 50b999535843546a5666620b944d175fb6169e4e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 19:14:26 +0200 Subject: [PATCH 01/12] Port vanilla tree, fallen tree and blob ore features Adds minecraft:tree with every 26.3 trunk placer (straight, forking, giant, mega_jungle, dark_oak, fancy, bending, upwards_branching, cherry, poplar), foliage placer (blob, fancy, bush, acacia, spruce, pine, mega_pine, jungle, dark_oak, random_spread, cherry, poplar), the mangrove root placer, all tree decorators, two/three-layer feature sizes and the native leaf-distance pass with Java HashSet iteration order. Adds minecraft:fallen_tree and minecraft:ore (BulkSectionAccess-style raw section writes with write-zone checks). Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 2 + .../src/worldgen/block_feature.rs | 11 + .../src/worldgen/feature_catalog.rs | 22 + .../src/worldgen/feature_graph.rs | 41 + .../src/worldgen/feature_region.rs | 39 +- .../horizon-world/src/worldgen/ore_feature.rs | 247 +++++- .../src/worldgen/placement/context.rs | 44 + .../src/worldgen/state_provider.rs | 4 +- .../src/worldgen/state_provider/properties.rs | 30 +- crates/horizon-world/src/worldgen/tree.rs | 822 ++++++++++++++++++ .../src/worldgen/tree/decorator.rs | 671 ++++++++++++++ .../horizon-world/src/worldgen/tree/fallen.rs | 182 ++++ .../src/worldgen/tree/foliage.rs | 629 ++++++++++++++ .../horizon-world/src/worldgen/tree/trunk.rs | 800 +++++++++++++++++ .../horizon-world/src/worldgen/tree_blocks.rs | 356 ++++++++ 15 files changed, 3892 insertions(+), 8 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/tree.rs create mode 100644 crates/horizon-world/src/worldgen/tree/decorator.rs create mode 100644 crates/horizon-world/src/worldgen/tree/fallen.rs create mode 100644 crates/horizon-world/src/worldgen/tree/foliage.rs create mode 100644 crates/horizon-world/src/worldgen/tree/trunk.rs create mode 100644 crates/horizon-world/src/worldgen/tree_blocks.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index ed126b40e..b8e259b0b 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -51,6 +51,8 @@ pub mod spike; pub mod spring; pub mod state_provider; pub mod tags; +pub mod tree; +pub(crate) mod tree_blocks; pub mod terrain; pub mod underwater_magma; pub mod value_provider; diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index 3616bacb2..ee61e3f35 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -29,8 +29,18 @@ pub struct FeatureBlockBindings<'r> { pub(crate) blocks: BTreeMap>>, pub(crate) tags: BTreeMap>>, pub(crate) air: [BlockStateId; 3], + tree_blocks: std::sync::OnceLock>, } impl<'r> FeatureBlockBindings<'r> { + /// Shared tree/vegetation classifications, built on first use. Requires + /// state-provider and block-property bindings. + pub(crate) fn tree_blocks(&self) -> Result, DecodeError> { + if let Some(blocks) = self.tree_blocks.get() { + return Ok(blocks.clone()); + } + let blocks = Arc::new(super::tree_blocks::TreeBlocks::build(self)?); + Ok(self.tree_blocks.get_or_init(|| blocks).clone()) + } pub fn registry(&self) -> &'r BlockRegistry { self.registry } @@ -143,6 +153,7 @@ impl<'r> FeatureBlockBindings<'r> { .map(|(name, states)| (name, Arc::new(states))) .collect(), tags: bound_tags, + tree_blocks: std::sync::OnceLock::new(), air: [ get("minecraft:air")?, get("minecraft:cave_air")?, diff --git a/crates/horizon-world/src/worldgen/feature_catalog.rs b/crates/horizon-world/src/worldgen/feature_catalog.rs index 1f88278f7..1aff708a0 100644 --- a/crates/horizon-world/src/worldgen/feature_catalog.rs +++ b/crates/horizon-world/src/worldgen/feature_catalog.rs @@ -234,6 +234,28 @@ impl FeatureCatalog { object.insert("cap_feature".into(), raw(expanded)?); } } + "minecraft:tree" => { + // PaleMossDecorator places the registry's pale_moss_patch by key. + let pale_moss = super::optional(&object, "decorators") + .map(|raw| serde_json::from_str::>(raw.get())) + .transpose()? + .unwrap_or_default() + .iter() + .any(|d| { + d.get("type").is_some_and(|t| { + serde_json::from_str::(t.get()) + .ok() + .and_then(|t| identifier(&t).ok()) + .as_deref() + == Some("minecraft:pale_moss") + }) + }); + const PATCH: &str = "minecraft:pale_moss_patch"; + if pale_moss && self.features.contains_key(PATCH) { + let expanded = self.named(PATCH, false, depth, work)?; + object.insert(super::tree::GROUND_FEATURE_KEY.into(), raw(expanded)?); + } + } "minecraft:sequence" | "minecraft:overlay" | "minecraft:simple_random_selector" => { let expanded = self.expand_set(required(&object, "features")?, depth + 1, work)?; object.insert("features".into(), raw(expanded)?); diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 1faf0abe0..27b7f2abd 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -66,6 +66,9 @@ pub enum FeatureDefinition { FillLayer(FillLayerFeature), ReplaceBlock(ReplaceBlockFeature), ScatteredOre(ScatteredOreFeature), + Ore(super::ore_feature::OreFeature), + Tree(Box), + FallenTree(Box), NoOp, WeightedChoice(OptionalWeightedList), Sequence(Vec), @@ -102,6 +105,8 @@ pub enum FeatureExecutionError { Query(PlacementQueryError), WorkLimit, InvalidPendingIndex, + /// A block-state transition required by a feature is absent from the registry. + InvalidState, } impl std::fmt::Display for FeatureExecutionError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { @@ -129,6 +134,7 @@ impl std::fmt::Display for FeatureExecutionError { Self::Query(e) => e.fmt(f), Self::WorkLimit => f.write_str("feature graph work limit exceeded"), Self::InvalidPendingIndex => f.write_str("invalid pending modifier index"), + Self::InvalidState => f.write_str("feature block state outside registry"), } } } @@ -525,6 +531,15 @@ impl FeatureDefinition { remaining, ) .map(Self::ReplaceBlock), + "minecraft:ore" => super::ore_feature::OreFeature::decode( + json, + blocks.ok_or_else(|| { + DecodeError::Registry("feature block bindings unavailable".into()) + })?, + depth, + remaining, + ) + .map(Self::Ore), "minecraft:scattered_ore" => ScatteredOreFeature::decode( json, blocks.ok_or_else(|| { @@ -534,6 +549,21 @@ impl FeatureDefinition { remaining, ) .map(Self::ScatteredOre), + "minecraft:tree" | "minecraft:fallen_tree" => { + let bindings = blocks.ok_or(DecodeError::Field("tree bindings"))?; + let nested = |json: &str, depth: usize, remaining: &mut usize| { + Self::decode(json, depth, remaining, empty_tags, blocks) + }; + if kind == "minecraft:tree" { + super::tree::TreeFeature::decode(json, bindings, depth, remaining, &nested) + .map(|t| Self::Tree(Box::new(t))) + } else { + super::tree::FallenTreeFeature::decode( + json, bindings, depth, remaining, &nested, + ) + .map(|t| Self::FallenTree(Box::new(t))) + } + } "minecraft:weighted_random_selector" => Ok(Self::WeightedChoice( OptionalWeightedList::decode(required(&object, "features")?, |raw| { PlacedFeatureDefinition::decode( @@ -846,6 +876,17 @@ impl FeatureDefinition { Self::ScatteredOre(feature) => feature .place(world, random, origin) .map_err(FeatureExecutionError::Basic), + Self::Ore(feature) => feature.place(world, random, origin), + Self::Tree(feature) => { + feature.place(world, random, origin, &mut |f, w, r, p| { + f.place_inner(w, r, p, run) + }) + } + Self::FallenTree(feature) => { + feature.place(world, random, origin, &mut |f, w, r, p| { + f.place_inner(w, r, p, run) + }) + } Self::FillLayer(feature) => feature.place(world, origin).map_err(|e| match e { BlockFeatureError::World(e) => FeatureExecutionError::Basic(FeatureError::World(e)), BlockFeatureError::Query(e) => FeatureExecutionError::Query(e), diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 8939d24f9..f3b4f9f49 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -425,6 +425,15 @@ where state: BlockStateId, flags: i32, ) -> Result { + if !self.can_write(position)? { + return Ok(false); + } + (self.write)(self.region, position, state, flags) + } +} +impl<'r, B: TerrainBlockStates, F> TerrainFeatureAccess<'_, 'r, B, F> { + /// WorldGenRegion.ensureCanWrite without its diagnostic logging. + fn can_write(&mut self, position: [i32; 3]) -> Result { if self.write_zone.is_some_and(|zone| { !zone.contains_block(BlockPos::new(position[0], position[1], position[2])) }) { @@ -441,10 +450,7 @@ where }) } }; - if height.is_some_and(|height| !height.contains(position[1])) { - return Ok(false); - } - (self.write)(self.region, position, state, flags) + Ok(!height.is_some_and(|height| !height.contains(position[1]))) } } impl<'r, B: TerrainBlockStates, F> PlacementContext for TerrainFeatureAccess<'_, 'r, B, F> @@ -476,6 +482,31 @@ where ) -> Result { self.region.fluid_state(position) } + fn ensure_can_write(&mut self, position: [i32; 3]) -> Result { + self.can_write(position).map_err(Into::into) + } + fn section_block( + &mut self, + position: [i32; 3], + ) -> Result, PlacementQueryError> { + if position[1] < self.region.min_y + || position[1] >= self.region.min_y.wrapping_add(self.region.height) + { + return Ok(None); + } + self.region.block(position).map(Some).map_err(Into::into) + } + fn set_section_block( + &mut self, + [x, y, z]: [i32; 3], + state: BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.region + .chunk_mut(x >> 4, z >> 4)? + .set_block_raw(x, y, z, state) + .map_err(RegionError::from)?; + Ok(()) + } fn water_at(&mut self, position: [i32; 3]) -> Result { self.region.water_at(position) } diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs index a6a6f4006..c4cbe447e 100644 --- a/crates/horizon-world/src/worldgen/ore_feature.rs +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -4,8 +4,12 @@ use super::{ block_feature::{BlockReplacements, FeatureBlockBindings, decode_targets}, density::identifier, feature::{FeatureError, FeatureWorld}, - int_range, number_text, required, + feature_graph::FeatureExecutionError, + int_range, number_text, + placement::PlacementContext, + required, }; +use crate::heightmap::HeightmapType; use crate::registry::BlockStateId; use horizon_core::{geometry::Direction, random::RandomSource}; @@ -99,3 +103,244 @@ impl ScatteredOreFeature { Ok(true) } } + +/// Vanilla `minecraft:ore`: an interpolated chain of spheres written straight +/// into chunk sections (BulkSectionAccess), bypassing block update effects. +#[derive(Clone, Debug)] +pub struct OreFeature { + targets: BlockReplacements, + size: i32, + discard: f32, + air: [BlockStateId; 3], +} +impl OreFeature { + pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + Self::decode(json, bindings, 0, &mut 65536) + } + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let kind = identifier(&serde_json::from_str::( + required(&object, "type")?.get(), + )?)?; + if kind != "minecraft:ore" { + return Err(DecodeError::Field("ore type")); + } + let targets = decode_targets(&object, bindings, depth, remaining)?; + let size = int_range(required(&object, "size")?, "ore size", 0, 64)?; + let discard: f32 = number_text(required(&object, "discard_chance_on_air_exposure")?)? + .parse() + .map_err(|_| DecodeError::Field("ore air exposure"))?; + if !(0.0..=1.0).contains(&discard) || discard.is_sign_negative() { + return Err(DecodeError::Field("ore air exposure")); + } + Ok(Self { + targets, + size, + discard, + air: bindings.air, + }) + } + pub fn place( + &self, + world: &mut W, + random: &mut impl RandomSource, + origin: [i32; 3], + ) -> Result> { + let dir = random.next_float() * std::f32::consts::PI; + let spread_xy = self.size as f32 / 8.0; + let max_radius = ((self.size as f32 / 16.0 * 2.0 + 1.0) / 2.0).ceil() as i32; + let (ox, oz) = (f64::from(origin[0]), f64::from(origin[2])); + let (sin, cos) = (f64::from(dir).sin(), f64::from(dir).cos()); + let spread = f64::from(spread_xy); + let x0 = ox + sin * spread; + let x1 = ox - sin * spread; + let z0 = oz + cos * spread; + let z1 = oz - cos * spread; + let y0 = f64::from( + origin[1] + .wrapping_add(random.next_int_bound(3)?) + .wrapping_sub(2), + ); + let y1 = f64::from( + origin[1] + .wrapping_add(random.next_int_bound(3)?) + .wrapping_sub(2), + ); + let spread_ceil = spread.ceil() as i32; + let x_start = origin[0].wrapping_sub(spread_ceil).wrapping_sub(max_radius); + let y_start = origin[1].wrapping_sub(2).wrapping_sub(max_radius); + let z_start = origin[2].wrapping_sub(spread_ceil).wrapping_sub(max_radius); + let size_xz = 2 * (spread_ceil + max_radius); + let size_y = 2 * (2 + max_radius); + for x in 0..=size_xz { + for z in 0..=size_xz { + let (px, pz) = (x_start.wrapping_add(x), z_start.wrapping_add(z)); + let floor = world + .height(HeightmapType::OceanFloorWg, px, pz) + .map_err(FeatureExecutionError::Query)?; + if y_start <= floor { + return self.do_place( + world, + random, + [x0, x1, z0, z1, y0, y1], + [x_start, y_start, z_start], + size_xz, + size_y, + ); + } + } + } + Ok(false) + } + fn do_place( + &self, + world: &mut W, + random: &mut impl RandomSource, + [x0, x1, z0, z1, y0, y1]: [f64; 6], + [x_start, y_start, z_start]: [i32; 3], + size_xz: i32, + size_y: i32, + ) -> Result> { + let size = self.size as usize; + let mut data = vec![[0f64; 4]; size]; + for (i, entry) in data.iter_mut().enumerate() { + let step = i as f32 / self.size as f32; + let step64 = f64::from(step); + let xx = x0 + step64 * (x1 - x0); + let yy = y0 + step64 * (y1 - y0); + let zz = z0 + step64 * (z1 - z0); + let ss = random.next_double() * f64::from(self.size) / 16.0; + let sine = horizon_core::geometry::trig::sin(f64::from(std::f32::consts::PI * step)); + let r = (f64::from(sine + 1.0) * ss + 1.0) / 2.0; + *entry = [xx, yy, zz, r]; + } + for i1 in 0..size.saturating_sub(1) { + if data[i1][3] <= 0.0 { + continue; + } + for i2 in i1 + 1..size { + if data[i2][3] <= 0.0 { + continue; + } + let dx = data[i1][0] - data[i2][0]; + let dy = data[i1][1] - data[i2][1]; + let dz = data[i1][2] - data[i2][2]; + let dr = data[i1][3] - data[i2][3]; + if dr * dr > dx * dx + dy * dy + dz * dz { + if dr > 0.0 { + data[i2][3] = -1.0; + } else { + data[i1][3] = -1.0; + } + } + } + } + let mut tested = vec![false; (size_xz as usize) * (size_y as usize) * (size_xz as usize)]; + let mut placed = 0; + for [xx, yy, zz, r] in data { + if r < 0.0 { + continue; + } + let x_min = ((xx - r).floor() as i32).max(x_start); + let y_min = ((yy - r).floor() as i32).max(y_start); + let z_min = ((zz - r).floor() as i32).max(z_start); + let x_max = ((xx + r).floor() as i32).max(x_min); + let y_max = ((yy + r).floor() as i32).max(y_min); + let z_max = ((zz + r).floor() as i32).max(z_min); + for x in x_min..=x_max { + let xd = (f64::from(x) + 0.5 - xx) / r; + if xd * xd >= 1.0 { + continue; + } + for y in y_min..=y_max { + let yd = (f64::from(y) + 0.5 - yy) / r; + if xd * xd + yd * yd >= 1.0 { + continue; + } + for z in z_min..=z_max { + let zd = (f64::from(z) + 0.5 - zz) / r; + if xd * xd + yd * yd + zd * zd >= 1.0 + || world + .outside_build_height(y) + .map_err(FeatureExecutionError::Query)? + { + continue; + } + let index = i64::from(x.wrapping_sub(x_start)) + + i64::from(y.wrapping_sub(y_start)) * i64::from(size_xz) + + i64::from(z.wrapping_sub(z_start)) + * i64::from(size_xz) + * i64::from(size_y); + // The sphere bounds keep indices inside the native BitSet. + let Some(bit) = usize::try_from(index) + .ok() + .and_then(|index| tested.get_mut(index)) + else { + return Err(FeatureExecutionError::WorkLimit); + }; + if *bit { + continue; + } + *bit = true; + let p = [x, y, z]; + if !world + .ensure_can_write(p) + .map_err(FeatureExecutionError::Query)? + { + continue; + } + let Some(state) = world + .section_block(p) + .map_err(FeatureExecutionError::Query)? + else { + continue; + }; + for (rule, target) in &self.targets { + if !rule.test(state, p, random) { + continue; + } + if !skip_air_check(random, self.discard) { + let mut exposed = false; + for direction in Direction::ALL { + let n = direction.normal(); + let q = std::array::from_fn(|i| p[i].wrapping_add(n[i])); + let neighbor = world + .section_block(q) + .map_err(FeatureExecutionError::Query)? + .unwrap_or(self.air[0]); + if self.air.contains(&neighbor) { + exposed = true; + break; + } + } + if exposed { + continue; + } + } + world + .set_section_block(p, *target) + .map_err(FeatureExecutionError::Query)?; + placed += 1; + break; + } + } + } + } + } + Ok(placed > 0) + } +} +fn skip_air_check(random: &mut impl RandomSource, discard: f32) -> bool { + if discard <= 0.0 { + true + } else if discard >= 1.0 { + false + } else { + random.next_float() >= discard + } +} diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 3d36ffdea..f65e90ebe 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -26,6 +26,50 @@ pub enum LayerBlock { Ground, } pub trait PlacementContext { + /// StructureTemplate.updateShapeAtEdge for one outer face of a placed + /// voxel shape: update the state at `position` against its neighbor in + /// `direction`, then the neighbor against the (possibly new) state, writing + /// changes with `flags & !1`. Worlds without block shape-update behavior + /// accept this as a no-op. + fn update_shape_at_face( + &mut self, + _position: [i32; 3], + _direction: horizon_core::geometry::Direction, + _flags: i32, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } + /// WorldGenRegion.ensureCanWrite: horizontal write radius and upgrade height. + fn ensure_can_write(&mut self, _position: [i32; 3]) -> Result { + Ok(true) + } + /// BulkSectionAccess read: None outside the world's section range. + fn section_block( + &mut self, + position: [i32; 3], + ) -> Result, PlacementQueryError> { + if self.outside_build_height(position[1])? { + return Ok(None); + } + self.block_state(position).map(Some) + } + /// Raw LevelChunkSection write: no heightmap, light, POI or neighbor effects. + fn set_section_block( + &mut self, + _position: [i32; 3], + _state: crate::registry::BlockStateId, + ) -> Result<(), PlacementQueryError> { + Err(PlacementQueryError::Unavailable) + } + /// Store worldgen beehive occupants (ticks in hive per bee) in the nest + /// block entity at `position`. Worlds without block-entity storage drop them. + fn store_beehive_occupants( + &mut self, + _position: [i32; 3], + _ticks_in_hive: &[i32], + ) -> Result<(), PlacementQueryError> { + Ok(()) + } /// Test the already-read state's collision shape in an empty entity context. fn state_collision_empty( &mut self, diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 6f69cfafa..37e9c866b 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -2,7 +2,7 @@ mod catalog; mod noise; pub use catalog::StateProviderCatalog; -mod properties; +pub(crate) mod properties; use super::{ DecodeError, Object, block_predicate::{BlockPredicate, PredicateBlockResolver}, @@ -137,7 +137,7 @@ impl<'r> StateProviderBindings<'r> { .clone() .map_err(DecodeError::Registry) } - fn properties(&self) -> Result, DecodeError> { + pub(crate) fn properties(&self) -> Result, DecodeError> { self.properties .get_or_init(|| StateProperties::build(self.registry, &self.integers).map(Arc::new)) .clone() diff --git a/crates/horizon-world/src/worldgen/state_provider/properties.rs b/crates/horizon-world/src/worldgen/state_provider/properties.rs index ee8389401..cac52e69e 100644 --- a/crates/horizon-world/src/worldgen/state_provider/properties.rs +++ b/crates/horizon-world/src/worldgen/state_provider/properties.rs @@ -21,7 +21,7 @@ struct Block { properties: Vec, } #[derive(Debug)] -pub(super) struct StateProperties { +pub(crate) struct StateProperties { blocks: Vec, addresses: Vec
, } @@ -175,4 +175,32 @@ impl StateProperties { .get(address.local - previous * property.stride + index * property.stride) .copied() } + + fn property(&self, state: BlockStateId, name: &str) -> Option<(Address, &Property)> { + let address = *self.addresses.get(state.0 as usize)?; + let property = self.blocks[address.block] + .properties + .iter() + .find(|p| p.name == name)?; + Some((address, property)) + } + /// The state's value for a named property, or None when it has no such property. + pub fn value(&self, state: BlockStateId, name: &str) -> Option<&str> { + let (address, property) = self.property(state, name)?; + Some(&property.values[(address.local / property.stride) % property.values.len()]) + } + /// All values of the state's named property in registry encounter order. + pub fn values(&self, state: BlockStateId, name: &str) -> Option<&[String]> { + self.property(state, name).map(|(_, p)| p.values.as_slice()) + } + /// Replace one property value, or None for a missing property or value. + pub fn with_value(&self, state: BlockStateId, name: &str, value: &str) -> Option { + let (address, property) = self.property(state, name)?; + let index = *property.lookup.get(value)?; + let previous = (address.local / property.stride) % property.values.len(); + self.blocks[address.block] + .states + .get(address.local - previous * property.stride + index * property.stride) + .copied() + } } diff --git a/crates/horizon-world/src/worldgen/tree.rs b/crates/horizon-world/src/worldgen/tree.rs new file mode 100644 index 000000000..460447310 --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree.rs @@ -0,0 +1,822 @@ +//! Vanilla 26.3 `minecraft:tree` and `minecraft:fallen_tree` features: trunk, +//! foliage and root placers, decorators, minimum-size clipping and the native +//! leaf-distance pass. Native HashSet iteration order is reproduced wherever it +//! feeds random draws. Neighbor shape updates at the tree's outer faces are +//! delegated to `PlacementContext::update_shape_at_face`. +mod decorator; +mod fallen; +mod foliage; +mod trunk; +use super::{ + DecodeError, Object, + block_feature::FeatureBlockBindings, + density::identifier, + feature::{FeatureError, FeatureWorld}, + feature_graph::{FeatureDefinition, FeatureExecutionError}, + int_range, number_text, optional, + placement::PlacementContext, + required, + state_provider::BlockStateProvider, + tree_blocks::{self as tb, PosSet, TreeBlocks}, + value_provider::IntProvider, +}; +use crate::registry::BlockStateId; +pub(crate) use decorator::GROUND_FEATURE_KEY; +use decorator::TreeDecorator; +pub use fallen::FallenTreeFeature; +use foliage::{FoliageAttachment, FoliagePlacer}; +use horizon_core::{geometry::Direction, random::RandomSource}; +use serde_json::value::RawValue; +use std::{collections::BTreeSet, sync::Arc}; +use trunk::TrunkPlacer; + +pub(crate) type TreeResult = Result>; +/// Places a nested configured feature (the pale-moss ground patch). +pub(crate) type NestedPlacer<'a, W, R> = dyn FnMut( + &FeatureDefinition, + &mut W, + &mut R, + [i32; 3], + ) -> TreeResult::Error> + + 'a; + +pub(crate) fn world_error(error: E) -> FeatureExecutionError { + FeatureExecutionError::Basic(FeatureError::World(error)) +} +pub(crate) fn read( + world: &mut W, + position: [i32; 3], +) -> TreeResult { + world.block(position).map_err(world_error) +} +pub(crate) fn write( + world: &mut W, + position: [i32; 3], + state: BlockStateId, + flags: i32, +) -> TreeResult { + world.set_block(position, state, flags).map_err(world_error) +} +pub(crate) fn sample_state( + provider: &BlockStateProvider, + world: &mut W, + random: &mut impl RandomSource, + position: [i32; 3], +) -> TreeResult { + provider + .get_state(world, random, position) + .map_err(FeatureExecutionError::Provider) +} +pub(crate) fn sample_optional( + provider: &BlockStateProvider, + world: &mut W, + random: &mut impl RandomSource, + position: [i32; 3], +) -> TreeResult, W::Error> { + provider + .get_optional_state(world, random, position) + .map_err(FeatureExecutionError::Provider) +} + +/// Decoding context shared by every tree component. +pub(crate) struct TreeDecoder<'a, 'r> { + pub bindings: &'a FeatureBlockBindings<'r>, + pub depth: usize, + pub remaining: &'a mut usize, +} +impl TreeDecoder<'_, '_> { + pub fn provider(&mut self, raw: &RawValue) -> Result { + let (providers, catalog, _) = self + .bindings + .simple_blocks + .as_ref() + .ok_or(DecodeError::Field("tree provider bindings"))?; + catalog.provider_with_budget(raw.get(), providers, self.depth + 1, self.remaining) + } + pub fn int_provider( + &mut self, + raw: &RawValue, + low: i32, + high: i32, + ) -> Result { + let value = IntProvider::decode(raw, self.depth + 1, self.remaining)?; + let [min, max] = value.bounds(); + if min < low || max > high { + return Err(DecodeError::Field("tree integer provider bounds")); + } + Ok(value) + } + pub fn block_set(&self, raw: &RawValue) -> Result>, DecodeError> { + super::block_predicate::PredicateBlockResolver::predicate_block_set( + self.bindings, + raw.get(), + ) + } +} +pub(crate) fn unit_float(raw: &RawValue, name: &'static str) -> Result { + let value: f32 = number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field(name))?; + if !(0.0..=1.0).contains(&value) { + return Err(DecodeError::Field(name)); + } + Ok(value) +} +pub(crate) fn kind(object: &Object) -> Result { + identifier(&serde_json::from_str::( + required(object, "type")?.get(), + )?) +} +fn optional_int( + object: &Object, + name: &'static str, + default: i32, + low: i32, + high: i32, +) -> Result { + optional(object, name) + .map(|raw| int_range(raw, name, low, high)) + .transpose() + .map(|v| v.unwrap_or(default)) +} + +#[derive(Clone, Debug)] +enum FeatureSize { + TwoLayers { + limit: i32, + lower: i32, + upper: i32, + }, + ThreeLayers { + limit: i32, + upper_limit: i32, + lower: i32, + middle: i32, + upper: i32, + }, +} +impl FeatureSize { + fn decode(raw: &RawValue) -> Result<(Self, Option), DecodeError> { + let object: Object = serde_json::from_str(raw.get())?; + let clipped = optional(&object, "min_clipped_height") + .map(|raw| int_range(raw, "min_clipped_height", 0, 80)) + .transpose()?; + let size = match kind(&object)?.as_str() { + "minecraft:two_layers_feature_size" => Self::TwoLayers { + limit: optional_int(&object, "limit", 1, 0, 81)?, + lower: optional_int(&object, "lower_size", 0, 0, 16)?, + upper: optional_int(&object, "upper_size", 1, 0, 16)?, + }, + "minecraft:three_layers_feature_size" => Self::ThreeLayers { + limit: optional_int(&object, "limit", 1, 0, 80)?, + upper_limit: optional_int(&object, "upper_limit", 1, 0, 80)?, + lower: optional_int(&object, "lower_size", 0, 0, 16)?, + middle: optional_int(&object, "middle_size", 1, 0, 16)?, + upper: optional_int(&object, "upper_size", 1, 0, 16)?, + }, + _ => return Err(DecodeError::Field("feature size type")), + }; + Ok((size, clipped)) + } + fn size_at_height(&self, tree_height: i32, yo: i32) -> i32 { + match *self { + Self::TwoLayers { + limit, + lower, + upper, + } => { + if yo < limit { + lower + } else { + upper + } + } + Self::ThreeLayers { + limit, + upper_limit, + lower, + middle, + upper, + } => { + if yo < limit { + lower + } else if yo >= tree_height.wrapping_sub(upper_limit) { + upper + } else { + middle + } + } + } + } +} + +#[derive(Clone, Debug)] +struct MangroveRoots { + can_grow_through: Arc>, + muddy_roots_in: Arc>, + muddy_roots_provider: BlockStateProvider, + max_root_width: i32, + max_root_length: i32, + random_skew_chance: f32, +} +#[derive(Clone, Debug)] +struct RootPlacer { + trunk_offset_y: IntProvider, + root_provider: BlockStateProvider, + above: Option<(BlockStateProvider, f32)>, + mangrove: MangroveRoots, +} +impl RootPlacer { + fn decode(raw: &RawValue, decoder: &mut TreeDecoder<'_, '_>) -> Result { + let object: Object = serde_json::from_str(raw.get())?; + if kind(&object)? != "minecraft:mangrove_root_placer" { + return Err(DecodeError::Field("root placer type")); + } + let trunk_offset_y = IntProvider::decode( + required(&object, "trunk_offset_y")?, + decoder.depth + 1, + decoder.remaining, + )?; + let root_provider = decoder.provider(required(&object, "root_provider")?)?; + let above = optional(&object, "above_root_placement") + .map(|raw| -> Result<_, DecodeError> { + let above: Object = serde_json::from_str(raw.get())?; + Ok(( + decoder.provider(required(&above, "above_root_provider")?)?, + unit_float( + required(&above, "above_root_placement_chance")?, + "above_root_placement_chance", + )?, + )) + }) + .transpose()?; + let placement: Object = + serde_json::from_str(required(&object, "mangrove_root_placement")?.get())?; + let mangrove = MangroveRoots { + can_grow_through: decoder.block_set(required(&placement, "can_grow_through")?)?, + muddy_roots_in: decoder.block_set(required(&placement, "muddy_roots_in")?)?, + muddy_roots_provider: decoder + .provider(required(&placement, "muddy_roots_provider")?)?, + max_root_width: int_range( + required(&placement, "max_root_width")?, + "max_root_width", + 1, + 12, + )?, + max_root_length: int_range( + required(&placement, "max_root_length")?, + "max_root_length", + 1, + 64, + )?, + random_skew_chance: unit_float( + required(&placement, "random_skew_chance")?, + "random_skew_chance", + )?, + }; + Ok(Self { + trunk_offset_y, + root_provider, + above, + mangrove, + }) + } + fn can_place_root( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + ) -> TreeResult { + let state = read(run.world, position)?; + Ok(tree.blocks.valid_tree_pos(state) || self.mangrove.can_grow_through.contains(&state)) + } + fn waterlogged( + tree: &TreeFeature, + world: &mut W, + position: [i32; 3], + state: BlockStateId, + ) -> TreeResult { + if tree.blocks.has(state, tb::WATERLOGGABLE) { + let here = read(world, position)?; + Ok(tree + .blocks + .waterlogged(state, tree.blocks.has(here, tb::WATER_FLUID))) + } else { + Ok(state) + } + } + fn place_root( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + ) -> TreeResult<(), W::Error> { + let here = read(run.world, position)?; + if self.mangrove.muddy_roots_in.contains(&here) { + let state = sample_state( + &self.mangrove.muddy_roots_provider, + run.world, + run.random, + position, + )?; + let state = Self::waterlogged(tree, run.world, position, state)?; + return run.set(Layer::Root, position, state); + } + if !self.can_place_root(run, tree, position)? { + return Ok(()); + } + let state = sample_state(&self.root_provider, run.world, run.random, position)?; + let state = Self::waterlogged(tree, run.world, position, state)?; + run.set(Layer::Root, position, state)?; + if let Some((provider, chance)) = &self.above { + let above = tb::offset(position, 0, 1, 0); + if run.random.next_float() < *chance && tree.blocks.is_air(read(run.world, above)?) { + let state = sample_state(provider, run.world, run.random, above)?; + let state = Self::waterlogged(tree, run.world, above, state)?; + run.set(Layer::Root, above, state)?; + } + } + Ok(()) + } + fn place_roots( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + origin: [i32; 3], + trunk_origin: [i32; 3], + ) -> TreeResult { + let mut column = origin; + while column[1] < trunk_origin[1] { + if !self.can_place_root(run, tree, column)? { + return Ok(false); + } + column[1] = column[1].wrapping_add(1); + } + let mut roots = vec![tb::offset(trunk_origin, 0, -1, 0)]; + for direction in tb::HORIZONTAL { + let start = tb::relative(trunk_origin, direction, 1); + let mut positions = Vec::new(); + if !self.simulate(run, tree, start, direction, trunk_origin, &mut positions, 0)? { + return Ok(false); + } + roots.extend(positions); + roots.push(start); + } + for root in roots { + self.place_root(run, tree, root)?; + } + Ok(true) + } + #[allow(clippy::too_many_arguments)] + fn simulate( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + direction: Direction, + origin: [i32; 3], + positions: &mut Vec<[i32; 3]>, + layer: i32, + ) -> TreeResult { + let max = self.mangrove.max_root_length; + if layer == max || positions.len() as i64 > i64::from(max) { + return Ok(false); + } + for next in self.potential(run.random, position, direction, origin)? { + if self.can_place_root(run, tree, next)? { + positions.push(next); + if !self.simulate(run, tree, next, direction, origin, positions, layer + 1)? { + return Ok(false); + } + } + } + Ok(true) + } + #[allow(clippy::if_same_then_else)] // Native branch order controls random draws. + fn potential( + &self, + random: &mut impl RandomSource, + position: [i32; 3], + direction: Direction, + origin: [i32; 3], + ) -> TreeResult, E> { + let below = tb::offset(position, 0, -1, 0); + let next_to = tb::relative(position, direction, 1); + let width = tb::dist_manhattan(position, origin); + let max = self.mangrove.max_root_width; + let skew = self.mangrove.random_skew_chance; + Ok(if width > max - 3 && width <= max { + if random.next_float() < skew { + vec![below, tb::offset(next_to, 0, -1, 0)] + } else { + vec![below] + } + } else if width > max { + vec![below] + } else if random.next_float() < skew { + vec![below] + } else if random.next_boolean() { + vec![next_to] + } else { + vec![below] + }) + } +} + +#[derive(Clone, Debug)] +pub struct TreeFeature { + trunk_provider: BlockStateProvider, + trunk_placer: TrunkPlacer, + foliage_provider: BlockStateProvider, + foliage_placer: FoliagePlacer, + root_placer: Option, + minimum_size: FeatureSize, + min_clipped_height: Option, + decorators: Vec, + ignore_vines: bool, + below_trunk_provider: BlockStateProvider, + blocks: Arc, +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum Layer { + Root, + Trunk, + Foliage, + Decoration, +} +#[derive(Default)] +pub(crate) struct Sets { + roots: PosSet, + trunks: PosSet, + foliage: PosSet, + decorations: PosSet, +} +pub(crate) struct Run<'a, W, R> { + pub world: &'a mut W, + pub random: &'a mut R, + sets: Sets, + /// Fallen trees write decorations without recording them. + track: bool, +} +impl Run<'_, W, R> { + pub(crate) fn set( + &mut self, + layer: Layer, + position: [i32; 3], + state: BlockStateId, + ) -> TreeResult<(), W::Error> { + if self.track { + match layer { + Layer::Root => self.sets.roots.insert(position), + Layer::Trunk => self.sets.trunks.insert(position), + Layer::Foliage => self.sets.foliage.insert(position), + Layer::Decoration => self.sets.decorations.insert(position), + }; + } + write(self.world, position, state, 19)?; + Ok(()) + } + pub(crate) fn foliage_contains(&self, position: [i32; 3]) -> bool { + self.sets.foliage.contains(position) + } +} + +impl TreeFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + nested: &decorator::NestedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:tree" { + return Err(DecodeError::Field("tree feature type")); + } + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let trunk_provider = decoder.provider(required(&object, "trunk_provider")?)?; + let trunk_placer = TrunkPlacer::decode(required(&object, "trunk_placer")?, &mut decoder)?; + let foliage_provider = decoder.provider(required(&object, "foliage_provider")?)?; + let foliage_placer = + FoliagePlacer::decode(required(&object, "foliage_placer")?, &mut decoder)?; + let root_placer = optional(&object, "root_placer") + .map(|raw| RootPlacer::decode(raw, &mut decoder)) + .transpose()?; + let (minimum_size, min_clipped_height) = + FeatureSize::decode(required(&object, "minimum_size")?)?; + let decorators = TreeDecorator::decode_list( + required(&object, "decorators")?, + &mut decoder, + optional(&object, decorator::GROUND_FEATURE_KEY), + nested, + )?; + let ignore_vines = optional(&object, "ignore_vines") + .map(|raw| serde_json::from_str::(raw.get())) + .transpose()? + .unwrap_or(false); + let below_trunk_provider = decoder.provider(required(&object, "below_trunk_provider")?)?; + Ok(Self { + trunk_provider, + trunk_placer, + foliage_provider, + foliage_placer, + root_placer, + minimum_size, + min_clipped_height, + decorators, + ignore_vines, + below_trunk_provider, + blocks, + }) + } + + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut NestedPlacer<'_, W, R>, + ) -> TreeResult { + let mut run = Run { + world, + random, + sets: Sets::default(), + track: true, + }; + let result = self.do_place(&mut run, origin)?; + if !result || (run.sets.trunks.is_empty() && run.sets.foliage.is_empty()) { + return Ok(false); + } + if !self.decorators.is_empty() { + let lists = decorator::Lists::new( + run.sets.trunks.to_vec(), + run.sets.foliage.to_vec(), + run.sets.roots.to_vec(), + ); + for decorator in &self.decorators { + decorator.place(&mut run, &self.blocks, &lists, nested)?; + } + } + let mut bounds: Option<([i32; 3], [i32; 3])> = None; + for set in [ + &run.sets.roots, + &run.sets.trunks, + &run.sets.foliage, + &run.sets.decorations, + ] { + for p in set.to_vec() { + bounds = Some(match bounds { + None => (p, p), + Some((lo, hi)) => ( + std::array::from_fn(|i| lo[i].min(p[i])), + std::array::from_fn(|i| hi[i].max(p[i])), + ), + }); + } + } + let Some((low, high)) = bounds else { + return Ok(false); + }; + let shape = update_leaves(&mut run, &self.blocks, low, high)?; + update_shape_at_edge(run.world, &shape, low, 3)?; + Ok(true) + } + + fn do_place( + &self, + run: &mut Run<'_, W, R>, + origin: [i32; 3], + ) -> TreeResult { + let tree_height = self.trunk_placer.tree_height(run.random)?; + let foliage_height = self.foliage_placer.foliage_height(run.random, tree_height)?; + let trunk_height = tree_height.wrapping_sub(foliage_height); + let leaf_radius = self.foliage_placer.foliage_radius(run.random, trunk_height)?; + let trunk_origin = match &self.root_placer { + Some(root) => tb::offset(origin, 0, root.trunk_offset_y.sample(run.random)?, 0), + None => origin, + }; + let min_y = origin[1].min(trunk_origin[1]); + let max_y = origin[1] + .max(trunk_origin[1]) + .wrapping_add(tree_height) + .wrapping_add(1); + let world_min = run.world.min_y().map_err(FeatureExecutionError::Query)?; + let world_max = run.world.max_y().map_err(FeatureExecutionError::Query)?; + if min_y < world_min.wrapping_add(1) || max_y > world_max.wrapping_add(1) { + return Ok(false); + } + let clipped = self.max_free_tree_height(run, tree_height, trunk_origin)?; + if clipped < tree_height && self.min_clipped_height.is_none_or(|min| clipped < min) { + return Ok(false); + } + if let Some(root) = &self.root_placer { + if !root.place_roots(run, self, origin, trunk_origin)? { + return Ok(false); + } + } + let attachments = self + .trunk_placer + .place_trunk(run, self, clipped, trunk_origin)?; + for attachment in attachments { + self.foliage_placer.create_foliage( + run, + self, + clipped, + attachment, + foliage_height, + leaf_radius, + )?; + } + Ok(true) + } + + fn max_free_tree_height( + &self, + run: &mut Run<'_, W, R>, + max_tree_height: i32, + tree_pos: [i32; 3], + ) -> TreeResult { + let mut y = 0; + while y <= max_tree_height.wrapping_add(1) { + let r = self.minimum_size.size_at_height(max_tree_height, y); + for x in -r..=r { + for z in -r..=r { + let p = tb::offset(tree_pos, x, y, z); + let state = read(run.world, p)?; + if !self.trunk_placer.is_free(&self.blocks, state) + || (!self.ignore_vines && self.blocks.has(state, tb::VINE)) + { + return Ok(y - 2); + } + } + } + y += 1; + } + Ok(max_tree_height) + } + + /// FoliagePlacer.tryPlaceLeaf. + pub(crate) fn try_place_leaf( + &self, + run: &mut Run<'_, W, R>, + position: [i32; 3], + ) -> TreeResult { + let here = read(run.world, position)?; + if self.blocks.has(here, tb::PERSISTENT) || !self.blocks.valid_tree_pos(here) { + return Ok(false); + } + let mut state = sample_state(&self.foliage_provider, run.world, run.random, position)?; + if self.blocks.has(state, tb::WATERLOGGABLE) { + let here = read(run.world, position)?; + state = self + .blocks + .waterlogged(state, self.blocks.has(here, tb::WATER_SOURCE)); + } + run.set(Layer::Foliage, position, state)?; + Ok(true) + } +} + +/// Voxel occupancy over the tree's bounding box. +pub(crate) struct Shape { + size: [i32; 3], + bits: Vec, +} +impl Shape { + fn new(size: [i32; 3]) -> Self { + let len = size.iter().map(|v| *v as usize).product(); + Self { + size, + bits: vec![false; len], + } + } + fn index(&self, [x, y, z]: [i32; 3]) -> usize { + ((x * self.size[1] + y) * self.size[2] + z) as usize + } + fn fill(&mut self, p: [i32; 3]) { + let i = self.index(p); + self.bits[i] = true; + } + fn full(&self, p: [i32; 3]) -> bool { + p.iter() + .zip(self.size) + .all(|(v, size)| (0..size).contains(v)) + && self.bits[self.index(p)] + } +} + +const MAX_TREE_SPAN: i64 = 512; +fn inside(low: [i32; 3], high: [i32; 3], p: [i32; 3]) -> bool { + (0..3).all(|i| p[i] >= low[i] && p[i] <= high[i]) +} + +/// TreeFeature.updateLeaves: native bucketed breadth-first distance pass. +fn update_leaves( + run: &mut Run<'_, W, R>, + blocks: &TreeBlocks, + low: [i32; 3], + high: [i32; 3], +) -> TreeResult { + let span: [i64; 3] = std::array::from_fn(|i| i64::from(high[i]) - i64::from(low[i]) + 1); + if span.iter().any(|s| *s > MAX_TREE_SPAN) { + return Err(FeatureExecutionError::WorkLimit); + } + let mut shape = Shape::new(span.map(|v| v as i32)); + let local = |p: [i32; 3]| -> [i32; 3] { std::array::from_fn(|i| p[i].wrapping_sub(low[i])) }; + let mut fixed = run.sets.decorations.to_vec(); + fixed.extend(run.sets.roots.to_vec()); + for p in fixed { + if inside(low, high, p) { + shape.fill(local(p)); + } + } + let mut to_check: [PosSet; 7] = Default::default(); + for p in run.sets.trunks.to_vec() { + to_check[0].insert(p); + } + let mut smallest = 0usize; + loop { + while smallest >= 7 || !to_check[smallest].is_empty() { + if smallest >= 7 { + return Ok(shape); + } + let pos = to_check[smallest] + .pop_first() + .ok_or(FeatureExecutionError::InvalidState)?; + if !inside(low, high, pos) { + continue; + } + if smallest != 0 { + let state = read(run.world, pos)?; + let updated = blocks + .with(state, "distance", &smallest.to_string()) + .ok_or(FeatureExecutionError::InvalidState)?; + write(run.world, pos, updated, 19)?; + } + shape.fill(local(pos)); + for direction in Direction::ALL { + let neighbor = tb::relative(pos, direction, 1); + if !inside(low, high, neighbor) || shape.full(local(neighbor)) { + continue; + } + let state = read(run.world, neighbor)?; + if let Some(distance) = blocks.leaf_distance(state) { + let next = distance.min(smallest as i32 + 1); + if next < 7 { + to_check[next as usize].insert(neighbor); + smallest = smallest.min(next as usize); + } + } + } + } + smallest += 1; + } +} + +/// StructureTemplate.updateShapeAtEdge face traversal (DiscreteVoxelShape.forAllFaces). +pub(crate) fn update_shape_at_edge( + world: &mut W, + shape: &Shape, + start: [i32; 3], + flags: i32, +) -> TreeResult<(), W::Error> { + let [sx, sy, sz] = shape.size; + // (c-axis, a size, b size, mapping (a, b, c) -> (x, y, z)) + type Map = fn(i32, i32, i32) -> [i32; 3]; + let passes: [(Direction, Direction, i32, i32, i32, Map); 3] = [ + (Direction::North, Direction::South, sx, sy, sz, |a, b, c| [a, b, c]), + (Direction::Down, Direction::Up, sz, sx, sy, |a, b, c| [b, c, a]), + (Direction::West, Direction::East, sy, sz, sx, |a, b, c| [c, a, b]), + ]; + for (negative, positive, a_size, b_size, c_size, map) in passes { + for a in 0..a_size { + for b in 0..b_size { + let mut last = false; + for c in 0..=c_size { + let full = c != c_size && shape.full(map(a, b, c)); + let face = if !last && full { + Some((negative, map(a, b, c))) + } else if last && !full { + Some((positive, map(a, b, c - 1))) + } else { + None + }; + if let Some((direction, local)) = face { + let p = std::array::from_fn(|i| start[i].wrapping_add(local[i])); + world + .update_shape_at_face(p, direction, flags) + .map_err(FeatureExecutionError::Query)?; + } + last = full; + } + } + } + } + Ok(()) +} diff --git a/crates/horizon-world/src/worldgen/tree/decorator.rs b/crates/horizon-world/src/worldgen/tree/decorator.rs new file mode 100644 index 000000000..be579b716 --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree/decorator.rs @@ -0,0 +1,671 @@ +//! Tree decorators (TreeDecorator subclasses), in native random-draw order. +use super::{ + Layer, NestedPlacer, Run, TreeDecoder, TreeResult, kind, read, sample_optional, sample_state, + unit_float, +}; +use crate::registry::BlockStateId; +use crate::worldgen::{ + DecodeError, Object, int_range, optional, + feature::FeatureWorld, + feature_graph::{FeatureDefinition, FeatureExecutionError}, + placement::PlacementContext, + required, + state_provider::BlockStateProvider, + tree_blocks::{self as tb, TreeBlocks}, +}; +use crate::heightmap::HeightmapType; +use horizon_core::{geometry::Direction, random::RandomSource}; +use serde_json::value::RawValue; +use std::collections::BTreeSet; + +/// Catalog-injected configured feature for the pale-moss ground patch, which +/// vanilla looks up by registry key during decoration. +pub(crate) const GROUND_FEATURE_KEY: &str = "horizon:pale_moss_patch"; + +/// Decorator context lists: set iteration order, stably sorted by Y. +pub(crate) struct Lists { + pub logs: Vec<[i32; 3]>, + pub leaves: Vec<[i32; 3]>, + pub roots: Vec<[i32; 3]>, +} +impl Lists { + pub(crate) fn new( + mut logs: Vec<[i32; 3]>, + mut leaves: Vec<[i32; 3]>, + mut roots: Vec<[i32; 3]>, + ) -> Self { + logs.sort_by_key(|p| p[1]); + leaves.sort_by_key(|p| p[1]); + roots.sort_by_key(|p| p[1]); + Self { + logs, + leaves, + roots, + } + } + /// TreeFeature.getLowestTrunkOrRootOfTree. + fn lowest(&self) -> Vec<[i32; 3]> { + if self.roots.is_empty() { + self.logs.clone() + } else if !self.logs.is_empty() && self.roots[0][1] == self.logs[0][1] { + let mut all = self.logs.clone(); + all.extend(&self.roots); + all + } else { + self.roots.clone() + } + } +} + +#[derive(Clone, Debug)] +pub(crate) enum TreeDecorator { + TrunkVine, + LeaveVine(f32), + Cocoa(f32), + Beehive(f32), + AlterGround(BlockStateProvider), + AttachedToLeaves { + probability: f32, + exclusion_xz: i32, + exclusion_y: i32, + provider: BlockStateProvider, + required_empty: i32, + directions: Vec, + }, + AttachedToLogs { + probability: f32, + provider: BlockStateProvider, + directions: Vec, + }, + CreakingHeart(f32), + PaleMoss { + leaves: f32, + trunk: f32, + ground: f32, + patch: Option>, + }, + PlaceOnGround { + tries: i32, + radius: i32, + height: i32, + provider: BlockStateProvider, + }, + ShelfMushroom(f32), +} + +fn directions(raw: &RawValue) -> Result, DecodeError> { + let names: Vec = serde_json::from_str(raw.get())?; + if names.is_empty() || names.len() > 64 { + return Err(DecodeError::Field("decorator directions")); + } + names.iter().map(|n| tb::decode_direction(n)).collect() +} + +pub(crate) type NestedDecoder<'a> = + dyn Fn(&str, usize, &mut usize) -> Result + 'a; + +impl TreeDecorator { + pub(crate) fn decode_list( + raw: &RawValue, + decoder: &mut TreeDecoder<'_, '_>, + ground: Option<&RawValue>, + nested: &NestedDecoder<'_>, + ) -> Result, DecodeError> { + let values: Vec> = serde_json::from_str(raw.get())?; + if values.len() > 256 { + return Err(DecodeError::Field("tree decorator count")); + } + values + .iter() + .map(|raw| Self::decode(raw, decoder, ground, nested)) + .collect() + } + fn decode( + raw: &RawValue, + decoder: &mut TreeDecoder<'_, '_>, + ground: Option<&RawValue>, + nested: &NestedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(raw.get())?; + let probability = || unit_float(required(&object, "probability")?, "probability"); + Ok(match kind(&object)?.as_str() { + "minecraft:trunk_vine" => Self::TrunkVine, + "minecraft:leave_vine" => Self::LeaveVine(probability()?), + "minecraft:cocoa" => Self::Cocoa(probability()?), + "minecraft:beehive" => Self::Beehive(probability()?), + "minecraft:creaking_heart" => Self::CreakingHeart(probability()?), + "minecraft:shelf_mushroom" => Self::ShelfMushroom(probability()?), + "minecraft:alter_ground" => { + Self::AlterGround(decoder.provider(required(&object, "provider")?)?) + } + "minecraft:attached_to_leaves" => Self::AttachedToLeaves { + probability: probability()?, + exclusion_xz: int_range( + required(&object, "exclusion_radius_xz")?, + "exclusion_radius_xz", + 0, + 16, + )?, + exclusion_y: int_range( + required(&object, "exclusion_radius_y")?, + "exclusion_radius_y", + 0, + 16, + )?, + provider: decoder.provider(required(&object, "block_provider")?)?, + required_empty: int_range( + required(&object, "required_empty_blocks")?, + "required_empty_blocks", + 1, + 16, + )?, + directions: directions(required(&object, "directions")?)?, + }, + "minecraft:attached_to_logs" => Self::AttachedToLogs { + probability: probability()?, + provider: decoder.provider(required(&object, "block_provider")?)?, + directions: directions(required(&object, "directions")?)?, + }, + "minecraft:pale_moss" => Self::PaleMoss { + leaves: unit_float( + required(&object, "leaves_probability")?, + "leaves_probability", + )?, + trunk: unit_float(required(&object, "trunk_probability")?, "trunk_probability")?, + ground: unit_float( + required(&object, "ground_probability")?, + "ground_probability", + )?, + patch: ground + .map(|raw| nested(raw.get(), decoder.depth + 1, decoder.remaining)) + .transpose()? + .map(Box::new), + }, + "minecraft:place_on_ground" => Self::PlaceOnGround { + tries: optional(&object, "tries") + .map(|raw| int_range(raw, "tries", 1, i32::MAX)) + .transpose()? + .unwrap_or(128), + radius: optional(&object, "radius") + .map(|raw| int_range(raw, "radius", 0, i32::MAX)) + .transpose()? + .unwrap_or(2), + height: optional(&object, "height") + .map(|raw| int_range(raw, "height", 0, i32::MAX)) + .transpose()? + .unwrap_or(1), + provider: decoder.provider(required(&object, "block_state_provider")?)?, + }, + _ => return Err(DecodeError::Field("tree decorator type")), + }) + } + + pub(crate) fn place( + &self, + run: &mut Run<'_, W, R>, + blocks: &TreeBlocks, + lists: &Lists, + nested: &mut NestedPlacer<'_, W, R>, + ) -> TreeResult<(), W::Error> { + let mut d = Decorate { run, blocks }; + match self { + Self::TrunkVine => { + for &pos in &lists.logs { + for (direction, face) in [ + (Direction::West, "east"), + (Direction::East, "west"), + (Direction::North, "south"), + (Direction::South, "north"), + ] { + if d.run.random.next_int_bound(3)? > 0 { + let p = tb::relative(pos, direction, 1); + if d.is_air(p)? { + d.place_vine(p, face)?; + } + } + } + } + } + Self::LeaveVine(probability) => { + for &pos in &lists.leaves { + for (direction, face) in [ + (Direction::West, "east"), + (Direction::East, "west"), + (Direction::North, "south"), + (Direction::South, "north"), + ] { + if d.run.random.next_float() < *probability { + let p = tb::relative(pos, direction, 1); + if d.is_air(p)? { + d.place_vine(p, face)?; + let mut below = tb::offset(p, 0, -1, 0); + let mut remaining = 4; + while d.is_air(below)? && remaining > 0 { + d.place_vine(below, face)?; + below = tb::offset(below, 0, -1, 0); + remaining -= 1; + } + } + } + } + } + } + Self::Cocoa(probability) => { + if d.run.random.next_float() >= *probability { + return Ok(()); + } + let Some(first) = lists.logs.first() else { + return Ok(()); + }; + let tree_y = first[1]; + for &pos in lists + .logs + .iter() + .filter(|p| p[1].wrapping_sub(tree_y) <= 2) + { + for direction in tb::HORIZONTAL { + if d.run.random.next_float() <= 0.25 { + let n = direction.opposite().normal(); + let p = tb::offset(pos, n[0], 0, n[2]); + if d.is_air(p)? { + let age = d.run.random.next_int_bound(3)?; + let state = d.default("minecraft:cocoa")?; + let state = d.with(state, "age", &age.to_string())?; + let state = d.with(state, "facing", tb::direction_name(direction))?; + d.set(p, state)?; + } + } + } + } + } + Self::Beehive(probability) => d.beehive(lists, *probability)?, + Self::AlterGround(provider) => { + let positions = lists.lowest(); + let Some(first) = positions.first() else { + return Ok(()); + }; + let min_y = first[1]; + for &pos in positions.iter().filter(|p| p[1] == min_y) { + d.circle(provider, tb::offset(pos, -1, 0, -1))?; + d.circle(provider, tb::offset(pos, 2, 0, -1))?; + d.circle(provider, tb::offset(pos, -1, 0, 2))?; + d.circle(provider, tb::offset(pos, 2, 0, 2))?; + for _ in 0..5 { + let placement = d.run.random.next_int_bound(64)?; + let (xx, zz) = (placement % 8, placement / 8); + if xx == 0 || xx == 7 || zz == 0 || zz == 7 { + d.circle(provider, tb::offset(pos, -3 + xx, 0, -3 + zz))?; + } + } + } + } + Self::AttachedToLeaves { + probability, + exclusion_xz, + exclusion_y, + provider, + required_empty, + directions, + } => { + let mut blacklist = BTreeSet::new(); + let mut leaves = lists.leaves.clone(); + tb::shuffle(&mut leaves, d.run.random)?; + for leaf in leaves { + let direction = + directions[d.run.random.next_int_bound(directions.len() as i32)? as usize]; + let p = tb::relative(leaf, direction, 1); + if blacklist.contains(&p) || d.run.random.next_float() >= *probability { + continue; + } + let mut empty = true; + for i in 1..=*required_empty { + if !d.is_air(tb::relative(leaf, direction, i))? { + empty = false; + break; + } + } + if !empty { + continue; + } + for dx in -exclusion_xz..=*exclusion_xz { + for dy in -exclusion_y..=*exclusion_y { + for dz in -exclusion_xz..=*exclusion_xz { + blacklist.insert(tb::offset(p, dx, dy, dz)); + } + } + } + let state = sample_state(provider, d.run.world, d.run.random, p)?; + d.set(p, state)?; + } + } + Self::AttachedToLogs { + probability, + provider, + directions, + } => { + let mut logs = lists.logs.clone(); + tb::shuffle(&mut logs, d.run.random)?; + for log in logs { + let direction = + directions[d.run.random.next_int_bound(directions.len() as i32)? as usize]; + let p = tb::relative(log, direction, 1); + if d.run.random.next_float() <= *probability && d.is_air(p)? { + let state = sample_state(provider, d.run.world, d.run.random, p)?; + d.set(p, state)?; + } + } + } + Self::CreakingHeart(probability) => { + if lists.logs.is_empty() || d.run.random.next_float() >= *probability { + return Ok(()); + } + let mut candidates = lists.logs.clone(); + tb::shuffle(&mut candidates, d.run.random)?; + for pos in candidates { + let mut enclosed = true; + for direction in Direction::ALL { + let state = read(d.run.world, tb::relative(pos, direction, 1))?; + if !blocks.has(state, tb::LOGS) { + enclosed = false; + break; + } + } + if enclosed { + let state = d.default("minecraft:creaking_heart")?; + let state = d.with(state, "creaking_heart_state", "dormant")?; + let state = d.with(state, "natural", "true")?; + d.set(pos, state)?; + break; + } + } + } + Self::PaleMoss { + leaves, + trunk, + ground, + patch, + } => { + let mut logs = lists.logs.clone(); + tb::shuffle(&mut logs, d.run.random)?; + let Some(origin) = logs + .iter() + .copied() + .reduce(|best, p| if p[1] < best[1] { p } else { best }) + else { + return Ok(()); + }; + if d.run.random.next_float() < *ground { + if let Some(patch) = patch { + nested(patch, d.run.world, d.run.random, tb::offset(origin, 0, 1, 0))?; + } + } + for (positions, chance) in [(&lists.logs, *trunk), (&lists.leaves, *leaves)] { + for &pos in positions { + if d.run.random.next_float() < chance { + let down = tb::offset(pos, 0, -1, 0); + if d.is_air(down)? { + d.moss_hanger(down)?; + } + } + } + } + } + Self::PlaceOnGround { + tries, + radius, + height, + provider, + } => { + let positions = lists.lowest(); + let Some(&origin) = positions.first() else { + return Ok(()); + }; + let min_y = origin[1]; + let (mut min_x, mut max_x, mut min_z, mut max_z) = + (origin[0], origin[0], origin[2], origin[2]); + for p in positions.iter().filter(|p| p[1] == min_y) { + min_x = min_x.min(p[0]); + max_x = max_x.max(p[0]); + min_z = min_z.min(p[2]); + max_z = max_z.max(p[2]); + } + let low = [ + min_x.wrapping_sub(*radius), + min_y.wrapping_sub(*height), + min_z.wrapping_sub(*radius), + ]; + let high = [ + max_x.wrapping_add(*radius), + min_y.wrapping_add(*height), + max_z.wrapping_add(*radius), + ]; + for _ in 0..*tries { + let p = [ + d.run.random.next_int_between_inclusive(low[0], high[0])?, + d.run.random.next_int_between_inclusive(low[1], high[1])?, + d.run.random.next_int_between_inclusive(low[2], high[2])?, + ]; + let above = tb::offset(p, 0, 1, 0); + let above_state = read(d.run.world, above)?; + if !blocks.has(above_state, tb::AIR | tb::VINE) { + continue; + } + if !blocks.has(read(d.run.world, p)?, tb::SOLID_RENDER) { + continue; + } + let surface = d + .run + .world + .height(HeightmapType::MotionBlockingNoLeaves, p[0], p[2]) + .map_err(FeatureExecutionError::Query)?; + if surface <= above[1] { + let state = sample_state(provider, d.run.world, d.run.random, above)?; + d.set(above, state)?; + } + } + } + Self::ShelfMushroom(probability) => d.shelf_mushroom(lists, *probability)?, + } + Ok(()) + } +} + +struct Decorate<'a, 'b, 'w, W, R> { + run: &'a mut Run<'w, W, R>, + blocks: &'b TreeBlocks, +} +impl Decorate<'_, '_, '_, W, R> { + fn is_air(&mut self, p: [i32; 3]) -> TreeResult { + Ok(self.blocks.is_air(read(self.run.world, p)?)) + } + fn has(&mut self, p: [i32; 3], flag: u32) -> TreeResult { + Ok(self.blocks.has(read(self.run.world, p)?, flag)) + } + fn set(&mut self, p: [i32; 3], state: BlockStateId) -> TreeResult<(), W::Error> { + self.run.set(Layer::Decoration, p, state) + } + fn default(&self, name: &str) -> TreeResult { + self.blocks + .default_state(name) + .ok_or(FeatureExecutionError::InvalidState) + } + fn with( + &self, + state: BlockStateId, + name: &str, + value: &str, + ) -> TreeResult { + self.blocks + .with(state, name, value) + .ok_or(FeatureExecutionError::InvalidState) + } + fn place_vine(&mut self, p: [i32; 3], face: &str) -> TreeResult<(), W::Error> { + let vine = self.default("minecraft:vine")?; + let state = self.with(vine, face, "true")?; + self.set(p, state) + } + fn circle(&mut self, provider: &BlockStateProvider, center: [i32; 3]) -> TreeResult<(), W::Error> { + for xx in -2i32..=2 { + for zz in -2i32..=2 { + if xx.abs() != 2 || zz.abs() != 2 { + let column = tb::offset(center, xx, 0, zz); + for dy in (-3..=2).rev() { + let cursor = tb::offset(column, 0, dy, 0); + if let Some(state) = + sample_optional(provider, self.run.world, self.run.random, cursor)? + { + self.set(cursor, state)?; + break; + } + if !self.is_air(cursor)? && dy < 0 { + break; + } + } + } + } + } + Ok(()) + } + fn moss_hanger(&mut self, mut p: [i32; 3]) -> TreeResult<(), W::Error> { + let moss = self.default("minecraft:pale_hanging_moss")?; + let middle = self.with(moss, "tip", "false")?; + let tip = self.with(moss, "tip", "true")?; + while self.is_air(tb::offset(p, 0, -1, 0))? && self.run.random.next_float() >= 0.5 { + self.set(p, middle)?; + p = tb::offset(p, 0, -1, 0); + } + self.set(p, tip) + } + fn beehive(&mut self, lists: &Lists, probability: f32) -> TreeResult<(), W::Error> { + let (Some(first_log), Some(last_log)) = (lists.logs.first(), lists.logs.last()) else { + return Ok(()); + }; + if self.run.random.next_float() >= probability { + return Ok(()); + } + let hive_y = match lists.leaves.first() { + Some(leaf) => (leaf[1] - 1).max(first_log[1] + 1), + None => (first_log[1] + 1 + self.run.random.next_int_bound(3)?).min(last_log[1]), + }; + let mut placements: Vec<[i32; 3]> = lists + .logs + .iter() + .filter(|p| p[1] == hive_y) + .flat_map(|p| { + [Direction::East, Direction::South, Direction::West] + .map(|d| tb::relative(*p, d, 1)) + }) + .collect(); + if placements.is_empty() { + return Ok(()); + } + tb::shuffle(&mut placements, self.run.random)?; + for p in placements { + if self.is_air(p)? && self.is_air(tb::relative(p, Direction::South, 1))? { + let nest = self.default("minecraft:bee_nest")?; + let nest = self.with(nest, "facing", "south")?; + self.set(p, nest)?; + // Occupants exist only when the write produced the nest block entity. + if read(self.run.world, p)? == nest { + let count = 2 + self.run.random.next_int_bound(2)?; + let mut ticks = Vec::with_capacity(count as usize); + for _ in 0..count { + ticks.push(self.run.random.next_int_bound(599)?); + } + self.run + .world + .store_beehive_occupants(p, &ticks) + .map_err(FeatureExecutionError::Query)?; + } + break; + } + } + Ok(()) + } + fn shelf_mushroom(&mut self, lists: &Lists, probability: f32) -> TreeResult<(), W::Error> { + if self.run.random.next_float() >= probability { + return Ok(()); + } + let (Some(first), Some(last)) = (lists.logs.first(), lists.logs.last()) else { + return Ok(()); + }; + if first[1] == last[1] { + let facings = if first[0] != last[0] { + [Direction::North, Direction::South] + } else { + [Direction::East, Direction::West] + }; + for &log in &lists.logs { + for facing in facings { + if self.run.random.next_float() <= 0.25 { + let p = mushroom_pos(log, facing); + if self.mushroom_replaceable(p)? + && !self.adjacent_mushroom(p)? + && !self.adjacent_mushroom(log)? + { + self.place_mushroom(p, facing)?; + } + } + } + } + } else { + let a = tb::HORIZONTAL[self.run.random.next_int_bound(4)? as usize]; + let facings = [a, tb::clockwise(a)]; + let base = first[1]; + for &log in &lists.logs { + let dy = log[1].wrapping_sub(base); + if !(1..=4).contains(&dy) { + continue; + } + for facing in facings { + if self.run.random.next_float() <= 0.25 { + let p = mushroom_pos(log, facing); + if self.mushroom_replaceable(p)? + && !self.has(tb::offset(p, 0, -1, 0), tb::SHELF_MUSHROOM)? + { + self.place_mushroom(p, facing)?; + break; + } + } + } + } + } + Ok(()) + } + fn mushroom_replaceable(&mut self, p: [i32; 3]) -> TreeResult { + if !self.has(p, tb::REPLACEABLE)? { + return Ok(false); + } + for q in [ + p, + tb::offset(p, 1, 0, 0), + tb::offset(p, -1, 0, 0), + tb::offset(p, 0, 0, -1), + tb::offset(p, 0, 0, 1), + ] { + if self.has(q, tb::WATER_BLOCK)? { + return Ok(false); + } + } + Ok(true) + } + fn adjacent_mushroom(&mut self, p: [i32; 3]) -> TreeResult { + for direction in tb::HORIZONTAL { + if self.has(tb::relative(p, direction, 1), tb::SHELF_MUSHROOM)? { + return Ok(true); + } + } + Ok(false) + } + fn place_mushroom(&mut self, p: [i32; 3], facing: Direction) -> TreeResult<(), W::Error> { + let age = self.run.random.next_int_bound(2)?; + let state = self.default("minecraft:shelf_mushroom")?; + let state = self.with(state, "age", &age.to_string())?; + let state = self.with(state, "facing", tb::direction_name(facing))?; + self.set(p, state) + } +} +fn mushroom_pos(log: [i32; 3], facing: Direction) -> [i32; 3] { + let n = facing.normal(); + tb::offset(log, n[0], 0, n[2]) +} diff --git a/crates/horizon-world/src/worldgen/tree/fallen.rs b/crates/horizon-world/src/worldgen/tree/fallen.rs new file mode 100644 index 000000000..ac4ba25ec --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree/fallen.rs @@ -0,0 +1,182 @@ +//! `minecraft:fallen_tree`: a stump and an optional fallen log with decorators. +use super::{ + NestedPlacer, Run, Sets, TreeDecoder, TreeResult, decorator::Lists, decorator::NestedDecoder, + decorator::TreeDecorator, kind, read, sample_state, write, +}; +use crate::worldgen::{ + DecodeError, Object, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::PlacementContext, + required, + state_provider::BlockStateProvider, + tree_blocks::{self as tb, Axis, PosSet, TreeBlocks}, + value_provider::IntProvider, +}; +use horizon_core::{geometry::Direction, random::RandomSource}; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub struct FallenTreeFeature { + trunk_provider: BlockStateProvider, + log_length: IntProvider, + stump_decorators: Vec, + log_decorators: Vec, + blocks: Arc, +} +impl FallenTreeFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + nested: &NestedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:fallen_tree" { + return Err(DecodeError::Field("fallen tree feature type")); + } + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + Ok(Self { + trunk_provider: decoder.provider(required(&object, "trunk_provider")?)?, + log_length: decoder.int_provider(required(&object, "log_length")?, 0, 16)?, + stump_decorators: TreeDecorator::decode_list( + required(&object, "stump_decorators")?, + &mut decoder, + None, + nested, + )?, + log_decorators: TreeDecorator::decode_list( + required(&object, "log_decorators")?, + &mut decoder, + None, + nested, + )?, + blocks, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut NestedPlacer<'_, W, R>, + ) -> TreeResult { + let mut run = Run { + world, + random, + sets: Sets::default(), + track: false, + }; + let stump = self.place_log(&mut run, origin, None)?; + self.decorate(&mut run, &[stump], &self.stump_decorators, nested)?; + let direction = tb::HORIZONTAL[run.random.next_int_bound(4)? as usize]; + let length = self.log_length.sample(run.random)? - 2; + let mut start = tb::relative(origin, direction, 2 + run.random.next_int_bound(2)?); + start = tb::offset(start, 0, 1, 0); + for _ in 0..6 { + if self.may_place_on(&mut run, start)? { + break; + } + start = tb::offset(start, 0, -1, 0); + } + if self.can_place_log(&mut run, length, start, direction)? { + let mut logs = PosSet::default(); + let mut p = start; + for _ in 0..length { + logs.insert(self.place_log(&mut run, p, Some(Axis::of(direction)))?); + p = tb::relative(p, direction, 1); + } + self.decorate(&mut run, &logs.to_vec(), &self.log_decorators, nested)?; + } + Ok(true) + } + fn decorate( + &self, + run: &mut Run<'_, W, R>, + logs: &[[i32; 3]], + decorators: &[TreeDecorator], + nested: &mut NestedPlacer<'_, W, R>, + ) -> TreeResult<(), W::Error> { + if decorators.is_empty() { + return Ok(()); + } + let lists = Lists::new(logs.to_vec(), vec![], vec![]); + for decorator in decorators { + decorator.place(run, &self.blocks, &lists, nested)?; + } + Ok(()) + } + fn place_log( + &self, + run: &mut Run<'_, W, R>, + p: [i32; 3], + axis: Option, + ) -> TreeResult<[i32; 3], W::Error> { + let mut state = sample_state(&self.trunk_provider, run.world, run.random, p)?; + if let Some(axis) = axis { + state = self.blocks.try_axis(state, axis); + } + write(run.world, p, state, 3)?; + // Feature.markAboveForPostProcessing. + let mut above = p; + for _ in 0..2 { + above = tb::offset(above, 0, 1, 0); + if self.blocks.is_air(read(run.world, above)?) { + break; + } + run.world + .mark_postprocessing(above) + .map_err(FeatureExecutionError::Query)?; + } + Ok(p) + } + fn over_solid_ground( + &self, + run: &mut Run<'_, W, R>, + p: [i32; 3], + ) -> TreeResult { + let below = read(run.world, tb::offset(p, 0, -1, 0))?; + run.world + .state_face_sturdy(below, p, Direction::Up) + .map_err(FeatureExecutionError::Query) + } + fn may_place_on( + &self, + run: &mut Run<'_, W, R>, + p: [i32; 3], + ) -> TreeResult { + Ok(self.blocks.valid_tree_pos(read(run.world, p)?) && self.over_solid_ground(run, p)?) + } + fn can_place_log( + &self, + run: &mut Run<'_, W, R>, + length: i32, + start: [i32; 3], + direction: Direction, + ) -> TreeResult { + let mut gap = 0; + let mut p = start; + for _ in 0..length { + if !self.blocks.valid_tree_pos(read(run.world, p)?) { + return Ok(false); + } + if !self.over_solid_ground(run, p)? { + gap += 1; + if gap > 2 { + return Ok(false); + } + } else { + gap = 0; + } + p = tb::relative(p, direction, 1); + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/tree/foliage.rs b/crates/horizon-world/src/worldgen/tree/foliage.rs new file mode 100644 index 000000000..d753b171c --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree/foliage.rs @@ -0,0 +1,629 @@ +//! Foliage placers (FoliagePlacer subclasses), in native random-draw order. +use super::{Layer, Run, TreeDecoder, TreeFeature, TreeResult, kind, read, sample_state, unit_float}; +use crate::worldgen::{ + DecodeError, Object, int_range, + feature::FeatureWorld, + placement::PlacementContext, + required, + tree_blocks::{self as tb, Axis}, + value_provider::IntProvider, +}; +use horizon_core::{geometry::Direction, random::RandomSource}; +use serde_json::value::RawValue; + +#[derive(Clone, Copy, Debug)] +pub(crate) struct FoliageAttachment { + pub pos: [i32; 3], + pub radius_offset: i32, + pub height_offset: i32, + size: [i32; 2], +} +impl FoliageAttachment { + pub(crate) fn new(pos: [i32; 3], radius_offset: i32, double_trunk: bool) -> Self { + let size = if double_trunk { 2 } else { 1 }; + Self { + pos, + radius_offset, + height_offset: 0, + size: [size; 2], + } + } + fn double_trunk(&self) -> bool { + self.size == [2, 2] + } +} + +#[derive(Clone, Debug)] +enum Kind { + Blob(i32), + Fancy(i32), + Bush(i32), + Acacia, + Spruce(IntProvider), + Pine(IntProvider), + MegaPine(IntProvider), + MegaJungle(i32), + DarkOak, + RandomSpread { + foliage_height: IntProvider, + attempts: i32, + }, + Cherry { + height: IntProvider, + wide_bottom_hole: f32, + corner_hole: f32, + hanging: f32, + hanging_extension: f32, + }, + Poplar { + height: IntProvider, + side_hole: f32, + }, +} +#[derive(Clone, Debug)] +pub(super) struct FoliagePlacer { + radius: IntProvider, + offset: IntProvider, + kind: Kind, +} + +fn abs(v: i32) -> i32 { + v.wrapping_abs() +} + +impl FoliagePlacer { + pub(super) fn decode( + raw: &RawValue, + decoder: &mut TreeDecoder<'_, '_>, + ) -> Result { + let object: Object = serde_json::from_str(raw.get())?; + let radius = decoder.int_provider(required(&object, "radius")?, 0, 16)?; + let offset = decoder.int_provider(required(&object, "offset")?, 0, 16)?; + let fixed_height = || int_range(required(&object, "height")?, "foliage height", 0, 16); + let chance = |name: &'static str| unit_float(required(&object, name)?, name); + let kind = match kind(&object)?.as_str() { + "minecraft:blob_foliage_placer" => Kind::Blob(fixed_height()?), + "minecraft:fancy_foliage_placer" => Kind::Fancy(fixed_height()?), + "minecraft:bush_foliage_placer" => Kind::Bush(fixed_height()?), + "minecraft:jungle_foliage_placer" => Kind::MegaJungle(fixed_height()?), + "minecraft:acacia_foliage_placer" => Kind::Acacia, + "minecraft:dark_oak_foliage_placer" => Kind::DarkOak, + "minecraft:spruce_foliage_placer" => { + Kind::Spruce(decoder.int_provider(required(&object, "trunk_height")?, 0, 24)?) + } + "minecraft:pine_foliage_placer" => { + Kind::Pine(decoder.int_provider(required(&object, "height")?, 0, 24)?) + } + "minecraft:mega_pine_foliage_placer" => { + Kind::MegaPine(decoder.int_provider(required(&object, "crown_height")?, 0, 24)?) + } + "minecraft:random_spread_foliage_placer" => Kind::RandomSpread { + foliage_height: decoder.int_provider( + required(&object, "foliage_height")?, + 1, + 512, + )?, + attempts: int_range( + required(&object, "leaf_placement_attempts")?, + "leaf_placement_attempts", + 0, + 256, + )?, + }, + "minecraft:cherry_foliage_placer" => Kind::Cherry { + height: decoder.int_provider(required(&object, "height")?, 4, 16)?, + wide_bottom_hole: chance("wide_bottom_layer_hole_chance")?, + corner_hole: chance("corner_hole_chance")?, + hanging: chance("hanging_leaves_chance")?, + hanging_extension: chance("hanging_leaves_extension_chance")?, + }, + "minecraft:poplar_foliage_placer" => Kind::Poplar { + height: decoder.int_provider(required(&object, "height")?, 5, 16)?, + side_hole: chance("side_hole_chance")?, + }, + _ => return Err(DecodeError::Field("foliage placer type")), + }; + Ok(Self { + radius, + offset, + kind, + }) + } + pub(super) fn foliage_height( + &self, + random: &mut impl RandomSource, + tree_height: i32, + ) -> TreeResult { + Ok(match &self.kind { + Kind::Blob(h) | Kind::Fancy(h) | Kind::Bush(h) | Kind::MegaJungle(h) => *h, + Kind::Acacia => 0, + Kind::DarkOak => 4, + Kind::Spruce(trunk) => 4.max(tree_height - trunk.sample(random)?), + Kind::Pine(h) | Kind::MegaPine(h) => h.sample(random)?, + Kind::RandomSpread { foliage_height, .. } => foliage_height.sample(random)?, + Kind::Cherry { height, .. } | Kind::Poplar { height, .. } => height.sample(random)?, + }) + } + pub(super) fn foliage_radius( + &self, + random: &mut impl RandomSource, + trunk_height: i32, + ) -> TreeResult { + let radius = self.radius.sample(random)?; + if matches!(self.kind, Kind::Pine(_)) { + return Ok(radius + random.next_int_bound(trunk_height.wrapping_add(1).max(1))?); + } + Ok(radius) + } + + /// shouldSkipLocation with already-unsigned offsets. + fn skip( + &self, + random: &mut impl RandomSource, + dx: i32, + y: i32, + dz: i32, + r: i32, + double: bool, + ) -> Result { + Ok(match &self.kind { + Kind::Blob(_) => dx == r && dz == r && (random.next_int_bound(2)? == 0 || y == 0), + Kind::Bush(_) => dx == r && dz == r && random.next_int_bound(2)? == 0, + Kind::Fancy(_) => { + let a = dx as f32 + 0.5; + let b = dz as f32 + 0.5; + a * a + b * b > r.wrapping_mul(r) as f32 + } + Kind::Acacia => { + if y == 0 { + (dx > 1 || dz > 1) && dx != 0 && dz != 0 + } else { + dx == r && dz == r && r > 0 + } + } + Kind::Spruce(_) | Kind::Pine(_) => dx == r && dz == r && r > 0, + Kind::MegaPine(_) | Kind::MegaJungle(_) => { + dx.wrapping_add(dz) >= 7 + || dx.wrapping_mul(dx).wrapping_add(dz.wrapping_mul(dz)) > r.wrapping_mul(r) + } + Kind::DarkOak => { + if y == -1 && !double { + dx == r && dz == r + } else if y == 1 { + dx.wrapping_add(dz) > r.wrapping_mul(2).wrapping_sub(2) + } else { + false + } + } + Kind::RandomSpread { .. } => false, + Kind::Cherry { + wide_bottom_hole, + corner_hole, + .. + } => { + if y == -1 && (dx == r || dz == r) && random.next_float() < *wide_bottom_hole { + return Ok(true); + } + let corner = dx == r && dz == r; + if r > 2 { + corner + || (dx.wrapping_add(dz) > r.wrapping_mul(2).wrapping_sub(2) + && random.next_float() < *corner_hole) + } else { + corner && random.next_float() < *corner_hole + } + } + Kind::Poplar { .. } => unreachable!("poplar uses its own row placement"), + }) + } + fn skip_signed( + &self, + random: &mut impl RandomSource, + dx: i32, + y: i32, + dz: i32, + r: i32, + double: bool, + ) -> Result { + if matches!(self.kind, Kind::DarkOak) { + let defer = y != 0 + || !double + || (dx != r.wrapping_neg() && dx < r) + || (dz != r.wrapping_neg() && dz < r); + if !defer { + return Ok(true); + } + } + let (mx, mz) = if double { + ( + abs(dx).min(abs(dx.wrapping_sub(1))), + abs(dz).min(abs(dz.wrapping_sub(1))), + ) + } else { + (abs(dx), abs(dz)) + }; + self.skip(random, mx, y, mz, r, double) + } + #[allow(clippy::too_many_arguments)] + fn leaves_row( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + origin: [i32; 3], + r: i32, + y: i32, + double: bool, + ) -> TreeResult<(), W::Error> { + let offset = i32::from(double); + let mut dx = r.wrapping_neg(); + while dx <= r.wrapping_add(offset) { + let mut dz = r.wrapping_neg(); + while dz <= r.wrapping_add(offset) { + if !self.skip_signed(run.random, dx, y, dz, r, double)? { + tree.try_place_leaf(run, tb::offset(origin, dx, y, dz))?; + } + dz += 1; + } + dx += 1; + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn leaves_row_with_hanging( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + origin: [i32; 3], + r: i32, + y: i32, + double: bool, + chance: f32, + extension: f32, + ) -> TreeResult<(), W::Error> { + self.leaves_row(run, tree, origin, r, y, double)?; + let offset = i32::from(double); + let log = tb::offset(origin, 0, -1, 0); + for along in tb::HORIZONTAL { + let to_edge = tb::clockwise(along); + let positive = matches!(to_edge, Direction::East | Direction::South); + let to_edge_offset = if positive { r + offset } else { r }; + let mut pos = tb::relative( + tb::relative(tb::offset(origin, 0, y - 1, 0), to_edge, to_edge_offset), + along, + r.wrapping_neg(), + ); + let mut along_offset = r.wrapping_neg(); + while along_offset < r + offset { + let above = run.foliage_contains(tb::offset(pos, 0, 1, 0)); + if above && Self::try_extension(run, tree, chance, log, pos)? { + Self::try_extension(run, tree, extension, log, tb::offset(pos, 0, -1, 0))?; + } + along_offset += 1; + pos = tb::relative(pos, along, 1); + } + } + Ok(()) + } + fn try_extension( + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + chance: f32, + log: [i32; 3], + pos: [i32; 3], + ) -> TreeResult { + if tb::dist_manhattan(pos, log) >= 7 { + return Ok(false); + } + if run.random.next_float() > chance { + return Ok(false); + } + tree.try_place_leaf(run, pos) + } + + pub(super) fn create_foliage( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + _tree_height: i32, + attachment: FoliageAttachment, + foliage_height: i32, + leaf_radius: i32, + ) -> TreeResult<(), W::Error> { + let offset = self.offset.sample(run.random)?; + let double = attachment.double_trunk(); + let pos = attachment.pos; + let with_offset = foliage_height + attachment.height_offset; + match &self.kind { + Kind::Blob(_) => { + let mut yo = offset; + while yo >= offset - with_offset { + let r = 0.max(leaf_radius + attachment.radius_offset - 1 - yo / 2); + self.leaves_row(run, tree, pos, r, yo, double)?; + yo -= 1; + } + } + Kind::Fancy(_) => { + let mut yo = offset; + while yo >= offset - foliage_height { + let r = leaf_radius + + i32::from(yo != offset && yo != offset - foliage_height); + self.leaves_row(run, tree, pos, r, yo, double)?; + yo -= 1; + } + } + Kind::Bush(_) => { + let mut yo = offset; + while yo >= offset - with_offset { + let r = leaf_radius + attachment.radius_offset - 1 - yo; + self.leaves_row(run, tree, pos, r, yo, double)?; + yo -= 1; + } + } + Kind::Acacia => { + let p = tb::offset(pos, 0, offset, 0); + self.leaves_row( + run, + tree, + p, + leaf_radius + attachment.radius_offset, + -1 - with_offset, + double, + )?; + self.leaves_row(run, tree, p, leaf_radius - 1, -with_offset, double)?; + self.leaves_row( + run, + tree, + p, + leaf_radius + attachment.radius_offset - 1, + 0, + double, + )?; + } + Kind::Spruce(_) => { + let mut r = run.random.next_int_bound(2)?; + let mut max_r = 1; + let mut min_r = 0; + let mut yo = offset; + while yo >= -with_offset { + self.leaves_row(run, tree, pos, r, yo, double)?; + if r >= max_r { + r = min_r; + min_r = 1; + max_r = (max_r + 1).min(leaf_radius + attachment.radius_offset); + } else { + r += 1; + } + yo -= 1; + } + } + Kind::Pine(_) => { + let mut r = 0; + let mut yo = offset; + while yo >= offset - with_offset { + self.leaves_row(run, tree, pos, r, yo, double)?; + if r >= 1 && yo == offset - with_offset + 1 { + r -= 1; + } else if r < leaf_radius + attachment.radius_offset { + r += 1; + } + yo -= 1; + } + } + Kind::MegaPine(_) => { + let mut previous = 0; + let mut yy = pos[1] - with_offset + offset; + while yy <= pos[1] + offset { + let yo = pos[1] - yy; + let smooth = leaf_radius + .wrapping_add(attachment.radius_offset) + .wrapping_add((yo as f32 / with_offset as f32 * 3.5f32).floor() as i32); + let jagged = if yo > 0 && smooth == previous && (yy & 1) == 0 { + smooth.wrapping_add(1) + } else { + smooth + }; + self.leaves_row(run, tree, [pos[0], yy, pos[2]], jagged, 0, double)?; + previous = smooth; + yy += 1; + } + } + Kind::MegaJungle(_) => { + let leaf_height = (if double { + foliage_height + } else { + 1 + run.random.next_int_bound(2)? + }) + attachment.height_offset; + let mut yo = offset; + while yo >= offset - leaf_height { + let r = leaf_radius + attachment.radius_offset + 1 - yo; + self.leaves_row(run, tree, pos, r, yo, double)?; + yo -= 1; + } + } + Kind::DarkOak => { + let p = tb::offset(pos, 0, offset, 0); + if double { + self.leaves_row(run, tree, p, leaf_radius + 2, -1, double)?; + self.leaves_row(run, tree, p, leaf_radius + 3, 0, double)?; + self.leaves_row(run, tree, p, leaf_radius + 2, 1, double)?; + if run.random.next_boolean() { + self.leaves_row(run, tree, p, leaf_radius, 2, double)?; + } + } else { + self.leaves_row(run, tree, p, leaf_radius + 2, -1, double)?; + self.leaves_row(run, tree, p, leaf_radius + 1, 0, double)?; + } + } + Kind::RandomSpread { attempts, .. } => { + for _ in 0..*attempts { + let dx = run.random.next_int_bound(leaf_radius)? + - run.random.next_int_bound(leaf_radius)?; + let dy = run.random.next_int_bound(foliage_height)? + - run.random.next_int_bound(foliage_height)?; + let dz = run.random.next_int_bound(leaf_radius)? + - run.random.next_int_bound(leaf_radius)?; + tree.try_place_leaf(run, tb::offset(pos, dx, dy, dz))?; + } + } + Kind::Cherry { + hanging, + hanging_extension, + .. + } => { + let p = tb::offset(pos, 0, offset, 0); + let r = leaf_radius + attachment.radius_offset - 1; + self.leaves_row(run, tree, p, r - 2, with_offset - 3, double)?; + self.leaves_row(run, tree, p, r - 1, with_offset - 4, double)?; + let mut y = with_offset - 5; + while y >= 0 { + self.leaves_row(run, tree, p, r, y, double)?; + y -= 1; + } + self.leaves_row_with_hanging( + run, + tree, + p, + r, + -1, + double, + *hanging, + *hanging_extension, + )?; + self.leaves_row_with_hanging( + run, + tree, + p, + r - 1, + -2, + double, + *hanging, + *hanging_extension, + )?; + } + Kind::Poplar { side_hole, .. } => { + let poplar = Poplar { + side_hole: *side_hole, + flip: run.random.next_boolean(), + height: with_offset, + double, + }; + let p = tb::offset(pos, 0, offset, 0); + let r = leaf_radius + attachment.radius_offset - 1; + poplar.row(run, tree, p, r - 2, with_offset - 1)?; + poplar.row(run, tree, p, r - 1, with_offset - 2)?; + poplar.row(run, tree, p, r - 1, with_offset - 3)?; + let mut y = with_offset - 4; + while y >= 1 { + poplar.row(run, tree, p, r, y)?; + y -= 1; + } + poplar.replace_with_log(run, tree, p, r, with_offset - 4)?; + poplar.row(run, tree, p, r - 1, 0)?; + poplar.row(run, tree, p, (r - 2).clamp(1, 2), -1)?; + } + } + Ok(()) + } +} + +struct Poplar { + side_hole: f32, + flip: bool, + height: i32, + double: bool, +} +impl Poplar { + fn partial_row(&self, y: i32) -> bool { + self.height - 1 == y || self.height - 2 == y + } + fn corner_cut(&self, dx: i32, dz: i32, r: i32, partial: bool) -> i32 { + let small = if self.flip { + (dx > 0 && dz > 0) || (dz < 0 && dx < 0) + } else { + (dx > 0 && dz < 0) || (dz > 0 && dx < 0) + }; + if small { + r - 1 + } else if partial { + r + 1 + } else { + r + } + } + fn within(r: i32, adx: i32, adz: i32, cut: i32, extra: i32) -> bool { + adx.wrapping_add(adz) <= r.wrapping_mul(2).wrapping_sub(cut.wrapping_add(extra)) + } + fn skip( + &self, + random: &mut impl RandomSource, + dx: i32, + y: i32, + dz: i32, + r: i32, + ) -> Result { + let partial = self.partial_row(y); + let cut = self.corner_cut(dx, dz, r, partial); + let (adx, adz) = (abs(dx), abs(dz)); + if partial && (adx == r || adz == r) { + return Ok(true); + } + let extra = i32::from(random.next_float() <= self.side_hole); + Ok(!Self::within(r, adx, adz, cut, extra)) + } + fn row( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + origin: [i32; 3], + r: i32, + y: i32, + ) -> TreeResult<(), W::Error> { + let offset = i32::from(self.double); + let mut dx = r.wrapping_neg(); + while dx <= r + offset { + let mut dz = r.wrapping_neg(); + while dz <= r + offset { + if !self.skip(run.random, dx, y, dz, r)? { + tree.try_place_leaf(run, tb::offset(origin, dx, y, dz))?; + } + dz += 1; + } + dx += 1; + } + Ok(()) + } + fn replace_with_log( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + origin: [i32; 3], + r: i32, + y: i32, + ) -> TreeResult<(), W::Error> { + let offset = i32::from(self.double); + let mut dx = r.wrapping_neg(); + while dx <= r + offset { + let mut dz = r.wrapping_neg(); + while dz <= r + offset { + let (adx, adz) = (abs(dx), abs(dz)); + let cut = self.corner_cut(dx, dz, r, self.partial_row(y)); + if Self::within(r, adx, adz, cut, 2) + && ((adz == 0 && r - adx >= 4) || (adx == 0 && r - adz >= 4)) + { + let pos = tb::offset(origin, dx, y, dz); + let axis = if adz == 0 { Axis::X } else { Axis::Z }; + // The comparison state is sampled from the foliage provider. + let here = read(run.world, pos)?; + let foliage = sample_state(&tree.foliage_provider, run.world, run.random, pos)?; + if here == foliage { + let log = sample_state(&tree.trunk_provider, run.world, run.random, pos)?; + run.set(Layer::Foliage, pos, tree.blocks.try_axis(log, axis))?; + } + } + dz += 1; + } + dx += 1; + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/tree/trunk.rs b/crates/horizon-world/src/worldgen/tree/trunk.rs new file mode 100644 index 000000000..8efcc1e40 --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree/trunk.rs @@ -0,0 +1,800 @@ +//! Trunk placers (TrunkPlacer subclasses), in native random-draw order. +use super::{ + FoliageAttachment, Layer, Run, TreeDecoder, TreeFeature, TreeResult, kind, read, sample_optional, + sample_state, unit_float, +}; +use crate::registry::BlockStateId; +use crate::worldgen::{ + DecodeError, Object, int_range, optional, + feature::FeatureWorld, + placement::PlacementContext, + required, + tree_blocks::{self as tb, Axis, TreeBlocks}, + value_provider::IntProvider, +}; +use horizon_core::{geometry::Direction, random::RandomSource}; +use serde_json::value::RawValue; +use std::{collections::BTreeSet, sync::Arc}; + +#[derive(Clone, Debug)] +enum Kind { + Straight, + Forking, + Giant, + MegaJungle, + DarkOak, + Fancy, + Bending { + min_height_for_leaves: i32, + bend_length: IntProvider, + }, + UpwardsBranching { + extra_branch_steps: IntProvider, + branch_probability: f32, + extra_branch_length: IntProvider, + can_grow_through: Arc>, + }, + Cherry { + branch_count: IntProvider, + branch_horizontal_length: IntProvider, + branch_start: [i32; 2], + branch_end_offset: IntProvider, + }, + Poplar { + trunk_height_above_branches: IntProvider, + branch_amount: IntProvider, + }, +} +#[derive(Clone, Debug)] +pub(super) struct TrunkPlacer { + base_height: i32, + height_rand_a: i32, + height_rand_b: i32, + kind: Kind, +} + +fn random_horizontal(random: &mut impl RandomSource) -> Result { + Ok(tb::HORIZONTAL[random.next_int_bound(4)? as usize]) +} + +impl TrunkPlacer { + pub(super) fn decode( + raw: &RawValue, + decoder: &mut TreeDecoder<'_, '_>, + ) -> Result { + let object: Object = serde_json::from_str(raw.get())?; + let base_height = int_range(required(&object, "base_height")?, "base_height", 0, 32)?; + let height_rand_a = int_range(required(&object, "height_rand_a")?, "height_rand_a", 0, 24)?; + let height_rand_b = int_range(required(&object, "height_rand_b")?, "height_rand_b", 0, 24)?; + let kind = match kind(&object)?.as_str() { + "minecraft:straight_trunk_placer" => Kind::Straight, + "minecraft:forking_trunk_placer" => Kind::Forking, + "minecraft:giant_trunk_placer" => Kind::Giant, + "minecraft:mega_jungle_trunk_placer" => Kind::MegaJungle, + "minecraft:dark_oak_trunk_placer" => Kind::DarkOak, + "minecraft:fancy_trunk_placer" => Kind::Fancy, + "minecraft:bending_trunk_placer" => Kind::Bending { + min_height_for_leaves: optional(&object, "min_height_for_leaves") + .map(|raw| int_range(raw, "min_height_for_leaves", 1, i32::MAX)) + .transpose()? + .unwrap_or(1), + bend_length: decoder.int_provider(required(&object, "bend_length")?, 1, 64)?, + }, + "minecraft:upwards_branching_trunk_placer" => Kind::UpwardsBranching { + extra_branch_steps: decoder.int_provider( + required(&object, "extra_branch_steps")?, + 1, + i32::MAX, + )?, + branch_probability: unit_float( + required(&object, "place_branch_per_log_probability")?, + "place_branch_per_log_probability", + )?, + extra_branch_length: decoder.int_provider( + required(&object, "extra_branch_length")?, + 0, + i32::MAX, + )?, + can_grow_through: decoder.block_set(required(&object, "can_grow_through")?)?, + }, + "minecraft:cherry_trunk_placer" => { + let start: Object = + serde_json::from_str(required(&object, "branch_start_offset_from_top")?.get())?; + if let Some(kind) = optional(&start, "type") { + if serde_json::from_str::(kind.get())? != "minecraft:uniform" { + return Err(DecodeError::Field("cherry branch start type")); + } + } + let min = int_range(required(&start, "min_inclusive")?, "branch start", -16, 0)?; + let max = int_range(required(&start, "max_inclusive")?, "branch start", -16, 0)?; + if max - min < 1 { + return Err(DecodeError::Field("cherry branch start variation")); + } + Kind::Cherry { + branch_count: decoder.int_provider(required(&object, "branch_count")?, 1, 3)?, + branch_horizontal_length: decoder.int_provider( + required(&object, "branch_horizontal_length")?, + 2, + 16, + )?, + branch_start: [min, max], + branch_end_offset: decoder.int_provider( + required(&object, "branch_end_offset_from_top")?, + -16, + 16, + )?, + } + } + "minecraft:poplar_trunk_placer" => Kind::Poplar { + trunk_height_above_branches: decoder.int_provider( + required(&object, "trunk_height_above_branches")?, + 0, + 8, + )?, + branch_amount: decoder.int_provider(required(&object, "branch_amount")?, 1, 4)?, + }, + _ => return Err(DecodeError::Field("trunk placer type")), + }; + Ok(Self { + base_height, + height_rand_a, + height_rand_b, + kind, + }) + } + pub(super) fn tree_height(&self, random: &mut impl RandomSource) -> TreeResult { + let a = random.next_int_bound(self.height_rand_a + 1)?; + let b = random.next_int_bound(self.height_rand_b + 1)?; + Ok(self.base_height + a + b) + } + /// Virtual TrunkPlacer.validTreePos. + fn valid_tree_pos(&self, blocks: &TreeBlocks, state: BlockStateId) -> bool { + blocks.valid_tree_pos(state) + || matches!(&self.kind, Kind::UpwardsBranching { can_grow_through, .. } if can_grow_through.contains(&state)) + } + pub(super) fn is_free(&self, blocks: &TreeBlocks, state: BlockStateId) -> bool { + self.valid_tree_pos(blocks, state) || blocks.has(state, tb::LOGS) + } + fn place_log( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + axis: Option, + ) -> TreeResult { + let here = read(run.world, position)?; + if !self.valid_tree_pos(&tree.blocks, here) { + return Ok(false); + } + let mut state = sample_state(&tree.trunk_provider, run.world, run.random, position)?; + if let Some(axis) = axis { + state = tree.blocks.try_axis(state, axis); + } + run.set(Layer::Trunk, position, state)?; + Ok(true) + } + fn place_log_if_free( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + ) -> TreeResult<(), W::Error> { + let here = read(run.world, position)?; + if self.is_free(&tree.blocks, here) { + self.place_log(run, tree, position, None)?; + } + Ok(()) + } + fn place_below_trunk( + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + position: [i32; 3], + ) -> TreeResult<(), W::Error> { + if let Some(state) = + sample_optional(&tree.below_trunk_provider, run.world, run.random, position)? + { + run.set(Layer::Trunk, position, state)?; + } + Ok(()) + } + pub(super) fn place_trunk( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + let below = tb::offset(origin, 0, -1, 0); + match &self.kind { + Kind::Straight => { + Self::place_below_trunk(run, tree, below)?; + for y in 0..tree_height { + self.place_log(run, tree, tb::offset(origin, 0, y, 0), None)?; + } + Ok(vec![FoliageAttachment::new( + tb::offset(origin, 0, tree_height, 0), + 0, + false, + )]) + } + Kind::Forking => self.forking(run, tree, tree_height, origin), + Kind::Giant => self.giant(run, tree, tree_height, origin), + Kind::MegaJungle => { + let mut attachments = self.giant(run, tree, tree_height, origin)?; + let mut branch_height = tree_height - 2 - run.random.next_int_bound(4)?; + while branch_height > tree_height / 2 { + let angle = run.random.next_float() * (std::f64::consts::PI * 2.0) as f32; + let (mut bx, mut bz) = (0, 0); + for b in 0..5 { + bx = (1.5f32 + + horizon_core::geometry::trig::cos(f64::from(angle)) * b as f32) + as i32; + bz = (1.5f32 + + horizon_core::geometry::trig::sin(f64::from(angle)) * b as f32) + as i32; + let p = tb::offset(origin, bx, branch_height - 3 + b / 2, bz); + self.place_log(run, tree, p, None)?; + } + attachments.push(FoliageAttachment::new( + tb::offset(origin, bx, branch_height, bz), + -2, + false, + )); + branch_height -= 2 + run.random.next_int_bound(4)?; + } + Ok(attachments) + } + Kind::DarkOak => self.dark_oak(run, tree, tree_height, origin), + Kind::Fancy => self.fancy(run, tree, tree_height, origin), + Kind::Bending { + min_height_for_leaves, + bend_length, + } => { + let direction = random_horizontal(run.random)?; + let log_height = tree_height - 1; + let mut pos = origin; + Self::place_below_trunk(run, tree, below)?; + let mut points = Vec::new(); + for i in 0..=log_height { + if i + 1 >= log_height + run.random.next_int_bound(2)? { + pos = tb::relative(pos, direction, 1); + } + if tree.blocks.valid_tree_pos(read(run.world, pos)?) { + self.place_log(run, tree, pos, None)?; + } + if i >= *min_height_for_leaves { + points.push(FoliageAttachment::new(pos, 0, false)); + } + pos = tb::offset(pos, 0, 1, 0); + } + let length = bend_length.sample(run.random)?; + for _ in 0..=length { + if tree.blocks.valid_tree_pos(read(run.world, pos)?) { + self.place_log(run, tree, pos, None)?; + } + points.push(FoliageAttachment::new(pos, 0, false)); + pos = tb::relative(pos, direction, 1); + } + Ok(points) + } + Kind::UpwardsBranching { + extra_branch_steps, + branch_probability, + extra_branch_length, + .. + } => { + let mut attachments = Vec::new(); + for height in 0..tree_height { + let current = origin[1].wrapping_add(height); + let log = [origin[0], current, origin[2]]; + if self.place_log(run, tree, log, None)? + && height < tree_height - 1 + && run.random.next_float() < *branch_probability + { + let direction = random_horizontal(run.random)?; + let length = extra_branch_length.sample(run.random)?; + let branch_pos = + 0.max(length - extra_branch_length.sample(run.random)? - 1); + let steps = extra_branch_steps.sample(run.random)?; + self.upwards_branch( + run, + tree, + tree_height, + &mut attachments, + log, + current, + direction, + branch_pos, + steps, + )?; + } + if height == tree_height - 1 { + attachments.push(FoliageAttachment::new( + [origin[0], current.wrapping_add(1), origin[2]], + 0, + false, + )); + } + } + Ok(attachments) + } + Kind::Cherry { .. } => self.cherry(run, tree, tree_height, origin), + Kind::Poplar { + trunk_height_above_branches, + branch_amount, + } => { + Self::place_below_trunk(run, tree, below)?; + let up_to_branches = + tree_height - trunk_height_above_branches.sample(run.random)?; + for y in 0..tree_height { + let log = tb::offset(origin, 0, y, 0); + self.place_log(run, tree, log, None)?; + let mut all = Direction::ALL; + tb::shuffle(&mut all, run.random)?; + let directions: Vec = all + .into_iter() + .filter(|d| !matches!(d, Direction::Up | Direction::Down)) + .collect(); + if up_to_branches - 1 == y { + let branches = branch_amount.sample(run.random)?; + for direction in directions.iter().take(branches.max(0) as usize) { + self.place_log( + run, + tree, + tb::relative(log, *direction, 1), + Some(Axis::of(*direction)), + )?; + } + } + } + Ok(vec![FoliageAttachment::new( + tb::offset(origin, 0, up_to_branches, 0), + 0, + false, + )]) + } + } + } + + fn forking( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + Self::place_below_trunk(run, tree, tb::offset(origin, 0, -1, 0))?; + let mut attachments = Vec::new(); + let lean = random_horizontal(run.random)?; + let lean_height = tree_height - run.random.next_int_bound(4)? - 1; + let mut lean_steps = 3 - run.random.next_int_bound(3)?; + let (mut tx, mut tz) = (origin[0], origin[2]); + let mut ey = None; + for yo in 0..tree_height { + let yy = origin[1].wrapping_add(yo); + if yo >= lean_height && lean_steps > 0 { + let n = lean.normal(); + tx = tx.wrapping_add(n[0]); + tz = tz.wrapping_add(n[2]); + lean_steps -= 1; + } + if self.place_log(run, tree, [tx, yy, tz], None)? { + ey = Some(yy.wrapping_add(1)); + } + } + if let Some(ey) = ey { + attachments.push(FoliageAttachment::new([tx, ey, tz], 1, false)); + } + tx = origin[0]; + tz = origin[2]; + let branch = random_horizontal(run.random)?; + if branch != lean { + let branch_pos = lean_height - run.random.next_int_bound(2)? - 1; + let mut steps = 1 + run.random.next_int_bound(3)?; + let mut ey = None; + let mut yo = branch_pos; + while yo < tree_height && steps > 0 { + if yo >= 1 { + let yy = origin[1].wrapping_add(yo); + let n = branch.normal(); + tx = tx.wrapping_add(n[0]); + tz = tz.wrapping_add(n[2]); + if self.place_log(run, tree, [tx, yy, tz], None)? { + ey = Some(yy.wrapping_add(1)); + } + } + yo += 1; + steps -= 1; + } + if let Some(ey) = ey { + attachments.push(FoliageAttachment::new([tx, ey, tz], 0, false)); + } + } + Ok(attachments) + } + + fn giant( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + let below = tb::offset(origin, 0, -1, 0); + Self::place_below_trunk(run, tree, below)?; + Self::place_below_trunk(run, tree, tb::offset(below, 1, 0, 0))?; + Self::place_below_trunk(run, tree, tb::offset(below, 0, 0, 1))?; + Self::place_below_trunk(run, tree, tb::offset(below, 1, 0, 1))?; + for hh in 0..tree_height { + self.place_log_if_free(run, tree, tb::offset(origin, 0, hh, 0))?; + if hh < tree_height - 1 { + self.place_log_if_free(run, tree, tb::offset(origin, 1, hh, 0))?; + self.place_log_if_free(run, tree, tb::offset(origin, 1, hh, 1))?; + self.place_log_if_free(run, tree, tb::offset(origin, 0, hh, 1))?; + } + } + Ok(vec![FoliageAttachment::new( + tb::offset(origin, 0, tree_height, 0), + 0, + true, + )]) + } + + fn dark_oak( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + let mut attachments = Vec::new(); + let below = tb::offset(origin, 0, -1, 0); + Self::place_below_trunk(run, tree, below)?; + Self::place_below_trunk(run, tree, tb::offset(below, 1, 0, 0))?; + Self::place_below_trunk(run, tree, tb::offset(below, 0, 0, 1))?; + Self::place_below_trunk(run, tree, tb::offset(below, 1, 0, 1))?; + let lean = random_horizontal(run.random)?; + let lean_height = tree_height - run.random.next_int_bound(4)?; + let mut lean_steps = 2 - run.random.next_int_bound(3)?; + let [x, y, z] = origin; + let (mut tx, mut tz) = (x, z); + let ey = y.wrapping_add(tree_height).wrapping_sub(1); + for dy in 0..tree_height { + if dy >= lean_height && lean_steps > 0 { + let n = lean.normal(); + tx = tx.wrapping_add(n[0]); + tz = tz.wrapping_add(n[2]); + lean_steps -= 1; + } + let p = [tx, y.wrapping_add(dy), tz]; + let here = read(run.world, p)?; + if tree.blocks.has(here, tb::AIR | tb::LEAVES) { + self.place_log(run, tree, p, None)?; + self.place_log(run, tree, tb::offset(p, 1, 0, 0), None)?; + self.place_log(run, tree, tb::offset(p, 0, 0, 1), None)?; + self.place_log(run, tree, tb::offset(p, 1, 0, 1), None)?; + } + } + attachments.push(FoliageAttachment::new([tx, ey, tz], 0, true)); + for ox in -1..=2 { + for oz in -1..=2 { + if (!(0..=1).contains(&ox) || !(0..=1).contains(&oz)) + && run.random.next_int_bound(3)? <= 0 + { + let length = run.random.next_int_bound(3)? + 2; + for branch_y in 0..length { + self.place_log( + run, + tree, + [ + x.wrapping_add(ox), + ey.wrapping_sub(branch_y).wrapping_sub(1), + z.wrapping_add(oz), + ], + None, + )?; + } + attachments.push(FoliageAttachment::new( + [x.wrapping_add(ox), ey, z.wrapping_add(oz)], + 0, + false, + )); + } + } + } + Ok(attachments) + } + + #[allow(clippy::too_many_arguments)] + fn upwards_branch( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + attachments: &mut Vec, + log: [i32; 3], + current_height: i32, + direction: Direction, + branch_pos: i32, + mut steps: i32, + ) -> TreeResult<(), W::Error> { + let mut height_along = current_height.wrapping_add(branch_pos); + let (mut lx, mut lz) = (log[0], log[2]); + let mut index = branch_pos; + let n = direction.normal(); + while index < tree_height && steps > 0 { + if index >= 1 { + let placement = current_height.wrapping_add(index); + lx = lx.wrapping_add(n[0]); + lz = lz.wrapping_add(n[2]); + height_along = placement; + let log = [lx, placement, lz]; + if self.place_log(run, tree, log, None)? { + height_along = height_along.wrapping_add(1); + } + attachments.push(FoliageAttachment::new(log, 0, false)); + } + index += 1; + steps -= 1; + } + if height_along.wrapping_sub(current_height) > 1 { + let foliage = [lx, height_along, lz]; + attachments.push(FoliageAttachment::new(foliage, 0, false)); + attachments.push(FoliageAttachment::new( + tb::offset(foliage, 0, -2, 0), + 0, + false, + )); + } + Ok(()) + } + + fn cherry( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + let Kind::Cherry { + branch_count, + branch_horizontal_length, + branch_start: [start_min, start_max], + branch_end_offset, + } = &self.kind + else { + unreachable!("cherry trunk kind"); + }; + Self::place_below_trunk(run, tree, tb::offset(origin, 0, -1, 0))?; + let first = 0.max( + tree_height - 1 + run.random.next_int_between_inclusive(*start_min, *start_max)?, + ); + let mut second = 0.max( + tree_height - 1 + run.random.next_int_between_inclusive(*start_min, start_max - 1)?, + ); + if second >= first { + second += 1; + } + let count = branch_count.sample(run.random)?; + let middle = count == 3; + let both = count >= 2; + let trunk_height = if middle { + tree_height + } else if both { + first.max(second) + 1 + } else { + first + 1 + }; + for y in 0..trunk_height { + self.place_log(run, tree, tb::offset(origin, 0, y, 0), None)?; + } + let mut attachments = Vec::new(); + if middle { + attachments.push(FoliageAttachment::new( + tb::offset(origin, 0, trunk_height, 0), + 0, + false, + )); + } + let direction = random_horizontal(run.random)?; + let sideways = Axis::of(direction); + let generate = |this: &Self, + run: &mut Run<'_, W, R>, + branch_direction: Direction, + offset: i32, + middle_continues: bool| + -> TreeResult { + let mut log = tb::offset(origin, 0, offset, 0); + let end_offset = tree_height - 1 + branch_end_offset.sample(run.random)?; + let extend = middle_continues || end_offset < offset; + let distance = branch_horizontal_length.sample(run.random)? + i32::from(extend); + let end = tb::offset(tb::relative(origin, branch_direction, distance), 0, end_offset, 0); + let steps = if extend { 2 } else { 1 }; + for _ in 0..steps { + log = tb::relative(log, branch_direction, 1); + this.place_log(run, tree, log, Some(sideways))?; + } + let vertical = if end[1] > log[1] { + Direction::Up + } else { + Direction::Down + }; + loop { + let distance = tb::dist_manhattan(log, end); + if distance == 0 { + return Ok(FoliageAttachment::new(tb::offset(end, 0, 1, 0), 0, false)); + } + let chance = end[1].wrapping_sub(log[1]).wrapping_abs() as f32 / distance as f32; + let grow_vertically = run.random.next_float() < chance; + log = tb::relative( + log, + if grow_vertically { + vertical + } else { + branch_direction + }, + 1, + ); + this.place_log( + run, + tree, + log, + if grow_vertically { + None + } else { + Some(sideways) + }, + )?; + } + }; + attachments.push(generate( + self, + run, + direction, + first, + first < trunk_height - 1, + )?); + if both { + attachments.push(generate( + self, + run, + direction.opposite(), + second, + second < trunk_height - 1, + )?); + } + Ok(attachments) + } + + fn fancy( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + tree_height: i32, + origin: [i32; 3], + ) -> TreeResult, W::Error> { + let height = tree_height + 2; + let trunk_height = (f64::from(height) * 0.618).floor() as i32; + Self::place_below_trunk(run, tree, tb::offset(origin, 0, -1, 0))?; + let clusters_per_y = + 1.min((1.382 + (1.0 * f64::from(height) / 13.0).powf(2.0)).floor() as i32); + let trunk_top = origin[1].wrapping_add(trunk_height); + let mut relative_y = height - 5; + // (attachment position, branch base y) + let mut coords = vec![(tb::offset(origin, 0, relative_y, 0), trunk_top)]; + while relative_y >= 0 { + let shape = tree_shape(height, relative_y); + // tree_shape never returns NaN. + if shape >= 0.0 { + for _ in 0..clusters_per_y { + let radius = + 1.0 * f64::from(shape) * (f64::from(run.random.next_float()) + 0.328); + let angle = f64::from(run.random.next_float() * 2.0f32) * std::f64::consts::PI; + let x = radius * angle.sin() + 0.5; + let z = radius * angle.cos() + 0.5; + let check_start = tb::offset( + origin, + x.floor() as i32, + relative_y - 1, + z.floor() as i32, + ); + let check_end = tb::offset(check_start, 0, 5, 0); + if self.make_limb(run, tree, check_start, check_end, false)? { + let dx = origin[0].wrapping_sub(check_start[0]); + let dz = origin[2].wrapping_sub(check_start[2]); + let branch_height = f64::from(check_start[1]) + - f64::from(dx.wrapping_mul(dx).wrapping_add(dz.wrapping_mul(dz))) + .sqrt() + * 0.381; + let branch_top = if branch_height > f64::from(trunk_top) { + trunk_top + } else { + branch_height as i32 + }; + let base = [origin[0], branch_top, origin[2]]; + if self.make_limb(run, tree, base, check_start, false)? { + coords.push((check_start, base[1])); + } + } + } + } + relative_y -= 1; + } + self.make_limb( + run, + tree, + origin, + tb::offset(origin, 0, trunk_height, 0), + true, + )?; + for (end, branch_base) in &coords { + let base = [origin[0], *branch_base, origin[2]]; + if base != *end && trim_branches(height, branch_base.wrapping_sub(origin[1])) { + self.make_limb(run, tree, base, *end, true)?; + } + } + Ok(coords + .into_iter() + .filter(|(_, base)| trim_branches(height, base.wrapping_sub(origin[1]))) + .map(|(p, _)| FoliageAttachment::new(p, 0, false)) + .collect()) + } + + fn make_limb( + &self, + run: &mut Run<'_, W, R>, + tree: &TreeFeature, + start: [i32; 3], + end: [i32; 3], + place: bool, + ) -> TreeResult { + if !place && start == end { + return Ok(true); + } + let delta: [i32; 3] = std::array::from_fn(|i| end[i].wrapping_sub(start[i])); + let steps = delta[0] + .wrapping_abs() + .max(delta[1].wrapping_abs().max(delta[2].wrapping_abs())); + let step: [f32; 3] = delta.map(|d| d as f32 / steps as f32); + for i in 0..=steps { + let p: [i32; 3] = std::array::from_fn(|axis| { + start[axis].wrapping_add((0.5f32 + i as f32 * step[axis]).floor() as i32) + }); + if place { + let axis = log_axis(start, p); + self.place_log(run, tree, p, Some(axis))?; + } else if !self.is_free(&tree.blocks, read(run.world, p)?) { + return Ok(false); + } + } + Ok(true) + } +} + +fn log_axis(start: [i32; 3], p: [i32; 3]) -> Axis { + let xdiff = p[0].wrapping_sub(start[0]).wrapping_abs(); + let zdiff = p[2].wrapping_sub(start[2]).wrapping_abs(); + let max = xdiff.max(zdiff); + if max > 0 { + if xdiff == max { Axis::X } else { Axis::Z } + } else { + Axis::Y + } +} +fn trim_branches(height: i32, local_y: i32) -> bool { + f64::from(local_y) >= f64::from(height) * 0.2 +} +fn tree_shape(height: i32, y: i32) -> f32 { + if (y as f32) < height as f32 * 0.3f32 { + return -1.0; + } + let radius = height as f32 / 2.0; + let adjacent = radius - y as f32; + let mut distance = (radius * radius - adjacent * adjacent).sqrt(); + if adjacent == 0.0 { + distance = radius; + } else if adjacent.abs() >= radius { + return 0.0; + } + distance * 0.5 +} diff --git a/crates/horizon-world/src/worldgen/tree_blocks.rs b/crates/horizon-world/src/worldgen/tree_blocks.rs new file mode 100644 index 000000000..d335b8d46 --- /dev/null +++ b/crates/horizon-world/src/worldgen/tree_blocks.rs @@ -0,0 +1,356 @@ +//! Registry-bound block classifications and property transitions shared by tree, +//! fallen-tree and other vegetation features. Built once per binding snapshot. +use super::{ + DecodeError, block_feature::FeatureBlockBindings, state_provider::properties::StateProperties, +}; +use crate::{ + block_properties::BlockProperty, + fluid::FluidKind, + registry::{BlockRegistry, BlockStateId}, +}; +use horizon_core::geometry::Direction; +use std::{collections::BTreeMap, sync::Arc}; + +pub(crate) const AIR: u32 = 1; +pub(crate) const LEAVES: u32 = 1 << 1; +pub(crate) const REPLACEABLE_BY_TREES: u32 = 1 << 2; +pub(crate) const LOGS: u32 = 1 << 3; +pub(crate) const PREVENTS_LEAF_DECAY: u32 = 1 << 4; +pub(crate) const VINE: u32 = 1 << 5; +pub(crate) const WATER_BLOCK: u32 = 1 << 6; +pub(crate) const WATER_SOURCE: u32 = 1 << 7; +pub(crate) const WATER_FLUID: u32 = 1 << 8; +pub(crate) const REPLACEABLE: u32 = 1 << 9; +pub(crate) const SOLID_RENDER: u32 = 1 << 10; +pub(crate) const SHELF_MUSHROOM: u32 = 1 << 11; +pub(crate) const PERSISTENT: u32 = 1 << 12; +pub(crate) const WATERLOGGABLE: u32 = 1 << 13; +pub(crate) const SOLID: u32 = 1 << 14; +pub(crate) const LAVA_FLUID: u32 = 1 << 15; +pub(crate) const ANY_FLUID: u32 = 1 << 16; +pub(crate) const FULL_AXIS: u32 = 1 << 17; + +/// Immutable per-state facts. Missing tags or blocks are empty classifications. +pub struct TreeBlocks { + flags: Vec, + /// Native LeavesBlock DISTANCE (1..=7) values; 0 when absent. + distance: Vec, + pub(crate) properties: Arc, + defaults: BTreeMap, +} +impl std::fmt::Debug for TreeBlocks { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TreeBlocks") + .field("states", &self.flags.len()) + .finish_non_exhaustive() + } +} +const DEFAULTS: [&str; 12] = [ + "minecraft:vine", + "minecraft:cocoa", + "minecraft:bee_nest", + "minecraft:creaking_heart", + "minecraft:pale_hanging_moss", + "minecraft:shelf_mushroom", + "minecraft:water", + "minecraft:lava", + "minecraft:air", + "minecraft:cave_air", + "minecraft:dirt", + "minecraft:mud", +]; +impl TreeBlocks { + pub(crate) fn build(bindings: &FeatureBlockBindings<'_>) -> Result { + let registry: &BlockRegistry = bindings.registry(); + let (providers, _, _) = bindings + .simple_blocks + .as_ref() + .ok_or(DecodeError::Field("tree state provider bindings"))?; + let properties = providers.properties()?; + let replaceable = super::block_predicate::PredicateBlockResolver::predicate_property( + bindings, + BlockProperty::Replaceable, + )?; + let solid_render = super::block_predicate::PredicateBlockResolver::predicate_property( + bindings, + BlockProperty::SolidRender, + )?; + let solid = super::block_predicate::PredicateBlockResolver::predicate_property( + bindings, + BlockProperty::Solid, + )?; + let mut flags = vec![0u32; registry.len()]; + let mut distance = vec![0u8; registry.len()]; + let mark_tag = |tag: &str, flag: u32, flags: &mut Vec| { + if let Some(states) = bindings.tags.get(tag) { + for state in states.iter() { + flags[state.0 as usize] |= flag; + } + } + }; + mark_tag("minecraft:leaves", LEAVES, &mut flags); + mark_tag( + "minecraft:replaceable_by_trees", + REPLACEABLE_BY_TREES, + &mut flags, + ); + mark_tag("minecraft:logs", LOGS, &mut flags); + mark_tag( + "minecraft:prevents_nearby_leaf_decay", + PREVENTS_LEAF_DECAY, + &mut flags, + ); + for (name, flag) in [ + ("minecraft:vine", VINE), + ("minecraft:water", WATER_BLOCK), + ("minecraft:shelf_mushroom", SHELF_MUSHROOM), + ] { + if let Some(states) = bindings.blocks.get(name) { + for state in states.iter() { + flags[state.0 as usize] |= flag; + } + } + } + for air in bindings.air { + flags[air.0 as usize] |= AIR; + } + for index in 0..registry.len() { + let id = BlockStateId(index as u32); + let flag = &mut flags[index]; + if replaceable.contains(id) { + *flag |= REPLACEABLE; + } + if solid_render.contains(id) { + *flag |= SOLID_RENDER; + } + if solid.contains(id) { + *flag |= SOLID; + } + if let Some(fluid) = bindings.fluids.state(id) { + match fluid.kind() { + FluidKind::Water => *flag |= WATER_SOURCE | WATER_FLUID | ANY_FLUID, + FluidKind::FlowingWater => *flag |= WATER_FLUID | ANY_FLUID, + FluidKind::Lava | FluidKind::FlowingLava => *flag |= LAVA_FLUID | ANY_FLUID, + FluidKind::Empty => {} + } + } + if properties.value(id, "persistent") == Some("true") { + *flag |= PERSISTENT; + } + if properties + .values(id, "waterlogged") + .is_some_and(|v| v.len() == 2) + { + *flag |= WATERLOGGABLE; + } + if properties.values(id, "axis").is_some_and(|values| { + values.len() == 3 && ["x", "y", "z"].iter().all(|a| values.iter().any(|v| v == a)) + }) { + *flag |= FULL_AXIS; + } + if let Some(values) = properties.values(id, "distance") { + let native = values.len() == 7 + && (1..=7).all(|n| values.iter().any(|v| *v == n.to_string())); + if native { + distance[index] = properties + .value(id, "distance") + .and_then(|v| v.parse().ok()) + .unwrap_or(0); + } + } + } + let defaults = DEFAULTS + .iter() + .filter_map(|name| { + registry + .default_state(name) + .map(|id| ((*name).to_owned(), id)) + }) + .collect(); + Ok(Self { + flags, + distance, + properties, + defaults, + }) + } + pub(crate) fn has(&self, state: BlockStateId, flag: u32) -> bool { + self.flags + .get(state.0 as usize) + .is_some_and(|value| value & flag != 0) + } + pub(crate) fn is_air(&self, state: BlockStateId) -> bool { + self.has(state, AIR) + } + /// TreeFeature.validTreePos: air or replaceable by trees. + pub(crate) fn valid_tree_pos(&self, state: BlockStateId) -> bool { + self.has(state, AIR | REPLACEABLE_BY_TREES) + } + /// LeavesBlock.getOptionalDistanceAt. + pub(crate) fn leaf_distance(&self, state: BlockStateId) -> Option { + if self.has(state, PREVENTS_LEAF_DECAY) { + return Some(0); + } + match self.distance.get(state.0 as usize) { + Some(0) | None => None, + Some(d) => Some(i32::from(*d)), + } + } + pub(crate) fn default_state(&self, name: &str) -> Option { + self.defaults.get(name).copied() + } + pub(crate) fn with(&self, state: BlockStateId, name: &str, value: &str) -> Option { + self.properties.with_value(state, name, value) + } + /// BlockState.trySetValue(RotatedPillarBlock.AXIS, axis). + pub(crate) fn try_axis(&self, state: BlockStateId, axis: Axis) -> BlockStateId { + if self.has(state, FULL_AXIS) { + self.with(state, "axis", axis.name()).unwrap_or(state) + } else { + state + } + } + /// Set WATERLOGGED when the state has that property; otherwise unchanged. + pub(crate) fn waterlogged(&self, state: BlockStateId, value: bool) -> BlockStateId { + if self.has(state, WATERLOGGABLE) { + self.with(state, "waterlogged", if value { "true" } else { "false" }) + .unwrap_or(state) + } else { + state + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Axis { + X, + Y, + Z, +} +impl Axis { + pub(crate) fn name(self) -> &'static str { + match self { + Self::X => "x", + Self::Y => "y", + Self::Z => "z", + } + } + pub(crate) fn of(direction: Direction) -> Self { + match direction { + Direction::West | Direction::East => Self::X, + Direction::Down | Direction::Up => Self::Y, + Direction::North | Direction::South => Self::Z, + } + } +} + +/// Direction.Plane.HORIZONTAL order. +pub(crate) const HORIZONTAL: [Direction; 4] = [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, +]; +pub(crate) fn clockwise(direction: Direction) -> Direction { + match direction { + Direction::North => Direction::East, + Direction::East => Direction::South, + Direction::South => Direction::West, + Direction::West => Direction::North, + other => other, + } +} +pub(crate) fn direction_name(direction: Direction) -> &'static str { + match direction { + Direction::Down => "down", + Direction::Up => "up", + Direction::North => "north", + Direction::South => "south", + Direction::West => "west", + Direction::East => "east", + } +} +pub(crate) fn decode_direction(name: &str) -> Result { + Direction::ALL + .into_iter() + .find(|d| direction_name(*d) == name) + .ok_or(DecodeError::Field("direction")) +} +pub(crate) fn offset(p: [i32; 3], dx: i32, dy: i32, dz: i32) -> [i32; 3] { + [ + p[0].wrapping_add(dx), + p[1].wrapping_add(dy), + p[2].wrapping_add(dz), + ] +} +pub(crate) fn relative(p: [i32; 3], direction: Direction, distance: i32) -> [i32; 3] { + let n = direction.normal(); + offset( + p, + n[0].wrapping_mul(distance), + n[1].wrapping_mul(distance), + n[2].wrapping_mul(distance), + ) +} +/// Vec3i.distManhattan, including its float accumulation. +pub(crate) fn dist_manhattan(a: [i32; 3], b: [i32; 3]) -> i32 { + let d = |i: usize| b[i].wrapping_sub(a[i]).wrapping_abs() as f32; + (d(0) + d(1) + d(2)) as i32 +} + +/// Java HashSet with native bucket iteration order. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct JavaPos(pub [i32; 3]); +impl crate::java_hash_map::JavaKey for JavaPos { + fn java_hash(&self) -> i32 { + let [x, y, z] = self.0; + y.wrapping_add(z.wrapping_mul(31)) + .wrapping_mul(31) + .wrapping_add(x) + } + fn tie_break(&self, other: &Self) -> std::cmp::Ordering { + // BlockPos is not self-Comparable for HashMap; vanilla falls back to + // identity hashes, which are not reproducible. Any total order works. + let key = |p: &Self| (p.0[1], p.0[2], p.0[0]); + match key(self).cmp(&key(other)) { + std::cmp::Ordering::Equal => std::cmp::Ordering::Less, + ordering => ordering, + } + } +} +#[derive(Default)] +pub(crate) struct PosSet(crate::java_hash_map::JavaHashMap); +impl PosSet { + pub(crate) fn insert(&mut self, p: [i32; 3]) -> bool { + self.0.put(JavaPos(p), ()).is_none() + } + pub(crate) fn contains(&self, p: [i32; 3]) -> bool { + self.0.get(&JavaPos(p)).is_some() + } + pub(crate) fn is_empty(&self) -> bool { + self.0.is_empty() + } + /// Iteration order of the native set. + pub(crate) fn to_vec(&self) -> Vec<[i32; 3]> { + self.0.entries().map(|(k, _)| k.0).collect() + } + /// iterator().next() followed by iterator.remove(). + pub(crate) fn pop_first(&mut self) -> Option<[i32; 3]> { + let mut cursor = self.0.cursor(); + let first = self.0.next_entry(&mut cursor).ok().flatten()?.0.0; + self.0.remove_current(&mut cursor).ok()?; + Some(first) + } +} + +/// Util.shuffle (Fisher-Yates from the end with nextInt(i)). +pub(crate) fn shuffle( + values: &mut [T], + random: &mut impl horizon_core::random::RandomSource, +) -> Result<(), horizon_core::random::InvalidBound> { + for i in (2..=values.len()).rev() { + let swap = random.next_int_bound(i as i32)? as usize; + values.swap(i - 1, swap); + } + Ok(()) +} From 03d32fc788027cbc77ac096e317b9dc2a3b00db5 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:04:57 +0200 Subject: [PATCH 02/12] Add tree, fallen-tree and ore differential parity harness Decodes every vanilla 26.3 tree, fallen_tree, ore and scattered_ore configured feature from the authenticated JAR, places each with both random kinds over layered synthetic worlds backed by native proto-chunk sections, and compares ordered writes, beehive occupants, post-processing marks, results, random tails and the final block diff with Rust. First run: 2783 of 3018 fixtures identical; every ore fixture matches. The remaining differences are StructureTemplate.updateShapeAtEdge neighbor shape updates (faceless vines and unsupported plants beside the tree), which the Rust world hook does not yet implement. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../examples/tree_feature_fixture.rs | 337 ++++++++++++++++++ .../parity/VanillaTreeFeatureOracle.java | 148 ++++++++ tools/test_tree_feature_parity.py | 123 +++++++ 3 files changed, 608 insertions(+) create mode 100644 crates/horizon-world/examples/tree_feature_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java create mode 100644 tools/test_tree_feature_parity.py diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/tree_feature_fixture.rs new file mode 100644 index 000000000..0a16dc554 --- /dev/null +++ b/crates/horizon-world/examples/tree_feature_fixture.rs @@ -0,0 +1,337 @@ +//! Vanilla tree, fallen-tree and ore features over a layered synthetic world. +use horizon_core::{ + geometry::{Direction, VoxelShape}, + random::{LegacyRandom, RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + block_placement::BlockPlacementBindings, + block_properties::BlockPropertiesRegistry, + block_support::{BlockSupportRegistry, SupportType}, + collision::CachedCollisionRegistry, + dynamic_support::DynamicSupportWorld, + fluid::{FluidKind, FluidState, FluidStateTable}, + heightmap::HeightmapType, + nbt::{self, Limits, Tag}, + registry::{BlockRegistry, BlockStateId}, + worldgen::{ + anchor::WorldGenerationContext, + block_feature::FeatureBlockBindings, + feature::{FeatureBlocks, FeatureWorld}, + feature_catalog::FeatureCatalog, + placement::{PlacementContext, PlacementQueryError}, + state_provider::{StateProviderBindings, StateProviderCatalog}, + tags::TagDefinitions, + }, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet, HashMap}, + fs, + io::{self, BufRead, Write}, + path::Path, + sync::Arc, +}; + +const MIN_Y: i32 = -64; +const HEIGHT: i32 = 384; + +struct Terrain { + layers: Vec<[i32; 2]>, + hole: [i32; 2], + obstacle: [i32; 3], + overrides: HashMap<[i32; 3], u32>, + air: u32, +} +impl Terrain { + fn new(f: &Value, air: u32) -> Self { + let n = |key: &str| f[key].as_i64().unwrap() as i32; + Self { + layers: f["layers"] + .as_array() + .unwrap() + .iter() + .map(|l| [l[0].as_i64().unwrap() as i32, l[1].as_i64().unwrap() as i32]) + .collect(), + hole: [n("hole_mod"), n("hole_state")], + obstacle: [n("obstacle_mod"), n("obstacle_state"), n("obstacle_min")], + overrides: f["states"] + .as_array() + .unwrap() + .iter() + .map(|v| { + ( + std::array::from_fn(|i| v[i].as_i64().unwrap() as i32), + v[3].as_u64().unwrap() as u32, + ) + }) + .collect(), + air, + } + } + fn hash(x: i32, y: i32, z: i32) -> i32 { + let mut h = x.wrapping_mul(73856093) ^ y.wrapping_mul(19349663) ^ z.wrapping_mul(83492791); + h ^= ((h as u32) >> 13) as i32; + h = h.wrapping_mul(0x5bd1e995); + h ^= ((h as u32) >> 15) as i32; + h & 0x7fff_ffff + } + fn at(&self, [x, y, z]: [i32; 3]) -> BlockStateId { + if let Some(state) = self.overrides.get(&[x, y, z]) { + return BlockStateId(*state); + } + let h = Self::hash(x, y, z); + if let Some(layer) = self.layers.iter().find(|l| y <= l[0]) { + if self.hole[0] > 0 && h % self.hole[0] == 0 { + return BlockStateId(self.hole[1] as u32); + } + return BlockStateId(layer[1] as u32); + } + if self.obstacle[0] > 0 && y >= self.obstacle[2] && h % self.obstacle[0] == 0 { + return BlockStateId(self.obstacle[1] as u32); + } + BlockStateId(self.air) + } +} + +struct World<'a, 'r, W> { + out: &'a mut W, + terrain: Terrain, + overlay: BTreeMap<[i32; 3], BlockStateId>, + void_air: BlockStateId, + height: i32, + fluids: &'a FluidStateTable, + tags: &'a BTreeMap>, + support: &'a BlockSupportRegistry<'r>, +} +impl World<'_, '_, W> { + fn get(&self, p: [i32; 3]) -> BlockStateId { + if p[1] < MIN_Y || p[1] >= MIN_Y + HEIGHT { + return self.void_air; + } + self.overlay + .get(&p) + .copied() + .unwrap_or_else(|| self.terrain.at(p)) + } +} +fn query(error: impl std::fmt::Display) -> PlacementQueryError { + PlacementQueryError::Failed(error.to_string()) +} +impl FeatureWorld for World<'_, '_, W> { + type Error = io::Error; + fn block(&mut self, p: [i32; 3]) -> io::Result { + Ok(self.get(p)) + } + fn set_block(&mut self, p: [i32; 3], state: BlockStateId, flags: i32) -> io::Result { + writeln!(self.out, "set {} {} {} {} {flags}", p[0], p[1], p[2], state.0)?; + if p[1] < MIN_Y || p[1] >= MIN_Y + HEIGHT { + return Ok(false); + } + self.overlay.insert(p, state); + Ok(true) + } +} +impl DynamicSupportWorld for World<'_, '_, W> { + type Error = io::Error; + fn shulker_is_closed(&mut self, _: [i32; 3]) -> io::Result> { + Ok(None) + } + fn moving_piston_shape(&mut self, _: [i32; 3]) -> io::Result> { + Ok(None) + } +} +impl PlacementContext for World<'_, '_, W> { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(MIN_Y, HEIGHT, 63) + } + fn min_y(&mut self) -> Result { + Ok(MIN_Y) + } + fn max_y(&mut self) -> Result { + Ok(MIN_Y + HEIGHT - 1) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Ok(self.height) + } + fn block_state(&mut self, p: [i32; 3]) -> Result { + Ok(self.get(p)) + } + fn fluid_state(&mut self, p: [i32; 3]) -> Result { + self.fluids + .get(self.get(p)) + .ok_or_else(|| query("unknown fluid")) + } + fn block_matches_tag(&mut self, p: [i32; 3], tag: &str) -> Result { + let state = self.get(p); + Ok(self.tags.get(tag).is_some_and(|s| s.contains(&state))) + } + fn state_face_sturdy( + &mut self, + state: BlockStateId, + p: [i32; 3], + direction: Direction, + ) -> Result { + let support = self.support; + support + .is_face_sturdy(self, state, p, direction, SupportType::Full) + .map_err(query) + } + fn face_sturdy(&mut self, p: [i32; 3], direction: Direction) -> Result { + let state = self.get(p); + self.state_face_sturdy(state, p, direction) + } + fn mark_postprocessing(&mut self, p: [i32; 3]) -> Result<(), PlacementQueryError> { + writeln!(self.out, "post {} {} {}", p[0], p[1], p[2]).map_err(query) + } + fn set_section_block(&mut self, p: [i32; 3], state: BlockStateId) -> Result<(), PlacementQueryError> { + self.overlay.insert(p, state); + Ok(()) + } + fn store_beehive_occupants(&mut self, p: [i32; 3], ticks: &[i32]) -> Result<(), PlacementQueryError> { + for t in ticks { + writeln!(self.out, "bee {} {} {} {t}", p[0], p[1], p[2]).map_err(query)?; + } + Ok(()) + } +} + +#[allow(clippy::too_many_arguments)] +fn fixture( + f: &Value, + mut random: R, + catalog: &FeatureCatalog, + features: &BTreeMap, + bindings: &FeatureBlockBindings<'_>, + blocks: FeatureBlocks, + world: &mut World<'_, '_, impl Write>, +) -> io::Result<()> { + let name = f["feature"].as_str().unwrap(); + writeln!(world.out, "fixture {name}")?; + let feature = match catalog.feature_with_blocks(&features[name], bindings) { + Ok(feature) => feature, + Err(error) => { + eprintln!("decode {name}: {error}"); + return writeln!(world.out, "decode error"); + } + }; + let origin = std::array::from_fn(|i| f["origin"][i].as_i64().unwrap() as i32); + match feature.place(world, &mut random, origin, blocks) { + Ok(result) => writeln!(world.out, "place {result}")?, + Err(error) => writeln!(world.out, "place error {error}")?, + } + writeln!(world.out, "next {}", random.next_long())?; + let changes: Vec<_> = world + .overlay + .iter() + .filter(|(p, state)| world.terrain.at(**p) != **state) + .map(|(p, s)| (*p, *s)) + .collect(); + for (p, state) in changes { + writeln!(world.out, "final {} {} {} {}", p[0], p[1], p[2], state.0)?; + } + writeln!(world.out, "end") +} + +fn main() -> Result<(), Box> { + let arg = std::env::args().nth(1).expect("private fixture directory"); + let dir = Path::new(&arg); + let read = |name: &str| -> Result> { + Ok(nbt::read_named(&fs::read(dir.join(name))?, Limits::default())?.0.tag) + }; + let registry = BlockRegistry::from_nbt(&read("block-registry.nbt")?)?; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?; + let properties = BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; + let support = BlockSupportRegistry::from_nbt(&read("cached-support.nbt")?, ®istry)?; + let resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("tags.json"))?)?; + let mut tags = TagDefinitions::default(); + for (name, text) in resources { + tags.apply_json(&name, "vanilla", &text)?; + } + let tags = tags.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; + let fluid_resources: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("fluid-tags.json"))?)?; + let mut fluid_tags = TagDefinitions::default(); + for (name, text) in fluid_resources { + fluid_tags.apply_json(&name, "vanilla", &text)?; + } + let fluid_tags = + fluid_tags.build(|name, _| FluidKind::from_name(name).map(|_| name.to_owned()))?; + let facts: Value = serde_json::from_str(&fs::read_to_string(dir.join("facts.json"))?)?; + let integers: BTreeSet<(String, String)> = facts["integers"] + .as_array() + .unwrap() + .iter() + .map(|v| (v[0].as_str().unwrap().to_owned(), v[1].as_str().unwrap().to_owned())) + .collect(); + let bundle: Value = + serde_json::from_str(&fs::read_to_string(dir.join("vanilla-features.json"))?)?; + let providers: BTreeMap = serde_json::from_value(bundle["providers"].clone())?; + let features: BTreeMap = serde_json::from_value(bundle["features"].clone())?; + let definitions: Value = + serde_json::from_str(&fs::read_to_string(dir.join("placement-definitions.json"))?)?; + let bindings = FeatureBlockBindings::with_tags(®istry, integers.clone(), &tags.tags)? + .with_block_properties(&properties)? + .with_fluid_tags(&fluid_tags.tags)? + .with_state_providers( + StateProviderBindings::new(®istry, integers, &tags.tags)? + .with_block_properties(&properties)? + .with_fluid_tags(&fluid_tags.tags)?, + StateProviderCatalog::from_resources(&providers)?, + BlockPlacementBindings::new( + ®istry, + &properties, + &serde_json::from_value(definitions["double_plants"].clone())?, + &serde_json::from_value(definitions["mossy_carpets"].clone())?, + )?, + )?; + let catalog = FeatureCatalog::from_resources(&features, &BTreeMap::new(), &TagDefinitions::default())?; + let blocks = FeatureBlocks::from_registry(®istry)?; + let fluids = FluidStateTable::new(®istry)?; + let mut by_name = BTreeMap::>::new(); + for id in 0..registry.len() { + let id = BlockStateId(id as u32); + by_name + .entry(registry.state(id).unwrap().name.clone()) + .or_default() + .push(id); + } + let tag_states: BTreeMap> = tags + .tags + .iter() + .map(|(name, entries)| { + ( + name.clone(), + entries + .iter() + .flat_map(|e| by_name.get(e).into_iter().flatten().copied()) + .collect(), + ) + }) + .collect(); + let support = Arc::new(support); + let air = registry.default_state("minecraft:air").unwrap().0; + let void_air = registry.default_state("minecraft:void_air").unwrap(); + let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); + for line in io::BufReader::new(fs::File::open(dir.join("inputs.txt"))?).lines() { + let f: Value = serde_json::from_str(&line?)?; + let mut world = World { + out: &mut out, + terrain: Terrain::new(&f, air), + overlay: BTreeMap::new(), + void_air, + height: f["height"].as_i64().unwrap() as i32, + fluids: &fluids, + tags: &tag_states, + support: &support, + }; + let seed = f["seed"].as_i64().unwrap(); + if f["legacy"].as_bool().unwrap() { + fixture(&f, LegacyRandom::new(seed), &catalog, &features, &bindings, blocks, &mut world)?; + } else { + fixture(&f, XoroshiroRandom::new(seed), &catalog, &features, &bindings, blocks, &mut world)?; + } + } + out.flush()?; + Ok(()) +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java new file mode 100644 index 000000000..34b5da571 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java @@ -0,0 +1,148 @@ +package dev.horizonlab.parity; +import com.google.gson.*; +import com.mojang.serialization.JsonOps; +import java.io.*; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.core.*; +import net.minecraft.core.registries.*; +import net.minecraft.resources.*; +import net.minecraft.util.RandomSource; +import net.minecraft.world.level.*; +import net.minecraft.world.level.biome.*; +import net.minecraft.world.level.block.*; +import net.minecraft.world.level.block.entity.*; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.chunk.*; +import net.minecraft.world.level.levelgen.*; +import net.minecraft.world.level.levelgen.feature.Feature; +import net.minecraft.world.level.levelgen.feature.stateproviders.BlockStateProvider; + +/** + * Actual native tree, fallen-tree and ore features over a layered synthetic + * world backed by proto-chunk sections. Logs ordered level writes, beehive + * occupants, post-processing marks, results, random tails and the final diff. + */ +public final class VanillaTreeFeatureOracle { + private static final int MIN_Y=-64,HEIGHT=384; + private static BlockPos pos(JsonArray a){return new BlockPos(a.get(0).getAsInt(),a.get(1).getAsInt(),a.get(2).getAsInt());} + private static String xyz(BlockPos p){return p.getX()+" "+p.getY()+" "+p.getZ();} + private static final class Chunks { + static final PalettedContainerFactory FACTORY; + static { + Holder biome=Holder.Reference.createStandAlone(new HolderOwner(){},Biomes.PLAINS); + var ids=new IdMapper>();ids.add(biome); + FACTORY=new PalettedContainerFactory(Strategy.createForBlockStates(Block.BLOCK_STATE_REGISTRY),Blocks.AIR.defaultBlockState(),null,Strategy.createForBiomes(ids),biome,null); + } + } + /** Shared with the Rust fixture: layered column, pseudo-random holes and obstacles, overrides. */ + static final class Terrain { + final int[][] layers;final int holeMod,holeState,obstacleMod,obstacleState,obstacleMin;final Map overrides=new HashMap<>(); + Terrain(JsonObject f){ + var raw=f.getAsJsonArray("layers");layers=new int[raw.size()][];for(int i=0;i>>13;h*=0x5bd1e995;h^=h>>>15;return h&0x7fffffff;} + int at(int x,int y,int z){ + var o=overrides.get(new BlockPos(x,y,z));if(o!=null)return o; + int base=-1;for(var l:layers)if(y<=l[0]){base=l[1];break;} + int h=hash(x,y,z); + if(base>=0){if(holeMod>0&&h%holeMod==0)return holeState;return base;} + if(obstacleMod>0&&y>=obstacleMin&&h%obstacleMod==0)return obstacleState; + return Block.getId(Blocks.AIR.defaultBlockState()); + } + } + private static final class World implements InvocationHandler { + final JsonObject f;final PrintWriter out;final Terrain terrain;final Map chunks=new HashMap<>();final Map hives=new HashMap<>(); + final RandomSource shapeRandom=RandomSource.create(0); + World(JsonObject f,PrintWriter out){this.f=f;this.out=out;this.terrain=new Terrain(f);} + ProtoChunk chunk(int cx,int cz){ + return chunks.computeIfAbsent(new ChunkPos(cx,cz),cp->{ + var chunk=new ProtoChunk(cp,UpgradeData.EMPTY,LevelHeightAccessor.create(MIN_Y,HEIGHT),Chunks.FACTORY,null){ + @Override public void markPosForPostProcessing(BlockPos position){out.println("post "+xyz(position));super.markPosForPostProcessing(position);} + }; + for(int s=0;s=MIN_Y+HEIGHT)return Blocks.VOID_AIR.defaultBlockState(); + return chunk(p.getX()>>4,p.getZ()>>4).getBlockState(p); + } + public Object invoke(Object proxy,Method method,Object[] args)throws Throwable { + String name=method.getName(); + switch(name){ + case "getBlockState":return get((BlockPos)args[0]); + case "getFluidState":return get((BlockPos)args[0]).getFluidState(); + case "isStateAtPosition":return ((java.util.function.Predicate)args[1]).test(get((BlockPos)args[0])); + case "isFluidAtPosition":return ((java.util.function.Predicate)args[1]).test(get((BlockPos)args[0]).getFluidState()); + case "getMinY":return MIN_Y; + case "getSeaLevel":return 63; + case "ensureCanWrite":return true; + case "getRandom":return shapeRandom; + case "scheduleTick":return null; + case "setCurrentlyGenerating":return null; + case "getBlockEntity":{ + if(args.length!=1)break;var p=((BlockPos)args[0]).immutable();var state=get(p); + if(!state.is(Blocks.BEE_NEST))return null; + return hives.computeIfAbsent(p,key->new BeehiveBlockEntity(key,state){@Override public void storeBee(BeehiveBlockEntity.Occupant occupant){out.println("bee "+xyz(key)+" "+occupant.ticksInHive());}}); + } + case "setBlock":{ + var p=((BlockPos)args[0]).immutable();var state=(BlockState)args[1];out.println("set "+xyz(p)+" "+Block.getId(state)+" "+args[2]); + if(p.getY()=MIN_Y+HEIGHT)return false; + chunk(p.getX()>>4,p.getZ()>>4).getSection((p.getY()-MIN_Y)>>4).setBlockState(p.getX()&15,p.getY()&15,p.getZ()&15,state,false);return true; + } + case "getHeight":if(args==null||args.length==0)return HEIGHT;return f.get("height").getAsInt(); + case "getChunk": + if(args.length==1&&args[0] instanceof BlockPos p)return chunk(p.getX()>>4,p.getZ()>>4); + if(args.length>=2&&args[0] instanceof Integer x&&args[1] instanceof Integer z)return chunk(x,z); + break; + default:break; + } + if(method.isDefault())return InvocationHandler.invokeDefault(proxy,method,args); + throw new AssertionError(method); + } + } + @SuppressWarnings("unchecked") + public static void main(String[] args)throws Exception { + net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); + VanillaHeightmapOracle.bindTags(JsonParser.parseString(Files.readString(dir.resolve("tags.json"))).getAsJsonObject()); + var bind=VanillaBlockSurvivalOracle.class.getDeclaredMethod("bindFluidTags",JsonObject.class);bind.setAccessible(true);bind.invoke(null,JsonParser.parseString(Files.readString(dir.resolve("fluid-tags.json"))).getAsJsonObject()); + var providers=new MappedRegistry(Registries.BLOCK_STATE_PROVIDER,com.mojang.serialization.Lifecycle.stable()); + var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ + if(key.equals(Registries.BLOCK_STATE_PROVIDER))return (Optional>)(Optional)Optional.of(providers); + if(key.equals(Registries.FLUID))return (Optional>)(Optional)Optional.of(BuiltInRegistries.FLUID); + return key.equals(Registries.BLOCK)?(Optional>)(Optional)Optional.of(BuiltInRegistries.BLOCK):Optional.empty(); + }}); + var bundle=JsonParser.parseString(Files.readString(dir.resolve("vanilla-features.json"))).getAsJsonObject(); + for(var entry:bundle.getAsJsonObject("providers").entrySet()) + providers.register(ResourceKey.create(Registries.BLOCK_STATE_PROVIDER,Identifier.parse(entry.getKey())),BlockStateProvider.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); + providers.freeze(); + var features=bundle.getAsJsonObject("features"); + try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { + for(var line:(Iterable)inputs::iterator){ + var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); + RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); + out.println("fixture "+f.get("feature").getAsString()); + Optional decoded; + try{decoded=Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(features.get(f.get("feature").getAsString()).getAsString())).result();}catch(RuntimeException error){decoded=Optional.empty();} + if(decoded.isEmpty()){out.println("decode error");continue;} + var handler=new World(f,out);var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},handler); + try{out.println("place "+decoded.get().place(world,null,random,pos(f.getAsJsonArray("origin"))));}catch(RuntimeException error){out.println("place error "+error);} + out.println("next "+random.nextLong()); + var keys=new ArrayList<>(handler.chunks.keySet());keys.sort(Comparator.comparingInt(ChunkPos::x).thenComparingInt(ChunkPos::z)); + var changes=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); + for(var key:keys){var chunk=handler.chunks.get(key); + for(int y=MIN_Y;y>4).getBlockState(lx,y&15,lz)); + if(id!=handler.terrain.at(x,y,z))changes.put(new BlockPos(x,y,z),id); + }} + for(var e:changes.entrySet())out.println("final "+xyz(e.getKey())+" "+e.getValue()); + out.println("end"); + } + } + } +} diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py new file mode 100644 index 000000000..6886044e1 --- /dev/null +++ b/tools/test_tree_feature_parity.py @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +"""Compare vanilla tree, fallen-tree and ore features block-for-block with vanilla.""" +import argparse +import json +import os +from pathlib import Path +import platform +import subprocess +import zipfile +try: + from . import lab, test_rust_parity as base, test_worldgen_parity as worldgen, test_block_survival_parity as survival +except ImportError: + import lab + import test_rust_parity as base + import test_worldgen_parity as worldgen + import test_block_survival_parity as survival + + +def feature_resources(jar): + """Vanilla configured features and named state providers from the authenticated JAR.""" + result={'features':{},'providers':{}} + with zipfile.ZipFile(jar) as archive: + for kind,key in [('feature','features'),('block_state_provider','providers')]: + prefix=f'data/minecraft/worldgen/{kind}/' + for name in sorted(archive.namelist()): + if name.startswith(prefix) and name.endswith('.json'): + result[key]['minecraft:'+name[len(prefix):-5]]=archive.read(name).decode('utf-8') + return result + + +def fixture_hashes(paths): + # Build outputs may live behind a linked private directory outside ROOT. + return {path.name:lab.digest(path,'sha256') for path in paths} + + +def corpus(facts,resources): + get=lambda name:facts['defaults']['minecraft:'+name] + def fixture(feature,**extra): + f={'feature':feature,'seed':0,'legacy':False,'origin':[8,65,8],'height':65,'layers':[[59,get('stone')],[63,get('dirt')],[64,get('grass_block')]], + 'hole_mod':0,'hole_state':get('air'),'obstacle_mod':0,'obstacle_state':get('air'),'obstacle_min':0,'states':[]} + f.update(extra);return f + seeds=[0,1,-1,0x5DEECE66D,0x123456789abcdef,-8070450532247928832] + origins=[[8,65,8],[15,65,0],[0,65,15],[-1,65,-17],[31,65,-16],[100003,65,-4097]] + trees,ores=[],[] + for name,text in resources['features'].items(): + value=json.loads(text);kind=value['type'].removeprefix('minecraft:') + if kind in ('tree','fallen_tree'): + if 'pale_moss' in text:continue # needs the level's feature registry and server level + trees.append(name) + elif kind in ('ore','scattered_ore'):ores.append(name) + worlds=[ + {}, + {'obstacle_mod':37,'obstacle_state':get('oak_leaves'),'obstacle_min':66}, + {'obstacle_mod':23,'obstacle_state':get('stone'),'obstacle_min':65}, + {'obstacle_mod':19,'obstacle_state':get('vine'),'obstacle_min':65}, + {'layers':[[59,get('stone')],[64,get('mud')],[67,get('water')]],'height':68}, + {'layers':[[300,get('stone')],[310,get('dirt')],[311,get('grass_block')]],'origin_y':312,'height':312}, + {'layers':[[59,get('stone')],[63,get('dirt')],[64,get('podzol')]],'hole_mod':11,'hole_state':get('short_grass')}, + ] + for name in trees: + for w,world in enumerate(worlds): + for s,seed in enumerate(seeds): + extra=dict(world);origin=list(origins[(s+w)%len(origins)]);origin[1]=extra.pop('origin_y',extra.get('height',65)) + yield fixture(name,seed=seed,legacy=s%3==2,origin=origin,**extra) + ore_worlds=[ + {'layers':[[-1,get('deepslate')],[250,get('stone')]],'height':251}, + {'layers':[[-1,get('deepslate')],[250,get('stone')]],'height':251,'hole_mod':5,'hole_state':get('air')}, + {'layers':[[-1,get('deepslate')],[250,get('stone')]],'height':-100}, + {'layers':[[250,get('netherrack')]],'height':251,'hole_mod':9,'hole_state':get('cave_air')}, + {'layers':[[30,get('tuff')],[250,get('granite')]],'height':251,'hole_mod':13,'hole_state':get('water')}, + ] + for name in ores: + for w,world in enumerate(ore_worlds): + for s,seed in enumerate(seeds): + origin=list(origins[(s+w)%len(origins)]);origin[1]=[-60,-3,0,40,316,-64][(s*5+w)%6] + yield fixture(name,seed=seed,legacy=s%3==2,origin=origin,**world) + + +def main(): + parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() + build=lab.LOCAL/'rust-tree-feature-parity';build.mkdir(parents=True,exist_ok=True);report_path=build/'report.json';report_path.unlink(missing_ok=True) + if args.prepare:lab.prepare() + lock,jars,libraries=base.verify_artifacts();parity=lab.ROOT/'mods/horizon/src/test/java/dev/horizonlab/parity' + oracle=parity/'VanillaTreeFeatureOracle.java';exporter=parity/'VanillaSimpleBlockOracle.java' + helpers=[parity/(name+'.java') for name in ['VanillaPlacementOracle','VanillaBlockSurvivalOracle','VanillaBlockPropertiesOracle','VanillaBlockSupportOracle','VanillaBlockStateCodecOracle','VanillaCollisionOracle','VanillaHeightmapOracle']] + sources=[oracle,exporter,*helpers,Path(__file__),*[lab.ROOT/'tools'/name for name in ['test_block_survival_parity.py','test_worldgen_parity.py','test_rust_parity.py','lab.py']],lab.ROOT/'Cargo.toml',lab.ROOT/'Cargo.lock', + *sorted((lab.ROOT/'crates/horizon-core/src').rglob('*.rs')),*sorted((lab.ROOT/'crates/horizon-world/src').rglob('*.rs')),lab.ROOT/'crates/horizon-world/examples/tree_feature_fixture.rs'] + tested_sources=base.source_hashes(sources);classes=build/'classes';classes.mkdir(exist_ok=True) + def run(command,name): + with (build/(name+'.log')).open('w',encoding='utf-8') as log:subprocess.run(list(map(str,command)),cwd=lab.ROOT,check=True,timeout=7200,stdout=log,stderr=subprocess.STDOUT) + dependency_path=os.pathsep.join(map(str,libraries)) + def java(main_class,side,mode,path):run(['java','-Xmx2G','-cp',os.pathsep.join([str(classes),str(jars[side]),dependency_path]),'dev.horizonlab.parity.'+main_class,mode,path],side+'-'+mode) + tags=worldgen.tag_resources(jars['server']);fluid_tags=survival.fluid_tag_resources(jars['server']);resources=feature_resources(jars['server']) + if tags!=worldgen.tag_resources(jars['client']) or fluid_tags!=survival.fluid_tag_resources(jars['client']) or resources!=feature_resources(jars['client']):raise ValueError('reference resources differ') + for name,value in [('tags.json',tags),('fluid-tags.json',fluid_tags),('vanilla-features.json',resources)]:(build/name).write_text(json.dumps(value,separators=(',',':'))) + run(['javac','--release',lock['minecraft']['java_major'],'-proc:none','-cp',str(jars['server'])+os.pathsep+dependency_path,'-d',classes,oracle,exporter,*helpers],'compile-java') + for side in jars: + export=build/(side+'-definitions');export.mkdir(exist_ok=True);java('VanillaSimpleBlockOracle',side,'export',export) + for path in (build/'server-definitions').iterdir(): + if path.read_bytes()!=(build/'client-definitions'/path.name).read_bytes():raise ValueError('reference definitions differ: '+path.name) + (build/path.name).write_bytes(path.read_bytes()) + facts=json.loads((build/'facts.json').read_text()) + inputs=build/'inputs.txt';count=0 + with inputs.open('w',encoding='utf-8') as output: + for fixture in corpus(facts,resources):output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 + fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) + print(f'Prepared {count:,} feature fixtures',flush=True) + run(['cargo','build','--release','-p','horizon-world','--example','tree_feature_fixture'],'compile-rust') + metadata=json.loads(subprocess.check_output(['cargo','metadata','--no-deps','--format-version','1'],cwd=lab.ROOT,text=True)) + binary=Path(metadata['target_directory'])/'release/examples'/('tree_feature_fixture.exe' if os.name=='nt' else 'tree_feature_fixture') + run([binary,build],'rust');references=[] + for side,jar in jars.items(): + java('VanillaTreeFeatureOracle',side,side,build);matched=base.compare(build/(side+'.txt'),build/'rust.txt');print(f'{side}: {matched:,} tree/ore output lines match Rust',flush=True) + references.append({'side':side,'jar_sha256':lab.digest(jar,'sha256'),'output_sha256':lab.digest(build/(side+'.txt'),'sha256'),'matched_output_lines':matched}) + base.ensure_sources_unchanged(sources,tested_sources); + if fixture_hashes(fixtures)!=tested_fixtures:raise ValueError('fixtures changed during the run') + report={'schema':1,'minecraft':lock['minecraft']['version'],'manifest_sha1':lock['minecraft']['manifest_sha1'],'platform':platform.platform(),'java':subprocess.check_output(['java','--version'],text=True).splitlines()[0], + 'rustc':subprocess.check_output(['rustc','--version'],text=True).strip(),'fixtures':count,'sources_sha256':tested_sources,'fixtures_sha256':tested_fixtures,'rust_output_sha256':lab.digest(build/'rust.txt','sha256'),'references':references, + 'scope':'Every vanilla 26.3 minecraft:tree (except pale-moss decorated), minecraft:fallen_tree, minecraft:ore and minecraft:scattered_ore configured feature, decoded from the authenticated JAR data, placed with both random kinds over layered synthetic worlds (open ground, leaf/stone/vine obstacles, flooded mud, near the build limit, podzol with grass) backed by native proto-chunk sections. Ordered level writes and flags, beehive occupants, post-processing marks, results, random tails and the final block diff of every touched chunk are compared, including native leaf distances and edge shape updates. Pale-moss ground patches, real WorldGenRegion write policy, heightmaps and decoration scheduling remain covered elsewhere or pending.'} + lab.write_json(report_path,report);print(f'Scoped tree/ore feature parity passed: {report_path}',flush=True) + + +if __name__=='__main__':main() From 13038b4f18547e65c560f9fa48cfe9a8701c585f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:04:57 +0200 Subject: [PATCH 03/12] Port vegetation patch, coral, huge mushroom, multiface, lake, dungeon, geode, iceberg and root system features Adds minecraft:vegetation_patch and waterlogged_vegetation_patch (native HashSet surface order), coral_tree/coral_claw over nested placed features, huge_red/brown_mushroom, multiface_growth (glow lichen and sculk vein spreaders), lake, monster_room (chest reorientation, loot seed and spawner entity hooks), geode (seeded parity noise via a new world-seed query), iceberg and root_system. Catalog expansion resolves their nested placed-feature holders. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 4 + crates/horizon-world/src/worldgen/cave.rs | 686 +++++++++++++++ .../src/worldgen/feature_catalog.rs | 9 + .../src/worldgen/feature_graph.rs | 92 ++ .../src/worldgen/feature_region.rs | 13 + crates/horizon-world/src/worldgen/iceberg.rs | 349 ++++++++ .../src/worldgen/placement/context.rs | 13 + .../horizon-world/src/worldgen/root_system.rs | 228 +++++ .../horizon-world/src/worldgen/tree_blocks.rs | 67 +- .../horizon-world/src/worldgen/vegetation.rs | 832 ++++++++++++++++++ 10 files changed, 2292 insertions(+), 1 deletion(-) create mode 100644 crates/horizon-world/src/worldgen/cave.rs create mode 100644 crates/horizon-world/src/worldgen/iceberg.rs create mode 100644 crates/horizon-world/src/worldgen/root_system.rs create mode 100644 crates/horizon-world/src/worldgen/vegetation.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index b8e259b0b..257e38b8b 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -19,6 +19,7 @@ pub mod bonus_chest; pub mod bulk_section; pub mod carver; pub mod carving; +pub mod cave; pub mod chorus_plant; pub mod climate; pub mod decoration; @@ -34,6 +35,7 @@ pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; pub mod height_provider; +pub mod iceberg; pub mod material_condition; pub mod material_extensions; pub mod material_stage; @@ -41,6 +43,7 @@ pub mod material_surface; pub mod ore_feature; pub mod placement; pub mod replace_blobs; +pub mod root_system; pub mod router; pub mod rule_test; pub mod settings; @@ -56,6 +59,7 @@ pub(crate) mod tree_blocks; pub mod terrain; pub mod underwater_magma; pub mod value_provider; +pub mod vegetation; pub mod vines; pub mod weighted; pub mod write_zone; diff --git a/crates/horizon-world/src/worldgen/cave.rs b/crates/horizon-world/src/worldgen/cave.rs new file mode 100644 index 000000000..baa0f350e --- /dev/null +++ b/crates/horizon-world/src/worldgen/cave.rs @@ -0,0 +1,686 @@ +//! Underground structures expressed as features: lakes, monster rooms +//! (dungeons) and geodes. +use super::{ + DecodeError, Object, double_range, int_range, optional, + block_feature::FeatureBlockBindings, + block_predicate::BlockPredicate, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + state_provider::BlockStateProvider, + tree::{TreeDecoder, TreeResult, kind, read, sample_state, write}, + tree_blocks::{self as tb, TreeBlocks}, + value_provider::IntProvider, +}; +use crate::registry::BlockStateId; +use horizon_core::{ + geometry::Direction, + noise::{Noise, NormalNoise}, + random::{LegacyRandom, RandomSource}, +}; +use std::{collections::BTreeSet, sync::Arc}; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} +fn state(blocks: &TreeBlocks, name: &str) -> TreeResult { + blocks + .default_state(name) + .ok_or(FeatureExecutionError::InvalidState) +} +/// Feature.safeSetBlock. +fn safe_set( + world: &mut W, + p: [i32; 3], + value: BlockStateId, + cannot_replace: impl Fn(BlockStateId) -> bool, +) -> TreeResult<(), W::Error> { + if !cannot_replace(read(world, p)?) { + write(world, p, value, 2)?; + } + Ok(()) +} +/// Feature.markAboveForPostProcessing. +fn mark_above( + world: &mut W, + blocks: &TreeBlocks, + p: [i32; 3], +) -> TreeResult<(), W::Error> { + let mut above = p; + for _ in 0..2 { + above = tb::offset(above, 0, 1, 0); + if blocks.is_air(read(world, above)?) { + return Ok(()); + } + world.mark_postprocessing(above).map_err(query)?; + } + Ok(()) +} + +#[derive(Clone, Debug)] +pub struct LakeFeature { + fluid: BlockStateProvider, + barrier: BlockStateProvider, + can_place: BlockPredicate, + can_replace_air_or_fluid: BlockPredicate, + can_replace_barrier: BlockPredicate, + blocks: Arc, +} +impl LakeFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:lake" { + return Err(DecodeError::Field("lake type")); + } + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let fluid = decoder.provider(required(&object, "fluid")?)?; + let barrier = decoder.provider(required(&object, "barrier")?)?; + let mut predicate = |name: &'static str| { + BlockPredicate::decode_with_blocks( + required(&object, name)?.get(), + depth + 1, + decoder.remaining, + Some(bindings), + ) + }; + Ok(Self { + fluid, + barrier, + can_place: predicate("can_place_feature")?, + can_replace_air_or_fluid: predicate("can_replace_with_air_or_fluid")?, + can_replace_barrier: predicate("can_replace_with_barrier")?, + blocks, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + if origin[1] <= world.min_y().map_err(query)?.wrapping_add(4) { + return Ok(false); + } + let origin = tb::offset(origin, -8, -4, -8); + let mut grid = [false; 2048]; + let spots = random.next_int_bound(4)? + 4; + for _ in 0..spots { + let xr = random.next_double() * 6.0 + 3.0; + let yr = random.next_double() * 4.0 + 2.0; + let zr = random.next_double() * 6.0 + 3.0; + let xp = random.next_double() * (16.0 - xr - 2.0) + 1.0 + xr / 2.0; + let yp = random.next_double() * (8.0 - yr - 4.0) + 2.0 + yr / 2.0; + let zp = random.next_double() * (16.0 - zr - 2.0) + 1.0 + zr / 2.0; + for xx in 1..15 { + for zz in 1..15 { + for yy in 1..7 { + let xd = (f64::from(xx) - xp) / (xr / 2.0); + let yd = (f64::from(yy) - yp) / (yr / 2.0); + let zd = (f64::from(zz) - zp) / (zr / 2.0); + if xd * xd + yd * yd + zd * zd < 1.0 { + grid[((xx * 16 + zz) * 8 + yy) as usize] = true; + } + } + } + } + } + let at = |x: i32, y: i32, z: i32| grid[((x * 16 + z) * 8 + y) as usize]; + let edge = |x: i32, y: i32, z: i32| { + !at(x, y, z) + && ((x < 15 && at(x + 1, y, z)) + || (x > 0 && at(x - 1, y, z)) + || (z < 15 && at(x, y, z + 1)) + || (z > 0 && at(x, y, z - 1)) + || (y < 7 && at(x, y + 1, z)) + || (y > 0 && at(x, y - 1, z))) + }; + let fluid = sample_state(&self.fluid, world, random, origin)?; + for xx in 0..16 { + for zz in 0..16 { + for yy in 0..8 { + if edge(xx, yy, zz) { + let p = tb::offset(origin, xx, yy, zz); + let state = read(world, p)?; + if yy >= 4 && self.blocks.has(state, tb::LIQUID) { + return Ok(false); + } + if yy < 4 && !self.blocks.has(state, tb::SOLID) && state != fluid { + return Ok(false); + } + if !self.can_place.test(world, p).map_err(query)? { + return Ok(false); + } + } + } + } + } + let cave_air = state(&self.blocks, "minecraft:cave_air")?; + for xx in 0..16 { + for zz in 0..16 { + for yy in 0..8 { + if at(xx, yy, zz) { + let p = tb::offset(origin, xx, yy, zz); + if self.can_replace_air_or_fluid.test(world, p).map_err(query)? { + let air = yy >= 4; + write(world, p, if air { cave_air } else { fluid }, 2)?; + if air { + world.schedule_block_tick(p, cave_air, 0).map_err(query)?; + mark_above(world, &self.blocks, p)?; + } + } + } + } + } + } + let barrier = sample_state(&self.barrier, world, random, origin)?; + if !self.blocks.is_air(barrier) { + for xx in 0..16 { + for zz in 0..16 { + for yy in 0..8 { + if edge(xx, yy, zz) && (yy < 4 || random.next_int_bound(2)? != 0) { + let p = tb::offset(origin, xx, yy, zz); + let state = read(world, p)?; + if self.blocks.has(state, tb::SOLID) + && self.can_replace_barrier.test(world, p).map_err(query)? + { + write(world, p, barrier, 2)?; + mark_above(world, &self.blocks, p)?; + } + } + } + } + } + } + if self.blocks.has(fluid, tb::WATER_FLUID) { + let ice = state(&self.blocks, "minecraft:ice")?; + for xx in 0..16 { + for zz in 0..16 { + let p = tb::offset(origin, xx, 4, zz); + let biome = world.biome_identity(p).map_err(query)?; + if world.biome_should_freeze(biome, p, false).map_err(query)? + && self.can_replace_air_or_fluid.test(world, p).map_err(query)? + { + write(world, p, ice, 2)?; + } + } + } + } + Ok(true) + } +} + +const DUNGEON_MOBS: [&str; 4] = [ + "minecraft:skeleton", + "minecraft:zombie", + "minecraft:zombie", + "minecraft:spider", +]; +#[derive(Clone, Debug)] +pub struct MonsterRoomFeature { + blocks: Arc, +} +impl MonsterRoomFeature { + pub(crate) fn new(bindings: &FeatureBlockBindings<'_>) -> Result { + Ok(Self { + blocks: bindings.tree_blocks()?, + }) + } + fn solid(&self, world: &mut W, p: [i32; 3]) -> TreeResult { + Ok(self.blocks.has(read(world, p)?, tb::SOLID)) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let blocks = &*self.blocks; + let cannot = |s: BlockStateId| blocks.has(s, tb::FEATURES_CANNOT_REPLACE); + let xr = random.next_int_bound(2)? + 2; + let (min_x, max_x) = (-xr - 1, xr + 1); + let zr = random.next_int_bound(2)? + 2; + let (min_z, max_z) = (-zr - 1, zr + 1); + let mut holes = 0; + for dx in min_x..=max_x { + for dy in -1..=4 { + for dz in min_z..=max_z { + let p = tb::offset(origin, dx, dy, dz); + let solid = self.solid(world, p)?; + if (dy == -1 || dy == 4) && !solid { + return Ok(false); + } + if (dx == min_x || dx == max_x || dz == min_z || dz == max_z) + && dy == 0 + && blocks.is_air(read(world, p)?) + && blocks.is_air(read(world, tb::offset(p, 0, 1, 0))?) + { + holes += 1; + } + } + } + } + if !(1..=5).contains(&holes) { + return Ok(false); + } + let cave_air = state(blocks, "minecraft:cave_air")?; + let cobble = state(blocks, "minecraft:cobblestone")?; + let mossy = state(blocks, "minecraft:mossy_cobblestone")?; + let min_y = world.min_y().map_err(query)?; + for dx in min_x..=max_x { + for dy in (-1..=3).rev() { + for dz in min_z..=max_z { + let p = tb::offset(origin, dx, dy, dz); + let wall = read(world, p)?; + if dx == min_x || dy == -1 || dz == min_z || dx == max_x || dy == 4 || dz == max_z + { + if p[1] >= min_y && !self.solid(world, tb::offset(p, 0, -1, 0))? { + write(world, p, cave_air, 2)?; + } else if blocks.has(wall, tb::SOLID) && !blocks.has(wall, tb::CHEST) { + let value = if dy == -1 && random.next_int_bound(4)? != 0 { + mossy + } else { + cobble + }; + safe_set(world, p, value, cannot)?; + } + } else if !blocks.has(wall, tb::CHEST | tb::SPAWNER) { + safe_set(world, p, cave_air, cannot)?; + } + } + } + } + let chest = state(blocks, "minecraft:chest")?; + for _ in 0..2 { + for _ in 0..3 { + let x = origin[0] + .wrapping_add(random.next_int_bound(xr * 2 + 1)?) + .wrapping_sub(xr); + let z = origin[2] + .wrapping_add(random.next_int_bound(zr * 2 + 1)?) + .wrapping_sub(zr); + let p = [x, origin[1], z]; + if !blocks.is_air(read(world, p)?) { + continue; + } + let mut walls = 0; + for direction in tb::HORIZONTAL { + if self.solid(world, tb::relative(p, direction, 1))? { + walls += 1; + } + } + if walls == 1 { + let oriented = self.reorient(world, p, chest)?; + safe_set(world, p, oriented, cannot)?; + world + .set_block_entity_loot_table(p, "minecraft:chests/simple_dungeon", random) + .map_err(query)?; + break; + } + } + } + let spawner = state(blocks, "minecraft:spawner")?; + safe_set(world, origin, spawner, cannot)?; + if read(world, origin)? == spawner { + let mob = DUNGEON_MOBS[random.next_int_bound(4)? as usize]; + world.configure_spawner(origin, mob).map_err(query)?; + } + Ok(true) + } + /// StructurePiece.reorient for the chest's horizontal facing. + fn reorient( + &self, + world: &mut W, + p: [i32; 3], + chest: BlockStateId, + ) -> TreeResult { + let blocks = &*self.blocks; + let mut solid_neighbor = None; + for direction in tb::HORIZONTAL { + let state = read(world, tb::relative(p, direction, 1))?; + if blocks.has(state, tb::CHEST) { + return Ok(chest); + } + if blocks.has(state, tb::SOLID_RENDER) { + if solid_neighbor.is_some() { + solid_neighbor = None; + break; + } + solid_neighbor = Some(direction); + } + } + let facing = |d: Direction| { + blocks + .with(chest, "facing", tb::direction_name(d)) + .ok_or(FeatureExecutionError::InvalidState) + }; + if let Some(direction) = solid_neighbor { + return facing(direction.opposite()); + } + let mut lock = blocks + .properties + .value(chest, "facing") + .and_then(|v| tb::decode_direction(v).ok()) + .ok_or(FeatureExecutionError::InvalidState)?; + let mut rel = tb::relative(p, lock, 1); + if blocks.has(read(world, rel)?, tb::SOLID_RENDER) { + lock = lock.opposite(); + rel = tb::relative(p, lock, 1); + } + if blocks.has(read(world, rel)?, tb::SOLID_RENDER) { + lock = tb::clockwise(lock); + rel = tb::relative(p, lock, 1); + } + if blocks.has(read(world, rel)?, tb::SOLID_RENDER) { + lock = lock.opposite(); + } + facing(lock) + } +} + +#[derive(Clone, Debug)] +pub struct GeodeFeature { + filling: BlockStateProvider, + inner: BlockStateProvider, + alternate_inner: BlockStateProvider, + middle: BlockStateProvider, + outer: BlockStateProvider, + inner_placements: Vec, + cannot_replace: Arc>, + invalid_blocks: Arc>, + layers: [f64; 4], + crack_chance: f64, + base_crack_size: f64, + crack_point_offset: i32, + potential_chance: f64, + alternate_chance: f64, + require_alternate: bool, + outer_wall_distance: IntProvider, + distribution_points: IntProvider, + point_offset: IntProvider, + min_gen_offset: i32, + max_gen_offset: i32, + noise_multiplier: f64, + invalid_threshold: i32, + noise: NormalNoise, + blocks: Arc, +} +fn chance(object: &Object, name: &'static str, default: f64) -> Result { + optional(object, name) + .map(|raw| double_range(raw, name, 0.0, 1.0)) + .transpose() + .map(|v| v.unwrap_or(default)) +} +impl GeodeFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:geode" { + return Err(DecodeError::Field("geode type")); + } + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let settings: Object = serde_json::from_str(required(&object, "blocks")?.get())?; + let placements: Vec> = + serde_json::from_str(required(&settings, "inner_placements")?.get())?; + if placements.is_empty() || placements.len() > 8192 { + return Err(DecodeError::Field("geode inner placements")); + } + let inner_placements = placements + .iter() + .map(|raw| { + bindings + .codec + .decode(raw.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }) + .collect::>()?; + let layers: Object = serde_json::from_str(required(&object, "layers")?.get())?; + let layer = |name: &'static str, default: f64| { + optional(&layers, name) + .map(|raw| double_range(raw, name, 0.01, 50.0)) + .transpose() + .map(|v| v.unwrap_or(default)) + }; + let crack: Object = serde_json::from_str(required(&object, "crack")?.get())?; + let mut provider = |name: &'static str, default: [i32; 2], low: i32, high: i32| { + match optional(&object, name) { + Some(raw) => decoder.int_provider(raw, low, high), + None => Ok(IntProvider::Uniform { + min: default[0], + max: default[1], + }), + } + }; + let outer_wall_distance = provider("outer_wall_distance", [4, 5], 1, 20)?; + let distribution_points = provider("distribution_points", [3, 4], 1, 20)?; + let point_offset = provider("point_offset", [1, 2], 0, 10)?; + let int_or = |name: &'static str, default: i32| { + optional(&object, name) + .map(super::integer) + .transpose() + .map(|v| v.unwrap_or(default)) + }; + Ok(Self { + filling: decoder.provider(required(&settings, "filling_provider")?)?, + inner: decoder.provider(required(&settings, "inner_layer_provider")?)?, + alternate_inner: decoder + .provider(required(&settings, "alternate_inner_layer_provider")?)?, + middle: decoder.provider(required(&settings, "middle_layer_provider")?)?, + outer: decoder.provider(required(&settings, "outer_layer_provider")?)?, + inner_placements, + cannot_replace: decoder.block_set(required(&settings, "cannot_replace")?)?, + invalid_blocks: decoder.block_set(required(&settings, "invalid_blocks")?)?, + layers: [ + layer("filling", 1.7)?, + layer("inner_layer", 2.2)?, + layer("middle_layer", 3.2)?, + layer("outer_layer", 4.2)?, + ], + crack_chance: chance(&crack, "generate_crack_chance", 1.0)?, + base_crack_size: optional(&crack, "base_crack_size") + .map(|raw| double_range(raw, "base_crack_size", 0.0, 5.0)) + .transpose()? + .unwrap_or(2.0), + crack_point_offset: optional(&crack, "crack_point_offset") + .map(|raw| int_range(raw, "crack_point_offset", 0, 10)) + .transpose()? + .unwrap_or(2), + potential_chance: chance(&object, "use_potential_placements_chance", 0.35)?, + alternate_chance: chance(&object, "use_alternate_layer0_chance", 0.0)?, + require_alternate: optional(&object, "placements_require_layer0_alternate") + .map(|raw| serde_json::from_str::(raw.get())) + .transpose()? + .unwrap_or(true), + outer_wall_distance, + distribution_points, + point_offset, + min_gen_offset: int_or("min_gen_offset", -16)?, + max_gen_offset: int_or("max_gen_offset", 16)?, + noise_multiplier: chance(&object, "noise_multiplier", 0.05)?, + invalid_threshold: super::integer(required(&object, "invalid_blocks_threshold")?)?, + noise: NormalNoise::create_parity(-4, &[1.0])?, + blocks, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let blocks = &*self.blocks; + let cannot = |s: BlockStateId| self.cannot_replace.contains(&s); + let num_points = self.distribution_points.sample(random)?; + let seed = world.world_seed().map_err(query)?; + let noise = self + .noise + .create(&mut LegacyRandom::new(seed)) + .map_err(|_| FeatureExecutionError::InvalidState)?; + let crack_adjust = f64::from(num_points) / f64::from(self.outer_wall_distance.bounds()[1]); + let [filling, inner, middle, outer] = self.layers; + let inner_air = 1.0 / filling.sqrt(); + let innermost = 1.0 / (inner + crack_adjust).sqrt(); + let inner_crust = 1.0 / (middle + crack_adjust).sqrt(); + let outer_crust = 1.0 / (outer + crack_adjust).sqrt(); + let crack_size = 1.0 + / (self.base_crack_size + + random.next_double() / 2.0 + + if num_points > 3 { crack_adjust } else { 0.0 }) + .sqrt(); + let crack = f64::from(random.next_float()) < self.crack_chance; + let mut invalid = 0; + let mut points = Vec::new(); + for _ in 0..num_points { + let x = self.outer_wall_distance.sample(random)?; + let y = self.outer_wall_distance.sample(random)?; + let z = self.outer_wall_distance.sample(random)?; + let p = tb::offset(origin, x, y, z); + let state = read(world, p)?; + if blocks.is_air(state) || self.invalid_blocks.contains(&state) { + invalid += 1; + if invalid > self.invalid_threshold { + return Ok(false); + } + } + points.push((p, self.point_offset.sample(random)?)); + } + let mut crack_points = Vec::new(); + if crack { + let index = random.next_int_bound(4)?; + let o = num_points * 2 + 1; + let (cx, cz) = match index { + 0 => (o, 0), + 1 => (0, o), + 2 => (o, o), + _ => (0, 0), + }; + for y in [7, 5, 1] { + crack_points.push(tb::offset(origin, cx, y, cz)); + } + } + let dist_sqr = |a: [i32; 3], b: [i32; 3]| -> f64 { + (0..3) + .map(|i| { + let d = f64::from(a[i]) - f64::from(b[i]); + d * d + }) + .sum() + }; + let mut potential = Vec::new(); + let air_state = blocks + .default_state("minecraft:air") + .ok_or(FeatureExecutionError::InvalidState)?; + let (lo, hi) = (self.min_gen_offset, self.max_gen_offset); + // BlockPos.betweenClosed iterates x fastest, then y, then z. + for dz in lo..=hi { + for dy in lo..=hi { + for dx in lo..=hi { + let p = tb::offset(origin, dx, dy, dz); + let noise_offset = f64::from(noise.get3( + f64::from(p[0]), + f64::from(p[1]), + f64::from(p[2]), + )) * self.noise_multiplier; + let mut shell = 0.0; + for (point, offset) in &points { + shell += 1.0 / (dist_sqr(p, *point) + f64::from(*offset)).sqrt() + + noise_offset; + } + if shell < outer_crust { + continue; + } + if shell >= inner_air { + let value = sample_state(&self.filling, world, random, p)?; + safe_set(world, p, value, cannot)?; + continue; + } + let mut crack_sum = 0.0; + for point in &crack_points { + crack_sum += 1.0 + / (dist_sqr(p, *point) + f64::from(self.crack_point_offset)).sqrt() + + noise_offset; + } + if crack && crack_sum >= crack_size { + safe_set(world, p, air_state, cannot)?; + for direction in Direction::ALL { + let q = tb::relative(p, direction, 1); + let fluid = world.fluid_state(q).map_err(query)?; + if fluid.kind() != crate::fluid::FluidKind::Empty { + world + .schedule_fluid_tick(q, fluid.kind(), 0) + .map_err(query)?; + } + } + } else if shell >= innermost { + let alternate = f64::from(random.next_float()) < self.alternate_chance; + let provider = if alternate { + &self.alternate_inner + } else { + &self.inner + }; + let value = sample_state(provider, world, random, p)?; + safe_set(world, p, value, cannot)?; + if (!self.require_alternate || alternate) + && f64::from(random.next_float()) < self.potential_chance + { + potential.push(p); + } + } else if shell >= inner_crust { + let value = sample_state(&self.middle, world, random, p)?; + safe_set(world, p, value, cannot)?; + } else if shell >= outer_crust { + let value = sample_state(&self.outer, world, random, p)?; + safe_set(world, p, value, cannot)?; + } + } + } + } + for crystal in potential { + let index = random.next_int_bound(self.inner_placements.len() as i32)? as usize; + let mut state = self.inner_placements[index]; + for direction in Direction::ALL { + if blocks + .properties + .values(state, "facing") + .is_some_and(|v| v.len() == 6) + { + state = blocks + .with(state, "facing", tb::direction_name(direction)) + .ok_or(FeatureExecutionError::InvalidState)?; + } + let target = tb::relative(crystal, direction, 1); + let existing = read(world, target)?; + if blocks.has(state, tb::WATERLOGGABLE) { + state = blocks.waterlogged(state, blocks.has(existing, tb::FLUID_SOURCE)); + } + // BuddingAmethystBlock.canClusterGrowAtState. + if blocks.is_air(existing) + || (blocks.has(existing, tb::WATER_BLOCK) && blocks.has(existing, tb::FLUID_FULL)) + { + safe_set(world, target, state, cannot)?; + break; + } + } + } + Ok(true) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_catalog.rs b/crates/horizon-world/src/worldgen/feature_catalog.rs index 1aff708a0..d9a142d96 100644 --- a/crates/horizon-world/src/worldgen/feature_catalog.rs +++ b/crates/horizon-world/src/worldgen/feature_catalog.rs @@ -234,6 +234,15 @@ impl FeatureCatalog { object.insert("cap_feature".into(), raw(expanded)?); } } + "minecraft:vegetation_patch" | "minecraft:waterlogged_vegetation_patch" => { + let expanded = + self.expand_placed(required(&object, "vegetation_feature")?, depth + 1, work)?; + object.insert("vegetation_feature".into(), raw(expanded)?); + } + "minecraft:coral_tree" | "minecraft:coral_claw" | "minecraft:root_system" => { + let expanded = self.expand_placed(required(&object, "feature")?, depth + 1, work)?; + object.insert("feature".into(), raw(expanded)?); + } "minecraft:tree" => { // PaleMossDecorator places the registry's pale_moss_patch by key. let pale_moss = super::optional(&object, "decorators") diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 27b7f2abd..340f6bcef 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -68,6 +68,15 @@ pub enum FeatureDefinition { ScatteredOre(ScatteredOreFeature), Ore(super::ore_feature::OreFeature), Tree(Box), + VegetationPatch(Box), + Coral(Box), + HugeMushroom(Box), + MultifaceGrowth(Box), + Lake(Box), + MonsterRoom(Box), + Geode(Box), + Iceberg(Box), + RootSystem(Box), FallenTree(Box), NoOp, WeightedChoice(OptionalWeightedList), @@ -549,6 +558,70 @@ impl FeatureDefinition { remaining, ) .map(Self::ScatteredOre), + "minecraft:vegetation_patch" | "minecraft:waterlogged_vegetation_patch" => { + let bindings = blocks.ok_or(DecodeError::Field("vegetation patch bindings"))?; + let nested = |json: &str, depth: usize, remaining: &mut usize| { + PlacedFeatureDefinition::decode(json, depth, remaining, empty_tags, blocks) + }; + super::vegetation::VegetationPatchFeature::decode( + json, bindings, depth, remaining, &nested, + ) + .map(|f| Self::VegetationPatch(Box::new(f))) + } + "minecraft:root_system" => { + let bindings = blocks.ok_or(DecodeError::Field("root system bindings"))?; + let nested = |json: &str, depth: usize, remaining: &mut usize| { + PlacedFeatureDefinition::decode(json, depth, remaining, empty_tags, blocks) + }; + super::root_system::RootSystemFeature::decode( + json, bindings, depth, remaining, &nested, + ) + .map(|f| Self::RootSystem(Box::new(f))) + } + "minecraft:coral_tree" | "minecraft:coral_claw" => { + let nested = |json: &str, depth: usize, remaining: &mut usize| { + PlacedFeatureDefinition::decode(json, depth, remaining, empty_tags, blocks) + }; + super::vegetation::CoralFeature::decode(json, depth, remaining, &nested) + .map(|f| Self::Coral(Box::new(f))) + } + "minecraft:huge_red_mushroom" | "minecraft:huge_brown_mushroom" => { + super::vegetation::HugeMushroomFeature::decode( + json, + blocks.ok_or(DecodeError::Field("huge mushroom bindings"))?, + depth, + remaining, + ) + .map(|f| Self::HugeMushroom(Box::new(f))) + } + "minecraft:lake" => super::cave::LakeFeature::decode( + json, + blocks.ok_or(DecodeError::Field("lake bindings"))?, + depth, + remaining, + ) + .map(|f| Self::Lake(Box::new(f))), + "minecraft:monster_room" => super::cave::MonsterRoomFeature::new( + blocks.ok_or(DecodeError::Field("monster room bindings"))?, + ) + .map(|f| Self::MonsterRoom(Box::new(f))), + "minecraft:geode" => super::cave::GeodeFeature::decode( + json, + blocks.ok_or(DecodeError::Field("geode bindings"))?, + depth, + remaining, + ) + .map(|f| Self::Geode(Box::new(f))), + "minecraft:iceberg" => super::iceberg::IcebergFeature::decode( + json, + blocks.ok_or(DecodeError::Field("iceberg bindings"))?, + ) + .map(|f| Self::Iceberg(Box::new(f))), + "minecraft:multiface_growth" => super::vegetation::MultifaceGrowthFeature::decode( + json, + blocks.ok_or(DecodeError::Field("multiface bindings"))?, + ) + .map(|f| Self::MultifaceGrowth(Box::new(f))), "minecraft:tree" | "minecraft:fallen_tree" => { let bindings = blocks.ok_or(DecodeError::Field("tree bindings"))?; let nested = |json: &str, depth: usize, remaining: &mut usize| { @@ -877,6 +950,25 @@ impl FeatureDefinition { .place(world, random, origin) .map_err(FeatureExecutionError::Basic), Self::Ore(feature) => feature.place(world, random, origin), + Self::VegetationPatch(feature) => { + feature.place(world, random, origin, &mut |f, w, r, p| { + f.place_in(&mut placer, w, r, p, run) + }) + } + Self::Coral(feature) => feature.place(world, random, origin, &mut |f, w, r, p| { + f.place_in(&mut placer, w, r, p, run) + }), + Self::HugeMushroom(feature) => feature.place(world, random, origin), + Self::MultifaceGrowth(feature) => feature.place(world, random, origin), + Self::Lake(feature) => feature.place(world, random, origin), + Self::MonsterRoom(feature) => feature.place(world, random, origin), + Self::Geode(feature) => feature.place(world, random, origin), + Self::Iceberg(feature) => feature.place(world, random, origin), + Self::RootSystem(feature) => { + feature.place(world, random, origin, &mut |f, w, r, p| { + f.place_in(&mut placer, w, r, p, run) + }) + } Self::Tree(feature) => { feature.place(world, random, origin, &mut |f, w, r, p| { f.place_inner(w, r, p, run) diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index f3b4f9f49..014076ec1 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -66,6 +66,7 @@ pub struct TerrainRegion<'r, B: TerrainBlockStates> { game_time: i64, next_tick_order: i64, block_queries: Option, + world_seed: Option, } impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn new( @@ -95,6 +96,7 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { game_time: 0, next_tick_order: 0, block_queries: None, + world_seed: None, min_y, height, generation: WorldGenerationContext::with_generator( @@ -124,6 +126,11 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { }); Ok(self) } + /// Supply the world seed (WorldGenLevel.getSeed) for seed-derived features. + pub fn with_world_seed(mut self, seed: i64) -> Self { + self.world_seed = Some(seed); + self + } /// Supply the owning world's current time and region-local next tick order. pub fn with_tick_clock(mut self, game_time: i64, next_tick_order: i64) -> Self { self.game_time = game_time; @@ -320,6 +327,9 @@ impl PlacementContext for TerrainRegion<'_, B> { fn sea_level(&mut self) -> Result { Ok(self.sea_level) } + fn world_seed(&mut self) -> Result { + self.world_seed.ok_or(PlacementQueryError::Unavailable) + } fn mark_postprocessing(&mut self, [x, y, z]: [i32; 3]) -> Result<(), PlacementQueryError> { self.chunk_mut(x >> 4, z >> 4)?.mark_postprocessing(x, y, z); @@ -538,6 +548,9 @@ where fn sea_level(&mut self) -> Result { self.region.sea_level() } + fn world_seed(&mut self) -> Result { + self.region.world_seed() + } fn mark_postprocessing(&mut self, position: [i32; 3]) -> Result<(), PlacementQueryError> { self.region.mark_postprocessing(position) diff --git a/crates/horizon-world/src/worldgen/iceberg.rs b/crates/horizon-world/src/worldgen/iceberg.rs new file mode 100644 index 000000000..e7daa12aa --- /dev/null +++ b/crates/horizon-world/src/worldgen/iceberg.rs @@ -0,0 +1,349 @@ +//! Vanilla `minecraft:iceberg`, with native float/double rounding and the +//! short-circuited random draws of IcebergFeature. +use super::{ + DecodeError, Object, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + placement::PlacementContext, + required, + tree::{TreeResult, kind, read, write}, + tree_blocks::{self as tb, TreeBlocks}, +}; +use crate::registry::BlockStateId; +use horizon_core::random::RandomSource; +use std::sync::Arc; + +#[derive(Clone, Debug)] +pub struct IcebergFeature { + state: BlockStateId, + blocks: Arc, + air: BlockStateId, + water: BlockStateId, + snow_block: BlockStateId, + ice: BlockStateId, + packed_ice: BlockStateId, + blue_ice: BlockStateId, + snow: BlockStateId, +} +fn ceil(v: f32) -> i32 { + f64::from(v).ceil() as i32 +} +fn pow2(v: i32) -> f64 { + f64::from(v).powf(2.0) +} +impl IcebergFeature { + pub(crate) fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:iceberg" { + return Err(DecodeError::Field("iceberg type")); + } + let state = bindings + .codec + .decode(required(&object, "state")?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string()))?; + let registry = bindings.registry(); + let get = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("missing iceberg block {name}"))) + }; + Ok(Self { + state, + blocks: bindings.tree_blocks()?, + air: get("minecraft:air")?, + water: get("minecraft:water")?, + snow_block: get("minecraft:snow_block")?, + ice: get("minecraft:ice")?, + packed_ice: get("minecraft:packed_ice")?, + blue_ice: get("minecraft:blue_ice")?, + snow: get("minecraft:snow")?, + }) + } + fn is(&self, a: BlockStateId, b: BlockStateId) -> bool { + self.blocks.same_block(a, b) + } + fn iceberg_state(&self, s: BlockStateId) -> bool { + self.is(s, self.packed_ice) || self.is(s, self.snow_block) || self.is(s, self.blue_ice) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let origin = [origin[0], world.generation().sea_level, origin[2]]; + let snow_on_top = random.next_double() > 0.7; + let angle = random.next_double() * 2.0 * std::f64::consts::PI; + let ellipse_a = 11 - random.next_int_bound(5)?; + let ellipse_c = 3 + random.next_int_bound(3)?; + let is_ellipse = random.next_double() > 0.7; + let mut over = if is_ellipse { + random.next_int_bound(6)? + 6 + } else { + random.next_int_bound(15)? + 3 + }; + if !is_ellipse && random.next_double() > 0.9 { + over += random.next_int_bound(19)? + 7; + } + let under = (over + random.next_int_bound(11)?).min(18); + let width = (over + random.next_int_bound(7)? - random.next_int_bound(5)?).min(11); + let a = if is_ellipse { ellipse_a } else { 11 }; + for xo in -a..a { + for zo in -a..a { + for y in 0..over { + let radius = if is_ellipse { + let scale = (1.0f32 - pow2(y) as f32 / (over as f32 * 1.0f32)) * width as f32; + ceil(scale / 2.0) + } else { + self.radius_round(random, y, over, width)? + }; + if is_ellipse || xo < radius { + self.generate_block( + world, random, origin, over, xo, y, zo, radius, a, is_ellipse, ellipse_c, + angle, snow_on_top, + )?; + } + } + } + } + self.smooth(world, origin, width, over, is_ellipse, ellipse_a)?; + for xo in -a..a { + for zo in -a..a { + let mut y = -1; + while y > -under { + let new_a = if is_ellipse { + ceil(a as f32 * (1.0f32 - pow2(y) as f32 / (under as f32 * 8.0f32))) + } else { + a + }; + let radius = self.radius_steep(random, -y, under, width)?; + if xo < radius { + self.generate_block( + world, random, origin, under, xo, y, zo, radius, new_a, is_ellipse, + ellipse_c, angle, snow_on_top, + )?; + } + y -= 1; + } + } + } + let cut_out = if is_ellipse { + random.next_double() > 0.1 + } else { + random.next_double() > 0.7 + }; + if cut_out { + self.cut_out(world, random, width, over, origin, is_ellipse, ellipse_a, angle, ellipse_c)?; + } + Ok(true) + } + #[allow(clippy::too_many_arguments)] + fn cut_out( + &self, + world: &mut W, + random: &mut R, + width: i32, + height: i32, + origin: [i32; 3], + is_ellipse: bool, + ellipse_a: i32, + angle: f64, + ellipse_c: i32, + ) -> TreeResult<(), W::Error> { + let sign_x = if random.next_boolean() { -1 } else { 1 }; + let sign_z = if random.next_boolean() { -1 } else { 1 }; + let mut x_off = random.next_int_bound((width / 2 - 2).max(1))?; + if random.next_boolean() { + x_off = width / 2 + 1 - random.next_int_bound((width - width / 2 - 1).max(1))?; + } + let mut z_off = random.next_int_bound((width / 2 - 2).max(1))?; + if random.next_boolean() { + z_off = width / 2 + 1 - random.next_int_bound((width - width / 2 - 1).max(1))?; + } + if is_ellipse { + x_off = random.next_int_bound((ellipse_a - 5).max(1))?; + z_off = x_off; + } + let local = [sign_x * x_off, 0, sign_z * z_off]; + let angle = if is_ellipse { + angle + std::f64::consts::FRAC_PI_2 + } else { + random.next_double() * 2.0 * std::f64::consts::PI + }; + for y in 0..height - 3 { + let radius = self.radius_round(random, y, height, width)?; + self.carve(world, radius, y, origin, false, angle, local, ellipse_a, ellipse_c)?; + } + let mut y = -1; + while y > -height + random.next_int_bound(5)? { + let radius = self.radius_steep(random, -y, height, width)?; + self.carve(world, radius, y, origin, true, angle, local, ellipse_a, ellipse_c)?; + y -= 1; + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn carve( + &self, + world: &mut W, + radius: i32, + y: i32, + origin: [i32; 3], + under_water: bool, + angle: f64, + local: [i32; 3], + ellipse_a: i32, + ellipse_c: i32, + ) -> TreeResult<(), W::Error> { + let a = radius + 1 + ellipse_a / 3; + let c = (radius - 3).min(3) + ellipse_c / 2 - 1; + for xo in -a..a { + for zo in -a..a { + if signed_ellipse(xo, zo, local, a, c, angle) < 0.0 { + let p = tb::offset(origin, xo, y, zo); + let state = read(world, p)?; + if self.iceberg_state(state) || self.is(state, self.snow_block) { + if under_water { + write(world, p, self.water, 3)?; + } else { + write(world, p, self.air, 3)?; + let above = tb::offset(p, 0, 1, 0); + if self.is(read(world, above)?, self.snow) { + write(world, above, self.air, 3)?; + } + } + } + } + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn generate_block( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + height: i32, + xo: i32, + y: i32, + zo: i32, + radius: i32, + a: i32, + is_ellipse: bool, + ellipse_c: i32, + angle: f64, + snow_on_top: bool, + ) -> TreeResult<(), W::Error> { + let signed = if is_ellipse { + let mut c = ellipse_c; + if y > 0 && height - y <= 3 { + c -= 4 - (height - y); + } + signed_ellipse(xo, zo, [0; 3], a, c, angle) + } else { + let off = 10.0f32 * random.next_float().clamp(0.2, 0.8) / radius as f32; + f64::from(off) + pow2(xo) + pow2(zo) - pow2(radius) + }; + if signed >= 0.0 { + return Ok(()); + } + let p = tb::offset(origin, xo, y, zo); + let compare = if is_ellipse { + -0.5 + } else { + f64::from(-6 - random.next_int_bound(3)?) + }; + if signed > compare && random.next_double() > 0.9 { + return Ok(()); + } + let h_diff = height - y; + let state = read(world, p)?; + if self.blocks.is_air(state) + || self.is(state, self.snow_block) + || self.is(state, self.ice) + || self.is(state, self.water) + { + let randomness = !is_ellipse || random.next_double() > 0.05; + let divisor = if is_ellipse { 3 } else { 2 }; + let snow = snow_on_top + && !self.is(state, self.water) + && f64::from(h_diff) + <= f64::from(random.next_int_bound((height / divisor).max(1))?) + + f64::from(height) * 0.6 + && randomness; + write(world, p, if snow { self.snow_block } else { self.state }, 3)?; + } + Ok(()) + } + fn radius_round( + &self, + random: &mut R, + y: i32, + height: i32, + width: i32, + ) -> TreeResult { + let k = 3.5f32 - random.next_float(); + let mut scale = (1.0f32 - pow2(y) as f32 / (height as f32 * k)) * width as f32; + if height > 15 + random.next_int_bound(5)? { + let temp = if y < 3 + random.next_int_bound(6)? { y / 2 } else { y }; + scale = (1.0f32 - temp as f32 / (height as f32 * k * 0.4f32)) * width as f32; + } + Ok(ceil(scale / 2.0)) + } + fn radius_steep( + &self, + random: &mut R, + y: i32, + height: i32, + width: i32, + ) -> TreeResult { + let k = 1.0f32 + random.next_float() / 2.0; + let scale = (1.0f32 - y as f32 / (height as f32 * k)) * width as f32; + Ok(ceil(scale / 2.0)) + } + fn smooth( + &self, + world: &mut W, + origin: [i32; 3], + width: i32, + height: i32, + is_ellipse: bool, + ellipse_a: i32, + ) -> TreeResult<(), W::Error> { + let a = if is_ellipse { ellipse_a } else { width / 2 }; + for x in -a..=a { + for z in -a..=a { + for y in 0..=height { + let p = tb::offset(origin, x, y, z); + let state = read(world, p)?; + if !(self.iceberg_state(state) || self.is(state, self.snow)) { + continue; + } + if self.blocks.is_air(read(world, tb::offset(p, 0, -1, 0))?) { + write(world, p, self.air, 3)?; + write(world, tb::offset(p, 0, 1, 0), self.air, 3)?; + } else if self.iceberg_state(state) { + let mut counter = 0; + for (dx, dz) in [(-1, 0), (1, 0), (0, -1), (0, 1)] { + if !self.iceberg_state(read(world, tb::offset(p, dx, 0, dz))?) { + counter += 1; + } + } + if counter >= 3 { + write(world, p, self.air, 3)?; + } + } + } + } + } + Ok(()) + } +} +fn signed_ellipse(xo: i32, zo: i32, origin: [i32; 3], a: i32, c: i32, angle: f64) -> f64 { + let dx = f64::from(xo - origin[0]); + let dz = f64::from(zo - origin[2]); + ((dx * angle.cos() - dz * angle.sin()) / f64::from(a)).powf(2.0) + + ((dx * angle.sin() + dz * angle.cos()) / f64::from(c)).powf(2.0) + - 1.0 +} diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index f65e90ebe..ef2522b1c 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -61,6 +61,19 @@ pub trait PlacementContext { ) -> Result<(), PlacementQueryError> { Err(PlacementQueryError::Unavailable) } + /// WorldGenLevel.getSeed: the world seed for seed-derived feature noise. + fn world_seed(&mut self) -> Result { + Err(PlacementQueryError::Unavailable) + } + /// Set the entity type of the spawner block entity at `position`, when one + /// exists. The caller has already drawn the native entity choice. + fn configure_spawner( + &mut self, + _position: [i32; 3], + _entity: &str, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } /// Store worldgen beehive occupants (ticks in hive per bee) in the nest /// block entity at `position`. Worlds without block-entity storage drop them. fn store_beehive_occupants( diff --git a/crates/horizon-world/src/worldgen/root_system.rs b/crates/horizon-world/src/worldgen/root_system.rs new file mode 100644 index 000000000..e55de0746 --- /dev/null +++ b/crates/horizon-world/src/worldgen/root_system.rs @@ -0,0 +1,228 @@ +//! `minecraft:root_system`: a nested tree on a rooted-dirt column with +//! hanging roots below. +use super::{ + DecodeError, Object, int_range, + block_feature::FeatureBlockBindings, + block_predicate::BlockPredicate, + feature::FeatureWorld, + feature_graph::{FeatureExecutionError, PlacedFeatureDefinition}, + placement::{PlacementContext, PlacementQueryError}, + required, + state_provider::BlockStateProvider, + tree::{TreeDecoder, TreeResult, kind, read, sample_state, write}, + tree_blocks::{self as tb, TreeBlocks}, + vegetation::{PlacedDecoder, PlacedPlacer}, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, random::RandomSource}; +use std::{collections::BTreeSet, sync::Arc}; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} + +#[derive(Clone, Debug)] +pub struct RootSystemFeature { + tree: Box, + required_vertical_space: i32, + level_test_distance: i32, + max_level_deviation: i32, + root_radius: i32, + root_replaceable: Arc>, + root_provider: BlockStateProvider, + root_attempts: i32, + root_column_max_height: i32, + hanging_radius: i32, + hanging_span: i32, + hanging_provider: BlockStateProvider, + hanging_attempts: i32, + allowed_water: i32, + allowed_tree_position: BlockPredicate, + blocks: Arc, +} +impl RootSystemFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + nested: &PlacedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:root_system" { + return Err(DecodeError::Field("root system type")); + } + let blocks = bindings.tree_blocks()?; + let tree = nested(required(&object, "feature")?.get(), depth + 1, remaining)?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let int = |name: &'static str, low: i32, high: i32| { + int_range(required(&object, name)?, name, low, high) + }; + Ok(Self { + tree: Box::new(tree), + required_vertical_space: int("required_vertical_space_for_tree", 1, 64)?, + level_test_distance: int("level_test_distance", 0, 16)?, + max_level_deviation: int("max_level_deviation", 0, 64)?, + root_radius: int("root_radius", 1, 64)?, + root_replaceable: decoder.block_set(required(&object, "root_replaceable")?)?, + root_provider: decoder.provider(required(&object, "root_state_provider")?)?, + root_attempts: int("root_placement_attempts", 1, 256)?, + root_column_max_height: int("root_column_max_height", 1, 4096)?, + hanging_radius: int("hanging_root_radius", 1, 64)?, + hanging_span: int("hanging_roots_vertical_span", 1, 16)?, + hanging_provider: decoder.provider(required(&object, "hanging_root_state_provider")?)?, + hanging_attempts: int("hanging_root_placement_attempts", 1, 256)?, + allowed_water: int("allowed_vertical_water_for_tree", 1, 64)?, + allowed_tree_position: BlockPredicate::decode_with_blocks( + required(&object, "allowed_tree_position")?.get(), + depth + 1, + decoder.remaining, + Some(bindings), + )?, + blocks, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut PlacedPlacer<'_, W, R>, + ) -> TreeResult { + if !self.blocks.is_air(read(world, origin)?) { + return Ok(false); + } + if self.dirt_and_tree(world, random, origin, nested)? { + self.hanging_roots(world, random, origin)?; + } + Ok(true) + } + fn space_for_tree( + &self, + world: &mut W, + pos: [i32; 3], + ) -> TreeResult { + let mut column = pos; + for i in 1..=self.required_vertical_space { + column = tb::offset(column, 0, 1, 0); + let state = read(world, column)?; + let allowed = self.blocks.is_air(state) + || (i < self.allowed_water && self.blocks.has(state, tb::WATER_FLUID)); + if !allowed { + return Ok(false); + } + } + if self.level_test_distance > 0 { + // Direction.from2DDataValue: SOUTH, WEST, NORTH, EAST. + for direction in [ + Direction::South, + Direction::West, + Direction::North, + Direction::East, + ] { + let corner = tb::relative(pos, direction, self.level_test_distance); + let below = read(world, tb::offset(corner, 0, -self.max_level_deviation, 0))?; + let above = read(world, tb::offset(corner, 0, self.max_level_deviation, 0))?; + if self.blocks.is_air(below) || !self.blocks.is_air(above) { + return Ok(false); + } + } + } + Ok(true) + } + fn dirt_and_tree( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut PlacedPlacer<'_, W, R>, + ) -> TreeResult { + let mut working = origin; + for y in 0..self.root_column_max_height { + working = tb::offset(working, 0, 1, 0); + let surface = world + .height( + crate::heightmap::HeightmapType::WorldSurface, + working[0], + working[2], + ) + .map_err(query)?; + if surface < working[1] { + return Ok(false); + } + if self + .allowed_tree_position + .test(world, working) + .map_err(query)? + && self.space_for_tree(world, working)? + { + let below_state = read(world, tb::offset(working, 0, -1, 0))?; + if self.blocks.has(below_state, tb::LAVA_FLUID) + || !self.blocks.has(below_state, tb::SOLID) + { + return Ok(false); + } + if nested(&self.tree, world, random, working)? { + let target = origin[1].wrapping_add(y); + let mut level = origin[1]; + while level < target { + self.rooted_dirt(world, random, [origin[0], level, origin[2]])?; + level += 1; + } + return Ok(true); + } + } + } + Ok(false) + } + fn rooted_dirt( + &self, + world: &mut W, + random: &mut R, + column: [i32; 3], + ) -> TreeResult<(), W::Error> { + let r = self.root_radius; + for _ in 0..self.root_attempts { + let dx = random.next_int_bound(r)? - random.next_int_bound(r)?; + let dz = random.next_int_bound(r)? - random.next_int_bound(r)?; + let p = tb::offset(column, dx, 0, dz); + if self.root_replaceable.contains(&read(world, p)?) { + let state = sample_state(&self.root_provider, world, random, p)?; + write(world, p, state, 2)?; + } + } + Ok(()) + } + fn hanging_roots( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult<(), W::Error> { + let (r, span) = (self.hanging_radius, self.hanging_span); + for _ in 0..self.hanging_attempts { + let dx = random.next_int_bound(r)? - random.next_int_bound(r)?; + let dy = random.next_int_bound(span)? - random.next_int_bound(span)?; + let dz = random.next_int_bound(r)? - random.next_int_bound(r)?; + let p = tb::offset(origin, dx, dy, dz); + if !self.blocks.is_air(read(world, p)?) { + continue; + } + let state = sample_state(&self.hanging_provider, world, random, p)?; + if world.block_survives(state, p).map_err(query)? { + let above = read(world, tb::offset(p, 0, 1, 0))?; + if world + .state_face_sturdy(above, p, Direction::Down) + .map_err(query)? + { + write(world, p, state, 2)?; + } + } + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/tree_blocks.rs b/crates/horizon-world/src/worldgen/tree_blocks.rs index d335b8d46..2ab24a0a0 100644 --- a/crates/horizon-world/src/worldgen/tree_blocks.rs +++ b/crates/horizon-world/src/worldgen/tree_blocks.rs @@ -29,12 +29,26 @@ pub(crate) const SOLID: u32 = 1 << 14; pub(crate) const LAVA_FLUID: u32 = 1 << 15; pub(crate) const ANY_FLUID: u32 = 1 << 16; pub(crate) const FULL_AXIS: u32 = 1 << 17; +pub(crate) const MUSHROOM_REPLACEABLE: u32 = 1 << 18; +pub(crate) const FIRE: u32 = 1 << 19; +pub(crate) const SCULK_BLOCKER: u32 = 1 << 20; +pub(crate) const SCULK_VEIN: u32 = 1 << 21; +pub(crate) const LIQUID: u32 = 1 << 22; +pub(crate) const FEATURES_CANNOT_REPLACE: u32 = 1 << 23; +pub(crate) const CHEST: u32 = 1 << 24; +pub(crate) const SPAWNER: u32 = 1 << 25; +/// Any source fluid state (water or lava), including waterlogged blocks. +pub(crate) const FLUID_SOURCE: u32 = 1 << 26; +/// Fluid amount 8 (sources and falling fluids). +pub(crate) const FLUID_FULL: u32 = 1 << 27; /// Immutable per-state facts. Missing tags or blocks are empty classifications. pub struct TreeBlocks { flags: Vec, /// Native LeavesBlock DISTANCE (1..=7) values; 0 when absent. distance: Vec, + /// Block identity (index of the block name) per state. + block: Vec, pub(crate) properties: Arc, defaults: BTreeMap, } @@ -45,7 +59,15 @@ impl std::fmt::Debug for TreeBlocks { .finish_non_exhaustive() } } -const DEFAULTS: [&str; 12] = [ +const DEFAULTS: [&str; 20] = [ + "minecraft:cobblestone", + "minecraft:mossy_cobblestone", + "minecraft:chest", + "minecraft:spawner", + "minecraft:ice", + "minecraft:packed_ice", + "minecraft:glow_lichen", + "minecraft:sculk_vein", "minecraft:vine", "minecraft:cocoa", "minecraft:bee_nest", @@ -79,6 +101,10 @@ impl TreeBlocks { bindings, BlockProperty::Solid, )?; + let liquid = super::block_predicate::PredicateBlockResolver::predicate_property( + bindings, + BlockProperty::Liquid, + )?; let mut flags = vec![0u32; registry.len()]; let mut distance = vec![0u8; registry.len()]; let mark_tag = |tag: &str, flag: u32, flags: &mut Vec| { @@ -100,10 +126,27 @@ impl TreeBlocks { PREVENTS_LEAF_DECAY, &mut flags, ); + mark_tag( + "minecraft:replaceable_by_mushrooms", + MUSHROOM_REPLACEABLE, + &mut flags, + ); + mark_tag("minecraft:fire", FIRE, &mut flags); + mark_tag( + "minecraft:features_cannot_replace", + FEATURES_CANNOT_REPLACE, + &mut flags, + ); for (name, flag) in [ ("minecraft:vine", VINE), ("minecraft:water", WATER_BLOCK), ("minecraft:shelf_mushroom", SHELF_MUSHROOM), + ("minecraft:sculk", SCULK_BLOCKER), + ("minecraft:sculk_catalyst", SCULK_BLOCKER), + ("minecraft:moving_piston", SCULK_BLOCKER), + ("minecraft:sculk_vein", SCULK_VEIN), + ("minecraft:chest", CHEST), + ("minecraft:spawner", SPAWNER), ] { if let Some(states) = bindings.blocks.get(name) { for state in states.iter() { @@ -126,6 +169,9 @@ impl TreeBlocks { if solid.contains(id) { *flag |= SOLID; } + if liquid.contains(id) { + *flag |= LIQUID; + } if let Some(fluid) = bindings.fluids.state(id) { match fluid.kind() { FluidKind::Water => *flag |= WATER_SOURCE | WATER_FLUID | ANY_FLUID, @@ -133,6 +179,12 @@ impl TreeBlocks { FluidKind::Lava | FluidKind::FlowingLava => *flag |= LAVA_FLUID | ANY_FLUID, FluidKind::Empty => {} } + if fluid.is_source() { + *flag |= FLUID_SOURCE; + } + if fluid.amount() == 8 { + *flag |= FLUID_FULL; + } } if properties.value(id, "persistent") == Some("true") { *flag |= PERSISTENT; @@ -159,6 +211,14 @@ impl TreeBlocks { } } } + let mut names = BTreeMap::new(); + let block = (0..registry.len()) + .map(|i| { + let name = ®istry.state(BlockStateId(i as u32)).unwrap().name; + let next = names.len() as u32; + *names.entry(name.clone()).or_insert(next) + }) + .collect(); let defaults = DEFAULTS .iter() .filter_map(|name| { @@ -170,6 +230,7 @@ impl TreeBlocks { Ok(Self { flags, distance, + block, properties, defaults, }) @@ -179,6 +240,10 @@ impl TreeBlocks { .get(state.0 as usize) .is_some_and(|value| value & flag != 0) } + /// BlockState.is(Block): same block, any properties. + pub(crate) fn same_block(&self, a: BlockStateId, b: BlockStateId) -> bool { + self.block.get(a.0 as usize) == self.block.get(b.0 as usize) + } pub(crate) fn is_air(&self, state: BlockStateId) -> bool { self.has(state, AIR) } diff --git a/crates/horizon-world/src/worldgen/vegetation.rs b/crates/horizon-world/src/worldgen/vegetation.rs new file mode 100644 index 000000000..f68bc0cb6 --- /dev/null +++ b/crates/horizon-world/src/worldgen/vegetation.rs @@ -0,0 +1,832 @@ +//! Vegetation and cave-decoration features: vegetation patches (plain and +//! waterlogged), coral trees/claws, huge mushrooms and multiface growth. +use super::{ + DecodeError, Object, int_range, optional, + block_feature::FeatureBlockBindings, + block_predicate::BlockPredicate, + feature::FeatureWorld, + feature_graph::{FeatureExecutionError, PlacedFeatureDefinition}, + placement::PlacementContext, + required, + state_provider::BlockStateProvider, + tree::{TreeDecoder, TreeResult, kind, read, sample_state, unit_float, write}, + tree_blocks::{self as tb, PosSet, TreeBlocks}, + value_provider::IntProvider, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, random::RandomSource}; +use std::{collections::BTreeSet, sync::Arc}; + +/// Places a nested placed feature with the caller's run budget. +pub(crate) type PlacedPlacer<'a, W, R> = dyn FnMut( + &PlacedFeatureDefinition, + &mut W, + &mut R, + [i32; 3], + ) -> TreeResult::Error> + + 'a; +pub(crate) type PlacedDecoder<'a> = + dyn Fn(&str, usize, &mut usize) -> Result + 'a; + +fn query(error: super::placement::PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} + +#[derive(Clone, Debug)] +pub struct VegetationPatchFeature { + replaceable: Arc>, + ground: BlockStateProvider, + vegetation: Box, + /// CaveSurface direction: DOWN for floor, UP for ceiling. + inwards: Direction, + depth: IntProvider, + extra_bottom: f32, + vertical_range: i32, + vegetation_chance: f32, + xz_radius: IntProvider, + extra_edge: f32, + waterlogged: bool, + blocks: Arc, +} +impl VegetationPatchFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + nested: &PlacedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let waterlogged = match kind(&object)?.as_str() { + "minecraft:vegetation_patch" => false, + "minecraft:waterlogged_vegetation_patch" => true, + _ => return Err(DecodeError::Field("vegetation patch type")), + }; + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let surface: String = serde_json::from_str(required(&object, "surface")?.get())?; + let inwards = match surface.as_str() { + "floor" => Direction::Down, + "ceiling" => Direction::Up, + _ => return Err(DecodeError::Field("cave surface")), + }; + let vegetation = nested( + required(&object, "vegetation_feature")?.get(), + depth + 1, + decoder.remaining, + )?; + Ok(Self { + replaceable: decoder.block_set(required(&object, "replaceable")?)?, + ground: decoder.provider(required(&object, "ground_state")?)?, + vegetation: Box::new(vegetation), + inwards, + depth: decoder.int_provider(required(&object, "depth")?, 1, 128)?, + extra_bottom: unit_float( + required(&object, "extra_bottom_block_chance")?, + "extra_bottom_block_chance", + )?, + vertical_range: int_range( + required(&object, "vertical_range")?, + "vertical_range", + 1, + 256, + )?, + vegetation_chance: unit_float( + required(&object, "vegetation_chance")?, + "vegetation_chance", + )?, + xz_radius: IntProvider::decode( + required(&object, "xz_radius")?, + depth + 1, + decoder.remaining, + )?, + extra_edge: unit_float( + required(&object, "extra_edge_column_chance")?, + "extra_edge_column_chance", + )?, + waterlogged, + blocks, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut PlacedPlacer<'_, W, R>, + ) -> TreeResult { + let x_radius = self.xz_radius.sample(random)?.wrapping_add(1); + let z_radius = self.xz_radius.sample(random)?.wrapping_add(1); + let mut surface = self.ground_patch(world, random, origin, x_radius, z_radius)?; + if self.waterlogged { + let mut water = PosSet::default(); + for p in surface.to_vec() { + let mut exposed = false; + for direction in [ + Direction::North, + Direction::East, + Direction::South, + Direction::West, + Direction::Down, + ] { + let q = tb::relative(p, direction, 1); + let state = read(world, q)?; + if !world + .state_face_sturdy(state, q, direction.opposite()) + .map_err(query)? + { + exposed = true; + break; + } + } + if !exposed { + water.insert(p); + } + } + let water_state = self + .blocks + .default_state("minecraft:water") + .ok_or(FeatureExecutionError::InvalidState)?; + for p in water.to_vec() { + write(world, p, water_state, 2)?; + } + surface = water; + } + let positions = surface.to_vec(); + for p in &positions { + if self.vegetation_chance > 0.0 && random.next_float() < self.vegetation_chance { + self.place_vegetation(world, random, *p, nested)?; + } + } + Ok(!positions.is_empty()) + } + fn place_vegetation( + &self, + world: &mut W, + random: &mut R, + position: [i32; 3], + nested: &mut PlacedPlacer<'_, W, R>, + ) -> TreeResult { + let outwards = self.inwards.opposite(); + if !self.waterlogged { + return nested(&self.vegetation, world, random, tb::relative(position, outwards, 1)); + } + // WaterloggedVegetationPatchFeature passes placementPos.below() to super. + let below = tb::offset(position, 0, -1, 0); + if nested(&self.vegetation, world, random, tb::relative(below, outwards, 1))? { + let placed = read(world, position)?; + if self.blocks.has(placed, tb::WATERLOGGABLE) + && self.blocks.properties.value(placed, "waterlogged") == Some("false") + { + write(world, position, self.blocks.waterlogged(placed, true), 2)?; + } + return Ok(true); + } + Ok(false) + } + fn ground_patch( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + x_radius: i32, + z_radius: i32, + ) -> TreeResult { + let inwards = self.inwards; + let outwards = inwards.opposite(); + let mut surface = PosSet::default(); + let mut dx = x_radius.wrapping_neg(); + while dx <= x_radius { + let x_edge = dx == x_radius.wrapping_neg() || dx == x_radius; + let mut dz = z_radius.wrapping_neg(); + while dz <= z_radius { + let z_edge = dz == z_radius.wrapping_neg() || dz == z_radius; + let edge = x_edge || z_edge; + let corner = x_edge && z_edge; + let edge_not_corner = edge && !corner; + if !corner + && (!edge_not_corner + || (self.extra_edge != 0.0 && random.next_float() <= self.extra_edge)) + { + let mut pos = tb::offset(origin, dx, 0, dz); + let mut offset = 0; + while self.blocks.is_air(read(world, pos)?) && offset < self.vertical_range { + pos = tb::relative(pos, inwards, 1); + offset += 1; + } + let mut offset = 0; + while !self.blocks.is_air(read(world, pos)?) && offset < self.vertical_range { + pos = tb::relative(pos, outwards, 1); + offset += 1; + } + let below = tb::relative(pos, inwards, 1); + let below_state = read(world, below)?; + if self.blocks.is_air(read(world, pos)?) + && world + .state_face_sturdy(below_state, below, outwards) + .map_err(query)? + { + let depth = self.depth.sample(random)?.wrapping_add(i32::from( + self.extra_bottom > 0.0 && random.next_float() < self.extra_bottom, + )); + if self.place_ground(world, random, below, depth)? { + surface.insert(below); + } + } + } + dz += 1; + } + dx += 1; + } + Ok(surface) + } + fn place_ground( + &self, + world: &mut W, + random: &mut R, + mut below: [i32; 3], + depth: i32, + ) -> TreeResult { + for i in 0..depth { + let state = sample_state(&self.ground, world, random, below)?; + let existing = read(world, below)?; + if !self.blocks.same_block(state, existing) { + if !self.replaceable.contains(&existing) { + return Ok(i != 0); + } + write(world, below, state, 2)?; + below = tb::relative(below, self.inwards, 1); + } + } + Ok(true) + } +} + +#[derive(Clone, Debug)] +pub struct CoralFeature { + claw: bool, + feature: Box, +} +impl CoralFeature { + pub(crate) fn decode( + json: &str, + depth: usize, + remaining: &mut usize, + nested: &PlacedDecoder<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let claw = match kind(&object)?.as_str() { + "minecraft:coral_tree" => false, + "minecraft:coral_claw" => true, + _ => return Err(DecodeError::Field("coral feature type")), + }; + Ok(Self { + claw, + feature: Box::new(nested( + required(&object, "feature")?.get(), + depth + 1, + remaining, + )?), + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + nested: &mut PlacedPlacer<'_, W, R>, + ) -> TreeResult { + let feature = &*self.feature; + if !self.claw { + let mut pos = origin; + let trunk = random.next_int_bound(3)? + 1; + for _ in 0..trunk { + if !nested(feature, world, random, pos)? { + return Ok(true); + } + pos = tb::offset(pos, 0, 1, 0); + } + let top = pos; + let branches = random.next_int_bound(3)? + 2; + let mut directions = tb::HORIZONTAL; + tb::shuffle(&mut directions, random)?; + for &direction in directions.iter().take(branches as usize) { + let mut pos = tb::relative(top, direction, 1); + let height = random.next_int_bound(5)? + 2; + let mut segment = 0; + let mut j = 0; + while j < height && nested(feature, world, random, pos)? { + segment += 1; + pos = tb::offset(pos, 0, 1, 0); + if j == 0 || (segment >= 2 && random.next_float() < 0.25) { + pos = tb::relative(pos, direction, 1); + segment = 0; + } + j += 1; + } + } + return Ok(true); + } + if !nested(feature, world, random, origin)? { + return Ok(false); + } + let claw = tb::HORIZONTAL[random.next_int_bound(4)? as usize]; + let branches = random.next_int_bound(2)? + 2; + let mut possible = [claw, tb::clockwise(claw), counter_clockwise(claw)]; + tb::shuffle(&mut possible, random)?; + for &branch in possible.iter().take(branches as usize) { + let mut pos = origin; + let sideways = random.next_int_bound(2)? + 1; + pos = tb::relative(pos, branch, 1); + let (segment, inway) = if branch == claw { + (claw, random.next_int_bound(3)? + 2) + } else { + pos = tb::offset(pos, 0, 1, 0); + let options = [branch, Direction::Up]; + let segment = options[random.next_int_bound(2)? as usize]; + (segment, random.next_int_bound(3)? + 3) + }; + let mut i = 0; + while i < sideways && nested(feature, world, random, pos)? { + pos = tb::relative(pos, segment, 1); + i += 1; + } + pos = tb::relative(pos, segment.opposite(), 1); + pos = tb::offset(pos, 0, 1, 0); + for _ in 0..inway { + pos = tb::relative(pos, claw, 1); + if !nested(feature, world, random, pos)? { + break; + } + if random.next_float() < 0.25 { + pos = tb::offset(pos, 0, 1, 0); + } + } + } + Ok(true) + } +} +pub(crate) fn counter_clockwise(direction: Direction) -> Direction { + match direction { + Direction::North => Direction::West, + Direction::East => Direction::North, + Direction::South => Direction::East, + Direction::West => Direction::South, + other => other, + } +} + +#[derive(Clone, Debug)] +pub struct HugeMushroomFeature { + red: bool, + cap: BlockStateProvider, + stem: BlockStateProvider, + foliage_radius: i32, + can_place_on: BlockPredicate, + blocks: Arc, +} +impl HugeMushroomFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + let red = match kind(&object)?.as_str() { + "minecraft:huge_red_mushroom" => true, + "minecraft:huge_brown_mushroom" => false, + _ => return Err(DecodeError::Field("huge mushroom type")), + }; + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let cap = decoder.provider(required(&object, "cap_provider")?)?; + let stem = decoder.provider(required(&object, "stem_provider")?)?; + let foliage_radius = optional(&object, "foliage_radius") + .map(super::integer) + .transpose()? + .unwrap_or(2); + let can_place_on = BlockPredicate::decode_with_blocks( + required(&object, "can_place_on")?.get(), + depth + 1, + decoder.remaining, + Some(bindings), + )?; + Ok(Self { + red, + cap, + stem, + foliage_radius, + can_place_on, + blocks, + }) + } + fn radius_for_height(&self, tree_height: i32, leaf_radius: i32, yo: i32) -> i32 { + if self.red { + if (yo < tree_height && yo >= tree_height - 3) || yo == tree_height { + leaf_radius + } else { + 0 + } + } else if yo <= 3 { + 0 + } else { + leaf_radius + } + } + fn place_block( + &self, + world: &mut W, + p: [i32; 3], + state: BlockStateId, + ) -> TreeResult<(), W::Error> { + let current = read(world, p)?; + if self.blocks.has(current, tb::AIR | tb::MUSHROOM_REPLACEABLE) { + write(world, p, state, 3)?; + } + Ok(()) + } + fn faces(&self, state: BlockStateId, faces: &[(&str, bool)]) -> BlockStateId { + if faces + .iter() + .all(|(name, _)| self.blocks.properties.value(state, name).is_some()) + { + faces.iter().fold(state, |state, (name, value)| { + self.blocks + .with(state, name, if *value { "true" } else { "false" }) + .unwrap_or(state) + }) + } else { + state + } + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let mut height = random.next_int_bound(3)? + 4; + if random.next_int_bound(12)? == 0 { + height *= 2; + } + let y = origin[1]; + let min = world.min_y().map_err(query)?; + let max = world.max_y().map_err(query)?; + if y < min.wrapping_add(1) || y.wrapping_add(height).wrapping_add(1) > max { + return Ok(false); + } + if !self + .can_place_on + .test(world, tb::offset(origin, 0, -1, 0)) + .map_err(query)? + { + return Ok(false); + } + for dy in 0..=height { + let radius = self.radius_for_height(-1, self.foliage_radius, dy); + for dx in -radius..=radius { + for dz in -radius..=radius { + let state = read(world, tb::offset(origin, dx, dy, dz))?; + if !self.blocks.has(state, tb::AIR | tb::LEAVES) { + return Ok(false); + } + } + } + } + let r = self.foliage_radius; + if self.red { + for dy in height - 3..=height { + let radius = if dy < height { r } else { r - 1 }; + let center = r - 2; + for dx in -radius..=radius { + for dz in -radius..=radius { + let x_edge = dx == -radius || dx == radius; + let z_edge = dz == -radius || dz == radius; + if dy >= height || x_edge != z_edge { + let p = tb::offset(origin, dx, dy, dz); + let state = sample_state(&self.cap, world, random, origin)?; + let state = self.faces( + state, + &[ + ("west", dx < -center), + ("east", dx > center), + ("north", dz < -center), + ("south", dz > center), + ("up", dy >= height - 1), + ], + ); + self.place_block(world, p, state)?; + } + } + } + } + } else { + for dx in -r..=r { + for dz in -r..=r { + let (min_x, max_x, min_z, max_z) = (dx == -r, dx == r, dz == -r, dz == r); + let x_edge = min_x || max_x; + let z_edge = min_z || max_z; + if !x_edge || !z_edge { + let p = tb::offset(origin, dx, height, dz); + let west = min_x || (z_edge && dx == 1 - r); + let east = max_x || (z_edge && dx == r - 1); + let north = min_z || (x_edge && dz == 1 - r); + let south = max_z || (x_edge && dz == r - 1); + let state = sample_state(&self.cap, world, random, origin)?; + let state = self.faces( + state, + &[ + ("west", west), + ("east", east), + ("north", north), + ("south", south), + ], + ); + self.place_block(world, p, state)?; + } + } + } + } + for dy in 0..height { + let state = sample_state(&self.stem, world, random, origin)?; + self.place_block(world, tb::offset(origin, 0, dy, 0), state)?; + } + Ok(true) + } +} + +#[derive(Clone, Debug)] +pub struct MultifaceGrowthFeature { + block: BlockStateId, + sculk: bool, + search_range: i32, + directions: Vec, + chance_of_spreading: f32, + can_be_placed_on: Arc>, + blocks: Arc, +} +#[derive(Clone, Copy)] +enum Spread { + SamePosition, + SamePlane, + WrapAround, +} +impl MultifaceGrowthFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:multiface_growth" { + return Err(DecodeError::Field("multiface growth type")); + } + let blocks = bindings.tree_blocks()?; + let name = super::density::identifier(&serde_json::from_str::( + required(&object, "block")?.get(), + )?)?; + // The 26.3 MultifaceSpreadeableBlock subclasses. + let sculk = match name.as_str() { + "minecraft:glow_lichen" => false, + "minecraft:sculk_vein" => true, + _ => return Err(DecodeError::Field("multiface spreadeable block")), + }; + let block = blocks + .default_state(&name) + .ok_or(DecodeError::Field("multiface block"))?; + let flag = |key: &str| -> Result { + Ok(optional(&object, key) + .map(|raw| serde_json::from_str::(raw.get())) + .transpose()? + .unwrap_or(false)) + }; + let mut directions = Vec::new(); + if flag("can_place_on_ceiling")? { + directions.push(Direction::Up); + } + if flag("can_place_on_floor")? { + directions.push(Direction::Down); + } + if flag("can_place_on_wall")? { + directions.extend(tb::HORIZONTAL); + } + Ok(Self { + block, + sculk, + search_range: optional(&object, "search_range") + .map(|raw| int_range(raw, "search_range", 1, 64)) + .transpose()? + .unwrap_or(10), + directions, + chance_of_spreading: optional(&object, "chance_of_spreading") + .map(|raw| unit_float(raw, "chance_of_spreading")) + .transpose()? + .unwrap_or(0.5), + can_be_placed_on: super::block_predicate::PredicateBlockResolver::predicate_block_set( + bindings, + required(&object, "can_be_placed_on")?.get(), + )?, + blocks, + }) + } + fn air_or_water(&self, state: BlockStateId) -> bool { + self.blocks.has(state, tb::AIR | tb::WATER_BLOCK) + } + fn is_block(&self, state: BlockStateId) -> bool { + self.blocks.same_block(state, self.block) + } + fn has_face(&self, state: BlockStateId, face: Direction) -> bool { + self.blocks.properties.value(state, tb::direction_name(face)) == Some("true") + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let here = read(world, origin)?; + if !self.air_or_water(here) { + return Ok(false); + } + let mut directions = self.directions.clone(); + tb::shuffle(&mut directions, random)?; + let here = read(world, origin)?; + if self.place_growth(world, random, origin, here, &directions)? { + return Ok(true); + } + for &search in &directions { + let mut placement: Vec = self + .directions + .iter() + .copied() + .filter(|d| *d != search.opposite()) + .collect(); + tb::shuffle(&mut placement, random)?; + for _ in 0..self.search_range { + // Native setWithOffset(origin, ...) revisits the first neighbor. + let pos = tb::relative(origin, search, 1); + let state = read(world, pos)?; + if !self.air_or_water(state) && !self.is_block(state) { + break; + } + if self.place_growth(world, random, pos, state, &placement)? { + return Ok(true); + } + } + } + Ok(false) + } + fn place_growth( + &self, + world: &mut W, + random: &mut R, + pos: [i32; 3], + old: BlockStateId, + directions: &[Direction], + ) -> TreeResult { + for &direction in directions { + let neighbor = read(world, tb::relative(pos, direction, 1))?; + if self.can_be_placed_on.contains(&neighbor) { + let Some(state) = self.state_for_placement(world, old, pos, direction)? else { + return Ok(false); + }; + write(world, pos, state, 3)?; + world.mark_postprocessing(pos).map_err(query)?; + if random.next_float() < self.chance_of_spreading { + let mut all = Direction::ALL; + tb::shuffle(&mut all, random)?; + for spread in all { + if self.spread(world, state, pos, direction, spread)? { + break; + } + } + } + return Ok(true); + } + } + Ok(false) + } + fn valid_for_placement( + &self, + world: &mut W, + old: BlockStateId, + pos: [i32; 3], + direction: Direction, + ) -> TreeResult { + if self.is_block(old) && self.has_face(old, direction) { + return Ok(false); + } + world.attachment_at(pos, direction).map_err(query) + } + fn state_for_placement( + &self, + world: &mut W, + old: BlockStateId, + pos: [i32; 3], + direction: Direction, + ) -> TreeResult, W::Error> { + if !self.valid_for_placement(world, old, pos, direction)? { + return Ok(None); + } + let state = if self.is_block(old) { + old + } else if self.blocks.has(old, tb::WATER_SOURCE) { + self.blocks.waterlogged(self.block, true) + } else { + self.block + }; + Ok(Some( + self.blocks + .with(state, tb::direction_name(direction), "true") + .ok_or(FeatureExecutionError::InvalidState)?, + )) + } + fn spread_types(&self) -> [Spread; 3] { + [Spread::SamePosition, Spread::SamePlane, Spread::WrapAround] + } + /// spreadFromFaceTowardDirection with postProcess = true. + fn spread( + &self, + world: &mut W, + state: BlockStateId, + pos: [i32; 3], + from: Direction, + direction: Direction, + ) -> TreeResult { + if tb::Axis::of(direction) == tb::Axis::of(from) { + return Ok(false); + } + let other_source = self.sculk && !self.blocks.has(state, tb::SCULK_VEIN); + if !(other_source || (self.has_face(state, from) && !self.has_face(state, direction))) { + return Ok(false); + } + for kind in self.spread_types() { + let (target, face) = match kind { + Spread::SamePosition => (pos, direction), + Spread::SamePlane => (tb::relative(pos, direction, 1), from), + Spread::WrapAround => ( + tb::relative(tb::relative(pos, direction, 1), from, 1), + direction.opposite(), + ), + }; + if self.can_spread_into(world, pos, target, face)? { + let old = read(world, target)?; + let Some(new) = self.state_for_placement(world, old, target, face)? else { + return Ok(false); + }; + world.mark_postprocessing(target).map_err(query)?; + return write(world, target, new, 2); + } + } + Ok(false) + } + fn can_spread_into( + &self, + world: &mut W, + source: [i32; 3], + target: [i32; 3], + face: Direction, + ) -> TreeResult { + let existing = read(world, target)?; + let replaceable = if self.sculk { + let against = read(world, tb::relative(target, face, 1))?; + if self.blocks.has(against, tb::SCULK_BLOCKER) { + false + } else { + let mut blocked = false; + if tb::dist_manhattan(source, target) == 2 { + let neighbor = tb::relative(source, face.opposite(), 1); + let state = read(world, neighbor)?; + blocked = world + .state_face_sturdy(state, neighbor, face) + .map_err(query)?; + } + if blocked + || (self.blocks.has(existing, tb::ANY_FLUID) + && !self.blocks.has(existing, tb::WATER_SOURCE)) + || self.blocks.has(existing, tb::FIRE) + { + false + } else { + self.blocks.has(existing, tb::REPLACEABLE) || self.default_replaceable(existing) + } + } + } else { + self.default_replaceable(existing) + }; + Ok(replaceable && self.valid_for_placement(world, existing, target, face)?) + } + fn default_replaceable(&self, existing: BlockStateId) -> bool { + self.blocks.is_air(existing) + || self.is_block(existing) + || (self.blocks.has(existing, tb::WATER_BLOCK) && self.blocks.has(existing, tb::WATER_SOURCE)) + } +} From 261a8091b6ceb5a9e0eb834a83bd76b8cf8e88e0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:24:16 +0200 Subject: [PATCH 04/12] Add native Marsaglia polar Gaussian sampling and clamped normal floats RandomSource gains next_gaussian with per-source cached second values, reset by set_seed for the legacy and Xoroshiro sources as in vanilla. The WorldgenRandom adapter keeps its own cache that native setSeed does not reset. FloatProvider decodes and samples minecraft:clamped_normal. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-core/src/random.rs | 43 ++++++++++++++++++- crates/horizon-core/src/random/worldgen.rs | 13 ++++++ .../src/worldgen/value_provider.rs | 31 ++++++++++++- 3 files changed, 85 insertions(+), 2 deletions(-) diff --git a/crates/horizon-core/src/random.rs b/crates/horizon-core/src/random.rs index 309d48124..46397b5c4 100644 --- a/crates/horizon-core/src/random.rs +++ b/crates/horizon-core/src/random.rs @@ -29,6 +29,9 @@ pub trait RandomSource: Sized { fn next_boolean(&mut self) -> bool; fn next_float(&mut self) -> f32; fn next_double(&mut self) -> f64; + /// MarsagliaPolarGaussian over this source; the cached second value is + /// part of the source state (reset by `set_seed` where vanilla resets it). + fn next_gaussian(&mut self) -> f64; fn fork_positional(&mut self) -> Self::Positional; fn fork(&mut self) -> Self where @@ -61,6 +64,7 @@ pub trait RandomSource: Sized { #[derive(Clone, Debug)] pub struct LegacyRandom { state: u64, + gaussian: Option, } impl LegacyRandom { @@ -70,6 +74,7 @@ impl LegacyRandom { pub fn new(seed: i64) -> Self { Self { state: (seed as u64 ^ Self::MULTIPLIER) & Self::MASK, + gaussian: None, } } @@ -125,6 +130,12 @@ impl RandomSource for LegacyRandom { let value = (i64::from(self.bits(26)) << 27) + i64::from(self.bits(27)); value as f64 * (1.0 / 9_007_199_254_740_992.0) } + fn next_gaussian(&mut self) -> f64 { + let mut cache = self.gaussian.take(); + let value = marsaglia_polar(&mut cache, || self.next_double()); + self.gaussian = cache; + value + } fn fork(&mut self) -> Self { Self::new(self.next_long()) @@ -135,6 +146,7 @@ impl RandomSource for LegacyRandom { pub struct XoroshiroRandom { lo: u64, hi: u64, + gaussian: Option, } impl XoroshiroRandom { @@ -154,9 +166,14 @@ impl XoroshiroRandom { Self { lo: Self::GOLDEN_RATIO, hi: Self::SILVER_RATIO, + gaussian: None, } } else { - Self { lo, hi } + Self { + lo, + hi, + gaussian: None, + } } } } @@ -207,6 +224,12 @@ impl RandomSource for XoroshiroRandom { fn next_double(&mut self) -> f64 { ((self.next_long() as u64) >> 11) as f64 * (1.0 / 9_007_199_254_740_992.0) } + fn next_gaussian(&mut self) -> f64 { + let mut cache = self.gaussian.take(); + let value = marsaglia_polar(&mut cache, || self.next_double()); + self.gaussian = cache; + value + } fn fork(&mut self) -> Self { let lo = self.next_long() as u64; let hi = self.next_long() as u64; @@ -214,6 +237,24 @@ impl RandomSource for XoroshiroRandom { } } +/// MarsagliaPolarGaussian.nextGaussian with an external second-value cache. +pub fn marsaglia_polar(cache: &mut Option, mut next_double: impl FnMut() -> f64) -> f64 { + if let Some(value) = cache.take() { + return value; + } + loop { + let x = 2.0 * next_double() - 1.0; + let y = 2.0 * next_double() - 1.0; + let radius = x * x + y * y; + if radius >= 1.0 || radius == 0.0 { + continue; + } + let multiplier = (-2.0 * radius.ln() / radius).sqrt(); + *cache = Some(y * multiplier); + return x * multiplier; + } +} + pub const fn mix_stafford13(mut value: u64) -> u64 { value = (value ^ (value >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9); value = (value ^ (value >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb); diff --git a/crates/horizon-core/src/random/worldgen.rs b/crates/horizon-core/src/random/worldgen.rs index 70c88b0e2..aa16ab249 100644 --- a/crates/horizon-core/src/random/worldgen.rs +++ b/crates/horizon-core/src/random/worldgen.rs @@ -28,6 +28,8 @@ pub struct WorldgenRandom { source: R, count: i32, wrapped: bool, + /// The adapter's own Gaussian cache; native setSeed does not reset it. + gaussian: Option, } impl WorldgenRandom { pub fn new(source: R) -> Self { @@ -35,6 +37,7 @@ impl WorldgenRandom { source, count: 0, wrapped: true, + gaussian: None, } } fn plain(source: R) -> Self { @@ -42,6 +45,7 @@ impl WorldgenRandom { source, count: 0, wrapped: false, + gaussian: None, } } pub fn count(&self) -> i32 { @@ -150,6 +154,15 @@ impl RandomSource for WorldgenRandom { let bits = ((self.next_bits(26) as i64) << 27) + self.next_bits(27) as i64; bits as f64 * (1.0 / 9007199254740992.0) } + fn next_gaussian(&mut self) -> f64 { + if !self.wrapped { + return self.source.next_gaussian(); + } + let mut cache = self.gaussian.take(); + let value = super::marsaglia_polar(&mut cache, || self.next_double()); + self.gaussian = cache; + value + } /// Native forks return the underlying source, not another bit adapter. /// The returned value keeps that behavior through a transparent variant. fn fork(&mut self) -> Self { diff --git a/crates/horizon-world/src/worldgen/value_provider.rs b/crates/horizon-world/src/worldgen/value_provider.rs index 27bc8d4ae..442b1cdb5 100644 --- a/crates/horizon-world/src/worldgen/value_provider.rs +++ b/crates/horizon-world/src/worldgen/value_provider.rs @@ -10,6 +10,12 @@ pub enum FloatProvider { Constant(f32), Uniform { min: f32, max: f32 }, Trapezoid { min: f32, max: f32, plateau: f32 }, + ClampedNormal { + mean: f32, + deviation: f32, + min: f32, + max: f32, + }, } impl FloatProvider { pub fn from_json(json: &str) -> Result { @@ -38,13 +44,27 @@ impl FloatProvider { } Ok(Self::Trapezoid { min, max, plateau }) } + "minecraft:clamped_normal" => { + let (min, max) = (field("min")?, field("max")?); + if max < min { + return Err(DecodeError::Field("clamped normal float bounds")); + } + Ok(Self::ClampedNormal { + mean: field("mean")?, + deviation: field("deviation")?, + min, + max, + }) + } _ => Err(DecodeError::Field("float provider type")), } } pub fn bounds(&self) -> [f32; 2] { match *self { Self::Constant(value) => [value; 2], - Self::Uniform { min, max } | Self::Trapezoid { min, max, .. } => [min, max], + Self::Uniform { min, max } + | Self::Trapezoid { min, max, .. } + | Self::ClampedNormal { min, max, .. } => [min, max], } } pub fn sample(&self, random: &mut impl RandomSource) -> f32 { @@ -57,6 +77,15 @@ impl FloatProvider { let middle = range - slope; (min + random.next_float() * middle) + random.next_float() * slope } + Self::ClampedNormal { + mean, + deviation, + min, + max, + } => { + let value = mean + random.next_gaussian() as f32 * deviation; + if value < min { min } else { value.min(max) } + } } } } From 254dda89a3099b3c6880636755f0608a365e73e1 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 20:24:16 +0200 Subject: [PATCH 05/12] Port speleothem cluster and large dripstone; widen feature parity corpus Adds minecraft:speleothem_cluster (Column scans, pools, merged tips) and minecraft:large_dripstone (wind offsets, base embedding, height curve). The differential harness now resolves named features and placed features lazily on the Java side, logs dungeon loot/spawner block entities, uses the world seed and survival rules, and exercises every other configured feature over surface, cave, flooded-cave, ocean and nether worlds. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../examples/tree_feature_fixture.rs | 195 ++++- crates/horizon-world/src/worldgen.rs | 1 + .../horizon-world/src/worldgen/dripstone.rs | 754 ++++++++++++++++++ .../src/worldgen/feature_graph.rs | 18 + .../horizon-world/src/worldgen/tree_blocks.rs | 6 + .../parity/VanillaTreeFeatureOracle.java | 39 +- tools/test_tree_feature_parity.py | 25 +- 7 files changed, 1027 insertions(+), 11 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/dripstone.rs diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/tree_feature_fixture.rs index 0a16dc554..fd015b175 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/tree_feature_fixture.rs @@ -4,7 +4,9 @@ use horizon_core::{ random::{LegacyRandom, RandomSource, XoroshiroRandom}, }; use horizon_world::{ + block_collision::{BlockCollisionRegistry, DynamicCollisionWorld, ShulkerCollisionState}, block_placement::BlockPlacementBindings, + block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule, SurvivalWorld}, block_properties::BlockPropertiesRegistry, block_support::{BlockSupportRegistry, SupportType}, collision::CachedCollisionRegistry, @@ -37,6 +39,7 @@ const HEIGHT: i32 = 384; struct Terrain { layers: Vec<[i32; 2]>, + boxes: Vec<[i32; 7]>, hole: [i32; 2], obstacle: [i32; 3], overrides: HashMap<[i32; 3], u32>, @@ -52,6 +55,16 @@ impl Terrain { .iter() .map(|l| [l[0].as_i64().unwrap() as i32, l[1].as_i64().unwrap() as i32]) .collect(), + boxes: f + .get("boxes") + .and_then(Value::as_array) + .map(|boxes| { + boxes + .iter() + .map(|b| std::array::from_fn(|i| b[i].as_i64().unwrap() as i32)) + .collect() + }) + .unwrap_or_default(), hole: [n("hole_mod"), n("hole_state")], obstacle: [n("obstacle_mod"), n("obstacle_state"), n("obstacle_min")], overrides: f["states"] @@ -79,6 +92,11 @@ impl Terrain { if let Some(state) = self.overrides.get(&[x, y, z]) { return BlockStateId(*state); } + for b in &self.boxes { + if x >= b[0] && y >= b[1] && z >= b[2] && x <= b[3] && y <= b[4] && z <= b[5] { + return BlockStateId(b[6] as u32); + } + } let h = Self::hash(x, y, z); if let Some(layer) = self.layers.iter().find(|l| y <= l[0]) { if self.hole[0] > 0 && h % self.hole[0] == 0 { @@ -102,6 +120,12 @@ struct World<'a, 'r, W> { fluids: &'a FluidStateTable, tags: &'a BTreeMap>, support: &'a BlockSupportRegistry<'r>, + survival: &'a BlockSurvivalRegistry<'r>, + collision: &'a BlockCollisionRegistry<'r>, + seed: i64, + chest: BlockStateId, + world_random: LegacyRandom, + water_mask: u8, } impl World<'_, '_, W> { fn get(&self, p: [i32; 3]) -> BlockStateId { @@ -140,7 +164,77 @@ impl DynamicSupportWorld for World<'_, '_, W> { Ok(None) } } +impl DynamicCollisionWorld for World<'_, '_, W> { + fn shulker_collision_state(&mut self, _: [i32; 3]) -> io::Result> { + Ok(None) + } +} +impl SurvivalWorld for World<'_, '_, W> { + fn block_state(&mut self, p: [i32; 3]) -> io::Result { + Ok(self.get(p)) + } + fn fluid_state(&mut self, p: [i32; 3]) -> io::Result { + self.fluids + .get(self.get(p)) + .ok_or_else(|| io::Error::other("unknown fluid")) + } + fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> io::Result { + Ok(15) + } +} impl PlacementContext for World<'_, '_, W> { + fn world_seed(&mut self) -> Result { + Ok(self.seed) + } + fn next_world_boolean(&mut self) -> Result { + Ok(self.world_random.next_boolean()) + } + fn schedule_block_tick(&mut self, _: [i32; 3], _: BlockStateId, _: i32) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn schedule_fluid_tick(&mut self, _: [i32; 3], _: FluidKind, _: i32) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn block_brightness(&mut self, _: [i32; 3]) -> Result { + Ok(15) + } + fn sea_level(&mut self) -> Result { + Ok(63) + } + fn water_at(&mut self, p: [i32; 3]) -> Result { + let fluid = PlacementContext::fluid_state(self, p)?; + Ok(fluid.kind().mask() & self.water_mask != 0) + } + fn block_survives(&mut self, state: BlockStateId, p: [i32; 3]) -> Result { + let survival = self.survival; + survival.can_survive(self, state, p).map_err(query) + } + fn attachment_at(&mut self, p: [i32; 3], direction: Direction) -> Result { + let survival = self.survival; + survival.can_attach_to(self, p, direction).map_err(query) + } + fn state_collision_empty(&mut self, state: BlockStateId, p: [i32; 3]) -> Result { + let collision = self.collision; + collision + .collision_shape(self, state, p) + .map(|shape| shape.is_empty()) + .map_err(query) + } + fn set_block_entity_loot_table( + &mut self, + p: [i32; 3], + table: &str, + random: &mut impl RandomSource, + ) -> Result<(), PlacementQueryError> { + if self.get(p) == self.chest { + let seed = random.next_long(); + writeln!(self.out, "loot {} {} {} {table} {seed}", p[0], p[1], p[2]).map_err(query)?; + } + Ok(()) + } + fn configure_spawner(&mut self, p: [i32; 3], entity: &str) -> Result<(), PlacementQueryError> { + writeln!(self.out, "spawner {} {} {} {entity}", p[0], p[1], p[2]).map_err(query) + } fn generation(&self) -> WorldGenerationContext { WorldGenerationContext::new(MIN_Y, HEIGHT, 63) } @@ -217,7 +311,10 @@ fn fixture( let origin = std::array::from_fn(|i| f["origin"][i].as_i64().unwrap() as i32); match feature.place(world, &mut random, origin, blocks) { Ok(result) => writeln!(world.out, "place {result}")?, - Err(error) => writeln!(world.out, "place error {error}")?, + Err(error) => { + eprintln!("{name}: {error}"); + writeln!(world.out, "place error")? + } } writeln!(world.out, "next {}", random.next_long())?; let changes: Vec<_> = world @@ -232,6 +329,63 @@ fn fixture( writeln!(world.out, "end") } +fn survival_rule(rule: &str) -> SurvivalRule { + use SurvivalRule::*; + match rule { + value if value.starts_with("TagBelow:") => TagBelow(value[9..].to_owned()), + "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, + _ => panic!("unknown rule {rule}"), + } +} fn main() -> Result<(), Box> { let arg = std::env::args().nth(1).expect("private fixture directory"); let dir = Path::new(&arg); @@ -268,6 +422,7 @@ fn main() -> Result<(), Box> { serde_json::from_str(&fs::read_to_string(dir.join("vanilla-features.json"))?)?; let providers: BTreeMap = serde_json::from_value(bundle["providers"].clone())?; let features: BTreeMap = serde_json::from_value(bundle["features"].clone())?; + let placed: BTreeMap = serde_json::from_value(bundle["placed"].clone())?; let definitions: Value = serde_json::from_str(&fs::read_to_string(dir.join("placement-definitions.json"))?)?; let bindings = FeatureBlockBindings::with_tags(®istry, integers.clone(), &tags.tags)? @@ -285,7 +440,7 @@ fn main() -> Result<(), Box> { &serde_json::from_value(definitions["mossy_carpets"].clone())?, )?, )?; - let catalog = FeatureCatalog::from_resources(&features, &BTreeMap::new(), &TagDefinitions::default())?; + let catalog = FeatureCatalog::from_resources(&features, &placed, &TagDefinitions::default())?; let blocks = FeatureBlocks::from_registry(®istry)?; let fluids = FluidStateTable::new(®istry)?; let mut by_name = BTreeMap::>::new(); @@ -310,6 +465,36 @@ fn main() -> Result<(), Box> { }) .collect(); let support = Arc::new(support); + let definitions_text: BTreeMap = + serde_json::from_str(&fs::read_to_string(dir.join("survival-rules.json"))?)?; + let rules = definitions_text + .into_iter() + .map(|(name, rule)| (name, survival_rule(&rule))) + .collect(); + let extra: Value = serde_json::from_str(&fs::read_to_string( + dir.join("survival-extra-definitions.json"), + )?)?; + let survival_definitions = SurvivalDefinitions { + rules, + ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?, + fence_gates: serde_json::from_value(extra["fence_gates"].clone())?, + }; + let collision = Arc::new(BlockCollisionRegistry::new(Arc::new( + CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, ®istry)?, + ))?); + let survival = BlockSurvivalRegistry::new( + ®istry, + &properties, + support.clone(), + collision.clone(), + &survival_definitions, + &tags.tags, + &fluid_tags.tags, + )?; + let chest = registry.default_state("minecraft:chest").unwrap(); + let water_mask = fluid_tags.tags["minecraft:water"] + .iter() + .fold(0, |mask, name| mask | FluidKind::from_name(name).unwrap().mask()); let air = registry.default_state("minecraft:air").unwrap().0; let void_air = registry.default_state("minecraft:void_air").unwrap(); let mut out = io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); @@ -324,6 +509,12 @@ fn main() -> Result<(), Box> { fluids: &fluids, tags: &tag_states, support: &support, + survival: &survival, + collision: &collision, + seed: f["world_seed"].as_i64().unwrap_or(0), + chest, + world_random: LegacyRandom::new(0), + water_mask, }; let seed = f["seed"].as_i64().unwrap(); if f["legacy"].as_bool().unwrap() { diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 257e38b8b..deaf65dbe 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -26,6 +26,7 @@ pub mod decoration; pub mod delta; pub mod density; pub mod disk; +pub mod dripstone; pub mod end_gateway; pub mod end_podium; pub mod feature; diff --git a/crates/horizon-world/src/worldgen/dripstone.rs b/crates/horizon-world/src/worldgen/dripstone.rs new file mode 100644 index 000000000..5d773e880 --- /dev/null +++ b/crates/horizon-world/src/worldgen/dripstone.rs @@ -0,0 +1,754 @@ +//! `minecraft:speleothem_cluster` and `minecraft:large_dripstone` +//! (SpeleothemClusterFeature, LargeDripstoneFeature and SpeleothemUtils). +use super::{ + DecodeError, Object, int_range, number_text, optional, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + tree::{TreeDecoder, TreeResult, kind, read, unit_float, write}, + tree_blocks::{self as tb, TreeBlocks}, + value_provider::{FloatProvider, IntProvider}, +}; +use crate::{heightmap::HeightmapType, registry::BlockStateId}; +use horizon_core::{geometry::trig, random::RandomSource}; +use std::{collections::BTreeSet, sync::Arc}; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} +/// Column.scan result: optional floor and ceiling edge heights. +#[derive(Clone, Copy, Debug)] +struct Column { + floor: Option, + ceiling: Option, +} +impl Column { + fn height(&self) -> Option { + match (self.floor, self.ceiling) { + (Some(floor), Some(ceiling)) => Some(ceiling - floor - 1), + _ => None, + } + } +} + +/// Shared speleothem block classification. +#[derive(Clone, Debug)] +struct Speleothem { + base: BlockStateId, + pointed: BlockStateId, + replaceable: Arc>, + lava: BlockStateId, + blocks: Arc, +} +impl Speleothem { + fn new( + bindings: &FeatureBlockBindings<'_>, + base: BlockStateId, + pointed: BlockStateId, + replaceable: Arc>, + ) -> Result { + let registry = bindings.registry(); + let default = |state: BlockStateId| { + registry + .default_state(®istry.state(state).unwrap().name) + .ok_or(DecodeError::Field("speleothem block")) + }; + Ok(Self { + base: default(base)?, + pointed: default(pointed)?, + replaceable, + lava: registry + .default_state("minecraft:lava") + .ok_or(DecodeError::Field("lava"))?, + blocks: bindings.tree_blocks()?, + }) + } + fn empty_or_water(&self, s: BlockStateId) -> bool { + self.blocks.is_air(s) || self.blocks.has(s, tb::WATER_BLOCK) + } + fn empty_water_or_lava(&self, s: BlockStateId) -> bool { + self.empty_or_water(s) || self.blocks.same_block(s, self.lava) + } + fn is_base(&self, s: BlockStateId) -> bool { + self.blocks.same_block(s, self.base) || self.replaceable.contains(&s) + } + fn scan( + &self, + world: &mut W, + pos: [i32; 3], + range: i32, + edge: impl Fn(&Self, BlockStateId) -> bool, + ) -> TreeResult, W::Error> { + if !self.empty_or_water(read(world, pos)?) { + return Ok(None); + } + let mut scan = |step: i32| -> TreeResult, W::Error> { + let mut p = pos; + let mut i = 1; + while i < range && self.empty_or_water(read(world, p)?) { + p[1] = p[1].wrapping_add(step); + i += 1; + } + Ok(edge(self, read(world, p)?).then_some(p[1])) + }; + let ceiling = scan(1)?; + let floor = scan(-1)?; + Ok(Some(Column { floor, ceiling })) + } + fn pointed_state(&self, up: bool, thickness: &str) -> Option { + let state = self.blocks.with( + self.pointed, + "vertical_direction", + if up { "up" } else { "down" }, + )?; + self.blocks.with(state, "thickness", thickness) + } + /// SpeleothemUtils.growSpeleothem. + #[allow(clippy::too_many_arguments)] + fn grow( + &self, + world: &mut W, + start: [i32; 3], + up: bool, + height: i32, + merged: bool, + ) -> TreeResult<(), W::Error> { + let step = if up { 1 } else { -1 }; + if !self.is_base(read(world, tb::offset(start, 0, -step, 0))?) { + return Ok(()); + } + let mut sequence = Vec::new(); + if height >= 3 { + sequence.push("base"); + sequence.extend(std::iter::repeat_n("middle", (height - 3) as usize)); + } + if height >= 2 { + sequence.push("frustum"); + } + if height >= 1 { + sequence.push(if merged { "tip_merge" } else { "tip" }); + } + let mut p = start; + for thickness in sequence { + let mut state = self + .pointed_state(up, thickness) + .ok_or(FeatureExecutionError::InvalidState)?; + let water = self.blocks.has(read(world, p)?, tb::WATER_FLUID); + state = self.blocks.waterlogged(state, water); + write(world, p, state, 2)?; + p[1] = p[1].wrapping_add(step); + } + Ok(()) + } + fn place_base_if_possible( + &self, + world: &mut W, + p: [i32; 3], + ) -> TreeResult { + if self.replaceable.contains(&read(world, p)?) { + write(world, p, self.base, 2)?; + return Ok(true); + } + Ok(false) + } +} + +fn float_provider(raw: &serde_json::value::RawValue, low: f32, high: f32) -> Result { + let value = FloatProvider::from_json(raw.get())?; + let [min, max] = value.bounds(); + if min < low || max > high { + return Err(DecodeError::Field("float provider bounds")); + } + Ok(value) +} +fn float_range(raw: &serde_json::value::RawValue, name: &'static str, low: f32, high: f32) -> Result { + let value: f32 = number_text(raw)? + .parse() + .map_err(|_| DecodeError::Field(name))?; + if !(low..=high).contains(&value) { + return Err(DecodeError::Field(name)); + } + Ok(value) +} +fn block_state(bindings: &FeatureBlockBindings<'_>, raw: &serde_json::value::RawValue) -> Result { + bindings + .codec + .decode(raw.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) +} +fn clamped_lerp(factor: f64, min: f64, max: f64) -> f64 { + if factor < 0.0 { + min + } else if factor > 1.0 { + max + } else { + min + factor * (max - min) + } +} +fn clamped_lerp_f32(factor: f32, min: f32, max: f32) -> f32 { + if factor < 0.0 { + min + } else if factor > 1.0 { + max + } else { + min + factor * (max - min) + } +} + +#[derive(Clone, Debug)] +pub struct SpeleothemClusterFeature { + speleothem: Speleothem, + search_range: i32, + height: IntProvider, + radius: IntProvider, + max_height_diff: i32, + height_deviation: i32, + layer_thickness: IntProvider, + density: FloatProvider, + wetness: FloatProvider, + chance_at_max_distance: f32, + max_distance_from_edge: i32, + max_distance_from_center: i32, +} +impl SpeleothemClusterFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:speleothem_cluster" { + return Err(DecodeError::Field("speleothem cluster type")); + } + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let int = |name: &'static str, low: i32, high: i32| { + int_range(required(&object, name)?, name, low, high) + }; + Ok(Self { + speleothem: Speleothem::new( + bindings, + block_state(bindings, required(&object, "base_block")?)?, + block_state(bindings, required(&object, "pointed_block")?)?, + decoder.block_set(required(&object, "replaceable_blocks")?)?, + )?, + search_range: int("floor_to_ceiling_search_range", 1, 512)?, + height: decoder.int_provider(required(&object, "height")?, 1, 128)?, + radius: decoder.int_provider(required(&object, "radius")?, 1, 128)?, + max_height_diff: int("max_stalagmite_stalactite_height_diff", 0, 64)?, + height_deviation: int("height_deviation", 1, 64)?, + layer_thickness: decoder.int_provider( + required(&object, "speleothem_block_layer_thickness")?, + 0, + 128, + )?, + density: float_provider(required(&object, "density")?, 0.0, 2.0)?, + wetness: float_provider(required(&object, "wetness")?, 0.0, 2.0)?, + chance_at_max_distance: unit_float( + required(&object, "chance_of_speleothem_at_max_distance_from_center")?, + "chance_of_speleothem_at_max_distance_from_center", + )?, + max_distance_from_edge: int( + "max_distance_from_edge_affecting_chance_of_speleothem", + 1, + 64, + )?, + max_distance_from_center: int("max_distance_from_center_affecting_height_bias", 1, 64)?, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + if !self.speleothem.empty_or_water(read(world, origin)?) { + return Ok(false); + } + let height = self.height.sample(random)?; + let wetness = self.wetness.sample(random); + let density = self.density.sample(random); + let x_radius = self.radius.sample(random)?; + let z_radius = self.radius.sample(random)?; + for dx in -x_radius..=x_radius { + for dz in -z_radius..=z_radius { + let distance = (x_radius - dx.abs()).min(z_radius - dz.abs()); + let chance = f64::from(clamped_lerp_f32( + (distance as f32 - 0.0) / (self.max_distance_from_edge as f32 - 0.0), + self.chance_at_max_distance, + 1.0, + )); + let p = tb::offset(origin, dx, 0, dz); + self.column(world, random, p, dx, dz, wetness, chance, height, density)?; + } + } + Ok(true) + } + #[allow(clippy::too_many_arguments)] + fn column( + &self, + world: &mut W, + random: &mut R, + pos: [i32; 3], + dx: i32, + dz: i32, + chance_of_water: f32, + chance: f64, + cluster_height: i32, + density: f32, + ) -> TreeResult<(), W::Error> { + let s = &self.speleothem; + let Some(base_column) = s.scan(world, pos, self.search_range, |s, st| { + !s.empty_or_water(st) + })? + else { + return Ok(()); + }; + let ceiling = base_column.ceiling; + let base_floor = base_column.floor; + if ceiling.is_none() && base_floor.is_none() { + return Ok(()); + } + let want_pool = random.next_float() < chance_of_water; + let column = match base_floor { + Some(floor_y) + if want_pool && self.can_place_pool(world, [pos[0], floor_y, pos[2]])? => + { + let water = s + .blocks + .default_state("minecraft:water") + .ok_or(FeatureExecutionError::InvalidState)?; + write(world, [pos[0], floor_y, pos[2]], water, 2)?; + Column { + floor: Some(floor_y - 1), + ceiling, + } + } + _ => base_column, + }; + let floor = column.floor; + let want_stalactite = random.next_double() < chance; + let stalactite_height = match ceiling { + Some(c) + if want_stalactite + && !s.blocks.same_block(read(world, [pos[0], c, pos[2]])?, s.lava) => + { + let thickness = self.layer_thickness.sample(random)?; + self.replace_with_base(world, [pos[0], c, pos[2]], thickness, 1)?; + let max = match floor { + Some(f) => cluster_height.min(c - f), + None => cluster_height, + }; + self.speleothem_height(random, dx, dz, density, max)? + } + _ => 0, + }; + let want_stalagmite = random.next_double() < chance; + let stalagmite_height = match floor { + Some(f) + if want_stalagmite + && !s.blocks.same_block(read(world, [pos[0], f, pos[2]])?, s.lava) => + { + let thickness = self.layer_thickness.sample(random)?; + self.replace_with_base(world, [pos[0], f, pos[2]], thickness, -1)?; + if ceiling.is_some() { + let diff = self.max_height_diff; + 0.max(stalactite_height + random.next_int_bound(diff * 2 + 1)? - diff) + } else { + self.speleothem_height(random, dx, dz, density, cluster_height)? + } + } + _ => 0, + }; + let (actual_stalactite, actual_stalagmite) = match (ceiling, floor) { + (Some(c), Some(f)) if c - stalactite_height <= f + stalagmite_height => { + let lowest_bottom = (c - stalactite_height).max(f + 1); + let highest_top = (f + stalagmite_height).min(c - 1); + let bottom = random.next_int_bound(highest_top + 1 - lowest_bottom + 1)? + lowest_bottom; + (c - bottom, bottom - 1 - f) + } + _ => (stalactite_height, stalagmite_height), + }; + let merge = random.next_boolean() + && actual_stalactite > 0 + && actual_stalagmite > 0 + && column + .height() + .is_some_and(|h| actual_stalactite + actual_stalagmite == h); + if let Some(c) = ceiling { + s.grow(world, [pos[0], c - 1, pos[2]], false, actual_stalactite, merge)?; + } + if let Some(f) = floor { + s.grow(world, [pos[0], f + 1, pos[2]], true, actual_stalagmite, merge)?; + } + Ok(()) + } + fn speleothem_height( + &self, + random: &mut impl RandomSource, + dx: i32, + dz: i32, + density: f32, + max_height: i32, + ) -> TreeResult { + if random.next_float() > density { + return Ok(0); + } + let distance = dx.abs() + dz.abs(); + let mean = clamped_lerp( + (f64::from(distance) - 0.0) / (f64::from(self.max_distance_from_center) - 0.0), + f64::from(max_height) / 2.0, + 0.0, + ) as f32; + let value = mean + random.next_gaussian() as f32 * self.height_deviation as f32; + let clamped = if value < 0.0 { + 0.0 + } else { + value.min(max_height as f32) + }; + Ok(clamped as i32) + } + fn can_place_pool( + &self, + world: &mut W, + p: [i32; 3], + ) -> TreeResult { + let s = &self.speleothem; + let state = read(world, p)?; + if s.blocks.has(state, tb::WATER_BLOCK) + || s.blocks.same_block(state, s.base) + || s.blocks.same_block(state, s.pointed) + { + return Ok(false); + } + if s.blocks.has(read(world, tb::offset(p, 0, 1, 0))?, tb::WATER_FLUID) { + return Ok(false); + } + for direction in tb::HORIZONTAL { + if !self.adjacent_ok(world, tb::relative(p, direction, 1))? { + return Ok(false); + } + } + self.adjacent_ok(world, tb::offset(p, 0, -1, 0)) + } + fn adjacent_ok(&self, world: &mut W, p: [i32; 3]) -> TreeResult { + let state = read(world, p)?; + let b = &self.speleothem.blocks; + Ok(b.has(state, tb::BASE_STONE_OVERWORLD) || b.has(state, tb::WATER_FLUID)) + } + fn replace_with_base( + &self, + world: &mut W, + first: [i32; 3], + count: i32, + step: i32, + ) -> TreeResult<(), W::Error> { + let mut p = first; + for _ in 0..count { + if !self.speleothem.place_base_if_possible(world, p)? { + return Ok(()); + } + p[1] = p[1].wrapping_add(step); + } + Ok(()) + } +} + +#[derive(Clone, Debug)] +pub struct LargeDripstoneFeature { + speleothem: Speleothem, + search_range: i32, + column_radius: IntProvider, + height_scale: FloatProvider, + max_radius_ratio: f32, + stalactite_bluntness: FloatProvider, + stalagmite_bluntness: FloatProvider, + wind_speed: FloatProvider, + min_radius_for_wind: i32, + min_bluntness_for_wind: f32, +} +struct LargeDripstone { + root: [i32; 3], + up: bool, + radius: i32, + bluntness: f64, + scale: f64, +} +#[derive(Clone, Copy)] +struct Wind { + origin_y: i32, + speed: Option<[f64; 3]>, + max_offset: i32, +} +impl Wind { + fn offset(&self, p: [i32; 3]) -> [i32; 3] { + let Some(speed) = self.speed else { + return p; + }; + let dy = f64::from(self.origin_y.wrapping_sub(p[1])); + let clamp = |v: f64| { + let v = v.floor() as i32; + if v < -self.max_offset { + -self.max_offset + } else { + v.min(self.max_offset) + } + }; + tb::offset(p, clamp(speed[0] * dy), 0, clamp(speed[2] * dy)) + } +} +fn speleothem_height(distance: f64, radius: f64, scale: f64, bluntness: f64) -> f64 { + let distance = if distance < bluntness { bluntness } else { distance }; + let r = distance / radius * 0.384; + let part1 = 0.75 * r.powf(1.3333333333333333); + let part2 = r.powf(0.6666666666666666); + let part3 = 0.3333333333333333 * r.ln(); + let height = (scale * (part1 - part2 - part3)).max(0.0); + height / 0.384 * radius +} +impl LargeDripstone { + fn height_at(&self, radius: f32) -> i32 { + speleothem_height(f64::from(radius), f64::from(self.radius), self.scale, self.bluntness) as i32 + } +} +impl LargeDripstoneFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:large_dripstone" { + return Err(DecodeError::Field("large dripstone type")); + } + let registry = bindings.registry(); + let dripstone = registry + .default_state("minecraft:dripstone_block") + .ok_or(DecodeError::Field("dripstone block"))?; + let pointed = registry + .default_state("minecraft:pointed_dripstone") + .ok_or(DecodeError::Field("pointed dripstone"))?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + Ok(Self { + speleothem: Speleothem::new( + bindings, + dripstone, + pointed, + decoder.block_set(required(&object, "replaceable_blocks")?)?, + )?, + search_range: optional(&object, "floor_to_ceiling_search_range") + .map(|raw| int_range(raw, "floor_to_ceiling_search_range", 1, 512)) + .transpose()? + .unwrap_or(30), + column_radius: decoder.int_provider(required(&object, "column_radius")?, 1, 16)?, + height_scale: float_provider(required(&object, "height_scale")?, 0.0, 20.0)?, + max_radius_ratio: float_range( + required(&object, "max_column_radius_to_cave_height_ratio")?, + "max_column_radius_to_cave_height_ratio", + 0.1, + 1.0, + )?, + stalactite_bluntness: float_provider( + required(&object, "stalactite_bluntness")?, + 0.1, + 10.0, + )?, + stalagmite_bluntness: float_provider( + required(&object, "stalagmite_bluntness")?, + 0.1, + 10.0, + )?, + wind_speed: float_provider(required(&object, "wind_speed")?, 0.0, 2.0)?, + min_radius_for_wind: int_range( + required(&object, "min_radius_for_wind")?, + "min_radius_for_wind", + 0, + 100, + )?, + min_bluntness_for_wind: float_range( + required(&object, "min_bluntness_for_wind")?, + "min_bluntness_for_wind", + 0.0, + 5.0, + )?, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let s = &self.speleothem; + if !s.empty_or_water(read(world, origin)?) { + return Ok(false); + } + let Some(column) = s.scan(world, origin, self.search_range, |s, st| { + s.is_base(st) || s.blocks.same_block(st, s.lava) + })? + else { + return Ok(false); + }; + let (Some(floor), Some(ceiling)) = (column.floor, column.ceiling) else { + return Ok(false); + }; + let height = ceiling - floor - 1; + if height < 4 { + return Ok(false); + } + let by_height = (height as f32 * self.max_radius_ratio) as i32; + let [min_r, max_r] = self.column_radius.bounds(); + let max_radius = if by_height < min_r { min_r } else { by_height.min(max_r) }; + let radius = random.next_int_bound(max_radius - min_r + 1)? + min_r; + let mut stalactite = LargeDripstone { + root: [origin[0], ceiling - 1, origin[2]], + up: false, + radius, + bluntness: f64::from(self.stalactite_bluntness.sample(random)), + scale: f64::from(self.height_scale.sample(random)), + }; + let mut stalagmite = LargeDripstone { + root: [origin[0], floor + 1, origin[2]], + up: true, + radius, + bluntness: f64::from(self.stalagmite_bluntness.sample(random)), + scale: f64::from(self.height_scale.sample(random)), + }; + let suitable = |d: &LargeDripstone| { + d.radius >= self.min_radius_for_wind && d.bluntness >= f64::from(self.min_bluntness_for_wind) + }; + let wind = if suitable(&stalactite) && suitable(&stalagmite) { + let speed = self.wind_speed.sample(random); + let direction = random.next_float() * (std::f32::consts::PI - 0.0) + 0.0; + Wind { + origin_y: origin[1], + speed: Some([ + f64::from(trig::cos(f64::from(direction)) * speed), + 0.0, + f64::from(trig::sin(f64::from(direction)) * speed), + ]), + max_offset: 16 - radius, + } + } else { + Wind { + origin_y: 0, + speed: None, + max_offset: 0, + } + }; + let top = self.move_back(world, &mut stalactite, wind)?; + let bottom = self.move_back(world, &mut stalagmite, wind)?; + if top { + self.place_blocks(world, random, &stalactite, wind)?; + } + if bottom { + self.place_blocks(world, random, &stalagmite, wind)?; + } + Ok(true) + } + fn move_back( + &self, + world: &mut W, + d: &mut LargeDripstone, + wind: Wind, + ) -> TreeResult { + let s = &self.speleothem; + while d.radius > 1 { + let mut root = d.root; + let tries = 10.min(d.height_at(0.0)); + for _ in 0..tries { + if s.blocks.same_block(read(world, root)?, s.lava) { + return Ok(false); + } + if self.circle_embedded(world, wind.offset(root), d.radius)? { + d.root = root; + return Ok(true); + } + root[1] = root[1].wrapping_add(if d.up { -1 } else { 1 }); + } + d.radius /= 2; + } + Ok(false) + } + fn circle_embedded( + &self, + world: &mut W, + center: [i32; 3], + radius: i32, + ) -> TreeResult { + let s = &self.speleothem; + if s.empty_water_or_lava(read(world, center)?) { + return Ok(false); + } + let increment = 6.0f32 / radius as f32; + let mut angle = 0.0f32; + while angle < (std::f64::consts::PI * 2.0) as f32 { + let dx = (trig::cos(f64::from(angle)) * radius as f32) as i32; + let dz = (trig::sin(f64::from(angle)) * radius as f32) as i32; + if s.empty_water_or_lava(read(world, tb::offset(center, dx, 0, dz))?) { + return Ok(false); + } + angle += increment; + } + Ok(true) + } + fn place_blocks( + &self, + world: &mut W, + random: &mut R, + d: &LargeDripstone, + wind: Wind, + ) -> TreeResult<(), W::Error> { + let s = &self.speleothem; + for dx in -d.radius..=d.radius { + for dz in -d.radius..=d.radius { + let current = ((dx * dx + dz * dz) as f32).sqrt(); + if current > d.radius as f32 { + continue; + } + let mut height = d.height_at(current); + if height <= 0 { + continue; + } + if f64::from(random.next_float()) < 0.2 { + let factor = random.next_float() * (1.0f32 - 0.8f32) + 0.8f32; + height = (height as f32 * factor) as i32; + } + let mut pos = tb::offset(d.root, dx, 0, dz); + let mut out_of_stone = false; + let max_y = if d.up { + world + .height(HeightmapType::WorldSurfaceWg, pos[0], pos[2]) + .map_err(query)? + } else { + i32::MAX + }; + let mut i = 0; + while i < height && pos[1] < max_y { + let adjusted = wind.offset(pos); + let state = read(world, adjusted)?; + if s.empty_water_or_lava(state) { + out_of_stone = true; + write(world, adjusted, s.base, 2)?; + } else if out_of_stone && s.blocks.has(state, tb::BASE_STONE_OVERWORLD) { + break; + } + pos[1] = pos[1].wrapping_add(if d.up { 1 } else { -1 }); + i += 1; + } + } + } + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 340f6bcef..c93029640 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -77,6 +77,8 @@ pub enum FeatureDefinition { Geode(Box), Iceberg(Box), RootSystem(Box), + SpeleothemCluster(Box), + LargeDripstone(Box), FallenTree(Box), NoOp, WeightedChoice(OptionalWeightedList), @@ -612,6 +614,20 @@ impl FeatureDefinition { remaining, ) .map(|f| Self::Geode(Box::new(f))), + "minecraft:speleothem_cluster" => super::dripstone::SpeleothemClusterFeature::decode( + json, + blocks.ok_or(DecodeError::Field("speleothem cluster bindings"))?, + depth, + remaining, + ) + .map(|f| Self::SpeleothemCluster(Box::new(f))), + "minecraft:large_dripstone" => super::dripstone::LargeDripstoneFeature::decode( + json, + blocks.ok_or(DecodeError::Field("large dripstone bindings"))?, + depth, + remaining, + ) + .map(|f| Self::LargeDripstone(Box::new(f))), "minecraft:iceberg" => super::iceberg::IcebergFeature::decode( json, blocks.ok_or(DecodeError::Field("iceberg bindings"))?, @@ -964,6 +980,8 @@ impl FeatureDefinition { Self::MonsterRoom(feature) => feature.place(world, random, origin), Self::Geode(feature) => feature.place(world, random, origin), Self::Iceberg(feature) => feature.place(world, random, origin), + Self::SpeleothemCluster(feature) => feature.place(world, random, origin), + Self::LargeDripstone(feature) => feature.place(world, random, origin), Self::RootSystem(feature) => { feature.place(world, random, origin, &mut |f, w, r, p| { f.place_in(&mut placer, w, r, p, run) diff --git a/crates/horizon-world/src/worldgen/tree_blocks.rs b/crates/horizon-world/src/worldgen/tree_blocks.rs index 2ab24a0a0..b4336b8de 100644 --- a/crates/horizon-world/src/worldgen/tree_blocks.rs +++ b/crates/horizon-world/src/worldgen/tree_blocks.rs @@ -41,6 +41,7 @@ pub(crate) const SPAWNER: u32 = 1 << 25; pub(crate) const FLUID_SOURCE: u32 = 1 << 26; /// Fluid amount 8 (sources and falling fluids). pub(crate) const FLUID_FULL: u32 = 1 << 27; +pub(crate) const BASE_STONE_OVERWORLD: u32 = 1 << 28; /// Immutable per-state facts. Missing tags or blocks are empty classifications. pub struct TreeBlocks { @@ -132,6 +133,11 @@ impl TreeBlocks { &mut flags, ); mark_tag("minecraft:fire", FIRE, &mut flags); + mark_tag( + "minecraft:base_stone_overworld", + BASE_STONE_OVERWORLD, + &mut flags, + ); mark_tag( "minecraft:features_cannot_replace", FEATURES_CANNOT_REPLACE, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java index 34b5da571..496a4ce20 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java @@ -38,15 +38,18 @@ public final class VanillaTreeFeatureOracle { } /** Shared with the Rust fixture: layered column, pseudo-random holes and obstacles, overrides. */ static final class Terrain { - final int[][] layers;final int holeMod,holeState,obstacleMod,obstacleState,obstacleMin;final Map overrides=new HashMap<>(); + final int[][] layers;final int[][] boxes;final int holeMod,holeState,obstacleMod,obstacleState,obstacleMin;final Map overrides=new HashMap<>(); Terrain(JsonObject f){ var raw=f.getAsJsonArray("layers");layers=new int[raw.size()][];for(int i=0;i>>13;h*=0x5bd1e995;h^=h>>>15;return h&0x7fffffff;} int at(int x,int y,int z){ var o=overrides.get(new BlockPos(x,y,z));if(o!=null)return o; + for(var b:boxes)if(x>=b[0]&&y>=b[1]&&z>=b[2]&&x<=b[3]&&y<=b[4]&&z<=b[5])return b[6]; int base=-1;for(var l:layers)if(y<=l[0]){base=l[1];break;} int h=hash(x,y,z); if(base>=0){if(holeMod>0&&h%holeMod==0)return holeState;return base;} @@ -55,7 +58,7 @@ public final class VanillaTreeFeatureOracle { } } private static final class World implements InvocationHandler { - final JsonObject f;final PrintWriter out;final Terrain terrain;final Map chunks=new HashMap<>();final Map hives=new HashMap<>(); + final JsonObject f;final PrintWriter out;final Terrain terrain;final Map chunks=new HashMap<>();final Map hives=new HashMap<>();final Map chests=new HashMap<>();final Map spawners=new HashMap<>(); final RandomSource shapeRandom=RandomSource.create(0); World(JsonObject f,PrintWriter out){this.f=f;this.out=out;this.terrain=new Terrain(f);} ProtoChunk chunk(int cx,int cz){ @@ -81,12 +84,17 @@ public final class VanillaTreeFeatureOracle { case "isFluidAtPosition":return ((java.util.function.Predicate)args[1]).test(get((BlockPos)args[0]).getFluidState()); case "getMinY":return MIN_Y; case "getSeaLevel":return 63; + case "getRawBrightness":case "getMaxLocalRawBrightness":return 15; + case "getBrightness":return 15; + case "getSeed":return f.get("world_seed").getAsLong(); case "ensureCanWrite":return true; case "getRandom":return shapeRandom; - case "scheduleTick":return null; + case "scheduleTick":return null; // Edge shape updates also schedule ticks; not compared. case "setCurrentlyGenerating":return null; case "getBlockEntity":{ if(args.length!=1)break;var p=((BlockPos)args[0]).immutable();var state=get(p); + if(state.is(Blocks.CHEST))return chests.computeIfAbsent(p,key->new ChestBlockEntity(key,state){@Override public void setLootTable(net.minecraft.resources.ResourceKey table,long seed){out.println("loot "+xyz(key)+" "+table.identifier()+" "+seed);super.setLootTable(table,seed);}}); + if(state.is(Blocks.SPAWNER))return spawners.computeIfAbsent(p,key->new SpawnerBlockEntity(key,state){@Override public void setEntityId(net.minecraft.world.entity.EntityType type,RandomSource r){super.setEntityId(type,r);out.println("spawner "+xyz(key)+" "+BuiltInRegistries.ENTITY_TYPE.getKey(type));}}); if(!state.is(Blocks.BEE_NEST))return null; return hives.computeIfAbsent(p,key->new BeehiveBlockEntity(key,state){@Override public void storeBee(BeehiveBlockEntity.Occupant occupant){out.println("bee "+xyz(key)+" "+occupant.ticksInHive());}}); } @@ -106,6 +114,21 @@ public final class VanillaTreeFeatureOracle { throw new AssertionError(method); } } + /** Parses named holders on first use from the bundled vanilla resources. */ + static final class Lazy implements HolderGetter, HolderOwner { + JsonObject json;com.mojang.serialization.Codec codec;RegistryOps ops;final Map,Holder.Reference> cache=new HashMap<>(); + public Optional> get(ResourceKey key){ + var cached=cache.get(key);if(cached!=null)return Optional.of(cached); + var text=json.get(key.identifier().toString());if(text==null)return Optional.empty(); + var ref=Holder.Reference.createStandAlone(this,key);cache.put(key,ref); + T value=codec.parse(ops,JsonParser.parseString(text.getAsString())).getOrThrow(); + try{var bind=Holder.Reference.class.getDeclaredMethod("bindValue",Object.class);bind.setAccessible(true);bind.invoke(ref,value);}catch(ReflectiveOperationException e){throw new IllegalStateException(e);} + return Optional.of(ref); + } + public Optional> get(net.minecraft.tags.TagKey tag){return Optional.empty();} + } + static final Lazy lazyFeatures=new Lazy<>(); + static final Lazy lazyPlaced=new Lazy<>(); @SuppressWarnings("unchecked") public static void main(String[] args)throws Exception { net.minecraft.SharedConstants.tryDetectVersion();net.minecraft.server.Bootstrap.bootStrap();Path dir=Path.of(args[1]); @@ -114,6 +137,8 @@ public final class VanillaTreeFeatureOracle { var providers=new MappedRegistry(Registries.BLOCK_STATE_PROVIDER,com.mojang.serialization.Lifecycle.stable()); var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public Optional> lookup(ResourceKey> key){ if(key.equals(Registries.BLOCK_STATE_PROVIDER))return (Optional>)(Optional)Optional.of(providers); + if(key.equals(Registries.FEATURE))return (Optional>)(Optional)Optional.of(lazyFeatures); + if(key.equals(Registries.PLACED_FEATURE))return (Optional>)(Optional)Optional.of(lazyPlaced); if(key.equals(Registries.FLUID))return (Optional>)(Optional)Optional.of(BuiltInRegistries.FLUID); return key.equals(Registries.BLOCK)?(Optional>)(Optional)Optional.of(BuiltInRegistries.BLOCK):Optional.empty(); }}); @@ -121,7 +146,11 @@ public final class VanillaTreeFeatureOracle { for(var entry:bundle.getAsJsonObject("providers").entrySet()) providers.register(ResourceKey.create(Registries.BLOCK_STATE_PROVIDER,Identifier.parse(entry.getKey())),BlockStateProvider.DIRECT_CODEC.parse(ops,JsonParser.parseString(entry.getValue().getAsString())).getOrThrow(),RegistrationInfo.BUILT_IN); providers.freeze(); - var features=bundle.getAsJsonObject("features"); + var features=bundle.getAsJsonObject("features");var placedJson=bundle.getAsJsonObject("placed"); + lazyFeatures.json=features;lazyPlaced.json=placedJson;lazyFeatures.codec=Feature.DIRECT_CODEC;lazyPlaced.codec=net.minecraft.world.level.levelgen.placement.PlacedFeature.DIRECT_CODEC;lazyFeatures.ops=ops;lazyPlaced.ops=ops; + var contextMethod=VanillaPlacementOracle.class.getDeclaredMethod("context",JsonObject.class);contextMethod.setAccessible(true); + var bounds=new JsonObject();bounds.add("context",JsonParser.parseString("[-64,384,63]")); + var generator=((net.minecraft.world.level.levelgen.placement.PlacementContext)contextMethod.invoke(null,bounds)).generator(); try(var out=new PrintWriter(Files.newBufferedWriter(dir.resolve(args[0]+".txt")));var inputs=Files.lines(dir.resolve("inputs.txt"))) { for(var line:(Iterable)inputs::iterator){ var f=JsonParser.parseString(line).getAsJsonObject();long seed=f.get("seed").getAsLong(); @@ -131,7 +160,7 @@ public final class VanillaTreeFeatureOracle { try{decoded=Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(features.get(f.get("feature").getAsString()).getAsString())).result();}catch(RuntimeException error){decoded=Optional.empty();} if(decoded.isEmpty()){out.println("decode error");continue;} var handler=new World(f,out);var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},handler); - try{out.println("place "+decoded.get().place(world,null,random,pos(f.getAsJsonArray("origin"))));}catch(RuntimeException error){out.println("place error "+error);} + try{out.println("place "+decoded.get().place(world,generator,random,pos(f.getAsJsonArray("origin"))));}catch(RuntimeException error){out.println("place error");System.err.println(f.get("feature").getAsString()+": "+error);} out.println("next "+random.nextLong()); var keys=new ArrayList<>(handler.chunks.keySet());keys.sort(Comparator.comparingInt(ChunkPos::x).thenComparingInt(ChunkPos::z)); var changes=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 6886044e1..2135c0b9e 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -18,9 +18,9 @@ except ImportError: def feature_resources(jar): """Vanilla configured features and named state providers from the authenticated JAR.""" - result={'features':{},'providers':{}} + result={'features':{},'providers':{},'placed':{}} with zipfile.ZipFile(jar) as archive: - for kind,key in [('feature','features'),('block_state_provider','providers')]: + for kind,key in [('feature','features'),('block_state_provider','providers'),('placed_feature','placed')]: prefix=f'data/minecraft/worldgen/{kind}/' for name in sorted(archive.namelist()): if name.startswith(prefix) and name.endswith('.json'): @@ -38,16 +38,17 @@ def corpus(facts,resources): def fixture(feature,**extra): f={'feature':feature,'seed':0,'legacy':False,'origin':[8,65,8],'height':65,'layers':[[59,get('stone')],[63,get('dirt')],[64,get('grass_block')]], 'hole_mod':0,'hole_state':get('air'),'obstacle_mod':0,'obstacle_state':get('air'),'obstacle_min':0,'states':[]} - f.update(extra);return f + f.update(extra);f.setdefault('world_seed',f['seed']^0x2545F4914F6CDD1D);return f seeds=[0,1,-1,0x5DEECE66D,0x123456789abcdef,-8070450532247928832] origins=[[8,65,8],[15,65,0],[0,65,15],[-1,65,-17],[31,65,-16],[100003,65,-4097]] - trees,ores=[],[] + trees,ores,others=[],[],[] for name,text in resources['features'].items(): value=json.loads(text);kind=value['type'].removeprefix('minecraft:') if kind in ('tree','fallen_tree'): if 'pale_moss' in text:continue # needs the level's feature registry and server level trees.append(name) elif kind in ('ore','scattered_ore'):ores.append(name) + elif kind not in ('freeze_top_layer',):others.append(name) worlds=[ {}, {'obstacle_mod':37,'obstacle_state':get('oak_leaves'),'obstacle_min':66}, @@ -75,6 +76,21 @@ def corpus(facts,resources): origin=list(origins[(s+w)%len(origins)]);origin[1]=[-60,-3,0,40,316,-64][(s*5+w)%6] yield fixture(name,seed=seed,legacy=s%3==2,origin=origin,**world) + air,water,stone=get('air'),get('water'),get('stone') + generic_worlds=[ + ({},[65]), + ({'layers':[[200,stone]],'height':201,'boxes':[[-40,20,-40,56,35,56,air]]},[20,35,27]), + ({'layers':[[200,stone]],'height':201,'boxes':[[-40,23,-40,56,35,56,air],[-40,20,-40,56,22,56,water]]},[21,23]), + ({'layers':[[35,stone],[39,get('sand')],[62,water]],'height':40},[40,63]), + ({'layers':[[31,get('lava')],[100,get('netherrack')]],'height':101,'boxes':[[-40,32,-40,56,60,56,air]]},[32,60]), + ] + for name in others: + for w,(world,ys) in enumerate(generic_worlds): + for y in ys: + for s,seed in enumerate(seeds[:4]): + origin=list(origins[(s+w)%len(origins)]);origin[1]=y + yield fixture(name,seed=seed,legacy=s%3==2,origin=origin,**world) + def main(): parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--prepare',action='store_true');args=parser.parse_args() @@ -100,6 +116,7 @@ def main(): if path.read_bytes()!=(build/'client-definitions'/path.name).read_bytes():raise ValueError('reference definitions differ: '+path.name) (build/path.name).write_bytes(path.read_bytes()) facts=json.loads((build/'facts.json').read_text()) + rules=survival.bind_definitions(*[json.loads((build/name).read_text()) for name in ['survival-classes.json','survival-placement-classes.json','survival-support-tags.json']]);(build/'survival-rules.json').write_text(json.dumps(rules,separators=(',',':'))) inputs=build/'inputs.txt';count=0 with inputs.open('w',encoding='utf-8') as output: for fixture in corpus(facts,resources):output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 From 3adb14529b6d5c4296c15e4ac47efef0de5fdf6b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:23:53 +0200 Subject: [PATCH 06/12] WIP: checkpoint interrupted agent work Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/feature_graph.rs | 22 ++ .../horizon-world/src/worldgen/projected.rs | 272 ++++++++++++++++++ 3 files changed, 295 insertions(+) create mode 100644 crates/horizon-world/src/worldgen/projected.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index deaf65dbe..3dab5edb8 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -43,6 +43,7 @@ pub mod material_stage; pub mod material_surface; pub mod ore_feature; pub mod placement; +pub mod projected; pub mod replace_blobs; pub mod root_system; pub mod router; diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index c93029640..78afbdbed 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -79,6 +79,8 @@ pub enum FeatureDefinition { RootSystem(Box), SpeleothemCluster(Box), LargeDripstone(Box), + ProjectedPatchySquare(Box), + SteppedColumnCluster(Box), FallenTree(Box), NoOp, WeightedChoice(OptionalWeightedList), @@ -628,6 +630,24 @@ impl FeatureDefinition { remaining, ) .map(|f| Self::LargeDripstone(Box::new(f))), + "minecraft:projected_random_patchy_square" => { + super::projected::ProjectedPatchySquareFeature::decode( + json, + blocks.ok_or(DecodeError::Field("patchy square bindings"))?, + depth, + remaining, + ) + .map(|f| Self::ProjectedPatchySquare(Box::new(f))) + } + "minecraft:stepped_column_cluster" => { + super::projected::SteppedColumnClusterFeature::decode( + json, + blocks.ok_or(DecodeError::Field("column cluster bindings"))?, + depth, + remaining, + ) + .map(|f| Self::SteppedColumnCluster(Box::new(f))) + } "minecraft:iceberg" => super::iceberg::IcebergFeature::decode( json, blocks.ok_or(DecodeError::Field("iceberg bindings"))?, @@ -982,6 +1002,8 @@ impl FeatureDefinition { Self::Iceberg(feature) => feature.place(world, random, origin), Self::SpeleothemCluster(feature) => feature.place(world, random, origin), Self::LargeDripstone(feature) => feature.place(world, random, origin), + Self::ProjectedPatchySquare(feature) => feature.place(world, random, origin), + Self::SteppedColumnCluster(feature) => feature.place(world, random, origin), Self::RootSystem(feature) => { feature.place(world, random, origin, &mut |f, w, r, p| { f.place_in(&mut placer, w, r, p, run) diff --git a/crates/horizon-world/src/worldgen/projected.rs b/crates/horizon-world/src/worldgen/projected.rs new file mode 100644 index 000000000..a8ba00c9b --- /dev/null +++ b/crates/horizon-world/src/worldgen/projected.rs @@ -0,0 +1,272 @@ +//! 26.3 projection-style features: `minecraft:projected_random_patchy_square` +//! and `minecraft:stepped_column_cluster` (basalt columns). +use super::{ + DecodeError, Object, int_range, + block_feature::FeatureBlockBindings, + block_predicate::BlockPredicate, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + state_provider::BlockStateProvider, + tree::{TreeDecoder, TreeResult, kind, read, sample_optional, sample_state, write}, + tree_blocks::{self as tb, TreeBlocks}, + value_provider::IntProvider, +}; +use crate::registry::BlockStateId; +use horizon_core::random::RandomSource; +use std::{collections::BTreeSet, sync::Arc}; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} +fn predicate( + object: &Object, + name: &'static str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, +) -> Result { + BlockPredicate::decode_with_blocks( + required(object, name)?.get(), + depth + 1, + remaining, + Some(bindings), + ) +} + +#[derive(Clone, Debug)] +pub struct ProjectedPatchySquareFeature { + block: BlockStateProvider, + project_through: BlockPredicate, + size: IntProvider, + max_projection_height: i32, +} +impl ProjectedPatchySquareFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:projected_random_patchy_square" { + return Err(DecodeError::Field("projected patchy square type")); + } + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let block = decoder.provider(required(&object, "block")?)?; + let size = decoder.int_provider(required(&object, "size")?, 1, 16)?; + Ok(Self { + block, + size, + project_through: predicate(&object, "project_through", bindings, depth, remaining)?, + max_projection_height: int_range( + required(&object, "max_projection_height")?, + "max_projection_height", + 0, + i32::MAX, + )?, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let size = self.size.sample(random)?; + let bound = size.wrapping_mul(size).wrapping_add(1); + for dx in -size..=size { + for dz in -size..=size { + let probability = dx.abs().wrapping_mul(dz.abs()); + if random.next_int_bound(bound)? < bound.wrapping_sub(probability) { + let mut base = tb::offset(origin, dx, 0, dz); + let mut drop = self.max_projection_height; + while self + .project_through + .test(world, tb::offset(base, 0, -1, 0)) + .map_err(query)? + { + base = tb::offset(base, 0, -1, 0); + drop -= 1; + if drop <= 0 { + break; + } + } + if let Some(state) = sample_optional(&self.block, world, random, base)? { + write(world, base, state, 2)?; + } + } + } + } + Ok(true) + } +} + +#[derive(Clone, Debug)] +pub struct SteppedColumnClusterFeature { + block: BlockStateProvider, + continue_through: BlockPredicate, + can_replace: BlockPredicate, + cannot_place_on: Arc>, + cluster_reach: IntProvider, + column_count: IntProvider, + column_reach: IntProvider, + height: IntProvider, + blocks: Arc, +} +impl SteppedColumnClusterFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:stepped_column_cluster" { + return Err(DecodeError::Field("stepped column cluster type")); + } + let blocks = bindings.tree_blocks()?; + let mut decoder = TreeDecoder { + bindings, + depth, + remaining, + }; + let block = decoder.provider(required(&object, "block")?)?; + let cannot_place_on = decoder.block_set(required(&object, "cannot_place_on")?)?; + let cluster_reach = decoder.int_provider(required(&object, "cluster_reach")?, 0, 13)?; + let column_count = decoder.int_provider(required(&object, "column_count")?, 1, 150)?; + let column_reach = decoder.int_provider(required(&object, "column_reach")?, 0, 3)?; + let height = decoder.int_provider(required(&object, "height")?, 1, 10)?; + Ok(Self { + block, + continue_through: predicate(&object, "continue_through", bindings, depth, remaining)?, + can_replace: predicate(&object, "can_replace", bindings, depth, remaining)?, + cannot_place_on, + cluster_reach, + column_count, + column_reach, + height, + blocks, + }) + } + fn can_place_at( + &self, + world: &mut W, + p: [i32; 3], + ) -> TreeResult { + if !self.can_replace.test(world, p).map_err(query)? { + return Ok(false); + } + let below = read(world, tb::offset(p, 0, -1, 0))?; + Ok(!self.blocks.is_air(below) && !self.cannot_place_on.contains(&below)) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + if !self.can_place_at(world, origin)? { + return Ok(false); + } + let column_height = self.height.sample(random)?; + let reach = column_height.min(self.cluster_reach.sample(random)?); + let count = self.column_count.sample(random)?; + let width = reach.wrapping_mul(2).wrapping_add(1); + let mut placed = false; + for _ in 0..count { + let x = origin[0].wrapping_sub(reach).wrapping_add(random.next_int_bound(width)?); + let y = origin[1].wrapping_add(random.next_int_bound(1)?); + let z = origin[2].wrapping_sub(reach).wrapping_add(random.next_int_bound(width)?); + let pos = [x, y, z]; + let blocks_y = column_height - tb::dist_manhattan(pos, origin); + if blocks_y >= 0 { + let column_reach = self.column_reach.sample(random)?; + placed |= self.place_column(world, random, pos, blocks_y, column_reach)?; + } + } + Ok(placed) + } + fn place_column( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + column_height: i32, + reach: i32, + ) -> TreeResult { + let mut placed = false; + // BlockPos.betweenClosed over a single layer: x fastest, then z. + for dz in -reach..=reach { + for dx in -reach..=reach { + let pos = tb::offset(origin, dx, 0, dz); + let step_limit = tb::dist_manhattan(pos, origin); + let column = if self.can_replace.test(world, pos).map_err(query)? { + self.find_surface(world, pos, step_limit)? + } else { + self.find_air(world, pos, step_limit)? + }; + let Some(mut cursor) = column else { + continue; + }; + let mut blocks_y = column_height - step_limit / 2; + while blocks_y >= 0 { + if self.can_replace.test(world, cursor).map_err(query)? { + let state = sample_state(&self.block, world, random, cursor)?; + write(world, cursor, state, 3)?; + cursor = tb::offset(cursor, 0, 1, 0); + placed = true; + } else { + if !self.continue_through.test(world, cursor).map_err(query)? { + break; + } + cursor = tb::offset(cursor, 0, 1, 0); + } + blocks_y -= 1; + } + } + } + Ok(placed) + } + fn find_surface( + &self, + world: &mut W, + mut cursor: [i32; 3], + mut limit: i32, + ) -> TreeResult, W::Error> { + let min_y = world.min_y().map_err(query)?; + while cursor[1] > min_y.wrapping_add(1) && limit > 0 { + limit -= 1; + if self.can_place_at(world, cursor)? { + return Ok(Some(cursor)); + } + cursor = tb::offset(cursor, 0, -1, 0); + } + Ok(None) + } + fn find_air( + &self, + world: &mut W, + mut cursor: [i32; 3], + mut limit: i32, + ) -> TreeResult, W::Error> { + let max_y = world.max_y().map_err(query)?; + while cursor[1] <= max_y && limit > 0 { + limit -= 1; + let state = read(world, cursor)?; + if self.cannot_place_on.contains(&state) { + return Ok(None); + } + if self.blocks.is_air(state) { + return Ok(Some(cursor)); + } + cursor = tb::offset(cursor, 0, 1, 0); + } + Ok(None) + } +} From df8d9d7184faf04a7f58f30488aaad4de505efdd Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:30:48 +0200 Subject: [PATCH 07/12] WIP: checkpoint remaining interrupted agent changes Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/feature_graph.rs | 9 + crates/horizon-world/src/worldgen/fungus.rs | 285 ++++++++++++++++++ .../parity/VanillaTreeFeatureOracle.java | 4 +- tools/test_tree_feature_parity.py | 2 +- 5 files changed, 298 insertions(+), 3 deletions(-) create mode 100644 crates/horizon-world/src/worldgen/fungus.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 3dab5edb8..3d5445447 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -35,6 +35,7 @@ pub mod feature_graph; pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; +pub mod fungus; pub mod height_provider; pub mod iceberg; pub mod material_condition; diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 78afbdbed..89e739e4e 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -79,6 +79,7 @@ pub enum FeatureDefinition { RootSystem(Box), SpeleothemCluster(Box), LargeDripstone(Box), + HugeFungus(Box), ProjectedPatchySquare(Box), SteppedColumnCluster(Box), FallenTree(Box), @@ -648,6 +649,13 @@ impl FeatureDefinition { ) .map(|f| Self::SteppedColumnCluster(Box::new(f))) } + "minecraft:huge_fungus" => super::fungus::HugeFungusFeature::decode( + json, + blocks.ok_or(DecodeError::Field("huge fungus bindings"))?, + depth, + remaining, + ) + .map(|f| Self::HugeFungus(Box::new(f))), "minecraft:iceberg" => super::iceberg::IcebergFeature::decode( json, blocks.ok_or(DecodeError::Field("iceberg bindings"))?, @@ -1002,6 +1010,7 @@ impl FeatureDefinition { Self::Iceberg(feature) => feature.place(world, random, origin), Self::SpeleothemCluster(feature) => feature.place(world, random, origin), Self::LargeDripstone(feature) => feature.place(world, random, origin), + Self::HugeFungus(feature) => feature.place(world, random, origin), Self::ProjectedPatchySquare(feature) => feature.place(world, random, origin), Self::SteppedColumnCluster(feature) => feature.place(world, random, origin), Self::RootSystem(feature) => { diff --git a/crates/horizon-world/src/worldgen/fungus.rs b/crates/horizon-world/src/worldgen/fungus.rs new file mode 100644 index 000000000..db77e841d --- /dev/null +++ b/crates/horizon-world/src/worldgen/fungus.rs @@ -0,0 +1,285 @@ +//! `minecraft:huge_fungus` (crimson and warped fungi, natural and planted). +use super::{ + DecodeError, Object, optional, + block_feature::FeatureBlockBindings, + block_predicate::BlockPredicate, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + tree::{TreeResult, kind, read, write}, + tree_blocks::{self as tb, TreeBlocks}, +}; +use crate::registry::BlockStateId; +use horizon_core::random::RandomSource; +use std::sync::Arc; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} +/// Mth.nextInt(random, min, max). +fn next_int(random: &mut impl RandomSource, min: i32, max: i32) -> TreeResult { + if min >= max { + Ok(min) + } else { + Ok(random.next_int_bound(max - min + 1)? + min) + } +} + +#[derive(Clone, Debug)] +pub struct HugeFungusFeature { + valid_base: BlockStateId, + stem: BlockStateId, + hat: BlockStateId, + decor: BlockStateId, + replaceable: BlockPredicate, + planted: bool, + air: BlockStateId, + weeping_vines: BlockStateId, + weeping_vines_plant: BlockStateId, + nether_wart_block: BlockStateId, + blocks: Arc, +} +impl HugeFungusFeature { + pub(crate) fn decode( + json: &str, + bindings: &FeatureBlockBindings<'_>, + depth: usize, + remaining: &mut usize, + ) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:huge_fungus" { + return Err(DecodeError::Field("huge fungus type")); + } + let state = |name: &'static str| { + bindings + .codec + .decode(required(&object, name)?.get(), false) + .map_err(|e| DecodeError::Registry(e.to_string())) + }; + let registry = bindings.registry(); + let default = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("missing fungus block {name}"))) + }; + Ok(Self { + valid_base: state("valid_base_block")?, + stem: state("stem_state")?, + hat: state("hat_state")?, + decor: state("decor_state")?, + replaceable: BlockPredicate::decode_with_blocks( + required(&object, "replaceable_blocks")?.get(), + depth + 1, + remaining, + Some(bindings), + )?, + planted: optional(&object, "planted") + .map(|raw| serde_json::from_str::(raw.get())) + .transpose()? + .unwrap_or(false), + air: default("minecraft:air")?, + weeping_vines: default("minecraft:weeping_vines")?, + weeping_vines_plant: default("minecraft:weeping_vines_plant")?, + nether_wart_block: default("minecraft:nether_wart_block")?, + blocks: bindings.tree_blocks()?, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let below = read(world, tb::offset(origin, 0, -1, 0))?; + if !self.blocks.same_block(below, self.valid_base) { + return Ok(false); + } + let mut height = next_int(random, 4, 13)?; + if random.next_int_bound(12)? == 0 { + height *= 2; + } + if !self.planted { + // ChunkGenerator.getGenDepth, compared against the absolute Y. + let depth = world.generation().height; + if origin[1].wrapping_add(height).wrapping_add(1) >= depth { + return Ok(false); + } + } + let huge = !self.planted && random.next_float() < 0.06; + write(world, origin, self.air, 260)?; + self.stem(world, random, origin, height, huge)?; + self.hat(world, random, origin, height, huge)?; + Ok(true) + } + fn replaceable( + &self, + world: &mut W, + p: [i32; 3], + plants: bool, + ) -> TreeResult { + if self.blocks.has(read(world, p)?, tb::REPLACEABLE) { + return Ok(true); + } + if plants { + return self.replaceable.test(world, p).map_err(query); + } + Ok(false) + } + fn stem( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + height: i32, + huge: bool, + ) -> TreeResult<(), W::Error> { + let r = i32::from(huge); + for dx in -r..=r { + for dz in -r..=r { + let corner = huge && dx.abs() == r && dz.abs() == r; + for dy in 0..height { + let p = tb::offset(origin, dx, dy, dz); + if !self.replaceable(world, p, true)? { + continue; + } + if self.planted { + if !self.blocks.is_air(read(world, tb::offset(p, 0, -1, 0))?) { + world + .destroy_block_without_entity(p, true) + .map_err(query)?; + } + write(world, p, self.stem, 3)?; + } else if corner { + if random.next_float() < 0.1 { + write(world, p, self.stem, 3)?; + } + } else { + write(world, p, self.stem, 3)?; + } + } + } + } + Ok(()) + } + fn hat( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + height: i32, + huge: bool, + ) -> TreeResult<(), W::Error> { + let vines = self.blocks.same_block(self.hat, self.nether_wart_block); + let hat_height = (random.next_int_bound(1 + height / 3)? + 5).min(height); + let start = height - hat_height; + for dy in start..=height { + let mut radius = if dy < height - random.next_int_bound(3)? { 2 } else { 1 }; + if hat_height > 8 && dy < start + 4 { + radius = 3; + } + if huge { + radius += 1; + } + for dx in -radius..=radius { + for dz in -radius..=radius { + let edge_x = dx == -radius || dx == radius; + let edge_z = dz == -radius || dz == radius; + let inside = !edge_x && !edge_z && dy != height; + let corner = edge_x && edge_z; + let bottom = dy < start + 3; + let p = tb::offset(origin, dx, dy, dz); + if !self.replaceable(world, p, false)? { + continue; + } + if self.planted && !self.blocks.is_air(read(world, tb::offset(p, 0, -1, 0))?) { + world + .destroy_block_without_entity(p, true) + .map_err(query)?; + } + if bottom { + if !inside { + self.hat_drop(world, random, p, vines)?; + } + } else if inside { + self.hat_block(world, random, p, 0.1, 0.2, if vines { 0.1 } else { 0.0 })?; + } else if corner { + self.hat_block(world, random, p, 0.01, 0.7, if vines { 0.083 } else { 0.0 })?; + } else { + self.hat_block(world, random, p, 5.0e-4, 0.98, if vines { 0.07 } else { 0.0 })?; + } + } + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn hat_block( + &self, + world: &mut W, + random: &mut R, + p: [i32; 3], + decor: f32, + hat: f32, + vines: f32, + ) -> TreeResult<(), W::Error> { + if random.next_float() < decor { + write(world, p, self.decor, 3)?; + } else if random.next_float() < hat { + write(world, p, self.hat, 3)?; + if random.next_float() < vines { + self.weeping_vines(world, random, p)?; + } + } + Ok(()) + } + fn hat_drop( + &self, + world: &mut W, + random: &mut R, + p: [i32; 3], + vines: bool, + ) -> TreeResult<(), W::Error> { + let below = read(world, tb::offset(p, 0, -1, 0))?; + if self.blocks.same_block(below, self.hat) { + write(world, p, self.hat, 3)?; + } else if f64::from(random.next_float()) < 0.15 { + write(world, p, self.hat, 3)?; + if vines && random.next_int_bound(11)? == 0 { + self.weeping_vines(world, random, p)?; + } + } + Ok(()) + } + fn weeping_vines( + &self, + world: &mut W, + random: &mut R, + hat: [i32; 3], + ) -> TreeResult<(), W::Error> { + let mut p = tb::offset(hat, 0, -1, 0); + if !self.blocks.is_air(read(world, p)?) { + return Ok(()); + } + let mut goal = next_int(random, 1, 5)?; + if random.next_int_bound(7)? == 0 { + goal *= 2; + } + for height in 0..=goal { + if self.blocks.is_air(read(world, p)?) { + if height == goal || !self.blocks.is_air(read(world, tb::offset(p, 0, -1, 0))?) { + let age = next_int(random, 23, 25)?; + let state = self + .blocks + .with(self.weeping_vines, "age", &age.to_string()) + .ok_or(FeatureExecutionError::InvalidState)?; + write(world, p, state, 2)?; + break; + } + write(world, p, self.weeping_vines_plant, 2)?; + } + p = tb::offset(p, 0, -1, 0); + } + Ok(()) + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java index 496a4ce20..544fc528c 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java @@ -157,10 +157,10 @@ public final class VanillaTreeFeatureOracle { RandomSource random=f.get("legacy").getAsBoolean()?new LegacyRandomSource(seed):new XoroshiroRandomSource(seed); out.println("fixture "+f.get("feature").getAsString()); Optional decoded; - try{decoded=Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(features.get(f.get("feature").getAsString()).getAsString())).result();}catch(RuntimeException error){decoded=Optional.empty();} + try{decoded=Feature.DIRECT_CODEC.parse(ops,JsonParser.parseString(features.get(f.get("feature").getAsString()).getAsString())).result();}catch(Throwable error){decoded=Optional.empty();} if(decoded.isEmpty()){out.println("decode error");continue;} var handler=new World(f,out);var world=(WorldGenLevel)Proxy.newProxyInstance(WorldGenLevel.class.getClassLoader(),new Class[]{WorldGenLevel.class},handler); - try{out.println("place "+decoded.get().place(world,generator,random,pos(f.getAsJsonArray("origin"))));}catch(RuntimeException error){out.println("place error");System.err.println(f.get("feature").getAsString()+": "+error);} + try{out.println("place "+decoded.get().place(world,generator,random,pos(f.getAsJsonArray("origin"))));}catch(Throwable error){out.println("place error");System.err.println(f.get("feature").getAsString()+": "+error);} out.println("next "+random.nextLong()); var keys=new ArrayList<>(handler.chunks.keySet());keys.sort(Comparator.comparingInt(ChunkPos::x).thenComparingInt(ChunkPos::z)); var changes=new TreeMap(Comparator.comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ)); diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 2135c0b9e..3517ec1ef 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -48,7 +48,7 @@ def corpus(facts,resources): if 'pale_moss' in text:continue # needs the level's feature registry and server level trees.append(name) elif kind in ('ore','scattered_ore'):ores.append(name) - elif kind not in ('freeze_top_layer',):others.append(name) + elif kind not in ('freeze_top_layer','template','fossil'):others.append(name) # templates need structure resources worlds=[ {}, {'obstacle_mod':37,'obstacle_state':get('oak_leaves'),'obstacle_min':66}, From a819c54e668befe33a1d14cf028e23648355e800 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:38:01 +0200 Subject: [PATCH 08/12] WIP: checkpoint stopped agent work Co-Authored-By: Claude Opus 5.5 (1M context) --- .../examples/tree_feature_fixture.rs | 14 + crates/horizon-world/src/worldgen.rs | 1 + .../src/worldgen/feature_graph.rs | 7 + .../src/worldgen/placement/context.rs | 8 + crates/horizon-world/src/worldgen/sculk.rs | 692 ++++++++++++++++++ tools/test_tree_feature_parity.py | 1 + 6 files changed, 723 insertions(+) create mode 100644 crates/horizon-world/src/worldgen/sculk.rs diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/tree_feature_fixture.rs index fd015b175..378f8b398 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/tree_feature_fixture.rs @@ -183,6 +183,20 @@ impl SurvivalWorld for World<'_, '_, W> { } } impl PlacementContext for World<'_, '_, W> { + fn collision_full_block(&mut self, state: BlockStateId, p: [i32; 3]) -> Result { + use horizon_core::geometry::Axis; + let collision = self.collision; + let shape = collision.collision_shape(self, state, p).map_err(query)?; + let [nx, ny, nz] = shape.sizes(); + let spans = [Axis::X, Axis::Y, Axis::Z] + .into_iter() + .all(|axis| shape.min(axis) == 0.0 && shape.max(axis) == 1.0); + Ok(!shape.is_empty() + && spans + && (0..nx).all(|x| { + (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) + })) + } fn world_seed(&mut self) -> Result { Ok(self.seed) } diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 3d5445447..12d870d1f 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -49,6 +49,7 @@ pub mod replace_blobs; pub mod root_system; pub mod router; pub mod rule_test; +pub mod sculk; pub mod settings; pub mod simple_block; pub mod snow_freeze; diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 89e739e4e..41173eff9 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -80,6 +80,7 @@ pub enum FeatureDefinition { SpeleothemCluster(Box), LargeDripstone(Box), HugeFungus(Box), + SculkPatch(Box), ProjectedPatchySquare(Box), SteppedColumnCluster(Box), FallenTree(Box), @@ -649,6 +650,11 @@ impl FeatureDefinition { ) .map(|f| Self::SteppedColumnCluster(Box::new(f))) } + "minecraft:sculk_patch" => super::sculk::SculkPatchFeature::decode( + json, + blocks.ok_or(DecodeError::Field("sculk patch bindings"))?, + ) + .map(|f| Self::SculkPatch(Box::new(f))), "minecraft:huge_fungus" => super::fungus::HugeFungusFeature::decode( json, blocks.ok_or(DecodeError::Field("huge fungus bindings"))?, @@ -1011,6 +1017,7 @@ impl FeatureDefinition { Self::SpeleothemCluster(feature) => feature.place(world, random, origin), Self::LargeDripstone(feature) => feature.place(world, random, origin), Self::HugeFungus(feature) => feature.place(world, random, origin), + Self::SculkPatch(feature) => feature.place(world, random, origin), Self::ProjectedPatchySquare(feature) => feature.place(world, random, origin), Self::SteppedColumnCluster(feature) => feature.place(world, random, origin), Self::RootSystem(feature) => { diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index ef2522b1c..ad443be25 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -61,6 +61,14 @@ pub trait PlacementContext { ) -> Result<(), PlacementQueryError> { Err(PlacementQueryError::Unavailable) } + /// BlockState.isCollisionShapeFullBlock for an already-read state. + fn collision_full_block( + &mut self, + _state: crate::registry::BlockStateId, + _position: [i32; 3], + ) -> Result { + Err(PlacementQueryError::Unavailable) + } /// WorldGenLevel.getSeed: the world seed for seed-derived feature noise. fn world_seed(&mut self) -> Result { Err(PlacementQueryError::Unavailable) diff --git a/crates/horizon-world/src/worldgen/sculk.rs b/crates/horizon-world/src/worldgen/sculk.rs new file mode 100644 index 000000000..9b20d4be2 --- /dev/null +++ b/crates/horizon-world/src/worldgen/sculk.rs @@ -0,0 +1,692 @@ +//! `minecraft:sculk_patch`: the world-generation SculkSpreader with sculk, +//! sculk vein and default charge-cursor behaviours. +use super::{ + DecodeError, Object, int_range, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + tree::{TreeResult, kind, read, write}, + tree_blocks::{self as tb, TreeBlocks}, +}; +use crate::registry::BlockStateId; +use horizon_core::{geometry::Direction, random::RandomSource}; +use std::{collections::BTreeSet, sync::Arc}; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} + +// Worldgen spreader constants (SculkSpreader.createWorldGenSpreader). +const GROWTH_SPAWN_COST: i32 = 50; +const NO_GROWTH_RADIUS: i32 = 1; +const CHARGE_DECAY_RATE: i32 = 5; +const ADDITIONAL_DECAY_RATE: i32 = 10; +const MAX_CURSORS: usize = 32; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum Behaviour { + Default, + Sculk, + Vein, +} +#[derive(Clone, Copy)] +enum Spread { + SamePosition, + SamePlane, + WrapAround, +} +const ALL_SPREADS: [Spread; 3] = [Spread::SamePosition, Spread::SamePlane, Spread::WrapAround]; + +struct Cursor { + pos: [i32; 3], + charge: i32, + update_delay: i32, + decay_delay: i32, + facings: Option>, +} + +#[derive(Clone, Debug)] +pub struct SculkPatchFeature { + charge_count: i32, + amount_per_charge: i32, + spread_attempts: i32, + growth_rounds: i32, + spread_rounds: i32, + sculk: BlockStateId, + vein: BlockStateId, + shrieker: BlockStateId, + sensor: BlockStateId, + water: BlockStateId, + air: BlockStateId, + replaceable_world_gen: Arc>, + replaceable: Arc>, + inhibitors: Arc>, + blocks: Arc, +} +impl SculkPatchFeature { + pub(crate) fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:sculk_patch" { + return Err(DecodeError::Field("sculk patch type")); + } + let int = |name: &'static str, low: i32, high: i32| { + int_range(required(&object, name)?, name, low, high) + }; + let registry = bindings.registry(); + let default = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("missing sculk block {name}"))) + }; + let tag = |name: &str| -> Arc> { + bindings.tags.get(name).cloned().unwrap_or_default() + }; + let blocks = bindings.tree_blocks()?; + let shrieker = blocks + .with(default("minecraft:sculk_shrieker")?, "can_summon", "true") + .ok_or(DecodeError::Field("sculk shrieker summon state"))?; + Ok(Self { + charge_count: int("charge_count", 1, 32)?, + amount_per_charge: int("amount_per_charge", 1, 500)?, + spread_attempts: int("spread_attempts", 1, 64)?, + growth_rounds: int("growth_rounds", 0, 8)?, + spread_rounds: int("spread_rounds", 0, 8)?, + sculk: default("minecraft:sculk")?, + vein: default("minecraft:sculk_vein")?, + shrieker, + sensor: default("minecraft:sculk_sensor")?, + water: default("minecraft:water")?, + air: default("minecraft:air")?, + replaceable_world_gen: tag("minecraft:sculk_replaceable_world_gen"), + replaceable: tag("minecraft:sculk_replaceable"), + inhibitors: tag("minecraft:sculk_growth_inhibitors"), + blocks, + }) + } + fn behaviour(&self, state: BlockStateId) -> Behaviour { + if self.blocks.same_block(state, self.sculk) { + Behaviour::Sculk + } else if self.blocks.same_block(state, self.vein) { + Behaviour::Vein + } else { + Behaviour::Default + } + } + fn has_face(&self, state: BlockStateId, face: Direction) -> bool { + self.blocks.properties.value(state, tb::direction_name(face)) == Some("true") + } + fn is_vein(&self, state: BlockStateId) -> bool { + self.blocks.same_block(state, self.vein) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + if !self.can_spread_from(world, origin)? { + return Ok(false); + } + let mut cursors: Vec = Vec::new(); + for round in 0..self.spread_rounds + self.growth_rounds { + for _ in 0..self.charge_count { + let mut charge = self.amount_per_charge; + while charge > 0 { + let current = charge.min(1000); + if cursors.len() < MAX_CURSORS { + cursors.push(Cursor { + pos: origin, + charge: current, + update_delay: 0, + decay_delay: 1, + facings: None, + }); + } + charge -= current; + } + } + let spread_veins = round < self.spread_rounds; + for _ in 0..self.spread_attempts { + cursors = self.update_cursors(world, random, origin, cursors, spread_veins)?; + } + cursors.clear(); + } + Ok(true) + } + fn can_spread_from( + &self, + world: &mut W, + origin: [i32; 3], + ) -> TreeResult { + let start = read(world, origin)?; + if self.behaviour(start) != Behaviour::Default { + return Ok(true); + } + let water_source = self.blocks.has(start, tb::WATER_BLOCK) && self.blocks.has(start, tb::FLUID_SOURCE); + if !self.blocks.is_air(start) && !water_source { + return Ok(false); + } + for direction in Direction::ALL { + let p = tb::relative(origin, direction, 1); + let state = read(world, p)?; + if world.collision_full_block(state, p).map_err(query)? { + return Ok(true); + } + } + Ok(false) + } + fn update_cursors( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + cursors: Vec, + spread_veins: bool, + ) -> TreeResult, W::Error> { + let mut processed: Vec = Vec::new(); + // Mergeable cursor charge per position (index into `processed`). + let mut mergeable: Vec<([i32; 3], usize, i32)> = Vec::new(); + for mut cursor in cursors { + let distance = (0..3) + .map(|i| cursor.pos[i].wrapping_sub(origin[i]).wrapping_abs()) + .max() + .unwrap_or(0); + if distance > 1024 { + continue; + } + self.update(world, random, origin, &mut cursor, spread_veins)?; + if cursor.charge <= 0 { + continue; + } + match mergeable.iter_mut().find(|(p, _, _)| *p == cursor.pos) { + None => { + mergeable.push((cursor.pos, processed.len(), cursor.charge)); + processed.push(cursor); + } + Some(entry) => { + // World generation never merges cursors. + if cursor.charge < entry.2 { + *entry = (cursor.pos, processed.len(), cursor.charge); + } + processed.push(cursor); + } + } + } + Ok(processed) + } + fn update( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + cursor: &mut Cursor, + spread_veins: bool, + ) -> TreeResult<(), W::Error> { + if cursor.charge <= 0 { + return Ok(()); + } + if cursor.update_delay > 0 { + cursor.update_delay -= 1; + return Ok(()); + } + let mut state = read(world, cursor.pos)?; + let mut behaviour = self.behaviour(state); + if spread_veins + && self.attempt_spread_vein(world, behaviour, cursor.pos, state, cursor.facings.as_deref())? + && behaviour != Behaviour::Sculk + { + state = read(world, cursor.pos)?; + behaviour = self.behaviour(state); + } + cursor.charge = self.attempt_use_charge(world, random, origin, behaviour, cursor, spread_veins)?; + if cursor.charge <= 0 { + self.on_discharged(world, behaviour, state, cursor.pos)?; + return Ok(()); + } + match self.valid_movement(world, random, cursor.pos, origin)? { + Some(target) => { + self.on_discharged(world, behaviour, state, cursor.pos)?; + cursor.pos = target; + state = read(world, target)?; + } + None => { + self.on_discharged(world, behaviour, state, cursor.pos)?; + cursor.charge = 0; + return Ok(()); + } + } + if self.behaviour(state) != Behaviour::Default { + cursor.facings = Some( + Direction::ALL + .into_iter() + .filter(|d| self.has_face(state, *d)) + .collect(), + ); + } + cursor.decay_delay = match behaviour { + Behaviour::Default => (cursor.decay_delay - 1).max(0), + _ => 1, + }; + cursor.update_delay = 1; + Ok(()) + } + fn attempt_spread_vein( + &self, + world: &mut W, + behaviour: Behaviour, + pos: [i32; 3], + state: BlockStateId, + facings: Option<&[Direction]>, + ) -> TreeResult { + if behaviour == Behaviour::Default { + match facings { + None => { + let current = read(world, pos)?; + return Ok(self.spread_all(world, current, pos, &[Spread::SamePosition])? > 0); + } + Some(faces) if !faces.is_empty() => { + let water_source = self.blocks.has(state, tb::WATER_SOURCE); + if !self.blocks.is_air(state) && !water_source { + return Ok(false); + } + return self.regrow(world, pos, state, faces); + } + Some(_) => {} + } + } + Ok(self.spread_all(world, state, pos, &ALL_SPREADS)? > 0) + } + fn regrow( + &self, + world: &mut W, + pos: [i32; 3], + existing: BlockStateId, + faces: &[Direction], + ) -> TreeResult { + let mut state = self.vein; + let mut any = false; + for &face in faces { + if world.attachment_at(pos, face).map_err(query)? { + state = self.with_face(state, face, true)?; + any = true; + } + } + if !any { + return Ok(false); + } + if self.blocks.has(existing, tb::ANY_FLUID) { + state = self.blocks.waterlogged(state, true); + } + write(world, pos, state, 3)?; + Ok(true) + } + fn with_face(&self, state: BlockStateId, face: Direction, value: bool) -> TreeResult { + self.blocks + .with(state, tb::direction_name(face), if value { "true" } else { "false" }) + .ok_or(FeatureExecutionError::InvalidState) + } + /// MultifaceSpreader.spreadAll with the sculk vein spreader configuration + /// (post-processing enabled for world generation). + fn spread_all( + &self, + world: &mut W, + state: BlockStateId, + pos: [i32; 3], + types: &[Spread], + ) -> TreeResult { + let other_source = !self.is_vein(state); + let mut count = 0; + for face in Direction::ALL { + if !(other_source || self.has_face(state, face)) { + continue; + } + for direction in Direction::ALL { + if tb::Axis::of(direction) == tb::Axis::of(face) { + continue; + } + if !(other_source || (self.has_face(state, face) && !self.has_face(state, direction))) { + continue; + } + let mut target = None; + for kind in types { + let candidate = match kind { + Spread::SamePosition => (pos, direction), + Spread::SamePlane => (tb::relative(pos, direction, 1), face), + Spread::WrapAround => ( + tb::relative(tb::relative(pos, direction, 1), face, 1), + direction.opposite(), + ), + }; + if self.can_spread_into(world, pos, candidate.0, candidate.1)? { + target = Some(candidate); + break; + } + } + let Some((target, face_to)) = target else { + continue; + }; + let old = read(world, target)?; + let Some(new) = self.state_for_placement(world, old, target, face_to)? else { + continue; + }; + world.mark_postprocessing(target).map_err(query)?; + if write(world, target, new, 2)? { + count += 1; + } + } + } + Ok(count) + } + fn valid_for_placement( + &self, + world: &mut W, + old: BlockStateId, + pos: [i32; 3], + face: Direction, + ) -> TreeResult { + if self.is_vein(old) && self.has_face(old, face) { + return Ok(false); + } + world.attachment_at(pos, face).map_err(query) + } + fn state_for_placement( + &self, + world: &mut W, + old: BlockStateId, + pos: [i32; 3], + face: Direction, + ) -> TreeResult, W::Error> { + if !self.valid_for_placement(world, old, pos, face)? { + return Ok(None); + } + let base = if self.is_vein(old) { + old + } else if self.blocks.has(old, tb::WATER_SOURCE) { + self.blocks.waterlogged(self.vein, true) + } else { + self.vein + }; + self.with_face(base, face, true).map(Some) + } + fn can_spread_into( + &self, + world: &mut W, + source: [i32; 3], + target: [i32; 3], + face: Direction, + ) -> TreeResult { + let existing = read(world, target)?; + let against = read(world, tb::relative(target, face, 1))?; + if self.blocks.has(against, tb::SCULK_BLOCKER) { + return Ok(false); + } + if tb::dist_manhattan(source, target) == 2 { + let neighbor = tb::relative(source, face.opposite(), 1); + let state = read(world, neighbor)?; + if world.state_face_sturdy(state, neighbor, face).map_err(query)? { + return Ok(false); + } + } + if self.blocks.has(existing, tb::ANY_FLUID) && !self.blocks.has(existing, tb::WATER_SOURCE) { + return Ok(false); + } + if self.blocks.has(existing, tb::FIRE) { + return Ok(false); + } + let replaceable = self.blocks.has(existing, tb::REPLACEABLE) + || self.blocks.is_air(existing) + || self.is_vein(existing) + || (self.blocks.has(existing, tb::WATER_BLOCK) && self.blocks.has(existing, tb::WATER_SOURCE)); + Ok(replaceable && self.valid_for_placement(world, existing, target, face)?) + } + fn attempt_use_charge( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + behaviour: Behaviour, + cursor: &Cursor, + spread_veins: bool, + ) -> TreeResult { + let charge = cursor.charge; + match behaviour { + Behaviour::Default => Ok(if cursor.decay_delay > 0 { charge } else { 0 }), + Behaviour::Vein => { + if spread_veins && self.place_sculk(world, random, cursor.pos)? { + Ok(charge - 1) + } else if random.next_int_bound(CHARGE_DECAY_RATE)? == 0 { + Ok((charge as f32 * 0.5f32).floor() as i32) + } else { + Ok(charge) + } + } + Behaviour::Sculk => { + if charge == 0 || random.next_int_bound(CHARGE_DECAY_RATE)? != 0 { + return Ok(charge); + } + let pos = cursor.pos; + let dist_sqr: f64 = (0..3) + .map(|i| { + let d = f64::from(pos[i]) - f64::from(origin[i]); + d * d + }) + .sum(); + let close = dist_sqr < f64::from(NO_GROWTH_RADIUS * NO_GROWTH_RADIUS); + if !close && self.can_place_growth(world, pos)? { + if random.next_int_bound(GROWTH_SPAWN_COST)? < charge { + let above = tb::offset(pos, 0, 1, 0); + let mut growth = if random.next_int_bound(11)? == 0 { + self.shrieker + } else { + self.sensor + }; + if self.blocks.has(growth, tb::WATERLOGGABLE) + && self.blocks.has(read(world, above)?, tb::ANY_FLUID) + { + growth = self.blocks.waterlogged(growth, true); + } + write(world, above, growth, 3)?; + } + return Ok(0.max(charge - GROWTH_SPAWN_COST)); + } + if random.next_int_bound(ADDITIONAL_DECAY_RATE)? != 0 { + return Ok(charge); + } + let penalty = if close { + 1 + } else { + let outer = (dist_sqr.sqrt() as f32 - NO_GROWTH_RADIUS as f32).powi(2); + let reach = (24 - NO_GROWTH_RADIUS) * (24 - NO_GROWTH_RADIUS); + let factor = 1.0f32.min(outer / reach as f32); + 1.max((charge as f32 * factor * 0.5f32) as i32) + }; + Ok(charge - penalty) + } + } + } + fn can_place_growth( + &self, + world: &mut W, + pos: [i32; 3], + ) -> TreeResult { + let above = read(world, tb::offset(pos, 0, 1, 0))?; + let open = self.blocks.is_air(above) + || (self.blocks.has(above, tb::WATER_BLOCK) && self.blocks.has(above, tb::WATER_SOURCE)); + if !open { + return Ok(false); + } + let mut matched = 0; + // BoxBlockMatcher iterates BlockPos.betweenClosed (x, then y, then z). + for dz in -4..=4 { + for dy in 0..=2 { + for dx in -4..=4 { + if self.inhibitors.contains(&read(world, tb::offset(pos, dx, dy, dz))?) { + matched += 1; + if matched >= 3 { + return Ok(false); + } + } + } + } + } + Ok(true) + } + fn place_sculk( + &self, + world: &mut W, + random: &mut R, + pos: [i32; 3], + ) -> TreeResult { + let state = read(world, pos)?; + let mut directions = Direction::ALL; + tb::shuffle(&mut directions, random)?; + for support in directions { + if !self.has_face(state, support) { + continue; + } + let support_pos = tb::relative(pos, support, 1); + let support_state = read(world, support_pos)?; + if !self.replaceable_world_gen.contains(&support_state) { + continue; + } + write(world, support_pos, self.sculk, 3)?; + self.spread_all(world, self.sculk, support_pos, &ALL_SPREADS)?; + let skip = support.opposite(); + for direction in Direction::ALL { + if direction == skip { + continue; + } + let vein_pos = tb::relative(support_pos, direction, 1); + let possible = read(world, vein_pos)?; + if self.is_vein(possible) { + self.on_discharged(world, Behaviour::Vein, possible, vein_pos)?; + } + } + return Ok(true); + } + Ok(false) + } + fn on_discharged( + &self, + world: &mut W, + behaviour: Behaviour, + state: BlockStateId, + pos: [i32; 3], + ) -> TreeResult<(), W::Error> { + if behaviour != Behaviour::Vein || !self.is_vein(state) { + return Ok(()); + } + let mut state = state; + for direction in Direction::ALL { + if self.has_face(state, direction) + && self + .blocks + .same_block(read(world, tb::relative(pos, direction, 1))?, self.sculk) + { + state = self.with_face(state, direction, false)?; + } + } + if !Direction::ALL.into_iter().any(|d| self.has_face(state, d)) { + let here = read(world, pos)?; + state = if self.blocks.has(here, tb::ANY_FLUID) { + self.water + } else { + self.air + }; + } + write(world, pos, state, 3)?; + Ok(()) + } + fn valid_movement( + &self, + world: &mut W, + random: &mut R, + pos: [i32; 3], + origin: [i32; 3], + ) -> TreeResult, W::Error> { + // NON_CORNER_NEIGHBOURS in betweenClosed order (x, then y, then z). + let mut offsets = Vec::with_capacity(18); + for z in -1..=1 { + for y in -1..=1 { + for x in -1..=1 { + if (x == 0 || y == 0 || z == 0) && (x, y, z) != (0, 0, 0) { + offsets.push([x, y, z]); + } + } + } + } + tb::shuffle(&mut offsets, random)?; + let mut best = pos; + for o in offsets { + let neighbour = tb::offset(pos, o[0], o[1], o[2]); + let dx = origin[0].wrapping_sub(neighbour[0]); + let dz = origin[2].wrapping_sub(neighbour[2]); + if dx.wrapping_mul(dx).wrapping_add(dz.wrapping_mul(dz)) > 144 { + continue; + } + let transferee = read(world, neighbour)?; + if self.behaviour(transferee) == Behaviour::Default + || !self.unobstructed_move(world, pos, neighbour)? + { + continue; + } + best = neighbour; + if self.is_vein(transferee) { + let mut substrate = false; + for direction in Direction::ALL { + if self.has_face(transferee, direction) + && self + .replaceable + .contains(&read(world, tb::relative(neighbour, direction, 1))?) + { + substrate = true; + break; + } + } + if substrate { + break; + } + } + } + Ok((best != pos).then_some(best)) + } + fn unobstructed_move( + &self, + world: &mut W, + from: [i32; 3], + to: [i32; 3], + ) -> TreeResult { + if tb::dist_manhattan(from, to) == 1 { + return Ok(true); + } + let delta: [i32; 3] = std::array::from_fn(|i| to[i].wrapping_sub(from[i])); + let pick = |v: i32, negative: Direction, positive: Direction| { + if v < 0 { negative } else { positive } + }; + let dir_x = pick(delta[0], Direction::West, Direction::East); + let dir_y = pick(delta[1], Direction::Down, Direction::Up); + let dir_z = pick(delta[2], Direction::North, Direction::South); + let (a, b) = if delta[0] == 0 { + (dir_y, dir_z) + } else if delta[1] == 0 { + (dir_x, dir_z) + } else { + (dir_x, dir_y) + }; + Ok(self.unobstructed(world, from, a)? || self.unobstructed(world, from, b)?) + } + fn unobstructed( + &self, + world: &mut W, + from: [i32; 3], + direction: Direction, + ) -> TreeResult { + let test = tb::relative(from, direction, 1); + let state = read(world, test)?; + Ok(!world + .state_face_sturdy(state, test, direction.opposite()) + .map_err(query)?) + } +} diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index 3517ec1ef..b492d9446 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -113,6 +113,7 @@ def main(): for side in jars: export=build/(side+'-definitions');export.mkdir(exist_ok=True);java('VanillaSimpleBlockOracle',side,'export',export) for path in (build/'server-definitions').iterdir(): + if path.name=='inputs.txt':continue # survival export's own corpus if path.read_bytes()!=(build/'client-definitions'/path.name).read_bytes():raise ValueError('reference definitions differ: '+path.name) (build/path.name).write_bytes(path.read_bytes()) facts=json.loads((build/'facts.json').read_text()) From dfda7acef23ac414e30e007fec335b0acb507f64 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Wed, 7 Oct 2026 23:45:55 +0200 Subject: [PATCH 09/12] Port end spike feature with seed-derived spike layout minecraft:end_spike reproduces SpikeCacheLoader (seed-keyed shuffled sizes), obsidian columns, iron-bar cages, the crystal's yaw draw, bedrock and fire; the crystal entity is handed to a new spawn_end_crystal world hook. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/horizon-world/src/worldgen.rs | 1 + .../horizon-world/src/worldgen/end_spike.rs | 204 ++++++++++++++++++ .../src/worldgen/feature_graph.rs | 7 + .../src/worldgen/placement/context.rs | 10 + 4 files changed, 222 insertions(+) create mode 100644 crates/horizon-world/src/worldgen/end_spike.rs diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index 12d870d1f..8fa6ec0ac 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -29,6 +29,7 @@ pub mod disk; pub mod dripstone; pub mod end_gateway; pub mod end_podium; +pub mod end_spike; pub mod feature; pub mod feature_catalog; pub mod feature_graph; diff --git a/crates/horizon-world/src/worldgen/end_spike.rs b/crates/horizon-world/src/worldgen/end_spike.rs new file mode 100644 index 000000000..3be8e0f24 --- /dev/null +++ b/crates/horizon-world/src/worldgen/end_spike.rs @@ -0,0 +1,204 @@ +//! `minecraft:end_spike`: the obsidian pillars around the main End island. +use super::{ + DecodeError, Object, integer, optional, + block_feature::FeatureBlockBindings, + feature::FeatureWorld, + feature_graph::FeatureExecutionError, + placement::{PlacementContext, PlacementQueryError}, + required, + tree::{TreeResult, kind, write}, + tree_blocks::{self as tb, TreeBlocks}, +}; +use crate::registry::BlockStateId; +use horizon_core::random::{LegacyRandom, RandomSource}; +use std::sync::Arc; + +fn query(error: PlacementQueryError) -> FeatureExecutionError { + FeatureExecutionError::Query(error) +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EndSpike { + pub center_x: i32, + pub center_z: i32, + pub radius: i32, + pub height: i32, + pub guarded: bool, +} +/// EndSpikeFeature.getSpikesForLevel (SpikeCacheLoader), from the world seed. +pub fn spikes_for_seed(seed: i64) -> Vec { + let key = LegacyRandom::new(seed).next_long() & 65535; + let mut random = LegacyRandom::new(key); + let mut sizes: Vec = (0..10).collect(); + tb::shuffle(&mut sizes, &mut random).expect("positive shuffle bounds"); + (0..10) + .map(|i| { + let angle = 2.0 * (-std::f64::consts::PI + (std::f64::consts::PI / 10.0) * f64::from(i)); + let size = sizes[i as usize]; + EndSpike { + center_x: (42.0 * angle.cos()).floor() as i32, + center_z: (42.0 * angle.sin()).floor() as i32, + radius: 2 + size / 3, + height: 76 + size * 3, + guarded: size == 1 || size == 2, + } + }) + .collect() +} + +#[derive(Clone, Debug)] +pub struct EndSpikeFeature { + spikes: Vec, + crystal_invulnerable: bool, + beam_target: Option<[i32; 3]>, + obsidian: BlockStateId, + air: BlockStateId, + iron_bars: BlockStateId, + bedrock: BlockStateId, + fire: BlockStateId, + blocks: Arc, +} +impl EndSpikeFeature { + pub(crate) fn decode(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { + let object: Object = serde_json::from_str(json)?; + if kind(&object)? != "minecraft:end_spike" { + return Err(DecodeError::Field("end spike type")); + } + let raw: Vec = serde_json::from_str(required(&object, "spikes")?.get())?; + let int = |o: &Object, name: &str| -> Result { + optional(o, name).map(integer).transpose().map(|v| v.unwrap_or(0)) + }; + let spikes = raw + .iter() + .map(|o| { + Ok(EndSpike { + center_x: int(o, "centerX")?, + center_z: int(o, "centerZ")?, + radius: int(o, "radius")?, + height: int(o, "height")?, + guarded: optional(o, "guarded") + .map(|v| serde_json::from_str::(v.get())) + .transpose()? + .unwrap_or(false), + }) + }) + .collect::>()?; + let beam_target = optional(&object, "crystal_beam_target") + .map(|raw| -> Result<[i32; 3], DecodeError> { + let v: Vec> = serde_json::from_str(raw.get())?; + if v.len() != 3 { + return Err(DecodeError::Field("beam target")); + } + Ok([integer(&v[0])?, integer(&v[1])?, integer(&v[2])?]) + }) + .transpose()?; + let registry = bindings.registry(); + let default = |name: &str| { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("missing spike block {name}"))) + }; + Ok(Self { + spikes, + crystal_invulnerable: optional(&object, "crystal_invulnerable") + .map(|v| serde_json::from_str::(v.get())) + .transpose()? + .unwrap_or(false), + beam_target, + obsidian: default("minecraft:obsidian")?, + air: default("minecraft:air")?, + iron_bars: default("minecraft:iron_bars")?, + bedrock: default("minecraft:bedrock")?, + fire: default("minecraft:fire")?, + blocks: bindings.tree_blocks()?, + }) + } + pub(crate) fn place( + &self, + world: &mut W, + random: &mut R, + origin: [i32; 3], + ) -> TreeResult { + let spikes = if self.spikes.is_empty() { + spikes_for_seed(world.world_seed().map_err(query)?) + } else { + self.spikes.clone() + }; + for spike in spikes { + if origin[0] >> 4 == spike.center_x >> 4 && origin[2] >> 4 == spike.center_z >> 4 { + self.place_spike(world, random, spike)?; + } + } + Ok(true) + } + fn bars(&self, north: bool, south: bool, west: bool, east: bool) -> TreeResult { + let mut state = self.iron_bars; + for (name, value) in [("north", north), ("south", south), ("west", west), ("east", east)] { + state = self + .blocks + .with(state, name, if value { "true" } else { "false" }) + .ok_or(FeatureExecutionError::InvalidState)?; + } + Ok(state) + } + fn place_spike( + &self, + world: &mut W, + random: &mut R, + spike: EndSpike, + ) -> TreeResult<(), W::Error> { + let r = spike.radius; + let min_y = world.min_y().map_err(query)?; + let (cx, cz) = (spike.center_x, spike.center_z); + for z in cz - r..=cz + r { + for y in min_y..=spike.height + 10 { + for x in cx - r..=cx + r { + let dx = f64::from(x) - f64::from(cx); + let dz = f64::from(z) - f64::from(cz); + let p = [x, y, z]; + if dx * dx + dz * dz <= f64::from(r * r + 1) && y < spike.height { + write(world, p, self.obsidian, 3)?; + } else if y > 65 { + write(world, p, self.air, 3)?; + } + } + } + } + if spike.guarded { + for dx in -2i32..=2 { + for dz in -2i32..=2 { + for dy in 0..=3 { + let x_side = dx.abs() == 2; + let z_side = dz.abs() == 2; + let top = dy == 3; + if x_side || z_side || top { + let x_edge = dx == -2 || dx == 2 || top; + let z_edge = dz == -2 || dz == 2 || top; + let state = self.bars( + x_edge && dz != -2, + x_edge && dz != 2, + z_edge && dx != -2, + z_edge && dx != 2, + )?; + write(world, [cx + dx, spike.height + dy, cz + dz], state, 3)?; + } + } + } + } + } + let yaw = random.next_float() * 360.0; + world + .spawn_end_crystal( + [f64::from(cx) + 0.5, f64::from(spike.height + 1), f64::from(cz) + 0.5], + yaw, + self.beam_target, + self.crystal_invulnerable, + ) + .map_err(query)?; + let crystal = [cx, spike.height + 1, cz]; + write(world, tb::offset(crystal, 0, -1, 0), self.bedrock, 3)?; + // FireBlock.getState above sturdy bedrock is the plain fire default. + write(world, crystal, self.fire, 3)?; + Ok(()) + } +} diff --git a/crates/horizon-world/src/worldgen/feature_graph.rs b/crates/horizon-world/src/worldgen/feature_graph.rs index 41173eff9..b03beef80 100644 --- a/crates/horizon-world/src/worldgen/feature_graph.rs +++ b/crates/horizon-world/src/worldgen/feature_graph.rs @@ -81,6 +81,7 @@ pub enum FeatureDefinition { LargeDripstone(Box), HugeFungus(Box), SculkPatch(Box), + EndSpike(Box), ProjectedPatchySquare(Box), SteppedColumnCluster(Box), FallenTree(Box), @@ -650,6 +651,11 @@ impl FeatureDefinition { ) .map(|f| Self::SteppedColumnCluster(Box::new(f))) } + "minecraft:end_spike" => super::end_spike::EndSpikeFeature::decode( + json, + blocks.ok_or(DecodeError::Field("end spike bindings"))?, + ) + .map(|f| Self::EndSpike(Box::new(f))), "minecraft:sculk_patch" => super::sculk::SculkPatchFeature::decode( json, blocks.ok_or(DecodeError::Field("sculk patch bindings"))?, @@ -1018,6 +1024,7 @@ impl FeatureDefinition { Self::LargeDripstone(feature) => feature.place(world, random, origin), Self::HugeFungus(feature) => feature.place(world, random, origin), Self::SculkPatch(feature) => feature.place(world, random, origin), + Self::EndSpike(feature) => feature.place(world, random, origin), Self::ProjectedPatchySquare(feature) => feature.place(world, random, origin), Self::SteppedColumnCluster(feature) => feature.place(world, random, origin), Self::RootSystem(feature) => { diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index ad443be25..d00bec6c4 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -69,6 +69,16 @@ pub trait PlacementContext { ) -> Result { Err(PlacementQueryError::Unavailable) } + /// Add an End crystal entity (structure spawn) at an entity position. + fn spawn_end_crystal( + &mut self, + _position: [f64; 3], + _yaw: f32, + _beam_target: Option<[i32; 3]>, + _invulnerable: bool, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } /// WorldGenLevel.getSeed: the world seed for seed-derived feature noise. fn world_seed(&mut self) -> Result { Err(PlacementQueryError::Unavailable) From 558dc6b7d31014368fb97078ec485aca027d78f4 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 00:00:45 +0200 Subject: [PATCH 10/12] Bind block behavior for decoration placement checks Load Java-exported block properties, face support, collision and survival rules from the worldgen bundle's blocks/ directory (copied there by prepare_native_client.py) and bind them with the state-provider catalog, so simple-block, patch and vegetation features decode and run. The decoration world answers survival, sturdy-face, collision and attachment queries, draws WorldGenRegion's positioned level random, and treats the entity-free, unlit proto region as unobstructed with zero light. 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 | 163 ++++++++++++++++++ .../src/worldgen/generator_decoration.rs | 150 +++++++++++++++- tools/prepare_native_client.py | 15 ++ 5 files changed, 361 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..390fb338c --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -0,0 +1,163 @@ +//! 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 6b2c4325eaaaacf8425d73f2d2f8b4646b0d8d1f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 00:23:15 +0200 Subject: [PATCH 11/12] Add tree/spike unit tests and harness hooks for sculk and gateways Unit tests pin Java HashSet bucket iteration, Fisher-Yates draw order and the seed-derived End spike layout. The oracle ignores sounds, level events and entity queries; the Rust fixture accepts end-gateway configuration; FEATURE_FILTER limits a rerun to matching features. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../examples/tree_feature_fixture.rs | 3 ++ .../horizon-world/src/worldgen/end_spike.rs | 16 +++++++++ .../horizon-world/src/worldgen/tree_blocks.rs | 36 +++++++++++++++++++ .../parity/VanillaTreeFeatureOracle.java | 3 +- tools/test_tree_feature_parity.py | 5 ++- 5 files changed, 61 insertions(+), 2 deletions(-) diff --git a/crates/horizon-world/examples/tree_feature_fixture.rs b/crates/horizon-world/examples/tree_feature_fixture.rs index 378f8b398..d79dbbe5b 100644 --- a/crates/horizon-world/examples/tree_feature_fixture.rs +++ b/crates/horizon-world/examples/tree_feature_fixture.rs @@ -197,6 +197,9 @@ impl PlacementContext for World<'_, '_, W> { (0..ny).all(|y| (0..nz).all(|z| shape.is_full(x as i32, y as i32, z as i32))) })) } + fn configure_end_gateway(&mut self, _: [i32; 3], _: [i32; 3], _: bool) -> Result<(), PlacementQueryError> { + Ok(()) + } fn world_seed(&mut self) -> Result { Ok(self.seed) } diff --git a/crates/horizon-world/src/worldgen/end_spike.rs b/crates/horizon-world/src/worldgen/end_spike.rs index 3be8e0f24..6125abdbd 100644 --- a/crates/horizon-world/src/worldgen/end_spike.rs +++ b/crates/horizon-world/src/worldgen/end_spike.rs @@ -202,3 +202,19 @@ impl EndSpikeFeature { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn spike_layout_is_a_permutation_of_sizes() { + let spikes = spikes_for_seed(0); + assert_eq!(spikes.len(), 10); + let mut heights: Vec = spikes.iter().map(|s| s.height).collect(); + heights.sort_unstable(); + assert_eq!(heights, (0..10).map(|s| 76 + s * 3).collect::>()); + assert_eq!(spikes.iter().filter(|s| s.guarded).count(), 2); + assert_eq!((spikes[0].center_x, spikes[0].center_z), (42, 0)); + assert_eq!(spikes_for_seed(0), spikes_for_seed(0)); + } +} diff --git a/crates/horizon-world/src/worldgen/tree_blocks.rs b/crates/horizon-world/src/worldgen/tree_blocks.rs index b4336b8de..b370cd6bd 100644 --- a/crates/horizon-world/src/worldgen/tree_blocks.rs +++ b/crates/horizon-world/src/worldgen/tree_blocks.rs @@ -425,3 +425,39 @@ pub(crate) fn shuffle( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::{LegacyRandom, RandomSource}; + #[test] + fn pos_set_iterates_in_java_hash_bucket_order() { + let mut set = PosSet::default(); + let inserted = [[0, 64, 1], [1, 64, 0], [0, 65, 0], [0, 64, 0]]; + for p in inserted { + set.insert(p); + } + // BlockPos.hashCode spread by h ^ (h >>> 16) into 16 buckets; ties keep + // insertion order within a bucket. + let mut expected = inserted.to_vec(); + expected.sort_by_key(|p| { + let h = crate::java_hash_map::JavaKey::java_hash(&JavaPos(*p)) as u32; + (h ^ (h >> 16)) & 15 + }); + assert_eq!(set.to_vec(), expected); + assert_eq!(set.pop_first(), Some(expected[0])); + assert!(!set.contains(expected[0])); + } + #[test] + fn fisher_yates_matches_native_draw_order() { + let mut values = [0, 1, 2, 3]; + shuffle(&mut values, &mut LegacyRandom::new(42)).unwrap(); + let mut reference = [0, 1, 2, 3]; + let mut random = LegacyRandom::new(42); + for i in (2..=4).rev() { + let j = random.next_int_bound(i).unwrap() as usize; + reference.swap(i as usize - 1, j); + } + assert_eq!(values, reference); + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java index 544fc528c..b96d7b70d 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaTreeFeatureOracle.java @@ -90,7 +90,8 @@ public final class VanillaTreeFeatureOracle { case "ensureCanWrite":return true; case "getRandom":return shapeRandom; case "scheduleTick":return null; // Edge shape updates also schedule ticks; not compared. - case "setCurrentlyGenerating":return null; + case "setCurrentlyGenerating":case "playSound":case "levelEvent":case "gameEvent":case "blockEvent":return null; + case "getEntities":return java.util.List.of(); case "getBlockEntity":{ if(args.length!=1)break;var p=((BlockPos)args[0]).immutable();var state=get(p); if(state.is(Blocks.CHEST))return chests.computeIfAbsent(p,key->new ChestBlockEntity(key,state){@Override public void setLootTable(net.minecraft.resources.ResourceKey table,long seed){out.println("loot "+xyz(key)+" "+table.identifier()+" "+seed);super.setLootTable(table,seed);}}); diff --git a/tools/test_tree_feature_parity.py b/tools/test_tree_feature_parity.py index b492d9446..bac83af2b 100644 --- a/tools/test_tree_feature_parity.py +++ b/tools/test_tree_feature_parity.py @@ -120,7 +120,10 @@ def main(): rules=survival.bind_definitions(*[json.loads((build/name).read_text()) for name in ['survival-classes.json','survival-placement-classes.json','survival-support-tags.json']]);(build/'survival-rules.json').write_text(json.dumps(rules,separators=(',',':'))) inputs=build/'inputs.txt';count=0 with inputs.open('w',encoding='utf-8') as output: - for fixture in corpus(facts,resources):output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 + only=os.environ.get('FEATURE_FILTER') # optional regex over feature names for focused reruns + for fixture in corpus(facts,resources): + if only and not __import__('re').search(only,fixture['feature']):continue + output.write(json.dumps(fixture,separators=(',',':'))+'\n');count+=1 fixtures=[inputs,*sorted(build.glob('*.nbt')),*[p for p in sorted(build.glob('*.json')) if p.name!='report.json']];tested_fixtures=fixture_hashes(fixtures) print(f'Prepared {count:,} feature fixtures',flush=True) run(['cargo','build','--release','-p','horizon-world','--example','tree_feature_fixture'],'compile-rust') From 6b80229269e05c52b295059680b3725f29b95cdb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 8 Oct 2026 01:38:28 +0200 Subject: [PATCH 12/12] Decode clamped_normal integer providers Mth.normal sampling with float clamping and a saturating int cast, as used by the pointed dripstone and sulfur spike placement offsets. Co-Authored-By: Claude Opus 5.5 (1M context) --- .../src/worldgen/value_provider.rs | 26 ++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/horizon-world/src/worldgen/value_provider.rs b/crates/horizon-world/src/worldgen/value_provider.rs index bee692502..ba081e3e9 100644 --- a/crates/horizon-world/src/worldgen/value_provider.rs +++ b/crates/horizon-world/src/worldgen/value_provider.rs @@ -123,6 +123,12 @@ pub enum IntProvider { min: i32, max: i32, }, + ClampedNormal { + mean: f32, + deviation: f32, + min: i32, + max: i32, + }, } impl IntProvider { pub fn from_json(json: &str) -> Result { @@ -170,6 +176,12 @@ impl IntProvider { } Ok(Self::Trapezoid { min, max, plateau }) } + "minecraft:clamped_normal" => Ok(Self::ClampedNormal { + mean: required(&object, "mean").and_then(float)?, + deviation: required(&object, "deviation").and_then(float)?, + min, + max, + }), "minecraft:clamped" => Ok(Self::Clamped { source: Box::new(Self::decode( required(&object, "source")?, @@ -196,7 +208,8 @@ impl IntProvider { Self::Uniform { min, max } | Self::BiasedToBottom { min, max } | Self::VeryBiasedToBottom { min, max } - | Self::Trapezoid { min, max, .. } => [*min, *max], + | Self::Trapezoid { min, max, .. } + | Self::ClampedNormal { min, max, .. } => [*min, *max], Self::Clamped { source, min, max } => { let bounds = source.bounds(); [(*min).max(bounds[0]), (*max).min(bounds[1])] @@ -236,6 +249,17 @@ impl IntProvider { let value = source.sample(random)?; Ok(if value < *min { *min } else { value.min(*max) }) } + // Mth.normal, then float Mth.clamp and a saturating int cast. + Self::ClampedNormal { + mean, + deviation, + min, + max, + } => { + let value = mean + random.next_gaussian() as f32 * deviation; + let (min, max) = (*min as f32, *max as f32); + Ok((if value < min { min } else { value.min(max) }) as i32) + } } } }