Grow saplings, fungi and mushrooms and apply bone meal through live feature placement

Port TreeGrower (all growers incl. 2x2 dark oak, pale oak, mega spruce/jungle,
mangrove, azalea, poplar), BoneMealItem.useOn/growCrop/growWaterPlant and every
BonemealableBlock. Configured and placed features run on the live level via a
FeatureWorld/PlacementContext adapter with vanilla setBlock semantics. Also fix
torchflower crops never maturing and kelp growth into flowing water.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-08 15:09:34 +02:00
parent 1b38d82aac
commit 0a4a4ea643
9 changed files with 2452 additions and 14 deletions
File diff suppressed because it is too large Load Diff
+1
View File
@@ -1084,6 +1084,7 @@ pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result<Behaviou
liquid_blocks,
dynamic,
occlusion_cache: Default::default(),
growth: Default::default(),
})
}
@@ -0,0 +1,293 @@
//! The live level as a feature-placement world (`ServerLevel` passed to
//! `Feature.place`): reads and writes go through the behaviour library, so
//! features placed by saplings, fungi and bone meal get vanilla's
//! `Level.setBlock` update semantics for the flags they request.
use super::{LevelAccess, Sim, data::state_flags, update::rel};
use crate::{
fluid::{FluidKind, FluidState},
heightmap::HeightmapType,
registry::BlockStateId,
worldgen::{
anchor::WorldGenerationContext,
biome::BiomeId,
feature::FeatureWorld,
live::LiveFeatures,
placement::{LayerBlock, PlacementContext, PlacementQueryError},
},
};
use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource};
pub(crate) struct LevelFeatureWorld<'s, 'a, L: LevelAccess + ?Sized> {
pub sim: &'s mut Sim<'a, L>,
pub features: &'s LiveFeatures,
}
fn pos([x, y, z]: [i32; 3]) -> BlockPos {
BlockPos::new(x, y, z)
}
impl<L: LevelAccess + ?Sized> LevelFeatureWorld<'_, '_, L> {
fn sea(&self) -> i32 {
match self.sim.level.dimension() {
super::Dimension::Nether => 32,
super::Dimension::End => 0,
super::Dimension::Overworld => 63,
}
}
fn in_tag(&self, state: BlockStateId, tag: &str) -> bool {
let name = tag.trim_start_matches('#');
self.sim
.b
.tag(name)
.is_some_and(|set| set.contains(self.sim.b.block(state)))
}
}
impl<L: LevelAccess + ?Sized> FeatureWorld for LevelFeatureWorld<'_, '_, L> {
type Error = PlacementQueryError;
fn block(&mut self, position: [i32; 3]) -> Result<BlockStateId, Self::Error> {
Ok(self.sim.state(pos(position)))
}
fn set_block(
&mut self,
position: [i32; 3],
state: BlockStateId,
flags: i32,
) -> Result<bool, Self::Error> {
Ok(self.sim.set_block(pos(position), state, flags))
}
}
impl<L: LevelAccess + ?Sized> PlacementContext for LevelFeatureWorld<'_, '_, L> {
/// `StructureTemplate.updateShapeAtEdge` for one face.
fn update_shape_at_face(
&mut self,
position: [i32; 3],
direction: Direction,
flags: i32,
) -> Result<(), PlacementQueryError> {
let place = pos(position);
let neighbour_pos = rel(place, direction);
let state = self.sim.state(place);
let neighbour = self.sim.state(neighbour_pos);
let new_state = self
.sim
.update_shape(state, place, direction, neighbour_pos, neighbour);
if new_state != state {
self.sim.set_block(place, new_state, flags & !1);
}
let new_neighbour = self.sim.update_shape(
neighbour,
neighbour_pos,
direction.opposite(),
place,
new_state,
);
if new_neighbour != neighbour {
self.sim.set_block(neighbour_pos, new_neighbour, flags & !1);
}
Ok(())
}
fn set_section_block(
&mut self,
position: [i32; 3],
state: BlockStateId,
) -> Result<(), PlacementQueryError> {
self.sim.level.set_raw(pos(position), state);
Ok(())
}
fn collision_full_block(
&mut self,
state: BlockStateId,
_position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
Ok(self.sim.b.full_collision(state))
}
fn world_seed(&mut self) -> Result<i64, PlacementQueryError> {
Ok(self.sim.level.world_seed())
}
fn state_collision_empty(
&mut self,
state: BlockStateId,
_position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
Ok(self.sim.b.has_flag(state, state_flags::COLLISION_EMPTY))
}
/// Live levels hold no loot-table containers placed by these features.
fn set_block_entity_loot_table(
&mut self,
_position: [i32; 3],
_table: &str,
_random: &mut impl RandomSource,
) -> Result<(), PlacementQueryError> {
Ok(())
}
fn block_brightness(&mut self, position: [i32; 3]) -> Result<i32, PlacementQueryError> {
Ok(self.sim.level.block_light(pos(position)))
}
fn fluid_state(&mut self, position: [i32; 3]) -> Result<FluidState, PlacementQueryError> {
Ok(self.sim.fluid_at(pos(position)))
}
fn destroy_block_without_entity(
&mut self,
position: [i32; 3],
drop_resources: bool,
) -> Result<bool, PlacementQueryError> {
Ok(self
.sim
.destroy_block(pos(position), drop_resources, super::flags::UPDATE_LIMIT))
}
fn sea_level(&mut self) -> Result<i32, PlacementQueryError> {
Ok(self.sea())
}
fn schedule_fluid_tick(
&mut self,
position: [i32; 3],
fluid: FluidKind,
delay: i32,
) -> Result<(), PlacementQueryError> {
self.sim.schedule_fluid_tick(pos(position), fluid, delay);
Ok(())
}
/// Live chunks are already post-processed.
fn mark_postprocessing(&mut self, _position: [i32; 3]) -> Result<(), PlacementQueryError> {
Ok(())
}
fn water_at(&mut self, position: [i32; 3]) -> Result<bool, PlacementQueryError> {
let kind = self.sim.fluid_at(pos(position)).kind();
Ok(self.sim.b.is_water_fluid(kind))
}
fn attachment_at(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let neighbour = self.sim.state(rel(pos(position), direction));
Ok(self.sim.b.multiface_can_attach(neighbour, direction))
}
fn next_world_boolean(&mut self) -> Result<bool, PlacementQueryError> {
Ok(self.sim.random().next_boolean())
}
fn next_world_float(&mut self) -> Result<f32, PlacementQueryError> {
Ok(self.sim.random().next_float())
}
fn next_world_int(&mut self, bound: i32) -> Result<i32, PlacementQueryError> {
self.sim
.random()
.next_int_bound(bound)
.map_err(|e| PlacementQueryError::Failed(e.to_string()))
}
fn schedule_block_tick(
&mut self,
position: [i32; 3],
block: BlockStateId,
delay: i32,
) -> Result<(), PlacementQueryError> {
let block = self.sim.b.block(block);
self.sim.schedule_tick(pos(position), block, delay);
Ok(())
}
fn block_survives(
&mut self,
state: BlockStateId,
position: [i32; 3],
) -> Result<bool, PlacementQueryError> {
Ok(self.sim.can_survive(state, pos(position)))
}
fn state_face_sturdy(
&mut self,
state: BlockStateId,
_position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
Ok(self.sim.b.is_face_sturdy(state, direction))
}
fn face_sturdy(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.sim.state(pos(position));
Ok(self.sim.b.is_face_sturdy(state, direction))
}
fn center_sturdy(
&mut self,
position: [i32; 3],
direction: Direction,
) -> Result<bool, PlacementQueryError> {
let state = self.sim.state(pos(position));
Ok(self.sim.b.is_face_sturdy_center(state, direction))
}
fn unobstructed_block(&mut self, position: [i32; 3]) -> Result<bool, PlacementQueryError> {
let stone = self.sim.b.default_of(self.sim.b.named.stone);
Ok(self.sim.level.is_unobstructed(pos(position), stone))
}
fn biome_identity(&mut self, position: [i32; 3]) -> Result<BiomeId, PlacementQueryError> {
self.sim
.level
.biome_name(pos(position))
.and_then(|name| self.features.biome_id(name))
.ok_or(PlacementQueryError::Unavailable)
}
fn block_state(&mut self, position: [i32; 3]) -> Result<BlockStateId, PlacementQueryError> {
Ok(self.sim.state(pos(position)))
}
fn block_matches_tag(
&mut self,
position: [i32; 3],
tag: &str,
) -> Result<bool, PlacementQueryError> {
let state = self.sim.state(pos(position));
Ok(self.in_tag(state, tag))
}
fn max_y(&mut self) -> Result<i32, PlacementQueryError> {
Ok(self.sim.level.max_y() - 1)
}
fn layer_block(&mut self, position: [i32; 3]) -> Result<LayerBlock, PlacementQueryError> {
let state = self.sim.state(pos(position));
let b = self.sim.b;
let block = b.block(state);
Ok(
if b.is_air(state) || block == b.named.water || block == b.named.lava {
LayerBlock::Empty
} else if b.table.name(state) == "minecraft:bedrock" {
LayerBlock::Bedrock
} else {
LayerBlock::Ground
},
)
}
fn generation(&self) -> WorldGenerationContext {
let min_y = self.sim.level.min_y();
WorldGenerationContext::new(min_y, self.sim.level.max_y() - min_y, self.sea())
}
fn min_y(&mut self) -> Result<i32, PlacementQueryError> {
Ok(self.sim.level.min_y())
}
/// `Level.getHeight(type, x, z)`: one above the highest matching block.
fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result<i32, PlacementQueryError> {
let (min, max) = (self.sim.level.min_y(), self.sim.level.max_y());
for y in (min..max).rev() {
let state = self.sim.state(BlockPos::new(x, y, z));
let fluid = self.sim.b.fluid(state).kind() != FluidKind::Empty;
let matches = match kind {
HeightmapType::WorldSurface | HeightmapType::WorldSurfaceWg => {
!self.sim.b.is_air(state)
}
HeightmapType::OceanFloor | HeightmapType::OceanFloorWg => {
self.in_tag(state, "minecraft:blocks_motion_in_heightmap")
}
HeightmapType::MotionBlocking => {
fluid || self.in_tag(state, "minecraft:blocks_motion_in_heightmap")
}
HeightmapType::MotionBlockingNoLeaves => {
fluid || self.in_tag(state, "minecraft:blocks_motion_in_heightmap_no_leaves")
}
};
if matches {
return Ok(y + 1);
}
}
Ok(min)
}
}
+342
View File
@@ -0,0 +1,342 @@
//! Feature-placing growth: `TreeGrower.growTree` (saplings, mangrove
//! propagules, azaleas), huge mushrooms and nether fungi, run on the live level
//! through [`LiveFeatures`].
use super::{Behaviours, LevelAccess, LevelEvent, Sim, feature_world::LevelFeatureWorld, flags};
use crate::{registry::BlockStateId, worldgen::live::LiveFeatures};
use horizon_core::{position::BlockPos, random::RandomSource};
use std::sync::{Arc, OnceLock};
/// Runtime extensions of [`Behaviours`] that depend on the worldgen bundle.
#[derive(Default)]
pub struct Growth {
features: OnceLock<Arc<LiveFeatures>>,
}
impl Behaviours {
/// Install the live feature registry used by sapling growth and bone meal.
/// Without it, saplings report [`LevelEvent::GrowTree`] instead of growing.
pub fn set_live_features(&self, features: Arc<LiveFeatures>) -> bool {
self.growth.features.set(features).is_ok()
}
pub fn live_features(&self) -> Option<&Arc<LiveFeatures>> {
self.growth.features.get()
}
}
/// `TreeGrower` (vanilla's registered growers, by name).
pub(crate) struct TreeGrower {
pub name: &'static str,
trees: &'static [(&'static str, i32)],
mega_trees: &'static [(&'static str, i32)],
flower_trees: &'static [(&'static str, i32)],
shortest: Option<&'static str>,
}
pub(crate) const GROWERS: &[TreeGrower] = &[
TreeGrower {
name: "oak",
trees: &[("minecraft:oak", 9), ("minecraft:fancy_oak", 1)],
mega_trees: &[],
flower_trees: &[
("minecraft:oak_bees_005", 9),
("minecraft:fancy_oak_bees_005", 1),
],
shortest: Some("minecraft:oak"),
},
TreeGrower {
name: "spruce",
trees: &[("minecraft:spruce", 1)],
mega_trees: &[("minecraft:mega_spruce", 1), ("minecraft:mega_pine", 1)],
flower_trees: &[],
shortest: Some("minecraft:spruce"),
},
TreeGrower {
name: "mangrove",
trees: &[("minecraft:mangrove", 15), ("minecraft:tall_mangrove", 85)],
mega_trees: &[],
flower_trees: &[],
shortest: Some("minecraft:mangrove"),
},
TreeGrower {
name: "azalea",
trees: &[("minecraft:azalea_tree", 1)],
mega_trees: &[],
flower_trees: &[],
shortest: Some("minecraft:azalea_tree"),
},
TreeGrower {
name: "birch",
trees: &[("minecraft:birch", 1)],
mega_trees: &[],
flower_trees: &[("minecraft:birch_bees_005", 1)],
shortest: Some("minecraft:birch"),
},
TreeGrower {
name: "jungle",
trees: &[("minecraft:jungle_tree_no_vine", 1)],
mega_trees: &[("minecraft:mega_jungle_tree", 1)],
flower_trees: &[],
shortest: Some("minecraft:jungle_tree_no_vine"),
},
TreeGrower {
name: "acacia",
trees: &[("minecraft:acacia", 1)],
mega_trees: &[],
flower_trees: &[],
shortest: Some("minecraft:acacia"),
},
TreeGrower {
name: "cherry",
trees: &[("minecraft:cherry", 1)],
mega_trees: &[],
flower_trees: &[("minecraft:cherry_bees_005", 1)],
shortest: Some("minecraft:cherry"),
},
TreeGrower {
name: "dark_oak",
trees: &[],
mega_trees: &[("minecraft:dark_oak", 1)],
flower_trees: &[],
shortest: None,
},
TreeGrower {
name: "pale_oak",
trees: &[],
mega_trees: &[("minecraft:pale_oak_bonemeal", 1)],
flower_trees: &[],
shortest: None,
},
TreeGrower {
name: "poplar",
trees: &[
("minecraft:red_poplar", 1),
("minecraft:orange_poplar", 1),
("minecraft:yellow_poplar", 1),
],
mega_trees: &[],
flower_trees: &[],
shortest: Some("minecraft:red_poplar"),
},
];
pub(crate) fn grower(name: &str) -> Option<&'static TreeGrower> {
GROWERS.iter().find(|g| g.name == name)
}
/// `WeightedList.getRandom`: no draw for an empty list.
fn weighted<R: RandomSource>(
list: &'static [(&'static str, i32)],
random: &mut R,
) -> Option<&'static str> {
let total: i32 = list.iter().map(|e| e.1).sum();
if total == 0 {
return None;
}
let mut selection = random.next_int_bound(total).unwrap_or(0);
for &(name, weight) in list {
if selection < weight {
return Some(name);
}
selection -= weight;
}
None
}
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
/// `ConfiguredFeature.place(level, generator, level.random, pos)`. The
/// feature draws from a copy of the level random that replaces it after.
pub(crate) fn place_configured_feature(&mut self, name: &str, pos: BlockPos) -> bool {
let b = self.b;
let Some(features) = b.live_features() else {
return false;
};
let mut random = self.random().clone();
let placed = {
let mut world = LevelFeatureWorld {
sim: self,
features,
};
features.place_configured(name, &mut world, &mut random, [pos.x, pos.y, pos.z])
};
*self.random() = random;
placed
}
/// `PlacedFeature.place(level, generator, level.random, pos)`.
pub(crate) fn place_placed_feature(&mut self, name: &str, pos: BlockPos) -> bool {
let b = self.b;
let Some(features) = b.live_features() else {
return false;
};
let mut random = self.random().clone();
let placed = {
let mut world = LevelFeatureWorld {
sim: self,
features,
};
features.place_placed(name, &mut world, &mut random, [pos.x, pos.y, pos.z])
};
*self.random() = random;
placed
}
fn feature_exists(&self, name: &str) -> bool {
self.b
.live_features()
.is_some_and(|f| f.configured(name).is_some())
}
/// `TreeGrower.hasFlowers`: a flower within 2 blocks horizontally, 1 vertically.
fn tree_has_flowers(&self, pos: BlockPos) -> bool {
let b = self.b;
let Some(flowers) = b.tag("minecraft:flowers") else {
return false;
};
for y in -1..=1 {
for z in -2..=2 {
for x in -2..=2 {
if b.in_set(self.state(pos.offset(x, y, z)), flowers) {
return true;
}
}
}
}
false
}
/// `TreeGrower.findTwoByTwoSaplingPos`.
fn two_by_two(
&self,
state: BlockStateId,
pos: BlockPos,
) -> Option<(i32, i32, [(BlockStateId, BlockPos); 4])> {
let block = self.b.block(state);
for dx in [0, -1] {
for dz in [0, -1] {
let at = |x: i32, z: i32| {
let p = pos.offset(dx + x, 0, dz + z);
(self.state(p), p)
};
let around = [at(0, 0), at(1, 0), at(0, 1), at(1, 1)];
if around.iter().all(|(s, _)| self.b.is_block(*s, block)) {
return Some((dx, dz, around));
}
}
}
None
}
/// `TreeGrower.removeSapling`: the fluid's legacy block, flags 818.
fn remove_sapling(&mut self, pos: BlockPos) {
let empty = self.b.legacy_block(self.fluid_at(pos));
self.set_block(
pos,
empty,
flags::UPDATE_SKIP_ALL_SIDEEFFECTS | flags::UPDATE_CLIENTS,
);
}
/// `TreeGrower.growTree`.
pub(crate) fn grow_tree(
&mut self,
grower: &TreeGrower,
pos: BlockPos,
state: BlockStateId,
) -> bool {
if let Some(mega) = weighted(grower.mega_trees, self.random())
&& self.feature_exists(mega)
&& let Some((dx, dz, around)) = self.two_by_two(state, pos)
{
for &(_, p) in &around {
self.remove_sapling(p);
}
if self.place_configured_feature(mega, pos.offset(dx, 0, dz)) {
return true;
}
for &(s, p) in &around {
self.set_block(p, s, flags::UPDATE_NONE);
}
return false;
}
let flowers = self.tree_has_flowers(pos);
let list = if flowers && !grower.flower_trees.is_empty() {
grower.flower_trees
} else {
grower.trees
};
let Some(feature) = weighted(list, self.random()) else {
return false;
};
if !self.feature_exists(feature) {
return false;
}
self.remove_sapling(pos);
if self.place_configured_feature(feature, pos) {
return true;
}
self.set_block(pos, state, flags::UPDATE_NONE);
false
}
/// `TreeGrower.canGrow` (draws as vanilla: feature, then mega feature).
pub(crate) fn tree_can_grow(
&mut self,
grower: &TreeGrower,
pos: BlockPos,
state: BlockStateId,
) -> bool {
let flowers = self.tree_has_flowers(pos);
let list = if flowers && !grower.flower_trees.is_empty() {
grower.flower_trees
} else {
grower.trees
};
let feature = weighted(list, self.random());
let mega = weighted(grower.mega_trees, self.random());
if feature.is_none() && mega.is_some() {
self.two_by_two(state, pos).is_some()
} else {
true
}
}
/// `TreeGrower.getMinimumHeight`: the shortest tree's trunk base height.
pub(crate) fn tree_minimum_height(&self, grower: &TreeGrower) -> i32 {
grower
.shortest
.and_then(|name| self.b.live_features()?.configured_json(name))
.filter(|json| json["type"] == "minecraft:tree")
.and_then(|json| json["trunk_placer"]["base_height"].as_i64())
.map_or(0, |h| h as i32)
}
/// `SaplingBlock.advanceTree` with the grower run inline when features are
/// installed; otherwise reported as [`LevelEvent::GrowTree`].
pub(crate) fn advance_tree(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
if b.table.int(state, b.props.stage) == 0 {
self.set_block(pos, b.table.cycle(state, b.props.stage), flags::UPDATE_NONE);
return;
}
let Some(name) = b.data(state).feature.clone() else {
return;
};
match grower(&name) {
Some(g) if b.live_features().is_some() => {
self.grow_tree(g, pos, state);
}
_ => self.emit(LevelEvent::GrowTree {
pos,
state,
grower: name,
}),
}
}
/// `MushroomBlock.growMushroom`.
pub(crate) fn grow_mushroom(&mut self, pos: BlockPos, state: BlockStateId) -> bool {
let Some(feature) = self.b.data(state).feature.clone() else {
return false;
};
if !self.feature_exists(&feature) {
return false;
}
self.remove_block(pos, false);
if self.place_configured_feature(&feature, pos) {
return true;
}
self.set_block_and_update(pos, state);
false
}
}
@@ -0,0 +1,342 @@
//! Sapling growth and bone meal through live feature placement. Needs the
//! prepared client resources and worldgen bundle (skipped when absent).
use super::*;
use crate::{chunk::BlockState, worldgen::generator::GeneratorData, worldgen::live::LiveFeatures};
use std::{
collections::{BTreeMap, HashMap},
path::PathBuf,
sync::OnceLock,
};
struct Fixture {
registry: &'static BlockRegistry,
behaviours: Behaviours,
}
fn fixture() -> Option<&'static Fixture> {
static FIXTURE: OnceLock<Option<Fixture>> = OnceLock::new();
FIXTURE
.get_or_init(|| {
let root = std::env::var_os("HORIZON_RESOURCES")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../.local/horizon-client/26.3")
});
// Trees need the feature block-behaviour exports in the worldgen bundle.
if !root.join("block-behaviours.json").exists()
|| !root.join("worldgen/blocks/block-properties.nbt").exists()
{
eprintln!("skipping growth tests: no resources at {}", root.display());
return None;
}
let registry: &'static BlockRegistry =
Box::leak(Box::new(data::load_registry(&root).expect("registry")));
let behaviours = Behaviours::load(registry, &root).expect("behaviours");
let data =
GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data");
let features = LiveFeatures::new(&data)
.expect("features")
.expect("feature bundle");
behaviours.set_live_features(Arc::new(features));
Some(Fixture {
registry,
behaviours,
})
})
.as_ref()
}
struct Level {
blocks: HashMap<BlockPos, BlockStateId>,
air: BlockStateId,
random: LegacyRandom,
events: Vec<LevelEvent>,
biome: &'static str,
}
impl LevelAccess for Level {
fn block_state(&self, pos: BlockPos) -> BlockStateId {
self.blocks.get(&pos).copied().unwrap_or(self.air)
}
fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option<BlockStateId> {
Some(self.blocks.insert(pos, state).unwrap_or(self.air))
}
fn is_loaded(&self, _pos: BlockPos) -> bool {
true
}
fn random(&mut self) -> &mut LegacyRandom {
&mut self.random
}
fn game_time(&self) -> i64 {
0
}
fn block_light(&self, _pos: BlockPos) -> i32 {
15
}
fn emit(&mut self, event: LevelEvent) {
self.events.push(event);
}
fn biome_name(&self, _pos: BlockPos) -> Option<&str> {
Some(self.biome)
}
}
struct World {
f: &'static Fixture,
level: Level,
ticks: Ticks,
}
impl World {
fn new(f: &'static Fixture, seed: i64) -> Self {
let mut ticks = Ticks::new(0);
for x in -4..4 {
for z in -4..4 {
ticks.add_empty_chunk(ChunkPos::new(x, z)).unwrap();
}
}
Self {
level: Level {
blocks: HashMap::new(),
air: f.behaviours.air(),
random: LegacyRandom::new(seed),
events: Vec::new(),
biome: "minecraft:plains",
},
f,
ticks,
}
}
fn id(&self, name: &str, props: &[(&str, &str)]) -> BlockStateId {
let state = BlockState {
name: format!("minecraft:{name}"),
properties: props
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<BTreeMap<_, _>>(),
};
self.f
.registry
.resolve(&state)
.unwrap_or_else(|_| panic!("unknown state {name} {props:?}"))
}
fn floor(&mut self, name: &str, radius: i32) {
let state = self.id(name, &[]);
let stone = self.id("stone", &[]);
for x in -radius..=radius {
for z in -radius..=radius {
self.level.blocks.insert(BlockPos::new(x, 63, z), state);
self.level.blocks.insert(BlockPos::new(x, 62, z), stone);
}
}
}
fn put(&mut self, pos: BlockPos, state: BlockStateId) {
self.level.blocks.insert(pos, state);
}
fn name(&self, pos: BlockPos) -> String {
let state = self.level.block_state(pos);
self.f.registry.state(state).unwrap().name.clone()
}
fn bone_meal(&mut self, pos: BlockPos) -> bool {
self.f
.behaviours
.use_bone_meal(&mut self.level, &mut self.ticks, pos, Direction::Up)
}
fn count(&self, suffix: &str) -> usize {
self.level
.blocks
.values()
.filter(|&&s| self.f.registry.state(s).unwrap().name.ends_with(suffix))
.count()
}
}
fn grow(sapling: &str, soil: &str, positions: &[(i32, i32)], log: &str) {
let Some(f) = fixture() else { return };
let mut grown = 0;
for seed in 0..6 {
let mut w = World::new(f, seed);
w.floor(soil, 12);
let state = w.id(sapling, &[]);
for &(x, z) in positions {
w.put(BlockPos::new(x, 64, z), state);
}
let origin = BlockPos::new(0, 64, 0);
let mut uses = 0;
while w.name(origin) == format!("minecraft:{sapling}") && uses < 64 {
assert!(w.bone_meal(origin), "{sapling} is a bone meal target");
uses += 1;
}
if w.count(log) > 0 {
grown += 1;
assert_eq!(
w.name(origin),
format!("minecraft:{log}"),
"{sapling} trunk at origin"
);
}
}
assert!(grown >= 5, "{sapling}: grew {grown} of 6 times");
}
#[test]
fn oak_sapling_grows_with_bone_meal() {
grow("oak_sapling", "grass_block", &[(0, 0)], "oak_log");
}
#[test]
fn single_saplings_grow() {
grow("birch_sapling", "dirt", &[(0, 0)], "birch_log");
grow("spruce_sapling", "dirt", &[(0, 0)], "spruce_log");
grow("jungle_sapling", "dirt", &[(0, 0)], "jungle_log");
grow("acacia_sapling", "dirt", &[(0, 0)], "acacia_log");
grow("cherry_sapling", "grass_block", &[(0, 0)], "cherry_log");
grow("poplar_sapling", "grass_block", &[(0, 0)], "poplar_log");
}
#[test]
fn two_by_two_saplings_grow() {
let square = [(0, 0), (1, 0), (0, 1), (1, 1)];
grow("dark_oak_sapling", "grass_block", &square, "dark_oak_log");
grow("pale_oak_sapling", "grass_block", &square, "pale_oak_log");
grow("spruce_sapling", "podzol", &square, "spruce_log");
grow("jungle_sapling", "grass_block", &square, "jungle_log");
}
#[test]
fn lone_dark_oak_sapling_cannot_grow() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 1);
w.floor("grass_block", 4);
let sapling = w.id("dark_oak_sapling", &[]);
w.put(BlockPos::new(0, 64, 0), sapling);
assert!(!w.bone_meal(BlockPos::new(0, 64, 0)));
}
#[test]
fn azalea_and_mangrove_grow() {
let Some(f) = fixture() else { return };
for (block, soil, log) in [
("azalea", "grass_block", "oak_log"),
("mangrove_propagule", "mud", "mangrove_log"),
] {
let mut grew = false;
for seed in 0..6 {
let mut w = World::new(f, seed);
w.floor(soil, 12);
let state = w.id(block, &[]);
w.put(BlockPos::new(0, 64, 0), state);
for _ in 0..64 {
if w.count(log) > 0 {
break;
}
w.bone_meal(BlockPos::new(0, 64, 0));
}
grew |= w.count(log) > 0;
}
assert!(grew, "{block} grows into a tree");
}
}
#[test]
fn random_ticks_advance_sapling_stage_then_grow() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 3);
w.floor("grass_block", 8);
let sapling = w.id("oak_sapling", &[]);
let pos = BlockPos::new(0, 64, 0);
w.put(pos, sapling);
for _ in 0..2000 {
let state = w.level.block_state(pos);
if !f.behaviours.is_randomly_ticking(state) {
break;
}
f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos);
}
assert_eq!(w.name(pos), "minecraft:oak_log");
}
#[test]
fn grass_bone_meal_places_grass_and_flowers() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 7);
w.floor("grass_block", 8);
assert!(w.bone_meal(BlockPos::new(0, 63, 0)));
let plants = w.count("short_grass") + w.count("tall_grass");
let flowers = w.count("dandelion")
+ w.count("poppy")
+ w.count("cornflower")
+ w.count("oxeye_daisy")
+ w.count("azure_bluet")
+ w.count("_tulip");
assert!(plants > 10, "grass placed: {plants}");
assert!(plants + flowers > 15);
assert!(
w.level
.events
.iter()
.any(|e| matches!(e, LevelEvent::LevelEvent { id: 1505, .. }))
);
}
#[test]
fn huge_mushroom_and_fungus_grow() {
let Some(f) = fixture() else { return };
let mut grew = (false, false);
for seed in 0..8 {
let mut w = World::new(f, seed);
w.floor("mycelium", 8);
let mushroom = w.id("red_mushroom", &[]);
w.put(BlockPos::new(0, 64, 0), mushroom);
for _ in 0..16 {
w.bone_meal(BlockPos::new(0, 64, 0));
}
grew.0 |= w.count("red_mushroom_block") > 0 && w.count("mushroom_stem") > 0;
let mut w = World::new(f, seed);
w.floor("crimson_nylium", 8);
let fungus = w.id("crimson_fungus", &[]);
w.put(BlockPos::new(0, 64, 0), fungus);
for _ in 0..16 {
if w.count("crimson_stem") > 0 {
break;
}
w.bone_meal(BlockPos::new(0, 64, 0));
}
grew.1 |= w.count("crimson_stem") > 0 && w.count("nether_wart_block") > 0;
}
assert!(grew.0, "huge red mushroom");
assert!(grew.1, "huge crimson fungus");
}
#[test]
fn crops_age_with_bone_meal() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 11);
let farmland = w.id("farmland", &[]);
let pos = BlockPos::new(0, 64, 0);
w.put(BlockPos::new(0, 63, 0), farmland);
w.put(pos, w.id("wheat", &[]));
let mut uses = 0;
while w.bone_meal(pos) {
uses += 1;
}
assert!((2..=4).contains(&uses), "wheat matured after {uses} uses");
assert_eq!(w.level.block_state(pos), w.id("wheat", &[("age", "7")]));
w.put(pos, w.id("torchflower_crop", &[]));
assert!(w.bone_meal(pos));
assert!(w.bone_meal(pos));
assert_eq!(w.name(pos), "minecraft:torchflower");
assert!(!w.bone_meal(pos), "torchflowers are not bonemealable");
}
#[test]
fn tall_flowers_and_seagrass() {
let Some(f) = fixture() else { return };
let mut w = World::new(f, 5);
w.floor("dirt", 2);
let fern = w.id("fern", &[]);
w.put(BlockPos::new(0, 64, 0), fern);
assert!(w.bone_meal(BlockPos::new(0, 64, 0)));
assert_eq!(w.name(BlockPos::new(0, 64, 0)), "minecraft:large_fern");
assert_eq!(w.name(BlockPos::new(0, 65, 0)), "minecraft:large_fern");
let lilac = w.id("lilac", &[("half", "lower")]);
w.put(BlockPos::new(1, 64, 0), lilac);
assert!(w.bone_meal(BlockPos::new(1, 64, 0)));
assert!(w.level.events.iter().any(|e| matches!(
e,
LevelEvent::BlockEvent {
kind: "pop_block_item",
..
}
)));
}
+15
View File
@@ -100,8 +100,11 @@ pub mod data;
pub mod states;
pub mod ticks;
mod bonemeal;
mod falling;
mod feature_world;
mod fluids;
mod growth;
mod hooks;
mod interact;
pub mod pistons;
@@ -115,6 +118,8 @@ mod survive;
mod tick;
mod update;
#[cfg(test)]
mod growth_tests;
#[cfg(test)]
mod tests;
@@ -337,6 +342,15 @@ pub trait LevelAccess {
true
}
fn emit(&mut self, _event: LevelEvent) {}
/// Biome identifier at `pos` (`minecraft:plains`), for features placed by
/// block behaviour (bone meal flowers). None when unknown.
fn biome_name(&self, _pos: BlockPos) -> Option<&str> {
None
}
/// World seed (`WorldGenLevel.getSeed`) for seed-derived feature noise.
fn world_seed(&self) -> i64 {
0
}
}
/// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`.
@@ -361,6 +375,7 @@ pub struct Behaviours {
/// Uncached (position- or block-entity-dependent) collision shapes.
dynamic: HashMap<BlockStateId, crate::dynamic_support::DynamicSupport>,
occlusion_cache: Mutex<HashMap<(i32, i32, u8), bool>>,
growth: growth::Growth,
}
impl Behaviours {
+11 -14
View File
@@ -708,11 +708,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
return;
}
let age = b.table.int(state, b.props.age);
let max = b.table.int_range(state, b.props.age).map_or(7, |r| r.1);
let max = self.crop_max_age(state);
if age < max {
let speed = self.crop_growth_speed(b.block(state), pos);
if self.rand_int((25.0 / speed) as i32 + 1) == 0 {
self.set_block(pos, b.table.set_int(state, b.props.age, age + 1), 2);
let next = self.crop_state_for_age(state, age + 1);
self.set_block(pos, next, 2);
}
}
}
@@ -789,11 +790,12 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.set_block(upper_pos, upper, 3);
}
}
fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool {
pub(crate) fn growing_plant_can_grow_into(&self, plant: BlockStateId, state: BlockStateId) -> bool {
let b = self.b;
let data = b.data(plant);
if data.is(Class::Kelp) {
b.is_block(state, b.named.water) && b.fluid(state).amount() == 8
// KelpBlock.canGrowInto: any water block state.
b.is_block(state, b.named.water)
} else {
// NetherVines.isValidGrowthState / CaveVines: air only.
b.is_air(state)
@@ -868,12 +870,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
/// `SaplingBlock.advanceTree`.
pub(crate) fn sapling_advance_tree(&mut self, pos: BlockPos, state: BlockStateId) {
let b = self.b;
if b.table.int(state, b.props.stage) == 0 {
self.set_block(pos, b.table.cycle(state, b.props.stage), 260);
} else if let Some(grower) = b.data(state).feature.clone() {
self.emit(LevelEvent::GrowTree { pos, state, grower });
}
self.advance_tree(pos, state);
}
fn mushroom_random_tick(&mut self, state: BlockStateId, mut pos: BlockPos) {
let b = self.b;
@@ -1013,13 +1010,13 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
self.set_block_and_update(grow, state);
}
}
fn bamboo_sapling_grow(&mut self, pos: BlockPos) {
pub(crate) fn bamboo_sapling_grow(&mut self, pos: BlockPos) {
let b = self.b;
let bamboo = b.default_of(b.named.bamboo);
let state = b.table.set_text(bamboo, b.props.leaves, "small");
self.set_block(above(pos), state, 3);
}
fn bamboo_height_below(&self, pos: BlockPos) -> i32 {
pub(crate) fn bamboo_height_below(&self, pos: BlockPos) -> i32 {
let mut height = 0;
while height < 16
&& self.b.is_block(
@@ -1031,7 +1028,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
}
height
}
fn bamboo_height_above(&self, pos: BlockPos) -> i32 {
pub(crate) fn bamboo_height_above(&self, pos: BlockPos) -> i32 {
let mut height = 0;
while height < 16
&& self.b.is_block(
@@ -1044,7 +1041,7 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
height
}
/// `BambooStalkBlock.growBamboo`.
fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) {
pub(crate) fn bamboo_grow(&mut self, state: BlockStateId, pos: BlockPos, height: i32) {
let b = self.b;
let p = b.props;
let below_state = self.below_state(pos);
+1
View File
@@ -43,6 +43,7 @@ mod generator_decoration;
mod generator_structures;
pub mod height_provider;
pub mod iceberg;
pub mod live;
pub mod material_condition;
pub mod material_extensions;
pub mod material_stage;
+316
View File
@@ -0,0 +1,316 @@
//! Configured and placed features for a live level: what vanilla block
//! behaviour reaches through `Feature.place(level, generator, random, pos)`
//! on a `ServerLevel` (sapling and fungus growth, bone meal on grass, nylium,
//! moss, huge mushrooms). Definitions are decoded lazily by name from the same
//! worldgen bundle as decoration and cached.
use super::{
biome::BiomeId,
biome_predicate::BiomePredicateBindings,
block_feature::FeatureBlockBindings,
feature::{FeatureBlocks, FeatureWorld},
feature_catalog::FeatureCatalog,
feature_graph::{FeatureDefinition, PlacedFeatureDefinition},
generator::{GeneratorData, GeneratorError},
placement::PlacementContext,
state_provider::{StateProviderBindings, StateProviderCatalog},
tags::TagDefinitions,
};
use crate::block_placement::BlockPlacementBindings;
use horizon_core::random::RandomSource;
use serde_json::Value;
use std::{
collections::{BTreeSet, HashMap},
sync::{Arc, Mutex},
};
type Cache<T> = Mutex<HashMap<String, Option<Arc<T>>>>;
pub struct LiveFeatures {
data: Arc<GeneratorData>,
catalog: FeatureCatalog,
bindings: FeatureBlockBindings<'static>,
blocks: FeatureBlocks,
configured: Cache<FeatureDefinition>,
placed: Cache<PlacedFeatureDefinition>,
/// `BiomeGenerationSettings.getBoneMealFeatures` per biome, in vanilla order.
bone_meal: Vec<Vec<String>>,
}
fn resource(message: impl Into<String>) -> GeneratorError {
GeneratorError::Resource(message.into())
}
/// `ConfiguredFeature.getFeatures`: nested configured-feature references of a
/// feature JSON, depth first (each reference followed by its own children).
fn nested_features(
json: &Value,
features: &std::collections::BTreeMap<String, String>,
depth: usize,
out: &mut Vec<String>,
) {
if depth > 64 {
return;
}
match json {
Value::Object(map) => {
for (key, value) in map {
if key == "feature"
&& let Some(name) = value.as_str()
{
let name = super::tags::identifier(name).unwrap_or_else(|_| name.to_owned());
out.push(name.clone());
if let Some(child) = features
.get(&name)
.and_then(|text| serde_json::from_str::<Value>(text).ok())
{
nested_features(&child, features, depth + 1, out);
}
} else {
nested_features(value, features, depth + 1, out);
}
}
}
Value::Array(values) => {
for value in values {
nested_features(value, features, depth + 1, out);
}
}
_ => {}
}
}
impl LiveFeatures {
/// None when the bundle carries no feature resources.
pub fn new(data: &Arc<GeneratorData>) -> Result<Option<Self>, GeneratorError> {
let Some(resources) = &data.feature_resources else {
return Ok(None);
};
let registry = data.registry();
let mut feature_tags = TagDefinitions::default();
for (name, json) in &resources.feature_tags {
feature_tags.apply_json(name, "vanilla", json)?;
}
let catalog =
FeatureCatalog::from_resources(&resources.features, &resources.placed, &feature_tags)?;
let biomes = Arc::new(BiomePredicateBindings::new(
&data
.biome_names()
.iter()
.enumerate()
.map(|(i, name)| (name.to_string(), BiomeId(i as u32)))
.collect(),
&data.biome_tags,
)?);
let mut bindings =
FeatureBlockBindings::with_tags(registry, data.integers().clone(), &data.block_tags)?
.with_fluid_tags(&resources.fluid_tags)?
.with_biomes(biomes.clone());
if let Some(structures) = &data.structures {
bindings = bindings.with_structures(structures.clone());
}
if let Some(blocks) = &resources.blocks {
bindings = bindings
.with_block_properties(&blocks.properties)?
.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,
)?,
)?;
}
// Configured-feature tag membership (feature_tags names configured features).
let mut bone_meal_tag = BTreeSet::new();
if let Some(json) = resources
.feature_tags
.get("minecraft:can_spawn_from_bone_meal")
{
let value: Value = serde_json::from_str(json)?;
for entry in value["values"].as_array().into_iter().flatten() {
if let Some(name) = entry.as_str() {
bone_meal_tag.insert(super::tags::identifier(name)?);
}
}
}
let placed_tags = feature_tags
.build(|name, _| resources.placed.contains_key(name).then(|| name.to_owned()))
.map_err(|e| resource(format!("feature tags: {e:?}")))?
.tags;
let mut bone_meal = Vec::with_capacity(data.biome_names().len());
for i in 0..data.biome_names().len() {
let biome: Value = serde_json::from_str(data.biome_json(BiomeId(i as u32)))?;
let mut list = Vec::new();
for step in biome["features"].as_array().into_iter().flatten() {
let entries: Vec<String> = match step {
Value::String(tag) if tag.starts_with('#') => placed_tags
.get(&super::tags::identifier(&tag[1..])?)
.cloned()
.unwrap_or_default(),
Value::String(name) => vec![name.clone()],
Value::Array(values) => values
.iter()
.filter_map(|v| v.as_str().map(str::to_owned))
.collect(),
_ => Vec::new(),
};
for entry in entries {
let name = super::tags::identifier(&entry)?;
let Some(placed) = resources
.placed
.get(&name)
.and_then(|text| serde_json::from_str::<Value>(text).ok())
else {
continue;
};
// PlacedFeature.getFeatures: its feature, then that feature's children.
let mut found = Vec::new();
match &placed["feature"] {
Value::String(feature) => {
let feature = super::tags::identifier(feature)?;
found.push(feature.clone());
if let Some(child) = resources
.features
.get(&feature)
.and_then(|text| serde_json::from_str::<Value>(text).ok())
{
nested_features(&child, &resources.features, 0, &mut found);
}
}
inline => nested_features(inline, &resources.features, 0, &mut found),
}
list.extend(found.into_iter().filter(|f| bone_meal_tag.contains(f)));
}
}
bone_meal.push(list);
}
Ok(Some(Self {
data: data.clone(),
catalog,
bindings,
blocks: FeatureBlocks::from_registry(registry)?,
configured: Mutex::new(HashMap::new()),
placed: Mutex::new(HashMap::new()),
bone_meal,
}))
}
pub fn data(&self) -> &Arc<GeneratorData> {
&self.data
}
pub fn biome_id(&self, name: &str) -> Option<BiomeId> {
self.data.biome_id(name)
}
/// Raw JSON of a configured feature (for configuration values such as a
/// trunk placer's base height).
pub fn configured_json(&self, name: &str) -> Option<Value> {
let resources = self.data.feature_resources.as_ref()?;
serde_json::from_str(resources.features.get(name)?).ok()
}
pub fn configured(&self, name: &str) -> Option<Arc<FeatureDefinition>> {
let mut cache = self.configured.lock().unwrap();
cache
.entry(name.to_owned())
.or_insert_with(|| {
match self
.catalog
.feature_with_blocks(&Value::from(name).to_string(), &self.bindings)
{
Ok(f) => Some(Arc::new(f)),
Err(e) => {
eprintln!("Horizon: feature {name} cannot be placed: {e}");
None
}
}
})
.clone()
}
pub fn placed(&self, name: &str) -> Option<Arc<PlacedFeatureDefinition>> {
let mut cache = self.placed.lock().unwrap();
cache
.entry(name.to_owned())
.or_insert_with(|| {
match self
.catalog
.placed_feature_with_blocks(&Value::from(name).to_string(), &self.bindings)
{
Ok(f) => Some(Arc::new(f)),
Err(e) => {
eprintln!("Horizon: placed feature {name} cannot be placed: {e}");
None
}
}
})
.clone()
}
/// `ConfiguredFeature.place`. Unknown or unsupported features and
/// execution errors report failure.
pub fn place_configured<W: FeatureWorld + PlacementContext>(
&self,
name: &str,
world: &mut W,
random: &mut impl RandomSource,
origin: [i32; 3],
) -> bool
where
W::Error: std::fmt::Display,
{
let Some(feature) = self.configured(name) else {
return false;
};
match feature.place(world, random, origin, self.blocks) {
Ok(placed) => placed,
Err(e) => {
eprintln!("Horizon: placing {name} failed: {e}");
false
}
}
}
/// `PlacedFeature.place` (placement modifiers, then the feature).
pub fn place_placed<W: FeatureWorld + PlacementContext>(
&self,
name: &str,
world: &mut W,
random: &mut impl RandomSource,
origin: [i32; 3],
) -> bool
where
W::Error: std::fmt::Display,
{
let Some(feature) = self.placed(name) else {
return false;
};
match feature.place(world, random, origin, self.blocks) {
Ok(placed) => placed,
Err(e) => {
eprintln!("Horizon: placing {name} failed: {e}");
false
}
}
}
/// Whether the named biome is in a biome tag (`minecraft:...`).
pub fn biome_in_tag(&self, biome: &str, tag: &str) -> bool {
self.data
.biome_tags
.get(tag)
.is_some_and(|members| members.iter().any(|m| m == biome))
}
/// A block tag's members in registry tag order (for `getRandomElementOf`).
pub fn block_tag_entries(&self, tag: &str) -> &[String] {
self.data.block_tags.get(tag).map_or(&[], Vec::as_slice)
}
/// `BiomeGenerationSettings.getBoneMealFeatures` of a biome.
pub fn bone_meal_features(&self, biome: BiomeId) -> &[String] {
self.bone_meal
.get(biome.0 as usize)
.map_or(&[], Vec::as_slice)
}
}