Handle resource pack reload failures and reset menu atlas cache

This commit is contained in:
Cosmic
2026-10-16 22:34:01 -04:00
parent 8ff9247edb
commit 5515cbab33
7 changed files with 233 additions and 40 deletions
+25 -7
View File
@@ -7650,7 +7650,15 @@ impl Game<'_> {
/// The renderer for the window, with the current block sprites, shared
/// atlas and world border texture.
fn new_renderer(&self, window: Arc<Window>) -> Result<Renderer> {
let assets = &self.pack.assets;
self.renderer_for(window, &self.pack, &self.atlas)
}
fn renderer_for(
&self,
window: Arc<Window>,
pack: &PackResources,
atlas: &HudAtlas,
) -> Result<Renderer> {
let assets = &pack.assets;
let mut renderer = pollster::block_on(Renderer::new(
window,
self.options.offscreen,
@@ -7660,12 +7668,11 @@ impl Game<'_> {
assets.texture_layers,
&assets.sprite_mips,
&assets.animations,
(&self.atlas.pixels, self.atlas.width, self.atlas.height),
(&self.pack.forcefield.2, self.pack.forcefield.0),
&self.pack.panorama,
(&atlas.pixels, atlas.width, atlas.height),
(&pack.forcefield.2, pack.forcefield.0),
&pack.panorama,
))?;
renderer.hud.fire_animations = self
.atlas
renderer.hud.fire_animations = atlas
.fire_animations
.iter()
.map(|(rect, animation)| (*rect, animation.clone(), usize::MAX))
@@ -10136,7 +10143,13 @@ pub fn run() -> Result<()> {
horizon_client::spans::enable(options.spikes.is_some());
let vanilla_root = options.resources.clone();
let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt"));
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs);
let mut pack_error = None;
options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs)
.unwrap_or_else(|e| {
log::warn!("Horizon: resource packs not applied: {e}");
pack_error = Some(e.to_string());
vanilla_root.clone()
});
options.resources = mods::content_root(
&options.resources,
&early_settings.mods.enabled,
@@ -10148,6 +10161,7 @@ pub fn run() -> Result<()> {
// with the game's own resources.
Err(e) if options.resources != vanilla_root => {
log::warn!("Horizon: resource packs failed to load ({e}); using the default resources");
pack_error = Some(e.to_string());
options.resources = vanilla_root.clone();
Assets::load(&vanilla_root)?
}
@@ -10254,6 +10268,10 @@ pub fn run() -> Result<()> {
}
let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?;
game.ui.vanilla_root = vanilla_root;
if let Some(error) = pack_error {
game.open_options_at(true, horizon_client::options_ui::Page::Packs);
game.ui.options.resource_error = Some(error);
}
if game.options.benchmark.is_some() {
// The same conditions on every machine: no VSync, no frame cap, no
// pause or idle limit without focus. In memory only, never saved.
@@ -206,6 +206,7 @@ impl Game<'_> {
self.apply_settings();
self.sync_mods();
}
Event::Close if self.ui.options.resource_error.is_some() => {}
Event::Close => {
self.settings.save(&Self::options_path());
self.screen = if std::mem::take(&mut self.options_to_world_options) {
+20 -6
View File
@@ -35,7 +35,7 @@ pub fn open_folder(dir: &Path) {
}
}
/// The resource root to load from, given the vanilla root and the selection.
pub fn startup_root(vanilla: &Path, selected: &[String]) -> PathBuf {
pub fn startup_root(vanilla: &Path, selected: &[String]) -> std::io::Result<PathBuf> {
let all = packs::discover(vanilla, &packs_dir());
let enabled = packs::enabled(&all, selected);
packs::resource_root(vanilla, &enabled, &cache_dir())
@@ -104,9 +104,18 @@ impl Game<'_> {
if self.ui.vanilla_root.as_os_str().is_empty() {
self.ui.vanilla_root = vanilla.clone();
}
let root = startup_root(&vanilla, &self.settings.resource_packs);
if let Err(e) = self.reload_resources(&root) {
let result = startup_root(&vanilla, &self.settings.resource_packs)
.map_err(Into::into)
.and_then(|root| self.reload_resources(&root));
if let Err(e) = result {
log::warn!("Horizon: resource reload failed: {e}");
if self.screen != super::Screen::Options {
self.open_options_at(
self.title.is_some(),
horizon_client::options_ui::Page::Packs,
);
}
self.ui.options.resource_error = Some(e.to_string());
}
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
@@ -121,12 +130,18 @@ impl Game<'_> {
self.pack.context.biomes.clone(),
self.pack.context.light.clone(),
)?;
let renderer = self
.window
.clone()
.map(|window| self.renderer_for(window, &pack, &atlas))
.transpose()?;
// Everything loaded: switch over.
self.random_tick_sections.clear();
self.options.resources = root.to_path_buf();
let context = pack.context.clone();
self.pack = pack;
self.atlas = atlas;
horizon_client::ui_theme::reset_atlas();
// Villager hats come from the pack's texture metadata (shared data, swapped in place).
*self
.res
@@ -142,9 +157,8 @@ impl Game<'_> {
self.pending_uploads.clear();
// New GPU textures: a renderer built from the reloaded resources; the
// sections are uploaded again as they are meshed.
if let Some(window) = self.window.clone() {
self.renderer = None;
self.renderer = Some(self.new_renderer(window)?);
if let Some(renderer) = renderer {
self.renderer = Some(renderer);
self.apply_ui_settings();
}
self.ui.chat.rescale(&self.atlas);
+111 -1
View File
@@ -824,6 +824,8 @@ pub struct OptionsUi {
pub pack_selection: Vec<String>,
/// The open pack screen, made at its first frame.
pub pack_screen: Option<crate::pack_screen::PackScreen>,
/// A reload failure, dismissed before returning to the current page.
pub resource_error: Option<String>,
/// When the pack screen's search box took the focus (its cursor blink).
pack_focus: Instant,
pub in_world: bool,
@@ -854,6 +856,7 @@ impl Default for OptionsUi {
pack_infos: Vec::new(),
pack_selection: Vec::new(),
pack_screen: None,
resource_error: None,
pack_focus: Instant::now(),
in_world: false,
center_language: false,
@@ -1596,6 +1599,42 @@ impl OptionsUi {
cursor: (f32, f32),
) {
let (w, h) = (batch.width, batch.height);
if let Some(error) = &self.resource_error {
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.in_world);
let title = tr("resourcePack.load_fail");
batch.text_styled(
atlas,
&title,
((w - atlas.font.width_text(&title)) / 2.0).floor(),
30.0,
u32::MAX,
true,
);
let lines = atlas.font.split(&Text::literal(error), (w - 50.0).max(1.0));
let limit = ((h - 110.0) / 9.0).max(1.0) as usize;
for (i, line) in lines.iter().take(limit).enumerate() {
batch.text_styled(
atlas,
line,
((w - atlas.font.width_text(line)) / 2.0).floor(),
60.0 + i as f32 * 9.0,
u32::MAX,
true,
);
}
ui::button(
batch,
atlas,
w / 2.0 - 100.0,
h - 28.0,
200.0,
20.0,
&tr("gui.done"),
true,
ui::hovered(cursor, w / 2.0 - 100.0, h - 28.0, 200.0, 20.0),
);
return;
}
if crate::ui_theme::horizon() && self.page() == Page::Main {
self.draw_horizon(s, batch, atlas, cursor);
return;
@@ -1784,6 +1823,16 @@ impl OptionsUi {
drag: bool,
right: bool,
) -> Vec<Event> {
if self.resource_error.is_some() {
if !drag
&& !right
&& ui::hovered((x, y), size.0 / 2.0 - 100.0, size.1 - 28.0, 200.0, 20.0)
{
self.resource_error = None;
return vec![Event::ButtonClick];
}
return Vec::new();
}
if crate::ui_theme::horizon() && self.page() == Page::Main {
return self.click_horizon(s, atlas, x, y, framebuffer, drag, right);
}
@@ -2012,6 +2061,9 @@ impl OptionsUi {
}
/// The mouse wheel at the cursor.
pub fn scroll_at(&mut self, s: &Settings, size: (f32, f32), cursor: (f32, f32), amount: f32) {
if self.resource_error.is_some() {
return;
}
if crate::ui_theme::horizon() && self.page() == Page::Main {
self.scroll_horizon(amount);
return;
@@ -2090,6 +2142,9 @@ impl OptionsUi {
}
/// Typed text (the language search box).
pub fn type_text(&mut self, atlas: &HudAtlas, text: &str) {
if self.resource_error.is_some() {
return;
}
if self.page() == Page::Packs
&& let Some(p) = &mut self.pack_screen
{
@@ -2109,7 +2164,7 @@ impl OptionsUi {
shortcut: crate::clipboard::EditShortcut,
clipboard: &mut dyn crate::clipboard::Clipboard,
) -> bool {
if self.selected_key.is_some() {
if self.resource_error.is_some() || self.selected_key.is_some() {
return false;
}
if self.page() == Page::Packs
@@ -2136,6 +2191,12 @@ impl OptionsUi {
text: Option<&str>,
) -> Vec<Event> {
use winit::keyboard::KeyCode as K;
if self.resource_error.is_some() {
if matches!(key, K::Escape | K::Enter | K::NumpadEnter) {
self.resource_error = None;
}
return Vec::new();
}
if self.page() == Page::Packs
&& let Some(p) = &mut self.pack_screen
{
@@ -2201,6 +2262,55 @@ mod tests {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
#[test]
fn resource_reload_error_blocks_options_until_dismissed() {
use winit::keyboard::KeyCode;
let atlas = atlas();
let mut settings = Settings::default();
let mut ui = OptionsUi {
resource_error: Some("broken pack".into()),
..Default::default()
};
let stack = ui.stack.clone();
assert!(
ui.click(
&mut settings,
&atlas,
10.0,
10.0,
(480.0, 270.0),
[960, 540],
false,
false
)
.is_empty()
);
assert!(ui.resource_error.is_some());
assert!(
ui.key(&mut settings, &atlas, KeyCode::KeyW, None)
.is_empty()
);
assert!(ui.resource_error.is_some());
ui.key(&mut settings, &atlas, KeyCode::Escape, None);
assert!(ui.resource_error.is_none());
assert_eq!(ui.stack, stack);
ui.resource_error = Some("broken pack".into());
assert_eq!(
ui.click(
&mut settings,
&atlas,
240.0,
250.0,
(480.0, 270.0),
[960, 540],
false,
false
),
vec![Event::ButtonClick]
);
assert!(ui.resource_error.is_none());
}
#[test]
fn option_tooltip_keys_follow_value_dependent_descriptions() {
let mut s = Settings::default();
+6 -10
View File
@@ -369,7 +369,8 @@ fn pack_files(pack: &Pack) -> io::Result<BTreeMap<String, Provided>> {
}
#[cfg(unix)]
fn link(target: &Path, at: &Path) -> io::Result<()> {
std::os::unix::fs::symlink(target, at)
// Relative sources are relative to the process, not the overlay directory.
std::os::unix::fs::symlink(std::path::absolute(target)?, at)
}
#[cfg(not(unix))]
fn link(target: &Path, at: &Path) -> io::Result<()> {
@@ -635,9 +636,9 @@ pub fn enabled(all: &[Pack], ids: &[String]) -> Vec<Pack> {
.collect()
}
/// Resource root for a pack selection: vanilla itself when no pack is on.
pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf {
pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> io::Result<PathBuf> {
if packs.is_empty() {
return vanilla.to_path_buf();
return Ok(vanilla.to_path_buf());
}
let key: String = packs
.iter()
@@ -648,13 +649,8 @@ pub fn resource_root(vanilla: &Path, packs: &[Pack], cache: &Path) -> PathBuf {
(h ^ u64::from(b)).wrapping_mul(0x100_0000_01b3)
});
let out = cache.join(format!("{hash:016x}"));
match build_overlay(vanilla, packs, &out) {
Ok(()) => out,
Err(e) => {
log::warn!("Horizon: resource packs not applied: {e}");
vanilla.to_path_buf()
}
}
build_overlay(vanilla, packs, &out)?;
Ok(out)
}
/// `Pack.Position`: where a pack goes when it is added to a list.
+33 -16
View File
@@ -8,7 +8,7 @@ use std::io::Read;
use std::{collections::BTreeSet, fs, io, path::Path, path::PathBuf};
// Bump when overlay/merge semantics change. Markers are disposable cache data.
const VERSION: u32 = 2;
const VERSION: u32 = 3;
#[derive(Default, Serialize, Deserialize)]
pub(super) struct Dependencies {
@@ -275,7 +275,6 @@ pub(super) fn build(vanilla: &Path, packs: &[Pack], out: &Path) -> io::Result<()
.truncate(false)
.open(lock_path(out))?;
lock.lock()?;
// Resolve marker identity only; preserve the builder's original link targets.
let vanilla_key = absolute(vanilla)?;
let marker_path = marker_path(out);
let signature = pack_signature(packs);
@@ -484,7 +483,9 @@ mod tests {
// a cache tree changed outside the builder.
packs::build_overlay(&f.0.join("vanilla"), std::slice::from_ref(&low), &out).unwrap();
assert_eq!(fs::read(out.join(resource)).unwrap(), b"corrupt");
fs::remove_file(&marker).unwrap();
let mut old: Marker = serde_json::from_slice(&fs::read(&marker).unwrap()).unwrap();
old.version = VERSION - 1;
fs::write(&marker, serde_json::to_vec(&old).unwrap()).unwrap();
f.rebuild_matches(std::slice::from_ref(&low));
fs::remove_file(out.join(resource)).unwrap();
fs::remove_file(&marker).unwrap();
@@ -564,8 +565,14 @@ mod tests {
f.write("pack.zip", &archive(&files(b"ddd"), true));
f.rebuild_matches(std::slice::from_ref(&pack));
fs::remove_file(f.0.join("pack.zip")).unwrap();
assert!(packs::build_overlay(&f.0.join("vanilla"), &[pack], &out).is_err());
assert!(
packs::build_overlay(&f.0.join("vanilla"), std::slice::from_ref(&pack), &out).is_err()
);
assert!(!marker_path(&out).exists());
assert!(
packs::resource_root(&f.0.join("vanilla"), &[pack], &f.0.join("selection-cache"))
.is_err()
);
}
#[cfg(unix)]
@@ -758,7 +765,7 @@ mod tests {
#[cfg(unix)]
#[test]
fn relative_builder_targets_are_preserved() {
fn relative_sources_are_readable_through_cached_and_uncached_overlays() {
let f = Fixture::new();
f.write("vanilla/facts.json", b"[]");
let mut pack = f.dir_pack("pack");
@@ -777,15 +784,21 @@ mod tests {
let out = f.0.join("cached");
let reference = f.0.join("reference");
packs::build_overlay(&vanilla, std::slice::from_ref(&pack), &out).unwrap();
build_overlay_uncached(&vanilla, &[pack], &reference, &mut Dependencies::default())
.unwrap();
let expected = relative.join("pack").join(name);
assert_eq!(fs::read_link(out.join(name)).unwrap(), expected);
assert_eq!(fs::read_link(reference.join(name)).unwrap(), expected);
assert_eq!(
fs::read_link(out.join("facts.json")).unwrap(),
vanilla.join("facts.json")
);
build_overlay_uncached(
&vanilla,
std::slice::from_ref(&pack),
&reference,
&mut Dependencies::default(),
)
.unwrap();
for root in [&out, &reference] {
assert!(fs::read_link(root.join(name)).unwrap().is_absolute());
assert_eq!(fs::read(root.join(name)).unwrap(), b"pack");
assert_eq!(fs::read(root.join("facts.json")).unwrap(), b"[]");
}
packs::build_overlay(&vanilla, &[pack], &out).unwrap();
assert_eq!(fs::read(out.join(name)).unwrap(), b"pack");
assert_eq!(fs::read(out.join("facts.json")).unwrap(), b"[]");
}
#[test]
@@ -827,14 +840,17 @@ mod tests {
let cached_cache = f.0.join("cached");
fs::create_dir_all(&reference_cache).unwrap();
let reference = original(&vanilla, selected, &reference_cache);
let out = packs::resource_root(&vanilla, selected, &cached_cache);
let out = packs::resource_root(&vanilla, selected, &cached_cache).unwrap();
assert_ne!(out, vanilla, "resource_root must not fall back to vanilla");
assert!(marker_path(&out).exists());
let expected = output_signature(&reference).unwrap();
assert_eq!(output_signature(&out).unwrap(), expected);
for _ in 0..2 {
original(&vanilla, selected, &reference_cache);
assert_eq!(packs::resource_root(&vanilla, selected, &cached_cache), out);
assert_eq!(
packs::resource_root(&vanilla, selected, &cached_cache).unwrap(),
out
);
}
let mut baseline = Vec::new();
let mut cold = Vec::new();
@@ -861,6 +877,7 @@ mod tests {
black_box(selected),
black_box(&cached_cache),
)
.unwrap()
};
black_box(&result);
let ms = started.elapsed().as_secs_f64() * 1000.0;
+37
View File
@@ -267,6 +267,10 @@ struct Cache {
thread_local! {
static CACHE: RefCell<Option<Cache>> = const { RefCell::new(None) };
}
/// Reloaded atlases can occupy the same address with empty run-time slots.
pub fn reset_atlas() {
CACHE.with(|cache| *cache.borrow_mut() = None);
}
fn with_cache<R>(atlas: &HudAtlas, f: impl FnOnce(&mut Cache) -> R) -> R {
CACHE.with(|c| {
let mut c = c.borrow_mut();
@@ -1366,3 +1370,36 @@ pub const fn id(name: &str, index: u64) -> u64 {
}
h ^ index.wrapping_mul(0x9e37_79b9_7f4a_7c15)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn atlas_reload_regenerates_text_and_corners_at_the_same_address() {
let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap();
reset_atlas();
let draw = |cache: &mut Cache| {
let glyph = cache.fonts.face(Face::Regular).glyph_id('A');
assert!(
cache
.glyph(&atlas, Face::Regular, glyph, 16.0)
.rect
.is_some()
);
assert!(cache.corner(&atlas, 8, false).is_some());
std::mem::take(&mut cache.pending)
};
let before = with_cache(&atlas, draw);
assert_eq!(before.len(), 2);
assert!(with_cache(&atlas, draw).is_empty());
reset_atlas();
let after = with_cache(&atlas, draw);
assert_eq!(after.len(), 2);
for (a, b) in before.iter().zip(&after) {
assert_eq!((a.x, a.y, a.width, a.height), (b.x, b.y, b.width, b.height));
assert_eq!(a.rgba, b.rgba);
}
reset_atlas();
}
}