bevy_enhanced_input 0.23.2

Input manager for Bevy, inspired by Unreal Engine Enhanced Input
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
use core::time::Duration;

use bevy::prelude::*;
use log::warn;

use crate::prelude::*;

/**
Sequence of actions that needs to be triggered in specific order.

The combo resets if a step is triggered out of order or by any defined
cancel action.

After the first step, returns [`ActionState::Ongoing`] until the last step.
Once all steps are completed, returns [`ActionState::Fired`] once, then resets.

Requires using [`SpawnRelated::spawn`] or separate spawning with [`ActionOf`]/[`BindingOf`]
because you need to pass [`Entity`] for step and cancel actions.

# Examples

Double click:

```
use bevy::prelude::*;
use bevy_enhanced_input::prelude::*;

# let mut world = World::new();
world.spawn((
    Menu,
    Actions::<Menu>::spawn(SpawnWith(|context: &mut ActionSpawner<_>| {
        let click = context
            .spawn((Action::<Click>::new(), bindings![MouseButton::Left]))
            .id();

        context.spawn((
            Action::<DoubleClick>::new(),
            Combo::default().with_step(click).with_step(click),
        ));
    })),
));

#[derive(InputAction)]
#[action_output(bool)]
struct Click;

#[derive(InputAction)]
#[action_output(bool)]
struct DoubleClick;

#[derive(Component)]
struct Menu;
```
*/
#[derive(Component, Reflect, Default, Debug, Clone)]
pub struct Combo {
    /// Ordered sequence of steps that define the combo.
    ///
    /// Each step is satisfied when its [`ComboStep::events`] occur,
    /// and steps must be completed in order.
    pub steps: Vec<ComboStep>,

    /// Actions that can cancel the combo.
    ///
    /// If a cancel action matches the action from the current step, it will be ignored.
    pub cancel_actions: Vec<CancelAction>,

    /// The type of time used to advance the timer.
    pub time_kind: TimeKind,

    /// Index of the current step in the combo.
    step_index: usize,

    /// Tracks timeout for completing the current step.
    timer: Timer,
}

impl Combo {
    /// Adds an action step to the combo.
    ///
    /// If you don't need to configure the step, you can just pass the action's [`Entity`].
    pub fn with_step(mut self, step: impl Into<ComboStep>) -> Self {
        self.steps.push(step.into());
        self
    }

    /// Adds an action that cancels the combo.
    ///
    /// If you don't need to configure the events, you can just pass the action's [`Entity`].
    pub fn with_cancel(mut self, action: impl Into<CancelAction>) -> Self {
        self.cancel_actions.push(action.into());
        self
    }

    /// Returns the associated timer.
    #[must_use]
    pub fn timer(&self) -> &Timer {
        &self.timer
    }

    fn reset(&mut self) {
        self.step_index = 0;
        self.timer.reset();

        let duration = self.steps.first().map(|s| s.timeout).unwrap_or_default();
        self.timer.set_duration(Duration::from_secs_f32(duration));
    }

    fn is_cancelled(&self, actions: &ActionsQuery) -> bool {
        let current_step = &self.steps[self.step_index];
        for condition in &self.cancel_actions {
            if condition.action == current_step.action {
                continue;
            }

            let Ok((.., events, _)) = actions.get(condition.action) else {
                // TODO: use `warn_once` when `bevy_log` becomes `no_std` compatible.
                warn!(
                    "cancel condition references an invalid action `{}`",
                    condition.action
                );
                continue;
            };

            if events.intersects(condition.events) {
                return true;
            }
        }

        // Check if any other step is also triggered, breaking the order.
        for step in &self.steps {
            if step.action == current_step.action {
                continue;
            }
            let Ok((.., events, _)) = actions.get(step.action) else {
                continue;
            };

            if events.intersects(step.events) {
                return true;
            }
        }

        false
    }
}

