Merge branch 'feature/error-handling' into improvement/viewport-aware-drawing

This commit is contained in:
Héctor Ramón Jiménez 2020-09-08 00:52:01 +02:00
commit 577fe8774c
64 changed files with 1095 additions and 479 deletions

View File

@ -78,6 +78,7 @@ members = [
[dependencies] [dependencies]
iced_core = { version = "0.2", path = "core" } iced_core = { version = "0.2", path = "core" }
iced_futures = { version = "0.1", path = "futures" } iced_futures = { version = "0.1", path = "futures" }
thiserror = "1.0"
[target.'cfg(not(target_arch = "wasm32"))'.dependencies] [target.'cfg(not(target_arch = "wasm32"))'.dependencies]
iced_winit = { version = "0.1", path = "winit" } iced_winit = { version = "0.1", path = "winit" }

View File

@ -13,3 +13,9 @@ impl From<Color> for Background {
Background::Color(color) Background::Color(color)
} }
} }
impl From<Color> for Option<Background> {
fn from(color: Color) -> Self {
Some(Background::from(color))
}
}

View File

@ -3,11 +3,11 @@ use iced::{
button, Align, Button, Column, Element, Length, Sandbox, Settings, Text, button, Align, Button, Column, Element, Length, Sandbox, Settings, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings { Example::run(Settings {
antialiasing: true, antialiasing: true,
..Settings::default() ..Settings::default()
}); })
} }
#[derive(Default)] #[derive(Default)]

View File

