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/game.rs b/crates/horizon-client/src/game.rs index f13be4c84..1fb3a7889 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -780,6 +780,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, @@ -6426,6 +6429,7 @@ impl Game<'_> { self.using = None; self.screen = Screen::Playing; self.title = None; + self.clear_lod(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -6575,6 +6579,7 @@ impl Game<'_> { self.pickups.clear(); self.orbs.clear(); self.mining = None; + self.clear_lod(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -6753,6 +6758,7 @@ impl Game<'_> { self.sleep_timer = 0; self.clear_entities(); self.screen = Screen::Playing; + self.clear_lod(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -8626,9 +8632,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() @@ -8705,6 +8712,7 @@ impl Game<'_> { bob, sky, distance, + detail_distance: (self.streaming.radius * 16) as f32, depth_far, underwater, title: title && !live, @@ -8889,7 +8897,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) @@ -9096,10 +9104,63 @@ impl Game<'_> { } Ok(()) } + /// Only surface LOD worlds extend the renderer's range, never simulation. + fn terrain_distance(&self) -> i32 { + if self.lod.is_some() && self.dim != Dim::Nether { + 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.dim != Dim::Nether + && 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, @@ -9108,6 +9169,21 @@ 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 { + 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) { + lod.observe(chunk, &self.res.facts); + } + } + } let dirty: Vec<_> = unloaded .iter() .filter(|c| self.world.modified.remove(&(c.x, c.z))) @@ -9183,6 +9259,30 @@ 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 lod.update( + [player.position.x, player.position.y, player.position.z], + self.streaming.radius, + self.settings.horizon.lod_distance, + covered, + ) { + renderer.upload_lod(key, &mesh); + } + for key in lod.removed() { + renderer.remove_lod(key); + } + } } } } @@ -10040,6 +10140,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, diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index cf7510065..9b5fc3bc6 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", @@ -368,6 +369,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" => { self.world.day_time = arg(1)?.parse()?; ok() @@ -699,6 +709,15 @@ 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(), + }); let mut status = json!({ "screen": self.screen_name(), "debug": { @@ -757,6 +776,7 @@ impl Game<'_> { .eye_position() .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); + status["lod"] = lod; status["physical_keys"] = json!(physical_keys); status } diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 0b95dd2ad..dad536282 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -170,6 +170,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 c2fab26db..7e8114444 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -258,6 +258,7 @@ impl Game<'_> { self.screen = Screen::Playing; self.title = None; self.dim = Dim::Overworld; + self.clear_lod(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -362,6 +363,7 @@ impl Game<'_> { self.border = Default::default(); self.screen = Screen::Playing; self.container = None; + self.clear_lod(); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } @@ -595,6 +597,7 @@ impl Game<'_> { // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); } + self.clear_lod(); 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 4ee10e6d2..fad4f7352 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -85,7 +85,7 @@ impl Game<'_> { (water & 255) as f32 / 255.0, ], biome, - render_distance_chunks: self.streaming.radius, + render_distance_chunks: self.terrain_distance(), 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 4280efd4a..ff874136f 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -59,6 +59,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] mod arena; mod java_stages; +mod lod; mod occlusion; mod pack_stages; pub mod panorama; @@ -115,6 +116,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, @@ -322,6 +325,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, @@ -333,6 +338,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. @@ -530,6 +537,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] @@ -1746,6 +1754,8 @@ impl Renderer { outline, depth, sections: resident::Resident::default(), + lods: HashMap::new(), + detail_columns: HashMap::new(), arena, sorted_indices, translucent_sorter: translucency::Sorter::default(), @@ -1754,6 +1764,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(), @@ -1921,11 +1933,22 @@ impl Renderer { } else { self.block_entities.insert(key, mesh.block_entities.clone()); } + 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 { @@ -1934,16 +1957,14 @@ impl Renderer { } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; // With video and system memory both full, the section is not drawn. - let Some((page, start)) = self.arena.alloc(&self.device, &self.queue, vertices) else { - return; - }; + let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices)?; let sorted_indices = if translucent > 0 { let indices = self.sorted_indices .alloc(&self.device, &self.queue, u64::from(translucent) * 6); if indices.is_none() { self.arena.release(page, start, vertices); - return; + return None; } indices } else { @@ -1961,25 +1982,22 @@ impl Renderer { ); } } - 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, - }, - ); + 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, + }) } /// Draws `count` section draws from `first` with the arena and section /// origins bound: one indirect multi-draw, or a loop without it. @@ -2008,14 +2026,17 @@ impl Renderer { } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { - 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((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() @@ -2023,12 +2044,26 @@ impl Renderer { pub fn clear_sections(&mut self) { self.block_entities.clear(); self.sections.clear(); + self.lods.clear(); + self.detail_columns.clear(); self.arena.clear(); self.sorted_indices.clear(); 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)); + } + } self.block_entities.remove(&key); self.occlusion.remove(key); self.release_section(key); @@ -2395,7 +2430,7 @@ impl Renderer { ); let culling = !frame.title && frame.cave_culling; if culling { - let radius = (frame.distance / 16.0) as i32 + 2; + let radius = (frame.detail_distance / 16.0) as i32 + 2; self.occlusion.update(camera_section, radius); } let reachable = &self.occlusion; @@ -2403,14 +2438,26 @@ impl Renderer { visible.clear(); 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, @@ -2422,7 +2469,12 @@ impl Renderer { self.origins.extend( visible .iter() - .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]), + .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]) + .chain( + visible_lods + .iter() + .map(|v| [v.origin[0], v.origin[1], v.origin[2], 0.0]), + ), ); if !self.origins.is_empty() { self.uploads.buffer( @@ -2432,9 +2484,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(); @@ -2452,10 +2501,20 @@ impl Renderer { self.draw_pages.push((s.page, None)); }); } + 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 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() { @@ -2483,16 +2542,62 @@ 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)), + )); } } + 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. + self.translucent_draws + .sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.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; if self.multi_draw && !self.draws.is_empty() { @@ -3052,6 +3157,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/lod.rs b/crates/horizon-client/src/gfx/lod.rs new file mode 100644 index 000000000..43c01f6ae --- /dev/null +++ b/crates/horizon-client/src/gfx/lod.rs @@ -0,0 +1,142 @@ +//! 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()) + } +} + +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 { + pos, + uv: [0.0; 2], + layer: 0, + light: 0, + color: 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 f10c6b3b3..0009fd0fa 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -115,6 +115,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. @@ -152,6 +154,7 @@ impl Default for Graphics { fn default() -> Self { Self { preset: Preset::Custom, + lod_distance: 0, cave_culling: true, cull_leaves: false, entity_culling: false, @@ -197,6 +200,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), @@ -234,8 +238,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), @@ -330,6 +335,7 @@ mod tests { fn round_trips() { let g = Graphics { preset: Preset::Balanced, + lod_distance: 256, cave_culling: false, cull_leaves: true, entity_culling: true, @@ -357,6 +363,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 battery_mode_only_lowers_the_frame_cap() { let mut g = Graphics::default(); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 745cd5d80..236dc8333 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 45e09a6a3..d1f5e64bd 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -100,6 +100,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..3d39c2639 --- /dev/null +++ b/crates/horizon-client/src/lod.rs @@ -0,0 +1,862 @@ +//! Bounded surface terrain for distances beyond the resident chunk area. +//! Far tiles never enter World, lighting, simulation or the section cave graph. +use crate::{ + blocks::{BlockFacts, Fluid}, + chunk::{Chunk, HEIGHT, MIN_Y}, + fast_hash::{FxHashMap, FxHashSet}, + mesher::{FaceGroups, SectionMesh, TerrainVertex}, + streaming::{LodSource, WorkerContext}, +}; +use horizon_core::position::BlockPos; +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 = 8192; +/// 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, +} +#[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 { + 64 << 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) + } +} +#[derive(Default)] +struct Plan { + roots: Vec, + nodes: FxHashSet, + split: FxHashSet, +} +impl Plan { + fn new(camera: [i32; 2], detail: i32, distance: u32) -> Self { + let range = distance.min(1024) as i32 * 16; + let mut level = 0; + while (64 << level) < range { + level += 1; + } + let size = 64 << level; + let mut result = 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); + } + } + result + } + fn visit(&mut self, key: TileKey, camera: [i32; 2], detail: i32, range: i32) { + if key.distance(camera) > range { + return; + } + self.nodes.insert(key); + // Inside the near area, stride4 divides chunk boundaries exactly. + if key.level > 0 && key.distance(camera) < (key.size() * 2).max(detail * 16 + 64) { + self.split.insert(key); + for child in key.children() { + self.visit(child, camera, detail, range); + } + } + } + fn select( + &self, + key: TileKey, + ready: &FxHashMap>>, + out: &mut Vec, + ) -> bool { + if !self.nodes.contains(&key) { + return true; + } + if self.split.contains(&key) { + let start = out.len(); + if key + .children() + .into_iter() + .all(|child| self.select(child, ready, out)) + { + return true; + } + if ready.contains_key(&key) { + out.truncate(start); + out.push(key); + return true; + } + // Keep any children already available while the parent is loading. + out.truncate(start); + for child in key.children() { + self.select(child, ready, out); + } + false + } else if ready.contains_key(&key) { + out.push(key); + true + } else { + false + } + } +} +struct Job { + key: TileKey, +} +struct Done { + key: TileKey, + samples: Vec>, +} +struct Shared { + jobs: Mutex>, + wake: Condvar, + stop: AtomicBool, +} +#[derive(Clone, Copy)] +struct Style { + layer: u16, + tint: i32, + translucent: bool, + light: u16, +} +/// 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, + context: Arc, + area: Option<([i32; 2], i32, u32)>, + plan: Plan, + pending: FxHashSet, + ready: FxHashMap>>, + active: FxHashSet, + dirty: FxHashSet, + removed: Vec, + covered: FxHashSet<(i32, i32)>, + covered_bounds: Option<[i32; 4]>, + saved: FxHashMap<(i32, i32), [Option; 16]>, + saved_order: VecDeque<(i32, i32)>, + styles: FxHashMap, +} +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 (tx, results) = mpsc::channel(); + let handle = thread::Builder::new() + .name("Far terrain".into()) + .spawn(move || { + let mut sampler = source.sampler(); + loop { + let job = { + let mut jobs = worker.jobs.lock().unwrap(); + while jobs.is_empty() && !worker.stop.load(Ordering::Relaxed) { + jobs = worker.wake.wait(jobs).unwrap(); + } + if worker.stop.load(Ordering::Relaxed) { + break; + } + jobs.pop_front().unwrap() + }; + let [x, _, z] = job.key.origin(); + let stride = job.key.size() / CELLS as i32; + let mut samples = Vec::with_capacity(CELLS * CELLS); + for dz in 0..CELLS { + if worker.stop.load(Ordering::Relaxed) { + break; + } + for dx in 0..CELLS { + samples.push( + sampler.sample(x + dx as i32 * stride, z + dz as i32 * stride), + ); + } + } + if tx + .send(Done { + key: job.key, + samples, + }) + .is_err() + { + break; + } + } + }) + .expect("far terrain worker"); + Self { + shared, + thread: Some(handle), + results, + context, + area: None, + plan: Plan::default(), + pending: FxHashSet::default(), + ready: FxHashMap::default(), + active: FxHashSet::default(), + dirty: FxHashSet::default(), + removed: Vec::new(), + covered: FxHashSet::default(), + covered_bounds: None, + saved: FxHashMap::default(), + saved_order: VecDeque::new(), + styles: FxHashMap::default(), + } + } + pub fn stats(&self) -> (usize, usize) { + (self.active.len(), self.ready.len()) + } + pub fn removed(&mut self) -> Vec { + std::mem::take(&mut self.removed) + } + pub fn invalidate_chunk(&mut self, x: i32, z: i32) { + 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); + } + } + } + /// Sample only sixteen columns, from current block storage (heightmaps can + /// be stale after edits). Memory stays bounded while exploring indefinitely. + pub fn observe(&mut self, chunk: &Chunk, facts: &BlockFacts) { + let values = std::array::from_fn(|i| { + let x = (i & 3) as i32 * 4; + let z = (i >> 2) as i32 * 4; + let mut water = None; + for y in (MIN_Y..MIN_Y + HEIGHT).rev() { + let state = BlockStateId(chunk.get(x, y, z)); + if facts.is_air(state) { + continue; + } + let f = facts.get(state); + if !matches!(f.fluid, Fluid::None) { + if water.is_none() { + water = Some((y + 1, state)); + } + } else if f.solid_render || f.name.ends_with("_leaves") { + return Some(Surface { + height: y + 1, + state, + water, + biome: chunk.biome(x, y, z), + }); + } + } + water.map(|(y, state)| Surface { + height: MIN_Y, + state: facts.air, + water: Some((y, state)), + biome: chunk.biome(x, y - 1, z), + }) + }); + 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.saved_order.push_back(key); + } + self.saved.insert(key, values); + self.invalidate_chunk(chunk.x, chunk.z); + } + pub fn update( + &mut self, + camera: [f64; 3], + detail: i32, + distance: u32, + covered: FxHashSet<(i32, i32)>, + ) -> Vec<(TileKey, SectionMesh)> { + let camera = [camera[0].floor() as i32, camera[2].floor() 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, + ); + if self.area != Some(area) { + self.area = Some(area); + self.plan = Plan::new(camera, detail, distance); + self.ready.retain(|key, _| self.plan.nodes.contains(key)); + } + while let Ok(done) = self.results.try_recv() { + self.pending.remove(&done.key); + if self.plan.nodes.contains(&done.key) { + if done.samples.len() == CELLS * CELLS { + self.ready.insert(done.key, done.samples); + } + } + } + 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; + } + let mut selected = Vec::new(); + for &key in &self.plan.roots { + self.plan.select(key, &self.ready, &mut selected); + } + let next: FxHashSet<_> = selected.iter().copied().collect(); + self.removed.extend(self.active.difference(&next).copied()); + self.dirty.extend(next.difference(&self.active).copied()); + self.active = next; + self.dirty.retain(|key| self.active.contains(key)); + let keys: Vec<_> = self.dirty.drain().collect(); + let meshes = keys.into_iter().map(|key| (key, self.mesh(key))).collect(); + let mut wanted: Vec<_> = self + .plan + .nodes + .iter() + .copied() + .filter(|key| !self.ready.contains_key(key) && !self.pending.contains(key)) + .collect(); + // Coarse ancestors first: cover the horizon quickly, then refine. + wanted + .sort_unstable_by_key(|key| (std::cmp::Reverse(key.level), key.distance(camera), *key)); + let mut jobs = self.shared.jobs.lock().unwrap(); + for key in wanted + .into_iter() + .take(2usize.saturating_sub(self.pending.len())) + { + self.pending.insert(key); + jobs.push_back(Job { key }); + } + self.shared.wake.notify_one(); + meshes + } + fn style(&mut self, state: BlockStateId) -> Style { + if let Some(style) = self.styles.get(&state) { + return *style; + } + let registry = self.context.assets.registry; + let name = registry.state(state).map(|s| s.name.as_str()).unwrap_or(""); + let fluid = match name { + "minecraft:water" | "minecraft:bubble_column" => Some(("block/water_still", true, -2)), + "minecraft:lava" => Some(("block/lava_still", false, -1)), + _ => None, + }; + let style = if let Some((sprite, translucent, tint)) = fluid { + Style { + layer: self + .context + .assets + .sprite_layers + .get(sprite) + .or_else(|| { + self.context + .assets + .sprite_layers + .get(&format!("minecraft:{sprite}")) + }) + .copied() + .unwrap_or(0) as u16, + tint, + translucent, + light: 240 + | (self + .context + .tables + .facts(state) + .map_or(0, |f| u16::from(f.emission)) + * 16 + << 8), + } + } else { + let models = self + .context + .assets + .model_catalog + .collect(state, BlockPos::new(0, 0, 0)) + .ok(); + let face = models.as_ref().and_then(|m| { + m.iter() + .flat_map(|(_, m)| &m.faces) + .find(|f| f.quad.facing == horizon_assets::model::Direction::Up) + }); + Style { + layer: face.map_or(0, |f| f.layer as u16), + tint: if face.is_some_and(|f| f.quad.tint_index >= 0) { + if name.contains("leaves") { -3 } else { 0 } + } else { + -1 + }, + translucent: face.is_some_and(|f| f.translucent), + light: 240 + | (self + .context + .tables + .facts(state) + .map_or(0, |f| u16::from(f.emission)) + * 16 + << 8), + } + }; + self.styles.insert(state, style); + style + } + fn mesh(&mut self, key: TileKey) -> SectionMesh { + let mut mesh = SectionMesh::default(); + let stride = key.size() / CELLS as i32; + let [ox, _, oz] = key.origin(); + let mut samples = 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(saved) = self.saved.get(&(wx.div_euclid(16), wz.div_euclid(16))) { + samples[z * CELLS + x] = + saved[((wz.rem_euclid(16) / 4) * 4 + wx.rem_euclid(16) / 4) as usize]; + } + } + } + for z in 0..CELLS { + for x in 0..CELLS { + let (wx, wz) = (ox + x as i32 * stride, oz + z as i32 * stride); + let Some(sample) = samples[z * CELLS + x] else { + continue; + }; + // Only fine cells overlap near chunks; coarse parent fallbacks + // also clip individual chunk-sized pieces while children load. + let overlaps = self.covered_bounds.is_some_and(|[x0, z0, x1, z1]| { + wx < x1 && wx + stride > x0 && wz < z1 && wz + stride > z0 + }); + let step = if overlaps { stride.min(16) } else { stride }; + for dz in (0..stride).step_by(step as usize) { + for dx in (0..stride).step_by(step as usize) { + if self + .covered + .contains(&((wx + dx).div_euclid(16), (wz + dz).div_euclid(16))) + { + continue; + } + let (x0, z0, x1, z1) = ( + (x as i32 * stride + dx) as f32, + (z as i32 * stride + dz) as f32, + (x as i32 * stride + dx + step) as f32, + (z as i32 * stride + dz + step) as f32, + ); + let y = sample.height as f32; + if y > MIN_Y as f32 { + let style = self.style(sample.state); + let color = self.color(style, sample.biome); + quad( + &mut mesh, + style, + color, + [[x0, y, z1], [x1, y, z1], [x1, y, z0], [x0, y, z0]], + 1.0, + ); + for (nx, nz, cell_edge, neighbor, points, shade) in [ + ( + x as i32 - 1, + z as i32, + dx == 0, + [wx + dx - 1, wz + dz], + [[x0, y, z0], [x0, y, z1], [x0, 0.0, z1], [x0, 0.0, z0]], + 0.6, + ), + ( + x as i32 + 1, + z as i32, + dx + step == stride, + [wx + dx + step, wz + dz], + [[x1, y, z1], [x1, y, z0], [x1, 0.0, z0], [x1, 0.0, z1]], + 0.6, + ), + ( + x as i32, + z as i32 - 1, + dz == 0, + [wx + dx, wz + dz - 1], + [[x1, y, z0], [x0, y, z0], [x0, 0.0, z0], [x1, 0.0, z0]], + 0.8, + ), + ( + x as i32, + z as i32 + 1, + dz + step == stride, + [wx + dx, wz + dz + step], + [[x0, y, z1], [x1, y, z1], [x1, 0.0, z1], [x0, 0.0, z1]], + 0.8, + ), + ] { + let cut_edge = self.covered.contains(&( + neighbor[0].div_euclid(16), + neighbor[1].div_euclid(16), + )); + let floor = if cut_edge { + // Near terrain may be below the coarse top; + // close the cut instead of exposing its underside. + MIN_Y + } else if !cell_edge { + continue; + } else if (0..CELLS as i32).contains(&nx) + && (0..CELLS as i32).contains(&nz) + { + samples[(nz as usize) * CELLS + nx as usize] + .map_or(MIN_Y, |s| s.height) + } else { + MIN_Y + }; + if floor < sample.height { + let mut p = points; + p[2][1] = floor as f32; + p[3][1] = floor as f32; + p.reverse(); + quad(&mut mesh, style, color, p, shade); + } + } + } + if let Some((height, state)) = sample.water { + let style = self.style(state); + let color = self.color(style, sample.biome); + let y = height as f32 - 1.0 / 9.0; + quad( + &mut mesh, + style, + color, + [[x0, y, z1], [x1, y, z1], [x1, y, z0], [x0, y, z0]], + 1.0, + ); + } + } + } + } + } + mesh.faces = FaceGroups::group(&mut mesh.solid); + mesh + } + fn color(&self, style: Style, biome: u16) -> u32 { + let b = self.context.biomes.get(biome); + match style.tint { + -2 => b.water, + -3 => b.foliage, + 0 => b.grass, + _ => 0xffffff, + } + } +} +fn quad(mesh: &mut SectionMesh, style: Style, color: u32, points: [[f32; 3]; 4], shade: f32) { + let channel = |shift: u32| (((color >> shift) & 255u32) as f32 * shade) as u32; + let color = channel(16) | (channel(8) << 8) | (channel(0) << 16) | 0xff000000; + let out = if style.translucent { + &mut mesh.translucent + } else { + &mut mesh.solid + }; + out.extend( + points + .into_iter() + .zip([[0., 1.], [1., 1.], [1., 0.], [0., 0.]]) + .map(|(pos, uv)| TerrainVertex { + pos, + uv, + layer: style.layer, + light: style.light, + color, + }), + ); +} +impl Drop for Lod { + fn drop(&mut self) { + self.shared.stop.store(true, Ordering::Relaxed); + self.shared.wake.notify_one(); + if let Some(thread) = self.thread.take() { + let _ = thread.join(); + } + } +} +#[cfg(test)] +mod tests { + use super::*; + #[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() < 2500, "{} 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 < 2000); + } + } + assert_eq!( + TileKey { + x: -1, + z: -2, + level: 1 + } + .origin(), + [-128, 0, -256] + ); + } + #[test] + fn parent_covers_missing_children_then_retires_without_overlap() { + 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(); + assert!(plan.select(parent, &ready, &mut selected)); + assert_eq!(selected, [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 coarse_quad_keeps_winding_light_and_transparency() { + let mut mesh = SectionMesh::default(); + let style = Style { + layer: 7, + tint: -1, + translucent: true, + light: 240, + }; + quad( + &mut mesh, + style, + 0x123456, + [ + [0., 70., 64.], + [64., 70., 64.], + [64., 70., 0.], + [0., 70., 0.], + ], + 1., + ); + assert!(mesh.solid.is_empty()); + assert_eq!(mesh.translucent.len(), 4); + assert_eq!(mesh.translucent[0].color, 0xff563412); + let q = &mesh.translucent; + assert!( + (glam::Vec3::from(q[1].pos) - glam::Vec3::from(q[0].pos)) + .cross(glam::Vec3::from(q[2].pos) - glam::Vec3::from(q[0].pos)) + .y + > 0. + ); + } + #[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 facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(MeshTables::new( + &assets, + &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(), + 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: 3, + }; + lod.ready.insert( + key, + vec![ + 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].unwrap().height, 121); + assert_eq!(observed[0].unwrap().state, stone); + assert_eq!(observed[5].unwrap().height, 55); + assert_eq!(observed[5].unwrap().water, Some((64, water))); + Ok(()) + } +} diff --git a/crates/horizon-client/src/mesher/facing.rs b/crates/horizon-client/src/mesher/facing.rs index 2a7f0ba61..b27e59e29 100644 --- a/crates/horizon-client/src/mesher/facing.rs +++ b/crates/horizon-client/src/mesher/facing.rs @@ -42,6 +42,11 @@ impl Default for FaceGroups { } impl FaceGroups { + /// Group arbitrary-sized terrain quads, including distant LOD tiles. + pub fn group(solid: &mut Vec) -> Self { + group(solid) + } + /// Whether group `g` can hold a front-facing quad for an eye at `eye`, /// relative to the section's minimum corner. pub fn visible(&self, g: usize, eye: Vec3) -> bool { diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 7ef38788b..6adb69de6 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -29,7 +29,7 @@ use horizon_world::{ chunk::BlockState, chunk_status::ChunkStatus, compression::Compression, - heightmap::{Heightmap, HeightmapChunk, HeightmapType}, + heightmap::{Heightmap, HeightmapChunk, HeightmapState, HeightmapType}, nbt::{self, Compound, JavaString, Limits, NamedTag, Tag}, region::{ChunkRecord, RegionFile, RegionWriter}, registry::{BlockRegistry, BlockStateId}, @@ -2783,11 +2783,188 @@ pub struct Persistent { pub registry: Arc, pub biomes: Arc, } +type LodSurfaces = [Option; 16]; +struct SavedLodSampler { + generator: Arc>, + inner: Box, + cache: std::collections::VecDeque<((i32, i32), Option)>, +} +impl crate::streaming::LodSampler for SavedLodSampler { + fn sample(&mut self, x: i32, z: i32) -> Option { + let key = (x >> 4, z >> 4); + let cached = match self.cache.iter().position(|(at, _)| *at == key) { + Some(index) => self.cache.remove(index).unwrap(), + None => { + let surfaces = self.generator.save.lod_surfaces( + key.0, + key.1, + &self.generator.registry, + &self.generator.biomes, + ); + (key, surfaces) + } + }; + let surfaces = cached.1; + self.cache.push_front(cached); + self.cache.truncate(128); + match surfaces { + Some(surfaces) => surfaces[((z & 15) / 4 * 4 + (x & 15) / 4) as usize], + None => self.inner.sample(x, z), + } + } +} + +/// Read one palette entry without expanding the other entries in the section. +fn lod_palette_entry( + container: &Tag, + index: usize, + entries: usize, + minimum_bits: u32, +) -> Option<&Tag> { + let Tag::List(palette) = container.get("palette")? else { + return None; + }; + if palette.is_empty() || palette.len() > entries || index >= entries { + return None; + } + if palette.len() == 1 { + return palette.first(); + } + let bits = (usize::BITS - (palette.len() - 1).leading_zeros()).max(minimum_bits); + let per_word = 64 / bits as usize; + let Tag::LongArray(data) = container.get("data")? else { + return None; + }; + if data.len() != entries.div_ceil(per_word) { + return None; + } + let value = ((data[index / per_word] as u64 >> ((index % per_word) * bits as usize)) + & ((1 << bits) - 1)) as usize; + palette.get(value) +} +fn decode_lod_surfaces( + root: &NamedTag, + assets: &crate::assets::Assets, + biomes: &Biomes, +) -> Option { + let Tag::List(sections) = root.tag.get("sections")? else { + return None; + }; + let mut sections: Vec<_> = sections + .iter() + .filter_map(|section| { + let y = number(section.get("Y"))? as i32; + (MIN_Y >> 4..(MIN_Y >> 4) + SECTIONS as i32) + .contains(&y) + .then_some((y, section)) + }) + .collect(); + sections.sort_unstable_by_key(|(y, _)| std::cmp::Reverse(*y)); + let mut surfaces = [None; 16]; + let mut water = [None; 16]; + let mut states = BTreeMap::new(); + for (section_y, section) in sections { + let Some(blocks) = section.get("block_states") else { + continue; + }; + for z in (0..16).step_by(4) { + for x in (0..16).step_by(4) { + let cell = z / 4 * 4 + x / 4; + if surfaces[cell].is_some() { + continue; + } + for y in (0..16).rev() { + let entry = lod_palette_entry(blocks, y * 256 + z * 16 + x, 4096, 4)?; + let descriptor = BlockState::from_nbt(entry).ok()?; + let state = *states.entry(descriptor.clone()).or_insert_with(|| { + assets + .registry + .id(&descriptor) + .or_else(|| assets.registry.default_state(&descriptor.name)) + }); + let Some(state) = state else { + continue; + }; + let properties = assets.properties.heightmap_state(state); + if properties.is_air() { + continue; + } + let height = section_y * 16 + y as i32 + 1; + if matches!( + descriptor.name.as_str(), + "minecraft:water" | "minecraft:lava" + ) { + water[cell].get_or_insert((height, state)); + continue; + } + if !properties.blocks_motion_in_heightmap() { + continue; + } + let biome = section + .get("biomes") + .and_then(|container| { + lod_palette_entry(container, (y / 4) * 16 + (z / 4) * 4 + x / 4, 64, 1) + }) + .and_then(|tag| match tag { + Tag::String(name) => Some(biomes.id(&name.to_string_lossy())), + _ => None, + }) + .unwrap_or(0); + surfaces[cell] = Some(crate::lod::Surface { + height, + state, + water: water[cell], + biome, + }); + break; + } + } + } + } + Some(surfaces) +} +impl SaveDir { + fn lod_surfaces( + &self, + x: i32, + z: i32, + assets: &crate::assets::Assets, + biomes: &Biomes, + ) -> Option { + let pending = self + .pending + .lock() + .ok()? + .get(&(false, x, z)) + .map(|(_, record)| record.clone()); + let root = if let Some(record) = pending { + record.tag().map(|tag| (*tag).clone())? + } else { + // Far-only reads must not populate the gameplay region cache across the whole view. + let mut region = RegionFile::open(self.region_path("region", x >> 5, z >> 5)).ok()?; + region + .read(ChunkPos::new(x, z)) + .ok()?? + .nbt(Limits::default()) + .ok()? + }; + decode_lod_surfaces(&root, assets, biomes) + } +} + impl ChunkGenerator for Persistent { type Worker = G::Worker; fn worker(&self) -> G::Worker { self.inner.worker() } + fn lod_sampler(self: Arc) -> Box { + let inner = ChunkGenerator::lod_sampler(self.inner.clone()); + Box::new(SavedLodSampler { + generator: self, + inner, + cache: Default::default(), + }) + } fn load(&self, x: i32, z: i32) -> Option { self.save .tables @@ -2799,6 +2976,10 @@ impl ChunkGenerator for Persistent { chunk.entities = self.save.load_entities(x, z); Some(chunk) } + fn lod_surface(&self, worker: &mut G::Worker, x: i32, z: i32) -> Option { + // Resident/visited summaries override this procedural fallback in the LOD cache. + self.inner.lod_surface(worker, x, z) + } fn prepare_loaded(&self, worker: &mut G::Worker, chunk: &Chunk) { self.inner.prepare_loaded(worker, chunk); } @@ -2857,6 +3038,52 @@ impl ChunkGenerator for Persistent { #[cfg(test)] mod tests { + #[test] + fn saved_far_surface_reads_builds_and_water_without_gameplay_chunks() { + let Some(root) = std::env::var_os("HORIZON_TEST_RESOURCES") else { + return; + }; + let root = PathBuf::from(root); + let assets = crate::assets::Assets::load(&root).expect("assets"); + let biomes = Biomes::load(&root).expect("biomes"); + let stone = assets.registry.default_state("minecraft:stone").unwrap(); + let water = assets.registry.default_state("minecraft:water").unwrap(); + let sand = assets.registry.default_state("minecraft:sand").unwrap(); + let mut chunk = Chunk::empty(-2, 3); + chunk.set(0, 109, 0, stone.0); + chunk.set(4, 54, 4, sand.0); + for y in 55..64 { + chunk.set(4, y, 4, water.0); + } + let mut saved = encode(&chunk, assets.registry, &biomes); + put( + &mut saved.tag, + "block_entities", + Tag::String("not decoded by far sampling".into()), + ); + let dir = std::env::temp_dir().join(format!("horizon-lod-save-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let save = SaveDir::new(dir.clone()); + save.write_records("region", vec![((-2, 3), Some(saved))], true) + .unwrap(); + let reopened = SaveDir::new(dir.clone()); + let surfaces = reopened + .lod_surfaces(-2, 3, &assets, &biomes) + .expect("saved summary"); + assert_eq!(surfaces[0].unwrap().height, 110); + assert_eq!(surfaces[0].unwrap().state, stone); + let underwater = surfaces[5].unwrap(); + assert_eq!((underwater.height, underwater.state), (55, sand)); + assert_eq!(underwater.water, Some((64, water))); + assert!(surfaces[15].is_none(), "saved void stays empty"); + assert!( + reopened.regions.lock().unwrap().is_empty(), + "far reads do not grow gameplay region cache" + ); + drop((save, reopened)); + fs::remove_dir_all(dir).unwrap(); + } + #[test] fn save_batch_preserves_order_coordinates_and_ownership() { use crate::containers::BlockEntity; diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 38fa33c7d..6453908c7 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -32,6 +32,25 @@ pub type Proto = Box; pub trait ChunkGenerator: Send + Sync + 'static { type Worker: Send + 'static; fn worker(&self) -> Self::Worker; + fn lod_sampler(self: Arc) -> Box + where + Self: Sized, + { + let worker = self.worker(); + Box::new(GeneratorSampler { + generator: self, + worker, + }) + } + /// An undecorated far-terrain column, without allocating gameplay chunks. + fn lod_surface( + &self, + _worker: &mut Self::Worker, + _x: i32, + _z: i32, + ) -> Option { + None + } /// A previously saved final chunk, bypassing generation. fn load(&self, _x: i32, _z: i32) -> Option { None @@ -63,8 +82,29 @@ pub trait ChunkGenerator: Send + Sync + 'static { /// neighbours' decoration is done, so it can't be generated again. fn save_finished(&self, _chunk: Chunk) {} } +/// Independent, thread-owned far-terrain sampling state. +pub trait LodSampler: Send { + fn sample(&mut self, x: i32, z: i32) -> Option; +} +pub trait LodSource: Send + Sync { + fn sampler(self: Arc) -> Box; +} +struct GeneratorSampler { + generator: Arc, + worker: G::Worker, +} +impl LodSampler for GeneratorSampler { + fn sample(&mut self, x: i32, z: i32) -> Option { + self.generator.lod_surface(&mut self.worker, x, z) + } +} +impl LodSource for G { + fn sampler(self: Arc) -> Box { + ChunkGenerator::lod_sampler(self) + } +} /// The generator's saving, for the streamer (which doesn't know its type). -trait Saves: Send + Sync { +trait Saves: LodSource { fn save_protos(&self, protos: &[&Proto]); fn save_finished(&self, chunk: Chunk); } @@ -486,6 +526,10 @@ impl Streaming { mesh: true, } } + /// Shares generation resources, but gives distant work its own worker state. + pub fn lod_source(&self) -> Arc { + self.saves.clone() + } /// Resource packs reloaded (`LevelRenderer.allChanged`): mesh with the new /// models and sprites, and rebuild every loaded section. Meshes in flight /// were made with the old resources; their results are dropped. diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs index 6268a8b6c..cded7ae47 100644 --- a/crates/horizon-client/src/testgen.rs +++ b/crates/horizon-client/src/testgen.rs @@ -64,6 +64,19 @@ fn hash(x: i32, z: i32) -> u32 { impl ChunkGenerator for TestTerrain { type Worker = (); fn worker(&self) {} + fn lod_surface(&self, _: &mut (), x: i32, z: i32) -> Option { + let h = Self::height(x, z); + Some(crate::lod::Surface { + height: h + 1, + state: horizon_world::registry::BlockStateId(if h <= 63 { + self.sand + } else { + self.grass + }), + water: (h < 62).then_some((63, horizon_world::registry::BlockStateId(self.water))), + biome: self.plains, + }) + } fn proto(&self, w: &mut (), x: i32, z: i32) -> crate::streaming::Proto { Box::new(self.generate(w, x, z)) } @@ -136,3 +149,38 @@ impl TestTerrain { chunk } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn far_surface_agrees_with_generated_land_and_water() { + let terrain = TestTerrain { + stone: 1, + dirt: 2, + grass: 3, + water: 4, + sand: 5, + bedrock: 6, + log: 7, + leaves: 8, + short_grass: 9, + plains: 10, + }; + let mut wet = false; + for (cx, cz) in [(0, 0), (-7, 3), (15, -12), (-21, -8)] { + let chunk = terrain.generate(&mut (), cx, cz); + for x in 0..16 { + let surface = terrain.lod_surface(&mut (), cx * 16 + x, cz * 16).unwrap(); + assert_eq!(chunk.get(x, surface.height - 1, 0), surface.state.0); + if let Some((height, state)) = surface.water { + wet = true; + assert_eq!(chunk.get(x, height - 1, 0), state.0); + assert_eq!(chunk.get(x, height, 0), 0); + } + } + } + assert!(wet, "fixture includes underwater land"); + } +} diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 657817bb9..6d8aeaa4b 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -35,6 +35,7 @@ pub struct VanillaTerrain { tick_blocks: Vec, /// Block index -> default state id: `tick_blocks` the other way. tick_states: Vec, + lod_supported: bool, } /// A proto chunk, or the position of one whose generation failed. enum VanillaProto { @@ -106,6 +107,7 @@ impl VanillaTerrain { query: std::sync::Mutex::new(None), tick_blocks, tick_states, + lod_supported: dimension != "minecraft:the_nether", }) } /// A proto chunk's blocks, biomes, scheduled ticks and post-processing @@ -265,6 +267,27 @@ impl ChunkGenerator for VanillaTerrain { fn worker(&self) -> GeneratorWorker { self.generator.worker() } + fn lod_surface( + &self, + worker: &mut GeneratorWorker, + x: i32, + z: i32, + ) -> Option { + if !self.lod_supported { + return None; + } + let surface = worker.surface_sample(x, z)?; + Some(crate::lod::Surface { + height: surface.height, + state: surface.state, + water: surface.water, + biome: self + .biome_map + .get(surface.biome.0 as usize) + .copied() + .unwrap_or(0), + }) + } /// The structure starts a saved chunk references, as vanilla reads them /// with the chunk: built here, on the loading worker, into the /// generator's cache, rather than on the game thread the first time diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 12dfc10d9..41f5d424b 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -24,8 +24,8 @@ use super::{ decode_noise, density::DensityRegistry, material_condition::{ - MaterialConditionRegistry, MaterialRule, MaterialRuleError, MaterialRuleLibrary, - MaterialSurfaceQueries, + MaterialConditionRegistry, MaterialConditions, MaterialDensitySources, MaterialRule, + MaterialRuleError, MaterialRuleLibrary, MaterialSurfaceQueries, }, material_extensions::{ExtensionBlocks, ExtensionNoises, MaterialExtensions}, material_stage::{SurfaceInputs, TopMaterialInputs, build_surface}, @@ -1412,6 +1412,7 @@ trait SeededPipeline: Send + Sync { ) -> Result; fn data(&self) -> &Arc; fn sea_level(&self) -> i32; + fn surface_sample(&self, worker: &mut WorkerState, x: i32, z: i32) -> Option; fn structure_starts( &self, worker: &mut WorkerState, @@ -1594,6 +1595,69 @@ where } None } + fn surface_sample(&self, worker: &mut WorkerState, x: i32, z: i32) -> Option { + let mut top = None; + let mut water = None; + let mut below = 0; + self.noise_column(x, z, &mut |y, state| { + let properties = self.data.states.get(state); + if properties.is_air() || properties.has_fluid() { + if top.is_some() { + return true; + } + if properties.has_fluid() { + water.get_or_insert((y + 1, state)); + } else { + // Match the material traversal's water reset across air gaps. + water = None; + } + } else { + top.get_or_insert((y + 1, state)); + below += 1; + } + false + }); + let (height, state) = top?; + let y = height - 1; + let position = BlockPos::new(x, y, z); + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + // Use a fresh bounded context: far samples must not grow the chunk/structure caches. + let mut biome_context = SamplerContext::default(); + let biome = resolver + .sample(&mut biome_context, self.zoom.quart_at_block(position)) + .ok()?; + let biome = self.data.biome_id(biome)?; + let volume = DensityVolume::new([1; 3], [x, y, z], [1; 3]).ok()?; + let queries = SurfaceQueries { + pipeline: self, + temperatures: &mut worker.temperatures, + biome: Biomes::Resolver(&mut resolver, &mut biome_context), + possible: None, + }; + let sources = MaterialDensitySources::new( + queries, + volume, + self.preliminary.clone(), + SamplerContext::default(), + ) + .ok()?; + let mut material = + MaterialConditions::::new(self.generation(), self.root.clone(), sources); + let rule = material.add_rule(self.rule.clone()).ok()?; + // shortcut: distant surfaces omit slope rules and column extensions; nearby chunks provide full terrain. + material.update_xz(x, z, 0, 0); + material.update_y(1, below, water.map_or(i32::MIN, |(height, _)| height), y); + let state = material.try_apply(rule, position).ok()?.unwrap_or(state); + Some(SurfaceSample { + height, + state, + water, + biome, + }) + } fn noise_biomes(&self, worker: &mut WorkerState, quarts: &[[i32; 3]]) -> Vec> { let mut resolver = self.source.resolver( &self.climate, @@ -1864,6 +1928,15 @@ impl OverworldGenerator { } } +/// A surface-only noise column for far terrain. Heights are exclusive top faces. +#[derive(Clone, Copy, Debug)] +pub struct SurfaceSample { + pub height: i32, + pub state: BlockStateId, + pub water: Option<(i32, BlockStateId)>, + pub biome: BiomeId, +} + /// Per-thread generation state. pub struct GeneratorWorker { pipeline: Arc, @@ -1877,6 +1950,10 @@ impl GeneratorWorker { self.state.timings.chunks += 1; result } + /// Noise/aquifer surface and its material rule, without chunks, structures or features. + pub fn surface_sample(&mut self, x: i32, z: i32) -> Option { + self.pipeline.surface_sample(&mut self.state, x, z) + } /// `/locate structure`: the nearest start of one of `names`. pub fn locate( &mut self, @@ -1935,6 +2012,44 @@ impl GeneratorWorker { mod tests { use super::*; + #[test] + fn far_surface_matches_undecorated_land_and_keeps_end_void() { + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .or_else(|| std::env::var_os("HORIZON_RESOURCES")) + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry: &'static BlockRegistry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data"); + let generator = + OverworldGenerator::without_structures(data.clone(), 1234).expect("generator"); + let mut worker = generator.worker(); + let sample = worker.surface_sample(0, 0).expect("land"); + let chunk = worker.generate_proto(ChunkPos::new(0, 0)).expect("terrain"); + assert_eq!( + sample.water.map_or(sample.height, |(height, _)| height), + chunk.surface_height(0, 0) + ); + assert_eq!(sample.state, chunk.block(0, sample.height - 1, 0)); + assert!( + sample.water.is_some(), + "fixture includes underwater terrain" + ); + let end = + OverworldGenerator::for_dimension(data, 1234, "minecraft:normal", "minecraft:the_end") + .expect("End generator"); + let mut worker = end.worker(); + assert!(worker.surface_sample(0, 0).is_some()); + assert!(worker.surface_sample(256, 0).is_none()); + } + /// Generators of one seed and dimension share their ring positions; /// another seed or generator gets its own, and old entries go. #[test] diff --git a/docs/graphics.md b/docs/graphics.md index a55313bea..727203646 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -4,7 +4,7 @@ In the Horizon menu style, the Options screen's **Video** section holds the graphics settings, with a Simple / Advanced switch at the top (remembered between sessions): -- **Simple**: a preset (Performance, Balanced, Quality, Ultra or Custom), render distance, FOV, max framerate, VSync and GUI scale. +- **Simple**: a preset (Performance, Balanced, Quality, Ultra or Custom), render distance, LOD distance, FOV, max framerate, VSync and GUI scale. - **Advanced**: every setting, grouped under Rendering, Quality, Display, Preferences, Performance and Overlay. In the Classic style, Video Settings starts with two buttons opening the same settings as vanilla-looking screens. @@ -17,7 +17,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi | Group | Setting | Stored in | | --- | --- | --- | | Rendering | render distance, simulation distance, entity distance | `options.txt` (vanilla keys) | -| | cave culling, chunk updates per frame | `horizon-graphics.txt` | +| | LOD distance, cave culling, chunk updates per frame | `horizon-graphics.txt` | | Quality | smooth lighting, mipmap levels, biome blend, clouds, cloud distance, weather radius, particles, entity shadows, cutout leaves | `options.txt` | | | sky, fog, weather, animated textures | `horizon-graphics.txt` | | Display | FOV, max framerate, VSync, fullscreen, GUI scale | `options.txt` | @@ -31,7 +31,17 @@ Every row has a one-line description and its cost in frame time (none, low, medi Which settings each level shows, their descriptions and costs are in `crates/horizon-client/src/graphics_ui.rs` (`rows`); the Horizon shell draws them in `options_horizon.rs` with `ui_theme::described_row`, and the Classic screens use `graphics_style.rs`. -Not implemented: distant-terrain LOD, anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless). +## Distant terrain + +**LOD Distance** is off by default. Enable it in Simple or Advanced graphics settings and choose 64, 128, 256, 512 or 1024 chunks. With LODs enabled, **Full Detail Distance** controls the nearby normal chunks; LOD Distance controls the outer view. Keep the nearby range modest, for example 12 chunks with a 256-chunk LOD distance. Increasing the distant range does not increase simulation distance. + +Distant terrain uses progressively coarser surface meshes, streamed in bounded background work instead of loading full chunks out to the distant range. It is available in local Overworld and End worlds; surface LODs are disabled in the Nether. Far samples approximate undecorated terrain: distant caves, decorations, structures and player builds are not guaranteed to match the nearby world. Procedural distant terrain requires a local world's generator; remote servers do not supply their world-generation seed. + +LOD terrain enters the existing world colour and depth passes, so supported shader-pack postprocessing can see it. This does not add Iris material passes or shadow maps: Java packs still have the [existing fullscreen-pass limitations](shader-packs.md). Shader appearance and transitions need testing with the selected pack. + +The setting is stored as `lodDistance` in `horizon-graphics.txt`; `0` disables it. Existing `renderDistance` in `options.txt` keeps its normal meaning for full chunks. + +Not implemented: anisotropic filtering (wgpu needs linear magnification for it, which blurs close blocks), MSAA (FXAA instead) and exclusive fullscreen (fullscreen is borderless). ## Benchmark