diff --git a/crates/horizon-world/src/worldgen.rs b/crates/horizon-world/src/worldgen.rs index a9828cc18..f9cf00a62 100644 --- a/crates/horizon-world/src/worldgen.rs +++ b/crates/horizon-world/src/worldgen.rs @@ -34,6 +34,7 @@ pub mod feature_region; pub mod feature_sort; pub mod fluid_predicate; pub mod generator; +mod generator_blocks; mod generator_decoration; pub mod height_provider; pub mod material_condition; diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 3a4647278..e3fe337aa 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -142,6 +142,9 @@ pub(super) struct FeatureResources { pub(super) placed: BTreeMap, pub(super) feature_tags: BTreeMap, pub(super) fluid_tags: BTreeMap>, + pub(super) state_providers: BTreeMap, + /// Block properties, support, collision and survival for placement checks. + pub(super) blocks: Option, } /// Seed-independent generation resources, loaded once and shared by every @@ -255,7 +258,8 @@ impl GeneratorData { /// per registry state. Multi-noise tables come from `presets.json` /// (quantized) or `biome_parameters/.json` data-generator reports. /// Optional decoration inputs: `features`, `placed_features`, - /// `feature_tags`, `fluid_tags`. Integer block properties are derived from + /// `feature_tags`, `fluid_tags`, `state_providers` and the Java-exported + /// block behavior files in `blocks/` (see `generator_blocks`). Integer block properties are derived from /// the registry: properties whose every value is a decimal integer. pub fn load(dir: &Path, registry: &'static BlockRegistry) -> Result, GeneratorError> { let flags: Vec<(bool, bool)> = @@ -376,7 +380,15 @@ impl GeneratorData { features, placed, feature_tags: read_optional_bundle(dir, "feature_tags")?.unwrap_or_default(), + blocks: super::generator_blocks::BlockBehavior::load( + &dir.join("blocks"), + registry, + &block_tags, + &fluid_tags, + )?, fluid_tags, + state_providers: read_optional_bundle(dir, "state_providers")? + .unwrap_or_default(), }) } _ => None, @@ -512,11 +524,12 @@ struct Pipeline { extensions: MaterialExtensions, picker: GlobalFluidPicker, zoom: BiomeZoom, - biome_cache: Mutex>>>, + biome_cache: BiomeCache, carver_cache: Mutex>, pub(super) decoration: Option, } const CACHE_LIMIT: usize = 16384; +type BiomeCache = Mutex>>>; fn state(registry: &BlockRegistry, raw: &Value) -> Result { let name = raw @@ -1052,7 +1065,25 @@ where ) -> Result { match &self.decoration { Some(decoration) => { - decoration.decorate(&self.data, self.seed, self.generation(), worker, region) + let center = region[4].position(); + // WorldGenRegion's level random, positioned at the center chunk. + let mut random = self + .root + .from_hash_of("minecraft:worldgen_region_random") + .fork_positional() + .at(BlockPos::new( + center.x.wrapping_shl(4), + 0, + center.z.wrapping_shl(4), + )); + decoration.decorate( + &self.data, + self.seed, + self.generation(), + worker, + region, + || random.next_boolean(), + ) } None => Err(resource("decoration resources were not loaded")), } diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs new file mode 100644 index 000000000..262a8cb2d --- /dev/null +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -0,0 +1,161 @@ +//! Optional block-behavior registries used by feature placement: physical +//! properties, face support, collision and survival rules. Loaded from the +//! bundle's `blocks/` directory (Java-exported, see prepare_native_client.py). +use super::generator::GeneratorError; +use crate::{ + block_collision::BlockCollisionRegistry, + block_properties::BlockPropertiesRegistry, + block_support::BlockSupportRegistry, + block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule}, + collision::CachedCollisionRegistry, + nbt::{self, Limits, Tag}, + registry::BlockRegistry, +}; +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + fs, + path::Path, + sync::Arc, +}; + +pub(super) struct BlockBehavior { + pub(super) properties: BlockPropertiesRegistry<'static>, + pub(super) support: Arc>, + pub(super) collision: Arc>, + pub(super) survival: BlockSurvivalRegistry<'static>, + pub(super) double_plants: BTreeSet, + pub(super) mossy_carpets: BTreeSet, +} +fn resource(message: impl Into) -> GeneratorError { + GeneratorError::Resource(message.into()) +} +fn rule(name: &str) -> Option { + use SurvivalRule::*; + if let Some(tag) = name.strip_prefix("TagBelow:") { + return Some(TagBelow(tag.to_owned())); + } + Some(match name { + "CactusFlower" => CactusFlower, + "Seagrass" => Seagrass, + "BubbleColumn" => BubbleColumn, + "RedstoneWire" => RedstoneWire, + "DoublePlant" => DoublePlant, + "Door" => Door, + "BigDripleaf" => BigDripleaf, + "BigDripleafStem" => BigDripleafStem, + "Farmland" => Farmland, + "Cocoa" => Cocoa, + "Crop" => Crop, + "GrowingPlant" => GrowingPlant, + "MangrovePropagule" => MangrovePropagule, + "Speleothem" => Speleothem, + "Scaffolding" => Scaffolding, + "PistonHead" => PistonHead, + "ChorusPlant" => ChorusPlant, + "ChorusFlower" => ChorusFlower, + "PitcherCrop" => PitcherCrop, + "Multiface" => Multiface, + "Vine" => Vine, + "HangingMoss" => HangingMoss, + "SnowLayer" => SnowLayer, + "SeaPickle" => SeaPickle, + "Fire" => Fire, + "Cactus" => Cactus, + "Path" => Path, + "Mushroom" => Mushroom, + "Bell" => Bell, + "SugarCane" => SugarCane, + "LilyPad" => LilyPad, + "Frogspawn" => Frogspawn, + "SporeBlossom" => SporeBlossom, + "SmallDripleaf" => SmallDripleaf, + "TallSeagrass" => TallSeagrass, + "Always" => Always, + "SolidBelow" => SolidBelow, + "SolidBehind" => SolidBehind, + "NonAirBelow" => NonAirBelow, + "MossCarpet" => MossCarpet, + "CenterBelow" => CenterBelow, + "Lantern" => Lantern, + "FullAbove" => FullAbove, + "FullBehind" => FullBehind, + "RigidOrCenterBelow" => RigidOrCenterBelow, + "RigidBelow" => RigidBelow, + "FullBelow" => FullBelow, + "CenterAbove" => CenterAbove, + "FaceAttached" => FaceAttached, + "SupportsBamboo" => SupportsBamboo, + _ => return None, + }) +} +impl BlockBehavior { + /// Files: `block-properties.nbt`, `cached-collision.nbt`, + /// `cached-support.nbt`, `survival-rules.json`, + /// `survival-extra-definitions.json` and `placement-definitions.json`. + pub(super) fn load( + dir: &Path, + registry: &'static BlockRegistry, + tags: &BTreeMap>, + fluid_tags: &BTreeMap>, + ) -> Result, GeneratorError> { + if !dir.join("block-properties.nbt").exists() { + return Ok(None); + } + let read = |name: &str| -> Result { + let limits = Limits { + max_bytes: 1 << 28, + ..Limits::default() + }; + Ok(nbt::read_named(&fs::read(dir.join(name))?, limits) + .map_err(|e| resource(format!("{name}: {e:?}")))? + .0 + .tag) + }; + let json = |name: &str| -> Result { + Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) + }; + let collisions = CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; + let properties = BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; + let support = Arc::new(BlockSupportRegistry::from_nbt( + &read("cached-support.nbt")?, + registry, + )?); + let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); + let rules = json("survival-rules.json")? + .as_object() + .ok_or_else(|| resource("survival rules"))? + .iter() + .map(|(name, value)| { + let text = value.as_str().unwrap_or_default(); + rule(text) + .map(|rule| (name.clone(), rule)) + .ok_or_else(|| resource(format!("unknown survival rule {text}"))) + }) + .collect::>()?; + let extra = json("survival-extra-definitions.json")?; + let definitions = SurvivalDefinitions { + rules, + ignition_odds: serde_json::from_value(extra["ignition_odds"].clone())?, + fence_gates: serde_json::from_value(extra["fence_gates"].clone())?, + }; + let survival = BlockSurvivalRegistry::new( + registry, + &properties, + support.clone(), + collision.clone(), + &definitions, + tags, + fluid_tags, + )?; + let placement = json("placement-definitions.json")?; + Ok(Some(Self { + double_plants: serde_json::from_value(placement["double_plants"].clone())?, + mossy_carpets: serde_json::from_value(placement["mossy_carpets"].clone())?, + properties, + support, + collision, + survival, + })) + } +} diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index e298de8cc..09cfe1b07 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -27,13 +27,23 @@ use super::{ terrain::PreLightChunkStage, write_zone::GenerationWriteZone, }; +use super::{ + generator_blocks::BlockBehavior, + state_provider::{StateProviderBindings, StateProviderCatalog}, +}; use crate::{ + block_collision::{DynamicCollisionWorld, ShulkerCollisionState}, + block_placement::BlockPlacementBindings, + block_support::SupportType, + block_survival::SurvivalWorld, + dynamic_support::DynamicSupportWorld, fluid::{FluidKind, FluidState}, heightmap::{HeightmapState, HeightmapType}, registry::BlockStateId, }; use horizon_core::{ biome::obfuscate_seed, + geometry::{Direction, VoxelShape}, position::{BlockPos, ChunkPos}, }; use serde_json::Value; @@ -111,10 +121,31 @@ impl Decoration { .collect(), &data.biome_tags, )?); - let bindings = + let mut bindings = FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)? .with_fluid_tags(&resources.fluid_tags)? - .with_biomes(biomes); + .with_biomes(biomes.clone()); + if let Some(blocks) = &resources.blocks { + bindings = bindings + .with_block_properties(&blocks.properties)? + .with_state_providers( + StateProviderBindings::new( + registry, + data.integers().clone(), + &data.block_tags, + )? + .with_block_properties(&blocks.properties)? + .with_fluid_tags(&resources.fluid_tags)? + .with_biomes(biomes), + StateProviderCatalog::from_resources(&resources.state_providers)?, + BlockPlacementBindings::new( + registry, + &blocks.properties, + &blocks.double_plants, + &blocks.mossy_carpets, + )?, + )?; + } let tags = feature_tags .build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned())) .map_err(|e| resource(format!("feature tags: {e:?}")))? @@ -196,6 +227,7 @@ impl Decoration { generation: WorldGenerationContext, worker: &mut WorkerState, region: &mut [ProtoChunk; 9], + next_boolean: impl FnMut() -> bool, ) -> Result { let center = region[4].position(); for (i, chunk) in region.iter().enumerate() { @@ -234,7 +266,13 @@ impl Decoration { Ok(terrain) => terrain, Err(e) => return Err(resource(e.to_string())), }; + let mut next_boolean = next_boolean; let mut world = World { + next_boolean: &mut next_boolean, + blocks: data + .feature_resources + .as_ref() + .and_then(|r| r.blocks.as_ref()), region: terrain, biomes: BiomeRegion::new(biomes, obfuscate_seed(seed)) .map_err(|e| resource(e.to_string()))?, @@ -287,6 +325,8 @@ impl Decoration { /// WorldGenRegion-style view: reads anywhere in the 3×3 region, writes within /// the FEATURES step's write radius, biome lookups through the biome zoom. struct World<'a> { + next_boolean: &'a mut dyn FnMut() -> bool, + blocks: Option<&'a BlockBehavior>, region: TerrainRegion<'static, GenBlockStates>, biomes: BiomeRegion, zone: GenerationWriteZone, @@ -335,7 +375,113 @@ impl FeatureWorld for World<'_> { fn query(e: impl std::fmt::Display) -> PlacementQueryError { PlacementQueryError::Failed(e.to_string()) } +impl<'a> World<'a> { + fn blocks(&self) -> Result<&'a BlockBehavior, PlacementQueryError> { + self.blocks.ok_or(PlacementQueryError::Unavailable) + } +} +/// Proto chunks hold no block entities, so dynamic shapes resolve to absent. +impl DynamicSupportWorld for World<'_> { + type Error = PlacementQueryError; + fn shulker_is_closed(&mut self, _: [i32; 3]) -> Result, PlacementQueryError> { + Ok(None) + } + fn moving_piston_shape( + &mut self, + _: [i32; 3], + ) -> Result, PlacementQueryError> { + Ok(None) + } +} +impl DynamicCollisionWorld for World<'_> { + fn shulker_collision_state( + &mut self, + _: [i32; 3], + ) -> Result, PlacementQueryError> { + Ok(None) + } +} +impl SurvivalWorld for World<'_> { + fn fluid_state(&mut self, position: [i32; 3]) -> Result { + self.region.fluid_state(position) + } + /// Unlit generation chunks report no sky or block light. + fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> Result { + Ok(0) + } + fn block_state(&mut self, position: [i32; 3]) -> Result { + self.region.block_state(position) + } +} impl PlacementContext for World<'_> { + fn state_collision_empty( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + let collision = self.blocks()?.collision.clone(); + collision + .collision_shape(self, state, position) + .map(|shape| shape.is_empty()) + .map_err(query) + } + /// Block entities are not stored in proto chunks; loot tables are no-ops. + fn set_block_entity_loot_table( + &mut self, + _: [i32; 3], + _: &str, + _: &mut impl horizon_core::random::RandomSource, + ) -> Result<(), PlacementQueryError> { + Ok(()) + } + fn attachment_at( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let blocks = self.blocks()?; + blocks + .survival + .can_attach_to(self, position, direction) + .map_err(query) + } + fn next_world_boolean(&mut self) -> Result { + Ok((self.next_boolean)()) + } + fn block_survives( + &mut self, + state: BlockStateId, + position: [i32; 3], + ) -> Result { + let blocks = self.blocks()?; + blocks + .survival + .can_survive(self, state, position) + .map_err(query) + } + fn face_sturdy( + &mut self, + position: [i32; 3], + direction: Direction, + ) -> Result { + let state = self.region.block_state(position)?; + self.state_face_sturdy(state, position, direction) + } + fn state_face_sturdy( + &mut self, + state: BlockStateId, + position: [i32; 3], + direction: Direction, + ) -> Result { + let support = self.blocks()?.support.clone(); + support + .is_face_sturdy(self, state, position, direction, SupportType::Full) + .map_err(query) + } + /// Generation regions contain no entities. + fn unobstructed_block(&mut self, _: [i32; 3]) -> Result { + Ok(true) + } fn destroy_block_without_entity( &mut self, position: [i32; 3], diff --git a/tools/prepare_native_client.py b/tools/prepare_native_client.py index 6d96390e8..f5dd4372c 100644 --- a/tools/prepare_native_client.py +++ b/tools/prepare_native_client.py @@ -42,12 +42,27 @@ def prepare_worldgen(root, jars, local): (out/'block_flags.json').write_text(json.dumps([[s[1], s[2]] for s in facts['states']], separators=(',', ':'))) reports = out/'biome_parameters' reports.mkdir(exist_ok=True) + presets = reports for source in [root/'biome-parameters', local/'datagen/out/reports/biome_parameters/minecraft']: if (source/'overworld.json').exists(): for report in sorted(source.glob('*.json')): (reports/report.name).write_bytes(report.read_bytes()) break else: + presets = None + # Block behavior used by feature placement checks (survival, support, collision). + # These come from the Java exporters of the simple-block parity run. + behavior = local/'rust-simple-block-parity' + blocks = out/'blocks' + names = ['block-properties.nbt', 'cached-collision.nbt', 'cached-support.nbt', 'survival-rules.json', + 'survival-extra-definitions.json', 'placement-definitions.json'] + if all((behavior/name).exists() for name in names): + blocks.mkdir(exist_ok=True) + for name in names: + (blocks/name).write_bytes((behavior/name).read_bytes()) + else: + print('Feature block behavior exports missing; run tools/test_simple_block_parity.py for full decoration') + if presets is None: # Fall back to the Java-exported quantized tables from the material-stage parity run. presets = local/'rust-material-stage-parity/presets.json' if not presets.exists():