Skip to content

Commit

Permalink
Event loop example
Browse files Browse the repository at this point in the history
  • Loading branch information
nanoqsh committed Jan 9, 2024
1 parent 8765e2d commit dbf6ca4
Show file tree
Hide file tree
Showing 18 changed files with 202 additions and 106 deletions.
9 changes: 8 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
[workspace]
members = ["dunge", "dunge_macros", "dunge_shader", "helpers"]
resolver = "2"
members = [
"dunge",
"dunge_macros",
"dunge_shader",
"examples/triangle",
"helpers",
]

[workspace.dependencies]
bytemuck = "1.13"
glam = "0.25"
log = "0.4"

[workspace.lints.clippy]
use-self = "deny"
Expand Down
2 changes: 1 addition & 1 deletion dunge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ dunge_shader = { version = "0.2.3", path = "../dunge_shader" }
bytemuck = { workspace = true }
glam = { workspace = true }
instant = { version = "0.1", optional = true }
log = "0.4"
log = { workspace = true }
wgpu = { version = "0.18", default-features = false, features = ["naga"] }

[dependencies.winit]
Expand Down
8 changes: 4 additions & 4 deletions dunge/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ use {
crate::{
bind::{self, Binder, GroupHandler, UniqueBinding, Update, Visit},
draw::Draw,
format::Format,
layer::Layer,
mesh::{self, Mesh},
shader::Shader,
sl::IntoModule,
state::{Render, RenderView, State},
state::{Render, State},
texture::{
self, CopyBuffer, CopyBufferView, DrawTexture, Filter, Format, Make, MapResult, Mapped,
Sampler,
self, CopyBuffer, CopyBufferView, DrawTexture, Filter, Make, MapResult, Mapped, Sampler,
},
Vertex,
},
Expand Down Expand Up @@ -80,7 +80,7 @@ impl Context {
T: DrawTexture,
D: Draw,
{
let view = RenderView::from_texture(texture.draw_texture());
let view = texture.draw_texture().render_view();
self.0.draw(render, view, draw);
}

Expand Down
47 changes: 26 additions & 21 deletions dunge/src/el.rs
Original file line number Diff line number Diff line change
@@ -1,21 +1,24 @@
use {
crate::{
context::Context,
state::{Render, RenderView},
state::Render,
time::{Fps, Time},
update::Update,
window::View,
},
std::{error, fmt, time::Duration},
std::{cell::Cell, error, fmt, time::Duration},
wgpu::SurfaceError,
winit::{
error::EventLoopError,
event,
event_loop::{self, EventLoop},
keyboard::{KeyCode, PhysicalKey, SmolStr},
keyboard,
},
};

pub type KeyCode = keyboard::KeyCode;
pub type SmolStr = keyboard::SmolStr;

pub(crate) struct Loop(EventLoop<()>);

impl Loop {
Expand Down Expand Up @@ -72,14 +75,15 @@ where
use {
event::{ElementState, KeyEvent, StartCause, WindowEvent},
event_loop::ControlFlow,
keyboard::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.),
close: Cell::default(),
min_delta_time: Cell::new(Duration::from_secs_f32(1. / 60.)),
fps: 0,
pressed_keys: vec![],
released_keys: vec![],
Expand All @@ -94,12 +98,6 @@ where
Event::NewEvents(cause) => match cause {
StartCause::ResumeTimeReached { .. } => {
log::debug!("resume time reached");
if ctrl.close {
log::debug!("close");
target.exit();
return;
}

view.request_redraw();
}
StartCause::WaitCancelled {
Expand Down Expand Up @@ -173,8 +171,9 @@ where
}

let delta_time = time.delta();
if delta_time < ctrl.min_delta_time {
let wait = ctrl.min_delta_time - delta_time;
let min_delta_time = ctrl.min_delta_time.get();
if delta_time < min_delta_time {
let wait = min_delta_time - delta_time;
target.set_control_flow(ControlFlow::wait_duration(wait));
return;
}
Expand All @@ -184,11 +183,17 @@ where
ctrl.fps = fps;
}

update.update(&mut ctrl);
update.update(&ctrl);
if ctrl.close.get() {
log::debug!("close");
target.exit();
return;
}

ctrl.clear_keys();
match view.output() {
Ok(output) => {
let view = RenderView::from_output(&output);
let view = output.render_view();
cx.state().draw(&mut render, view, &update);
output.present();
}
Expand Down Expand Up @@ -224,20 +229,20 @@ where
}

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

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

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

pub fn fps(&self) -> u32 {
Expand Down
31 changes: 31 additions & 0 deletions dunge/src/format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
use wgpu::TextureFormat;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
RgbAlpha,
BgrAlpha,
}

impl Format {
pub(crate) const fn bytes(self) -> u32 {
match self {
Self::RgbAlpha => 4,
Self::BgrAlpha => 4,
}
}

pub(crate) const fn wgpu(self) -> TextureFormat {
match self {
Self::RgbAlpha => TextureFormat::Rgba8UnormSrgb,
Self::BgrAlpha => TextureFormat::Bgra8UnormSrgb,
}
}

pub(crate) const fn from_wgpu(format: TextureFormat) -> Option<Self> {
match format {
TextureFormat::Rgba8UnormSrgb => Some(Self::RgbAlpha),
TextureFormat::Bgra8UnormSrgb => Some(Self::BgrAlpha),
_ => None,
}
}
}
2 changes: 1 addition & 1 deletion dunge/src/layer.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use {
crate::{bind::Binding, mesh::Mesh, shader::Shader, state::State, texture::Format},
crate::{bind::Binding, format::Format, mesh::Mesh, shader::Shader, state::State},
std::{iter, marker::PhantomData},
wgpu::{RenderPass, RenderPipeline},
};
Expand Down
3 changes: 2 additions & 1 deletion dunge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ pub mod bind;
pub mod color;
pub mod context;
pub mod draw;
pub mod format;
pub mod group;
mod init;
pub mod layer;
Expand All @@ -21,7 +22,7 @@ pub mod update;
pub mod window;

pub use {
crate::init::context,
crate::{init::context, state::Frame},
dunge_macros::{Group, Vertex},
dunge_shader::{group::Group, sl, types, vertex::Vertex},
glam,
Expand Down
34 changes: 17 additions & 17 deletions dunge/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,16 @@ use {
color::Rgba,
context::Error,
draw::Draw,
format::Format,
layer::{Layer, SetLayer},
texture::{CopyBuffer, CopyTexture, DrawTexture, Format, Texture},
texture::{CopyBuffer, CopyTexture, DrawTexture},
},
std::sync::atomic::{self, AtomicUsize},
wgpu::{Color, CommandEncoder, Device, Instance, LoadOp, Queue, TextureView},
};

#[cfg(feature = "winit")]
use {crate::window::Output, wgpu::Adapter};
use wgpu::Adapter;

pub(crate) struct State {
#[cfg(feature = "winit")]
Expand Down Expand Up @@ -116,6 +117,12 @@ impl Options {
}
}

impl From<Rgba> for Options {
fn from(v: Rgba) -> Self {
Self::default().with_clear(v)
}
}

pub struct Frame<'v, 'e> {
view: RenderView<'v>,
device: &'e Device,
Expand All @@ -128,18 +135,22 @@ impl Frame<'_, '_> {
where
T: DrawTexture,
{
let view = RenderView::from_texture(texture.draw_texture());
let view = texture.draw_texture().render_view();
self.encoders.make(self.device, view)
}

pub fn layer<'p, V>(&'p mut self, layer: &'p Layer<V>, opts: Options) -> SetLayer<'p, V> {
pub fn layer<'p, V, O>(&'p mut self, layer: &'p Layer<V>, opts: O) -> SetLayer<'p, V>
where
O: Into<Options>,
{
use wgpu::*;

assert!(
self.view.format == layer.format(),
"layer format doesn't match frame format",
);

let opts = opts.into();
let attachment = RenderPassColorAttachment {
view: self.view.txview,
resolve_target: None,
Expand Down Expand Up @@ -206,18 +217,7 @@ pub(crate) struct RenderView<'v> {
}

impl<'v> RenderView<'v> {
pub fn from_texture(texture: &'v Texture) -> Self {
Self {
txview: texture.view(),
format: texture.format(),
}
}

#[cfg(feature = "winit")]
pub fn from_output(output: &'v Output) -> Self {
Self {
txview: output.view(),
format: output.format(),
}
pub fn new(txview: &'v TextureView, format: Format) -> Self {
Self { txview, format }
}
}
38 changes: 9 additions & 29 deletions dunge/src/texture.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use {
crate::state::State,
crate::{
format::Format,
state::{RenderView, State},
},
std::{error, fmt, future::IntoFuture, mem},
wgpu::{
Buffer, BufferAsyncError, BufferSlice, BufferView, CommandEncoder, FilterMode,
TextureFormat, TextureUsages, TextureView, WasmNotSend,
TextureUsages, TextureView, WasmNotSend,
},
};

Expand Down Expand Up @@ -94,33 +97,6 @@ impl fmt::Display for ZeroSized {

impl error::Error for ZeroSized {}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Format {
RgbAlpha,
}

impl Format {
const fn bytes(self) -> u32 {
match self {
Self::RgbAlpha => 4,
}
}

pub(crate) const fn wgpu(self) -> TextureFormat {
match self {
Self::RgbAlpha => TextureFormat::Rgba8UnormSrgb,
}
}

#[allow(dead_code)]
const fn from_wgpu(format: TextureFormat) -> Option<Self> {
match format {
TextureFormat::Rgba8UnormSrgb => Some(Self::RgbAlpha),
_ => None,
}
}
}

pub struct Texture {
inner: wgpu::Texture,
view: TextureView,
Expand Down Expand Up @@ -191,6 +167,10 @@ impl Texture {
pub(crate) fn view(&self) -> &TextureView {
&self.view
}

pub(crate) fn render_view(&self) -> RenderView {
RenderView::new(&self.view, self.format())
}
}

pub(crate) fn make<M>(state: &State, data: M) -> M::Out
Expand Down
8 changes: 4 additions & 4 deletions dunge/src/update.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::{draw::Draw, el::Control, state::Frame};

pub trait Update: Draw {
fn update(&mut self, ctrl: &mut Control);
fn update(&mut self, ctrl: &Control);
}

pub fn from_fn<U, D>(update: U, draw: D) -> impl Update
where
U: FnMut(&mut Control),
U: FnMut(&Control),
D: Fn(Frame),
{
struct Func<U, D>(U, D);
Expand All @@ -22,10 +22,10 @@ where

impl<U, D> Update for Func<U, D>
where
U: FnMut(&mut Control),
U: FnMut(&Control),
D: Fn(Frame),
{
fn update(&mut self, ctrl: &mut Control) {
fn update(&mut self, ctrl: &Control) {
(self.0)(ctrl);
}
}
Expand Down
Loading

0 comments on commit dbf6ca4

Please sign in to comment.