Merge pull request #269 from hecrj/update-wgpu

Update `wgpu` to `0.5` in `iced_wgpu`
This commit is contained in:
Héctor Ramón 2020-04-16 04:59:56 +02:00 committed by GitHub
commit 99e020c7b5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 314 additions and 269 deletions

View File

@ -7,7 +7,9 @@ use scene::Scene;
use iced_wgpu::{ use iced_wgpu::{
wgpu, window::SwapChain, Primitive, Renderer, Settings, Target, wgpu, window::SwapChain, Primitive, Renderer, Settings, Target,
}; };
use iced_winit::{winit, Cache, Clipboard, MouseCursor, Size, UserInterface}; use iced_winit::{
futures, winit, Cache, Clipboard, MouseCursor, Size, UserInterface,
};
use winit::{ use winit::{
event::{Event, ModifiersState, WindowEvent}, event::{Event, ModifiersState, WindowEvent},
@ -25,21 +27,29 @@ pub fn main() {
let mut modifiers = ModifiersState::default(); let mut modifiers = ModifiersState::default();
// Initialize WGPU // Initialize WGPU
let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default,
backends: wgpu::BackendBit::PRIMARY,
})
.expect("Request adapter");
let (mut device, mut queue) =
adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
limits: wgpu::Limits::default(),
});
let surface = wgpu::Surface::create(&window); let surface = wgpu::Surface::create(&window);
let (mut device, queue) = futures::executor::block_on(async {
let adapter = wgpu::Adapter::request(
&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default,
compatible_surface: Some(&surface),
},
wgpu::BackendBit::PRIMARY,
)
.await
.expect("Request adapter");
adapter
.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
limits: wgpu::Limits::default(),
})
.await
});
let format = wgpu::TextureFormat::Bgra8UnormSrgb; let format = wgpu::TextureFormat::Bgra8UnormSrgb;
let mut swap_chain = { let mut swap_chain = {
@ -168,10 +178,11 @@ pub fn main() {
); );
} }
let (frame, viewport) = swap_chain.next_frame(); let (frame, viewport) =
swap_chain.next_frame().expect("Next frame");
let mut encoder = device.create_command_encoder( let mut encoder = device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { todo: 0 }, &wgpu::CommandEncoderDescriptor { label: None },
); );
// We draw the scene first // We draw the scene first

View File

@ -69,10 +69,12 @@ fn build_pipeline(
let bind_group_layout = let bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None,
bindings: &[], bindings: &[],
}); });
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &bind_group_layout, layout: &bind_group_layout,
bindings: &[], bindings: &[],
}); });
@ -108,8 +110,10 @@ fn build_pipeline(
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}], }],
depth_stencil_state: None, depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16, vertex_state: wgpu::VertexStateDescriptor {
vertex_buffers: &[], index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[],
},
sample_count: 1, sample_count: 1,
sample_mask: !0, sample_mask: !0,
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,

View File

@ -12,8 +12,9 @@ svg = ["resvg"]
canvas = ["lyon"] canvas = ["lyon"]
[dependencies] [dependencies]
wgpu = "0.4" wgpu = "0.5"
wgpu_glyph = "0.7" wgpu_glyph = "0.8"
zerocopy = "0.3"
glyph_brush = "0.6" glyph_brush = "0.6"
raw-window-handle = "0.3" raw-window-handle = "0.3"
glam = "0.8" glam = "0.8"

View File

