Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update deps #21

Merged
merged 4 commits into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2,378 changes: 1,274 additions & 1,104 deletions Cargo.lock

Large diffs are not rendered by default.

27 changes: 13 additions & 14 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,20 @@ winit = ["dep:winit"]
[dependencies]
wasm-bindgen = "0.2.84"
wasm-bindgen-futures = "0.4.31"

pollster = "0.3.0"
bytemuck = { version = "1.9.1", features = ["derive"] }
log = "0.4.17"
env_logger = "0.10.0"
env_logger = "0.11.3"
num = "0.4.0"
regex = "1.5.6"
lazy_static = "1.4.0"
bitvec = "1.0.0"
lazy-regex = "2.3.0"
itertools = "0.10.3"
lazy-regex = "3.1.0"
itertools = "0.12.1"
futures-intrusive = "0.5.0"
async-recursion = "1.0.0"
snailquote = "0.3.1"
indexmap = "1.9.3"
indexmap = "2.2.5"

# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
Expand All @@ -47,21 +46,21 @@ wee_alloc = { version = "0.4.5", optional = true }
console_log = "1.0.0"
js-sys = "0.3.57"
web-sys = "0.3.57"
gloo-utils = "0.1.4"
gloo-net = "0.2.1"
raw-window-handle = "0.5.2"
gloo-utils = "0.2.0"
gloo-net = "0.5.0"
raw-window-handle = { version = "0.6.0", features = ["wasm-bindgen-0-2"] }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
reqwest = "0.11.16"
reqwest-middleware = "0.1"
reqwest-middleware-cache = "0.1"
reqwest-middleware = "0.2.4"
http-cache-reqwest = "0.13.0"
tokio = { version = "1.27.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
winit = { version = "0.28.5", optional = true }
winit = { version = "0.29.14", optional = true }

[dependencies.wgpu]
version = "0.16.0"
version = "0.19.3"

[dependencies.image]
version = "0.24.2"
Expand All @@ -73,9 +72,9 @@ version = "0.1.12"
features = ["wasm-bindgen"]

[dependencies.cached]
version = "0.43.0"
version = "0.49.2"
default-features = false
features = ["proc_macro", "wasm"]
features = ["proc_macro", "wasm", "async"]

[dev-dependencies]
wasm-bindgen-test = "0.3.31"
Expand Down
102 changes: 66 additions & 36 deletions src/bin/toy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,36 @@ fn main() -> Result<(), Box<dyn Error>> {
#[cfg(not(feature = "winit"))]
return Err("must be compiled with winit feature to run".into());

#[cfg(feature = "winit")]
#[cfg(all(feature = "winit", not(target_arch = "wasm32")))]
return winit::main();

#[cfg(all(feature = "winit", target_arch = "wasm32"))]
return Err("winit not supported on wasm target".into());
}

#[cfg(feature = "winit")]
#[cfg(all(feature = "winit", not(target_arch = "wasm32")))]
mod winit {
use http_cache_reqwest::{CACacheManager, Cache, CacheMode, HttpCache, HttpCacheOptions};
use serde::{Deserialize, Serialize};
use std::error::Error;
use wgputoy::context::init_wgpu;
use wgputoy::WgpuToyRenderer;
use winit::{
event::{ElementState, Event, WindowEvent},
event_loop::ControlFlow,
};

#[cfg(not(wasm_platform))]
use std::time;
#[cfg(wasm_platform)]
use web_time as time;

const POLL_SLEEP_TIME: time::Duration = time::Duration::from_millis(100);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
Poll,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
Expand Down Expand Up @@ -47,10 +67,11 @@ mod winit {
let shader = std::fs::read_to_string(&filename)?;

let client = reqwest_middleware::ClientBuilder::new(reqwest::Client::new())
.with(reqwest_middleware_cache::Cache {
mode: reqwest_middleware_cache::CacheMode::Default,
cache_manager: reqwest_middleware_cache::managers::CACacheManager::default(),
})
.with(Cache(HttpCache {
mode: CacheMode::Default,
manager: CACacheManager::default(),
options: HttpCacheOptions::default(),
}))
.build();

if let Ok(json) = std::fs::read_to_string(std::format!("{filename}.json")) {
Expand Down Expand Up @@ -101,45 +122,54 @@ mod winit {
std::thread::spawn(move || loop {
device_clone.poll(wgpu::Maintain::Wait);
});
event_loop.run(move |event, _, control_flow| {
*control_flow = winit::event_loop::ControlFlow::Poll;
match event {
winit::event::Event::RedrawRequested(_) => {
let time = start_time.elapsed().as_micros() as f32 * 1e-6;
wgputoy.set_time_elapsed(time);
let future = wgputoy.render_async();
runtime.block_on(future);

let mode = Mode::Poll;
let mut close_requested = false;

let _ = event_loop.run(move |event, elwt| match event {
Event::WindowEvent { event, .. } => match event {
WindowEvent::CloseRequested => {
close_requested = true;
}
winit::event::Event::MainEventsCleared => {
wgputoy.wgpu.window.request_redraw();
WindowEvent::CursorMoved { position, .. } => {
wgputoy.set_mouse_pos(
position.x as f32 / screen_size.width as f32,
position.y as f32 / screen_size.height as f32,
);
}
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::CloseRequested,
..
} => *control_flow = winit::event_loop::ControlFlow::Exit,
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::CursorMoved { position, .. },
..
} => wgputoy.set_mouse_pos(
position.x as f32 / screen_size.width as f32,
position.y as f32 / screen_size.height as f32,
),
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::Resized(size),
..
} => {
WindowEvent::MouseInput { state, .. } => {
wgputoy.set_mouse_click(state == ElementState::Pressed);
}
WindowEvent::Resized(size) => {
if size.width != 0 && size.height != 0 {
wgputoy.resize(size.width, size.height, 1.);
}
}
winit::event::Event::WindowEvent {
event: winit::event::WindowEvent::MouseInput { state, .. },
..
} => wgputoy.set_mouse_click(state == winit::event::ElementState::Pressed),
WindowEvent::RedrawRequested => {
let time = start_time.elapsed().as_micros() as f32 * 1e-6;
wgputoy.set_time_elapsed(time);
let future = wgputoy.render_async();
runtime.block_on(future);
}
_ => (),
},
Event::AboutToWait => {
wgputoy.wgpu.window.request_redraw();

match mode {
Mode::Poll => {
std::thread::sleep(POLL_SLEEP_TIME);
elwt.set_control_flow(ControlFlow::Poll);
}
_ => (),
};

if close_requested {
elwt.exit();
}
}
_ => (),
});

Ok(())
}
}
15 changes: 7 additions & 8 deletions src/bind.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::WgpuContext;
use bitvec::prelude::*;
use itertools::Itertools;
use std::mem::size_of;

const NUM_KEYCODES: usize = 256;
Expand Down Expand Up @@ -596,19 +595,19 @@ impl Bindings {
}

pub fn to_wgsl(&self) -> String {
self.to_vec()
.iter()
.enumerate()
.map(|(i, b)| {
// Note: In the future, the Rust standard library might get a intersperse method, see https://github.com/rust-lang/rust/issues/79524
itertools::Itertools::intersperse(
self.to_vec().iter().enumerate().map(|(i, b)| {
let d = b.to_wgsl();
if d.is_empty() {
String::new()
} else {
format!("@group(0) @binding({i}) {};", b.to_wgsl())
}
})
.intersperse("\n".to_string())
.collect()
}),
"\n".to_string(),
)
.collect()
}

pub fn stage(&self, queue: &wgpu::Queue) {
Expand Down
4 changes: 3 additions & 1 deletion src/blit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,12 @@ impl Blitter {
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::GREEN),
store: true,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: None,
occlusion_query_set: None,
timestamp_writes: None,
});
render_pass.set_pipeline(&self.render_pipeline);
render_pass.set_bind_group(0, &self.render_bind_group, &[]);
Expand Down
48 changes: 27 additions & 21 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use std::sync::Arc;

#[cfg(target_arch = "wasm32")]
use raw_window_handle::{
HasRawDisplayHandle, HasRawWindowHandle, RawDisplayHandle, RawWindowHandle, WebDisplayHandle,
WebWindowHandle,
DisplayHandle, HasDisplayHandle, HasWindowHandle, WebCanvasWindowHandle, WebDisplayHandle,
WindowHandle,
};

pub struct WgpuContext {
Expand All @@ -13,28 +13,27 @@ pub struct WgpuContext {
pub window: winit::window::Window,
pub device: Arc<wgpu::Device>,
pub queue: wgpu::Queue,
pub surface: wgpu::Surface,
pub surface: wgpu::Surface<'static>,
pub surface_config: wgpu::SurfaceConfiguration,
}

#[cfg(target_arch = "wasm32")]
struct CanvasWindow {
id: u32,
handle: WebCanvasWindowHandle,
}

#[cfg(target_arch = "wasm32")]
unsafe impl HasRawWindowHandle for CanvasWindow {
fn raw_window_handle(&self) -> RawWindowHandle {
let mut window_handle = WebWindowHandle::empty();
window_handle.id = self.id;
RawWindowHandle::Web(window_handle)
impl HasWindowHandle for CanvasWindow {
fn window_handle(&self) -> Result<WindowHandle<'_>, raw_window_handle::HandleError> {
unsafe { Ok(WindowHandle::borrow_raw(self.handle.into())) }
}
}

#[cfg(target_arch = "wasm32")]
unsafe impl HasRawDisplayHandle for CanvasWindow {
fn raw_display_handle(&self) -> RawDisplayHandle {
RawDisplayHandle::Web(WebDisplayHandle::empty())
impl HasDisplayHandle for CanvasWindow {
fn display_handle(&self) -> Result<DisplayHandle<'_>, raw_window_handle::HandleError> {
// FIXME: Use raw_window_handle::DisplayHandle::<'static>::web() once a new version of raw_window_handle is released
unsafe { Ok(DisplayHandle::borrow_raw(WebDisplayHandle::new().into())) }
}
}

Expand All @@ -48,18 +47,18 @@ fn init_window(bind_id: &str) -> Result<CanvasWindow, Box<dyn std::error::Error>
let element = doc
.get_element_by_id(bind_id)
.ok_or(format!("cannot find element {bind_id}"))?;
use wasm_bindgen::JsCast;
use wasm_bindgen::{JsCast, JsValue};
let canvas = element
.dyn_into::<web_sys::HtmlCanvasElement>()
.or(Err("cannot cast to canvas"))?;
canvas
.get_context("webgpu")
.or(Err("no webgpu"))?
.ok_or("no webgpu")?;
canvas
.set_attribute("data-raw-handle", "42")
.or(Err("cannot set attribute"))?;
Ok(CanvasWindow { id: 42 })
let canvas_js_value: &JsValue = &canvas;
Ok(CanvasWindow {
handle: WebCanvasWindowHandle::from_wasm_bindgen_0_2(canvas_js_value),
})
}

#[cfg(all(not(target_arch = "wasm32"), feature = "winit"))]
Expand All @@ -79,7 +78,7 @@ fn init_window(
#[cfg(feature = "winit")]
pub async fn init_wgpu(width: u32, height: u32, bind_id: &str) -> Result<WgpuContext, String> {
#[cfg(not(target_arch = "wasm32"))]
let event_loop = winit::event_loop::EventLoop::new();
let event_loop = winit::event_loop::EventLoop::new().map_err(|e| e.to_string())?;
#[cfg(not(target_arch = "wasm32"))]
let window = init_window(
winit::dpi::Size::Physical(winit::dpi::PhysicalSize::new(width, height)),
Expand All @@ -93,8 +92,14 @@ pub async fn init_wgpu(width: u32, height: u32, bind_id: &str) -> Result<WgpuCon
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
backends: wgpu::Backends::PRIMARY,
dx12_shader_compiler: wgpu::Dx12Compiler::Fxc,
flags: wgpu::InstanceFlags::default(),
gles_minor_version: wgpu::Gles3MinorVersion::Automatic,
});
let surface = unsafe { instance.create_surface(&window) }.map_err(|e| e.to_string())?;

let surface = unsafe {
instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&window).unwrap())
}
.map_err(|e| e.to_string())?;

let adapter = instance
.request_adapter(&wgpu::RequestAdapterOptions {
Expand All @@ -108,8 +113,8 @@ pub async fn init_wgpu(width: u32, height: u32, bind_id: &str) -> Result<WgpuCon
.request_device(
&wgpu::DeviceDescriptor {
label: Some("GPU Device"),
features: wgpu::Features::empty(),
limits: wgpu::Limits::default(),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
},
None,
)
Expand All @@ -128,6 +133,7 @@ pub async fn init_wgpu(width: u32, height: u32, bind_id: &str) -> Result<WgpuCon
surface_format.add_srgb_suffix(),
surface_format.remove_srgb_suffix(),
],
desired_maximum_frame_latency: 1,
};
surface.configure(&device, &surface_config);

Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ impl WgpuToyRenderer {
Some(Ok(())) => {
let data = buffer_slice.get_mapped_range();
let assertions: &[u32] = bytemuck::cast_slice(&data[0..ASSERTS_SIZE]);
let timestamps: &[u64] = bytemuck::cast_slice(&data[ASSERTS_SIZE..]);
let _timestamps: &[u64] = bytemuck::cast_slice(&data[ASSERTS_SIZE..]);
for (i, count) in assertions.iter().enumerate() {
if count > &0 {
let percent =
Expand Down
1 change: 0 additions & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::WGSLError;
#[cfg(target_arch = "wasm32")]
use {
cached::proc_macro::cached, std::future::Future, wasm_bindgen::prelude::*,
wasm_bindgen::JsValue,
};

pub fn set_panic_hook() {
Expand Down
Loading