euv-core 0.51.0

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
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
use super::*;

/// Default persistent incremental R8 GPU glyph atlas initialized at `1024x512`.
impl Default for IncrementalGpuGlyphAtlas {
    /// Creates an empty persistent R8 GPU glyph atlas with zero eagerly packed glyphs.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized incremental GPU glyph atlas.
    fn default() -> Self {
        let width: u32 = GPU_GLYPH_ATLAS_INITIAL_WIDTH;
        let height: u32 = GPU_GLYPH_ATLAS_INITIAL_HEIGHT;
        Self {
            width,
            height,
            pixels: vec![0u8; (width as usize).saturating_mul(height as usize)],
            cursor_x: GPU_GLYPH_ATLAS_PAD_PX,
            cursor_y: GPU_GLYPH_ATLAS_PAD_PX,
            shelf_height: 0,
            placements: HashMap::new(),
            pending_dirty_rects: Vec::new(),
            submission_dirty_rects: Vec::new(),
            synced_revision: 0,
            synced_entry_count: 0,
            needs_full_upload: false,
            submission_needs_full_upload: true,
            total_uploaded_bytes: 0,
        }
    }
}

/// Incremental glyph shelf packing, UV lookup, and GPU sub-rectangle upload for `IncrementalGpuGlyphAtlas`.
impl IncrementalGpuGlyphAtlas {
    /// Looks up the cached GPU UV placement for `key` if already packed.
    ///
    /// # Arguments
    ///
    /// - `GlyphKey` - Rasterized glyph lookup key.
    ///
    /// # Returns
    ///
    /// - `Option<GpuGlyphPlacement>` - Placement coordinates and normalized UV rect when present.
    #[must_use]
    pub fn placement(&self, key: GlyphKey) -> Option<GpuGlyphPlacement> {
        self.get_placements().get(&key).copied()
    }

    /// Packs a single rasterized glyph into the persistent R8 shelf and queues its dirty sub-rect for GPU upload.
    ///
    /// # Arguments
    ///
    /// - `GlyphKey` - Unique glyph cache key.
    /// - `&RasterizedGlyph` - Rasterized alpha coverage bitmap.
    ///
    /// # Returns
    ///
    /// - `GpuGlyphPlacement` - Resolved atlas placement and normalized UV rectangle.
    pub fn insert_or_get(&mut self, key: GlyphKey, glyph: &RasterizedGlyph) -> GpuGlyphPlacement {
        if let Some(existing) = self.get_placements().get(&key).copied() {
            return existing;
        }
        let glyph_w: u32 = glyph.get_width();
        let glyph_h: u32 = glyph.get_height();
        if glyph_w == 0 || glyph_h == 0 {
            let empty: GpuGlyphPlacement = GpuGlyphPlacement::new(0, 0, 0, 0, [0, 0, 0, 0]);
            let _: Option<GpuGlyphPlacement> = self.get_mut_placements().insert(key, empty);
            return empty;
        }
        if self
            .get_cursor_x()
            .saturating_add(glyph_w)
            .saturating_add(GPU_GLYPH_ATLAS_PAD_PX)
            > self.get_width()
        {
            self.set_cursor_x(GPU_GLYPH_ATLAS_PAD_PX);
            let next_y: u32 = self
                .get_cursor_y()
                .saturating_add(self.get_shelf_height())
                .saturating_add(GPU_GLYPH_ATLAS_PAD_PX);
            self.set_cursor_y(next_y);
            self.set_shelf_height(0);
        }
        if self
            .get_cursor_y()
            .saturating_add(glyph_h)
            .saturating_add(GPU_GLYPH_ATLAS_PAD_PX)
            > self.get_height()
        {
            let next_h: u32 = (self.get_height().saturating_mul(2)).min(GPU_GLYPH_ATLAS_MAX_DIM);
            if next_h > self.get_height() {
                self.grow_height(next_h);
            } else {
                self.reset_shelves();
            }
        }
        let dst_x: u32 = self.get_cursor_x();
        let dst_y: u32 = self.get_cursor_y();
        let atlas_w: u32 = self.get_width();
        let atlas_h: u32 = self.get_height();
        let coverage: &[u8] = glyph.get_coverage().as_slice();
        let pixel_count: usize = (glyph_w as usize).saturating_mul(glyph_h as usize);
        let is_color: bool = pixel_count > 0 && coverage.len() >= pixel_count.saturating_mul(4);
        {
            let pixels: &mut Vec<u8> = self.get_mut_pixels();
            for row_idx in 0..glyph_h {
                let dst_row: usize = ((dst_y + row_idx) as usize).saturating_mul(atlas_w as usize);
                for col_idx in 0..glyph_w {
                    let cov: u8 = if is_color {
                        let src_idx: usize =
                            ((row_idx as usize) * (glyph_w as usize) + (col_idx as usize)) * 4 + 3;
                        coverage.get(src_idx).copied().unwrap_or(0)
                    } else {
                        let src_idx: usize =
                            (row_idx as usize) * (glyph_w as usize) + (col_idx as usize);
                        coverage.get(src_idx).copied().unwrap_or(0)
                    };
                    let dst_idx: usize = dst_row + ((dst_x + col_idx) as usize);
                    if let Some(slot) = pixels.get_mut(dst_idx) {
                        *slot = cov;
                    }
                }
            }
        }
        let uv_rect: [u16; 4] =
            encode_glyph_atlas_uv(dst_x, dst_y, glyph_w, glyph_h, atlas_w, atlas_h);
        let placement: GpuGlyphPlacement =
            GpuGlyphPlacement::new(dst_x, dst_y, glyph_w, glyph_h, uv_rect);
        let _: Option<GpuGlyphPlacement> = self.get_mut_placements().insert(key, placement);
        self.set_cursor_x(
            dst_x
                .saturating_add(glyph_w)
                .saturating_add(GPU_GLYPH_ATLAS_PAD_PX),
        );
        self.set_shelf_height(self.get_shelf_height().max(glyph_h));
        let dirty: PixelDirtyRect = PixelDirtyRect::new(dst_x, dst_y, glyph_w, glyph_h);
        self.get_mut_pending_dirty_rects().push(dirty);
        self.get_mut_submission_dirty_rects().push(dirty);
        placement
    }

