Merge pull request #1920 from ludovic111/fix/opengl-downlevel
🤖 Agent: merged after verify and a real OpenGL run on the desktop (Mesa, GL 4.6 and 3.3: no crash, animated sprites on the CPU below 4.3). Released at once on Ludovic's request.
This commit is contained in:
@@ -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<wgpu::Texture> = 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,
|
||||
@@ -1352,6 +1368,7 @@ impl Renderer {
|
||||
sprite_mips,
|
||||
&sprite_textures,
|
||||
split,
|
||||
animate::SpriteAnimator::compute(&adapter, &device),
|
||||
);
|
||||
let sprite_unused = device
|
||||
.create_texture(&wgpu::TextureDescriptor {
|
||||
@@ -1359,7 +1376,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 +4577,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(
|
||||
|
||||
@@ -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<wgpu::BindGroup>,
|
||||
/// This tick's jobs.
|
||||
jobs: Vec<u8>,
|
||||
/// 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<Vec<u8>>,
|
||||
textures: Vec<wgpu::Texture>,
|
||||
},
|
||||
}
|
||||
|
||||
pub(super) struct SpriteAnimator {
|
||||
sprites: Vec<Sprite>,
|
||||
groups: Vec<Group>,
|
||||
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 says it runs compute shaders writing storage textures.
|
||||
pub fn new(
|
||||
device: &wgpu::Device,
|
||||
animations: &[SpriteAnimation],
|
||||
@@ -65,11 +85,18 @@ impl SpriteAnimator {
|
||||
settings: &[Settings],
|
||||
textures: &[wgpu::Texture],
|
||||
split: u32,
|
||||
compute: bool,
|
||||
) -> Self {
|
||||
let pipeline = if compute { pipeline(device) } else { None };
|
||||
let limits = device.limits();
|
||||
let limit = limits
|
||||
.max_storage_buffer_binding_size
|
||||
.min(limits.max_buffer_size);
|
||||
let limit = if pipeline.is_some() {
|
||||
limits
|
||||
.max_storage_buffer_binding_size
|
||||
.min(limits.max_buffer_size)
|
||||
} else {
|
||||
// Word offsets.
|
||||
u64::from(u32::MAX) * 4
|
||||
};
|
||||
let mut frames: Vec<Vec<u8>> = Vec::new();
|
||||
// Each group's sprite array and frames buffer.
|
||||
let mut keys: Vec<(u32, usize)> = Vec::new();
|
||||
@@ -119,6 +146,29 @@ impl SpriteAnimator {
|
||||
group,
|
||||
});
|
||||
}
|
||||
let Some(pipeline) = pipeline else {
|
||||
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| {
|
||||
@@ -142,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()
|
||||
@@ -198,19 +236,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 +279,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::<JOB_BYTES>().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 +363,62 @@ 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<wgpu::ComputePipeline> {
|
||||
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<u8> {
|
||||
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 +653,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 +703,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] {
|
||||
|
||||
Reference in New Issue
Block a user