wgpu + egui 0.20.0

android broken but let's just fix it on the egui/winit side once that's
all updated
This commit is contained in:
William Casarin
2022-12-10 16:57:46 -08:00
parent 3f64dedf76
commit b6f5d8dc03
8 changed files with 610 additions and 973 deletions

2
.envrc
View File

@@ -1 +1,3 @@
use nix
export PATH=$PATH:$HOME/.cargo/bin

1040
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -11,42 +11,22 @@ edition = "2021"
crate-type = ["lib", "cdylib"]
[dependencies]
chrono = "0.4"
egui = "0.19.0"
eframe = "0.19.0"
egui_extras = { version = "0.19.0", features = ["image", "svg"] }
#egui-winit = "0.19.0"
#egui-android = { git = "https://github.com/jb55/egui-android.git" }
egui = "0.20.0"
eframe = { version = "0.20.0", features = [ "wgpu" ] }
#eframe = "0.20.0"
egui_extras = { version = "0.20.0", features = ["image", "svg"] }
ehttp = "0.2.0"
epi = "0.17.0"
hex = "0.4.3"
image = { version = "0.24", features = ["jpeg", "png", "webp"] }
log = "0.4.17"
#nostr_rust = { git = "git://jb55.com/nostr_rust", rev = "ccf7e521fe3bb9ca8f86516aef2c1f71db0213ed" }
poll-promise = "0.2.0"
pollster = "0.2"
serde_derive = "1"
serde_json = { version = "1", default-features = false, features = ["std"] }
serde = { version = "1", features = ["derive"] } # You only need this if you want app persistence
sha2 = "0.10.6"
tracing = "0.1.37"
tracing-subscriber = "0.3"
#winit = "0.27.1"
# This dependency will only be included when targeting Android
[target.'cfg(target_os = "android")'.dependencies]
egui_wgpu_backend = "0.20.0"
wgpu = "0.14.0"
winit = { git="https://github.com/rust-windowing/winit.git", default-features = false, features = ["android-native-activity"] }
egui_winit_platform = {git = "https://github.com/inferrna/egui_winit_platform.git"}
[target.'cfg(debug_assertions)'.dependencies]
simple_logger = "*"
android_logger = "0.11.1"
# This dependency will only be included when targeting Android
[target.'cfg(not(target_os = "android"))'.dependencies]
winit = { git="https://github.com/rust-windowing/winit.git" }
ewebsock = "0.2.0"
#wasm-bindgen = "0.2.83"
wasm-bindgen-futures = "0.4"
# web:
@@ -54,12 +34,15 @@ winit = { git="https://github.com/rust-windowing/winit.git" }
console_error_panic_hook = "0.1.6"
tracing-wasm = "0.2"
# This dependency will only be included when targeting Android
#[target.'cfg(target_os = "android")'.dependencies]
#winit = { git="https://github.com/rust-windowing/winit.git", default-features = false, features = ["android-native-activity"] }
[target.'cfg(target_os = "android")'.dependencies]
android_logger = "0.11.1"
#android-activity = "0.4.0"
#winit = "0.27.5"
#winit = { version = "0.28", features = [ "android-native-activity" ] }
#winit = { git="https://github.com/rust-windowing/winit.git", rev = "2a58b785fed2a3746f7c7eebce95bce67ddfd27c", features = ["android-native-activity"] }
[package.metadata.android]
#package = "com.damus"
package = "com.damus.app"
apk_name = "damus"
#assets = "assets"
@@ -75,39 +58,5 @@ max_sdk_version = 18
[[package.metadata.android.uses_permission]]
name = "android.permission.INTERNET"
# See https://developer.android.com/guide/topics/manifest/application-element
#[package.metadata.android.application]
#label = "Damus"
# See https://developer.android.com/guide/topics/manifest/application-element#debug
#
# Defaults to false.
#debuggable = false
# See https://developer.android.com/guide/topics/manifest/application-element#theme
#
# Example shows setting the theme of an application to fullscreen.
#theme = "@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen"
# Virtual path your application's icon for any mipmap level.
# If not specified, an icon will not be included in the APK.
#icon = "@mipmap/ic_launcher"
# See https://developer.android.com/guide/topics/manifest/application-element#label
#
# Defaults to the compiled artifact's name.
#[profile.release]
#opt-level = 2 # fast and small wasm
#[patch.crates-io]
# If you want to use the bleeding edge version of egui and eframe:
# egui = { git = "https://github.com/emilk/egui", branch = "master" }
# eframe = { git = "https://github.com/emilk/egui", branch = "master" }
# If you fork https://github.com/emilk/egui you can test with:
#egui = { path = "../egui/crates/egui" }
#eframe = { path = "../egui/crates/eframe" }
#egui_extras = { path = "../egui/crates/egui_extras", features = ["image", "svg"] }
[package.metadata.android.application]
label = "Damus"

