leafwing-input-manager 0.20.0

A powerful, flexible and ergonomic way to manage action-input keybindings for the Bevy game engine.
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
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
//! This module contains [`VirtualAxis`], [`VirtualDPad`], and [`VirtualDPad3D`].

use crate as leafwing_input_manager;
use crate::InputControlKind;
use crate::clashing_inputs::BasicInputs;
use crate::input_processing::{
    AxisProcessor, DualAxisProcessor, WithAxisProcessingPipelineExt,
    WithDualAxisProcessingPipelineExt,
};
use crate::prelude::updating::CentralInputStore;
use crate::prelude::{Axislike, DualAxislike, TripleAxislike, UserInput};
use crate::user_input::Buttonlike;
use bevy::math::{Vec2, Vec3};
#[cfg(feature = "gamepad")]
use bevy::prelude::GamepadButton;
#[cfg(feature = "keyboard")]
use bevy::prelude::KeyCode;
use bevy::prelude::{Entity, Reflect, World};
use leafwing_input_manager_macros::serde_typetag;
use serde::{Deserialize, Serialize};

/// A virtual single-axis control constructed from two [`Buttonlike`]s.
/// One button represents the negative direction (left for the X-axis, down for the Y-axis),
/// while the other represents the positive direction (right for the X-axis, up for the Y-axis).
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithAxisProcessingPipelineExt`] for details.
///
/// The raw value is determined based on the state of the associated buttons:
/// - `-1.0` if only the negative button is currently pressed.
/// - `1.0` if only the positive button is currently pressed.
/// - `0.0` if neither button is pressed, or both are pressed simultaneously.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
/// use leafwing_input_manager::plugin::CentralInputStorePlugin;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, CentralInputStorePlugin));
///
/// // Define a virtual Y-axis using arrow "up" and "down" keys
/// let axis = VirtualAxis::vertical_arrow_keys();
///
/// // Pressing either key activates the input
/// KeyCode::ArrowUp.press(app.world_mut());
/// app.update();
/// assert_eq!(app.read_axis_value(axis), 1.0);
///
/// // You can configure a processing pipeline (e.g., doubling the value)
/// let doubled = VirtualAxis::vertical_arrow_keys().sensitivity(2.0);
/// assert_eq!(app.read_axis_value(doubled), 2.0);
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct VirtualAxis {
    /// The button that represents the negative direction.
    pub negative: Box<dyn Buttonlike>,

    /// The button that represents the positive direction.
    pub positive: Box<dyn Buttonlike>,

    /// A processing pipeline that handles input values.
    pub processors: Vec<AxisProcessor>,
}

impl VirtualAxis {
    /// Creates a new [`VirtualAxis`] with two given [`Buttonlike`]s.
    /// No processing is applied to raw data.
    #[inline]
    pub fn new(negative: impl Buttonlike, positive: impl Buttonlike) -> Self {
        Self {
            negative: Box::new(negative),
            positive: Box::new(positive),
            processors: Vec::new(),
        }
    }

    /// The [`VirtualAxis`] using the vertical arrow key mappings.
    ///
    /// - [`KeyCode::ArrowDown`] for negative direction.
    /// - [`KeyCode::ArrowUp`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn vertical_arrow_keys() -> Self {
        Self::new(KeyCode::ArrowDown, KeyCode::ArrowUp)
    }

    /// The [`VirtualAxis`] using the horizontal arrow key mappings.
    ///
    /// - [`KeyCode::ArrowLeft`] for negative direction.
    /// - [`KeyCode::ArrowRight`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn horizontal_arrow_keys() -> Self {
        Self::new(KeyCode::ArrowLeft, KeyCode::ArrowRight)
    }

    /// The [`VirtualAxis`] using the common W/S key mappings.
    ///
    /// - [`KeyCode::KeyS`] for negative direction.
    /// - [`KeyCode::KeyW`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn ws() -> Self {
        Self::new(KeyCode::KeyS, KeyCode::KeyW)
    }

    /// The [`VirtualAxis`] using the common A/D key mappings.
    ///
    /// - [`KeyCode::KeyA`] for negative direction.
    /// - [`KeyCode::KeyD`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn ad() -> Self {
        Self::new(KeyCode::KeyA, KeyCode::KeyD)
    }

    /// The [`VirtualAxis`] using the vertical numpad key mappings.
    ///
    /// - [`KeyCode::Numpad2`] for negative direction.
    /// - [`KeyCode::Numpad8`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn vertical_numpad() -> Self {
        Self::new(KeyCode::Numpad2, KeyCode::Numpad8)
    }

    /// The [`VirtualAxis`] using the horizontal numpad key mappings.
    ///
    /// - [`KeyCode::Numpad4`] for negative direction.
    /// - [`KeyCode::Numpad6`] for positive direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn horizontal_numpad() -> Self {
        Self::new(KeyCode::Numpad4, KeyCode::Numpad6)
    }

    /// The [`VirtualAxis`] using the horizontal D-Pad button mappings.
    /// No processing is applied to raw data from the gamepad.
    ///
    /// - [`GamepadButton::DPadLeft`] for negative direction.
    /// - [`GamepadButton::DPadRight`] for positive direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn dpad_x() -> Self {
        Self::new(GamepadButton::DPadLeft, GamepadButton::DPadRight)
    }

    /// The [`VirtualAxis`] using the vertical D-Pad button mappings.
    /// No processing is applied to raw data from the gamepad.
    ///
    /// - [`GamepadButton::DPadDown`] for negative direction.
    /// - [`GamepadButton::DPadUp`] for positive direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn dpad_y() -> Self {
        Self::new(GamepadButton::DPadDown, GamepadButton::DPadUp)
    }

    /// The [`VirtualAxis`] using the horizontal action pad button mappings.
    /// No processing is applied to raw data from the gamepad.
    ///
    /// - [`GamepadButton::West`] for negative direction.
    /// - [`GamepadButton::East`] for positive direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn action_pad_x() -> Self {
        Self::new(GamepadButton::West, GamepadButton::East)
    }

    /// The [`VirtualAxis`] using the vertical action pad button mappings.
    /// No processing is applied to raw data from the gamepad.
    ///
    /// - [`GamepadButton::South`] for negative direction.
    /// - [`GamepadButton::North`] for positive direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn action_pad_y() -> Self {
        Self::new(GamepadButton::South, GamepadButton::North)
    }
}

impl UserInput for VirtualAxis {
    /// [`VirtualAxis`] acts as a virtual axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::Axis
    }

    /// [`VirtualAxis`] represents a compositions of two buttons.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![self.negative.clone(), self.positive.clone()])
    }
}

#[serde_typetag]
impl Axislike for VirtualAxis {
    /// Retrieves the current value of this axis after processing by the associated processors.
    #[inline]
    fn get_value(&self, input_store: &CentralInputStore, gamepad: Entity) -> Option<f32> {
        let negative = self.negative.value(input_store, gamepad);
        let positive = self.positive.value(input_store, gamepad);
        let value = positive - negative;
        Some(
            self.processors
                .iter()
                .fold(value, |value, processor| processor.process(value)),
        )
    }

    /// Sets the value of corresponding button based on the given `value`.
    ///
    /// When `value` is non-zero, set its absolute value to the value of:
    /// - the negative button if the `value` is negative;
    /// - the positive button if the `value` is positive.
    fn set_value_as_gamepad(&self, world: &mut World, value: f32, gamepad: Option<Entity>) {
        if value < 0.0 {
            self.negative
                .set_value_as_gamepad(world, value.abs(), gamepad);
        } else if value > 0.0 {
            self.positive.set_value_as_gamepad(world, value, gamepad);
        }
    }
}

impl WithAxisProcessingPipelineExt for VirtualAxis {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processors: impl IntoIterator<Item = AxisProcessor>,
    ) -> Self {
        self.processors = processors.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<AxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// A virtual dual-axis control constructed from four [`Buttonlike`]s.
/// Each button represents a specific direction (up, down, left, right),
/// functioning similarly to a directional pad (D-pad) on both X and Y axes,
/// and offering intermediate diagonals by means of two-button combinations.
///
/// By default, it reads from **any connected gamepad**.
/// Use the [`InputMap::set_gamepad`](crate::input_map::InputMap::set_gamepad) for specific ones.
///
/// # Value Processing
///
/// You can customize how the values are processed using a pipeline of processors.
/// See [`WithDualAxisProcessingPipelineExt`] for details.
///
/// The raw axis values are determined based on the state of the associated buttons:
/// - `-1.0` if only the negative button is currently pressed (Down/Left).
/// - `1.0` if only the positive button is currently pressed (Up/Right).
/// - `0.0` if neither button is pressed, or both are pressed simultaneously.
///
/// ```rust
/// use bevy::prelude::*;
/// use bevy::input::InputPlugin;
/// use leafwing_input_manager::user_input::testing_utils::FetchUserInput;
/// use leafwing_input_manager::prelude::*;
/// use leafwing_input_manager::plugin::CentralInputStorePlugin;
///
/// let mut app = App::new();
/// app.add_plugins((InputPlugin, CentralInputStorePlugin));
///
/// // Define a virtual D-pad using the WASD keys
/// let input = VirtualDPad::wasd();
///
/// // Pressing the W key activates the corresponding axis
/// KeyCode::KeyW.press(app.world_mut());
/// app.update();
/// assert_eq!(app.read_dual_axis_values(input), Vec2::new(0.0, 1.0));
///
/// // You can configure a processing pipeline (e.g., doubling the Y value)
/// let doubled = VirtualDPad::wasd().sensitivity_y(2.0);
/// assert_eq!(app.read_dual_axis_values(doubled), Vec2::new(0.0, 2.0));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct VirtualDPad {
    /// The button for the upward direction.
    pub up: Box<dyn Buttonlike>,

    /// The button for the downward direction.
    pub down: Box<dyn Buttonlike>,

    /// The button for the leftward direction.
    pub left: Box<dyn Buttonlike>,

    /// The button for the rightward direction.
    pub right: Box<dyn Buttonlike>,

    /// A processing pipeline that handles input values.
    pub processors: Vec<DualAxisProcessor>,
}

