Merge pull request #1256 from ludovic111/perf/random-tick-counts
🤖 Agent: merged after verify passed and the wave-3 integration on the desktop by integ-w3: main + 17 PRs, fmt, clippy 0, 1929 workspace tests, parity --changed (only known flakes failed, and those passed on rerun), lan_e2e in both modes, and the perf numbers back to back against main posted on each PR.
This commit is contained in:
@@ -0,0 +1,132 @@
|
||||
//! Random-tick sections companion for tools/test_random_tick_sections_parity.py:
|
||||
//! the game's `RandomTickSections` choosing the sections of a chunk that
|
||||
//! `Behaviours::tick_chunk_random` ticks, after the case's edits (see
|
||||
//! VanillaRandomTickSectionsOracle for the format; the `#resources` line names
|
||||
//! the prepared resources). The level the ticks run against reads as air
|
||||
//! everywhere, so nothing ticks for real: its reads are the drawn positions.
|
||||
use horizon_client::{
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, MIN_Y, Section},
|
||||
random_tick_sections::RandomTickSections,
|
||||
};
|
||||
use horizon_core::{
|
||||
position::{BlockPos, ChunkPos},
|
||||
random::LegacyRandom,
|
||||
};
|
||||
use horizon_world::{
|
||||
fluid::FluidKind,
|
||||
level::{GameRules, LevelAccess, LevelEvent, Ticks, data},
|
||||
registry::BlockStateId,
|
||||
};
|
||||
use std::{cell::RefCell, error::Error, fmt::Write, path::PathBuf, sync::Arc};
|
||||
|
||||
struct Air {
|
||||
reads: RefCell<Vec<BlockPos>>,
|
||||
random: LegacyRandom,
|
||||
speed: i32,
|
||||
}
|
||||
impl LevelAccess for Air {
|
||||
fn block_state(&self, pos: BlockPos) -> BlockStateId {
|
||||
self.reads.borrow_mut().push(pos);
|
||||
BlockStateId(0)
|
||||
}
|
||||
fn set_raw(&mut self, _: BlockPos, _: BlockStateId) -> Option<BlockStateId> {
|
||||
None
|
||||
}
|
||||
fn is_loaded(&self, _: BlockPos) -> bool {
|
||||
true
|
||||
}
|
||||
fn random(&mut self) -> &mut LegacyRandom {
|
||||
&mut self.random
|
||||
}
|
||||
fn game_time(&self) -> i64 {
|
||||
0
|
||||
}
|
||||
fn game_rules(&self) -> GameRules {
|
||||
GameRules {
|
||||
random_tick_speed: self.speed,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
fn emit(&mut self, _: LevelEvent) {}
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let input = std::fs::read_to_string(&args[1])?;
|
||||
let root = input
|
||||
.lines()
|
||||
.find_map(|l| l.strip_prefix("#resources "))
|
||||
.map(PathBuf::from)
|
||||
.ok_or("no #resources line")?;
|
||||
let registry = data::load_registry(&root)?;
|
||||
let (facts, behaviours) = BlockFacts::load_pair(&root, ®istry)?;
|
||||
let mut output = String::new();
|
||||
for line in input.lines().filter(|l| !l.starts_with('#')) {
|
||||
let mut words = line.split(' ');
|
||||
let mut ticks = Ticks::new(0);
|
||||
ticks.random_tick_value = words.next().ok_or("no randValue")?.parse()?;
|
||||
let mut level = Air {
|
||||
reads: RefCell::default(),
|
||||
random: LegacyRandom::new(0),
|
||||
speed: words.next().ok_or("no speed")?.parse()?,
|
||||
};
|
||||
let mut chunk = Arc::new(Chunk::empty(0, 0));
|
||||
let mut cache = RandomTickSections::default();
|
||||
for word in words {
|
||||
let op: Vec<&str> = word.split(':').collect();
|
||||
let int = |i: usize| -> Result<i32, Box<dyn Error>> { Ok(op[i].parse()?) };
|
||||
match op[0] {
|
||||
"s" => {
|
||||
let (section, index) = (int(1)?, int(2)?);
|
||||
Arc::make_mut(&mut chunk).set(
|
||||
index & 15,
|
||||
MIN_Y + section * 16 + (index >> 8),
|
||||
index >> 4 & 15,
|
||||
int(3)? as u32,
|
||||
);
|
||||
}
|
||||
"f" => {
|
||||
let (a, b, m) = (int(2)? as u32, int(3)? as u32, int(4)? as usize);
|
||||
let values = std::array::from_fn(|i| if i % m == m - 1 { b } else { a });
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[int(1)? as usize])
|
||||
.blocks = Section::from_blocks(&values);
|
||||
}
|
||||
"t" => {
|
||||
output.push('|');
|
||||
level.reads.borrow_mut().clear();
|
||||
behaviours.tick_chunk_random(
|
||||
&mut level,
|
||||
&mut ticks,
|
||||
ChunkPos::new(0, 0),
|
||||
|_, from| cache.get((0, 0), &chunk, &facts).from(from),
|
||||
);
|
||||
for pos in level.reads.borrow().iter() {
|
||||
let state = chunk.block(pos.x, pos.y, pos.z);
|
||||
let fluid = matches!(
|
||||
behaviours.fluid(state).kind(),
|
||||
FluidKind::Lava | FluidKind::FlowingLava
|
||||
);
|
||||
write!(
|
||||
output,
|
||||
" {},{},{},{}{}",
|
||||
pos.x,
|
||||
pos.y,
|
||||
pos.z,
|
||||
if behaviours.is_randomly_ticking(state) {
|
||||
'B'
|
||||
} else {
|
||||
'-'
|
||||
},
|
||||
if fluid { 'F' } else { '-' },
|
||||
)?;
|
||||
}
|
||||
}
|
||||
other => return Err(format!("unknown op {other}").into()),
|
||||
}
|
||||
}
|
||||
writeln!(output, " | {}", ticks.random_tick_value)?;
|
||||
}
|
||||
std::fs::write(&args[2], output)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -524,6 +524,7 @@ struct GameLevel<'w> {
|
||||
spill: &'w mut spill::Spill,
|
||||
/// Where the chunk tickets let blocks tick.
|
||||
tickets: horizon_client::ticket_levels::Levels,
|
||||
random_tick_sections: &'w mut horizon_client::random_tick_sections::RandomTickSections,
|
||||
}
|
||||
struct PlayerCollision {
|
||||
y: f64,
|
||||
@@ -2291,6 +2292,7 @@ impl Game<'_> {
|
||||
pending: &mut self.pending,
|
||||
spill: &mut self.spill,
|
||||
tickets: self.tickets.levels(),
|
||||
random_tick_sections: &mut self.random_tick_sections,
|
||||
};
|
||||
let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks);
|
||||
self.flush_spill();
|
||||
@@ -2385,18 +2387,15 @@ impl Game<'_> {
|
||||
self.sync_tick_chunks();
|
||||
self.start_ticking_chunks();
|
||||
let levels = self.tickets.levels();
|
||||
let mut ticking = Vec::new();
|
||||
let facts = self.res.facts();
|
||||
for (&(x, z), chunk) in &self.world.chunks {
|
||||
if !levels.random_ticking(x, z) || !ticking_chunk(&self.world, x, z) {
|
||||
continue;
|
||||
}
|
||||
// Capture eligibility before inside-block and scheduled updates, as
|
||||
// before. Keep the world map's chunk order, including empty chunks
|
||||
// (tick_chunk_random still draws for precipitation in those).
|
||||
let sections = self.random_tick_sections.get((x, z), chunk, facts);
|
||||
ticking.push((x, z, sections));
|
||||
}
|
||||
// Keep the world map's chunk order, including empty chunks
|
||||
// (tick_chunk_random still draws for precipitation in those).
|
||||
let ticking: Vec<_> = self
|
||||
.world
|
||||
.chunks
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|&(x, z)| levels.random_ticking(x, z) && ticking_chunk(&self.world, x, z))
|
||||
.collect();
|
||||
// Entity.checkInsideBlocks for the plates, tripwires and detector rails
|
||||
// under the players (the host and the LAN guests) and the minecarts.
|
||||
let mut inside = Vec::new();
|
||||
@@ -2438,13 +2437,24 @@ impl Game<'_> {
|
||||
self.process_level_events()?;
|
||||
self.tick_scheduled()?;
|
||||
self.with_level(|b, level, ticks| {
|
||||
for (x, z, sections) in ticking {
|
||||
b.tick_chunk_random(
|
||||
level,
|
||||
ticks,
|
||||
horizon_core::position::ChunkPos::new(x, z),
|
||||
sections,
|
||||
);
|
||||
for (x, z) in ticking {
|
||||
// The sections are read again only after a block changed.
|
||||
let mut read = None;
|
||||
let mut sections = Default::default();
|
||||
let pos = horizon_core::position::ChunkPos::new(x, z);
|
||||
b.tick_chunk_random(level, ticks, pos, |level, from| {
|
||||
if read != Some(level.world.revision) {
|
||||
read = Some(level.world.revision);
|
||||
sections = level
|
||||
.world
|
||||
.chunks
|
||||
.get(&(x, z))
|
||||
.map_or_else(Default::default, |chunk| {
|
||||
level.random_tick_sections.get((x, z), chunk, level.facts)
|
||||
});
|
||||
}
|
||||
sections.from(from)
|
||||
});
|
||||
}
|
||||
b.run_block_events(level, ticks);
|
||||
b.tick_block_entities(level, ticks);
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! Memoized palette eligibility for the game thread's random-tick snapshot.
|
||||
//! Which sections of the game thread's chunks random-tick
|
||||
//! (`LevelChunkSection.isRandomlyTicking`), memoized per section.
|
||||
use crate::{
|
||||
blocks::BlockFacts,
|
||||
chunk::{Chunk, MIN_Y, SECTIONS},
|
||||
chunk::{Chunk, MIN_Y, SECTIONS, Section},
|
||||
fast_hash::FxHashMap,
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
@@ -10,6 +11,13 @@ use std::sync::{Arc, Weak};
|
||||
/// A value snapshot, in ascending section order, with no per-chunk allocation.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Sections(u32);
|
||||
impl Sections {
|
||||
/// The minimum Y of the lowest section in the set from block `min_y` up.
|
||||
pub fn from(self, min_y: i32) -> Option<i32> {
|
||||
let index = ((min_y - MIN_Y) >> 4).max(0) as u32;
|
||||
Sections(self.0 & u32::MAX.checked_shl(index).unwrap_or(0)).next()
|
||||
}
|
||||
}
|
||||
impl Iterator for Sections {
|
||||
type Item = i32;
|
||||
fn next(&mut self) -> Option<i32> {
|
||||
@@ -29,12 +37,20 @@ impl ExactSizeIterator for Sections {}
|
||||
|
||||
struct Cached {
|
||||
chunk: Weak<Chunk>,
|
||||
/// The section each bit of `sections` was read from.
|
||||
read: [Weak<Section>; SECTIONS],
|
||||
sections: Sections,
|
||||
}
|
||||
/// Resident chunks are immutable behind `Arc`; edits use `Arc::make_mut`.
|
||||
/// A weak reference detects both edits and replacement, without retaining block
|
||||
/// data or forcing a deep copy on the next edit. It also prevents address reuse.
|
||||
/// Clear this cache whenever the gameplay facts change (including resource reload).
|
||||
/// Vanilla keeps a count of randomly ticking blocks and fluids per section,
|
||||
/// updated by every `setBlockState`, and ticks the sections where it is above
|
||||
/// zero. Here a section's answer is read from its blocks after any edit:
|
||||
/// resident chunks and sections are immutable behind `Arc` and edited through
|
||||
/// `Arc::make_mut`, so a weak reference tells an edited or replaced one from
|
||||
/// the one read, without retaining block data or forcing a deep copy on the
|
||||
/// next edit, and prevents address reuse. An unchanged chunk costs one
|
||||
/// pointer comparison; a changed one, a comparison per section and a read of
|
||||
/// the sections that changed. Clear this cache whenever the gameplay facts
|
||||
/// change (including resource reload).
|
||||
#[derive(Default)]
|
||||
pub struct RandomTickSections {
|
||||
chunks: FxHashMap<(i32, i32), Cached>,
|
||||
@@ -46,6 +62,7 @@ impl RandomTickSections {
|
||||
pub fn remove(&mut self, key: &(i32, i32)) {
|
||||
self.chunks.remove(key);
|
||||
}
|
||||
/// The sections of `chunk` holding a randomly ticking block or fluid.
|
||||
pub fn get(&mut self, key: (i32, i32), chunk: &Arc<Chunk>, facts: &BlockFacts) -> Sections {
|
||||
self.get_with(key, chunk, |id| facts.get(BlockStateId(id)).random_ticks)
|
||||
}
|
||||
@@ -60,17 +77,23 @@ impl RandomTickSections {
|
||||
}
|
||||
let cached = self.chunks.entry(key).or_insert_with(|| Cached {
|
||||
chunk: Weak::new(),
|
||||
read: std::array::from_fn(|_| Weak::new()),
|
||||
sections: Sections::default(),
|
||||
});
|
||||
if cached.chunk.as_ptr() != Arc::as_ptr(chunk) {
|
||||
let mut mask = 0;
|
||||
for (i, section) in chunk.sections.iter().enumerate() {
|
||||
// Preserve maybe_has, including unused entries and global palettes.
|
||||
if section.blocks.maybe_has(&mut random) {
|
||||
mask |= 1 << i;
|
||||
for (i, (section, read)) in chunk.sections.iter().zip(&mut cached.read).enumerate() {
|
||||
if read.as_ptr() == Arc::as_ptr(section) {
|
||||
continue;
|
||||
}
|
||||
// `isRandomlyTicking`: the blocks themselves, not the palette,
|
||||
// which keeps the states no block uses any more.
|
||||
if section.blocks.has(&mut random) {
|
||||
cached.sections.0 |= 1 << i;
|
||||
} else {
|
||||
cached.sections.0 &= !(1 << i);
|
||||
}
|
||||
*read = Arc::downgrade(section);
|
||||
}
|
||||
cached.sections = Sections(mask);
|
||||
cached.chunk = Arc::downgrade(chunk);
|
||||
}
|
||||
cached.sections
|
||||
@@ -97,10 +120,24 @@ mod tests {
|
||||
[MIN_Y]
|
||||
);
|
||||
assert_eq!(worker.get(0, MIN_Y, 0), 0);
|
||||
// Even after the last ticking block is removed, its unused palette entry counts.
|
||||
// Once the last ticking block is gone the section stops ticking, as
|
||||
// vanilla's count drops to zero, though its palette still lists it.
|
||||
Arc::make_mut(&mut chunk).set(0, MIN_Y, 0, 0);
|
||||
assert_eq!(cache.get_with((0, 0), &chunk, |id| id == 1).len(), 1);
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[0]).compact();
|
||||
assert!(chunk.sections[0].blocks.maybe_has(|id| id == 1));
|
||||
assert_eq!(cache.get_with((0, 0), &chunk, |id| id == 1).len(), 0);
|
||||
// Only the edited section is read again (its palette: air, then 1).
|
||||
Arc::make_mut(&mut chunk).set(0, MIN_Y + 16, 0, 1);
|
||||
let mut asked = Vec::new();
|
||||
let sections = cache.get_with((0, 0), &chunk, |id| {
|
||||
asked.push(id);
|
||||
id == 1
|
||||
});
|
||||
assert_eq!(
|
||||
(sections.collect::<Vec<_>>(), asked),
|
||||
(vec![MIN_Y + 16], vec![0, 1])
|
||||
);
|
||||
Arc::make_mut(&mut chunk).set(0, MIN_Y + 16, 0, 0);
|
||||
Arc::make_mut(&mut Arc::make_mut(&mut chunk).sections[1]).compact();
|
||||
assert_eq!(cache.get_with((0, 0), &chunk, |id| id == 1).len(), 0);
|
||||
Arc::make_mut(&mut chunk).sections[SECTIONS - 1] = Arc::new(Section::default());
|
||||
cache.clear(); // resource reload, with changed facts for the same state IDs
|
||||
@@ -138,13 +175,36 @@ mod tests {
|
||||
}
|
||||
let chunk = Arc::new(chunk);
|
||||
let mut cache = RandomTickSections::default();
|
||||
// Global maybe_has considers the entire ID range, including absent states.
|
||||
// Global palettes: the states the blocks hold, not the whole ID range.
|
||||
assert_eq!(cache.get_with((0, 0), &chunk, |id| id == 40000).len(), 0);
|
||||
cache.clear();
|
||||
assert_eq!(
|
||||
cache
|
||||
.get_with((0, 0), &chunk, |id| id == 40000)
|
||||
.get_with((0, 0), &chunk, |id| id == 299)
|
||||
.collect::<Vec<_>>(),
|
||||
[MIN_Y, MIN_Y + 9 * 16, MIN_Y + (SECTIONS as i32 - 1) * 16]
|
||||
);
|
||||
let sections = cache.get_with((0, 0), &chunk, |id| id == 299);
|
||||
let top = MIN_Y + (SECTIONS as i32 - 1) * 16;
|
||||
let from = |y| sections.from(y);
|
||||
assert_eq!(
|
||||
[
|
||||
from(MIN_Y - 16),
|
||||
from(MIN_Y),
|
||||
from(MIN_Y + 16),
|
||||
from(MIN_Y + 9 * 16)
|
||||
],
|
||||
[
|
||||
Some(MIN_Y),
|
||||
Some(MIN_Y),
|
||||
Some(MIN_Y + 9 * 16),
|
||||
Some(MIN_Y + 9 * 16)
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
[from(top), from(top + 16), from(top + 1000)],
|
||||
[Some(top), None, None]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +261,7 @@ mod tick_parity {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actual_random_ticks_match_original_scan() {
|
||||
fn actual_random_ticks_match_a_block_scan() {
|
||||
let root = std::env::var_os("HORIZON_RESOURCES")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| {
|
||||
@@ -228,6 +288,7 @@ mod tick_parity {
|
||||
let registry = data::load_registry(&root).unwrap();
|
||||
let (mut facts, behaviours) = BlockFacts::load_pair(&root, ®istry).unwrap();
|
||||
let grass = registry.default_state("minecraft:grass_block").unwrap();
|
||||
let stone = registry.default_state("minecraft:stone").unwrap();
|
||||
let chunk = |x| {
|
||||
let mut c = Chunk::empty(x, 0);
|
||||
c.lit = true;
|
||||
@@ -280,6 +341,15 @@ mod tick_parity {
|
||||
40 | 41 => {
|
||||
Arc::make_mut(level.chunks.get_mut(&(0, 0)).unwrap()).lit = step == 41;
|
||||
}
|
||||
70 => {
|
||||
// Every block of a ticking section replaced: its
|
||||
// palette still lists grass, but nothing ticks there.
|
||||
let c = Arc::make_mut(level.chunks.get_mut(&(-1, 0)).unwrap());
|
||||
for i in 0..4096 {
|
||||
c.set(i & 15, MIN_Y + 4 * 16 + (i >> 8), i >> 4 & 15, stone.0);
|
||||
}
|
||||
assert!(c.sections[4].blocks.maybe_has(|id| id == grass.0));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -290,47 +360,43 @@ mod tick_parity {
|
||||
facts.states[grass.0 as usize].random_ticks = step == 60;
|
||||
cache.clear();
|
||||
}
|
||||
let old: Vec<_> = original
|
||||
.chunks
|
||||
.iter()
|
||||
.filter(|(_, c)| c.lit)
|
||||
.map(|(&key, c)| {
|
||||
let sections: Vec<_> = c
|
||||
.sections
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, s)| {
|
||||
s.blocks
|
||||
.maybe_has(|id| facts.get(BlockStateId(id)).random_ticks)
|
||||
})
|
||||
.map(|(i, _)| MIN_Y + i as i32 * 16)
|
||||
.collect();
|
||||
(key, sections)
|
||||
})
|
||||
.collect();
|
||||
let new: Vec<_> = cached
|
||||
.chunks
|
||||
.iter()
|
||||
.filter(|(_, c)| c.lit)
|
||||
.map(|(&key, c)| (key, cache.get(key, c, &facts)))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
old,
|
||||
new.iter()
|
||||
.map(|(k, s)| (*k, s.collect::<Vec<_>>()))
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
// Stand in for an inside-block/scheduled write AFTER eligibility capture.
|
||||
// A write between ticks.
|
||||
if step == 20 {
|
||||
for level in [&mut original, &mut cached] {
|
||||
level.set_raw(BlockPos::new(0, MIN_Y + 16, 0), grass);
|
||||
}
|
||||
}
|
||||
for ((x, z), sections) in old {
|
||||
behaviours.tick_chunk_random(&mut original, &mut a, ChunkPos::new(x, z), sections);
|
||||
let lit = |level: &Level| {
|
||||
let mut keys: Vec<_> = level
|
||||
.chunks
|
||||
.iter()
|
||||
.filter(|(_, c)| c.lit)
|
||||
.map(|(&key, _)| key)
|
||||
.collect();
|
||||
keys.sort();
|
||||
keys
|
||||
};
|
||||
let random = |id| facts.get(BlockStateId(id)).random_ticks;
|
||||
for (x, z) in lit(&original) {
|
||||
// Vanilla's rule, asked as each section is reached: any of its
|
||||
// 4,096 blocks ticks randomly.
|
||||
let reference = |level: &mut Level, from: i32| {
|
||||
let chunk = &level.chunks[&(x, z)];
|
||||
(from..MIN_Y + SECTIONS as i32 * 16)
|
||||
.step_by(16)
|
||||
.find(|&min_y| {
|
||||
(0..16).any(|y| {
|
||||
(0..16).any(|z| (0..16).any(|x| random(chunk.get(x, min_y + y, z))))
|
||||
})
|
||||
})
|
||||
};
|
||||
behaviours.tick_chunk_random(&mut original, &mut a, ChunkPos::new(x, z), reference);
|
||||
}
|
||||
for ((x, z), sections) in new {
|
||||
behaviours.tick_chunk_random(&mut cached, &mut b, ChunkPos::new(x, z), sections);
|
||||
for (x, z) in lit(&cached) {
|
||||
let memoized = |level: &mut Level, from| {
|
||||
cache.get((x, z), &level.chunks[&(x, z)], &facts).from(from)
|
||||
};
|
||||
behaviours.tick_chunk_random(&mut cached, &mut b, ChunkPos::new(x, z), memoized);
|
||||
}
|
||||
assert_eq!(original.reads, cached.reads, "ordered reads at tick {step}");
|
||||
assert_eq!(original.events, cached.events, "events at tick {step}");
|
||||
|
||||
@@ -685,6 +685,47 @@ impl PalettedContainer {
|
||||
Palette::Global => (0..1u32 << self.bits.min(31)).any(predicate),
|
||||
}
|
||||
}
|
||||
/// Whether any entry satisfies `predicate`. Unlike [`Self::maybe_has`],
|
||||
/// palette entries no entry uses any more don't count.
|
||||
pub fn has(&self, mut predicate: impl FnMut(u32) -> bool) -> bool {
|
||||
let list = match &self.palette {
|
||||
Palette::Single(value) => return predicate(*value),
|
||||
Palette::List(list) => list,
|
||||
Palette::Global => {
|
||||
return (0..self.strategy.entries()).any(|i| predicate(self.raw(i) as u32));
|
||||
}
|
||||
};
|
||||
let matching: Vec<bool> = list.iter().map(|&v| predicate(v)).collect();
|
||||
let count = matching.iter().filter(|&&m| m).count();
|
||||
if count == 0 || count == list.len() {
|
||||
return count != 0;
|
||||
}
|
||||
let (bits, entries) = (usize::from(self.bits), self.strategy.entries());
|
||||
let per = 64 / bits;
|
||||
// The words whose fields all hold entries; the last may be partial.
|
||||
let full = entries / per;
|
||||
if count <= 4 {
|
||||
// A field-wise zero test of each word XORed with the matching
|
||||
// index in every field: `(v - lo) & !v & hi` is non-zero exactly
|
||||
// when some field of `v` is zero.
|
||||
let lo = (0..per).fold(0u64, |a, f| a | 1 << (f * bits));
|
||||
let hi = lo << (bits - 1);
|
||||
let words = &self.words[..full];
|
||||
let found = matching
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, m)| **m)
|
||||
.any(|(i, _)| {
|
||||
let pattern = lo * i as u64;
|
||||
words.iter().any(|&w| {
|
||||
let v = w ^ pattern;
|
||||
v.wrapping_sub(lo) & !v & hi != 0
|
||||
})
|
||||
});
|
||||
return found || (full * per..entries).any(|i| matching[self.raw(i)]);
|
||||
}
|
||||
(0..entries).any(|i| matching[self.raw(i)])
|
||||
}
|
||||
/// Heap bytes held by the palette and the storage.
|
||||
pub fn heap_bytes(&self) -> usize {
|
||||
self.words.capacity() * 8
|
||||
@@ -782,9 +823,78 @@ mod tests {
|
||||
let wire =
|
||||
PalettedContainer::from_wire(strategy, bits, palette, words.to_vec()).unwrap();
|
||||
assert_eq!(wire, c);
|
||||
for wanted in [0, 7, 14, 35, 7 * 699, 5] {
|
||||
assert_eq!(
|
||||
c.has(|v| v == wanted || v == wanted + 7),
|
||||
plain.iter().any(|&v| v == wanted || v == wanted + 7),
|
||||
"has {wanted} in {distinct} values"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn has_matches_a_scan_at_every_width() {
|
||||
let mut state = 0x9E37_79B9_7F4A_7C15u64;
|
||||
for (strategy, distinct) in [
|
||||
(BLOCKS, 2u32),
|
||||
(BLOCKS, 3),
|
||||
(BLOCKS, 17),
|
||||
(BLOCKS, 33),
|
||||
(BLOCKS, 65),
|
||||
(BLOCKS, 129),
|
||||
(BIOMES, 2),
|
||||
(BIOMES, 3),
|
||||
(BIOMES, 5),
|
||||
] {
|
||||
let entries = strategy.entries();
|
||||
let mut c = PalettedContainer::new(strategy, 0);
|
||||
let mut plain = vec![0u32; entries];
|
||||
for i in 0..entries {
|
||||
let v = (rng(&mut state) % u64::from(distinct)) as u32;
|
||||
c.set(i, v);
|
||||
plain[i] = v;
|
||||
}
|
||||
// Take some values away again (stale entries), the last index too.
|
||||
for gone in [0, 1, distinct - 1] {
|
||||
for i in 0..entries {
|
||||
if plain[i] == gone {
|
||||
c.set(i, distinct);
|
||||
plain[i] = distinct;
|
||||
}
|
||||
}
|
||||
for m in [3, 5, 7] {
|
||||
let hit = |v: u32| v % m == gone % m;
|
||||
assert_eq!(c.has(hit), plain.iter().any(|&v| hit(v)));
|
||||
}
|
||||
for wanted in 0..=distinct {
|
||||
for other in [wanted, wanted + 1, wanted + 2, wanted + 3, wanted + 4] {
|
||||
let hit = |v: u32| v == wanted || v == other;
|
||||
assert_eq!(
|
||||
c.has(hit),
|
||||
plain.iter().any(|&v| hit(v)),
|
||||
"{distinct} values, {wanted}/{other}, without {gone}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn has_ignores_stale_palette_entries() {
|
||||
let mut c = PalettedContainer::new(BLOCKS, 0);
|
||||
assert!(c.has(|v| v == 0) && !c.has(|v| v == 3));
|
||||
c.set(4095, 3);
|
||||
assert!(c.has(|v| v == 3));
|
||||
c.set(4095, 0);
|
||||
assert!(c.maybe_has(|v| v == 3) && !c.has(|v| v == 3));
|
||||
for v in 1..=300 {
|
||||
c.set(v as usize, v);
|
||||
}
|
||||
assert!(c.is_global() && c.has(|v| v == 300));
|
||||
c.set(300, 0);
|
||||
assert!(c.maybe_has(|v| v == 300) && !c.has(|v| v == 300));
|
||||
}
|
||||
#[test]
|
||||
fn uniform_detection_ignores_stale_palette_entries() {
|
||||
let mut c = PalettedContainer::new(BLOCKS, 0);
|
||||
c.set(10, 3);
|
||||
|
||||
@@ -19,9 +19,9 @@
|
||||
//! `ServerLevel.tickChunk`'s random ticks: for each non-empty section,
|
||||
//! `randomTickSpeed` (game rule, default 3) positions are drawn with
|
||||
//! `Level.getBlockRandomPos` and randomly-ticking block and fluid states are
|
||||
//! ticked. The caller decides which sections are randomly ticking (vanilla
|
||||
//! counts randomly-ticking states per section); [`Behaviours::random_tick`]
|
||||
//! ticks a single position.
|
||||
//! ticked. The caller says which sections are randomly ticking when each is
|
||||
//! reached (vanilla counts randomly-ticking states per section);
|
||||
//! [`Behaviours::random_tick`] ticks a single position.
|
||||
//! 3. [`Behaviours::run_block_events`] runs queued block events (pistons),
|
||||
//! then (after entities) [`Behaviours::tick_block_entities`] advances
|
||||
//! moving pistons ([`Ticks::moving_pistons`]).
|
||||
@@ -69,7 +69,7 @@
|
||||
//! level.time += 1;
|
||||
//! behaviours.tick_scheduled(&mut level, &mut ticks);
|
||||
//! for chunk in ticking_chunks {
|
||||
//! behaviours.tick_chunk_random(&mut level, &mut ticks, chunk, randomly_ticking_section_min_ys(chunk));
|
||||
//! behaviours.tick_chunk_random(&mut level, &mut ticks, chunk, |level, from| level.next_ticking_section(chunk, from));
|
||||
//! }
|
||||
//! behaviours.run_block_events(&mut level, &mut ticks);
|
||||
//! /* tick entities */
|
||||
|
||||
@@ -1615,16 +1615,19 @@ impl Behaviours {
|
||||
};
|
||||
ticks.handling_tick = false;
|
||||
}
|
||||
/// Random-tick one chunk (`ServerLevel.tickChunk` block part). `sections`
|
||||
/// yields the minimum block Y of every section the caller considers
|
||||
/// randomly ticking (vanilla: sections containing randomly-ticking states),
|
||||
/// in ascending order. Draws `randomTickSpeed` positions per section.
|
||||
/// Random-tick one chunk (`ServerLevel.tickChunk` block part). Visits the
|
||||
/// sections from the bottom up and draws `randomTickSpeed` positions in
|
||||
/// each randomly ticking one (`LevelChunkSection.isRandomlyTicking`: it
|
||||
/// holds a randomly ticking block or fluid). `next_ticking(level, min_y)`
|
||||
/// is the minimum Y of the lowest such section from `min_y` up, as the
|
||||
/// chunk is now: vanilla asks as it reaches each section, so the ticks of
|
||||
/// the sections below count.
|
||||
pub fn tick_chunk_random<L: LevelAccess + ?Sized>(
|
||||
&self,
|
||||
level: &mut L,
|
||||
ticks: &mut Ticks,
|
||||
chunk: ChunkPos,
|
||||
sections: impl IntoIterator<Item = i32>,
|
||||
mut next_ticking: impl FnMut(&mut L, i32) -> Option<i32>,
|
||||
) {
|
||||
let speed = level.game_rules().random_tick_speed;
|
||||
if speed <= 0 {
|
||||
@@ -1639,11 +1642,13 @@ impl Behaviours {
|
||||
}
|
||||
}
|
||||
}
|
||||
for min_y in sections {
|
||||
let mut from = level.min_y();
|
||||
while let Some(min_y) = next_ticking(level, from).filter(|&y| y < level.max_y()) {
|
||||
for _ in 0..speed {
|
||||
let pos = ticks.block_random_pos(min_x, min_y, min_z, 15);
|
||||
self.sim(level, ticks).random_tick_at(pos);
|
||||
}
|
||||
from = min_y + 16;
|
||||
}
|
||||
}
|
||||
/// Random-tick a single position (block then fluid), as `tickChunk` does.
|
||||
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package dev.horizonlab.parity;
|
||||
|
||||
import java.io.*;
|
||||
import java.lang.reflect.Field;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.*;
|
||||
import net.minecraft.core.BlockPos;
|
||||
import net.minecraft.util.RandomSource;
|
||||
import net.minecraft.world.level.Level;
|
||||
import net.minecraft.world.level.block.Block;
|
||||
import net.minecraft.world.level.block.state.BlockState;
|
||||
import net.minecraft.world.level.chunk.LevelChunkSection;
|
||||
import net.minecraft.world.level.chunk.PalettedContainerFactory;
|
||||
|
||||
/**
|
||||
* Original oracle for which sections of a chunk random-tick and where: the
|
||||
* real LevelChunkSection block counts (setBlockState, and recalcBlockCounts
|
||||
* for a section built from a filled container, as a loaded one is) and
|
||||
* isRandomlyTicking, with the block part of ServerLevel.tickChunk's section
|
||||
* loop around them (the precipitation draws included, on a level random
|
||||
* seeded 0) and the real Level.getBlockRandomPos drawing the positions.
|
||||
*
|
||||
* Each case line is "randValue speed op...", ops being "s:section:index:state"
|
||||
* (setBlockState, index y << 8 | z << 4 | x), "f:section:a:b:m" (a section
|
||||
* loaded from a container holding b where index % m == m - 1, a elsewhere) and
|
||||
* "t" (one tick). Prints, per tick, every drawn position with whether its
|
||||
* block and its fluid tick randomly, then the final randValue.
|
||||
*/
|
||||
public final class VanillaRandomTickSectionsOracle {
|
||||
static final int SECTIONS = 24;
|
||||
static final int MIN_Y = -64;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
ParityData.init();
|
||||
var factory = PalettedContainerFactory.create(ParityData.access);
|
||||
Level level = ParityData.level;
|
||||
Field randValue = Level.class.getDeclaredField("randValue");
|
||||
randValue.setAccessible(true);
|
||||
try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8));
|
||||
var lines = Files.lines(Path.of(args[0]))) {
|
||||
for (var line : (Iterable<String>) lines::iterator) {
|
||||
if (line.startsWith("#")) continue;
|
||||
String[] words = line.trim().split(" ");
|
||||
randValue.setInt(level, Integer.parseInt(words[0]));
|
||||
int speed = Integer.parseInt(words[1]);
|
||||
RandomSource random = RandomSource.create(0);
|
||||
LevelChunkSection[] sections = new LevelChunkSection[SECTIONS];
|
||||
for (int i = 0; i < SECTIONS; i++) sections[i] = new LevelChunkSection(factory);
|
||||
StringBuilder result = new StringBuilder();
|
||||
for (int w = 2; w < words.length; w++) {
|
||||
String[] op = words[w].split(":");
|
||||
switch (op[0]) {
|
||||
case "s" -> {
|
||||
int index = Integer.parseInt(op[2]);
|
||||
sections[Integer.parseInt(op[1])].setBlockState(index & 15, index >> 8, index >> 4 & 15,
|
||||
state(op[3]));
|
||||
}
|
||||
case "f" -> {
|
||||
BlockState a = state(op[2]), b = state(op[3]);
|
||||
int m = Integer.parseInt(op[4]);
|
||||
var states = factory.createForBlockStates();
|
||||
for (int index = 0; index < 4096; index++) {
|
||||
states.getAndSetUnchecked(index & 15, index >> 8, index >> 4 & 15,
|
||||
index % m == m - 1 ? b : a);
|
||||
}
|
||||
sections[Integer.parseInt(op[1])] = new LevelChunkSection(states, factory.createForBiomes());
|
||||
}
|
||||
case "t" -> {
|
||||
result.append('|');
|
||||
// ServerLevel.tickChunk, for a chunk at 0, 0. Its
|
||||
// precipitation positions use randValue too.
|
||||
for (int i = 0; i < speed; i++) {
|
||||
if (random.nextInt(48) == 0) level.getBlockRandomPos(0, 0, 0, 15);
|
||||
}
|
||||
if (speed <= 0) continue;
|
||||
for (int s = 0; s < SECTIONS; s++) {
|
||||
LevelChunkSection section = sections[s];
|
||||
if (!section.isRandomlyTicking()) continue;
|
||||
int minY = MIN_Y + s * 16;
|
||||
for (int i = 0; i < speed; i++) {
|
||||
BlockPos pos = level.getBlockRandomPos(0, minY, 0, 15);
|
||||
BlockState state = section.getBlockState(pos.getX(), pos.getY() - minY, pos.getZ());
|
||||
result.append(' ').append(pos.getX()).append(',').append(pos.getY()).append(',')
|
||||
.append(pos.getZ()).append(',')
|
||||
.append(state.isRandomlyTicking() ? 'B' : '-')
|
||||
.append(state.getFluidState().isRandomlyTicking() ? 'F' : '-');
|
||||
}
|
||||
}
|
||||
}
|
||||
default -> throw new IllegalArgumentException(words[w]);
|
||||
}
|
||||
}
|
||||
out.println(result.append(" | ").append(randValue.getInt(level)));
|
||||
}
|
||||
}
|
||||
System.exit(0);
|
||||
}
|
||||
|
||||
static BlockState state(String id) {
|
||||
return Block.BLOCK_STATE_REGISTRY.byId(Integer.parseInt(id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare which sections of a chunk random-tick, and the positions drawn in them, with the pinned client.
|
||||
|
||||
Vanilla random-ticks a section while its count of randomly ticking blocks and fluids is above zero
|
||||
(LevelChunkSection.isRandomlyTicking, counted by setBlockState and recalcBlockCounts), whatever its palette still lists.
|
||||
Each case loads sections (every block state fills one, alone, so each state's own answer is compared; others mix a
|
||||
ticking and a non-ticking state), ticks, sets and removes randomly ticking blocks (leaving them in the palette), and
|
||||
ticks again. Vanilla runs ServerLevel.tickChunk's section loop on real sections with the real getBlockRandomPos
|
||||
(VanillaRandomTickSectionsOracle); Horizon runs Behaviours::tick_chunk_random with the game's RandomTickSections
|
||||
(examples/random_tick_sections_probe). Both print every drawn position, whether its block and its fluid tick
|
||||
randomly, and the final randValue.
|
||||
"""
|
||||
import itertools
|
||||
import json
|
||||
import random
|
||||
|
||||
try:
|
||||
from . import lab, oracle_harness as harness
|
||||
except ImportError:
|
||||
import lab, oracle_harness as harness
|
||||
|
||||
COUNT = 3000
|
||||
SECTIONS = 24
|
||||
|
||||
|
||||
def make_cases(build):
|
||||
resources = lab.LOCAL / 'horizon-client' / '26.3'
|
||||
states = json.loads((resources / 'gameplay-facts.json').read_text())['states']
|
||||
ticking = [s['id'] for s in states if s['random_ticks']]
|
||||
still = [s['id'] for s in states if not s['random_ticks']]
|
||||
sweep = itertools.cycle(range(len(states)))
|
||||
rng = random.Random(0x5449434B)
|
||||
lines = [f'#resources {resources}']
|
||||
for _ in range(COUNT):
|
||||
ops = []
|
||||
loaded = rng.sample(range(SECTIONS), 14)
|
||||
for section in loaded[:12]:
|
||||
state = next(sweep)
|
||||
ops.append(f'f:{section}:{state}:{state}:1')
|
||||
mixed = loaded[12:]
|
||||
for section in mixed:
|
||||
ops.append(f'f:{section}:{rng.choice(still)}:{rng.choice(ticking)}:{rng.choice([1, 2, 7, 64, 4096])}')
|
||||
ops.append('t')
|
||||
placed = []
|
||||
for _ in range(rng.randrange(1, 6)):
|
||||
section, index = rng.randrange(SECTIONS), rng.randrange(4096)
|
||||
ops.append(f's:{section}:{index}:{rng.choice(ticking)}')
|
||||
placed.append((section, index))
|
||||
ops.append('t')
|
||||
# Take them away again, and the lone ticking block of the mixed sections:
|
||||
# their palettes keep the states.
|
||||
for section, index in placed + [(section, 4095) for section in mixed]:
|
||||
ops.append(f's:{section}:{index}:{rng.choice([0, 0, rng.choice(still)])}')
|
||||
ops.append('t')
|
||||
ops.append('t')
|
||||
lines.append(f'{rng.randrange(-2**31, 2**31)} {rng.choice([0, 1, 2, 3, 3, 3, 4])} {" ".join(ops)}')
|
||||
path = build / 'cases.txt'
|
||||
path.write_text('\n'.join(lines) + '\n')
|
||||
return path, COUNT
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
harness.differential(
|
||||
'random-tick-sections-parity', 'VanillaRandomTickSectionsOracle', 'random_tick_sections_probe', make_cases,
|
||||
'Which sections of a chunk random-tick (block and fluid counts over loads, sets and removals, not the palette) '
|
||||
'and the positions tickChunk draws in them, with each position\'s block and fluid random-tick flags. The '
|
||||
'blocks\' random-tick behaviour itself is test_random_tick_parity\'s.',
|
||||
sources=[lab.ROOT / 'crates/horizon-client/src/random_tick_sections.rs',
|
||||
lab.ROOT / 'crates/horizon-client/src/chunk.rs',
|
||||
lab.ROOT / 'crates/horizon-core/src/paletted.rs',
|
||||
lab.ROOT / 'crates/horizon-world/src/level/tick.rs',
|
||||
lab.ROOT / 'crates/horizon-world/src/level/ticks.rs'],
|
||||
expected_lines=COUNT)
|
||||
Reference in New Issue
Block a user