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.

The layout snapshot's rects in one pass: what each element asks of its ancestors (display: none, a transform on the way up) is kept for the next (blitz-dom's RectMemo, get_client_bounding_rect_in). Each was a walk to the root for every element, every frame, and on the installed app's page the snapshot was about a third of its main thread. The same rects (tests/rects.rs, every element in tree and reverse order); on a 3,153-element page 20 deep, 0.37 ms to 0.18 ms

shinyobjectzd44cd9c41bb1
diff --git a/systems/page/src/snapshot.rs b/systems/page/src/snapshot.rs
index 14646c44..fd537ce9 100644
--- a/systems/page/src/snapshot.rs
+++ b/systems/page/src/snapshot.rs
@@ -39,11 +39,13 @@ pub fn snapshot_by(doc: &BaseDocument, nodes: &Nodes, id: impl Fn(u64) -> Option
let (vp, dpr) = (doc.viewport().logical_size(), doc.viewport().scale());
let mut n = String::new();
let mut o = String::new();
+ // what each element's rect asks of its ancestors, kept for the next (display: none, a transform on the way up)
+ let mut memo = blitz_dom::RectMemo::default();
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 Some(b) = doc.get_client_bounding_rect_in(*node, &mut memo) else { continue };
let l = el.final_layout();
let s = el.scroll_offset();
num(&mut n, sid as f64);
diff --git a/systems/page/tests/rects.rs b/systems/page/tests/rects.rs
new file mode 100644
index 00000000..cbef4209
--- /dev/null
+++ b/systems/page/tests/rects.rs
@@ -0,0 +1,89 @@
+//! The layout snapshot's rects, taken in one pass with what each element asks of its ancestors kept for the next
+//! (blitz-dom's RectMemo), are the rects each element's own getBoundingClientRect answers. The pass had walked to the
+//! root two more times for every element, every frame: on the app's own page a third of its main thread (11-16).
+use bevy::math::UVec2;
+use blitz_dom::{BaseDocument, NodeId, RectMemo};
+use raea_sys_page::{Page, config};
+
+fn laid_out(html: &str) -> BaseDocument {
+ let mut doc = blitz_html::HtmlDocument::from_html(html, config(Page { size: UVec2::new(800, 600), scale: 1.0 })).into_inner();
+ doc.resolve(0.0);
+ doc
+}
+
+fn elements(doc: &BaseDocument) -> Vec<NodeId> {
+ doc.tree().iter().filter(|(_, n)| n.is_element()).map(|(id, _)| id).collect()
+}
+
+/// Every element's rect, one at a time and in one pass (in `order`), side by side where they differ.
+fn differences(doc: &BaseDocument, order: &[NodeId]) -> Vec<String> {
+ let mut memo = RectMemo::default();
+ order
+ .iter()
+ .filter_map(|&id| {
+ let (alone, pass) = (doc.get_client_bounding_rect(id), doc.get_client_bounding_rect_in(id, &mut memo));
+ (alone != pass).then(|| format!("node {id}: alone {alone:?}, in the pass {pass:?}"))
+ })
+ .collect()
+}
+
+const PAGE: &str = r##"<!doctype html><html><body style="margin:8px">
+<div id="hidden" style="display:none"><div><span>under display: none</span><p>a paragraph</p></div></div>
+<div style="transform: rotate(12deg); width: 200px; padding: 10px">
+ <div style="transform: scale(1.5) translate(4px, 2px)"><p>twice turned</p><span>a span</span></div>
+ <div><div><b>deep under a turned box</b></div></div>
+</div>
+<div style="perspective: 400px">
+ <div style="transform-style: preserve-3d; transform: rotateY(30deg)">
+ <div style="transform: translateZ(40px)">in a 3D context</div>
+ </div>
+</div>
+<p style="width: 120px">Some text <span>that wraps across <i>more than one</i> line box</span> and a
+ <a href="#">link</a> at the end of it.</p>
+<table><tbody><tr><td>one</td><td>two</td></tr><tr><td colspan="2">three</td></tr></tbody></table>
+<div style="position: relative; height: 80px">
+ <div style="position: absolute; left: 30px; top: 20px"><div>out of flow</div></div>
+</div>
+<div style="height: 60px; overflow: auto"><div style="height: 300px"><div>in a scroller</div></div></div>
+<div style="display: contents"><div>under display: contents</div></div>
+</body></html>"##;
+
+#[test]
+fn every_rect_in_a_pass_is_the_rect_alone() {
+ let doc = laid_out(PAGE);
+ let ids = elements(&doc);
+ assert!(ids.len() > 30, "the page has its elements ({})", ids.len());
+ // tree order (a parent asked before its children) and the reverse (a child first: the walk fills its ancestors)
+ assert_eq!(differences(&doc, &ids), Vec::<String>::new());
+ let reversed: Vec<NodeId> = ids.iter().rev().copied().collect();
+ assert_eq!(differences(&doc, &reversed), Vec::<String>::new());
+ // and the page's turns and hidden boxes are what the pass met
+ let rect = |id: NodeId| doc.get_client_bounding_rect(id).unwrap();
+ let id_of = |id: NodeId| doc.get_node(id).and_then(|n| n.element_data()).and_then(|e| e.attr(blitz_dom::local_name!("id")));
+ let hidden = ids.iter().copied().find(|&id| id_of(id) == Some("hidden")).unwrap();
+ assert_eq!((rect(hidden).width, rect(hidden).height), (0.0, 0.0));
+}
+
+/// A page as big as the app's (a few thousand elements, twenty deep): the pass's time against each element alone.
+/// `cargo test -p raea-sys-page --test rects --release -- --ignored --nocapture`
+#[test]
+#[ignore]
+fn a_big_page_in_one_pass() {
+ let row = (0..20).fold("<span>clip</span>".to_string(), |inner, _| format!("<div>{inner}</div>"));
+ let doc = laid_out(&format!("<!doctype html><html><body>{}</body></html>", row.repeat(150)));
+ let ids = elements(&doc);
+ let time = |f: &dyn Fn()| {
+ let t = std::time::Instant::now();
+ for _ in 0..20 {
+ f();
+ }
+ t.elapsed().as_secs_f64() * 1000.0 / 20.0
+ };
+ let alone = time(&|| ids.iter().for_each(|&id| _ = std::hint::black_box(doc.get_client_bounding_rect(id))));
+ let pass = time(&|| {
+ let mut memo = RectMemo::default();
+ ids.iter().for_each(|&id| _ = std::hint::black_box(doc.get_client_bounding_rect_in(id, &mut memo)))
+ });
+ println!("{} elements: {alone:.2} ms alone, {pass:.2} ms in one pass", ids.len());
+ assert_eq!(differences(&doc, &ids), Vec::<String>::new());
+}
diff --git a/vendor/blitz-dom/src/document.rs b/vendor/blitz-dom/src/document.rs
index ece36e85..889424c5 100644
--- a/vendor/blitz-dom/src/document.rs
+++ b/vendor/blitz-dom/src/document.rs
@@ -2583,17 +2583,7 @@ impl BaseDocument {
// raea: most chains carry no transform and no projection, and then the walk below multiplies a matrix at every
// step only to answer None. Asked first without the math (a page's every element's rect is taken each frame:
// the twins' boxes and the JS's layout snapshot; with 400 timeline clips this was the frame's busiest leaf)
- let mut c = Some(node_id);
- let mut any = false;
- while let Some(id) = c {
- let Some(node) = self.nodes.get(id) else { break };
- if self.projections.contains_key(&id) || node.transform().is_some() {
- any = true;
- break;
- }
- c = node.containing_block();
- }
- if !any {
+ if !walk_up(node_id, |id| self.turned_up(id)) {
return None;
}
// a 3x3 on column vectors (x, y, w), row-major, in CSS px
@@ -2686,21 +2676,39 @@ impl BaseDocument {
})
}
- /// raea: whether `node_id` or an ancestor is `display: none`, so it generates no box (#108).
- fn in_display_none(&self, node_id: NodeId) -> bool {
- let mut current = Some(node_id);
- while let Some(id) = current {
- let Some(node) = self.nodes.get(id) else { return false };
- if node.primary_styles().is_some_and(|s| stylo_taffy::convert::display(s.get_box().display) == taffy::Display::None) {
- return true;
- }
- current = node.parent;
+ /// raea: one step of the walk up the DOM for `display: none` (an element with no box, #108): this node is, or the
+ /// next to ask. A node gone from the tree ends the walk, as a missing one did.
+ fn none_up(&self, id: NodeId) -> Up {
+ match self.nodes.get(id) {
+ None => Up::No,
+ Some(n) if n.primary_styles().is_some_and(|s| stylo_taffy::convert::display(s.get_box().display) == taffy::Display::None) => Up::Yes,
+ Some(n) => n.parent.map_or(Up::No, Up::Next),
+ }
+ }
+
+ /// raea: one step of the walk up the containing blocks for a transform or a projection (transformed_rect's
+ /// first question).
+ fn turned_up(&self, id: NodeId) -> Up {
+ match self.nodes.get(id) {
+ None => Up::No,
+ Some(n) if self.projections.contains_key(&id) || n.transform().is_some() => Up::Yes,
+ Some(n) => n.containing_block().map_or(Up::No, Up::Next),
}
- false
}
/// Computes the size and position of the `Node` relative to the viewport
pub fn get_client_bounding_rect(&self, node_id: NodeId) -> Option<BoundingRect> {
+ self.client_rect(node_id, None)
+ }
+
+ /// raea: [`get_client_bounding_rect`](Self::get_client_bounding_rect) for one of many elements taken in one pass
+ /// over a page laid out once (the layout snapshot's every element, each frame): what an element asks of its
+ /// ancestors is kept in `memo` for the next. The same rect, without two walks to the root for each element.
+ pub fn get_client_bounding_rect_in(&self, node_id: NodeId, memo: &mut RectMemo) -> Option<BoundingRect> {
+ self.client_rect(node_id, Some(memo))
+ }
+
+ fn client_rect(&self, node_id: NodeId, mut memo: Option<&mut RectMemo>) -> Option<BoundingRect> {
// Non-atomic inline elements have no layout box of their own: return
// the union of their per-line-box fragment rects.
if let Some(rects) = self.inline_fragment_rects(node_id) {
@@ -2710,7 +2718,11 @@ impl BaseDocument {
let node = self.get_node(node_id)?;
// raea: an element with no box (it or an ancestor is `display: none`) answers Chrome's zero rect, not whatever
// its last layout left (#108)
- if self.in_display_none(node_id) {
+ let none = match memo.as_deref_mut() {
+ Some(m) => remembered(&mut m.none, &mut m.path, node_id, |id| self.none_up(id)),
+ None => walk_up(node_id, |id| self.none_up(id)),
+ };
+ if none {
return Some(BoundingRect { x: 0.0, y: 0.0, width: 0.0, height: 0.0 });
}
// raea: a table row or row group has no box of its own (its cells are the table grid's items): its rect is
@@ -2728,12 +2740,14 @@ impl BaseDocument {
.children
.iter()
.filter(|c| self.get_node(**c).is_some_and(|n| n.is_element()))
- .filter_map(|c| self.get_client_bounding_rect(*c))
+ .filter_map(|c| self.client_rect(*c, memo.as_deref_mut()))
.reduce(BoundingRect::union);
}
// raea: under a transform (its own or a containing block's) the rect is the transformed box's bounds, as
- // Chrome's getBoundingClientRect is (a skewed or rotated box was its untransformed layout box)
- if let Some(r) = self.transformed_bounds(node_id) {
+ // Chrome's getBoundingClientRect is (a skewed or rotated box was its untransformed layout box). Without a memo
+ // transformed_bounds asks for itself whether there's one on the way up.
+ let turned = memo.is_none_or(|m| remembered(&mut m.turned, &mut m.path, node_id, |id| self.turned_up(id)));
+ if turned && let Some(r) = self.transformed_bounds(node_id) {
return Some(r);
}
let (mut pos, layout) = self.physical_unrounded_geometry(node_id);
@@ -3218,6 +3232,72 @@ pub struct BoundingRect {
pub height: f64,
}
+/// raea: what one pass over a page's elements' rects remembers from one element to the next
+/// ([`BaseDocument::get_client_bounding_rect_in`]): whether a node or an ancestor is `display: none`, and whether a
+/// node's containing-block chain carries a transform or a projection. Each was a walk to the root for every element,
+/// and the layout snapshot takes every element's rect each frame: on a big page, with the rect's position walk, a third
+/// of the app's main thread (11-16). Kept, each node is asked once a pass. Good for one layout: a new one after a resolve.
+#[derive(Default)]
+pub struct RectMemo {
+ /// by a node's slot in the tree: the node asked about and its answer. The whole id is kept, as a stale id (a freed
+ /// node's, still a containing-block link) shares its slot with whatever lives there now, and answers otherwise.
+ none: Vec<Option<(NodeId, bool)>>,
+ turned: Vec<Option<(NodeId, bool)>>,
+ /// the nodes one walk passed, given its answer when it ends
+ path: Vec<NodeId>,
+}
+
+/// A node's slot in the tree: its id's low 32 bits (blitz-traits' NodeId packs the slot there, its version above).
+fn slot(id: NodeId) -> usize {
+ id.as_u64() as u32 as usize
+}
+
+/// One step of a walk up a chain of nodes: the answer is here, or ask the next.
+enum Up {
+ Yes,
+ No,
+ Next(NodeId),
+}
+
+/// The answer a walk from `start` comes to, `up` taking each step.
+fn walk_up(start: NodeId, mut up: impl FnMut(NodeId) -> Up) -> bool {
+ let mut id = start;
+ loop {
+ match up(id) {
+ Up::Yes => return true,
+ Up::No => return false,
+ Up::Next(next) => id = next,
+ }
+ }
+}
+
+/// [`walk_up`], stopping at a node `seen` already has an answer for and giving every node it passed the answer: a
+/// node's is its chain's, so the nodes below one on the same chain share it.
+fn remembered(seen: &mut Vec<Option<(NodeId, bool)>>, path: &mut Vec<NodeId>, start: NodeId, mut up: impl FnMut(NodeId) -> Up) -> bool {
+ path.clear();
+ let yes = walk_up(start, |id| match seen.get(slot(id)).copied().flatten() {
+ Some((asked, yes)) if asked == id => {
+ if yes {
+ Up::Yes
+ } else {
+ Up::No
+ }
+ }
+ _ => {
+ path.push(id);
+ up(id)
+ }
+ });
+ for &id in path.iter() {
+ let s = slot(id);
+ if s >= seen.len() {
+ seen.resize(s + 1, None);
+ }
+ seen[s] = Some((id, yes));
+ }
+ yes
+}
+
impl BoundingRect {
/// The smallest rect containing both `self` and `other`.
pub fn union(self, other: BoundingRect) -> BoundingRect {
diff --git a/vendor/blitz-dom/src/lib.rs b/vendor/blitz-dom/src/lib.rs
index b46b744a..b82f0847 100644
--- a/vendor/blitz-dom/src/lib.rs
+++ b/vendor/blitz-dom/src/lib.rs
@@ -102,7 +102,7 @@ pub use blitz_traits::node_id::NodeId;
// `Node::final_layout`)
pub use config::{DocumentConfig, StyleThreading};
pub use document::{
- BaseDocument, BoundingRect, DocGuard, DocGuardMut, Document, PlainDocument, UserAgentStylesheet,
+ BaseDocument, BoundingRect, DocGuard, DocGuardMut, Document, PlainDocument, RectMemo, UserAgentStylesheet,
};
pub use markup5ever::{
LocalName, Namespace, NamespaceStaticSet, Prefix, PrefixStaticSet, QualName, local_name,