InputMap

Struct InputMap 

Source
pub struct InputMap<F: Hash + Copy> {
    pub mouse_pos: (f32, f32),
    pub recently_pressed: Option<InputCode>,
    pub text_typed: Option<String>,
    pub mouse_scale: f32,
    pub scroll_scale: f32,
    pub press_sensitivity: f32,
    /* private fields */
}
Expand description

A struct that handles all your input needs once you’ve hooked it up to winit and gilrs.

use gilrs::Gilrs;
use winit::{event::*, application::*, window::*, event_loop::*};
use winit_input_map::*;
struct App {
    window: Option<Window>,
    input: InputMap<()>,
    gilrs: Gilrs
}
impl ApplicationHandler for App {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        self.window = Some(event_loop.create_window(Window::default_attributes()).unwrap());
    }
    fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
        self.input.update_with_window_event(&event);
        if let WindowEvent::CloseRequested = &event { event_loop.exit() }
    }
    fn device_event(&mut self, _: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
        self.input.update_with_device_event(id, &event);
    }
    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
        self.input.update_with_gilrs(&mut self.gilrs);
 
        // put your code here

        self.input.init();
    }
}

Fields§

§mouse_pos: (f32, f32)

The mouse position

§recently_pressed: Option<InputCode>

The last input event, even if it isn’t in the binds. Useful for handling rebinding

§text_typed: Option<String>

The text typed this loop

§mouse_scale: f32

Since most values are from 0-1 reducing the mouse sensitivity will result in better consistancy

§scroll_scale: f32

Since most values are from 0-1 reducing the scroll sensitivity will result in better consistancy

§press_sensitivity: f32

The minimum value something has to be at to count as being pressed. Values over 1 will result in most buttons being unusable

Implementations§

Source§

impl InputMap<()>

Source

pub fn empty() -> Self

Use if you dont want to have any actions and binds. Will still have access to everything else.

Source§

impl<F: Hash + Copy + Eq> InputMap<F>

Source

pub fn new(binds: &Binds<F>) -> Self

Creates a new input system. Takes the action and a list of its associated binds. An action will count as being pressed if any of the binds are pressed. A bind is a list of InputCodes that need to all be pressed for the bind to count as being pressed.

It’s recommended to use the input_map! macro to reduce boilerplate and increase readability.

use Action::*;
use winit_input_map::*;
use winit::keyboard::KeyCode;
#[derive(Hash, PartialEq, Eq, Clone, Copy)]
enum Action {
    Forward,
    Back,
    Pos,
    Neg
}
// doesnt have to be the same ordered as the enum.
let input = InputMap::new(&vec![
    (Forward, vec![ vec![KeyCode::KeyW.into()] ]),
    (Pos,     vec![ vec![KeyCode::KeyA.into()] ]),
    (Back,    vec![ vec![KeyCode::KeyS.into()] ]),
    (Neg,     vec![ vec![KeyCode::KeyD.into()] ])
]);
Source

pub fn add_binds(&mut self, binds: &Binds<F>)

Takes binds and adds them to the currently existing map. The binds!() macro will help reduce the boiler_plate of this function.

Source

pub fn set_binds(&mut self, binds: &Binds<F>)

Removes all binds and then adds the inputed binds. The binds!() macro will help reduce the boiler_plate of this function.

Source

pub fn get_binds(&self) -> Binds<F>

Returns the current binds of the InputMap, may not be in the same order as the inputed binds.

Examples found in repository?
examples/example.rs (line 62)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn update_with_winit(&mut self, event: &Event<()>)

👎Deprecated: use update_with_window_event and update_with_device_event

Updates the input map using a winit event. Make sure to call input.init() when your done with the input this loop.

use winit::{event::*, window::WindowAttributes, event_loop::EventLoop};
use winit_input_map::*;

let mut event_loop = EventLoop::new().unwrap();
event_loop.set_control_flow(winit::event_loop::ControlFlow::Poll);
let _window = event_loop.create_window(WindowAttributes::default()).unwrap();

let mut input = input_map!();

event_loop.run(|event, target|{
    input.update_with_winit(&event);
    match &event{
        Event::WindowEvent { event: WindowEvent::CloseRequested, .. } => target.exit(),
        Event::AboutToWait => input.init(),
        _ => ()
    }
});
Source

pub fn update_with_device_event(&mut self, id: DeviceId, event: &DeviceEvent)

Examples found in repository?
examples/minimum.rs (line 21)
20    fn device_event(&mut self, _: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
21        self.input.update_with_device_event(id, &event);
22    }
More examples
Hide additional examples
examples/typing.rs (line 26)
25    fn device_event(&mut self, _: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) {
26        self.input.update_with_device_event(id, &event);
27    }
examples/example.rs (line 53)
50    fn device_event(
51        &mut self, _: &ActiveEventLoop, id: DeviceId, event: DeviceEvent
52    ) {
53        self.input.update_with_device_event(id, &event);
54    }
Source

pub fn update_with_window_event(&mut self, event: &WindowEvent)

Examples found in repository?
examples/minimum.rs (line 17)
16    fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
17        self.input.update_with_window_event(&event);
18        if let WindowEvent::CloseRequested = &event { event_loop.exit() }
19    }
More examples
Hide additional examples
examples/typing.rs (line 22)
21    fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
22        self.input.update_with_window_event(&event);
23        if let WindowEvent::CloseRequested = &event { event_loop.exit() }
24    }
examples/example.rs (line 47)
43    fn window_event(
44        &mut self, event_loop: &ActiveEventLoop,
45        _: WindowId, event: WindowEvent
46    ) {
47        self.input.update_with_window_event(&event);
48        if let WindowEvent::CloseRequested = &event { event_loop.exit() }
49    }
Source

