From 8d68c8584ea99d3974571cd92edcb31999ebb8fa Mon Sep 17 00:00:00 2001 From: Billy Messenger Date: Thu, 13 Aug 2020 12:54:34 -0500 Subject: [PATCH 01/19] widget Rule added --- examples/styling/src/main.rs | 35 ++++++++-- glow/src/widget.rs | 3 + glow/src/widget/rule.rs | 10 +++ graphics/src/widget.rs | 3 + graphics/src/widget/rule.rs | 89 +++++++++++++++++++++++++ native/src/widget.rs | 3 + native/src/widget/rule.rs | 125 +++++++++++++++++++++++++++++++++++ src/widget.rs | 6 +- style/src/lib.rs | 1 + style/src/rule.rs | 51 ++++++++++++++ wgpu/src/widget.rs | 3 + wgpu/src/widget/rule.rs | 10 +++ 12 files changed, 331 insertions(+), 8 deletions(-) create mode 100644 glow/src/widget/rule.rs create mode 100644 graphics/src/widget/rule.rs create mode 100644 native/src/widget/rule.rs create mode 100644 style/src/rule.rs create mode 100644 wgpu/src/widget/rule.rs diff --git a/examples/styling/src/main.rs b/examples/styling/src/main.rs index 63ab9d62..c969526c 100644 --- a/examples/styling/src/main.rs +++ b/examples/styling/src/main.rs @@ -1,7 +1,7 @@ use iced::{ button, scrollable, slider, text_input, Align, Button, Checkbox, Column, - Container, Element, Length, ProgressBar, Radio, Row, Sandbox, Scrollable, - Settings, Slider, Space, Text, TextInput, + Container, Element, Length, ProgressBar, Radio, Row, Rule, Sandbox, + Scrollable, Settings, Slider, Space, Text, TextInput, }; pub fn main() { @@ -113,14 +113,17 @@ impl Sandbox for Styling { .padding(20) .max_width(600) .push(choose_theme) + .push(Rule::horizontal(38).style(self.theme)) .push(Row::new().spacing(10).push(text_input).push(button)) .push(slider) .push(progress_bar) .push( Row::new() .spacing(10) + .height(Length::Units(100)) .align_items(Align::Center) .push(scrollable) + .push(Rule::vertical(38).style(self.theme)) .push(checkbox), ); @@ -136,8 +139,8 @@ impl Sandbox for Styling { mod style { use iced::{ - button, checkbox, container, progress_bar, radio, scrollable, slider, - text_input, + button, checkbox, container, progress_bar, radio, rule, scrollable, + slider, text_input, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -228,6 +231,15 @@ mod style { } } + impl From for Box { + fn from(theme: Theme) -> Self { + match theme { + Theme::Light => Default::default(), + Theme::Dark => dark::Rule.into(), + } + } + } + mod light { use iced::{button, Background, Color, Vector}; @@ -258,7 +270,7 @@ mod style { mod dark { use iced::{ - button, checkbox, container, progress_bar, radio, scrollable, + button, checkbox, container, progress_bar, radio, rule, scrollable, slider, text_input, Background, Color, }; @@ -516,5 +528,18 @@ mod style { } } } + + pub struct Rule; + + impl rule::StyleSheet for Rule { + fn style(&self) -> rule::Style { + rule::Style { + color: SURFACE, + width: 2, + radius: 1, + fill_percent: 90, + } + } + } } } diff --git a/glow/src/widget.rs b/glow/src/widget.rs index 4e2fedc5..0e33909d 100644 --- a/glow/src/widget.rs +++ b/glow/src/widget.rs @@ -16,6 +16,7 @@ pub mod pane_grid; pub mod pick_list; pub mod progress_bar; pub mod radio; +pub mod rule; pub mod scrollable; pub mod slider; pub mod text_input; @@ -35,6 +36,8 @@ pub use progress_bar::ProgressBar; #[doc(no_inline)] pub use radio::Radio; #[doc(no_inline)] +pub use rule::Rule; +#[doc(no_inline)] pub use scrollable::Scrollable; #[doc(no_inline)] pub use slider::Slider; diff --git a/glow/src/widget/rule.rs b/glow/src/widget/rule.rs new file mode 100644 index 00000000..16eaa267 --- /dev/null +++ b/glow/src/widget/rule.rs @@ -0,0 +1,10 @@ +//! Display a horizontal or vertical rule for dividing content. + +use crate::Renderer; + +pub use iced_graphics::rule::{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; diff --git a/graphics/src/widget.rs b/graphics/src/widget.rs index 94a65011..f87b558a 100644 --- a/graphics/src/widget.rs +++ b/graphics/src/widget.rs @@ -15,6 +15,7 @@ pub mod pane_grid; pub mod pick_list; pub mod progress_bar; pub mod radio; +pub mod rule; pub mod scrollable; pub mod slider; pub mod svg; @@ -40,6 +41,8 @@ pub use progress_bar::ProgressBar; #[doc(no_inline)] pub use radio::Radio; #[doc(no_inline)] +pub use rule::Rule; +#[doc(no_inline)] pub use scrollable::Scrollable; #[doc(no_inline)] pub use slider::Slider; diff --git a/graphics/src/widget/rule.rs b/graphics/src/widget/rule.rs new file mode 100644 index 00000000..5ff5197d --- /dev/null +++ b/graphics/src/widget/rule.rs @@ -0,0 +1,89 @@ +//! 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::{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 = iced_native::Rule>; + +impl rule::Renderer for Renderer +where + B: Backend, +{ + type Style = Box; + + 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 (line_x, line_width) = if style.fill_percent >= 100 { + (bounds.x, bounds.width) + } else { + let percent_width = + (bounds.width * style.fill_percent as f32 / 100.0).round(); + ( + bounds.x + ((bounds.width - percent_width) / 2.0).round(), + percent_width, + ) + }; + + 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 (line_y, line_height) = if style.fill_percent >= 100 { + (bounds.y, bounds.height) + } else { + let percent_height = + (bounds.height * style.fill_percent as f32 / 100.0).round(); + ( + bounds.y + ((bounds.height - percent_height) / 2.0).round(), + percent_height, + ) + }; + + 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()) + } +} diff --git a/native/src/widget.rs b/native/src/widget.rs index 8539e519..a10281df 100644 --- a/native/src/widget.rs +++ b/native/src/widget.rs @@ -30,6 +30,7 @@ pub mod pick_list; pub mod progress_bar; pub mod radio; pub mod row; +pub mod rule; pub mod scrollable; pub mod slider; pub mod space; @@ -58,6 +59,8 @@ pub use radio::Radio; #[doc(no_inline)] pub use row::Row; #[doc(no_inline)] +pub use rule::Rule; +#[doc(no_inline)] pub use scrollable::Scrollable; #[doc(no_inline)] pub use slider::Slider; diff --git a/native/src/widget/rule.rs b/native/src/widget/rule.rs new file mode 100644 index 00000000..25cec53b --- /dev/null +++ b/native/src/widget/rule.rs @@ -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 { + width: Length, + height: Length, + style: Renderer::Style, + is_horizontal: bool, +} + +impl Rule { + /// 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) -> Self { + self.style = style.into(); + self + } +} + +impl Widget for Rule +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::().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> + for Element<'a, Message, Renderer> +where + Renderer: 'a + self::Renderer, + Message: 'a, +{ + fn from(rule: Rule) -> Element<'a, Message, Renderer> { + Element::new(rule) + } +} diff --git a/src/widget.rs b/src/widget.rs index b26f14d4..e8fff9cc 100644 --- a/src/widget.rs +++ b/src/widget.rs @@ -20,7 +20,7 @@ mod platform { pub use crate::renderer::widget::{ 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"))] @@ -46,8 +46,8 @@ mod platform { pub use { button::Button, checkbox::Checkbox, container::Container, image::Image, pane_grid::PaneGrid, pick_list::PickList, progress_bar::ProgressBar, - radio::Radio, scrollable::Scrollable, slider::Slider, svg::Svg, - text_input::TextInput, + radio::Radio, rule::Rule, scrollable::Scrollable, slider::Slider, + svg::Svg, text_input::TextInput, }; #[cfg(any(feature = "canvas", feature = "glow_canvas"))] diff --git a/style/src/lib.rs b/style/src/lib.rs index 8e402bb1..3d23d990 100644 --- a/style/src/lib.rs +++ b/style/src/lib.rs @@ -11,6 +11,7 @@ pub mod menu; pub mod pick_list; pub mod progress_bar; pub mod radio; +pub mod rule; pub mod scrollable; pub mod slider; pub mod text_input; diff --git a/style/src/rule.rs b/style/src/rule.rs new file mode 100644 index 00000000..dbd72d41 --- /dev/null +++ b/style/src/rule.rs @@ -0,0 +1,51 @@ +//! Display a horizontal or vertical rule for dividing content. + +use iced_core::Color; + +/// 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 rectangle corners. + pub radius: u16, + /// The percent from [0, 100] of the filled space the rule + /// will be drawn. + pub fill_percent: u16, +} + +/// 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.49].into(), + width: 1, + radius: 0, + fill_percent: 90, + } + } +} + +impl std::default::Default for Box { + fn default() -> Self { + Box::new(Default) + } +} + +impl From for Box +where + T: 'static + StyleSheet, +{ + fn from(style: T) -> Self { + Box::new(style) + } +} diff --git a/wgpu/src/widget.rs b/wgpu/src/widget.rs index ced64332..1dae26f5 100644 --- a/wgpu/src/widget.rs +++ b/wgpu/src/widget.rs @@ -16,6 +16,7 @@ pub mod pane_grid; pub mod pick_list; pub mod progress_bar; pub mod radio; +pub mod rule; pub mod scrollable; pub mod slider; pub mod text_input; @@ -35,6 +36,8 @@ pub use progress_bar::ProgressBar; #[doc(no_inline)] pub use radio::Radio; #[doc(no_inline)] +pub use rule::Rule; +#[doc(no_inline)] pub use scrollable::Scrollable; #[doc(no_inline)] pub use slider::Slider; diff --git a/wgpu/src/widget/rule.rs b/wgpu/src/widget/rule.rs new file mode 100644 index 00000000..630a6f33 --- /dev/null +++ b/wgpu/src/widget/rule.rs @@ -0,0 +1,10 @@ +//! Display a horizontal or vertical rule for dividing content. + +use crate::Renderer; + +pub use iced_graphics::rule::{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; From 32561bd85c6db0d7e6d9d12c87b87f4b50f1d43f Mon Sep 17 00:00:00 2001 From: Billy Messenger Date: Sun, 16 Aug 2020 10:10:32 -0500 Subject: [PATCH 02/19] added FillMode enum style for the Rule widget --- examples/styling/src/main.rs | 2 +- glow/src/widget/rule.rs | 2 +- graphics/src/widget/rule.rs | 101 ++++++++++++++++++++++++++++------- style/src/rule.rs | 28 ++++++++-- wgpu/src/widget/rule.rs | 2 +- 5 files changed, 108 insertions(+), 27 deletions(-) diff --git a/examples/styling/src/main.rs b/examples/styling/src/main.rs index c969526c..0c2cfc57 100644 --- a/examples/styling/src/main.rs +++ b/examples/styling/src/main.rs @@ -537,7 +537,7 @@ mod style { color: SURFACE, width: 2, radius: 1, - fill_percent: 90, + fill_mode: rule::FillMode::Padded(15), } } } diff --git a/glow/src/widget/rule.rs b/glow/src/widget/rule.rs index 16eaa267..faa2be86 100644 --- a/glow/src/widget/rule.rs +++ b/glow/src/widget/rule.rs @@ -2,7 +2,7 @@ use crate::Renderer; -pub use iced_graphics::rule::{Style, StyleSheet}; +pub use iced_graphics::rule::{FillMode, Style, StyleSheet}; /// Display a horizontal or vertical rule for dividing content. /// diff --git a/graphics/src/widget/rule.rs b/graphics/src/widget/rule.rs index 5ff5197d..e058dffe 100644 --- a/graphics/src/widget/rule.rs +++ b/graphics/src/widget/rule.rs @@ -5,7 +5,7 @@ use iced_native::mouse; use iced_native::rule; use iced_native::{Background, Color, Rectangle}; -pub use iced_style::rule::{Style, StyleSheet}; +pub use iced_style::rule::{FillMode, Style, StyleSheet}; /// Display a horizontal or vertical rule for dividing content. /// @@ -31,15 +31,46 @@ where - (style.width as f32 / 2.0)) .round(); - let (line_x, line_width) = if style.fill_percent >= 100 { - (bounds.x, bounds.width) - } else { - let percent_width = - (bounds.width * style.fill_percent as f32 / 100.0).round(); - ( - bounds.x + ((bounds.width - percent_width) / 2.0).round(), - percent_width, - ) + let (line_x, line_width) = match style.fill_mode { + FillMode::Full => (bounds.x, bounds.width), + FillMode::Percent(percent) => { + if percent >= 100.0 { + (bounds.x, bounds.width) + } else { + let percent_width = + (bounds.width * percent / 100.0).round(); + + ( + bounds.x + + ((bounds.width - percent_width) / 2.0) + .round(), + percent_width, + ) + } + } + FillMode::Padded(padding) => { + if padding == 0 { + (bounds.x, bounds.width) + } else { + let padding = padding as f32; + let mut line_width = bounds.width - (padding * 2.0); + if line_width < 0.0 { + line_width = 0.0; + } + + (bounds.x + 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 = bounds.width - first_pad - second_pad; + if line_width < 0.0 { + line_width = 0.0; + } + + (bounds.x + first_pad, line_width) + } }; Primitive::Quad { @@ -59,15 +90,47 @@ where - (style.width as f32 / 2.0)) .round(); - let (line_y, line_height) = if style.fill_percent >= 100 { - (bounds.y, bounds.height) - } else { - let percent_height = - (bounds.height * style.fill_percent as f32 / 100.0).round(); - ( - bounds.y + ((bounds.height - percent_height) / 2.0).round(), - percent_height, - ) + let (line_y, line_height) = match style.fill_mode { + FillMode::Full => (bounds.y, bounds.height), + FillMode::Percent(percent) => { + if percent >= 100.0 { + (bounds.y, bounds.height) + } else { + let percent_height = + (bounds.height * percent / 100.0).round(); + + ( + bounds.y + + ((bounds.height - percent_height) / 2.0) + .round(), + percent_height, + ) + } + } + FillMode::Padded(padding) => { + if padding == 0 { + (bounds.y, bounds.height) + } else { + let padding = padding as f32; + let mut line_height = bounds.height - (padding * 2.0); + if line_height < 0.0 { + line_height = 0.0; + } + + (bounds.y + padding, line_height) + } + } + FillMode::AsymmetricPadding(first_pad, second_pad) => { + let first_pad = first_pad as f32; + let second_pad = second_pad as f32; + let mut line_height = + bounds.height - first_pad - second_pad; + if line_height < 0.0 { + line_height = 0.0; + } + + (bounds.y + first_pad, line_height) + } }; Primitive::Quad { diff --git a/style/src/rule.rs b/style/src/rule.rs index dbd72d41..aa095d3b 100644 --- a/style/src/rule.rs +++ b/style/src/rule.rs @@ -2,6 +2,23 @@ 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), +} + /// The appearance of a rule. #[derive(Debug, Clone, Copy)] pub struct Style { @@ -11,9 +28,10 @@ pub struct Style { pub width: u16, /// The radius of the rectangle corners. pub radius: u16, - /// The percent from [0, 100] of the filled space the rule - /// will be drawn. - pub fill_percent: 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. @@ -27,10 +45,10 @@ struct Default; impl StyleSheet for Default { fn style(&self) -> Style { Style { - color: [0.6, 0.6, 0.6, 0.49].into(), + color: [0.6, 0.6, 0.6, 0.51].into(), width: 1, radius: 0, - fill_percent: 90, + fill_mode: FillMode::Percent(90.0), } } } diff --git a/wgpu/src/widget/rule.rs b/wgpu/src/widget/rule.rs index 630a6f33..3f7bc67a 100644 --- a/wgpu/src/widget/rule.rs +++ b/wgpu/src/widget/rule.rs @@ -2,7 +2,7 @@ use crate::Renderer; -pub use iced_graphics::rule::{Style, StyleSheet}; +pub use iced_graphics::rule::{FillMode, Style, StyleSheet}; /// Display a horizontal or vertical rule for dividing content. /// From fed30ef7753bbe33af026f1f46a09d8381682284 Mon Sep 17 00:00:00 2001 From: Billy Messenger Date: Sun, 16 Aug 2020 19:20:02 -0500 Subject: [PATCH 03/19] added FillMode::fill() --- graphics/src/widget/rule.rs | 87 ++----------------------------------- style/src/rule.rs | 49 ++++++++++++++++++++- 2 files changed, 52 insertions(+), 84 deletions(-) diff --git a/graphics/src/widget/rule.rs b/graphics/src/widget/rule.rs index e058dffe..a7a5d0e7 100644 --- a/graphics/src/widget/rule.rs +++ b/graphics/src/widget/rule.rs @@ -31,47 +31,8 @@ where - (style.width as f32 / 2.0)) .round(); - let (line_x, line_width) = match style.fill_mode { - FillMode::Full => (bounds.x, bounds.width), - FillMode::Percent(percent) => { - if percent >= 100.0 { - (bounds.x, bounds.width) - } else { - let percent_width = - (bounds.width * percent / 100.0).round(); - - ( - bounds.x - + ((bounds.width - percent_width) / 2.0) - .round(), - percent_width, - ) - } - } - FillMode::Padded(padding) => { - if padding == 0 { - (bounds.x, bounds.width) - } else { - let padding = padding as f32; - let mut line_width = bounds.width - (padding * 2.0); - if line_width < 0.0 { - line_width = 0.0; - } - - (bounds.x + 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 = bounds.width - first_pad - second_pad; - if line_width < 0.0 { - line_width = 0.0; - } - - (bounds.x + first_pad, line_width) - } - }; + let (offset, line_width) = style.fill_mode.fill(bounds.width); + let line_x = bounds.x + offset; Primitive::Quad { bounds: Rectangle { @@ -90,48 +51,8 @@ where - (style.width as f32 / 2.0)) .round(); - let (line_y, line_height) = match style.fill_mode { - FillMode::Full => (bounds.y, bounds.height), - FillMode::Percent(percent) => { - if percent >= 100.0 { - (bounds.y, bounds.height) - } else { - let percent_height = - (bounds.height * percent / 100.0).round(); - - ( - bounds.y - + ((bounds.height - percent_height) / 2.0) - .round(), - percent_height, - ) - } - } - FillMode::Padded(padding) => { - if padding == 0 { - (bounds.y, bounds.height) - } else { - let padding = padding as f32; - let mut line_height = bounds.height - (padding * 2.0); - if line_height < 0.0 { - line_height = 0.0; - } - - (bounds.y + padding, line_height) - } - } - FillMode::AsymmetricPadding(first_pad, second_pad) => { - let first_pad = first_pad as f32; - let second_pad = second_pad as f32; - let mut line_height = - bounds.height - first_pad - second_pad; - if line_height < 0.0 { - line_height = 0.0; - } - - (bounds.y + first_pad, line_height) - } - }; + let (offset, line_height) = style.fill_mode.fill(bounds.height); + let line_y = bounds.y + offset; Primitive::Quad { bounds: Rectangle { diff --git a/style/src/rule.rs b/style/src/rule.rs index aa095d3b..6ba54e33 100644 --- a/style/src/rule.rs +++ b/style/src/rule.rs @@ -19,6 +19,53 @@ pub enum FillMode { 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 { @@ -26,7 +73,7 @@ pub struct Style { pub color: Color, /// The width (thickness) of the rule line. pub width: u16, - /// The radius of the rectangle corners. + /// The radius of the line corners. pub radius: u16, /// The [`FillMode`] of the rule. /// From 72f89ba77f45e5345ef863d5e75b99895419f583 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Tue, 25 Aug 2020 01:39:54 +0200 Subject: [PATCH 04/19] Fix cursor position after a `CursorLeft` event --- winit/src/application.rs | 5 +++++ winit/src/conversion.rs | 6 ++++++ 2 files changed, 11 insertions(+) diff --git a/winit/src/application.rs b/winit/src/application.rs index 1fa282a1..73dad398 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -148,6 +148,7 @@ pub fn run( .expect("Open 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 mouse_interaction = mouse::Interaction::default(); let mut modifiers = winit::event::ModifiersState::default(); @@ -378,6 +379,10 @@ pub fn handle_window_event( WindowEvent::CursorMoved { 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) => { *modifiers = *new_modifiers; } diff --git a/winit/src/conversion.rs b/winit/src/conversion.rs index 3a8f54f5..638787ab 100644 --- a/winit/src/conversion.rs +++ b/winit/src/conversion.rs @@ -40,6 +40,12 @@ pub fn window_event( 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, .. } => { let button = mouse_button(*button); From 1b980bc6e823b7e049f5bb86d039e3b7db5ce353 Mon Sep 17 00:00:00 2001 From: Kaiden42 Date: Wed, 19 Aug 2020 01:30:22 +0200 Subject: [PATCH 05/19] Implement From for Option --- core/src/background.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/core/src/background.rs b/core/src/background.rs index e1a37ddc..54a9cad2 100644 --- a/core/src/background.rs +++ b/core/src/background.rs @@ -13,3 +13,9 @@ impl From for Background { Background::Color(color) } } + +impl From for Option { + fn from(color: Color) -> Self { + Some(Background::from(color)) + } +} \ No newline at end of file From f0257949856a9a7edf747684925f85d2ce811198 Mon Sep 17 00:00:00 2001 From: Kaiden42 Date: Wed, 19 Aug 2020 01:30:46 +0200 Subject: [PATCH 06/19] Update styling example Also run `cargo fmt` --- core/src/background.rs | 2 +- examples/styling/src/main.rs | 47 +++++++++++++++--------------------- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/core/src/background.rs b/core/src/background.rs index 54a9cad2..cfb95867 100644 --- a/core/src/background.rs +++ b/core/src/background.rs @@ -18,4 +18,4 @@ impl From for Option { fn from(color: Color) -> Self { Some(Background::from(color)) } -} \ No newline at end of file +} diff --git a/examples/styling/src/main.rs b/examples/styling/src/main.rs index 0c2cfc57..dcbc2744 100644 --- a/examples/styling/src/main.rs +++ b/examples/styling/src/main.rs @@ -241,16 +241,14 @@ mod style { } mod light { - use iced::{button, Background, Color, Vector}; + use iced::{button, Color, Vector}; pub struct Button; impl button::StyleSheet for Button { fn active(&self) -> button::Style { button::Style { - background: Some(Background::Color(Color::from_rgb( - 0.11, 0.42, 0.87, - ))), + background: Color::from_rgb(0.11, 0.42, 0.87).into(), border_radius: 12, shadow_offset: Vector::new(1.0, 1.0), text_color: Color::from_rgb8(0xEE, 0xEE, 0xEE), @@ -271,7 +269,7 @@ mod style { mod dark { use iced::{ button, checkbox, container, progress_bar, radio, rule, scrollable, - slider, text_input, Background, Color, + slider, text_input, Color, }; const SURFACE: Color = Color::from_rgb( @@ -303,10 +301,8 @@ mod style { impl container::StyleSheet for Container { fn style(&self) -> container::Style { container::Style { - background: Some(Background::Color(Color::from_rgb8( - 0x36, 0x39, 0x3F, - ))), - text_color: Some(Color::WHITE), + background: Color::from_rgb8(0x36, 0x39, 0x3F).into(), + text_color: Color::WHITE.into(), ..container::Style::default() } } @@ -317,7 +313,7 @@ mod style { impl radio::StyleSheet for Radio { fn active(&self) -> radio::Style { radio::Style { - background: Background::Color(SURFACE), + background: SURFACE.into(), dot_color: ACTIVE, border_width: 1, border_color: ACTIVE, @@ -326,7 +322,7 @@ mod style { fn hovered(&self) -> radio::Style { radio::Style { - background: Background::Color(Color { a: 0.5, ..SURFACE }), + background: Color { a: 0.5, ..SURFACE }.into(), ..self.active() } } @@ -337,7 +333,7 @@ mod style { impl text_input::StyleSheet for TextInput { fn active(&self) -> text_input::Style { text_input::Style { - background: Background::Color(SURFACE), + background: SURFACE.into(), border_radius: 2, border_width: 0, border_color: Color::TRANSPARENT, @@ -378,7 +374,7 @@ mod style { impl button::StyleSheet for Button { fn active(&self) -> button::Style { button::Style { - background: Some(Background::Color(ACTIVE)), + background: ACTIVE.into(), border_radius: 3, text_color: Color::WHITE, ..button::Style::default() @@ -387,7 +383,7 @@ mod style { fn hovered(&self) -> button::Style { button::Style { - background: Some(Background::Color(HOVERED)), + background: HOVERED.into(), text_color: Color::WHITE, ..self.active() } @@ -407,7 +403,7 @@ mod style { impl scrollable::StyleSheet for Scrollable { fn active(&self) -> scrollable::Scrollbar { scrollable::Scrollbar { - background: Some(Background::Color(SURFACE)), + background: SURFACE.into(), border_radius: 2, border_width: 0, border_color: Color::TRANSPARENT, @@ -424,10 +420,7 @@ mod style { let active = self.active(); scrollable::Scrollbar { - background: Some(Background::Color(Color { - a: 0.5, - ..SURFACE - })), + background: Color { a: 0.5, ..SURFACE }.into(), scroller: scrollable::Scroller { color: HOVERED, ..active.scroller @@ -494,8 +487,8 @@ mod style { impl progress_bar::StyleSheet for ProgressBar { fn style(&self) -> progress_bar::Style { progress_bar::Style { - background: Background::Color(SURFACE), - bar: Background::Color(ACTIVE), + background: SURFACE.into(), + bar: ACTIVE.into(), border_radius: 10, } } @@ -506,11 +499,8 @@ mod style { impl checkbox::StyleSheet for Checkbox { fn active(&self, is_checked: bool) -> checkbox::Style { checkbox::Style { - background: Background::Color(if is_checked { - ACTIVE - } else { - SURFACE - }), + background: if is_checked { ACTIVE } else { SURFACE } + .into(), checkmark_color: Color::WHITE, border_radius: 2, border_width: 1, @@ -520,10 +510,11 @@ mod style { fn hovered(&self, is_checked: bool) -> checkbox::Style { checkbox::Style { - background: Background::Color(Color { + background: Color { a: 0.8, ..if is_checked { ACTIVE } else { SURFACE } - }), + } + .into(), ..self.active(is_checked) } } From 67d90e394678eba94975a19ef51821135373b634 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 13:03:42 +0200 Subject: [PATCH 07/19] Update `wgpu` to `0.6` in `iced_wgpu` --- wgpu/Cargo.toml | 8 +- wgpu/src/backend.rs | 6 + wgpu/src/lib.rs | 2 +- wgpu/src/quad.rs | 125 +++++++++++---------- wgpu/src/text.rs | 2 + wgpu/src/triangle.rs | 199 +++++++++++++++++++--------------- wgpu/src/triangle/msaa.rs | 55 +++++----- wgpu/src/window/compositor.rs | 89 ++++++++++----- 8 files changed, 275 insertions(+), 211 deletions(-) diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml index 6d9a1830..05088bbd 100644 --- a/wgpu/Cargo.toml +++ b/wgpu/Cargo.toml @@ -13,17 +13,15 @@ canvas = ["iced_graphics/canvas"] default_system_font = ["iced_graphics/font-source"] [dependencies] -wgpu = "0.5" -wgpu_glyph = "0.9" +wgpu = "0.6" +wgpu_glyph = "0.10" glyph_brush = "0.7" zerocopy = "0.3" bytemuck = "1.2" raw-window-handle = "0.3" log = "0.4" guillotiere = "0.5" -# Pin `gfx-memory` until https://github.com/gfx-rs/wgpu-rs/issues/261 is -# resolved -gfx-memory = "=0.1.1" +futures = "0.3" [dependencies.iced_native] version = "0.2" diff --git a/wgpu/src/backend.rs b/wgpu/src/backend.rs index c71a6a77..80c982d7 100644 --- a/wgpu/src/backend.rs +++ b/wgpu/src/backend.rs @@ -64,6 +64,7 @@ impl Backend { pub fn draw>( &mut self, device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, frame: &wgpu::TextureView, viewport: &Viewport, @@ -85,6 +86,7 @@ impl Backend { scale_factor, transformation, &layer, + staging_belt, encoder, &frame, target_size.width, @@ -104,6 +106,7 @@ impl Backend { scale_factor: f32, transformation: Transformation, layer: &Layer<'_>, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, target_width: u32, @@ -114,6 +117,7 @@ impl Backend { if !layer.quads.is_empty() { self.quad_pipeline.draw( device, + staging_belt, encoder, &layer.quads, transformation, @@ -129,6 +133,7 @@ impl Backend { self.triangle_pipeline.draw( device, + staging_belt, encoder, target, target_width, @@ -225,6 +230,7 @@ impl Backend { self.text_pipeline.draw_queued( device, + staging_belt, encoder, target, transformation, diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index e51a225c..570e8a94 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -23,7 +23,7 @@ #![deny(missing_docs)] #![deny(missing_debug_implementations)] #![deny(unused_results)] -#![forbid(unsafe_code)] +#![deny(unsafe_code)] #![forbid(rust_2018_idioms)] #![cfg_attr(docsrs, feature(doc_cfg))] diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index 0b62f44f..f8d6c509 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -3,6 +3,7 @@ use iced_graphics::layer; use iced_native::Rectangle; use std::mem; +use wgpu::util::DeviceExt; use zerocopy::AsBytes; #[derive(Debug)] @@ -20,50 +21,54 @@ impl Pipeline { let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[wgpu::BindGroupLayoutEntry { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, 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::() as u64, + ), + }, + count: None, }], }); - let constants_buffer = device.create_buffer_with_data( - Uniforms::default().as_bytes(), - wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, - ); + let constants_buffer = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: Uniforms::default().as_bytes(), + usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, + }); let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &constant_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &constants_buffer, - range: 0..std::mem::size_of::() as u64, - }, + resource: wgpu::BindingResource::Buffer( + constants_buffer.slice(..), + ), }], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + push_constant_ranges: &[], bind_group_layouts: &[&constant_layout], }); - let vs = include_bytes!("shader/quad.vert.spv"); - let vs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&vs[..])) - .expect("Read quad vertex shader as SPIR-V"), - ); + let vs_module = device + .create_shader_module(wgpu::include_spirv!("shader/quad.vert.spv")); - let fs = include_bytes!("shader/quad.frag.spv"); - let fs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&fs[..])) - .expect("Read quad fragment shader as SPIR-V"), - ); + let fs_module = device + .create_shader_module(wgpu::include_spirv!("shader/quad.frag.spv")); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - layout: &layout, + label: None, + layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", @@ -78,6 +83,7 @@ impl Pipeline { depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, + ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { @@ -150,20 +156,25 @@ impl Pipeline { alpha_to_coverage_enabled: false, }); - let vertices = device.create_buffer_with_data( - QUAD_VERTS.as_bytes(), - wgpu::BufferUsage::VERTEX, - ); + let vertices = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: QUAD_VERTS.as_bytes(), + usage: wgpu::BufferUsage::VERTEX, + }); - let indices = device.create_buffer_with_data( - QUAD_INDICES.as_bytes(), - wgpu::BufferUsage::INDEX, - ); + let indices = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: QUAD_INDICES.as_bytes(), + usage: wgpu::BufferUsage::INDEX, + }); let instances = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: mem::size_of::() as u64 * MAX_INSTANCES as u64, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, + mapped_at_creation: false, }); Pipeline { @@ -179,6 +190,7 @@ impl Pipeline { pub fn draw( &mut self, device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, instances: &[layer::Quad], transformation: Transformation, @@ -188,18 +200,18 @@ impl Pipeline { ) { let uniforms = Uniforms::new(transformation, scale); - let constants_buffer = device.create_buffer_with_data( - uniforms.as_bytes(), - wgpu::BufferUsage::COPY_SRC, - ); + { + let mut constants_buffer = staging_belt.write_buffer( + encoder, + &self.constants_buffer, + 0, + wgpu::BufferSize::new(mem::size_of::() as u64) + .unwrap(), + device, + ); - encoder.copy_buffer_to_buffer( - &constants_buffer, - 0, - &self.constants_buffer, - 0, - std::mem::size_of::() as u64, - ); + constants_buffer.copy_from_slice(uniforms.as_bytes()); + } let mut i = 0; let total = instances.len(); @@ -208,19 +220,18 @@ impl Pipeline { let end = (i + MAX_INSTANCES).min(total); let amount = end - i; - let instance_buffer = device.create_buffer_with_data( - bytemuck::cast_slice(&instances[i..end]), - wgpu::BufferUsage::COPY_SRC, - ); + let instance_bytes = bytemuck::cast_slice(&instances[i..end]); - encoder.copy_buffer_to_buffer( - &instance_buffer, - 0, + let mut instance_buffer = staging_belt.write_buffer( + encoder, &self.instances, 0, - (mem::size_of::() * amount) as u64, + wgpu::BufferSize::new(instance_bytes.len() as u64).unwrap(), + device, ); + instance_buffer.copy_from_slice(instance_bytes); + { let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { @@ -228,13 +239,9 @@ impl Pipeline { wgpu::RenderPassColorAttachmentDescriptor { attachment: target, resolve_target: None, - load_op: wgpu::LoadOp::Load, - store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: true, }, }, ], @@ -243,9 +250,9 @@ impl Pipeline { render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, &self.constants, &[]); - render_pass.set_index_buffer(&self.indices, 0, 0); - render_pass.set_vertex_buffer(0, &self.vertices, 0, 0); - render_pass.set_vertex_buffer(1, &self.instances, 0, 0); + render_pass.set_index_buffer(self.indices.slice(..)); + render_pass.set_vertex_buffer(0, self.vertices.slice(..)); + render_pass.set_vertex_buffer(1, self.instances.slice(..)); render_pass.set_scissor_rect( bounds.x, bounds.y, diff --git a/wgpu/src/text.rs b/wgpu/src/text.rs index a7123d39..78999cf8 100644 --- a/wgpu/src/text.rs +++ b/wgpu/src/text.rs @@ -65,6 +65,7 @@ impl Pipeline { pub fn draw_queued( &mut self, device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, transformation: Transformation, @@ -74,6 +75,7 @@ impl Pipeline { .borrow_mut() .draw_queued_with_transform_and_scissoring( device, + staging_belt, encoder, target, transformation.into(), diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index 2744c67a..fcab5e3d 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -8,7 +8,7 @@ pub use iced_graphics::triangle::{Mesh2D, Vertex2D}; mod msaa; -const UNIFORM_BUFFER_SIZE: usize = 100; +const UNIFORM_BUFFER_SIZE: usize = 50; const VERTEX_BUFFER_SIZE: usize = 10_000; const INDEX_BUFFER_SIZE: usize = 10_000; @@ -41,6 +41,7 @@ impl Buffer { label: None, size: (std::mem::size_of::() * size) as u64, usage, + mapped_at_creation: false, }); Buffer { @@ -59,6 +60,7 @@ impl Buffer { label: None, size: (std::mem::size_of::() * size) as u64, usage: self.usage, + mapped_at_creation: false, }); self.size = size; @@ -77,10 +79,16 @@ impl Pipeline { let constants_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[wgpu::BindGroupLayoutEntry { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, 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::() as u64, + ), + }, + count: None, }], }); @@ -94,35 +102,35 @@ impl Pipeline { device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &constants_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &constants_buffer.raw, - range: 0..std::mem::size_of::() as u64, - }, + resource: wgpu::BindingResource::Buffer( + constants_buffer + .raw + .slice(0..std::mem::size_of::() as u64), + ), }], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + push_constant_ranges: &[], bind_group_layouts: &[&constants_layout], }); - let vs = include_bytes!("shader/triangle.vert.spv"); - let vs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&vs[..])) - .expect("Read triangle vertex shader as SPIR-V"), - ); + let vs_module = device.create_shader_module(wgpu::include_spirv!( + "shader/triangle.vert.spv" + )); - let fs = include_bytes!("shader/triangle.frag.spv"); - let fs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&fs[..])) - .expect("Read triangle fragment shader as SPIR-V"), - ); + let fs_module = device.create_shader_module(wgpu::include_spirv!( + "shader/triangle.frag.spv" + )); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - layout: &layout, + label: None, + layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", @@ -137,6 +145,7 @@ impl Pipeline { depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, + ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { @@ -204,6 +213,7 @@ impl Pipeline { pub fn draw( &mut self, device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, target: &wgpu::TextureView, target_width: u32, @@ -236,12 +246,13 @@ impl Pipeline { device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.constants_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &self.uniforms_buffer.raw, - range: 0..std::mem::size_of::() as u64, - }, + resource: wgpu::BindingResource::Buffer( + self.uniforms_buffer.raw.slice( + 0..std::mem::size_of::() as u64, + ), + ), }], }); } @@ -261,65 +272,85 @@ impl Pipeline { * Transformation::translate(mesh.origin.x, mesh.origin.y)) .into(); - let vertex_buffer = device.create_buffer_with_data( - bytemuck::cast_slice(&mesh.buffers.vertices), - wgpu::BufferUsage::COPY_SRC, - ); + let vertices = bytemuck::cast_slice(&mesh.buffers.vertices); + let indices = bytemuck::cast_slice(&mesh.buffers.indices); - let index_buffer = device.create_buffer_with_data( - mesh.buffers.indices.as_bytes(), - wgpu::BufferUsage::COPY_SRC, - ); + if let Some(vertices_size) = + wgpu::BufferSize::new(vertices.len() as u64) + { + if let Some(indices_size) = + wgpu::BufferSize::new(indices.len() as u64) + { + { + let mut vertex_buffer = staging_belt.write_buffer( + encoder, + &self.vertex_buffer.raw, + (std::mem::size_of::() * last_vertex) + as u64, + vertices_size, + device, + ); - encoder.copy_buffer_to_buffer( - &vertex_buffer, - 0, - &self.vertex_buffer.raw, - (std::mem::size_of::() * last_vertex) as u64, - (std::mem::size_of::() * mesh.buffers.vertices.len()) - as u64, - ); + vertex_buffer.copy_from_slice(vertices); + } - encoder.copy_buffer_to_buffer( - &index_buffer, - 0, - &self.index_buffer.raw, - (std::mem::size_of::() * last_index) as u64, - (std::mem::size_of::() * mesh.buffers.indices.len()) - as u64, - ); + { + let mut index_buffer = staging_belt.write_buffer( + encoder, + &self.index_buffer.raw, + (std::mem::size_of::() * last_index) as u64, + indices_size, + device, + ); - uniforms.push(transform); - offsets.push(( - last_vertex as u64, - last_index as u64, - mesh.buffers.indices.len(), - )); + index_buffer.copy_from_slice(indices); + } - last_vertex += mesh.buffers.vertices.len(); - last_index += mesh.buffers.indices.len(); + uniforms.push(transform); + 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( - uniforms.as_bytes(), - wgpu::BufferUsage::COPY_SRC, - ); + let uniforms = uniforms.as_bytes(); - encoder.copy_buffer_to_buffer( - &uniforms_buffer, - 0, - &self.uniforms_buffer.raw, - 0, - (std::mem::size_of::() * uniforms.len()) as u64, - ); + if let Some(uniforms_size) = + wgpu::BufferSize::new(uniforms.len() as u64) + { + let mut uniforms_buffer = staging_belt.write_buffer( + encoder, + &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 { let (attachment, resolve_target) = blit.targets(device, target_width, target_height); - (attachment, Some(resolve_target), wgpu::LoadOp::Clear) + ( + attachment, + Some(resolve_target), + wgpu::LoadOp::Clear(wgpu::Color { + r: 0.0, + g: 0.0, + b: 0.0, + a: 0.0, + }), + ) } else { (target, None, wgpu::LoadOp::Load) }; @@ -330,14 +361,7 @@ impl Pipeline { wgpu::RenderPassColorAttachmentDescriptor { attachment, resolve_target, - load_op, - store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, - }, + ops: wgpu::Operations { load, store: true }, }, ], depth_stencil_attachment: None, @@ -363,20 +387,17 @@ impl Pipeline { &[(std::mem::size_of::() * i) as u32], ); - render_pass.set_index_buffer( - &self.index_buffer.raw, - index_offset * std::mem::size_of::() as u64, - 0, - ); + render_pass.set_index_buffer(self.index_buffer.raw.slice(..)); - render_pass.set_vertex_buffer( - 0, - &self.vertex_buffer.raw, - vertex_offset * std::mem::size_of::() as u64, - 0, - ); + render_pass + .set_vertex_buffer(0, self.vertex_buffer.raw.slice(..)); - render_pass.draw_indexed(0..indices as u32, 0, 0..1); + render_pass.draw_indexed( + index_offset as u32 + ..(index_offset as usize + indices) as u32, + vertex_offset as i32, + 0..1, + ); } } diff --git a/wgpu/src/triangle/msaa.rs b/wgpu/src/triangle/msaa.rs index f52c888b..f25667a5 100644 --- a/wgpu/src/triangle/msaa.rs +++ b/wgpu/src/triangle/msaa.rs @@ -23,18 +23,17 @@ impl Blit { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear, - lod_min_clamp: -100.0, - lod_max_clamp: 100.0, - compare: wgpu::CompareFunction::Always, + ..Default::default() }); let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[wgpu::BindGroupLayoutEntry { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false }, + count: None, }], }); @@ -42,7 +41,7 @@ impl Blit { device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &constant_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::Sampler(&sampler), }], @@ -51,7 +50,7 @@ impl Blit { let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[wgpu::BindGroupLayoutEntry { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::SampledTexture { @@ -59,29 +58,29 @@ impl Blit { component_type: wgpu::TextureComponentType::Float, multisampled: false, }, + count: None, }], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); - let vs = include_bytes!("../shader/blit.vert.spv"); - let vs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&vs[..])) - .expect("Read blit vertex shader as SPIR-V"), - ); + let vs_module = device.create_shader_module(wgpu::include_spirv!( + "../shader/blit.vert.spv" + )); - let fs = include_bytes!("../shader/blit.frag.spv"); - let fs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&fs[..])) - .expect("Read blit fragment shader as SPIR-V"), - ); + let fs_module = device.create_shader_module(wgpu::include_spirv!( + "../shader/blit.frag.spv" + )); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - layout: &layout, + label: None, + layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", @@ -96,6 +95,7 @@ impl Blit { depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, + ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { @@ -179,13 +179,9 @@ impl Blit { wgpu::RenderPassColorAttachmentDescriptor { attachment: target, resolve_target: None, - load_op: wgpu::LoadOp::Load, - store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: true, }, }, ], @@ -230,7 +226,6 @@ impl Targets { let attachment = device.create_texture(&wgpu::TextureDescriptor { label: None, size: extent, - array_layer_count: 1, mip_level_count: 1, sample_count, dimension: wgpu::TextureDimension::D2, @@ -241,7 +236,6 @@ impl Targets { let resolve = device.create_texture(&wgpu::TextureDescriptor { label: None, size: extent, - array_layer_count: 1, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -250,13 +244,16 @@ impl Targets { | wgpu::TextureUsage::SAMPLED, }); - let attachment = attachment.create_default_view(); - let resolve = resolve.create_default_view(); + let attachment = + attachment.create_view(&wgpu::TextureViewDescriptor::default()); + + let resolve = + resolve.create_view(&wgpu::TextureViewDescriptor::default()); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: texture_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&resolve), }], diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index 5bdd34bc..0c94c281 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -1,18 +1,24 @@ use crate::{Backend, Color, Renderer, Settings}; +use futures::task::SpawnExt; use iced_graphics::Viewport; use iced_native::{futures, mouse}; use raw_window_handle::HasRawWindowHandle; /// A window graphics backend for iced powered by `wgpu`. -#[derive(Debug)] +#[allow(missing_debug_implementations)] pub struct Compositor { settings: Settings, + instance: wgpu::Instance, device: wgpu::Device, queue: wgpu::Queue, + staging_belt: wgpu::util::StagingBelt, + local_pool: futures::executor::LocalPool, } impl Compositor { + const CHUNK_SIZE: u64 = 10 * 1024; + /// Requests a new [`Compositor`] with the given [`Settings`]. /// /// Returns `None` if no compatible graphics adapter could be found. @@ -20,32 +26,44 @@ impl Compositor { /// [`Compositor`]: struct.Compositor.html /// [`Settings`]: struct.Settings.html pub async fn request(settings: Settings) -> Option { - let adapter = wgpu::Adapter::request( - &wgpu::RequestAdapterOptions { + let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); + + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { power_preference: if settings.antialiasing.is_none() { wgpu::PowerPreference::Default } else { wgpu::PowerPreference::HighPerformance }, compatible_surface: None, - }, - wgpu::BackendBit::PRIMARY, - ) - .await?; + }) + .await?; let (device, queue) = adapter - .request_device(&wgpu::DeviceDescriptor { - extensions: wgpu::Extensions { - anisotropic_filtering: false, + .request_device( + &wgpu::DeviceDescriptor { + features: wgpu::Features::empty(), + limits: wgpu::Limits { + max_bind_groups: 2, + ..wgpu::Limits::default() + }, + shader_validation: false, }, - limits: wgpu::Limits { max_bind_groups: 2 }, - }) - .await; + None, + ) + .await + .ok()?; + + let staging_belt = wgpu::util::StagingBelt::new(Self::CHUNK_SIZE); + let local_pool = futures::executor::LocalPool::new(); Some(Compositor { + instance, settings, device, queue, + staging_belt, + local_pool, }) } @@ -77,7 +95,10 @@ impl iced_graphics::window::Compositor for Compositor { &mut self, window: &W, ) -> wgpu::Surface { - wgpu::Surface::create(window) + #[allow(unsafe_code)] + unsafe { + self.instance.create_surface(window) + } } fn create_swap_chain( @@ -107,7 +128,7 @@ impl iced_graphics::window::Compositor for Compositor { output: &::Output, overlay: &[T], ) -> 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( &wgpu::CommandEncoderDescriptor { label: None }, @@ -115,19 +136,20 @@ impl iced_graphics::window::Compositor for Compositor { let _ = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { - attachment: &frame.view, + attachment: &frame.output.view, resolve_target: None, - load_op: wgpu::LoadOp::Clear, - store_op: wgpu::StoreOp::Store, - clear_color: { - let [r, g, b, a] = background_color.into_linear(); + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear({ + let [r, g, b, a] = background_color.into_linear(); - wgpu::Color { - r: f64::from(r), - g: f64::from(g), - b: f64::from(b), - a: f64::from(a), - } + wgpu::Color { + r: f64::from(r), + g: f64::from(g), + b: f64::from(b), + a: f64::from(a), + } + }), + store: true, }, }], depth_stencil_attachment: None, @@ -135,14 +157,25 @@ impl iced_graphics::window::Compositor for Compositor { let mouse_interaction = renderer.backend_mut().draw( &mut self.device, + &mut self.staging_belt, &mut encoder, - &frame.view, + &frame.output.view, viewport, output, 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 } From 83e037829c67d010afa1f3318252f2e40535352e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 13:41:00 +0200 Subject: [PATCH 08/19] Update `image` pipeline in `iced_wgpu` --- wgpu/src/backend.rs | 1 + wgpu/src/image.rs | 156 ++++++++++++++++++++++------------------ wgpu/src/image/atlas.rs | 76 +++++++++++++++----- 3 files changed, 146 insertions(+), 87 deletions(-) diff --git a/wgpu/src/backend.rs b/wgpu/src/backend.rs index 80c982d7..819d65c7 100644 --- a/wgpu/src/backend.rs +++ b/wgpu/src/backend.rs @@ -152,6 +152,7 @@ impl Backend { self.image_pipeline.draw( device, + staging_belt, encoder, &layer.images, scaled, diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 49f1d29c..cd756c1e 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -42,6 +42,8 @@ pub struct Pipeline { impl Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + use wgpu::util::DeviceExt; + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { address_mode_u: wgpu::AddressMode::ClampToEdge, address_mode_v: wgpu::AddressMode::ClampToEdge, @@ -49,24 +51,29 @@ impl Pipeline { mag_filter: wgpu::FilterMode::Linear, min_filter: wgpu::FilterMode::Linear, mipmap_filter: wgpu::FilterMode::Linear, - lod_min_clamp: -100.0, - lod_max_clamp: 100.0, - compare: wgpu::CompareFunction::Always, + ..Default::default() }); let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[ + entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, 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::() as u64, + ), + }, + count: None, }, wgpu::BindGroupLayoutEntry { binding: 1, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::Sampler { comparison: false }, + count: None, }, ], }); @@ -75,24 +82,25 @@ impl Pipeline { transform: Transformation::identity().into(), }; - let uniforms_buffer = device.create_buffer_with_data( - uniforms.as_bytes(), - wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, - ); + let uniforms_buffer = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: uniforms.as_bytes(), + usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, + }); let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &constant_layout, - bindings: &[ - wgpu::Binding { + entries: &[ + wgpu::BindGroupEntry { binding: 0, - resource: wgpu::BindingResource::Buffer { - buffer: &uniforms_buffer, - range: 0..std::mem::size_of::() as u64, - }, + resource: wgpu::BindingResource::Buffer( + uniforms_buffer.slice(..), + ), }, - wgpu::Binding { + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&sampler), }, @@ -102,7 +110,7 @@ impl Pipeline { let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: None, - bindings: &[wgpu::BindGroupLayoutEntry { + entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, ty: wgpu::BindingType::SampledTexture { @@ -110,29 +118,29 @@ impl Pipeline { component_type: wgpu::TextureComponentType::Float, multisampled: false, }, + count: None, }], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); - let vs = include_bytes!("shader/image.vert.spv"); - let vs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&vs[..])) - .expect("Read image vertex shader as SPIR-V"), - ); + let vs_module = device.create_shader_module(wgpu::include_spirv!( + "shader/image.vert.spv" + )); - let fs = include_bytes!("shader/image.frag.spv"); - let fs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&fs[..])) - .expect("Read image fragment shader as SPIR-V"), - ); + let fs_module = device.create_shader_module(wgpu::include_spirv!( + "shader/image.frag.spv" + )); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - layout: &layout, + label: None, + layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", @@ -147,6 +155,7 @@ impl Pipeline { depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, + ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { @@ -214,20 +223,25 @@ impl Pipeline { alpha_to_coverage_enabled: false, }); - let vertices = device.create_buffer_with_data( - QUAD_VERTS.as_bytes(), - wgpu::BufferUsage::VERTEX, - ); + let vertices = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: QUAD_VERTS.as_bytes(), + usage: wgpu::BufferUsage::VERTEX, + }); - let indices = device.create_buffer_with_data( - QUAD_INDICES.as_bytes(), - wgpu::BufferUsage::INDEX, - ); + let indices = + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: QUAD_INDICES.as_bytes(), + usage: wgpu::BufferUsage::INDEX, + }); let instances = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: mem::size_of::() as u64 * Instance::MAX as u64, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, + mapped_at_creation: false, }); let texture_atlas = Atlas::new(device); @@ -235,7 +249,7 @@ impl Pipeline { let texture = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &texture_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView( &texture_atlas.view(), @@ -282,6 +296,7 @@ impl Pipeline { pub fn draw( &mut self, device: &wgpu::Device, + staging_belt: &mut wgpu::util::StagingBelt, encoder: &mut wgpu::CommandEncoder, images: &[layer::Image], transformation: Transformation, @@ -356,7 +371,7 @@ impl Pipeline { device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.texture_layout, - bindings: &[wgpu::Binding { + entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView( &self.texture_atlas.view(), @@ -367,26 +382,23 @@ impl Pipeline { self.texture_version = texture_version; } - let uniforms_buffer = device.create_buffer_with_data( - Uniforms { - transform: transformation.into(), - } - .as_bytes(), - wgpu::BufferUsage::COPY_SRC, - ); + { + let mut uniforms_buffer = staging_belt.write_buffer( + encoder, + &self.uniforms, + 0, + wgpu::BufferSize::new(mem::size_of::() as u64) + .unwrap(), + device, + ); - encoder.copy_buffer_to_buffer( - &uniforms_buffer, - 0, - &self.uniforms, - 0, - std::mem::size_of::() as u64, - ); - - let instances_buffer = device.create_buffer_with_data( - instances.as_bytes(), - wgpu::BufferUsage::COPY_SRC, - ); + uniforms_buffer.copy_from_slice( + Uniforms { + transform: transformation.into(), + } + .as_bytes(), + ); + } let mut i = 0; let total = instances.len(); @@ -395,27 +407,29 @@ impl Pipeline { let end = (i + Instance::MAX).min(total); let amount = end - i; - encoder.copy_buffer_to_buffer( - &instances_buffer, - (i * std::mem::size_of::()) as u64, + let mut instances_buffer = staging_belt.write_buffer( + encoder, &self.instances, 0, - (amount * std::mem::size_of::()) as u64, + wgpu::BufferSize::new( + (amount * std::mem::size_of::()) as u64, + ) + .unwrap(), + device, ); + instances_buffer + .copy_from_slice(instances[i..i + amount].as_bytes()); + let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { color_attachments: &[ wgpu::RenderPassColorAttachmentDescriptor { attachment: target, resolve_target: None, - load_op: wgpu::LoadOp::Load, - store_op: wgpu::StoreOp::Store, - clear_color: wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: true, }, }, ], @@ -425,9 +439,9 @@ impl Pipeline { render_pass.set_pipeline(&self.pipeline); render_pass.set_bind_group(0, &self.constants, &[]); render_pass.set_bind_group(1, &self.texture, &[]); - render_pass.set_index_buffer(&self.indices, 0, 0); - render_pass.set_vertex_buffer(0, &self.vertices, 0, 0); - render_pass.set_vertex_buffer(1, &self.instances, 0, 0); + render_pass.set_index_buffer(self.indices.slice(..)); + render_pass.set_vertex_buffer(0, self.vertices.slice(..)); + render_pass.set_vertex_buffer(1, self.instances.slice(..)); render_pass.set_scissor_rect( bounds.x, diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index 3ce3ce8b..99e9995f 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -30,7 +30,6 @@ impl Atlas { let texture = device.create_texture(&wgpu::TextureDescriptor { label: None, size: extent, - array_layer_count: 2, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -40,7 +39,10 @@ impl Atlas { | 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 { texture, @@ -65,6 +67,8 @@ impl Atlas { device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, ) -> Option { + use wgpu::util::DeviceExt; + let entry = { let current_size = self.layers.len(); let entry = self.allocate(width, height)?; @@ -78,8 +82,31 @@ impl Atlas { 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 = - device.create_buffer_with_data(data, wgpu::BufferUsage::COPY_SRC); + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: &padded_data, + usage: wgpu::BufferUsage::COPY_SRC, + }); match &entry { Entry::Contiguous(allocation) => { @@ -87,6 +114,7 @@ impl Atlas { &buffer, width, height, + padding, 0, &allocation, encoder, @@ -95,12 +123,13 @@ impl Atlas { Entry::Fragmented { fragments, .. } => { for fragment in fragments { let (x, y) = fragment.position; - let offset = (y * width + x) as usize * 4; + let offset = (y * padded_width as u32 + x) as usize * 4; self.upload_allocation( &buffer, width, height, + padding, offset, &fragment.allocation, encoder, @@ -253,6 +282,7 @@ impl Atlas { buffer: &wgpu::Buffer, image_width: u32, image_height: u32, + padding: u32, offset: usize, allocation: &Allocation, encoder: &mut wgpu::CommandEncoder, @@ -270,15 +300,20 @@ impl Atlas { encoder.copy_buffer_to_texture( wgpu::BufferCopyView { buffer, - offset: offset as u64, - bytes_per_row: 4 * image_width, - rows_per_image: image_height, + layout: wgpu::TextureDataLayout { + offset: offset as u64, + bytes_per_row: 4 * image_width + padding, + rows_per_image: image_height, + }, }, wgpu::TextureCopyView { texture: &self.texture, - array_layer: layer as u32, mip_level: 0, - origin: wgpu::Origin3d { x, y, z: 0 }, + origin: wgpu::Origin3d { + x, + y, + z: layer as u32, + }, }, extent, ); @@ -299,9 +334,8 @@ impl Atlas { size: wgpu::Extent3d { width: SIZE, height: SIZE, - depth: 1, + depth: self.layers.len() as u32, }, - array_layer_count: self.layers.len() as u32, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -323,15 +357,21 @@ impl Atlas { encoder.copy_texture_to_texture( wgpu::TextureCopyView { texture: &self.texture, - array_layer: i as u32, 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 { texture: &new_texture, - array_layer: i as u32, 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 { width: SIZE, @@ -342,6 +382,10 @@ impl Atlas { } 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() + }); } } From ecbee66bd652228204568c17dd5e8a97b0a59ee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 14:44:51 +0200 Subject: [PATCH 09/19] Fix `layers` initialization in `image::Atlas` --- wgpu/src/image/atlas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index 99e9995f..8d110fc4 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -47,7 +47,7 @@ impl Atlas { Atlas { texture, texture_view, - layers: vec![Layer::Empty, Layer::Empty], + layers: vec![Layer::Empty], } } From bb5f034e08c46e5ce46ed0e38a684c5ca710cb11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 14:45:08 +0200 Subject: [PATCH 10/19] Fix `offset` calculation in `image::Atlas` --- wgpu/src/image/atlas.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index 8d110fc4..69f872e8 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -123,7 +123,7 @@ impl Atlas { Entry::Fragmented { fragments, .. } => { for fragment in fragments { let (x, y) = fragment.position; - let offset = (y * padded_width as u32 + x) as usize * 4; + let offset = (y * padded_width as u32 + 4 * x) as usize; self.upload_allocation( &buffer, From bae0a3e46e6f4f21ef8c6c8e9035efb7c87a9449 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 14:55:41 +0200 Subject: [PATCH 11/19] Update `wgpu` in `integration` example --- examples/integration/src/main.rs | 58 ++++++++++++++++++++----------- examples/integration/src/scene.rs | 40 ++++++++++----------- 2 files changed, 58 insertions(+), 40 deletions(-) diff --git a/examples/integration/src/main.rs b/examples/integration/src/main.rs index 33d4c361..9b52f3a5 100644 --- a/examples/integration/src/main.rs +++ b/examples/integration/src/main.rs @@ -7,6 +7,7 @@ use scene::Scene; use iced_wgpu::{wgpu, Backend, Renderer, Settings, Viewport}; use iced_winit::{conversion, futures, program, winit, Debug, Size}; +use futures::task::SpawnExt; use winit::{ dpi::PhysicalPosition, event::{Event, ModifiersState, WindowEvent}, @@ -29,26 +30,29 @@ pub fn main() { let mut modifiers = ModifiersState::default(); // 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 adapter = wgpu::Adapter::request( - &wgpu::RequestAdapterOptions { + let adapter = instance + .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::Default, compatible_surface: Some(&surface), - }, - wgpu::BackendBit::PRIMARY, - ) - .await - .expect("Request adapter"); - - adapter - .request_device(&wgpu::DeviceDescriptor { - extensions: wgpu::Extensions { - anisotropic_filtering: false, - }, - limits: wgpu::Limits::default(), }) .await + .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; @@ -69,6 +73,10 @@ pub fn main() { }; 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 let scene = Scene::new(&mut device); let controls = Controls::new(); @@ -160,7 +168,7 @@ pub fn main() { 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( &wgpu::CommandEncoderDescriptor { label: None }, @@ -171,7 +179,7 @@ pub fn main() { { // We clear the frame let mut render_pass = scene.clear( - &frame.view, + &frame.output.view, &mut encoder, program.background_color(), ); @@ -183,22 +191,32 @@ pub fn main() { // And then iced on top let mouse_interaction = renderer.backend_mut().draw( &mut device, + &mut staging_belt, &mut encoder, - &frame.view, + &frame.output.view, &viewport, state.primitive(), &debug.overlay(), ); // 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( iced_winit::conversion::mouse_interaction( mouse_interaction, ), ); + + // And recall staging buffers + local_pool + .spawner() + .spawn(staging_belt.recall()) + .expect("Recall staging buffers"); + + local_pool.run_until_stalled(); } _ => {} } diff --git a/examples/integration/src/scene.rs b/examples/integration/src/scene.rs index 74cbb925..67a40eab 100644 --- a/examples/integration/src/scene.rs +++ b/examples/integration/src/scene.rs @@ -22,17 +22,18 @@ impl Scene { color_attachments: &[wgpu::RenderPassColorAttachmentDescriptor { attachment: target, resolve_target: None, - load_op: wgpu::LoadOp::Clear, - store_op: wgpu::StoreOp::Store, - clear_color: { - let [r, g, b, a] = background_color.into_linear(); + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear({ + let [r, g, b, a] = background_color.into_linear(); - wgpu::Color { - r: r as f64, - g: g as f64, - b: b as f64, - a: a as f64, - } + wgpu::Color { + r: r as f64, + g: g as f64, + b: b as f64, + a: a as f64, + } + }), + store: true, }, }], depth_stencil_attachment: None, @@ -46,25 +47,23 @@ impl Scene { } fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline { - let vs = include_bytes!("shader/vert.spv"); - let fs = include_bytes!("shader/frag.spv"); + let vs_module = + device.create_shader_module(wgpu::include_spirv!("shader/vert.spv")); - let vs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&vs[..])).unwrap(), - ); - - let fs_module = device.create_shader_module( - &wgpu::read_spirv(std::io::Cursor::new(&fs[..])).unwrap(), - ); + let fs_module = + device.create_shader_module(wgpu::include_spirv!("shader/frag.spv")); let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: None, + push_constant_ranges: &[], bind_group_layouts: &[], }); let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - layout: &pipeline_layout, + label: None, + layout: Some(&pipeline_layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, entry_point: "main", @@ -79,6 +78,7 @@ fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline { depth_bias: 0, depth_bias_slope_scale: 0.0, depth_bias_clamp: 0.0, + ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, color_states: &[wgpu::ColorStateDescriptor { From b689778ed94b34706bf97e5994a721a8648386a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 19:15:05 +0200 Subject: [PATCH 12/19] Remove redundant depth bias fields in `iced_wgpu` --- examples/integration/src/scene.rs | 3 --- wgpu/src/image.rs | 3 --- wgpu/src/quad.rs | 3 --- wgpu/src/triangle.rs | 3 --- wgpu/src/triangle/msaa.rs | 3 --- 5 files changed, 15 deletions(-) diff --git a/examples/integration/src/scene.rs b/examples/integration/src/scene.rs index 67a40eab..03a338c6 100644 --- a/examples/integration/src/scene.rs +++ b/examples/integration/src/scene.rs @@ -75,9 +75,6 @@ fn build_pipeline(device: &wgpu::Device) -> wgpu::RenderPipeline { rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Ccw, cull_mode: wgpu::CullMode::None, - depth_bias: 0, - depth_bias_slope_scale: 0.0, - depth_bias_clamp: 0.0, ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index cd756c1e..3a08662a 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -152,9 +152,6 @@ impl Pipeline { rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Cw, cull_mode: wgpu::CullMode::None, - depth_bias: 0, - depth_bias_slope_scale: 0.0, - depth_bias_clamp: 0.0, ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index f8d6c509..a115fa73 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -80,9 +80,6 @@ impl Pipeline { rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Cw, cull_mode: wgpu::CullMode::None, - depth_bias: 0, - depth_bias_slope_scale: 0.0, - depth_bias_clamp: 0.0, ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index fcab5e3d..d06e29c0 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -142,9 +142,6 @@ impl Pipeline { rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Cw, cull_mode: wgpu::CullMode::None, - depth_bias: 0, - depth_bias_slope_scale: 0.0, - depth_bias_clamp: 0.0, ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, diff --git a/wgpu/src/triangle/msaa.rs b/wgpu/src/triangle/msaa.rs index f25667a5..14560281 100644 --- a/wgpu/src/triangle/msaa.rs +++ b/wgpu/src/triangle/msaa.rs @@ -92,9 +92,6 @@ impl Blit { rasterization_state: Some(wgpu::RasterizationStateDescriptor { front_face: wgpu::FrontFace::Cw, cull_mode: wgpu::CullMode::None, - depth_bias: 0, - depth_bias_slope_scale: 0.0, - depth_bias_clamp: 0.0, ..Default::default() }), primitive_topology: wgpu::PrimitiveTopology::TriangleList, From 3eb63762c72ccd91717d4feb98128aa12cc1b126 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 19:28:03 +0200 Subject: [PATCH 13/19] Remove unnecessary `create_buffer_init` for uniforms --- wgpu/src/image.rs | 16 ++++++---------- wgpu/src/quad.rs | 12 ++++++------ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 3a08662a..814eefea 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -78,16 +78,12 @@ impl Pipeline { ], }); - let uniforms = Uniforms { - transform: Transformation::identity().into(), - }; - - let uniforms_buffer = - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, - contents: uniforms.as_bytes(), - usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, - }); + let uniforms_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: mem::size_of::() as u64, + usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, + mapped_at_creation: false, + }); let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index a115fa73..0c54db15 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -34,12 +34,12 @@ impl Pipeline { }], }); - let constants_buffer = - device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, - contents: Uniforms::default().as_bytes(), - usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, - }); + let constants_buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: mem::size_of::() as u64, + usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, + mapped_at_creation: false, + }); let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, From 8d605be4e3e0b678c7563708ea941d6188f45678 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 19:30:56 +0200 Subject: [PATCH 14/19] Use `wgpu::Color::TRANSPARENT` --- wgpu/src/triangle.rs | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index d06e29c0..a5789a61 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -341,12 +341,7 @@ impl Pipeline { ( attachment, Some(resolve_target), - wgpu::LoadOp::Clear(wgpu::Color { - r: 0.0, - g: 0.0, - b: 0.0, - a: 0.0, - }), + wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), ) } else { (target, None, wgpu::LoadOp::Load) From 7559e4fb30a282271717f700cb6e420cdf6123f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 19:35:24 +0200 Subject: [PATCH 15/19] Set offsets in buffer slices in `iced_wgpu` --- wgpu/src/triangle.rs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index a5789a61..6ae46cba 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -379,17 +379,20 @@ impl Pipeline { &[(std::mem::size_of::() * i) as u32], ); - render_pass.set_index_buffer(self.index_buffer.raw.slice(..)); - - render_pass - .set_vertex_buffer(0, self.vertex_buffer.raw.slice(..)); - - render_pass.draw_indexed( - index_offset as u32 - ..(index_offset as usize + indices) as u32, - vertex_offset as i32, - 0..1, + render_pass.set_index_buffer( + self.index_buffer + .raw + .slice(index_offset * mem::size_of::() as u64..), ); + + render_pass.set_vertex_buffer( + 0, + self.vertex_buffer.raw.slice( + vertex_offset * mem::size_of::() as u64.., + ), + ); + + render_pass.draw_indexed(0..indices as u32, 0, 0..1); } } From 07880c392c865d700cbaff7601c1fffd3354dd4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Thu, 27 Aug 2020 19:40:42 +0200 Subject: [PATCH 16/19] Turn consecutive if-lets into pattern match --- wgpu/src/triangle.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index 6ae46cba..ed6af0ff 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -272,12 +272,11 @@ impl Pipeline { let vertices = bytemuck::cast_slice(&mesh.buffers.vertices); let indices = bytemuck::cast_slice(&mesh.buffers.indices); - if let Some(vertices_size) = - wgpu::BufferSize::new(vertices.len() as u64) - { - if let Some(indices_size) = - wgpu::BufferSize::new(indices.len() as u64) - { + match ( + wgpu::BufferSize::new(vertices.len() as u64), + wgpu::BufferSize::new(indices.len() as u64), + ) { + (Some(vertices_size), Some(indices_size)) => { { let mut vertex_buffer = staging_belt.write_buffer( encoder, @@ -313,6 +312,7 @@ impl Pipeline { last_vertex += mesh.buffers.vertices.len(); last_index += mesh.buffers.indices.len(); } + _ => {} } } From 44118263b5de7bc32f6280ee3d1dc170a9b034d3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Mon, 31 Aug 2020 14:41:41 +0200 Subject: [PATCH 17/19] Add labels to `iced_wgpu` internals --- wgpu/src/image.rs | 22 +++++++++++----------- wgpu/src/image/atlas.rs | 6 +++--- wgpu/src/quad.rs | 16 ++++++++-------- wgpu/src/triangle.rs | 20 +++++++++++++------- wgpu/src/triangle/msaa.rs | 16 ++++++++-------- wgpu/src/window/compositor.rs | 4 +++- 6 files changed, 46 insertions(+), 38 deletions(-) diff --git a/wgpu/src/image.rs b/wgpu/src/image.rs index 814eefea..891dba1e 100644 --- a/wgpu/src/image.rs +++ b/wgpu/src/image.rs @@ -56,7 +56,7 @@ impl Pipeline { let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::image constants layout"), entries: &[ wgpu::BindGroupLayoutEntry { binding: 0, @@ -79,7 +79,7 @@ impl Pipeline { }); let uniforms_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some("iced_wgpu::image uniforms buffer"), size: mem::size_of::() as u64, usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, @@ -87,7 +87,7 @@ impl Pipeline { let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::image constants bind group"), layout: &constant_layout, entries: &[ wgpu::BindGroupEntry { @@ -105,7 +105,7 @@ impl Pipeline { let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::image texture atlas layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, @@ -120,7 +120,7 @@ impl Pipeline { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: None, + label: Some("iced_wgpu::image pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); @@ -135,7 +135,7 @@ impl Pipeline { let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: None, + label: Some("iced_wgpu::image pipeline"), layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, @@ -218,20 +218,20 @@ impl Pipeline { let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, + label: Some("iced_wgpu::image vertex buffer"), contents: QUAD_VERTS.as_bytes(), usage: wgpu::BufferUsage::VERTEX, }); let indices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, + label: Some("iced_wgpu::image index buffer"), contents: QUAD_INDICES.as_bytes(), usage: wgpu::BufferUsage::INDEX, }); let instances = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some("iced_wgpu::image instance buffer"), size: mem::size_of::() as u64 * Instance::MAX as u64, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, @@ -240,7 +240,7 @@ impl Pipeline { let texture_atlas = Atlas::new(device); let texture = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::image texture atlas bind group"), layout: &texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, @@ -362,7 +362,7 @@ impl Pipeline { self.texture = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::image texture atlas bind group"), layout: &self.texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, diff --git a/wgpu/src/image/atlas.rs b/wgpu/src/image/atlas.rs index 69f872e8..660ebe44 100644 --- a/wgpu/src/image/atlas.rs +++ b/wgpu/src/image/atlas.rs @@ -28,7 +28,7 @@ impl Atlas { }; let texture = device.create_texture(&wgpu::TextureDescriptor { - label: None, + label: Some("iced_wgpu::image texture atlas"), size: extent, mip_level_count: 1, sample_count: 1, @@ -103,7 +103,7 @@ impl Atlas { let buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, + label: Some("iced_wgpu::image staging buffer"), contents: &padded_data, usage: wgpu::BufferUsage::COPY_SRC, }); @@ -330,7 +330,7 @@ impl Atlas { } let new_texture = device.create_texture(&wgpu::TextureDescriptor { - label: None, + label: Some("iced_wgpu::image texture atlas"), size: wgpu::Extent3d { width: SIZE, height: SIZE, diff --git a/wgpu/src/quad.rs b/wgpu/src/quad.rs index 0c54db15..d54f2577 100644 --- a/wgpu/src/quad.rs +++ b/wgpu/src/quad.rs @@ -20,7 +20,7 @@ impl Pipeline { pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Pipeline { let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::quad uniforms layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX, @@ -35,14 +35,14 @@ impl Pipeline { }); let constants_buffer = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some("iced_wgpu::quad uniforms buffer"), size: mem::size_of::() as u64, usage: wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, }); let constants = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::quad uniforms bind group"), layout: &constant_layout, entries: &[wgpu::BindGroupEntry { binding: 0, @@ -54,7 +54,7 @@ impl Pipeline { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: None, + label: Some("iced_wgpu::quad pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constant_layout], }); @@ -67,7 +67,7 @@ impl Pipeline { let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: None, + label: Some("iced_wgpu::quad pipeline"), layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, @@ -155,20 +155,20 @@ impl Pipeline { let vertices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, + label: Some("iced_wgpu::quad vertex buffer"), contents: QUAD_VERTS.as_bytes(), usage: wgpu::BufferUsage::VERTEX, }); let indices = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { - label: None, + label: Some("iced_wgpu::quad index buffer"), contents: QUAD_INDICES.as_bytes(), usage: wgpu::BufferUsage::INDEX, }); let instances = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some("iced_wgpu::quad instance buffer"), size: mem::size_of::() as u64 * MAX_INSTANCES as u64, usage: wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, mapped_at_creation: false, diff --git a/wgpu/src/triangle.rs b/wgpu/src/triangle.rs index ed6af0ff..53ce454b 100644 --- a/wgpu/src/triangle.rs +++ b/wgpu/src/triangle.rs @@ -25,6 +25,7 @@ pub(crate) struct Pipeline { #[derive(Debug)] struct Buffer { + label: &'static str, raw: wgpu::Buffer, size: usize, usage: wgpu::BufferUsage, @@ -33,18 +34,20 @@ struct Buffer { impl Buffer { pub fn new( + label: &'static str, device: &wgpu::Device, size: usize, usage: wgpu::BufferUsage, ) -> Self { let raw = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some(label), size: (std::mem::size_of::() * size) as u64, usage, mapped_at_creation: false, }); Buffer { + label, raw, size, usage, @@ -57,7 +60,7 @@ impl Buffer { if needs_resize { self.raw = device.create_buffer(&wgpu::BufferDescriptor { - label: None, + label: Some(self.label), size: (std::mem::size_of::() * size) as u64, usage: self.usage, mapped_at_creation: false, @@ -78,7 +81,7 @@ impl Pipeline { ) -> Pipeline { let constants_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::triangle uniforms layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::VERTEX, @@ -93,6 +96,7 @@ impl Pipeline { }); let constants_buffer = Buffer::new( + "iced_wgpu::triangle uniforms buffer", device, UNIFORM_BUFFER_SIZE, wgpu::BufferUsage::UNIFORM | wgpu::BufferUsage::COPY_DST, @@ -100,7 +104,7 @@ impl Pipeline { let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::triangle uniforms bind group"), layout: &constants_layout, entries: &[wgpu::BindGroupEntry { binding: 0, @@ -114,7 +118,7 @@ impl Pipeline { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: None, + label: Some("iced_wgpu::triangle pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constants_layout], }); @@ -129,7 +133,7 @@ impl Pipeline { let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: None, + label: Some("iced_wgpu::triangle pipeline"), layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, @@ -195,11 +199,13 @@ impl Pipeline { constants: constant_bind_group, uniforms_buffer: constants_buffer, vertex_buffer: Buffer::new( + "iced_wgpu::triangle vertex buffer", device, VERTEX_BUFFER_SIZE, wgpu::BufferUsage::VERTEX | wgpu::BufferUsage::COPY_DST, ), index_buffer: Buffer::new( + "iced_wgpu::triangle index buffer", device, INDEX_BUFFER_SIZE, wgpu::BufferUsage::INDEX | wgpu::BufferUsage::COPY_DST, @@ -241,7 +247,7 @@ impl Pipeline { if self.uniforms_buffer.expand(device, meshes.len()) { self.constants = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::triangle uniforms buffer"), layout: &self.constants_layout, entries: &[wgpu::BindGroupEntry { binding: 0, diff --git a/wgpu/src/triangle/msaa.rs b/wgpu/src/triangle/msaa.rs index 14560281..db86f748 100644 --- a/wgpu/src/triangle/msaa.rs +++ b/wgpu/src/triangle/msaa.rs @@ -28,7 +28,7 @@ impl Blit { let constant_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::triangle:msaa uniforms layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, @@ -39,7 +39,7 @@ impl Blit { let constant_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa uniforms bind group"), layout: &constant_layout, entries: &[wgpu::BindGroupEntry { binding: 0, @@ -49,7 +49,7 @@ impl Blit { let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa texture layout"), entries: &[wgpu::BindGroupLayoutEntry { binding: 0, visibility: wgpu::ShaderStage::FRAGMENT, @@ -64,7 +64,7 @@ impl Blit { let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa pipeline layout"), push_constant_ranges: &[], bind_group_layouts: &[&constant_layout, &texture_layout], }); @@ -79,7 +79,7 @@ impl Blit { let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa pipeline"), layout: Some(&layout), vertex_stage: wgpu::ProgrammableStageDescriptor { module: &vs_module, @@ -221,7 +221,7 @@ impl Targets { }; let attachment = device.create_texture(&wgpu::TextureDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa attachment"), size: extent, mip_level_count: 1, sample_count, @@ -231,7 +231,7 @@ impl Targets { }); let resolve = device.create_texture(&wgpu::TextureDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa resolve target"), size: extent, mip_level_count: 1, sample_count: 1, @@ -248,7 +248,7 @@ impl Targets { resolve.create_view(&wgpu::TextureViewDescriptor::default()); let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: None, + label: Some("iced_wgpu::triangle::msaa texture bind group"), layout: texture_layout, entries: &[wgpu::BindGroupEntry { binding: 0, diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index 0c94c281..c790f35f 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -131,7 +131,9 @@ impl iced_graphics::window::Compositor for Compositor { let frame = swap_chain.get_current_frame().expect("Next frame"); 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 { From f6dda3b2f584e0bfd7071bde9aaadc81b3bc9c4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Sun, 6 Sep 2020 15:02:55 +0200 Subject: [PATCH 18/19] Fix `Radio` border radius when using custom size --- graphics/src/widget/radio.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/graphics/src/widget/radio.rs b/graphics/src/widget/radio.rs index dd8b5f17..da41ac47 100644 --- a/graphics/src/widget/radio.rs +++ b/graphics/src/widget/radio.rs @@ -13,16 +13,13 @@ pub use iced_style::radio::{Style, StyleSheet}; pub type Radio = iced_native::Radio>; -const SIZE: f32 = 28.0; -const DOT_SIZE: f32 = SIZE / 2.0; - impl radio::Renderer for Renderer where B: Backend, { type Style = Box; - const DEFAULT_SIZE: u16 = SIZE as u16; + const DEFAULT_SIZE: u16 = 28; const DEFAULT_SPACING: u16 = 15; fn draw( @@ -39,10 +36,13 @@ where style_sheet.active() }; + let size = bounds.width; + let dot_size = size / 2.0; + let radio = Primitive::Quad { bounds, background: style.background, - border_radius: (SIZE / 2.0) as u16, + border_radius: (size / 2.0) as u16, border_width: style.border_width, border_color: style.border_color, }; @@ -52,13 +52,13 @@ where primitives: if is_selected { let radio_circle = Primitive::Quad { bounds: Rectangle { - x: bounds.x + DOT_SIZE / 2.0, - y: bounds.y + DOT_SIZE / 2.0, - width: bounds.width - DOT_SIZE, - height: bounds.height - DOT_SIZE, + x: bounds.x + dot_size / 2.0, + y: bounds.y + dot_size / 2.0, + width: bounds.width - dot_size, + height: bounds.height - dot_size, }, 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_color: Color::TRANSPARENT, }; From c1f79b40cf704cafc807250b177fc7d3444fe54f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ram=C3=B3n=20Jim=C3=A9nez?= Date: Tue, 8 Sep 2020 00:35:17 +0200 Subject: [PATCH 19/19] Make `Application` and `Sandbox` return a `Result` --- Cargo.toml | 1 + examples/bezier_tool/src/main.rs | 4 +-- examples/clock/src/main.rs | 2 +- examples/color_palette/src/main.rs | 2 +- examples/counter/src/main.rs | 2 +- examples/custom_widget/src/main.rs | 2 +- examples/download_progress/src/main.rs | 2 +- examples/events/src/main.rs | 2 +- examples/game_of_life/src/main.rs | 2 +- examples/geometry/src/main.rs | 2 +- examples/pane_grid/src/main.rs | 2 +- examples/pick_list/src/main.rs | 2 +- examples/pokedex/src/main.rs | 2 +- examples/progress_bar/src/main.rs | 2 +- examples/solar_system/src/main.rs | 2 +- examples/stopwatch/src/main.rs | 2 +- examples/styling/src/main.rs | 2 +- examples/svg/src/main.rs | 2 +- examples/todos/src/main.rs | 2 +- examples/tour/src/main.rs | 2 +- glow/src/lib.rs | 2 +- glow/src/window/compositor.rs | 6 ++--- glutin/src/application.rs | 20 +++++++++++---- glutin/src/lib.rs | 2 +- graphics/Cargo.toml | 1 + graphics/src/error.rs | 7 ++++++ graphics/src/lib.rs | 2 ++ graphics/src/window/compositor.rs | 4 +-- graphics/src/window/gl_compositor.rs | 4 +-- src/application.rs | 22 ++++++++++------- src/error.rs | 34 ++++++++++++++++++++++++++ src/lib.rs | 4 +++ src/result.rs | 6 +++++ src/sandbox.rs | 7 +++--- wgpu/src/lib.rs | 4 ++- wgpu/src/window/compositor.rs | 9 +++---- winit/Cargo.toml | 5 ++++ winit/src/application.rs | 15 +++++++----- winit/src/error.rs | 27 ++++++++++++++++++++ winit/src/lib.rs | 2 ++ 40 files changed, 166 insertions(+), 58 deletions(-) create mode 100644 graphics/src/error.rs create mode 100644 src/error.rs create mode 100644 src/result.rs create mode 100644 winit/src/error.rs diff --git a/Cargo.toml b/Cargo.toml index 63ccb82e..d97707ab 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,6 +78,7 @@ members = [ [dependencies] iced_core = { version = "0.2", path = "core" } iced_futures = { version = "0.1", path = "futures" } +thiserror = "1.0" [target.'cfg(not(target_arch = "wasm32"))'.dependencies] iced_winit = { version = "0.1", path = "winit" } diff --git a/examples/bezier_tool/src/main.rs b/examples/bezier_tool/src/main.rs index fb740b83..cb5247aa 100644 --- a/examples/bezier_tool/src/main.rs +++ b/examples/bezier_tool/src/main.rs @@ -3,11 +3,11 @@ use iced::{ button, Align, Button, Column, Element, Length, Sandbox, Settings, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings { antialiasing: true, ..Settings::default() - }); + }) } #[derive(Default)] diff --git a/examples/clock/src/main.rs b/examples/clock/src/main.rs index 9c583c78..b317ac00 100644 --- a/examples/clock/src/main.rs +++ b/examples/clock/src/main.rs @@ -4,7 +4,7 @@ use iced::{ Point, Rectangle, Settings, Subscription, Vector, }; -pub fn main() { +pub fn main() -> iced::Result { Clock::run(Settings { antialiasing: true, ..Settings::default() diff --git a/examples/color_palette/src/main.rs b/examples/color_palette/src/main.rs index 3186deff..fec5f48c 100644 --- a/examples/color_palette/src/main.rs +++ b/examples/color_palette/src/main.rs @@ -8,7 +8,7 @@ use palette::{self, Hsl, Limited, Srgb}; use std::marker::PhantomData; use std::ops::RangeInclusive; -pub fn main() { +pub fn main() -> iced::Result { ColorPalette::run(Settings { antialiasing: true, ..Settings::default() diff --git a/examples/counter/src/main.rs b/examples/counter/src/main.rs index bde0ea94..e0b2ebd6 100644 --- a/examples/counter/src/main.rs +++ b/examples/counter/src/main.rs @@ -1,6 +1,6 @@ use iced::{button, Align, Button, Column, Element, Sandbox, Settings, Text}; -pub fn main() { +pub fn main() -> iced::Result { Counter::run(Settings::default()) } diff --git a/examples/custom_widget/src/main.rs b/examples/custom_widget/src/main.rs index bcf896b0..0eba1cd0 100644 --- a/examples/custom_widget/src/main.rs +++ b/examples/custom_widget/src/main.rs @@ -90,7 +90,7 @@ use iced::{ Slider, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings::default()) } diff --git a/examples/download_progress/src/main.rs b/examples/download_progress/src/main.rs index c37ae678..77b01354 100644 --- a/examples/download_progress/src/main.rs +++ b/examples/download_progress/src/main.rs @@ -5,7 +5,7 @@ use iced::{ mod download; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings::default()) } diff --git a/examples/events/src/main.rs b/examples/events/src/main.rs index 066fc230..6eba6aad 100644 --- a/examples/events/src/main.rs +++ b/examples/events/src/main.rs @@ -3,7 +3,7 @@ use iced::{ Element, Length, Settings, Subscription, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Events::run(Settings::default()) } diff --git a/examples/game_of_life/src/main.rs b/examples/game_of_life/src/main.rs index 2addd950..332d2d95 100644 --- a/examples/game_of_life/src/main.rs +++ b/examples/game_of_life/src/main.rs @@ -16,7 +16,7 @@ use iced::{ use preset::Preset; use std::time::{Duration, Instant}; -pub fn main() { +pub fn main() -> iced::Result { GameOfLife::run(Settings { antialiasing: true, ..Settings::default() diff --git a/examples/geometry/src/main.rs b/examples/geometry/src/main.rs index 71ce0d8c..1c13c8d5 100644 --- a/examples/geometry/src/main.rs +++ b/examples/geometry/src/main.rs @@ -165,7 +165,7 @@ use iced::{ }; use rainbow::Rainbow; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings::default()) } diff --git a/examples/pane_grid/src/main.rs b/examples/pane_grid/src/main.rs index 09c33613..c4946645 100644 --- a/examples/pane_grid/src/main.rs +++ b/examples/pane_grid/src/main.rs @@ -4,7 +4,7 @@ use iced::{ Settings, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings::default()) } diff --git a/examples/pick_list/src/main.rs b/examples/pick_list/src/main.rs index 3917a554..68662602 100644 --- a/examples/pick_list/src/main.rs +++ b/examples/pick_list/src/main.rs @@ -3,7 +3,7 @@ use iced::{ Sandbox, Scrollable, Settings, Space, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Example::run(Settings::default()) } diff --git a/examples/pokedex/src/main.rs b/examples/pokedex/src/main.rs index e7afa8f5..30674fa0 100644 --- a/examples/pokedex/src/main.rs +++ b/examples/pokedex/src/main.rs @@ -3,7 +3,7 @@ use iced::{ Container, Element, Image, Length, Row, Settings, Text, }; -pub fn main() { +pub fn main() -> iced::Result { Pokedex::run(Settings::default()) } diff --git a/examples/progress_bar/src/main.rs b/examples/progress_bar/src/main.rs index 51b56eda..c9a8e798 100644 --- a/examples/progress_bar/src/main.rs +++ b/examples/progress_bar/src/main.rs @@ -1,6 +1,6 @@ use iced::{slider, Column, Element, ProgressBar, Sandbox, Settings, Slider}; -pub fn main() { +pub fn main() -> iced::Result { Progress::run(Settings::default()) } diff --git a/examples/solar_system/src/main.rs b/examples/solar_system/src/main.rs index 98bd3b21..6a2de736 100644 --- a/examples/solar_system/src/main.rs +++ b/examples/solar_system/src/main.rs @@ -14,7 +14,7 @@ use iced::{ use std::time::Instant; -pub fn main() { +pub fn main() -> iced::Result { SolarSystem::run(Settings { antialiasing: true, ..Settings::default() diff --git a/examples/stopwatch/src/main.rs b/examples/stopwatch/src/main.rs index 9de6d39e..5a69aa9a 100644 --- a/examples/stopwatch/src/main.rs +++ b/examples/stopwatch/src/main.rs @@ -5,7 +5,7 @@ use iced::{ }; use std::time::{Duration, Instant}; -pub fn main() { +pub fn main() -> iced::Result { Stopwatch::run(Settings::default()) } diff --git a/examples/styling/src/main.rs b/examples/styling/src/main.rs index dcbc2744..ef302e61 100644 --- a/examples/styling/src/main.rs +++ b/examples/styling/src/main.rs @@ -4,7 +4,7 @@ use iced::{ Scrollable, Settings, Slider, Space, Text, TextInput, }; -pub fn main() { +pub fn main() -> iced::Result { Styling::run(Settings::default()) } diff --git a/examples/svg/src/main.rs b/examples/svg/src/main.rs index e19eeca2..8707fa3b 100644 --- a/examples/svg/src/main.rs +++ b/examples/svg/src/main.rs @@ -1,6 +1,6 @@ use iced::{Container, Element, Length, Sandbox, Settings, Svg}; -pub fn main() { +pub fn main() -> iced::Result { Tiger::run(Settings::default()) } diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 5713a6f2..7a546815 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -5,7 +5,7 @@ use iced::{ }; use serde::{Deserialize, Serialize}; -pub fn main() { +pub fn main() -> iced::Result { Todos::run(Settings::default()) } diff --git a/examples/tour/src/main.rs b/examples/tour/src/main.rs index 4f8a4b32..ec464801 100644 --- a/examples/tour/src/main.rs +++ b/examples/tour/src/main.rs @@ -4,7 +4,7 @@ use iced::{ Sandbox, Scrollable, Settings, Slider, Space, Text, TextInput, }; -pub fn main() { +pub fn main() -> iced::Result { env_logger::init(); Tour::run(Settings::default()) diff --git a/glow/src/lib.rs b/glow/src/lib.rs index a6c8a75a..5011da8e 100644 --- a/glow/src/lib.rs +++ b/glow/src/lib.rs @@ -26,7 +26,7 @@ pub(crate) use iced_graphics::Transformation; #[doc(no_inline)] pub use widget::*; -pub use iced_graphics::Viewport; +pub use iced_graphics::{Error, Viewport}; pub use iced_native::{ Background, Color, Command, HorizontalAlignment, Length, Vector, VerticalAlignment, diff --git a/glow/src/window/compositor.rs b/glow/src/window/compositor.rs index 3ad10b59..1fb671ad 100644 --- a/glow/src/window/compositor.rs +++ b/glow/src/window/compositor.rs @@ -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 glow::HasContext; @@ -18,7 +18,7 @@ impl iced_graphics::window::GLCompositor for Compositor { unsafe fn new( settings: Self::Settings, 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); // 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)); - (Self { gl }, renderer) + Ok((Self { gl }, renderer)) } fn sample_count(settings: &Settings) -> u32 { diff --git a/glutin/src/application.rs b/glutin/src/application.rs index 3be9b65f..fe6ad99d 100644 --- a/glutin/src/application.rs +++ b/glutin/src/application.rs @@ -1,5 +1,5 @@ //! 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::Viewport; use iced_winit::application; @@ -16,7 +16,8 @@ pub use iced_winit::{program, Program}; pub fn run( settings: Settings, compositor_settings: C::Settings, -) where +) -> Result<(), Error> +where A: Application + 'static, E: Executor + 'static, C: window::GLCompositor + 'static, @@ -32,7 +33,7 @@ pub fn run( let event_loop = EventLoop::with_user_event(); 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()); Runtime::new(executor, proxy) @@ -61,7 +62,16 @@ pub fn run( .with_vsync(true) .with_multisampling(C::sample_count(&compositor_settings) as u16) .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)] unsafe { @@ -85,7 +95,7 @@ pub fn run( let (mut compositor, mut renderer) = unsafe { C::new(compositor_settings, |address| { context.get_proc_address(address) - }) + })? }; let mut state = program::State::new( diff --git a/glutin/src/lib.rs b/glutin/src/lib.rs index b0e0bdd4..49bc2a33 100644 --- a/glutin/src/lib.rs +++ b/glutin/src/lib.rs @@ -15,7 +15,7 @@ pub use iced_native::*; pub mod application; pub use iced_winit::settings; -pub use iced_winit::Mode; +pub use iced_winit::{Error, Mode}; #[doc(no_inline)] pub use application::Application; diff --git a/graphics/Cargo.toml b/graphics/Cargo.toml index 723b9232..dec24c59 100644 --- a/graphics/Cargo.toml +++ b/graphics/Cargo.toml @@ -15,6 +15,7 @@ opengl = [] bytemuck = "1.2" glam = "0.9" raw-window-handle = "0.3" +thiserror = "1.0" [dependencies.iced_native] version = "0.2" diff --git a/graphics/src/error.rs b/graphics/src/error.rs new file mode 100644 index 00000000..c86e326a --- /dev/null +++ b/graphics/src/error.rs @@ -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, +} diff --git a/graphics/src/lib.rs b/graphics/src/lib.rs index d03f3b48..a3bd5364 100644 --- a/graphics/src/lib.rs +++ b/graphics/src/lib.rs @@ -9,6 +9,7 @@ #![forbid(rust_2018_idioms)] #![cfg_attr(docsrs, feature(doc_cfg))] mod antialiasing; +mod error; mod primitive; mod renderer; mod transformation; @@ -29,6 +30,7 @@ pub use widget::*; pub use antialiasing::Antialiasing; pub use backend::Backend; pub use defaults::Defaults; +pub use error::Error; pub use layer::Layer; pub use primitive::Primitive; pub use renderer::Renderer; diff --git a/graphics/src/window/compositor.rs b/graphics/src/window/compositor.rs index aa625f43..7674f227 100644 --- a/graphics/src/window/compositor.rs +++ b/graphics/src/window/compositor.rs @@ -1,4 +1,4 @@ -use crate::{Color, Viewport}; +use crate::{Color, Error, Viewport}; use iced_native::mouse; use raw_window_handle::HasRawWindowHandle; @@ -19,7 +19,7 @@ pub trait Compositor: Sized { /// Creates a new [`Backend`]. /// /// [`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. /// diff --git a/graphics/src/window/gl_compositor.rs b/graphics/src/window/gl_compositor.rs index 2ba39d6e..1f37642e 100644 --- a/graphics/src/window/gl_compositor.rs +++ b/graphics/src/window/gl_compositor.rs @@ -1,4 +1,4 @@ -use crate::{Color, Size, Viewport}; +use crate::{Color, Error, Size, Viewport}; use iced_native::mouse; use core::ffi::c_void; @@ -41,7 +41,7 @@ pub trait GLCompositor: Sized { unsafe fn new( settings: Self::Settings, 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 /// an OpenGL context for this [`Compositor`]. diff --git a/src/application.rs b/src/application.rs index 47b89dbd..d46cd2ac 100644 --- a/src/application.rs +++ b/src/application.rs @@ -1,6 +1,5 @@ -use crate::{ - window, Color, Command, Element, Executor, Settings, Subscription, -}; +use crate::window; +use crate::{Color, Command, Element, Executor, Settings, Subscription}; /// An interactive cross-platform application. /// @@ -59,7 +58,7 @@ use crate::{ /// ```no_run /// use iced::{executor, Application, Command, Element, Settings, Text}; /// -/// pub fn main() { +/// pub fn main() -> iced::Result { /// Hello::run(Settings::default()) /// } /// @@ -204,12 +203,13 @@ pub trait Application: Sized { /// Runs the [`Application`]. /// /// 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. /// /// [`Application`]: trait.Application.html - fn run(settings: Settings) + /// [`Error`]: enum.Error.html + fn run(settings: Settings) -> crate::Result where Self: 'static, { @@ -226,15 +226,19 @@ pub trait Application: Sized { ..crate::renderer::Settings::default() }; - crate::runtime::application::run::< + Ok(crate::runtime::application::run::< Instance, Self::Executor, crate::renderer::window::Compositor, - >(settings.into(), renderer_settings); + >(settings.into(), renderer_settings)?) } #[cfg(target_arch = "wasm32")] - as iced_web::Application>::run(settings.flags); + { + as iced_web::Application>::run(settings.flags); + + Ok(()) + } } } diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 00000000..31b87d17 --- /dev/null +++ b/src/error.rs @@ -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), + + /// 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 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 + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index d08b39cf..610683b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -181,6 +181,8 @@ #![cfg_attr(docsrs, feature(doc_cfg))] mod application; mod element; +mod error; +mod result; mod sandbox; pub mod executor; @@ -225,7 +227,9 @@ pub use widget::*; pub use application::Application; pub use element::Element; +pub use error::Error; pub use executor::Executor; +pub use result::Result; pub use sandbox::Sandbox; pub use settings::Settings; diff --git a/src/result.rs b/src/result.rs new file mode 100644 index 00000000..2f05a6a9 --- /dev/null +++ b/src/result.rs @@ -0,0 +1,6 @@ +use crate::Error; + +/// The result of running an [`Application`]. +/// +/// [`Application`]: trait.Application.html +pub type Result = std::result::Result<(), Error>; diff --git a/src/sandbox.rs b/src/sandbox.rs index 6a73eab0..c72b58d8 100644 --- a/src/sandbox.rs +++ b/src/sandbox.rs @@ -1,5 +1,6 @@ +use crate::executor; use crate::{ - executor, Application, Color, Command, Element, Settings, Subscription, + Application, Color, Command, Element, Error, Settings, Subscription, }; /// A sandboxed [`Application`]. @@ -64,7 +65,7 @@ use crate::{ /// ```no_run /// use iced::{Element, Sandbox, Settings, Text}; /// -/// pub fn main() { +/// pub fn main() -> iced::Result { /// Hello::run(Settings::default()) /// } /// @@ -159,7 +160,7 @@ pub trait Sandbox { /// It should probably be that last thing you call in your `main` function. /// /// [`Sandbox`]: trait.Sandbox.html - fn run(settings: Settings<()>) + fn run(settings: Settings<()>) -> Result<(), Error> where Self: 'static + Sized, { diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index 570e8a94..5f44dd91 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -36,7 +36,9 @@ mod backend; mod quad; 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 backend::Backend; diff --git a/wgpu/src/window/compositor.rs b/wgpu/src/window/compositor.rs index c790f35f..79ffacdd 100644 --- a/wgpu/src/window/compositor.rs +++ b/wgpu/src/window/compositor.rs @@ -1,7 +1,6 @@ -use crate::{Backend, Color, Renderer, Settings}; +use crate::{Backend, Color, Error, Renderer, Settings, Viewport}; use futures::task::SpawnExt; -use iced_graphics::Viewport; use iced_native::{futures, mouse}; use raw_window_handle::HasRawWindowHandle; @@ -82,13 +81,13 @@ impl iced_graphics::window::Compositor for Compositor { type Surface = wgpu::Surface; 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)) - .expect("Could not find a suitable graphics adapter"); + .ok_or(Error::AdapterNotFound)?; let backend = compositor.create_backend(); - (compositor, Renderer::new(backend)) + Ok((compositor, Renderer::new(backend))) } fn create_surface( diff --git a/winit/Cargo.toml b/winit/Cargo.toml index 7fe83b96..06e5df9a 100644 --- a/winit/Cargo.toml +++ b/winit/Cargo.toml @@ -17,6 +17,7 @@ debug = ["iced_native/debug"] winit = "0.22" window_clipboard = "0.1" log = "0.4" +thiserror = "1.0" [dependencies.iced_native] version = "0.2" @@ -26,5 +27,9 @@ path = "../native" version = "0.1" path = "../graphics" +[dependencies.iced_futures] +version = "0.1" +path = "../futures" + [target.'cfg(target_os = "windows")'.dependencies.winapi] version = "0.3.6" diff --git a/winit/src/application.rs b/winit/src/application.rs index 73dad398..12f92053 100644 --- a/winit/src/application.rs +++ b/winit/src/application.rs @@ -1,7 +1,9 @@ //! Create interactive, native cross-platform applications. +use crate::conversion; +use crate::mouse; use crate::{ - conversion, mouse, Clipboard, Color, Command, Debug, Executor, Mode, Proxy, - Runtime, Settings, Size, Subscription, + Clipboard, Color, Command, Debug, Error, Executor, Mode, Proxy, Runtime, + Settings, Size, Subscription, }; use iced_graphics::window; use iced_graphics::Viewport; @@ -108,7 +110,8 @@ pub trait Application: Program { pub fn run( settings: Settings, compositor_settings: C::Settings, -) where +) -> Result<(), Error> +where A: Application + 'static, E: Executor + 'static, C: window::Compositor + 'static, @@ -123,7 +126,7 @@ pub fn run( let event_loop = EventLoop::with_user_event(); 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()); Runtime::new(executor, proxy) @@ -145,7 +148,7 @@ pub fn run( .window .into_builder(&title, mode, event_loop.primary_monitor()) .build(&event_loop) - .expect("Open window"); + .map_err(Error::WindowCreationFailed)?; let clipboard = Clipboard::new(&window); // TODO: Encode cursor availability in the type-system @@ -160,7 +163,7 @@ pub fn run( ); 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); diff --git a/winit/src/error.rs b/winit/src/error.rs new file mode 100644 index 00000000..8e1d20e8 --- /dev/null +++ b/winit/src/error.rs @@ -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 for Error { + fn from(error: iced_graphics::Error) -> Error { + match error { + iced_graphics::Error::AdapterNotFound => { + Error::GraphicsAdapterNotFound + } + } + } +} diff --git a/winit/src/lib.rs b/winit/src/lib.rs index bdab3ed7..8ca8eec1 100644 --- a/winit/src/lib.rs +++ b/winit/src/lib.rs @@ -30,11 +30,13 @@ pub mod conversion; pub mod settings; mod clipboard; +mod error; mod mode; mod proxy; pub use application::Application; pub use clipboard::Clipboard; +pub use error::Error; pub use mode::Mode; pub use proxy::Proxy; pub use settings::Settings;