    /// Synchronizes all newly rasterized entries from `atlas` into this persistent incremental GPU atlas.
    ///
    /// # Arguments
    ///
    /// - `&GlyphAtlas` - Source CPU glyph cache.
    ///
    /// # Returns
    ///
    /// - `usize` - Number of newly packed glyphs added during this sync.
    pub fn sync_from_glyph_atlas(&mut self, atlas: &GlyphAtlas) -> usize {
        let rev: u64 = atlas.get_revision();
        let entry_count: usize = atlas.len();
        if rev == self.get_synced_revision() && entry_count == self.get_synced_entry_count() {
            return 0;
        }
        if entry_count < self.get_synced_entry_count() {
            self.reset_shelves();
        }
        let mut added: usize = 0;
        for (key, glyph) in atlas.get_entries().iter() {
            if !self.get_placements().contains_key(key) {
                let _: GpuGlyphPlacement = self.insert_or_get(*key, glyph);
                added += 1;
            }
        }
        self.set_synced_revision(rev);
        self.set_synced_entry_count(entry_count);
        added
    }

    /// Drains all queued dirty glyph sub-rectangles pending GPU texture upload.
    ///
    /// # Returns
    ///
    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles accumulated since the last flush.
    pub fn take_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
        if self.get_needs_full_upload() {
            self.set_needs_full_upload(false);
            self.get_mut_pending_dirty_rects().clear();
            return vec![PixelDirtyRect::new(
                0,
                0,
                self.get_width(),
                self.get_height(),
            )];
        }
        take(self.get_mut_pending_dirty_rects())
    }

    /// Drains queued dirty glyph sub-rectangles strictly for direct-GPU platform swapchain submissions, unaffected by driver-local flushes.
    ///
    /// # Returns
    ///
    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles (or full atlas rect on initial/resized sync) pending swapchain upload.
    pub fn take_submission_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
        if self.get_submission_needs_full_upload() {
            if self.get_placements().is_empty() {
                return Vec::new();
            }
            self.set_submission_needs_full_upload(false);
            self.get_mut_submission_dirty_rects().clear();
            return vec![PixelDirtyRect::new(
                0,
                0,
                self.get_width(),
                self.get_height(),
            )];
        }
        take(self.get_mut_submission_dirty_rects())
    }

    /// Uploads all pending dirty R8 sub-rectangles into `driver`'s resident GPU glyph texture slot 0.
    ///
    /// # Arguments
    ///
    /// - `&mut NativeGpuDriver` - Target hardware GPU driver.
    ///
    /// # Returns
    ///
    /// - `usize` - Total R8 texel bytes uploaded to the GPU texture during this flush.
    pub fn flush_to_driver(&mut self, driver: &mut NativeGpuDriver) -> usize {
        let dirty_rects: Vec<PixelDirtyRect> = self.take_dirty_rects();
        if dirty_rects.is_empty() {
            return 0;
        }
        let atlas_w: u32 = self.get_width();
        let atlas_h: u32 = self.get_height();
        let row_stride: usize = atlas_w as usize;
        let mut uploaded_bytes: usize = 0;
        let pixels_slice: &[u8] = self.get_pixels().as_slice();
        for rect in dirty_rects.iter() {
            let Some(clamped) = rect.clamp_to(atlas_w, atlas_h) else {
                continue;
            };
            let start_offset: usize = (clamped.get_y() as usize)
                .saturating_mul(row_stride)
                .saturating_add(clamped.get_x() as usize);
            if start_offset >= pixels_slice.len() {
                continue;
            }
            let _: bool = driver.upload_texture_dirty_rect(
                GpuAtlasPixelFormat::R8Unorm,
                0,
                (atlas_w, atlas_h),
                (
                    clamped.get_x(),
                    clamped.get_y(),
                    clamped.get_width(),
                    clamped.get_height(),
                ),
                &pixels_slice[start_offset..],
                row_stride,
            );
            uploaded_bytes = uploaded_bytes.saturating_add(clamped.area_pixels());
        }
        self.set_total_uploaded_bytes(
            self.get_total_uploaded_bytes()
                .saturating_add(uploaded_bytes as u64),
        );
        uploaded_bytes
    }

    /// Grows backing atlas height while preserving existing pixel rows and re-normalizing cached UVs.
    ///
    /// # Arguments
    ///
    /// - `u32` - New atlas height in texels.
    fn grow_height(&mut self, next_height: u32) {
        let atlas_w: u32 = self.get_width();
        let next_len: usize = (atlas_w as usize).saturating_mul(next_height as usize);
        self.get_mut_pixels().resize(next_len, 0);
        self.set_height(next_height);
        self.set_needs_full_upload(true);
        self.set_submission_needs_full_upload(true);
        for placement in self.get_mut_placements().values_mut() {
            let uv: [u16; 4] = encode_glyph_atlas_uv(
                placement.get_x(),
                placement.get_y(),
                placement.get_width(),
                placement.get_height(),
                atlas_w,
                next_height,
            );
            placement.set_uv_rect(uv);
        }
    }

    /// Clears all shelf placements and pixels, marking the atlas for a clean full upload.
    fn reset_shelves(&mut self) {
        self.get_mut_placements().clear();
        self.get_mut_pixels().fill(0);
        self.set_cursor_x(GPU_GLYPH_ATLAS_PAD_PX);
        self.set_cursor_y(GPU_GLYPH_ATLAS_PAD_PX);
        self.set_shelf_height(0);
        self.get_mut_pending_dirty_rects().clear();
        self.get_mut_submission_dirty_rects().clear();
        self.set_needs_full_upload(true);
        self.set_submission_needs_full_upload(true);
    }
}

