bevy_picking_state_machine 0.4.0

A global state machine for working with `bevy_picking`.
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
#![doc = include_str!("../README.md")]
#![allow(clippy::collapsible_if)]
#![allow(clippy::too_many_arguments)]
use core::f32;
use std::cmp::Reverse;
mod local;
pub mod propagation;
mod transitions;
pub use local::{ButtonFilter, PickPriority};
pub use transitions::PickingTransition;

use bevy::{
    app::{Plugin, PreUpdate},
    ecs::{
        entity::Entity,
        message::MessageReader,
        query::With,
        resource::Resource,
        schedule::IntoScheduleConfigs,
        system::{In, IntoSystem, Query, Res, ResMut},
    },
    input::{
        ButtonInput,
        mouse::{MouseButton, MouseMotion},
    },
    math::Vec2,
    picking::{PickingSystems, backend::PointerHits},
    time::{Time, Virtual},
    window::{PrimaryWindow, Window},
};

/// Plugin for [`PickingStateMachine`].
#[derive(Debug, Clone, Resource)]
pub struct PickingStateMachinePlugin {
    /// Only buttons in this list will be considered.
    ///
    /// By default we only consider the left mouse button.
    pub allowed_buttons: Vec<MouseButton>,
    /// If true, pressing multiple buttons will immediately cancel `Hover` to `None`.
    pub cancel_hover: bool,
}

impl Default for PickingStateMachinePlugin {
    fn default() -> Self {
        Self {
            allowed_buttons: vec![MouseButton::Left],
            cancel_hover: false,
        }
    }
}

impl Plugin for PickingStateMachinePlugin {
    fn build(&self, app: &mut bevy::app::App) {
        app.insert_resource(self.clone());
        app.init_resource::<PickingStateMachine>();
        app.add_systems(
            PreUpdate,
            picking_window_system
                .pipe(picking_button_system)
                .pipe(picking_state_machine_system)
                .in_set(PickingSystems::Hover),
        );
    }
}

/// Picking state of an entity.
#[derive(Debug, Clone, Copy, Default)]
pub enum EntityPickingState {
    #[default]
    None,
    Hover,
    Pressed,
}

/// Picking state globally.
#[derive(Debug, Clone, Copy, Default)]
pub enum GlobalPickingState {
    #[default]
    None,
    Hover {
        entity: Entity,
    },
    Pressed {
        entity: Entity,
    },
}

impl GlobalPickingState {
    pub fn current_entity(&self) -> Option<Entity> {
        match self {
            GlobalPickingState::None => None,
            GlobalPickingState::Hover { entity } => Some(*entity),
            GlobalPickingState::Pressed { entity } => Some(*entity),
        }
    }
}

/// State for a button press.
#[derive(Debug, Clone, Copy)]
pub struct PressState {
    pub button: MouseButton,
    pub position: Vec2,
    pub time: f32,
}

/// Determines who owns the cursor.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum CursorOwner {
    /// Represents curser is being controlled by the mouse.
    #[default]
    Mouse,
    /// Represents curser is being controlled by something other than the mouse.
    Keyboard,
}

/// Global state machine for `bevy_picking`.
#[derive(Debug, Clone, Default, Resource)]
#[non_exhaustive]
pub struct PickingStateMachine {
    /// State of the previous frame.
    pub previous: GlobalPickingState,
    /// State of the current frame.
    pub current: GlobalPickingState,
    /// Pointer position.
    pub pointer: Vec2,
    /// If mouse is pressed, contains position, button and time of the button press.
    ///
    /// # Note
    ///
    /// This will not be present on button release, use `transitions` instead.
    pub press: Option<PressState>,
    /// If true, current button is just pressed.
    pub current_btn_just_pressed: bool,
    /// If true, [`PickingStateMachine::pointer`]
    /// is not retrieved from the current frame.
    pub pointer_is_out_of_bounds: bool,
    /// True if multiple valid buttons are pressed as the same time.
    /// Lasts until all valid buttons are released.
    pub is_post_cancellation_state: bool,
    /// An internal event channel for picking events.
    ///
    /// Use `as_ref` or `iter` to access items.
    pub transitions: Vec<PickingTransition>,
    /// Determines who owns the cursor.
    ///
    /// The user can manually set this value to [`CursorOwner::Keyboard`].
    /// If [`CursorOwner::Keyboard`] is active, a portion of
    /// the state machine is user controlled, until the mouse moves and triggers
    /// either hover or click, in which case reverts back to [`CursorOwner::Mouse`].
    pub owner: CursorOwner,
    /// Cached elapsed seconds.
    pub now: f32,
}

