Update `wgpu` to `0.6` in `iced_wgpu`

This commit is contained in:
Héctor Ramón Jiménez 2020-08-27 13:03:42 +02:00
parent fb015a85d2
commit 67d90e3946
8 changed files with 275 additions and 211 deletions

View File

@ -13,17 +13,15 @@ canvas = ["iced_graphics/canvas"]
default_system_font = ["iced_graphics/font-source"] default_system_font = ["iced_graphics/font-source"]
[dependencies] [dependencies]
wgpu = "0.5" wgpu = "0.6"
wgpu_glyph = "0.9" wgpu_glyph = "0.10"
glyph_brush = "0.7" glyph_brush = "0.7"
zerocopy = "0.3" zerocopy = "0.3"
bytemuck = "1.2" bytemuck = "1.2"
raw-window-handle = "0.3" raw-window-handle = "0.3"
log = "0.4" log = "0.4"
guillotiere = "0.5" guillotiere = "0.5"
# Pin `gfx-memory` until https://github.com/gfx-rs/wgpu-rs/issues/261 is futures = "0.3"
# resolved
gfx-memory = "=0.1.1"
[dependencies.iced_native] [dependencies.iced_native]
version = "0.2" version = "0.2"

View File

@ -64,6 +64,7 @@ impl Backend {
pub fn draw<T: AsRef<str>>( pub fn draw<T: AsRef<str>>(
&mut self, &mut self,
device: &wgpu::Device, device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
frame: &wgpu::TextureView, frame: &wgpu::TextureView,
viewport: &Viewport, viewport: &Viewport,
@ -85,6 +86,7 @@ impl Backend {
scale_factor, scale_factor,
transformation, transformation,
&layer, &layer,
staging_belt,
encoder, encoder,
&frame, &frame,
target_size.width, target_size.width,
@ -104,6 +106,7 @@ impl Backend {
scale_factor: f32, scale_factor: f32,
transformation: Transformation, transformation: Transformation,
layer: &Layer<'_>, layer: &Layer<'_>,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView, target: &wgpu::TextureView,
target_width: u32, target_width: u32,
@ -114,6 +117,7 @@ impl Backend {
if !layer.quads.is_empty() { if !layer.quads.is_empty() {
self.quad_pipeline.draw( self.quad_pipeline.draw(
device, device,
staging_belt,
encoder, encoder,
&layer.quads, &layer.quads,
transformation, transformation,
@ -129,6 +133,7 @@ impl Backend {
self.triangle_pipeline.draw( self.triangle_pipeline.draw(
device, device,
staging_belt,
encoder, encoder,
target, target,
target_width, target_width,
@ -225,6 +230,7 @@ impl Backend {
self.text_pipeline.draw_queued( self.text_pipeline.draw_queued(
device, device,
staging_belt,
encoder, encoder,
target, target,
transformation, transformation,

View File

@ -23,7 +23,7 @@
#![deny(missing_docs)] #![deny(missing_docs)]
#![deny(missing_debug_implementations)] #![deny(missing_debug_implementations)]
#![deny(unused_results)] #![deny(unused_results)]
#![forbid(unsafe_code)] #![deny(unsafe_code)]
#![forbid(rust_2018_idioms)] #![forbid(rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]

View File

@ -3,6 +3,7 @@ use iced_graphics::layer;
use iced_native::Rectangle; use iced_native::Rectangle;
use std::mem; use std::mem;
use wgpu::util::DeviceExt;
use zerocopy::AsBytes; use zerocopy::AsBytes;
#[derive(Debug)] #[derive(Debug)]
@ -20,50 +21,54 @@ impl Pipeline {
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: None,
bindings: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::VERTEX, visibility: wgpu::ShaderStage::VERTEX,
ty: wgpu::BindingType::UniformBuffer { dynamic: false }, ty: wgpu::BindingType::UniformBuffer {
dynamic: false,
min_binding_size: wgpu::BufferSize::new(
mem::size_of::<Uniforms>() as u64,
),
},
count: None,
}], }],
}); });
let constants_buffer = device.create_buffer_with_data( let constants_buffer =
Uniforms::default().as_bytes(), device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, label: None,
); contents: Uniforms::default().as_bytes(),
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
});
let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { let constants = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Buffer { resource: wgpu::BindingResource::Buffer(
buffer: &constants_buffer, constants_buffer.slice(..),
range: 0..std::mem::size_of::<Uniforms>() as u64, ),
},
}], }],
}); });
let layout = let layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
push_constant_ranges: &[],
bind_group_layouts: &[&constant_layout], bind_group_layouts: &[&constant_layout],
}); });
let vs = include_bytes!("shader/quad.vert.spv"); let vs_module = device
let vs_module = device.create_shader_module( .create_shader_module(wgpu::include_spirv!("shader/quad.vert.spv"));
&wgpu::read_spirv(std::io::Cursor::new(&vs[..]))
.expect("Read quad vertex shader as SPIR-V"),
);
let fs = include_bytes!("shader/quad.frag.spv"); let fs_module = device
let fs_module = device.create_shader_module( .create_shader_module(wgpu::include_spirv!("shader/quad.frag.spv"));
&wgpu::read_spirv(std::io::Cursor::new(&fs[..]))
.expect("Read quad fragment shader as SPIR-V"),
);
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &layout, label: None,
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -78,6 +83,7 @@ impl Pipeline {
depth_bias: 0, depth_bias: 0,
depth_bias_slope_scale: 0.0, depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0, depth_bias_clamp: 0.0,
..Default::default()
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -150,20 +156,25 @@ impl Pipeline {
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,
}); });
let vertices = device.create_buffer_with_data( let vertices =
QUAD_VERTS.as_bytes(), device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
wgpu::BufferUsage::VERTEX, label: None,
); contents: QUAD_VERTS.as_bytes(),
usage: wgpu::BufferUsage::VERTEX,
});
let indices = device.create_buffer_with_data( let indices =
QUAD_INDICES.as_bytes(), device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
wgpu::BufferUsage::INDEX, label: None,
); contents: QUAD_INDICES.as_bytes(),
usage: wgpu::BufferUsage::INDEX,
});
let instances = device.create_buffer(&wgpu::BufferDescriptor { let instances = device.create_buffer(&wgpu::BufferDescriptor {
label: None, label: None,
size: mem::size_of::<layer::Quad>() as u64 * MAX_INSTANCES as u64, size: mem::size_of::<layer::Quad>() as u64 * MAX_INSTANCES as u64,
usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
mapped_at_creation: false,
}); });
Pipeline { Pipeline {
@ -179,6 +190,7 @@ impl Pipeline {
pub fn draw( pub fn draw(
&mut self, &mut self,
device: &wgpu::Device, device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
instances: &[layer::Quad], instances: &[layer::Quad],
transformation: Transformation, transformation: Transformation,
@ -188,18 +200,18 @@ impl Pipeline {
) { ) {
let uniforms = Uniforms::new(transformation, scale); let uniforms = Uniforms::new(transformation, scale);
let constants_buffer = device.create_buffer_with_data( {
uniforms.as_bytes(), let mut constants_buffer = staging_belt.write_buffer(
wgpu::BufferUsage::COPY_SRC, encoder,
); &self.constants_buffer,
0,
wgpu::BufferSize::new(mem::size_of::<Uniforms>() as u64)
.unwrap(),
device,
);
encoder.copy_buffer_to_buffer( constants_buffer.copy_from_slice(uniforms.as_bytes());
&constants_buffer, }
0,
&self.constants_buffer,
0,
std::mem::size_of::<Uniforms>() as u64,
);
let mut i = 0; let mut i = 0;
let total = instances.len(); let total = instances.len();
@ -208,19 +220,18 @@ impl Pipeline {
let end = (i + MAX_INSTANCES).min(total); let end = (i + MAX_INSTANCES).min(total);
let amount = end - i; let amount = end - i;
let instance_buffer = device.create_buffer_with_data( let instance_bytes = bytemuck::cast_slice(&instances[i..end]);
bytemuck::cast_slice(&instances[i..end]),
wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( let mut instance_buffer = staging_belt.write_buffer(
&instance_buffer, encoder,
0,
&self.instances, &self.instances,
0, 0,
(mem::size_of::<layer::Quad>() * amount) as u64, wgpu::BufferSize::new(instance_bytes.len() as u64).unwrap(),
device,
); );
instance_buffer.copy_from_slice(instance_bytes);
{ {
let mut render_pass = let mut render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor { encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
@ -228,13 +239,9 @@ impl Pipeline {
wgpu::RenderPassColorAttachmentDescriptor { wgpu::RenderPassColorAttachmentDescriptor {
attachment: target, attachment: target,
resolve_target: None, resolve_target: None,
load_op: wgpu::LoadOp::Load, ops: wgpu::Operations {
store_op: wgpu::StoreOp::Store, load: wgpu::LoadOp::Load,
clear_color: wgpu::Color { store: true,
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
}, },
}, },
], ],
@ -243,9 +250,9 @@ impl Pipeline {
render_pass.set_pipeline(&self.pipeline); render_pass.set_pipeline(&self.pipeline);
render_pass.set_bind_group(0, &self.constants, &[]); render_pass.set_bind_group(0, &self.constants, &[]);
render_pass.set_index_buffer(&self.indices, 0, 0); render_pass.set_index_buffer(self.indices.slice(..));
render_pass.set_vertex_buffer(0, &self.vertices, 0, 0); render_pass.set_vertex_buffer(0, self.vertices.slice(..));
render_pass.set_vertex_buffer(1, &self.instances, 0, 0); render_pass.set_vertex_buffer(1, self.instances.slice(..));
render_pass.set_scissor_rect( render_pass.set_scissor_rect(
bounds.x, bounds.x,
bounds.y, bounds.y,

View File

@ -65,6 +65,7 @@ impl Pipeline {
pub fn draw_queued( pub fn draw_queued(
&mut self, &mut self,
device: &wgpu::Device, device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView, target: &wgpu::TextureView,
transformation: Transformation, transformation: Transformation,
@ -74,6 +75,7 @@ impl Pipeline {
.borrow_mut() .borrow_mut()
.draw_queued_with_transform_and_scissoring( .draw_queued_with_transform_and_scissoring(
device, device,
staging_belt,
encoder, encoder,
target, target,
transformation.into(), transformation.into(),

View File

@ -8,7 +8,7 @@ pub use iced_graphics::triangle::{Mesh2D, Vertex2D};
mod msaa; mod msaa;
const UNIFORM_BUFFER_SIZE: usize = 100; const UNIFORM_BUFFER_SIZE: usize = 50;
const VERTEX_BUFFER_SIZE: usize = 10_000; const VERTEX_BUFFER_SIZE: usize = 10_000;
const INDEX_BUFFER_SIZE: usize = 10_000; const INDEX_BUFFER_SIZE: usize = 10_000;
@ -41,6 +41,7 @@ impl<T> Buffer<T> {
label: None, label: None,
size: (std::mem::size_of::<T>() * size) as u64, size: (std::mem::size_of::<T>() * size) as u64,
usage, usage,
mapped_at_creation: false,
}); });
Buffer { Buffer {
@ -59,6 +60,7 @@ impl<T> Buffer<T> {
label: None, label: None,
size: (std::mem::size_of::<T>() * size) as u64, size: (std::mem::size_of::<T>() * size) as u64,
usage: self.usage, usage: self.usage,
mapped_at_creation: false,
}); });
self.size = size; self.size = size;
@ -77,10 +79,16 @@ impl Pipeline {
let constants_layout = let constants_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: None,
bindings: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::VERTEX, visibility: wgpu::ShaderStage::VERTEX,
ty: wgpu::BindingType::UniformBuffer { dynamic: true }, ty: wgpu::BindingType::UniformBuffer {
dynamic: true,
min_binding_size: wgpu::BufferSize::new(
mem::size_of::<Uniforms>() as u64,
),
},
count: None,
}], }],
}); });
@ -94,35 +102,35 @@ impl Pipeline {
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: None,
layout: &constants_layout, layout: &constants_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Buffer { resource: wgpu::BindingResource::Buffer(
buffer: &constants_buffer.raw, constants_buffer
range: 0..std::mem::size_of::<Uniforms>() as u64, .raw
}, .slice(0..std::mem::size_of::<Uniforms>() as u64),
),
}], }],
}); });
let layout = let layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
push_constant_ranges: &[],
bind_group_layouts: &[&constants_layout], bind_group_layouts: &[&constants_layout],
}); });
let vs = include_bytes!("shader/triangle.vert.spv"); let vs_module = device.create_shader_module(wgpu::include_spirv!(
let vs_module = device.create_shader_module( "shader/triangle.vert.spv"
&wgpu::read_spirv(std::io::Cursor::new(&vs[..])) ));
.expect("Read triangle vertex shader as SPIR-V"),
);
let fs = include_bytes!("shader/triangle.frag.spv"); let fs_module = device.create_shader_module(wgpu::include_spirv!(
let fs_module = device.create_shader_module( "shader/triangle.frag.spv"
&wgpu::read_spirv(std::io::Cursor::new(&fs[..])) ));
.expect("Read triangle fragment shader as SPIR-V"),
);
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &layout, label: None,
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -137,6 +145,7 @@ impl Pipeline {
depth_bias: 0, depth_bias: 0,
depth_bias_slope_scale: 0.0, depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0, depth_bias_clamp: 0.0,
..Default::default()
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -204,6 +213,7 @@ impl Pipeline {
pub fn draw( pub fn draw(
&mut self, &mut self,
device: &wgpu::Device, device: &wgpu::Device,
staging_belt: &mut wgpu::util::StagingBelt,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView, target: &wgpu::TextureView,
target_width: u32, target_width: u32,
@ -236,12 +246,13 @@ impl Pipeline {
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: None,
layout: &self.constants_layout, layout: &self.constants_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Buffer { resource: wgpu::BindingResource::Buffer(
buffer: &self.uniforms_buffer.raw, self.uniforms_buffer.raw.slice(
range: 0..std::mem::size_of::<Uniforms>() as u64, 0..std::mem::size_of::<Uniforms>() as u64,
}, ),
),
}], }],
}); });
} }
@ -261,65 +272,85 @@ impl Pipeline {
* Transformation::translate(mesh.origin.x, mesh.origin.y)) * Transformation::translate(mesh.origin.x, mesh.origin.y))
.into(); .into();
let vertex_buffer = device.create_buffer_with_data( let vertices = bytemuck::cast_slice(&mesh.buffers.vertices);
bytemuck::cast_slice(&mesh.buffers.vertices), let indices = bytemuck::cast_slice(&mesh.buffers.indices);
wgpu::BufferUsage::COPY_SRC,
);
let index_buffer = device.create_buffer_with_data( if let Some(vertices_size) =
mesh.buffers.indices.as_bytes(), wgpu::BufferSize::new(vertices.len() as u64)
wgpu::BufferUsage::COPY_SRC, {
); if let Some(indices_size) =
wgpu::BufferSize::new(indices.len() as u64)
{
{
let mut vertex_buffer = staging_belt.write_buffer(
encoder,
&self.vertex_buffer.raw,
(std::mem::size_of::<Vertex2D>() * last_vertex)
as u64,
vertices_size,
device,
);
encoder.copy_buffer_to_buffer( vertex_buffer.copy_from_slice(vertices);
&vertex_buffer, }
0,
&self.vertex_buffer.raw,
(std::mem::size_of::<Vertex2D>() * last_vertex) as u64,
(std::mem::size_of::<Vertex2D>() * mesh.buffers.vertices.len())
as u64,
);
encoder.copy_buffer_to_buffer( {
&index_buffer, let mut index_buffer = staging_belt.write_buffer(
0, encoder,
&self.index_buffer.raw, &self.index_buffer.raw,
(std::mem::size_of::<u32>() * last_index) as u64, (std::mem::size_of::<u32>() * last_index) as u64,
(std::mem::size_of::<u32>() * mesh.buffers.indices.len()) indices_size,
as u64, device,
); );
uniforms.push(transform); index_buffer.copy_from_slice(indices);
offsets.push(( }
last_vertex as u64,
last_index as u64,
mesh.buffers.indices.len(),
));
last_vertex += mesh.buffers.vertices.len(); uniforms.push(transform);
last_index += mesh.buffers.indices.len(); offsets.push((
last_vertex as u64,
last_index as u64,
mesh.buffers.indices.len(),
));
last_vertex += mesh.buffers.vertices.len();
last_index += mesh.buffers.indices.len();
}
}
} }
let uniforms_buffer = device.create_buffer_with_data( let uniforms = uniforms.as_bytes();
uniforms.as_bytes(),
wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( if let Some(uniforms_size) =
&uniforms_buffer, wgpu::BufferSize::new(uniforms.len() as u64)
0, {
&self.uniforms_buffer.raw, let mut uniforms_buffer = staging_belt.write_buffer(
0, encoder,
(std::mem::size_of::<Uniforms>() * uniforms.len()) as u64, &self.uniforms_buffer.raw,
); 0,
uniforms_size,
device,
);
uniforms_buffer.copy_from_slice(uniforms);
}
{ {
let (attachment, resolve_target, load_op) = let (attachment, resolve_target, load) =
if let Some(blit) = &mut self.blit { if let Some(blit) = &mut self.blit {
let (attachment, resolve_target) = let (attachment, resolve_target) =
blit.targets(device, target_width, target_height); blit.targets(device, target_width, target_height);
(attachment, Some(resolve_target), wgpu::LoadOp::Clear) (
attachment,
Some(resolve_target),
wgpu::LoadOp::Clear(wgpu::Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
}),
)
} else { } else {
(target, None, wgpu::LoadOp::Load) (target, None, wgpu::LoadOp::Load)
}; };
@ -330,14 +361,7 @@ impl Pipeline {
wgpu::RenderPassColorAttachmentDescriptor { wgpu::RenderPassColorAttachmentDescriptor {
attachment, attachment,
resolve_target, resolve_target,
load_op, ops: wgpu::Operations { load, store: true },
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color {
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
},
}, },
], ],
depth_stencil_attachment: None, depth_stencil_attachment: None,
@ -363,20 +387,17 @@ impl Pipeline {
&[(std::mem::size_of::<Uniforms>() * i) as u32], &[(std::mem::size_of::<Uniforms>() * i) as u32],
); );
render_pass.set_index_buffer( render_pass.set_index_buffer(self.index_buffer.raw.slice(..));
&self.index_buffer.raw,
index_offset * std::mem::size_of::<u32>() as u64,
0,
);
render_pass.set_vertex_buffer( render_pass
0, .set_vertex_buffer(0, self.vertex_buffer.raw.slice(..));
&self.vertex_buffer.raw,
vertex_offset * std::mem::size_of::<Vertex2D>() as u64,
0,
);
render_pass.draw_indexed(0..indices as u32, 0, 0..1); render_pass.draw_indexed(
index_offset as u32
..(index_offset as usize + indices) as u32,
vertex_offset as i32,
0..1,
);
} }
} }

