Skip to main content

euv_core/render/command/
impl.rs

1use super::*;
2
3/// Command emission helpers for `DisplayList`.
4impl DisplayList {
5    /// Clears all commands while preserving allocated backing capacity.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Mutable display list.
10    /// - `Size` - Target logical viewport size.
11    /// - `f32` - Active DPI scale factor.
12    pub fn reset(&mut self, viewport: Size, scale_factor: f32) {
13        self.get_mut_commands().clear();
14        self.set_viewport(viewport);
15        self.set_scale_factor(scale_factor.max(0.5));
16        self.set_portal_split_index(0);
17    }
18
19    /// Appends a single `DrawCommand` to the list.
20    ///
21    /// # Arguments
22    ///
23    /// - `&Self` - Mutable display list.
24    /// - `DrawCommand` - Command to push.
25    pub fn push(&mut self, command: DrawCommand) {
26        self.get_mut_commands().push(command);
27    }
28
29    /// Returns total emitted command count.
30    ///
31    /// # Arguments
32    ///
33    /// - `&Self` - Display list reference.
34    ///
35    /// # Returns
36    ///
37    /// - `usize` - Number of commands.
38    #[must_use]
39    pub fn len(&self) -> usize {
40        self.get_commands().len()
41    }
42
43    /// Returns true when the display list contains zero commands.
44    ///
45    /// # Arguments
46    ///
47    /// - `&Self` - Display list reference.
48    ///
49    /// # Returns
50    ///
51    /// - `bool` - True if empty.
52    #[must_use]
53    pub fn is_empty(&self) -> bool {
54        self.get_commands().is_empty()
55    }
56
57    /// Folds a 64-bit value into an FNV-1a accumulator.
58    ///
59    /// # Arguments
60    ///
61    /// - `&mut u64` - Mutable hash accumulator.
62    /// - `u64` - Value to fold into the digest.
63    fn mix_hash(hash: &mut u64, value: u64) {
64        *hash ^= value;
65        *hash = hash.wrapping_mul(FNV1A_PRIME);
66    }
67
68    /// Computes a fast O(commands) 64-bit FNV-1a digest over the display list without scanning framebuffer pixels.
69    ///
70    /// # Arguments
71    ///
72    /// - `&Self` - Display list reference.
73    ///
74    /// # Returns
75    ///
76    /// - `u64` - Deterministic command-stream digest.
77    #[must_use]
78    pub fn fast_hash(&self) -> u64 {
79        let mut hash: u64 = FNV1A_OFFSET_BASIS;
80        Self::mix_hash(&mut hash, self.get_commands().len() as u64);
81        Self::mix_hash(&mut hash, self.get_viewport().get_width().to_bits() as u64);
82        Self::mix_hash(&mut hash, self.get_viewport().get_height().to_bits() as u64);
83        Self::mix_hash(&mut hash, self.get_scale_factor().to_bits() as u64);
84        for cmd in self.get_commands().iter() {
85            match cmd {
86                DrawCommand::Clear(c) => {
87                    Self::mix_hash(&mut hash, 1);
88                    Self::mix_hash(&mut hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
89                }
90                DrawCommand::FillRoundedRect {
91                    rect,
92                    color,
93                    border,
94                    ..
95                } => {
96                    Self::mix_hash(&mut hash, 2);
97                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
98                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
99                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
100                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
101                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
102                    Self::mix_hash(&mut hash, border.get_width().to_bits() as u64);
103                }
104                DrawCommand::LinearGradientRect { rect, gradient, .. } => {
105                    Self::mix_hash(&mut hash, 3);
106                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
107                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
108                    Self::mix_hash(
109                        &mut hash,
110                        u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
111                    );
112                }
113                DrawCommand::BoxShadow { rect, shadow, .. } => {
114                    Self::mix_hash(&mut hash, 4);
115                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
116                    Self::mix_hash(&mut hash, shadow.get_blur_radius().to_bits() as u64);
117                }
118                DrawCommand::TextRun { rect, text, style } => {
119                    Self::mix_hash(&mut hash, 5);
120                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
121                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
122                    Self::mix_hash(&mut hash, text.len() as u64);
123                    for byte in text.as_bytes().iter().take(16).copied() {
124                        Self::mix_hash(&mut hash, byte as u64);
125                    }
126                    Self::mix_hash(
127                        &mut hash,
128                        u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
129                    );
130                }
131                DrawCommand::TextCaret {
132                    text_rect,
133                    text,
134                    color,
135                    ..
136                } => {
137                    Self::mix_hash(&mut hash, 13);
138                    Self::mix_hash(&mut hash, text_rect.get_x().to_bits() as u64);
139                    Self::mix_hash(&mut hash, text_rect.get_y().to_bits() as u64);
140                    Self::mix_hash(&mut hash, text.len() as u64);
141                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
142                }
143                DrawCommand::Image { rect, buffer, .. } => {
144                    Self::mix_hash(&mut hash, 6);
145                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
146                    Self::mix_hash(&mut hash, buffer.get_width() as u64);
147                    Self::mix_hash(&mut hash, buffer.get_height() as u64);
148                }
149                DrawCommand::Line {
150                    from,
151                    to,
152                    color,
153                    width,
154                } => {
155                    Self::mix_hash(&mut hash, 7);
156                    Self::mix_hash(&mut hash, from.get_x().to_bits() as u64);
157                    Self::mix_hash(&mut hash, to.get_y().to_bits() as u64);
158                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
159                    Self::mix_hash(&mut hash, width.to_bits() as u64);
160                }
161                DrawCommand::Circle {
162                    center,
163                    radius,
164                    color,
165                } => {
166                    Self::mix_hash(&mut hash, 8);
167                    Self::mix_hash(&mut hash, center.get_x().to_bits() as u64);
168                    Self::mix_hash(&mut hash, center.get_y().to_bits() as u64);
169                    Self::mix_hash(&mut hash, radius.to_bits() as u64);
170                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
171                }
172                DrawCommand::Triangle { p0, p1, p2, color } => {
173                    Self::mix_hash(&mut hash, 9);
174                    Self::mix_hash(&mut hash, p0.get_x().to_bits() as u64);
175                    Self::mix_hash(&mut hash, p1.get_y().to_bits() as u64);
176                    Self::mix_hash(&mut hash, p2.get_x().to_bits() as u64);
177                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
178                }
179                DrawCommand::SpriteRegion {
180                    rect,
181                    src_rect,
182                    tint,
183                    ..
184                } => {
185                    Self::mix_hash(&mut hash, 10);
186                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
187                    Self::mix_hash(&mut hash, src_rect.get_x().to_bits() as u64);
188                    Self::mix_hash(&mut hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
189                }
190                DrawCommand::PushClip(r) => {
191                    Self::mix_hash(&mut hash, 11);
192                    Self::mix_hash(&mut hash, r.get_x().to_bits() as u64);
193                    Self::mix_hash(&mut hash, r.get_y().to_bits() as u64);
194                }
195                DrawCommand::PushRoundedClip { rect, radius } => {
196                    Self::mix_hash(&mut hash, 14);
197                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
198                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
199                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
200                }
201                DrawCommand::PopClip => {
202                    Self::mix_hash(&mut hash, 12);
203                }
204            }
205        }
206        hash
207    }
208
209    /// Computes a full collision-resistant 64-bit FNV-1a digest over the base-scene slice `commands[..portal_split_index]` for lossless portal backdrop caching.
210    ///
211    /// # Arguments
212    ///
213    /// - `&Self` - Display list reference.
214    ///
215    /// # Returns
216    ///
217    /// - `u64` - Complete base-scene digest (guaranteed non-zero when commands are present).
218    #[must_use]
219    pub fn base_layer_hash(&self) -> u64 {
220        let split: usize = self.get_portal_split_index().min(self.get_commands().len());
221        let mut hash: u64 = FNV1A_OFFSET_BASIS;
222        Self::mix_hash(&mut hash, split as u64);
223        Self::mix_hash(&mut hash, self.get_viewport().get_width().to_bits() as u64);
224        Self::mix_hash(&mut hash, self.get_viewport().get_height().to_bits() as u64);
225        Self::mix_hash(&mut hash, self.get_scale_factor().to_bits() as u64);
226        for cmd in self.get_commands()[..split].iter() {
227            match cmd {
228                DrawCommand::Clear(c) => {
229                    Self::mix_hash(&mut hash, 1);
230                    Self::mix_hash(&mut hash, u32::from_le_bytes(c.to_rgba_bytes()) as u64);
231                }
232                DrawCommand::FillRoundedRect {
233                    rect,
234                    color,
235                    radius,
236                    border,
237                } => {
238                    Self::mix_hash(&mut hash, 2);
239                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
240                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
241                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
242                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
243                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
244                    Self::mix_hash(&mut hash, radius.get_top_left().to_bits() as u64);
245                    Self::mix_hash(&mut hash, radius.get_top_right().to_bits() as u64);
246                    Self::mix_hash(&mut hash, radius.get_bottom_right().to_bits() as u64);
247                    Self::mix_hash(&mut hash, radius.get_bottom_left().to_bits() as u64);
248                    Self::mix_hash(&mut hash, border.get_width().to_bits() as u64);
249                    Self::mix_hash(
250                        &mut hash,
251                        u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64,
252                    );
253                }
254                DrawCommand::LinearGradientRect {
255                    rect,
256                    gradient,
257                    radius,
258                } => {
259                    Self::mix_hash(&mut hash, 3);
260                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
261                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
262                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
263                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
264                    Self::mix_hash(&mut hash, gradient.get_angle_deg().to_bits() as u64);
265                    Self::mix_hash(
266                        &mut hash,
267                        u32::from_le_bytes(gradient.get_start_color().to_rgba_bytes()) as u64,
268                    );
269                    Self::mix_hash(
270                        &mut hash,
271                        u32::from_le_bytes(gradient.get_end_color().to_rgba_bytes()) as u64,
272                    );
273                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
274                }
275                DrawCommand::BoxShadow {
276                    rect,
277                    radius,
278                    shadow,
279                } => {
280                    Self::mix_hash(&mut hash, 4);
281                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
282                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
283                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
284                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
285                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
286                    Self::mix_hash(&mut hash, shadow.get_offset_x().to_bits() as u64);
287                    Self::mix_hash(&mut hash, shadow.get_offset_y().to_bits() as u64);
288                    Self::mix_hash(&mut hash, shadow.get_blur_radius().to_bits() as u64);
289                    Self::mix_hash(&mut hash, shadow.get_spread_radius().to_bits() as u64);
290                    Self::mix_hash(
291                        &mut hash,
292                        u32::from_le_bytes(shadow.get_color().to_rgba_bytes()) as u64,
293                    );
294                }
295                DrawCommand::TextRun { rect, text, style } => {
296                    Self::mix_hash(&mut hash, 5);
297                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
298                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
299                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
300                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
301                    Self::mix_hash(&mut hash, style.get_font_size().to_bits() as u64);
302                    Self::mix_hash(&mut hash, style.get_family() as u64);
303                    Self::mix_hash(&mut hash, style.get_weight() as u64);
304                    Self::mix_hash(&mut hash, u64::from(style.get_italic()));
305                    Self::mix_hash(&mut hash, style.get_align() as u64);
306                    Self::mix_hash(
307                        &mut hash,
308                        u32::from_le_bytes(style.get_color().to_rgba_bytes()) as u64,
309                    );
310                    Self::mix_hash(&mut hash, text.len() as u64);
311                    for byte in text.as_bytes().iter().copied() {
312                        Self::mix_hash(&mut hash, byte as u64);
313                    }
314                }
315                DrawCommand::TextCaret {
316                    text_rect,
317                    content_rect,
318                    text,
319                    style,
320                    caret_height,
321                    color,
322                    multiline,
323                } => {
324                    Self::mix_hash(&mut hash, 13);
325                    Self::mix_hash(&mut hash, text_rect.get_x().to_bits() as u64);
326                    Self::mix_hash(&mut hash, text_rect.get_y().to_bits() as u64);
327                    Self::mix_hash(&mut hash, content_rect.get_width().to_bits() as u64);
328                    Self::mix_hash(&mut hash, caret_height.to_bits() as u64);
329                    Self::mix_hash(&mut hash, style.get_font_size().to_bits() as u64);
330                    Self::mix_hash(&mut hash, u64::from(*multiline));
331                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
332                    Self::mix_hash(&mut hash, text.len() as u64);
333                    for byte in text.as_bytes().iter().copied() {
334                        Self::mix_hash(&mut hash, byte as u64);
335                    }
336                }
337                DrawCommand::Image {
338                    rect,
339                    buffer,
340                    radius,
341                } => {
342                    Self::mix_hash(&mut hash, 6);
343                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
344                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
345                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
346                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
347                    Self::mix_hash(&mut hash, buffer.get_width() as u64);
348                    Self::mix_hash(&mut hash, buffer.get_height() as u64);
349                    Self::mix_hash(&mut hash, buffer.get_pixels().as_ptr() as usize as u64);
350                    Self::mix_hash(&mut hash, radius.max_radius().to_bits() as u64);
351                }
352                DrawCommand::Line {
353                    from,
354                    to,
355                    color,
356                    width,
357                } => {
358                    Self::mix_hash(&mut hash, 7);
359                    Self::mix_hash(&mut hash, from.get_x().to_bits() as u64);
360                    Self::mix_hash(&mut hash, from.get_y().to_bits() as u64);
361                    Self::mix_hash(&mut hash, to.get_x().to_bits() as u64);
362                    Self::mix_hash(&mut hash, to.get_y().to_bits() as u64);
363                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
364                    Self::mix_hash(&mut hash, width.to_bits() as u64);
365                }
366                DrawCommand::Circle {
367                    center,
368                    radius,
369                    color,
370                } => {
371                    Self::mix_hash(&mut hash, 8);
372                    Self::mix_hash(&mut hash, center.get_x().to_bits() as u64);
373                    Self::mix_hash(&mut hash, center.get_y().to_bits() as u64);
374                    Self::mix_hash(&mut hash, radius.to_bits() as u64);
375                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
376                }
377                DrawCommand::Triangle { p0, p1, p2, color } => {
378                    Self::mix_hash(&mut hash, 9);
379                    Self::mix_hash(&mut hash, p0.get_x().to_bits() as u64);
380                    Self::mix_hash(&mut hash, p0.get_y().to_bits() as u64);
381                    Self::mix_hash(&mut hash, p1.get_x().to_bits() as u64);
382                    Self::mix_hash(&mut hash, p1.get_y().to_bits() as u64);
383                    Self::mix_hash(&mut hash, p2.get_x().to_bits() as u64);
384                    Self::mix_hash(&mut hash, p2.get_y().to_bits() as u64);
385                    Self::mix_hash(&mut hash, u32::from_le_bytes(color.to_rgba_bytes()) as u64);
386                }
387                DrawCommand::SpriteRegion {
388                    rect,
389                    buffer,
390                    src_rect,
391                    tint,
392                } => {
393                    Self::mix_hash(&mut hash, 10);
394                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
395                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
396                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
397                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
398                    Self::mix_hash(&mut hash, buffer.get_pixels().as_ptr() as usize as u64);
399                    Self::mix_hash(&mut hash, src_rect.get_x().to_bits() as u64);
400                    Self::mix_hash(&mut hash, src_rect.get_y().to_bits() as u64);
401                    Self::mix_hash(&mut hash, u32::from_le_bytes(tint.to_rgba_bytes()) as u64);
402                }
403                DrawCommand::PushClip(r) => {
404                    Self::mix_hash(&mut hash, 11);
405                    Self::mix_hash(&mut hash, r.get_x().to_bits() as u64);
406                    Self::mix_hash(&mut hash, r.get_y().to_bits() as u64);
407                    Self::mix_hash(&mut hash, r.get_width().to_bits() as u64);
408                    Self::mix_hash(&mut hash, r.get_height().to_bits() as u64);
409                }
410                DrawCommand::PushRoundedClip { rect, radius } => {
411                    Self::mix_hash(&mut hash, 14);
412                    Self::mix_hash(&mut hash, rect.get_x().to_bits() as u64);
413                    Self::mix_hash(&mut hash, rect.get_y().to_bits() as u64);
414                    Self::mix_hash(&mut hash, rect.get_width().to_bits() as u64);
415                    Self::mix_hash(&mut hash, rect.get_height().to_bits() as u64);
416                    Self::mix_hash(&mut hash, radius.get_top_left().to_bits() as u64);
417                    Self::mix_hash(&mut hash, radius.get_top_right().to_bits() as u64);
418                    Self::mix_hash(&mut hash, radius.get_bottom_right().to_bits() as u64);
419                    Self::mix_hash(&mut hash, radius.get_bottom_left().to_bits() as u64);
420                }
421                DrawCommand::PopClip => {
422                    Self::mix_hash(&mut hash, 12);
423                }
424            }
425        }
426        if hash == 0 { 1 } else { hash }
427    }
428}
429
430/// Telemetry and invalidation helpers for `PaintFragmentCache`.
431impl PaintFragmentCache {
432    /// Clears cached whole-list signature and all retained subtree fragments.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Mutable fragment cache reference.
437    pub fn clear(&mut self) {
438        let Self {
439            has_last_scene,
440            last_has_canvas,
441            slots,
442            ..
443        } = self;
444        *has_last_scene = false;
445        *last_has_canvas = false;
446        for slot in slots.iter_mut() {
447            *slot = None;
448        }
449    }
450
451    /// Returns cumulative retention telemetry `(whole_list_hits, fragment_hits, fragment_misses, fragment_evictions)`.
452    ///
453    /// # Arguments
454    ///
455    /// - `&Self` - Fragment cache reference.
456    ///
457    /// # Returns
458    ///
459    /// - `(u64, u64, u64, u64)` - Tuple of whole-list hits, fragment hits, misses, and evictions.
460    #[must_use]
461    pub fn stats(&self) -> (u64, u64, u64, u64) {
462        (
463            self.get_whole_list_hits(),
464            self.get_fragment_hits(),
465            self.get_fragment_misses(),
466            self.get_fragment_evictions(),
467        )
468    }
469
470    /// Ensures the bounded direct-mapped slot table is allocated with `PAINT_FRAGMENT_CACHE_SLOTS` entries.
471    ///
472    /// # Arguments
473    ///
474    /// - `&Self` - Mutable fragment cache reference.
475    #[inline]
476    fn ensure_slots(&mut self) {
477        let Self { slots, .. } = self;
478        if slots.len() != PAINT_FRAGMENT_CACHE_SLOTS {
479            slots.resize_with(PAINT_FRAGMENT_CACHE_SLOTS, || None);
480        }
481    }
482}
483
484/// Scene-to-display-list compilation pass.
485impl PaintPass {
486    /// Computes a deterministic 64-bit signature of the active text selection state.
487    ///
488    /// # Arguments
489    ///
490    /// - `&SceneTree` - Retained scene tree.
491    ///
492    /// # Returns
493    ///
494    /// - `u64` - Selection digest (`0` when no text selection is active).
495    #[inline]
496    #[must_use]
497    fn text_selection_sig(tree: &SceneTree) -> u64 {
498        let Some(sel) = tree.text_selection() else {
499            return 0;
500        };
501        if sel.is_empty() {
502            return 0;
503        }
504        let (start, end): (usize, usize) = sel.ordered_range();
505        let nid: NodeId = sel.get_node_id();
506        let mut h: u64 = ((nid.get_index() as u64) << 32) | (nid.get_generation() as u64);
507        h = (h ^ (start as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
508        h = (h ^ (end as u64)).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
509        if h == 0 { 1 } else { h }
510    }
511
512    /// Folds one `u64` word into a running FxHash accumulator.
513    ///
514    /// # Arguments
515    ///
516    /// - `&mut u64` - Running hash accumulator.
517    /// - `u64` - Word to fold.
518    #[inline(always)]
519    fn fx_fold(hash: &mut u64, word: u64) {
520        *hash = (*hash ^ word).wrapping_mul(PAINT_FRAGMENT_FX_MULT);
521    }
522
523    /// Folds a `Rect`'s exact IEEE-754 bit pattern into `hash`.
524    ///
525    /// # Arguments
526    ///
527    /// - `&mut u64` - Running hash accumulator.
528    /// - `Rect` - Rectangle to hash.
529    #[inline(always)]
530    fn fx_fold_rect(hash: &mut u64, rect: Rect) {
531        let lo: u64 = ((rect.get_x().to_bits() as u64) << 32) | (rect.get_y().to_bits() as u64);
532        let hi: u64 =
533            ((rect.get_width().to_bits() as u64) << 32) | (rect.get_height().to_bits() as u64);
534        Self::fx_fold(hash, lo);
535        Self::fx_fold(hash, hi);
536    }
537
538    /// Folds a `PaintStyle`'s visual fields into `hash`.
539    ///
540    /// # Arguments
541    ///
542    /// - `&mut u64` - Running hash accumulator.
543    /// - `&PaintStyle` - Paint style reference.
544    #[inline]
545    fn fx_fold_paint(hash: &mut u64, paint: &PaintStyle) {
546        let bg_bits: u64 = paint
547            .background_color()
548            .map(|c: Color| u32::from_le_bytes(c.to_rgba_bytes()) as u64 | (1_u64 << 32))
549            .unwrap_or(0);
550        Self::fx_fold(hash, bg_bits);
551        if let Some(grad) = paint.background_gradient() {
552            let g0: u64 = u32::from_le_bytes(grad.get_start_color().to_rgba_bytes()) as u64;
553            let g1: u64 = u32::from_le_bytes(grad.get_end_color().to_rgba_bytes()) as u64;
554            Self::fx_fold(hash, (g0 << 32) | g1);
555            Self::fx_fold(hash, grad.get_angle_deg().to_bits() as u64 | (1_u64 << 33));
556        }
557        let border: Border = paint.get_border();
558        let b_word: u64 = ((border.get_width().to_bits() as u64) << 32)
559            | (u32::from_le_bytes(border.get_color().to_rgba_bytes()) as u64);
560        Self::fx_fold(hash, b_word);
561        let r: CornerRadius = paint.get_radius();
562        let r0: u64 =
563            ((r.get_top_left().to_bits() as u64) << 32) | (r.get_top_right().to_bits() as u64);
564        let r1: u64 = ((r.get_bottom_right().to_bits() as u64) << 32)
565            | (r.get_bottom_left().to_bits() as u64);
566        Self::fx_fold(hash, r0);
567        Self::fx_fold(hash, r1);
568        Self::fx_fold(hash, paint.get_opacity().to_bits() as u64);
569        if let Some(sh) = paint.box_shadow() {
570            let s0: u64 =
571                ((sh.get_offset_x().to_bits() as u64) << 32) | (sh.get_offset_y().to_bits() as u64);
572            let s1: u64 = ((sh.get_blur_radius().to_bits() as u64) << 32)
573                | (sh.get_spread_radius().to_bits() as u64);
574            Self::fx_fold(hash, s0);
575            Self::fx_fold(hash, s1);
576            Self::fx_fold(
577                hash,
578                u32::from_le_bytes(sh.get_color().to_rgba_bytes()) as u64 | (1_u64 << 34),
579            );
580        }
581    }
582
583    /// Folds a `TextStyle` and UTF-8 string bytes into `hash`.
584    ///
585    /// # Arguments
586    ///
587    /// - `&mut u64` - Running hash accumulator.
588    /// - `&TextStyle` - Typography style reference.
589    /// - `&str` - Text content slice.
590    #[inline]
591    fn fx_fold_text(hash: &mut u64, text_style: &TextStyle, text: &str) {
592        let m0: u64 = ((text_style.get_font_size().to_bits() as u64) << 32)
593            | (text_style.get_line_height().to_bits() as u64);
594        let m1: u64 = ((text_style.get_letter_spacing().to_bits() as u64) << 32)
595            | (u32::from_le_bytes(text_style.get_color().to_rgba_bytes()) as u64);
596        let flags: u64 = (text_style.get_family() as u64)
597            | ((text_style.get_weight() as u64) << 8)
598            | ((text_style.get_align() as u64) << 16)
599            | ((text_style.get_overflow() as u64) << 24)
600            | (u64::from(text_style.get_italic()) << 32);
601        Self::fx_fold(hash, m0);
602        Self::fx_fold(hash, m1);
603        Self::fx_fold(hash, flags);
604        let bytes: &[u8] = text.as_bytes();
605        Self::fx_fold(hash, bytes.len() as u64);
606        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
607        for chunk in chunks.iter() {
608            Self::fx_fold(hash, u64::from_ne_bytes(*chunk));
609        }
610        if !rem.is_empty() {
611            let mut tail: u64 = 0;
612            for (idx, &b) in rem.iter().enumerate() {
613                tail |= (b as u64) << (idx * 8);
614            }
615            Self::fx_fold(hash, tail);
616        }
617    }
618
619    /// Computes `(geom_hash, style_text_hash)` for an eligible shallow clipped container, or `None` if uncacheable.
620    ///
621    /// # Arguments
622    ///
623    /// - `&SceneTree` - Retained scene tree.
624    /// - `NodeId` - Candidate container node handle.
625    /// - `&SceneNode` - Candidate container node reference.
626    /// - `Option<NodeId>` - Active innermost hover target.
627    /// - `Option<NodeId>` - Active text selection node ID, if non-empty.
628    ///
629    /// # Returns
630    ///
631    /// - `Option<(u64, u64)>` - Tuple `(geom_hash, style_text_hash)` when the subtree is pure and cache-eligible.
632    #[inline]
633    #[must_use]
634    fn fingerprint_shallow_container(
635        tree: &SceneTree,
636        node_id: NodeId,
637        node: &SceneNode,
638        active_hover_target: Option<NodeId>,
639        selection_node: Option<NodeId>,
640    ) -> Option<(u64, u64)> {
641        let children: &[NodeId] = node.get_children().as_slice();
642        if children.is_empty() || children.len() > PAINT_FRAGMENT_MAX_CHILDREN {
643            return None;
644        }
645        let style: &Style = node.style_ref();
646        let transform: Transform2D = style.paint.get_transform();
647        let scroll: Point = node.layout_box.get_scroll_offset();
648        let mut geom_h: u64 = children.len() as u64;
649        Self::fx_fold_rect(&mut geom_h, node.layout_box.get_bounds());
650        Self::fx_fold(
651            &mut geom_h,
652            ((transform.get_translate_x().to_bits() as u64) << 32)
653                | (transform.get_translate_y().to_bits() as u64),
654        );
655        Self::fx_fold(
656            &mut geom_h,
657            ((transform.get_scale_x().to_bits() as u64) << 32)
658                | (transform.get_scale_y().to_bits() as u64),
659        );
660        Self::fx_fold(
661            &mut geom_h,
662            ((scroll.get_x().to_bits() as u64) << 32) | (scroll.get_y().to_bits() as u64),
663        );
664        let mut style_h: u64 =
665            ((node_id.get_index() as u64) << 32) | (node_id.get_generation() as u64);
666        Self::fx_fold_paint(&mut style_h, &style.paint);
667        for &cid in children.iter() {
668            if active_hover_target == Some(cid) || selection_node == Some(cid) {
669                return None;
670            }
671            let child: &SceneNode = tree.get_node(cid)?;
672            if !child.get_children().is_empty() {
673                return None;
674            }
675            let c_inter: InteractionState = child.get_interaction();
676            let c_active: bool = c_inter.get_hovered() || c_inter.get_pressed();
677            if c_active || c_inter.get_focused() {
678                return None;
679            }
680            let c_style: &Style = child.style_ref();
681            if c_style.layout.get_position() == Position::Fixed {
682                return None;
683            }
684            let c_tag: u64 = match child.get_kind() {
685                NodeKind::View | NodeKind::Fragment => 1,
686                NodeKind::Text(text) => {
687                    Self::fx_fold_text(&mut style_h, &c_style.text, text.as_str());
688                    Self::fx_fold_rect(&mut geom_h, child.layout_box.get_content_bounds());
689                    2
690                }
691                NodeKind::Image(buf) => {
692                    Self::fx_fold(
693                        &mut style_h,
694                        ((buf.get_width() as u64) << 32) | (buf.get_height() as u64),
695                    );
696                    Self::fx_fold(&mut style_h, buf.get_pixels().as_ptr() as usize as u64);
697                    3
698                }
699                NodeKind::Portal | NodeKind::Canvas | NodeKind::Input(_) | NodeKind::ScrollView => {
700                    return None;
701                }
702            };
703            let c_id_bits: u64 = ((cid.get_index() as u64) << 32) | (cid.get_generation() as u64);
704            Self::fx_fold(&mut geom_h, c_id_bits);
705            Self::fx_fold_rect(&mut geom_h, child.layout_box.get_bounds());
706            let ct: Transform2D = c_style.paint.get_transform();
707            Self::fx_fold(
708                &mut geom_h,
709                ((ct.get_translate_x().to_bits() as u64) << 32)
710                    | (ct.get_translate_y().to_bits() as u64),
711            );
712            Self::fx_fold(
713                &mut geom_h,
714                ((ct.get_scale_x().to_bits() as u64) << 32) | (ct.get_scale_y().to_bits() as u64),
715            );
716            let c_lay_bits: u64 = (c_tag << 40)
717                | ((c_style.layout.get_display() as u64) << 32)
718                | ((c_style.layout.get_overflow() as u64) << 24)
719                | ((c_style.layout.get_z_index() as u32) as u64);
720            Self::fx_fold(&mut style_h, c_lay_bits);
721            Self::fx_fold_paint(&mut style_h, &c_style.paint);
722        }
723        Some((geom_h, style_h))
724    }
725
726    /// Shifts one `DrawCommand`'s logical coordinates by `(dx, dy)` for dyadic-scale scroll fragment reuse.
727    ///
728    /// # Arguments
729    ///
730    /// - `&DrawCommand` - Cached draw command.
731    /// - `f32` - Logical X translation delta.
732    /// - `f32` - Logical Y translation delta.
733    ///
734    /// # Returns
735    ///
736    /// - `DrawCommand` - Translated command copy.
737    #[inline]
738    #[must_use]
739    fn translate_command(cmd: &DrawCommand, dx: f32, dy: f32) -> DrawCommand {
740        match cmd {
741            DrawCommand::Clear(c) => DrawCommand::Clear(*c),
742            DrawCommand::FillRoundedRect {
743                rect,
744                color,
745                radius,
746                border,
747            } => DrawCommand::FillRoundedRect {
748                rect: Rect::new(
749                    rect.get_x() + dx,
750                    rect.get_y() + dy,
751                    rect.get_width(),
752                    rect.get_height(),
753                ),
754                color: *color,
755                radius: *radius,
756                border: *border,
757            },
758            DrawCommand::LinearGradientRect {
759                rect,
760                gradient,
761                radius,
762            } => DrawCommand::LinearGradientRect {
763                rect: Rect::new(
764                    rect.get_x() + dx,
765                    rect.get_y() + dy,
766                    rect.get_width(),
767                    rect.get_height(),
768                ),
769                gradient: *gradient,
770                radius: *radius,
771            },
772            DrawCommand::BoxShadow {
773                rect,
774                radius,
775                shadow,
776            } => DrawCommand::BoxShadow {
777                rect: Rect::new(
778                    rect.get_x() + dx,
779                    rect.get_y() + dy,
780                    rect.get_width(),
781                    rect.get_height(),
782                ),
783                radius: *radius,
784                shadow: *shadow,
785            },
786            DrawCommand::TextRun { rect, text, style } => DrawCommand::TextRun {
787                rect: Rect::new(
788                    rect.get_x() + dx,
789                    rect.get_y() + dy,
790                    rect.get_width(),
791                    rect.get_height(),
792                ),
793                text: text.clone(),
794                style: *style,
795            },
796            DrawCommand::TextCaret {
797                text_rect,
798                content_rect,
799                text,
800                style,
801                caret_height,
802                color,
803                multiline,
804            } => DrawCommand::TextCaret {
805                text_rect: Rect::new(
806                    text_rect.get_x() + dx,
807                    text_rect.get_y() + dy,
808                    text_rect.get_width(),
809                    text_rect.get_height(),
810                ),
811                content_rect: Rect::new(
812                    content_rect.get_x() + dx,
813                    content_rect.get_y() + dy,
814                    content_rect.get_width(),
815                    content_rect.get_height(),
816                ),
817                text: text.clone(),
818                style: *style,
819                caret_height: *caret_height,
820                color: *color,
821                multiline: *multiline,
822            },
823            DrawCommand::Image {
824                rect,
825                buffer,
826                radius,
827            } => DrawCommand::Image {
828                rect: Rect::new(
829                    rect.get_x() + dx,
830                    rect.get_y() + dy,
831                    rect.get_width(),
832                    rect.get_height(),
833                ),
834                buffer: buffer.clone(),
835                radius: *radius,
836            },
837            DrawCommand::Line {
838                from,
839                to,
840                color,
841                width,
842            } => DrawCommand::Line {
843                from: Point::new(from.get_x() + dx, from.get_y() + dy),
844                to: Point::new(to.get_x() + dx, to.get_y() + dy),
845                color: *color,
846                width: *width,
847            },
848            DrawCommand::Circle {
849                center,
850                radius,
851                color,
852            } => DrawCommand::Circle {
853                center: Point::new(center.get_x() + dx, center.get_y() + dy),
854                radius: *radius,
855                color: *color,
856            },
857            DrawCommand::Triangle { p0, p1, p2, color } => DrawCommand::Triangle {
858                p0: Point::new(p0.get_x() + dx, p0.get_y() + dy),
859                p1: Point::new(p1.get_x() + dx, p1.get_y() + dy),
860                p2: Point::new(p2.get_x() + dx, p2.get_y() + dy),
861                color: *color,
862            },
863            DrawCommand::SpriteRegion {
864                rect,
865                buffer,
866                src_rect,
867                tint,
868            } => DrawCommand::SpriteRegion {
869                rect: Rect::new(
870                    rect.get_x() + dx,
871                    rect.get_y() + dy,
872                    rect.get_width(),
873                    rect.get_height(),
874                ),
875                buffer: buffer.clone(),
876                src_rect: *src_rect,
877                tint: *tint,
878            },
879            DrawCommand::PushClip(rect) => DrawCommand::PushClip(Rect::new(
880                rect.get_x() + dx,
881                rect.get_y() + dy,
882                rect.get_width(),
883                rect.get_height(),
884            )),
885            DrawCommand::PushRoundedClip { rect, radius } => DrawCommand::PushRoundedClip {
886                rect: Rect::new(
887                    rect.get_x() + dx,
888                    rect.get_y() + dy,
889                    rect.get_width(),
890                    rect.get_height(),
891                ),
892                radius: *radius,
893            },
894            DrawCommand::PopClip => DrawCommand::PopClip,
895        }
896    }
897
898    /// Compiles `tree` into `display_list`, culling offscreen nodes and honoring z-index stacking.
899    ///
900    /// # Arguments
901    ///
902    /// - `&SceneTree` - Laid-out scene tree.
903    /// - `Size` - Logical viewport size.
904    /// - `f32` - DPI scale factor.
905    /// - `Color` - Surface clear background color.
906    /// - `&mut DisplayList` - Output reusable display list.
907    pub fn build(
908        tree: &SceneTree,
909        viewport: Size,
910        scale_factor: f32,
911        clear_color: Color,
912        display_list: &mut DisplayList,
913    ) {
914        let mut saw_canvas: bool = false;
915        Self::build_inner(
916            tree,
917            viewport,
918            scale_factor,
919            clear_color,
920            display_list,
921            None,
922            &mut saw_canvas,
923        );
924    }
925
926    /// Packs an optional `NodeId` into a single `u64` (`u64::MAX` when `None`).
927    ///
928    /// # Arguments
929    ///
930    /// - `Option<NodeId>` - Optional node handle.
931    ///
932    /// # Returns
933    ///
934    /// - `u64` - Packed `(index << 32) | generation` or `u64::MAX`.
935    #[inline(always)]
936    #[must_use]
937    fn pack_opt_node_id(node: Option<NodeId>) -> u64 {
938        match node {
939            Some(id) => ((id.get_index() as u64) << 32) | (id.get_generation() as u64),
940            None => u64::MAX,
941        }
942    }
943
944    /// Compiles `tree` into `display_list` with cross-frame whole-list retention and subtree `DrawCommand` fragment caching.
945    ///
946    /// # Arguments
947    ///
948    /// - `&SceneTree` - Laid-out scene tree.
949    /// - `Size` - Logical viewport size.
950    /// - `f32` - DPI scale factor.
951    /// - `Color` - Surface clear background color.
952    /// - `bool` - Whether layout recomputed any node geometry on this frame.
953    /// - `&mut DisplayList` - Output reusable display list.
954    /// - `&mut PaintFragmentCache` - Persistent cross-frame fragment cache.
955    pub fn build_retained(
956        tree: &SceneTree,
957        viewport: Size,
958        scale_factor: f32,
959        clear_color: Color,
960        layout_changed: bool,
961        display_list: &mut DisplayList,
962        cache: &mut PaintFragmentCache,
963    ) {
964        let clamped_scale: f32 = scale_factor.max(0.5);
965        let focus: FocusManager = tree.get_focus();
966        let sig: PaintSceneSignature = PaintSceneSignature {
967            tree_ptr: (tree as *const SceneTree) as usize,
968            tree_revision: tree.get_revision(),
969            viewport_w_bits: viewport.get_width().to_bits(),
970            viewport_h_bits: viewport.get_height().to_bits(),
971            scale_bits: clamped_scale.to_bits(),
972            clear_rgba: u32::from_le_bytes(clear_color.to_rgba_bytes()),
973            focused_packed: Self::pack_opt_node_id(focus.focused_node()),
974            hovered_packed: Self::pack_opt_node_id(focus.hovered_node()),
975            pressed_packed: Self::pack_opt_node_id(focus.pressed_node()),
976            caret_visible: tree.get_caret_visible(),
977            text_sel_sig: Self::text_selection_sig(tree),
978        };
979        if !layout_changed
980            && !cache.last_has_canvas
981            && !display_list.is_empty()
982            && cache.has_last_scene
983            && cache.last_scene_sig == sig
984        {
985            cache.whole_list_hits = cache.whole_list_hits.wrapping_add(1);
986            return;
987        }
988        cache.ensure_slots();
989        let mut saw_canvas: bool = false;
990        Self::build_inner(
991            tree,
992            viewport,
993            clamped_scale,
994            clear_color,
995            display_list,
996            Some(cache),
997            &mut saw_canvas,
998        );
999        cache.last_has_canvas = saw_canvas;
1000        cache.has_last_scene = true;
1001        cache.last_scene_sig = sig;
1002    }
1003
1004    /// Shared internal scene-to-display-list builder supporting optional retained fragment caching.
1005    ///
1006    /// # Arguments
1007    ///
1008    /// - `&SceneTree` - Laid-out scene tree.
1009    /// - `Size` - Logical viewport size.
1010    /// - `f32` - DPI scale factor.
1011    /// - `Color` - Surface clear background color.
1012    /// - `&mut DisplayList` - Output reusable display list.
1013    /// - `Option<&mut PaintFragmentCache>` - Optional cross-frame fragment cache.
1014    /// - `&mut bool` - Output flag set when any `NodeKind::Canvas` is visited.
1015    fn build_inner(
1016        tree: &SceneTree,
1017        viewport: Size,
1018        scale_factor: f32,
1019        clear_color: Color,
1020        display_list: &mut DisplayList,
1021        mut fragments: Option<&mut PaintFragmentCache>,
1022        saw_canvas: &mut bool,
1023    ) {
1024        display_list.reset(viewport, scale_factor);
1025        display_list.push(DrawCommand::Clear(clear_color));
1026        let viewport_rect: Rect = Rect::new(0.0, 0.0, viewport.get_width(), viewport.get_height());
1027        let active_hover_target: Option<NodeId> = Self::resolve_active_hover_target(tree);
1028        let mut portals: Vec<(i32, usize, NodeId)> = take(&mut display_list.portals_scratch);
1029        let mut z_sort: Vec<(i32, usize, NodeId)> = take(&mut display_list.z_sort_scratch);
1030        portals.clear();
1031        z_sort.clear();
1032        {
1033            let mut scratch: PaintScratch<'_> = PaintScratch {
1034                portals: Some(&mut portals),
1035                z_sort: &mut z_sort,
1036                fragments: fragments.as_deref_mut(),
1037                saw_canvas,
1038            };
1039            Self::emit_node(
1040                tree,
1041                tree.get_root(),
1042                (Point::new(0.0, 0.0), 1.0),
1043                viewport_rect,
1044                active_hover_target,
1045                &mut scratch,
1046                display_list,
1047            );
1048        }
1049        display_list.set_portal_split_index(display_list.len());
1050        if portals.len() > 1 {
1051            portals.sort_by(|a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
1052                a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
1053            });
1054        }
1055        {
1056            let mut portal_scratch: PaintScratch<'_> = PaintScratch {
1057                portals: None,
1058                z_sort: &mut z_sort,
1059                fragments,
1060                saw_canvas,
1061            };
1062            for &(_, _, portal_id) in portals.iter() {
1063                Self::emit_node(
1064                    tree,
1065                    portal_id,
1066                    (Point::new(0.0, 0.0), 1.0),
1067                    viewport_rect,
1068                    active_hover_target,
1069                    &mut portal_scratch,
1070                    display_list,
1071                );
1072            }
1073        }
1074        portals.clear();
1075        z_sort.clear();
1076        display_list.portals_scratch = portals;
1077        display_list.z_sort_scratch = z_sort;
1078    }
1079
1080    /// Resolves the single innermost interactive non-scrim node along the active hover chain so nested controls never stack duplicate hover fills.
1081    ///
1082    /// # Arguments
1083    ///
1084    /// - `&SceneTree` - Retained scene tree.
1085    ///
1086    /// # Returns
1087    ///
1088    /// - `Option<NodeId>` - Innermost interactive node eligible for hover tinting.
1089    #[must_use]
1090    fn resolve_active_hover_target(tree: &SceneTree) -> Option<NodeId> {
1091        let mut cursor: Option<NodeId> = tree.get_focus().hovered_node();
1092        while let Some(id) = cursor {
1093            let Some(node) = tree.get_node(id) else {
1094                break;
1095            };
1096            let style: &Style = node.style_ref();
1097            let paint: &PaintStyle = &style.paint;
1098            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
1099                || style.layout.get_position() == Position::Fixed;
1100            let is_transparent_canvas: bool =
1101                matches!(node.get_kind(), NodeKind::Canvas) && paint.background_color().is_none();
1102            if !is_scrim && !is_transparent_canvas {
1103                let is_interactive: bool = paint.get_cursor() == CursorIcon::Pointer
1104                    || node
1105                        .get_handlers()
1106                        .handler_for(&UiEventKind::Click(Point::default()))
1107                        .is_some();
1108                if is_interactive {
1109                    return Some(id);
1110                }
1111            }
1112            cursor = node.parent_id();
1113        }
1114        None
1115    }
1116
1117    /// Computes subtle shadcn-aligned hover/pressed color tinting for interactive controls.
1118    ///
1119    /// # Arguments
1120    ///
1121    /// - `Option<Color>` - Base background color, if any.
1122    /// - `bool` - Whether the pointer hovers the control.
1123    /// - `bool` - Whether the pointer actively presses the control.
1124    ///
1125    /// # Returns
1126    ///
1127    /// - `Option<Color>` - Tinted background color.
1128    fn interactive_tint(base: Option<Color>, hovered: bool, pressed: bool) -> Option<Color> {
1129        if !hovered && !pressed {
1130            return base;
1131        }
1132        let delta: i32 = if pressed { 24 } else { 14 };
1133        match base {
1134            Some(c) if c.get_a() > 0 => {
1135                let luma: u32 =
1136                    (c.get_r() as u32) * 299 + (c.get_g() as u32) * 587 + (c.get_b() as u32) * 114;
1137                if luma < 120_000 {
1138                    let lift: i32 = if pressed { 30 } else { 20 };
1139                    Some(Color::new(
1140                        (c.get_r() as i32 + lift).clamp(0, 255) as u8,
1141                        (c.get_g() as i32 + lift).clamp(0, 255) as u8,
1142                        (c.get_b() as i32 + lift).clamp(0, 255) as u8,
1143                        c.get_a(),
1144                    ))
1145                } else {
1146                    Some(Color::new(
1147                        (c.get_r() as i32 - delta).clamp(0, 255) as u8,
1148                        (c.get_g() as i32 - delta).clamp(0, 255) as u8,
1149                        (c.get_b() as i32 - delta).clamp(0, 255) as u8,
1150                        c.get_a(),
1151                    ))
1152                }
1153            }
1154            _ => Some(Color::rgba(113, 113, 122, if pressed { 42 } else { 26 })),
1155        }
1156    }
1157
1158    /// Recursively emits commands for `node_id` and its z-sorted children with hierarchical transform and physical-pixel lockstep.
1159    ///
1160    /// # Arguments
1161    ///
1162    /// - `&SceneTree` - Scene tree reference.
1163    /// - `NodeId` - Node to paint.
1164    /// - `(Point, f32)` - Accumulated ancestor physical pixel displacement `(tx_phys - scroll_phys)` and opacity.
1165    /// - `Rect` - Active cull clip rectangle.
1166    /// - `Option<NodeId>` - Innermost hovered interactive node eligible for automatic hover tinting.
1167    /// - `&mut PaintScratch<'_>` - Reusable portal queue and nested z-sort scratch buffers.
1168    /// - `&mut DisplayList` - Output command list.
1169    fn emit_node(
1170        tree: &SceneTree,
1171        node_id: NodeId,
1172        offset_and_opacity: (Point, f32),
1173        cull_rect: Rect,
1174        active_hover_target: Option<NodeId>,
1175        scratch: &mut PaintScratch<'_>,
1176        display_list: &mut DisplayList,
1177    ) {
1178        let (offset_phys, parent_opacity): (Point, f32) = offset_and_opacity;
1179        let Some(node) = tree.get_node(node_id) else {
1180            return;
1181        };
1182        let style: &Style = node.style_ref();
1183        let layout: &LayoutStyle = &style.layout;
1184        if layout.get_display() == Display::None {
1185            return;
1186        }
1187        if let Some(portal_queue) = scratch.portals.as_deref_mut()
1188            && (matches!(node.get_kind(), NodeKind::Portal)
1189                || layout.get_position() == Position::Fixed)
1190        {
1191            portal_queue.push((layout.get_z_index(), portal_queue.len(), node_id));
1192            return;
1193        }
1194        let interaction: InteractionState = node.get_interaction();
1195        let hovered: bool = interaction.get_hovered();
1196        let pressed: bool = interaction.get_pressed();
1197        let hover_visual: bool = hovered && active_hover_target == Some(node_id);
1198        let mut paint_owned: Option<PaintStyle> = if hovered { node.hover_paint() } else { None };
1199        if (hover_visual || pressed)
1200            && paint_owned.is_none()
1201            && (hovered || node.hover_paint().is_none())
1202        {
1203            let base_paint: &PaintStyle = &style.paint;
1204            let is_scrim: bool = matches!(node.get_kind(), NodeKind::Portal)
1205                || layout.get_position() == Position::Fixed;
1206            let is_transparent_canvas: bool = matches!(node.get_kind(), NodeKind::Canvas)
1207                && base_paint.background_color().is_none();
1208            if !is_scrim && !is_transparent_canvas {
1209                let is_interactive: bool = base_paint.get_cursor() == CursorIcon::Pointer
1210                    || node
1211                        .get_handlers()
1212                        .handler_for(&UiEventKind::Click(Point::default()))
1213                        .is_some();
1214                if is_interactive {
1215                    let mut tinted: PaintStyle = *base_paint;
1216                    tinted.set_background(Self::interactive_tint(
1217                        tinted.background_color(),
1218                        hover_visual,
1219                        pressed,
1220                    ));
1221                    paint_owned = Some(tinted);
1222                }
1223            }
1224        }
1225        let paint: &PaintStyle = paint_owned.as_ref().unwrap_or(&style.paint);
1226        let opacity: f32 = (parent_opacity * paint.get_opacity()).clamp(0.0, 1.0);
1227        if opacity <= 0.0 {
1228            return;
1229        }
1230        let scale: f32 = display_list.get_scale_factor().max(0.5);
1231        let inv_scale: f32 = 1.0 / scale;
1232        let raw_bounds: Rect = node.layout_box.get_bounds();
1233        let transform: Transform2D = paint.get_transform();
1234        let tx_phys: f32 = (transform.get_translate_x() * scale).round();
1235        let ty_phys: f32 = (transform.get_translate_y() * scale).round();
1236        let total_off_x: f32 = offset_phys.get_x() + tx_phys;
1237        let total_off_y: f32 = offset_phys.get_y() + ty_phys;
1238        let raw_x0: f32 = (raw_bounds.get_x() * scale).round();
1239        let raw_y0: f32 = (raw_bounds.get_y() * scale).round();
1240        let raw_x1: f32 = (raw_bounds.right() * scale).round();
1241        let raw_y1: f32 = (raw_bounds.bottom() * scale).round();
1242        let static_w_phys: f32 = (raw_x1 - raw_x0).max(0.0);
1243        let static_h_phys: f32 = (raw_y1 - raw_y0).max(0.0);
1244        let scaled_w_phys: f32 = (static_w_phys * transform.get_scale_x()).round().max(0.0);
1245        let scaled_h_phys: f32 = (static_h_phys * transform.get_scale_y()).round().max(0.0);
1246        let scale_dx_phys: f32 = ((static_w_phys - scaled_w_phys) * 0.5).round();
1247        let scale_dy_phys: f32 = ((static_h_phys - scaled_h_phys) * 0.5).round();
1248        let bounds: Rect = Rect::new(
1249            (raw_x0 + total_off_x + scale_dx_phys) * inv_scale,
1250            (raw_y0 + total_off_y + scale_dy_phys) * inv_scale,
1251            scaled_w_phys * inv_scale,
1252            scaled_h_phys * inv_scale,
1253        );
1254        let clipped: bool = matches!(layout.get_overflow(), Overflow::Hidden | Overflow::Scroll);
1255        let next_cull: Rect = if clipped {
1256            match cull_rect.intersect(bounds) {
1257                Some(r) => r,
1258                None => return,
1259            }
1260        } else {
1261            cull_rect
1262        };
1263        let halo: f32 = if paint.box_shadow().is_some() {
1264            36.0
1265        } else if paint.focus_ring_border().is_some() {
1266            8.0
1267        } else {
1268            2.0
1269        };
1270        let self_vis_rect: Rect = Rect::new(
1271            bounds.get_x() - halo,
1272            bounds.get_y() - halo,
1273            bounds.get_width() + halo * 2.0,
1274            bounds.get_height() + halo * 2.0,
1275        );
1276        let self_visible: bool = bounds.get_width() > 0.0
1277            && bounds.get_height() > 0.0
1278            && self_vis_rect.intersect(cull_rect).is_some();
1279        let mut frag_capture: Option<(usize, usize, u64, u64)> = None;
1280        if self_visible
1281            && scratch.fragments.is_some()
1282            && scratch.portals.is_some()
1283            && matches!(node.get_kind(), NodeKind::View)
1284            && layout.get_overflow() == Overflow::Hidden
1285            && !hovered
1286            && !pressed
1287            && !interaction.get_focused()
1288            && active_hover_target != Some(node_id)
1289        {
1290            let vis_x_in: bool = self_vis_rect.get_x() >= cull_rect.get_x()
1291                && self_vis_rect.right() <= cull_rect.right();
1292            let vis_y_in: bool = self_vis_rect.get_y() >= cull_rect.get_y()
1293                && self_vis_rect.bottom() <= cull_rect.bottom();
1294            if vis_x_in && vis_y_in {
1295                let sel_node: Option<NodeId> = tree
1296                    .text_selection()
1297                    .filter(|s: &SelectionState| !s.is_empty())
1298                    .map(|s: SelectionState| s.get_node_id());
1299                if let Some((geom_hash, style_text_hash)) = Self::fingerprint_shallow_container(
1300                    tree,
1301                    node_id,
1302                    node,
1303                    active_hover_target,
1304                    sel_node,
1305                ) {
1306                    let slot_idx: usize =
1307                        (node_id.get_index() as usize) & (PAINT_FRAGMENT_CACHE_SLOTS - 1);
1308                    let scale_bits: u32 = scale.to_bits();
1309                    let opacity_bits: u32 = parent_opacity.to_bits();
1310                    let dyadic_12: bool = scale == 1.0 || scale == 2.0;
1311                    let dyadic_scale: bool = dyadic_12 || scale == 4.0;
1312                    if let Some(cache) = scratch.fragments.as_deref_mut()
1313                        && let Some(cached) = cache.slots.get(slot_idx).and_then(Option::as_ref)
1314                        && cached.node_id == node_id
1315                        && cached.scale_bits == scale_bits
1316                        && cached.opacity_bits == opacity_bits
1317                        && cached.geom_hash == geom_hash
1318                        && cached.style_text_hash == style_text_hash
1319                    {
1320                        if cached.offset_phys == offset_phys {
1321                            display_list
1322                                .get_mut_commands()
1323                                .extend_from_slice(cached.commands.as_slice());
1324                            cache.fragment_hits = cache.fragment_hits.wrapping_add(1);
1325                            return;
1326                        }
1327                        if dyadic_scale {
1328                            let dx: f32 =
1329                                (offset_phys.get_x() - cached.offset_phys.get_x()) * inv_scale;
1330                            let dy: f32 =
1331                                (offset_phys.get_y() - cached.offset_phys.get_y()) * inv_scale;
1332                            let dst: &mut Vec<DrawCommand> = display_list.get_mut_commands();
1333                            dst.reserve(cached.commands.len());
1334                            for cmd in cached.commands.iter() {
1335                                dst.push(Self::translate_command(cmd, dx, dy));
1336                            }
1337                            cache.fragment_hits = cache.fragment_hits.wrapping_add(1);
1338                            return;
1339                        }
1340                    }
1341                    frag_capture = Some((display_list.len(), slot_idx, geom_hash, style_text_hash));
1342                }
1343            }
1344        }
1345        if self_visible {
1346            if let Some(mut shadow) = paint.box_shadow() {
1347                shadow.set_color(shadow.get_color().multiply_alpha(opacity));
1348                display_list.push(DrawCommand::BoxShadow {
1349                    rect: bounds,
1350                    radius: paint.get_radius(),
1351                    shadow,
1352                });
1353            }
1354            if let Some(mut gradient) = paint.background_gradient() {
1355                gradient.set_start_color(gradient.get_start_color().multiply_alpha(opacity));
1356                gradient.set_end_color(gradient.get_end_color().multiply_alpha(opacity));
1357                display_list.push(DrawCommand::LinearGradientRect {
1358                    rect: bounds,
1359                    gradient,
1360                    radius: paint.get_radius(),
1361                });
1362            } else if let Some(bg) = paint.background_color() {
1363                let mut border: Border = paint.get_border();
1364                border.set_color(border.get_color().multiply_alpha(opacity));
1365                display_list.push(DrawCommand::FillRoundedRect {
1366                    rect: bounds,
1367                    color: bg.multiply_alpha(opacity),
1368                    radius: paint.get_radius(),
1369                    border,
1370                });
1371            } else if paint.get_border().get_width() > 0.0 {
1372                let mut border: Border = paint.get_border();
1373                border.set_color(border.get_color().multiply_alpha(opacity));
1374                display_list.push(DrawCommand::FillRoundedRect {
1375                    rect: bounds,
1376                    color: COLOR_TRANSPARENT,
1377                    radius: paint.get_radius(),
1378                    border,
1379                });
1380            }
1381            if interaction.get_focused()
1382                && let Some(mut ring) = paint.focus_ring_border()
1383            {
1384                ring.set_color(ring.get_color().multiply_alpha(opacity));
1385                let ring_w: f32 = ring.get_width();
1386                let ring_rect: Rect = Rect::new(
1387                    bounds.get_x() - ring_w,
1388                    bounds.get_y() - ring_w,
1389                    bounds.get_width() + ring_w * 2.0,
1390                    bounds.get_height() + ring_w * 2.0,
1391                );
1392                display_list.push(DrawCommand::FillRoundedRect {
1393                    rect: ring_rect,
1394                    color: COLOR_TRANSPARENT,
1395                    radius: CornerRadius::all(paint.get_radius().max_radius() + ring_w),
1396                    border: ring,
1397                });
1398            }
1399            match node.get_kind() {
1400                NodeKind::Text(text) => {
1401                    let mut text_style: TextStyle = style.text;
1402                    text_style.set_color(text_style.get_color().multiply_alpha(opacity));
1403                    let content_b: Rect = node.layout_box.get_content_bounds();
1404                    let cx0: f32 = (content_b.get_x() * scale).round();
1405                    let cy0: f32 = (content_b.get_y() * scale).round();
1406                    let shifted_content: Rect = Rect::new(
1407                        (cx0 + total_off_x) * inv_scale,
1408                        (cy0 + total_off_y) * inv_scale,
1409                        content_b.get_width(),
1410                        content_b.get_height(),
1411                    );
1412                    if let Some(sel) = tree.text_selection()
1413                        && sel.get_node_id() == node_id
1414                        && !sel.is_empty()
1415                    {
1416                        let sel_color: Color = tree
1417                            .effective_selection_color(node_id)
1418                            .multiply_alpha(opacity);
1419                        let sel_rects: Vec<Rect> = compute_text_selection_rects(
1420                            text.as_str(),
1421                            text_style,
1422                            shifted_content,
1423                            sel.ordered_range(),
1424                        );
1425                        for sel_rect in sel_rects.into_iter() {
1426                            display_list.push(DrawCommand::FillRoundedRect {
1427                                rect: sel_rect,
1428                                color: sel_color,
1429                                radius: CornerRadius::all(2.0),
1430                                border: Border::default(),
1431                            });
1432                        }
1433                    }
1434                    display_list.push(DrawCommand::TextRun {
1435                        rect: shifted_content,
1436                        text: text.clone(),
1437                        style: text_style,
1438                    });
1439                }
1440                NodeKind::Input(input_state) => {
1441                    let mut text_style: TextStyle = style.text;
1442                    let is_empty_value: bool = input_state.get_value().is_empty();
1443                    let is_focused: bool = interaction.get_focused();
1444                    let rendered_text: String = if is_empty_value {
1445                        text_style.set_color(text_style.get_color().multiply_alpha(opacity * 0.55));
1446                        input_state.get_placeholder().clone()
1447                    } else if input_state.get_password() {
1448                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
1449                        "*".repeat(input_state.get_value().chars().count())
1450                    } else {
1451                        text_style.set_color(text_style.get_color().multiply_alpha(opacity));
1452                        input_state.get_value().clone()
1453                    };
1454                    let content_b: Rect = node.layout_box.get_content_bounds();
1455                    let cx0: f32 = (content_b.get_x() * scale).round();
1456                    let cy0: f32 = (content_b.get_y() * scale).round();
1457                    let shifted_content: Rect = Rect::new(
1458                        (cx0 + total_off_x) * inv_scale,
1459                        (cy0 + total_off_y) * inv_scale,
1460                        content_b.get_width(),
1461                        content_b.get_height(),
1462                    );
1463                    let line_h: f32 =
1464                        (text_style.get_font_size() * text_style.get_line_height()).max(1.0);
1465                    let text_rect: Rect = if input_state.get_multiline() {
1466                        shifted_content
1467                    } else {
1468                        text_style.set_overflow(TextOverflow::Clip);
1469                        let v_off_phys: f32 =
1470                            (((shifted_content.get_height() - line_h) * 0.5).max(0.0) * scale)
1471                                .round();
1472                        let text_y: f32 = (cy0 + total_off_y + v_off_phys) * inv_scale;
1473                        Rect::new(
1474                            shifted_content.get_x(),
1475                            text_y,
1476                            shifted_content.get_width(),
1477                            line_h,
1478                        )
1479                    };
1480                    let run_rect: Rect =
1481                        if is_empty_value && is_focused && !rendered_text.is_empty() {
1482                            let clearance_phys: f32 =
1483                                (PLACEHOLDER_FOCUSED_CARET_CLEARANCE_PX * scale).round();
1484                            let clearance_logical: f32 = clearance_phys * inv_scale;
1485                            Rect::new(
1486                                text_rect.get_x() + clearance_logical,
1487                                text_rect.get_y(),
1488                                (text_rect.get_width() - clearance_logical).max(0.0),
1489                                text_rect.get_height(),
1490                            )
1491                        } else {
1492                            text_rect
1493                        };
1494                    let show_caret: bool = is_focused && tree.get_caret_visible();
1495                    let caret_text: String = if show_caret && !is_empty_value {
1496                        rendered_text.clone()
1497                    } else {
1498                        String::new()
1499                    };
1500                    display_list.push(DrawCommand::PushClip(shifted_content));
1501                    display_list.push(DrawCommand::TextRun {
1502                        rect: run_rect,
1503                        text: rendered_text,
1504                        style: text_style,
1505                    });
1506                    if show_caret {
1507                        let caret_h: f32 = (text_style.get_font_size() * 1.15)
1508                            .min(shifted_content.get_height().max(12.0));
1509                        display_list.push(DrawCommand::TextCaret {
1510                            text_rect,
1511                            content_rect: shifted_content,
1512                            text: caret_text,
1513                            style: text_style,
1514                            caret_height: caret_h,
1515                            color: style.text.get_color().multiply_alpha(opacity),
1516                            multiline: input_state.get_multiline(),
1517                        });
1518                    }
1519                    display_list.push(DrawCommand::PopClip);
1520                }
1521                NodeKind::Image(buffer) => {
1522                    display_list.push(DrawCommand::Image {
1523                        rect: bounds,
1524                        buffer: buffer.clone(),
1525                        radius: paint.get_radius(),
1526                    });
1527                }
1528                NodeKind::Canvas => {
1529                    *scratch.saw_canvas = true;
1530                    if let Some(callback) = node.canvas_callback()
1531                        && let Ok(mut func) = callback.try_borrow_mut()
1532                    {
1533                        let canvas_bw: f32 = paint.get_border().get_width();
1534                        let canvas_clip_rect: Rect = if canvas_bw > 0.0 {
1535                            Rect::new(
1536                                bounds.get_x() + canvas_bw,
1537                                bounds.get_y() + canvas_bw,
1538                                (bounds.get_width() - canvas_bw * 2.0).max(0.0),
1539                                (bounds.get_height() - canvas_bw * 2.0).max(0.0),
1540                            )
1541                        } else {
1542                            bounds
1543                        };
1544                        let canvas_max_r: f32 = (bounds.get_width() * 0.5)
1545                            .min(bounds.get_height() * 0.5)
1546                            .max(0.0);
1547                        let canvas_raw_r: CornerRadius = paint.get_radius();
1548                        let canvas_inner_r: CornerRadius = CornerRadius::new(
1549                            (canvas_raw_r.get_top_left().min(canvas_max_r) - canvas_bw).max(0.0),
1550                            (canvas_raw_r.get_top_right().min(canvas_max_r) - canvas_bw).max(0.0),
1551                            (canvas_raw_r.get_bottom_right().min(canvas_max_r) - canvas_bw)
1552                                .max(0.0),
1553                            (canvas_raw_r.get_bottom_left().min(canvas_max_r) - canvas_bw).max(0.0),
1554                        );
1555                        if canvas_inner_r.max_radius() > 0.25 {
1556                            display_list.push(DrawCommand::PushRoundedClip {
1557                                rect: canvas_clip_rect,
1558                                radius: canvas_inner_r,
1559                            });
1560                        } else {
1561                            display_list.push(DrawCommand::PushClip(canvas_clip_rect));
1562                        }
1563                        func(bounds, display_list);
1564                        display_list.push(DrawCommand::PopClip);
1565                    }
1566                }
1567                NodeKind::View | NodeKind::ScrollView | NodeKind::Portal | NodeKind::Fragment => {}
1568            }
1569        }
1570        if clipped {
1571            let bw: f32 = paint.get_border().get_width();
1572            let clip_rect: Rect = if bw > 0.0 {
1573                Rect::new(
1574                    bounds.get_x() + bw,
1575                    bounds.get_y() + bw,
1576                    (bounds.get_width() - bw * 2.0).max(0.0),
1577                    (bounds.get_height() - bw * 2.0).max(0.0),
1578                )
1579            } else {
1580                bounds
1581            };
1582            let max_r: f32 = (bounds.get_width() * 0.5)
1583                .min(bounds.get_height() * 0.5)
1584                .max(0.0);
1585            let raw_r: CornerRadius = paint.get_radius();
1586            let inner_r: CornerRadius = CornerRadius::new(
1587                (raw_r.get_top_left().min(max_r) - bw).max(0.0),
1588                (raw_r.get_top_right().min(max_r) - bw).max(0.0),
1589                (raw_r.get_bottom_right().min(max_r) - bw).max(0.0),
1590                (raw_r.get_bottom_left().min(max_r) - bw).max(0.0),
1591            );
1592            if inner_r.max_radius() > 0.25 {
1593                display_list.push(DrawCommand::PushRoundedClip {
1594                    rect: clip_rect,
1595                    radius: inner_r,
1596                });
1597            } else {
1598                display_list.push(DrawCommand::PushClip(clip_rect));
1599            }
1600        }
1601        let raw_node_scroll: Point = node.layout_box.get_scroll_offset();
1602        let scroll_x_phys: f32 = (raw_node_scroll.get_x() * scale).round();
1603        let scroll_y_phys: f32 = (raw_node_scroll.get_y() * scale).round();
1604        let child_offset_phys: Point =
1605            Point::new(total_off_x - scroll_x_phys, total_off_y - scroll_y_phys);
1606        let raw_children: &[NodeId] = node.get_children().as_slice();
1607        let needs_z_sort: bool = raw_children.len() > 1
1608            && raw_children.iter().copied().any(|cid: NodeId| {
1609                tree.get_node(cid)
1610                    .map(|c: &SceneNode| c.style_ref().layout.get_z_index() != 0)
1611                    .unwrap_or(false)
1612            });
1613        if !needs_z_sort {
1614            for child_id in raw_children.iter().copied() {
1615                Self::emit_node(
1616                    tree,
1617                    child_id,
1618                    (child_offset_phys, opacity),
1619                    next_cull,
1620                    active_hover_target,
1621                    scratch,
1622                    display_list,
1623                );
1624            }
1625        } else {
1626            let sort_start: usize = scratch.z_sort.len();
1627            for (idx, cid) in raw_children.iter().copied().enumerate() {
1628                if let Some(c) = tree.get_node(cid) {
1629                    scratch
1630                        .z_sort
1631                        .push((c.style_ref().layout.get_z_index(), idx, cid));
1632                }
1633            }
1634            let sort_end: usize = scratch.z_sort.len();
1635            scratch.z_sort[sort_start..sort_end].sort_by(
1636                |a: &(i32, usize, NodeId), b: &(i32, usize, NodeId)| {
1637                    a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1))
1638                },
1639            );
1640            for slot_idx in sort_start..sort_end {
1641                let child_id: NodeId = scratch.z_sort[slot_idx].2;
1642                Self::emit_node(
1643                    tree,
1644                    child_id,
1645                    (child_offset_phys, opacity),
1646                    next_cull,
1647                    active_hover_target,
1648                    scratch,
1649                    display_list,
1650                );
1651            }
1652            scratch.z_sort.truncate(sort_start);
1653        }
1654        let vp: Size = display_list.get_viewport();
1655        let show_scrollbar: bool = vp.get_width().min(vp.get_height()) >= 540.0;
1656        if show_scrollbar && layout.get_overflow() == Overflow::Scroll && bounds.get_height() > 24.0
1657        {
1658            let lbox: &LayoutBox = &node.layout_box;
1659            let border_w: f32 = paint.get_border().get_width();
1660            let inner_x: f32 = bounds.get_x() + border_w;
1661            let inner_y: f32 = bounds.get_y() + border_w;
1662            let inner_w: f32 = (bounds.get_width() - border_w * 2.0).max(1.0);
1663            let inner_h: f32 = (bounds.get_height() - border_w * 2.0).max(1.0);
1664            let view_w: f32 = lbox.get_content_bounds().get_width().max(1.0);
1665            let view_h: f32 = lbox.get_content_bounds().get_height().max(1.0);
1666            let (scroll_y, total_h): (f32, f32) = match node.virtual_scroll_metrics() {
1667                Some((vy, vh)) => (vy, vh),
1668                None => (
1669                    lbox.get_scroll_offset().get_y(),
1670                    lbox.get_content_size().get_height(),
1671                ),
1672            };
1673            let scroll_x: f32 = lbox.get_scroll_offset().get_x();
1674            let total_w: f32 = lbox.get_content_size().get_width();
1675            let max_scroll_y: f32 = (total_h - view_h).max(0.0);
1676            let max_scroll_x: f32 = (total_w - view_w).max(0.0);
1677            let has_v_bar: bool = max_scroll_y > 1.0;
1678            let has_h_bar: bool = max_scroll_x > 1.0 && bounds.get_width() > 24.0;
1679            let corner_inset: f32 = if has_v_bar && has_h_bar { 8.0 } else { 0.0 };
1680            if has_v_bar {
1681                let track_margin: f32 = 3.0;
1682                let track_w: f32 = if hovered { 6.0 } else { 4.0 };
1683                let track_x: f32 = (inner_x + inner_w - track_w - 2.0).max(inner_x);
1684                let track_y: f32 = inner_y + track_margin;
1685                let track_h: f32 = (inner_h - track_margin * 2.0 - corner_inset).max(16.0);
1686                let ratio: f32 = (view_h / total_h.max(view_h)).clamp(0.0, 1.0);
1687                let min_thumb_h: f32 = 20.0_f32.min(track_h);
1688                let thumb_h: f32 = (track_h * ratio).clamp(min_thumb_h, track_h);
1689                let scroll_frac: f32 = (scroll_y / max_scroll_y).clamp(0.0, 1.0);
1690                let thumb_y: f32 = track_y + (track_h - thumb_h) * scroll_frac;
1691                let track_x_snapped: f32 = (track_x * scale).round() * inv_scale;
1692                let track_y_snapped: f32 = (track_y * scale).round() * inv_scale;
1693                let track_w_snapped: f32 = (track_w * scale).round().max(1.0) * inv_scale;
1694                let track_h_snapped: f32 = (track_h * scale).round().max(1.0) * inv_scale;
1695                let thumb_y_snapped: f32 = (thumb_y * scale).round() * inv_scale;
1696                let thumb_h_snapped: f32 = (thumb_h * scale).round().max(1.0) * inv_scale;
1697                if hovered {
1698                    display_list.push(DrawCommand::FillRoundedRect {
1699                        rect: Rect::new(
1700                            track_x_snapped,
1701                            track_y_snapped,
1702                            track_w_snapped,
1703                            track_h_snapped,
1704                        ),
1705                        color: Color::rgba(113, 113, 122, 24).multiply_alpha(opacity),
1706                        radius: CornerRadius::all(3.0),
1707                        border: Border::default(),
1708                    });
1709                }
1710                let thumb_alpha: u8 = if hovered { 180 } else { 112 };
1711                display_list.push(DrawCommand::FillRoundedRect {
1712                    rect: Rect::new(
1713                        track_x_snapped,
1714                        thumb_y_snapped,
1715                        track_w_snapped,
1716                        thumb_h_snapped,
1717                    ),
1718                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
1719                    radius: CornerRadius::all(track_w * 0.5),
1720                    border: Border::default(),
1721                });
1722            }
1723            if has_h_bar {
1724                let track_margin: f32 = 3.0;
1725                let track_h: f32 = if hovered { 6.0 } else { 4.0 };
1726                let track_y: f32 = (inner_y + inner_h - track_h - 2.0).max(inner_y);
1727                let track_x: f32 = inner_x + track_margin;
1728                let track_w: f32 = (inner_w - track_margin * 2.0 - corner_inset).max(16.0);
1729                let ratio: f32 = (view_w / total_w.max(view_w)).clamp(0.0, 1.0);
1730                let min_thumb_w: f32 = 20.0_f32.min(track_w);
1731                let thumb_w: f32 = (track_w * ratio).clamp(min_thumb_w, track_w);
1732                let scroll_frac: f32 = (scroll_x / max_scroll_x).clamp(0.0, 1.0);
1733                let thumb_x: f32 = track_x + (track_w - thumb_w) * scroll_frac;
1734                let track_x_snapped: f32 = (track_x * scale).round() * inv_scale;
1735                let track_y_snapped: f32 = (track_y * scale).round() * inv_scale;
1736                let track_w_snapped: f32 = (track_w * scale).round().max(1.0) * inv_scale;
1737                let track_h_snapped: f32 = (track_h * scale).round().max(1.0) * inv_scale;
1738                let thumb_x_snapped: f32 = (thumb_x * scale).round() * inv_scale;
1739                let thumb_w_snapped: f32 = (thumb_w * scale).round().max(1.0) * inv_scale;
1740                if hovered {
1741                    display_list.push(DrawCommand::FillRoundedRect {
1742                        rect: Rect::new(
1743                            track_x_snapped,
1744                            track_y_snapped,
1745                            track_w_snapped,
1746                            track_h_snapped,
1747                        ),
1748                        color: Color::rgba(113, 113, 122, 24).multiply_alpha(opacity),
1749                        radius: CornerRadius::all(3.0),
1750                        border: Border::default(),
1751                    });
1752                }
1753                let thumb_alpha: u8 = if hovered { 180 } else { 112 };
1754                display_list.push(DrawCommand::FillRoundedRect {
1755                    rect: Rect::new(
1756                        thumb_x_snapped,
1757                        track_y_snapped,
1758                        thumb_w_snapped,
1759                        track_h_snapped,
1760                    ),
1761                    color: Color::rgba(113, 113, 122, thumb_alpha).multiply_alpha(opacity),
1762                    radius: CornerRadius::all(track_h * 0.5),
1763                    border: Border::default(),
1764                });
1765            }
1766        }
1767        if clipped {
1768            display_list.push(DrawCommand::PopClip);
1769        }
1770        if let Some((cmd_start, slot_idx, geom_hash, style_text_hash)) = frag_capture
1771            && let Some(cache) = scratch.fragments.as_deref_mut()
1772            && let Some(slot_ref) = cache.slots.get_mut(slot_idx)
1773        {
1774            let cmd_slice: &[DrawCommand] = &display_list.get_commands()[cmd_start..];
1775            cache.fragment_misses = cache.fragment_misses.wrapping_add(1);
1776            if let Some(existing) = slot_ref.as_mut() {
1777                if existing.node_id != node_id {
1778                    cache.fragment_evictions = cache.fragment_evictions.wrapping_add(1);
1779                }
1780                existing.node_id = node_id;
1781                existing.scale_bits = scale.to_bits();
1782                existing.opacity_bits = parent_opacity.to_bits();
1783                existing.offset_phys = offset_phys;
1784                existing.geom_hash = geom_hash;
1785                existing.style_text_hash = style_text_hash;
1786                existing.commands.clear();
1787                existing.commands.extend_from_slice(cmd_slice);
1788            } else {
1789                *slot_ref = Some(RetainedPaintFragment {
1790                    node_id,
1791                    scale_bits: scale.to_bits(),
1792                    opacity_bits: parent_opacity.to_bits(),
1793                    offset_phys,
1794                    geom_hash,
1795                    style_text_hash,
1796                    commands: cmd_slice.to_vec(),
1797                });
1798            }
1799        }
1800    }
1801}