noesis_bevy 0.14.0

Bevy plugin that drives the Noesis GUI Native SDK and renders its UIs into a Bevy frame via wgpu compositing.
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
//! Bevy → Noesis input forwarding.
//!
//! The app observes Bevy's raw input events and a few window events, converts
//! each into a [`NoesisInputEvent`], and pushes it onto the shared
//! [`NoesisInputQueue`] resource. The `apply_noesis_input` system (defined in
//! `render.rs`, in [`NoesisSet::Apply`](crate::NoesisSet)) drains that queue
//! onto the live [`noesis_runtime::view::View`] just before the frame is
//! driven. Both ends live in the main world, on the one thread Noesis is
//! pinned to.
//!
//! # Coordinate handling
//!
//! Bevy delivers cursor positions in *logical* pixels relative to the
//! window. Noesis hit-tests in the view's own pixel space, whatever
//! [`NoesisView::size`] is set to (the intermediate texture).
//! We convert on the main side, collapsing Window scale factor and any
//! intermediate-vs-window size mismatch into a single ratio:
//!
//! ```text
//!   view_x = cursor_logical_x * view_w / window_logical_w
//!   view_y = cursor_logical_y * view_h / window_logical_h
//! ```
//!
//! Once `resize_noesis_scene` snaps the intermediate to the window's
//! physical size, this ratio reduces to the scale factor.
//!
//! # Queue lifecycle
//!
//! The forwarders push in `PreUpdate`; `apply_noesis_input` drains the queue
//! in `PostUpdate` ([`NoesisSet::Apply`](crate::NoesisSet)), leaving it empty
//! for the next frame's pushes. Push and drain both touch the one main-world
//! resource in schedule order, so no separate clearing pass is needed.

use bevy::input::{
    ButtonState,
    keyboard::KeyboardInput,
    mouse::{MouseButton as BevyMouseButton, MouseButtonInput, MouseScrollUnit, MouseWheel},
    touch::{TouchInput, TouchPhase},
};
use bevy::prelude::*;
use bevy::window::{CursorLeft, CursorMoved, PrimaryWindow, WindowFocused, WindowResized};
use noesis_runtime::view::{Key, MouseButton};

use crate::render::NoesisView;

pub mod key_map;

// ── Events and queue ───────────────────────────────────────────────────────

/// A single input event already translated into Noesis terms, waiting in the
/// [`NoesisInputQueue`] to be replayed onto the live [`View`].
///
/// All `x`/`y` coordinates are in the view's own pixel space (see the
/// module-level coordinate handling notes), already converted from Bevy's
/// logical-pixel window coordinates by `to_view_coords`.
///
/// [`View`]: noesis_runtime::view::View
#[derive(Clone, Copy, Debug)]
pub enum NoesisInputEvent {
    /// Pointer moved to a new position. Noesis tracks this as the last known
    /// cursor location for subsequent hit-tests.
    MouseMove {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
    },
    /// A mouse button changed state at the given position.
    MouseButton {
        /// `true` on press, `false` on release.
        down: bool,
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Which button changed.
        button: MouseButton,
    },
    /// A vertical wheel detent, in the Win32 `WHEEL_DELTA` convention Noesis
    /// expects (120 units per notch).
    MouseWheel {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Wheel movement in 120-units-per-notch increments.
        delta: i32,
    },
    /// A horizontal wheel detent (tilt-wheel or trackpad swipe), same
    /// 120-units-per-notch convention as [`MouseWheel`](Self::MouseWheel);
    /// positive scrolls right.
    MouseHWheel {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Wheel movement in 120-units-per-notch increments.
        delta: i32,
    },
    /// A scroll in line counts, the other path Noesis's scrolling controls
    /// listen on. Reserved for an explicit scroll source (e.g. a gamepad
    /// bridge); the mouse wheel drives [`MouseWheel`](Self::MouseWheel) /
    /// [`MouseHWheel`](Self::MouseHWheel) only, so a `ScrollViewer` reachable
    /// by both paths isn't scrolled twice.
    Scroll {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Scroll amount in lines.
        value: f32,
        /// `true` for horizontal scroll, `false` for vertical.
        horizontal: bool,
    },
    /// A touch point made contact.
    TouchDown {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Touch point identifier, stable across this contact's lifetime.
        id: u64,
    },
    /// A touch point moved while in contact.
    TouchMove {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Touch point identifier, stable across this contact's lifetime.
        id: u64,
    },
    /// A touch point lifted or was canceled.
    TouchUp {
        /// X position in view-pixel space.
        x: i32,
        /// Y position in view-pixel space.
        y: i32,
        /// Touch point identifier, stable across this contact's lifetime.
        id: u64,
    },
    /// A key was pressed. Carries the mapped Noesis [`Key`]; keys that don't
    /// map are dropped before they reach the queue.
    KeyDown(Key),
    /// A key was released.
    KeyUp(Key),
    /// A typed character, as a Unicode scalar value. Drives text entry
    /// separately from the [`KeyDown`](Self::KeyDown) / [`KeyUp`](Self::KeyUp)
    /// pair, including on auto-repeat.
    Char(u32),
    /// Window focus changed: `true` gained, `false` lost.
    Focus(bool),
}

