1use super::{LoopError, seconds};
9
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29pub struct InteractionInput {
30 pub pair: Option<(u64, u64)>,
32 pub held: bool,
34 pub in_range: bool,
36 pub focused: bool,
38 pub permitted: bool,
40 pub visible: bool,
42}
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum InteractionRejection {
51 NoTarget,
53 FocusLost,
55 NotHeld,
57 OutOfRange,
59 PermissionDenied,
61 Obstructed,
63 AlreadyCompleted,
65}
66
67#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum InteractionInterruption {
74 Rejected(InteractionRejection),
76 PairChanged {
78 previous: (u64, u64),
80 current: (u64, u64),
82 },
83}
84
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
91pub struct InteractionOutcome {
92 pub completed: bool,
94 pub rejection: Option<InteractionRejection>,
96 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 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 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 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 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 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}