Skip to main content

rayengine_core/ui/
interaction.rs

1//! Interaction only: game-owned region IDs/layout and no renderer dependency.
2
3use crate::{
4    collision::Aabb2,
5    input::{Action, Input},
6};
7use glam::Vec2;
8
9/// Stable game-owned identity. IDs must be unique within an update's regions.
10#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
11pub struct UiId(pub u64);
12
13/// Hit region in reference UI units. Last listed region wins overlapping hits,
14/// including disabled regions, which block clicks reaching lower regions.
15#[derive(Clone, Copy, Debug)]
16pub struct UiRegion {
17    /// Stable identity, independent of region order.
18    pub id: UiId,
19    /// Resolved bounds using the current viewport's logical size.
20    pub bounds: Aabb2,
21    /// Disabled regions cannot activate, focus, or begin dragging.
22    pub enabled: bool,
23    /// Eligible for pointer and keyboard focus.
24    pub focusable: bool,
25    /// Starts a drag immediately on pointer press; does not activate on release.
26    pub draggable: bool,
27}
28
29impl UiRegion {
30    /// Enabled, focusable button/region. Set `draggable` for a drag surface.
31    pub fn new(id: UiId, bounds: Aabb2) -> Self {
32        Self {
33            id,
34            bounds,
35            enabled: true,
36            focusable: true,
37            draggable: false,
38        }
39    }
40}
41
42/// Physical bindings remain game-owned; these actions drive the interaction state.
43#[derive(Clone, Copy, Debug)]
44pub struct UiActions {
45    /// Pointer's primary button action.
46    pub primary: Action,
47    /// Move focus forward in region order.
48    pub next: Action,
49    /// Move focus backward in region order.
50    pub previous: Action,
51    /// Activate the focused region on a press edge.
52    pub activate: Action,
53    /// Cancel pointer capture and clear keyboard focus.
54    pub cancel: Action,
55}
56
57/// Button snapshot, retaining quick taps with both edges between fixed ticks.
58#[derive(Clone, Copy, Debug, Default)]
59pub struct UiButton {
60    /// Currently held.
61    pub down: bool,
62    /// Pressed since the previous consumed tick.
63    pub pressed: bool,
64    /// Released since the previous consumed tick.
65    pub released: bool,
66}
67
68/// One fixed tick's UI input. Supply viewport-mapped positions; `None` denotes
69/// bars/unavailable motion. Focus loss cancels interactions and clears focus.
70#[derive(Clone, Copy, Debug, Default)]
71pub struct UiInput {
72    /// Pointer in reference UI units, when available.
73    pub pointer: Option<Vec2>,
74    /// Primary pointer button.
75    pub primary: UiButton,
76    /// Forward focus press edge.
77    pub next: bool,
78    /// Backward focus press edge.
79    pub previous: bool,
80    /// Focused activation press edge.
81    pub activate: bool,
82    /// Cancellation press edge.
83    pub cancel: bool,
84    /// Whether the native window can accept input.
85    pub window_focused: bool,
86}
87
88impl UiInput {
89    /// Samples game-defined actions without consuming the original input.
90    /// A pending input reset cancels interaction even if focus already returned.
91    pub fn from_actions(
92        input: &Input,
93        pointer: Option<Vec2>,
94        actions: UiActions,
95        window_focused: bool,
96    ) -> Self {
97        Self {
98            pointer,
99            primary: UiButton {
100                down: input.down(actions.primary),
101                pressed: input.pressed(actions.primary),
102                released: input.released(actions.primary),
103            },
104            next: input.pressed(actions.next),
105            previous: input.pressed(actions.previous),
106            activate: input.pressed(actions.activate),
107            cancel: input.pressed(actions.cancel),
108            window_focused: window_focused && !input.reset_pending(),
109        }
110    }
111}
112
113/// Ownership signals for explicit gameplay routing. Modal games can block all
114/// gameplay actions; overlays can block only shared click/navigation actions.
115#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
116pub struct UiCapture {
117    /// A region is hovered or owns this tick's pointer press/drag/release.
118    pub pointer: bool,
119    /// A region has keyboard focus or this tick cancelled an existing focus.
120    pub keyboard: bool,
121}
122
123/// Current presentation state and one-tick events for an identified region.
124#[derive(Clone, Copy, Debug)]
125pub struct UiResponse {
126    /// Original stable identity.
127    pub id: UiId,
128    /// Whether the current region is enabled.
129    pub enabled: bool,
130    /// Topmost pointer hit, including disabled regions.
131    pub hovered: bool,
132    /// Keyboard focus.
133    pub focused: bool,
134    /// Pointer press began here.
135    pub pressed: bool,
136    /// Pointer is held by this region, including outside its bounds.
137    pub held: bool,
138    /// Pointer capture ended, including cancellation.
139    pub released: bool,
140    /// Button release inside its region, or focused keyboard activation.
141    pub activated: bool,
142    /// Drag began on this tick.
143    pub drag_started: bool,
144    /// UI-unit motion since the preceding update; zero for unavailable positions.
145    pub drag_delta: Vec2,
146    /// UI-unit motion from drag start to the latest available position.
147    pub drag_total: Vec2,
148    /// Drag ended, including cancellation.
149    pub drag_ended: bool,
150    /// Capture cancelled by focus loss, removal, disable, cancel, or lost button state.
151    pub cancelled: bool,
152}
153
154impl UiResponse {
155    fn new(id: UiId, enabled: bool) -> Self {
156        Self {
157            id,
158            enabled,
159            hovered: false,
160            focused: false,
161            pressed: false,
162            held: false,
163            released: false,
164            activated: false,
165            drag_started: false,
166            drag_delta: Vec2::ZERO,
167            drag_total: Vec2::ZERO,
168            drag_ended: false,
169            cancelled: false,
170        }
171    }
172}
173
174#[derive(Clone, Copy)]
175struct Active {
176    id: UiId,
177    draggable: bool,
178    origin: Vec2,
179    last: Vec2,
180}
181
182/// Small immediate UI interaction state. Response storage is reused after its
183/// high-water mark; hit testing/navigation is linear in the submitted regions.
184/// Update once per fixed tick before gameplay, then draw the responses.
185#[derive(Default)]
186pub struct UiState {
187    focus: Option<UiId>,
188    active: Option<Active>,
189    responses: Vec<UiResponse>,
190}
191
192impl UiState {
193    /// Preallocates response storage, including one removed-capture cancellation.
194    pub fn with_capacity(regions: usize) -> Self {
195        Self {
196            responses: Vec::with_capacity(regions.saturating_add(1)),
197            ..Self::default()
198        }
199    }
200
201    /// Focused region, retained by identity across reordering and resizing.
202    pub fn focused(&self) -> Option<UiId> {
203        self.focus
204    }
205
206    /// Current response. A removed captured region is retained for one update
207    /// with `cancelled = true`, allowing game-owned drag cleanup.
208    pub fn response(&self, id: UiId) -> Option<&UiResponse> {
209        self.responses.iter().find(|response| response.id == id)
210    }
211
212    /// All current responses in region order, then any removed capture event.
213    pub fn responses(&self) -> &[UiResponse] {
214        &self.responses
215    }
216
217    /// Resolves focus and pointer capture using the current layout. Releasing
218    /// outside does not activate a button; drags retain capture outside/bars.
219    /// Simultaneous next/previous presses cancel navigation. Pointer capture
220    /// suspends keyboard navigation/activation until it ends.
221    pub fn update(&mut self, regions: &[UiRegion], input: UiInput) -> UiCapture {
222        debug_assert!(
223            regions
224                .iter()
225                .enumerate()
226                .all(|(i, r)| regions[..i].iter().all(|other| other.id != r.id)),
227            "UI region IDs must be unique"
228        );
229        self.responses.clear();
230        self.responses
231            .extend(regions.iter().map(|r| UiResponse::new(r.id, r.enabled)));
232        let had_focus = self.focus.is_some();
233        let had_active = self.active.is_some();
234        if self.focus.is_some_and(|id| {
235            !regions
236                .iter()
237                .any(|r| r.id == id && r.enabled && r.focusable)
238        }) {
239            self.focus = None;
240        }
241        let invalid_active = self
242            .active
243            .is_some_and(|a| !regions.iter().any(|r| r.id == a.id && r.enabled));
244        if (invalid_active || !input.window_focused || input.cancel)
245            && let Some(active) = self.active.take()
246        {
247            if self.response(active.id).is_none() {
248                self.responses.push(UiResponse::new(active.id, false));
249            }
250            let response = self.response_mut(active.id);
251            response.released = true;
252            response.cancelled = true;
253            response.drag_ended = active.draggable;
254            response.drag_total = active.last - active.origin;
255        }
256        if !input.window_focused || input.cancel {
257            self.focus = None;
258        }
259        if !input.window_focused {
260            return UiCapture {
261                pointer: had_active,
262                keyboard: had_focus,
263            };
264        }
265        let pointer = input.pointer.filter(|p| p.is_finite());
266        let hovered = pointer.and_then(|p| regions.iter().rposition(|r| r.bounds.contains(p)));
267        if !input.cancel && self.active.is_none() && input.next != input.previous {
268            let current = self
269                .focus
270                .and_then(|id| regions.iter().position(|r| r.id == id));
271            let count = regions.len();
272            for offset in 0..count {
273                let index = if input.next {
274                    current.map_or(offset, |i| (i + 1 + offset) % count)
275                } else {
276                    current.map_or(count - 1 - offset, |i| (i + count - 1 - offset) % count)
277                };
278                if regions[index].enabled && regions[index].focusable {
279                    self.focus = Some(regions[index].id);
280                    break;
281                }
282            }
283        }
284        if !input.cancel && input.primary.pressed && self.active.is_none() {
285            self.focus = None;
286            if let Some(index) = hovered.filter(|&i| regions[i].enabled) {
287                let region = regions[index];
288                if region.focusable {
289                    self.focus = Some(region.id);
290                }
291                let position = pointer.expect("hover requires a pointer");
292                self.active = Some(Active {
293                    id: region.id,
294                    draggable: region.draggable,
295                    origin: position,
296                    last: position,
297                });
298                let response = self.response_mut(region.id);
299                response.pressed = true;
300                response.drag_started = region.draggable;
301            }
302        }
303        if let Some(mut active) = self.active {
304            let response = self.response_mut(active.id);
305            response.held = input.primary.down;
306            if active.draggable {
307                if let Some(position) = pointer {
308                    response.drag_delta = position - active.last;
309                    active.last = position;
310                }
311                response.drag_total = active.last - active.origin;
312            }
313            if input.primary.released || !input.primary.down {
314                response.released = true;
315                response.held = false;
316                response.drag_ended = active.draggable;
317                response.cancelled = !input.primary.released;
318                response.activated = !active.draggable
319                    && input.primary.released
320                    && hovered.is_some_and(|i| regions[i].id == active.id);
321                self.active = None;
322            } else {
323                self.active = Some(active);
324            }
325        }
326        if !input.cancel
327            && !input.primary.pressed
328            && self.active.is_none()
329            && input.activate
330            && let Some(id) = self.focus
331        {
332            // A drag surface's Enter/Space press can still be handled by game code.
333            self.response_mut(id).activated = true;
334        }
335        if let Some(index) = hovered {
336            self.responses[index].hovered = true;
337        }
338        if let Some(id) = self.focus {
339            self.response_mut(id).focused = true;
340        }
341        UiCapture {
342            pointer: hovered.is_some() || had_active || self.active.is_some(),
343            keyboard: self.focus.is_some() || (had_focus && input.cancel),
344        }
345    }
346
347    fn response_mut(&mut self, id: UiId) -> &mut UiResponse {
348        self.responses
349            .iter_mut()
350            .find(|r| r.id == id)
351            .expect("active/focused region has a response")
352    }
353}
354
355#[cfg(test)]
356mod tests;