/// A [`NoesisInputEvent`] paired with the view it is routed to.
///
/// The coordinate forwarders convert a pointer position against a specific
/// view's pixel space, then stamp that same view here so the render side
/// hit-tests against the view the coordinates were scaled for. `target: None`
/// means "the primary view" — the deterministic fallback (lowest-`Entity` live
/// scene) used for events with no natural view (keyboard, focus) or for
/// programmatic pushes via [`NoesisInputQueue::push`].
///
/// The `target` lays the rails for real per-view routing; today the primary
/// view is the only one that reliably owns the pointer.
#[derive(Clone, Copy, Debug)]
pub struct TargetedInput {
    /// The view this event is routed to, or `None` for the primary view.
    pub target: Option<Entity>,
    /// The translated input event.
    pub event: NoesisInputEvent,
}

/// Batched input events waiting to be drained onto the Noesis `View`.
/// Populated by systems in this module; drained by the `apply_noesis_input`
/// system every frame.
#[derive(Resource, Clone, Default, Debug)]
pub struct NoesisInputQueue {
    /// Events queued this frame, in arrival order, each tagged with its target
    /// view (see [`TargetedInput`]).
    pub events: Vec<TargetedInput>,
}

/// Whether the mouse pointer is currently over hit-test-visible Noesis UI.
///
/// The integration exposes no per-element hit-test, so this one flag is the
/// pointer-over-UI signal. Read it in the main world to suppress 3D-world
/// interaction when a click lands on the interface. It mirrors the primary
/// `View`'s hit-test from the last pointer event and updates only on pointer
/// events in `PostUpdate`, so it lags by one frame like the rest of the input
/// bridge.
#[derive(Resource, Default, Clone, Copy, Debug)]
pub struct NoesisPointerOverUi {
    /// `true` when the last pointer event hit-tested onto the UI.
    pub over: bool,
}

impl NoesisInputQueue {
    /// Append an event bound to the primary view (see [`TargetedInput`]).
    pub fn push(&mut self, ev: NoesisInputEvent) {
        self.push_to_opt(None, ev);
    }

    /// Append an event bound to a specific view.
    pub fn push_to(&mut self, target: Entity, ev: NoesisInputEvent) {
        self.push_to_opt(Some(target), ev);
    }

    /// Append an event bound to `target` when `Some`, or to the primary view
    /// when `None`.
    pub fn push_to_opt(&mut self, target: Option<Entity>, ev: NoesisInputEvent) {
        self.events.push(TargetedInput { target, event: ev });
    }

