sim_logic/application/input/
motion.rs1use std::{error::Error, fmt};
4
5#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
11pub struct RelativePointerMotion {
12 bits: [u64; 2],
13}
14
15impl RelativePointerMotion {
16 pub const ZERO: Self = Self { bits: [0; 2] };
18 pub const MAX_DISPLACEMENT: f64 = 1_000_000.0;
20
21 pub fn new(x: f64, y: f64) -> Result<Self, RelativePointerMotionError> {
23 if !x.is_finite() || !y.is_finite() {
24 return Err(RelativePointerMotionError::NonFinite);
25 }
26 if x.abs() > Self::MAX_DISPLACEMENT || y.abs() > Self::MAX_DISPLACEMENT {
27 return Err(RelativePointerMotionError::OutOfRange);
28 }
29 Ok(Self {
30 bits: [canonical_bits(x), canonical_bits(y)],
31 })
32 }
33 pub const fn x(self) -> f64 {
35 f64::from_bits(self.bits[0])
36 }
37 pub const fn y(self) -> f64 {
39 f64::from_bits(self.bits[1])
40 }
41 pub fn checked_add(self, other: Self) -> Result<Self, RelativePointerMotionError> {
43 Self::new(self.x() + other.x(), self.y() + other.y())
44 }
45}
46
47fn canonical_bits(value: f64) -> u64 {
48 if value == 0.0 { 0 } else { value.to_bits() }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
53pub enum RelativePointerMotionError {
54 NonFinite,
56 OutOfRange,
58}
59
60impl fmt::Display for RelativePointerMotionError {
61 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
62 formatter.write_str(match self {
63 Self::NonFinite => "relative pointer motion must be finite",
64 Self::OutOfRange => "relative pointer motion exceeds the displacement limit",
65 })
66 }
67}
68impl Error for RelativePointerMotionError {}
69
70pub(super) fn frame_motion(
71 events: &[super::InputEvent],
72) -> Result<(RelativePointerMotion, bool), RelativePointerMotionError> {
73 let mut motion = RelativePointerMotion::ZERO;
74 let mut focus_lost = false;
75 for event in events {
76 match event {
77 super::InputEvent::RelativePointerMotion { motion: incoming } if !focus_lost => {
78 motion = motion.checked_add(*incoming)?;
79 }
80 super::InputEvent::FocusLost => {
81 motion = RelativePointerMotion::ZERO;
82 focus_lost = true;
83 }
84 _ => {}
85 }
86 }
87 Ok((motion, focus_lost))
88}