use crate::data::input::*;
use crate::{emath::*, util::History};
use std::collections::HashSet;
pub use crate::data::input::Key;
const MAX_CLICK_DIST: f32 = 6.0;
const MAX_CLICK_DELAY: f64 = 0.3;
#[derive(Clone, Debug)]
pub struct InputState {
pub raw: RawInput,
pub pointer: PointerState,
pub scroll_delta: Vec2,
pub screen_rect: Rect,
pub pixels_per_point: f32,
pub time: f64,
pub unstable_dt: f32,
pub predicted_dt: f32,
pub modifiers: Modifiers,
pub keys_down: HashSet<Key>,
pub events: Vec<Event>,
}
impl Default for InputState {
fn default() -> Self {
Self {
raw: Default::default(),
pointer: Default::default(),
scroll_delta: Default::default(),
screen_rect: Rect::from_min_size(Default::default(), vec2(10_000.0, 10_000.0)),
pixels_per_point: 1.0,
time: 0.0,
unstable_dt: 1.0 / 6.0,
predicted_dt: 1.0 / 6.0,
modifiers: Default::default(),
keys_down: Default::default(),
events: Default::default(),
}
}
}
impl InputState {
#[must_use]
pub fn begin_frame(self, new: RawInput) -> InputState {
#![allow(deprecated)]
let time = new
.time
.unwrap_or_else(|| self.time + new.predicted_dt as f64);
let unstable_dt = (time - self.time) as f32;
let screen_rect = new.screen_rect.unwrap_or_else(|| {
if new.screen_size != Default::default() {
Rect::from_min_size(Default::default(), new.screen_size)
} else {
self.screen_rect
}
});
let pointer = self.pointer.begin_frame(time, &new);
let mut keys_down = self.keys_down;
for event in &new.events {
if let Event::Key { key, pressed, .. } = event {
if *pressed {
keys_down.insert(*key);
} else {
keys_down.remove(key);
}
}
}
InputState {
pointer,
scroll_delta: new.scroll_delta,
screen_rect,
pixels_per_point: new.pixels_per_point.unwrap_or(self.pixels_per_point),
time,
unstable_dt,
predicted_dt: new.predicted_dt,
modifiers: new.modifiers,
keys_down,
events: new.events.clone(),
raw: new,
}
}
pub fn screen_rect(&self) -> Rect {
self.screen_rect
}
pub fn wants_repaint(&self) -> bool {
self.pointer.wants_repaint() || self.scroll_delta != Vec2::ZERO || !self.events.is_empty()
}
pub fn key_pressed(&self, desired_key: Key) -> bool {
self.events.iter().any(|event| {
matches!(
event,
Event::Key {
key,
pressed: true,
..
} if *key == desired_key
)
})
}
pub fn key_down(&self, desired_key: Key) -> bool {
self.keys_down.contains(&desired_key)
}
pub fn key_released(&self, desired_key: Key) -> bool {
self.events.iter().any(|event| {
matches!(
event,
Event::Key {
key,
pressed: false,
..
} if *key == desired_key
)
})
}
pub fn pixels_per_point(&self) -> f32 {
self.pixels_per_point
}
pub fn physical_pixel_size(&self) -> f32 {
1.0 / self.pixels_per_point()
}
pub fn aim_radius(&self) -> f32 {
self.physical_pixel_size()
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Click {
pub pos: Pos2,
pub button: PointerButton,
pub count: u32,
pub modifiers: Modifiers,
}
impl Click {
pub fn is_double(&self) -> bool {
self.count == 2
}
}
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum PointerEvent {
Moved(Pos2),
Pressed(Pos2),
Released(Option<Click>),
}
impl PointerEvent {
pub fn is_press(&self) -> bool {
matches!(self, PointerEvent::Pressed(_))
}
pub fn is_release(&self) -> bool {
matches!(self, PointerEvent::Released(_))
}
pub fn is_click(&self) -> bool {
matches!(self, PointerEvent::Released(Some(_click)))
}
}
#[derive(Clone, Debug)]
pub struct PointerState {
latest_pos: Option<Pos2>,
interact_pos: Option<Pos2>,
delta: Vec2,
velocity: Vec2,
pos_history: History<Pos2>,
down: [bool; NUM_POINTER_BUTTONS],
press_origin: Option<Pos2>,
could_be_click: bool,
last_click_time: f64,
pub(crate) pointer_events: Vec<PointerEvent>,
}
impl Default for PointerState {
fn default() -> Self {
Self {
latest_pos: None,
interact_pos: None,
delta: Vec2::ZERO,
velocity: Vec2::ZERO,
pos_history: History::new(1000, 0.1),
down: Default::default(),
press_origin: None,
could_be_click: false,
last_click_time: std::f64::NEG_INFINITY,
pointer_events: vec![],
}
}
}
impl PointerState {
#[must_use]
pub(crate) fn begin_frame(mut self, time: f64, new: &RawInput) -> PointerState {
self.pointer_events.clear();
let old_pos = self.latest_pos;
self.interact_pos = self.latest_pos;
for event in &new.events {
match event {
Event::PointerMoved(pos) => {
let pos = *pos;
self.latest_pos = Some(pos);
self.interact_pos = Some(pos);
if let Some(press_origin) = &mut self.press_origin {
self.could_be_click &= press_origin.distance(pos) < MAX_CLICK_DIST;
} else {
self.could_be_click = false;
}
self.pointer_events.push(PointerEvent::Moved(pos));
}
Event::PointerButton {
pos,
button,
pressed,
modifiers,
} => {
let pos = *pos;
let button = *button;
let pressed = *pressed;
let modifiers = *modifiers;
self.latest_pos = Some(pos);
self.interact_pos = Some(pos);
if pressed {
self.pos_history.clear();
}
if pressed {
self.press_origin = Some(pos);
self.could_be_click = true;
self.pointer_events.push(PointerEvent::Pressed(pos));
} else {
let clicked = self.could_be_click;
let click = if clicked {
let double_click = (time - self.last_click_time) < MAX_CLICK_DELAY;
let count = if double_click { 2 } else { 1 };
self.last_click_time = time;
Some(Click {
pos,
button,
count,
modifiers,
})
} else {
None
};
self.pointer_events.push(PointerEvent::Released(click));
self.press_origin = None;
self.could_be_click = false;
}
self.down[button as usize] = pressed;
}
Event::PointerGone => {
self.latest_pos = None;
}
_ => {}
}
}
self.delta = if let (Some(old_pos), Some(new_pos)) = (old_pos, self.latest_pos) {
new_pos - old_pos
} else {
Vec2::ZERO
};
if let Some(pos) = self.latest_pos {
self.pos_history.add(time, pos);
} else {
}
self.pos_history.flush(time);
self.velocity = if self.pos_history.len() >= 3 && self.pos_history.duration() > 0.01 {
self.pos_history.velocity().unwrap_or_default()
} else {
Vec2::default()
};
self
}
fn wants_repaint(&self) -> bool {
!self.pointer_events.is_empty() || self.delta != Vec2::ZERO
}
pub fn delta(&self) -> Vec2 {
self.delta
}
pub fn velocity(&self) -> Vec2 {
self.velocity
}
pub fn press_origin(&self) -> Option<Pos2> {
self.press_origin
}
pub(crate) fn latest_pos(&self) -> Option<Pos2> {
self.latest_pos
}
pub fn tooltip_pos(&self) -> Option<Pos2> {
self.latest_pos
}
pub fn interact_pos(&self) -> Option<Pos2> {
self.interact_pos
}
pub fn has_pointer(&self) -> bool {
self.latest_pos.is_some()
}
pub fn is_still(&self) -> bool {
self.velocity == Vec2::ZERO
}
pub fn is_moving(&self) -> bool {
self.velocity != Vec2::ZERO
}
pub fn any_pressed(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_press())
}
pub fn any_released(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_release())
}
pub fn any_down(&self) -> bool {
self.down.iter().any(|&down| down)
}
pub fn any_click(&self) -> bool {
self.pointer_events.iter().any(|event| event.is_click())
}
pub fn button_down(&self, button: PointerButton) -> bool {
self.down[button as usize]
}
pub(crate) fn could_any_button_be_click(&self) -> bool {
self.could_be_click
}
}
impl InputState {
pub fn ui(&self, ui: &mut crate::Ui) {
let Self {
raw,
pointer,
scroll_delta,
screen_rect,
pixels_per_point,
time,
unstable_dt,
predicted_dt,
modifiers,
keys_down,
events,
} = self;
ui.style_mut().body_text_style = epaint::TextStyle::Monospace;
ui.collapsing("Raw Input", |ui| raw.ui(ui));
crate::containers::CollapsingHeader::new("🖱 Pointer")
.default_open(true)
.show(ui, |ui| {
pointer.ui(ui);
});
ui.label(format!("scroll_delta: {:?} points", scroll_delta));
ui.label(format!("screen_rect: {:?} points", screen_rect));
ui.label(format!(
"{:?} physical pixels for each logical point",
pixels_per_point
));
ui.label(format!("time: {:.3} s", time));
ui.label(format!(
"time since previous frame: {:.1} ms",
1e3 * unstable_dt
));
ui.label(format!("predicted_dt: {:.1} ms", 1e3 * predicted_dt));
ui.label(format!("modifiers: {:#?}", modifiers));
ui.label(format!("keys_down: {:?}", keys_down));
ui.label(format!("events: {:?}", events))
.on_hover_text("key presses etc");
}
}
impl PointerState {
pub fn ui(&self, ui: &mut crate::Ui) {
let Self {
latest_pos,
interact_pos,
delta,
velocity,
pos_history: _,
down,
press_origin,
could_be_click,
last_click_time,
pointer_events,
} = self;
ui.label(format!("latest_pos: {:?}", latest_pos));
ui.label(format!("interact_pos: {:?}", interact_pos));
ui.label(format!("delta: {:?}", delta));
ui.label(format!(
"velocity: [{:3.0} {:3.0}] points/sec",
velocity.x, velocity.y
));
ui.label(format!("down: {:#?}", down));
ui.label(format!("press_origin: {:?}", press_origin));
ui.label(format!("could_be_click: {:#?}", could_be_click));
ui.label(format!("last_click_time: {:#?}", last_click_time));
ui.label(format!("pointer_events: {:?}", pointer_events));
}
}