    /// Drain every queued event, leaving the queue empty. The
    /// `apply_noesis_input` system uses this to feed events onto the [`View`].
    ///
    /// [`View`]: noesis_runtime::view::View
    pub fn drain(&mut self) -> std::vec::Drain<'_, TargetedInput> {
        self.events.drain(..)
    }
}

/// Scale a logical-px point on the window into Noesis view-pixel space.
/// Returns `None` when the window has zero size (startup race).
fn to_view_coords(window: &Window, scene: &NoesisView, x: f32, y: f32) -> Option<(i32, i32)> {
    let ww = window.width();
    let wh = window.height();
    if ww <= 0.0 || wh <= 0.0 {
        return None;
    }
    let vw = scene.size.x as f32;
    let vh = scene.size.y as f32;
    Some(((x * vw / ww) as i32, (y * vh / wh) as i32))
}

// ── Systems ────────────────────────────────────────────────────────────────

/// Track the cursor position separately from `CursorMoved` so we can attach
/// a move-at-press-coord to every `MouseButton` / Touch event. Noesis
/// hit-tests on the last known pointer position; without this, a button
/// pressed before the cursor has entered the window hits (0,0).
#[derive(Resource, Default, Clone, Copy, Debug)]
struct LastPointer {
    x: i32,
    y: i32,
    valid: bool,
    /// The view the last cursor position was converted against. Button and
    /// wheel events reuse it so they route to the same view as the move.
    target: Option<Entity>,
}

#[allow(clippy::needless_pass_by_value)]
fn forward_cursor_moved(
    mut reader: MessageReader<CursorMoved>,
    mut queue: ResMut<NoesisInputQueue>,
    mut last: ResMut<LastPointer>,
    window: Single<(Entity, &Window), With<PrimaryWindow>>,
    views: Query<(Entity, &NoesisView)>,
) {
    let (primary_window, window) = (window.0, window.1);
    // Convert against the deterministic primary view (lowest `Entity`) and stamp
    // it onto the event, so the render side hit-tests against the same view the
    // coordinates were scaled for. `iter().next()` is query order and would let
    // two differently-sized views disagree.
    let Some((entity, scene)) = views.iter().min_by_key(|(entity, _)| *entity) else {
        reader.read(); // drop events so we don't replay them later
        return;
    };
    for ev in reader.read() {
        // Only the primary window feeds the primary view; a secondary window's
        // moves would be converted with the wrong dimensions (see P0.7's
        // primary-view rule).
        if ev.window != primary_window {
            continue;
        }
        if let Some((x, y)) = to_view_coords(window, scene, ev.position.x, ev.position.y) {
            last.x = x;
            last.y = y;
            last.valid = true;
            last.target = Some(entity);
            queue.push_to(entity, NoesisInputEvent::MouseMove { x, y });
        }
    }
}

/// When the cursor leaves the primary window, move the Noesis pointer off-view
/// so hover highlights clear and [`NoesisPointerOverUi`] resets — otherwise a
/// pointer parked over UI as it exits keeps `over` true, wrongly suppressing
/// 3D interaction. `CursorLeft` carries no position, so we send a move to a
/// coordinate that hit-tests nothing.
#[allow(clippy::needless_pass_by_value)]
fn forward_cursor_left(
    mut reader: MessageReader<CursorLeft>,
    mut queue: ResMut<NoesisInputQueue>,
    mut last: ResMut<LastPointer>,
    primary_window: Single<Entity, With<PrimaryWindow>>,
) {
    let primary_window = *primary_window;
    let mut left_primary = false;
    for ev in reader.read() {
        if ev.window == primary_window {
            left_primary = true;
        }
    }
    if left_primary {
        queue.push_to_opt(last.target, NoesisInputEvent::MouseMove { x: -1, y: -1 });
        last.valid = false;
    }
}

