Content mods: keep the built content root for later starts

resource_root built the content root again on every start. With ATM10's 40
carried data-tier mods that is about 25 s on a quiet machine (50 s on a busy
one) and the biggest memory peak of the start, above 3 GB of footprint. The
root now records a stamp of what it was built from (this build of the game,
the base's manifest and rewritten tables, every mod file by size and time) and
later starts with the same stamp use it as it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-17 21:51:33 +02:00
parent ce38c8d74f
commit 24fd51b186
3 changed files with 102 additions and 0 deletions
+60
View File
@@ -943,15 +943,75 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> {
/// The root to load: `base` itself with no content, else the mods' overlay
/// over it, built in `cache/mod-content`.
///
/// The root is built once and kept: later starts with the same build, base
/// and mod files reuse it. With ATM10's carried mods a build takes about
/// 25 s and peaks above 3 GB, more than everything the game keeps.
pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result<PathBuf> {
if mods.iter().all(|m| m.content.is_empty()) {
return Ok(base.to_owned());
}
let out = cache.join("mod-content");
let stamp = stamp(base, mods)?;
if fs::read(out.join(STAMP)).is_ok_and(|s| s == stamp.as_bytes()) {
return Ok(out);
}
build(base, mods, &out)?;
fs::write(out.join(STAMP), stamp)?;
Ok(out)
}
/// In a root built by [`resource_root`]: what it was built from.
const STAMP: &str = "horizon-mod-content.stamp";
/// What a content root is built from: this build of the game, the base's
/// manifest and the tables [`build`] rewrites, and every file of every mod
/// in order. Files count by size and modification time, as build tools do.
fn stamp(base: &Path, mods: &[ContentMod]) -> Result<String> {
use sha2::{Digest, Sha256};
let meta = |path: &Path| -> Result<String> {
let m = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
let modified = m
.modified()?
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
Ok(format!(
"{} {} {}",
path.display(),
m.len(),
modified.as_nanos()
))
};
let mut parts = vec!["horizon mod content 1".to_owned()];
parts.push(meta(&std::env::current_exe()?)?);
let base = std::path::absolute(base)?;
parts.push(
String::from_utf8_lossy(&fs::read(base.join("horizon-resources.json"))?).into_owned(),
);
for name in JSON_TABLES.iter().chain(&NBT_TABLES).chain(&TAG_BUNDLES) {
if base.join(name).exists() {
parts.push(meta(&base.join(name))?);
}
}
for m in mods {
parts.push(m.id.clone());
let source = m.content.source();
if source.is_dir() {
for file in &m.content.files {
parts.push(meta(&source.join(file))?);
}
} else {
parts.push(meta(source)?);
}
}
let mut hasher = Sha256::new();
for part in &parts {
hasher.update((part.len() as u64).to_le_bytes());
hasher.update(part.as_bytes());
}
Ok(format!("{:x}", hasher.finalize()))
}
#[cfg(test)]
#[path = "mod_content_tests.rs"]
mod tests;
@@ -502,3 +502,38 @@ fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() {
);
fs::remove_dir_all(&scratch).unwrap();
}
/// A built root is kept for later starts, and built again when a mod's
/// files change.
#[test]
fn content_root_is_reused_until_a_mod_changes() {
let Some(base) = prepared() else {
return;
};
let scratch = std::env::temp_dir().join(format!("horizon-mod-reuse-{}", std::process::id()));
let _ = fs::remove_dir_all(&scratch);
let m = ruby_mod(&scratch.join("ruby"));
let cache = scratch.join("cache");
let root = resource_root(&base, std::slice::from_ref(&m), &cache).unwrap();
// A rebuild starts from an empty folder: this file tells them apart.
let sentinel = root.join("sentinel");
fs::write(&sentinel, b"").unwrap();
assert_eq!(
resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(),
root
);
assert!(sentinel.exists(), "an unchanged mod rebuilt the root");
let lang = scratch.join("ruby/assets/ruby/lang/en_us.json");
fs::write(&lang, r#"{"block.ruby.ruby_block": "Ruby Block"}"#).unwrap();
let file = fs::File::options().write(true).open(&lang).unwrap();
file.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(5))
.unwrap();
resource_root(&base, std::slice::from_ref(&m), &cache).unwrap();
assert!(!sentinel.exists(), "a changed mod kept the old root");
assert!(
fs::read_to_string(root.join("assets/ruby/lang/en_us.json"))
.unwrap()
.contains("Ruby Block")
);
let _ = fs::remove_dir_all(&scratch);
}
+7
View File
@@ -192,6 +192,13 @@ impl Content {
Ok(content)
}
/// Where the files are read from: the mod's folder or its `.hmod`.
pub fn source(&self) -> &Path {
match &self.source {
Source::Dir(path) | Source::Zip(path) => path,
}
}
/// No files: a mod with code only.
pub fn is_empty(&self) -> bool {
self.files.is_empty()