From b3e400a52673862fa237ef4341ba21d4440d3c52 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:25:37 +0100 Subject: [PATCH 1/3] Renderer: sprite arrays OpenGL can view as arrays wgpu's GL backend picks a texture's target from its layer count when it creates it: one layer makes a 2D texture and a multiple of six on a square texture a cube map, and neither can be bound as terrain.wgsl's texture_2d_array. On GL, the 1-layer stand-in for unused sprite arrays gets two layers and a sprite array of 1 or 6n layers one empty layer more. Other backends are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index b55022510..a02e6eb7f 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -516,6 +516,18 @@ fn sprite_split() -> u32 { } /// Sprite arrays terrain.wgsl binds (`sprites`, `sprites_1`...). const SPRITE_ARRAYS: u32 = 8; +/// The layers to give a square texture of `count` layers viewed as a 2D +/// array. wgpu's OpenGL backend picks a texture's target from its layer +/// count when it is created: one layer makes a 2D texture and a multiple of +/// six a cube map, neither of which can be viewed as an array. +fn array_layers(count: u32, gl: bool) -> u32 { + match count { + _ if !gl => count, + 0 | 1 => 2, + n if n % 6 == 0 => n + 1, + n => n, + } +} /// The views of terrain.wgsl's sprite arrays, the unused ones a 1-layer /// stand-in. fn sprite_views( @@ -1312,13 +1324,17 @@ impl Renderer { PreparedTextures::new(sprite_pixels, sprite_size, layers, sprite_mips, forcefield) }); let mut mip_levels = 1; + let gl = adapter.get_info().backend == wgpu::Backend::Gl; let sprite_textures: Vec = prepared .sprites .into_iter() .enumerate() - .map(|(array, (mips, levels))| { + .map(|(array, (mut mips, levels))| { let first = array as u32 * split; - let count = layers.saturating_sub(first).clamp(1, split); + let used = layers.saturating_sub(first).clamp(1, split); + let count = array_layers(used, gl); + // The extra layers are empty. + mips.resize(mips.len() / used as usize * count as usize, 0); mip_levels = levels; device.create_texture_with_data( &queue, @@ -1359,7 +1375,7 @@ impl Renderer { size: wgpu::Extent3d { width: 1, height: 1, - depth_or_array_layers: 1, + depth_or_array_layers: array_layers(1, gl), }, mip_level_count: 1, sample_count: 1, @@ -4560,6 +4576,13 @@ mod tests { } } #[test] + fn gl_sprite_arrays_are_neither_2d_textures_nor_cube_maps() { + for (count, gl) in [(1, 2), (2, 2), (5, 5), (6, 7), (12, 13), (2048, 2048)] { + assert_eq!(super::array_layers(count, true), gl); + assert_eq!(super::array_layers(count, false), count); + } + } + #[test] fn entity_shader_validates_with_its_overlay_constants() { let module = naga::front::wgsl::parse_str(&super::entity_shader()).unwrap(); naga::valid::Validator::new( From 1a16e35aaa45800285fca7d5be2a07e48f0421c0 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:25:37 +0100 Subject: [PATCH 2/3] Animated sprites without compute shaders (OpenGL before 4.3) SpriteAnimator wrote every changed sprite with a compute pass, which OpenGL 3.3 to 4.2 has no equivalent for in wgpu: creating the pipeline failed. Without compute shaders and storage, the same jobs now run on the CPU with animate.wgsl's integer mix, and each level is copied into its layer through the upload belt. The GPU test runs both paths against the same CPU reference. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx.rs | 1 + crates/horizon-client/src/gfx/animate.rs | 162 +++++++++++++++++++++-- 2 files changed, 150 insertions(+), 13 deletions(-) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index a02e6eb7f..baa8c5099 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -1368,6 +1368,7 @@ impl Renderer { sprite_mips, &sprite_textures, split, + animate::SpriteAnimator::compute(&adapter, &device), ); let sprite_unused = device .create_texture(&wgpu::TextureDescriptor { diff --git a/crates/horizon-client/src/gfx/animate.rs b/crates/horizon-client/src/gfx/animate.rs index b7c44429b..c94d8034e 100644 --- a/crates/horizon-client/src/gfx/animate.rs +++ b/crates/horizon-client/src/gfx/animate.rs @@ -10,6 +10,10 @@ //! frames. Blending on the CPU at the array's size and copying every changed //! sprite level by level (a copy command each, a blit each in Mesa) was about //! a fifth of the render thread on an integrated GPU. +//! +//! Without compute shaders (OpenGL before 4.3, the last fallback) the same +//! jobs run on the CPU, the same integer mix as `animate.wgsl`, and each +//! changed level is copied into its layer. use super::upload::Uploads; use crate::mipmap::Settings; use crate::sprites::{FrameBlend, SpriteAnimation}; @@ -38,17 +42,32 @@ struct Sprite { struct Group { /// Where its jobs start in `SpriteAnimator::jobs`, in bytes. offset: u64, - /// One bind group per mip level of the array. + /// One bind group per mip level of the array (none on the CPU). levels: Vec, /// This tick's jobs. jobs: Vec, + /// Its sprite array and its frames, for the CPU. + array: usize, + buffer: usize, +} + +/// Where the jobs run. +enum Writer { + Gpu { + jobs: wgpu::Buffer, + pipeline: wgpu::ComputePipeline, + }, + /// Every frames buffer's words, and the sprite arrays to copy into. + Cpu { + frames: Vec>, + textures: Vec, + }, } pub(super) struct SpriteAnimator { sprites: Vec, groups: Vec, - jobs: wgpu::Buffer, - pipeline: wgpu::ComputePipeline, + writer: Writer, /// Edge of the arrays' layers. size: u32, /// The layers the last `animate` rewrote, counted over all arrays. @@ -57,7 +76,8 @@ pub(super) struct SpriteAnimator { impl SpriteAnimator { /// `textures` are the sprite arrays, `split` layers each, `size` pixels - /// wide; `animations` hold their frames at that size. + /// wide; `animations` hold their frames at that size. `compute`: whether + /// the device runs compute shaders writing storage textures. pub fn new( device: &wgpu::Device, animations: &[SpriteAnimation], @@ -65,11 +85,17 @@ impl SpriteAnimator { settings: &[Settings], textures: &[wgpu::Texture], split: u32, + compute: bool, ) -> Self { let limits = device.limits(); - let limit = limits - .max_storage_buffer_binding_size - .min(limits.max_buffer_size); + let limit = if compute { + limits + .max_storage_buffer_binding_size + .min(limits.max_buffer_size) + } else { + // Word offsets. + u64::from(u32::MAX) * 4 + }; let mut frames: Vec> = Vec::new(); // Each group's sprite array and frames buffer. let mut keys: Vec<(u32, usize)> = Vec::new(); @@ -119,6 +145,29 @@ impl SpriteAnimator { group, }); } + if !compute { + let groups = keys + .iter() + .zip(&counts) + .map(|(&(array, buffer), &count)| Group { + offset: 0, + levels: Vec::new(), + jobs: Vec::with_capacity(count * JOB_BYTES), + array: array as usize, + buffer, + }) + .collect(); + return Self { + sprites, + groups, + writer: Writer::Cpu { + frames, + textures: textures.to_vec(), + }, + size, + changed: Vec::new(), + }; + } let frames: Vec<_> = frames .iter() .map(|data| { @@ -198,19 +247,33 @@ impl SpriteAnimator { offset, levels, jobs: Vec::with_capacity(count * JOB_BYTES), + array: array as usize, + buffer, } }) .collect(); Self { sprites, groups, - jobs, - pipeline, + writer: Writer::Gpu { jobs, pipeline }, size, changed: Vec::new(), } } + /// Whether the jobs can run on the GPU: compute shaders writing a + /// storage texture and reading two storage buffers (not OpenGL before + /// 4.3). + pub fn compute(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + let limits = device.limits(); + adapter + .get_downlevel_capabilities() + .flags + .contains(wgpu::DownlevelFlags::COMPUTE_SHADERS) + && limits.max_storage_textures_per_shader_stage >= 1 + && limits.max_storage_buffers_per_shader_stage >= 2 + } + /// The layers the last `animate` rewrote (for the shader pack atlas). pub fn changed(&self) -> &[u32] { &self.changed @@ -227,14 +290,47 @@ impl SpriteAnimator { if self.collect(tick) == 0 { return; } + let (jobs, pipeline) = match &self.writer { + Writer::Gpu { jobs, pipeline } => (jobs, pipeline), + Writer::Cpu { frames, textures } => { + for group in &mut self.groups { + let (frames, texture) = (&frames[group.buffer], &textures[group.array]); + for job in group.jobs.as_chunks::().0 { + let (words, _) = job.as_chunks::<4>(); + let job: [u32; 5] = std::array::from_fn(|i| u32::from_le_bytes(words[i])); + for level in 0..texture.mip_level_count() { + let width = self.size >> level; + uploads.texture( + encoder, + wgpu::TexelCopyTextureInfo { + texture, + mip_level: level, + origin: wgpu::Origin3d { + x: 0, + y: 0, + z: job[0], + }, + aspect: wgpu::TextureAspect::All, + }, + width, + width, + &mix_level(frames, job, width), + ); + } + } + group.jobs.clear(); + } + return; + } + }; for group in &self.groups { - uploads.buffer(encoder, &self.jobs, group.offset, &group.jobs); + uploads.buffer(encoder, jobs, group.offset, &group.jobs); } let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("Animated sprites"), timestamp_writes: None, }); - pass.set_pipeline(&self.pipeline); + pass.set_pipeline(pipeline); for group in &mut self.groups { let count = (group.jobs.len() / JOB_BYTES) as u32; if count == 0 { @@ -278,6 +374,33 @@ impl SpriteAnimator { } } +/// `animate.wgsl` on the CPU: one `width` wide level of a job +/// (`[layer, current, next, millis, edge]`) from `frames`' chains. +fn mix_level(frames: &[u8], [_, current, next, millis, edge]: [u32; 5], width: u32) -> Vec { + let mut out = Vec::with_capacity((width * width * 4) as usize); + for y in 0..width { + for x in 0..width { + let texel = if width >= edge { + let scale = width / edge; + y / scale * edge + x / scale + } else { + 4 * (edge * edge - width * width) / 3 + y * width + x + }; + let at = |chain: u32| ((chain + texel) * 4) as usize; + let a = &frames[at(current)..at(current) + 4]; + if millis == 0 { + out.extend_from_slice(a); + continue; + } + let b = &frames[at(next)..at(next) + 4]; + out.extend(a.iter().zip(b).map(|(&a, &b)| { + ((u32::from(a) * (1000 - millis) + u32::from(b) * millis + 500) / 1000) as u8 + })); + } + } + out +} + /// The mip chain a frame's layer is made of, and its first level's edge. /// `mipmap::generate` makes a sprite scaled up by whole pixels to the /// array's size from its own size's chain, its first level repeated into the @@ -512,6 +635,16 @@ mod tests { #[test] fn gpu_layers_match_the_cpu_chains_every_tick() { + layers_match_the_cpu_chains_every_tick(true); + } + + /// Without compute shaders (OpenGL before 4.3): the same layers. + #[test] + fn copied_layers_match_the_cpu_chains_every_tick() { + layers_match_the_cpu_chains_every_tick(false); + } + + fn layers_match_the_cpu_chains_every_tick(compute: bool) { let Some((device, queue)) = device() else { return; }; @@ -552,12 +685,15 @@ mod tests { sample_count: 1, dimension: wgpu::TextureDimension::D2, format: wgpu::TextureFormat::Rgba8Unorm, - usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::COPY_SRC, + usage: wgpu::TextureUsages::STORAGE_BINDING + | wgpu::TextureUsages::COPY_SRC + | wgpu::TextureUsages::COPY_DST, view_formats: &[], }) }) .collect(); - let mut animator = SpriteAnimator::new(&device, &animations, size, &mips, &textures, split); + let mut animator = + SpriteAnimator::new(&device, &animations, size, &mips, &textures, split, compute); let mut uploads = Uploads::new(&device); let mut writes = Vec::new(); for tick in [0, 0, 1, 2, 3, 4, 7, 7, 12, 30] { From 21203de7f07aec02ac1bb325462c729d9ae8fc38 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Sun, 25 Oct 2026 21:33:05 +0100 Subject: [PATCH 3/3] Animated sprites: the CPU path also when the driver cannot build the compute pipeline An OpenGL driver can list compute shaders among its extensions while wgpu writes GLSL of its core version, which has none (seen under MESA_GL_VERSION_OVERRIDE=3.3: the pipeline failed and the game panicked). The pipeline is now created inside error scopes, and a failure falls back to the CPU path with one warning. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/gfx/animate.rs | 50 ++++++++++++++++-------- 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/crates/horizon-client/src/gfx/animate.rs b/crates/horizon-client/src/gfx/animate.rs index c94d8034e..5a70f3b0f 100644 --- a/crates/horizon-client/src/gfx/animate.rs +++ b/crates/horizon-client/src/gfx/animate.rs @@ -77,7 +77,7 @@ pub(super) struct SpriteAnimator { impl SpriteAnimator { /// `textures` are the sprite arrays, `split` layers each, `size` pixels /// wide; `animations` hold their frames at that size. `compute`: whether - /// the device runs compute shaders writing storage textures. + /// the device says it runs compute shaders writing storage textures. pub fn new( device: &wgpu::Device, animations: &[SpriteAnimation], @@ -87,8 +87,9 @@ impl SpriteAnimator { split: u32, compute: bool, ) -> Self { + let pipeline = if compute { pipeline(device) } else { None }; let limits = device.limits(); - let limit = if compute { + let limit = if pipeline.is_some() { limits .max_storage_buffer_binding_size .min(limits.max_buffer_size) @@ -145,7 +146,7 @@ impl SpriteAnimator { group, }); } - if !compute { + let Some(pipeline) = pipeline else { let groups = keys .iter() .zip(&counts) @@ -167,7 +168,7 @@ impl SpriteAnimator { size, changed: Vec::new(), }; - } + }; let frames: Vec<_> = frames .iter() .map(|data| { @@ -191,18 +192,6 @@ impl SpriteAnimator { usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { - label: Some("Animated sprites"), - source: wgpu::ShaderSource::Wgsl(include_str!("animate.wgsl").into()), - }); - let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { - label: Some("Animated sprites"), - layout: None, - module: &module, - entry_point: Some("animate"), - compilation_options: Default::default(), - cache: None, - }); let layout = pipeline.get_bind_group_layout(0); let groups = keys .iter() @@ -374,6 +363,35 @@ impl SpriteAnimator { } } +/// `animate.wgsl`'s pipeline, unless the device fails to make it: an OpenGL +/// driver can list compute shaders among its extensions while wgpu writes +/// the GLSL version of its core version, which has none (Mesa's +/// `MESA_GL_VERSION_OVERRIDE`, older drivers). +fn pipeline(device: &wgpu::Device) -> Option { + let validation = device.push_error_scope(wgpu::ErrorFilter::Validation); + let internal = device.push_error_scope(wgpu::ErrorFilter::Internal); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Animated sprites"), + source: wgpu::ShaderSource::Wgsl(include_str!("animate.wgsl").into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Animated sprites"), + layout: None, + module: &module, + entry_point: Some("animate"), + compilation_options: Default::default(), + cache: None, + }); + let internal = pollster::block_on(internal.pop()); + match internal.or(pollster::block_on(validation.pop())) { + None => Some(pipeline), + Some(e) => { + log::warn!("Horizon renderer: animated sprites drawn on the CPU ({e})"); + None + } + } +} + /// `animate.wgsl` on the CPU: one `width` wide level of a job /// (`[layer, current, next, millis, edge]`) from `frames`' chains. fn mix_level(frames: &[u8], [_, current, next, millis, edge]: [u32; 5], width: u32) -> Vec {