impl VirtualDPad {
    /// Creates a new [`VirtualDPad`] with four given [`Buttonlike`]s.
    /// Each button represents a specific direction (up, down, left, right).
    #[inline]
    pub fn new(
        up: impl Buttonlike,
        down: impl Buttonlike,
        left: impl Buttonlike,
        right: impl Buttonlike,
    ) -> Self {
        Self {
            up: Box::new(up),
            down: Box::new(down),
            left: Box::new(left),
            right: Box::new(right),
            processors: Vec::new(),
        }
    }

    /// The [`VirtualDPad`] using the common arrow key mappings.
    ///
    /// - [`KeyCode::ArrowUp`] for upward direction.
    /// - [`KeyCode::ArrowDown`] for downward direction.
    /// - [`KeyCode::ArrowLeft`] for leftward direction.
    /// - [`KeyCode::ArrowRight`] for rightward direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn arrow_keys() -> Self {
        Self::new(
            KeyCode::ArrowUp,
            KeyCode::ArrowDown,
            KeyCode::ArrowLeft,
            KeyCode::ArrowRight,
        )
    }

    /// The [`VirtualDPad`] using the common WASD key mappings.
    ///
    /// - [`KeyCode::KeyW`] for upward direction.
    /// - [`KeyCode::KeyS`] for downward direction.
    /// - [`KeyCode::KeyA`] for leftward direction.
    /// - [`KeyCode::KeyD`] for rightward direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn wasd() -> Self {
        Self::new(KeyCode::KeyW, KeyCode::KeyS, KeyCode::KeyA, KeyCode::KeyD)
    }

    /// The [`VirtualDPad`] using the common numpad key mappings.
    ///
    /// - [`KeyCode::Numpad8`] for upward direction.
    /// - [`KeyCode::Numpad2`] for downward direction.
    /// - [`KeyCode::Numpad4`] for leftward direction.
    /// - [`KeyCode::Numpad6`] for rightward direction.
    #[cfg(feature = "keyboard")]
    #[inline]
    pub fn numpad() -> Self {
        Self::new(
            KeyCode::Numpad8,
            KeyCode::Numpad2,
            KeyCode::Numpad4,
            KeyCode::Numpad6,
        )
    }

    /// Creates a new [`VirtualDPad`] using the common D-Pad button mappings.
    ///
    /// - [`GamepadButton::DPadUp`] for upward direction.
    /// - [`GamepadButton::DPadDown`] for downward direction.
    /// - [`GamepadButton::DPadLeft`] for leftward direction.
    /// - [`GamepadButton::DPadRight`] for rightward direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn dpad() -> Self {
        Self::new(
            GamepadButton::DPadUp,
            GamepadButton::DPadDown,
            GamepadButton::DPadLeft,
            GamepadButton::DPadRight,
        )
    }

    /// Creates a new [`VirtualDPad`] using the common action pad button mappings.
    ///
    /// - [`GamepadButton::North`] for upward direction.
    /// - [`GamepadButton::South`] for downward direction.
    /// - [`GamepadButton::West`] for leftward direction.
    /// - [`GamepadButton::East`] for rightward direction.
    #[cfg(feature = "gamepad")]
    #[inline]
    pub fn action_pad() -> Self {
        Self::new(
            GamepadButton::North,
            GamepadButton::South,
            GamepadButton::West,
            GamepadButton::East,
        )
    }
}