impl InputCondition for Combo {
    fn evaluate(
        &mut self,
        actions: &ActionsQuery,
        time: &ContextTime,
        _value: ActionValue,
    ) -> ActionState {
        if self.steps.is_empty() {
            // TODO: use `warn_once` when `bevy_log` becomes `no_std` compatible.
            warn!("combo has no steps");
            return ActionState::None;
        }

        if self.is_cancelled(actions) {
            // We don't early-return since the first step could be triggered.
            self.reset();
        }

        if self.step_index > 0 {
            self.timer.tick(time.delta_kind(self.time_kind));

            if self.timer.is_finished() {
                self.reset();
            }
        }

        let current_step = &self.steps[self.step_index];
        let Ok((_, &state, events, _)) = actions.get(current_step.action) else {
            // TODO: use `warn_once` when `bevy_log` becomes `no_std` compatible.
            warn!(
                "step {} references an invalid action `{}`",
                self.step_index, current_step.action
            );
            self.reset();
            return ActionState::None;
        };

        if events.contains(current_step.events) {
            self.step_index += 1;

            if self.step_index >= self.steps.len() {
                // Completed all combo actions.
                self.reset();
                return ActionState::Fired;
            } else {
                let next_step = &self.steps[self.step_index];
                self.timer.reset();
                self.timer
                    .set_duration(Duration::from_secs_f32(next_step.timeout));
            }
        }

        if self.step_index > 0 || state > ActionState::None {
            return ActionState::Ongoing;
        }

        ActionState::None
    }

    fn kind(&self) -> ConditionKind {
        ConditionKind::Implicit
    }
}

/// An action with associated events that progress [`Combo`].
#[derive(Reflect, Debug, Clone, Copy)]
pub struct ComboStep {
    /// Associated action.
    pub action: Entity,

    /// Events for the action to complete this step.
    pub events: ActionEvents,

    /// Time in seconds to trigger [`Self::events`] before the combo is cancelled.
    ///
    /// Starts once the previous step in the combo is completed.
    /// Ignored for the first action in the combo.
    pub timeout: f32,
}

impl ComboStep {
    /// Creates a new instance with [`Self::events`] set to [`ActionEvents::COMPLETE`]
    /// and [`Self::timeout`] set to 0.5.
    #[must_use]
    pub fn new(action: Entity) -> Self {
        Self {
            action,
            events: ActionEvents::COMPLETE,
            timeout: 0.5,
        }
    }

    /// Sets [`Self::with_events`].
    #[must_use]
    pub fn with_events(mut self, events: ActionEvents) -> Self {
        self.events = events;
        self
    }

    /// Sets [`Self::timeout`].
    #[must_use]
    pub fn with_timeout(mut self, timeout: f32) -> Self {
        self.timeout = timeout;
        self
    }
}

impl From<Entity> for ComboStep {
    fn from(action: Entity) -> Self {
        Self::new(action)
    }
}

/// An action with associated events that cancel a [`Combo`].
#[derive(Reflect, Debug, Clone, Copy)]
pub struct CancelAction {
    /// Associated action.
    pub action: Entity,

    /// Events that cancel the combo if any occur.
    pub events: ActionEvents,
}

impl CancelAction {
    /// Creates a new instance with events set to [`ActionEvents::ONGOING`] and [`ActionEvents::FIRED`].
    #[must_use]
    fn new(action: Entity) -> Self {
        Self {
            action,
            events: ActionEvents::ONGOING | ActionEvents::FIRE,
        }
    }
}