/// Default persistent incremental RGBA8 GPU image atlas initialized at `1024x512`.
impl Default for IncrementalGpuImageAtlas {
    /// Creates an empty persistent RGBA8 GPU image atlas ready for shelf packing.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized incremental GPU image atlas.
    fn default() -> Self {
        let width: u32 = GPU_IMAGE_ATLAS_INITIAL_WIDTH;
        let height: u32 = GPU_IMAGE_ATLAS_INITIAL_HEIGHT;
        let byte_len: usize = (width as usize)
            .saturating_mul(height as usize)
            .saturating_mul(4);
        Self {
            width,
            height,
            pixels: vec![0u8; byte_len],
            cursor_x: GPU_IMAGE_ATLAS_PAD_PX,
            cursor_y: GPU_IMAGE_ATLAS_PAD_PX,
            shelf_height: 0,
            placements: HashMap::new(),
            submission_dirty_rects: Vec::new(),
            submission_needs_full_upload: true,
            revision: 0,
        }
    }
}

/// Incremental shelf packing, edge-clamped gutter blitting, and dirty-rect upload tracking for `IncrementalGpuImageAtlas`.
impl IncrementalGpuImageAtlas {
    /// Recycles atlas shelves at frame start when dynamic occupancy approaches capacity so mid-frame UV invalidations never occur.
    pub fn begin_frame(&mut self) {
        let height_limit: u32 = (self.get_height().saturating_mul(3)) / 4;
        if self.get_cursor_y() >= height_limit
            && self.get_height() >= GPU_IMAGE_ATLAS_MAX_DIM
            && self.get_placements().len() > 8
        {
            self.reset_shelves();
        }
    }

