Skip to main content

euv_core/layout/soa/
impl.rs

1use super::*;
2
3/// Exclusive byte end and overlap utilities for `DirtyBufferSpan`.
4impl DirtyBufferSpan {
5    /// Returns the exclusive ending byte offset (`byte_offset + byte_len`).
6    ///
7    /// # Returns
8    ///
9    /// - `usize` - Exclusive byte end offset.
10    #[cfg_attr(not(target_arch = "wasm32"), inline)]
11    #[must_use]
12    pub fn byte_end(&self) -> usize {
13        self.get_byte_offset().saturating_add(self.get_byte_len())
14    }
15
16    /// Returns `true` when this span covers zero bytes.
17    ///
18    /// # Returns
19    ///
20    /// - `bool` - `true` when `byte_len == 0`.
21    #[cfg_attr(not(target_arch = "wasm32"), inline)]
22    #[must_use]
23    pub fn is_empty(&self) -> bool {
24        self.get_byte_len() == 0
25    }
26}
27
28/// Default `DirtySpanCoalescer` configured with `DIRTY_SPAN_MERGE_GAP_BYTES` (`256` bytes).
29impl Default for DirtySpanCoalescer {
30    /// Creates an empty `DirtySpanCoalescer` with the default 256-byte gap merge threshold.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - Initialized dirty span coalescer.
35    fn default() -> Self {
36        Self::with_merge_gap(DIRTY_SPAN_MERGE_GAP_BYTES)
37    }
38}
39
40/// Dirty byte-range collection and gap-bridging coalescing for `DirtySpanCoalescer`.
41impl DirtySpanCoalescer {
42    /// Creates an empty `DirtySpanCoalescer` merging spans separated by at most `merge_gap_bytes`.
43    ///
44    /// # Arguments
45    ///
46    /// - `usize` - Maximum inter-span byte gap bridged during coalescing.
47    ///
48    /// # Returns
49    ///
50    /// - `Self` - Configured dirty span coalescer.
51    #[must_use]
52    pub fn with_merge_gap(merge_gap_bytes: usize) -> Self {
53        Self {
54            merge_gap_bytes,
55            pending: Vec::new(),
56            coalesced: Vec::new(),
57            needs_coalesce: false,
58            retained_primitives: Vec::new(),
59            last_dirty_bytes: 0,
60            last_full_bytes: 0,
61            cumulative_bytes_saved: 0,
62        }
63    }
64
65    /// Clears all pending and coalesced spans while retaining backing vector capacity.
66    pub fn clear(&mut self) {
67        let Self {
68            pending,
69            coalesced,
70            needs_coalesce,
71            ..
72        } = self;
73        pending.clear();
74        coalesced.clear();
75        *needs_coalesce = false;
76    }
77
78    /// Records a dirty byte range `[byte_offset .. byte_offset + byte_len)`.
79    ///
80    /// # Arguments
81    ///
82    /// - `usize` - Inclusive starting byte offset.
83    /// - `usize` - Byte length of the dirty range.
84    pub fn mark_range(&mut self, byte_offset: usize, byte_len: usize) {
85        if byte_len == 0 {
86            return;
87        }
88        let Self {
89            pending,
90            needs_coalesce,
91            ..
92        } = self;
93        pending.push(DirtyBufferSpan::new(byte_offset, byte_len));
94        *needs_coalesce = true;
95    }
96
97    /// Records a single dirty fixed-stride record at `elem_index` (`elem_index * stride_bytes`).
98    ///
99    /// # Arguments
100    ///
101    /// - `usize` - Zero-based element index inside the target GPU storage buffer.
102    /// - `usize` - Byte stride per element.
103    pub fn mark_element(&mut self, elem_index: usize, stride_bytes: usize) {
104        self.mark_range(elem_index.saturating_mul(stride_bytes), stride_bytes);
105    }
106
107    /// Sorts and merges all pending spans whose inter-span gap is `<= merge_gap_bytes`, returning the coalesced slice.
108    ///
109    /// # Returns
110    ///
111    /// - `&[DirtyBufferSpan]` - Sorted, non-overlapping coalesced dirty spans ready for GPU upload.
112    pub fn coalesce(&mut self) -> &[DirtyBufferSpan] {
113        let Self {
114            merge_gap_bytes,
115            pending,
116            coalesced,
117            needs_coalesce,
118            ..
119        } = self;
120        if !*needs_coalesce {
121            return coalesced.as_slice();
122        }
123        coalesced.clear();
124        if !pending.is_empty() {
125            pending.sort_unstable_by_key(|span: &DirtyBufferSpan| {
126                (span.get_byte_offset(), span.get_byte_len())
127            });
128            let mut active: DirtyBufferSpan = pending[0];
129            for next_span in pending.iter().copied().skip(1) {
130                let active_end: usize = active.byte_end();
131                let next_start: usize = next_span.get_byte_offset();
132                let next_end: usize = next_span.byte_end();
133                if next_start <= active_end.saturating_add(*merge_gap_bytes) {
134                    let merged_end: usize = active_end.max(next_end);
135                    active.set_byte_len(merged_end.saturating_sub(active.get_byte_offset()));
136                } else {
137                    coalesced.push(active);
138                    active = next_span;
139                }
140            }
141            coalesced.push(active);
142            pending.clear();
143        }
144        *needs_coalesce = false;
145        coalesced.as_slice()
146    }
147
148    /// Returns the total number of bytes covered by all currently coalesced spans.
149    ///
150    /// # Returns
151    ///
152    /// - `usize` - Sum of `byte_len` across all coalesced spans.
153    #[must_use]
154    pub fn total_coalesced_bytes(&mut self) -> usize {
155        self.coalesce()
156            .iter()
157            .map(DirtyBufferSpan::get_byte_len)
158            .sum()
159    }
160
161    /// Returns `true` when no pending or coalesced dirty spans are recorded.
162    ///
163    /// # Returns
164    ///
165    /// - `bool` - `true` when empty.
166    #[must_use]
167    pub fn is_empty(&self) -> bool {
168        let Self {
169            pending, coalesced, ..
170        } = self;
171        pending.is_empty() && coalesced.is_empty()
172    }
173
174    /// Diffs `current` against the retained primitive buffer and returns coalesced dirty byte spans for Pass 1 upload.
175    ///
176    /// # Arguments
177    ///
178    /// - `&[GpuPrimitiveInstance]` - Current frame's packed 64-byte primitive slice.
179    ///
180    /// # Returns
181    ///
182    /// - `&[DirtyBufferSpan]` - Coalesced dirty byte ranges requiring GPU copy.
183    pub fn diff_and_coalesce(&mut self, current: &[GpuPrimitiveInstance]) -> &[DirtyBufferSpan] {
184        let stride: usize = size_of::<GpuPrimitiveInstance>();
185        let full_bytes: usize = current.len().saturating_mul(stride);
186        let Self {
187            merge_gap_bytes,
188            pending,
189            coalesced,
190            needs_coalesce,
191            retained_primitives,
192            last_dirty_bytes,
193            last_full_bytes,
194            cumulative_bytes_saved,
195        } = self;
196        pending.clear();
197        coalesced.clear();
198        *needs_coalesce = false;
199        let prev_len: usize = retained_primitives.len();
200        let cur_len: usize = current.len();
201        if prev_len != cur_len {
202            retained_primitives.clear();
203            retained_primitives.extend_from_slice(current);
204            if full_bytes > 0 {
205                coalesced.push(DirtyBufferSpan::new(0, full_bytes));
206            }
207            *last_dirty_bytes = full_bytes;
208            *last_full_bytes = full_bytes;
209            return coalesced.as_slice();
210        }
211        let mut run_start: Option<usize> = None;
212        for (idx, prim) in current.iter().enumerate() {
213            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding bytes.
214            let prev_words: &[u64; 8] = unsafe {
215                &*(&retained_primitives[idx] as *const GpuPrimitiveInstance).cast::<[u64; 8]>()
216            };
217            // SAFETY: `GpuPrimitiveInstance` is `#[repr(C)]` 64 bytes with no uninitialized padding bytes.
218            let cur_words: &[u64; 8] =
219                unsafe { &*(prim as *const GpuPrimitiveInstance).cast::<[u64; 8]>() };
220            if prev_words != cur_words {
221                retained_primitives[idx] = *prim;
222                if run_start.is_none() {
223                    run_start = Some(idx);
224                }
225            } else if let Some(start_idx) = run_start.take() {
226                coalesced.push(DirtyBufferSpan::new(
227                    start_idx.saturating_mul(stride),
228                    idx.saturating_sub(start_idx).saturating_mul(stride),
229                ));
230            }
231        }
232        if let Some(start_idx) = run_start {
233            coalesced.push(DirtyBufferSpan::new(
234                start_idx.saturating_mul(stride),
235                cur_len.saturating_sub(start_idx).saturating_mul(stride),
236            ));
237        }
238        coalesce_dirty_buffer_spans(coalesced, *merge_gap_bytes);
239        let dirty_bytes: usize = coalesced
240            .iter()
241            .map(|span: &DirtyBufferSpan| span.get_byte_len())
242            .sum();
243        *last_dirty_bytes = dirty_bytes;
244        *last_full_bytes = full_bytes;
245        *cumulative_bytes_saved =
246            cumulative_bytes_saved.saturating_add(full_bytes.saturating_sub(dirty_bytes) as u64);
247        coalesced.as_slice()
248    }
249
250    /// Returns the most recent upload bandwidth savings ratio in `[0.0, 1.0]`.
251    ///
252    /// # Returns
253    ///
254    /// - `f32` - Fraction of full-frame primitive bytes avoided by dirty-span coalescing.
255    #[must_use]
256    pub fn last_savings_ratio(&self) -> f32 {
257        let full: usize = self.get_last_full_bytes();
258        if full == 0 {
259            return 0.0;
260        }
261        let dirty: usize = self.get_last_dirty_bytes().min(full);
262        ((full - dirty) as f32) / (full as f32)
263    }
264
265    /// Clears the retained shadow buffer and dirty spans, forcing a full upload on the next frame.
266    pub fn reset(&mut self) {
267        let Self {
268            pending,
269            coalesced,
270            needs_coalesce,
271            retained_primitives,
272            ..
273        } = self;
274        pending.clear();
275        coalesced.clear();
276        *needs_coalesce = false;
277        retained_primitives.clear();
278    }
279}
280
281/// Level-contiguous Breadth-First Search topology construction and query helpers for `FlatBfsTopology`.
282impl FlatBfsTopology {
283    /// Returns the total number of reachable nodes in the BFS ordering.
284    ///
285    /// # Returns
286    ///
287    /// - `usize` - Reachable BFS node count.
288    #[cfg_attr(not(target_arch = "wasm32"), inline)]
289    #[must_use]
290    pub fn node_count(&self) -> usize {
291        self.get_bfs_to_arena().len()
292    }
293
294    /// Returns the number of tree depth levels (`0` when empty).
295    ///
296    /// # Returns
297    ///
298    /// - `usize` - Depth level count.
299    #[cfg_attr(not(target_arch = "wasm32"), inline)]
300    #[must_use]
301    pub fn depth_count(&self) -> usize {
302        self.get_level_offsets().len().saturating_sub(1)
303    }
304
305    /// Returns the inclusive-exclusive BFS index range `[start, end)` for tree depth `level`.
306    ///
307    /// # Arguments
308    ///
309    /// - `usize` - Zero-based tree depth level (`0` = root).
310    ///
311    /// # Returns
312    ///
313    /// - `(usize, usize)` - Contiguous BFS slice bounds for `level`.
314    #[cfg_attr(not(target_arch = "wasm32"), inline)]
315    #[must_use]
316    pub fn level_range(&self, level: usize) -> (usize, usize) {
317        let offsets: &[u32] = self.get_level_offsets().as_slice();
318        if level + 1 >= offsets.len() {
319            return (0, 0);
320        }
321        (offsets[level] as usize, offsets[level + 1] as usize)
322    }
323
324    /// Returns the contiguous BFS index range `[first, first + count)` of direct children for `bfs_index`.
325    ///
326    /// # Arguments
327    ///
328    /// - `usize` - BFS node index.
329    ///
330    /// # Returns
331    ///
332    /// - `(usize, usize)` - Contiguous direct-child BFS slice bounds.
333    #[cfg_attr(not(target_arch = "wasm32"), inline)]
334    #[must_use]
335    pub fn children_bfs_range(&self, bfs_index: usize) -> (usize, usize) {
336        let first: u32 = self
337            .get_child_first()
338            .get(bfs_index)
339            .copied()
340            .unwrap_or(GPU_LAYOUT_INDEX_NONE);
341        let count: u32 = self.get_child_count().get(bfs_index).copied().unwrap_or(0);
342        if first == GPU_LAYOUT_INDEX_NONE || count == 0 {
343            return (0, 0);
344        }
345        let start: usize = first as usize;
346        (start, start.saturating_add(count as usize))
347    }
348
349    /// Rebuilds the level-contiguous BFS topology from `tree` only when `topology_revision` or `root` changed.
350    ///
351    /// # Arguments
352    ///
353    /// - `&SceneTree` - Retained scene tree reference.
354    ///
355    /// # Returns
356    ///
357    /// - `bool` - `true` when topology was rebuilt; `false` when already up to date.
358    pub fn rebuild_from_tree(&mut self, tree: &SceneTree) -> bool {
359        let root_id: NodeId = tree.get_root();
360        let root_arena: u32 = root_id.get_index();
361        let tree_topo_rev: u64 = tree.get_topology_revision();
362        let arena_len: usize = tree.get_nodes().len();
363        if self.get_topology_revision() == tree_topo_rev
364            && self.get_root_arena_index() == root_arena
365            && self.get_arena_to_bfs().len() == arena_len
366            && !self.get_bfs_to_arena().is_empty()
367        {
368            return false;
369        }
370        let Self {
371            topology_revision,
372            root_arena_index,
373            bfs_to_arena,
374            arena_to_bfs,
375            parent_bfs,
376            child_first,
377            child_count,
378            level_offsets,
379            subtree_sizes,
380        } = self;
381        bfs_to_arena.clear();
382        parent_bfs.clear();
383        child_first.clear();
384        child_count.clear();
385        level_offsets.clear();
386        subtree_sizes.clear();
387        arena_to_bfs.clear();
388        arena_to_bfs.resize(arena_len, GPU_LAYOUT_INDEX_NONE);
389        if tree.get_node(root_id).is_none() {
390            *topology_revision = tree_topo_rev;
391            *root_arena_index = GPU_LAYOUT_INDEX_NONE;
392            return true;
393        }
394        let live_cap: usize = tree.live_node_count().max(1);
395        if bfs_to_arena.capacity() < live_cap {
396            bfs_to_arena.reserve(live_cap - bfs_to_arena.len());
397            parent_bfs.reserve(live_cap - parent_bfs.len());
398            child_first.reserve(live_cap - child_first.len());
399            child_count.reserve(live_cap - child_count.len());
400        }
401        let meta_slice: &[NodeMeta] = tree.get_meta().as_slice();
402        let topo_slice: &[NodeTopology] = tree.get_topology().as_slice();
403        arena_to_bfs[root_arena as usize] = 0;
404        bfs_to_arena.push(root_arena);
405        parent_bfs.push(GPU_LAYOUT_INDEX_NONE);
406        child_first.push(GPU_LAYOUT_INDEX_NONE);
407        child_count.push(0);
408        level_offsets.push(0);
409        let mut level_start: usize = 0;
410        while level_start < bfs_to_arena.len() {
411            let level_end: usize = bfs_to_arena.len();
412            level_offsets.push(level_end as u32);
413            for cur_bfs in level_start..level_end {
414                let cur_arena: usize = bfs_to_arena[cur_bfs] as usize;
415                let mut child_arena: u32 = topo_slice[cur_arena].get_first_child();
416                let mut first_slot: u32 = GPU_LAYOUT_INDEX_NONE;
417                let mut pushed_children: u32 = 0;
418                while child_arena != NODE_INDEX_NONE {
419                    let child_idx: usize = child_arena as usize;
420                    let next_sib: u32 = topo_slice[child_idx].get_next_sibling();
421                    let is_alive: bool = (meta_slice[child_idx].get_flags() & NODE_FLAG_ALIVE) != 0;
422                    if is_alive && arena_to_bfs[child_idx] == GPU_LAYOUT_INDEX_NONE {
423                        let next_bfs: u32 = bfs_to_arena.len() as u32;
424                        if first_slot == GPU_LAYOUT_INDEX_NONE {
425                            first_slot = next_bfs;
426                        }
427                        arena_to_bfs[child_idx] = next_bfs;
428                        bfs_to_arena.push(child_arena);
429                        parent_bfs.push(cur_bfs as u32);
430                        child_first.push(GPU_LAYOUT_INDEX_NONE);
431                        child_count.push(0);
432                        pushed_children = pushed_children.saturating_add(1);
433                    }
434                    child_arena = next_sib;
435                }
436                child_first[cur_bfs] = first_slot;
437                child_count[cur_bfs] = pushed_children;
438            }
439            level_start = level_end;
440        }
441        let total_bfs: usize = bfs_to_arena.len();
442        subtree_sizes.resize(total_bfs, 1);
443        for cur_bfs in (1..total_bfs).rev() {
444            let parent_idx: u32 = parent_bfs[cur_bfs];
445            if parent_idx != GPU_LAYOUT_INDEX_NONE {
446                let sub_val: u32 = subtree_sizes[cur_bfs];
447                let p_slot: usize = parent_idx as usize;
448                subtree_sizes[p_slot] = subtree_sizes[p_slot].saturating_add(sub_val);
449            }
450        }
451        *topology_revision = tree_topo_rev;
452        *root_arena_index = root_arena;
453        true
454    }
455}
456
457/// Incremental `SceneTree` extraction, GPU compute input packing, and box write-back for `SceneLayoutSoa`.
458impl SceneLayoutSoa {
459    /// Returns the UTF-8 text string slice stored in `text_bytes` for arena slot `arena_index`.
460    ///
461    /// # Arguments
462    ///
463    /// - `usize` - Scene tree arena slot index.
464    ///
465    /// # Returns
466    ///
467    /// - `&str` - Contiguous UTF-8 text payload (`""` for non-text nodes).
468    #[cfg_attr(not(target_arch = "wasm32"), inline)]
469    #[must_use]
470    pub fn text_for_arena(&self, arena_index: usize) -> &str {
471        let Some(slice) = self.get_text_slices().get(arena_index).copied() else {
472            return "";
473        };
474        let start: usize = slice.get_byte_start() as usize;
475        let end: usize = start.saturating_add(slice.get_byte_len() as usize);
476        if end > self.get_text_bytes().len() || start == end {
477            return "";
478        }
479        from_utf8(&self.get_text_bytes()[start..end]).unwrap_or("")
480    }
481
482    /// Synchronizes `FlatBfsTopology`, dense `Send + Sync` SoA slabs, and GPU dirty-range inputs from `tree`.
483    ///
484    /// # Arguments
485    ///
486    /// - `&SceneTree` - Retained scene tree to mirror into SoA slabs.
487    ///
488    /// # Returns
489    ///
490    /// - `SoaSyncMode` - Whether sync was skipped, incremental, or a full topology rebuild.
491    pub fn sync_from_tree(&mut self, tree: &SceneTree) -> SoaSyncMode {
492        let tree_rev: u64 = tree.get_revision();
493        let tree_topo_rev: u64 = tree.get_topology_revision();
494        let tree_serial_epoch: u64 = tree.get_serial_layout_epoch();
495        if self.get_synced_revision() == tree_rev
496            && self.get_synced_topology_revision() == tree_topo_rev
497            && self.get_synced_serial_epoch() == tree_serial_epoch
498            && !self.get_topology().get_bfs_to_arena().is_empty()
499        {
500            self.get_mut_input_dirty_spans().clear();
501            self.get_mut_visual_dirty_spans().clear();
502            self.set_last_sync_mode(SoaSyncMode::SkippedClean);
503            return SoaSyncMode::SkippedClean;
504        }
505        let topo_rebuilt: bool = self.get_mut_topology().rebuild_from_tree(tree);
506        let arena_len: usize = tree.get_nodes().len();
507        let bfs_len: usize = self.get_topology().node_count();
508        let Self {
509            synced_revision,
510            synced_topology_revision,
511            synced_serial_epoch,
512            last_sync_mode,
513            topology,
514            node_ids,
515            node_kinds,
516            layout_styles,
517            text_styles,
518            border_widths,
519            transforms,
520            layout_boxes,
521            dirty_masks,
522            synced_node_epochs,
523            text_slices,
524            text_bytes,
525            image_sizes,
526            gpu_inputs,
527            gpu_outputs,
528            gpu_visuals,
529            input_dirty_spans,
530            visual_dirty_spans,
531        } = self;
532        let serial_diverged: bool = *synced_serial_epoch != tree_serial_epoch;
533        let force_full: bool = topo_rebuilt
534            || node_ids.len() != arena_len
535            || synced_node_epochs.len() != arena_len
536            || gpu_inputs.len() != bfs_len
537            || gpu_visuals.len() != bfs_len;
538        input_dirty_spans.clear();
539        visual_dirty_spans.clear();
540        if force_full {
541            node_ids.resize(arena_len, NodeId::default());
542            node_kinds.resize(arena_len, SoaNodeKindTag::Container);
543            layout_styles.resize(arena_len, LayoutStyle::default());
544            text_styles.resize(arena_len, TextStyle::default());
545            border_widths.resize(arena_len, 0.0);
546            transforms.resize(arena_len, Transform2D::default());
547            layout_boxes.resize(arena_len, LayoutBox::default());
548            dirty_masks.resize(arena_len, 0);
549            synced_node_epochs.resize(arena_len, 0);
550            text_slices.resize(arena_len, SoaTextSlice::default());
551            image_sizes.resize(arena_len, Size::default());
552            text_bytes.clear();
553            gpu_inputs.resize(bfs_len, GpuLayoutNodeInput::default());
554            gpu_outputs.resize(bfs_len, GpuLayoutNodeOutput::default());
555            gpu_visuals.resize(bfs_len, GpuVisualStyleInput::default());
556        }
557        let nodes: &[SceneNode] = tree.get_nodes().as_slice();
558        let meta_slice: &[NodeMeta] = tree.get_meta().as_slice();
559        let tree_epochs: &[u32] = tree.get_node_mutation_epochs().as_slice();
560        let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
561        let parent_bfs: &[u32] = topology.get_parent_bfs().as_slice();
562        let child_first: &[u32] = topology.get_child_first().as_slice();
563        let child_count: &[u32] = topology.get_child_count().as_slice();
564        for bfs_idx in 0..bfs_len {
565            let arena_idx: usize = bfs_to_arena[bfs_idx] as usize;
566            let node: &SceneNode = &nodes[arena_idx];
567            let dirty_bits: u16 = meta_slice[arena_idx].get_dirty();
568            let node_epoch: u32 = tree_epochs.get(arena_idx).copied().unwrap_or(0);
569            let node_changed: bool = force_full
570                || dirty_bits != 0
571                || dirty_masks[arena_idx] != dirty_bits
572                || synced_node_epochs[arena_idx] != node_epoch
573                || node_ids[arena_idx].get_generation() != node.get_generation();
574            if !node_changed {
575                if serial_diverged {
576                    let cur_box: LayoutBox = node.get_layout_box();
577                    layout_boxes[arena_idx] = cur_box;
578                    dirty_masks[arena_idx] = dirty_bits;
579                    let bounds: Rect = cur_box.get_bounds();
580                    let content_bounds: Rect = cur_box.get_content_bounds();
581                    gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
582                        rect: [
583                            bounds.get_x(),
584                            bounds.get_y(),
585                            bounds.get_width(),
586                            bounds.get_height(),
587                        ],
588                        content_rect: [
589                            content_bounds.get_x(),
590                            content_bounds.get_y(),
591                            content_bounds.get_width(),
592                            content_bounds.get_height(),
593                        ],
594                    };
595                }
596                continue;
597            }
598            synced_node_epochs[arena_idx] = node_epoch;
599            node_ids[arena_idx] = NodeId::new(arena_idx as u32, node.get_generation());
600            let kind_tag: SoaNodeKindTag = soa_kind_from_node_kind(node.get_kind());
601            node_kinds[arena_idx] = kind_tag;
602            let style_ref: &Style = node.style_ref();
603            let layout_style: LayoutStyle = *style_ref.layout_ref();
604            let paint_style: &PaintStyle = style_ref.paint_ref();
605            let text_style: TextStyle = *style_ref.text_ref();
606            let border_width: f32 = paint_style.get_border().get_width();
607            layout_styles[arena_idx] = layout_style;
608            text_styles[arena_idx] = text_style;
609            border_widths[arena_idx] = border_width;
610            transforms[arena_idx] = paint_style.get_transform();
611            layout_boxes[arena_idx] = node.get_layout_box();
612            dirty_masks[arena_idx] = dirty_bits;
613            let mut intrinsic_size: Size = Size::default();
614            let mut wrapping_text: bool = false;
615            match node.get_kind() {
616                NodeKind::Text(text) => {
617                    let raw_bytes: &[u8] = text.as_bytes();
618                    let prev_slice: SoaTextSlice = text_slices[arena_idx];
619                    let prev_start: usize = prev_slice.get_byte_start() as usize;
620                    let prev_len: usize = prev_slice.get_byte_len() as usize;
621                    let next_slice: SoaTextSlice = if !force_full
622                        && raw_bytes.len() <= prev_len
623                        && prev_start.saturating_add(prev_len) <= text_bytes.len()
624                    {
625                        text_bytes[prev_start..prev_start + raw_bytes.len()]
626                            .copy_from_slice(raw_bytes);
627                        SoaTextSlice::new(
628                            prev_slice.get_byte_start(),
629                            raw_bytes.len() as u32,
630                            text.is_ascii(),
631                        )
632                    } else {
633                        let text_start: u32 = text_bytes.len() as u32;
634                        text_bytes.extend_from_slice(raw_bytes);
635                        SoaTextSlice::new(text_start, raw_bytes.len() as u32, text.is_ascii())
636                    };
637                    text_slices[arena_idx] = next_slice;
638                    wrapping_text = text_style.get_overflow() != TextOverflow::Clip;
639                }
640                NodeKind::Input(input_state) => {
641                    let sample: &str = if input_state.get_value().is_empty() {
642                        input_state.get_placeholder().as_str()
643                    } else {
644                        input_state.get_value().as_str()
645                    };
646                    let raw_bytes: &[u8] = sample.as_bytes();
647                    let prev_slice: SoaTextSlice = text_slices[arena_idx];
648                    let prev_start: usize = prev_slice.get_byte_start() as usize;
649                    let prev_len: usize = prev_slice.get_byte_len() as usize;
650                    let next_slice: SoaTextSlice = if !force_full
651                        && raw_bytes.len() <= prev_len
652                        && prev_start.saturating_add(prev_len) <= text_bytes.len()
653                    {
654                        text_bytes[prev_start..prev_start + raw_bytes.len()]
655                            .copy_from_slice(raw_bytes);
656                        SoaTextSlice::new(
657                            prev_slice.get_byte_start(),
658                            raw_bytes.len() as u32,
659                            sample.is_ascii(),
660                        )
661                    } else {
662                        let text_start: u32 = text_bytes.len() as u32;
663                        text_bytes.extend_from_slice(raw_bytes);
664                        SoaTextSlice::new(text_start, raw_bytes.len() as u32, sample.is_ascii())
665                    };
666                    text_slices[arena_idx] = next_slice;
667                    wrapping_text = text_style.get_overflow() != TextOverflow::Clip;
668                }
669                NodeKind::Image(img) => {
670                    intrinsic_size = Size::new(img.get_width() as f32, img.get_height() as f32);
671                    image_sizes[arena_idx] = intrinsic_size;
672                    text_slices[arena_idx] = SoaTextSlice::default();
673                }
674                NodeKind::View
675                | NodeKind::ScrollView
676                | NodeKind::Portal
677                | NodeKind::Fragment
678                | NodeKind::Canvas(_) => {
679                    text_slices[arena_idx] = SoaTextSlice::default();
680                }
681            }
682            let p_bfs: u32 = parent_bfs[bfs_idx];
683            let clip_ancestor_bfs: u32 = if p_bfs == GPU_LAYOUT_INDEX_NONE {
684                GPU_LAYOUT_INDEX_NONE
685            } else {
686                let p_arena: usize = bfs_to_arena[p_bfs as usize] as usize;
687                if matches!(
688                    layout_styles[p_arena].get_overflow(),
689                    Overflow::Hidden | Overflow::Scroll
690                ) {
691                    p_bfs
692                } else {
693                    gpu_visuals[p_bfs as usize].get_clip_ancestor_bfs()
694                }
695            };
696            let scroll_layer_id: u32 = if p_bfs == GPU_LAYOUT_INDEX_NONE {
697                0
698            } else {
699                gpu_visuals[p_bfs as usize].get_scroll_layer_id()
700            };
701            let next_input: GpuLayoutNodeInput = pack_gpu_layout_node_input(
702                (p_bfs, child_first[bfs_idx], child_count[bfs_idx]),
703                layout_style,
704                kind_tag,
705                (border_width, dirty_bits, intrinsic_size, wrapping_text),
706            );
707            if force_full || gpu_inputs[bfs_idx] != next_input {
708                gpu_inputs[bfs_idx] = next_input;
709                if !force_full {
710                    input_dirty_spans.mark_element(bfs_idx, GPU_LAYOUT_NODE_INPUT_BYTES);
711                }
712            }
713            let next_visual: GpuVisualStyleInput = pack_gpu_visual_style_input(
714                paint_style,
715                layout_style,
716                clip_ancestor_bfs,
717                scroll_layer_id,
718            );
719            if force_full || gpu_visuals[bfs_idx] != next_visual {
720                gpu_visuals[bfs_idx] = next_visual;
721                if !force_full {
722                    visual_dirty_spans.mark_element(bfs_idx, GPU_VISUAL_STYLE_INPUT_BYTES);
723                }
724            }
725            let cur_box: LayoutBox = layout_boxes[arena_idx];
726            let bounds: Rect = cur_box.get_bounds();
727            let content_bounds: Rect = cur_box.get_content_bounds();
728            gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
729                rect: [
730                    bounds.get_x(),
731                    bounds.get_y(),
732                    bounds.get_width(),
733                    bounds.get_height(),
734                ],
735                content_rect: [
736                    content_bounds.get_x(),
737                    content_bounds.get_y(),
738                    content_bounds.get_width(),
739                    content_bounds.get_height(),
740                ],
741            };
742        }
743        if force_full && bfs_len > 0 {
744            input_dirty_spans.mark_range(0, bfs_len.saturating_mul(GPU_LAYOUT_NODE_INPUT_BYTES));
745            visual_dirty_spans.mark_range(0, bfs_len.saturating_mul(GPU_VISUAL_STYLE_INPUT_BYTES));
746        }
747        *synced_revision = tree_rev;
748        *synced_topology_revision = tree_topo_rev;
749        *synced_serial_epoch = tree_serial_epoch;
750        let sync_mode: SoaSyncMode = if force_full {
751            SoaSyncMode::FullRebuild
752        } else {
753            SoaSyncMode::Incremental
754        };
755        *last_sync_mode = sync_mode;
756        sync_mode
757    }
758
759    /// Mirrors updated arena-indexed `layout_boxes` into BFS-ordered `gpu_outputs` for downstream GPU indirect rendering.
760    pub fn sync_gpu_outputs_from_boxes(&mut self) {
761        let Self {
762            topology,
763            layout_boxes,
764            gpu_outputs,
765            ..
766        } = self;
767        let bfs_to_arena: &[u32] = topology.get_bfs_to_arena().as_slice();
768        if gpu_outputs.len() != bfs_to_arena.len() {
769            gpu_outputs.resize(bfs_to_arena.len(), GpuLayoutNodeOutput::default());
770        }
771        for (bfs_idx, &arena_u32) in bfs_to_arena.iter().enumerate() {
772            let cur_box: LayoutBox = layout_boxes[arena_u32 as usize];
773            let bounds: Rect = cur_box.get_bounds();
774            let content_bounds: Rect = cur_box.get_content_bounds();
775            gpu_outputs[bfs_idx] = GpuLayoutNodeOutput {
776                rect: [
777                    bounds.get_x(),
778                    bounds.get_y(),
779                    bounds.get_width(),
780                    bounds.get_height(),
781                ],
782                content_rect: [
783                    content_bounds.get_x(),
784                    content_bounds.get_y(),
785                    content_bounds.get_width(),
786                    content_bounds.get_height(),
787                ],
788            };
789        }
790    }
791
792    /// Exports this synchronized `SceneLayoutSoa` directly into a `GpuComputeSceneInput` sharing the exact unified `GpuLayoutNodeInput` and `GpuVisualStyleInput` ABI.
793    ///
794    /// # Arguments
795    ///
796    /// - `f32` - Physical viewport width in pixels.
797    /// - `f32` - Physical viewport height in pixels.
798    /// - `f32` - Simulation frame delta time in seconds.
799    ///
800    /// # Returns
801    ///
802    /// - `GpuComputeSceneInput` - Ready-to-dispatch compute layout scene mirroring `topology` and `gpu_visuals`.
803    #[must_use]
804    pub fn to_gpu_compute_scene(
805        &self,
806        viewport_width: f32,
807        viewport_height: f32,
808        dt_secs: f32,
809    ) -> GpuComputeSceneInput {
810        let bfs_to_arena: &[u32] = self.get_topology().get_bfs_to_arena().as_slice();
811        let node_count: usize = bfs_to_arena.len();
812        let mut nodes: Vec<GpuLayoutNodeInput> = Vec::with_capacity(node_count);
813        for (bfs_idx, &arena_u32) in bfs_to_arena.iter().enumerate() {
814            let mut input: GpuLayoutNodeInput = self
815                .get_gpu_inputs()
816                .get(bfs_idx)
817                .copied()
818                .unwrap_or_default();
819            let style: LayoutStyle = self
820                .get_layout_styles()
821                .get(arena_u32 as usize)
822                .copied()
823                .unwrap_or_default();
824            let mode: GpuLayoutMode = match style.get_display() {
825                Display::None | Display::Block => GpuLayoutMode::Block,
826                Display::Grid => GpuLayoutMode::Grid,
827                Display::Flex => match style.get_flex_direction() {
828                    FlexDirection::Row | FlexDirection::RowReverse => GpuLayoutMode::FlexRow,
829                    FlexDirection::Column | FlexDirection::ColumnReverse => {
830                        GpuLayoutMode::FlexColumn
831                    }
832                },
833            };
834            let justify: GpuJustifyMode = match style.get_justify_content() {
835                JustifyContent::Start => GpuJustifyMode::Start,
836                JustifyContent::Center => GpuJustifyMode::Center,
837                JustifyContent::End => GpuJustifyMode::End,
838                JustifyContent::SpaceBetween
839                | JustifyContent::SpaceAround
840                | JustifyContent::SpaceEvenly => GpuJustifyMode::SpaceBetween,
841            };
842            let align: GpuAlignMode = match style.get_align_items() {
843                AlignItems::Start => GpuAlignMode::Start,
844                AlignItems::Center => GpuAlignMode::Center,
845                AlignItems::End => GpuAlignMode::End,
846                AlignItems::Stretch => GpuAlignMode::Stretch,
847            };
848            let visible: bool = style.get_display() != Display::None;
849            let clips: bool = matches!(style.get_overflow(), Overflow::Hidden | Overflow::Scroll);
850            let visual_color: u32 = self
851                .get_gpu_visuals()
852                .get(bfs_idx)
853                .map_or(0, GpuVisualStyleInput::get_color_rgba);
854            let emit_visual: bool = visible && (visual_color >> 24) > 0;
855            input.set_flags_kind(pack_gpu_layout_flags(
856                mode,
857                justify,
858                align,
859                visible,
860                clips,
861                emit_visual,
862            ));
863            nodes.push(input);
864        }
865        let safe_w: f32 = viewport_width.max(1.0);
866        let safe_h: f32 = viewport_height.max(1.0);
867        GpuComputeSceneInput {
868            nodes,
869            visuals: self.get_gpu_visuals().clone(),
870            level_offsets: self.get_topology().get_level_offsets().clone(),
871            viewport_size: [safe_w, safe_h],
872            root_boundary_rect: [0.0, 0.0, safe_w, safe_h],
873            dt_secs: if dt_secs.is_finite() && dt_secs > 0.0 {
874                dt_secs
875            } else {
876                1.0 / 120.0
877            },
878            pick_point: None,
879            clear_color: Color::rgba(0, 0, 0, 0),
880        }
881    }
882}