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
//! Defines the [ClickArea] element.

use ambient_cb::{cb, Cb};
use ambient_element::{
    to_owned, use_frame, use_ref_with, use_runtime_message, Element, ElementComponent, Hooks,
};
use ambient_guest_bridge::{
    core::{
        input::components::{is_mouse_over, mouse_pickable_max, mouse_pickable_min},
        messages,
    },
    ecs::{EntityId, World},
};
use ambient_shared_types::MouseButton;
use glam::{Vec2, Vec3};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// The state of a mouse button.
pub enum MouseInput {
    /// The button is pressed.
    Pressed,
    /// The button is released.
    Released,
}
impl From<bool> for MouseInput {
    fn from(value: bool) -> Self {
        if value {
            Self::Pressed
        } else {
            Self::Released
        }
    }
}

#[derive(Debug, Clone)]
/// An area that tracks mouse events.
pub struct ClickArea {
    /// The inner element.
    pub inner: Element,
    /// Callback for when the mouse enters the area.
    pub on_mouse_enter: Vec<Cb<dyn Fn(&mut World, EntityId) + Sync + Send>>,
    /// Callback for when the mouse leaves the area.
    pub on_mouse_leave: Vec<Cb<dyn Fn(&mut World, EntityId) + Sync + Send>>,
    /// Callback for when the mouse hovers over the area.
    pub on_mouse_hover: Vec<Cb<dyn Fn(&mut World, EntityId) + Sync + Send>>,
    /// Callback for when a mouse button is.
    pub on_mouse_input:
        Vec<Cb<dyn Fn(&mut World, EntityId, MouseInput, MouseButton) + Sync + Send>>,
    /// Callback for when the mouse wheel is scrolled.
    pub on_mouse_wheel: Vec<Cb<dyn Fn(&mut World, EntityId, Vec2, bool) + Sync + Send>>,
}
impl ClickArea {
    /// Create a new ClickArea.
    pub fn new(inner: Element) -> Self {
        Self {
            inner,
            on_mouse_enter: Vec::new(),
            on_mouse_leave: Vec::new(),
            on_mouse_hover: Vec::new(),
            on_mouse_input: Vec::new(),
            on_mouse_wheel: Vec::new(),
        }
    }
    /// Set the callback for when the mouse hovers over the area.
    pub fn on_mouse_hover<F: Fn(&mut World, EntityId) + Sync + Send + 'static>(
        mut self,
        handle: F,
    ) -> Self {
        self.on_mouse_hover.push(cb(handle));
        self
    }
    /// Set the callback for when the mouse enters the area.
    pub fn on_mouse_enter<F: Fn(&mut World, EntityId) + Sync + Send + 'static>(
        mut self,
        handle: F,
    ) -> Self {
        self.on_mouse_enter.push(cb(handle));
        self
    }
    /// Set the callback for when the mouse leaves the area.
    pub fn on_mouse_leave<F: Fn(&mut World, EntityId) + Sync + Send + 'static>(
        mut self,
        handle: F,
    ) -> Self {
        self.on_mouse_leave.push(cb(handle));
        self
    }
    /// Set the callback for when a mouse button is pressed or released.
    pub fn on_mouse_input<
        F: Fn(&mut World, EntityId, MouseInput, MouseButton) + Sync + Send + 'static,
    >(
        mut self,
        handle: F,
    ) -> Self {
        self.on_mouse_input.push(cb(handle));
        self
    }
    /// Set the callback for when the mouse wheel is scrolled.
    pub fn on_mouse_wheel<F: Fn(&mut World, EntityId, Vec2, bool) + Sync + Send + 'static>(
        mut self,
        handle: F,
    ) -> Self {
        self.on_mouse_wheel.push(cb(handle));
        self
    }
    /// Set the callback for when a mouse button is pressed.
    pub fn on_mouse_down<F: Fn(&mut World, EntityId, MouseButton) + Sync + Send + 'static>(
        self,
        handle: F,
    ) -> Self {
        self.on_mouse_input(move |world, id, state, button| {
            if state == MouseInput::Pressed {
                handle(world, id, button)
            }
        })
    }
    /// Set the callback for when a mouse button is released.
    pub fn on_mouse_up<F: Fn(&mut World, EntityId, MouseButton) + Sync + Send + 'static>(
        self,
        handle: F,
    ) -> Self {
        self.on_mouse_input(move |world, id, state, button| {
            if state == MouseInput::Released {
                handle(world, id, button)
            }
        })
    }
}
impl ElementComponent for ClickArea {
    fn render(self: Box<Self>, hooks: &mut Hooks) -> Element {
        let Self {
            inner,
            on_mouse_enter,
            on_mouse_leave,
            on_mouse_hover,
            on_mouse_input,
            on_mouse_wheel,
        } = *self;
        let id = use_ref_with(hooks, |_| None);
        let mouse_over_count = use_ref_with(hooks, |_| 0);
        use_frame(hooks, {
            to_owned![id, mouse_over_count];
            move |world| {
                if let Some(id) = *id.lock() {
                    let next = world.get(id, is_mouse_over()).unwrap_or(0);
                    let mut state = mouse_over_count.lock();
                    if *state == 0 && next > 0 {
                        for handler in &on_mouse_enter {
                            handler(world, id);
                        }
                    }
                    if *state > 0 && next == 0 {
                        for handler in &on_mouse_leave {
                            handler(world, id);
                        }
                    }
                    if next > 0 {
                        for handler in &on_mouse_hover {
                            handler(world, id);
                        }
                    }
                    *state = next;
                }
            }
        });

        use_runtime_message::<messages::WindowMouseInput>(hooks, {
            to_owned![id, mouse_over_count];
            move |world, event| {
                if let Some(id) = *id.lock() {
                    if *mouse_over_count.lock() > 0 {
                        for handler in &on_mouse_input {
                            handler(world, id, event.pressed.into(), event.button.into());
                        }
                    }
                }
            }
        });

        use_runtime_message::<messages::WindowMouseWheel>(hooks, {
            to_owned![id];
            move |world, event| {
                if let Some(id) = *id.lock() {
                    if *mouse_over_count.lock() > 0 {
                        for handler in &on_mouse_wheel {
                            handler(world, id, event.delta, event.pixels);
                        }
                    }
                }
            }
        });

        inner
            .init(mouse_pickable_min(), Vec3::ZERO)
            .init(mouse_pickable_max(), Vec3::ZERO)
            .on_spawned(move |_, new_id, _| {
                *id.lock() = Some(new_id);
            })
    }
}