pub fn update_with_gilrs(&mut self, gilrs: &mut Gilrs)

Examples found in repository?
examples/minimum.rs (line 24)
23    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
24        self.input.update_with_gilrs(&mut self.gilrs);
25
26        // put your code here
27
28        self.input.init();
29    }
More examples
Hide additional examples
examples/typing.rs (line 29)
28    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
29        self.input.update_with_gilrs(&mut self.gilrs);
30
31        if self.input.pressed(Action::Return) {
32            println!("{}", self.text);
33            self.text = String::new();
34        } else if let Some(new) = &self.input.text_typed {
35            self.text.push_str(new);
36        }
37
38        self.input.init();
39    }
examples/example.rs (line 56)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn init(&mut self)

Makes the input map ready to recieve new events.

Examples found in repository?
examples/minimum.rs (line 28)
23    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
24        self.input.update_with_gilrs(&mut self.gilrs);
25
26        // put your code here
27
28        self.input.init();
29    }
More examples
Hide additional examples
examples/typing.rs (line 38)
28    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
29        self.input.update_with_gilrs(&mut self.gilrs);
30
31        if self.input.pressed(Action::Return) {
32            println!("{}", self.text);
33            self.text = String::new();
34        } else if let Some(new) = &self.input.text_typed {
35            self.text.push_str(new);
36        }
37
38        self.input.init();
39    }
examples/example.rs (line 87)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn pressing(&self, action: F) -> bool

Checks if action is being pressed currently based on the press_sensitivity. same as self.value(action) >= self.press_sensitivty.

Examples found in repository?
examples/example.rs (line 64)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn value(&self, action: F) -> f32

Checks how much an action is being pressed. May be higher than 1 in the case of scroll wheels, mouse movement or when multiple binds are bound to an action.

Source

pub fn pressed(&self, action: F) -> bool

Checks if action was just pressed.

Examples found in repository?
examples/typing.rs (line 31)
28    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
29        self.input.update_with_gilrs(&mut self.gilrs);
30
31        if self.input.pressed(Action::Return) {
32            println!("{}", self.text);
33            self.text = String::new();
34        } else if let Some(new) = &self.input.text_typed {
35            self.text.push_str(new);
36        }
37
38        self.input.init();
39    }
More examples
Hide additional examples
examples/example.rs (line 61)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn released(&self, action: F) -> bool

Checks if action was just released.

Examples found in repository?
examples/example.rs (line 75)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn axis(&self, pos: F, neg: F) -> f32

Returns f32 based on how much pos and neg are pressed. may return values higher than 1.0 in the case of mouse movement and scrolling. usefull for movement controls. for 2d values see dir and dir_max_len_1

let move_dir = input.axis(Neg, Pos);

same as input.value(pos) - input.value(neg)

Examples found in repository?
examples/example.rs (line 59)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn dir(&self, pos_x: F, neg_x: F, pos_y: F, neg_y: F) -> (f32, f32)

Returns a vector based off of the x and y axis. Can return values with a length higher than 1, if this is undesirable see dir_max_len_1.

Examples found in repository?
examples/example.rs (line 68)
55    fn about_to_wait(&mut self, _: &ActiveEventLoop) {
56        self.input.update_with_gilrs(&mut self.gilrs);
57
58        let input = &mut self.input;
59        let scroll = input.axis(ScrollU, ScrollD);
60    
61        if input.pressed(Debug) {
62            println!("pressed {:?}", input.get_binds().into_iter().find(|&(a, _)| a == Debug).map(|(_, v)| v))
63        }
64        if input.pressing(Right) || input.pressing(Left) {
65            println!("axis: {}", input.axis(Right, Left))
66        }
67
68        let mouse_move = input.dir(MouseL, MouseR, MouseU, MouseD);
69        if mouse_move != (0.0, 0.0) {
70            println!(
71                "mouse moved: {:?} and is now at {:?}",
72                mouse_move, input.mouse_pos
73            )
74        }
75        if input.released(Click) { println!("released") }
76
77        if input.pressed(Undo) { println!("Undone") }
78
79        if scroll != 0.0 {
80            println!("scrolling {}", scroll);
81        }
82        if let Some(other) = input.recently_pressed {
83            println!("{other:?}");
84        }
85        std::thread::sleep(std::time::Duration::from_millis(100));
86        // reset input. use after your done with the input
87        input.init();
88    }
Source

pub fn dir_max_len_1( &self, pos_x: F, neg_x: F, pos_y: F, neg_y: F, ) -> (f32, f32)

Returns a vector based off of x and y axis with a maximum length of 1 (the same as a normalised vector). If this undesirable see dir.

Trait Implementations§

Source§

impl<F: Hash + Copy> Default for InputMap<F>

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

§

impl<F> Freeze for InputMap<F>

§

impl<F> RefUnwindSafe for InputMap<F>
where F: RefUnwindSafe,

§

impl<F> Send for InputMap<F>
where F: Send,

§

impl<F> Sync for InputMap<F>
where F: Sync,

§

impl<F> Unpin for InputMap<F>
where F: Unpin,

§

impl<F> UnwindSafe for InputMap<F>
where F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> DowncastSync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Sync + Send>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more