fix: contain GPU initialization and retire failed readbacks
This commit is contained in:
+267
-104
@@ -21,10 +21,9 @@ use crate::context::{Enc, GpuContext, GpuImage};
|
||||
|
||||
/// Pipelines (built on first use).
|
||||
pub(crate) struct Pipes {
|
||||
bgl: wgpu::BindGroupLayout,
|
||||
/// (opaque, transparent); `None` when the adapter can't rasterise ([`raster_unsupported`]):
|
||||
/// scenes then render on the CPU.
|
||||
raster: Option<(wgpu::RenderPipeline, wgpu::RenderPipeline)>,
|
||||
raster: Option<(wgpu::BindGroupLayout, wgpu::RenderPipeline, wgpu::RenderPipeline)>,
|
||||
post: Post,
|
||||
}
|
||||
|
||||
@@ -45,21 +44,171 @@ const VERTEX_SIZE: u64 = 52;
|
||||
/// would be a validation error, which release builds only log (and then draw nothing), so the
|
||||
/// caller keeps the scenes on the CPU instead.
|
||||
pub(crate) fn raster_unsupported(adapter: &wgpu::Adapter) -> Option<String> {
|
||||
raster_capability_reason(adapter.get_downlevel_capabilities().flags, |format| adapter.get_texture_format_features(format))
|
||||
}
|
||||
|
||||
fn raster_capability_reason(flags: wgpu::DownlevelFlags, features: impl Fn(wgpu::TextureFormat) -> wgpu::TextureFormatFeatures) -> Option<String> {
|
||||
use wgpu::TextureFormatFeatureFlags as F;
|
||||
let needs = [(COLOR, F::BLENDABLE), (DEPTH_OUT, F::empty()), (DEPTH, F::empty())];
|
||||
for (format, flags) in needs {
|
||||
let f = adapter.get_texture_format_features(format);
|
||||
if !f.allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT) || !f.flags.contains(flags) {
|
||||
return Some(format!("{format:?} is not a {}render target", if flags.is_empty() { "" } else { "blendable " }));
|
||||
use wgpu::TextureUsages as U;
|
||||
if !flags.contains(wgpu::DownlevelFlags::FRAGMENT_STORAGE) {
|
||||
return Some("no fragment storage buffers".into());
|
||||
}
|
||||
let targets = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING | U::COPY_SRC;
|
||||
let needs = [(COLOR, targets, F::BLENDABLE), (DEPTH_OUT, targets, F::empty()), (DEPTH, U::RENDER_ATTACHMENT, F::empty())];
|
||||
for (format, usages, required_flags) in needs {
|
||||
let f = features(format);
|
||||
if !f.allowed_usages.contains(usages) || !f.flags.contains(required_flags) {
|
||||
return Some(format!("{format:?} lacks raster usages {usages:?} or flags {required_flags:?}"));
|
||||
}
|
||||
}
|
||||
// The transparent pipeline blends colour and masks the depth target off.
|
||||
if !adapter.get_downlevel_capabilities().flags.contains(wgpu::DownlevelFlags::INDEPENDENT_BLEND) {
|
||||
if !flags.contains(wgpu::DownlevelFlags::INDEPENDENT_BLEND) {
|
||||
return Some("no independent blending".into());
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Bound one allocation by its actual byte stride, without imposing a global image limit.
|
||||
fn buffer_bytes(count: u64, stride: u64, limit: u64) -> Option<u64> {
|
||||
let size = count.checked_mul(stride)?;
|
||||
(size > 0 && size <= limit && usize::try_from(size).is_ok()).then_some(size)
|
||||
}
|
||||
|
||||
/// Sizes of exactly the arrays serialized by pack, including its empty storage padding.
|
||||
/// Checking these before serialization bounds host packing as well as the GPU uploads.
|
||||
fn packed_bytes(counts: [u64; 6], uniform_limit: u64, storage_limit: u64, buffer_limit: u64) -> Option<[u64; 7]> {
|
||||
let mut sizes = [0; 7];
|
||||
sizes[0] = buffer_bytes(40, 4, uniform_limit.min(buffer_limit))?;
|
||||
for (index, (count, stride)) in counts.into_iter().zip([96, 16, 16, 80, 80, 4]).enumerate() {
|
||||
let size = count.checked_mul(stride)?.max(16);
|
||||
sizes[index + 1] = buffer_bytes(size, 1, storage_limit.min(buffer_limit))?;
|
||||
}
|
||||
Some(sizes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod capability_tests {
|
||||
use super::*;
|
||||
|
||||
fn supported(format: wgpu::TextureFormat) -> wgpu::TextureFormatFeatures {
|
||||
let rt = wgpu::TextureUsages::RENDER_ATTACHMENT;
|
||||
wgpu::TextureFormatFeatures {
|
||||
allowed_usages: if format == DEPTH { rt } else { rt | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC },
|
||||
flags: if format == COLOR { wgpu::TextureFormatFeatureFlags::BLENDABLE } else { wgpu::TextureFormatFeatureFlags::empty() },
|
||||
}
|
||||
}
|
||||
|
||||
fn downlevel() -> wgpu::DownlevelFlags {
|
||||
wgpu::DownlevelFlags::FRAGMENT_STORAGE | wgpu::DownlevelFlags::INDEPENDENT_BLEND
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matching_raster_capabilities_are_accepted_without_optional_features() {
|
||||
assert!(raster_capability_reason(downlevel(), supported).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fragment_storage_and_independent_blending_are_required() {
|
||||
for flag in [wgpu::DownlevelFlags::FRAGMENT_STORAGE, wgpu::DownlevelFlags::INDEPENDENT_BLEND] {
|
||||
assert!(raster_capability_reason(downlevel() - flag, supported).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_and_integer_depth_require_their_actual_texture_usages() {
|
||||
for target in [COLOR, DEPTH_OUT] {
|
||||
for usage in [wgpu::TextureUsages::RENDER_ATTACHMENT, wgpu::TextureUsages::TEXTURE_BINDING, wgpu::TextureUsages::COPY_SRC] {
|
||||
assert!(
|
||||
raster_capability_reason(downlevel(), |format| {
|
||||
let mut features = supported(format);
|
||||
if format == target {
|
||||
features.allowed_usages.remove(usage);
|
||||
}
|
||||
features
|
||||
})
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn color_blending_and_depth_attachment_are_required() {
|
||||
for target in [COLOR, DEPTH] {
|
||||
assert!(
|
||||
raster_capability_reason(downlevel(), |format| {
|
||||
let mut features = supported(format);
|
||||
if format == target {
|
||||
if target == COLOR {
|
||||
features.flags.remove(wgpu::TextureFormatFeatureFlags::BLENDABLE);
|
||||
} else {
|
||||
features.allowed_usages.remove(wgpu::TextureUsages::RENDER_ATTACHMENT);
|
||||
}
|
||||
}
|
||||
features
|
||||
})
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_guards_use_each_buffer_stride_and_reject_overflow() {
|
||||
assert_eq!(buffer_bytes(2, VERTEX_SIZE, 104), Some(104));
|
||||
assert_eq!(buffer_bytes(2, VERTEX_SIZE, 103), None);
|
||||
assert_eq!(buffer_bytes(26, 4, 104), Some(104));
|
||||
assert_eq!(buffer_bytes(27, 4, 104), None);
|
||||
assert_eq!(buffer_bytes(0, 4, 104), None);
|
||||
assert_eq!(buffer_bytes(u64::MAX, 4, u64::MAX), None);
|
||||
assert_eq!(buffer_bytes(1, 16, 15), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_arrays_preflight_exact_strides_and_empty_padding() {
|
||||
assert_eq!(packed_bytes([0; 6], 160, 16, 160), Some([160, 16, 16, 16, 16, 16, 16]));
|
||||
assert_eq!(packed_bytes([2; 6], 160, 192, 192), Some([160, 192, 32, 32, 160, 160, 16]));
|
||||
assert!(packed_bytes([0; 6], 159, 16, 160).is_none());
|
||||
assert!(packed_bytes([0; 6], 160, 15, 160).is_none());
|
||||
assert!(packed_bytes([2; 6], 160, 192, 191).is_none());
|
||||
for index in 0..6 {
|
||||
let mut counts = [0; 6];
|
||||
counts[index] = u64::MAX;
|
||||
assert!(packed_bytes(counts, u64::MAX, u64::MAX, u64::MAX).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predicted_sizes_match_the_real_scene_serializer() {
|
||||
use effectcraft_render::three_d::adv::{Light, Material, ShadowMap, TexInfo};
|
||||
let scene = Scene {
|
||||
materials: vec![Material::default()],
|
||||
textures: vec![TexInfo { offset: 0, width: 1, height: 1, wrap_u: 0, wrap_v: 0 }],
|
||||
texels: vec![[0.0; 4]],
|
||||
lights: vec![Light {
|
||||
kind: 0,
|
||||
pos: [0.0; 3],
|
||||
dir: [0.0; 3],
|
||||
color: [0.0; 3],
|
||||
cos_inner: 0.0,
|
||||
cos_outer: 0.0,
|
||||
falloff: 0,
|
||||
radius: 0.0,
|
||||
falloff_distance: 0.0,
|
||||
shadow: -1,
|
||||
shadow_darkness: 0.0,
|
||||
shadow_diffusion: 0.0,
|
||||
}],
|
||||
shadows: vec![ShadowMap { view: [[0.0; 4]; 3], focal: 0.0, ortho: false, size: 1, offset: 0, bias: 0.0, radius: 0.0 }],
|
||||
shadow_texels: vec![0.0],
|
||||
..Scene::default()
|
||||
};
|
||||
for (scene, counts) in [(Scene::default(), [0; 6]), (scene, [1; 6])] {
|
||||
let actual = pack(&scene).map(|bytes| bytes.len() as u64);
|
||||
assert_eq!(Some(actual), packed_bytes(counts, 160, 160, 160));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn storage(binding: u32) -> wgpu::BindGroupLayoutEntry {
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
@@ -71,70 +220,78 @@ fn storage(binding: u32) -> wgpu::BindGroupLayoutEntry {
|
||||
|
||||
impl Pipes {
|
||||
fn new(device: &wgpu::Device, raster: bool) -> Pipes {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("effectcraft advanced 3d"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/advanced3d.wgsl").into()),
|
||||
let raster = raster.then(|| {
|
||||
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("effectcraft advanced 3d"),
|
||||
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/advanced3d.wgsl").into()),
|
||||
});
|
||||
let mut entries = vec![wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
}];
|
||||
entries.extend((1..=6).map(storage));
|
||||
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("advanced 3d"), entries: &entries });
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("advanced 3d"),
|
||||
bind_group_layouts: &[Some(&bgl)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let attrs = [
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x4, offset: 32, shader_location: 3 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Uint32, offset: 48, shader_location: 4 },
|
||||
];
|
||||
let make = |transparent: bool| {
|
||||
let blend = transparent.then_some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(if transparent { "advanced 3d transparent" } else { "advanced 3d opaque" }),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some("vs"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: VERTEX_SIZE, step_mode: wgpu::VertexStepMode::Vertex, attributes: &attrs })],
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: DEPTH,
|
||||
depth_write_enabled: Some(!transparent),
|
||||
depth_compare: Some(wgpu::CompareFunction::Greater),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[
|
||||
Some(wgpu::ColorTargetState { format: COLOR, blend, write_mask: wgpu::ColorWrites::ALL }),
|
||||
Some(wgpu::ColorTargetState {
|
||||
format: DEPTH_OUT,
|
||||
blend: None,
|
||||
write_mask: if transparent { wgpu::ColorWrites::empty() } else { wgpu::ColorWrites::ALL },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
let opaque = make(false);
|
||||
let transparent = make(true);
|
||||
(bgl, opaque, transparent)
|
||||
});
|
||||
let mut entries = vec![wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
|
||||
count: None,
|
||||
}];
|
||||
entries.extend((1..=6).map(storage));
|
||||
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("advanced 3d"), entries: &entries });
|
||||
let layout =
|
||||
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("advanced 3d"), bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
|
||||
let attrs = [
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 0, shader_location: 0 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x3, offset: 12, shader_location: 1 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x2, offset: 24, shader_location: 2 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Float32x4, offset: 32, shader_location: 3 },
|
||||
wgpu::VertexAttribute { format: wgpu::VertexFormat::Uint32, offset: 48, shader_location: 4 },
|
||||
];
|
||||
let make = |transparent: bool| {
|
||||
let blend = transparent.then_some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING);
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some(if transparent { "advanced 3d transparent" } else { "advanced 3d opaque" }),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &module,
|
||||
entry_point: Some("vs"),
|
||||
compilation_options: Default::default(),
|
||||
buffers: &[Some(wgpu::VertexBufferLayout { array_stride: VERTEX_SIZE, step_mode: wgpu::VertexStepMode::Vertex, attributes: &attrs })],
|
||||
},
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
front_face: wgpu::FrontFace::Ccw,
|
||||
cull_mode: None,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: Some(wgpu::DepthStencilState {
|
||||
format: DEPTH,
|
||||
depth_write_enabled: Some(!transparent),
|
||||
depth_compare: Some(wgpu::CompareFunction::Greater),
|
||||
stencil: Default::default(),
|
||||
bias: Default::default(),
|
||||
}),
|
||||
multisample: Default::default(),
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &module,
|
||||
entry_point: Some("fs"),
|
||||
compilation_options: Default::default(),
|
||||
targets: &[
|
||||
Some(wgpu::ColorTargetState { format: COLOR, blend, write_mask: wgpu::ColorWrites::ALL }),
|
||||
Some(wgpu::ColorTargetState {
|
||||
format: DEPTH_OUT,
|
||||
blend: None,
|
||||
write_mask: if transparent { wgpu::ColorWrites::empty() } else { wgpu::ColorWrites::ALL },
|
||||
}),
|
||||
],
|
||||
}),
|
||||
multiview_mask: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
Pipes { raster: raster.then(|| (make(false), make(true))), bgl, post: Post::new(device) }
|
||||
Pipes { raster, post: Post::new(device) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -251,16 +408,28 @@ fn half_to_f32(h: u16) -> f32 {
|
||||
/// (render targets, size or buffer limits).
|
||||
fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)> {
|
||||
let g = e.g;
|
||||
if !g.fits(s.width, s.height) || s.indices.is_empty() {
|
||||
if !g.adv3d_raster || !g.fits(s.width, s.height) || s.indices.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let limits = g.device.limits();
|
||||
buffer_bytes(u64::try_from(s.vertices.len()).ok()?, VERTEX_SIZE, limits.max_buffer_size)?;
|
||||
buffer_bytes(u64::try_from(s.indices.len()).ok()?, 4, limits.max_buffer_size)?;
|
||||
let n = u32::try_from(s.indices.len()).ok()?;
|
||||
if s.opaque_count > n {
|
||||
return None;
|
||||
}
|
||||
let counts = [s.materials.len(), s.textures.len(), s.texels.len(), s.lights.len(), s.shadows.len(), s.shadow_texels.len()];
|
||||
let mut checked_counts = [0; 6];
|
||||
for (out, count) in checked_counts.iter_mut().zip(counts) {
|
||||
*out = u64::try_from(count).ok()?;
|
||||
}
|
||||
let expected_sizes = packed_bytes(checked_counts, limits.max_uniform_buffer_binding_size, limits.max_storage_buffer_binding_size, limits.max_buffer_size)?;
|
||||
let bufs = pack(s);
|
||||
if bufs.iter().any(|b| b.len() as u64 > limits.max_storage_buffer_binding_size) {
|
||||
if bufs.iter().zip(expected_sizes).any(|(bytes, expected)| bytes.len() as u64 != expected) {
|
||||
return None;
|
||||
}
|
||||
let p = pipes(g);
|
||||
let Some((opaque, transparent)) = &p.raster else { return None };
|
||||
let Some((bgl, opaque, transparent)) = &p.raster else { return None };
|
||||
let dev = &g.device;
|
||||
let vb: Vec<u8> = s
|
||||
.vertices
|
||||
@@ -286,7 +455,7 @@ fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)>
|
||||
for (i, b) in sbs.iter().enumerate() {
|
||||
entries.push(wgpu::BindGroupEntry { binding: i as u32 + 1, resource: b.as_entire_binding() });
|
||||
}
|
||||
let bg = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("adv3d"), layout: &p.bgl, entries: &entries });
|
||||
let bg = dev.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("adv3d"), layout: bgl, entries: &entries });
|
||||
let tex = |format: wgpu::TextureFormat, usage: wgpu::TextureUsages| {
|
||||
dev.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("adv3d target"),
|
||||
@@ -334,7 +503,6 @@ fn raster_into(e: &mut Enc, s: &Scene) -> Option<(wgpu::Texture, wgpu::Texture)>
|
||||
pass.set_bind_group(0, &bg, &[]);
|
||||
pass.set_vertex_buffer(0, vbuf.slice(..));
|
||||
pass.set_index_buffer(ibuf.slice(..), wgpu::IndexFormat::Uint32);
|
||||
let n = s.indices.len() as u32;
|
||||
if s.opaque_count > 0 {
|
||||
pass.set_pipeline(opaque);
|
||||
pass.draw_indexed(0..s.opaque_count, 0, 0..1);
|
||||
@@ -604,6 +772,11 @@ fn read_buffer(e: &mut Enc, buf: &wgpu::Buffer, size: u64) -> Option<Vec<u8>> {
|
||||
if !e.g.can_wait() {
|
||||
return None;
|
||||
}
|
||||
buffer_bytes(size, 1, e.g.device.limits().max_buffer_size)?;
|
||||
let row = usize::try_from(size).ok()?;
|
||||
if size > buf.size() || !size.is_multiple_of(wgpu::COPY_BUFFER_ALIGNMENT) {
|
||||
return None;
|
||||
}
|
||||
let rb = e.g.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("adv3d readback"),
|
||||
size,
|
||||
@@ -612,14 +785,7 @@ fn read_buffer(e: &mut Enc, buf: &wgpu::Buffer, size: u64) -> Option<Vec<u8>> {
|
||||
});
|
||||
e.encoder().copy_buffer_to_buffer(buf, 0, &rb, 0, size);
|
||||
e.submit();
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
rb.map_async(wgpu::MapMode::Read, .., move |r| {
|
||||
let _ = tx.send(r);
|
||||
});
|
||||
e.g.device.poll(wgpu::PollType::wait_indefinitely()).ok()?;
|
||||
rx.recv().ok()?.ok()?;
|
||||
let out = rb.get_mapped_range(..).ok()?.to_vec();
|
||||
rb.unmap();
|
||||
let out = e.g.read_buffer(&rb, row, row, 1).map_err(|e| log::error!("gpu 3d readback: {e}")).ok()?;
|
||||
Some(out)
|
||||
}
|
||||
|
||||
@@ -645,12 +811,12 @@ pub(crate) fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolve
|
||||
return None;
|
||||
}
|
||||
let px = w as u64 * h as u64;
|
||||
let max = g.device.limits().max_storage_buffer_binding_size;
|
||||
if px * 16 > max {
|
||||
return None;
|
||||
}
|
||||
let acc = storage_buf(g, px * 16, "adv3d acc");
|
||||
let depth = storage_buf(g, px * 4, "adv3d depth");
|
||||
let limits = g.device.limits();
|
||||
let max = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
|
||||
let acc_bytes = buffer_bytes(px, 16, max)?;
|
||||
let depth_bytes = buffer_bytes(px, 4, max)?;
|
||||
let acc = storage_buf(g, acc_bytes, "adv3d acc");
|
||||
let depth = storage_buf(g, depth_bytes, "adv3d depth");
|
||||
let n = prep.samples.max(1);
|
||||
let weight = if n <= 1 { 1.0 } else { 1.0 / n as f32 };
|
||||
let mut first = true;
|
||||
@@ -659,7 +825,7 @@ pub(crate) fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolve
|
||||
if s.indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if s.width != w * s.ssaa.max(1) || s.height != h * s.ssaa.max(1) {
|
||||
if Some(s.width) != w.checked_mul(s.ssaa.max(1)) || Some(s.height) != h.checked_mul(s.ssaa.max(1)) {
|
||||
return None;
|
||||
}
|
||||
let (color, zout) = raster_into(e, &s)?;
|
||||
@@ -684,9 +850,10 @@ pub(crate) fn resolve_run(e: &mut Enc, prep: &Prepared) -> Option<Option<Resolve
|
||||
fn depth_of_field(e: &mut Enc, acc: &wgpu::Buffer, depth: &wgpu::Buffer, (w, h): (u32, u32), dof: &Dof, scale: f64) -> Option<()> {
|
||||
let g = e.g;
|
||||
let px = w as u64 * h as u64;
|
||||
if (w as u64 + 1) * h as u64 * 16 > g.device.limits().max_storage_buffer_binding_size {
|
||||
return None;
|
||||
}
|
||||
let limits = g.device.limits();
|
||||
let max = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size);
|
||||
let prefix_bytes = buffer_bytes((u64::from(w) + 1).checked_mul(u64::from(h))?, 16, max)?;
|
||||
buffer_bytes(1, 16, max)?;
|
||||
let radius = storage_buf(g, px * 4, "adv3d radius");
|
||||
let mut init = Vec::with_capacity(16);
|
||||
for v in [f32::INFINITY.to_bits(), 0, 0, 0] {
|
||||
@@ -724,12 +891,12 @@ fn depth_of_field(e: &mut Enc, acc: &wgpu::Buffer, depth: &wgpu::Buffer, (w, h):
|
||||
}
|
||||
}
|
||||
let table: Vec<u8> = heads.iter().chain(&spans).flatten().flat_map(|x| x.to_le_bytes()).collect();
|
||||
if table.len() as u64 > g.device.limits().max_storage_buffer_binding_size {
|
||||
if table.len() as u64 > max {
|
||||
return None;
|
||||
}
|
||||
let table = e.bytes(table);
|
||||
let src = storage_buf(g, px * 16, "adv3d dof source");
|
||||
let prefix = storage_buf(g, (w as u64 + 1) * h as u64 * 16, "adv3d prefix");
|
||||
let prefix = storage_buf(g, prefix_bytes, "adv3d prefix");
|
||||
let hl = dof.highlight;
|
||||
let b = Binds { bufs: [Some(acc), None, Some(&src), None, Some(&radius), None, None], ..Default::default() };
|
||||
dispatch(e, "boost", [w, h, 0, 0], [hl.gain as f32, hl.threshold as f32, hl.saturation as f32, 0.0], b, pixel_groups(w, h));
|
||||
@@ -788,6 +955,8 @@ fn render_prepared_deferred(g: &GpuContext, d: &std::sync::Arc<crate::deferred::
|
||||
return None;
|
||||
}
|
||||
let (w, h) = prep.out;
|
||||
let size = buffer_bytes(u64::from(w).checked_mul(u64::from(h))?, 4, g.device.limits().max_buffer_size)?;
|
||||
let row = usize::try_from(size).ok()?;
|
||||
let mut k = crate::deferred::Key::new(5);
|
||||
k.u64(w as u64);
|
||||
k.u64(h as u64);
|
||||
@@ -836,7 +1005,6 @@ fn render_prepared_deferred(g: &GpuContext, d: &std::sync::Arc<crate::deferred::
|
||||
let Some(r) = resolve_run(&mut e, prep)? else { return Some(None) };
|
||||
let img = finish(&mut e, &r, !prep.linear, None);
|
||||
let _ = e.read_keyed(&img, ki, [0.0; 2], 1.0);
|
||||
let size = w as u64 * h as u64 * 4;
|
||||
let rb = g.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("adv3d depth readback"),
|
||||
size,
|
||||
@@ -846,14 +1014,9 @@ fn render_prepared_deferred(g: &GpuContext, d: &std::sync::Arc<crate::deferred::
|
||||
e.encoder().copy_buffer_to_buffer(&r.depth, 0, &rb, 0, size);
|
||||
e.submit();
|
||||
let done = d.start(kz, w, h, [0.0; 2], 1.0);
|
||||
let b = rb.clone();
|
||||
rb.map_async(wgpu::MapMode::Read, .., move |res| {
|
||||
let out = res.ok().and_then(|_| b.get_mapped_range(..).ok().map(|v| v.to_vec()));
|
||||
b.unmap();
|
||||
done(out);
|
||||
});
|
||||
g.map_readback(&rb, row, row, 1, move |r| done(r.map_err(|e| log::error!("gpu depth readback: {e}")).ok()));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let _ = g.device.poll(wgpu::PollType::Poll);
|
||||
let _ = g.poll_readbacks(wgpu::PollType::Poll);
|
||||
d.miss();
|
||||
Some(None)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user