#[allow(clippy::needless_pass_by_value)]
fn forward_mouse_buttons(
    mut reader: MessageReader<MouseButtonInput>,
    mut queue: ResMut<NoesisInputQueue>,
    last: Res<LastPointer>,
) {
    for ev in reader.read() {
        let button = match ev.button {
            BevyMouseButton::Left => MouseButton::Left,
            BevyMouseButton::Right => MouseButton::Right,
            BevyMouseButton::Middle => MouseButton::Middle,
            BevyMouseButton::Back => MouseButton::XButton1,
            BevyMouseButton::Forward => MouseButton::XButton2,
            BevyMouseButton::Other(_) => continue,
        };
        let (x, y) = if last.valid { (last.x, last.y) } else { (0, 0) };
        // Re-enqueue last pos so the press coord matches the last MouseMove,
        // regardless of event arrival order. Route to the same view the move
        // was converted against.
        if last.valid {
            queue.push_to_opt(last.target, NoesisInputEvent::MouseMove { x, y });
        }
        queue.push_to_opt(
            last.target,
            NoesisInputEvent::MouseButton {
                down: matches!(ev.state, ButtonState::Pressed),
                x,
                y,
                button,
            },
        );
    }
}

#[allow(clippy::needless_pass_by_value)]
fn forward_mouse_wheel(
    mut reader: MessageReader<MouseWheel>,
    mut queue: ResMut<NoesisInputQueue>,
    last: Res<LastPointer>,
) {
    // Feed the wheel path only: MouseWheel (vertical) and MouseHWheel
    // (horizontal), Windows-style 120 units per detent. The Scroll (line-count)
    // path also drives ScrollViewers, so emitting both would scroll a control
    // reachable by both at double rate; Scroll is reserved for an explicit
    // scroll source (see [`NoesisInputEvent::Scroll`]).
    for ev in reader.read() {
        let (x, y) = if last.valid { (last.x, last.y) } else { (0, 0) };
        // Convert pixel scroll to "lines": rough heuristic of 40 px/line;
        // MouseScrollUnit::Line passes through.
        let lines_y = match ev.unit {
            MouseScrollUnit::Line => ev.y,
            MouseScrollUnit::Pixel => ev.y / 40.0,
        };
        let lines_x = match ev.unit {
            MouseScrollUnit::Line => ev.x,
            MouseScrollUnit::Pixel => ev.x / 40.0,
        };
        // 120 units per line is the Win32 `WHEEL_DELTA` convention Noesis uses.
        let wheel_delta = (lines_y * 120.0) as i32;
        let hwheel_delta = (lines_x * 120.0) as i32;
        // Route to the same view the last move was converted against.
        if wheel_delta != 0 {
            queue.push_to_opt(
                last.target,
                NoesisInputEvent::MouseWheel {
                    x,
                    y,
                    delta: wheel_delta,
                },
            );
        }
        if hwheel_delta != 0 {
            queue.push_to_opt(
                last.target,
                NoesisInputEvent::MouseHWheel {
                    x,
                    y,
                    delta: hwheel_delta,
                },
            );
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
fn forward_keyboard(mut reader: MessageReader<KeyboardInput>, mut queue: ResMut<NoesisInputQueue>) {
    for ev in reader.read() {
        // Forward OS auto-repeat as repeated KeyDown: `View::KeyDown` has no
        // internal repeat timer, so held keys (arrows, Backspace/Delete —
        // KeyDown-handled, not Char-handled) act once otherwise. Repeat events
        // are always `Pressed` and carry `text`, so the normal arm below emits
        // the accompanying Char exactly once.
        let key = key_map::from_bevy(ev.key_code);
        match ev.state {
            ButtonState::Pressed => {
                if key != Key::None {
                    queue.push(NoesisInputEvent::KeyDown(key));
                }
                if let Some(text) = ev.text.as_deref() {
                    for ch in text.chars() {
                        queue.push(NoesisInputEvent::Char(ch as u32));
                    }
                }
            }
            ButtonState::Released => {
                if key != Key::None {
                    queue.push(NoesisInputEvent::KeyUp(key));
                }
            }
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
fn forward_touch(
    mut reader: MessageReader<TouchInput>,
    mut queue: ResMut<NoesisInputQueue>,
    window: Single<(Entity, &Window), With<PrimaryWindow>>,
    views: Query<(Entity, &NoesisView)>,
) {
    let (primary_window, window) = (window.0, window.1);
    // Same deterministic primary-view selection as the cursor forwarder.
    let Some((entity, scene)) = views.iter().min_by_key(|(entity, _)| *entity) else {
        reader.read();
        return;
    };
    for ev in reader.read() {
        // Only the primary window feeds the primary view (see P0.7's rule).
        if ev.window != primary_window {
            continue;
        }
        let Some((x, y)) = to_view_coords(window, scene, ev.position.x, ev.position.y) else {
            continue;
        };
        let id = ev.id;
        match ev.phase {
            TouchPhase::Started => queue.push_to(entity, NoesisInputEvent::TouchDown { x, y, id }),
            TouchPhase::Moved => queue.push_to(entity, NoesisInputEvent::TouchMove { x, y, id }),
            TouchPhase::Ended | TouchPhase::Canceled => {
                queue.push_to(entity, NoesisInputEvent::TouchUp { x, y, id });
            }
        }
    }
}

#[allow(clippy::needless_pass_by_value)]
fn forward_focus(
    mut reader: MessageReader<WindowFocused>,
    mut queue: ResMut<NoesisInputQueue>,
    primary_window: Single<Entity, With<PrimaryWindow>>,
) {
    let primary_window = *primary_window;
    for ev in reader.read() {
        // Ignore focus changes on secondary windows; alt-tabbing between the
        // app's own windows would otherwise spuriously activate/deactivate the
        // primary view (see P0.7's rule).
        if ev.window != primary_window {
            continue;
        }
        queue.push(NoesisInputEvent::Focus(ev.focused));
    }
}

/// Snap each [`NoesisView`]'s size to the window's physical pixel size on
/// resize. Makes the `NoesisNode` blit effectively 1:1 and brings the
/// cursor-coord ratio in `to_view_coords` down to just the scale factor.
///
/// Writes the authoritative [`NoesisView::size`]; the scene-ensure pass picks
/// up the new size on the next frame, detects the mismatch, and rebuilds the
/// intermediate texture + re-calls `View::set_size`.
#[allow(clippy::needless_pass_by_value)]
fn resize_noesis_scene(
    mut reader: MessageReader<WindowResized>,
    mut views: Query<&mut NoesisView>,
    window: Single<(Entity, &Window), With<PrimaryWindow>>,
) {
    let (primary_window, window) = (window.0, window.1);
    if views.is_empty() {
        reader.read();
        return;
    }
    for ev in reader.read() {
        // Secondary-window resizes must not resize the primary view's
        // intermediate (see P0.7's rule).
        if ev.window != primary_window {
            continue;
        }
        let physical = window.physical_size();
        if physical.x > 0 && physical.y > 0 {
            for mut scene in &mut views {
                scene.size = UVec2::new(physical.x, physical.y);
            }
        }
    }
}

// ── Plugin ─────────────────────────────────────────────────────────────────

/// Installs the Bevy → Noesis input bridge. Add alongside [`NoesisPlugin`].
///
/// [`NoesisPlugin`]: crate::NoesisPlugin
pub struct NoesisInputPlugin;

impl Plugin for NoesisInputPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<NoesisInputQueue>()
            .init_resource::<LastPointer>()
            .init_resource::<NoesisPointerOverUi>()
            .add_systems(
                PreUpdate,
                (
                    resize_noesis_scene,
                    forward_cursor_moved,
                    forward_cursor_left,
                    forward_mouse_buttons,
                    forward_mouse_wheel,
                    forward_keyboard,
                    forward_touch,
                    forward_focus,
                )
                    .chain(),
            );
    }
}