    /// Packs an RGBA8 image into the persistent shelf atlas (or reuses its cached placement by content hash) with a `1px` edge-clamped gutter.
    ///
    /// # Arguments
    ///
    /// - `u32` - Source image width in pixels.
    /// - `u32` - Source image height in pixels.
    /// - `&[u8]` - Tightly packed RGBA8 pixel slice (`width * height * 4`).
    ///
    /// # Returns
    ///
    /// - `Option<GpuImagePlacement>` - Resolved atlas placement and normalized UV rectangle, or `None` for empty buffers.
    pub fn insert_or_get(
        &mut self,
        src_w: u32,
        src_h: u32,
        rgba_pixels: &[u8],
    ) -> Option<GpuImagePlacement> {
        let required: usize = (src_w as usize)
            .saturating_mul(src_h as usize)
            .saturating_mul(4);
        if src_w == 0 || src_h == 0 || rgba_pixels.len() < required {
            return None;
        }
        let key: u64 = hash_rgba8_image_content(src_w, src_h, &rgba_pixels[..required]);
        if let Some(existing) = self.get_placements().get(&key).copied() {
            return Some(existing);
        }
        let pad: u32 = GPU_IMAGE_ATLAS_PAD_PX;
        let max_slot_dim: u32 = GPU_IMAGE_ATLAS_MAX_DIM.saturating_sub(pad.saturating_mul(2));
        let (pack_w, pack_h): (u32, u32) = if src_w <= max_slot_dim && src_h <= max_slot_dim {
            (src_w, src_h)
        } else {
            let scale_x: f32 = (max_slot_dim as f32) / (src_w as f32);
            let scale_y: f32 = (max_slot_dim as f32) / (src_h as f32);
            let fit: f32 = scale_x.min(scale_y);
            (
                ((src_w as f32) * fit).floor().max(1.0) as u32,
                ((src_h as f32) * fit).floor().max(1.0) as u32,
            )
        };
        let need_w: u32 = pack_w.saturating_add(pad.saturating_mul(2));
        if need_w > self.get_width() {
            let next_w: u32 = need_w.next_power_of_two().min(GPU_IMAGE_ATLAS_MAX_DIM);
            self.grow_dimensions(next_w, self.get_height());
        }
        if self
            .get_cursor_x()
            .saturating_add(pack_w)
            .saturating_add(pad)
            > self.get_width()
        {
            self.set_cursor_x(pad);
            let next_y: u32 = self
                .get_cursor_y()
                .saturating_add(self.get_shelf_height())
                .saturating_add(pad.saturating_mul(2));
            self.set_cursor_y(next_y);
            self.set_shelf_height(0);
        }
        if self
            .get_cursor_y()
            .saturating_add(pack_h)
            .saturating_add(pad)
            > self.get_height()
        {
            let target_h: u32 = self
                .get_cursor_y()
                .saturating_add(pack_h)
                .saturating_add(pad.saturating_mul(2))
                .next_power_of_two()
                .min(GPU_IMAGE_ATLAS_MAX_DIM);
            if target_h > self.get_height() {
                self.grow_dimensions(self.get_width(), target_h);
            } else {
                self.reset_shelves();
                if pack_h.saturating_add(pad.saturating_mul(2)) > self.get_height() {
                    let exact_h: u32 = pack_h
                        .saturating_add(pad.saturating_mul(2))
                        .next_power_of_two()
                        .min(GPU_IMAGE_ATLAS_MAX_DIM);
                    self.grow_dimensions(self.get_width(), exact_h);
                }
            }
        }
        let dst_x: u32 = self.get_cursor_x();
        let dst_y: u32 = self.get_cursor_y();
        let atlas_w: u32 = self.get_width();
        let atlas_h: u32 = self.get_height();
        {
            let pixels: &mut Vec<u8> = self.get_mut_pixels();
            let atlas_stride: usize = (atlas_w as usize).saturating_mul(4);
            let src_stride: usize = (src_w as usize).saturating_mul(4);
            if pack_w == src_w && pack_h == src_h {
                for row_idx in 0..pack_h {
                    let src_off: usize = (row_idx as usize).saturating_mul(src_stride);
                    let dst_off: usize = ((dst_y + row_idx) as usize)
                        .saturating_mul(atlas_stride)
                        .saturating_add((dst_x as usize).saturating_mul(4));
                    let row_bytes: usize = (pack_w as usize).saturating_mul(4);
                    if src_off + row_bytes <= rgba_pixels.len()
                        && dst_off + row_bytes <= pixels.len()
                    {
                        pixels[dst_off..(dst_off + row_bytes)]
                            .copy_from_slice(&rgba_pixels[src_off..(src_off + row_bytes)]);
                    }
                }
            } else {
                for row_idx in 0..pack_h {
                    let sy: u32 = (((row_idx as u64) * u64::from(src_h)) / u64::from(pack_h))
                        .min(u64::from(src_h.saturating_sub(1)))
                        as u32;
                    let dst_row_off: usize =
                        ((dst_y + row_idx) as usize).saturating_mul(atlas_stride);
                    let src_row_off: usize = (sy as usize).saturating_mul(src_stride);
                    for col_idx in 0..pack_w {
                        let sx: u32 = (((col_idx as u64) * u64::from(src_w)) / u64::from(pack_w))
                            .min(u64::from(src_w.saturating_sub(1)))
                            as u32;
                        let s_off: usize = src_row_off + (sx as usize) * 4;
                        let d_off: usize = dst_row_off + ((dst_x + col_idx) as usize) * 4;
                        if s_off + 4 <= rgba_pixels.len() && d_off + 4 <= pixels.len() {
                            pixels[d_off..(d_off + 4)]
                                .copy_from_slice(&rgba_pixels[s_off..(s_off + 4)]);
                        }
                    }
                }
            }
            let left_gutter: bool = dst_x > 0;
            let right_gutter: bool = dst_x.saturating_add(pack_w) < atlas_w;
            for row_idx in 0..pack_h {
                let row_base: usize = ((dst_y + row_idx) as usize).saturating_mul(atlas_stride);
                if left_gutter {
                    let src_px: usize = row_base + (dst_x as usize) * 4;
                    let dst_px: usize = row_base + ((dst_x - 1) as usize) * 4;
                    if src_px + 4 <= pixels.len() {
                        let edge: [u8; 4] = [
                            pixels[src_px],
                            pixels[src_px + 1],
                            pixels[src_px + 2],
                            pixels[src_px + 3],
                        ];
                        pixels[dst_px..(dst_px + 4)].copy_from_slice(&edge);
                    }
                }
                if right_gutter {
                    let src_px: usize = row_base + ((dst_x + pack_w - 1) as usize) * 4;
                    let dst_px: usize = row_base + ((dst_x + pack_w) as usize) * 4;
                    if dst_px + 4 <= pixels.len() {
                        let edge: [u8; 4] = [
                            pixels[src_px],
                            pixels[src_px + 1],
                            pixels[src_px + 2],
                            pixels[src_px + 3],
                        ];
                        pixels[dst_px..(dst_px + 4)].copy_from_slice(&edge);
                    }
                }
            }
            let copy_x0: u32 = dst_x.saturating_sub(1);
            let copy_x1: u32 = dst_x.saturating_add(pack_w).saturating_add(1).min(atlas_w);
            let span_bytes: usize = ((copy_x1.saturating_sub(copy_x0)) as usize).saturating_mul(4);
            if dst_y > 0 && span_bytes > 0 {
                let src_row: usize =
                    (dst_y as usize).saturating_mul(atlas_stride) + (copy_x0 as usize) * 4;
                let dst_row: usize =
                    ((dst_y - 1) as usize).saturating_mul(atlas_stride) + (copy_x0 as usize) * 4;
                if src_row + span_bytes <= pixels.len() {
                    pixels.copy_within(src_row..(src_row + span_bytes), dst_row);
                }
            }
            if dst_y.saturating_add(pack_h) < atlas_h && span_bytes > 0 {
                let src_row: usize = ((dst_y + pack_h - 1) as usize).saturating_mul(atlas_stride)
                    + (copy_x0 as usize) * 4;
                let dst_row: usize = ((dst_y + pack_h) as usize).saturating_mul(atlas_stride)
                    + (copy_x0 as usize) * 4;
                if dst_row + span_bytes <= pixels.len() {
                    pixels.copy_within(src_row..(src_row + span_bytes), dst_row);
                }
            }
        }
        let uv_rect: [u16; 4] =
            encode_glyph_atlas_uv(dst_x, dst_y, pack_w, pack_h, atlas_w, atlas_h);
        let placement: GpuImagePlacement =
            GpuImagePlacement::new(dst_x, dst_y, pack_w, pack_h, uv_rect);
        let _: Option<GpuImagePlacement> = self.get_mut_placements().insert(key, placement);
        self.set_cursor_x(
            dst_x
                .saturating_add(pack_w)
                .saturating_add(pad.saturating_mul(2)),
        );
        self.set_shelf_height(self.get_shelf_height().max(pack_h));
        let dirty_x: u32 = dst_x.saturating_sub(1);
        let dirty_y: u32 = dst_y.saturating_sub(1);
        let dirty_w: u32 = dst_x
            .saturating_add(pack_w)
            .saturating_add(1)
            .min(atlas_w)
            .saturating_sub(dirty_x);
        let dirty_h: u32 = dst_y
            .saturating_add(pack_h)
            .saturating_add(1)
            .min(atlas_h)
            .saturating_sub(dirty_y);
        self.get_mut_submission_dirty_rects()
            .push(PixelDirtyRect::new(dirty_x, dirty_y, dirty_w, dirty_h));
        self.set_revision(self.get_revision().wrapping_add(1));
        Some(placement)
    }