impl UserInput for VirtualDPad {
    /// [`VirtualDPad`] acts as a dual-axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::DualAxis
    }

    /// Returns the four [`GamepadButton`]s used by this D-pad.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            self.up.clone(),
            self.down.clone(),
            self.left.clone(),
            self.right.clone(),
        ])
    }
}

#[serde_typetag]
impl DualAxislike for VirtualDPad {
    /// Retrieves the current X and Y values of this D-pad after processing by the associated processors.
    #[inline]
    fn get_axis_pair(&self, input_store: &CentralInputStore, gamepad: Entity) -> Option<Vec2> {
        let up = self.up.get_value(input_store, gamepad);
        let down = self.down.get_value(input_store, gamepad);
        let left = self.left.get_value(input_store, gamepad);
        let right = self.right.get_value(input_store, gamepad);

        if up.is_none() && down.is_none() && left.is_none() && right.is_none() {
            return None;
        }

        let up = up.unwrap_or(0.0);
        let down = down.unwrap_or(0.0);
        let left = left.unwrap_or(0.0);
        let right = right.unwrap_or(0.0);

        let value = Vec2::new(right - left, up - down);
        Some(
            self.processors
                .iter()
                .fold(value, |value, processor| processor.process(value)),
        )
    }

    /// Sets the value of corresponding button on each axis based on the given `value`.
    ///
    /// When `value` along an axis is non-zero, set its absolute value to the value of:
    /// - the negative button of the axis if the `value` is negative;
    /// - the positive button of the axis if the `value` is positive.
    fn set_axis_pair_as_gamepad(&self, world: &mut World, value: Vec2, gamepad: Option<Entity>) {
        let Vec2 { x, y } = value;

        if x < 0.0 {
            self.left.set_value_as_gamepad(world, x.abs(), gamepad);
        } else if x > 0.0 {
            self.right.set_value_as_gamepad(world, x, gamepad);
        }

        if y < 0.0 {
            self.down.set_value_as_gamepad(world, y.abs(), gamepad);
        } else if y > 0.0 {
            self.up.set_value_as_gamepad(world, y, gamepad);
        }
    }
}