View File

@ -23,18 +23,17 @@ impl Blit {
mag_filter: wgpu::FilterMode::Linear, mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear,
lod_min_clamp: -100.0, ..Default::default()
lod_max_clamp: 100.0,
compare: wgpu::CompareFunction::Always,
}); });
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: None,
bindings: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler { comparison: false }, ty: wgpu::BindingType::Sampler { comparison: false },
count: None,
}], }],
}); });
@ -42,7 +41,7 @@ impl Blit {
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Sampler(&sampler), resource: wgpu::BindingResource::Sampler(&sampler),
}], }],
@ -51,7 +50,7 @@ impl Blit {
let texture_layout = let texture_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: None,
bindings: &[wgpu::BindGroupLayoutEntry { entries: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::SampledTexture { ty: wgpu::BindingType::SampledTexture {
@ -59,29 +58,29 @@ impl Blit {
component_type: wgpu::TextureComponentType::Float, component_type: wgpu::TextureComponentType::Float,
multisampled: false, multisampled: false,
}, },
count: None,
}], }],
}); });
let layout = let layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
push_constant_ranges: &[],
bind_group_layouts: &[&constant_layout, &texture_layout], bind_group_layouts: &[&constant_layout, &texture_layout],
}); });
let vs = include_bytes!("../shader/blit.vert.spv"); let vs_module = device.create_shader_module(wgpu::include_spirv!(
let vs_module = device.create_shader_module( "../shader/blit.vert.spv"
&wgpu::read_spirv(std::io::Cursor::new(&vs[..])) ));
.expect("Read blit vertex shader as SPIR-V"),
);
let fs = include_bytes!("../shader/blit.frag.spv"); let fs_module = device.create_shader_module(wgpu::include_spirv!(
let fs_module = device.create_shader_module( "../shader/blit.frag.spv"
&wgpu::read_spirv(std::io::Cursor::new(&fs[..])) ));
.expect("Read blit fragment shader as SPIR-V"),
);
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &layout, label: None,
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -96,6 +95,7 @@ impl Blit {
depth_bias: 0, depth_bias: 0,
depth_bias_slope_scale: 0.0, depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0, depth_bias_clamp: 0.0,
..Default::default()
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -179,13 +179,9 @@ impl Blit {
wgpu::RenderPassColorAttachmentDescriptor { wgpu::RenderPassColorAttachmentDescriptor {
attachment: target, attachment: target,
resolve_target: None, resolve_target: None,
load_op: wgpu::LoadOp::Load, ops: wgpu::Operations {
store_op: wgpu::StoreOp::Store, load: wgpu::LoadOp::Load,
clear_color: wgpu::Color { store: true,
r: 0.0,
g: 0.0,
b: 0.0,
a: 0.0,
}, },
}, },
], ],
@ -230,7 +226,6 @@ impl Targets {
let attachment = device.create_texture(&wgpu::TextureDescriptor { let attachment = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: None,
size: extent, size: extent,
array_layer_count: 1,
mip_level_count: 1, mip_level_count: 1,
sample_count, sample_count,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
@ -241,7 +236,6 @@ impl Targets {
let resolve = device.create_texture(&wgpu::TextureDescriptor { let resolve = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: None,
size: extent, size: extent,
array_layer_count: 1,
mip_level_count: 1, mip_level_count: 1,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
@ -250,13 +244,16 @@ impl Targets {
| wgpu::TextureUsage::SAMPLED, | wgpu::TextureUsage::SAMPLED,
}); });
let attachment = attachment.create_default_view(); let attachment =
let resolve = resolve.create_default_view(); attachment.create_view(&wgpu::TextureViewDescriptor::default());
let resolve =
resolve.create_view(&wgpu::TextureViewDescriptor::default());
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: None,
layout: texture_layout, layout: texture_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::TextureView(&resolve), resource: wgpu::BindingResource::TextureView(&resolve),
}], }],

