diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index 75c2d8408..7b9bc8fee 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -47,6 +47,11 @@ pub struct Report { pub items_unknown: BTreeMap, /// Convention (`c:`) tags the recipes use, filled in from the oracle. pub convention_tags: usize, + /// Structure, placement and pool element types rewritten as vanilla's, + /// and those left as they are. + pub worldgen_types: crate::worldgen::Upgrade, + /// The loader's convention biome tags the structures name, carried. + pub convention_biome_tags: usize, } /// Vanilla blocks by their sorted property names. @@ -333,6 +338,7 @@ pub fn carry( out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, + conventions: &BTreeMap, ) -> Result { let id = &info.mod_id; if id.is_empty() @@ -355,6 +361,7 @@ pub fn carry( let mut item_models = BTreeSet::new(); let mut convention = BTreeSet::new(); let mut block_loot = BTreeSet::new(); + let mut biome_conventions = BTreeSet::new(); 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(); @@ -404,6 +411,24 @@ pub fn carry( report.recipes_kept.push(file.to_owned()); } } + } else if let Some(kind) = rel + .strip_prefix("worldgen/") + .and_then(|r| r.split_once('/')) + .map(|(kind, _)| kind) + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + if let Ok(mut v) = serde_json::from_slice::(&bytes) { + if kind == "structure" { + crate::worldgen::convention_tags(&v["biomes"], &mut biome_conventions); + } + if crate::worldgen::upgrade(kind, &mut v, &mut report.worldgen_types) { + bytes = serde_json::to_vec_pretty(&v).unwrap_or(bytes); + } + } + } 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); + } } else if rel.starts_with("loot_table/") && name.starts_with("data/") { if let Some(b) = rel .strip_prefix("loot_table/blocks/") @@ -445,6 +470,18 @@ pub fn carry( report.item_definitions_added += 1; } } + // The loader's convention biome tags the structures and their tags name + // (NeoForge's `c:is_plains`...): the game has no loader, so they come along. + for tag in crate::worldgen::with_included(&biome_conventions, conventions) { + let file = inside.join(format!("data/c/tags/worldgen/biome/{tag}.json")); + if !file.exists() { + write( + &file, + &serde_json::to_vec_pretty(&conventions[&tag]).unwrap_or_default(), + )?; + report.convention_biome_tags += 1; + } + } let decl = inside.join(format!("data/{id}/horizon")); let write_decl = |kind: &str, name: &str, v: &Value| { let text = serde_json::to_vec_pretty(v).unwrap_or_default(); @@ -819,7 +856,7 @@ mod tests { ); assert_eq!(info.census.classes, 1); let out = dir.join("work/mods/gem"); - let report = carry(&jar, &info, &out, None, &|_| true).unwrap(); + let report = carry(&jar, &info, &out, None, &|_| true, &BTreeMap::new()).unwrap(); assert_eq!(report.copied, 13); let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect(); assert_eq!( diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs index 011e99e1f..f8f7b2dc7 100644 --- a/crates/horizon-port-pack/src/fetch.rs +++ b/crates/horizon-port-pack/src/fetch.rs @@ -139,6 +139,28 @@ pub fn fetch( } fetched.files.push(o); } + // The loader's own data (its convention tags), from its own repository. + if let Some((dest, url)) = crate::worldgen::loader_jar(work, &pack.loader, &pack.loader_version) + .filter(|(dest, _)| !dest.exists()) + { + let sha1 = ureq::get(&format!("{url}.sha1")) + .set("User-Agent", modrinth::AGENT) + .call() + .ok() + .and_then(|r| r.into_string().ok()) + .map(|s| s.trim().to_owned()); + let made = dest.parent().map(fs::create_dir_all); + match made + .unwrap_or(Ok(())) + .map_err(|e| e.to_string()) + .and_then(|()| download(&url, sha1.as_deref(), &dest)) + { + Ok(()) => log(format!("loader: {}", dest.display())), + Err(e) => log(format!( + "loader: {e} (structures keep only vanilla biome tags)" + )), + } + } write_json(&work.join("fetch.json"), &fetched)?; log(format!( "jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed", diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index ecd61956c..0e678fb9a 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -15,3 +15,4 @@ pub mod modrinth; pub mod oracle; pub mod pipeline; pub mod report; +pub mod worldgen; diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 0fe87d181..3afe5b3a3 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -119,6 +119,7 @@ pub fn carry( .ok() }); 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() { @@ -154,6 +155,7 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, + &conventions, ) { Ok(report) => { done += 1; diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs new file mode 100644 index 000000000..c44cc1108 --- /dev/null +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -0,0 +1,262 @@ +//! Structure mods' worldgen, carried over: the structure, placement and pool +//! element types of the common structure libraries rewritten as vanilla's, +//! and the loader's convention biome tags (`c:`) the structures name. +//! +//! The libraries' types add rules on top of vanilla's (a structure that may +//! not start in liquid, a minimum distance from the world origin, a count +//! cap per piece). Mapped to vanilla, those rules are lost: the structure +//! keeps its pieces and its spacing but can start where the mod would not. +//! Each rewrite is counted in the carry report, and every type left as it is +//! is listed, so the coverage report can say what generates and how closely. +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::Read, + path::{Path, PathBuf}, +}; + +/// Structure types that are vanilla's jigsaw with extra start rules. +const JIGSAWS: [&str; 3] = [ + "lithostitched:jigsaw", + "moogs_structures:moogs_structures_generic_jigsaw_structure", + "repurposed_structures:generic_jigsaw_structure", +]; +/// Placements that are vanilla's random spread with extra rules. +const SPREADS: [&str; 2] = [ + "moogs_structures:advanced_random_spread", + "repurposed_structures:advanced_random_spread", +]; +/// Pool elements that are vanilla's with extra fields: (mod type, vanilla type). +const ELEMENTS: [(&str, &str); 3] = [ + ( + "moogs_structures:versioned_single_pool_element", + "minecraft:single_pool_element", + ), + ( + "repurposed_structures:legacy_ocean_bottom_single_pool_element", + "minecraft:legacy_single_pool_element", + ), + ("empty_pool_element", "minecraft:empty_pool_element"), +]; + +/// What carry-over did to a mod's worldgen files. +#[derive(Debug, Default, serde::Serialize)] +pub struct Upgrade { + /// Files rewritten to vanilla types. + pub mapped: usize, + /// Types left as they are (Horizon skips what it cannot run), by type. + pub unsupported: BTreeMap, +} + +/// Rewrites one `data//worldgen//...` file in place; whether it +/// changed. +pub fn upgrade(kind: &str, v: &mut Value, report: &mut Upgrade) -> bool { + 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) => { + v["type"] = "minecraft:jigsaw".into(); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "structure_set" => match v["placement"]["type"].as_str() { + Some(t) if SPREADS.contains(&t) => { + v["placement"]["type"] = "minecraft:random_spread".into(); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "template_pool" => { + let mut changed = false; + let mut elements: Vec<&mut Value> = Vec::new(); + for e in v["elements"].as_array_mut().into_iter().flatten() { + let element = &mut e["element"]; + // A list element holds elements of its own. + if element.get("elements").is_some_and(Value::is_array) { + elements.extend(element["elements"].as_array_mut().into_iter().flatten()); + } else { + elements.push(element); + } + } + for element in elements { + let Some(t) = element["element_type"].as_str() else { + continue; + }; + if let Some((_, to)) = ELEMENTS.iter().find(|(from, _)| *from == t) { + element["element_type"] = (*to).into(); + changed = true; + } else if !t.starts_with("minecraft:") { + unsupported(t); + } + } + changed + } + _ => false, + }; + report.mapped += usize::from(changed); + changed +} + +/// The `#c:` biome tags `v` names. +pub fn convention_tags(v: &Value, out: &mut BTreeSet) { + match v { + Value::String(s) => { + if let Some(tag) = s.strip_prefix("#c:") { + out.insert(tag.to_owned()); + } + } + Value::Array(a) => a.iter().for_each(|x| convention_tags(x, out)), + Value::Object(o) => o.values().for_each(|x| convention_tags(x, out)), + _ => {} + } +} + +/// The loader's own convention biome tags (`data/c/tags/worldgen/biome/`), +/// by path, read from the loader jar `fetch` keeps in `/loader/`. +pub fn loader_biome_tags(work: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(dir) = std::fs::read_dir(work.join("loader")) else { + return out; + }; + for jar in dir.flatten().map(|e| e.path()) { + let Some(mut zip) = std::fs::File::open(&jar) + .ok() + .and_then(|f| zip::ZipArchive::new(f).ok()) + else { + continue; + }; + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some(path) = entry + .name() + .strip_prefix("data/c/tags/worldgen/biome/") + .and_then(|p| p.strip_suffix(".json")) + .map(str::to_owned) + else { + continue; + }; + let mut text = String::new(); + if entry.read_to_string(&mut text).is_ok() { + if let Ok(v) = serde_json::from_str(&text) { + out.insert(path, v); + } + } + } + } + out +} + +/// `tags` and the convention tags they include, in `conventions`. +pub fn with_included( + tags: &BTreeSet, + conventions: &BTreeMap, +) -> BTreeSet { + let mut all = BTreeSet::new(); + let mut todo: Vec = tags.iter().cloned().collect(); + while let Some(tag) = todo.pop() { + if !conventions.contains_key(&tag) || !all.insert(tag.clone()) { + continue; + } + let mut more = BTreeSet::new(); + convention_tags(&conventions[&tag], &mut more); + todo.extend(more); + } + all +} + +/// Where `fetch` keeps the pack's loader jar, and where it comes from: +/// NeoForge's own Maven repository. Only NeoForge packs need it today. +pub fn loader_jar(work: &Path, loader: &str, version: &str) -> Option<(PathBuf, String)> { + (loader == "neoforge" && !version.is_empty()).then(|| { + ( + work.join("loader").join(format!("neoforge-{version}-universal.jar")), + format!( + "https://maven.neoforged.net/releases/net/neoforged/neoforge/{version}/neoforge-{version}-universal.jar" + ), + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn maps_library_types_to_vanillas() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "lithostitched:jigsaw", "start_pool": "a:b"}); + assert!(upgrade("structure", &mut s, &mut report)); + 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)); + 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)); + assert_eq!(set["placement"]["type"], "minecraft:random_spread"); + assert_eq!(set["placement"]["spacing"], 10); + let mut pool = json!({"elements": [ + {"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"}} + ]}); + assert!(upgrade("template_pool", &mut pool, &mut report)); + assert_eq!( + pool["elements"][0]["element"]["element_type"], + "minecraft:single_pool_element" + ); + assert_eq!( + pool["elements"][1]["element"]["elements"][0]["element_type"], + "minecraft:empty_pool_element" + ); + assert_eq!(report.mapped, 3); + assert_eq!( + report.unsupported, + BTreeMap::from([ + ( + "moogs_structures:moogs_structures_generic_nether_jigsaw_structure".into(), + 1 + ), + ("yungsapi:yung_single_element".into(), 1), + ]) + ); + } + + #[test] + fn convention_tags_include_theirs() { + let conventions = BTreeMap::from([ + ( + "is_hot".to_owned(), + json!({"values": ["#c:is_desert", "#minecraft:is_badlands"]}), + ), + ( + "is_desert".to_owned(), + json!({"values": ["minecraft:desert"]}), + ), + ("is_cold".to_owned(), json!({"values": []})), + ]); + let mut used = BTreeSet::new(); + convention_tags( + &json!({"biomes": ["#c:is_hot", "#c:unknown", "#minecraft:x"]}), + &mut used, + ); + assert_eq!(used, BTreeSet::from(["is_hot".into(), "unknown".into()])); + assert_eq!( + with_included(&used, &conventions), + BTreeSet::from(["is_hot".into(), "is_desert".into()]) + ); + } +}