euv-core 0.48.2

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
use super::*;

/// Single disjoint horizontal framebuffer strip dispatched to a persistent rasterization worker thread.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Data, Debug, Default)]
pub(crate) struct BandTaskSlice {
    /// Raw mutable pixel buffer base address encoded as `usize` for `Send` transfer.
    #[get(type(copy))]
    pub(crate) pixels_ptr: usize,
    /// Byte length of the disjoint horizontal pixel strip.
    #[get(type(copy))]
    pub(crate) pixels_len: usize,
    /// Full framebuffer physical width in pixels.
    #[get(type(copy))]
    pub(crate) width: u32,
    /// Inclusive top physical Y row of this strip.
    #[get(type(copy))]
    pub(crate) y_start: u32,
    /// Number of physical rows inside this strip.
    #[get(type(copy))]
    pub(crate) height: u32,
    /// Optional raw source pointer for parallel base-scene backdrop restore (`0` when unused).
    #[get(type(copy))]
    pub(crate) base_src_ptr: usize,
    /// Horizontal byte offset within each row where backdrop restore starts.
    #[get(type(copy))]
    pub(crate) restore_x0_bytes: usize,
    /// Horizontal byte length restored per row (`width * 4` for full-width contiguous restore).
    #[get(type(copy))]
    pub(crate) restore_row_bytes: usize,
}

/// Optional base-scene backdrop restore and fused full-viewport scrim LUT specification for band dispatch.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct BandRestoreSpec<'a> {
    /// Cached full-framebuffer RGBA8 base scene pixels, if restoring backdrop.
    pub(crate) base_pixels: Option<&'a [u8]>,
    /// Inclusive physical start X column to restore on each row.
    pub(crate) x0: u32,
    /// Exclusive physical end X column to restore on each row.
    pub(crate) x1: u32,
    /// Optional prebuilt 256-entry linear-light scrim LUT fused into backdrop restore.
    pub(crate) scrim_luts: Option<&'a [[u8; 256]; 4]>,
}

/// Read-only auxiliary frame slices passed to band rasterizers (glyphs, caret rects, rounded clips, and cached corner masks).
#[derive(Clone, Copy)]
pub(crate) struct BandAuxSlices<'a> {
    /// Pre-positioned glyph instances for the active frame.
    pub(crate) positioned_glyphs: &'a [PositionedGlyph],
    /// Pre-measured caret bounding rectangles for the active frame.
    pub(crate) caret_rects: &'a [Rect],
    /// Active rounded clip masks for the frame.
    pub(crate) rounded_clips: &'a [RoundedClipMask],
    /// Cached quadrant corner anti-aliasing masks.
    pub(crate) corner_masks: &'a [CachedCornerMask],
}

/// Precomputed 1D horizontal edge pixel sample reused across every vertical interior scanline of a rounded rectangle.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct EdgeBlendSample {
    /// Physical X pixel coordinate inside the target scanline.
    pub(crate) x: u32,
    /// Direct RGBA8 bytes written verbatim when `is_opaque` is true.
    pub(crate) rgba: [u8; 4],
    /// Pre-multiplied linear red channel `SRGB_TO_LIN_LUT[r] * alpha`.
    pub(crate) sr_a: f32,
    /// Pre-multiplied linear green channel `SRGB_TO_LIN_LUT[g] * alpha`.
    pub(crate) sg_a: f32,
    /// Pre-multiplied linear blue channel `SRGB_TO_LIN_LUT[b] * alpha`.
    pub(crate) sb_a: f32,
    /// Complement opacity `1.0 - alpha`.
    pub(crate) inv_a: f32,
    /// Quantized source alpha in `0..=255` for destination alpha update.
    pub(crate) sa_u32: u32,
    /// True when the sample overwrites destination pixels without blending.
    pub(crate) is_opaque: bool,
}

/// Precomputed per-row exterior, anti-aliased, and dirty horizontal spans inside a cached rounded-clip corner mask.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct CornerMaskRowSpan {
    /// Inclusive start X (in mask-local `0..dim`) of the contiguous exterior (`cov == 0`) run.
    pub(crate) ext_start: u16,
    /// Exclusive end X of the contiguous exterior (`cov == 0`) run.
    pub(crate) ext_end: u16,
    /// Inclusive start X of the anti-aliased (`1..=15`) transition run.
    pub(crate) aa_start: u16,
    /// Exclusive end X of the anti-aliased (`1..=15`) transition run.
    pub(crate) aa_end: u16,
    /// Inclusive start X of all non-interior (`cov < 16`) pixels requiring save/restore.
    pub(crate) dirty_start: u16,
    /// Exclusive end X of all non-interior (`cov < 16`) pixels requiring save/restore.
    pub(crate) dirty_end: u16,
}

