Renderer and tick performance: section arena with indirect multi-draw, dense occlusion graph, entity ticking within the simulation distance, fast chunk-map hashing
- Terrain sections live in one vertex arena (first-fit free list, grown on the GPU) and draw with one multi_draw_indexed_indirect per pass instead of a buffer bind and draw per section; per-frame scratch vectors are reused. - The SectionOcclusionGraph search runs over dense arrays around the camera instead of hash sets, with per-column visibility. - Mobs outside the entity-ticking chunks (Chebyshev distance of the simulation distance, DistanceManager.inEntityTickingRange) only check despawning, as in ServerLevel.tick; before, every loaded mob ticked. - World chunks use the Fx hash; sky darkening is sampled once per time and weather instead of once per mob; creaking-heart scans compare state ids. - Horizon-only graphics settings (horizon-graphics.txt): frame pacing without spinning, present mode, animated textures, worker threads. RD 32 village flight on the 4080: 3.1 -> 81 fps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
//! A fast, non-cryptographic hasher (the Fx hash used by rustc) for hot maps
|
||||
//! keyed by small integers, such as chunk coordinates. Iteration order of
|
||||
//! such maps carries no meaning: the default hasher's is random anyway.
|
||||
use std::hash::{BuildHasherDefault, Hasher};
|
||||
|
||||
const SEED: u64 = 0xf135_7aea_2e62_a9c5;
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct FxHasher {
|
||||
hash: u64,
|
||||
}
|
||||
impl FxHasher {
|
||||
#[inline]
|
||||
fn add(&mut self, word: u64) {
|
||||
self.hash = self.hash.wrapping_add(word).wrapping_mul(SEED);
|
||||
}
|
||||
}
|
||||
impl Hasher for FxHasher {
|
||||
#[inline]
|
||||
fn write(&mut self, bytes: &[u8]) {
|
||||
let mut chunks = bytes.chunks_exact(8);
|
||||
for c in &mut chunks {
|
||||
self.add(u64::from_le_bytes(c.try_into().expect("eight bytes")));
|
||||
}
|
||||
let rest = chunks.remainder();
|
||||
if !rest.is_empty() {
|
||||
let mut word = [0u8; 8];
|
||||
word[..rest.len()].copy_from_slice(rest);
|
||||
self.add(u64::from_le_bytes(word));
|
||||
}
|
||||
}
|
||||
#[inline]
|
||||
fn write_u8(&mut self, i: u8) {
|
||||
self.add(u64::from(i));
|
||||
}
|
||||
#[inline]
|
||||
fn write_u16(&mut self, i: u16) {
|
||||
self.add(u64::from(i));
|
||||
}
|
||||
#[inline]
|
||||
fn write_u32(&mut self, i: u32) {
|
||||
self.add(u64::from(i));
|
||||
}
|
||||
#[inline]
|
||||
fn write_u64(&mut self, i: u64) {
|
||||
self.add(i);
|
||||
}
|
||||
#[inline]
|
||||
fn write_usize(&mut self, i: usize) {
|
||||
self.add(i as u64);
|
||||
}
|
||||
#[inline]
|
||||
fn write_i32(&mut self, i: i32) {
|
||||
self.add(u64::from(i as u32));
|
||||
}
|
||||
#[inline]
|
||||
fn finish(&self) -> u64 {
|
||||
// The multiply leaves the low bits weakest; hash tables use them.
|
||||
self.hash.rotate_left(26)
|
||||
}
|
||||
}
|
||||
pub type FxBuild = BuildHasherDefault<FxHasher>;
|
||||
pub type FxHashMap<K, V> = std::collections::HashMap<K, V, FxBuild>;
|
||||
pub type FxHashSet<K> = std::collections::HashSet<K, FxBuild>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn nearby_chunks_spread_over_buckets() {
|
||||
let mut map: FxHashMap<(i32, i32), i32> = FxHashMap::default();
|
||||
for x in -40..40 {
|
||||
for z in -40..40 {
|
||||
map.insert((x, z), x * z);
|
||||
}
|
||||
}
|
||||
assert_eq!(map.len(), 6400);
|
||||
assert_eq!(map[&(-7, 13)], -91);
|
||||
let mut low = std::collections::HashSet::new();
|
||||
for x in 0..64 {
|
||||
low.insert(std::hash::BuildHasher::hash_one(&FxBuild::default(), (x, 0)) & 63);
|
||||
}
|
||||
assert!(low.len() > 32, "low bits vary: {}", low.len());
|
||||
}
|
||||
}
|
||||
@@ -783,6 +783,8 @@ struct Game<'a> {
|
||||
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
|
||||
/// A scripted flight from the control socket (`fly`).
|
||||
flight: Option<control::Flight>,
|
||||
/// The overworld's last `sky_darken` and its inputs (time, rain, thunder).
|
||||
sky_darken_memo: std::cell::Cell<Option<((i64, u32, u32), i32)>>,
|
||||
persist: persist::EntityMemory,
|
||||
/// Connected to a server: the world comes from the network (game/remote.rs).
|
||||
remote: Option<remote::Remote>,
|
||||
@@ -4608,11 +4610,20 @@ impl Game<'_> {
|
||||
.sample(self.world.day_time, None, None);
|
||||
return (15.0 - 15.0 * sky.sky_light_level).round() as i32;
|
||||
}
|
||||
let mut sky = self.res.environment.sample(self.world.day_time, None, None);
|
||||
let (rain, thunder) = self.world.weather.levels(1.0);
|
||||
// Sampled once per (time, weather): every mob asks each tick.
|
||||
let key = (self.world.day_time, rain.to_bits(), thunder.to_bits());
|
||||
if let Some((k, darken)) = self.sky_darken_memo.get()
|
||||
&& k == key
|
||||
{
|
||||
return darken;
|
||||
}
|
||||
let mut sky = self.res.environment.sample(self.world.day_time, None, None);
|
||||
horizon_client::environment::apply_weather(&mut sky, rain, thunder);
|
||||
// Level.updateSkyBrightness: darkening from the sky light level.
|
||||
(15.0 - 15.0 * sky.sky_light_level).round() as i32
|
||||
let darken = (15.0 - 15.0 * sky.sky_light_level).round() as i32;
|
||||
self.sky_darken_memo.set(Some((key, darken)));
|
||||
darken
|
||||
}
|
||||
fn mob_hit(&self) -> Option<(usize, f64)> {
|
||||
let eye = self.eye_position()?;
|
||||
@@ -8178,10 +8189,7 @@ pub fn run() -> Result<()> {
|
||||
biomes: biomes.clone(),
|
||||
light,
|
||||
});
|
||||
let threads = std::thread::available_parallelism()
|
||||
.map_or(2, |n| n.get())
|
||||
.saturating_sub(1)
|
||||
.max(1);
|
||||
let threads = early_settings.horizon.worker_threads();
|
||||
eprintln!(
|
||||
"Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads",
|
||||
started.elapsed().as_secs_f32(),
|
||||
@@ -8456,6 +8464,7 @@ pub fn run() -> Result<()> {
|
||||
pending_screenshot: None,
|
||||
pending_bench: None,
|
||||
flight: None,
|
||||
sky_darken_memo: Default::default(),
|
||||
persist: Default::default(),
|
||||
remote: None,
|
||||
lan: None,
|
||||
|
||||
@@ -18,7 +18,7 @@ use horizon_core::{
|
||||
};
|
||||
use horizon_world::registry::BlockStateId;
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
collections::HashMap,
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
@@ -319,7 +319,16 @@ impl Game<'_> {
|
||||
let Some(chunk) = self.world.chunks.get(&key).cloned() else {
|
||||
continue;
|
||||
};
|
||||
let name = |id: u16| &*self.res.facts.get(BlockStateId(u32::from(id))).name;
|
||||
if self.creaking.hearts.is_empty() {
|
||||
self.creaking.hearts = self
|
||||
.res
|
||||
.facts
|
||||
.states
|
||||
.iter()
|
||||
.map(|f| &*f.name == "minecraft:creaking_heart")
|
||||
.collect();
|
||||
}
|
||||
let hearts = &self.creaking.hearts;
|
||||
let _ = heart;
|
||||
for (si, section) in chunk.sections.iter().enumerate() {
|
||||
if section.is_uniform(0) {
|
||||
@@ -327,7 +336,7 @@ impl Game<'_> {
|
||||
}
|
||||
for i in 0..4096 {
|
||||
let id = section.get(i);
|
||||
if name(id) != "minecraft:creaking_heart" {
|
||||
if !hearts.get(usize::from(id)).copied().unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32);
|
||||
@@ -343,8 +352,8 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
let loaded: HashSet<(i32, i32)> = self.world.chunks.keys().copied().collect();
|
||||
self.creaking.scanned.retain(|k| loaded.contains(k));
|
||||
let chunks = &self.world.chunks;
|
||||
self.creaking.scanned.retain(|k| chunks.contains_key(k));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,5 +361,7 @@ impl Game<'_> {
|
||||
#[derive(Default)]
|
||||
pub(super) struct CreakingState {
|
||||
/// Chunks already scanned for heart blocks.
|
||||
scanned: HashSet<(i32, i32)>,
|
||||
scanned: horizon_client::fast_hash::FxHashSet<(i32, i32)>,
|
||||
/// Which block states are creaking hearts, by state id.
|
||||
hearts: Vec<bool>,
|
||||
}
|
||||
|
||||
@@ -403,6 +403,25 @@ impl Game<'_> {
|
||||
self.tick_raids();
|
||||
self.tick_creature_entities()
|
||||
}
|
||||
/// `DistanceManager.inEntityTickingRange`: chunks within the simulation
|
||||
/// distance (Chebyshev, in chunks) of the player or of a guest.
|
||||
pub(super) fn entity_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> {
|
||||
let d = self.settings.simulation_distance.max(2);
|
||||
let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect();
|
||||
if let Some(p) = &self.player {
|
||||
centres.push((
|
||||
(p.position.x.floor() as i32) >> 4,
|
||||
(p.position.z.floor() as i32) >> 4,
|
||||
));
|
||||
}
|
||||
let everywhere = centres.is_empty();
|
||||
move |x, z| {
|
||||
everywhere
|
||||
|| centres
|
||||
.iter()
|
||||
.any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d)
|
||||
}
|
||||
}
|
||||
/// The entity phase of `tick_creatures`: every mob's tick, deaths, and the
|
||||
/// projectiles and effects that follow from them.
|
||||
pub(super) fn tick_creature_entities(&mut self) -> Result<()> {
|
||||
@@ -424,6 +443,7 @@ impl Game<'_> {
|
||||
let mut mobs = std::mem::take(&mut self.mobs);
|
||||
let mut dead = Vec::new();
|
||||
let mut died = std::mem::take(&mut self.died);
|
||||
let ticking = self.entity_ticking_area();
|
||||
let level_random;
|
||||
{
|
||||
// The level random, lent to the mobs (brain behaviours draw from
|
||||
@@ -441,6 +461,18 @@ impl Game<'_> {
|
||||
keep.push(!m.hostile() || m.persistent);
|
||||
continue;
|
||||
}
|
||||
// ServerLevel.tick: every loaded entity checks despawning, but
|
||||
// only those in entity-ticking chunks (within the simulation
|
||||
// distance) tick.
|
||||
if !ticking(m.position.x.floor() as i32, m.position.z.floor() as i32) {
|
||||
let kept = horizon_client::mobs::ai::despawn_check(m, &w);
|
||||
if !kept {
|
||||
died.remove(&m.id);
|
||||
snapshot[i].alive = false;
|
||||
}
|
||||
keep.push(kept);
|
||||
continue;
|
||||
}
|
||||
horizon_client::mobs::apply_mob_pushes(m, &mut pushes);
|
||||
let from = events.len();
|
||||
let kept = m.tick(&w, &mut scratch, &mut events);
|
||||
|
||||
@@ -376,6 +376,7 @@ impl Game<'_> {
|
||||
self.set_default_game_mode(game_mode);
|
||||
self.ui.difficulty = props.difficulty as u8;
|
||||
self.settings.render_distance = props.view_distance.clamp(2, 32);
|
||||
self.settings.simulation_distance = props.simulation_distance.clamp(2, 32);
|
||||
self.streaming.radius = self.settings.render_distance;
|
||||
self.settle_spawn()?;
|
||||
let gate_lists = lists.clone();
|
||||
|
||||
@@ -142,7 +142,8 @@ impl Game<'_> {
|
||||
let s = &self.settings;
|
||||
if let Some(r) = self.renderer.as_mut() {
|
||||
r.gamma = s.gamma;
|
||||
r.set_vsync(s.vsync);
|
||||
r.set_present_mode(s.vsync, s.horizon.present_mode);
|
||||
r.animated_textures = s.horizon.animated_textures;
|
||||
}
|
||||
if let Some(w) = &self.window {
|
||||
let want = s.fullscreen;
|
||||
@@ -207,6 +208,14 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
let limit = self.framerate_limit();
|
||||
horizon_client::window::end_frame(&mut self.limiter, limit, &mut self.frame_clock);
|
||||
match self.settings.horizon.pacing {
|
||||
horizon_client::graphics::Pacing::Precise => {
|
||||
horizon_client::window::end_frame(&mut self.limiter, limit, &mut self.frame_clock)
|
||||
}
|
||||
horizon_client::graphics::Pacing::Efficient => {
|
||||
let mut clock = horizon_client::window::SleepingClock(self.frame_clock);
|
||||
horizon_client::window::end_frame(&mut self.limiter, limit, &mut clock);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+162
-119
@@ -13,6 +13,8 @@ use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Instant};
|
||||
use wgpu::util::DeviceExt;
|
||||
use winit::window::Window;
|
||||
|
||||
mod arena;
|
||||
mod occlusion;
|
||||
mod timing;
|
||||
|
||||
#[repr(C)]
|
||||
@@ -35,10 +37,13 @@ struct Globals {
|
||||
}
|
||||
pub type SectionKey = (i32, i32, i32);
|
||||
struct SectionGpu {
|
||||
buffer: wgpu::Buffer,
|
||||
/// First vertex in the section arena: solid quads, then translucent ones.
|
||||
start: u64,
|
||||
solid: u32,
|
||||
translucent: u32,
|
||||
}
|
||||
/// A visible section this frame: key, squared distance, camera-relative origin.
|
||||
type Visible = (SectionKey, f64, [f32; 3]);
|
||||
/// Line segments the hit outline can hold.
|
||||
const MAX_OUTLINE_EDGES: u64 = 256;
|
||||
pub struct Frame<'a> {
|
||||
@@ -169,13 +174,22 @@ pub struct Renderer {
|
||||
outline: wgpu::Buffer,
|
||||
depth: wgpu::TextureView,
|
||||
sections: HashMap<SectionKey, SectionGpu>,
|
||||
arena: arena::Arena,
|
||||
/// `DrawIndexedIndirectArgs` for this frame's solid then translucent draws.
|
||||
indirect: wgpu::Buffer,
|
||||
indirect_capacity: u64,
|
||||
/// Indirect draws may set `first_instance` (the section origin).
|
||||
multi_draw: bool,
|
||||
/// Per-frame scratch, kept to avoid allocating every frame.
|
||||
visible: Vec<Visible>,
|
||||
origins: Vec<[f32; 4]>,
|
||||
/// `DrawIndexedIndirectArgs` words: index count, instance count, first
|
||||
/// index, base vertex, first instance.
|
||||
draws: Vec<[u32; 5]>,
|
||||
/// Block-entity blocks per meshed section (world position, state id).
|
||||
block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>,
|
||||
/// VisGraph face connectivity per meshed section (cave culling).
|
||||
visibility: HashMap<SectionKey, u64>,
|
||||
reachable: std::collections::HashSet<SectionKey>,
|
||||
reachable_from: Option<SectionKey>,
|
||||
visibility_dirty: bool,
|
||||
occlusion: occlusion::Occlusion,
|
||||
pub hud: HudRenderer,
|
||||
pub info: wgpu::AdapterInfo,
|
||||
pub suspended: bool,
|
||||
@@ -188,6 +202,8 @@ pub struct Renderer {
|
||||
pub screenshot_result: Option<std::result::Result<[u32; 2], String>>,
|
||||
/// Brightness option (lightmap gamma), 0..1.
|
||||
pub gamma: f32,
|
||||
/// Advance animated block textures (Horizon setting; vanilla always does).
|
||||
pub animated_textures: bool,
|
||||
present_modes: Vec<wgpu::PresentMode>,
|
||||
}
|
||||
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
|
||||
@@ -1085,6 +1101,16 @@ impl Renderer {
|
||||
usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let arena = arena::Arena::new(&device, std::mem::size_of::<Vertex>() as u64, 1 << 20);
|
||||
let indirect = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section draws"),
|
||||
size: 1024 * 20,
|
||||
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let multi_draw = device
|
||||
.features()
|
||||
.contains(wgpu::Features::INDIRECT_FIRST_INSTANCE);
|
||||
Ok(Self {
|
||||
instance,
|
||||
surface,
|
||||
@@ -1130,11 +1156,15 @@ impl Renderer {
|
||||
outline,
|
||||
depth,
|
||||
sections: HashMap::new(),
|
||||
arena,
|
||||
indirect,
|
||||
indirect_capacity: 1024,
|
||||
multi_draw,
|
||||
visible: Vec::new(),
|
||||
origins: Vec::new(),
|
||||
draws: Vec::new(),
|
||||
block_entities: HashMap::new(),
|
||||
visibility: HashMap::new(),
|
||||
reachable: std::collections::HashSet::new(),
|
||||
reachable_from: None,
|
||||
visibility_dirty: true,
|
||||
occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16),
|
||||
hud,
|
||||
info,
|
||||
suspended: size.width == 0 || size.height == 0,
|
||||
@@ -1144,6 +1174,7 @@ impl Renderer {
|
||||
screenshot: None,
|
||||
screenshot_result: None,
|
||||
gamma: 0.5,
|
||||
animated_textures: true,
|
||||
present_modes,
|
||||
})
|
||||
}
|
||||
@@ -1202,6 +1233,27 @@ impl Renderer {
|
||||
.create_view(&Default::default())
|
||||
}
|
||||
/// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available.
|
||||
/// VSync, unless Horizon's present-mode setting names a supported mode.
|
||||
pub fn set_present_mode(&mut self, vsync: bool, mode: crate::graphics::PresentMode) {
|
||||
use crate::graphics::PresentMode as P;
|
||||
let wanted = match mode {
|
||||
P::Auto => None,
|
||||
P::Fifo => Some(wgpu::PresentMode::Fifo),
|
||||
P::Mailbox => Some(wgpu::PresentMode::Mailbox),
|
||||
P::Immediate => Some(wgpu::PresentMode::Immediate),
|
||||
};
|
||||
match wanted.filter(|m| self.present_modes.contains(m)) {
|
||||
Some(m) => {
|
||||
if self.config.present_mode != m
|
||||
&& let Some(surface) = &self.surface
|
||||
{
|
||||
self.config.present_mode = m;
|
||||
surface.configure(&self.device, &self.config);
|
||||
}
|
||||
}
|
||||
None => self.set_vsync(vsync),
|
||||
}
|
||||
}
|
||||
pub fn set_vsync(&mut self, vsync: bool) {
|
||||
use crate::window::{PresentMode, vsync_present_mode};
|
||||
let supported: Vec<PresentMode> = self
|
||||
@@ -1245,9 +1297,7 @@ impl Renderer {
|
||||
self.sections.len()
|
||||
}
|
||||
pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) {
|
||||
if self.visibility.insert(key, mesh.visibility) != Some(mesh.visibility) {
|
||||
self.visibility_dirty = true;
|
||||
}
|
||||
self.occlusion.set(key, mesh.visibility);
|
||||
if mesh.block_entities.is_empty() {
|
||||
self.block_entities.remove(&key);
|
||||
} else {
|
||||
@@ -1255,8 +1305,8 @@ impl Renderer {
|
||||
}
|
||||
let solid = (mesh.solid.len() / 4) as u32;
|
||||
let translucent = (mesh.translucent.len() / 4) as u32;
|
||||
self.release_section(key);
|
||||
if solid + translucent == 0 {
|
||||
self.sections.remove(&key);
|
||||
return;
|
||||
}
|
||||
let max = solid.max(translucent);
|
||||
@@ -1264,27 +1314,49 @@ impl Renderer {
|
||||
self.index_quads = max.next_power_of_two();
|
||||
self.indices = Self::quad_indices(&self.device, self.index_quads);
|
||||
}
|
||||
let mut data = Vec::with_capacity(mesh.solid.len() + mesh.translucent.len());
|
||||
data.extend_from_slice(&mesh.solid);
|
||||
data.extend_from_slice(&mesh.translucent);
|
||||
let bytes: &[u8] = bytemuck::cast_slice(&data);
|
||||
self.uploaded_bytes += bytes.len() as u64;
|
||||
let buffer = self
|
||||
.device
|
||||
.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("Section mesh"),
|
||||
contents: bytes,
|
||||
usage: wgpu::BufferUsages::VERTEX,
|
||||
});
|
||||
let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64;
|
||||
let start = self.arena.alloc(&self.device, &self.queue, vertices);
|
||||
let stride = std::mem::size_of::<Vertex>() as u64;
|
||||
for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] {
|
||||
if !part.is_empty() {
|
||||
let bytes: &[u8] = bytemuck::cast_slice(part);
|
||||
self.uploaded_bytes += bytes.len() as u64;
|
||||
self.queue.write_buffer(
|
||||
&self.arena.buffer,
|
||||
(start + offset as u64) * stride,
|
||||
bytes,
|
||||
);
|
||||
}
|
||||
}
|
||||
self.sections.insert(
|
||||
key,
|
||||
SectionGpu {
|
||||
buffer,
|
||||
start,
|
||||
solid,
|
||||
translucent,
|
||||
},
|
||||
);
|
||||
}
|
||||
/// Draws `count` section draws from `first` with the arena and section
|
||||
/// origins bound: one indirect multi-draw, or a loop without it.
|
||||
fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) {
|
||||
if count == 0 {
|
||||
return;
|
||||
}
|
||||
if self.multi_draw {
|
||||
pass.multi_draw_indexed_indirect(&self.indirect, u64::from(first) * 20, count);
|
||||
} else {
|
||||
for d in &self.draws[first as usize..(first + count) as usize] {
|
||||
pass.draw_indexed(0..d[0], d[3] as i32, d[4]..d[4] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn release_section(&mut self, key: SectionKey) {
|
||||
if let Some(s) = self.sections.remove(&key) {
|
||||
self.arena
|
||||
.release(s.start, u64::from(s.solid + s.translucent) * 4);
|
||||
}
|
||||
}
|
||||
/// Block-entity blocks of every meshed section (see `SectionMesh::block_entities`).
|
||||
pub fn block_entities(&self) -> impl Iterator<Item = &([i32; 3], u32)> {
|
||||
self.block_entities.values().flatten()
|
||||
@@ -1292,63 +1364,13 @@ impl Renderer {
|
||||
pub fn clear_sections(&mut self) {
|
||||
self.block_entities.clear();
|
||||
self.sections.clear();
|
||||
self.visibility.clear();
|
||||
self.visibility_dirty = true;
|
||||
}
|
||||
/// SectionOcclusionGraph: breadth-first from the camera section through
|
||||
/// faces its VisGraph connects, never stepping back towards the camera.
|
||||
fn update_reachable(&mut self, from: SectionKey, radius: i32) {
|
||||
const STEPS: [(i32, i32, i32); 6] = [
|
||||
(0, -1, 0),
|
||||
(0, 1, 0),
|
||||
(0, 0, -1),
|
||||
(0, 0, 1),
|
||||
(-1, 0, 0),
|
||||
(1, 0, 0),
|
||||
];
|
||||
let opposite = |d: usize| d ^ 1;
|
||||
self.reachable.clear();
|
||||
let mut queue = std::collections::VecDeque::new();
|
||||
// (section, entered face, directions travelled)
|
||||
queue.push_back((from, None::<usize>, 0u8));
|
||||
self.reachable.insert(from);
|
||||
let sections = crate::chunk::HEIGHT / 16;
|
||||
while let Some((key, entered, travelled)) = queue.pop_front() {
|
||||
let vis = self
|
||||
.visibility
|
||||
.get(&key)
|
||||
.copied()
|
||||
.unwrap_or(crate::mesher::ALL_VISIBLE);
|
||||
for (d, step) in STEPS.iter().enumerate() {
|
||||
if travelled & (1 << opposite(d)) != 0 {
|
||||
continue;
|
||||
}
|
||||
if let Some(e) = entered
|
||||
&& vis & (1 << (e * 6 + d)) == 0
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2);
|
||||
if next.1 < -1
|
||||
|| next.1 > sections
|
||||
|| (next.0 - from.0).abs() > radius
|
||||
|| (next.2 - from.2).abs() > radius
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if self.reachable.insert(next) {
|
||||
queue.push_back((next, Some(opposite(d)), travelled | (1 << d)));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.reachable_from = Some(from);
|
||||
self.visibility_dirty = false;
|
||||
self.arena.clear();
|
||||
self.occlusion.clear();
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
self.block_entities.remove(&key);
|
||||
self.visibility.remove(&key);
|
||||
self.visibility_dirty = true;
|
||||
self.sections.remove(&key);
|
||||
self.occlusion.remove(key);
|
||||
self.release_section(key);
|
||||
}
|
||||
pub fn view_projection(&self, frame: &Frame) -> Mat4 {
|
||||
let aspect = self.config.width as f32 / self.config.height.max(1) as f32;
|
||||
@@ -1497,7 +1519,9 @@ impl Renderer {
|
||||
Some(f) => f.texture.clone(),
|
||||
None => self.offscreen.clone().ok_or("no offscreen target")?,
|
||||
};
|
||||
self.animate(frame.ticks);
|
||||
if self.animated_textures {
|
||||
self.animate(frame.ticks);
|
||||
}
|
||||
self.update_lightmap(
|
||||
&frame.sky,
|
||||
frame.darkness.1,
|
||||
@@ -1592,15 +1616,17 @@ impl Renderer {
|
||||
(camera.z.floor() as i32) >> 4,
|
||||
);
|
||||
let culling = !frame.title && frame.cave_culling;
|
||||
if culling && (self.visibility_dirty || self.reachable_from != Some(camera_section)) {
|
||||
if culling {
|
||||
let radius = (frame.distance / 16.0) as i32 + 2;
|
||||
self.update_reachable(camera_section, radius);
|
||||
self.occlusion.update(camera_section, radius);
|
||||
}
|
||||
let reachable = &self.reachable;
|
||||
let mut visible: Vec<(SectionKey, f64, [f32; 3])> = self
|
||||
.sections
|
||||
let reachable = &self.occlusion;
|
||||
let mut visible = std::mem::take(&mut self.visible);
|
||||
visible.clear();
|
||||
visible.extend(
|
||||
self.sections
|
||||
.keys()
|
||||
.filter(|k| !culling || reachable.contains(k))
|
||||
.filter(|&&k| !culling || reachable.contains(k))
|
||||
.filter_map(|&(sx, sy, sz)| {
|
||||
let origin = DVec3::new(
|
||||
f64::from(sx * 16),
|
||||
@@ -1629,9 +1655,9 @@ impl Renderer {
|
||||
center.length_squared(),
|
||||
origin.as_vec3().to_array(),
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
visible.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
}),
|
||||
);
|
||||
visible.sort_unstable_by(|a, b| a.1.total_cmp(&b.1));
|
||||
self.drawn_sections = visible.len();
|
||||
if visible.len() as u64 > self.instance_capacity {
|
||||
self.instance_capacity = (visible.len() as u64).next_power_of_two();
|
||||
@@ -1642,13 +1668,47 @@ impl Renderer {
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
}
|
||||
let origins: Vec<[f32; 4]> = visible
|
||||
.iter()
|
||||
.map(|(_, _, o)| [o[0], o[1], o[2], 0.0])
|
||||
.collect();
|
||||
if !origins.is_empty() {
|
||||
self.origins.clear();
|
||||
self.origins
|
||||
.extend(visible.iter().map(|(_, _, o)| [o[0], o[1], o[2], 0.0]));
|
||||
if !self.origins.is_empty() {
|
||||
self.queue
|
||||
.write_buffer(&self.instances, 0, bytemuck::cast_slice(&origins));
|
||||
.write_buffer(&self.instances, 0, bytemuck::cast_slice(&self.origins));
|
||||
}
|
||||
if frame.title {
|
||||
visible.clear();
|
||||
}
|
||||
// Solid sections front to back, then translucent ones back to front,
|
||||
// as one list of indirect draws over the section arena.
|
||||
self.draws.clear();
|
||||
let draw = |s: &SectionGpu, i: usize, translucent: bool| {
|
||||
let (quads, first) = if translucent {
|
||||
(s.translucent, s.start + u64::from(s.solid) * 4)
|
||||
} else {
|
||||
(s.solid, s.start)
|
||||
};
|
||||
(quads > 0).then_some([quads * 6, 1, 0, first as u32, i as u32])
|
||||
};
|
||||
for (i, (key, _, _)) in visible.iter().enumerate() {
|
||||
self.draws.extend(draw(&self.sections[key], i, false));
|
||||
}
|
||||
let solid_draws = self.draws.len() as u32;
|
||||
for (i, (key, _, _)) in visible.iter().enumerate().rev() {
|
||||
self.draws.extend(draw(&self.sections[key], i, true));
|
||||
}
|
||||
let translucent_draws = self.draws.len() as u32 - solid_draws;
|
||||
if self.multi_draw && !self.draws.is_empty() {
|
||||
if self.draws.len() as u64 > self.indirect_capacity {
|
||||
self.indirect_capacity = (self.draws.len() as u64).next_power_of_two();
|
||||
self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section draws"),
|
||||
size: self.indirect_capacity * 20,
|
||||
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
}
|
||||
self.queue
|
||||
.write_buffer(&self.indirect, 0, bytemuck::cast_slice(&self.draws));
|
||||
}
|
||||
let outline_edges = frame.outline.len().min(MAX_OUTLINE_EDGES as usize);
|
||||
if outline_edges > 0 {
|
||||
@@ -1811,20 +1871,11 @@ impl Renderer {
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
if frame.title {
|
||||
visible.clear();
|
||||
}
|
||||
pass.set_pipeline(&self.solid);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.arena.buffer.slice(..));
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
for (i, (key, _, _)) in visible.iter().enumerate() {
|
||||
let s = &self.sections[key];
|
||||
if s.solid == 0 {
|
||||
continue;
|
||||
}
|
||||
pass.set_vertex_buffer(0, s.buffer.slice(..));
|
||||
pass.draw_indexed(0..s.solid * 6, 0, i as u32..i as u32 + 1);
|
||||
}
|
||||
self.draw_sections(&mut pass, 0, solid_draws);
|
||||
if entity_quads > 0 {
|
||||
pass.set_pipeline(&self.entity_pipeline);
|
||||
pass.set_bind_group(0, &self.entity_group, &[]);
|
||||
@@ -1845,19 +1896,10 @@ impl Renderer {
|
||||
pass.draw(0..outline_edges as u32 * 2, 0..1);
|
||||
}
|
||||
pass.set_pipeline(&self.translucent);
|
||||
pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32);
|
||||
pass.set_vertex_buffer(0, self.arena.buffer.slice(..));
|
||||
pass.set_vertex_buffer(1, self.instances.slice(..));
|
||||
for (i, (key, _, _)) in visible.iter().enumerate().rev() {
|
||||
let s = &self.sections[key];
|
||||
if s.translucent == 0 {
|
||||
continue;
|
||||
}
|
||||
pass.set_vertex_buffer(0, s.buffer.slice(..));
|
||||
pass.draw_indexed(
|
||||
0..s.translucent * 6,
|
||||
(s.solid * 4) as i32,
|
||||
i as u32..i as u32 + 1,
|
||||
);
|
||||
}
|
||||
self.draw_sections(&mut pass, solid_draws, translucent_draws);
|
||||
// LevelRenderer: the world border after translucent terrain and weather.
|
||||
if let Some(b) = frame.border.as_ref().filter(|_| !frame.title) {
|
||||
pass.set_pipeline(&self.border_pipeline);
|
||||
@@ -1992,6 +2034,7 @@ impl Renderer {
|
||||
self.last_wait += present.elapsed();
|
||||
self.last_encode = started.elapsed().saturating_sub(self.last_wait);
|
||||
let _ = self.started;
|
||||
self.visible = visible;
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! One vertex buffer for every terrain section: sections own ranges of it, so
|
||||
//! a frame binds it once and draws every section with indirect multi-draw.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Ranges are rounded up to this many vertices to limit fragmentation.
|
||||
const GRAIN: u64 = 256;
|
||||
|
||||
/// Free vertex ranges: start -> length, never adjacent.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct FreeList(BTreeMap<u64, u64>);
|
||||
|
||||
impl FreeList {
|
||||
fn new(capacity: u64) -> Self {
|
||||
Self(BTreeMap::from([(0, capacity)]))
|
||||
}
|
||||
/// First fit.
|
||||
fn take(&mut self, len: u64) -> Option<u64> {
|
||||
let (&start, &free) = self.0.iter().find(|(_, l)| **l >= len)?;
|
||||
self.0.remove(&start);
|
||||
if free > len {
|
||||
self.0.insert(start + len, free - len);
|
||||
}
|
||||
Some(start)
|
||||
}
|
||||
fn give(&mut self, start: u64, len: u64) {
|
||||
let (mut start, mut len) = (start, len);
|
||||
if let Some((&prev, &prev_len)) = self.0.range(..start).next_back()
|
||||
&& prev + prev_len == start
|
||||
{
|
||||
self.0.remove(&prev);
|
||||
start = prev;
|
||||
len += prev_len;
|
||||
}
|
||||
if let Some(next_len) = self.0.remove(&(start + len)) {
|
||||
len += next_len;
|
||||
}
|
||||
self.0.insert(start, len);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Arena {
|
||||
pub buffer: wgpu::Buffer,
|
||||
/// Capacity in vertices.
|
||||
capacity: u64,
|
||||
stride: u64,
|
||||
free: FreeList,
|
||||
}
|
||||
|
||||
impl Arena {
|
||||
pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self {
|
||||
let capacity = capacity.next_multiple_of(GRAIN);
|
||||
Self {
|
||||
buffer: Self::create(device, stride, capacity),
|
||||
capacity,
|
||||
stride,
|
||||
free: FreeList::new(capacity),
|
||||
}
|
||||
}
|
||||
fn create(device: &wgpu::Device, stride: u64, capacity: u64) -> wgpu::Buffer {
|
||||
device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("Section vertex arena"),
|
||||
size: capacity * stride,
|
||||
usage: wgpu::BufferUsages::VERTEX
|
||||
| wgpu::BufferUsages::COPY_DST
|
||||
| wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
})
|
||||
}
|
||||
/// The rounded length a request of `vertices` occupies.
|
||||
fn span(vertices: u64) -> u64 {
|
||||
vertices.max(1).next_multiple_of(GRAIN)
|
||||
}
|
||||
/// A range of `vertices`, growing the buffer (copying its contents on the
|
||||
/// GPU) when no free range is large enough. Returns the first vertex.
|
||||
pub fn alloc(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, vertices: u64) -> u64 {
|
||||
let len = Self::span(vertices);
|
||||
if let Some(start) = self.free.take(len) {
|
||||
return start;
|
||||
}
|
||||
self.grow(device, queue, (self.capacity * 2).max(self.capacity + len));
|
||||
self.free.take(len).expect("grown arena has room")
|
||||
}
|
||||
pub fn release(&mut self, start: u64, vertices: u64) {
|
||||
self.free.give(start, Self::span(vertices));
|
||||
}
|
||||
fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, capacity: u64) {
|
||||
let capacity = capacity.next_multiple_of(GRAIN);
|
||||
let buffer = Self::create(device, self.stride, capacity);
|
||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
||||
label: Some("Grow section arena"),
|
||||
});
|
||||
encoder.copy_buffer_to_buffer(&self.buffer, 0, &buffer, 0, self.capacity * self.stride);
|
||||
// Writes queued for the old buffer run before this copy.
|
||||
queue.submit([encoder.finish()]);
|
||||
let old = self.capacity;
|
||||
self.buffer = buffer;
|
||||
self.capacity = capacity;
|
||||
self.free.give(old, capacity - old);
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.free = FreeList::new(self.capacity);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn free_ranges_coalesce() {
|
||||
let mut free = FreeList::new(4 * GRAIN);
|
||||
let a = free.take(GRAIN).unwrap();
|
||||
let b = free.take(2 * GRAIN).unwrap();
|
||||
let c = free.take(GRAIN).unwrap();
|
||||
assert_eq!((a, b, c), (0, GRAIN, 3 * GRAIN));
|
||||
assert_eq!(free.take(1), None);
|
||||
free.give(a, GRAIN);
|
||||
free.give(c, GRAIN);
|
||||
// Two holes of one grain: a two-grain request does not fit.
|
||||
assert_eq!(free.take(2 * GRAIN), None);
|
||||
free.give(b, 2 * GRAIN);
|
||||
assert_eq!(free, FreeList::new(4 * GRAIN));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_fit_reuses_the_lowest_hole() {
|
||||
let mut free = FreeList::new(8 * GRAIN);
|
||||
let a = free.take(GRAIN).unwrap();
|
||||
let _b = free.take(GRAIN).unwrap();
|
||||
free.give(a, GRAIN);
|
||||
assert_eq!(free.take(GRAIN), Some(a));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! `SectionOcclusionGraph`: which sections the camera can see through open
|
||||
//! faces. Breadth-first from the camera section through the faces each
|
||||
//! section's VisGraph connects, never stepping back towards the camera.
|
||||
//!
|
||||
//! The search runs over dense arrays around the camera rather than hash sets,
|
||||
//! so it stays cheap enough to redo whenever a section is meshed.
|
||||
use super::SectionKey;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
const STEPS: [(i32, i32, i32); 6] = [
|
||||
(0, -1, 0),
|
||||
(0, 1, 0),
|
||||
(0, 0, -1),
|
||||
(0, 0, 1),
|
||||
(-1, 0, 0),
|
||||
(1, 0, 0),
|
||||
];
|
||||
const NONE: u8 = 6;
|
||||
|
||||
pub struct Occlusion {
|
||||
/// VisGraph connectivity per column, one entry per section (bottom first).
|
||||
columns: HashMap<(i32, i32), Box<[u64]>>,
|
||||
sections: i32,
|
||||
dirty: bool,
|
||||
from: Option<SectionKey>,
|
||||
radius: i32,
|
||||
/// The searched box: lowest section y and its height in sections.
|
||||
y0: i32,
|
||||
height: i32,
|
||||
reached: Vec<bool>,
|
||||
vis: Vec<u64>,
|
||||
queue: VecDeque<(u32, u8, u8)>,
|
||||
}
|
||||
|
||||
impl Occlusion {
|
||||
pub fn new(sections: i32) -> Self {
|
||||
Self {
|
||||
columns: HashMap::new(),
|
||||
sections,
|
||||
dirty: true,
|
||||
from: None,
|
||||
radius: 0,
|
||||
y0: 0,
|
||||
height: 0,
|
||||
reached: Vec::new(),
|
||||
vis: Vec::new(),
|
||||
queue: VecDeque::new(),
|
||||
}
|
||||
}
|
||||
pub fn set(&mut self, key: SectionKey, vis: u64) {
|
||||
if !(0..self.sections).contains(&key.1) {
|
||||
return;
|
||||
}
|
||||
let sections = self.sections as usize;
|
||||
let column = self
|
||||
.columns
|
||||
.entry((key.0, key.2))
|
||||
.or_insert_with(|| vec![crate::mesher::ALL_VISIBLE; sections].into());
|
||||
let slot = &mut column[key.1 as usize];
|
||||
if *slot != vis {
|
||||
*slot = vis;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
pub fn remove(&mut self, key: SectionKey) {
|
||||
let Some(column) = self.columns.get_mut(&(key.0, key.2)) else {
|
||||
return;
|
||||
};
|
||||
if let Some(slot) = column.get_mut(key.1 as usize)
|
||||
&& *slot != crate::mesher::ALL_VISIBLE
|
||||
{
|
||||
*slot = crate::mesher::ALL_VISIBLE;
|
||||
self.dirty = true;
|
||||
}
|
||||
if column.iter().all(|&v| v == crate::mesher::ALL_VISIBLE) {
|
||||
self.columns.remove(&(key.0, key.2));
|
||||
}
|
||||
}
|
||||
pub fn clear(&mut self) {
|
||||
self.columns.clear();
|
||||
self.dirty = true;
|
||||
}
|
||||
fn index(&self, key: SectionKey) -> Option<usize> {
|
||||
let from = self.from?;
|
||||
let (dx, dz, dy) = (key.0 - from.0, key.2 - from.2, key.1 - self.y0);
|
||||
let side = 2 * self.radius + 1;
|
||||
if dx.abs() > self.radius || dz.abs() > self.radius || !(0..self.height).contains(&dy) {
|
||||
return None;
|
||||
}
|
||||
Some((((dz + self.radius) * side + dx + self.radius) * self.height + dy) as usize)
|
||||
}
|
||||
fn key(&self, index: usize) -> SectionKey {
|
||||
let from = self.from.expect("searched");
|
||||
let side = 2 * self.radius + 1;
|
||||
let i = index as i32;
|
||||
let dy = i % self.height;
|
||||
let column = i / self.height;
|
||||
(
|
||||
from.0 + column % side - self.radius,
|
||||
self.y0 + dy,
|
||||
from.2 + column / side - self.radius,
|
||||
)
|
||||
}
|
||||
pub fn contains(&self, key: SectionKey) -> bool {
|
||||
self.index(key).is_some_and(|i| self.reached[i])
|
||||
}
|
||||
/// Search again when sections changed or the camera moved to another section.
|
||||
pub fn update(&mut self, from: SectionKey, radius: i32) {
|
||||
if !self.dirty && self.from == Some(from) && self.radius == radius {
|
||||
return;
|
||||
}
|
||||
self.from = Some(from);
|
||||
self.radius = radius;
|
||||
self.y0 = from.1.min(-1);
|
||||
self.height = from.1.max(self.sections) - self.y0 + 1;
|
||||
let side = (2 * radius + 1) as usize;
|
||||
let size = side * side * self.height as usize;
|
||||
self.reached.clear();
|
||||
self.reached.resize(size, false);
|
||||
self.vis.clear();
|
||||
self.vis.resize(size, crate::mesher::ALL_VISIBLE);
|
||||
for dz in -radius..=radius {
|
||||
for dx in -radius..=radius {
|
||||
let Some(column) = self.columns.get(&(from.0 + dx, from.2 + dz)) else {
|
||||
continue;
|
||||
};
|
||||
let base = self
|
||||
.index((from.0 + dx, 0, from.2 + dz))
|
||||
.expect("column inside the searched box");
|
||||
self.vis[base..base + column.len()].copy_from_slice(column);
|
||||
}
|
||||
}
|
||||
let start = self.index(from).expect("camera inside the searched box");
|
||||
self.reached[start] = true;
|
||||
self.queue.clear();
|
||||
self.queue.push_back((start as u32, NONE, 0));
|
||||
while let Some((index, entered, travelled)) = self.queue.pop_front() {
|
||||
let vis = self.vis[index as usize];
|
||||
let key = self.key(index as usize);
|
||||
for (d, step) in STEPS.iter().enumerate() {
|
||||
let opposite = d ^ 1;
|
||||
if travelled & (1 << opposite) != 0 {
|
||||
continue;
|
||||
}
|
||||
if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 {
|
||||
continue;
|
||||
}
|
||||
let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2);
|
||||
if next.1 < -1 || next.1 > self.sections {
|
||||
continue;
|
||||
}
|
||||
let Some(n) = self.index(next) else { continue };
|
||||
if !self.reached[n] {
|
||||
self.reached[n] = true;
|
||||
self.queue
|
||||
.push_back((n as u32, opposite as u8, travelled | (1 << d)));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.dirty = false;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::mesher::ALL_VISIBLE;
|
||||
|
||||
#[test]
|
||||
fn open_space_reaches_the_whole_box() {
|
||||
let mut o = Occlusion::new(4);
|
||||
o.update((0, 1, 0), 2);
|
||||
for x in -2..=2 {
|
||||
for z in -2..=2 {
|
||||
for y in -1..=4 {
|
||||
assert!(o.contains((x, y, z)), "{x} {y} {z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(!o.contains((3, 1, 0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn closed_neighbours_hide_what_is_behind_them() {
|
||||
let mut o = Occlusion::new(4);
|
||||
for (dx, dy, dz) in STEPS {
|
||||
o.set((dx, 1 + dy, dz), 0);
|
||||
}
|
||||
o.update((0, 1, 0), 3);
|
||||
assert!(o.contains((1, 1, 0)), "a neighbour is seen");
|
||||
assert!(!o.contains((2, 1, 0)), "nothing shows through it");
|
||||
o.set((1, 1, 0), ALL_VISIBLE);
|
||||
o.update((0, 1, 0), 3);
|
||||
assert!(o.contains((2, 1, 0)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
//! Horizon's own graphics settings, beyond vanilla's options: kept in
|
||||
//! `horizon-graphics.txt` next to `options.txt` so that file stays exactly
|
||||
//! vanilla's. Every default reproduces vanilla's rendering; only choices the
|
||||
//! player makes here depart from it.
|
||||
use std::{fs, path::Path};
|
||||
|
||||
pub const FILE: &str = "horizon-graphics.txt";
|
||||
|
||||
/// Simple-level presets. `Custom` leaves every option as the player set it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Preset {
|
||||
Performance,
|
||||
Balanced,
|
||||
Quality,
|
||||
Ultra,
|
||||
#[default]
|
||||
Custom,
|
||||
}
|
||||
impl Preset {
|
||||
pub const ALL: [Preset; 5] = [
|
||||
Preset::Performance,
|
||||
Preset::Balanced,
|
||||
Preset::Quality,
|
||||
Preset::Ultra,
|
||||
Preset::Custom,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Preset::Performance => "performance",
|
||||
Preset::Balanced => "balanced",
|
||||
Preset::Quality => "quality",
|
||||
Preset::Ultra => "ultra",
|
||||
Preset::Custom => "custom",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Preset::Performance => "Performance",
|
||||
Preset::Balanced => "Balanced",
|
||||
Preset::Quality => "Quality",
|
||||
Preset::Ultra => "Ultra",
|
||||
Preset::Custom => "Custom",
|
||||
}
|
||||
}
|
||||
fn parse(s: &str) -> Self {
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|p| p.name() == s)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// How the swapchain presents frames.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum PresentMode {
|
||||
/// Follow vanilla's VSync option (Mailbox or Fifo on, Immediate off).
|
||||
#[default]
|
||||
Auto,
|
||||
Fifo,
|
||||
Mailbox,
|
||||
Immediate,
|
||||
}
|
||||
impl PresentMode {
|
||||
pub const ALL: [PresentMode; 4] = [
|
||||
PresentMode::Auto,
|
||||
PresentMode::Fifo,
|
||||
PresentMode::Mailbox,
|
||||
PresentMode::Immediate,
|
||||
];
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
PresentMode::Auto => "auto",
|
||||
PresentMode::Fifo => "fifo",
|
||||
PresentMode::Mailbox => "mailbox",
|
||||
PresentMode::Immediate => "immediate",
|
||||
}
|
||||
}
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
PresentMode::Auto => "Auto (VSync)",
|
||||
PresentMode::Fifo => "FIFO",
|
||||
PresentMode::Mailbox => "Mailbox",
|
||||
PresentMode::Immediate => "Immediate",
|
||||
}
|
||||
}
|
||||
fn parse(s: &str) -> Self {
|
||||
Self::ALL
|
||||
.into_iter()
|
||||
.find(|p| p.name() == s)
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
/// What the frame limiter does in the last half millisecond before a frame.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Pacing {
|
||||
/// Sleep the whole wait: no CPU spent spinning, a little less precise.
|
||||
#[default]
|
||||
Efficient,
|
||||
/// Vanilla's `FramerateLimiter`: sleep, then spin until the deadline.
|
||||
Precise,
|
||||
}
|
||||
|
||||
/// The performance overlay drawn over the HUD.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
|
||||
pub enum Overlay {
|
||||
#[default]
|
||||
Off,
|
||||
/// Frames per second and frame time.
|
||||
Fps,
|
||||
/// The numbers and a graph of recent frame times.
|
||||
Graph,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Graphics {
|
||||
pub preset: Preset,
|
||||
/// Skip sections hidden behind closed ones (vanilla's occlusion graph).
|
||||
pub cave_culling: bool,
|
||||
/// Meshed sections uploaded per frame; 0 uploads all that are ready.
|
||||
pub chunk_updates: u32,
|
||||
/// Section mesh bytes uploaded per frame, in KiB; 0 is unlimited.
|
||||
pub upload_budget_kib: u32,
|
||||
pub sky: bool,
|
||||
pub fog: bool,
|
||||
pub weather: bool,
|
||||
pub animated_textures: bool,
|
||||
pub present_mode: PresentMode,
|
||||
pub pacing: Pacing,
|
||||
/// Chunk worker threads; 0 uses every core but one. Applies at the next start.
|
||||
pub workers: u32,
|
||||
pub overlay: Overlay,
|
||||
}
|
||||
impl Default for Graphics {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
preset: Preset::Custom,
|
||||
cave_culling: true,
|
||||
chunk_updates: 0,
|
||||
upload_budget_kib: 0,
|
||||
sky: true,
|
||||
fog: true,
|
||||
weather: true,
|
||||
animated_textures: true,
|
||||
present_mode: PresentMode::Auto,
|
||||
pacing: Pacing::Efficient,
|
||||
workers: 0,
|
||||
overlay: Overlay::Off,
|
||||
}
|
||||
}
|
||||
}
|
||||
fn bool_text(v: bool) -> &'static str {
|
||||
if v { "true" } else { "false" }
|
||||
}
|
||||
impl Graphics {
|
||||
pub fn load(dir: &Path) -> Self {
|
||||
fs::read_to_string(dir.join(FILE))
|
||||
.map(|t| Self::parse(&t))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut g = Self::default();
|
||||
for line in text.lines() {
|
||||
let Some((key, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
let value = value.trim();
|
||||
let flag = |d: bool| match value {
|
||||
"true" => true,
|
||||
"false" => false,
|
||||
_ => d,
|
||||
};
|
||||
let number = |d: u32| value.parse().unwrap_or(d);
|
||||
match key.trim() {
|
||||
"preset" => g.preset = Preset::parse(value),
|
||||
"caveCulling" => g.cave_culling = flag(g.cave_culling),
|
||||
"chunkUpdates" => g.chunk_updates = number(g.chunk_updates).min(512),
|
||||
"uploadBudgetKiB" => g.upload_budget_kib = number(g.upload_budget_kib).min(65536),
|
||||
"sky" => g.sky = flag(g.sky),
|
||||
"fog" => g.fog = flag(g.fog),
|
||||
"weather" => g.weather = flag(g.weather),
|
||||
"animatedTextures" => g.animated_textures = flag(g.animated_textures),
|
||||
"presentMode" => g.present_mode = PresentMode::parse(value),
|
||||
"framePacing" => {
|
||||
g.pacing = if value == "precise" {
|
||||
Pacing::Precise
|
||||
} else {
|
||||
Pacing::Efficient
|
||||
}
|
||||
}
|
||||
"workers" => g.workers = number(g.workers).min(64),
|
||||
"overlay" => {
|
||||
g.overlay = match value {
|
||||
"fps" => Overlay::Fps,
|
||||
"graph" => Overlay::Graph,
|
||||
_ => Overlay::Off,
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
g
|
||||
}
|
||||
pub fn serialize(&self) -> String {
|
||||
format!(
|
||||
"preset:{}\ncaveCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\n",
|
||||
self.preset.name(),
|
||||
bool_text(self.cave_culling),
|
||||
self.chunk_updates,
|
||||
self.upload_budget_kib,
|
||||
bool_text(self.sky),
|
||||
bool_text(self.fog),
|
||||
bool_text(self.weather),
|
||||
bool_text(self.animated_textures),
|
||||
self.present_mode.name(),
|
||||
match self.pacing {
|
||||
Pacing::Efficient => "efficient",
|
||||
Pacing::Precise => "precise",
|
||||
},
|
||||
self.workers,
|
||||
match self.overlay {
|
||||
Overlay::Off => "off",
|
||||
Overlay::Fps => "fps",
|
||||
Overlay::Graph => "graph",
|
||||
},
|
||||
)
|
||||
}
|
||||
pub fn save(&self, dir: &Path) {
|
||||
let _ = fs::write(dir.join(FILE), self.serialize());
|
||||
}
|
||||
/// Worker threads for chunk generation and meshing.
|
||||
pub fn worker_threads(&self) -> usize {
|
||||
if self.workers > 0 {
|
||||
return self.workers as usize;
|
||||
}
|
||||
std::thread::available_parallelism()
|
||||
.map_or(2, |n| n.get())
|
||||
.saturating_sub(1)
|
||||
.max(1)
|
||||
}
|
||||
}
|
||||
|
||||
/// A preset's values for vanilla's options and Horizon's own.
|
||||
pub fn apply_preset(preset: Preset, s: &mut crate::settings::Settings) {
|
||||
let (rd, sim, clouds, particles, shadows, blend, mipmaps, entity, leaves, weather_r) =
|
||||
match preset {
|
||||
Preset::Performance => (8, 6, "false", 2, false, 0, 0, 0.5, false, 3),
|
||||
Preset::Balanced => (12, 8, "fast", 1, true, 1, 2, 0.75, true, 5),
|
||||
Preset::Quality => (16, 12, "true", 0, true, 2, 4, 1.0, true, 10),
|
||||
Preset::Ultra => (24, 12, "true", 0, true, 3, 4, 1.5, true, 10),
|
||||
Preset::Custom => return,
|
||||
};
|
||||
s.render_distance = rd;
|
||||
s.simulation_distance = sim;
|
||||
s.clouds = clouds.into();
|
||||
s.particles = particles;
|
||||
s.entity_shadows = shadows;
|
||||
s.biome_blend = blend;
|
||||
s.mipmap_levels = mipmaps;
|
||||
s.entity_distance = entity;
|
||||
s.cutout_leaves = leaves;
|
||||
s.weather_radius = weather_r;
|
||||
s.graphics_preset = "custom".into();
|
||||
let g = &mut s.horizon;
|
||||
g.preset = preset;
|
||||
g.cave_culling = true;
|
||||
g.animated_textures = preset != Preset::Performance;
|
||||
g.chunk_updates = 0;
|
||||
g.upload_budget_kib = 0;
|
||||
g.sky = true;
|
||||
g.fog = true;
|
||||
g.weather = true;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
let g = Graphics {
|
||||
preset: Preset::Balanced,
|
||||
cave_culling: false,
|
||||
chunk_updates: 12,
|
||||
upload_budget_kib: 4096,
|
||||
sky: false,
|
||||
fog: false,
|
||||
weather: false,
|
||||
animated_textures: false,
|
||||
present_mode: PresentMode::Mailbox,
|
||||
pacing: Pacing::Precise,
|
||||
workers: 6,
|
||||
overlay: Overlay::Graph,
|
||||
};
|
||||
assert_eq!(Graphics::parse(&g.serialize()), g);
|
||||
assert_eq!(Graphics::parse(""), Graphics::default());
|
||||
assert_eq!(Graphics::parse("workers:abc\nsky:maybe\n"), Graphics::default());
|
||||
}
|
||||
}
|
||||
@@ -40,12 +40,14 @@ pub mod enchant;
|
||||
pub mod entities;
|
||||
pub mod entity_nbt;
|
||||
pub mod environment;
|
||||
pub mod fast_hash;
|
||||
pub mod fastutil_order;
|
||||
pub mod flatgen;
|
||||
pub mod fog;
|
||||
pub mod font;
|
||||
pub mod gamerules;
|
||||
pub mod gfx;
|
||||
pub mod graphics;
|
||||
pub mod gossip;
|
||||
pub mod health;
|
||||
pub mod hotbar;
|
||||
|
||||
@@ -359,7 +359,7 @@ pub trait LightWorld {
|
||||
fn light(&self, x: i32, y: i32, z: i32) -> Option<u8>;
|
||||
fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8);
|
||||
}
|
||||
impl LightWorld for HashMap<(i32, i32), Arc<Chunk>> {
|
||||
impl<S: std::hash::BuildHasher> LightWorld for HashMap<(i32, i32), Arc<Chunk>, S> {
|
||||
fn state(&self, x: i32, y: i32, z: i32) -> Option<u16> {
|
||||
if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) {
|
||||
return None;
|
||||
|
||||
@@ -899,6 +899,18 @@ fn species_ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
/// `Entity.checkDespawn` alone, for a mob outside the entity-ticking
|
||||
/// chunks. Returns false when the mob is gone.
|
||||
pub fn despawn_check(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
if m.removed {
|
||||
return false;
|
||||
}
|
||||
if !check_despawn(m, w) {
|
||||
m.removed = true;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
}
|
||||
/// Mob.checkDespawn, before the tick (players are the only despawn
|
||||
/// reference). Returns false when the mob is discarded.
|
||||
fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool {
|
||||
|
||||
@@ -175,6 +175,8 @@ pub struct Settings {
|
||||
pub toggle_use: bool,
|
||||
/// Taps of the sprint key counted as double taps (sprintWindow).
|
||||
pub sprint_window: i32,
|
||||
/// Horizon's own graphics settings (`horizon-graphics.txt`, not options.txt).
|
||||
pub horizon: crate::graphics::Graphics,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
@@ -243,6 +245,7 @@ impl Default for Settings {
|
||||
toggle_attack: false,
|
||||
toggle_use: false,
|
||||
sprint_window: 7,
|
||||
horizon: Default::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -273,10 +276,20 @@ fn put_s(f: &mut OptionsFile, key: &str, v: &str) {
|
||||
}
|
||||
impl Settings {
|
||||
pub fn load(path: &Path) -> Self {
|
||||
let horizon = path
|
||||
.parent()
|
||||
.map(crate::graphics::Graphics::load)
|
||||
.unwrap_or_default();
|
||||
let Ok(bytes) = fs::read(path) else {
|
||||
return Self::default();
|
||||
return Self {
|
||||
horizon,
|
||||
..Self::default()
|
||||
};
|
||||
};
|
||||
Self::parse(&String::from_utf8_lossy(&bytes))
|
||||
Self {
|
||||
horizon,
|
||||
..Self::parse(&String::from_utf8_lossy(&bytes))
|
||||
}
|
||||
}
|
||||
pub fn parse(text: &str) -> Self {
|
||||
Self::from_file(OptionsFile::parse(text))
|
||||
@@ -332,6 +345,7 @@ impl Settings {
|
||||
toggle_attack: f.bool("toggleAttack"),
|
||||
toggle_use: f.bool("toggleUse"),
|
||||
sprint_window: f.int("sprintWindow"),
|
||||
horizon: Default::default(),
|
||||
auto_jump: f.bool("autoJump"),
|
||||
language: f.string("lang"),
|
||||
force_unicode: f.bool("forceUnicodeFont"),
|
||||
@@ -461,6 +475,9 @@ impl Settings {
|
||||
}
|
||||
pub fn save(&self, path: &Path) {
|
||||
let _ = fs::write(path, self.serialize());
|
||||
if let Some(dir) = path.parent() {
|
||||
self.horizon.save(dir);
|
||||
}
|
||||
}
|
||||
/// Volume of a sound source (master excluded).
|
||||
pub fn volume(&self, source: &str) -> f32 {
|
||||
|
||||
@@ -174,6 +174,23 @@ impl LimiterClock for SystemClock {
|
||||
}
|
||||
}
|
||||
|
||||
/// The real clock without busy waiting: where vanilla spins on
|
||||
/// `Thread.onSpinWait` for the last half millisecond, this sleeps in short
|
||||
/// steps, so a capped frame rate leaves the core idle.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct SleepingClock(pub SystemClock);
|
||||
impl LimiterClock for SleepingClock {
|
||||
fn nanos(&mut self) -> i64 {
|
||||
self.0.nanos()
|
||||
}
|
||||
fn park(&mut self, nanos: i64) {
|
||||
self.0.park(nanos);
|
||||
}
|
||||
fn spin(&mut self) {
|
||||
std::thread::sleep(std::time::Duration::from_micros(50));
|
||||
}
|
||||
}
|
||||
|
||||
/// `Minecraft.runTick`'s frame-limiter step: only limits below 260
|
||||
/// (the "unlimited" setting) pace frames.
|
||||
pub fn end_frame(
|
||||
|
||||
@@ -9,7 +9,7 @@ use std::{
|
||||
};
|
||||
|
||||
pub struct World {
|
||||
pub chunks: HashMap<(i32, i32), Arc<Chunk>>,
|
||||
pub chunks: crate::fast_hash::FxHashMap<(i32, i32), Arc<Chunk>>,
|
||||
pub random: LegacyRandom,
|
||||
pub revision: u64,
|
||||
pub health_rules: crate::health::HealthRules,
|
||||
@@ -108,7 +108,7 @@ impl Weather {
|
||||
impl World {
|
||||
pub fn new(air: BlockStateId, seed: i64) -> Self {
|
||||
Self {
|
||||
chunks: HashMap::new(),
|
||||
chunks: Default::default(),
|
||||
random: LegacyRandom::new(seed),
|
||||
revision: 0,
|
||||
health_rules: crate::health::HealthRules::default(),
|
||||
|
||||
@@ -130,7 +130,7 @@ def main():
|
||||
p.add_argument("--build", default=str(ROOT / "target/release"))
|
||||
p.add_argument("--out", help="JSON file (default benchmarks/graphics/<label>.json)")
|
||||
args = p.parse_args()
|
||||
ctl = Path(args.build) / "horizon-ctl"
|
||||
ctl = Path(args.build).resolve() / "horizon-ctl"
|
||||
if not ctl.exists():
|
||||
sys.exit(f"{ctl} missing: cargo build --release -p horizon-client --bins")
|
||||
cwd = ROOT / ".local/graphics-bench"
|
||||
|
||||
Reference in New Issue
Block a user