@ -4,7 +4,7 @@ use iced::{
Point, Rectangle, Settings, Subscription, Vector, Point, Rectangle, Settings, Subscription, Vector,
}; };
pub fn main() { pub fn main() -> iced::Result {
Clock::run(Settings { Clock::run(Settings {
antialiasing: true, antialiasing: true,
..Settings::default() ..Settings::default()

View File

@ -8,7 +8,7 @@ use palette::{self, Hsl, Limited, Srgb};
use std::marker::PhantomData; use std::marker::PhantomData;
use std::ops::RangeInclusive; use std::ops::RangeInclusive;
pub fn main() { pub fn main() -> iced::Result {
ColorPalette::run(Settings { ColorPalette::run(Settings {
antialiasing: true, antialiasing: true,
..Settings::default() ..Settings::default()

View File

@ -1,6 +1,6 @@
use iced::{button, Align, Button, Column, Element, Sandbox, Settings, Text}; use iced::{button, Align, Button, Column, Element, Sandbox, Settings, Text};
pub fn main() { pub fn main() -> iced::Result {
Counter::run(Settings::default()) Counter::run(Settings::default())
} }

View File

@ -91,7 +91,7 @@ use iced::{
Slider, Text, Slider, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings::default()) Example::run(Settings::default())
} }

View File

@ -5,7 +5,7 @@ use iced::{
mod download; mod download;
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings::default()) Example::run(Settings::default())
} }

View File

@ -3,7 +3,7 @@ use iced::{
Element, Length, Settings, Subscription, Text, Element, Length, Settings, Subscription, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Events::run(Settings::default()) Events::run(Settings::default())
} }

View File

@ -16,7 +16,7 @@ use iced::{
use preset::Preset; use preset::Preset;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
pub fn main() { pub fn main() -> iced::Result {
GameOfLife::run(Settings { GameOfLife::run(Settings {
antialiasing: true, antialiasing: true,
..Settings::default() ..Settings::default()

View File

@ -166,7 +166,7 @@ use iced::{
}; };
use rainbow::Rainbow; use rainbow::Rainbow;
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings::default()) Example::run(Settings::default())
} }

View File

@ -7,6 +7,7 @@ use scene::Scene;
use iced_wgpu::{wgpu, Backend, Renderer, Settings, Viewport}; use iced_wgpu::{wgpu, Backend, Renderer, Settings, Viewport};
use iced_winit::{conversion, futures, program, winit, Debug, Size}; use iced_winit::{conversion, futures, program, winit, Debug, Size};
use futures::task::SpawnExt;
use winit::{ use winit::{
dpi::PhysicalPosition, dpi::PhysicalPosition,
event::{Event, ModifiersState, WindowEvent}, event::{Event, ModifiersState, WindowEvent},
@ -29,26 +30,29 @@ pub fn main() {
let mut modifiers = ModifiersState::default(); let mut modifiers = ModifiersState::default();
// Initialize wgpu // Initialize wgpu
let surface = wgpu::Surface::create(&window); let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY);
let surface = unsafe { instance.create_surface(&window) };
let (mut device, queue) = futures::executor::block_on(async { let (mut device, queue) = futures::executor::block_on(async {
let adapter = wgpu::Adapter::request( let adapter = instance
&wgpu::RequestAdapterOptions { .request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::Default, power_preference: wgpu::PowerPreference::Default,
compatible_surface: Some(&surface), 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 .await
.expect("Request adapter");
adapter
.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::empty(),
limits: wgpu::Limits::default(),
shader_validation: false,
},
None,
)
.await
.expect("Request device")
}); });
let format = wgpu::TextureFormat::Bgra8UnormSrgb; let format = wgpu::TextureFormat::Bgra8UnormSrgb;
@ -69,6 +73,10 @@ pub fn main() {
}; };
let mut resized = false; let mut resized = false;
// Initialize staging belt and local pool
let mut staging_belt = wgpu::util::StagingBelt::new(5 * 1024);
let mut local_pool = futures::executor::LocalPool::new();
// Initialize scene and GUI controls // Initialize scene and GUI controls
let scene = Scene::new(&mut device); let scene = Scene::new(&mut device);
let controls = Controls::new(); let controls = Controls::new();
@ -160,7 +168,7 @@ pub fn main() {
resized = false; resized = false;
} }
let frame = swap_chain.get_next_texture().expect("Next frame"); let frame = swap_chain.get_current_frame().expect("Next frame");
let mut encoder = device.create_command_encoder( let mut encoder = device.create_command_encoder(
&wgpu::CommandEncoderDescriptor { label: None }, &wgpu::CommandEncoderDescriptor { label: None },
@ -171,7 +179,7 @@ pub fn main() {
{ {
// We clear the frame // We clear the frame
let mut render_pass = scene.clear( let mut render_pass = scene.clear(
&frame.view, &frame.output.view,
&mut encoder, &mut encoder,
program.background_color(), program.background_color(),
); );
@ -183,22 +191,32 @@ pub fn main() {
// And then iced on top // And then iced on top
let mouse_interaction = renderer.backend_mut().draw( let mouse_interaction = renderer.backend_mut().draw(
&mut device, &mut device,
&mut staging_belt,
&mut encoder, &mut encoder,
&frame.view, &frame.output.view,
&viewport, &viewport,
state.primitive(), state.primitive(),
&debug.overlay(), &debug.overlay(),
); );
// Then we submit the work // Then we submit the work
queue.submit(&[encoder.finish()]); staging_belt.finish();
queue.submit(Some(encoder.finish()));
// And update the mouse cursor // Update the mouse cursor
window.set_cursor_icon( window.set_cursor_icon(
iced_winit::conversion::mouse_interaction( iced_winit::conversion::mouse_interaction(
mouse_interaction, mouse_interaction,
), ),
); );
// And recall staging buffers
local_pool
.spawner()
.spawn(staging_belt.recall())
.expect("Recall staging buffers");
local_pool.run_until_stalled();
} }
_ => {} _ => {}
} }

View File

@ -22,17 +22,18 @@ impl Scene {
color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor {
attachment: target, attachment: target,
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: r as f64, r: r as f64,
g: g as f64, g: g as f64,
b: b as f64, b: b as f64,
a: a as f64, a: a as f64,
} }
}),
store: true,
}, },
}], }],
depth_stencil_attachment: None, depth_stencil_attachment: None,
@ -46,25 +47,23 @@ impl Scene {
} }
fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline { fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline {
let vs = include_bytes!("shader/vert.spv"); let vs_module =
let fs = include_bytes!("shader/frag.spv"); device.create_shader_module(wgpu::include_spirv!("shader/vert.spv"));
let vs_module = device.create_shader_module( let fs_module =
&wgpu::read_spirv(std::io::Cursor::new(&vs[..])).unwrap(), device.create_shader_module(wgpu::include_spirv!("shader/frag.spv"));
);
let fs_module = device.create_shader_module(
&wgpu::read_spirv(std::io::Cursor::new(&fs[..])).unwrap(),
);
let pipeline_layout = let pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
push_constant_ranges: &[],
bind_group_layouts: &[], bind_group_layouts: &[],
}); });
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &pipeline_layout, label: None,
layout: Some(&pipeline_layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -76,9 +75,7 @@ fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline {
rasterization_state: Some(wgpu::RasterizationStateDescriptor { rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Ccw, front_face: wgpu::FrontFace::Ccw,
cull_mode: wgpu::CullMode::None, cull_mode: wgpu::CullMode::None,
depth_bias: 0, ..Default::default()
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {

View File

@ -4,7 +4,7 @@ use iced::{
Settings, Text, Settings, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings::default()) Example::run(Settings::default())
} }

View File

@ -3,7 +3,7 @@ use iced::{
Sandbox, Scrollable, Settings, Space, Text, Sandbox, Scrollable, Settings, Space, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Example::run(Settings::default()) Example::run(Settings::default())
} }

View File

@ -3,7 +3,7 @@ use iced::{
Container, Element, Image, Length, Row, Settings, Text, Container, Element, Image, Length, Row, Settings, Text,
}; };
pub fn main() { pub fn main() -> iced::Result {
Pokedex::run(Settings::default()) Pokedex::run(Settings::default())
} }

View File

@ -1,6 +1,6 @@
use iced::{slider, Column, Element, ProgressBar, Sandbox, Settings, Slider}; use iced::{slider, Column, Element, ProgressBar, Sandbox, Settings, Slider};
pub fn main() { pub fn main() -> iced::Result {
Progress::run(Settings::default()) Progress::run(Settings::default())
} }

View File

@ -14,7 +14,7 @@ use iced::{
use std::time::Instant; use std::time::Instant;
pub fn main() { pub fn main() -> iced::Result {
SolarSystem::run(Settings { SolarSystem::run(Settings {
antialiasing: true, antialiasing: true,
..Settings::default() ..Settings::default()

View File

@ -5,7 +5,7 @@ use iced::{
}; };
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
pub fn main() { pub fn main() -> iced::Result {
Stopwatch::run(Settings::default()) Stopwatch::run(Settings::default())
} }

View File

@ -1,10 +1,10 @@
use iced::{ use iced::{
button, scrollable, slider, text_input, Align, Button, Checkbox, Column, button, scrollable, slider, text_input, Align, Button, Checkbox, Column,
Container, Element, Length, ProgressBar, Radio, Row, Sandbox, Scrollable, Container, Element, Length, ProgressBar, Radio, Row, Rule, Sandbox,
Settings, Slider, Space, Text, TextInput, Scrollable, Settings, Slider, Space, Text, TextInput,
}; };
pub fn main() { pub fn main() -> iced::Result {
Styling::run(Settings::default()) Styling::run(Settings::default())
} }
@ -113,14 +113,17 @@ impl Sandbox for Styling {
.padding(20) .padding(20)
.max_width(600) .max_width(600)
.push(choose_theme) .push(choose_theme)
.push(Rule::horizontal(38).style(self.theme))
.push(Row::new().spacing(10).push(text_input).push(button)) .push(Row::new().spacing(10).push(text_input).push(button))
.push(slider) .push(slider)
.push(progress_bar) .push(progress_bar)
.push( .push(
Row::new() Row::new()
.spacing(10) .spacing(10)
.height(Length::Units(100))
.align_items(Align::Center) .align_items(Align::Center)
.push(scrollable) .push(scrollable)
.push(Rule::vertical(38).style(self.theme))
.push(checkbox), .push(checkbox),
); );
@ -136,8 +139,8 @@ impl Sandbox for Styling {
mod style { mod style {
use iced::{ use iced::{
button, checkbox, container, progress_bar, radio, scrollable, slider, button, checkbox, container, progress_bar, radio, rule, scrollable,
text_input, slider, text_input,
}; };
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@ -228,17 +231,24 @@ mod style {
} }
} }
impl From<Theme> for Box<dyn rule::StyleSheet> {
fn from(theme: Theme) -> Self {
match theme {
Theme::Light => Default::default(),
Theme::Dark => dark::Rule.into(),
}
}
}
mod light { mod light {
use iced::{button, Background, Color, Vector}; use iced::{button, Color, Vector};
pub struct Button; pub struct Button;
impl button::StyleSheet for Button { impl button::StyleSheet for Button {
fn active(&self) -> button::Style { fn active(&self) -> button::Style {
button::Style { button::Style {
background: Some(Background::Color(Color::from_rgb( background: Color::from_rgb(0.11, 0.42, 0.87).into(),
0.11, 0.42, 0.87,
))),
border_radius: 12, border_radius: 12,
shadow_offset: Vector::new(1.0, 1.0), shadow_offset: Vector::new(1.0, 1.0),
text_color: Color::from_rgb8(0xEE, 0xEE, 0xEE), text_color: Color::from_rgb8(0xEE, 0xEE, 0xEE),
@ -258,8 +268,8 @@ mod style {
mod dark { mod dark {
use iced::{ use iced::{
button, checkbox, container, progress_bar, radio, scrollable, button, checkbox, container, progress_bar, radio, rule, scrollable,
slider, text_input, Background, Color, slider, text_input, Color,
}; };
const SURFACE: Color = Color::from_rgb( const SURFACE: Color = Color::from_rgb(
@ -291,10 +301,8 @@ mod style {
impl container::StyleSheet for Container { impl container::StyleSheet for Container {
fn style(&self) -> container::Style { fn style(&self) -> container::Style {
container::Style { container::Style {
background: Some(Background::Color(Color::from_rgb8( background: Color::from_rgb8(0x36, 0x39, 0x3F).into(),
0x36, 0x39, 0x3F, text_color: Color::WHITE.into(),
))),
text_color: Some(Color::WHITE),
..container::Style::default() ..container::Style::default()
} }
} }
@ -305,7 +313,7 @@ mod style {
impl radio::StyleSheet for Radio { impl radio::StyleSheet for Radio {
fn active(&self) -> radio::Style { fn active(&self) -> radio::Style {
radio::Style { radio::Style {
background: Background::Color(SURFACE), background: SURFACE.into(),
dot_color: ACTIVE, dot_color: ACTIVE,
border_width: 1, border_width: 1,
border_color: ACTIVE, border_color: ACTIVE,
@ -314,7 +322,7 @@ mod style {
fn hovered(&self) -> radio::Style { fn hovered(&self) -> radio::Style {
radio::Style { radio::Style {
background: Background::Color(Color { a: 0.5, ..SURFACE }), background: Color { a: 0.5, ..SURFACE }.into(),
..self.active() ..self.active()
} }
} }
@ -325,7 +333,7 @@ mod style {
impl text_input::StyleSheet for TextInput { impl text_input::StyleSheet for TextInput {
fn active(&self) -> text_input::Style { fn active(&self) -> text_input::Style {
text_input::Style { text_input::Style {
background: Background::Color(SURFACE), background: SURFACE.into(),
border_radius: 2, border_radius: 2,
border_width: 0, border_width: 0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,
@ -366,7 +374,7 @@ mod style {
impl button::StyleSheet for Button { impl button::StyleSheet for Button {
fn active(&self) -> button::Style { fn active(&self) -> button::Style {
button::Style { button::Style {
background: Some(Background::Color(ACTIVE)), background: ACTIVE.into(),
border_radius: 3, border_radius: 3,
text_color: Color::WHITE, text_color: Color::WHITE,
..button::Style::default() ..button::Style::default()
@ -375,7 +383,7 @@ mod style {
fn hovered(&self) -> button::Style { fn hovered(&self) -> button::Style {
button::Style { button::Style {
background: Some(Background::Color(HOVERED)), background: HOVERED.into(),
text_color: Color::WHITE, text_color: Color::WHITE,
..self.active() ..self.active()
} }
@ -395,7 +403,7 @@ mod style {
impl scrollable::StyleSheet for Scrollable { impl scrollable::StyleSheet for Scrollable {
fn active(&self) -> scrollable::Scrollbar { fn active(&self) -> scrollable::Scrollbar {
scrollable::Scrollbar { scrollable::Scrollbar {
background: Some(Background::Color(SURFACE)), background: SURFACE.into(),
border_radius: 2, border_radius: 2,
border_width: 0, border_width: 0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,
@ -412,10 +420,7 @@ mod style {
let active = self.active(); let active = self.active();
scrollable::Scrollbar { scrollable::Scrollbar {
background: Some(Background::Color(Color { background: Color { a: 0.5, ..SURFACE }.into(),
a: 0.5,
..SURFACE
})),
scroller: scrollable::Scroller { scroller: scrollable::Scroller {
color: HOVERED, color: HOVERED,
..active.scroller ..active.scroller
@ -482,8 +487,8 @@ mod style {
impl progress_bar::StyleSheet for ProgressBar { impl progress_bar::StyleSheet for ProgressBar {
fn style(&self) -> progress_bar::Style { fn style(&self) -> progress_bar::Style {
progress_bar::Style { progress_bar::Style {
background: Background::Color(SURFACE), background: SURFACE.into(),
bar: Background::Color(ACTIVE), bar: ACTIVE.into(),
border_radius: 10, border_radius: 10,
} }
} }
@ -494,11 +499,8 @@ mod style {
impl checkbox::StyleSheet for Checkbox { impl checkbox::StyleSheet for Checkbox {
fn active(&self, is_checked: bool) -> checkbox::Style { fn active(&self, is_checked: bool) -> checkbox::Style {
checkbox::Style { checkbox::Style {
background: Background::Color(if is_checked { background: if is_checked { ACTIVE } else { SURFACE }
ACTIVE .into(),
} else {
SURFACE
}),
checkmark_color: Color::WHITE, checkmark_color: Color::WHITE,
border_radius: 2, border_radius: 2,
border_width: 1, border_width: 1,
@ -508,13 +510,27 @@ mod style {
fn hovered(&self, is_checked: bool) -> checkbox::Style { fn hovered(&self, is_checked: bool) -> checkbox::Style {
checkbox::Style { checkbox::Style {
background: Background::Color(Color { background: Color {
a: 0.8, a: 0.8,
..if is_checked { ACTIVE } else { SURFACE } ..if is_checked { ACTIVE } else { SURFACE }
}), }
.into(),
..self.active(is_checked) ..self.active(is_checked)
} }
} }
} }
pub struct Rule;
impl rule::StyleSheet for Rule {
fn style(&self) -> rule::Style {
rule::Style {
color: SURFACE,
width: 2,
radius: 1,
fill_mode: rule::FillMode::Padded(15),
}
}
}
} }
} }

View File

@ -1,6 +1,6 @@
use iced::{Container, Element, Length, Sandbox, Settings, Svg}; use iced::{Container, Element, Length, Sandbox, Settings, Svg};
pub fn main() { pub fn main() -> iced::Result {
Tiger::run(Settings::default()) Tiger::run(Settings::default())
} }

View File

@ -5,7 +5,7 @@ use iced::{
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
pub fn main() { pub fn main() -> iced::Result {
Todos::run(Settings::default()) Todos::run(Settings::default())
} }

View File

@ -4,7 +4,7 @@ use iced::{
Sandbox, Scrollable, Settings, Slider, Space, Text, TextInput, Sandbox, Scrollable, Settings, Slider, Space, Text, TextInput,
}; };
pub fn main() { pub fn main() -> iced::Result {
env_logger::init(); env_logger::init();
Tour::run(Settings::default()) Tour::run(Settings::default())

View File

@ -26,7 +26,7 @@ pub(crate) use iced_graphics::Transformation;
#[doc(no_inline)] #[doc(no_inline)]
pub use widget::*; pub use widget::*;
pub use iced_graphics::Viewport; pub use iced_graphics::{Error, Viewport};
pub use iced_native::{ pub use iced_native::{
Background, Color, Command, HorizontalAlignment, Length, Vector, Background, Color, Command, HorizontalAlignment, Length, Vector,
VerticalAlignment, VerticalAlignment,

View File

@ -16,6 +16,7 @@ pub mod pane_grid;
pub mod pick_list; pub mod pick_list;
pub mod progress_bar; pub mod progress_bar;
pub mod radio; pub mod radio;
pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod text_input; pub mod text_input;
@ -35,6 +36,8 @@ pub use progress_bar::ProgressBar;
#[doc(no_inline)] #[doc(no_inline)]
pub use radio::Radio; pub use radio::Radio;
#[doc(no_inline)] #[doc(no_inline)]
pub use rule::Rule;
#[doc(no_inline)]
pub use scrollable::Scrollable; pub use scrollable::Scrollable;
#[doc(no_inline)] #[doc(no_inline)]
pub use slider::Slider; pub use slider::Slider;

10
glow/src/widget/rule.rs Normal file
View File

@ -0,0 +1,10 @@
//! Display a horizontal or vertical rule for dividing content.
use crate::Renderer;
pub use iced_graphics::rule::{FillMode, Style, StyleSheet};
/// Display a horizontal or vertical rule for dividing content.
///
/// This is an alias of an `iced_native` rule with an `iced_glow::Renderer`.
pub type Rule = iced_native::Rule<Renderer>;

View File

@ -1,4 +1,4 @@
use crate::{Backend, Color, Renderer, Settings, Viewport}; use crate::{Backend, Color, Error, Renderer, Settings, Viewport};
use core::ffi::c_void; use core::ffi::c_void;
use glow::HasContext; use glow::HasContext;
@ -18,7 +18,7 @@ impl iced_graphics::window::GLCompositor for Compositor {
unsafe fn new( unsafe fn new(
settings: Self::Settings, settings: Self::Settings,
loader_function: impl FnMut(&str) -> *const c_void, loader_function: impl FnMut(&str) -> *const c_void,
) -> (Self, Self::Renderer) { ) -> Result<(Self, Self::Renderer), Error> {
let gl = glow::Context::from_loader_function(loader_function); let gl = glow::Context::from_loader_function(loader_function);
// Enable auto-conversion from/to sRGB // Enable auto-conversion from/to sRGB
@ -33,7 +33,7 @@ impl iced_graphics::window::GLCompositor for Compositor {
let renderer = Renderer::new(Backend::new(&gl, settings)); let renderer = Renderer::new(Backend::new(&gl, settings));
(Self { gl }, renderer) Ok((Self { gl }, renderer))
} }
fn sample_count(settings: &Settings) -> u32 { fn sample_count(settings: &Settings) -> u32 {

View File

@ -1,5 +1,5 @@
//! Create interactive, native cross-platform applications. //! Create interactive, native cross-platform applications.
use crate::{mouse, Executor, Runtime, Size}; use crate::{mouse, Error, Executor, Runtime, Size};
use iced_graphics::window; use iced_graphics::window;
use iced_graphics::Viewport; use iced_graphics::Viewport;
use iced_winit::application; use iced_winit::application;
@ -16,7 +16,8 @@ pub use iced_winit::{program, Program};
pub fn run<A, E, C>( pub fn run<A, E, C>(
settings: Settings<A::Flags>, settings: Settings<A::Flags>,
compositor_settings: C::Settings, compositor_settings: C::Settings,
) where ) -> Result<(), Error>
where
A: Application + 'static, A: Application + 'static,
E: Executor + 'static, E: Executor + 'static,
C: window::GLCompositor<Renderer = A::Renderer> + 'static, C: window::GLCompositor<Renderer = A::Renderer> + 'static,
@ -32,7 +33,7 @@ pub fn run<A, E, C>(
let event_loop = EventLoop::with_user_event(); let event_loop = EventLoop::with_user_event();
let mut runtime = { let mut runtime = {
let executor = E::new().expect("Create executor"); let executor = E::new().map_err(Error::ExecutorCreationFailed)?;
let proxy = Proxy::new(event_loop.create_proxy()); let proxy = Proxy::new(event_loop.create_proxy());
Runtime::new(executor, proxy) Runtime::new(executor, proxy)
@ -61,7 +62,16 @@ pub fn run<A, E, C>(
.with_vsync(true) .with_vsync(true)
.with_multisampling(C::sample_count(&compositor_settings) as u16) .with_multisampling(C::sample_count(&compositor_settings) as u16)
.build_windowed(builder, &event_loop) .build_windowed(builder, &event_loop)
.expect("Open window"); .map_err(|error| {
use glutin::CreationError;
match error {
CreationError::Window(error) => {
Error::WindowCreationFailed(error)
}
_ => Error::GraphicsAdapterNotFound,
}
})?;
#[allow(unsafe_code)] #[allow(unsafe_code)]
unsafe { unsafe {
@ -85,7 +95,7 @@ pub fn run<A, E, C>(
let (mut compositor, mut renderer) = unsafe { let (mut compositor, mut renderer) = unsafe {
C::new(compositor_settings, |address| { C::new(compositor_settings, |address| {
context.get_proc_address(address) context.get_proc_address(address)
}) })?
}; };
let mut state = program::State::new( let mut state = program::State::new(

View File

@ -15,7 +15,7 @@ pub use iced_native::*;
pub mod application; pub mod application;
pub use iced_winit::settings; pub use iced_winit::settings;
pub use iced_winit::Mode; pub use iced_winit::{Error, Mode};
#[doc(no_inline)] #[doc(no_inline)]
pub use application::Application; pub use application::Application;

View File

@ -15,6 +15,7 @@ opengl = []
bytemuck = "1.2" bytemuck = "1.2"
glam = "0.9" glam = "0.9"
raw-window-handle = "0.3" raw-window-handle = "0.3"
thiserror = "1.0"
[dependencies.iced_native] [dependencies.iced_native]
version = "0.2" version = "0.2"

7
graphics/src/error.rs Normal file
View File

@ -0,0 +1,7 @@
/// A graphical error that occurred while running an application.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// A suitable graphics adapter or device could not be found
#[error("a suitable graphics adapter or device could not be found")]
AdapterNotFound,
}

View File

@ -9,6 +9,7 @@
#![forbid(rust_2018_idioms)] #![forbid(rust_2018_idioms)]
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]
mod antialiasing; mod antialiasing;
mod error;
mod primitive; mod primitive;
mod renderer; mod renderer;
mod transformation; mod transformation;
@ -29,6 +30,7 @@ pub use widget::*;
pub use antialiasing::Antialiasing; pub use antialiasing::Antialiasing;
pub use backend::Backend; pub use backend::Backend;
pub use defaults::Defaults; pub use defaults::Defaults;
pub use error::Error;
pub use layer::Layer; pub use layer::Layer;
pub use primitive::Primitive; pub use primitive::Primitive;
pub use renderer::Renderer; pub use renderer::Renderer;

View File

@ -15,6 +15,7 @@ pub mod pane_grid;
pub mod pick_list; pub mod pick_list;
pub mod progress_bar; pub mod progress_bar;
pub mod radio; pub mod radio;
pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod svg; pub mod svg;
@ -40,6 +41,8 @@ pub use progress_bar::ProgressBar;
#[doc(no_inline)] #[doc(no_inline)]
pub use radio::Radio; pub use radio::Radio;
#[doc(no_inline)] #[doc(no_inline)]
pub use rule::Rule;
#[doc(no_inline)]
pub use scrollable::Scrollable; pub use scrollable::Scrollable;
#[doc(no_inline)] #[doc(no_inline)]
pub use slider::Slider; pub use slider::Slider;

View File

@ -13,16 +13,13 @@ pub use iced_style::radio::{Style, StyleSheet};
pub type Radio<Message, Backend> = pub type Radio<Message, Backend> =
iced_native::Radio<Message, Renderer<Backend>>; iced_native::Radio<Message, Renderer<Backend>>;
const SIZE: f32 = 28.0;
const DOT_SIZE: f32 = SIZE / 2.0;
impl<B> radio::Renderer for Renderer<B> impl<B> radio::Renderer for Renderer<B>
where where
B: Backend, B: Backend,
{ {
type Style = Box<dyn StyleSheet>; type Style = Box<dyn StyleSheet>;
const DEFAULT_SIZE: u16 = SIZE as u16; const DEFAULT_SIZE: u16 = 28;
const DEFAULT_SPACING: u16 = 15; const DEFAULT_SPACING: u16 = 15;
fn draw( fn draw(
@ -39,10 +36,13 @@ where
style_sheet.active() style_sheet.active()
}; };
let size = bounds.width;
let dot_size = size / 2.0;
let radio = Primitive::Quad { let radio = Primitive::Quad {
bounds, bounds,
background: style.background, background: style.background,
border_radius: (SIZE / 2.0) as u16, border_radius: (size / 2.0) as u16,
border_width: style.border_width, border_width: style.border_width,
border_color: style.border_color, border_color: style.border_color,
}; };
@ -52,13 +52,13 @@ where
primitives: if is_selected { primitives: if is_selected {
let radio_circle = Primitive::Quad { let radio_circle = Primitive::Quad {
bounds: Rectangle { bounds: Rectangle {
x: bounds.x + DOT_SIZE / 2.0, x: bounds.x + dot_size / 2.0,
y: bounds.y + DOT_SIZE / 2.0, y: bounds.y + dot_size / 2.0,
width: bounds.width - DOT_SIZE, width: bounds.width - dot_size,
height: bounds.height - DOT_SIZE, height: bounds.height - dot_size,
}, },
background: Background::Color(style.dot_color), background: Background::Color(style.dot_color),
border_radius: (DOT_SIZE / 2.0) as u16, border_radius: (dot_size / 2.0) as u16,
border_width: 0, border_width: 0,
border_color: Color::TRANSPARENT, border_color: Color::TRANSPARENT,
}; };

View File

@ -0,0 +1,73 @@
//! Display a horizontal or vertical rule for dividing content.
use crate::{Backend, Primitive, Renderer};
use iced_native::mouse;
use iced_native::rule;
use iced_native::{Background, Color, Rectangle};
pub use iced_style::rule::{FillMode, Style, StyleSheet};
/// Display a horizontal or vertical rule for dividing content.
///
/// This is an alias of an `iced_native` rule with an `iced_graphics::Renderer`.
pub type Rule<Backend> = iced_native::Rule<Renderer<Backend>>;
impl<B> rule::Renderer for Renderer<B>
where
B: Backend,
{
type Style = Box<dyn StyleSheet>;
fn draw(
&mut self,
bounds: Rectangle,
style_sheet: &Self::Style,
is_horizontal: bool,
) -> Self::Output {
let style = style_sheet.style();
let line = if is_horizontal {
let line_y = (bounds.y + (bounds.height / 2.0)
- (style.width as f32 / 2.0))
.round();
let (offset, line_width) = style.fill_mode.fill(bounds.width);
let line_x = bounds.x + offset;
Primitive::Quad {
bounds: Rectangle {
x: line_x,
y: line_y,
width: line_width,
height: style.width as f32,
},
background: Background::Color(style.color),
border_radius: style.radius,
border_width: 0,
border_color: Color::TRANSPARENT,
}
} else {
let line_x = (bounds.x + (bounds.width / 2.0)
- (style.width as f32 / 2.0))
.round();
let (offset, line_height) = style.fill_mode.fill(bounds.height);
let line_y = bounds.y + offset;
Primitive::Quad {
bounds: Rectangle {
x: line_x,
y: line_y,
width: style.width as f32,
height: line_height,
},
background: Background::Color(style.color),
border_radius: style.radius,
border_width: 0,
border_color: Color::TRANSPARENT,
}
};
(line, mouse::Interaction::default())
}
}

View File

@ -1,4 +1,4 @@
use crate::{Color, Viewport}; use crate::{Color, Error, Viewport};
use iced_native::mouse; use iced_native::mouse;
use raw_window_handle::HasRawWindowHandle; use raw_window_handle::HasRawWindowHandle;
@ -19,7 +19,7 @@ pub trait Compositor: Sized {
/// Creates a new [`Backend`]. /// Creates a new [`Backend`].
/// ///
/// [`Backend`]: trait.Backend.html /// [`Backend`]: trait.Backend.html
fn new(settings: Self::Settings) -> (Self, Self::Renderer); fn new(settings: Self::Settings) -> Result<(Self, Self::Renderer), Error>;
/// Crates a new [`Surface`] for the given window. /// Crates a new [`Surface`] for the given window.
/// ///

View File

@ -1,4 +1,4 @@
use crate::{Color, Size, Viewport}; use crate::{Color, Error, Size, Viewport};
use iced_native::mouse; use iced_native::mouse;
use core::ffi::c_void; use core::ffi::c_void;
@ -41,7 +41,7 @@ pub trait GLCompositor: Sized {
unsafe fn new( unsafe fn new(
settings: Self::Settings, settings: Self::Settings,
loader_function: impl FnMut(&str) -> *const c_void, loader_function: impl FnMut(&str) -> *const c_void,
) -> (Self, Self::Renderer); ) -> Result<(Self, Self::Renderer), Error>;
/// Returns the amount of samples that should be used when configuring /// Returns the amount of samples that should be used when configuring
/// an OpenGL context for this [`Compositor`]. /// an OpenGL context for this [`Compositor`].

View File

@ -30,6 +30,7 @@ pub mod pick_list;
pub mod progress_bar; pub mod progress_bar;
pub mod radio; pub mod radio;
pub mod row; pub mod row;
pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod space; pub mod space;
@ -58,6 +59,8 @@ pub use radio::Radio;
#[doc(no_inline)] #[doc(no_inline)]
pub use row::Row; pub use row::Row;
#[doc(no_inline)] #[doc(no_inline)]
pub use rule::Rule;
#[doc(no_inline)]
pub use scrollable::Scrollable; pub use scrollable::Scrollable;
#[doc(no_inline)] #[doc(no_inline)]
pub use slider::Slider; pub use slider::Slider;

125
native/src/widget/rule.rs Normal file
View File

@ -0,0 +1,125 @@
//! Display a horizontal or vertical rule for dividing content.
use std::hash::Hash;
use crate::{
layout, Element, Hasher, Layout, Length, Point, Rectangle, Size, Widget,
};
/// Display a horizontal or vertical rule for dividing content.
#[derive(Debug, Copy, Clone)]
pub struct Rule<Renderer: self::Renderer> {
width: Length,
height: Length,
style: Renderer::Style,
is_horizontal: bool,
}
impl<Renderer: self::Renderer> Rule<Renderer> {
/// Creates a horizontal [`Rule`] for dividing content by the given vertical spacing.
///
/// [`Rule`]: struct.Rule.html
pub fn horizontal(spacing: u16) -> Self {
Rule {
width: Length::Fill,
height: Length::from(Length::Units(spacing)),
style: Renderer::Style::default(),
is_horizontal: true,
}
}
/// Creates a vertical [`Rule`] for dividing content by the given horizontal spacing.
///
/// [`Rule`]: struct.Rule.html
pub fn vertical(spacing: u16) -> Self {
Rule {
width: Length::from(Length::Units(spacing)),
height: Length::Fill,
style: Renderer::Style::default(),
is_horizontal: false,
}
}
/// Sets the style of the [`Rule`].
///
/// [`Rule`]: struct.Rule.html
pub fn style(mut self, style: impl Into<Renderer::Style>) -> Self {
self.style = style.into();
self
}
}
impl<Message, Renderer> Widget<Message, Renderer> for Rule<Renderer>
where
Renderer: self::Renderer,
{
fn width(&self) -> Length {
self.width
}
fn height(&self) -> Length {
self.height
}
fn layout(
&self,
_renderer: &Renderer,
limits: &layout::Limits,
) -> layout::Node {
let limits = limits.width(self.width).height(self.height);
layout::Node::new(limits.resolve(Size::ZERO))
}
fn draw(
&self,
renderer: &mut Renderer,
_defaults: &Renderer::Defaults,
layout: Layout<'_>,
_cursor_position: Point,
) -> Renderer::Output {
renderer.draw(layout.bounds(), &self.style, self.is_horizontal)
}
fn hash_layout(&self, state: &mut Hasher) {
struct Marker;
std::any::TypeId::of::<Marker>().hash(state);
self.width.hash(state);
self.height.hash(state);
}
}
/// The renderer of a [`Rule`].
///
/// [`Rule`]: struct.Rule.html
pub trait Renderer: crate::Renderer {
/// The style supported by this renderer.
type Style: Default;
/// Draws a [`Rule`].
///
/// It receives:
/// * the bounds of the [`Rule`]
/// * the style of the [`Rule`]
/// * whether the [`Rule`] is horizontal (true) or vertical (false)
///
/// [`Rule`]: struct.Rule.html
fn draw(
&mut self,
bounds: Rectangle,
style: &Self::Style,
is_horizontal: bool,
) -> Self::Output;
}
impl<'a, Message, Renderer> From<Rule<Renderer>>
for Element<'a, Message, Renderer>
where
Renderer: 'a + self::Renderer,
Message: 'a,
{
fn from(rule: Rule<Renderer>) -> Element<'a, Message, Renderer> {
Element::new(rule)
}
}

View File

@ -1,6 +1,5 @@
use crate::{ use crate::window;
window, Color, Command, Element, Executor, Settings, Subscription, use crate::{Color, Command, Element, Executor, Settings, Subscription};
};
/// An interactive cross-platform application. /// An interactive cross-platform application.
/// ///
@ -59,7 +58,7 @@ use crate::{
/// ```no_run /// ```no_run
/// use iced::{executor, Application, Command, Element, Settings, Text}; /// use iced::{executor, Application, Command, Element, Settings, Text};
/// ///
/// pub fn main() { /// pub fn main() -> iced::Result {
/// Hello::run(Settings::default()) /// Hello::run(Settings::default())
/// } /// }
/// ///
@ -204,12 +203,13 @@ pub trait Application: Sized {
/// Runs the [`Application`]. /// Runs the [`Application`].
/// ///
/// On native platforms, this method will take control of the current thread /// On native platforms, this method will take control of the current thread
/// and __will NOT return__. /// and __will NOT return__ unless there is an [`Error`] during startup.
/// ///
/// It should probably be that last thing you call in your `main` function. /// It should probably be that last thing you call in your `main` function.
/// ///
/// [`Application`]: trait.Application.html /// [`Application`]: trait.Application.html
fn run(settings: Settings<Self::Flags>) /// [`Error`]: enum.Error.html
fn run(settings: Settings<Self::Flags>) -> crate::Result
where where
Self: 'static, Self: 'static,
{ {
@ -226,15 +226,19 @@ pub trait Application: Sized {
..crate::renderer::Settings::default() ..crate::renderer::Settings::default()
}; };
crate::runtime::application::run::< Ok(crate::runtime::application::run::<
Instance<Self>, Instance<Self>,
Self::Executor, Self::Executor,
crate::renderer::window::Compositor, crate::renderer::window::Compositor,
>(settings.into(), renderer_settings); >(settings.into(), renderer_settings)?)
} }
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
<Instance<Self> as iced_web::Application>::run(settings.flags); {
<Instance<Self> as iced_web::Application>::run(settings.flags);
Ok(())
}
} }
} }

34
src/error.rs Normal file
View File

@ -0,0 +1,34 @@
use iced_futures::futures;
/// An error that occurred while running an application.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// The futures executor could not be created.
#[error("the futures executor could not be created")]
ExecutorCreationFailed(futures::io::Error),
/// The application window could not be created.
#[error("the application window could not be created")]
WindowCreationFailed(Box<dyn std::error::Error>),
/// A suitable graphics adapter or device could not be found.
#[error("a suitable graphics adapter or device could not be found")]
GraphicsAdapterNotFound,
}
#[cfg(not(target_arch = "wasm32"))]
impl From<iced_winit::Error> for Error {
fn from(error: iced_winit::Error) -> Error {
match error {
iced_winit::Error::ExecutorCreationFailed(error) => {
Error::ExecutorCreationFailed(error)
}
iced_winit::Error::WindowCreationFailed(error) => {
Error::WindowCreationFailed(Box::new(error))
}
iced_winit::Error::GraphicsAdapterNotFound => {
Error::GraphicsAdapterNotFound
}
}
}
}

View File

@ -181,6 +181,8 @@
#![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(docsrs, feature(doc_cfg))]
mod application; mod application;
mod element; mod element;
mod error;
mod result;
mod sandbox; mod sandbox;
pub mod executor; pub mod executor;
@ -225,7 +227,9 @@ pub use widget::*;
pub use application::Application; pub use application::Application;
pub use element::Element; pub use element::Element;
pub use error::Error;
pub use executor::Executor; pub use executor::Executor;
pub use result::Result;
pub use sandbox::Sandbox; pub use sandbox::Sandbox;
pub use settings::Settings; pub use settings::Settings;

6
src/result.rs Normal file
View File

@ -0,0 +1,6 @@
use crate::Error;
/// The result of running an [`Application`].
///
/// [`Application`]: trait.Application.html
pub type Result = std::result::Result<(), Error>;

View File

@ -1,5 +1,6 @@
use crate::executor;
use crate::{ use crate::{
executor, Application, Color, Command, Element, Settings, Subscription, Application, Color, Command, Element, Error, Settings, Subscription,
}; };
/// A sandboxed [`Application`]. /// A sandboxed [`Application`].
@ -64,7 +65,7 @@ use crate::{
/// ```no_run /// ```no_run
/// use iced::{Element, Sandbox, Settings, Text}; /// use iced::{Element, Sandbox, Settings, Text};
/// ///
/// pub fn main() { /// pub fn main() -> iced::Result {
/// Hello::run(Settings::default()) /// Hello::run(Settings::default())
/// } /// }
/// ///
@ -159,7 +160,7 @@ pub trait Sandbox {
/// It should probably be that last thing you call in your `main` function. /// It should probably be that last thing you call in your `main` function.
/// ///
/// [`Sandbox`]: trait.Sandbox.html /// [`Sandbox`]: trait.Sandbox.html
fn run(settings: Settings<()>) fn run(settings: Settings<()>) -> Result<(), Error>
where where
Self: 'static + Sized, Self: 'static + Sized,
{ {

View File

@ -20,7 +20,7 @@
mod platform { mod platform {
pub use crate::renderer::widget::{ pub use crate::renderer::widget::{
button, checkbox, container, pane_grid, pick_list, progress_bar, radio, button, checkbox, container, pane_grid, pick_list, progress_bar, radio,
scrollable, slider, text_input, Column, Row, Space, Text, rule, scrollable, slider, text_input, Column, Row, Space, Text,
}; };
#[cfg(any(feature = "canvas", feature = "glow_canvas"))] #[cfg(any(feature = "canvas", feature = "glow_canvas"))]
@ -46,8 +46,8 @@ mod platform {
pub use { pub use {
button::Button, checkbox::Checkbox, container::Container, image::Image, button::Button, checkbox::Checkbox, container::Container, image::Image,
pane_grid::PaneGrid, pick_list::PickList, progress_bar::ProgressBar, pane_grid::PaneGrid, pick_list::PickList, progress_bar::ProgressBar,
radio::Radio, scrollable::Scrollable, slider::Slider, svg::Svg, radio::Radio, rule::Rule, scrollable::Scrollable, slider::Slider,
text_input::TextInput, svg::Svg, text_input::TextInput,
}; };
#[cfg(any(feature = "canvas", feature = "glow_canvas"))] #[cfg(any(feature = "canvas", feature = "glow_canvas"))]

View File

@ -11,6 +11,7 @@ pub mod menu;
pub mod pick_list; pub mod pick_list;
pub mod progress_bar; pub mod progress_bar;
pub mod radio; pub mod radio;
pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod text_input; pub mod text_input;

116
style/src/rule.rs Normal file
View File

@ -0,0 +1,116 @@
//! Display a horizontal or vertical rule for dividing content.
use iced_core::Color;
/// The fill mode of a rule.
#[derive(Debug, Clone, Copy)]
pub enum FillMode {
/// Fill the whole length of the container.
Full,
/// Fill a percent of the length of the container. The rule
/// will be centered in that container.
///
/// The range is `[0.0, 100.0]`.
Percent(f32),
/// Uniform offset from each end, length units.
Padded(u16),
/// Different offset on each end of the rule, length units.
/// First = top or left.
AsymmetricPadding(u16, u16),
}
impl FillMode {
/// Return the starting offset and length of the rule.
///
/// * `space` - The space to fill.
///
/// # Returns
///
/// * (starting_offset, length)
pub fn fill(&self, space: f32) -> (f32, f32) {
match *self {
FillMode::Full => (0.0, space),
FillMode::Percent(percent) => {
if percent >= 100.0 {
(0.0, space)
} else {
let percent_width = (space * percent / 100.0).round();
(((space - percent_width) / 2.0).round(), percent_width)
}
}
FillMode::Padded(padding) => {
if padding == 0 {
(0.0, space)
} else {
let padding = padding as f32;
let mut line_width = space - (padding * 2.0);
if line_width < 0.0 {
line_width = 0.0;
}
(padding, line_width)
}
}
FillMode::AsymmetricPadding(first_pad, second_pad) => {
let first_pad = first_pad as f32;
let second_pad = second_pad as f32;
let mut line_width = space - first_pad - second_pad;
if line_width < 0.0 {
line_width = 0.0;
}
(first_pad, line_width)
}
}
}
}
/// The appearance of a rule.
#[derive(Debug, Clone, Copy)]
pub struct Style {
/// The color of the rule.
pub color: Color,
/// The width (thickness) of the rule line.
pub width: u16,
/// The radius of the line corners.
pub radius: u16,
/// The [`FillMode`] of the rule.
///
/// [`FillMode`]: enum.FillMode.html
pub fill_mode: FillMode,
}
/// A set of rules that dictate the style of a rule.
pub trait StyleSheet {
/// Produces the style of a rule.
fn style(&self) -> Style;
}
struct Default;
impl StyleSheet for Default {
fn style(&self) -> Style {
Style {
color: [0.6, 0.6, 0.6, 0.51].into(),
width: 1,
radius: 0,
fill_mode: FillMode::Percent(90.0),
}
}
}
impl std::default::Default for Box<dyn StyleSheet> {
fn default() -> Self {
Box::new(Default)
}
}
impl<T> From<T> for Box<dyn StyleSheet>
where
T: 'static + StyleSheet,
{
fn from(style: T) -> Self {
Box::new(style)
}
}

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,
@ -147,6 +152,7 @@ impl Backend {
self.image_pipeline.draw( self.image_pipeline.draw(
device, device,
staging_belt,
encoder, encoder,
&layer.images, &layer.images,
scaled, scaled,
@ -225,6 +231,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

@ -42,6 +42,8 @@ pub struct Pipeline {
impl Pipeline { impl Pipeline {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
use wgpu::util::DeviceExt;
let sampler = device.create_sampler(&wgpu::SamplerDescriptor { let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge,
@ -49,50 +51,52 @@ impl Pipeline {
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: Some("iced_wgpu::image constants layout"),
bindings: &[ entries: &[
wgpu::BindGroupLayoutEntry { 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,
}, },
wgpu::BindGroupLayoutEntry { wgpu::BindGroupLayoutEntry {
binding: 1, binding: 1,
visibility: wgpu::ShaderStage::FRAGMENT, visibility: wgpu::ShaderStage::FRAGMENT,
ty: wgpu::BindingType::Sampler { comparison: false }, ty: wgpu::BindingType::Sampler { comparison: false },
count: None,
}, },
], ],
}); });
let uniforms = Uniforms { let uniforms_buffer = device.create_buffer(&wgpu::BufferDescriptor {
transform: Transformation::identity().into(), label: Some("iced_wgpu::image uniforms buffer"),
}; size: mem::size_of::<Uniforms>() as u64,
usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
let uniforms_buffer = device.create_buffer_with_data( mapped_at_creation: false,
uniforms.as_bytes(), });
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
);
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::image constants bind group"),
layout: &constant_layout, layout: &constant_layout,
bindings: &[ entries: &[
wgpu::Binding { wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::Buffer { resource: wgpu::BindingResource::Buffer(
buffer: &uniforms_buffer, uniforms_buffer.slice(..),
range: 0..std::mem::size_of::<Uniforms>() as u64, ),
},
}, },
wgpu::Binding { wgpu::BindGroupEntry {
binding: 1, binding: 1,
resource: wgpu::BindingResource::Sampler(&sampler), resource: wgpu::BindingResource::Sampler(&sampler),
}, },
@ -101,8 +105,8 @@ impl Pipeline {
let texture_layout = let texture_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: Some("iced_wgpu::image texture atlas layout"),
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 {
@ -110,29 +114,29 @@ impl Pipeline {
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: Some("iced_wgpu::image pipeline layout"),
push_constant_ranges: &[],
bind_group_layouts: &[&constant_layout, &texture_layout], bind_group_layouts: &[&constant_layout, &texture_layout],
}); });
let vs = include_bytes!("shader/image.vert.spv"); let vs_module = device.create_shader_module(wgpu::include_spirv!(
let vs_module = device.create_shader_module( "shader/image.vert.spv"
&wgpu::read_spirv(std::io::Cursor::new(&vs[..])) ));
.expect("Read image vertex shader as SPIR-V"),
);
let fs = include_bytes!("shader/image.frag.spv"); let fs_module = device.create_shader_module(wgpu::include_spirv!(
let fs_module = device.create_shader_module( "shader/image.frag.spv"
&wgpu::read_spirv(std::io::Cursor::new(&fs[..])) ));
.expect("Read image fragment shader as SPIR-V"),
);
let pipeline = let pipeline =
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
layout: &layout, label: Some("iced_wgpu::image pipeline"),
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -144,9 +148,7 @@ impl Pipeline {
rasterization_state: Some(wgpu::RasterizationStateDescriptor { rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw, front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::None, cull_mode: wgpu::CullMode::None,
depth_bias: 0, ..Default::default()
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -214,28 +216,33 @@ 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: Some("iced_wgpu::image vertex buffer"),
); 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: Some("iced_wgpu::image index buffer"),
); 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: Some("iced_wgpu::image instance buffer"),
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,
mapped_at_creation: false,
}); });
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, label: Some("iced_wgpu::image texture atlas bind group"),
layout: &texture_layout, layout: &texture_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::TextureView( resource: wgpu::BindingResource::TextureView(
&texture_atlas.view(), &texture_atlas.view(),
@ -282,6 +289,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,
images: &[layer::Image], images: &[layer::Image],
transformation: Transformation, transformation: Transformation,
@ -354,9 +362,9 @@ impl Pipeline {
self.texture = self.texture =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::image texture atlas bind group"),
layout: &self.texture_layout, layout: &self.texture_layout,
bindings: &[wgpu::Binding { entries: &[wgpu::BindGroupEntry {
binding: 0, binding: 0,
resource: wgpu::BindingResource::TextureView( resource: wgpu::BindingResource::TextureView(
&self.texture_atlas.view(), &self.texture_atlas.view(),
@ -367,26 +375,23 @@ impl Pipeline {
self.texture_version = texture_version; self.texture_version = texture_version;
} }
let uniforms_buffer = device.create_buffer_with_data( {
Uniforms { let mut uniforms_buffer = staging_belt.write_buffer(
transform: transformation.into(), encoder,
} &self.uniforms,
.as_bytes(), 0,
wgpu::BufferUsage::COPY_SRC, wgpu::BufferSize::new(mem::size_of::<Uniforms>() as u64)
); .unwrap(),
device,
);
encoder.copy_buffer_to_buffer( uniforms_buffer.copy_from_slice(
&uniforms_buffer, Uniforms {
0, transform: transformation.into(),
&self.uniforms, }
0, .as_bytes(),
std::mem::size_of::<Uniforms>() as u64, );
); }
let instances_buffer = device.create_buffer_with_data(
instances.as_bytes(),
wgpu::BufferUsage::COPY_SRC,
);
let mut i = 0; let mut i = 0;
let total = instances.len(); let total = instances.len();
@ -395,27 +400,29 @@ impl Pipeline {
let end = (i + Instance::MAX).min(total); let end = (i + Instance::MAX).min(total);
let amount = end - i; let amount = end - i;
encoder.copy_buffer_to_buffer( let mut instances_buffer = staging_belt.write_buffer(
&instances_buffer, encoder,
(i * std::mem::size_of::<Instance>()) as u64,
&self.instances, &self.instances,
0, 0,
(amount * std::mem::size_of::<Instance>()) as u64, wgpu::BufferSize::new(
(amount * std::mem::size_of::<Instance>()) as u64,
)
.unwrap(),
device,
); );
instances_buffer
.copy_from_slice(instances[i..i + amount].as_bytes());
let mut render_pass = let mut render_pass =
encoder.begin_render_pass(&wgpu::RenderPassDescriptor { encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[ color_attachments: &[
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,
}, },
}, },
], ],
@ -425,9 +432,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, 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,

View File

@ -28,9 +28,8 @@ impl Atlas {
}; };
let texture = device.create_texture(&wgpu::TextureDescriptor { let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: Some("iced_wgpu::image texture atlas"),
size: extent, size: extent,
array_layer_count: 2,
mip_level_count: 1, mip_level_count: 1,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
@ -40,12 +39,15 @@ impl Atlas {
| wgpu::TextureUsage::SAMPLED, | wgpu::TextureUsage::SAMPLED,
}); });
let texture_view = texture.create_default_view(); let texture_view = texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
Atlas { Atlas {
texture, texture,
texture_view, texture_view,
layers: vec![Layer::Empty, Layer::Empty], layers: vec![Layer::Empty],
} }
} }
@ -65,6 +67,8 @@ impl Atlas {
device: &wgpu::Device, device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
) -> Option<Entry> { ) -> Option<Entry> {
use wgpu::util::DeviceExt;
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)?;
@ -78,8 +82,31 @@ impl Atlas {
log::info!("Allocated atlas entry: {:?}", entry); log::info!("Allocated atlas entry: {:?}", entry);
// It is a webgpu requirement that:
// BufferCopyView.layout.bytes_per_row % wgpu::COPY_BYTES_PER_ROW_ALIGNMENT == 0
// So we calculate padded_width by rounding width up to the next
// multiple of wgpu::COPY_BYTES_PER_ROW_ALIGNMENT.
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
let padding = (align - (4 * width) % align) % align;
let padded_width = (4 * width + padding) as usize;
let padded_data_size = padded_width * height as usize;
let mut padded_data = vec![0; padded_data_size];
for row in 0..height as usize {
let offset = row * padded_width;
padded_data[offset..offset + 4 * width as usize].copy_from_slice(
&data[row * 4 * width as usize..(row + 1) * 4 * width as usize],
)
}
let buffer = let buffer =
device.create_buffer_with_data(data, wgpu::BufferUsage::COPY_SRC); device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("iced_wgpu::image staging buffer"),
contents: &padded_data,
usage: wgpu::BufferUsage::COPY_SRC,
});
match &entry { match &entry {
Entry::Contiguous(allocation) => { Entry::Contiguous(allocation) => {
@ -87,6 +114,7 @@ impl Atlas {
&buffer, &buffer,
width, width,
height, height,
padding,
0, 0,
&allocation, &allocation,
encoder, encoder,
@ -95,12 +123,13 @@ impl Atlas {
Entry::Fragmented { fragments, .. } => { Entry::Fragmented { fragments, .. } => {
for fragment in fragments { for fragment in fragments {
let (x, y) = fragment.position; let (x, y) = fragment.position;
let offset = (y * width + x) as usize * 4; let offset = (y * padded_width as u32 + 4 * x) as usize;
self.upload_allocation( self.upload_allocation(
&buffer, &buffer,
width, width,
height, height,
padding,
offset, offset,
&fragment.allocation, &fragment.allocation,
encoder, encoder,
@ -253,6 +282,7 @@ impl Atlas {
buffer: &wgpu::Buffer, buffer: &wgpu::Buffer,
image_width: u32, image_width: u32,
image_height: u32, image_height: u32,
padding: u32,
offset: usize, offset: usize,
allocation: &Allocation, allocation: &Allocation,
encoder: &mut wgpu::CommandEncoder, encoder: &mut wgpu::CommandEncoder,
@ -270,15 +300,20 @@ impl Atlas {
encoder.copy_buffer_to_texture( encoder.copy_buffer_to_texture(
wgpu::BufferCopyView { wgpu::BufferCopyView {
buffer, buffer,
offset: offset as u64, layout: wgpu::TextureDataLayout {
bytes_per_row: 4 * image_width, offset: offset as u64,
rows_per_image: image_height, bytes_per_row: 4 * image_width + padding,
rows_per_image: image_height,
},
}, },
wgpu::TextureCopyView { wgpu::TextureCopyView {
texture: &self.texture, texture: &self.texture,
array_layer: layer as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { x, y, z: 0 }, origin: wgpu::Origin3d {
x,
y,
z: layer as u32,
},
}, },
extent, extent,
); );
@ -295,13 +330,12 @@ impl Atlas {
} }
let new_texture = device.create_texture(&wgpu::TextureDescriptor { let new_texture = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: Some("iced_wgpu::image texture atlas"),
size: wgpu::Extent3d { size: wgpu::Extent3d {
width: SIZE, width: SIZE,
height: SIZE, height: SIZE,
depth: 1, depth: self.layers.len() as u32,
}, },
array_layer_count: self.layers.len() as u32,
mip_level_count: 1, mip_level_count: 1,
sample_count: 1, sample_count: 1,
dimension: wgpu::TextureDimension::D2, dimension: wgpu::TextureDimension::D2,
@ -323,15 +357,21 @@ impl Atlas {
encoder.copy_texture_to_texture( encoder.copy_texture_to_texture(
wgpu::TextureCopyView { wgpu::TextureCopyView {
texture: &self.texture, texture: &self.texture,
array_layer: i as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: 0, z: 0 }, origin: wgpu::Origin3d {
x: 0,
y: 0,
z: i as u32,
},
}, },
wgpu::TextureCopyView { wgpu::TextureCopyView {
texture: &new_texture, texture: &new_texture,
array_layer: i as u32,
mip_level: 0, mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: 0, z: 0 }, origin: wgpu::Origin3d {
x: 0,
y: 0,
z: i as u32,
},
}, },
wgpu::Extent3d { wgpu::Extent3d {
width: SIZE, width: SIZE,
@ -342,6 +382,10 @@ impl Atlas {
} }
self.texture = new_texture; self.texture = new_texture;
self.texture_view = self.texture.create_default_view(); self.texture_view =
self.texture.create_view(&wgpu::TextureViewDescriptor {
dimension: Some(wgpu::TextureViewDimension::D2Array),
..Default::default()
});
} }
} }

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))]
@ -36,7 +36,9 @@ mod backend;
mod quad; mod quad;
mod text; mod text;
pub use iced_graphics::{Antialiasing, Color, Defaults, Primitive, Viewport}; pub use iced_graphics::{
Antialiasing, Color, Defaults, Error, Primitive, Viewport,
};
pub use wgpu; pub use wgpu;
pub use backend::Backend; pub use backend::Backend;

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)]
@ -19,51 +20,55 @@ impl Pipeline {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipeline {
let constant_layout = let constant_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: Some("iced_wgpu::quad uniforms layout"),
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 = device.create_buffer(&wgpu::BufferDescriptor {
Uniforms::default().as_bytes(), label: Some("iced_wgpu::quad uniforms buffer"),
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, size: mem::size_of::<Uniforms>() as u64,
); usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
mapped_at_creation: false,
});
let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { let constants = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::quad uniforms bind group"),
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: Some("iced_wgpu::quad pipeline layout"),
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: Some("iced_wgpu::quad pipeline"),
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -75,9 +80,7 @@ impl Pipeline {
rasterization_state: Some(wgpu::RasterizationStateDescriptor { rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw, front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::None, cull_mode: wgpu::CullMode::None,
depth_bias: 0, ..Default::default()
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -150,20 +153,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: Some("iced_wgpu::quad vertex buffer"),
); 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: Some("iced_wgpu::quad index buffer"),
); 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: Some("iced_wgpu::quad instance buffer"),
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 +187,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 +197,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 +217,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 +236,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 +247,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;
@ -25,6 +25,7 @@ pub(crate) struct Pipeline {
#[derive(Debug)] #[derive(Debug)]
struct Buffer<T> { struct Buffer<T> {
label: &'static str,
raw: wgpu::Buffer, raw: wgpu::Buffer,
size: usize, size: usize,
usage: wgpu::BufferUsage, usage: wgpu::BufferUsage,
@ -33,17 +34,20 @@ struct Buffer<T> {
impl<T> Buffer<T> { impl<T> Buffer<T> {
pub fn new( pub fn new(
label: &'static str,
device: &wgpu::Device, device: &wgpu::Device,
size: usize, size: usize,
usage: wgpu::BufferUsage, usage: wgpu::BufferUsage,
) -> Self { ) -> Self {
let raw = device.create_buffer(&wgpu::BufferDescriptor { let raw = device.create_buffer(&wgpu::BufferDescriptor {
label: None, label: Some(label),
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 {
label,
raw, raw,
size, size,
usage, usage,
@ -56,9 +60,10 @@ impl<T> Buffer<T> {
if needs_resize { if needs_resize {
self.raw = device.create_buffer(&wgpu::BufferDescriptor { self.raw = device.create_buffer(&wgpu::BufferDescriptor {
label: None, label: Some(self.label),
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;
@ -76,15 +81,22 @@ impl Pipeline {
) -> Pipeline { ) -> Pipeline {
let constants_layout = let constants_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: None, label: Some("iced_wgpu::triangle uniforms layout"),
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,
}], }],
}); });
let constants_buffer = Buffer::new( let constants_buffer = Buffer::new(
"iced_wgpu::triangle uniforms buffer",
device, device,
UNIFORM_BUFFER_SIZE, UNIFORM_BUFFER_SIZE,
wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST,
@ -92,37 +104,37 @@ impl Pipeline {
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::triangle uniforms bind group"),
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: Some("iced_wgpu::triangle pipeline layout"),
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: Some("iced_wgpu::triangle pipeline"),
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -134,9 +146,7 @@ impl Pipeline {
rasterization_state: Some(wgpu::RasterizationStateDescriptor { rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw, front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::None, cull_mode: wgpu::CullMode::None,
depth_bias: 0, ..Default::default()
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -189,11 +199,13 @@ impl Pipeline {
constants: constant_bind_group, constants: constant_bind_group,
uniforms_buffer: constants_buffer, uniforms_buffer: constants_buffer,
vertex_buffer: Buffer::new( vertex_buffer: Buffer::new(
"iced_wgpu::triangle vertex buffer",
device, device,
VERTEX_BUFFER_SIZE, VERTEX_BUFFER_SIZE,
wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST,
), ),
index_buffer: Buffer::new( index_buffer: Buffer::new(
"iced_wgpu::triangle index buffer",
device, device,
INDEX_BUFFER_SIZE, INDEX_BUFFER_SIZE,
wgpu::BufferUsage::INDEX | wgpu::BufferUsage::COPY_DST, wgpu::BufferUsage::INDEX | wgpu::BufferUsage::COPY_DST,
@ -204,6 +216,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,
@ -234,14 +247,15 @@ impl Pipeline {
if self.uniforms_buffer.expand(device, meshes.len()) { if self.uniforms_buffer.expand(device, meshes.len()) {
self.constants = self.constants =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::triangle uniforms buffer"),
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 +275,80 @@ 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( match (
mesh.buffers.indices.as_bytes(), wgpu::BufferSize::new(vertices.len() as u64),
wgpu::BufferUsage::COPY_SRC, wgpu::BufferSize::new(indices.len() as u64),
); ) {
(Some(vertices_size), Some(indices_size)) => {
{
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::TRANSPARENT),
)
} else { } else {
(target, None, wgpu::LoadOp::Load) (target, None, wgpu::LoadOp::Load)
}; };
@ -330,14 +359,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,
@ -364,16 +386,16 @@ impl Pipeline {
); );
render_pass.set_index_buffer( render_pass.set_index_buffer(
&self.index_buffer.raw, self.index_buffer
index_offset * std::mem::size_of::<u32>() as u64, .raw
0, .slice(index_offset * mem::size_of::<u32>() as u64..),
); );
render_pass.set_vertex_buffer( render_pass.set_vertex_buffer(
0, 0,
&self.vertex_buffer.raw, self.vertex_buffer.raw.slice(
vertex_offset * std::mem::size_of::<Vertex2D>() as u64, vertex_offset * mem::size_of::<Vertex2D>() as u64..,
0, ),
); );
render_pass.draw_indexed(0..indices as u32, 0, 0..1); render_pass.draw_indexed(0..indices as u32, 0, 0..1);

View File

@ -23,26 +23,25 @@ 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: Some("iced_wgpu::triangle:msaa uniforms layout"),
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,
}], }],
}); });
let constant_bind_group = let constant_bind_group =
device.create_bind_group(&wgpu::BindGroupDescriptor { device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None, label: Some("iced_wgpu::triangle::msaa uniforms bind group"),
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),
}], }],
@ -50,8 +49,8 @@ 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: Some("iced_wgpu::triangle::msaa texture layout"),
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: Some("iced_wgpu::triangle::msaa pipeline layout"),
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: Some("iced_wgpu::triangle::msaa pipeline"),
layout: Some(&layout),
vertex_stage: wgpu::ProgrammableStageDescriptor { vertex_stage: wgpu::ProgrammableStageDescriptor {
module: &vs_module, module: &vs_module,
entry_point: "main", entry_point: "main",
@ -93,9 +92,7 @@ impl Blit {
rasterization_state: Some(wgpu::RasterizationStateDescriptor { rasterization_state: Some(wgpu::RasterizationStateDescriptor {
front_face: wgpu::FrontFace::Cw, front_face: wgpu::FrontFace::Cw,
cull_mode: wgpu::CullMode::None, cull_mode: wgpu::CullMode::None,
depth_bias: 0, ..Default::default()
depth_bias_slope_scale: 0.0,
depth_bias_clamp: 0.0,
}), }),
primitive_topology: wgpu::PrimitiveTopology::TriangleList, primitive_topology: wgpu::PrimitiveTopology::TriangleList,
color_states: &[wgpu::ColorStateDescriptor { color_states: &[wgpu::ColorStateDescriptor {
@ -179,13 +176,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,
}, },
}, },
], ],
@ -228,9 +221,8 @@ impl Targets {
}; };
let attachment = device.create_texture(&wgpu::TextureDescriptor { let attachment = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: Some("iced_wgpu::triangle::msaa attachment"),
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,
@ -239,9 +231,8 @@ impl Targets {
}); });
let resolve = device.create_texture(&wgpu::TextureDescriptor { let resolve = device.create_texture(&wgpu::TextureDescriptor {
label: None, label: Some("iced_wgpu::triangle::msaa resolve target"),
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 +241,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: Some("iced_wgpu::triangle::msaa texture bind group"),
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

@ -16,6 +16,7 @@ pub mod pane_grid;
pub mod pick_list; pub mod pick_list;
pub mod progress_bar; pub mod progress_bar;
pub mod radio; pub mod radio;
pub mod rule;
pub mod scrollable; pub mod scrollable;
pub mod slider; pub mod slider;
pub mod text_input; pub mod text_input;
@ -35,6 +36,8 @@ pub use progress_bar::ProgressBar;
#[doc(no_inline)] #[doc(no_inline)]
pub use radio::Radio; pub use radio::Radio;
#[doc(no_inline)] #[doc(no_inline)]
pub use rule::Rule;
#[doc(no_inline)]
pub use scrollable::Scrollable; pub use scrollable::Scrollable;
#[doc(no_inline)] #[doc(no_inline)]
pub use slider::Slider; pub use slider::Slider;

10
wgpu/src/widget/rule.rs Normal file
View File

@ -0,0 +1,10 @@
//! Display a horizontal or vertical rule for dividing content.
use crate::Renderer;
pub use iced_graphics::rule::{FillMode, Style, StyleSheet};
/// Display a horizontal or vertical rule for dividing content.
///
/// This is an alias of an `iced_native` rule with an `iced_wgpu::Renderer`.
pub type Rule = iced_native::Rule<Renderer>;

View File

@ -1,18 +1,23 @@
use crate::{Backend, Color, Renderer, Settings}; use crate::{Backend, Color, Error, Renderer, Settings, Viewport};
use iced_graphics::Viewport; use futures::task::SpawnExt;
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 +25,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,
}) })
} }
@ -64,20 +81,23 @@ impl iced_graphics::window::Compositor for Compositor {
type Surface = wgpu::Surface; type Surface = wgpu::Surface;
type SwapChain = wgpu::SwapChain; type SwapChain = wgpu::SwapChain;
fn new(settings: Self::Settings) -> (Self, Renderer) { fn new(settings: Self::Settings) -> Result<(Self, Renderer), Error> {
let compositor = futures::executor::block_on(Self::request(settings)) let compositor = futures::executor::block_on(Self::request(settings))
.expect("Could not find a suitable graphics adapter"); .ok_or(Error::AdapterNotFound)?;
let backend = compositor.create_backend(); let backend = compositor.create_backend();
(compositor, Renderer::new(backend)) Ok((compositor, Renderer::new(backend)))
} }
fn create_surface<W: HasRawWindowHandle>( fn create_surface<W: HasRawWindowHandle>(
&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,27 +127,30 @@ 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: Some("iced_wgpu encoder"),
},
); );
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 +158,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
} }

View File

@ -17,6 +17,7 @@ debug = ["iced_native/debug"]
winit = "0.22" winit = "0.22"
window_clipboard = "0.1" window_clipboard = "0.1"
log = "0.4" log = "0.4"
thiserror = "1.0"
[dependencies.iced_native] [dependencies.iced_native]
version = "0.2" version = "0.2"
@ -26,5 +27,9 @@ path = "../native"
version = "0.1" version = "0.1"
path = "../graphics" path = "../graphics"
[dependencies.iced_futures]
version = "0.1"
path = "../futures"
[target.'cfg(target_os = "windows")'.dependencies.winapi] [target.'cfg(target_os = "windows")'.dependencies.winapi]
version = "0.3.6" version = "0.3.6"

View File

@ -1,7 +1,9 @@
//! Create interactive, native cross-platform applications. //! Create interactive, native cross-platform applications.
use crate::conversion;
use crate::mouse;
use crate::{ use crate::{
conversion, mouse, Clipboard, Color, Command, Debug, Executor, Mode, Proxy, Clipboard, Color, Command, Debug, Error, Executor, Mode, Proxy, Runtime,
Runtime, Settings, Size, Subscription, Settings, Size, Subscription,
}; };
use iced_graphics::window; use iced_graphics::window;
use iced_graphics::Viewport; use iced_graphics::Viewport;
@ -108,7 +110,8 @@ pub trait Application: Program {
pub fn run<A, E, C>( pub fn run<A, E, C>(
settings: Settings<A::Flags>, settings: Settings<A::Flags>,
compositor_settings: C::Settings, compositor_settings: C::Settings,
) where ) -> Result<(), Error>
where
A: Application + 'static, A: Application + 'static,
E: Executor + 'static, E: Executor + 'static,
C: window::Compositor<Renderer = A::Renderer> + 'static, C: window::Compositor<Renderer = A::Renderer> + 'static,
@ -123,7 +126,7 @@ pub fn run<A, E, C>(
let event_loop = EventLoop::with_user_event(); let event_loop = EventLoop::with_user_event();
let mut runtime = { let mut runtime = {
let executor = E::new().expect("Create executor"); let executor = E::new().map_err(Error::ExecutorCreationFailed)?;
let proxy = Proxy::new(event_loop.create_proxy()); let proxy = Proxy::new(event_loop.create_proxy());
Runtime::new(executor, proxy) Runtime::new(executor, proxy)
@ -145,9 +148,10 @@ pub fn run<A, E, C>(
.window .window
.into_builder(&title, mode, event_loop.primary_monitor()) .into_builder(&title, mode, event_loop.primary_monitor())
.build(&event_loop) .build(&event_loop)
.expect("Open window"); .map_err(Error::WindowCreationFailed)?;
let clipboard = Clipboard::new(&window); let clipboard = Clipboard::new(&window);
// TODO: Encode cursor availability in the type-system
let mut cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0); let mut cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0);
let mut mouse_interaction = mouse::Interaction::default(); let mut mouse_interaction = mouse::Interaction::default();
let mut modifiers = winit::event::ModifiersState::default(); let mut modifiers = winit::event::ModifiersState::default();
@ -159,7 +163,7 @@ pub fn run<A, E, C>(
); );
let mut resized = false; let mut resized = false;
let (mut compositor, mut renderer) = C::new(compositor_settings); let (mut compositor, mut renderer) = C::new(compositor_settings)?;
let surface = compositor.create_surface(&window); let surface = compositor.create_surface(&window);
@ -378,6 +382,10 @@ pub fn handle_window_event(
WindowEvent::CursorMoved { position, .. } => { WindowEvent::CursorMoved { position, .. } => {
*cursor_position = *position; *cursor_position = *position;
} }
WindowEvent::CursorLeft { .. } => {
// TODO: Encode cursor availability in the type-system
*cursor_position = winit::dpi::PhysicalPosition::new(-1.0, -1.0);
}
WindowEvent::ModifiersChanged(new_modifiers) => { WindowEvent::ModifiersChanged(new_modifiers) => {
*modifiers = *new_modifiers; *modifiers = *new_modifiers;
} }

View File

@ -40,6 +40,12 @@ pub fn window_event(
y: position.y as f32, y: position.y as f32,
})) }))
} }
WindowEvent::CursorEntered { .. } => {
Some(Event::Mouse(mouse::Event::CursorEntered))
}
WindowEvent::CursorLeft { .. } => {
Some(Event::Mouse(mouse::Event::CursorLeft))
}
WindowEvent::MouseInput { button, state, .. } => { WindowEvent::MouseInput { button, state, .. } => {
let button = mouse_button(*button); let button = mouse_button(*button);

27
winit/src/error.rs Normal file
View File

@ -0,0 +1,27 @@
use iced_futures::futures;
/// An error that occurred while running an application.
#[derive(Debug, thiserror::Error)]
pub enum Error {
/// The futures executor could not be created.
#[error("the futures executor could not be created")]
ExecutorCreationFailed(futures::io::Error),
/// The application window could not be created.
#[error("the application window could not be created")]
WindowCreationFailed(winit::error::OsError),
/// A suitable graphics adapter or device could not be found.
#[error("a suitable graphics adapter or device could not be found")]
GraphicsAdapterNotFound,
}
impl From<iced_graphics::Error> for Error {
fn from(error: iced_graphics::Error) -> Error {
match error {
iced_graphics::Error::AdapterNotFound => {
Error::GraphicsAdapterNotFound
}
}
}
}

View File

@ -30,11 +30,13 @@ pub mod conversion;
pub mod settings; pub mod settings;
mod clipboard; mod clipboard;
mod error;
mod mode; mod mode;
mod proxy; mod proxy;
pub use application::Application; pub use application::Application;
pub use clipboard::Clipboard; pub use clipboard::Clipboard;
pub use error::Error;
pub use mode::Mode; pub use mode::Mode;
pub use proxy::Proxy; pub use proxy::Proxy;
pub use settings::Settings; pub use settings::Settings;