Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_picking/src/hover.rs
6596 views
1
//! Determines which entities are being hovered by which pointers.
2
//!
3
//! The most important type in this module is the [`HoverMap`], which maps pointers to the entities
4
//! they are hovering over.
5
6
use alloc::collections::BTreeMap;
7
use core::fmt::Debug;
8
use std::collections::HashSet;
9
10
use crate::{
11
backend::{self, HitData},
12
pointer::{PointerAction, PointerId, PointerInput, PointerInteraction, PointerPress},
13
Pickable,
14
};
15
16
use bevy_derive::{Deref, DerefMut};
17
use bevy_ecs::{entity::EntityHashSet, prelude::*};
18
use bevy_math::FloatOrd;
19
use bevy_platform::collections::HashMap;
20
use bevy_reflect::prelude::*;
21
22
type DepthSortedHits = Vec<(Entity, HitData)>;
23
24
/// Events returned from backends can be grouped with an order field. This allows picking to work
25
/// with multiple layers of rendered output to the same render target.
26
type PickLayer = FloatOrd;
27
28
/// Maps [`PickLayer`]s to the map of entities within that pick layer, sorted by depth.
29
type LayerMap = BTreeMap<PickLayer, DepthSortedHits>;
30
31
/// Maps Pointers to a [`LayerMap`]. Note this is much more complex than the [`HoverMap`] because
32
/// this data structure is used to sort entities by layer then depth for every pointer.
33
type OverMap = HashMap<PointerId, LayerMap>;
34
35
/// The source of truth for all hover state. This is used to determine what events to send, and what
36
/// state components should be in.
37
///
38
/// Maps pointers to the entities they are hovering over.
39
///
40
/// "Hovering" refers to the *hover* state, which is not the same as whether or not a picking
41
/// backend is reporting hits between a pointer and an entity. A pointer is "hovering" an entity
42
/// only if the pointer is hitting the entity (as reported by a picking backend) *and* no entities
43
/// between it and the pointer block interactions.
44
///
45
/// For example, if a pointer is hitting a UI button and a 3d mesh, but the button is in front of
46
/// the mesh, the UI button will be hovered, but the mesh will not. Unless, the [`Pickable`]
47
/// component is present with [`should_block_lower`](Pickable::should_block_lower) set to `false`.
48
///
49
/// # Advanced Users
50
///
51
/// If you want to completely replace the provided picking events or state produced by this plugin,
52
/// you can use this resource to do that. All of the event systems for picking are built *on top of*
53
/// this authoritative hover state, and you can do the same. You can also use the
54
/// [`PreviousHoverMap`] as a robust way of determining changes in hover state from the previous
55
/// update.
56
#[derive(Debug, Deref, DerefMut, Default, Resource)]
57
pub struct HoverMap(pub HashMap<PointerId, HashMap<Entity, HitData>>);
58
59
/// The previous state of the hover map, used to track changes to hover state.
60
#[derive(Debug, Deref, DerefMut, Default, Resource)]
61
pub struct PreviousHoverMap(pub HashMap<PointerId, HashMap<Entity, HitData>>);
62
63
/// Coalesces all data from inputs and backends to generate a map of the currently hovered entities.
64
/// This is the final focusing step to determine which entity the pointer is hovering over.
65
pub fn generate_hovermap(
66
// Inputs
67
pickable: Query<&Pickable>,
68
pointers: Query<&PointerId>,
69
mut under_pointer: EventReader<backend::PointerHits>,
70
mut pointer_input: EventReader<PointerInput>,
71
// Local
72
mut over_map: Local<OverMap>,
73
// Output
74
mut hover_map: ResMut<HoverMap>,
75
mut previous_hover_map: ResMut<PreviousHoverMap>,
76
) {
77
reset_maps(
78
&mut hover_map,
79
&mut previous_hover_map,
80
&mut over_map,
81
&pointers,
82
);
83
build_over_map(&mut under_pointer, &mut over_map, &mut pointer_input);
84
build_hover_map(&pointers, pickable, &over_map, &mut hover_map);
85
}
86
87
/// Clear non-empty local maps, reusing allocated memory.
88
fn reset_maps(
89
hover_map: &mut HoverMap,
90
previous_hover_map: &mut PreviousHoverMap,
91
over_map: &mut OverMap,
92
pointers: &Query<&PointerId>,
93
) {
94
// Swap the previous and current hover maps. This results in the previous values being stored in
95
// `PreviousHoverMap`. Swapping is okay because we clear the `HoverMap` which now holds stale
96
// data. This process is done without any allocations.
97
core::mem::swap(&mut previous_hover_map.0, &mut hover_map.0);
98
99
for entity_set in hover_map.values_mut() {
100
entity_set.clear();
101
}
102
for layer_map in over_map.values_mut() {
103
layer_map.clear();
104
}
105
106
// Clear pointers from the maps if they have been removed.
107
let active_pointers: Vec<PointerId> = pointers.iter().copied().collect();
108
hover_map.retain(|pointer, _| active_pointers.contains(pointer));
109
over_map.retain(|pointer, _| active_pointers.contains(pointer));
110
}
111
112
/// Build an ordered map of entities that are under each pointer
113
fn build_over_map(
114
backend_events: &mut EventReader<backend::PointerHits>,
115
pointer_over_map: &mut Local<OverMap>,
116
pointer_input: &mut EventReader<PointerInput>,
117
) {
118
let cancelled_pointers: HashSet<PointerId> = pointer_input
119
.read()
120
.filter_map(|p| {
121
if let PointerAction::Cancel = p.action {
122
Some(p.pointer_id)
123
} else {
124
None
125
}
126
})
127
.collect();
128
129
for entities_under_pointer in backend_events
130
.read()
131
.filter(|e| !cancelled_pointers.contains(&e.pointer))
132
{
133
let pointer = entities_under_pointer.pointer;
134
let layer_map = pointer_over_map.entry(pointer).or_default();
135
for (entity, pick_data) in entities_under_pointer.picks.iter() {
136
let layer = entities_under_pointer.order;
137
let hits = layer_map.entry(FloatOrd(layer)).or_default();
138
hits.push((*entity, pick_data.clone()));
139
}
140
}
141
142
for layers in pointer_over_map.values_mut() {
143
for hits in layers.values_mut() {
144
hits.sort_by_key(|(_, hit)| FloatOrd(hit.depth));
145
}
146
}
147
}
148
149
/// Build an unsorted set of hovered entities, accounting for depth, layer, and [`Pickable`]. Note
150
/// that unlike the pointer map, this uses [`Pickable`] to determine if lower entities receive hover
151
/// focus. Often, only a single entity per pointer will be hovered.
152
fn build_hover_map(
153
pointers: &Query<&PointerId>,
154
pickable: Query<&Pickable>,
155
over_map: &Local<OverMap>,
156
// Output
157
hover_map: &mut HoverMap,
158
) {
159
for pointer_id in pointers.iter() {
160
let pointer_entity_set = hover_map.entry(*pointer_id).or_default();
161
if let Some(layer_map) = over_map.get(pointer_id) {
162
// Note we reverse here to start from the highest layer first.
163
for (entity, pick_data) in layer_map.values().rev().flatten() {
164
if let Ok(pickable) = pickable.get(*entity) {
165
if pickable.is_hoverable {
166
pointer_entity_set.insert(*entity, pick_data.clone());
167
}
168
if pickable.should_block_lower {
169
break;
170
}
171
} else {
172
pointer_entity_set.insert(*entity, pick_data.clone()); // Emit events by default
173
break; // Entities block by default so we break out of the loop
174
}
175
}
176
}
177
}
178
}
179
180
/// A component that aggregates picking interaction state of this entity across all pointers.
181
///
182
/// Unlike bevy's `Interaction` component, this is an aggregate of the state of all pointers
183
/// interacting with this entity. Aggregation is done by taking the interaction with the highest
184
/// precedence.
185
///
186
/// For example, if we have an entity that is being hovered by one pointer, and pressed by another,
187
/// the entity will be considered pressed. If that entity is instead being hovered by both pointers,
188
/// it will be considered hovered.
189
#[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)]
190
#[reflect(Component, Default, PartialEq, Debug, Clone)]
191
pub enum PickingInteraction {
192
/// The entity is being pressed down by a pointer.
193
Pressed = 2,
194
/// The entity is being hovered by a pointer.
195
Hovered = 1,
196
/// No pointers are interacting with this entity.
197
#[default]
198
None = 0,
199
}
200
201
/// Uses [`HoverMap`] changes to update [`PointerInteraction`] and [`PickingInteraction`] components.
202
pub fn update_interactions(
203
// Input
204
hover_map: Res<HoverMap>,
205
previous_hover_map: Res<PreviousHoverMap>,
206
// Outputs
207
mut commands: Commands,
208
mut pointers: Query<(&PointerId, &PointerPress, &mut PointerInteraction)>,
209
mut interact: Query<&mut PickingInteraction>,
210
) {
211
// Create a map to hold the aggregated interaction for each entity. This is needed because we
212
// need to be able to insert the interaction component on entities if they do not exist. To do
213
// so we need to know the final aggregated interaction state to avoid the scenario where we set
214
// an entity to `Pressed`, then overwrite that with a lower precedent like `Hovered`.
215
let mut new_interaction_state = HashMap::<Entity, PickingInteraction>::default();
216
for (pointer, pointer_press, mut pointer_interaction) in &mut pointers {
217
if let Some(pointers_hovered_entities) = hover_map.get(pointer) {
218
// Insert a sorted list of hit entities into the pointer's interaction component.
219
let mut sorted_entities: Vec<_> = pointers_hovered_entities.clone().drain().collect();
220
sorted_entities.sort_by_key(|(_, hit)| FloatOrd(hit.depth));
221
pointer_interaction.sorted_entities = sorted_entities;
222
223
for hovered_entity in pointers_hovered_entities.iter().map(|(entity, _)| entity) {
224
merge_interaction_states(pointer_press, hovered_entity, &mut new_interaction_state);
225
}
226
}
227
}
228
229
// Take the aggregated entity states and update or insert the component if missing.
230
for (&hovered_entity, &new_interaction) in new_interaction_state.iter() {
231
if let Ok(mut interaction) = interact.get_mut(hovered_entity) {
232
interaction.set_if_neq(new_interaction);
233
} else if let Ok(mut entity_commands) = commands.get_entity(hovered_entity) {
234
entity_commands.try_insert(new_interaction);
235
}
236
}
237
238
// Clear all previous hover data from pointers that are no longer hovering any entities.
239
// We do this last to preserve change detection for picking interactions.
240
for (pointer, _, _) in &mut pointers {
241
let Some(previously_hovered_entities) = previous_hover_map.get(pointer) else {
242
continue;
243
};
244
245
for entity in previously_hovered_entities.keys() {
246
if !new_interaction_state.contains_key(entity)
247
&& let Ok(mut interaction) = interact.get_mut(*entity)
248
{
249
interaction.set_if_neq(PickingInteraction::None);
250
}
251
}
252
}
253
}
254
255
/// Merge the interaction state of this entity into the aggregated map.
256
fn merge_interaction_states(
257
pointer_press: &PointerPress,
258
hovered_entity: &Entity,
259
new_interaction_state: &mut HashMap<Entity, PickingInteraction>,
260
) {
261
let new_interaction = match pointer_press.is_any_pressed() {
262
true => PickingInteraction::Pressed,
263
false => PickingInteraction::Hovered,
264
};
265
266
if let Some(old_interaction) = new_interaction_state.get_mut(hovered_entity) {
267
// Only update if the new value has a higher precedence than the old value.
268
if *old_interaction != new_interaction
269
&& matches!(
270
(*old_interaction, new_interaction),
271
(PickingInteraction::Hovered, PickingInteraction::Pressed)
272
| (PickingInteraction::None, PickingInteraction::Pressed)
273
| (PickingInteraction::None, PickingInteraction::Hovered)
274
)
275
{
276
*old_interaction = new_interaction;
277
}
278
} else {
279
new_interaction_state.insert(*hovered_entity, new_interaction);
280
}
281
}
282
283
/// A component that allows users to use regular Bevy change detection to determine when the pointer
284
/// enters or leaves an entity. Users should insert this component on an entity to indicate interest
285
/// in knowing about hover state changes.
286
///
287
/// The component's boolean value will be `true` whenever the pointer is currently directly hovering
288
/// over the entity, or any of the entity's descendants (as defined by the [`ChildOf`]
289
/// relationship). This is consistent with the behavior of the CSS `:hover` pseudo-class, which
290
/// applies to the element and all of its descendants.
291
///
292
/// The contained boolean value is guaranteed to only be mutated when the pointer enters or leaves
293
/// the entity, allowing Bevy change detection to be used efficiently. This is in contrast to the
294
/// [`HoverMap`] resource, which is updated every frame.
295
///
296
/// Typically, a simple hoverable entity or widget will have this component added to it. More
297
/// complex widgets can have this component added to each hoverable part.
298
///
299
/// The computational cost of keeping the `Hovered` components up to date is relatively cheap, and
300
/// linear in the number of entities that have the [`Hovered`] component inserted.
301
#[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)]
302
#[reflect(Component, Default, PartialEq, Debug, Clone)]
303
#[component(immutable)]
304
pub struct Hovered(pub bool);
305
306
impl Hovered {
307
/// Get whether the entity is currently hovered.
308
pub fn get(&self) -> bool {
309
self.0
310
}
311
}
312
313
/// A component that allows users to use regular Bevy change detection to determine when the pointer
314
/// is directly hovering over an entity. Users should insert this component on an entity to indicate
315
/// interest in knowing about hover state changes.
316
///
317
/// This is similar to [`Hovered`] component, except that it does not include descendants in the
318
/// hover state.
319
#[derive(Component, Copy, Clone, Default, Eq, PartialEq, Debug, Reflect)]
320
#[reflect(Component, Default, PartialEq, Debug, Clone)]
321
#[component(immutable)]
322
pub struct DirectlyHovered(pub bool);
323
324
impl DirectlyHovered {
325
/// Get whether the entity is currently hovered.
326
pub fn get(&self) -> bool {
327
self.0
328
}
329
}
330
331
/// Uses [`HoverMap`] changes to update [`Hovered`] components.
332
pub fn update_is_hovered(
333
hover_map: Option<Res<HoverMap>>,
334
mut hovers: Query<(Entity, &Hovered)>,
335
parent_query: Query<&ChildOf>,
336
mut commands: Commands,
337
) {
338
// Don't do any work if there's no hover map.
339
let Some(hover_map) = hover_map else { return };
340
341
// Don't bother collecting ancestors if there are no hovers.
342
if hovers.is_empty() {
343
return;
344
}
345
346
// Algorithm: for each entity having a `Hovered` component, we want to know if the current
347
// entry in the hover map is "within" (that is, in the set of descendants of) that entity. Rather
348
// than doing an expensive breadth-first traversal of children, instead start with the hovermap
349
// entry and search upwards. We can make this even cheaper by building a set of ancestors for
350
// the hovermap entry, and then testing each `Hovered` entity against that set.
351
352
// A set which contains the hovered for the current pointer entity and its ancestors. The
353
// capacity is based on the likely tree depth of the hierarchy, which is typically greater for
354
// UI (because of layout issues) than for 3D scenes. A depth of 32 is a reasonable upper bound
355
// for most use cases.
356
let mut hover_ancestors = EntityHashSet::with_capacity(32);
357
if let Some(map) = hover_map.get(&PointerId::Mouse) {
358
for hovered_entity in map.keys() {
359
hover_ancestors.insert(*hovered_entity);
360
hover_ancestors.extend(parent_query.iter_ancestors(*hovered_entity));
361
}
362
}
363
364
// For each hovered entity, it is considered "hovering" if it's in the set of hovered ancestors.
365
for (entity, hoverable) in hovers.iter_mut() {
366
let is_hovering = hover_ancestors.contains(&entity);
367
if hoverable.0 != is_hovering {
368
commands.entity(entity).insert(Hovered(is_hovering));
369
}
370
}
371
}
372
373
/// Uses [`HoverMap`] changes to update [`DirectlyHovered`] components.
374
pub fn update_is_directly_hovered(
375
hover_map: Option<Res<HoverMap>>,
376
hovers: Query<(Entity, &DirectlyHovered)>,
377
mut commands: Commands,
378
) {
379
// Don't do any work if there's no hover map.
380
let Some(hover_map) = hover_map else { return };
381
382
// Don't bother collecting ancestors if there are no hovers.
383
if hovers.is_empty() {
384
return;
385
}
386
387
if let Some(map) = hover_map.get(&PointerId::Mouse) {
388
// It's hovering if it's in the HoverMap.
389
for (entity, hoverable) in hovers.iter() {
390
let is_hovering = map.contains_key(&entity);
391
if hoverable.0 != is_hovering {
392
commands.entity(entity).insert(DirectlyHovered(is_hovering));
393
}
394
}
395
} else {
396
// No hovered entity, reset all hovers.
397
for (entity, hoverable) in hovers.iter() {
398
if hoverable.0 {
399
commands.entity(entity).insert(DirectlyHovered(false));
400
}
401
}
402
}
403
}
404
405
#[cfg(test)]
406
mod tests {
407
use bevy_camera::Camera;
408
409
use super::*;
410
411
#[test]
412
fn update_is_hovered_memoized() {
413
let mut world = World::default();
414
let camera = world.spawn(Camera::default()).id();
415
416
// Setup entities
417
let hovered_child = world.spawn_empty().id();
418
let hovered_entity = world.spawn(Hovered(false)).add_child(hovered_child).id();
419
420
// Setup hover map with hovered_entity hovered by mouse
421
let mut hover_map = HoverMap::default();
422
let mut entity_map = HashMap::new();
423
entity_map.insert(
424
hovered_child,
425
HitData {
426
depth: 0.0,
427
camera,
428
position: None,
429
normal: None,
430
},
431
);
432
hover_map.insert(PointerId::Mouse, entity_map);
433
world.insert_resource(hover_map);
434
435
// Run the system
436
assert!(world.run_system_cached(update_is_hovered).is_ok());
437
438
// Check to insure that the hovered entity has the Hovered component set to true
439
let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap();
440
assert!(hover.get());
441
assert!(hover.is_changed());
442
443
// Now do it again, but don't change the hover map.
444
world.increment_change_tick();
445
446
assert!(world.run_system_cached(update_is_hovered).is_ok());
447
let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap();
448
assert!(hover.get());
449
450
// Should not be changed
451
// NOTE: Test doesn't work - thinks it is always changed
452
// assert!(!hover.is_changed());
453
454
// Clear the hover map and run again.
455
world.insert_resource(HoverMap::default());
456
world.increment_change_tick();
457
458
assert!(world.run_system_cached(update_is_hovered).is_ok());
459
let hover = world.entity(hovered_entity).get_ref::<Hovered>().unwrap();
460
assert!(!hover.get());
461
assert!(hover.is_changed());
462
}
463
464
#[test]
465
fn update_is_hovered_direct_self() {
466
let mut world = World::default();
467
let camera = world.spawn(Camera::default()).id();
468
469
// Setup entities
470
let hovered_entity = world.spawn(DirectlyHovered(false)).id();
471
472
// Setup hover map with hovered_entity hovered by mouse
473
let mut hover_map = HoverMap::default();
474
let mut entity_map = HashMap::new();
475
entity_map.insert(
476
hovered_entity,
477
HitData {
478
depth: 0.0,
479
camera,
480
position: None,
481
normal: None,
482
},
483
);
484
hover_map.insert(PointerId::Mouse, entity_map);
485
world.insert_resource(hover_map);
486
487
// Run the system
488
assert!(world.run_system_cached(update_is_directly_hovered).is_ok());
489
490
// Check to insure that the hovered entity has the DirectlyHovered component set to true
491
let hover = world
492
.entity(hovered_entity)
493
.get_ref::<DirectlyHovered>()
494
.unwrap();
495
assert!(hover.get());
496
assert!(hover.is_changed());
497
498
// Now do it again, but don't change the hover map.
499
world.increment_change_tick();
500
501
assert!(world.run_system_cached(update_is_directly_hovered).is_ok());
502
let hover = world
503
.entity(hovered_entity)
504
.get_ref::<DirectlyHovered>()
505
.unwrap();
506
assert!(hover.get());
507
508
// Should not be changed
509
// NOTE: Test doesn't work - thinks it is always changed
510
// assert!(!hover.is_changed());
511
512
// Clear the hover map and run again.
513
world.insert_resource(HoverMap::default());
514
world.increment_change_tick();
515
516
assert!(world.run_system_cached(update_is_directly_hovered).is_ok());
517
let hover = world
518
.entity(hovered_entity)
519
.get_ref::<DirectlyHovered>()
520
.unwrap();
521
assert!(!hover.get());
522
assert!(hover.is_changed());
523
}
524
525
#[test]
526
fn update_is_hovered_direct_child() {
527
let mut world = World::default();
528
let camera = world.spawn(Camera::default()).id();
529
530
// Setup entities
531
let hovered_child = world.spawn_empty().id();
532
let hovered_entity = world
533
.spawn(DirectlyHovered(false))
534
.add_child(hovered_child)
535
.id();
536
537
// Setup hover map with hovered_entity hovered by mouse
538
let mut hover_map = HoverMap::default();
539
let mut entity_map = HashMap::new();
540
entity_map.insert(
541
hovered_child,
542
HitData {
543
depth: 0.0,
544
camera,
545
position: None,
546
normal: None,
547
},
548
);
549
hover_map.insert(PointerId::Mouse, entity_map);
550
world.insert_resource(hover_map);
551
552
// Run the system
553
assert!(world.run_system_cached(update_is_directly_hovered).is_ok());
554
555
// Check to insure that the DirectlyHovered component is still false
556
let hover = world
557
.entity(hovered_entity)
558
.get_ref::<DirectlyHovered>()
559
.unwrap();
560
assert!(!hover.get());
561
assert!(hover.is_changed());
562
}
563
}
564
565