/// Cached exact 4x4 RGSS coverage grid (`0..=16` hit counts) for one rounded-clip quadrant `(radius, quadrant, aa)`.
#[derive(Clone, Debug)]
pub(crate) struct CachedCornerMask {
    /// Bit representation of the clamped physical corner radius `r.to_bits()`.
    pub(crate) radius_bits: u32,
    /// Quadrant index (`0 = TL`, `1 = TR`, `2 = BR`, `3 = BL`).
    pub(crate) quadrant: u8,
    /// Whether 4x4 RGSS anti-aliasing is enabled (`false` for `AntialiasingMode::None`).
    pub(crate) aa_enabled: bool,
    /// Side length of the square coverage grid in physical pixels (`ceil(r + 1)`).
    pub(crate) dim: u16,
    /// Row-major exact coverage hit counts in `0..=16` (`0` = outside, `16` = fully inside).
    pub(crate) cov: Vec<u8>,
    /// Per-row horizontal exterior/AA/dirty span bounds (`len == dim`).
    pub(crate) row_spans: Vec<CornerMaskRowSpan>,
}

/// Persistent cache of precomputed rounded-clip corner coverage masks reused across cards and frames.
#[derive(Clone, Debug, Default)]
pub(crate) struct CornerMaskCache {
    /// Contiguous arena of cached quadrant coverage masks indexed by `u32` ID.
    pub(crate) entries: Vec<CachedCornerMask>,
}

/// Single saved horizontal row segment belonging to one cached rounded-clip corner.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct SavedCornerRow {
    /// Global physical Y row coordinate.
    pub(crate) y: u32,
    /// Inclusive global physical start X of the saved segment.
    pub(crate) sx0: u32,
    /// Exclusive global physical end X of the saved segment.
    pub(crate) sx1: u32,
    /// Byte offset into `BandCornerScratch::saved_bytes` where this row's RGBA bytes start.
    pub(crate) byte_off: usize,
    /// Index into `CornerMaskCache::entries` for this quadrant.
    pub(crate) mask_id: u32,
    /// Mask-local X origin in global physical coordinates.
    pub(crate) origin_x: i32,
    /// Mask-local Y origin in global physical coordinates.
    pub(crate) origin_y: i32,
}

/// Per-thread reusable scratch buffers for rounded-clip corner save and restore in `render_band`.
#[derive(Debug, Default)]
pub(crate) struct BandCornerScratch {
    /// Bulk RGBA8 byte buffer storing pre-command corner pixels via `extend_from_slice`.
    pub(crate) saved_bytes: Vec<u8>,
    /// Saved row descriptors for the single-mask cached fast path.
    pub(crate) saved_rows: Vec<SavedCornerRow>,
    /// Clipped corner box bounds for the multi-mask / fallback path.
    pub(crate) corner_boxes: Vec<(u32, u32, u32, u32)>,
}

/// Active rounded-rectangle clip mask in physical pixels applied during software band rasterization.
#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
pub(crate) struct RoundedClipMask {
    /// Physical clip rectangle bounds.
    #[get(type(copy))]
    pub(crate) rect: Rect,
    /// Physical corner radii.
    #[get(type(copy))]
    pub(crate) radius: CornerRadius,
    /// Cached quadrant mask IDs `[tl, tr, br, bl]` into `CornerMaskCache::entries` (`u32::MAX` = uncached/inactive).
    #[get(type(copy))]
    pub(crate) corner_mask_ids: [u32; 4],
}

/// Pre-positioned glyph instance resolved once per frame on the main thread for zero-lookup band blitting.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub(crate) struct PositionedGlyph {
    /// Direct arena slot index into `GlyphAtlas::entries`.
    pub(crate) glyph_idx: u32,
    /// Rounded physical X coordinate of the glyph's left edge.
    pub(crate) x: i32,
    /// Rounded physical Y coordinate of the glyph's top edge.
    pub(crate) y: i32,
    /// Cached glyph bitmap width in physical pixels for fast band culling.
    pub(crate) width: u16,
    /// Cached glyph bitmap height in physical pixels for fast band culling.
    pub(crate) height: u16,
}

/// Cache-line-isolated 128-byte aligned atomic counter preventing Apple Silicon (128B) and x86 (64B) false sharing.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug, Default)]
pub(crate) struct AlignedAtomicUsize {
    /// Underlying atomic word padded to its own 128-byte cache line.
    pub(crate) value: AtomicUsize,
}

