diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index cc04ae033..266928b2f 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -279,6 +279,11 @@ 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] + } _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], _ => return None, }) @@ -407,6 +412,110 @@ 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 { @@ -773,6 +882,41 @@ 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_rule_tests_become_the_games() { let rule = |input: Value, position: Value| { diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index 4bdb94729..acd4297ca 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -286,6 +286,7 @@ pub enum Processor { LavaSubmerged, BlackstoneReplace, SpawnerMobs(Box), + Pick(Box), } #[derive(Clone, Debug, Default)] pub struct ProcessorList(pub Vec); @@ -302,6 +303,146 @@ const SPAWNER_FIELDS: [(&str, &str, i16); 7] = [ ("spawn_range", "SpawnRange", 4), ]; +/// `horizon:pick`, which `horizon-port-pack` writes for the mods' processors +/// that turn a placeholder block into one of several (YUNG's, written in +/// Java): a block of `block` takes the first of `picks` whose `below` is past +/// one `settings.getRandom(pos).nextFloat()`, else `default` (no float is +/// drawn when there are no picks; with no default the block stays). +#[derive(Clone, Debug)] +pub struct Pick { + block: String, + picks: Vec<(f32, Outcome)>, + default: Option, +} +#[derive(Clone, Debug)] +struct Outcome { + /// The state, or one of them by `nextInt(len)` (Util.getRandom), drawn + /// after the pick. + states: Vec, + /// The new block entity; the block's own stays when missing. + nbt: Option, + /// Keys set to lists of `count` strings, each the first of `values` + /// whose bound is past a new `nextFloat`, else `default` (pot sherds). + lists: Vec, +} +#[derive(Clone, Debug)] +struct PickedList { + key: String, + count: usize, + values: Vec<(f32, String)>, + default: String, +} +fn below(v: &Value) -> Result { + v["below"] + .as_f64() + .map(|b| b as f32) + .ok_or(DecodeError::Field("pick bound")) +} +impl Pick { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result, + ) -> Result { + let outcome = |v: &Value| -> Result { + let states = match v.get("states") { + Some(list) => list + .as_array() + .ok_or(DecodeError::Field("pick states"))? + .iter() + .map(&state) + .collect::, _>>()?, + None => vec![state(&v["state"])?], + }; + if states.is_empty() { + return Err(DecodeError::Field("pick states")); + } + let nbt = match v.get("nbt").map(json_to_nbt) { + Some(Tag::Compound(c)) => Some(c), + Some(_) => return Err(DecodeError::Field("pick nbt")), + None => None, + }; + let text = |v: &Value| { + v.as_str() + .map(str::to_owned) + .ok_or(DecodeError::Field("pick list")) + }; + let lists = v["lists"] + .as_array() + .into_iter() + .flatten() + .map(|l| { + Ok(PickedList { + key: text(&l["key"])?, + count: l["count"].as_u64().ok_or(DecodeError::Field("pick list"))? as usize, + values: l["values"] + .as_array() + .into_iter() + .flatten() + .map(|e| Ok((below(e)?, text(&e["value"])?))) + .collect::>()?, + default: text(&l["default"])?, + }) + }) + .collect::>()?; + Ok(Outcome { states, nbt, lists }) + }; + Ok(Self { + block: value["block"] + .as_str() + .map(|b| super::super::tags::identifier(b).map(|i| i.to_string())) + .ok_or(DecodeError::Field("pick block"))??, + picks: value["picks"] + .as_array() + .into_iter() + .flatten() + .map(|p| Ok((below(p)?, outcome(p)?))) + .collect::>()?, + default: value.get("default").map(outcome).transpose()?, + }) + } + fn apply(&self, info: BlockInfo, random: &mut dyn ProcessorRandom) -> BlockInfo { + let outcome = match self.picks.is_empty() { + true => self.default.as_ref(), + false => { + let f = random.float(); + self.picks + .iter() + .find(|(b, _)| f < *b) + .map(|(_, o)| o) + .or(self.default.as_ref()) + } + }; + let Some(outcome) = outcome else { + return info; + }; + let state = match outcome.states.as_slice() { + [one] => *one, + many => many[random.int(many.len() as i32) as usize], + }; + let mut nbt = outcome.nbt.clone().or(info.nbt); + for list in &outcome.lists { + let values = (0..list.count) + .map(|_| { + let f = random.float(); + let v = list + .values + .iter() + .find(|(b, _)| f < *b) + .map_or(&list.default, |(_, v)| v); + Tag::String(v.as_str().into()) + }) + .collect(); + nbt.get_or_insert_with(Compound::new) + .insert(list.key.as_str().into(), Tag::List(values)); + } + BlockInfo { + pos: info.pos, + state, + nbt, + } + } +} + /// `horizon:spawner_mobs`, which `horizon-port-pack` writes for the spawner /// randomizing processors of Moog's Structure Lib and Repurposed Structures /// (Java code in the mods): a spawner gets one mob of a weighted list, @@ -533,6 +674,7 @@ impl Processor { None => Ok(resources.registry.default_state("minecraft:air").unwrap()), })?)) } + "horizon:pick" => Self::Pick(Box::new(Pick::decode(value, state)?)), _ => return Err(DecodeError::Field("structure processor type")), }) } @@ -764,6 +906,10 @@ fn process_block( Some(info) } Processor::Capped { .. } => Some(info), + Processor::Pick(pick) => match name(info.state) == pick.block { + true => Some(settings.with_random(info.pos, |r| pick.apply(info, r))), + false => Some(info), + }, Processor::SpawnerMobs(spawner) => { if name(info.state) != "minecraft:spawner" { return Ok(Some(info)); @@ -1471,4 +1617,111 @@ mod tests { let bad = json!({"type": "horizon:edit", "remove": [1], "data": {}}); assert!(Modifier::decode(Some(&bad)).is_err()); } + + /// Scripted draws: floats in turn, then ints. + struct Draws(Vec, Vec); + impl ProcessorRandom for Draws { + fn float(&mut self) -> f32 { + self.0.remove(0) + } + fn int(&mut self, bound: i32) -> i32 { + let i = self.1.remove(0); + assert!(i < bound); + i + } + fn long(&mut self) -> i64 { + unreachable!() + } + } + + #[test] + fn picks_follow_yungs_cascade() { + // States by name: sand 1, sandstone 2, the four stairs 10..13. + let id = |v: &Value| { + Ok(BlockStateId(match v["Name"].as_str() { + Some("minecraft:sand") => 1, + Some("minecraft:sandstone") => 2, + Some("minecraft:suspicious_sand") => 3, + _ => { + 10 + ["north", "east", "south", "west"] + .iter() + .position(|f| v["Properties"]["facing"] == *f) + .unwrap_or(9) as u32 + } + })) + }; + let stairs: Vec = ["north", "east", "south", "west"] + .iter() + .map(|f| json!({"Name": "minecraft:sandstone_stairs", "Properties": {"facing": f}})) + .collect(); + let pick = Pick::decode( + &json!({"block": "red_stained_glass", "picks": [ + {"below": 0.01, "state": {"Name": "minecraft:suspicious_sand"}, + "nbt": {"LootTable": "minecraft:archaeology/desert_pyramid"}}, + {"below": 0.3, "state": {"Name": "minecraft:sand"}}, + {"below": 0.75, "state": {"Name": "minecraft:sandstone"}}], + "default": {"states": stairs}}), + id, + ) + .unwrap(); + assert_eq!(pick.block, "minecraft:red_stained_glass"); + let glass = || BlockInfo { + pos: [1, 2, 3], + state: BlockStateId(0), + nbt: Some(Compound::new()), + }; + let run = |f: f32, i: Vec| pick.apply(glass(), &mut Draws(vec![f], i)); + let sus = run(0.005, vec![]); + assert_eq!(sus.state, BlockStateId(3)); + assert!( + sus.nbt + .unwrap() + .contains_key(&JavaString::from("LootTable")) + ); + assert_eq!(run(0.01, vec![]).state, BlockStateId(1)); + assert_eq!(run(0.2999, vec![]).nbt, Some(Compound::new())); + assert_eq!(run(0.3, vec![]).state, BlockStateId(2)); + // The stairs' facing: Plane.HORIZONTAL[nextInt(4)] after the pick. + assert_eq!(run(0.75, vec![2]).state, BlockStateId(12)); + assert_eq!(run(0.99, vec![1]).state, BlockStateId(11)); + + let pot = Pick::decode( + &json!({"block": "minecraft:decorated_pot", "default": { + "state": {"Name": "minecraft:sand"}, + "lists": [{"key": "sherds", "count": 4, "default": "minecraft:brick", + "values": [{"below": 0.05, "value": "minecraft:archer_pottery_sherd"}, + {"below": 0.1, "value": "minecraft:miner_pottery_sherd"}]}]}}), + id, + ) + .unwrap(); + // No picks: no float for them; one float per sherd. + let out = pot.apply( + BlockInfo { + nbt: None, + ..glass() + }, + &mut Draws(vec![0.5, 0.01, 0.07, 0.1], vec![]), + ); + let Some(Tag::List(sherds)) = out.nbt.unwrap().get(&JavaString::from("sherds")).cloned() + else { + panic!("sherds") + }; + let names: Vec = sherds + .iter() + .map(|t| match t { + Tag::String(s) => s.to_string_lossy(), + _ => String::new(), + }) + .collect(); + assert_eq!( + names, + [ + "minecraft:brick", + "minecraft:archer_pottery_sherd", + "minecraft:miner_pottery_sherd", + "minecraft:brick" + ] + ); + assert!(Pick::decode(&json!({"block": "a", "default": {"states": []}}), id).is_err()); + } } diff --git a/docs/modpacks.md b/docs/modpacks.md index 5bbb99d80..1f792f7b4 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -453,9 +453,13 @@ Two cases the oracle fills in: template was saved with (a vault saved with `state_updating_resumes_at` far in the future never opens; a spawner's saved `spawn_data` blocks its own mobs) and merges in the spawner's normal and ominous configs (by id: the carry upgrades `trial_spawner/` files' - mobs to 26.3's `equipment`) or the vault's loot table and key. 125 of the 1,427 - processors are carried; 1,302 are still taken out (blocks swapped, aged or propped up, - YUNG's chest caps). + mobs to 26.3's `equipment`) or the vault's loot table and key. Better Desert Temples' + placeholder blocks (orange, red and white glass, blue and yellow concrete, red wool, + polished diorite, blank pots) become what its processors make of them: the fixed swaps as + vanilla's `rule`, the random ones (suspicious sand, sand and sandstone, upside-down stairs, + cobwebs, sherds on the pots) as the game's `horizon:pick`, on the same `nextFloat` as the + mod. 133 of the 1,427 processors are carried; 1,294 are still taken out (blocks swapped, + aged or propped up, YUNG's chest caps). In the 128×128-chunk square (seed 1234), every spawner of a mod structure now has its mob: in the Overworld 83 Better Dungeons spawners held the template's placeholder pig and 17 of Moog's were empty (763 spawners with a mob, up from 628); in the Nether the 52 empty ones