impl WithDualAxisProcessingPipelineExt for VirtualDPad {
    #[inline]
    fn reset_processing_pipeline(mut self) -> Self {
        self.processors.clear();
        self
    }

    #[inline]
    fn replace_processing_pipeline(
        mut self,
        processor: impl IntoIterator<Item = DualAxisProcessor>,
    ) -> Self {
        self.processors = processor.into_iter().collect();
        self
    }

    #[inline]
    fn with_processor(mut self, processor: impl Into<DualAxisProcessor>) -> Self {
        self.processors.push(processor.into());
        self
    }
}

/// A virtual triple-axis control constructed from six [`Buttonlike`]s.
/// Each button represents a specific direction (up, down, left, right, forward, backward),
/// functioning similarly to a three-dimensional directional pad (D-pad) on all X, Y, and Z axes,
/// and offering intermediate diagonals by means of two/three-key combinations.
///
/// The raw axis values are determined based on the state of the associated buttons:
/// - `-1.0` if only the negative button is currently pressed (Down/Left/Forward).
/// - `1.0` if only the positive button is currently pressed (Up/Right/Backward).
/// - `0.0` if neither button is pressed, or both are pressed simultaneously.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Reflect, Serialize, Deserialize)]
#[must_use]
pub struct VirtualDPad3D {
    /// The button for the upward direction.
    pub up: Box<dyn Buttonlike>,

