From 0a8fd9a78f76c4f113ebe20fdfb3e080b917529d Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sat, 10 Oct 2026 22:24:03 +0200 Subject: [PATCH] WIP: unfinished loot-spawn parity work, stopped for the night Uncommitted changes the agent had in progress when it was stopped; may not build or pass its harnesses yet. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/biome.rs | 26 +-- crates/horizon-client/src/game.rs | 4 - crates/horizon-client/src/game/creatures.rs | 60 ++---- crates/horizon-client/src/game/structures.rs | 93 ++------- crates/horizon-client/src/mobs.rs | 1 + .../src/mobs/spawn_selection.rs | 193 ++++++++++++++++++ 6 files changed, 234 insertions(+), 143 deletions(-) create mode 100644 crates/horizon-client/src/mobs/spawn_selection.rs diff --git a/crates/horizon-client/src/biome.rs b/crates/horizon-client/src/biome.rs index 1be7a4ce9..338bec1f9 100644 --- a/crates/horizon-client/src/biome.rs +++ b/crates/horizon-client/src/biome.rs @@ -17,6 +17,8 @@ pub struct SpawnEntry { pub weight: u32, pub min: u32, pub max: u32, + /// A `ConstantInt` count (sampling draws nothing). + pub constant: bool, } #[derive(Clone, Debug)] pub struct BiomeInfo { @@ -105,29 +107,7 @@ impl Biomes { let mut spawns: HashMap> = HashMap::new(); let categories = &attributes["minecraft:gameplay/natural_mob_spawns"]["argument"]["spawns_by_category"]; for (category, entries) in categories.as_object().into_iter().flatten() { - let list = entries - .as_array() - .into_iter() - .flatten() - .filter_map(|e| { - let (min, max) = match &e["count"] { - Value::Number(n) => { - let n = n.as_u64().unwrap_or(1) as u32; - (n, n) - } - c => ( - c["min_inclusive"].as_u64().unwrap_or(1) as u32, - c["max_inclusive"].as_u64().unwrap_or(1) as u32, - ), - }; - Some(SpawnEntry { - entity: e["type"].as_str()?.to_owned(), - weight: e["weight"].as_u64().unwrap_or(1) as u32, - min, - max, - }) - }) - .collect(); + let list = crate::mobs::spawn_selection::parse_entries(entries); spawns.insert(category.clone(), list); } list.push(BiomeInfo { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b81c403fd..911ebfa04 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -752,9 +752,6 @@ struct Game<'a> { adv_ui: advancements_screen::AdvUi, camera_type: perspective::CameraType, fangs: fangs::FangState, - /// Structure `spawn_overrides`: structure -> category -> (piece only, spawns). - spawn_overrides: - HashMap)>>, /// The local player as a model (third person, the inventory). player_model: Option, } @@ -8628,7 +8625,6 @@ pub fn run() -> Result<()> { adv_ui: Default::default(), camera_type: Default::default(), fangs: Default::default(), - spawn_overrides: HashMap::new(), player_model: None, }; game.ui.vanilla_root = vanilla_root; diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 8441baaf1..95e4590e4 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -3,6 +3,7 @@ //! breeding, conversions, drops), projectiles, player interactions //! (feeding, shearing, milking, spawn eggs, throwing) and rendering. use super::{Dim, Game, view_vector}; +use horizon_client::mobs::spawn_selection; use horizon_client::{ Result, blocks::Fluid, @@ -355,23 +356,6 @@ impl Game<'_> { } horizon_client::chunk::MIN_Y } - fn weighted_entry( - &mut self, - entries: &[horizon_client::biome::SpawnEntry], - ) -> Option { - let total: u32 = entries.iter().map(|e| e.weight).sum(); - if total == 0 { - return None; - } - let mut r = self.world.random.next_int_bound(total as i32).ok()? as u32; - for e in entries { - if r < e.weight { - return Some(e.clone()); - } - r -= e.weight; - } - None - } /// NaturalSpawner.spawnMobsForChunkGeneration (creature packs at generation). pub(super) fn spawn_generation_creatures(&mut self, cx: i32, cz: i32) { let Some(chunk) = self.world.chunks.get(&(cx, cz)).cloned() else { @@ -383,15 +367,11 @@ impl Game<'_> { }; let (xo, zo) = (cx * 16, cz * 16); while self.world.random.next_float() < biome.creature_probability { - let Some(entry) = self.weighted_entry(&entries) else { + let Some(entry) = spawn_selection::weighted_pick(&entries, &mut self.world.random) + else { return; }; - let count = entry.min - + self - .world - .random - .next_int_bound((entry.max - entry.min + 1) as i32) - .unwrap_or(0) as u32; + let count = spawn_selection::sample_count(&entry, &mut self.world.random); let mut x = xo + self.world.random.next_int_bound(16).unwrap_or(0); let mut z = zo + self.world.random.next_int_bound(16).unwrap_or(0); let (sx, sz) = (x, z); @@ -592,26 +572,22 @@ impl Game<'_> { break; }; let biome = self.res.biomes.get(chunk.biome(x, y, z)).clone(); - let list = match self.structure_spawns(category, [x, y, z]) { - Some(list) => list, - None => match biome.spawns.get(category).cloned() { - Some(list) => list, - None => break, - }, - }; - let list: Vec<_> = list - .into_iter() - .filter(|e| self.res.mob_types.contains_key(&e.entity)) - .collect(); - let Some(e) = self.weighted_entry(&list) else { + let list = self.spawn_list(category, [x, y, z], &biome.spawns); + let reduced = self + .res + .mob_data + .biome_tags + .get("minecraft:reduced_water_ambient_spawns") + .is_some_and(|t| t.contains(&biome.name)); + let Some(e) = spawn_selection::random_spawn_mob_at( + &list, + category, + reduced, + &mut self.world.random, + ) else { break; }; - group = e.min - + self - .world - .random - .next_int_bound((e.max - e.min + 1) as i32) - .unwrap_or(0) as u32; + group = spawn_selection::sample_count(&e, &mut self.world.random); entry = Some(e); } let e = entry.clone().unwrap_or_else(|| unreachable!()); diff --git a/crates/horizon-client/src/game/structures.rs b/crates/horizon-client/src/game/structures.rs index 116f2100e..1b2199d4d 100644 --- a/crates/horizon-client/src/game/structures.rs +++ b/crates/horizon-client/src/game/structures.rs @@ -39,83 +39,28 @@ impl Game<'_> { .map(|(n, _)| n) .collect() } - /// `ChunkGenerator.getMobsAt` / `NaturalSpawner.mobsAt`: a structure's - /// `spawn_overrides` for the category replace the biome's list where its - /// box (or piece) holds `pos`; fortress spawns on nether bricks. - pub(super) fn structure_spawns( - &mut self, + /// `NaturalSpawner.mobsAt`: the fortress bounds on nether bricks, the + /// structure `spawn_overrides` whose box (or piece) holds `pos`, else the + /// biome's list. + pub(super) fn spawn_list( + &self, category: &str, pos: [i32; 3], - ) -> Option> { - let reaching = self.structures_reaching(pos); - if reaching.is_empty() { - return None; - } + biome: &std::collections::HashMap>, + ) -> Vec { + use horizon_client::mobs::spawn_selection::{StructureAt, StructureSpawns, mobs_at}; + let structures: Vec = self + .structures_reaching(pos) + .into_iter() + .map(|(id, in_piece)| StructureAt { + id, + in_piece, + in_bounds: true, + }) + .collect(); let below = self.world.block(pos[0], pos[1] - 1, pos[2]); let bricks = &*self.res.facts.get(below).name == "minecraft:nether_bricks"; - for (id, piece) in &reaching { - let Some(o) = self.spawn_override(id, category) else { - continue; - }; - if !o.0 || *piece { - return Some(o.1); - } - } - if category == "monster" - && bricks - && reaching.iter().any(|(n, _)| n == "minecraft:fortress") - { - return self - .spawn_override("minecraft:fortress", "monster") - .map(|o| o.1); - } - None - } - /// A structure's override for a category: (piece-only, spawns). - fn spawn_override( - &mut self, - structure: &str, - category: &str, - ) -> Option<(bool, Vec)> { - if !self.spawn_overrides.contains_key(structure) { - let (ns, path) = structure - .split_once(':') - .unwrap_or(("minecraft", structure)); - let file = self - .options - .resources - .join(format!("data/{ns}/worldgen/structure/{path}.json")); - let v: serde_json::Value = std::fs::read(file) - .ok() - .and_then(|b| serde_json::from_slice(&b).ok()) - .unwrap_or_default(); - let mut map = std::collections::HashMap::new(); - for (cat, o) in v["spawn_overrides"].as_object().into_iter().flatten() { - let piece = o["bounding_box"].as_str() == Some("piece"); - let spawns = o["spawns"] - .as_array() - .into_iter() - .flatten() - .map(|e| { - let count = &e["count"]; - horizon_client::biome::SpawnEntry { - entity: e["type"].as_str().unwrap_or_default().to_owned(), - weight: e["weight"].as_u64().unwrap_or(1) as u32, - min: count["min_inclusive"] - .as_u64() - .or_else(|| e["minCount"].as_u64()) - .unwrap_or(1) as u32, - max: count["max_inclusive"] - .as_u64() - .or_else(|| e["maxCount"].as_u64()) - .unwrap_or(1) as u32, - } - }) - .collect(); - map.insert(cat.clone(), (piece, spawns)); - } - self.spawn_overrides.insert(structure.to_owned(), map); - } - self.spawn_overrides.get(structure)?.get(category).cloned() + let spawns = StructureSpawns::shared(&self.options.resources); + mobs_at(spawns, biome, category, &structures, bricks) } } diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index b45da996c..1bc36183b 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -48,6 +48,7 @@ pub mod shulker; pub mod sniffer; pub mod spawning; pub mod spawn_rules; +pub mod spawn_selection; pub mod species; pub mod sulfur_cube; pub mod tame; diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs new file mode 100644 index 000000000..fba1cb8fa --- /dev/null +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -0,0 +1,193 @@ +//! `NaturalSpawner.getRandomSpawnMobAt` and `mobsAt`: which spawn list a +//! position uses (the nether fortress bounds, then structure spawn overrides +//! by piece or bounding box, then the biome's natural mob spawns), the +//! reduced water ambient odds, the weighted pick and the group size sample. +use crate::biome::SpawnEntry; +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{collections::HashMap, fs, path::Path}; + +/// A `natural_mob_spawns` / `spawn_overrides` entry list. +pub fn parse_entries(list: &Value) -> Vec { + list.as_array() + .into_iter() + .flatten() + .filter_map(|e| { + let count = &e["count"]; + let (min, max, constant) = match count { + Value::Number(n) => { + let n = n.as_u64().unwrap_or(1) as u32; + (n, n, true) + } + c if c["type"].as_str() == Some("minecraft:constant") => { + let n = c["value"].as_u64().unwrap_or(1) as u32; + (n, n, true) + } + c => ( + c["min_inclusive"].as_u64().unwrap_or(1) as u32, + c["max_inclusive"].as_u64().unwrap_or(1) as u32, + false, + ), + }; + Some(SpawnEntry { + entity: e["type"].as_str()?.to_owned(), + weight: e["weight"].as_u64().unwrap_or(1) as u32, + min, + max, + constant, + }) + }) + .collect() +} + +/// A structure's spawn override for one category. +#[derive(Clone, Debug)] +pub struct Override { + /// `bounding_box: piece` (else the whole structure's box). + pub piece: bool, + pub spawns: Vec, +} +/// Every structure's `spawn_overrides`, by structure id then category. +#[derive(Clone, Debug, Default)] +pub struct StructureSpawns { + pub overrides: HashMap>, +} +impl StructureSpawns { + /// The overrides of the resource root first asked for, loaded once. + pub fn shared(root: &Path) -> &'static Self { + static SHARED: std::sync::OnceLock = std::sync::OnceLock::new(); + SHARED.get_or_init(|| Self::load(root)) + } + pub fn load(root: &Path) -> Self { + let mut overrides = HashMap::new(); + let dir = root.join("data/minecraft/worldgen/structure"); + for entry in fs::read_dir(dir).into_iter().flatten().flatten() { + let path = entry.path(); + let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else { + continue; + }; + let Some(v) = fs::read(&path) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + else { + continue; + }; + let map: HashMap = v["spawn_overrides"] + .as_object() + .into_iter() + .flatten() + .map(|(category, o)| { + ( + category.clone(), + Override { + piece: o["bounding_box"].as_str() == Some("piece"), + spawns: parse_entries(&o["spawns"]), + }, + ) + }) + .collect(); + if !map.is_empty() { + overrides.insert(format!("minecraft:{stem}"), map); + } + } + Self { overrides } + } + pub fn get(&self, structure: &str, category: &str) -> Option<&Override> { + self.overrides.get(structure)?.get(category) + } +} + +/// A structure whose references reach a position. +#[derive(Clone, Debug)] +pub struct StructureAt { + pub id: String, + /// A piece of one of its starts holds the position. + pub in_piece: bool, + /// One of its starts' bounding boxes holds the position. + pub in_bounds: bool, +} + +/// `NetherFortressStructure.FORTRESS_ENEMIES`. +pub fn fortress_enemies() -> Vec { + let e = |entity: &str, weight, min, max, constant| SpawnEntry { + entity: entity.to_owned(), + weight, + min, + max, + constant, + }; + vec![ + e("minecraft:blaze", 10, 2, 3, false), + e("minecraft:zombified_piglin", 5, 4, 4, true), + e("minecraft:wither_skeleton", 8, 5, 5, true), + e("minecraft:skeleton", 2, 5, 5, true), + e("minecraft:magma_cube", 3, 4, 4, true), + ] +} + +/// `NaturalSpawner.mobsAt`. +pub fn mobs_at( + spawns: &StructureSpawns, + biome: &HashMap>, + category: &str, + structures: &[StructureAt], + below_nether_bricks: bool, +) -> Vec { + // isInNetherFortressBounds. + if category == "monster" + && below_nether_bricks + && structures + .iter() + .any(|s| s.id == "minecraft:fortress" && s.in_bounds) + { + return fortress_enemies(); + } + // ChunkGenerator.getMobsAt: the first structure whose override holds. + for s in structures { + if let Some(o) = spawns.get(&s.id, category) + && (if o.piece { s.in_piece } else { s.in_bounds }) + { + return o.spawns.clone(); + } + } + biome.get(category).cloned().unwrap_or_default() +} + +/// `WeightedList.getRandom`. +pub fn weighted_pick(list: &[SpawnEntry], random: &mut impl RandomSource) -> Option { + let total: i64 = list.iter().map(|e| i64::from(e.weight)).sum(); + if total <= 0 { + return None; + } + let mut selection = i64::from(random.next_int_bound(total as i32).ok()?); + for e in list { + selection -= i64::from(e.weight); + if selection < 0 { + return Some(e.clone()); + } + } + None +} + +/// `NaturalSpawner.getRandomSpawnMobAt`. +pub fn random_spawn_mob_at( + list: &[SpawnEntry], + category: &str, + reduced_water_ambient: bool, + random: &mut impl RandomSource, +) -> Option { + if category == "water_ambient" && reduced_water_ambient && random.next_float() < 0.98 { + return None; + } + weighted_pick(list, random) +} + +/// `SpawnerData.count().sample(random)`: a constant draws nothing. +pub fn sample_count(entry: &SpawnEntry, random: &mut impl RandomSource) -> u32 { + if entry.constant { + entry.min + } else { + let span = entry.max.saturating_sub(entry.min) as i32 + 1; + entry.min + random.next_int_bound(span).unwrap_or(0) as u32 + } +}