Merge pull request #630 from ludovic111/feat/mod-content-real-mods

Content mods: load real carried-over mods (large tables, convention tags, mod recipes)
This commit is contained in:
Ludovic Marie
2026-10-17 04:57:55 +02:00
committed by GitHub
12 changed files with 168 additions and 43 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ use std::{fs, io, path::Path, sync::Arc};
pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result<BlockCollisionRegistry<'r>> {
let data = nbt::read_named(
&fs::read(root.join("cached-collision.nbt"))?,
Limits::default(),
Limits::tables(),
)?
.0
.tag;
+14 -6
View File
@@ -274,16 +274,20 @@ pub(crate) fn load_tags(root: &Path, kind: &str) -> Result<HashMap<String, HashS
}
/// Every tag's contents in `TagLoader.tryBuildTag` order (a `LinkedHashSet`).
pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result<HashMap<String, Vec<String>>> {
let dir = root.join(format!("data/minecraft/tags/{kind}"));
let mut raw: HashMap<String, Vec<String>> = HashMap::new();
fn walk(dir: &Path, base: &Path, raw: &mut HashMap<String, Vec<String>>) -> Result<()> {
fn walk(
dir: &Path,
base: &Path,
namespace: &str,
raw: &mut HashMap<String, Vec<String>>,
) -> Result<()> {
for entry in fs::read_dir(dir)?.flatten() {
let p = entry.path();
if p.is_dir() {
walk(&p, base, raw)?;
walk(&p, base, namespace, raw)?;
} else if p.extension().is_some_and(|e| e == "json") {
let name = format!(
"minecraft:{}",
"{namespace}:{}",
p.strip_prefix(base)?
.with_extension("")
.to_string_lossy()
@@ -301,8 +305,12 @@ pub(crate) fn load_tag_lists(root: &Path, kind: &str) -> Result<HashMap<String,
}
Ok(())
}
if dir.exists() {
walk(&dir, &dir, &mut raw)?;
// Vanilla's tags; with content mods also the convention (`c`) tags and the mods' own.
for namespace in crate::mod_content::tag_namespaces(root) {
let dir = root.join(format!("data/{namespace}/tags/{kind}"));
if dir.exists() {
walk(&dir, &dir, &namespace, &mut raw)?;
}
}
fn resolve(name: &str, raw: &HashMap<String, Vec<String>>, out: &mut Vec<String>, depth: u32) {
if depth > 32 {
+1 -1
View File
@@ -71,7 +71,7 @@ impl LightTables {
};
let data = nbt::read_named(
&std::fs::read(root.join("occlusion.nbt"))?,
Limits::default(),
Limits::tables(),
)?
.0
.tag;
+81 -2
View File
@@ -638,6 +638,19 @@ pub fn namespaces(root: &Path) -> Vec<String> {
.unwrap_or_default()
}
/// The namespaces whose tags loaders read in `root`: `minecraft`, and in a
/// root built by [`build`] the convention tags (`c`, shared between mods as
/// on NeoForge and Fabric) and the content mods' own.
pub fn tag_namespaces(root: &Path) -> Vec<String> {
let mods = namespaces(root);
let mut out = vec!["minecraft".to_owned()];
if !mods.is_empty() {
out.push("c".to_owned());
out.extend(mods);
}
out
}
/// Bundles of block tag files (tag id → the tag file's text).
const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"];
@@ -735,8 +748,67 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result<String> {
Ok(serde_json::to_string_pretty(&doc)?)
}
/// The block and item ids and tags a content root has, for tag entries.
struct Known {
blocks: std::collections::BTreeSet<String>,
items: std::collections::BTreeSet<String>,
/// `data/<ns>/tags/<kind>/<path>.json` files the mods add.
tag_files: std::collections::BTreeSet<String>,
}
impl Known {
fn new(base: &Path, plan: &Plan, tags: &BTreeMap<String, Vec<J>>) -> Result<Self> {
let mut blocks: std::collections::BTreeSet<String> =
plan.defaults.keys().cloned().collect();
blocks.extend(plan.blocks.iter().map(|b| b.decl.id.clone()));
let mut items = std::collections::BTreeSet::new();
if let J::Obj(o) = read_json(&base.join("items.json"))? {
items.extend(o.into_iter().map(|(k, _)| k));
}
items.extend(plan.items.iter().map(|i| i.rename.to.clone()));
Ok(Known {
blocks,
items,
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).
fn keeps(&self, file: &str, v: &J) -> bool {
let id = match v {
J::Str(s) => s.as_str(),
J::Obj(_) => match v.get("id") {
Some(J::Str(s)) => s.as_str(),
_ => return true,
},
_ => return true,
};
let Some(kind) = file
.strip_prefix("data/")
.and_then(|r| r.split_once("/tags/"))
.and_then(|(_, rest)| Some(rest.split_once('/')?.0))
else {
return true;
};
let ids = match kind {
"block" => &self.blocks,
"item" => &self.items,
_ => 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"
}
None => ids.contains(id),
}
}
}
/// Builds the content root for `mods` over `base` in `out`.
pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
// The overlay links to the base: a relative base would leave them dangling.
let base = &std::path::absolute(base)?;
let plan = Plan::new(base, mods)?;
let overlay = Overlay::new(base, out)?;
for name in JSON_TABLES {
@@ -754,11 +826,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
if !path.exists() {
continue;
}
let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::default())
let (mut named, _) = nbt::read_named(&fs::read(&path)?, Limits::tables())
.map_err(|e| format!("{name}: {e}"))?;
plan.nbt(&mut named.tag);
let bytes =
nbt::write_named(&named, Limits::default()).map_err(|e| format!("{name}: {e}"))?;
nbt::write_named(&named, Limits::tables()).map_err(|e| format!("{name}: {e}"))?;
overlay.write(name, &bytes)?;
}
// Mod files, and every tag addition gathered per tag file.
@@ -788,6 +860,13 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
}
}
}
// A tag naming an id nobody registers fails as a whole in vanilla, and
// carried-over mods name blocks left out or other mods' ids: such
// entries are dropped instead, so the rest of the tag holds.
let known = Known::new(base, &plan, &tags)?;
for (file, values) in &mut tags {
values.retain(|v| known.keeps(file, v));
}
let mut bundles: Vec<(&str, J)> = Vec::new();
for name in TAG_BUNDLES {
if base.join(name).exists() {
+18 -4
View File
@@ -56,7 +56,7 @@ fn prepared() -> Option<PathBuf> {
/// A content mod folder: a full block, a door and an item-less glass from
/// templates, an item, a vanilla tag addition and a language file.
fn ruby_mod(dir: &Path) -> ContentMod {
let files: [(&str, &str); 7] = [
let files: [(&str, &str); 8] = [
(
"horizon-mod.toml",
"id = \"ruby\"\nname = \"Ruby\"\nversion = \"0.1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n",
@@ -78,9 +78,15 @@ fn ruby_mod(dir: &Path) -> ContentMod {
"data/ruby/horizon/item/ruby.json",
r#"{"template": "minecraft:diamond", "max_stack_size": 16, "rarity": "rare"}"#,
),
// Carried-over tags name blocks left out and other mods' ids too.
(
"data/minecraft/tags/block/mineable/pickaxe.json",
r#"{"values": ["ruby:ruby_block"]}"#,
r##"{"values": ["ruby:ruby_block", "ruby:left_out", "othermod:thing",
{"id": "othermod:optional", "required": false}, "#c:storage_blocks/ruby"]}"##,
),
(
"data/c/tags/item/gems/ruby.json",
r#"{"values": ["ruby:ruby", "othermod:ruby"]}"#,
),
(
"assets/ruby/lang/en_us.json",
@@ -110,7 +116,10 @@ fn content_root_loads_with_every_table() {
let scratch = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
let m = ruby_mod(&scratch.join("ruby"));
let root = resource_root(&base, std::slice::from_ref(&m), &scratch.join("cache")).unwrap();
// The base as a relative path (cargo runs tests in the crate's folder):
// the overlay's links still resolve.
let relative = Path::new("../../.local/horizon-client/26.3");
let root = resource_root(relative, std::slice::from_ref(&m), &scratch.join("cache")).unwrap();
assert_ne!(root, base);
let vanilla = Assets::load(&base).unwrap();
@@ -169,7 +178,12 @@ fn content_root_loads_with_every_table() {
let gem = &items.items["ruby:ruby"];
assert_eq!(gem.max_stack, 16);
assert!(!items.items.contains_key("ruby:ruby_glass"));
assert!(items.block_tags["minecraft:mineable/pickaxe"].contains("ruby:ruby_block"));
let pickaxe = &items.block_tags["minecraft:mineable/pickaxe"];
assert!(pickaxe.contains("ruby:ruby_block"));
assert!(!pickaxe.contains("ruby:left_out") && !pickaxe.contains("othermod:thing"));
assert!(pickaxe.contains("minecraft:stone"));
// Convention tags load, with the ids nobody registers dropped.
assert_eq!(items.item_tag_order["c:gems/ruby"], ["ruby:ruby"]);
crate::collisions::load(&root, new).unwrap();
crate::models::load_visibility(&root, new).unwrap();
+1 -1
View File
@@ -120,7 +120,7 @@ pub fn load_visibility(
nbt::{self, Limits},
};
use std::{collections::BTreeMap, fs};
let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::default())?
let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())?
.0
.tag;
let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?;
+1 -1
View File
@@ -63,7 +63,7 @@ impl MotionResources {
)?)?)?);
let data = nbt::read_named(
&fs::read(root.join("movement-properties.nbt"))?,
Limits::default(),
Limits::tables(),
)?
.0
.tag;
+17 -10
View File
@@ -481,23 +481,30 @@ fn ingredient(v: &Value, items: &Items) -> Ingredient {
}
impl StationRecipes {
pub fn load(root: &Path, items: &Items) -> Self {
let mut files: Vec<_> = fs::read_dir(root.join("data/minecraft/recipe"))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
files.sort();
// Vanilla's recipes, then the content mods' (docs/modpacks.md).
let mut files = Vec::new();
let namespaces =
std::iter::once("minecraft".to_owned()).chain(crate::mod_content::namespaces(root));
for namespace in namespaces {
let mut more: Vec<_> = fs::read_dir(root.join(format!("data/{namespace}/recipe")))
.into_iter()
.flatten()
.flatten()
.map(|e| e.path())
.filter(|p| p.extension().is_some_and(|e| e == "json"))
.collect();
more.sort();
files.extend(more.into_iter().map(|p| (namespace.clone(), p)));
}
let mut smithing = Vec::new();
let mut stonecutting = Vec::new();
for p in files {
for (namespace, p) in files {
let Ok(bytes) = fs::read(&p) else { continue };
let Ok(v) = serde_json::from_slice::<Value>(&bytes) else {
continue;
};
let id = format!(
"minecraft:{}",
"{namespace}:{}",
p.file_stem().and_then(|s| s.to_str()).unwrap_or("")
);
match v["type"].as_str().unwrap_or("") {
+10 -6
View File
@@ -4,7 +4,7 @@
//!
//! Content is data, not code: nothing here runs in the sandbox. What a mod
//! may add is fenced instead. Its own namespace, plus additions to vanilla
//! tags. Paths are plain, files and totals are capped, and vanilla ids
//! tags and to the convention tags (`c`, which NeoForge and Fabric mods share). Paths are plain, files and totals are capped, and vanilla ids
//! cannot be redefined.
use crate::manifest::{Capability, MANIFEST, Manifest};
use serde::Deserialize;
@@ -242,12 +242,13 @@ impl Content {
parts.next().unwrap_or(""),
);
let own = namespace == id;
// Vanilla's own files stay vanilla's; a mod may only add to its tags.
let allowed =
own || (top == "data" && namespace == "minecraft" && rest.starts_with("tags/"));
// Vanilla's own files stay vanilla's; a mod may only add to its
// tags, and to the convention tags mods share.
let shared = matches!(namespace, "minecraft" | "c");
let allowed = own || (top == "data" && shared && rest.starts_with("tags/"));
if !allowed {
return Err(format!(
"{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla tags"
"{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla and convention (c) tags"
));
}
let Some(decl) = (own && top == "data")
@@ -417,10 +418,11 @@ capabilities = ["registries"]
("data/ruby/horizon/item/ruby.json", ITEM),
("data/ruby/recipe/ruby_block.json", b"{}"),
("data/minecraft/tags/block/mineable/pickaxe.json", b"{}"),
("data/c/tags/item/gems/ruby.json", b"{}"),
("assets/ruby/textures/block/ruby_block.png", b"png"),
];
let content = hmod("ok", MANIFEST_TEXT, files).unwrap();
assert_eq!(content.files.len(), 5);
assert_eq!(content.files.len(), 6);
assert_eq!(
content.blocks,
[Block {
@@ -471,6 +473,8 @@ capabilities = ["registries"]
"vanilla-recipe",
&[("data/minecraft/recipe/stone.json", b"{}")],
);
refused("convention-recipe", &[("data/c/recipe/stone.json", b"{}")]);
refused("convention-asset", &[("assets/c/lang/en_us.json", b"{}")]);
let e = refused(
"modded-template",
&[(
+12
View File
@@ -97,6 +97,18 @@ impl Default for Limits {
}
}
}
impl Limits {
/// The prepared per-state block tables (`cached-collision.nbt`,
/// `block-properties.nbt`, ...): trusted files with a row per block
/// state, which content mods' states grow past the default caps.
pub fn tables() -> Self {
Self {
max_bytes: 1 << 28,
max_nodes: 16_000_000,
max_depth: 512,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Error {
@@ -103,14 +103,12 @@ impl BlockBehavior {
return Ok(None);
}
let read = |name: &str| -> Result<Tag, GeneratorError> {
let limits = Limits {
max_bytes: 1 << 28,
..Limits::default()
};
Ok(nbt::read_named(&fs::read(dir.join(name))?, limits)
.map_err(|e| resource(format!("{name}: {e:?}")))?
.0
.tag)
Ok(
nbt::read_named(&fs::read(dir.join(name))?, Limits::tables())
.map_err(|e| resource(format!("{name}: {e:?}")))?
.0
.tag,
)
};
let json = |name: &str| -> Result<Value, GeneratorError> {
Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?)
+6 -3
View File
@@ -277,12 +277,15 @@ blocks and items by declaring them in `data/<id>/horizon/block/*.json` and
```
The fence: files go in the mod's own namespace (`assets/<id>/`,
`data/<id>/`), plus additions to vanilla tags (`data/minecraft/tags/`).
`data/<id>/`), plus additions to vanilla tags (`data/minecraft/tags/`) and
to the convention tags NeoForge and Fabric mods share (`data/c/tags/`).
Templates and `sounds` name vanilla blocks; unknown keys are refused. Paths
use vanilla's resource characters, at most 65,536 files, 16 MiB each and
512 MiB in all. A mod whose content is refused stays off, with the reason on
its row. The game reading this content into its block and item tables comes
next (docs/modpacks.md).
its row. The game reads this content into its block and item tables
(`horizon_client::mod_content`, docs/modpacks.md). A tag entry naming an id
nobody registers (a block a port left out, another mod's item) is dropped,
so the rest of the tag still loads; vanilla would drop the whole tag.
## Versions and compatibility