impl From<Entity> for CancelAction {
    fn from(action: Entity) -> Self {
        Self::new(action)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context;

    #[test]
    fn empty() {
        let (world, mut state) = context::init_world();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default();
        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
    }

    #[test]
    fn invalid_step() {
        let (world, mut state) = context::init_world();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default().with_step(Entity::PLACEHOLDER);
        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn timeout() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::COMPLETE))
            .id();
        let action_b = world.spawn(Action::<B>::new()).id();
        world
            .resource_mut::<Time<Real>>()
            .advance_by(Duration::from_secs(1));
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default().with_step(action_a).with_step(action_b);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing,
            "first step shouldn't be affected by time"
        );
        assert_eq!(condition.step_index, 1);

        world
            .resource_mut::<Time<Real>>()
            .advance_by(Duration::from_secs(1));
        world.entity_mut(action_a).insert(ActionEvents::empty()); // Clear `Complete` event.
        world.entity_mut(action_b).insert(ActionEvents::COMPLETE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn first_step_ongoing() {
        let (mut world, mut state) = context::init_world();
        let action_a = world.spawn((Action::<A>::new(), ActionState::Ongoing)).id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default().with_step(action_a);
        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
    }

    #[test]
    fn steps() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::ONGOING))
            .id();
        let action_b = world.spawn(Action::<B>::new()).id();
        let action_c = world.spawn(Action::<C>::new()).id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default()
            .with_step(ComboStep::new(action_a).with_events(ActionEvents::ONGOING))
            .with_step(ComboStep::new(action_b).with_timeout(0.6))
            .with_step(ComboStep::new(action_c).with_timeout(0.3));

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
        assert_eq!(condition.step_index, 1);

        world
            .resource_mut::<Time<Real>>()
            .advance_by(Duration::from_secs_f32(0.5));
        world.entity_mut(action_a).insert(ActionEvents::empty());
        world.entity_mut(action_b).insert(ActionEvents::COMPLETE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
        assert_eq!(condition.step_index, 2);

        world
            .resource_mut::<Time<Real>>()
            .advance_by(Duration::from_secs_f32(0.2));
        world.entity_mut(action_b).insert(ActionEvents::empty());
        world.entity_mut(action_c).insert(ActionEvents::COMPLETE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Fired
        );
        assert_eq!(condition.step_index, 0);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn same_action() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::COMPLETE))
            .id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default().with_step(action_a).with_step(action_a);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
        assert_eq!(condition.step_index, 1);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Fired
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn out_of_order() {
        let (mut world, mut state) = context::init_world();
        let action_a = world.spawn(Action::<A>::new()).id();
        let action_b = world
            .spawn((Action::<B>::new(), ActionEvents::COMPLETE))
            .id();
        let action_c = world.spawn(Action::<C>::new()).id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default()
            .with_step(action_a)
            .with_step(action_b)
            .with_step(action_c);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);

        world.entity_mut(action_b).insert(ActionEvents::empty());
        world.entity_mut(action_a).insert(ActionEvents::COMPLETE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
        assert_eq!(condition.step_index, 1);

        world.entity_mut(action_a).insert(ActionEvents::empty());
        world.entity_mut(action_c).insert(ActionEvents::COMPLETE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn ignore_same_cancel_action() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::COMPLETE))
            .id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default().with_step(action_a).with_cancel(action_a);
        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Fired
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn missing_cancel_action() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::COMPLETE))
            .id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default()
            .with_step(action_a)
            .with_cancel(Entity::PLACEHOLDER);
        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Fired
        );
        assert_eq!(condition.step_index, 0);
    }

    #[test]
    fn cancel() {
        let (mut world, mut state) = context::init_world();
        let action_a = world
            .spawn((Action::<A>::new(), ActionEvents::COMPLETE))
            .id();
        let action_b = world.spawn(Action::<B>::new()).id();
        let action_c = world.spawn(Action::<C>::new()).id();
        let (time, actions) = state.get(&world);

        let mut condition = Combo::default()
            .with_step(action_a)
            .with_step(action_b)
            .with_cancel(action_c);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::Ongoing
        );
        assert_eq!(condition.step_index, 1);

        world.entity_mut(action_a).insert(ActionEvents::empty());
        world.entity_mut(action_b).insert(ActionEvents::COMPLETE);
        world.entity_mut(action_c).insert(ActionEvents::FIRE);
        let (time, actions) = state.get(&world);

        assert_eq!(
            condition.evaluate(&actions, &time, 0.0.into()),
            ActionState::None
        );
        assert_eq!(condition.step_index, 0);
    }

    #[derive(Debug, InputAction)]
    #[action_output(bool)]
    struct A;

    #[derive(Debug, InputAction)]
    #[action_output(bool)]
    struct B;

    #[derive(Debug, InputAction)]
    #[action_output(bool)]
    struct C;
}