diff --git a/crates/horizon-client/src/flatgen.rs b/crates/horizon-client/src/flatgen.rs index 1cff68b11..339f1fca1 100644 --- a/crates/horizon-client/src/flatgen.rs +++ b/crates/horizon-client/src/flatgen.rs @@ -6,6 +6,7 @@ use horizon_world::{nbt::Tag, registry::BlockRegistry}; pub struct FlatTerrain { layers: Vec, biome: u16, + surface: Option, } impl FlatTerrain { /// The overworld generator of `world_gen_settings` (`data.dimensions`), if it @@ -34,9 +35,40 @@ impl FlatTerrain { layers.extend(std::iter::repeat_n(state, height as usize)); } } + let biome = biomes.id(&biome); + let mut water = None; + let mut surface = None; + for (i, &id) in layers + .iter() + .take(crate::chunk::HEIGHT as usize) + .enumerate() + .rev() + { + let state = horizon_world::registry::BlockStateId(id); + let name = registry.state(state)?.name.as_str(); + if matches!( + name, + "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" + ) { + continue; + } + let height = crate::chunk::MIN_Y + i as i32 + 1; + if matches!(name, "minecraft:water" | "minecraft:lava") { + water.get_or_insert((height, state)); + } else { + surface = Some(crate::lod::Surface { + height, + state, + water, + biome, + }); + break; + } + } Some(Self { layers, - biome: biomes.id(&biome), + biome, + surface, }) } /// FlatLevelSource.getSpawnHeight: the top of the layers. @@ -154,6 +186,9 @@ pub fn settings_from_json( impl ChunkGenerator for FlatTerrain { type Worker = (); fn worker(&self) {} + fn lod_surface(&self, _: &mut (), _: i32, _: i32) -> Option { + self.surface + } fn proto(&self, _: &mut (), cx: i32, cz: i32) -> crate::streaming::Proto { let mut chunk = Chunk::empty(cx, cz); for s in &mut chunk.sections { diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 4e29aeae9..942bae556 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -181,6 +181,8 @@ pub struct FogInputs<'a> { pub water_fog_color: [f32; 3], pub biome: u16, pub render_distance_chunks: i32, + /// Extend ordinary Overworld atmosphere for terrain beyond vanilla's range. + pub distant_terrain: bool, /// The Cloud Distance option, in chunks. pub cloud_range_chunks: i32, pub camera_y: f64, @@ -337,6 +339,18 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog let span = (rd / 10.0).clamp(4.0, 64.0); fog.render_distance_start = rd - span; fog.render_distance_end = rd; + if input.distant_terrain + && input.skybox + && input.fog_type == FogType::Atmospheric + && input.blindness.is_none() + && input.darkness.is_none() + && !input.boss_world_fog + && sky.fog_end >= 1024.0 + { + let scale = (rd / 1024.0).max(1.0); + fog.environmental_start *= scale; + fog.environmental_end *= scale; + } fog } /// `AtmosphericFogEnvironment.updateRainFogState`. @@ -369,6 +383,7 @@ mod tests { water_fog_color: [0.0, 0.0, 0.2], biome: 0, render_distance_chunks: 12, + distant_terrain: false, cloud_range_chunks: 128, camera_y: 70.0, min_y: -64, @@ -447,6 +462,38 @@ mod tests { assert_eq!(fog.sky_end, 192.0); } #[test] + fn distant_atmosphere_extends_without_extending_environmental_overrides() { + let sky = Sky { + fog_end: 1024., + ..Sky::default() + }; + let tables = FogTables { + water_fog_end: vec![1.], + }; + let mut input = inputs(&sky); + input.render_distance_chunks = 1024; + input.distant_terrain = true; + let fog = setup_fog(&tables, &FogState::default(), &input); + assert_eq!(fog.environmental_end, 16384.); + input.fog_type = FogType::Water; + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).environmental_end, + 24. + ); + input.fog_type = FogType::Atmospheric; + input.darkness = Some(1.); + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).environmental_end, + 15. + ); + input.darkness = None; + input.boss_world_fog = true; + assert_eq!( + setup_fog(&tables, &FogState::default(), &input).environmental_end, + 96. + ); + } + #[test] fn cloud_fog_ends_at_the_cloud_distance() { let sky = Sky { fog_end: 1024.0, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index bc818fe44..a15d92d6f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -1002,6 +1002,9 @@ struct Game<'a> { screen_fx: horizon_client::screen_effects::ScreenEffects, world: World, streaming: Streaming, + lod: Option, + lod_source_attempted: bool, + lod_observe: horizon_client::fast_hash::FxHashSet<(i32, i32)>, options: Options, player: Option, spawn: Option, @@ -6881,6 +6884,8 @@ impl Game<'_> { self.using = None; self.screen = Screen::Playing; self.title = None; + self.clear_lod(); + self.pending_uploads.clear(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -7035,6 +7040,8 @@ impl Game<'_> { self.pickups.clear(); self.orbs.clear(); self.mining = None; + self.clear_lod(); + self.pending_uploads.clear(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -7213,6 +7220,8 @@ impl Game<'_> { self.sleep_timer = 0; self.clear_entities(); self.screen = Screen::Playing; + self.clear_lod(); + self.pending_uploads.clear(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -9158,9 +9167,10 @@ impl Game<'_> { } else { self.bob_matrix(alpha as f32) }; - let distance = (self.streaming.radius * 16) as f32; + let terrain_distance = self.terrain_distance(); + let distance = (terrain_distance * 16) as f32; let depth_far = - horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range); + horizon_client::camera::depth_far(terrain_distance, self.settings.cloud_range); self.view_frustum = self .renderer .as_ref() @@ -9237,6 +9247,7 @@ impl Game<'_> { bob, sky, distance, + detail_distance: (self.streaming.radius * 16) as f32, depth_far, underwater, title: title && !live, @@ -9248,7 +9259,13 @@ impl Game<'_> { fog: Some({ let mut fog = self.frame_fog(camera, &sky, biome); // Horizon's fog setting: no distance fog (fluids keep theirs). - if !self.settings.horizon.fog && !underwater && fog.environmental_end >= distance { + if !self.settings.horizon.fog + && !underwater + && self.darkness_fog().is_none() + && !self.dragon_bar_shown() + && self.potions.effects.get("blindness").is_none() + && fog.environmental_end >= (self.streaming.radius * 16) as f32 + { (fog.render_distance_start, fog.render_distance_end) = (1e9, 2e9); (fog.environmental_start, fog.environmental_end) = (1e9, 2e9); } @@ -9416,7 +9433,7 @@ impl Game<'_> { ); // Camera.depthFar, as the renderer's far plane. let depth_far = - horizon_client::camera::depth_far(self.streaming.radius, self.settings.cloud_range); + horizon_client::camera::depth_far(self.terrain_distance(), self.settings.cloud_range); if !self .border_renderer .prepare(&self.border_state, camera, distance, depth_far) @@ -9623,10 +9640,62 @@ impl Game<'_> { } Ok(()) } + /// Only enabled LOD worlds extend the renderer's range, never simulation. + fn terrain_distance(&self) -> i32 { + if self.lod.is_some() { + self.streaming + .radius + .max(self.settings.horizon.lod_distance.min(1024) as i32) + } else { + self.streaming.radius + } + } + fn clear_lod(&mut self) { + self.lod = None; + self.lod_source_attempted = false; + self.lod_observe.clear(); + if let Some(renderer) = &mut self.renderer { + renderer.clear_lods(); + } + } + fn prepare_lod(&mut self) { + let enabled = self.settings.horizon.lod_distance > 0 + && self.renderer.is_some() + && self.player.is_some() + && self.title.is_none() + && (self.remote.is_none() || self.integrated.is_some()); + if !enabled { + if self.lod.is_some() || self.lod_source_attempted { + self.clear_lod(); + } + return; + } + if self.lod_source_attempted { + return; + } + self.lod_source_attempted = true; + let source = match &self.integrated { + Some(server) => server.call(|game| game.streaming.lod_source()), + None => Some(self.streaming.lod_source()), + }; + if let Some(source) = source { + self.lod = Some(horizon_client::lod::Lod::new( + source, + self.pack.context.clone(), + )); + self.lod_observe.extend(self.world.chunks.keys().copied()); + } + } fn update_world(&mut self) { if let Err(e) = self.poll_remote() { log::warn!("Horizon: {e}"); } + self.prepare_lod(); + if self.lod.is_some() { + for &((x, _, z), _, _) in &self.world.light_edits { + self.lod_observe.insert((x >> 4, z >> 4)); + } + } if let Some(p) = &self.player { self.streaming.center = ( (p.position.x.floor() as i32) >> 4, @@ -9635,6 +9704,23 @@ impl Game<'_> { } let (uploads, unloaded) = horizon_client::spans::time("streaming", || self.streaming.update(&mut self.world)); + if let Some(lod) = &mut self.lod { + self.lod_observe + .extend(uploads.iter().map(|(key, _)| (key.0, key.2))); + for chunk in &unloaded { + horizon_client::spans::time("lod_observe", || lod.observe(chunk, self.res.facts())); + self.lod_observe.remove(&(chunk.x, chunk.z)); + } + let observe: Vec<_> = self.lod_observe.iter().copied().take(2).collect(); + for key in observe { + self.lod_observe.remove(&key); + if let Some(chunk) = self.world.chunks.get(&key) { + horizon_client::spans::time("lod_observe", || { + lod.observe(chunk, self.res.facts()) + }); + } + } + } let dirty: Vec<_> = unloaded .iter() .filter(|c| self.world.modified.remove(&(c.x, c.z))) @@ -9672,14 +9758,18 @@ impl Game<'_> { } else { // Horizon's chunk-update and upload budgets: the nearest // sections go first, the rest wait for later frames; a newer - // mesh of a waiting section replaces it. + // mesh of a waiting section replaces it, and sections of + // chunks no longer loaded are dropped. let pending = &mut self.pending_uploads; let fresh: horizon_client::fast_hash::FxHashSet<(i32, i32, i32)> = uploads.iter().map(|(k, _)| *k).collect(); - let gone: horizon_client::fast_hash::FxHashSet<(i32, i32)> = - unloaded.iter().map(|c| (c.x, c.z)).collect(); - pending.retain(|(k, _)| !fresh.contains(k) && !gone.contains(&(k.0, k.2))); - pending.extend(uploads); + let chunks = &self.world.chunks; + pending.retain(|(k, _)| !fresh.contains(k) && chunks.contains_key(&(k.0, k.2))); + pending.extend( + uploads + .into_iter() + .filter(|(k, _)| chunks.contains_key(&(k.0, k.2))), + ); let centre = self.streaming.center; let far = |k: &(i32, i32, i32)| (k.0 - centre.0).pow(2) + (k.2 - centre.1).pow(2); pending.sort_unstable_by_key(|(k, _)| std::cmp::Reverse(far(k))); @@ -9693,7 +9783,9 @@ impl Game<'_> { }; let (mut count, mut bytes) = (0, 0u64); while let Some((_, mesh)) = pending.last() { - let size = ((mesh.solid.len() + mesh.translucent.len()) * 32) as u64; + let size = ((mesh.solid.len() + mesh.translucent.len()) + * std::mem::size_of::()) + as u64; if (limit > 0 && count >= limit) || (budget > 0 && bytes > 0 && bytes + size > budget) { @@ -9710,6 +9802,33 @@ impl Game<'_> { renderer.remove((c.x, sy, c.z)); } } + if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { + let covered = renderer + .lod_detail_columns() + .filter(|&(x, z)| { + horizon_client::streaming::in_view_distance( + self.streaming.center, + self.streaming.radius, + x, + z, + ) + }) + .collect(); + for (key, mesh) in horizon_client::spans::time("lod_update", || { + lod.update( + [player.position.x, player.position.y, player.position.z], + self.yaw, + self.streaming.radius, + self.settings.horizon.lod_distance, + covered, + ) + }) { + horizon_client::spans::time("lod_upload", || renderer.upload_lod(key, &mesh)); + } + for key in lod.removed() { + renderer.remove_lod(key); + } + } } } } @@ -10607,6 +10726,9 @@ impl<'a> Game<'a> { screen_fx: Default::default(), world, streaming, + lod: None, + lod_source_attempted: false, + lod_observe: Default::default(), options, player: None, spawn: None, @@ -11426,6 +11548,7 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { bob: glam::Mat4::IDENTITY, sky: horizon_client::environment::Sky::default(), distance: 12.0, + detail_distance: 12.0, depth_far: 1000.0, underwater: false, cave_culling: false, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 3e0711aeb..212ec0505 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -20,6 +20,7 @@ const HELP: &[&str] = &[ "hotbar 1-9 select a hotbar slot", "give ITEM [COUNT] add items to the inventory", "render-distance N chunks, 2..64", + "lod-distance N far surface chunks, 0 disables, up to1024", "time TICKS set the time of day", "summon KIND [X Y Z] [baby] spawn a mob (in front of the player without a position)", "mobs [RADIUS] list mobs near the player with their AI state", @@ -410,6 +411,15 @@ impl Game<'_> { self.apply_settings(); ok() } + "lod-distance" => { + let n: u32 = arg(1)?.parse()?; + if n > 1024 { + return Err("LOD distance must be 0..1024".into()); + } + self.settings.horizon.lod_distance = n; + self.apply_settings(); + ok() + } "time" => { let time: i64 = arg(1)?.parse()?; self.world.day_time = time; @@ -740,6 +750,16 @@ impl Game<'_> { .map(|k| format!("{k:?}")) .collect(); physical_keys.sort(); + let lod = json!({ + "distance": self.settings.horizon.lod_distance, + "terrain_distance": self.terrain_distance(), + "source": if self.lod.is_none() { "none" } else if self.integrated.is_some() { "integrated" } else { "local" }, + "source_attempted": self.lod_source_attempted, + "active_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().0), + "cached_tiles": self.lod.as_ref().map_or(0, |lod| lod.stats().1), + "pending_observations": self.lod_observe.len(), + "refined_samples": self.lod.as_ref().map_or(0, |lod| lod.refined_samples()), + }); let mut status = json!({ "screen": self.screen_name(), "debug": { @@ -798,6 +818,11 @@ impl Game<'_> { .eye_position() .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); + status["lod"] = lod; + let (target, sampled) = self.lod.as_ref().map_or((0, 0), |lod| lod.progress()); + status["lod"]["target_tiles"] = target.into(); + status["lod"]["sampled_target_tiles"] = sampled.into(); + status["pending_uploads"] = self.pending_uploads.len().into(); status["physical_keys"] = json!(physical_keys); // Boats, minecarts, armor stands, item frames and paintings. status["objects"] = json!(self.objects_status()); diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 0f5a48312..a5605977c 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -189,6 +189,7 @@ impl Game<'_> { horizon_client::ui::load_metadata(root); lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code())); self.audio.reload(root); + self.clear_lod(); self.streaming.reload_resources(&mut self.world, context); self.pending_uploads.clear(); // New GPU textures: a renderer built from the reloaded resources; the diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 60003cc4f..58909fb4c 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -288,6 +288,8 @@ impl Game<'_> { self.screen = Screen::Playing; self.title = None; self.dim = Dim::Overworld; + self.clear_lod(); + self.pending_uploads.clear(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -396,6 +398,8 @@ impl Game<'_> { self.border = Default::default(); self.screen = Screen::Playing; self.container = None; + self.clear_lod(); + self.pending_uploads.clear(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -706,6 +710,8 @@ impl Game<'_> { // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); } + self.clear_lod(); + self.pending_uploads.clear(); if let Some(renderer) = self.renderer.as_mut() { renderer.clear_sections(); } diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index b990869a5..ba07755b9 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -91,7 +91,8 @@ impl Game<'_> { (water & 255) as f32 / 255.0, ], biome, - render_distance_chunks: self.streaming.radius, + render_distance_chunks: self.terrain_distance(), + distant_terrain: self.lod.is_some(), cloud_range_chunks: self.settings.cloud_range, camera_y: camera.y, // level.getMinY(): the Nether and the End start at y 0. diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 8481fdcab..99a755941 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -61,6 +61,7 @@ mod arena; mod cull; mod flat; mod java_stages; +mod lod; mod occlusion; mod pack_stages; pub mod panorama; @@ -70,6 +71,16 @@ pub mod translucency; pub(crate) mod upload; mod world_post; +/// A section's instance: its camera-relative origin and, in `w`, the step of +/// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`). +fn section_instance(origin: [f32; 3]) -> [f32; 4] { + [ + origin[0], + origin[1], + origin[2], + 1.0 / crate::mesher::UV_STEPS, + ] +} /// A new value for `Renderer::block_entity_revision`. fn next_block_entity_revision() -> u64 { static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); @@ -131,6 +142,8 @@ pub struct Frame<'a> { pub sky: Sky, /// Render distance in blocks (fog end). pub distance: f32, + /// Full-detail terrain distance in blocks; distant LODs bypass the cave graph. + pub detail_distance: f32, /// `Camera.depthFar`: the far plane (`crate::camera::depth_far`). pub depth_far: f32, pub underwater: bool, @@ -352,6 +365,8 @@ pub struct Renderer { outline: wgpu::Buffer, depth: wgpu::TextureView, sections: resident::Resident, + lods: HashMap, + detail_columns: HashMap<(i32, i32), u32>, arena: arena::Arena, sorted_indices: arena::Arena, translucent_sorter: translucency::Sorter, @@ -363,6 +378,8 @@ pub struct Renderer { pub multi_draw: bool, /// Per-frame scratch, kept to avoid allocating every frame. visible: Vec, + visible_lods: Vec, + translucent_draws: Vec<(u64, usize, [u32; 5], (u32, Option))>, origins: Vec<[f32; 4]>, /// `DrawIndexedIndirectArgs` words: index count, instance count, first /// index, base vertex, first instance. @@ -570,6 +587,7 @@ impl Renderer { let vertices: u64 = self .sections .values() + .chain(self.lods.values().map(|tile| &tile.mesh)) .map(|s| u64::from(s.solid + s.translucent) * 4) .sum(); [self.arena.bytes(), vertices * stride] @@ -1856,6 +1874,8 @@ impl Renderer { outline, depth, sections: resident::Resident::default(), + lods: HashMap::new(), + detail_columns: HashMap::new(), arena, sorted_indices, translucent_sorter: translucency::Sorter::default(), @@ -1864,6 +1884,8 @@ impl Renderer { indirect_capacity: 1024, multi_draw, visible: Vec::new(), + visible_lods: Vec::new(), + translucent_draws: Vec::new(), origins: Vec::new(), draws: Vec::new(), draw_pages: Vec::new(), @@ -2067,11 +2089,22 @@ impl Renderer { if changed { self.block_entity_revision = next_block_entity_revision(); } + self.release_section(key); + let section = self.upload_mesh(mesh); + if section.is_some() || (mesh.solid.is_empty() && mesh.translucent.is_empty()) { + *self.detail_columns.entry((key.0, key.2)).or_default() |= 1 << key.1; + } else if let Some(mask) = self.detail_columns.get_mut(&(key.0, key.2)) { + *mask &= !(1 << key.1); + } + if let Some(section) = section { + self.sections.insert(key, section); + } + } + fn upload_mesh(&mut self, mesh: &SectionMesh) -> Option { let solid = (mesh.solid.len() / 4) as u32; let translucent = (mesh.translucent.len() / 4) as u32; - self.release_section(key); if solid + translucent == 0 { - return; + return None; } let max = solid.max(translucent); if max > self.index_quads { @@ -2086,16 +2119,14 @@ impl Renderer { }) }); // With video and system memory both full, the section is not drawn. - let Some((page, start)) = self.arena.alloc(&self.device, encoder, vertices) else { - return; - }; + let (page, start) = self.arena.alloc(&self.device, encoder, vertices)?; let sorted_indices = if translucent > 0 { let indices = self.sorted_indices .alloc(&self.device, encoder, u64::from(translucent) * 6); if indices.is_none() { self.arena.release(page, start, vertices); - return; + return None; } indices } else { @@ -2130,26 +2161,23 @@ impl Renderer { { self.queue.submit([copies]); } - self.sections.insert( - key, - SectionGpu { - page, - start, - solid, - translucent, - faces: mesh.faces, - sort: translucency::SortState::new( - mesh.translucent - .as_chunks::<4>() - .0 - .iter() - .map(|q| translucency::quad_center(q[0].pos, q[2].pos)) - .collect(), - ), - sorted_indices, - flat_id, - }, - ); + Some(SectionGpu { + page, + start, + solid, + translucent, + faces: mesh.faces, + sort: translucency::SortState::new( + mesh.translucent + .as_chunks::<4>() + .0 + .iter() + .map(|q| translucency::quad_center(q[0].pos, q[2].pos)) + .collect(), + ), + sorted_indices, + flat_id, + }) } /// The section copies recorded since the last submission, closed. fn take_section_copies(&mut self) -> Option { @@ -2194,17 +2222,20 @@ impl Renderer { } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { - if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) { - flat.remove(id); - } - if let Some((page, start)) = s.sorted_indices { - self.sorted_indices - .release(page, start, u64::from(s.translucent) * 6); - } - self.arena - .release(s.page, s.start, u64::from(s.solid + s.translucent) * 4); + self.release_mesh(s); } } + fn release_mesh(&mut self, s: SectionGpu) { + if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) { + flat.remove(id); + } + if let Some((page, start)) = s.sorted_indices { + self.sorted_indices + .release(page, start, u64::from(s.translucent) * 6); + } + self.arena + .release(s.page, 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 { self.block_entities.values().flatten() @@ -2217,6 +2248,8 @@ impl Renderer { self.block_entities.clear(); self.block_entity_revision = next_block_entity_revision(); self.sections.clear(); + self.lods.clear(); + self.detail_columns.clear(); self.arena.clear(); if let Some(flat) = &mut self.flat { flat.clear(); @@ -2225,7 +2258,19 @@ impl Renderer { self.translucency_cursor = 0; self.occlusion.clear(); } + pub fn lod_detail_columns(&self) -> impl Iterator + '_ { + let complete = (1u32 << (crate::chunk::HEIGHT / 16)) - 1; + self.detail_columns + .iter() + .filter_map(move |(&column, &mask)| (mask == complete).then_some(column)) + } pub fn remove(&mut self, key: SectionKey) { + if let Some(mask) = self.detail_columns.get_mut(&(key.0, key.2)) { + *mask &= !(1 << key.1); + if *mask == 0 { + self.detail_columns.remove(&(key.0, key.2)); + } + } if self.block_entities.remove(&key).is_some() { self.block_entity_revision = next_block_entity_revision(); } @@ -2608,7 +2653,9 @@ impl Renderer { let camera_section = camera_section(camera); let culling = !frame.title && frame.cave_culling; if culling { - crate::spans::time("occlusion", || self.start_occlusion(camera, frame.distance)); + crate::spans::time("occlusion", || { + self.start_occlusion(camera, frame.detail_distance) + }); } let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); @@ -2616,15 +2663,27 @@ impl Renderer { crate::spans::time("visibility", || { self.sections.visible( camera, - (frame.distance / 16.0) as i32, + (frame.detail_distance / 16.0) as i32, &view, |k| !culling || reachable.contains(k), &mut visible, ) }); - self.drawn_sections = visible.len(); - if visible.len() as u64 > self.instance_capacity { - self.instance_capacity = (visible.len() as u64).next_power_of_two(); + let mut visible_lods = std::mem::take(&mut self.visible_lods); + visible_lods.clear(); + if frame.title { + visible.clear(); + } else { + visible_lods.extend( + self.lods + .iter() + .filter_map(|(&key, tile)| tile.visible(key, camera, frame.distance, &view)), + ); + visible_lods.sort_unstable_by_key(|v| (v.distance, v.key)); + } + self.drawn_sections = visible.len() + visible_lods.len(); + if self.drawn_sections as u64 > self.instance_capacity { + self.instance_capacity = (self.drawn_sections as u64).next_power_of_two(); self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: self.instance_capacity * 16, @@ -2638,7 +2697,8 @@ impl Renderer { self.origins.extend( visible .iter() - .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]), + .map(|v| section_instance(v.origin)) + .chain(visible_lods.iter().map(|v| lod::instance(v.origin))), ); if !self.origins.is_empty() { self.uploads.buffer( @@ -2648,9 +2708,6 @@ impl Renderer { 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(); @@ -2697,6 +2754,16 @@ impl Renderer { None => {} } } + // Distant terrain tiles are never occlusion tested: phase 1. + for (i, v) in visible_lods.iter().enumerate() { + let s = &self.lods[&v.key].mesh; + s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { + let first = s.start + u64::from(first) * 4; + self.draws + .push([quads * 6, 1, 0, first as u32, (visible.len() + i) as u32]); + self.draw_pages.push((s.page, None)); + }); + } let phase1_draws = self.draws.len() as u32; self.draws.extend_from_slice(&self.phase2_draws); self.draw_pages.extend_from_slice(&self.phase2_pages); @@ -2704,7 +2771,8 @@ impl Renderer { let solid_draws = self.draws.len() as u32; // LevelRenderer: nearby sections each frame, plus a rotating eighth // (at least 15) of the visible list. Cached views avoid needless sorts. - let count = visible.len(); + self.translucent_draws.clear(); + let count = visible.len() + visible_lods.len(); let budget = (count / 8).max(15).min(count); self.translucency_cursor %= count.max(1); for (i, v) in visible.iter().enumerate().rev() { @@ -2732,16 +2800,67 @@ impl Renderer { ); } let first = s.start + u64::from(s.solid) * 4; - self.draws.push([ - s.translucent * 6, - 1, - index_start as u32, - first as u32, - i as u32, - ]); - self.draw_pages.push((s.page, Some(index_page))); + self.translucent_draws.push(( + v.distance, + i, + [ + s.translucent * 6, + 1, + index_start as u32, + first as u32, + i as u32, + ], + (s.page, Some(index_page)), + )); } } + // Sections went back to front (`visible` is sorted by distance, then + // key): tiles' water only needs sorting in when there is some. + let section_translucent = self.translucent_draws.len(); + for (i, v) in visible_lods.iter().enumerate() { + let instance = visible.len() + i; + let tile = self.lods.get_mut(&v.key).expect("visible resident tile"); + let s = &mut tile.mesh; + if let Some((index_page, index_start)) = s.sorted_indices { + let scheduled = (instance + count - self.translucency_cursor) % count < budget; + if (!s.sort.is_sorted() || scheduled) + && let Some(indices) = s.sort.update_lod( + camera.to_array(), + v.key.origin(), + &mut self.translucent_sorter, + ) + { + self.uploads.buffer( + &mut encoder, + self.sorted_indices.buffer(index_page), + index_start * 4, + bytemuck::cast_slice(indices), + ); + } + let first = s.start + u64::from(s.solid) * 4; + self.translucent_draws.push(( + v.distance, + instance, + [ + s.translucent * 6, + 1, + index_start as u32, + first as u32, + instance as u32, + ], + (s.page, Some(index_page)), + )); + } + } + // Near water and distant water share one back-to-front draw order. + if self.translucent_draws.len() > section_translucent { + self.translucent_draws + .sort_unstable_by(|a, b| b.0.cmp(&a.0).then(b.1.cmp(&a.1))); + } + for &(_, _, draw, pages) in &self.translucent_draws { + self.draws.push(draw); + self.draw_pages.push(pages); + } self.translucency_cursor += budget; let translucent_draws = self.draws.len() as u32 - solid_draws; self.section_draws = self.draws.len(); @@ -2928,6 +3047,7 @@ impl Renderer { if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws => { let sections = &self.sections; + let lods = &self.lods; let sorted = &self.sorted_indices; crate::spans::time("flatten", || { flat.prepare( @@ -2939,7 +3059,14 @@ impl Renderer { solid_draws as usize, visible .iter() - .filter_map(|v| sections.get(v.slot).flat_id.map(|id| (id, v.origin))), + .filter_map(|v| { + let id = sections.get(v.slot).flat_id?; + Some((id, section_instance(v.origin))) + }) + .chain(visible_lods.iter().filter_map(|v| { + let id = lods[&v.key].mesh.flat_id?; + Some((id, lod::instance(v.origin))) + })), |page| sorted.buffer(page).clone(), ) }) @@ -3453,6 +3580,7 @@ impl Renderer { self.last_encode = started.elapsed().saturating_sub(self.last_wait); let _ = self.started; self.visible = visible; + self.visible_lods = visible_lods; Ok(true) } } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs index ff58e3ca6..a1ae20d09 100644 --- a/crates/horizon-client/src/gfx/flat.rs +++ b/crates/horizon-client/src/gfx/flat.rs @@ -330,7 +330,7 @@ impl Flat { draws: &[[u32; 5]], pages: &[(u32, Option)], solid_draws: usize, - origins: impl Iterator, + origins: impl Iterator, sorted_page: impl Fn(u32) -> wgpu::Buffer, ) -> bool { // Origins by section id. @@ -340,7 +340,7 @@ impl Flat { if self.origin_data.len() <= id { self.origin_data.resize(id + 1, [0.0; 4]); } - self.origin_data[id] = [o[0], o[1], o[2], 0.0]; + self.origin_data[id] = o; } if self.origin_data.len() as u64 > self.origin_capacity { self.origin_capacity = (self.origin_data.len() as u64).next_power_of_two(); diff --git a/crates/horizon-client/src/gfx/lod.rs b/crates/horizon-client/src/gfx/lod.rs new file mode 100644 index 000000000..6699a62a3 --- /dev/null +++ b/crates/horizon-client/src/gfx/lod.rs @@ -0,0 +1,146 @@ +//! Far meshes share the terrain arena and passes, with their actual bounds +//! rather than the 16³ boxes used by the near-section residency walk. +use super::{Frustum, Renderer, SectionGpu}; +use crate::{lod::TileKey, mesher::SectionMesh}; +use glam::{DVec3, Vec3}; + +pub(super) struct Tile { + pub mesh: SectionGpu, + bounds: Bounds, +} + +#[derive(Clone, Copy)] +struct Bounds { + min: Vec3, + max: Vec3, +} + +impl Bounds { + fn mesh(mesh: &SectionMesh) -> Option { + let mut positions = mesh + .solid + .iter() + .chain(&mesh.translucent) + .map(|v| Vec3::from(v.pos)); + let first = positions.next()?; + let mut bounds = Self { + min: first, + max: first, + }; + for pos in positions { + bounds.min = bounds.min.min(pos); + bounds.max = bounds.max.max(pos); + } + Some(bounds) + } + + fn visible(self, origin: DVec3, distance: f32, frustum: &Frustum) -> Option { + let min = origin + self.min.as_dvec3(); + let max = origin + self.max.as_dvec3(); + let nearest = DVec3::ZERO.clamp(min, max); + if nearest.x * nearest.x + nearest.z * nearest.z > f64::from(distance).powi(2) + || !frustum.intersects(min.as_vec3(), max.as_vec3()) + { + return None; + } + Some(((min + max) * 0.5).length_squared().to_bits()) + } +} + +/// A tile's instance: like a section's, with the UV step of merged faces. +pub(super) fn instance(origin: [f32; 3]) -> [f32; 4] { + [ + origin[0], + origin[1], + origin[2], + 1.0 / crate::mesher::TILED_UV_STEPS, + ] +} + +pub(super) struct Visible { + pub key: TileKey, + pub distance: u64, + pub origin: [f32; 3], +} + +impl Tile { + pub fn visible( + &self, + key: TileKey, + camera: DVec3, + distance: f32, + frustum: &Frustum, + ) -> Option { + let origin = DVec3::from(key.origin().map(f64::from)) - camera; + Some(Visible { + key, + distance: self.bounds.visible(origin, distance, frustum)?, + origin: origin.as_vec3().to_array(), + }) + } +} + +impl Renderer { + pub fn resident_lods(&self) -> usize { + self.lods.len() + } + + pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh) { + self.remove_lod(key); + if let Some(bounds) = Bounds::mesh(mesh) + && let Some(mesh) = self.upload_mesh(mesh) + { + self.lods.insert(key, Tile { mesh, bounds }); + } + } + + pub fn remove_lod(&mut self, key: TileKey) { + if let Some(tile) = self.lods.remove(&key) { + self.release_mesh(tile.mesh); + } + } + + pub fn clear_lods(&mut self) { + for (_, tile) in std::mem::take(&mut self.lods) { + self.release_mesh(tile.mesh); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::mesher::TerrainVertex; + + #[test] + fn large_tile_bounds_include_water_and_do_not_cull_by_origin() { + let vertex = |pos| TerrainVertex::tiled(pos, [0.0; 2], 0, 0, 0); + let mesh = SectionMesh { + solid: vec![vertex([0.0, -64.0, 0.0]), vertex([1024.0, 100.0, 1024.0])], + translucent: vec![vertex([512.0, 120.0, 512.0])], + ..Default::default() + }; + let bounds = Bounds::mesh(&mesh).unwrap(); + assert_eq!(bounds.min, Vec3::new(0.0, -64.0, 0.0)); + assert_eq!(bounds.max, Vec3::new(1024.0, 120.0, 1024.0)); + let view = Frustum { + planes: super::super::frustum( + super::super::world_projection(70.0, 16.0 / 9.0, 8192.0) + * crate::camera::view_matrix(0.0, 0.0), + ), + }; + // The tile origin is farther than the range, but its far edge reaches + // the camera. Negative world origins therefore remain visible. + assert!( + bounds + .visible(DVec3::new(-1000.0, -80.0, -512.0), 256.0, &view) + .is_some() + ); + assert!( + bounds + .visible(DVec3::new(-2000.0, -80.0, -512.0), 256.0, &view) + .is_none() + ); + assert!(Bounds::mesh(&SectionMesh::default()).is_none()); + } +} diff --git a/crates/horizon-client/src/gfx/translucency.rs b/crates/horizon-client/src/gfx/translucency.rs index 927152a39..4c1ad6683 100644 --- a/crates/horizon-client/src/gfx/translucency.rs +++ b/crates/horizon-client/src/gfx/translucency.rs @@ -47,6 +47,25 @@ impl SortState { self.last.is_some() } + /// Large tiles cannot use the section viewpoint shortcut: the camera may + /// cross a quad's plane while remaining on the same side of the first 16³. + pub fn update_lod<'a>( + &mut self, + camera: [f64; 3], + origin: [i32; 3], + sorter: &'a mut Sorter, + ) -> Option<&'a [u32]> { + let block = camera.map(|v| v.floor() as i32); + if self.last.is_some_and(|(last, _)| last == block) { + return None; + } + self.last = Some((block, [0; 3])); + Some(sorter.sort( + &self.centers, + std::array::from_fn(|i| (camera[i] - f64::from(origin[i])) as f32), + )) + } + /// TranslucencyPointOfView and ResortTransparencyTask: diagonal views keep /// their ordering until the point of view changes; aligned views also /// resort on crossing a block boundary. Sub-block movement needs no upload. @@ -116,4 +135,28 @@ mod tests { .is_some() ); } + #[test] + fn large_tiles_resort_inside_the_same_section_viewpoint() { + let mut state = SortState::new(vec![[32.0, 0.0, 0.0], [96.0, 0.0, 0.0]]); + let mut sorter = Sorter::default(); + assert_eq!( + state + .update_lod([48.0, 20.0, 20.0], [0; 3], &mut sorter) + .unwrap()[0], + 4 + ); + assert!( + state + .update_lod([48.5, 20.0, 20.0], [0; 3], &mut sorter) + .is_none() + ); + // Both views have positive x/y/z signs relative to the first section, + // so the section-sized shortcut would incorrectly keep the old order. + assert_eq!( + state + .update_lod([80.0, 20.0, 20.0], [0; 3], &mut sorter) + .unwrap()[0], + 0 + ); + } } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index b564825e7..467afc8c2 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -117,6 +117,8 @@ pub enum Overlay { #[derive(Clone, Debug, PartialEq)] pub struct Graphics { pub preset: Preset, + /// Distant surface terrain range, in chunks; 0 disables LODs. + pub lod_distance: u32, /// Skip sections hidden behind closed ones (vanilla's occlusion graph). pub cave_culling: bool, /// Hide shared leaf and mangrove-root faces, reducing foliage density. @@ -154,6 +156,7 @@ impl Default for Graphics { fn default() -> Self { Self { preset: Preset::Custom, + lod_distance: 0, cave_culling: true, cull_leaves: false, entity_culling: false, @@ -199,6 +202,7 @@ impl Graphics { let number = |d: u32| value.parse().unwrap_or(d); match key.trim() { "preset" => g.preset = Preset::parse(value), + "lodDistance" => g.lod_distance = number(g.lod_distance).min(1024), "caveCulling" => g.cave_culling = flag(g.cave_culling), "cullLeaves" => g.cull_leaves = flag(g.cull_leaves), "entityCulling" => g.entity_culling = flag(g.entity_culling), @@ -236,8 +240,9 @@ impl Graphics { } pub fn serialize(&self) -> String { format!( - "preset:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", + "preset:{}\nlodDistance:{}\ncaveCulling:{}\ncullLeaves:{}\nentityCulling:{}\nchunkUpdates:{}\nuploadBudgetKiB:{}\nsky:{}\nfog:{}\nweather:{}\nanimatedTextures:{}\npresentMode:{}\nframePacing:{}\nworkers:{}\noverlay:{}\nresolutionScale:{}\nfxaa:{}\nlevel:{}\nbatteryMode:{}\nshaderPack:{}\n", self.preset.name(), + self.lod_distance, bool_text(self.cave_culling), bool_text(self.cull_leaves), bool_text(self.entity_culling), @@ -337,6 +342,7 @@ mod tests { fn round_trips() { let g = Graphics { preset: Preset::Balanced, + lod_distance: 256, cave_culling: false, cull_leaves: true, entity_culling: true, @@ -364,6 +370,19 @@ mod tests { ); } + #[test] + fn lod_distance_is_opt_in_and_bounded() { + assert_eq!(Graphics::default().lod_distance, 0); + for distance in [0, 64, 128, 256, 512, 1024] { + let g = Graphics::parse(&format!("lodDistance:{distance}\n")); + assert_eq!(g.lod_distance, distance); + assert_eq!(Graphics::parse(&g.serialize()), g); + } + assert_eq!(Graphics::parse("lodDistance:10000\n").lod_distance, 1024); + assert_eq!(Graphics::parse("lodDistance:-1\n").lod_distance, 0); + assert_eq!(Graphics::parse("lodDistance:invalid\n").lod_distance, 0); + } + #[test] fn automatic_workers_leave_cores_for_the_render_and_server_threads() { let g = Graphics::default(); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 4d7619037..1da7c0f4f 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -21,6 +21,7 @@ pub enum Level { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum H { Preset, + LodDistance, CaveCulling, CullLeaves, EntityCulling, @@ -76,7 +77,12 @@ pub fn rows(level: Level) -> Vec { let render = v( Opt::RenderDistance, High, - "How far terrain is drawn, in chunks. The biggest lever on frame time.", + "Full-detail terrain range. LOD Distance can extend local worlds farther.", + ); + let lod = h( + H::LodDistance, + Medium, + "Coarse distant surface in local worlds; no extra simulation.", ); let fov = v( Opt::Fov, @@ -100,10 +106,11 @@ pub fn rows(level: Level) -> Vec { "Sets the options below together. Changing one makes it Custom.", ); match level { - Level::Simple => vec![preset, render, fov, fps, vsync, gui], + Level::Simple => vec![preset, render, lod, fov, fps, vsync, gui], Level::Advanced => vec![ Row::Header("Rendering"), render, + lod, v( Opt::SimulationDistance, Medium, @@ -311,6 +318,10 @@ impl H { let g = &s.horizon; match self { H::Preset => labelled("Preset", g.preset.label()), + H::LodDistance => match g.lod_distance { + 0 => labelled("LOD Distance", "Off"), + n => labelled("LOD Distance", format!("{n} chunks")), + }, H::CaveCulling => labelled("Cave Culling", on_off(g.cave_culling)), H::CullLeaves => labelled("Cull Leaves", on_off(g.cull_leaves)), H::EntityCulling => labelled("Entity Culling", on_off(g.entity_culling)), @@ -383,6 +394,9 @@ impl H { } let g = &mut s.horizon; match self { + H::LodDistance => { + g.lod_distance = step(&[0, 64, 128, 256, 512, 1024], g.lod_distance, back) + } H::CaveCulling => g.cave_culling = !g.cave_culling, H::CullLeaves => g.cull_leaves = !g.cull_leaves, H::EntityCulling => g.entity_culling = !g.entity_culling, @@ -467,6 +481,10 @@ impl Item { } pub fn label(self, s: &Settings) -> Text { match self { + Item::Vanilla(Opt::RenderDistance) if s.horizon.lod_distance > 0 => labelled( + "Full Detail Distance", + format!("{} chunks", s.render_distance), + ), Item::Vanilla(o) => o.label(s), Item::Horizon(h) => h.label(s), } @@ -923,6 +941,40 @@ mod tests { } } + #[test] + fn lod_distance_cycles_in_both_levels_without_changing_near_distance() { + let mut s = Settings::default(); + let item = Item::Horizon(H::LodDistance); + let near = s.render_distance; + assert_eq!(item.label(&s).plain(), "LOD Distance: Off"); + for level in [Level::Simple, Level::Advanced] { + let items: Vec<_> = rows(level) + .into_iter() + .filter_map(|row| match row { + Row::Setting(setting) => Some(setting.item), + Row::Header(_) => None, + }) + .collect(); + let render = items + .iter() + .position(|i| *i == Item::Vanilla(Opt::RenderDistance)) + .unwrap(); + assert_eq!(items[render + 1], item); + } + for distance in [64, 128, 256, 512, 1024, 0] { + item.cycle(&mut s, false, [854, 480]); + assert_eq!(s.horizon.lod_distance, distance); + assert_eq!(s.render_distance, near); + } + item.cycle(&mut s, true, [854, 480]); + assert_eq!(s.horizon.lod_distance, 1024); + assert_eq!(item.label(&s).plain(), "LOD Distance: 1024 chunks"); + assert_eq!( + Item::Vanilla(Opt::RenderDistance).label(&s).plain(), + format!("Full Detail Distance: {near} chunks") + ); + } + #[test] fn the_shader_pack_row_is_off_by_default_and_outside_presets() { let mut s = Settings::default(); diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index a3b4be279..7a69de4aa 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -102,6 +102,7 @@ pub mod landing; pub mod lang; pub mod level_loading; pub mod light; +pub mod lod; pub mod logging; pub mod menu; pub mod menu_blur; diff --git a/crates/horizon-client/src/lod.rs b/crates/horizon-client/src/lod.rs new file mode 100644 index 000000000..c2e69a291 --- /dev/null +++ b/crates/horizon-client/src/lod.rs @@ -0,0 +1,1727 @@ +//! Bounded voxel-column terrain for distances beyond the resident chunk area. +//! Far tiles never enter World, lighting, simulation or the section cave graph. +use crate::{ + blocks::BlockFacts, + chunk::{Chunk, MIN_Y}, + fast_hash::{FxHashMap, FxHashSet}, + mesher::SectionMesh, + streaming::{LodDetail, LodSource, WorkerContext}, +}; +mod mesh; +use horizon_world::registry::BlockStateId; +use std::{ + collections::VecDeque, + sync::{ + Arc, Condvar, Mutex, + atomic::{AtomicBool, Ordering}, + mpsc, + }, + thread, +}; + +const CELLS: usize = 16; +const MAX_SAVED: usize = 1024; +const SAMPLE_JOBS: usize = 4; +/// Top solid face and optional fluid face, in absolute block coordinates. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Surface { + pub height: i32, + pub state: BlockStateId, + pub water: Option<(i32, BlockStateId)>, + pub biome: u16, +} +/// A half-open material run; gaps between runs remain air. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Span { + pub min: i16, + pub max: i16, + pub state: BlockStateId, + pub biome: u16, + pub light: u16, +} +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Column { + pub surface: Option, + pub spans: Vec, +} +impl Column { + /// Reduce an entire horizontal footprint, rather than inflating its corner + /// column (a single leaf used to become a whole distant tree-sized slab). + pub(crate) fn reduced(columns: &[Column; 256], x: usize, z: usize, width: usize) -> Self { + if width == 1 { + return columns[z * 16 + x].clone(); + } + let mut events = Vec::new(); + for dz in z..z + width { + for dx in x..x + width { + for span in &columns[dz * 16 + dx].spans { + let material = (span.state, span.biome, span.light); + events.push((span.min, material, 1)); + events.push((span.max, material, -1)); + } + } + } + events.sort_unstable_by_key(|event| event.0); + let mut result = Self::default(); + let mut votes = Vec::<((BlockStateId, u16), i32)>::new(); + let mut sky = [0i32; 16]; + let mut block = [0i32; 16]; + let mut occupied = 0; + let mut bottom = MIN_Y as i16; + for (y, material, change) in events { + if bottom < y { + if occupied * 2 >= (width * width) as i32 + && let Some(&((state, biome), _)) = + votes.iter().max_by_key(|&(material, count)| { + (*count, std::cmp::Reverse((material.0.0, material.1))) + }) + { + // Lighting must not split votes for the same material. + // Reduction can expose buried faces; retain the brightest + // actual light in this occupied footprint, per channel. + let light = (sky.iter().rposition(|&n| n > 0).unwrap_or(0) << 4) + | (block.iter().rposition(|&n| n > 0).unwrap_or(0) << 12); + result.push(Span { + min: bottom, + max: y, + state, + biome, + light: light as u16, + }); + } + bottom = y; + } + occupied += change; + sky[usize::from((material.2 >> 4) & 15)] += change; + block[usize::from((material.2 >> 12) & 15)] += change; + let material = (material.0, material.1); + if let Some(vote) = votes.iter_mut().find(|vote| vote.0 == material) { + vote.1 += change; + } else { + votes.push((material, change)); + } + } + result + } + pub fn from_surface(surface: Option) -> Self { + let mut column = Self { + surface, + spans: Vec::new(), + }; + if let Some(s) = surface { + if s.height > MIN_Y { + column.spans.push(Span { + min: MIN_Y as i16, + max: s.height as i16, + state: s.state, + biome: s.biome, + light: 240, + }); + } + if let Some((height, state)) = s.water { + column.spans.push(Span { + min: s.height as i16, + max: height as i16, + state, + biome: s.biome, + light: 240, + }); + } + } + column + } + pub(crate) fn push(&mut self, span: Span) { + if let Some(last) = self.spans.last_mut() + && last.max == span.min + && last.state == span.state + && last.biome == span.biome + && last.light == span.light + { + last.max = span.max; + } else { + self.spans.push(span); + } + } + fn from_chunk(chunk: &Chunk, facts: &BlockFacts, x: i32, z: i32) -> Self { + let face_light = |y: i32| { + let mut sky = 0; + let mut block = 0; + for (dx, dy, dz) in [ + (0, 0, 0), + (-1, 0, 0), + (1, 0, 0), + (0, -1, 0), + (0, 1, 0), + (0, 0, -1), + (0, 0, 1), + ] { + if !(0..16).contains(&(x + dx)) || !(0..16).contains(&(z + dz)) { + continue; + } + let value = chunk.light(x + dx, y + dy, z + dz); + sky = sky.max(value & 0xf0); + block = block.max(value & 15); + } + sky | block + }; + let mut column = Self::default(); + for (sy, section) in chunk.sections.iter().enumerate() { + let min = MIN_Y + sy as i32 * 16; + let uniform = section.blocks.bits() == 0 + && section.biomes.bits() == 0 + && matches!(section.light, crate::chunk::Light::Uniform(_)); + let uniform = uniform + && face_light(min) == chunk.light(x, min, z) + && face_light(min + 15) == chunk.light(x, min, z); + let step = if uniform { 16 } else { 1 }; + for offset in (0..16).step_by(step) { + let y = min + offset; + let state = BlockStateId(chunk.get(x, y, z)); + let f = facts.get(state); + if facts.is_air(state) + || !(f.solid_render + || f.full_collision + || f.name.ends_with("_leaves") + || matches!(&*f.name, "minecraft:water" | "minecraft:lava")) + { + continue; + } + let light = face_light(y); + column.push(Span { + min: y as i16, + max: (y + step as i32) as i16, + state, + biome: chunk.biome(x, y, z), + light: u16::from(light & 0xf0) + | (u16::from((light & 15).max(f.emission)) << 12), + }); + } + } + let mut water = None; + for span in column.spans.iter().rev() { + if matches!( + &*facts.get(span.state).name, + "minecraft:water" | "minecraft:lava" + ) { + water.get_or_insert((i32::from(span.max), span.state)); + } else { + column.surface = Some(Surface { + height: i32::from(span.max), + state: span.state, + water, + biome: span.biome, + }); + break; + } + } + if column.surface.is_none() + && let Some((height, state)) = water + { + column.surface = Some(Surface { + height: MIN_Y, + state: facts.air, + water: Some((height, state)), + biome: chunk.biome(x, height - 1, z), + }); + } + column + } +} +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct TileKey { + pub x: i32, + pub z: i32, + pub level: u8, +} +impl TileKey { + pub fn size(self) -> i32 { + 16 << self.level + } + pub fn origin(self) -> [i32; 3] { + [self.x * self.size(), 0, self.z * self.size()] + } + fn children(self) -> [Self; 4] { + std::array::from_fn(|i| Self { + x: self.x * 2 + (i & 1) as i32, + z: self.z * 2 + (i >> 1) as i32, + level: self.level - 1, + }) + } + fn distance(self, camera: [i32; 2]) -> i32 { + let [x, _, z] = self.origin(); + (x - camera[0]) + .max(camera[0] - x - self.size()) + .max(z - camera[1]) + .max(camera[1] - z - self.size()) + .max(0) + } + fn in_view(self, camera: [i32; 2], yaw: f32) -> bool { + let [x, _, z] = self.origin(); + let (sin, cos) = yaw.sin_cos(); + let mut forward = f32::NEG_INFINITY; + let mut left = f32::NEG_INFINITY; + let mut right = f32::NEG_INFINITY; + for (dx, dz) in [ + (0, 0), + (self.size(), 0), + (0, self.size()), + (self.size(), self.size()), + ] { + let (x, z) = ((x + dx - camera[0]) as f32, (z + dz - camera[1]) as f32); + let f = -x * sin + z * cos; + let side = x * cos + z * sin; + forward = forward.max(f); + left = left.max(f * 0.866 + side * 0.5); + right = right.max(f * 0.866 - side * 0.5); + } + forward > 0. && left > 0. && right > 0. + } +} +#[derive(Default)] +struct Plan { + roots: Vec, + nodes: FxHashSet, + split: FxHashSet, + elevation: i32, +} +impl Plan { + #[cfg(test)] + fn new(camera: [i32; 2], detail: i32, distance: u32) -> Self { + Self::with_previous(camera, detail, distance, &Self::default(), 0) + } + fn with_previous( + camera: [i32; 2], + detail: i32, + distance: u32, + previous: &Self, + elevation: i32, + ) -> Self { + let range = distance.min(1024) as i32 * 16; + let mut level = 0; + while (16 << level) < range { + level += 1; + } + let size = 16 << level; + let mut result = Self { + elevation, + ..Self::default() + }; + for z in (camera[1] - range).div_euclid(size)..=(camera[1] + range).div_euclid(size) { + for x in (camera[0] - range).div_euclid(size)..=(camera[0] + range).div_euclid(size) { + let key = TileKey { x, z, level }; + result.roots.push(key); + result.visit(key, camera, detail, range, previous); + } + } + result + } + fn visit(&mut self, key: TileKey, camera: [i32; 2], detail: i32, range: i32, previous: &Self) { + if key.distance(camera) > range { + return; + } + self.nodes.insert(key); + // Keep distant cells small on screen; finest tiles retain individual blocks. + let threshold = key.size() * if previous.split.contains(&key) { 10 } else { 8 }; + if key.level > 0 + && (key.distance(camera) < detail * 16 + 16 + || key.distance(camera).max(self.elevation) < threshold) + { + self.split.insert(key); + for child in key.children() { + self.visit(child, camera, detail, range, previous); + } + } + } + fn select( + &self, + key: TileKey, + ready: &FxHashMap>, + out: &mut Vec, + ) -> bool { + if !self.nodes.contains(&key) { + return true; + } + if self.split.contains(&key) { + // Visit every child: a missing sibling must not hide ready detail. + let complete = key + .children() + .into_iter() + .map(|child| self.select(child, ready, out)) + .fold(true, |complete, child| complete & child); + if complete { + return true; + } + if ready.contains_key(&key) { + // Its mesh is clipped around every selected finer tile. + out.push(key); + return true; + } + false + } else if ready.contains_key(&key) { + out.push(key); + true + } else { + false + } + } +} +struct MeshInput { + key: TileKey, + columns: Vec, + neighbors: [Vec; 4], + finer: Vec, +} +struct ReducedColumns { + columns: Arc<[Column; 256]>, + levels: [Vec; 4], +} +impl ReducedColumns { + fn new(columns: Arc<[Column; 256]>) -> Self { + let levels = std::array::from_fn(|level| { + let width = 2 << level; + (0..16 / width) + .flat_map(|z| { + let columns = &columns; + (0..16 / width) + .map(move |x| Column::reduced(columns, x * width, z * width, width)) + }) + .collect() + }); + Self { columns, levels } + } + fn get(&self, x: usize, z: usize, width: usize) -> &Column { + if width == 1 { + &self.columns[z * 16 + x] + } else { + &self.levels[width.trailing_zeros() as usize - 1] + [(z / width) * (16 / width) + x / width] + } + } +} +enum Job { + Sample(TileKey), + Reduce(LodDetail), + RequestDetail { + chunks: Vec<(i32, i32)>, + center: [i32; 2], + }, + Mesh { + active: FxHashSet, + inputs: Vec, + covered: FxHashSet<(i32, i32)>, + bounds: Option<[i32; 4]>, + }, +} +enum Done { + Detail((i32, i32), ReducedColumns), + DetailRequested, + Sample { + key: TileKey, + samples: Vec, + }, + Mesh { + active: FxHashSet, + meshes: Vec<(TileKey, SectionMesh)>, + }, +} +struct Shared { + jobs: Mutex>, + wake: Condvar, + stop: AtomicBool, +} +/// One background worker and at most two outstanding sample jobs. Only the +/// current view's quadtree and a bounded set of visited summaries are retained. +pub struct Lod { + shared: Arc, + thread: Option>, + results: mpsc::Receiver, + #[cfg(test)] + context: Arc, + meshing: bool, + invalidated: FxHashSet<(i32, i32)>, + area: Option<([i32; 2], i32, u32, i32)>, + plan: Plan, + pending: FxHashSet, + sample_nearby: bool, + detail_masks: FxHashMap, + detail_request_pending: bool, + detail_request_at: std::time::Instant, + ready: FxHashMap>, + active: FxHashSet, + dirty: FxHashSet, + removed: Vec, + covered: FxHashSet<(i32, i32)>, + covered_bounds: Option<[i32; 4]>, + saved: FxHashMap<(i32, i32), Arc<[Column; 256]>>, + reduced: FxHashMap<(i32, i32), ReducedColumns>, + saved_order: VecDeque<(i32, i32)>, +} +impl Lod { + pub fn new(source: Arc, context: Arc) -> Self { + let shared = Arc::new(Shared { + jobs: Mutex::new(VecDeque::new()), + wake: Condvar::new(), + stop: AtomicBool::new(false), + }); + let worker = shared.clone(); + let mesh_context = context.clone(); + let (tx, results) = mpsc::channel(); + let handle = thread::Builder::new() + .name("Far terrain".into()) + .spawn(move || { + let mut sampler = source.sampler(); + let count = thread::available_parallelism() + .map_or(1, |n| n.get() / 4) + .clamp(1, 3); + let mut sampling = Vec::new(); + for _ in 0..count { + let Some(mut sample) = sampler.fork() else { + break; + }; + let shared = worker.clone(); + let tx = tx.clone(); + sampling.push( + thread::Builder::new() + .name("Far sampling".into()) + .spawn(move || { + loop { + let key = { + let mut jobs = shared.jobs.lock().unwrap(); + loop { + if shared.stop.load(Ordering::Relaxed) { + return; + } + if let Some(index) = jobs + .iter() + .position(|job| matches!(job, Job::Sample(_))) + { + let Some(Job::Sample(key)) = jobs.remove(index) + else { + unreachable!() + }; + break key; + } + jobs = shared.wake.wait(jobs).unwrap(); + } + }; + let [x, _, z] = key.origin(); + let samples = + sample.grid(x, z, key.size() / CELLS as i32, CELLS); + if shared.stop.load(Ordering::Relaxed) { + return; + } + if tx.send(Done::Sample { key, samples }).is_err() { + return; + } + } + }) + .expect("far sampling worker"), + ); + } + let mut mesher = mesh::Mesher::default(); + 'work: loop { + for (key, columns) in sampler.drain_details() { + if tx + .send(Done::Detail(key, ReducedColumns::new(columns))) + .is_err() + { + break 'work; + } + } + let job = { + let mut jobs = worker.jobs.lock().unwrap(); + if (jobs.is_empty() + || (!sampling.is_empty() + && jobs.iter().all(|job| matches!(job, Job::Sample(_))))) + && !worker.stop.load(Ordering::Relaxed) + { + jobs = worker + .wake + .wait_timeout(jobs, std::time::Duration::from_millis(100)) + .unwrap() + .0; + } + if worker.stop.load(Ordering::Relaxed) { + break; + } + if sampling.is_empty() { + jobs.pop_front() + } else { + jobs.iter() + .position(|job| !matches!(job, Job::Sample(_))) + .and_then(|index| jobs.remove(index)) + } + }; + let Some(job) = job else { continue }; + let done = match job { + Job::Reduce((key, columns)) => { + Done::Detail(key, ReducedColumns::new(columns)) + } + Job::RequestDetail { chunks, center } => { + sampler.request_detail(&chunks, center); + Done::DetailRequested + } + Job::Sample(key) => { + let [x, _, z] = key.origin(); + let samples = sampler.grid(x, z, key.size() / CELLS as i32, CELLS); + Done::Sample { key, samples } + } + Job::Mesh { + active, + inputs, + covered, + bounds, + } => { + let mut meshes = Vec::with_capacity(inputs.len()); + for input in inputs { + if worker.stop.load(Ordering::Relaxed) { + break 'work; + } + let mesh = mesher.mesh( + input.key, + &input.columns, + &covered, + bounds, + &mesh_context, + &input.neighbors, + &input.finer, + ); + meshes.push((input.key, mesh)); + } + Done::Mesh { active, meshes } + } + }; + if tx.send(done).is_err() { + break; + } + } + worker.stop.store(true, Ordering::Relaxed); + worker.wake.notify_all(); + for handle in sampling { + let _ = handle.join(); + } + }) + .expect("far terrain worker"); + Self { + shared, + thread: Some(handle), + results, + #[cfg(test)] + context, + meshing: false, + invalidated: FxHashSet::default(), + area: None, + plan: Plan::default(), + pending: FxHashSet::default(), + sample_nearby: true, + detail_masks: FxHashMap::default(), + detail_request_pending: false, + detail_request_at: std::time::Instant::now(), + ready: FxHashMap::default(), + active: FxHashSet::default(), + dirty: FxHashSet::default(), + removed: Vec::new(), + covered: FxHashSet::default(), + covered_bounds: None, + saved: FxHashMap::default(), + reduced: FxHashMap::default(), + saved_order: VecDeque::new(), + } + } + pub fn stats(&self) -> (usize, usize) { + (self.active.len(), self.ready.len()) + } + pub fn progress(&self) -> (usize, usize) { + let mut desired = 0; + let mut sampled = 0; + for key in &self.plan.nodes { + if !self.plan.split.contains(key) { + desired += 1; + sampled += usize::from(self.ready.contains_key(key)); + } + } + (desired, sampled) + } + pub fn refined_samples(&self) -> usize { + self.active + .iter() + .filter_map(|key| self.detail_masks.get(key)) + .flat_map(|mask| mask.iter()) + .map(|bits| bits.count_ones() as usize) + .sum() + } + pub fn removed(&mut self) -> Vec { + std::mem::take(&mut self.removed) + } + pub fn invalidate_chunk(&mut self, x: i32, z: i32) { + if self.meshing { + self.invalidated.insert((x, z)); + } + for &key in &self.active { + let [ox, _, oz] = key.origin(); + if x * 16 <= ox + key.size() + && (x + 1) * 16 >= ox + && z * 16 <= oz + key.size() + && (z + 1) * 16 >= oz + { + self.dirty.insert(key); + } + } + } + /// Capture actual block columns, including canopy gaps and material layers. + pub fn observe(&mut self, chunk: &Chunk, facts: &BlockFacts) { + let values = Arc::new(std::array::from_fn(|i| { + Column::from_chunk(chunk, facts, (i & 15) as i32, (i >> 4) as i32) + })); + let key = (chunk.x, chunk.z); + if self.saved.get(&key) == Some(&values) { + return; + } + if !self.saved.contains_key(&key) { + while self.saved.len() >= MAX_SAVED { + if let Some(old) = self.saved_order.pop_front() { + self.saved.remove(&old); + self.reduced.remove(&old); + } + } + self.saved_order.push_back(key); + } + self.apply_fine(key, &values); + self.saved.insert(key, values.clone()); + self.reduced.remove(&key); + let mut jobs = self.shared.jobs.lock().unwrap(); + // Coalesce edits and drop jobs whose bounded visited cache was evicted. + jobs.retain(|job| !matches!(job, Job::Reduce((at, _)) if *at == key || !self.saved.contains_key(at))); + jobs.push_back(Job::Reduce((key, values))); + drop(jobs); + self.shared.wake.notify_all(); + self.invalidate_chunk(chunk.x, chunk.z); + } + fn apply_fine(&mut self, (cx, cz): (i32, i32), columns: &[Column; 256]) { + let fine = TileKey { + x: cx, + z: cz, + level: 0, + }; + if self.plan.nodes.contains(&fine) || self.ready.contains_key(&fine) { + self.ready.insert(fine, columns.to_vec()); + self.detail_masks.insert(fine, [u64::MAX; 4]); + } + } + fn apply_detail(&mut self, (cx, cz): (i32, i32), columns: &ReducedColumns) { + self.apply_fine((cx, cz), &columns.columns); + // A single generated chunk cannot describe a larger cell's area + // (strides over 16 blocks, levels over 4); at each level up to that, + // only the tile holding the chunk overlaps it. + for level in 0..=4u8 { + let size = 16 << level; + let key = TileKey { + x: (cx * 16).div_euclid(size), + z: (cz * 16).div_euclid(size), + level, + }; + let Some(samples) = self.ready.get_mut(&key) else { + continue; + }; + let [ox, _, oz] = key.origin(); + let stride = key.size() / 16; + let x0 = ((cx * 16 - ox + stride - 1).div_euclid(stride)).clamp(0, 16); + let x1 = (((cx + 1) * 16 - ox + stride - 1).div_euclid(stride)).clamp(0, 16); + let z0 = ((cz * 16 - oz + stride - 1).div_euclid(stride)).clamp(0, 16); + let z1 = (((cz + 1) * 16 - oz + stride - 1).div_euclid(stride)).clamp(0, 16); + if x0 == x1 || z0 == z1 { + continue; + } + let mask = self.detail_masks.entry(key).or_default(); + for z in z0..z1 { + for x in x0..x1 { + let index = (z * 16 + x) as usize; + samples[index] = columns + .get( + (ox + x * stride).rem_euclid(16) as usize, + (oz + z * stride).rem_euclid(16) as usize, + stride as usize, + ) + .clone(); + mask[index / 64] |= 1 << (index % 64); + } + } + } + } + fn finish_sample(&mut self, key: TileKey, samples: Vec) { + self.pending.remove(&key); + if self.plan.nodes.contains(&key) && samples.len() == CELLS * CELLS { + let mut samples = samples; + if let (Some(old), Some(mask)) = (self.ready.get(&key), self.detail_masks.get(&key)) { + for i in 0..256 { + if mask[i / 64] & (1 << (i % 64)) != 0 { + samples[i] = old[i].clone(); + } + } + } + self.ready.insert(key, samples); + } + } + fn finish_detail(&mut self, key: (i32, i32), columns: ReducedColumns) { + if let Some(visited) = self.saved.get(&key).cloned() + && !Arc::ptr_eq(&visited, &columns.columns) + { + // Its latest reduction is queued; never restore old edits or seed data. + self.apply_fine(key, &visited); + return; + } + self.apply_detail(key, &columns); + if self.saved.contains_key(&key) { + self.reduced.insert(key, columns); + } + self.invalidate_chunk(key.0, key.1); + } + fn request_detail(&mut self, camera: [i32; 2]) { + if self.detail_request_pending + || self.detail_request_at.elapsed() < std::time::Duration::from_millis(250) + { + return; + } + self.detail_request_at = std::time::Instant::now(); + let mut keys: Vec<_> = self + .active + .iter() + .filter(|key| { + key.level <= 1 + && !self.plan.split.contains(key) + && !(key.level == 0 && self.covered.contains(&(key.x, key.z))) + && self.detail_masks.get(key) != Some(&[u64::MAX; 4]) + }) + .copied() + .collect(); + keys.sort_unstable_by_key(|key| (key.distance(camera), *key)); + let mut chunks = FxHashSet::default(); + for key in keys { + let [ox, _, oz] = key.origin(); + let stride = key.size() / 16; + let mask = self.detail_masks.get(&key).copied().unwrap_or_default(); + for index in 0..256 { + if mask[index / 64] & (1 << (index % 64)) == 0 { + let chunk = ( + (ox + (index as i32 % 16) * stride).div_euclid(16), + (oz + (index as i32 / 16) * stride).div_euclid(16), + ); + if self.covered.contains(&chunk) { + self.detail_masks.entry(key).or_default()[index / 64] |= 1 << (index % 64); + } else { + chunks.insert(chunk); + } + } + } + if chunks.len() >= 32 { + break; + } + } + let mut chunks: Vec<_> = chunks.into_iter().collect(); + chunks.sort_unstable_by_key(|&(x, z)| { + let dx = i64::from(x * 16 + 8 - camera[0]); + let dz = i64::from(z * 16 + 8 - camera[1]); + dx * dx + dz * dz + }); + chunks.truncate(32); + if !chunks.is_empty() { + self.detail_request_pending = true; + self.shared + .jobs + .lock() + .unwrap() + .push_back(Job::RequestDetail { + chunks, + center: camera, + }); + self.shared.wake.notify_all(); + } + } + pub fn update( + &mut self, + camera: [f64; 3], + yaw: f32, + detail: i32, + distance: u32, + covered: FxHashSet<(i32, i32)>, + ) -> Vec<(TileKey, SectionMesh)> { + let elevation = + (((camera[1] - f64::from(MIN_Y + crate::chunk::HEIGHT)).clamp(0., 16384.)) as i32 / 32) + * 32; + let camera = [camera[0].floor() as i32, camera[2].floor() as i32]; + // Fill the view ahead first; a nearest-only ring spends most work out + // of sight while visible forests remain undecorated noise terrain. + let ahead = (detail * 16 + 128).max(elevation * 2).min(4096) as f32; + let yaw = yaw.to_radians(); + let focus = [ + camera[0] - (yaw.sin() * ahead) as i32, + camera[1] + (yaw.cos() * ahead) as i32, + ]; + // Replan at chunk boundaries, not on every camera movement. + let area = ( + [camera[0].div_euclid(16), camera[1].div_euclid(16)], + detail, + distance, + elevation, + ); + if self.area != Some(area) { + self.area = Some(area); + self.plan = Plan::with_previous(camera, detail, distance, &self.plan, elevation); + self.ready.retain(|key, _| self.plan.nodes.contains(key)); + self.detail_masks + .retain(|key, _| self.plan.nodes.contains(key)); + } + let mut meshes = Vec::new(); + while let Ok(done) = self.results.try_recv() { + match done { + Done::Detail(key, columns) => { + crate::spans::time("lod_detail", || self.finish_detail(key, columns)) + } + Done::DetailRequested => self.detail_request_pending = false, + Done::Sample { key, samples } => self.finish_sample(key, samples), + Done::Mesh { + active, + meshes: completed, + } => { + // Retire parents only when the entire replacement is ready. + self.removed + .extend(self.active.difference(&active).copied()); + self.active = active; + self.meshing = false; + for (x, z) in std::mem::take(&mut self.invalidated) { + self.invalidate_chunk(x, z); + } + meshes.extend(completed); + } + } + } + if self.covered != covered { + let changes: Vec<_> = self + .covered + .symmetric_difference(&covered) + .copied() + .collect(); + for (x, z) in changes { + self.invalidate_chunk(x, z); + } + self.covered_bounds = covered.iter().fold(None, |bounds, &(x, z)| { + Some(match bounds { + None => [x * 16, z * 16, (x + 1) * 16, (z + 1) * 16], + Some([x0, z0, x1, z1]) => [ + x0.min(x * 16), + z0.min(z * 16), + x1.max((x + 1) * 16), + z1.max((z + 1) * 16), + ], + }) + }); + self.covered = covered; + } + // Complete resident columns need no duplicate noise work. Their real + // summaries are retained when the full-detail chunks leave the view. + for &key in &self.plan.nodes { + if key.level == 0 && self.covered.contains(&(key.x, key.z)) { + self.ready + .entry(key) + .or_insert_with(|| vec![Column::default(); CELLS * CELLS]); + } + } + if !self.meshing { + let mut selected = Vec::new(); + for &key in &self.plan.roots { + self.plan.select(key, &self.ready, &mut selected); + } + // Their normal meshes already provide coverage. Empty stand-ins + // must not become hundreds of redundant fallback clipping masks. + selected.retain(|key| key.level != 0 || !self.covered.contains(&(key.x, key.z))); + let next: FxHashSet<_> = selected.iter().copied().collect(); + let changed: Vec<_> = self.active.symmetric_difference(&next).copied().collect(); + for &tile in &next { + let [x, _, z] = tile.origin(); + let size = tile.size(); + if changed.iter().any(|other| { + let [ox, _, oz] = other.origin(); + let os = other.size(); + (x < ox + os && ox < x + size && z < oz + os && oz < z + size) + || (((x + size == ox) || (ox + os == x)) && z < oz + os && oz < z + size) + || (((z + size == oz) || (oz + os == z)) && x < ox + os && ox < x + size) + }) { + self.dirty.insert(tile); + } + } + self.dirty.extend(next.difference(&self.active).copied()); + self.dirty.retain(|key| next.contains(key)); + if !self.dirty.is_empty() || next != self.active { + let inputs = self + .dirty + .iter() + .map(|&key| crate::spans::time("lod_input", || self.mesh_input(key, &next))) + .collect(); + self.dirty.clear(); + self.meshing = true; + self.shared.jobs.lock().unwrap().push_front(Job::Mesh { + active: next, + inputs, + covered: self.covered.clone(), + bounds: self.covered_bounds, + }); + self.shared.wake.notify_all(); + } + } + self.request_detail(focus); + // Every sample slot busy: no tile can be requested this frame. + let free = SAMPLE_JOBS.saturating_sub(self.pending.len()); + if free == 0 { + return meshes; + } + // Load desired nearby leaves directly, alongside broad fallback coverage. + // Waiting for every ancestor/sibling made full detail take minutes to appear. + let mut wanted = Vec::new(); + for &root in &self.plan.roots { + if self.plan.nodes.contains(&root) && !self.ready.contains_key(&root) { + wanted.push((0, 0, root)); + } + } + for &key in &self.plan.nodes { + if !self.plan.split.contains(&key) && !self.ready.contains_key(&key) { + wanted.push(( + if key.in_view(camera, yaw) { 1 } else { 3 }, + i64::from(key.distance(focus)) * 4 + i64::from(key.distance(camera)), + key, + )); + } + } + let mut fallback = Vec::new(); + for &parent in &self.active { + if self.plan.split.contains(&parent) { + for child in parent.children() { + if self.plan.nodes.contains(&child) && !self.ready.contains_key(&child) { + // Covered near terrain bounds projected error. Using + // zero distance for a parent touching the camera kept + // refining it while huge visible walls waited elsewhere. + let priority = + i64::from(child.distance(camera).max((detail * 16).max(elevation))) + * 1024 + / i64::from(child.size()); + fallback.push(( + if child.in_view(camera, yaw) { 2 } else { 4 }, + priority, + child, + )); + } + } + } + } + // Only the first `free` keys not already pending are taken. A key is + // listed at most twice (as a root and as a node), so the best + // `2 * (SAMPLE_JOBS + pending)` entries hold them, in order. + let best = 2 * (SAMPLE_JOBS + self.pending.len()); + if wanted.len() > best { + wanted.select_nth_unstable(best); + wanted.truncate(best); + } + wanted.sort_unstable(); + // Alternate one nearby final tile with one broad refinement tile. + if let Some(fallback) = fallback + .into_iter() + .filter(|(_, _, k)| !self.pending.contains(k)) + .min() + { + let index = if self.sample_nearby { + wanted + .iter() + .position(|(_, _, k)| !self.pending.contains(k)) + .map_or(0, |i| i + 1) + } else { + 0 + }; + wanted.insert(index, fallback); + } + let mut unique = FxHashSet::default(); + let wanted: Vec<_> = wanted + .into_iter() + .map(|(_, _, key)| key) + .filter(|key| !self.pending.contains(key) && unique.insert(*key)) + .collect(); + if !wanted.is_empty() { + let mut jobs = self.shared.jobs.lock().unwrap(); + for key in wanted.into_iter().take(free) { + self.pending.insert(key); + self.sample_nearby = !self.sample_nearby; + jobs.push_back(Job::Sample(key)); + } + drop(jobs); + self.shared.wake.notify_all(); + } + meshes + } + fn visited_column(&self, wx: i32, wz: i32, width: i32) -> Option<&Column> { + let key = (wx.div_euclid(16), wz.div_euclid(16)); + if width == 1 { + self.saved + .get(&key) + .map(|columns| &columns[(wz.rem_euclid(16) * 16 + wx.rem_euclid(16)) as usize]) + } else if width <= 16 { + self.reduced.get(&key).map(|columns| { + columns.get( + wx.rem_euclid(16) as usize, + wz.rem_euclid(16) as usize, + width as usize, + ) + }) + } else { + None + } + } + fn neighbor(&self, wx: i32, wz: i32, active: &FxHashSet) -> Option<(Column, i32)> { + for level in 0..=10 { + let size = 16 << level; + let key = TileKey { + x: wx.div_euclid(size), + z: wz.div_euclid(size), + level, + }; + if !active.contains(&key) { + continue; + } + let stride = 1 << level; + let [ox, _, oz] = key.origin(); + let x = (wx - ox) / stride; + let z = (wz - oz) / stride; + let (sx, sz) = (ox + x * stride, oz + z * stride); + if let Some(column) = self.visited_column(sx, sz, stride) { + return Some((column.clone(), stride)); + } + return Some((self.ready[&key][(z * 16 + x) as usize].clone(), stride)); + } + None + } + fn mesh_input(&self, key: TileKey, active: &FxHashSet) -> MeshInput { + let stride = key.size() / CELLS as i32; + let [ox, _, oz] = key.origin(); + let mut columns = self.ready[&key].clone(); + for z in 0..CELLS { + for x in 0..CELLS { + let (wx, wz) = (ox + x as i32 * stride, oz + z as i32 * stride); + if let Some(column) = self.visited_column(wx, wz, stride) { + columns[z * CELLS + x] = column.clone(); + } + } + } + let neighbors = std::array::from_fn(|direction| { + let mut edge = Vec::new(); + let mut offset = 0; + while offset < key.size() { + let (wx, wz) = match direction { + 0 => (ox - 1, oz + offset), + 1 => (ox + key.size(), oz + offset), + 2 => (ox + offset, oz - 1), + _ => (ox + offset, oz + key.size()), + }; + let (column, neighbor_stride) = self + .neighbor(wx, wz, active) + .unwrap_or_else(|| (Column::default(), stride)); + let coordinate = if direction < 2 { wz } else { wx }; + let width = (neighbor_stride - coordinate.rem_euclid(neighbor_stride)) + .min(key.size() - offset); + edge.push(mesh::EdgeColumn { + start: offset, + end: offset + width, + column, + }); + offset += width; + } + edge + }); + MeshInput { + key, + columns, + neighbors, + finer: active + .iter() + .copied() + .filter(|other| { + let [x, _, z] = other.origin(); + other.level < key.level + && x >= ox + && z >= oz + && x + other.size() <= ox + key.size() + && z + other.size() <= oz + key.size() + }) + .collect(), + } + } + #[cfg(test)] + fn mesh(&self, key: TileKey) -> SectionMesh { + let input = self.mesh_input(key, &self.active); + mesh::Mesher::default().mesh( + key, + &input.columns, + &self.covered, + self.covered_bounds, + &self.context, + &input.neighbors, + &input.finer, + ) + } +} +impl Drop for Lod { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.shared.wake.notify_all(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} +#[cfg(test)] +mod tests { + use super::*; + use crate::mesher::TerrainVertex; + #[test] + fn far_plan_is_bounded_and_near_tiles_align_with_chunks() { + for camera in [[0, 0], [-1, -17], [1023, -4097]] { + for distance in [64, 256, 1024] { + let plan = Plan::new(camera, 12, distance); + assert!(plan.nodes.len() < 12000, "{} nodes", plan.nodes.len()); + for key in &plan.nodes { + if !plan.split.contains(key) && key.distance(camera) < 12 * 16 { + assert_eq!(key.level, 0); + } + } + let cells = plan + .nodes + .iter() + .filter(|k| !plan.split.contains(k)) + .count(); + assert!(cells < 10000); + } + } + assert_eq!( + TileKey { + x: -1, + z: -2, + level: 1 + } + .origin(), + [-32, 0, -64] + ); + } + #[test] + fn aerial_distance_avoids_unseen_full_detail_outside_the_near_area() { + let ground = Plan::new([0, 0], 12, 1024); + let high = Plan::with_previous([0, 0], 12, 1024, &Plan::default(), 1024); + assert!(high.nodes.len() < ground.nodes.len()); + assert!( + high.nodes.contains(&TileKey { + x: 0, + z: 0, + level: 0 + }), + "near full-detail footprint stays exact" + ); + assert!( + !high.nodes.contains(&TileKey { + x: 20, + z: 0, + level: 0 + }), + "far terrain viewed from high above needs distance-appropriate detail" + ); + } + #[test] + fn late_parent_keeps_ready_detail_and_only_fills_missing_children() { + let parent = TileKey { + x: -1, + z: 0, + level: 1, + }; + let mut plan = Plan::default(); + plan.roots.push(parent); + plan.nodes.insert(parent); + plan.split.insert(parent); + plan.nodes.extend(parent.children()); + let mut ready = FxHashMap::default(); + ready.insert(parent, vec![]); + ready.insert(parent.children()[0], vec![]); + let mut selected = Vec::new(); + ready.remove(&parent); + assert!(!plan.select(parent, &ready, &mut selected)); + assert_eq!(selected, [parent.children()[0]]); + ready.insert(parent, vec![]); + selected.clear(); + assert!(plan.select(parent, &ready, &mut selected)); + assert_eq!(selected, [parent.children()[0], parent]); + for child in parent.children() { + ready.insert(child, vec![]); + } + selected.clear(); + assert!(plan.select(parent, &ready, &mut selected)); + assert_eq!(selected, parent.children()); + } + #[test] + fn detail_survives_movement_across_a_split_threshold() { + let before = Plan::new([0, 0], 2, 256); + let after = Plan::with_previous([16, 0], 2, 256, &before, 0); + let mut retained = 0; + for key in &before.split { + if key.distance([16, 0]) < key.size() * 10 { + assert!(after.split.contains(key)); + retained += 1; + } + } + assert!(retained > 100); + assert!(after.nodes.len() < 16000); + } + #[test] + fn reduced_material_votes_ignore_light_and_retain_exposure() { + let mut columns: [Column; 256] = std::array::from_fn(|_| Column::default()); + for i in 0..16 { + columns[(i / 4) * 16 + i % 4].spans.push(Span { + min: 60, + max: 64, + state: BlockStateId(if i < 10 { 2 } else { 1 }), + biome: 0, + light: if i < 10 { (i as u16 + 6) << 4 } else { 0 }, + }); + } + let coarse = Column::reduced(&columns, 0, 0, 4); + assert_eq!(coarse.spans.len(), 1); + assert_eq!( + coarse.spans[0].state, + BlockStateId(2), + "majority grass must beat dark dirt" + ); + assert_eq!(coarse.spans[0].light, 240, "retain sampled sky exposure"); + for column in &mut columns { + for span in &mut column.spans { + span.light = 0; + } + } + assert_eq!( + Column::reduced(&columns, 0, 0, 4).spans[0].light, + 0, + "unlit caves stay unlit" + ); + columns[0].spans[0].light = 7 << 12; + assert_eq!( + Column::reduced(&columns, 0, 0, 4).spans[0].light, + 7 << 12, + "block light does not invent skylight" + ); + } + #[test] + fn coarse_voxels_reduce_the_area_instead_of_inflating_one_leaf() { + let span = |min, max, state| Span { + min, + max, + state: BlockStateId(state), + biome: 0, + light: 240, + }; + let mut columns = std::array::from_fn(|_| Column { + surface: None, + spans: vec![span(0, 4, 1)], + }); + columns[0].spans.push(span(8, 10, 2)); + assert_eq!(Column::reduced(&columns, 0, 0, 4).spans, [span(0, 4, 1)]); + for z in 0..4 { + for x in 0..4 { + columns[z * 16 + x].spans.push(span(12, 14, 3)); + } + } + assert_eq!( + Column::reduced(&columns, 0, 0, 4).spans, + [span(0, 4, 1), span(12, 14, 3)] + ); + assert_eq!(Column::reduced(&columns, 0, 0, 1), columns[0]); + let reduced = ReducedColumns::new(Arc::new(columns)); + assert_eq!( + reduced.get(0, 0, 1).spans, + [span(0, 4, 1), span(8, 10, 2), span(12, 14, 3)] + ); + assert_eq!(reduced.get(0, 0, 4).spans, [span(0, 4, 1), span(12, 14, 3)]); + assert_eq!(reduced.get(4, 8, 4).spans, [span(0, 4, 1)]); + assert_eq!(reduced.get(0, 0, 16).spans, [span(0, 4, 1)]); + } + #[test] + #[ignore = "requires prepared models/textures in HORIZON_TEST_RESOURCES"] + fn real_mesh_clips_near_chunks_and_preserves_water_and_edited_surfaces() -> crate::Result<()> { + use crate::{ + assets::Assets, biome::Biomes, light::LightTables, mesher::MeshTables, + testgen::TestTerrain, + }; + let root = std::path::PathBuf::from( + std::env::var_os("HORIZON_TEST_RESOURCES").expect("HORIZON_TEST_RESOURCES"), + ); + let assets = Arc::new(Assets::load(&root)?); + let render = Arc::new(assets.reload(&root)?); + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(MeshTables::new( + &assets, + &render, + &facts, + crate::models::load_visibility(&root, assets.registry)?, + )?); + let context = Arc::new(WorkerContext { + light: Arc::new(LightTables::load(&root, assets.registry, &facts)?), + tables, + assets: assets.clone(), + render, + biomes: biomes.clone(), + }); + let source = Arc::new(TestTerrain::new(assets.registry, &biomes)?); + let mut lod = Lod::new(source, context); + let stone = assets.registry.default_state("minecraft:stone").unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let key = TileKey { + x: -1, + z: -1, + level: 5, + }; + lod.ready.insert( + key, + vec![ + Column::from_surface(Some(Surface { + height: 70, + state: stone, + water: Some((80, water)), + biome: biomes.id("minecraft:plains"), + })); + CELLS * CELLS + ], + ); + // A chunk covers only one quarter of this parent's 32² cell. Both + // opaque terrain and water must leave precisely that 16² footprint. + lod.covered.insert((-1, -2)); + lod.covered_bounds = Some([-16, -32, 0, -16]); + let mesh = lod.mesh(key); + let top_area = |vertices: &[TerrainVertex], y: f32| { + vertices + .as_chunks::<4>() + .0 + .iter() + .filter(|quad| quad.iter().all(|v| (v.pos[1] - y).abs() < 0.001)) + .map(|quad| { + let a = glam::Vec3::from(quad[0].pos); + let b = glam::Vec3::from(quad[1].pos); + let c = glam::Vec3::from(quad[2].pos); + let normal = (b - a).cross(c - a); + assert!(normal.y > 0.0, "surface must face the camera from above"); + let center = (a + c) * 0.5; + let [ox, _, oz] = key.origin(); + let chunk = ( + ((center.x as i32) + ox).div_euclid(16), + ((center.z as i32) + oz).div_euclid(16), + ); + assert!( + !lod.covered.contains(&chunk), + "LOD overlaps a full-detail chunk" + ); + normal.y + }) + .sum::() + }; + let expected = (key.size() * key.size() - 16 * 16) as f32; + assert_eq!(top_area(&mesh.solid, 70.0), expected); + assert_eq!(top_area(&mesh.translucent, 80.0 - 1.0 / 9.0), expected); + assert_eq!( + mesh.faces.quads.iter().sum::() as usize, + mesh.solid.len() / 4 + ); + assert!(mesh.translucent.iter().all(|v| v.light == 240)); + let side = |axis: usize, plane: f32, low: f32, high: f32| { + let other = if axis == 0 { 2 } else { 0 }; + mesh.solid + .as_chunks::<4>() + .0 + .iter() + .filter(|quad| { + quad.iter().all(|v| v.pos[axis] == plane) + && quad.iter().map(|v| v.pos[1]).fold(f32::INFINITY, f32::min) + == MIN_Y as f32 + && quad + .iter() + .map(|v| v.pos[1]) + .fold(f32::NEG_INFINITY, f32::max) + == 70.0 + && quad + .iter() + .map(|v| v.pos[other]) + .fold(f32::INFINITY, f32::min) + == low + && quad + .iter() + .map(|v| v.pos[other]) + .fold(f32::NEG_INFINITY, f32::max) + == high + }) + .map(move |quad| { + let a = glam::Vec3::from(quad[0].pos); + (glam::Vec3::from(quad[1].pos) - a).cross(glam::Vec3::from(quad[2].pos) - a) + [axis] + }) + .collect::>() + }; + // The two exposed edges face the missing full-detail chunk and seal + // the height mismatch all the way down. Shared subpieces add no walls. + let east_cut = side(0, 496.0, 480.0, 496.0); + assert_eq!(east_cut.len(), 1); + assert!(east_cut[0] > 0.0); + let north_cut = side(2, 496.0, 496.0, 512.0); + assert_eq!(north_cut.len(), 1); + assert!(north_cut[0] < 0.0); + assert!(side(0, 496.0, 496.0, 512.0).is_empty()); + + // Block edits do not refresh Chunk.heights; observation must scan the + // actual blocks, including builds above the old heightmap. + let mut chunk = Chunk::empty(-1, -1); + chunk.set(0, 120, 0, stone.0); + chunk.set(4, 54, 4, stone.0); + for y in 55..64 { + chunk.set(4, y, 4, water.0); + } + lod.observe(&chunk, &facts); + let observed = &lod.saved[&(-1, -1)]; + assert_eq!(observed[0].surface.unwrap().height, 121); + assert_eq!(observed[0].surface.unwrap().state, stone); + assert_eq!(observed[68].surface.unwrap().height, 55); + assert_eq!(observed[68].surface.unwrap().water, Some((64, water))); + + let fine = TileKey { + x: -1, + z: -1, + level: 0, + }; + lod.ready.insert(fine, vec![Column::default(); 256]); + lod.finish_detail( + (-1, -1), + ReducedColumns::new(Arc::new(std::array::from_fn(|_| Column::default()))), + ); + assert_eq!( + lod.ready[&fine][0].surface.unwrap().height, + 121, + "late seed generation cannot overwrite a visited build" + ); + assert_eq!(lod.detail_masks[&fine], [u64::MAX; 4]); + lod.plan.nodes.insert(fine); + lod.pending.insert(fine); + lod.finish_sample(fine, vec![Column::default(); 256]); + assert_eq!( + lod.ready[&fine][0].surface.unwrap().height, + 121, + "a late coarse sampling job cannot erase completed detail" + ); + assert_eq!(lod.detail_masks[&fine], [u64::MAX; 4]); + lod.plan.nodes.remove(&fine); + + // Real worker results populate the reusable pyramid; an older result + // must never put a previous edit back into that cache. + let receive_reduction = |lod: &mut Lod| { + let Done::Detail(key, columns) = lod + .results + .recv_timeout(std::time::Duration::from_secs(5)) + .unwrap() + else { + panic!("expected queued visited reduction"); + }; + lod.finish_detail(key, columns); + }; + receive_reduction(&mut lod); + assert!(Arc::ptr_eq( + &lod.reduced[&(-1, -1)].columns, + &lod.saved[&(-1, -1)] + )); + assert!(lod.visited_column(-16, -16, 2).unwrap().spans.is_empty()); + let old = lod.saved[&(-1, -1)].clone(); + chunk.set(0, 130, 0, stone.0); + lod.observe(&chunk, &facts); + assert!(!lod.reduced.contains_key(&(-1, -1))); + lod.finish_detail((-1, -1), ReducedColumns::new(old)); + assert!(!lod.reduced.contains_key(&(-1, -1))); + assert_eq!(lod.ready[&fine][0].surface.unwrap().height, 131); + receive_reduction(&mut lod); + assert!(Arc::ptr_eq( + &lod.reduced[&(-1, -1)].columns, + &lod.saved[&(-1, -1)] + )); + + // Exercise the actual worker/update seam: a parent stays displayed + // until all four child meshes can replace it in the same update. + let camera = [-256.0, 100.0, -256.0]; + lod.area = Some(([-16, -16], 2, 64, 0)); + lod.plan.roots = vec![key]; + lod.plan.nodes.insert(key); + let await_meshes = |lod: &mut Lod| { + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + let meshes = lod.update(camera, 0.0, 2, 64, lod.covered.clone()); + if !meshes.is_empty() { + return meshes; + } + assert!(std::time::Instant::now() < deadline, "mesh worker stalled"); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + }; + let uploaded = await_meshes(&mut lod); + assert_eq!(uploaded.len(), 1); + assert_eq!(uploaded[0].0, key); + assert!(lod.active.contains(&key)); + lod.plan.split.insert(key); + for child in key.children() { + lod.plan.nodes.insert(child); + lod.ready.insert(child, lod.ready[&key].clone()); + } + assert!( + lod.update(camera, 0.0, 2, 64, lod.covered.clone()) + .is_empty() + ); + assert!( + lod.active.contains(&key), + "parent retired before child meshes" + ); + assert!(lod.removed().is_empty()); + let uploaded = await_meshes(&mut lod); + assert_eq!(uploaded.len(), 4); + assert!( + key.children() + .iter() + .all(|child| lod.active.contains(child)) + ); + assert_eq!(lod.removed(), [key]); + + let covered_fine = TileKey { + x: -1, + z: -2, + level: 0, + }; + lod.plan = Plan::default(); + lod.plan.roots.push(covered_fine); + lod.plan.nodes.insert(covered_fine); + lod.ready.insert(covered_fine, vec![Column::default(); 256]); + lod.covered.insert((-1, -2)); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + loop { + lod.update(camera, 0., 2, 64, lod.covered.clone()); + if !lod.meshing && lod.active.is_empty() { + break; + } + assert!( + std::time::Instant::now() < deadline, + "covered normal chunk remained an active LOD mask" + ); + std::thread::sleep(std::time::Duration::from_millis(1)); + } + assert_eq!(lod.progress(), (1, 1)); + + // Keep one sample outstanding, as on ordinary frames. Completing just + // one job at a time must still let both loading queues make progress. + lod.shared.stop.store(true, Ordering::Relaxed); + lod.shared.wake.notify_all(); + lod.thread.take().unwrap().join().unwrap(); + while lod.results.try_recv().is_ok() {} + lod.shared.jobs.lock().unwrap().clear(); + lod.plan = Plan::new([-256, -256], 2, 64); + let parent = TileKey { + x: -2, + z: -2, + level: 3, + }; + lod.plan.roots = vec![parent]; + lod.ready.clear(); + lod.ready.insert(parent, vec![Column::default(); 256]); + lod.active = [parent].into_iter().collect(); + lod.pending = (0..SAMPLE_JOBS - 1) + .map(|i| TileKey { + x: 999 + i as i32, + z: 999, + level: 0, + }) + .collect(); + lod.sample_nearby = true; + lod.detail_request_pending = true; + lod.meshing = true; + lod.update(camera, 0.0, 2, 64, FxHashSet::default()); + let Some(Job::Sample(nearby)) = lod.shared.jobs.lock().unwrap().pop_front() else { + panic!("nearby detail was not scheduled"); + }; + assert_eq!(nearby.level, 0); + assert!( + nearby.origin()[2] > -256 + 64, + "detail should load ahead of the view" + ); + lod.finish_sample(nearby, vec![Column::default(); 256]); + lod.update(camera, 0.0, 2, 64, FxHashSet::default()); + let Some(Job::Sample(fallback)) = lod.shared.jobs.lock().unwrap().pop_front() else { + panic!("fallback refinement was starved"); + }; + assert!(fallback.level > 0); + lod.pending.remove(&fallback); + lod.sample_nearby = true; + lod.update(camera, 90.0, 2, 64, FxHashSet::default()); + let Some(Job::Sample(turned)) = lod.shared.jobs.lock().unwrap().pop_front() else { + panic!("turned view was not scheduled"); + }; + assert!( + turned.origin()[0] < -256 - 64, + "loading priority should follow a turn" + ); + lod.shared.jobs.lock().unwrap().clear(); + let near = TileKey { + x: -4, + z: -4, + level: 2, + }; + let far = TileKey { + x: 0, + z: 0, + level: 6, + }; + lod.plan = Plan::default(); + lod.plan.roots = vec![near, far]; + lod.ready.clear(); + for parent in [near, far] { + lod.plan.nodes.insert(parent); + lod.plan.split.insert(parent); + lod.plan.nodes.extend(parent.children()); + lod.ready.insert(parent, vec![Column::default(); 256]); + } + lod.active = [near, far].into_iter().collect(); + lod.shared.jobs.lock().unwrap().clear(); + lod.pending = (0..SAMPLE_JOBS - 1) + .map(|i| TileKey { + x: 999 + i as i32, + z: 999, + level: 0, + }) + .collect(); + lod.sample_nearby = false; + lod.update(camera, 0., 2, 64, FxHashSet::default()); + let Some(Job::Sample(broad)) = lod.shared.jobs.lock().unwrap().pop_front() else { + panic!("projected-error refinement missing") + }; + assert_eq!( + broad.level, 5, + "a near tile touching the camera must not starve a huge visible distant tile" + ); + lod.shared.jobs.lock().unwrap().clear(); + lod.active = (0..40).map(|x| TileKey { x, z: 0, level: 0 }).collect(); + lod.plan.split.clear(); + lod.detail_masks.clear(); + lod.covered = [(0, 0)].into_iter().collect(); + lod.detail_request_pending = false; + lod.detail_request_at = std::time::Instant::now() - std::time::Duration::from_secs(1); + lod.request_detail([0, 0]); + let Some(Job::RequestDetail { chunks, .. }) = lod.shared.jobs.lock().unwrap().pop_front() + else { + panic!("detail batch was not requested"); + }; + assert_eq!( + chunks, + (1..=32).map(|x| (x, 0)).collect::>(), + "one unfinished fine tile must not starve neighbouring requests" + ); + Ok(()) + } +} diff --git a/crates/horizon-client/src/lod/mesh.rs b/crates/horizon-client/src/lod/mesh.rs new file mode 100644 index 000000000..a991a4a8e --- /dev/null +++ b/crates/horizon-client/src/lod/mesh.rs @@ -0,0 +1,1178 @@ +//! Exposed voxel-column faces, merged without changing their block-scale UVs. +use super::{Column, Span, TileKey}; +use crate::{ + fast_hash::{FxHashMap, FxHashSet}, + mesher::{FaceGroups, OPAQUE_LAYER, SectionMesh, TerrainVertex}, + streaming::WorkerContext, +}; +use horizon_assets::model::Direction; +use horizon_core::position::BlockPos; +use horizon_world::registry::BlockStateId; +use std::collections::BTreeMap; + +const CELLS: usize = 16; + +pub(super) struct EdgeColumn { + pub start: i32, + pub end: i32, + pub column: Column, +} + +#[derive(Clone, Copy)] +enum Tint { + None, + Grass, + Foliage, + Dry, + Water, + Constant(u32), +} +#[derive(Clone, Copy)] +struct Style { + layer: u16, + tint: Tint, + translucent: bool, +} +#[derive(Clone, Copy)] +struct Styles { + faces: [Option