    /// Computes normalized sub-rectangle UV coordinates inside `placement` for a cropped `SpriteRegion`.
    ///
    /// # Arguments
    ///
    /// - `GpuImagePlacement` - Packed sheet placement inside this atlas.
    /// - `u32` - Original sprite sheet width in pixels.
    /// - `u32` - Original sprite sheet height in pixels.
    /// - `Rect` - Cropped source sub-rectangle in sprite-sheet pixels.
    ///
    /// # Returns
    ///
    /// - `[u16; 4]` - Quantized normalized UV rectangle `[u0, v0, u1, v1]` in `[0..=65535]`.
    #[must_use]
    pub fn sub_uv_rect(
        &self,
        placement: GpuImagePlacement,
        sheet_w: u32,
        sheet_h: u32,
        src_rect: Rect,
    ) -> [u16; 4] {
        let sx_scale: f32 = (placement.get_width() as f32) / (sheet_w.max(1) as f32);
        let sy_scale: f32 = (placement.get_height() as f32) / (sheet_h.max(1) as f32);
        let rx: f32 = (placement.get_x() as f32) + src_rect.get_x().max(0.0) * sx_scale;
        let ry: f32 = (placement.get_y() as f32) + src_rect.get_y().max(0.0) * sy_scale;
        let rw: f32 = (src_rect.get_width().max(1.0) * sx_scale).min(placement.get_width() as f32);
        let rh: f32 =
            (src_rect.get_height().max(1.0) * sy_scale).min(placement.get_height() as f32);
        let inv_w: f32 = 1.0 / (self.get_width().max(1) as f32);
        let inv_h: f32 = 1.0 / (self.get_height().max(1) as f32);
        [
            (rx * inv_w * 65535.0).round().clamp(0.0, 65535.0) as u16,
            (ry * inv_h * 65535.0).round().clamp(0.0, 65535.0) as u16,
            ((rx + rw) * inv_w * 65535.0).round().clamp(0.0, 65535.0) as u16,
            ((ry + rh) * inv_h * 65535.0).round().clamp(0.0, 65535.0) as u16,
        ]
    }