View File

@ -1,18 +1,24 @@
use crate::{Backend, Color, Renderer, Settings}; use crate::{Backend, Color, Renderer, Settings};
use futures::task::SpawnExt;
use iced_graphics::Viewport; use iced_graphics::Viewport;
use iced_native::{futures, mouse}; use iced_native::{futures, mouse};
use raw_window_handle::HasRawWindowHandle; use raw_window_handle::HasRawWindowHandle;
/// A window graphics backend for iced powered by `wgpu`. /// A window graphics backend for iced powered by `wgpu`.
#[derive(Debug)] #[allow(missing_debug_implementations)]
pub struct Compositor { pub struct Compositor {
settings: Settings, settings: Settings,
instance: wgpu::Instance,
device: wgpu::Device, device: wgpu::Device,
queue: wgpu::Queue, queue: wgpu::Queue,
staging_belt: wgpu::util::StagingBelt,
local_pool: futures::executor::LocalPool,
} }
impl Compositor { impl Compositor {
const CHUNK_SIZE: u64 = 10 * 1024;
/// Requests a new [`Compositor`] with the given [`Settings`]. /// Requests a new [`Compositor`] with the given [`Settings`].
/// ///
/// Returns `None` if no compatible graphics adapter could be found. /// Returns `None` if no compatible graphics adapter could be found.
@ -20,32 +26,44 @@ impl Compositor {
/// [`Compositor`]: struct.Compositor.html /// [`Compositor`]: struct.Compositor.html
/// [`Settings`]: struct.Settings.html /// [`Settings`]: struct.Settings.html
pub async fn request(settings: Settings) -> Option<Self> { pub async fn request(settings: Settings) -> Option<Self> {
let adapter = wgpu::Adapter::request( let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
&wgpu::RequestAdapterOptions {
let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: if settings.antialiasing.is_none() { power_preference: if settings.antialiasing.is_none() {
wgpu::PowerPreference::Default wgpu::PowerPreference::Default
} else { } else {
wgpu::PowerPreference::HighPerformance wgpu::PowerPreference::HighPerformance
}, },
compatible_surface: None, compatible_surface: None,
}, })
wgpu::BackendBit::PRIMARY, .await?;
)
.await?;
let (device, queue) = adapter let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor { .request_device(
extensions: wgpu::Extensions { &wgpu::DeviceDescriptor {
anisotropic_filtering: false, features: wgpu::Features::empty(),
limits: wgpu::Limits {
max_bind_groups: 2,
..wgpu::Limits::default()
},
shader_validation: false,
}, },
limits: wgpu::Limits { max_bind_groups: 2 }, None,
}) )
.await; .await
.ok()?;
let staging_belt = wgpu::util::StagingBelt::new(Self::CHUNK_SIZE);
let local_pool = futures::executor::LocalPool::new();
Some(Compositor { Some(Compositor {
instance,
settings, settings,
device, device,
queue, queue,
staging_belt,
local_pool,
}) })
} }
@ -77,7 +95,10 @@ impl iced_graphics::window::Compositor for Compositor {
&mut self, &mut self,
window: &W, window: &W,
) -> wgpu::Surface { ) -> wgpu::Surface {
wgpu::Surface::create(window) #[allow(unsafe_code)]
unsafe {
self.instance.create_surface(window)
}
} }
fn create_swap_chain( fn create_swap_chain(
@ -107,7 +128,7 @@ impl iced_graphics::window::Compositor for Compositor {
output: &<Self::Renderer as iced_native::Renderer>::Output, output: &<Self::Renderer as iced_native::Renderer>::Output,
overlay: &[T], overlay: &[T],
) -> mouse::Interaction { ) -> mouse::Interaction {
let frame = swap_chain.get_next_texture().expect("Next frame"); let frame = swap_chain.get_current_frame().expect("Next frame");
let mut encoder = self.device.create_command_encoder( let mut encoder = self.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None }, &wgpu::CommandEncoderDescriptor { label: None },
@ -115,19 +136,20 @@ impl iced_graphics::window::Compositor for Compositor {
let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: &frame.view, attachment: &frame.output.view,
resolve_target: None, resolve_target: None,
load_op: wgpu::LoadOp::Clear, ops: wgpu::Operations {
store_op: wgpu::StoreOp::Store, load: wgpu::LoadOp::Clear({
clear_color: { let [r, g, b, a] = background_color.into_linear();
let [r, g, b, a] = background_color.into_linear();
wgpu::Color { wgpu::Color {
r: f64::from(r), r: f64::from(r),
g: f64::from(g), g: f64::from(g),
b: f64::from(b), b: f64::from(b),
a: f64::from(a), a: f64::from(a),
} }
}),
store: true,
}, },
}], }],
depth_stencil_attachment: None, depth_stencil_attachment: None,
@ -135,14 +157,25 @@ impl iced_graphics::window::Compositor for Compositor {
let mouse_interaction = renderer.backend_mut().draw( let mouse_interaction = renderer.backend_mut().draw(
&mut self.device, &mut self.device,
&mut self.staging_belt,
&mut encoder, &mut encoder,
&frame.view, &frame.output.view,
viewport, viewport,
output, output,
overlay, overlay,
); );
self.queue.submit(&[encoder.finish()]); // Submit work
self.staging_belt.finish();
self.queue.submit(Some(encoder.finish()));
// Recall staging buffers
self.local_pool
.spawner()
.spawn(self.staging_belt.recall())
.expect("Recall staging belt");
self.local_pool.run_until_stalled();
mouse_interaction mouse_interaction
} }