@ -12,6 +12,7 @@ use atlas::Atlas;
use iced_native::Rectangle; use iced_native::Rectangle;
use std::cell::RefCell; use std::cell::RefCell;
use std::mem; use std::mem;
use zerocopy::AsBytes;
#[cfg(feature = "image")] #[cfg(feature = "image")]
use iced_native::image; use iced_native::image;
@ -49,21 +50,22 @@ impl Pipeline {
mipmap_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear,
lod_min_clamp: -100.0, lod_min_clamp: -100.0,
lod_max_clamp: 100.0, lod_max_clamp: 100.0,
compare_function: wgpu::CompareFunction::Always, 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,
bindings: &[ bindings: &[
wgpu::BindGroupLayoutBinding { 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 },
}, },
wgpu::BindGroupLayoutBinding { wgpu::BindGroupLayoutEntry {
binding: 1, binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler, ty: wgpu::BindingType::Sampler { comparison: false },
}, },
], ],
}); });
@ -72,15 +74,14 @@ impl Pipeline {
transform: Transformation::identity().into(), transform: Transformation::identity().into(),
}; };
let uniforms_buffer = device let uniforms_buffer = device.create_buffer_with_data(
.create_buffer_mapped( uniforms.as_bytes(),
1, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, );
)
.fill_from_slice(&[uniforms]);
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[ bindings: &[
wgpu::Binding { wgpu::Binding {
@ -99,12 +100,14 @@ impl Pipeline {
let texture_layout = let texture_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding { label: None,
bindings: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::SampledTexture { ty: wgpu::BindingType::SampledTexture {
multisampled: false,
dimension: wgpu::TextureViewDimension::D2, dimension: wgpu::TextureViewDimension::D2,
component_type: wgpu::TextureComponentType::Float,
multisampled: false,
}, },
}], }],
}); });
@ -160,63 +163,68 @@ impl Pipeline {
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}], }],
depth_stencil_state: None, depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16, vertex_state: wgpu::VertexStateDescriptor {
vertex_buffers: &[ index_format: wgpu::IndexFormat::Uint16,
wgpu::VertexBufferDescriptor { vertex_buffers: &[
stride: mem::size_of::<Vertex>() as u64, wgpu::VertexBufferDescriptor {
step_mode: wgpu::InputStepMode::Vertex, stride: mem::size_of::<Vertex>() as u64,
attributes: &[wgpu::VertexAttributeDescriptor { step_mode: wgpu::InputStepMode::Vertex,
shader_location: 0, attributes: &[wgpu::VertexAttributeDescriptor {
format: wgpu::VertexFormat::Float2, shader_location: 0,
offset: 0,
}],
},
wgpu::VertexBufferDescriptor {
stride: mem::size_of::<Instance>() as u64,
step_mode: wgpu::InputStepMode::Instance,
attributes: &[
wgpu::VertexAttributeDescriptor {
shader_location: 1,
format: wgpu::VertexFormat::Float2, format: wgpu::VertexFormat::Float2,
offset: 0, offset: 0,
}, }],
wgpu::VertexAttributeDescriptor { },
shader_location: 2, wgpu::VertexBufferDescriptor {
format: wgpu::VertexFormat::Float2, stride: mem::size_of::<Instance>() as u64,
offset: 4 * 2, step_mode: wgpu::InputStepMode::Instance,
}, attributes: &[
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 3, shader_location: 1,
format: wgpu::VertexFormat::Float2, format: wgpu::VertexFormat::Float2,
offset: 4 * 4, offset: 0,
}, },
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 4, shader_location: 2,
format: wgpu::VertexFormat::Float2, format: wgpu::VertexFormat::Float2,
offset: 4 * 6, offset: 4 * 2,
}, },
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 5, shader_location: 3,
format: wgpu::VertexFormat::Uint, format: wgpu::VertexFormat::Float2,
offset: 4 * 8, offset: 4 * 4,
}, },
], wgpu::VertexAttributeDescriptor {
}, shader_location: 4,
], format: wgpu::VertexFormat::Float2,
offset: 4 * 6,
},
wgpu::VertexAttributeDescriptor {
shader_location: 5,
format: wgpu::VertexFormat::Uint,
offset: 4 * 8,
},
],
},
],
},
sample_count: 1, sample_count: 1,
sample_mask: !0, sample_mask: !0,
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,
}); });
let vertices = device let vertices = device.create_buffer_with_data(
.create_buffer_mapped(QUAD_VERTS.len(), wgpu::BufferUsage::VERTEX) QUAD_VERTS.as_bytes(),
.fill_from_slice(&QUAD_VERTS); wgpu::BufferUsage::VERTEX,
);
let indices = device let indices = device.create_buffer_with_data(
.create_buffer_mapped(QUAD_INDICES.len(), wgpu::BufferUsage::INDEX) QUAD_INDICES.as_bytes(),
.fill_from_slice(&QUAD_INDICES); wgpu::BufferUsage::INDEX,
);
let instances = device.create_buffer(&wgpu::BufferDescriptor { let instances = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: mem::size_of::<Instance>() as u64 * Instance::MAX as u64, size: mem::size_of::<Instance>() as u64 * Instance::MAX as u64,
usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
}); });
@ -224,6 +232,7 @@ impl Pipeline {
let texture_atlas = Atlas::new(device); let texture_atlas = Atlas::new(device);
let texture = device.create_bind_group(&wgpu::BindGroupDescriptor { let texture = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &texture_layout, layout: &texture_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,
@ -327,6 +336,7 @@ impl Pipeline {
self.texture = self.texture =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &self.texture_layout, layout: &self.texture_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,
@ -339,11 +349,13 @@ impl Pipeline {
self.texture_version = texture_version; self.texture_version = texture_version;
} }
let uniforms_buffer = device let uniforms_buffer = device.create_buffer_with_data(
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC) Uniforms {
.fill_from_slice(&[Uniforms {
transform: transformation.into(), transform: transformation.into(),
}]); }
.as_bytes(),
wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&uniforms_buffer, &uniforms_buffer,
@ -353,9 +365,10 @@ impl Pipeline {
std::mem::size_of::<Uniforms>() as u64, std::mem::size_of::<Uniforms>() as u64,
); );
let instances_buffer = device let instances_buffer = device.create_buffer_with_data(
.create_buffer_mapped(instances.len(), wgpu::BufferUsage::COPY_SRC) instances.as_bytes(),
.fill_from_slice(&instances); wgpu::BufferUsage::COPY_SRC,
);
let mut i = 0; let mut i = 0;
let total = instances.len(); let total = instances.len();
@ -394,11 +407,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_bind_group(1, &self.texture, &[]); render_pass.set_bind_group(1, &self.texture, &[]);
render_pass.set_index_buffer(&self.indices, 0); render_pass.set_index_buffer(&self.indices, 0, 0);
render_pass.set_vertex_buffers( render_pass.set_vertex_buffer(0, &self.vertices, 0, 0);
0, render_pass.set_vertex_buffer(1, &self.instances, 0, 0);
&[(&self.vertices, 0), (&self.instances, 0)],
);
render_pass.set_scissor_rect( render_pass.set_scissor_rect(
bounds.x, bounds.x,
@ -441,7 +452,7 @@ pub enum Handle {
} }
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy)] #[derive(Clone, Copy, AsBytes)]
pub struct Vertex { pub struct Vertex {
_position: [f32; 2], _position: [f32; 2],
} }
@ -464,7 +475,7 @@ const QUAD_VERTS: [Vertex; 4] = [
]; ];
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsBytes)]
struct Instance { struct Instance {
_position: [f32; 2], _position: [f32; 2],
_size: [f32; 2], _size: [f32; 2],
@ -478,7 +489,7 @@ impl Instance {
} }
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsBytes)]
struct Uniforms { struct Uniforms {
transform: [f32; 16], transform: [f32; 16],
} }