/// Shared read-only descriptor for separable sliding-window `BackdropBlur` passes executed serially or in parallel.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct BlurPassDesc {
    /// Raw mutable framebuffer RGBA8 pixel base pointer (`*mut u8 as usize`).
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fb_ptr: usize,
    /// Total framebuffer RGBA8 byte length.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) fb_len: usize,
    /// Full framebuffer physical width in pixels.
    pub(crate) fb_w: u32,
    /// Raw mutable persistent horizontal-pass scratch base pointer (`*mut [u8; 4] as usize`).
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) horiz_ptr: usize,
    /// Element count (`sw * sh`) of the active slice inside `blur_horiz_scratch`.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) horiz_len: usize,
    /// Inclusive halo source start X in physical pixels.
    pub(crate) sx0: u32,
    /// Inclusive halo source start Y in physical pixels.
    pub(crate) sy0: u32,
    /// Halo source width in physical pixels (`sx1 - sx0`).
    pub(crate) sw: u32,
    /// Halo source height in physical pixels (`sy1 - sy0`).
    pub(crate) sh: u32,
    /// Inclusive destination blur start X in physical pixels.
    pub(crate) x0: u32,
    /// Inclusive destination blur start Y in physical pixels.
    pub(crate) y0: u32,
    /// Exclusive destination blur end X in physical pixels.
    pub(crate) x1: u32,
    /// Exclusive destination blur end Y in physical pixels.
    pub(crate) y1: u32,
    /// Clamped integer box-filter half-radius (`1..=24`).
    pub(crate) rad: u32,
    /// Exact fixed-point Q24 reciprocal `ceil(2^24 / (2*rad + 1))` matching integer division bit-for-bit.
    pub(crate) inv_win_q24: u64,
    /// Physical destination rectangle for rounded-corner clipping.
    pub(crate) rect: Rect,
    /// Physical corner radii for rounded-corner clipping.
    pub(crate) radius: CornerRadius,
    /// True when `radius.max_radius() > 0.25`.
    pub(crate) has_radius: bool,
    /// Number of rows processed per work-stealing strip in parallel blur passes.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) strip_rows: u32,
    /// Total number of parallel blur strips for the current pass.
    #[cfg(not(target_arch = "wasm32"))]
    pub(crate) strip_count: usize,
}

/// Shared 128-byte aligned frame dispatch state consumed lock-free by persistent band workers during a single job epoch.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug)]
pub(crate) struct BandJob {
    /// Active job execution mode (`RasterBands`, `BlurHoriz`, or `BlurVert`).
    pub(crate) kind: BandJobKind,
    /// Base address of the caller-owned `BandTaskSlice` slice.
    pub(crate) tasks_ptr: usize,
    /// Number of horizontal strips in the frame job.
    pub(crate) tasks_len: usize,
    /// Base address of `DisplayList::commands`.
    pub(crate) commands_ptr: usize,
    /// Length of `DisplayList::commands`.
    pub(crate) commands_len: usize,
    /// Base address of the pre-processed `PreppedCommand` slice.
    pub(crate) prepped_ptr: usize,
    /// Length of the pre-processed `PreppedCommand` slice.
    pub(crate) prepped_len: usize,
    /// Base address of the per-frame pre-positioned `PositionedGlyph` slice.
    pub(crate) glyphs_ptr: usize,
    /// Length of the per-frame pre-positioned `PositionedGlyph` slice.
    pub(crate) glyphs_len: usize,
    /// Base address of the per-frame pre-computed `TextCaret` rectangle slice.
    pub(crate) caret_rects_ptr: usize,
    /// Length of the per-frame pre-computed `TextCaret` rectangle slice.
    pub(crate) caret_rects_len: usize,
    /// Base address of the per-frame active `RoundedClipMask` slice.
    pub(crate) rounded_clips_ptr: usize,
    /// Length of the per-frame active `RoundedClipMask` slice.
    pub(crate) rounded_clips_len: usize,
    /// Base address of the read-only cached quadrant corner masks slice.
    pub(crate) corner_masks_ptr: usize,
    /// Length of the read-only cached quadrant corner masks slice.
    pub(crate) corner_masks_len: usize,
    /// Base address of the shared read-only `GlyphAtlas`.
    pub(crate) atlas_ptr: usize,
    /// Optional raw pointer to a stack-pinned 4-channel RGBA blend LUT tuple fused into backdrop restore (`0` when unused).
    pub(crate) scrim_luts_ptr: usize,
    /// Active physical DPI scale factor.
    pub(crate) scale: f32,
    /// Active anti-aliasing policy.
    pub(crate) aa: AntialiasingMode,
    /// Descriptor used when `kind` is `BlurHoriz` or `BlurVert`.
    pub(crate) blur_desc: BlurPassDesc,
    /// Cache-line-isolated atomic work-stealing strip cursor shared by the caller and all worker threads.
    pub(crate) next_idx: AlignedAtomicUsize,
    /// Cache-line-isolated atomic count of worker threads that finished observing this epoch.
    pub(crate) workers_done: AlignedAtomicUsize,
    /// Cache-line-isolated atomic accumulated shaded pixel count across all strips.
    pub(crate) total_shaded: AlignedAtomicUsize,
}

