Skip to content

Commit

Permalink
Update event loop
Browse files Browse the repository at this point in the history
  • Loading branch information
nanoqsh committed Jan 9, 2024
1 parent 047e1a8 commit 040ed4c
Show file tree
Hide file tree
Showing 8 changed files with 154 additions and 53 deletions.
11 changes: 8 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ bytemuck = "1.13"
glam = "0.25"

[workspace.lints.clippy]
use_self = "deny"
unwrap_used = "deny"
missing_assert_message = "deny"
use-self = "deny"
unwrap-used = "deny"
missing-assert-message = "deny"
match-wildcard-for-single-variants = "deny"
flat-map-option = "deny"
semicolon-if-nothing-returned = "deny"
manual-assert = "deny"
needless-pass-by-value = "deny"

[profile.dev]
opt-level = 1
Expand Down
169 changes: 129 additions & 40 deletions dunge/src/el.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use {
error::EventLoopError,
event,
event_loop::{self, EventLoop},
keyboard,
keyboard::{KeyCode, PhysicalKey, SmolStr},
},
};

Expand Down Expand Up @@ -62,26 +62,6 @@ impl fmt::Display for LoopError {

impl error::Error for LoopError {}

pub struct Control {
close: bool,
min_delta_time: Duration,
fps: u32,
}

impl Control {
pub fn close(&mut self) {
self.close = true;
}

pub fn set_min_delta_time(&mut self, min_delta_time: Duration) {
self.min_delta_time = min_delta_time;
}

pub fn fps(&self) -> u32 {
self.fps
}
}

type Event = event::Event<()>;
type Target = event_loop::EventLoopWindowTarget<()>;

Expand All @@ -90,24 +70,32 @@ where
U: Update,
{
use {
event::{KeyEvent, StartCause, WindowEvent},
event::{ElementState, KeyEvent, StartCause, WindowEvent},
event_loop::ControlFlow,
keyboard::{KeyCode, PhysicalKey},
winit::dpi::PhysicalSize,
};

const WAIT_TIME: Duration = Duration::from_millis(100);

let mut ctrl = Control {
close: false,
min_delta_time: Duration::from_secs_f32(1. / 60.),
fps: 0,
pressed_keys: vec![],
released_keys: vec![],
};

// Initial state
let mut active = false;
let mut render = Render::default();
let mut time = Time::now();
let mut fps = Fps::default();
move |ev, target| match ev {
Event::NewEvents(cause) => match cause {
StartCause::ResumeTimeReached { .. } => {
log::debug!("resume time reached");
if ctrl.close {
log::debug!("close");
target.exit();
return;
}
Expand All @@ -117,32 +105,73 @@ where
StartCause::WaitCancelled {
requested_resume, ..
} => {
log::debug!("wait cancelled");
let flow = match requested_resume {
Some(resume) => ControlFlow::WaitUntil(resume),
None => {
const WAIT_TIME: Duration = Duration::from_millis(100);

ControlFlow::wait_duration(WAIT_TIME)
}
None => ControlFlow::wait_duration(WAIT_TIME),
};

target.set_control_flow(flow)
}
StartCause::Poll => {}
StartCause::Init => {}
StartCause::Poll => log::debug!("poll"),
StartCause::Init => log::debug!("init"),
},
Event::WindowEvent { event, window_id } if window_id == view.id() => match event {
WindowEvent::Resized(_) => view.resize(cx.state()),
WindowEvent::CloseRequested
| WindowEvent::KeyboardInput {
WindowEvent::Resized(PhysicalSize { width, height }) => {
log::debug!("resized: {width}, {height}");
view.resize(cx.state());
}
WindowEvent::CloseRequested => {
log::debug!("close requested");
target.exit();
}
WindowEvent::Focused(true) => {
log::debug!("focused");
view.request_redraw();
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
physical_key: PhysicalKey::Code(KeyCode::Escape),
physical_key,
text,
location,
state,
..
},
is_synthetic: false,
..
} => target.exit(),
} => {
let code = match physical_key {
PhysicalKey::Code(code) => {
log::debug!("keyboard input: {code:?}");
code
}
PhysicalKey::Unidentified(code) => {
log::debug!("keyboard input: (unidentified) {code:?}");
return;
}
};

// TODO: Support key location
_ = location;

let key = Key { code, text };
match state {
ElementState::Pressed => ctrl.pressed_keys.push(key),
ElementState::Released => ctrl.released_keys.push(key),
}
}
WindowEvent::RedrawRequested => {
if active {
log::debug!("redraw requested");
} else {
log::debug!("redraw requested (non-active)");

// Wait a while to become active
target.set_control_flow(ControlFlow::wait_duration(WAIT_TIME));
return;
}

let delta_time = time.delta();
if delta_time < ctrl.min_delta_time {
let wait = ctrl.min_delta_time - delta_time;
Expand All @@ -156,21 +185,81 @@ where
}

update.update(&mut ctrl);
ctrl.clear_keys();
match view.output() {
Ok(output) => {
let view = RenderView::from_output(&output);
cx.state().draw(&mut render, view, &update);
output.present();
}
Err(SurfaceError::Lost) => view.resize(cx.state()),
Err(SurfaceError::OutOfMemory) => target.exit(),
Err(err) => eprintln!("{err:?}"),
Err(SurfaceError::Timeout) => log::info!("suface error: timeout"),
Err(SurfaceError::Outdated) => log::info!("suface error: outdated"),
Err(SurfaceError::Lost) => {
log::info!("suface error: lost");
view.resize(cx.state());
}
Err(SurfaceError::OutOfMemory) => {
log::error!("suface error: out of memory");
target.exit();
}
}
}
_ => {}
},
Event::Suspended => {}
Event::Resumed => view.request_redraw(),
Event::Suspended => {
log::debug!("suspended");
// TODO: Drop the surface
active = false;
}
Event::Resumed => {
log::debug!("resumed");
active = true;
view.request_redraw();

// Reset the timer before start the loop
time.reset();
}
_ => {}
}
}

pub struct Control {
close: bool,
min_delta_time: Duration,
fps: u32,
pressed_keys: Vec<Key>,
released_keys: Vec<Key>,
}

impl Control {
pub fn close(&mut self) {
self.close = true;
}

pub fn set_min_delta_time(&mut self, min_delta_time: Duration) {
self.min_delta_time = min_delta_time;
}

pub fn fps(&self) -> u32 {
self.fps
}

pub fn pressed_keys(&self) -> &[Key] {
&self.pressed_keys
}

pub fn released_keys(&self) -> &[Key] {
&self.released_keys
}

fn clear_keys(&mut self) {
self.pressed_keys.clear();
self.released_keys.clear();
}
}

#[derive(Clone)]
pub struct Key {
pub code: KeyCode,
pub text: Option<SmolStr>,
}
2 changes: 1 addition & 1 deletion dunge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub mod texture;
pub mod vertex;

#[cfg(feature = "winit")]
mod el;
pub mod el;
#[cfg(feature = "winit")]
mod time;
#[cfg(feature = "winit")]
Expand Down
3 changes: 3 additions & 0 deletions dunge/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ impl State {
.ok_or(Error::BackendSelection)?
};

let backend = adapter.get_info().backend;
log::info!("selected backend: {backend:?}");

let (device, queue) = {
use wgpu::{DeviceDescriptor, Limits};

Expand Down
2 changes: 1 addition & 1 deletion dunge_macros/src/group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub(crate) fn derive(input: DeriveInput) -> TokenStream {
};
}

lts.push(param.lifetime)
lts.push(param.lifetime);
}