impl PickingStateMachine {
    /// Returns the current state on an entity.
    ///
    /// # Note
    ///
    /// * At most one entity have state other than [`EntityPickingState::None`] at a given frame.
    /// * Does not require the entity to exist.
    pub fn get_state(&self, entity: Entity) -> EntityPickingState {
        match self.current {
            GlobalPickingState::None => EntityPickingState::None,
            GlobalPickingState::Hover { entity: e } => {
                if entity == e {
                    EntityPickingState::Hover
                } else {
                    EntityPickingState::None
                }
            }
            GlobalPickingState::Pressed { entity: e } => {
                if entity == e {
                    EntityPickingState::Hover
                } else {
                    EntityPickingState::None
                }
            }
        }
    }

    /// Returns the current state on the active entity.
    pub fn active_state(&self) -> EntityPickingState {
        match self.current {
            GlobalPickingState::None => EntityPickingState::None,
            GlobalPickingState::Hover { .. } => EntityPickingState::Hover,
            GlobalPickingState::Pressed { .. } => EntityPickingState::Pressed,
        }
    }

    /// Returns the current state transition events on an entity.
    pub fn iter_transitions(&self) -> impl Iterator<Item = PickingTransition> {
        self.transitions.iter().copied()
    }

    /// Returns the current state transition events on an entity.
    pub fn get_transitions(&self, entity: Entity) -> impl Iterator<Item = PickingTransition> {
        self.transitions
            .iter()
            .copied()
            .filter(move |x| x.entity() == entity)
    }

    /// Returns the active entity that is being hovered or pressed.
    pub fn get_active_entity(&self) -> Option<Entity> {
        self.current.current_entity()
    }

    /// Returns the active entity that is being hovered or pressed,
    /// if the active entity has changed.
    pub fn get_active_entity_if_changed(&self) -> Option<Entity> {
        if self.active_entity_changed() {
            self.get_active_entity()
        } else {
            None
        }
    }

    /// Returns the previous active entity that was hovered or pressed,
    /// if the active entity has changed.
    pub fn get_previous_entity_if_changed(&self) -> Option<Entity> {
        if self.active_entity_changed() {
            self.previous.current_entity()
        } else {
            None
        }
    }

    /// Returns true if the active entity has changed.
    pub fn active_entity_changed(&self) -> bool {
        self.previous.current_entity() != self.current.current_entity()
    }

    /// Returns true if something is hovered and no recognized button is being pressed.
    pub fn is_hovering(&self) -> bool {
        matches!(self.current, GlobalPickingState::Hover { .. })
    }

    /// Returns true if a recognized button is pressed and not in cancellation state.
    pub fn is_pressing(&self) -> bool {
        matches!(self.current, GlobalPickingState::Pressed { .. })
    }

    /// Returns true if in cancellation state.
    pub fn is_cancelled(&self) -> bool {
        self.is_post_cancellation_state
    }

    /// We allow acquiring new target if
    /// * Not post-cancellation state.
    /// * Not pressed or just pressed.
    fn can_acquire_new_target(&self) -> bool {
        !self.is_post_cancellation_state && (self.press.is_none() || self.current_btn_just_pressed)
    }

    /// Hover over an entity with a non-mouse action.
    pub fn keyboard_hover(&mut self, entity: Entity) {
        self.owner = CursorOwner::Keyboard;
        self.current = GlobalPickingState::Hover { entity };
    }

    /// Exit hover over an entity with a non-mouse action.
    pub fn keyboard_hover_exit(&mut self) {
        self.owner = CursorOwner::Keyboard;
        self.current = GlobalPickingState::None;
    }

    /// Press the active entity with a non-mouse action.
    pub fn keyboard_press(&mut self) {
        self.owner = CursorOwner::Keyboard;
        if let GlobalPickingState::Hover { entity } = self.current {
            self.current = GlobalPickingState::Pressed { entity };
            self.press = Some(PressState {
                button: MouseButton::Other(u16::MAX),
                position: Vec2::ZERO,
                time: self.now,
            })
        }
    }

    /// Release the active entity with a non-mouse action.
    pub fn keyboard_release(&mut self) {
        self.owner = CursorOwner::Keyboard;
        if let GlobalPickingState::Pressed { entity } = self.current {
            self.current = GlobalPickingState::Hover { entity };
            self.press = None
        }
    }
}

fn picking_window_system(
    mut state_machine: ResMut<PickingStateMachine>,
    window: Query<&Window, With<PrimaryWindow>>,
) {
    let mouse_position = match window.single() {
        Ok(window) => window.cursor_position(),
        Err(_) => None,
    };
    match mouse_position {
        Some(position) => {
            state_machine.pointer = position;
            state_machine.pointer_is_out_of_bounds = false;
        }
        None => {
            state_machine.pointer_is_out_of_bounds = true;
        }
    }
}