/// Per-worker cache-line-isolated wake slot eliminating N-way mutex convoys and false sharing.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug, Default)]
pub(crate) struct BandWorkerSlot {
    /// Per-worker monotonically increasing dispatch epoch counter.
    pub(crate) epoch: AtomicUsize,
    /// Non-zero while this worker thread is parked inside `wake.wait`.
    pub(crate) parked: AtomicUsize,
    /// Private mutex guarding this worker's condvar sleep transition.
    pub(crate) lock: Mutex<()>,
    /// Condition variable waking only this worker on a new epoch or shutdown.
    pub(crate) wake: Condvar,
}

/// Lock-free 128-byte aligned dispatch header and per-worker wake slots shared between the caller and persistent band workers.
#[cfg(not(target_arch = "wasm32"))]
#[repr(align(128))]
#[derive(Debug, Default)]
pub(crate) struct BandPoolShared {
    /// Raw pointer address of the active `BandJob` (`0` while idle).
    pub(crate) active_job: AtomicUsize,
    /// Number of background workers dispatched for the current epoch.
    pub(crate) active_workers: AtomicUsize,
    /// Adaptive hybrid spin limit (`~3072` during active animation/scroll, `0` immediately on idle).
    pub(crate) spin_limit: AtomicUsize,
    /// Non-zero when the worker pool is shutting down during `Drop`.
    pub(crate) shutdown: AtomicUsize,
    /// Cache-line-isolated flag set while the calling thread is parked waiting for workers to finish.
    pub(crate) caller_parked: AlignedAtomicUsize,
    /// Mutex guarding caller parking transitions (bypassed on the spin fast-path).
    pub(crate) caller_lock: Mutex<()>,
    /// Condition variable waking a parked caller once all dispatched workers finish an epoch.
    pub(crate) wake_caller: Condvar,
    /// Contention-free per-worker wake slots indexed by worker ID `0..worker_count`.
    pub(crate) slots: Vec<BandWorkerSlot>,
}

/// Persistent native worker pool eliminating per-frame `pthread_create` overhead on high-refresh mobile and desktop targets.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Debug)]
pub(crate) struct BandWorkerPool {
    /// Number of background worker threads (excluding the calling main thread).
    pub(crate) worker_count: usize,
    /// Non-blocking guard owning reusable horizontal band task slices across frames.
    pub(crate) dispatch_tasks: Mutex<Vec<BandTaskSlice>>,
    /// Shared atomic dispatch state and condition variables.
    pub(crate) shared: Arc<BandPoolShared>,
    /// Background worker join handles drained cleanly on `Drop`.
    pub(crate) handles: Vec<JoinHandle<()>>,
}

/// Preprocessed draw-command metadata computed once on the main thread before parallel band rasterization.
#[derive(Clone, Copy, Data, Debug, Default, PartialEq)]
pub(crate) struct PreppedCommand {
    /// Original index inside `DisplayList::commands`.
    #[get(type(copy))]
    pub(crate) cmd_index: usize,
    /// Active intersected physical clip rectangle for this command.
    #[get(type(copy))]
    pub(crate) active_clip: Rect,
    /// Inclusive top physical Y row affected by this command.
    #[get(type(copy))]
    pub(crate) y0: u32,
    /// Exclusive bottom physical Y row affected by this command.
    #[get(type(copy))]
    pub(crate) y1: u32,
    /// Optional opaque inner vertical-span cutout for a `BoxShadow` followed immediately by an opaque `FillRoundedRect`.
    #[get(type(copy))]
    pub(crate) opaque_cutout_h: Rect,
    /// Optional opaque inner horizontal-span cutout for a `BoxShadow` followed immediately by an opaque `FillRoundedRect`.
    #[get(type(copy))]
    pub(crate) opaque_cutout_v: Rect,
    /// Start index into the per-frame `PositionedGlyph` slice for `TextRun` commands (`0` when unused).
    #[get(type(copy))]
    pub(crate) glyph_run_start: u32,
    /// Count of pre-positioned glyphs for `TextRun` commands (`0` when unused).
    #[get(type(copy))]
    pub(crate) glyph_run_len: u32,
    /// Optional index into the per-frame pre-resolved `TextCaret` rectangle slice (`u32::MAX` when unused).
    #[get(type(copy))]
    pub(crate) caret_rect_idx: u32,
    /// Start index into the per-frame `RoundedClipMask` slice (`0` when unused).
    #[get(type(copy))]
    pub(crate) rounded_clip_start: u32,
    /// Count of active `RoundedClipMask` entries touching this command (`0` on fast path).
    #[get(type(copy))]
    pub(crate) rounded_clip_len: u16,
    /// Relative index jump inside `prepped_scratch` when a `usize::MAX` clip-scope sentinel misses a band.
    #[get(type(copy))]
    pub(crate) skip_delta: u32,
}

