diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index b342f45fd..2f4af104c 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -205,6 +205,29 @@ pub fn upgrade_recipe(recipe: &mut Value) -> bool { true } +/// Block and item ids vanilla renamed after 1.21.1, as its datafixers +/// rename them in worlds (DataVersion 4541: the chain became the iron chain +/// when copper chains came in). A data file naming the old id fails to load +/// in 26.3: a recipe, a loot entry, a processor's block match. +const RENAMED_IDS: [(&str, &str); 1] = [("minecraft:chain", "minecraft:iron_chain")]; + +/// Every string of a data file that is a renamed id ([`RENAMED_IDS`]) set to +/// the new one, in place; whether any was. +pub fn renamed_ids(v: &mut Value) -> bool { + match v { + Value::String(s) => match RENAMED_IDS.iter().find(|(old, _)| s == old) { + Some((_, new)) => { + *s = (*new).to_owned(); + true + } + None => false, + }, + Value::Array(a) => a.iter_mut().fold(false, |c, x| renamed_ids(x) | c), + Value::Object(o) => o.values_mut().fold(false, |c, x| renamed_ids(x) | c), + _ => false, + } +} + /// A 1.21.1 loot table in 26.3's shape, in place: `conditions` lists become /// one `condition` (`all_of` for several), `functions` become `modifier`, /// and conditions and functions name their kind in `type`. A tool match on @@ -410,12 +433,16 @@ pub fn carry( { if let Ok(mut recipe) = serde_json::from_slice::(&bytes) { tags_used(&recipe, &mut convention); - if upgrade_recipe(&mut recipe) { + let renamed = renamed_ids(&mut recipe); + let upgraded = upgrade_recipe(&mut recipe); + if upgraded { report.recipes_upgraded += 1; - bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); } else { report.recipes_kept.push(file.to_owned()); } + if upgraded || renamed { + bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); + } } } else if let Some(kind) = rel .strip_prefix("worldgen/") @@ -433,6 +460,10 @@ pub fn carry( &mut v, &processor_data, &mut types.processors_carried, + ) | crate::processors::rule_tests( + kind, + &mut v, + &mut types.rule_tests_carried, ); let mut changed = crate::worldgen::upgrade(kind, &mut v, types, &set_tags) || carried; @@ -463,6 +494,7 @@ pub fn carry( &processor_data, &mut types.processors_carried, ); + crate::processors::rule_tests(kind, &mut added, &mut types.rule_tests_carried); crate::worldgen::upgrade(kind, &mut added, types, &set_tags); let to = format!( "data/{id}/worldgen/{kind}/{}/{path}", @@ -473,6 +505,16 @@ pub fn carry( &serde_json::to_vec_pretty(&added).unwrap_or_default(), )?; } + } else if rel.starts_with("trial_spawner/") + && name.starts_with("data/") + && name.ends_with(".json") + { + // Trial spawner configs (Moog's arenas): their mobs' NBT. + if let Ok(mut config) = serde_json::from_slice::(&bytes) + && crate::processors::upgrade_trial_spawner(&mut config) + { + bytes = serde_json::to_vec_pretty(&config).unwrap_or(bytes); + } } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { if let Ok(v) = serde_json::from_slice::(&bytes) { crate::worldgen::convention_tags(&v, &mut biome_conventions); @@ -487,6 +529,7 @@ pub fn carry( if let Ok(mut table) = serde_json::from_slice::(&bytes) { let before = table.clone(); upgrade_loot(&mut table); + renamed_ids(&mut table); if table != before { report.loot_tables_upgraded += 1; bytes = serde_json::to_vec_pretty(&table).unwrap_or(bytes); @@ -809,6 +852,27 @@ mod tests { assert_eq!(new, glass); } + #[test] + fn renames_ids_vanilla_renamed() { + let mut recipe = json!({"type": "minecraft:crafting_shaped", "pattern": ["c"], + "key": {"c": {"item": "minecraft:chain"}}, "result": {"id": "m:sign", "count": 1}}); + assert!(renamed_ids(&mut recipe)); + assert_eq!(recipe["key"]["c"]["item"], "minecraft:iron_chain"); + let mut rule = json!({"input_predicate": {"predicate_type": "minecraft:block_match", + "block": "minecraft:chain"}, "output_state": {"id": "minecraft:chain", + "properties": {"axis": "y"}}}); + assert!(renamed_ids(&mut rule)); + assert_eq!(rule["input_predicate"]["block"], "minecraft:iron_chain"); + assert_eq!(rule["output_state"]["id"], "minecraft:iron_chain"); + // Only whole ids: other blocks and mods' own chains stay. + let mut other = json!([ + "minecraft:chain_command_block", + "m:chain", + "minecraft:iron_chain" + ]); + assert!(!renamed_ids(&mut other)); + } + #[test] fn templates_from_blockstate_properties() { let door = diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index 7fcc0fd94..33cde2f99 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -150,6 +150,49 @@ pub fn carry( }) } +/// 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] = [ + ( + "repurposed_structures:matter_phase_rule_test", + "horizon:matter_phase", + ), + ( + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "horizon:piece_origin_axis_aligned_linear_pos", + ), + ( + "repurposed_structures:y_value_pos_rule_test", + "horizon:y_value", + ), +]; + +/// Renames the rule tests written in Java that the game runs under its own +/// type ([`RULE_TESTS`]) in a worldgen file's processor lists; each is +/// counted by type in `carried`. Their fields are the mod's. Whether +/// anything changed. Without this the game, like vanilla, refuses the list +/// and every pool naming it: Repurposed's mineshafts and Nether monument. +pub fn rule_tests(kind: &str, v: &mut Value, carried: &mut BTreeMap) -> bool { + fn rename(v: &mut Value, carried: &mut BTreeMap) -> bool { + match v { + Value::Object(o) => { + let mut changed = false; + if let Some(Value::String(t)) = o.get_mut("predicate_type") + && let Some((old, new)) = RULE_TESTS.iter().find(|(old, _)| t == old) + { + *carried.entry((*old).to_owned()).or_default() += 1; + *t = (*new).to_owned(); + changed = true; + } + o.values_mut().fold(changed, |c, x| rename(x, carried) | c) + } + Value::Array(a) => a.iter_mut().fold(false, |c, x| rename(x, carried) | c), + _ => false, + } + } + each_list(kind, v, &mut |list| rename(list, carried)) +} + /// 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> { @@ -193,11 +236,299 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { } Vec::new() } + "moogs_structures:trial_spawner_randomizing_processor" => { + // The configs by id: 26.3 reads them from `trial_spawner/`, the + // folder Moog's loads them from. + let mut nbt = json!({"normal_config": p["normal_config"].as_str()?}); + if let Some(ominous) = p["ominous_config"].as_str() { + nbt["ominous_config"] = ominous.into(); + } + // The state the template was saved with goes. + let saved = [ + "server_data", + "shared_data", + "spawn_data", + "cooldown_end_at_tick", + "next_mob_spawns_at", + ]; + vec![same_state_rule(&TRIAL_SPAWNER_STATES, &saved, |_| { + nbt.clone() + })] + } + "moogs_structures:vault_randomizing_processor" => { + let normal = p["loot_table"].as_str()?; + let config = |ominous: bool| { + let (table, key) = match ominous { + true => ( + p["ominous_loot_table"].as_str().unwrap_or(normal), + p["ominous_key_item"] + .as_str() + .unwrap_or("minecraft:ominous_trial_key"), + ), + false => ( + normal, + p["key_item"].as_str().unwrap_or("minecraft:trial_key"), + ), + }; + // Merged into the vault's config, as the mod puts both in. + json!({"config": {"loot_table": table, "key_item": {"id": key, "count": 1}}}) + }; + vec![same_state_rule( + &VAULT_STATES, + &["server_data", "shared_data"], + |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"]})] + } + "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")})] + } _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], _ => return None, }) } +/// A block's states, as (block, [(property, values)]). +type States = ( + &'static str, + &'static [(&'static str, &'static [&'static str])], +); +const TRIAL_SPAWNER_STATES: States = ( + "minecraft:trial_spawner", + &[ + ( + "trial_spawner_state", + &[ + "inactive", + "waiting_for_players", + "active", + "waiting_for_reward_ejection", + "ejecting_reward", + "cooldown", + ], + ), + ("ominous", &["false", "true"]), + ], +); +const VAULT_STATES: States = ( + "minecraft:vault", + &[ + ("facing", &["north", "south", "west", "east"]), + ( + "vault_state", + &["inactive", "active", "unlocking", "ejecting"], + ), + ("ominous", &["false", "true"]), + ], +); + +/// Moog's trial spawner and vault processors keep the block, take keys out +/// of its block entity and set others. As vanilla's `rule`: one rule per +/// state of the block, matching it and writing it back, with the game's +/// `horizon:edit` modifier taking out `remove` and merging `nbt(state)` in. +fn same_state_rule( + states: &States, + remove: &[&str], + nbt: impl Fn(&BTreeMap<&str, &str>) -> Value, +) -> Value { + let (block, properties) = states; + let mut all = vec![BTreeMap::new()]; + for (key, values) in properties.iter() { + all = all + .into_iter() + .flat_map(|s| { + values.iter().map(move |v| { + let mut s = s.clone(); + s.insert(*key, *v); + s + }) + }) + .collect(); + } + let rules: Vec = all + .iter() + .map(|s| { + let state = json!({"id": block, "properties": s}); + json!({ + "input_predicate": {"predicate_type": "minecraft:blockstate_match", "block_state": state}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": state, + "block_entity_modifier": {"type": "horizon:edit", "remove": remove, "data": nbt(s)}, + }) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) +} + +/// An entity's NBT in 26.3's shape, in place: 1.21.1's `ArmorItems` (feet +/// to head), `HandItems` (main hand, off hand) and their drop chances become +/// `equipment` and `drop_chances` by slot; empty items and the default drop +/// chance (0.085) are left out, as 26.3 saves them. Whether it changed. +pub fn upgrade_entity(entity: &mut Value) -> bool { + let Some(o) = entity.as_object_mut() else { + return false; + }; + const ARMOR: [&str; 4] = ["feet", "legs", "chest", "head"]; + const HANDS: [&str; 2] = ["mainhand", "offhand"]; + let mut changed = false; + for (items, chances, slots) in [ + ("ArmorItems", "ArmorDropChances", &ARMOR[..]), + ("HandItems", "HandDropChances", &HANDS[..]), + ] { + if let Some(Value::Array(list)) = o.remove(items) { + changed = true; + for (slot, item) in slots.iter().zip(list) { + if item.get("id").is_some() { + let equipment = o.entry("equipment").or_insert_with(|| json!({})); + equipment[*slot] = item; + } + } + } + if let Some(Value::Array(list)) = o.remove(chances) { + changed = true; + for (slot, chance) in slots.iter().zip(list) { + if chance.as_f64().is_some_and(|c| (c - 0.085).abs() > 1e-6) { + let drop = o.entry("drop_chances").or_insert_with(|| json!({})); + drop[*slot] = chance; + } + } + } + } + changed +} + +/// A 1.21.1 trial spawner config (`trial_spawner/`) in 26.3's shape, in +/// place: its mobs' NBT ([`upgrade_entity`]). Whether it changed. +pub fn upgrade_trial_spawner(config: &mut Value) -> bool { + let mut changed = false; + for p in config["spawn_potentials"] + .as_array_mut() + .into_iter() + .flatten() + { + changed |= upgrade_entity(&mut p["data"]["entity"]); + } + 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 { @@ -502,4 +833,187 @@ mod tests { 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": [ + {"processor_type": "moogs_structures:trial_spawner_randomizing_processor", + "normal_config": "mns:arena/normal", "ominous_config": "mns:arena/ominous"}, + {"processor_type": "moogs_structures:vault_randomizing_processor", + "loot_table": "mns:vaults/main", "ominous_loot_table": "mns:vaults/ominous"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + let rules = |i: usize| p[i]["rules"].as_array().unwrap().clone(); + // Every state of the block: 6 x 2 trial spawners, 4 x 4 x 2 vaults. + assert_eq!((rules(0).len(), rules(1).len()), (12, 32)); + let spawner = &rules(0)[0]; + assert_eq!( + spawner["input_predicate"]["block_state"], + spawner["output_state"] + ); + assert_eq!( + spawner["block_entity_modifier"], + json!({"type": "horizon:edit", + "remove": ["server_data", "shared_data", "spawn_data", + "cooldown_end_at_tick", "next_mob_spawns_at"], + "data": {"normal_config": "mns:arena/normal", + "ominous_config": "mns:arena/ominous"}}) + ); + for rule in rules(1) { + let ominous = rule["output_state"]["properties"]["ominous"] == "true"; + let (table, key) = match ominous { + true => ("mns:vaults/ominous", "minecraft:ominous_trial_key"), + false => ("mns:vaults/main", "minecraft:trial_key"), + }; + assert_eq!( + rule["block_entity_modifier"], + json!({"type": "horizon:edit", "remove": ["server_data", "shared_data"], + "data": {"config": {"loot_table": table, + "key_item": {"id": key, "count": 1}}}}) + ); + } + assert_eq!(carried.len(), 2); + } + + #[test] + fn trial_spawner_mobs_take_26_3s_equipment() { + let mut config = json!({"spawn_potentials": [{"weight": 1, "data": {"entity": { + "id": "minecraft:skeleton", + "ArmorItems": [{}, {}, {}, {"id": "minecraft:iron_helmet", "count": 1}], + "ArmorDropChances": [0.085, 0.085, 0.085, 0.0], + "HandItems": [{"id": "minecraft:bow", "count": 1}, {}], + "HandDropChances": [0.085, 0.085]}}}]}); + assert!(upgrade_trial_spawner(&mut config)); + assert_eq!( + config["spawn_potentials"][0]["data"]["entity"], + json!({"id": "minecraft:skeleton", + "equipment": {"head": {"id": "minecraft:iron_helmet", "count": 1}, + "mainhand": {"id": "minecraft:bow", "count": 1}}, + "drop_chances": {"head": 0.0}}) + ); + 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 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 repurposed_rule_tests_become_the_games() { + let rule = |input: Value, position: Value| { + json!({"input_predicate": input, "location_predicate": {"predicate_type": + "repurposed_structures:matter_phase_rule_test", "phase_to_test_for": "AIR"}, + "position_predicate": position, "output_state": {"id": "minecraft:lava"}}) + }; + let mut pool = json!({"elements": [{"weight": 1, "element": { + "element_type": "minecraft:single_pool_element", "processors": {"processors": [ + {"processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:always_true"}), + json!({"predicate_type": "repurposed_structures:y_value_pos_rule_test", + "min_y_value": 0, "max_y_value": 31}))]}, + {"processor_type": "minecraft:capped", "limit": 2, "delegate": { + "processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:block_match", "block": "minecraft:rail"}), + json!({"predicate_type": + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "axis": "y", "min_dist": 0, "max_dist": 1}))]}}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(rule_tests("template_pool", &mut pool, &mut carried)); + let list = &pool["elements"][0]["element"]["processors"]["processors"]; + let first = &list[0]["rules"][0]; + assert_eq!( + first["location_predicate"]["predicate_type"], + "horizon:matter_phase" + ); + assert_eq!(first["location_predicate"]["phase_to_test_for"], "AIR"); + assert_eq!( + first["position_predicate"]["predicate_type"], + "horizon:y_value" + ); + assert_eq!(first["position_predicate"]["max_y_value"], 31); + let delegated = &list[1]["delegate"]["rules"][0]; + assert_eq!( + delegated["position_predicate"]["predicate_type"], + "horizon:piece_origin_axis_aligned_linear_pos" + ); + assert_eq!( + delegated["input_predicate"]["predicate_type"], + "minecraft:block_match" + ); + assert_eq!(carried.values().sum::(), 4); + assert_eq!(carried["repurposed_structures:matter_phase_rule_test"], 2); + // A file holding none is left as it is. + assert!(!rule_tests("template_pool", &mut pool, &mut carried)); + assert!(!rule_tests( + "structure", + &mut json!({"predicate_type": + "repurposed_structures:y_value_pos_rule_test"}), + &mut carried + )); + } } diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 7de9f39ce..a6adc2000 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -42,6 +42,9 @@ const REPURPOSED_CHECKED: [(&str, &str); 3] = [ ), ("repurposed_structures:stronghold_end", "stronghold_end"), ]; +/// Repurposed Structures' mineshaft: its generic jigsaw laid out under the +/// terrain (`"layout": "mineshaft"` in `horizon:piece_limited`). +const REPURPOSED_MINESHAFT: &str = "repurposed_structures:generic_mineshaft"; /// Layout rules the piece-limited assembler keeps (`horizon:piece_limited`). const PIECE_LIMITED_RULES: [&str; 4] = [ "y_allowance", @@ -94,14 +97,17 @@ const START_RULES: [(&str, &str); 3] = [ ]; /// The jigsaws' rules on laying out pieces, which vanilla's jigsaw has no /// place for. -const LAYOUT_RULES: [&str; 6] = [ +const LAYOUT_RULES: [&str; 5] = [ "y_allowance", "burying_type", "use_bounding_box_hack", "pools_that_ignore_boundaries", "enhanced_terrain_adaptation", - "vertical_distance_from_start_piece", ]; +/// 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`. +const DEAD_FIELDS: [&str; 1] = ["vertical_distance_from_start_piece"]; /// Pool elements that are vanilla's with extra fields: (mod type, vanilla type). const ELEMENTS: [(&str, &str); 3] = [ ( @@ -131,6 +137,9 @@ pub struct Upgrade { /// Processors written in Java carried as data the game runs /// ([`crate::processors`]), by type. pub processors_carried: BTreeMap, + /// Rule tests written in Java carried as the game's own + /// ([`crate::processors::rule_tests`]), by type. + pub rule_tests_carried: BTreeMap, /// Entries added to other structure sets and template pools /// (`horizon:add_to`), by the set or pool they join. pub added_to: BTreeMap, @@ -345,10 +354,11 @@ pub fn upgrade( ) -> bool { let states = block_states(v); report.block_states += usize::from(states); + let renamed = crate::carry::renamed_ids(v); let dropped = crate::processors::each_list(kind, v, &mut |list| { drop_java_processors(list, &mut report.processors_dropped) }); - upgrade_types(kind, v, report, set_tags) || states || dropped + upgrade_types(kind, v, report, set_tags) || states || dropped || renamed } /// Takes the processors written in Java (any type outside `minecraft:` and @@ -414,15 +424,19 @@ fn upgrade_types( let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; let changed = match kind { "structure" => match v["type"].as_str() { - Some("yungsapi:yung_jigsaw") => { + // 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) + || t == REPURPOSED_MINESHAFT || REPURPOSED_CHECKED.iter().any(|(r, _)| *r == t) => { + let mineshaft = t == REPURPOSED_MINESHAFT; let check = REPURPOSED_CHECKED.iter().find(|(r, _)| *r == t); let check = check.map(|(_, c)| *c); let library = match t.split_once(':').map(|(ns, _)| ns) { @@ -435,7 +449,10 @@ fn upgrade_types( } else { "lowest" }; - let limited = library.map(|l| piece_limited(v, l)); + let mut limited = library.map(|l| piece_limited(v, l)); + if let Some(limited) = limited.as_mut().filter(|_| mineshaft) { + limited["layout"] = "mineshaft".into(); + } start_checks(v, liquid, lost, limited.is_some()); if let Some(check) = check { if !v["horizon:start_checks"].is_object() { @@ -646,6 +663,9 @@ fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap, checks.insert(to.into(), n.clone()); } } + for field in DEAD_FIELDS { + o.remove(field); + } for rule in LAYOUT_RULES { let kept = limited && PIECE_LIMITED_RULES.contains(&rule); if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) && !kept { @@ -1101,11 +1121,13 @@ mod tests { assert!(moogs.get(gone).is_none(), "{gone}"); } assert_eq!(moogs["size"], 7); - // Repurposed Structures reads the block above the bottom. + // Repurposed Structures reads the block above the bottom. Its jungle + // fortress's vertical distance is a field its code no longer reads. let mut rs = json!({"type": "repurposed_structures:generic_jigsaw_structure", - "cannot_spawn_in_liquid": true}); + "cannot_spawn_in_liquid": true, "vertical_distance_from_start_piece": 35}); assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); assert_eq!(rs["horizon:start_checks"], json!({"liquid": "lowest"})); + assert!(rs.get("vertical_distance_from_start_piece").is_none()); // Repurposed's own checks: the Nether city, Nether shipwrecks, the End stronghold. for (t, check) in [ ("city_nether_structure", "city_nether"), @@ -1182,6 +1204,19 @@ mod tests { 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["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", @@ -1345,6 +1380,17 @@ mod tests { moogs["horizon:piece_limited"], json!({"library": "moogs", "burying": "average_land"}) ); + // Repurposed's mineshaft is laid out under the terrain. + let mut mineshaft = json!({"type": "repurposed_structures:generic_mineshaft", + "start_pool": "rs:mineshafts/birch/start_pool", "size": 9, + "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut mineshaft, &mut report, &NO_TAGS)); + assert_eq!(mineshaft["type"], "minecraft:jigsaw"); + assert_eq!( + mineshaft["horizon:piece_limited"], + json!({"library": "repurposed", "layout": "mineshaft"}) + ); + assert_eq!(mineshaft["liquid_settings"], "ignore_waterlogging"); // Lithostitched's jigsaw is vanilla's: no key. let mut litho = json!({"type": "lithostitched:jigsaw"}); assert!(upgrade("structure", &mut litho, &mut report, &NO_TAGS)); diff --git a/crates/horizon-world/src/block_properties.rs b/crates/horizon-world/src/block_properties.rs index 7c0e17f61..98e06f7cb 100644 --- a/crates/horizon-world/src/block_properties.rs +++ b/crates/horizon-world/src/block_properties.rs @@ -79,15 +79,18 @@ impl BlockProperty { #[derive(Clone, Debug)] pub struct BoundBlockProperty { states: Arc<[u8]>, - property: BlockProperty, + mask: u8, } impl BoundBlockProperty { pub fn contains(&self, id: BlockStateId) -> bool { self.states .get(id.0 as usize) - .is_some_and(|flags| flags & self.property.mask() != 0) + .is_some_and(|flags| flags & self.mask != 0) } } +/// The per-state flag of the block definition's `canOcclude`, past the +/// [`BlockProperty`] bits. +const CAN_OCCLUDE: u8 = 16; /// Immutable FULL face-occlusion results, independent of support/collision. #[derive(Clone, Debug)] @@ -195,7 +198,12 @@ impl<'r> BlockPropertiesRegistry<'r> { .ok_or_else(|| invalid("missing block occlusion shape"))?, ) .map_err(|error| invalid(error.to_string()))?, - ) << 3), + ) << 3) + | if properties.can_occlude { + CAN_OCCLUDE + } else { + 0 + }, ); } Ok(Self { @@ -225,7 +233,14 @@ impl<'r> BlockPropertiesRegistry<'r> { pub fn bind(&self, property: BlockProperty) -> BoundBlockProperty { BoundBlockProperty { states: Arc::clone(&self.states), - property, + mask: property.mask(), + } + } + /// The states whose block definition can occlude (BlockState.canOcclude). + pub fn bind_can_occlude(&self) -> BoundBlockProperty { + BoundBlockProperty { + states: Arc::clone(&self.states), + mask: CAN_OCCLUDE, } } } diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index a901a583d..00f0c64c1 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -23,6 +23,7 @@ pub struct FeatureBlockBindings<'r> { )>, physical_properties: Option<[BoundBlockProperty; 4]>, pub(crate) occlusion_faces: Option, + pub(crate) can_occlude: Option, biomes: Option>, pub(crate) fluids: super::fluid_predicate::FluidPredicateBindings, pub(crate) codec: BlockStateJsonCodec<'r>, @@ -88,6 +89,7 @@ impl<'r> FeatureBlockBindings<'r> { properties.bind(BlockProperty::SolidRender), ]); self.occlusion_faces = Some(properties.bind_occlusion_faces()); + self.can_occlude = Some(properties.bind_can_occlude()); Ok(self) } pub fn with_biomes( @@ -156,6 +158,7 @@ impl<'r> FeatureBlockBindings<'r> { biomes: None, physical_properties: None, occlusion_faces: None, + can_occlude: None, fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?, blocks: blocks .into_iter() diff --git a/crates/horizon-world/src/worldgen/fluid_predicate.rs b/crates/horizon-world/src/worldgen/fluid_predicate.rs index d8bcb10ab..1394445c9 100644 --- a/crates/horizon-world/src/worldgen/fluid_predicate.rs +++ b/crates/horizon-world/src/worldgen/fluid_predicate.rs @@ -45,6 +45,9 @@ impl FluidPredicateBindings { self.tags = resolved; Ok(self) } + pub(crate) fn table(&self) -> &Arc { + &self.table + } pub fn state(&self, block: BlockStateId) -> Option { self.table.get(block) } diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index 3b6d058ae..11765ab57 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -195,11 +195,19 @@ impl StructureState { for (i, def) in registry.structures.iter().enumerate() { by_step[def.step].push(i); } - let bindings = FeatureBlockBindings::with_tags( + let mut bindings = FeatureBlockBindings::with_tags( data.registry(), data.integers().clone(), &data.block_tags, )?; + // Processors that test what a block is made of read canOcclude. + if let Some(blocks) = data + .feature_resources + .as_ref() + .and_then(|r| r.blocks.as_ref()) + { + bindings = bindings.with_block_properties(&blocks.properties)?; + } Ok(Some(Self { registry, resources: resources.clone(), diff --git a/crates/horizon-world/src/worldgen/rule_test.rs b/crates/horizon-world/src/worldgen/rule_test.rs index d9f836961..5202baa31 100644 --- a/crates/horizon-world/src/worldgen/rule_test.rs +++ b/crates/horizon-world/src/worldgen/rule_test.rs @@ -3,7 +3,11 @@ use super::{ DecodeError, Object, block_feature::FeatureBlockBindings, density::identifier, integer, number_text, required, }; -use crate::registry::BlockStateId; +use crate::{ + block_properties::BoundBlockProperty, + fluid::{FluidKind, FluidStateTable}, + registry::BlockStateId, +}; use horizon_core::random::RandomSource; use serde_json::value::RawValue; use std::{collections::BTreeSet, sync::Arc}; @@ -21,6 +25,85 @@ enum Node { RandomStates(Arc>, f32), RandomState(BlockStateId, f32), Height(i32, i32), + Phase(Box), +} +/// `horizon:matter_phase`: Repurposed Structures' MatterPhaseRuleTest, which +/// its mineshafts and Nether monument use to match a block by what it is +/// made of (`phase_to_test_for`), optionally inverted (`invert_condition`). +#[derive(Clone, Debug)] +struct MatterPhase { + phase: Phase, + invert: bool, + air: [BlockStateId; 3], + fluids: Arc, + /// Only for `SOLID`. + can_occlude: Option, + /// Blocks.RAIL and Blocks.CHAIN (26.3's iron chain). + rail_or_chain: BTreeSet, +} +#[derive(Clone, Copy, Debug)] +enum Phase { + Solid, + Liquid, + Air, + AirRailOrChain, + LiquidRailOrChain, +} +impl MatterPhase { + fn decode(object: &Object, bindings: &FeatureBlockBindings<'_>) -> Result { + let name: String = serde_json::from_str(required(object, "phase_to_test_for")?.get())?; + let phase = match name.as_str() { + "SOLID" => Phase::Solid, + "LIQUID" => Phase::Liquid, + "AIR" => Phase::Air, + "AIR_RAIL_OR_CHAIN" => Phase::AirRailOrChain, + "LIQUID_RAIL_OR_CHAIN" => Phase::LiquidRailOrChain, + _ => return Err(DecodeError::Field("matter phase")), + }; + let invert = match object.get("invert_condition") { + Some(v) => serde_json::from_str(v.get())?, + None => false, + }; + let can_occlude = match phase { + Phase::Solid => Some( + bindings + .can_occlude + .clone() + .ok_or(DecodeError::Field("matter phase block properties"))?, + ), + _ => None, + }; + let mut rail_or_chain = BTreeSet::new(); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + rail_or_chain.extend(bindings.blocks.get(name).into_iter().flat_map(|s| s.iter())); + } + Ok(Self { + phase, + invert, + air: bindings.air, + fluids: bindings.fluids.table().clone(), + can_occlude, + rail_or_chain, + }) + } + fn test(&self, state: BlockStateId) -> bool { + let air = self.air.contains(&state); + let liquid = self + .fluids + .get(state) + .is_some_and(|f| f.kind() != FluidKind::Empty); + let rail_or_chain = || self.rail_or_chain.contains(&state); + let matched = match self.phase { + Phase::Solid => { + !air && !liquid && self.can_occlude.as_ref().is_some_and(|c| c.contains(state)) + } + Phase::Liquid => liquid, + Phase::Air => air, + Phase::AirRailOrChain => air || rail_or_chain(), + Phase::LiquidRailOrChain => liquid || rail_or_chain(), + }; + matched != self.invert + } } impl RuleTest { pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result { @@ -104,6 +187,9 @@ impl RuleTest { Node::Any(values) } } + "horizon:matter_phase" => { + Node::Phase(Box::new(MatterPhase::decode(&object, bindings)?)) + } _ => return Err(DecodeError::Field("replacement rule type")), }; Ok(Self(node)) @@ -128,6 +214,7 @@ impl RuleTest { state == *expected && random.next_float() < *probability } Node::Height(min, max) => *min <= position[1] && position[1] <= *max, + Node::Phase(phase) => phase.test(state), } } } diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 1372f247b..753df0258 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -13,7 +13,8 @@ //! "ignore_bounds_pools": ["x:pool"], //! "land_search": "highest_land", // the Nether variants: or "lowest_land", "fixed_height" //! "ledge_offset_y": 2, -//! "pieces": [{"name": "x:piece", "required": 1, "min_depth": 3, "max": 2}] +//! "pieces": [{"name": "x:piece", "required": 1, "min_depth": 3, "max": 2}], +//! "layout": "mineshaft" // Repurposed's mineshafts: moved under the terrain //! } //! ``` //! @@ -25,6 +26,8 @@ //! (`required`, from `min_depth`), the whole layout retried up to 40 times //! until every required piece is in, and after it the pieces centred on the //! chunk corner, then buried in the terrain or moved onto Nether land. +//! Repurposed's overworld mineshafts are not centred: their top goes 15 +//! blocks under the terrain around the chunk. use super::{ BoundingBox, Rotation, StructureResources, StructureTemplate, jigsaw::{ @@ -63,6 +66,15 @@ pub enum Burying { LowestSide, } +/// The structure type's postLayoutAdjustments. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layout { + /// GenericJigsawStructure's: centred, then buried or moved onto land. + Generic, + /// Repurposed Structures' MineshaftStructure. + Mineshaft, +} + #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum LandSearch { Highest, @@ -89,6 +101,7 @@ pub struct Config { ignore_bounds: HashSet, land_search: Option, ledge: i32, + layout: Layout, /// Counted templates by id, in the order of Java's HashMap of the /// required pieces (the first one still short is forced in first). pieces: Vec<(Identifier, Counted)>, @@ -152,6 +165,10 @@ impl Config { _ => None, }, ledge: int("ledge_offset_y").unwrap_or(0), + layout: match v["layout"].as_str() { + Some("mineshaft") => Layout::Mineshaft, + _ => Layout::Generic, + }, pieces: sorted, } } @@ -353,6 +370,10 @@ fn adjust( if pieces.is_empty() { return; } + if limits.layout == Layout::Mineshaft { + below_terrain(limits, context, start, pieces); + return; + } // GeneralUtils.centerAllPieces on the chunk's corner. let center = pieces[0].bounding_box.center(); let d = [start[0] - center[0], 0, start[2] - center[2]]; @@ -435,6 +456,44 @@ fn adjust( shift_all(limits, pieces, [0, dy, 0]); } +/// MineshaftStructure.postLayoutAdjustments: the layout's top moved to 15 +/// blocks under the lowest ocean floor at the chunk's middle and 16 blocks +/// to each side, within y_allowance; never up. +fn below_terrain( + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut [PoolPiece], +) { + let target = mineshaft_top(start, limits.min_y, |x, z| { + context.base_height(x, z, HeightmapType::OceanFloorWg) + }); + let top = pieces + .iter() + .map(|p| p.bounding_box.max[1]) + .max() + .unwrap_or(i32::MIN); + if target < limits.max_y.unwrap_or(i32::MAX) && target < top { + shift_all(limits, pieces, [0, target - top, 0]); + } +} + +/// Where [`below_terrain`] puts a mineshaft's top: `floor` is the first free +/// height over the ocean floor (getFirstFreeHeight, OCEAN_FLOOR_WG). +fn mineshaft_top( + start: [i32; 3], + min_y: Option, + mut floor: impl FnMut(i32, i32) -> i32, +) -> i32 { + let (x, z) = (start[0] + 7, start[2] + 7); + let mut terrain = floor(x, z) - 1; + // Plane.HORIZONTAL's order; the mod takes one more off after each. + for (dx, dz) in [(0, -16), (16, 0), (0, 16), (-16, 0)] { + terrain = terrain.min(floor(x + dx, z + dz)) - 1; + } + (terrain - 15).max(min_y.unwrap_or(i32::MIN)) +} + /// AVERAGE_LAND: the mean land height over a grid on the first piece's /// footprint; no structure when none of the heights is allowed. fn average_land( @@ -918,6 +977,22 @@ mod tests { assert_eq!(limits.library, Library::Repurposed); } + #[test] + fn mineshafts_go_under_the_lowest_floor_around() { + // Floor 80 at the middle (7, 7), 70 north, 90 east, 60 south, 85 west. + let floor = |x, z| match (x, z) { + (7, 7) => 80, + (7, -9) => 70, + (23, 7) => 90, + (7, 23) => 60, + (-9, 7) => 85, + other => panic!("{other:?}"), + }; + // 79, min(79, 70) - 1 = 69, 68, min(68, 60) - 1 = 59, 58; 15 under it. + assert_eq!(mineshaft_top([0, 50, 0], None, floor), 43); + assert_eq!(mineshaft_top([0, 50, 0], Some(48), floor), 48); + } + #[test] fn nether_land_is_found_in_the_column() { // A column from y 0: netherrack to 40, lava 41..=45, air, a ledge 70..=72. diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index 76e1a4cd1..980a90848 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -49,6 +49,22 @@ enum PosRule { max_dist: i32, axis: Option, }, + /// `horizon:piece_origin_axis_aligned_linear_pos`: Repurposed Structures' + /// PieceOriginAxisAlignedLinearPosRuleTest, vanilla's axis-aligned chance + /// over the block's distance from the template's origin along one axis. + PieceOrigin { + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + axis: usize, + }, + /// `horizon:y_value`: Repurposed Structures' YValuePosRuleTest, the + /// block's world height in `min_y_value..=max_y_value`. + YValue { + min: i32, + max: i32, + }, } #[derive(Clone, Debug)] enum Modifier { @@ -56,6 +72,14 @@ enum Modifier { Clear, AppendLoot(String), AppendStatic(Compound), + /// `horizon:edit`: `remove`'s keys taken out of the block entity, then + /// `data` merged in as append_static does. The data form of the mods' + /// processors that copy a block entity and change parts of it (Moog's + /// trial spawners and vaults drop their saved state). + Edit { + remove: Vec, + data: Compound, + }, } impl PosRule { /// A rule's `position_predicate` (always true when missing). Types are @@ -83,9 +107,97 @@ impl PosRule { } }), }, + "horizon:piece_origin_axis_aligned_linear_pos" => { + let int = |key| p.get(key).and_then(Value::as_i64).unwrap_or(0) as i32; + let (min_dist, max_dist) = (int("min_dist"), int("max_dist")); + if min_dist >= max_dist { + return Err(DecodeError::Field("position predicate distance range")); + } + Self::PieceOrigin { + min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + min_dist, + max_dist, + axis: match p.get("axis").map(|a| a.as_str()) { + Some(Some("x")) => 0, + None | Some(Some("y")) => 1, + Some(Some("z")) => 2, + _ => return Err(DecodeError::Field("position predicate axis")), + }, + } + } + "horizon:y_value" => { + let int = |key| { + p.get(key) + .and_then(Value::as_i64) + .map(|v| v as i32) + .ok_or(DecodeError::Field("position predicate y value")) + }; + let (min, max) = (int("min_y_value")?, int("max_y_value")?); + if min > max { + return Err(DecodeError::Field("position predicate y range")); + } + Self::YValue { min, max } + } _ => return Err(DecodeError::Field("position predicate")), }) } + /// PosRuleTest.test for a block at `world`, `relative` in its template, + /// in a piece placed at `reference`. + fn test( + &self, + relative: [i32; 3], + world: [i32; 3], + reference: [i32; 3], + random: &mut impl RandomSource, + ) -> bool { + match *self { + Self::Always => true, + Self::Linear { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = match axis { + None => (0..3).map(|i| (world[i] - reference[i]).abs()).sum::(), + Some(a) => ((world[a] - reference[a]) as f32).abs() as i32, + }; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::PieceOrigin { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = (relative[axis] as f32).abs() as i32; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::YValue { min, max } => (min..=max).contains(&world[1]), + } + } +} +/// Mth.clampedLerp(min_chance, max_chance, Mth.inverseLerp(dist, min_dist, max_dist)). +fn clamped_chance( + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + dist: i32, +) -> f32 { + let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; + if t < 0. { + min_chance + } else if t > 1. { + max_chance + } else { + min_chance + t * (max_chance - min_chance) + } } impl Modifier { /// A rule's `block_entity_modifier` (passthrough when missing). @@ -104,11 +216,45 @@ impl Modifier { Tag::Compound(c) => Self::AppendStatic(c), _ => Self::AppendStatic(Compound::new()), }, + "horizon:edit" => Self::Edit { + remove: m["remove"] + .as_array() + .into_iter() + .flatten() + .map(|k| k.as_str().map(str::to_owned)) + .collect::>() + .ok_or(DecodeError::Field("block entity modifier keys"))?, + data: match json_to_nbt(&m["data"]) { + Tag::Compound(c) => c, + _ => Compound::new(), + }, + }, _ => return Err(DecodeError::Field("block entity modifier")), }, ) } } +/// A block entity with `remove`'s keys taken out and `data` merged in +/// (append_static is the one with nothing to remove). +fn edited(nbt: Option<&Compound>, remove: &[String], data: &Compound) -> Compound { + let mut nbt = nbt.cloned().unwrap_or_default(); + for key in remove { + nbt.remove(&JavaString::from(key.as_str())); + } + merge(&mut nbt, data); + nbt +} +/// CompoundTag.merge: compounds in both are merged, anything else replaced. +fn merge(into: &mut Compound, other: &Compound) { + for (key, value) in other { + match (into.get_mut(key), value) { + (Some(Tag::Compound(mine)), Tag::Compound(theirs)) => merge(mine, theirs), + _ => { + into.insert(key.clone(), value.clone()); + } + } + } +} #[derive(Clone, Debug)] pub struct Rule { input: RuleTest, @@ -140,6 +286,11 @@ pub enum Processor { LavaSubmerged, BlackstoneReplace, SpawnerMobs(Box), + Pick(Box), + CountCap(Box), + /// `horizon:block_swap` (Lithostitched's `block_swap`): blocks by name + /// become others, keeping the properties both have. + BlockSwap(std::collections::BTreeMap), } #[derive(Clone, Debug, Default)] pub struct ProcessorList(pub Vec); @@ -156,6 +307,196 @@ 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:count_cap`, which `horizon-port-pack` writes for Better +/// Dungeons' chest processor (Java in the mod): of the `blocks` one +/// placement meets, the first `min` stay, the rest each stay when +/// `settings.getRandom(pos).nextFloat() <= chance` until `max` have, and the +/// others become `replacement`. The count is the placement's (the mod's +/// DungeonContext, set up per StructureTemplate.placeInWorld: one chunk of +/// the piece), shared by every such processor in it. +#[derive(Clone, Debug)] +pub struct CountCap { + blocks: BTreeSet, + min: u32, + max: u32, + chance: f32, + replacement: BlockStateId, +} +impl CountCap { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result, + ) -> Result { + let count = |key: &'static str| { + value[key] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or(DecodeError::Field(key)) + }; + Ok(Self { + blocks: value["blocks"] + .as_array() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|b| { + let b = b.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(super::super::tags::identifier(b)?.to_string()) + }) + .collect::>()?, + min: count("min")?, + max: count("max")?, + chance: float(value, "chance")?, + replacement: state(&value["replacement"])?, + }) + } + /// Whether a counted block stays, counting it if so. + fn keeps(&self, counted: &mut u32, roll: impl FnOnce() -> f32) -> bool { + let keep = *counted < self.min || (*counted < self.max && roll() <= self.chance); + *counted += u32::from(keep); + keep + } +} + /// `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, @@ -387,6 +728,22 @@ impl Processor { None => Ok(resources.registry.default_state("minecraft:air").unwrap()), })?)) } + "horizon:pick" => Self::Pick(Box::new(Pick::decode(value, state)?)), + "horizon:block_swap" => Self::BlockSwap( + value["blocks"] + .as_object() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|(from, to)| { + let to = to.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(( + super::super::tags::identifier(from)?.to_string(), + super::super::tags::identifier(to)?.to_string(), + )) + }) + .collect::>()?, + ), + "horizon:count_cap" => Self::CountCap(Box::new(CountCap::decode(value, state)?)), _ => return Err(DecodeError::Field("structure processor type")), }) } @@ -440,6 +797,8 @@ pub struct PlaceSettings<'a> { /// StructurePlaceSettings.ignoreEntities / finalizeEntities. pub ignore_entities: bool, pub finalize_entities: bool, + /// The blocks `horizon:count_cap` kept in this placement. + counted: u32, } impl<'a> PlaceSettings<'a> { pub fn new(rotation: Rotation) -> Self { @@ -454,6 +813,7 @@ impl<'a> PlaceSettings<'a> { known_shape: false, ignore_entities: false, finalize_entities: false, + counted: 0, } } pub fn with_processors(mut self, list: &'a ProcessorList) -> Self { @@ -475,6 +835,30 @@ impl<'a> PlaceSettings<'a> { } } +/// Block.withPropertiesOf: `block`'s default state with each property of +/// `from` it has too (by name, when the value is one of its own). None for +/// a block the registry does not know (the mod keeps the block then). +fn with_properties_of( + registry: &crate::registry::BlockRegistry, + block: &str, + from: BlockStateId, +) -> Option { + let default = registry.default_state(block)?; + let mut state = registry.state(default)?.clone(); + for (key, value) in ®istry.state(from)?.properties { + if let Some(own) = state.properties.get(key) + && own != value + { + let mut changed = state.clone(); + changed.properties.insert(key.clone(), value.clone()); + if registry.id(&changed).is_some() { + state = changed; + } + } + } + registry.id(&state) +} + /// BlackstoneReplaceProcessor's block map. fn blackstone(name: &str) -> Option<&'static str> { Some(match name.strip_prefix("minecraft:")? { @@ -589,42 +973,9 @@ fn process_block( if !rule.location.test(located, info.pos, &mut random) { continue; } - let position_ok = match &rule.position { - PosRule::Always => true, - PosRule::Linear { - min_chance, - max_chance, - min_dist, - max_dist, - axis, - } => { - let dist = match axis { - None => (0..3) - .map(|i| (info.pos[i] - reference[i]).abs()) - .sum::(), - Some(a) => { - let d: [f32; 3] = std::array::from_fn(|i| { - if i == *a { - ((info.pos[i] - reference[i]) as f32).abs() - } else { - 0. - } - }); - (d[0] + d[1] + d[2]) as i32 - } - }; - let roll = random.next_float(); - let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; - let chance = if t < 0. { - *min_chance - } else if t > 1. { - *max_chance - } else { - min_chance + t * (max_chance - min_chance) - }; - roll <= chance - } - }; + let position_ok = rule + .position + .test(relative, info.pos, reference, &mut random); if !position_ok { continue; } @@ -637,10 +988,9 @@ fn process_block( nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); Some(nbt) } - Modifier::AppendStatic(data) => { - let mut nbt = info.nbt.clone().unwrap_or_default(); - nbt.extend(data.clone()); - Some(nbt) + Modifier::AppendStatic(data) => Some(edited(info.nbt.as_ref(), &[], data)), + Modifier::Edit { remove, data } => { + Some(edited(info.nbt.as_ref(), remove, data)) } }; return Ok(Some(BlockInfo { @@ -652,6 +1002,36 @@ fn process_block( Some(info) } Processor::Capped { .. } => Some(info), + Processor::BlockSwap(blocks) => { + let swapped = blocks + .get(name(info.state)) + .and_then(|to| with_properties_of(registry, to, info.state)); + Some(match swapped { + Some(state) => BlockInfo { state, ..info }, + None => info, + }) + } + Processor::CountCap(cap) => match cap.blocks.contains(name(info.state)) { + true => { + let pos = info.pos; + let mut counted = settings.counted; + let keep = cap.keeps(&mut counted, || settings.with_random(pos, |r| r.float())); + settings.counted = counted; + Some(match keep { + true => info, + false => BlockInfo { + pos, + state: cap.replacement, + nbt: None, + }, + }) + } + false => 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)); @@ -769,6 +1149,7 @@ fn process_infos( reference: [i32; 3], settings: &mut PlaceSettings<'_>, ) -> Result, PlacementQueryError> { + settings.counted = 0; let whole = settings .processors .iter() @@ -1250,6 +1631,42 @@ mod tests { assert!(SpawnerMobs::decode(&bad, |_| Ok(BlockStateId(0))).is_err()); } + #[test] + fn repurposed_position_rules() { + let decode = |v: Value| PosRule::decode(Some(&v)); + // Over 3..4 blocks from the template's origin along y, 0 to 1. + let rule = decode( + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "axis": "y", "min_chance": 0, "max_chance": 1, "min_dist": 3, "max_dist": 4}), + ) + .unwrap(); + let mut random = LegacyRandom::new(1); + let world = [100, 64, -100]; + // At or under min_dist the chance is 0, a roll of 0 aside; past max_dist it is 1. + assert!(!rule.test([9, 2, 9], world, world, &mut random)); + assert!(rule.test([0, -5, 0], world, world, &mut random)); + // The world position and the piece's do not count. + assert!(rule.test([0, 4, 0], [0, 0, 0], [50, 50, 50], &mut random)); + // Repurposed refuses an empty distance range and an unknown axis. + for bad in [ + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos"}), + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "min_dist": 0, "max_dist": 1, "axis": "w"}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5, "max_y_value": 4}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5}), + ] { + assert!(decode(bad.clone()).is_err(), "{bad}"); + } + let y = decode( + json!({"predicate_type": "horizon:y_value", "min_y_value": 0, "max_y_value": 31}), + ) + .unwrap(); + assert!(y.test([0; 3], [7, 31, 7], [0; 3], &mut random)); + assert!(y.test([0, 99, 0], [7, 0, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, 32, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, -1, 7], [0; 3], &mut random)); + } + #[test] fn rule_parts_read_ids_without_a_namespace() { // CTOV writes "always_true"; vanilla reads it as minecraft:always_true. @@ -1282,4 +1699,206 @@ mod tests { )); assert!(Modifier::decode(Some(&json!({"type": ""}))).is_err()); } + + #[test] + fn block_entity_edits_merge_deep_and_drop_keys() { + let nbt = |v: Value| match json_to_nbt(&v) { + Tag::Compound(c) => c, + _ => unreachable!(), + }; + let vault = nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:old", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})); + // append_static merges compounds the way CompoundTag.merge does. + let Ok(Modifier::AppendStatic(data)) = Modifier::decode(Some(&json!({ + "type": "append_static", "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("append_static") + }; + let merged = edited(Some(&vault), &[], &data); + assert_eq!( + merged, + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})) + ); + let Ok(Modifier::Edit { remove, data }) = Modifier::decode(Some(&json!({ + "type": "horizon:edit", "remove": ["server_data"], + "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("horizon:edit") + }; + assert_eq!( + edited(Some(&vault), &remove, &data), + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}})) + ); + assert_eq!( + edited(None, &remove, &data), + nbt(json!({"config": {"loot_table": "x:new"}})) + ); + 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()); + } + + #[test] + fn count_caps_keep_the_first_then_some() { + let cap = CountCap::decode( + &json!({"blocks": ["chest", "minecraft:trapped_chest"], "min": 1, "max": 2, + "chance": 0.2, "replacement": {"id": "minecraft:cave_air"}}), + |_| Ok(BlockStateId(5)), + ) + .unwrap(); + assert!(cap.blocks.contains("minecraft:chest")); + let mut counted = 0; + // The first stays without a roll. + assert!(cap.keeps(&mut counted, || unreachable!())); + // Then each stays on nextFloat <= 0.2, until two have. + assert!(!cap.keeps(&mut counted, || 0.21)); + assert!(cap.keeps(&mut counted, || 0.2)); + assert!(!cap.keeps(&mut counted, || unreachable!())); + assert_eq!(counted, 2); + assert!( + CountCap::decode(&json!({"blocks": [], "min": -1}), |_| Ok(BlockStateId(5))).is_err() + ); + } + + #[test] + fn block_swaps_keep_the_properties_both_blocks_have() { + let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]); + let facts = json!({"defaults": {"a:log": 1, "a:stairs": 4, "a:stone": 6}, + "states": [ + row("a:log", json!({"axis": "x"})), row("a:log", json!({"axis": "y"})), + row("a:stairs", json!({"facing": "east", "half": "top"})), + row("a:stairs", json!({"facing": "east", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "top"})), + ["a:stone", false, false, "", "a:stone"]]}); + let registry = + crate::registry::BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap(); + // facing and half carried over; the default where `from` has none. + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(2)), + Some(BlockStateId(2)) + ); + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(0)), + Some(BlockStateId(4)) + ); + assert_eq!( + with_properties_of(®istry, "a:stone", BlockStateId(5)), + Some(BlockStateId(6)) + ); + assert_eq!( + with_properties_of(®istry, "a:missing", BlockStateId(0)), + None + ); + } } diff --git a/crates/horizon-world/tests/rule_test_bounds.rs b/crates/horizon-world/tests/rule_test_bounds.rs index de4862f54..e3f614590 100644 --- a/crates/horizon-world/tests/rule_test_bounds.rs +++ b/crates/horizon-world/tests/rule_test_bounds.rs @@ -67,3 +67,80 @@ fn binding_rejects_unknown_tag_blocks_and_duplicate_canonical_tags() { ]); assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err()); } +#[test] +fn matter_phase_matches_what_a_block_is_made_of() { + // air, cave_air, void_air, stone, then water (level 0), rail, iron_chain. + let mut states: Vec = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + ] + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(); + states.push(Tag::compound([ + ("id", Tag::String("minecraft:water".into())), + ( + "properties", + Tag::compound([("level", Tag::String("0".into()))]), + ), + ])); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + states.push(Tag::compound([("id", Tag::String(name.into()))])); + } + let names = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + "minecraft:rail", + "minecraft:iron_chain", + ]; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states)), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap(); + let bindings = FeatureBlockBindings::new(®istry, BTreeSet::new()).unwrap(); + let mut random = horizon_core::random::LegacyRandom::new(0); + let matches = |phase: &str, invert: bool, random: &mut horizon_core::random::LegacyRandom| { + let json = format!( + r#"{{"predicate_type":"horizon:matter_phase","phase_to_test_for":"{phase}","invert_condition":{invert}}}"# + ); + let test = RuleTest::from_json(&json, &bindings).unwrap(); + (0..names.len() as u32) + .filter(|&id| test.test(horizon_world::registry::BlockStateId(id), [0; 3], random)) + .collect::>() + }; + assert_eq!(matches("AIR", false, &mut random), [0, 1, 2]); + assert_eq!(matches("LIQUID", false, &mut random), [4]); + assert_eq!( + matches("AIR_RAIL_OR_CHAIN", false, &mut random), + [0, 1, 2, 5, 6] + ); + assert_eq!( + matches("LIQUID_RAIL_OR_CHAIN", false, &mut random), + [4, 5, 6] + ); + assert_eq!(matches("AIR", true, &mut random), [3, 4, 5, 6]); + // The phase is the enum's name as written; SOLID needs canOcclude. + for json in [ + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"air"}"#, + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"SOLID"}"#, + r#"{"predicate_type":"horizon:matter_phase"}"#, + ] { + assert!(RuleTest::from_json(json, &bindings).is_err(), "{json}"); + } +} diff --git a/docs/modpacks.md b/docs/modpacks.md index 12e522e24..48e2a28e8 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -447,14 +447,42 @@ Two cases the oracle fills in: written in). YUNG's Better Dungeons and Better Desert Temples turn a spawner or a placeholder block (gravel, bone block, yellow wool...) into a spawner of a fixed mob: that is vanilla's `rule` processor with an `append_static` block entity. Moog's vanilla loot - swap acts only when a "replace vanilla" preset is on, and they ship off. 119 of the 1,427 - processors are carried; 1,308 are still taken out (blocks swapped, aged or propped up, - Moog's trial spawner and vault configs, YUNG's chest caps). + swap acts only when a "replace vanilla" preset is on, and they ship off. Moog's trial + spawner and vault processors keep the block and change its block entity: one `rule` per + block state, with the game's `horizon:edit` modifier, which takes out the state the + 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. 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. Better Dungeons' small dungeons keep one chest and each other one with a fifth's + chance, two at most (the game's `horizon:count_cap`, counted per placement as the mod's + DungeonContext is): 12 chests in five small dungeons at seed 1234 become 6. + Lithostitched's `block_swap` (137 lists, all in ChoiceTheorem's Overhauled Village) is the + game's `horizon:block_swap`: the same map, with Block.withPropertiesOf's properties kept; + a target block the game does not have (most of them are Nature's Spirit's and Croptopia's) + leaves the block as it is, as the mod does. 273 of the 1,427 processors are carried; 1,154 + are still taken out (Formations' biome replacements, Repurposed's pillars and fluid fixes, + Lithostitched's reference, condition and apply_random, blocks aged or propped up). 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 in Moog's Nether Structures are filled (162, up from 110). Chests are unchanged: 2,777 and 1,405 with a loot table. + - **Rule tests** written in Java. Repurposed Structures' mineshafts and Nether monument test + blocks with three of the mod's own rule tests inside vanilla `rule` processors: what a + block is made of (solid, liquid, air, with rails and chains), a chance over the distance + from the template's origin along one axis, and a world height range. The game runs them + as `horizon:matter_phase`, `horizon:piece_origin_axis_aligned_linear_pos` and + `horizon:y_value` with the mod's fields, and carry renames them (213 in 75 lists). + - **Renamed ids.** 26.3 calls 1.21.1's chain the iron chain (its datafixers rename it in + worlds). Carry renames it in recipes, loot tables and worldgen files (112 files in 5 mods: + Repurposed's mineshafts, Better Dungeons' processors, Regions Unexplored's hanging sign + recipes...), which otherwise fail to load in 26.3. With both, the 5 Nether mineshaft pools load: 47 of + Repurposed's Nether mineshafts in the 128×128-chunk square (seed 1234), under the lava sea. - **Big templates** (#838). Vanilla reads structure templates with no limit on their tag count; Horizon now does too (`nbt::Limits::templates`). Seven of ATM10's 8,962 carried templates are past the old 1,000,000-tag cap: YUNG's monument start, four When Dungeons