View File

@ -28,6 +28,7 @@ impl Atlas {
}; };
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: extent, size: extent,
array_layer_count: 2, array_layer_count: 2,
mip_level_count: 1, mip_level_count: 1,
@ -56,17 +57,14 @@ impl Atlas {
self.layers.len() self.layers.len()
} }
pub fn upload<C>( pub fn upload(
&mut self, &mut self,
width: u32, width: u32,
height: u32, height: u32,
data: &[C], data: &[u8],
device: &wgpu::Device, device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
) -> Option<Entry> ) -> Option<Entry> {
where
C: Copy + 'static,
{
let entry = { let entry = {
let current_size = self.layers.len(); let current_size = self.layers.len();
let entry = self.allocate(width, height)?; let entry = self.allocate(width, height)?;
@ -80,9 +78,8 @@ impl Atlas {
log::info!("Allocated atlas entry: {:?}", entry); log::info!("Allocated atlas entry: {:?}", entry);
let buffer = device let buffer =
.create_buffer_mapped(data.len(), wgpu::BufferUsage::COPY_SRC) device.create_buffer_with_data(data, wgpu::BufferUsage::COPY_SRC);
.fill_from_slice(data);
match &entry { match &entry {
Entry::Contiguous(allocation) => { Entry::Contiguous(allocation) => {
@ -274,18 +271,14 @@ impl Atlas {
wgpu::BufferCopyView { wgpu::BufferCopyView {
buffer, buffer,
offset: offset as u64, offset: offset as u64,
row_pitch: 4 * image_width, bytes_per_row: 4 * image_width,
image_height, rows_per_image: image_height,
}, },
wgpu::TextureCopyView { wgpu::TextureCopyView {
texture: &self.texture, texture: &self.texture,
array_layer: layer as u32, array_layer: layer as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { origin: wgpu::Origin3d { x, y, z: 0 },
x: x as f32,
y: y as f32,
z: 0.0,
},
}, },
extent, extent,
); );
@ -302,6 +295,7 @@ impl Atlas {
} }
let new_texture = device.create_texture(&wgpu::TextureDescriptor { let new_texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { size: wgpu::Extent3d {
width: SIZE, width: SIZE,
height: SIZE, height: SIZE,
@ -331,21 +325,13 @@ impl Atlas {
texture: &self.texture, texture: &self.texture,
array_layer: i as u32, array_layer: i as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { origin: wgpu::Origin3d { x: 0, y: 0, z: 0 },
x: 0.0,
y: 0.0,
z: 0.0,
},
}, },
wgpu::TextureCopyView { wgpu::TextureCopyView {
texture: &new_texture, texture: &new_texture,
array_layer: i as u32, array_layer: i as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { origin: wgpu::Origin3d { x: 0, y: 0, z: 0 },
x: 0.0,
y: 0.0,
z: 0.0,
},
}, },
wgpu::Extent3d { wgpu::Extent3d {
width: SIZE, width: SIZE,

View File

@ -2,6 +2,8 @@ use crate::image::atlas::{self, Atlas};
use iced_native::svg; use iced_native::svg;
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet};
use zerocopy::AsBytes;
pub enum Svg { pub enum Svg {
Loaded(resvg::usvg::Tree), Loaded(resvg::usvg::Tree),
NotFound, NotFound,
@ -117,7 +119,7 @@ impl Cache {
let allocation = texture_atlas.upload( let allocation = texture_atlas.upload(
width, width,
height, height,
canvas.get_data(), canvas.get_data().as_bytes(),
device, device,
encoder, encoder,
)?; )?;

View File

@ -2,6 +2,7 @@ use crate::Transformation;
use iced_native::Rectangle; use iced_native::Rectangle;
use std::mem; use std::mem;
use zerocopy::AsBytes;
#[derive(Debug)] #[derive(Debug)]
pub struct Pipeline { pub struct Pipeline {
@ -20,21 +21,21 @@ impl Pipeline {
) -> Pipeline { ) -> Pipeline {
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding { label: None,
bindings: &[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 },
}], }],
}); });
let constants_buffer = device let constants_buffer = device.create_buffer_with_data(
.create_buffer_mapped( Uniforms::default().as_bytes(),
1, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, );
)
.fill_from_slice(&[Uniforms::default()]);
let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { let constants = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,
@ -96,68 +97,73 @@ impl Pipeline {
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}], }],
depth_stencil_state: None, depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16, vertex_state: wgpu::VertexStateDescriptor {
vertex_buffers: &[ index_format: wgpu::IndexFormat::Uint16,
wgpu::VertexBufferDescriptor { vertex_buffers: &[
stride: mem::size_of::<Vertex>() as u64, wgpu::VertexBufferDescriptor {
step_mode: wgpu::InputStepMode::Vertex, stride: mem::size_of::<Vertex>() as u64,
attributes: &[wgpu::VertexAttributeDescriptor { step_mode: wgpu::InputStepMode::Vertex,
shader_location: 0, attributes: &[wgpu::VertexAttributeDescriptor {
format: wgpu::VertexFormat::Float2, shader_location: 0,
offset: 0,
}],
},
wgpu::VertexBufferDescriptor {
stride: mem::size_of::<Quad>() as u64,
step_mode: wgpu::InputStepMode::Instance,
attributes: &[
wgpu::VertexAttributeDescriptor {
shader_location: 1,
format: wgpu::VertexFormat::Float2, format: wgpu::VertexFormat::Float2,
offset: 0, offset: 0,
}, }],
wgpu::VertexAttributeDescriptor { },
shader_location: 2, wgpu::VertexBufferDescriptor {
format: wgpu::VertexFormat::Float2, stride: mem::size_of::<Quad>() as u64,
offset: 4 * 2, step_mode: wgpu::InputStepMode::Instance,
}, attributes: &[
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 3, shader_location: 1,
format: wgpu::VertexFormat::Float4, format: wgpu::VertexFormat::Float2,
offset: 4 * (2 + 2), offset: 0,
}, },
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 4, shader_location: 2,
format: wgpu::VertexFormat::Float4, format: wgpu::VertexFormat::Float2,
offset: 4 * (2 + 2 + 4), offset: 4 * 2,
}, },
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 5, shader_location: 3,
format: wgpu::VertexFormat::Float, format: wgpu::VertexFormat::Float4,
offset: 4 * (2 + 2 + 4 + 4), offset: 4 * (2 + 2),
}, },
wgpu::VertexAttributeDescriptor { wgpu::VertexAttributeDescriptor {
shader_location: 6, shader_location: 4,
format: wgpu::VertexFormat::Float, format: wgpu::VertexFormat::Float4,
offset: 4 * (2 + 2 + 4 + 4 + 1), offset: 4 * (2 + 2 + 4),
}, },
], wgpu::VertexAttributeDescriptor {
}, shader_location: 5,
], format: wgpu::VertexFormat::Float,
offset: 4 * (2 + 2 + 4 + 4),
},
wgpu::VertexAttributeDescriptor {
shader_location: 6,
format: wgpu::VertexFormat::Float,
offset: 4 * (2 + 2 + 4 + 4 + 1),
},
],
},
],
},
sample_count: 1, sample_count: 1,
sample_mask: !0, sample_mask: !0,
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,
}); });
let vertices = device let vertices = device.create_buffer_with_data(
.create_buffer_mapped(QUAD_VERTS.len(), wgpu::BufferUsage::VERTEX) QUAD_VERTS.as_bytes(),
.fill_from_slice(&QUAD_VERTS); wgpu::BufferUsage::VERTEX,
);
let indices = device let indices = device.create_buffer_with_data(
.create_buffer_mapped(QUAD_INDICES.len(), wgpu::BufferUsage::INDEX) QUAD_INDICES.as_bytes(),
.fill_from_slice(&QUAD_INDICES); wgpu::BufferUsage::INDEX,
);
let instances = device.create_buffer(&wgpu::BufferDescriptor { let instances = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: mem::size_of::<Quad>() as u64 * Quad::MAX as u64, size: mem::size_of::<Quad>() as u64 * Quad::MAX as u64,
usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
}); });
@ -184,9 +190,10 @@ impl Pipeline {
) { ) {
let uniforms = Uniforms::new(transformation, scale); let uniforms = Uniforms::new(transformation, scale);
let constants_buffer = device let constants_buffer = device.create_buffer_with_data(
.create_buffer_mapped(1, wgpu::BufferUsage::COPY_SRC) uniforms.as_bytes(),
.fill_from_slice(&[uniforms]); wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&constants_buffer, &constants_buffer,
@ -203,9 +210,10 @@ impl Pipeline {
let end = (i + Quad::MAX).min(total); let end = (i + Quad::MAX).min(total);
let amount = end - i; let amount = end - i;
let instance_buffer = device let instance_buffer = device.create_buffer_with_data(
.create_buffer_mapped(amount, wgpu::BufferUsage::COPY_SRC) &instances[i..end].as_bytes(),
.fill_from_slice(&instances[i..end]); wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&instance_buffer, &instance_buffer,
@ -237,11 +245,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); render_pass.set_index_buffer(&self.indices, 0, 0);
render_pass.set_vertex_buffers( render_pass.set_vertex_buffer(0, &self.vertices, 0, 0);
0, render_pass.set_vertex_buffer(1, &self.instances, 0, 0);
&[(&self.vertices, 0), (&self.instances, 0)],
);
render_pass.set_scissor_rect( render_pass.set_scissor_rect(
bounds.x, bounds.x,
bounds.y, bounds.y,
@ -263,7 +269,7 @@ impl Pipeline {
} }
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy)] #[derive(Clone, Copy, AsBytes)]
pub struct Vertex { pub struct Vertex {
_position: [f32; 2], _position: [f32; 2],
} }
@ -286,7 +292,7 @@ const QUAD_VERTS: [Vertex; 4] = [
]; ];
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsBytes)]
pub struct Quad { pub struct Quad {
pub position: [f32; 2], pub position: [f32; 2],
pub scale: [f32; 2], pub scale: [f32; 2],
@ -301,7 +307,7 @@ impl Quad {
} }
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsBytes)]
struct Uniforms { struct Uniforms {
transform: [f32; 16], transform: [f32; 16],
scale: f32, scale: f32,

View File

@ -16,9 +16,9 @@ impl Transformation {
pub fn orthographic(width: u32, height: u32) -> Transformation { pub fn orthographic(width: u32, height: u32) -> Transformation {
Transformation(Mat4::from_cols( Transformation(Mat4::from_cols(
Vec4::new(2.0 / width as f32, 0.0, 0.0, 0.0), Vec4::new(2.0 / width as f32, 0.0, 0.0, 0.0),
Vec4::new(0.0, 2.0 / height as f32, 0.0, 0.0), Vec4::new(0.0, -2.0 / height as f32, 0.0, 0.0),
Vec4::new(0.0, 0.0, -1.0, 0.0), Vec4::new(0.0, 0.0, -1.0, 0.0),
Vec4::new(-1.0, -1.0, 0.0, 1.0) Vec4::new(-1.0, 1.0, 0.0, 1.0)
)) ))
} }

View File

@ -2,6 +2,7 @@
use crate::{settings, Transformation}; use crate::{settings, Transformation};
use iced_native::{Point, Rectangle}; use iced_native::{Point, Rectangle};
use std::mem; use std::mem;
use zerocopy::AsBytes;
mod msaa; mod msaa;
@ -34,6 +35,7 @@ impl<T> Buffer<T> {
usage: wgpu::BufferUsage, usage: wgpu::BufferUsage,
) -> Self { ) -> Self {
let raw = device.create_buffer(&wgpu::BufferDescriptor { let raw = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (std::mem::size_of::<T>() * size) as u64, size: (std::mem::size_of::<T>() * size) as u64,
usage, usage,
}); });
@ -49,6 +51,7 @@ impl<T> Buffer<T> {
pub fn ensure_capacity(&mut self, device: &wgpu::Device, size: usize) { pub fn ensure_capacity(&mut self, device: &wgpu::Device, size: usize) {
if self.size < size { if self.size < size {
self.raw = device.create_buffer(&wgpu::BufferDescriptor { self.raw = device.create_buffer(&wgpu::BufferDescriptor {
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,
}); });
@ -66,7 +69,8 @@ impl Pipeline {
) -> Pipeline { ) -> Pipeline {
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding { label: None,
bindings: &[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 },
@ -81,6 +85,7 @@ impl Pipeline {
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,
@ -142,25 +147,27 @@ impl Pipeline {
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}], }],
depth_stencil_state: None, depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint32, vertex_state: wgpu::VertexStateDescriptor {
vertex_buffers: &[wgpu::VertexBufferDescriptor { index_format: wgpu::IndexFormat::Uint32,
stride: mem::size_of::<Vertex2D>() as u64, vertex_buffers: &[wgpu::VertexBufferDescriptor {
step_mode: wgpu::InputStepMode::Vertex, stride: mem::size_of::<Vertex2D>() as u64,
attributes: &[ step_mode: wgpu::InputStepMode::Vertex,
// Position attributes: &[
wgpu::VertexAttributeDescriptor { // Position
shader_location: 0, wgpu::VertexAttributeDescriptor {
format: wgpu::VertexFormat::Float2, shader_location: 0,
offset: 0, format: wgpu::VertexFormat::Float2,
}, offset: 0,
// Color },
wgpu::VertexAttributeDescriptor { // Color
shader_location: 1, wgpu::VertexAttributeDescriptor {
format: wgpu::VertexFormat::Float4, shader_location: 1,
offset: 4 * 2, format: wgpu::VertexFormat::Float4,
}, offset: 4 * 2,
], },
}], ],
}],
},
sample_count: antialiasing sample_count: antialiasing
.map(|a| a.sample_count()) .map(|a| a.sample_count())
.unwrap_or(1), .unwrap_or(1),
@ -230,19 +237,15 @@ impl Pipeline {
.into(), .into(),
}; };
let vertex_buffer = device let vertex_buffer = device.create_buffer_with_data(
.create_buffer_mapped( mesh.vertices.as_bytes(),
mesh.vertices.len(), wgpu::BufferUsage::COPY_SRC,
wgpu::BufferUsage::COPY_SRC, );
)
.fill_from_slice(&mesh.vertices);
let index_buffer = device let index_buffer = device.create_buffer_with_data(
.create_buffer_mapped( mesh.indices.as_bytes(),
mesh.indices.len(), wgpu::BufferUsage::COPY_SRC,
wgpu::BufferUsage::COPY_SRC, );
)
.fill_from_slice(&mesh.indices);
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&vertex_buffer, &vertex_buffer,
@ -271,9 +274,10 @@ impl Pipeline {
last_index += mesh.indices.len(); last_index += mesh.indices.len();
} }
let uniforms_buffer = device let uniforms_buffer = device.create_buffer_with_data(
.create_buffer_mapped(uniforms.len(), wgpu::BufferUsage::COPY_SRC) uniforms.as_bytes(),
.fill_from_slice(&uniforms); wgpu::BufferUsage::COPY_SRC,
);
encoder.copy_buffer_to_buffer( encoder.copy_buffer_to_buffer(
&uniforms_buffer, &uniforms_buffer,
@ -327,20 +331,20 @@ impl Pipeline {
render_pass.set_bind_group( render_pass.set_bind_group(
0, 0,
&self.constants, &self.constants,
&[(std::mem::size_of::<Uniforms>() * i) as u64], &[(std::mem::size_of::<Uniforms>() * i) as u32],
); );
render_pass.set_index_buffer( render_pass.set_index_buffer(
&self.index_buffer.raw, &self.index_buffer.raw,
index_offset * std::mem::size_of::<u32>() as u64, index_offset * std::mem::size_of::<u32>() as u64,
0,
); );
render_pass.set_vertex_buffers( render_pass.set_vertex_buffer(
0,
&self.vertex_buffer.raw,
vertex_offset * std::mem::size_of::<Vertex2D>() as u64,
0, 0,
&[(
&self.vertex_buffer.raw,
vertex_offset * std::mem::size_of::<Vertex2D>() as u64,
)],
); );
render_pass.draw_indexed(0..indices as u32, 0, 0..1); render_pass.draw_indexed(0..indices as u32, 0, 0..1);
@ -354,7 +358,7 @@ impl Pipeline {
} }
#[repr(C)] #[repr(C)]
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy, AsBytes)]
struct Uniforms { struct Uniforms {
transform: [f32; 16], transform: [f32; 16],
} }
@ -369,7 +373,7 @@ impl Default for Uniforms {
/// A two-dimensional vertex with some color in __linear__ RGBA. /// A two-dimensional vertex with some color in __linear__ RGBA.
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug, AsBytes)]
pub struct Vertex2D { pub struct Vertex2D {
/// The vertex position /// The vertex position
pub position: [f32; 2], pub position: [f32; 2],

View File

@ -25,20 +25,22 @@ impl Blit {
mipmap_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear,
lod_min_clamp: -100.0, lod_min_clamp: -100.0,
lod_max_clamp: 100.0, lod_max_clamp: 100.0,
compare_function: wgpu::CompareFunction::Always, compare: wgpu::CompareFunction::Always,
}); });
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding { label: None,
bindings: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler, ty: wgpu::BindingType::Sampler { comparison: false },
}], }],
}); });
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &constant_layout, layout: &constant_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,
@ -48,12 +50,14 @@ impl Blit {
let texture_layout = let texture_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
bindings: &[wgpu::BindGroupLayoutBinding { label: None,
bindings: &[wgpu::BindGroupLayoutEntry {
binding: 0, binding: 0,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::SampledTexture { ty: wgpu::BindingType::SampledTexture {
multisampled: false,
dimension: wgpu::TextureViewDimension::D2, dimension: wgpu::TextureViewDimension::D2,
component_type: wgpu::TextureComponentType::Float,
multisampled: false,
}, },
}], }],
}); });
@ -109,8 +113,10 @@ impl Blit {
write_mask: wgpu::ColorWrite::ALL, write_mask: wgpu::ColorWrite::ALL,
}], }],
depth_stencil_state: None, depth_stencil_state: None,
index_format: wgpu::IndexFormat::Uint16, vertex_state: wgpu::VertexStateDescriptor {
vertex_buffers: &[], index_format: wgpu::IndexFormat::Uint16,
vertex_buffers: &[],
},
sample_count: 1, sample_count: 1,
sample_mask: !0, sample_mask: !0,
alpha_to_coverage_enabled: false, alpha_to_coverage_enabled: false,
@ -222,6 +228,7 @@ impl Targets {
}; };
let attachment = device.create_texture(&wgpu::TextureDescriptor { let attachment = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: extent, size: extent,
array_layer_count: 1, array_layer_count: 1,
mip_level_count: 1, mip_level_count: 1,
@ -232,6 +239,7 @@ impl Targets {
}); });
let resolve = device.create_texture(&wgpu::TextureDescriptor { let resolve = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: extent, size: extent,
array_layer_count: 1, array_layer_count: 1,
mip_level_count: 1, mip_level_count: 1,
@ -246,6 +254,7 @@ impl Targets {
let resolve = resolve.create_default_view(); let resolve = resolve.create_default_view();
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: texture_layout, layout: texture_layout,
bindings: &[wgpu::Binding { bindings: &[wgpu::Binding {
binding: 0, binding: 0,

View File

@ -248,7 +248,7 @@ impl Frame {
.transforms .transforms
.current .current
.raw .raw
.pre_rotate(lyon::math::Angle::radians(-angle)); .pre_rotate(lyon::math::Angle::radians(angle));
self.transforms.current.is_identity = false; self.transforms.current.is_identity = false;
} }

View File

@ -1,6 +1,6 @@
use crate::{window::SwapChain, Renderer, Settings, Target}; use crate::{window::SwapChain, Renderer, Settings, Target};
use iced_native::MouseCursor; use iced_native::{futures, MouseCursor};
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`.
@ -18,23 +18,30 @@ impl iced_native::window::Backend for Backend {
type SwapChain = SwapChain; type SwapChain = SwapChain;
fn new(settings: Self::Settings) -> (Backend, Renderer) { fn new(settings: Self::Settings) -> (Backend, Renderer) {
let adapter = wgpu::Adapter::request(&wgpu::RequestAdapterOptions { let (mut device, queue) = futures::executor::block_on(async {
power_preference: if settings.antialiasing.is_none() { let adapter = wgpu::Adapter::request(
wgpu::PowerPreference::Default &wgpu::RequestAdapterOptions {
} else { power_preference: if settings.antialiasing.is_none() {
wgpu::PowerPreference::HighPerformance wgpu::PowerPreference::Default
}, } else {
backends: wgpu::BackendBit::all(), wgpu::PowerPreference::HighPerformance
}) },
.expect("Request adapter"); compatible_surface: None,
let (mut device, queue) =
adapter.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
}, },
limits: wgpu::Limits { max_bind_groups: 2 }, wgpu::BackendBit::all(),
}); )
.await
.expect("Request adapter");
adapter
.request_device(&wgpu::DeviceDescriptor {
extensions: wgpu::Extensions {
anisotropic_filtering: false,
},
limits: wgpu::Limits { max_bind_groups: 2 },
})
.await
});
let renderer = Renderer::new(&mut device, settings); let renderer = Renderer::new(&mut device, settings);
@ -72,10 +79,10 @@ impl iced_native::window::Backend for Backend {
scale_factor: f64, scale_factor: f64,
overlay: &[T], overlay: &[T],
) -> MouseCursor { ) -> MouseCursor {
let (frame, viewport) = swap_chain.next_frame(); let (frame, viewport) = swap_chain.next_frame().expect("Next frame");
let mut encoder = self.device.create_command_encoder( let mut encoder = self.device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { todo: 0 }, &wgpu::CommandEncoderDescriptor { label: None },
); );
let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {

View File

@ -32,8 +32,12 @@ impl SwapChain {
/// ///
/// [`SwapChain`]: struct.SwapChain.html /// [`SwapChain`]: struct.SwapChain.html
/// [`Viewport`]: ../struct.Viewport.html /// [`Viewport`]: ../struct.Viewport.html
pub fn next_frame(&mut self) -> (wgpu::SwapChainOutput<'_>, &Viewport) { pub fn next_frame(
(self.raw.get_next_texture(), &self.viewport) &mut self,
) -> Result<(wgpu::SwapChainOutput, &Viewport), wgpu::TimeOut> {
let viewport = &self.viewport;
self.raw.get_next_texture().map(|output| (output, viewport))
} }
} }
@ -51,7 +55,7 @@ fn new_swap_chain(
format, format,
width, width,
height, height,
present_mode: wgpu::PresentMode::Vsync, present_mode: wgpu::PresentMode::Mailbox,
}, },
) )
} }