    /// Drains queued dirty RGBA8 sub-rectangles strictly for direct-GPU platform swapchain submissions.
    ///
    /// # Returns
    ///
    /// - `Vec<PixelDirtyRect>` - Dirty sub-rectangles (or full atlas rect on initial/resized sync) pending swapchain upload.
    pub fn take_submission_dirty_rects(&mut self) -> Vec<PixelDirtyRect> {
        if self.get_submission_needs_full_upload() {
            if self.get_placements().is_empty() {
                return Vec::new();
            }
            self.set_submission_needs_full_upload(false);
            self.get_mut_submission_dirty_rects().clear();
            return vec![PixelDirtyRect::new(
                0,
                0,
                self.get_width(),
                self.get_height(),
            )];
        }
        take(self.get_mut_submission_dirty_rects())
    }

    /// Grows backing RGBA8 atlas dimensions while preserving existing rows and re-normalizing cached UVs.
    ///
    /// # Arguments
    ///
    /// - `u32` - New atlas width in texels.
    /// - `u32` - New atlas height in texels.
    fn grow_dimensions(&mut self, next_width: u32, next_height: u32) {
        let old_w: u32 = self.get_width();
        let old_h: u32 = self.get_height();
        let next_len: usize = (next_width as usize)
            .saturating_mul(next_height as usize)
            .saturating_mul(4);
        let mut next_pixels: Vec<u8> = vec![0u8; next_len];
        let old_stride: usize = (old_w as usize).saturating_mul(4);
        let new_stride: usize = (next_width as usize).saturating_mul(4);
        let copy_rows: u32 = old_h.min(next_height);
        let copy_bytes: usize = old_stride.min(new_stride);
        {
            let old_pixels: &[u8] = self.get_pixels().as_slice();
            for row_idx in 0..copy_rows {
                let s_off: usize = (row_idx as usize).saturating_mul(old_stride);
                let d_off: usize = (row_idx as usize).saturating_mul(new_stride);
                if s_off + copy_bytes <= old_pixels.len() && d_off + copy_bytes <= next_pixels.len()
                {
                    next_pixels[d_off..(d_off + copy_bytes)]
                        .copy_from_slice(&old_pixels[s_off..(s_off + copy_bytes)]);
                }
            }
        }
        self.set_width(next_width);
        self.set_height(next_height);
        self.set_pixels(next_pixels);
        self.set_submission_needs_full_upload(true);
        for placement in self.get_mut_placements().values_mut() {
            let uv: [u16; 4] = encode_glyph_atlas_uv(
                placement.get_x(),
                placement.get_y(),
                placement.get_width(),
                placement.get_height(),
                next_width,
                next_height,
            );
            placement.set_uv_rect(uv);
        }
    }