/// Single open-addressed slot in `TextLayoutCache` mapping `(key_hash, width_key)` to an arena index.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct TextLayoutSlot {
    /// Deterministic 64-bit FxHash of source text bytes and typography style.
    pub(crate) key_hash: u64,
    /// Quantized wrap width (`(max_w * 10.0).round() as u32`, or `u32::MAX` for unbounded lines).
    pub(crate) width_key: u32,
    /// Arena index into `TextLayoutCache::entries` (`u32::MAX` marks an empty slot).
    pub(crate) entry_idx: u32,
}

/// Zero-clone, SipHash-free open-addressed cache of wrapped `TextLayoutResult` entries with bounded LRU eviction and telemetry.
#[derive(Clone, Debug, Default)]
pub(crate) struct TextLayoutCache {
    /// Power-of-two linear-probing slot table (`entry_idx == u32::MAX` denotes an empty slot).
    pub(crate) slots: Vec<TextLayoutSlot>,
    /// Contiguous arena owning cached `TextLayoutResult` entries read lock-free across band workers.
    pub(crate) entries: Vec<TextLayoutResult>,
    /// Lookup keys `(key_hash, width_key)` aligned 1:1 with `entries` for slot table reconstruction after LRU eviction.
    pub(crate) entry_keys: Vec<(u64, u32)>,
    /// Monotonic access ticks aligned 1:1 with `entries` for bounded LRU eviction.
    pub(crate) entry_last_used: Vec<u64>,
    /// Tracked resident byte footprint per entry aligned 1:1 with `entries`.
    pub(crate) entry_bytes: Vec<usize>,
    /// Current total resident memory in bytes across all cached layouts.
    pub(crate) resident_bytes: usize,
    /// Optional custom memory budget in bytes (`0` selects `TEXT_LAYOUT_CACHE_BUDGET_BYTES`).
    pub(crate) budget_bytes: usize,
    /// Monotonic access clock incremented on every cache lookup.
    pub(crate) lru_clock: u64,
    /// Cumulative count of text layout cache hits.
    pub(crate) cache_hits: u64,
    /// Cumulative count of text layout cache misses.
    pub(crate) cache_misses: u64,
    /// Cumulative count of evicted cold text layouts.
    pub(crate) evictions: u64,
}

/// Single open-addressed slot in `PositionedGlyphRunCache` keyed by `(text_style_hash, width_bits, phys_scale_milli)`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct PositionedGlyphRunSlot {
    /// Deterministic 64-bit FxHash of source text bytes and typography style.
    pub(crate) key_hash: u64,
    /// IEEE-754 bits of the logical text box width.
    pub(crate) width_bits: u32,
    /// Quantized physical scale factor `(scale * 1000.0).round() as u32`.
    pub(crate) phys_scale_milli: u32,
    /// Arena index into `PositionedGlyphRunCache::entries` (`u32::MAX` marks an empty slot).
    pub(crate) entry_idx: u32,
}

/// Cached relative-offset glyph sequence range inside `PositionedGlyphRunCache::glyph_slab`.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct CachedPositionedGlyphRun {
    /// Start index inside `PositionedGlyphRunCache::glyph_slab`.
    pub(crate) glyph_start: u32,
    /// Number of relative `PositionedGlyph` entries owned by this run.
    pub(crate) glyph_len: u32,
    /// True when any glyph had a non-integer relative X offset before rounding (guards negative-origin tie parity).
    pub(crate) has_fractional_x: bool,
    /// Maximum `GlyphAtlas` slot index referenced by this run for O(1) validity checks.
    pub(crate) max_glyph_slot: u32,
}

