diff --git a/crates/horizon-world/src/worldgen/biome_temperature.rs b/crates/horizon-world/src/worldgen/biome_temperature.rs index c7e22c985..7111214f4 100644 --- a/crates/horizon-world/src/worldgen/biome_temperature.rs +++ b/crates/horizon-world/src/worldgen/biome_temperature.rs @@ -123,10 +123,12 @@ pub struct BiomeTemperature { } impl BiomeTemperature { pub fn new(settings: BiomeTemperatureSettings) -> Self { + // Empty until used: a decoration region makes one per biome, and + // most biomes never ask for a temperature. Self { settings, - values: HashMap::with_capacity(1024), - order: VecDeque::with_capacity(1024), + values: HashMap::new(), + order: VecDeque::new(), } } pub fn settings(&self) -> BiomeTemperatureSettings { diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 5ab361985..b4e8c07b0 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -22,7 +22,7 @@ use horizon_core::{ }, }; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, sync::Arc, }; @@ -58,7 +58,10 @@ impl From for PlacementQueryError { } } pub struct TerrainRegion<'r, B: TerrainBlockStates> { - chunks: BTreeMap<(i32, i32), TerrainChunk<'r, B>>, + /// Ordered by X then Z. + chunks: Vec>, + /// Each chunk's index in `chunks`: every block access looks one up. + index: ChunkIndex, min_y: i32, height: i32, generation: WorldGenerationContext, @@ -68,6 +71,77 @@ pub struct TerrainRegion<'r, B: TerrainBlockStates> { block_queries: Option, world_seed: Option, } +/// Where each chunk of a region sits in its list: a grid over the chunks' +/// bounding box while it is small (the usual square of neighbours), else a +/// map (chunks spread far apart). +enum ChunkIndex { + Grid { + origin: (i32, i32), + columns: i64, + rows: i64, + /// Row by row from `origin`; `u32::MAX` where no chunk is. + cells: Vec, + }, + Sparse(HashMap<(i32, i32), u32>), +} +impl ChunkIndex { + /// The largest grid, in chunk columns. + const GRID_CELLS: i64 = 1 << 20; + /// `None` when two chunks share a position. + fn new(positions: &[(i32, i32)]) -> Option { + let x0 = positions.iter().map(|p| p.0).min()?; + let z0 = positions.iter().map(|p| p.1).min()?; + let columns = i64::from(positions.iter().map(|p| p.0).max()?) - i64::from(x0) + 1; + let rows = i64::from(positions.iter().map(|p| p.1).max()?) - i64::from(z0) + 1; + if columns * rows > Self::GRID_CELLS { + let mut map = HashMap::with_capacity(positions.len()); + for (i, &p) in positions.iter().enumerate() { + if map.insert(p, i as u32).is_some() { + return None; + } + } + return Some(Self::Sparse(map)); + } + let mut cells = vec![u32::MAX; (columns * rows) as usize]; + for (i, &(x, z)) in positions.iter().enumerate() { + let cell = (i64::from(z) - i64::from(z0)) * columns + (i64::from(x) - i64::from(x0)); + let cell = &mut cells[cell as usize]; + if *cell != u32::MAX { + return None; + } + *cell = i as u32; + } + Some(Self::Grid { + origin: (x0, z0), + columns, + rows, + cells, + }) + } + fn get(&self, x: i32, z: i32) -> Option { + match self { + Self::Grid { + origin, + columns, + rows, + cells, + } => { + let (dx, dz) = ( + i64::from(x) - i64::from(origin.0), + i64::from(z) - i64::from(origin.1), + ); + if !(0..*columns).contains(&dx) || !(0..*rows).contains(&dz) { + return None; + } + match cells[(dz * columns + dx) as usize] { + u32::MAX => None, + i => Some(i as usize), + } + } + Self::Sparse(map) => map.get(&(x, z)).map(|&i| i as usize), + } + } +} impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { pub fn new( chunks: Vec>, @@ -83,15 +157,16 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { }) { return Err(RegionError::InvalidChunks); } - let mut stored = BTreeMap::new(); - for chunk in chunks { - let p = chunk.position(); - if stored.insert((p.x, p.z), chunk).is_some() { - return Err(RegionError::InvalidChunks); - } - } + let mut chunks = chunks; + chunks.sort_by_key(|c| (c.position().x, c.position().z)); + let positions: Vec<(i32, i32)> = chunks + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let index = ChunkIndex::new(&positions).ok_or(RegionError::InvalidChunks)?; Ok(Self { - chunks: stored, + chunks, + index, sea_level: generator.sea_level, game_time: 0, next_tick_order: 0, @@ -114,10 +189,7 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { mut self, bindings: &super::block_feature::FeatureBlockBindings<'r>, ) -> Result { - if !std::ptr::eq( - self.chunks.first_key_value().unwrap().1.registry(), - bindings.registry(), - ) { + if !std::ptr::eq(self.chunks[0].registry(), bindings.registry()) { return Err(RegionError::InvalidBindings); } self.block_queries = Some(RegionBlockQueries { @@ -186,20 +258,25 @@ impl<'r, B: TerrainBlockStates> TerrainRegion<'r, B> { } /// Release the resident chunks, ordered by X then Z; match them by position. pub fn into_chunks(self) -> Vec> { - self.chunks.into_values().collect() + self.chunks } pub fn chunks(&self) -> impl Iterator> { - self.chunks.values() + self.chunks.iter() + } + fn index(&self, x: i32, z: i32) -> Option { + self.index.get(x, z) } pub fn chunk(&self, x: i32, z: i32) -> Result<&TerrainChunk<'r, B>, RegionError> { - self.chunks - .get(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn chunk_mut(&mut self, x: i32, z: i32) -> Result<&mut TerrainChunk<'r, B>, RegionError> { - self.chunks - .get_mut(&(x, z)) - .ok_or(RegionError::MissingChunk([x, z])) + match self.index(x, z) { + Some(i) => Ok(&mut self.chunks[i]), + None => Err(RegionError::MissingChunk([x, z])), + } } pub fn block(&self, [x, y, z]: [i32; 3]) -> Result { Ok(self.chunk(x >> 4, z >> 4)?.block(x, y, z)) @@ -302,12 +379,7 @@ impl PlacementContext for TerrainRegion<'_, B> { block: BlockStateId, delay: i32, ) -> Result<(), PlacementQueryError> { - let registry = self - .chunks - .first_key_value() - .expect("nonempty region") - .1 - .registry(); + let registry = self.chunks[0].registry(); let state = registry .state(block) .ok_or(RegionError::InvalidTickState(block))?; diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index 1284d0054..fc1cd8bcf 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -1129,4 +1129,41 @@ impl PlacementContext for World<'_> { fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result { self.region.height(kind, x, z) } + /// OreFeature's search for a column under its blob, without a trait call + /// per column. Defers to `height` when a heightmap still has to be primed. + fn any_height_at_least( + &mut self, + kind: HeightmapType, + [x0, z0]: [i32; 2], + size: i32, + y: i32, + ) -> Result, PlacementQueryError> { + let (x1, z1) = (x0.wrapping_add(size), z0.wrapping_add(size)); + if size < 0 || x1 < x0 || z1 < z0 { + return Ok(None); + } + for cx in x0 >> 4..=x1 >> 4 { + for cz in z0 >> 4..=z1 >> 4 { + if !self + .region + .chunk(cx, cz) + .is_ok_and(|c| c.heightmap(kind).is_some()) + { + return Ok(None); + } + } + } + for x in x0..=x1 { + for z in z0..=z1 { + let map = self.region.chunk(x >> 4, z >> 4)?.heightmap(kind).unwrap(); + let floor = map + .first_available(x & 15, z & 15) + .map_err(|e| RegionError::from(super::terrain::TerrainError::from(e)))?; + if y <= floor { + return Ok(Some(true)); + } + } + } + Ok(Some(false)) + } } diff --git a/crates/horizon-world/src/worldgen/ore_feature.rs b/crates/horizon-world/src/worldgen/ore_feature.rs index 9d723ae40..d69874d76 100644 --- a/crates/horizon-world/src/worldgen/ore_feature.rs +++ b/crates/horizon-world/src/worldgen/ore_feature.rs @@ -180,6 +180,27 @@ impl OreFeature { let z_start = origin[2].wrapping_sub(spread_ceil).wrapping_sub(max_radius); let size_xz = 2 * (spread_ceil + max_radius); let size_y = 2 * (2 + max_radius); + if let Some(found) = world + .any_height_at_least( + HeightmapType::OceanFloorWg, + [x_start, z_start], + size_xz, + y_start, + ) + .map_err(FeatureExecutionError::Query)? + { + return match found { + true => self.do_place( + world, + random, + [x0, x1, z0, z1, y0, y1], + [x_start, y_start, z_start], + size_xz, + size_y, + ), + false => Ok(false), + }; + } for x in 0..=size_xz { for z in 0..=size_xz { let (px, pz) = (x_start.wrapping_add(x), z_start.wrapping_add(z)); @@ -243,7 +264,8 @@ impl OreFeature { } } } - let mut tested = vec![false; (size_xz as usize) * (size_y as usize) * (size_xz as usize)]; + let tested_len = (size_xz as usize) * (size_y as usize) * (size_xz as usize); + let mut tested = vec![0u64; tested_len.div_ceil(64)]; let mut placed = 0; for [xx, yy, zz, r] in data { if r < 0.0 { @@ -280,16 +302,15 @@ impl OreFeature { * i64::from(size_xz) * i64::from(size_y); // The sphere bounds keep indices inside the native BitSet. - let Some(bit) = usize::try_from(index) - .ok() - .and_then(|index| tested.get_mut(index)) + let Some(index) = usize::try_from(index).ok().filter(|&i| i < tested_len) else { return Err(FeatureExecutionError::WorkLimit); }; - if *bit { + let (word, bit) = (&mut tested[index / 64], 1u64 << (index % 64)); + if *word & bit != 0 { continue; } - *bit = true; + *word |= bit; let p = [x, y, z]; if !world .ensure_can_write(p) diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 96a5df130..654ff849c 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -351,6 +351,18 @@ pub trait PlacementContext { /// World minimum, which can differ from the generator's minimum. fn min_y(&mut self) -> Result; fn height(&mut self, kind: HeightmapType, x: i32, z: i32) -> Result; + /// Whether any column of the square `x..=x + size`, `z..=z + size` has + /// `height(kind)` at least `y`, read faster than column by column; `None` + /// when the world can't (callers then ask `height` for each column). + fn any_height_at_least( + &mut self, + _kind: HeightmapType, + _corner: [i32; 2], + _size: i32, + _y: i32, + ) -> Result, PlacementQueryError> { + Ok(None) + } } impl PlacementContext for WorldGenerationContext { fn max_y(&mut self) -> Result { diff --git a/crates/horizon-world/tests/feature_region.rs b/crates/horizon-world/tests/feature_region.rs index c484393bf..7ff34da6f 100644 --- a/crates/horizon-world/tests/feature_region.rs +++ b/crates/horizon-world/tests/feature_region.rs @@ -385,3 +385,46 @@ fn retained_upgrade_status_allows_old_biome_reads() { } } } +#[test] +fn spread_out_regions_route_like_dense_ones() { + // Chunks too far apart for a grid over their bounding box (fixtures put + // one at the far edge of the world beside the origin's neighbours). + let registry = registry(); + let context = WorldGenerationContext::new(0, 16, 8); + let chunk = + |x, z| TerrainChunk::new(ChunkPos::new(x, z), 0, 16, ®istry, Properties).unwrap(); + for far in [4_194_304, -4_194_304] { + let mut region = TerrainRegion::new( + vec![chunk(0, 0), chunk(far, 0), chunk(1, -1), chunk(-1, 1)], + context, + ) + .unwrap(); + let x = far * 16 + 3; + region + .set_block_worldgen([x, 7, 5], BlockStateId(2)) + .unwrap(); + assert_eq!(region.block([x, 7, 5]).unwrap(), BlockStateId(2)); + assert_eq!(region.block([3, 7, 5]).unwrap(), BlockStateId(0)); + assert_eq!(region.block([16, 7, -1]).unwrap(), BlockStateId(0)); + assert!(matches!( + region.block([x + 16, 7, 5]), + Err(RegionError::MissingChunk([_, 0])) + )); + assert!(matches!( + region.block([0, 7, 16]), + Err(RegionError::MissingChunk([0, 1])) + )); + let order: Vec<_> = region + .into_chunks() + .iter() + .map(|c| (c.position().x, c.position().z)) + .collect(); + let mut sorted = order.clone(); + sorted.sort(); + assert_eq!(order, sorted, "into_chunks is ordered by X then Z"); + // A position twice is refused either way. + assert!( + TerrainRegion::new(vec![chunk(0, 0), chunk(far, 0), chunk(far, 0)], context).is_err() + ); + } +}