    /// Clears all packed image placements and pixels, scheduling a clean full RGBA8 upload.
    fn reset_shelves(&mut self) {
        self.get_mut_placements().clear();
        self.get_mut_pixels().fill(0);
        self.set_cursor_x(GPU_IMAGE_ATLAS_PAD_PX);
        self.set_cursor_y(GPU_IMAGE_ATLAS_PAD_PX);
        self.set_shelf_height(0);
        self.get_mut_submission_dirty_rects().clear();
        self.set_submission_needs_full_upload(true);
        self.set_revision(self.get_revision().wrapping_add(1));
    }
}

/// Default `RenderGraph` configured for `max_frames_in_flight = 2` pipelined CPU/GPU overlap.
impl Default for RenderGraph {
    /// Creates a `RenderGraph` with `2` frames in flight and empty dirty-span and glyph atlas caches.
    ///
    /// # Returns
    ///
    /// - `Self` - Initialized render-graph scheduler.
    fn default() -> Self {
        Self {
            max_frames_in_flight: RENDER_GRAPH_DEFAULT_MAX_IN_FLIGHT,
            dirty_coalescer: DirtySpanCoalescer::default(),
            gpu_glyph_atlas: IncrementalGpuGlyphAtlas::default(),
            last_plan: RenderGraphFramePlan::default(),
            last_receipt: RenderGraphExecutionReceipt::default(),
            executed_frames: 0,
        }
    }
}

/// Construction helpers for `RenderGraphFrameTarget`.
impl RenderGraphFrameTarget {
    /// Creates a frame target descriptor without an external offscreen texture.
    ///
    /// # Arguments
    ///
    /// - `u32` - Physical surface width in pixels.
    /// - `u32` - Physical surface height in pixels.
    /// - `Color` - Surface clear color.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured frame target descriptor.
    #[must_use]
    pub fn new(width: u32, height: u32, clear_color: Color) -> Self {
        Self {
            width,
            height,
            clear_color,
            external_texture_handle: 0,
        }
    }

    /// Attaches an external GPU texture handle for Pass 2 compositing.
    ///
    /// # Arguments
    ///
    /// - `usize` - External GPU texture handle (`0` disables Pass 2).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated frame target descriptor.
    #[must_use]
    pub fn with_external_texture(mut self, external_texture_handle: usize) -> Self {
        self.set_external_texture_handle(external_texture_handle);
        self
    }
}

/// Pass planning, coalesced dirty upload, Dual-Kawase blur orchestration, and submission for `RenderGraph`.
impl RenderGraph {
    /// Builds an explicit pass execution plan for the current frame.
    ///
    /// # Arguments
    ///
    /// - `RenderGraphFrameTarget` - Target surface dimensions and optional external texture handle.
    /// - `RenderGraphPlanCounts` - Active pass counts for Pass 0, Pass 1, and Pass 3.
    ///
    /// # Returns
    ///
    /// - `RenderGraphFramePlan` - Ordered render-graph pass schedule.
    #[must_use]
    pub fn plan_frame(
        &self,
        target: RenderGraphFrameTarget,
        counts: RenderGraphPlanCounts,
    ) -> RenderGraphFramePlan {
        let mut passes: Vec<RenderGraphPassKind> = Vec::with_capacity(5);
        if counts.get_has_compute_layout() {
            passes.push(RenderGraphPassKind::ComputeLayout);
        }
        if counts.get_dirty_span_count() > 0 || counts.get_atlas_dirty_rect_count() > 0 {
            passes.push(RenderGraphPassKind::BlitAndAtlasUpload);
        }
        if target.get_external_texture_handle() != 0 {
            passes.push(RenderGraphPassKind::OffscreenExternalTarget);
        }
        if counts.get_blur_pass_count() > 0 {
            passes.push(RenderGraphPassKind::DualKawaseBackdropBlur);
        }
        passes.push(RenderGraphPassKind::UberUiDirectAndIndirect);
        RenderGraphFramePlan {
            passes,
            width: target.get_width(),
            height: target.get_height(),
            dirty_span_count: counts.get_dirty_span_count(),
            atlas_dirty_rect_count: counts.get_atlas_dirty_rect_count(),
            blur_pass_count: counts
                .get_blur_pass_count()
                .min(RENDER_GRAPH_MAX_BLUR_PASSES),
            external_texture_handle: target.get_external_texture_handle(),
        }
    }