fn picking_button_system(
    time: Res<Time<Virtual>>,
    mut state_machine: ResMut<PickingStateMachine>,
    settings: Res<PickingStateMachinePlugin>,
    input: Res<ButtonInput<MouseButton>>,
    mut mouse_movements: MessageReader<MouseMotion>,
) -> bool {
    let mut current_button = None;
    let mut cancel = false;
    let mut just_pressed = false;
    let time = time.elapsed_secs();
    state_machine.now = time;
    for button in &settings.allowed_buttons {
        if input.pressed(*button) {
            if input.just_pressed(*button) {
                just_pressed = true;
            }
            if current_button.is_none() {
                current_button = Some(*button)
            } else {
                current_button = None;
                cancel = true;
                break;
            }
        }
    }
    if just_pressed || mouse_movements.read().count() > 0 {
        state_machine.owner = CursorOwner::Mouse;
    }
    // To make state transitions less weird,
    // if you release one button and press another in the same frame,
    // treat it as entering cancellation state,
    // this ensures one event per frame.
    if let Some(press) = state_machine.press {
        if current_button.is_some_and(|b| b != press.button) {
            cancel = true;
        }
    }
    state_machine.current_btn_just_pressed = false;
    if cancel {
        state_machine.is_post_cancellation_state = true;
    } else if state_machine.is_post_cancellation_state && current_button.is_none() {
        state_machine.is_post_cancellation_state = false;
    } else if just_pressed {
        state_machine.current_btn_just_pressed = true;
    }
    // We need to keep this for events so deletion is delayed.
    if let Some(button) = current_button {
        state_machine.press = Some(PressState {
            button,
            position: state_machine.pointer,
            time,
        });
    }
    current_button.is_some()
}

fn picking_state_machine_system(
    pressed: In<bool>,
    time: Res<Time<Virtual>>,
    settings: Res<PickingStateMachinePlugin>,
    mut pick: MessageReader<PointerHits>,
    mut state_machine: ResMut<PickingStateMachine>,
    filters: Query<&ButtonFilter>,
    priorities: Query<&PickPriority>,
) {
    // This is fine since this will be reset if the cursor moved or a button is pressed.
    if state_machine.owner == CursorOwner::Keyboard {
        return;
    }
    let pressed = *pressed;
    let time = time.elapsed_secs();
    let mut min = (f32::NEG_INFINITY, Reverse(f32::INFINITY));
    let mut target = None;
    let current = match state_machine.current {
        GlobalPickingState::None => None,
        GlobalPickingState::Hover { .. } => None,
        GlobalPickingState::Pressed { entity } => Some(entity),
    };
    let can_acquire = state_machine.can_acquire_new_target();
    'main: for hits in pick.read() {
        for (entity, hit) in &hits.picks {
            if Some(*entity) == current {
                target = current;
                break 'main;
            }
            if !can_acquire {
                continue;
            }
            let priority = if let Ok(priority) = priorities.get(*entity) {
                (
                    hits.order + priority.order,
                    Reverse(hit.depth - priority.distance),
                )
            } else {
                (hits.order, Reverse(hit.depth))
            };
            if priority > min {
                min = priority;
                target = Some(*entity);
            }
        }
    }
    state_machine.previous = state_machine.current;
    match target {
        None => {
            if pressed && !state_machine.current_btn_just_pressed {
                match state_machine.current {
                    GlobalPickingState::Pressed { .. } => (),
                    _ => state_machine.current = GlobalPickingState::None,
                }
            } else {
                state_machine.current = GlobalPickingState::None;
            }
        }
        Some(entity) if state_machine.is_post_cancellation_state => {
            match state_machine.current {
                // If hovering, maintain it, otherwise cancel to base state.
                GlobalPickingState::Hover { entity: e }
                    if e == entity && !settings.cancel_hover =>
                {
                    state_machine.current = GlobalPickingState::Hover { entity };
                }
                _ => {
                    state_machine.current = GlobalPickingState::None;
                }
            }
        }
        Some(entity) if !pressed => state_machine.current = GlobalPickingState::Hover { entity },
        Some(entity) => {
            let filter = if let Ok(filter) = filters.get(entity) {
                filter.contains(state_machine.press.unwrap().button)
            } else {
                true
            };
            if filter {
                state_machine.current = GlobalPickingState::Pressed { entity }
            } else {
                state_machine.current = GlobalPickingState::Hover { entity }
            }
        }
    }
    state_machine.queue_transitions(time);
    if !pressed {
        state_machine.press = None;
    }
}