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) <noreply@anthropic.com>
This commit is contained in:
@@ -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<String, BTreeSet<BlockStateId>>,
|
||||
support: &'a BlockSupportRegistry<'r>,
|
||||
survival: &'a BlockSurvivalRegistry<'r>,
|
||||
collision: &'a BlockCollisionRegistry<'r>,
|
||||
seed: i64,
|
||||
chest: BlockStateId,
|
||||
world_random: LegacyRandom,
|
||||
water_mask: u8,
|
||||
}
|
||||
impl<W: Write> World<'_, '_, W> {
|
||||
fn get(&self, p: [i32; 3]) -> BlockStateId {
|
||||
@@ -140,7 +164,77 @@ impl<W: Write> DynamicSupportWorld for World<'_, '_, W> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
impl<W: Write> DynamicCollisionWorld for World<'_, '_, W> {
|
||||
fn shulker_collision_state(&mut self, _: [i32; 3]) -> io::Result<Option<ShulkerCollisionState>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
impl<W: Write> SurvivalWorld for World<'_, '_, W> {
|
||||
fn block_state(&mut self, p: [i32; 3]) -> io::Result<BlockStateId> {
|
||||
Ok(self.get(p))
|
||||
}
|
||||
fn fluid_state(&mut self, p: [i32; 3]) -> io::Result<FluidState> {
|
||||
self.fluids
|
||||
.get(self.get(p))
|
||||
.ok_or_else(|| io::Error::other("unknown fluid"))
|
||||
}
|
||||
fn raw_brightness(&mut self, _: [i32; 3], _: i32) -> io::Result<i32> {
|
||||
Ok(15)
|
||||
}
|
||||
}
|
||||
impl<W: Write> PlacementContext for World<'_, '_, W> {
|
||||
fn world_seed(&mut self) -> Result<i64, PlacementQueryError> {
|
||||
Ok(self.seed)
|
||||
}
|
||||
fn next_world_boolean(&mut self) -> Result<bool, PlacementQueryError> {
|
||||
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<i32, PlacementQueryError> {
|
||||
Ok(15)
|
||||
}
|
||||
fn sea_level(&mut self) -> Result<i32, PlacementQueryError> {
|
||||
Ok(63)
|
||||
}
|
||||
fn water_at(&mut self, p: [i32; 3]) -> Result<bool, PlacementQueryError> {
|
||||
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<bool, PlacementQueryError> {
|
||||
let survival = self.survival;
|
||||
survival.can_survive(self, state, p).map_err(query)
|
||||
}
|
||||
fn attachment_at(&mut self, p: [i32; 3], direction: Direction) -> Result<bool, PlacementQueryError> {
|
||||
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<bool, PlacementQueryError> {
|
||||
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<R: RandomSource>(
|
||||
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<R: RandomSource>(
|
||||
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<dyn std::error::Error>> {
|
||||
let arg = std::env::args().nth(1).expect("private fixture directory");
|
||||
let dir = Path::new(&arg);
|
||||
@@ -268,6 +422,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
serde_json::from_str(&fs::read_to_string(dir.join("vanilla-features.json"))?)?;
|
||||
let providers: BTreeMap<String, String> = serde_json::from_value(bundle["providers"].clone())?;
|
||||
let features: BTreeMap<String, String> = serde_json::from_value(bundle["features"].clone())?;
|
||||
let placed: BTreeMap<String, String> = 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<dyn std::error::Error>> {
|
||||
&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::<String, Vec<BlockStateId>>::new();
|
||||
@@ -310,6 +465,36 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
})
|
||||
.collect();
|
||||
let support = Arc::new(support);
|
||||
let definitions_text: BTreeMap<String, String> =
|
||||
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<dyn std::error::Error>> {
|
||||
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() {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<E>(error: PlacementQueryError) -> FeatureExecutionError<E> {
|
||||
FeatureExecutionError::Query(error)
|
||||
}
|
||||
/// Column.scan result: optional floor and ceiling edge heights.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Column {
|
||||
floor: Option<i32>,
|
||||
ceiling: Option<i32>,
|
||||
}
|
||||
impl Column {
|
||||
fn height(&self) -> Option<i32> {
|
||||
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<BTreeSet<BlockStateId>>,
|
||||
lava: BlockStateId,
|
||||
blocks: Arc<TreeBlocks>,
|
||||
}
|
||||
impl Speleothem {
|
||||
fn new(
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
base: BlockStateId,
|
||||
pointed: BlockStateId,
|
||||
replaceable: Arc<BTreeSet<BlockStateId>>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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<W: FeatureWorld>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
pos: [i32; 3],
|
||||
range: i32,
|
||||
edge: impl Fn(&Self, BlockStateId) -> bool,
|
||||
) -> TreeResult<Option<Column>, W::Error> {
|
||||
if !self.empty_or_water(read(world, pos)?) {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut scan = |step: i32| -> TreeResult<Option<i32>, 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<BlockStateId> {
|
||||
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<W: FeatureWorld + PlacementContext>(
|
||||
&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<W: FeatureWorld>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
p: [i32; 3],
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<FloatProvider, DecodeError> {
|
||||
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<f32, DecodeError> {
|
||||
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<BlockStateId, DecodeError> {
|
||||
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<Self, DecodeError> {
|
||||
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<W: FeatureWorld + PlacementContext, R: RandomSource>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
random: &mut R,
|
||||
origin: [i32; 3],
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld + PlacementContext, R: RandomSource>(
|
||||
&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<E>(
|
||||
&self,
|
||||
random: &mut impl RandomSource,
|
||||
dx: i32,
|
||||
dz: i32,
|
||||
density: f32,
|
||||
max_height: i32,
|
||||
) -> TreeResult<i32, E> {
|
||||
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<W: FeatureWorld + PlacementContext>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
p: [i32; 3],
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld>(&self, world: &mut W, p: [i32; 3]) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld>(
|
||||
&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<Self, DecodeError> {
|
||||
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<W: FeatureWorld + PlacementContext, R: RandomSource>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
random: &mut R,
|
||||
origin: [i32; 3],
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
d: &mut LargeDripstone,
|
||||
wind: Wind,
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld>(
|
||||
&self,
|
||||
world: &mut W,
|
||||
center: [i32; 3],
|
||||
radius: i32,
|
||||
) -> TreeResult<bool, W::Error> {
|
||||
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<W: FeatureWorld + PlacementContext, R: RandomSource>(
|
||||
&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(())
|
||||
}
|
||||
}
|
||||
@@ -77,6 +77,8 @@ pub enum FeatureDefinition {
|
||||
Geode(Box<super::cave::GeodeFeature>),
|
||||
Iceberg(Box<super::iceberg::IcebergFeature>),
|
||||
RootSystem(Box<super::root_system::RootSystemFeature>),
|
||||
SpeleothemCluster(Box<super::dripstone::SpeleothemClusterFeature>),
|
||||
LargeDripstone(Box<super::dripstone::LargeDripstoneFeature>),
|
||||
FallenTree(Box<super::tree::FallenTreeFeature>),
|
||||
NoOp,
|
||||
WeightedChoice(OptionalWeightedList<PlacedFeatureDefinition>),
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<BlockPos,Integer> overrides=new HashMap<>();
|
||||
final int[][] layers;final int[][] boxes;final int holeMod,holeState,obstacleMod,obstacleState,obstacleMin;final Map<BlockPos,Integer> overrides=new HashMap<>();
|
||||
Terrain(JsonObject f){
|
||||
var raw=f.getAsJsonArray("layers");layers=new int[raw.size()][];for(int i=0;i<raw.size();i++){var l=raw.get(i).getAsJsonArray();layers[i]=new int[]{l.get(0).getAsInt(),l.get(1).getAsInt()};}
|
||||
var rawBoxes=f.has("boxes")?f.getAsJsonArray("boxes"):new JsonArray();boxes=new int[rawBoxes.size()][7];
|
||||
for(int i=0;i<rawBoxes.size();i++)for(int j=0;j<7;j++)boxes[i][j]=rawBoxes.get(i).getAsJsonArray().get(j).getAsInt();
|
||||
holeMod=f.get("hole_mod").getAsInt();holeState=f.get("hole_state").getAsInt();obstacleMod=f.get("obstacle_mod").getAsInt();obstacleState=f.get("obstacle_state").getAsInt();obstacleMin=f.get("obstacle_min").getAsInt();
|
||||
for(var e:f.getAsJsonArray("states")){var v=e.getAsJsonArray();overrides.put(pos(v),v.get(3).getAsInt());}
|
||||
}
|
||||
static int hash(int x,int y,int z){int h=x*73856093^y*19349663^z*83492791;h^=h>>>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<ChunkPos,ProtoChunk> chunks=new HashMap<>();final Map<BlockPos,BeehiveBlockEntity> hives=new HashMap<>();
|
||||
final JsonObject f;final PrintWriter out;final Terrain terrain;final Map<ChunkPos,ProtoChunk> chunks=new HashMap<>();final Map<BlockPos,BeehiveBlockEntity> hives=new HashMap<>();final Map<BlockPos,ChestBlockEntity> chests=new HashMap<>();final Map<BlockPos,SpawnerBlockEntity> 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<net.minecraft.world.level.material.FluidState>)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<net.minecraft.world.level.storage.loot.LootTable> 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<T> implements HolderGetter<T>, HolderOwner<T> {
|
||||
JsonObject json;com.mojang.serialization.Codec<T> codec;RegistryOps<JsonElement> ops;final Map<ResourceKey<T>,Holder.Reference<T>> cache=new HashMap<>();
|
||||
public Optional<Holder.Reference<T>> get(ResourceKey<T> 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<HolderSet.Named<T>> get(net.minecraft.tags.TagKey<T> tag){return Optional.empty();}
|
||||
}
|
||||
static final Lazy<Feature> lazyFeatures=new Lazy<>();
|
||||
static final Lazy<net.minecraft.world.level.levelgen.placement.PlacedFeature> 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<BlockStateProvider>(Registries.BLOCK_STATE_PROVIDER,com.mojang.serialization.Lifecycle.stable());
|
||||
var ops=RegistryOps.create(JsonOps.INSTANCE,new RegistryOps.RegistryInfoLookup(){public <T> Optional<HolderGetter<T>> lookup(ResourceKey<? extends Registry<? extends T>> key){
|
||||
if(key.equals(Registries.BLOCK_STATE_PROVIDER))return (Optional<HolderGetter<T>>)(Optional<?>)Optional.of(providers);
|
||||
if(key.equals(Registries.FEATURE))return (Optional<HolderGetter<T>>)(Optional<?>)Optional.of(lazyFeatures);
|
||||
if(key.equals(Registries.PLACED_FEATURE))return (Optional<HolderGetter<T>>)(Optional<?>)Optional.of(lazyPlaced);
|
||||
if(key.equals(Registries.FLUID))return (Optional<HolderGetter<T>>)(Optional<?>)Optional.of(BuiltInRegistries.FLUID);
|
||||
return key.equals(Registries.BLOCK)?(Optional<HolderGetter<T>>)(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<String>)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.<ChunkPos>comparingInt(ChunkPos::x).thenComparingInt(ChunkPos::z));
|
||||
var changes=new TreeMap<BlockPos,Integer>(Comparator.<BlockPos>comparingInt(BlockPos::getX).thenComparingInt(BlockPos::getY).thenComparingInt(BlockPos::getZ));
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user