Fewer stalls: region writes on a writer thread, culled entities, villager POI scans skip empty sections
- Unloaded chunks and entity chunks are encoded and written by a background region writer, in order; loads see queued records first, and synchronous saves wait for the queue. Deleting entity chunks a region doesn't hold no longer rewrites the region file. - Mobs render within Entity.shouldRenderAtSqrDistance (64 x bounding-box size x entity distance) and inside the view frustum (EntityRenderer.shouldRender); block entities outside the frustum are skipped, beams and structure blocks excepted. - Minecarts and dropped items tick only in entity-ticking chunks, like mobs. - Villager POI searches skip sections whose palette has no POI block. - Streaming bookkeeping uses the Fx hash and checks a column's light readiness once per frame instead of once per dirty section. - HORIZON_SPIKES=MS prints the timed spans of slow frames; frame summaries give the phase split of the slowest 1%. RD 32 village flight on the 4080: 81 -> 230 fps; 1% low 5.8 -> 18. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -147,9 +147,8 @@ pub struct FrameStats {
|
||||
millis: Vec<f32>,
|
||||
cpu: Vec<f32>,
|
||||
gpu: Vec<f32>,
|
||||
/// Summed milliseconds per frame phase (`PHASES`) and the frames counted.
|
||||
phases: [f64; PHASES.len()],
|
||||
phase_frames: u64,
|
||||
/// Milliseconds per frame phase (`PHASES`), one entry per rendered frame.
|
||||
phases: Vec<[f32; PHASES.len()]>,
|
||||
}
|
||||
|
||||
/// The parts of a frame's CPU time: world streaming and uploads, game ticks,
|
||||
@@ -189,10 +188,29 @@ impl FrameStats {
|
||||
}
|
||||
}
|
||||
pub fn record_phases(&mut self, millis: [f32; PHASES.len()]) {
|
||||
for (sum, m) in self.phases.iter_mut().zip(millis) {
|
||||
*sum += f64::from(m);
|
||||
if self.phases.len() < Self::LIMIT {
|
||||
self.phases.push(millis);
|
||||
}
|
||||
self.phase_frames += 1;
|
||||
}
|
||||
/// Average milliseconds per phase over the frames whose CPU time is at
|
||||
/// least `min_cpu` (all frames for 0): where the slow frames go.
|
||||
fn phase_average(&self, min_cpu: f32) -> serde_json::Value {
|
||||
let mut sums = [0.0f64; PHASES.len()];
|
||||
let mut n = 0;
|
||||
for (i, phases) in self.phases.iter().enumerate() {
|
||||
if self.cpu.get(i).is_some_and(|&c| c >= min_cpu) {
|
||||
for (sum, m) in sums.iter_mut().zip(phases) {
|
||||
*sum += f64::from(*m);
|
||||
}
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
PHASES
|
||||
.iter()
|
||||
.zip(sums)
|
||||
.map(|(name, sum)| (name.to_string(), (sum / f64::from(n.max(1))).into()))
|
||||
.collect::<serde_json::Map<_, _>>()
|
||||
.into()
|
||||
}
|
||||
pub fn record_gpu(&mut self, millis: &[f32]) {
|
||||
if self.gpu.len() < Self::LIMIT {
|
||||
@@ -203,8 +221,7 @@ impl FrameStats {
|
||||
self.millis.clear();
|
||||
self.cpu.clear();
|
||||
self.gpu.clear();
|
||||
self.phases = [0.0; PHASES.len()];
|
||||
self.phase_frames = 0;
|
||||
self.phases.clear();
|
||||
}
|
||||
pub fn summary(&self) -> serde_json::Value {
|
||||
let mut sorted = self.millis.clone();
|
||||
@@ -222,6 +239,15 @@ impl FrameStats {
|
||||
.map(|&m| f64::from(m))
|
||||
.sum::<f64>()
|
||||
/ slowest as f64;
|
||||
// Where the slowest 1% of frames by CPU time go.
|
||||
let slow_phases = {
|
||||
let mut cpu = self.cpu.clone();
|
||||
cpu.sort_by(f32::total_cmp);
|
||||
let p99 = cpu
|
||||
.get(cpu.len().saturating_sub(cpu.len().div_ceil(100)))
|
||||
.copied();
|
||||
p99.map_or(serde_json::Value::Null, |p| self.phase_average(p))
|
||||
};
|
||||
serde_json::json!({
|
||||
"frames": n,
|
||||
"seconds": total / 1000.0,
|
||||
@@ -233,11 +259,8 @@ impl FrameStats {
|
||||
"max_ms": sorted[n - 1],
|
||||
"cpu": percentiles(&self.cpu),
|
||||
"gpu": percentiles(&self.gpu),
|
||||
"phases_avg_ms": PHASES
|
||||
.iter()
|
||||
.zip(self.phases)
|
||||
.map(|(name, sum)| (name.to_string(), (sum / self.phase_frames.max(1) as f64).into()))
|
||||
.collect::<serde_json::Map<_, _>>(),
|
||||
"phases_avg_ms": self.phase_average(0.0),
|
||||
"slow_phases_avg_ms": slow_phases,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,6 +183,8 @@ struct Options {
|
||||
no_pause: bool,
|
||||
/// Control socket path (`--control`), for `horizon-ctl`.
|
||||
control: Option<PathBuf>,
|
||||
/// `HORIZON_SPIKES=MS`: print the timed spans of frames slower than MS.
|
||||
spikes: Option<f32>,
|
||||
/// Render into a texture instead of the window (`--offscreen`), so a
|
||||
/// GPU the display cannot present from can still be benchmarked.
|
||||
offscreen: bool,
|
||||
@@ -222,6 +224,7 @@ impl Options {
|
||||
no_pause: false,
|
||||
control: None,
|
||||
offscreen: false,
|
||||
spikes: std::env::var("HORIZON_SPIKES").ok().and_then(|v| v.parse().ok()),
|
||||
server: None,
|
||||
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
|
||||
dedicated: None,
|
||||
@@ -781,6 +784,8 @@ struct Game<'a> {
|
||||
/// Control replies waiting for a rendered frame or a benchmark deadline.
|
||||
pending_screenshot: Option<std::sync::mpsc::Sender<String>>,
|
||||
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
|
||||
/// This frame's view frustum, for culling entities and block entities.
|
||||
view_frustum: Option<horizon_client::gfx::Frustum>,
|
||||
/// A scripted flight from the control socket (`fly`).
|
||||
flight: Option<control::Flight>,
|
||||
/// The overworld's last `sky_darken` and its inputs (time, rain, thunder).
|
||||
@@ -1227,7 +1232,12 @@ impl Game<'_> {
|
||||
}
|
||||
fn tick_items(&mut self) {
|
||||
let mut items = std::mem::take(&mut self.dropped);
|
||||
items.retain_mut(|item| item.tick(&self.world, &self.res.facts, self.collision));
|
||||
// ServerLevel.tick: only entities in entity-ticking chunks tick.
|
||||
let ticking = self.entity_ticking_area();
|
||||
items.retain_mut(|item| {
|
||||
!ticking(item.position.x.floor() as i32, item.position.z.floor() as i32)
|
||||
|| item.tick(&self.world, &self.res.facts, self.collision)
|
||||
});
|
||||
let Some(p) = self.player.as_ref() else {
|
||||
self.dropped = items;
|
||||
return;
|
||||
@@ -2790,64 +2800,64 @@ impl Game<'_> {
|
||||
/// What the tick runs after the local player's own update: effects, the
|
||||
/// world's entities and blocks, and the network hub.
|
||||
fn tick_world(&mut self, running: bool) -> Result<()> {
|
||||
self.tick_effects();
|
||||
self.tick_burning();
|
||||
self.tick_using();
|
||||
self.tick_hud();
|
||||
horizon_client::spans::time("tick_effects", || self.tick_effects());
|
||||
horizon_client::spans::time("tick_burning", || self.tick_burning());
|
||||
horizon_client::spans::time("tick_using", || self.tick_using());
|
||||
horizon_client::spans::time("tick_hud", || self.tick_hud());
|
||||
// The player's digging comes in with its packets, before the level
|
||||
// ticks; ServerLevel.tick then runs the scheduled and random block
|
||||
// ticks before any entity, so what they drop or spawn (dispensed
|
||||
// items, popped crops) moves on the tick it appears, as in vanilla.
|
||||
self.tick_mining()?;
|
||||
self.postprocess_chunks()?;
|
||||
horizon_client::spans::time("tick_mining", || self.tick_mining())?;
|
||||
horizon_client::spans::time("postprocess_chunks", || self.postprocess_chunks())?;
|
||||
if running {
|
||||
self.tick_blocks()?;
|
||||
horizon_client::spans::time("tick_blocks", || self.tick_blocks())?;
|
||||
}
|
||||
if running {
|
||||
self.tick_paintings();
|
||||
self.tick_item_frames();
|
||||
self.tick_armor_stands();
|
||||
self.tick_boats();
|
||||
self.tick_carts();
|
||||
self.tick_thunder();
|
||||
self.tick_lecterns();
|
||||
self.tick_maps();
|
||||
self.tick_bolts();
|
||||
self.tick_fishing();
|
||||
self.tick_tridents();
|
||||
self.tick_rockets();
|
||||
horizon_client::spans::time("tick_paintings", || self.tick_paintings());
|
||||
horizon_client::spans::time("tick_item_frames", || self.tick_item_frames());
|
||||
horizon_client::spans::time("tick_armor_stands", || self.tick_armor_stands());
|
||||
horizon_client::spans::time("tick_boats", || self.tick_boats());
|
||||
horizon_client::spans::time("tick_carts", || self.tick_carts());
|
||||
horizon_client::spans::time("tick_thunder", || self.tick_thunder());
|
||||
horizon_client::spans::time("tick_lecterns", || self.tick_lecterns());
|
||||
horizon_client::spans::time("tick_maps", || self.tick_maps());
|
||||
horizon_client::spans::time("tick_bolts", || self.tick_bolts());
|
||||
horizon_client::spans::time("tick_fishing", || self.tick_fishing());
|
||||
horizon_client::spans::time("tick_tridents", || self.tick_tridents());
|
||||
horizon_client::spans::time("tick_rockets", || self.tick_rockets());
|
||||
}
|
||||
if running {
|
||||
self.tick_items();
|
||||
horizon_client::spans::time("tick_items", || self.tick_items());
|
||||
}
|
||||
self.spawn_loaded_entities();
|
||||
horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities());
|
||||
if running {
|
||||
self.tick_mobs()?;
|
||||
self.recheck_golem_openers();
|
||||
self.tick_experience();
|
||||
horizon_client::spans::time("tick_mobs", || self.tick_mobs())?;
|
||||
horizon_client::spans::time("recheck_golem_openers", || self.recheck_golem_openers());
|
||||
horizon_client::spans::time("tick_experience", || self.tick_experience());
|
||||
}
|
||||
self.tick_lan();
|
||||
self.tick_hand();
|
||||
self.tick_sleep();
|
||||
self.tick_portal()?;
|
||||
horizon_client::spans::time("tick_lan", || self.tick_lan());
|
||||
horizon_client::spans::time("tick_hand", || self.tick_hand());
|
||||
horizon_client::spans::time("tick_sleep", || self.tick_sleep());
|
||||
horizon_client::spans::time("tick_portal", || self.tick_portal())?;
|
||||
if running {
|
||||
self.tick_end()?;
|
||||
horizon_client::spans::time("tick_end", || self.tick_end())?;
|
||||
}
|
||||
if running {
|
||||
self.tick_falling()?;
|
||||
self.tick_tnt()?;
|
||||
horizon_client::spans::time("tick_falling", || self.tick_falling())?;
|
||||
horizon_client::spans::time("tick_tnt", || self.tick_tnt())?;
|
||||
}
|
||||
if running {
|
||||
self.tick_block_entities()?;
|
||||
self.tick_sculk_entities();
|
||||
self.tick_sculk_blocks()?;
|
||||
self.tick_brewing_stands()?;
|
||||
horizon_client::spans::time("tick_block_entities", || self.tick_block_entities())?;
|
||||
horizon_client::spans::time("tick_sculk_entities", || self.tick_sculk_entities());
|
||||
horizon_client::spans::time("tick_sculk_blocks", || self.tick_sculk_blocks())?;
|
||||
horizon_client::spans::time("tick_brewing_stands", || self.tick_brewing_stands())?;
|
||||
}
|
||||
if running {
|
||||
// ClientLevel.tickBlockEntities (not while paused or frozen):
|
||||
// chest lids, books, shulker boxes, bells, conduits, heads.
|
||||
self.tick_block_entity_anims();
|
||||
self.tick_particles();
|
||||
horizon_client::spans::time("tick_block_entity_anims", || self.tick_block_entity_anims());
|
||||
horizon_client::spans::time("tick_particles", || self.tick_particles());
|
||||
}
|
||||
if self.right && self.use_delay == 0 && self.screen == Screen::Playing {
|
||||
self.use_item()?;
|
||||
@@ -4374,9 +4384,32 @@ impl Game<'_> {
|
||||
banner: &|p| self.banner_layers_at(p),
|
||||
glyph: &|c| self.res.atlas.glyph_cell(c),
|
||||
};
|
||||
// Block entities outside the view frustum are skipped (with a
|
||||
// block of margin for models larger than their block).
|
||||
let view = self.view_frustum;
|
||||
// Beams and structure outlines reach far outside their block
|
||||
// (BlockEntityRenderer.shouldRenderOffScreen): never culled.
|
||||
let off_screen = |state: u32| {
|
||||
let name = &*self.res.facts.get(BlockStateId(state)).name;
|
||||
matches!(
|
||||
name,
|
||||
"minecraft:beacon"
|
||||
| "minecraft:end_gateway"
|
||||
| "minecraft:structure_block"
|
||||
| "minecraft:test_instance_block"
|
||||
)
|
||||
};
|
||||
let visible = r.block_entities().filter(|(p, state)| {
|
||||
off_screen(*state) || view.is_none_or(|v| {
|
||||
let o = (glam::DVec3::new(f64::from(p[0]), f64::from(p[1]), f64::from(p[2]))
|
||||
- camera)
|
||||
.as_vec3();
|
||||
v.intersects(o - glam::Vec3::ONE, o + glam::Vec3::splat(2.0))
|
||||
})
|
||||
});
|
||||
self.res
|
||||
.block_entity_render
|
||||
.render(&scene, r.block_entities(), &mut out);
|
||||
.render(&scene, visible, &mut out);
|
||||
}
|
||||
// Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet.
|
||||
if let Some(r) = self
|
||||
@@ -7235,14 +7268,35 @@ impl Game<'_> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let mut hud = self.hud(size);
|
||||
let mut hud = horizon_client::spans::time("hud", || self.hud(size));
|
||||
// Map textures changed since the last drawn frame (game/maps.rs).
|
||||
hud.patches.append(&mut self.map_patches);
|
||||
let title = self.title.is_some();
|
||||
let (yaw, pitch) = if title {
|
||||
// PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees.
|
||||
(-(self.started.elapsed().as_secs_f32() * 2.0) % 360.0, 10.0)
|
||||
} else {
|
||||
(view_yaw, view_pitch)
|
||||
};
|
||||
let fov_degrees = if title {
|
||||
85.0
|
||||
} else {
|
||||
self.fov_degrees(alpha as f32, camera.to_array())
|
||||
};
|
||||
let bob = if title {
|
||||
glam::Mat4::IDENTITY
|
||||
} else {
|
||||
self.bob_matrix(alpha as f32)
|
||||
};
|
||||
let distance = (self.streaming.radius * 16) as f32;
|
||||
self.view_frustum = self
|
||||
.renderer
|
||||
.as_ref()
|
||||
.map(|r| r.camera_frustum(fov_degrees, yaw, pitch, bob, distance));
|
||||
let mut entities = if title {
|
||||
Vec::new()
|
||||
} else {
|
||||
self.entity_geometry(camera, alpha)
|
||||
horizon_client::spans::time("entity_geometry", || self.entity_geometry(camera, alpha))
|
||||
};
|
||||
let mut additive = Vec::new();
|
||||
if !title {
|
||||
@@ -7281,15 +7335,13 @@ impl Game<'_> {
|
||||
self.end_geometry(camera, &mut entities);
|
||||
}
|
||||
if !title && self.dim == Dim::Overworld {
|
||||
self.cloud_geometry(&sky, camera, alpha, &mut entities);
|
||||
self.weather_geometry(camera, alpha, &mut entities);
|
||||
horizon_client::spans::time("clouds", || {
|
||||
self.cloud_geometry(&sky, camera, alpha, &mut entities)
|
||||
});
|
||||
horizon_client::spans::time("weather", || {
|
||||
self.weather_geometry(camera, alpha, &mut entities)
|
||||
});
|
||||
}
|
||||
// PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees.
|
||||
let (yaw, pitch) = if title {
|
||||
(-(self.started.elapsed().as_secs_f32() * 2.0) % 360.0, 10.0)
|
||||
} else {
|
||||
(view_yaw, view_pitch)
|
||||
};
|
||||
let water_fog = {
|
||||
let c = info.water_fog;
|
||||
[
|
||||
@@ -7305,18 +7357,10 @@ impl Game<'_> {
|
||||
camera,
|
||||
yaw,
|
||||
pitch,
|
||||
fov_degrees: if title {
|
||||
85.0
|
||||
} else {
|
||||
self.fov_degrees(alpha as f32, camera.to_array())
|
||||
},
|
||||
bob: if title {
|
||||
glam::Mat4::IDENTITY
|
||||
} else {
|
||||
self.bob_matrix(alpha as f32)
|
||||
},
|
||||
fov_degrees,
|
||||
bob,
|
||||
sky,
|
||||
distance: (self.streaming.radius * 16) as f32,
|
||||
distance,
|
||||
underwater,
|
||||
title,
|
||||
skybox: self.dim == Dim::Overworld,
|
||||
@@ -7353,7 +7397,8 @@ impl Game<'_> {
|
||||
night_vision: self.night_vision_intensity(),
|
||||
block_flicker: self.res.fog.state.block_light_flicker,
|
||||
};
|
||||
self.renderer.as_mut().ok_or("renderer")?.render(&frame)
|
||||
let renderer = self.renderer.as_mut().ok_or("renderer")?;
|
||||
horizon_client::spans::time("renderer", || renderer.render(&frame))
|
||||
}
|
||||
/// `LevelExtractor` / `LevelRenderer`: the world border wall this frame.
|
||||
fn border_draw(
|
||||
@@ -7556,33 +7601,41 @@ impl Game<'_> {
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
);
|
||||
}
|
||||
let (uploads, unloaded) = self.streaming.update(&mut self.world);
|
||||
let (uploads, unloaded) =
|
||||
horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world));
|
||||
let dirty: Vec<_> = unloaded
|
||||
.iter()
|
||||
.filter(|c| self.world.modified.remove(&(c.x, c.z)))
|
||||
.cloned()
|
||||
.collect();
|
||||
let modified: Vec<_> = dirty.iter().map(|c| self.with_entities(c)).collect();
|
||||
self.unload_entities(&unloaded);
|
||||
for c in &unloaded {
|
||||
let modified: Vec<_> = horizon_client::spans::time("with_entities", || {
|
||||
dirty.iter().map(|c| self.with_entities(c)).collect()
|
||||
});
|
||||
horizon_client::spans::time("unload_entities", || self.unload_entities(&unloaded));
|
||||
if !unloaded.is_empty() {
|
||||
let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> =
|
||||
unloaded.iter().map(|c| (c.x, c.z)).collect();
|
||||
self.world
|
||||
.block_entities
|
||||
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
|
||||
.retain(|p, _| !gone.contains(&(p.0 >> 4, p.2 >> 4)));
|
||||
self.world
|
||||
.block_names
|
||||
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
|
||||
.retain(|p, _| !gone.contains(&(p.0 >> 4, p.2 >> 4)));
|
||||
}
|
||||
if !modified.is_empty()
|
||||
&& let Err(e) = self
|
||||
.save
|
||||
.save(&modified, self.res.assets.registry, &self.res.biomes)
|
||||
&& let Err(e) = horizon_client::spans::time("save_chunks", || {
|
||||
self.save
|
||||
.save_later(&modified, self.res.assets.registry, &self.res.biomes)
|
||||
})
|
||||
{
|
||||
eprintln!("Horizon: failed to save unloaded chunks: {e}");
|
||||
}
|
||||
if let Some(renderer) = self.renderer.as_mut() {
|
||||
for (key, mesh) in uploads {
|
||||
renderer.upload(key, &mesh);
|
||||
}
|
||||
horizon_client::spans::time("upload", || {
|
||||
for (key, mesh) in uploads {
|
||||
renderer.upload(key, &mesh);
|
||||
}
|
||||
});
|
||||
for c in unloaded {
|
||||
for sy in 0..(HEIGHT / 16) {
|
||||
renderer.remove((c.x, sy, c.z));
|
||||
@@ -8021,8 +8074,8 @@ impl ApplicationHandler for Game<'_> {
|
||||
+ (turn(KeyCode::ArrowDown) - turn(KeyCode::ArrowUp)) * 90.0 * secs)
|
||||
.clamp(-90.0, 90.0);
|
||||
if self.title.is_none() {
|
||||
self.update_world();
|
||||
self.spawn_player()?;
|
||||
horizon_client::spans::time("update_world", || self.update_world());
|
||||
horizon_client::spans::time("spawn_player", || self.spawn_player())?;
|
||||
}
|
||||
let updated = Instant::now();
|
||||
self.track_toggle_screens();
|
||||
@@ -8030,7 +8083,7 @@ impl ApplicationHandler for Game<'_> {
|
||||
for _ in 0..steps {
|
||||
let started = Instant::now();
|
||||
if self.title.is_none() && !self.pause {
|
||||
self.tick()?;
|
||||
horizon_client::spans::time("tick", || self.tick())?;
|
||||
self.tick_ambience();
|
||||
self.tick_fov();
|
||||
}
|
||||
@@ -8045,6 +8098,24 @@ impl ApplicationHandler for Game<'_> {
|
||||
self.advance_flight();
|
||||
let ticked = Instant::now();
|
||||
let rendered = self.render()?;
|
||||
if let Some(threshold) = self.options.spikes
|
||||
&& let Some(r) = self.renderer.as_ref()
|
||||
{
|
||||
let cpu = now.elapsed().saturating_sub(r.last_wait).as_secs_f32() * 1000.0;
|
||||
let spans = horizon_client::spans::take();
|
||||
if cpu > threshold {
|
||||
let list: Vec<String> = spans
|
||||
.iter()
|
||||
.filter(|(_, ms)| *ms >= 0.5)
|
||||
.map(|(n, ms)| format!("{n} {ms:.1}"))
|
||||
.collect();
|
||||
eprintln!(
|
||||
"Horizon: slow frame {cpu:.1} ms ({} ticks): {}",
|
||||
steps,
|
||||
list.join(", ")
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
let cpu = now.elapsed().saturating_sub(r.last_wait);
|
||||
if rendered {
|
||||
@@ -8141,6 +8212,7 @@ pub fn run() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
let started = Instant::now();
|
||||
horizon_client::spans::enable(options.spikes.is_some());
|
||||
let vanilla_root = options.resources.clone();
|
||||
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
|
||||
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs);
|
||||
@@ -8464,6 +8536,7 @@ pub fn run() -> Result<()> {
|
||||
pending_screenshot: None,
|
||||
pending_bench: None,
|
||||
flight: None,
|
||||
view_frustum: None,
|
||||
sky_darken_memo: Default::default(),
|
||||
persist: Default::default(),
|
||||
remote: None,
|
||||
|
||||
@@ -2280,11 +2280,27 @@ impl Game<'_> {
|
||||
pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec<Vertex>) {
|
||||
let atlas = &self.res.atlas;
|
||||
let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]);
|
||||
let scale = f64::from(self.settings.entity_distance);
|
||||
for mob in &self.mobs {
|
||||
let d = glam::DVec3::new(mob.position.x, mob.position.y, mob.position.z) - camera;
|
||||
if d.length_squared() > 128.0 * 128.0 {
|
||||
// Entity.shouldRenderAtSqrDistance: 64 times the bounding box's
|
||||
// mean edge, scaled by the entity distance option.
|
||||
let (w, h, _) = mob.dims();
|
||||
let range = (w + h + w) / 3.0 * 64.0 * scale;
|
||||
if d.length_squared() >= range * range {
|
||||
continue;
|
||||
}
|
||||
// EntityRenderer.shouldRender: the culling box, grown by 0.5
|
||||
// (GuardianRenderer also draws while its beam is out).
|
||||
if let Some(view) = &self.view_frustum
|
||||
&& horizon_client::mobs::guardian::beam(mob, alpha as f32).is_none()
|
||||
{
|
||||
let lo = d.as_vec3() - glam::Vec3::new(w as f32 / 2.0 + 0.5, 0.5, w as f32 / 2.0 + 0.5);
|
||||
let hi = d.as_vec3() + glam::Vec3::new(w as f32 / 2.0 + 0.5, h as f32 + 0.5, w as f32 / 2.0 + 0.5);
|
||||
if !view.intersects(lo, hi) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let light = self.world.light(
|
||||
mob.position.x.floor() as i32,
|
||||
(mob.position.y + mob.eye_height()).floor() as i32,
|
||||
|
||||
@@ -762,9 +762,14 @@ impl Game<'_> {
|
||||
/// Every cart but the ridden one (which ticks with its rider).
|
||||
pub(super) fn tick_carts(&mut self) {
|
||||
self.push_carts();
|
||||
// ServerLevel.tick: only entities in entity-ticking chunks tick.
|
||||
let ticking = self.entity_ticking_area();
|
||||
let mut i = 0;
|
||||
while i < self.carts.len() {
|
||||
if Some(self.carts[i].id) == self.riding {
|
||||
let p = self.carts[i].position;
|
||||
if Some(self.carts[i].id) == self.riding
|
||||
|| !ticking(p.x.floor() as i32, p.z.floor() as i32)
|
||||
{
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -831,7 +831,7 @@ impl Game<'_> {
|
||||
self.spawn_loaded_entities();
|
||||
let keys: HashSet<(i32, i32)> = unloaded.iter().map(|c| (c.x, c.z)).collect();
|
||||
let chunks = self.entity_chunks(&keys, true);
|
||||
if let Err(e) = self.save.save_entities(chunks) {
|
||||
if let Err(e) = self.save.save_entities_later(chunks) {
|
||||
eprintln!("Horizon: failed to save entities: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,17 +1373,39 @@ impl Renderer {
|
||||
self.release_section(key);
|
||||
}
|
||||
pub fn view_projection(&self, frame: &Frame) -> Mat4 {
|
||||
self.projection(
|
||||
frame.fov_degrees,
|
||||
frame.yaw,
|
||||
frame.pitch,
|
||||
frame.bob,
|
||||
frame.distance,
|
||||
)
|
||||
}
|
||||
/// The view frustum `render` will cull with, for culling geometry built
|
||||
/// before the frame (entities, block entities) the same way.
|
||||
pub fn camera_frustum(
|
||||
&self,
|
||||
fov_degrees: f32,
|
||||
yaw: f32,
|
||||
pitch: f32,
|
||||
bob: Mat4,
|
||||
distance: f32,
|
||||
) -> Frustum {
|
||||
Frustum {
|
||||
planes: frustum(self.projection(fov_degrees, yaw, pitch, bob, distance)),
|
||||
}
|
||||
}
|
||||
fn projection(&self, fov_degrees: f32, yaw: f32, pitch: f32, bob: Mat4, distance: f32) -> Mat4 {
|
||||
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
|
||||
let (yaw, pitch) = (frame.yaw.to_radians(), frame.pitch.to_radians());
|
||||
let (yaw, pitch) = (yaw.to_radians(), pitch.to_radians());
|
||||
// Minecraft yaw: 0 = +Z (south), 90 = -X (west); pitch positive looks down.
|
||||
let forward = Vec3::new(
|
||||
-yaw.sin() * pitch.cos(),
|
||||
-pitch.sin(),
|
||||
yaw.cos() * pitch.cos(),
|
||||
);
|
||||
let far = (frame.distance * 4.0).max(1024.0);
|
||||
let bob = frame.bob;
|
||||
Mat4::perspective_rh(frame.fov_degrees.to_radians(), aspect, 0.05, far)
|
||||
let far = (distance * 4.0).max(1024.0);
|
||||
Mat4::perspective_rh(fov_degrees.to_radians(), aspect, 0.05, far)
|
||||
* bob
|
||||
* Mat4::look_to_rh(Vec3::ZERO, forward, Vec3::Y)
|
||||
}
|
||||
@@ -1608,7 +1630,9 @@ impl Renderer {
|
||||
self.queue
|
||||
.write_buffer(&self.globals, 0, bytemuck::bytes_of(&globals));
|
||||
// Frustum culling and camera-relative origins.
|
||||
let planes = frustum(view_proj);
|
||||
let view = Frustum {
|
||||
planes: frustum(view_proj),
|
||||
};
|
||||
let camera = frame.camera;
|
||||
let camera_section = (
|
||||
(camera.x.floor() as i32) >> 4,
|
||||
@@ -1640,14 +1664,7 @@ impl Renderer {
|
||||
}
|
||||
let min = origin.as_vec3();
|
||||
let max = min + Vec3::splat(16.0);
|
||||
if planes.iter().any(|p| {
|
||||
let v = Vec3::new(
|
||||
if p.x >= 0.0 { max.x } else { min.x },
|
||||
if p.y >= 0.0 { max.y } else { min.y },
|
||||
if p.z >= 0.0 { max.z } else { min.z },
|
||||
);
|
||||
p.truncate().dot(v) + p.w < 0.0
|
||||
}) {
|
||||
if !view.intersects(min, max) {
|
||||
return None;
|
||||
}
|
||||
Some((
|
||||
@@ -2120,6 +2137,24 @@ impl Renderer {
|
||||
Ok([width, height])
|
||||
}
|
||||
}
|
||||
/// Camera-relative clip planes (`Frustum`).
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Frustum {
|
||||
planes: [Vec4; 6],
|
||||
}
|
||||
impl Frustum {
|
||||
/// Whether the camera-relative box `min..max` is at least partly inside.
|
||||
pub fn intersects(&self, min: Vec3, max: Vec3) -> bool {
|
||||
!self.planes.iter().any(|p| {
|
||||
let v = Vec3::new(
|
||||
if p.x >= 0.0 { max.x } else { min.x },
|
||||
if p.y >= 0.0 { max.y } else { min.y },
|
||||
if p.z >= 0.0 { max.z } else { min.z },
|
||||
);
|
||||
p.truncate().dot(v) + p.w < 0.0
|
||||
})
|
||||
}
|
||||
}
|
||||
fn frustum(m: Mat4) -> [Vec4; 6] {
|
||||
let r = |i| m.row(i);
|
||||
let planes = [
|
||||
|
||||
@@ -108,6 +108,7 @@ pub mod snbt;
|
||||
pub mod sound_engine;
|
||||
pub mod sound_events;
|
||||
pub mod sprint;
|
||||
pub mod spans;
|
||||
pub mod sprites;
|
||||
pub mod stations;
|
||||
pub mod stopwatches;
|
||||
|
||||
@@ -920,12 +920,24 @@ fn pois_in_range(
|
||||
let chunks = radius.div_euclid(16) + 1;
|
||||
let y0 = (c[1] - radius).max(crate::chunk::MIN_Y);
|
||||
let y1 = (c[1] + radius).min(crate::chunk::MIN_Y + crate::chunk::HEIGHT - 1);
|
||||
let poi = poi_states(w.facts);
|
||||
for qz in cz - chunks..=cz + chunks {
|
||||
for qx in cx - chunks..=cx + chunks {
|
||||
if !w.world.chunks.contains_key(&(qx, qz)) {
|
||||
let Some(chunk) = w.world.chunks.get(&(qx, qz)) else {
|
||||
continue;
|
||||
};
|
||||
// Sections whose palette holds no bell, bed or job site have no
|
||||
// POI: skip them whole (PoiManager indexes POIs instead).
|
||||
let mut may_hold = [false; crate::chunk::SECTIONS];
|
||||
for (slot, section) in may_hold.iter_mut().zip(&chunk.sections) {
|
||||
*slot = section
|
||||
.blocks
|
||||
.maybe_has(|id| poi.get(id as usize).copied().unwrap_or(true));
|
||||
}
|
||||
for y in y0..=y1 {
|
||||
if !may_hold[((y - crate::chunk::MIN_Y) >> 4) as usize] {
|
||||
continue;
|
||||
}
|
||||
for z in qz * 16..qz * 16 + 16 {
|
||||
for x in qx * 16..qx * 16 + 16 {
|
||||
if (x - c[0]).abs() > radius || (z - c[2]).abs() > radius {
|
||||
@@ -966,6 +978,28 @@ fn pois_in_range(
|
||||
});
|
||||
found
|
||||
}
|
||||
/// Which block states `poi_at` can find a POI in, by state id.
|
||||
fn poi_states(facts: &crate::blocks::BlockFacts) -> std::sync::Arc<Vec<bool>> {
|
||||
static TABLE: std::sync::Mutex<Option<std::sync::Arc<Vec<bool>>>> = std::sync::Mutex::new(None);
|
||||
let mut table = TABLE.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(t) = table.as_ref().filter(|t| t.len() == facts.states.len()) {
|
||||
return t.clone();
|
||||
}
|
||||
let t: std::sync::Arc<Vec<bool>> = std::sync::Arc::new(
|
||||
facts
|
||||
.states
|
||||
.iter()
|
||||
.map(|f| {
|
||||
let name = &*f.name;
|
||||
name == "minecraft:bell"
|
||||
|| name.ends_with("_bed")
|
||||
|| super::villager::job_site_profession(name).is_some()
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
*table = Some(t.clone());
|
||||
t
|
||||
}
|
||||
/// `PoiManager.exists(pos, predicate)`.
|
||||
fn poi_exists(m: &Mob, w: &MobWorld, p: [i32; 3], f: PoiFilter) -> bool {
|
||||
poi_at(w, p[0], p[1], p[2]).is_some_and(|poi| poi_matches(m, f, poi))
|
||||
|
||||
@@ -36,6 +36,10 @@ use horizon_world::{
|
||||
};
|
||||
use std::{
|
||||
collections::{BTreeMap, HashMap},
|
||||
sync::{
|
||||
Condvar, mpsc,
|
||||
atomic::{AtomicU64, Ordering},
|
||||
},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::{Arc, Mutex, OnceLock},
|
||||
@@ -1108,12 +1112,159 @@ pub fn load_light(tag: &Tag, chunk: &mut Chunk, sky_light: bool) {
|
||||
}
|
||||
|
||||
type RegionCache = Mutex<HashMap<(i32, i32), Option<Arc<Mutex<RegionFile>>>>>;
|
||||
/// Rewrite every region file in `folder` touched by `records`, keeping its
|
||||
/// other chunks. `None` deletes a chunk.
|
||||
fn write_region_records(
|
||||
root: &Path,
|
||||
cache: &RegionCache,
|
||||
folder: &str,
|
||||
records: Vec<((i32, i32), Option<Arc<NamedTag>>)>,
|
||||
) -> Result<()> {
|
||||
let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option<Arc<NamedTag>>)>> =
|
||||
BTreeMap::new();
|
||||
for (key, tag) in records {
|
||||
by_region
|
||||
.entry((key.0 >> 5, key.1 >> 5))
|
||||
.or_default()
|
||||
.push((key, tag));
|
||||
}
|
||||
if by_region.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let staging = root.join(folder).join(".staging");
|
||||
fs::create_dir_all(&staging)?;
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as u32);
|
||||
for ((rx, rz), list) in by_region {
|
||||
let path = region_path(root, folder, rx, rz);
|
||||
let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new();
|
||||
let only_deletes = list.iter().all(|(_, tag)| tag.is_none());
|
||||
if let Ok(mut existing) = RegionFile::open(&path) {
|
||||
let positions: Vec<ChunkPos> = existing.chunks().map(|(p, _)| p).collect();
|
||||
if only_deletes
|
||||
&& !positions
|
||||
.iter()
|
||||
.any(|p| list.iter().any(|(k, _)| *k == (p.x, p.z)))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
for p in positions {
|
||||
if let Ok(Some(r)) = existing.read(p) {
|
||||
records.insert((p.x, p.z), r);
|
||||
}
|
||||
}
|
||||
} else if only_deletes {
|
||||
continue;
|
||||
}
|
||||
// Deleting chunks the region doesn't hold changes nothing: leave
|
||||
// the file alone (unloading empty entity chunks asks for that).
|
||||
let mut changed = false;
|
||||
for (key, tag) in list {
|
||||
match tag {
|
||||
Some(tag) => {
|
||||
changed = true;
|
||||
records.insert(
|
||||
key,
|
||||
ChunkRecord::from_nbt(
|
||||
&tag,
|
||||
Compression::Zlib,
|
||||
timestamp,
|
||||
Limits::default(),
|
||||
)?,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
changed |= records.remove(&key).is_some();
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
continue;
|
||||
}
|
||||
if records.is_empty() {
|
||||
let _ = fs::remove_file(&path);
|
||||
} else {
|
||||
let temporary = staging.join(format!("r.{rx}.{rz}.mca"));
|
||||
let _ = fs::remove_file(&temporary);
|
||||
let mut writer = RegionWriter::create(&temporary)?;
|
||||
for ((x, z), r) in &records {
|
||||
writer.write(ChunkPos::new(*x, *z), r)?;
|
||||
}
|
||||
writer.finish()?;
|
||||
fs::rename(&temporary, &path)?;
|
||||
}
|
||||
cache
|
||||
.lock()
|
||||
.map_err(|_| "region cache poisoned")?
|
||||
.remove(&(rx, rz));
|
||||
}
|
||||
let _ = fs::remove_dir(&staging);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn region_path(root: &Path, folder: &str, rx: i32, rz: i32) -> PathBuf {
|
||||
root.join(format!("{folder}/r.{rx}.{rz}.mca"))
|
||||
}
|
||||
|
||||
/// A record waiting for the writer thread.
|
||||
#[derive(Clone)]
|
||||
enum Record {
|
||||
Tag(Arc<NamedTag>),
|
||||
/// A chunk to encode on the writer thread.
|
||||
Chunk(Arc<Chunk>, Arc<Encoding>),
|
||||
Delete,
|
||||
}
|
||||
/// What encoding a chunk needs, captured when it is queued.
|
||||
struct Encoding {
|
||||
registry: &'static BlockRegistry,
|
||||
biomes: Arc<Biomes>,
|
||||
tables: Option<Arc<SaveTables>>,
|
||||
sky_light: bool,
|
||||
}
|
||||
impl Record {
|
||||
fn tag(&self) -> Option<Arc<NamedTag>> {
|
||||
match self {
|
||||
Record::Tag(t) => Some(t.clone()),
|
||||
Record::Chunk(c, e) => Some(Arc::new(encode_with(
|
||||
c,
|
||||
e.registry,
|
||||
&e.biomes,
|
||||
e.tables.as_deref(),
|
||||
e.sky_light,
|
||||
))),
|
||||
Record::Delete => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Chunk and entity records waiting for the writer thread, by (entities?,
|
||||
/// x, z): reads see them before the region files do.
|
||||
type PendingWrites = Mutex<HashMap<(bool, i32, i32), (u64, Record)>>;
|
||||
type WriteBatch = (bool, Vec<((i32, i32), Record, u64)>);
|
||||
|
||||
/// The background thread that encodes chunks and rewrites region files, in
|
||||
/// submission order.
|
||||
struct Writer {
|
||||
send: mpsc::Sender<WriteBatch>,
|
||||
thread: std::thread::JoinHandle<()>,
|
||||
}
|
||||
|
||||
/// Writes still queued or running, with a condition to wait for none.
|
||||
#[derive(Default)]
|
||||
struct Outstanding {
|
||||
count: Mutex<usize>,
|
||||
done: Condvar,
|
||||
}
|
||||
/// One dimension folder (`dimensions/minecraft/<name>`). Region files are
|
||||
/// read lazily by worker threads.
|
||||
pub struct SaveDir {
|
||||
pub root: PathBuf,
|
||||
regions: RegionCache,
|
||||
entity_regions: RegionCache,
|
||||
regions: Arc<RegionCache>,
|
||||
entity_regions: Arc<RegionCache>,
|
||||
pending: Arc<PendingWrites>,
|
||||
sequence: AtomicU64,
|
||||
writer: Mutex<Option<Writer>>,
|
||||
outstanding: Arc<Outstanding>,
|
||||
/// Set by `Persistent` before the first load.
|
||||
pub tables: OnceLock<Arc<SaveTables>>,
|
||||
/// False in dimensions without skylight (no SkyLight layers are written).
|
||||
@@ -1124,16 +1275,29 @@ impl SaveDir {
|
||||
let sky_light = !root.ends_with("the_nether") && !root.ends_with("DIM-1");
|
||||
Self {
|
||||
root,
|
||||
regions: Mutex::new(HashMap::new()),
|
||||
entity_regions: Mutex::new(HashMap::new()),
|
||||
regions: Default::default(),
|
||||
entity_regions: Default::default(),
|
||||
pending: Default::default(),
|
||||
sequence: AtomicU64::new(0),
|
||||
writer: Mutex::new(None),
|
||||
outstanding: Default::default(),
|
||||
tables: OnceLock::new(),
|
||||
sky_light,
|
||||
}
|
||||
}
|
||||
fn region_path(&self, folder: &str, rx: i32, rz: i32) -> PathBuf {
|
||||
self.root.join(format!("{folder}/r.{rx}.{rz}.mca"))
|
||||
region_path(&self.root, folder, rx, rz)
|
||||
}
|
||||
fn read_record(&self, folder: &str, x: i32, z: i32) -> Option<NamedTag> {
|
||||
let pending = self
|
||||
.pending
|
||||
.lock()
|
||||
.ok()?
|
||||
.get(&(folder != "region", x, z))
|
||||
.map(|(_, r)| r.clone());
|
||||
if let Some(record) = pending {
|
||||
return record.tag().map(|t| (*t).clone());
|
||||
}
|
||||
let key = (x >> 5, z >> 5);
|
||||
let cache = if folder == "region" {
|
||||
&self.regions
|
||||
@@ -1172,83 +1336,91 @@ impl SaveDir {
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Rewrite every region file in `folder` touched by `records`, keeping
|
||||
/// its other chunks. `None` deletes a chunk.
|
||||
/// Queue `records` for the writer thread; with `wait`, return once
|
||||
/// they and every earlier write are on disk.
|
||||
fn write_records(
|
||||
&self,
|
||||
folder: &str,
|
||||
records: Vec<((i32, i32), Option<NamedTag>)>,
|
||||
wait: bool,
|
||||
) -> Result<()> {
|
||||
let mut by_region: BTreeMap<(i32, i32), Vec<((i32, i32), Option<NamedTag>)>> =
|
||||
BTreeMap::new();
|
||||
for (key, tag) in records {
|
||||
by_region
|
||||
.entry((key.0 >> 5, key.1 >> 5))
|
||||
.or_default()
|
||||
.push((key, tag));
|
||||
}
|
||||
if by_region.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let staging = self.root.join(folder).join(".staging");
|
||||
fs::create_dir_all(&staging)?;
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_secs() as u32);
|
||||
let cache = if folder == "region" {
|
||||
&self.regions
|
||||
} else {
|
||||
&self.entity_regions
|
||||
};
|
||||
for ((rx, rz), list) in by_region {
|
||||
let path = self.region_path(folder, rx, rz);
|
||||
let mut records: BTreeMap<(i32, i32), ChunkRecord> = BTreeMap::new();
|
||||
if let Ok(mut existing) = RegionFile::open(&path) {
|
||||
let positions: Vec<ChunkPos> = existing.chunks().map(|(p, _)| p).collect();
|
||||
for p in positions {
|
||||
if let Ok(Some(r)) = existing.read(p) {
|
||||
records.insert((p.x, p.z), r);
|
||||
}
|
||||
let records = records
|
||||
.into_iter()
|
||||
.map(|(k, t)| (k, t.map_or(Record::Delete, |t| Record::Tag(Arc::new(t)))))
|
||||
.collect();
|
||||
self.queue(folder != "region", records, wait)
|
||||
}
|
||||
fn queue(&self, entities: bool, records: Vec<((i32, i32), Record)>, wait: bool) -> Result<()> {
|
||||
if !records.is_empty() {
|
||||
let mut batch = Vec::with_capacity(records.len());
|
||||
{
|
||||
let mut pending = self.pending.lock().map_err(|_| "pending writes poisoned")?;
|
||||
for (key, record) in records {
|
||||
let seq = self.sequence.fetch_add(1, Ordering::Relaxed);
|
||||
pending.insert((entities, key.0, key.1), (seq, record.clone()));
|
||||
batch.push((key, record, seq));
|
||||
}
|
||||
}
|
||||
for (key, tag) in list {
|
||||
match tag {
|
||||
Some(tag) => {
|
||||
records.insert(
|
||||
key,
|
||||
ChunkRecord::from_nbt(
|
||||
&tag,
|
||||
Compression::Zlib,
|
||||
timestamp,
|
||||
Limits::default(),
|
||||
)?,
|
||||
);
|
||||
}
|
||||
None => {
|
||||
records.remove(&key);
|
||||
}
|
||||
}
|
||||
*self.outstanding.count.lock().map_err(|_| "writer poisoned")? += 1;
|
||||
let mut writer = self.writer.lock().map_err(|_| "writer poisoned")?;
|
||||
let writer = writer.get_or_insert_with(|| self.start_writer());
|
||||
if writer.send.send((entities, batch)).is_err() {
|
||||
return Err("the region writer stopped".into());
|
||||
}
|
||||
if records.is_empty() {
|
||||
let _ = fs::remove_file(&path);
|
||||
} else {
|
||||
let temporary = staging.join(format!("r.{rx}.{rz}.mca"));
|
||||
let _ = fs::remove_file(&temporary);
|
||||
let mut writer = RegionWriter::create(&temporary)?;
|
||||
for ((x, z), r) in &records {
|
||||
writer.write(ChunkPos::new(*x, *z), r)?;
|
||||
}
|
||||
writer.finish()?;
|
||||
fs::rename(&temporary, &path)?;
|
||||
}
|
||||
cache
|
||||
.lock()
|
||||
.map_err(|_| "region cache poisoned")?
|
||||
.remove(&(rx, rz));
|
||||
}
|
||||
let _ = fs::remove_dir(&staging);
|
||||
if wait {
|
||||
self.flush();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn start_writer(&self) -> Writer {
|
||||
let (send, receive) = mpsc::channel::<WriteBatch>();
|
||||
let root = self.root.clone();
|
||||
let (regions, entity_regions) = (self.regions.clone(), self.entity_regions.clone());
|
||||
let pending = self.pending.clone();
|
||||
let outstanding = self.outstanding.clone();
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("horizon-region-writer".into())
|
||||
.spawn(move || {
|
||||
for (entities, batch) in receive {
|
||||
let (folder, cache) = if entities {
|
||||
("entities", &entity_regions)
|
||||
} else {
|
||||
("region", ®ions)
|
||||
};
|
||||
let records = batch.iter().map(|(k, r, _)| (*k, r.tag())).collect();
|
||||
if let Err(e) = write_region_records(&root, cache, folder, records) {
|
||||
eprintln!("Horizon: failed to write {folder} files: {e}");
|
||||
}
|
||||
// Readers find the files (and a fresh region cache) from here on.
|
||||
if let Ok(mut pending) = pending.lock() {
|
||||
for (k, _, seq) in &batch {
|
||||
if pending.get(&(entities, k.0, k.1)).is_some_and(|p| p.0 == *seq) {
|
||||
pending.remove(&(entities, k.0, k.1));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Ok(mut count) = outstanding.count.lock() {
|
||||
*count -= 1;
|
||||
outstanding.done.notify_all();
|
||||
}
|
||||
}
|
||||
})
|
||||
.expect("spawn region writer");
|
||||
Writer { send, thread }
|
||||
}
|
||||
/// Wait until every queued write is on disk.
|
||||
pub fn flush(&self) {
|
||||
let Ok(mut count) = self.outstanding.count.lock() else {
|
||||
return;
|
||||
};
|
||||
while *count > 0 {
|
||||
count = match self.outstanding.done.wait(count) {
|
||||
Ok(c) => c,
|
||||
Err(_) => return,
|
||||
};
|
||||
}
|
||||
}
|
||||
/// Rewrite every region touched by `chunks`, keeping their other chunks.
|
||||
pub fn save(
|
||||
&self,
|
||||
@@ -1266,11 +1438,39 @@ impl SaveDir {
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
self.write_records("region", records)?;
|
||||
self.write_records("region", records, true)?;
|
||||
Ok(chunks.len())
|
||||
}
|
||||
/// `save` on the writer thread: returns before the files are written;
|
||||
/// loads see the chunks meanwhile.
|
||||
pub fn save_later(
|
||||
&self,
|
||||
chunks: &[Arc<Chunk>],
|
||||
registry: &'static BlockRegistry,
|
||||
biomes: &Arc<Biomes>,
|
||||
) -> Result<usize> {
|
||||
let encoding = Arc::new(Encoding {
|
||||
registry,
|
||||
biomes: biomes.clone(),
|
||||
tables: self.tables.get().cloned(),
|
||||
sky_light: self.sky_light,
|
||||
});
|
||||
let records = chunks
|
||||
.iter()
|
||||
.map(|c| ((c.x, c.z), Record::Chunk(c.clone(), encoding.clone())))
|
||||
.collect();
|
||||
self.queue(false, records, false)?;
|
||||
Ok(chunks.len())
|
||||
}
|
||||
/// Write the entity chunks (`EntityStorage`): an empty list deletes it.
|
||||
pub fn save_entities(&self, chunks: Vec<((i32, i32), Vec<Tag>)>) -> Result<()> {
|
||||
self.write_entities(chunks, true)
|
||||
}
|
||||
/// `save_entities` on the writer thread.
|
||||
pub fn save_entities_later(&self, chunks: Vec<((i32, i32), Vec<Tag>)>) -> Result<()> {
|
||||
self.write_entities(chunks, false)
|
||||
}
|
||||
fn write_entities(&self, chunks: Vec<((i32, i32), Vec<Tag>)>, wait: bool) -> Result<()> {
|
||||
let records = chunks
|
||||
.into_iter()
|
||||
.map(|((x, z), entities)| {
|
||||
@@ -1285,7 +1485,17 @@ impl SaveDir {
|
||||
((x, z), tag)
|
||||
})
|
||||
.collect();
|
||||
self.write_records("entities", records)
|
||||
self.write_records("entities", records, wait)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SaveDir {
|
||||
/// Finish queued writes before the world is let go.
|
||||
fn drop(&mut self) {
|
||||
if let Some(writer) = self.writer.get_mut().ok().and_then(Option::take) {
|
||||
drop(writer.send);
|
||||
let _ = writer.thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Named timings within a frame, for finding what makes a frame slow:
|
||||
//! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time
|
||||
//! exceeds MS milliseconds. Costs one clock read per span when enabled and
|
||||
//! a relaxed load otherwise.
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
sync::atomic::{AtomicBool, Ordering},
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
static ENABLED: AtomicBool = AtomicBool::new(false);
|
||||
thread_local! {
|
||||
static SPANS: RefCell<Vec<(&'static str, f32)>> = const { RefCell::new(Vec::new()) };
|
||||
}
|
||||
|
||||
pub fn enable(on: bool) {
|
||||
ENABLED.store(on, Ordering::Relaxed);
|
||||
}
|
||||
/// Run `f`, recording its duration under `name` when spans are enabled.
|
||||
#[inline]
|
||||
pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T {
|
||||
if !ENABLED.load(Ordering::Relaxed) {
|
||||
return f();
|
||||
}
|
||||
let started = Instant::now();
|
||||
let out = f();
|
||||
let ms = started.elapsed().as_secs_f32() * 1000.0;
|
||||
SPANS.with(|s| s.borrow_mut().push((name, ms)));
|
||||
out
|
||||
}
|
||||
/// The frame's spans, summed by name, slowest first; clears them.
|
||||
pub fn take() -> Vec<(&'static str, f32)> {
|
||||
let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut()));
|
||||
let mut sums: Vec<(&'static str, f32)> = Vec::new();
|
||||
for (name, ms) in spans {
|
||||
match sums.iter_mut().find(|(n, _)| *n == name) {
|
||||
Some(entry) => entry.1 += ms,
|
||||
None => sums.push((name, ms)),
|
||||
}
|
||||
}
|
||||
sums.sort_by(|a, b| b.1.total_cmp(&a.1));
|
||||
sums
|
||||
}
|
||||
@@ -9,8 +9,9 @@ use crate::{
|
||||
world::World,
|
||||
};
|
||||
use horizon_core::biome::BiomeZoom;
|
||||
use crate::fast_hash::{FxHashMap, FxHashSet};
|
||||
use std::{
|
||||
collections::{BinaryHeap, HashMap, HashSet},
|
||||
collections::{BinaryHeap, HashSet},
|
||||
sync::{
|
||||
Arc, Condvar, Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
@@ -98,19 +99,19 @@ pub struct Streaming {
|
||||
results: mpsc::Receiver<Done>,
|
||||
threads: Vec<thread::JoinHandle<()>>,
|
||||
order: u64,
|
||||
generating: HashSet<(i32, i32)>,
|
||||
generating: FxHashSet<(i32, i32)>,
|
||||
/// Proto chunks: `None` while checked out to a decoration job.
|
||||
protos: HashMap<(i32, i32), Option<Proto>>,
|
||||
decorated: HashSet<(i32, i32)>,
|
||||
protos: FxHashMap<(i32, i32), Option<Proto>>,
|
||||
decorated: FxHashSet<(i32, i32)>,
|
||||
decorating: usize,
|
||||
finishing: HashSet<(i32, i32)>,
|
||||
finishing: FxHashSet<(i32, i32)>,
|
||||
decorates: bool,
|
||||
lighting: HashMap<(i32, i32), u64>,
|
||||
meshing: HashMap<(i32, i32, i32), u64>,
|
||||
lighting: FxHashMap<(i32, i32), u64>,
|
||||
meshing: FxHashMap<(i32, i32, i32), u64>,
|
||||
/// Chunks whose light is current.
|
||||
lit: HashSet<(i32, i32)>,
|
||||
lit: FxHashSet<(i32, i32)>,
|
||||
/// Columns whose sections have been meshed at least once.
|
||||
meshed: HashSet<(i32, i32)>,
|
||||
meshed: FxHashSet<(i32, i32)>,
|
||||
sequence: u64,
|
||||
pub center: (i32, i32),
|
||||
pub radius: i32,
|
||||
@@ -133,7 +134,7 @@ pub struct Streaming {
|
||||
light_log: Vec<(u64, (i32, i32, i32))>,
|
||||
light_edit_sequence: u64,
|
||||
/// Edit sequence at each in-flight light job's snapshot.
|
||||
light_snapshots: HashMap<(i32, i32), u64>,
|
||||
light_snapshots: FxHashMap<(i32, i32), u64>,
|
||||
pub generated_total: u64,
|
||||
pub meshed_total: u64,
|
||||
/// Chunks come from a server (`insert_remote`/`forget`): nothing is
|
||||
@@ -234,16 +235,16 @@ impl Streaming {
|
||||
results,
|
||||
threads,
|
||||
order: 0,
|
||||
generating: HashSet::new(),
|
||||
protos: HashMap::new(),
|
||||
decorated: HashSet::new(),
|
||||
generating: Default::default(),
|
||||
protos: Default::default(),
|
||||
decorated: Default::default(),
|
||||
decorating: 0,
|
||||
finishing: HashSet::new(),
|
||||
finishing: Default::default(),
|
||||
decorates: generator.decorates(),
|
||||
lighting: HashMap::new(),
|
||||
meshing: HashMap::new(),
|
||||
lit: HashSet::new(),
|
||||
meshed: HashSet::new(),
|
||||
lighting: Default::default(),
|
||||
meshing: Default::default(),
|
||||
lit: Default::default(),
|
||||
meshed: Default::default(),
|
||||
sequence: 0,
|
||||
center: (0, 0),
|
||||
radius: 8,
|
||||
@@ -258,7 +259,7 @@ impl Streaming {
|
||||
light_tables,
|
||||
light_log: Vec::new(),
|
||||
light_edit_sequence: 0,
|
||||
light_snapshots: HashMap::new(),
|
||||
light_snapshots: Default::default(),
|
||||
generated_total: 0,
|
||||
meshed_total: 0,
|
||||
remote: false,
|
||||
@@ -614,13 +615,19 @@ impl Streaming {
|
||||
}
|
||||
// Meshing once the column and its neighbours are lit.
|
||||
let dirty: Vec<_> = world.dirty_sections.iter().copied().collect();
|
||||
let mut columns: HashMap<(i32, i32), Option<Box<Region>>> = HashMap::new();
|
||||
let mut columns: FxHashMap<(i32, i32), Option<Box<Region>>> = FxHashMap::default();
|
||||
let mut ready_columns: FxHashMap<(i32, i32), bool> = FxHashMap::default();
|
||||
for (x, sy, z) in dirty {
|
||||
if !world.chunks.contains_key(&(x, z)) || !self.in_main_range(x, z, 0) {
|
||||
world.dirty_sections.remove(&(x, sy, z));
|
||||
continue;
|
||||
}
|
||||
let ready = (-1..=1).all(|dz| (-1..=1).all(|dx| self.lit.contains(&(x + dx, z + dz))));
|
||||
// Once per column: the 3x3 lit check would otherwise repeat for
|
||||
// each of its sections every frame.
|
||||
let lit = &self.lit;
|
||||
let ready = *ready_columns.entry((x, z)).or_insert_with(|| {
|
||||
(-1..=1).all(|dz| (-1..=1).all(|dx| lit.contains(&(x + dx, z + dz))))
|
||||
});
|
||||
if !ready || self.lighting.contains_key(&(x, z)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -15,9 +15,9 @@ pub struct World {
|
||||
pub health_rules: crate::health::HealthRules,
|
||||
pub air: BlockStateId,
|
||||
/// Sections whose geometry changed and need remeshing.
|
||||
pub dirty_sections: HashSet<(i32, i32, i32)>,
|
||||
pub dirty_sections: crate::fast_hash::FxHashSet<(i32, i32, i32)>,
|
||||
/// Chunks whose light must be recomputed.
|
||||
pub dirty_light: HashSet<(i32, i32)>,
|
||||
pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>,
|
||||
/// Edits on lit chunks (position, old state, new state), relit
|
||||
/// incrementally by streaming.
|
||||
pub light_edits: Vec<((i32, i32, i32), u16, u16)>,
|
||||
@@ -113,8 +113,8 @@ impl World {
|
||||
revision: 0,
|
||||
health_rules: crate::health::HealthRules::default(),
|
||||
air,
|
||||
dirty_sections: HashSet::new(),
|
||||
dirty_light: HashSet::new(),
|
||||
dirty_sections: Default::default(),
|
||||
dirty_light: Default::default(),
|
||||
light_edits: Vec::new(),
|
||||
loaded_entities: Vec::new(),
|
||||
modified: HashSet::new(),
|
||||
|
||||
@@ -106,7 +106,8 @@ def run_distance(args, ctl, env, cwd, distance):
|
||||
f" p99 {summary.get('p99_ms', 0):6.2f} ms"
|
||||
f" cpu {((summary.get('cpu') or {}).get('avg_ms') or 0):6.2f} ms"
|
||||
f" gpu {((summary.get('gpu') or {}).get('avg_ms') or 0):6.2f} ms"
|
||||
+ " [" + " ".join(f"{k} {v:.2f}" for k, v in (summary.get("phases_avg_ms") or {}).items()) + "]",
|
||||
+ " [" + " ".join(f"{k} {v:.2f}" for k, v in (summary.get("phases_avg_ms") or {}).items()) + "]"
|
||||
+ " slow [" + " ".join(f"{k} {v:.1f}" for k, v in (summary.get("slow_phases_avg_ms") or {}).items()) + "]",
|
||||
flush=True,
|
||||
)
|
||||
finally:
|
||||
@@ -150,9 +151,11 @@ def main():
|
||||
"flight_seconds": args.seconds,
|
||||
"scenes": {n: {"from": a, "to": b, "pitch": c} for n, a, b, c in SCENES},
|
||||
"distances": {},
|
||||
"load_before": os.getloadavg(),
|
||||
}
|
||||
for d in [int(x) for x in args.distances.split(",")]:
|
||||
report["distances"][str(d)] = run_distance(args, ctl, env, cwd, d)
|
||||
report["load_after"] = os.getloadavg()
|
||||
out = Path(args.out) if args.out else ROOT / "benchmarks/graphics" / f"{args.label}.json"
|
||||
out.parent.mkdir(parents=True, exist_ok=True)
|
||||
out.write_text(json.dumps(report, indent=2) + "\n")
|
||||
|
||||
Reference in New Issue
Block a user