    /// Executes Passes 0..4 against `driver`, updating real GPU timing, dirty-span savings, and completion fences.
    ///
    /// # Arguments
    ///
    /// - `&mut NativeGpuDriver` - Target hardware GPU driver.
    /// - `RenderGraphFrameTarget` - Surface dimensions, clear color, and optional external texture handle.
    /// - `&[GpuBatch]` - Coalesced 64-byte primitive batches for Pass 4.
    /// - `&[GpuBackdropBlurPass]` - Dual-Kawase backdrop blur regions for Pass 3.
    /// - `Option<(&mut GpuComputeLayoutEngine, &GpuComputeSceneInput)>` - Optional Pass 0 GPU compute layout workload.
    ///
    /// # Returns
    ///
    /// - `Result<RenderGraphExecutionReceipt, PlatformError>` - Detailed pass execution and timing receipt.
    pub fn execute_frame(
        &mut self,
        driver: &mut NativeGpuDriver,
        target: RenderGraphFrameTarget,
        batches: &[GpuBatch],
        blur_passes: &[GpuBackdropBlurPass],
        compute_work: Option<(&mut GpuComputeLayoutEngine, &GpuComputeSceneInput)>,
    ) -> Result<RenderGraphExecutionReceipt, PlatformError> {
        let width: u32 = target.get_width();
        let height: u32 = target.get_height();
        let clear_color: Color = target.get_clear_color();
        let external_texture_handle: usize = target.get_external_texture_handle();
        let dirty_spans_count: usize = if batches.len() == 1 {
            self.get_mut_dirty_coalescer()
                .diff_and_coalesce(batches[0].get_primitives().as_slice())
                .len()
        } else {
            let mut flat_prims: Vec<GpuPrimitiveInstance> = Vec::new();
            for batch in batches.iter() {
                flat_prims.extend_from_slice(batch.get_primitives().as_slice());
            }
            self.get_mut_dirty_coalescer()
                .diff_and_coalesce(flat_prims.as_slice())
                .len()
        };
        let dirty_upload_bytes: usize = self.get_dirty_coalescer().get_last_dirty_bytes();
        let full_upload_bytes: usize = self.get_dirty_coalescer().get_last_full_bytes();
        let pending_atlas_rects: usize = self.get_gpu_glyph_atlas().get_pending_dirty_rects().len()
            + usize::from(self.get_gpu_glyph_atlas().get_needs_full_upload());
        let plan_counts: RenderGraphPlanCounts = RenderGraphPlanCounts::new(
            compute_work.is_some(),
            dirty_spans_count,
            pending_atlas_rects,
            blur_passes.len(),
        );
        let plan: RenderGraphFramePlan = self.plan_frame(target, plan_counts);
        let observed_completed: u64 = completed_gpu_fence();
        let mut gpu_compute_ns: u64 = last_gpu_compute_ns();
        let mut draw_calls: usize = 0;
        if let Some((compute_engine, compute_scene)) = compute_work {
            let comp_res: GpuComputeDispatchResult = compute_engine.dispatch(compute_scene, false);
            gpu_compute_ns = comp_res.get_gpu_compute_ns();
            draw_calls = draw_calls.saturating_add(comp_res.get_draw_calls());
        }
        let atlas_upload_bytes: usize = self.get_mut_gpu_glyph_atlas().flush_to_driver(driver);
        if external_texture_handle != 0 {
            driver.set_external_texture(external_texture_handle);
        }
        let blur_executed: usize =
            if !blur_passes.is_empty() && driver.supports_backdrop_blur_pass() {
                driver.execute_dual_kawase_blur_passes(width, height, blur_passes)
            } else {
                0
            };
        let ui_draws: usize = driver.submit_batches(width, height, clear_color, batches)?;
        draw_calls = draw_calls
            .saturating_add(ui_draws)
            .saturating_add(blur_executed.saturating_mul(2));
        let submitted_fence_id: u64 = submitted_gpu_fence().max(driver.get_submitted_frames());
        let gpu_render_ns: u64 = driver.get_last_gpu_exec_ns().max(last_gpu_render_ns());
        let receipt: RenderGraphExecutionReceipt = RenderGraphExecutionReceipt {
            executed_passes: plan.get_passes().clone(),
            submitted_fence_id,
            observed_completed_fence_id: observed_completed,
            dirty_upload_bytes,
            full_upload_bytes,
            atlas_upload_bytes,
            blur_passes_executed: blur_executed,
            draw_calls,
            gpu_compute_ns,
            gpu_render_ns,
        };
        self.set_last_plan(plan);
        self.set_last_receipt(receipt.clone());
        self.set_executed_frames(self.get_executed_frames().wrapping_add(1));
        Ok(receipt)
    }
}