ferravex_play/gameplay/
interaction.rs

1//! Hold interactions bound to a specific actor/target pair with explicit interruption.
2//!
3//! Query [`Interaction::eligibility`] for prompts without changing the hold. On
4//! each actual simulation tick, supply current conditions to
5//! [`Interaction::step_checked`]; only its `completed` result grants a reward or
6//! accepted-event feedback. Hosts remain responsible for authoritative range,
7//! visibility and permission checks. These rules read no platform state or clock.
8use super::{LoopError, seconds};
9
10/// A host-supplied snapshot of the conditions for one actor/target pair.
11///
12/// `pair` is `(actor, target)`. All gates must be true to advance a hold. Range
13/// and visibility are supplied as booleans so this rule does not duplicate the
14/// host's geometry queries. `focused` means gameplay input is enabled for this
15/// actor; suppressing local input must not stop authoritative simulation ticks.
16/// The default has no target and all gates closed.
17///
18/// ```
19/// use ferravex_play::gameplay::interaction::{Interaction, InteractionInput};
20/// let input = InteractionInput {
21///     pair: Some((1, 2)), held: true, in_range: true, focused: true,
22///     permitted: true, visible: true,
23/// };
24/// let interaction = Interaction::new(1.0).unwrap();
25/// assert_eq!(interaction.eligibility(input), Ok(()));
26/// assert_eq!(interaction.progress(), 0.0);
27/// ```
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub struct InteractionInput {
30    /// The actor and target, or `None` when no interaction target is selected.
31    pub pair: Option<(u64, u64)>,
32    /// Whether the interaction button is currently held.
33    pub held: bool,
34    /// Whether the actor is within the target's interaction range.
35    pub in_range: bool,
36    /// Whether gameplay input for this actor has focus.
37    pub focused: bool,
38    /// Whether the actor is allowed to perform the interaction.
39    pub permitted: bool,
40    /// Whether required line of sight is clear.
41    pub visible: bool,
42}
43
44/// The first failing gate reported by [`Interaction::eligibility`].
45///
46/// Gate precedence is no target, focus, hold, range, permission, visibility,
47/// then the completion latch. A failed gate can therefore rearm a completed
48/// hold when applied by [`Interaction::step_checked`], just like legacy `None`.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum InteractionRejection {
51    /// No actor/target pair was supplied.
52    NoTarget,
53    /// Gameplay input for this actor no longer has focus.
54    FocusLost,
55    /// The interaction button is not held.
56    NotHeld,
57    /// The target is outside interaction range.
58    OutOfRange,
59    /// The host denied permission to interact.
60    PermissionDenied,
61    /// Required line of sight is blocked.
62    Obstructed,
63    /// This pair already completed; continued holding cannot grant again.
64    AlreadyCompleted,
65}
66
67/// Why an unfinished hold was discarded on this tick.
68///
69/// Rejections interrupt only when there was an unfinished hold. A valid pair
70/// switch both interrupts the old hold and starts the new one using this tick's
71/// time. Resetting a completed latch does not report an unfinished interruption.
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum InteractionInterruption {
74    /// A required condition failed. `AlreadyCompleted` never interrupts a hold.
75    Rejected(InteractionRejection),
76    /// An eligible actor/target pair replaced the unfinished one.
77    PairChanged {
78        /// The pair whose progress was discarded.
79        previous: (u64, u64),
80        /// The pair receiving this tick's time.
81        current: (u64, u64),
82    },
83}
84
85/// Result of one checked simulation step; no events are stored internally.
86///
87/// `completed` is the sole accepted completion signal. A rejection never
88/// completes or advances progress. A pair switch can interrupt the old hold and
89/// complete the new one on the same tick if enough simulation time is supplied.
90#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct InteractionOutcome {
92    /// True exactly once when this hold completes; apply rewards/feedback here.
93    pub completed: bool,
94    /// The gate preventing progress, or `None` for an eligible step.
95    pub rejection: Option<InteractionRejection>,
96    /// The unfinished hold discarded by this step, if any.
97    pub interruption: Option<InteractionInterruption>,
98}
99
100#[derive(Clone, Copy, Debug)]
101pub struct Interaction {
102    duration: f64,
103    elapsed: f64,
104    pair: Option<(u64, u64)>,
105    completed: bool,
106}
107impl Interaction {
108    pub fn new(duration: f32) -> Result<Self, LoopError> {
109        let duration = seconds(duration)?;
110        if duration == 0. {
111            return Err(LoopError::Invalid);
112        }
113        Ok(Self {
114            duration,
115            elapsed: 0.,
116            pair: None,
117            completed: false,
118        })
119    }
120    pub fn progress(&self) -> f32 {
121        (self.elapsed / self.duration) as f32
122    }
123    pub fn cancel(&mut self) {
124        self.elapsed = 0.;
125        self.pair = None;
126        self.completed = false;
127    }
128
129    /// Checks current conditions without consuming time, changing the pair,
130    /// clearing progress or rearming the completion latch.
131    ///
132    /// `Ok(())` means the hold may advance, not that it is complete. A different
133    /// eligible pair may start a new hold; the query does not perform that switch.
134    /// If several gates fail, precedence follows [`InteractionRejection`]. Always
135    /// supply current conditions again when stepping; a query is not authorization
136    /// to use a stale snapshot later.
137    ///
138    /// ```
139    /// use ferravex_play::gameplay::interaction::{
140    ///     Interaction, InteractionInput, InteractionRejection,
141    /// };
142    /// let mut hold = Interaction::new(1.0).unwrap();
143    /// hold.step(0.5, Some((1, 2))).unwrap();
144    /// let blocked = InteractionInput {
145    ///     pair: Some((1, 2)), held: true, in_range: false, focused: true,
146    ///     permitted: true, visible: true,
147    /// };
148    /// assert_eq!(hold.eligibility(blocked), Err(InteractionRejection::OutOfRange));
149    /// assert_eq!(hold.progress(), 0.5);
150    /// ```
151    pub fn eligibility(&self, input: InteractionInput) -> Result<(), InteractionRejection> {
152        let reason = if input.pair.is_none() {
153            InteractionRejection::NoTarget
154        } else if !input.focused {
155            InteractionRejection::FocusLost
156        } else if !input.held {
157            InteractionRejection::NotHeld
158        } else if !input.in_range {
159            InteractionRejection::OutOfRange
160        } else if !input.permitted {
161            InteractionRejection::PermissionDenied
162        } else if !input.visible {
163            InteractionRejection::Obstructed
164        } else if input.pair == self.pair && self.completed {
165            InteractionRejection::AlreadyCompleted
166        } else {
167            return Ok(());
168        };
169        Err(reason)
170    }
171
172    /// Advances an eligible hold and reports rejection/interruption reasons.
173    ///
174    /// A failed condition discards the unfinished hold (continuous holding is
175    /// required), but spends none of `dt` and cannot emit a completion. Repeating
176    /// a rejected input reports the same rejection without another interruption.
177    /// `AlreadyCompleted` preserves the completion latch and full progress.
178    /// Pair switches restart exactly as in [`Self::step`].
179    ///
180    /// Call only for actual simulation ticks, using simulation seconds in
181    /// `0..=3600`. Invalid time returns [`LoopError::Invalid`] before checking
182    /// gates or changing any state, including when input would interrupt.
183    ///
184    /// ```
185    /// use ferravex_play::gameplay::interaction::{
186    ///     Interaction, InteractionInput, InteractionInterruption, InteractionRejection,
187    /// };
188    /// let input = InteractionInput {
189    ///     pair: Some((1, 2)), held: true, in_range: true, focused: true,
190    ///     permitted: true, visible: true,
191    /// };
192    /// let mut hold = Interaction::new(1.0).unwrap();
193    /// assert!(!hold.step_checked(0.5, input).unwrap().completed);
194    /// let lost_focus = InteractionInput { focused: false, ..input };
195    /// let stopped = hold.step_checked(1.0, lost_focus).unwrap();
196    /// assert!(!stopped.completed);
197    /// assert_eq!(stopped.interruption, Some(InteractionInterruption::Rejected(
198    ///     InteractionRejection::FocusLost,
199    /// )));
200    /// assert_eq!(hold.progress(), 0.0);
201    /// assert!(hold.step_checked(1.0, input).unwrap().completed);
202    /// assert_eq!(hold.step_checked(1.0, input).unwrap().rejection,
203    ///     Some(InteractionRejection::AlreadyCompleted));
204    /// ```
205    pub fn step_checked(
206        &mut self,
207        dt: f32,
208        input: InteractionInput,
209    ) -> Result<InteractionOutcome, LoopError> {
210        let dt = seconds(dt)?;
211        if let Err(reason) = self.eligibility(input) {
212            let interruption = (self.pair.is_some() && !self.completed)
213                .then_some(InteractionInterruption::Rejected(reason));
214            if reason != InteractionRejection::AlreadyCompleted {
215                self.cancel();
216            }
217            return Ok(InteractionOutcome {
218                completed: false,
219                rejection: Some(reason),
220                interruption,
221            });
222        }
223        let interruption = match (self.pair, input.pair) {
224            (Some(previous), Some(current)) if previous != current && !self.completed => {
225                Some(InteractionInterruption::PairChanged { previous, current })
226            }
227            _ => None,
228        };
229        Ok(InteractionOutcome {
230            completed: self.step_validated(dt, input.pair),
231            rejection: None,
232            interruption,
233        })
234    }
235
236    /// None interrupts. Supply Some only while the button, range, permissions and
237    /// line of sight are valid. Target switches restart; completion latches until
238    /// interruption/switch, so holding cannot repeatedly grant a reward.
239    /// Use [`Self::step_checked`] to retain typed reasons for failed conditions.
240    pub fn step(&mut self, dt: f32, pair: Option<(u64, u64)>) -> Result<bool, LoopError> {
241        Ok(self.step_validated(seconds(dt)?, pair))
242    }
243
244    fn step_validated(&mut self, dt: f64, pair: Option<(u64, u64)>) -> bool {
245        if pair != self.pair {
246            self.cancel();
247            self.pair = pair;
248        }
249        if pair.is_none() || self.completed {
250            return false;
251        }
252        self.elapsed = (self.elapsed + dt).min(self.duration);
253        if self.elapsed + 1e-7 >= self.duration {
254            self.elapsed = self.duration;
255            self.completed = true;
256            true
257        } else {
258            false
259        }
260    }
261}
262#[cfg(test)]
263mod tests {
264    use super::*;
265
266    fn eligible(pair: (u64, u64)) -> InteractionInput {
267        InteractionInput {
268            pair: Some(pair),
269            held: true,
270            in_range: true,
271            focused: true,
272            permitted: true,
273            visible: true,
274        }
275    }
276
277    fn blocked_inputs() -> [(InteractionInput, InteractionRejection); 6] {
278        let input = eligible((1, 2));
279        [
280            (
281                InteractionInput {
282                    pair: None,
283                    ..input
284                },
285                InteractionRejection::NoTarget,
286            ),
287            (
288                InteractionInput {
289                    focused: false,
290                    ..input
291                },
292                InteractionRejection::FocusLost,
293            ),
294            (
295                InteractionInput {
296                    held: false,
297                    ..input
298                },
299                InteractionRejection::NotHeld,
300            ),
301            (
302                InteractionInput {
303                    in_range: false,
304                    ..input
305                },
306                InteractionRejection::OutOfRange,
307            ),
308            (
309                InteractionInput {
310                    permitted: false,
311                    ..input
312                },
313                InteractionRejection::PermissionDenied,
314            ),
315            (
316                InteractionInput {
317                    visible: false,
318                    ..input
319                },
320                InteractionRejection::Obstructed,
321            ),
322        ]
323    }
324
325    fn assert_same_state(actual: Interaction, expected: Interaction) {
326        assert_eq!(actual.duration, expected.duration);
327        assert_eq!(actual.elapsed, expected.elapsed);
328        assert_eq!(actual.pair, expected.pair);
329        assert_eq!(actual.completed, expected.completed);
330    }
331
332    #[test]
333    fn interruptions_and_target_switches_require_a_full_new_hold() {
334        let mut i = Interaction::new(1.).unwrap();
335        assert!(!i.step(0.5, Some((1, 2))).unwrap());
336        assert!(!i.step(0.5, Some((1, 3))).unwrap());
337        assert!(!i.step(0., None).unwrap());
338        assert_eq!(i.progress(), 0.);
339        assert!(i.step(1., Some((1, 3))).unwrap());
340        assert!(!i.step(2., Some((1, 3))).unwrap());
341        assert!(i.step(f32::NAN, None).is_err());
342        assert_eq!(i.progress(), 1.);
343    }
344
345    #[test]
346    fn eligibility_queries_preserve_idle_partial_and_completed_holds() {
347        for elapsed in [0., 0.5, 1.] {
348            let mut hold = Interaction::new(1.).unwrap();
349            if elapsed > 0. {
350                hold.step(elapsed, Some((1, 2))).unwrap();
351            }
352            let before = hold;
353            for (input, reason) in blocked_inputs() {
354                assert_eq!(hold.eligibility(input), Err(reason));
355                assert_same_state(hold, before);
356            }
357            let expected = if elapsed == 1. {
358                Err(InteractionRejection::AlreadyCompleted)
359            } else {
360                Ok(())
361            };
362            for _ in 0..3 {
363                assert_eq!(hold.eligibility(eligible((1, 2))), expected);
364                // Merely displaying another target must not switch or rearm.
365                assert_eq!(hold.eligibility(eligible((1, 3))), Ok(()));
366                assert_eq!(hold.eligibility(eligible((9, 2))), Ok(()));
367                assert_same_state(hold, before);
368            }
369        }
370    }
371
372    #[test]
373    fn failed_gates_interrupt_once_without_using_time_or_completing() {
374        let valid = eligible((1, 2));
375        for (input, reason) in blocked_inputs() {
376            let mut hold = Interaction::new(1.).unwrap();
377            assert!(!hold.step_checked(0.75, valid).unwrap().completed);
378            assert_eq!(
379                hold.step_checked(3600., input).unwrap(),
380                InteractionOutcome {
381                    completed: false,
382                    rejection: Some(reason),
383                    interruption: Some(InteractionInterruption::Rejected(reason)),
384                }
385            );
386            assert_eq!(hold.progress(), 0.);
387            assert_eq!(
388                hold.step_checked(3600., input).unwrap(),
389                InteractionOutcome {
390                    completed: false,
391                    rejection: Some(reason),
392                    interruption: None,
393                }
394            );
395            // Neither the previous hold nor the blocked time is carried over.
396            assert!(!hold.step_checked(0.25, valid).unwrap().completed);
397            assert_eq!(hold.progress(), 0.25);
398            assert!(hold.step_checked(0.75, valid).unwrap().completed);
399        }
400    }
401
402    #[test]
403    fn gate_precedence_is_stable_even_after_completion() {
404        let mut hold = Interaction::new(1.).unwrap();
405        hold.step(1., Some((1, 2))).unwrap();
406        let mut input = InteractionInput::default();
407        assert_eq!(hold.eligibility(input), Err(InteractionRejection::NoTarget));
408        input.pair = Some((1, 2));
409        assert_eq!(
410            hold.eligibility(input),
411            Err(InteractionRejection::FocusLost)
412        );
413        input.focused = true;
414        assert_eq!(hold.eligibility(input), Err(InteractionRejection::NotHeld));
415        input.held = true;
416        assert_eq!(
417            hold.eligibility(input),
418            Err(InteractionRejection::OutOfRange)
419        );
420        input.in_range = true;
421        assert_eq!(
422            hold.eligibility(input),
423            Err(InteractionRejection::PermissionDenied)
424        );
425        input.permitted = true;
426        assert_eq!(
427            hold.eligibility(input),
428            Err(InteractionRejection::Obstructed)
429        );
430        input.visible = true;
431        assert_eq!(
432            hold.eligibility(input),
433            Err(InteractionRejection::AlreadyCompleted)
434        );
435        assert_eq!(hold.progress(), 1.);
436    }
437
438    #[test]
439    fn completion_latches_until_a_condition_fails_or_the_pair_changes() {
440        let valid = eligible((1, 2));
441        for (input, reason) in blocked_inputs() {
442            let mut hold = Interaction::new(1.).unwrap();
443            assert!(hold.step_checked(1., valid).unwrap().completed);
444            let completed = hold;
445            for _ in 0..3 {
446                assert_eq!(
447                    hold.step_checked(3600., valid).unwrap(),
448                    InteractionOutcome {
449                        completed: false,
450                        rejection: Some(InteractionRejection::AlreadyCompleted),
451                        interruption: None,
452                    }
453                );
454                assert_same_state(hold, completed);
455            }
456            assert_eq!(
457                hold.step_checked(0., input).unwrap(),
458                InteractionOutcome {
459                    completed: false,
460                    rejection: Some(reason),
461                    interruption: None,
462                }
463            );
464            assert_eq!(hold.progress(), 0.);
465            assert!(!hold.step_checked(0.5, valid).unwrap().completed);
466            assert!(hold.step_checked(0.5, valid).unwrap().completed);
467        }
468        let mut hold = Interaction::new(1.).unwrap();
469        hold.step_checked(1., valid).unwrap();
470        assert_eq!(
471            hold.step_checked(1., eligible((1, 3))).unwrap(),
472            InteractionOutcome {
473                completed: true,
474                rejection: None,
475                interruption: None,
476            }
477        );
478    }
479
480    #[test]
481    fn actor_and_target_switches_report_the_discarded_hold() {
482        for next_pair in [(1, 3), (9, 2)] {
483            for dt in [0.25, 1.] {
484                let mut hold = Interaction::new(1.).unwrap();
485                hold.step_checked(0.75, eligible((1, 2))).unwrap();
486                assert_eq!(
487                    hold.step_checked(dt, eligible(next_pair)).unwrap(),
488                    InteractionOutcome {
489                        completed: dt == 1.,
490                        rejection: None,
491                        interruption: Some(InteractionInterruption::PairChanged {
492                            previous: (1, 2),
493                            current: next_pair,
494                        }),
495                    }
496                );
497                assert_eq!(hold.progress(), dt);
498            }
499        }
500    }
501
502    #[test]
503    fn ineligible_replacement_cannot_receive_or_complete_the_old_hold() {
504        let mut hold = Interaction::new(1.).unwrap();
505        hold.step_checked(0.75, eligible((1, 2))).unwrap();
506        let unavailable = InteractionInput {
507            in_range: false,
508            ..eligible((1, 3))
509        };
510        let result = hold.step_checked(1., unavailable).unwrap();
511        assert!(!result.completed);
512        assert_eq!(result.rejection, Some(InteractionRejection::OutOfRange));
513        assert_eq!(
514            result.interruption,
515            Some(InteractionInterruption::Rejected(
516                InteractionRejection::OutOfRange
517            ))
518        );
519        assert_eq!(hold.pair, None);
520        assert!(!hold.step_checked(0.25, eligible((1, 3))).unwrap().completed);
521        assert_eq!(hold.progress(), 0.25);
522    }
523
524    #[test]
525    fn invalid_time_is_transactional_before_gates_switches_and_latches() {
526        let valid = eligible((1, 2));
527        for elapsed in [0., 0.5, 1.] {
528            let mut hold = Interaction::new(1.).unwrap();
529            if elapsed > 0. {
530                hold.step_checked(elapsed, valid).unwrap();
531            }
532            let before = hold;
533            for dt in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -0.1, 3601.] {
534                for input in [valid, eligible((9, 3)), InteractionInput::default()]
535                    .into_iter()
536                    .chain(blocked_inputs().map(|(input, _)| input))
537                {
538                    assert_eq!(hold.step_checked(dt, input), Err(LoopError::Invalid));
539                    assert_same_state(hold, before);
540                    assert_eq!(hold.step(dt, input.pair), Err(LoopError::Invalid));
541                    assert_same_state(hold, before);
542                }
543            }
544        }
545    }
546
547    #[test]
548    fn legacy_and_checked_steps_share_progress_cancellation_and_completion() {
549        let mut legacy = Interaction::new(1.).unwrap();
550        let mut checked = legacy;
551        let valid = eligible((1, 2));
552        let switched = eligible((9, 3));
553        for (dt, input) in [
554            (0., valid),
555            (0.5, valid),
556            (0.5, switched),
557            (0., InteractionInput::default()),
558            (0.25, switched),
559            (0.75, switched),
560            (1., switched),
561            (0.5, valid),
562            (0.5, valid),
563        ] {
564            assert_eq!(
565                legacy.step(dt, input.pair).unwrap(),
566                checked.step_checked(dt, input).unwrap().completed
567            );
568            assert_same_state(checked, legacy);
569        }
570        checked.cancel();
571        legacy.cancel();
572        assert_same_state(checked, legacy);
573        assert_eq!(checked.eligibility(valid), Ok(()));
574        assert_eq!(checked.progress(), 0.);
575    }
576
577    #[test]
578    fn fixed_ticks_complete_once_and_queries_between_ticks_do_not_advance() {
579        let mut hold = Interaction::new(1.).unwrap();
580        let input = eligible((1, 2));
581        let mut completions = 0;
582        for tick in 0..120 {
583            let before = hold;
584            for _ in 0..3 {
585                let _ = hold.eligibility(input);
586            }
587            assert_same_state(hold, before);
588            let result = hold.step_checked(1. / 60., input).unwrap();
589            completions += usize::from(result.completed);
590            assert_eq!(result.completed, tick == 59);
591        }
592        assert_eq!(completions, 1);
593        assert_eq!(hold.progress(), 1.);
594    }
595}