Merge pull request #1201 from pirut/claude/upstream-chunk-bookkeeping

🤖 Agent: merged after verify passed and the integration run on the desktop (main 34c3c1cf + the 14 contributor PRs: workspace tests 1,869/0, launcher 113, parity --changed 320/0).
This commit is contained in:
Ludovic Marie
2026-10-22 19:52:15 +02:00
committed by GitHub
3 changed files with 560 additions and 22 deletions
+98 -14
View File
@@ -242,6 +242,30 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool {
dx * dx + dz * dz < i64::from(r) * i64::from(r)
}
/// The view's queue around a new centre: the queued chunks still tracked, then
/// the tracked ones neither sent nor queued, closest first (a stable sort, so
/// equally close chunks keep their order).
fn requeue(
queue: &mut Vec<(i32, i32)>,
sent: &crate::fast_hash::FxHashSet<(i32, i32)>,
(cx, cz): (i32, i32),
r: i32,
) {
queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
// A walking player changes chunk every few ticks with hundreds of chunks
// queued: a set, not a scan of the queue for each of the view's chunks.
let mut queued: crate::fast_hash::FxHashSet<(i32, i32)> = queue.iter().copied().collect();
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && queued.insert(key) {
queue.push(key);
}
}
}
queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
/// What a level's players were last told of its clock and weather.
#[derive(Clone, Copy)]
struct LevelSync {
@@ -1295,20 +1319,7 @@ impl Hub {
g.sent_chunks.remove(&(x, z));
g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] }));
}
g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1)
&& !g.sent_chunks.contains(&key)
&& !g.chunk_queue.contains(&key)
{
g.chunk_queue.push(key);
}
}
}
g.chunk_queue
.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
requeue(&mut g.chunk_queue, &g.sent_chunks, (cx, cz), r);
}
/// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first,
@@ -2485,3 +2496,76 @@ fn ticking_state(rate: f32, frozen: bool) -> C {
w.bool(frozen);
raw(ids::TICKING_STATE, w.data)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fast_hash::FxHashSet;
/// `requeue` as it was, scanning the queue for each chunk of the view.
fn requeue_scan(
queue: &mut Vec<(i32, i32)>,
sent: &FxHashSet<(i32, i32)>,
(cx, cz): (i32, i32),
r: i32,
) {
queue.retain(|&(x, z)| tracked(cx, cz, r, x, z));
for dz in -r - 2..=r + 2 {
for dx in -r - 2..=r + 2 {
let key = (cx + dx, cz + dz);
if tracked(cx, cz, r, key.0, key.1) && !sent.contains(&key) && !queue.contains(&key)
{
queue.push(key);
}
}
}
queue.sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2));
}
/// A player walking a loop, sending a few chunks a tick: the queue
/// after every move is the one the scan built.
#[test]
fn requeue_matches_the_scan() {
for r in [2, 5, 10, 12, 32] {
let (mut a, mut b) = (Vec::new(), Vec::new());
let mut sent = FxHashSet::default();
for step in 0..60i32 {
let center = ((step % 17) - 8, (step * 3 % 11) - 5);
requeue(&mut a, &sent, center, r);
requeue_scan(&mut b, &sent, center, r);
assert_eq!(a, b, "radius {r}, step {step}");
for key in a.drain(..a.len().min(7)) {
sent.insert(key);
}
b.drain(..b.len().min(7));
sent.retain(|&(x, z)| tracked(center.0, center.1, r, x, z));
}
}
}
/// cargo test --release -p horizon-client --lib lan::hub::tests::requeue_cost -- --ignored --nocapture
#[test]
#[ignore]
fn requeue_cost() {
for r in [10, 16, 32] {
for (name, f) in [
("scan", requeue_scan as fn(&mut _, &_, _, _)),
("set", requeue as fn(&mut _, &_, _, _)),
] {
let sent = FxHashSet::default();
let mut queue = Vec::new();
let start = std::time::Instant::now();
let moves = 200;
for step in 0..moves {
// Nothing sent yet (an explorer waiting on generation).
f(&mut queue, &sent, (step, 0), r);
}
let per = start.elapsed().as_secs_f64() * 1e6 / f64::from(moves);
println!(
"view {r}: {name} {per:.1} us per chunk crossed, {} queued",
queue.len()
);
}
}
}
}
+238
View File
@@ -276,6 +276,8 @@ pub struct Streaming {
/// chunks finish out to `radius + 1` (Chebyshev) and generation reaches
/// past that as around the player. They are generated and kept but not meshed.
pub extra: Vec<((i32, i32), i32)>,
/// `extra`'s squares as a grid, made again when `extra` changes.
cover: Option<ExtraCover>,
/// Mesh the sections for drawing (false on a server thread).
pub mesh: bool,
}
@@ -391,6 +393,7 @@ impl GenerationScan {
radius: input.ranges.radius,
extra: input.ranges.extra,
forced: input.ranges.forced,
cover: input.ranges.cover,
};
self.remember(ranges, input.world);
} else {
@@ -562,6 +565,7 @@ impl Streaming {
meshed_total: 0,
remote: false,
extra: Vec::new(),
cover: None,
mesh: true,
}
}
@@ -808,6 +812,7 @@ impl Streaming {
if self.paused {
return (uploads, Vec::new());
}
ExtraCover::refresh(&mut self.cover, &self.extra);
self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -982,6 +987,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
};
let (protos, generating) = (&self.protos, &self.generating);
self.decoration_order.retain(|x, z| {
@@ -1109,6 +1115,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
};
self.waiting.retain(|&(x, sy, z)| {
let back = ranges.in_view(x, z);
@@ -1185,6 +1192,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
},
world,
generating: &self.generating,
@@ -1280,6 +1288,7 @@ impl Streaming {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: ExtraCover::matching(&self.cover, &self.extra),
}
}
fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool {
@@ -1365,6 +1374,100 @@ struct Ranges<'a> {
radius: i32,
extra: &'a [((i32, i32), i32)],
forced: &'a HashSet<(i32, i32)>,
/// `extra` as a grid, when one was made for it: `in_extra` without a
/// scan of every area.
cover: Option<&'a ExtraCover>,
}
/// For every column near the extra areas, how far it lies outside the
/// nearest one's square (Chebyshev distance less its radius; 0 inside). A server has an area per player, and streaming asks of every
/// loaded and wanted column whether one reaches it, several times a tick:
/// with fifty players, a scan of fifty squares per question.
struct ExtraCover {
extra: Vec<((i32, i32), i32)>,
x0: i32,
z0: i32,
width: u32,
depth: u32,
cells: Box<[i8]>,
}
impl ExtraCover {
/// The largest margin the grid answers for; beyond it (and outside the
/// grid) a column is further than that from every square.
const REACH: i32 = 4;
/// The largest grid, in columns (a mebibyte).
const CELLS: u64 = 1 << 20;
fn matching<'a>(
cover: &'a Option<ExtraCover>,
extra: &[((i32, i32), i32)],
) -> Option<&'a ExtraCover> {
cover.as_ref().filter(|c| c.extra == extra)
}
/// Make the grid again if `extra` changed; none for one area or none
/// (a scan is as quick), or areas too far apart.
fn refresh(cover: &mut Option<ExtraCover>, extra: &[((i32, i32), i32)]) {
if cover.as_ref().is_some_and(|c| c.extra == extra) {
return;
}
*cover = Self::new(extra);
}
fn new(extra: &[((i32, i32), i32)]) -> Option<Self> {
if extra.len() < 2 || extra.iter().any(|&(_, r)| !(0..=64).contains(&r)) {
return None;
}
let k = i64::from(Self::REACH);
let (mut x0, mut z0, mut x1, mut z1) = (i64::MAX, i64::MAX, i64::MIN, i64::MIN);
for &((x, z), r) in extra {
let (x, z, r) = (i64::from(x), i64::from(z), i64::from(r) + k);
(x0, z0, x1, z1) = (x0.min(x - r), z0.min(z - r), x1.max(x + r), z1.max(z + r));
}
let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64);
let fits = |lo: i64, hi: i64| lo >= i64::from(i32::MIN) && hi <= i64::from(i32::MAX);
if width * depth > Self::CELLS || !fits(x0, x1) || !fits(z0, z1) {
return None;
}
let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32);
let mut cells = vec![(Self::REACH + 1) as i8; (width * depth) as usize].into_boxed_slice();
// Inside a square counts as 0: no margin asked for is below it. Each
// row of a square is a run of one value with a slope at either end.
let lower = |run: &mut [i8], v: i8| run.iter_mut().for_each(|c| *c = (*c).min(v));
for &((cx, cz), r) in extra {
let reach = r + Self::REACH;
for dz in -reach..=reach {
let start = (cz + dz - z0) as usize * width as usize + (cx - x0) as usize;
let row = &mut cells[start - reach as usize..=start + reach as usize];
let flat = dz.abs().max(r);
let centre = reach as usize;
lower(
&mut row[centre - flat as usize..=centre + flat as usize],
(flat - r) as i8,
);
for d in flat + 1..=reach {
let v = (d - r) as i8;
lower(&mut row[centre - d as usize..=centre - d as usize], v);
lower(&mut row[centre + d as usize..=centre + d as usize], v);
}
}
}
Some(Self {
extra: extra.to_vec(),
x0,
z0,
width,
depth,
cells,
})
}
/// Whether (x, z) is within `margin` of an area's square, for a
/// `margin` up to `REACH`.
fn within(&self, x: i32, z: i32, margin: i32) -> bool {
let (dx, dz) = (
x.wrapping_sub(self.x0) as u32,
z.wrapping_sub(self.z0) as u32,
);
dx < self.width
&& dz < self.depth
&& i32::from(self.cells[(dz * self.width + dx) as usize]) <= margin
}
}
impl Ranges<'_> {
/// `distance`, or `rings` while the level loading screen is up.
@@ -1441,6 +1544,11 @@ impl Ranges<'_> {
/// Within `margin` of an extra area's square (Chebyshev distance, as
/// vanilla's ticket levels spread).
fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool {
if let Some(cover) = self.cover
&& (0..=ExtraCover::REACH).contains(&margin)
{
return cover.within(x, z, margin);
}
self.extra
.iter()
.any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin)
@@ -1554,6 +1662,7 @@ mod tests {
radius: self.radius,
extra: &self.extra,
forced: &self.forced,
cover: None,
},
world: &self.world,
generating: &self.generating,
@@ -1866,6 +1975,7 @@ mod tests {
radius,
extra: &[],
forced: &forced,
cover: None,
};
let square = |x: i32, z: i32, n: i32| {
(-n..=n).flat_map(move |dz| (-n..=n).map(move |dx| (x + dx, z + dz)))
@@ -1920,6 +2030,7 @@ mod tests {
radius: 12,
extra: &[],
forced: &forced,
cover: None,
};
let at = |dx: i32, dz: i32| (2 + dx, -1 + dz);
let key = |(x, z): (i32, i32), loading| r.priority(x, z, loading);
@@ -1945,6 +2056,7 @@ mod tests {
radius,
extra: &[((radius * 2 + 9, 3), 4)],
forced: &forced,
cover: None,
};
let span = radius * 3 + 20;
for x in -span..=span {
@@ -1984,6 +2096,7 @@ mod tests {
radius: 2,
extra: &extra,
forced: &forced,
cover: None,
};
let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0);
for x in 40 - view - 8..=40 + view + 8 {
@@ -2021,3 +2134,128 @@ mod tests {
}
}
}
#[cfg(test)]
mod cover_tests {
use super::*;
fn areas(seed: &mut u64, n: usize, spread: i32) -> Vec<((i32, i32), i32)> {
let mut next = |m: i32| {
*seed ^= *seed << 13;
*seed ^= *seed >> 7;
*seed ^= *seed << 17;
(*seed % (2 * m as u64 + 1)) as i32 - m
};
(0..n)
.map(|_| ((next(spread), next(spread)), 2 + next(14).abs()))
.collect()
}
/// Every question streaming asks gets the same answer with the grid.
#[test]
fn the_grid_answers_as_the_scan() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let forced: HashSet<(i32, i32)> = [(40, -40)].into();
for case in 0..60 {
let extra = areas(&mut seed, 2 + case % 20, [4, 30, 120][case % 3]);
let cover = ExtraCover::new(&extra).expect("a grid");
let ranges = |cover| Ranges {
center: (3, -2),
radius: 10,
extra: &extra,
forced: &forced,
cover,
};
let (scan, grid) = (ranges(None), ranges(Some(&cover)));
let span = [4, 30, 120][case % 3] + 40;
for z in -span..=span {
for x in -span..=span {
for m in 0..=ExtraCover::REACH + 2 {
assert_eq!(
scan.in_extra(x, z, m),
grid.in_extra(x, z, m),
"case {case} ({x}, {z}) {m}"
);
}
for d in [false, true] {
assert_eq!(scan.unloaded(x, z, d), grid.unloaded(x, z, d));
assert_eq!(scan.requested(x, z, d), grid.requested(x, z, d));
assert_eq!(scan.chunk_kept(x, z, d), grid.chunk_kept(x, z, d));
}
}
}
}
}
#[test]
fn a_stale_or_impossible_grid_is_not_used() {
let mut cover = None;
ExtraCover::refresh(&mut cover, &[((0, 0), 11), ((5, 5), 11)]);
assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 5), 11)]).is_some());
assert!(ExtraCover::matching(&cover, &[((0, 0), 11), ((5, 6), 11)]).is_none());
// Too far apart for a mebibyte of grid, and one area alone: scans.
assert!(ExtraCover::new(&[((0, 0), 11), ((100_000, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((0, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((i32::MAX - 1, 0), 11), ((i32::MAX - 3, 0), 11)]).is_none());
assert!(ExtraCover::new(&[((0, i32::MAX - 1), 11), ((0, i32::MAX - 3), 11)]).is_none());
assert!(ExtraCover::new(&[((0, i32::MIN + 1), 11), ((0, i32::MIN + 3), 11)]).is_none());
}
/// cargo test --release -p horizon-client --lib cover_tests::cover_cost -- --ignored --nocapture
#[test]
#[ignore]
fn cover_cost() {
let forced = HashSet::new();
for players in [10usize, 25, 50] {
// The benchmark's bots: most near spawn, a fifth flying outwards.
let extra: Vec<_> = (0..players)
.map(|i| {
let a = i as f64 * 2.399;
let d = if i % 5 == 0 { 30.0 } else { 3.0 };
(((a.cos() * d) as i32, (a.sin() * d) as i32), 11)
})
.collect();
let cover = ExtraCover::new(&extra).unwrap();
let ranges = |cover| Ranges {
center: (0, 0),
radius: 10,
extra: &extra,
forced: &forced,
cover,
};
// The columns streaming asks about: everything kept, and the
// generation scan's ring past it.
let columns: Vec<(i32, i32)> = (-60..=60)
.flat_map(|z| (-60..=60).map(move |x| (x, z)))
.filter(|&(x, z)| {
ranges(None).requested(x, z, true) || !ranges(None).unloaded(x, z, true)
})
.collect();
let rounds = 100;
let time = |r: &Ranges| {
let t = std::time::Instant::now();
let mut n = 0usize;
for _ in 0..rounds {
for &(x, z) in &columns {
n += usize::from(r.unloaded(x, z, true));
n += usize::from(r.requested(x, z, true));
n += usize::from(r.in_range(x, z, 1));
}
}
std::hint::black_box(n);
t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds)
};
let t = std::time::Instant::now();
for _ in 0..rounds {
std::hint::black_box(ExtraCover::new(std::hint::black_box(&extra)));
}
let build = t.elapsed().as_secs_f64() * 1e3 / f64::from(rounds);
println!(
"{players} players, {} columns, 3 questions each: scan {:.3} ms, grid {:.3} ms (+ {build:.3} ms to build)",
columns.len(),
time(&ranges(None)),
time(&ranges(Some(&cover))),
);
}
}
}
+224 -8
View File
@@ -45,13 +45,52 @@ pub struct Sources {
/// block ticking or lower; `None` ticks everywhere (a game with no server and
/// no player: the headless fixtures).
#[derive(Clone, Default)]
pub struct Levels(Option<Arc<FxHashMap<(i32, i32), (u8, u8)>>>);
pub struct Levels(Option<Arc<Map>>);
/// The levels by chunk: a grid over the tickets' bounding box while it is
/// small (players near each other, the usual case), a map otherwise. Every
/// block entity, mob and ticking chunk asks each tick, so an index beats a
/// hash; and a player crossing into another chunk rebuilds it all.
enum Map {
Grid {
x0: i32,
z0: i32,
width: u32,
depth: u32,
cells: Box<[(u8, u8)]>,
},
Sparse(FxHashMap<(i32, i32), (u8, u8)>),
}
/// The largest grid, in chunks: 1 MiB of levels, a box 724 chunks wide.
const GRID_CELLS: u64 = 1 << 19;
impl Map {
fn get(&self, x: i32, z: i32) -> (u8, u8) {
match self {
Self::Grid {
x0,
z0,
width,
depth,
cells,
} => {
let (dx, dz) = (x.wrapping_sub(*x0) as u32, z.wrapping_sub(*z0) as u32);
if dx < *width && dz < *depth {
cells[(dz * width + dx) as usize]
} else {
NONE
}
}
Self::Sparse(map) => map.get(&(x, z)).copied().unwrap_or(NONE),
}
}
}
impl Levels {
/// Chunk coordinates.
fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> {
let map = self.0.as_ref()?;
Some(map.get(&(x, z)).copied().unwrap_or(NONE))
Some(self.0.as_ref()?.get(x, z))
}
/// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk:
/// where entities tick.
@@ -112,19 +151,89 @@ impl ChunkTickets {
}
}
fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> {
/// How far a player's tickets reach, and the simulation ticket's level.
fn reach(s: &Sources) -> (i32, i32, i32) {
let view = s.view_distance.clamp(0, 32);
let simulation = s.simulation_distance.clamp(0, 32);
// PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the
// player's chunk (`getPlayerTicketLevel`: never below 0).
let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0);
let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim);
(view, player_sim, reach)
}
fn compute(s: &Sources) -> Map {
let (view, player_sim, reach) = reach(s);
let boxes = s
.players
.iter()
.map(|&p| (p, reach))
.chain(s.forced.iter().map(|&f| (f, 1)));
let Some((x0, z0, x1, z1)) = boxes.fold(None, |b, ((x, z), r)| {
let (lo_x, lo_z, hi_x, hi_z) = (
i64::from(x) - i64::from(r),
i64::from(z) - i64::from(r),
i64::from(x) + i64::from(r),
i64::from(z) + i64::from(r),
);
Some(match b {
None => (lo_x, lo_z, hi_x, hi_z),
Some((a, b, c, d)) => (lo_x.min(a), lo_z.min(b), hi_x.max(c), hi_z.max(d)),
})
}) else {
return Map::Sparse(FxHashMap::default());
};
let (width, depth) = ((x1 - x0 + 1) as u64, (z1 - z0 + 1) as u64);
if width * depth > GRID_CELLS {
return Map::Sparse(compute_sparse(s));
}
let (x0, z0, width, depth) = (x0 as i32, z0 as i32, width as u32, depth as u32);
let mut cells = vec![NONE; (width * depth) as usize].into_boxed_slice();
let mut lower = |x: i32, z: i32, loading: i32, sim: i32| {
let i = ((z - z0) as u32 * width + (x - x0) as u32) as usize;
let e = &mut cells[i];
e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8);
e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8);
};
for &(px, pz) in &s.players {
for dz in -reach..=reach {
for dx in -reach..=reach {
let d = dx.abs().max(dz.abs());
lower(
px + dx,
pz + dz,
i32::from(ENTITY_TICKING) + (d - view).max(0),
player_sim + d,
);
}
}
}
for &(fx, fz) in &s.forced {
for dz in -1i32..=1 {
for dx in -1i32..=1 {
let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs());
lower(fx + dx, fz + dz, level, level);
}
}
}
Map::Grid {
x0,
z0,
width,
depth,
cells,
}
}
/// The levels as a map, for tickets spread too far apart for a grid.
fn compute_sparse(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> {
let (view, player_sim, reach) = reach(s);
let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default();
let mut lower = |key, loading: i32, sim: i32| {
let e = levels.entry(key).or_insert(NONE);
e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8);
e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8);
};
// PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the
// player's chunk (`getPlayerTicketLevel`: never below 0).
let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0);
let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim);
for &(px, pz) in &s.players {
for dz in -reach..=reach {
for dx in -reach..=reach {
@@ -229,4 +338,111 @@ mod tests {
t.update(None);
assert!(t.levels().0.is_none());
}
/// The grid answers as the map does, everywhere around the tickets.
#[test]
fn grid_matches_the_map() {
let mut seed = 0x2545_f491_4f6c_dd1du64;
let mut next = |n: i32| {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
(seed % (2 * n as u64 + 1)) as i32 - n
};
for case in 0..200 {
let spread = [3, 20, 80][case % 3];
let players: Vec<_> = (0..1 + case % 12)
.map(|_| (next(spread), next(spread)))
.collect();
let forced: Vec<_> = (0..case % 4)
.map(|_| (next(spread), next(spread)))
.collect();
let s = Sources {
players,
forced,
view_distance: 2 + next(12).abs(),
simulation_distance: 2 + next(12).abs(),
};
let Map::Grid { .. } = compute(&s) else {
panic!("case {case} fell back to the map");
};
let (grid, map) = (compute(&s), Map::Sparse(compute_sparse(&s)));
let r = spread + 50;
for z in -r..=r {
for x in -r..=r {
assert_eq!(grid.get(x, z), map.get(x, z), "case {case} at ({x}, {z})");
}
}
}
}
#[test]
fn far_apart_tickets_use_the_map() {
let l = levels(
&[(0, 0), (100_000, -100_000)],
&[(i32::MAX - 2, i32::MIN + 2)],
10,
10,
);
assert!(matches!(**l.0.as_ref().unwrap(), Map::Sparse(_)));
assert!(l.entity_ticking(100_010, -100_010) && !l.block_ticking(50_000, 0));
assert!(l.entity_ticking(i32::MAX - 2, i32::MIN + 2));
}
/// cargo test --release -p horizon-client --lib ticket_levels::tests::levels_cost -- --ignored --nocapture
#[test]
#[ignore]
fn levels_cost() {
for players in [1usize, 10, 25, 50] {
// The benchmark's bots: most near spawn, a fifth flying outwards.
let at: Vec<_> = (0..players)
.map(|i| {
let a = i as f64 * 2.399;
let d = if i % 5 == 0 { 30.0 } else { 3.0 };
((a.cos() * d) as i32, (a.sin() * d) as i32)
})
.collect();
let s = Sources {
players: at.clone(),
forced: Vec::new(),
view_distance: 10,
simulation_distance: 10,
};
let rounds = 200;
let t = std::time::Instant::now();
for _ in 0..rounds {
std::hint::black_box(compute_sparse(std::hint::black_box(&s)));
}
let map_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64;
let t = std::time::Instant::now();
for _ in 0..rounds {
std::hint::black_box(compute(std::hint::black_box(&s)));
}
let grid_build = t.elapsed().as_secs_f64() * 1e3 / rounds as f64;
// A tick's questions: every chunk within 12 of every player.
let (map, grid) = (Map::Sparse(compute_sparse(&s)), compute(&s));
let ask = |m: &Map| {
let t = std::time::Instant::now();
let mut n = 0u32;
for _ in 0..rounds {
for &(px, pz) in &at {
for z in pz - 12..=pz + 12 {
for x in px - 12..=px + 12 {
n +=
u32::from(std::hint::black_box(m.get(x, z)).0 <= BLOCK_TICKING);
}
}
}
}
std::hint::black_box(n);
t.elapsed().as_secs_f64() * 1e3 / rounds as f64
};
println!(
"{players} players: build {map_build:.3} -> {grid_build:.3} ms, {} lookups {:.3} -> {:.3} ms",
players * 625,
ask(&map),
ask(&grid)
);
}
}
}