From 5515cbab33d2fd3d64558ec269d10649a55f5d2f Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:34:01 -0400 Subject: [PATCH 1/3] Handle resource pack reload failures and reset menu atlas cache --- crates/horizon-client/src/game.rs | 32 +++++-- crates/horizon-client/src/game/options.rs | 1 + crates/horizon-client/src/game/packs.rs | 26 +++-- crates/horizon-client/src/options_ui.rs | 112 +++++++++++++++++++++- crates/horizon-client/src/packs.rs | 16 ++-- crates/horizon-client/src/packs/cache.rs | 49 ++++++---- crates/horizon-client/src/ui_theme.rs | 37 +++++++ 7 files changed, 233 insertions(+), 40 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0454a0d69..728049172 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -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) -> Result { - let assets = &self.pack.assets; + self.renderer_for(window, &self.pack, &self.atlas) + } + fn renderer_for( + &self, + window: Arc, + pack: &PackResources, + atlas: &HudAtlas, + ) -> Result { + 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. diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index dcc7bb23b..da1017e8e 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -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) { diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 4a80bee48..8e068e59b 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -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 { 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); diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 38be29576..86d1fca43 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -824,6 +824,8 @@ pub struct OptionsUi { pub pack_selection: Vec, /// The open pack screen, made at its first frame. pub pack_screen: Option, + /// A reload failure, dismissed before returning to the current page. + pub resource_error: Option, /// 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 { + 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 { 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(); diff --git a/crates/horizon-client/src/packs.rs b/crates/horizon-client/src/packs.rs index 917bad561..4c3972291 100644 --- a/crates/horizon-client/src/packs.rs +++ b/crates/horizon-client/src/packs.rs @@ -369,7 +369,8 @@ fn pack_files(pack: &Pack) -> io::Result> { } #[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 { .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 { 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. diff --git a/crates/horizon-client/src/packs/cache.rs b/crates/horizon-client/src/packs/cache.rs index 1f17c018b..efcf01e4a 100644 --- a/crates/horizon-client/src/packs/cache.rs +++ b/crates/horizon-client/src/packs/cache.rs @@ -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; diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 1c41add9d..1d57e5ada 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -267,6 +267,10 @@ struct Cache { thread_local! { static CACHE: RefCell> = 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(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(); + } +} From e0d6e562810d882afd87c8800df63d8c28dcc9e0 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:41:33 -0400 Subject: [PATCH 2/3] Release Wayland surface before replacing the pack renderer --- crates/horizon-client/src/game/packs.rs | 21 +++++++++++++++++++-- crates/horizon-client/src/gfx.rs | 20 +++++++++++++++++--- 2 files changed, 36 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index 8e068e59b..0b95dd2ad 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -130,11 +130,28 @@ impl Game<'_> { self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; - let renderer = self + // Keep the working GPU resources, but release its exclusive window surface. + if let Some(renderer) = &mut self.renderer { + renderer.release_surface(); + } + let renderer = match self .window .clone() .map(|window| self.renderer_for(window, &pack, &atlas)) - .transpose()?; + .transpose() + { + Ok(renderer) => renderer, + Err(error) => { + if let Some(renderer) = &mut self.renderer { + renderer.recreate_surface().map_err(|restore| { + format!( + "{error}; could not restore the previous rendering surface: {restore}" + ) + })?; + } + return Err(error); + } + }; // Everything loaded: switch over. self.random_tick_sections.clear(); self.options.resources = root.to_path_buf(); diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index f64200e5c..9fcc8ae39 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1656,6 +1656,22 @@ impl Renderer { pub fn is_offscreen(&self) -> bool { self.surface.is_none() } + /// Release the window surface before another renderer uses the same window. + pub fn release_surface(&mut self) { + self.surface = None; + } + /// Reattach a window after surface loss or a failed renderer replacement. + pub fn recreate_surface(&mut self) -> Result<()> { + if self.offscreen.is_some() { + return Ok(()); + } + // Wayland allows only one tearing-control object per window surface. + self.release_surface(); + let surface = self.instance.create_surface(self.window.clone())?; + surface.configure(&self.device, &self.config); + self.surface = Some(surface); + Ok(()) + } fn depth(device: &wgpu::Device, config: &wgpu::SurfaceConfiguration) -> wgpu::TextureView { device .create_texture(&wgpu::TextureDescriptor { @@ -2039,9 +2055,7 @@ impl Renderer { return Ok(false); } Some(wgpu::CurrentSurfaceTexture::Lost) => { - let surface = self.instance.create_surface(self.window.clone())?; - surface.configure(&self.device, &self.config); - self.surface = Some(surface); + self.recreate_surface()?; return Ok(false); } Some(wgpu::CurrentSurfaceTexture::Validation) => { From 7575719d11257cd7b72e64b4e35f13d992f52927 Mon Sep 17 00:00:00 2001 From: Cosmic <84875247+Online5277@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:46:47 -0400 Subject: [PATCH 3/3] Reuse the GPU device and presentation mode across pack reloads --- crates/horizon-client/src/game.rs | 1 + crates/horizon-client/src/gfx.rs | 69 ++++++++++++++++++++----------- 2 files changed, 46 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 728049172..a579f44ff 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -7671,6 +7671,7 @@ impl Game<'_> { (&atlas.pixels, atlas.width, atlas.height), (&pack.forcefield.2, pack.forcefield.0), &pack.panorama, + self.renderer.as_ref(), ))?; renderer.hud.fire_animations = atlas .fire_animations diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 9fcc8ae39..6c8a5272f 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -222,6 +222,7 @@ struct BorderUniform { } pub struct Renderer { instance: wgpu::Instance, + adapter: wgpu::Adapter, /// The window's swapchain; `None` when rendering offscreen (`--offscreen`). surface: Option>, /// The offscreen colour target, sized like `config`. @@ -454,8 +455,14 @@ impl Renderer { hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), panorama_faces: &panorama::Faces, + previous: Option<&Self>, ) -> Result { - let instance = wgpu::Instance::new(instance_descriptor()); + // Reload resources on the same device; replacing live Vulkan devices + // can invalidate the driver's swapchain state on the same window. + let instance = previous.map_or_else( + || wgpu::Instance::new(instance_descriptor()), + |renderer| renderer.instance.clone(), + ); // Offscreen rendering needs no surface, so it can use a GPU the // window's display cannot present from (a headless compositor). let surface = if offscreen { @@ -463,15 +470,18 @@ impl Renderer { } else { Some(instance.create_surface(window.clone())?) }; - let adapter = instance - .request_adapter(&wgpu::RequestAdapterOptions { - power_preference: wgpu::PowerPreference::HighPerformance, - compatible_surface: surface.as_ref(), - force_fallback_adapter: false, - ..Default::default() - }) - .await - .map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?; + let adapter = match previous { + Some(renderer) => renderer.adapter.clone(), + None => instance + .request_adapter(&wgpu::RequestAdapterOptions { + power_preference: wgpu::PowerPreference::HighPerformance, + compatible_surface: surface.as_ref(), + force_fallback_adapter: false, + ..Default::default() + }) + .await + .map_err(|e| format!("{NO_GPU_DRIVER} ({e})"))?, + }; let info = adapter.get_info(); log::info!( "Horizon renderer: {} ({:?}, {:?})", @@ -501,15 +511,20 @@ impl Renderer { ) .into()); } - let (device, queue) = adapter - .request_device(&wgpu::DeviceDescriptor { - label: Some("Horizon device"), - required_features: timing::GpuTimer::features(&adapter) - | (adapter.features() & wgpu::Features::INDIRECT_FIRST_INSTANCE), - required_limits: limits.clone(), - ..Default::default() - }) - .await?; + let (device, queue) = match previous { + Some(renderer) => (renderer.device.clone(), renderer.queue.clone()), + None => { + adapter + .request_device(&wgpu::DeviceDescriptor { + label: Some("Horizon device"), + required_features: timing::GpuTimer::features(&adapter) + | (adapter.features() & wgpu::Features::INDIRECT_FIRST_INSTANCE), + required_limits: limits.clone(), + ..Default::default() + }) + .await? + } + }; let size = window.inner_size(); let (config, present_modes) = if let Some(surface) = &surface { let mut config = surface @@ -528,11 +543,16 @@ impl Renderer { if caps.usages.contains(wgpu::TextureUsages::COPY_SRC) { config.usage |= wgpu::TextureUsages::COPY_SRC; } - config.present_mode = if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) { - wgpu::PresentMode::Mailbox - } else { - wgpu::PresentMode::Fifo - }; + config.present_mode = previous + .map(|renderer| renderer.config.present_mode) + .filter(|mode| caps.present_modes.contains(mode)) + .unwrap_or_else(|| { + if caps.present_modes.contains(&wgpu::PresentMode::Mailbox) { + wgpu::PresentMode::Mailbox + } else { + wgpu::PresentMode::Fifo + } + }); surface.configure(&device, &config); (config, caps.present_modes.clone()) } else { @@ -1523,6 +1543,7 @@ impl Renderer { ); Ok(Self { instance, + adapter, surface, offscreen, in_flight: std::collections::VecDeque::new(),