Merge remote-tracking branch 'origin/wip/parity-blocks' into t3/minecraft-parity
# Conflicts: # crates/horizon-client/src/containers.rs # crates/horizon-client/src/game.rs # crates/horizon-client/src/game/control.rs # crates/horizon-client/src/save.rs
This commit is contained in:
@@ -77,6 +77,36 @@ impl BlockEntity {
|
||||
match self {
|
||||
Self::Chest(_) => "minecraft:chest",
|
||||
Self::Brewing(_) => "minecraft:brewing_stand",
|
||||
let size = match name {
|
||||
"minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27,
|
||||
"minecraft:hopper" => 5,
|
||||
"minecraft:dispenser" | "minecraft:dropper" => 9,
|
||||
_ => return None,
|
||||
};
|
||||
Some(Self::Chest(vec![None; size]))
|
||||
}
|
||||
/// The vanilla block entity type id of a container block.
|
||||
pub fn id_for_block(name: &str) -> Option<&'static str> {
|
||||
Some(match name {
|
||||
"minecraft:chest" => "minecraft:chest",
|
||||
"minecraft:trapped_chest" => "minecraft:trapped_chest",
|
||||
"minecraft:barrel" => "minecraft:barrel",
|
||||
"minecraft:hopper" => "minecraft:hopper",
|
||||
"minecraft:dispenser" => "minecraft:dispenser",
|
||||
"minecraft:dropper" => "minecraft:dropper",
|
||||
"minecraft:furnace" => "minecraft:furnace",
|
||||
"minecraft:blast_furnace" => "minecraft:blast_furnace",
|
||||
"minecraft:smoker" => "minecraft:smoker",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
pub fn id(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Chest(items) => match items.len() {
|
||||
5 => "minecraft:hopper",
|
||||
9 => "minecraft:dispenser",
|
||||
_ => "minecraft:chest",
|
||||
},
|
||||
Self::Furnace(f) => match f.kind {
|
||||
FurnaceKind::Furnace => "minecraft:furnace",
|
||||
FurnaceKind::BlastFurnace => "minecraft:blast_furnace",
|
||||
@@ -91,6 +121,12 @@ impl BlockEntity {
|
||||
Self::Brewing(b) => b.items.iter().flatten().cloned().collect(),
|
||||
}
|
||||
}
|
||||
pub fn slots(&self) -> &[Option<ItemStack>] {
|
||||
match self {
|
||||
Self::Chest(items) => items,
|
||||
Self::Furnace(f) => &f.items,
|
||||
}
|
||||
}
|
||||
pub fn slots_mut(&mut self) -> &mut [Option<ItemStack>] {
|
||||
match self {
|
||||
Self::Chest(items) => items,
|
||||
|
||||
@@ -21,6 +21,7 @@ struct Out {
|
||||
@location(1) color: vec4<f32>,
|
||||
@location(2) spherical: f32,
|
||||
@location(3) cylindrical: f32,
|
||||
@location(4) flash: f32,
|
||||
}
|
||||
@vertex fn vs_entity(@location(0) position: vec3<f32>, @location(1) uv: vec2<f32>,
|
||||
@location(2) overlay: u32, @location(3) color: vec4<f32>, @location(4) light: vec4<u32>) -> Out {
|
||||
@@ -35,6 +36,8 @@ struct Out {
|
||||
// Hurt overlay (OverlayTexture red tint).
|
||||
if overlay == 1u { c = vec4(mix(c.rgb, vec3(1.0, 0.0, 0.0), 0.3), c.a); }
|
||||
out.color = c;
|
||||
// Overlay 4: OverlayTexture white flash (primed TNT), applied after texturing.
|
||||
out.flash = select(0.0, 0.75, overlay == 4u);
|
||||
// Sky geometry (clouds, celestial bodies) is exempt from render-distance fog.
|
||||
out.spherical = select(length(position), 0.0, overlay >= 2u);
|
||||
out.cylindrical = select(max(length(position.xz), abs(position.y)), 0.0, overlay >= 2u);
|
||||
@@ -46,8 +49,9 @@ fn linear_fog(d: f32, start: f32, end: f32) -> f32 {
|
||||
return (d - start) / (end - start);
|
||||
}
|
||||
@fragment fn fs_entity(in: Out) -> @location(0) vec4<f32> {
|
||||
let color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
|
||||
var color = textureSample(atlas, atlas_sampler, in.uv) * in.color;
|
||||
if color.a < 0.1 { discard; }
|
||||
color = vec4(mix(color.rgb, vec3(1.0), in.flash), color.a);
|
||||
let f = max(linear_fog(in.spherical, globals.fog.x, globals.fog.y),
|
||||
linear_fog(in.cylindrical, globals.fog.z, globals.fog.w));
|
||||
return vec4(mix(color.rgb, globals.fog_color.rgb, f * globals.fog_color.a), color.a);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The playable game loop: streaming world, player simulation at 20 ticks/s,
|
||||
//! block interaction, inventory and HUD.
|
||||
mod blockctl;
|
||||
mod control;
|
||||
mod end;
|
||||
mod postprocess;
|
||||
@@ -9,6 +10,10 @@ mod potions;
|
||||
mod station_control;
|
||||
mod stations;
|
||||
mod trading;
|
||||
mod explosion;
|
||||
mod growth;
|
||||
mod machines;
|
||||
mod tnt;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
assets::Assets,
|
||||
@@ -204,8 +209,32 @@ struct GameLevel<'w> {
|
||||
raining: bool,
|
||||
thundering: bool,
|
||||
player_box: Option<([f64; 3], [f64; 3])>,
|
||||
biomes: &'w Biomes,
|
||||
seed: i64,
|
||||
behaviours: &'w Behaviours,
|
||||
items: &'w Items,
|
||||
registry: &'static horizon_world::registry::BlockRegistry,
|
||||
}
|
||||
impl LevelAccess for GameLevel<'_> {
|
||||
fn precipitation(&self, pos: BlockPos) -> Option<horizon_world::level::Precipitation> {
|
||||
self.behaviours.precipitation_info(self, pos)
|
||||
}
|
||||
fn is_raining_at(&self, pos: BlockPos) -> bool {
|
||||
self.behaviours.is_raining_at(self, pos)
|
||||
}
|
||||
fn block_entity_analog_signal(&self, pos: BlockPos, _state: BlockStateId, _direction: Direction) -> i32 {
|
||||
machines::container_signal(self.world, self.behaviours, self.items, self.registry, pos)
|
||||
}
|
||||
fn biome_name(&self, pos: BlockPos) -> Option<&str> {
|
||||
let chunk = self.world.chunks.get(&(pos.x >> 4, pos.z >> 4))?;
|
||||
Some(&self.biomes.get(chunk.biome(pos.x, pos.y, pos.z)).name)
|
||||
}
|
||||
fn world_seed(&self) -> i64 {
|
||||
self.seed
|
||||
}
|
||||
fn day_time(&self) -> i64 {
|
||||
self.world.day_time
|
||||
}
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId {
|
||||
self.world.block(pos.x, pos.y, pos.z)
|
||||
}
|
||||
@@ -225,6 +254,8 @@ impl LevelAccess for GameLevel<'_> {
|
||||
}
|
||||
fn max_y(&self) -> i32 {
|
||||
if self.dimension != LevelDimension::Overworld { 255 } else { MIN_Y + HEIGHT - 1 }
|
||||
// Exclusive, as LevelAccess::max_y documents.
|
||||
if self.dimension == LevelDimension::Nether { 256 } else { MIN_Y + HEIGHT }
|
||||
}
|
||||
fn random(&mut self) -> &mut horizon_core::random::LegacyRandom {
|
||||
&mut self.world.random
|
||||
@@ -401,6 +432,8 @@ struct Game<'a> {
|
||||
tick_chunks: HashSet<(i32, i32)>,
|
||||
level_events: Vec<LevelEvent>,
|
||||
falling: Vec<FallingBlock>,
|
||||
tnts: Vec<tnt::PrimedTnt>,
|
||||
hoppers: HashMap<(i32, i32, i32), machines::HopperState>,
|
||||
creative_screen: Creative,
|
||||
control: Option<horizon_client::control::Server>,
|
||||
frame_stats: horizon_client::control::FrameStats,
|
||||
@@ -717,6 +750,11 @@ impl Game<'_> {
|
||||
raining: rain > 0.2,
|
||||
thundering: thunder > 0.9,
|
||||
player_box,
|
||||
biomes: &self.res.biomes,
|
||||
seed: self.level.seed,
|
||||
behaviours: &self.res.behaviours,
|
||||
items: &self.res.items,
|
||||
registry: self.res.assets.registry,
|
||||
};
|
||||
f(&self.res.behaviours, &mut level, &mut self.block_ticks)
|
||||
}
|
||||
@@ -791,6 +829,7 @@ impl Game<'_> {
|
||||
1502 => Some(("minecraft:block.redstone_torch.burnout", 0.5)),
|
||||
1030 => Some(("minecraft:block.anvil.use", 1.0)),
|
||||
1031 => Some(("minecraft:block.anvil.land", 0.3)),
|
||||
1505 => Some(("minecraft:item.bone_meal.use", 1.0)),
|
||||
_ => None,
|
||||
};
|
||||
if let Some((name, volume)) = sound {
|
||||
@@ -837,9 +876,11 @@ impl Game<'_> {
|
||||
}
|
||||
PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {}
|
||||
},
|
||||
LevelEvent::PrimeTnt { pos } => {
|
||||
// Simplified: TNT explodes after its 80-tick fuse immediately.
|
||||
self.explode([f64::from(pos.x) + 0.5, f64::from(pos.y), f64::from(pos.z) + 0.5], 4.0)?;
|
||||
LevelEvent::PrimeTnt { pos } => self.spawn_primed_tnt(pos, false),
|
||||
LevelEvent::BlockEvent { pos, state, kind: "dispense" } => self.dispense_from(pos, state)?,
|
||||
LevelEvent::BlockEvent { pos, state, kind: "pop_block_item" } => {
|
||||
let item = self.res.facts.get(state).item.clone();
|
||||
self.pop_resource([pos.x, pos.y, pos.z], ItemStack { item, count: 1, damage: 0 });
|
||||
}
|
||||
LevelEvent::GrowTree { .. } | LevelEvent::PlaceFeature { .. } | LevelEvent::BlockEvent { .. } | LevelEvent::GameEvent { .. } => {}
|
||||
}
|
||||
@@ -1018,6 +1059,9 @@ impl Game<'_> {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
if self.use_tool(&stack)? {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1391,6 +1435,13 @@ impl Game<'_> {
|
||||
};
|
||||
self.audio.play(name, Some(feet), volume, pitch);
|
||||
}
|
||||
MotionEvent::Fall(horizon_client::landing::FallEvent::Write { position, flags, .. }) => {
|
||||
// Landing rules (farmland trampling, turtle eggs) wrote the block raw.
|
||||
self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, flags as i32));
|
||||
}
|
||||
MotionEvent::Fall(horizon_client::landing::FallEvent::Destroy { position, .. }) => {
|
||||
self.with_level(|b, level, ticks| b.notify_written(level, ticks, position, level_flags::UPDATE_ALL));
|
||||
}
|
||||
MotionEvent::Fall(horizon_client::landing::FallEvent::Damage { .. }) => {
|
||||
self.audio.play("minecraft:entity.player.hurt", Some(feet), 1.0, 1.0);
|
||||
}
|
||||
@@ -1434,6 +1485,7 @@ impl Game<'_> {
|
||||
self.postprocess_chunks()?;
|
||||
self.tick_blocks()?;
|
||||
self.tick_falling()?;
|
||||
self.tick_tnt()?;
|
||||
if let Some(p) = &self.player {
|
||||
// Player.aiStep bob and Entity.walkDist (0.6 per block).
|
||||
let (dx, dz) = (p.position.x - self.previous_position.x, p.position.z - self.previous_position.z);
|
||||
@@ -1775,7 +1827,7 @@ impl Game<'_> {
|
||||
batch
|
||||
}
|
||||
fn inventory_origin(&self, batch: &HudBatch) -> (f32, f32) {
|
||||
((batch.width - 176.0) / 2.0, (batch.height - 166.0) / 2.0)
|
||||
((batch.width - 176.0) / 2.0, (batch.height - self.screen_height()) / 2.0)
|
||||
}
|
||||
/// Slot ids: 0..36 player inventory, 100..109 crafting grid, 200 result.
|
||||
fn container_kind(&self) -> Option<&BlockEntity> {
|
||||
@@ -1804,6 +1856,7 @@ impl Game<'_> {
|
||||
/// InventoryMenu / CraftingMenu slot layouts.
|
||||
fn slot_position(&self, i: usize) -> (f32, f32) {
|
||||
if let Some(p) = self.station_slot_position(i) {
|
||||
if let Some(p) = self.machine_slot_position(i) {
|
||||
return p;
|
||||
}
|
||||
let table = self.craft_size == 3;
|
||||
@@ -1881,6 +1934,7 @@ impl Game<'_> {
|
||||
};
|
||||
let grey = rgba(64, 64, 64, 255);
|
||||
match self.container.and_then(|k| self.world.block_entities.get(&k)) {
|
||||
Some(BlockEntity::Chest(_)) if self.draw_machine_screen(batch, ox, oy) => {}
|
||||
Some(BlockEntity::Chest(_)) => {
|
||||
// ContainerScreen with 3 rows: top 71px, then the player inventory from v=126.
|
||||
part(batch, "gui/container/generic_54", 0.0, 0.0, 176.0, 71.0, ox, oy);
|
||||
@@ -2287,6 +2341,7 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
self.tnt_geometry(camera, alpha, &mut out);
|
||||
// Camera-facing particle quads.
|
||||
let (yaw, pitch) = (self.yaw.to_radians(), self.pitch.to_radians());
|
||||
let forward = glam::Vec3::new(-yaw.sin() * pitch.cos(), -pitch.sin(), yaw.cos() * pitch.cos());
|
||||
@@ -2552,84 +2607,13 @@ impl Game<'_> {
|
||||
true
|
||||
}
|
||||
/// ServerExplosion: rays from a 16^3 grid lose (resistance + 0.3) * 0.3 per step.
|
||||
/// A mob explosion (`Level.ExplosionInteraction.MOB`: drop decay with the
|
||||
/// default mobGriefing rule).
|
||||
fn explode(&mut self, center: [f64; 3], radius: f32) -> Result<()> {
|
||||
let mut destroyed = HashSet::new();
|
||||
for j in 0..16 {
|
||||
for k in 0..16 {
|
||||
for l in 0..16 {
|
||||
if !(j == 0 || j == 15 || k == 0 || k == 15 || l == 0 || l == 15) {
|
||||
continue;
|
||||
}
|
||||
let mut d = [f64::from(j) / 15.0 * 2.0 - 1.0, f64::from(k) / 15.0 * 2.0 - 1.0, f64::from(l) / 15.0 * 2.0 - 1.0];
|
||||
let len = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
d = d.map(|v| v / len);
|
||||
let mut h = radius * (0.7 + self.world.random.next_float() * 0.6);
|
||||
let mut p = center;
|
||||
while h > 0.0 {
|
||||
let b = [p[0].floor() as i32, p[1].floor() as i32, p[2].floor() as i32];
|
||||
let state = self.world.block(b[0], b[1], b[2]);
|
||||
if !self.res.facts.is_air(state) {
|
||||
let f = self.res.facts.get(state);
|
||||
let resistance = if f.fluid != Fluid::None && !f.waterlogged { 100.0 } else { f.explosion_resistance };
|
||||
h -= (resistance + 0.3) * 0.3;
|
||||
if h > 0.0 && f.hardness >= 0.0 {
|
||||
destroyed.insert(b);
|
||||
}
|
||||
}
|
||||
p = [p[0] + d[0] * 0.3, p[1] + d[1] * 0.3, p[2] + d[2] * 0.3];
|
||||
h -= 0.225_000_01;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for b in destroyed {
|
||||
let state = self.world.block(b[0], b[1], b[2]);
|
||||
if self.res.facts.is_air(state) {
|
||||
continue;
|
||||
}
|
||||
// Explosion decay: each drop survives with probability 1 / radius.
|
||||
if self.world.random.next_float() < 1.0 / radius {
|
||||
let drops = self.res.items.block_drops(&self.res.assets.registry, state, None, &mut self.world.random);
|
||||
for d in drops {
|
||||
self.pop_resource(b, d);
|
||||
}
|
||||
}
|
||||
self.world.set(b[0], b[1], b[2], self.world.air)?;
|
||||
}
|
||||
self.audio.play("minecraft:entity.generic.explode", Some(center), 4.0, (1.0 + (self.world.random.next_float() - self.world.random.next_float()) * 0.2) * 0.7);
|
||||
// Entity damage by distance (exposure approximated as unobstructed).
|
||||
let diameter = f64::from(radius) * 2.0;
|
||||
let mut armor_damage = None;
|
||||
if let Some(player) = self.player.as_mut() {
|
||||
let p = [player.position.x, player.position.y, player.position.z];
|
||||
let dist = ((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2)).sqrt() / diameter;
|
||||
if dist <= 1.0 {
|
||||
let impact = 1.0 - dist;
|
||||
let damage = ((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32;
|
||||
if let Some(id) = self.motion.health.damage.id("minecraft:explosion") {
|
||||
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, damage);
|
||||
armor_damage = Some(damage);
|
||||
}
|
||||
let (dx, dy, dz) = (p[0] - center[0], p[1] - center[1], p[2] - center[2]);
|
||||
let l = (dx * dx + dy * dy + dz * dz).sqrt().max(1e-4);
|
||||
player.velocity = Vec3::new(player.velocity.x + dx / l * impact, player.velocity.y + dy / l * impact, player.velocity.z + dz / l * impact);
|
||||
}
|
||||
}
|
||||
if let Some(d) = armor_damage
|
||||
&& !self.creative
|
||||
{
|
||||
self.hurt_armor(d);
|
||||
}
|
||||
for m in &mut self.mobs {
|
||||
let dist = ((m.position.x - center[0]).powi(2) + (m.position.y - center[1]).powi(2) + (m.position.z - center[2]).powi(2)).sqrt() / diameter;
|
||||
if dist <= 1.0 && m.alive() {
|
||||
let impact = 1.0 - dist;
|
||||
m.hurt(((impact * impact + impact) / 2.0 * 7.0 * diameter + 1.0) as f32, Some(center), &mut self.world.random);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
self.server_explode(center, radius, explosion::BlockInteraction::DestroyWithDecay, false)
|
||||
}
|
||||
fn tick_block_entities(&mut self) -> Result<()> {
|
||||
self.tick_hoppers()?;
|
||||
// ChestLidController: 0.1 per tick towards open/closed.
|
||||
if let Some(key) = self.container {
|
||||
self.chest_open.entry(key).or_insert((0.0, 0.0));
|
||||
@@ -3008,8 +2992,10 @@ impl Game<'_> {
|
||||
self.dim = dim;
|
||||
self.world_root = save_root.clone();
|
||||
self.block_ticks = Ticks::new(self.level.seed as i32);
|
||||
self.install_live_features();
|
||||
self.tick_chunks.clear();
|
||||
self.falling.clear();
|
||||
self.tnts.clear();
|
||||
self.travelling = None;
|
||||
self.player = None;
|
||||
self.spawn = None;
|
||||
@@ -3089,6 +3075,7 @@ impl Game<'_> {
|
||||
self.block_ticks = Ticks::new(self.level.seed as i32);
|
||||
self.tick_chunks.clear();
|
||||
self.falling.clear();
|
||||
self.tnts.clear();
|
||||
self.mobs.clear();
|
||||
self.arrows.clear();
|
||||
self.dropped.clear();
|
||||
@@ -4592,6 +4579,9 @@ impl ApplicationHandler for Game<'_> {
|
||||
}
|
||||
Screen::Inventory if pressed => {
|
||||
self.click_inventory(button == MouseButton::Right);
|
||||
if let Some(key) = self.container {
|
||||
self.container_changed(key);
|
||||
}
|
||||
}
|
||||
Screen::Creative if pressed => {
|
||||
self.click_creative(button == MouseButton::Right);
|
||||
@@ -4938,6 +4928,8 @@ pub fn run() -> Result<()> {
|
||||
tick_chunks: HashSet::new(),
|
||||
level_events: Vec::new(),
|
||||
falling: Vec::new(),
|
||||
tnts: Vec::new(),
|
||||
hoppers: HashMap::new(),
|
||||
creative_screen: Creative::load(&game_root)?,
|
||||
control: None,
|
||||
frame_stats: Default::default(),
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
//! Control-socket block commands for scripted tests: `setblock`, `fill`,
|
||||
//! `getblock` and `container` (list or put items in a block entity).
|
||||
use super::Game;
|
||||
use horizon_client::{Result, containers::BlockEntity, items::ItemStack};
|
||||
use horizon_world::{chunk::BlockState, registry::BlockStateId};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) const HELP: &[&str] = &[
|
||||
"setblock X Y Z BLOCK[props] set a block with neighbour updates",
|
||||
"fill X1 Y1 Z1 X2 Y2 Z2 BLOCK set a box of blocks",
|
||||
"getblock X Y Z block state at a position",
|
||||
"container X Y Z [ITEM COUNT] list a container, or add items to it",
|
||||
];
|
||||
|
||||
fn parse_state(text: &str) -> Result<BlockState> {
|
||||
let (name, props) = match text.split_once('[') {
|
||||
Some((name, rest)) => (name, rest.trim_end_matches(']')),
|
||||
None => (text, ""),
|
||||
};
|
||||
let name = if name.contains(':') {
|
||||
name.to_owned()
|
||||
} else {
|
||||
format!("minecraft:{name}")
|
||||
};
|
||||
let mut properties = BTreeMap::new();
|
||||
for pair in props.split(',').filter(|p| !p.is_empty()) {
|
||||
let (k, v) = pair.split_once('=').ok_or("properties are key=value")?;
|
||||
properties.insert(k.to_owned(), v.to_owned());
|
||||
}
|
||||
Ok(BlockState { name, properties })
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
fn state_text(&self, state: BlockStateId) -> String {
|
||||
let Some(s) = self.res.assets.registry.state(state) else {
|
||||
return "?".into();
|
||||
};
|
||||
if s.properties.is_empty() {
|
||||
return s.name.clone();
|
||||
}
|
||||
let props: Vec<String> = s
|
||||
.properties
|
||||
.iter()
|
||||
.map(|(k, v)| format!("{k}={v}"))
|
||||
.collect();
|
||||
format!("{}[{}]", s.name, props.join(","))
|
||||
}
|
||||
fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> {
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
|
||||
self.level_set(pos, state)?;
|
||||
if let Some(entity) = BlockEntity::for_block(&name) {
|
||||
self.world
|
||||
.block_entities
|
||||
.insert((pos[0], pos[1], pos[2]), entity);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Block commands; None when `words[0]` is not one of them.
|
||||
pub(super) fn block_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
|
||||
let int = |i: usize| -> Result<i32> {
|
||||
Ok(words
|
||||
.get(i)
|
||||
.ok_or_else(|| format!("missing argument {i}"))?
|
||||
.parse()?)
|
||||
};
|
||||
match words[0] {
|
||||
"setblock" => {
|
||||
let pos = [int(1)?, int(2)?, int(3)?];
|
||||
let state = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.resolve(&parse_state(words.get(4).ok_or("missing block")?)?)?;
|
||||
self.put_block(pos, state)?;
|
||||
Ok(Some(
|
||||
json!({ "ok": true, "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }),
|
||||
))
|
||||
}
|
||||
"fill" => {
|
||||
let (a, b) = ([int(1)?, int(2)?, int(3)?], [int(4)?, int(5)?, int(6)?]);
|
||||
let state = self
|
||||
.res
|
||||
.assets
|
||||
.registry
|
||||
.resolve(&parse_state(words.get(7).ok_or("missing block")?)?)?;
|
||||
let mut count = 0;
|
||||
for x in a[0].min(b[0])..=a[0].max(b[0]) {
|
||||
for y in a[1].min(b[1])..=a[1].max(b[1]) {
|
||||
for z in a[2].min(b[2])..=a[2].max(b[2]) {
|
||||
self.put_block([x, y, z], state)?;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(json!({ "ok": true, "count": count })))
|
||||
}
|
||||
"getblock" => {
|
||||
let pos = [int(1)?, int(2)?, int(3)?];
|
||||
Ok(Some(
|
||||
json!({ "block": self.state_text(self.world.block(pos[0], pos[1], pos[2])) }),
|
||||
))
|
||||
}
|
||||
"container" => {
|
||||
let key = (int(1)?, int(2)?, int(3)?);
|
||||
if let Some(item) = words.get(4) {
|
||||
let item = if item.contains(':') {
|
||||
(*item).to_owned()
|
||||
} else {
|
||||
format!("minecraft:{item}")
|
||||
};
|
||||
let count: u32 = words.get(5).map_or(Ok(1), |c| c.parse())?;
|
||||
let entity = self
|
||||
.world
|
||||
.block_entities
|
||||
.get_mut(&key)
|
||||
.ok_or("no container there")?;
|
||||
let slot = entity
|
||||
.slots_mut()
|
||||
.iter_mut()
|
||||
.find(|s| s.is_none())
|
||||
.ok_or("container is full")?;
|
||||
*slot = Some(ItemStack {
|
||||
item: item.as_str().into(),
|
||||
count,
|
||||
damage: 0,
|
||||
});
|
||||
}
|
||||
let entity = self
|
||||
.world
|
||||
.block_entities
|
||||
.get(&key)
|
||||
.ok_or("no container there")?;
|
||||
let slots: Vec<Value> = entity
|
||||
.clone()
|
||||
.slots_mut()
|
||||
.iter()
|
||||
.map(|s| {
|
||||
s.as_ref().map_or(
|
||||
Value::Null,
|
||||
|s| json!({ "item": &*s.item, "count": s.count }),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok(Some(json!({ "slots": slots })))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -64,8 +64,12 @@ impl Game<'_> {
|
||||
.ok_or_else(|| format!("missing argument {i} for {}", words[0]))
|
||||
};
|
||||
let ok = || Ok(Some(json!({ "ok": true })));
|
||||
if let Some(value) = self.block_command(&words)? {
|
||||
return Ok(Some(value));
|
||||
}
|
||||
match words[0] {
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::station_control::HELP).collect::<Vec<_>>() }))),
|
||||
"help" => Ok(Some(json!({ "commands": HELP.iter().chain(super::blockctl::HELP).collect::<Vec<_>>() }))),
|
||||
"status" => Ok(Some(self.control_status())),
|
||||
"key" => {
|
||||
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
|
||||
|
||||
@@ -0,0 +1,460 @@
|
||||
//! `ServerExplosion`: exploded positions (vanilla ray march over a Java
|
||||
//! HashSet, so iteration and the following shuffle match vanilla's random
|
||||
//! draws), entity damage with exposure and knockback, block interaction with
|
||||
//! merged drops and TNT chain priming, and optional fire.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, blocks::Fluid, items::ItemStack};
|
||||
use horizon_core::{
|
||||
geometry::Vec3,
|
||||
position::BlockPos,
|
||||
random::{LegacyRandom, RandomSource},
|
||||
};
|
||||
use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
struct Key([i32; 3]);
|
||||
impl JavaKey for Key {
|
||||
fn java_hash(&self) -> i32 {
|
||||
let [x, y, z] = self.0;
|
||||
y.wrapping_add(z.wrapping_mul(31))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(x)
|
||||
}
|
||||
fn comparable_compare(&self, other: &Self) -> Option<Ordering> {
|
||||
let ([x, y, z], [ox, oy, oz]) = (self.0, other.0);
|
||||
Some(y.cmp(&oy).then(z.cmp(&oz)).then(x.cmp(&ox)))
|
||||
}
|
||||
fn tie_break(&self, _other: &Self) -> Ordering {
|
||||
Ordering::Less
|
||||
}
|
||||
}
|
||||
|
||||
/// `Explosion.BlockInteraction` for the explosions Horizon produces.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(super) enum BlockInteraction {
|
||||
Keep,
|
||||
Destroy,
|
||||
DestroyWithDecay,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// Client-side randomness (explosion sound pitch), separate from the level random.
|
||||
static CLIENT_RANDOM: std::cell::RefCell<LegacyRandom> = std::cell::RefCell::new(LegacyRandom::new(0x5eed));
|
||||
}
|
||||
pub(super) fn client_float() -> f32 {
|
||||
CLIENT_RANDOM.with(|r| r.borrow_mut().next_float())
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
|
||||
/// collision cubes as obstacles.
|
||||
fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
|
||||
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
|
||||
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
let steps = (length / 0.1).ceil().max(1.0) as i32;
|
||||
let mut last = [i32::MIN; 3];
|
||||
for i in 0..=steps {
|
||||
let t = f64::from(i) / f64::from(steps);
|
||||
let b = [
|
||||
(from[0] + d[0] * t).floor() as i32,
|
||||
(from[1] + d[1] * t).floor() as i32,
|
||||
(from[2] + d[2] * t).floor() as i32,
|
||||
];
|
||||
if b == last {
|
||||
continue;
|
||||
}
|
||||
last = b;
|
||||
if self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(b[0], b[1], b[2]))
|
||||
.full_collision
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
/// `ServerExplosion.getSeenPercent` for an entity box.
|
||||
fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
|
||||
let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
|
||||
let ys = 1.0 / ((max[1] - min[1]) * 2.0 + 1.0);
|
||||
let zs = 1.0 / ((max[2] - min[2]) * 2.0 + 1.0);
|
||||
let x_offset = (1.0 - (1.0 / xs).floor() * xs) / 2.0;
|
||||
let z_offset = (1.0 - (1.0 / zs).floor() * zs) / 2.0;
|
||||
if xs < 0.0 || ys < 0.0 || zs < 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let (mut hits, mut count) = (0, 0);
|
||||
let mut xx = 0.0;
|
||||
while xx <= 1.0 {
|
||||
let mut yy = 0.0;
|
||||
while yy <= 1.0 {
|
||||
let mut zz = 0.0;
|
||||
while zz <= 1.0 {
|
||||
let x = min[0] + (max[0] - min[0]) * xx;
|
||||
let y = min[1] + (max[1] - min[1]) * yy;
|
||||
let z = min[2] + (max[2] - min[2]) * zz;
|
||||
if self.clear_line([x + x_offset, y, z + z_offset], center) {
|
||||
hits += 1;
|
||||
}
|
||||
count += 1;
|
||||
zz += zs;
|
||||
}
|
||||
yy += ys;
|
||||
}
|
||||
xx += xs;
|
||||
}
|
||||
hits as f32 / count as f32
|
||||
}
|
||||
/// `ServerExplosion.calculateExplodedPositions`.
|
||||
fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> {
|
||||
let (min_y, max_y) = self.with_level(|_, level, _| {
|
||||
use horizon_world::level::LevelAccess;
|
||||
(level.min_y(), level.max_y())
|
||||
});
|
||||
let mut set: JavaHashMap<Key, ()> = JavaHashMap::default();
|
||||
for xx in 0..16 {
|
||||
for yy in 0..16 {
|
||||
for zz in 0..16 {
|
||||
if !(xx == 0 || xx == 15 || yy == 0 || yy == 15 || zz == 0 || zz == 15) {
|
||||
continue;
|
||||
}
|
||||
let mut xd = f64::from(xx as f32 / 15.0 * 2.0 - 1.0);
|
||||
let mut yd = f64::from(yy as f32 / 15.0 * 2.0 - 1.0);
|
||||
let mut zd = f64::from(zz as f32 / 15.0 * 2.0 - 1.0);
|
||||
let d = (xd * xd + yd * yd + zd * zd).sqrt();
|
||||
xd /= d;
|
||||
yd /= d;
|
||||
zd /= d;
|
||||
let mut power = radius * (0.7 + self.world.random.next_float() * 0.6);
|
||||
let (mut xp, mut yp, mut zp) = (center[0], center[1], center[2]);
|
||||
while power > 0.0 {
|
||||
let pos = [xp.floor() as i32, yp.floor() as i32, zp.floor() as i32];
|
||||
if pos[1] < min_y
|
||||
|| pos[1] >= max_y
|
||||
|| !(-30_000_000..30_000_000).contains(&pos[0])
|
||||
|| !(-30_000_000..30_000_000).contains(&pos[2])
|
||||
{
|
||||
break;
|
||||
}
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
let f = self.res.facts.get(state);
|
||||
let fluid = if f.fluid != Fluid::None {
|
||||
100.0f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
if !self.res.facts.is_air(state) || f.fluid != Fluid::None {
|
||||
power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3;
|
||||
}
|
||||
if power > 0.0 {
|
||||
set.put(Key(pos), ());
|
||||
}
|
||||
xp += xd * f64::from(0.3f32);
|
||||
yp += yd * f64::from(0.3f32);
|
||||
zp += zd * f64::from(0.3f32);
|
||||
power -= 0.225_000_01;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
set.entries().map(|(k, _)| k.0).collect()
|
||||
}
|
||||
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT).
|
||||
fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) {
|
||||
if radius < 1.0e-5 {
|
||||
return;
|
||||
}
|
||||
let diameter = f64::from(radius * 2.0);
|
||||
let distance = |p: [f64; 3]| {
|
||||
((p[0] - center[0]).powi(2) + (p[1] - center[1]).powi(2) + (p[2] - center[2]).powi(2))
|
||||
.sqrt()
|
||||
};
|
||||
let damage = |dist: f64, exposure: f32| {
|
||||
let pow = (1.0 - dist) * f64::from(exposure);
|
||||
((pow * pow + pow) / 2.0 * 7.0 * diameter + 1.0) as f32
|
||||
};
|
||||
let direction = |origin: [f64; 3]| {
|
||||
let d = [
|
||||
origin[0] - center[0],
|
||||
origin[1] - center[1],
|
||||
origin[2] - center[2],
|
||||
];
|
||||
let l = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
|
||||
if l < 1.0e-4 {
|
||||
[0.0; 3]
|
||||
} else {
|
||||
[d[0] / l, d[1] / l, d[2] / l]
|
||||
}
|
||||
};
|
||||
// Player.
|
||||
if let Some(p) = self.player.as_ref() {
|
||||
let feet = [p.position.x, p.position.y, p.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist <= 1.0 && !p.health.dead_or_dying() {
|
||||
let w = f64::from(p.dimensions.width) / 2.0;
|
||||
let h = f64::from(p.dimensions.height);
|
||||
let eye = [
|
||||
feet[0],
|
||||
feet[1] + f64::from(p.dimensions.eye_height),
|
||||
feet[2],
|
||||
];
|
||||
let exposure = self.seen_percent(
|
||||
center,
|
||||
[feet[0] - w, feet[1], feet[2] - w],
|
||||
[feet[0] + w, feet[1] + h, feet[2] + w],
|
||||
);
|
||||
let amount = damage(dist, exposure);
|
||||
let dir = direction(eye);
|
||||
let power = (1.0 - dist) * f64::from(exposure);
|
||||
let mut hurt = false;
|
||||
let creative = self.creative;
|
||||
if let Some(p) = self.player.as_mut()
|
||||
&& let Some(id) = self.motion.health.damage.id("minecraft:explosion")
|
||||
{
|
||||
// Creative players are invulnerable to explosions.
|
||||
if !creative {
|
||||
hurt = p
|
||||
.hurt(&self.motion.health, self.world.health_rules, id, amount)
|
||||
.unwrap_or(false);
|
||||
}
|
||||
p.velocity = Vec3::new(
|
||||
p.velocity.x + dir[0] * power,
|
||||
p.velocity.y + dir[1] * power,
|
||||
p.velocity.z + dir[2] * power,
|
||||
);
|
||||
}
|
||||
if hurt && !self.creative {
|
||||
self.hurt_armor(amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Mobs.
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
for m in mobs.iter_mut().filter(|m| m.alive()) {
|
||||
let feet = [m.position.x, m.position.y, m.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist > 1.0 {
|
||||
continue;
|
||||
}
|
||||
let (w, h) = (m.kind.width / 2.0, m.kind.height);
|
||||
let eye = [feet[0], feet[1] + m.kind.eye_height, feet[2]];
|
||||
let exposure = self.seen_percent(
|
||||
center,
|
||||
[feet[0] - w, feet[1], feet[2] - w],
|
||||
[feet[0] + w, feet[1] + h, feet[2] + w],
|
||||
);
|
||||
m.hurt(damage(dist, exposure), None, &mut self.world.random);
|
||||
let dir = direction(eye);
|
||||
let power = (1.0 - dist) * f64::from(exposure);
|
||||
m.velocity = Vec3::new(
|
||||
m.velocity.x + dir[0] * power,
|
||||
m.velocity.y + dir[1] * power,
|
||||
m.velocity.z + dir[2] * power,
|
||||
);
|
||||
}
|
||||
self.mobs = mobs;
|
||||
// Dropped items: 5 health, destroyed by the explosion damage (nether stars resist).
|
||||
let mut items = std::mem::take(&mut self.dropped);
|
||||
items.retain_mut(|item| {
|
||||
let feet = [item.position.x, item.position.y, item.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist > 1.0 {
|
||||
return true;
|
||||
}
|
||||
let half = 0.125;
|
||||
let exposure = self.seen_percent(
|
||||
center,
|
||||
[feet[0] - half, feet[1], feet[2] - half],
|
||||
[feet[0] + half, feet[1] + 0.25, feet[2] + half],
|
||||
);
|
||||
if &*item.stack.item != "minecraft:nether_star" && damage(dist, exposure) >= 5.0 {
|
||||
return false;
|
||||
}
|
||||
let dir = direction([feet[0], feet[1] + 0.2125, feet[2]]);
|
||||
let power = (1.0 - dist) * f64::from(exposure);
|
||||
item.velocity = Vec3::new(
|
||||
item.velocity.x + dir[0] * power,
|
||||
item.velocity.y + dir[1] * power,
|
||||
item.velocity.z + dir[2] * power,
|
||||
);
|
||||
true
|
||||
});
|
||||
self.dropped = items;
|
||||
// Primed TNT: knockback only, from its position (not its eyes).
|
||||
let mut tnts = std::mem::take(&mut self.tnts);
|
||||
for t in &mut tnts {
|
||||
let feet = [t.position.x, t.position.y, t.position.z];
|
||||
let dist = distance(feet) / diameter;
|
||||
if dist > 1.0 {
|
||||
continue;
|
||||
}
|
||||
let half = 0.49;
|
||||
let exposure = self.seen_percent(
|
||||
center,
|
||||
[feet[0] - half, feet[1], feet[2] - half],
|
||||
[feet[0] + half, feet[1] + 0.98, feet[2] + half],
|
||||
);
|
||||
let dir = direction(feet);
|
||||
let power = (1.0 - dist) * f64::from(exposure);
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x + dir[0] * power,
|
||||
t.velocity.y + dir[1] * power,
|
||||
t.velocity.z + dir[2] * power,
|
||||
);
|
||||
}
|
||||
self.tnts = tnts;
|
||||
}
|
||||
/// `Level.explode` on the server: positions, entities, blocks, fire; then
|
||||
/// the client's explosion sound.
|
||||
pub(super) fn server_explode(
|
||||
&mut self,
|
||||
center: [f64; 3],
|
||||
radius: f32,
|
||||
interaction: BlockInteraction,
|
||||
fire: bool,
|
||||
) -> Result<()> {
|
||||
let mut targets = self.exploded_positions(center, radius);
|
||||
self.explosion_hurt_entities(center, radius);
|
||||
if interaction != BlockInteraction::Keep {
|
||||
// Util.shuffle(list, level.random)
|
||||
for i in (2..=targets.len()).rev() {
|
||||
let swap = self.world.random.next_int_bound(i as i32).unwrap_or(0) as usize;
|
||||
targets.swap(i - 1, swap);
|
||||
}
|
||||
let mut stacks: Vec<([i32; 3], ItemStack)> = Vec::new();
|
||||
for &pos in &targets {
|
||||
self.explosion_hit_block(pos, radius, interaction, &mut stacks)?;
|
||||
}
|
||||
for (pos, stack) in stacks {
|
||||
self.pop_resource(pos, stack);
|
||||
}
|
||||
}
|
||||
if fire {
|
||||
for &pos in &targets {
|
||||
if self.world.random.next_int_bound(3).unwrap_or(1) == 0
|
||||
&& self
|
||||
.res
|
||||
.facts
|
||||
.is_air(self.world.block(pos[0], pos[1], pos[2]))
|
||||
&& self
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(pos[0], pos[1] - 1, pos[2]))
|
||||
.solid_render
|
||||
&& let Some(fire) = self.res.assets.registry.default_state("minecraft:fire")
|
||||
{
|
||||
self.level_set(pos, fire)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let pitch = (1.0 + (client_float() - client_float()) * 0.2) * 0.7;
|
||||
self.audio
|
||||
.play("minecraft:entity.generic.explode", Some(center), 4.0, pitch);
|
||||
Ok(())
|
||||
}
|
||||
/// `BlockBehaviour.onExplosionHit` (TNT: `wasExploded` primes a short fuse).
|
||||
fn explosion_hit_block(
|
||||
&mut self,
|
||||
pos: [i32; 3],
|
||||
radius: f32,
|
||||
interaction: BlockInteraction,
|
||||
stacks: &mut Vec<([i32; 3], ItemStack)>,
|
||||
) -> Result<()> {
|
||||
let state = self.world.block(pos[0], pos[1], pos[2]);
|
||||
if self.res.facts.is_air(state) {
|
||||
return Ok(());
|
||||
}
|
||||
let name = self.res.facts.get(state).name.clone();
|
||||
let is_tnt = &*name == "minecraft:tnt";
|
||||
if !is_tnt {
|
||||
let drops = self.res.items.block_drops(
|
||||
self.res.assets.registry,
|
||||
state,
|
||||
None,
|
||||
&mut self.world.random,
|
||||
);
|
||||
for stack in drops {
|
||||
if &*stack.item == "minecraft:air" || stack.count == 0 {
|
||||
continue;
|
||||
}
|
||||
// survives_explosion / explosion_decay: 1 / radius per stack.
|
||||
if interaction == BlockInteraction::DestroyWithDecay
|
||||
&& self.world.random.next_float() > 1.0 / radius
|
||||
{
|
||||
continue;
|
||||
}
|
||||
add_or_append_stack(stacks, stack, pos);
|
||||
}
|
||||
}
|
||||
let contents = self.world.block_entities.remove(&(pos[0], pos[1], pos[2]));
|
||||
self.level_set(pos, self.world.air)?;
|
||||
if let Some(entity) = contents {
|
||||
for stack in entity.contents() {
|
||||
self.pop_resource(pos, stack);
|
||||
}
|
||||
}
|
||||
if is_tnt {
|
||||
self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerExplosion.addOrAppendStack` with `ItemEntity.merge(.., 16)`.
|
||||
fn add_or_append_stack(
|
||||
stacks: &mut Vec<([i32; 3], ItemStack)>,
|
||||
mut stack: ItemStack,
|
||||
pos: [i32; 3],
|
||||
) {
|
||||
for (_, existing) in stacks.iter_mut() {
|
||||
if existing.item == stack.item && existing.damage == stack.damage && existing.count < 16 {
|
||||
let moved = (16 - existing.count).min(stack.count);
|
||||
existing.count += moved;
|
||||
stack.count -= moved;
|
||||
if stack.count == 0 {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
stacks.push((pos, stack));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn block_pos_hash_matches_vec3i() {
|
||||
// Vec3i.hashCode: (y + z * 31) * 31 + x
|
||||
assert_eq!(Key([1, 2, 3]).java_hash(), (2 + 3 * 31) * 31 + 1);
|
||||
assert_eq!(Key([-5, 64, -7]).java_hash(), (64 - 7 * 31) * 31 - 5);
|
||||
assert_eq!(
|
||||
Key([0, 1, 0]).comparable_compare(&Key([5, 0, 9])),
|
||||
Some(Ordering::Greater)
|
||||
);
|
||||
assert_eq!(
|
||||
Key([1, 0, 2]).comparable_compare(&Key([0, 0, 3])),
|
||||
Some(Ordering::Less)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn drops_merge_up_to_sixteen() {
|
||||
let stack = |item: &str| ItemStack {
|
||||
item: item.into(),
|
||||
count: 1,
|
||||
damage: 0,
|
||||
};
|
||||
let mut stacks = Vec::new();
|
||||
for _ in 0..20 {
|
||||
add_or_append_stack(&mut stacks, stack("minecraft:dirt"), [0, 0, 0]);
|
||||
}
|
||||
add_or_append_stack(&mut stacks, stack("minecraft:stone"), [1, 0, 0]);
|
||||
let counts: Vec<u32> = stacks.iter().map(|(_, s)| s.count).collect();
|
||||
assert_eq!(counts, vec![16, 4, 1]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Client glue for sapling growth and bone meal: installs the live feature
|
||||
//! registry and routes `BoneMealItem.useOn` through the behaviour library.
|
||||
use super::Game;
|
||||
use horizon_client::{Result, items::ItemStack, vanillagen};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos};
|
||||
use horizon_world::worldgen::live::LiveFeatures;
|
||||
use std::sync::Arc;
|
||||
|
||||
impl Game<'_> {
|
||||
/// Load the configured/placed feature registry used by saplings, fungi
|
||||
/// and bone meal (once per process; shares the generator's bundle).
|
||||
pub(super) fn install_live_features(&self) {
|
||||
if self.res.behaviours.live_features().is_some() {
|
||||
return;
|
||||
}
|
||||
let dir = self.options.resources.join("worldgen");
|
||||
let started = std::time::Instant::now();
|
||||
let features = vanillagen::shared_data(&dir, self.res.assets.registry)
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string()));
|
||||
match features {
|
||||
Ok(Some(features)) => {
|
||||
self.res.behaviours.set_live_features(Arc::new(features));
|
||||
eprintln!("Horizon: live features ready in {:?}", started.elapsed());
|
||||
}
|
||||
Ok(None) => {
|
||||
eprintln!("Horizon: the worldgen bundle has no features; saplings will not grow")
|
||||
}
|
||||
Err(e) => eprintln!("Horizon: live features unavailable: {e}"),
|
||||
}
|
||||
}
|
||||
/// `BoneMealItem.useOn` for the targeted block.
|
||||
pub(super) fn use_bone_meal(&mut self, stack: &ItemStack) -> Result<bool> {
|
||||
if &*stack.item != "minecraft:bone_meal" {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(hit) = self.pick() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let face = match hit.face {
|
||||
[0, 1, 0] => Direction::Up,
|
||||
[0, -1, 0] => Direction::Down,
|
||||
[0, 0, -1] => Direction::North,
|
||||
[0, 0, 1] => Direction::South,
|
||||
[-1, 0, 0] => Direction::West,
|
||||
_ => Direction::East,
|
||||
};
|
||||
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
let used = self.with_level(|b, level, ticks| b.use_bone_meal(level, ticks, pos, face));
|
||||
self.process_level_events()?;
|
||||
if used {
|
||||
self.swing_arm();
|
||||
self.consume_held();
|
||||
}
|
||||
Ok(used)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,258 @@
|
||||
//! Primed TNT (`PrimedTnt`): 80-tick fuse, gravity and drag, explosion of
|
||||
//! power 4, `TntRenderer` swell and white flash, and `TntBlock.useItemOn`
|
||||
//! (flint and steel / fire charge).
|
||||
use super::{Game, explosion::BlockInteraction};
|
||||
use horizon_client::{Result, collisions::SceneCollisions, items::ItemStack, mesher::Vertex};
|
||||
use horizon_core::{
|
||||
geometry::{Aabb, Vec3},
|
||||
position::BlockPos,
|
||||
random::RandomSource,
|
||||
};
|
||||
use horizon_world::level::flags as level_flags;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct PrimedTnt {
|
||||
pub position: Vec3,
|
||||
pub previous: Vec3,
|
||||
pub velocity: Vec3,
|
||||
pub fuse: i32,
|
||||
pub on_ground: bool,
|
||||
}
|
||||
impl PrimedTnt {
|
||||
const SIZE: f64 = 0.98;
|
||||
fn bounds(&self) -> Aabb {
|
||||
let h = Self::SIZE / 2.0;
|
||||
Aabb::new(
|
||||
Vec3::new(self.position.x - h, self.position.y, self.position.z - h),
|
||||
Vec3::new(
|
||||
self.position.x + h,
|
||||
self.position.y + Self::SIZE,
|
||||
self.position.z + h,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// `new PrimedTnt(level, x + 0.5, y, z + 0.5, owner)`; `short` applies
|
||||
/// `wasExploded`'s random short fuse. Plays `entity.tnt.primed` for primes.
|
||||
pub(super) fn spawn_primed_tnt(&mut self, pos: BlockPos, short: bool) {
|
||||
let r = &mut self.world.random;
|
||||
let rot = r.next_double() * f64::from(std::f32::consts::TAU);
|
||||
let position = Vec3::new(
|
||||
f64::from(pos.x) + 0.5,
|
||||
f64::from(pos.y),
|
||||
f64::from(pos.z) + 0.5,
|
||||
);
|
||||
let mut tnt = PrimedTnt {
|
||||
position,
|
||||
previous: position,
|
||||
velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02),
|
||||
fuse: 80,
|
||||
on_ground: false,
|
||||
};
|
||||
if short {
|
||||
// PrimedTnt.getRandomShortFuse
|
||||
tnt.fuse = r.next_int_bound((tnt.fuse / 4).max(1)).unwrap_or(0) + tnt.fuse / 8;
|
||||
} else {
|
||||
self.audio.play(
|
||||
"minecraft:entity.tnt.primed",
|
||||
Some([position.x, position.y, position.z]),
|
||||
1.0,
|
||||
1.0,
|
||||
);
|
||||
}
|
||||
self.tnts.push(tnt);
|
||||
}
|
||||
/// `PrimedTnt.tick` for every primed TNT, in order; an expired fuse
|
||||
/// explodes immediately (later TNT in the list feel its knockback this
|
||||
/// tick). TNT primed by an explosion starts ticking next tick.
|
||||
pub(super) fn tick_tnt(&mut self) -> Result<()> {
|
||||
let mut count = self.tnts.len();
|
||||
let mut i = 0;
|
||||
while i < count {
|
||||
let t = &mut self.tnts[i];
|
||||
t.previous = t.position;
|
||||
t.velocity.y -= 0.04;
|
||||
let mut scene = SceneCollisions {
|
||||
world: &self.world,
|
||||
binding: self.collision,
|
||||
};
|
||||
let wanted = t.velocity;
|
||||
let moved = scene
|
||||
.resolve(t.bounds(), wanted, 0.0, t.on_ground)
|
||||
.unwrap_or(Vec3::ZERO);
|
||||
t.position = Vec3::new(
|
||||
t.position.x + moved.x,
|
||||
t.position.y + moved.y,
|
||||
t.position.z + moved.z,
|
||||
);
|
||||
t.on_ground = wanted.y < 0.0 && moved.y != wanted.y;
|
||||
if moved.x != wanted.x {
|
||||
t.velocity.x = 0.0;
|
||||
}
|
||||
if moved.z != wanted.z {
|
||||
t.velocity.z = 0.0;
|
||||
}
|
||||
if moved.y != wanted.y {
|
||||
t.velocity.y = 0.0;
|
||||
}
|
||||
t.velocity = Vec3::new(
|
||||
t.velocity.x * 0.98,
|
||||
t.velocity.y * 0.98,
|
||||
t.velocity.z * 0.98,
|
||||
);
|
||||
if t.on_ground {
|
||||
t.velocity = Vec3::new(t.velocity.x * 0.7, t.velocity.y * -0.5, t.velocity.z * 0.7);
|
||||
}
|
||||
t.fuse -= 1;
|
||||
if t.fuse <= 0 {
|
||||
let center = [
|
||||
t.position.x,
|
||||
t.position.y + PrimedTnt::SIZE * 0.0625,
|
||||
t.position.z,
|
||||
];
|
||||
self.tnts.remove(i);
|
||||
count -= 1;
|
||||
self.server_explode(center, 4.0, BlockInteraction::Destroy, false)?;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `TntBlock.useItemOn`: flint and steel or a fire charge primes TNT.
|
||||
pub(super) fn ignite_tnt(&mut self, stack: &ItemStack) -> Result<bool> {
|
||||
let item = &*stack.item;
|
||||
if item != "minecraft:flint_and_steel" && item != "minecraft:fire_charge" {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(hit) = self.pick() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
if &*self.res.facts.get(state).name != "minecraft:tnt" {
|
||||
return Ok(false);
|
||||
}
|
||||
let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]);
|
||||
self.spawn_primed_tnt(pos, false);
|
||||
let air = self.world.air;
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.set_block(level, ticks, pos, air, level_flags::UPDATE_ALL_IMMEDIATE)
|
||||
});
|
||||
self.process_level_events()?;
|
||||
self.swing_arm();
|
||||
if item == "minecraft:flint_and_steel" {
|
||||
self.damage_held(1);
|
||||
} else {
|
||||
self.consume_held();
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
/// `TntRenderer`: the block centred on the entity, swelling over the last
|
||||
/// 10 ticks and flashing white every 5 ticks.
|
||||
pub(super) fn tnt_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
if self.tnts.is_empty() {
|
||||
return;
|
||||
}
|
||||
let Some(state) = self.res.assets.registry.default_state("minecraft:tnt") else {
|
||||
return;
|
||||
};
|
||||
// Face sprites from the block model: up, down, north, south, west, east.
|
||||
let Ok(models) = self
|
||||
.res
|
||||
.assets
|
||||
.model_catalog
|
||||
.collect(state, BlockPos::new(0, 0, 0))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut sprites = [None; 6];
|
||||
for face in models.iter().flat_map(|(_, m)| m.faces.iter()) {
|
||||
use horizon_assets::model::Direction as D;
|
||||
let index = match face.quad.facing {
|
||||
D::Up => 0,
|
||||
D::Down => 1,
|
||||
D::North => 2,
|
||||
D::South => 3,
|
||||
D::West => 4,
|
||||
D::East => 5,
|
||||
};
|
||||
if sprites[index].is_none() {
|
||||
sprites[index] = self
|
||||
.res
|
||||
.layer_names
|
||||
.get(&face.layer)
|
||||
.and_then(|name| self.res.atlas.sprites.get(name).copied());
|
||||
}
|
||||
}
|
||||
for t in &self.tnts {
|
||||
let fuse = t.fuse as f32 - alpha as f32 + 1.0;
|
||||
let scale = if fuse < 10.0 {
|
||||
let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0);
|
||||
1.0 + g * g * g * g * 0.3
|
||||
} else {
|
||||
1.0
|
||||
};
|
||||
let lit = fuse >= 0.0 && (fuse / 5.0) as i32 % 2 == 0;
|
||||
let base = glam::DVec3::new(
|
||||
t.previous.x + (t.position.x - t.previous.x) * alpha,
|
||||
t.previous.y + (t.position.y - t.previous.y) * alpha + 0.5,
|
||||
t.previous.z + (t.position.z - t.previous.z) * alpha,
|
||||
) - camera;
|
||||
let o = base.as_vec3();
|
||||
let light = self.world.light(
|
||||
t.position.x.floor() as i32,
|
||||
(t.position.y + 0.5).floor() as i32,
|
||||
t.position.z.floor() as i32,
|
||||
);
|
||||
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
|
||||
let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x - 0.5, y - 0.5, z - 0.5) * scale;
|
||||
let faces = [
|
||||
(
|
||||
[v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)],
|
||||
1.0,
|
||||
),
|
||||
(
|
||||
[v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)],
|
||||
0.5,
|
||||
),
|
||||
(
|
||||
[v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)],
|
||||
0.8,
|
||||
),
|
||||
(
|
||||
[v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)],
|
||||
0.8,
|
||||
),
|
||||
(
|
||||
[v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)],
|
||||
0.6,
|
||||
),
|
||||
(
|
||||
[v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)],
|
||||
0.6,
|
||||
),
|
||||
];
|
||||
for ((corners, shade), sprite) in faces.into_iter().zip(sprites) {
|
||||
let Some(r) = sprite else { continue };
|
||||
let c = (255.0 * shade) as u32;
|
||||
let color = 0xFF00_0000 | c << 16 | c << 8 | c;
|
||||
for (p, uv) in
|
||||
corners
|
||||
.iter()
|
||||
.zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]])
|
||||
{
|
||||
// Overlay 4: OverlayTexture white flash.
|
||||
out.push(Vertex {
|
||||
pos: p.to_array(),
|
||||
uv,
|
||||
layer: if lit { 4 } else { 0 },
|
||||
color,
|
||||
light: packed,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,7 +360,7 @@ fn decode_block_entity(tag: &Tag) -> Option<((i32, i32, i32), crate::containers:
|
||||
let pos = (int("x")?, int("y")?, int("z")?);
|
||||
let mut entity = BlockEntity::for_block(&id)?;
|
||||
match &mut entity {
|
||||
BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), 27),
|
||||
BlockEntity::Chest(items) => *items = decode_items(tag.get("Items"), items.len()),
|
||||
BlockEntity::Furnace(f) => {
|
||||
let items = decode_items(tag.get("Items"), 3);
|
||||
f.items = [items[0].clone(), items[1].clone(), items[2].clone()];
|
||||
@@ -557,6 +557,28 @@ pub fn encode_with(chunk: &Chunk, registry: &BlockRegistry, biomes: &Biomes, tab
|
||||
("block_entities", Tag::List(block_entities)),
|
||||
] {
|
||||
put(&mut root, key, value);
|
||||
NamedTag {
|
||||
name: "".into(),
|
||||
tag: Tag::compound([
|
||||
("DataVersion", Tag::Int(DATA_VERSION)),
|
||||
("xPos", Tag::Int(chunk.x)),
|
||||
("zPos", Tag::Int(chunk.z)),
|
||||
("yPos", Tag::Int(MIN_Y >> 4)),
|
||||
("Status", string("minecraft:full")),
|
||||
("LastUpdate", Tag::Long(0)),
|
||||
("InhabitedTime", Tag::Long(0)),
|
||||
("isLightOn", Tag::Byte(0)),
|
||||
("sections", Tag::List(sections)),
|
||||
("block_entities", Tag::List(chunk.block_entities.iter().map(|(p, e)| {
|
||||
// The block's own entity id (barrels, droppers, trapped chests).
|
||||
let mut tag = encode_block_entity(*p, e);
|
||||
let state = chunk.block(p.0 & 15, p.1, p.2 & 15);
|
||||
if let (Tag::Compound(entries), Some(id)) = (&mut tag, registry.state(state).and_then(|s| crate::containers::BlockEntity::id_for_block(&s.name))) {
|
||||
entries.insert("id".into(), string(id));
|
||||
}
|
||||
tag
|
||||
}).collect())),
|
||||
]),
|
||||
}
|
||||
if let Some(Tag::Compound(map)) = Some(&mut root) {
|
||||
map.entry("InhabitedTime".into()).or_insert(Tag::Long(0));
|
||||
|
||||
@@ -27,7 +27,7 @@ impl VanillaTerrain {
|
||||
Self::for_dimension(dir, registry, biomes, seed, "minecraft:overworld")
|
||||
}
|
||||
pub fn for_dimension(dir: &Path, registry: &'static BlockRegistry, biomes: &Biomes, seed: i64, dimension: &str) -> crate::Result<Self> {
|
||||
let data: Arc<GeneratorData> = GeneratorData::load(dir, registry)?;
|
||||
let data: Arc<GeneratorData> = shared_data(dir, registry)?;
|
||||
let biome_map = data.biome_names().iter().map(|name| biomes.id(name)).collect();
|
||||
let generator = OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?;
|
||||
let unsupported = generator.unsupported_features();
|
||||
@@ -50,6 +50,18 @@ impl VanillaTerrain {
|
||||
self.generator.ring_positions(set)
|
||||
}
|
||||
}
|
||||
/// The worldgen bundle at `dir`, loaded once and shared by every generator
|
||||
/// and by live feature placement (sapling growth, bone meal).
|
||||
pub fn shared_data(dir: &Path, registry: &'static BlockRegistry) -> crate::Result<Arc<GeneratorData>> {
|
||||
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> = std::sync::Mutex::new(Vec::new());
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
|
||||
return Ok(data.clone());
|
||||
}
|
||||
let data = GeneratorData::load(dir, registry)?;
|
||||
cache.push((dir.to_owned(), data.clone()));
|
||||
Ok(data)
|
||||
}
|
||||
impl ChunkGenerator for VanillaTerrain {
|
||||
type Worker = GeneratorWorker;
|
||||
fn worker(&self) -> GeneratorWorker {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
//! 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()
|
||||
}
|
||||
}
|
||||
|
||||
/// The four (state, position) pairs of a 2x2 sapling square.
|
||||
type Saplings = [(BlockStateId, BlockPos); 4];
|
||||
|
||||
/// `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, Saplings)> {
|
||||
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,416 @@
|
||||
//! 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,
|
||||
day: i64,
|
||||
}
|
||||
impl LevelAccess for Level {
|
||||
fn day_time(&self) -> i64 {
|
||||
self.day
|
||||
}
|
||||
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 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",
|
||||
day: 6000,
|
||||
},
|
||||
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",
|
||||
..
|
||||
}
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snowy_biomes_freeze_and_snow() {
|
||||
let Some(f) = fixture() else { return };
|
||||
let mut w = World::new(f, 1);
|
||||
w.level.biome = "minecraft:snowy_plains";
|
||||
w.floor("grass_block", 2);
|
||||
let water = w.id("water", &[]);
|
||||
w.put(BlockPos::new(1, 63, 0), water);
|
||||
let b = &f.behaviours;
|
||||
let grass = b
|
||||
.precipitation_info(&w.level, BlockPos::new(0, 70, 0))
|
||||
.unwrap();
|
||||
assert_eq!(grass.top, BlockPos::new(0, 64, 0));
|
||||
assert!(grass.snows_at_top && !grass.freezes_below);
|
||||
assert_eq!(grass.kind, PrecipitationKind::Snow);
|
||||
let pond = b
|
||||
.precipitation_info(&w.level, BlockPos::new(1, 70, 0))
|
||||
.unwrap();
|
||||
assert!(pond.freezes_below, "a water source at the edge freezes");
|
||||
w.level.biome = "minecraft:plains";
|
||||
let rain = b
|
||||
.precipitation_info(&w.level, BlockPos::new(0, 70, 0))
|
||||
.unwrap();
|
||||
assert!(!rain.snows_at_top && !rain.freezes_below);
|
||||
assert_eq!(rain.kind, PrecipitationKind::Rain);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eyeblossoms_open_at_night_and_wake_neighbours() {
|
||||
let Some(f) = fixture() else { return };
|
||||
let mut w = World::new(f, 2);
|
||||
w.floor("grass_block", 4);
|
||||
let closed = w.id("closed_eyeblossom", &[]);
|
||||
w.put(BlockPos::new(0, 64, 0), closed);
|
||||
w.put(BlockPos::new(2, 64, 1), closed);
|
||||
f.behaviours
|
||||
.random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 64, 0));
|
||||
assert_eq!(
|
||||
w.name(BlockPos::new(0, 64, 0)),
|
||||
"minecraft:closed_eyeblossom",
|
||||
"closed by day"
|
||||
);
|
||||
w.level.day = 13000;
|
||||
f.behaviours
|
||||
.random_tick(&mut w.level, &mut w.ticks, BlockPos::new(0, 64, 0));
|
||||
assert_eq!(w.name(BlockPos::new(0, 64, 0)), "minecraft:open_eyeblossom");
|
||||
let block = f.behaviours.block(closed);
|
||||
assert!(
|
||||
w.ticks.has_block_tick(BlockPos::new(2, 64, 1), block),
|
||||
"neighbour scheduled"
|
||||
);
|
||||
assert!(w.level.events.iter().any(|e| matches!(e, LevelEvent::Sound { sound, .. } if &**sound == "minecraft:block.eyeblossom.open_long")));
|
||||
}
|
||||
#[test]
|
||||
fn turtle_eggs_crack_at_dawn_on_sand() {
|
||||
let Some(f) = fixture() else { return };
|
||||
let mut w = World::new(f, 3);
|
||||
w.floor("sand", 1);
|
||||
let egg = w.id("turtle_egg", &[]);
|
||||
let pos = BlockPos::new(0, 64, 0);
|
||||
w.put(pos, egg);
|
||||
w.level.day = 21500;
|
||||
f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos);
|
||||
assert_eq!(
|
||||
w.level.block_state(pos),
|
||||
w.id("turtle_egg", &[("hatch", "1")])
|
||||
);
|
||||
f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos);
|
||||
f.behaviours.random_tick(&mut w.level, &mut w.ticks, pos);
|
||||
assert_eq!(w.name(pos), "minecraft:air", "hatched");
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `neighborChanged`, `onPlace`, `affectNeighborsAfterRemoval` and
|
||||
//! `updateIndirectNeighbourShapes` for the overriding vanilla classes.
|
||||
use super::{
|
||||
LevelAccess, Sim,
|
||||
LevelAccess, LevelEvent, Sim,
|
||||
classes::Class,
|
||||
states::BlockId,
|
||||
update::{below, rel},
|
||||
@@ -389,6 +389,10 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
self.level_event(2001, head_pos, head.0 as i32);
|
||||
}
|
||||
}
|
||||
// TntBlock.playerWillDestroy: unstable TNT primes unless instabuild.
|
||||
if !creative && data.is(Class::Tnt) && b.table.bool(state, p.unstable) {
|
||||
self.emit(LevelEvent::PrimeTnt { pos });
|
||||
}
|
||||
self.level_event(2001, pos, state.0 as i32);
|
||||
self.game_event(pos, "minecraft:block_destroy");
|
||||
self.remove_block(pos, false)
|
||||
|
||||
@@ -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;
|
||||
@@ -110,11 +113,16 @@ mod query;
|
||||
mod rails;
|
||||
mod redstone;
|
||||
mod shapes;
|
||||
mod signals;
|
||||
mod speleothem;
|
||||
mod survive;
|
||||
mod tick;
|
||||
mod timeline;
|
||||
mod update;
|
||||
mod weather;
|
||||
|
||||
#[cfg(test)]
|
||||
mod growth_tests;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -337,6 +345,20 @@ 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
|
||||
}
|
||||
/// `Level.getDayTime` (the overworld clock driving the day timeline's
|
||||
/// environment attributes, e.g. eyeblossoms opening at night).
|
||||
fn day_time(&self) -> i64 {
|
||||
6000
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw brightness as `Level.getRawBrightness(pos, skyDarken)`.
|
||||
@@ -361,6 +383,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 {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
//! Output-signal notifications for block entities the caller owns.
|
||||
use super::{Behaviours, LevelAccess, Ticks};
|
||||
use horizon_core::position::BlockPos;
|
||||
|
||||
impl Behaviours {
|
||||
/// `BlockEntity.setChanged`: a container at `pos` changed its contents, so
|
||||
/// comparators reading it (`Level.updateNeighbourForOutputSignal`) update.
|
||||
pub fn container_changed<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
) {
|
||||
let state = level.block_state(pos);
|
||||
if !self.is_air(state) {
|
||||
let block = self.block(state);
|
||||
self.sim(level, ticks)
|
||||
.update_neighbour_for_output_signal(pos, block);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Behaviours {
|
||||
/// The update half of `Level.setBlock` for a state the caller already
|
||||
/// wrote to storage (entity landing rules write blocks directly):
|
||||
/// neighbour updates, then neighbour shape updates, per `flags`.
|
||||
pub fn notify_written<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
pos: BlockPos,
|
||||
flags: i32,
|
||||
) {
|
||||
use super::flags as f;
|
||||
let state = level.block_state(pos);
|
||||
let mut sim = self.sim(level, ticks);
|
||||
if flags & f::UPDATE_NEIGHBORS != 0 {
|
||||
sim.update_neighbors_at(pos, self.block(state));
|
||||
}
|
||||
if flags & f::UPDATE_KNOWN_SHAPE == 0 {
|
||||
let neighbour_flags = flags & !(f::UPDATE_NEIGHBORS | f::UPDATE_SUPPRESS_DROPS);
|
||||
sim.update_neighbour_shapes(state, pos, neighbour_flags, f::UPDATE_LIMIT - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -208,6 +208,10 @@ impl StateTable {
|
||||
pub fn key(&mut self, name: &str) -> PropKey {
|
||||
self.key_or_insert(name)
|
||||
}
|
||||
/// An existing property key, without interning a new one.
|
||||
pub fn key_of(&self, name: &str) -> Option<PropKey> {
|
||||
self.keys.get(name).copied()
|
||||
}
|
||||
pub fn state_count(&self) -> usize {
|
||||
self.state_block.len()
|
||||
}
|
||||
|
||||
@@ -140,6 +140,8 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
}
|
||||
}
|
||||
Class::Observer => self.observer_tick(pos, state),
|
||||
Class::Eyeblossom => self.eyeblossom_tick(state, pos, false),
|
||||
Class::DriedGhast => self.dried_ghast_tick(state, pos),
|
||||
Class::RedstoneLamp => self.lamp_tick(pos, state),
|
||||
Class::RedstoneTorch => self.torch_tick(pos, state),
|
||||
Class::Scaffolding => self.scaffolding_tick(pos, state),
|
||||
@@ -329,6 +331,10 @@ impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
}
|
||||
}
|
||||
Class::Vine => self.vine_random_tick(state, pos),
|
||||
Class::Eyeblossom => self.eyeblossom_tick(state, pos, true),
|
||||
Class::FlowerPot => self.potted_eyeblossom_tick(state, pos),
|
||||
Class::TurtleEgg => self.turtle_egg_tick(state, pos),
|
||||
Class::DriedGhast => self.dried_ghast_random_tick(state, pos),
|
||||
Class::WeatheringCopperFull => self.copper_change_over_time(state, pos),
|
||||
_ => continue,
|
||||
}
|
||||
@@ -708,11 +714,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 +796,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 +876,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 +1016,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 +1034,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 +1047,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);
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Blocks driven by the overworld day timeline's environment attributes
|
||||
//! (`gameplay/eyeblossom_open`, `gameplay/turtle_egg_hatch_chance`) and the
|
||||
//! dried ghast's hydration ticks.
|
||||
use super::{Dimension, LevelAccess, LevelEvent, Sim, update::below};
|
||||
use crate::registry::BlockStateId;
|
||||
use horizon_core::{position::BlockPos, random::RandomSource};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// `BlockScanUtils.findBlocks` order: sections by x, z, y; blocks by y, z, x.
|
||||
pub(crate) fn box_scan_order(min: BlockPos, max: BlockPos) -> Vec<BlockPos> {
|
||||
let mut out = Vec::new();
|
||||
for sx in (min.x >> 4)..=(max.x >> 4) {
|
||||
for sz in (min.z >> 4)..=(max.z >> 4) {
|
||||
for sy in (min.y >> 4)..=(max.y >> 4) {
|
||||
for y in (sy * 16).max(min.y)..=(sy * 16 + 15).min(max.y) {
|
||||
for z in (sz * 16).max(min.z)..=(sz * 16 + 15).min(max.z) {
|
||||
for x in (sx * 16).max(min.x)..=(sx * 16 + 15).min(max.x) {
|
||||
out.push(BlockPos::new(x, y, z));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl<L: LevelAccess + ?Sized> Sim<'_, L> {
|
||||
fn day_ticks(&self) -> Option<i64> {
|
||||
(self.level.dimension() == Dimension::Overworld)
|
||||
.then(|| self.level.day_time().rem_euclid(24000))
|
||||
}
|
||||
/// `EnvironmentAttributes.EYEBLOSSOM_OPEN` (day timeline: open from 12600
|
||||
/// to 23400); None (TriState.DEFAULT) outside the overworld.
|
||||
fn eyeblossom_open(&self) -> Option<bool> {
|
||||
self.day_ticks().map(|t| (12600..23401).contains(&t))
|
||||
}
|
||||
/// `EnvironmentAttributes.TURTLE_EGG_HATCH_CHANCE`: 1.0 around dawn
|
||||
/// (21062..21905), otherwise the 0.002 default.
|
||||
fn turtle_hatch_chance(&self) -> f32 {
|
||||
match self.day_ticks() {
|
||||
Some(t) if (21062..21905).contains(&t) => 1.0,
|
||||
_ => 0.002,
|
||||
}
|
||||
}
|
||||
fn named_state(&self, name: &str) -> Option<BlockStateId> {
|
||||
self.b
|
||||
.table
|
||||
.block_by_name(name)
|
||||
.map(|b| self.b.default_of(b))
|
||||
}
|
||||
fn play(&mut self, pos: BlockPos, sound: &str, volume: f32, pitch: f32) {
|
||||
self.emit(LevelEvent::Sound {
|
||||
pos,
|
||||
sound: Arc::from(sound),
|
||||
volume,
|
||||
pitch,
|
||||
});
|
||||
}
|
||||
/// `EyeblossomBlock.Type.spawnTransformParticle`: four random draws.
|
||||
fn eyeblossom_particle_draws(&mut self) {
|
||||
for _ in 0..4 {
|
||||
self.random().next_double();
|
||||
}
|
||||
}
|
||||
/// `EyeblossomBlock.tryChangingState`; `long` picks the random-tick sound.
|
||||
pub(crate) fn eyeblossom_tick(&mut self, state: BlockStateId, pos: BlockPos, long: bool) {
|
||||
let b = self.b;
|
||||
let open = b.table.name(state) == "minecraft:open_eyeblossom";
|
||||
let Some(should_be_open) = self.eyeblossom_open() else {
|
||||
return;
|
||||
};
|
||||
if should_be_open == open {
|
||||
return;
|
||||
}
|
||||
let new_name = if open {
|
||||
"minecraft:closed_eyeblossom"
|
||||
} else {
|
||||
"minecraft:open_eyeblossom"
|
||||
};
|
||||
let Some(next) = self.named_state(new_name) else {
|
||||
return;
|
||||
};
|
||||
self.set_block_and_update(pos, next);
|
||||
self.game_event(pos, "minecraft:block_change");
|
||||
self.eyeblossom_particle_draws();
|
||||
let min = pos.offset(-3, -2, -3);
|
||||
let max = pos.offset(3, 2, 3);
|
||||
let block = b.block(state);
|
||||
for near in box_scan_order(min, max) {
|
||||
if self.state(near) != state {
|
||||
continue;
|
||||
}
|
||||
let (dx, dy, dz) = (near.x - pos.x, near.y - pos.y, near.z - pos.z);
|
||||
let distance = f64::from(dx * dx + dy * dy + dz * dz).sqrt();
|
||||
let (lo, hi) = ((distance * 5.0) as i32, (distance * 10.0) as i32);
|
||||
let delay = self
|
||||
.random()
|
||||
.next_int_between_inclusive(lo, hi)
|
||||
.unwrap_or(lo);
|
||||
self.schedule_tick(near, block, delay);
|
||||
}
|
||||
let sound = match (!open, long) {
|
||||
(true, true) => "minecraft:block.eyeblossom.open_long",
|
||||
(true, false) => "minecraft:block.eyeblossom.open",
|
||||
(false, true) => "minecraft:block.eyeblossom.close_long",
|
||||
(false, false) => "minecraft:block.eyeblossom.close",
|
||||
};
|
||||
self.play(pos, sound, 1.0, 1.0);
|
||||
}
|
||||
/// `FlowerPotBlock.randomTick` for potted eyeblossoms.
|
||||
pub(crate) fn potted_eyeblossom_tick(&mut self, state: BlockStateId, pos: BlockPos) {
|
||||
let name = self.b.table.name(state);
|
||||
let open = match name {
|
||||
"minecraft:potted_open_eyeblossom" => true,
|
||||
"minecraft:potted_closed_eyeblossom" => false,
|
||||
_ => return,
|
||||
};
|
||||
let Some(should_be_open) = self.eyeblossom_open() else {
|
||||
return;
|
||||
};
|
||||
if open == should_be_open {
|
||||
return;
|
||||
}
|
||||
let other = if open {
|
||||
"minecraft:potted_closed_eyeblossom"
|
||||
} else {
|
||||
"minecraft:potted_open_eyeblossom"
|
||||
};
|
||||
let Some(next) = self.named_state(other) else {
|
||||
return;
|
||||
};
|
||||
self.set_block_and_update(pos, next);
|
||||
self.eyeblossom_particle_draws();
|
||||
let sound = if open {
|
||||
"minecraft:block.eyeblossom.close_long"
|
||||
} else {
|
||||
"minecraft:block.eyeblossom.open_long"
|
||||
};
|
||||
self.play(pos, sound, 1.0, 1.0);
|
||||
}
|
||||
/// `TurtleEggBlock.randomTick`: crack, then hatch on sand.
|
||||
pub(crate) fn turtle_egg_tick(&mut self, state: BlockStateId, pos: BlockPos) {
|
||||
let b = self.b;
|
||||
let chance = self.turtle_hatch_chance();
|
||||
if !(chance > 0.0 && self.random().next_float() < chance) {
|
||||
return;
|
||||
}
|
||||
if !b
|
||||
.tag("minecraft:sand")
|
||||
.is_some_and(|t| b.in_set(self.state(below(pos)), t))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let hatch = b.table.int(state, b.props.hatch);
|
||||
let pitch = 0.9 + self.random().next_float() * 0.2;
|
||||
if hatch < 2 {
|
||||
self.play(pos, "minecraft:entity.turtle.egg_crack", 0.7, pitch);
|
||||
self.set_block(pos, b.table.set_int(state, b.props.hatch, hatch + 1), 2);
|
||||
self.game_event(pos, "minecraft:block_change");
|
||||
} else {
|
||||
self.play(pos, "minecraft:entity.turtle.egg_hatch", 0.7, pitch);
|
||||
self.remove_block(pos, false);
|
||||
self.game_event(pos, "minecraft:block_destroy");
|
||||
for _ in 0..b.table.int(state, b.props.eggs) {
|
||||
self.level_event(2001, pos, state.0 as i32);
|
||||
}
|
||||
// Baby turtles are entities the caller spawns (one per egg).
|
||||
self.emit(LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "hatch_turtles",
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `DriedGhastBlock.tick`: hydrate while waterlogged, dry out otherwise.
|
||||
pub(crate) fn dried_ghast_tick(&mut self, state: BlockStateId, pos: BlockPos) {
|
||||
let b = self.b;
|
||||
let Some(key) = b.table.key_of("hydration") else {
|
||||
return;
|
||||
};
|
||||
let hydration = b.table.int(state, key);
|
||||
if b.table.bool(state, b.props.waterlogged) {
|
||||
if hydration < 3 {
|
||||
self.play(pos, "minecraft:block.dried_ghast.transition", 1.0, 1.0);
|
||||
self.set_block(pos, b.table.set_int(state, key, hydration + 1), 2);
|
||||
self.game_event(pos, "minecraft:block_change");
|
||||
} else {
|
||||
self.remove_block(pos, false);
|
||||
// The happy ghastling is an entity the caller spawns.
|
||||
self.emit(LevelEvent::BlockEvent {
|
||||
pos,
|
||||
state,
|
||||
kind: "spawn_ghastling",
|
||||
});
|
||||
}
|
||||
} else if hydration > 0 {
|
||||
self.set_block(pos, b.table.set_int(state, key, hydration - 1), 2);
|
||||
self.game_event(pos, "minecraft:block_change");
|
||||
}
|
||||
}
|
||||
/// `DriedGhastBlock.randomTick`: keep a 5000-tick hydration tick scheduled.
|
||||
pub(crate) fn dried_ghast_random_tick(&mut self, state: BlockStateId, pos: BlockPos) {
|
||||
let b = self.b;
|
||||
let hydration = b
|
||||
.table
|
||||
.key_of("hydration")
|
||||
.map_or(0, |k| b.table.int(state, k));
|
||||
let block = b.block(state);
|
||||
if (b.table.bool(state, b.props.waterlogged) || hydration > 0)
|
||||
&& !self.ticks.has_block_tick(pos, block)
|
||||
{
|
||||
self.schedule_tick(pos, block, 5000);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
//! Biome weather queries for a live level: `ServerLevel.tickPrecipitation`'s
|
||||
//! inputs (`Biome.shouldFreeze`, `shouldSnow`, `getPrecipitationAt`) and
|
||||
//! `Level.isRainingAt`, from the biome temperatures of the worldgen bundle.
|
||||
use super::{Behaviours, Dimension, LevelAccess, Precipitation, PrecipitationKind};
|
||||
use crate::{
|
||||
fluid::FluidKind,
|
||||
worldgen::biome_temperature::{BiomeTemperatureSettings, Precipitation as BiomePrecipitation},
|
||||
};
|
||||
use horizon_core::{geometry::Direction, position::BlockPos};
|
||||
|
||||
fn sea_level<L: LevelAccess + ?Sized>(level: &L) -> i32 {
|
||||
match level.dimension() {
|
||||
Dimension::Nether => 32,
|
||||
Dimension::End => 0,
|
||||
Dimension::Overworld => 63,
|
||||
}
|
||||
}
|
||||
|
||||
impl Behaviours {
|
||||
fn biome_settings<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &L,
|
||||
pos: BlockPos,
|
||||
) -> Option<BiomeTemperatureSettings> {
|
||||
let features = self.live_features()?;
|
||||
let biome = features.biome_id(level.biome_name(pos)?)?;
|
||||
features.biome_temperature(biome)
|
||||
}
|
||||
/// `Biome.getPrecipitationAt(pos, seaLevel)`.
|
||||
fn precipitation_kind(
|
||||
settings: BiomeTemperatureSettings,
|
||||
pos: BlockPos,
|
||||
sea: i32,
|
||||
) -> BiomePrecipitation {
|
||||
if !settings.has_precipitation {
|
||||
BiomePrecipitation::None
|
||||
} else if settings.height_adjusted(pos, sea) < 0.15 {
|
||||
BiomePrecipitation::Snow
|
||||
} else {
|
||||
BiomePrecipitation::Rain
|
||||
}
|
||||
}
|
||||
/// `getHeightmapPos(MOTION_BLOCKING, pos)`.
|
||||
fn motion_blocking_top<L: LevelAccess + ?Sized>(&self, level: &L, pos: BlockPos) -> BlockPos {
|
||||
let blocks = self.tag("minecraft:blocks_motion_in_heightmap");
|
||||
for y in (level.min_y()..level.max_y()).rev() {
|
||||
let state = level.block_state(BlockPos::new(pos.x, y, pos.z));
|
||||
let fluid = self.fluid(state).kind() != FluidKind::Empty;
|
||||
if fluid || blocks.is_some_and(|t| t.contains(self.block(state))) {
|
||||
return BlockPos::new(pos.x, y + 1, pos.z);
|
||||
}
|
||||
}
|
||||
BlockPos::new(pos.x, level.min_y(), pos.z)
|
||||
}
|
||||
/// Answers for one `ServerLevel.tickPrecipitation` at the column of `pos`;
|
||||
/// None without live features or a biome.
|
||||
pub fn precipitation_info<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &L,
|
||||
pos: BlockPos,
|
||||
) -> Option<Precipitation> {
|
||||
let top = self.motion_blocking_top(level, pos);
|
||||
let below = BlockPos::new(top.x, top.y - 1, top.z);
|
||||
let settings = self.biome_settings(level, top)?;
|
||||
let sea = sea_level(level);
|
||||
let inside = |p: BlockPos| p.y >= level.min_y() && p.y < level.max_y();
|
||||
// Biome.shouldFreeze(level, below, true)
|
||||
let freezes_below = settings.height_adjusted(below, sea) < 0.15
|
||||
&& inside(below)
|
||||
&& level.block_light(below) < 10
|
||||
&& {
|
||||
let state = level.block_state(below);
|
||||
self.block(state) == self.named.water && self.fluid(state).is_source()
|
||||
}
|
||||
&& [
|
||||
Direction::West,
|
||||
Direction::East,
|
||||
Direction::North,
|
||||
Direction::South,
|
||||
]
|
||||
.into_iter()
|
||||
.any(|d| {
|
||||
let n = super::update::rel(below, d);
|
||||
!self.is_water_fluid(self.fluid(level.block_state(n)).kind())
|
||||
});
|
||||
// Biome.shouldSnow(level, top)
|
||||
let snows_at_top = Self::precipitation_kind(settings, top, sea) == BiomePrecipitation::Snow
|
||||
&& inside(top)
|
||||
&& level.block_light(top) < 10
|
||||
&& {
|
||||
let state = level.block_state(top);
|
||||
(self.is_air(state) || self.block(state) == self.named.snow)
|
||||
&& self.snow_survives(level, top)
|
||||
};
|
||||
let kind = match Self::precipitation_kind(settings, below, sea) {
|
||||
BiomePrecipitation::None => PrecipitationKind::None,
|
||||
BiomePrecipitation::Rain => PrecipitationKind::Rain,
|
||||
BiomePrecipitation::Snow => PrecipitationKind::Snow,
|
||||
};
|
||||
Some(Precipitation {
|
||||
top,
|
||||
freezes_below,
|
||||
snows_at_top,
|
||||
kind,
|
||||
})
|
||||
}
|
||||
/// `SnowLayerBlock.canSurvive` for a default snow layer at `pos`.
|
||||
fn snow_survives<L: LevelAccess + ?Sized>(&self, level: &L, pos: BlockPos) -> bool {
|
||||
let below = level.block_state(BlockPos::new(pos.x, pos.y - 1, pos.z));
|
||||
let block = self.block(below);
|
||||
if self.tags.cannot_support_snow_layer.contains(block) {
|
||||
return false;
|
||||
}
|
||||
if self.tags.support_override_snow_layer.contains(block) {
|
||||
return true;
|
||||
}
|
||||
self.collision_face_full(below, Direction::Up)
|
||||
|| (block == self.named.snow && self.table.int(below, self.props.layers) == 8)
|
||||
}
|
||||
/// `Level.isRainingAt(pos)`.
|
||||
pub fn is_raining_at<L: LevelAccess + ?Sized>(&self, level: &L, pos: BlockPos) -> bool {
|
||||
if !level.is_raining() || level.sky_light(pos) < 15 {
|
||||
return false;
|
||||
}
|
||||
if self.motion_blocking_top(level, pos).y > pos.y {
|
||||
return false;
|
||||
}
|
||||
self.biome_settings(level, pos).is_some_and(|s| {
|
||||
Self::precipitation_kind(s, pos, sea_level(level)) == BiomePrecipitation::Rain
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
//! 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>>,
|
||||
/// Temperature settings per biome (`Biome.getTemperature`).
|
||||
temperatures: Vec<super::biome_temperature::BiomeTemperatureSettings>,
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
let temperatures = (0..data.biome_names().len())
|
||||
.map(|i| {
|
||||
super::biome_temperature::BiomeTemperatureSettings::from_json(
|
||||
data.biome_json(BiomeId(i as u32)),
|
||||
)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(Some(Self {
|
||||
temperatures,
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Temperature settings of a biome.
|
||||
pub fn biome_temperature(
|
||||
&self,
|
||||
biome: BiomeId,
|
||||
) -> Option<super::biome_temperature::BiomeTemperatureSettings> {
|
||||
self.temperatures.get(biome.0 as usize).copied()
|
||||
}
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
# Block behaviours and ticking: parity status
|
||||
|
||||
Area: random and scheduled block ticks, growth, bone meal, TNT and
|
||||
explosions, hoppers, dispensers and droppers, comparators reading
|
||||
containers, weather-driven blocks. The library code lives in
|
||||
`crates/horizon-world/src/level/`. The client glue lives in
|
||||
`crates/horizon-client/src/game/` (`growth.rs`, `tnt.rs`, `explosion.rs`,
|
||||
`machines.rs`, `blockctl.rs`).
|
||||
|
||||
## Implemented (ported from the 26.3 sources)
|
||||
|
||||
- **Growth through live feature placement.** `worldgen/live.rs` decodes
|
||||
configured and placed features by name from the worldgen bundle. It shares
|
||||
the generator's `GeneratorData`. `level/feature_world.rs` runs features on
|
||||
the live level as a `FeatureWorld` and `PlacementContext`, and writes
|
||||
blocks through `Behaviours::set_block` with the feature's flags. Tree
|
||||
placement also calls `updateShapeAtEdge`.
|
||||
- **`TreeGrower.growTree`** (`level/growth.rs`) covers every vanilla grower:
|
||||
oak and its bee variants (with the flower check), spruce, birch, jungle,
|
||||
acacia, cherry, mangrove, azalea and poplar. It also covers the 2×2 forms:
|
||||
dark oak, pale oak, mega spruce and pine, and mega jungle. It keeps the
|
||||
random draw order: mega feature, then flowers, then feature. Saplings are
|
||||
removed with flags 818 and restored with flags 260 when the tree does not
|
||||
fit. Saplings, propagules and azaleas grow both on random ticks and with
|
||||
bone meal.
|
||||
- **Bone meal** (`level/bonemeal.rs`) ports `BoneMealItem.useOn`,
|
||||
`growCrop` and `growWaterPlant`, including coral from bone meal in warm
|
||||
ocean biomes. It also ports every vanilla `BonemealableBlock`:
|
||||
- saplings, propagules, mushrooms, fungi and azaleas
|
||||
- grass (with the biome's `getBoneMealFeatures`), nylium, netherrack and
|
||||
moss
|
||||
- rooted dirt, mangrove leaves, crops (including beetroot and torchflower
|
||||
increments) and stems
|
||||
- pitcher, bamboo and bamboo sapling, cocoa and sweet berries
|
||||
- tall grass and fern, tall flowers, bush and firefly bush, flower beds
|
||||
- kelp, twisting and weeping vines, cave vines (head and body), seagrass
|
||||
and sea pickles
|
||||
- big and small dripleaf, glow lichen (`MultifaceSpreader`), hanging moss
|
||||
and pale moss carpet
|
||||
- short and tall dry grass, and shelf mushroom
|
||||
|
||||
Level event 1505 plays the bone meal sound.
|
||||
- **Fixes to existing ticks.** Torchflower crops now mature into
|
||||
torchflowers. Kelp grows into any water block, as in vanilla.
|
||||
- **Primed TNT** (`game/tnt.rs`):
|
||||
- It has an 80-tick fuse, gravity 0.04, 0.98 drag and the 0.7/−0.5 ground
|
||||
bounce.
|
||||
- It explodes with power 4 at `y + 0.06125`.
|
||||
- It renders with the `TntRenderer` swell and a white flash every 5 ticks
|
||||
(entity overlay 4 in `entity.wgsl`).
|
||||
- TNT is primed by redstone, fire, flint and steel or fire charges
|
||||
(`TntBlock.useItemOn`), and by players breaking unstable TNT.
|
||||
- Explosions prime TNT with a random short fuse (chain reactions).
|
||||
- Dispensers prime TNT too.
|
||||
- **`ServerExplosion`** (`game/explosion.rs`):
|
||||
- It marches 1352 rays through a Java `HashSet<BlockPos>`
|
||||
(`java_hash_map`), so iteration and the `Util.shuffle` draws match
|
||||
vanilla.
|
||||
- Each block costs `max(block, fluid)` resistance.
|
||||
- Damage and knockback scale with exposure for the player, mobs, items
|
||||
and TNT. Creative players take no damage.
|
||||
- TNT explosions drop every block. Mob explosions use drop decay.
|
||||
- Drops merge in stacks of up to 16. Container contents spill.
|
||||
- **Hoppers** (`game/machines.rs`):
|
||||
- They push and pull through `HopperBlockEntity.tryMoveItems`.
|
||||
- The 8-tick cooldown applies, with the transfer cooldown hand-off between
|
||||
hoppers.
|
||||
- They insert into furnace faces (`WorldlyContainer` slots, fuel and
|
||||
bucket rules) and into double chests (right half first).
|
||||
- They respect `does_not_block_hoppers` and pick up item entities from the
|
||||
suck box.
|
||||
- The `enabled` property stops them.
|
||||
- **Dispensers and droppers.** They use `getRandomSlot` and the drop
|
||||
position and velocity from `DefaultDispenseItemBehavior.spawnItem`. The
|
||||
dispense behaviours are:
|
||||
- bone meal
|
||||
- TNT
|
||||
- flint and steel (fire, TNT, campfires and candles)
|
||||
- water and lava buckets (including waterlogging)
|
||||
- empty buckets (fluids, waterlogged blocks and powder snow)
|
||||
- arrows (power 1.1, uncertainty 6)
|
||||
|
||||
Droppers insert into containers. Clicks and failure sounds play.
|
||||
- **Comparators reading containers.** `GameLevel` answers
|
||||
`block_entity_analog_signal` with
|
||||
`AbstractContainerMenu.getRedstoneSignalFromContainer`. Chests blocked by
|
||||
a conductor read 0. Double chests are combined. Container changes from
|
||||
hoppers, dispensers and the player call `container_changed`, which runs
|
||||
`updateNeighbourForOutputSignal`.
|
||||
- **Weather** (`level/weather.rs`) uses biome temperatures from the worldgen
|
||||
bundle, with the height adjustment and frozen noise. They feed
|
||||
`ServerLevel.tickPrecipitation`: ice formation, snow accumulation, and
|
||||
cauldrons filling with water or powder snow. They also feed
|
||||
`Level.isRainingAt`, which drives farmland moisture and fire going out in
|
||||
rain.
|
||||
- **Day-timeline blocks** (`level/timeline.rs`):
|
||||
- Eyeblossoms open and close, and potted eyeblossoms follow. Neighbours are
|
||||
scheduled in the `BlockScanUtils` scan order.
|
||||
- Turtle eggs crack and hatch on sand, using the dawn hatch chance.
|
||||
- Dried ghasts hydrate while waterlogged.
|
||||
- **Landing writes.** Farmland trampling and turtle eggs crushed by landing
|
||||
now run neighbour and shape updates, so crops on trampled farmland pop.
|
||||
- **Smaller fixes.**
|
||||
- Hopper, dispenser and dropper block entities save with their own ids.
|
||||
Barrels and trapped chests do too.
|
||||
- Their screens use the vanilla hopper and dispenser layouts.
|
||||
- `GameLevel::max_y` is exclusive, as `LevelAccess` documents.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit tests in `crates/horizon-world/src/level/growth_tests.rs` cover:
|
||||
- every sapling kind, including the 2×2 trees
|
||||
- azalea and mangrove growth
|
||||
- random-tick stage advance followed by growth
|
||||
- grass bone meal with flowers
|
||||
- huge mushrooms and crimson fungi
|
||||
- crop ages, torchflowers, ferns and tall flowers
|
||||
- snow, ice and rain answers
|
||||
- eyeblossoms and turtle eggs
|
||||
|
||||
They need the feature block exports in `worldgen/blocks`
|
||||
(`block-properties.nbt`). The shared `.local` bundle lacks those files, so
|
||||
run the tests with `HORIZON_RESOURCES` pointing at a complete prepared
|
||||
bundle. Without one, the tests skip.
|
||||
- Client tests cover the Java `Vec3i` hash and compare order and the
|
||||
explosion stack merging.
|
||||
- In the game on the virtual screen, driven by `horizon-ctl`:
|
||||
- Bone meal on oak, birch, cherry, 2×2 dark oak, spruce and jungle
|
||||
saplings grew all of them.
|
||||
- Flint and steel on a TNT cluster: the TNT flashed white and chain
|
||||
exploded, leaving a crater with drops.
|
||||
- A redstone block primed TNT.
|
||||
- A chest drained through a hopper chain into a chest at 2.5 items/s. The
|
||||
comparator lit a lamp.
|
||||
- A dispenser bone-mealed a sapling into a tree. A dropper ejected an item.
|
||||
- Landing on farmland turned it to dirt and popped the wheat.
|
||||
- The hopper screen shows the vanilla layout.
|
||||
|
||||
New `horizon-ctl` commands drive these checks: `setblock`, `fill`,
|
||||
`getblock` and `container`.
|
||||
|
||||
## Known gaps
|
||||
|
||||
- **Random draws.**
|
||||
- Features placed from block behaviour draw from a copy of the level
|
||||
random. Their `next_world_*` draws and any draws in neighbour updates
|
||||
during placement do not reach the real stream.
|
||||
- Client sections that hold any non-air block get random ticks, not only
|
||||
sections with randomly ticking states. This advances the
|
||||
`getBlockRandomPos` generator more often than vanilla does.
|
||||
- **Explosion details.** Exposure uses full-collision blocks only.
|
||||
`getEntities` order is approximate. Experience orbs, falling blocks and
|
||||
arrows are not pushed.
|
||||
- **Missing entities.**
|
||||
- Dispensers have no behaviour for fire charges, other projectiles,
|
||||
armour, shulker boxes, boats, minecarts or spawn eggs. Fire charges and
|
||||
most other items drop instead; projectiles, boats, minecarts and spawn
|
||||
eggs are not entities in Horizon.
|
||||
- Turtle hatchlings and happy ghastlings are reported as `BlockEvent`s and
|
||||
not spawned.
|
||||
- Hoppers do not see minecart containers. Item entities do not trigger the
|
||||
hopper's `entityInside`; suction covers the same box on the hopper tick.
|
||||
- **Not implemented.** The sculk vibration system (sensors, shriekers,
|
||||
catalyst spread) and creaking hearts. Lightning (`tickThunder`).
|
||||
Particles for bone meal, explosions and TNT smoke.
|
||||
- **Not saved.** Primed TNT and hopper cooldowns (`TransferCooldown`).
|
||||
Reference in New Issue
Block a user