From a919e4405020826d86f4881a09f64041c20e1849 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 11 Oct 2026 17:35:55 +0200 Subject: [PATCH] Run /locate biome and poi and /place feature, jigsaw and structure as vanilla /locate biome samples the biome source like BiomeSource.findClosestBiome3d, /locate poi scans loaded chunks for PoiTypes block states within 256 blocks, /place feature places the configured feature with the level random, /place jigsaw assembles pieces with JigsawPlacement.addPieces and places them into the level, and unknown structures or pools report vanilla's errors. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/commands.rs | 196 ++++++++++++++++-- .../horizon-client/src/game/commands/place.rs | 131 +++++++++++- crates/horizon-client/src/vanillagen.rs | 19 ++ crates/horizon-world/src/level/bonemeal.rs | 12 ++ crates/horizon-world/src/level/growth.rs | 53 +++++ .../horizon-world/src/worldgen/generator.rs | 177 ++++++++++++++++ 6 files changed, 556 insertions(+), 32 deletions(-) diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 7ac127990..1ffe7a496 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -601,6 +601,9 @@ impl Game<'_> { id if id.starts_with("test.") => self.cmd_test(id, ctx), "compute" => self.cmd_compute(ctx), "place" => self.cmd_place(ctx), + "place.feature" | "place.jigsaw" | "place.structure" => { + self.cmd_place_generated(id, ctx) + } "recipe.give" | "recipe.take" => self.cmd_recipe(id, ctx), "damage" => self.cmd_damage(ctx), "rotate" => self.cmd_rotate(ctx), @@ -645,6 +648,7 @@ impl Game<'_> { self.cmd_scoreboard(id, ctx) } "locate.structure" | "locate.biome" => self.cmd_locate(id, ctx), + "locate.poi" => self.cmd_locate_poi(ctx), "warden_spawn_tracker.clear" | "warden_spawn_tracker.set" => { let level = Self::int(ctx, "warning_level"); self.cmd_warden_spawn_tracker(level); @@ -2243,35 +2247,179 @@ impl Game<'_> { )); Ok(removed) } + /// `PoiTypes`: the point of interest type of a block state. + fn poi_type(&self, state: horizon_world::registry::BlockStateId) -> Option<&'static str> { + let s = self.res.assets.registry.state(state)?; + let name = s.name.strip_prefix("minecraft:")?; + Some(match name { + "blast_furnace" => "minecraft:armorer", + "smoker" => "minecraft:butcher", + "cartography_table" => "minecraft:cartographer", + "brewing_stand" => "minecraft:cleric", + "composter" => "minecraft:farmer", + "barrel" => "minecraft:fisherman", + "fletching_table" => "minecraft:fletcher", + "cauldron" | "lava_cauldron" | "water_cauldron" | "powder_snow_cauldron" => { + "minecraft:leatherworker" + } + "lectern" => "minecraft:librarian", + "stonecutter" => "minecraft:mason", + "loom" => "minecraft:shepherd", + "smithing_table" => "minecraft:toolsmith", + "grindstone" => "minecraft:weaponsmith", + "bell" => "minecraft:meeting", + "beehive" => "minecraft:beehive", + "bee_nest" => "minecraft:bee_nest", + "nether_portal" => "minecraft:nether_portal", + "lodestone" => "minecraft:lodestone", + "test_instance_block" => "minecraft:test_instance", + n if n.ends_with("_bed") => { + if s.properties.get("part").map(String::as_str) != Some("head") { + return None; + } + "minecraft:home" + } + n if n.ends_with("lightning_rod") => "minecraft:lightning_rod", + _ => return None, + }) + } + /// `LocateCommand.locatePoi`: `PoiManager.findClosestWithType` within + /// 256 blocks of the source, over the loaded chunks. + fn cmd_locate_poi(&mut self, ctx: &Context) -> R { + let Some(Arg::Resource(poi)) = ctx.get("poi").cloned() else { + return Ok(0); + }; + let wanted: Vec = match poi.strip_prefix('#') { + Some(tag) => self.tag_entries("point_of_interest_type", tag), + None => vec![poi.clone()], + }; + let from = self.source_position().map(|v| v.floor() as i32); + const RANGE: i32 = 256; + let mut cache: std::collections::HashMap> = + std::collections::HashMap::new(); + let mut best: Option<(i64, [i32; 3], &'static str)> = None; + let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4); + let (cx1, cz1) = ((from[0] + RANGE) >> 4, (from[2] + RANGE) >> 4); + for cx in cx0..=cx1 { + for cz in cz0..=cz1 { + let Some(chunk) = self.world.chunks.get(&(cx, cz)) else { + continue; + }; + for (i, section) in chunk.sections.iter().enumerate() { + let mut wanted_state = |v: u32| { + let state = v as u16; + cache + .entry(state) + .or_insert_with(|| { + self.poi_type(horizon_world::registry::BlockStateId( + u32::from(state), + )) + .filter(|t| wanted.iter().any(|w| w == t)) + }) + .is_some() + }; + if !section.blocks.maybe_has(&mut wanted_state) { + continue; + } + let base_y = horizon_client::chunk::MIN_Y + 16 * i as i32; + for j in 0..4096 { + let state = section.get(j); + let Some(kind) = cache.get(&state).copied().flatten() else { + continue; + }; + let p = [ + cx * 16 + (j & 15) as i32, + base_y + (j >> 8) as i32, + cz * 16 + ((j >> 4) & 15) as i32, + ]; + let d = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| i64::from(d) * i64::from(d)) + .iter() + .sum::(); + if d <= i64::from(RANGE * RANGE) && best.is_none_or(|(b, _, _)| d < b) { + best = Some((d, p, kind)); + } + } + } + } + } + let Some((_, p, kind)) = best else { + return Err(CommandError::new(Text::tr( + "commands.locate.poi.not_found", + &[&poi], + ))); + }; + let coords = Text::translate( + "chat.coordinates", + &[ + Text::literal(p[0].to_string()), + Text::literal("~"), + Text::literal(p[2].to_string()), + ], + ); + let link = Text::literal("[") + .append(coords) + .append("]") + .with_style(&Style { + color: Some(text::GREEN), + suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])), + ..Style::default() + }); + let (dx, dz) = (p[0] - from[0], p[2] - from[2]); + let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32; + let shown = if poi.starts_with('#') { + format!("{poi} ({kind})") + } else { + poi + }; + self.feedback(Text::translate( + "commands.locate.poi.success", + &[ + Text::literal(shown), + link, + Text::literal(distance.to_string()), + ], + )); + Ok(distance) + } fn cmd_locate(&mut self, id: &str, ctx: &Context) -> R { let origin = self.source_position(); if id == "locate.biome" { let Some(Arg::Resource(biome)) = ctx.get("biome").cloned() else { return Ok(0); }; - // Search loaded chunks around the player (BiomeSource.findClosestBiome3d - // samples a 6400-block radius; Horizon searches what is generated). - let (px, pz) = (origin[0].floor() as i32, origin[2].floor() as i32); - let mut best: Option<([i32; 3], f64)> = None; - for (&(cx, cz), chunk) in &self.world.chunks { - for (dx, dz) in [(0, 0), (8, 8)] { - let (x, z) = (cx * 16 + dx, cz * 16 + dz); - let y = origin[1].floor() as i32; - let b = self.res.biomes.get(chunk.biome(x, y, z)); - if b.name == biome { - let d = f64::from((x - px).pow(2) + (z - pz).pow(2)); - if best.is_none_or(|(_, bd)| d < bd) { - best = Some(([x, y, z], d)); - } - } - } - } - let Some((p, d2)) = best else { + // LocateCommand.locateBiome: BiomeSource.findClosestBiome3d with + // a 6400-block radius, 32-block columns and 64-block layers. + let from = origin.map(|v| v.floor() as i32); + let allowed = |name: &str| self.biome_matches(&biome, name); + let search = horizon_world::worldgen::generator::BiomeSearch { + allowed: &allowed, + origin: from, + radius: 6400, + horizontal: 32, + vertical: 64, + min_y: horizon_client::chunk::MIN_Y, + max_y: horizon_client::chunk::MIN_Y + horizon_client::chunk::HEIGHT - 1, + }; + let found = self + .end + .locator() + .and_then(|t| t.find_closest_biome(&search)); + let Some((name, p)) = found else { return Err(CommandError::new(Text::tr( "commands.locate.biome.not_found", &[&biome], ))); }; + let d2 = [p[0] - from[0], p[1] - from[1], p[2] - from[2]] + .map(|d| f64::from(d) * f64::from(d)) + .iter() + .sum::(); + let shown = if biome.starts_with('#') { + format!("{biome} ({name})") + } else { + biome.clone() + }; let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]); let link = Text::literal("[") .append(coords) @@ -2281,11 +2429,11 @@ impl Game<'_> { suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])), ..Style::default() }); - let distance = d2.sqrt().floor() as i32; - self.system_message(Text::translate( + let distance = (d2 as f32).sqrt().floor() as i32; + self.feedback(Text::translate( "commands.locate.biome.success", &[ - Text::literal(biome), + Text::literal(shown), link, Text::literal(distance.to_string()), ], @@ -2343,6 +2491,10 @@ impl Game<'_> { } /// The structures of a `worldgen/structure` tag, nested tags expanded. pub(super) fn structure_tag(&self, tag: &str) -> Vec { + self.tag_entries("worldgen/structure", tag) + } + /// The entries of a data pack tag of `registry`, nested tags expanded. + pub(super) fn tag_entries(&self, registry: &str, tag: &str) -> Vec { let mut out = Vec::new(); let mut pending = vec![tag.to_owned()]; let mut seen = std::collections::HashSet::new(); @@ -2354,7 +2506,7 @@ impl Game<'_> { let file = self .options .resources - .join(format!("data/{ns}/tags/worldgen/structure/{path}.json")); + .join(format!("data/{ns}/tags/{registry}/{path}.json")); let Ok(v) = std::fs::read(file) .map_err(|_| ()) .and_then(|b| serde_json::from_slice::(&b).map_err(|_| ())) diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index a51dea3f9..2d9140782 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -70,20 +70,131 @@ impl Game<'_> { } None } + /// `BlockPosArgument.getLoadedBlockPos(pos)`, or the source's block. + fn place_pos(&self, ctx: &Context, name: &str) -> R<[i32; 3]> { + if ctx.get(name).is_some() { + return self.block_pos_arg(ctx, name); + } + Ok(self.source_position().map(|v| v.floor() as i32)) + } + /// `PlaceCommand.checkLoaded`: every chunk of the inclusive range. + fn place_check_loaded(&self, min: [i32; 2], max: [i32; 2]) -> R<()> { + let elsewhere = self.command_source.is_some_and(|s| s.elsewhere); + for cx in min[0]..=max[0] { + for cz in min[1]..=max[1] { + if elsewhere || !self.world.chunks.contains_key(&(cx, cz)) { + return Err(err("argument.pos.unloaded", &[])); + } + } + } + Ok(()) + } + /// `PlaceCommand.placeFeature`, `placeJigsaw` and `placeStructure`. + pub(super) fn cmd_place_generated(&mut self, id: &str, ctx: &Context) -> R { + match id { + "place.feature" => { + let raw = match ctx.get("feature") { + Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(), + _ => return Ok(0), + }; + let pos = self.place_pos(ctx, "pos")?; + let (cx, cz) = (pos[0] >> 4, pos[2] >> 4); + self.place_check_loaded([cx - 1, cz - 1], [cx + 1, cz + 1])?; + // Inline features are not built by the live feature registry. + if raw.starts_with('{') { + return Err(err("command.failed", &[])); + } + let name = if raw.contains(':') { + raw + } else { + format!("minecraft:{raw}") + }; + let at = horizon_core::position::BlockPos::new(pos[0], pos[1], pos[2]); + let placed = self + .with_level(|b, level, ticks| b.place_feature(level, ticks, &name, at)) + .ok_or_else(|| err("command.failed", &[]))?; + self.process_level_events() + .map_err(|_| err("command.failed", &[]))?; + if !placed { + return Err(err("commands.place.feature.failed", &[])); + } + self.feedback(Text::translate( + "commands.place.feature.success", + &[Text::literal(name), num(pos[0]), num(pos[1]), num(pos[2])], + )); + Ok(1) + } + "place.jigsaw" => { + let Some(Arg::Resource(pool)) = ctx.get("pool").cloned() else { + return Ok(0); + }; + if !self + .ui + .registries + .ids("minecraft:worldgen/template_pool") + .contains(&pool) + { + return Err(err("commands.place.jigsaw.invalid", &[&pool])); + } + let target = match ctx.get("target") { + Some(Arg::Resource(s) | Arg::Str(s)) => s.clone(), + _ => return Ok(0), + }; + let max_depth = match ctx.get("max_depth") { + Some(Arg::Int(n)) => *n, + _ => return Ok(0), + }; + let pos = self.place_pos(ctx, "position")?; + self.place_check_loaded([pos[0] >> 4, pos[2] >> 4], [pos[0] >> 4, pos[2] >> 4])?; + let terrain = self + .end + .locator() + .ok_or_else(|| err("command.failed", &[]))?; + let query = horizon_world::worldgen::generator::JigsawQuery { + pool: &pool, + target: &target, + max_depth, + position: pos, + }; + let placed = self.with_level(|b, level, ticks| { + b.place_jigsaw(level, ticks, pos, |random| { + terrain.jigsaw_pieces(&query, random) + }) + }); + self.process_level_events() + .map_err(|_| err("command.failed", &[]))?; + if !placed { + return Err(err("commands.place.jigsaw.failed", &[])); + } + self.feedback(Text::translate( + "commands.place.jigsaw.success", + &[num(pos[0]), num(pos[1]), num(pos[2])], + )); + Ok(1) + } + _ => { + let Some(Arg::Resource(structure)) = ctx.get("structure").cloned() else { + return Ok(0); + }; + if !self + .ui + .registries + .ids("minecraft:worldgen/structure") + .contains(&structure) + { + return Err(err("commands.place.structure.invalid", &[&structure])); + } + self.place_pos(ctx, "pos")?; + // Structure.generate is not wired to the live level. + Err(err("command.failed", &[])) + } + } + } pub(super) fn cmd_place(&mut self, ctx: &Context) -> R { let Some(Arg::Resource(id)) = ctx.get("template").cloned() else { return Ok(0); }; - let pos = if ctx.get("pos").is_some() { - self.block_pos_arg(ctx, "pos")? - } else { - let p = self.source_position(); - [ - p[0].floor() as i32, - p[1].floor() as i32, - p[2].floor() as i32, - ] - }; + let pos = self.place_pos(ctx, "pos")?; let rotation = match ctx.get("rotation") { Some(Arg::Str(r)) => Rotation::from_name(r).unwrap_or(Rotation::None), _ => Rotation::None, diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index c889c5169..6b4b7c769 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -91,6 +91,25 @@ impl VanillaTerrain { ) -> Option<(String, [i32; 3])> { self.generator.worker().locate(names, from, radius) } + /// `/locate biome`: `BiomeSource.findClosestBiome3d`. + pub fn find_closest_biome( + &self, + search: &horizon_world::worldgen::generator::BiomeSearch<'_>, + ) -> Option<(String, [i32; 3])> { + let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner()); + let worker = worker.get_or_insert_with(|| self.generator.worker()); + worker.find_closest_biome(search) + } + /// `/place jigsaw`: `JigsawPlacement.addPieces` drawing from `random`. + pub fn jigsaw_pieces( + &self, + query: &horizon_world::worldgen::generator::JigsawQuery<'_>, + random: &mut horizon_core::random::LegacyRandom, + ) -> Option { + let mut worker = self.query.lock().unwrap_or_else(|e| e.into_inner()); + let worker = worker.get_or_insert_with(|| self.generator.worker()); + worker.jigsaw_pieces(query, random) + } /// Concentric ring positions of a structure set (strongholds), once known. pub fn ring_positions(&self, set: &str) -> Option> { self.generator.ring_positions(set) diff --git a/crates/horizon-world/src/level/bonemeal.rs b/crates/horizon-world/src/level/bonemeal.rs index cf930109a..274512138 100644 --- a/crates/horizon-world/src/level/bonemeal.rs +++ b/crates/horizon-world/src/level/bonemeal.rs @@ -105,6 +105,18 @@ fn next_int_between(random: &mut R, min: i32, max: i32) -> i32 } impl Behaviours { + /// `/place feature`: `ConfiguredFeature.place` at `pos` with the level + /// random. `None` when the feature is unknown or cannot run. + pub fn place_feature( + &self, + level: &mut L, + ticks: &mut Ticks, + name: &str, + pos: BlockPos, + ) -> Option { + self.live_features()?.configured(name)?; + Some(self.sim(level, ticks).place_configured_feature(name, pos)) + } /// `BoneMealItem.useOn` for a player clicking `pos` on `face`. Returns /// whether bone meal was used (the caller then shrinks the stack unless /// the player is in creative mode). Reports level event 1505 (growth diff --git a/crates/horizon-world/src/level/growth.rs b/crates/horizon-world/src/level/growth.rs index f1110943d..14950d495 100644 --- a/crates/horizon-world/src/level/growth.rs +++ b/crates/horizon-world/src/level/growth.rs @@ -21,6 +21,59 @@ impl Behaviours { pub fn live_features(&self) -> Option<&Arc> { self.growth.features.get() } + /// `JigsawPlacement.generateJigsaw`: `assemble` builds the pieces from + /// the level random, then each piece is placed into the level with an + /// unbounded box and `reference` as the origin. Returns whether pieces + /// were assembled. + pub fn place_jigsaw( + &self, + level: &mut L, + ticks: &mut super::Ticks, + reference: [i32; 3], + assemble: impl FnOnce( + &mut horizon_core::random::LegacyRandom, + ) -> Option, + ) -> bool { + let Some(features) = self.live_features() else { + return false; + }; + let mut sim = self.sim(level, ticks); + let mut random = sim.random().clone(); + let Some(jigsaw) = assemble(&mut random) else { + *sim.random() = random; + return false; + }; + { + let mut world = LevelFeatureWorld { + sim: &mut sim, + features, + }; + let unbounded = crate::worldgen::structure::BoundingBox::new( + [i32::MIN; 3], + [i32::MAX; 3], + ); + for piece in &jigsaw.pieces { + let mut place_feature = |w: &mut LevelFeatureWorld<'_, '_, L>, + r: &mut horizon_core::random::LegacyRandom, + name: &str, + p: [i32; 3]| { + Ok(features.place_placed(name, w, r, p)) + }; + if let Err(e) = piece.place( + &mut world, + &jigsaw.resources, + &mut random, + unbounded, + reference, + &mut place_feature, + ) { + eprintln!("Horizon: placing a jigsaw piece failed: {e}"); + } + } + } + *sim.random() = random; + true + } } /// The four (state, position) pairs of a 2x2 sapling square. diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7a264020f..81000b1d1 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1370,6 +1370,17 @@ trait SeededPipeline: Send + Sync { from: [i32; 3], radius: i32, ) -> Option<(String, [i32; 3])>; + fn find_closest_biome( + &self, + worker: &mut WorkerState, + search: &BiomeSearch<'_>, + ) -> Option<(String, [i32; 3])>; + fn jigsaw_pieces( + &self, + worker: &mut WorkerState, + query: &JigsawQuery<'_>, + random: &mut horizon_core::random::LegacyRandom, + ) -> Option; } impl SeededPipeline for Pipeline where @@ -1470,6 +1481,159 @@ where radius, ) } + fn find_closest_biome( + &self, + worker: &mut WorkerState, + search: &BiomeSearch<'_>, + ) -> Option<(String, [i32; 3])> { + // BiomeSource.findClosestBiome3d. + let candidates: BTreeSet<&str> = self + .source + .possible_biomes() + .into_iter() + .filter(|name| (search.allowed)(name)) + .collect(); + if candidates.is_empty() { + return None; + } + let mut resolver = self.source.resolver( + &self.climate, + self.router.get(RouterField::Erosion).as_ref(), + ); + let ys = out_from_origin( + search.origin[1], + search.min_y + 1, + search.max_y + 1, + search.vertical, + ); + let radius = search.radius.div_euclid(search.horizontal); + for [sx, sz] in spiral_around(radius) { + let x = search.origin[0].wrapping_add(sx.wrapping_mul(search.horizontal)); + let z = search.origin[2].wrapping_add(sz.wrapping_mul(search.horizontal)); + for &y in &ys { + let quart = [x >> 2, y >> 2, z >> 2]; + let Ok(name) = resolver.sample(&mut worker.carver_context, quart) else { + continue; + }; + if candidates.contains(name) { + return Some((name.to_owned(), [x, y, z])); + } + } + } + None + } + fn jigsaw_pieces( + &self, + worker: &mut WorkerState, + query: &JigsawQuery<'_>, + random: &mut horizon_core::random::LegacyRandom, + ) -> Option { + // JigsawPlacement.generateJigsaw: addPieces with no heightmap + // projection, MaxDistance(128), no aliases, no padding and + // waterlogging applied. + let structures = self.structures.as_ref()?; + let aliases = BTreeMap::new(); + let config = super::structure::jigsaw::JigsawConfig { + start_pool: query.pool, + start_jigsaw: Some(query.target), + max_depth: query.max_depth, + use_expansion_hack: false, + project_to: None, + max_distance: [128, 128], + aliases: &aliases, + padding: [0, 0], + waterlogging: true, + }; + let (_, pieces) = super::structure::jigsaw::assemble( + &config, + &mut StructureQueries { + pipeline: self, + worker, + valid: BTreeSet::new(), + }, + &structures.registry.pools, + &structures.resources, + &structures.bindings, + random, + query.position, + )?; + Some(JigsawPieces { + pieces, + resources: structures.resources.clone(), + }) + } +} + +/// A `JigsawPlacement.generateJigsaw` request (`/place jigsaw`). +pub struct JigsawQuery<'a> { + pub pool: &'a str, + pub target: &'a str, + pub max_depth: i32, + pub position: [i32; 3], +} +/// The assembled pieces of a jigsaw and the templates they place. +pub struct JigsawPieces { + pub pieces: Vec, + pub resources: Arc, +} + +/// A `findClosestBiome3d` query. +pub struct BiomeSearch<'a> { + pub allowed: &'a dyn Fn(&str) -> bool, + pub origin: [i32; 3], + pub radius: i32, + pub horizontal: i32, + pub vertical: i32, + /// `level.getMinY()` and `level.getMaxY()`. + pub min_y: i32, + pub max_y: i32, +} + +/// `Mth.outFromOrigin(origin, lower, upper, step)`. +pub fn out_from_origin(origin: i32, lower: i32, upper: i32, step: i32) -> Vec { + let center = origin.clamp(lower, upper); + let mut out = Vec::new(); + let mut cursor = center; + loop { + let distance = (center - cursor).abs(); + if !(center - distance >= lower || center + distance <= upper) { + return out; + } + out.push(cursor); + let negative = cursor <= center; + let can_move_positive = center + distance + step <= upper; + let mut next = center + distance + step; + if !negative || !can_move_positive { + let attempt = center - distance - if negative { step } else { 0 }; + if attempt >= lower { + next = attempt; + } + } + cursor = next; + } +} + +/// `BlockPos.spiralAround(ZERO, radius, EAST, SOUTH)` as (x, z) offsets. +pub fn spiral_around(radius: i32) -> impl Iterator { + const DIRS: [[i32; 2]; 4] = [[1, 0], [0, 1], [-1, 0], [0, -1]]; + let legs = 4 * radius; + let (mut leg, mut leg_size, mut leg_index) = (-1i32, 0i32, 0i32); + let mut last = [0, 1]; + std::iter::from_fn(move || { + let d = DIRS[((leg + 4) % 4) as usize]; + let cursor = [last[0] + d[0], last[1] + d[1]]; + last = cursor; + if leg_index >= leg_size { + if leg >= legs { + return None; + } + leg += 1; + leg_index = 0; + leg_size = leg / 2 + 1; + } + leg_index += 1; + Some(cursor) + }) } /// Counters from one FEATURES pass. @@ -1622,6 +1786,19 @@ impl GeneratorWorker { ) -> Option<(String, [i32; 3])> { self.pipeline.locate(&mut self.state, names, from, radius) } + /// `BiomeSource.findClosestBiome3d`: the first sampled position whose + /// noise biome passes `allowed`, spiralling out from the origin. + pub fn find_closest_biome(&mut self, search: &BiomeSearch<'_>) -> Option<(String, [i32; 3])> { + self.pipeline.find_closest_biome(&mut self.state, search) + } + /// `JigsawPlacement.addPieces` for `/place jigsaw`, drawing from `random`. + pub fn jigsaw_pieces( + &mut self, + query: &JigsawQuery<'_>, + random: &mut horizon_core::random::LegacyRandom, + ) -> Option { + self.pipeline.jigsaw_pieces(&mut self.state, query, random) + } /// STRUCTURE_STARTS: the structure starts owned by a chunk (cached). pub fn structure_starts( &mut self,