    /// The button for the downward direction.
    pub down: Box<dyn Buttonlike>,

    /// The button for the leftward direction.
    pub left: Box<dyn Buttonlike>,

    /// The button for the rightward direction.
    pub right: Box<dyn Buttonlike>,

    /// The button for the forward direction.
    pub forward: Box<dyn Buttonlike>,

    /// The button for the backward direction.
    pub backward: Box<dyn Buttonlike>,
}

impl VirtualDPad3D {
    /// Creates a new [`VirtualDPad3D`] with six given [`Buttonlike`]s.
    /// Each button represents a specific direction (up, down, left, right, forward, backward).
    #[inline]
    pub fn new(
        up: impl Buttonlike,
        down: impl Buttonlike,
        left: impl Buttonlike,
        right: impl Buttonlike,
        forward: impl Buttonlike,
        backward: impl Buttonlike,
    ) -> Self {
        Self {
            up: Box::new(up),
            down: Box::new(down),
            left: Box::new(left),
            right: Box::new(right),
            forward: Box::new(forward),
            backward: Box::new(backward),
        }
    }
}

impl UserInput for VirtualDPad3D {
    /// [`VirtualDPad3D`] acts as a virtual triple-axis input.
    #[inline]
    fn kind(&self) -> InputControlKind {
        InputControlKind::TripleAxis
    }

    /// [`VirtualDPad3D`] represents a compositions of six [`Buttonlike`]s.
    #[inline]
    fn decompose(&self) -> BasicInputs {
        BasicInputs::Composite(vec![
            self.up.clone(),
            self.down.clone(),
            self.left.clone(),
            self.right.clone(),
            self.forward.clone(),
            self.backward.clone(),
        ])
    }
}

#[serde_typetag]
impl TripleAxislike for VirtualDPad3D {
    /// Retrieves the current X, Y, and Z values of this D-pad.
    #[inline]
    fn get_axis_triple(&self, input_store: &CentralInputStore, gamepad: Entity) -> Option<Vec3> {
        let up = self.up.get_value(input_store, gamepad);
        let down = self.down.get_value(input_store, gamepad);
        let left = self.left.get_value(input_store, gamepad);
        let right = self.right.get_value(input_store, gamepad);
        let forward = self.forward.get_value(input_store, gamepad);
        let backward = self.backward.get_value(input_store, gamepad);

        if up.is_none()
            && down.is_none()
            && left.is_none()
            && right.is_none()
            && forward.is_none()
            && backward.is_none()
        {
            return None;
        }

        let up = up.unwrap_or(0.0);
        let down = down.unwrap_or(0.0);
        let left = left.unwrap_or(0.0);
        let right = right.unwrap_or(0.0);
        let forward = forward.unwrap_or(0.0);
        let backward = backward.unwrap_or(0.0);

        Some(Vec3::new(right - left, up - down, backward - forward))
    }