View File

@@ -20,9 +20,11 @@ in
mkShell {
nativeBuildInputs = [
cargo-edit cargo-watch rustup rustfmt libiconv pkgconfig cmake fontconfig
cargo-udeps cargo-edit cargo-watch rustup rustfmt libiconv pkgconfig cmake fontconfig
brotli wabt
heaptrack
# android
jre openssl libiconv androidsdk
];

View File

@@ -1,366 +0,0 @@
// TODO: replace all of this old stuff with eframe once it supports
// android properly
use crate::app::Damus;
use ::egui::FontDefinitions;
use chrono::Timelike;
use egui_wgpu_backend::{RenderPass, ScreenDescriptor};
use egui_winit_platform::{Platform, PlatformDescriptor};
use log::{error, info, warn};
use std::iter;
use std::time::Instant;
use wgpu::CompositeAlphaMode;
use winit::event::Event::*;
use winit::event_loop::ControlFlow;
use winit::event_loop::EventLoop;
#[cfg(target_os = "android")]
use winit::{
event::StartCause, platform::android::EventLoopBuilderExtAndroid,
platform::run_return::EventLoopExtRunReturn,
};
/// A custom event type for the winit app.
#[derive(Debug, Clone, Copy)]
pub enum WinitEvent {
RequestRedraw,
}
/// This is the repaint signal type that egui needs for requesting a repaint from another thread.
/// It sends the custom RequestRedraw event to the winit event loop.
struct ExampleRepaintSignal(std::sync::Mutex<winit::event_loop::EventLoopProxy<WinitEvent>>);
impl epi::backend::RepaintSignal for ExampleRepaintSignal {
fn request_repaint(&self) {
match self.0.lock() {
Err(e) => {
error!(
"Failed to lock guard at {} line {} with error\n{}",
file!(),
line!(),
e
);
}
Ok(e) => {
let _ = e.send_event(WinitEvent::RequestRedraw);
}
};
}
}
#[cfg(target_os = "android")]
#[no_mangle]
pub fn android_main(app: winit::platform::android::activity::AndroidApp) {
#[cfg(debug_assertions)]
{
std::env::set_var("RUST_BACKTRACE", "full");
android_logger::init_once(
android_logger::Config::default().with_min_level(log::Level::Trace),
);
}
let event_loop = winit::event_loop::EventLoopBuilder::<WinitEvent>::with_user_event()
.with_android_app(app)
.build();
run_evloop(event_loop);
}
pub fn run_evloop(mut event_loop: EventLoop<WinitEvent>) {
//'Cannot get the native window, it's null and will always be null before Event::Resumed and after Event::Suspended. Make sure you only call this function between those events.', ..../winit-c2fdb27092aba5a7/418cc44/src/platform_impl/android/mod.rs:1028:13
warn!("Winit build window at {} line {}", file!(), line!());
let window = winit::window::WindowBuilder::new()
.with_decorations(!cfg!(android)) /* !cfg!(android) */
.with_resizable(!cfg!(android))
.with_transparent(false)
.with_title("egui-wgpu_winit example")
.build(&event_loop)
.unwrap_or_else(|e| {
panic!(
"Failed to init window at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
});
warn!("WGPU new instance at {} line {}", file!(), line!());
let instance = wgpu::Instance::new(wgpu::Backends::PRIMARY);
let mut size = window.inner_size();
let outer_size = window.outer_size();
warn!("outer_size = {:?}", outer_size);
warn!("size = {:?}", size);
warn!("Create platform at {} line {}", file!(), line!());
// We use the egui_winit_platform crate as the platform.
let mut platform = Platform::new(PlatformDescriptor {
physical_width: size.width as u32,
physical_height: size.height as u32,
scale_factor: window.scale_factor(),
font_definitions: FontDefinitions::default(),
style: Default::default(),
});
let mut recreate_surface = false;
#[cfg(target_os = "android")]
let mut platform = {
//Just find the actual screen size on android
event_loop.run_return(|main_event, tgt, control_flow| {
control_flow.set_poll();
warn!(
"Got event: {:?} at {} line {}",
&main_event,
file!(),
line!()
);
match main_event {
NewEvents(e) => match e {
StartCause::ResumeTimeReached { .. } => {}
StartCause::WaitCancelled { .. } => {}
StartCause::Poll => {}
StartCause::Init => {}
},
WindowEvent {
//window_id,
ref event,
..
} => {
if let winit::event::WindowEvent::Resized(r) = event {
size = *r;
}
}
DeviceEvent { .. } => {}
UserEvent(_) => {}
Suspended => {
info!("Suspended");
control_flow.set_poll();
}
Resumed => {
if let Some(primary_mon) = tgt.primary_monitor() {
size = primary_mon.size();
window.set_inner_size(size);
warn!(
"Set to new size: {:?} at {} line {}",
&size,
file!(),
line!()
);
} else if let Some(other_mon) = tgt.available_monitors().next() {
size = other_mon.size();
window.set_inner_size(size);
warn!(
"Set to new size: {:?} at {} line {}",
&size,
file!(),
line!()
);
}
info!("Resumed");
recreate_surface = true;
control_flow.set_exit();
}
MainEventsCleared => {}
RedrawRequested(_rdr) => {}
RedrawEventsCleared => {}
LoopDestroyed => {}
};
platform.handle_event(&main_event);
});
warn!("Recreate platform at {} line {}", file!(), line!());
// We use the egui_winit_platform crate as the platform.
Platform::new(PlatformDescriptor {
physical_width: size.width as u32,
physical_height: size.height as u32,
scale_factor: window.scale_factor(),
font_definitions: FontDefinitions::default(),
style: Default::default(),
})
};
warn!("WGPU new surface at {} line {}", file!(), line!());
let mut surface = unsafe { instance.create_surface(&window) };
warn!("instance request_adapter at {} line {}", file!(), line!());
// WGPU 0.11+ support force fallback (if HW implementation not supported), set it to true or false (optional).
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
compatible_surface: Some(&surface),
force_fallback_adapter: false,
}))
.unwrap_or_else(|| panic!("Failed get adapter at {} line {}", file!(), line!()));
warn!("adapter request_device at {} line {}", file!(), line!());
let (device, queue) = pollster::block_on(adapter.request_device(
&wgpu::DeviceDescriptor {
features: wgpu::Features::default(),
limits: wgpu::Limits::default(),
label: None,
},
None,
))
.unwrap_or_else(|e| {
panic!(
"Failed to request device at {} line {} with error\n{:?}",
file!(),
line!(),
e
)
});
let surface_format = surface.get_supported_formats(&adapter)[0];
let mut surface_config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
format: surface_format,
width: size.width as u32,
height: size.height as u32,
present_mode: wgpu::PresentMode::AutoNoVsync,
alpha_mode: CompositeAlphaMode::Auto,
};
warn!("surface configure at {} line {}", file!(), line!());
surface.configure(&device, &surface_config);
warn!("RenderPass new at {} line {}", file!(), line!());
// We use the egui_wgpu_backend crate as the render backend.
let mut egui_rpass = RenderPass::new(&device, surface_format, 1);
warn!("DemoWindows default at {} line {}", file!(), line!());
// Display the demo application that ships with egui.
let mut app = Damus::new();
app.add_test_events();
let start_time = Instant::now();
warn!("Enter the loop");
event_loop.run(move |event, _, control_flow| {
// Pass the winit events to the platform integration.
warn!("Got event: {:?} at {} line {}", &event, file!(), line!());
platform.handle_event(&event);
match event {
RedrawRequested(..) => {
platform.update_time(start_time.elapsed().as_secs_f64());
let output_frame = match surface.get_current_texture() {
Ok(frame) => frame,
Err(wgpu::SurfaceError::Outdated) => {
// This error occurs when the app is minimized on Windows.
// Silently return here to prevent spamming the console with:
error!("The underlying surface has changed, and therefore the swap chain must be updated");
recreate_surface = true;
return;
}
Err(wgpu::SurfaceError::Lost) => {
// This error occurs when the app is minimized on Windows.
// Silently return here to prevent spamming the console with:
error!("LOST surface, drop frame. Originally: \"The swap chain has been lost and needs to be recreated\"");
recreate_surface = true;
return;
}
Err(e) => {
error!("Dropped frame with error: {}", e);
return;
}
};
let output_view = output_frame
.texture
.create_view(&wgpu::TextureViewDescriptor::default());
// Begin to draw the UI frame.
platform.begin_frame();
// Draw the demo application.
app.ui(&platform.context());
// End the UI frame. We could now handle the output and draw the UI with the backend.
let full_output = platform.end_frame(Some(&window));
let paint_jobs = platform.context().tessellate(full_output.shapes);
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("encoder"),
});
// Upload all resources for the GPU.
let screen_descriptor = ScreenDescriptor {
physical_width: surface_config.width,
physical_height: surface_config.height,
scale_factor: window.scale_factor() as f32
};
let tdelta: egui::TexturesDelta = full_output.textures_delta;
egui_rpass
.add_textures(&device, &queue, &tdelta)
.expect("add texture ok");
egui_rpass.update_buffers(&device, &queue, &paint_jobs, &screen_descriptor);
// Record all render passes.
egui_rpass
.execute(
&mut encoder,
&output_view,
&paint_jobs,
&screen_descriptor,
Some(wgpu::Color::BLACK),
)
.unwrap_or_else(|e| panic!("Failed to render pass at {} line {} with error\n{:?}", file!(), line!(), e));
// Submit the commands.
queue.submit(iter::once(encoder.finish()));
// Redraw egui
output_frame.present();
egui_rpass
.remove_textures(tdelta)
.expect("remove texture ok");
// Support reactive on windows only, but not on linux.
// if _output.needs_repaint {
// *control_flow = ControlFlow::Poll;
// } else {
// *control_flow = ControlFlow::Wait;
// }
}
MainEventsCleared | UserEvent(WinitEvent::RequestRedraw) => {
window.request_redraw();
}
WindowEvent { event, .. } => match event {
winit::event::WindowEvent::Resized(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 size.width > 0 && size.height > 0 {
surface_config.width = size.width;
surface_config.height = size.height;
surface.configure(&device, &surface_config);
}
}
winit::event::WindowEvent::CloseRequested => {
*control_flow = ControlFlow::Exit;
}
_ => {}
},
Resumed => {
info!("Damus Resumed (recreate surface? {})", recreate_surface);
if recreate_surface {
//https://github.com/gfx-rs/wgpu/issues/2302
warn!("WGPU new surface at {} line {}", file!(), line!());
surface = unsafe { instance.create_surface(&window) };
warn!("surface configure at {} line {}", file!(), line!());
surface.configure(&device, &surface_config);
recreate_surface = false;
}
},
Suspended => {
recreate_surface = true;
},
_ => (),
}
});
}
/// Time of day as seconds since midnight. Used for clock in demo app.
pub fn seconds_since_midnight() -> f64 {
let time = chrono::Local::now().time();
time.num_seconds_from_midnight() as f64 + 1e-9 * (time.nanosecond() as f64)
}

