Block entities: tick only those with a ticker, in vanilla's order
World::block_entities keeps vanilla's Level.blockEntityTickers beside the map: a slot when a block entity whose state has a ticker is added, kept when it is replaced, freed when it is removed, unloaded or its state loses the ticker; a loaded chunk's in its block entity map's order. The tick visits that list once, in block-ticking chunks within the world border, instead of scanning the whole map once per kind. New harness block_entity_tickers: real LevelChunks of a server level against BlockEntities. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,99 @@
|
||||
//! The Rust side of tools/test_block_entity_tickers_parity.py: the ops of
|
||||
//! `VanillaBlockEntityTickerOracle` on `BlockEntities`, as `World` drives it
|
||||
//! (a state write calls `state_changed`), printing the tick order.
|
||||
use horizon_client::{
|
||||
block_entities::{BlockEntities, Pos, Ticking},
|
||||
containers::BlockEntity,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// State ids of the fixture: 0 air, 1 a block whose block entity ticks, 2 a
|
||||
/// jukebox without a record, 3 a block entity that never ticks (a chest).
|
||||
fn state(name: &str) -> u32 {
|
||||
match name {
|
||||
"chest" | "barrel" => 3,
|
||||
"jukebox" => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn entity(name: &str) -> BlockEntity {
|
||||
if name.starts_with("jukebox") {
|
||||
// The game makes a jukebox's block entity when a record goes in.
|
||||
return BlockEntity::Jukebox(Default::default());
|
||||
}
|
||||
BlockEntity::for_block(&format!("minecraft:{name}"))
|
||||
.unwrap_or_else(|| panic!("no block entity for {name}"))
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let input = std::fs::read_to_string(&args[1]).expect("input");
|
||||
let mut out = String::new();
|
||||
let mut entities = BlockEntities::default();
|
||||
let mut states: HashMap<Pos, u32> = HashMap::new();
|
||||
let mut kinds: HashMap<Pos, String> = HashMap::new();
|
||||
let table = vec![Ticking::No, Ticking::Yes, Ticking::Idle, Ticking::No];
|
||||
for line in input.lines() {
|
||||
let w: Vec<&str> = line.split_whitespace().collect();
|
||||
let pos = |i: usize| -> Pos {
|
||||
let n = |j: usize| w[i + j].parse::<i32>().expect("coordinate");
|
||||
(n(0), n(1), n(2))
|
||||
};
|
||||
match w[0] {
|
||||
"reset" => {
|
||||
entities = BlockEntities::default();
|
||||
entities.set_states(table.clone());
|
||||
states.clear();
|
||||
kinds.clear();
|
||||
}
|
||||
"load" => {
|
||||
let mut chunk = Vec::new();
|
||||
for i in (3..w.len()).step_by(4) {
|
||||
let p = pos(i + 1);
|
||||
states.insert(p, state(w[i]));
|
||||
kinds.insert(p, w[i].to_owned());
|
||||
chunk.push((p, entity(w[i])));
|
||||
}
|
||||
entities.load_chunk(chunk);
|
||||
}
|
||||
"place" => {
|
||||
let p = pos(2);
|
||||
// World::set, then the game adds the block entity.
|
||||
let old = states.insert(p, state(w[1])).unwrap_or(0);
|
||||
kinds.insert(p, w[1].to_owned());
|
||||
entities.state_changed(p, old, state(w[1]));
|
||||
entities.insert(p, entity(w[1]));
|
||||
}
|
||||
"replace" => {
|
||||
let p = pos(1);
|
||||
entities.insert(p, entity(&kinds[&p]));
|
||||
}
|
||||
"remove" => {
|
||||
let p = pos(1);
|
||||
entities.remove(&p);
|
||||
let old = states.insert(p, 0).unwrap_or(0);
|
||||
entities.state_changed(p, old, 0);
|
||||
}
|
||||
"record" => {
|
||||
let p = pos(1);
|
||||
let s = if w[4] == "1" { 1 } else { 2 };
|
||||
let old = states.insert(p, s).unwrap_or(0);
|
||||
entities.state_changed(p, old, s);
|
||||
}
|
||||
"unload" => {
|
||||
let c = (w[1].parse::<i32>().unwrap(), w[2].parse::<i32>().unwrap());
|
||||
entities.retain(|p, _| (p.0 >> 4, p.2 >> 4) != c);
|
||||
}
|
||||
"tick" => {
|
||||
out.push_str("tick");
|
||||
for (p, _) in entities.tickers(|p| states.get(&p).copied().unwrap_or(0)) {
|
||||
out.push_str(&format!(" {},{},{}", p.0, p.1, p.2));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
other => panic!("unknown op {other}"),
|
||||
}
|
||||
}
|
||||
std::fs::write(&args[2], out).expect("output");
|
||||
}
|
||||
@@ -0,0 +1,374 @@
|
||||
//! The world's block entities and the order they tick in: vanilla's
|
||||
//! `Level.blockEntityTickers`, kept beside the block entity map so a tick
|
||||
//! visits only the block entities that tick, in vanilla's order, instead of
|
||||
//! scanning the whole map once per kind.
|
||||
//!
|
||||
//! The list follows `LevelChunk.updateBlockEntityTicker` and
|
||||
//! `Level.tickBlockEntities`:
|
||||
//! - a block entity whose block state has a ticker gets a slot at the end of
|
||||
//! the list (through `pendingBlockEntityTickers`, so a slot made during a
|
||||
//! tick first ticks on the next one);
|
||||
//! - replacing the block entity at a position (`setBlockEntity`), or changing
|
||||
//! its block state to another state with a ticker, keeps its slot
|
||||
//! (`RebindableTickingBlockEntityWrapper.rebind`);
|
||||
//! - removing it (`removeBlockEntity`), unloading its chunk
|
||||
//! (`clearAllBlockEntities`) or changing its state to one without a ticker
|
||||
//! (a jukebox losing its record) frees the slot; a later ticker there is
|
||||
//! appended again;
|
||||
//! - a loaded chunk's block entities are added in the iteration order of its
|
||||
//! `Object2ObjectOpenHashMap<BlockPos, BlockEntity>`
|
||||
//! (`registerAllBlockEntitiesAfterLevelLoad`), filled in the order the chunk
|
||||
//! listed them.
|
||||
//!
|
||||
//! Which states tick is a table by state id, built by the game from the block
|
||||
//! registry; whether a slot is made is decided when the slot is promoted at
|
||||
//! the start of the next tick, from the block state then.
|
||||
use crate::containers::BlockEntity;
|
||||
use crate::fast_hash::FxHashMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub type Pos = (i32, i32, i32);
|
||||
|
||||
/// What a block state's block entity does each tick (`BlockState.getTicker`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum Ticking {
|
||||
/// No ticker, and the block has no block entity that could have one.
|
||||
#[default]
|
||||
No,
|
||||
/// A ticker.
|
||||
Yes,
|
||||
/// The block's block entity, but this state has no ticker (a jukebox
|
||||
/// without a record): a state change to it frees the slot.
|
||||
Idle,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct BlockEntities {
|
||||
map: HashMap<Pos, BlockEntity>,
|
||||
/// `Level.blockEntityTickers`: positions and the slot each was given.
|
||||
tickers: Vec<(Pos, u32)>,
|
||||
/// `LevelChunk.tickersInLevel`: the live slot of each ticking position.
|
||||
live: FxHashMap<Pos, u32>,
|
||||
/// Positions that may need a slot, in the order vanilla would have made
|
||||
/// it (`pendingBlockEntityTickers`), each with a token; decided at the
|
||||
/// next promotion from the block state then.
|
||||
added: Vec<(Pos, u32)>,
|
||||
/// The token of each position's pending entry: an entry whose token is
|
||||
/// not here any more was cancelled.
|
||||
pending: FxHashMap<Pos, u32>,
|
||||
next_slot: u32,
|
||||
/// `Ticking` by block state id; empty until the game builds it.
|
||||
states: Vec<Ticking>,
|
||||
}
|
||||
|
||||
impl std::ops::Deref for BlockEntities {
|
||||
type Target = HashMap<Pos, BlockEntity>;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> IntoIterator for &'a BlockEntities {
|
||||
type Item = (&'a Pos, &'a BlockEntity);
|
||||
type IntoIter = std::collections::hash_map::Iter<'a, Pos, BlockEntity>;
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.map.iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// `Vec3i.hashCode`.
|
||||
fn java_hash((x, y, z): Pos) -> i32 {
|
||||
y.wrapping_add(z.wrapping_mul(31))
|
||||
.wrapping_mul(31)
|
||||
.wrapping_add(x)
|
||||
}
|
||||
/// `HashCommon.mix`.
|
||||
fn mix(x: i32) -> usize {
|
||||
let h = (x as u32).wrapping_mul(0x9E37_79B9);
|
||||
(h ^ (h >> 16)) as usize
|
||||
}
|
||||
|
||||
/// The order `values().forEach` visits a `new Object2ObjectOpenHashMap<>()`
|
||||
/// keyed by these positions, put in this order (repeats keep their first
|
||||
/// slot): open addressing with linear probing, a rehash to twice the size
|
||||
/// past three quarters full, and iteration from the last slot down.
|
||||
pub fn chunk_map_order(positions: impl IntoIterator<Item = Pos>) -> Vec<Pos> {
|
||||
// HashCommon.arraySize(16, .75f), and maxFill of each size.
|
||||
let mut slots: Vec<Option<Pos>> = vec![None; 32];
|
||||
let max_fill = |n: usize| (n * 3).div_ceil(4).min(n - 1);
|
||||
let mut size = 0;
|
||||
for p in positions {
|
||||
let mask = slots.len() - 1;
|
||||
let mut at = mix(java_hash(p)) & mask;
|
||||
let mut known = false;
|
||||
while let Some(k) = slots[at] {
|
||||
if k == p {
|
||||
known = true;
|
||||
break;
|
||||
}
|
||||
at = (at + 1) & mask;
|
||||
}
|
||||
if known {
|
||||
continue;
|
||||
}
|
||||
slots[at] = Some(p);
|
||||
// `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`, which
|
||||
// puts the keys back from the last slot down.
|
||||
size += 1;
|
||||
if size > max_fill(slots.len()) {
|
||||
let n = ((size + 1) * 4).div_ceil(3).next_power_of_two();
|
||||
let old = std::mem::replace(&mut slots, vec![None; n]);
|
||||
for k in old.into_iter().rev().flatten() {
|
||||
let mut at = mix(java_hash(k)) & (n - 1);
|
||||
while slots[at].is_some() {
|
||||
at = (at + 1) & (n - 1);
|
||||
}
|
||||
slots[at] = Some(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
slots.into_iter().rev().flatten().collect()
|
||||
}
|
||||
|
||||
impl BlockEntities {
|
||||
/// Whether the ticking table has been built.
|
||||
pub fn has_states(&self) -> bool {
|
||||
!self.states.is_empty()
|
||||
}
|
||||
pub fn set_states(&mut self, states: Vec<Ticking>) {
|
||||
self.states = states;
|
||||
}
|
||||
pub fn take_states(&mut self) -> Vec<Ticking> {
|
||||
std::mem::take(&mut self.states)
|
||||
}
|
||||
pub fn ticking(&self, state: u32) -> Ticking {
|
||||
self.states.get(state as usize).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> u32 {
|
||||
let n = self.next_slot;
|
||||
self.next_slot = n.wrapping_add(1);
|
||||
n
|
||||
}
|
||||
/// A ticker may be made for `pos` now (`updateBlockEntityTicker`).
|
||||
fn add(&mut self, pos: Pos) {
|
||||
let token = self.next();
|
||||
self.pending.insert(pos, token);
|
||||
self.added.push((pos, token));
|
||||
}
|
||||
/// `removeBlockEntityTicker`: no slot, made or pending.
|
||||
fn cancel(&mut self, pos: &Pos) {
|
||||
self.live.remove(pos);
|
||||
self.pending.remove(pos);
|
||||
}
|
||||
|
||||
pub fn get_mut(&mut self, pos: &Pos) -> Option<&mut BlockEntity> {
|
||||
self.map.get_mut(pos)
|
||||
}
|
||||
pub fn iter_mut(&mut self) -> impl Iterator<Item = (&Pos, &mut BlockEntity)> {
|
||||
self.map.iter_mut()
|
||||
}
|
||||
pub fn values_mut(&mut self) -> impl Iterator<Item = &mut BlockEntity> {
|
||||
self.map.values_mut()
|
||||
}
|
||||
/// `LevelChunk.setBlockEntity` (+ `addAndRegisterBlockEntity`): a new
|
||||
/// block entity may get a slot; one replacing another keeps its slot.
|
||||
pub fn insert(&mut self, pos: Pos, entity: BlockEntity) -> Option<BlockEntity> {
|
||||
let old = self.map.insert(pos, entity);
|
||||
if old.is_none() {
|
||||
self.add(pos);
|
||||
}
|
||||
old
|
||||
}
|
||||
/// The block entity at `pos`, made by `make` when there is none.
|
||||
pub fn get_or_insert_with(
|
||||
&mut self,
|
||||
pos: Pos,
|
||||
make: impl FnOnce() -> BlockEntity,
|
||||
) -> &mut BlockEntity {
|
||||
if !self.map.contains_key(&pos) {
|
||||
self.add(pos);
|
||||
}
|
||||
self.map.entry(pos).or_insert_with(make)
|
||||
}
|
||||
/// `LevelChunk.removeBlockEntity`: the block entity and its slot.
|
||||
pub fn remove(&mut self, pos: &Pos) -> Option<BlockEntity> {
|
||||
self.cancel(pos);
|
||||
self.map.remove(pos)
|
||||
}
|
||||
/// The block entity at `pos`, out of the map for a while: its slot stays
|
||||
/// for `put` to bring it back (a tick working on it).
|
||||
pub fn take(&mut self, pos: &Pos) -> Option<BlockEntity> {
|
||||
self.map.remove(pos)
|
||||
}
|
||||
/// Brings back what `take` took, in its slot.
|
||||
pub fn put(&mut self, pos: Pos, entity: BlockEntity) {
|
||||
if self.map.insert(pos, entity).is_none()
|
||||
&& !self.live.contains_key(&pos)
|
||||
&& !self.pending.contains_key(&pos)
|
||||
{
|
||||
self.add(pos);
|
||||
}
|
||||
}
|
||||
/// Removes the block entities `keep` refuses, and their slots
|
||||
/// (`clearAllBlockEntities` of unloaded chunks).
|
||||
pub fn retain(&mut self, mut keep: impl FnMut(&Pos, &mut BlockEntity) -> bool) {
|
||||
let (live, pending) = (&mut self.live, &mut self.pending);
|
||||
self.map.retain(|p, e| {
|
||||
let kept = keep(p, e);
|
||||
if !kept {
|
||||
live.remove(p);
|
||||
pending.remove(p);
|
||||
}
|
||||
kept
|
||||
});
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.map.clear();
|
||||
self.tickers.clear();
|
||||
self.live.clear();
|
||||
self.added.clear();
|
||||
self.pending.clear();
|
||||
}
|
||||
/// A loaded or generated chunk's block entities, in the order the chunk
|
||||
/// lists them; they tick in its block entity map's order
|
||||
/// (`registerAllBlockEntitiesAfterLevelLoad`).
|
||||
pub fn load_chunk(&mut self, entities: Vec<(Pos, BlockEntity)>) {
|
||||
let order = chunk_map_order(entities.iter().map(|(p, _)| *p));
|
||||
for (p, e) in entities {
|
||||
self.map.insert(p, e);
|
||||
}
|
||||
for p in order {
|
||||
self.add(p);
|
||||
}
|
||||
}
|
||||
/// `LevelChunk.setBlockState` on a block entity's position, from state
|
||||
/// `old` to `new`: a ticker made, kept or dropped.
|
||||
pub fn state_changed(&mut self, pos: Pos, old: u32, new: u32) {
|
||||
if self.states.is_empty() || !self.map.contains_key(&pos) {
|
||||
return;
|
||||
}
|
||||
match self.ticking(new) {
|
||||
// A new ticker, unless one was made or is pending (rebound).
|
||||
Ticking::Yes => {
|
||||
if self.ticking(old) != Ticking::Yes && !self.live.contains_key(&pos) {
|
||||
self.add(pos);
|
||||
}
|
||||
}
|
||||
Ticking::Idle => self.cancel(&pos),
|
||||
// Another block: the game removes or replaces the block entity.
|
||||
Ticking::No => {}
|
||||
}
|
||||
}
|
||||
/// The start of `Level.tickBlockEntities`: pending slots join the list
|
||||
/// and freed ones leave it. `state` reads the block state at a position.
|
||||
/// Returns the slots to tick, in order; check each with `is_live` before
|
||||
/// ticking it, as the ticks before it can free it.
|
||||
pub fn tickers(&mut self, state: impl Fn(Pos) -> u32) -> Vec<(Pos, u32)> {
|
||||
for (pos, token) in std::mem::take(&mut self.added) {
|
||||
if self.pending.get(&pos) != Some(&token) {
|
||||
continue;
|
||||
}
|
||||
self.pending.remove(&pos);
|
||||
if self.live.contains_key(&pos)
|
||||
|| !self.map.contains_key(&pos)
|
||||
|| self.ticking(state(pos)) != Ticking::Yes
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let slot = self.next();
|
||||
self.live.insert(pos, slot);
|
||||
self.tickers.push((pos, slot));
|
||||
}
|
||||
let (live, map) = (&mut self.live, &self.map);
|
||||
self.tickers.retain(|(p, slot)| {
|
||||
let mine = live.get(p) == Some(slot);
|
||||
if mine && !map.contains_key(p) {
|
||||
live.remove(p);
|
||||
}
|
||||
mine && map.contains_key(p)
|
||||
});
|
||||
self.tickers.clone()
|
||||
}
|
||||
/// Whether a slot from `tickers` still ticks.
|
||||
pub fn is_live(&self, (pos, slot): (Pos, u32)) -> bool {
|
||||
self.live.get(&pos) == Some(&slot) && self.map.contains_key(&pos)
|
||||
}
|
||||
/// Frees the slot at `pos` (the block entity stays).
|
||||
pub fn forget(&mut self, pos: &Pos) {
|
||||
self.cancel(pos);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn hopper() -> BlockEntity {
|
||||
BlockEntity::Chest(vec![None; 5])
|
||||
}
|
||||
/// States: 0 air, 1 ticks, 2 idle.
|
||||
fn level() -> BlockEntities {
|
||||
let mut b = BlockEntities::default();
|
||||
b.set_states(vec![Ticking::No, Ticking::Yes, Ticking::Idle]);
|
||||
b
|
||||
}
|
||||
fn order(b: &mut BlockEntities, states: &HashMap<Pos, u32>) -> Vec<Pos> {
|
||||
b.tickers(|p| states.get(&p).copied().unwrap_or(0))
|
||||
.into_iter()
|
||||
.map(|(p, _)| p)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slots_follow_vanilla_lifecycle() {
|
||||
let mut b = level();
|
||||
let mut s = HashMap::new();
|
||||
for p in [(0, 0, 0), (1, 0, 0), (2, 0, 0)] {
|
||||
s.insert(p, 1);
|
||||
b.insert(p, hopper());
|
||||
}
|
||||
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]);
|
||||
// Replacing keeps the slot; removing and placing again appends.
|
||||
b.insert((0, 0, 0), hopper());
|
||||
b.remove(&(1, 0, 0));
|
||||
b.insert((1, 0, 0), hopper());
|
||||
assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]);
|
||||
// Take and put keep it; an idle state frees it, ticking again appends.
|
||||
let e = b.take(&(0, 0, 0)).unwrap();
|
||||
b.put((0, 0, 0), e);
|
||||
assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]);
|
||||
s.insert((2, 0, 0), 2);
|
||||
b.state_changed((2, 0, 0), 1, 2);
|
||||
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0)]);
|
||||
s.insert((2, 0, 0), 1);
|
||||
b.state_changed((2, 0, 0), 2, 1);
|
||||
assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]);
|
||||
// A slot freed during a tick is not live any more.
|
||||
let slots = b.tickers(|p| s.get(&p).copied().unwrap_or(0));
|
||||
b.retain(|p, _| *p != (1, 0, 0));
|
||||
assert!(b.is_live(slots[0]) && !b.is_live(slots[1]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_loads_in_open_hash_map_order() {
|
||||
// A few keys: their mixed hashes over 32 slots, read from the top.
|
||||
let positions = [
|
||||
(0, 64, 0),
|
||||
(1, 64, 0),
|
||||
(0, 64, 1),
|
||||
(15, -64, 15),
|
||||
(3, 70, 9),
|
||||
];
|
||||
let slot = |p: &Pos| mix(java_hash(*p)) & 31;
|
||||
let mut expected = positions.to_vec();
|
||||
expected.sort_by_key(|p| std::cmp::Reverse(slot(p)));
|
||||
let distinct: std::collections::HashSet<usize> = positions.iter().map(slot).collect();
|
||||
assert_eq!(distinct.len(), positions.len());
|
||||
assert_eq!(chunk_map_order(positions), expected);
|
||||
// Past 24 keys the table doubles; every key stays, once.
|
||||
let many: Vec<Pos> = (0..100).map(|i| (i % 16, i / 16, 3)).collect();
|
||||
let order = chunk_map_order(many.iter().copied().chain(many.iter().copied()));
|
||||
assert_eq!(order.len(), 100);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ mod banners;
|
||||
mod beacon;
|
||||
mod beehives;
|
||||
mod block_entity_anims;
|
||||
mod block_entity_ticks;
|
||||
mod block_items;
|
||||
mod blockctl;
|
||||
mod boats;
|
||||
@@ -2196,13 +2197,13 @@ impl Game<'_> {
|
||||
self.audio
|
||||
.play("minecraft:block.ender_chest.open", Some(at), 0.5, pitch);
|
||||
} else if &*name == "minecraft:beacon" && self.open_station(pos, &name) {
|
||||
self.world.block_entities.entry(key).or_insert_with(|| {
|
||||
self.world.block_entities.get_or_insert_with(key, || {
|
||||
BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new()))
|
||||
});
|
||||
} else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) {
|
||||
// ShulkerBoxBlock.canOpen: the lid has no room; nothing opens.
|
||||
} else if let Some(entity) = BlockEntity::for_block(&name) {
|
||||
self.world.block_entities.entry(key).or_insert(entity);
|
||||
self.world.block_entities.get_or_insert_with(key, || entity);
|
||||
let centre = [
|
||||
f64::from(key.0) + 0.5,
|
||||
f64::from(key.1) + 0.5,
|
||||
@@ -6087,38 +6088,6 @@ impl Game<'_> {
|
||||
false,
|
||||
)
|
||||
}
|
||||
fn tick_block_entities(&mut self) -> Result<()> {
|
||||
self.tick_hoppers()?;
|
||||
self.tick_crafters();
|
||||
self.tick_mount_menu();
|
||||
self.tick_jukeboxes();
|
||||
self.tick_beacons();
|
||||
self.tick_creaking_hearts()?;
|
||||
self.tick_spawners()?;
|
||||
self.tick_trial_spawners()?;
|
||||
self.tick_vaults()?;
|
||||
self.tick_beehives();
|
||||
let mut lit_changes = Vec::new();
|
||||
for (pos, entity) in self.world.block_entities.iter_mut() {
|
||||
if let BlockEntity::Furnace(f) = entity
|
||||
&& let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers)
|
||||
{
|
||||
lit_changes.push((*pos, lit));
|
||||
}
|
||||
}
|
||||
for ((x, y, z), lit) in lit_changes {
|
||||
let state = self.world.block(x, y, z);
|
||||
if let Some(mut s) = self.pack.assets.registry.state(state).cloned()
|
||||
&& s.properties.contains_key("lit")
|
||||
{
|
||||
s.properties.insert("lit".into(), lit.to_string());
|
||||
if let Ok(id) = self.pack.assets.registry.resolve(&s) {
|
||||
self.world.set(x, y, z, id)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Copies of a save batch carrying its live block entities and save data.
|
||||
fn with_entities<'a>(
|
||||
&self,
|
||||
|
||||
@@ -105,24 +105,13 @@ impl Game<'_> {
|
||||
.find(|&y| !self.res.facts.is_air(self.world.block(x, y, z)))
|
||||
.map_or(min, |y| y + 1)
|
||||
}
|
||||
/// `BeaconBlockEntity.tick` for every beacon.
|
||||
pub(super) fn tick_beacons(&mut self) {
|
||||
let keys: Vec<(i32, i32, i32)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Beacon(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.remove(&key) else {
|
||||
continue;
|
||||
};
|
||||
self.tick_beacon(key, &mut b);
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Beacon(b));
|
||||
}
|
||||
/// `BeaconBlockEntity.tick` of the beacon at `key`.
|
||||
pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) {
|
||||
let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else {
|
||||
return;
|
||||
};
|
||||
self.tick_beacon(key, &mut b);
|
||||
self.world.block_entities.put(key, BlockEntity::Beacon(b));
|
||||
}
|
||||
fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon) {
|
||||
let mut check = if b.last_check_y < y {
|
||||
|
||||
@@ -87,48 +87,37 @@ impl Game<'_> {
|
||||
let facing = beehive::facing_step(props.get("facing").map(String::as_str));
|
||||
Some((honey, facing))
|
||||
}
|
||||
/// `BeehiveBlockEntity.serverTick` for every hive, after an emergency
|
||||
/// exit for those with fire beside them (`BeehiveBlock.updateShape`).
|
||||
pub(super) fn tick_beehives(&mut self) {
|
||||
let mut keys: Vec<(i32, i32, i32)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Beehive(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
keys.sort_unstable();
|
||||
for key in keys {
|
||||
let at = [key.0, key.1, key.2];
|
||||
let Some((honey, facing)) = self.hive_state(at) else {
|
||||
continue;
|
||||
};
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let fire = [
|
||||
[1, 0, 0],
|
||||
[-1, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, -1, 0],
|
||||
[0, 0, 1],
|
||||
[0, 0, -1],
|
||||
]
|
||||
.iter()
|
||||
.any(|d| {
|
||||
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
|
||||
&*self.res.facts.get(state).name == "minecraft:fire"
|
||||
});
|
||||
let mut host = GameHive { game: self };
|
||||
if fire && !hive.bees.is_empty() {
|
||||
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
|
||||
}
|
||||
hive.server_tick(at, facing, honey, &mut host);
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Beehive(hive));
|
||||
/// `BeehiveBlockEntity.serverTick` of the hive at `key`, after an
|
||||
/// emergency exit if fire is beside it (`BeehiveBlock.updateShape`).
|
||||
pub(super) fn tick_beehive(&mut self, key: (i32, i32, i32)) {
|
||||
let at = [key.0, key.1, key.2];
|
||||
let Some((honey, facing)) = self.hive_state(at) else {
|
||||
return;
|
||||
};
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
|
||||
return;
|
||||
};
|
||||
let fire = [
|
||||
[1, 0, 0],
|
||||
[-1, 0, 0],
|
||||
[0, 1, 0],
|
||||
[0, -1, 0],
|
||||
[0, 0, 1],
|
||||
[0, 0, -1],
|
||||
]
|
||||
.iter()
|
||||
.any(|d| {
|
||||
let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]);
|
||||
&*self.res.facts.get(state).name == "minecraft:fire"
|
||||
});
|
||||
let mut host = GameHive { game: self };
|
||||
if fire && !hive.bees.is_empty() {
|
||||
hive.release_all(at, facing, honey, Release::Emergency, &mut host);
|
||||
}
|
||||
hive.server_tick(at, facing, honey, &mut host);
|
||||
self.world
|
||||
.block_entities
|
||||
.put(key, BlockEntity::Beehive(hive));
|
||||
}
|
||||
/// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal`
|
||||
/// sent in: off its lead, its tag stored, the bee gone.
|
||||
@@ -152,13 +141,13 @@ impl Game<'_> {
|
||||
self.mobs[i].extra.mount = None;
|
||||
let tag = self.mob_tree_nbt(i);
|
||||
let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower);
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
|
||||
return;
|
||||
};
|
||||
let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self });
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Beehive(hive));
|
||||
.put(key, BlockEntity::Beehive(hive));
|
||||
if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) {
|
||||
m.removed = true;
|
||||
}
|
||||
@@ -166,13 +155,13 @@ impl Game<'_> {
|
||||
/// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about.
|
||||
pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) {
|
||||
let key = (at[0], at[1], at[2]);
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else {
|
||||
let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else {
|
||||
return;
|
||||
};
|
||||
hive.release_all(at, facing, None, status, &mut GameHive { game: self });
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Beehive(hive));
|
||||
.put(key, BlockEntity::Beehive(hive));
|
||||
}
|
||||
/// `BeehiveBlock.playerDestroy` without silk touch: the bees come out
|
||||
/// angry at the player unless smoke calms them, then
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
//! `Level.tickBlockEntities` for the block entities ticked together here
|
||||
//! (hoppers, crafters, jukeboxes, beacons, creaking hearts, spawners, trial
|
||||
//! spawners, vaults, beehives and furnaces): only those whose state has a
|
||||
//! ticker, in vanilla's list order (`horizon_client::block_entities`), in
|
||||
//! chunks that tick blocks. Sculk, brewing stands and pistons tick in their
|
||||
//! own passes.
|
||||
use super::Game;
|
||||
use horizon_client::{
|
||||
Result,
|
||||
block_entities::{Pos, Ticking},
|
||||
containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS},
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
|
||||
impl Game<'_> {
|
||||
pub(super) fn tick_block_entities(&mut self) -> Result<()> {
|
||||
self.tick_mount_menu();
|
||||
self.load_entity_types();
|
||||
if !self.world.block_entities.has_states() {
|
||||
let states = self.ticking_states();
|
||||
self.world.block_entities.set_states(states);
|
||||
}
|
||||
self.forget_gone_hoppers();
|
||||
let ticking = self.block_ticking_area();
|
||||
let mut spawners = Vec::new();
|
||||
let mut trial_spawners = Vec::new();
|
||||
for slot in self.world.block_entity_tickers() {
|
||||
let pos = slot.0;
|
||||
// Ticks before this one can remove it (`TickingBlockEntity.isRemoved`).
|
||||
if !self.world.block_entities.is_live(slot)
|
||||
|| !ticking(pos.0, pos.2)
|
||||
|| !self.border.contains(f64::from(pos.0), f64::from(pos.2))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match self.world.block_entities.get(&pos) {
|
||||
Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS => {
|
||||
self.tick_hopper(pos)
|
||||
}
|
||||
Some(BlockEntity::Crafter(_)) => self.tick_crafter(pos),
|
||||
Some(BlockEntity::Jukebox(_)) => self.tick_jukebox(pos),
|
||||
Some(BlockEntity::Beacon(_)) => self.tick_beacon_at(pos),
|
||||
Some(BlockEntity::CreakingHeart(_)) => self.tick_creaking_heart(pos)?,
|
||||
Some(BlockEntity::Spawner(_)) => {
|
||||
self.tick_spawner(pos)?;
|
||||
spawners.push(pos);
|
||||
}
|
||||
Some(BlockEntity::TrialSpawner(_)) => {
|
||||
self.tick_trial_spawner(pos)?;
|
||||
trial_spawners.push(pos);
|
||||
}
|
||||
Some(BlockEntity::Vault(_)) => self.tick_vault(pos)?,
|
||||
Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos),
|
||||
Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.update_song_volumes();
|
||||
self.scan_for_hearts();
|
||||
self.client_tick_spawners(&spawners);
|
||||
for key in trial_spawners {
|
||||
self.client_tick_trial_spawner(key);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// `BlockState.getTicker` of every state, for the block entities ticked
|
||||
/// here. A creaking heart keeps its slot while uprooted (see
|
||||
/// `tick_creaking_heart`).
|
||||
fn ticking_states(&self) -> Vec<Ticking> {
|
||||
let registry = self.pack.assets.registry;
|
||||
(0..registry.len())
|
||||
.map(|i| {
|
||||
let state = BlockStateId(i as u32);
|
||||
let name: &str = &self.res.facts.get(state).name;
|
||||
match name {
|
||||
"minecraft:hopper"
|
||||
| "minecraft:crafter"
|
||||
| "minecraft:beacon"
|
||||
| "minecraft:creaking_heart"
|
||||
| "minecraft:spawner"
|
||||
| "minecraft:trial_spawner"
|
||||
| "minecraft:vault"
|
||||
| "minecraft:beehive"
|
||||
| "minecraft:bee_nest" => Ticking::Yes,
|
||||
"minecraft:jukebox" => {
|
||||
let record = registry
|
||||
.state(state)
|
||||
.and_then(|s| s.properties.get("has_record"))
|
||||
.is_some_and(|v| v == "true");
|
||||
if record { Ticking::Yes } else { Ticking::Idle }
|
||||
}
|
||||
n if FurnaceKind::from_block(n).is_some() => Ticking::Yes,
|
||||
_ => Ticking::No,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// `ServerLevel.shouldTickBlocksAt`: chunks within the simulation
|
||||
/// distance plus one (`DistanceManager.inBlockTickingRange`, Chebyshev
|
||||
/// in chunks) of the player or a guest. With nobody there, a dedicated
|
||||
/// server ticks none; the game alone (no player yet, headless fixtures)
|
||||
/// ticks every chunk.
|
||||
fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
|
||||
let d = self.settings.simulation_distance.max(2) + 1;
|
||||
let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect();
|
||||
if let Some(p) = &self.player {
|
||||
centres.push((
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
));
|
||||
}
|
||||
let everywhere = centres.is_empty() && self.options.dedicated.is_none();
|
||||
move |x, z| {
|
||||
everywhere
|
||||
|| centres
|
||||
.iter()
|
||||
.any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d)
|
||||
}
|
||||
}
|
||||
/// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and
|
||||
/// its block's `lit` following it.
|
||||
fn tick_furnace(&mut self, pos: Pos) -> Result<()> {
|
||||
let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) else {
|
||||
return Ok(());
|
||||
};
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
if let Some(mut s) = self.pack.assets.registry.state(state).cloned()
|
||||
&& s.properties.contains_key("lit")
|
||||
{
|
||||
s.properties.insert("lit".into(), lit.to_string());
|
||||
if let Ok(id) = self.pack.assets.registry.resolve(&s) {
|
||||
self.world.set(pos.0, pos.1, pos.2, id)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -598,13 +598,13 @@ impl Game<'_> {
|
||||
if let Ok(id) = registry.resolve(&wanted)
|
||||
&& wanted != *current
|
||||
{
|
||||
let entity = self.world.block_entities.remove(&pos);
|
||||
let entity = self.world.block_entities.take(&pos);
|
||||
let at = BlockPos::new(pos.0, pos.1, pos.2);
|
||||
self.with_level(|b, level, ticks| {
|
||||
b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS)
|
||||
});
|
||||
if let Some(entity) = entity {
|
||||
self.world.block_entities.insert(pos, entity);
|
||||
self.world.block_entities.put(pos, entity);
|
||||
}
|
||||
let _ = self.process_level_events();
|
||||
}
|
||||
|
||||
@@ -164,7 +164,7 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
let key = (home[0], home[1], home[2]);
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -173,7 +173,7 @@ impl Game<'_> {
|
||||
});
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
.put(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
/// `Creaking.tearDown`: the crumble particles.
|
||||
pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) {
|
||||
@@ -220,7 +220,7 @@ impl Game<'_> {
|
||||
/// death and a natural heart drops experience.
|
||||
pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) {
|
||||
let key = (pos[0], pos[1], pos[2]);
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key)
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
@@ -248,43 +248,35 @@ impl Game<'_> {
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
.put(key, BlockEntity::CreakingHeart(heart));
|
||||
}
|
||||
/// `CreakingHeartBlockEntity.serverTick` for every heart.
|
||||
pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) =
|
||||
self.world.block_entities.remove(&key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
|
||||
// The block is gone: preRemoveSideEffects.
|
||||
self.with_heart(key, &mut heart, |h, _, _, host, out| {
|
||||
creaking_heart::remove_protector(h, host, false, out);
|
||||
})?;
|
||||
continue;
|
||||
}
|
||||
// getTicker: none once uprooted.
|
||||
if self.heart_state_name(state) != "uprooted" {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
self.with_heart(key, &mut heart, |h, w, lr, host, out| {
|
||||
creaking_heart::server_tick(h, pos, w, lr, host, out);
|
||||
})?;
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::CreakingHeart(heart));
|
||||
/// `CreakingHeartBlockEntity.serverTick` of the heart at `key`. Its slot
|
||||
/// stays while uprooted, so that a heart whose block went away is still
|
||||
/// found here and lets go of its protector.
|
||||
pub(super) fn tick_creaking_heart(&mut self, key: Pos) -> Result<()> {
|
||||
let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:creaking_heart" {
|
||||
// The block is gone: preRemoveSideEffects.
|
||||
self.world.block_entities.forget(&key);
|
||||
self.with_heart(key, &mut heart, |h, _, _, host, out| {
|
||||
creaking_heart::remove_protector(h, host, false, out);
|
||||
})?;
|
||||
return Ok(());
|
||||
}
|
||||
self.scan_for_hearts();
|
||||
// getTicker: none once uprooted.
|
||||
if self.heart_state_name(state) != "uprooted" {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
self.with_heart(key, &mut heart, |h, w, lr, host, out| {
|
||||
creaking_heart::server_tick(h, pos, w, lr, host, out);
|
||||
})?;
|
||||
}
|
||||
self.world
|
||||
.block_entities
|
||||
.put(key, BlockEntity::CreakingHeart(heart));
|
||||
Ok(())
|
||||
}
|
||||
/// `ServerLevel.isSpawningMonsters`.
|
||||
@@ -295,7 +287,7 @@ impl Game<'_> {
|
||||
}
|
||||
/// Hearts that came with generated or loaded chunks get their block
|
||||
/// entity (`newBlockEntity`) the first time their chunk is seen.
|
||||
fn scan_for_hearts(&mut self) {
|
||||
pub(super) fn scan_for_hearts(&mut self) {
|
||||
let Some(heart) = self
|
||||
.pack
|
||||
.assets
|
||||
@@ -344,8 +336,7 @@ impl Game<'_> {
|
||||
);
|
||||
self.world
|
||||
.block_entities
|
||||
.entry(pos)
|
||||
.or_insert_with(|| BlockEntity::CreakingHeart(Box::default()));
|
||||
.get_or_insert_with(pos, || BlockEntity::CreakingHeart(Box::default()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,8 +318,18 @@ impl Game<'_> {
|
||||
} else {
|
||||
self.dispense_from(origin, state)?;
|
||||
// CrafterBlockEntity.serverTick, the crafting animation running down.
|
||||
let mut crafters: Vec<(i32, i32, i32)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
crafters.sort_unstable();
|
||||
for _ in 0..case["ticks"].as_u64().unwrap_or(0) {
|
||||
self.tick_crafters();
|
||||
for &p in &crafters {
|
||||
self.tick_crafter(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -140,63 +140,53 @@ impl Game<'_> {
|
||||
pub(super) fn jukebox_removed(&mut self, pos: [i32; 3]) {
|
||||
self.stop_song(pos);
|
||||
}
|
||||
/// `JukeboxSongPlayer.tick` for every playing jukebox.
|
||||
pub(super) fn tick_jukeboxes(&mut self) {
|
||||
let playing: Vec<((i32, i32, i32), String, i64)> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter_map(|(k, e)| match e {
|
||||
BlockEntity::Jukebox(j) if j.playing => {
|
||||
let song = self
|
||||
.res
|
||||
.items
|
||||
.get(&j.record.as_ref()?.item)?
|
||||
.jukebox_song
|
||||
.clone()?;
|
||||
Some((*k, song, j.ticks))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
for (key, song, ticks) in playing {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let Some(s) = self.res.items.songs.get(&song).cloned() else {
|
||||
continue;
|
||||
};
|
||||
if s.finished(ticks) {
|
||||
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
|
||||
j.playing = false;
|
||||
j.ticks = 0;
|
||||
}
|
||||
self.stop_song(pos);
|
||||
self.jukebox_changed(pos);
|
||||
continue;
|
||||
}
|
||||
if !self.jukebox_sounds.contains_key(&key) && ticks == 0 {
|
||||
self.start_song(pos, &song);
|
||||
}
|
||||
if ticks % 20 == 0 {
|
||||
let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 1.2,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.particles.add(
|
||||
&ParticleOptions::simple(ParticleType::Note),
|
||||
at,
|
||||
[color, 0.0, 0.0],
|
||||
);
|
||||
}
|
||||
/// `JukeboxSongPlayer.tick` of the jukebox at `key`, while it plays.
|
||||
pub(super) fn tick_jukebox(&mut self, key: (i32, i32, i32)) {
|
||||
let playing = match self.world.block_entities.get(&key) {
|
||||
Some(BlockEntity::Jukebox(j)) if j.playing => j.record.as_ref().and_then(|r| {
|
||||
let song = self.res.items.get(&r.item)?.jukebox_song.clone()?;
|
||||
Some((song, j.ticks))
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
let Some((song, ticks)) = playing else {
|
||||
return;
|
||||
};
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let Some(s) = self.res.items.songs.get(&song).cloned() else {
|
||||
return;
|
||||
};
|
||||
if s.finished(ticks) {
|
||||
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
|
||||
j.ticks += 1;
|
||||
j.playing = false;
|
||||
j.ticks = 0;
|
||||
}
|
||||
self.stop_song(pos);
|
||||
self.jukebox_changed(pos);
|
||||
return;
|
||||
}
|
||||
if !self.jukebox_sounds.contains_key(&key) && ticks == 0 {
|
||||
self.start_song(pos, &song);
|
||||
}
|
||||
if ticks % 20 == 0 {
|
||||
let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0;
|
||||
let at = [
|
||||
f64::from(pos[0]) + 0.5,
|
||||
f64::from(pos[1]) + 1.2,
|
||||
f64::from(pos[2]) + 0.5,
|
||||
];
|
||||
self.particles.add(
|
||||
&ParticleOptions::simple(ParticleType::Note),
|
||||
at,
|
||||
[color, 0.0, 0.0],
|
||||
);
|
||||
}
|
||||
if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) {
|
||||
j.ticks += 1;
|
||||
}
|
||||
self.update_song_volumes();
|
||||
}
|
||||
/// Let go of songs that ended or whose jukebox stopped.
|
||||
fn update_song_volumes(&mut self) {
|
||||
pub(super) fn update_song_volumes(&mut self) {
|
||||
let sounds: Vec<_> = self
|
||||
.jukebox_sounds
|
||||
.iter()
|
||||
|
||||
@@ -497,42 +497,35 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Every hopper's `pushItemsTick`, in a stable position order.
|
||||
pub(super) fn tick_hoppers(&mut self) -> Result<()> {
|
||||
/// `HopperBlockEntity.pushItemsTick` of the hopper at `pos`, if its block
|
||||
/// is still a hopper (`BlockEntityType.isValid`).
|
||||
pub(super) fn tick_hopper(&mut self, pos: Pos) {
|
||||
let hopper = self
|
||||
.pack
|
||||
.assets
|
||||
.registry
|
||||
.default_state("minecraft:hopper")
|
||||
.map(|s| self.res.facts.get(s).name.clone());
|
||||
let Some(hopper) = hopper else { return Ok(()) };
|
||||
// A hopper's block entity is the plain container with five slots
|
||||
// (`BlockEntity::for_block`; `BlockEntity::id` names it the hopper):
|
||||
// only those need their block looked up (the ticker runs for a
|
||||
// HopperBlockEntity whose block is still a hopper,
|
||||
// `BlockEntityType.isValid`).
|
||||
let mut positions: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Chest(items) if items.len() == HOPPER_SLOTS))
|
||||
.map(|(p, _)| *p)
|
||||
.filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper)
|
||||
.collect();
|
||||
positions.sort_unstable();
|
||||
self.hoppers
|
||||
.retain(|p, _| positions.binary_search(p).is_ok());
|
||||
let time = self.world.game_time;
|
||||
for pos in positions {
|
||||
let state = self.hoppers.entry(pos).or_default();
|
||||
state.cooldown -= 1;
|
||||
state.ticked = time;
|
||||
if state.cooldown <= 0 {
|
||||
state.cooldown = 0;
|
||||
self.hopper_try_move_items(pos);
|
||||
}
|
||||
.res
|
||||
.facts
|
||||
.get(self.world.block(pos.0, pos.1, pos.2))
|
||||
.name
|
||||
.as_ref()
|
||||
== "minecraft:hopper";
|
||||
if !hopper {
|
||||
self.hoppers.remove(&pos);
|
||||
return;
|
||||
}
|
||||
Ok(())
|
||||
let time = self.world.game_time;
|
||||
let state = self.hoppers.entry(pos).or_default();
|
||||
state.cooldown -= 1;
|
||||
state.ticked = time;
|
||||
if state.cooldown <= 0 {
|
||||
state.cooldown = 0;
|
||||
self.hopper_try_move_items(pos);
|
||||
}
|
||||
}
|
||||
/// Drops the cooldowns of hoppers whose block entity is gone.
|
||||
pub(super) fn forget_gone_hoppers(&mut self) {
|
||||
let entities = &self.world.block_entities;
|
||||
self.hoppers.retain(|p, _| {
|
||||
matches!(entities.get(p), Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS)
|
||||
});
|
||||
}
|
||||
/// `HopperBlockEntity.tryMoveItems` with `suckInItems`.
|
||||
pub(super) fn hopper_try_move_items(&mut self, pos: Pos) {
|
||||
|
||||
@@ -56,44 +56,33 @@ impl Game<'_> {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// `CrafterBlockEntity.serverTick` for every crafter, and the powered
|
||||
/// flag following the block state.
|
||||
pub(in crate::game) fn tick_crafters(&mut self) {
|
||||
let positions: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Crafter(_)))
|
||||
.map(|(p, _)| *p)
|
||||
.collect();
|
||||
let mut positions = positions;
|
||||
positions.sort_unstable();
|
||||
for pos in positions {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let triggered = self.containers().prop(state, "triggered") == Some("true");
|
||||
let mut finished = false;
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
|
||||
// CrafterBlock.neighborChanged sets the flag with the state; a
|
||||
// loaded crafter keeps its saved flag until then.
|
||||
if c.state_triggered.is_some_and(|t| t != triggered) {
|
||||
c.triggered = triggered;
|
||||
}
|
||||
c.state_triggered = Some(triggered);
|
||||
let remaining = c.crafting_ticks - 1;
|
||||
if remaining >= 0 {
|
||||
c.crafting_ticks = remaining;
|
||||
finished = remaining == 0;
|
||||
}
|
||||
/// `CrafterBlockEntity.serverTick` of the crafter at `pos`, and the
|
||||
/// powered flag following the block state.
|
||||
pub(in crate::game) fn tick_crafter(&mut self, pos: Pos) {
|
||||
let state = self.world.block(pos.0, pos.1, pos.2);
|
||||
let triggered = self.containers().prop(state, "triggered") == Some("true");
|
||||
let mut finished = false;
|
||||
if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) {
|
||||
// CrafterBlock.neighborChanged sets the flag with the state; a
|
||||
// loaded crafter keeps its saved flag until then.
|
||||
if c.state_triggered.is_some_and(|t| t != triggered) {
|
||||
c.triggered = triggered;
|
||||
}
|
||||
if finished {
|
||||
self.set_bool_prop(
|
||||
pos,
|
||||
"crafting",
|
||||
false,
|
||||
horizon_world::level::flags::UPDATE_ALL,
|
||||
);
|
||||
c.state_triggered = Some(triggered);
|
||||
let remaining = c.crafting_ticks - 1;
|
||||
if remaining >= 0 {
|
||||
c.crafting_ticks = remaining;
|
||||
finished = remaining == 0;
|
||||
}
|
||||
}
|
||||
if finished {
|
||||
self.set_bool_prop(
|
||||
pos,
|
||||
"crafting",
|
||||
false,
|
||||
horizon_world::level::flags::UPDATE_ALL,
|
||||
);
|
||||
}
|
||||
}
|
||||
/// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse).
|
||||
pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> {
|
||||
|
||||
@@ -127,7 +127,7 @@ impl Game<'_> {
|
||||
let entity = horizon_client::containers::BlockEntity::for_block(&name)
|
||||
.filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_)))
|
||||
.ok_or("no sign there")?;
|
||||
self.world.block_entities.entry(key).or_insert(entity);
|
||||
self.world.block_entities.get_or_insert_with(key, || entity);
|
||||
self.open_sign_editor(key, words.get(4) != Some(&"back"));
|
||||
Ok(Some(json!({ "ok": true })))
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ impl Game<'_> {
|
||||
.as_ref()
|
||||
.is_some_and(|t| t.contains(id))
|
||||
}
|
||||
fn load_entity_types(&mut self) {
|
||||
pub(super) fn load_entity_types(&mut self) {
|
||||
if self.spawners.entity_types.is_some() {
|
||||
return;
|
||||
}
|
||||
@@ -63,32 +63,27 @@ impl Game<'_> {
|
||||
.unwrap_or_default();
|
||||
self.spawners.entity_types = Some(types);
|
||||
}
|
||||
/// Every spawner's server tick, then its client tick.
|
||||
pub(super) fn tick_spawners(&mut self) -> Result<()> {
|
||||
self.load_entity_types();
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Spawner(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in &keys {
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:spawner" {
|
||||
continue;
|
||||
}
|
||||
let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let result = self.server_tick_spawner(*key, &mut spawner);
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(*key, BlockEntity::Spawner(spawner));
|
||||
result?;
|
||||
/// The server tick of the spawner at `key`, if its block is still a
|
||||
/// spawner. Its client tick comes after every block entity's
|
||||
/// (`client_tick_spawners`).
|
||||
pub(super) fn tick_spawner(&mut self, key: Pos) -> Result<()> {
|
||||
let state = self.world.block(key.0, key.1, key.2);
|
||||
if &*self.res.facts.get(state).name != "minecraft:spawner" {
|
||||
return Ok(());
|
||||
}
|
||||
for key in keys {
|
||||
let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.take(&key) else {
|
||||
return Ok(());
|
||||
};
|
||||
let result = self.server_tick_spawner(key, &mut spawner);
|
||||
self.world
|
||||
.block_entities
|
||||
.put(key, BlockEntity::Spawner(spawner));
|
||||
result
|
||||
}
|
||||
/// The client ticks of these spawners, then the shown mobs of spawners
|
||||
/// that are gone go.
|
||||
pub(super) fn client_tick_spawners(&mut self, keys: &[Pos]) {
|
||||
for &key in keys {
|
||||
self.client_tick_spawner(key);
|
||||
}
|
||||
let entities = &self.world.block_entities;
|
||||
@@ -98,7 +93,6 @@ impl Game<'_> {
|
||||
Some(BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_))
|
||||
)
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
|
||||
@@ -106,34 +106,21 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> {
|
||||
}
|
||||
|
||||
impl Game<'_> {
|
||||
/// Every trial spawner's server tick.
|
||||
pub(super) fn tick_trial_spawners(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
/// The server tick of the trial spawner at `key`. Its client tick comes
|
||||
/// after every block entity's.
|
||||
pub(super) fn tick_trial_spawner(&mut self, key: Pos) -> Result<()> {
|
||||
let Some((current, ominous)) = self.trial_spawner_block(key) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(BlockEntity::TrialSpawner(mut spawner)) = self.world.block_entities.take(&key)
|
||||
else {
|
||||
return Ok(());
|
||||
};
|
||||
let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous);
|
||||
self.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for &key in &keys {
|
||||
let Some((current, ominous)) = self.trial_spawner_block(key) else {
|
||||
continue;
|
||||
};
|
||||
let Some(BlockEntity::TrialSpawner(mut spawner)) =
|
||||
self.world.block_entities.remove(&key)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous);
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::TrialSpawner(spawner));
|
||||
result?;
|
||||
}
|
||||
for key in keys {
|
||||
self.client_tick_trial_spawner(key);
|
||||
}
|
||||
Ok(())
|
||||
.put(key, BlockEntity::TrialSpawner(spawner));
|
||||
result
|
||||
}
|
||||
/// The trial spawner block at `key`: its state and ominous flag.
|
||||
pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> {
|
||||
|
||||
@@ -237,7 +237,7 @@ impl Game<'_> {
|
||||
let shows = vault.display_item.is_some();
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Vault(vault));
|
||||
.put(key, BlockEntity::Vault(vault));
|
||||
let pos = [key.0, key.1, key.2];
|
||||
if self.world.game_time % 20 == 0 {
|
||||
self.vault_connection_particles(pos);
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Game<'_> {
|
||||
.and_then(|s| VaultState::from_name(s))
|
||||
.unwrap_or_default();
|
||||
let ominous = block.properties.get("ominous").is_some_and(|v| v == "true");
|
||||
let Some(BlockEntity::Vault(vault)) = self.world.block_entities.remove(&key) else {
|
||||
let Some(BlockEntity::Vault(vault)) = self.world.block_entities.take(&key) else {
|
||||
return None;
|
||||
};
|
||||
Some((vault, current, ominous))
|
||||
@@ -118,28 +118,19 @@ impl Game<'_> {
|
||||
self.rand_sequences = sequences;
|
||||
self.world
|
||||
.block_entities
|
||||
.insert(key, BlockEntity::Vault(vault));
|
||||
.put(key, BlockEntity::Vault(vault));
|
||||
Some(self.vault_events(key, events).map(|()| out))
|
||||
}
|
||||
/// Every vault's server tick, then its client tick.
|
||||
pub(super) fn tick_vaults(&mut self) -> Result<()> {
|
||||
let keys: Vec<Pos> = self
|
||||
.world
|
||||
.block_entities
|
||||
.iter()
|
||||
.filter(|(_, e)| matches!(e, BlockEntity::Vault(_)))
|
||||
.map(|(k, _)| *k)
|
||||
.collect();
|
||||
for key in keys {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| {
|
||||
v.server_tick(l, random, pos, state, ominous, roll, events);
|
||||
});
|
||||
if let Some(result) = ticked {
|
||||
result?;
|
||||
}
|
||||
self.client_tick_vault(key);
|
||||
/// The server tick of the vault at `key`, then its client tick.
|
||||
pub(super) fn tick_vault(&mut self, key: Pos) -> Result<()> {
|
||||
let pos = [key.0, key.1, key.2];
|
||||
let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| {
|
||||
v.server_tick(l, random, pos, state, ominous, roll, events);
|
||||
});
|
||||
if let Some(result) = ticked {
|
||||
result?;
|
||||
}
|
||||
self.client_tick_vault(key);
|
||||
Ok(())
|
||||
}
|
||||
/// `VaultBlock.useItemOn` with `held` in the hand that acts: true when the
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod banner;
|
||||
pub mod beehive;
|
||||
pub mod benchmark;
|
||||
pub mod biome;
|
||||
pub mod block_entities;
|
||||
pub mod block_entity_anim;
|
||||
pub mod block_entity_item;
|
||||
pub mod block_entity_nbt;
|
||||
|
||||
@@ -589,7 +589,7 @@ impl Streaming {
|
||||
}
|
||||
world
|
||||
.block_entities
|
||||
.extend(std::mem::take(&mut chunk.block_entities));
|
||||
.load_chunk(std::mem::take(&mut chunk.block_entities));
|
||||
world
|
||||
.block_names
|
||||
.extend(std::mem::take(&mut chunk.block_names));
|
||||
|
||||
@@ -26,7 +26,8 @@ pub struct World {
|
||||
pub loaded_entities: Vec<((i32, i32), Vec<horizon_world::nbt::Tag>)>,
|
||||
/// Chunks changed since the last save.
|
||||
pub modified: HashSet<(i32, i32)>,
|
||||
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
|
||||
/// Block entities, and the order they tick in.
|
||||
pub block_entities: crate::block_entities::BlockEntities,
|
||||
/// Each chest's `ContainerOpenersCounter`: opener count and largest
|
||||
/// interaction range.
|
||||
pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>,
|
||||
@@ -122,7 +123,7 @@ impl World {
|
||||
light_edits: Vec::new(),
|
||||
loaded_entities: Vec::new(),
|
||||
modified: HashSet::new(),
|
||||
block_entities: HashMap::new(),
|
||||
block_entities: Default::default(),
|
||||
chest_openers: HashMap::new(),
|
||||
block_names: HashMap::new(),
|
||||
watched: Vec::new(),
|
||||
@@ -200,6 +201,8 @@ impl World {
|
||||
}
|
||||
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0);
|
||||
if previous != state.0 {
|
||||
self.block_entities
|
||||
.state_changed((x, y, z), previous, state.0);
|
||||
let watches = |id: u32| self.watched.get(id as usize).copied().unwrap_or(false);
|
||||
if watches(previous) || watches(state.0) {
|
||||
self.watched_writes.push(((x, y, z), previous, state.0));
|
||||
@@ -240,6 +243,16 @@ impl World {
|
||||
.get(&(x >> 4, z >> 4))
|
||||
.map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15))
|
||||
}
|
||||
/// The block entities to tick this tick, in order (`BlockEntities::tickers`).
|
||||
pub fn block_entity_tickers(&mut self) -> Vec<(crate::block_entities::Pos, u32)> {
|
||||
let (chunks, air) = (&self.chunks, self.air);
|
||||
self.block_entities.tickers(|(x, y, z)| {
|
||||
chunks
|
||||
.get(&(x >> 4, z >> 4))
|
||||
.map_or(air, |chunk| chunk.block(x & 15, y, z & 15))
|
||||
.0
|
||||
})
|
||||
}
|
||||
pub fn light(&self, x: i32, y: i32, z: i32) -> u8 {
|
||||
self.chunks
|
||||
.get(&(x >> 4, z >> 4))
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.core.registries.BuiltInRegistries;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.util.debug.LevelDebugSynchronizers;
|
||||
import net.minecraft.world.TickRateManager;
|
||||
import net.minecraft.world.level.ChunkPos;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.Blocks;
|
||||
import net.minecraft.world.level.block.EntityBlock;
|
||||
import net.minecraft.world.level.block.JukeboxBlock;
|
||||
import net.minecraft.world.level.block.entity.BlockEntity;
|
||||
import net.minecraft.world.level.block.entity.TickingBlockEntity;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.ChunkAccess;
|
||||
import net.minecraft.world.level.chunk.LevelChunk;
|
||||
|
||||
/**
|
||||
* The order of vanilla's `Level.blockEntityTickers`: real `LevelChunk`s of a
|
||||
* server level register, rebind and drop the tickers of real block entities
|
||||
* (`addAndRegisterBlockEntity`, `setBlockEntity`, `removeBlockEntity`,
|
||||
* `updateBlockEntityTicker` after a state change, `registerAllBlockEntitiesAfterLevelLoad`
|
||||
* after a chunk load, `clearAllBlockEntities` when it unloads), and
|
||||
* `Level.tickBlockEntities` runs with the tick rate frozen, so it only
|
||||
* promotes pending tickers and drops removed ones. After each `tick` the
|
||||
* positions of the live tickers are printed in list order.
|
||||
*
|
||||
* Input lines: `reset`, `load CX CZ BLOCK X Y Z ...` (a chunk's block entities in
|
||||
* its save order), `place BLOCK X Y Z`, `replace X Y Z`, `remove X Y Z`,
|
||||
* `record X Y Z 0|1` (a jukebox's has_record), `unload CX CZ`, `tick`.
|
||||
*/
|
||||
public final class VanillaBlockEntityTickerOracle {
|
||||
static Object unsafe;
|
||||
static Method allocate;
|
||||
|
||||
static <T> T alloc(Class<T> c) throws Exception {
|
||||
return c.cast(allocate.invoke(unsafe, c));
|
||||
}
|
||||
|
||||
static void set(Class<?> owner, Object target, String name, Object value) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
f.set(target, value);
|
||||
}
|
||||
|
||||
static Object get(Class<?> owner, Object target, String name) throws Exception {
|
||||
Field f = owner.getDeclaredField(name);
|
||||
f.setAccessible(true);
|
||||
return f.get(target);
|
||||
}
|
||||
|
||||
static Map<BlockPos, BlockState> cells = new HashMap<>();
|
||||
static Map<Long, Chunk> chunks = new HashMap<>();
|
||||
static World world;
|
||||
|
||||
static final class World extends net.minecraft.server.level.ServerLevel {
|
||||
TickRateManager rate;
|
||||
LevelDebugSynchronizers debug;
|
||||
World() {
|
||||
super(null, null, null, null, null, null, false, 0L, List.of(), false);
|
||||
}
|
||||
@Override public boolean isClientSide() { return false; }
|
||||
@Override public TickRateManager tickRateManager() { return rate; }
|
||||
@Override public LevelDebugSynchronizers debugSynchronizers() { return debug; }
|
||||
@Override public void onBlockEntityAdded(BlockEntity blockEntity) { }
|
||||
@Override public void levelEvent(net.minecraft.world.entity.Entity source, int type, BlockPos at, int data) { }
|
||||
@Override public void gameEvent(net.minecraft.core.Holder<net.minecraft.world.level.gameevent.GameEvent> event,
|
||||
net.minecraft.world.phys.Vec3 at, net.minecraft.world.level.gameevent.GameEvent.Context context) { }
|
||||
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, Blocks.AIR.defaultBlockState()); }
|
||||
@Override public void playSeededSound(net.minecraft.world.entity.Entity except, double x, double y, double z,
|
||||
net.minecraft.core.Holder<net.minecraft.sounds.SoundEvent> sound, net.minecraft.sounds.SoundSource source,
|
||||
float volume, float pitch, long seed) { }
|
||||
@Override public int getMinY() { return -64; }
|
||||
@Override public int getHeight() { return 384; }
|
||||
}
|
||||
|
||||
static final class Chunk extends LevelChunk {
|
||||
Chunk() {
|
||||
super(null, null);
|
||||
}
|
||||
@Override public BlockState getBlockState(BlockPos p) { return cells.getOrDefault(p, Blocks.AIR.defaultBlockState()); }
|
||||
@Override public void markUnsaved() { }
|
||||
}
|
||||
|
||||
static void reset() throws Exception {
|
||||
cells = new HashMap<>();
|
||||
chunks = new HashMap<>();
|
||||
world = alloc(World.class);
|
||||
set(Level.class, world, "blockEntityTickers", new ArrayList<TickingBlockEntity>());
|
||||
set(Level.class, world, "pendingBlockEntityTickers", new ArrayList<TickingBlockEntity>());
|
||||
set(Level.class, world, "soundSeedGenerator", net.minecraft.util.RandomSource.create(0));
|
||||
TickRateManager rate = new TickRateManager();
|
||||
set(TickRateManager.class, rate, "runGameElements", false);
|
||||
world.rate = rate;
|
||||
LevelDebugSynchronizers debug = alloc(LevelDebugSynchronizers.class);
|
||||
set(LevelDebugSynchronizers.class, debug, "sleeping", true);
|
||||
world.debug = debug;
|
||||
}
|
||||
|
||||
static Chunk chunk(int cx, int cz) throws Exception {
|
||||
Chunk c = chunks.get(ChunkPos.pack(cx, cz));
|
||||
if (c != null) return c;
|
||||
c = alloc(Chunk.class);
|
||||
set(ChunkAccess.class, c, "blockEntities", new it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap<BlockPos, BlockEntity>());
|
||||
set(ChunkAccess.class, c, "pendingBlockEntities", new HashMap<BlockPos, net.minecraft.nbt.CompoundTag>());
|
||||
set(ChunkAccess.class, c, "chunkPos", new ChunkPos(cx, cz));
|
||||
set(LevelChunk.class, c, "level", world);
|
||||
set(LevelChunk.class, c, "tickersInLevel", new HashMap<>());
|
||||
chunks.put(ChunkPos.pack(cx, cz), c);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** The chunk at `p`, in the level (a chunk first seen here was already loaded). */
|
||||
static Chunk at(BlockPos p) throws Exception {
|
||||
Chunk c = chunk(p.getX() >> 4, p.getZ() >> 4);
|
||||
c.setLoaded(true);
|
||||
return c;
|
||||
}
|
||||
|
||||
/** The block's state: a jukebox's has_record from the name (`jukebox_record`). */
|
||||
static BlockState state(String name) {
|
||||
boolean record = name.equals("jukebox_record");
|
||||
Block block = BuiltInRegistries.BLOCK.getValue(Identifier.withDefaultNamespace(record ? "jukebox" : name));
|
||||
BlockState s = block.defaultBlockState();
|
||||
return block instanceof JukeboxBlock ? s.setValue(JukeboxBlock.HAS_RECORD, record) : s;
|
||||
}
|
||||
|
||||
static BlockEntity make(BlockPos p) {
|
||||
BlockState s = cells.get(p);
|
||||
return ((EntityBlock) s.getBlock()).newBlockEntity(p, s);
|
||||
}
|
||||
|
||||
static BlockPos pos(String[] w, int i) {
|
||||
return new BlockPos(Integer.parseInt(w[i]), Integer.parseInt(w[i + 1]), Integer.parseInt(w[i + 2]));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
// Registries with item components bound (vaults hold item stacks).
|
||||
ParityData.init();
|
||||
var allocator = Class.forName("sun.misc.Unsafe");
|
||||
var field = allocator.getDeclaredField("theUnsafe");
|
||||
field.setAccessible(true);
|
||||
unsafe = field.get(null);
|
||||
allocate = allocator.getMethod("allocateInstance", Class.class);
|
||||
Method update = LevelChunk.class.getDeclaredMethod("updateBlockEntityTicker", BlockEntity.class);
|
||||
update.setAccessible(true);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (String line : Files.readAllLines(Path.of(args[0]))) {
|
||||
String[] w = line.trim().split(" ");
|
||||
switch (w[0]) {
|
||||
case "reset" -> reset();
|
||||
case "load" -> {
|
||||
// SerializableChunkData.postLoadChunk, then ChunkStatusTasks.full.
|
||||
Chunk c = chunk(Integer.parseInt(w[1]), Integer.parseInt(w[2]));
|
||||
for (int i = 3; i + 3 < w.length; i += 4) {
|
||||
BlockPos p = pos(w, i + 1);
|
||||
cells.put(p, state(w[i]));
|
||||
c.setBlockEntity(make(p));
|
||||
}
|
||||
c.setLoaded(true);
|
||||
c.registerAllBlockEntitiesAfterLevelLoad();
|
||||
}
|
||||
case "place" -> {
|
||||
// LevelChunk.setBlockState: a new block entity block.
|
||||
BlockPos p = pos(w, 2);
|
||||
cells.put(p, state(w[1]));
|
||||
at(p).addAndRegisterBlockEntity(make(p));
|
||||
}
|
||||
case "replace" -> {
|
||||
BlockPos p = pos(w, 1);
|
||||
at(p).addAndRegisterBlockEntity(make(p));
|
||||
}
|
||||
case "remove" -> {
|
||||
BlockPos p = pos(w, 1);
|
||||
at(p).removeBlockEntity(p);
|
||||
cells.remove(p);
|
||||
}
|
||||
case "record" -> {
|
||||
// LevelChunk.setBlockState: the same block, another state.
|
||||
BlockPos p = pos(w, 1);
|
||||
BlockState s = state(w[4].equals("1") ? "jukebox_record" : "jukebox");
|
||||
cells.put(p, s);
|
||||
BlockEntity be = at(p).getBlockEntity(p);
|
||||
be.setBlockState(s);
|
||||
update.invoke(at(p), be);
|
||||
}
|
||||
case "unload" -> {
|
||||
Chunk c = chunks.remove(ChunkPos.pack(Integer.parseInt(w[1]), Integer.parseInt(w[2])));
|
||||
if (c != null) c.clearAllBlockEntities();
|
||||
}
|
||||
case "tick" -> {
|
||||
world.tickBlockEntities();
|
||||
@SuppressWarnings("unchecked")
|
||||
List<TickingBlockEntity> list = (List<TickingBlockEntity>) get(Level.class, world, "blockEntityTickers");
|
||||
out.append("tick");
|
||||
for (TickingBlockEntity t : list) {
|
||||
BlockPos p = t.getPos();
|
||||
out.append(' ').append(p.getX()).append(',').append(p.getY()).append(',').append(p.getZ());
|
||||
}
|
||||
out.append('\n');
|
||||
}
|
||||
default -> throw new IllegalArgumentException(line);
|
||||
}
|
||||
}
|
||||
Files.writeString(Path.of(args[1]), out);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the order block entities tick in with vanilla's `Level.blockEntityTickers`.
|
||||
|
||||
Random scenarios load chunks with block entities in a save order (enough in
|
||||
one chunk to make its block entity map grow), place, replace and remove block
|
||||
entities, give jukeboxes a record and take it, and unload chunks, with ticks
|
||||
in between. `VanillaBlockEntityTickerOracle` runs them on real `LevelChunk`s
|
||||
of a server level and prints, after each tick, the positions of the live
|
||||
tickers in list order; `examples/block_entity_tickers_fixture` runs the same
|
||||
on `horizon_client::block_entities::BlockEntities`. The block entities are
|
||||
the kinds the game ticks in that list (hoppers, furnaces, beacons, spawners,
|
||||
trial spawners, vaults, hives, crafters, jukebox), with chests and barrels,
|
||||
which have no ticker, among them.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import sys
|
||||
try:
|
||||
from . import lab, test_rust_parity as base
|
||||
except ImportError:
|
||||
import lab
|
||||
import test_rust_parity as base
|
||||
|
||||
PARITY = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity'
|
||||
TICKING = ['hopper', 'furnace', 'blast_furnace', 'smoker', 'beacon', 'spawner', 'trial_spawner', 'vault',
|
||||
'beehive', 'bee_nest', 'crafter', 'jukebox_record']
|
||||
KINDS = TICKING + ['jukebox', 'chest', 'barrel']
|
||||
|
||||
|
||||
def scenario(rng):
|
||||
"""One scenario's lines: a few chunks near the origin and the ops on them."""
|
||||
lines = ['reset']
|
||||
loaded, blocks = set(), {}
|
||||
|
||||
def free(cx, cz):
|
||||
while True:
|
||||
p = (cx * 16 + rng.randrange(16), rng.randrange(-64, 320), cz * 16 + rng.randrange(16))
|
||||
if p not in blocks:
|
||||
return p
|
||||
|
||||
def load():
|
||||
options = [(x, z) for x in range(-2, 3) for z in range(-2, 3) if (x, z) not in loaded]
|
||||
if not options:
|
||||
return
|
||||
cx, cz = rng.choice(options)
|
||||
loaded.add((cx, cz))
|
||||
words = ['load', str(cx), str(cz)]
|
||||
for _ in range(rng.choice([0, 1, 3, 8, 20, 30, 60])):
|
||||
p, kind = free(cx, cz), rng.choice(KINDS)
|
||||
blocks[p] = kind
|
||||
words += [kind, *map(str, p)]
|
||||
lines.append(' '.join(words))
|
||||
for _ in range(rng.randrange(1, 4)):
|
||||
load()
|
||||
lines.append('tick')
|
||||
for _ in range(rng.randrange(10, 60)):
|
||||
op = rng.random()
|
||||
mine = sorted(blocks)
|
||||
if op < 0.25 and loaded:
|
||||
cx, cz = rng.choice(sorted(loaded))
|
||||
p, kind = free(cx, cz), rng.choice(KINDS)
|
||||
blocks[p] = kind
|
||||
lines.append(f'place {kind} {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.4 and mine:
|
||||
p = rng.choice(mine)
|
||||
lines.append(f'replace {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.6 and mine:
|
||||
p = rng.choice(mine)
|
||||
del blocks[p]
|
||||
lines.append(f'remove {p[0]} {p[1]} {p[2]}')
|
||||
elif op < 0.72:
|
||||
jukeboxes = [p for p in mine if blocks[p].startswith('jukebox')]
|
||||
if jukeboxes:
|
||||
p = rng.choice(jukeboxes)
|
||||
record = blocks[p] == 'jukebox'
|
||||
blocks[p] = 'jukebox_record' if record else 'jukebox'
|
||||
lines.append(f'record {p[0]} {p[1]} {p[2]} {int(record)}')
|
||||
elif op < 0.78 and loaded:
|
||||
cx, cz = rng.choice(sorted(loaded))
|
||||
loaded.discard((cx, cz))
|
||||
for p in [p for p in blocks if (p[0] >> 4, p[2] >> 4) == (cx, cz)]:
|
||||
del blocks[p]
|
||||
lines.append(f'unload {cx} {cz}')
|
||||
elif op < 0.85:
|
||||
load()
|
||||
else:
|
||||
lines.append('tick')
|
||||
lines.append('tick')
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--scenarios', type=int, default=3000)
|
||||
parser.add_argument('--seed', type=int, default=0x7469636b)
|
||||
args = parser.parse_args()
|
||||
lock, jars, libraries = base.verify_artifacts()
|
||||
build = lab.LOCAL / 'rust-block-entity-tickers-parity'
|
||||
build.mkdir(parents=True, exist_ok=True)
|
||||
rng = random.Random(args.seed)
|
||||
lines = [line for _ in range(args.scenarios) for line in scenario(rng)]
|
||||
inputs = build / 'inputs.txt'
|
||||
inputs.write_text('\n'.join(lines) + '\n')
|
||||
classes = build / 'classes'
|
||||
classes.mkdir(exist_ok=True)
|
||||
dependencies = os.pathsep.join(map(str, [jars['server'], *libraries]))
|
||||
|
||||
def run(command, name):
|
||||
with (build / (name + '.log')).open('w') as log:
|
||||
result = subprocess.run(list(map(str, command)), cwd=lab.ROOT, timeout=3600, stdout=log,
|
||||
stderr=subprocess.STDOUT)
|
||||
if result.returncode:
|
||||
print((build / (name + '.log')).read_text()[-4000:])
|
||||
sys.exit(f'{name} failed')
|
||||
run(['javac', '--release', lock['minecraft']['java_major'], '-proc:none', '-nowarn', '-cp', dependencies,
|
||||
'-d', classes, *(PARITY / f'{n}.java' for n in ('ParityData', 'VanillaBlockEntityTickerOracle'))],
|
||||
'compile-java')
|
||||
run(['java', '-Xmx1G', '-cp', str(classes) + os.pathsep + dependencies,
|
||||
'dev.horizonlab.parity.VanillaBlockEntityTickerOracle', inputs, build / 'vanilla.txt'], 'vanilla')
|
||||
run(['cargo', 'run', '--quiet', '--profile', 'fast', '-p', 'horizon-client', '--example',
|
||||
'block_entity_tickers_fixture', '--', inputs, build / 'rust.txt'], 'rust')
|
||||
matched = base.compare(build / 'vanilla.txt', build / 'rust.txt')
|
||||
ticks = sum(1 for line in lines if line == 'tick')
|
||||
listed = sum(len(line.split()) - 1 for line in (build / 'vanilla.txt').read_text().splitlines())
|
||||
print(f'block entity tickers: {args.scenarios} scenarios, {matched} of {ticks} ticks match vanilla '
|
||||
f'({listed} tickers listed)')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user