diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index 03b5d7dc9..42c0483b4 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -814,7 +814,7 @@ pub fn carry( if kind == "structure" { let path = rel.trim_start_matches("worldgen/structure/"); let structure = format!("{ns}:{}", path.trim_end_matches(".json")); - changed |= crate::worldgen::disables(&structure, &mut v); + changed |= crate::legacy_structure_mods::yung::disables(&structure, &mut v); changed |= crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); } @@ -829,9 +829,9 @@ pub fn carry( // 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)) - { + if let Some((kind, mut added)) = modifier.and_then(|v| { + crate::legacy_structure_mods::lithostitched::modifier(&v, loaded, types) + }) { crate::processors::carry( kind, &mut added, @@ -910,7 +910,7 @@ pub fn carry( } // 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) { + for (file, set, entries) in crate::legacy_structure_mods::ctov::code_set_entries(id) { let entries: Vec = entries .into_iter() .filter(|(s, _)| { diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs b/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs new file mode 100644 index 000000000..af46174ae --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/ctov.rs @@ -0,0 +1,179 @@ +//! Choice Theorem's Overhauled Village: the entries it adds to other +//! structure sets in Java code, and its `modular_compat` processor. +use crate::processors::{ProcessorData, referenced}; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; + +/// 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(crate) 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(), + } +} + +/// Choice Theorem's Overhauled Village's processor that runs the list +/// `reference` when mod `modid` is loaded (ModularCompatProcessor). +const MODULAR_COMPAT: &str = "ctov:modular_compat"; + +/// Notes which mods its compat processors name are `loaded`. +pub(crate) fn mark_loaded(data: &mut ProcessorData, loaded: &dyn Fn(&str) -> bool) { + fn walk(v: &Value, out: &mut BTreeSet) { + match v { + Value::Object(o) => { + if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { + if let Some(id) = o.get("modid").and_then(Value::as_str) { + out.insert(id.to_owned()); + } + } + o.values().for_each(|v| walk(v, out)); + } + Value::Array(a) => a.iter().for_each(|v| walk(v, out)), + _ => {} + } + } + let mut named = BTreeSet::new(); + data.lists.values().for_each(|l| walk(l, &mut named)); + data.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); +} + +/// A `ctov:modular_compat` processor in a list being carried, at `depth` +/// (see [`super::lithostitched`]'s references): counted in `carried`, and +/// the processors of the list it names when its mod is loaded, else none. +/// `None` for any other processor, or past the depth limit. +pub(super) fn modular_compat( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, +) -> Option> { + if p["processor_type"] != MODULAR_COMPAT || depth >= 8 { + return None; + } + *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; + let loaded = p["modid"] + .as_str() + .is_some_and(|m| data.compat_loaded.contains(m)); + Some( + loaded + .then(|| referenced(&p["reference"], data)) + .flatten() + .unwrap_or_default(), + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::processors::carry; + use serde_json::json; + + #[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 modular_compat_runs_its_list_only_with_its_mod() { + let mut data = ProcessorData::default(); + let swap = json!({"processor_type": "minecraft:rule", "rules": []}); + data.lists + .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); + let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); + let gravity = json!({"processor_type": "minecraft:gravity"}); + data.lists.insert( + "v:house".into(), + json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), + ); + data.mark_loaded(&|m| m == "ns"); + assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); + let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut v, &data, &mut carried)); + assert_eq!(v, json!({"processors": [swap, gravity]})); + assert_eq!(carried["ctov:modular_compat"], 2); + } +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs b/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs new file mode 100644 index 000000000..54415a76a --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/lithostitched.rs @@ -0,0 +1,503 @@ +//! Lithostitched: its jigsaw structure, its worldgen modifiers and its +//! processors. +use super::ctov; +use crate::processors::{ProcessorData, carry_all, processors, referenced}; +use crate::worldgen::{ENHANCED_TERRAIN, Upgrade, start_checks}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// A `structure` file of Lithostitched's jigsaw type as vanilla's, with the +/// start rules it shares with the other libraries' jigsaws (`worldgen`'s +/// `start_checks`). `None` for any other file. +pub(crate) fn upgrade( + kind: &str, + v: &mut Value, + lost: &mut BTreeMap, +) -> Option { + if kind != "structure" || v["type"] != "lithostitched:jigsaw" { + return None; + } + start_checks(v, "lowest", lost, false); + if v.as_object_mut() + .and_then(|o| o.remove(ENHANCED_TERRAIN)) + .is_some() + { + *lost.entry(ENHANCED_TERRAIN.into()).or_default() += 1; + } + v["type"] = "minecraft:jigsaw".into(); + Some(true) +} + +/// 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(crate) 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 +} + +/// The data form of one of Lithostitched's processors: the processors to put +/// in its place, or `None` when it has none (or is not Lithostitched's). +pub(crate) fn processor( + kind: &str, + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option> { + match kind { + "lithostitched:apply_random" => apply_random(p, data, carried).map(|p| vec![p]), + "lithostitched:condition" => condition(p, data, carried).map(|p| vec![p]), + "lithostitched:block_swap" => { + // The same map; the game's swap keeps the properties both have. + p["blocks"].as_object()?; + Some(vec![ + json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]}), + ]) + } + "lithostitched:set_block" => { + // A simple or weighted state provider, the block entity left as + // it is. + let provider = p["state_provider"]["type"].as_str()?; + let modifier = p["block_entity_modifier"]["type"].as_str(); + let plain = + modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough"); + if !plain + || !matches!( + provider, + "minecraft:simple_state_provider" | "minecraft:weighted_state_provider" + ) + { + return None; + } + let mut out = p.clone(); + out["processor_type"] = "horizon:set_block".into(); + if let Some(o) = out.as_object_mut() { + o.remove("block_entity_modifier"); + } + Some(vec![out]) + } + _ => None, + } +} + +/// The references (Lithostitched's, and CTOV's compat processors) in a +/// processor list written in; whether any was. +pub(crate) fn expand_references( + list: Vec, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> (Vec, bool) { + references(list, data, carried, 0) +} + +/// A processor list inside a carried processor: an id stays (the game reads +/// that file, carried on its own); an inline one is carried here. +fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap) -> Value { + let mut list = list.clone(); + if let Some(ps) = processors(&mut list) { + *ps = carry_all(std::mem::take(ps), data, carried).0; + } + list +} + +/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted +/// lists, or its set of lists at weight 1. A tag is not carried. +fn apply_random( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option { + let lists = &p["processor_lists"]; + let weighted = lists.as_array().is_some_and(|a| { + a.iter() + .all(|e| e.get("weight").is_some() && e.get("data").is_some()) + }); + let entries: Vec<(Value, Value)> = if weighted { + lists + .as_array()? + .iter() + .map(|e| (e["weight"].clone(), e["data"].clone())) + .collect() + } else { + match lists { + Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())], + Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => { + vec![(1.into(), lists.clone())] + } + Value::Array(a) + if a.iter() + .all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) => + { + a.iter().map(|x| (1.into(), x.clone())).collect() + } + Value::Object(_) => vec![(1.into(), lists.clone())], + _ => return None, + } + }; + let lists: Vec = entries + .into_iter() + .map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)})) + .collect(); + let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists}); + if let Some(mode) = p.get("mode") { + out["mode"] = mode.clone(); + } + Some(out) +} + +/// Lithostitched's `condition` as `horizon:condition`, when the game runs +/// every condition in it (true, all_of, any_of, not, random_chance, +/// matching_blocks with plain property values); else it stays Java. +fn condition( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap, +) -> Option { + fn runs(c: &Value) -> bool { + if let Some(all) = c.as_array() { + return all.iter().all(runs); + } + let kind = c["type"].as_str().unwrap_or_default(); + match kind.strip_prefix("lithostitched:").unwrap_or(kind) { + "true" | "random_chance" => true, + "all_of" | "any_of" => c["conditions"] + .as_array() + .is_some_and(|a| a.iter().all(runs)), + "not" => runs(&c["condition"]), + "matching_blocks" => c.get("properties").is_none_or(|p| { + p.as_object() + .is_some_and(|o| o.values().all(Value::is_string)) + }), + _ => false, + } + } + if !runs(&p["if_true"]) { + return None; + } + // One processor or a list of them. + let mut branch = |key: &str| -> Value { + let list = match p.get(key) { + None => Vec::new(), + Some(Value::Array(a)) => a.clone(), + Some(one) => vec![one.clone()], + }; + carry_all(list, data, carried).0.into() + }; + let (then, otherwise) = (branch("then"), branch("else")); + let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"], + "then": then, "else": otherwise}); + if let Some(mode) = p.get("random_mode") { + out["random_mode"] = mode.clone(); + } + Some(out) +} + +/// Lithostitched's references in a list, each replaced by the processors of +/// the lists it names, in order (references in them too, to a depth of 8). +/// One naming a tag or a list the mod does not have stays, to be dropped. +/// Whether any was replaced. +fn references( + list: Vec, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, +) -> (Vec, bool) { + let mut out = Vec::with_capacity(list.len()); + let mut changed = false; + for p in list { + if let Some(inner) = ctov::modular_compat(&p, data, carried, depth) { + changed = true; + out.extend(references(inner, data, carried, depth + 1).0); + continue; + } + let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) + .then(|| referenced(&p["processor_lists"], data)) + .flatten(); + match named { + Some(inner) => { + *carried.entry("lithostitched:reference".into()).or_default() += 1; + out.extend(references(inner, data, carried, depth + 1).0); + changed = true; + } + None => out.push(p), + } + } + (out, changed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_structure_mods::data; + use crate::processors::carry; + + #[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 lithostitched_block_swaps_become_the_games() { + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, + {"processor_type": "lithostitched:block_swap", "blocks": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0], + json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) + ); + // A map that is not one stays Java (dropped later). + assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); + } + + #[test] + fn lithostitched_references_are_written_in() { + let mut data = data(); + let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}); + data.lists + .insert("v:road".into(), json!({"processors": [gravity.clone()]})); + data.lists.insert( + "v:house".into(), + json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:road"}, + {"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}), + ); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]}, + {"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"}, + {"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + // House (its own reference to road first, then its swap), then road; + // the swap inside is carried too. + assert_eq!(p[0], gravity); + assert_eq!(p[1]["processor_type"], "horizon:block_swap"); + assert_eq!(p[2], gravity); + // A tag or a list the mod lacks stays, to be dropped. + assert_eq!(p[3]["processor_lists"], "#v:roads"); + assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"])); + assert_eq!(carried["lithostitched:reference"], 2); + } + + #[test] + fn lithostitched_random_and_condition_become_the_games() { + let mut data = data(); + let swap = json!({"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + data.lists + .insert("v:green".into(), json!({"processors": [swap.clone()]})); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:green"}, + {"processor_type": "v:java"}]}}]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": ["v:green", "v:red"]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": "#v:colours"}, + {"processor_type": "lithostitched:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}}, + {"processor_type": "lithostitched:condition", + "if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"}, + "then": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + let green = json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + // Inline lists are carried; Java left in them is dropped later. + assert_eq!( + p[0], + json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]}) + ); + assert_eq!( + p[1]["processor_lists"], + json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}]) + ); + assert_eq!(p[2]["processor_type"], "lithostitched:apply_random"); + assert_eq!( + p[3], + json!({"processor_type": "horizon:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]}) + ); + assert_eq!(p[4]["processor_type"], "lithostitched:condition"); + assert_eq!(carried["lithostitched:apply_random"], 2); + assert_eq!(carried["lithostitched:condition"], 1); + } +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs b/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs new file mode 100644 index 000000000..49db376bc --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/mod.rs @@ -0,0 +1,32 @@ +//! The conversion of three families of structure mods' data, kept apart from +//! the general conversion code (`worldgen`, `processors`, `carry`): +//! +//! - [`yung`]: YUNG's API and the mods built on it (Better Dungeons, Desert +//! Temples, Jungle Temples, Witch Huts, Ocean Monuments, Strongholds, +//! Fortresses, Mineshafts), written under `horizon:yungsapi` and the other +//! keys `horizon_world::worldgen::structure::yung` reads. +//! - [`lithostitched`]: Lithostitched's jigsaw, worldgen modifiers and +//! processors. +//! - [`ctov`]: Choice Theorem's Overhauled Village's code-registered set +//! entries and its modular compat processor. +//! +//! The general code reaches them only through the `pub(crate)` entry points +//! of these three modules. Nothing in them is used by another mod's +//! conversion. +pub(crate) mod ctov; +pub(crate) mod lithostitched; +pub(crate) mod yung; + +#[cfg(test)] +fn data() -> crate::processors::ProcessorData { + let mut d = crate::processors::ProcessorData::default(); + d.spawners.insert( + "repurposed_structures:dungeons/badlands".into(), + vec![ + ("minecraft:husk".into(), 10.), + ("minecraft:cave_spider".into(), 3.), + ], + ); + d.replace_vanilla.insert(("mvs".into(), "village".into())); + d +} diff --git a/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs b/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs new file mode 100644 index 000000000..26dd25923 --- /dev/null +++ b/crates/horizon-port-pack/src/legacy_structure_mods/yung.rs @@ -0,0 +1,1055 @@ +//! YUNG's API and the mods built on it: structures, placements, pool +//! elements and processors. +use crate::worldgen::{ENHANCED_TERRAIN, HORIZON_ENHANCED_TERRAIN, moogs_terrain, placement_rules}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// 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"), +]; + +/// A `structure` or `structure_set` file of YUNG's types as vanilla's: its +/// jigsaw, and its placements. `None` for any other file. +pub(crate) fn upgrade( + kind: &str, + v: &mut Value, + set_tags: &BTreeMap>, + lost: &mut BTreeMap, +) -> Option { + match kind { + "structure" => match v["type"].as_str() { + // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a + // config switch that ships on. + Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { + yung_structure(v, lost); + Some(true) + } + _ => None, + }, + "structure_set" => match v["placement"]["type"].as_str() { + Some(t) if YUNG_SPREADS.contains(&t) => { + let t = t.to_owned(); + yung_placement(&t, &mut v["placement"], set_tags, lost); + Some(true) + } + _ => None, + }, + _ => None, + } +} + +/// A pool element of YUNG's type as vanilla's; whether it was one. +pub(crate) fn upgrade_pool_element( + element: &mut Value, + lost: &mut BTreeMap, +) -> bool { + if element["element_type"] != "yungsapi:yung_single_element" { + return false; + } + yung_element(element, lost); + true +} + +/// 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 under `horizon:enhanced_terrain_adaptation`. A start offset in +/// the chunk is 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); + } + } + // YungJigsawStructure's adaptation (NONE by default): every piece's + // junctions, and the start's box grown by its radius. + let own = o.remove(ENHANCED_TERRAIN); + let mut kernel = yung_terrain(own.as_ref().unwrap_or(&Value::Null), lost); + kernel["rigid_junctions"] = true.into(); + kernel["inflate"] = true.into(); + o.insert(HORIZON_ENHANCED_TERRAIN.into(), kernel); + 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`, its condition, dead-end pool and modifiers; its terrain +/// adaptation under `horizon:enhanced_terrain_adaptation`. +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)); + } + // A piece's own adaptation, NONE included, replaces its structure's. + if let Some(a) = o.remove(ENHANCED_TERRAIN) { + o.insert(HORIZON_ENHANCED_TERRAIN.into(), yung_terrain(&a, lost)); + } + if let Some(pool) = o.remove("deadend_pool").filter(Value::is_string) { + rules.insert("deadend_pool".into(), pool); + } + let modifiers: Vec = o + .remove("modifiers") + .and_then(|m| m.as_array().cloned()) + .unwrap_or_default() + .iter() + .filter_map(|m| yung_modifier(m, lost)) + .collect(); + if !modifiers.is_empty() { + rules.insert("modifiers".into(), modifiers.into()); + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// One of YUNG's structure modifiers in the game's terms: its condition and +/// its transform and delay_generation actions, on the piece itself (`self`, +/// the API's only target). Another target loses the modifier, another action +/// just that action. +fn yung_modifier(m: &Value, lost: &mut BTreeMap) -> Option { + let target = m["target_selector"]["type"].as_str().unwrap_or_default(); + if target != "yungsapi:self" { + *lost + .entry(format!("yungsapi modifier target {target}")) + .or_default() += 1; + return None; + } + let mut actions = Vec::new(); + for a in m["actions"].as_array().into_iter().flatten() { + let int = |k: &str| a[k].as_i64().unwrap_or(0); + match a["type"].as_str().unwrap_or_default() { + "yungsapi:transform" => actions.push(serde_json::json!({"type": "transform", + "output": a["output"].clone(), + "offset": [int("x_offset"), int("y_offset"), int("z_offset")]})), + "yungsapi:delay_generation" => { + actions.push(serde_json::json!({"type": "delay_generation"})) + } + other => { + *lost + .entry(format!("yungsapi modifier action {other}")) + .or_default() += 1 + } + } + } + let condition = match m.get("condition") { + Some(c) => yung_condition(c, lost), + None => serde_json::json!({"type": "true"}), + }; + Some(serde_json::json!({"condition": condition, "actions": actions})) +} + +/// YUNG's API's terrain adaptation as the game's kernel: its two presets +/// spelled out, NONE (also the default) as size 0. An aquifer override +/// (none of ATM10's) is lost. +fn yung_terrain(a: &Value, lost: &mut BTreeMap) -> Value { + let kernel = |size: i32, distance: i32, top: &str, bottom: &str| { + serde_json::json!({"kernel_size": size, "kernel_distance": distance, + "top": top, "bottom": bottom}) + }; + match a["type"].as_str() { + Some("yungsapi:carved_top_no_beard_large") => kernel(24, 16, "carve", "none"), + Some("yungsapi:carved_top_no_beard_small") => kernel(12, 6, "carve", "none"), + Some("yungsapi:custom") => { + let mut out = serde_json::Map::new(); + for key in [ + "kernel_size", + "kernel_distance", + "top", + "bottom", + "bottom_offset", + "padding", + ] { + if let Some(x) = a.get(key) { + out.insert(key.into(), x.clone()); + } + } + if a.get("aquifer_override") + .is_some_and(|x| x["type"] != "yungsapi:none") + { + *lost.entry("yungsapi aquifer_override".into()).or_default() += 1; + } + moogs_terrain(&out.into(), lost).unwrap_or_else(|| kernel(0, 0, "none", "none")) + } + None | Some("yungsapi:none") => kernel(0, 0, "none", "none"), + Some(other) => { + *lost + .entry(format!("yungsapi terrain adaptation {other}")) + .or_default() += 1; + kernel(0, 0, "none", "none") + } + } +} + +/// 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")}) + } + // The game reads "yungsapi:all" (or no list) as any piece. + "piece_in_range" => serde_json::json!({"type": "piece_in_range", + "pieces": c.get("pieces").cloned().unwrap_or_else(|| Vec::::new().into()), + "horizontal_range": opt("horizontal_range"), "above_range": opt("above_range"), + "below_range": opt("below_range")}), + "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"}) + } + } +} + +/// 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(crate) 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 game's type for the YUNG's processors that place blocks past their +/// template, which keep their fields (`horizon-world`'s `pillars.rs`). +pub(crate) fn pillar_type(kind: &str) -> Option<&'static str> { + Some(match kind { + "betterfortresses:pillar_processor" | "betterjungletemples:pillar_processor" => { + "horizon:yung_pillar" + } + _ => return None, + }) +} + +/// The data form of one of YUNG's processors: the processors to put in its +/// place, or `None` when it has none (or is not YUNG's). +pub(crate) fn processor(kind: &str, p: &Value) -> Option> { + let (ns, _) = kind.split_once(':')?; + Some(match kind { + // Better Fortresses' stair supports get the blocks its Java code + // names. + "betterfortresses:stair_pillar_processor" => { + vec![json!({"processor_type": "horizon:stair_pillar", + "blocks": {"minecraft:stone_brick_stairs": "minecraft:red_nether_brick_stairs", + "minecraft:purpur_stairs": "minecraft:red_nether_bricks"}, + "front": "minecraft:red_nether_brick_stairs", + "pillar": "minecraft:red_nether_bricks"})] + } + _ if ns == "betterdeserttemples" + && let Some(processor) = desert_temple(kind) => + { + vec![processor] + } + "betterdungeons:small_dungeon_chest_processor" => { + // Its config's defaults: one chest at least, two at most, a + // fifth of the others kept until then; ChestBlock covers both. + vec![json!({"processor_type": "horizon:count_cap", + "blocks": ["minecraft:chest", "minecraft:trapped_chest"], + "min": 1, "max": 2, "chance": 0.2f32 as f64, + "replacement": block("minecraft:cave_air")})] + } + "betterwitchhuts:leg_processor" => vec![yung_leg( + "minecraft:brown_stained_glass", + json!({"id": "minecraft:oak_log", "properties": {"axis": "y"}}), + false, + )], + "betterwitchhuts:fence_leg_processor" => vec![yung_leg( + "minecraft:crimson_fence", + block("minecraft:oak_fence"), + true, + )], + _ if ns == "betteroceanmonuments" => ocean_monument(kind)?, + _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], + _ => return None, + }) +} + +/// YUNG's leg processors (Better Ocean Monuments, Better Witch Huts): a +/// placeholder block becomes `state` and a column of it runs down through +/// air and fluids: the game's `horizon:yung_pillar` with fixed states, and +/// the placeholder's properties kept for the fence legs. +fn yung_leg(target: &str, state: Value, keep_properties: bool) -> Value { + let fixed = json!({"entries": [], "defaultBlockState": state}); + json!({"processor_type": "horizon:yung_pillar", "target_block": block(target), + "target_block_output": fixed, "pillar_states": fixed, + "keep_properties": keep_properties}) +} + +/// Better Ocean Monuments' processors (no fields; what they do is in their +/// Java code): placeholder blocks as vanilla's `rule` or the game's +/// `horizon:pick` (a new `nextFloat` for each chance, as the mod draws), +/// and its sea-level ones as the game's `horizon:flood_air`, +/// `horizon:waterlog` and `horizon:keep_world_block`. +fn ocean_monument(kind: &str) -> Option> { + let rule = |rules: &[(&str, Value)]| { + let rules: Vec = rules + .iter() + .map(|(from, to)| { + json!({"input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": to}) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) + }; + let state = |id: &str, props: Value| json!({"id": id, "properties": props}); + let pick = |from: &str, picks: Vec<(f32, Value)>, default: Value, keep: bool| { + let picks: Vec = picks + .into_iter() + .map(|(below, state)| json!({"below": below as f64, "state": state})) + .collect(); + json!({"processor_type": "horizon:pick", "block": from, "picks": picks, + "default": {"state": default}, "redraw": true, "keep_properties": keep}) + }; + let slabs = |from: &str, slab: &str, otherwise: &str| { + let wet = |t: &str| state(slab, json!({"type": t, "waterlogged": "true"})); + pick( + from, + vec![(0.4, wet("top")), (0.8, wet("bottom"))], + block(otherwise), + false, + ) + }; + // Exposed below 0.1, else weathered below a new 0.3, else oxidized, + // with the placeholder's properties for the stairs and slabs. + let copper = |kind: &str| { + let id = |age: &str| block(&format!("minecraft:{age}{kind}")); + pick( + &format!("minecraft:oxidized_{kind}"), + vec![(0.1, id("exposed_")), (0.3, id("weathered_"))], + id("oxidized_"), + true, + ) + }; + Some(match kind.strip_prefix("betteroceanmonuments:")? { + "random_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:lime_concrete", + "minecraft:prismarine_slab", + "minecraft:air", + )], + "random_dark_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:blue_concrete", + "minecraft:dark_prismarine_slab", + "minecraft:water", + )], + "sand_gravel_processor" => { + vec![rule(&[( + "minecraft:yellow_stained_glass", + block("minecraft:gravel"), + )])] + } + "random_oxidization_processor" => [ + "copper", + "cut_copper", + "cut_copper_stairs", + "cut_copper_slab", + ] + .into_iter() + .map(copper) + .collect(), + "structure_void_processor" => vec![json!({"processor_type": "horizon:keep_world_block", + "blocks": ["minecraft:purpur_slab", "minecraft:brown_wool"]})], + "air_processor" => vec![json!({"processor_type": "horizon:flood_air"})], + "waterlog_processor" => vec![json!({"processor_type": "horizon:waterlog"})], + "seagrass_processor" => vec![rule(&[ + ( + "minecraft:red_sandstone_slab", + state("minecraft:tall_seagrass", json!({"half": "lower"})), + ), + ( + "minecraft:end_stone_brick_slab", + state("minecraft:tall_seagrass", json!({"half": "upper"})), + ), + ("minecraft:brick_slab", block("minecraft:seagrass")), + ])], + "random_sponge_processor" => vec![pick( + "minecraft:orange_stained_glass", + vec![(0.75, block("minecraft:wet_sponge"))], + block("minecraft:water"), + false, + )], + "leg_processor" => vec![yung_leg( + "minecraft:blue_stained_glass", + block("minecraft:prismarine_bricks"), + false, + )], + _ => return None, + }) +} + +/// A block state as 26.3 writes it. +fn block(id: &str) -> Value { + json!({"id": id}) +} + +/// Better Desert Temples' placeholder blocks (glass, concrete and wool in +/// the templates) as the mod's processors turn them: the fixed ones as +/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the +/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its +/// chances up in floats). The ones that read or change the world around +/// (pillars, Diorite's waterlogging) stay dropped. +fn desert_temple(kind: &str) -> Option { + let swap = |from: &str, to: &str| { + json!({"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": block(to)}]}) + }; + let pick = |from: &str, picks: Vec, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); + // YUNG's BlockStateRandomizer: an entry wins below the sum of the + // chances so far, summed as floats. + let randomizer = |entries: &[(f32, &str)]| { + let mut bottom = 0f32; + entries + .iter() + .map(|(chance, id)| { + bottom += chance; + json!({"below": bottom as f64, "state": block(id)}) + }) + .collect::>() + }; + let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); + // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. + let stairs = || { + let states: Vec = ["north", "east", "south", "west"] + .iter() + .map(|facing| { + json!({"id": "minecraft:sandstone_stairs", "properties": { + "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) + }) + .collect(); + json!({"states": states}) + }; + Some(match kind.strip_prefix("betterdeserttemples:")? { + "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), + "yellow_concrete_processor" => { + swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") + } + "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), + "white_stained_glass_processor" => pick( + "minecraft:white_stained_glass", + randomizer(&[(0.4, "minecraft:cobweb")]), + json!({"state": block("minecraft:air")}), + ), + "polished_diorite_processor" => pick( + "minecraft:polished_diorite", + randomizer(&[(0.6, "minecraft:cut_sandstone")]), + json!({"state": block("minecraft:sandstone")}), + ), + "orange_stained_glass_processor" => { + let mut sus = at(0.01, "minecraft:suspicious_sand"); + sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); + let mut stairs = stairs(); + stairs["below"] = (0.45f32 as f64).into(); + pick( + "minecraft:orange_stained_glass", + vec![ + sus, + at(0.1, "minecraft:sand"), + at(0.2, "minecraft:sandstone"), + stairs, + ], + json!({"state": block("minecraft:cut_sandstone")}), + ) + } + "red_stained_glass_processor" => pick( + "minecraft:red_stained_glass", + vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], + stairs(), + ), + "pot_processor" => { + // Four sherds, one float each; the pot back to its default state. + let values: Vec = [ + (0.05f32, "archer"), + (0.1, "miner"), + (0.15, "prize"), + (0.2, "skull"), + ] + .iter() + .map(|(below, sherd)| { + json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) + }) + .collect(); + pick( + "minecraft:decorated_pot", + Vec::new(), + json!({"state": block("minecraft:decorated_pot"), "lists": [{ + "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), + ) + } + _ => return None, + }) +} + +/// An item as 26.3 saves it. +fn item(id: &str) -> Value { + json!({"id": format!("minecraft:{id}"), "count": 1}) +} + +/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's +/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a +/// spawner with that NBT. +fn yung_spawner(kind: &str, p: &Value) -> Option { + const SPAWNER: &str = "minecraft:spawner"; + // (input block, mob, fields other than the defaults, whether the mob is + // also the only potential, its equipment) + let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { + "betterdungeons:mob_spawner_processor" => { + (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) + } + "betterdungeons:zombie_mob_spawner_processor" => ( + SPAWNER, + "minecraft:zombie", + &[("MaxNearbyEntities", 8)], + true, + None, + ), + "betterdungeons:skeleton_mob_spawner_processor" => ( + SPAWNER, + "minecraft:skeleton", + &[ + ("RequiredPlayerRange", 18), + ("MaxNearbyEntities", 8), + ("MaxSpawnDelay", 650), + ], + true, + None, + ), + "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { + let mob = p["spawner_mob"].as_str()?; + // Wither skeletons get netherite armor that never drops and a + // stone sword (with the mod's default config, they and blazes + // keep their loot). + let armor = (mob == "minecraft:wither_skeleton").then(|| { + json!({ + "equipment": { + "feet": item("netherite_boots"), + "legs": item("netherite_leggings"), + "chest": item("netherite_chestplate"), + "head": item("netherite_helmet"), + "mainhand": item("stone_sword"), + }, + "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, + }) + }); + (SPAWNER, mob, &[], true, armor) + } + "betterdungeons:zombie_tombstone_spawner_processor" => ( + "minecraft:black_stained_glass", + "minecraft:skeleton", + &[], + false, + Some(json!({"equipment": {"mainhand": item("iron_sword")}})), + ), + "betterdeserttemples:gravel_processor" => ( + "minecraft:gravel", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + None, + ), + // An empty hand list in 1.21.1: the skeletons spawn without a bow, + // since a spawn entry with more than its id is not finalized. + "betterdeserttemples:bone_block_processor" => ( + "minecraft:bone_block", + "minecraft:skeleton", + &[("RequiredPlayerRange", 32)], + false, + Some(json!({"equipment": {}})), + ), + "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( + "minecraft:infested_cracked_stone_bricks", + "minecraft:silverfish", + &[("RequiredPlayerRange", 24)], + false, + None, + ), + // 1.21.1 ignores the items' old `Count` and `tag` (the shield's + // pattern, the boots' dye): plain items. + "betterdeserttemples:yellow_wool_processor" => ( + "minecraft:yellow_wool", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + Some(json!({"equipment": { + "mainhand": item("golden_sword"), + "offhand": item("shield"), + "feet": item("leather_boots"), + "legs": item("leather_leggings"), + "chest": item("golden_chestplate"), + "head": item("chainmail_helmet"), + }})), + ), + _ => return None, + }; + let mut entity = json!({"id": mob}); + if let Some(Value::Object(extra)) = equipment { + entity.as_object_mut()?.extend(extra); + } + let potentials = match potential { + true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), + false => json!([]), + }; + let mut nbt = json!({ + "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, + "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, + "SpawnData": {"entity": entity}, + "SpawnPotentials": potentials, + }); + for (key, value) in fields { + nbt[*key] = (*value).into(); + } + Some(json!({ + "processor_type": "minecraft:rule", + "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": SPAWNER}, + "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, + }], + })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::legacy_structure_mods::data; + use crate::processors::{ProcessorData, carry}; + use crate::worldgen::{Upgrade, upgrade}; + + const NO_TAGS: BTreeMap> = BTreeMap::new(); + + #[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, + "kernel_distance": 24, "top": "carve", "bottom": "none"}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); + assert_eq!( + s["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", "bottom": "none", + "rigid_junctions": true, "inflate": true}) + ); + for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { + assert!(s.get(gone).is_none(), "{gone}"); + } + // Better Dungeons' small Nether dungeon is the same jigsaw. + let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", + "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, + "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", + "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!(nether["horizon:yungsapi"], json!({})); + assert_eq!( + nether["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 0, "kernel_distance": 0, "top": "none", "bottom": "none", + "rigid_junctions": true, "inflate": true}) + ); + assert_eq!( + nether["start_jigsaw_name"], + "betterdungeons:small_nether_dungeon_anchor" + ); + assert!(report.unsupported.is_empty()); + 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", + "modifiers": [ + {"condition": {"type": "yungsapi:piece_in_range", "pieces": ["y:pillar"], + "above_range": 40}, + "target_selector": {"type": "yungsapi:self"}, + "actions": [{"type": "yungsapi:transform", "output": ["y:covered"], "x_offset": -1}, + {"type": "yungsapi:delay_generation"}, {"type": "yungsapi:spin"}]}, + {"condition": {"type": "yungsapi:always_true"}, + "target_selector": {"type": "yungsapi:all"}, "actions": []}], + "enhanced_terrain_adaptation": {"type": "yungsapi:carved_top_no_beard_small"}, + "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"}]}, + "deadend_pool": "y:end", + "modifiers": [{"condition": {"type": "piece_in_range", "pieces": ["y:pillar"], + "horizontal_range": null, "above_range": 40, "below_range": null}, + "actions": [{"type": "transform", "output": ["y:covered"], "offset": [-1, 0, 0]}, + {"type": "delay_generation"}]}]}) + ); + assert!(e.get("deadend_pool").is_none() && e.get("modifiers").is_none()); + assert_eq!( + e["horizon:enhanced_terrain_adaptation"], + json!({"kernel_size": 12, "kernel_distance": 6, "top": "carve", "bottom": "none"}) + ); + assert_eq!( + report.rules_lost, + BTreeMap::from([ + ("yungsapi condition yungsapi:biome".into(), 1), + ("yungsapi modifier action yungsapi:spin".into(), 1), + ("yungsapi modifier target yungsapi:all".into(), 1), + ]) + ); + assert!(report.unsupported.is_empty()); + } + + #[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 yungs_spawners_become_rules() { + let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ + {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, + {"processor_type": "betterdeserttemples:bone_block_processor"}, + {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", + "spawner_mob": "minecraft:wither_skeleton"}, + {"processor_type": "betterdungeons:candle_processor"}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("template_pool", &mut pool, &data(), &mut carried)); + let p = &pool["elements"][0]["element"]["processors"]["processors"]; + let rule = |i: usize| &p[i]["rules"][0]; + assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); + assert_eq!( + rule(0)["output_state"], + json!({"Name": "minecraft:spawner"}) + ); + let nbt = &rule(0)["block_entity_modifier"]["data"]; + assert_eq!( + ( + nbt["RequiredPlayerRange"].clone(), + nbt["MaxNearbyEntities"].clone() + ), + (json!(18), json!(8)) + ); + assert_eq!(nbt["MaxSpawnDelay"], 650); + assert_eq!( + nbt["SpawnPotentials"], + json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) + ); + // Bone blocks become bowless skeleton spawners with no potentials. + let bone = &rule(1)["block_entity_modifier"]["data"]; + assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); + assert_eq!( + bone["SpawnData"], + json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) + ); + assert_eq!(bone["SpawnPotentials"], json!([])); + let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; + assert_eq!( + wither["equipment"]["head"]["id"], + "minecraft:netherite_helmet" + ); + assert_eq!(wither["drop_chances"]["feet"], 0.0); + assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); + assert_eq!(carried.values().sum::(), 3); + } + + #[test] + fn desert_temple_placeholders_become_rules_and_picks() { + let mut list = json!({"processors": [ + {"processor_type": "betterdeserttemples:red_wool_processor"}, + {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:pot_processor"}, + {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0]["rules"][0]["output_state"], + json!({"id": "minecraft:tnt"}) + ); + assert_eq!(p[1]["processor_type"], "horizon:pick"); + assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); + let glass = &p[2]["picks"]; + assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); + assert_eq!( + glass[0]["nbt"]["LootTable"], + "minecraft:archaeology/desert_pyramid" + ); + assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); + assert_eq!(glass[3]["below"], 0.45f32 as f64); + assert_eq!(p[3]["default"]["lists"][0]["count"], 4); + // The pillar reads the world below: still Java, still dropped later. + assert_eq!( + p[4]["processor_type"], + "betterdeserttemples:quartz_pillar_processor" + ); + assert_eq!(carried.values().sum::(), 4); + } + + #[test] + fn small_dungeon_chests_are_capped() { + let mut list = json!({"processors": [ + {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let cap = &list["processors"][0]; + assert_eq!(cap["processor_type"], "horizon:count_cap"); + assert_eq!( + (cap["min"].as_u64(), cap["max"].as_u64()), + (Some(1), Some(2)) + ); + assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); + } + + #[test] + fn ocean_monuments_become_the_games() { + let names = [ + "random_prismarine_slab_decoration_processor", + "random_dark_prismarine_slab_decoration_processor", + "sand_gravel_processor", + "random_oxidization_processor", + "structure_void_processor", + "air_processor", + "waterlog_processor", + "seagrass_processor", + "random_sponge_processor", + "leg_processor", + ]; + let processors: Vec = names + .iter() + .map(|n| json!({"processor_type": format!("betteroceanmonuments:{n}")})) + .chain([json!({"processor_type": "betterwitchhuts:fence_leg_processor"})]) + .collect(); + let mut list = json!({"processors": processors}); + let mut carried = BTreeMap::new(); + assert!(carry( + "processor_list", + &mut list, + &ProcessorData::default(), + &mut carried + )); + let p = list["processors"].as_array().unwrap(); + let types: Vec<&str> = p + .iter() + .map(|p| p["processor_type"].as_str().unwrap()) + .collect(); + let mut want = vec!["horizon:pick", "horizon:pick", "minecraft:rule"]; + want.extend(["horizon:pick"; 4]); + want.extend([ + "horizon:keep_world_block", + "horizon:flood_air", + "horizon:waterlog", + "minecraft:rule", + "horizon:pick", + "horizon:yung_pillar", + "horizon:yung_pillar", + ]); + assert_eq!(types, want); + assert_eq!(carried.values().sum::(), 11); + // Copper stairs keep their properties, each chance on a new float. + let stairs = &p[5]; + assert_eq!(stairs["block"], "minecraft:oxidized_cut_copper_stairs"); + assert_eq!( + stairs["picks"][1]["state"]["id"], + "minecraft:weathered_cut_copper_stairs" + ); + assert_eq!( + (stairs["redraw"].clone(), stairs["keep_properties"].clone()), + (json!(true), json!(true)) + ); + assert_eq!(p[0]["picks"][0]["state"]["properties"]["type"], "top"); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:water"); + assert_eq!( + p[12]["target_block_output"]["defaultBlockState"]["id"], + "minecraft:prismarine_bricks" + ); + assert_eq!(p[13]["keep_properties"], true); + } +} diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index f729b6c52..950413341 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -13,6 +13,7 @@ pub mod fetch; pub mod import; pub mod inventory; pub mod jar; +pub(crate) mod legacy_structure_mods; pub mod modrinth; pub mod oracle; pub mod pipeline; diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index e6c0fe7d8..f182bee7b 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -5,27 +5,18 @@ //! processors pick a mob from a weighted list for each spawner. They become //! `horizon:spawner_mobs` (`horizon_world::worldgen::structure::processor`), //! with Repurposed's `rs_spawners` list written in. -//! - YUNG's Better Dungeons and Better Desert Temples turn a spawner or a -//! placeholder block into a spawner of a fixed mob. That is vanilla's `rule` -//! processor with an `append_static` block entity. //! - Moog's vanilla loot swap only acts when its mod's "replace vanilla" //! preset is on; one that ships off is a no-op and is taken out. -//! - Lithostitched's `reference` runs other processor lists in turn: their -//! processors are written in its place (Choice Theorem's Overhauled -//! Villages builds most of its lists so). Its `apply_random` and -//! `condition` become the game's `horizon:apply_random` and -//! `horizon:condition`, with the lists inside them carried the same way, -//! and its `set_block` (simple or weighted states) `horizon:set_block`. //! - Repurposed Structures' mineshaft sky view becomes the game's //! `horizon:mineshaft_sky_view`. -//! - Choice Theorem's Overhauled Village's `modular_compat` runs another -//! list only when the mod it names is loaded: that list is written in its -//! place when the mod is ported along, and it is taken out (a no-op, as in -//! the mod) when it is not. +//! +//! The processors of YUNG's mods, Lithostitched and Choice Theorem's Overhauled +//! Village are carried by `legacy_structure_mods`, called from [`carry`]. //! //! What is not here is taken out of its list later and counted //! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an //! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`). +use crate::legacy_structure_mods::{ctov, lithostitched, yung}; use serde_json::{Value, json}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -48,30 +39,10 @@ pub struct ProcessorData { pub compat_loaded: BTreeSet, } -/// Choice Theorem's Overhauled Village's processor that runs the list -/// `reference` when mod `modid` is loaded (ModularCompatProcessor). -const MODULAR_COMPAT: &str = "ctov:modular_compat"; - impl ProcessorData { /// Notes which mods its compat processors name are `loaded`. pub fn mark_loaded(&mut self, loaded: &dyn Fn(&str) -> bool) { - fn walk(v: &Value, out: &mut BTreeSet) { - match v { - Value::Object(o) => { - if o.get("processor_type").and_then(Value::as_str) == Some(MODULAR_COMPAT) { - if let Some(id) = o.get("modid").and_then(Value::as_str) { - out.insert(id.to_owned()); - } - } - o.values().for_each(|v| walk(v, out)); - } - Value::Array(a) => a.iter().for_each(|v| walk(v, out)), - _ => {} - } - } - let mut named = BTreeSet::new(); - self.lists.values().for_each(|l| walk(l, &mut named)); - self.compat_loaded = named.into_iter().filter(|m| loaded(m)).collect(); + ctov::mark_loaded(self, loaded); } pub fn read(zip: &mut zip::ZipArchive) -> Self { @@ -187,7 +158,7 @@ pub fn carry( /// The processors of one list carried: references written in, then each /// one with a data form replaced by it. Whether anything changed. -fn carry_all( +pub(crate) fn carry_all( list: Vec, data: &ProcessorData, carried: &mut BTreeMap, @@ -202,18 +173,18 @@ fn carry_at( carried: &mut BTreeMap, depth: usize, ) -> (Vec, bool) { - let (expanded, mut changed) = references(list, data, carried, 0); + let (expanded, mut changed) = lithostitched::expand_references(list, data, carried); let mut out = Vec::with_capacity(expanded.len()); for p in expanded { let kind = p["processor_type"].as_str().unwrap_or_default().to_owned(); - let replacement = match kind.as_str() { - "lithostitched:apply_random" => apply_random(&p, data, carried).map(|p| vec![p]), - "lithostitched:condition" => condition(&p, data, carried).map(|p| vec![p]), - _ => match pillar_type(&kind) { + // Lithostitched's and YUNG's processors are carried apart from this + // code (`legacy_structure_mods`). + let replacement = lithostitched::processor(&kind, &p, data, carried).or_else(|| { + match pillar_type(&kind).or_else(|| yung::pillar_type(&kind)) { Some(to) => Some(vec![pillar(&p, to, data, carried, depth)]), - None => as_data(&kind, &p, data), - }, - }; + None => as_data(&kind, &p, data).or_else(|| yung::processor(&kind, &p)), + } + }); match replacement { Some(replacement) => { *carried.entry(kind).or_default() += 1; @@ -237,10 +208,6 @@ fn pillar_type(kind: &str) -> Option<&'static str> { "repurposed_structures:close_off_fluid_sources_processor" | "moogs_structures:close_off_fluid_sources_processor" => "horizon:close_off_fluid_sources", "repurposed_structures:close_off_air_sources_processor" => "horizon:close_off_air_sources", - "betterfortresses:pillar_processor" | "betterjungletemples:pillar_processor" => { - "horizon:yung_pillar" - } - "betterfortresses:stair_pillar_processor" => "horizon:stair_pillar", _ => return None, }) } @@ -248,8 +215,7 @@ fn pillar_type(kind: &str) -> Option<&'static str> { /// A pillar processor as the game's `to`. Its `pillar_processor_list` /// (which runs on each block of the column; Repurposed's often names the /// list it is in) is written in, carried; the pillars inside that copy lose -/// theirs, as a column's blocks are never the mods' triggers. Better -/// Fortresses' stair supports get the blocks its Java code names. +/// theirs, as a column's blocks are never the mods' triggers. fn pillar( p: &Value, to: &str, @@ -257,13 +223,6 @@ fn pillar( carried: &mut BTreeMap, depth: usize, ) -> Value { - if to == "horizon:stair_pillar" { - return json!({"processor_type": to, - "blocks": {"minecraft:stone_brick_stairs": "minecraft:red_nether_brick_stairs", - "minecraft:purpur_stairs": "minecraft:red_nether_bricks"}, - "front": "minecraft:red_nether_brick_stairs", - "pillar": "minecraft:red_nether_bricks"}); - } let mut out = p.clone(); out["processor_type"] = to.into(); let Some(o) = out.as_object_mut() else { @@ -284,108 +243,6 @@ fn pillar( out } -/// A processor list inside a carried processor: an id stays (the game reads -/// that file, carried on its own); an inline one is carried here. -fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap) -> Value { - let mut list = list.clone(); - if let Some(ps) = processors(&mut list) { - *ps = carry_all(std::mem::take(ps), data, carried).0; - } - list -} - -/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted -/// lists, or its set of lists at weight 1. A tag is not carried. -fn apply_random( - p: &Value, - data: &ProcessorData, - carried: &mut BTreeMap, -) -> Option { - let lists = &p["processor_lists"]; - let weighted = lists.as_array().is_some_and(|a| { - a.iter() - .all(|e| e.get("weight").is_some() && e.get("data").is_some()) - }); - let entries: Vec<(Value, Value)> = if weighted { - lists - .as_array()? - .iter() - .map(|e| (e["weight"].clone(), e["data"].clone())) - .collect() - } else { - match lists { - Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())], - Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => { - vec![(1.into(), lists.clone())] - } - Value::Array(a) - if a.iter() - .all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) => - { - a.iter().map(|x| (1.into(), x.clone())).collect() - } - Value::Object(_) => vec![(1.into(), lists.clone())], - _ => return None, - } - }; - let lists: Vec = entries - .into_iter() - .map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)})) - .collect(); - let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists}); - if let Some(mode) = p.get("mode") { - out["mode"] = mode.clone(); - } - Some(out) -} - -/// Lithostitched's `condition` as `horizon:condition`, when the game runs -/// every condition in it (true, all_of, any_of, not, random_chance, -/// matching_blocks with plain property values); else it stays Java. -fn condition( - p: &Value, - data: &ProcessorData, - carried: &mut BTreeMap, -) -> Option { - fn runs(c: &Value) -> bool { - if let Some(all) = c.as_array() { - return all.iter().all(runs); - } - let kind = c["type"].as_str().unwrap_or_default(); - match kind.strip_prefix("lithostitched:").unwrap_or(kind) { - "true" | "random_chance" => true, - "all_of" | "any_of" => c["conditions"] - .as_array() - .is_some_and(|a| a.iter().all(runs)), - "not" => runs(&c["condition"]), - "matching_blocks" => c.get("properties").is_none_or(|p| { - p.as_object() - .is_some_and(|o| o.values().all(Value::is_string)) - }), - _ => false, - } - } - if !runs(&p["if_true"]) { - return None; - } - // One processor or a list of them. - let mut branch = |key: &str| -> Value { - let list = match p.get(key) { - None => Vec::new(), - Some(Value::Array(a)) => a.clone(), - Some(one) => vec![one.clone()], - }; - carry_all(list, data, carried).0.into() - }; - let (then, otherwise) = (branch("then"), branch("else")); - let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"], - "then": then, "else": otherwise}); - if let Some(mode) = p.get("random_mode") { - out["random_mode"] = mode.clone(); - } - Some(out) -} - /// Repurposed Structures' rule tests and the game's types that run them /// (`horizon_world::worldgen`'s `rule_test` and `structure::processor`). const RULE_TESTS: [(&str, &str); 3] = [ @@ -429,48 +286,9 @@ pub fn rule_tests(kind: &str, v: &mut Value, carried: &mut BTreeMap, - data: &ProcessorData, - carried: &mut BTreeMap, - depth: usize, -) -> (Vec, bool) { - let mut out = Vec::with_capacity(list.len()); - let mut changed = false; - for p in list { - if p["processor_type"] == MODULAR_COMPAT && depth < 8 { - *carried.entry(MODULAR_COMPAT.into()).or_default() += 1; - changed = true; - let loaded = p["modid"] - .as_str() - .is_some_and(|m| data.compat_loaded.contains(m)); - if let Some(inner) = loaded.then(|| referenced(&p["reference"], data)).flatten() { - out.extend(references(inner, data, carried, depth + 1).0); - } - continue; - } - let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) - .then(|| referenced(&p["processor_lists"], data)) - .flatten(); - match named { - Some(inner) => { - *carried.entry("lithostitched:reference".into()).or_default() += 1; - out.extend(references(inner, data, carried, depth + 1).0); - changed = true; - } - None => out.push(p), - } - } - (out, changed) -} - /// The processors of the lists a reference names: an id, an inline list, or /// a list of either. -fn referenced(lists: &Value, data: &ProcessorData) -> Option> { +pub(crate) fn referenced(lists: &Value, data: &ProcessorData) -> Option> { let one = |l: &Value| -> Option> { let mut list = match l { Value::String(id) if !id.starts_with('#') => { @@ -497,7 +315,7 @@ fn referenced(lists: &Value, data: &ProcessorData) -> Option> { /// The data form of a Java processor: the processors to put in its place /// (none for a no-op), or `None` when it has none. fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { - let (ns, _) = kind.split_once(':')?; + kind.split_once(':')?; Some(match kind { // Its structure voids keep the world's block, as vanilla's // block_ignore does (the templates hold them; vanilla places them). @@ -593,171 +411,6 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { |s| config(s.get("ominous") == Some(&"true")), )] } - _ if ns == "betterdeserttemples" - && let Some(processor) = desert_temple(kind) => - { - vec![processor] - } - "lithostitched:block_swap" => { - // The same map; the game's swap keeps the properties both have. - p["blocks"].as_object()?; - vec![json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]})] - } - "lithostitched:set_block" => { - // A simple or weighted state provider, the block entity left as - // it is. - let provider = p["state_provider"]["type"].as_str()?; - let modifier = p["block_entity_modifier"]["type"].as_str(); - let plain = - modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough"); - if !plain - || !matches!( - provider, - "minecraft:simple_state_provider" | "minecraft:weighted_state_provider" - ) - { - return None; - } - let mut out = p.clone(); - out["processor_type"] = "horizon:set_block".into(); - if let Some(o) = out.as_object_mut() { - o.remove("block_entity_modifier"); - } - vec![out] - } - "betterdungeons:small_dungeon_chest_processor" => { - // Its config's defaults: one chest at least, two at most, a - // fifth of the others kept until then; ChestBlock covers both. - vec![json!({"processor_type": "horizon:count_cap", - "blocks": ["minecraft:chest", "minecraft:trapped_chest"], - "min": 1, "max": 2, "chance": 0.2f32 as f64, - "replacement": block("minecraft:cave_air")})] - } - "betterwitchhuts:leg_processor" => vec![yung_leg( - "minecraft:brown_stained_glass", - json!({"id": "minecraft:oak_log", "properties": {"axis": "y"}}), - false, - )], - "betterwitchhuts:fence_leg_processor" => vec![yung_leg( - "minecraft:crimson_fence", - block("minecraft:oak_fence"), - true, - )], - _ if ns == "betteroceanmonuments" => ocean_monument(kind)?, - _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], - _ => return None, - }) -} - -/// YUNG's leg processors (Better Ocean Monuments, Better Witch Huts): a -/// placeholder block becomes `state` and a column of it runs down through -/// air and fluids: the game's `horizon:yung_pillar` with fixed states, and -/// the placeholder's properties kept for the fence legs. -fn yung_leg(target: &str, state: Value, keep_properties: bool) -> Value { - let fixed = json!({"entries": [], "defaultBlockState": state}); - json!({"processor_type": "horizon:yung_pillar", "target_block": block(target), - "target_block_output": fixed, "pillar_states": fixed, - "keep_properties": keep_properties}) -} - -/// Better Ocean Monuments' processors (no fields; what they do is in their -/// Java code): placeholder blocks as vanilla's `rule` or the game's -/// `horizon:pick` (a new `nextFloat` for each chance, as the mod draws), -/// and its sea-level ones as the game's `horizon:flood_air`, -/// `horizon:waterlog` and `horizon:keep_world_block`. -fn ocean_monument(kind: &str) -> Option> { - let rule = |rules: &[(&str, Value)]| { - let rules: Vec = rules - .iter() - .map(|(from, to)| { - json!({"input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": to}) - }) - .collect(); - json!({"processor_type": "minecraft:rule", "rules": rules}) - }; - let state = |id: &str, props: Value| json!({"id": id, "properties": props}); - let pick = |from: &str, picks: Vec<(f32, Value)>, default: Value, keep: bool| { - let picks: Vec = picks - .into_iter() - .map(|(below, state)| json!({"below": below as f64, "state": state})) - .collect(); - json!({"processor_type": "horizon:pick", "block": from, "picks": picks, - "default": {"state": default}, "redraw": true, "keep_properties": keep}) - }; - let slabs = |from: &str, slab: &str, otherwise: &str| { - let wet = |t: &str| state(slab, json!({"type": t, "waterlogged": "true"})); - pick( - from, - vec![(0.4, wet("top")), (0.8, wet("bottom"))], - block(otherwise), - false, - ) - }; - // Exposed below 0.1, else weathered below a new 0.3, else oxidized, - // with the placeholder's properties for the stairs and slabs. - let copper = |kind: &str| { - let id = |age: &str| block(&format!("minecraft:{age}{kind}")); - pick( - &format!("minecraft:oxidized_{kind}"), - vec![(0.1, id("exposed_")), (0.3, id("weathered_"))], - id("oxidized_"), - true, - ) - }; - Some(match kind.strip_prefix("betteroceanmonuments:")? { - "random_prismarine_slab_decoration_processor" => vec![slabs( - "minecraft:lime_concrete", - "minecraft:prismarine_slab", - "minecraft:air", - )], - "random_dark_prismarine_slab_decoration_processor" => vec![slabs( - "minecraft:blue_concrete", - "minecraft:dark_prismarine_slab", - "minecraft:water", - )], - "sand_gravel_processor" => { - vec![rule(&[( - "minecraft:yellow_stained_glass", - block("minecraft:gravel"), - )])] - } - "random_oxidization_processor" => [ - "copper", - "cut_copper", - "cut_copper_stairs", - "cut_copper_slab", - ] - .into_iter() - .map(copper) - .collect(), - "structure_void_processor" => vec![json!({"processor_type": "horizon:keep_world_block", - "blocks": ["minecraft:purpur_slab", "minecraft:brown_wool"]})], - "air_processor" => vec![json!({"processor_type": "horizon:flood_air"})], - "waterlog_processor" => vec![json!({"processor_type": "horizon:waterlog"})], - "seagrass_processor" => vec![rule(&[ - ( - "minecraft:red_sandstone_slab", - state("minecraft:tall_seagrass", json!({"half": "lower"})), - ), - ( - "minecraft:end_stone_brick_slab", - state("minecraft:tall_seagrass", json!({"half": "upper"})), - ), - ("minecraft:brick_slab", block("minecraft:seagrass")), - ])], - "random_sponge_processor" => vec![pick( - "minecraft:orange_stained_glass", - vec![(0.75, block("minecraft:wet_sponge"))], - block("minecraft:water"), - false, - )], - "leg_processor" => vec![yung_leg( - "minecraft:blue_stained_glass", - block("minecraft:prismarine_bricks"), - false, - )], _ => return None, }) } @@ -885,110 +538,6 @@ pub fn upgrade_trial_spawner(config: &mut Value) -> bool { changed } -/// A block state as 26.3 writes it. -fn block(id: &str) -> Value { - json!({"id": id}) -} - -/// Better Desert Temples' placeholder blocks (glass, concrete and wool in -/// the templates) as the mod's processors turn them: the fixed ones as -/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the -/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its -/// chances up in floats). The ones that read or change the world around -/// (pillars, Diorite's waterlogging) stay dropped. -fn desert_temple(kind: &str) -> Option { - let swap = |from: &str, to: &str| { - json!({"processor_type": "minecraft:rule", "rules": [{ - "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": block(to)}]}) - }; - let pick = |from: &str, picks: Vec, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); - // YUNG's BlockStateRandomizer: an entry wins below the sum of the - // chances so far, summed as floats. - let randomizer = |entries: &[(f32, &str)]| { - let mut bottom = 0f32; - entries - .iter() - .map(|(chance, id)| { - bottom += chance; - json!({"below": bottom as f64, "state": block(id)}) - }) - .collect::>() - }; - let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); - // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. - let stairs = || { - let states: Vec = ["north", "east", "south", "west"] - .iter() - .map(|facing| { - json!({"id": "minecraft:sandstone_stairs", "properties": { - "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) - }) - .collect(); - json!({"states": states}) - }; - Some(match kind.strip_prefix("betterdeserttemples:")? { - "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), - "yellow_concrete_processor" => { - swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") - } - "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), - "white_stained_glass_processor" => pick( - "minecraft:white_stained_glass", - randomizer(&[(0.4, "minecraft:cobweb")]), - json!({"state": block("minecraft:air")}), - ), - "polished_diorite_processor" => pick( - "minecraft:polished_diorite", - randomizer(&[(0.6, "minecraft:cut_sandstone")]), - json!({"state": block("minecraft:sandstone")}), - ), - "orange_stained_glass_processor" => { - let mut sus = at(0.01, "minecraft:suspicious_sand"); - sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); - let mut stairs = stairs(); - stairs["below"] = (0.45f32 as f64).into(); - pick( - "minecraft:orange_stained_glass", - vec![ - sus, - at(0.1, "minecraft:sand"), - at(0.2, "minecraft:sandstone"), - stairs, - ], - json!({"state": block("minecraft:cut_sandstone")}), - ) - } - "red_stained_glass_processor" => pick( - "minecraft:red_stained_glass", - vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], - stairs(), - ), - "pot_processor" => { - // Four sherds, one float each; the pot back to its default state. - let values: Vec = [ - (0.05f32, "archer"), - (0.1, "miner"), - (0.15, "prize"), - (0.2, "skull"), - ] - .iter() - .map(|(below, sherd)| { - json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) - }) - .collect(); - pick( - "minecraft:decorated_pot", - Vec::new(), - json!({"state": block("minecraft:decorated_pot"), "lists": [{ - "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), - ) - } - _ => return None, - }) -} - /// [`as_data`]'s `horizon:spawner_mobs` for the mods' spawner randomizing /// processors, whose fields have the same names and defaults. fn spawner_mobs(p: &Value, mobs: Vec, rules: Option) -> Value { @@ -1046,135 +595,6 @@ fn repurposed_light(p: &Value) -> Option> { Some(Some(rules)) } -/// An item as 26.3 saves it. -fn item(id: &str) -> Value { - json!({"id": format!("minecraft:{id}"), "count": 1}) -} - -/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's -/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a -/// spawner with that NBT. -fn yung_spawner(kind: &str, p: &Value) -> Option { - const SPAWNER: &str = "minecraft:spawner"; - // (input block, mob, fields other than the defaults, whether the mob is - // also the only potential, its equipment) - let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { - "betterdungeons:mob_spawner_processor" => { - (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) - } - "betterdungeons:zombie_mob_spawner_processor" => ( - SPAWNER, - "minecraft:zombie", - &[("MaxNearbyEntities", 8)], - true, - None, - ), - "betterdungeons:skeleton_mob_spawner_processor" => ( - SPAWNER, - "minecraft:skeleton", - &[ - ("RequiredPlayerRange", 18), - ("MaxNearbyEntities", 8), - ("MaxSpawnDelay", 650), - ], - true, - None, - ), - "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { - let mob = p["spawner_mob"].as_str()?; - // Wither skeletons get netherite armor that never drops and a - // stone sword (with the mod's default config, they and blazes - // keep their loot). - let armor = (mob == "minecraft:wither_skeleton").then(|| { - json!({ - "equipment": { - "feet": item("netherite_boots"), - "legs": item("netherite_leggings"), - "chest": item("netherite_chestplate"), - "head": item("netherite_helmet"), - "mainhand": item("stone_sword"), - }, - "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, - }) - }); - (SPAWNER, mob, &[], true, armor) - } - "betterdungeons:zombie_tombstone_spawner_processor" => ( - "minecraft:black_stained_glass", - "minecraft:skeleton", - &[], - false, - Some(json!({"equipment": {"mainhand": item("iron_sword")}})), - ), - "betterdeserttemples:gravel_processor" => ( - "minecraft:gravel", - "minecraft:husk", - &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], - false, - None, - ), - // An empty hand list in 1.21.1: the skeletons spawn without a bow, - // since a spawn entry with more than its id is not finalized. - "betterdeserttemples:bone_block_processor" => ( - "minecraft:bone_block", - "minecraft:skeleton", - &[("RequiredPlayerRange", 32)], - false, - Some(json!({"equipment": {}})), - ), - "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( - "minecraft:infested_cracked_stone_bricks", - "minecraft:silverfish", - &[("RequiredPlayerRange", 24)], - false, - None, - ), - // 1.21.1 ignores the items' old `Count` and `tag` (the shield's - // pattern, the boots' dye): plain items. - "betterdeserttemples:yellow_wool_processor" => ( - "minecraft:yellow_wool", - "minecraft:husk", - &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], - false, - Some(json!({"equipment": { - "mainhand": item("golden_sword"), - "offhand": item("shield"), - "feet": item("leather_boots"), - "legs": item("leather_leggings"), - "chest": item("golden_chestplate"), - "head": item("chainmail_helmet"), - }})), - ), - _ => return None, - }; - let mut entity = json!({"id": mob}); - if let Some(Value::Object(extra)) = equipment { - entity.as_object_mut()?.extend(extra); - } - let potentials = match potential { - true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), - false => json!([]), - }; - let mut nbt = json!({ - "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, - "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, - "SpawnData": {"entity": entity}, - "SpawnPotentials": potentials, - }); - for (key, value) in fields { - nbt[*key] = (*value).into(); - } - Some(json!({ - "processor_type": "minecraft:rule", - "rules": [{ - "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, - "location_predicate": {"predicate_type": "minecraft:always_true"}, - "output_state": {"Name": SPAWNER}, - "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, - }], - })) -} - #[cfg(test)] mod tests { use super::*; @@ -1246,54 +666,6 @@ mod tests { ); } - #[test] - fn yungs_spawners_become_rules() { - let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ - {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, - {"processor_type": "betterdeserttemples:bone_block_processor"}, - {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", - "spawner_mob": "minecraft:wither_skeleton"}, - {"processor_type": "betterdungeons:candle_processor"}]}}}]}); - let mut carried = BTreeMap::new(); - assert!(carry("template_pool", &mut pool, &data(), &mut carried)); - let p = &pool["elements"][0]["element"]["processors"]["processors"]; - let rule = |i: usize| &p[i]["rules"][0]; - assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); - assert_eq!( - rule(0)["output_state"], - json!({"Name": "minecraft:spawner"}) - ); - let nbt = &rule(0)["block_entity_modifier"]["data"]; - assert_eq!( - ( - nbt["RequiredPlayerRange"].clone(), - nbt["MaxNearbyEntities"].clone() - ), - (json!(18), json!(8)) - ); - assert_eq!(nbt["MaxSpawnDelay"], 650); - assert_eq!( - nbt["SpawnPotentials"], - json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) - ); - // Bone blocks become bowless skeleton spawners with no potentials. - let bone = &rule(1)["block_entity_modifier"]["data"]; - assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); - assert_eq!( - bone["SpawnData"], - json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) - ); - assert_eq!(bone["SpawnPotentials"], json!([])); - let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; - assert_eq!( - wither["equipment"]["head"]["id"], - "minecraft:netherite_helmet" - ); - assert_eq!(wither["drop_chances"]["feet"], 0.0); - assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); - assert_eq!(carried.values().sum::(), 3); - } - #[test] fn trial_spawners_and_vaults_drop_their_saved_state() { let mut list = json!({"processors": [ @@ -1355,41 +727,6 @@ mod tests { assert!(!upgrade_trial_spawner(&mut config)); } - #[test] - fn desert_temple_placeholders_become_rules_and_picks() { - let mut list = json!({"processors": [ - {"processor_type": "betterdeserttemples:red_wool_processor"}, - {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, - {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, - {"processor_type": "betterdeserttemples:pot_processor"}, - {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let p = list["processors"].as_array().unwrap(); - assert_eq!( - p[0]["rules"][0]["output_state"], - json!({"id": "minecraft:tnt"}) - ); - assert_eq!(p[1]["processor_type"], "horizon:pick"); - assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); - assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); - let glass = &p[2]["picks"]; - assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); - assert_eq!( - glass[0]["nbt"]["LootTable"], - "minecraft:archaeology/desert_pyramid" - ); - assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); - assert_eq!(glass[3]["below"], 0.45f32 as f64); - assert_eq!(p[3]["default"]["lists"][0]["count"], 4); - // The pillar reads the world below: still Java, still dropped later. - assert_eq!( - p[4]["processor_type"], - "betterdeserttemples:quartz_pillar_processor" - ); - assert_eq!(carried.values().sum::(), 4); - } - #[test] fn repurposed_waterlogging_follows_the_world() { let mut list = json!({"processors": [{"processor_type": @@ -1409,143 +746,6 @@ mod tests { ); } - #[test] - fn small_dungeon_chests_are_capped() { - let mut list = json!({"processors": [ - {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let cap = &list["processors"][0]; - assert_eq!(cap["processor_type"], "horizon:count_cap"); - assert_eq!( - (cap["min"].as_u64(), cap["max"].as_u64()), - (Some(1), Some(2)) - ); - assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); - } - - #[test] - fn lithostitched_block_swaps_become_the_games() { - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:block_swap", - "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, - {"processor_type": "lithostitched:block_swap", "blocks": []}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data(), &mut carried)); - let p = list["processors"].as_array().unwrap(); - assert_eq!( - p[0], - json!({"processor_type": "horizon:block_swap", - "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) - ); - // A map that is not one stays Java (dropped later). - assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); - } - - #[test] - fn modular_compat_runs_its_list_only_with_its_mod() { - let mut data = ProcessorData::default(); - let swap = json!({"processor_type": "minecraft:rule", "rules": []}); - data.lists - .insert("v:house_ns".into(), json!({"processors": [swap.clone()]})); - let compat = |m: &str| json!({"processor_type": "ctov:modular_compat", "modid": m, "reference": "v:house_ns"}); - let gravity = json!({"processor_type": "minecraft:gravity"}); - data.lists.insert( - "v:house".into(), - json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}), - ); - data.mark_loaded(&|m| m == "ns"); - assert_eq!(data.compat_loaded, BTreeSet::from(["ns".to_owned()])); - let mut v = json!({"processors": [compat("ns"), compat("absent"), gravity.clone()]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut v, &data, &mut carried)); - assert_eq!(v, json!({"processors": [swap, gravity]})); - assert_eq!(carried["ctov:modular_compat"], 2); - } - - #[test] - fn lithostitched_references_are_written_in() { - let mut data = data(); - let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}); - data.lists - .insert("v:road".into(), json!({"processors": [gravity.clone()]})); - data.lists.insert( - "v:house".into(), - json!({"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": "v:road"}, - {"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}), - ); - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]}, - {"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"}, - {"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data, &mut carried)); - let p = list["processors"].as_array().unwrap(); - // House (its own reference to road first, then its swap), then road; - // the swap inside is carried too. - assert_eq!(p[0], gravity); - assert_eq!(p[1]["processor_type"], "horizon:block_swap"); - assert_eq!(p[2], gravity); - // A tag or a list the mod lacks stays, to be dropped. - assert_eq!(p[3]["processor_lists"], "#v:roads"); - assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"])); - assert_eq!(carried["lithostitched:reference"], 2); - } - - #[test] - fn lithostitched_random_and_condition_become_the_games() { - let mut data = data(); - let swap = json!({"processor_type": "lithostitched:block_swap", - "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); - data.lists - .insert("v:green".into(), json!({"processors": [swap.clone()]})); - let mut list = json!({"processors": [ - {"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [ - {"weight": 3, "data": "minecraft:empty"}, - {"weight": 1, "data": {"processors": [ - {"processor_type": "lithostitched:reference", "processor_lists": "v:green"}, - {"processor_type": "v:java"}]}}]}, - {"processor_type": "lithostitched:apply_random", "mode": "per_block", - "processor_lists": ["v:green", "v:red"]}, - {"processor_type": "lithostitched:apply_random", "mode": "per_block", - "processor_lists": "#v:colours"}, - {"processor_type": "lithostitched:condition", - "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], - "then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider": - {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}}, - {"processor_type": "lithostitched:condition", - "if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"}, - "then": []}]}); - let mut carried = BTreeMap::new(); - assert!(carry("processor_list", &mut list, &data, &mut carried)); - let p = list["processors"].as_array().unwrap(); - let green = json!({"processor_type": "horizon:block_swap", - "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); - // Inline lists are carried; Java left in them is dropped later. - assert_eq!( - p[0], - json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [ - {"weight": 3, "data": "minecraft:empty"}, - {"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]}) - ); - assert_eq!( - p[1]["processor_lists"], - json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}]) - ); - assert_eq!(p[2]["processor_type"], "lithostitched:apply_random"); - assert_eq!( - p[3], - json!({"processor_type": "horizon:condition", - "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], - "then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider": - {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]}) - ); - assert_eq!(p[4]["processor_type"], "lithostitched:condition"); - assert_eq!(carried["lithostitched:apply_random"], 2); - assert_eq!(carried["lithostitched:condition"], 1); - } - #[test] fn repurposed_rule_tests_become_the_games() { let rule = |input: Value, position: Value| { @@ -1600,71 +800,6 @@ mod tests { )); } - #[test] - fn ocean_monuments_become_the_games() { - let names = [ - "random_prismarine_slab_decoration_processor", - "random_dark_prismarine_slab_decoration_processor", - "sand_gravel_processor", - "random_oxidization_processor", - "structure_void_processor", - "air_processor", - "waterlog_processor", - "seagrass_processor", - "random_sponge_processor", - "leg_processor", - ]; - let processors: Vec = names - .iter() - .map(|n| json!({"processor_type": format!("betteroceanmonuments:{n}")})) - .chain([json!({"processor_type": "betterwitchhuts:fence_leg_processor"})]) - .collect(); - let mut list = json!({"processors": processors}); - let mut carried = BTreeMap::new(); - assert!(carry( - "processor_list", - &mut list, - &ProcessorData::default(), - &mut carried - )); - let p = list["processors"].as_array().unwrap(); - let types: Vec<&str> = p - .iter() - .map(|p| p["processor_type"].as_str().unwrap()) - .collect(); - let mut want = vec!["horizon:pick", "horizon:pick", "minecraft:rule"]; - want.extend(["horizon:pick"; 4]); - want.extend([ - "horizon:keep_world_block", - "horizon:flood_air", - "horizon:waterlog", - "minecraft:rule", - "horizon:pick", - "horizon:yung_pillar", - "horizon:yung_pillar", - ]); - assert_eq!(types, want); - assert_eq!(carried.values().sum::(), 11); - // Copper stairs keep their properties, each chance on a new float. - let stairs = &p[5]; - assert_eq!(stairs["block"], "minecraft:oxidized_cut_copper_stairs"); - assert_eq!( - stairs["picks"][1]["state"]["id"], - "minecraft:weathered_cut_copper_stairs" - ); - assert_eq!( - (stairs["redraw"].clone(), stairs["keep_properties"].clone()), - (json!(true), json!(true)) - ); - assert_eq!(p[0]["picks"][0]["state"]["properties"]["type"], "top"); - assert_eq!(p[1]["default"]["state"]["id"], "minecraft:water"); - assert_eq!( - p[12]["target_block_output"]["defaultBlockState"]["id"], - "minecraft:prismarine_bricks" - ); - assert_eq!(p[13]["keep_properties"], true); - } - #[test] fn repurposed_structure_voids_keep_the_world() { let mut list = json!({"processors": [ diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 91b659217..1070b2aad 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -13,6 +13,11 @@ //! by name. 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. +//! +//! YUNG's, Lithostitched's and CTOV's worldgen files are converted by +//! `legacy_structure_mods`, called from [`upgrade`], [`crate::carry`] and the +//! processors. +use crate::legacy_structure_mods::{lithostitched, yung}; use serde_json::Value; use std::{ collections::{BTreeMap, BTreeSet}, @@ -21,8 +26,7 @@ use std::{ }; /// Structure types that are vanilla's jigsaw with extra start rules. -const JIGSAWS: [&str; 3] = [ - "lithostitched:jigsaw", +const JIGSAWS: [&str; 2] = [ "moogs_structures:moogs_structures_generic_jigsaw_structure", "repurposed_structures:generic_jigsaw_structure", ]; @@ -57,35 +61,6 @@ 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"), -]; /// Mo' Structures' placement (`mostructures:type`) takes its spacing and /// separation from the mod's config, not its files: the defaults it writes /// (MoStructuresConfig), by config key, as (spacing, separation). @@ -130,8 +105,8 @@ const LAYOUT_RULES: [&str; 4] = [ ]; /// The libraries' terrain kernel field, the game's /// `horizon:enhanced_terrain_adaptation` (docs/mods.md). -const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation"; -const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation"; +pub(crate) const ENHANCED_TERRAIN: &str = "enhanced_terrain_adaptation"; +pub(crate) const HORIZON_ENHANCED_TERRAIN: &str = "horizon:enhanced_terrain_adaptation"; /// Fields of older versions the mods' codecs no longer read: their own /// structures ignore them, and so does carry. Repurposed's jungle fortress /// and End stronghold still write `vertical_distance_from_start_piece`. @@ -181,195 +156,6 @@ pub struct Upgrade { /// `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 /// changed. /// `set_tags` are the mod's structure set tags, expanded @@ -474,15 +260,16 @@ fn upgrade_types( set_tags: &BTreeMap>, ) -> bool { let lost = &mut report.rules_lost; + // YUNG's and Lithostitched's types are converted apart from this code. + if let Some(changed) = + yung::upgrade(kind, v, set_tags, lost).or_else(|| lithostitched::upgrade(kind, v, lost)) + { + report.mapped += usize::from(changed); + return changed; + } let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; let changed = match kind { "structure" => match v["type"].as_str() { - // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a - // config switch that ships on. - Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { - yung_structure(v, lost); - true - } Some(t) if JIGSAWS.contains(&t) || NETHER_JIGSAWS.contains(&t) @@ -591,11 +378,6 @@ fn upgrade_types( true } Some("mostructures:type") => mo_placement(&mut v["placement"], lost), - 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 @@ -615,6 +397,10 @@ fn upgrade_types( } } for element in elements { + if yung::upgrade_pool_element(element, lost) { + changed = true; + continue; + } let Some(t) = element["element_type"].as_str() else { continue; }; @@ -629,9 +415,6 @@ fn upgrade_types( } element["element_type"] = (*to).into(); changed = true; - } else if t == "yungsapi:yung_single_element" { - yung_element(element, lost); - changed = true; } else if t == "formations:single_pool_element" { // Vanilla's element with its own ground level (1 when // missing, as its codec reads it). @@ -653,167 +436,10 @@ 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 under `horizon:enhanced_terrain_adaptation`. A start offset in -/// the chunk is 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); - } - } - // YungJigsawStructure's adaptation (NONE by default): every piece's - // junctions, and the start's box grown by its radius. - let own = o.remove(ENHANCED_TERRAIN); - let mut kernel = yung_terrain(own.as_ref().unwrap_or(&Value::Null), lost); - kernel["rigid_junctions"] = true.into(); - kernel["inflate"] = true.into(); - o.insert(HORIZON_ENHANCED_TERRAIN.into(), kernel); - 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`, its condition, dead-end pool and modifiers; its terrain -/// adaptation under `horizon:enhanced_terrain_adaptation`. -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)); - } - // A piece's own adaptation, NONE included, replaces its structure's. - if let Some(a) = o.remove(ENHANCED_TERRAIN) { - o.insert(HORIZON_ENHANCED_TERRAIN.into(), yung_terrain(&a, lost)); - } - if let Some(pool) = o.remove("deadend_pool").filter(Value::is_string) { - rules.insert("deadend_pool".into(), pool); - } - let modifiers: Vec = o - .remove("modifiers") - .and_then(|m| m.as_array().cloned()) - .unwrap_or_default() - .iter() - .filter_map(|m| yung_modifier(m, lost)) - .collect(); - if !modifiers.is_empty() { - rules.insert("modifiers".into(), modifiers.into()); - } - o.insert("horizon:yungsapi".into(), rules.into()); -} - -/// One of YUNG's structure modifiers in the game's terms: its condition and -/// its transform and delay_generation actions, on the piece itself (`self`, -/// the API's only target). Another target loses the modifier, another action -/// just that action. -fn yung_modifier(m: &Value, lost: &mut BTreeMap) -> Option { - let target = m["target_selector"]["type"].as_str().unwrap_or_default(); - if target != "yungsapi:self" { - *lost - .entry(format!("yungsapi modifier target {target}")) - .or_default() += 1; - return None; - } - let mut actions = Vec::new(); - for a in m["actions"].as_array().into_iter().flatten() { - let int = |k: &str| a[k].as_i64().unwrap_or(0); - match a["type"].as_str().unwrap_or_default() { - "yungsapi:transform" => actions.push(serde_json::json!({"type": "transform", - "output": a["output"].clone(), - "offset": [int("x_offset"), int("y_offset"), int("z_offset")]})), - "yungsapi:delay_generation" => { - actions.push(serde_json::json!({"type": "delay_generation"})) - } - other => { - *lost - .entry(format!("yungsapi modifier action {other}")) - .or_default() += 1 - } - } - } - let condition = match m.get("condition") { - Some(c) => yung_condition(c, lost), - None => serde_json::json!({"type": "true"}), - }; - Some(serde_json::json!({"condition": condition, "actions": actions})) -} - -/// YUNG's API's terrain adaptation as the game's kernel: its two presets -/// spelled out, NONE (also the default) as size 0. An aquifer override -/// (none of ATM10's) is lost. -fn yung_terrain(a: &Value, lost: &mut BTreeMap) -> Value { - let kernel = |size: i32, distance: i32, top: &str, bottom: &str| { - serde_json::json!({"kernel_size": size, "kernel_distance": distance, - "top": top, "bottom": bottom}) - }; - match a["type"].as_str() { - Some("yungsapi:carved_top_no_beard_large") => kernel(24, 16, "carve", "none"), - Some("yungsapi:carved_top_no_beard_small") => kernel(12, 6, "carve", "none"), - Some("yungsapi:custom") => { - let mut out = serde_json::Map::new(); - for key in [ - "kernel_size", - "kernel_distance", - "top", - "bottom", - "bottom_offset", - "padding", - ] { - if let Some(x) = a.get(key) { - out.insert(key.into(), x.clone()); - } - } - if a.get("aquifer_override") - .is_some_and(|x| x["type"] != "yungsapi:none") - { - *lost.entry("yungsapi aquifer_override".into()).or_default() += 1; - } - moogs_terrain(&out.into(), lost).unwrap_or_else(|| kernel(0, 0, "none", "none")) - } - None | Some("yungsapi:none") => kernel(0, 0, "none", "none"), - Some(other) => { - *lost - .entry(format!("yungsapi terrain adaptation {other}")) - .or_default() += 1; - kernel(0, 0, "none", "none") - } - } -} - /// MoogsStructureLib's terrain adaptation: already the game's shape (with /// its band), when it has the fields the game needs (else it is lost, as /// the library's codec would refuse it). -fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option { +pub(crate) fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option { let ok = ["kernel_size", "kernel_distance"] .iter() .all(|k| a[k].is_u64()) @@ -824,58 +450,15 @@ fn moogs_terrain(a: &Value, lost: &mut BTreeMap) -> Option ok.then(|| a.clone()) } -/// 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")}) - } - // The game reads "yungsapi:all" (or no list) as any piece. - "piece_in_range" => serde_json::json!({"type": "piece_in_range", - "pieces": c.get("pieces").cloned().unwrap_or_else(|| Vec::::new().into()), - "horizontal_range": opt("horizontal_range"), "above_range": opt("above_range"), - "below_range": opt("below_range")}), - "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, limited: bool) { +pub(crate) fn start_checks( + v: &mut Value, + liquid: &str, + lost: &mut BTreeMap, + limited: bool, +) { let Some(o) = v.as_object_mut() else { return; }; @@ -1043,7 +626,7 @@ fn moogs_spacing(p: &mut Value, lost: &mut BTreeMap) { /// An advanced random spread's minimum distance from the world origin and /// its super exclusion zone (sets named by a tag) under `horizon:` keys. -fn placement_rules( +pub(crate) fn placement_rules( p: &mut Value, set_tags: &BTreeMap>, lost: &mut BTreeMap, @@ -1115,65 +698,6 @@ fn mo_placement(p: &mut Value, lost: &mut BTreeMap) -> bool { true } -/// 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. @@ -1590,94 +1114,6 @@ 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, - "kernel_distance": 24, "top": "carve", "bottom": "none"}}); - assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); - assert_eq!(s["type"], "minecraft:jigsaw"); - assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); - assert_eq!( - s["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 24, "kernel_distance": 24, "top": "carve", "bottom": "none", - "rigid_junctions": true, "inflate": true}) - ); - for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { - assert!(s.get(gone).is_none(), "{gone}"); - } - // Better Dungeons' small Nether dungeon is the same jigsaw. - let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", - "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, - "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", - "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); - assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); - assert_eq!(nether["type"], "minecraft:jigsaw"); - assert_eq!(nether["horizon:yungsapi"], json!({})); - assert_eq!( - nether["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 0, "kernel_distance": 0, "top": "none", "bottom": "none", - "rigid_junctions": true, "inflate": true}) - ); - assert_eq!( - nether["start_jigsaw_name"], - "betterdungeons:small_nether_dungeon_anchor" - ); - assert!(report.unsupported.is_empty()); - 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", - "modifiers": [ - {"condition": {"type": "yungsapi:piece_in_range", "pieces": ["y:pillar"], - "above_range": 40}, - "target_selector": {"type": "yungsapi:self"}, - "actions": [{"type": "yungsapi:transform", "output": ["y:covered"], "x_offset": -1}, - {"type": "yungsapi:delay_generation"}, {"type": "yungsapi:spin"}]}, - {"condition": {"type": "yungsapi:always_true"}, - "target_selector": {"type": "yungsapi:all"}, "actions": []}], - "enhanced_terrain_adaptation": {"type": "yungsapi:carved_top_no_beard_small"}, - "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"}]}, - "deadend_pool": "y:end", - "modifiers": [{"condition": {"type": "piece_in_range", "pieces": ["y:pillar"], - "horizontal_range": null, "above_range": 40, "below_range": null}, - "actions": [{"type": "transform", "output": ["y:covered"], "offset": [-1, 0, 0]}, - {"type": "delay_generation"}]}]}) - ); - assert!(e.get("deadend_pool").is_none() && e.get("modifiers").is_none()); - assert_eq!( - e["horizon:enhanced_terrain_adaptation"], - json!({"kernel_size": 12, "kernel_distance": 6, "top": "carve", "bottom": "none"}) - ); - assert_eq!( - report.rules_lost, - BTreeMap::from([ - ("yungsapi condition yungsapi:biome".into(), 1), - ("yungsapi modifier action yungsapi:spin".into(), 1), - ("yungsapi modifier target yungsapi:all".into(), 1), - ]) - ); - assert!(report.unsupported.is_empty()); - } - #[test] fn drops_processors_written_in_java() { let mut report = Upgrade::default(); @@ -1722,59 +1158,6 @@ 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(); @@ -1886,88 +1269,6 @@ 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([