diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 3e447a7fb..c2ea487ee 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -53,13 +53,7 @@ impl Game<'_> { let Ok(raw) = Compression::Gzip.decode(&bytes, 1 << 28) else { continue; }; - let Ok((named, _)) = nbt::read_named( - &raw, - Limits { - max_bytes: 1 << 28, - ..Limits::default() - }, - ) else { + let Ok((named, _)) = nbt::read_named(&raw, Limits::templates()) else { continue; }; return Some(Arc::new(StructureTemplate::from_nbt( diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index 1cd155297..c396c3333 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -697,6 +697,78 @@ fn worldgen_entry(file: &str) -> Option<(&'static str, String)> { Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?))) } +/// The key of a mod's structure set or template pool file that adds its +/// entries to other sets or pools (vanilla's, another mod's) instead of +/// being one of its own. Vanilla data never has it. +const ADD_TO: &str = "horizon:add_to"; +/// The bundles a mod may add to, and the list each entry goes into. +const ADDABLE: [(&str, &str); 2] = [ + ("worldgen/structure_sets.json", "structures"), + ("worldgen/template_pools.json", "elements"), +]; + +/// A mod file's additions (`horizon:add_to`): its entries appended to the +/// list of each set or pool it names, as lithostitched's +/// `add_structure_set_entries` and `add_template_pool_elements` do for +/// NeoForge and Fabric packs. +struct Addition { + targets: Vec, + list: &'static str, + entries: Vec, +} +impl Addition { + /// What a mod file of `bundle` adds, if it is an addition file. + fn read(bundle: &str, text: &str) -> Result> { + let Some((_, list)) = ADDABLE.iter().find(|(b, _)| *b == bundle) else { + return Ok(None); + }; + if !text.contains(ADD_TO) { + return Ok(None); + } + let doc: J = serde_json::from_str(text)?; + let Some(targets) = doc.get(ADD_TO) else { + return Ok(None); + }; + let targets = match targets { + J::Str(s) => vec![s.clone()], + J::Arr(a) => a + .iter() + .map(|v| match v { + J::Str(s) => Some(s.clone()), + _ => None, + }) + .collect::>() + .ok_or(format!("{ADD_TO}: not a list of ids"))?, + _ => return Err(format!("{ADD_TO}: not an id or a list of ids").into()), + }; + let Some(J::Arr(entries)) = doc.get(list) else { + return Err(format!("{ADD_TO} without a {list} list").into()); + }; + Ok(Some(Self { + targets, + list, + entries: entries.clone(), + })) + } + /// Appends the entries to each target in the bundle `doc` (id → the + /// file's text). A target nobody defines is skipped, as a tag entry + /// naming an unknown id is. + fn apply(&self, doc: &mut J) -> Result<()> { + for target in &self.targets { + let Some(J::Str(text)) = doc.get(target) else { + continue; + }; + let mut v: J = serde_json::from_str(text).map_err(|e| format!("{target}: {e}"))?; + let Some(J::Arr(list)) = v.get_mut(self.list) else { + continue; + }; + list.extend(self.entries.iter().cloned()); + doc.set(target, J::Str(serde_json::to_string(&v)?)); + } + Ok(()) + } +} + /// The overlay being written: `out` mirrors `base` through links, and a /// directory becomes real only when something inside it is written. struct Overlay<'a> { @@ -904,6 +976,7 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { // Mod files, and every tag addition gathered per tag file. let mut tags: BTreeMap> = BTreeMap::new(); let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new(); + let mut additions: BTreeMap<&str, Vec> = BTreeMap::new(); for m in mods { let declarations = format!("data/{}/horizon/", m.id); for file in &m.content.files { @@ -928,7 +1001,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { overlay.write(file, &bytes)?; if let Some((bundle, id)) = worldgen_entry(file) { let text = String::from_utf8(bytes).map_err(|e| format!("{file}: {e}"))?; - worldgen.entry(bundle).or_default().push((id, text)); + let entries = worldgen.entry(bundle).or_default(); + match Addition::read(bundle, &text).map_err(|e| format!("{file}: {e}"))? { + Some(addition) => additions.entry(bundle).or_default().push(addition), + None => entries.push((id, text)), + } } else if let Some(template) = file .strip_prefix("data/") .and_then(|r| r.split_once("/structure/")) @@ -1002,7 +1079,8 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { } overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?; } - // Structures and the pools, sets, processors and features they use. + // Structures and the pools, sets, processors and features they use, then + // what mods add to sets and pools, in mod and file order. for (bundle, entries) in &worldgen { if !base.join(bundle).exists() { continue; @@ -1011,6 +1089,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { for (id, text) in entries { doc.set(id, J::Str(text.clone())); } + for addition in additions.get(bundle).into_iter().flatten() { + addition + .apply(&mut doc) + .map_err(|e| format!("{bundle}: {e}"))?; + } overlay.write(bundle, &serde_json::to_vec(&doc)?)?; } // A block without its own blockstate looks like its template, so every diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 614705562..c80b45c3e 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -576,6 +576,18 @@ fn content_root_carries_a_structure_mod() { "data/huts/tags/worldgen/biome/has_hut.json", r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##, ), + // Additions to vanilla's set and pool; a target nobody defines is skipped. + ( + "data/huts/worldgen/structure_set/added/villages.json", + r#"{"horizon:add_to": "minecraft:villages", + "structures": [{"structure": "huts:hut", "weight": 3}]}"#, + ), + ( + "data/huts/worldgen/template_pool/added/houses.json", + r#"{"horizon:add_to": ["othermod:houses", "minecraft:village/plains/houses"], + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}]}"#, + ), ]; for (name, text) in files { let path = dir.join(name); @@ -601,6 +613,37 @@ fn content_root_carries_a_structure_mod() { hut["values"], serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"]) ); + // The additions join vanilla's entries at the end and are no set or pool + // of their own. + let bundle = |name: &str, base: &Path| -> BTreeMap { + serde_json::from_slice(&fs::read(base.join("worldgen").join(name)).unwrap()).unwrap() + }; + for (name, id, list, added) in [ + ( + "structure_sets.json", + "minecraft:villages", + "structures", + serde_json::json!({"structure": "huts:hut", "weight": 3}), + ), + ( + "template_pools.json", + "minecraft:village/plains/houses", + "elements", + serde_json::json!({"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}), + ), + ] { + let (ours, vanilla) = (bundle(name, &root), bundle(name, &base)); + let entries = |text: &str| -> Vec { + let v: serde_json::Value = serde_json::from_str(text).unwrap(); + v[list].as_array().unwrap().clone() + }; + let mut expected = entries(&vanilla[id]); + expected.push(added); + assert_eq!(entries(&ours[id]), expected, "{id}"); + assert!(!ours.keys().any(|k| k.starts_with("huts:added/")), "{name}"); + assert!(!ours.contains_key("othermod:houses")); + } let assets = Assets::load(&root).unwrap(); let biomes = crate::biome::Biomes::load(&root).unwrap(); diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index c73570684..bfd0bcad5 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -331,13 +331,16 @@ fn unreadable(name: &str, bytes: &mut Vec) -> Option { /// Carries `jar` over into `out/carry/`. With the oracle's `facts`, blocks /// and items are the ones the mod registers, with the templates and numbers -/// the facts give; `allowed` says which vanilla blocks the game has. +/// the facts give; `allowed` says which vanilla blocks the game has; +/// `loaded` which mods are ported along, for the conditions of the mod's +/// worldgen modifiers. pub fn carry( jar: &Path, info: &JarInfo, out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, + loaded: &dyn Fn(&str) -> bool, conventions: &BTreeMap, ) -> Result { let id = &info.mod_id; @@ -363,6 +366,7 @@ pub fn carry( let mut block_loot = BTreeSet::new(); let mut biome_conventions = BTreeSet::new(); let set_tags = crate::worldgen::structure_set_tags(&mut zip); + let piece_counts = crate::worldgen::piece_counts(&mut zip); for i in 0..zip.len() { let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; let name = entry.name().to_owned(); @@ -422,11 +426,43 @@ pub fn carry( if kind == "structure" { crate::worldgen::convention_tags(&v["biomes"], &mut biome_conventions); } - if crate::worldgen::upgrade(kind, &mut v, &mut report.worldgen_types, &set_tags) - { + let mut changed = crate::worldgen::upgrade( + kind, + &mut v, + &mut report.worldgen_types, + &set_tags, + ); + if kind == "structure" { + let path = rel.trim_start_matches("worldgen/structure/"); + let structure = format!("{id}:{}", path.trim_end_matches(".json")); + changed |= crate::worldgen::disables(&structure, &mut v); + changed |= + crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); + } + if changed { bytes = serde_json::to_vec_pretty(&v).unwrap_or(bytes); } } + } else if let Some(path) = rel + .strip_prefix("lithostitched/worldgen_modifier/") + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + // Additions to other sets and pools, as files the game merges. + let modifier = serde_json::from_slice::(&bytes).ok(); + let types = &mut report.worldgen_types; + if let Some((kind, mut added)) = + modifier.and_then(|v| crate::worldgen::modifier(&v, loaded, types)) + { + crate::worldgen::upgrade(kind, &mut added, types, &set_tags); + let to = format!( + "data/{id}/worldgen/{kind}/{}/{path}", + crate::worldgen::ADDED + ); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&added).unwrap_or_default(), + )?; + } } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { if let Ok(v) = serde_json::from_slice::(&bytes) { crate::worldgen::convention_tags(&v, &mut biome_conventions); @@ -462,6 +498,35 @@ pub fn carry( } write(&dest, &bytes)?; } + // Entries the mod adds to other structure sets in Java code, for the + // structures it has. + for (file, set, entries) in crate::worldgen::code_set_entries(id) { + let entries: Vec = entries + .into_iter() + .filter(|(s, _)| { + s.split_once(':').is_some_and(|(ns, path)| { + inside + .join(format!("data/{ns}/worldgen/structure/{path}.json")) + .exists() + }) + }) + .map(|(structure, weight)| json!({"structure": structure, "weight": weight})) + .collect(); + if entries.is_empty() { + continue; + } + let added = &mut report.worldgen_types.added_to; + *added.entry(set.to_owned()).or_default() += entries.len(); + let to = format!( + "data/{id}/worldgen/structure_set/{}/{file}.json", + crate::worldgen::ADDED + ); + let v = json!({"horizon:add_to": set, "structures": entries}); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&v).unwrap_or_default(), + )?; + } // 1.21.4 moved item models behind `items/.json` definitions. for m in &item_models { let def = inside.join(format!("assets/{id}/items/{m}.json")); @@ -832,6 +897,14 @@ mod tests { r#"{"values": ["gem:gem_block"]}"#, ), ("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#), + ( + "data/gem/lithostitched/worldgen_modifier/houses.json", + r#"{"type": "lithostitched:add_template_pool_elements", + "template_pools": "minecraft:village/plains/houses", + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "gem:hut", "projection": "rigid", + "processors": {"processors": [{"processor_type": "lithostitched:block_swap"}]}}}]}"#, + ), // What the game would refuse: vanilla skips these files alone. ("assets/gem/lang/ry_UA.json", r#"{"item.gem.gem": "Gem"}"#), ("data/gem/tags/item/empty.json", ""), @@ -858,8 +931,17 @@ mod tests { ); assert_eq!(info.census.classes, 1); let out = dir.join("work/mods/gem"); - let report = carry(&jar, &info, &out, None, &|_| true, &BTreeMap::new()).unwrap(); - assert_eq!(report.copied, 13); + let report = carry( + &jar, + &info, + &out, + None, + &|_| true, + &|_| true, + &BTreeMap::new(), + ) + .unwrap(); + assert_eq!(report.copied, 14); let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect(); assert_eq!( unreadable, @@ -892,6 +974,25 @@ mod tests { ) .unwrap(); assert_eq!(recipe["key"]["#"], "gem:gem"); + // A lithostitched pool addition, as a file the game merges, upgraded + // as the mod's own pools are. + let added: Value = serde_json::from_slice( + &fs::read(carried.join("data/gem/worldgen/template_pool/horizon_added/houses.json")) + .unwrap(), + ) + .unwrap(); + assert_eq!( + added["horizon:add_to"], + json!(["minecraft:village/plains/houses"]) + ); + assert_eq!( + added["elements"][0]["element"]["processors"], + json!({"processors": []}) + ); + assert_eq!( + report.worldgen_types.added_to["minecraft:village/plains/houses"], + 1 + ); // Horizon's own reader accepts it: blocks and items declared, files fenced. let package = horizon_mods::Package::read(&carried).unwrap(); diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 3afe5b3a3..7152dc921 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -120,13 +120,27 @@ pub fn carry( }); let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b)); let conventions = crate::worldgen::loader_biome_tags(work); - let mut done = 0; - for r in &records { - let chosen = if only.is_empty() { + let chosen = |r: &inventory::Record| { + if only.is_empty() { r.class == "content" } else { only.contains(&r.key) - }; + } + }; + // The mods ported along (carried now or before), for the conditions of + // the mods' worldgen modifiers. + let ported: BTreeSet<&str> = records + .iter() + .filter(|r| { + r.jar.is_some() && (chosen(r) || work.join("mods").join(&r.key).join("carry").is_dir()) + }) + .filter_map(|r| Some(r.info.as_ref()?.mod_id.as_str())) + .chain(["minecraft"]) + .collect(); + let loaded = |m: &str| ported.contains(m); + let mut done = 0; + for r in &records { + let chosen = chosen(r); let (Some(jar), Some(info)) = (&r.jar, &r.info) else { if chosen && !only.is_empty() { log(format!( @@ -155,6 +169,7 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, + &loaded, &conventions, ) { Ok(report) => { diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 25e0dbbea..dbd4fb8c6 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -26,11 +26,53 @@ const JIGSAWS: [&str; 3] = [ "moogs_structures:moogs_structures_generic_jigsaw_structure", "repurposed_structures:generic_jigsaw_structure", ]; +/// The Nether variants of the piece-limited jigsaws: laid out the same, +/// then moved onto land. +const NETHER_JIGSAWS: [&str; 2] = [ + "moogs_structures:moogs_structures_generic_nether_jigsaw_structure", + "repurposed_structures:generic_nether_jigsaw_structure", +]; +/// Layout rules the piece-limited assembler keeps (`horizon:piece_limited`). +const PIECE_LIMITED_RULES: [&str; 4] = [ + "y_allowance", + "burying_type", + "use_bounding_box_hack", + "pools_that_ignore_boundaries", +]; /// Placements that are vanilla's random spread with extra rules. const SPREADS: [&str; 2] = [ "moogs_structures:advanced_random_spread", "repurposed_structures:advanced_random_spread", ]; +/// YUNG's placements: vanilla's random spread with an enhanced exclusion +/// zone (several sets), plus, for the temples, no start near an ocean or a +/// river, and for strongholds, starts only in odd rings around the origin. +const YUNG_SPREADS: [&str; 4] = [ + "yungsapi:enhanced_random_spread", + "betterdeserttemples:desert_temple", + "betterjungletemples:jungle_temple", + "betterstrongholds:stronghold", +]; +/// YUNG's structures and the vanilla structure type each one's mod turns +/// off (its DisableVanilla*Mixin, on by default in each mod's config). +const YUNG_REPLACES: [(&str, &str); 7] = [ + ( + "betterdeserttemples:desert_temple", + "minecraft:desert_pyramid", + ), + ( + "betterjungletemples:jungle_temple", + "minecraft:jungle_temple", + ), + ("betterwitchhuts:witch_hut", "minecraft:swamp_hut"), + ( + "betteroceanmonuments:ocean_monument", + "minecraft:ocean_monument", + ), + ("betterstrongholds:stronghold", "minecraft:stronghold"), + ("betterfortresses:fortress", "minecraft:fortress"), + ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), +]; /// Moog's Structure Lib spreads its structures 1.65 times as far apart as /// its files say (AdvancedRandomSpread's constructor). const MOOGS_SPACING: f64 = 1.65; @@ -76,6 +118,206 @@ pub struct Upgrade { pub rules_lost: BTreeMap, /// Processors written in Java, taken out of their lists, by type. pub processors_dropped: BTreeMap, + /// Entries added to other structure sets and template pools + /// (`horizon:add_to`), by the set or pool they join. + pub added_to: BTreeMap, + /// Lithostitched worldgen modifiers not carried: by type, `conditions` + /// when they need a mod that is not ported along, `target` when they + /// name their sets or pools by a tag. + pub modifiers_left: BTreeMap, +} + +/// Where a mod's additions to other sets and pools go in its carry: +/// `data//worldgen//horizon_added/.json`. +pub const ADDED: &str = "horizon_added"; + +/// A lithostitched worldgen modifier +/// (`data//lithostitched/worldgen_modifier/`) that adds to structure +/// sets or template pools, as a file the game merges into them (the key +/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The +/// modifier's conditions are checked against `loaded`, the mods ported +/// along: a compat addition for a mod that is not would place that mod's +/// blocks, which the game does not have. Other modifier types are left out. +/// Both are counted in `report`. +pub fn modifier( + v: &Value, + loaded: &dyn Fn(&str) -> bool, + report: &mut Upgrade, +) -> Option<(&'static str, Value)> { + let t = v["type"].as_str().unwrap_or_default(); + let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1; + let (kind, targets, from, to) = match t { + "lithostitched:add_structure_set_entries" => { + ("structure_set", "structure_sets", "entries", "structures") + } + "lithostitched:add_template_pool_elements" => { + ("template_pool", "template_pools", "elements", "elements") + } + _ => { + left(t); + return None; + } + }; + if !conditions_hold(v, loaded) { + left("conditions"); + return None; + } + let targets: Option> = match &v[targets] { + Value::String(s) => Some(vec![s.as_str()]), + Value::Array(a) => a.iter().map(Value::as_str).collect(), + _ => None, + }; + let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#'))) + else { + left("target"); + return None; + }; + let entries = v[from].as_array().cloned().unwrap_or_default(); + for target in &targets { + *report.added_to.entry((*target).to_owned()).or_default() += entries.len(); + } + Some(( + kind, + serde_json::json!({"horizon:add_to": targets, to: entries}), + )) +} + +/// Whether a modifier's load conditions hold: lithostitched's `predicate`, +/// and the loader's conditions (NeoForge's, else Fabric's). A condition +/// type not known here does not hold. +fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let all = |list: &Value, test: &dyn Fn(&Value) -> bool| { + list.as_array().is_some_and(|a| a.iter().all(test)) + }; + fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| predicate(q, loaded); + let list = &p["predicates"]; + match p["type"] + .as_str() + .map(|t| t.trim_start_matches("lithostitched:")) + { + Some("true") => true, + Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded), + Some("not") => !predicate(&p["predicate"], loaded), + Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)), + Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| neoforge(q, loaded); + match c["type"].as_str() { + Some("neoforge:true") => true, + Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded), + Some("neoforge:not") => !neoforge(&c["value"], loaded), + Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| fabric(q, loaded); + let mods = || { + c["values"] + .as_array() + .into_iter() + .flatten() + .map(Value::as_str) + }; + match c["condition"].as_str() { + Some("fabric:true") => true, + Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)), + Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)), + Some("fabric:not") => !fabric(&c["value"], loaded), + Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded)); + let loader = match ( + v.get("neoforge:conditions"), + v.get("fabric:load_conditions"), + ) { + (Some(c), _) => all(c, &|c| neoforge(c, loaded)), + // One condition or a list of them. + (None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)), + (None, Some(c)) => fabric(c, loaded), + (None, None) => true, + }; + litho && loader +} + +/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds +/// to vanilla's `villages` and `pillager_outposts` sets in Java code +/// (`CTOV.registerstructure`, through lithostitched), with its default +/// config: every village type in three sizes, weighted 10, 4 and 1, and +/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each). +const CTOV_VILLAGES: [&str; 21] = [ + "beach", + "christmas", + "desert", + "desert_oasis", + "dark_forest", + "jungle", + "jungle_tree", + "mesa", + "mesa_fortified", + "mountain", + "mountain_alpine", + "mushroom", + "plains", + "plains_fortified", + "savanna", + "savanna_na", + "snowy_igloo", + "swamp", + "swamp_fortified", + "taiga", + "taiga_fortified", +]; +const CTOV_OUTPOSTS: [&str; 11] = [ + "beach", + "dark_forest", + "desert", + "jungle", + "badlands", + "mountain", + "plains", + "savanna", + "snowy", + "swamp", + "taiga", +]; + +/// The entries a mod adds to other structure sets in Java code, as its +/// default config has them: (file name, set, `[(structure, weight)]`). +/// Lithostitched appends them in the order of a hash map of every modifier +/// in the pack, which carry cannot know; they are written in the order the +/// mod registers them. Each set picks by weight, so how often each starts +/// is the same. +pub fn code_set_entries(mod_id: &str) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> { + match mod_id { + "ctov" => { + let outposts = CTOV_OUTPOSTS + .iter() + .map(|v| (format!("ctov:pillager_outpost_{v}"), 1)) + .collect(); + let villages = [("small", 10), ("medium", 4), ("large", 1)] + .into_iter() + .flat_map(|(size, weight)| { + CTOV_VILLAGES + .iter() + .map(move |v| (format!("ctov:{size}/village_{v}"), weight)) + }) + .collect(); + vec![ + ("pillager_outposts", "minecraft:pillager_outposts", outposts), + ("villages", "minecraft:villages", villages), + ] + } + _ => Vec::new(), + } } /// Rewrites one `data//worldgen//...` file in place; whether it @@ -180,12 +422,26 @@ fn upgrade_types( let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; let changed = match kind { "structure" => match v["type"].as_str() { - Some(t) if JIGSAWS.contains(&t) => { - let liquid = match t.split_once(':').map(|(ns, _)| ns) { - Some("moogs_structures") => "top", - _ => "lowest", + Some("yungsapi:yung_jigsaw") => { + yung_structure(v, lost); + true + } + Some(t) if JIGSAWS.contains(&t) || NETHER_JIGSAWS.contains(&t) => { + let library = match t.split_once(':').map(|(ns, _)| ns) { + Some("moogs_structures") => Some("moogs"), + Some("repurposed_structures") => Some("repurposed"), + _ => None, }; - start_checks(v, liquid, lost); + let liquid = if library == Some("moogs") { + "top" + } else { + "lowest" + }; + let limited = library.map(|l| piece_limited(v, l)); + start_checks(v, liquid, lost, limited.is_some()); + if let Some(limited) = limited { + v["horizon:piece_limited"] = limited; + } v["type"] = "minecraft:jigsaw".into(); true } @@ -206,6 +462,11 @@ fn upgrade_types( p["type"] = "minecraft:random_spread".into(); true } + Some(t) if YUNG_SPREADS.contains(&t) => { + let t = t.to_owned(); + yung_placement(&t, &mut v["placement"], set_tags, lost); + true + } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -231,6 +492,9 @@ fn upgrade_types( if let Some((_, to)) = ELEMENTS.iter().find(|(from, _)| *from == t) { element["element_type"] = (*to).into(); changed = true; + } else if t == "yungsapi:yung_single_element" { + yung_element(element, lost); + changed = true; } else if !t.starts_with("minecraft:") { unsupported(t); } @@ -243,10 +507,122 @@ fn upgrade_types( changed } +/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the +/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`): +/// the heights pieces stay within move under the key. Its terrain +/// adaptation and a start offset in the chunk are lost. +fn yung_structure(v: &mut Value, lost: &mut BTreeMap) { + let Some(o) = v.as_object_mut() else { + return; + }; + o.insert("type".into(), "minecraft:jigsaw".into()); + let mut rules = serde_json::Map::new(); + for key in ["min_y", "max_y"] { + if let Some(y) = o.remove(key) { + rules.insert(key.into(), y); + } + } + let none = |a: &Value| a["type"] == "yungsapi:none"; + if o.remove("enhanced_terrain_adaptation") + .is_some_and(|a| !none(&a)) + { + *lost + .entry("enhanced_terrain_adaptation".into()) + .or_default() += 1; + } + for key in ["x_offset_in_chunk", "z_offset_in_chunk"] { + if o.remove(key).is_some_and(|n| n != 0) { + *lost.entry(key.into()).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// YUNG's single pool element as vanilla's, its rules under +/// `horizon:yungsapi`: name and `max_count`, depth range, priority, +/// `ignore_bounds` and its condition. Its terrain adaptation, dead-end pool +/// and modifiers are lost. +fn yung_element(element: &mut Value, lost: &mut BTreeMap) { + let Some(o) = element.as_object_mut() else { + return; + }; + o.insert( + "element_type".into(), + "minecraft:single_pool_element".into(), + ); + let mut rules = serde_json::Map::new(); + for (from, to) in [ + ("name", "name"), + ("max_count", "max_count"), + ("min_required_depth", "min_depth"), + ("max_possible_depth", "max_depth"), + ("is_priority", "priority"), + ("ignore_bounds", "ignore_bounds"), + ] { + if let Some(x) = o.remove(from) { + rules.insert(to.into(), x); + } + } + if let Some(c) = o.remove("condition") { + rules.insert("condition".into(), yung_condition(&c, lost)); + } + for key in ["enhanced_terrain_adaptation", "deadend_pool", "modifiers"] { + let empty = + |x: &Value| x.as_array().is_some_and(Vec::is_empty) || x["type"] == "yungsapi:none"; + if o.remove(key).is_some_and(|x| !empty(&x)) { + *lost.entry(format!("yungsapi {key}")).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// One of YUNG's structure conditions in the game's terms. `mod_loaded` +/// holds for Minecraft alone: a mod that needs code is not ported, and the +/// pieces it guards would place its blocks. A condition the game does not +/// have does not hold, and is counted. +fn yung_condition(c: &Value, lost: &mut BTreeMap) -> Value { + let t = c["type"].as_str().unwrap_or_default(); + let list = |lost: &mut BTreeMap| -> Value { + let all = c["conditions"].as_array().into_iter().flatten(); + all.map(|x| yung_condition(x, lost)) + .collect::>() + .into() + }; + let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null); + match t.trim_start_matches("yungsapi:") { + "always_true" => serde_json::json!({"type": "true"}), + "not" => { + serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)}) + } + "all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}), + "any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}), + "depth" => serde_json::json!({"type": "depth", + "min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}), + "altitude" => serde_json::json!({"type": "altitude", + "bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}), + "random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}), + "rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}), + "piece_in_horizontal_direction" => { + // "yungsapi:all" (or no list) matches any piece. + let pieces: Vec = c["pieces"].as_array().cloned().unwrap_or_default(); + let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); + serde_json::json!({"type": "piece_in_horizontal_direction", + "pieces": if any { Vec::new() } else { pieces }, + "range": opt("range"), "rotation": opt("rotation")}) + } + "mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}), + "mod_loaded" => serde_json::json!({"type": "false"}), + _ => { + *lost.entry(format!("yungsapi condition {t}")).or_default() += 1; + serde_json::json!({"type": "false"}) + } + } +} + /// Moves a Repurposed Structures or Moog's jigsaw's start rules under /// `horizon:start_checks`, and counts the layout rules it loses. `liquid` is /// the block its no-start-in-liquid rule reads. -fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap) { +fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap, limited: bool) { let Some(o) = v.as_object_mut() else { return; }; @@ -267,7 +643,8 @@ fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap) } } for rule in LAYOUT_RULES { - if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) { + let kept = limited && PIECE_LIMITED_RULES.contains(&rule); + if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) && !kept { *lost.entry(rule.into()).or_default() += 1; } } @@ -276,6 +653,121 @@ fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap) } } +/// A Repurposed Structures or Moog's jigsaw's layout rules for the game's +/// piece-limited assembler: y_allowance, burying, the pools whose fallbacks +/// ignore the bounds, liquid, and the Nether variants' land search. The +/// bounding box hack is vanilla's expansion hack. The pieces' counts are +/// added from the mod's count files ([`piece_counts`]). +fn piece_limited(v: &mut Value, library: &str) -> Value { + let mut out = serde_json::Map::new(); + out.insert("library".into(), library.into()); + let lower = |x: &Value| x.as_str().map(str::to_ascii_lowercase); + for (from, to) in [("min_y_allowed", "min_y"), ("max_y_allowed", "max_y")] { + if let Some(n) = v.get("y_allowance").and_then(|y| y.get(from)) { + out.insert(to.into(), n.clone()); + } + } + if let Some(b) = v.get("burying_type").and_then(lower) { + out.insert("burying".into(), b.into()); + } + if v["cannot_spawn_in_liquid"].as_bool() == Some(true) { + out.insert("no_liquid".into(), true.into()); + } + if let Some(pools) = v + .get("pools_that_ignore_boundaries") + .filter(|p| p.is_array()) + { + out.insert("ignore_bounds_pools".into(), pools.clone()); + } + if v["use_bounding_box_hack"].as_bool() == Some(true) { + v["use_expansion_hack"] = true.into(); + } + if let Some(o) = v.as_object_mut() { + if let Some(search) = o.remove("land_search_direction") { + out.insert("land_search".into(), lower(&search).into()); + } + if let Some(ledge) = o.remove("ledge_offset_y") { + out.insert("ledge_offset_y".into(), ledge); + } + } + out.into() +} + +/// The pieces' spawn counts of the structures a mod ships, by structure id: +/// Repurposed Structures' `rs_pieces_spawn_counts` (each file names its +/// `target_structure`) and Moog's `msl_pieces_spawn_counts` (the file's id), +/// in the game's `horizon:piece_limited` shape. +pub fn piece_counts( + zip: &mut zip::ZipArchive, +) -> BTreeMap { + let mut out = BTreeMap::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let name = entry.name().to_owned(); + let Some((ns, rest)) = name + .strip_prefix("data/") + .and_then(|r| r.strip_suffix(".json")) + .and_then(|r| r.split_once('/')) + else { + continue; + }; + let (rs, path) = if let Some(p) = rest.strip_prefix("rs_pieces_spawn_counts/") { + (true, p) + } else if let Some(p) = rest.strip_prefix("msl_pieces_spawn_counts/") { + (false, p) + } else { + continue; + }; + let mut text = String::new(); + let Ok(v) = entry + .read_to_string(&mut text) + .map_err(|_| ()) + .and_then(|_| serde_json::from_str::(&text).map_err(|_| ())) + else { + continue; + }; + let id = match v["target_structure"].as_str() { + Some(target) if rs => target.to_owned(), + _ if rs => continue, + _ => format!("{ns}:{path}"), + }; + let pieces: Vec = v["pieces_spawn_counts"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| { + let mut e = serde_json::Map::new(); + e.insert("name".into(), p["nbt_piece_name"].as_str()?.into()); + for (from, to) in [ + ("always_spawn_this_many", "required"), + ("never_spawn_more_than_this_many", "max"), + ("minimum_distance_from_center_piece", "min_depth"), + ] { + if let Some(n) = p.get(from).filter(|n| n.is_number()) { + e.insert(to.into(), n.clone()); + } + } + Some(Value::Object(e)) + }) + .collect(); + out.insert(id, pieces.into()); + } + out +} + +/// Adds a structure's piece counts to its `horizon:piece_limited` key. +pub fn add_piece_counts(id: &str, v: &mut Value, counts: &BTreeMap) -> bool { + match (counts.get(id), v.get_mut("horizon:piece_limited")) { + (Some(pieces), Some(limited)) => { + limited["pieces"] = pieces.clone(); + true + } + _ => false, + } +} + /// AdvancedRandomSpread's spacing and separation, as Moog's computes them /// with its default config: 1.65 times the file's, rounded, the separation /// below the spacing. `when_replacing` (other numbers while a preset @@ -306,7 +798,10 @@ fn placement_rules( if let Some(d) = o.remove("min_distance_from_world_origin") { o.insert("horizon:min_distance_from_world_origin".into(), d); } - if let Some(zone) = o.remove("super_exclusion_zone") { + let zone = ["super_exclusion_zone", "enhanced_exclusion_zone"] + .into_iter() + .find_map(|k| Some((k, o.remove(k)?))); + if let Some((key, zone)) = zone { let sets: Vec = match &zone["other_set"] { Value::String(s) => match s.strip_prefix('#') { Some(tag) => set_tags.get(tag).cloned().unwrap_or_default(), @@ -319,7 +814,7 @@ fn placement_rules( _ => Vec::new(), }; if sets.is_empty() { - *lost.entry("super_exclusion_zone".into()).or_default() += 1; + *lost.entry(key.into()).or_default() += 1; } else { o.insert( "horizon:exclusion_zone".into(), @@ -329,6 +824,65 @@ fn placement_rules( } } +/// One of YUNG's placements as vanilla's random spread with `horizon:` keys: +/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' +/// ocean and river search (findBiomeHorizontal around the chunk's middle +/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the +/// strongholds' rings as `horizon:ring_sections`. +fn yung_placement( + t: &str, + p: &mut Value, + set_tags: &BTreeMap>, + lost: &mut BTreeMap, +) { + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + let Some(o) = p.as_object_mut() else { + return; + }; + match t { + "betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => { + o.insert( + "horizon:avoid_biomes".into(), + serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}), + ); + } + "betterstrongholds:stronghold" => { + let mut rings = serde_json::Map::new(); + for (from, to) in [ + ("chunk_distance_to_first_ring", "distance_to_first_ring"), + ("ring_chunk_thickness", "thickness"), + ("max_ring_section", "max_section"), + ] { + if let Some(n) = o.remove(from) { + rings.insert(to.into(), n); + } + } + o.insert("horizon:ring_sections".into(), rings.into()); + } + _ => {} + } +} + +/// Marks a YUNG's structure that the game can start (its type is vanilla's +/// after the upgrade) with the vanilla type its mod turns off, under +/// `horizon:disables`. One the game cannot start leaves the vanilla +/// structure in place, so the world keeps one of the two. +pub fn disables(id: &str, v: &mut Value) -> bool { + let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else { + return false; + }; + if !v["type"] + .as_str() + .is_some_and(|t| t.starts_with("minecraft:")) + { + return false; + } + v["horizon:disables"] = serde_json::json!([vanilla]); + true +} + /// The mod's structure set tags (`data//tags/worldgen/structure_set/`), /// by tag id, with the tags they include expanded. Optional entries /// (`{"id": ..., "required": false}`) count as their id. @@ -476,9 +1030,8 @@ mod tests { let mut s = json!({"type": "lithostitched:jigsaw", "start_pool": "a:b"}); assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); assert_eq!(s["type"], "minecraft:jigsaw"); - let mut nether = - json!({"type": "moogs_structures:moogs_structures_generic_nether_jigsaw_structure"}); - assert!(!upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + let mut formation = json!({"type": "formations:simple"}); + assert!(!upgrade("structure", &mut formation, &mut report, &NO_TAGS)); let mut set = json!({"placement": {"type": "moogs_structures:advanced_random_spread", "spacing": 10, "separation": 5, "min_distance_from_world_origin": 250}}); assert!(upgrade("structure_set", &mut set, &mut report, &NO_TAGS)); @@ -499,7 +1052,7 @@ mod tests { {"weight": 1, "element": {"element_type": "moogs_structures:versioned_single_pool_element", "location": "m:x"}}, {"weight": 1, "element": {"element_type": "minecraft:list_pool_element", "elements": [ {"element_type": "empty_pool_element"}]}}, - {"weight": 1, "element": {"element_type": "yungsapi:yung_single_element"}} + {"weight": 1, "element": {"element_type": "somelib:element"}} ]}); assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); assert_eq!( @@ -515,11 +1068,8 @@ mod tests { assert_eq!( report.unsupported, BTreeMap::from([ - ( - "moogs_structures:moogs_structures_generic_nether_jigsaw_structure".into(), - 1 - ), - ("yungsapi:yung_single_element".into(), 1), + ("formations:simple".into(), 1), + ("somelib:element".into(), 1), ]) ); } @@ -556,9 +1106,12 @@ mod tests { let mut plain = json!({"type": "lithostitched:jigsaw", "cannot_spawn_in_liquid": false}); assert!(upgrade("structure", &mut plain, &mut report, &NO_TAGS)); assert!(plain.get("horizon:start_checks").is_none()); + // The layout rules go to the piece-limited assembler. + assert!(report.rules_lost.is_empty()); assert_eq!( - report.rules_lost, - BTreeMap::from([("burying_type".into(), 1), ("y_allowance".into(), 1)]) + moogs["horizon:piece_limited"], + json!({"library": "moogs", "min_y": 60, "burying": "lowest_corner", + "no_liquid": true}) ); } @@ -599,6 +1152,52 @@ mod tests { assert_eq!(report.rules_lost["super_exclusion_zone"], 1); } + #[test] + fn yungs_jigsaws_keep_their_rules() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20, + "max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80, + "enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); + for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { + assert!(s.get(gone).is_none(), "{gone}"); + } + let mut pool = json!({"elements": [{"weight": 3, "element": { + "element_type": "yungsapi:yung_single_element", "location": "y:room", + "processors": "minecraft:empty", "projection": "rigid", + "name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true, + "ignore_bounds": false, "deadend_pool": "y:end", + "condition": {"type": "yungsapi:all_of", "conditions": [ + {"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"], + "range": 5, "rotation": "none"}, + {"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}}, + {"type": "yungsapi:biome", "biomes": []}]}}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + let e = &pool["elements"][0]["element"]; + assert_eq!(e["element_type"], "minecraft:single_pool_element"); + assert_eq!(e["location"], "y:room"); + assert_eq!( + e["horizon:yungsapi"], + json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true, + "ignore_bounds": false, "condition": {"type": "all_of", "conditions": [ + {"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"}, + {"type": "not", "condition": {"type": "false"}}, + {"type": "false"}]}}) + ); + assert!(e.get("deadend_pool").is_none()); + assert_eq!( + report.rules_lost, + BTreeMap::from([ + ("enhanced_terrain_adaptation".into(), 1), + ("yungsapi condition yungsapi:biome".into(), 1), + ("yungsapi deadend_pool".into(), 1), + ]) + ); + assert!(report.unsupported.is_empty()); + } + #[test] fn drops_processors_written_in_java() { let mut report = Upgrade::default(); @@ -643,6 +1242,127 @@ mod tests { ); } + #[test] + fn yungs_placements_keep_their_rules() { + let tags = BTreeMap::from([( + "bf:avoid".to_owned(), + vec!["minecraft:nether_complexes".to_owned()], + )]); + let mut report = Upgrade::default(); + let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread", + "salt": 1, "spacing": 30, "separation": 20, + "enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}}); + assert!(upgrade("structure_set", &mut fortress, &mut report, &tags)); + assert_eq!( + fortress["placement"], + json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20, + "horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}}) + ); + let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple", + "salt": 2, "spacing": 30, "separation": 20, + "exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}}); + assert!(upgrade("structure_set", &mut temple, &mut report, &tags)); + assert_eq!(temple["placement"]["type"], "minecraft:random_spread"); + assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6); + assert_eq!( + temple["placement"]["horizon:avoid_biomes"], + json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}) + ); + let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold", + "salt": 3, "spacing": 85, "separation": 50, + "chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}}); + assert!(upgrade( + "structure_set", + &mut stronghold, + &mut report, + &tags + )); + assert_eq!( + stronghold["placement"], + json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50, + "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}}) + ); + assert_eq!(report.mapped, 3); + assert!(report.unsupported.is_empty()); + // The vanilla counterpart is turned off only for a structure the game starts. + let mut ported = json!({"type": "minecraft:jigsaw"}); + assert!(disables("betterstrongholds:stronghold", &mut ported)); + assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"])); + let mut java = json!({"type": "bettermineshafts:mineshaft"}); + assert!(!disables("bettermineshafts:mineshaft_oak", &mut java)); + let mut circle = json!({"type": "minecraft:jigsaw"}); + assert!(!disables("betterwitchhuts:witch_circle", &mut circle)); + } + + #[test] + fn piece_limited_jigsaws_keep_their_layout() { + let mut report = Upgrade::default(); + let mut nether = json!({"type": "repurposed_structures:generic_nether_jigsaw_structure", + "start_pool": "rs:x", "size": 8, "y_allowance": {"min_y_allowed": 40, "max_y_allowed": 90}, + "cannot_spawn_in_liquid": true, "pools_that_ignore_boundaries": ["rs:roof"], + "use_bounding_box_hack": true, "land_search_direction": "HIGHEST_LAND", + "ledge_offset_y": 2}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!( + nether["horizon:piece_limited"], + json!({"library": "repurposed", "min_y": 40, "max_y": 90, "no_liquid": true, + "ignore_bounds_pools": ["rs:roof"], "land_search": "highest_land", + "ledge_offset_y": 2}) + ); + assert_eq!(nether["use_expansion_hack"], true); + for gone in [ + "y_allowance", + "use_bounding_box_hack", + "land_search_direction", + "ledge_offset_y", + ] { + assert!(nether.get(gone).is_none(), "{gone}"); + } + let mut moogs = json!({"type": "moogs_structures:moogs_structures_generic_jigsaw_structure", + "burying_type": "AVERAGE_LAND"}); + assert!(upgrade("structure", &mut moogs, &mut report, &NO_TAGS)); + assert_eq!( + moogs["horizon:piece_limited"], + json!({"library": "moogs", "burying": "average_land"}) + ); + // Lithostitched's jigsaw is vanilla's: no key. + let mut litho = json!({"type": "lithostitched:jigsaw"}); + assert!(upgrade("structure", &mut litho, &mut report, &NO_TAGS)); + assert!(litho.get("horizon:piece_limited").is_none()); + assert!(report.rules_lost.is_empty(), "{:?}", report.rules_lost); + assert!(report.unsupported.is_empty()); + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, text) in [ + ( + "data/rs/rs_pieces_spawn_counts/city.json", + r#"{"target_structure": "rs:city_nether", "pieces_spawn_counts": [ + {"nbt_piece_name": "rs:city/center", "always_spawn_this_many": 1, + "never_spawn_more_than_this_many": 1, "minimum_distance_from_center_piece": 3}]}"#, + ), + ( + "data/mvs/msl_pieces_spawn_counts/tower.json", + r#"{"pieces_spawn_counts": [{"nbt_piece_name": "mvs:top", "never_spawn_more_than_this_many": 2}]}"#, + ), + ] { + zip.start_file(name, opts).unwrap(); + std::io::Write::write_all(&mut zip, text.as_bytes()).unwrap(); + } + let mut zip = zip::ZipArchive::new(zip.finish().unwrap()).unwrap(); + let counts = piece_counts(&mut zip); + assert_eq!( + counts["rs:city_nether"], + json!([{"name": "rs:city/center", "required": 1, "max": 1, "min_depth": 3}]) + ); + assert_eq!(counts["mvs:tower"], json!([{"name": "mvs:top", "max": 2}])); + assert!(add_piece_counts("rs:city_nether", &mut nether, &counts)); + assert_eq!(nether["horizon:piece_limited"]["pieces"][0]["required"], 1); + assert!(!add_piece_counts("rs:other", &mut nether, &counts)); + } + #[test] fn writes_block_states_in_26_3_shape() { let mut report = Upgrade::default(); @@ -675,6 +1395,88 @@ mod tests { assert_eq!(report.mapped, 0); } + #[test] + fn modifiers_add_to_sets_and_pools() { + let mut report = Upgrade::default(); + let only_fd = |m: &str| m == "farmersdelight"; + let set = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "minecraft:villages", + "entries": [{"structure": "x:village", "weight": 4}]}); + let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap(); + assert_eq!(kind, "structure_set"); + assert_eq!( + added, + json!({"horizon:add_to": ["minecraft:villages"], + "structures": [{"structure": "x:village", "weight": 4}]}) + ); + // A compat addition holds only when its mod is ported along. + let pool = |modid: &str| { + json!({"type": "lithostitched:add_template_pool_elements", + "neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}], + "fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]}, + "template_pools": ["x:houses", "y:houses"], + "elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element", + "location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]}) + }; + let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap(); + assert_eq!(kind, "template_pool"); + assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"])); + assert_eq!(added["elements"][0]["weight"], 5); + assert!(modifier(&pool("create"), &only_fd, &mut report).is_none()); + // Fabric's conditions when there are no NeoForge ones; lithostitched's own. + let fabric = json!({"type": "lithostitched:add_structure_set_entries", + "fabric:load_conditions": [{"condition": "fabric:not", + "value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}], + "predicate": {"type": "lithostitched:all_of", "predicates": [ + {"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"}, + {"type": "lithostitched:true"}]}, + "structure_sets": "minecraft:villages", "entries": []}); + assert!(modifier(&fabric, &only_fd, &mut report).is_some()); + let tagged = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "#x:sets", "entries": []}); + assert!(modifier(&tagged, &only_fd, &mut report).is_none()); + let features = json!({"type": "lithostitched:add_features"}); + assert!(modifier(&features, &only_fd, &mut report).is_none()); + assert_eq!( + report.added_to, + BTreeMap::from([ + ("minecraft:villages".into(), 1), + ("x:houses".into(), 1), + ("y:houses".into(), 1), + ]) + ); + assert_eq!( + report.modifiers_left, + BTreeMap::from([ + ("conditions".into(), 1), + ("lithostitched:add_features".into(), 1), + ("target".into(), 1), + ]) + ); + } + + #[test] + fn ctov_joins_vanillas_villages_and_outposts() { + let sets = code_set_entries("ctov"); + let (file, set, outposts) = &sets[0]; + assert_eq!( + (*file, *set), + ("pillager_outposts", "minecraft:pillager_outposts") + ); + assert_eq!(outposts.len(), 11); + assert!(outposts.iter().all(|(_, w)| *w == 1)); + let (_, set, villages) = &sets[1]; + assert_eq!(*set, "minecraft:villages"); + assert_eq!(villages.len(), 63); + assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10)); + assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4)); + assert_eq!( + villages[62], + ("ctov:large/village_taiga_fortified".into(), 1) + ); + assert!(code_set_entries("mvs").is_empty()); + } + #[test] fn convention_tags_include_theirs() { let conventions = BTreeMap::from([ diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 2a8b11591..a8bed543a 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -110,6 +110,19 @@ impl Limits { max_depth: 512, } } + + /// Structure templates (`structure/*.nbt`): vanilla reads them with + /// `NbtAccounter.unlimitedHeap()` (TemplateSource.readStructure), and + /// mods ship templates past the default node cap (YUNG's Better Ocean + /// Monuments' start piece, 115x64x126 blocks, holds millions of tags). + /// The byte cap stays as the only guard on the decompressed file. + pub fn templates() -> Self { + Self { + max_bytes: 1 << 28, + max_nodes: usize::MAX, + max_depth: 512, + } + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -836,6 +849,18 @@ mod tests { assert!(read_network(&bytes, limits).is_err()); } #[test] + fn templates_read_past_the_default_node_cap() { + // A big mod template (YUNG's monument start) holds more tags than the + // default cap; vanilla reads templates with an unlimited accounter. + let root = NamedTag { + name: JavaString::default(), + tag: Tag::compound([("blocks", Tag::List(vec![Tag::Byte(1); 1_000_001]))]), + }; + let bytes = write_named(&root, Limits::templates()).unwrap(); + assert!(read_named(&bytes, Limits::default()).is_err()); + assert_eq!(read_named(&bytes, Limits::templates()).unwrap().0, root); + } + #[test] fn depth_boundary_and_every_truncated_prefix() { let mut tag = Tag::Int(1); for _ in 0..512 { diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 361b2c1d0..4dbbc9ade 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -10,6 +10,7 @@ pub mod mineshaft; pub mod monument; pub mod nether_fossil; pub mod ocean_ruin; +pub mod piece_limited; pub mod processor; pub mod ruined_portal; pub mod simple; @@ -18,6 +19,7 @@ pub mod start_checks; pub mod stronghold; pub mod template; pub mod temple; +pub mod yung; use crate::{ nbt::{self, Limits}, @@ -342,11 +344,7 @@ impl StructureResources { flate2::read::GzDecoder::new(bytes.as_slice()) .read_to_end(&mut raw) .ok()?; - let limits = Limits { - max_bytes: 1 << 28, - ..Limits::default() - }; - let tag = nbt::read_named(&raw, limits).ok()?.0.tag; + let tag = nbt::read_named(&raw, Limits::templates()).ok()?.0.tag; Some(Arc::new(StructureTemplate::from_nbt( &tag, self.registry, diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index a50275941..34a2728f4 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -39,6 +39,9 @@ pub enum PoolElement { legacy: bool, projection: Projection, waterlogging: Option, + /// YUNG's API's rules on the piece (`"horizon:yungsapi"`), read only + /// by its assembler ([`super::yung`]). + yung: Option>, }, Feature { feature: String, @@ -81,11 +84,12 @@ fn opposite(d: Direction) -> Direction { Direction::East => Direction::West, } } -fn step(d: Direction) -> [i32; 3] { +pub(super) fn step(d: Direction) -> [i32; 3] { let n = d.normal(); [n[0], n[1], n[2]] } -fn shuffle(list: &mut [T], random: &mut impl RandomSource) { +/// Util.shuffle. +pub(super) fn shuffle(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, swap); @@ -135,6 +139,10 @@ impl PoolElement { Some("ignore_waterlogging") => Some(false), _ => None, }, + yung: value + .get("horizon:yungsapi") + .map(|rules| super::yung::Rules::decode(rules, resources).map(Box::new)) + .transpose()?, } } "minecraft:feature_pool_element" => Self::Feature { @@ -219,10 +227,13 @@ impl PoolElement { .first() .map(|e| e.shuffled_jigsaws(resources, position, rotation, random)) .unwrap_or_default(), - Self::Single { template, .. } => { + Self::Single { template, yung, .. } => { let mut jigsaws = template_jigsaws(resources, template, position, rotation); shuffle(&mut jigsaws, random); - jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + // YUNG's elements keep the shuffled order. + if yung.is_none() { + jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + } jigsaws } } @@ -230,6 +241,13 @@ impl PoolElement { pub fn ground_level_delta(&self) -> i32 { 1 } + /// YUNG's API's rules, on a piece of one of its structures. + pub fn yung(&self) -> Option<&super::yung::Rules> { + match self { + Self::Single { yung, .. } => yung.as_deref(), + _ => None, + } + } } /// StructureTemplate.getJigsaws: palette chosen by a position-seeded random. fn template_jigsaws( @@ -274,7 +292,7 @@ fn template_jigsaws( }) .collect() } -fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { +pub(super) fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { source.front == opposite(target.front) && (source.rollable || source.top == target.top) && target @@ -285,12 +303,15 @@ fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { #[derive(Debug)] pub struct Pool { - templates: Vec>, - fallback: String, + /// Each element repeated by its weight. + pub(super) templates: Vec>, + /// The elements with their weights, in file order (`rawTemplates`). + pub(super) raw: Vec<(Arc, i32)>, + pub(super) fallback: String, max_size: OnceLock, } impl Pool { - fn random_template(&self, random: &mut impl RandomSource) -> Arc { + pub(super) fn random_template(&self, random: &mut impl RandomSource) -> Arc { if self.templates.is_empty() { return Arc::new(PoolElement::Empty); } @@ -304,7 +325,7 @@ impl Pool { shuffle(&mut copy, random); copy } - fn max_size(&self) -> i32 { + pub(super) fn max_size(&self) -> i32 { *self.max_size.get_or_init(|| { self.templates .iter() @@ -343,7 +364,7 @@ impl Pools { } let pool = self.raw.get(name).and_then(|json| { let value: Value = serde_json::from_str(json).ok()?; - let mut templates = Vec::new(); + let (mut templates, mut raw) = (Vec::new(), Vec::new()); for entry in value["elements"].as_array()? { let element = match PoolElement::decode(&entry["element"], resources, bindings, None) { @@ -355,12 +376,15 @@ impl Pools { return None; } }; - for _ in 0..entry["weight"].as_i64().unwrap_or(1) { + let weight = entry["weight"].as_i64().unwrap_or(1); + for _ in 0..weight { templates.push(element.clone()); } + raw.push((element, weight as i32)); } Some(Arc::new(Pool { templates, + raw, fallback: value["fallback"] .as_str() .unwrap_or("minecraft:empty") @@ -393,7 +417,7 @@ pub struct PoolPiece { pub waterlogging: bool, } impl PoolPiece { - fn moved(&mut self, dy: i32) { + pub(super) fn moved(&mut self, dy: i32) { self.position[1] += dy; self.bounding_box = self.bounding_box.moved([0, dy, 0]); } @@ -466,6 +490,7 @@ fn place_element( legacy, projection, waterlogging: override_liquid, + .. } => { let ignore = if *legacy { IGNORE_STRUCTURE_AND_AIR.get_or_init(|| { @@ -547,13 +572,13 @@ pub struct JigsawConfig<'a> { /// Free space for children: an inclusive container box minus placed boxes. #[derive(Debug)] -struct Free { - container: BoundingBox, - removed: Vec, +pub(super) struct Free { + pub(super) container: BoundingBox, + pub(super) removed: Vec, } impl Free { /// Whether every point of the (0.25-deflated) box lies in free space. - fn fits(&self, b: &BoundingBox) -> bool { + pub(super) fn fits(&self, b: &BoundingBox) -> bool { (0..3).all(|i| b.min[i] >= self.container.min[i] && b.max[i] <= self.container.max[i]) && !self.removed.iter().any(|r| r.intersects(b)) } diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs new file mode 100644 index 000000000..1372f247b --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -0,0 +1,980 @@ +//! The piece-limited jigsaw assembler of Repurposed Structures and Moog's +//! Structure Lib (PieceLimitedJigsawManager, the same code in both), for +//! their structures carried over from a modpack (docs/modpacks.md). Carry +//! maps their jigsaw types to `minecraft:jigsaw` with a +//! `"horizon:piece_limited"` key; vanilla data never has it. +//! +//! ```json +//! "horizon:piece_limited": { +//! "library": "moogs", // or "repurposed": their few differences +//! "min_y": 40, "max_y": 120, // y_allowance: pieces stay inside, unless buried +//! "burying": "lowest_corner", // or "average_land", "lowest_side" +//! "no_liquid": true, // cannot_spawn_in_liquid, as burying reads it +//! "ignore_bounds_pools": ["x:pool"], +//! "land_search": "highest_land", // the Nether variants: or "lowest_land", "fixed_height" +//! "ledge_offset_y": 2, +//! "pieces": [{"name": "x:piece", "required": 1, "min_depth": 3, "max": 2}] +//! } +//! ``` +//! +//! It differs from vanilla's JigsawPlacement: a fresh random seeded by the +//! chunk, the start piece drawn uniformly and moved to the surface at its +//! center, a bounding volume 120 blocks down and 180 up, children drawn by +//! weight from the pools' weighted entries in order (`nextInt(total) + 1`, +//! counted down), pieces capped by template (`max`) and some required +//! (`required`, from `min_depth`), the whole layout retried up to 40 times +//! until every required piece is in, and after it the pieces centred on the +//! chunk corner, then buried in the terrain or moved onto Nether land. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, Junction, PoolElement, PoolPiece, Pools, Projection, can_attach, + shuffle, step, + }, + start::StartContext, +}; +use crate::{ + heightmap::HeightmapType, identifier::Identifier, java_hash_map::JavaHashMap, + worldgen::block_feature::FeatureBlockBindings, +}; +use horizon_core::{ + position::ChunkPos, + random::{LegacyRandom, RandomSource, WorldgenRandom}, +}; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashSet, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// Which mod's copy of the code: they differ in a few post-layout steps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Library { + Moogs, + Repurposed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Burying { + LowestCorner, + AverageLand, + LowestSide, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LandSearch { + Highest, + Lowest, + Fixed, +} + +/// One template's counts (`*_pieces_spawn_counts`). +#[derive(Clone, Debug)] +struct Counted { + required: Option, + min_depth: i32, + max: Option, +} + +/// `"horizon:piece_limited"` of a jigsaw structure. +#[derive(Debug)] +pub struct Config { + library: Library, + min_y: Option, + max_y: Option, + burying: Option, + no_liquid: bool, + ignore_bounds: HashSet, + land_search: Option, + ledge: i32, + /// Counted templates by id, in the order of Java's HashMap of the + /// required pieces (the first one still short is forced in first). + pieces: Vec<(Identifier, Counted)>, +} + +impl Config { + pub fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let mut pieces: Vec<(Identifier, Counted)> = Vec::new(); + for p in v["pieces"].as_array().into_iter().flatten() { + let Some(id) = p["name"].as_str().and_then(|n| Identifier::parse(n).ok()) else { + continue; + }; + let counted = Counted { + required: p["required"].as_i64().map(|n| n as i32), + min_depth: p["min_depth"].as_i64().unwrap_or(0) as i32, + max: p["max"].as_i64().map(|n| n as i32), + }; + // A later entry for the same piece replaces it, as HashMap.put. + match pieces.iter_mut().find(|(k, _)| *k == id) { + Some(slot) => slot.1 = counted, + None => pieces.push((id, counted)), + } + } + // getRequirePieces builds a HashMap of the required ones and the + // assembler copies it (new HashMap(map)): iterate as that copy does. + let mut map = JavaHashMap::default(); + for (i, (id, c)) in pieces.iter().enumerate() { + if c.required.is_some() { + map.put(id.clone(), i); + } + } + let order: Vec = map.copied().entries().map(|(_, &i)| i).collect(); + let mut sorted: Vec<(Identifier, Counted)> = + order.iter().map(|&i| pieces[i].clone()).collect(); + sorted.extend(pieces.iter().filter(|(_, c)| c.required.is_none()).cloned()); + Self { + library: match v["library"].as_str() { + Some("repurposed") => Library::Repurposed, + _ => Library::Moogs, + }, + min_y: int("min_y"), + max_y: int("max_y"), + burying: match v["burying"].as_str() { + Some("lowest_corner") => Some(Burying::LowestCorner), + Some("average_land") => Some(Burying::AverageLand), + Some("lowest_side") => Some(Burying::LowestSide), + _ => None, + }, + no_liquid: v["no_liquid"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds_pools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| Some(p.as_str()?.to_owned())) + .collect(), + land_search: match v["land_search"].as_str() { + Some("highest_land") => Some(LandSearch::Highest), + Some("lowest_land") => Some(LandSearch::Lowest), + Some("fixed_height") => Some(LandSearch::Fixed), + _ => None, + }, + ledge: int("ledge_offset_y").unwrap_or(0), + pieces: sorted, + } + } + fn required(&self) -> impl Iterator { + self.pieces + .iter() + .map(|(_, c)| c) + .filter(|c| c.required.is_some()) + } +} + +/// The counted templates, loaded, in [`Config::pieces`] order. +struct Counts(Vec>); +impl Counts { + fn new(limits: &Config, resources: &StructureResources) -> Self { + Self( + limits + .pieces + .iter() + .map(|(id, _)| { + resources + .template(&id.to_string()) + .unwrap_or_else(|| Arc::new(StructureTemplate::empty())) + }) + .collect(), + ) + } + /// The index of a single element's template among the counted ones. + fn of(&self, element: &PoolElement) -> Option { + let PoolElement::Single { template, .. } = element else { + return None; + }; + self.0.iter().position(|t| Arc::ptr_eq(t, template)) + } +} + +/// PieceLimitedJigsawManager.assembleJigsawStructure and the structure's +/// postLayoutAdjustments: the start's center and the pieces, or None when +/// nothing starts. `start` is the chunk's corner at the sampled start height. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + chunk: ChunkPos, + start: [i32; 3], +) -> Option<([i32; 3], Vec)> { + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_seed(context.seed(), chunk.x, chunk.z); + let rotation = Rotation::random(&mut random); + let pool = pools.get(config.start_pool, resources, bindings)?; + // An empty start pool crashes the mod's generation; nothing starts. + if pool.templates.is_empty() { + return None; + } + let element = pool.random_template(&mut random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let mut first = PoolPiece { + bounding_box: element.bounding_box(start, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = first.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let top = limits.max_y.unwrap_or(i32::MAX); + let bottom = limits.min_y.unwrap_or(i32::MIN); + let cy = match config.project_to { + Some(kind) => { + let y = start[1] + context.base_height(cx, cz, kind); + if y > top || y < bottom { + return None; + } + y + } + None => start[1], + }; + first.moved(cy - (b.min[1] + first.ground_level_delta)); + let start_box = first.bounding_box; + let (start_position, start_rotation) = (first.position, first.rotation); + let counts = Counts::new(limits, resources); + let run_once = limits.required().next().is_none(); + let mut pieces = vec![first]; + let mut attempts = 0; + // `for (attempts = 0; runOnce || doesNotHaveAllRequiredPieces(...); attempts++)`: + // the first test sees the start piece alone. + while run_once || lacks_required(limits, &counts, &pieces) { + if attempts == 40 { + break; + } + if attempts > 0 { + let element = pool.random_template(&mut random); + pieces = vec![PoolPiece { + bounding_box: element.bounding_box(start_position, start_rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start_position, + rotation: start_rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }]; + } else { + pieces.truncate(1); + } + if config.max_depth > 0 { + let r = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - r, cy - 120, cz - r], [cx + r, cy + 180, cz + r]), + removed: vec![start_box], + })); + let buried = limits.burying.is_some(); + let mut assembler = Assembler { + config, + limits, + counted: &counts, + pools, + resources, + bindings, + pieces: std::mem::take(&mut pieces), + states: vec![(free, 0)], + counts: vec![0; limits.pieces.len()], + max_y: if buried { i32::MAX } else { top }, + min_y: if buried { i32::MIN } else { bottom }, + }; + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, &mut random); + } + pieces = assembler.pieces; + } + if run_once { + break; + } + attempts += 1; + } + adjust(config, limits, context, start, &mut pieces); + if pieces.is_empty() { + return None; + } + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + // The builder is cleared when the layout reaches past the build height. + if whole.max[1] > context.max_y() + 1 { + return None; + } + Some(([cx, cy, cz], pieces)) +} + +/// doesNotHaveAllRequiredPieces. +fn lacks_required(limits: &Config, counts: &Counts, pieces: &[PoolPiece]) -> bool { + let mut left: Vec = limits + .pieces + .iter() + .map(|(_, c)| c.required.unwrap_or(0)) + .collect(); + for p in pieces { + if let Some(i) = counts.of(&p.element) { + left[i] -= 1; + } + } + left.iter().any(|&n| n > 0) +} + +/// Moves a piece; Repurposed Structures' movePieceProperly also writes its +/// junctions, all three setters into the source X, so only the last sticks. +fn shift(limits: &Config, piece: &mut PoolPiece, d: [i32; 3]) { + piece.position = std::array::from_fn(|i| piece.position[i] + d[i]); + piece.bounding_box = piece.bounding_box.moved(d); + if limits.library == Library::Repurposed { + for j in &mut piece.junctions { + j.source_x = j.source_z + d[2]; + } + } +} +fn shift_all(limits: &Config, pieces: &mut [PoolPiece], d: [i32; 3]) { + for p in pieces { + shift(limits, p, d); + } +} + +/// The structure's postLayoutAdjustments. +fn adjust( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut Vec, +) { + if pieces.is_empty() { + return; + } + // GeneralUtils.centerAllPieces on the chunk's corner. + let center = pieces[0].bounding_box.center(); + let d = [start[0] - center[0], 0, start[2] - center[2]]; + for p in pieces.iter_mut() { + // Centring uses StructurePiece.move in both mods. + p.position = std::array::from_fn(|i| p.position[i] + d[i]); + p.bounding_box = p.bounding_box.moved(d); + } + let offset_y = start[1]; + let sea = context.sea_level(); + if let Some(search) = limits.land_search { + nether(limits, context, search, offset_y, pieces); + return; + } + let Some(burying) = limits.burying else { + return; + }; + let kind = config.project_to.unwrap_or(HeightmapType::WorldSurfaceWg); + let ocean_floor = matches!( + kind, + HeightmapType::OceanFloorWg | HeightmapType::OceanFloor + ); + let box0 = pieces[0].bounding_box; + let mut land = match burying { + Burying::LowestCorner => [ + (box0.min[0], box0.min[2]), + (box0.min[0], box0.max[2]), + (box0.max[0], box0.min[2]), + (box0.max[0], box0.max[2]), + ] + .into_iter() + .map(|(x, z)| context.base_height(x, z, kind) - 1) + .min() + .unwrap_or(0), + Burying::LowestSide => { + let c = box0.center(); + let mut highest = i32::MAX; + for (x, z) in [ + (box0.min[0], c[2]), + (c[0], box0.max[2]), + (c[0], box0.min[2]), + (box0.max[0], c[2]), + ] { + // getFirstOccupiedHeight (Repurposed's cached free height - 1). + let land = context.base_height(x, z, kind) - 1; + match limits.min_y { + Some(min) if land >= min => highest = land, + Some(_) => {} + None => highest = highest.min(land), + } + } + if let Some(min) = limits.min_y.filter(|_| highest == i32::MAX) { + highest = min; + } + highest + } + Burying::AverageLand => { + average_land(limits, context, kind, ocean_floor, offset_y, pieces); + return; + } + }; + if limits.no_liquid || !ocean_floor { + land = land.max(sea); + } else { + land = land.min(sea - box0.span()[1]); + } + // offsetToNewHeight. + if limits.max_y.is_some() + && let Some(min) = limits.min_y + && box0.max[1] + offset_y < min + { + land = land.max(limits.max_y.unwrap_or(land)); + } + if let Some(min) = limits.min_y + && box0.min[1] + offset_y < min + { + land = land.min(min); + } + let dy = land - box0.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// AVERAGE_LAND: the mean land height over a grid on the first piece's +/// footprint; no structure when none of the heights is allowed. +fn average_land( + limits: &Config, + context: &mut impl StartContext, + kind: HeightmapType, + ocean_floor: bool, + offset_y: i32, + pieces: &mut Vec, +) { + let b = pieces[0].bounding_box; + let c = b.center(); + let (lx, lz) = (b.max[0] - b.min[0], b.max[2] - b.min[2]); + let radius = (f64::from(lx * lx + lz * lz).sqrt() as i32) / 2; + // The mod's loop never ends with a step of 0; one block apart instead. + let step = (radius / 2).max(1); + let (min, max) = ( + limits.min_y.unwrap_or(i32::MIN), + limits.max_y.unwrap_or(i32::MAX), + ); + let (mut sum, mut n) = (0i64, 0i64); + let mut x = -radius; + while x <= radius { + let mut z = -radius; + while z <= radius { + let h = context.base_height(c[0] + x, c[2] + z, kind) - 1; + if h > min && h < max { + sum += i64::from(h); + n += 1; + } + z += step; + } + x += step; + } + let mut average = (n > 0).then(|| sum as f64 / n as f64); + if average.is_none() { + average = limits.max_y.or(limits.min_y).map(f64::from); + } + let Some(mut average) = average else { + pieces.clear(); + return; + }; + if limits.no_liquid && !ocean_floor { + average = average.max(f64::from(context.sea_level())); + if let Some(max) = limits.max_y { + // Math.max, as the mod has it. + average = average.max(f64::from(max)); + } + } + let dy = average as i32 - b.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// The Nether variants: onto the highest or lowest land at the layout's +/// center (or a fixed height), a ledge above it, within y_allowance. +fn nether( + limits: &Config, + context: &mut impl StartContext, + search: LandSearch, + offset_y: i32, + pieces: &mut [PoolPiece], +) { + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + let sea = context.sea_level(); + let generation = context.generation(); + let terrain_limit = generation.min_y + generation.height; + let base = pieces[0].bounding_box.min[1]; + let found = |context: &mut dyn ColumnQuery, highest: bool| { + let c = whole.center(); + context.land(c[0], c[2], highest, !limits.no_liquid, sea, terrain_limit) + }; + let mut target = match (limits.library, search) { + (Library::Moogs, LandSearch::Fixed) => offset_y + limits.ledge, + (library, search) => { + let y = found(context, search == LandSearch::Highest); + let at = if y < terrain_limit && y > sea + 1 { + y + } else { + sea + }; + if library == Library::Repurposed { + shift_all(limits, pieces, [0, at + limits.ledge - base, 0]); + return; + } + at + limits.ledge + offset_y + } + }; + let height = whole.max[1] - whole.min[1]; + let below = whole.min[1] - base; + if let Some(top) = limits.max_y { + target = target.min(top - height - below); + } + if let Some(bottom) = limits.min_y { + target = target.max(bottom - below); + } + shift_all(limits, pieces, [0, target - base, 0]); +} + +/// GeneralUtils.getHighestLand and getLowestLand on the noise column. +trait ColumnQuery { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32; +} +impl ColumnQuery for C { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32 { + let min = self.generation().min_y; + let mut columns = self.base_columns( + x, + z, + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg], + ); + let solid = columns.pop().unwrap_or_default(); + let filled = columns.pop().unwrap_or_default(); + land_in(&filled, &solid, min, highest, on_liquid, sea, terrain_limit) + } +} + +/// The land search over one noise column: `filled` (not air) and `solid` +/// (canOcclude, for the noise's own blocks) from `min` up; past the +/// column's ends a NoiseColumn reads air. +fn land_in( + filled: &[bool], + solid: &[bool], + min: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, +) -> i32 { + let at = |c: &[bool], y: i32| { + usize::try_from(y - min) + .ok() + .and_then(|i| c.get(i).copied()) + .unwrap_or(false) + }; + let air = |y: i32| !at(filled, y); + let stands = |y: i32| if on_liquid { !air(y) } else { at(solid, y) }; + if highest { + let mut y = terrain_limit - 40; + while y > sea { + if at(solid, y) && air(y + 3) && stands(y) { + return y; + } + y -= 1; + } + y + } else { + let mut y = sea + 1; + while y <= terrain_limit - 40 { + if stands(y) && air(y + 1) && air(y + 5) { + return y + 1; + } + y += 1; + } + sea + } +} + +/// PieceLimitedJigsawManager.Assembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + limits: &'a Config, + counted: &'a Counts, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc>, i32)>, + /// Pieces placed per counted template. + counts: Vec, + max_y: i32, + min_y: i32, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +struct Slot<'s> { + source: usize, + jigsaw: &'s super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// generatePiece: one child per jigsaw where one fits, from the target + /// pool unless the piece is at the last depth, else from its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option>> = None; + for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw: &jigsaw, + target_pos, + free, + depth, + }; + if depth != self.config.max_depth + && self.process(&slot, target.raw.clone(), false, queue, context, random) + { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + let ignore = self.limits.ignore_bounds.contains(&target.fallback); + self.process(&slot, fallback.raw.clone(), ignore, queue, context, random); + } + } + /// processList: whether a piece was placed. + fn process( + &mut self, + slot: &Slot<'_>, + mut candidates: Vec<(Arc, i32)>, + ignore_bounds: bool, + queue: &mut VecDeque, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = + |context: &mut dyn SurfaceQuery| *surface.get_or_insert_with(|| context.surface(x, z)); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() { + let mut chosen = None; + // The first required piece still short is forced in once deep enough. + let needed = self + .limits + .pieces + .iter() + .enumerate() + .find(|(i, (_, c))| c.required.is_some_and(|r| self.counts[*i] < r)); + if let Some((need_index, (_, need))) = needed { + let need_template = &self.counted.0[need_index]; + let found = candidates.iter().position(|(e, _)| { + matches!(e.as_ref(), PoolElement::Single { template, .. } + if Arc::ptr_eq(template, need_template)) + }); + if let Some(i) = found { + if slot.depth >= (self.config.max_depth - 1).min(need.min_depth) { + chosen = Some(i); + } else { + total -= candidates[i].1; + candidates.remove(i); + } + } + } + let index = match chosen { + Some(i) => i, + None => { + if total <= 0 || candidates.is_empty() { + return false; + } + let mut weight = random.next_int_bound(total).unwrap_or(0) + 1; + let mut found = candidates.len() - 1; + for (i, (_, w)) in candidates.iter().enumerate() { + weight -= w; + if weight <= 0 { + found = i; + break; + } + } + found + } + }; + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let counted = self.counted.of(&target); + let full = counted.is_some_and(|i| { + self.limits.pieces[i] + .1 + .max + .is_some_and(|m| self.counts[i] >= m) + }); + if full { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if target_box.max[1] > self.max_y || target_box.min[1] < self.min_y { + continue; + } + if !ignore_bounds && !slot.free.borrow().fits(&target_box) { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + self.pieces[slot.source].junctions.push(Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some(i) = counted { + self.counts[i] += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +/// The surface height query, object-safe for the per-call cache. +trait SurfaceQuery { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl SurfaceQuery for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn required_pieces_follow_javas_hash_map() { + let limits = Config::decode(&json!({"library": "repurposed", "pieces": [ + {"name": "rs:city/a", "required": 1}, + {"name": "rs:city/x", "max": 2}, + {"name": "rs:city/b", "required": 1, "min_depth": 3}, + {"name": "rs:city/c", "required": 2}, + {"name": "rs:city/a", "required": 4}]})); + let names: Vec = limits.pieces.iter().map(|(id, _)| id.to_string()).collect(); + // Buckets 3, 2, 1 of the copied map's 4: c, b, a; then the capped one. + assert_eq!(names, ["rs:city/c", "rs:city/b", "rs:city/a", "rs:city/x"]); + assert_eq!( + limits.pieces[2].1.required, + Some(4), + "a later entry replaces" + ); + assert_eq!(limits.pieces[1].1.min_depth, 3); + assert_eq!(limits.library, Library::Repurposed); + } + + #[test] + fn nether_land_is_found_in_the_column() { + // A column from y 0: netherrack to 40, lava 41..=45, air, a ledge 70..=72. + let (mut filled, mut solid) = (vec![false; 128], vec![false; 128]); + for y in 0..=45 { + filled[y] = true; + solid[y] = y <= 40; + } + for y in 70..=72 { + filled[y] = true; + solid[y] = true; + } + // Highest: from 88 down, a solid block with air 3 above. + assert_eq!(land_in(&filled, &solid, 0, true, true, 32, 128), 72); + // Lowest: from 33 up, a block to stand on with air 1 and 5 above; one up. + assert_eq!(land_in(&filled, &solid, 0, false, true, 32, 128), 46); + assert_eq!(land_in(&filled, &solid, 0, false, false, 32, 128), 73); + // Nothing found: the highest search stops at the sea level. + let empty = vec![false; 128]; + assert_eq!(land_in(&empty, &empty, 0, true, true, 32, 128), 32); + assert_eq!(land_in(&empty, &empty, 0, false, true, 32, 128), 32); + } + + #[test] + fn repurposed_moves_junctions_as_its_code_does() { + let template = Arc::new(StructureTemplate::empty()); + let element = Arc::new(PoolElement::Single { + template, + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: None, + }); + let piece = || PoolPiece { + bounding_box: BoundingBox::new([0; 3], [4; 3]), + ground_level_delta: 1, + element: element.clone(), + position: [0; 3], + rotation: Rotation::None, + junctions: vec![Junction { + source_x: 1, + source_ground_y: 2, + source_z: 3, + }], + waterlogging: true, + }; + let moogs = Config::decode(&json!({})); + let rs = Config::decode(&json!({"library": "repurposed"})); + let (mut a, mut b) = (piece(), piece()); + shift(&moogs, &mut a, [10, 20, 30]); + shift(&rs, &mut b, [10, 20, 30]); + assert_eq!(a.bounding_box, BoundingBox::new([10, 20, 30], [14, 24, 34])); + assert_eq!(a.position, [10, 20, 30]); + assert_eq!(a.junctions[0].source_x, 1); + // movePieceProperly sets the source X three times; Z + dz is left. + assert_eq!(b.junctions[0].source_x, 33); + assert_eq!(b.junctions[0].source_ground_y, 2); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index a66f27509..3d61bf168 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -57,6 +57,11 @@ pub struct JigsawDef { waterlogging: bool, /// A carried mod's start rules (`"horizon:start_checks"`). checks: super::start_checks::StartChecks, + /// Laid out by YUNG's API's assembler (`"horizon:yungsapi"`). + yung: Option, + /// Laid out by Repurposed Structures' and Moog's piece-limited + /// assembler (`"horizon:piece_limited"`). + piece_limited: Option, } #[derive(Debug)] pub enum StructureKind { @@ -97,6 +102,9 @@ pub struct StructureDef { pub biomes: BTreeSet, pub step: usize, pub terrain: TerrainAdjustment, + /// Another loaded structure turns this one's type off + /// (`"horizon:disables"`): it never starts. + pub disabled: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Reduction { @@ -137,6 +145,107 @@ pub struct StructureSet { /// (`"horizon:exclusion_zone"`: `other_sets`, `chunk_count`). min_distance: Option, avoid: Option<(Vec, i32)>, + /// `"horizon:ring_sections"`: starts only in odd rings around the origin. + rings: Option, + /// `"horizon:avoid_biomes"`: no start with one of these biomes near. + avoid_biomes: Option, +} + +/// YUNG's Better Strongholds' placement (BetterStrongholdsPlacement +/// .isPlacementChunk): the world is cut into rings `thickness` chunks wide, +/// the first one starting `distance_to_first_ring` chunks out; a start is +/// placed only in the odd ones, and in none past `max_section`. +/// +/// ```json +/// "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96, "max_section": 5} +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +struct RingSections { + first: i32, + thickness: i32, + max: Option, +} +impl RingSections { + fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + first: int("distance_to_first_ring").unwrap_or(0), + thickness: int("thickness").unwrap_or(1).max(1), + max: int("max_section"), + } + } + fn allows(&self, x: i32, z: i32) -> bool { + // Java int arithmetic: the squares wrap past 46,340 chunks, and the + // square root of a negative int is NaN, which casts to 0. + let squared = x.wrapping_mul(x).wrapping_add(z.wrapping_mul(z)); + let distance = f64::from(squared).sqrt() as i32; + let section = distance.wrapping_add(self.thickness - self.first) / self.thickness; + !self.max.is_some_and(|max| section > max) && section % 2 == 1 + } +} + +/// YUNG's Better Desert and Jungle Temples' placement: no start when a +/// biome of the set is found around the chunk's middle block at height `y` +/// (BiomeSource.findBiomeHorizontal with `radius` blocks and `step` quarts +/// between samples, closest first). +/// +/// ```json +/// "horizon:avoid_biomes": {"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], +/// "radius": 48, "step": 2, "y": 120} +/// ``` +#[derive(Debug)] +struct AvoidBiomes { + biomes: BTreeSet, + radius: i32, + step: i32, + y: i32, +} +impl AvoidBiomes { + fn decode( + v: &Value, + biome_set: &dyn Fn(&Value) -> Result, DecodeError>, + ) -> Result { + let mut biomes = BTreeSet::new(); + match &v["biomes"] { + Value::Array(list) => { + for entry in list { + biomes.extend(biome_set(entry)?); + } + } + other => biomes = biome_set(other)?, + } + let int = |k: &str, default: i32| v[k].as_i64().map_or(default, |n| n as i32); + Ok(Self { + biomes, + radius: int("radius", 0), + step: int("step", 1).max(1), + y: int("y", 0), + }) + } + fn near(&self, chunk: ChunkPos, mut biome: impl FnMut([i32; 3]) -> BiomeId) -> bool { + // ChunkPos.getMiddleBlockPosition, then QuartPos.fromBlock. + let (cx, cz) = ((chunk.x * 16 + 8) >> 2, (chunk.z * 16 + 8) >> 2); + let (radius, y) = (self.radius >> 2, self.y >> 2); + let mut r = 0; + while r <= radius { + let mut dz = -r; + while dz <= r { + let z_edge = dz.abs() == r; + let mut dx = -r; + while dx <= r { + if (z_edge || dx.abs() == r) + && self.biomes.contains(&biome([cx + dx, y, cz + dz])) + { + return true; + } + dx += self.step; + } + dz += self.step; + } + r += self.step; + } + false + } } fn heightmap(name: &str) -> Option { @@ -182,8 +291,19 @@ impl StructureRegistry { biome_set: &dyn Fn(&Value) -> Result, DecodeError>, ) -> Result { let mut defs = Vec::new(); + let (mut types, mut disables) = (Vec::new(), BTreeSet::new()); for (name, json) in structures { let v: Value = serde_json::from_str(json)?; + types.push(v["type"].as_str().unwrap_or_default().to_owned()); + // YUNG's mods turn their vanilla counterparts off (the + // DisableVanilla*Mixin on ChunkGenerator.tryGenerateStructure). + disables.extend( + v["horizon:disables"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| Some(t.as_str()?.to_owned())), + ); let kind = match v["type"].as_str().unwrap_or_default() { "minecraft:jigsaw" => StructureKind::Jigsaw(JigsawDef { start_pool: v["start_pool"].as_str().unwrap_or_default().to_owned(), @@ -202,6 +322,10 @@ impl StructureRegistry { padding: pair(v.get("dimension_padding"), "bottom", "top", 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), + yung: v.get("horizon:yungsapi").map(super::yung::Config::decode), + piece_limited: v + .get("horizon:piece_limited") + .map(super::piece_limited::Config::decode), }), "minecraft:buried_treasure" => StructureKind::BuriedTreasure, "minecraft:igloo" => StructureKind::Igloo, @@ -251,8 +375,12 @@ impl StructureRegistry { .position(|s| Some(*s) == v["step"].as_str()) .unwrap_or(4), terrain: terrain(v["terrain_adaptation"].as_str()), + disabled: false, }); } + for (def, kind) in defs.iter_mut().zip(&types) { + def.disabled = disables.contains(kind); + } let index = |name: &str| defs.iter().position(|d| d.name == name); let mut out = Vec::new(); for (name, json) in sets { @@ -314,6 +442,11 @@ impl StructureRegistry { z["chunk_count"].as_i64().unwrap_or(0) as i32, ) }), + rings: p.get("horizon:ring_sections").map(RingSections::decode), + avoid_biomes: p + .get("horizon:avoid_biomes") + .map(|a| AvoidBiomes::decode(a, biome_set)) + .transpose()?, }); } Ok(Self { @@ -420,6 +553,9 @@ impl StructureRegistry { if !placed { return false; } + if set.rings.as_ref().is_some_and(|r| !r.allows(x, z)) { + return false; + } // AdvancedRandomSpread.isPlacementChunk, in blocks from the chunk's corner. if let Some(d) = set.min_distance { let (bx, bz) = (i64::from(x) * 16, i64::from(z) * 16); @@ -591,6 +727,16 @@ pub fn create_starts( if !registry.is_structure_chunk(set, seed, chunk.x, chunk.z, rings) { continue; } + // Part of the set's placement in YUNG's mods; checked here, where the + // biome source is at hand, so another set's exclusion zone naming + // this one does not see it. + if set + .avoid_biomes + .as_ref() + .is_some_and(|a| a.near(chunk, |q| context.noise_biome(q))) + { + continue; + } if set.structures.len() == 1 { if let Some(start) = try_generate( registry, @@ -640,6 +786,9 @@ fn try_generate( chunk: ChunkPos, ) -> Option { let def = ®istry.structures[structure]; + if def.disabled { + return None; + } context.set_valid_biomes(&def.biomes); let seed = context.seed(); let mut random = WorldgenRandom::new(LegacyRandom::new(0)); @@ -669,16 +818,40 @@ fn try_generate( padding: jigsaw.padding, waterlogging: jigsaw.waterlogging, }; - let (position, mut pieces) = assemble( - &config, - context, - ®istry.pools, - resources, - bindings, - &mut random, - start, - )?; - if jigsaw.max_depth <= 0 { + let (position, mut pieces) = match (&jigsaw.yung, &jigsaw.piece_limited) { + (_, Some(limits)) => super::piece_limited::assemble( + &config, + limits, + context, + ®istry.pools, + resources, + bindings, + chunk, + start, + )?, + (Some(yung), None) => super::yung::assemble( + &config, + yung, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + (None, None) => assemble( + &config, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + }; + // Vanilla's JigsawPlacement keeps no piece at size 0; the + // piece-limited assembler keeps the start piece. + if jigsaw.max_depth <= 0 && jigsaw.piece_limited.is_none() { pieces.clear(); } ( @@ -1114,3 +1287,106 @@ pub fn place_in_chunk StructureRegistry { + let text = |l: &[(&str, Value)]| { + l.iter() + .map(|(k, v)| ((*k).to_owned(), v.to_string())) + .collect::>() + }; + // Biome tags: `#t:one` is biome 1, `#t:two` biome 2. + StructureRegistry::new(&text(structures), &text(sets), BTreeMap::new(), &|v| { + Ok(match v.as_str() { + Some("#t:one") => BTreeSet::from([BiomeId(1)]), + Some("#t:two") => BTreeSet::from([BiomeId(2)]), + _ => BTreeSet::new(), + }) + }) + .unwrap() + } + + #[test] + fn a_structure_turns_its_vanilla_counterpart_off() { + let r = registry( + &[ + ( + "minecraft:pyramid", + json!({"type": "minecraft:desert_pyramid"}), + ), + ("minecraft:igloo", json!({"type": "minecraft:igloo"})), + ( + "yung:temple", + json!({"type": "minecraft:swamp_hut", "horizon:disables": ["minecraft:desert_pyramid"]}), + ), + ], + &[], + ); + let disabled: Vec<_> = r + .structures + .iter() + .map(|d| (d.name.as_str(), d.disabled)) + .collect(); + assert_eq!( + disabled, + [ + ("minecraft:igloo", false), + ("minecraft:pyramid", true), + ("yung:temple", false) + ] + ); + } + + #[test] + fn ring_sections_keep_the_odd_rings() { + let rings = RingSections::decode( + &json!({"distance_to_first_ring": 80, "thickness": 96, "max_section": 3}), + ); + // (d + 16) / 96: 0 inside 80 chunks, 1 to 175, 2 to 271, 3 to 367. + assert!(!rings.allows(79, 0)); + assert!(rings.allows(80, 0)); + assert!(rings.allows(0, -175)); + assert!(!rings.allows(176, 0)); + assert!(rings.allows(272, 0)); + assert!(!rings.allows(464, 0), "section 5 is past max_section 3"); + // Java's int square wraps: 50,000² + 0 is negative, its root NaN, 0. + assert!(!rings.allows(50_000, 0)); + let open = RingSections::decode(&json!({"distance_to_first_ring": 80, "thickness": 96})); + assert!(open.allows(464, 0)); + } + + #[test] + fn avoid_biomes_samples_around_the_middle_block() { + let r = registry( + &[], + &[( + "yung:temples", + json!({"structures": [], "placement": {"type": "minecraft:random_spread", + "spacing": 24, "separation": 8, "salt": 1, + "horizon:avoid_biomes": {"biomes": ["#t:one", "#t:two"], + "radius": 48, "step": 2, "y": 120}}}), + )], + ); + let avoid = r.sets[0].avoid_biomes.as_ref().unwrap(); + assert_eq!(avoid.biomes, BTreeSet::from([BiomeId(1), BiomeId(2)])); + // Chunk (1, -1): middle block (24, 120, -8), quart (6, 30, -2). + let mut asked = Vec::new(); + assert!(!avoid.near(ChunkPos::new(1, -1), |q| { + asked.push(q); + BiomeId(0) + })); + assert_eq!(asked[0], [6, 30, -2]); + // Every even offset within 12 quarts, once: 13 x 13. + assert_eq!(asked.len(), 169); + assert!(asked.contains(&[6 - 12, 30, -2 + 12])); + assert!(!asked.contains(&[7, 30, -2])); + // An ocean on the edge of the square is found. + assert!(avoid.near(ChunkPos::new(1, -1), |q| { + BiomeId(if q == [18, 30, 10] { 2 } else { 0 }) + })); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs new file mode 100644 index 000000000..07b363cfb --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -0,0 +1,727 @@ +//! YUNG's API's jigsaw assembler, for the structures of the "YUNG's Better" +//! mods carried over from a modpack (docs/modpacks.md). Carry maps +//! `yungsapi:yung_jigsaw` to `minecraft:jigsaw` with a `"horizon:yungsapi"` +//! key, and its pool elements to vanilla's single element with the piece's +//! rules under the same key; vanilla data never has it. +//! +//! The assembler differs from vanilla's JigsawPlacement: it picks the start +//! piece and every child by weight from the pool's weighted entries (a +//! priority piece first), lays pieces out breadth first, caps pieces by name +//! (`max_count`), limits them by depth, lets some ignore the bounds, checks +//! each piece's condition, and keeps every piece between `min_y` and +//! `max_y`. Pieces fit the same free space as vanilla's. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, JigsawContext, Junction, PoolElement, PoolPiece, Pools, Projection, + can_attach, shuffle, step, + }, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// A YUNG structure's own settings (`"horizon:yungsapi"` on the structure): +/// the heights every piece must stay within. +#[derive(Debug, Default)] +pub struct Config { + pub min_y: Option, + pub max_y: Option, +} +impl Config { + pub fn decode(v: &Value) -> Self { + let y = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + min_y: y("min_y"), + max_y: y("max_y"), + } + } +} + +/// A piece's rules (`"horizon:yungsapi"` on a pool element). +#[derive(Debug, Default)] +pub struct Rules { + /// Pieces sharing a name share the cap `max_count`. + name: Option, + max_count: Option, + min_depth: Option, + max_depth: Option, + /// Chosen before any other piece of its pool. + priority: bool, + /// Placed even where it overlaps other pieces or leaves the bounds. + ignore_bounds: bool, + condition: Condition, +} +impl Rules { + pub fn decode(v: &Value, resources: &StructureResources) -> Result { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Ok(Self { + name: v["name"].as_str().map(str::to_owned), + max_count: int("max_count"), + min_depth: int("min_depth"), + max_depth: int("max_depth"), + priority: v["priority"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds"].as_bool().unwrap_or(false), + condition: match v.get("condition") { + Some(c) => Condition::decode(c, resources)?, + None => Condition::True, + }, + }) + } + /// YungJigsawPoolElement.isAtValidDepth. + fn at_valid_depth(&self, depth: i32) -> bool { + self.min_depth.is_none_or(|d| d <= depth) && self.max_depth.is_none_or(|d| d >= depth) + } + /// The name a capped piece counts under: `max_count` without a name is + /// ignored, as YUNG's does. + fn capped(&self) -> Option<(&str, i32)> { + Some((self.name.as_deref()?, self.max_count?)) + } +} + +/// YUNG's structure conditions, as carry writes them. +#[derive(Debug, Default)] +enum Condition { + #[default] + True, + False, + Not(Box), + AllOf(Vec), + AnyOf(Vec), + Depth { + min: Option, + max: Option, + }, + Altitude { + bottom: Option, + top: Option, + }, + RandomChance(f32), + Rotation(Vec), + /// Another piece (of these templates, or any) within `range` blocks in + /// the direction `rotation` turns the piece's own north. + PieceInDirection { + templates: Vec>, + range: i32, + rotation: Rotation, + }, +} +impl Condition { + fn decode(v: &Value, resources: &StructureResources) -> Result { + let list = |k: &'static str| -> Result, DecodeError> { + v[k].as_array() + .ok_or(DecodeError::Field(k))? + .iter() + .map(|c| Self::decode(c, resources)) + .collect() + }; + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let rotation = |r: &Value| { + r.as_str() + .and_then(Rotation::from_name) + .ok_or(DecodeError::Field("condition rotation")) + }; + Ok(match v["type"].as_str().unwrap_or_default() { + "true" => Self::True, + "false" => Self::False, + "not" => Self::Not(Box::new(Self::decode(&v["condition"], resources)?)), + "all_of" => Self::AllOf(list("conditions")?), + "any_of" => Self::AnyOf(list("conditions")?), + "depth" => Self::Depth { + min: int("min_depth"), + max: int("max_depth"), + }, + "altitude" => Self::Altitude { + bottom: v["bottom"].as_f64(), + top: v["top"].as_f64(), + }, + "random_chance" => Self::RandomChance(v["chance"].as_f64().unwrap_or(0.) as f32), + "rotation" => Self::Rotation( + v["rotations"] + .as_array() + .into_iter() + .flatten() + .map(rotation) + .collect::>()?, + ), + "piece_in_horizontal_direction" => Self::PieceInDirection { + templates: v["pieces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| resources.template(p.as_str()?)) + .collect(), + range: int("range").unwrap_or(0), + rotation: rotation(&v["rotation"])?, + }, + _ => return Err(DecodeError::Field("YUNG condition type")), + }) + } + /// StructureCondition.passes. `at` is the piece being placed: its box, + /// rotation and depth; the start piece has no box yet. + fn passes(&self, at: &At<'_>, random: &mut impl RandomSource) -> bool { + match self { + Self::True => true, + Self::False => false, + Self::Not(c) => !c.passes(at, random), + Self::AllOf(all) => all.iter().all(|c| c.passes(at, random)), + Self::AnyOf(any) => any.iter().any(|c| c.passes(at, random)), + Self::Depth { min, max } => { + min.is_none_or(|d| d <= at.depth) && max.is_none_or(|d| d >= at.depth) + } + Self::Altitude { bottom, top } => { + let [low, high] = at.piece.map_or([0, 0], |b| [b.min[1], b.max[1]]); + bottom.is_none_or(|y| f64::from(low) >= y) + && top.is_none_or(|y| f64::from(high) <= y) + } + Self::RandomChance(chance) => random.next_float() < *chance, + Self::Rotation(valid) => valid.contains(&at.rotation), + Self::PieceInDirection { + templates, + range, + rotation, + } => { + let Some(piece) = at.piece else { + return false; + }; + let mut search = piece; + match at.rotation.get_rotated(*rotation) { + Rotation::None => search.min[2] -= range, + Rotation::Clockwise90 => search.max[0] += range, + Rotation::Clockwise180 => search.max[2] += range, + Rotation::Counterclockwise90 => search.min[0] -= range, + } + at.pieces.iter().any(|other| { + let PoolElement::Single { template, .. } = other.element.as_ref() else { + return false; + }; + let b = other.bounding_box; + b != piece + && (templates.is_empty() + || templates.iter().any(|t| Arc::ptr_eq(t, template))) + && b.intersects(&search) + && !b.intersects(&piece) + }) + } + } + } +} + +/// The surface height query, object-safe for the per-call cache. +trait JigsawContextDyn { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl JigsawContextDyn for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +/// What a condition sees of the piece being placed. +struct At<'a> { + depth: i32, + rotation: Rotation, + piece: Option, + pieces: &'a [PoolPiece], +} + +/// The index of the entry to try: the first priority piece, else one drawn +/// by weight (`nextInt(total) + 1`, counted down). +fn pick( + candidates: &[(Arc, i32)], + total: i32, + random: &mut impl RandomSource, +) -> usize { + if let Some(i) = candidates + .iter() + .position(|(e, _)| e.yung().is_some_and(|r| r.priority)) + { + return i; + } + let mut chosen = random.next_int_bound(total).unwrap_or(0) + 1; + for (i, (_, weight)) in candidates.iter().enumerate() { + chosen -= weight; + if chosen <= 0 { + return i; + } + } + candidates.len() - 1 +} + +/// JigsawManager.assembleJigsawStructure: the start position and the +/// pieces, or None when no start piece fits. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + yung: &Config, + context: &mut impl JigsawContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + position: [i32; 3], +) -> Option<([i32; 3], Vec)> { + let pool = pools.get(config.start_pool, resources, bindings)?; + let mut candidates = pool.raw.clone(); + shuffle(&mut candidates, random); + let rotation = Rotation::random(random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + let (element, adjusted, local) = loop { + if candidates.is_empty() || total <= 0 { + return None; + } + let index = pick(&candidates, total, random); + let (element, weight) = candidates[index].clone(); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let anchored = match config.start_jigsaw { + Some(name) => { + element + .shuffled_jigsaws(resources, position, rotation, random) + .into_iter() + .find(|j| j.name.as_deref() == Some(name))? + .pos + } + None => position, + }; + let local: [i32; 3] = std::array::from_fn(|i| anchored[i] - position[i]); + let adjusted: [i32; 3] = std::array::from_fn(|i| position[i] - local[i]); + let at = At { + depth: 0, + rotation, + piece: None, + pieces: &[], + }; + if element + .yung() + .is_some_and(|r| !r.condition.passes(&at, random)) + { + total -= weight; + candidates.remove(index); + continue; + } + break (element, adjusted, local); + }; + let mut start = PoolPiece { + bounding_box: element.bounding_box(adjusted, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: adjusted, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = start.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let bottom = match config.project_to { + Some(kind) => position[1] + context.base_height(cx, cz, kind), + None => adjusted[1], + }; + start.moved(bottom - (b.min[1] + start.ground_level_delta)); + let cy = bottom + local[1]; + let d = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - d, cy - d, cz - d], [cx + d, cy + d, cz + d]), + removed: vec![start.bounding_box], + })); + let mut assembler = Assembler { + config, + yung, + pools, + resources, + bindings, + pieces: vec![start], + states: vec![(free, 0)], + counts: HashMap::new(), + }; + if config.max_depth > 0 { + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, random); + } + } + Some(([cx, cy, cz], assembler.pieces)) +} + +/// JigsawStructureAssembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + yung: &'a Config, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc>, i32)>, + /// Pieces placed per capped name. + counts: HashMap, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +struct Slot<'s> { + source: usize, + jigsaw: &'s super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// JigsawStructureAssembler.Settings.isInBounds. + fn in_bounds(&self, y: i32, context: &impl JigsawContext) -> bool { + self.yung.max_y.is_none_or(|m| y <= m) + && self.yung.min_y.is_none_or(|m| y >= m) + && y >= context.min_y() + self.config.padding[0] + && y <= context.max_y() + 1 - self.config.padding[1] + } + /// addChildrenForPiece: one child per jigsaw where one fits, from the + /// target pool unless the piece is at the last depth, else its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option>> = None; + for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + if fallback.templates.is_empty() && target.fallback != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw: &jigsaw, + target_pos, + free, + depth, + }; + let placed = depth != self.config.max_depth + && self.choose(&slot, target.raw.clone(), queue, context, random); + if !placed { + self.choose(&slot, fallback.raw.clone(), queue, context, random); + } + } + } + /// chooseCandidateFromPool: whether a piece was placed. + fn choose( + &mut self, + slot: &Slot<'_>, + mut candidates: Vec<(Arc, i32)>, + queue: &mut VecDeque, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + // The surface at the jigsaw, read once per call. + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = |context: &mut dyn JigsawContextDyn| { + *surface.get_or_insert_with(|| context.surface(x, z)) + }; + shuffle(&mut candidates, random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() && total > 0 { + let index = pick(&candidates, total, random); + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let rules = target.yung(); + let capped = rules.and_then(Rules::capped); + let full = capped + .is_some_and(|(name, max)| self.counts.get(name).copied().unwrap_or(0) >= max); + if full || rules.is_some_and(|r| !r.at_valid_depth(slot.depth)) { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if !self.in_bounds(target_box.max[1], context) + || !self.in_bounds(target_box.min[1], context) + { + continue; + } + if !rules.is_some_and(|r| r.ignore_bounds) + && !slot.free.borrow().fits(&target_box) + { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + let at = At { + depth: slot.depth + 1, + rotation, + piece: Some(target_box), + pieces: &self.pieces, + }; + if rules.is_some_and(|r| !r.condition.passes(&at, random)) { + continue; + } + self.pieces[slot.source].junctions.push(Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some((name, _)) = capped { + *self.counts.entry(name.to_owned()).or_default() += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + fn single(template: &Arc, rules: Option) -> Arc { + Arc::new(PoolElement::Single { + template: template.clone(), + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: rules.map(Box::new), + }) + } + + #[test] + fn picks_priority_pieces_then_by_weight() { + let t = Arc::new(StructureTemplate::empty()); + let plain = single(&t, None); + let first = single( + &t, + Some(Rules { + priority: true, + ..Rules::default() + }), + ); + let mut random = LegacyRandom::new(7); + let list = vec![(plain.clone(), 3), (first, 1)]; + assert_eq!(pick(&list, 4, &mut random), 1); + // By weight: nextInt(total) + 1, counted down; the first entry + // takes draws 1..=3 of 4. + let list = vec![(plain.clone(), 3), (plain, 1)]; + let mut ours = LegacyRandom::new(42); + let mut theirs = LegacyRandom::new(42); + for _ in 0..32 { + let draw = theirs.next_int_bound(4).unwrap() + 1; + assert_eq!(pick(&list, 4, &mut ours), usize::from(draw > 3)); + } + } + + #[test] + fn rules_cap_by_name_and_depth() { + let rules = Rules { + name: Some("room".into()), + max_count: Some(2), + min_depth: Some(1), + max_depth: Some(3), + ..Rules::default() + }; + assert_eq!(rules.capped(), Some(("room", 2))); + assert!(!rules.at_valid_depth(0) && rules.at_valid_depth(1) && !rules.at_valid_depth(4)); + // max_count without a name is ignored, as YUNG's does. + let unnamed = Rules { + max_count: Some(1), + ..Rules::default() + }; + assert_eq!(unnamed.capped(), None); + } + + #[test] + fn conditions() { + let t = Arc::new(StructureTemplate::empty()); + let other = Arc::new(StructureTemplate::empty()); + let neighbour = PoolPiece { + element: single(&t, None), + position: [0; 3], + ground_level_delta: 1, + rotation: Rotation::None, + bounding_box: BoundingBox::new([0, 0, -6], [4, 4, -1]), + junctions: Vec::new(), + waterlogging: true, + }; + let pieces = [neighbour]; + let at = |rotation, depth| At { + depth, + rotation, + piece: Some(BoundingBox::new([0, 10, 0], [4, 14, 4])), + pieces: &pieces, + }; + let mut random = LegacyRandom::new(1); + let depth = Condition::Depth { + min: Some(2), + max: None, + }; + assert!(!depth.passes(&at(Rotation::None, 1), &mut random)); + assert!(depth.passes(&at(Rotation::None, 2), &mut random)); + let altitude = |bottom, top| Condition::Altitude { bottom, top }; + assert!(altitude(Some(10.), Some(14.)).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(Some(10.5), None).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(None, Some(13.9)).passes(&at(Rotation::None, 0), &mut random)); + // North (-Z) of an unrotated piece, within 5 blocks; the neighbour + // stays below it in Y, but only X and Z are searched, and it must + // not overlap the piece itself. + let north = |templates, rotation| Condition::PieceInDirection { + templates, + range: 5, + rotation, + }; + assert!(!north(Vec::new(), Rotation::None).passes(&at(Rotation::None, 1), &mut random)); + let low = At { + piece: Some(BoundingBox::new([0, 0, 0], [4, 4, 4])), + ..at(Rotation::None, 1) + }; + assert!(north(Vec::new(), Rotation::None).passes(&low, &mut random)); + assert!(north(vec![t.clone()], Rotation::None).passes(&low, &mut random)); + assert!(!north(vec![other], Rotation::None).passes(&low, &mut random)); + // The piece turned 180°: its north is south. + let turned = At { + rotation: Rotation::Clockwise180, + ..low + }; + assert!(!north(Vec::new(), Rotation::None).passes(&turned, &mut random)); + assert!(north(Vec::new(), Rotation::Clockwise180).passes(&turned, &mut random)); + let all = Condition::AllOf(vec![ + Condition::True, + Condition::Not(Box::new(Condition::False)), + Condition::Rotation(vec![Rotation::Clockwise180]), + ]); + assert!(all.passes(&turned, &mut random)); + assert!(!Condition::AnyOf(vec![Condition::False]).passes(&turned, &mut random)); + } +} diff --git a/docs/modpacks.md b/docs/modpacks.md index 1ecaed8bb..3dced2eee 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -439,6 +439,35 @@ Two cases the oracle fills in: template has them); 1,427 processors of 146 types in ATM10's mods, the most common `lithostitched:block_swap`, Formations' `biome_replacements` and Repurposed Structures' pillar, fluid and void processors. Porting the common ones is next. + - **Big templates** (#838). Vanilla reads structure templates with no limit on their tag + count; Horizon now does too (`nbt::Limits::templates`). Seven of ATM10's 8,962 carried + templates are past the old 1,000,000-tag cap: YUNG's monument start, four When Dungeons + Arise main pieces and two Nullscape pieces. They used to load as empty templates, so their + structures never started. + - **Additions to other sets and pools** (#832 in the game, #833 in carry). A set or pool file + holding `horizon:add_to` appends its entries to the sets or pools it names (docs/mods.md). + Carry writes these from lithostitched's `add_structure_set_entries` and + `add_template_pool_elements` modifiers whose load conditions hold for the mods ported + along, and from CTOV's Java registration: its 21 village types and 11 outposts join + vanilla's `villages` and `pillager_outposts` with the mod's default weights. + - **YUNG's API** (#839, #846 in the game; #840, #847 in carry). `yungsapi:yung_jigsaw` and its + elements become vanilla's jigsaw and single element, with their rules under + `horizon:yungsapi`. The game assembles them as YUNG's `JigsawManager` does: priority + pieces, caps by name, depth ranges, `ignore_bounds` and the conditions tree. YUNG's + placements become `horizon:` keys on a random spread: `horizon:exclusion_zone` for the + enhanced exclusion zone, `horizon:avoid_biomes` for the temples' ocean and river search, + `horizon:ring_sections` for Better Strongholds' rings. `horizon:disables` on a YUNG + structure turns off the vanilla type its mod's mixin turns off. It is written only when + the game can start the replacement, so vanilla mineshafts stay while Better Mineshafts (a + Java type) can't. + - **Repurposed Structures' and Moog's own assembler** (#850 in the game, #851 in carry). Both + lay out their jigsaws with `PieceLimitedJigsawManager`, not vanilla's. Their structures, the + Nether variants too, get `horizon:piece_limited`: `y_allowance`, burying, the pools whose + fallbacks ignore the bounds, liquid, the Nether land search and ledge, and each + structure's piece caps and required pieces from the mod's `*_pieces_spawn_counts` files. + The game assembles them the mods' way and runs their post-layout steps (centring, + burying, the Nether land search). + Each mod's `carry-report.json` lists what was mapped, the rules and processors lost by name, and the types left as they are. NeoForge's convention biome tags (`#c:is_forest`, ...) come @@ -453,19 +482,22 @@ Two cases the oracle fills in: ChoiceTheorem's Overhauled Village 66), and 103 convention biome tags written. - When Dungeons Arise, Structory and Towns and Towers use vanilla's types already. - Still lost, written in Java: - - YUNG's API: its own jigsaw assembler (priority pieces, per-piece caps, conditions, - enhanced terrain adaptation) and 491 elements and jigsaws, behind every "YUNG's Better" - mod; - - Formations' structure and element types (179); - - the nether jigsaw variants of Moog's and Repurposed (69), which search the column for - land after the layout; - - Moog's and Repurposed's layout rules: they centre the pieces on the start, bury or lift - the structure to the terrain and cap pieces per pool; - - Repurposed's mineshafts, mansions, monuments and cities, and MO Structures (38; its - library is only on CurseForge). - - CTOV's villages and outposts are added to vanilla's `villages` and `pillager_outposts` - sets by Java code, as lithostitched's `add_structure_set_entries` worldgen modifiers do for - many packs; a content mod has no way to add to a vanilla set yet, so none start. + - Formations' structure and element types (179): their placements read block states in the + noise column (solid, water, lava), which the structure context doesn't give yet; + - Repurposed's mineshafts, mansions, monuments, Nether cities and shipwrecks, Better + Mineshafts and two Better Dungeons types: Java structure types; + - YUNG's and Moog's enhanced terrain adaptation, YUNG's piece modifiers and dead-end pools, + and the processors written in Java (YUNG's spawners, chests, banners; 29 in Better Dungeons + alone), so these structures place their template blocks only; + - MO Structures (38; its library is only on CurseForge). + + With every structure PR above, the same square (seed 1234, chunks -64..63) holds 362 + overworld starts with 22,026 pieces. CTOV has 7, Better Dungeons 72 and Better Ocean + Monuments 3, and vanilla's monuments are gone as YUNG's mod has them. In the Nether there + are 512 starts, up from 322: Moog's Nether Structures 147, Repurposed's Nether structures + 40, Better Fortresses 7, with no vanilla fortress. Over chunks -256..255: Better Strongholds 10 + (vanilla 0), Better Jungle Temples 5, Better Witch Huts 11. Vanilla's own worlds are + unchanged: the structure-start oracle still matches 35 of 35. In a world with the 40 mods, seed 1234, `/locate structure mvs:azelea_house` finds one 27 blocks from spawn and it stands there as the template builds it; When Dungeons Arise's diff --git a/docs/mods.md b/docs/mods.md index d1556abd7..bdf45f620 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -287,6 +287,22 @@ its row. The game reads this content into its block and item tables nobody registers (a block a port left out, another mod's item) is dropped, so the rest of the tag still loads; vanilla would drop the whole tag. +A mod adds to structure sets and template pools that are not its own +(vanilla's villages, another mod's houses) with a set or pool file in its own +namespace holding `horizon:add_to`, a key vanilla data never has. Its entries +are appended to each set or pool named, after every mod's own files, in mod +and file order; the file is no set or pool itself. A name nobody defines is +skipped. + +```json +{ "horizon:add_to": "minecraft:villages", + "structures": [ { "structure": "mymod:village_beach", "weight": 10 } ] } +``` + +A pool addition holds `"elements"` as a pool does. This is what lithostitched's +`add_structure_set_entries` and `add_template_pool_elements` modifiers do on +NeoForge and Fabric, and `horizon-port-pack carry` writes them from those. + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and