pub use winit::event::VirtualKeyCode as Key;
use {
crate::{context::Context, frame::Frame},
std::{fmt, iter, slice},
};
pub trait Loop {
type Error: From<Error> + fmt::Debug;
fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error>;
fn render(&self, frame: &mut Frame) -> Result<(), Self::Error>;
fn error_occurred(&mut self, err: Self::Error) {
log::error!("{err:?}");
}
fn close_requested(&mut self) -> bool {
true
}
}
impl<L> Loop for &mut L
where
L: Loop,
{
type Error = L::Error;
fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error> {
(**self).update(context, input)
}
fn render(&self, frame: &mut Frame) -> Result<(), Self::Error> {
(**self).render(frame)
}
}
impl<L> Loop for Box<L>
where
L: Loop,
{
type Error = L::Error;
fn update(&mut self, context: &mut Context, input: &Input) -> Result<(), Self::Error> {
self.as_mut().update(context, input)
}
fn render(&self, frame: &mut Frame) -> Result<(), Self::Error> {
self.as_ref().render(frame)
}
}
#[derive(Debug)]
pub enum Error {
ResourceNotFound,
InstanceNotSet,
}
pub struct Input<'a> {
pub delta_time: f32,
pub cursor_position: Option<(f32, f32)>,
pub mouse: Mouse,
pub pressed_keys: Keys<'a>,
pub released_keys: Keys<'a>,
}
#[derive(Clone, Copy, Default)]
pub struct Mouse {
pub motion_delta: (f32, f32),
pub wheel_delta: (f32, f32),
pub pressed_left: bool,
pub pressed_middle: bool,
pub pressed_right: bool,
}
#[derive(Clone, Copy)]
pub struct Keys<'a> {
pub(crate) keys: &'a [Key],
}
impl<'a> IntoIterator for Keys<'a> {
type Item = Key;
type IntoIter = KeysIterator<'a>;
fn into_iter(self) -> Self::IntoIter {
KeysIterator {
iter: self.keys.iter().copied(),
}
}
}
pub struct KeysIterator<'a> {
iter: iter::Copied<slice::Iter<'a, Key>>,
}
impl Iterator for KeysIterator<'_> {
type Item = Key;
fn next(&mut self) -> Option<Self::Item> {
self.iter.next()
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl ExactSizeIterator for KeysIterator<'_> {}