if fields.is_empty() {
Expand Down
4 changes: 2 additions & 2 deletions dunge_shader/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ impl InputKind {
fn into_input_info(self) -> Option<InputInfo> {
match self {
Self::Type(info) => Some(info),
_ => None,
Self::Index => None,
}
}
}
Expand Down Expand Up @@ -136,7 +136,7 @@ impl Context {
self.inputs
.iter()
.copied()
.flat_map(InputKind::into_input_info)
.filter_map(InputKind::into_input_info)
}
}

Expand Down
8 changes: 5 additions & 3 deletions dunge_shader/src/eval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,8 @@ where
let ReadGlobal { id, binding, out } = self.get();
out.with_stage(E::STAGE);
let en = en.get_entry();
let var = en.compl.globs.get(ResourceBinding { group: id, binding });
let res = ResourceBinding { group: id, binding };
let var = en.compl.globs.get(&res);
en.global(var)
}
}
Expand Down Expand Up @@ -487,6 +488,7 @@ struct Built {
point: EntryPoint,
}

#[derive(Clone, Copy)]
enum Return {
Ty(Handle<Type>),
Color,
Expand Down Expand Up @@ -828,8 +830,8 @@ impl Globals {
});
}

fn get(&self, res: ResourceBinding) -> Handle<GlobalVariable> {
self.handles[&res]
fn get(&self, res: &ResourceBinding) -> Handle<GlobalVariable> {
self.handles[res]
}
}

Expand Down
8 changes: 5 additions & 3 deletions helpers/src/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,11 @@ impl Image {
let mut reader = decoder.read_info().expect("png reader");
let mut data = Box::from(vec![0; reader.output_buffer_size()]);
let info = reader.next_frame(&mut data).expect("read image");
if info.color_type != ColorType::Rgba {
panic!("only rgba format is supported");
}

assert!(
info.color_type == ColorType::Rgba,
"only rgba format is supported",
);

Self {
data,
Expand Down

0 comments on commit 040ed4c

Please sign in to comment.