/// Bounded open-addressed flat-slab cache of `CachedPositionedGlyphRun` entries keyed by `(text_hash, width_bits, phys_scale_milli)`.
#[derive(Clone, Debug, Default)]
pub(crate) struct PositionedGlyphRunCache {
    /// Power-of-two linear-probing slot table (`entry_idx == u32::MAX` marks an empty slot).
    pub(crate) slots: Vec<PositionedGlyphRunSlot>,
    /// Contiguous flat glyph slab eliminating per-entry `Vec<PositionedGlyph>` heap allocations.
    pub(crate) glyph_slab: Vec<PositionedGlyph>,
    /// Contiguous arena of cached relative-positioned glyph run descriptors.
    pub(crate) entries: Vec<CachedPositionedGlyphRun>,
    /// Lookup keys `(key_hash, width_bits, phys_scale_milli)` aligned 1:1 with `entries`.
    pub(crate) entry_keys: Vec<(u64, u32, u32)>,
    /// Monotonic LRU access ticks aligned 1:1 with `entries`.
    pub(crate) entry_last_used: Vec<u64>,
    /// Pre-allocated keep-flag vector reused during zero-allocation LRU compaction.
    pub(crate) evict_keep: Vec<bool>,
    /// Pre-allocated destination slab reused during zero-allocation LRU compaction.
    pub(crate) evict_slab_scratch: Vec<PositionedGlyph>,
    /// Consecutive misses without any cache hit (detects streaming virtual-list text churn).
    pub(crate) miss_streak: u32,
    /// Misses observed during the current frame for streaming-churn decay on static frames.
    pub(crate) frame_misses: u32,
    /// Monotonic access clock incremented on lookups.
    pub(crate) lru_clock: u64,
    /// `GlyphAtlas::evictions` watermark last observed when populating cached slot indices.
    pub(crate) atlas_evictions: u64,
    /// `GlyphAtlas::font_chain_revision` watermark last observed when populating cached slot indices.
    pub(crate) font_chain_revision: u64,
    /// Highest `GlyphAtlas` slot index referenced across all cached runs.
    pub(crate) max_cached_slot: u32,
    /// Cumulative positioned glyph run cache hits (reused without `GlyphAtlas` mutation).
    pub(crate) cache_hits: u64,
    /// Cumulative positioned glyph run cache misses.
    pub(crate) cache_misses: u64,
    /// Cumulative evicted cold positioned glyph runs.
    pub(crate) evictions: u64,
}

