input handling stuff

This commit is contained in:
griffi-gh 2024-02-29 17:57:06 +01:00
parent 4745dcad1d
commit 99774e7f5f
4 changed files with 132 additions and 41 deletions

View file

@ -16,3 +16,22 @@ pub enum UiEvent {
}, },
TextInput(char), TextInput(char),
} }
#[derive(Default)]
pub(crate) struct EventQueue {
events: Vec<UiEvent>,
}
impl EventQueue {
pub(crate) fn new() -> Self {
Self::default()
}
pub(crate) fn push(&mut self, event: UiEvent) {
self.events.push(event);
}
pub(crate) fn drain(&mut self) -> std::vec::Drain<UiEvent> {
self.events.drain(..)
}
}

View file

@ -3,9 +3,9 @@
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use glam::Vec2; use glam::Vec2;
use hashbrown::HashMap; use hashbrown::HashMap;
use nohash_hasher::BuildNoHashHasher; use nohash_hasher::{BuildNoHashHasher, NoHashHasher};
use tinyset::{SetU32, SetUsize}; use tinyset::{Fits64, Set64, SetU32};
use crate::rectangle::Rect; use crate::{event::{EventQueue, UiEvent}, rectangle::Rect};
/// Represents a mouse button. /// Represents a mouse button.
/// ///
@ -60,42 +60,76 @@ impl ButtonState {
/// ///
/// Values of the `KeyCode` variant are not standardized and may change depending on the platform or the backend used. /// Values of the `KeyCode` variant are not standardized and may change depending on the platform or the backend used.
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum KeyboardKey { pub enum KeyboardKey {
//Keyboard buttons: //Keyboard buttons:
A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22, X = 23, Y = 24, Z = 25,
Num0, Num1, Num2, Num3, Num4, Num5, Num6, Num7, Num8, Num9, Num0 = 26, Num1 = 27, Num2 = 28, Num3 = 29, Num4 = 30, Num5 = 31, Num6 = 32, Num7 = 33, Num8 = 34, Num9 = 35,
Np0, Np1, Np2, Np3, Np4, Np5, Np6, Np7, Np8, Np9, Np0 = 36, Np1 = 37, Np2 = 38, Np3 = 39, Np4 = 40, Np5 = 41, Np6 = 42, Np7 = 43, Np8 = 44, Np9 = 45,
NpDivide, NpMultiply, NpSubtract, NpAdd, NpEnter, NpDecimal, NpDivide = 46, NpMultiply = 47, NpSubtract = 48, NpAdd = 49, NpEnter = 50, NpDecimal = 51,
F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, F1 = 52, F2 = 53, F3 = 54, F4 = 55, F5 = 56, F6 = 57, F7 = 58, F8 = 59, F9 = 60, F10 = 61, F11 = 62, F12 = 63,
Up, Down, Left, Right, Up = 64, Down = 65, Left = 66, Right = 67,
Space, Enter, Escape, Backspace, Tab, CapsLock, Space = 68, Enter = 69, Escape = 70, Backspace = 71, Tab = 72, CapsLock = 73,
LControl, RControl, LShift, RShift, LAlt, RAlt, LSuper, RSuper, LControl = 74, RControl = 75, LShift = 76, RShift = 77, LAlt = 78, RAlt = 79, LSuper = 80, RSuper = 81,
Grave, Minus, Equals, LeftBracket, RightBracket, Backslash, Semicolon, Apostrophe, Comma, Period, Slash, Grave = 82, Minus = 83, Equals = 84, LeftBracket = 85, RightBracket = 86, Backslash = 87, Semicolon = 88, Apostrophe = 89, Comma = 90, Period = 91, Slash = 92,
Insert, Delete, Home, End, PageUp, PageDown, PrintScreen, ScrollLock, Pause, Menu, NumLock, Insert = 93, Delete = 94, Home = 95, End = 96, PageUp = 97, PageDown = 98, PrintScreen = 99, ScrollLock = 100, Pause = 101, Menu = 102, NumLock = 103,
//Multimedia keys and android-specific (e.g. volume keys): //Multimedia keys and android-specific (e.g. volume keys):
Mute, VolumeUp, VolumeDown, MediaPlay, MediaStop, MediaNext, MediaPrevious, Mute = 104, VolumeUp = 105, VolumeDown = 106, MediaPlay = 107, MediaStop = 108, MediaNext = 109, MediaPrevious = 110,
//Keycode: //Keycode:
/// Represents a key code. /// Represents a key code.
/// ///
/// This enum variant holds an unsigned 32-bit integer representing a key code. /// This enum variant holds an unsigned 32-bit integer representing a key code.\
/// The value of the key code is not standardized and may change depending on the platform or the backend used. /// The value of the key code is not standardized and may change depending on the platform or the backend used.
KeyCode(u32), KeyCode(u32),
} }
macro_rules! impl_fits64_for_keyboard_key {
($($i:ident = $v:literal),*) => {
impl Fits64 for KeyboardKey {
unsafe fn from_u64(x: u64) -> Self {
match x {
$( $v => KeyboardKey::$i, )*
_ => KeyboardKey::KeyCode(x as u32),
}
}
fn to_u64(self) -> u64 {
match self {
$( KeyboardKey::$i => $v, )*
KeyboardKey::KeyCode(x) => x as u64 | 0x8000000000000000u64,
}
}
}
};
}
impl_fits64_for_keyboard_key!(
A = 0, B = 1, C = 2, D = 3, E = 4, F = 5, G = 6, H = 7, I = 8, J = 9, K = 10, L = 11, M = 12, N = 13, O = 14, P = 15, Q = 16, R = 17, S = 18, T = 19, U = 20, V = 21, W = 22, X = 23, Y = 24, Z = 25,
Num0 = 26, Num1 = 27, Num2 = 28, Num3 = 29, Num4 = 30, Num5 = 31, Num6 = 32, Num7 = 33, Num8 = 34, Num9 = 35,
Np0 = 36, Np1 = 37, Np2 = 38, Np3 = 39, Np4 = 40, Np5 = 41, Np6 = 42, Np7 = 43, Np8 = 44, Np9 = 45,
NpDivide = 46, NpMultiply = 47, NpSubtract = 48, NpAdd = 49, NpEnter = 50, NpDecimal = 51,
F1 = 52, F2 = 53, F3 = 54, F4 = 55, F5 = 56, F6 = 57, F7 = 58, F8 = 59, F9 = 60, F10 = 61, F11 = 62, F12 = 63,
Up = 64, Down = 65, Left = 66, Right = 67,
Space = 68, Enter = 69, Escape = 70, Backspace = 71, Tab = 72, CapsLock = 73,
LControl = 74, RControl = 75, LShift = 76, RShift = 77, LAlt = 78, RAlt = 79, LSuper = 80, RSuper = 81,
Grave = 82, Minus = 83, Equals = 84, LeftBracket = 85, RightBracket = 86, Backslash = 87, Semicolon = 88, Apostrophe = 89, Comma = 90, Period = 91, Slash = 92,
Insert = 93, Delete = 94, Home = 95, End = 96, PageUp = 97, PageDown = 98, PrintScreen = 99, ScrollLock = 100, Pause = 101, Menu = 102, NumLock = 103,
Mute = 104, VolumeUp = 105, VolumeDown = 106, MediaPlay = 107, MediaStop = 108, MediaNext = 109, MediaPrevious = 110
);
/// Information about the state of a mouse button /// Information about the state of a mouse button
pub(crate) struct ActiveMouseButton { #[derive(Default, Clone, Copy, Debug)]
pub(crate) struct MouseButtonState {
/// Whether the input is currently active (i.e. the button is currently held down) /// Whether the input is currently active (i.e. the button is currently held down)
pub active: bool, pub state: ButtonState,
/// The button that initiated the input
pub button: MouseButton,
/// Position at which the input was initiated (last time it was pressed **down**) /// Position at which the input was initiated (last time it was pressed **down**)
pub start_position: Option<Vec2>, pub start_position: Option<Vec2>,
} }
#[derive(Default)]
pub(crate) struct MousePointer { pub(crate) struct MousePointer {
pub current_position: Vec2, pub current_position: Vec2,
pub buttons: HashMap<ButtonState, ActiveMouseButton, BuildNoHashHasher<u16>>, pub buttons: HashMap<MouseButton, MouseButtonState, BuildNoHashHasher<u16>>,
} }
pub(crate) struct TouchFinger { pub(crate) struct TouchFinger {
@ -120,7 +154,7 @@ impl Pointer {
} }
} }
impl ActiveMouseButton { impl MouseButtonState {
/// Check if the pointer (mouse or touch) was just pressed\ /// Check if the pointer (mouse or touch) was just pressed\
/// (i.e. it was not pressed in the previous frame, but is pressed now) /// (i.e. it was not pressed in the previous frame, but is pressed now)
/// ///
@ -139,22 +173,22 @@ impl ActiveMouseButton {
} }
pub struct PointerQuery<'a> { pub struct PointerQuery<'a> {
pointers: &'a [Pointer], pointers: &'a HashMap<u32, Pointer, BuildNoHashHasher<u32>>,
/// Set of pointer IDs to filter **out** /// Set of pointer IDs to filter **out**
filter_out: SetUsize, filter_out: SetU32,
} }
impl<'a> PointerQuery<'a> { impl<'a> PointerQuery<'a> {
fn new(pointers: &'a [Pointer]) -> Self { fn new(pointers: &'a HashMap<u32, Pointer, BuildNoHashHasher<u32>>) -> Self {
Self { Self {
pointers, pointers,
filter_out: SetUsize::new(), filter_out: SetU32::new(),
} }
} }
/// Filter pointers that are *currently* located within the specified rectangle /// Filter pointers that are *currently* located within the specified rectangle
pub fn within_rect(&mut self, rect: Rect) -> &mut Self { pub fn within_rect(&mut self, rect: Rect) -> &mut Self {
for (idx, pointer) in self.pointers.iter().enumerate() { for (&idx, pointer) in self.pointers {
if !rect.contains_point(pointer.current_position()) { if !rect.contains_point(pointer.current_position()) {
self.filter_out.insert(idx); self.filter_out.insert(idx);
} }
@ -168,18 +202,47 @@ impl<'a> PointerQuery<'a> {
} }
} }
const MOUSE_POINTER_ID: u32 = u32::MAX;
pub(crate) struct UiInputState { pub(crate) struct UiInputState {
pointers: Vec<Pointer>, pointers: HashMap<u32, Pointer, BuildNoHashHasher<u32>>,
keyboard_state: Set64<KeyboardKey>,
} }
impl UiInputState { impl UiInputState {
pub fn new() -> Self { pub fn new() -> Self {
Self { Self {
pointers: Vec::new(), pointers: HashMap::default(),
keyboard_state: Set64::new(),
} }
} }
pub fn query_pointer(&self) -> PointerQuery { pub fn query_pointer(&self) -> PointerQuery {
PointerQuery::new(&self.pointers) PointerQuery::new(&self.pointers)
} }
/// Drain the event queue and update the internal input state
pub fn update_state(&mut self, event_queue: &mut EventQueue) {
for event in event_queue.drain() {
match event {
UiEvent::MouseMove(pos) => {
let Pointer::MousePointer(mouse) = self.pointers.entry(MOUSE_POINTER_ID)
.or_insert(Pointer::MousePointer(MousePointer::default())) else { unreachable!() };
mouse.current_position = pos;
},
UiEvent::MouseButton { button, state } => {
let Pointer::MousePointer(mouse) = self.pointers.entry(MOUSE_POINTER_ID)
.or_insert(Pointer::MousePointer(MousePointer::default())) else { unreachable!() };
let button_state = mouse.buttons.entry(button)
.or_insert(MouseButtonState::default());
button_state.state = state;
button_state.start_position = state.is_pressed().then_some(mouse.current_position);
},
UiEvent::KeyboardButton { key, state } => {
todo!()
},
_ => (), //TODO: Handle other events
}
}
}
} }

View file

@ -1,15 +1,9 @@
use std::collections::VecDeque;
use glam::Vec2; use glam::Vec2;
use crate::{ use crate::{
draw::{ draw::{
atlas::{TextureAtlasManager, TextureAtlasMeta}, atlas::{TextureAtlasManager, TextureAtlasMeta},
UiDrawCall, UiDrawCommandList, UiDrawCall, UiDrawCommandList,
}, }, element::{MeasureContext, ProcessContext, UiElement}, event::{EventQueue, UiEvent}, input::UiInputState, layout::{LayoutInfo, UiDirection}, state::StateRepo, text::{FontHandle, TextRenderer}
element::{MeasureContext, ProcessContext, UiElement},
event::UiEvent,
layout::{LayoutInfo, UiDirection},
state::StateRepo,
text::{FontHandle, TextRenderer}
}; };
/// The main instance of the UI system. /// The main instance of the UI system.
@ -26,7 +20,8 @@ pub struct UiInstance {
draw_call_modified: bool, draw_call_modified: bool,
text_renderer: TextRenderer, text_renderer: TextRenderer,
atlas: TextureAtlasManager, atlas: TextureAtlasManager,
events: VecDeque<UiEvent>, events: EventQueue,
input: UiInputState,
//True if in the middle of a laying out a frame //True if in the middle of a laying out a frame
state: bool, state: bool,
} }
@ -53,7 +48,8 @@ impl UiInstance {
atlas.add_grayscale(1, &[255]); atlas.add_grayscale(1, &[255]);
atlas atlas
}, },
events: VecDeque::new(), events: EventQueue::new(),
input: UiInputState::new(),
state: false, state: false,
} }
} }
@ -98,11 +94,19 @@ impl UiInstance {
/// If called twice in a row (for example, if you forget to call [`UiInstance::end`])\ /// If called twice in a row (for example, if you forget to call [`UiInstance::end`])\
/// This is an indication of a bug in your code and should be fixed. /// This is an indication of a bug in your code and should be fixed.
pub fn begin(&mut self) { pub fn begin(&mut self) {
//check and update current state
assert!(!self.state, "must call UiInstance::end before calling UiInstance::begin again"); assert!(!self.state, "must call UiInstance::end before calling UiInstance::begin again");
self.state = true; self.state = true;
//first, drain and process the event queue
self.input.update_state(&mut self.events);
//then, reset the draw commands
std::mem::swap(&mut self.prev_draw_commands, &mut self.draw_commands); std::mem::swap(&mut self.prev_draw_commands, &mut self.draw_commands);
self.draw_call_modified = false;
self.draw_commands.commands.clear(); self.draw_commands.commands.clear();
self.draw_call_modified = false;
//reset atlas modification flag
self.atlas.reset_modified(); self.atlas.reset_modified();
} }
@ -110,14 +114,19 @@ impl UiInstance {
/// You must call this function at the end of the frame, before rendering the UI /// You must call this function at the end of the frame, before rendering the UI
/// ///
/// # Panics /// # Panics
/// If called without calling [`UiInstance::begin`] first.\ /// If called without calling [`UiInstance::begin`] first. (or if called twice)\
/// This is an indication of a bug in your code and should be fixed. /// This is an indication of a bug in your code and should be fixed.
pub fn end(&mut self) { pub fn end(&mut self) {
//check and update current state
assert!(self.state, "must call UiInstance::begin before calling UiInstance::end"); assert!(self.state, "must call UiInstance::begin before calling UiInstance::end");
self.state = false; self.state = false;
//check if the draw commands have been modified
if self.draw_commands.commands == self.prev_draw_commands.commands { if self.draw_commands.commands == self.prev_draw_commands.commands {
return return
} }
//if they have, rebuild the draw call and set the modified flag
self.draw_call = UiDrawCall::build(&self.draw_commands, &mut self.atlas, &mut self.text_renderer); self.draw_call = UiDrawCall::build(&self.draw_commands, &mut self.atlas, &mut self.text_renderer);
self.draw_call_modified = true; self.draw_call_modified = true;
} }
@ -176,7 +185,7 @@ impl UiInstance {
if self.state { if self.state {
log::warn!("UiInstance::push_event called while in the middle of a frame, this is probably a mistake"); log::warn!("UiInstance::push_event called while in the middle of a frame, this is probably a mistake");
} }
self.events.push_back(event); self.events.push(event);
} }
} }

View file

@ -6,7 +6,7 @@
#![doc = document_features::document_features!()] #![doc = document_features::document_features!()]
#![allow(unused_parens)] #![allow(unused_parens)]
#![forbid(unsafe_code)] //#![forbid(unsafe_code)]
#![forbid(unsafe_op_in_unsafe_fn)] #![forbid(unsafe_op_in_unsafe_fn)]
mod instance; mod instance;