ferravex_play/input/
touch.rs

1//! Bounded logical-pixel touch capture. Layout order sets hit-test priority;
2//! a captured finger keeps its role until end/cancel, even outside its region.
3//!
4//! Immediate controls are unchanged. Opt in with [`TouchSurface::set_gesture_profile`]
5//! and feed caller-supplied seconds to [`TouchSurface::handle_timed`] to observe
6//! gestures separately from tick-consumed actions. No clock, queue, new input
7//! channel or platform ABI is involved.
8use super::{ActionMap, InputCode, InputError};
9use ferravex_math::{Rect, Vec2};
10pub const MAX_TOUCHES: usize = 16;
11pub const MAX_TOUCH_CONTROLS: usize = 16;
12#[derive(Clone, Copy, Debug, PartialEq)]
13pub enum Region {
14    Circle { center: Vec2, radius: f32 },
15    Rect(Rect),
16}
17impl Region {
18    fn valid(self) -> bool {
19        match self {
20            Self::Circle { center, radius } => {
21                bounded(center) && radius.is_finite() && (0.001..=1e5).contains(&radius)
22            }
23            Self::Rect(r) => {
24                bounded(Vec2::new(r.x, r.y))
25                    && r.w.is_finite()
26                    && r.h.is_finite()
27                    && r.w > 0.
28                    && r.h > 0.
29                    && r.w <= 1e6
30                    && r.h <= 1e6
31            }
32        }
33    }
34    fn contains(self, p: Vec2) -> bool {
35        match self {
36            Self::Circle { center, radius } => center.distance_squared(p) <= radius * radius,
37            Self::Rect(r) => r.contains(p),
38        }
39    }
40    fn center(self) -> Vec2 {
41        match self {
42            Self::Circle { center, .. } => center,
43            Self::Rect(r) => r.center(),
44        }
45    }
46}
47#[derive(Clone, Copy, Debug, PartialEq)]
48pub enum Output {
49    Button(u8),
50    Stick {
51        x: u8,
52        y: u8,
53        radius: f32,
54        floating: bool,
55    },
56    Look {
57        x: u8,
58        y: u8,
59    },
60}
61#[derive(Clone, Copy, Debug, PartialEq)]
62pub struct Control {
63    pub region: Region,
64    pub output: Output,
65}
66impl Control {
67    fn valid(self) -> bool {
68        self.region.valid()
69            && match self.output {
70                Output::Button(n) => n < 64,
71                Output::Stick { x, y, radius, .. } => {
72                    x < 64
73                        && y < 64
74                        && x != y
75                        && radius.is_finite()
76                        && (0.001..=1e5).contains(&radius)
77                }
78                Output::Look { x, y } => x < 16 && y < 16 && x != y,
79            }
80    }
81}
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub enum Phase {
84    Start,
85    Move,
86    End,
87    Cancel,
88}
89#[derive(Clone, Copy, Debug, PartialEq)]
90pub struct Event {
91    pub id: u64,
92    pub position: Vec2,
93    pub phase: Phase,
94}
95/// Logical-pixel distances and supplied-time seconds for opt-in recognition.
96///
97/// Distances must be finite, with `0 <= tap_max_distance < drag_min_distance
98/// <= swipe_min_distance <= 1e6`. Times must be finite in `0..=3600` seconds.
99/// Every threshold is inclusive. Tap uses maximum excursion from the starting
100/// point and maximum duration; drag latches once maximum excursion and minimum
101/// duration both qualify. Swipe uses **final net displacement** and maximum
102/// duration, and takes precedence over drag on End. There is no velocity test.
103/// A gap between tap and drag distances can deliberately produce no gesture.
104///
105/// Default thresholds are provided only for this new opt-in path: 10 px / 0.25 s
106/// tap, 12 px / 0 s drag, and 48 px / 0.5 s swipe. Legacy handling never reads them.
107///
108/// ```
109/// use ferravex_play::input::touch::{GestureError, GestureProfile};
110/// let profile = GestureProfile { tap_max_seconds: 0.4, ..GestureProfile::default() };
111/// profile.validate()?;
112/// assert_eq!(GestureProfile { drag_min_distance: 0.0, ..profile }.validate(),
113///     Err(GestureError::InvalidProfile));
114/// # Ok::<(), GestureError>(())
115/// ```
116#[derive(Clone, Copy, Debug, PartialEq)]
117pub struct GestureProfile {
118    pub tap_max_distance: f32,
119    pub tap_max_seconds: f64,
120    pub drag_min_distance: f32,
121    pub drag_min_seconds: f64,
122    pub swipe_min_distance: f32,
123    pub swipe_max_seconds: f64,
124}
125impl Default for GestureProfile {
126    fn default() -> Self {
127        Self {
128            tap_max_distance: 10.,
129            tap_max_seconds: 0.25,
130            drag_min_distance: 12.,
131            drag_min_seconds: 0.,
132            swipe_min_distance: 48.,
133            swipe_max_seconds: 0.5,
134        }
135    }
136}
137impl GestureProfile {
138    /// Validate all fields without changing a surface. See the type's example.
139    pub fn validate(self) -> Result<(), GestureError> {
140        let distances = [
141            self.tap_max_distance,
142            self.drag_min_distance,
143            self.swipe_min_distance,
144        ];
145        let times = [
146            self.tap_max_seconds,
147            self.drag_min_seconds,
148            self.swipe_max_seconds,
149        ];
150        if distances
151            .iter()
152            .any(|d| !d.is_finite() || !(0.0..=1e6).contains(d))
153            || times
154                .iter()
155                .any(|t| !t.is_finite() || !(0.0..=3600.0).contains(t))
156            || self.tap_max_distance >= self.drag_min_distance
157            || self.drag_min_distance > self.swipe_min_distance
158        {
159            return Err(GestureError::InvalidProfile);
160        }
161        Ok(())
162    }
163}
164
165/// Separate recognition errors keep the existing exhaustive InputError intact.
166#[derive(Clone, Copy, Debug, PartialEq, Eq)]
167pub enum GestureError {
168    InvalidProfile,
169    Disabled,
170    /// Supplied seconds must be finite and nonnegative.
171    InvalidTime,
172    /// Earlier than the last successfully accepted timed event on this surface.
173    TimeWentBackwards,
174    Input(InputError),
175}
176impl std::fmt::Display for GestureError {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        write!(f, "touch gesture: {self:?}")
179    }
180}
181impl std::error::Error for GestureError {
182    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
183        match self {
184            Self::Input(error) => Some(error),
185            _ => None,
186        }
187    }
188}
189
190/// Classification carried only by the explicit observation return value.
191#[derive(Clone, Copy, Debug, PartialEq, Eq)]
192pub enum GestureKind {
193    Tap,
194    Drag,
195    Swipe,
196}
197
198/// One accepted event's observation; never inserted into ActionMap.
199///
200/// Tap and Swipe occur only at End. Drag occurs at each qualifying Move and at
201/// End (including an End that crosses the threshold without an earlier Move).
202/// An End produces at most one observation: Swipe, else latched/qualifying Drag,
203/// else Tap, else none. Start/Cancel never produce an observation. A prior Drag
204/// may finish as Swipe. Consumers must discard drag presentation on Cancel or
205/// explicit clear/layout/profile reset; resets do not synthesize terminal events.
206/// `control` is the captured layout index, not an InputCode or saved stable slot.
207/// See [`TouchSurface::handle_timed`] for an executable example.
208#[derive(Clone, Copy, Debug, PartialEq)]
209pub struct GestureObservation {
210    pub id: u64,
211    pub control: usize,
212    pub kind: GestureKind,
213    pub phase: Phase,
214    /// Actual touch start, including for nonfloating sticks.
215    pub origin: Vec2,
216    pub position: Vec2,
217    pub elapsed_seconds: f64,
218}
219
220#[derive(Clone, Copy, Debug)]
221struct GestureCapture {
222    origin: Vec2,
223    started_seconds: f64,
224    max_distance_squared: f64,
225    dragging: bool,
226}
227impl GestureCapture {
228    fn observe(
229        &mut self,
230        capture: Capture,
231        event: Event,
232        seconds: f64,
233        profile: GestureProfile,
234    ) -> Option<GestureObservation> {
235        // Widen before subtraction/squaring: all validated f32 thresholds,
236        // including subnormal distances near zero, retain their ordering.
237        let dx = f64::from(event.position.x) - f64::from(self.origin.x);
238        let dy = f64::from(event.position.y) - f64::from(self.origin.y);
239        let distance_squared = dx * dx + dy * dy;
240        self.max_distance_squared = self.max_distance_squared.max(distance_squared);
241        let elapsed = seconds - self.started_seconds;
242        self.dragging |= self.max_distance_squared >= f64::from(profile.drag_min_distance).powi(2)
243            && elapsed >= profile.drag_min_seconds;
244        let kind = if event.phase == Phase::End
245            && distance_squared >= f64::from(profile.swipe_min_distance).powi(2)
246            && elapsed <= profile.swipe_max_seconds
247        {
248            GestureKind::Swipe
249        } else if self.dragging {
250            GestureKind::Drag
251        } else if event.phase == Phase::End
252            && self.max_distance_squared <= f64::from(profile.tap_max_distance).powi(2)
253            && elapsed <= profile.tap_max_seconds
254        {
255            GestureKind::Tap
256        } else {
257            return None;
258        };
259        Some(GestureObservation {
260            id: event.id,
261            control: capture.control,
262            kind,
263            phase: event.phase,
264            origin: self.origin,
265            position: event.position,
266            elapsed_seconds: elapsed,
267        })
268    }
269}
270
271#[derive(Clone, Copy, Debug)]
272struct Capture {
273    id: u64,
274    control: usize,
275    origin: Vec2,
276    position: Vec2,
277    gesture: Option<GestureCapture>,
278}
279pub struct TouchSurface {
280    controls: Vec<Control>,
281    captures: [Option<Capture>; MAX_TOUCHES],
282    gesture_profile: Option<GestureProfile>,
283    last_gesture_seconds: Option<f64>,
284}
285impl Default for TouchSurface {
286    fn default() -> Self {
287        Self {
288            controls: Vec::with_capacity(MAX_TOUCH_CONTROLS),
289            captures: [None; MAX_TOUCHES],
290            gesture_profile: None,
291            last_gesture_seconds: None,
292        }
293    }
294}
295fn bounded(p: Vec2) -> bool {
296    p.is_finite() && p.abs().max_element() <= 1e6
297}
298impl TouchSurface {
299    /// Identical layouts preserve captures. A changed/resized layout releases
300    /// all old output codes before installing the new one, without reallocating.
301    pub fn controls(&self) -> &[Control] {
302        &self.controls
303    }
304    pub fn set_layout(
305        &mut self,
306        controls: &[Control],
307        map: &mut ActionMap,
308    ) -> Result<(), InputError> {
309        if controls.len() > MAX_TOUCH_CONTROLS {
310            return Err(InputError::TouchCapacity);
311        }
312        if controls.iter().any(|c| !c.valid()) {
313            return Err(InputError::InvalidTouch);
314        }
315        if self.controls == controls {
316            return Ok(());
317        }
318        self.clear(map);
319        self.controls.clear();
320        self.controls.extend_from_slice(controls);
321        Ok(())
322    }
323    pub fn handle(&mut self, event: Event, map: &mut ActionMap) -> Result<(), InputError> {
324        self.handle_scaled(event, map, Vec2::ONE)
325    }
326    /// Apply a host's per-pixel sensitivity before motion reaches bound actions.
327    pub fn handle_scaled(
328        &mut self,
329        event: Event,
330        map: &mut ActionMap,
331        look_scale: Vec2,
332    ) -> Result<(), InputError> {
333        if !look_scale.is_finite() || look_scale.abs().max_element() > 100. {
334            return Err(InputError::InvalidTouch);
335        }
336        if !bounded(event.position) {
337            return Err(InputError::InvalidTouch);
338        }
339        let old = self
340            .captures
341            .iter()
342            .position(|c| c.is_some_and(|c| c.id == event.id));
343        if matches!(event.phase, Phase::End | Phase::Cancel) {
344            if let Some(i) = old {
345                self.captures[i] = None;
346                self.flush(map);
347            }
348            return Ok(());
349        }
350        if event.phase == Phase::Start {
351            let Some(control) = self
352                .controls
353                .iter()
354                .position(|c| c.region.contains(event.position))
355            else {
356                if let Some(i) = old {
357                    self.captures[i] = None;
358                    self.flush(map);
359                }
360                return Ok(());
361            };
362            let slot = old
363                .or_else(|| self.captures.iter().position(Option::is_none))
364                .ok_or(InputError::TouchCapacity)?;
365            let origin = match self.controls[control].output {
366                Output::Stick {
367                    floating: false, ..
368                } => self.controls[control].region.center(),
369                _ => event.position,
370            };
371            self.captures[slot] = Some(Capture {
372                id: event.id,
373                control,
374                origin,
375                position: event.position,
376                gesture: None,
377            });
378            self.flush(map);
379            return Ok(());
380        }
381        if let Some(i) = old {
382            let capture = self.captures[i].as_mut().unwrap();
383            if let Output::Look { x, y } = self.controls[capture.control].output {
384                let delta = (event.position - capture.position) * look_scale;
385                map.feed_delta(InputCode::TouchDelta(x), delta.x);
386                map.feed_delta(InputCode::TouchDelta(y), delta.y);
387            }
388            capture.position = event.position;
389            capture.gesture = None;
390            self.flush(map);
391        }
392        Ok(())
393    }
394    /// Current opt-in profile; None by default. See [`Self::set_gesture_profile`].
395    pub fn gesture_profile(&self) -> Option<GestureProfile> {
396        self.gesture_profile
397    }
398
399    /// Validate before mutation. A different profile (including enable/disable)
400    /// clears all captures, releases their held outputs and resets the supplied
401    /// time watermark. An identical profile preserves captures/time. Unrelated
402    /// queued input edges and accumulated motion are not consumed or erased.
403    /// Invalid profiles preserve all state, even with active captures.
404    ///
405    /// ```
406    /// use ferravex_play::input::{ActionMap, touch::{TouchSurface, GestureProfile}};
407    /// let mut map = ActionMap::default();
408    /// let mut touch = TouchSurface::default();
409    /// assert_eq!(touch.gesture_profile(), None);
410    /// touch.set_gesture_profile(Some(GestureProfile::default()), &mut map)?;
411    /// assert!(touch.gesture_profile().is_some());
412    /// touch.set_gesture_profile(None, &mut map)?;
413    /// assert_eq!(touch.gesture_profile(), None);
414    /// # Ok::<(), ferravex_play::input::touch::GestureError>(())
415    /// ```
416    pub fn set_gesture_profile(
417        &mut self,
418        profile: Option<GestureProfile>,
419        map: &mut ActionMap,
420    ) -> Result<(), GestureError> {
421        if let Some(profile) = profile {
422            profile.validate()?;
423        }
424        if self.gesture_profile != profile {
425            self.clear(map);
426            self.gesture_profile = profile;
427        }
428        Ok(())
429    }
430
431    /// Handle immediate controls and return an optional gesture using supplied
432    /// seconds, without consuming any action edges. Equivalent to
433    /// [`Self::handle_timed_scaled`] with unit look sensitivity.
434    ///
435    /// ```
436    /// use ferravex_math::{Rect, Vec2};
437    /// use ferravex_play::input::{ActionMap, Binding, InputCode, touch::*};
438    /// let mut map = ActionMap::default();
439    /// let jump = map.try_action(vec![Binding::digital(InputCode::Touch(0))]).unwrap();
440    /// let mut touch = TouchSurface::default();
441    /// touch.set_layout(&[Control { region: Region::Rect(Rect::new(0., 0., 100., 100.)),
442    ///     output: Output::Button(0) }], &mut map)?;
443    /// touch.set_gesture_profile(Some(GestureProfile::default()), &mut map)?;
444    /// let event = |phase| Event { id: 7, position: Vec2::splat(20.), phase };
445    /// assert!(touch.handle_timed(event(Phase::Start), 10.0, &mut map)?.is_none());
446    /// let observed = touch.handle_timed(event(Phase::End), 10.125, &mut map)?.unwrap();
447    /// assert_eq!((observed.kind, observed.elapsed_seconds), (GestureKind::Tap, 0.125));
448    /// // No actual simulation tick yet: both immediate button edges remain.
449    /// assert!(map.peek(jump).pressed && map.peek(jump).released);
450    /// let tick = map.consume_tick(jump); // Only inside an actual executed update.
451    /// assert!(tick.pressed && tick.released);
452    /// assert!(!map.consume_tick(jump).pressed);
453    /// # Ok::<(), Box<dyn std::error::Error>>(())
454    /// ```
455    pub fn handle_timed(
456        &mut self,
457        event: Event,
458        seconds: f64,
459        map: &mut ActionMap,
460    ) -> Result<Option<GestureObservation>, GestureError> {
461        self.handle_timed_scaled(event, seconds, map, Vec2::ONE)
462    }
463
464    /// Supplied-time observation with the same capture ownership, layout priority
465    /// and immediate outputs as [`Self::handle_scaled`]. Look scaling affects
466    /// only existing TouchDelta outputs; recognition uses unscaled logical pixels.
467    /// See [`Self::handle_timed`] for an executable example.
468    ///
469    /// Supply finite nonnegative seconds in one caller-owned monotonic domain
470    /// (prefer seconds since session start). Equal timestamps are allowed. Time
471    /// must not decrease across **any** successfully accepted timed events on this
472    /// surface, including uncaptured IDs. No wall clock is inferred. Caller f64
473    /// precision determines time resolution. Clear, changed layout or changed
474    /// profile forgets this watermark, so focus loss needs no timestamp.
475    ///
476    /// Error precedence: disabled profile, invalid seconds, decreasing seconds,
477    /// then legacy position/scale/capture-capacity validation. Every error leaves
478    /// map, captures, recognition and watermark unchanged. Uncaptured events have
479    /// no observation. There are at most MAX_TOUCHES captures; a repeated Start
480    /// replaces that ID's old capture/gesture (or drops it if outside the layout),
481    /// even at capacity. Cancel always drops recognition without a tap/swipe.
482    /// End uses its own position, even without a Move; legacy control release still
483    /// ignores End motion. Repeated End cannot deliver the observation again.
484    ///
485    /// A capture is observed only if its Start used this timed path. Successfully
486    /// accepted untimed events drop recognition for their affected capture while
487    /// preserving legacy output behavior; later timed events cannot revive it.
488    /// Mixing timed and untimed pointers is allowed. Recognition storage is inline,
489    /// with no queue/backpressure: each call returns at most one observation that
490    /// the caller must handle immediately or retain in its own bounded storage.
491    pub fn handle_timed_scaled(
492        &mut self,
493        event: Event,
494        seconds: f64,
495        map: &mut ActionMap,
496        look_scale: Vec2,
497    ) -> Result<Option<GestureObservation>, GestureError> {
498        let profile = self.gesture_profile.ok_or(GestureError::Disabled)?;
499        if !seconds.is_finite() || seconds < 0. {
500            return Err(GestureError::InvalidTime);
501        }
502        if self.last_gesture_seconds.is_some_and(|last| seconds < last) {
503            return Err(GestureError::TimeWentBackwards);
504        }
505        let old = self
506            .captures
507            .iter()
508            .flatten()
509            .find(|c| c.id == event.id)
510            .copied();
511        self.handle_scaled(event, map, look_scale)
512            .map_err(GestureError::Input)?;
513        self.last_gesture_seconds = Some(seconds);
514        let mut observation = None;
515        let gesture = match event.phase {
516            Phase::Start => Some(GestureCapture {
517                origin: event.position,
518                started_seconds: seconds,
519                max_distance_squared: 0.,
520                dragging: false,
521            }),
522            Phase::Move | Phase::End => old.and_then(|capture| {
523                capture.gesture.map(|mut gesture| {
524                    observation = gesture.observe(capture, event, seconds, profile);
525                    gesture
526                })
527            }),
528            Phase::Cancel => None,
529        };
530        if let Some(capture) = self
531            .captures
532            .iter_mut()
533            .flatten()
534            .find(|c| c.id == event.id)
535        {
536            capture.gesture = gesture;
537        }
538        Ok(observation)
539    }
540
541    fn flush(&self, map: &mut ActionMap) {
542        let mut values = [0_f32; 64];
543        for c in self.captures.iter().flatten() {
544            match self.controls[c.control].output {
545                Output::Button(n) => values[n as usize] = 1.,
546                Output::Stick { x, y, radius, .. } => {
547                    let delta = ((c.position - c.origin) / radius).clamp_length_max(1.);
548                    values[x as usize] = (values[x as usize] + delta.x).clamp(-1., 1.);
549                    values[y as usize] = (values[y as usize] + delta.y).clamp(-1., 1.);
550                }
551                Output::Look { .. } => {}
552            }
553        }
554        for (i, &value) in values.iter().enumerate() {
555            map.feed(InputCode::Touch(i as u8), value);
556        }
557    }
558    /// Release captures and discard recognition/time history, retaining the
559    /// configured profile. Valid for focus loss with no supplied timestamp.
560    /// Does not consume queued action edges or reset unrelated input sources.
561    pub fn clear(&mut self, map: &mut ActionMap) {
562        self.captures.fill(None);
563        self.last_gesture_seconds = None;
564        self.flush(map);
565    }
566    pub fn active(&self) -> usize {
567        self.captures.iter().filter(|c| c.is_some()).count()
568    }
569    pub fn stick(&self, x: u8, y: u8) -> Option<(Vec2, Vec2)> {
570        self.captures
571            .iter()
572            .flatten()
573            .find_map(|c| match self.controls[c.control].output {
574                Output::Stick {
575                    x: cx,
576                    y: cy,
577                    radius,
578                    ..
579                } if (cx, cy) == (x, y) => Some((
580                    c.origin,
581                    ((c.position - c.origin) / radius).clamp_length_max(1.),
582                )),
583                _ => None,
584            })
585    }
586}
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use crate::input::{ActionKind, Binding, ContextId};
591    fn event(id: u64, x: f32, y: f32, phase: Phase) -> Event {
592        Event {
593            id,
594            position: Vec2::new(x, y),
595            phase,
596        }
597    }
598    #[test]
599    fn quick_taps_and_two_fingers_keep_independent_roles() {
600        let mut map = ActionMap::default();
601        let jump = map
602            .named_action(
603                "jump",
604                ActionKind::Button,
605                ContextId::GLOBAL,
606                vec![Binding::digital(InputCode::Touch(0))],
607            )
608            .unwrap();
609        let mut touch = TouchSurface::default();
610        touch
611            .set_layout(
612                &[Control {
613                    region: Region::Rect(Rect::new(0., 0., 100., 100.)),
614                    output: Output::Button(0),
615                }],
616                &mut map,
617            )
618            .unwrap();
619        touch
620            .handle(event(1, 10., 10., Phase::Start), &mut map)
621            .unwrap();
622        touch
623            .handle(event(1, 10., 10., Phase::End), &mut map)
624            .unwrap();
625        let tap = map.consume_tick(jump);
626        assert!(tap.pressed && tap.released);
627        assert_eq!(tap.value, 0.);
628        for id in [1, 2] {
629            touch
630                .handle(event(id, 10., 10., Phase::Start), &mut map)
631                .unwrap();
632        }
633        touch
634            .handle(event(1, 200., 200., Phase::Cancel), &mut map)
635            .unwrap();
636        assert_eq!(map.peek(jump).value, 1.);
637        touch
638            .handle(event(2, 200., 200., Phase::End), &mut map)
639            .unwrap();
640        assert_eq!(map.peek(jump).value, 0.);
641    }
642    #[test]
643    fn floating_stick_look_capture_and_resize_do_not_stick() {
644        let mut map = ActionMap::default();
645        let look = map
646            .named_action(
647                "look",
648                ActionKind::Delta,
649                ContextId::GLOBAL,
650                vec![Binding::digital(InputCode::TouchDelta(0))],
651            )
652            .unwrap();
653        let mut touch = TouchSurface::default();
654        let layout = [
655            Control {
656                region: Region::Rect(Rect::new(0., 0., 100., 100.)),
657                output: Output::Stick {
658                    x: 0,
659                    y: 1,
660                    radius: 20.,
661                    floating: true,
662                },
663            },
664            Control {
665                region: Region::Rect(Rect::new(100., 0., 100., 100.)),
666                output: Output::Look { x: 0, y: 1 },
667            },
668        ];
669        touch.set_layout(&layout, &mut map).unwrap();
670        touch
671            .handle(event(1, 50., 50., Phase::Start), &mut map)
672            .unwrap();
673        touch
674            .handle(event(2, 150., 50., Phase::Start), &mut map)
675            .unwrap();
676        touch
677            .handle(event(1, 150., 50., Phase::Move), &mut map)
678            .unwrap();
679        touch
680            .handle(event(2, 165., 45., Phase::Move), &mut map)
681            .unwrap();
682        assert_eq!(map.physical_value(InputCode::Touch(0)), 1.);
683        assert_eq!(map.consume_tick(look).value, 15.);
684        assert_eq!(touch.stick(0, 1).unwrap().1, Vec2::X);
685        touch.set_layout(&layout, &mut map).unwrap();
686        assert_eq!(touch.active(), 2);
687        touch.set_layout(&[], &mut map).unwrap();
688        assert_eq!(touch.active(), 0);
689        assert_eq!(map.physical_value(InputCode::Touch(0)), 0.);
690    }
691    #[test]
692    fn invalid_layout_or_event_never_loses_existing_capture() {
693        let mut map = ActionMap::default();
694        let mut touch = TouchSurface::default();
695        touch
696            .set_layout(
697                &[Control {
698                    region: Region::Circle {
699                        center: Vec2::ZERO,
700                        radius: 50.,
701                    },
702                    output: Output::Button(0),
703                }],
704                &mut map,
705            )
706            .unwrap();
707        touch
708            .handle(event(1, 0., 0., Phase::Start), &mut map)
709            .unwrap();
710        assert!(
711            touch
712                .handle(event(1, f32::NAN, 0., Phase::End), &mut map)
713                .is_err()
714        );
715        assert_eq!(touch.active(), 1);
716        assert!(
717            touch
718                .set_layout(
719                    &[Control {
720                        region: Region::Circle {
721                            center: Vec2::ZERO,
722                            radius: 0.
723                        },
724                        output: Output::Button(0)
725                    }],
726                    &mut map
727                )
728                .is_err()
729        );
730        assert_eq!(touch.active(), 1);
731        touch.clear(&mut map);
732        assert_eq!(map.physical_value(InputCode::Touch(0)), 0.);
733    }
734}
735
736mod layout;
737pub use layout::{TouchEdit, TouchLayoutDiagnostics, TouchLayoutSettings};