Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

FC0a: ui/widgets/standard_widgets under scripted input: the menu opens, its popup placed by Bevy's Popover

shinyobjectz450f8e4a974e
diff --git a/bench/bevy-parity/input/standard_widgets_menu.json b/bench/bevy-parity/input/standard_widgets_menu.json
new file mode 100644
index 00000000..9a1a1b30
--- /dev/null
+++ b/bench/bevy-parity/input/standard_widgets_menu.json
@@ -0,0 +1 @@
+{"2": ["Pointer:640:450"], "3": ["Pointer:640:450:down"], "4": ["Pointer:640:450"], "6": ["Pointer:640:520"]}
diff --git a/bench/bevy-parity/runs.tsv b/bench/bevy-parity/runs.tsv
index 1563efd2..c67c4bb6 100644
--- a/bench/bevy-parity/runs.tsv
+++ b/bench/bevy-parity/runs.tsv
@@ -1,4 +1,4 @@
-# path example arguments (- for none) frames probed (docs/control.feature FC0a; tools/bevy-parity)
+# path example arguments (- for none) frames probed input script, optional (docs/control.feature FC0a; tools/bevy-parity)
stress_tests/many_cubes --benchmark --instance-count 10000 30,60
3d/3d_scene - 5,10
stress_tests/many_lights - 30,60
@@ -98,7 +98,7 @@ ui/widgets/viewport_node - 10
ui/widgets/vertical_slider - 10
ui/widgets/virtual_keyboard - 10
ui/widgets/standard_widgets_observers - 10
-ui/widgets/standard_widgets - 10
+ui/widgets/standard_widgets - 10 bench/bevy-parity/input/standard_widgets_menu.json
ui/widgets/feathers_counter - 10
ui/widgets/feathers_number_input - 10
ui/widgets/feathers_gallery - 10
diff --git a/docs/bevy-parity.md b/docs/bevy-parity.md
index ae31b8b3..cefc843f 100644
--- a/docs/bevy-parity.md
+++ b/docs/bevy-parity.md
@@ -154,8 +154,6 @@ doesn't pay.
| ui/widgets/viewport_node | 10 | 0.999871 | 0 | 1 / 1 | 446 / 505 | 6 / 8 | 2 / 2 | 52.1 / 3.767 = 3.767 + 0 | yes | |
| ui/widgets/vertical_slider | 10 | 0.999004 | 11 | 0 / 0 | 459 / 500 | 5 / 7 | 1 / 1 | 45.47 / 2.709 = 2.709 + 0 | yes | |
| ui/widgets/virtual_keyboard | 10 | 0.993705 | 13 | 0 / 0 | 646 / 500 | 5 / 7 | 1 / 1 | 48.94 / 3.192 = 3.192 + 0 | yes | |
-| ui/widgets/standard_widgets_observers | 10 | 0.998736 | 14 | 0 / 0 | 473 / 500 | 5 / 7 | 1 / 1 | 45.687 / 2.689 = 2.689 + 0 | yes | |
-| ui/widgets/standard_widgets | 10 | 0.997647 | 17 | 0 / 0 | 477 / 500 | 5 / 7 | 1 / 1 | 46.358 / 2.889 = 2.889 + 0 | yes | |
| ui/widgets/feathers_counter | 10 | 0.999941 | 1 | 0 / 0 | 493 / 500 | 5 / 7 | 1 / 1 | 47.404 / 2.734 = 2.734 + 0 | yes | |
| ui/widgets/feathers_number_input | 10 | 0.997483 | 6 | 0 / 0 | 972 / 500 | 5 / 7 | 1 / 1 | 48.5 / 3.029 = 3.029 + 0 | yes | |
| ui/widgets/feathers_gallery | 10 | 0.995606 | 9 | 0 / 0 | 1060 / 500 | 5 / 7 | 1 / 1 | 82.162 / 2.866 = 2.866 + 0 | yes | |
@@ -168,8 +166,10 @@ doesn't pay.
| ui/ui_material | 10 | 0.999993 | 0 | 0 / 0 | 446 / 502 | 5 / 7 | 1 / 1 | 46.877 / 3.374 = 3.374 + 0 | yes | |
| ui/text/system_fonts | 10 | 0.987943 | 18 | 0 / 0 | 1992 / 500 | 5 / 7 | 1 / 1 | 115.916 / 3.184 = 3.184 + 0 | yes | |
| ui/text/font_atlas_debug | 10 | 0.999660 | 6 | 0 / 0 | 445 / 500 | 5 / 7 | 1 / 1 | 45.934 / 3.204 = 3.204 + 0 | yes | |
-| 3d/two_passes | 10 | 0.999025 | 0 | 2 / 2 | 444 / 505 | 7 / 9 | 3 / 3 | 58.492 / 4.378 = 4.378 + 0 | yes | |
| 3d/split_screen | 10 | 0.998973 | 5 | 2 / 2 | 546 / 537 | 7 / 9 | 3 / 3 | 55.168 / 6.114 = 6.114 + 0 | yes | |
+| ui/widgets/standard_widgets_observers | 10 | 0.998736 | 14 | 0 / 0 | 473 / 500 | 5 / 7 | 1 / 1 | 66.788 / 4.068 = 4.068 + 0 | yes | |
+| 3d/two_passes | 10 | 0.999025 | 0 | 2 / 2 | 444 / 505 | 7 / 9 | 3 / 3 | 85.672 / 6.572 = 6.572 + 0 | yes | |
+| ui/widgets/standard_widgets | 10 | 0.994691 | 17 | 0 / 0 | 487 / 500 | 5 / 7 | 1 / 1 | 63.168 / 3.666 = 3.666 + 0 | yes | |
## Excluded
diff --git a/docs/bevy-parity/results.jsonl b/docs/bevy-parity/results.jsonl
index 4b241a73..9c25d9a2 100644
--- a/docs/bevy-parity/results.jsonl
+++ b/docs/bevy-parity/results.jsonl
@@ -141,8 +141,6 @@
{"example":"ui/widgets/viewport_node","frame":10,"ssim":0.999871,"tile":0,"bevy":{"batch_keys":1,"entities":446,"extents":["2.5000 2.5000 2.5000"],"frame":10,"frame_ms":52.1,"materials":2,"mesh_entities":1,"meshes":6,"other_material":0,"visible":1},"raea":{"frame":17,"entities":505,"mesh_entities":1,"visible":1,"meshes":8,"materials":2,"batch_keys":1,"other_material":0,"extents":["2.5000 2.5000 2.5000"],"frame_ms":3.767,"step_ms":null,"cost_ms":3.767},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/widgets/vertical_slider","frame":10,"ssim":0.999004,"tile":11,"bevy":{"batch_keys":0,"entities":459,"extents":[],"frame":10,"frame_ms":45.47,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.709,"step_ms":null,"cost_ms":2.709},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/widgets/virtual_keyboard","frame":10,"ssim":0.993705,"tile":13,"bevy":{"batch_keys":0,"entities":646,"extents":[],"frame":10,"frame_ms":48.94,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.192,"step_ms":null,"cost_ms":3.192},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"ui/widgets/standard_widgets_observers","frame":10,"ssim":0.998736,"tile":14,"bevy":{"batch_keys":0,"entities":473,"extents":[],"frame":10,"frame_ms":45.687,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.689,"step_ms":null,"cost_ms":2.689},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"ui/widgets/standard_widgets","frame":10,"ssim":0.997647,"tile":17,"bevy":{"batch_keys":0,"entities":477,"extents":[],"frame":10,"frame_ms":46.358,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.889,"step_ms":null,"cost_ms":2.889},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/widgets/feathers_counter","frame":10,"ssim":0.999941,"tile":1,"bevy":{"batch_keys":0,"entities":493,"extents":[],"frame":10,"frame_ms":47.404,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.734,"step_ms":null,"cost_ms":2.734},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/widgets/feathers_number_input","frame":10,"ssim":0.997483,"tile":6,"bevy":{"batch_keys":0,"entities":972,"extents":[],"frame":10,"frame_ms":48.5,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.029,"step_ms":null,"cost_ms":3.029},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/widgets/feathers_gallery","frame":10,"ssim":0.995606,"tile":9,"bevy":{"batch_keys":0,"entities":1060,"extents":[],"frame":10,"frame_ms":82.162,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":2.866,"step_ms":null,"cost_ms":2.866},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
@@ -155,5 +153,7 @@
{"example":"ui/ui_material","frame":10,"ssim":0.999993,"tile":0,"bevy":{"batch_keys":0,"entities":446,"extents":[],"frame":10,"frame_ms":46.877,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":502,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.374,"step_ms":null,"cost_ms":3.374},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/system_fonts","frame":10,"ssim":0.987943,"tile":18,"bevy":{"batch_keys":0,"entities":1992,"extents":[],"frame":10,"frame_ms":115.916,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.184,"step_ms":null,"cost_ms":3.184},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"ui/text/font_atlas_debug","frame":10,"ssim":0.999660,"tile":6,"bevy":{"batch_keys":0,"entities":445,"extents":[],"frame":10,"frame_ms":45.934,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.204,"step_ms":null,"cost_ms":3.204},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
-{"example":"3d/two_passes","frame":10,"ssim":0.999025,"tile":0,"bevy":{"batch_keys":2,"entities":444,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":58.492,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":17,"entities":505,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":4.378,"step_ms":null,"cost_ms":4.378},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
{"example":"3d/split_screen","frame":10,"ssim":0.998973,"tile":5,"bevy":{"batch_keys":2,"entities":546,"extents":["12.5927 39.5145 77.3599","50.0000 0.0000 50.0000"],"frame":10,"frame_ms":55.168,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":20,"entities":537,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["12.5927 39.5145 77.3599","50.0000 0.0000 50.0000"],"frame_ms":6.114,"step_ms":null,"cost_ms":6.114},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"ui/widgets/standard_widgets_observers","frame":10,"ssim":0.998736,"tile":14,"bevy":{"batch_keys":0,"entities":473,"extents":[],"frame":10,"frame_ms":66.788,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":4.068,"step_ms":null,"cost_ms":4.068},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"3d/two_passes","frame":10,"ssim":0.999025,"tile":0,"bevy":{"batch_keys":2,"entities":444,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame":10,"frame_ms":85.672,"materials":3,"mesh_entities":2,"meshes":7,"other_material":0,"visible":2},"raea":{"frame":17,"entities":505,"mesh_entities":2,"visible":2,"meshes":9,"materials":3,"batch_keys":2,"other_material":0,"extents":["0.5000 0.5000 0.5000","2.5000 0.0000 2.5000"],"frame_ms":6.572,"step_ms":null,"cost_ms":6.572},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
+{"example":"ui/widgets/standard_widgets","frame":10,"ssim":0.994691,"tile":17,"bevy":{"batch_keys":0,"entities":487,"extents":[],"frame":10,"frame_ms":63.168,"materials":1,"mesh_entities":0,"meshes":5,"other_material":0,"visible":0},"raea":{"frame":17,"entities":500,"mesh_entities":0,"visible":0,"meshes":7,"materials":1,"batch_keys":0,"other_material":0,"extents":[],"frame_ms":3.666,"step_ms":null,"cost_ms":3.666},"pixels":true,"draws":true,"time":true,"pass":true,"why":""}
diff --git a/engine/page/src/motion/read.rs b/engine/page/src/motion/read.rs
index ddb570a9..55064b95 100644
--- a/engine/page/src/motion/read.rs
+++ b/engine/page/src/motion/read.rs
@@ -133,6 +133,22 @@ impl BlitzPage {
}
}
+ /// Every element the ops made from the one topmost at the point (page px) up to the root, innermost first: the
+ /// path a pointer event there bubbles along.
+ pub fn hit_path(&mut self, x: f32, y: f32) -> Vec<u64> {
+ let docs = self.app.world().non_send::<Docs>();
+ let Some(doc) = docs.0.get(&self.page) else { return Vec::new() };
+ let mut out = Vec::new();
+ let mut n = doc.hit(x, y).map(|h| h.node_id);
+ while let Some(at) = n {
+ if let Some(id) = self.nodes.id_of(at).filter(|id| *id != 0) {
+ out.push(id);
+ }
+ n = doc.get_node(at).and_then(|d| d.parent);
+ }
+ out
+ }
+
/// Each element's box as last laid out, [x, y, w, h] in page px, by its path.
pub fn boxes(&mut self) -> Vec<(String, [f32; 4])> {
let docs = self.app.world().non_send::<Docs>();
diff --git a/runtime/live/src/lib.rs b/runtime/live/src/lib.rs
index 194cfec1..8613e4ec 100644
--- a/runtime/live/src/lib.rs
+++ b/runtime/live/src/lib.rs
@@ -14,6 +14,7 @@ use raea_runtime_react::{ReactOutbox, ReactPlugin};
mod open;
mod sound;
+mod pointer;
pub use sound::warm_audio;
mod draw;
@@ -55,6 +56,8 @@ pub struct Live {
frame: i64,
/// the gamepads' marked keys the last frame was given beside its input ("Pad0:South"), for its input log
pads: Vec<String>,
+ /// the pointer on the page's elements, as the last frame left it (pointer.rs)
+ pointer: pointer::PagePointer,
/// generated sounds' files, by what they were made from (looked up once)
made: std::collections::HashMap<String, Option<PathBuf>>,
/// the frame's sounds, kept between frames (ZeroHeap)
@@ -199,6 +202,13 @@ impl Live {
None => None,
};
let keys = routed.as_deref().unwrap_or(keys);
+ // the pointer on the page's elements: their on* handlers, before the frame's step (pointer.rs)
+ if let Some(p) = pointer {
+ let path = self.page.hit_path(p.0 as f32, p.1 as f32);
+ for m in self.pointer.step(p, path) {
+ self.app.world().resource::<ReactOutbox>().send(m);
+ }
+ }
self.app.world().resource::<ReactOutbox>().send_raw(frame_event(f, keys, pointer, Some(self.session)));
raea_runtime_react::scene::settle(&mut self.app, Some(f), 5.0)?;
// a game's 3D: this frame's scene, as it was just computed, set on the live engine
diff --git a/runtime/live/src/open.rs b/runtime/live/src/open.rs
index 75be8c88..364f3da8 100644
--- a/runtime/live/src/open.rs
+++ b/runtime/live/src/open.rs
@@ -65,7 +65,7 @@ impl Live {
let (w, h) = if responsive { (stage.0.max(1), stage.1.max(1)) } else { (cw, ch) };
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
- let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
+ let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
if responsive {
live.send("raea-size", json!({"w": w, "h": h}));
}
@@ -117,7 +117,7 @@ impl Live {
raea_runtime_react::scene::one_thread(&mut app);
let page = raea_runtime_page::BevyPage::new(w, h, &dir)?;
let brand = raea_runtime_react::scene::page_css(&dir, w, &js);
- let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
+ let mut live = Live { app, dir: dir.clone(), page, brand, dirty: true, mixer: None, mixer_failed: false, lag: (0.0, std::time::Instant::now()), w, h, fps, frames, responsive: false, js, master: None, master_wav: None, game_master: None, game_gain: None, scene_rx: None, scene: None, live3d: None, frame: 0, pads: Vec::new(), pointer: Default::default(), made: Default::default(), sound_buf: Vec::new(), holders: Vec::new(), baked: None, applied: -1, session: new_session() };
for b in &baked.init {
live.app.world().resource::<raea_runtime_react::ReplayFeed>().feed(b.clone());
}
diff --git a/runtime/live/src/pointer.rs b/runtime/live/src/pointer.rs
new file mode 100644
index 00000000..57e9f3e9
--- /dev/null
+++ b/runtime/live/src/pointer.rs
@@ -0,0 +1,76 @@
+//! The play's pointer on the page's elements (docs/control.feature FC0a, FC3c): each frame's pointer, a window's or
+//! `--input-script`'s "Pointer:X:Y[:down]", hit tested on the page as last laid out, its events sent to the React
+//! elements' on* handlers as a browser fires them: pointerOut and pointerOver along the old and new paths when the
+//! element under it changes, pointerLeave and pointerEnter on the elements left and entered (innermost left first,
+//! outermost entered first), pointerMove when it moves, pointerDown and pointerUp on the button's edges, and click on
+//! the elements both the press and the release were over. Each goes to every element up the path (bevy-react runs
+//! the ones that have that handler), as `{"t": "uiEvent"}` (runtime/react pointer.rs), before the frame's step.
+
+use serde_json::{Value, json};
+
+/// The page pointer as the last frame left it.
+#[derive(Default)]
+pub(crate) struct PagePointer {
+ at: Option<(f64, f64)>,
+ path: Vec<u64>,
+ down: Option<Vec<u64>>,
+}
+
+impl PagePointer {
+ /// This frame's events for a pointer at `(x, y, down)` over `path` (the elements under it, innermost first).
+ pub(crate) fn step(&mut self, (x, y, down): (f64, f64, bool), path: Vec<u64>) -> Vec<Value> {
+ let mut out = Vec::new();
+ let mut send = |ids: &mut dyn Iterator<Item = &u64>, kind: &str| {
+ for id in ids {
+ out.push(json!({"t": "uiEvent", "event": {"id": id, "kind": kind, "x": x, "y": y, "button": 0}}));
+ }
+ };
+ if self.path.first() != path.first() {
+ send(&mut self.path.iter(), "pointerOut");
+ send(&mut self.path.iter().filter(|id| !path.contains(id)), "pointerLeave");
+ send(&mut path.iter(), "pointerOver");
+ send(&mut path.iter().rev().filter(|id| !self.path.contains(id)), "pointerEnter");
+ }
+ if self.at.is_some_and(|a| a != (x, y)) {
+ send(&mut path.iter(), "pointerMove");
+ }
+ match (down, self.down.take()) {
+ (true, None) => {
+ send(&mut path.iter(), "pointerDown");
+ self.down = Some(path.clone());
+ }
+ (true, held) => self.down = held,
+ (false, Some(pressed)) => {
+ send(&mut path.iter(), "pointerUp");
+ send(&mut path.iter().filter(|id| pressed.contains(id)), "click");
+ }
+ (false, None) => {}
+ }
+ self.at = Some((x, y));
+ self.path = path;
+ out
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn kinds(v: &[Value]) -> Vec<(String, u64)> {
+ v.iter().map(|m| (m["event"]["kind"].as_str().unwrap().to_string(), m["event"]["id"].as_u64().unwrap())).collect()
+ }
+
+ #[test]
+ fn a_browsers_order_over_enter_down_up_click() {
+ let mut p = PagePointer::default();
+ let k = |s: &str, id: u64| (s.to_string(), id);
+ // onto a child (5) of 3: over bubbles, enter from the outside in
+ assert_eq!(kinds(&p.step((10.0, 10.0, false), vec![5, 3])), vec![k("pointerOver", 5), k("pointerOver", 3), k("pointerEnter", 3), k("pointerEnter", 5)]);
+ // pressed on 5, released on its parent 3 alone: the click is 3's
+ assert_eq!(kinds(&p.step((10.0, 10.0, true), vec![5, 3])), vec![k("pointerDown", 5), k("pointerDown", 3)]);
+ let up = kinds(&p.step((20.0, 10.0, false), vec![3]));
+ assert_eq!(up, vec![k("pointerOut", 5), k("pointerOut", 3), k("pointerLeave", 5), k("pointerOver", 3), k("pointerMove", 3), k("pointerUp", 3), k("click", 3)]);
+ // still: nothing
+ assert!(p.step((20.0, 10.0, false), vec![3]).is_empty());
+ }
+}
diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rs
index dddfe234..0b8a99bc 100644
--- a/runtime/page/src/bevy_page.rs
+++ b/runtime/page/src/bevy_page.rs
@@ -180,6 +180,18 @@ impl BevyPage {
self.page.hit(x, y).map(|id| id & !TEXT_BIT).filter(|id| *id >= REACT_IDS).map(|id| id - REACT_IDS)
}
+ /// The React elements under the point (page px), the topmost first and then each one up to the root: the path a
+ /// pointer event there bubbles along (live play's page pointer).
+ pub fn hit_path(&mut self, x: f32, y: f32) -> Vec<u64> {
+ let mut out: Vec<u64> = Vec::new();
+ for id in self.page.hit_path(x, y).into_iter().map(|id| id & !TEXT_BIT).filter(|id| *id >= REACT_IDS).map(|id| id - REACT_IDS) {
+ if out.last() != Some(&id) {
+ out.push(id);
+ }
+ }
+ out
+ }
+
/// Each element's box as last laid out ([x, y, w, h] in page px), by its path among the page's elements.
pub fn boxes(&mut self) -> Vec<(String, [f32; 4])> {
self.page.boxes()
diff --git a/runtime/page/src/elements.rs b/runtime/page/src/elements.rs
index 9f293d5e..092447e2 100644
--- a/runtime/page/src/elements.rs
+++ b/runtime/page/src/elements.rs
@@ -237,8 +237,9 @@ pub(crate) fn page_props(kind: &str, props: Option<&Map<String, Value>>, dir: &P
// blends in linear light, systems/page paint; a bevy_ui scroller's data-raea-bevy-scroll and an IgnoreScroll node's
// data-raea-bevy-ignore-scroll kept: Blitz floors its offset and keeps the node in place, vendor/blitz-dom resolve.rs;
// a spreading box shadow's data-raea-bevy-shadow kept: Blitz spreads it as bevy_ui does, vendor/blitz-paint render/box_shadow.rs;
+ // a Popover's data-raea-bevy-popover kept: Blitz places it beside its parent after layout, vendor/blitz-dom bevy_popover.rs;
// the source stamps data-raea-loc and data-raea-use kept for the render manifest, engine/bundle stamp.rs)
- const KEPT: [&str; 13] = ["data-raea-start", "data-raea-bevy-debug", "data-raea-bevy-shadow", "data-raea-bevy-text", "data-raea-bevy-slice", "data-raea-bevy-global-z", "data-raea-blend", "data-raea-bevy-scroll", "data-raea-bevy-ignore-scroll", "data-raea-bevy-scrollbar", "data-raea-bevy-thumb", "data-raea-loc", "data-raea-use"];
+ const KEPT: [&str; 14] = ["data-raea-start", "data-raea-bevy-debug", "data-raea-bevy-popover", "data-raea-bevy-shadow", "data-raea-bevy-text", "data-raea-bevy-slice", "data-raea-bevy-global-z", "data-raea-blend", "data-raea-bevy-scroll", "data-raea-bevy-ignore-scroll", "data-raea-bevy-scrollbar", "data-raea-bevy-thumb", "data-raea-loc", "data-raea-use"];
if k == "children" || k == "key" || (k.starts_with("data-raea") && !KEPT.contains(&k.as_str())) || k == "data-props" || k == "data-shape" || k == "data-anim" || v.is_null() {
continue;
}
diff --git a/sdk/raea/bench/bevy-parity/ui/widgets/standard_widgets.tsx b/sdk/raea/bench/bevy-parity/ui/widgets/standard_widgets.tsx
index 1ced1376..7e1db509 100644
--- a/sdk/raea/bench/bevy-parity/ui/widgets/standard_widgets.tsx
+++ b/sdk/raea/bench/bevy-parity/ui/widgets/standard_widgets.tsx
@@ -9,11 +9,16 @@
// radio matching DemoWidgetStates' Snap; a 200 x 65 menu Button (5 px black border, 5 px corners, 16 px padding each
// side, its items spaced between) holding "Menu" as the Button's text and a 12 px gray square; and "Press 'D' to
// toggle widget disabled states" in Bevy's default font. The menu's popup opens, and hover, presses and 'D' change
-// the widgets, only under input. Bevy's Camera2d over the default clear colour is the layered <Canvas3D>, in Bevy's
+// the widgets under input: the Button reads "Hover" on srgb(0.25, 0.25, 0.25) with a white border while the pointer is over
+// it and "Press" on srgb(0.35, 0.75, 0.35) with a red one while pressed there; activating the menu button toggles its
+// popup (spawn_menu: a GRAY column, 1 px GREEN border, its shadow, GlobalZIndex 100, placed by its Popover below the
+// anchor, else above, 2 px off, 10 px from the window's edge) of four "Menu Item"s, each lit while hovered and green
+// while pressed; activating one closes it. The slider, checkbox, radios and 'D' respond to input in Bevy only. Bevy's Camera2d over the default clear colour is the layered <Canvas3D>, in Bevy's
// default 1280 x 720 window.
+import { useState } from "react";
import { AbsoluteFill, Composition, registerRoot, staticFile } from "raea";
import { Canvas3D } from "raea/3d";
-import { BorderRadius, Node, Text, TextShadow, UiRect, percent, px } from "raea/ui";
+import { BorderRadius, BoxShadow, Node, Text, TextShadow, UiRect, percent, px } from "raea/ui";
import { Srgba } from "raea/color";
const BOLD = "fonts/FiraSans-Bold.ttf";
@@ -21,6 +26,62 @@ const OUTLINE = new Srgba(0.45, 0.45, 0.45);
const FILL = new Srgba(0.35, 0.75, 0.35);
const NONE = new Srgba(0, 0, 0, 0);
const GRAY = new Srgba(0.5019608, 0.5019608, 0.5019608);
+// basic::GREEN, and the example's button colours
+const GREEN = new Srgba(0, 0.5019608, 0);
+const NORMAL_BUTTON = new Srgba(0.15, 0.15, 0.15);
+const HOVERED_BUTTON = new Srgba(0.25, 0.25, 0.25);
+const PRESSED_BUTTON = new Srgba(0.35, 0.75, 0.35);
+const LABEL = { font: staticFile(BOLD), font_size: { Px: 33 }, color: new Srgba(0.9, 0.9, 0.9), shadow: TextShadow.default() } as const;
+
+/** Hovered (the pointer over it or what's in it) and Pressed (pressed on it, until the release), as bevy_picking and
+ * bevy_ui_widgets' Button keep them, and their handlers */
+function useHoverPress() {
+ const [hovered, setHovered] = useState(false);
+ const [pressed, setPressed] = useState(false);
+ const on = { onPointerEnter: () => setHovered(true), onPointerLeave: () => setHovered(false), onPointerDown: () => setPressed(true), onPointerUp: () => setPressed(false) };
+ return { hovered, pressed, on };
+}
+
+/** DemoButton, styled by set_button_style */
+function DemoButton() {
+ const { hovered, pressed, on } = useHoverPress();
+ const [text, bg, border] = hovered && pressed ? ["Press", PRESSED_BUTTON, new Srgba(1, 0, 0)] : hovered ? ["Hover", HOVERED_BUTTON, new Srgba(1, 1, 1)] : ["Button", NORMAL_BUTTON, new Srgba(0, 0, 0)];
+ return (
+ <Node width={px(150)} height={px(65)} border={UiRect.all(px(5))} border_radius={BorderRadius.MAX} justify_content="Center" align_items="Center" border_color={border} background_color={bg} {...on}>
+ <Text {...LABEL}>{text}</Text>
+ </Node>
+ );
+}
+
+/** A DemoMenuItem, styled by set_menu_item_style; activating it closes the menu */
+function MenuItem({ close }: { close: () => void }) {
+ const { hovered, pressed, on } = useHoverPress();
+ return (
+ <Node padding={UiRect.axes(px(8), px(2))} justify_content="Center" align_items="Start" background_color={hovered ? (pressed ? PRESSED_BUTTON : HOVERED_BUTTON) : NORMAL_BUTTON} {...on} onClick={close}>
+ <Text {...LABEL}>Menu Item</Text>
+ </Node>
+ );
+}
+
+/** The DemoMenuAnchor: its MenuButton toggles the popup spawn_menu makes */
+function Menu() {
+ const [open, setOpen] = useState(false);
+ return (
+ <Node>
+ <Node width={px(200)} height={px(65)} border={UiRect.all(px(5))} box_sizing="BorderBox" justify_content="SpaceBetween" align_items="Center" padding={UiRect.axes(px(16), px(0))} border_radius={BorderRadius.all(px(5))} border_color={new Srgba(0, 0, 0)} background_color={NORMAL_BUTTON} onClick={() => setOpen((o) => !o)}>
+ <Text {...LABEL}>Menu</Text>
+ <Node width={px(12)} height={px(12)} background_color={GRAY} />
+ </Node>
+ {open && (
+ <Node display="Flex" flex_direction="Column" min_height={px(10)} min_width={percent(100)} border={UiRect.all(px(1))} position_type="Absolute" border_color={GREEN} background_color={GRAY}
+ box_shadow={BoxShadow.new(new Srgba(0, 0, 0, 0.9), px(0), px(0), px(1), px(4))} global_z_index={100}
+ popover={{ positions: [{ side: "Bottom", align: "Start", gap: 2 }, { side: "Top", align: "Start", gap: 2 }], window_margin: 10 }}>
+ {[0, 1, 2, 3].map((i) => <MenuItem key={i} close={() => setOpen(false)} />)}
+ </Node>
+ )}
+ </Node>
+ );
+}
/** a checkbox or radio: its 16 px box with an 8 px mark (cleared unless checked) beside its caption */
function Toggle({ caption, round, checked }: { caption: string; round: boolean; checked: boolean }) {
@@ -39,9 +100,7 @@ function Shot() {
<AbsoluteFill>
<Canvas3D layered clearColor="rgb(43, 44, 47)" />
<Node width={percent(100)} height={percent(100)} align_items="Center" justify_content="Center" display="Flex" flex_direction="Column" row_gap={px(10)}>
- <Node width={px(150)} height={px(65)} border={UiRect.all(px(5))} border_radius={BorderRadius.MAX} justify_content="Center" align_items="Center" border_color={new Srgba(0, 0, 0)} background_color={new Srgba(0.15, 0.15, 0.15)}>
- <Text font={staticFile(BOLD)} font_size={{ Px: 33 }} color={new Srgba(0.9, 0.9, 0.9)} shadow={TextShadow.default()}>Button</Text>
- </Node>
+ <DemoButton />
<Node display="Flex" flex_direction="Column" justify_content="Center" align_items="Stretch" justify_items="Center" column_gap={px(4)} height={px(12)} width={percent(30)}>
<Node height={px(6)} border_radius={BorderRadius.all(px(3))} background_color={new Srgba(0.05, 0.05, 0.05)} />
<Node display="Flex" position_type="Absolute" left={px(0)} right={px(12)} top={px(0)} bottom={px(0)}>
@@ -54,12 +113,7 @@ function Shot() {
<Toggle caption="Slider Step" round checked={false} />
<Toggle caption="Slider Snap" round checked />
</Node>
- <Node>
- <Node width={px(200)} height={px(65)} border={UiRect.all(px(5))} box_sizing="BorderBox" justify_content="SpaceBetween" align_items="Center" padding={UiRect.axes(px(16), px(0))} border_radius={BorderRadius.all(px(5))} border_color={new Srgba(0, 0, 0)} background_color={new Srgba(0.15, 0.15, 0.15)}>
- <Text font={staticFile(BOLD)} font_size={{ Px: 33 }} color={new Srgba(0.9, 0.9, 0.9)} shadow={TextShadow.default()}>Menu</Text>
- <Node width={px(12)} height={px(12)} background_color={GRAY} />
- </Node>
- </Node>
+ <Menu />
<Text>Press 'D' to toggle widget disabled states</Text>
</Node>
</AbsoluteFill>
diff --git a/sdk/raea/conformance/ui-pick.test.tsx b/sdk/raea/conformance/ui-pick.test.tsx
new file mode 100644
index 00000000..284d355c
--- /dev/null
+++ b/sdk/raea/conformance/ui-pick.test.tsx
@@ -0,0 +1,25 @@
+// A bevy_ui node's picking handlers and bevy_ui_widgets' Popover (docs/control.feature FC0a, FC3c: ui/widgets/
+// standard_widgets' menu): what the node's element carries for the page.
+import { describe, expect, test } from "bun:test";
+import { Node, px } from "raea/ui";
+import { renderFrame } from "../src/test";
+
+const html = (el: React.ReactElement) => renderFrame(el, { frame: 0, width: 320, height: 240, fps: 60, durationInFrames: 1 });
+
+describe("Popover", () => {
+ test("carries its window margin and placements, defaults filled, and is absolute", () => {
+ const out = html(<Node><Node width={px(10)} popover={{ positions: [{ side: "Bottom", align: "Start", gap: 2 }, { side: "Top" }], window_margin: 10 }} /></Node>);
+ expect(out).toContain('data-raea-bevy-popover="10;Bottom Start 2;Top Start 0"');
+ expect(out).toMatch(/position:\s*absolute[^"]*"[^>]*data-raea-bevy-popover/);
+ });
+ test("refuses no placements and an unknown side", () => {
+ expect(() => html(<Node popover={{ positions: [] }} />)).toThrow(/popover/);
+ expect(() => html(<Node popover={{ positions: [{ side: "Middle" as never }] }} />)).toThrow(/positions\[0\]/);
+ });
+});
+
+describe("picking handlers", () => {
+ test("refuses a handler that isn't a function", () => {
+ expect(() => html(<Node onClick={"go" as never} />)).toThrow(/onClick is a function/);
+ });
+});
diff --git a/sdk/raea/src/ui.ts b/sdk/raea/src/ui.ts
index 7d89c99e..47d8e90c 100644
--- a/sdk/raea/src/ui.ts
+++ b/sdk/raea/src/ui.ts
@@ -10,6 +10,7 @@ export { Node, GhostNode, Text, TextSpan, TextShadow, Text2d, UiScale, Viewport,
export { LinearGradient, RadialGradient, ConicGradient, ColorStop, AngularColorStop, UiPosition, type Gradient, type RadialGradientShape, type InterpolationColorSpace } from "@raea/render/bevy3d";
export { GridTrack, RepeatedGridTrack, GridPlacement, type GridTrackRepetition, type GridAutoFlow, type MinTrackSizingFunction, type MaxTrackSizingFunction, FontAtlasSet, type FontAtlas, FontCx, FontSource, type GenericFontFamily } from "@raea/render/bevy3d";
export { Rot2, Val2, UiTransform, BoxShadow, BoxShadowSamples, type ShadowStyle } from "@raea/render/bevy3d";
+export type { Popover, PopoverPlacement } from "@raea/render/bevy3d";
export { MaterialNode, type MaterialNodeProps } from "@raea/render/bevy3d";
export { FontFeatureTag, FontWidth } from "@raea/render/bevy3d";
export { GlobalUiDebugOptions, type UiDebugOptions } from "@raea/render/bevy3d";
diff --git a/sdk/render/src/bevy3d.tsx b/sdk/render/src/bevy3d.tsx
index 9649cd35..3bc363f4 100644
--- a/sdk/render/src/bevy3d.tsx
+++ b/sdk/render/src/bevy3d.tsx
@@ -37,6 +37,7 @@ export { LinearGradient, RadialGradient, ConicGradient, ColorStop, AngularColorS
export { GridTrack, RepeatedGridTrack, GridPlacement, type GridTrackRepetition, type GridAutoFlow, type MinTrackSizingFunction, type MaxTrackSizingFunction } from "./bevy3d/ui-grid";
export { Rot2, Val2, UiTransform, BoxShadow, BoxShadowSamples, type ShadowStyle } from "./bevy3d/ui-transform";
export { MaterialNode, type MaterialNodeProps } from "./bevy3d/ui-material";
+export type { Popover, PopoverPlacement } from "./bevy3d/ui-pick";
export { FontFeatureTag, FontWidth } from "./bevy3d/ui-features";
export { GlobalUiDebugOptions, type UiDebugOptions } from "./bevy3d/ui-debug";
export type { IgnoreScroll } from "./bevy3d/ui-scroll";
diff --git a/sdk/render/src/bevy3d/ui-pick.ts b/sdk/render/src/bevy3d/ui-pick.ts
new file mode 100644
index 00000000..44628845
--- /dev/null
+++ b/sdk/render/src/bevy3d/ui-pick.ts
@@ -0,0 +1,81 @@
+// bevy_picking on a bevy_ui node, and bevy_ui_widgets' Popover (docs/control.feature FC0a, FC3c: ui/widgets'
+// menus). A node's pointer events are Bevy's picking events as React spells them, the same set a 3D part takes
+// (events3d.tsx, docs/sdk.feature S3a): Pointer<Click> is onClick, Pointer<Press> onPointerDown, Pointer<Over>
+// onPointerOver. In a render they come from the composition's input timeline, in play from the pointer (a window's,
+// or --input-script's): the page hit tests the pointer and fires them in a browser's order (runtime/live pointer.rs).
+
+/** One of a Popover's placements beside its parent. @bevy bevy_ui_widgets::popover::PopoverPlacement */
+export interface PopoverPlacement {
+ /** PopoverSide: Bottom by default */
+ side?: "Top" | "Bottom" | "Left" | "Right";
+ /** PopoverAlign: which edges line up along that side, Start by default */
+ align?: "Start" | "End" | "Center";
+ /** the gap from the parent, in px (0 by default) */
+ gap?: number;
+}
+
+/** A popup placed beside its parent's box (inside its border) after layout, at the first of `positions` the window
+ * (less `window_margin` px) hides least; absolutely positioned, as Bevy's position_popover makes it.
+ * @bevy bevy_ui_widgets::popover::Popover */
+export interface Popover {
+ positions: PopoverPlacement[];
+ window_margin?: number;
+}
+
+/** The pointer event a handler gets: the pointer in page px and the button (0 primary, 1 middle, 2 secondary). */
+export interface UiPointerEvent {
+ id: number;
+ kind: string;
+ x: number;
+ y: number;
+ button?: number;
+}
+
+type On = (e: UiPointerEvent) => void;
+
+/** A node's bevy_picking events and its Popover. */
+export interface PickProps {
+ popover?: Popover;
+ onClick?: On;
+ onPointerDown?: On;
+ onPointerUp?: On;
+ onPointerOver?: On;
+ onPointerOut?: On;
+ onPointerEnter?: On;
+ onPointerLeave?: On;
+ onPointerMove?: On;
+}
+
+const HANDLERS = ["onClick", "onPointerDown", "onPointerUp", "onPointerOver", "onPointerOut", "onPointerEnter", "onPointerLeave", "onPointerMove"] as const;
+
+/** The node's handlers, for its element. */
+export function handlersOf(who: string, p: PickProps): Record<string, On> {
+ const out: Record<string, On> = {};
+ for (const k of HANDLERS) {
+ const f = p[k];
+ if (f === undefined) continue;
+ if (typeof f !== "function") throw new TypeError(`${who}: ${k} is a function, got ${JSON.stringify(f)}`);
+ out[k] = f;
+ }
+ return out;
+}
+
+/** The Popover's attribute (raea's Blitz places it after layout, bevy_popover.rs), and its position made absolute. */
+export function popoverAttr(who: string, p: PickProps, s: Record<string, unknown>, attrs: Record<string, string | number>) {
+ const pop = p.popover;
+ if (pop === undefined) return;
+ if (!pop || !Array.isArray(pop.positions) || pop.positions.length === 0) throw new TypeError(`${who}: popover is { positions: [{ side, align, gap }, ...], window_margin }, got ${JSON.stringify(pop)}`);
+ const margin = pop.window_margin ?? 0;
+ if (!Number.isFinite(margin)) throw new RangeError(`${who}: popover.window_margin is a number of px, got ${margin}`);
+ const at = pop.positions.map((q, i) => {
+ const side = q.side ?? "Bottom";
+ const align = q.align ?? "Start";
+ const gap = q.gap ?? 0;
+ if (!["Top", "Bottom", "Left", "Right"].includes(side) || !["Start", "End", "Center"].includes(align) || !Number.isFinite(gap)) {
+ throw new TypeError(`${who}: popover.positions[${i}] is { side: Top|Bottom|Left|Right, align: Start|End|Center, gap: px }, got ${JSON.stringify(q)}`);
+ }
+ return `${side} ${align} ${gap}`;
+ });
+ attrs["data-raea-bevy-popover"] = [String(margin), ...at].join(";");
+ s.position = "absolute";
+}
diff --git a/sdk/render/src/bevy3d/ui.tsx b/sdk/render/src/bevy3d/ui.tsx
index e7353cb4..9aec7ecb 100644
--- a/sdk/render/src/bevy3d/ui.tsx
+++ b/sdk/render/src/bevy3d/ui.tsx
@@ -14,6 +14,7 @@ import { gradientsCss, gradientsOpaque, type Gradient } from "./ui-gradient";
import { gridCss, type GridAutoFlow, type GridPlacement, type GridTrack, type RepeatedGridTrack } from "./ui-grid";
import { ShadowSamplesCx, shadowCss, transformCss, type BoxShadow, type UiTransform } from "./ui-transform";
import { featuresCss } from "./ui-features";
+import { handlersOf, popoverAttr, type PickProps } from "./ui-pick";
import { scrollCss, type IgnoreScroll } from "./ui-scroll";
import { useDebugAttr, type UiDebugOptions } from "./ui-debug";
import type { TransformValue } from "./core";
@@ -24,7 +25,7 @@ type Color = Srgba | LinearRgba | string;
/** bevy_ui's Node: its layout fields as Bevy names them (each Bevy's default when left out), and the components that
* draw it: background_color (BackgroundColor), border_color (BorderColor, every side), z_index (ZIndex). */
-export interface NodeProps {
+export interface NodeProps extends PickProps {
/** bevy_ecs's Name, as a Scrollbar's target names its scroller (the element's id) */
name?: string;
/** UiDebugOptions: this node's debug overlay, in place of the GlobalUiDebugOptions it's in */
@@ -141,6 +142,7 @@ export function nodeCss(who: string, p: NodeProps, back?: Backdrop, scale = 1):
const attrs: Record<string, string | number> = p.global_z_index ? { "data-raea-bevy-global-z": "" } : {};
// every shadow drawn as bevy_ui draws it (its spread, its blur summed in BoxShadowSamples steps), raea's Blitz box_shadow.rs
if (p.box_shadow !== undefined && p.box_shadow.length) attrs["data-raea-bevy-shadow"] = String(samples);
+ popoverAttr(who, p, s as Record<string, unknown>, attrs);
if (p.margin !== undefined) s.margin = rectCss(who, "margin", p.margin);
if (p.padding !== undefined) s.padding = rectCss(who, "padding", p.padding);
if (p.border !== undefined) {
@@ -210,7 +212,7 @@ export function nodeCss(who: string, p: NodeProps, back?: Backdrop, scale = 1):
// a root's implicit viewport (bevy_ui ui_surface.rs): a grid the window's size, its one item at the start of both axes
export const VIEWPORT: CSSProperties = { position: "absolute", left: 0, top: 0, width: "100%", height: "100%", display: "grid", alignItems: "start", justifyItems: "start" };
-export function boxOf(css: CSSProperties, back: Backdrop, children: ReactNode, root: boolean | "fixed", font?: ReactNode, attrs?: Record<string, string | number>) {
+export function boxOf(css: CSSProperties, back: Backdrop, children: ReactNode, root: boolean | "fixed", font?: ReactNode, attrs?: Record<string, unknown>) {
const inner = (
<div style={css} {...attrs}>
<InUi.Provider value={{ back }}>{children}</InUi.Provider>
@@ -225,7 +227,7 @@ export function boxOf(css: CSSProperties, back: Backdrop, children: ReactNode, r
export function Node({ children, fixed, ...p }: NodeProps) {
const ui = useContext(InUi);
const n = nodeCss("Node", p, ui?.back, useContext(UiScaleCx));
- return boxOf(n.css, n.back, children, fixed ? "fixed" : ui === null, undefined, n.attrs);
+ return boxOf(n.css, n.back, children, fixed ? "fixed" : ui === null, undefined, { ...n.attrs, ...handlersOf("Node", p) });
}
/** bevy_ui's GhostNode: no box of its own, its children laid out as its parent's (CSS display: contents), each one a
diff --git a/systems/parity/Cargo.toml b/systems/parity/Cargo.toml
index 0d115b02..56671f6f 100644
--- a/systems/parity/Cargo.toml
+++ b/systems/parity/Cargo.toml
@@ -7,5 +7,5 @@ publish = false
description = "The parity probe (docs/control.feature FC0a): what a frame cost and what the World held, written as JSON lines at chosen frames, the same plugin in a Bevy example and in raea, off unless RAEA_PARITY is set"
[dependencies]
-bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "ui_bevy_render"] }
+bevy = { version = "=0.20.0", default-features = false, features = ["std", "default_app", "3d_bevy_render", "ui_bevy_render", "bevy_picking"] }
serde_json = "1"
diff --git a/systems/parity/src/input.rs b/systems/parity/src/input.rs
new file mode 100644
index 00000000..f1e4cc8d
--- /dev/null
+++ b/systems/parity/src/input.rs
@@ -0,0 +1,65 @@
+//! Scripted input for an interactive example (docs/control.feature FC0a: "scripted input for an interactive one"):
+//! RAEA_PARITY_INPUT=FILE, the script `raea play --input-script` takes, {"FRAME": [keys], ...}, each entry held from
+//! the update numbered FRAME (the probe's count) until the next. "Pointer:X:Y" puts the mouse pointer at X, Y in the
+//! window's logical px, ":down" while its primary button is held; the pointer is bevy_picking's, written as the
+//! PointerInput messages a mouse sends (a Move when it moves, a Press and a Release on the button's edges), on the
+//! picture the cameras draw into (the offscreen image while pictures are taken, else the primary window).
+
+use std::collections::BTreeMap;
+
+use bevy::camera::RenderTarget;
+use bevy::picking::pointer::{Location, PointerAction, PointerButton, PointerId, PointerInput};
+use bevy::prelude::*;
+use bevy::window::PrimaryWindow;
+
+#[derive(Resource)]
+pub(crate) struct Script {
+ at: BTreeMap<u64, Vec<String>>,
+ pointer: Option<(Vec2, bool)>,
+}
+
+/// The script at RAEA_PARITY_INPUT, if set; a script that can't be read ends the run, as the port's would.
+pub(crate) fn load() -> Option<Script> {
+ let p = std::env::var("RAEA_PARITY_INPUT").ok()?;
+ let text = std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("RAEA_PARITY_INPUT {p}: {e}"));
+ let at: BTreeMap<u64, Vec<String>> = serde_json::from_str(&text).unwrap_or_else(|e| panic!("RAEA_PARITY_INPUT {p}: {{\"FRAME\": [keys]}}: {e}"));
+ Some(Script { at, pointer: None })
+}
+
+/// "Pointer:X:Y[:down]" among an entry's keys
+fn pointer_of(keys: &[String]) -> Option<(Vec2, bool)> {
+ keys.iter().find_map(|k| {
+ let p: Vec<&str> = k.strip_prefix("Pointer:")?.split(':').collect();
+ let (x, y) = (p.first()?.parse().ok()?, p.get(1)?.parse().ok()?);
+ Some((Vec2::new(x, y), p.get(2) == Some(&"down")))
+ })
+}
+
+/// This update's pointer, as PointerInput messages, before bevy_picking reads them in PreUpdate.
+pub(crate) fn scripted(
+ mut s: ResMut<Script>,
+ probe: Res<super::Probe>,
+ offscreen: Option<Res<super::Offscreen>>,
+ window: Query<Entity, With<PrimaryWindow>>,
+ mut out: MessageWriter<PointerInput>,
+) {
+ let Some(now) = s.at.range(..=probe.frame).next_back().and_then(|(_, k)| pointer_of(k)) else { return };
+ let target = match &offscreen {
+ Some(o) => RenderTarget::Image(o.0.clone().into()).normalize(None),
+ None => RenderTarget::Window(bevy::window::WindowRef::Primary).normalize(window.single().ok()),
+ };
+ let Some(target) = target else { return };
+ let location = Location { target, position: now.0 };
+ let was = s.pointer;
+ if was.map(|w| w.0) != Some(now.0) {
+ let delta = was.map_or(Vec2::ZERO, |w| now.0 - w.0);
+ out.write(PointerInput::new(PointerId::Mouse, location.clone(), PointerAction::Move { delta }));
+ }
+ let held = was.is_some_and(|w| w.1);
+ if now.1 && !held {
+ out.write(PointerInput::new(PointerId::Mouse, location.clone(), PointerAction::Press(PointerButton::Primary)));
+ } else if !now.1 && held {
+ out.write(PointerInput::new(PointerId::Mouse, location, PointerAction::Release(PointerButton::Primary)));
+ }
+ s.pointer = Some(now);
+}
diff --git a/systems/parity/src/lib.rs b/systems/parity/src/lib.rs
index 2b1836c9..17995589 100644
--- a/systems/parity/src/lib.rs
+++ b/systems/parity/src/lib.rs
@@ -8,6 +8,7 @@
//! RAEA_PARITY_EXIT=1 exit a few frames after the last probed frame (the screenshot's readback lands first)
//! RAEA_PARITY_TYPES=A,B also each listed Bevy type's value on every entity that has it, reflected as Bevy
//! serializes it, one line a probed frame in FILE.world.jsonl (FC0c's defaults test)
+//! RAEA_PARITY_INPUT=FILE scripted input, the script `raea play --input-script` takes (input.rs)
//!
//! A line holds what decides a frame's cost, read from the main World:
//! entities every entity
@@ -32,6 +33,8 @@ use bevy::prelude::*;
use bevy::render::view::window::screenshot::{Screenshot, save_to_disk};
use bevy::time::TimeUpdateStrategy;
+mod input;
+
#[derive(Resource)]
struct Probe {
out: PathBuf,
@@ -71,6 +74,10 @@ pub fn install(app: &mut App) {
app.add_systems(First, offscreen);
app.add_systems(PreUpdate, no_input.after(bevy::input::InputSystems));
}
+ if let Some(script) = input::load() {
+ app.insert_resource(script);
+ app.add_systems(First, input::scripted);
+ }
app.insert_resource(Probe { out: out.into(), frames, png, exit, types, frame: 0, since: Instant::now(), ticks: 0 });
app.add_systems(Last, (probe, dump).chain());
}
diff --git a/tools/bevy-parity b/tools/bevy-parity
index ceed1a02..ec3a927b 100755
--- a/tools/bevy-parity
+++ b/tools/bevy-parity
@@ -10,6 +10,10 @@
# world (not yet: entities and components over BRP)
#
# tools/bevy-parity [PATH ...] default: every row of bench/bevy-parity/runs.tsv
+# A row's fourth column (optional) is an input script for an interactive example, the file `raea play
+# --input-script` takes ({"FRAME": ["Pointer:X:Y:down", keys...]}): the example gets it as RAEA_PARITY_INPUT
+# (systems/parity input.rs, bevy_picking's pointer), and the port's pictures are `raea play`'s under it (its cost
+# still the render's, which has no input)
# tools/bevy-parity --report only rewrite docs/bevy-parity.md from docs/bevy-parity/results.jsonl
# Needs target/release/raea-bevy-parity and raea, built in two cargo runs (lane build -- cargo build --release -p
# raea-bevy-parity, then -p raea-cli --bin raea): the host turns on bevy_winit for Bevy's examples, and one run of both
@@ -65,24 +69,27 @@ report() {
# runs.tsv: path, the example's arguments, the frames probed
rows=()
-while IFS=$'\t' read -r path args frames; do
+while IFS=$'\t' read -r path args frames input; do
[[ -z "$path" || "$path" == \#* ]] && continue
if [ $# -gt 0 ]; then
- for want in "$@"; do [ "$want" = "$path" ] && rows+=("$path"$'\t'"$args"$'\t'"$frames"); done
+ for want in "$@"; do [ "$want" = "$path" ] && rows+=("$path"$'\t'"$args"$'\t'"$frames"$'\t'"${input:--}"); done
else
- rows+=("$path"$'\t'"$args"$'\t'"$frames")
+ rows+=("$path"$'\t'"$args"$'\t'"$frames"$'\t'"${input:--}")
fi
done < "$RUNS"
for row in "${rows[@]}"; do
- IFS=$'\t' read -r path args frames <<< "$row"
+ IFS=$'\t' read -r path args frames input <<< "$row"
[ "$args" = - ] && args=""
+ [ "$input" = - ] && input=""
+ inenv=()
+ [ -n "$input" ] && inenv=(RAEA_PARITY_INPUT="$ROOT/$input")
d="$OUT/${path//\//__}"
rm -rf "$d"; mkdir -p "$d/bevy" "$d/raea"
echo "== $path ($args) at frames $frames"
# the example as Bevy wrote it
# shellcheck disable=SC2086
- if ! RAEA_PARITY="$d/bevy.jsonl" RAEA_PARITY_FRAMES="$frames" RAEA_PARITY_PNG="$d/bevy" RAEA_PARITY_EXIT=1 \
+ if ! env ${inenv[@]+"${inenv[@]}"} RAEA_PARITY="$d/bevy.jsonl" RAEA_PARITY_FRAMES="$frames" RAEA_PARITY_PNG="$d/bevy" RAEA_PARITY_EXIT=1 \
RAEA_PARITY_EXAMPLE="$path" BEVY_ASSET_ROOT="$BEVY_SRC" "$HOST" $args > "$d/bevy.log" 2>&1; then
echo " the example failed: $(tail -1 "$d/bevy.log")"
fi
@@ -102,6 +109,9 @@ for row in "${rows[@]}"; do
elif ! RAEA_STARTUP_TRACE=$(perl -MTime::HiRes=time -e 'printf "%.1f", time * 1000') RAEA_PARITY="$d/raea-$f.jsonl" \
"$RAEA" render "$tsx" --frame "$f" -o "$d/raea/$f.png" > "$d/raea-$f.log" 2>&1; then
why="${why:+$why; }raea failed: $(grep -iE 'error|refused|panick' "$d/raea-$f.log" | tail -1 | cut -c1-140)"
+ elif [ -n "$input" ] && ! "$RAEA" play "$tsx" --offscreen --size "$(magick identify -format '%wx%h' "$d/bevy/$f.png" 2>/dev/null || echo 1280x720)" --input-script "$ROOT/$input" \
+ --snapshot "$(perl -e "printf '%.4f', $f / 60")" "$d/raea/$f.png" --seconds "$(perl -e "printf '%.4f', ($f + 14) / 60")" > "$d/raea-play-$f.log" 2>&1; then
+ why="${why:+$why; }raea play failed: $(grep -iE 'error|refused|panick' "$d/raea-play-$f.log" | tail -1 | cut -c1-140)"
else
# the counts from the last update before the readback; its time the median update after the first five (the
# last line holds the readback's stall, the first the load)
diff --git a/vendor/blitz-dom/src/bevy_popover.rs b/vendor/blitz-dom/src/bevy_popover.rs
new file mode 100644
index 00000000..f7873adb
--- /dev/null
+++ b/vendor/blitz-dom/src/bevy_popover.rs
@@ -0,0 +1,131 @@
+//! raea: bevy_ui_widgets' Popover after layout (sdk/render's `popover`, `data-raea-bevy-popover`): the popup is moved
+//! next to its parent's box, inside its border, at the first of its placements that the window (less its margin)
+//! hides least, as bevy_ui_widgets' position_popover does after Bevy's layout. Its layout location is what moves, so
+//! it's drawn and hit tested there, as Bevy's UiGlobalTransform is.
+
+use crate::BaseDocument;
+use markup5ever::LocalName;
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum Side {
+ Top,
+ Bottom,
+ Left,
+ Right,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) enum Align {
+ Start,
+ End,
+ Center,
+}
+
+/// `data-raea-bevy-popover="MARGIN;SIDE ALIGN GAP;..."` (Bottom Start 2): the window margin and the placements, in order
+pub(crate) fn spec(v: &str) -> Option<(f32, Vec<(Side, Align, f32)>)> {
+ let mut it = v.split(';');
+ let margin = it.next()?.trim().parse().ok()?;
+ let mut out = Vec::new();
+ for p in it {
+ let mut w = p.split_whitespace();
+ let side = match w.next()? {
+ "Top" => Side::Top,
+ "Bottom" => Side::Bottom,
+ "Left" => Side::Left,
+ "Right" => Side::Right,
+ _ => return None,
+ };
+ let align = match w.next()? {
+ "Start" => Align::Start,
+ "End" => Align::End,
+ "Center" => Align::Center,
+ _ => return None,
+ };
+ out.push((side, align, w.next()?.parse().ok()?));
+ }
+ Some((margin, out))
+}
+
+/// A rect as min x, min y, max x, max y
+type Rect = [f32; 4];
+
+/// The placement position_popover picks: the popup (`w` x `h`) beside `parent` at each placement, the one the window
+/// rect hides least (the first of equals); its rect.
+pub(crate) fn place(parent: Rect, (w, h): (f32, f32), window: Rect, at: &[(Side, Align, f32)]) -> Option<Rect> {
+ let mut best: Option<(f32, Rect)> = None;
+ for &(side, align, gap) in at {
+ let mut r = [0.0f32; 4];
+ match side {
+ Side::Top => (r[3], r[1]) = (parent[1] - gap, parent[1] - gap - h),
+ Side::Bottom => (r[1], r[3]) = (parent[3] + gap, parent[3] + gap + h),
+ Side::Left => (r[2], r[0]) = (parent[0] - gap, parent[0] - gap - w),
+ Side::Right => (r[0], r[2]) = (parent[2] + gap, parent[2] + gap + w),
+ }
+ let vertical = matches!(side, Side::Top | Side::Bottom);
+ let (lo, hi, len, i) = if vertical { (parent[0], parent[2], w, 0) } else { (parent[1], parent[3], h, 1) };
+ let start = match align {
+ Align::Start => lo,
+ Align::End => hi - len,
+ Align::Center => lo + (hi - lo - len) * 0.5,
+ };
+ (r[i], r[i + 2]) = (start, start + len);
+ let area = |q: Rect| (q[2] - q[0]).max(0.0) * (q[3] - q[1]).max(0.0);
+ let clipped = [r[0].max(window[0]), r[1].max(window[1]), r[2].min(window[2]), r[3].min(window[3])];
+ let hidden = area(r) - area(clipped);
+ if best.is_none_or(|(b, _)| hidden < b) {
+ best = Some((hidden, r));
+ }
+ }
+ best.map(|(_, r)| r)
+}
+
+impl BaseDocument {
+ pub(crate) fn resolve_bevy_popovers(&mut self) {
+ let name = LocalName::from("data-raea-bevy-popover");
+ let pops: Vec<(crate::NodeId, f32, Vec<(Side, Align, f32)>)> = self.nodes.iter().filter_map(|(id, n)| n.attr(name.clone()).and_then(spec).map(|(m, at)| (id, m, at))).collect();
+ if pops.is_empty() {
+ return;
+ }
+ let v = self.viewport();
+ let scale = v.scale();
+ let (vw, vh) = (v.window_size.0 as f32 / scale, v.window_size.1 as f32 / scale);
+ for (id, margin, at) in pops {
+ let Some(parent) = self.nodes[id].parent else { continue };
+ let p = &self.nodes[parent];
+ let (pl, b) = (p.final_layout(), p.final_layout().border);
+ let o = p.absolute_position(0.0, 0.0);
+ let rect = [o.x + b.left, o.y + b.top, o.x + pl.size.width - b.right, o.y + pl.size.height - b.bottom];
+ let me = &self.nodes[id];
+ let size = (me.final_layout().size.width, me.final_layout().size.height);
+ let now = me.absolute_position(0.0, 0.0);
+ let window = [margin, margin, vw - margin, vh - margin];
+ let Some(r) = place(rect, size, window, &at) else { continue };
+ let (dx, dy) = (r[0] - now.x, r[1] - now.y);
+ if dx == 0.0 && dy == 0.0 {
+ continue;
+ }
+ let node = &mut self.nodes[id];
+ let l = node.final_layout_mut();
+ (l.location.x, l.location.y) = (l.location.x + dx, l.location.y + dy);
+ let l = node.unrounded_layout_mut();
+ (l.location.x, l.location.y) = (l.location.x + dx, l.location.y + dy);
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn below_at_the_start_unless_the_window_hides_more_of_it_than_above() {
+ let at = spec("10;Bottom Start 2;Top Start 2").unwrap().1;
+ // a 200 x 65 button at (540, 418) with a 5 px border: its inside 190 x 55, the popup 200 x 178 under it
+ let parent = [545.0, 423.0, 735.0, 478.0];
+ assert_eq!(place(parent, (200.0, 178.0), [10.0, 10.0, 1270.0, 710.0], &at), Some([545.0, 480.0, 745.0, 658.0]));
+ // near the window's bottom: above
+ let low = [545.0, 600.0, 735.0, 655.0];
+ assert_eq!(place(low, (200.0, 178.0), [10.0, 10.0, 1270.0, 710.0], &at), Some([545.0, 420.0, 745.0, 598.0]));
+ assert_eq!(spec("10;Middle Start 2"), None);
+ }
+}
diff --git a/vendor/blitz-dom/src/layout/inline.rs b/vendor/blitz-dom/src/layout/inline.rs
index b19af1e1..2adc922b 100644
--- a/vendor/blitz-dom/src/layout/inline.rs
+++ b/vendor/blitz-dom/src/layout/inline.rs
@@ -261,6 +261,10 @@ impl LayoutPassState<'_> {
.unwrap()
.take_inline_layout()
.unwrap();
+ // raea: a measure (taffy's intrinsic sizing, a re-layout's probes; a bevy_text box's min-content breaks them at
+ // no width) breaks the lines a laid-out box keeps; they're put back after it, so a box whose layout taffy keeps
+ // from its cache this pass still draws its own lines (TextLayout::performed_width)
+ let kept = (inputs.run_mode == RunMode::ComputeSize && inline_layout.performed_width.is_some()).then(|| inline_layout.layout.clone());
let style = self.nodes[node_id].layout_style();
@@ -688,6 +692,9 @@ impl LayoutPassState<'_> {
if inputs.run_mode == taffy::RunMode::ComputeSize
&& inputs.axis == RequestedAxis::Horizontal
{
+ if let Some(l) = kept {
+ inline_layout.layout = l;
+ }
// Put layout back
self.nodes[node_id]
.data
@@ -1279,8 +1286,12 @@ impl LayoutPassState<'_> {
if inputs.run_mode == RunMode::PerformLayout {
inline_layout.span_cb_flags = span_cb_flags;
+ inline_layout.performed_width = Some(width);
}
+ if let Some(l) = kept {
+ inline_layout.layout = l;
+ }
// Put layout back
self.nodes[node_id]
.data
diff --git a/vendor/blitz-dom/src/lib.rs b/vendor/blitz-dom/src/lib.rs
index 3ba678d1..b46b744a 100644
--- a/vendor/blitz-dom/src/lib.rs
+++ b/vendor/blitz-dom/src/lib.rs
@@ -55,6 +55,7 @@ mod mutator;
mod query_selector;
mod resolve;
mod bevy_scroll;
+mod bevy_popover;
/// Computation of resolved CSS property values (`getComputedStyle()`)
mod resolved_style;
/// Scrolling of nodes and the viewport, and scroll animations.
diff --git a/vendor/blitz-dom/src/node/text.rs b/vendor/blitz-dom/src/node/text.rs
index 6467af52..c9411e27 100644
--- a/vendor/blitz-dom/src/node/text.rs
+++ b/vendor/blitz-dom/src/node/text.rs
@@ -37,6 +37,10 @@ pub struct TextLayout {
/// (a collapsed run's space may sit just before or after): what maps a DOM offset in it to the layout's and back
/// (raea-runtime-dom's editing.rs: Range rects, caretPositionFromPoint, the selection's paint)
pub text_nodes: Vec<(NodeId, usize, usize)>,
+ /// raea: the width (layout px) its lines were last broken at by a PerformLayout run: a height measured at another
+ /// width breaks them again, and they're put back after (layout/inline.rs), so a box whose layout taffy keeps from
+ /// its cache (no PerformLayout run this pass) still draws its own lines
+ pub performed_width: Option<f32>,
}
impl TextLayout {
diff --git a/vendor/blitz-dom/src/resolve.rs b/vendor/blitz-dom/src/resolve.rs
index 9b45e06b..e51044a4 100644
--- a/vendor/blitz-dom/src/resolve.rs
+++ b/vendor/blitz-dom/src/resolve.rs
@@ -143,6 +143,8 @@ impl BaseDocument {
// raea: scroll offsets the page set kept in range and bevy_ui Scrollbar thumbs placed, now that layout has the
// content (bevy_scroll.rs)
self.resolve_bevy_scroll();
+ // raea: bevy_ui_widgets Popovers placed beside their parents (bevy_popover.rs)
+ self.resolve_bevy_popovers();
// Resolve transforms
self.resolve_transforms(root_node_id, None, None);