    /// Sets the value of corresponding button on each axis based on the given `value`.
    ///
    /// When `value` along an axis is non-zero, set its absolute value to the value of:
    /// - the negative button of the axis if the `value` is negative;
    /// - the positive button of the axis if the `value` is positive.
    fn set_axis_triple_as_gamepad(&self, world: &mut World, value: Vec3, gamepad: Option<Entity>) {
        let Vec3 { x, y, z } = value;

        if x < 0.0 {
            self.left.set_value_as_gamepad(world, x.abs(), gamepad);
        } else if x > 0.0 {
            self.right.set_value_as_gamepad(world, x, gamepad);
        }

        if y < 0.0 {
            self.down.set_value_as_gamepad(world, y.abs(), gamepad);
        } else if y > 0.0 {
            self.up.set_value_as_gamepad(world, y, gamepad);
        }

        if z < 0.0 {
            self.forward.set_value_as_gamepad(world, z.abs(), gamepad);
        } else if z > 0.0 {
            self.backward.set_value_as_gamepad(world, z, gamepad);
        }
    }
}

#[cfg(feature = "keyboard")]
#[cfg(test)]
mod tests {
    use bevy::input::InputPlugin;
    use bevy::prelude::*;

    use crate::plugin::CentralInputStorePlugin;
    use crate::prelude::updating::CentralInputStore;
    use crate::prelude::*;

    fn test_app() -> App {
        let mut app = App::new();
        app.add_plugins(InputPlugin)
            .add_plugins(CentralInputStorePlugin);
        app
    }

    #[test]
    fn test_virtual() {
        let x = VirtualAxis::horizontal_arrow_keys();
        let xy = VirtualDPad::arrow_keys();
        let xyz = VirtualDPad3D::new(
            KeyCode::ArrowUp,
            KeyCode::ArrowDown,
            KeyCode::ArrowLeft,
            KeyCode::ArrowRight,
            KeyCode::KeyF,
            KeyCode::KeyB,
        );

        // No inputs
        let mut app = test_app();
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        let gamepad = Entity::PLACEHOLDER;

        assert_eq!(x.value(inputs, gamepad), 0.0);
        assert_eq!(xy.axis_pair(inputs, gamepad), Vec2::ZERO);
        assert_eq!(xyz.axis_triple(inputs, gamepad), Vec3::ZERO);

        // Press arrow left
        let mut app = test_app();
        KeyCode::ArrowLeft.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert_eq!(x.value(inputs, gamepad), -1.0);
        assert_eq!(xy.axis_pair(inputs, gamepad), Vec2::new(-1.0, 0.0));
        assert_eq!(xyz.axis_triple(inputs, gamepad), Vec3::new(-1.0, 0.0, 0.0));

        // Press arrow up
        let mut app = test_app();
        KeyCode::ArrowUp.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert_eq!(x.value(inputs, gamepad), 0.0);
        assert_eq!(xy.axis_pair(inputs, gamepad), Vec2::new(0.0, 1.0));
        assert_eq!(xyz.axis_triple(inputs, gamepad), Vec3::new(0.0, 1.0, 0.0));

        // Press arrow right
        let mut app = test_app();
        KeyCode::ArrowRight.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert_eq!(x.value(inputs, gamepad), 1.0);
        assert_eq!(xy.axis_pair(inputs, gamepad), Vec2::new(1.0, 0.0));
        assert_eq!(xyz.axis_triple(inputs, gamepad), Vec3::new(1.0, 0.0, 0.0));

        // Press key B
        let mut app = test_app();
        KeyCode::KeyB.press(app.world_mut());
        app.update();
        let inputs = app.world().resource::<CentralInputStore>();

        assert_eq!(x.value(inputs, gamepad), 0.0);
        assert_eq!(xy.axis_pair(inputs, gamepad), Vec2::new(0.0, 0.0));
        assert_eq!(xyz.axis_triple(inputs, gamepad), Vec3::new(0.0, 0.0, 1.0));
    }
}