/// High-performance CPU tile and analytical-SDF software rasterizer with zero GPU dependencies.
#[derive(Clone, Data, Debug, Default)]
pub struct SoftwareRenderer {
    /// Lazily allocated RGBA8 framebuffer (`None` when GPU direct-draw is active with zero CPU FB bytes).
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) framebuffer: Option<Framebuffer>,
    /// Shared glyph rasterization atlas.
    pub(crate) glyph_atlas: GlyphAtlas,
    /// Native or deterministic font rasterization provider.
    #[set(skip)]
    pub(crate) font_provider: NativeSystemFont,
    /// Deterministic text measurer matching `LayoutEngine` metrics.
    #[get(type(copy))]
    pub(crate) measurer: DeterministicTextMeasurer,
    /// Zero-clone open-addressed cache of wrapped `TextLayoutResult` entries eliminating per-frame cloning and SipHash.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) text_layout_cache: TextLayoutCache,
    /// Relative-offset `PositionedGlyphRun` cache keyed by `(text_hash, width_bits, phys_scale_milli)` for zero-LRU-mutation scroll reuse.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(skip)]
    pub(crate) positioned_glyph_run_cache: PositionedGlyphRunCache,
    /// Persistent scratch buffer for Pass 1 of separable sliding-window `BackdropBlur` (zero steady-state per-frame allocs).
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(skip)]
    pub(crate) blur_horiz_scratch: Vec<[u8; 4]>,
    /// Persistent keep-flag buffer reused by `cull_occluded_prepped_commands` across frames.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cull_keep_scratch: Vec<bool>,
    /// Persistent compacted command buffer reused by `cull_occluded_prepped_commands` across frames.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cull_compacted_scratch: Vec<PreppedCommand>,
    /// Persistent open-sentinel stack reused by `cull_occluded_prepped_commands` across frames.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cull_sentinels_scratch: Vec<(usize, usize)>,
    /// Active physical clip-rectangle stack.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) clip_stack: Vec<Rect>,
    /// Parallel stack of optional rounded-rectangle clip masks aligned 1:1 with `clip_stack`.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) rounded_clip_stack: Vec<Option<RoundedClipMask>>,
    /// Active anti-aliasing policy.
    #[get(type(copy))]
    pub(crate) antialiasing: AntialiasingMode,
    /// Tile edge length in physical pixels for damage tile accounting.
    #[get(type(copy))]
    pub(crate) tile_size: u32,
    /// Cached physical width of the static base-scene snapshot behind active portals.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) base_cache_width: u32,
    /// Cached physical height of the static base-scene snapshot behind active portals.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) base_cache_height: u32,
    /// Full base-layer command hash for the cached static backdrop (`0` when invalid).
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) base_cache_hash: u64,
    /// Base-layer command hash observed on the immediately preceding frame to avoid copying active scroll frames.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) prev_base_hash: u64,
    /// Saved RGBA8 pixels of the static base scene beneath active portals for fast overlay compositing.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) base_cache_pixels: Vec<u8>,
    /// Reusable pre-processed draw command buffer cleared at frame start to avoid per-frame allocations.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) prepped_scratch: Vec<PreppedCommand>,
    /// Reusable active rounded-clip mask buffer cleared at frame start to avoid per-frame allocations.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) rounded_clips_scratch: Vec<RoundedClipMask>,
    /// Reusable flat buffer of pre-positioned glyphs emitted once per frame for zero-lookup band rasterization.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) positioned_glyphs_scratch: Vec<PositionedGlyph>,
    /// Reusable line buffer for single-lookup `Center`/`Right` text alignment positioning.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) line_glyphs_scratch: Vec<(u32, f32, u16, u16)>,
    /// Reusable buffer of pre-computed physical caret rectangles for `DrawCommand::TextCaret`.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) caret_rects_scratch: Vec<Rect>,
    /// Persistent cache of precomputed rounded-clip corner coverage masks reused across cards and frames.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) corner_mask_cache: CornerMaskCache,
    /// Physical union bounds of the foreground portal commands painted on the previous cached frame.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) prev_portal_bounds: Option<Rect>,
    /// Full-viewport translucent scrim color active on the previous cached portal frame, if any.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) prev_portal_scrim: Option<Color>,
    /// Physical union bounds of all prepped commands emitted during the latest `prepare_frame_range`.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) prepped_bounds: Option<Rect>,
    /// Physical union bounds of `prepped_scratch[1..]` emitted during the latest `prepare_frame_range`.
    #[get(pub(crate), type(copy))]
    #[set(pub(crate))]
    pub(crate) prepped_fg_bounds: Option<Rect>,
    /// Reusable clip-scope stack `(clip_y0, clip_y1, optional_sentinel_idx)` for O(1) off-band subtree skipping.
    #[get(pub(crate))]
    #[get_mut(pub(crate))]
    #[set(pub(crate))]
    pub(crate) clip_scope_scratch: Vec<(u32, u32, Option<usize>)>,
    /// Cached full-viewport translucent scrim color matching `cached_scrim_luts`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cached_scrim_color: Option<Color>,
    /// Cached 256-entry per-channel linear-light scrim LUT reused across frames with identical scrim color.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) cached_scrim_luts: Option<Box<[[u8; 256]; 4]>>,
    /// Cumulative number of rasterization passes executed serially on the calling thread.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) serial_dispatches: u64,
    /// Cumulative number of rasterization passes dispatched across `BandWorkerPool`.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) parallel_dispatches: u64,
    /// Cumulative number of fully occluded draw commands culled without reordering translucent layers.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) culled_occluded_commands: u64,
    /// Current adaptive pixel-area threshold separating serial execution from multi-threaded band dispatch.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) adaptive_parallel_threshold_pixels: usize,
    /// Optional explicit pixel-area override for parallel band dispatch (`0` selects adaptive auto-tuning).
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) adaptive_threshold_override: usize,
    /// Most recently observed serial band rasterization duration in microseconds.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) last_serial_us: u64,
    /// Most recently observed parallel band rasterization duration in microseconds.
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) last_parallel_us: u64,
    /// Total frames rendered by this `SoftwareRenderer` (Frame 1 runs serially before async worker pool warm-up).
    #[get(type(copy))]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) rendered_frames: u64,
    /// Gates `Instant::now()` microsecond timing instrumentation inside `execute_prepared_bands` (`false` by default).
    #[get(type(copy))]
    pub(crate) telemetry_enabled: bool,
    /// Tracks whether active animation or scrolling keeps `BandWorkerPool` adaptive hybrid spin enabled (`false` = `0` spin).
    #[get(type(copy))]
    #[set(skip)]
    pub(crate) high_frequency_active: bool,
    /// Cached per-tile (`128x16`) FNV-1a framebuffer hashes for O(dirty_tiles) bit-exact `incremental_framebuffer_hash`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) hash_tiles: Vec<u64>,
    /// Bitset marking `128x16` framebuffer tiles dirtied since the last `incremental_framebuffer_hash` computation.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) hash_dirty_bits: Vec<u64>,
    /// Framebuffer width in pixels matching `hash_tiles`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) hash_tiles_w: u32,
    /// Framebuffer height in pixels matching `hash_tiles`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) hash_tiles_h: u32,
    /// True once `hash_tiles` holds valid hashes for `(hash_tiles_w, hash_tiles_h)`.
    #[get(skip)]
    #[get_mut(skip)]
    #[set(skip)]
    pub(crate) hash_tiles_valid: bool,
}

/// Compact 16-byte hot per-column cache entry reused across every vertical shadow strip scanline.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ShadowStripHot {
    /// Precomputed horizontal IGN phase term `(x as f32) * 0.067_110_56`.
    pub(crate) ign_x: f32,
    /// Last observed destination RGBA8 bytes packed as native-endian `u32`.
    pub(crate) cached_dst: u32,
    /// Cached quantized sRGB Q4 red output prior to IGN dither addition.
    pub(crate) q4_r: i16,
    /// Cached quantized sRGB Q4 green output prior to IGN dither addition.
    pub(crate) q4_g: i16,
    /// Cached quantized sRGB Q4 blue output prior to IGN dither addition.
    pub(crate) q4_b: i16,
    /// Cached composited output alpha byte.
    pub(crate) out_a: u8,
    /// Column blend state (`0` = inactive, `1` = uncached blend, `2` = cached blend, `3` = opaque).
    pub(crate) state: u8,
}

