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.

LR1: A composition reads its layout synchronously from the page that draws its frame (#54). Its JS asks page.layout and blocks; settle wakes on the ask as on a flush, applies the commits already sent, and the host lays its page out at the frame's time and answers every element's boxes at once, keyed by React id: raea-sys-page's snapshot (now runtime/dom's too), with offsets from blitz-dom's offset_rect and offsetParent. settle_with takes the host's answer; plain settle says the host lays no page out. Each runtime has its own ask (a render's 3D pre-pass and a bake's workers run beside it). The still, 3D and fed renders answer from their page; the sound pass and the 3D rows' pre-pass answer no boxes. sdk/raea's page-layout keeps the answer until the next commit or frame, so a composition that never reads makes no snapshot

shinyobjectz7fb219450331
diff --git a/docs/layout-reads.feature b/docs/layout-reads.feature
index cb8874ee..ff26bbc6 100644
--- a/docs/layout-reads.feature
+++ b/docs/layout-reads.feature
@@ -78,7 +78,7 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
Rule: a read gets the layout that draws the frame, synchronously
- @needs:LR0
+ @needs:LR0 @done
Scenario: LR1. A synchronous layout call answered by the page
Given the composition's JS asks `page.layout` while an effect runs
Then the JS thread blocks until the main thread answers
@@ -92,6 +92,24 @@ Feature: Layout reads: a composition measures its text and layout as Chrome does
scoped thread-local, or a parameter, chosen when it's built
And with no page to answer (a host that lays nothing out), the call says so, and the ref's reads throw an error
that names the host, instead of returning guesses
+ And 11-12, built:
+ - The page is a parameter: `settle_with(app, want, secs, answer)`, where `answer` lays the host's page out
+ from the World. Plain `settle` answers "this host lays no page out", so every host is still a choice
+ LR2 makes.
+ - Each runtime has its own ask (runtime/react/src/layout.rs: a LayoutAsk resource in its App, the same Arc
+ on its JS thread). One process runs several runtimes: a render's 3D-rows pre-pass, and a bake's workers
+ on threads. A shared ask would let one runtime's page answer another's read.
+ - The answer is raea-sys-page's snapshot, the one an app page's DOM already reads (runtime/dom now uses
+ it too). With offsets it adds `o`, from blitz-dom's offset_rect and offsetParent: offsetLeft, offsetTop,
+ offsetWidth, offsetHeight, the offsetParent's React id, and whether the element is a non-atomic inline.
+ - The render and export answer from their frame's page: the still loop, the 3D loop and the fed render.
+ bevy_frame.rs's layout_answer syncs the page at the frame's time, lays it out, and snapshots it. Passes
+ that draw no page get an answer with no boxes, where every read is 0. Those are the sound pass and the
+ 3D-rows pre-pass (raea-bake's step_frames).
+ - sdk/raea/src/page-layout.ts parses the answer once and keeps it until the next op_flush or raea-frame.
+ A composition that never reads makes no snapshot.
+ - With LR3's getters, bench/layout-reads/probes pass against Chrome. In repro, "here" is at x 342 as in
+ Chrome (Inter at 64 px). geometry prints each value it read, and all match Chrome's words.
@needs:LR1
Scenario: LR2. Every host that runs a composition answers
diff --git a/engine/page/src/motion/read.rs b/engine/page/src/motion/read.rs
index c0ac8c97..ec94bad6 100644
--- a/engine/page/src/motion/read.rs
+++ b/engine/page/src/motion/read.rs
@@ -139,6 +139,14 @@ impl BlitzPage {
Some([b.x as f32, b.y as f32, b.width as f32, b.height as f32])
}
+ /// The page's layout as a composition's script reads it (`page.layout`, docs/layout-reads.feature LR1): raea-sys-page's
+ /// snapshot with offsets, each element under the id `id` gives it (None leaves it out). Lay the page out first.
+ pub fn layout_snapshot(&self, id: impl Fn(u64) -> Option<u64>) -> String {
+ let docs = self.app.world().non_send::<Docs>();
+ let Some(doc) = docs.0.get(&self.page) else { return "{\"vw\":0,\"vh\":0,\"n\":[],\"o\":[]}".into() };
+ raea_sys_page::snapshot_by(doc, &self.nodes, id, true)
+ }
+
/// The element the ops made that's topmost at the point (page px), as Blitz's hit test finds it (transforms and
/// pointer-events as drawn): the nearest element up from the hit that has an id.
pub fn hit(&mut self, x: f32, y: f32) -> Option<u64> {
diff --git a/runtime/bake/src/lib.rs b/runtime/bake/src/lib.rs
index 1d85dcfe..1a98251f 100644
--- a/runtime/bake/src/lib.rs
+++ b/runtime/bake/src/lib.rs
@@ -214,7 +214,8 @@ pub fn step_frames(app: &mut App, a: i64, b: i64, mut each: impl FnMut(&mut App,
let mut t_each = std::time::Duration::ZERO;
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frames", "value": {"from": a, "to": b}}));
for g in a..b {
- raea_runtime_react::scene::settle(app, Some(g), 20.0)?;
+ // a layout read gets no boxes: the frames stepped here draw no page (the 3D rows' pre-pass; docs/layout-reads.feature LR2)
+ raea_runtime_react::scene::settle_with(app, Some(g), 20.0, &mut raea_runtime_react::layout::nothing_drawn)?;
let te = std::time::Instant::now();
each(app, g)?;
t_each += te.elapsed();
diff --git a/runtime/bundle/src/entry.rs b/runtime/bundle/src/entry.rs
index 233bc25c..363b0073 100644
--- a/runtime/bundle/src/entry.rs
+++ b/runtime/bundle/src/entry.rs
@@ -14,7 +14,11 @@ pub fn entry(file: &str, o: &CompOpts) -> String {
r#"import {{ frameCallbacks, pureAgain, pureFrame, pureSession, seedOf }} from "./motion/pure";
import {{ canvas2d }} from "./motion/canvas2d";
import {{ mount, addEventListener, BevyCanvasElement }} from "bevy-react";
+import {{ layoutReads, stale as layoutStale }} from "./motion/page-layout";
canvas2d(BevyCanvasElement); // a <canvas> ref's getContext("2d") is the web's (motion canvas2d.ts, #55)
+// a composition reads its layout from the page that draws the frame (page.layout, docs/layout-reads.feature LR1),
+// the answer kept until its next commit or frame
+layoutReads();
import {{ Component, useEffect, useMemo, useState }} from "react";
import * as M from "./src/{file}";
import {{ Clock, getCompositions, tickClocks }} from "./motion";
@@ -96,6 +100,7 @@ function Root() {{
const [size, setSize] = useState<{{ w: number; h: number }} | null>(null);
useEffect(() => addEventListener("raea-size", (v: any) => setSize(v)), []);
useEffect(() => addEventListener("raea-frame", (v: any) => {{
+ layoutStale(); // the page is at another time: its CSS animations have moved
if (typeof v === "number") return setF(v);
live = true;
// a live session's own seed and start (live.rs), which its input log keeps for a replay
diff --git a/runtime/dom/src/host/elements.rs b/runtime/dom/src/host/elements.rs
index 7d0b1200..3d32fef6 100644
--- a/runtime/dom/src/host/elements.rs
+++ b/runtime/dom/src/host/elements.rs
@@ -177,40 +177,9 @@ impl Plugin for HostPlugin {
}
}
-/// Numbers per element in the layout snapshot (raea_runtime_js::dom::STRIDE: sdk/ui's dom.ts reads the same).
-pub(crate) const STRIDE: usize = 18;
-
-/// The page's layout as its JS reads it (`__ui_layout`'s argument, and `layout.now`'s answer: computed.rs): per wired
-/// element, in page px, id, x, y, w, h, scroll offsets and sizes, padding, border and z (STRIDE numbers).
-pub fn snapshot(doc: &BaseDocument, nodes: &Nodes) -> String {
- let vp = doc.viewport().window_size;
- let mut n = String::new();
- let mut num = |v: f32| {
- let x = (v * 100.0).round() / 100.0;
- if x == x.trunc() {
- n.push_str(&format!("{},", x as i64));
- } else {
- n.push_str(&format!("{x},"));
- }
- };
- for (id, node) in &nodes.by_id {
- // (text nodes have no layout data of their own to ask)
- let Some(el) = doc.get_node(*node).filter(|n| n.is_element()) else { continue };
- let Some(b) = doc.get_client_bounding_rect(*node) else { continue };
- let l = el.final_layout();
- let s = el.scroll_offset();
- num(*id as f32);
- for v in [b.x as f32, b.y as f32, b.width as f32, b.height as f32, s.x as f32, s.y as f32, el.scroll_width(), el.scroll_height()] {
- num(v);
- }
- for v in [l.padding.left, l.padding.top, l.padding.right, l.padding.bottom, l.border.left, l.border.top, l.border.right, l.border.bottom, 0.0] {
- num(v);
- }
- }
- debug_assert_eq!(STRIDE, 18);
- n.pop();
- format!("{{\"vw\":{},\"vh\":{},\"dpr\":1,\"n\":[{n}]}}", vp.0, vp.1)
-}
+/// The page's layout as its JS reads it (`__ui_layout`'s argument, and `layout.now`'s answer: computed.rs): raea-sys-page's
+/// snapshot, the one a composition's `page.layout` answers too (docs/layout-reads.feature LR1).
+pub use raea_sys_page::snapshot;
/// After the page's layout: each root's snapshot to its JS's `__ui_layout`, as raea-runtime-js's dom.rs sends bevy_ui's (the
/// DOM layer's geometry: getBoundingClientRect, client and scroll sizes, hit tests, the observers, rAF). Per element,
diff --git a/runtime/export/src/bevy_frame.rs b/runtime/export/src/bevy_frame.rs
index 88081bc0..dab0207b 100644
--- a/runtime/export/src/bevy_frame.rs
+++ b/runtime/export/src/bevy_frame.rs
@@ -227,6 +227,16 @@ pub(crate) fn bevy_page_frame(world: &mut World, page: &mut raea_runtime_page::B
Ok((px, pics))
}
+/// A composition's layout read answered by the frame's page (`page.layout`, docs/layout-reads.feature LR1): the page made
+/// to match the React World as it is mid-settle, at frame `f`'s time, laid out, and every element's boxes by React id.
+/// Nothing is drawn; the frame's own sync redoes what this did once the frame settles.
+pub(crate) fn layout_answer(world: &mut World, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, f: i64, fps: f64) -> R<String> {
+ page.at_frame(f, fps);
+ page_with_holders(world, page, cx)?;
+ page.lay_out();
+ Ok(page.layout_snapshot())
+}
+
/// The frame's page made to match the React tree, not drawn yet; the frame's sound, mix, marker and 3D rows collected
/// on the way.
pub(crate) fn bevy_page_sync(world: &mut World, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx) -> R<()> {
diff --git a/runtime/export/src/fed.rs b/runtime/export/src/fed.rs
index 2cc84fff..c56432a3 100644
--- a/runtime/export/src/fed.rs
+++ b/runtime/export/src/fed.rs
@@ -225,7 +225,7 @@ pub(crate) fn render_fed(app: &mut App, js: &Path, w: u32, h: u32, fps: f64, tot
if asked != Some(f) {
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
}
- settle(app, Some(f), 20.0)?;
+ settle_with(app, Some(f), 20.0, &mut |w| layout_answer(w, bevy, cx, f, fps))?;
cx.now = f;
// the next frame asked for now, so React renders it on its own thread while this one's 3D and page are
// drawn here: its commits wait in the inbox until the next settle applies them, so nothing this frame
diff --git a/runtime/export/src/render.rs b/runtime/export/src/render.rs
index 0eaf8597..6c933bb0 100644
--- a/runtime/export/src/render.rs
+++ b/runtime/export/src/render.rs
@@ -276,7 +276,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
let px = raea_gpu_device::check::frame_caught(f, || { // a panic drawing it an error naming it (#33)
engine_before(&app, &mut cx, f);
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
- settle(&mut app, Some(f), 20.0)?;
+ settle_with(&mut app, Some(f), 20.0, &mut |w| layout_answer(w, pg, &mut cx, f, fps))?;
cx.now = f;
pg.at_frame(f, fps);
let mut px = bevy_over_3d(app.world_mut(), pg, &mut cx, fps)?;
@@ -317,7 +317,7 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
for &f in &wanted {
let t0 = std::time::Instant::now();
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
- settle(&mut app, Some(f), 20.0)?;
+ settle_with(&mut app, Some(f), 20.0, &mut |w| layout_answer(w, &mut page, &mut cx, f, fps))?;
cx.now = f;
let t1 = std::time::Instant::now();
page.at_frame(f, fps);
diff --git a/runtime/export/src/sound.rs b/runtime/export/src/sound.rs
index 99b1a812..5fe3339d 100644
--- a/runtime/export/src/sound.rs
+++ b/runtime/export/src/sound.rs
@@ -87,7 +87,8 @@ pub(crate) fn core_cues(js: &Path, dir: &Path, need_mix: bool) -> R<Option<(Vec<
let (mut frames, mut notes) = (Vec::new(), Vec::new());
for f in 0..total {
app.world().resource::<ReactOutbox>().send(json!({"t": "event", "name": "raea-frame", "value": f}));
- settle(&mut app, Some(f), 20.0)?;
+ // (a layout read here gets no boxes: the sound pass draws no page, docs/layout-reads.feature LR2)
+ settle_with(&mut app, Some(f), 20.0, &mut raea_runtime_react::layout::nothing_drawn)?;
cx.now = f;
cx.sounds.clear();
cx.mix = None;
diff --git a/runtime/page/src/bevy_page.rs b/runtime/page/src/bevy_page.rs
index 8a0c6115..dfc6f06d 100644
--- a/runtime/page/src/bevy_page.rs
+++ b/runtime/page/src/bevy_page.rs
@@ -176,6 +176,12 @@ impl BevyPage {
self.page.client_box(id + REACT_IDS)
}
+ /// Every React element's boxes as the page lays them out now (`page.layout`, docs/layout-reads.feature LR1), keyed by
+ /// React id: the page's own elements (the body, holders' parts) left out. Lay the page out first.
+ pub fn layout_snapshot(&self) -> String {
+ self.page.layout_snapshot(|id| (id >= REACT_IDS && id & TEXT_BIT == 0).then(|| id - REACT_IDS))
+ }
+
/// The React element topmost at the point (page px): its React id (none over the page's own body).
pub fn hit(&mut self, x: f32, y: f32) -> Option<u64> {
self.page.hit(x, y).map(|id| id & !TEXT_BIT).filter(|id| *id >= REACT_IDS).map(|id| id - REACT_IDS)
diff --git a/runtime/react/src/layout.rs b/runtime/react/src/layout.rs
new file mode 100644
index 00000000..5d59fbb4
--- /dev/null
+++ b/runtime/react/src/layout.rs
@@ -0,0 +1,103 @@
+//! Layout reads (docs/layout-reads.feature LR1, #54): the composition's `page.layout` answered by the page that draws its
+//! frame, synchronously. The JS thread asks and blocks; settle, on the main thread, wakes on the ask as it wakes on a
+//! flush, applies the commits already sent, and has its host lay the page out and answer every element's boxes at once.
+//! A host that lays nothing out answers that it can't, and the composition's read throws that.
+//! Each runtime has its own ask (one process runs several: a bake's workers, a render's pre-pass beside its frames), so
+//! a read is answered only by its own runtime's settle.
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Condvar, Mutex};
+use std::time::{Duration, Instant};
+
+use bevy::prelude::{Resource, World};
+
+use crate::scene::HANG_SECS;
+
+/// A host's answer to a layout read: the page laid out as the React World has it now, its snapshot (raea-sys-page's,
+/// with offsets, keyed by React id) as JSON; or why it can't.
+pub type Answer<'a> = dyn FnMut(&mut World) -> Result<String, String> + 'a;
+
+/// One runtime's layout read: asked by its JS thread, answered by its settle.
+#[derive(Default)]
+pub struct Ask {
+ /// the JS thread is waiting on a read
+ asked: AtomicBool,
+ /// the read's answer, once settle has made it
+ answer: Mutex<Option<Result<String, String>>>,
+ told: Condvar,
+}
+
+impl Ask {
+ /// Whether a read is waiting (wait_flush wakes on it).
+ pub fn asked(&self) -> bool {
+ self.asked.load(Ordering::SeqCst)
+ }
+}
+
+/// The runtime's ask, in its App (ReactPlugin puts it there and on its JS thread).
+#[derive(Resource, Clone, Default)]
+pub struct LayoutAsk(pub Arc<Ask>);
+
+thread_local! {
+ /// The JS thread's runtime's ask.
+ pub(crate) static ASK: std::cell::RefCell<Option<Arc<Ask>>> = const { std::cell::RefCell::new(None) };
+}
+
+/// settle's side: a read waiting is answered by `answer`, on this (the main) thread.
+pub(crate) fn answer_if_asked(ask: &Ask, world: &mut World, answer: &mut Answer) {
+ if !ask.asked.swap(false, Ordering::SeqCst) {
+ return;
+ }
+ let t0 = Instant::now();
+ let r = answer(world);
+ READS.fetch_add(1, Ordering::Relaxed);
+ READ_NS.fetch_add(t0.elapsed().as_nanos() as u64, Ordering::Relaxed);
+ *ask.answer.lock().unwrap() = Some(r);
+ ask.told.notify_all();
+}
+
+/// Layout reads answered, and the nanoseconds the main thread spent answering them (LR10's cost per read)
+pub static READS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+pub static READ_NS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+/// The JS thread's side (`page.layout`): ask, wake settle's wait, and block until the answer comes.
+fn read() -> Result<String, String> {
+ let ask = ASK.with(|a| a.borrow().clone()).ok_or("page.layout: this thread runs no composition")?;
+ let mut g = ask.answer.lock().unwrap();
+ *g = None;
+ ask.asked.store(true, Ordering::SeqCst);
+ // settle's wait is on FLUSHED's condvar: notified under its lock, so a wait about to start can't miss it
+ {
+ let (n, fcv) = &crate::FLUSHED;
+ let _n = n.lock().unwrap();
+ fcv.notify_all();
+ }
+ let (mut g, r) = ask.told.wait_timeout_while(g, Duration::from_secs_f64(HANG_SECS), |a| a.is_none()).unwrap();
+ if r.timed_out() {
+ ask.asked.store(false, Ordering::SeqCst);
+ return Err(format!("page.layout got no answer in {HANG_SECS} s: the host never stepped the composition while it waited"));
+ }
+ g.take().unwrap_or_else(|| Err("page.layout: no answer".into()))
+}
+
+/// The native call (thread.rs's register_natives).
+pub(crate) fn register() {
+ raea_native::register(
+ "page.layout",
+ "{}",
+ "string",
+ "every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id; the composition's thread waits for it",
+ |_| read().map(serde_json::Value::String),
+ );
+}
+
+/// The answer of a pass that runs the composition but draws nothing (the sound pass, the 3D rows' pre-pass): no element
+/// has a box, so every read is 0, and the composition goes on as it would before it's laid out.
+pub fn nothing_drawn(_: &mut World) -> Result<String, String> {
+ Ok("{\"vw\":0,\"vh\":0,\"dpr\":1,\"n\":[],\"o\":[]}".into())
+}
+
+/// A host's answer when it has no page to lay out.
+pub fn no_page(host: &'static str) -> impl FnMut(&mut World) -> Result<String, String> {
+ move |_| Err(format!("{host} lays no page out, so a composition can't read its layout here (getBoundingClientRect, offsetWidth and the rest)"))
+}
diff --git a/runtime/react/src/lib.rs b/runtime/react/src/lib.rs
index 90a44b20..6bd31267 100644
--- a/runtime/react/src/lib.rs
+++ b/runtime/react/src/lib.rs
@@ -25,6 +25,8 @@ pub use raea_runtime_shared::{self as shared, ReactOutbox};
pub use raea_runtime_calls::{self as native, CLI};
use serde_json::Value;
+// a composition's synchronous layout reads, answered by its host's page (docs/layout-reads.feature LR1)
+pub mod layout;
mod thread;
use thread::*;
pub use thread::register_natives;
@@ -166,14 +168,19 @@ impl Plugin for ReactPlugin {
let (tx, rx) = channel();
let (out_tx, out_rx) = channel::<String>();
let bundle = self.bundle.clone();
+ // the runtime's layout reads (layout.rs): asked on its JS thread, answered by its settle
+ let ask = layout::LayoutAsk::default();
+ let js_ask = ask.0.clone();
std::thread::Builder::new()
.name("raea-runtime-react js".into())
.spawn(move || {
+ layout::ASK.with(|a| *a.borrow_mut() = Some(js_ask));
// JavaScriptCore on Apple (the system's engine, the JIT on with the entitlement tools/link-jit.sh signs in),
// QuickJS elsewhere
js_thread(bundle, tx, out_rx)
})
.expect("the JS thread");
+ app.insert_resource(ask);
app.insert_resource(ReactOutbox(Mutex::new(out_tx)));
let root = app.world_mut().spawn((ReactRoot, ReactNode(ROOT_ID), ReactKind("#root".into()))).id();
let mut ents = ReactEntities::default();
@@ -313,10 +320,15 @@ pub fn flushed() -> u64 {
/// Block until React flushes a commit after the `seen`-th, or `timeout` passes; the count now.
pub fn wait_flush(seen: u64, timeout: Duration) -> u64 {
+ wait_flush_or(seen, timeout, None)
+}
+
+/// [`wait_flush`], woken also by `ask`'s layout read (settle answers it: layout.rs).
+pub fn wait_flush_or(seen: u64, timeout: Duration, ask: Option<&layout::Ask>) -> u64 {
let (n, cv) = &FLUSHED;
let t0 = Instant::now();
let g = n.lock().unwrap();
- let (g, r) = cv.wait_timeout_while(g, timeout, |c| *c <= seen).unwrap();
+ let (g, r) = cv.wait_timeout_while(g, timeout, |c| *c <= seen && !ask.is_some_and(layout::Ask::asked)).unwrap();
FLUSH_WAIT_NS.fetch_add(t0.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
if r.timed_out() {
FLUSH_TIMEOUTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
diff --git a/runtime/react/src/scene/settle.rs b/runtime/react/src/scene/settle.rs
index bc358755..a612d1ed 100644
--- a/runtime/react/src/scene/settle.rs
+++ b/runtime/react/src/scene/settle.rs
@@ -31,8 +31,16 @@ pub const SETTINGS_SECS: f64 = 120.0;
/// One JS call running longer than this is a hang (a loop that never returns), not progress.
pub const HANG_SECS: f64 = 600.0;
-/// Run React until its commits settle and the marker says `want` (or anything, for None).
+/// Run React until its commits settle and the marker says `want` (or anything, for None). A layout read the composition
+/// makes meanwhile is told this host lays no page out: a host with a page settles with [`settle_with`].
pub fn settle(app: &mut App, want: Option<i64>, secs: f64) -> R<Option<Map<String, Value>>> {
+ settle_with(app, want, secs, &mut crate::layout::no_page("this host"))
+}
+
+/// [`settle`], with `answer` laying the host's page out for a layout read the composition makes while it runs
+/// (`page.layout`, docs/layout-reads.feature LR1): the read wakes the wait as a flush does, the commits sent before it
+/// are applied, and `answer` lays the page out from the World and returns its snapshot.
+pub fn settle_with(app: &mut App, want: Option<i64>, secs: f64, answer: &mut crate::layout::Answer) -> R<Option<Map<String, Value>>> {
// the settings' settle waits on the module's own top-level work too: parkour lays and performs its courses there,
// 17-18 s of CPU on a quiet machine, and at load 20 the callers' 20 s refused it every time (10-26)
let secs = if want == Some(-1) { secs.max(SETTINGS_SECS) } else { secs };
@@ -53,6 +61,8 @@ pub fn settle(app: &mut App, want: Option<i64>, secs: f64) -> R<Option<Map<Strin
// a bake's runtime (OneBatch): only what a commit needs, applied and its animations sampled (PreUpdate). The whole
// main schedule ran each frame for nothing else, ~50 us a frame, more than React's render (lightspeed T3)
let pre_only = app.world().get_resource::<crate::OneBatch>().is_some();
+ // this runtime's layout reads (layout.rs): a replay's App has none
+ let ask = app.world().get_resource::<crate::layout::LayoutAsk>().map(|a| a.0.clone());
loop {
if pre_only {
app.world_mut().run_schedule(PreUpdate);
@@ -62,6 +72,17 @@ pub fn settle(app: &mut App, want: Option<i64>, secs: f64) -> R<Option<Map<Strin
if let Some(e) = crate::COMPOSITION_ERROR.lock().unwrap().take() {
return Err(format!("the composition threw at frame {}: {e}", want.map(|w| w.to_string()).unwrap_or("?".into())));
}
+ // a layout read waiting: every commit sent before it applied (one an update with OneBatch), then answered, and
+ // the loop goes on (the read's thread carries on from its effect, so more commits and the marker follow)
+ if let Some(ask) = ask.as_deref().filter(|a| a.asked()) {
+ // (the read's own commit can land after this pass's update: its batch is sent before its effects run)
+ app.world_mut().run_schedule(PreUpdate);
+ while app.world().get_resource::<crate::OneBatch>().is_some_and(|q| !q.0.is_empty()) {
+ app.world_mut().run_schedule(PreUpdate);
+ }
+ crate::layout::answer_if_asked(ask, app.world_mut(), answer);
+ continue;
+ }
let world = app.world_mut();
// the marker's entity, remembered (a scan of every entity's props for it each pass was most of a settle)
let marker = world.get_resource::<MarkerEntity>().map(|m| m.0).filter(|e| world.get::<ReactProps>(*e).is_some_and(|p| p.0.contains_key("data-raea-frame")));
@@ -122,7 +143,7 @@ pub fn settle(app: &mut App, want: Option<i64>, secs: f64) -> R<Option<Map<Strin
if app.world().get_resource::<crate::OneBatch>().is_some_and(|q| !q.0.is_empty()) {
continue;
}
- seen = crate::wait_flush(seen, std::time::Duration::from_secs_f64(left.min(0.5)));
+ seen = crate::wait_flush_or(seen, std::time::Duration::from_secs_f64(left.min(0.5)), ask.as_deref());
}
// a call past HANG_SECS is a hang, named: which runtime's call, and how long it has run
if let Some(d) = crate::js_call_for().filter(|d| d.as_secs_f64() >= HANG_SECS) {
diff --git a/runtime/react/src/thread.rs b/runtime/react/src/thread.rs
index 3eb725ef..a906edba 100644
--- a/runtime/react/src/thread.rs
+++ b/runtime/react/src/thread.rs
@@ -37,7 +37,7 @@ fn log(a: &[String]) -> Result<Ret, String> {
pub fn register_natives() {
raea_native::register("page.viewBox", "{}", "[number, number, number, number] | null", "the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a)", |_| Ok(serde_json::json!(*VIEW_BOX.lock().unwrap())));
// the calls crate's, matchmove.solve (scene/track.rs), physics.* (systems/bake), scene.* (scene/contact.rs), *.shot (runtime/shots)
- [native::register, scene::track::register, scene::physics::register, raea_runtime_shots::register, scene::register_scene].iter().for_each(|r| r());
+ [native::register, layout::register, scene::track::register, scene::physics::register, raea_runtime_shots::register, scene::register_scene].iter().for_each(|r| r());
}
/// The JS thread: the prelude, the shims, the bundle, then timers and Bevy's events. Both engines run promise jobs as
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index 61a8be6c..e17ae84f 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -184,6 +184,8 @@ export interface NativeCalls {
"net.fetch": { args: { policy: number; url: string; method?: string; headers?: Record<string, string>; body?: string; followRedirects?: boolean; maxRedirects?: number; timeoutMs?: number }; answer: { status: number; statusText: string; headers: Record<string, string>; body: string; url: string; redirectChain: { status: number; statusText: string; headers: Record<string, string> }[] } };
/** a network policy (allowed URL prefixes and methods; headers injected at the boundary, secrets from the host's environment) */
"net.policy": { args: { allow: { prefix: string; methods?: string[]; headers?: Record<string, string>; secretHeaders?: Record<string, string> }[]; timeoutMs?: number; maxRedirects?: number; maxBytes?: number }; answer: { id: number } };
+ /** every element's boxes as the page that draws the frame lays it out now (docs/layout-reads.feature LR1): JSON {vw, vh, n: [id, x, y, w, h, scroll x y w h, padding l t r b, border l t r b, z per element], o: [id, offsetLeft, offsetTop, offsetWidth, offsetHeight, offsetParent, inline per element]}, keyed by React id; the composition's thread waits for it */
+ "page.layout": { args: {}; answer: string };
/** the box (x, y, w, h in frame px) a camera in a page element draws its view in, as last laid out; null when it draws under the whole frame (3D picking in the box, docs/sdk.feature S3a) */
"page.viewBox": { args: {}; answer: [number, number, number, number] | null };
/** rigid bodies stepped by Rapier, deterministic, made once per request and kept: each body's rigid motion from rest per frame */
diff --git a/sdk/raea/src/page-layout.ts b/sdk/raea/src/page-layout.ts
new file mode 100644
index 00000000..4d4f3b72
--- /dev/null
+++ b/sdk/raea/src/page-layout.ts
@@ -0,0 +1,91 @@
+// A composition's layout, read synchronously from the page that draws its frame (docs/layout-reads.feature LR1, #54).
+// `page.layout` lays the page out as React last committed it, at the frame's time, and answers every element's boxes
+// at once (raea-sys-page's snapshot, the one an app page's DOM reads): the read blocks the composition's thread until
+// the page answers, as a browser lays out when script reads a box. The answer is kept until the next commit or frame,
+// so a burst of reads costs one layout. A host that lays nothing out says so, and the read throws that.
+
+import { native } from "@raea/app/native";
+
+/** Numbers per element in the snapshot's `n` (raea-sys-page's STRIDE) and in its `o`. */
+const STRIDE = 18;
+const OFFSETS = 7;
+
+/** An element's boxes, in the composition's CSS px. */
+export type Box = {
+ /** its bounding client rect: x, y, width, height (transformed; an inline element's line fragments joined) */
+ rect: [number, number, number, number];
+ /** scroll left, top, width, height */
+ scroll: [number, number, number, number];
+ /** padding left, top, right, bottom */
+ padding: [number, number, number, number];
+ /** border left, top, right, bottom */
+ border: [number, number, number, number];
+ /** its border box with no transform applied: x, y, width, height (offsetWidth and the rest read it) */
+ layout: [number, number, number, number];
+ /** its offsetParent's id: -1 for the page's body, -2 for none (it or an ancestor isn't displayed) */
+ offsetParent: number;
+ /** a non-atomic inline element (a span in a line): its client* and scroll* are 0, as in Chrome */
+ inline: boolean;
+};
+
+type Snapshot = { vw: number; vh: number; n: number[]; o?: number[] };
+
+let boxes: Map<number, Box> | null = null;
+let viewport: [number, number] = [0, 0];
+const HOST = (globalThis as any).__bevyHost;
+
+/** The layout read last is stale: something committed, or a new frame started. */
+export function stale(): void {
+ boxes = null;
+}
+
+function read(): Map<number, Box> {
+ if (boxes) return boxes;
+ // the page answers its snapshot as one JSON string (made in Rust as text, not a value to re-encode)
+ const s = JSON.parse(native("page.layout", {})) as Snapshot;
+ const m = new Map<number, Box>();
+ for (let i = 0; i + STRIDE <= s.n.length; i += STRIDE) {
+ const v = s.n;
+ m.set(v[i], {
+ rect: [v[i + 1], v[i + 2], v[i + 3], v[i + 4]],
+ scroll: [v[i + 5], v[i + 6], v[i + 7], v[i + 8]],
+ padding: [v[i + 9], v[i + 10], v[i + 11], v[i + 12]],
+ border: [v[i + 13], v[i + 14], v[i + 15], v[i + 16]],
+ layout: [v[i + 1], v[i + 2], v[i + 3], v[i + 4]],
+ offsetParent: -1,
+ inline: false,
+ });
+ }
+ const o = s.o ?? [];
+ for (let i = 0; i + OFFSETS <= o.length; i += OFFSETS) {
+ const b = m.get(o[i]);
+ if (!b) continue;
+ b.layout = [o[i + 1], o[i + 2], o[i + 3], o[i + 4]];
+ b.offsetParent = o[i + 5];
+ b.inline = o[i + 6] === 1;
+ }
+ viewport = [s.vw, s.vh];
+ return (boxes = m);
+}
+
+/** Element `id`'s boxes as the page lays it out now; undefined when it has none (not displayed, or not on the page). */
+export function boxOf(id: number): Box | undefined {
+ return read().get(id);
+}
+
+/** The page's size, as the last read gave it. */
+export function viewportSize(): [number, number] {
+ read();
+ return viewport;
+}
+
+/** From the entry, once: any commit makes the layout stale (each batch passes the host's op_flush). */
+export function layoutReads(): void {
+ if (!HOST || typeof HOST.op_flush !== "function" || HOST.__layoutReads) return;
+ HOST.__layoutReads = true;
+ const flush = HOST.op_flush;
+ HOST.op_flush = (json: string, devtools: boolean) => {
+ boxes = null;
+ return flush(json, devtools);
+ };
+}
diff --git a/systems/page/src/lib.rs b/systems/page/src/lib.rs
index 1e12e061..ffd94602 100644
--- a/systems/page/src/lib.rs
+++ b/systems/page/src/lib.rs
@@ -27,6 +27,8 @@ pub mod providers;
pub mod widgets;
pub use providers::{PageFonts, PageHtmlParser, PageNavigation, PageNet, PageShell};
pub use raea_sys_page_ops as ops;
+mod snapshot;
+pub use snapshot::{OFFSET_BODY, OFFSET_NONE, OFFSETS, STRIDE, snapshot, snapshot_by};
pub mod view3d;
pub use draw::{Placed, view, view_at};
diff --git a/systems/page/src/snapshot.rs b/systems/page/src/snapshot.rs
new file mode 100644
index 00000000..015aadce
--- /dev/null
+++ b/systems/page/src/snapshot.rs
@@ -0,0 +1,109 @@
+//! The page's layout as script reads it: the one snapshot every page's JS gets its boxes from. An app page's (runtime/dom:
+//! `__ui_layout` after each frame's layout, `layout.now` when script reads a box it changed) and a composition's
+//! (`page.layout`, docs/layout-reads.feature LR1) are this same list, read the same way by sdk/ui's dom and sdk/raea's
+//! page-layout.
+
+use blitz_dom::BaseDocument;
+
+use crate::ops::Nodes;
+
+/// Numbers per element in the snapshot's `n` (sdk/ui's dom and sdk/raea's page-layout read the same).
+pub const STRIDE: usize = 18;
+
+/// Numbers per element in the snapshot's `o`, its offsets (sdk/raea's page-layout).
+pub const OFFSETS: usize = 7;
+
+/// An offsetParent that's the page's body (or the initial containing block): `offsetParent` is the body.
+pub const OFFSET_BODY: i64 = -1;
+
+/// No offsetParent: the element or an ancestor isn't displayed (Chrome's null).
+pub const OFFSET_NONE: i64 = -2;
+
+/// A number as the snapshot writes it: to 0.01 px, an integer without its point.
+fn num(n: &mut String, v: f64) {
+ let x = (v * 100.0).round() / 100.0;
+ if x == x.trunc() {
+ n.push_str(&format!("{},", x as i64));
+ } else {
+ n.push_str(&format!("{x},"));
+ }
+}
+
+/// Per element, in page px: its id, then x, y, w, h (its bounding client rect: transformed, an inline element's line
+/// fragments joined), scroll offsets and sizes, padding l t r b, border l t r b, and z (STRIDE numbers), as JSON with
+/// the viewport's size. `id` gives the id script knows an element by, from its page id (None leaves it out).
+/// With `offsets`, `o` has each element's id, offsetLeft, offsetTop, offsetWidth, offsetHeight (untransformed, from
+/// its offsetParent's padding edge) its offsetParent's id (OFFSET_BODY, OFFSET_NONE), and 1 when it's a non-atomic inline (its client* and scroll* are 0).
+pub fn snapshot_by(doc: &BaseDocument, nodes: &Nodes, id: impl Fn(u64) -> Option<u64>, offsets: bool) -> String {
+ let vp = doc.viewport().window_size;
+ let mut n = String::new();
+ let mut o = String::new();
+ for (page_id, node) in &nodes.by_id {
+ let Some(sid) = id(*page_id) else { continue };
+ // (text nodes have no layout data of their own to ask)
+ let Some(el) = doc.get_node(*node).filter(|n| n.is_element()) else { continue };
+ let Some(b) = doc.get_client_bounding_rect(*node) else { continue };
+ let l = el.final_layout();
+ let s = el.scroll_offset();
+ num(&mut n, sid as f64);
+ for v in [b.x, b.y, b.width, b.height, s.x, s.y, el.scroll_width() as f64, el.scroll_height() as f64] {
+ num(&mut n, v);
+ }
+ for v in [l.padding.left, l.padding.top, l.padding.right, l.padding.bottom, l.border.left, l.border.top, l.border.right, l.border.bottom, 0.0] {
+ num(&mut n, v as f64);
+ }
+ if !offsets {
+ continue;
+ }
+ num(&mut o, sid as f64);
+ if undisplayed(doc, *node) {
+ for v in [0.0, 0.0, 0.0, 0.0, OFFSET_NONE as f64, 0.0] {
+ num(&mut o, v);
+ }
+ continue;
+ }
+ let r = doc.offset_rect(*node).unwrap_or(blitz_dom::BoundingRect { x: 0.0, y: 0.0, width: 0.0, height: 0.0 });
+ // a non-atomic inline's offsetParent is its inline root's (the root itself when it's positioned), as offset_rect
+ // measures it
+ let parent = match el.inline_root_ancestor().filter(|_| el.inline_fragment_boxes().is_some()) {
+ Some(root) if root.id != el.id && root.is_offset_parent() => Some(root),
+ Some(root) => root.offset_parent(),
+ None => el.offset_parent(),
+ };
+ let parent = match parent {
+ None => OFFSET_BODY,
+ Some(p) if p.data.is_element_with_tag_name(&blitz_dom::local_name!("body")) => OFFSET_BODY,
+ Some(p) => nodes.id_of(p.id).and_then(&id).map_or(OFFSET_BODY, |i| i as i64),
+ };
+ let inline = if el.inline_fragment_boxes().is_some() { 1.0 } else { 0.0 };
+ for v in [r.x, r.y, r.width, r.height, parent as f64, inline] {
+ num(&mut o, v);
+ }
+ }
+ n.pop();
+ o.pop();
+ if offsets {
+ format!("{{\"vw\":{},\"vh\":{},\"dpr\":1,\"n\":[{n}],\"o\":[{o}]}}", vp.0, vp.1)
+ } else {
+ format!("{{\"vw\":{},\"vh\":{},\"dpr\":1,\"n\":[{n}]}}", vp.0, vp.1)
+ }
+}
+
+/// [`snapshot_by`] with each element under its own page id, no offsets (an app page's).
+pub fn snapshot(doc: &BaseDocument, nodes: &Nodes) -> String {
+ snapshot_by(doc, nodes, Some, false)
+}
+
+/// Whether `node` or an ancestor is `display: none` (it has no box: offsetParent null, offsets 0, as in Chrome).
+fn undisplayed(doc: &BaseDocument, node: blitz_dom::NodeId) -> bool {
+ let mut at = Some(node);
+ while let Some(id) = at {
+ let Some(n) = doc.get_node(id) else { return false };
+ if n.primary_styles().is_some_and(|s| s.get_box().display.is_none()) {
+ return true;
+ }
+ at = n.parent;
+ }
+ false
+}
+
diff --git a/vendor/blitz-dom/src/node/node.rs b/vendor/blitz-dom/src/node/node.rs
index 0b067cb4..ca2b23a4 100644
--- a/vendor/blitz-dom/src/node/node.rs
+++ b/vendor/blitz-dom/src/node/node.rs
@@ -1845,7 +1845,7 @@ impl Node {
/// Whether this node can act as an [`offset_parent`](Self::offset_parent): a positioned
/// element, or one of the elements that always qualify (`body`, `td`, `th`).
- pub(crate) fn is_offset_parent(&self) -> bool {
+ pub fn is_offset_parent(&self) -> bool { // raea: pub, for the layout snapshot's offsetParent (raea-sys-page)
let Some(styles) = self.primary_styles() else {
return false;
};