1
0
mirror of https://github.com/emilk/egui.git synced 2026-08-29 21:00:03 -04:00

Add egui_wgpu crate (#1564)

Based on https://github.com/hasenbanck/egui_wgpu_backend

`egui-wgpu` is now an official backend for `eframe` (opt-in).

Use the `wgpu` feature flag on `eframe` and the `NativeOptions::renderer` settings to pick it.

Co-authored-by: Nils Hasenbanck <nils@hasenbanck.de>
Co-authored-by: Sven Niederberger <niederberger@embotech.com>
Co-authored-by: Sven Niederberger <73159570+s-nie@users.noreply.github.com>
This commit is contained in:
Emil Ernerfeldt
2022-05-12 09:02:28 +02:00
committed by GitHub
parent 3d52cc8867
commit 931e716b97
32 changed files with 1540 additions and 101 deletions

View File

@@ -27,7 +27,8 @@ pub struct CreationContext<'s> {
/// The [`glow::Context`] allows you to initialize OpenGL resources (e.g. shaders) that
/// you might want to use later from a [`egui::PaintCallback`].
pub gl: std::rc::Rc<glow::Context>,
#[cfg(feature = "glow")]
pub gl: Option<std::rc::Rc<glow::Context>>,
}
// ----------------------------------------------------------------------------
@@ -71,7 +72,17 @@ pub trait App {
/// Called once on shutdown, after [`Self::save`].
///
/// If you need to abort an exit use [`Self::on_exit_event`].
fn on_exit(&mut self, _gl: &glow::Context) {}
///
/// To get a [`glow`] context you need to compile with the `glow` feature flag,
/// and run eframe with the glow backend.
#[cfg(feature = "glow")]
fn on_exit(&mut self, _gl: Option<&glow::Context>) {}
/// Called once on shutdown, after [`Self::save`].
///
/// If you need to abort an exit use [`Self::on_exit_event`].
#[cfg(not(feature = "glow"))]
fn on_exit(&mut self) {}
// ---------
// Settings:
@@ -199,6 +210,9 @@ pub struct NativeOptions {
///
/// `egui` doesn't need the stencil buffer, so the default value is 0.
pub stencil_buffer: u8,
/// What rendering backend to use.
pub renderer: Renderer,
}
impl Default for NativeOptions {
@@ -219,10 +233,74 @@ impl Default for NativeOptions {
multisampling: 0,
depth_buffer: 0,
stencil_buffer: 0,
renderer: Renderer::default(),
}
}
}
// ----------------------------------------------------------------------------
/// What rendering backend to use.
///
/// You need to enable the "glow" and "wgpu" features to have a choice.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Renderer {
/// Use [`egui_glow`] renderer for [`glow`](https://github.com/grovesNL/glow).
#[cfg(feature = "glow")]
Glow,
/// Use [`egui_wgpu`] renderer for [`wgpu`](https://github.com/gfx-rs/wgpu).
#[cfg(feature = "wgpu")]
Wgpu,
}
impl Default for Renderer {
fn default() -> Self {
#[cfg(feature = "glow")]
return Self::Glow;
#[cfg(not(feature = "glow"))]
#[cfg(feature = "wgpu")]
return Self::Wgpu;
#[cfg(not(feature = "glow"))]
#[cfg(not(feature = "wgpu"))]
compile_error!("eframe: you must enable at least one of the rendering backend features: 'glow' or 'wgpu'");
}
}
impl std::fmt::Display for Renderer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
#[cfg(feature = "glow")]
Self::Glow => "glow".fmt(f),
#[cfg(feature = "wgpu")]
Self::Wgpu => "wgpu".fmt(f),
}
}
}
impl std::str::FromStr for Renderer {
type Err = String;
fn from_str(name: &str) -> Result<Self, String> {
match name.to_lowercase().as_str() {
#[cfg(feature = "glow")]
"glow" => Ok(Self::Glow),
#[cfg(feature = "wgpu")]
"wgpu" => Ok(Self::Wgpu),
_ => Err(format!("eframe renderer {name:?} is not available. Make sure that the corresponding eframe feature is enabled."))
}
}
}
// ----------------------------------------------------------------------------
/// Image data for an application icon.
#[derive(Clone)]
pub struct IconData {
@@ -254,8 +332,9 @@ pub struct Frame {
pub storage: Option<Box<dyn Storage>>,
/// A reference to the underlying [`glow`] (OpenGL) context.
#[cfg(feature = "glow")]
#[doc(hidden)]
pub gl: std::rc::Rc<glow::Context>,
pub gl: Option<std::rc::Rc<glow::Context>>,
}
impl Frame {
@@ -288,8 +367,12 @@ impl Frame {
///
/// Note that all egui painting is deferred to after the call to [`App::update`]
/// ([`egui`] only collects [`egui::Shape`]s and then eframe paints them all in one go later on).
pub fn gl(&self) -> &std::rc::Rc<glow::Context> {
&self.gl
///
/// To get a [`glow`] context you need to compile with the `glow` feature flag,
/// and run eframe with the glow backend.
#[cfg(feature = "glow")]
pub fn gl(&self) -> Option<&std::rc::Rc<glow::Context>> {
self.gl.as_ref()
}
/// Signal the app to stop/exit/quit the app (only works for native apps, not web apps).

View File

@@ -56,7 +56,10 @@
#![allow(clippy::needless_doctest_main)]
// Re-export all useful libraries:
pub use {egui, egui::emath, egui::epaint, glow};
pub use {egui, egui::emath, egui::epaint};
#[cfg(feature = "glow")]
pub use {egui_glow, glow};
mod epi;
@@ -142,7 +145,21 @@ mod native;
#[cfg(not(target_arch = "wasm32"))]
#[allow(clippy::needless_pass_by_value)]
pub fn run_native(app_name: &str, native_options: NativeOptions, app_creator: AppCreator) -> ! {
native::run(app_name, &native_options, app_creator)
let renderer = native_options.renderer;
match renderer {
#[cfg(feature = "glow")]
Renderer::Glow => {
tracing::debug!("Using the glow renderer");
native::run::run_glow(app_name, &native_options, app_creator)
}
#[cfg(feature = "wgpu")]
Renderer::Wgpu => {
tracing::debug!("Using the wgpu renderer");
native::run::run_wgpu(app_name, &native_options, app_creator)
}
}
}
// ---------------------------------------------------------------------------

View File

@@ -28,6 +28,7 @@ pub fn window_builder(
multisampling: _, // used in `fn create_display`
depth_buffer: _, // used in `fn create_display`
stencil_buffer: _, // used in `fn create_display`
renderer: _, // used in `fn run_native`
} = native_options;
let window_icon = icon_data.clone().and_then(load_icon);
@@ -159,10 +160,10 @@ pub struct EpiIntegration {
impl EpiIntegration {
pub fn new(
gl: std::rc::Rc<glow::Context>,
max_texture_side: usize,
window: &winit::window::Window,
storage: Option<Box<dyn epi::Storage>>,
#[cfg(feature = "glow")] gl: Option<std::rc::Rc<glow::Context>>,
) -> Self {
let egui_ctx = egui::Context::default();
@@ -179,6 +180,7 @@ impl EpiIntegration {
},
output: Default::default(),
storage,
#[cfg(feature = "glow")]
gl,
};

View File

@@ -1,8 +1,6 @@
mod epi_integration;
mod run;
pub mod run;
/// File storage which can be used by native backends.
#[cfg(feature = "persistence")]
pub mod file_storage;
pub use run::run;

View File

@@ -4,6 +4,7 @@ use egui_winit::winit;
struct RequestRepaintEvent;
#[cfg(feature = "glow")]
#[allow(unsafe_code)]
fn create_display(
native_options: &NativeOptions,
@@ -37,13 +38,18 @@ fn create_display(
pub use epi::NativeOptions;
/// Run an egui app
#[allow(unsafe_code)]
pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi::AppCreator) -> ! {
#[cfg(feature = "glow")]
pub fn run_glow(
app_name: &str,
native_options: &epi::NativeOptions,
app_creator: epi::AppCreator,
) -> ! {
let storage = epi_integration::create_storage(app_name);
let window_settings = epi_integration::load_window_settings(storage.as_deref());
let event_loop = winit::event_loop::EventLoop::with_user_event();
let window_builder =
epi_integration::window_builder(native_options, &window_settings).with_title(app_name);
let event_loop = winit::event_loop::EventLoop::with_user_event();
let (gl_window, gl) = create_display(native_options, window_builder, &event_loop);
let gl = std::rc::Rc::new(gl);
@@ -51,10 +57,10 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
.unwrap_or_else(|error| panic!("some OpenGL error occurred {}\n", error));
let mut integration = epi_integration::EpiIntegration::new(
gl.clone(),
painter.max_texture_side(),
gl_window.window(),
storage,
Some(gl.clone()),
);
{
@@ -68,7 +74,7 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
egui_ctx: integration.egui_ctx.clone(),
integration_info: integration.frame.info(),
storage: integration.frame.storage(),
gl: gl.clone(),
gl: Some(gl.clone()),
});
if app.warm_up_enabled() {
@@ -78,22 +84,14 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
let mut is_focused = true;
event_loop.run(move |event, _, control_flow| {
let window = gl_window.window();
let mut redraw = || {
#[cfg(feature = "puffin")]
puffin::GlobalProfiler::lock().new_frame();
if !is_focused {
// On Mac, a minimized Window uses up all CPU: https://github.com/emilk/egui/issues/325
// We can't know if we are minimized: https://github.com/rust-windowing/winit/issues/208
// But we know if we are focused (in foreground). When minimized, we are not focused.
// However, a user may want an egui with an animation in the background,
// so we still need to repaint quite fast.
crate::profile_scope!("bg_sleep");
std::thread::sleep(std::time::Duration::from_millis(10));
}
crate::profile_scope!("frame");
let screen_size_in_pixels: [u32; 2] = gl_window.window().inner_size().into();
let screen_size_in_pixels: [u32; 2] = window.inner_size().into();
egui_glow::painter::clear(
&gl,
@@ -106,9 +104,9 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
needs_repaint,
textures_delta,
shapes,
} = integration.update(app.as_mut(), gl_window.window());
} = integration.update(app.as_mut(), window);
integration.handle_platform_output(gl_window.window(), platform_output);
integration.handle_platform_output(window, platform_output);
let clipped_primitives = {
crate::profile_scope!("tessellate");
@@ -127,18 +125,26 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
gl_window.swap_buffers().unwrap();
}
{
*control_flow = if integration.should_quit() {
winit::event_loop::ControlFlow::Exit
} else if needs_repaint {
gl_window.window().request_redraw();
winit::event_loop::ControlFlow::Poll
} else {
winit::event_loop::ControlFlow::Wait
};
}
*control_flow = if integration.should_quit() {
winit::event_loop::ControlFlow::Exit
} else if needs_repaint {
window.request_redraw();
winit::event_loop::ControlFlow::Poll
} else {
winit::event_loop::ControlFlow::Wait
};
integration.maybe_autosave(app.as_mut(), gl_window.window());
integration.maybe_autosave(app.as_mut(), window);
if !is_focused {
// On Mac, a minimized Window uses up all CPU: https://github.com/emilk/egui/issues/325
// We can't know if we are minimized: https://github.com/rust-windowing/winit/issues/208
// But we know if we are focused (in foreground). When minimized, we are not focused.
// However, a user may want an egui with an animation in the background,
// so we still need to repaint quite fast.
crate::profile_scope!("bg_sleep");
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
match event {
@@ -149,35 +155,194 @@ pub fn run(app_name: &str, native_options: &epi::NativeOptions, app_creator: epi
winit::event::Event::RedrawRequested(_) if !cfg!(windows) => redraw(),
winit::event::Event::WindowEvent { event, .. } => {
if let winit::event::WindowEvent::Focused(new_focused) = event {
is_focused = new_focused;
}
if let winit::event::WindowEvent::Resized(physical_size) = &event {
gl_window.resize(*physical_size);
} else if let glutin::event::WindowEvent::ScaleFactorChanged {
new_inner_size,
..
} = &event
{
gl_window.resize(**new_inner_size);
match &event {
winit::event::WindowEvent::Focused(new_focused) => {
is_focused = *new_focused;
}
winit::event::WindowEvent::Resized(physical_size) => {
// Resize with 0 width and height is used by winit to signal a minimize event on Windows.
// See: https://github.com/rust-windowing/winit/issues/208
// This solves an issue where the app would panic when minimizing on Windows.
if physical_size.width > 0 && physical_size.height > 0 {
gl_window.resize(*physical_size);
}
}
winit::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
gl_window.resize(**new_inner_size);
}
winit::event::WindowEvent::CloseRequested => {
*control_flow = winit::event_loop::ControlFlow::Exit;
}
_ => {}
}
integration.on_event(app.as_mut(), &event);
if integration.should_quit() {
*control_flow = winit::event_loop::ControlFlow::Exit;
}
gl_window.window().request_redraw(); // TODO: ask egui if the events warrants a repaint instead
window.request_redraw(); // TODO: ask egui if the events warrants a repaint instead
}
winit::event::Event::LoopDestroyed => {
integration.save(&mut *app, gl_window.window());
app.on_exit(&gl);
integration.save(&mut *app, window);
app.on_exit(Some(&gl));
painter.destroy();
}
winit::event::Event::UserEvent(RequestRepaintEvent) => {
gl_window.window().request_redraw();
}
winit::event::Event::UserEvent(RequestRepaintEvent) => window.request_redraw(),
_ => (),
}
});
}
// TODO: merge with with the clone above
/// Run an egui app
#[cfg(feature = "wgpu")]
pub fn run_wgpu(
app_name: &str,
native_options: &epi::NativeOptions,
app_creator: epi::AppCreator,
) -> ! {
let storage = epi_integration::create_storage(app_name);
let window_settings = epi_integration::load_window_settings(storage.as_deref());
let event_loop = winit::event_loop::EventLoop::with_user_event();
let window = epi_integration::window_builder(native_options, &window_settings)
.with_title(app_name)
.build(&event_loop)
.unwrap();
// SAFETY: `window` must outlive `painter`.
#[allow(unsafe_code)]
let mut painter = unsafe {
egui_wgpu::winit::Painter::new(&window, native_options.multisampling.max(1) as _)
};
let mut integration = epi_integration::EpiIntegration::new(
painter.max_texture_side(),
&window,
storage,
#[cfg(feature = "glow")]
None,
);
{
let event_loop_proxy = egui::mutex::Mutex::new(event_loop.create_proxy());
integration.egui_ctx.set_request_repaint_callback(move || {
event_loop_proxy.lock().send_event(RequestRepaintEvent).ok();
});
}
let mut app = app_creator(&epi::CreationContext {
egui_ctx: integration.egui_ctx.clone(),
integration_info: integration.frame.info(),
storage: integration.frame.storage(),
#[cfg(feature = "glow")]
gl: None,
});
if app.warm_up_enabled() {
integration.warm_up(app.as_mut(), &window);
}
let mut is_focused = true;
event_loop.run(move |event, _, control_flow| {
let window = &window;
let mut redraw = || {
#[cfg(feature = "puffin")]
puffin::GlobalProfiler::lock().new_frame();
crate::profile_scope!("frame");
let egui::FullOutput {
platform_output,
needs_repaint,
textures_delta,
shapes,
} = integration.update(app.as_mut(), window);
integration.handle_platform_output(window, platform_output);
let clipped_primitives = {
crate::profile_scope!("tessellate");
integration.egui_ctx.tessellate(shapes)
};
painter.paint_and_update_textures(
integration.egui_ctx.pixels_per_point(),
app.clear_color(&integration.egui_ctx.style().visuals),
&clipped_primitives,
&textures_delta,
);
*control_flow = if integration.should_quit() {
winit::event_loop::ControlFlow::Exit
} else if needs_repaint {
window.request_redraw();
winit::event_loop::ControlFlow::Poll
} else {
winit::event_loop::ControlFlow::Wait
};
integration.maybe_autosave(app.as_mut(), window);
if !is_focused {
// On Mac, a minimized Window uses up all CPU: https://github.com/emilk/egui/issues/325
// We can't know if we are minimized: https://github.com/rust-windowing/winit/issues/208
// But we know if we are focused (in foreground). When minimized, we are not focused.
// However, a user may want an egui with an animation in the background,
// so we still need to repaint quite fast.
crate::profile_scope!("bg_sleep");
std::thread::sleep(std::time::Duration::from_millis(10));
}
};
match event {
// Platform-dependent event handlers to workaround a winit bug
// See: https://github.com/rust-windowing/winit/issues/987
// See: https://github.com/rust-windowing/winit/issues/1619
winit::event::Event::RedrawEventsCleared if cfg!(windows) => redraw(),
winit::event::Event::RedrawRequested(_) if !cfg!(windows) => redraw(),
winit::event::Event::WindowEvent { event, .. } => {
match &event {
winit::event::WindowEvent::Focused(new_focused) => {
is_focused = *new_focused;
}
winit::event::WindowEvent::Resized(physical_size) => {
// Resize with 0 width and height is used by winit to signal a minimize event on Windows.
// See: https://github.com/rust-windowing/winit/issues/208
// This solves an issue where the app would panic when minimizing on Windows.
if physical_size.width > 0 && physical_size.height > 0 {
painter.on_window_resized(physical_size.width, physical_size.height);
}
}
winit::event::WindowEvent::ScaleFactorChanged { new_inner_size, .. } => {
painter.on_window_resized(new_inner_size.width, new_inner_size.height);
}
winit::event::WindowEvent::CloseRequested => {
*control_flow = winit::event_loop::ControlFlow::Exit;
}
_ => {}
};
integration.on_event(app.as_mut(), &event);
if integration.should_quit() {
*control_flow = winit::event_loop::ControlFlow::Exit;
}
window.request_redraw(); // TODO: ask egui if the events warrants a repaint instead
}
winit::event::Event::LoopDestroyed => {
integration.save(&mut *app, window);
#[cfg(feature = "glow")]
app.on_exit(None);
#[cfg(not(feature = "glow"))]
app.on_exit();
painter.destroy();
}
winit::event::Event::UserEvent(RequestRepaintEvent) => window.request_redraw(),
_ => (),
}
});

View File

@@ -167,14 +167,16 @@ impl AppRunner {
egui_ctx: egui_ctx.clone(),
integration_info: info.clone(),
storage: Some(&storage),
gl: painter.painter.gl().clone(),
#[cfg(feature = "glow")]
gl: Some(painter.painter.gl().clone()),
});
let frame = epi::Frame {
info,
output: Default::default(),
storage: Some(Box::new(storage)),
gl: painter.gl().clone(),
#[cfg(feature = "glow")]
gl: Some(painter.gl().clone()),
};
let needs_repaint: std::sync::Arc<NeedRepaint> = Default::default();