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] 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)) + } +}