Merge remote-tracking branch 'pr/764' into integ/mp-sh

This commit is contained in:
Ludovic Marie
2026-10-18 06:34:06 +02:00
2 changed files with 177 additions and 4 deletions
+96 -4
View File
@@ -674,6 +674,28 @@ pub fn tag_namespaces(root: &Path) -> Vec<String> {
/// Bundles of block tag files (tag id → the tag file's text).
const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"];
/// The worldgen loader's bundle of biome tags.
const BIOME_TAGS: &str = "worldgen/biome_tags.json";
/// Worldgen registries a content mod may add to, and the bundle the
/// worldgen loader reads each from (id → the file's text): what structure
/// mods hold. Biomes, noise and density functions change the terrain and
/// are not read from mods.
const WORLDGEN_BUNDLES: [(&str, &str); 6] = [
("structure", "worldgen/structures.json"),
("structure_set", "worldgen/structure_sets.json"),
("template_pool", "worldgen/template_pools.json"),
("processor_list", "worldgen/processor_lists.json"),
("configured_feature", "worldgen/features.json"),
("placed_feature", "worldgen/placed_features.json"),
];
/// A mod file that adds to a worldgen bundle: (bundle, id).
fn worldgen_entry(file: &str) -> Option<(&'static str, String)> {
let (ns, rest) = file.strip_prefix("data/")?.split_once("/worldgen/")?;
let (kind, path) = rest.split_once('/')?;
let (_, bundle) = WORLDGEN_BUNDLES.iter().find(|(k, _)| *k == kind)?;
Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?)))
}
/// The overlay being written: `out` mirrors `base` through links, and a
/// directory becomes real only when something inside it is written.
@@ -773,6 +795,9 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result<String> {
struct Known {
blocks: std::collections::BTreeSet<String>,
items: std::collections::BTreeSet<String>,
/// The worldgen loader's biomes and biome tags.
biomes: std::collections::BTreeSet<String>,
biome_tags: std::collections::BTreeSet<String>,
/// `data/<ns>/tags/<kind>/<path>.json` files the mods add.
tag_files: std::collections::BTreeSet<String>,
}
@@ -786,14 +811,27 @@ impl Known {
items.extend(o.into_iter().map(|(k, _)| k));
}
items.extend(plan.items.iter().map(|i| i.rename.to.clone()));
let keys = |name: &str| -> Result<std::collections::BTreeSet<String>> {
Ok(match base.join(name).exists() {
true => match read_json(&base.join(name))? {
J::Obj(o) => o.into_iter().map(|(k, _)| k).collect(),
_ => Default::default(),
},
false => Default::default(),
})
};
Ok(Known {
blocks,
items,
biomes: keys("worldgen/biomes.json")?,
biome_tags: keys(BIOME_TAGS)?,
tag_files: tags.keys().cloned().collect(),
})
}
/// Whether tag `file` keeps entry `v`: a known id or an existing tag,
/// for block and item tags (other registries are kept as they are).
/// for block, item and biome tags (other registries are kept as they
/// are). The worldgen loader refuses a biome tag naming what it lacks
/// (another mod's biomes, a loader's tags), so those entries go.
fn keeps(&self, file: &str, v: &J) -> bool {
let id = match v {
J::Str(s) => s.as_str(),
@@ -803,23 +841,32 @@ impl Known {
},
_ => return true,
};
let Some(kind) = file
let Some(rest) = file
.strip_prefix("data/")
.and_then(|r| r.split_once("/tags/"))
.and_then(|(_, rest)| Some(rest.split_once('/')?.0))
.map(|(_, rest)| rest)
else {
return true;
};
let kind = match rest.strip_prefix("worldgen/biome/") {
Some(_) => "worldgen/biome",
None => rest.split_once('/').map_or("", |(k, _)| k),
};
let ids = match kind {
"block" => &self.blocks,
"item" => &self.items,
"worldgen/biome" => &self.biomes,
_ => return true,
};
match id.strip_prefix('#') {
Some(tag) => {
let (tns, path) = tag.split_once(':').unwrap_or(("minecraft", tag));
let rel = format!("data/{tns}/tags/{kind}/{path}.json");
self.tag_files.contains(&rel) || tns == "minecraft"
self.tag_files.contains(&rel)
|| match kind {
"worldgen/biome" => self.biome_tags.contains(&format!("{tns}:{path}")),
_ => tns == "minecraft",
}
}
None => ids.contains(id),
}
@@ -856,6 +903,7 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
}
// Mod files, and every tag addition gathered per tag file.
let mut tags: BTreeMap<String, Vec<J>> = BTreeMap::new();
let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new();
for m in mods {
let declarations = format!("data/{}/horizon/", m.id);
for file in &m.content.files {
@@ -878,6 +926,18 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
.extend(values.iter().cloned());
} else if !file.starts_with(&declarations) {
overlay.write(file, &bytes)?;
if let Some((bundle, id)) = worldgen_entry(file) {
let text = String::from_utf8(bytes).map_err(|e| format!("{file}: {e}"))?;
worldgen.entry(bundle).or_default().push((id, text));
} else if let Some(template) = file
.strip_prefix("data/")
.and_then(|r| r.split_once("/structure/"))
.filter(|(_, path)| path.ends_with(".nbt"))
{
// The worldgen loader's templates: worldgen/structure/<ns>/<path>.nbt.
let (ns, path) = template;
overlay.write(&format!("worldgen/structure/{ns}/{path}"), &bytes)?;
}
}
}
}
@@ -921,6 +981,38 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
for (name, doc) in &bundles {
overlay.write(name, &serde_json::to_vec(doc)?)?;
}
// Biome tags, merged into the worldgen loader's bundle as block tags are.
let biome_tags: Vec<(String, &Vec<J>)> = tags
.iter()
.filter_map(|(file, values)| {
let (ns, path) = file
.strip_prefix("data/")?
.split_once("/tags/worldgen/biome/")?;
Some((format!("{ns}:{}", path.strip_suffix(".json")?), values))
})
.collect();
if !biome_tags.is_empty() && base.join(BIOME_TAGS).exists() {
let mut doc = read_json(&base.join(BIOME_TAGS))?;
for (id, values) in biome_tags {
let text = match doc.get(&id) {
Some(J::Str(t)) => Some(t.clone()),
_ => None,
};
doc.set(&id, J::Str(merge_tag(text.as_deref(), values, BIOME_TAGS)?));
}
overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?;
}
// Structures and the pools, sets, processors and features they use.
for (bundle, entries) in &worldgen {
if !base.join(bundle).exists() {
continue;
}
let mut doc = read_json(&base.join(bundle))?;
for (id, text) in entries {
doc.set(id, J::Str(text.clone()));
}
overlay.write(bundle, &serde_json::to_vec(&doc)?)?;
}
// A block without its own blockstate looks like its template, so every
// state still has a model.
for m in mods {
@@ -537,3 +537,84 @@ fn content_root_is_reused_until_a_mod_changes() {
);
let _ = fs::remove_dir_all(&scratch);
}
/// A structure mod's worldgen reaches the worldgen loader: its structure,
/// set, pool and templates join the bundles, and its biome tag keeps only
/// what the loader knows.
#[test]
fn content_root_carries_a_structure_mod() {
let Some(base) = prepared() else {
return;
};
let scratch = std::env::temp_dir().join(format!("horizon-mod-worldgen-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
let dir = scratch.join("huts");
let files = [
(
"horizon-mod.toml",
"id = \"huts\"\nname = \"Huts\"\nversion = \"1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n",
),
(
"data/huts/worldgen/structure/hut.json",
r##"{"type": "minecraft:jigsaw", "biomes": "#huts:has_hut", "step": "surface_structures",
"spawn_overrides": {}, "terrain_adaptation": "beard_thin", "start_pool": "huts:hut/start",
"size": 1, "start_height": {"absolute": 0}, "project_start_to_heightmap": "WORLD_SURFACE_WG",
"max_distance_from_center": 80}"##,
),
(
"data/huts/worldgen/template_pool/hut/start.json",
r#"{"fallback": "minecraft:empty", "elements": [{"weight": 1, "element": {
"element_type": "minecraft:single_pool_element", "location": "huts:hut",
"projection": "rigid", "processors": "minecraft:empty"}}]}"#,
),
(
"data/huts/worldgen/structure_set/huts.json",
r#"{"structures": [{"structure": "huts:hut", "weight": 1}],
"placement": {"type": "minecraft:random_spread", "salt": 7, "spacing": 4, "separation": 2}}"#,
),
(
"data/huts/tags/worldgen/biome/has_hut.json",
r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##,
),
];
for (name, text) in files {
let path = dir.join(name);
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
// The template: vanilla's smallest plains house, as the mod's own file.
let house =
base.join("worldgen/structure/minecraft/village/plains/houses/plains_small_house_1.nbt");
fs::create_dir_all(dir.join("data/huts/structure")).unwrap();
fs::copy(&house, dir.join("data/huts/structure/hut.nbt")).unwrap();
let package = horizon_mods::Package::read(&dir).unwrap();
let m = ContentMod {
id: "huts".into(),
content: Content::read(&dir, &package.manifest).unwrap(),
};
let root = resource_root(&base, &[m], &scratch.join("cache")).unwrap();
assert!(root.join("worldgen/structure/huts/hut.nbt").exists());
let tags: BTreeMap<String, String> =
serde_json::from_slice(&fs::read(root.join("worldgen/biome_tags.json")).unwrap()).unwrap();
let hut: serde_json::Value = serde_json::from_str(&tags["huts:has_hut"]).unwrap();
assert_eq!(
hut["values"],
serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"])
);
let assets = Assets::load(&root).unwrap();
let biomes = crate::biome::Biomes::load(&root).unwrap();
let terrain = crate::vanillagen::VanillaTerrain::new(
&root.join("worldgen"),
assets.registry,
&biomes,
1234,
)
.unwrap();
let (name, at) = terrain
.locate(&["huts:hut".to_owned()], [0, 64, 0], 16)
.expect("the mod's structure generates");
assert_eq!(name, "huts:hut");
assert!(at[0].abs() < 1024 && at[2].abs() < 1024, "{at:?}");
let _ = fs::remove_dir_all(&scratch);
}