/// Precomputed linear-light blend factors for a single shadow column or mirrored corner sample.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ShadowStripParams {
    /// Premultiplied linear red channel `SRGB_TO_LIN_LUT[r] * alpha`.
    pub(crate) sr_a: f32,
    /// Premultiplied linear green channel `SRGB_TO_LIN_LUT[g] * alpha`.
    pub(crate) sg_a: f32,
    /// Premultiplied linear blue channel `SRGB_TO_LIN_LUT[b] * alpha`.
    pub(crate) sb_a: f32,
    /// Complement opacity `1.0 - alpha`.
    pub(crate) inv_a: f32,
    /// Quantized source alpha `(alpha * 255.0) as u32`.
    pub(crate) sa_u32: u32,
    /// Complement integer alpha `255 - sa_u32`.
    pub(crate) inv_a_u32: u32,
}

/// Single-pixel destination cache shared across 2x/4x symmetrically mirrored shadow corner writes.
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ShadowPixelCache {
    /// Last observed destination RGBA8 bytes packed as native-endian `u32`.
    pub(crate) dst_u32: u32,
    /// Cached quantized sRGB Q4 red output prior to IGN dither addition.
    pub(crate) q4_r: i32,
    /// Cached quantized sRGB Q4 green output prior to IGN dither addition.
    pub(crate) q4_g: i32,
    /// Cached quantized sRGB Q4 blue output prior to IGN dither addition.
    pub(crate) q4_b: i32,
    /// Cached composited output alpha byte.
    pub(crate) out_a: u8,
    /// Whether `dst_u32` and `q4_*` have been populated for the current corner sample.
    pub(crate) valid: bool,
}

/// Per-thread reusable 1D horizontal shadow falloff strip buffers eliminating per-shadow allocations.
#[derive(Debug, Default)]
pub(crate) struct BandShadowScratch {
    /// Hot per-column cache entries for the left vertical shadow strip.
    pub(crate) left_hot: Vec<ShadowStripHot>,
    /// Cold linear blend parameters for the left vertical shadow strip.
    pub(crate) left_params: Vec<ShadowStripParams>,
    /// Hot per-column cache entries for the right vertical shadow strip.
    pub(crate) right_hot: Vec<ShadowStripHot>,
    /// Cold linear blend parameters for the right vertical shadow strip.
    pub(crate) right_params: Vec<ShadowStripParams>,
}

/// Precomputed geometry and hoisted linear tint constants shared across rows of one `raster_shadow` invocation.
#[derive(Clone, Copy, Debug)]
pub(crate) struct ShadowRenderCtx {
    /// Shadow tint RGBA color passed to `blend_shadow_span_const_alpha`.
    pub(crate) color: Color,
    /// Shadow tint sRGB RGB bytes `[r, g, b]`.
    pub(crate) color_rgb: [u8; 3],
    /// Hoisted linear-light shadow tint `[sr, sg, sb]`.
    pub(crate) lin_rgb: [f32; 3],
    /// Caster horizontal center X in physical pixels.
    pub(crate) cx: f32,
    /// Caster vertical center Y in physical pixels.
    pub(crate) cy: f32,
    /// Caster half-width in physical pixels.
    pub(crate) half_w: f32,
    /// Caster half-height in physical pixels.
    pub(crate) half_h: f32,
    /// Normalized shadow tint alpha in `[0.0, 1.0]`.
    pub(crate) base_alpha: f32,
    /// Inverse Gaussian standard deviation `1.0 / sigma.max(0.5)`.
    pub(crate) inv_sigma: f32,
    /// Gaussian cutoff radius `3.0 * sigma`.
    pub(crate) cutoff: f32,
    /// Clamped uniform corner radius in physical pixels.
    pub(crate) uniform_r: f32,
    /// Conservative squared distance threshold `(cutoff + uniform_r + 1e-3)^2` for sqrt-free corner early reject.
    pub(crate) cutoff_r_safe_sq: f32,
    /// Clamped inclusive visible left X bound.
    pub(crate) x0: u32,
    /// Clamped exclusive visible right X bound.
    pub(crate) x1: u32,
    /// Exclusive end X of the left corner region (`sx0` when `has_mid_x`, else `split_x`).
    pub(crate) lx1: u32,
    /// Inclusive start X of the right corner region (`sx1` when `has_mid_x`, else `split_x`).
    pub(crate) rx0: u32,
    /// Horizontal mirror sum `(2 * cx).round() - 1` when `cx` is half-integer aligned.
    pub(crate) mirror_x_sum: i32,
    /// True when the shadow has a middle constant-alpha horizontal span (`sx0 < sx1`).
    pub(crate) has_mid_x: bool,
}