Mods read live blocks while replay shows history (#105)

Co-Authored-By: Kimi <noreply@moonshot.ai>
This commit is contained in:
2026-11-01 02:30:48 +03:00
committed by airdef
parent 3de52c252c
commit 6a893473a4
8 changed files with 549 additions and 83 deletions
+9
View File
@@ -10798,6 +10798,15 @@ impl Game<'_> {
HeightmapType::MotionBlocking.is_opaque(properties.heightmap_state(s))
})
}
/// `rain_height` over the real blocks: what a mod's ground query reads, whatever a film's
/// view of an earlier time shows (the weather's rain follows the picture).
fn live_rain_height(&self, x: i32, z: i32) -> i32 {
use horizon_world::{heightmap::HeightmapType, worldgen::terrain::TerrainBlockStates};
let properties = &self.pack.assets.properties;
self.world.live_motion_blocking(x, z, |s| {
HeightmapType::MotionBlocking.is_opaque(properties.heightmap_state(s))
})
}
fn tick_weather_effects(&mut self) {
if self.flash > 0 {
self.flash -= 1;
+14 -66
View File
@@ -4,11 +4,13 @@
//! the game holds: a chunk it doesn't have is `unknown`, never air. The
//! walk and the bit packing are `horizon_mods::world_query`; this is the
//! game's side: which blocks count under each policy, and the chunks.
//! The chunks are read through `horizon_client::world_view`, which puts back
//! every block a film's view of an earlier time shows otherwise: what a mod
//! simulates is the real world, whatever the picture (and #105).
use super::Game;
use horizon_client::chunk::{Chunk, MIN_Y, SECTIONS};
use horizon_client::world::World;
use horizon_client::world_view::{SectionView, WorldProbe};
use horizon_core::geometry::Axis;
use horizon_mods::world_query::{self, BlockProbe, Cell, SectionBits, Trace};
use horizon_mods::world_query::{SectionBits, Trace};
use horizon_mods::{
SectionFill, WorldChanges, WorldPolicy, WorldRay, WorldRayAnswer, WorldSection, WorldVerdict,
};
@@ -43,41 +45,6 @@ fn mask(policy: WorldPolicy) -> u8 {
}
}
/// The blocks of the resident chunks, for [`world_query::trace`].
struct Probe<'a> {
world: &'a World,
tables: &'a WorldTables,
mask: u8,
last: Option<((i32, i32), &'a Arc<Chunk>)>,
cells: usize,
}
impl BlockProbe for Probe<'_> {
fn cell(&mut self, x: i32, y: i32, z: i32) -> Cell<'_> {
self.cells += 1;
let key = (x >> 4, z >> 4);
let chunk = match self.last {
Some((k, c)) if k == key => c,
_ => {
let Some(c) = self.world.chunks.get(&key) else {
return Cell::Unknown;
};
self.last = Some((key, c));
c
}
};
let state = chunk.get(x & 15, y, z & 15) as usize;
if self
.tables
.flags
.get(state)
.is_none_or(|f| f & self.mask == 0)
{
return Cell::Empty;
}
Cell::Solid(self.tables.boxes[state].as_deref())
}
}
impl Game<'_> {
/// The tables for this world, made when it is new.
fn world_tables(&mut self) -> Arc<WorldTables> {
@@ -158,7 +125,7 @@ impl Game<'_> {
let (changed, overflow) = self.world.mod_changes.take();
let changes = WorldChanges {
epoch: self.world.epoch,
revision: self.world.revision,
revision: self.world.live_revision,
overflow,
sections: changed,
};
@@ -192,14 +159,8 @@ impl Game<'_> {
if budget == 0 {
return (unknown(r.id, 0.0), 0);
}
let mut probe = Probe {
world: &self.world,
tables,
mask: mask(r.policy),
last: None,
cells: 0,
};
let t = world_query::trace(
let mut probe = WorldProbe::new(&self.world, &tables.flags, &tables.boxes, mask(r.policy));
let t = horizon_mods::world_query::trace(
&mut probe,
[r.start.0, r.start.1, r.start.2],
[r.end.0, r.end.1, r.end.2],
@@ -238,25 +199,12 @@ impl Game<'_> {
fill: SectionFill::Unknown,
bits: Vec::new(),
};
let Some(chunk) = self.world.chunks.get(&(x, z)) else {
return s;
};
let index = y - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&index) {
s.fill = SectionFill::Empty;
return s;
}
let section = &chunk.sections[index as usize];
let mut states = [0u32; 4096];
if let Some(v) = section.blocks.uniform() {
states.fill(v);
} else {
section.unpack(&mut states);
}
match world_query::section_bits(&states, &tables.flags, mask) {
SectionBits::Empty => s.fill = SectionFill::Empty,
SectionBits::Full => s.fill = SectionFill::Full,
SectionBits::Mixed(bits) => {
match self.world.live_section(x, y, z, &tables.flags, mask) {
SectionView::Unknown => {}
SectionView::Empty => s.fill = SectionFill::Empty,
SectionView::Bits(SectionBits::Empty) => s.fill = SectionFill::Empty,
SectionView::Bits(SectionBits::Full) => s.fill = SectionFill::Full,
SectionView::Bits(SectionBits::Mixed(bits)) => {
s.fill = SectionFill::Mixed;
s.bits = bits.to_vec();
}
+7 -3
View File
@@ -789,8 +789,9 @@ impl Game<'_> {
tickets.truncate(CHUNK_TICKETS);
}
}
/// `render.query-ground`'s answer: the heightmap, or `i32::MIN` for a column whose chunk a
/// mod asked to load and which is not there yet.
/// `render.query-ground`'s answer: the heightmap of the real blocks, or `i32::MIN` for a
/// column whose chunk a mod asked to load and which is not there yet. A film's view of an
/// earlier time is the picture only: a simulation's ground is the one it flies over.
fn mod_ground(&self, x: i32, z: i32) -> i32 {
let key = (x >> 4, z >> 4);
if !self.world.chunks.contains_key(&key)
@@ -798,7 +799,7 @@ impl Game<'_> {
{
return i32::MIN;
}
self.rain_height(x, z)
self.live_rain_height(x, z)
}
/// The mods' persistent sound sources (API level 20): their changes go to the mixer, and the
/// sources of a mod that no longer runs are released. The generation the mods read is the
@@ -941,6 +942,9 @@ impl Game<'_> {
match wanted {
Some(id) => {
if self.world.log.as_ref().is_none_or(|l| l.id != id) {
// A log replaced while it still shows earlier blocks puts them back first:
// only the log knows which block is real where the picture differs.
self.world.view_log(None, usize::MAX, None);
self.world.log = Some(WorldLog::new(id, self.ticks));
}
}
+1
View File
@@ -186,6 +186,7 @@ pub mod win_screen;
pub mod world;
pub mod world_log;
pub mod world_spawn;
pub mod world_view;
pub mod worldborder;
pub mod zip;
pub use horizon_client_core::Result;
+2 -2
View File
@@ -626,7 +626,7 @@ impl Streaming {
let key = (chunk.x, chunk.z);
self.lighting.remove(&key);
self.light_snapshots.remove(&key);
world.chunks.insert(key, Arc::new(chunk));
world.insert_chunk(key, Arc::new(chunk));
self.lit.insert(key);
self.generated_total += 1;
for dz in -1..=1 {
@@ -770,7 +770,7 @@ impl Streaming {
// A chunk saved with its light needs no light job; its unlit
// neighbours still light themselves from it.
let loaded = chunk.light_loaded;
world.chunks.insert(key, Arc::new(chunk));
world.insert_chunk(key, Arc::new(chunk));
if loaded {
self.lit.insert(key);
for sy in 0..SECTIONS as i32 {
+92 -5
View File
@@ -52,7 +52,12 @@ pub struct World {
pub fast_lava: bool,
pub chunks: crate::chunk_map::ChunkMap,
pub random: LegacyRandom,
/// The revision of the blocks shown: a real change, and a view of an earlier time that
/// changes the picture (the renderer and the acoustics follow it). Mods cache on
/// `live_revision`: a film's view is no change of the world they simulate.
pub revision: u64,
/// The revision of the real blocks, which a view of an earlier time leaves alone.
pub live_revision: u64,
pub health_rules: HealthRules,
pub air: BlockStateId,
/// Sections whose geometry changed and need remeshing.
@@ -130,6 +135,23 @@ impl ModChanges {
self.sections.insert((x >> 4, y >> 4, z >> 4));
}
}
/// A column's residency changed (a chunk loaded, was replaced by a reload
/// or is gone): every section of the column counts as changed, for caches
/// keyed to sections. Bounded like `note` is.
pub fn column(&mut self, x: i32, z: i32) {
if self.sections.len() < Self::MAX {
for sy in 0..SECTIONS as i32 {
self.sections.insert((x, sy, z));
}
}
if self.sections.len() >= Self::MAX {
self.overflow = true;
}
}
/// The change log overflowed or the resident columns were cleared: every cached section may be stale.
pub fn overflow(&mut self) {
self.overflow = true;
}
/// What changed since the last call, as the mod reads it.
pub fn take(&mut self) -> (Vec<(i32, i32, i32)>, bool) {
(
@@ -209,6 +231,7 @@ impl World {
chunks: Default::default(),
random: LegacyRandom::new(seed),
revision: 0,
live_revision: 0,
health_rules: HealthRules::default(),
air,
fast_lava: false,
@@ -335,6 +358,7 @@ impl World {
self.watched_writes.push(((x, y, z), previous, state.0));
}
self.revision = self.revision.wrapping_add(1);
self.live_revision = self.live_revision.wrapping_add(1);
if self.mod_changes.watching {
self.mod_changes.note(x, y, z);
}
@@ -378,7 +402,9 @@ impl World {
}
/// A mod's view of the world at an earlier tick (`render.set-world-time-view`): moves it
/// toward `target` by at most `budget` changes, leaving alone the blocks around `protect`
/// (a block position whose neighbourhood stays as it is: the player's). Only the client's copy of the blocks changes. True when it has got there.
/// (a block position whose neighbourhood stays as it is: the player's). Only the picture
/// changes: the renderer meshes these chunks, while a simulation reads the real blocks
/// ([`Self::live_block`]). True when it has got there.
pub fn view_log(
&mut self,
target: Option<u64>,
@@ -400,7 +426,9 @@ impl World {
done
}
}
/// The world as a log's view writes it: only what is drawn changes.
/// The world as a log's view writes it: the picture the renderer meshes changes, and nothing
/// else. The real state of every block written stays in the log (`WorldLog::real`), which is
/// what a simulation reads; the world's own change signals stay the real ones.
struct ShownBlocks<'a>(&'a mut World);
impl crate::world_log::Blocks for ShownBlocks<'_> {
fn get(&self, pos: [i32; 3]) -> Option<u32> {
@@ -419,10 +447,10 @@ impl crate::world_log::Blocks for ShownBlocks<'_> {
};
let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state);
if previous != state {
// The picture changed, so the renderer and the acoustics look at it again; the
// blocks did not, so `live_revision` and `mod_changes` — what mods cache and
// simulate by — stay as they are.
w.revision = w.revision.wrapping_add(1);
if w.mod_changes.watching {
w.mod_changes.note(x, y, z);
}
if w.sound_changes.watching {
w.sound_changes.note(x, y, z);
}
@@ -452,6 +480,65 @@ impl World {
.get(&(x >> 4, z >> 4))
.map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15))
}
/// Inserts a whole current column. A replay keeps its picture, but the real states behind it
/// are refreshed from this column and simulations hear the change.
pub fn insert_chunk(&mut self, key: (i32, i32), mut chunk: Arc<crate::chunk::Chunk>) -> Option<Arc<crate::chunk::Chunk>> {
if let Some(log) = &mut self.log {
let current = self.chunks.get(&key).cloned();
log.reload_column(key.0, key.1, current.as_deref(), Arc::make_mut(&mut chunk));
}
self.live_revision = self.live_revision.wrapping_add(1);
if self.mod_changes.watching {
self.mod_changes.column(key.0, key.1);
}
self.chunks.insert(key, chunk)
}
/// The real block at `(x, y, z)`: what a simulation reads, where a view of an earlier
/// time shows something else for a film ([`Self::view_log`]). [`Self::block`] stays the
/// picture, which is what the renderer meshes.
pub fn live_block(&self, x: i32, y: i32, z: i32) -> BlockStateId {
match self.log.as_ref().and_then(|log| log.real([x, y, z])) {
Some(real) => BlockStateId(real),
None => self.block(x, y, z),
}
}
/// Whether a view of an earlier time shows a block of the column `(x >> 4, z >> 4)`
/// otherwise: until it does, the column reads as the real one.
pub fn view_shows_in_column(&self, cx: i32, cz: i32) -> bool {
self.log
.as_ref()
.is_some_and(|log| log.shows_in_column(cx, cz))
}
/// The blocks of section `(cx, sy, cz)` (vanilla section coordinates, `sy = y >> 4`), in
/// `chunk::index` order, with every block a view of an earlier time shows otherwise put
/// back to its real state.
pub fn live_section_states(&self, cx: i32, sy: i32, cz: i32, states: &mut [u32; 4096]) {
let Some(log) = &self.log else {
return;
};
if !log.shows_in_section(cx, sy, cz) {
return;
}
for ([x, y, z], real) in log.real_in_section(cx, sy, cz) {
states[crate::chunk::index(x, y, z)] = real;
}
}
/// [`Self::motion_blocking`] over the real blocks: a mod's ground query, whatever a view
/// of an earlier time shows.
pub fn live_motion_blocking(
&self,
x: i32,
z: i32,
blocks: impl Fn(BlockStateId) -> bool,
) -> i32 {
if !self.view_shows_in_column(x >> 4, z >> 4) {
return self.motion_blocking(x, z, blocks);
}
(MIN_Y..MIN_Y + (SECTIONS as i32) * 16)
.rev()
.find(|&y| blocks(self.live_block(x, y, z)))
.map_or(MIN_Y, |y| y + 1)
}
/// Whether a block of the box `lo..=hi` may match, from the palettes of
/// the sections it reaches (a palette of the whole registry may hold
/// anything): `false` means [`Self::block`] matches in none of its cells,
+128 -7
View File
@@ -7,6 +7,11 @@
//! while the cursor is behind the end is logged and kept as the block's real state, but not
//! written (it lies after the view's time): it shows when the cursor passes it, or when the
//! view ends and every displaced block is put back. Pure over [`Blocks`]; the world is one.
//!
//! A block written here is the picture (what the renderer meshes): the real state of every
//! displaced block stays in `shown`, and what stands for the simulation reads it
//! ([`WorldLog::real`], `World::live_block`). Moving the view changes the picture alone, so it
//! is no block change of the world a mod simulates.
use std::collections::{HashMap, VecDeque};
pub type Pos = [i32; 3];
@@ -39,6 +44,10 @@ pub struct WorldLog {
cursor: u64,
/// Blocks shown other than they are: their real state.
shown: HashMap<Pos, u32>,
/// How many blocks of each section (`x >> 4, y >> 4, z >> 4`) and column (`x >> 4,
/// z >> 4`) are in `shown`: absent means none, so a query passes those over whole.
sections: HashMap<(i32, i32, i32), usize>,
columns: HashMap<(i32, i32), usize>,
cap: usize,
/// The tick the log began, and the tick of the newest change it let go.
start: u64,
@@ -56,6 +65,8 @@ impl WorldLog {
base: 0,
cursor: 0,
shown: HashMap::new(),
sections: HashMap::new(),
columns: HashMap::new(),
cap: cap.max(1),
start: tick,
lost: None,
@@ -82,6 +93,54 @@ impl WorldLog {
pub fn displaced(&self) -> usize {
self.shown.len()
}
/// The real state of a block the view shows otherwise, which is what a simulation reads:
/// None where the block is shown as it is.
pub fn real(&self, pos: Pos) -> Option<u32> {
self.shown.get(&pos).copied()
}
/// Whether the view shows a block of section `(x >> 4, y >> 4, z >> 4)` otherwise.
pub fn shows_in_section(&self, cx: i32, sy: i32, cz: i32) -> bool {
self.sections.contains_key(&(cx, sy, cz))
}
/// Whether the view shows a block of column `(x >> 4, z >> 4)` otherwise.
pub fn shows_in_column(&self, cx: i32, cz: i32) -> bool {
self.columns.contains_key(&(cx, cz))
}
/// The blocks of a section the view shows otherwise, with their real states.
pub fn real_in_section(
&self,
cx: i32,
sy: i32,
cz: i32,
) -> impl Iterator<Item = (Pos, u32)> + '_ {
self.shown.iter().filter_map(move |(&pos, &real)| {
(pos[0] >> 4 == cx && pos[1] >> 4 == sy && pos[2] >> 4 == cz).then_some((pos, real))
})
}
/// A whole column arrived from the server or generation: its current blocks replace the real
/// states saved behind the picture, while the picture itself stays at the replay's time.
pub fn reload_column(
&mut self,
cx: i32,
cz: i32,
current: Option<&crate::chunk::Chunk>,
next: &mut crate::chunk::Chunk,
) {
let changes: Vec<(Pos, u32, u32)> = self
.shown
.iter()
.filter(|(pos, _)| pos[0] >> 4 == cx && pos[2] >> 4 == cz)
.map(|(&pos, &real)| {
let fresh = next.get(pos[0] & 15, pos[1], pos[2] & 15);
let picture = current.map_or(real, |chunk| chunk.get(pos[0] & 15, pos[1], pos[2] & 15));
(pos, fresh, picture)
})
.collect();
for (pos, fresh, picture) in changes {
next.set(pos[0] & 15, pos[1], pos[2] & 15, picture);
self.shown.insert(pos, fresh);
}
}
/// The first sequence number whose change came after tick `t` (the world at `t` is the real
/// one with those undone).
fn seq_after(&self, t: u64) -> u64 {
@@ -114,7 +173,7 @@ impl WorldLog {
self.cursor = self.end();
}
if deferred {
self.shown.insert(pos, new);
self.displace(pos, new);
if at_end {
// Displaced blocks wait for their restoration with the cursor at the end.
self.cursor = self.end();
@@ -162,7 +221,7 @@ impl WorldLog {
.collect();
for (pos, real) in rest {
blocks.put(pos, real);
self.shown.remove(&pos);
self.put_back(pos);
}
}
self.cursor == goal && (goal != self.end() || self.shown.is_empty())
@@ -186,14 +245,46 @@ impl WorldLog {
None => return,
},
};
if !blocks.put(pos, state) {
self.shown.remove(&pos);
} else if state == real {
self.shown.remove(&pos);
if !blocks.put(pos, state) || state == real {
self.put_back(pos);
} else {
self.shown.insert(pos, real);
self.displace(pos, real);
}
}
/// Keeps `real` as the real state of a block shown otherwise.
fn displace(&mut self, pos: Pos, real: u32) {
if self.shown.insert(pos, real).is_some() {
return;
}
count(
&mut self.sections,
(pos[0] >> 4, pos[1] >> 4, pos[2] >> 4),
1,
);
count(&mut self.columns, (pos[0] >> 4, pos[2] >> 4), 1);
}
/// Forgets a displaced block: what is shown is its real state again.
fn put_back(&mut self, pos: Pos) {
if self.shown.remove(&pos).is_none() {
return;
}
count(
&mut self.sections,
(pos[0] >> 4, pos[1] >> 4, pos[2] >> 4),
-1,
);
count(&mut self.columns, (pos[0] >> 4, pos[2] >> 4), -1);
}
}
/// Keeps the number of displaced blocks under `key`, dropping it at zero.
fn count<K: std::hash::Hash + Eq>(counts: &mut HashMap<K, usize>, key: K, by: isize) {
let n = counts.get(&key).copied().unwrap_or(0) as isize + by;
if n > 0 {
counts.insert(key, n as usize);
} else {
counts.remove(&key);
}
}
#[cfg(test)]
@@ -369,4 +460,34 @@ mod tests {
log.view(&mut w, None, 100, all);
assert_eq!(w.shows([0, 0, 0]), 7);
}
#[test]
fn the_real_blocks_of_a_view_are_read_where_it_shows_others() {
let (mut w, mut log) = raid();
log.view(&mut w, Some(5), 100, all);
// The sections and columns the view touches, and the real state of what it shows otherwise.
assert_eq!(log.real([0, 0, 0]), Some(7));
assert_eq!(log.real([9, 0, 0]), None);
assert!(log.shows_in_column(0, 0));
assert!(!log.shows_in_column(1, 0));
assert!(log.shows_in_section(0, 0, 0));
assert!(!log.shows_in_section(0, 1, 0));
let displaced: Vec<_> = log.real_in_section(0, 0, 0).collect();
assert_eq!(displaced.len(), 3);
for (pos, real) in [([0, 0, 0], 7), ([1, 0, 0], 0), ([2, 0, 0], 0)] {
assert!(displaced.contains(&(pos, real)));
}
// A change arriving behind the view is the block's real state, shown nowhere.
w.set(&mut log, 40, [20, 20, 3], 5);
assert_eq!(w.shows([20, 20, 3]), 0);
assert_eq!(log.real([20, 20, 3]), Some(5));
assert!(log.shows_in_column(1, 0) && log.shows_in_section(1, 1, 0));
// The end puts every block back: nothing is left to read.
assert!(log.view(&mut w, None, 100, all));
for pos in [[0, 0, 0], [20, 20, 3]] {
assert_eq!(log.real(pos), None);
}
assert!(!log.shows_in_column(0, 0) && !log.shows_in_column(1, 0));
assert!(!log.shows_in_section(0, 0, 0) && !log.shows_in_section(1, 1, 0));
}
}
+296
View File
@@ -0,0 +1,296 @@
//! The world as a mod's simulation reads it (capability `render`, AirDef fork): the real
//! blocks. A film's view of an earlier time (`World::view_log`) is written into the chunks
//! the renderer meshes, so a query that stands for a simulation has to read past it: a raid
//! does not go back in time with the picture (#105).
use crate::chunk::{Chunk, MIN_Y, SECTIONS};
use crate::world::World;
use horizon_mods::world_query::{BlockProbe, Cell, SectionBits, section_bits};
use std::sync::Arc;
/// The resident chunks, with every block a view of an earlier time shows otherwise put back
/// to its real state.
pub struct WorldProbe<'a> {
world: &'a World,
/// Per state: the policy bits that it stops.
flags: &'a [u8],
/// Per state: its collision boxes in block space; none for a full cube (or a state that
/// stops nothing).
boxes: &'a [Option<Box<[[f64; 6]]>>],
mask: u8,
/// The last column read, and whether the view shows any of its blocks otherwise.
last: Option<((i32, i32), &'a Arc<Chunk>, bool)>,
/// Cells read.
pub cells: usize,
}
impl<'a> WorldProbe<'a> {
pub fn new(
world: &'a World,
flags: &'a [u8],
boxes: &'a [Option<Box<[[f64; 6]]>>],
mask: u8,
) -> Self {
Self {
world,
flags,
boxes,
mask,
last: None,
cells: 0,
}
}
}
impl BlockProbe for WorldProbe<'_> {
fn cell(&mut self, x: i32, y: i32, z: i32) -> Cell<'_> {
self.cells += 1;
let key = (x >> 4, z >> 4);
let (chunk, view) = match self.last {
Some((k, chunk, view)) if k == key => (chunk, view),
_ => {
let Some(chunk) = self.world.chunks.get(&key) else {
return Cell::Unknown;
};
let view = self.world.view_shows_in_column(key.0, key.1);
self.last = Some((key, chunk, view));
(chunk, view)
}
};
// Only a column the view touches costs a lookup per block.
let state = if view {
self.world.live_block(x, y, z).0
} else {
chunk.get(x & 15, y, z & 15)
} as usize;
if self.flags.get(state).is_none_or(|f| f & self.mask == 0) {
return Cell::Empty;
}
Cell::Solid(self.boxes[state].as_deref())
}
}
/// A section as a mod's query reads it: the real blocks, never a film's picture.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SectionView {
/// No chunk holds the column.
Unknown,
/// The section lies outside the world's height: nothing there.
Empty,
/// Its real blocks under the state table.
Bits(SectionBits),
}
impl World {
/// A section (`x >> 4, y >> 4, z >> 4`: vanilla section coordinates) under a state table
/// and a policy mask, read from the real blocks.
pub fn live_section(&self, cx: i32, sy: i32, cz: i32, flags: &[u8], mask: u8) -> SectionView {
let Some(chunk) = self.chunks.get(&(cx, cz)) else {
return SectionView::Unknown;
};
let index = sy - (MIN_Y >> 4);
if !(0..SECTIONS as i32).contains(&index) {
return SectionView::Empty;
}
let section = &chunk.sections[index as usize];
let mut states = [0u32; 4096];
if let Some(v) = section.blocks.uniform() {
states.fill(v);
} else {
section.unpack(&mut states);
}
self.live_section_states(cx, sy, cz, &mut states);
SectionView::Bits(section_bits(&states, flags, mask))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::chunk::index;
use crate::world_log::WorldLog;
use horizon_mods::world_query::{Trace, trace};
use horizon_world::registry::BlockStateId;
use std::sync::Arc;
const AIR: u32 = 0;
const STONE: u32 = 1;
/// The policy bits of `COLLISION | SIGHT | SOUND`, as `game::mod_world` makes them.
const ALL: u8 = 0b111;
/// The section of the wall at y 100 (`y >> 4`).
const SY: i32 = 6;
type Tables = (Vec<u8>, Vec<Option<Box<[[f64; 6]]>>>);
/// A floor at y 70 and a wall at x 10, z 0, in the one resident chunk.
fn walled() -> World {
let mut world = World::new(BlockStateId(AIR), 0);
world.chunks.insert((0, 0), Arc::new(Chunk::empty(0, 0)));
for z in 0..=2 {
for x in 0..=14 {
world.set(x, 70, z, BlockStateId(STONE)).unwrap();
}
}
world.set(10, 100, 0, BlockStateId(STONE)).unwrap();
world
}
/// State flags and collision boxes: stone stops every policy, as a full cube.
fn tables() -> Tables {
let mut flags = vec![0u8; 8];
flags[STONE as usize] = ALL;
(flags, vec![None; 8])
}
/// A collision flight from x 9.5 to 11.5 at y 100.5, along `z`, as a mod asks one.
fn ray(world: &World, z: i32, tables: &Tables) -> Trace {
let mut probe = WorldProbe::new(world, &tables.0, &tables.1, 0b001);
let z = f64::from(z) + 0.5;
trace(&mut probe, [9.5, 100.5, z], [11.5, 100.5, z])
}
/// Whether the section's presented bits have the block `(10, y, 0)` set.
fn presented_bit(world: &World, flags: &[u8], y: i32) -> bool {
let chunk = world.chunks.get(&(0, 0)).unwrap();
let mut states = [0u32; 4096];
chunk.sections[((y - MIN_Y) >> 4) as usize].unpack(&mut states);
let i = index(10, y, 0);
match section_bits(&states, flags, 0b001) {
SectionBits::Mixed(bits) => bits[i >> 3] & (1 << (i & 7)) != 0,
_ => false,
}
}
#[test]
fn a_films_view_of_earlier_blocks_is_no_change_of_the_simulated_world() {
let tables = tables();
let mut world = walled();
// The wall stops the flight.
let wall = ray(&world, 0, &tables);
assert!(
matches!(
wall,
Trace::Hit {
block: [10, 100, 0],
..
}
),
"{wall:?}"
);
world.log = Some(WorldLog::new(1, 0));
// The raid breaks it: a real change, logged.
world.log_tick = 10;
world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
let cleared = ray(&world, 0, &tables);
assert_eq!(cleared, Trace::Clear);
assert_eq!(
world.live_section(0, SY, 0, &tables.0, 0b001),
SectionView::Bits(SectionBits::Empty)
);
let live_revision = world.live_revision;
// Watching for block changes, as a mod's world query does.
world.mod_changes.watching = true;
let _ = world.mod_changes.take();
// The film goes back to before the blast: the picture has the wall, the world has not.
assert!(world.view_log(Some(0), 100, None));
assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the picture");
assert_eq!(world.live_block(10, 100, 0), BlockStateId(AIR), "the world");
assert!(presented_bit(&world, &tables.0, 100));
assert_eq!(
world.live_section(0, SY, 0, &tables.0, 0b001),
SectionView::Bits(SectionBits::Empty)
);
assert_eq!(
ray(&world, 0, &tables),
cleared,
"the same flight through the passage the raid made"
);
// The picture changed; no block change reached the mod, and its revision stands.
assert_eq!(world.mod_changes.take(), (Vec::new(), false));
assert_eq!(world.live_revision, live_revision);
// A real change during the film: the simulation meets it, the picture stays at tick 0.
world.log_tick = 20;
world.set(10, 100, 2, BlockStateId(STONE)).unwrap();
assert_eq!(world.block(10, 100, 2), BlockStateId(AIR), "not shown");
assert!(
matches!(
ray(&world, 2, &tables),
Trace::Hit {
block: [10, 100, 2],
..
}
),
"a change behind the view is the real block"
);
assert_ne!(world.mod_changes.take(), (Vec::new(), false));
assert_eq!(world.live_revision, live_revision + 1);
// Seeking about changes nothing else either.
assert!(world.view_log(None, usize::MAX, None));
assert_eq!(world.mod_changes.take(), (Vec::new(), false));
assert_eq!(world.live_revision, live_revision + 1);
// The film ends: the picture is the real world again, and so are both flights.
world.log = None;
assert_eq!(world.block(10, 100, 0), BlockStateId(AIR));
assert_eq!(world.block(10, 100, 2), BlockStateId(STONE));
assert_eq!(ray(&world, 0, &tables), cleared);
assert!(matches!(
ray(&world, 2, &tables),
Trace::Hit {
block: [10, 100, 2],
..
}
));
}
#[test]
fn a_ground_query_reads_the_real_blocks() {
let mut world = walled();
let opaque = |s: BlockStateId| s.0 != AIR;
assert_eq!(world.motion_blocking(10, 0, opaque), 101);
world.log = Some(WorldLog::new(1, 0));
world.log_tick = 10;
world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
assert_eq!(world.live_motion_blocking(10, 0, opaque), 71);
world.view_log(Some(0), 100, None);
assert_eq!(world.motion_blocking(10, 0, opaque), 101, "the picture");
assert_eq!(world.live_motion_blocking(10, 0, opaque), 71, "the world");
// A column of the same chunk with no displaced block reads the same height either way.
assert_eq!(world.motion_blocking(5, 0, opaque), 71);
assert_eq!(world.live_motion_blocking(5, 0, opaque), 71);
world.view_log(None, usize::MAX, None);
assert_eq!(world.motion_blocking(10, 0, opaque), 71);
assert_eq!(world.live_motion_blocking(10, 0, opaque), 71);
}
#[test]
fn a_server_chunk_replacement_refreshes_the_real_blocks_behind_the_picture() {
let tables = tables();
let mut world = walled();
world.log = Some(WorldLog::new(1, 0));
world.log_tick = 10;
world.set(10, 100, 0, BlockStateId(AIR)).unwrap();
world.view_log(Some(0), 100, None);
assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the old wall is shown");
world.mod_changes.watching = true;
let _ = world.mod_changes.take();
let mut replacement = Chunk::empty(0, 0);
replacement.set(10, 100, 2, STONE);
world.insert_chunk((0, 0), Arc::new(replacement));
assert_eq!(world.live_block(10, 100, 0), BlockStateId(AIR));
assert_eq!(world.live_block(10, 100, 2), BlockStateId(STONE));
assert_eq!(world.block(10, 100, 0), BlockStateId(STONE), "the picture is unchanged");
assert!(matches!(ray(&world, 2, &tables), Trace::Hit { block: [10, 100, 2], .. }));
assert_eq!(world.mod_changes.take().0.len(), crate::chunk::SECTIONS);
}
#[test]
fn a_ray_into_an_unloaded_column_is_unknown() {
let tables = tables();
let world = walled();
let mut probe = WorldProbe::new(&world, &tables.0, &tables.1, 0b001);
assert_eq!(
trace(&mut probe, [20.5, 100.5, 0.5], [40.5, 100.5, 0.5]),
Trace::Unknown { known_to: 0.0 }
);
}
}