View File

@@ -1,4 +1,5 @@
//use egui::TextureFilter;
//use egui_android::SimpleApp;
use egui_extras::RetainedImage;
//use nostr_rust::events::Event;
@@ -61,15 +62,15 @@ pub fn is_mobile(ctx: &egui::Context) -> bool {
screen_size.x < 550.0
}
impl Damus<'_> {
pub fn ui(&mut self, ctx: &Context) {
if is_mobile(ctx) {
render_damus_mobile(ctx, self)
} else {
render_damus_desktop(ctx, self)
}
fn damus_update(damus: &mut Damus, ctx: &Context) {
if is_mobile(ctx) {
render_damus_mobile(ctx, damus);
} else {
render_damus_desktop(ctx, damus);
}
}
impl Damus<'_> {
pub fn add_test_events(&mut self) {
add_test_events(self);
}
@@ -208,8 +209,8 @@ fn timeline_view(ui: &mut egui::Ui, app: &mut Damus<'_>) {
.auto_shrink([false; 2])
.show(ui, |ui| {
for ev in &app.events {
ui.separator();
render_event(ui, &mut app.img_cache, ev);
ui.separator();
}
});
}
@@ -231,7 +232,7 @@ fn render_panel(ctx: &egui::Context, app: &mut Damus<'_>) {
if app.n_panels != 1 {
if ui
.add(egui::Button::new("-").frame(false))
.on_hover_text("Add Timeline")
.on_hover_text("Remove Timeline")
.clicked()
{
app.n_panels -= 1;
@@ -261,6 +262,15 @@ fn render_damus_desktop(ctx: &egui::Context, app: &mut Damus<'_>) {
calc_panel_width
};
if app.n_panels == 1 {
let panel_width = ctx.input().screen_rect.width();
egui::CentralPanel::default().show(ctx, |ui| {
timeline_panel(ui, app, panel_width, 0);
});
return;
}
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::horizontal()
.auto_shrink([false; 2])
@@ -323,14 +333,14 @@ fn add_test_events(damus: &mut Damus<'_>) {
impl eframe::App for Damus<'_> {
/// Called by the frame work to save state before shutdown.
fn save(&mut self, storage: &mut dyn eframe::Storage) {
fn save(&mut self, _storage: &mut dyn eframe::Storage) {
//eframe::set_value(storage, eframe::APP_KEY, self);
}
/// Called each time the UI needs repainting, which may be many times per second.
/// Put your widgets into a `SidePanel`, `TopPanel`, `CentralPanel`, `Window` or `Area`.
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
self.ui(ctx);
damus_update(self, ctx);
}
}

View File

@@ -2,6 +2,11 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] // hide console window on Windows in release
use damus::Damus;
use eframe;
use log::info;
// Entry point for wasm
//#[cfg(target_arch = "wasm32")]
//use wasm_bindgen::prelude::*;
// Desktop
#[cfg(not(target_arch = "wasm32"))]
@@ -17,20 +22,22 @@ fn main() {
);
}
// Web
#[cfg(target_arch = "wasm32")]
fn main() {
pub fn main() {
// Make sure panics are logged using `console.error`.
console_error_panic_hook::set_once();
// Redirect tracing to console.log and friends:
tracing_wasm::set_as_global_default();
let web_options = eframe::WebOptions::default();
eframe::start_web(
"the_canvas_id", // hardcode it
web_options,
Box::new(|_cc| Box::new(Damus::new())),
)
.expect("failed to start eframe");
wasm_bindgen_futures::spawn_local(async {
let web_options = eframe::WebOptions::default();
eframe::start_web(
"the_canvas_id", // hardcode it
web_options,
Box::new(|_cc| Box::new(Damus::new())),
)
.await
.expect("failed to start eframe");
});
}

View File

@@ -1,8 +1,31 @@
#[cfg(target_os = "android")]
pub mod android;
mod app;
//mod camera;
mod event;
pub use app::Damus;
pub use event::Event;
//#[cfg(target_os = "android")]
//use egui_android::run_android;
#[cfg(target_os = "android")]
use winit::platform::android::activity::AndroidApp;
#[cfg(target_os = "android")]
#[no_mangle]
pub fn android_main(app: AndroidApp) {
std::env::set_var("RUST_BACKTRACE", "full");
android_logger::init_once(android_logger::Config::default().with_min_level(log::Level::Info));
let mut options = eframe::NativeOptions::default();
options.renderer = eframe::Renderer::Wgpu;
options.event_loop_builder = Some(Box::new(move |builder| {
builder.with_android_app(app);
}));
eframe::run_native(
"Damus Desktop",
options,
Box::new(|_cc| Box::new(Damus::new())),
);
}