ferravex_render/input/
touch_layout.rs

1//! Project authored HUD shapes once for both drawing and existing touch routing.
2//!
3//! Geometry is in **host logical screen pixels**, never framebuffer pixels. A
4//! viewport adds its safe origin once; a canvas adds its world offset once. DPR
5//! belongs to the host. Rectangles/circles and stick travel radii scale together;
6//! output channels, floating-stick policy and authored slot order never change.
7//! There is no implicit cropping, enlargement, overlap avoidance or font scaling.
8//! Draw the returned `Control::region` with a screen camera (or a zero-inset,
9//! responsive UI viewport), rather than projecting it a second time.
10//!
11//! Install [`TouchLayout::controls`] as the **authored** PlayerInput layout, then
12//! draw [`TouchLayout::resolve`] using the player's loaded settings. Installing
13//! an already resolved layout would apply customization twice. This preserves
14//! the existing editor, save indexes, hit priority and resize cancellation.
15//!
16//! Hidden suffixes are supported, including an entirely hidden layout. Hidden
17//! gaps return an error: PlayerInput indexes saved edits by slice position and
18//! has no per-slot enable mask. Never compact a hidden middle slot or park its
19//! geometry offscreen (saved edits could move that geometry back onscreen).
20//!
21//! ```
22//! use ferravex_render::{input::{PlayerInput, touch::{Output, TouchLayoutSettings},
23//!     touch_layout::{TouchLayout, TouchSlot, MinimumTouchSize}}, ui::{UiRect, Viewport}};
24//! let viewport = Viewport::responsive([390., 844.], [10., 24., 12., 16.]).unwrap();
25//! let slots = [TouchSlot::rect(0, UiRect { min: [8., 700.], size: [56.; 2] },
26//!     Output::Button(3)), TouchSlot::hidden(1)];
27//! let authored = TouchLayout::from_viewport(viewport, &slots, MinimumTouchSize::Require(44.))?;
28//! let mut input = PlayerInput::transient("touch-geometry-example");
29//! input.set_touch_layout(authored.controls())?; // Loads any saved settings first.
30//! let drawing = authored.resolve(input.touch_settings(), [390., 844.])?;
31//! assert_eq!(drawing.controls().len(), 1);
32//! assert_eq!(input.touch_settings(), TouchLayoutSettings::default());
33//! // Paint drawing.controls()[0].region in absolute logical screen coordinates.
34//! # Ok::<(), Box<dyn std::error::Error>>(())
35//! ```
36
37use super::touch::{Control, MAX_TOUCH_CONTROLS, Output, Region, TouchLayoutSettings};
38use crate::{
39    Rect, Vec2,
40    canvas::Canvas2D,
41    ui::{UiRect, Viewport},
42};
43
44/// Explicit saved-layout identity. Visible slots must be a prefix in slot order.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct TouchSlot {
47    pub slot: usize,
48    /// `None` omits this slot from drawing and input; only a suffix may be hidden.
49    pub control: Option<Control>,
50}
51impl TouchSlot {
52    /// Adapt a UI rectangle in the supplied viewport's local units.
53    /// Geometry is checked by the layout constructor, including zero extents.
54    pub fn rect(slot: usize, rect: UiRect, output: Output) -> Self {
55        Self {
56            slot,
57            control: Some(Control {
58                region: Region::Rect(Rect::new(
59                    rect.min[0],
60                    rect.min[1],
61                    rect.size[0],
62                    rect.size[1],
63                )),
64                output,
65            }),
66        }
67    }
68
69    /// Hide a trailing authored slot without changing earlier saved indexes.
70    pub fn hidden(slot: usize) -> Self {
71        Self {
72            slot,
73            control: None,
74        }
75    }
76}
77
78/// Minimum **screen logical** extent after projection, never a silent resize.
79#[derive(Clone, Copy, Debug, Default, PartialEq)]
80pub enum MinimumTouchSize {
81    /// Preserve existing authored defaults, including small controls.
82    #[default]
83    Preserve,
84    /// Reject rectangles with either side, or circles with diameter, below this
85    /// positive finite size. Look regions are also checked. Consumers can reflow
86    /// or hide the whole layout on error; this adapter does not choose a policy.
87    Require(f32),
88}
89
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub enum TouchGeometryError {
92    Capacity,
93    /// Slot IDs must equal their slice indexes, including hidden suffix slots.
94    SlotOrder,
95    HiddenGap,
96    InvalidGeometry,
97    BelowMinimum,
98}
99impl std::fmt::Display for TouchGeometryError {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.write_str(match self {
102            Self::Capacity => "touch geometry exceeds 16 slots",
103            Self::SlotOrder => "touch geometry must retain authored slot order",
104            Self::HiddenGap => "PlayerInput cannot hide a slot before a visible slot",
105            Self::InvalidGeometry => "invalid touch geometry, output, transform or settings",
106            Self::BelowMinimum => "touch geometry is below the requested logical minimum",
107        })
108    }
109}
110impl std::error::Error for TouchGeometryError {}
111
112/// Fixed-capacity projected controls; construction/resolution allocate nothing.
113/// Rebuild from authored slots on resize; do not feed resolved geometry back in.
114/// Empty layouts release existing captures when installed through PlayerInput.
115#[derive(Clone, Copy, Debug, PartialEq)]
116pub struct TouchLayout {
117    controls: [Control; MAX_TOUCH_CONTROLS],
118    len: usize,
119    minimum: MinimumTouchSize,
120}
121impl TouchLayout {
122    /// Project viewport-local shapes, including [`TouchSlot::rect`] UI rectangles.
123    /// Bounds are not a clip: shapes extending outside the viewport stay intact.
124    /// A viewport with either displayed extent below one logical pixel suspends
125    /// the entire layout, after validating slot order and authored geometry.
126    ///
127    /// ```
128    /// use ferravex_render::{input::{touch::Output, touch_layout::*}, ui::{UiRect, Viewport}};
129    /// let v = Viewport::fit([800., 600.], [400., 200.], [0.; 4]).unwrap();
130    /// let slots = [TouchSlot::rect(0, UiRect { min: [10., 20.], size: [30., 40.] }, Output::Button(7))];
131    /// let layout = TouchLayout::from_viewport(v, &slots, MinimumTouchSize::Require(44.))?;
132    /// assert_eq!(layout.controls()[0].region, ferravex_render::input::touch::Region::Rect(
133    ///     ferravex_render::Rect::new(20., 140., 60., 80.)));
134    /// # Ok::<(), Box<dyn std::error::Error>>(())
135    /// ```
136    pub fn from_viewport(
137        viewport: Viewport,
138        slots: &[TouchSlot],
139        minimum: MinimumTouchSize,
140    ) -> Result<Self, TouchGeometryError> {
141        let pixels = viewport.pixels();
142        Self::project(
143            slots,
144            minimum,
145            Vec2::from(pixels.min),
146            viewport.scale(),
147            pixels.valid() && viewport.bounds().valid(),
148            pixels.size.into_iter().any(|n| n < 1.),
149        )
150    }
151
152    /// Project canvas-world shapes using the same affine arithmetic as drawing.
153    /// No crop is applied, preserving existing broad/background touch regions.
154    /// Manually authored canvas fields are checked; zero/subpixel screen or
155    /// displayed-world extents suspend input instead of leaving stale targets.
156    ///
157    /// ```
158    /// use ferravex_render::{vec2, canvas::Canvas2D,
159    ///     input::{touch::{Control, Output, Region}, touch_layout::*}};
160    /// let canvas = Canvas2D::try_fit(vec2(400., 200.), vec2(800., 600.))?.unwrap();
161    /// let slots = [TouchSlot { slot: 0, control: Some(Control {
162    ///     region: Region::Circle { center: vec2(20., 30.), radius: 22. },
163    ///     output: Output::Stick { x: 0, y: 1, radius: 16., floating: false },
164    /// }) }];
165    /// let layout = TouchLayout::from_canvas(canvas, &slots, MinimumTouchSize::Preserve)?;
166    /// assert_eq!(layout.controls()[0].region,
167    ///     Region::Circle { center: canvas.project(vec2(20., 30.)), radius: 44. });
168    /// assert_eq!(layout.controls()[0].output,
169    ///     Output::Stick { x: 0, y: 1, radius: 32., floating: false });
170    /// # Ok::<(), Box<dyn std::error::Error>>(())
171    /// ```
172    pub fn from_canvas(
173        canvas: Canvas2D,
174        slots: &[TouchSlot],
175        minimum: MinimumTouchSize,
176    ) -> Result<Self, TouchGeometryError> {
177        Self::project(
178            slots,
179            minimum,
180            canvas.offset,
181            canvas.scale,
182            canvas.size.is_finite()
183                && canvas.size.min_element() > 0.
184                && canvas.screen.is_finite()
185                && canvas.screen.min_element() >= 0.
186                && (canvas.size * canvas.scale).is_finite()
187                && canvas.project(canvas.size).is_finite(),
188            canvas.screen.min_element() < 1. || (canvas.size * canvas.scale).min_element() < 1.,
189        )
190    }
191
192    /// Visible prefix, in unchanged authored slot order. Used for both drawing
193    /// and installation; boundaries retain existing inclusive touch hit tests.
194    /// Overlapping/shared edges resolve to the earliest slot, as in TouchSurface.
195    pub fn controls(&self) -> &[Control] {
196        &self.controls[..self.len]
197    }
198
199    /// Resolve the exact legacy PlayerInput customization for drawing. Supply
200    /// current full-screen logical dimensions, not the safe-area size. Like
201    /// PlayerInput, each dimension is floored at 64 before `settings.apply`.
202    /// Safe offsets are already projected; `apply_in_safe_area` here would apply
203    /// them twice. This method never mutates settings, channels or saved slots.
204    /// The minimum is checked again after edits; errors preserve the authored
205    /// value. Never install this result into PlayerInput a second time.
206    pub fn resolve(
207        &self,
208        settings: TouchLayoutSettings,
209        screen: [f32; 2],
210    ) -> Result<Self, TouchGeometryError> {
211        if !settings.valid() || screen.into_iter().any(|n| !n.is_finite() || n < 0.) {
212            return Err(TouchGeometryError::InvalidGeometry);
213        }
214        let mut resolved = *self;
215        for (slot, control) in resolved.controls[..self.len].iter_mut().enumerate() {
216            *control = settings
217                .apply(*control, slot, Vec2::from(screen).max(Vec2::splat(64.)))
218                .map_err(|_| TouchGeometryError::InvalidGeometry)?;
219            check_control(*control, self.minimum)?;
220        }
221        Ok(resolved)
222    }
223
224    fn project(
225        slots: &[TouchSlot],
226        minimum: MinimumTouchSize,
227        offset: Vec2,
228        scale: f32,
229        valid: bool,
230        suspended: bool,
231    ) -> Result<Self, TouchGeometryError> {
232        if slots.len() > MAX_TOUCH_CONTROLS {
233            return Err(TouchGeometryError::Capacity);
234        }
235        if !valid
236            || !offset.is_finite()
237            || !scale.is_finite()
238            || scale <= 0.
239            || matches!(minimum, MinimumTouchSize::Require(n) if !n.is_finite() || n <= 0.)
240        {
241            return Err(TouchGeometryError::InvalidGeometry);
242        }
243        let mut result = Self {
244            controls: [Control {
245                region: Region::Rect(Rect::new(0., 0., 1., 1.)),
246                output: Output::Button(0),
247            }; MAX_TOUCH_CONTROLS],
248            len: 0,
249            minimum,
250        };
251        let mut hidden = false;
252        for (i, slot) in slots.iter().enumerate() {
253            if slot.slot != i {
254                return Err(TouchGeometryError::SlotOrder);
255            }
256            let Some(mut control) = slot.control else {
257                hidden = true;
258                continue;
259            };
260            if hidden {
261                return Err(TouchGeometryError::HiddenGap);
262            }
263            check_control(control, MinimumTouchSize::Preserve)?;
264            if suspended {
265                continue;
266            }
267            control.region = match control.region {
268                Region::Rect(r) => {
269                    let p = offset + Vec2::new(r.x, r.y) * scale;
270                    Region::Rect(Rect::new(p.x, p.y, r.w * scale, r.h * scale))
271                }
272                Region::Circle { center, radius } => Region::Circle {
273                    center: offset + center * scale,
274                    radius: radius * scale,
275                },
276            };
277            if let Output::Stick { radius, .. } = &mut control.output {
278                *radius *= scale;
279            }
280            check_control(control, minimum)?;
281            result.controls[result.len] = control;
282            result.len += 1;
283        }
284        Ok(result)
285    }
286}
287
288fn check_control(control: Control, minimum: MinimumTouchSize) -> Result<(), TouchGeometryError> {
289    // Reuse the existing touch contract rather than duplicate channel/shape limits.
290    TouchLayoutSettings::default()
291        .apply(control, 0, Vec2::splat(64.))
292        .map_err(|_| TouchGeometryError::InvalidGeometry)?;
293    if let MinimumTouchSize::Require(n) = minimum {
294        let size = match control.region {
295            Region::Rect(r) => r.w.min(r.h),
296            Region::Circle { radius, .. } => 2. * radius,
297        };
298        if size < n {
299            return Err(TouchGeometryError::BelowMinimum);
300        }
301    }
302    Ok(())
303}